From d308647b4bc1a57e5f22cab641d222a2647ff09e Mon Sep 17 00:00:00 2001 From: Magnus Svensson Date: Thu, 22 Oct 2026 08:47:08 +0200 Subject: [PATCH 1/3] Update deps. --- .devcontainer/devcontainer.json | 2 +- .github/workflows/docker-build-push.yml | 2 +- go.mod | 24 +- go.sum | 36 +- .../bytedance/sonic/loader/mmap_unix.go | 25 +- .../purego/internal/fakecgo/libcgo.go | 6 - .../purego/internal/fakecgo/libcgo_darwin.go | 7 + .../purego/internal/fakecgo/libcgo_freebsd.go | 7 + .../purego/internal/fakecgo/libcgo_linux.go | 7 + .../purego/internal/fakecgo/libcgo_netbsd.go | 7 + .../gabriel-vasile/mimetype/README.md | 3 + .../mimetype/internal/cdf/cdf.go | 171 +++++-- .../mimetype/internal/magic/audio.go | 27 +- .../mimetype/internal/magic/binary.go | 25 +- .../mimetype/internal/magic/image.go | 4 +- .../mimetype/internal/magic/magic.go | 14 +- .../mimetype/internal/magic/ms_office.go | 90 ++-- vendor/github.com/klauspost/cpuid/v2/cpuid.go | 21 +- .../klauspost/cpuid/v2/featureid_string.go | 8 +- .../klauspost/cpuid/v2/riscv_isa.go | 7 +- .../github.com/klauspost/cpuid/v2/topology.go | 480 ++++++++++++++++++ .../klauspost/cpuid/v2/topology/topology.go | 389 ++++++++++++++ .../klauspost/cpuid/v2/topology_scan.go | 34 ++ .../cpuid/v2/topology_scan_linux_amd64.go | 43 ++ .../klauspost/cpuid/v2/topology_scan_stub.go | 11 + .../cpuid/v2/topology_scan_windows_amd64.go | 75 +++ vendor/github.com/quic-go/quic-go/README.md | 2 +- vendor/github.com/quic-go/quic-go/config.go | 15 +- .../quic-go/quic-go/conn_id_manager.go | 2 +- .../github.com/quic-go/quic-go/connection.go | 162 +++--- .../quic-go/quic-go/crypto_stream_manager.go | 7 - .../quic-go/quic-go/datagram_queue.go | 38 +- vendor/github.com/quic-go/quic-go/framer.go | 10 + .../quic-go/quic-go/http3/headers.go | 22 +- .../quic-go/http3/qlog/header_redactor.go | 75 +++ .../quic-go/quic-go/http3/server_conn.go | 4 +- .../quic-go/http3/state_tracking_stream.go | 37 +- .../quic-go/quic-go/http3/stream.go | 16 +- .../github.com/quic-go/quic-go/interface.go | 7 + .../quic-go/internal/ackhandler/interfaces.go | 6 +- .../ackhandler/lost_packet_tracker.go | 12 +- .../ackhandler/packet_number_generator.go | 68 +-- .../ackhandler/received_packet_handler.go | 12 +- .../ackhandler/received_packet_tracker.go | 11 +- .../ackhandler/sent_packet_handler.go | 459 +++++++++++------ .../ackhandler/sent_packet_history.go | 42 +- .../internal/congestion/cubic_sender.go | 102 +++- .../quic-go/internal/congestion/interface.go | 1 + .../quic-go/internal/congestion/pacer.go | 60 +-- .../internal/handshake/updatable_aead.go | 5 +- .../internal/protocol/encryption_level.go | 22 + .../quic-go/internal/protocol/params.go | 38 -- .../quic-go/internal/utils/connstats.go | 2 + .../quic-go/quic-go/internal/utils/rand.go | 28 +- .../quic-go/quic-go/mtu_discoverer.go | 4 +- .../quic-go/quic-go/packet_packer.go | 74 ++- .../quic-go/quic-go/path_manager.go | 63 ++- .../github.com/quic-go/quic-go/qlog/event.go | 79 ++- .../github.com/quic-go/quic-go/qlog/types.go | 8 + .../github.com/quic-go/quic-go/send_stream.go | 13 +- vendor/github.com/quic-go/quic-go/server.go | 20 +- vendor/github.com/quic-go/quic-go/stream.go | 1 + .../shopspring/decimal/.golangci.yml | 11 + .../shopspring/decimal/CHANGELOG.md | 32 ++ .../github.com/shopspring/decimal/README.md | 46 +- vendor/github.com/shopspring/decimal/const.go | 55 -- .../shopspring/decimal/decimal-go.go | 415 --------------- .../github.com/shopspring/decimal/decimal.go | 310 +++++++++-- .../github.com/shopspring/decimal/encoding.go | 197 ++++++- vendor/github.com/shopspring/decimal/math.go | 264 +++++----- .../github.com/shopspring/decimal/rounding.go | 160 ------ .../go-trust/pkg/authzen/types.go | 85 +++- .../go-trust/pkg/registry/clientid.go | 36 +- .../go-trust/pkg/registry/composite.go | 9 +- .../go-trust/pkg/registry/did_vm_policy.go | 60 +++ .../pkg/registry/didweb/didweb_registry.go | 15 +- .../go-trust/pkg/registry/manager.go | 11 + .../go-trust/pkg/registry/policy.go | 49 +- .../pkg/registry/rpcert/semanticid.go | 155 ++++++ .../go-trust/pkg/registry/rpcert/wrpac.go | 50 +- .../go-trust/pkg/registry/strategies.go | 16 +- .../go-trust/pkg/registry/test_helpers.go | 32 ++ .../go-trust/pkg/registry/verifierid.go | 225 ++++++++ .../go-trust/pkg/registry/x5c_enrichment.go | 102 ++++ vendor/modules.txt | 23 +- 85 files changed, 3830 insertions(+), 1580 deletions(-) create mode 100644 vendor/github.com/klauspost/cpuid/v2/topology.go create mode 100644 vendor/github.com/klauspost/cpuid/v2/topology/topology.go create mode 100644 vendor/github.com/klauspost/cpuid/v2/topology_scan.go create mode 100644 vendor/github.com/klauspost/cpuid/v2/topology_scan_linux_amd64.go create mode 100644 vendor/github.com/klauspost/cpuid/v2/topology_scan_stub.go create mode 100644 vendor/github.com/klauspost/cpuid/v2/topology_scan_windows_amd64.go create mode 100644 vendor/github.com/quic-go/quic-go/http3/qlog/header_redactor.go delete mode 100644 vendor/github.com/shopspring/decimal/decimal-go.go delete mode 100644 vendor/github.com/shopspring/decimal/rounding.go create mode 100644 vendor/github.com/sirosfoundation/go-trust/pkg/registry/did_vm_policy.go create mode 100644 vendor/github.com/sirosfoundation/go-trust/pkg/registry/rpcert/semanticid.go create mode 100644 vendor/github.com/sirosfoundation/go-trust/pkg/registry/verifierid.go diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 563967938..2e51414a7 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -5,7 +5,7 @@ "build": { "dockerfile": "Dockerfile", "args": { - "GO_VERSION": "1.27.0" + "GO_VERSION": "1.27.3" } }, "customizations": { diff --git a/.github/workflows/docker-build-push.yml b/.github/workflows/docker-build-push.yml index d38e7c29c..feba16579 100644 --- a/.github/workflows/docker-build-push.yml +++ b/.github/workflows/docker-build-push.yml @@ -277,7 +277,7 @@ jobs: - name: Upload Trivy results to Security tab if: ${{ !cancelled() }} - uses: github/codeql-action/upload-sarif@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4.39.0 + uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1 continue-on-error: true with: sarif_file: trivy-results.sarif diff --git a/go.mod b/go.mod index fc869e2c0..24ef4087c 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/SUNET/vc -go 1.27.2 +go 1.27.3 require ( filippo.io/edwards25519 v1.2.0 @@ -25,6 +25,7 @@ require ( github.com/go-logr/zapr v1.3.0 github.com/go-playground/validator/v10 v10.30.5 github.com/go-sql-driver/mysql v1.10.1 + github.com/goccy/go-yaml v1.19.2 github.com/golang-jwt/jwt/v5 v5.3.1 github.com/golang-migrate/migrate/v4 v4.20.1 github.com/google/uuid v1.6.0 @@ -50,7 +51,7 @@ require ( github.com/russellhaering/goxmldsig v1.6.1 github.com/sirosfoundation/go-cryptoutil v0.7.2 github.com/sirosfoundation/go-spocp v0.1.0 - github.com/sirosfoundation/go-trust v0.24.1 + github.com/sirosfoundation/go-trust v0.26.0 github.com/sirosfoundation/go-ts11client v0.0.0-20260821071625-a8d5997107d0 github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e github.com/stretchr/testify v1.12.1 @@ -74,6 +75,7 @@ require ( go.opentelemetry.io/otel/trace v1.47.0 go.uber.org/zap v1.28.0 golang.org/x/crypto v0.58.0 + golang.org/x/net v0.61.0 golang.org/x/oauth2 v0.37.0 golang.org/x/sync v0.24.0 golang.org/x/time v0.16.0 @@ -92,7 +94,7 @@ require ( github.com/beorn7/perks v1.0.1 // indirect github.com/bytedance/gopkg v0.1.4 // indirect github.com/bytedance/sonic v1.15.4 // indirect - github.com/bytedance/sonic/loader v0.5.2 // indirect + github.com/bytedance/sonic/loader v0.5.3 // indirect github.com/cayleygraph/quad v1.3.0 // indirect github.com/cenkalti/backoff/v4 v4.3.0 // indirect github.com/cenkalti/backoff/v5 v5.0.3 // indirect @@ -109,9 +111,9 @@ require ( github.com/docker/go-connections v0.8.2 // indirect github.com/docker/go-units v0.5.0 // indirect github.com/eapache/go-resiliency v1.7.0 // indirect - github.com/ebitengine/purego v0.11.1 // indirect + github.com/ebitengine/purego v0.11.2 // indirect github.com/felixge/httpsnoop v1.1.0 // indirect - github.com/gabriel-vasile/mimetype v1.4.15 // indirect + github.com/gabriel-vasile/mimetype v1.4.16 // indirect github.com/gin-contrib/sse v1.1.2 // indirect github.com/go-jose/go-jose/v3 v3.0.5 // indirect github.com/go-logr/stdr v1.2.2 // indirect @@ -132,7 +134,6 @@ require ( github.com/gobwas/pool v0.2.1 // indirect github.com/gobwas/ws v1.4.0 // indirect github.com/goccy/go-json v0.11.2 // indirect - github.com/goccy/go-yaml v1.19.2 // indirect github.com/golang-jwt/jwt/v4 v4.5.2 // indirect github.com/google/go-cmp v0.7.0 // indirect github.com/gorilla/context v1.1.2 // indirect @@ -150,7 +151,7 @@ require ( github.com/jonboulle/clockwork v0.5.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/kaptinlin/jsonpointer v0.4.28 // indirect - github.com/klauspost/cpuid/v2 v2.4.0 // indirect + github.com/klauspost/cpuid/v2 v2.4.1 // indirect github.com/leodido/go-urn v1.5.0 // indirect github.com/lestrrat-go/blackmagic v1.0.4 // indirect github.com/lestrrat-go/dsig v1.4.0 // indirect @@ -190,11 +191,11 @@ require ( github.com/prometheus/otlptranslator v1.0.0 // indirect github.com/prometheus/procfs v0.22.0 // indirect github.com/quic-go/qpack v0.6.0 // indirect - github.com/quic-go/quic-go v0.63.0 // indirect + github.com/quic-go/quic-go v0.64.1 // indirect github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 // indirect github.com/segmentio/asm v1.2.1 // indirect github.com/shirou/gopsutil/v4 v4.26.9 // indirect - github.com/shopspring/decimal v1.5.0 // indirect + github.com/shopspring/decimal v1.6.0 // indirect github.com/sirosfoundation/g119612 v0.7.0 // indirect github.com/sirupsen/logrus v1.10.2 // indirect github.com/tklauser/go-sysconf v0.4.0 // indirect @@ -218,12 +219,11 @@ require ( go.yaml.in/yaml/v3 v3.0.5 // indirect golang.org/x/arch v0.32.0 // indirect golang.org/x/mod v0.42.0 // indirect - golang.org/x/net v0.61.0 // indirect golang.org/x/sys v0.49.0 // indirect golang.org/x/text v0.43.0 // indirect golang.org/x/tools v0.52.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20261012220534-4341edf3f941 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20261012220534-4341edf3f941 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20261019180522-ce908d29299b // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b // indirect ) replace github.com/russellhaering/goxmldsig => github.com/sirosfoundation/goxmldsig v1.6.1-siros1 diff --git a/go.sum b/go.sum index a59e4ff0f..5a1e6456f 100644 --- a/go.sum +++ b/go.sum @@ -33,8 +33,8 @@ github.com/bytedance/gopkg v0.1.4 h1:oZnQwnX82KAIWb7033bEwtxvTqXcYMxDBaQxo5JJHWM github.com/bytedance/gopkg v0.1.4/go.mod h1:v1zWfPm21Fb+OsyXN2VAHdL6TBb2L88anLQgdyje6R4= github.com/bytedance/sonic v1.15.4 h1:FgtV/4aBHpla9AxuMpuuzVUpa/Cf3izufkxNmnEzdI8= github.com/bytedance/sonic v1.15.4/go.mod h1:8e51yTPdY8M6t+vvGL1c2Y1xL9i+frEeIAQAEl75NUc= -github.com/bytedance/sonic/loader v0.5.2 h1:0QtP1gevc1OZ6/H8Lb9BRZiCXd1Ftjd3OKuj1T1lBIo= -github.com/bytedance/sonic/loader v0.5.2/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= +github.com/bytedance/sonic/loader v0.5.3 h1:ziVGAbXQtLoaot/M6YQxntGkekxz6B/DyuJVwnTbMAA= +github.com/bytedance/sonic/loader v0.5.3/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= github.com/cayleygraph/quad v1.3.0 h1:xg7HOLWWPgvZ4CcvzEpfCwq42L8mzYUR+8V0jtYoBzc= github.com/cayleygraph/quad v1.3.0/go.mod h1:NadtM7uMm78FskmX++XiOOrNvgkq0E1KvvhQdMseMz4= github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= @@ -89,14 +89,14 @@ github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4 github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/eapache/go-resiliency v1.7.0 h1:n3NRTnBn5N0Cbi/IeOHuQn9s2UwVUH7Ga0ZWcP+9JTA= github.com/eapache/go-resiliency v1.7.0/go.mod h1:5yPzW0MIvSe0JDsv0v+DvcjEv2FyD6iZYSs1ZI+iQho= -github.com/ebitengine/purego v0.11.1 h1:2zpWRSQNVKN4eKsKO9eM1ILDgWfYMY9GwqRmK6XeQ/0= -github.com/ebitengine/purego v0.11.1/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= +github.com/ebitengine/purego v0.11.2 h1:WWiTx8rD8zYdOwSj8O/NiNbsOvSAgJMTlyV1XlbUSeU= +github.com/ebitengine/purego v0.11.2/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= github.com/fxamacker/cbor/v2 v2.9.6 h1:NHZPxuUjJXQjX9itA785y/5NKSlI4HQ+S7noZsmI7hs= github.com/fxamacker/cbor/v2 v2.9.6/go.mod h1:4EaZp6ClVunETjQ4GHmGNzysDK91Lr+r6Yz6tJqzVCw= -github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI= -github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ= +github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E= +github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4= github.com/gin-contrib/cors v1.7.9 h1:69rz5YU6PW7XlQ4VPXacl77ldFiUvR0E0bmEqmbq86w= github.com/gin-contrib/cors v1.7.9/go.mod h1:KTqiTA5HzlWPgVz7p4tolzAuptzGO7DEJn/CbklG0nU= github.com/gin-contrib/gzip v1.2.8 h1:wDb1thtVsSUe+126xHdgLiWcZqHdWXiBzdZj2yhdUM8= @@ -241,8 +241,8 @@ github.com/kelseyhightower/envconfig v1.4.0 h1:Im6hONhd3pLkfDFsbRgu68RDNkGF1r3dv github.com/kelseyhightower/envconfig v1.4.0/go.mod h1:cccZRl6mQpaq41TPp5QxidR+Sa3axMbJDNb//FQX6Gg= github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTfY5j4= github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= -github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= -github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= +github.com/klauspost/cpuid/v2 v2.4.1 h1:I9KxadAkvo+QjtcEE2f2tyfEvmIla/T0m+14PrZNl0U= +github.com/klauspost/cpuid/v2 v2.4.1/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -364,8 +364,8 @@ github.com/quic-go/go-ossfuzz-seeds v0.1.0 h1:APacT+iIaNF6fd8AGEiN3bT/Jtkd2jz4v4 github.com/quic-go/go-ossfuzz-seeds v0.1.0/go.mod h1:3IOHRbJIc+L6YKMwfDtJAM9Vj9k0YY4muhuyUYk5tbk= github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= -github.com/quic-go/quic-go v0.63.0 h1:LIFGHI4PFUhhw2dDD1ARHdCff143ffMHwZtbnbuJ78A= -github.com/quic-go/quic-go v0.63.0/go.mod h1:RAro2j2yN9a9EiPACLHT9IB2NXCvGQmmo/alT0yYI0w= +github.com/quic-go/quic-go v0.64.1 h1:BCNTP+6x6++OPKrGST2FR3f1tycx8O3QOA3QQv09g70= +github.com/quic-go/quic-go v0.64.1/go.mod h1:RAro2j2yN9a9EiPACLHT9IB2NXCvGQmmo/alT0yYI0w= github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 h1:bsUq1dX0N8AOIL7EB/X911+m4EHsnWEHeJ0c+3TTBrg= github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s= @@ -377,16 +377,16 @@ github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr github.com/shirou/gopsutil/v4 v4.26.9 h1:CaBo/hBFqvlJoLvAQEKdHdf5GD97/MN2ACfyv63+2Ig= github.com/shirou/gopsutil/v4 v4.26.9/go.mod h1:nKH+8wX2zxr/mDbsR+AAy6Qd2z4ZOQ7wfQaEp+yrYmg= github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= -github.com/shopspring/decimal v1.5.0 h1:HxSWk31RmJv0EyY4oLiGQB9u7WPludUwPBdvQZnYFPc= -github.com/shopspring/decimal v1.5.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= +github.com/shopspring/decimal v1.6.0 h1:DcTwjCj4tJPLuGZYsR9W0hyX9pQwMIkdo26Ig1T9xX4= +github.com/shopspring/decimal v1.6.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= github.com/sirosfoundation/g119612 v0.7.0 h1:aVj6iNio/z7YVW4qFZk485Pn8gvwDiW3CCId2YUDWH8= github.com/sirosfoundation/g119612 v0.7.0/go.mod h1:JWUPZGeKDgsS3ehs4OGEDD10oMVQIS/XWSb31MJRkMU= github.com/sirosfoundation/go-cryptoutil v0.7.2 h1:V6rVKSsaFD3tNL8nVHMSQ0KdRFE9K+XrFf2/yiWGe14= github.com/sirosfoundation/go-cryptoutil v0.7.2/go.mod h1:6JWcg/wLtALH2x6Hofa6VYX4b6XKiMNfXAVjp4yv9CA= github.com/sirosfoundation/go-spocp v0.1.0 h1:fH/jrSHS8vc+KfAzJmq3fE9OH69ShRgL7G1ihb9FCPs= github.com/sirosfoundation/go-spocp v0.1.0/go.mod h1:a6WtxG5hnsUzcqUt5iHmSMvyX4PLUPMDFK7FLoDMSMs= -github.com/sirosfoundation/go-trust v0.24.1 h1:PsoQ71rKdye8IsDjYRcl5KFHlRgMoa6eMqf2iJLUFQU= -github.com/sirosfoundation/go-trust v0.24.1/go.mod h1:AdXwiqPiRG40tb6ox5N82HCmVbUVSpgAy0L5wKpCG00= +github.com/sirosfoundation/go-trust v0.26.0 h1:hZcii002VP15g9JevqYCzZrGf6Kpipo7YBnOfs6g3Xg= +github.com/sirosfoundation/go-trust v0.26.0/go.mod h1:/bfPbXR7fnNM4lBRYmWQRgqHutGfX6wuRlsj1CeB0eg= github.com/sirosfoundation/go-ts11client v0.0.0-20260821071625-a8d5997107d0 h1:UyoIfTiFimESFkS/nQ1g8qIWpB8Dropwl2XLzGFDxPk= github.com/sirosfoundation/go-ts11client v0.0.0-20260821071625-a8d5997107d0/go.mod h1:PEH6L1hSgFvbUjIjcLlp5XK7y0fg02B4WQk8tIsw2us= github.com/sirosfoundation/goxmldsig v1.6.1-siros1 h1:iQadRZy/iwj0E/hXlfKrEDqA94Ey1ozIdLtATKGpGH8= @@ -568,10 +568,10 @@ golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/genproto/googleapis/api v0.0.0-20261012220534-4341edf3f941 h1:DS/w3N8rsfrwxwgGSj6WhMsPo7aNQGmDx74J81zd0NQ= -google.golang.org/genproto/googleapis/api v0.0.0-20261012220534-4341edf3f941/go.mod h1:AuGAdi9KnXss7xbLxIKhCvk+Ro/SxpET/iS45DNYN+M= -google.golang.org/genproto/googleapis/rpc v0.0.0-20261012220534-4341edf3f941 h1:QG6hS4zFplRZvOQedzei4t2pT/zkQc3VR1u+S9/rcAw= -google.golang.org/genproto/googleapis/rpc v0.0.0-20261012220534-4341edf3f941/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= +google.golang.org/genproto/googleapis/api v0.0.0-20261019180522-ce908d29299b h1:nB3spRIaSPtxJpxb0k41yljROvm2Jrwfs2pSNdKS5y8= +google.golang.org/genproto/googleapis/api v0.0.0-20261019180522-ce908d29299b/go.mod h1:9N4vtjEwvgQKEdlFVQO0M44ErhecQ9DCSQfGoZ51M6w= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b h1:6WNWHZk91dp4gZ25642OALkuG1UVNZbwENJD19DnB8k= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= google.golang.org/grpc v1.84.0 h1:soMyaPJ8pAak5PIQ0DGBUir0XRo2fRoMqhNWMLlLxO0= google.golang.org/grpc v1.84.0/go.mod h1:ljCht0DrxQrXBDRTZp52Qxh3Ffk8CdYm2sj4O2QN2C0= google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= diff --git a/vendor/github.com/bytedance/sonic/loader/mmap_unix.go b/vendor/github.com/bytedance/sonic/loader/mmap_unix.go index 26bdb6584..4d0875d06 100644 --- a/vendor/github.com/bytedance/sonic/loader/mmap_unix.go +++ b/vendor/github.com/bytedance/sonic/loader/mmap_unix.go @@ -20,26 +20,25 @@ package loader import ( - `syscall` + "syscall" ) const ( - _AP = syscall.MAP_ANON | syscall.MAP_PRIVATE - _RX = syscall.PROT_READ | syscall.PROT_EXEC - _RW = syscall.PROT_READ | syscall.PROT_WRITE + _AP = syscall.MAP_ANON | syscall.MAP_PRIVATE + _RX = syscall.PROT_READ | syscall.PROT_EXEC + _RW = syscall.PROT_READ | syscall.PROT_WRITE ) - func mmap(nb int) uintptr { - if m, _, e := syscall.RawSyscall6(syscall.SYS_MMAP, 0, uintptr(nb), _RW, _AP, 0, 0); e != 0 { - panic(e) - } else { - return m - } + if m, _, e := syscall.RawSyscall6(syscall.SYS_MMAP, 0, uintptr(nb), _RW, _AP, ^uintptr(0), 0); e != 0 { + panic(e) + } else { + return m + } } func mprotect(p uintptr, nb int) { - if _, _, err := syscall.RawSyscall(syscall.SYS_MPROTECT, p, uintptr(nb), _RX); err != 0 { - panic(err) - } + if _, _, err := syscall.RawSyscall(syscall.SYS_MPROTECT, p, uintptr(nb), _RX); err != 0 { + panic(err) + } } diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo.go index d1c842e63..365fb3cf6 100644 --- a/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo.go +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo.go @@ -23,12 +23,6 @@ type ( type sighow int32 -const ( - SIG_BLOCK sighow = 0 - SIG_UNBLOCK sighow = 1 - SIG_SETMASK sighow = 2 -) - type G struct { _ structs.HostLayout stacklo uintptr diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_darwin.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_darwin.go index 8b1eec2d7..5ff687121 100644 --- a/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_darwin.go +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_darwin.go @@ -25,6 +25,13 @@ var ( PTHREAD_MUTEX_INITIALIZER = pthread_mutex_t{sig: 0x32AAABA7} ) +// Source: https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/bsd/sys/signal.h#L488 +const ( + SIG_BLOCK sighow = 1 + SIG_UNBLOCK sighow = 2 + SIG_SETMASK sighow = 3 +) + type stack_t struct { /* not implemented */ } diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_freebsd.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_freebsd.go index 4bfb70c3d..1651022f8 100644 --- a/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_freebsd.go +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_freebsd.go @@ -15,6 +15,13 @@ var ( PTHREAD_MUTEX_INITIALIZER = pthread_mutex_t(0) ) +// Source: https://github.com/freebsd/freebsd-src/blob/f84cdc2584305f8b656ce3f3746868c4a58a9a82/sys/sys/signal.h#L470 +const ( + SIG_BLOCK sighow = 1 + SIG_UNBLOCK sighow = 2 + SIG_SETMASK sighow = 3 +) + type stack_t struct { /* not implemented */ } diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_linux.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_linux.go index b08a44a10..e2691aa57 100644 --- a/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_linux.go +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_linux.go @@ -15,6 +15,13 @@ var ( PTHREAD_MUTEX_INITIALIZER = pthread_mutex_t{} ) +// Source: https://github.com/torvalds/linux/blob/0fcb05b72344f40806cbe810de8872f1698bf053/include/uapi/asm-generic/signal-defs.h#L71 +const ( + SIG_BLOCK sighow = 0 + SIG_UNBLOCK sighow = 1 + SIG_SETMASK sighow = 2 +) + type stack_t struct { /* not implemented */ } diff --git a/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_netbsd.go b/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_netbsd.go index 5d0d57860..870b6841f 100644 --- a/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_netbsd.go +++ b/vendor/github.com/ebitengine/purego/internal/fakecgo/libcgo_netbsd.go @@ -17,6 +17,13 @@ var ( PTHREAD_MUTEX_INITIALIZER = pthread_mutex_t(0) ) +// Source: https://github.com/NetBSD/src/blob/613e27c65223fd2283b6ed679da1197e12f50e27/sys/sys/signal.h#L242 +const ( + SIG_BLOCK sighow = 1 + SIG_UNBLOCK sighow = 2 + SIG_SETMASK sighow = 3 +) + // Source: https://github.com/NetBSD/src/blob/613e27c65223fd2283b6ed679da1197e12f50e27/sys/sys/signal.h#L225 type stack_t struct { _ structs.HostLayout diff --git a/vendor/github.com/gabriel-vasile/mimetype/README.md b/vendor/github.com/gabriel-vasile/mimetype/README.md index b02431699..bb2dece0d 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/README.md +++ b/vendor/github.com/gabriel-vasile/mimetype/README.md @@ -13,6 +13,9 @@ Go Reference + + Tests + Code coverage diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/cdf/cdf.go b/vendor/github.com/gabriel-vasile/mimetype/internal/cdf/cdf.go index 926cef7b0..574c2ea34 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/cdf/cdf.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/cdf/cdf.go @@ -46,12 +46,14 @@ type cdf struct { satSecs int32s // list of SAT sector ids; usually a sub-slice of raw input satEntries int // number of valid SAT entries reachable through satSecs firstSSAT int32 + ssatSecs int32s // list of SSAT sector ids, precomputed from the firstSSAT chain dirRaw []byte // directory stream bytes (entries are decoded on demand) sst []byte // short-stream pool (root storage's stream) sstBuilt bool // whether sst was already loaded (it is loaded lazily) rootStreamFirst int32 // first sector of the root storage short-stream pool rootStreamSize uint32 // size of the root storage short-stream pool - rootStorageUUID []byte + rootChild int32 // directory id of the root storage's child tree + rootStorageUUID [16]byte } // parse reads the entire on-disk structure required for type detection. It @@ -81,35 +83,108 @@ func parse(raw []byte, c *cdf) bool { masterSAT := int32s{b: raw[76 : 76+4*masterSATSize]} c.buildSAT(masterSAT, firstMSAT, nMSAT) + c.buildSSAT() c.dirRaw = c.readLong(firstDirSec, 0) c.rootStreamFirst = -1 + c.rootChild = -1 var d dirEntry for i, n := 0, c.dirLen(); i < n; i++ { c.dirAt(i, &d) - if d.typ != dirTypeRootStorage || d.streamFirst < 0 { + if d.typ != dirTypeRootStorage { continue } - c.rootStorageUUID = d.storageUUID[:] + copy(c.rootStorageUUID[:], d.storageUUID[:]) + c.rootChild = d.child // Record where the short-stream pool lives; it is loaded lazily by // shortStream the first time a short stream is actually read. - c.rootStreamFirst = d.streamFirst - c.rootStreamSize = d.size + if d.streamFirst >= 0 { + c.rootStreamFirst = d.streamFirst + c.rootStreamSize = d.size + } break } return true } +// rootChildIter iterates over the directory entries that are direct children +// of the root storage, walking the red-black sibling tree hanging off the root +// entry's child pointer. Restricting detection to root-level entries matters: +// embedded OLE objects (e.g. an Excel sheet inside a Word document) carry +// their own SummaryInformation streams deeper in the hierarchy, and a flat +// directory scan can pick those up instead of the document's own. +// If the tree is unusable (no valid root child) iteration degrades to a flat +// scan of all entries so truncated or malformed files still get best-effort +// detection. The iterator lives entirely on the caller's stack: it allocates +// nothing and decodes each visited entry into its inline d field. +type rootChildIter struct { + c *cdf + d dirEntry // entry decoded by the latest successful next call + n int // total directory entries + i int // next index for the flat fallback scan + flat bool // no usable tree; scan all entries instead + visited int // entries visited so far; guards against cyclic trees + sp int // number of ids on stack + stack [64]int32 +} + +// rootChildren returns an iterator over the root storage's direct children. +// Usage: for it := c.rootChildren(); it.next(); { ... use it.d ... } +func (c *cdf) rootChildren() rootChildIter { + it := rootChildIter{c: c, n: c.dirLen()} + if c.rootChild >= 0 && int(c.rootChild) < it.n { + it.stack[0] = c.rootChild + it.sp = 1 + } else { + it.flat = true + } + return it +} + +// next advances to the next entry, decoding it into it.d. It reports false +// when iteration is done. +func (it *rootChildIter) next() bool { + if it.flat { + if it.i >= it.n { + return false + } + it.c.dirAt(it.i, &it.d) + it.i++ + return true + } + for it.sp > 0 { + it.sp-- + id := it.stack[it.sp] + if id < 0 || int(id) >= it.n { + continue + } + if it.visited++; it.visited > it.n { + return false // cyclic sibling pointers in a malformed directory + } + it.c.dirAt(int(id), &it.d) + // Push the siblings. A valid red-black tree of n entries is at most + // 2*log2(n) deep, so the fixed-size stack cannot overflow for any + // real directory; if a malformed tree overflows it, the excess + // branches are dropped and detection degrades gracefully. + for _, sib := range [2]int32{it.d.left, it.d.right} { + if sib >= 0 && it.sp < len(it.stack) { + it.stack[it.sp] = sib + it.sp++ + } + } + return true + } + return false +} + func (c *cdf) detect() CDFType { for _, name := range []string{"\x05SummaryInformation", "\x05DocumentSummaryInformation"} { if t, ok := c.detectFromSummary(name); ok { return t } } - var d dirEntry - for i, n := 0, c.dirLen(); i < n; i++ { - c.dirAt(i, &d) - if t, ok := lookupSection(d.nameBytes(), d.typ); ok { + for it := c.rootChildren(); it.next(); { + if t, ok := lookupSection(it.d.nameBytes(), it.d.typ); ok { return t } } @@ -120,7 +195,7 @@ func (c *cdf) detect() CDFType { // derive a CDFType from the root-storage CLSID, the property NameOfApplication, // and finally the names of sibling user streams. func (c *cdf) detectFromSummary(streamName string) (CDFType, bool) { - if c.rootStorageUUID != nil && bytes.Equal(c.rootStorageUUID, msiCLSID) { + if bytes.Equal(c.rootStorageUUID[:], msiCLSID) { return CDFTypeInstaller, true } raw, ok := c.userStream(streamName) @@ -132,13 +207,11 @@ func (c *cdf) detectFromSummary(streamName string) (CDFType, bool) { return t, true } } - for i, n := 0, c.dirLen(); i < n; i++ { - var d dirEntry - c.dirAt(i, &d) - if d.nameLen == 0 { + for it := c.rootChildren(); it.next(); { + if it.d.nameLen == 0 { continue } - if t, ok := lookupSubstring(d.nameBytes(), name2type); ok { + if t, ok := lookupSubstring(it.d.nameBytes(), name2type); ok { return t, true } } @@ -164,6 +237,9 @@ type dirEntry struct { name [32]byte nameLen uint8 typ uint8 + left int32 // left sibling directory id + right int32 // right sibling directory id + child int32 // first child directory id (for storages) streamFirst int32 size uint32 storageUUID [16]byte @@ -172,23 +248,56 @@ type dirEntry struct { // nameBytes returns the decoded ASCII name without copying. func (d *dirEntry) nameBytes() []byte { return d.name[:d.nameLen] } -func (c *cdf) ssatAt(i int32) int32 { +// buildSSAT records the list of SSAT sector ids by walking the firstSSAT chain +// through the SAT once. The SSAT contents are not materialized; ssatAt computes +// the requested entry directly from c.data via ssatSecs, mirroring satSecs/satAt. +// The walk is bounded by the number of sectors in the file so a cyclic SAT +// (a self-looping sector) cannot spin forever. +func (c *cdf) buildSSAT() { + maxIDs := len(c.data)/c.secSize + 1 + buf := make([]byte, 0, 4*8) + var tmp [4]byte for sid := c.firstSSAT; sid >= 0; { if int(sid) >= c.satLen() { break // SAT is truncated; stop collecting } - buf, ok := c.sector(sid) - if !ok { + if _, ok := c.sector(sid); !ok { break } - lbuf := int32(len(buf) / 4) //nolint:gosec // anything divided by 4 fits int32 - if i < lbuf { - return int32(binary.LittleEndian.Uint32(buf[4*i:])) //nolint:gosec // intentional two's-complement reinterpretation of a sector id + binary.LittleEndian.PutUint32(tmp[:], uint32(sid)) //nolint:gosec // reinterpret sector id + buf = append(buf, tmp[:]...) + if len(buf)/4 > maxIDs { + break // cyclic SAT chain; stop allocating } - i -= lbuf sid = c.satAt(sid) } - return -1 + c.ssatSecs = int32s{b: buf} +} + +// ssatAt returns the i-th SSAT entry (a short-sector id) by indexing directly +// into the precomputed ssatSecs, the same way satAt indexes satSecs. It returns +// -1 when i is past the end of the SSAT or the backing sector is truncated. +func (c *cdf) ssatAt(i int32) int32 { + if i < 0 { + return -1 + } + perSec := int32(c.secSize / 4) //nolint:gosec // secSize is a small power of two + secIdx := int(i / perSec) + if secIdx >= c.ssatSecs.len() { + return -1 + } + sid := c.ssatSecs.at(secIdx) + buf, ok := c.sector(sid) + if !ok { + return -1 + } + entryIdx := i % perSec + //nolint:gosec // anything divided by 4 fits int32 + if entryIdx >= int32(len(buf)/4) { + return -1 // sector truncated short of this entry + } + //nolint:gosec // intentional two's-complement reinterpretation of a sector id + return int32(binary.LittleEndian.Uint32(buf[4*entryIdx:])) } // shortStream returns the root storage short-stream pool, loading it on first @@ -435,6 +544,9 @@ func (c *cdf) readShort(sid int32, length uint32) []byte { } off := int(off64) out = append(out, sst[off:off+c.shortSecSize]...) + if length > 0 && int64(len(out)) >= int64(length) { + break // read enough to satisfy the stream's declared length + } if len(out) >= len(sst) { break // chain longer than the pool: cyclic SSAT, stop } @@ -476,18 +588,19 @@ func (c *cdf) dirAt(i int, out *dirEntry) { } out.nameLen = k out.typ = raw[66] + out.left = readSecID(raw[68:72]) + out.right = readSecID(raw[72:76]) + out.child = readSecID(raw[76:80]) out.streamFirst = readSecID(raw[116:120]) out.size = binary.LittleEndian.Uint32(raw[120:]) copy(out.storageUUID[:], raw[80:96]) } -// userStream finds a user stream by name and returns its bytes. +// userStream finds a root-level user stream by name and returns its bytes. func (c *cdf) userStream(name string) ([]byte, bool) { - var d dirEntry - for i, n := 0, c.dirLen(); i < n; i++ { - c.dirAt(i, &d) - if d.typ == dirTypeUserStream && string(d.nameBytes()) == name { - buf := c.readChain(d.streamFirst, d.size) + for it := c.rootChildren(); it.next(); { + if it.d.typ == dirTypeUserStream && string(it.d.nameBytes()) == name { + buf := c.readChain(it.d.streamFirst, it.d.size) if buf == nil { return nil, false } diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/audio.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/audio.go index ad48d8fb8..7ef997564 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/audio.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/audio.go @@ -50,7 +50,7 @@ func M3U(raw []byte, _ uint32) bool { // AAC matches an Advanced Audio Coding file. func AAC(raw []byte, _ uint32) bool { - return len(raw) > 1 && ((raw[0] == 0xFF && raw[1] == 0xF1) || (raw[0] == 0xFF && raw[1] == 0xF9)) + return len(raw) > 1 && raw[0] == 0xFF && (raw[1] == 0xF1 || raw[1] == 0xF9) } // MP3 matches a .mp3 file. @@ -128,27 +128,30 @@ func id3v2(raw []byte) bool { } size := uint32(raw[6])<<21 | uint32(raw[7])<<14 | uint32(raw[8])<<7 | uint32(raw[9]) - // Disallow too big frames, let's say 10MB. - return size > 0 && size < 10*1024*1024 + // The synchsafe integer is already bounded to 28 bits (~256MB). A 10MB + // cap rejected legitimate files with large ID3v2 album art. #839 + return size > 0 +} + +// iff checks for an Interchange File Format layout: 4-byte container tag, +// 4-byte size, 4-byte format tag. +func iff(raw []byte, container, format []byte) bool { + return len(raw) > 12 && + bytes.Equal(raw[:4], container) && + bytes.Equal(raw[8:12], format) } // Wav matches a Waveform Audio File Format file. func Wav(raw []byte, limit uint32) bool { - return len(raw) > 12 && - bytes.Equal(raw[:4], []byte("RIFF")) && - bytes.Equal(raw[8:12], []byte{0x57, 0x41, 0x56, 0x45}) + return iff(raw, []byte("RIFF"), []byte("WAVE")) } // Aiff matches Audio Interchange File Format file. func Aiff(raw []byte, limit uint32) bool { - return len(raw) > 12 && - bytes.Equal(raw[:4], []byte{0x46, 0x4F, 0x52, 0x4D}) && - bytes.Equal(raw[8:12], []byte{0x41, 0x49, 0x46, 0x46}) + return iff(raw, []byte("FORM"), []byte("AIFF")) } // Qcp matches a Qualcomm Pure Voice file. func Qcp(raw []byte, limit uint32) bool { - return len(raw) > 12 && - bytes.Equal(raw[:4], []byte("RIFF")) && - bytes.Equal(raw[8:12], []byte("QLCM")) + return iff(raw, []byte("RIFF"), []byte("QLCM")) } diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go index d21796873..9e14b6f81 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go @@ -121,29 +121,22 @@ func Dbf(raw []byte, limit uint32) bool { return slices.Contains(dbfTypes, raw[0]) } -// ElfObj matches an object file. -func ElfObj(raw []byte, limit uint32) bool { - return len(raw) > 17 && ((raw[16] == 0x01 && raw[17] == 0x00) || - (raw[16] == 0x00 && raw[17] == 0x01)) +func elfType(raw []byte, t byte) bool { + return len(raw) > 17 && + ((raw[16] == t && raw[17] == 0x00) || (raw[16] == 0x00 && raw[17] == t)) } +// ElfObj matches an object file. +func ElfObj(raw []byte, limit uint32) bool { return elfType(raw, 0x01) } + // ElfExe matches an executable file. -func ElfExe(raw []byte, limit uint32) bool { - return len(raw) > 17 && ((raw[16] == 0x02 && raw[17] == 0x00) || - (raw[16] == 0x00 && raw[17] == 0x02)) -} +func ElfExe(raw []byte, limit uint32) bool { return elfType(raw, 0x02) } // ElfLib matches a shared library file. -func ElfLib(raw []byte, limit uint32) bool { - return len(raw) > 17 && ((raw[16] == 0x03 && raw[17] == 0x00) || - (raw[16] == 0x00 && raw[17] == 0x03)) -} +func ElfLib(raw []byte, limit uint32) bool { return elfType(raw, 0x03) } // ElfDump matches a core dump file. -func ElfDump(raw []byte, limit uint32) bool { - return len(raw) > 17 && ((raw[16] == 0x04 && raw[17] == 0x00) || - (raw[16] == 0x00 && raw[17] == 0x04)) -} +func ElfDump(raw []byte, limit uint32) bool { return elfType(raw, 0x04) } // Dcm matches a DICOM medical format file. func Dcm(raw []byte, limit uint32) bool { diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/image.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/image.go index d46faca73..1f4164ec3 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/image.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/image.go @@ -178,9 +178,7 @@ func jpeg2k(raw []byte, sig []byte) bool { // Webp matches a WebP file. func Webp(raw []byte, _ uint32) bool { - return len(raw) > 12 && - bytes.Equal(raw[0:4], []byte("RIFF")) && - bytes.Equal(raw[8:12], []byte{0x57, 0x45, 0x42, 0x50}) + return iff(raw, []byte("RIFF"), []byte("WEBP")) } // Dwg matches a CAD drawing file. diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go index f078ff332..802515b25 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go @@ -101,25 +101,13 @@ func markup(b scan.Bytes, sigs ...[]byte) bool { return false } func markupCheck(sig, raw []byte) bool { - if len(raw) < len(sig)+1 { + if !ciCheck(sig, raw) { return false } - - // perform case insensitive check - for i, b := range sig { - db := raw[i] - if 'A' <= b && b <= 'Z' { - db &= 0xDF - } - if b != db { - return false - } - } // Next byte must be space or right angle bracket. if db := raw[len(sig)]; !scan.ByteIsWS(db) && db != '>' { return false } - return true } diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ms_office.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ms_office.go index 62cced078..27b63b2a1 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ms_office.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ms_office.go @@ -46,26 +46,16 @@ func Ole(raw []byte, limit uint32) bool { return bytes.HasPrefix(raw, []byte{0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1}) } -// Doc matches a Microsoft Word 97-2003 file. -// See: https://github.com/decalage2/oletools/blob/412ee36ae45e70f42123e835871bac956d958461/oletools/common/clsid.py -func Doc(raw []byte, _ uint32) bool { +// cdfOrClsid checks if the raw input is detected as the given CDF type, and if +// the CDF parser returns a generic result, falls back to matching root storage CLSIDs. +func cdfOrClsid(raw []byte, want cdf.CDFType, clsids ...[]byte) bool { fromParsing := cdf.Detect(raw) - if fromParsing == cdf.CDFTypeDoc { + if fromParsing == want { return true } if fromParsing != cdf.CDFTypeGeneric { return false } - // Fallback for inputs where the CDF directory is past the read limit: match - // the root storage CLSID, which often lies within the first sectors. - clsids := [][]byte{ - // Microsoft Word 97-2003 Document (Word.Document.8) - {0x06, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, - // Microsoft Word 6.0-7.0 Document (Word.Document.6) - {0x00, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, - // Microsoft Word Picture (Word.Picture.8) - {0x07, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, - } for _, clsid := range clsids { if matchOleClsid(raw, clsid) { return true @@ -74,25 +64,27 @@ func Doc(raw []byte, _ uint32) bool { return false } +// Doc matches a Microsoft Word 97-2003 file. +// See: https://github.com/decalage2/oletools/blob/412ee36ae45e70f42123e835871bac956d958461/oletools/common/clsid.py +func Doc(raw []byte, _ uint32) bool { + return cdfOrClsid(raw, cdf.CDFTypeDoc, + // Microsoft Word 97-2003 Document (Word.Document.8) + []byte{0x06, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, + // Microsoft Word 6.0-7.0 Document (Word.Document.6) + []byte{0x00, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, + // Microsoft Word Picture (Word.Picture.8) + []byte{0x07, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, + ) +} + // Ppt matches a Microsoft PowerPoint 97-2003 file or a PowerPoint 95 presentation. func Ppt(raw []byte, limit uint32) bool { - fromParsing := cdf.Detect(raw) - if fromParsing == cdf.CDFTypePpt { - return true - } - if fromParsing != cdf.CDFTypeGeneric { - return false - } - // Fallback for inputs where the CDF directory is past the read limit. - // Root CLSID test is the safest way to identify the OLE, however, the format - // often places the root CLSID at the end of the file. - if matchOleClsid(raw, []byte{ - 0x10, 0x8d, 0x81, 0x64, 0x9b, 0x4f, 0xcf, 0x11, - 0x86, 0xea, 0x00, 0xaa, 0x00, 0xb9, 0x29, 0xe8, - }) || matchOleClsid(raw, []byte{ - 0x70, 0xae, 0x7b, 0xea, 0x3b, 0xfb, 0xcd, 0x11, - 0xa9, 0x03, 0x00, 0xaa, 0x00, 0x51, 0x0e, 0xa3, - }) { + if cdfOrClsid(raw, cdf.CDFTypePpt, + []byte{0x10, 0x8d, 0x81, 0x64, 0x9b, 0x4f, 0xcf, 0x11, + 0x86, 0xea, 0x00, 0xaa, 0x00, 0xb9, 0x29, 0xe8}, + []byte{0x70, 0xae, 0x7b, 0xea, 0x3b, 0xfb, 0xcd, 0x11, + 0xa9, 0x03, 0x00, 0xaa, 0x00, 0x51, 0x0e, 0xa3}, + ) { return true } @@ -117,21 +109,10 @@ func Ppt(raw []byte, limit uint32) bool { // Xls matches a Microsoft Excel 97-2003 file. func Xls(raw []byte, limit uint32) bool { - fromParsing := cdf.Detect(raw) - if fromParsing == cdf.CDFTypeXls { - return true - } - if fromParsing != cdf.CDFTypeGeneric { - return false - } - // Fallback for inputs where the CDF directory is past the read limit. - // Root CLSID test is the safest way to identify the OLE, however, the format - // often places the root CLSID at the end of the file. - if matchOleClsid(raw, []byte{ - 0x10, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, - }) || matchOleClsid(raw, []byte{ - 0x20, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, - }) { + if cdfOrClsid(raw, cdf.CDFTypeXls, + []byte{0x10, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00}, + []byte{0x20, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00}, + ) { return true } @@ -168,19 +149,10 @@ func Pub(raw []byte, limit uint32) bool { // Msg matches a Microsoft Outlook email file. func Msg(raw []byte, limit uint32) bool { - fromParsing := cdf.Detect(raw) - if fromParsing == cdf.CDFTypeMsg { - return true - } - if fromParsing != cdf.CDFTypeGeneric { - return false - } - // Fallback for inputs where the CDF directory does not carry the streams the - // parser keys on: match the root storage CLSID instead. - return matchOleClsid(raw, []byte{ - 0x0B, 0x0D, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, - }) + return cdfOrClsid(raw, cdf.CDFTypeMsg, + []byte{0x0B, 0x0D, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, + ) } // Msi matches a Microsoft Windows Installer file. diff --git a/vendor/github.com/klauspost/cpuid/v2/cpuid.go b/vendor/github.com/klauspost/cpuid/v2/cpuid.go index db903f46a..741af8ac8 100644 --- a/vendor/github.com/klauspost/cpuid/v2/cpuid.go +++ b/vendor/github.com/klauspost/cpuid/v2/cpuid.go @@ -68,6 +68,8 @@ const ( THead Andes SpacemiT + Microchip + MIPS lastVendor ) @@ -477,6 +479,7 @@ func init() { // exported CPU variable. func Detect() { // Set defaults + topoSnapshot.Store(nil) CPU.ThreadsPerCore = 1 CPU.Cache.L1I = -1 CPU.Cache.L1D = -1 @@ -1223,10 +1226,14 @@ func (c *CPUInfo) cacheSize() { // 2 = Instruction Cache c.Cache.L1I = size } else { - if c.Cache.L1D < 0 { - c.Cache.L1I = size + // Unified cache; apply to whichever of L1D/L1I is still + // unset. L1D/L1I are zeroed for Intel and pre-populated + // from CPUID 0x80000005 for AMD/Hygon, so check for both + // the -1 sentinel and an unset zero value. + if c.Cache.L1D <= 0 { + c.Cache.L1D = size } - if c.Cache.L1I < 0 { + if c.Cache.L1I <= 0 { c.Cache.L1I = size } } @@ -1295,10 +1302,12 @@ func (c *CPUInfo) cacheSize() { // Inst cache c.Cache.L1I = size default: - if c.Cache.L1D < 0 { - c.Cache.L1I = size + // Unified cache; apply to whichever of L1D/L1I is still + // unset (see the Intel path for the <= 0 rationale). + if c.Cache.L1D <= 0 { + c.Cache.L1D = size } - if c.Cache.L1I < 0 { + if c.Cache.L1I <= 0 { c.Cache.L1I = size } } diff --git a/vendor/github.com/klauspost/cpuid/v2/featureid_string.go b/vendor/github.com/klauspost/cpuid/v2/featureid_string.go index f88ead130..c219be92c 100644 --- a/vendor/github.com/klauspost/cpuid/v2/featureid_string.go +++ b/vendor/github.com/klauspost/cpuid/v2/featureid_string.go @@ -356,12 +356,14 @@ func _() { _ = x[THead-33] _ = x[Andes-34] _ = x[SpacemiT-35] - _ = x[lastVendor-36] + _ = x[Microchip-36] + _ = x[MIPS-37] + _ = x[lastVendor-38] } -const _Vendor_name = "VendorUnknownIntelAMDVIATransmetaNSCKVMMSVMVMwareXenHVMBhyveHygonSiSRDCAmpereARMBroadcomCaviumDECFujitsuInfineonMotorolaNVIDIAAMCCQualcommMarvellQEMUQNXACRNSREAppleSiFiveStarFiveTHeadAndesSpacemiTlastVendor" +const _Vendor_name = "VendorUnknownIntelAMDVIATransmetaNSCKVMMSVMVMwareXenHVMBhyveHygonSiSRDCAmpereARMBroadcomCaviumDECFujitsuInfineonMotorolaNVIDIAAMCCQualcommMarvellQEMUQNXACRNSREAppleSiFiveStarFiveTHeadAndesSpacemiTMicrochipMIPSlastVendor" -var _Vendor_index = [...]uint8{0, 13, 18, 21, 24, 33, 36, 39, 43, 49, 55, 60, 65, 68, 71, 77, 80, 88, 94, 97, 104, 112, 120, 126, 130, 138, 145, 149, 152, 156, 159, 164, 170, 178, 183, 188, 196, 206} +var _Vendor_index = [...]uint8{0, 13, 18, 21, 24, 33, 36, 39, 43, 49, 55, 60, 65, 68, 71, 77, 80, 88, 94, 97, 104, 112, 120, 126, 130, 138, 145, 149, 152, 156, 159, 164, 170, 178, 183, 188, 196, 205, 209, 219} func (i Vendor) String() string { idx := int(i) - 0 diff --git a/vendor/github.com/klauspost/cpuid/v2/riscv_isa.go b/vendor/github.com/klauspost/cpuid/v2/riscv_isa.go index 5a87679bd..b4df7c4ff 100644 --- a/vendor/github.com/klauspost/cpuid/v2/riscv_isa.go +++ b/vendor/github.com/klauspost/cpuid/v2/riscv_isa.go @@ -78,10 +78,11 @@ func parseISAString(c *CPUInfo, isa string) { } var riscvVendorMap = map[uint64]Vendor{ - 0x489: SiFive, - 0x5b7: StarFive, - 0x5b1: THead, + 0x029: Microchip, + 0x127: MIPS, 0x31e: Andes, + 0x489: SiFive, + 0x5b7: THead, 0x710: SpacemiT, } diff --git a/vendor/github.com/klauspost/cpuid/v2/topology.go b/vendor/github.com/klauspost/cpuid/v2/topology.go new file mode 100644 index 000000000..957281f03 --- /dev/null +++ b/vendor/github.com/klauspost/cpuid/v2/topology.go @@ -0,0 +1,480 @@ +// Copyright (c) 2026 Klaus Post, released under MIT License. See LICENSE file. + +package cpuid + +import ( + "cmp" + "math/bits" + "slices" + "sync/atomic" + + "github.com/klauspost/cpuid/v2/topology" +) + +// logicalCPU holds the topology-relevant CPUID data of a single logical +// processor. It is produced by parseLogicalCPU on whichever CPU the calling +// goroutine currently runs, so a full tree needs one per online CPU (see +// ScanTopology); a single one drives the extrapolated snapshot. +type logicalCPU struct { + apicID uint32 // (x2)APIC id + vendor Vendor // + smtShift uint8 // apicID>>smtShift == core id + pkgShift uint8 // apicID>>pkgShift == package id + l3Shift uint8 // apicID>>l3Shift == L3 (group) id; 0 if no L3 + nodeID int // AMD node id (leaf 0x8000001E ECX) + coreType topology.CoreType // + model string // + caches []cpuCache // +} + +// cpuCache pairs a decoded cache with the addressable number of logical +// processors that share it, which is what determines its sharing domain. +type cpuCache struct { + c topology.Cache + numShare int +} + +// topoSnapshot caches the extrapolated single-CPU topology; Detect resets it. +var topoSnapshot atomic.Pointer[topology.System] + +// Topology returns the CPU topology as a fixed hierarchy of +// System → Package → Group → Core → Thread. +// +// It is extrapolated from the current core's CPUID and the detected core +// counts, so counts and cache totals are accurate for homogeneous CPUs but +// individual cores of a hybrid CPU cannot be classified. For an exact, +// per-core tree (real efficiency/performance mapping and CCD membership) use +// ScanTopology, which briefly pins the current goroutine to each CPU. +func (c CPUInfo) Topology() *topology.System { + if t := topoSnapshot.Load(); t != nil { + return t + } + t := snapshotTopology() + topoSnapshot.Store(t) + return t +} + +// parseLogicalCPU reads the topology leaves of the current logical processor. +func parseLogicalCPU() logicalCPU { + var lc logicalCPU + lc.vendor, _ = vendorID() + mfi := maxFunctionID() + mef := maxExtendedFunction() + + // Extended topology enumeration: leaf 0x1F (V2) is preferred over 0x0B. + // EAX[4:0] is the right-shift of the x2APIC id (EDX) that yields the id of + // the next coarser level; ECX[15:8] is the level type (1=SMT, 2=Core, …). + topoLeaf := uint32(0) + if mfi >= 0x1f { + if _, ebx, _, _ := cpuidex(0x1f, 0); ebx&0xffff != 0 { + topoLeaf = 0x1f + } + } + if topoLeaf == 0 && mfi >= 0xb { + if _, ebx, _, _ := cpuidex(0xb, 0); ebx&0xffff != 0 { + topoLeaf = 0xb + } + } + switch { + case topoLeaf != 0: + var maxShift uint8 + for sub := range uint32(16) { + eax, ebx, ecx, edx := cpuidex(topoLeaf, sub) + if ebx&0xffff == 0 { + break + } + lc.apicID = edx + shift := uint8(eax & 0x1f) + if (ecx>>8)&0xff == 1 { // SMT level + lc.smtShift = shift + } + if shift > maxShift { + maxShift = shift + } + } + lc.pkgShift = maxShift + case mfi >= 1: + // Legacy 8-bit initial APIC id. + _, ebx, _, _ := cpuid(1) + lc.apicID = (ebx >> 24) & 0xff + lc.smtShift = ceilLog2(threadsPerCore()) + lc.pkgShift = 8 + } + + if lc.vendor == AMD || lc.vendor == Hygon { + if mef >= 0x8000001e { + eax, ebx, ecx, _ := cpuid(0x8000001e) + if topoLeaf == 0 { + lc.apicID = eax // Extended APIC id, authoritative on AMD. + } + // EBX[15:8]+1 == threads per core, but only on Zen (fam>=0x17) and + // Hygon (fam 0x18); pre-Zen "modules" (fam 0x15/0x16) are not SMT. + if fam, _, _ := familyModel(); lc.smtShift == 0 && fam >= 0x17 { + lc.smtShift = ceilLog2(int((ebx>>8)&0xff) + 1) + } + lc.nodeID = int(ecx & 0xff) + } + } + + lc.caches = parseCaches(lc.vendor, mfi, mef) + for _, cc := range lc.caches { + if cc.c.Level == 3 { + lc.l3Shift = ceilLog2(cc.numShare) + } + } + lc.coreType, lc.model = parseCoreType(lc.vendor, mfi) + return lc +} + +// parseCaches decodes the deterministic cache leaves (Intel 0x04 / AMD +// 0x8000001D). AMD only populates 0x8000001D when TopologyExtensions is set. +func parseCaches(vendor Vendor, mfi, mef uint32) []cpuCache { + var out []cpuCache + switch vendor { + case Intel: + if mfi < 4 { + return nil + } + for i := range uint32(16) { + eax, ebx, ecx, edx := cpuidex(4, i) + if eax&0xf == 0 { + break + } + out = append(out, decodeCache(eax, ebx, ecx, edx)) + } + case AMD, Hygon: + topext := false + if mef >= 0x80000001 { + _, _, ecx, _ := cpuid(0x80000001) + topext = ecx&(1<<22) != 0 + } + if mef >= 0x8000001d && topext { + for i := range uint32(16) { + eax, ebx, ecx, edx := cpuidex(0x8000001d, i) + if eax&0xf == 0 { + break + } + out = append(out, decodeCache(eax, ebx, ecx, edx)) + } + } + } + return out +} + +// decodeCache reads one subleaf of leaf 0x04 / 0x8000001D, which share layout. +func decodeCache(eax, ebx, ecx, edx uint32) cpuCache { + line := int(ebx&0xfff) + 1 + parts := int((ebx>>12)&0x3ff) + 1 + ways := int((ebx>>22)&0x3ff) + 1 + sets := int(ecx) + 1 + return cpuCache{ + c: topology.Cache{ + Level: int((eax >> 5) & 7), + Type: topology.CacheType(eax & 0xf), // 1=Data, 2=Instruction, 3=Unified + Size: line * parts * ways * sets, + LineSize: line, + Ways: ways, + Sets: sets, + Inclusive: edx&2 != 0, + }, + numShare: int((eax>>14)&0xfff) + 1, + } +} + +// parseCoreType classifies the current core from Intel's hybrid leaf 0x1A. +// The leaf reads 0 on non-hybrid Intel parts (so they fall through to +// performance), but all-efficiency parts populate it without the hybrid flag, +// so it is read whenever present rather than gated on that flag. +func parseCoreType(vendor Vendor, mfi uint32) (topology.CoreType, string) { + if vendor == Intel && mfi >= 0x1a { + switch eax, _, _, _ := cpuid(0x1a); eax >> 24 { + case 0x40: + return topology.Performance, "" + case 0x20: + return topology.Efficiency, "" + } + } + if vendor == Intel || vendor == AMD || vendor == Hygon { + return topology.Performance, "" + } + return topology.Unknown, "" +} + +// assembleTopology builds the exact tree from one record per logical CPU. +// Package/group/core membership is derived by masking the x2APIC id, and each +// cache instance is attached to the deepest node that contains every logical +// processor sharing it, so aggregate sizes never double-count. +func assembleTopology(cpus []logicalCPU) *topology.System { + sys := &topology.System{Scanned: true, Online: len(cpus)} + if len(cpus) == 0 { + return sys + } + sys.Vendor = cpus[0].vendor.String() + + groupShiftOf := func(lc logicalCPU) uint8 { + s := lc.l3Shift + if s == 0 { + s = lc.pkgShift // no L3: one group spans the package + } + if s < lc.smtShift { + s = lc.smtShift + } + if s == 0 { + s = 32 + } + return s + } + + type coreData struct { + typ topology.CoreType + model string + threads []topology.Thread + } + cores := map[uint32]*coreData{} + groupOf := map[uint32]uint32{} // coreKey -> groupKey + pkgOf := map[uint32]uint32{} // groupKey -> pkgKey + nodeOf := map[uint32]int{} // groupKey -> NUMA node + pkgSet := map[uint32]bool{} + var pkgKeys, groupKeys, coreKeys []uint32 + + for i, lc := range cpus { + pk := lc.apicID >> lc.pkgShift + gk := lc.apicID >> groupShiftOf(lc) + ck := lc.apicID >> lc.smtShift + cd := cores[ck] + if cd == nil { + cd = &coreData{typ: lc.coreType, model: lc.model} + cores[ck] = cd + coreKeys = append(coreKeys, ck) + groupOf[ck] = gk + } + if _, ok := pkgOf[gk]; !ok { + pkgOf[gk] = pk + groupKeys = append(groupKeys, gk) + } + nodeOf[gk] = lc.nodeID + if !pkgSet[pk] { + pkgSet[pk] = true + pkgKeys = append(pkgKeys, pk) + } + cd.threads = append(cd.threads, topology.Thread{APICID: lc.apicID, ID: i}) + } + + coreCaches, groupCaches, pkgCaches := attachCaches(cpus, groupShiftOf) + + slices.Sort(pkgKeys) + slices.Sort(groupKeys) + slices.Sort(coreKeys) + + coreID, groupID := 0, 0 + for pi, pk := range pkgKeys { + p := topology.Package{ID: pi, Caches: sortCaches(pkgCaches[pk])} + for _, gk := range groupKeys { + if pkgOf[gk] != pk { + continue + } + g := topology.Group{ID: groupID, NUMANode: nodeOf[gk], Caches: sortCaches(groupCaches[gk])} + groupID++ + for _, ck := range coreKeys { + if groupOf[ck] != gk { + continue + } + cd := cores[ck] + slices.SortFunc(cd.threads, func(a, b topology.Thread) int { return cmp.Compare(a.APICID, b.APICID) }) + g.Cores = append(g.Cores, topology.Core{ + ID: coreID, + Type: cd.typ, + Model: cd.model, + Threads: cd.threads, + Caches: sortCaches(coreCaches[ck]), + }) + coreID++ + } + p.Groups = append(p.Groups, g) + } + sys.Packages = append(sys.Packages, p) + } + return sys +} + +// attachCaches groups every reported cache into instances by sharing domain +// and returns them keyed by the core/group/package they belong to. +func attachCaches(cpus []logicalCPU, groupShiftOf func(logicalCPU) uint8) (core, group, pkg map[uint32][]topology.Cache) { + type cacheKey struct { + level int + typ topology.CacheType + dom uint32 + } + type cacheAgg struct { + c topology.Cache + cores map[uint32]bool + groups map[uint32]bool + pkgs map[uint32]bool + shared int + } + insts := map[cacheKey]*cacheAgg{} + for _, lc := range cpus { + pk := lc.apicID >> lc.pkgShift + gk := lc.apicID >> groupShiftOf(lc) + ck := lc.apicID >> lc.smtShift + for _, cc := range lc.caches { + key := cacheKey{cc.c.Level, cc.c.Type, lc.apicID >> ceilLog2(cc.numShare)} + a := insts[key] + if a == nil { + a = &cacheAgg{c: cc.c, cores: map[uint32]bool{}, groups: map[uint32]bool{}, pkgs: map[uint32]bool{}} + insts[key] = a + } + a.cores[ck], a.groups[gk], a.pkgs[pk] = true, true, true + a.shared++ + } + } + core, group, pkg = map[uint32][]topology.Cache{}, map[uint32][]topology.Cache{}, map[uint32][]topology.Cache{} + for _, a := range insts { + c := a.c + c.SharedThreads = a.shared + switch { + case len(a.cores) == 1: + k := onlyKey(a.cores) + core[k] = append(core[k], c) + case len(a.groups) == 1: + k := onlyKey(a.groups) + group[k] = append(group[k], c) + default: + k := onlyKey(a.pkgs) + pkg[k] = append(pkg[k], c) + } + } + return core, group, pkg +} + +// snapshotTopology extrapolates a homogeneous tree from the current core and +// the detected core counts, without pinning to other CPUs. +func snapshotTopology() *topology.System { + if cpuid == nil { + return countsTopology() // Non-x86: no CPUID, build from detected counts. + } + lc := parseLogicalCPU() + tpc := max(threadsPerCore(), 1) + physical := max(physicalCores(), 1) + logical := max(logicalCores(), physical*tpc) + + var l1d, l1i, l2, l3 *topology.Cache + l3Share := 0 + for i := range lc.caches { + cc := &lc.caches[i] + switch { + case cc.c.Level == 1 && cc.c.Type == topology.Instruction: + l1i = &cc.c + case cc.c.Level == 1: + l1d = &cc.c + case cc.c.Level == 2: + l2 = &cc.c + case cc.c.Level == 3: + l3 = &cc.c + l3Share = cc.numShare + } + } + + coresPerGroup := physical + if l3Share > 0 && l3Share/tpc > 0 { + coresPerGroup = l3Share / tpc + } + coresPerGroup = min(coresPerGroup, physical) + groups := 1 + if coresPerGroup > 0 { + groups = (physical + coresPerGroup - 1) / coresPerGroup + } + + sys := &topology.System{Vendor: lc.vendor.String(), Online: logical} + pkg := topology.Package{} + coreID, apic, remaining := 0, uint32(0), physical + for g := range groups { + grp := topology.Group{ID: g, NUMANode: lc.nodeID} + n := min(coresPerGroup, remaining) + for range n { + core := topology.Core{ID: coreID, Type: lc.coreType, Model: lc.model} + for range tpc { + core.Threads = append(core.Threads, topology.Thread{APICID: apic, ID: int(apic)}) + apic++ + } + addCache(&core.Caches, l1d, tpc) + addCache(&core.Caches, l1i, tpc) + addCache(&core.Caches, l2, tpc) + grp.Cores = append(grp.Cores, core) + coreID++ + } + addCache(&grp.Caches, l3, n*tpc) + remaining -= n + pkg.Groups = append(pkg.Groups, grp) + } + sys.Packages = []topology.Package{pkg} + return sys +} + +func addCache(dst *[]topology.Cache, c *topology.Cache, shared int) { + if c == nil || c.Size == 0 { + return + } + cc := *c + cc.SharedThreads = shared + *dst = append(*dst, cc) +} + +// countsTopology builds a minimal tree from the already-detected counts and +// cache sizes, used where CPUID is not available (non-x86, or noasm builds). +func countsTopology() *topology.System { + tpc := max(CPU.ThreadsPerCore, 1) + physical := CPU.PhysicalCores + if physical < 1 { + physical = max(1, CPU.LogicalCores/tpc) + } + sys := &topology.System{Vendor: CPU.VendorString, Online: CPU.LogicalCores} + var grp topology.Group + id := 0 + for c := range physical { + core := topology.Core{ID: c, Type: topology.Performance} + for range tpc { + core.Threads = append(core.Threads, topology.Thread{ID: id}) + id++ + } + addCacheVal(&core.Caches, 1, topology.Data, CPU.Cache.L1D, tpc) + addCacheVal(&core.Caches, 1, topology.Instruction, CPU.Cache.L1I, tpc) + addCacheVal(&core.Caches, 2, topology.Unified, CPU.Cache.L2, tpc) + grp.Cores = append(grp.Cores, core) + } + addCacheVal(&grp.Caches, 3, topology.Unified, CPU.Cache.L3, physical*tpc) + sys.Packages = []topology.Package{{Groups: []topology.Group{grp}}} + return sys +} + +func addCacheVal(dst *[]topology.Cache, level int, t topology.CacheType, size, shared int) { + if size <= 0 { + return + } + *dst = append(*dst, topology.Cache{Level: level, Type: t, Size: size, SharedThreads: shared}) +} + +func sortCaches(cs []topology.Cache) []topology.Cache { + slices.SortFunc(cs, func(a, b topology.Cache) int { + if a.Level != b.Level { + return cmp.Compare(a.Level, b.Level) + } + return cmp.Compare(a.Type, b.Type) + }) + return cs +} + +func onlyKey(m map[uint32]bool) uint32 { + for k := range m { + return k + } + return 0 +} + +// ceilLog2 returns the smallest s such that 1<= n. +func ceilLog2(n int) uint8 { + if n <= 1 { + return 0 + } + return uint8(bits.Len(uint(n - 1))) +} diff --git a/vendor/github.com/klauspost/cpuid/v2/topology/topology.go b/vendor/github.com/klauspost/cpuid/v2/topology/topology.go new file mode 100644 index 000000000..894d20b85 --- /dev/null +++ b/vendor/github.com/klauspost/cpuid/v2/topology/topology.go @@ -0,0 +1,389 @@ +// Copyright (c) 2026 Klaus Post, released under MIT License. See LICENSE file. + +// Package topology describes the layout of a system's CPUs as a fixed +// hierarchy: System → Package → Group → Core → Thread. +// +// A Package is a socket (a physical "CPU"). A Group is a set of cores that +// share a last-level cache — an AMD CCX/CCD or an Intel LLC tile; there is +// always at least one, so a monolithic chip has a single Group holding the +// whole L3. A Core carries its type (performance/efficiency/…), its shared +// per-core caches and its logical Threads. +// +// Caches are attached to the level that owns them: L1/L2 on a Core, the +// shared L3 on a Group, a package-wide last-level cache on a Package. Because +// every instance is stored exactly once, the TotalCache aggregate never +// double-counts: System.TotalCache(3, Unified) is the combined L3 across all +// groups (e.g. all CCDs). +// +// The package holds types and queries only; it is filled in by the cpuid +// package and has no dependencies of its own. +package topology + +import ( + "fmt" + "strings" +) + +// CacheType identifies what a cache stores. The values match the type field +// of CPUID leaves 0x04 / 0x8000001D. +type CacheType uint8 + +const ( + Data CacheType = iota + 1 // Data cache + Instruction // Instruction cache + Unified // Unified cache (holds both) +) + +func (t CacheType) String() string { + switch t { + case Data: + return "Data" + case Instruction: + return "Instruction" + case Unified: + return "Unified" + } + return "Unknown" +} + +// MarshalText renders the cache type as its name, so it serializes as a string +// in JSON and other text encodings rather than a number. +func (t CacheType) MarshalText() ([]byte, error) { return []byte(t.String()), nil } + +// CoreType is the microarchitectural class of a core. On heterogeneous +// ("hybrid") CPUs this distinguishes performance from efficiency cores. +type CoreType uint8 + +const ( + Unknown CoreType = iota // Type could not be determined + Performance // Intel P-core (leaf 0x1A == 0x40), AMD classic Zen core + Efficiency // Intel E-core (leaf 0x1A == 0x20) + LPEfficiency // Intel low-power E-core on the SoC tile + Dense // AMD dense core (Zen 4c / 5c) +) + +func (t CoreType) String() string { + switch t { + case Performance: + return "Performance" + case Efficiency: + return "Efficiency" + case LPEfficiency: + return "LP-Efficiency" + case Dense: + return "Dense" + } + return "Unknown" +} + +// MarshalText renders the core type as its name for JSON and other text +// encodings. +func (t CoreType) MarshalText() ([]byte, error) { return []byte(t.String()), nil } + +// Cache describes a single cache instance. +type Cache struct { + Level int // 1, 2, 3, … + Type CacheType // Data, Instruction or Unified + Size int // Size in bytes of this instance + LineSize int // Line size in bytes + Ways int // Associativity + Sets int // Number of sets + SharedThreads int // Logical processors that share this instance + Inclusive bool // Inclusive of lower cache levels +} + +// Thread is a single logical processor. +type Thread struct { + APICID uint32 // (x2)APIC id + ID int // OS logical CPU number if known from a scan, else the enumeration index +} + +// Core is a single physical core and the threads it runs. +type Core struct { + ID int + Type CoreType + Model string // Microarchitecture label if known, e.g. "Golden Cove" + Threads []Thread // More than one indicates SMT / hyper-threading + Caches []Cache // Caches private to this core, typically L1 and L2 +} + +// NumThreads returns the number of logical processors on the core. +func (c *Core) NumThreads() int { return len(c.Threads) } + +// TotalCache returns the size in bytes of the core-private caches of the +// given level and type. +func (c *Core) TotalCache(level int, t CacheType) int { return sumCaches(c.Caches, level, t) } + +// Group is a set of cores sharing a last-level cache — an AMD CCX/CCD or an +// Intel LLC tile. There is always at least one per package. +type Group struct { + ID int + NUMANode int // AMD node id (leaf 0x8000001E ECX); 0 when unknown or single-node + Cores []Core // Cores in the group + Caches []Cache // Caches shared by the whole group, typically L3 +} + +// NumCores returns the number of cores in the group. +func (g *Group) NumCores() int { return len(g.Cores) } + +// NumThreads returns the number of logical processors below the group. +func (g *Group) NumThreads() int { return countThreads(g.Cores) } + +// CoresByType returns a count of cores per CoreType within the group. +func (g *Group) CoresByType() map[CoreType]int { return coresByType(g.Cores) } + +// TotalCache sums the caches of the given level and type at and below the +// group, counting each instance once. +func (g *Group) TotalCache(level int, t CacheType) int { + return sumCaches(g.Caches, level, t) + coresCache(g.Cores, level, t) +} + +// Package is a socket / physical CPU. +type Package struct { + ID int + Groups []Group + Caches []Cache // Package-wide caches, if any +} + +// NumCores returns the number of cores in the package. +func (p *Package) NumCores() int { + n := 0 + for i := range p.Groups { + n += len(p.Groups[i].Cores) + } + return n +} + +// NumThreads returns the number of logical processors in the package. +func (p *Package) NumThreads() int { + n := 0 + for i := range p.Groups { + n += p.Groups[i].NumThreads() + } + return n +} + +// CoresByType returns a count of cores per CoreType within the package. +func (p *Package) CoresByType() map[CoreType]int { + m := map[CoreType]int{} + for i := range p.Groups { + mergeCounts(m, p.Groups[i].Cores) + } + return m +} + +// Cores returns every core in the package. +func (p *Package) Cores() []Core { + var out []Core + for i := range p.Groups { + out = append(out, p.Groups[i].Cores...) + } + return out +} + +// TotalCache sums the caches of the given level and type at and below the +// package, counting each instance once. +func (p *Package) TotalCache(level int, t CacheType) int { + n := sumCaches(p.Caches, level, t) + for i := range p.Groups { + n += p.Groups[i].TotalCache(level, t) + } + return n +} + +// System is the root of the topology: the whole machine. +type System struct { + Vendor string // CPU vendor string + Scanned bool // true if built from a per-core scan, false if extrapolated from one core + Online int // Logical processors observed + Packages []Package // Physical packages / sockets +} + +// NumPackages returns the number of packages (sockets). +func (s *System) NumPackages() int { return len(s.Packages) } + +// NumCores returns the total number of physical cores in the system. +func (s *System) NumCores() int { + n := 0 + for i := range s.Packages { + n += s.Packages[i].NumCores() + } + return n +} + +// NumThreads returns the total number of logical processors in the system. +func (s *System) NumThreads() int { + n := 0 + for i := range s.Packages { + n += s.Packages[i].NumThreads() + } + return n +} + +// CoresByType returns a count of cores per CoreType across the system. +func (s *System) CoresByType() map[CoreType]int { + m := map[CoreType]int{} + for i := range s.Packages { + for j := range s.Packages[i].Groups { + mergeCounts(m, s.Packages[i].Groups[j].Cores) + } + } + return m +} + +// Cores returns every core in the system. +func (s *System) Cores() []Core { + var out []Core + for i := range s.Packages { + out = append(out, s.Packages[i].Cores()...) + } + return out +} + +// TotalCache sums the caches of the given level and type across the whole +// system, counting each instance once. For example TotalCache(3, Unified) +// returns the combined L3 across all groups. +func (s *System) TotalCache(level int, t CacheType) int { + n := 0 + for i := range s.Packages { + n += s.Packages[i].TotalCache(level, t) + } + return n +} + +func sumCaches(cs []Cache, level int, t CacheType) int { + n := 0 + for _, c := range cs { + if c.Level == level && c.Type == t { + n += c.Size + } + } + return n +} + +func coresCache(cs []Core, level int, t CacheType) int { + n := 0 + for i := range cs { + n += sumCaches(cs[i].Caches, level, t) + } + return n +} + +func countThreads(cs []Core) int { + n := 0 + for i := range cs { + n += len(cs[i].Threads) + } + return n +} + +func coresByType(cs []Core) map[CoreType]int { + m := map[CoreType]int{} + mergeCounts(m, cs) + return m +} + +func mergeCounts(m map[CoreType]int, cs []Core) { + for i := range cs { + m[cs[i].Type]++ + } +} + +// String renders the topology as an indented tree, followed by a summary. +func (s *System) String() string { + var b strings.Builder + kind := "extrapolated from one core" + if s.Scanned { + kind = "scanned" + } + fmt.Fprintf(&b, "System: %s (%s) — %d package(s), %d core(s), %d thread(s)\n", + s.Vendor, kind, s.NumPackages(), s.NumCores(), s.NumThreads()) + for pi := range s.Packages { + p := &s.Packages[pi] + fmt.Fprintf(&b, " Package #%d%s\n", p.ID, cacheSuffix(p.Caches)) + for gi := range p.Groups { + g := &p.Groups[gi] + numa := "" + if g.NUMANode != 0 { + numa = fmt.Sprintf(" NUMA#%d", g.NUMANode) + } + fmt.Fprintf(&b, " Group #%d%s%s\n", g.ID, numa, cacheSuffix(g.Caches)) + for ci := range g.Cores { + c := &g.Cores[ci] + model := "" + if c.Model != "" { + model = " " + c.Model + } + fmt.Fprintf(&b, " Core #%d (%s%s) threads:%s%s\n", + c.ID, c.Type, model, threadList(c.Threads), cacheSuffix(c.Caches)) + } + } + } + if types := s.CoresByType(); len(types) > 1 || !hasOnly(types, Performance) { + b.WriteString(" Cores by type:") + for _, t := range []CoreType{Performance, Efficiency, LPEfficiency, Dense, Unknown} { + if n := types[t]; n > 0 { + fmt.Fprintf(&b, " %s=%d", t, n) + } + } + b.WriteByte('\n') + } + fmt.Fprintf(&b, " Total cache: L1D %s, L1I %s, L2 %s, L3 %s\n", + humanBytes(s.TotalCache(1, Data)), humanBytes(s.TotalCache(1, Instruction)), + humanBytes(s.TotalCache(2, Unified)), humanBytes(s.TotalCache(3, Unified))) + return b.String() +} + +func hasOnly(m map[CoreType]int, t CoreType) bool { + for k := range m { + if k != t { + return false + } + } + return true +} + +func cacheSuffix(cs []Cache) string { + if len(cs) == 0 { + return "" + } + parts := make([]string, 0, len(cs)) + for _, c := range cs { + parts = append(parts, fmt.Sprintf("L%d%s %s", c.Level, cacheShort(c.Type), humanBytes(c.Size))) + } + return " [" + strings.Join(parts, " ") + "]" +} + +func cacheShort(t CacheType) string { + switch t { + case Data: + return "d" + case Instruction: + return "i" + } + return "" +} + +func threadList(ts []Thread) string { + var b strings.Builder + for i, t := range ts { + if i > 0 { + b.WriteByte(',') + } + fmt.Fprintf(&b, " %d", t.ID) + } + return b.String() +} + +func humanBytes(b int) string { + switch { + case b <= 0: + return "0" + case b%(1<<20) == 0: + return fmt.Sprintf("%dMB", b>>20) + case b%(1<<10) == 0: + return fmt.Sprintf("%dKB", b>>10) + default: + return fmt.Sprintf("%dB", b) + } +} diff --git a/vendor/github.com/klauspost/cpuid/v2/topology_scan.go b/vendor/github.com/klauspost/cpuid/v2/topology_scan.go new file mode 100644 index 000000000..4af6f2ad0 --- /dev/null +++ b/vendor/github.com/klauspost/cpuid/v2/topology_scan.go @@ -0,0 +1,34 @@ +// Copyright (c) 2026 Klaus Post, released under MIT License. See LICENSE file. + +package cpuid + +import ( + "errors" + + "github.com/klauspost/cpuid/v2/topology" +) + +// ErrTopologyScanUnavailable is returned by ScanTopology when a per-core scan +// is not possible on the current platform, or CPU affinity could not be set. +// The returned topology is then the extrapolated snapshot from CPU.Topology. +var ErrTopologyScanUnavailable = errors.New("cpuid: per-core topology scan unavailable; returning extrapolated snapshot") + +// ScanTopology returns the exact CPU topology by reading CPUID on every online +// logical processor. +// +// To sample each processor it locks the calling goroutine to an OS thread and +// pins that thread to each CPU in turn, so it has transient scheduling side +// effects. Call it explicitly when you need a precise tree (real +// efficiency/performance core mapping, CCD membership); it is not run +// automatically. +// +// It is supported on linux/amd64 and windows/amd64. On any other platform, or +// if affinity cannot be set (e.g. a restrictive cgroup cpuset), it returns +// CPU.Topology() together with ErrTopologyScanUnavailable. +func ScanTopology() (*topology.System, error) { + cpus, err := scanLogicalCPUs() + if err != nil { + return CPU.Topology(), err + } + return assembleTopology(cpus), nil +} diff --git a/vendor/github.com/klauspost/cpuid/v2/topology_scan_linux_amd64.go b/vendor/github.com/klauspost/cpuid/v2/topology_scan_linux_amd64.go new file mode 100644 index 000000000..9e45365a9 --- /dev/null +++ b/vendor/github.com/klauspost/cpuid/v2/topology_scan_linux_amd64.go @@ -0,0 +1,43 @@ +// Copyright (c) 2026 Klaus Post, released under MIT License. See LICENSE file. + +//go:build linux && amd64 && !noasm && !appengine && !gccgo + +package cpuid + +import ( + "runtime" + + "golang.org/x/sys/unix" +) + +// scanLogicalCPUs samples CPUID on every CPU in the calling thread's affinity +// mask by pinning the thread to each in turn. sched_setaffinity migrates the +// thread synchronously when its current CPU leaves the mask, so CPUID reflects +// the intended processor once the call returns. +func scanLogicalCPUs() ([]logicalCPU, error) { + var orig unix.CPUSet + if err := unix.SchedGetaffinity(0, &orig); err != nil { + return nil, ErrTopologyScanUnavailable + } + + runtime.LockOSThread() + defer runtime.UnlockOSThread() + defer unix.SchedSetaffinity(0, &orig) + + var cpus []logicalCPU + for i := range len(orig) * 64 { + if !orig.IsSet(i) { + continue + } + var set unix.CPUSet + set.Set(i) + if unix.SchedSetaffinity(0, &set) != nil { + continue + } + cpus = append(cpus, parseLogicalCPU()) + } + if len(cpus) == 0 { + return nil, ErrTopologyScanUnavailable + } + return cpus, nil +} diff --git a/vendor/github.com/klauspost/cpuid/v2/topology_scan_stub.go b/vendor/github.com/klauspost/cpuid/v2/topology_scan_stub.go new file mode 100644 index 000000000..31c742462 --- /dev/null +++ b/vendor/github.com/klauspost/cpuid/v2/topology_scan_stub.go @@ -0,0 +1,11 @@ +// Copyright (c) 2026 Klaus Post, released under MIT License. See LICENSE file. + +//go:build !amd64 || noasm || appengine || gccgo || (!linux && !windows) + +package cpuid + +// scanLogicalCPUs is unavailable on this platform; ScanTopology falls back to +// the extrapolated snapshot. +func scanLogicalCPUs() ([]logicalCPU, error) { + return nil, ErrTopologyScanUnavailable +} diff --git a/vendor/github.com/klauspost/cpuid/v2/topology_scan_windows_amd64.go b/vendor/github.com/klauspost/cpuid/v2/topology_scan_windows_amd64.go new file mode 100644 index 000000000..9b79c1c10 --- /dev/null +++ b/vendor/github.com/klauspost/cpuid/v2/topology_scan_windows_amd64.go @@ -0,0 +1,75 @@ +// Copyright (c) 2026 Klaus Post, released under MIT License. See LICENSE file. + +//go:build windows && amd64 && !noasm && !appengine && !gccgo + +package cpuid + +import ( + "runtime" + "unsafe" + + "golang.org/x/sys/windows" +) + +var ( + kernel32 = windows.NewLazySystemDLL("kernel32.dll") + procGetCurrentThread = kernel32.NewProc("GetCurrentThread") + procGetCurrentProcess = kernel32.NewProc("GetCurrentProcess") + procGetProcessAffinityMask = kernel32.NewProc("GetProcessAffinityMask") + procSetThreadAffinityMask = kernel32.NewProc("SetThreadAffinityMask") + procGetCurrentProcessorNumber = kernel32.NewProc("GetCurrentProcessorNumber") + procGetActiveProcessorGroupCnt = kernel32.NewProc("GetActiveProcessorGroupCount") +) + +// scanLogicalCPUs samples CPUID on every CPU in the process affinity mask by +// pinning the current thread to each in turn. It covers a single processor +// group (up to 64 logical CPUs); larger systems are not fully enumerated. +func scanLogicalCPUs() ([]logicalCPU, error) { + // A single process affinity mask only covers one processor group (<=64 + // CPUs). Rather than record a partial tree on a machine with more than one + // group, bail out and let ScanTopology fall back to the snapshot, whose + // counts come from the (group-aware) OS totals. + if n, _, _ := procGetActiveProcessorGroupCnt.Call(); n > 1 { + return nil, ErrTopologyScanUnavailable + } + + proc, _, _ := procGetCurrentProcess.Call() + var procMask, sysMask uintptr + if ret, _, _ := procGetProcessAffinityMask.Call(proc, uintptr(unsafe.Pointer(&procMask)), uintptr(unsafe.Pointer(&sysMask))); ret == 0 || procMask == 0 { + return nil, ErrTopologyScanUnavailable + } + + runtime.LockOSThread() + defer runtime.UnlockOSThread() + th, _, _ := procGetCurrentThread.Call() + defer procSetThreadAffinityMask.Call(th, procMask) + + var cpus []logicalCPU + for i := range 64 { + bit := uintptr(1) << i + if procMask&bit == 0 { + continue + } + if prev, _, _ := procSetThreadAffinityMask.Call(th, bit); prev == 0 { + continue + } + // SetThreadAffinityMask may defer migration; wait until we are on CPU i. + // If it never lands there, skip it rather than record another CPU's data. + migrated := false + for range 10000 { + if cur, _, _ := procGetCurrentProcessorNumber.Call(); uint32(cur) == uint32(i) { + migrated = true + break + } + runtime.Gosched() + } + if !migrated { + continue + } + cpus = append(cpus, parseLogicalCPU()) + } + if len(cpus) == 0 { + return nil, ErrTopologyScanUnavailable + } + return cpus, nil +} diff --git a/vendor/github.com/quic-go/quic-go/README.md b/vendor/github.com/quic-go/quic-go/README.md index c2cf5e518..d8dda3125 100644 --- a/vendor/github.com/quic-go/quic-go/README.md +++ b/vendor/github.com/quic-go/quic-go/README.md @@ -8,7 +8,7 @@ [![Documentation](https://img.shields.io/badge/docs-quic--go.net-red?style=flat)](https://quic-go.net/docs/) [![PkgGoDev](https://pkg.go.dev/badge/github.com/quic-go/quic-go)](https://pkg.go.dev/github.com/quic-go/quic-go) [![Code Coverage](https://img.shields.io/codecov/c/github/quic-go/quic-go/master.svg?style=flat-square)](https://codecov.io/gh/quic-go/quic-go/) -[![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/quic-go.svg)](https://issues.oss-fuzz.com/issues?q=quic-go) +[![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/quic-go.svg)](https://introspector.oss-fuzz.com/project-profile?project=quic-go) quic-go is an implementation of the QUIC protocol ([RFC 9000](https://datatracker.ietf.org/doc/html/rfc9000), [RFC 9001](https://datatracker.ietf.org/doc/html/rfc9001), [RFC 9002](https://datatracker.ietf.org/doc/html/rfc9002)) in Go. diff --git a/vendor/github.com/quic-go/quic-go/config.go b/vendor/github.com/quic-go/quic-go/config.go index 74c2054e4..f107ac489 100644 --- a/vendor/github.com/quic-go/quic-go/config.go +++ b/vendor/github.com/quic-go/quic-go/config.go @@ -22,6 +22,13 @@ func (c *Config) maxRetryTokenAge() time.Duration { return c.handshakeTimeout() } +func (c *Config) initialPacketSize() protocol.ByteCount { + if c.InitialPacketSize == 0 { + return protocol.InitialPacketSize + } + return protocol.ByteCount(c.InitialPacketSize) +} + func validateConfig(config *Config) error { if config == nil { return nil @@ -56,6 +63,7 @@ func validateConfig(config *Config) error { // populateConfig populates fields in the quic.Config with their default values, if none are set // it may be called with nil +// InitialPacketSize keeps zero to distinguish the default from an explicit packet-size floor. func populateConfig(config *Config) *Config { if config == nil { config = &Config{} @@ -100,11 +108,6 @@ func populateConfig(config *Config) *Config { } else if maxIncomingUniStreams < 0 { maxIncomingUniStreams = 0 } - initialPacketSize := config.InitialPacketSize - if initialPacketSize == 0 { - initialPacketSize = protocol.InitialPacketSize - } - return &Config{ GetConfigForClient: config.GetConfigForClient, Versions: versions, @@ -120,7 +123,7 @@ func populateConfig(config *Config) *Config { MaxIncomingUniStreams: maxIncomingUniStreams, TokenStore: config.TokenStore, EnableDatagrams: config.EnableDatagrams, - InitialPacketSize: initialPacketSize, + InitialPacketSize: config.InitialPacketSize, DisablePathMTUDiscovery: config.DisablePathMTUDiscovery, EnableStreamResetPartialDelivery: config.EnableStreamResetPartialDelivery, Allow0RTT: config.Allow0RTT, diff --git a/vendor/github.com/quic-go/quic-go/conn_id_manager.go b/vendor/github.com/quic-go/quic-go/conn_id_manager.go index 8d08e07c6..b75167905 100644 --- a/vendor/github.com/quic-go/quic-go/conn_id_manager.go +++ b/vendor/github.com/quic-go/quic-go/conn_id_manager.go @@ -186,7 +186,7 @@ func (h *connIDManager) updateConnectionID() { h.activeConnectionID = front.ConnectionID h.activeStatelessResetToken = &front.StatelessResetToken h.packetsSinceLastChange = 0 - h.packetsPerConnectionID = protocol.PacketsPerConnectionID/2 + uint32(h.rand.Int31n(protocol.PacketsPerConnectionID)) + h.packetsPerConnectionID = protocol.PacketsPerConnectionID/2 + h.rand.Uint32N(protocol.PacketsPerConnectionID) h.addStatelessResetToken(*h.activeStatelessResetToken) } diff --git a/vendor/github.com/quic-go/quic-go/connection.go b/vendor/github.com/quic-go/quic-go/connection.go index a1f327bcd..52dcd212d 100644 --- a/vendor/github.com/quic-go/quic-go/connection.go +++ b/vendor/github.com/quic-go/quic-go/connection.go @@ -2,6 +2,7 @@ package quic import ( "bytes" + "cmp" "context" "crypto/tls" "errors" @@ -162,7 +163,7 @@ type Conn struct { unpacker unpacker frameParser wire.FrameParser packer packer - mtuDiscoverer *mtuFinder // initialized when the transport parameters are received + mtuDiscoverer *mtuFinder // initialized after the first write at the configured Initial size maxPayloadSizeEstimate atomic.Uint32 @@ -311,7 +312,7 @@ var newConnection = func( s.rttStats.SetInitialRTT(rtt) s.sentPacketHandler = ackhandler.NewSentPacketHandler( 0, - protocol.ByteCount(s.config.InitialPacketSize), + s.config.initialPacketSize(), s.rttStats, &s.connStats, clientAddressValidated, @@ -321,7 +322,7 @@ var newConnection = func( s.qlogger, s.logger, ) - s.maxPayloadSizeEstimate.Store(uint32(estimateMaxPayloadSize(protocol.ByteCount(s.config.InitialPacketSize)))) + s.maxPayloadSizeEstimate.Store(uint32(estimateMaxPayloadSize(s.config.initialPacketSize()))) statelessResetToken := statelessResetter.GetStatelessResetToken(srcConnID) params := &wire.TransportParameters{ InitialMaxStreamDataBidiLocal: protocol.ByteCount(s.config.InitialStreamReceiveWindow), @@ -331,7 +332,7 @@ var newConnection = func( MaxIdleTimeout: s.config.MaxIdleTimeout, MaxBidiStreamNum: protocol.StreamNum(s.config.MaxIncomingStreams), MaxUniStreamNum: protocol.StreamNum(s.config.MaxIncomingUniStreams), - MaxAckDelay: protocol.MaxAckDelayInclGranularity, + MaxAckDelay: ackhandler.MaxAckDelay + protocol.TimerGranularity, AckDelayExponent: protocol.AckDelayExponent, MaxUDPPayloadSize: protocol.MaxPacketBufferSize, StatelessResetToken: &statelessResetToken, @@ -367,7 +368,7 @@ var newConnection = func( s.version, ) s.cryptoStreamHandler = cs - s.packer = newPacketPacker(srcConnID, s.connIDManager.Get, s.initialStream, s.handshakeStream, s.sentPacketHandler, s.retransmissionQueue, cs, s.framer, &s.receivedPacketHandler, s.datagramQueue, s.perspective) + s.packer = newPacketPacker(srcConnID, s.connIDManager.Get, s.initialStream, s.handshakeStream, s.sentPacketHandler, s.retransmissionQueue, cs, s.framer, &s.receivedPacketHandler, s.datagramQueue, s.perspective, s.qlogger) s.unpacker = newPacketUnpacker(cs, s.srcConnIDLen) s.cryptoStreamManager = newCryptoStreamManager(s.initialStream, s.handshakeStream, s.oneRTTStream) return &wrappedConn{Conn: s} @@ -438,9 +439,21 @@ var newClientConnection = func( ) s.ctx, s.ctxCancel = context.WithCancelCause(ctx) s.preSetup() + if len(tlsConf.ServerName) > 0 { + s.tokenStoreKey = tlsConf.ServerName + } else { + s.tokenStoreKey = conn.RemoteAddr().String() + } + var token *ClientToken + if s.config.TokenStore != nil { + token = s.config.TokenStore.Pop(s.tokenStoreKey) + if token != nil { + s.rttStats.SetInitialRTT(token.rtt) + } + } s.sentPacketHandler = ackhandler.NewSentPacketHandler( initialPacketNumber, - protocol.ByteCount(s.config.InitialPacketSize), + s.config.initialPacketSize(), s.rttStats, &s.connStats, false, // has no effect @@ -450,7 +463,7 @@ var newClientConnection = func( s.qlogger, s.logger, ) - s.maxPayloadSizeEstimate.Store(uint32(estimateMaxPayloadSize(protocol.ByteCount(s.config.InitialPacketSize)))) + s.maxPayloadSizeEstimate.Store(uint32(estimateMaxPayloadSize(s.config.initialPacketSize()))) oneRTTStream := newCryptoStream() params := &wire.TransportParameters{ InitialMaxStreamDataBidiRemote: protocol.ByteCount(s.config.InitialStreamReceiveWindow), @@ -460,7 +473,7 @@ var newClientConnection = func( MaxIdleTimeout: s.config.MaxIdleTimeout, MaxBidiStreamNum: protocol.StreamNum(s.config.MaxIncomingStreams), MaxUniStreamNum: protocol.StreamNum(s.config.MaxIncomingUniStreams), - MaxAckDelay: protocol.MaxAckDelayInclGranularity, + MaxAckDelay: ackhandler.MaxAckDelay + protocol.TimerGranularity, MaxUDPPayloadSize: protocol.MaxPacketBufferSize, AckDelayExponent: protocol.AckDelayExponent, // For interoperability with quic-go versions before May 2023, this value must be set to a value @@ -493,17 +506,9 @@ var newClientConnection = func( s.cryptoStreamHandler = cs s.cryptoStreamManager = newCryptoStreamManager(s.initialStream, s.handshakeStream, oneRTTStream) s.unpacker = newPacketUnpacker(cs, s.srcConnIDLen) - s.packer = newPacketPacker(srcConnID, s.connIDManager.Get, s.initialStream, s.handshakeStream, s.sentPacketHandler, s.retransmissionQueue, cs, s.framer, &s.receivedPacketHandler, s.datagramQueue, s.perspective) - if len(tlsConf.ServerName) > 0 { - s.tokenStoreKey = tlsConf.ServerName - } else { - s.tokenStoreKey = conn.RemoteAddr().String() - } - if s.config.TokenStore != nil { - if token := s.config.TokenStore.Pop(s.tokenStoreKey); token != nil { - s.packer.SetToken(token.data) - s.rttStats.SetInitialRTT(token.rtt) - } + s.packer = newPacketPacker(srcConnID, s.connIDManager.Get, s.initialStream, s.handshakeStream, s.sentPacketHandler, s.retransmissionQueue, cs, s.framer, &s.receivedPacketHandler, s.datagramQueue, s.perspective, s.qlogger) + if token != nil { + s.packer.SetToken(token.data) } return &wrappedConn{Conn: s} } @@ -555,7 +560,7 @@ func (c *Conn) preSetup() { c.receivedPacketHandler = *ackhandler.NewReceivedPacketHandler(c.logger) - c.datagramQueue = newDatagramQueue(c.scheduleSending, c.logger) + c.datagramQueue = newDatagramQueue(c.scheduleSending, c.logger, c.qlogger) c.connState.Version = c.version } @@ -801,6 +806,11 @@ type ConnectionStats struct { // variation. See https://www.rfc-editor.org/rfc/rfc9002#section-5.3 MeanDeviation time.Duration + // CongestionWindow is the local sender's congestion window on the active + // network path, in bytes. It limits bytes in flight and includes QUIC + // packet overhead, excluding UDP and IP headers. + CongestionWindow uint64 + // BytesSent is the number of bytes sent on the underlying connection, // including retransmissions. Does not include UDP or any other outer // framing. @@ -826,6 +836,8 @@ type ConnectionStats struct { PacketsLost uint64 } +// ConnectionStats returns statistics about the connection. +// It can be called concurrently with other connection operations. func (c *Conn) ConnectionStats() ConnectionStats { return ConnectionStats{ MinRTT: c.rttStats.MinRTT(), @@ -833,6 +845,8 @@ func (c *Conn) ConnectionStats() ConnectionStats { SmoothedRTT: c.rttStats.SmoothedRTT(), MeanDeviation: c.rttStats.MeanDeviation(), + CongestionWindow: c.connStats.CongestionWindow.Load(), + BytesSent: c.connStats.BytesSent.Load(), PacketsSent: c.connStats.PacketsSent.Load(), BytesReceived: c.connStats.BytesReceived.Load(), @@ -911,14 +925,14 @@ func (c *Conn) idleTimeoutStartTime() monotime.Time { } func (c *Conn) switchToNewPath(tr *Transport, now monotime.Time) { - initialPacketSize := protocol.ByteCount(c.config.InitialPacketSize) + initialPacketSize := protocol.ByteCount(cmp.Or(c.config.InitialPacketSize, protocol.MinInitialPacketSize)) c.sentPacketHandler.MigratedPath(now, initialPacketSize) - maxPacketSize := protocol.ByteCount(protocol.MaxPacketBufferSize) - if c.peerParams.MaxUDPPayloadSize > 0 && c.peerParams.MaxUDPPayloadSize < maxPacketSize { - maxPacketSize = c.peerParams.MaxUDPPayloadSize - } - c.mtuDiscoverer.Reset(now, initialPacketSize, maxPacketSize) + c.maxPayloadSizeEstimate.Store(uint32(estimateMaxPayloadSize(initialPacketSize))) + c.mtuDiscoverer.Reset(initialPacketSize, c.maxMTU()) c.conn = newSendConn(tr.conn, c.conn.RemoteAddr(), packetInfo{}, utils.DefaultLogger) // TODO: find a better way + if !c.config.DisablePathMTUDiscovery && c.conn.capabilities().DF { + c.mtuDiscoverer.Start(now) + } c.sendQueue.Close() c.sendQueue = newSendQueue(c.conn) go func() { @@ -961,10 +975,8 @@ func (c *Conn) handleHandshakeComplete(now monotime.Time) error { } if ticket != nil { // may be nil if session tickets are disabled via tls.Config.SessionTicketsDisabled c.oneRTTStream.Write(ticket) - for c.oneRTTStream.HasData() { - if cf := c.oneRTTStream.PopCryptoFrame(protocol.MaxPostHandshakeCryptoFrameSize); cf != nil { - c.queueControlFrame(cf) - } + if cf := c.oneRTTStream.PopCryptoFrame(protocol.MaxByteCount); cf != nil { + c.queueControlFrame(cf) } } token, err := c.tokenGenerator.NewToken(c.conn.RemoteAddr(), c.rttStats.SmoothedRTT()) @@ -1214,7 +1226,7 @@ func (c *Conn) handleShortHeaderPacket( wire.LogShortHeader(c.logger, destConnID, pn, pnLen, keyPhase) } - if c.receivedPacketHandler.IsPotentiallyDuplicate(pn, protocol.Encryption1RTT) { + if c.receivedPacketHandler.IsPotentiallyDuplicate(pn, protocol.PacketNumberSpaceAppData) { c.logger.Debugf("Dropping (potentially) duplicate packet.") if c.qlogger != nil { c.qlogger.RecordEvent(qlog.PacketDropped{ @@ -1288,16 +1300,13 @@ func (c *Conn) handleShortHeaderPacket( return true, nil } c.pathManager.SwitchToPath(p.remoteAddr) - c.sentPacketHandler.MigratedPath(p.rcvTime, protocol.ByteCount(c.config.InitialPacketSize)) - maxPacketSize := protocol.ByteCount(protocol.MaxPacketBufferSize) - if c.peerParams.MaxUDPPayloadSize > 0 && c.peerParams.MaxUDPPayloadSize < maxPacketSize { - maxPacketSize = c.peerParams.MaxUDPPayloadSize - } - c.mtuDiscoverer.Reset( - p.rcvTime, - protocol.ByteCount(c.config.InitialPacketSize), - maxPacketSize, - ) + initialPacketSize := protocol.ByteCount(cmp.Or(c.config.InitialPacketSize, protocol.MinInitialPacketSize)) + c.sentPacketHandler.MigratedPath(p.rcvTime, initialPacketSize) + c.maxPayloadSizeEstimate.Store(uint32(estimateMaxPayloadSize(initialPacketSize))) + c.mtuDiscoverer.Reset(initialPacketSize, c.maxMTU()) + if !c.config.DisablePathMTUDiscovery && c.conn.capabilities().DF { + c.mtuDiscoverer.Start(p.rcvTime) + } c.conn.ChangeRemoteAddr(p.remoteAddr, p.info) return true, nil } @@ -1360,7 +1369,7 @@ func (c *Conn) handleLongHeaderPacket(p receivedPacket, hdr *wire.Header, datagr packet.hdr.Log(c.logger) } - if pn := packet.hdr.PacketNumber; c.receivedPacketHandler.IsPotentiallyDuplicate(pn, packet.encryptionLevel) { + if pn := packet.hdr.PacketNumber; c.receivedPacketHandler.IsPotentiallyDuplicate(pn, packet.encryptionLevel.PacketNumberSpace()) { c.logger.Debugf("Dropping (potentially) duplicate packet.") if c.qlogger != nil { c.qlogger.RecordEvent(qlog.PacketDropped{ @@ -1628,7 +1637,7 @@ func (c *Conn) handleVersionNegotiationPacket(p receivedPacket) error { } c.logger.Infof("Switching to QUIC version %s.", newVersion) - nextPN, _ := c.sentPacketHandler.PeekPacketNumber(protocol.EncryptionInitial) + nextPN, _ := c.sentPacketHandler.PeekPacketNumber(protocol.PacketNumberSpaceInitial) return &errCloseForRecreating{ nextPacketNumber: nextPN, nextVersion: newVersion, @@ -2436,16 +2445,16 @@ func (c *Conn) applyTransportParameters() { // Retire the connection ID. c.connIDManager.AddFromPreferredAddress(params.PreferredAddress.ConnectionID, params.PreferredAddress.StatelessResetToken) } - maxPacketSize := protocol.ByteCount(protocol.MaxPacketBufferSize) - if params.MaxUDPPayloadSize > 0 && params.MaxUDPPayloadSize < maxPacketSize { - maxPacketSize = params.MaxUDPPayloadSize + if c.mtuDiscoverer != nil { + c.mtuDiscoverer = newMTUDiscoverer(c.rttStats, c.mtuDiscoverer.CurrentSize(), c.maxMTU(), c.qlogger) } - c.mtuDiscoverer = newMTUDiscoverer( - c.rttStats, - protocol.ByteCount(c.config.InitialPacketSize), - maxPacketSize, - c.qlogger, - ) +} + +func (c *Conn) maxMTU() protocol.ByteCount { + if c.peerParams == nil || c.peerParams.MaxUDPPayloadSize <= 0 { + return protocol.MaxPacketBufferSize + } + return min(protocol.MaxPacketBufferSize, c.peerParams.MaxUDPPayloadSize) } func (c *Conn) triggerSending(now monotime.Time) error { @@ -2530,10 +2539,6 @@ func (c *Conn) sendPackets(now monotime.Time) error { if offset := c.connFlowController.GetWindowUpdate(now); offset > 0 { c.framer.QueueControlFrame(&wire.MaxDataFrame{MaximumData: offset}) } - if cf := c.cryptoStreamManager.GetPostHandshakeData(protocol.MaxPostHandshakeCryptoFrameSize); cf != nil { - c.queueControlFrame(cf) - } - if !c.handshakeConfirmed { packet, err := c.packer.PackCoalescedPacket(false, c.maxPacketSize(), now, c.version) if err != nil || packet == nil { @@ -2711,7 +2716,7 @@ func (c *Conn) sendProbePacket(sendMode ackhandler.SendMode, now monotime.Time) // or until there are no more packets to queue. var packet *coalescedPacket for packet == nil { - if wasQueued := c.sentPacketHandler.QueueProbePacket(encLevel); !wasQueued { + if wasQueued := c.sentPacketHandler.QueueProbePacket(encLevel.PacketNumberSpace()); !wasQueued { break } var err error @@ -2837,7 +2842,31 @@ func (c *Conn) sendPackedCoalescedPacket(packet *coalescedPacket, ecn protocol.E ) } c.connIDManager.SentPacket() - c.sendQueue.Send(packet.buffer, 0, ecn) + if c.mtuDiscoverer != nil { + c.sendQueue.Send(packet.buffer, 0, ecn) + return nil + } + + // Write directly until we've tried the configured Initial size. The server + // can send smaller ACKs before receiving the full ClientHello. Keep those + // writes here too, so the send queue can't write concurrently with us. + packetSize := packet.buffer.Len() + err := c.conn.Write(packet.buffer.Data, 0, ecn) + packet.buffer.Release() + if err != nil { + if !isSendMsgSizeErr(err) || c.config.InitialPacketSize != 0 { + return err + } + } + initialPacketSize := c.config.initialPacketSize() + if packetSize >= initialPacketSize { + if err != nil { + initialPacketSize = protocol.MinInitialPacketSize + c.maxPayloadSizeEstimate.Store(uint32(estimateMaxPayloadSize(protocol.MinInitialPacketSize))) + c.sentPacketHandler.SetMaxDatagramSize(protocol.MinInitialPacketSize) + } + c.mtuDiscoverer = newMTUDiscoverer(c.rttStats, initialPacketSize, c.maxMTU(), c.qlogger) + } return nil } @@ -2863,20 +2892,13 @@ func (c *Conn) sendConnectionClose(e error) ([]byte, error) { } func (c *Conn) maxPacketSize() protocol.ByteCount { - if c.mtuDiscoverer == nil { - // Use the configured packet size on the client side. - // If the server sends a max_udp_payload_size that's smaller than this size, we can ignore this: - // Apparently the server still processed the (fully padded) Initial packet anyway. - if c.perspective == protocol.PerspectiveClient { - return protocol.ByteCount(c.config.InitialPacketSize) - } - // On the server side, there's no downside to using 1200 bytes until we received the client's transport - // parameters: - // * If the first packet didn't contain the entire ClientHello, all we can do is ACK that packet. We don't - // need a lot of bytes for that. - // * If it did, we will have processed the transport parameters and initialized the MTU discoverer. + if c.perspective == protocol.PerspectiveServer && c.peerParams == nil { + // Use 1200-byte server packets until we've received the client's transport parameters. return protocol.MinInitialPacketSize } + if c.mtuDiscoverer == nil { + return c.config.initialPacketSize() + } return c.mtuDiscoverer.CurrentSize() } diff --git a/vendor/github.com/quic-go/quic-go/crypto_stream_manager.go b/vendor/github.com/quic-go/quic-go/crypto_stream_manager.go index 7f586b84a..ff5ab701d 100644 --- a/vendor/github.com/quic-go/quic-go/crypto_stream_manager.go +++ b/vendor/github.com/quic-go/quic-go/crypto_stream_manager.go @@ -53,13 +53,6 @@ func (m *cryptoStreamManager) GetCryptoData(encLevel protocol.EncryptionLevel) [ } } -func (m *cryptoStreamManager) GetPostHandshakeData(maxSize protocol.ByteCount) *wire.CryptoFrame { - if !m.oneRTTStream.HasData() { - return nil - } - return m.oneRTTStream.PopCryptoFrame(maxSize) -} - func (m *cryptoStreamManager) Finish(encLevel protocol.EncryptionLevel) error { //nolint:exhaustive // The 1-RTT CRYPTO stream is never finished. switch encLevel { diff --git a/vendor/github.com/quic-go/quic-go/datagram_queue.go b/vendor/github.com/quic-go/quic-go/datagram_queue.go index e26285b26..48727f2b3 100644 --- a/vendor/github.com/quic-go/quic-go/datagram_queue.go +++ b/vendor/github.com/quic-go/quic-go/datagram_queue.go @@ -7,6 +7,8 @@ import ( "github.com/quic-go/quic-go/internal/utils" "github.com/quic-go/quic-go/internal/utils/ringbuffer" "github.com/quic-go/quic-go/internal/wire" + "github.com/quic-go/quic-go/qlog" + "github.com/quic-go/quic-go/qlogwriter" ) const ( @@ -28,16 +30,18 @@ type datagramQueue struct { hasData func() - logger utils.Logger + logger utils.Logger + qlogger qlogwriter.Recorder } -func newDatagramQueue(hasData func(), logger utils.Logger) *datagramQueue { +func newDatagramQueue(hasData func(), logger utils.Logger, qlogger qlogwriter.Recorder) *datagramQueue { return &datagramQueue{ hasData: hasData, rcvd: make(chan struct{}, 1), sent: make(chan struct{}, 1), closed: make(chan struct{}), logger: logger, + qlogger: qlogger, } } @@ -48,6 +52,14 @@ func (h *datagramQueue) Add(f *wire.DatagramFrame) error { h.sendMx.Lock() for { + // don't queue frames after the connection is closed + select { + case <-h.closed: + h.sendMx.Unlock() + return h.closeErr + default: + } + if h.sendQueue.Len() < maxDatagramSendQueueLen { h.sendQueue.PushBack(f) h.sendMx.Unlock() @@ -55,10 +67,11 @@ func (h *datagramQueue) Add(f *wire.DatagramFrame) error { return nil } select { - case <-h.sent: // drain the queue so we don't loop immediately + case <-h.sent: // drain any stale notification, so we don't wake up immediately below default: } h.sendMx.Unlock() + // The queue is full. Wait until a frame is dequeued. select { case <-h.closed: return h.closeErr @@ -104,13 +117,26 @@ func (h *datagramQueue) HandleDatagramFrame(f *wire.DatagramFrame) { } } h.rcvMx.Unlock() - if !queued && h.logger.Debug() { - h.logger.Debugf("Discarding received DATAGRAM frame (%d bytes payload)", len(f.Data)) + + if !queued { + if h.logger.Debug() { + h.logger.Debugf("Discarding received DATAGRAM frame (%d bytes payload)", len(f.Data)) + } + if h.qlogger != nil { + h.qlogger.RecordEvent(qlog.DatagramDropped{ + Direction: qlog.DirectionReceiving, + Raw: qlog.RawInfo{Length: len(f.Data)}, + Trigger: "buffer_full", + }) + } } } // Receive gets a received DATAGRAM frame. func (h *datagramQueue) Receive(ctx context.Context) ([]byte, error) { + if err := context.Cause(ctx); err != nil { + return nil, err + } for { h.rcvMx.Lock() if len(h.rcvQueue) > 0 { @@ -126,7 +152,7 @@ func (h *datagramQueue) Receive(ctx context.Context) ([]byte, error) { case <-h.closed: return nil, h.closeErr case <-ctx.Done(): - return nil, ctx.Err() + return nil, context.Cause(ctx) } } } diff --git a/vendor/github.com/quic-go/quic-go/framer.go b/vendor/github.com/quic-go/quic-go/framer.go index 0ce60c8f6..dd26831e1 100644 --- a/vendor/github.com/quic-go/quic-go/framer.go +++ b/vendor/github.com/quic-go/quic-go/framer.go @@ -274,6 +274,16 @@ func (f *framer) appendControlFrames( for len(f.controlFrames) > 0 { frame := f.controlFrames[len(f.controlFrames)-1] + if cf, ok := frame.(*wire.CryptoFrame); ok { + if split, needsSplit := cf.MaybeSplitOffFrame(maxLen-length, v); needsSplit { + if split != nil { + frames = append(frames, ackhandler.Frame{Frame: split}) + length += split.Length(v) + } + // Leave the original frame queued with the remaining data. + break + } + } frameLen := frame.Length(v) if length+frameLen > maxLen { break diff --git a/vendor/github.com/quic-go/quic-go/http3/headers.go b/vendor/github.com/quic-go/quic-go/http3/headers.go index 26bf16852..d1d88f53a 100644 --- a/vendor/github.com/quic-go/quic-go/http3/headers.go +++ b/vendor/github.com/quic-go/quic-go/http3/headers.go @@ -27,6 +27,24 @@ func (e *qpackError) Unwrap() error { return e.err } var errHeaderTooLarge = errors.New("http3: headers too large") +// readHeaderBlock preallocates up to 8 KiB, growing larger buffers as data arrives. +// The caller must check length against the configured header size limit first. +func readHeaderBlock(r io.Reader, length uint64) ([]byte, error) { + const maxInitialBufferSize = 8 << 10 + + b := make([]byte, min(length, maxInitialBufferSize)) + if length <= maxInitialBufferSize { + _, err := io.ReadFull(r, b) + return b, err + } + buf := bytes.NewBuffer(b[:0]) + n, err := io.CopyN(buf, r, int64(length)) + if errors.Is(err, io.EOF) && n > 0 { + err = io.ErrUnexpectedEOF + } + return buf.Bytes(), err +} + type header struct { // Pseudo header fields defined in RFC 9114 Path string @@ -450,8 +468,8 @@ func decodeTrailers(r io.Reader, hf *headersFrame, maxHeaderBytes int, decoder * return nil, fmt.Errorf("http3: HEADERS frame too large: %d bytes (max: %d)", hf.Length, maxHeaderBytes) } - b := make([]byte, hf.Length) - if _, err := io.ReadFull(r, b); err != nil { + b, err := readHeaderBlock(r, hf.Length) + if err != nil { return nil, err } decodeFn := decoder.Decode(b) diff --git a/vendor/github.com/quic-go/quic-go/http3/qlog/header_redactor.go b/vendor/github.com/quic-go/quic-go/http3/qlog/header_redactor.go new file mode 100644 index 000000000..09192ceb1 --- /dev/null +++ b/vendor/github.com/quic-go/quic-go/http3/qlog/header_redactor.go @@ -0,0 +1,75 @@ +package qlog + +import ( + "context" + "net/http" + "strings" + + "github.com/quic-go/quic-go" + "github.com/quic-go/quic-go/qlogwriter" +) + +// RedactHeaders wraps a QUIC connection tracer to redact HTTP/3 header and trailer field values. +// redact receives names canonicalized by [http.CanonicalHeaderKey], except pseudoheader +// names, which are passed unchanged in lowercase (e.g. ":path"). +func RedactHeaders( + tracer func(context.Context, bool, quic.ConnectionID) qlogwriter.Trace, + redact func(name, value string) string, +) func(context.Context, bool, quic.ConnectionID) qlogwriter.Trace { + if tracer == nil || redact == nil { + return tracer + } + return func(ctx context.Context, client bool, id quic.ConnectionID) qlogwriter.Trace { + trace := tracer(ctx, client, id) + if trace == nil { + return nil + } + return &headerRedactingTrace{Trace: trace, redact: redact} + } +} + +type headerRedactingTrace struct { + qlogwriter.Trace + redact func(name, value string) string +} + +var _ qlogwriter.Trace = &headerRedactingTrace{} + +func (t *headerRedactingTrace) AddProducer() qlogwriter.Recorder { + recorder := t.Trace.AddProducer() + if recorder == nil { + return nil + } + return &headerRedactingRecorder{Recorder: recorder, redact: t.redact} +} + +type headerRedactingRecorder struct { + qlogwriter.Recorder + redact func(name, value string) string +} + +var _ qlogwriter.Recorder = &headerRedactingRecorder{} + +func (r *headerRedactingRecorder) RecordEvent(event qlogwriter.Event) { + switch e := event.(type) { + case FrameCreated: + r.redactFrame(e.Frame) + case FrameParsed: + r.redactFrame(e.Frame) + } + r.Recorder.RecordEvent(event) +} + +func (r *headerRedactingRecorder) redactFrame(frame Frame) { + hf, ok := frame.Frame.(HeadersFrame) + if !ok { + return + } + for i, f := range hf.HeaderFields { + name := f.Name + if !strings.HasPrefix(name, ":") { + name = http.CanonicalHeaderKey(name) + } + hf.HeaderFields[i].Value = r.redact(name, f.Value) + } +} diff --git a/vendor/github.com/quic-go/quic-go/http3/server_conn.go b/vendor/github.com/quic-go/quic-go/http3/server_conn.go index 2bb8566b6..ce1e378c3 100644 --- a/vendor/github.com/quic-go/quic-go/http3/server_conn.go +++ b/vendor/github.com/quic-go/quic-go/http3/server_conn.go @@ -134,8 +134,8 @@ func (c *RawServerConn) handleRequestStream(str *stateTrackingStream) { c.rejectWithHeaderFieldsTooLarge(str) return } - headerBlock := make([]byte, hf.Length) - if _, err := io.ReadFull(str, headerBlock); err != nil { + headerBlock, err := readHeaderBlock(str, hf.Length) + if err != nil { maybeQlogInvalidHeadersFrame(qlogger, str.StreamID(), hf.Length) str.CancelRead(quic.StreamErrorCode(ErrCodeRequestIncomplete)) str.CancelWrite(quic.StreamErrorCode(ErrCodeRequestIncomplete)) diff --git a/vendor/github.com/quic-go/quic-go/http3/state_tracking_stream.go b/vendor/github.com/quic-go/quic-go/http3/state_tracking_stream.go index 440e42bac..e38d750fe 100644 --- a/vendor/github.com/quic-go/quic-go/http3/state_tracking_stream.go +++ b/vendor/github.com/quic-go/quic-go/http3/state_tracking_stream.go @@ -25,9 +25,9 @@ type stateTrackingStream struct { hasData chan struct{} queue [][]byte // TODO: use a ring buffer - mx sync.Mutex - sendErr error - recvErr error + mx sync.Mutex + sendStreamDone bool + recvErr error clearer streamClearer } @@ -46,24 +46,22 @@ func newStateTrackingStream(s *quic.Stream, clearer streamClearer, sendDatagram hasData: make(chan struct{}, 1), } - context.AfterFunc(s.Context(), func() { - t.closeSend(context.Cause(s.Context())) - }) + context.AfterFunc(s.Context(), t.closeSend) return t } -func (s *stateTrackingStream) closeSend(e error) { +func (s *stateTrackingStream) closeSend() { s.mx.Lock() defer s.mx.Unlock() // clear the stream the first time both the send // and receive are finished - if s.sendErr == nil { + if !s.sendStreamDone { if s.recvErr != nil { s.clearer.clearStream(s.StreamID()) } - s.sendErr = e + s.sendStreamDone = true } } @@ -74,7 +72,7 @@ func (s *stateTrackingStream) closeReceive(e error) { // clear the stream the first time both the send // and receive are finished if s.recvErr == nil { - if s.sendErr != nil { + if s.sendStreamDone { s.clearer.clearStream(s.StreamID()) } s.recvErr = e @@ -83,19 +81,19 @@ func (s *stateTrackingStream) closeReceive(e error) { } func (s *stateTrackingStream) Close() error { - s.closeSend(errors.New("write on closed stream")) + s.closeSend() return s.Stream.Close() } func (s *stateTrackingStream) CancelWrite(e quic.StreamErrorCode) { - s.closeSend(&quic.StreamError{StreamID: s.StreamID(), ErrorCode: e}) + s.closeSend() s.Stream.CancelWrite(e) } func (s *stateTrackingStream) Write(b []byte) (int, error) { n, err := s.Stream.Write(b) if err != nil && !errors.Is(err, os.ErrDeadlineExceeded) { - s.closeSend(err) + s.closeSend() } return n, err } @@ -103,7 +101,7 @@ func (s *stateTrackingStream) Write(b []byte) (int, error) { func (s *stateTrackingStream) TryWriteAll(b []byte) error { err := s.Stream.TryWriteAll(b) if err != nil && !errors.Is(err, quic.ErrWouldBlock) { - s.closeSend(err) + s.closeSend() } return err } @@ -122,13 +120,9 @@ func (s *stateTrackingStream) Read(b []byte) (int, error) { } func (s *stateTrackingStream) SendDatagram(b []byte) error { - s.mx.Lock() - sendErr := s.sendErr - s.mx.Unlock() - if sendErr != nil { - return sendErr + if err := context.Cause(s.Context()); err != nil { + return err } - return s.sendDatagram(b) } @@ -154,6 +148,9 @@ func (s *stateTrackingStream) enqueueDatagram(data []byte) { } func (s *stateTrackingStream) ReceiveDatagram(ctx context.Context) ([]byte, error) { + if err := context.Cause(ctx); err != nil { + return nil, err + } start: s.mx.Lock() if len(s.queue) > 0 { diff --git a/vendor/github.com/quic-go/quic-go/http3/stream.go b/vendor/github.com/quic-go/quic-go/http3/stream.go index 3d1c4734a..21c66738f 100644 --- a/vendor/github.com/quic-go/quic-go/http3/stream.go +++ b/vendor/github.com/quic-go/quic-go/http3/stream.go @@ -171,6 +171,12 @@ func (s *Stream) StreamID() quic.StreamID { return s.datagramStream.StreamID() } +// QlogTrace returns the qlog trace of the underlying QUIC connection. +// It is nil if qlog is not enabled. +func (s *Stream) QlogTrace() qlogwriter.Trace { + return s.conn.conn.QlogTrace() +} + func (s *Stream) SendDatagram(b []byte) error { // TODO: reject if datagrams are not negotiated (yet) return maybeReplaceError(s.datagramStream.SendDatagram(b)) @@ -243,6 +249,12 @@ func (s *RequestStream) StreamID() quic.StreamID { return s.str.StreamID() } +// QlogTrace returns the qlog trace of the underlying QUIC connection. +// It is nil if qlog is not enabled. +func (s *RequestStream) QlogTrace() qlogwriter.Trace { + return s.str.QlogTrace() +} + // Write writes data to the stream. // // It can only be used after the request has been sent using [RequestStream.SendRequestHeader]. @@ -378,8 +390,8 @@ func (s *RequestStream) ReadResponse() (*http.Response, error) { s.str.CancelWrite(quic.StreamErrorCode(ErrCodeFrameError)) return nil, fmt.Errorf("http3: HEADERS frame too large: %d bytes (max: %d)", hf.Length, s.maxHeaderBytes) } - headerBlock := make([]byte, hf.Length) - if _, err := io.ReadFull(s.str.datagramStream, headerBlock); err != nil { + headerBlock, err := readHeaderBlock(s.str.datagramStream, hf.Length) + if err != nil { maybeQlogInvalidHeadersFrame(s.str.qlogger, s.str.StreamID(), hf.Length) s.str.CancelRead(quic.StreamErrorCode(ErrCodeRequestIncomplete)) s.str.CancelWrite(quic.StreamErrorCode(ErrCodeRequestIncomplete)) diff --git a/vendor/github.com/quic-go/quic-go/interface.go b/vendor/github.com/quic-go/quic-go/interface.go index ad2bb9913..db942ac9c 100644 --- a/vendor/github.com/quic-go/quic-go/interface.go +++ b/vendor/github.com/quic-go/quic-go/interface.go @@ -64,6 +64,10 @@ var ErrWouldBlock = errors.New("operation would block") // ErrWriteLimitReached is returned by [SendStream.WriteWithLimit] when its limiter prevents accepting the entire slice. var ErrWriteLimitReached = errors.New("write limit reached") +// ErrStreamClosed is returned when writing to a stream after [SendStream.Close] was called. +// Closing a stream also cancels its context with this error as the cause. +var ErrStreamClosed = errors.New("stream closed") + // QUICVersionContextKey can be used to find out the QUIC version of a TLS handshake from the // context returned by [tls.ClientHelloInfo.Context]. var QUICVersionContextKey = handshake.QUICVersionContextKey @@ -167,6 +171,9 @@ type Config struct { // Under most circumstances, it is not necessary to manually set this value, // since path MTU discovery quickly finds the path's MTU. // If set too high, the path might not support packets of that size, leading to a timeout of the QUIC handshake. + // If set to 0, it defaults to 1280 bytes and falls back to 1200 bytes if the first write at that size + // returns a "message too long" error. An explicitly set value is kept as the lower limit; + // a "message too long" error at that size fails the handshake instead. // Values below 1200 are invalid. InitialPacketSize uint16 // DisablePathMTUDiscovery disables Path MTU Discovery (RFC 8899). diff --git a/vendor/github.com/quic-go/quic-go/internal/ackhandler/interfaces.go b/vendor/github.com/quic-go/quic-go/internal/ackhandler/interfaces.go index 620a5e11f..d50b47851 100644 --- a/vendor/github.com/quic-go/quic-go/internal/ackhandler/interfaces.go +++ b/vendor/github.com/quic-go/quic-go/internal/ackhandler/interfaces.go @@ -26,11 +26,11 @@ type SentPacketHandler interface { SetMaxDatagramSize(count protocol.ByteCount) // only to be called once the handshake is complete - QueueProbePacket(protocol.EncryptionLevel) bool /* was a packet queued */ + QueueProbePacket(protocol.PacketNumberSpace) bool /* was a packet queued */ ECNMode(isShortHeaderPacket bool) protocol.ECN // isShortHeaderPacket should only be true for non-coalesced 1-RTT packets - PeekPacketNumber(protocol.EncryptionLevel) (protocol.PacketNumber, protocol.PacketNumberLen) - PopPacketNumber(protocol.EncryptionLevel) protocol.PacketNumber + PeekPacketNumber(protocol.PacketNumberSpace) (protocol.PacketNumber, protocol.PacketNumberLen) + PopPacketNumber(protocol.PacketNumberSpace) protocol.PacketNumber GetLossDetectionTimeout() monotime.Time OnLossDetectionTimeout(now monotime.Time) error diff --git a/vendor/github.com/quic-go/quic-go/internal/ackhandler/lost_packet_tracker.go b/vendor/github.com/quic-go/quic-go/internal/ackhandler/lost_packet_tracker.go index 40665734d..e2c3f072a 100644 --- a/vendor/github.com/quic-go/quic-go/internal/ackhandler/lost_packet_tracker.go +++ b/vendor/github.com/quic-go/quic-go/internal/ackhandler/lost_packet_tracker.go @@ -8,19 +8,19 @@ import ( "github.com/quic-go/quic-go/internal/protocol" ) +const maxTrackedLostPackets = 64 + type lostPacket struct { PacketNumber protocol.PacketNumber SendTime monotime.Time } type lostPacketTracker struct { - maxLength int lostPackets []lostPacket } -func newLostPacketTracker(maxLength int) *lostPacketTracker { +func newLostPacketTracker() *lostPacketTracker { return &lostPacketTracker{ - maxLength: maxLength, // Preallocate a small slice only. // Hopefully we won't lose many packets. lostPackets: make([]lostPacket, 0, 4), @@ -28,7 +28,7 @@ func newLostPacketTracker(maxLength int) *lostPacketTracker { } func (t *lostPacketTracker) Add(p protocol.PacketNumber, sendTime monotime.Time) { - if len(t.lostPackets) == t.maxLength { + if len(t.lostPackets) == maxTrackedLostPackets { t.lostPackets = t.lostPackets[1:] } t.lostPackets = append(t.lostPackets, lostPacket{ @@ -71,3 +71,7 @@ func (t *lostPacketTracker) DeleteBefore(ti monotime.Time) { } t.lostPackets = slices.Delete(t.lostPackets, 0, idx) } + +func (t *lostPacketTracker) Reset() { + t.lostPackets = t.lostPackets[:0] +} diff --git a/vendor/github.com/quic-go/quic-go/internal/ackhandler/packet_number_generator.go b/vendor/github.com/quic-go/quic-go/internal/ackhandler/packet_number_generator.go index 4a9db8635..3e0c7ae6b 100644 --- a/vendor/github.com/quic-go/quic-go/internal/ackhandler/packet_number_generator.go +++ b/vendor/github.com/quic-go/quic-go/internal/ackhandler/packet_number_generator.go @@ -5,51 +5,31 @@ import ( "github.com/quic-go/quic-go/internal/utils" ) -type packetNumberGenerator interface { - Peek() protocol.PacketNumber - // Pop pops the packet number. - // It reports if the packet number (before the one just popped) was skipped. - // It never skips more than one packet number in a row. - Pop() (skipped bool, _ protocol.PacketNumber) -} - -type sequentialPacketNumberGenerator struct { - next protocol.PacketNumber -} - -var _ packetNumberGenerator = &sequentialPacketNumberGenerator{} +const ( + // skipPacketInitialPeriod is the initial period length used for packet number skipping + // to prevent an Optimistic ACK attack. + // Every time a packet number is skipped, the period is doubled, up to skipPacketMaxPeriod. + skipPacketInitialPeriod = 256 -func newSequentialPacketNumberGenerator(initial protocol.PacketNumber) packetNumberGenerator { - return &sequentialPacketNumberGenerator{next: initial} -} - -func (p *sequentialPacketNumberGenerator) Peek() protocol.PacketNumber { - return p.next -} - -func (p *sequentialPacketNumberGenerator) Pop() (bool, protocol.PacketNumber) { - next := p.next - p.next++ - return false, next -} + // skipPacketMaxPeriod is the maximum period length used for packet number skipping. + skipPacketMaxPeriod = 128 * 1024 +) -// The skippingPacketNumberGenerator generates the packet number for the next packet +// The packetNumberGenerator generates the packet number for the next packet // it randomly skips a packet number every averagePeriod packets (on average). // It is guaranteed to never skip two consecutive packet numbers. -type skippingPacketNumberGenerator struct { - period protocol.PacketNumber - maxPeriod protocol.PacketNumber +type packetNumberGenerator struct { + next protocol.PacketNumber - next protocol.PacketNumber - nextToSkip protocol.PacketNumber + period uint32 + maxPeriod uint32 + packetsUntilSkip uint32 rng utils.Rand } -var _ packetNumberGenerator = &skippingPacketNumberGenerator{} - -func newSkippingPacketNumberGenerator(initial, initialPeriod, maxPeriod protocol.PacketNumber) packetNumberGenerator { - g := &skippingPacketNumberGenerator{ +func newPacketNumberGenerator(initial protocol.PacketNumber, initialPeriod, maxPeriod uint32) *packetNumberGenerator { + g := &packetNumberGenerator{ next: initial, period: initialPeriod, maxPeriod: maxPeriod, @@ -58,27 +38,31 @@ func newSkippingPacketNumberGenerator(initial, initialPeriod, maxPeriod protocol return g } -func (p *skippingPacketNumberGenerator) Peek() protocol.PacketNumber { - if p.next == p.nextToSkip { +func (p *packetNumberGenerator) Peek(allowSkip bool) protocol.PacketNumber { + if allowSkip && p.packetsUntilSkip == 0 { return p.next + 1 } return p.next } -func (p *skippingPacketNumberGenerator) Pop() (bool, protocol.PacketNumber) { +// Pop reports whether the packet number before the returned number was skipped. +func (p *packetNumberGenerator) Pop(allowSkip bool) (bool, protocol.PacketNumber) { next := p.next - if p.next == p.nextToSkip { + if allowSkip && p.packetsUntilSkip == 0 { next++ p.next += 2 p.generateNewSkip() return true, next } + if allowSkip { + p.packetsUntilSkip-- + } p.next++ // generate a new packet number for the next packet return false, next } -func (p *skippingPacketNumberGenerator) generateNewSkip() { +func (p *packetNumberGenerator) generateNewSkip() { // make sure that there are never two consecutive packet numbers that are skipped - p.nextToSkip = p.next + 3 + protocol.PacketNumber(p.rng.Int31n(int32(2*p.period))) + p.packetsUntilSkip = 3 + p.rng.Uint32N(2*p.period) p.period = min(2*p.period, p.maxPeriod) } diff --git a/vendor/github.com/quic-go/quic-go/internal/ackhandler/received_packet_handler.go b/vendor/github.com/quic-go/quic-go/internal/ackhandler/received_packet_handler.go index d0d24bf30..d6ddf4d7e 100644 --- a/vendor/github.com/quic-go/quic-go/internal/ackhandler/received_packet_handler.go +++ b/vendor/github.com/quic-go/quic-go/internal/ackhandler/received_packet_handler.go @@ -102,18 +102,18 @@ func (h *ReceivedPacketHandler) GetAckFrame(encLevel protocol.EncryptionLevel, n } } -func (h *ReceivedPacketHandler) IsPotentiallyDuplicate(pn protocol.PacketNumber, encLevel protocol.EncryptionLevel) bool { - switch encLevel { - case protocol.EncryptionInitial: +func (h *ReceivedPacketHandler) IsPotentiallyDuplicate(pn protocol.PacketNumber, space protocol.PacketNumberSpace) bool { + switch space { + case protocol.PacketNumberSpaceInitial: if h.initialPackets != nil { return h.initialPackets.IsPotentiallyDuplicate(pn) } - case protocol.EncryptionHandshake: + case protocol.PacketNumberSpaceHandshake: if h.handshakePackets != nil { return h.handshakePackets.IsPotentiallyDuplicate(pn) } - case protocol.Encryption0RTT, protocol.Encryption1RTT: + case protocol.PacketNumberSpaceAppData: return h.appDataPackets.IsPotentiallyDuplicate(pn) } - panic("unexpected encryption level") + panic("unexpected packet number space") } diff --git a/vendor/github.com/quic-go/quic-go/internal/ackhandler/received_packet_tracker.go b/vendor/github.com/quic-go/quic-go/internal/ackhandler/received_packet_tracker.go index 64092cccf..e1b54b49d 100644 --- a/vendor/github.com/quic-go/quic-go/internal/ackhandler/received_packet_tracker.go +++ b/vendor/github.com/quic-go/quic-go/internal/ackhandler/received_packet_tracker.go @@ -75,6 +75,9 @@ func (h *receivedPacketTracker) IsPotentiallyDuplicate(pn protocol.PacketNumber) return h.packetHistory.IsPotentiallyDuplicate(pn) } +// MaxAckDelay is the maximum time by which we delay sending ACKs. +const MaxAckDelay = 25 * time.Millisecond + // number of ack-eliciting packets received before sending an ACK const packetsBeforeAck = 2 @@ -88,8 +91,7 @@ type appDataReceivedPacketTracker struct { largestObserved protocol.PacketNumber ignoreBelow protocol.PacketNumber - maxAckDelay time.Duration - ackQueued bool // true if we need send a new ACK + ackQueued bool // true if we need send a new ACK ackElicitingPacketsReceivedSinceLastAck int ackAlarm monotime.Time @@ -100,7 +102,6 @@ type appDataReceivedPacketTracker struct { func newAppDataReceivedPacketTracker(logger utils.Logger) *appDataReceivedPacketTracker { h := &appDataReceivedPacketTracker{ receivedPacketTracker: *newReceivedPacketTracker(), - maxAckDelay: protocol.MaxAckDelay, logger: logger, } return h @@ -125,9 +126,9 @@ func (h *appDataReceivedPacketTracker) ReceivedPacket(pn protocol.PacketNumber, } if !h.ackQueued { // No ACK queued, but we'll need to acknowledge the packet after max_ack_delay. - h.ackAlarm = rcvTime.Add(h.maxAckDelay) + h.ackAlarm = rcvTime.Add(MaxAckDelay) if h.logger.Debug() { - h.logger.Debugf("\tSetting ACK timer to max ack delay: %s", h.maxAckDelay) + h.logger.Debugf("\tSetting ACK timer to max ack delay: %s", MaxAckDelay) } } return nil diff --git a/vendor/github.com/quic-go/quic-go/internal/ackhandler/sent_packet_handler.go b/vendor/github.com/quic-go/quic-go/internal/ackhandler/sent_packet_handler.go index 9b539eadd..5af617a37 100644 --- a/vendor/github.com/quic-go/quic-go/internal/ackhandler/sent_packet_handler.go +++ b/vendor/github.com/quic-go/quic-go/internal/ackhandler/sent_packet_handler.go @@ -16,9 +16,9 @@ import ( ) const ( - // Maximum reordering in time space before time based loss detection considers a packet lost. - // Specified as an RTT multiplier. - timeThreshold = 9.0 / 8 + // Extra RTT allowance for time-threshold loss detection, in eighths of an RTT. + defaultTimeThresholdEighths = 1 + maxTimeThresholdEighths = 8 // Maximum reordering in packets before packet threshold loss detection considers a packet lost. packetThreshold = 3 // Before validating the client's address, the server won't send more than 3x bytes than it received. @@ -33,8 +33,7 @@ const ( const pathProbePacketLossTimeout = time.Second type packetNumberSpace struct { - history sentPacketHistory - pns packetNumberGenerator + numOutstanding int lossTime monotime.Time lastAckElicitingPacketTime monotime.Time @@ -43,16 +42,8 @@ type packetNumberSpace struct { largestSent protocol.PacketNumber } -func newPacketNumberSpace(initialPN protocol.PacketNumber, isAppData bool) *packetNumberSpace { - var pns packetNumberGenerator - if isAppData { - pns = newSkippingPacketNumberGenerator(initialPN, protocol.SkipPacketInitialPeriod, protocol.SkipPacketMaxPeriod) - } else { - pns = newSequentialPacketNumberGenerator(initialPN) - } +func newPacketNumberSpace() *packetNumberSpace { return &packetNumberSpace{ - history: *newSentPacketHistory(isAppData), - pns: pns, largestSent: protocol.InvalidPacketNumber, largestAcked: protocol.InvalidPacketNumber, } @@ -64,7 +55,32 @@ type alarmTimer struct { EncryptionLevel protocol.EncryptionLevel } +type handshakePacketNumbers struct { + Initial []protocol.PacketNumber + Handshake []protocol.PacketNumber +} + +func (p *handshakePacketNumbers) Highest() protocol.PacketNumber { + switch { + case len(p.Initial) == 0 && len(p.Handshake) == 0: + return protocol.InvalidPacketNumber + case len(p.Initial) == 0: + return p.Handshake[len(p.Handshake)-1] + case len(p.Handshake) == 0: + return p.Initial[len(p.Initial)-1] + default: + return max(p.Initial[len(p.Initial)-1], p.Handshake[len(p.Handshake)-1]) + } +} + type sentPacketHandler struct { + // Packet numbers and their history are shared across encryption levels. + // ACK processing and loss detection still use the state for each space. + pns *packetNumberGenerator + hist sentPacketHistory + + handshakePNs *handshakePacketNumbers + initialPackets *packetNumberSpace handshakePackets *packetNumberSpace appDataPackets *packetNumberSpace @@ -72,6 +88,13 @@ type sentPacketHandler struct { // send time of the largest acknowledged packet, across all packet number spaces largestAckedTime monotime.Time + // In the application-data packet number space, packet threshold loss detection is + // disabled when spurious losses are detected. + packetThresholdDisabled bool + timeThresholdEighths uint8 + // Only packets sent after a time-threshold increase can trigger another one. + minPNToRelaxReordering protocol.PacketNumber + // Do we know that the peer completed address validation yet? // Always true for the server. peerCompletedAddressValidation bool @@ -141,53 +164,95 @@ func NewSentPacketHandler( h := &sentPacketHandler{ peerCompletedAddressValidation: pers == protocol.PerspectiveServer, peerAddressValidated: pers == protocol.PerspectiveClient || clientAddressValidated, - initialPackets: newPacketNumberSpace(initialPN, false), - handshakePackets: newPacketNumberSpace(0, false), - appDataPackets: newPacketNumberSpace(0, true), - lostPackets: *newLostPacketTracker(64), - rttStats: rttStats, - connStats: connStats, - congestion: congestion, - ignorePacketsBelow: ignorePacketsBelow, - perspective: pers, - qlogger: qlogger, - logger: logger, + pns: newPacketNumberGenerator(initialPN, skipPacketInitialPeriod, skipPacketMaxPeriod), + hist: *newSentPacketHistory(), + timeThresholdEighths: defaultTimeThresholdEighths, + minPNToRelaxReordering: protocol.InvalidPacketNumber, + handshakePNs: &handshakePacketNumbers{ + Initial: make([]protocol.PacketNumber, 0, 4), + Handshake: make([]protocol.PacketNumber, 0, 8), + }, + initialPackets: newPacketNumberSpace(), + handshakePackets: newPacketNumberSpace(), + appDataPackets: newPacketNumberSpace(), + lostPackets: *newLostPacketTracker(), + rttStats: rttStats, + connStats: connStats, + congestion: congestion, + ignorePacketsBelow: ignorePacketsBelow, + perspective: pers, + qlogger: qlogger, + logger: logger, } if enableECN { h.enableECN = true h.ecnTracker = newECNTracker(logger, qlogger) } + h.qlogRecoveryParametersSet(true) return h } +func (h *sentPacketHandler) qlogRecoveryParametersSet(initial bool) { + if h.qlogger == nil { + return + } + ev := qlog.RecoveryParametersSet{ + EncryptionLevel: protocol.Encryption1RTT, + ReorderingThreshold: packetThreshold, + PacketThresholdDisabled: h.packetThresholdDisabled, + TimeThreshold: float64(8+h.timeThresholdEighths) / 8, + TimerGranularity: protocol.TimerGranularity, + } + if initial { + ev.InitialCongestionWindow = h.congestion.GetCongestionWindow() + ev.InitialRTT = h.rttStats.SmoothedRTT() + } + h.qlogger.RecordEvent(ev) +} + func (h *sentPacketHandler) removeFromBytesInFlight(p *packet) { if p.includedInBytesInFlight { if p.Length > h.bytesInFlight { panic("negative bytes_in_flight") } h.bytesInFlight -= p.Length + if p.Outstanding() { + h.getPacketNumberSpace(p.EncryptionLevel.PacketNumberSpace()).numOutstanding-- + } p.includedInBytesInFlight = false } } func (h *sentPacketHandler) DropPackets(encLevel protocol.EncryptionLevel, now monotime.Time) { + if encLevel == protocol.Encryption1RTT { + panic(fmt.Sprintf("Cannot drop keys for encryption level %s", encLevel)) + } // The server won't await address validation after the handshake is confirmed. // This applies even if we didn't receive an ACK for a Handshake packet. if h.perspective == protocol.PerspectiveClient && encLevel == protocol.EncryptionHandshake { h.peerCompletedAddressValidation = true } - // remove outstanding packets from bytes_in_flight - if encLevel == protocol.EncryptionInitial || encLevel == protocol.EncryptionHandshake { - pnSpace := h.getPacketNumberSpace(encLevel) - // We might already have dropped this packet number space. - if pnSpace == nil { - return + // remove packets from the history and bytes_in_flight + pnSpace := h.getPacketNumberSpace(encLevel.PacketNumberSpace()) + // We might already have dropped this packet number space. + if pnSpace == nil { + return + } + for pn, p := range h.hist.Packets() { + if pn > pnSpace.largestSent { + break } - for _, p := range pnSpace.history.Packets() { - h.removeFromBytesInFlight(p) + // no 0-RTT packets are sent after the first 1-RTT packet + if encLevel == protocol.Encryption0RTT && p.EncryptionLevel == protocol.Encryption1RTT { + break + } + if p.EncryptionLevel != encLevel { + continue } + h.removeFromBytesInFlight(p) + h.hist.Remove(pn) } - // drop the packet history + // drop the packet number space //nolint:exhaustive // Not every packet number space can be dropped. switch encLevel { case protocol.EncryptionInitial: @@ -200,17 +265,6 @@ func (h *sentPacketHandler) DropPackets(encLevel protocol.EncryptionLevel, now m case protocol.Encryption0RTT: // This function is only called when 0-RTT is rejected, // and not when the client drops 0-RTT keys when the handshake completes. - // When 0-RTT is rejected, all application data sent so far becomes invalid. - // Delete the packets from the history and remove them from bytes_in_flight. - for pn, p := range h.appDataPackets.history.Packets() { - if p.EncryptionLevel != protocol.Encryption0RTT { - break - } - h.removeFromBytesInFlight(p) - h.appDataPackets.history.Remove(pn) - } - default: - panic(fmt.Sprintf("Cannot drop keys for encryption level %s", encLevel)) } if h.qlogger != nil && h.ptoCount != 0 { h.qlogger.RecordEvent(qlog.PTOCountUpdated{PTOCount: 0}) @@ -238,17 +292,6 @@ func (h *sentPacketHandler) ReceivedPacket(l protocol.EncryptionLevel, t monotim } } -func (h *sentPacketHandler) packetsInFlight() int { - packetsInFlight := h.appDataPackets.history.NumOutstanding() - if h.handshakePackets != nil { - packetsInFlight += h.handshakePackets.history.NumOutstanding() - } - if h.initialPackets != nil { - packetsInFlight += h.initialPackets.history.NumOutstanding() - } - return packetsInFlight -} - func (h *sentPacketHandler) SentPacket( t monotime.Time, pn, largestAcked protocol.PacketNumber, @@ -264,14 +307,19 @@ func (h *sentPacketHandler) SentPacket( h.connStats.BytesSent.Add(uint64(size)) h.connStats.PacketsSent.Add(1) - pnSpace := h.getPacketNumberSpace(encLevel) - if h.logger.Debug() && (pnSpace.history.HasOutstandingPackets() || pnSpace.history.HasOutstandingPathProbes()) { - for p := max(0, pnSpace.largestSent+1); p < pn; p++ { - h.logger.Debugf("Skipping packet number %d", p) - } - } - + pnSpace := h.getPacketNumberSpace(encLevel.PacketNumberSpace()) pnSpace.largestSent = pn + if encLevel.PacketNumberSpace() == protocol.PacketNumberSpaceAppData && + h.minPNToRelaxReordering == protocol.InvalidPacketNumber { + h.minPNToRelaxReordering = pn + } + //nolint:exhaustive // Only Initial and Handshake packet numbers are stored separately. + switch encLevel { + case protocol.EncryptionInitial: + h.handshakePNs.Initial = append(h.handshakePNs.Initial, pn) + case protocol.EncryptionHandshake: + h.handshakePNs.Handshake = append(h.handshakePNs.Handshake, pn) + } p := getPacket() p.SendTime = t @@ -285,7 +333,7 @@ func (h *sentPacketHandler) SentPacket( isAckEliciting := p.IsAckEliciting() if isPathProbePacket { - pnSpace.history.SentPathProbePacket(pn, p) + h.hist.SentPathProbePacket(pn, p) h.setLossDetectionTimer(t) return } @@ -303,7 +351,10 @@ func (h *sentPacketHandler) SentPacket( h.ecnTracker.SentPacket(pn, ecn) } - pnSpace.history.SentPacket(pn, p) + if p.Outstanding() { + pnSpace.numOutstanding++ + } + h.hist.SentPacket(pn, p) if !isAckEliciting { if !h.peerCompletedAddressValidation { h.setLossDetectionTimer(t) @@ -351,7 +402,7 @@ func (h *sentPacketHandler) qlogMetricsUpdated() { h.lastMetrics.BytesInFlight = metricsUpdatedEvent.BytesInFlight updated = true } - packetsInFlight := h.packetsInFlight() + packetsInFlight := h.hist.NumOutstanding() if h.lastMetrics.PacketsInFlight != packetsInFlight { metricsUpdatedEvent.PacketsInFlight = packetsInFlight h.lastMetrics.PacketsInFlight = metricsUpdatedEvent.PacketsInFlight @@ -362,13 +413,13 @@ func (h *sentPacketHandler) qlogMetricsUpdated() { } } -func (h *sentPacketHandler) getPacketNumberSpace(encLevel protocol.EncryptionLevel) *packetNumberSpace { - switch encLevel { - case protocol.EncryptionInitial: +func (h *sentPacketHandler) getPacketNumberSpace(space protocol.PacketNumberSpace) *packetNumberSpace { + switch space { + case protocol.PacketNumberSpaceInitial: return h.initialPackets - case protocol.EncryptionHandshake: + case protocol.PacketNumberSpaceHandshake: return h.handshakePackets - case protocol.Encryption0RTT, protocol.Encryption1RTT: + case protocol.PacketNumberSpaceAppData: return h.appDataPackets default: panic("invalid packet number space") @@ -376,7 +427,7 @@ func (h *sentPacketHandler) getPacketNumberSpace(encLevel protocol.EncryptionLev } func (h *sentPacketHandler) ReceivedAck(ack *wire.AckFrame, encLevel protocol.EncryptionLevel, rcvTime monotime.Time) (bool /* contained 1-RTT packet */, error) { - pnSpace := h.getPacketNumberSpace(encLevel) + pnSpace := h.getPacketNumberSpace(encLevel.PacketNumberSpace()) largestAcked := ack.LargestAcked() if largestAcked > pnSpace.largestSent { @@ -397,7 +448,7 @@ func (h *sentPacketHandler) ReceivedAck(ack *wire.AckFrame, encLevel protocol.En priorInFlight := h.bytesInFlight ackedPackets, hasAckEliciting, err := h.detectAndRemoveAckedPackets(ack, encLevel) - if err != nil || len(ackedPackets) == 0 { + if err != nil { return false, err } // update the RTT, if: @@ -421,20 +472,50 @@ func (h *sentPacketHandler) ReceivedAck(ack *wire.AckFrame, encLevel protocol.En } } - // Only inform the ECN tracker about new 1-RTT ACKs if the ACK increases the largest acked. - if encLevel == protocol.Encryption1RTT && h.ecnTracker != nil && largestAcked > pnSpace.largestAcked { - congested := h.ecnTracker.HandleNewlyAcked(ackedPackets, int64(ack.ECT0), int64(ack.ECT1), int64(ack.ECNCE)) - if congested { - h.congestion.OnCongestionEvent(largestAcked, 0, priorInFlight) - } + // Detect spurious losses even if no outstanding packets were newly acknowledged. + var spuriousLosses []protocol.PacketNumber + var timeThresholdIncreased bool + if encLevel == protocol.Encryption1RTT { + spuriousLosses, timeThresholdIncreased = h.detectSpuriousLosses( + ack, + rcvTime.Add(-min(ack.DelayTime, h.rttStats.MaxAckDelay())), + ) + // clean up lost packet history + h.lostPackets.DeleteBefore(rcvTime.Add(-3 * h.rttStats.PTO(false))) } + if len(ackedPackets) > 0 { + // Only inform the ECN tracker about new 1-RTT ACKs if the ACK increases the largest acked. + if encLevel == protocol.Encryption1RTT && h.ecnTracker != nil && largestAcked > pnSpace.largestAcked { + congested := h.ecnTracker.HandleNewlyAcked(ackedPackets, int64(ack.ECT0), int64(ack.ECT1), int64(ack.ECNCE)) + if congested { + h.congestion.OnCongestionEvent(largestAcked, 0, priorInFlight) + } + } - pnSpace.largestAcked = max(pnSpace.largestAcked, largestAcked) - - h.detectLostPackets(rcvTime, encLevel) - if encLevel == protocol.Encryption1RTT { - h.detectLostPathProbes(rcvTime) + pnSpace.largestAcked = max(pnSpace.largestAcked, largestAcked) + } + // new acked packets can advance largestAcked or update the RTT, + // and a larger time threshold moves the loss deadline + if len(ackedPackets) > 0 || timeThresholdIncreased { + h.detectLostPackets(rcvTime, encLevel) + if encLevel == protocol.Encryption1RTT { + h.detectLostPathProbes(rcvTime) + } + } + // report spurious losses after any new congestion events from this ACK + for _, pn := range spuriousLosses { + h.congestion.OnSpuriousLoss(pn) + } + if len(ackedPackets) == 0 { + if len(spuriousLosses) > 0 && h.qlogger != nil { + h.qlogMetricsUpdated() + } + if timeThresholdIncreased { + h.setLossDetectionTimer(rcvTime) + } + return false, nil } + var acked1RTTPacket bool for _, p := range ackedPackets { if p.includedInBytesInFlight { @@ -449,16 +530,6 @@ func (h *sentPacketHandler) ReceivedAck(ack *wire.AckFrame, encLevel protocol.En } } - // detect spurious losses for application data packets, if the ACK was not reordered - if encLevel == protocol.Encryption1RTT && largestAcked == pnSpace.largestAcked { - h.detectSpuriousLosses( - ack, - rcvTime.Add(-min(ack.DelayTime, h.rttStats.MaxAckDelay())), - ) - // clean up lost packet history - h.lostPackets.DeleteBefore(rcvTime.Add(-3 * h.rttStats.PTO(false))) - } - // After this point, we must not use ackedPackets any longer! // We've already returned the buffers. ackedPackets = nil //nolint:ineffassign // This is just to be on the safe side. @@ -482,18 +553,15 @@ func (h *sentPacketHandler) ReceivedAck(ack *wire.AckFrame, encLevel protocol.En return acked1RTTPacket, nil } -func (h *sentPacketHandler) detectSpuriousLosses(ack *wire.AckFrame, ackTime monotime.Time) { +func (h *sentPacketHandler) detectSpuriousLosses(ack *wire.AckFrame, ackTime monotime.Time) (_ []protocol.PacketNumber, timeThresholdIncreased bool) { var maxPacketReordering protocol.PacketNumber var maxTimeReordering time.Duration + var packetThresholdChanged bool ackRangeIdx := len(ack.AckRanges) - 1 var spuriousLosses []protocol.PacketNumber for pn, sendTime := range h.lostPackets.All() { ackRange := ack.AckRanges[ackRangeIdx] - for pn > ackRange.Largest { - // this should never happen, since detectSpuriousLosses is only called for ACKs that increase the largest acked - if ackRangeIdx == 0 { - break - } + for pn > ackRange.Largest && ackRangeIdx > 0 { ackRangeIdx-- ackRange = ack.AckRanges[ackRangeIdx] } @@ -501,10 +569,16 @@ func (h *sentPacketHandler) detectSpuriousLosses(ack *wire.AckFrame, ackTime mon continue } if pn <= ackRange.Largest { - packetReordering := h.appDataPackets.history.Difference(ack.LargestAcked(), pn) + if !h.packetThresholdDisabled { + h.packetThresholdDisabled = true + packetThresholdChanged = true + } + packetReordering := h.hist.Difference(ack.LargestAcked(), pn) timeReordering := ackTime.Sub(sendTime) maxPacketReordering = max(maxPacketReordering, packetReordering) - maxTimeReordering = max(maxTimeReordering, timeReordering) + if h.minPNToRelaxReordering != protocol.InvalidPacketNumber && pn >= h.minPNToRelaxReordering { + maxTimeReordering = max(maxTimeReordering, timeReordering) + } if h.qlogger != nil { h.qlogger.RecordEvent(qlog.SpuriousLoss{ @@ -520,6 +594,19 @@ func (h *sentPacketHandler) detectSpuriousLosses(ack *wire.AckFrame, ackTime mon for _, pn := range spuriousLosses { h.lostPackets.Delete(pn) } + lossDelay := max( + max(h.rttStats.LatestRTT(), h.rttStats.SmoothedRTT())*time.Duration(8+h.timeThresholdEighths)/8, + protocol.TimerGranularity, + ) + if maxTimeReordering > lossDelay && h.timeThresholdEighths < maxTimeThresholdEighths { + h.timeThresholdEighths = min(2*h.timeThresholdEighths, maxTimeThresholdEighths) + h.minPNToRelaxReordering = protocol.InvalidPacketNumber + timeThresholdIncreased = true + } + if packetThresholdChanged || timeThresholdIncreased { + h.qlogRecoveryParametersSet(false) + } + return spuriousLosses, timeThresholdIncreased } // Packets are returned in ascending packet number order. @@ -531,10 +618,8 @@ func (h *sentPacketHandler) detectAndRemoveAckedPackets( return nil, false, errors.New("ackhandler BUG: ackedPackets slice not empty") } - pnSpace := h.getPacketNumberSpace(encLevel) - if encLevel == protocol.Encryption1RTT { - for p := range pnSpace.history.SkippedPackets() { + for p := range h.hist.SkippedPackets() { if ack.AcksPacket(p) { return nil, false, &qerr.TransportError{ ErrorCode: qerr.ProtocolViolation, @@ -547,7 +632,7 @@ func (h *sentPacketHandler) detectAndRemoveAckedPackets( var ackRangeIndex int lowestAcked := ack.LowestAcked() largestAcked := ack.LargestAcked() - for pn, p := range pnSpace.history.Packets() { + for pn, p := range h.hist.Packets() { // ignore packets below the lowest acked if pn < lowestAcked { continue @@ -555,6 +640,9 @@ func (h *sentPacketHandler) detectAndRemoveAckedPackets( if pn > largestAcked { break } + if p.EncryptionLevel.PacketNumberSpace() != encLevel.PacketNumberSpace() { + continue + } if ack.HasMissingRanges() { ackRange := ack.AckRanges[len(ack.AckRanges)-1-ackRangeIndex] @@ -572,7 +660,7 @@ func (h *sentPacketHandler) detectAndRemoveAckedPackets( } } if p.isPathProbePacket { - probePacket := pnSpace.history.RemovePathProbe(pn) + probePacket := h.hist.RemovePathProbe(pn) // the probe packet might already have been declared lost if probePacket != nil { h.ackedPackets = append(h.ackedPackets, packetWithPacketNumber{PacketNumber: pn, packet: probePacket}) @@ -607,7 +695,7 @@ func (h *sentPacketHandler) detectAndRemoveAckedPackets( f.Handler.OnAcked(f.Frame) } } - if err := pnSpace.history.Remove(p.PacketNumber); err != nil { + if err := h.hist.Remove(p.PacketNumber); err != nil { return nil, false, err } } @@ -657,14 +745,14 @@ func (h *sentPacketHandler) getPTOTimeAndSpace(now monotime.Time) (pto monotime. return t, protocol.EncryptionHandshake } - if h.initialPackets != nil && h.initialPackets.history.HasOutstandingPackets() && + if h.initialPackets != nil && h.initialPackets.numOutstanding > 0 && !h.initialPackets.lastAckElicitingPacketTime.IsZero() { encLevel = protocol.EncryptionInitial if t := h.initialPackets.lastAckElicitingPacketTime; !t.IsZero() { pto = t.Add(h.getScaledPTO(false)) } } - if h.handshakePackets != nil && h.handshakePackets.history.HasOutstandingPackets() && + if h.handshakePackets != nil && h.handshakePackets.numOutstanding > 0 && !h.handshakePackets.lastAckElicitingPacketTime.IsZero() { t := h.handshakePackets.lastAckElicitingPacketTime.Add(h.getScaledPTO(false)) if pto.IsZero() || (!t.IsZero() && t.Before(pto)) { @@ -672,7 +760,7 @@ func (h *sentPacketHandler) getPTOTimeAndSpace(now monotime.Time) (pto monotime. encLevel = protocol.EncryptionHandshake } } - if h.handshakeConfirmed && h.appDataPackets.history.HasOutstandingPackets() && + if h.handshakeConfirmed && h.appDataPackets.numOutstanding > 0 && !h.appDataPackets.lastAckElicitingPacketTime.IsZero() { t := h.appDataPackets.lastAckElicitingPacketTime.Add(h.getScaledPTO(true)) if pto.IsZero() || (!t.IsZero() && t.Before(pto)) { @@ -684,10 +772,10 @@ func (h *sentPacketHandler) getPTOTimeAndSpace(now monotime.Time) (pto monotime. } func (h *sentPacketHandler) hasOutstandingCryptoPackets() bool { - if h.initialPackets != nil && h.initialPackets.history.HasOutstandingPackets() { + if h.initialPackets != nil && h.initialPackets.numOutstanding > 0 { return true } - if h.handshakePackets != nil && h.handshakePackets.history.HasOutstandingPackets() { + if h.handshakePackets != nil && h.handshakePackets.numOutstanding > 0 { return true } return false @@ -720,8 +808,7 @@ func (h *sentPacketHandler) setLossDetectionTimer(now monotime.Time) { func (h *sentPacketHandler) lossDetectionTime(now monotime.Time) alarmTimer { // cancel the alarm if no packets are outstanding - if h.peerCompletedAddressValidation && !h.hasOutstandingCryptoPackets() && - !h.appDataPackets.history.HasOutstandingPackets() && !h.appDataPackets.history.HasOutstandingPathProbes() { + if h.peerCompletedAddressValidation && !h.hist.HasOutstandingPackets() && !h.hist.HasOutstandingPathProbes() { return alarmTimer{} } @@ -731,8 +818,8 @@ func (h *sentPacketHandler) lossDetectionTime(now monotime.Time) alarmTimer { } var pathProbeLossTime monotime.Time - if h.appDataPackets.history.HasOutstandingPathProbes() { - if _, p := h.appDataPackets.history.FirstOutstandingPathProbe(); p != nil { + if h.hist.HasOutstandingPathProbes() { + if _, p := h.hist.FirstOutstandingPathProbe(); p != nil { pathProbeLossTime = p.SendTime.Add(pathProbePacketLossTimeout) } } @@ -765,13 +852,13 @@ func (h *sentPacketHandler) lossDetectionTime(now monotime.Time) alarmTimer { } func (h *sentPacketHandler) detectLostPathProbes(now monotime.Time) { - if !h.appDataPackets.history.HasOutstandingPathProbes() { + if !h.hist.HasOutstandingPathProbes() { return } lossTime := now.Add(-pathProbePacketLossTimeout) // RemovePathProbe cannot be called while iterating. var lostPathProbes []packetWithPacketNumber - for pn, p := range h.appDataPackets.history.PathProbes() { + for pn, p := range h.hist.PathProbes() { if !p.SendTime.After(lossTime) { lostPathProbes = append(lostPathProbes, packetWithPacketNumber{PacketNumber: pn, packet: p}) } @@ -780,29 +867,63 @@ func (h *sentPacketHandler) detectLostPathProbes(now monotime.Time) { for _, f := range p.Frames { f.Handler.OnLost(f.Frame) } - h.appDataPackets.history.RemovePathProbe(p.PacketNumber) + h.hist.RemovePathProbe(p.PacketNumber) + } +} + +func countPacketNumbers(pns []protocol.PacketNumber, lower, upper protocol.PacketNumber) protocol.PacketNumber { + if len(pns) == 0 || pns[len(pns)-1] <= lower { + return 0 + } + var count protocol.PacketNumber + for _, pn := range pns { + if pn > lower && pn <= upper { + count++ + } } + return count } func (h *sentPacketHandler) detectLostPackets(now monotime.Time, encLevel protocol.EncryptionLevel) { - pnSpace := h.getPacketNumberSpace(encLevel) + pnSpace := h.getPacketNumberSpace(encLevel.PacketNumberSpace()) pnSpace.lossTime = 0 + space := encLevel.PacketNumberSpace() + usePacketThreshold := space != protocol.PacketNumberSpaceAppData || !h.packetThresholdDisabled + timeThresholdEighths := uint8(defaultTimeThresholdEighths) + if space == protocol.PacketNumberSpaceAppData { + timeThresholdEighths = h.timeThresholdEighths + } - maxRTT := float64(max(h.rttStats.LatestRTT(), h.rttStats.SmoothedRTT())) - lossDelay := time.Duration(timeThreshold * maxRTT) - - // Minimum time of granularity before packets are deemed lost. - lossDelay = max(lossDelay, protocol.TimerGranularity) + lossDelay := max( + max(h.rttStats.LatestRTT(), h.rttStats.SmoothedRTT())*time.Duration(8+timeThresholdEighths)/8, + protocol.TimerGranularity, + ) // Packets sent before this time are deemed lost. lostSendTime := now.Add(-lossDelay) priorInFlight := h.bytesInFlight - for pn, p := range pnSpace.history.Packets() { + for pn, p := range h.hist.Packets() { if pn > pnSpace.largestAcked { break } + if p.EncryptionLevel.PacketNumberSpace() != space { + continue + } + var distance protocol.PacketNumber + switch space { + case protocol.PacketNumberSpaceInitial: + distance = countPacketNumbers(h.handshakePNs.Initial, pn, pnSpace.largestAcked) + case protocol.PacketNumberSpaceHandshake: + distance = countPacketNumbers(h.handshakePNs.Handshake, pn, pnSpace.largestAcked) + case protocol.PacketNumberSpaceAppData: + distance = h.hist.Difference(pnSpace.largestAcked, pn) + if h.handshakePNs != nil { + distance -= countPacketNumbers(h.handshakePNs.Initial, pn, pnSpace.largestAcked) + distance -= countPacketNumbers(h.handshakePNs.Handshake, pn, pnSpace.largestAcked) + } + } var packetLost bool if !p.SendTime.After(lostSendTime) { packetLost = true @@ -820,7 +941,7 @@ func (h *sentPacketHandler) detectLostPackets(now monotime.Time, encLevel protoc }) } } - } else if pnSpace.history.Difference(pnSpace.largestAcked, pn) >= packetThreshold { + } else if usePacketThreshold && distance >= packetThreshold { packetLost = true if !p.isPathProbePacket && p.IsAckEliciting() { if h.logger.Debug() { @@ -845,10 +966,10 @@ func (h *sentPacketHandler) detectLostPackets(now monotime.Time, encLevel protoc pnSpace.lossTime = lossTime } if packetLost { - if encLevel == protocol.Encryption0RTT || encLevel == protocol.Encryption1RTT { + if p.Outstanding() && space == protocol.PacketNumberSpaceAppData { h.lostPackets.Add(pn, p.SendTime) } - pnSpace.history.DeclareLost(pn) + h.hist.DeclareLost(pn) if !p.isPathProbePacket && p.IsAckEliciting() { // the bytes in flight need to be reduced no matter if the frames in this packet will be retransmitted h.removeFromBytesInFlight(p) @@ -862,6 +983,13 @@ func (h *sentPacketHandler) detectLostPackets(now monotime.Time, encLevel protoc } } } + if h.handshakeConfirmed && h.handshakePNs != nil { + firstPN := h.hist.FirstPacketNumber() + highestPN := h.handshakePNs.Highest() + if firstPN == protocol.InvalidPacketNumber || highestPN == protocol.InvalidPacketNumber || firstPN > highestPN { + h.handshakePNs = nil + } + } } func (h *sentPacketHandler) OnLossDetectionTimeout(now monotime.Time) error { @@ -910,8 +1038,8 @@ func (h *sentPacketHandler) OnLossDetectionTimeout(now monotime.Time) error { if ptoTime.IsZero() { return nil } - ps := h.getPacketNumberSpace(encLevel) - if !ps.history.HasOutstandingPackets() && !ps.history.HasOutstandingPathProbes() && !h.peerCompletedAddressValidation { + ps := h.getPacketNumberSpace(encLevel.PacketNumberSpace()) + if ps.numOutstanding == 0 && (encLevel != protocol.Encryption1RTT || !h.hist.HasOutstandingPathProbes()) && !h.peerCompletedAddressValidation { return nil } h.ptoCount++ @@ -935,8 +1063,8 @@ func (h *sentPacketHandler) OnLossDetectionTimeout(now monotime.Time) error { h.ptoMode = SendPTOHandshake case protocol.Encryption1RTT: // skip a packet number in order to elicit an immediate ACK - pn := h.PopPacketNumber(protocol.Encryption1RTT) - h.getPacketNumberSpace(protocol.Encryption1RTT).history.SkippedPacket(pn) + pn := h.PopPacketNumber(protocol.PacketNumberSpaceAppData) + h.hist.SkippedPacket(pn) h.ptoMode = SendPTOAppData default: return fmt.Errorf("PTO timer in unexpected encryption level: %s", encLevel) @@ -958,19 +1086,18 @@ func (h *sentPacketHandler) ECNMode(isShortHeaderPacket bool) protocol.ECN { return h.ecnTracker.Mode() } -func (h *sentPacketHandler) PeekPacketNumber(encLevel protocol.EncryptionLevel) (protocol.PacketNumber, protocol.PacketNumberLen) { - pnSpace := h.getPacketNumberSpace(encLevel) - pn := pnSpace.pns.Peek() +func (h *sentPacketHandler) PeekPacketNumber(space protocol.PacketNumberSpace) (protocol.PacketNumber, protocol.PacketNumberLen) { + pnSpace := h.getPacketNumberSpace(space) + pn := h.pns.Peek(space == protocol.PacketNumberSpaceAppData) // See section 17.1 of RFC 9000. return pn, protocol.PacketNumberLengthForHeader(pn, pnSpace.largestAcked) } -func (h *sentPacketHandler) PopPacketNumber(encLevel protocol.EncryptionLevel) protocol.PacketNumber { - pnSpace := h.getPacketNumberSpace(encLevel) - skipped, pn := pnSpace.pns.Pop() +func (h *sentPacketHandler) PopPacketNumber(space protocol.PacketNumberSpace) protocol.PacketNumber { + skipped, pn := h.pns.Pop(space == protocol.PacketNumberSpaceAppData) if skipped { skippedPN := pn - 1 - pnSpace.history.SkippedPacket(skippedPN) + h.hist.SkippedPacket(skippedPN) if h.logger.Debug() { h.logger.Debugf("Skipping packet number %d", skippedPN) } @@ -979,13 +1106,7 @@ func (h *sentPacketHandler) PopPacketNumber(encLevel protocol.EncryptionLevel) p } func (h *sentPacketHandler) SendMode(now monotime.Time) SendMode { - numTrackedPackets := h.appDataPackets.history.Len() - if h.initialPackets != nil { - numTrackedPackets += h.initialPackets.history.Len() - } - if h.handshakePackets != nil { - numTrackedPackets += h.handshakePackets.history.Len() - } + numTrackedPackets := h.hist.Len() if h.isAmplificationLimited() { h.logger.Debugf("Amplification window limited. Received %d bytes, already sent out %d bytes", h.bytesReceived, h.bytesSent) @@ -1038,16 +1159,15 @@ func (h *sentPacketHandler) isAmplificationLimited() bool { return h.bytesSent >= amplificationFactor*h.bytesReceived } -func (h *sentPacketHandler) QueueProbePacket(encLevel protocol.EncryptionLevel) bool { - pnSpace := h.getPacketNumberSpace(encLevel) - pn, p := pnSpace.history.FirstOutstanding() +func (h *sentPacketHandler) QueueProbePacket(space protocol.PacketNumberSpace) bool { + pn, p := h.hist.FirstOutstanding(space) if p == nil { return false } // TODO: don't declare the packet lost here. // Keep track of acknowledged frames instead. // Call DeclareLost before queueFramesForRetransmission, which clears the packet's frames. - pnSpace.history.DeclareLost(pn) + h.hist.DeclareLost(pn) h.removeFromBytesInFlight(p) h.queueFramesForRetransmission(p) return true @@ -1074,21 +1194,15 @@ func (h *sentPacketHandler) queueFramesForRetransmission(p *packet) { func (h *sentPacketHandler) ResetForRetry(now monotime.Time) { h.bytesInFlight = 0 var firstPacketSendTime monotime.Time - for _, p := range h.initialPackets.history.Packets() { - if firstPacketSendTime.IsZero() { + // Only Initial and 0-RTT packets can have been sent before a Retry. + for _, p := range h.hist.Packets() { + if p.EncryptionLevel == protocol.EncryptionInitial && firstPacketSendTime.IsZero() { firstPacketSendTime = p.SendTime } if p.IsAckEliciting() { h.queueFramesForRetransmission(p) } } - // All application data packets sent at this point are 0-RTT packets. - // In the case of a Retry, we can assume that the server dropped all of them. - for _, p := range h.appDataPackets.history.Packets() { - if p.IsAckEliciting() { - h.queueFramesForRetransmission(p) - } - } // Only use the Retry to estimate the RTT if we didn't send any retransmission for the Initial. // Otherwise, we don't know which Initial the Retry was sent in response to. @@ -1102,8 +1216,11 @@ func (h *sentPacketHandler) ResetForRetry(now monotime.Time) { h.qlogMetricsUpdated() } } - h.initialPackets = newPacketNumberSpace(h.initialPackets.pns.Peek(), false) - h.appDataPackets = newPacketNumberSpace(h.appDataPackets.pns.Peek(), true) + h.hist = *newSentPacketHistory() + h.handshakePNs.Initial = h.handshakePNs.Initial[:0] + h.handshakePNs.Handshake = h.handshakePNs.Handshake[:0] + h.initialPackets = newPacketNumberSpace() + h.appDataPackets = newPacketNumberSpace() oldAlarm := h.alarm h.alarm = alarmTimer{} if h.qlogger != nil { @@ -1119,8 +1236,15 @@ func (h *sentPacketHandler) ResetForRetry(now monotime.Time) { func (h *sentPacketHandler) MigratedPath(now monotime.Time, initialMaxDatagramSize protocol.ByteCount) { h.rttStats.ResetForPathMigration() - for pn, p := range h.appDataPackets.history.Packets() { - h.appDataPackets.history.DeclareLost(pn) + h.packetThresholdDisabled = false + h.timeThresholdEighths = defaultTimeThresholdEighths + h.minPNToRelaxReordering = protocol.InvalidPacketNumber + h.lostPackets.Reset() + for pn, p := range h.hist.Packets() { + if p.EncryptionLevel.PacketNumberSpace() != protocol.PacketNumberSpaceAppData { + continue + } + h.hist.DeclareLost(pn) if !p.isPathProbePacket { h.removeFromBytesInFlight(p) if p.IsAckEliciting() { @@ -1128,8 +1252,8 @@ func (h *sentPacketHandler) MigratedPath(now monotime.Time, initialMaxDatagramSi } } } - for pn := range h.appDataPackets.history.PathProbes() { - h.appDataPackets.history.RemovePathProbe(pn) + for pn := range h.hist.PathProbes() { + h.hist.RemovePathProbe(pn) } h.congestion = congestion.NewCubicSender( congestion.DefaultClock{}, @@ -1139,5 +1263,6 @@ func (h *sentPacketHandler) MigratedPath(now monotime.Time, initialMaxDatagramSi true, // use Reno h.qlogger, ) + h.qlogRecoveryParametersSet(true) h.setLossDetectionTimer(now) } diff --git a/vendor/github.com/quic-go/quic-go/internal/ackhandler/sent_packet_history.go b/vendor/github.com/quic-go/quic-go/internal/ackhandler/sent_packet_history.go index 102dd0068..8efe66f84 100644 --- a/vendor/github.com/quic-go/quic-go/internal/ackhandler/sent_packet_history.go +++ b/vendor/github.com/quic-go/quic-go/internal/ackhandler/sent_packet_history.go @@ -21,26 +21,24 @@ type sentPacketHistory struct { highestPacketNumber protocol.PacketNumber } -func newSentPacketHistory(isAppData bool) *sentPacketHistory { - h := &sentPacketHistory{ +func newSentPacketHistory() *sentPacketHistory { + return &sentPacketHistory{ + packets: make([]*packet, 0, 32), + skippedPackets: make([]protocol.PacketNumber, 0, maxSkippedPackets), highestPacketNumber: protocol.InvalidPacketNumber, firstPacketNumber: protocol.InvalidPacketNumber, } - if isAppData { - h.packets = make([]*packet, 0, 32) - h.skippedPackets = make([]protocol.PacketNumber, 0, maxSkippedPackets) - } else { - h.packets = make([]*packet, 0, 6) - } - return h } -func (h *sentPacketHistory) checkSequentialPacketNumberUse(pn protocol.PacketNumber) { +func (h *sentPacketHistory) checkPacketNumberUse(pn protocol.PacketNumber) { if h.highestPacketNumber != protocol.InvalidPacketNumber { - if pn != h.highestPacketNumber+1 { - panic("non-sequential packet number use") + if pn <= h.highestPacketNumber { + panic("non-increasing packet number use") } } + if len(h.packets) > 0 { + h.packets = append(h.packets, make([]*packet, pn-h.highestPacketNumber-1)...) + } h.highestPacketNumber = pn if len(h.packets) == 0 { h.firstPacketNumber = pn @@ -48,10 +46,6 @@ func (h *sentPacketHistory) checkSequentialPacketNumberUse(pn protocol.PacketNum } func (h *sentPacketHistory) SkippedPacket(pn protocol.PacketNumber) { - h.checkSequentialPacketNumberUse(pn) - if len(h.packets) > 0 { - h.packets = append(h.packets, nil) - } if len(h.skippedPackets) == maxSkippedPackets { h.skippedPackets = slices.Delete(h.skippedPackets, 0, 1) } @@ -59,7 +53,7 @@ func (h *sentPacketHistory) SkippedPacket(pn protocol.PacketNumber) { } func (h *sentPacketHistory) SentPacket(pn protocol.PacketNumber, p *packet) { - h.checkSequentialPacketNumberUse(pn) + h.checkPacketNumberUse(pn) h.packets = append(h.packets, p) if p.Outstanding() { h.numOutstanding++ @@ -67,8 +61,8 @@ func (h *sentPacketHistory) SentPacket(pn protocol.PacketNumber, p *packet) { } func (h *sentPacketHistory) SentPathProbePacket(pn protocol.PacketNumber, p *packet) { - h.checkSequentialPacketNumberUse(pn) - h.packets = append(h.packets, &packet{isPathProbePacket: true}) + h.checkPacketNumberUse(pn) + h.packets = append(h.packets, &packet{EncryptionLevel: p.EncryptionLevel, isPathProbePacket: true}) h.pathProbePackets = append(h.pathProbePackets, packetWithPacketNumber{PacketNumber: pn, packet: p}) } @@ -98,13 +92,13 @@ func (h *sentPacketHistory) PathProbes() iter.Seq2[protocol.PacketNumber, *packe } } -// FirstOutstanding returns the first outstanding packet. -func (h *sentPacketHistory) FirstOutstanding() (protocol.PacketNumber, *packet) { +// FirstOutstanding returns the first outstanding packet in the given packet number space. +func (h *sentPacketHistory) FirstOutstanding(space protocol.PacketNumberSpace) (protocol.PacketNumber, *packet) { if !h.HasOutstandingPackets() { return protocol.InvalidPacketNumber, nil } for i, p := range h.packets { - if p != nil && p.Outstanding() { + if p != nil && p.Outstanding() && p.EncryptionLevel.PacketNumberSpace() == space { return h.firstPacketNumber + protocol.PacketNumber(i), p } } @@ -210,6 +204,10 @@ func (h *sentPacketHistory) HasOutstandingPackets() bool { return h.numOutstanding > 0 } +func (h *sentPacketHistory) FirstPacketNumber() protocol.PacketNumber { + return h.firstPacketNumber +} + func (h *sentPacketHistory) HasOutstandingPathProbes() bool { return len(h.pathProbePackets) > 0 } diff --git a/vendor/github.com/quic-go/quic-go/internal/congestion/cubic_sender.go b/vendor/github.com/quic-go/quic-go/internal/congestion/cubic_sender.go index e5457ddb8..e398b046f 100644 --- a/vendor/github.com/quic-go/quic-go/internal/congestion/cubic_sender.go +++ b/vendor/github.com/quic-go/quic-go/internal/congestion/cubic_sender.go @@ -1,8 +1,6 @@ package congestion import ( - "fmt" - "github.com/quic-go/quic-go/internal/monotime" "github.com/quic-go/quic-go/internal/protocol" "github.com/quic-go/quic-go/internal/utils" @@ -20,6 +18,25 @@ const ( initialCongestionWindow = 32 ) +// renoUndoState saves Reno's state before the latest cutback. +type renoUndoState struct { + congestionWindow protocol.ByteCount + slowStartThreshold protocol.ByteCount + numAckedPackets uint64 + // Previous cutback's boundary; cubicSender holds the current boundary. + largestSentAtLastCutback protocol.PacketNumber + // Includes ECN events, which cannot be undone by spurious-loss reports. + numCongestionEvents uint64 +} + +func (s *renoUndoState) IsActive() bool { + return s.numCongestionEvents > 0 +} + +func (s *renoUndoState) Reset() { + *s = renoUndoState{} +} + type cubicSender struct { hybridSlowStart HybridSlowStart rttStats *utils.RTTStats @@ -36,7 +53,7 @@ type cubicSender struct { // Track the largest packet that has been acked. largestAckedPacketNumber protocol.PacketNumber - // Track the largest packet number outstanding when a CWND cutback occurs. + // Largest packet number sent when the latest CWND cutback occurred. largestSentAtLastCutback protocol.PacketNumber // Whether the last loss event caused us to exit slowstart. @@ -52,6 +69,9 @@ type cubicSender struct { // ACK counter for the Reno implementation. numAckedPackets uint64 + // Retained after recovery, since spurious losses can be reported later. + undoState renoUndoState + initialCongestionWindow protocol.ByteCount initialMaxCongestionWindow protocol.ByteCount @@ -108,12 +128,13 @@ func newCubicSender( congestionWindow: initialCongestionWindow, slowStartThreshold: protocol.MaxByteCount, cubic: NewCubic(clock), + pacer: newPacer(), clock: clock, reno: reno, qlogger: qlogger, maxDatagramSize: initialMaxDatagramSize, } - c.pacer = newPacer(c.BandwidthEstimate) + c.connStats.CongestionWindow.Store(uint64(c.congestionWindow)) if c.qlogger != nil { c.lastState = qlog.CongestionStateSlowStart c.qlogger.RecordEvent(qlog.CongestionStateUpdated{ @@ -125,11 +146,11 @@ func newCubicSender( // TimeUntilSend returns when the next packet should be sent. func (c *cubicSender) TimeUntilSend(_ protocol.ByteCount) monotime.Time { - return c.pacer.TimeUntilSend() + return c.pacer.TimeUntilSend(c.pacingRate()) } func (c *cubicSender) HasPacingBudget(now monotime.Time) bool { - return c.pacer.Budget(now) >= c.maxDatagramSize + return c.pacer.Budget(now, c.pacingRate()) >= c.maxDatagramSize } func (c *cubicSender) maxCongestionWindow() protocol.ByteCount { @@ -147,7 +168,7 @@ func (c *cubicSender) OnPacketSent( bytes protocol.ByteCount, isRetransmittable bool, ) { - c.pacer.SentPacket(sentTime, bytes) + c.pacer.SentPacket(sentTime, bytes, c.pacingRate()) if !isRetransmittable { return } @@ -191,6 +212,7 @@ func (c *cubicSender) OnPacketAcked( return } c.maybeIncreaseCwnd(ackedPacketNumber, ackedBytes, priorInFlight, eventTime) + c.connStats.CongestionWindow.Store(uint64(c.congestionWindow)) if c.InSlowStart() { c.hybridSlowStart.OnPacketAcked(ackedPacketNumber) } @@ -203,8 +225,22 @@ func (c *cubicSender) OnCongestionEvent(packetNumber protocol.PacketNumber, lost // TCP NewReno (RFC6582) says that once a loss occurs, any losses in packets // already sent should be treated as a single loss event, since it's expected. if packetNumber <= c.largestSentAtLastCutback { + // Older events are already accounted for in the saved congestion window. + if c.undoState.IsActive() && packetNumber > c.undoState.largestSentAtLastCutback { + c.undoState.numCongestionEvents++ + } return } + if c.reno { + c.undoState = renoUndoState{ + congestionWindow: c.congestionWindow, + slowStartThreshold: c.slowStartThreshold, + numAckedPackets: c.numAckedPackets, + largestSentAtLastCutback: c.largestSentAtLastCutback, + numCongestionEvents: 1, + } + } + c.lastCutbackExitedSlowstart = c.InSlowStart() c.maybeQlogStateChange(qlog.CongestionStateRecovery) @@ -216,6 +252,7 @@ func (c *cubicSender) OnCongestionEvent(packetNumber protocol.PacketNumber, lost if minCwnd := c.minCongestionWindow(); c.congestionWindow < minCwnd { c.congestionWindow = minCwnd } + c.connStats.CongestionWindow.Store(uint64(c.congestionWindow)) c.slowStartThreshold = c.congestionWindow c.largestSentAtLastCutback = c.largestSentPacketNumber // reset packet count from congestion avoidance mode. We start @@ -223,6 +260,40 @@ func (c *cubicSender) OnCongestionEvent(packetNumber protocol.PacketNumber, lost c.numAckedPackets = 0 } +func (c *cubicSender) OnSpuriousLoss(packetNumber protocol.PacketNumber) { + if !c.undoState.IsActive() { + return + } + // only losses counted for this cutback can undo it + if packetNumber <= c.undoState.largestSentAtLastCutback || packetNumber > c.largestSentAtLastCutback { + return + } + c.undoState.numCongestionEvents-- + if c.undoState.numCongestionEvents > 0 { + return + } + + state := c.undoState + c.undoState.Reset() + // Regaining the old window usually takes multiple RTTs, making a spurious-loss report this late unlikely. + if c.congestionWindow > state.congestionWindow { + return + } + c.congestionWindow = state.congestionWindow + c.slowStartThreshold = state.slowStartThreshold + c.numAckedPackets = state.numAckedPackets + c.largestSentAtLastCutback = state.largestSentAtLastCutback + c.connStats.CongestionWindow.Store(uint64(c.congestionWindow)) + switch { + case c.InRecovery(): + c.maybeQlogStateChange(qlog.CongestionStateRecovery) + case c.InSlowStart(): + c.maybeQlogStateChange(qlog.CongestionStateSlowStart) + default: + c.maybeQlogStateChange(qlog.CongestionStateCongestionAvoidance) + } +} + // Called when we receive an ack. Normal TCP tracks how many packets one ack // represents, but quic has a separate ack for each packet. func (c *cubicSender) maybeIncreaseCwnd( @@ -284,9 +355,19 @@ func (c *cubicSender) BandwidthEstimate() Bandwidth { return BandwidthFromDelta(c.GetCongestionWindow(), srtt) } +func (c *cubicSender) pacingRate() Bandwidth { + if c.InSlowStart() { + // Allow slow start to double the sending rate every RTT. + return 2 * c.BandwidthEstimate() + } + // Allow for RTT variations when filling the congestion window. + return c.BandwidthEstimate() * 5 / 4 +} + // OnRetransmissionTimeout is called on an retransmission timeout func (c *cubicSender) OnRetransmissionTimeout(packetsRetransmitted bool) { c.largestSentAtLastCutback = protocol.InvalidPacketNumber + c.undoState.Reset() if !packetsRetransmitted { return } @@ -294,6 +375,7 @@ func (c *cubicSender) OnRetransmissionTimeout(packetsRetransmitted bool) { c.cubic.Reset() c.slowStartThreshold = c.congestionWindow / 2 c.congestionWindow = c.minCongestionWindow() + c.connStats.CongestionWindow.Store(uint64(c.congestionWindow)) } // OnConnectionMigration is called when the connection is migrated (?) @@ -302,10 +384,12 @@ func (c *cubicSender) OnConnectionMigration() { c.largestSentPacketNumber = protocol.InvalidPacketNumber c.largestAckedPacketNumber = protocol.InvalidPacketNumber c.largestSentAtLastCutback = protocol.InvalidPacketNumber + c.undoState.Reset() c.lastCutbackExitedSlowstart = false c.cubic.Reset() c.numAckedPackets = 0 c.congestionWindow = c.initialCongestionWindow + c.connStats.CongestionWindow.Store(uint64(c.congestionWindow)) c.slowStartThreshold = c.initialMaxCongestionWindow } @@ -318,13 +402,11 @@ func (c *cubicSender) maybeQlogStateChange(new qlog.CongestionState) { } func (c *cubicSender) SetMaxDatagramSize(s protocol.ByteCount) { - if s < c.maxDatagramSize { - panic(fmt.Sprintf("congestion BUG: decreased max datagram size from %d to %d", c.maxDatagramSize, s)) - } cwndIsMinCwnd := c.congestionWindow == c.minCongestionWindow() c.maxDatagramSize = s if cwndIsMinCwnd { c.congestionWindow = c.minCongestionWindow() + c.connStats.CongestionWindow.Store(uint64(c.congestionWindow)) } c.pacer.SetMaxDatagramSize(s) } diff --git a/vendor/github.com/quic-go/quic-go/internal/congestion/interface.go b/vendor/github.com/quic-go/quic-go/internal/congestion/interface.go index 996907c61..ab54a8988 100644 --- a/vendor/github.com/quic-go/quic-go/internal/congestion/interface.go +++ b/vendor/github.com/quic-go/quic-go/internal/congestion/interface.go @@ -14,6 +14,7 @@ type SendAlgorithm interface { MaybeExitSlowStart() OnPacketAcked(number protocol.PacketNumber, ackedBytes protocol.ByteCount, priorInFlight protocol.ByteCount, eventTime monotime.Time) OnCongestionEvent(number protocol.PacketNumber, lostBytes protocol.ByteCount, priorInFlight protocol.ByteCount) + OnSpuriousLoss(number protocol.PacketNumber) OnRetransmissionTimeout(packetsRetransmitted bool) SetMaxDatagramSize(protocol.ByteCount) } diff --git a/vendor/github.com/quic-go/quic-go/internal/congestion/pacer.go b/vendor/github.com/quic-go/quic-go/internal/congestion/pacer.go index 7656f5296..58b03b51d 100644 --- a/vendor/github.com/quic-go/quic-go/internal/congestion/pacer.go +++ b/vendor/github.com/quic-go/quic-go/internal/congestion/pacer.go @@ -10,33 +10,26 @@ import ( const maxBurstSizePackets = 10 +// minPacingDelay is the minimum duration that is used for packet pacing +// If the packet packing frequency is higher, multiple packets might be sent at once. +// Example: For a packet pacing delay of 200μs, we would send 5 packets at once, wait for 1ms, and so forth. +const minPacingDelay = time.Millisecond + // The pacer implements a token bucket pacing algorithm. type pacer struct { - budgetAtLastSent protocol.ByteCount - maxDatagramSize protocol.ByteCount - lastSentTime monotime.Time - adjustedBandwidth func() uint64 // in bytes/s + budgetAtLastSent protocol.ByteCount + maxDatagramSize protocol.ByteCount + lastSentTime monotime.Time } -func newPacer(getBandwidth func() Bandwidth) *pacer { - p := &pacer{ - maxDatagramSize: initialMaxDatagramSize, - adjustedBandwidth: func() uint64 { - // Bandwidth is in bits/s. We need the value in bytes/s. - bw := uint64(getBandwidth() / BytesPerSecond) - // Use a slightly higher value than the actual measured bandwidth. - // RTT variations then won't result in under-utilization of the congestion window. - // Ultimately, this will result in sending packets as acknowledgments are received rather than when timers fire, - // provided the congestion window is fully utilized and acknowledgments arrive at regular intervals. - return bw * 5 / 4 - }, +func newPacer() *pacer { + return &pacer{ + maxDatagramSize: protocol.InitialPacketSize, } - p.budgetAtLastSent = p.maxBurstSize() - return p } -func (p *pacer) SentPacket(sendTime monotime.Time, size protocol.ByteCount) { - budget := p.Budget(sendTime) +func (p *pacer) SentPacket(sendTime monotime.Time, size protocol.ByteCount, rate Bandwidth) { + budget := p.Budget(sendTime, rate) if size >= budget { p.budgetAtLastSent = 0 } else { @@ -45,38 +38,39 @@ func (p *pacer) SentPacket(sendTime monotime.Time, size protocol.ByteCount) { p.lastSentTime = sendTime } -func (p *pacer) Budget(now monotime.Time) protocol.ByteCount { +func (p *pacer) Budget(now monotime.Time, rate Bandwidth) protocol.ByteCount { if p.lastSentTime.IsZero() { - return p.maxBurstSize() + return p.maxBurstSize(rate) } delta := now.Sub(p.lastSentTime) var added protocol.ByteCount if delta > 0 { - added = p.timeScaledBandwidth(uint64(delta.Nanoseconds())) + added = p.timeScaledBandwidth(delta, rate) } budget := p.budgetAtLastSent + added if added > 0 && budget < p.budgetAtLastSent { budget = protocol.MaxByteCount } - return min(p.maxBurstSize(), budget) + return min(p.maxBurstSize(rate), budget) } -func (p *pacer) maxBurstSize() protocol.ByteCount { +func (p *pacer) maxBurstSize(rate Bandwidth) protocol.ByteCount { return max( - p.timeScaledBandwidth(uint64((protocol.MinPacingDelay + protocol.TimerGranularity).Nanoseconds())), + p.timeScaledBandwidth(minPacingDelay+protocol.TimerGranularity, rate), maxBurstSizePackets*p.maxDatagramSize, ) } // timeScaledBandwidth calculates the number of bytes that may be sent within -// a given time interval (ns nanoseconds), based on the current bandwidth estimate. +// a given duration, based on the current pacing rate. // It caps the scaled value to the maximum allowed burst and handles overflows. -func (p *pacer) timeScaledBandwidth(ns uint64) protocol.ByteCount { - bw := p.adjustedBandwidth() +func (p *pacer) timeScaledBandwidth(d time.Duration, rate Bandwidth) protocol.ByteCount { + bw := uint64(rate / BytesPerSecond) if bw == 0 { return 0 } const nsPerSecond = 1e9 + ns := uint64(d) maxBurst := maxBurstSizePackets * p.maxDatagramSize var scaled protocol.ByteCount if ns > math.MaxUint64/bw { @@ -89,12 +83,12 @@ func (p *pacer) timeScaledBandwidth(ns uint64) protocol.ByteCount { // TimeUntilSend returns when the next packet should be sent. // It returns zero if a packet can be sent immediately. -func (p *pacer) TimeUntilSend() monotime.Time { - if p.budgetAtLastSent >= p.maxDatagramSize { +func (p *pacer) TimeUntilSend(rate Bandwidth) monotime.Time { + if p.lastSentTime.IsZero() || p.budgetAtLastSent >= p.maxDatagramSize { return 0 } diff := 1e9 * uint64(p.maxDatagramSize-p.budgetAtLastSent) - bw := p.adjustedBandwidth() + bw := uint64(rate / BytesPerSecond) // We might need to round up this value. // Otherwise, we might have a budget (slightly) smaller than the datagram size when the timer expires. d := diff / bw @@ -102,7 +96,7 @@ func (p *pacer) TimeUntilSend() monotime.Time { if diff%bw > 0 { d++ } - return p.lastSentTime.Add(max(protocol.MinPacingDelay, time.Duration(d)*time.Nanosecond)) + return p.lastSentTime.Add(max(minPacingDelay, time.Duration(d)*time.Nanosecond)) } func (p *pacer) SetMaxDatagramSize(s protocol.ByteCount) { diff --git a/vendor/github.com/quic-go/quic-go/internal/handshake/updatable_aead.go b/vendor/github.com/quic-go/quic-go/internal/handshake/updatable_aead.go index f88f76ad8..902f8ce4a 100644 --- a/vendor/github.com/quic-go/quic-go/internal/handshake/updatable_aead.go +++ b/vendor/github.com/quic-go/quic-go/internal/handshake/updatable_aead.go @@ -16,10 +16,13 @@ import ( "github.com/quic-go/quic-go/qlogwriter" ) +// defaultKeyUpdateInterval is the maximum number of packets we send or receive before initiating a key update. +const defaultKeyUpdateInterval = 100 * 1000 + var keyUpdateInterval atomic.Uint64 func init() { - keyUpdateInterval.Store(protocol.KeyUpdateInterval) + keyUpdateInterval.Store(defaultKeyUpdateInterval) } func SetKeyUpdateInterval(v uint64) (reset func()) { diff --git a/vendor/github.com/quic-go/quic-go/internal/protocol/encryption_level.go b/vendor/github.com/quic-go/quic-go/internal/protocol/encryption_level.go index 40aa331aa..f5c2878ab 100644 --- a/vendor/github.com/quic-go/quic-go/internal/protocol/encryption_level.go +++ b/vendor/github.com/quic-go/quic-go/internal/protocol/encryption_level.go @@ -5,6 +5,15 @@ import ( "fmt" ) +// PacketNumberSpace is a QUIC packet number space. +type PacketNumberSpace uint8 + +const ( + PacketNumberSpaceInitial PacketNumberSpace = iota + PacketNumberSpaceHandshake + PacketNumberSpaceAppData +) + // EncryptionLevel is the encryption level // Default value is Unencrypted type EncryptionLevel uint8 @@ -34,6 +43,19 @@ func (e EncryptionLevel) String() string { return "unknown" } +func (e EncryptionLevel) PacketNumberSpace() PacketNumberSpace { + switch e { + case EncryptionInitial: + return PacketNumberSpaceInitial + case EncryptionHandshake: + return PacketNumberSpaceHandshake + case Encryption0RTT, Encryption1RTT: + return PacketNumberSpaceAppData + default: + panic("invalid encryption level") + } +} + func (e EncryptionLevel) ToTLSEncryptionLevel() tls.QUICEncryptionLevel { switch e { case EncryptionInitial: diff --git a/vendor/github.com/quic-go/quic-go/internal/protocol/params.go b/vendor/github.com/quic-go/quic-go/internal/protocol/params.go index 77657eb27..ce89ffe5c 100644 --- a/vendor/github.com/quic-go/quic-go/internal/protocol/params.go +++ b/vendor/github.com/quic-go/quic-go/internal/protocol/params.go @@ -42,13 +42,6 @@ const MaxServerUnprocessedPackets = 1024 // MaxConnUnprocessedPackets is the max number of packets stored in each connection that are not yet processed. const MaxConnUnprocessedPackets = 256 -// SkipPacketInitialPeriod is the initial period length used for packet number skipping to prevent an Optimistic ACK attack. -// Every time a packet number is skipped, the period is doubled, up to SkipPacketMaxPeriod. -const SkipPacketInitialPeriod PacketNumber = 256 - -// SkipPacketMaxPeriod is the maximum period length used for packet number skipping. -const SkipPacketMaxPeriod PacketNumber = 128 * 1024 - // MaxAcceptQueueSize is the maximum number of connections that the server queues for accepting. // If the queue is full, new connection attempts will be rejected. const MaxAcceptQueueSize = 32 @@ -102,10 +95,6 @@ const DefaultHandshakeIdleTimeout = 5 * time.Second // 2. it reduces the head-of-line blocking, when a packet is lost const MinStreamFrameSize ByteCount = 128 -// MaxPostHandshakeCryptoFrameSize is the maximum size of CRYPTO frames -// we send after the handshake completes. -const MaxPostHandshakeCryptoFrameSize = 1000 - // MaxNumAckRanges is the maximum number of ACK ranges that we send in an ACK frame. // It also serves as a limit for the packet history. // If at any point we keep track of more ranges, old ranges are discarded. @@ -114,11 +103,6 @@ const MaxPostHandshakeCryptoFrameSize = 1000 // in a single byte varint. const MaxNumAckRanges = 64 -// MinPacingDelay is the minimum duration that is used for packet pacing -// If the packet packing frequency is higher, multiple packets might be sent at once. -// Example: For a packet pacing delay of 200μs, we would send 5 packets at once, wait for 1ms, and so forth. -const MinPacingDelay = time.Millisecond - // DefaultConnectionIDLength is the connection ID length that is used for multiplexed connections // if no other value is configured. const DefaultConnectionIDLength = 4 @@ -139,25 +123,3 @@ const AckDelayExponent = 3 // Estimated timer granularity. // The loss detection timer will not be set to a value smaller than granularity. const TimerGranularity = time.Millisecond - -// MaxAckDelay is the maximum time by which we delay sending ACKs. -const MaxAckDelay = 25 * time.Millisecond - -// MaxAckDelayInclGranularity is the max_ack_delay including the timer granularity. -// This is the value that should be advertised to the peer. -const MaxAckDelayInclGranularity = MaxAckDelay + TimerGranularity - -// KeyUpdateInterval is the maximum number of packets we send or receive before initiating a key update. -const KeyUpdateInterval = 100 * 1000 - -// Max0RTTQueueingDuration is the maximum time that we store 0-RTT packets in order to wait for the corresponding Initial to be received. -const Max0RTTQueueingDuration = 100 * time.Millisecond - -// Max0RTTQueues is the maximum number of connections that we buffer 0-RTT packets for. -const Max0RTTQueues = 32 - -// Max0RTTQueueLen is the maximum number of 0-RTT packets that we buffer for each connection. -// When a new connection is created, all buffered packets are passed to the connection immediately. -// To avoid blocking, this value has to be smaller than MaxConnUnprocessedPackets. -// To avoid packets being dropped as undecryptable by the connection, this value has to be smaller than MaxUndecryptablePackets. -const Max0RTTQueueLen = 31 diff --git a/vendor/github.com/quic-go/quic-go/internal/utils/connstats.go b/vendor/github.com/quic-go/quic-go/internal/utils/connstats.go index 19d883126..878b7ee49 100644 --- a/vendor/github.com/quic-go/quic-go/internal/utils/connstats.go +++ b/vendor/github.com/quic-go/quic-go/internal/utils/connstats.go @@ -5,6 +5,8 @@ import "sync/atomic" // ConnectionStats stores stats for the connection. See the public // ConnectionStats struct in connection.go for more information type ConnectionStats struct { + CongestionWindow atomic.Uint64 + BytesSent atomic.Uint64 PacketsSent atomic.Uint64 BytesReceived atomic.Uint64 diff --git a/vendor/github.com/quic-go/quic-go/internal/utils/rand.go b/vendor/github.com/quic-go/quic-go/internal/utils/rand.go index 30069144a..c4a8fa42b 100644 --- a/vendor/github.com/quic-go/quic-go/internal/utils/rand.go +++ b/vendor/github.com/quic-go/quic-go/internal/utils/rand.go @@ -10,20 +10,26 @@ type Rand struct { buf [4]byte } -func (r *Rand) Int31() int32 { +func (r *Rand) Uint32() uint32 { rand.Read(r.buf[:]) - return int32(binary.BigEndian.Uint32(r.buf[:]) & ^uint32(1<<31)) + return binary.BigEndian.Uint32(r.buf[:]) } -// copied from the standard library math/rand implementation of Int63n -func (r *Rand) Int31n(n int32) int32 { - if n&(n-1) == 0 { // n is power of two, can mask - return r.Int31() & (n - 1) +// copied from https://go.dev/src/internal/fuzz/pcg.go#L110. +func (r *Rand) Uint32N(n uint32) uint32 { + if n == 0 { + panic("invalid argument to Uint32N") } - max := int32((1 << 31) - 1 - (1<<31)%uint32(n)) - v := r.Int31() - for v > max { - v = r.Int31() + v := r.Uint32() + prod := uint64(v) * uint64(n) + low := uint32(prod) + if low < n { + thresh := uint32(-int32(n)) % n + for low < thresh { + v = r.Uint32() + prod = uint64(v) * uint64(n) + low = uint32(prod) + } } - return v % n + return uint32(prod >> 32) } diff --git a/vendor/github.com/quic-go/quic-go/mtu_discoverer.go b/vendor/github.com/quic-go/quic-go/mtu_discoverer.go index 76b28e726..3b43e85ef 100644 --- a/vendor/github.com/quic-go/quic-go/mtu_discoverer.go +++ b/vendor/github.com/quic-go/quic-go/mtu_discoverer.go @@ -168,9 +168,9 @@ func (f *mtuFinder) CurrentSize() protocol.ByteCount { return f.min } -func (f *mtuFinder) Reset(now monotime.Time, start, max protocol.ByteCount) { +func (f *mtuFinder) Reset(start, max protocol.ByteCount) { f.generation++ - f.lastProbeTime = now + f.lastProbeTime = 0 f.lastProbeWasLost = false f.inFlight = protocol.InvalidByteCount f.init(start, max) diff --git a/vendor/github.com/quic-go/quic-go/packet_packer.go b/vendor/github.com/quic-go/quic-go/packet_packer.go index 332e23e69..3e948a8c5 100644 --- a/vendor/github.com/quic-go/quic-go/packet_packer.go +++ b/vendor/github.com/quic-go/quic-go/packet_packer.go @@ -13,6 +13,8 @@ import ( "github.com/quic-go/quic-go/internal/protocol" "github.com/quic-go/quic-go/internal/qerr" "github.com/quic-go/quic-go/internal/wire" + "github.com/quic-go/quic-go/qlog" + "github.com/quic-go/quic-go/qlogwriter" ) var errNothingToPack = errors.New("nothing to pack") @@ -95,8 +97,8 @@ func (p *longHeaderPacket) EncryptionLevel() protocol.EncryptionLevel { func (p *longHeaderPacket) IsAckEliciting() bool { return ackhandler.HasAckElicitingFrames(p.frames) } type packetNumberManager interface { - PeekPacketNumber(protocol.EncryptionLevel) (protocol.PacketNumber, protocol.PacketNumberLen) - PopPacketNumber(protocol.EncryptionLevel) protocol.PacketNumber + PeekPacketNumber(protocol.PacketNumberSpace) (protocol.PacketNumber, protocol.PacketNumberLen) + PopPacketNumber(protocol.PacketNumberSpace) protocol.PacketNumber } type sealingManager interface { @@ -135,6 +137,7 @@ type packetPacker struct { rand rand.Rand numNonAckElicitingAcks int + qlogger qlogwriter.Recorder } var _ packer = &packetPacker{} @@ -151,6 +154,7 @@ func newPacketPacker( acks ackFrameSource, datagramQueue *datagramQueue, perspective protocol.Perspective, + qlogger qlogwriter.Recorder, ) *packetPacker { var b [16]byte _, _ = crand.Read(b[:]) @@ -168,6 +172,7 @@ func newPacketPacker( acks: acks, rand: *rand.New(rand.NewPCG(binary.BigEndian.Uint64(b[:8]), binary.BigEndian.Uint64(b[8:]))), pnManager: packetNumberManager, + qlogger: qlogger, } } @@ -252,16 +257,22 @@ func (p *packetPacker) packConnectionClose( var hdr *wire.ExtendedHeader if encLevel == protocol.Encryption1RTT { connID = p.getDestConnID() - oneRTTPacketNumber, oneRTTPacketNumberLen = p.pnManager.PeekPacketNumber(protocol.Encryption1RTT) + oneRTTPacketNumber, oneRTTPacketNumberLen = p.pnManager.PeekPacketNumber(protocol.PacketNumberSpaceAppData) size += p.shortHeaderPacketLength(connID, oneRTTPacketNumberLen, pl) + protocol.ByteCount(sealer.Overhead()) } else { hdr = p.getLongHeader(encLevel, v) + if pn := p.pnManager.PopPacketNumber(encLevel.PacketNumberSpace()); pn != hdr.PacketNumber { + return nil, fmt.Errorf("packetPacker BUG: Peeked and Popped packet numbers do not match: expected %d, got %d", hdr.PacketNumber, pn) + } hdrs[i] = hdr size += p.longHeaderPacketLength(hdr, pl, v) + protocol.ByteCount(sealer.Overhead()) numLongHdrPackets++ } payloads[i] = pl } + if size > maxPacketSize { + return nil, fmt.Errorf("packet too large (%d bytes, allowed %d bytes)", size, maxPacketSize) + } buffer := getPacketBuffer() packet := &coalescedPacket{ buffer: buffer, @@ -282,7 +293,7 @@ func (p *packetPacker) packConnectionClose( if encLevel == protocol.EncryptionInitial { paddingLen = p.initialPaddingLen(payloads[i].frames, size, maxPacketSize) } - longHdrPacket, err := p.appendLongHeaderPacket(buffer, hdrs[i], payloads[i], paddingLen, encLevel, sealers[i], v) + longHdrPacket, err := p.appendLongHeaderPacket(buffer, hdrs[i], payloads[i], paddingLen, sealers[i], v) if err != nil { return nil, err } @@ -353,6 +364,10 @@ func (p *packetPacker) PackCoalescedPacket(onlyAck bool, maxSize protocol.ByteCo v, ) if initialPayload.length > 0 { + // reserve the number before preparing the next coalesced packet + if pn := p.pnManager.PopPacketNumber(protocol.PacketNumberSpaceInitial); pn != initialHdr.PacketNumber { + return nil, fmt.Errorf("packetPacker BUG: Peeked and Popped packet numbers do not match: expected %d, got %d", initialHdr.PacketNumber, pn) + } size += p.longHeaderPacketLength(initialHdr, initialPayload, v) + protocol.ByteCount(initialSealer.Overhead()) } } @@ -375,6 +390,9 @@ func (p *packetPacker) PackCoalescedPacket(onlyAck bool, maxSize protocol.ByteCo v, ) if handshakePayload.length > 0 { + if pn := p.pnManager.PopPacketNumber(protocol.PacketNumberSpaceHandshake); pn != handshakeHdr.PacketNumber { + return nil, fmt.Errorf("packetPacker BUG: Peeked and Popped packet numbers do not match: expected %d, got %d", handshakeHdr.PacketNumber, pn) + } s := p.longHeaderPacketLength(handshakeHdr, handshakePayload, v) + protocol.ByteCount(handshakeSealer.Overhead()) size += s } @@ -395,7 +413,7 @@ func (p *packetPacker) PackCoalescedPacket(onlyAck bool, maxSize protocol.ByteCo if err == nil { // 1-RTT kp = oneRTTSealer.KeyPhase() connID = p.getDestConnID() - oneRTTPacketNumber, oneRTTPacketNumberLen = p.pnManager.PeekPacketNumber(protocol.Encryption1RTT) + oneRTTPacketNumber, oneRTTPacketNumberLen = p.pnManager.PeekPacketNumber(protocol.PacketNumberSpaceAppData) hdrLen := wire.ShortHeaderLen(connID, oneRTTPacketNumberLen) oneRTTPayload = p.maybeGetShortHeaderPacket(oneRTTSealer, hdrLen, maxSize-size, onlyAck, now, v) if oneRTTPayload.length > 0 { @@ -410,6 +428,9 @@ func (p *packetPacker) PackCoalescedPacket(onlyAck bool, maxSize protocol.ByteCo if zeroRTTSealer != nil { zeroRTTHdr, zeroRTTPayload = p.maybeGetAppDataPacketFor0RTT(zeroRTTSealer, maxSize-size, now, v) if zeroRTTPayload.length > 0 { + if pn := p.pnManager.PopPacketNumber(protocol.PacketNumberSpaceAppData); pn != zeroRTTHdr.PacketNumber { + return nil, fmt.Errorf("packetPacker BUG: Peeked and Popped packet numbers do not match: expected %d, got %d", zeroRTTHdr.PacketNumber, pn) + } size += p.longHeaderPacketLength(zeroRTTHdr, zeroRTTPayload, v) + protocol.ByteCount(zeroRTTSealer.Overhead()) } } @@ -420,6 +441,9 @@ func (p *packetPacker) PackCoalescedPacket(onlyAck bool, maxSize protocol.ByteCo return nil, nil } + if size > maxSize { + return nil, fmt.Errorf("packet too large (%d bytes, allowed %d bytes)", size, maxSize) + } buffer := getPacketBuffer() packet := &coalescedPacket{ buffer: buffer, @@ -427,21 +451,21 @@ func (p *packetPacker) PackCoalescedPacket(onlyAck bool, maxSize protocol.ByteCo } if initialPayload.length > 0 { padding := p.initialPaddingLen(initialPayload.frames, size, maxSize) - cont, err := p.appendLongHeaderPacket(buffer, initialHdr, initialPayload, padding, protocol.EncryptionInitial, initialSealer, v) + cont, err := p.appendLongHeaderPacket(buffer, initialHdr, initialPayload, padding, initialSealer, v) if err != nil { return nil, err } packet.longHdrPackets = append(packet.longHdrPackets, cont) } if handshakePayload.length > 0 { - cont, err := p.appendLongHeaderPacket(buffer, handshakeHdr, handshakePayload, 0, protocol.EncryptionHandshake, handshakeSealer, v) + cont, err := p.appendLongHeaderPacket(buffer, handshakeHdr, handshakePayload, 0, handshakeSealer, v) if err != nil { return nil, err } packet.longHdrPackets = append(packet.longHdrPackets, cont) } if zeroRTTPayload.length > 0 { - longHdrPacket, err := p.appendLongHeaderPacket(buffer, zeroRTTHdr, zeroRTTPayload, 0, protocol.Encryption0RTT, zeroRTTSealer, v) + longHdrPacket, err := p.appendLongHeaderPacket(buffer, zeroRTTHdr, zeroRTTPayload, 0, zeroRTTSealer, v) if err != nil { return nil, err } @@ -481,7 +505,7 @@ func (p *packetPacker) appendPacket( if err != nil { return shortHeaderPacket{}, err } - pn, pnLen := p.pnManager.PeekPacketNumber(protocol.Encryption1RTT) + pn, pnLen := p.pnManager.PeekPacketNumber(protocol.PacketNumberSpaceAppData) connID := p.getDestConnID() hdrLen := wire.ShortHeaderLen(connID, pnLen) pl := p.maybeGetShortHeaderPacket(sealer, hdrLen, maxPacketSize, onlyAck, now, v) @@ -662,6 +686,13 @@ func (p *packetPacker) composeNextPacket( // Discard this frame. There's no point in retrying this in the next packet, // as it's unlikely that the available packet size will increase. p.datagramQueue.Pop() + if p.qlogger != nil { + p.qlogger.RecordEvent(qlog.DatagramDropped{ + Direction: qlog.DirectionSending, + Raw: qlog.RawInfo{Length: len(f.Data)}, + Trigger: "too_large", + }) + } } // If the DATAGRAM frame was too large and the packet contained an ACK, we'll try to send it out later. } @@ -749,15 +780,21 @@ func (p *packetPacker) PackPTOProbePacket( if pl.length == 0 { return nil, nil } + if pn := p.pnManager.PopPacketNumber(encLevel.PacketNumberSpace()); pn != hdr.PacketNumber { + return nil, fmt.Errorf("packetPacker BUG: Peeked and Popped packet numbers do not match: expected %d, got %d", hdr.PacketNumber, pn) + } + size := p.longHeaderPacketLength(hdr, pl, v) + protocol.ByteCount(sealer.Overhead()) + if size > maxPacketSize { + return nil, fmt.Errorf("packet too large (%d bytes, allowed %d bytes)", size, maxPacketSize) + } buffer := getPacketBuffer() packet := &coalescedPacket{buffer: buffer} - size := p.longHeaderPacketLength(hdr, pl, v) + protocol.ByteCount(sealer.Overhead()) var padding protocol.ByteCount if encLevel == protocol.EncryptionInitial { padding = p.initialPaddingLen(pl.frames, size, maxPacketSize) } - longHdrPacket, err := p.appendLongHeaderPacket(buffer, hdr, pl, padding, encLevel, sealer, v) + longHdrPacket, err := p.appendLongHeaderPacket(buffer, hdr, pl, padding, sealer, v) if err != nil { return nil, err } @@ -772,7 +809,7 @@ func (p *packetPacker) packPTOProbePacket1RTT(maxPacketSize protocol.ByteCount, } kp := s.KeyPhase() connID := p.getDestConnID() - pn, pnLen := p.pnManager.PeekPacketNumber(protocol.Encryption1RTT) + pn, pnLen := p.pnManager.PeekPacketNumber(protocol.PacketNumberSpaceAppData) hdrLen := wire.ShortHeaderLen(connID, pnLen) pl := p.maybeGetAppDataPacket(maxPacketSize-protocol.ByteCount(s.Overhead())-hdrLen, false, true, now, v) if pl.length == 0 { @@ -804,7 +841,7 @@ func (p *packetPacker) PackMTUProbePacket(ping ackhandler.Frame, size protocol.B return shortHeaderPacket{}, nil, err } connID := p.getDestConnID() - pn, pnLen := p.pnManager.PeekPacketNumber(protocol.Encryption1RTT) + pn, pnLen := p.pnManager.PeekPacketNumber(protocol.PacketNumberSpaceAppData) padding := size - p.shortHeaderPacketLength(connID, pnLen, pl) - protocol.ByteCount(s.Overhead()) kp := s.KeyPhase() packet, err := p.appendShortHeaderPacket(buffer, connID, pn, pnLen, kp, pl, padding, size, s, true, v) @@ -812,7 +849,7 @@ func (p *packetPacker) PackMTUProbePacket(ping ackhandler.Frame, size protocol.B } func (p *packetPacker) PackPathProbePacket(connID protocol.ConnectionID, frames []ackhandler.Frame, v protocol.Version) (shortHeaderPacket, *packetBuffer, error) { - pn, pnLen := p.pnManager.PeekPacketNumber(protocol.Encryption1RTT) + pn, pnLen := p.pnManager.PeekPacketNumber(protocol.PacketNumberSpaceAppData) buf := getPacketBuffer() s, err := p.cryptoSetup.Get1RTTSealer() if err != nil { @@ -836,7 +873,7 @@ func (p *packetPacker) PackPathProbePacket(connID protocol.ConnectionID, frames } func (p *packetPacker) getLongHeader(encLevel protocol.EncryptionLevel, v protocol.Version) *wire.ExtendedHeader { - pn, pnLen := p.pnManager.PeekPacketNumber(encLevel) + pn, pnLen := p.pnManager.PeekPacketNumber(encLevel.PacketNumberSpace()) hdr := &wire.ExtendedHeader{ PacketNumber: pn, PacketNumberLen: pnLen, @@ -858,7 +895,7 @@ func (p *packetPacker) getLongHeader(encLevel protocol.EncryptionLevel, v protoc return hdr } -func (p *packetPacker) appendLongHeaderPacket(buffer *packetBuffer, header *wire.ExtendedHeader, pl payload, padding protocol.ByteCount, encLevel protocol.EncryptionLevel, sealer sealer, v protocol.Version) (*longHeaderPacket, error) { +func (p *packetPacker) appendLongHeaderPacket(buffer *packetBuffer, header *wire.ExtendedHeader, pl payload, padding protocol.ByteCount, sealer sealer, v protocol.Version) (*longHeaderPacket, error) { var paddingLen protocol.ByteCount pnLen := protocol.ByteCount(header.PacketNumberLen) if pl.length < 4-pnLen { @@ -882,9 +919,6 @@ func (p *packetPacker) appendLongHeaderPacket(buffer *packetBuffer, header *wire raw = p.encryptPacket(raw, sealer, header.PacketNumber, payloadOffset, pnLen) buffer.Data = buffer.Data[:len(buffer.Data)+len(raw)] - if pn := p.pnManager.PopPacketNumber(encLevel); pn != header.PacketNumber { - return nil, fmt.Errorf("packetPacker BUG: Peeked and Popped packet numbers do not match: expected %d, got %d", pn, header.PacketNumber) - } return &longHeaderPacket{ header: header, ack: pl.ack, @@ -932,7 +966,7 @@ func (p *packetPacker) appendShortHeaderPacket( raw = p.encryptPacket(raw, sealer, pn, payloadOffset, protocol.ByteCount(pnLen)) buffer.Data = buffer.Data[:len(buffer.Data)+len(raw)] - if newPN := p.pnManager.PopPacketNumber(protocol.Encryption1RTT); newPN != pn { + if newPN := p.pnManager.PopPacketNumber(protocol.PacketNumberSpaceAppData); newPN != pn { return shortHeaderPacket{}, fmt.Errorf("packetPacker BUG: Peeked and Popped packet numbers do not match: expected %d, got %d", pn, newPN) } return shortHeaderPacket{ diff --git a/vendor/github.com/quic-go/quic-go/path_manager.go b/vendor/github.com/quic-go/quic-go/path_manager.go index dd188ea14..80637b759 100644 --- a/vendor/github.com/quic-go/quic-go/path_manager.go +++ b/vendor/github.com/quic-go/quic-go/path_manager.go @@ -32,7 +32,8 @@ type path struct { id pathID addr net.Addr lastPacketTime monotime.Time - pathChallenge [8]byte + pathChallenges [][8]byte // length is implicitly limited by exponential backoff + nextProbeTime monotime.Time validated bool rcvdNonProbing bool } @@ -74,7 +75,6 @@ func (pm *pathManager) HandlePacket( if addrsEqual(path.addr, remoteAddr) { p = path p.lastPacketTime = t - // already sent a PATH_CHALLENGE for this path if isNonProbing { path.rcvdNonProbing = true } @@ -87,13 +87,19 @@ func (pm *pathManager) HandlePacket( pm.paths = slices.Delete(pm.paths, i, i+1) pm.paths = append(pm.paths, p) } - if pathChallenge == nil { + // Nothing to send: + // * the packet didn't contain a PATH_CHALLENGE, and + // * the path does not need a probe (already validated, or still inside the backoff). + if pathChallenge == nil && (path.validated || t.Before(path.nextProbeTime)) { return protocol.ConnectionID{}, nil, shouldSwitch } + break } } - if len(pm.paths) >= maxPaths { + // new path while already at maxPaths + if p == nil && len(pm.paths) >= maxPaths { + // ignore it if the oldest path received a packet within pathTimeout if pm.paths[0].lastPacketTime.Add(pathTimeout).After(t) { if pm.logger.Debug() { pm.logger.Debugf("received packet for previously unseen path %s, but already have %d paths", remoteAddr, len(pm.paths)) @@ -112,36 +118,45 @@ func (pm *pathManager) HandlePacket( pathID = pm.nextPathID } - // previously unseen path, initiate path validation by sending a PATH_CHALLENGE connID, ok := pm.getConnID(pathID) if !ok { pm.logger.Debugf("skipping validation of new path %s since no connection ID is available", remoteAddr) return protocol.ConnectionID{}, nil, shouldSwitch } - frames := make([]ackhandler.Frame, 0, 2) if p == nil { - var pathChallengeData [8]byte - rand.Read(pathChallengeData[:]) p = &path{ id: pm.nextPathID, addr: remoteAddr, lastPacketTime: t, rcvdNonProbing: isNonProbing, - pathChallenge: pathChallengeData, + nextProbeTime: t, + pathChallenges: make([][8]byte, 0, 2), } pm.nextPathID++ pm.paths = append(pm.paths, p) + } + + frames := make([]ackhandler.Frame, 0, 2) + // Probe an unvalidated path with a new PATH_CHALLENGE: + // * sent on the next packet once nextProbeTime has passed, and + // * repeated until a PATH_RESPONSE arrives, ignoring ACKs and loss. + if !p.validated && !t.Before(p.nextProbeTime) { + backoffFactor := 1 << len(p.pathChallenges) + p.nextProbeTime = t.Add(utils.DefaultInitialRTT * time.Duration(backoffFactor)) + var b [8]byte + rand.Read(b[:]) + p.pathChallenges = append(p.pathChallenges, b) frames = append(frames, ackhandler.Frame{ - Frame: &wire.PathChallengeFrame{Data: p.pathChallenge}, - Handler: (*pathManagerAckHandler)(pm), + Frame: &wire.PathChallengeFrame{Data: b}, + Handler: emptyHandler{}, }) pm.logger.Debugf("enqueueing PATH_CHALLENGE for new path %s", remoteAddr) } if pathChallenge != nil { frames = append(frames, ackhandler.Frame{ Frame: &wire.PathResponseFrame{Data: pathChallenge.Data}, - Handler: (*pathManagerAckHandler)(pm), + Handler: emptyHandler{}, }) } return connID, frames, shouldSwitch @@ -149,9 +164,10 @@ func (pm *pathManager) HandlePacket( func (pm *pathManager) HandlePathResponseFrame(f *wire.PathResponseFrame) { for _, p := range pm.paths { - if f.Data == p.pathChallenge { + if slices.Contains(p.pathChallenges, f.Data) { // path validated p.validated = true + p.pathChallenges = nil pm.logger.Debugf("path %s validated", p.addr) break } @@ -172,27 +188,6 @@ func (pm *pathManager) SwitchToPath(addr net.Addr) { pm.paths = pm.paths[:0] } -type pathManagerAckHandler pathManager - -var _ ackhandler.FrameHandler = &pathManagerAckHandler{} - -// Acknowledging the frame doesn't validate the path, only receiving the PATH_RESPONSE does. -func (pm *pathManagerAckHandler) OnAcked(f wire.Frame) {} - -func (pm *pathManagerAckHandler) OnLost(f wire.Frame) { - pc, ok := f.(*wire.PathChallengeFrame) - if !ok { - return - } - for i, path := range pm.paths { - if path.pathChallenge == pc.Data { - pm.paths = slices.Delete(pm.paths, i, i+1) - pm.retireConnID(path.id) - break - } - } -} - func addrsEqual(addr1, addr2 net.Addr) bool { if addr1 == nil || addr2 == nil { return false diff --git a/vendor/github.com/quic-go/quic-go/qlog/event.go b/vendor/github.com/quic-go/quic-go/qlog/event.go index bbd1db647..5ef449baa 100644 --- a/vendor/github.com/quic-go/quic-go/qlog/event.go +++ b/vendor/github.com/quic-go/quic-go/qlog/event.go @@ -7,6 +7,7 @@ import ( "github.com/quic-go/quic-go/internal/protocol" "github.com/quic-go/quic-go/internal/qerr" + "github.com/quic-go/quic-go/qlogwriter" "github.com/quic-go/quic-go/qlogwriter/jsontext" ) @@ -414,6 +415,36 @@ func (e PacketDropped) Encode(enc *jsontext.Encoder, _ time.Time) error { return h.err } +// DatagramDropped is the quic:datagram_dropped event. +type DatagramDropped struct { + Direction Direction + Raw RawInfo + Trigger string +} + +var _ qlogwriter.Event = DatagramDropped{} + +func (e DatagramDropped) Name() string { return "quic:datagram_dropped" } + +func (e DatagramDropped) Encode(enc *jsontext.Encoder, _ time.Time) error { + h := encoderHelper{enc: enc} + h.WriteToken(jsontext.BeginObject) + if e.Direction != "" { + h.WriteToken(jsontext.String("direction")) + h.WriteToken(jsontext.String(string(e.Direction))) + } + h.WriteToken(jsontext.String("raw")) + if err := e.Raw.encode(enc); err != nil { + return err + } + if e.Trigger != "" { + h.WriteToken(jsontext.String("trigger")) + h.WriteToken(jsontext.String(e.Trigger)) + } + h.WriteToken(jsontext.EndObject) + return h.err +} + // StreamPriorityUpdated closely follows the http3:priority_updated event from // draft-ietf-quic-qlog-h3-events. type StreamPriorityUpdated struct { @@ -457,6 +488,48 @@ func (e MTUUpdated) Encode(enc *jsontext.Encoder, _ time.Time) error { return h.err } +// RecoveryParametersSet is the quic:recovery_parameters_set event. +type RecoveryParametersSet struct { + EncryptionLevel EncryptionLevel + ReorderingThreshold uint16 + PacketThresholdDisabled bool + TimeThreshold float64 // RTT multiplier. + TimerGranularity time.Duration + InitialCongestionWindow protocol.ByteCount + InitialRTT time.Duration +} + +var _ qlogwriter.Event = RecoveryParametersSet{} + +func (e RecoveryParametersSet) Name() string { return "quic:recovery_parameters_set" } + +func (e RecoveryParametersSet) Encode(enc *jsontext.Encoder, _ time.Time) error { + h := encoderHelper{enc: enc} + h.WriteToken(jsontext.BeginObject) + h.WriteToken(jsontext.String("packet_number_space")) + h.WriteToken(jsontext.String(encLevelToPacketNumberSpace(e.EncryptionLevel))) + h.WriteToken(jsontext.String("reordering_threshold")) + if e.PacketThresholdDisabled { + h.WriteToken(jsontext.String("disabled")) + } else { + h.WriteToken(jsontext.Uint(uint64(e.ReorderingThreshold))) + } + h.WriteToken(jsontext.String("time_threshold")) + h.WriteToken(jsontext.Float(e.TimeThreshold)) + h.WriteToken(jsontext.String("timer_granularity")) + h.WriteToken(jsontext.Uint(uint64(e.TimerGranularity / time.Millisecond))) + if e.InitialCongestionWindow != 0 { + h.WriteToken(jsontext.String("initial_congestion_window")) + h.WriteToken(jsontext.Uint(uint64(e.InitialCongestionWindow))) + } + if e.InitialRTT != 0 { + h.WriteToken(jsontext.String("initial_rtt")) + h.WriteToken(jsontext.Float(milliseconds(e.InitialRTT))) + } + h.WriteToken(jsontext.EndObject) + return h.err +} + // MetricsUpdated logs RTT and congestion metrics as defined in the // recovery:metrics_updated event. // The PTO count is logged via [PTOCountUpdated]. @@ -545,8 +618,10 @@ func (e PacketLost) Encode(enc *jsontext.Encoder, _ time.Time) error { } type SpuriousLoss struct { - EncryptionLevel protocol.EncryptionLevel - PacketNumber protocol.PacketNumber + EncryptionLevel protocol.EncryptionLevel + PacketNumber protocol.PacketNumber + // PacketReordering is the distance to the ACK's largest acknowledged packet, + // adjusted for known skipped packet numbers. Reordered ACKs can yield zero. PacketReordering uint64 TimeReordering time.Duration } diff --git a/vendor/github.com/quic-go/quic-go/qlog/types.go b/vendor/github.com/quic-go/quic-go/qlog/types.go index 97c7febef..9dc8ceb58 100644 --- a/vendor/github.com/quic-go/quic-go/qlog/types.go +++ b/vendor/github.com/quic-go/quic-go/qlog/types.go @@ -51,6 +51,14 @@ const ( InitiatorRemote Initiator = "remote" ) +// Direction identifies the sending or receiving side of an endpoint. +type Direction string + +const ( + DirectionSending Direction = "sending" + DirectionReceiving Direction = "receiving" +) + type streamType protocol.StreamType func (s streamType) String() string { diff --git a/vendor/github.com/quic-go/quic-go/send_stream.go b/vendor/github.com/quic-go/quic-go/send_stream.go index 0cd8a6e03..fe7cf00a3 100644 --- a/vendor/github.com/quic-go/quic-go/send_stream.go +++ b/vendor/github.com/quic-go/quic-go/send_stream.go @@ -115,6 +115,7 @@ func (s *SendStream) StreamID() StreamID { // Write writes data to the stream. // Write can be made to time out using [SendStream.SetWriteDeadline]. // If the stream was canceled, the error is a [StreamError]. +// If the stream was closed, the error is [ErrStreamClosed]. func (s *SendStream) Write(p []byte) (int, error) { return s.WriteWithLimit(p, nil) } @@ -177,7 +178,7 @@ func (s *SendStream) tryWriteAll(p []byte) (bool /* is newly completed */, bool return false, false, s.shutdownErr } if s.finishedWriting { - return false, false, fmt.Errorf("write on closed stream %d", s.streamID) + return false, false, ErrStreamClosed } if len(p) == 0 { return false, false, nil @@ -237,7 +238,7 @@ func (s *SendStream) write(p []byte, limiter func(int) int) (bool /* is newly co return false, 0, s.shutdownErr } if s.finishedWriting { - return false, 0, fmt.Errorf("write on closed stream %d", s.streamID) + return false, 0, ErrStreamClosed } if !s.deadline.IsZero() && !monotime.Now().Before(s.deadline) { return false, 0, errDeadline @@ -601,7 +602,7 @@ func (s *SendStream) Close() error { } s.sender.onHasStreamData(s.streamID, s) // need to send the FIN, must be called without holding the mutex - s.ctxCancel(nil) + s.ctxCancel(ErrStreamClosed) return nil } @@ -613,6 +614,10 @@ func (s *SendStream) SetReliableBoundary() { s.mutex.Lock() defer s.mutex.Unlock() + if s.resetErr != nil { + return + } + if s.nextFrame != nil { s.reliableSize = max(s.reliableSize, s.writeOffset+s.nextFrame.DataLen()) } else { @@ -824,7 +829,7 @@ func (s *SendStream) SetPriority(urgency int8, incremental bool) { // This happens when [SendStream.Close] or [SendStream.CancelWrite] is called, or when the peer // cancels the read-side of their stream. // The cancellation cause is set to the error that caused the stream to -// close, or [context.Canceled] in case the stream is closed without error. +// close, which is [ErrStreamClosed] if [SendStream.Close] was called. func (s *SendStream) Context() context.Context { return s.ctx } diff --git a/vendor/github.com/quic-go/quic-go/server.go b/vendor/github.com/quic-go/quic-go/server.go index 4a4dde250..3b562af67 100644 --- a/vendor/github.com/quic-go/quic-go/server.go +++ b/vendor/github.com/quic-go/quic-go/server.go @@ -35,6 +35,20 @@ type packetHandler interface { closeWithTransportError(qerr.TransportErrorCode) } +const ( + // max0RTTQueueingDuration is the maximum time that we store 0-RTT packets in order to wait for the corresponding Initial to be received. + max0RTTQueueingDuration = 100 * time.Millisecond + + // max0RTTQueues is the maximum number of connections that we buffer 0-RTT packets for. + max0RTTQueues = 32 + + // max0RTTQueueLen is the maximum number of 0-RTT packets that we buffer for each connection. + // When a new connection is created, all buffered packets are passed to the connection immediately. + // To avoid blocking, this value has to be smaller than MaxConnUnprocessedPackets. + // To avoid packets being dropped as undecryptable by the connection, this value has to be smaller than MaxUndecryptablePackets. + max0RTTQueueLen = 31 +) + type zeroRTTQueue struct { packets []receivedPacket expiration monotime.Time @@ -578,7 +592,7 @@ func (s *baseServer) handle0RTTPacket(p receivedPacket) bool { } if q, ok := s.zeroRTTQueues[connID]; ok { - if len(q.packets) >= protocol.Max0RTTQueueLen { + if len(q.packets) >= max0RTTQueueLen { if s.qlogger != nil { v, _ := wire.ParseVersion(p.data) s.qlogger.RecordEvent(qlog.PacketDropped{ @@ -597,7 +611,7 @@ func (s *baseServer) handle0RTTPacket(p receivedPacket) bool { return true } - if len(s.zeroRTTQueues) >= protocol.Max0RTTQueues { + if len(s.zeroRTTQueues) >= max0RTTQueues { if s.qlogger != nil { v, _ := wire.ParseVersion(p.data) s.qlogger.RecordEvent(qlog.PacketDropped{ @@ -614,7 +628,7 @@ func (s *baseServer) handle0RTTPacket(p receivedPacket) bool { } queue := &zeroRTTQueue{packets: make([]receivedPacket, 1, 8)} queue.packets[0] = p - expiration := p.rcvTime.Add(protocol.Max0RTTQueueingDuration) + expiration := p.rcvTime.Add(max0RTTQueueingDuration) queue.expiration = expiration if s.nextZeroRTTCleanup.IsZero() || s.nextZeroRTTCleanup.After(expiration) { s.nextZeroRTTCleanup = expiration diff --git a/vendor/github.com/quic-go/quic-go/stream.go b/vendor/github.com/quic-go/quic-go/stream.go index 9365a08a2..4c077919e 100644 --- a/vendor/github.com/quic-go/quic-go/stream.go +++ b/vendor/github.com/quic-go/quic-go/stream.go @@ -137,6 +137,7 @@ func (s *Stream) Peek(b []byte) (int, error) { // Write writes data to the stream. // Write can be made to time out using [Stream.SetWriteDeadline] or [Stream.SetDeadline]. // If the stream was canceled, the error is a [StreamError]. +// If the stream was closed, the error is [ErrStreamClosed]. func (s *Stream) Write(p []byte) (int, error) { return s.sendStr.Write(p) } diff --git a/vendor/github.com/shopspring/decimal/.golangci.yml b/vendor/github.com/shopspring/decimal/.golangci.yml index 50e57bc48..794257a8b 100644 --- a/vendor/github.com/shopspring/decimal/.golangci.yml +++ b/vendor/github.com/shopspring/decimal/.golangci.yml @@ -29,6 +29,17 @@ linters: disable: - fieldalignment # field order follows readability, not padding - shadow # shadowing err and loop variables is common and harmless here + staticcheck: + checks: + # golangci-lint's defaults + - all + - -ST1000 + - -ST1003 + - -ST1016 + - -ST1020 + - -ST1021 + - -ST1022 + - -QF1004 # suggests strings.ReplaceAll, which needs Go 1.12 gocritic: # Bug and performance checks only. The style checks are opinionated, and the experimental # commentedOutCode check reads formula comments like "v * 10^(f-q) = e^s * 10^f" as code. diff --git a/vendor/github.com/shopspring/decimal/CHANGELOG.md b/vendor/github.com/shopspring/decimal/CHANGELOG.md index 0ba232548..2d3bad96a 100644 --- a/vendor/github.com/shopspring/decimal/CHANGELOG.md +++ b/vendor/github.com/shopspring/decimal/CHANGELOG.md @@ -1,3 +1,35 @@ +## Decimal v1.6.0 + +#### BEHAVIOR CHANGES +- `Decimal` implements `fmt.Formatter`. `%#v` prints Go code that recreates the value, like `decimal.New(314, -2)`, instead of the struct fields, and verbs that don't apply, like `%d`, print `%!d(decimal.Decimal=3.14)`. `%v`, `%s`, `%q`, `%x` and `fmt.Println` print the same as before [#463](https://github.com/shopspring/decimal/pull/463) +- `Ln` rounds correctly, so some results change in the last digit: `Ln` of 10 to 5 places is `2.30259`, not `2.30258` [#471](https://github.com/shopspring/decimal/pull/471) +- `ExpHullAbrham` returns `overallPrecision` significant figures for every input. Negative inputs used to lose digits or return 0, like `-50` at precision 10, and large inputs returned extra digits [#429](https://github.com/shopspring/decimal/pull/429) [#470](https://github.com/shopspring/decimal/pull/470) +- `Scan` converts `float32` with `NewFromFloat32`, so `54.33` stays `54.33` instead of becoming `54.33000183105469`. NaN and infinite floats return an error instead of panicking [#469](https://github.com/shopspring/decimal/pull/469) +- On Go 1.10 to 1.12, `NewFromFloat` can pick a different shortest form in rare cases ([golang/go#29491](https://github.com/golang/go/issues/29491)). It still converts back to the same float [#431](https://github.com/shopspring/decimal/pull/431) + +#### FEATURES +- Add BSON Decimal128 support for `Decimal` and `NullDecimal` with the official MongoDB Go driver v2, without a new dependency [#460](https://github.com/shopspring/decimal/pull/460) +- Add `%f` formatting with precision, width and flags, like `%.2f` and `%08.2f` [#463](https://github.com/shopspring/decimal/pull/463) +- Add `Normalize`, which strips trailing zeros so equal decimals also match with `reflect.DeepEqual`, testify and gomock [#464](https://github.com/shopspring/decimal/pull/464) +- Add `Sqrt` and `SqrtRound` [#465](https://github.com/shopspring/decimal/pull/465) +- Add `Root` and `RootRound` for n-th roots [#473](https://github.com/shopspring/decimal/pull/473) +- Add `NewFromBigFloat` constructor [#457](https://github.com/shopspring/decimal/pull/457) +- `Scan` accepts `Decimal`, `big.Int`, `*big.Int` and all integer sizes, as passed by ClickHouse and other drivers [#469](https://github.com/shopspring/decimal/pull/469) + +#### ENHANCEMENTS +- `NewFromFloat` and `NewFromFloat32` are 3 to 6 times faster. They use `strconv` instead of a vendored copy of it from 2009, which is removed [#431](https://github.com/shopspring/decimal/pull/431) +- `Ln` is 3 to 14 times faster [#471](https://github.com/shopspring/decimal/pull/471) +- Slightly faster `IsInteger` and `Ceil` [#299](https://github.com/shopspring/decimal/pull/299) +- `NewFromString` accepts the Unicode minus sign `−` (U+2212) [#428](https://github.com/shopspring/decimal/pull/428) +- Scanning NULL into a `Decimal` returns an error that points to `NullDecimal` or `*Decimal` [#474](https://github.com/shopspring/decimal/pull/474) +- Document that global settings aren't goroutine-safe, and list them with their per-call alternatives in the README [#466](https://github.com/shopspring/decimal/pull/466) +- README: show how to control the JSON format of one field, add `udecimal` to the alternative libraries, and update the Go doc and playground links [#475](https://github.com/shopspring/decimal/pull/475) [#476](https://github.com/shopspring/decimal/pull/476) [#264](https://github.com/shopspring/decimal/pull/264) +- Fix doc examples that were wrong or didn't compile [#468](https://github.com/shopspring/decimal/pull/468) +- Fix benchmarks that measured their setup or the wrong function [#467](https://github.com/shopspring/decimal/pull/467) + +#### BUGFIXES +- `QuoRem` and `DivRound` panic on precision `math.MinInt32` instead of returning a wrong quotient [#472](https://github.com/shopspring/decimal/pull/472) + ## Decimal v1.5.0 #### BEHAVIOR CHANGES diff --git a/vendor/github.com/shopspring/decimal/README.md b/vendor/github.com/shopspring/decimal/README.md index 995e5740b..4b782f518 100644 --- a/vendor/github.com/shopspring/decimal/README.md +++ b/vendor/github.com/shopspring/decimal/README.md @@ -1,11 +1,13 @@ # decimal [![ci](https://github.com/shopspring/decimal/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/shopspring/decimal/actions/workflows/ci.yml) -[![GoDoc](https://godoc.org/github.com/shopspring/decimal?status.svg)](https://godoc.org/github.com/shopspring/decimal) +[![GoDoc](https://pkg.go.dev/badge/github.com/shopspring/decimal)](https://pkg.go.dev/github.com/shopspring/decimal) Arbitrary-precision fixed-point decimal numbers in go. _Note:_ Decimal library can "only" represent numbers with a maximum of 2^31 digits after the decimal point. +Results that aren't exact, like `Div` and `Sqrt`, are rounded to 16 decimal places by default, and decoded input is +limited to exponents up to 10,000. See [Global settings](#global-settings). ## Features @@ -14,6 +16,7 @@ _Note:_ Decimal library can "only" represent numbers with a maximum of 2^31 digi * Division with specified precision * Database/sql serialization/deserialization * JSON and XML serialization/deserialization + * MongoDB BSON serialization/deserialization as Decimal128, with the official Go driver v2 ## Install @@ -25,7 +28,7 @@ Decimal library requires Go version `>=1.10` ## Documentation -http://godoc.org/github.com/shopspring/decimal +https://pkg.go.dev/github.com/shopspring/decimal ## Usage @@ -63,6 +66,22 @@ func main() { } ``` +## Global settings + +These package-level variables change how some functions behave: + +| Variable | Default | What it changes | Per-call alternative | +|---|---|---|---| +| `DivisionPrecision` | `16` | Decimal places in `Div` and `Sqrt` results, and in `Avg`, `Atan` and `Tan` | `DivRound`, `SqrtRound` | +| `PowPrecisionNegativeExponent` | `16` | Decimal places in `Pow`, `PowInt32` and `PowBigInt` results for negative or fractional exponents | `PowWithPrecision` | +| `TrimTrailingZeros` | `true` | Whether `String`, and so JSON, text and SQL output, drops trailing zeros: `2.50` prints as `2.5` | `StringFixed` | +| `UseScientificNotation` | `false` | Whether `String` prints numbers stored with a positive exponent in scientific notation, like `1.2E3` | `StringFixed` | +| `MarshalJSONWithoutQuotes` | `false` | Whether JSON output is a number instead of a string | | +| `ExpMaxIterations` | `1000` | Iteration limit of `ExpHullAbrham` | | +| `MaxDecodeExponent` | `10000` | Largest exponent size that `NewFromString` and the decoders accept | | + +Set them once at program start. Changing one while other goroutines use the library is a data race. + ## Alternative libraries When working with decimal numbers, you might face problems this library is not perfectly suited for. @@ -72,6 +91,7 @@ Explore other alternatives to find the one that best fits your needs :) * [cockroachdb/apd](https://github.com/cockroachdb/apd) - arbitrary precision, mutable and rich API similar to `big.Int`, more performant than this library * [alpacahq/alpacadecimal](https://github.com/alpacahq/alpacadecimal) - high performance, low precision (12 digits), fully compatible API with this library * [govalues/decimal](https://github.com/govalues/decimal) - high performance, zero-allocation, low precision (19 digits) +* [quagmt/udecimal](https://github.com/quagmt/udecimal) - high performance, mostly zero-allocation, up to 19 digits after the decimal point * [greatcloak/decimal](https://github.com/greatcloak/decimal) - fork focusing on billing and e-commerce web application related use cases, includes out-of-the-box BSON marshaling support ## FAQ @@ -81,7 +101,7 @@ Explore other alternatives to find the one that best fits your needs :) Because float64 (or any binary floating point type, actually) can't represent numbers such as `0.1` exactly. -Consider this code: http://play.golang.org/p/TQBd4yJe6B You might expect that +Consider this code: https://go.dev/play/p/TQBd4yJe6B You might expect that it prints out `10`, but it actually prints `9.999999999999831`. Over time, these small errors can really add up! @@ -96,7 +116,7 @@ out, the string output has to stop somewhere (let's say it stops at 3 decimal digits, for simplicity), so you'll get 0.333, 0.333, and 0.333. But where did the other 0.001 go? -Here's the above example as code: http://play.golang.org/p/lCZZs0w9KE +Here's the above example as code: https://go.dev/play/p/lCZZs0w9KE With Decimal, the strings being printed out represent the number exactly. So, if you have `x = y = 1/3` (with precision 3), they will actually be equal to @@ -121,7 +141,7 @@ modifies `a` and sets `z` as an alias for `a`, which they might not expect. It also modifies any other aliases to `a`. Here's an example of the subtle bugs you can introduce with big.Int's API: -https://play.golang.org/p/x2R_78pa8r +https://go.dev/play/p/x2R_78pa8r In contrast, it's difficult to make such mistakes with decimal. Decimals behave like other go numbers types: even though `a = b` will not deep copy @@ -131,6 +151,22 @@ this causes extra allocations, so Decimal is less performant. My assumption is that if you're using Decimals, you probably care more about correctness than performance. +#### How do I control the JSON format of one field? + +Wrap the field in a small type with its own `MarshalJSON`. For example, to always write money with 2 decimal places: + +```go +type Money struct{ decimal.Decimal } + +func (m Money) MarshalJSON() ([]byte, error) { + return []byte(`"` + m.StringFixed(2) + `"`), nil +} +``` + +A `Money` field marshals as `"12.50"`, other decimals keep their usual format, and unmarshaling still works through +the embedded `Decimal`. To write one field as a JSON number instead of a string, return `[]byte(m.String())`. +This is safer than the global settings, which change every decimal in the program. + ## License The MIT License (MIT) diff --git a/vendor/github.com/shopspring/decimal/const.go b/vendor/github.com/shopspring/decimal/const.go index 4538cab70..f2f86476b 100644 --- a/vendor/github.com/shopspring/decimal/const.go +++ b/vendor/github.com/shopspring/decimal/const.go @@ -2,67 +2,12 @@ package decimal import ( "math/big" - "strings" ) const ( strLn10 = "2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286248633409525465082806756666287369098781689482907208325554680843799894826233198528393505308965377732628846163366222287698219886746543667474404243274365155048934314939391479619404400222105101714174800368808401264708068556774321622835522011480466371565912137345074785694768346361679210180644507064800027750268491674655058685693567342067058113642922455440575892572420824131469568901675894025677631135691929203337658714166023010570308963457207544037084746994016826928280848118428931484852494864487192780967627127577539702766860595249671667418348570442250719796500471495105049221477656763693866297697952211071826454973477266242570942932258279850258550978526538320760672631716430950599508780752371033310119785754733154142180842754386359177811705430982748238504564801909561029929182431823752535770975053956518769751037497088869218020518933950723853920514463419726528728696511086257149219884997874887377134568620916705849807828059751193854445009978131146915934666241071846692310107598438319191292230792503747298650929009880391941702654416816335727555703151596113564846546190897042819763365836983716328982174407366009162177850541779276367731145041782137660111010731042397832521894898817597921798666394319523936855916447118246753245630912528778330963604262982153040874560927760726641354787576616262926568298704957954913954918049209069438580790032763017941503117866862092408537949861264933479354871737451675809537088281067452440105892444976479686075120275724181874989395971643105518848195288330746699317814634930000321200327765654130472621883970596794457943468343218395304414844803701305753674262153675579814770458031413637793236291560128185336498466942261465206459942072917119370602444929358037007718981097362533224548366988505528285966192805098447175198503666680874970496982273220244823343097169111136813588418696549323714996941979687803008850408979618598756579894836445212043698216415292987811742973332588607915912510967187510929248475023930572665446276200923068791518135803477701295593646298412366497023355174586195564772461857717369368404676577047874319780573853271810933883496338813069945569399346101090745616033312247949360455361849123333063704751724871276379140924398331810164737823379692265637682071706935846394531616949411701841938119405416449466111274712819705817783293841742231409930022911502362192186723337268385688273533371925103412930705632544426611429765388301822384091026198582888433587455960453004548370789052578473166283701953392231047527564998119228742789713715713228319641003422124210082180679525276689858180956119208391760721080919923461516952599099473782780648128058792731993893453415320185969711021407542282796298237068941764740642225757212455392526179373652434440560595336591539160312524480149313234572453879524389036839236450507881731359711238145323701508413491122324390927681724749607955799151363982881058285740538000653371655553014196332241918087621018204919492651483892" ) -var ( - ln10 = newConstApproximation(strLn10) -) - -type constApproximation struct { - exact Decimal - approximations []Decimal -} - -func newConstApproximation(value string) constApproximation { - parts := strings.Split(value, ".") - coeff, fractional := parts[0], parts[1] - - coeffLen := len(coeff) - maxPrecision := len(fractional) - - var approximations []Decimal - for p := 1; p < maxPrecision; p *= 2 { - r := RequireFromString(value[:coeffLen+p]) - approximations = append(approximations, r) - } - - return constApproximation{ - RequireFromString(value), - approximations, - } -} - -// Returns the smallest approximation available that's at least as precise -// as the passed precision (places after decimal point), i.e. Floor[ log2(precision) ] + 1 -func (c constApproximation) withPrecision(precision int32) Decimal { - i := 0 - - if precision >= 1 { - i++ - } - - for precision >= 16 { - precision /= 16 - i += 4 - } - - for precision >= 2 { - precision /= 2 - i++ - } - - if i >= len(c.approximations) { - return c.exact - } - - return c.approximations[i] -} - var zeroInt = big.NewInt(0) var oneInt = big.NewInt(1) var twoInt = big.NewInt(2) diff --git a/vendor/github.com/shopspring/decimal/decimal-go.go b/vendor/github.com/shopspring/decimal/decimal-go.go deleted file mode 100644 index 9958d6902..000000000 --- a/vendor/github.com/shopspring/decimal/decimal-go.go +++ /dev/null @@ -1,415 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Multiprecision decimal numbers. -// For floating-point formatting only; not general purpose. -// Only operations are assign and (binary) left/right shift. -// Can do binary floating point in multiprecision decimal precisely -// because 2 divides 10; cannot do decimal floating point -// in multiprecision binary precisely. - -package decimal - -type decimal struct { - d [800]byte // digits, big-endian representation - nd int // number of digits used - dp int // decimal point - neg bool // negative flag - trunc bool // discarded nonzero digits beyond d[:nd] -} - -func (a *decimal) String() string { - n := 10 + a.nd - if a.dp > 0 { - n += a.dp - } - if a.dp < 0 { - n += -a.dp - } - - buf := make([]byte, n) - w := 0 - switch { - case a.nd == 0: - return "0" - - case a.dp <= 0: - // zeros fill space between decimal point and digits - buf[w] = '0' - w++ - buf[w] = '.' - w++ - w += digitZero(buf[w : w+-a.dp]) - w += copy(buf[w:], a.d[0:a.nd]) - - case a.dp < a.nd: - // decimal point in middle of digits - w += copy(buf[w:], a.d[0:a.dp]) - buf[w] = '.' - w++ - w += copy(buf[w:], a.d[a.dp:a.nd]) - - default: - // zeros fill space between digits and decimal point - w += copy(buf[w:], a.d[0:a.nd]) - w += digitZero(buf[w : w+a.dp-a.nd]) - } - return string(buf[0:w]) -} - -func digitZero(dst []byte) int { - for i := range dst { - dst[i] = '0' - } - return len(dst) -} - -// trim trailing zeros from number. -// (They are meaningless; the decimal point is tracked -// independent of the number of digits.) -func trim(a *decimal) { - for a.nd > 0 && a.d[a.nd-1] == '0' { - a.nd-- - } - if a.nd == 0 { - a.dp = 0 - } -} - -// Assign v to a. -func (a *decimal) Assign(v uint64) { - var buf [24]byte - - // Write reversed decimal in buf. - n := 0 - for v > 0 { - v1 := v / 10 - v -= 10 * v1 - buf[n] = byte(v + '0') - n++ - v = v1 - } - - // Reverse again to produce forward decimal in a.d. - a.nd = 0 - for n--; n >= 0; n-- { - a.d[a.nd] = buf[n] - a.nd++ - } - a.dp = a.nd - trim(a) -} - -// Maximum shift that we can do in one pass without overflow. -// A uint has 32 or 64 bits, and we have to be able to accommodate 9<> 63) -const maxShift = uintSize - 4 - -// Binary shift right (/ 2) by k bits. k <= maxShift to avoid overflow. -func rightShift(a *decimal, k uint) { - r := 0 // read pointer - w := 0 // write pointer - - // Pick up enough leading digits to cover first shift. - var n uint - for ; n>>k == 0; r++ { - if r >= a.nd { - if n == 0 { - // a == 0; shouldn't get here, but handle anyway. - a.nd = 0 - return - } - for n>>k == 0 { - n = n * 10 - r++ - } - break - } - c := uint(a.d[r]) - n = n*10 + c - '0' - } - a.dp -= r - 1 - - var mask uint = (1 << k) - 1 - - // Pick up a digit, put down a digit. - for ; r < a.nd; r++ { - c := uint(a.d[r]) - dig := n >> k - n &= mask - a.d[w] = byte(dig + '0') - w++ - n = n*10 + c - '0' - } - - // Put down extra digits. - for n > 0 { - dig := n >> k - n &= mask - if w < len(a.d) { - a.d[w] = byte(dig + '0') - w++ - } else if dig > 0 { - a.trunc = true - } - n = n * 10 - } - - a.nd = w - trim(a) -} - -// Cheat sheet for left shift: table indexed by shift count giving -// number of new digits that will be introduced by that shift. -// -// For example, leftcheats[4] = {2, "625"}. That means that -// if we are shifting by 4 (multiplying by 16), it will add 2 digits -// when the string prefix is "625" through "999", and one fewer digit -// if the string prefix is "000" through "624". -// -// Credit for this trick goes to Ken. - -type leftCheat struct { - delta int // number of new digits - cutoff string // minus one digit if original < a. -} - -var leftcheats = []leftCheat{ - // Leading digits of 1/2^i = 5^i. - // 5^23 is not an exact 64-bit floating point number, - // so have to use bc for the math. - // Go up to 60 to be large enough for 32bit and 64bit platforms. - /* - seq 60 | sed 's/^/5^/' | bc | - awk 'BEGIN{ print "\t{ 0, \"\" }," } - { - log2 = log(2)/log(10) - printf("\t{ %d, \"%s\" },\t// * %d\n", - int(log2*NR+1), $0, 2**NR) - }' - */ - {0, ""}, - {1, "5"}, // * 2 - {1, "25"}, // * 4 - {1, "125"}, // * 8 - {2, "625"}, // * 16 - {2, "3125"}, // * 32 - {2, "15625"}, // * 64 - {3, "78125"}, // * 128 - {3, "390625"}, // * 256 - {3, "1953125"}, // * 512 - {4, "9765625"}, // * 1024 - {4, "48828125"}, // * 2048 - {4, "244140625"}, // * 4096 - {4, "1220703125"}, // * 8192 - {5, "6103515625"}, // * 16384 - {5, "30517578125"}, // * 32768 - {5, "152587890625"}, // * 65536 - {6, "762939453125"}, // * 131072 - {6, "3814697265625"}, // * 262144 - {6, "19073486328125"}, // * 524288 - {7, "95367431640625"}, // * 1048576 - {7, "476837158203125"}, // * 2097152 - {7, "2384185791015625"}, // * 4194304 - {7, "11920928955078125"}, // * 8388608 - {8, "59604644775390625"}, // * 16777216 - {8, "298023223876953125"}, // * 33554432 - {8, "1490116119384765625"}, // * 67108864 - {9, "7450580596923828125"}, // * 134217728 - {9, "37252902984619140625"}, // * 268435456 - {9, "186264514923095703125"}, // * 536870912 - {10, "931322574615478515625"}, // * 1073741824 - {10, "4656612873077392578125"}, // * 2147483648 - {10, "23283064365386962890625"}, // * 4294967296 - {10, "116415321826934814453125"}, // * 8589934592 - {11, "582076609134674072265625"}, // * 17179869184 - {11, "2910383045673370361328125"}, // * 34359738368 - {11, "14551915228366851806640625"}, // * 68719476736 - {12, "72759576141834259033203125"}, // * 137438953472 - {12, "363797880709171295166015625"}, // * 274877906944 - {12, "1818989403545856475830078125"}, // * 549755813888 - {13, "9094947017729282379150390625"}, // * 1099511627776 - {13, "45474735088646411895751953125"}, // * 2199023255552 - {13, "227373675443232059478759765625"}, // * 4398046511104 - {13, "1136868377216160297393798828125"}, // * 8796093022208 - {14, "5684341886080801486968994140625"}, // * 17592186044416 - {14, "28421709430404007434844970703125"}, // * 35184372088832 - {14, "142108547152020037174224853515625"}, // * 70368744177664 - {15, "710542735760100185871124267578125"}, // * 140737488355328 - {15, "3552713678800500929355621337890625"}, // * 281474976710656 - {15, "17763568394002504646778106689453125"}, // * 562949953421312 - {16, "88817841970012523233890533447265625"}, // * 1125899906842624 - {16, "444089209850062616169452667236328125"}, // * 2251799813685248 - {16, "2220446049250313080847263336181640625"}, // * 4503599627370496 - {16, "11102230246251565404236316680908203125"}, // * 9007199254740992 - {17, "55511151231257827021181583404541015625"}, // * 18014398509481984 - {17, "277555756156289135105907917022705078125"}, // * 36028797018963968 - {17, "1387778780781445675529539585113525390625"}, // * 72057594037927936 - {18, "6938893903907228377647697925567626953125"}, // * 144115188075855872 - {18, "34694469519536141888238489627838134765625"}, // * 288230376151711744 - {18, "173472347597680709441192448139190673828125"}, // * 576460752303423488 - {19, "867361737988403547205962240695953369140625"}, // * 1152921504606846976 -} - -// Is the leading prefix of b lexicographically less than s? -func prefixIsLessThan(b []byte, s string) bool { - for i := 0; i < len(s); i++ { - if i >= len(b) { - return true - } - if b[i] != s[i] { - return b[i] < s[i] - } - } - return false -} - -// Binary shift left (* 2) by k bits. k <= maxShift to avoid overflow. -func leftShift(a *decimal, k uint) { - delta := leftcheats[k].delta - if prefixIsLessThan(a.d[0:a.nd], leftcheats[k].cutoff) { - delta-- - } - - r := a.nd // read index - w := a.nd + delta // write index - - // Pick up a digit, put down a digit. - var n uint - for r--; r >= 0; r-- { - n += (uint(a.d[r]) - '0') << k - quo := n / 10 - rem := n - 10*quo - w-- - if w < len(a.d) { - a.d[w] = byte(rem + '0') - } else if rem != 0 { - a.trunc = true - } - n = quo - } - - // Put down extra digits. - for n > 0 { - quo := n / 10 - rem := n - 10*quo - w-- - if w < len(a.d) { - a.d[w] = byte(rem + '0') - } else if rem != 0 { - a.trunc = true - } - n = quo - } - - a.nd += delta - if a.nd >= len(a.d) { - a.nd = len(a.d) - } - a.dp += delta - trim(a) -} - -// Binary shift left (k > 0) or right (k < 0). -func (a *decimal) Shift(k int) { - switch { - case a.nd == 0: - // nothing to do: a == 0 - case k > 0: - for k > maxShift { - leftShift(a, maxShift) - k -= maxShift - } - leftShift(a, uint(k)) - case k < 0: - for k < -maxShift { - rightShift(a, maxShift) - k += maxShift - } - rightShift(a, uint(-k)) - } -} - -// If we chop a at nd digits, should we round up? -func shouldRoundUp(a *decimal, nd int) bool { - if nd < 0 || nd >= a.nd { - return false - } - if a.d[nd] == '5' && nd+1 == a.nd { // exactly halfway - round to even - // if we truncated, a little higher than what's recorded - always round up - if a.trunc { - return true - } - return nd > 0 && (a.d[nd-1]-'0')%2 != 0 - } - // not halfway - digit tells all - return a.d[nd] >= '5' -} - -// Round a to nd digits (or fewer). -// If nd is zero, it means we're rounding -// just to the left of the digits, as in -// 0.09 -> 0.1. -func (a *decimal) Round(nd int) { - if nd < 0 || nd >= a.nd { - return - } - if shouldRoundUp(a, nd) { - a.RoundUp(nd) - } else { - a.RoundDown(nd) - } -} - -// Round a down to nd digits (or fewer). -func (a *decimal) RoundDown(nd int) { - if nd < 0 || nd >= a.nd { - return - } - a.nd = nd - trim(a) -} - -// Round a up to nd digits (or fewer). -func (a *decimal) RoundUp(nd int) { - if nd < 0 || nd >= a.nd { - return - } - - // round up - for i := nd - 1; i >= 0; i-- { - c := a.d[i] - if c < '9' { // can stop after this digit - a.d[i]++ - a.nd = i + 1 - return - } - } - - // Number is all 9s. - // Change to single 1 with adjusted decimal point. - a.d[0] = '1' - a.nd = 1 - a.dp++ -} - -// Extract integer part, rounded appropriately. -// No guarantees about overflow. -func (a *decimal) RoundedInteger() uint64 { - if a.dp > 20 { - return 0xFFFFFFFFFFFFFFFF - } - var i int - n := uint64(0) - for i = 0; i < a.dp && i < a.nd; i++ { - n = n*10 + uint64(a.d[i]-'0') - } - for ; i < a.dp; i++ { - n *= 10 - } - if shouldRoundUp(a, a.dp) { - n++ - } - return n -} diff --git a/vendor/github.com/shopspring/decimal/decimal.go b/vendor/github.com/shopspring/decimal/decimal.go index b1aa884af..90a17e341 100644 --- a/vendor/github.com/shopspring/decimal/decimal.go +++ b/vendor/github.com/shopspring/decimal/decimal.go @@ -18,6 +18,7 @@ package decimal import ( "fmt" + "io" "math" "math/big" "math/bits" @@ -27,7 +28,10 @@ import ( ) // DivisionPrecision is the number of decimal places in the result when it -// doesn't divide exactly. +// doesn't divide exactly. Div and Sqrt read it, and so do Avg, Atan and Tan through Div. +// +// Set it once at program start. Changing it while other goroutines use the package is a data race. +// To choose the precision per call, use DivRound instead of Div and SqrtRound instead of Sqrt. // // Example: // @@ -47,6 +51,9 @@ var DivisionPrecision = 16 // PowPrecisionNegativeExponent significant digits instead (at least one). // PowWithPrecision is not affected, it takes the precision as an argument. // +// Set it once at program start. Changing it while other goroutines use the package is a data race. +// To choose the precision per call, use PowWithPrecision. +// // Example: // // d1, err := decimal.NewFromFloat(15.2).PowInt32(-2) @@ -63,12 +70,18 @@ var PowPrecisionNegativeExponent = 16 // unmarshallers (ex: Javascript's) will unmarshal JSON numbers to IEEE 754 // double-precision floating point numbers, which means you can potentially // silently lose precision. +// +// Set it once at program start. Changing it while other goroutines use the package is a data race. var MarshalJSONWithoutQuotes = false // TrimTrailingZeros specifies whether trailing zeroes should be trimmed from a string representation of decimal. // If set to true, trailing zeroes will be truncated (2.00 -> 2, 3.11 -> 3.11, 13.000 -> 13), // otherwise trailing zeroes will be preserved (2.00 -> 2.00, 3.11 -> 3.11, 13.000 -> 13.000). // Setting this value to false can be useful for APIs where exact decimal string representation matters. +// It affects String and everything built on it, such as MarshalJSON, MarshalText and Value. +// +// Set it once at program start. Changing it while other goroutines use the package is a data race. +// For a fixed number of decimal places per call, use StringFixed. var TrimTrailingZeros = true // UseScientificNotation specifies whether scientific notation should be used when a decimal is turned @@ -76,14 +89,20 @@ var TrimTrailingZeros = true // // For example, 1200 rounded to the nearest 100 cannot accurately be shown as "1200" because the last two // digits are unknown. With this set to true, that number would be expressed as "1.2E3" instead. +// +// Set it once at program start. Changing it while other goroutines use the package is a data race. +// StringFixed never uses scientific notation. var UseScientificNotation = false // ExpMaxIterations specifies the maximum number of iterations needed to calculate // precise natural exponent value using ExpHullAbrham method. +// +// Set it once at program start. Changing it while other goroutines use the package is a data race. var ExpMaxIterations = 1000 // MaxDecodeExponent is the largest exponent magnitude that NewFromString and UnmarshalBinary accept, -// and so UnmarshalJSON, UnmarshalText, Scan, GobDecode, DecodeSpanner and their NullDecimal variants too. +// and so UnmarshalJSON, UnmarshalText, Scan, GobDecode, DecodeSpanner, UnmarshalBSONValue and their +// NullDecimal variants too. // Operations like String, Add and Float64 take time and memory that grow with the exponent, so without // this limit a short input like "1e-2000000000" can stall the process or exhaust its memory. // The default covers the float64 and IEEE 754 decimal128 exponent ranges. @@ -92,7 +111,8 @@ var ExpMaxIterations = 1000 // their own String or MarshalBinary output. The limit does not bound the cost of Pow or ExpTaylor // arguments or of very long inputs; validate those separately. // -// Set it once at program start, before any decoding. Raise it only for trusted input. +// Set it once at program start, before any decoding. Changing it while other goroutines decode is a +// data race. Raise it only for trusted input. var MaxDecodeExponent = 10000 // Zero constant, to make computations faster. @@ -192,6 +212,28 @@ func NewFromBigRat(value *big.Rat, precision int32) Decimal { }, precision) } +// NewFromBigFloat returns a new Decimal from a big.Float. The result is the shortest decimal +// that rounds back to value at value's precision, as NewFromFloat does for a float64. +// It returns an error for nil and infinite values, and for exponents beyond MaxDecodeExponent. +// +// Example: +// +// f, _ := new(big.Float).SetString("-123.45") +// d, err := NewFromBigFloat(f) +// d.String() // output: "-123.45" +func NewFromBigFloat(value *big.Float) (Decimal, error) { + if value == nil { + return Decimal{}, fmt.Errorf("can't convert nil *big.Float to decimal") + } + if value.IsInf() { + return Decimal{}, fmt.Errorf("can't convert infinite *big.Float to decimal") + } + if value.Sign() == 0 { + return New(0, 0), nil + } + return NewFromString(value.Text('g', -1)) +} + // NewFromString returns a new Decimal from a string representation. // Trailing zeroes are not trimmed. // @@ -204,6 +246,9 @@ func NewFromString(value string) (Decimal, error) { originalInput := value var exp int64 + // Accept Unicode minus sign (U+2212) in addition to ASCII '-'. + value = strings.Replace(value, "\u2212", "-", -1) + // Check if number is using scientific notation and find dots eIndex := -1 pIndex := -1 @@ -364,7 +409,7 @@ func NewFromFloat(value float64) Decimal { if value == 0 { return New(0, 0) } - return newFromFloat(value, math.Float64bits(value), &float64info) + return newFromFloat(value, 64) } // NewFromFloat32 converts a float32 to Decimal. @@ -383,55 +428,66 @@ func NewFromFloat32(value float32) Decimal { if value == 0 { return New(0, 0) } - // XOR is workaround for https://github.com/golang/go/issues/26285 - a := math.Float32bits(value) ^ 0x80808080 - return newFromFloat(float64(value), uint64(a)^0x80808080, &float32info) + return newFromFloat(float64(value), 32) } -func newFromFloat(val float64, bits uint64, flt *floatInfo) Decimal { +// newFromFloat converts val to a Decimal holding the shortest decimal digit +// string that round-trips back to val when parsed at the given bit size. +// +// strconv already computes exactly that string, so we ask it for the value in +// 'e' format with precision -1 and read the digits back out. The 'e' layout is +// [-]d[.ddd]e±dd, which is bounded (at most 24 bytes) and trivial to scan, +// unlike 'f' which can run to over 750 bytes for extreme exponents. +func newFromFloat(val float64, bitSize int) Decimal { if math.IsNaN(val) || math.IsInf(val, 0) { panic(fmt.Sprintf("Cannot create a Decimal from %v", val)) } - exp := int(bits>>flt.mantbits) & (1<>(flt.expbits+flt.mantbits) != 0 - - roundShortest(&d, mant, exp, flt) - // If less than 19 digits, we can do calculation in an int64. - if d.nd < 19 { - tmp := int64(0) - m := int64(1) - for i := d.nd - 1; i >= 0; i-- { - tmp += m * int64(d.d[i]-'0') - m *= 10 - } - if d.neg { - tmp *= -1 + neg := b[0] == '-' + if neg { + b = b[1:] + } + + // Split the significand from the exponent. b always contains an 'e'. + var i int + for b[i] != 'e' { + i++ + } + digits, expDigits := b[:i], b[i+1:] + + // The shortest round-trip form has at most 17 significant digits for a + // float64 and 9 for a float32, so the significand always fits in an int64. + var mant int64 + nd := 0 + for _, c := range digits { + if c == '.' { + continue } - return Decimal{value: big.NewInt(tmp), exp: int32(d.dp) - int32(d.nd)} + mant = mant*10 + int64(c-'0') + nd++ + } + if neg { + mant = -mant + } + + esign := 1 + switch expDigits[0] { + case '-': + esign = -1 + expDigits = expDigits[1:] + case '+': + expDigits = expDigits[1:] } - dValue := new(big.Int) - dValue, ok := dValue.SetString(string(d.d[:d.nd]), 10) - if ok { - return Decimal{value: dValue, exp: int32(d.dp) - int32(d.nd)} + e := 0 + for _, c := range expDigits { + e = e*10 + int(c-'0') } - return NewFromFloatWithExponent(val, int32(d.dp)-int32(d.nd)) + // digits is d.ddd, i.e. the significand scaled by 10^(nd-1). + return Decimal{value: big.NewInt(mant), exp: int32(esign*e - nd + 1)} } // NewFromFloatWithExponent converts a float64 to Decimal, with an arbitrary @@ -535,18 +591,18 @@ func (d Decimal) Copy() Decimal { // // Example: // -// d := New(12345, -4) -// d2 := d.rescale(-1) +// d1 := New(12345, -4) +// d2 := d1.rescale(-1) // d3 := d2.rescale(-4) -// println(d1) -// println(d2) -// println(d3) +// fmt.Println(d1) +// fmt.Println(d2) +// fmt.Println(d3) // // Output: // // 1.2345 // 1.2 -// 1.2000 +// 1.2 func (d Decimal) rescale(exp int32) Decimal { if d.exp == exp { return Decimal{ @@ -673,8 +729,50 @@ func (d Decimal) Shift(shift int32) Decimal { } } +// Normalize returns d with the trailing zeros removed from its coefficient, so equal decimals get the +// same coefficient and exponent: 1.50, 1.5 and New(15, -1) all become New(15, -1), and every zero +// becomes Decimal{}, the same as Zero. It's like Java's BigDecimal.stripTrailingZeros. +// +// reflect.DeepEqual, and test helpers built on it such as testify's assert.Equal and gomock.Eq, compare +// the coefficient and exponent rather than the value, so normalize decimals before comparing them that +// way. Equal and Cmp compare values and don't need it. +// +// The value doesn't change, but its string form can: with TrimTrailingZeros = false, 1.50 prints as +// 1.5, and with UseScientificNotation = true, 1500 prints as 1.5E3. +func (d Decimal) Normalize() Decimal { + v := d.getValue() + if v.Sign() == 0 { + return Decimal{} + } + + // Count the trailing zeros with integer math: in v if it fits an int64, else in v mod 10^19, + // and in all the digits of v only when those 19 are all zeros. + var zeros int64 + if v.IsInt64() { + for x := v.Int64(); x%10 == 0; x /= 10 { + zeros++ + } + } else { + r := new(big.Int).Rem(v, pow10(19)) + for n := r.Abs(r).Uint64(); n%10 == 0 && zeros < 19; n /= 10 { + zeros++ + } + if zeros == 19 { + s := v.String() + zeros = int64(len(s) - len(strings.TrimRight(s, "0"))) + } + } + if room := math.MaxInt32 - int64(d.exp); zeros > room { + zeros = room + } + if zeros == 0 { + return d + } + return Decimal{value: new(big.Int).Quo(v, pow10(zeros)), exp: d.exp + int32(zeros)} +} + // Div returns d / d2. If it doesn't divide exactly, the result will have -// DivisionPrecision digits after the decimal point. +// DivisionPrecision digits after the decimal point. Use DivRound to choose the precision per call. func (d Decimal) Div(d2 Decimal) Decimal { return d.DivRound(d2, int32(DivisionPrecision)) } @@ -698,7 +796,7 @@ func (d Decimal) quoRem(d2 Decimal, precision int32, bb *big.Int) (Decimal, Deci } scale := -precision e := int64(d.exp) - int64(d2.exp) - int64(scale) - if e > math.MaxInt32 || e < math.MinInt32 { + if precision == math.MinInt32 || e > math.MaxInt32 || e < math.MinInt32 { panic("overflow in decimal QuoRem") } if bb == nil { @@ -811,7 +909,7 @@ func (d Decimal) IsInteger() bool { q := new(big.Int).Set(v) for z := abs(d.exp); z > 0; z-- { q.QuoRem(q, tenInt, &r) - if r.Cmp(zeroInt) != 0 { + if r.Sign() != 0 { return false } } @@ -1045,7 +1143,7 @@ func (d Decimal) String() string { // NewFromFloat(5.45).StringFixed(1) // output: "5.5" // NewFromFloat(5.45).StringFixed(2) // output: "5.45" // NewFromFloat(5.45).StringFixed(3) // output: "5.450" -// NewFromFloat(545).StringFixed(-1) // output: "540" +// NewFromFloat(545).StringFixed(-1) // output: "550" // // Regardless of the UseScientificNotation option, the returned string will never be in scientific notation. func (d Decimal) StringFixed(places int32) string { @@ -1081,6 +1179,106 @@ func (d Decimal) StringFixedCash(interval uint8) string { return rounded.string(false, false) } +// Format implements fmt.Formatter, so decimals work with the fmt verbs: +// +// - %v and %s print String(), and %q, %x and %X quote it or print it in hex, as for any fmt.Stringer. +// - %f and %F print fixed-point notation. With a precision, as in %.2f, the decimal is rounded like +// StringFixed. Without one, it's printed exactly, like String() but never in scientific notation. +// Width and the '-', '+', ' ' and '0' flags work as they do for floats. +// - %#v prints Go syntax that recreates the decimal exactly, such as decimal.New(314, -2). +// +// Other verbs print fmt's usual error, such as %!d(decimal.Decimal=3.14). +func (d Decimal) Format(f fmt.State, verb rune) { + switch verb { + case 'v', 's', 'q', 'x', 'X': + if verb == 'v' && f.Flag('#') { + formatString(f, 's', d.goSyntax()) + } else { + formatString(f, verb, d.String()) + } + case 'f', 'F': + d.formatFixed(f) + default: + _, _ = fmt.Fprintf(f, "%%!%c(decimal.Decimal=%s)", verb, d.String()) + } +} + +// formatString formats s as fmt would for the directive that called Format, with verb in place of its own. +func formatString(f fmt.State, verb rune, s string) { + // Println and plain %v are the common case, and rebuilding the directive costs 3 allocations. + _, hasWidth := f.Width() + _, hasPrec := f.Precision() + if (verb == 'v' || verb == 's') && !hasWidth && !hasPrec { + _, _ = io.WriteString(f, s) + return + } + _, _ = fmt.Fprintf(f, fmtDirective(f, verb), s) +} + +// fmtDirective rebuilds the directive that called Format, as fmt.FormatString does from Go 1.20. +func fmtDirective(f fmt.State, verb rune) string { + b := []byte{'%'} + for _, flag := range "+-# 0" { + if f.Flag(int(flag)) { + b = append(b, byte(flag)) + } + } + if width, ok := f.Width(); ok { + b = strconv.AppendInt(b, int64(width), 10) + } + if prec, ok := f.Precision(); ok { + b = strconv.AppendInt(append(b, '.'), int64(prec), 10) + } + return string(append(b, string(verb)...)) +} + +func (d Decimal) formatFixed(f fmt.State) { + var s string + if prec, ok := f.Precision(); ok { + s = d.StringFixed(int32(prec)) + } else { + s = d.string(TrimTrailingZeros, false) + } + + sign := "" + switch { + case s[0] == '-': + sign, s = "-", s[1:] + case f.Flag('+'): + sign = "+" + case f.Flag(' '): + sign = " " + } + // Before Go 1.23, fmt keeps the width of an earlier directive when ok is false. + pad := 0 + if width, ok := f.Width(); ok { + pad = width - len(sign) - len(s) + } + switch { + case pad <= 0: + s = sign + s + case f.Flag('-'): + s = sign + s + strings.Repeat(" ", pad) + case f.Flag('0'): + s = sign + strings.Repeat("0", pad) + s + default: + s = strings.Repeat(" ", pad) + sign + s + } + _, _ = io.WriteString(f, s) +} + +func (d Decimal) goSyntax() string { + switch { + case d.value == nil: + return "decimal.Decimal{}" + case d.value.IsInt64(): + return fmt.Sprintf("decimal.New(%d, %d)", d.value.Int64(), d.exp) + default: + // Shift instead of an exponent in the string, which RequireFromString caps at MaxDecodeExponent. + return fmt.Sprintf("decimal.RequireFromString(%q).Shift(%d)", d.value.String(), d.exp) + } +} + // Round rounds the decimal to places decimal places. // If places < 0, it will round the integer part to the nearest 10^(-places). // @@ -1291,7 +1489,7 @@ func (d Decimal) Ceil() Decimal { // NOTE(vadim): must negate after casting to prevent int32 overflow z, m := new(big.Int).DivMod(d.getValue(), pow10(-int64(d.exp)), new(big.Int)) - if m.Cmp(zeroInt) != 0 { + if m.Sign() != 0 { z.Add(z, oneInt) } return Decimal{value: z, exp: 0} @@ -1305,9 +1503,9 @@ func (d Decimal) Ceil() Decimal { // // Example: // -// decimal.NewFromString("123.456").Truncate(2).String() // "123.45" -// decimal.NewFromString("5432").Truncate(-2).String() // "5400" -// decimal.NewFromString("-5432").Truncate(-2).String() // "-5400" +// decimal.RequireFromString("123.456").Truncate(2).String() // output: "123.45" +// decimal.RequireFromString("5432").Truncate(-2).String() // output: "5400" +// decimal.RequireFromString("-5432").Truncate(-2).String() // output: "-5400" func (d Decimal) Truncate(precision int32) Decimal { if -precision > d.exp { return d.rescale(-precision) diff --git a/vendor/github.com/shopspring/decimal/encoding.go b/vendor/github.com/shopspring/decimal/encoding.go index 792d9b12f..6801f9977 100644 --- a/vendor/github.com/shopspring/decimal/encoding.go +++ b/vendor/github.com/shopspring/decimal/encoding.go @@ -4,7 +4,9 @@ import ( "database/sql/driver" "encoding/binary" "fmt" + "math" "math/big" + "reflect" ) // UnmarshalJSON implements the json.Unmarshaler interface. @@ -79,12 +81,21 @@ func (d *Decimal) Scan(value interface{}) error { // first try to see if the data is stored in database as a Numeric datatype switch v := value.(type) { + case nil: + return fmt.Errorf("can't scan NULL into a Decimal, use NullDecimal or *Decimal") + case float32: - *d = NewFromFloat(float64(v)) + if math.IsNaN(float64(v)) || math.IsInf(float64(v), 0) { + return fmt.Errorf("could not convert value '%v' to decimal", v) + } + *d = NewFromFloat32(v) return nil case float64: // numeric in sqlite3 sends us float64 + if math.IsNaN(v) || math.IsInf(v, 0) { + return fmt.Errorf("could not convert value '%v' to decimal", v) + } *d = NewFromFloat(v) return nil @@ -99,6 +110,31 @@ func (d *Decimal) Scan(value interface{}) error { *d = NewFromUint64(v) return nil + case int, int8, int16, int32: + // clickhouse and test mocks send the other integer sizes + *d = New(reflect.ValueOf(v).Int(), 0) + return nil + + case uint, uint8, uint16, uint32: + *d = NewFromUint64(reflect.ValueOf(v).Uint()) + return nil + + case big.Int: + // clickhouse sends Int128, UInt128 and Int256 through database/sql as big.Int + *d = NewFromBigInt(&v, 0) + return nil + + case *big.Int: + if v != nil { + *d = NewFromBigInt(v, 0) + return nil + } + + case Decimal: + // clickhouse sends Decimal columns through its native API as Decimal + *d = v + return nil + case string: var err error *d, err = NewFromString(unquoteIfQuoted(v)) @@ -108,10 +144,8 @@ func (d *Decimal) Scan(value interface{}) error { var err error *d, err = NewFromString(unquoteIfQuoted(string(v))) return err - - default: - return fmt.Errorf("could not convert value '%+v' to any known type", value) } + return fmt.Errorf("could not convert value '%+v' to any known type", value) } // Value implements the driver.Valuer interface for database serialization. @@ -159,6 +193,144 @@ func (d Decimal) EncodeSpanner() (interface{}, error) { return d.String(), nil } +// BSON type numbers, see https://bsonspec.org/spec.html +const ( + bsonTypeDouble byte = 0x01 + bsonTypeString byte = 0x02 + bsonTypeUndefined byte = 0x06 + bsonTypeNull byte = 0x0A + bsonTypeInt32 byte = 0x10 + bsonTypeInt64 byte = 0x12 + bsonTypeDecimal128 byte = 0x13 +) + +// MarshalBSONValue implements the bson.ValueMarshaler interface of the MongoDB Go driver v2. It stores +// the decimal as a BSON Decimal128, MongoDB's decimal type, which holds 34 significant digits and +// exponents from -6176 to 6111. Trailing zeros move between the coefficient and the exponent to fit, so +// Exponent() can change in a round trip but the value can't. Decimals that still don't fit return an +// error instead of being rounded. +// +// The v1 driver declares this interface with its own bsontype.Type, so it doesn't call this method. +func (d Decimal) MarshalBSONValue() (byte, []byte, error) { + coef := new(big.Int).Abs(d.getValue()) + exp := d.exp + + // Zero fits at any exponent, and the loops below could take 2^31 steps to get there. + if coef.Sign() == 0 { + if exp < decimal128MinExp { + exp = decimal128MinExp + } else if exp > decimal128MaxExp { + exp = decimal128MaxExp + } + } + + quo, rem := new(big.Int), new(big.Int) + for (coef.Cmp(decimal128MaxCoef) > 0 || exp < decimal128MinExp) && exp < decimal128MaxExp { + if quo.QuoRem(coef, tenInt, rem); rem.Sign() != 0 { + break + } + coef, quo = quo, coef + exp++ + } + for exp > decimal128MaxExp && coef.Cmp(decimal128MaxCoef) <= 0 { + coef.Mul(coef, tenInt) + exp-- + } + if coef.Cmp(decimal128MaxCoef) > 0 || exp < decimal128MinExp { + return 0, nil, fmt.Errorf("can't encode %se%d as BSON Decimal128 without rounding: it holds 34 significant digits and exponents from %d to %d", + d.getValue(), d.exp, decimal128MinExp, decimal128MaxExp) + } + return bsonTypeDecimal128, encodeDecimal128(d.Sign() < 0, coef, exp), nil +} + +// UnmarshalBSONValue implements the bson.ValueUnmarshaler interface of the MongoDB Go driver v2. +// It decodes BSON Decimal128, string, double, int32 and int64 values. BSON null and undefined decode +// to zero, as they do for the driver's own number types. +func (d *Decimal) UnmarshalBSONValue(typ byte, data []byte) error { + var err error + switch { + case typ == bsonTypeNull || typ == bsonTypeUndefined: + *d = Decimal{} + case typ == bsonTypeDecimal128 && len(data) == 16: + *d, err = decodeDecimal128(data) + case typ == bsonTypeString && len(data) >= 5: + // int32 length, the string, then a NUL byte + *d, err = NewFromString(string(data[4 : len(data)-1])) + case typ == bsonTypeDouble && len(data) == 8: + f := math.Float64frombits(binary.LittleEndian.Uint64(data)) + if math.IsNaN(f) || math.IsInf(f, 0) { + return fmt.Errorf("can't convert BSON double %v to decimal", f) + } + *d = NewFromFloat(f) + case typ == bsonTypeInt32 && len(data) == 4: + *d = New(int64(int32(binary.LittleEndian.Uint32(data))), 0) + case typ == bsonTypeInt64 && len(data) == 8: + *d = New(int64(binary.LittleEndian.Uint64(data)), 0) + default: + return fmt.Errorf("can't convert BSON value of type 0x%02x and length %d to decimal", typ, len(data)) + } + return err +} + +// BSON stores a Decimal128 as a little-endian IEEE 754-2008 decimal128 in the binary integer decimal +// encoding: from the top bit down, a sign bit, a 14-bit exponent biased by 6176 and a 113-bit coefficient. +const ( + decimal128MinExp = -6176 + decimal128MaxExp = 6111 +) + +// decimal128MaxCoef is 10^34 - 1, the largest Decimal128 coefficient. +var decimal128MaxCoef = new(big.Int).Sub(new(big.Int).Exp(tenInt, big.NewInt(34), nil), oneInt) + +// encodeDecimal128 expects a coefficient and exponent that are already in range. +func encodeDecimal128(neg bool, coef *big.Int, exp int32) []byte { + var buf [16]byte + b := coef.Bytes() + copy(buf[16-len(b):], b) + hi := binary.BigEndian.Uint64(buf[:8]) | uint64(exp-decimal128MinExp)<<49 + if neg { + hi |= 1 << 63 + } + data := make([]byte, 16) + binary.LittleEndian.PutUint64(data, binary.BigEndian.Uint64(buf[8:])) + binary.LittleEndian.PutUint64(data[8:], hi) + return data +} + +func decodeDecimal128(data []byte) (Decimal, error) { + lo := binary.LittleEndian.Uint64(data) + hi := binary.LittleEndian.Uint64(data[8:]) + neg := hi>>63 == 1 + + var exp int32 + switch { + case hi>>59&0xF == 0xF: + return Decimal{}, fmt.Errorf("can't convert BSON Decimal128 NaN or Infinity to decimal") + case hi>>61&3 == 3: + // The exponent starts 2 bits lower, and the coefficient is always above 10^34 - 1. + exp, hi, lo = int32(hi>>47&0x3FFF), 0, 0 + default: + exp, hi = int32(hi>>49&0x3FFF), hi&(1<<49-1) + } + exp += decimal128MinExp + if int64(exp) > int64(MaxDecodeExponent) || int64(exp) < -int64(MaxDecodeExponent) { + return Decimal{}, fmt.Errorf("can't convert BSON Decimal128 to decimal: exponent %d exceeds MaxDecodeExponent (%d)", exp, MaxDecodeExponent) + } + + var buf [16]byte + binary.BigEndian.PutUint64(buf[:8], hi) + binary.BigEndian.PutUint64(buf[8:], lo) + value := new(big.Int).SetBytes(buf[:]) + // IEEE 754 reads coefficients above 10^34 - 1 as zero. + if value.Cmp(decimal128MaxCoef) > 0 { + value.SetInt64(0) + } + if neg { + value.Neg(value) + } + return Decimal{value: value, exp: exp}, nil +} + func unquoteIfQuoted(value string) string { // If the amount is quoted, strip the quotes if len(value) > 2 && value[0] == '"' && value[len(value)-1] == '"' { @@ -274,3 +446,20 @@ func (d NullDecimal) EncodeSpanner() (interface{}, error) { } return d.Decimal.String(), nil } + +// MarshalBSONValue implements the bson.ValueMarshaler interface of the MongoDB Go driver v2. +// An invalid NullDecimal is stored as BSON null, see Decimal.MarshalBSONValue for the rest. +func (d NullDecimal) MarshalBSONValue() (byte, []byte, error) { + if !d.Valid { + return bsonTypeNull, nil, nil + } + return d.Decimal.MarshalBSONValue() +} + +// UnmarshalBSONValue implements the bson.ValueUnmarshaler interface of the MongoDB Go driver v2. +// BSON null and undefined make the NullDecimal invalid, see Decimal.UnmarshalBSONValue for the rest. +func (d *NullDecimal) UnmarshalBSONValue(typ byte, data []byte) error { + err := d.Decimal.UnmarshalBSONValue(typ, data) + d.Valid = err == nil && typ != bsonTypeNull && typ != bsonTypeUndefined + return err +} diff --git a/vendor/github.com/shopspring/decimal/math.go b/vendor/github.com/shopspring/decimal/math.go index 6100afb56..e5c7d5c37 100644 --- a/vendor/github.com/shopspring/decimal/math.go +++ b/vendor/github.com/shopspring/decimal/math.go @@ -350,14 +350,14 @@ func powRatio(d Decimal) (*big.Int, *big.Int) { return p.Quo(p, g), q.Quo(q, g) } -// iroot returns the integer k-th root of x >= 1 and whether it is exact. +// iroot returns the integer k-th root of x >= 1, rounded down, and whether it is exact. func iroot(x *big.Int, k int64) (*big.Int, bool) { if k == 1 || x.Cmp(oneInt) == 0 { return x, true } if int64(x.BitLen()) <= k { - // 1 < x < 2^k has no integer k-th root - return nil, false + // 1 < x < 2^k + return big.NewInt(1), false } // Newton's method from above converges to the floor of the root kb, km1 := big.NewInt(k), big.NewInt(k-1) @@ -597,6 +597,97 @@ func abs64(n int64) int64 { return n } +// Sqrt returns the square root of d with DivisionPrecision digits after the decimal point, like Div. +// Use SqrtRound to choose the precision per call. It returns an error for negative d. +// +// Example: +// +// d, err := NewFromInt(2).Sqrt() +// d.String() // output: "1.414213562373095" +func (d Decimal) Sqrt() (Decimal, error) { + return d.SqrtRound(int32(DivisionPrecision)) +} + +// SqrtRound returns the square root of d rounded half away from zero to places digits after the +// decimal point, like DivRound. The result is exact up to that rounding. It returns an error for +// negative d. +// +// Example: +// +// d, err := NewFromFloat(0.002342).SqrtRound(4) +// d.String() // output: "0.0484" +func (d Decimal) SqrtRound(places int32) (Decimal, error) { + if d.Sign() < 0 { + return Decimal{}, fmt.Errorf("cannot represent imaginary value of sqrt(x), where x < 0") + } + + // floor(sqrt(d) * 10^(places+1)) is the integer square root of d * 10^(2*places+2), and its + // last digit decides the rounding. Below 1 that product truncates to an integer first, which + // doesn't change the floor, and when it's below 1 the result is 0. + k := int64(d.exp) + 2*int64(places) + 2 + n := new(big.Int) + if k >= 0 { + n.Mul(d.getValue(), pow10(k)) + } else if -k <= int64(d.NumDigits()) { + n.Quo(d.getValue(), pow10(-k)) + } + n.Sqrt(n) + n.Add(n, fiveInt).Quo(n, tenInt) + return Decimal{value: n, exp: -places}, nil +} + +// Root returns the n-th root of d with DivisionPrecision digits after the decimal point, like Div. +// Use RootRound to choose the precision per call. Odd roots of negative numbers are negative. +// It returns an error when n < 1, and for negative d when n is even. +// +// Example: +// +// d, err := NewFromInt(2).Root(3) +// d.String() // output: "1.2599210498948732" +func (d Decimal) Root(n int64) (Decimal, error) { + return d.RootRound(n, int32(DivisionPrecision)) +} + +// RootRound returns the n-th root of d rounded half away from zero to places digits after the +// decimal point, like DivRound. The result is exact up to that rounding. Odd roots of negative +// numbers are negative. It returns an error when n < 1, and for negative d when n is even. +// The work grows with n times places, so very large roots such as the millionth are slow. +// +// Example: +// +// d, err := NewFromFloat(-0.125).RootRound(3, 2) +// d.String() // output: "-0.5" +func (d Decimal) RootRound(n int64, places int32) (Decimal, error) { + if n < 1 { + return Decimal{}, fmt.Errorf("cannot calculate the %d-th root, n must be at least 1", n) + } + if d.Sign() < 0 && n%2 == 0 { + return Decimal{}, fmt.Errorf("cannot represent imaginary value of an even root of x, where x < 0") + } + + // floor(root(|d|) * 10^(places+1)) is the integer n-th root of |d| * 10^(n*(places+1)), and its + // last digit decides the rounding, as in SqrtRound. + k := int64(d.exp) + n*(int64(places)+1) + x := new(big.Int).Abs(d.getValue()) + if k >= 0 { + x.Mul(x, pow10(k)) + } else if -k <= int64(d.NumDigits()) { + x.Quo(x, pow10(-k)) + } else { + x.SetInt64(0) + } + r := new(big.Int) + if x.Sign() > 0 { + root, _ := iroot(x, n) + r.Set(root) + } + r.Add(r, fiveInt).Quo(r, tenInt) + if d.Sign() < 0 { + r.Neg(r) + } + return Decimal{value: r, exp: -places}, nil +} + // ExpHullAbrham calculates the natural exponent of decimal (e to the power of d) using Hull-Abraham algorithm. // OverallPrecision argument specifies the overall precision of the result (integer part + decimal part). // @@ -604,8 +695,11 @@ func abs64(n int64) int64 { // // Example: // -// NewFromFloat(26.1).ExpHullAbrham(2).String() // output: "220000000000" -// NewFromFloat(26.1).ExpHullAbrham(20).String() // output: "216314672147.05767284" +// d1, err := NewFromFloat(26.1).ExpHullAbrham(2) +// d1.String() // output: "220000000000" +// +// d2, err := NewFromFloat(26.1).ExpHullAbrham(20) +// d2.String() // output: "216314672147.05767284" func (d Decimal) ExpHullAbrham(overallPrecision uint32) (Decimal, error) { // Algorithm based on Variable precision exponential function. // ACM Transactions on Mathematical Software by T. E. Hull & A. Abrham. @@ -675,14 +769,13 @@ func (d Decimal) ExpHullAbrham(overallPrecision uint32) (Decimal, error) { } res := Decimal{new(big.Int).Exp(sum.getValue(), big.NewInt(ki), nil), int32(expInt64)} - resNumDigits := int32(res.NumDigits()) - - var roundDigits int32 - if resNumDigits > abs(res.exp) { - roundDigits = int32(currentPrecision) - resNumDigits - res.exp - } else { - roundDigits = int32(currentPrecision) + // Round to overallPrecision significant figures, at least 1. A raised currentPrecision only keeps + // the calculation precise, it doesn't add digits to the result. + sig := int32(overallPrecision) + if sig == 0 { + sig = 1 } + roundDigits := sig - int32(res.NumDigits()) - res.exp res = res.Round(roundDigits) @@ -697,14 +790,14 @@ func (d Decimal) ExpHullAbrham(overallPrecision uint32) (Decimal, error) { // // Example: // -// d, err := NewFromFloat(26.1).ExpTaylor(2).String() -// d.String() // output: "216314672147.06" +// d1, err := NewFromFloat(26.1).ExpTaylor(2) +// d1.String() // output: "216314672147.06" // -// NewFromFloat(26.1).ExpTaylor(20).String() -// d.String() // output: "216314672147.05767284062928674083" +// d2, err := NewFromFloat(26.1).ExpTaylor(20) +// d2.String() // output: "216314672147.05767284062928674083" // -// NewFromFloat(26.1).ExpTaylor(-10).String() -// d.String() // output: "220000000000" +// d3, err := NewFromFloat(26.1).ExpTaylor(-10) +// d3.String() // output: "220000000000" func (d Decimal) ExpTaylor(precision int32) (Decimal, error) { // Note(mwoss): Implementation can be optimized by exclusively using big.Int API only if d.IsZero() { @@ -769,7 +862,7 @@ func (d Decimal) ExpTaylor(precision int32) (Decimal, error) { // Ln calculates natural logarithm of d. // Precision argument specifies how precise the result must be (number of digits after decimal point). -// Negative precision is allowed. +// Negative precision is allowed. The result is correctly rounded half away from zero. // // Example: // @@ -779,120 +872,49 @@ func (d Decimal) ExpTaylor(precision int32) (Decimal, error) { // d2, err := NewFromFloat(579.161).Ln(10) // d2.String() // output: "6.3615805046" func (d Decimal) Ln(precision int32) (Decimal, error) { - // Algorithm based on The Use of Iteration Methods for Approximating the Natural Logarithm, - // James F. Epperson, The American Mathematical Monthly, Vol. 96, No. 9, November 1989, pp. 831-835. if d.IsNegative() { return Decimal{}, fmt.Errorf("cannot calculate natural logarithm for negative decimals") } - if d.IsZero() { return Decimal{}, fmt.Errorf("cannot represent natural logarithm of 0, result: -infinity") } - calcPrecision := precision + 2 - z := d.Copy() - - var comp1, comp3, comp2, comp4, reduceAdjust Decimal - comp1 = z.Sub(Decimal{oneInt, 0}) - comp3 = Decimal{oneInt, -1} - - // for decimal in range [0.9, 1.1] where ln(d) is close to 0 - usePowerSeries := false - - if comp1.Abs().Cmp(comp3) <= 0 { - usePowerSeries = true - } else { - // reduce input decimal to range [0.1, 1) - expDelta := int32(z.NumDigits()) + z.exp - z.exp -= expDelta - - // Input decimal was reduced by factor of 10^expDelta, thus we will need to add - // ln(10^expDelta) = expDelta * ln(10) - // to the result to compensate that - ln10 := ln10.withPrecision(calcPrecision) - reduceAdjust = NewFromInt32(expDelta) - reduceAdjust = reduceAdjust.Mul(ln10) - - comp1 = z.Sub(Decimal{oneInt, 0}) - - if comp1.Abs().Cmp(comp3) <= 0 { - usePowerSeries = true - } else { - // initial estimate using floats - zFloat := z.InexactFloat64() - comp1 = NewFromFloat(math.Log(zFloat)) - } - } - - epsilon := Decimal{oneInt, -calcPrecision} - - if usePowerSeries { - // Power Series - https://en.wikipedia.org/wiki/Logarithm#Power_series - // Calculating n-th term of formula: ln(z+1) = 2 sum [ 1 / (2n+1) * (z / (z+2))^(2n+1) ] - // until the difference between current and next term is smaller than epsilon. - // Coverage quite fast for decimals close to 1.0 - - // z + 2 - comp2 = comp1.Add(Decimal{twoInt, 0}) - // z / (z + 2) - comp3 = comp1.DivRound(comp2, calcPrecision) - // 2 * (z / (z + 2)) - comp1 = comp3.Add(comp3) - comp2 = comp1.Copy() - - for n := 1; ; n++ { - // 2 * (z / (z+2))^(2n+1) - comp2 = comp2.Mul(comp3).Mul(comp3) - - // 1 / (2n+1) * 2 * (z / (z+2))^(2n+1) - comp4 = NewFromInt(int64(2*n + 1)) - comp4 = comp2.DivRound(comp4, calcPrecision) - - // comp1 = 2 sum [ 1 / (2n+1) * (z / (z+2))^(2n+1) ] - comp1 = comp1.Add(comp4) - - if comp4.Abs().Cmp(epsilon) <= 0 { - break - } + // d = m * 10^k with 1 <= m < 10, so ln(d) = ln(m) + k*ln(10). Both are computed with error bounds, + // and the working precision grows until the whole interval rounds to the same value. That ends, + // because ln(d) is irrational for every d other than 1. + k := int64(d.NumDigits()) - 1 + int64(d.exp) + f := int64(precision) + 10 + if f < 10 { + f = 10 + } + for ; ; f += 20 { + b := uint(float64(f)*math.Log2(10)) + uint(bits.Len64(uint64(abs64(k)))) + 8 + m := new(big.Int).Lsh(d.getValue(), b) + m.Quo(m, pow10(int64(d.NumDigits())-1)) + t, lnErr := lnFixed(m, b) + ln10, ln10Err := ln10Fixed(b) + t.Add(t, new(big.Int).Mul(big.NewInt(k), ln10)) + tErr := big.NewInt(lnErr + 1 + abs64(k)*ln10Err) + + neg := t.Sign() < 0 + t.Abs(t) + p := pow10(f) + hi := new(big.Int).Add(t, tErr) + hi.Mul(hi, p).Rsh(hi, b).Add(hi, oneInt) + lo := t.Sub(t, tErr) + if lo.Sign() < 0 { + lo.SetInt64(0) } - } else { - // Halley's Iteration. - // Calculating n-th term of formula: a_(n+1) = a_n - 2 * (exp(a_n) - z) / (exp(a_n) + z), - // until the difference between current and next term is smaller than epsilon - var prevStep Decimal - maxIters := calcPrecision*2 + 10 - - for i := int32(0); i < maxIters; i++ { - // exp(a_n) - comp3, _ = comp1.ExpTaylor(calcPrecision) - // exp(a_n) - z - comp2 = comp3.Sub(z) - // 2 * (exp(a_n) - z) - comp2 = comp2.Add(comp2) - // exp(a_n) + z - comp4 = comp3.Add(z) - // 2 * (exp(a_n) - z) / (exp(a_n) + z) - comp3 = comp2.DivRound(comp4, calcPrecision) - // comp1 = a_(n+1) = a_n - 2 * (exp(a_n) - z) / (exp(a_n) + z) - comp1 = comp1.Sub(comp3) - - if prevStep.Add(comp3).IsZero() { - // If iteration steps oscillate we should return early and prevent an infinity loop - // NOTE(mwoss): This should be quite a rare case, returning error is not necessary - break - } + lo.Mul(lo, p).Rsh(lo, b) - if comp3.Abs().Cmp(epsilon) <= 0 { - break + g := f - int64(precision) + if q := roundHalfUp(hi, g); q.Cmp(roundHalfUp(lo, g)) == 0 { + if neg { + q.Neg(q) } - - prevStep = comp3 + return Decimal{value: q, exp: -precision}, nil } } - - comp1 = comp1.Add(reduceAdjust) - - return comp1.Round(precision), nil } // Trig functions diff --git a/vendor/github.com/shopspring/decimal/rounding.go b/vendor/github.com/shopspring/decimal/rounding.go deleted file mode 100644 index d4b0cd007..000000000 --- a/vendor/github.com/shopspring/decimal/rounding.go +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Multiprecision decimal numbers. -// For floating-point formatting only; not general purpose. -// Only operations are assign and (binary) left/right shift. -// Can do binary floating point in multiprecision decimal precisely -// because 2 divides 10; cannot do decimal floating point -// in multiprecision binary precisely. - -package decimal - -type floatInfo struct { - mantbits uint - expbits uint - bias int -} - -var float32info = floatInfo{23, 8, -127} -var float64info = floatInfo{52, 11, -1023} - -// roundShortest rounds d (= mant * 2^exp) to the shortest number of digits -// that will let the original floating point value be precisely reconstructed. -func roundShortest(d *decimal, mant uint64, exp int, flt *floatInfo) { - // If mantissa is zero, the number is zero; stop now. - if mant == 0 { - d.nd = 0 - return - } - - // Compute upper and lower such that any decimal number - // between upper and lower (possibly inclusive) - // will round to the original floating point number. - - // We may see at once that the number is already shortest. - // - // Suppose d is not denormal, so that 2^exp <= d < 10^dp. - // The closest shorter number is at least 10^(dp-nd) away. - // The lower/upper bounds computed below are at distance - // at most 2^(exp-mantbits). - // - // So the number is already shortest if 10^(dp-nd) > 2^(exp-mantbits), - // or equivalently log2(10)*(dp-nd) > exp-mantbits. - // It is true if 332/100*(dp-nd) >= exp-mantbits (log2(10) > 3.32). - minexp := flt.bias + 1 // minimum possible exponent - if exp > minexp && 332*(d.dp-d.nd) >= 100*(exp-int(flt.mantbits)) { - // The number is already shortest. - return - } - - // d = mant << (exp - mantbits) - // Next highest floating point number is mant+1 << exp-mantbits. - // Our upper bound is halfway between, mant*2+1 << exp-mantbits-1. - upper := new(decimal) - upper.Assign(mant*2 + 1) - upper.Shift(exp - int(flt.mantbits) - 1) - - // d = mant << (exp - mantbits) - // Next lowest floating point number is mant-1 << exp-mantbits, - // unless mant-1 drops the significant bit and exp is not the minimum exp, - // in which case the next lowest is mant*2-1 << exp-mantbits-1. - // Either way, call it mantlo << explo-mantbits. - // Our lower bound is halfway between, mantlo*2+1 << explo-mantbits-1. - var mantlo uint64 - var explo int - if mant > 1<= d.nd { - break - } - li := ui - upper.dp + lower.dp - l := byte('0') // lower digit - if li >= 0 && li < lower.nd { - l = lower.d[li] - } - m := byte('0') // middle digit - if mi >= 0 { - m = d.d[mi] - } - u := byte('0') // upper digit - if ui < upper.nd { - u = upper.d[ui] - } - - // Okay to round down (truncate) if lower has a different digit - // or if lower is inclusive and is exactly the result of rounding - // down (i.e., and we have reached the final digit of lower). - okdown := l != m || inclusive && li+1 == lower.nd - - switch { - case upperdelta == 0 && m+1 < u: - // Example: - // m = 12345xxx - // u = 12347xxx - upperdelta = 2 - case upperdelta == 0 && m != u: - // Example: - // m = 12345xxx - // u = 12346xxx - upperdelta = 1 - case upperdelta == 1 && (m != '9' || u != '0'): - // Example: - // m = 1234598x - // u = 1234600x - upperdelta = 2 - } - // Okay to round up if upper has a different digit and either upper - // is inclusive or upper is bigger than the result of rounding up. - okup := upperdelta > 0 && (inclusive || upperdelta > 1 || ui+1 < upper.nd) - - // If it's okay to do either, then round to the nearest one. - // If it's okay to do only one, do it. - switch { - case okdown && okup: - d.Round(mi + 1) - return - case okdown: - d.RoundDown(mi + 1) - return - case okup: - d.RoundUp(mi + 1) - return - } - } -} diff --git a/vendor/github.com/sirosfoundation/go-trust/pkg/authzen/types.go b/vendor/github.com/sirosfoundation/go-trust/pkg/authzen/types.go index 1b4856a5a..6cbdf5f42 100644 --- a/vendor/github.com/sirosfoundation/go-trust/pkg/authzen/types.go +++ b/vendor/github.com/sirosfoundation/go-trust/pkg/authzen/types.go @@ -55,7 +55,7 @@ type EvaluationRequest struct { Subject Subject `json:"subject"` // The name to be bound to the key Resource Resource `json:"resource"` // The public key to be validated Action *Action `json:"action,omitempty"` // Optional role constraint - Context map[string]interface{} `json:"context,omitempty" swaggertype:"object,string"` // Optional context (MUST NOT be critical) + Context map[string]interface{} `json:"context,omitempty" swaggertype:"object,string"` // Optional context (MUST NOT be critical). Recognised member: verifier_id_type narrows context.verifier_ids in the response to that one type } // EvaluationResponse represents the authorization decision response in the AuthZEN protocol. @@ -78,6 +78,89 @@ type EvaluationResponseContext struct { // For OpenID Federation: contains the Entity Configuration // This field is set when trust_metadata is requested or for resolution-only requests. TrustMetadata interface{} `json:"trust_metadata,omitempty" swaggertype:"object"` // DID Document or Entity Configuration + // VerifierIDs lists verifier identifiers the PDP derived from authenticated + // material, for wallets that need a stable identifier string for the relying + // party (for example as input to a pseudonym function). It is present only + // when the policy enables it (constraints.return_verifier_ids), the decision + // is true, and the identifier was verified. Informational, never critical. + VerifierIDs []VerifierID `json:"verifier_ids,omitempty"` // Verified verifier identifiers +} + +// Verifier identifier types a PDP can return in EvaluationResponseContext.VerifierIDs. +// Clients treat the type string as opaque; the PDP defines the exact form of each +// value (see VerifierID). +const ( + // VerifierIDTypeSemantic is "semantic_id:" followed by the ETSI semantic + // identifier (EN 319 412-1 5.1.3) from the access certificate. + VerifierIDTypeSemantic = "semantic" + // VerifierIDTypeDNS (x509_san_dns) is the dNSName SAN value, + // in its ASCII (A-label) form, ASCII lower case, without a trailing dot. + // An internationalised name is its A-label (xn--...); a U-label is not converted. + VerifierIDTypeDNS = "x509_san_dns" + // VerifierIDTypeURI (x509_san_uri) is the uniformResourceIdentifier SAN + // value, byte-for-byte as bound. + VerifierIDTypeURI = "x509_san_uri" + // VerifierIDTypeDID is the full DID (without fragment) of a resolved DID + // document whose verification method matched the presented key. + VerifierIDTypeDID = "decentralized_identifier" + // VerifierIDTypeOIDFEntity is the OpenID Federation Entity ID (https URL), + // byte-for-byte as in the validated trust chain. + VerifierIDTypeOIDFEntity = "openid_federation" +) + +// Basis values describe how a verifier identifier was verified. +const ( + VerifierIDBasisX5CChain = "x5c-chain" + VerifierIDBasisClientIDBinding = "client-id-binding" + VerifierIDBasisDIDResolution = "did-resolution" + VerifierIDBasisOIDFTrustChain = "oidf-trust-chain" +) + +// VerifierIDSemanticPrefix precedes the ETSI semantic identifier in a +// "semantic" verifier identifier. +const VerifierIDSemanticPrefix = "semantic_id:" + +// Request/context keys of the verifier_ids feature. +const ( + // VerifierIDHintContextKey is the optional request context member that + // narrows the response to one verifier identifier type. + VerifierIDHintContextKey = "verifier_id_type" + // VerifierIDsPolicyContextKey carries the policy's enabled types to the + // registries. Server-controlled: a client cannot set it. + VerifierIDsPolicyContextKey = "return_verifier_ids" +) + +// SupportedVerifierIDTypes lists the verifier identifier types go-trust can derive. +func SupportedVerifierIDTypes() []string { + return []string{ + VerifierIDTypeSemantic, + VerifierIDTypeDNS, + VerifierIDTypeURI, + VerifierIDTypeDID, + VerifierIDTypeOIDFEntity, + } +} + +// IsSupportedVerifierIDType reports whether t is a type go-trust can derive. +func IsSupportedVerifierIDType(t string) bool { + for _, s := range SupportedVerifierIDTypes() { + if s == t { + return true + } + } + return false +} + +// VerifierID is one verifier identifier in the evaluation response context. +// @Description A verifier identifier derived by the PDP from authenticated material +type VerifierID struct { + // Type is an opaque type string, for example "semantic" or "x509_san_dns". + Type string `json:"verifier_id_type" example:"semantic"` + // ID is the identifier in the canonical form defined for the type. + ID string `json:"verifier_id" example:"semantic_id:VATSE-556000000101"` + // Basis states how the value was verified, for example "x5c-chain", + // "client-id-binding", "did-resolution" or "oidf-trust-chain". + Basis string `json:"basis,omitempty" example:"x5c-chain"` } // Validate checks if the EvaluationRequest is compliant with the AuthZEN Trust Registry Profile. diff --git a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/clientid.go b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/clientid.go index 6619f729c..31a642c32 100644 --- a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/clientid.go +++ b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/clientid.go @@ -109,20 +109,22 @@ func VerifyLeafBinding(scheme ClientIDScheme, value string, leaf *x509.Certifica } // DNSSANMatches reports whether clientID matches one of dnsNames, per -// OpenID4VP's x509_san_dns semantics (exact match) with RFC 6125 single-label -// wildcard support: "*.example.com" matches "sub.example.com" but not -// "example.com" or "deep.sub.example.com". +// OpenID4VP's x509_san_dns semantics with RFC 6125 single-label wildcard +// support: "*.example.com" matches "sub.example.com" but not "example.com" or +// "deep.sub.example.com". Comparison is ASCII case-insensitive, as DNS names +// are; nothing else is folded, so a non-ASCII clientID (a U-label) never +// matches: an internationalised name must be presented as its A-label. func DNSSANMatches(clientID string, dnsNames []string) bool { for _, dnsName := range dnsNames { - if dnsName == clientID { + if equalASCIIFold(dnsName, clientID) { return true } if strings.HasPrefix(dnsName, "*.") { suffix := dnsName[1:] // *.example.com -> .example.com baseDomain := dnsName[2:] // *.example.com -> example.com - if strings.HasSuffix(clientID, suffix) && clientID != baseDomain { + if len(clientID) > len(suffix) && equalASCIIFold(clientID[len(clientID)-len(suffix):], suffix) && !equalASCIIFold(clientID, baseDomain) { // Ensure only a single label before the suffix (no nested subdomains). - prefix := strings.TrimSuffix(clientID, suffix) + prefix := clientID[:len(clientID)-len(suffix)] if !strings.Contains(prefix, ".") { return true } @@ -132,6 +134,28 @@ func DNSSANMatches(clientID string, dnsNames []string) bool { return false } +// equalASCIIFold reports whether a and b are equal when only ASCII letters are +// case-folded. Unlike strings.EqualFold it never folds non-ASCII characters +// (U+212A KELVIN SIGN would otherwise equal "k"). +func equalASCIIFold(a, b string) bool { + if len(a) != len(b) { + return false + } + for i := 0; i < len(a); i++ { + x, y := a[i], b[i] + if x >= 'A' && x <= 'Z' { + x += 'a' - 'A' + } + if y >= 'A' && y <= 'Z' { + y += 'a' - 'A' + } + if x != y { + return false + } + } + return true +} + // URISANMatches reports whether clientID matches one of the certificate's // URI SANs, per OpenID4VP's x509_san_uri semantics (exact match). func URISANMatches(clientID string, uris []*url.URL) bool { diff --git a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/composite.go b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/composite.go index 6ae6cee70..cb88cf4ec 100644 --- a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/composite.go +++ b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/composite.go @@ -174,6 +174,7 @@ func (c *CompositeRegistry) applyLogic(results []compositeResult) *authzen.Evalu // Count agreements and build details var agreedCount, disagreedCount, errorCount int var agreedRegistries, disagreedRegistries []string + var positive []*authzen.EvaluationResponse var details []map[string]interface{} for _, r := range results { @@ -191,6 +192,7 @@ func (c *CompositeRegistry) applyLogic(results []compositeResult) *authzen.Evalu disagreedRegistries = append(disagreedRegistries, info.Name) } else if r.response != nil && r.response.Decision { agreedCount++ + positive = append(positive, r.response) detail["decision"] = true agreedRegistries = append(agreedRegistries, info.Name) } else { @@ -248,12 +250,17 @@ func (c *CompositeRegistry) applyLogic(results []compositeResult) *authzen.Evalu reason["error"] = fmt.Sprintf("unknown operator: %s", c.operator) } - return &authzen.EvaluationResponse{ + resp := &authzen.EvaluationResponse{ Decision: decision, Context: &authzen.EvaluationResponseContext{ Reason: reason, }, } + // Every identifier was verified by a child that returned true; carry them + // through when the composite as a whole allows (AND: all children, OR, + // MAJORITY and QUORUM: the agreeing ones). + mergeVerifierIDs(resp, positive) + return resp } // SupportedResourceTypes returns the union of all child registry resource types diff --git a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/did_vm_policy.go b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/did_vm_policy.go new file mode 100644 index 000000000..527c8531f --- /dev/null +++ b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/did_vm_policy.go @@ -0,0 +1,60 @@ +package registry + +import ( + "time" + + "github.com/sirosfoundation/go-trust/pkg/authzen" +) + +// DenyMissingVerificationMethods enforces the did.required_verification_methods +// policy constraint, which the manager injects into the request context under +// "required_verification_methods". It is shared by every DID-resolving +// registry (did:web, did:webvh, did:jwks and the generic DID resolver). +// +// The DID document must contain ALL of the required types among the `type` +// values of its top-level verificationMethod array (exact, case-sensitive, +// like required_services). Methods embedded in relationship arrays such as +// authentication or assertionMethod are not considered. It returns nil when +// the constraint is unset or satisfied, otherwise a deny response. +func DenyMissingVerificationMethods[T any](ctx map[string]interface{}, methods []T, typeOf func(T) string, startTime time.Time) *authzen.EvaluationResponse { + required := contextStrings(ctx["required_verification_methods"]) + if len(required) == 0 { + return nil + } + present := make(map[string]bool, len(methods)) + for _, m := range methods { + present[typeOf(m)] = true + } + for _, r := range required { + if !present[r] { + return &authzen.EvaluationResponse{ + Decision: false, + Context: &authzen.EvaluationResponseContext{ + Reason: map[string]interface{}{ + "error": "DID document missing required verification methods for this role", + "required_verification_methods": required, + "resolution_ms": time.Since(startTime).Milliseconds(), + }, + }, + } + } + } + return nil +} + +// contextStrings converts a context value ([]string or []interface{}) to []string. +func contextStrings(v interface{}) []string { + switch s := v.(type) { + case []string: + return s + case []interface{}: + out := make([]string, 0, len(s)) + for _, item := range s { + if str, ok := item.(string); ok { + out = append(out, str) + } + } + return out + } + return nil +} diff --git a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/didweb/didweb_registry.go b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/didweb/didweb_registry.go index 7d4b4ac57..cbbd24dcb 100644 --- a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/didweb/didweb_registry.go +++ b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/didweb/didweb_registry.go @@ -198,7 +198,7 @@ func (r *DIDWebRegistry) Evaluate(ctx context.Context, req *authzen.EvaluationRe } // Success - key binding is valid - return &authzen.EvaluationResponse{ + resp := &authzen.EvaluationResponse{ Decision: true, Context: &authzen.EvaluationResponseContext{ Reason: map[string]interface{}{ @@ -210,7 +210,9 @@ func (r *DIDWebRegistry) Evaluate(ctx context.Context, req *authzen.EvaluationRe }, TrustMetadata: r.didDocumentToTrustMetadata(didDoc), }, - }, nil + } + registry.AddDIDVerifierID(resp, req, didDoc.ID) + return resp, nil } // buildResolutionOnlyResponse creates an EvaluationResponse for resolution-only requests. @@ -451,6 +453,12 @@ func (r *DIDWebRegistry) checkPolicyConstraints(req *authzen.EvaluationRequest, } } + // Check required_verification_methods: the DID document must contain every + // listed verificationMethod[].type (exact match, like required_services). + if didWebVMDenial := registry.DenyMissingVerificationMethods(req.Context, didDoc.VerificationMethod, verificationMethodType, startTime); didWebVMDenial != nil { + return didWebVMDenial + } + // Check required_services: DID document must have specific service types if requiredServices := extractStringSlice(req.Context, "required_services"); len(requiredServices) > 0 { if !hasRequiredServices(didDoc.Service, requiredServices) { @@ -599,3 +607,6 @@ func (r *DIDWebRegistry) Refresh(ctx context.Context) error { func (r *DIDWebRegistry) SetHTTPClient(client *http.Client) { r.httpClient = client } + +// verificationMethodType returns the verification method's type string. +func verificationMethodType(m VerificationMethod) string { return m.Type } diff --git a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/manager.go b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/manager.go index 7c0900ff6..c6a95a562 100644 --- a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/manager.go +++ b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/manager.go @@ -324,6 +324,12 @@ func (m *RegistryManager) applyPolicyToRequest(req *authzen.EvaluationRequest, p return } + // Verifier identifiers the policy enables. Registries read it through + // VerifierIDTypesEnabled; absent means the member is not returned. + if len(policyCtx.Policy.Constraints.ReturnVerifierIDs) > 0 { + req.Context[authzen.VerifierIDsPolicyContextKey] = policyCtx.Policy.Constraints.ReturnVerifierIDs + } + // Apply OIDF constraints if policyCtx.Policy.OIDFed != nil { oidfed := policyCtx.Policy.OIDFed @@ -473,6 +479,11 @@ var clientSuppliableContextKeys = map[string]bool{ // Informational / audit "purpose": true, // presentation purpose + // verifier_id_type only ever narrows the verifier_ids the policy enabled + // to one type; it cannot enable a type (return_verifier_ids is a policy + // control, set only by applyPolicyToRequest). + authzen.VerifierIDHintContextKey: true, + // signing_time is the eMRTD document signing time (RFC 3339) at which the // DSC/CSCA validity is evaluated (ICAO 9303 Part 12). It is data about // the document, which only the PEP knows. The emrtd registry parses it diff --git a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/policy.go b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/policy.go index bdeaa6aa0..fbcf707b7 100644 --- a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/policy.go +++ b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/policy.go @@ -4,7 +4,10 @@ package registry import ( "fmt" + "strings" "sync" + + "github.com/sirosfoundation/go-trust/pkg/authzen" ) // maxWarnedUnknownActions bounds the warning-deduplication set. action.name is @@ -58,6 +61,24 @@ type PolicyConstraints struct { // validated. When true, resolution-only requests (no resource.type or no // resource.key) are rejected rather than answered with resolved metadata. RequireKeyBinding bool `json:"require_key_binding,omitempty" yaml:"require_key_binding,omitempty"` + + // ReturnVerifierIDs lists the verifier identifier types to return in + // response.Context.VerifierIDs (see authzen.SupportedVerifierIDTypes). + // Empty (the default) returns none, so existing responses are unchanged. + // Entries are emitted only for an allow decision whose identifier was + // verified; unknown type names are rejected at config load. + ReturnVerifierIDs []string `json:"return_verifier_ids,omitempty" yaml:"return_verifier_ids,omitempty"` +} + +// Validate rejects unknown return_verifier_ids type names. +func (c PolicyConstraints) Validate() error { + for _, t := range c.ReturnVerifierIDs { + if !authzen.IsSupportedVerifierIDType(t) { + return fmt.Errorf("return_verifier_ids: unknown verifier id type %q (supported: %s)", + t, strings.Join(authzen.SupportedVerifierIDTypes(), ", ")) + } + } + return nil } // OIDFedPolicyConstraints contains OpenID Federation-specific constraints. @@ -139,7 +160,11 @@ type DIDPolicyConstraints struct { // If empty, all domains are allowed. AllowedDomains []string `json:"allowed_domains,omitempty" yaml:"allowed_domains,omitempty"` - // RequiredVerificationMethods requires specific verification method types. + // RequiredVerificationMethods requires the DID document to contain every + // listed verification method type (exact, case-sensitive match on the + // top-level verificationMethod[].type values). Enforced by the did:web, + // did:webvh, did:jwks and generic DID registries; a DID that lacks any + // listed type is denied. // E.g., ["Ed25519VerificationKey2020", "JsonWebKey2020"] RequiredVerificationMethods []string `json:"required_verification_methods,omitempty" yaml:"required_verification_methods,omitempty"` @@ -286,18 +311,30 @@ func NewPolicyManager() *PolicyManager { } } -// RegisterPolicy adds a policy to the manager. -func (pm *PolicyManager) RegisterPolicy(policy *Policy) { +// RegisterPolicy adds a policy to the manager. A policy whose constraints fail +// validation (an unknown return_verifier_ids type) is not registered and the +// error is returned, so that a mis-typed policy is rejected at installation +// rather than silently returning nothing. +func (pm *PolicyManager) RegisterPolicy(policy *Policy) error { + if err := policy.Constraints.Validate(); err != nil { + return fmt.Errorf("policy %q: %w", policy.Name, err) + } pm.policies[policy.Name] = policy if len(policy.Registries) > 0 { pm.registryFilter[policy.Name] = policy.Registries } + return nil } -// SetDefaultPolicy sets the policy used when action.name is not specified. -func (pm *PolicyManager) SetDefaultPolicy(policy *Policy) { +// SetDefaultPolicy sets the policy used when action.name is not specified. It +// returns the validation error of RegisterPolicy, in which case the default is +// left unchanged. +func (pm *PolicyManager) SetDefaultPolicy(policy *Policy) error { + if err := pm.RegisterPolicy(policy); err != nil { + return err + } pm.defaultPolicy = policy - pm.RegisterPolicy(policy) + return nil } // GetPolicy returns the policy for the given action name. diff --git a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/rpcert/semanticid.go b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/rpcert/semanticid.go new file mode 100644 index 000000000..88cd73378 --- /dev/null +++ b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/rpcert/semanticid.go @@ -0,0 +1,155 @@ +package rpcert + +import ( + "crypto/x509" + "regexp" +) + +// SubjectKind classifies a WRPAC subject as a natural or legal person. +type SubjectKind int + +const ( + // SubjectKindUnknown means the certificate carries no (or contradictory) + // WRPAC policy OIDs, so its kind cannot be told from the policy. + SubjectKindUnknown SubjectKind = iota + // SubjectKindContradictory means the certificate carries both natural- and + // legal-person WRPAC policy OIDs. It is not "unclassified": consumers that + // accept unclassified certificates must still refuse this one. + SubjectKindContradictory + // SubjectKindNaturalPerson is a certificate under NCP-n-eudiwrp or QCP-n-eudiwrp. + SubjectKindNaturalPerson + // SubjectKindLegalPerson is a certificate under NCP-l-eudiwrp or QCP-l-eudiwrp. + SubjectKindLegalPerson +) + +// SubjectKindFromPolicies classifies cert by its WRPAC certificate policy OIDs +// (ETSI TS 119 411-8: the -n and -l policies are what distinguish natural from +// legal person certificates). A certificate carrying neither kind is +// SubjectKindUnknown; one carrying both is SubjectKindContradictory. +func SubjectKindFromPolicies(cert *x509.Certificate) SubjectKind { + if cert == nil { + return SubjectKindUnknown + } + var natural, legal bool + for _, oid := range CertPolicyOIDStrings(cert) { + switch oid { + case OIDNCPNaturalPerson, OIDQCPNaturalPerson: + natural = true + case OIDNCPLegalPerson, OIDQCPLegalPerson: + legal = true + } + } + switch { + case natural && legal: + return SubjectKindContradictory + case natural: + return SubjectKindNaturalPerson + case legal: + return SubjectKindLegalPerson + } + return SubjectKindUnknown +} + +// semanticIDPattern is the EN 319 412-1 clause 5.1.3 semantics identifier +// syntax: a 3-letter identifier type, a 2-letter country code, a hyphen-minus +// and a non-empty value without leading or trailing whitespace. +var semanticIDPattern = regexp.MustCompile(`^[A-Z]{3}[A-Z]{2}-[\x21-\x7E]([\x20-\x7E]*[\x21-\x7E])?$`) + +// naturalPersonSemanticTypes are the identifier types EN 319 412-1 5.1.3 defines +// for natural persons: passport, identity card, personal number, tax and +// taxpayer identification number. Every other type names a legal person. +var naturalPersonSemanticTypes = map[string]bool{ + "PAS": true, "IDC": true, "PNO": true, "TAX": true, "TIN": true, +} + +// IsSemanticIdentifier reports whether s matches the semantic identifier +// syntax (3-letter type, 2-letter country, hyphen, value). +func IsSemanticIdentifier(s string) bool { + return semanticIDPattern.MatchString(s) +} + +// organizationIdentifierAttr reports whether the certificate carries an +// organizationIdentifier attribute (2.5.4.97) at all, and its value when it is a +// non-empty string. present is true for an attribute that is empty or not a +// string, with value "": presence is what tells "absent" from "malformed", and +// only the former may fall back to serialNumber. +func organizationIdentifierAttr(cert *x509.Certificate) (value string, present bool) { + for _, atv := range cert.Subject.Names { + if atv.Type.Equal(oidOrganizationIdentifier) { + if v, ok := atv.Value.(string); ok && v != "" { + return v, true + } + present = true + } + } + return "", present +} + +// realOrganizationIdentifier returns only the organizationIdentifier attribute +// (2.5.4.97), without the serialNumber fallback of SubjectOrganizationIdentifier. +func realOrganizationIdentifier(cert *x509.Certificate) string { + v, _ := organizationIdentifierAttr(cert) + return v +} + +// SemanticIdentifier returns the ETSI semantic identifier of the certificate's +// subject, and false when there is none that can be trusted as one. +// +// Where it lives depends on the subject (ETSI TS 119 475 5.1.3 and 5.1.5, which +// refer to EN 319 412-1 5.1.3): +// - legal person: organizationIdentifier (2.5.4.97), per EN 319 412-3 4.2.1. +// The serialNumber fallback exists for older certificates and fixtures that +// put it there. +// - natural person: Subject serialNumber (2.5.4.5), never +// organizationIdentifier, which would name an affiliated organization. +// +// The value must match the semantic identifier syntax, and its type must fit +// the subject: a natural-person type (PNO, IDC, PAS, TAX, TIN) is refused for a +// legal-person certificate and any other type for a natural-person one. The +// subject kind comes from the WRPAC policy OIDs alone; a certificate with +// neither kind has no semantic identifier, because an organizationIdentifier +// there could be the affiliation of a natural person rather than the verifier. +// A serialNumber that is merely a certificate +// serial (or anything else non-semantic) is therefore never returned. An +// organizationIdentifier that is present but not valid is not papered over by +// falling back to serialNumber. A certificate carrying both natural- and +// legal-person policy OIDs has no semantic identifier. +func SemanticIdentifier(cert *x509.Certificate) (string, bool) { + if cert == nil { + return "", false + } + kind := SubjectKindFromPolicies(cert) + if kind == SubjectKindContradictory { + // Both a natural- and a legal-person policy: which identifier is the + // subject's cannot be told, so none is returned (fail closed). + return "", false + } + + // Which attribute names the subject depends on whether it is a natural or a + // legal person, and only the WRPAC policy OIDs say so. Without one the + // organizationIdentifier cannot be told from an affiliation of a natural + // person, so no identifier is returned (fail closed). + var candidate string + switch kind { + case SubjectKindNaturalPerson: + candidate = cert.Subject.SerialNumber + case SubjectKindLegalPerson: + var present bool + candidate, present = organizationIdentifierAttr(cert) + if !present { + // Older certificates put it in serialNumber, but only when 2.5.4.97 + // is absent. A malformed one is not papered over. + candidate = cert.Subject.SerialNumber + } + default: + return "", false + } + + if !IsSemanticIdentifier(candidate) { + return "", false + } + if naturalPersonSemanticTypes[candidate[:3]] != (kind == SubjectKindNaturalPerson) { + return "", false + } + return candidate, true +} diff --git a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/rpcert/wrpac.go b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/rpcert/wrpac.go index 224044228..7b0f85700 100644 --- a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/rpcert/wrpac.go +++ b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/rpcert/wrpac.go @@ -4,9 +4,11 @@ // in the EUDI Wallet ecosystem. It defines: // // - Four certificate policy OIDs (NCP/QCP × natural/legal person) -// - Required extensions (keyUsage, subjectAltName, certificatePolicies, AIA) +// - Required extensions (subjectAltName, certificatePolicies, AIA) // - Identity extraction from Subject DN and SANs -// - Security constraints (key usage restricted to nonRepudiation) +// - No keyUsage constraint: the access certificate authenticates the relying +// party (RFC 5280 4.2.1.3 digitalSignature), and TS 119 411-8 specifies no +// keyUsage bit, so none is enforced // // The profile is based on the APTITUDE wp2-trust-specifications access-certificate // topic (derived from ETSI TS 119 411-8, ETSI EN 319 412-x, and CIR 2025/848). @@ -189,10 +191,26 @@ func (p *WRPACProfile) ExtractIdentity(credential interface{}) (map[string]inter // Subject.Names, so it has to be read out by OID. Fall back to // serialNumber (2.5.4.5), which earlier certificates and test fixtures // used, so both continue to resolve. + // + // The serialNumber fallback does not apply to a natural-person certificate + // (NCP-n/QCP-n policy). ETSI TS 119 475 5.1.5 puts a natural person's + // semantic identifier (e.g. PNOSE-...) in serialNumber; that identifies the + // person, so relabelling it organization_identifier - and classifying the + // certificate legal_person when it also names an affiliated organisation - + // was wrong. + naturalPerson := SubjectKindFromPolicies(cert) == SubjectKindNaturalPerson orgID := SubjectOrganizationIdentifier(cert) + if naturalPerson { + orgID = realOrganizationIdentifier(cert) + } if orgID != "" { identity["organization_identifier"] = orgID - delete(identity, "serial_number") + // Only an organisation identifier that came from serialNumber replaces + // it. A natural person's serialNumber is their own identifier and stays, + // next to the affiliated organisation's real identifier. + if !naturalPerson { + delete(identity, "serial_number") + } } // Determine subject type (natural vs legal person). Keyed off the same @@ -200,11 +218,7 @@ func (p *WRPACProfile) ExtractIdentity(credential interface{}) (map[string]inter // directly classified a conformant legal-person certificate, which // carries the value in 2.5.4.97, as a natural person. Reusing the one // value keeps the two decisions from ever disagreeing. - if len(cert.Subject.Organization) > 0 && orgID != "" { - identity["subject_type"] = "legal_person" - } else { - identity["subject_type"] = "natural_person" - } + identity["subject_type"] = wrpacSubjectType(cert, orgID, naturalPerson) // Certificate policy classification policyOIDStrs := CertPolicyOIDStrings(cert) @@ -274,20 +288,18 @@ func extractSubjectAttribute(cert *x509.Certificate, oid asn1.ObjectIdentifier) // ValidateCredential performs WRPAC-specific validation on an X.509 certificate. // Checks required by the profile beyond basic chain verification: -// - keyUsage must include nonRepudiation (Type A, B, or F per ETSI EN 319 412) // - subjectAltName must be present with at least one contact method // - certificatePolicies must contain at least one WRPAC policy OID +// +// keyUsage is deliberately not checked: ETSI TS 119 411-8 specifies none, and +// an access certificate authenticates the relying party (digitalSignature), +// it does not commit to content (contentCommitment/nonRepudiation). func (p *WRPACProfile) ValidateCredential(credential interface{}) error { cert, ok := credential.(*x509.Certificate) if !ok { return fmt.Errorf("wrpac: expected *x509.Certificate, got %T", credential) } - // Check keyUsage — WRPAC requires nonRepudiation (contentCommitment) - if cert.KeyUsage&x509.KeyUsageContentCommitment == 0 { - return fmt.Errorf("wrpac: certificate keyUsage does not include nonRepudiation (contentCommitment)") - } - // Check subjectAltName — must contain at least one contact method if len(cert.URIs) == 0 && len(cert.EmailAddresses) == 0 { return fmt.Errorf("wrpac: subjectAltName missing required contact information (URI or email)") @@ -336,3 +348,13 @@ func SubjectOrganizationIdentifier(cert *x509.Certificate) string { } return cert.Subject.SerialNumber } + +// wrpacSubjectType classifies the subject as "legal_person" or "natural_person". +// A certificate whose policy OIDs say natural person is one; otherwise it is a +// legal person when it names an organisation and has an organisation identifier. +func wrpacSubjectType(cert *x509.Certificate, orgID string, naturalPerson bool) string { + if !naturalPerson && len(cert.Subject.Organization) > 0 && orgID != "" { + return "legal_person" + } + return "natural_person" +} diff --git a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/strategies.go b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/strategies.go index 009ba2eb0..a68c7002c 100644 --- a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/strategies.go +++ b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/strategies.go @@ -348,6 +348,7 @@ func (m *RegistryManager) evaluateAll(ctx context.Context, req *authzen.Evaluati var allResults []map[string]interface{} decision := false registriesMatched := []string{} + var positive []*authzen.EvaluationResponse for r := range results { resultInfo := map[string]interface{}{ @@ -362,6 +363,7 @@ func (m *RegistryManager) evaluateAll(ctx context.Context, req *authzen.Evaluati if r.response.Decision { decision = true registriesMatched = append(registriesMatched, r.registry) + positive = append(positive, r.response) } if r.response.Context != nil && r.response.Context.Reason != nil { resultInfo["reason"] = r.response.Context.Reason @@ -381,10 +383,12 @@ func (m *RegistryManager) evaluateAll(ctx context.Context, req *authzen.Evaluati } else { promoteSingleAllowAdmin(reason, registriesMatched) } - return &authzen.EvaluationResponse{ + resp := &authzen.EvaluationResponse{ Decision: decision, Context: &authzen.EvaluationResponseContext{Reason: reason}, - }, nil + } + mergeVerifierIDs(resp, positive) + return resp, nil } // evaluateBestMatch queries all registries and returns the one with highest confidence. @@ -764,6 +768,7 @@ func (m *RegistryManager) evaluateAllFiltered(ctx context.Context, req *authzen. var allResults []map[string]interface{} decision := false registriesMatched := []string{} + var positive []*authzen.EvaluationResponse for r := range results { resultInfo := map[string]interface{}{ @@ -778,6 +783,7 @@ func (m *RegistryManager) evaluateAllFiltered(ctx context.Context, req *authzen. if r.response.Decision { decision = true registriesMatched = append(registriesMatched, r.registry) + positive = append(positive, r.response) } if r.response.Context != nil && r.response.Context.Reason != nil { resultInfo["reason"] = r.response.Context.Reason @@ -801,10 +807,12 @@ func (m *RegistryManager) evaluateAllFiltered(ctx context.Context, req *authzen. reason["policy"] = policyCtx.Policy.Name } - return &authzen.EvaluationResponse{ + resp := &authzen.EvaluationResponse{ Decision: decision, Context: &authzen.EvaluationResponseContext{ Reason: reason, }, - }, nil + } + mergeVerifierIDs(resp, positive) + return resp, nil } diff --git a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/test_helpers.go b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/test_helpers.go index 94cc5b492..494e02a91 100644 --- a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/test_helpers.go +++ b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/test_helpers.go @@ -2,6 +2,7 @@ package registry import ( "context" + "fmt" "github.com/sirosfoundation/go-trust/pkg/authzen" ) @@ -98,3 +99,34 @@ func createTestRequest() *authzen.EvaluationRequest { }, } } + +// CheckRequiredVerificationMethodsEnforcement is a shared conformance check for +// DID registries. newMethod builds a verification method of the registry's own +// type with the given `type` string; check must evaluate the registry's policy +// constraints for a DID document holding exactly those methods, with ctx as the +// request context, and return the denial (nil when allowed). It returns an +// error describing the first case the registry gets wrong. +func CheckRequiredVerificationMethodsEnforcement[M any](newMethod func(typ string) M, check func(ctx map[string]interface{}, methods []M) *authzen.EvaluationResponse) error { + methods := []M{newMethod("JsonWebKey2020"), newMethod("Multikey")} + cases := []struct { + name string + required []string + deny bool + }{ + {"all present", []string{"JsonWebKey2020", "Multikey"}, false}, + {"missing type", []string{"Ed25519VerificationKey2020"}, true}, + {"partially present", []string{"JsonWebKey2020", "Ed25519VerificationKey2020"}, true}, + {"unset", nil, false}, + } + for _, c := range cases { + ctx := map[string]interface{}{} + if c.required != nil { + ctx["required_verification_methods"] = c.required + } + resp := check(ctx, methods) + if denied := resp != nil && !resp.Decision; denied != c.deny { + return fmt.Errorf("%s: deny=%v, want %v", c.name, denied, c.deny) + } + } + return nil +} diff --git a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/verifierid.go b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/verifierid.go new file mode 100644 index 000000000..452c5ddb7 --- /dev/null +++ b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/verifierid.go @@ -0,0 +1,225 @@ +package registry + +import ( + "crypto/x509" + "sort" + "strings" + + "github.com/sirosfoundation/go-trust/pkg/authzen" +) + +// VerifierIDTypesEnabled returns the verifier identifier types the policy +// enabled for this request (context key return_verifier_ids, written only by +// applyPolicyToRequest), narrowed to hint when the client sent the optional +// verifier_id_type context member. A nil result means the feature is off. +// +// A hint naming a type the policy did not enable yields an empty, non-nil +// result: the hint only ever narrows, it can never enable a type. +func VerifierIDTypesEnabled(req *authzen.EvaluationRequest) []string { + if req == nil || req.Context == nil { + return nil + } + enabled := extractStringSliceFromContext(req.Context, authzen.VerifierIDsPolicyContextKey) + if len(enabled) == 0 { + return nil + } + hint, hasHint := req.Context[authzen.VerifierIDHintContextKey].(string) + if !hasHint || hint == "" { + return enabled + } + narrowed := []string{} + for _, t := range enabled { + if t == hint { + narrowed = append(narrowed, t) + } + } + return narrowed +} + +// verifierIDEnabled reports whether type t may be emitted for req. +func verifierIDEnabled(req *authzen.EvaluationRequest, t string) bool { + for _, e := range VerifierIDTypesEnabled(req) { + if e == t { + return true + } + } + return false +} + +// AddVerifierID appends one verified identifier to resp.Context.VerifierIDs. +// It is the single emission point for registries that derive an identifier +// themselves (DID, OpenID Federation), and fails closed: nothing is added +// unless the decision is true, the policy enabled the type, the hint (if any) +// matches, and id is non-empty. Duplicate (type, id) pairs are not added twice. +func AddVerifierID(resp *authzen.EvaluationResponse, req *authzen.EvaluationRequest, idType, id, basis string) { + if resp == nil || !resp.Decision || id == "" || !verifierIDEnabled(req, idType) { + return + } + if resp.Context == nil { + resp.Context = &authzen.EvaluationResponseContext{} + } + for _, v := range resp.Context.VerifierIDs { + if v.Type == idType && v.ID == id { + return + } + } + resp.Context.VerifierIDs = append(resp.Context.VerifierIDs, authzen.VerifierID{Type: idType, ID: id, Basis: basis}) +} + +// CanonicalDNSName returns the canonical verifier form of a DNS name for the +// x509_san_dns identifier: the ASCII (A-label) spelling, ASCII lower case, one +// trailing dot removed. ok is false when name is not an identifier, in which +// case no entry is emitted (fail closed). +// +// The value is hashed into a pseudonym, so two spellings of one host must give +// one string and nothing may be rewritten that could be rewritten differently +// elsewhere. In particular U-labels are NOT converted to A-labels: IDNA2003, +// IDNA2008 and UTS #46 disagree for some names, and a conversion difference is a +// different pseudonym. A name containing any non-ASCII byte is therefore not an +// identifier, and an A-label ("xn--...") is passed through verbatim apart from +// case. Also refused: empty labels (including a leading dot or more than one +// trailing dot), labels over 63 and names over 253 octets, whitespace and +// control characters, and a wildcard. +func CanonicalDNSName(name string) (string, bool) { + name = strings.TrimSuffix(name, ".") + if name == "" || len(name) > 253 { + return "", false + } + for _, label := range strings.Split(name, ".") { + if label == "" || len(label) > 63 { + return "", false + } + } + b := []byte(name) + for i, c := range b { + switch { + case c < 0x21 || c > 0x7e || c == '*': + return "", false + case c >= 'A' && c <= 'Z': + b[i] = c + ('a' - 'A') + } + } + return string(b), true +} + +// sanExactlyContains reports whether dnsNames holds clientID, ASCII +// case-insensitively like the binding. A client_id bound only through a +// wildcard SAN (*.example.com) is one of many hosts under one certificate, so it +// does not identify a single verifier. +func sanExactlyContains(dnsNames []string, clientID string) bool { + for _, n := range dnsNames { + if equalASCIIFold(n, clientID) { + return true + } + } + return false +} + +// CanonicalDID returns the DID without any fragment, i.e. the DID itself rather +// than a verification method reference. Nothing else is altered: the +// method-specific part can be case-sensitive (did:web path segments). +func CanonicalDID(did string) string { + if i := strings.IndexByte(did, '#'); i >= 0 { + return did[:i] + } + return did +} + +// AddDIDVerifierID emits the "did" verifier identifier for a DID registry's +// successful key-bound decision. docID is the id of the resolved DID document; +// it is emitted only when it equals the DID the request named (fragment +// ignored), so a resolver that returned a different document can never put its +// own identifier in the response. The match is exact. +func AddDIDVerifierID(resp *authzen.EvaluationResponse, req *authzen.EvaluationRequest, docID string) { + if req == nil || CanonicalDID(docID) != CanonicalDID(req.Subject.ID) { + return + } + AddVerifierID(resp, req, authzen.VerifierIDTypeDID, CanonicalDID(docID), authzen.VerifierIDBasisDIDResolution) +} + +// DeriveCertVerifierIDs derives the verifier identifiers of the relying party +// from a leaf certificate that a registry outside the ETSI/LoTE path has +// accepted, for the types the policy enabled. It applies exactly the rules of +// the etsi and lote registries (same canonical forms, same wildcard and +// intermediary omissions, same VerifyLeafBinding check) and is the single +// derivation for the whitelist, system_cert_pool and mdoc_rical registries. +// +// chainValidated says whether the leaf's content is authenticated, i.e. the +// registry validated the chain to a trust anchor. When false (the whitelist's +// pinned-key path, where trust rests on the key and not on the certificate) the +// certificate's own claims are not vouched for by anyone, so the access +// certificate's semantic identifier is not emitted; the SAN identifiers still +// need the client_id binding, and the client_id is the very entry the +// whitelist authorised for that key. +// +// Call it only for a positive decision; AddVerifierIDs enforces that again. +func DeriveCertVerifierIDs(req *authzen.EvaluationRequest, leaf *x509.Certificate, chainValidated bool) []authzen.VerifierID { + if req == nil || leaf == nil { + return nil + } + ids := deriveX5CVerifierIDs(req, leaf, len(extractIntermediaryX5C(req)) > 0) + if chainValidated { + return ids + } + kept := ids[:0:0] + for _, id := range ids { + if id.Type != authzen.VerifierIDTypeSemantic { + kept = append(kept, id) + } + } + return kept +} + +// AddVerifierIDs appends already-derived identifiers to resp.Context.VerifierIDs. +// Like AddVerifierID it fails closed (nothing on a deny) and never adds a +// (type, id) pair twice. Identifiers are re-checked against the policy's enabled +// types, so a caller cannot widen what the policy allows. +func AddVerifierIDs(resp *authzen.EvaluationResponse, req *authzen.EvaluationRequest, ids []authzen.VerifierID) { + for _, v := range ids { + AddVerifierID(resp, req, v.Type, v.ID, v.Basis) + } +} + +// mergeVerifierIDs copies the verifier identifiers of the positive child +// responses into resp (the aggregate of a multi-registry strategy or composite). +// Only positive children contribute: an identifier is only ever as verified as +// the decision it came from. resp itself must already be positive. +func mergeVerifierIDs(resp *authzen.EvaluationResponse, children []*authzen.EvaluationResponse) { + if resp == nil || !resp.Decision { + return + } + for _, c := range children { + if c == nil || !c.Decision || c.Context == nil { + continue + } + for _, v := range c.Context.VerifierIDs { + dup := false + if resp.Context != nil { + for _, e := range resp.Context.VerifierIDs { + if e.Type == v.Type && e.ID == v.ID { + dup = true + break + } + } + } + if dup { + continue + } + if resp.Context == nil { + resp.Context = &authzen.EvaluationResponseContext{} + } + resp.Context.VerifierIDs = append(resp.Context.VerifierIDs, v) + } + } + // Children finish in no particular order; a stable order keeps responses + // reproducible (the order carries no meaning for clients). + if resp.Context != nil { + sort.SliceStable(resp.Context.VerifierIDs, func(i, j int) bool { + a, b := resp.Context.VerifierIDs[i], resp.Context.VerifierIDs[j] + if a.Type != b.Type { + return a.Type < b.Type + } + return a.ID < b.ID + }) + } +} diff --git a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/x5c_enrichment.go b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/x5c_enrichment.go index 662c7e723..32d25a351 100644 --- a/vendor/github.com/sirosfoundation/go-trust/pkg/registry/x5c_enrichment.go +++ b/vendor/github.com/sirosfoundation/go-trust/pkg/registry/x5c_enrichment.go @@ -54,6 +54,12 @@ type X5CEnrichmentResult struct { // organisation-level binding check. WRPACServiceID string + // VerifierIDs are the verifier identifiers derived from the verified leaf + // certificate, for the types the policy enabled (return_verifier_ids). It is + // empty unless Decision is true and ProfileValidationError is empty: nothing + // is derived from a certificate that failed profile validation. + VerifierIDs []authzen.VerifierID + // FailureReason is set when Decision is false, describing why. FailureReason map[string]interface{} } @@ -194,6 +200,13 @@ func EnrichX5CResponseWithProfiles(req *authzen.EvaluationRequest, leaf *x509.Ce } } + // Verifier identifiers: only from a certificate that passed every check + // above, including the matched profile's validation. A profile failure is + // otherwise only a warning, so it has to be tested for explicitly here. + if result.Decision && result.ProfileValidationError == "" { + result.VerifierIDs = deriveX5CVerifierIDs(req, leaf, result.IsIntermediaryRequest) + } + return result } @@ -249,6 +262,12 @@ func ApplyEnrichmentToResponse(resp *authzen.EvaluationResponse, enrichment *X5C } } + // Verifier identifiers, fail closed: never on a deny, never when the profile + // validation failed, never from a failed enrichment. + if resp.Decision && enrichment.Decision && enrichment.ProfileValidationError == "" { + resp.Context.VerifierIDs = append(resp.Context.VerifierIDs, enrichment.VerifierIDs...) + } + // Add profile validation warnings if any if enrichment.ProfileValidationError != "" { resp.Context.Reason["profile_validation_warning"] = enrichment.ProfileValidationError @@ -443,3 +462,86 @@ func isIntermediariesAllowed(req *authzen.EvaluationRequest) bool { b, ok := v.(bool) return ok && b } + +// deriveX5CVerifierIDs derives the verifier identifiers of the relying party +// from its verified leaf certificate, for the types the policy enabled. +// The chain has already been validated by the caller. +// +// - semantic: the ETSI semantic identifier from the leaf (basis x5c-chain), +// validated against the semantic-id syntax; "semantic_id:" + the value. +// - dns / uri: the client_id of an x509_san_dns / x509_san_uri request, but +// only after VerifyLeafBinding confirms it is a SAN of this leaf (basis +// client-id-binding). The client_id is never echoed otherwise. +// +// For an intermediary request the identifier must be the end relying party's. +// The leaf is the end RP's certificate (the intermediary's own chain is +// unvalidated and is never read here), so semantic is established. The +// client_id of a brokered request cannot be shown to name the end RP, so dns +// and uri are omitted. +func deriveX5CVerifierIDs(req *authzen.EvaluationRequest, leaf *x509.Certificate, intermediary bool) []authzen.VerifierID { + enabled := VerifierIDTypesEnabled(req) + if len(enabled) == 0 || leaf == nil { + return nil + } + want := make(map[string]bool, len(enabled)) + for _, t := range enabled { + want[t] = true + } + + var ids []authzen.VerifierID + if want[authzen.VerifierIDTypeSemantic] { + if sem, ok := rpcert.SemanticIdentifier(leaf); ok { + ids = append(ids, authzen.VerifierID{ + Type: authzen.VerifierIDTypeSemantic, + ID: authzen.VerifierIDSemanticPrefix + sem, + Basis: authzen.VerifierIDBasisX5CChain, + }) + } + } + + // dns / uri: not for an intermediary request (see above). + if intermediary { + return ids + } + if id, ok := deriveSANVerifierID(req, leaf, want); ok { + ids = append(ids, id) + } + return ids +} + +// deriveSANVerifierID derives the dns or uri identifier from the client_id of +// an x509_san_dns / x509_san_uri request, only when the type is wanted and +// VerifyLeafBinding confirms the value is a SAN of leaf. +func deriveSANVerifierID(req *authzen.EvaluationRequest, leaf *x509.Certificate, want map[string]bool) (authzen.VerifierID, bool) { + scheme, value, ok := ParseClientIDScheme(OriginalSubjectID(req)) + if !ok || value == "" { + return authzen.VerifierID{}, false + } + var idType, id string + switch scheme { + case ClientIDSchemeX509SANDNS: + // Not an identifier of one RP: a wildcard, or anything that has no + // canonical form (non-ASCII, empty labels, over-long, ...). Checked + // here explicitly rather than left to the SAN binding. + canonical, ok := CanonicalDNSName(value) + if !ok { + return authzen.VerifierID{}, false + } + // Likewise a client_id that binds only through a wildcard SAN names + // one of many hosts, not the certificate holder. + if !sanExactlyContains(leaf.DNSNames, value) { + return authzen.VerifierID{}, false + } + idType, id = authzen.VerifierIDTypeDNS, canonical + case ClientIDSchemeX509SANURI: + // Byte-for-byte: URISANMatches is an exact comparison, so the bound + // value already is the SAN. Not re-serialised through net/url. + idType, id = authzen.VerifierIDTypeURI, value + default: + return authzen.VerifierID{}, false + } + if !want[idType] || VerifyLeafBinding(scheme, value, leaf) != nil { + return authzen.VerifierID{}, false + } + return authzen.VerifierID{Type: idType, ID: id, Basis: authzen.VerifierIDBasisClientIDBinding}, true +} diff --git a/vendor/modules.txt b/vendor/modules.txt index d2ad8dbdb..c60ab145e 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -76,7 +76,7 @@ github.com/bytedance/sonic/internal/utils github.com/bytedance/sonic/option github.com/bytedance/sonic/unquote github.com/bytedance/sonic/utf8 -# github.com/bytedance/sonic/loader v0.5.2 +# github.com/bytedance/sonic/loader v0.5.3 ## explicit; go 1.16 github.com/bytedance/sonic/loader github.com/bytedance/sonic/loader/internal/abi @@ -222,7 +222,7 @@ github.com/docker/go-units # github.com/eapache/go-resiliency v1.7.0 ## explicit; go 1.13 github.com/eapache/go-resiliency/breaker -# github.com/ebitengine/purego v0.11.1 +# github.com/ebitengine/purego v0.11.2 ## explicit; go 1.25.0 github.com/ebitengine/purego github.com/ebitengine/purego/internal/cgo @@ -234,8 +234,8 @@ github.com/felixge/httpsnoop # github.com/fxamacker/cbor/v2 v2.9.6 ## explicit; go 1.20 github.com/fxamacker/cbor/v2 -# github.com/gabriel-vasile/mimetype v1.4.15 -## explicit; go 1.21 +# github.com/gabriel-vasile/mimetype v1.4.16 +## explicit; go 1.24 github.com/gabriel-vasile/mimetype github.com/gabriel-vasile/mimetype/internal/cdf github.com/gabriel-vasile/mimetype/internal/charset @@ -542,9 +542,10 @@ github.com/klauspost/compress/snappy github.com/klauspost/compress/snappy/xerial github.com/klauspost/compress/zstd github.com/klauspost/compress/zstd/internal/xxhash -# github.com/klauspost/cpuid/v2 v2.4.0 +# github.com/klauspost/cpuid/v2 v2.4.1 ## explicit; go 1.24.0 github.com/klauspost/cpuid/v2 +github.com/klauspost/cpuid/v2/topology # github.com/leodido/go-urn v1.5.0 ## explicit; go 1.24.0 github.com/leodido/go-urn @@ -778,7 +779,7 @@ github.com/prometheus/procfs/internal/parsers # github.com/quic-go/qpack v0.6.0 ## explicit; go 1.24 github.com/quic-go/qpack -# github.com/quic-go/quic-go v0.63.0 +# github.com/quic-go/quic-go v0.64.1 ## explicit; go 1.26.0 github.com/quic-go/quic-go github.com/quic-go/quic-go/http3 @@ -840,7 +841,7 @@ github.com/shirou/gopsutil/v4/internal/common github.com/shirou/gopsutil/v4/mem github.com/shirou/gopsutil/v4/net github.com/shirou/gopsutil/v4/process -# github.com/shopspring/decimal v1.5.0 +# github.com/shopspring/decimal v1.6.0 ## explicit; go 1.10 github.com/shopspring/decimal # github.com/sirosfoundation/g119612 v0.7.0 @@ -856,8 +857,8 @@ github.com/sirosfoundation/go-spocp/pkg/compare github.com/sirosfoundation/go-spocp/pkg/persist github.com/sirosfoundation/go-spocp/pkg/sexp github.com/sirosfoundation/go-spocp/pkg/starform -# github.com/sirosfoundation/go-trust v0.24.1 -## explicit; go 1.27 +# github.com/sirosfoundation/go-trust v0.26.0 +## explicit; go 1.27.2 github.com/sirosfoundation/go-trust/pkg/api github.com/sirosfoundation/go-trust/pkg/authzen github.com/sirosfoundation/go-trust/pkg/authzenclient @@ -1244,10 +1245,10 @@ golang.org/x/tools/internal/gopathwalk golang.org/x/tools/internal/imports golang.org/x/tools/internal/modindex golang.org/x/tools/internal/stdlib -# google.golang.org/genproto/googleapis/api v0.0.0-20261012220534-4341edf3f941 +# google.golang.org/genproto/googleapis/api v0.0.0-20261019180522-ce908d29299b ## explicit; go 1.26.0 google.golang.org/genproto/googleapis/api/httpbody -# google.golang.org/genproto/googleapis/rpc v0.0.0-20261012220534-4341edf3f941 +# google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b ## explicit; go 1.26.0 google.golang.org/genproto/googleapis/rpc/status # google.golang.org/grpc v1.84.0 From f9f5b04aea50f635d53ac44e0344aa3a5e3891d3 Mon Sep 17 00:00:00 2001 From: Magnus Svensson Date: Thu, 22 Oct 2026 10:53:09 +0200 Subject: [PATCH 2/3] model: drop keyUsage expectation from WRPAC profile tests The updated go-trust WRPAC profile no longer enforces a keyUsage constraint. ETSI TS 119 411-8 specifies no keyUsage bit for relying party access certificates. Tests still expected a certificate without nonRepudiation (contentCommitment) to be rejected, so they failed after the dependency upgrade. - Remove the "keyUsage without contentCommitment" violation case. - Break the issuer/verifier shared-rule fixture by omitting the policy OID instead of clearing keyUsage. - Update AccessCertificate/IssuerAccessCertificate field docs and regenerate docs/CONFIGURATION.md. --- docs/CONFIGURATION.md | 20 +++++++++---------- .../issuer/apiv1/access_certificate_test.go | 1 - pkg/model/access_certificate.go | 20 +++++++++---------- pkg/model/access_certificate_test.go | 7 +------ pkg/model/issuer_access_certificate_test.go | 4 ++-- 5 files changed, 22 insertions(+), 30 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index d551a9ee7..6f35590ab 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -1550,12 +1550,12 @@ When KeyConfig is unset the issuer falls back to signing metadata with the credential key, logging a warning. That keeps an existing single-key deployment booting across an upgrade rather than failing on start. -| Field | Type | Description | Example | Default | Required | -| --------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | ------- | -------- | -| `validate` | `bool` | Validate enforces the WRPAC certificate profile at startup: keyUsage must include nonRepudiation (contentCommitment), subjectAltName must carry contact information (URI or email), and certificatePolicies must contain a WRPAC policy OID. Startup fails when the certificate does not conform. | - | - | No | -| `allowed_policy_oids` | `[]string` | AllowedPolicyOIDs optionally narrows which WRPAC certificate policy OIDs are accepted, for a deployment that must assert a specific assurance level. When empty, all four TS 119 411-8 WRPAC policy OIDs are accepted. | `["0.4.0.194118.1.3","0.4.0.194118.1.4"]` | - | No | -| `key_config` | `object` | Signing key and certificate chain for the access certificate. When set, issuer metadata is signed with this key and the chain is advertised in the JWT's x5c header; credentials continue to be signed with Issuer.KeyConfig. | - | - | No | -| `revocation` | `object` | Checking this certificate against the CRL distribution points it names. A certificate naming none cannot be checked, which reads as "could not determine" rather than as "not revoked". | - | - | No | +| Field | Type | Description | Example | Default | Required | +| --------------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | ------- | -------- | +| `validate` | `bool` | Validate enforces the WRPAC certificate profile at startup: subjectAltName must carry contact information (URI or email), and certificatePolicies must contain a WRPAC policy OID. Startup fails when the certificate does not conform. | - | - | No | +| `allowed_policy_oids` | `[]string` | AllowedPolicyOIDs optionally narrows which WRPAC certificate policy OIDs are accepted, for a deployment that must assert a specific assurance level. When empty, all four TS 119 411-8 WRPAC policy OIDs are accepted. | `["0.4.0.194118.1.3","0.4.0.194118.1.4"]` | - | No | +| `key_config` | `object` | Signing key and certificate chain for the access certificate. When set, issuer metadata is signed with this key and the chain is advertised in the JWT's x5c header; credentials continue to be signed with Issuer.KeyConfig. | - | - | No | +| `revocation` | `object` | Checking this certificate against the CRL distribution points it names. A certificate naming none cannot be checked, which reads as "could not determine" rather than as "not revoked". | - | - | No | ### `bbs` @@ -1632,10 +1632,10 @@ with - it does not introduce a second certificate. Deployments not participating in an ARF trust framework can leave it disabled and are unaffected. -| Field | Type | Description | Example | Default | Required | -| --------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | ------- | -------- | -| `validate` | `bool` | Validate enforces the WRPAC certificate profile at startup: keyUsage must include nonRepudiation (contentCommitment), subjectAltName must carry contact information (URI or email), and certificatePolicies must contain a WRPAC policy OID. Startup fails when the certificate does not conform. | - | - | No | -| `allowed_policy_oids` | `[]string` | AllowedPolicyOIDs optionally narrows which WRPAC certificate policy OIDs are accepted, for a deployment that must assert a specific assurance level (e.g. only the qualified policies). When empty, all four TS 119 411-8 WRPAC policy OIDs are accepted. | `["0.4.0.194118.1.3","0.4.0.194118.1.4"]` | - | No | +| Field | Type | Description | Example | Default | Required | +| --------------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | ------- | -------- | +| `validate` | `bool` | Validate enforces the WRPAC certificate profile at startup: subjectAltName must carry contact information (URI or email), and certificatePolicies must contain a WRPAC policy OID. Startup fails when the certificate does not conform. | - | - | No | +| `allowed_policy_oids` | `[]string` | AllowedPolicyOIDs optionally narrows which WRPAC certificate policy OIDs are accepted, for a deployment that must assert a specific assurance level (e.g. only the qualified policies). When empty, all four TS 119 411-8 WRPAC policy OIDs are accepted. | `["0.4.0.194118.1.3","0.4.0.194118.1.4"]` | - | No | ### `preferred_vp_formats` diff --git a/internal/issuer/apiv1/access_certificate_test.go b/internal/issuer/apiv1/access_certificate_test.go index 94b07b9f3..5be278f36 100644 --- a/internal/issuer/apiv1/access_certificate_test.go +++ b/internal/issuer/apiv1/access_certificate_test.go @@ -46,7 +46,6 @@ func writeWRPACKeyPair(t *testing.T) (*pki.KeyConfig, string) { }, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(24 * time.Hour), - // nonRepudiation (contentCommitment) is required by the WRPAC profile. KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageContentCommitment, URIs: []*url.URL{contact}, DNSNames: []string{"issuer.example.com"}, diff --git a/pkg/model/access_certificate.go b/pkg/model/access_certificate.go index 734149b28..d85dcc186 100644 --- a/pkg/model/access_certificate.go +++ b/pkg/model/access_certificate.go @@ -18,11 +18,10 @@ import ( // participating in an ARF trust framework can leave it disabled and are // unaffected. type AccessCertificate struct { - // Validate enforces the WRPAC certificate profile at startup: keyUsage - // must include nonRepudiation (contentCommitment), subjectAltName must - // carry contact information (URI or email), and certificatePolicies must - // contain a WRPAC policy OID. Startup fails when the certificate does - // not conform. + // Validate enforces the WRPAC certificate profile at startup: + // subjectAltName must carry contact information (URI or email), and + // certificatePolicies must contain a WRPAC policy OID. Startup fails + // when the certificate does not conform. Validate bool `yaml:"validate,omitempty"` // AllowedPolicyOIDs optionally narrows which WRPAC certificate policy // OIDs are accepted, for a deployment that must assert a specific @@ -79,7 +78,7 @@ func (a *AccessCertificate) ValidateCertificate(leaf *x509.Certificate, now time leaf.NotAfter.UTC().Format(time.RFC3339), now.UTC().Format(time.RFC3339)) } - // WRPAC profile conformance: keyUsage, SAN contact info, policy OID. + // WRPAC profile conformance: SAN contact info, policy OID. if err := rpcert.NewWRPACProfile().ValidateCredential(leaf); err != nil { return fmt.Errorf("access certificate does not conform to the WRPAC profile: %w", err) } @@ -173,11 +172,10 @@ func (v *Verifier) CheckPublicURLMatchesCertificate(leaf *x509.Certificate) erro // credential key, logging a warning. That keeps an existing single-key // deployment booting across an upgrade rather than failing on start. type IssuerAccessCertificate struct { - // Validate enforces the WRPAC certificate profile at startup: keyUsage - // must include nonRepudiation (contentCommitment), subjectAltName must - // carry contact information (URI or email), and certificatePolicies must - // contain a WRPAC policy OID. Startup fails when the certificate does - // not conform. + // Validate enforces the WRPAC certificate profile at startup: + // subjectAltName must carry contact information (URI or email), and + // certificatePolicies must contain a WRPAC policy OID. Startup fails + // when the certificate does not conform. Validate bool `yaml:"validate,omitempty"` // AllowedPolicyOIDs optionally narrows which WRPAC certificate policy // OIDs are accepted, for a deployment that must assert a specific diff --git a/pkg/model/access_certificate_test.go b/pkg/model/access_certificate_test.go index 6518b82a3..aa6d5b5d2 100644 --- a/pkg/model/access_certificate_test.go +++ b/pkg/model/access_certificate_test.go @@ -91,7 +91,7 @@ func verifierWithAccessCert(validate bool, allowed ...string) *Verifier { // certificate that would not pass them. func TestValidateAccessCertificate_DisabledByDefault(t *testing.T) { nonConformant := newWRPACTestCert(t, wrpacCertOptions{ - keyUsage: x509.KeyUsageDigitalSignature, // no contentCommitment + keyUsage: x509.KeyUsageDigitalSignature, // no SAN contact info or policy OID notBefore: time.Now().Add(-time.Hour), notAfter: time.Now().Add(time.Hour), }) @@ -130,11 +130,6 @@ func TestValidateAccessCertificate_ProfileViolations(t *testing.T) { mutate func(*wrpacCertOptions) wantErr string }{ - { - name: "keyUsage without contentCommitment", - mutate: func(o *wrpacCertOptions) { o.keyUsage = x509.KeyUsageDigitalSignature }, - wantErr: "nonRepudiation", - }, { name: "subjectAltName without contact information", mutate: func(o *wrpacCertOptions) { o.uris = nil; o.emails = nil }, diff --git a/pkg/model/issuer_access_certificate_test.go b/pkg/model/issuer_access_certificate_test.go index 3513f7005..3c74815d3 100644 --- a/pkg/model/issuer_access_certificate_test.go +++ b/pkg/model/issuer_access_certificate_test.go @@ -25,7 +25,7 @@ func issuerWithAccessCert(validate bool, key *pki.KeyConfig, allowed ...string) // holding a certificate that would not pass them. func TestIssuerValidateAccessCertificate_DisabledByDefault(t *testing.T) { opts := conformantWRPACOptions(t) - opts.keyUsage = 0 // would fail the profile + opts.policyOID = "" // would fail the profile cert := newWRPACTestCert(t, opts) assert.NoError(t, (&Issuer{}).ValidateAccessCertificate(cert, time.Now()), @@ -48,7 +48,7 @@ func TestIssuerValidateAccessCertificate_Conformant(t *testing.T) { // two copies will drift. func TestIssuerValidateAccessCertificate_SharesTheVerifierRule(t *testing.T) { opts := conformantWRPACOptions(t) - opts.keyUsage = 0 + opts.policyOID = "" broken := newWRPACTestCert(t, opts) issuerErr := issuerWithAccessCert(true, nil).ValidateAccessCertificate(broken, time.Now()) From ce4a9f21900151557ff651b827efeafd78c901f5 Mon Sep 17 00:00:00 2001 From: Magnus Svensson Date: Thu, 22 Oct 2026 14:13:41 +0200 Subject: [PATCH 3/3] deps: bump chromedp to v0.21.0 and cdproto to v0.158.2 Covers dependabot #834 and #835 (and #833 via go-trust v0.26.0). chromedp 0.21 moved to a generic Action[T] API: typed selectors, value-returning Evaluate/AttributeValue, and cdproto commands as cdp.Command values. Migrate the cross-device integration test. --- dockerfiles/gobuild | 2 +- dockerfiles/worker | 2 +- go.mod | 8 +- go.sum | 21 +- .../gen/issuer/apiv1_issuer/v1-issuer.pb.go | 2 +- .../issuer/apiv1_issuer/v1-issuer_grpc.pb.go | 1 - .../registry/apiv1_registry/v1-registry.pb.go | 7 +- .../apiv1_registry/v1-registry_grpc.pb.go | 1 - .../status/apiv1_status/v1-status-model.pb.go | 7 +- .../verifier/integration/cross_device_test.go | 48 +- .../github.com/chromedp/cdproto/CHANGELOG.md | 245 ++ vendor/github.com/chromedp/cdproto/LICENSE | 2 +- vendor/github.com/chromedp/cdproto/README.md | 70 +- .../cdproto/accessibility/accessibility.go | 384 +--- .../chromedp/cdproto/accessibility/events.go | 4 +- .../chromedp/cdproto/accessibility/types.go | 241 +- vendor/github.com/chromedp/cdproto/ads/ads.go | 44 +- .../github.com/chromedp/cdproto/ads/types.go | 16 +- .../chromedp/cdproto/animation/animation.go | 255 +-- .../chromedp/cdproto/animation/events.go | 4 +- .../chromedp/cdproto/animation/types.go | 25 +- .../chromedp/cdproto/audits/audits.go | 142 +- .../chromedp/cdproto/audits/events.go | 4 +- .../chromedp/cdproto/audits/types.go | 1202 +--------- .../chromedp/cdproto/autofill/autofill.go | 92 +- .../chromedp/cdproto/autofill/events.go | 4 +- .../chromedp/cdproto/autofill/types.go | 23 +- .../backgroundservice/backgroundservice.go | 91 +- .../cdproto/backgroundservice/events.go | 4 +- .../cdproto/backgroundservice/types.go | 33 +- .../bluetoothemulation/bluetoothemulation.go | 416 +--- .../cdproto/bluetoothemulation/events.go | 8 +- .../cdproto/bluetoothemulation/types.go | 99 +- .../chromedp/cdproto/browser/browser.go | 586 ++--- .../chromedp/cdproto/browser/events.go | 4 +- .../chromedp/cdproto/browser/types.go | 197 +- .../cdproto/cachestorage/cachestorage.go | 200 +- .../chromedp/cdproto/cachestorage/types.go | 33 +- .../github.com/chromedp/cdproto/cast/cast.go | 123 +- .../chromedp/cdproto/cast/events.go | 4 +- .../github.com/chromedp/cdproto/cast/types.go | 4 +- .../chromedp/cdproto/cdp/jsonv2/doc.go | 34 + .../cdproto/cdp/jsonv2/json_compat.go | 68 + .../chromedp/cdproto/cdp/jsonv2/json_std.go | 67 + .../github.com/chromedp/cdproto/cdp/types.go | 956 +------- vendor/github.com/chromedp/cdproto/cdproto.go | 573 ++--- .../crashreportcontext/crashreportcontext.go | 41 +- .../cdproto/crashreportcontext/types.go | 4 +- vendor/github.com/chromedp/cdproto/css/css.go | 1442 +++--------- .../github.com/chromedp/cdproto/css/events.go | 4 +- .../github.com/chromedp/cdproto/css/types.go | 119 +- .../chromedp/cdproto/debugger/debugger.go | 1162 ++-------- .../chromedp/cdproto/debugger/events.go | 12 +- .../chromedp/cdproto/debugger/types.go | 275 +-- .../cdproto/deviceaccess/deviceaccess.go | 76 +- .../chromedp/cdproto/deviceaccess/events.go | 4 +- .../chromedp/cdproto/deviceaccess/types.go | 4 +- .../deviceorientation/deviceorientation.go | 43 +- .../digitalcredentials/digitalcredentials.go | 51 +- .../cdproto/digitalcredentials/types.go | 29 +- vendor/github.com/chromedp/cdproto/dom/dom.go | 2014 ++++------------- .../github.com/chromedp/cdproto/dom/events.go | 4 +- .../github.com/chromedp/cdproto/dom/types.go | 113 +- .../cdproto/domdebugger/domdebugger.go | 214 +- .../chromedp/cdproto/domdebugger/types.go | 41 +- .../cdproto/domsnapshot/domsnapshot.go | 123 +- .../chromedp/cdproto/domsnapshot/types.go | 6 +- .../chromedp/cdproto/domstorage/domstorage.go | 145 +- .../chromedp/cdproto/domstorage/events.go | 4 +- .../chromedp/cdproto/domstorage/types.go | 4 +- .../chromedp/cdproto/emulation/emulation.go | 1335 ++--------- .../chromedp/cdproto/emulation/events.go | 4 +- .../chromedp/cdproto/emulation/types.go | 302 +-- .../eventbreakpoints/eventbreakpoints.go | 58 +- .../chromedp/cdproto/extensions/extensions.go | 249 +- .../chromedp/cdproto/extensions/types.go | 29 +- .../chromedp/cdproto/fedcm/events.go | 4 +- .../chromedp/cdproto/fedcm/fedcm.go | 153 +- .../chromedp/cdproto/fedcm/types.go | 79 +- .../chromedp/cdproto/fetch/events.go | 4 +- .../chromedp/cdproto/fetch/fetch.go | 415 +--- .../chromedp/cdproto/fetch/types.go | 57 +- .../chromedp/cdproto/filesystem/filesystem.go | 45 +- .../chromedp/cdproto/filesystem/types.go | 12 +- .../chromedp/cdproto/findinpage/findinpage.go | 49 + .../headlessexperimental.go | 101 +- .../cdproto/headlessexperimental/types.go | 29 +- .../chromedp/cdproto/heapprofiler/events.go | 4 +- .../cdproto/heapprofiler/heapprofiler.go | 398 +--- .../chromedp/cdproto/heapprofiler/types.go | 4 +- .../chromedp/cdproto/indexeddb/indexeddb.go | 401 +--- .../chromedp/cdproto/indexeddb/types.go | 55 +- .../chromedp/cdproto/input/events.go | 4 +- .../chromedp/cdproto/input/input.go | 714 +----- .../chromedp/cdproto/input/types.go | 358 +-- .../chromedp/cdproto/inspector/events.go | 6 +- .../chromedp/cdproto/inspector/inspector.go | 55 +- .../chromedp/cdproto/inspector/types.go | 46 - vendor/github.com/chromedp/cdproto/io/io.go | 144 +- .../github.com/chromedp/cdproto/io/types.go | 4 +- .../chromedp/cdproto/layertree/events.go | 4 +- .../chromedp/cdproto/layertree/layertree.go | 333 +-- .../chromedp/cdproto/layertree/types.go | 27 +- .../github.com/chromedp/cdproto/log/events.go | 4 +- vendor/github.com/chromedp/cdproto/log/log.go | 79 +- .../github.com/chromedp/cdproto/log/types.go | 193 +- .../chromedp/cdproto/media/events.go | 4 +- .../chromedp/cdproto/media/media.go | 64 +- .../chromedp/cdproto/media/types.go | 31 +- .../chromedp/cdproto/memory/memory.go | 270 +-- .../chromedp/cdproto/memory/types.go | 25 +- .../chromedp/cdproto/network/events.go | 189 +- .../chromedp/cdproto/network/network.go | 1475 ++++-------- .../chromedp/cdproto/network/types.go | 1389 +----------- .../chromedp/cdproto/overlay/events.go | 4 +- .../chromedp/cdproto/overlay/overlay.go | 732 ++---- .../chromedp/cdproto/overlay/types.go | 118 +- .../chromedp/cdproto/page/events.go | 20 +- .../github.com/chromedp/cdproto/page/page.go | 1902 ++++------------ .../github.com/chromedp/cdproto/page/types.go | 1201 ++-------- .../chromedp/cdproto/performance/events.go | 4 +- .../cdproto/performance/performance.go | 70 +- .../chromedp/cdproto/performance/types.go | 25 +- .../cdproto/performancetimeline/events.go | 4 +- .../performancetimeline.go | 30 +- .../cdproto/performancetimeline/types.go | 20 +- .../chromedp/cdproto/preload/events.go | 5 +- .../chromedp/cdproto/preload/preload.go | 64 +- .../chromedp/cdproto/preload/types.go | 332 +-- .../chromedp/cdproto/profiler/events.go | 4 +- .../chromedp/cdproto/profiler/profiler.go | 249 +- .../chromedp/cdproto/profiler/types.go | 4 +- vendor/github.com/chromedp/cdproto/pwa/pwa.go | 266 +-- .../github.com/chromedp/cdproto/pwa/types.go | 25 +- .../chromedp/cdproto/runtime/events.go | 25 +- .../chromedp/cdproto/runtime/runtime.go | 1068 ++------- .../chromedp/cdproto/runtime/types.go | 529 ++--- .../chromedp/cdproto/security/events.go | 4 +- .../chromedp/cdproto/security/security.go | 54 +- .../chromedp/cdproto/security/types.go | 117 +- .../chromedp/cdproto/serviceworker/events.go | 4 +- .../cdproto/serviceworker/serviceworker.go | 229 +- .../chromedp/cdproto/serviceworker/types.go | 113 +- .../cdproto/smartcardemulation/events.go | 10 +- .../smartcardemulation/smartcardemulation.go | 428 ++-- .../cdproto/smartcardemulation/types.go | 167 +- .../chromedp/cdproto/storage/events.go | 44 +- .../chromedp/cdproto/storage/storage.go | 893 ++------ .../chromedp/cdproto/storage/types.go | 273 +-- .../chromedp/cdproto/systeminfo/systeminfo.go | 110 +- .../chromedp/cdproto/systeminfo/types.go | 49 +- .../chromedp/cdproto/target/events.go | 4 +- .../chromedp/cdproto/target/target.go | 786 ++----- .../chromedp/cdproto/target/types.go | 31 +- .../chromedp/cdproto/tethering/events.go | 4 +- .../chromedp/cdproto/tethering/tethering.go | 46 +- .../chromedp/cdproto/tracing/events.go | 8 +- .../chromedp/cdproto/tracing/tracing.go | 256 +-- .../chromedp/cdproto/tracing/types.go | 169 +- vendor/github.com/chromedp/cdproto/version.go | 23 + .../chromedp/cdproto/webaudio/events.go | 4 +- .../chromedp/cdproto/webaudio/types.go | 100 +- .../chromedp/cdproto/webaudio/webaudio.go | 135 +- .../chromedp/cdproto/webauthn/events.go | 6 +- .../chromedp/cdproto/webauthn/types.go | 105 +- .../chromedp/cdproto/webauthn/webauthn.go | 401 +--- .../chromedp/cdproto/webmcp/events.go | 8 +- .../chromedp/cdproto/webmcp/types.go | 31 +- .../chromedp/cdproto/webmcp/webmcp.go | 114 +- .../chromedp/chromedp/.gitattributes | 6 + .../github.com/chromedp/chromedp/.gitignore | 9 +- vendor/github.com/chromedp/chromedp/AGENTS.md | 287 +++ vendor/github.com/chromedp/chromedp/CLAUDE.md | 1 + .../chromedp/chromedp/CONTRIBUTING.md | 48 + vendor/github.com/chromedp/chromedp/LICENSE | 2 +- vendor/github.com/chromedp/chromedp/README.md | 466 +++- vendor/github.com/chromedp/chromedp/action.go | 231 ++ .../github.com/chromedp/chromedp/allocate.go | 797 +++++-- .../chromedp/chromedp/allocate_darwin.go | 81 + .../chromedp/chromedp/allocate_detach_unix.go | 17 + .../chromedp/allocate_detach_windows.go | 21 + .../chromedp/chromedp/allocate_linux.go | 76 + .../chromedp/chromedp/allocate_other.go | 11 +- .../chromedp/chromedp/allocate_pipe.go | 236 ++ .../github.com/chromedp/chromedp/browser.go | 346 ++- vendor/github.com/chromedp/chromedp/call.go | 123 +- .../github.com/chromedp/chromedp/chromedp.go | 887 +++++--- vendor/github.com/chromedp/chromedp/conn.go | 152 -- .../github.com/chromedp/chromedp/console.go | 447 ++++ .../chromedp/chromedp/device/device.go | 88 + vendor/github.com/chromedp/chromedp/drag.go | 299 +++ .../github.com/chromedp/chromedp/emulate.go | 93 +- vendor/github.com/chromedp/chromedp/errors.go | 65 +- vendor/github.com/chromedp/chromedp/eval.go | 185 +- vendor/github.com/chromedp/chromedp/expose.go | 254 +++ vendor/github.com/chromedp/chromedp/frame.go | 63 + vendor/github.com/chromedp/chromedp/input.go | 241 +- vendor/github.com/chromedp/chromedp/js.go | 28 +- .../chromedp/chromedp/js/exposeFunc.js | 46 + .../github.com/chromedp/chromedp/js/text.js | 7 +- .../github.com/chromedp/chromedp/kb/event.go | 53 + vendor/github.com/chromedp/chromedp/kb/kb.go | 24 +- .../github.com/chromedp/chromedp/keepopen.go | 274 +++ vendor/github.com/chromedp/chromedp/nav.go | 123 +- vendor/github.com/chromedp/chromedp/node.go | 363 +++ vendor/github.com/chromedp/chromedp/pdf.go | 203 ++ vendor/github.com/chromedp/chromedp/pipe.go | 136 ++ .../github.com/chromedp/chromedp/pipe_unix.go | 17 + .../chromedp/chromedp/pipe_windows.go | 42 + vendor/github.com/chromedp/chromedp/poll.go | 106 +- vendor/github.com/chromedp/chromedp/query.go | 1321 ++++++----- .../chromedp/chromedp/screenshot.go | 168 +- .../github.com/chromedp/chromedp/session.go | 199 ++ .../chromedp/chromedp/skills-lock.json | 17 + vendor/github.com/chromedp/chromedp/target.go | 142 +- vendor/github.com/chromedp/chromedp/util.go | 231 +- .../github.com/chromedp/sysutil/.travis.yml | 6 - vendor/github.com/chromedp/sysutil/LICENSE | 21 - vendor/github.com/chromedp/sysutil/README.md | 6 - vendor/github.com/chromedp/sysutil/sysutil.go | 17 - .../chromedp/sysutil/sysutil_bsd.go | 26 - .../chromedp/sysutil/sysutil_linux.go | 34 - .../chromedp/sysutil/sysutil_other.go | 9 - .../chromedp/sysutil/sysutil_windows.go | 22 - vendor/github.com/chromedp/sysutil/timeval.go | 9 - .../github.com/chromedp/sysutil/timeval32.go | 8 - vendor/github.com/gobwas/httphead/LICENSE | 21 - vendor/github.com/gobwas/httphead/README.md | 63 - vendor/github.com/gobwas/httphead/cookie.go | 200 -- vendor/github.com/gobwas/httphead/head.go | 275 --- vendor/github.com/gobwas/httphead/httphead.go | 331 --- vendor/github.com/gobwas/httphead/lexer.go | 360 --- vendor/github.com/gobwas/httphead/octet.go | 83 - vendor/github.com/gobwas/httphead/option.go | 193 -- vendor/github.com/gobwas/httphead/writer.go | 101 - vendor/github.com/gobwas/pool/LICENSE | 21 - vendor/github.com/gobwas/pool/README.md | 107 - vendor/github.com/gobwas/pool/generic.go | 87 - .../gobwas/pool/internal/pmath/pmath.go | 65 - vendor/github.com/gobwas/pool/option.go | 43 - .../github.com/gobwas/pool/pbufio/pbufio.go | 106 - .../gobwas/pool/pbufio/pbufio_go110.go | 13 - .../gobwas/pool/pbufio/pbufio_go19.go | 27 - .../github.com/gobwas/pool/pbytes/pbytes.go | 24 - vendor/github.com/gobwas/pool/pbytes/pool.go | 59 - .../gobwas/pool/pbytes/pool_sanitize.go | 121 - vendor/github.com/gobwas/pool/pool.go | 25 - vendor/github.com/gobwas/ws/.gitignore | 5 - vendor/github.com/gobwas/ws/LICENSE | 21 - vendor/github.com/gobwas/ws/Makefile | 54 - vendor/github.com/gobwas/ws/README.md | 541 ----- vendor/github.com/gobwas/ws/check.go | 145 -- vendor/github.com/gobwas/ws/cipher.go | 61 - vendor/github.com/gobwas/ws/dialer.go | 573 ----- .../github.com/gobwas/ws/dialer_tls_go17.go | 35 - .../github.com/gobwas/ws/dialer_tls_go18.go | 10 - vendor/github.com/gobwas/ws/doc.go | 81 - vendor/github.com/gobwas/ws/errors.go | 59 - vendor/github.com/gobwas/ws/frame.go | 420 ---- vendor/github.com/gobwas/ws/hijack_go119.go | 18 - vendor/github.com/gobwas/ws/hijack_go120.go | 19 - vendor/github.com/gobwas/ws/http.go | 507 ----- vendor/github.com/gobwas/ws/nonce.go | 78 - vendor/github.com/gobwas/ws/read.go | 147 -- vendor/github.com/gobwas/ws/server.go | 658 ------ vendor/github.com/gobwas/ws/util.go | 199 -- vendor/github.com/gobwas/ws/util_purego.go | 12 - vendor/github.com/gobwas/ws/util_unsafe.go | 22 - vendor/github.com/gobwas/ws/write.go | 104 - vendor/github.com/gobwas/ws/wsutil/cipher.go | 72 - vendor/github.com/gobwas/ws/wsutil/dialer.go | 147 -- .../github.com/gobwas/ws/wsutil/extenstion.go | 31 - vendor/github.com/gobwas/ws/wsutil/handler.go | 219 -- vendor/github.com/gobwas/ws/wsutil/helper.go | 279 --- vendor/github.com/gobwas/ws/wsutil/reader.go | 373 --- .../github.com/gobwas/ws/wsutil/upgrader.go | 68 - vendor/github.com/gobwas/ws/wsutil/utf8.go | 140 -- vendor/github.com/gobwas/ws/wsutil/writer.go | 599 ----- vendor/github.com/gobwas/ws/wsutil/wsutil.go | 57 - vendor/modules.txt | 26 +- 280 files changed, 13811 insertions(+), 36406 deletions(-) create mode 100644 vendor/github.com/chromedp/cdproto/CHANGELOG.md create mode 100644 vendor/github.com/chromedp/cdproto/cdp/jsonv2/doc.go create mode 100644 vendor/github.com/chromedp/cdproto/cdp/jsonv2/json_compat.go create mode 100644 vendor/github.com/chromedp/cdproto/cdp/jsonv2/json_std.go create mode 100644 vendor/github.com/chromedp/cdproto/findinpage/findinpage.go delete mode 100644 vendor/github.com/chromedp/cdproto/inspector/types.go create mode 100644 vendor/github.com/chromedp/cdproto/version.go create mode 100644 vendor/github.com/chromedp/chromedp/.gitattributes create mode 100644 vendor/github.com/chromedp/chromedp/AGENTS.md create mode 100644 vendor/github.com/chromedp/chromedp/CLAUDE.md create mode 100644 vendor/github.com/chromedp/chromedp/CONTRIBUTING.md create mode 100644 vendor/github.com/chromedp/chromedp/action.go create mode 100644 vendor/github.com/chromedp/chromedp/allocate_darwin.go create mode 100644 vendor/github.com/chromedp/chromedp/allocate_detach_unix.go create mode 100644 vendor/github.com/chromedp/chromedp/allocate_detach_windows.go create mode 100644 vendor/github.com/chromedp/chromedp/allocate_pipe.go delete mode 100644 vendor/github.com/chromedp/chromedp/conn.go create mode 100644 vendor/github.com/chromedp/chromedp/console.go create mode 100644 vendor/github.com/chromedp/chromedp/drag.go create mode 100644 vendor/github.com/chromedp/chromedp/expose.go create mode 100644 vendor/github.com/chromedp/chromedp/frame.go create mode 100644 vendor/github.com/chromedp/chromedp/js/exposeFunc.js create mode 100644 vendor/github.com/chromedp/chromedp/kb/event.go create mode 100644 vendor/github.com/chromedp/chromedp/keepopen.go create mode 100644 vendor/github.com/chromedp/chromedp/node.go create mode 100644 vendor/github.com/chromedp/chromedp/pdf.go create mode 100644 vendor/github.com/chromedp/chromedp/pipe.go create mode 100644 vendor/github.com/chromedp/chromedp/pipe_unix.go create mode 100644 vendor/github.com/chromedp/chromedp/pipe_windows.go create mode 100644 vendor/github.com/chromedp/chromedp/session.go create mode 100644 vendor/github.com/chromedp/chromedp/skills-lock.json delete mode 100644 vendor/github.com/chromedp/sysutil/.travis.yml delete mode 100644 vendor/github.com/chromedp/sysutil/LICENSE delete mode 100644 vendor/github.com/chromedp/sysutil/README.md delete mode 100644 vendor/github.com/chromedp/sysutil/sysutil.go delete mode 100644 vendor/github.com/chromedp/sysutil/sysutil_bsd.go delete mode 100644 vendor/github.com/chromedp/sysutil/sysutil_linux.go delete mode 100644 vendor/github.com/chromedp/sysutil/sysutil_other.go delete mode 100644 vendor/github.com/chromedp/sysutil/sysutil_windows.go delete mode 100644 vendor/github.com/chromedp/sysutil/timeval.go delete mode 100644 vendor/github.com/chromedp/sysutil/timeval32.go delete mode 100644 vendor/github.com/gobwas/httphead/LICENSE delete mode 100644 vendor/github.com/gobwas/httphead/README.md delete mode 100644 vendor/github.com/gobwas/httphead/cookie.go delete mode 100644 vendor/github.com/gobwas/httphead/head.go delete mode 100644 vendor/github.com/gobwas/httphead/httphead.go delete mode 100644 vendor/github.com/gobwas/httphead/lexer.go delete mode 100644 vendor/github.com/gobwas/httphead/octet.go delete mode 100644 vendor/github.com/gobwas/httphead/option.go delete mode 100644 vendor/github.com/gobwas/httphead/writer.go delete mode 100644 vendor/github.com/gobwas/pool/LICENSE delete mode 100644 vendor/github.com/gobwas/pool/README.md delete mode 100644 vendor/github.com/gobwas/pool/generic.go delete mode 100644 vendor/github.com/gobwas/pool/internal/pmath/pmath.go delete mode 100644 vendor/github.com/gobwas/pool/option.go delete mode 100644 vendor/github.com/gobwas/pool/pbufio/pbufio.go delete mode 100644 vendor/github.com/gobwas/pool/pbufio/pbufio_go110.go delete mode 100644 vendor/github.com/gobwas/pool/pbufio/pbufio_go19.go delete mode 100644 vendor/github.com/gobwas/pool/pbytes/pbytes.go delete mode 100644 vendor/github.com/gobwas/pool/pbytes/pool.go delete mode 100644 vendor/github.com/gobwas/pool/pbytes/pool_sanitize.go delete mode 100644 vendor/github.com/gobwas/pool/pool.go delete mode 100644 vendor/github.com/gobwas/ws/.gitignore delete mode 100644 vendor/github.com/gobwas/ws/LICENSE delete mode 100644 vendor/github.com/gobwas/ws/Makefile delete mode 100644 vendor/github.com/gobwas/ws/README.md delete mode 100644 vendor/github.com/gobwas/ws/check.go delete mode 100644 vendor/github.com/gobwas/ws/cipher.go delete mode 100644 vendor/github.com/gobwas/ws/dialer.go delete mode 100644 vendor/github.com/gobwas/ws/dialer_tls_go17.go delete mode 100644 vendor/github.com/gobwas/ws/dialer_tls_go18.go delete mode 100644 vendor/github.com/gobwas/ws/doc.go delete mode 100644 vendor/github.com/gobwas/ws/errors.go delete mode 100644 vendor/github.com/gobwas/ws/frame.go delete mode 100644 vendor/github.com/gobwas/ws/hijack_go119.go delete mode 100644 vendor/github.com/gobwas/ws/hijack_go120.go delete mode 100644 vendor/github.com/gobwas/ws/http.go delete mode 100644 vendor/github.com/gobwas/ws/nonce.go delete mode 100644 vendor/github.com/gobwas/ws/read.go delete mode 100644 vendor/github.com/gobwas/ws/server.go delete mode 100644 vendor/github.com/gobwas/ws/util.go delete mode 100644 vendor/github.com/gobwas/ws/util_purego.go delete mode 100644 vendor/github.com/gobwas/ws/util_unsafe.go delete mode 100644 vendor/github.com/gobwas/ws/write.go delete mode 100644 vendor/github.com/gobwas/ws/wsutil/cipher.go delete mode 100644 vendor/github.com/gobwas/ws/wsutil/dialer.go delete mode 100644 vendor/github.com/gobwas/ws/wsutil/extenstion.go delete mode 100644 vendor/github.com/gobwas/ws/wsutil/handler.go delete mode 100644 vendor/github.com/gobwas/ws/wsutil/helper.go delete mode 100644 vendor/github.com/gobwas/ws/wsutil/reader.go delete mode 100644 vendor/github.com/gobwas/ws/wsutil/upgrader.go delete mode 100644 vendor/github.com/gobwas/ws/wsutil/utf8.go delete mode 100644 vendor/github.com/gobwas/ws/wsutil/writer.go delete mode 100644 vendor/github.com/gobwas/ws/wsutil/wsutil.go diff --git a/dockerfiles/gobuild b/dockerfiles/gobuild index 7327dddda..682788a79 100644 --- a/dockerfiles/gobuild +++ b/dockerfiles/gobuild @@ -6,7 +6,7 @@ # already present (see dockerfiles/worker). # Pinned to -bookworm so glibc matches distroless/cc-debian12 at runtime. # Keep this tag aligned with GOBUILD_IMAGE default in dockerfiles/worker. -FROM golang:1.27.1-bookworm +FROM golang:1.27.3-bookworm WORKDIR /go/src/app diff --git a/dockerfiles/worker b/dockerfiles/worker index ef1bab5e8..666a420e8 100644 --- a/dockerfiles/worker +++ b/dockerfiles/worker @@ -6,7 +6,7 @@ # toolchains — the tool-install steps below no-op when they detect the # tools are already present. # Keep the golang tag aligned with dockerfiles/gobuild's FROM. -ARG GOBUILD_IMAGE=golang:1.27.1-bookworm +ARG GOBUILD_IMAGE=golang:1.27.3-bookworm FROM ${GOBUILD_IMAGE} AS gobuild WORKDIR /go/src/app COPY Makefile . diff --git a/go.mod b/go.mod index 24ef4087c..85a8d62f0 100644 --- a/go.mod +++ b/go.mod @@ -8,8 +8,8 @@ require ( github.com/PaesslerAG/jsonpath v0.1.1 github.com/beevik/etree v1.8.1 github.com/biter777/countries v1.7.5 - github.com/chromedp/cdproto v0.0.0-20260719223732-95f6af754cfe - github.com/chromedp/chromedp v0.16.0 + github.com/chromedp/cdproto v0.158.2 + github.com/chromedp/chromedp v0.21.0 github.com/coreos/go-oidc/v3 v3.21.0 github.com/creasty/defaults v1.11.0 github.com/crewjam/saml v0.5.1 @@ -99,7 +99,6 @@ require ( github.com/cenkalti/backoff/v4 v4.3.0 // indirect github.com/cenkalti/backoff/v5 v5.0.3 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/chromedp/sysutil v1.1.0 // indirect github.com/cloudwego/base64x v0.1.7 // indirect github.com/containerd/errdefs v1.0.0 // indirect github.com/containerd/errdefs/pkg v0.3.0 // indirect @@ -130,9 +129,6 @@ require ( github.com/go-openapi/swag/yamlutils v0.29.2 // indirect github.com/go-playground/locales v0.14.2 // indirect github.com/go-playground/universal-translator v0.18.2 // indirect - github.com/gobwas/httphead v0.1.0 // indirect - github.com/gobwas/pool v0.2.1 // indirect - github.com/gobwas/ws v1.4.0 // indirect github.com/goccy/go-json v0.11.2 // indirect github.com/golang-jwt/jwt/v4 v4.5.2 // indirect github.com/google/go-cmp v0.7.0 // indirect diff --git a/go.sum b/go.sum index 5a1e6456f..6b36b8ad5 100644 --- a/go.sum +++ b/go.sum @@ -43,12 +43,10 @@ github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1x github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/chromedp/cdproto v0.0.0-20260719223732-95f6af754cfe h1:PmhRwLZ8qLtldQCBiydwdPFJI8WVQ936ux1cpgHLRb8= -github.com/chromedp/cdproto v0.0.0-20260719223732-95f6af754cfe/go.mod h1:RwFsSODCtFExll+GhHM6R92SARHR3Z3oipaxLHj46C0= -github.com/chromedp/chromedp v0.16.0 h1:rOO4deOm4CbZgBCa8mD9g2rDyIoNs0BkgvNrlbp5ouk= -github.com/chromedp/chromedp v0.16.0/go.mod h1:rbuGKFT1vMcFcFqKfPIO1GpX/N+2s8onm2qMxZLbU5U= -github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM= -github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8= +github.com/chromedp/cdproto v0.158.2 h1:EIrQ/1Ns6+WEmaK23ynKbWm+kMV1IeG5hd8zyOLSMXs= +github.com/chromedp/cdproto v0.158.2/go.mod h1:h68JaIuFr9o3yiayxEYhBdvaxgYO3shDrPSYhNlyfu0= +github.com/chromedp/chromedp v0.21.0 h1:nVHgS2LHyhZJ1l3BWRbG2eFIFYiJMnvkJbELbd8WBoQ= +github.com/chromedp/chromedp v0.21.0/go.mod h1:6z1Y5FdKUxRzxx2qcC5h1xjaBJrSWrZp1mjgITfNZig= github.com/cloudwego/base64x v0.1.7 h1:NppS+Fgzg5ovhn4NkUXaDT3x9jldgH5ToMCqzBSi2zI= github.com/cloudwego/base64x v0.1.7/go.mod h1:Cu1PV9zfrSf7ET2tIbWbbEy7jO7HHJ13q4X2SQ8aWYg= github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= @@ -161,12 +159,6 @@ github.com/go-playground/validator/v10 v10.30.5/go.mod h1:wEqiaov48pXX1kjhc3Da8y github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME= github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= -github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU= -github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM= -github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og= -github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= -github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs= -github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc= github.com/goccy/go-json v0.11.2 h1:jdZv93Tt4ioR8yW1CoNsvSxrcZlCXAUU1aZXN7gpXUA= github.com/goccy/go-json v0.11.2/go.mod h1:3NdmfEkZlB7YI5UFw/qdFKq8XN1aiWR0YyRPWZNQltY= github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= @@ -249,8 +241,6 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80 h1:6Yzfa6GP0rIo/kULo2bwGEkFvCePZ3qHDDTC3/J9Swo= -github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80/go.mod h1:imJHygn/1yfhB7XSJJKlFZKl/J+dCPAknuiaGOshXAs= github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0= github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE= github.com/lestrrat-go/blackmagic v1.0.4 h1:IwQibdnf8l2KoO+qC3uT4OaTWsW7tuRQXy9TRN9QanA= @@ -333,8 +323,6 @@ github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8 github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= -github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw= -github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0= github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY= @@ -536,7 +524,6 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= diff --git a/internal/gen/issuer/apiv1_issuer/v1-issuer.pb.go b/internal/gen/issuer/apiv1_issuer/v1-issuer.pb.go index 4b3d811f6..90fa52295 100644 --- a/internal/gen/issuer/apiv1_issuer/v1-issuer.pb.go +++ b/internal/gen/issuer/apiv1_issuer/v1-issuer.pb.go @@ -1,6 +1,6 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.36.11 +// protoc-gen-go v1.36.12 // protoc v3.21.12 // source: v1-issuer.proto diff --git a/internal/gen/issuer/apiv1_issuer/v1-issuer_grpc.pb.go b/internal/gen/issuer/apiv1_issuer/v1-issuer_grpc.pb.go index b597213e6..78df15c46 100644 --- a/internal/gen/issuer/apiv1_issuer/v1-issuer_grpc.pb.go +++ b/internal/gen/issuer/apiv1_issuer/v1-issuer_grpc.pb.go @@ -8,7 +8,6 @@ package apiv1_issuer import ( context "context" - apiv1_status "github.com/SUNET/vc/internal/gen/status/apiv1_status" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" diff --git a/internal/gen/registry/apiv1_registry/v1-registry.pb.go b/internal/gen/registry/apiv1_registry/v1-registry.pb.go index 214bf09b4..2d72460b5 100644 --- a/internal/gen/registry/apiv1_registry/v1-registry.pb.go +++ b/internal/gen/registry/apiv1_registry/v1-registry.pb.go @@ -7,13 +7,12 @@ package apiv1_registry import ( - reflect "reflect" - sync "sync" - unsafe "unsafe" - apiv1_status "github.com/SUNET/vc/internal/gen/status/apiv1_status" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + unsafe "unsafe" ) const ( diff --git a/internal/gen/registry/apiv1_registry/v1-registry_grpc.pb.go b/internal/gen/registry/apiv1_registry/v1-registry_grpc.pb.go index 4e4c20360..9ee9dae96 100644 --- a/internal/gen/registry/apiv1_registry/v1-registry_grpc.pb.go +++ b/internal/gen/registry/apiv1_registry/v1-registry_grpc.pb.go @@ -8,7 +8,6 @@ package apiv1_registry import ( context "context" - apiv1_status "github.com/SUNET/vc/internal/gen/status/apiv1_status" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" diff --git a/internal/gen/status/apiv1_status/v1-status-model.pb.go b/internal/gen/status/apiv1_status/v1-status-model.pb.go index e2a980d45..84e548b4e 100644 --- a/internal/gen/status/apiv1_status/v1-status-model.pb.go +++ b/internal/gen/status/apiv1_status/v1-status-model.pb.go @@ -7,13 +7,12 @@ package apiv1_status import ( - reflect "reflect" - sync "sync" - unsafe "unsafe" - protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" timestamppb "google.golang.org/protobuf/types/known/timestamppb" + reflect "reflect" + sync "sync" + unsafe "unsafe" ) const ( diff --git a/internal/verifier/integration/cross_device_test.go b/internal/verifier/integration/cross_device_test.go index 363fa6abe..8d3aea57c 100644 --- a/internal/verifier/integration/cross_device_test.go +++ b/internal/verifier/integration/cross_device_test.go @@ -180,13 +180,14 @@ func TestCrossDevice_FullFlow(t *testing.T) { t.Logf("Navigating to: %s", authorizeURL) // Navigate and wait for QR code to render - var sessionID string - err := chromedp.Run(browserCtx, - // Ignore TLS errors at CDP level - network.SetExtraHTTPHeaders(network.Headers{}), + _, err := chromedp.Call(browserCtx, network.SetExtraHTTPHeaders, network.SetExtraHTTPHeadersParams{Headers: network.Headers{}}) + require.NoError(t, err, "browser: set extra HTTP headers") + err = chromedp.Do(browserCtx, chromedp.Navigate(authorizeURL), - chromedp.WaitVisible(`#qr-code`, chromedp.ByID), - chromedp.Evaluate(`(() => { + chromedp.WaitVisible(chromedp.ID("qr-code")), + ) + require.NoError(t, err, "browser: navigate and wait for QR code") + sessionID, err := chromedp.Run(browserCtx, chromedp.Evaluate[string](`(() => { // Extract sessionId from page JavaScript const scripts = document.querySelectorAll('script'); for (const s of scripts) { @@ -200,9 +201,8 @@ func TestCrossDevice_FullFlow(t *testing.T) { if (m) return m[1]; } return ''; - })()`, &sessionID), - ) - require.NoError(t, err, "browser: navigate and extract session ID") + })()`)) + require.NoError(t, err, "browser: extract session ID") require.NotEmpty(t, sessionID, "session ID must be extracted from page") t.Logf("Phase 4 complete: session_id=%s, QR code visible", sessionID) @@ -287,21 +287,23 @@ func TestCrossDevice_QRCodeRenders(t *testing.T) { authorizeURL := fmt.Sprintf("%s/authorize?response_type=code&client_id=%s&redirect_uri=%s&scope=%s&state=%s&code_challenge=%s&code_challenge_method=S256", verifierPublicURL, vpClient.ClientID, url.QueryEscape(oauthRedirect), url.QueryEscape("openid pid"), uuid.New().String(), codeChallenge) - var qrSrc, sessionID string - err := chromedp.Run(browserCtx, + err := chromedp.Do(browserCtx, chromedp.Navigate(authorizeURL), - chromedp.WaitVisible(`#qr-code`, chromedp.ByID), - chromedp.AttributeValue(`#qr-code`, "src", &qrSrc, nil, chromedp.ByID), - chromedp.Evaluate(`(() => { + chromedp.WaitVisible(chromedp.ID("qr-code")), + ) + require.NoError(t, err, "browser navigation failed") + qrAttr, err := chromedp.Run(browserCtx, chromedp.AttributeValue(chromedp.ID("qr-code"), "src")) + require.NoError(t, err, "browser: read QR src") + qrSrc := qrAttr.Value + sessionID, err := chromedp.Run(browserCtx, chromedp.Evaluate[string](`(() => { const scripts = document.querySelectorAll('script'); for (const s of scripts) { const match = s.textContent.match(/sessionId:\s*'([^']+)'/); if (match) return match[1]; } return ''; - })()`, &sessionID), - ) - require.NoError(t, err, "browser navigation failed") + })()`)) + require.NoError(t, err, "browser: extract session ID") assert.NotEmpty(t, qrSrc, "QR code image must have src attribute") assert.NotEmpty(t, sessionID, "session ID must be extractable from page") assert.Contains(t, qrSrc, "/qr/", "QR src must point to /qr/ endpoint") @@ -334,19 +336,19 @@ func TestCrossDevice_SSENotification(t *testing.T) { verifierPublicURL, vpClient.ClientID, url.QueryEscape(callbackServer.RedirectURI()), url.QueryEscape("openid pid"), vpState, codeChallenge) // Navigate and wait for QR + SSE connection to establish - var sessionID string - err := chromedp.Run(browserCtx, + err := chromedp.Do(browserCtx, chromedp.Navigate(authorizeURL), - chromedp.WaitVisible(`#qr-code`, chromedp.ByID), - chromedp.Evaluate(`(() => { + chromedp.WaitVisible(chromedp.ID("qr-code")), + ) + require.NoError(t, err) + sessionID, err := chromedp.Run(browserCtx, chromedp.Evaluate[string](`(() => { const scripts = document.querySelectorAll('script'); for (const s of scripts) { const match = s.textContent.match(/sessionId:\s*'([^']+)'/); if (match) return match[1]; } return ''; - })()`, &sessionID), - ) + })()`)) require.NoError(t, err) require.NotEmpty(t, sessionID) diff --git a/vendor/github.com/chromedp/cdproto/CHANGELOG.md b/vendor/github.com/chromedp/cdproto/CHANGELOG.md new file mode 100644 index 000000000..07dc3d195 --- /dev/null +++ b/vendor/github.com/chromedp/cdproto/CHANGELOG.md @@ -0,0 +1,245 @@ +# Changelog + +Each release of `cdproto` is generated from the Chromium and V8 protocol +definitions listed below. The minor version is the Chromium major version. As +the protocol definitions deprecate and remove commands, events, types, and +fields, any release can contain incompatible changes to the generated API. + +Since 2026-10-06 the package builds with Go 1.25 and later. The package +`cdp/jsonv2` defines the JSON types and funcs that the generated code uses, such +as `jsonv2.Value` and `jsonv2.Unmarshal`. They are aliases of the standard types with Go +1.27 or `GOEXPERIMENT=jsonv2`. Otherwise they come from the module +`github.com/go-json-experiment/json`. + +## v0.158.2 - 2026-10-17 + +- Chromium: 158.0.8110.1 (was 158.0.8108.1) +- V8: 15.8.17 +- API changes since v0.158.1: 0 incompatible, 0 compatible + +## v0.158.1 - 2026-10-16 + +- Chromium: 158.0.8108.1 (was 158.0.8104.1) +- V8: 15.8.17 (was 15.7.112) +- API changes since v0.158.0: 0 incompatible, 1 compatible + +By package, as removed, changed and added names: + + network 0 removed 0 changed 1 added + +## v0.158.0 - 2026-10-14 + +- Chromium: 158.0.8104.1 (was 157.0.8103.0) +- V8: 15.7.112 +- API changes since v0.157.11: 0 incompatible, 1 compatible + +By package, as removed, changed and added names: + + page 0 removed 0 changed 1 added + +## v0.157.11 - 2026-10-13 + +- Chromium: 157.0.8103.0 (was 157.0.8100.1) +- V8: 15.7.112 (was 15.7.108) +- API changes since v0.157.10: 5 incompatible, 4 compatible + +By package, as removed, changed and added names: + + cdproto 1 removed 0 changed 1 added + io 4 removed 0 changed 0 added + page 0 removed 0 changed 3 added + +## v0.157.10 - 2026-10-12 + +- Chromium: 157.0.8100.1 (was 157.0.8086.1) +- V8: 15.7.108 (was 15.7.37) +- API changes since v0.157.9: 2 incompatible, 8 compatible + +By package, as removed, changed and added names: + + audits 0 removed 0 changed 1 added + cdproto 0 removed 0 changed 1 added + debugger 0 removed 0 changed 1 added + network 0 removed 0 changed 1 added + page 2 removed 0 changed 4 added + +## v0.157.7 - 2026-10-05 + +- Chromium: 157.0.8086.1 (was 157.0.8085.3) +- V8: 15.7.37 (was 15.7.33) +- API changes since v0.157.6: 0 incompatible, 0 compatible + +## v0.157.6 - 2026-10-04 + +- Chromium: 157.0.8085.3 (was 157.0.8085.2) +- V8: 15.7.33 +- API changes since v0.157.5: 0 incompatible, 0 compatible + +## v0.157.5 - 2026-10-04 + +- Chromium: 157.0.8085.2 (was 157.0.8085.1) +- V8: 15.7.33 +- API changes since v0.157.4: 0 incompatible, 0 compatible + +## v0.157.4 - 2026-10-03 + +- Chromium: 157.0.8085.1 +- V8: 15.7.33 +- API changes since v0.157.3: 72 incompatible, 1 compatible + +By package, as removed, changed and added names: + + accessibility 0 removed 1 changed 0 added + animation 0 removed 1 changed 0 added + audits 0 removed 1 changed 0 added + browser 0 removed 2 changed 0 added + cdp 1 removed 0 changed 0 added + css 0 removed 1 changed 0 added + debugger 0 removed 2 changed 0 added + dom 0 removed 3 changed 0 added + domdebugger 0 removed 1 changed 0 added + emulation 0 removed 19 changed 0 added + har 0 removed 7 changed 0 added + headlessexperimental 0 removed 1 changed 0 added + indexeddb 0 removed 2 changed 0 added + input 0 removed 8 changed 0 added + io 0 removed 1 changed 0 added + layertree 0 removed 1 changed 0 added + network 0 removed 5 changed 1 added + overlay 0 removed 2 changed 0 added + page 0 removed 6 changed 0 added + runtime 0 removed 1 changed 0 added + storage 0 removed 1 changed 0 added + target 0 removed 2 changed 0 added + webauthn 0 removed 3 changed 0 added + +## v0.157.3 - 2026-10-03 + +- Chromium: 157.0.8085.1 +- V8: 15.7.33 +- API changes since v0.157.2: 2237 incompatible, 1079 compatible + +By package, as removed, changed and added names: + + accessibility 30 removed 17 changed 8 added + ads 4 removed 4 changed 2 added + animation 15 removed 20 changed 7 added + audits 8 removed 9 changed 3 added + autofill 7 removed 8 changed 1 added + backgroundservice 4 removed 8 changed 2 added + bluetoothemulation 20 removed 40 changed 6 added + browser 45 removed 47 changed 10 added + cachestorage 14 removed 12 changed 3 added + cast 7 removed 12 changed 2 added + cdp 4 removed 0 changed 6 added + crashreportcontext 2 removed 2 changed 1 added + css 76 removed 79 changed 35 added + debugger 69 removed 71 changed 16 added + deviceaccess 4 removed 8 changed 1 added + deviceorientation 2 removed 4 changed 0 added + digitalcredentials 4 removed 2 changed 0 added + dom 136 removed 116 changed 51 added + domdebugger 13 removed 17 changed 1 added + domsnapshot 8 removed 10 changed 1 added + domstorage 7 removed 12 changed 5 added + emulation 105 removed 98 changed 7 added + eventbreakpoints 3 removed 6 changed 0 added + extensions 13 removed 17 changed 3 added + fedcm 9 removed 16 changed 2 added + fetch 26 removed 24 changed 4 added + filesystem 2 removed 2 changed 1 added + findinpage 4 removed 8 changed 0 added + har 0 removed 2 changed 1 added + headlessexperimental 6 removed 3 changed 1 added + heapprofiler 28 removed 33 changed 9 added + indexeddb 36 removed 18 changed 4 added + input 65 removed 30 changed 1 added + inspector 2 removed 4 changed 4 added + io 7 removed 6 changed 2 added + layertree 21 removed 20 changed 8 added + log 5 removed 10 changed 1 added + media 2 removed 4 changed 5 added + memory 18 removed 23 changed 5 added + network 69 removed 96 changed 54 added + overlay 51 removed 59 changed 9 added + page 133 removed 132 changed 47 added + performance 5 removed 6 changed 2 added + performancetimeline 1 removed 2 changed 1 added + preload 2 removed 4 changed 6 added + profiler 16 removed 21 changed 7 added + pwa 14 removed 15 changed 3 added + runtime 77 removed 71 changed 19 added + security 3 removed 6 changed 1 added + serviceworker 12 removed 24 changed 3 added + smartcardemulation 14 removed 36 changed 14 added + storage 39 removed 54 changed 15 added + systeminfo 6 removed 6 changed 3 added + target 54 removed 46 changed 16 added + tethering 2 removed 4 changed 1 added + tracing 20 removed 17 changed 6 added + webaudio 4 removed 6 changed 14 added + webauthn 25 removed 46 changed 7 added + webmcp 5 removed 8 changed 5 added + +## v0.157.2 - 2026-10-03 + +- Chromium: 157.0.8085.1 (was 157.0.8084.3) +- V8: 15.7.33 (was 15.7.23) +- API changes since v0.157.1: 0 incompatible, 0 compatible + +## v0.157.1 - 2026-10-03 + +- Chromium: 157.0.8084.3 +- V8: 15.7.23 +- API changes since v0.157.0: 267 incompatible, 493 compatible + +By package, as removed, changed and added names: + + accessibility 4 removed 0 changed 0 added + animation 0 removed 1 changed 4 added + audits 29 removed 2 changed 4 added + autofill 1 removed 0 changed 0 added + backgroundservice 1 removed 0 changed 0 added + bluetoothemulation 5 removed 0 changed 0 added + browser 4 removed 3 changed 9 added + cachestorage 1 removed 0 changed 0 added + cdp 11 removed 0 changed 0 added + css 2 removed 3 changed 17 added + debugger 1 removed 13 changed 49 added + digitalcredentials 1 removed 0 changed 0 added + dom 3 removed 6 changed 10 added + domdebugger 2 removed 0 changed 0 added + emulation 5 removed 15 changed 37 added + extensions 1 removed 0 changed 0 added + fedcm 4 removed 0 changed 0 added + fetch 1 removed 2 changed 7 added + headlessexperimental 0 removed 1 changed 4 added + indexeddb 0 removed 2 changed 9 added + input 2 removed 12 changed 28 added + layertree 0 removed 1 changed 4 added + log 0 removed 4 changed 29 added + media 0 removed 1 changed 5 added + memory 1 removed 0 changed 0 added + network 27 removed 11 changed 77 added + overlay 4 removed 1 changed 3 added + page 10 removed 18 changed 44 added + performance 0 removed 2 changed 3 added + preload 6 removed 0 changed 0 added + pwa 1 removed 0 changed 0 added + runtime 0 removed 9 changed 142 added + security 4 removed 0 changed 0 added + serviceworker 3 removed 0 changed 0 added + smartcardemulation 5 removed 0 changed 0 added + storage 2 removed 0 changed 0 added + systeminfo 2 removed 0 changed 0 added + target 1 removed 0 changed 0 added + tracing 4 removed 3 changed 8 added + webaudio 5 removed 0 changed 0 added + webauthn 3 removed 0 changed 0 added + webmcp 1 removed 0 changed 0 added + +## v0.157.0 - 2026-10-03 + +- Chromium: 157.0.8084.3 +- V8: 15.7.23 +- API changes: first tagged release diff --git a/vendor/github.com/chromedp/cdproto/LICENSE b/vendor/github.com/chromedp/cdproto/LICENSE index b9ba4a540..7c49e6c89 100644 --- a/vendor/github.com/chromedp/cdproto/LICENSE +++ b/vendor/github.com/chromedp/cdproto/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2016-2025 Kenneth Shaw +Copyright (c) 2016-2026 Kenneth Shaw Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/github.com/chromedp/cdproto/README.md b/vendor/github.com/chromedp/cdproto/README.md index a21f77cac..be2eb4bbf 100644 --- a/vendor/github.com/chromedp/cdproto/README.md +++ b/vendor/github.com/chromedp/cdproto/README.md @@ -1,29 +1,81 @@ # About cdproto +

+ chromedp logo +

+ Package `cdproto` contains the generated commands, types, and events for the [Chrome DevTools Protocol domains][devtools-protocol]. [![Unit Tests][cdproto-ci-status]][cdproto-ci] [![Go Reference][goref-cdproto-status]][goref-cdproto] +[![Releases][release-status]][releases] +[![Discord Discussion][discord-status]][discord] + +This package is generated by the [`pdlgen`][pdlgen] command. Please refer to +that project and to the main [`chromedp`][chromedp] project for information on +using the commands, types, and events available here. + +## Install + +```sh +go get github.com/chromedp/cdproto@latest +``` + +The package needs Go 1.25 or later. Go 1.27 has `encoding/json/v2` in the +standard library, but Go 1.25 and Go 1.26 have it only with +`GOEXPERIMENT=jsonv2`. To work without that setting, the package `cdp/jsonv2` is +the only package that imports a JSON package. It has the names of the standard +library, such as `jsonv2.Value`, `jsonv2.Options`, `jsonv2.Marshal` and +`jsonv2.Unmarshal`. With Go 1.27, or with +`GOEXPERIMENT=jsonv2`, they are aliases of the standard types. In all other +cases they come from the module `github.com/go-json-experiment/json`. The build +tag `cdproto_jsoncompat` selects the module on every version of Go. With Go 1.27, +set `GOEXPERIMENT=nojsonv2` as well, because the pinned version of the module +does not build with the standard package of Go 1.27. + +## Using the API + +Each protocol command is a value with a parameter type and a result type. The +function `cdp.Call` runs it on a session. Each protocol event is a value too. +The function `cdp.Events` returns an iterator for it. + +```go +res, err := cdp.Call(ctx, session, page.Navigate, page.NavigateParams{URL: "https://example.com"}) +``` + +See the [Go Reference][goref-cdproto] for the API, and +[`docs/API.md`][pdlgen-api] in the [`pdlgen`][pdlgen] project for the rules that the generator follows. -This package is generated by the [`cdproto-gen`][cdproto-gen] command. Please -refer to that project and to the main [`chromedp`][chromedp] project for -information on using the commands, types, and events available here. +## Versions -## API +A tag has the form `v0..`, where the minor version is the +Chromium major version of the protocol. Any release can contain incompatible +changes, because the protocol removes and renames things. `CHANGELOG.md` and the +annotation of each tag list the changes. The releases up to `v0.157.2` have the +old API, which had a `Do` method on each command. The release `v0.157.3` is the +first one with the typed API. -Please see the [Go Reference][goref-cdproto]. +A new Chromium or V8 version alone makes no release. If the generated API is +the same, the workflow makes no commit and no tag. For this reason, +`cdproto.ChromiumVersion()` can name an older Chromium build than the newest +one. ## Contributing If you would like to submit a change to the code in this package, please submit -your Pull Request to the [`cdproto-gen`][cdproto-gen] project. Any Issues and -Pull Requests submitted to this project will be closed without being reviewed. +your Pull Request to the [`pdlgen`][pdlgen] project. Any Issues and Pull +Requests submitted to this project will be closed without being reviewed. [cdproto-ci]: https://github.com/chromedp/cdproto/actions/workflows/build.yml (Build CI) [cdproto-ci-status]: https://github.com/chromedp/cdproto/actions/workflows/build.yml/badge.svg (Build CI) -[cdproto-gen]: https://github.com/chromedp/cdproto-gen [chromedp]: https://github.com/chromedp/chromedp [devtools-protocol]: https://chromedevtools.github.io/devtools-protocol/ [goref-cdproto]: https://pkg.go.dev/github.com/chromedp/cdproto -[goref-cdproto-status]: https://pkg.go.dev/badge/github.com/chromedp/chromedp.svg +[goref-cdproto-status]: https://pkg.go.dev/badge/github.com/chromedp/cdproto.svg +[pdlgen]: https://github.com/chromedp/pdlgen +[pdlgen-api]: https://github.com/chromedp/pdlgen/blob/main/docs/API.md +[release-status]: https://img.shields.io/github/v/tag/chromedp/cdproto?sort=semver&label=release (Latest Tag) +[releases]: https://github.com/chromedp/cdproto/tags (Tags) +[discord]: https://discord.gg/WDWAgXwJqN "Discord Discussion" +[discord-status]: https://img.shields.io/discord/829150509658013727.svg?label=Discord&logo=Discord&colorB=7289da&style=flat-square "Discord Discussion" diff --git a/vendor/github.com/chromedp/cdproto/accessibility/accessibility.go b/vendor/github.com/chromedp/cdproto/accessibility/accessibility.go index 80d0ca82a..4b0da255b 100644 --- a/vendor/github.com/chromedp/cdproto/accessibility/accessibility.go +++ b/vendor/github.com/chromedp/cdproto/accessibility/accessibility.go @@ -1,330 +1,126 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package accessibility provides the Chrome DevTools Protocol // commands, types, and events for the Accessibility domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package accessibility -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/runtime" ) -// DisableParams disables the accessibility domain. -type DisableParams struct{} - // Disable disables the accessibility domain. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes Accessibility.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// EnableParams enables the accessibility domain which causes AXNodeIds to -// remain consistent between method calls. This turns on accessibility for the -// page, which can impact performance until accessibility is disabled. -type EnableParams struct{} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} // Enable enables the accessibility domain which causes AXNodeIds to remain // consistent between method calls. This turns on accessibility for the page, // which can impact performance until accessibility is disabled. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} -// Do executes Accessibility.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) +// GetPartialAXTreeParams are the parameters of the command +// Accessibility.getPartialAXTree. +type GetPartialAXTreeParams struct { + NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Identifier of the node to get the partial accessibility tree for. + BackendNodeID cdp.BackendNodeID `json:"backendNodeId,omitempty,omitzero"` // Identifier of the backend node to get the partial accessibility tree for. + ObjectID runtime.RemoteObjectID `json:"objectId,omitempty,omitzero"` // JavaScript object id of the node wrapper to get the partial accessibility tree for. + FetchRelatives *bool `json:"fetchRelatives,omitempty,omitzero"` // Whether to fetch this node's ancestors, siblings and children. Defaults to true. } -// GetPartialAXTreeParams fetches the accessibility node and partial -// accessibility tree for this DOM node, if it exists. -type GetPartialAXTreeParams struct { - NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Identifier of the node to get the partial accessibility tree for. - BackendNodeID cdp.BackendNodeID `json:"backendNodeId,omitempty,omitzero"` // Identifier of the backend node to get the partial accessibility tree for. - ObjectID runtime.RemoteObjectID `json:"objectId,omitempty,omitzero"` // JavaScript object id of the node wrapper to get the partial accessibility tree for. - FetchRelatives bool `json:"fetchRelatives"` // Whether to fetch this node's ancestors, siblings and children. Defaults to true. +// GetPartialAXTreeResult is the result of the command +// Accessibility.getPartialAXTree. +type GetPartialAXTreeResult struct { + Nodes []*Node `json:"nodes,omitempty,omitzero"` // The Accessibility.AXNode for this DOM node, if it exists, plus its ancestors, siblings and children, if requested. } // GetPartialAXTree fetches the accessibility node and partial accessibility // tree for this DOM node, if it exists. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-getPartialAXTree -// -// parameters: -func GetPartialAXTree() *GetPartialAXTreeParams { - return &GetPartialAXTreeParams{ - FetchRelatives: true, - } -} - -// WithNodeID identifier of the node to get the partial accessibility tree -// for. -func (p GetPartialAXTreeParams) WithNodeID(nodeID cdp.NodeID) *GetPartialAXTreeParams { - p.NodeID = nodeID - return &p -} +var GetPartialAXTree = cdp.Command[GetPartialAXTreeParams, GetPartialAXTreeResult]{Method: CommandGetPartialAXTree} -// WithBackendNodeID identifier of the backend node to get the partial -// accessibility tree for. -func (p GetPartialAXTreeParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *GetPartialAXTreeParams { - p.BackendNodeID = backendNodeID - return &p -} - -// WithObjectID JavaScript object id of the node wrapper to get the partial -// accessibility tree for. -func (p GetPartialAXTreeParams) WithObjectID(objectID runtime.RemoteObjectID) *GetPartialAXTreeParams { - p.ObjectID = objectID - return &p -} - -// WithFetchRelatives whether to fetch this node's ancestors, siblings and -// children. Defaults to true. -func (p GetPartialAXTreeParams) WithFetchRelatives(fetchRelatives bool) *GetPartialAXTreeParams { - p.FetchRelatives = fetchRelatives - return &p -} - -// GetPartialAXTreeReturns return values. -type GetPartialAXTreeReturns struct { - Nodes []*Node `json:"nodes,omitempty,omitzero"` // The Accessibility.AXNode for this DOM node, if it exists, plus its ancestors, siblings and children, if requested. -} - -// Do executes Accessibility.getPartialAXTree against the provided context. -// -// returns: -// -// nodes - The Accessibility.AXNode for this DOM node, if it exists, plus its ancestors, siblings and children, if requested. -func (p *GetPartialAXTreeParams) Do(ctx context.Context) (nodes []*Node, err error) { - // execute - var res GetPartialAXTreeReturns - err = cdp.Execute(ctx, CommandGetPartialAXTree, p, &res) - if err != nil { - return nil, err - } - - return res.Nodes, nil -} - -// GetFullAXTreeParams fetches the entire accessibility tree for the root -// Document. +// GetFullAXTreeParams are the parameters of the command +// Accessibility.getFullAXTree. type GetFullAXTreeParams struct { - Depth int64 `json:"depth,omitempty,omitzero"` // The maximum depth at which descendants of the root node should be retrieved. If omitted, the full tree is returned. + Depth *int64 `json:"depth,omitempty,omitzero"` // The maximum depth at which descendants of the root node should be retrieved. If omitted, the full tree is returned. FrameID cdp.FrameID `json:"frameId,omitempty,omitzero"` // The frame for whose document the AX tree should be retrieved. If omitted, the root frame is used. } -// GetFullAXTree fetches the entire accessibility tree for the root Document. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-getFullAXTree -// -// parameters: -func GetFullAXTree() *GetFullAXTreeParams { - return &GetFullAXTreeParams{} -} - -// WithDepth the maximum depth at which descendants of the root node should -// be retrieved. If omitted, the full tree is returned. -func (p GetFullAXTreeParams) WithDepth(depth int64) *GetFullAXTreeParams { - p.Depth = depth - return &p -} - -// WithFrameID the frame for whose document the AX tree should be retrieved. -// If omitted, the root frame is used. -func (p GetFullAXTreeParams) WithFrameID(frameID cdp.FrameID) *GetFullAXTreeParams { - p.FrameID = frameID - return &p -} - -// GetFullAXTreeReturns return values. -type GetFullAXTreeReturns struct { +// GetFullAXTreeResult is the result of the command +// Accessibility.getFullAXTree. +type GetFullAXTreeResult struct { Nodes []*Node `json:"nodes,omitempty,omitzero"` } -// Do executes Accessibility.getFullAXTree against the provided context. -// -// returns: +// GetFullAXTree fetches the entire accessibility tree for the root Document. // -// nodes -func (p *GetFullAXTreeParams) Do(ctx context.Context) (nodes []*Node, err error) { - // execute - var res GetFullAXTreeReturns - err = cdp.Execute(ctx, CommandGetFullAXTree, p, &res) - if err != nil { - return nil, err - } - - return res.Nodes, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-getFullAXTree +var GetFullAXTree = cdp.Command[GetFullAXTreeParams, GetFullAXTreeResult]{Method: CommandGetFullAXTree} -// GetRootAXNodeParams fetches the root node. Requires enable() to have been -// called previously. +// GetRootAXNodeParams are the parameters of the command +// Accessibility.getRootAXNode. type GetRootAXNodeParams struct { FrameID cdp.FrameID `json:"frameId,omitempty,omitzero"` // The frame in whose document the node resides. If omitted, the root frame is used. } -// GetRootAXNode fetches the root node. Requires enable() to have been called -// previously. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-getRootAXNode -// -// parameters: -func GetRootAXNode() *GetRootAXNodeParams { - return &GetRootAXNodeParams{} -} - -// WithFrameID the frame in whose document the node resides. If omitted, the -// root frame is used. -func (p GetRootAXNodeParams) WithFrameID(frameID cdp.FrameID) *GetRootAXNodeParams { - p.FrameID = frameID - return &p -} - -// GetRootAXNodeReturns return values. -type GetRootAXNodeReturns struct { +// GetRootAXNodeResult is the result of the command +// Accessibility.getRootAXNode. +type GetRootAXNodeResult struct { Node *Node `json:"node,omitempty,omitzero"` } -// Do executes Accessibility.getRootAXNode against the provided context. -// -// returns: +// GetRootAXNode fetches the root node. Requires enable() to have been called +// previously. // -// node -func (p *GetRootAXNodeParams) Do(ctx context.Context) (node *Node, err error) { - // execute - var res GetRootAXNodeReturns - err = cdp.Execute(ctx, CommandGetRootAXNode, p, &res) - if err != nil { - return nil, err - } - - return res.Node, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-getRootAXNode +var GetRootAXNode = cdp.Command[GetRootAXNodeParams, GetRootAXNodeResult]{Method: CommandGetRootAXNode} -// GetAXNodeAndAncestorsParams fetches a node and all ancestors up to and -// including the root. Requires enable() to have been called previously. +// GetAXNodeAndAncestorsParams are the parameters of the command +// Accessibility.getAXNodeAndAncestors. type GetAXNodeAndAncestorsParams struct { NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Identifier of the node to get. BackendNodeID cdp.BackendNodeID `json:"backendNodeId,omitempty,omitzero"` // Identifier of the backend node to get. ObjectID runtime.RemoteObjectID `json:"objectId,omitempty,omitzero"` // JavaScript object id of the node wrapper to get. } -// GetAXNodeAndAncestors fetches a node and all ancestors up to and including -// the root. Requires enable() to have been called previously. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-getAXNodeAndAncestors -// -// parameters: -func GetAXNodeAndAncestors() *GetAXNodeAndAncestorsParams { - return &GetAXNodeAndAncestorsParams{} -} - -// WithNodeID identifier of the node to get. -func (p GetAXNodeAndAncestorsParams) WithNodeID(nodeID cdp.NodeID) *GetAXNodeAndAncestorsParams { - p.NodeID = nodeID - return &p -} - -// WithBackendNodeID identifier of the backend node to get. -func (p GetAXNodeAndAncestorsParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *GetAXNodeAndAncestorsParams { - p.BackendNodeID = backendNodeID - return &p -} - -// WithObjectID JavaScript object id of the node wrapper to get. -func (p GetAXNodeAndAncestorsParams) WithObjectID(objectID runtime.RemoteObjectID) *GetAXNodeAndAncestorsParams { - p.ObjectID = objectID - return &p -} - -// GetAXNodeAndAncestorsReturns return values. -type GetAXNodeAndAncestorsReturns struct { +// GetAXNodeAndAncestorsResult is the result of the command +// Accessibility.getAXNodeAndAncestors. +type GetAXNodeAndAncestorsResult struct { Nodes []*Node `json:"nodes,omitempty,omitzero"` } -// Do executes Accessibility.getAXNodeAndAncestors against the provided context. -// -// returns: +// GetAXNodeAndAncestors fetches a node and all ancestors up to and including +// the root. Requires enable() to have been called previously. // -// nodes -func (p *GetAXNodeAndAncestorsParams) Do(ctx context.Context) (nodes []*Node, err error) { - // execute - var res GetAXNodeAndAncestorsReturns - err = cdp.Execute(ctx, CommandGetAXNodeAndAncestors, p, &res) - if err != nil { - return nil, err - } - - return res.Nodes, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-getAXNodeAndAncestors +var GetAXNodeAndAncestors = cdp.Command[GetAXNodeAndAncestorsParams, GetAXNodeAndAncestorsResult]{Method: CommandGetAXNodeAndAncestors} -// GetChildAXNodesParams fetches a particular accessibility node by AXNodeId. -// Requires enable() to have been called previously. +// GetChildAXNodesParams are the parameters of the command +// Accessibility.getChildAXNodes. type GetChildAXNodesParams struct { ID NodeID `json:"id"` FrameID cdp.FrameID `json:"frameId,omitempty,omitzero"` // The frame in whose document the node resides. If omitted, the root frame is used. } -// GetChildAXNodes fetches a particular accessibility node by AXNodeId. -// Requires enable() to have been called previously. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-getChildAXNodes -// -// parameters: -// -// id -func GetChildAXNodes(id NodeID) *GetChildAXNodesParams { - return &GetChildAXNodesParams{ - ID: id, - } -} - -// WithFrameID the frame in whose document the node resides. If omitted, the -// root frame is used. -func (p GetChildAXNodesParams) WithFrameID(frameID cdp.FrameID) *GetChildAXNodesParams { - p.FrameID = frameID - return &p -} - -// GetChildAXNodesReturns return values. -type GetChildAXNodesReturns struct { +// GetChildAXNodesResult is the result of the command +// Accessibility.getChildAXNodes. +type GetChildAXNodesResult struct { Nodes []*Node `json:"nodes,omitempty,omitzero"` } -// Do executes Accessibility.getChildAXNodes against the provided context. -// -// returns: +// GetChildAXNodes fetches a particular accessibility node by AXNodeId. +// Requires enable() to have been called previously. // -// nodes -func (p *GetChildAXNodesParams) Do(ctx context.Context) (nodes []*Node, err error) { - // execute - var res GetChildAXNodesReturns - err = cdp.Execute(ctx, CommandGetChildAXNodes, p, &res) - if err != nil { - return nil, err - } - - return res.Nodes, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-getChildAXNodes +var GetChildAXNodes = cdp.Command[GetChildAXNodesParams, GetChildAXNodesResult]{Method: CommandGetChildAXNodes} -// QueryAXTreeParams query a DOM node's accessibility subtree for accessible -// name and role. This command computes the name and role for all nodes in the -// subtree, including those that are ignored for accessibility, and returns -// those that match the specified name and role. If no DOM node is specified, or -// the DOM node does not exist, the command returns an error. If neither -// accessibleName or role is specified, it returns all the accessibility nodes -// in the subtree. +// QueryAXTreeParams are the parameters of the command +// Accessibility.queryAXTree. type QueryAXTreeParams struct { NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Identifier of the node for the root to query. BackendNodeID cdp.BackendNodeID `json:"backendNodeId,omitempty,omitzero"` // Identifier of the backend node for the root to query. @@ -333,6 +129,11 @@ type QueryAXTreeParams struct { Role string `json:"role,omitempty,omitzero"` // Find nodes with this computed role. } +// QueryAXTreeResult is the result of the command Accessibility.queryAXTree. +type QueryAXTreeResult struct { + Nodes []*Node `json:"nodes,omitempty,omitzero"` // A list of Accessibility.AXNode matching the specified attributes, including nodes that are ignored for accessibility. +} + // QueryAXTree query a DOM node's accessibility subtree for accessible name // and role. This command computes the name and role for all nodes in the // subtree, including those that are ignored for accessibility, and returns @@ -342,63 +143,20 @@ type QueryAXTreeParams struct { // in the subtree. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-queryAXTree -// -// parameters: -func QueryAXTree() *QueryAXTreeParams { - return &QueryAXTreeParams{} -} - -// WithNodeID identifier of the node for the root to query. -func (p QueryAXTreeParams) WithNodeID(nodeID cdp.NodeID) *QueryAXTreeParams { - p.NodeID = nodeID - return &p -} - -// WithBackendNodeID identifier of the backend node for the root to query. -func (p QueryAXTreeParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *QueryAXTreeParams { - p.BackendNodeID = backendNodeID - return &p -} - -// WithObjectID JavaScript object id of the node wrapper for the root to -// query. -func (p QueryAXTreeParams) WithObjectID(objectID runtime.RemoteObjectID) *QueryAXTreeParams { - p.ObjectID = objectID - return &p -} - -// WithAccessibleName find nodes with this computed name. -func (p QueryAXTreeParams) WithAccessibleName(accessibleName string) *QueryAXTreeParams { - p.AccessibleName = accessibleName - return &p -} +var QueryAXTree = cdp.Command[QueryAXTreeParams, QueryAXTreeResult]{Method: CommandQueryAXTree} -// WithRole find nodes with this computed role. -func (p QueryAXTreeParams) WithRole(role string) *QueryAXTreeParams { - p.Role = role - return &p -} - -// QueryAXTreeReturns return values. -type QueryAXTreeReturns struct { - Nodes []*Node `json:"nodes,omitempty,omitzero"` // A list of Accessibility.AXNode matching the specified attributes, including nodes that are ignored for accessibility. -} - -// Do executes Accessibility.queryAXTree against the provided context. +// LoadComplete the loadComplete event mirrors the load complete event sent +// by the browser to assistive technology when the web page has finished +// loading. // -// returns: -// -// nodes - A list of Accessibility.AXNode matching the specified attributes, including nodes that are ignored for accessibility. -func (p *QueryAXTreeParams) Do(ctx context.Context) (nodes []*Node, err error) { - // execute - var res QueryAXTreeReturns - err = cdp.Execute(ctx, CommandQueryAXTree, p, &res) - if err != nil { - return nil, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#event-loadComplete +var LoadComplete = cdp.Event[EventLoadComplete]{Method: "Accessibility.loadComplete"} - return res.Nodes, nil -} +// NodesUpdated the nodesUpdated event is sent every time a previously +// requested node has changed the in tree. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#event-nodesUpdated +var NodesUpdated = cdp.Event[EventNodesUpdated]{Method: "Accessibility.nodesUpdated"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/accessibility/events.go b/vendor/github.com/chromedp/cdproto/accessibility/events.go index ae3b511fc..12e06305c 100644 --- a/vendor/github.com/chromedp/cdproto/accessibility/events.go +++ b/vendor/github.com/chromedp/cdproto/accessibility/events.go @@ -1,6 +1,6 @@ -package accessibility +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package accessibility // EventLoadComplete the loadComplete event mirrors the load complete event // sent by the browser to assistive technology when the web page has finished diff --git a/vendor/github.com/chromedp/cdproto/accessibility/types.go b/vendor/github.com/chromedp/cdproto/accessibility/types.go index ca1c95dba..dcb004940 100644 --- a/vendor/github.com/chromedp/cdproto/accessibility/types.go +++ b/vendor/github.com/chromedp/cdproto/accessibility/types.go @@ -1,13 +1,10 @@ -package accessibility +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package accessibility import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/cdp" - "github.com/go-json-experiment/json/jsontext" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" ) // NodeID unique accessibility node identifier. @@ -51,52 +48,6 @@ const ( ValueTypeValueUndefined ValueType = "valueUndefined" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ValueType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ValueType(s) { - case ValueTypeBoolean: - *t = ValueTypeBoolean - case ValueTypeTristate: - *t = ValueTypeTristate - case ValueTypeBooleanOrUndefined: - *t = ValueTypeBooleanOrUndefined - case ValueTypeIdref: - *t = ValueTypeIdref - case ValueTypeIdrefList: - *t = ValueTypeIdrefList - case ValueTypeInteger: - *t = ValueTypeInteger - case ValueTypeNode: - *t = ValueTypeNode - case ValueTypeNodeList: - *t = ValueTypeNodeList - case ValueTypeNumber: - *t = ValueTypeNumber - case ValueTypeString: - *t = ValueTypeString - case ValueTypeComputedString: - *t = ValueTypeComputedString - case ValueTypeToken: - *t = ValueTypeToken - case ValueTypeTokenList: - *t = ValueTypeTokenList - case ValueTypeDomRelation: - *t = ValueTypeDomRelation - case ValueTypeRole: - *t = ValueTypeRole - case ValueTypeInternalRole: - *t = ValueTypeInternalRole - case ValueTypeValueUndefined: - *t = ValueTypeValueUndefined - default: - return fmt.Errorf("unknown ValueType value: %v", s) - } - return nil -} - // ValueSourceType enum of possible property sources. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#type-AXValueSourceType @@ -117,30 +68,6 @@ const ( ValueSourceTypeRelatedElement ValueSourceType = "relatedElement" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ValueSourceType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ValueSourceType(s) { - case ValueSourceTypeAttribute: - *t = ValueSourceTypeAttribute - case ValueSourceTypeImplicit: - *t = ValueSourceTypeImplicit - case ValueSourceTypeStyle: - *t = ValueSourceTypeStyle - case ValueSourceTypeContents: - *t = ValueSourceTypeContents - case ValueSourceTypePlaceholder: - *t = ValueSourceTypePlaceholder - case ValueSourceTypeRelatedElement: - *t = ValueSourceTypeRelatedElement - default: - return fmt.Errorf("unknown ValueSourceType value: %v", s) - } - return nil -} - // ValueNativeSourceType enum of possible native property sources (as a // subtype of a particular AXValueSourceType). // @@ -166,38 +93,6 @@ const ( ValueNativeSourceTypeOther ValueNativeSourceType = "other" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ValueNativeSourceType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ValueNativeSourceType(s) { - case ValueNativeSourceTypeDescription: - *t = ValueNativeSourceTypeDescription - case ValueNativeSourceTypeFigcaption: - *t = ValueNativeSourceTypeFigcaption - case ValueNativeSourceTypeLabel: - *t = ValueNativeSourceTypeLabel - case ValueNativeSourceTypeLabelfor: - *t = ValueNativeSourceTypeLabelfor - case ValueNativeSourceTypeLabelwrapped: - *t = ValueNativeSourceTypeLabelwrapped - case ValueNativeSourceTypeLegend: - *t = ValueNativeSourceTypeLegend - case ValueNativeSourceTypeRubyannotation: - *t = ValueNativeSourceTypeRubyannotation - case ValueNativeSourceTypeTablecaption: - *t = ValueNativeSourceTypeTablecaption - case ValueNativeSourceTypeTitle: - *t = ValueNativeSourceTypeTitle - case ValueNativeSourceTypeOther: - *t = ValueNativeSourceTypeOther - default: - return fmt.Errorf("unknown ValueNativeSourceType value: %v", s) - } - return nil -} - // ValueSource a single source for a computed AX property. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#type-AXValueSource @@ -235,7 +130,7 @@ type Property struct { // See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#type-AXValue type Value struct { Type ValueType `json:"type"` // The type of this value. - Value jsontext.Value `json:"value,omitempty,omitzero"` // The computed value of this property. + Value jsonv2.Value `json:"value,omitempty,omitzero"` // The computed value of this property. RelatedNodes []*RelatedNode `json:"relatedNodes,omitempty,omitzero"` // One or more related nodes, if applicable. Sources []*ValueSource `json:"sources,omitempty,omitzero"` // The sources which contributed to the computation of this property. } @@ -319,134 +214,6 @@ const ( PropertyNameUninteresting PropertyName = "uninteresting" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *PropertyName) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch PropertyName(s) { - case PropertyNameActions: - *t = PropertyNameActions - case PropertyNameBusy: - *t = PropertyNameBusy - case PropertyNameDisabled: - *t = PropertyNameDisabled - case PropertyNameEditable: - *t = PropertyNameEditable - case PropertyNameFocusable: - *t = PropertyNameFocusable - case PropertyNameFocused: - *t = PropertyNameFocused - case PropertyNameHidden: - *t = PropertyNameHidden - case PropertyNameHiddenRoot: - *t = PropertyNameHiddenRoot - case PropertyNameInvalid: - *t = PropertyNameInvalid - case PropertyNameKeyshortcuts: - *t = PropertyNameKeyshortcuts - case PropertyNameSettable: - *t = PropertyNameSettable - case PropertyNameRoledescription: - *t = PropertyNameRoledescription - case PropertyNameLive: - *t = PropertyNameLive - case PropertyNameAtomic: - *t = PropertyNameAtomic - case PropertyNameRelevant: - *t = PropertyNameRelevant - case PropertyNameRoot: - *t = PropertyNameRoot - case PropertyNameAutocomplete: - *t = PropertyNameAutocomplete - case PropertyNameHasPopup: - *t = PropertyNameHasPopup - case PropertyNameLevel: - *t = PropertyNameLevel - case PropertyNameMultiselectable: - *t = PropertyNameMultiselectable - case PropertyNameOrientation: - *t = PropertyNameOrientation - case PropertyNameMultiline: - *t = PropertyNameMultiline - case PropertyNameReadonly: - *t = PropertyNameReadonly - case PropertyNameRequired: - *t = PropertyNameRequired - case PropertyNameValuemin: - *t = PropertyNameValuemin - case PropertyNameValuemax: - *t = PropertyNameValuemax - case PropertyNameValuetext: - *t = PropertyNameValuetext - case PropertyNameChecked: - *t = PropertyNameChecked - case PropertyNameExpanded: - *t = PropertyNameExpanded - case PropertyNameModal: - *t = PropertyNameModal - case PropertyNamePressed: - *t = PropertyNamePressed - case PropertyNameSelected: - *t = PropertyNameSelected - case PropertyNameActivedescendant: - *t = PropertyNameActivedescendant - case PropertyNameControls: - *t = PropertyNameControls - case PropertyNameDescribedby: - *t = PropertyNameDescribedby - case PropertyNameDetails: - *t = PropertyNameDetails - case PropertyNameErrormessage: - *t = PropertyNameErrormessage - case PropertyNameFlowto: - *t = PropertyNameFlowto - case PropertyNameLabelledby: - *t = PropertyNameLabelledby - case PropertyNameOwns: - *t = PropertyNameOwns - case PropertyNameURL: - *t = PropertyNameURL - case PropertyNameActiveFullscreenElement: - *t = PropertyNameActiveFullscreenElement - case PropertyNameActiveModalDialog: - *t = PropertyNameActiveModalDialog - case PropertyNameActiveAriaModalDialog: - *t = PropertyNameActiveAriaModalDialog - case PropertyNameAriaHiddenElement: - *t = PropertyNameAriaHiddenElement - case PropertyNameAriaHiddenSubtree: - *t = PropertyNameAriaHiddenSubtree - case PropertyNameEmptyAlt: - *t = PropertyNameEmptyAlt - case PropertyNameEmptyText: - *t = PropertyNameEmptyText - case PropertyNameInertElement: - *t = PropertyNameInertElement - case PropertyNameInertSubtree: - *t = PropertyNameInertSubtree - case PropertyNameLabelContainer: - *t = PropertyNameLabelContainer - case PropertyNameLabelFor: - *t = PropertyNameLabelFor - case PropertyNameNotRendered: - *t = PropertyNameNotRendered - case PropertyNameNotVisible: - *t = PropertyNameNotVisible - case PropertyNamePresentationalRole: - *t = PropertyNamePresentationalRole - case PropertyNameProbablyPresentational: - *t = PropertyNameProbablyPresentational - case PropertyNameInactiveCarouselTabContent: - *t = PropertyNameInactiveCarouselTabContent - case PropertyNameUninteresting: - *t = PropertyNameUninteresting - default: - return fmt.Errorf("unknown PropertyName value: %v", s) - } - return nil -} - // Node a node in the accessibility tree. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#type-AXNode diff --git a/vendor/github.com/chromedp/cdproto/ads/ads.go b/vendor/github.com/chromedp/cdproto/ads/ads.go index 17c00c63c..9b01be860 100644 --- a/vendor/github.com/chromedp/cdproto/ads/ads.go +++ b/vendor/github.com/chromedp/cdproto/ads/ads.go @@ -1,51 +1,41 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package ads provides the Chrome DevTools Protocol // commands, types, and events for the Ads domain. // // A domain for ad-related metrics and data. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package ads -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// GetAdMetricsParams retrieves ad metrics for the current page. -type GetAdMetricsParams struct{} +// GetAdMetricsResult is the result of the command Ads.getAdMetrics. +type GetAdMetricsResult struct { + Metrics *AdMetrics `json:"metrics,omitempty,omitzero"` +} // GetAdMetrics retrieves ad metrics for the current page. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Ads#method-getAdMetrics -func GetAdMetrics() *GetAdMetricsParams { - return &GetAdMetricsParams{} -} +var GetAdMetrics = cdp.Command[cdp.Empty, GetAdMetricsResult]{Method: CommandGetAdMetrics} -// GetAdMetricsReturns return values. -type GetAdMetricsReturns struct { - Metrics *AdMetrics `json:"metrics,omitempty,omitzero"` +// GetAdScriptsResult is the result of the command Ads.getAdScripts. +type GetAdScriptsResult struct { + NewScripts []*AdScript `json:"newScripts,omitempty,omitzero"` } -// Do executes Ads.getAdMetrics against the provided context. -// -// returns: +// GetAdScripts retrieves ad scripts for the current page. To minimize +// payload size, this only returns the newly tracked ad scripts since the last +// call to getAdScripts (i.e., the delta). // -// metrics -func (p *GetAdMetricsParams) Do(ctx context.Context) (metrics *AdMetrics, err error) { - // execute - var res GetAdMetricsReturns - err = cdp.Execute(ctx, CommandGetAdMetrics, nil, &res) - if err != nil { - return nil, err - } - - return res.Metrics, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Ads#method-getAdScripts +var GetAdScripts = cdp.Command[cdp.Empty, GetAdScriptsResult]{Method: CommandGetAdScripts} // Command names. const ( CommandGetAdMetrics = "Ads.getAdMetrics" + CommandGetAdScripts = "Ads.getAdScripts" ) diff --git a/vendor/github.com/chromedp/cdproto/ads/types.go b/vendor/github.com/chromedp/cdproto/ads/types.go index 582429b0a..fb713e81b 100644 --- a/vendor/github.com/chromedp/cdproto/ads/types.go +++ b/vendor/github.com/chromedp/cdproto/ads/types.go @@ -1,6 +1,6 @@ -package ads +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package ads import ( "github.com/chromedp/cdproto/cdp" @@ -29,3 +29,15 @@ type AdMetrics struct { UpdateAdFrames []*AdFrameData `json:"updateAdFrames"` // The list of ad frames that have been updated since the last event. RemoveAdFrames []cdp.FrameID `json:"removeAdFrames"` // The list of ad frame IDs that have been removed since the last event. } + +// AdScript an ad script. Note: when the script is a transitive ad script, we +// only fill in the immediate ancestor script in the provenance's +// adScriptAncestry field (as its first entry), rather than filling in the full +// ancestry. This saves work for the backend, and the frontend can reconstruct +// the full ancestry if necessary. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Ads#type-AdScript +type AdScript struct { + ScriptID cdp.ScriptID `json:"scriptId"` // The script ID. + Provenance *cdp.AdProvenance `json:"provenance"` // The ad provenance. +} diff --git a/vendor/github.com/chromedp/cdproto/animation/animation.go b/vendor/github.com/chromedp/cdproto/animation/animation.go index 6d935244d..f5f5bbaf9 100644 --- a/vendor/github.com/chromedp/cdproto/animation/animation.go +++ b/vendor/github.com/chromedp/cdproto/animation/animation.go @@ -1,120 +1,56 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package animation provides the Chrome DevTools Protocol // commands, types, and events for the Animation domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package animation -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/runtime" ) -// DisableParams disables animation domain notifications. -type DisableParams struct{} - // Disable disables animation domain notifications. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes Animation.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// EnableParams enables animation domain notifications. -type EnableParams struct{} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} // Enable enables animation domain notifications. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} -// Do executes Animation.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) -} - -// GetCurrentTimeParams returns the current time of the an animation. +// GetCurrentTimeParams are the parameters of the command +// Animation.getCurrentTime. type GetCurrentTimeParams struct { ID string `json:"id"` // Id of animation. } -// GetCurrentTime returns the current time of the an animation. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-getCurrentTime -// -// parameters: -// -// id - Id of animation. -func GetCurrentTime(id string) *GetCurrentTimeParams { - return &GetCurrentTimeParams{ - ID: id, - } -} - -// GetCurrentTimeReturns return values. -type GetCurrentTimeReturns struct { +// GetCurrentTimeResult is the result of the command +// Animation.getCurrentTime. +type GetCurrentTimeResult struct { CurrentTime float64 `json:"currentTime,omitempty,omitzero"` // Current time of the page. } -// Do executes Animation.getCurrentTime against the provided context. -// -// returns: +// GetCurrentTime returns the current time of the an animation. // -// currentTime - Current time of the page. -func (p *GetCurrentTimeParams) Do(ctx context.Context) (currentTime float64, err error) { - // execute - var res GetCurrentTimeReturns - err = cdp.Execute(ctx, CommandGetCurrentTime, p, &res) - if err != nil { - return 0, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-getCurrentTime +var GetCurrentTime = cdp.Command[GetCurrentTimeParams, GetCurrentTimeResult]{Method: CommandGetCurrentTime} - return res.CurrentTime, nil +// GetPlaybackRateResult is the result of the command +// Animation.getPlaybackRate. +type GetPlaybackRateResult struct { + PlaybackRate float64 `json:"playbackRate,omitempty,omitzero"` // Playback rate for animations on page. } -// GetPlaybackRateParams gets the playback rate of the document timeline. -type GetPlaybackRateParams struct{} - // GetPlaybackRate gets the playback rate of the document timeline. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-getPlaybackRate -func GetPlaybackRate() *GetPlaybackRateParams { - return &GetPlaybackRateParams{} -} - -// GetPlaybackRateReturns return values. -type GetPlaybackRateReturns struct { - PlaybackRate float64 `json:"playbackRate,omitempty,omitzero"` // Playback rate for animations on page. -} +var GetPlaybackRate = cdp.Command[cdp.Empty, GetPlaybackRateResult]{Method: CommandGetPlaybackRate} -// Do executes Animation.getPlaybackRate against the provided context. -// -// returns: -// -// playbackRate - Playback rate for animations on page. -func (p *GetPlaybackRateParams) Do(ctx context.Context) (playbackRate float64, err error) { - // execute - var res GetPlaybackRateReturns - err = cdp.Execute(ctx, CommandGetPlaybackRate, nil, &res) - if err != nil { - return 0, err - } - - return res.PlaybackRate, nil -} - -// ReleaseAnimationsParams releases a set of animations to no longer be -// manipulated. +// ReleaseAnimationsParams are the parameters of the command +// Animation.releaseAnimations. type ReleaseAnimationsParams struct { Animations []string `json:"animations"` // List of animation ids to seek. } @@ -123,89 +59,40 @@ type ReleaseAnimationsParams struct { // manipulated. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-releaseAnimations -// -// parameters: -// -// animations - List of animation ids to seek. -func ReleaseAnimations(animations []string) *ReleaseAnimationsParams { - return &ReleaseAnimationsParams{ - Animations: animations, - } -} +var ReleaseAnimations = cdp.Command[ReleaseAnimationsParams, cdp.Empty]{Method: CommandReleaseAnimations} -// Do executes Animation.releaseAnimations against the provided context. -func (p *ReleaseAnimationsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandReleaseAnimations, p, nil) -} - -// ResolveAnimationParams gets the remote object of the Animation. +// ResolveAnimationParams are the parameters of the command +// Animation.resolveAnimation. type ResolveAnimationParams struct { AnimationID string `json:"animationId"` // Animation id. } -// ResolveAnimation gets the remote object of the Animation. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-resolveAnimation -// -// parameters: -// -// animationID - Animation id. -func ResolveAnimation(animationID string) *ResolveAnimationParams { - return &ResolveAnimationParams{ - AnimationID: animationID, - } -} - -// ResolveAnimationReturns return values. -type ResolveAnimationReturns struct { +// ResolveAnimationResult is the result of the command +// Animation.resolveAnimation. +type ResolveAnimationResult struct { RemoteObject *runtime.RemoteObject `json:"remoteObject,omitempty,omitzero"` // Corresponding remote object. } -// Do executes Animation.resolveAnimation against the provided context. -// -// returns: +// ResolveAnimation gets the remote object of the Animation. // -// remoteObject - Corresponding remote object. -func (p *ResolveAnimationParams) Do(ctx context.Context) (remoteObject *runtime.RemoteObject, err error) { - // execute - var res ResolveAnimationReturns - err = cdp.Execute(ctx, CommandResolveAnimation, p, &res) - if err != nil { - return nil, err - } - - return res.RemoteObject, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-resolveAnimation +var ResolveAnimation = cdp.Command[ResolveAnimationParams, ResolveAnimationResult]{Method: CommandResolveAnimation} -// SeekAnimationsParams seek a set of animations to a particular time within -// each animation. +// SeekAnimationsParams are the parameters of the command +// Animation.seekAnimations. type SeekAnimationsParams struct { - Animations []string `json:"animations"` // List of animation ids to seek. - CurrentTime float64 `json:"currentTime"` // Set the current time of each animation. + Animations []string `json:"animations"` // List of animation ids to seek. + CurrentTime *float64 `json:"currentTime,omitempty,omitzero"` // Set each animation to the same time. + CurrentTimes []float64 `json:"currentTimes,omitempty,omitzero"` // Set each animation to a different time. If set, should have the same length as animations. Exactly one of currentTime or currentTimes should be set. } // SeekAnimations seek a set of animations to a particular time within each // animation. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-seekAnimations -// -// parameters: -// -// animations - List of animation ids to seek. -// currentTime - Set the current time of each animation. -func SeekAnimations(animations []string, currentTime float64) *SeekAnimationsParams { - return &SeekAnimationsParams{ - Animations: animations, - CurrentTime: currentTime, - } -} - -// Do executes Animation.seekAnimations against the provided context. -func (p *SeekAnimationsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSeekAnimations, p, nil) -} +var SeekAnimations = cdp.Command[SeekAnimationsParams, cdp.Empty]{Method: CommandSeekAnimations} -// SetPausedParams sets the paused state of a set of animations. +// SetPausedParams are the parameters of the command Animation.setPaused. type SetPausedParams struct { Animations []string `json:"animations"` // Animations to set the pause state of. Paused bool `json:"paused"` // Paused state to set to. @@ -214,24 +101,10 @@ type SetPausedParams struct { // SetPaused sets the paused state of a set of animations. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-setPaused -// -// parameters: -// -// animations - Animations to set the pause state of. -// paused - Paused state to set to. -func SetPaused(animations []string, paused bool) *SetPausedParams { - return &SetPausedParams{ - Animations: animations, - Paused: paused, - } -} +var SetPaused = cdp.Command[SetPausedParams, cdp.Empty]{Method: CommandSetPaused} -// Do executes Animation.setPaused against the provided context. -func (p *SetPausedParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetPaused, p, nil) -} - -// SetPlaybackRateParams sets the playback rate of the document timeline. +// SetPlaybackRateParams are the parameters of the command +// Animation.setPlaybackRate. type SetPlaybackRateParams struct { PlaybackRate float64 `json:"playbackRate"` // Playback rate for animations on page } @@ -239,22 +112,9 @@ type SetPlaybackRateParams struct { // SetPlaybackRate sets the playback rate of the document timeline. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-setPlaybackRate -// -// parameters: -// -// playbackRate - Playback rate for animations on page -func SetPlaybackRate(playbackRate float64) *SetPlaybackRateParams { - return &SetPlaybackRateParams{ - PlaybackRate: playbackRate, - } -} +var SetPlaybackRate = cdp.Command[SetPlaybackRateParams, cdp.Empty]{Method: CommandSetPlaybackRate} -// Do executes Animation.setPlaybackRate against the provided context. -func (p *SetPlaybackRateParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetPlaybackRate, p, nil) -} - -// SetTimingParams sets the timing of an animation node. +// SetTimingParams are the parameters of the command Animation.setTiming. type SetTimingParams struct { AnimationID string `json:"animationId"` // Animation id. Duration float64 `json:"duration"` // Duration of the animation. @@ -264,24 +124,27 @@ type SetTimingParams struct { // SetTiming sets the timing of an animation node. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-setTiming +var SetTiming = cdp.Command[SetTimingParams, cdp.Empty]{Method: CommandSetTiming} + +// AnimationCanceled event for when an animation has been cancelled. // -// parameters: +// See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#event-animationCanceled +var AnimationCanceled = cdp.Event[EventAnimationCanceled]{Method: "Animation.animationCanceled"} + +// AnimationCreated event for each animation that has been created. // -// animationID - Animation id. -// duration - Duration of the animation. -// delay - Delay of the animation. -func SetTiming(animationID string, duration float64, delay float64) *SetTimingParams { - return &SetTimingParams{ - AnimationID: animationID, - Duration: duration, - Delay: delay, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#event-animationCreated +var AnimationCreated = cdp.Event[EventAnimationCreated]{Method: "Animation.animationCreated"} -// Do executes Animation.setTiming against the provided context. -func (p *SetTimingParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetTiming, p, nil) -} +// AnimationStarted event for animation that has been started. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#event-animationStarted +var AnimationStarted = cdp.Event[EventAnimationStarted]{Method: "Animation.animationStarted"} + +// AnimationUpdated event for animation that has been updated. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#event-animationUpdated +var AnimationUpdated = cdp.Event[EventAnimationUpdated]{Method: "Animation.animationUpdated"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/animation/events.go b/vendor/github.com/chromedp/cdproto/animation/events.go index c6319851e..df3c7a8c5 100644 --- a/vendor/github.com/chromedp/cdproto/animation/events.go +++ b/vendor/github.com/chromedp/cdproto/animation/events.go @@ -1,6 +1,6 @@ -package animation +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package animation // EventAnimationCanceled event for when an animation has been cancelled. // diff --git a/vendor/github.com/chromedp/cdproto/animation/types.go b/vendor/github.com/chromedp/cdproto/animation/types.go index ececad8f0..bd15aa08d 100644 --- a/vendor/github.com/chromedp/cdproto/animation/types.go +++ b/vendor/github.com/chromedp/cdproto/animation/types.go @@ -1,11 +1,8 @@ -package animation +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package animation import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/dom" ) @@ -86,21 +83,3 @@ const ( TypeCSSAnimation Type = "CSSAnimation" TypeWebAnimation Type = "WebAnimation" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *Type) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch Type(s) { - case TypeCSSTransition: - *t = TypeCSSTransition - case TypeCSSAnimation: - *t = TypeCSSAnimation - case TypeWebAnimation: - *t = TypeWebAnimation - default: - return fmt.Errorf("unknown Type value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/audits/audits.go b/vendor/github.com/chromedp/cdproto/audits/audits.go index 208a3067d..528cc3a52 100644 --- a/vendor/github.com/chromedp/cdproto/audits/audits.go +++ b/vendor/github.com/chromedp/cdproto/audits/audits.go @@ -1,158 +1,70 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package audits provides the Chrome DevTools Protocol // commands, types, and events for the Audits domain. // // Audits domain allows investigation of page violations and possible // improvements. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package audits -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "encoding/base64" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/network" ) -// GetEncodedResponseParams returns the response body and size if it were -// re-encoded with the specified settings. Only applies to images. +// GetEncodedResponseParams are the parameters of the command +// Audits.getEncodedResponse. type GetEncodedResponseParams struct { - RequestID network.RequestID `json:"requestId"` // Identifier of the network request to get content for. - Encoding GetEncodedResponseEncoding `json:"encoding"` // The encoding to use. - Quality float64 `json:"quality,omitempty,omitzero"` // The quality of the encoding (0-1). (defaults to 1) - SizeOnly bool `json:"sizeOnly"` // Whether to only return the size information (defaults to false). + RequestID network.RequestID `json:"requestId"` // Identifier of the network request to get content for. + Encoding GetEncodedResponseEncoding `json:"encoding"` // The encoding to use. + Quality *float64 `json:"quality,omitempty,omitzero"` // The quality of the encoding (0-1). (defaults to 1) + SizeOnly *bool `json:"sizeOnly,omitempty,omitzero"` // Whether to only return the size information (defaults to false). } -// GetEncodedResponse returns the response body and size if it were -// re-encoded with the specified settings. Only applies to images. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#method-getEncodedResponse -// -// parameters: -// -// requestID - Identifier of the network request to get content for. -// encoding - The encoding to use. -func GetEncodedResponse(requestID network.RequestID, encoding GetEncodedResponseEncoding) *GetEncodedResponseParams { - return &GetEncodedResponseParams{ - RequestID: requestID, - Encoding: encoding, - SizeOnly: false, - } -} - -// WithQuality the quality of the encoding (0-1). (defaults to 1). -func (p GetEncodedResponseParams) WithQuality(quality float64) *GetEncodedResponseParams { - p.Quality = quality - return &p -} - -// WithSizeOnly whether to only return the size information (defaults to -// false). -func (p GetEncodedResponseParams) WithSizeOnly(sizeOnly bool) *GetEncodedResponseParams { - p.SizeOnly = sizeOnly - return &p -} - -// GetEncodedResponseReturns return values. -type GetEncodedResponseReturns struct { - Body string `json:"body,omitempty,omitzero"` // The encoded body as a base64 string. Omitted if sizeOnly is true. +// GetEncodedResponseResult is the result of the command +// Audits.getEncodedResponse. +type GetEncodedResponseResult struct { + Body []byte `json:"body,omitempty,omitzero"` // The encoded body as a base64 string. Omitted if sizeOnly is true. OriginalSize int64 `json:"originalSize,omitempty,omitzero"` // Size before re-encoding. EncodedSize int64 `json:"encodedSize,omitempty,omitzero"` // Size after re-encoding. } -// Do executes Audits.getEncodedResponse against the provided context. -// -// returns: +// GetEncodedResponse returns the response body and size if it were +// re-encoded with the specified settings. Only applies to images. // -// body - The encoded body as a base64 string. Omitted if sizeOnly is true. -// originalSize - Size before re-encoding. -// encodedSize - Size after re-encoding. -func (p *GetEncodedResponseParams) Do(ctx context.Context) (body []byte, originalSize int64, encodedSize int64, err error) { - // execute - var res GetEncodedResponseReturns - err = cdp.Execute(ctx, CommandGetEncodedResponse, p, &res) - if err != nil { - return nil, 0, 0, err - } - - // decode - var dec []byte - dec, err = base64.StdEncoding.DecodeString(res.Body) - if err != nil { - return nil, 0, 0, err - } - return dec, res.OriginalSize, res.EncodedSize, nil -} - -// DisableParams disables issues domain, prevents further issues from being -// reported to the client. -type DisableParams struct{} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#method-getEncodedResponse +var GetEncodedResponse = cdp.Command[GetEncodedResponseParams, GetEncodedResponseResult]{Method: CommandGetEncodedResponse} // Disable disables issues domain, prevents further issues from being // reported to the client. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes Audits.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// EnableParams enables issues domain, sends the issues collected so far to -// the client by means of the issueAdded event. -type EnableParams struct{} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} // Enable enables issues domain, sends the issues collected so far to the // client by means of the issueAdded event. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} -// Do executes Audits.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) +// CheckFormsIssuesResult is the result of the command +// Audits.checkFormsIssues. +type CheckFormsIssuesResult struct { + FormIssues []*GenericIssueDetails `json:"formIssues,omitempty,omitzero"` } -// CheckFormsIssuesParams runs the form issues check for the target page. -// Found issues are reported using Audits.issueAdded event. -type CheckFormsIssuesParams struct{} - // CheckFormsIssues runs the form issues check for the target page. Found // issues are reported using Audits.issueAdded event. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#method-checkFormsIssues -func CheckFormsIssues() *CheckFormsIssuesParams { - return &CheckFormsIssuesParams{} -} +var CheckFormsIssues = cdp.Command[cdp.Empty, CheckFormsIssuesResult]{Method: CommandCheckFormsIssues} -// CheckFormsIssuesReturns return values. -type CheckFormsIssuesReturns struct { - FormIssues []*GenericIssueDetails `json:"formIssues,omitempty,omitzero"` -} - -// Do executes Audits.checkFormsIssues against the provided context. -// -// returns: +// IssueAdded [no description]. // -// formIssues -func (p *CheckFormsIssuesParams) Do(ctx context.Context) (formIssues []*GenericIssueDetails, err error) { - // execute - var res CheckFormsIssuesReturns - err = cdp.Execute(ctx, CommandCheckFormsIssues, nil, &res) - if err != nil { - return nil, err - } - - return res.FormIssues, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#event-issueAdded +var IssueAdded = cdp.Event[EventIssueAdded]{Method: "Audits.issueAdded"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/audits/events.go b/vendor/github.com/chromedp/cdproto/audits/events.go index 495b433db..e081d4c84 100644 --- a/vendor/github.com/chromedp/cdproto/audits/events.go +++ b/vendor/github.com/chromedp/cdproto/audits/events.go @@ -1,6 +1,6 @@ -package audits +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package audits // EventIssueAdded [no description]. // diff --git a/vendor/github.com/chromedp/cdproto/audits/types.go b/vendor/github.com/chromedp/cdproto/audits/types.go index 4fed3d17a..d89da22d5 100644 --- a/vendor/github.com/chromedp/cdproto/audits/types.go +++ b/vendor/github.com/chromedp/cdproto/audits/types.go @@ -1,11 +1,8 @@ -package audits +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package audits import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/network" "github.com/chromedp/cdproto/runtime" @@ -49,47 +46,16 @@ func (t CookieExclusionReason) String() string { // CookieExclusionReason values. const ( - CookieExclusionReasonExcludeSameSiteUnspecifiedTreatedAsLax CookieExclusionReason = "ExcludeSameSiteUnspecifiedTreatedAsLax" - CookieExclusionReasonExcludeSameSiteNoneInsecure CookieExclusionReason = "ExcludeSameSiteNoneInsecure" - CookieExclusionReasonExcludeSameSiteLax CookieExclusionReason = "ExcludeSameSiteLax" - CookieExclusionReasonExcludeSameSiteStrict CookieExclusionReason = "ExcludeSameSiteStrict" - CookieExclusionReasonExcludeDomainNonASCII CookieExclusionReason = "ExcludeDomainNonASCII" - CookieExclusionReasonExcludeThirdPartyCookieBlockedInFirstPartySet CookieExclusionReason = "ExcludeThirdPartyCookieBlockedInFirstPartySet" - CookieExclusionReasonExcludeThirdPartyPhaseout CookieExclusionReason = "ExcludeThirdPartyPhaseout" - CookieExclusionReasonExcludePortMismatch CookieExclusionReason = "ExcludePortMismatch" - CookieExclusionReasonExcludeSchemeMismatch CookieExclusionReason = "ExcludeSchemeMismatch" + CookieExclusionReasonExcludeSameSiteUnspecifiedTreatedAsLax CookieExclusionReason = "ExcludeSameSiteUnspecifiedTreatedAsLax" + CookieExclusionReasonExcludeSameSiteNoneInsecure CookieExclusionReason = "ExcludeSameSiteNoneInsecure" + CookieExclusionReasonExcludeSameSiteLax CookieExclusionReason = "ExcludeSameSiteLax" + CookieExclusionReasonExcludeSameSiteStrict CookieExclusionReason = "ExcludeSameSiteStrict" + CookieExclusionReasonExcludeDomainNonASCII CookieExclusionReason = "ExcludeDomainNonASCII" + CookieExclusionReasonExcludeThirdPartyPhaseout CookieExclusionReason = "ExcludeThirdPartyPhaseout" + CookieExclusionReasonExcludePortMismatch CookieExclusionReason = "ExcludePortMismatch" + CookieExclusionReasonExcludeSchemeMismatch CookieExclusionReason = "ExcludeSchemeMismatch" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CookieExclusionReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CookieExclusionReason(s) { - case CookieExclusionReasonExcludeSameSiteUnspecifiedTreatedAsLax: - *t = CookieExclusionReasonExcludeSameSiteUnspecifiedTreatedAsLax - case CookieExclusionReasonExcludeSameSiteNoneInsecure: - *t = CookieExclusionReasonExcludeSameSiteNoneInsecure - case CookieExclusionReasonExcludeSameSiteLax: - *t = CookieExclusionReasonExcludeSameSiteLax - case CookieExclusionReasonExcludeSameSiteStrict: - *t = CookieExclusionReasonExcludeSameSiteStrict - case CookieExclusionReasonExcludeDomainNonASCII: - *t = CookieExclusionReasonExcludeDomainNonASCII - case CookieExclusionReasonExcludeThirdPartyCookieBlockedInFirstPartySet: - *t = CookieExclusionReasonExcludeThirdPartyCookieBlockedInFirstPartySet - case CookieExclusionReasonExcludeThirdPartyPhaseout: - *t = CookieExclusionReasonExcludeThirdPartyPhaseout - case CookieExclusionReasonExcludePortMismatch: - *t = CookieExclusionReasonExcludePortMismatch - case CookieExclusionReasonExcludeSchemeMismatch: - *t = CookieExclusionReasonExcludeSchemeMismatch - default: - return fmt.Errorf("unknown CookieExclusionReason value: %v", s) - } - return nil -} - // CookieWarningReason [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-CookieWarningReason @@ -118,46 +84,6 @@ const ( CookieWarningReasonWarnThirdPartyCookieHeuristic CookieWarningReason = "WarnThirdPartyCookieHeuristic" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CookieWarningReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CookieWarningReason(s) { - case CookieWarningReasonWarnSameSiteUnspecifiedCrossSiteContext: - *t = CookieWarningReasonWarnSameSiteUnspecifiedCrossSiteContext - case CookieWarningReasonWarnSameSiteNoneInsecure: - *t = CookieWarningReasonWarnSameSiteNoneInsecure - case CookieWarningReasonWarnSameSiteUnspecifiedLaxAllowUnsafe: - *t = CookieWarningReasonWarnSameSiteUnspecifiedLaxAllowUnsafe - case CookieWarningReasonWarnSameSiteStrictLaxDowngradeStrict: - *t = CookieWarningReasonWarnSameSiteStrictLaxDowngradeStrict - case CookieWarningReasonWarnSameSiteStrictCrossDowngradeStrict: - *t = CookieWarningReasonWarnSameSiteStrictCrossDowngradeStrict - case CookieWarningReasonWarnSameSiteStrictCrossDowngradeLax: - *t = CookieWarningReasonWarnSameSiteStrictCrossDowngradeLax - case CookieWarningReasonWarnSameSiteLaxCrossDowngradeStrict: - *t = CookieWarningReasonWarnSameSiteLaxCrossDowngradeStrict - case CookieWarningReasonWarnSameSiteLaxCrossDowngradeLax: - *t = CookieWarningReasonWarnSameSiteLaxCrossDowngradeLax - case CookieWarningReasonWarnAttributeValueExceedsMaxSize: - *t = CookieWarningReasonWarnAttributeValueExceedsMaxSize - case CookieWarningReasonWarnDomainNonASCII: - *t = CookieWarningReasonWarnDomainNonASCII - case CookieWarningReasonWarnThirdPartyPhaseout: - *t = CookieWarningReasonWarnThirdPartyPhaseout - case CookieWarningReasonWarnCrossSiteRedirectDowngradeChangesInclusion: - *t = CookieWarningReasonWarnCrossSiteRedirectDowngradeChangesInclusion - case CookieWarningReasonWarnDeprecationTrialMetadata: - *t = CookieWarningReasonWarnDeprecationTrialMetadata - case CookieWarningReasonWarnThirdPartyCookieHeuristic: - *t = CookieWarningReasonWarnThirdPartyCookieHeuristic - default: - return fmt.Errorf("unknown CookieWarningReason value: %v", s) - } - return nil -} - // CookieOperation [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-CookieOperation @@ -174,22 +100,6 @@ const ( CookieOperationReadCookie CookieOperation = "ReadCookie" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CookieOperation) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CookieOperation(s) { - case CookieOperationSetCookie: - *t = CookieOperationSetCookie - case CookieOperationReadCookie: - *t = CookieOperationReadCookie - default: - return fmt.Errorf("unknown CookieOperation value: %v", s) - } - return nil -} - // InsightType represents the category of insight that a cookie issue falls // under. // @@ -208,24 +118,6 @@ const ( InsightTypeHeuristics InsightType = "Heuristics" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *InsightType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch InsightType(s) { - case InsightTypeGitHubResource: - *t = InsightTypeGitHubResource - case InsightTypeGracePeriod: - *t = InsightTypeGracePeriod - case InsightTypeHeuristics: - *t = InsightTypeHeuristics - default: - return fmt.Errorf("unknown InsightType value: %v", s) - } - return nil -} - // CookieIssueInsight information about the suggested solution to a cookie // issue. // @@ -267,20 +159,6 @@ const ( PerformanceIssueTypeDocumentCookie PerformanceIssueType = "DocumentCookie" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *PerformanceIssueType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch PerformanceIssueType(s) { - case PerformanceIssueTypeDocumentCookie: - *t = PerformanceIssueTypeDocumentCookie - default: - return fmt.Errorf("unknown PerformanceIssueType value: %v", s) - } - return nil -} - // PerformanceIssueDetails details for a performance issue. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-PerformanceIssueDetails @@ -306,24 +184,6 @@ const ( MixedContentResolutionStatusMixedContentWarning MixedContentResolutionStatus = "MixedContentWarning" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *MixedContentResolutionStatus) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch MixedContentResolutionStatus(s) { - case MixedContentResolutionStatusMixedContentBlocked: - *t = MixedContentResolutionStatusMixedContentBlocked - case MixedContentResolutionStatusMixedContentAutomaticallyUpgraded: - *t = MixedContentResolutionStatusMixedContentAutomaticallyUpgraded - case MixedContentResolutionStatusMixedContentWarning: - *t = MixedContentResolutionStatusMixedContentWarning - default: - return fmt.Errorf("unknown MixedContentResolutionStatus value: %v", s) - } - return nil -} - // MixedContentResourceType [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-MixedContentResourceType @@ -366,74 +226,6 @@ const ( MixedContentResourceTypeXSLT MixedContentResourceType = "XSLT" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *MixedContentResourceType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch MixedContentResourceType(s) { - case MixedContentResourceTypeAudio: - *t = MixedContentResourceTypeAudio - case MixedContentResourceTypeBeacon: - *t = MixedContentResourceTypeBeacon - case MixedContentResourceTypeCSPReport: - *t = MixedContentResourceTypeCSPReport - case MixedContentResourceTypeDownload: - *t = MixedContentResourceTypeDownload - case MixedContentResourceTypeEventSource: - *t = MixedContentResourceTypeEventSource - case MixedContentResourceTypeFavicon: - *t = MixedContentResourceTypeFavicon - case MixedContentResourceTypeFont: - *t = MixedContentResourceTypeFont - case MixedContentResourceTypeForm: - *t = MixedContentResourceTypeForm - case MixedContentResourceTypeFrame: - *t = MixedContentResourceTypeFrame - case MixedContentResourceTypeImage: - *t = MixedContentResourceTypeImage - case MixedContentResourceTypeImport: - *t = MixedContentResourceTypeImport - case MixedContentResourceTypeJSON: - *t = MixedContentResourceTypeJSON - case MixedContentResourceTypeManifest: - *t = MixedContentResourceTypeManifest - case MixedContentResourceTypePing: - *t = MixedContentResourceTypePing - case MixedContentResourceTypePluginData: - *t = MixedContentResourceTypePluginData - case MixedContentResourceTypePluginResource: - *t = MixedContentResourceTypePluginResource - case MixedContentResourceTypePrefetch: - *t = MixedContentResourceTypePrefetch - case MixedContentResourceTypeResource: - *t = MixedContentResourceTypeResource - case MixedContentResourceTypeScript: - *t = MixedContentResourceTypeScript - case MixedContentResourceTypeServiceWorker: - *t = MixedContentResourceTypeServiceWorker - case MixedContentResourceTypeSharedWorker: - *t = MixedContentResourceTypeSharedWorker - case MixedContentResourceTypeSpeculationRules: - *t = MixedContentResourceTypeSpeculationRules - case MixedContentResourceTypeStylesheet: - *t = MixedContentResourceTypeStylesheet - case MixedContentResourceTypeTrack: - *t = MixedContentResourceTypeTrack - case MixedContentResourceTypeVideo: - *t = MixedContentResourceTypeVideo - case MixedContentResourceTypeWorker: - *t = MixedContentResourceTypeWorker - case MixedContentResourceTypeXMLHTTPRequest: - *t = MixedContentResourceTypeXMLHTTPRequest - case MixedContentResourceTypeXSLT: - *t = MixedContentResourceTypeXSLT - default: - return fmt.Errorf("unknown MixedContentResourceType value: %v", s) - } - return nil -} - // MixedContentIssueDetails [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-MixedContentIssueDetails @@ -469,34 +261,6 @@ const ( BlockedByResponseReasonSRIMessageSignatureMismatch BlockedByResponseReason = "SRIMessageSignatureMismatch" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *BlockedByResponseReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch BlockedByResponseReason(s) { - case BlockedByResponseReasonCoepFrameResourceNeedsCoepHeader: - *t = BlockedByResponseReasonCoepFrameResourceNeedsCoepHeader - case BlockedByResponseReasonCoopSandboxedIFrameCannotNavigateToCoopPage: - *t = BlockedByResponseReasonCoopSandboxedIFrameCannotNavigateToCoopPage - case BlockedByResponseReasonCorpNotSameOrigin: - *t = BlockedByResponseReasonCorpNotSameOrigin - case BlockedByResponseReasonCorpNotSameOriginAfterDefaultedToSameOriginByCoep: - *t = BlockedByResponseReasonCorpNotSameOriginAfterDefaultedToSameOriginByCoep - case BlockedByResponseReasonCorpNotSameOriginAfterDefaultedToSameOriginByDip: - *t = BlockedByResponseReasonCorpNotSameOriginAfterDefaultedToSameOriginByDip - case BlockedByResponseReasonCorpNotSameOriginAfterDefaultedToSameOriginByCoepAndDip: - *t = BlockedByResponseReasonCorpNotSameOriginAfterDefaultedToSameOriginByCoepAndDip - case BlockedByResponseReasonCorpNotSameSite: - *t = BlockedByResponseReasonCorpNotSameSite - case BlockedByResponseReasonSRIMessageSignatureMismatch: - *t = BlockedByResponseReasonSRIMessageSignatureMismatch - default: - return fmt.Errorf("unknown BlockedByResponseReason value: %v", s) - } - return nil -} - // BlockedByResponseIssueDetails details for a request that has been blocked // with the BLOCKED_BY_RESPONSE code. Currently only used for COEP/COOP, but may // be extended to include some CSP errors in the future. @@ -525,22 +289,6 @@ const ( HeavyAdResolutionStatusHeavyAdWarning HeavyAdResolutionStatus = "HeavyAdWarning" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *HeavyAdResolutionStatus) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch HeavyAdResolutionStatus(s) { - case HeavyAdResolutionStatusHeavyAdBlocked: - *t = HeavyAdResolutionStatusHeavyAdBlocked - case HeavyAdResolutionStatusHeavyAdWarning: - *t = HeavyAdResolutionStatusHeavyAdWarning - default: - return fmt.Errorf("unknown HeavyAdResolutionStatus value: %v", s) - } - return nil -} - // HeavyAdReason [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-HeavyAdReason @@ -558,24 +306,6 @@ const ( HeavyAdReasonCPUPeakLimit HeavyAdReason = "CpuPeakLimit" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *HeavyAdReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch HeavyAdReason(s) { - case HeavyAdReasonNetworkTotalLimit: - *t = HeavyAdReasonNetworkTotalLimit - case HeavyAdReasonCPUTotalLimit: - *t = HeavyAdReasonCPUTotalLimit - case HeavyAdReasonCPUPeakLimit: - *t = HeavyAdReasonCPUPeakLimit - default: - return fmt.Errorf("unknown HeavyAdReason value: %v", s) - } - return nil -} - // HeavyAdIssueDetails [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-HeavyAdIssueDetails @@ -606,32 +336,6 @@ const ( ContentSecurityPolicyViolationTypeKWasmEvalViolation ContentSecurityPolicyViolationType = "kWasmEvalViolation" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ContentSecurityPolicyViolationType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ContentSecurityPolicyViolationType(s) { - case ContentSecurityPolicyViolationTypeKInlineViolation: - *t = ContentSecurityPolicyViolationTypeKInlineViolation - case ContentSecurityPolicyViolationTypeKEvalViolation: - *t = ContentSecurityPolicyViolationTypeKEvalViolation - case ContentSecurityPolicyViolationTypeKURLViolation: - *t = ContentSecurityPolicyViolationTypeKURLViolation - case ContentSecurityPolicyViolationTypeKSRIViolation: - *t = ContentSecurityPolicyViolationTypeKSRIViolation - case ContentSecurityPolicyViolationTypeKTrustedTypesSinkViolation: - *t = ContentSecurityPolicyViolationTypeKTrustedTypesSinkViolation - case ContentSecurityPolicyViolationTypeKTrustedTypesPolicyViolation: - *t = ContentSecurityPolicyViolationTypeKTrustedTypesPolicyViolation - case ContentSecurityPolicyViolationTypeKWasmEvalViolation: - *t = ContentSecurityPolicyViolationTypeKWasmEvalViolation - default: - return fmt.Errorf("unknown ContentSecurityPolicyViolationType value: %v", s) - } - return nil -} - // SourceCodeLocation [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-SourceCodeLocation @@ -671,22 +375,6 @@ const ( SharedArrayBufferIssueTypeCreationIssue SharedArrayBufferIssueType = "CreationIssue" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SharedArrayBufferIssueType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SharedArrayBufferIssueType(s) { - case SharedArrayBufferIssueTypeTransferIssue: - *t = SharedArrayBufferIssueTypeTransferIssue - case SharedArrayBufferIssueTypeCreationIssue: - *t = SharedArrayBufferIssueTypeCreationIssue - default: - return fmt.Errorf("unknown SharedArrayBufferIssueType value: %v", s) - } - return nil -} - // SharedArrayBufferIssueDetails details for a issue arising from an SAB // being instantiated in, or transferred to a context that is not cross-origin // isolated. @@ -752,70 +440,6 @@ const ( SharedDictionaryErrorWriteErrorUnsupportedType SharedDictionaryError = "WriteErrorUnsupportedType" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SharedDictionaryError) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SharedDictionaryError(s) { - case SharedDictionaryErrorUseErrorCrossOriginNoCorsRequest: - *t = SharedDictionaryErrorUseErrorCrossOriginNoCorsRequest - case SharedDictionaryErrorUseErrorDictionaryLoadFailure: - *t = SharedDictionaryErrorUseErrorDictionaryLoadFailure - case SharedDictionaryErrorUseErrorMatchingDictionaryNotUsed: - *t = SharedDictionaryErrorUseErrorMatchingDictionaryNotUsed - case SharedDictionaryErrorUseErrorUnexpectedContentDictionaryHeader: - *t = SharedDictionaryErrorUseErrorUnexpectedContentDictionaryHeader - case SharedDictionaryErrorWriteErrorCossOriginNoCorsRequest: - *t = SharedDictionaryErrorWriteErrorCossOriginNoCorsRequest - case SharedDictionaryErrorWriteErrorDisallowedBySettings: - *t = SharedDictionaryErrorWriteErrorDisallowedBySettings - case SharedDictionaryErrorWriteErrorExpiredResponse: - *t = SharedDictionaryErrorWriteErrorExpiredResponse - case SharedDictionaryErrorWriteErrorFeatureDisabled: - *t = SharedDictionaryErrorWriteErrorFeatureDisabled - case SharedDictionaryErrorWriteErrorInsufficientResources: - *t = SharedDictionaryErrorWriteErrorInsufficientResources - case SharedDictionaryErrorWriteErrorInvalidMatchField: - *t = SharedDictionaryErrorWriteErrorInvalidMatchField - case SharedDictionaryErrorWriteErrorInvalidStructuredHeader: - *t = SharedDictionaryErrorWriteErrorInvalidStructuredHeader - case SharedDictionaryErrorWriteErrorInvalidTTLField: - *t = SharedDictionaryErrorWriteErrorInvalidTTLField - case SharedDictionaryErrorWriteErrorNavigationRequest: - *t = SharedDictionaryErrorWriteErrorNavigationRequest - case SharedDictionaryErrorWriteErrorNoMatchField: - *t = SharedDictionaryErrorWriteErrorNoMatchField - case SharedDictionaryErrorWriteErrorNonIntegerTTLField: - *t = SharedDictionaryErrorWriteErrorNonIntegerTTLField - case SharedDictionaryErrorWriteErrorNonListMatchDestField: - *t = SharedDictionaryErrorWriteErrorNonListMatchDestField - case SharedDictionaryErrorWriteErrorNonSecureContext: - *t = SharedDictionaryErrorWriteErrorNonSecureContext - case SharedDictionaryErrorWriteErrorNonStringIDField: - *t = SharedDictionaryErrorWriteErrorNonStringIDField - case SharedDictionaryErrorWriteErrorNonStringInMatchDestList: - *t = SharedDictionaryErrorWriteErrorNonStringInMatchDestList - case SharedDictionaryErrorWriteErrorInvalidMatchDestList: - *t = SharedDictionaryErrorWriteErrorInvalidMatchDestList - case SharedDictionaryErrorWriteErrorNonStringMatchField: - *t = SharedDictionaryErrorWriteErrorNonStringMatchField - case SharedDictionaryErrorWriteErrorNonTokenTypeField: - *t = SharedDictionaryErrorWriteErrorNonTokenTypeField - case SharedDictionaryErrorWriteErrorRequestAborted: - *t = SharedDictionaryErrorWriteErrorRequestAborted - case SharedDictionaryErrorWriteErrorShuttingDown: - *t = SharedDictionaryErrorWriteErrorShuttingDown - case SharedDictionaryErrorWriteErrorTooLongIDField: - *t = SharedDictionaryErrorWriteErrorTooLongIDField - case SharedDictionaryErrorWriteErrorUnsupportedType: - *t = SharedDictionaryErrorWriteErrorUnsupportedType - default: - return fmt.Errorf("unknown SharedDictionaryError value: %v", s) - } - return nil -} - // SRIMessageSignatureError [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-SRIMessageSignatureError @@ -855,68 +479,6 @@ const ( SRIMessageSignatureErrorSignatureBaseUnsupportedComponent SRIMessageSignatureError = "SignatureBaseUnsupportedComponent" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SRIMessageSignatureError) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SRIMessageSignatureError(s) { - case SRIMessageSignatureErrorMissingSignatureHeader: - *t = SRIMessageSignatureErrorMissingSignatureHeader - case SRIMessageSignatureErrorMissingSignatureInputHeader: - *t = SRIMessageSignatureErrorMissingSignatureInputHeader - case SRIMessageSignatureErrorInvalidSignatureHeader: - *t = SRIMessageSignatureErrorInvalidSignatureHeader - case SRIMessageSignatureErrorInvalidSignatureInputHeader: - *t = SRIMessageSignatureErrorInvalidSignatureInputHeader - case SRIMessageSignatureErrorSignatureHeaderValueIsNotByteSequence: - *t = SRIMessageSignatureErrorSignatureHeaderValueIsNotByteSequence - case SRIMessageSignatureErrorSignatureHeaderValueIsParameterized: - *t = SRIMessageSignatureErrorSignatureHeaderValueIsParameterized - case SRIMessageSignatureErrorSignatureHeaderValueIsIncorrectLength: - *t = SRIMessageSignatureErrorSignatureHeaderValueIsIncorrectLength - case SRIMessageSignatureErrorSignatureInputHeaderMissingLabel: - *t = SRIMessageSignatureErrorSignatureInputHeaderMissingLabel - case SRIMessageSignatureErrorSignatureInputHeaderValueNotInnerList: - *t = SRIMessageSignatureErrorSignatureInputHeaderValueNotInnerList - case SRIMessageSignatureErrorSignatureInputHeaderValueMissingComponents: - *t = SRIMessageSignatureErrorSignatureInputHeaderValueMissingComponents - case SRIMessageSignatureErrorSignatureInputHeaderInvalidComponentType: - *t = SRIMessageSignatureErrorSignatureInputHeaderInvalidComponentType - case SRIMessageSignatureErrorSignatureInputHeaderInvalidComponentName: - *t = SRIMessageSignatureErrorSignatureInputHeaderInvalidComponentName - case SRIMessageSignatureErrorSignatureInputHeaderInvalidHeaderComponentParameter: - *t = SRIMessageSignatureErrorSignatureInputHeaderInvalidHeaderComponentParameter - case SRIMessageSignatureErrorSignatureInputHeaderInvalidDerivedComponentParameter: - *t = SRIMessageSignatureErrorSignatureInputHeaderInvalidDerivedComponentParameter - case SRIMessageSignatureErrorSignatureInputHeaderKeyIDLength: - *t = SRIMessageSignatureErrorSignatureInputHeaderKeyIDLength - case SRIMessageSignatureErrorSignatureInputHeaderInvalidParameter: - *t = SRIMessageSignatureErrorSignatureInputHeaderInvalidParameter - case SRIMessageSignatureErrorSignatureInputHeaderMissingRequiredParameters: - *t = SRIMessageSignatureErrorSignatureInputHeaderMissingRequiredParameters - case SRIMessageSignatureErrorValidationFailedSignatureExpired: - *t = SRIMessageSignatureErrorValidationFailedSignatureExpired - case SRIMessageSignatureErrorValidationFailedInvalidLength: - *t = SRIMessageSignatureErrorValidationFailedInvalidLength - case SRIMessageSignatureErrorValidationFailedSignatureMismatch: - *t = SRIMessageSignatureErrorValidationFailedSignatureMismatch - case SRIMessageSignatureErrorValidationFailedIntegrityMismatch: - *t = SRIMessageSignatureErrorValidationFailedIntegrityMismatch - case SRIMessageSignatureErrorSignatureBaseUnknownDerivedComponent: - *t = SRIMessageSignatureErrorSignatureBaseUnknownDerivedComponent - case SRIMessageSignatureErrorSignatureBaseMissingHeader: - *t = SRIMessageSignatureErrorSignatureBaseMissingHeader - case SRIMessageSignatureErrorSignatureBaseInvalidUnencodedDigest: - *t = SRIMessageSignatureErrorSignatureBaseInvalidUnencodedDigest - case SRIMessageSignatureErrorSignatureBaseUnsupportedComponent: - *t = SRIMessageSignatureErrorSignatureBaseUnsupportedComponent - default: - return fmt.Errorf("unknown SRIMessageSignatureError value: %v", s) - } - return nil -} - // UnencodedDigestError [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-UnencodedDigestError @@ -935,26 +497,6 @@ const ( UnencodedDigestErrorIncorrectDigestLength UnencodedDigestError = "IncorrectDigestLength" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *UnencodedDigestError) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch UnencodedDigestError(s) { - case UnencodedDigestErrorMalformedDictionary: - *t = UnencodedDigestErrorMalformedDictionary - case UnencodedDigestErrorUnknownAlgorithm: - *t = UnencodedDigestErrorUnknownAlgorithm - case UnencodedDigestErrorIncorrectDigestType: - *t = UnencodedDigestErrorIncorrectDigestType - case UnencodedDigestErrorIncorrectDigestLength: - *t = UnencodedDigestErrorIncorrectDigestLength - default: - return fmt.Errorf("unknown UnencodedDigestError value: %v", s) - } - return nil -} - // ConnectionAllowlistError [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-ConnectionAllowlistError @@ -967,38 +509,17 @@ func (t ConnectionAllowlistError) String() string { // ConnectionAllowlistError values. const ( - ConnectionAllowlistErrorInvalidHeader ConnectionAllowlistError = "InvalidHeader" - ConnectionAllowlistErrorMoreThanOneList ConnectionAllowlistError = "MoreThanOneList" - ConnectionAllowlistErrorItemNotInnerList ConnectionAllowlistError = "ItemNotInnerList" - ConnectionAllowlistErrorInvalidAllowlistItemType ConnectionAllowlistError = "InvalidAllowlistItemType" - ConnectionAllowlistErrorReportingEndpointNotToken ConnectionAllowlistError = "ReportingEndpointNotToken" - ConnectionAllowlistErrorInvalidURLPattern ConnectionAllowlistError = "InvalidUrlPattern" + ConnectionAllowlistErrorInvalidHeader ConnectionAllowlistError = "InvalidHeader" + ConnectionAllowlistErrorMoreThanOneList ConnectionAllowlistError = "MoreThanOneList" + ConnectionAllowlistErrorItemNotInnerList ConnectionAllowlistError = "ItemNotInnerList" + ConnectionAllowlistErrorInvalidAllowlistItemType ConnectionAllowlistError = "InvalidAllowlistItemType" + ConnectionAllowlistErrorReportingEndpointNotToken ConnectionAllowlistError = "ReportingEndpointNotToken" + ConnectionAllowlistErrorInvalidURLPattern ConnectionAllowlistError = "InvalidUrlPattern" + ConnectionAllowlistErrorIFrameAttributeLoosensEmbeddingRequirement ConnectionAllowlistError = "IFrameAttributeLoosensEmbeddingRequirement" + ConnectionAllowlistErrorInvalidAllowConnectionAllowlistFrom ConnectionAllowlistError = "InvalidAllowConnectionAllowlistFrom" + ConnectionAllowlistErrorEmbeddingRequirementNotSatisfied ConnectionAllowlistError = "EmbeddingRequirementNotSatisfied" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ConnectionAllowlistError) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ConnectionAllowlistError(s) { - case ConnectionAllowlistErrorInvalidHeader: - *t = ConnectionAllowlistErrorInvalidHeader - case ConnectionAllowlistErrorMoreThanOneList: - *t = ConnectionAllowlistErrorMoreThanOneList - case ConnectionAllowlistErrorItemNotInnerList: - *t = ConnectionAllowlistErrorItemNotInnerList - case ConnectionAllowlistErrorInvalidAllowlistItemType: - *t = ConnectionAllowlistErrorInvalidAllowlistItemType - case ConnectionAllowlistErrorReportingEndpointNotToken: - *t = ConnectionAllowlistErrorReportingEndpointNotToken - case ConnectionAllowlistErrorInvalidURLPattern: - *t = ConnectionAllowlistErrorInvalidURLPattern - default: - return fmt.Errorf("unknown ConnectionAllowlistError value: %v", s) - } - return nil -} - // QuirksModeIssueDetails details for issues about documents in Quirks Mode // or Limited Quirks Mode that affects page layouting. // @@ -1078,62 +599,9 @@ const ( GenericIssueErrorTypeFormModelContextMissingToolDescription GenericIssueErrorType = "FormModelContextMissingToolDescription" GenericIssueErrorTypeFormModelContextRequiredParameterMissingName GenericIssueErrorType = "FormModelContextRequiredParameterMissingName" GenericIssueErrorTypeFormModelContextParameterMissingName GenericIssueErrorType = "FormModelContextParameterMissingName" + GenericIssueErrorTypeGeolocationPromptWithoutUserGesture GenericIssueErrorType = "GeolocationPromptWithoutUserGesture" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *GenericIssueErrorType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch GenericIssueErrorType(s) { - case GenericIssueErrorTypeFormLabelForNameError: - *t = GenericIssueErrorTypeFormLabelForNameError - case GenericIssueErrorTypeFormDuplicateIDForInputError: - *t = GenericIssueErrorTypeFormDuplicateIDForInputError - case GenericIssueErrorTypeFormInputWithNoLabelError: - *t = GenericIssueErrorTypeFormInputWithNoLabelError - case GenericIssueErrorTypeFormAutocompleteAttributeEmptyError: - *t = GenericIssueErrorTypeFormAutocompleteAttributeEmptyError - case GenericIssueErrorTypeFormEmptyIDAndNameAttributesForInputError: - *t = GenericIssueErrorTypeFormEmptyIDAndNameAttributesForInputError - case GenericIssueErrorTypeFormAriaLabelledByToNonExistingIDError: - *t = GenericIssueErrorTypeFormAriaLabelledByToNonExistingIDError - case GenericIssueErrorTypeFormInputAssignedAutocompleteValueToIDOrNameAttributeError: - *t = GenericIssueErrorTypeFormInputAssignedAutocompleteValueToIDOrNameAttributeError - case GenericIssueErrorTypeFormLabelHasNeitherForNorNestedInputError: - *t = GenericIssueErrorTypeFormLabelHasNeitherForNorNestedInputError - case GenericIssueErrorTypeFormLabelForMatchesNonExistingIDError: - *t = GenericIssueErrorTypeFormLabelForMatchesNonExistingIDError - case GenericIssueErrorTypeFormInputHasWrongButWellIntendedAutocompleteValueError: - *t = GenericIssueErrorTypeFormInputHasWrongButWellIntendedAutocompleteValueError - case GenericIssueErrorTypeResponseWasBlockedByORB: - *t = GenericIssueErrorTypeResponseWasBlockedByORB - case GenericIssueErrorTypeNavigationEntryMarkedSkippable: - *t = GenericIssueErrorTypeNavigationEntryMarkedSkippable - case GenericIssueErrorTypeBackUINavigationWouldSkipAd: - *t = GenericIssueErrorTypeBackUINavigationWouldSkipAd - case GenericIssueErrorTypeAutofillAndManualTextPolicyControlledFeaturesInfo: - *t = GenericIssueErrorTypeAutofillAndManualTextPolicyControlledFeaturesInfo - case GenericIssueErrorTypeAutofillPolicyControlledFeatureInfo: - *t = GenericIssueErrorTypeAutofillPolicyControlledFeatureInfo - case GenericIssueErrorTypeManualTextPolicyControlledFeatureInfo: - *t = GenericIssueErrorTypeManualTextPolicyControlledFeatureInfo - case GenericIssueErrorTypeFormModelContextParameterMissingTitleAndDescription: - *t = GenericIssueErrorTypeFormModelContextParameterMissingTitleAndDescription - case GenericIssueErrorTypeFormModelContextMissingToolName: - *t = GenericIssueErrorTypeFormModelContextMissingToolName - case GenericIssueErrorTypeFormModelContextMissingToolDescription: - *t = GenericIssueErrorTypeFormModelContextMissingToolDescription - case GenericIssueErrorTypeFormModelContextRequiredParameterMissingName: - *t = GenericIssueErrorTypeFormModelContextRequiredParameterMissingName - case GenericIssueErrorTypeFormModelContextParameterMissingName: - *t = GenericIssueErrorTypeFormModelContextParameterMissingName - default: - return fmt.Errorf("unknown GenericIssueErrorType value: %v", s) - } - return nil -} - // GenericIssueDetails depending on the concrete errorType, different // properties are set. // @@ -1199,22 +667,6 @@ const ( ClientHintIssueReasonMetaTagModifiedHTML ClientHintIssueReason = "MetaTagModifiedHTML" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ClientHintIssueReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ClientHintIssueReason(s) { - case ClientHintIssueReasonMetaTagAllowListInvalidOrigin: - *t = ClientHintIssueReasonMetaTagAllowListInvalidOrigin - case ClientHintIssueReasonMetaTagModifiedHTML: - *t = ClientHintIssueReasonMetaTagModifiedHTML - default: - return fmt.Errorf("unknown ClientHintIssueReason value: %v", s) - } - return nil -} - // FederatedAuthRequestIssueDetails [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-FederatedAuthRequestIssueDetails @@ -1238,146 +690,55 @@ func (t FederatedAuthRequestIssueReason) String() string { // FederatedAuthRequestIssueReason values. const ( - FederatedAuthRequestIssueReasonShouldEmbargo FederatedAuthRequestIssueReason = "ShouldEmbargo" - FederatedAuthRequestIssueReasonTooManyRequests FederatedAuthRequestIssueReason = "TooManyRequests" - FederatedAuthRequestIssueReasonWellKnownHTTPNotFound FederatedAuthRequestIssueReason = "WellKnownHttpNotFound" - FederatedAuthRequestIssueReasonWellKnownNoResponse FederatedAuthRequestIssueReason = "WellKnownNoResponse" - FederatedAuthRequestIssueReasonWellKnownInvalidResponse FederatedAuthRequestIssueReason = "WellKnownInvalidResponse" - FederatedAuthRequestIssueReasonWellKnownListEmpty FederatedAuthRequestIssueReason = "WellKnownListEmpty" - FederatedAuthRequestIssueReasonWellKnownInvalidContentType FederatedAuthRequestIssueReason = "WellKnownInvalidContentType" - FederatedAuthRequestIssueReasonConfigNotInWellKnown FederatedAuthRequestIssueReason = "ConfigNotInWellKnown" - FederatedAuthRequestIssueReasonWellKnownTooBig FederatedAuthRequestIssueReason = "WellKnownTooBig" - FederatedAuthRequestIssueReasonConfigHTTPNotFound FederatedAuthRequestIssueReason = "ConfigHttpNotFound" - FederatedAuthRequestIssueReasonConfigNoResponse FederatedAuthRequestIssueReason = "ConfigNoResponse" - FederatedAuthRequestIssueReasonConfigInvalidResponse FederatedAuthRequestIssueReason = "ConfigInvalidResponse" - FederatedAuthRequestIssueReasonConfigInvalidContentType FederatedAuthRequestIssueReason = "ConfigInvalidContentType" - FederatedAuthRequestIssueReasonIdpNotPotentiallyTrustworthy FederatedAuthRequestIssueReason = "IdpNotPotentiallyTrustworthy" - FederatedAuthRequestIssueReasonDisabledInSettings FederatedAuthRequestIssueReason = "DisabledInSettings" - FederatedAuthRequestIssueReasonDisabledInFlags FederatedAuthRequestIssueReason = "DisabledInFlags" - FederatedAuthRequestIssueReasonErrorFetchingSignin FederatedAuthRequestIssueReason = "ErrorFetchingSignin" - FederatedAuthRequestIssueReasonInvalidSigninResponse FederatedAuthRequestIssueReason = "InvalidSigninResponse" - FederatedAuthRequestIssueReasonAccountsHTTPNotFound FederatedAuthRequestIssueReason = "AccountsHttpNotFound" - FederatedAuthRequestIssueReasonAccountsNoResponse FederatedAuthRequestIssueReason = "AccountsNoResponse" - FederatedAuthRequestIssueReasonAccountsInvalidResponse FederatedAuthRequestIssueReason = "AccountsInvalidResponse" - FederatedAuthRequestIssueReasonAccountsListEmpty FederatedAuthRequestIssueReason = "AccountsListEmpty" - FederatedAuthRequestIssueReasonAccountsInvalidContentType FederatedAuthRequestIssueReason = "AccountsInvalidContentType" - FederatedAuthRequestIssueReasonIDTokenHTTPNotFound FederatedAuthRequestIssueReason = "IdTokenHttpNotFound" - FederatedAuthRequestIssueReasonIDTokenNoResponse FederatedAuthRequestIssueReason = "IdTokenNoResponse" - FederatedAuthRequestIssueReasonIDTokenInvalidResponse FederatedAuthRequestIssueReason = "IdTokenInvalidResponse" - FederatedAuthRequestIssueReasonIDTokenIdpErrorResponse FederatedAuthRequestIssueReason = "IdTokenIdpErrorResponse" - FederatedAuthRequestIssueReasonIDTokenCrossSiteIdpErrorResponse FederatedAuthRequestIssueReason = "IdTokenCrossSiteIdpErrorResponse" - FederatedAuthRequestIssueReasonIDTokenInvalidRequest FederatedAuthRequestIssueReason = "IdTokenInvalidRequest" - FederatedAuthRequestIssueReasonIDTokenInvalidContentType FederatedAuthRequestIssueReason = "IdTokenInvalidContentType" - FederatedAuthRequestIssueReasonErrorIDToken FederatedAuthRequestIssueReason = "ErrorIdToken" - FederatedAuthRequestIssueReasonCanceled FederatedAuthRequestIssueReason = "Canceled" - FederatedAuthRequestIssueReasonRpPageNotVisible FederatedAuthRequestIssueReason = "RpPageNotVisible" - FederatedAuthRequestIssueReasonSilentMediationFailure FederatedAuthRequestIssueReason = "SilentMediationFailure" - FederatedAuthRequestIssueReasonNotSignedInWithIdp FederatedAuthRequestIssueReason = "NotSignedInWithIdp" - FederatedAuthRequestIssueReasonMissingTransientUserActivation FederatedAuthRequestIssueReason = "MissingTransientUserActivation" - FederatedAuthRequestIssueReasonReplacedByActiveMode FederatedAuthRequestIssueReason = "ReplacedByActiveMode" - FederatedAuthRequestIssueReasonRelyingPartyOriginIsOpaque FederatedAuthRequestIssueReason = "RelyingPartyOriginIsOpaque" - FederatedAuthRequestIssueReasonTypeNotMatching FederatedAuthRequestIssueReason = "TypeNotMatching" - FederatedAuthRequestIssueReasonUIDismissedNoEmbargo FederatedAuthRequestIssueReason = "UiDismissedNoEmbargo" - FederatedAuthRequestIssueReasonCorsError FederatedAuthRequestIssueReason = "CorsError" - FederatedAuthRequestIssueReasonSuppressedBySegmentationPlatform FederatedAuthRequestIssueReason = "SuppressedBySegmentationPlatform" + FederatedAuthRequestIssueReasonShouldEmbargo FederatedAuthRequestIssueReason = "ShouldEmbargo" + FederatedAuthRequestIssueReasonTooManyRequests FederatedAuthRequestIssueReason = "TooManyRequests" + FederatedAuthRequestIssueReasonWellKnownHTTPNotFound FederatedAuthRequestIssueReason = "WellKnownHttpNotFound" + FederatedAuthRequestIssueReasonWellKnownNoResponse FederatedAuthRequestIssueReason = "WellKnownNoResponse" + FederatedAuthRequestIssueReasonWellKnownBlockedByConnectionAllowlist FederatedAuthRequestIssueReason = "WellKnownBlockedByConnectionAllowlist" + FederatedAuthRequestIssueReasonWellKnownInvalidResponse FederatedAuthRequestIssueReason = "WellKnownInvalidResponse" + FederatedAuthRequestIssueReasonWellKnownListEmpty FederatedAuthRequestIssueReason = "WellKnownListEmpty" + FederatedAuthRequestIssueReasonWellKnownInvalidContentType FederatedAuthRequestIssueReason = "WellKnownInvalidContentType" + FederatedAuthRequestIssueReasonConfigNotInWellKnown FederatedAuthRequestIssueReason = "ConfigNotInWellKnown" + FederatedAuthRequestIssueReasonWellKnownTooBig FederatedAuthRequestIssueReason = "WellKnownTooBig" + FederatedAuthRequestIssueReasonConfigHTTPNotFound FederatedAuthRequestIssueReason = "ConfigHttpNotFound" + FederatedAuthRequestIssueReasonConfigNoResponse FederatedAuthRequestIssueReason = "ConfigNoResponse" + FederatedAuthRequestIssueReasonConfigBlockedByConnectionAllowlist FederatedAuthRequestIssueReason = "ConfigBlockedByConnectionAllowlist" + FederatedAuthRequestIssueReasonConfigInvalidResponse FederatedAuthRequestIssueReason = "ConfigInvalidResponse" + FederatedAuthRequestIssueReasonConfigInvalidContentType FederatedAuthRequestIssueReason = "ConfigInvalidContentType" + FederatedAuthRequestIssueReasonIdpNotPotentiallyTrustworthy FederatedAuthRequestIssueReason = "IdpNotPotentiallyTrustworthy" + FederatedAuthRequestIssueReasonDisabledInSettings FederatedAuthRequestIssueReason = "DisabledInSettings" + FederatedAuthRequestIssueReasonDisabledInFlags FederatedAuthRequestIssueReason = "DisabledInFlags" + FederatedAuthRequestIssueReasonErrorFetchingSignin FederatedAuthRequestIssueReason = "ErrorFetchingSignin" + FederatedAuthRequestIssueReasonInvalidSigninResponse FederatedAuthRequestIssueReason = "InvalidSigninResponse" + FederatedAuthRequestIssueReasonAccountsHTTPNotFound FederatedAuthRequestIssueReason = "AccountsHttpNotFound" + FederatedAuthRequestIssueReasonAccountsNoResponse FederatedAuthRequestIssueReason = "AccountsNoResponse" + FederatedAuthRequestIssueReasonAccountsBlockedByConnectionAllowlist FederatedAuthRequestIssueReason = "AccountsBlockedByConnectionAllowlist" + FederatedAuthRequestIssueReasonAccountsInvalidResponse FederatedAuthRequestIssueReason = "AccountsInvalidResponse" + FederatedAuthRequestIssueReasonAccountsListEmpty FederatedAuthRequestIssueReason = "AccountsListEmpty" + FederatedAuthRequestIssueReasonAccountsInvalidContentType FederatedAuthRequestIssueReason = "AccountsInvalidContentType" + FederatedAuthRequestIssueReasonIDTokenHTTPNotFound FederatedAuthRequestIssueReason = "IdTokenHttpNotFound" + FederatedAuthRequestIssueReasonIDTokenNoResponse FederatedAuthRequestIssueReason = "IdTokenNoResponse" + FederatedAuthRequestIssueReasonIDTokenBlockedByConnectionAllowlist FederatedAuthRequestIssueReason = "IdTokenBlockedByConnectionAllowlist" + FederatedAuthRequestIssueReasonIDTokenInvalidResponse FederatedAuthRequestIssueReason = "IdTokenInvalidResponse" + FederatedAuthRequestIssueReasonIDTokenIdpErrorResponse FederatedAuthRequestIssueReason = "IdTokenIdpErrorResponse" + FederatedAuthRequestIssueReasonIDTokenCrossSiteIdpErrorResponse FederatedAuthRequestIssueReason = "IdTokenCrossSiteIdpErrorResponse" + FederatedAuthRequestIssueReasonIDTokenInvalidRequest FederatedAuthRequestIssueReason = "IdTokenInvalidRequest" + FederatedAuthRequestIssueReasonIDTokenInvalidContentType FederatedAuthRequestIssueReason = "IdTokenInvalidContentType" + FederatedAuthRequestIssueReasonErrorIDToken FederatedAuthRequestIssueReason = "ErrorIdToken" + FederatedAuthRequestIssueReasonCanceled FederatedAuthRequestIssueReason = "Canceled" + FederatedAuthRequestIssueReasonRpPageNotVisible FederatedAuthRequestIssueReason = "RpPageNotVisible" + FederatedAuthRequestIssueReasonSilentMediationFailure FederatedAuthRequestIssueReason = "SilentMediationFailure" + FederatedAuthRequestIssueReasonNotSignedInWithIdp FederatedAuthRequestIssueReason = "NotSignedInWithIdp" + FederatedAuthRequestIssueReasonMissingTransientUserActivation FederatedAuthRequestIssueReason = "MissingTransientUserActivation" + FederatedAuthRequestIssueReasonReplacedByActiveMode FederatedAuthRequestIssueReason = "ReplacedByActiveMode" + FederatedAuthRequestIssueReasonRelyingPartyOriginIsOpaque FederatedAuthRequestIssueReason = "RelyingPartyOriginIsOpaque" + FederatedAuthRequestIssueReasonTypeNotMatching FederatedAuthRequestIssueReason = "TypeNotMatching" + FederatedAuthRequestIssueReasonUIDismissedNoEmbargo FederatedAuthRequestIssueReason = "UiDismissedNoEmbargo" + FederatedAuthRequestIssueReasonCorsError FederatedAuthRequestIssueReason = "CorsError" + FederatedAuthRequestIssueReasonSuppressedBySegmentationPlatform FederatedAuthRequestIssueReason = "SuppressedBySegmentationPlatform" + FederatedAuthRequestIssueReasonPopupBlockedByConnectionAllowlist FederatedAuthRequestIssueReason = "PopupBlockedByConnectionAllowlist" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *FederatedAuthRequestIssueReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch FederatedAuthRequestIssueReason(s) { - case FederatedAuthRequestIssueReasonShouldEmbargo: - *t = FederatedAuthRequestIssueReasonShouldEmbargo - case FederatedAuthRequestIssueReasonTooManyRequests: - *t = FederatedAuthRequestIssueReasonTooManyRequests - case FederatedAuthRequestIssueReasonWellKnownHTTPNotFound: - *t = FederatedAuthRequestIssueReasonWellKnownHTTPNotFound - case FederatedAuthRequestIssueReasonWellKnownNoResponse: - *t = FederatedAuthRequestIssueReasonWellKnownNoResponse - case FederatedAuthRequestIssueReasonWellKnownInvalidResponse: - *t = FederatedAuthRequestIssueReasonWellKnownInvalidResponse - case FederatedAuthRequestIssueReasonWellKnownListEmpty: - *t = FederatedAuthRequestIssueReasonWellKnownListEmpty - case FederatedAuthRequestIssueReasonWellKnownInvalidContentType: - *t = FederatedAuthRequestIssueReasonWellKnownInvalidContentType - case FederatedAuthRequestIssueReasonConfigNotInWellKnown: - *t = FederatedAuthRequestIssueReasonConfigNotInWellKnown - case FederatedAuthRequestIssueReasonWellKnownTooBig: - *t = FederatedAuthRequestIssueReasonWellKnownTooBig - case FederatedAuthRequestIssueReasonConfigHTTPNotFound: - *t = FederatedAuthRequestIssueReasonConfigHTTPNotFound - case FederatedAuthRequestIssueReasonConfigNoResponse: - *t = FederatedAuthRequestIssueReasonConfigNoResponse - case FederatedAuthRequestIssueReasonConfigInvalidResponse: - *t = FederatedAuthRequestIssueReasonConfigInvalidResponse - case FederatedAuthRequestIssueReasonConfigInvalidContentType: - *t = FederatedAuthRequestIssueReasonConfigInvalidContentType - case FederatedAuthRequestIssueReasonIdpNotPotentiallyTrustworthy: - *t = FederatedAuthRequestIssueReasonIdpNotPotentiallyTrustworthy - case FederatedAuthRequestIssueReasonDisabledInSettings: - *t = FederatedAuthRequestIssueReasonDisabledInSettings - case FederatedAuthRequestIssueReasonDisabledInFlags: - *t = FederatedAuthRequestIssueReasonDisabledInFlags - case FederatedAuthRequestIssueReasonErrorFetchingSignin: - *t = FederatedAuthRequestIssueReasonErrorFetchingSignin - case FederatedAuthRequestIssueReasonInvalidSigninResponse: - *t = FederatedAuthRequestIssueReasonInvalidSigninResponse - case FederatedAuthRequestIssueReasonAccountsHTTPNotFound: - *t = FederatedAuthRequestIssueReasonAccountsHTTPNotFound - case FederatedAuthRequestIssueReasonAccountsNoResponse: - *t = FederatedAuthRequestIssueReasonAccountsNoResponse - case FederatedAuthRequestIssueReasonAccountsInvalidResponse: - *t = FederatedAuthRequestIssueReasonAccountsInvalidResponse - case FederatedAuthRequestIssueReasonAccountsListEmpty: - *t = FederatedAuthRequestIssueReasonAccountsListEmpty - case FederatedAuthRequestIssueReasonAccountsInvalidContentType: - *t = FederatedAuthRequestIssueReasonAccountsInvalidContentType - case FederatedAuthRequestIssueReasonIDTokenHTTPNotFound: - *t = FederatedAuthRequestIssueReasonIDTokenHTTPNotFound - case FederatedAuthRequestIssueReasonIDTokenNoResponse: - *t = FederatedAuthRequestIssueReasonIDTokenNoResponse - case FederatedAuthRequestIssueReasonIDTokenInvalidResponse: - *t = FederatedAuthRequestIssueReasonIDTokenInvalidResponse - case FederatedAuthRequestIssueReasonIDTokenIdpErrorResponse: - *t = FederatedAuthRequestIssueReasonIDTokenIdpErrorResponse - case FederatedAuthRequestIssueReasonIDTokenCrossSiteIdpErrorResponse: - *t = FederatedAuthRequestIssueReasonIDTokenCrossSiteIdpErrorResponse - case FederatedAuthRequestIssueReasonIDTokenInvalidRequest: - *t = FederatedAuthRequestIssueReasonIDTokenInvalidRequest - case FederatedAuthRequestIssueReasonIDTokenInvalidContentType: - *t = FederatedAuthRequestIssueReasonIDTokenInvalidContentType - case FederatedAuthRequestIssueReasonErrorIDToken: - *t = FederatedAuthRequestIssueReasonErrorIDToken - case FederatedAuthRequestIssueReasonCanceled: - *t = FederatedAuthRequestIssueReasonCanceled - case FederatedAuthRequestIssueReasonRpPageNotVisible: - *t = FederatedAuthRequestIssueReasonRpPageNotVisible - case FederatedAuthRequestIssueReasonSilentMediationFailure: - *t = FederatedAuthRequestIssueReasonSilentMediationFailure - case FederatedAuthRequestIssueReasonNotSignedInWithIdp: - *t = FederatedAuthRequestIssueReasonNotSignedInWithIdp - case FederatedAuthRequestIssueReasonMissingTransientUserActivation: - *t = FederatedAuthRequestIssueReasonMissingTransientUserActivation - case FederatedAuthRequestIssueReasonReplacedByActiveMode: - *t = FederatedAuthRequestIssueReasonReplacedByActiveMode - case FederatedAuthRequestIssueReasonRelyingPartyOriginIsOpaque: - *t = FederatedAuthRequestIssueReasonRelyingPartyOriginIsOpaque - case FederatedAuthRequestIssueReasonTypeNotMatching: - *t = FederatedAuthRequestIssueReasonTypeNotMatching - case FederatedAuthRequestIssueReasonUIDismissedNoEmbargo: - *t = FederatedAuthRequestIssueReasonUIDismissedNoEmbargo - case FederatedAuthRequestIssueReasonCorsError: - *t = FederatedAuthRequestIssueReasonCorsError - case FederatedAuthRequestIssueReasonSuppressedBySegmentationPlatform: - *t = FederatedAuthRequestIssueReasonSuppressedBySegmentationPlatform - default: - return fmt.Errorf("unknown FederatedAuthRequestIssueReason value: %v", s) - } - return nil -} - // FederatedAuthUserInfoRequestIssueDetails [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-FederatedAuthUserInfoRequestIssueDetails @@ -1411,36 +772,6 @@ const ( FederatedAuthUserInfoRequestIssueReasonNoReturningUserFromFetchedAccounts FederatedAuthUserInfoRequestIssueReason = "NoReturningUserFromFetchedAccounts" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *FederatedAuthUserInfoRequestIssueReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch FederatedAuthUserInfoRequestIssueReason(s) { - case FederatedAuthUserInfoRequestIssueReasonNotSameOrigin: - *t = FederatedAuthUserInfoRequestIssueReasonNotSameOrigin - case FederatedAuthUserInfoRequestIssueReasonNotIframe: - *t = FederatedAuthUserInfoRequestIssueReasonNotIframe - case FederatedAuthUserInfoRequestIssueReasonNotPotentiallyTrustworthy: - *t = FederatedAuthUserInfoRequestIssueReasonNotPotentiallyTrustworthy - case FederatedAuthUserInfoRequestIssueReasonNoAPIPermission: - *t = FederatedAuthUserInfoRequestIssueReasonNoAPIPermission - case FederatedAuthUserInfoRequestIssueReasonNotSignedInWithIdp: - *t = FederatedAuthUserInfoRequestIssueReasonNotSignedInWithIdp - case FederatedAuthUserInfoRequestIssueReasonNoAccountSharingPermission: - *t = FederatedAuthUserInfoRequestIssueReasonNoAccountSharingPermission - case FederatedAuthUserInfoRequestIssueReasonInvalidConfigOrWellKnown: - *t = FederatedAuthUserInfoRequestIssueReasonInvalidConfigOrWellKnown - case FederatedAuthUserInfoRequestIssueReasonInvalidAccountsResponse: - *t = FederatedAuthUserInfoRequestIssueReasonInvalidAccountsResponse - case FederatedAuthUserInfoRequestIssueReasonNoReturningUserFromFetchedAccounts: - *t = FederatedAuthUserInfoRequestIssueReasonNoReturningUserFromFetchedAccounts - default: - return fmt.Errorf("unknown FederatedAuthUserInfoRequestIssueReason value: %v", s) - } - return nil -} - // EmailVerificationRequestIssueDetails [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-EmailVerificationRequestIssueDetails @@ -1520,134 +851,9 @@ const ( EmailVerificationRequestIssueReasonTokenVerificationKbInvalidSdHash EmailVerificationRequestIssueReason = "TokenVerificationKbInvalidSdHash" EmailVerificationRequestIssueReasonTokenVerificationKbMissingCnf EmailVerificationRequestIssueReason = "TokenVerificationKbMissingCnf" EmailVerificationRequestIssueReasonTokenVerificationKbSignatureFailed EmailVerificationRequestIssueReason = "TokenVerificationKbSignatureFailed" + EmailVerificationRequestIssueReasonCrossOriginIframeNotSupported EmailVerificationRequestIssueReason = "CrossOriginIframeNotSupported" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *EmailVerificationRequestIssueReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch EmailVerificationRequestIssueReason(s) { - case EmailVerificationRequestIssueReasonInvalidEmail: - *t = EmailVerificationRequestIssueReasonInvalidEmail - case EmailVerificationRequestIssueReasonDNSFetchFailed: - *t = EmailVerificationRequestIssueReasonDNSFetchFailed - case EmailVerificationRequestIssueReasonDNSInvalidRecord: - *t = EmailVerificationRequestIssueReasonDNSInvalidRecord - case EmailVerificationRequestIssueReasonWellKnownHTTPNotFound: - *t = EmailVerificationRequestIssueReasonWellKnownHTTPNotFound - case EmailVerificationRequestIssueReasonWellKnownNoResponse: - *t = EmailVerificationRequestIssueReasonWellKnownNoResponse - case EmailVerificationRequestIssueReasonWellKnownInvalidResponse: - *t = EmailVerificationRequestIssueReasonWellKnownInvalidResponse - case EmailVerificationRequestIssueReasonWellKnownListEmpty: - *t = EmailVerificationRequestIssueReasonWellKnownListEmpty - case EmailVerificationRequestIssueReasonWellKnownInvalidContentType: - *t = EmailVerificationRequestIssueReasonWellKnownInvalidContentType - case EmailVerificationRequestIssueReasonWellKnownMissingIssuanceEndpoint: - *t = EmailVerificationRequestIssueReasonWellKnownMissingIssuanceEndpoint - case EmailVerificationRequestIssueReasonWellKnownIssuanceEndpointCrossOrigin: - *t = EmailVerificationRequestIssueReasonWellKnownIssuanceEndpointCrossOrigin - case EmailVerificationRequestIssueReasonWellKnownUnsupportedSigningAlgorithm: - *t = EmailVerificationRequestIssueReasonWellKnownUnsupportedSigningAlgorithm - case EmailVerificationRequestIssueReasonTokenHTTPNotFound: - *t = EmailVerificationRequestIssueReasonTokenHTTPNotFound - case EmailVerificationRequestIssueReasonTokenNoResponse: - *t = EmailVerificationRequestIssueReasonTokenNoResponse - case EmailVerificationRequestIssueReasonTokenInvalidResponse: - *t = EmailVerificationRequestIssueReasonTokenInvalidResponse - case EmailVerificationRequestIssueReasonTokenInvalidContentType: - *t = EmailVerificationRequestIssueReasonTokenInvalidContentType - case EmailVerificationRequestIssueReasonTokenMalformedSdJwt: - *t = EmailVerificationRequestIssueReasonTokenMalformedSdJwt - case EmailVerificationRequestIssueReasonTokenInvalidSdJwt: - *t = EmailVerificationRequestIssueReasonTokenInvalidSdJwt - case EmailVerificationRequestIssueReasonKeyBindingSigningFailed: - *t = EmailVerificationRequestIssueReasonKeyBindingSigningFailed - case EmailVerificationRequestIssueReasonRpOriginIsOpaque: - *t = EmailVerificationRequestIssueReasonRpOriginIsOpaque - case EmailVerificationRequestIssueReasonWellKnownMissingAccountsEndpoint: - *t = EmailVerificationRequestIssueReasonWellKnownMissingAccountsEndpoint - case EmailVerificationRequestIssueReasonUserLoggedOut: - *t = EmailVerificationRequestIssueReasonUserLoggedOut - case EmailVerificationRequestIssueReasonWellKnownAccountsEndpointCrossOrigin: - *t = EmailVerificationRequestIssueReasonWellKnownAccountsEndpointCrossOrigin - case EmailVerificationRequestIssueReasonAccountsHTTPNotFound: - *t = EmailVerificationRequestIssueReasonAccountsHTTPNotFound - case EmailVerificationRequestIssueReasonAccountsNoResponse: - *t = EmailVerificationRequestIssueReasonAccountsNoResponse - case EmailVerificationRequestIssueReasonAccountsInvalidResponse: - *t = EmailVerificationRequestIssueReasonAccountsInvalidResponse - case EmailVerificationRequestIssueReasonAccountsInvalidContentType: - *t = EmailVerificationRequestIssueReasonAccountsInvalidContentType - case EmailVerificationRequestIssueReasonAccountsEmptyList: - *t = EmailVerificationRequestIssueReasonAccountsEmptyList - case EmailVerificationRequestIssueReasonEmailVerificationWellKnownHTTPNotFound: - *t = EmailVerificationRequestIssueReasonEmailVerificationWellKnownHTTPNotFound - case EmailVerificationRequestIssueReasonEmailVerificationWellKnownNoResponse: - *t = EmailVerificationRequestIssueReasonEmailVerificationWellKnownNoResponse - case EmailVerificationRequestIssueReasonEmailVerificationWellKnownInvalidResponse: - *t = EmailVerificationRequestIssueReasonEmailVerificationWellKnownInvalidResponse - case EmailVerificationRequestIssueReasonEmailVerificationWellKnownInvalidContentType: - *t = EmailVerificationRequestIssueReasonEmailVerificationWellKnownInvalidContentType - case EmailVerificationRequestIssueReasonJwksHTTPNotFound: - *t = EmailVerificationRequestIssueReasonJwksHTTPNotFound - case EmailVerificationRequestIssueReasonJwksInvalidResponse: - *t = EmailVerificationRequestIssueReasonJwksInvalidResponse - case EmailVerificationRequestIssueReasonTokenVerificationSdJwtUnsupportedHeaderAlg: - *t = EmailVerificationRequestIssueReasonTokenVerificationSdJwtUnsupportedHeaderAlg - case EmailVerificationRequestIssueReasonTokenVerificationSdJwtInvalidTyp: - *t = EmailVerificationRequestIssueReasonTokenVerificationSdJwtInvalidTyp - case EmailVerificationRequestIssueReasonTokenVerificationSdJwtMissingIss: - *t = EmailVerificationRequestIssueReasonTokenVerificationSdJwtMissingIss - case EmailVerificationRequestIssueReasonTokenVerificationSdJwtMissingIat: - *t = EmailVerificationRequestIssueReasonTokenVerificationSdJwtMissingIat - case EmailVerificationRequestIssueReasonTokenVerificationSdJwtMissingCnf: - *t = EmailVerificationRequestIssueReasonTokenVerificationSdJwtMissingCnf - case EmailVerificationRequestIssueReasonTokenVerificationSdJwtMissingEmail: - *t = EmailVerificationRequestIssueReasonTokenVerificationSdJwtMissingEmail - case EmailVerificationRequestIssueReasonTokenVerificationSdJwtInvalidIssuedAt: - *t = EmailVerificationRequestIssueReasonTokenVerificationSdJwtInvalidIssuedAt - case EmailVerificationRequestIssueReasonTokenVerificationSdJwtInvalidIssuer: - *t = EmailVerificationRequestIssueReasonTokenVerificationSdJwtInvalidIssuer - case EmailVerificationRequestIssueReasonTokenVerificationSdJwtJwksMissingKeys: - *t = EmailVerificationRequestIssueReasonTokenVerificationSdJwtJwksMissingKeys - case EmailVerificationRequestIssueReasonTokenVerificationSdJwtSignatureFailed: - *t = EmailVerificationRequestIssueReasonTokenVerificationSdJwtSignatureFailed - case EmailVerificationRequestIssueReasonTokenVerificationSdJwtInvalidEmailVerified: - *t = EmailVerificationRequestIssueReasonTokenVerificationSdJwtInvalidEmailVerified - case EmailVerificationRequestIssueReasonTokenVerificationSdJwtInvalidEmail: - *t = EmailVerificationRequestIssueReasonTokenVerificationSdJwtInvalidEmail - case EmailVerificationRequestIssueReasonTokenVerificationSdJwtInvalidHolderKey: - *t = EmailVerificationRequestIssueReasonTokenVerificationSdJwtInvalidHolderKey - case EmailVerificationRequestIssueReasonTokenVerificationKbInvalidTyp: - *t = EmailVerificationRequestIssueReasonTokenVerificationKbInvalidTyp - case EmailVerificationRequestIssueReasonTokenVerificationKbMissingAud: - *t = EmailVerificationRequestIssueReasonTokenVerificationKbMissingAud - case EmailVerificationRequestIssueReasonTokenVerificationKbMissingNonce: - *t = EmailVerificationRequestIssueReasonTokenVerificationKbMissingNonce - case EmailVerificationRequestIssueReasonTokenVerificationKbMissingIat: - *t = EmailVerificationRequestIssueReasonTokenVerificationKbMissingIat - case EmailVerificationRequestIssueReasonTokenVerificationKbMissingSdHash: - *t = EmailVerificationRequestIssueReasonTokenVerificationKbMissingSdHash - case EmailVerificationRequestIssueReasonTokenVerificationKbInvalidIssuedAt: - *t = EmailVerificationRequestIssueReasonTokenVerificationKbInvalidIssuedAt - case EmailVerificationRequestIssueReasonTokenVerificationKbInvalidAudience: - *t = EmailVerificationRequestIssueReasonTokenVerificationKbInvalidAudience - case EmailVerificationRequestIssueReasonTokenVerificationKbInvalidNonce: - *t = EmailVerificationRequestIssueReasonTokenVerificationKbInvalidNonce - case EmailVerificationRequestIssueReasonTokenVerificationKbInvalidSdHash: - *t = EmailVerificationRequestIssueReasonTokenVerificationKbInvalidSdHash - case EmailVerificationRequestIssueReasonTokenVerificationKbMissingCnf: - *t = EmailVerificationRequestIssueReasonTokenVerificationKbMissingCnf - case EmailVerificationRequestIssueReasonTokenVerificationKbSignatureFailed: - *t = EmailVerificationRequestIssueReasonTokenVerificationKbSignatureFailed - default: - return fmt.Errorf("unknown EmailVerificationRequestIssueReason value: %v", s) - } - return nil -} - // ClientHintIssueDetails this issue tracks client hints related issues. It's // used to deprecate old features, encourage the use of new ones, and provide // general guidance. @@ -1683,22 +889,6 @@ const ( PartitioningBlobURLInfoEnforceNoopenerForNavigation PartitioningBlobURLInfo = "EnforceNoopenerForNavigation" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *PartitioningBlobURLInfo) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch PartitioningBlobURLInfo(s) { - case PartitioningBlobURLInfoBlockedCrossPartitionFetching: - *t = PartitioningBlobURLInfoBlockedCrossPartitionFetching - case PartitioningBlobURLInfoEnforceNoopenerForNavigation: - *t = PartitioningBlobURLInfoEnforceNoopenerForNavigation - default: - return fmt.Errorf("unknown PartitioningBlobURLInfo value: %v", s) - } - return nil -} - // PartitioningBlobURLIssueDetails [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-PartitioningBlobURLIssueDetails @@ -1727,30 +917,6 @@ const ( ElementAccessibilityIssueReasonInteractiveContentSummaryDescendant ElementAccessibilityIssueReason = "InteractiveContentSummaryDescendant" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ElementAccessibilityIssueReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ElementAccessibilityIssueReason(s) { - case ElementAccessibilityIssueReasonDisallowedSelectChild: - *t = ElementAccessibilityIssueReasonDisallowedSelectChild - case ElementAccessibilityIssueReasonDisallowedOptGroupChild: - *t = ElementAccessibilityIssueReasonDisallowedOptGroupChild - case ElementAccessibilityIssueReasonNonPhrasingContentOptionChild: - *t = ElementAccessibilityIssueReasonNonPhrasingContentOptionChild - case ElementAccessibilityIssueReasonInteractiveContentOptionChild: - *t = ElementAccessibilityIssueReasonInteractiveContentOptionChild - case ElementAccessibilityIssueReasonInteractiveContentLegendChild: - *t = ElementAccessibilityIssueReasonInteractiveContentLegendChild - case ElementAccessibilityIssueReasonInteractiveContentSummaryDescendant: - *t = ElementAccessibilityIssueReasonInteractiveContentSummaryDescendant - default: - return fmt.Errorf("unknown ElementAccessibilityIssueReason value: %v", s) - } - return nil -} - // ElementAccessibilityIssueDetails this issue warns about errors in the // select or summary element content model. // @@ -1777,22 +943,6 @@ const ( StyleSheetLoadingIssueReasonRequestFailed StyleSheetLoadingIssueReason = "RequestFailed" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *StyleSheetLoadingIssueReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch StyleSheetLoadingIssueReason(s) { - case StyleSheetLoadingIssueReasonLateImportRule: - *t = StyleSheetLoadingIssueReasonLateImportRule - case StyleSheetLoadingIssueReasonRequestFailed: - *t = StyleSheetLoadingIssueReasonRequestFailed - default: - return fmt.Errorf("unknown StyleSheetLoadingIssueReason value: %v", s) - } - return nil -} - // StylesheetLoadingIssueDetails this issue warns when a referenced // stylesheet couldn't be loaded. // @@ -1821,26 +971,6 @@ const ( PropertyRuleIssueReasonInvalidName PropertyRuleIssueReason = "InvalidName" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *PropertyRuleIssueReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch PropertyRuleIssueReason(s) { - case PropertyRuleIssueReasonInvalidSyntax: - *t = PropertyRuleIssueReasonInvalidSyntax - case PropertyRuleIssueReasonInvalidInitialValue: - *t = PropertyRuleIssueReasonInvalidInitialValue - case PropertyRuleIssueReasonInvalidInherits: - *t = PropertyRuleIssueReasonInvalidInherits - case PropertyRuleIssueReasonInvalidName: - *t = PropertyRuleIssueReasonInvalidName - default: - return fmt.Errorf("unknown PropertyRuleIssueReason value: %v", s) - } - return nil -} - // PropertyRuleIssueDetails this issue warns about errors in property rules // that lead to property registrations being ignored. // @@ -1868,24 +998,6 @@ const ( UserReidentificationIssueTypeNoisedCanvasReadback UserReidentificationIssueType = "NoisedCanvasReadback" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *UserReidentificationIssueType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch UserReidentificationIssueType(s) { - case UserReidentificationIssueTypeBlockedFrameNavigation: - *t = UserReidentificationIssueTypeBlockedFrameNavigation - case UserReidentificationIssueTypeBlockedSubresource: - *t = UserReidentificationIssueTypeBlockedSubresource - case UserReidentificationIssueTypeNoisedCanvasReadback: - *t = UserReidentificationIssueTypeNoisedCanvasReadback - default: - return fmt.Errorf("unknown UserReidentificationIssueType value: %v", s) - } - return nil -} - // UserReidentificationIssueDetails this issue warns about uses of APIs that // may be considered misuse to re-identify users. // @@ -1933,64 +1045,6 @@ const ( PermissionElementIssueTypeMissingTransientUserActivation PermissionElementIssueType = "MissingTransientUserActivation" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *PermissionElementIssueType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch PermissionElementIssueType(s) { - case PermissionElementIssueTypeInvalidType: - *t = PermissionElementIssueTypeInvalidType - case PermissionElementIssueTypeFencedFrameDisallowed: - *t = PermissionElementIssueTypeFencedFrameDisallowed - case PermissionElementIssueTypeCspFrameAncestorsMissing: - *t = PermissionElementIssueTypeCspFrameAncestorsMissing - case PermissionElementIssueTypePermissionsPolicyBlocked: - *t = PermissionElementIssueTypePermissionsPolicyBlocked - case PermissionElementIssueTypePaddingRightUnsupported: - *t = PermissionElementIssueTypePaddingRightUnsupported - case PermissionElementIssueTypePaddingBottomUnsupported: - *t = PermissionElementIssueTypePaddingBottomUnsupported - case PermissionElementIssueTypeInsetBoxShadowUnsupported: - *t = PermissionElementIssueTypeInsetBoxShadowUnsupported - case PermissionElementIssueTypeRequestInProgress: - *t = PermissionElementIssueTypeRequestInProgress - case PermissionElementIssueTypeUntrustedEvent: - *t = PermissionElementIssueTypeUntrustedEvent - case PermissionElementIssueTypeRegistrationFailed: - *t = PermissionElementIssueTypeRegistrationFailed - case PermissionElementIssueTypeTypeNotSupported: - *t = PermissionElementIssueTypeTypeNotSupported - case PermissionElementIssueTypeInvalidTypeActivation: - *t = PermissionElementIssueTypeInvalidTypeActivation - case PermissionElementIssueTypeSecurityChecksFailed: - *t = PermissionElementIssueTypeSecurityChecksFailed - case PermissionElementIssueTypeActivationDisabled: - *t = PermissionElementIssueTypeActivationDisabled - case PermissionElementIssueTypeGeolocationDeprecated: - *t = PermissionElementIssueTypeGeolocationDeprecated - case PermissionElementIssueTypeInvalidDisplayStyle: - *t = PermissionElementIssueTypeInvalidDisplayStyle - case PermissionElementIssueTypeNonOpaqueColor: - *t = PermissionElementIssueTypeNonOpaqueColor - case PermissionElementIssueTypeLowContrast: - *t = PermissionElementIssueTypeLowContrast - case PermissionElementIssueTypeFontSizeTooSmall: - *t = PermissionElementIssueTypeFontSizeTooSmall - case PermissionElementIssueTypeFontSizeTooLarge: - *t = PermissionElementIssueTypeFontSizeTooLarge - case PermissionElementIssueTypeInvalidSizeValue: - *t = PermissionElementIssueTypeInvalidSizeValue - case PermissionElementIssueTypeNonSecureContext: - *t = PermissionElementIssueTypeNonSecureContext - case PermissionElementIssueTypeMissingTransientUserActivation: - *t = PermissionElementIssueTypeMissingTransientUserActivation - default: - return fmt.Errorf("unknown PermissionElementIssueType value: %v", s) - } - return nil -} - // PermissionElementIssueDetails this issue warns about improper usage of the // element. // @@ -2006,6 +1060,34 @@ type PermissionElementIssueDetails struct { DisableReason string `json:"disableReason,omitempty,omitzero"` // Used for messages about activation disabled reason } +// WebInstallIssueReason [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-WebInstallIssueReason +type WebInstallIssueReason string + +// String returns the WebInstallIssueReason as string value. +func (t WebInstallIssueReason) String() string { + return string(t) +} + +// WebInstallIssueReason values. +const ( + WebInstallIssueReasonManifestParsingOrNetworkError WebInstallIssueReason = "ManifestParsingOrNetworkError" + WebInstallIssueReasonStartURLInvalid WebInstallIssueReason = "StartUrlInvalid" + WebInstallIssueReasonManifestMissingNameOrShortName WebInstallIssueReason = "ManifestMissingNameOrShortName" + WebInstallIssueReasonManifestMissingID WebInstallIssueReason = "ManifestMissingId" + WebInstallIssueReasonNoManifest WebInstallIssueReason = "NoManifest" +) + +// WebInstallIssueDetails this issue reports a failure involving a web app +// manifest used by a Web Install operation. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-WebInstallIssueDetails +type WebInstallIssueDetails struct { + ManifestURL string `json:"manifestUrl,omitempty,omitzero"` + Reason WebInstallIssueReason `json:"reason"` +} + // SelectivePermissionsInterventionIssueDetails the issue warns about blocked // calls to privacy sensitive APIs via the Selective Permissions Intervention. // @@ -2070,80 +1152,9 @@ const ( InspectorIssueCodeSelectivePermissionsInterventionIssue InspectorIssueCode = "SelectivePermissionsInterventionIssue" InspectorIssueCodeEmailVerificationRequestIssue InspectorIssueCode = "EmailVerificationRequestIssue" InspectorIssueCodeLazyLoadImageIssue InspectorIssueCode = "LazyLoadImageIssue" + InspectorIssueCodeWebInstallIssue InspectorIssueCode = "WebInstallIssue" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *InspectorIssueCode) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch InspectorIssueCode(s) { - case InspectorIssueCodeCookieIssue: - *t = InspectorIssueCodeCookieIssue - case InspectorIssueCodeMixedContentIssue: - *t = InspectorIssueCodeMixedContentIssue - case InspectorIssueCodeBlockedByResponseIssue: - *t = InspectorIssueCodeBlockedByResponseIssue - case InspectorIssueCodeHeavyAdIssue: - *t = InspectorIssueCodeHeavyAdIssue - case InspectorIssueCodeContentSecurityPolicyIssue: - *t = InspectorIssueCodeContentSecurityPolicyIssue - case InspectorIssueCodeSharedArrayBufferIssue: - *t = InspectorIssueCodeSharedArrayBufferIssue - case InspectorIssueCodeCorsIssue: - *t = InspectorIssueCodeCorsIssue - case InspectorIssueCodeQuirksModeIssue: - *t = InspectorIssueCodeQuirksModeIssue - case InspectorIssueCodePartitioningBlobURLIssue: - *t = InspectorIssueCodePartitioningBlobURLIssue - case InspectorIssueCodeNavigatorUserAgentIssue: - *t = InspectorIssueCodeNavigatorUserAgentIssue - case InspectorIssueCodeGenericIssue: - *t = InspectorIssueCodeGenericIssue - case InspectorIssueCodeDeprecationIssue: - *t = InspectorIssueCodeDeprecationIssue - case InspectorIssueCodeClientHintIssue: - *t = InspectorIssueCodeClientHintIssue - case InspectorIssueCodeFederatedAuthRequestIssue: - *t = InspectorIssueCodeFederatedAuthRequestIssue - case InspectorIssueCodeBounceTrackingIssue: - *t = InspectorIssueCodeBounceTrackingIssue - case InspectorIssueCodeCookieDeprecationMetadataIssue: - *t = InspectorIssueCodeCookieDeprecationMetadataIssue - case InspectorIssueCodeStylesheetLoadingIssue: - *t = InspectorIssueCodeStylesheetLoadingIssue - case InspectorIssueCodeFederatedAuthUserInfoRequestIssue: - *t = InspectorIssueCodeFederatedAuthUserInfoRequestIssue - case InspectorIssueCodePropertyRuleIssue: - *t = InspectorIssueCodePropertyRuleIssue - case InspectorIssueCodeSharedDictionaryIssue: - *t = InspectorIssueCodeSharedDictionaryIssue - case InspectorIssueCodeElementAccessibilityIssue: - *t = InspectorIssueCodeElementAccessibilityIssue - case InspectorIssueCodeSRIMessageSignatureIssue: - *t = InspectorIssueCodeSRIMessageSignatureIssue - case InspectorIssueCodeUnencodedDigestIssue: - *t = InspectorIssueCodeUnencodedDigestIssue - case InspectorIssueCodeConnectionAllowlistIssue: - *t = InspectorIssueCodeConnectionAllowlistIssue - case InspectorIssueCodeUserReidentificationIssue: - *t = InspectorIssueCodeUserReidentificationIssue - case InspectorIssueCodePermissionElementIssue: - *t = InspectorIssueCodePermissionElementIssue - case InspectorIssueCodePerformanceIssue: - *t = InspectorIssueCodePerformanceIssue - case InspectorIssueCodeSelectivePermissionsInterventionIssue: - *t = InspectorIssueCodeSelectivePermissionsInterventionIssue - case InspectorIssueCodeEmailVerificationRequestIssue: - *t = InspectorIssueCodeEmailVerificationRequestIssue - case InspectorIssueCodeLazyLoadImageIssue: - *t = InspectorIssueCodeLazyLoadImageIssue - default: - return fmt.Errorf("unknown InspectorIssueCode value: %v", s) - } - return nil -} - // InspectorIssueDetails this struct holds a list of optional fields with // additional information specific to the kind of issue. When adding a new issue // code, please also add a new optional field to this type. @@ -2179,6 +1190,7 @@ type InspectorIssueDetails struct { SelectivePermissionsInterventionIssueDetails *SelectivePermissionsInterventionIssueDetails `json:"selectivePermissionsInterventionIssueDetails,omitempty,omitzero"` EmailVerificationRequestIssueDetails *EmailVerificationRequestIssueDetails `json:"emailVerificationRequestIssueDetails,omitempty,omitzero"` LazyLoadImageIssueDetails *LazyLoadImageIssueDetails `json:"lazyLoadImageIssueDetails,omitempty,omitzero"` + WebInstallIssueDetails *WebInstallIssueDetails `json:"webInstallIssueDetails,omitempty,omitzero"` } // IssueID a unique id for a DevTools inspector issue. Allows other entities @@ -2217,21 +1229,3 @@ const ( GetEncodedResponseEncodingJpeg GetEncodedResponseEncoding = "jpeg" GetEncodedResponseEncodingPng GetEncodedResponseEncoding = "png" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *GetEncodedResponseEncoding) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch GetEncodedResponseEncoding(s) { - case GetEncodedResponseEncodingWebp: - *t = GetEncodedResponseEncodingWebp - case GetEncodedResponseEncodingJpeg: - *t = GetEncodedResponseEncodingJpeg - case GetEncodedResponseEncodingPng: - *t = GetEncodedResponseEncodingPng - default: - return fmt.Errorf("unknown GetEncodedResponseEncoding value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/autofill/autofill.go b/vendor/github.com/chromedp/cdproto/autofill/autofill.go index ff6878f51..c02512dc8 100644 --- a/vendor/github.com/chromedp/cdproto/autofill/autofill.go +++ b/vendor/github.com/chromedp/cdproto/autofill/autofill.go @@ -1,21 +1,18 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package autofill provides the Chrome DevTools Protocol // commands, types, and events for the Autofill domain. // // Defines commands and events for Autofill. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package autofill -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// TriggerParams trigger autofill on a form identified by the fieldId. If the -// field and related form cannot be autofilled, returns an error. +// TriggerParams are the parameters of the command Autofill.trigger. type TriggerParams struct { FieldID cdp.BackendNodeID `json:"fieldId"` // Identifies a field that serves as an anchor for autofill. FrameID cdp.FrameID `json:"frameId,omitempty,omitzero"` // Identifies the frame that field belongs to. @@ -27,43 +24,10 @@ type TriggerParams struct { // and related form cannot be autofilled, returns an error. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Autofill#method-trigger -// -// parameters: -// -// fieldID - Identifies a field that serves as an anchor for autofill. -func Trigger(fieldID cdp.BackendNodeID) *TriggerParams { - return &TriggerParams{ - FieldID: fieldID, - } -} - -// WithFrameID identifies the frame that field belongs to. -func (p TriggerParams) WithFrameID(frameID cdp.FrameID) *TriggerParams { - p.FrameID = frameID - return &p -} - -// WithCard credit card information to fill out the form. Credit card data is -// not saved. Mutually exclusive with address. -func (p TriggerParams) WithCard(card *CreditCard) *TriggerParams { - p.Card = card - return &p -} - -// WithAddress address to fill out the form. Address data is not saved. -// Mutually exclusive with card. -func (p TriggerParams) WithAddress(address *Address) *TriggerParams { - p.Address = address - return &p -} - -// Do executes Autofill.trigger against the provided context. -func (p *TriggerParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandTrigger, p, nil) -} +var Trigger = cdp.Command[TriggerParams, cdp.Empty]{Method: CommandTrigger} -// SetAddressesParams set addresses so that developers can verify their forms -// implementation. +// SetAddressesParams are the parameters of the command +// Autofill.setAddresses. type SetAddressesParams struct { Addresses []*Address `json:"addresses"` } @@ -72,50 +36,22 @@ type SetAddressesParams struct { // implementation. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Autofill#method-setAddresses -// -// parameters: -// -// addresses -func SetAddresses(addresses []*Address) *SetAddressesParams { - return &SetAddressesParams{ - Addresses: addresses, - } -} - -// Do executes Autofill.setAddresses against the provided context. -func (p *SetAddressesParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetAddresses, p, nil) -} - -// DisableParams disables autofill domain notifications. -type DisableParams struct{} +var SetAddresses = cdp.Command[SetAddressesParams, cdp.Empty]{Method: CommandSetAddresses} // Disable disables autofill domain notifications. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Autofill#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes Autofill.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// EnableParams enables autofill domain notifications. -type EnableParams struct{} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} // Enable enables autofill domain notifications. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Autofill#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} -// Do executes Autofill.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) -} +// AddressFormFilled emitted when an address form is filled. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Autofill#event-addressFormFilled +var AddressFormFilled = cdp.Event[EventAddressFormFilled]{Method: "Autofill.addressFormFilled"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/autofill/events.go b/vendor/github.com/chromedp/cdproto/autofill/events.go index 446abb4ee..3b8e44bbf 100644 --- a/vendor/github.com/chromedp/cdproto/autofill/events.go +++ b/vendor/github.com/chromedp/cdproto/autofill/events.go @@ -1,6 +1,6 @@ -package autofill +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package autofill // EventAddressFormFilled emitted when an address form is filled. // diff --git a/vendor/github.com/chromedp/cdproto/autofill/types.go b/vendor/github.com/chromedp/cdproto/autofill/types.go index bd7a0c7fa..0511cdbe9 100644 --- a/vendor/github.com/chromedp/cdproto/autofill/types.go +++ b/vendor/github.com/chromedp/cdproto/autofill/types.go @@ -1,11 +1,8 @@ -package autofill +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package autofill import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/cdp" ) @@ -72,22 +69,6 @@ const ( FillingStrategyAutofillInferred FillingStrategy = "autofillInferred" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *FillingStrategy) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch FillingStrategy(s) { - case FillingStrategyAutocompleteAttribute: - *t = FillingStrategyAutocompleteAttribute - case FillingStrategyAutofillInferred: - *t = FillingStrategyAutofillInferred - default: - return fmt.Errorf("unknown FillingStrategy value: %v", s) - } - return nil -} - // FilledField [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Autofill#type-FilledField diff --git a/vendor/github.com/chromedp/cdproto/backgroundservice/backgroundservice.go b/vendor/github.com/chromedp/cdproto/backgroundservice/backgroundservice.go index 74c073aeb..dceeab506 100644 --- a/vendor/github.com/chromedp/cdproto/backgroundservice/backgroundservice.go +++ b/vendor/github.com/chromedp/cdproto/backgroundservice/backgroundservice.go @@ -1,20 +1,19 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package backgroundservice provides the Chrome DevTools Protocol // commands, types, and events for the BackgroundService domain. // // Defines events for background web platform features. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package backgroundservice -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// StartObservingParams enables event updates for the service. +// StartObservingParams are the parameters of the command +// BackgroundService.startObserving. type StartObservingParams struct { Service ServiceName `json:"service"` } @@ -22,22 +21,10 @@ type StartObservingParams struct { // StartObserving enables event updates for the service. // // See: https://chromedevtools.github.io/devtools-protocol/tot/BackgroundService#method-startObserving -// -// parameters: -// -// service -func StartObserving(service ServiceName) *StartObservingParams { - return &StartObservingParams{ - Service: service, - } -} +var StartObserving = cdp.Command[StartObservingParams, cdp.Empty]{Method: CommandStartObserving} -// Do executes BackgroundService.startObserving against the provided context. -func (p *StartObservingParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStartObserving, p, nil) -} - -// StopObservingParams disables event updates for the service. +// StopObservingParams are the parameters of the command +// BackgroundService.stopObserving. type StopObservingParams struct { Service ServiceName `json:"service"` } @@ -45,22 +32,10 @@ type StopObservingParams struct { // StopObserving disables event updates for the service. // // See: https://chromedevtools.github.io/devtools-protocol/tot/BackgroundService#method-stopObserving -// -// parameters: -// -// service -func StopObserving(service ServiceName) *StopObservingParams { - return &StopObservingParams{ - Service: service, - } -} +var StopObserving = cdp.Command[StopObservingParams, cdp.Empty]{Method: CommandStopObserving} -// Do executes BackgroundService.stopObserving against the provided context. -func (p *StopObservingParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStopObserving, p, nil) -} - -// SetRecordingParams set the recording state for the service. +// SetRecordingParams are the parameters of the command +// BackgroundService.setRecording. type SetRecordingParams struct { ShouldRecord bool `json:"shouldRecord"` Service ServiceName `json:"service"` @@ -69,24 +44,10 @@ type SetRecordingParams struct { // SetRecording set the recording state for the service. // // See: https://chromedevtools.github.io/devtools-protocol/tot/BackgroundService#method-setRecording -// -// parameters: -// -// shouldRecord -// service -func SetRecording(shouldRecord bool, service ServiceName) *SetRecordingParams { - return &SetRecordingParams{ - ShouldRecord: shouldRecord, - Service: service, - } -} - -// Do executes BackgroundService.setRecording against the provided context. -func (p *SetRecordingParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetRecording, p, nil) -} +var SetRecording = cdp.Command[SetRecordingParams, cdp.Empty]{Method: CommandSetRecording} -// ClearEventsParams clears all stored data for the service. +// ClearEventsParams are the parameters of the command +// BackgroundService.clearEvents. type ClearEventsParams struct { Service ServiceName `json:"service"` } @@ -94,20 +55,20 @@ type ClearEventsParams struct { // ClearEvents clears all stored data for the service. // // See: https://chromedevtools.github.io/devtools-protocol/tot/BackgroundService#method-clearEvents +var ClearEvents = cdp.Command[ClearEventsParams, cdp.Empty]{Method: CommandClearEvents} + +// RecordingStateChanged called when the recording state for the service has +// been updated. // -// parameters: -// -// service -func ClearEvents(service ServiceName) *ClearEventsParams { - return &ClearEventsParams{ - Service: service, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/BackgroundService#event-recordingStateChanged +var RecordingStateChanged = cdp.Event[EventRecordingStateChanged]{Method: "BackgroundService.recordingStateChanged"} -// Do executes BackgroundService.clearEvents against the provided context. -func (p *ClearEventsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClearEvents, p, nil) -} +// BackgroundServiceEventReceived called with all existing +// backgroundServiceEvents when enabled, and all new events afterwards if +// enabled and recording. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/BackgroundService#event-backgroundServiceEventReceived +var BackgroundServiceEventReceived = cdp.Event[EventBackgroundServiceEventReceived]{Method: "BackgroundService.backgroundServiceEventReceived"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/backgroundservice/events.go b/vendor/github.com/chromedp/cdproto/backgroundservice/events.go index f2eae95dd..5800cdf69 100644 --- a/vendor/github.com/chromedp/cdproto/backgroundservice/events.go +++ b/vendor/github.com/chromedp/cdproto/backgroundservice/events.go @@ -1,6 +1,6 @@ -package backgroundservice +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package backgroundservice // EventRecordingStateChanged called when the recording state for the service // has been updated. diff --git a/vendor/github.com/chromedp/cdproto/backgroundservice/types.go b/vendor/github.com/chromedp/cdproto/backgroundservice/types.go index 125afc2c0..2b1f26004 100644 --- a/vendor/github.com/chromedp/cdproto/backgroundservice/types.go +++ b/vendor/github.com/chromedp/cdproto/backgroundservice/types.go @@ -1,11 +1,8 @@ -package backgroundservice +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package backgroundservice import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/serviceworker" ) @@ -32,30 +29,6 @@ const ( ServiceNamePeriodicBackgroundSync ServiceName = "periodicBackgroundSync" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ServiceName) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ServiceName(s) { - case ServiceNameBackgroundFetch: - *t = ServiceNameBackgroundFetch - case ServiceNameBackgroundSync: - *t = ServiceNameBackgroundSync - case ServiceNamePushMessaging: - *t = ServiceNamePushMessaging - case ServiceNameNotifications: - *t = ServiceNameNotifications - case ServiceNamePaymentHandler: - *t = ServiceNamePaymentHandler - case ServiceNamePeriodicBackgroundSync: - *t = ServiceNamePeriodicBackgroundSync - default: - return fmt.Errorf("unknown ServiceName value: %v", s) - } - return nil -} - // EventMetadata a key-value pair for additional event information to pass // along. // @@ -69,7 +42,7 @@ type EventMetadata struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/BackgroundService#type-BackgroundServiceEvent type Event struct { - Timestamp *cdp.TimeSinceEpoch `json:"timestamp"` // Timestamp of the event (in seconds). + Timestamp cdp.TimeSinceEpoch `json:"timestamp"` // Timestamp of the event (in seconds). Origin string `json:"origin"` // The origin this event belongs to. ServiceWorkerRegistrationID serviceworker.RegistrationID `json:"serviceWorkerRegistrationId"` // The Service Worker ID that initiated the event. Service ServiceName `json:"service"` // The Background Service this event belongs to. diff --git a/vendor/github.com/chromedp/cdproto/bluetoothemulation/bluetoothemulation.go b/vendor/github.com/chromedp/cdproto/bluetoothemulation/bluetoothemulation.go index 4a46f227f..2c44c7b8c 100644 --- a/vendor/github.com/chromedp/cdproto/bluetoothemulation/bluetoothemulation.go +++ b/vendor/github.com/chromedp/cdproto/bluetoothemulation/bluetoothemulation.go @@ -1,21 +1,19 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package bluetoothemulation provides the Chrome DevTools Protocol // commands, types, and events for the BluetoothEmulation domain. // // This domain allows configuring virtual Bluetooth devices to test the // web-bluetooth API. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package bluetoothemulation -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// EnableParams enable the BluetoothEmulation domain. +// EnableParams are the parameters of the command BluetoothEmulation.enable. type EnableParams struct { State CentralState `json:"state"` // State of the simulated central. LeSupported bool `json:"leSupported"` // If the simulated central supports low-energy. @@ -24,24 +22,10 @@ type EnableParams struct { // Enable enable the BluetoothEmulation domain. // // See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#method-enable -// -// parameters: -// -// state - State of the simulated central. -// leSupported - If the simulated central supports low-energy. -func Enable(state CentralState, leSupported bool) *EnableParams { - return &EnableParams{ - State: state, - LeSupported: leSupported, - } -} - -// Do executes BluetoothEmulation.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, p, nil) -} +var Enable = cdp.Command[EnableParams, cdp.Empty]{Method: CommandEnable} -// SetSimulatedCentralStateParams set the state of the simulated central. +// SetSimulatedCentralStateParams are the parameters of the command +// BluetoothEmulation.setSimulatedCentralState. type SetSimulatedCentralStateParams struct { State CentralState `json:"state"` // State of the simulated central. } @@ -49,39 +33,15 @@ type SetSimulatedCentralStateParams struct { // SetSimulatedCentralState set the state of the simulated central. // // See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#method-setSimulatedCentralState -// -// parameters: -// -// state - State of the simulated central. -func SetSimulatedCentralState(state CentralState) *SetSimulatedCentralStateParams { - return &SetSimulatedCentralStateParams{ - State: state, - } -} - -// Do executes BluetoothEmulation.setSimulatedCentralState against the provided context. -func (p *SetSimulatedCentralStateParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetSimulatedCentralState, p, nil) -} - -// DisableParams disable the BluetoothEmulation domain. -type DisableParams struct{} +var SetSimulatedCentralState = cdp.Command[SetSimulatedCentralStateParams, cdp.Empty]{Method: CommandSetSimulatedCentralState} // Disable disable the BluetoothEmulation domain. // // See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} -// Do executes BluetoothEmulation.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// SimulatePreconnectedPeripheralParams simulates a peripheral with -// |address|, |name| and |knownServiceUuids| that has already been connected to -// the system. +// SimulatePreconnectedPeripheralParams are the parameters of the command +// BluetoothEmulation.simulatePreconnectedPeripheral. type SimulatePreconnectedPeripheralParams struct { Address string `json:"address"` Name string `json:"name"` @@ -93,29 +53,10 @@ type SimulatePreconnectedPeripheralParams struct { // |name| and |knownServiceUuids| that has already been connected to the system. // // See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#method-simulatePreconnectedPeripheral -// -// parameters: -// -// address -// name -// manufacturerData -// knownServiceUUIDs -func SimulatePreconnectedPeripheral(address string, name string, manufacturerData []*ManufacturerData, knownServiceUUIDs []string) *SimulatePreconnectedPeripheralParams { - return &SimulatePreconnectedPeripheralParams{ - Address: address, - Name: name, - ManufacturerData: manufacturerData, - KnownServiceUUIDs: knownServiceUUIDs, - } -} +var SimulatePreconnectedPeripheral = cdp.Command[SimulatePreconnectedPeripheralParams, cdp.Empty]{Method: CommandSimulatePreconnectedPeripheral} -// Do executes BluetoothEmulation.simulatePreconnectedPeripheral against the provided context. -func (p *SimulatePreconnectedPeripheralParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSimulatePreconnectedPeripheral, p, nil) -} - -// SimulateAdvertisementParams simulates an advertisement packet described in -// |entry| being received by the central. +// SimulateAdvertisementParams are the parameters of the command +// BluetoothEmulation.simulateAdvertisement. type SimulateAdvertisementParams struct { Entry *ScanEntry `json:"entry"` } @@ -124,25 +65,10 @@ type SimulateAdvertisementParams struct { // |entry| being received by the central. // // See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#method-simulateAdvertisement -// -// parameters: -// -// entry -func SimulateAdvertisement(entry *ScanEntry) *SimulateAdvertisementParams { - return &SimulateAdvertisementParams{ - Entry: entry, - } -} - -// Do executes BluetoothEmulation.simulateAdvertisement against the provided context. -func (p *SimulateAdvertisementParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSimulateAdvertisement, p, nil) -} +var SimulateAdvertisement = cdp.Command[SimulateAdvertisementParams, cdp.Empty]{Method: CommandSimulateAdvertisement} -// SimulateGATTOperationResponseParams simulates the response code from the -// peripheral with |address| for a GATT operation of |type|. The |code| value -// follows the HCI Error Codes from Bluetooth Core Specification Vol 2 Part D -// 1.3 List Of Error Codes. +// SimulateGATTOperationResponseParams are the parameters of the command +// BluetoothEmulation.simulateGATTOperationResponse. type SimulateGATTOperationResponseParams struct { Address string `json:"address"` Type GATTOperationType `json:"type"` @@ -155,35 +81,15 @@ type SimulateGATTOperationResponseParams struct { // 1.3 List Of Error Codes. // // See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#method-simulateGATTOperationResponse -// -// parameters: -// -// address -// type -// code -func SimulateGATTOperationResponse(address string, typeVal GATTOperationType, code int64) *SimulateGATTOperationResponseParams { - return &SimulateGATTOperationResponseParams{ - Address: address, - Type: typeVal, - Code: code, - } -} - -// Do executes BluetoothEmulation.simulateGATTOperationResponse against the provided context. -func (p *SimulateGATTOperationResponseParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSimulateGATTOperationResponse, p, nil) -} +var SimulateGATTOperationResponse = cdp.Command[SimulateGATTOperationResponseParams, cdp.Empty]{Method: CommandSimulateGATTOperationResponse} -// SimulateCharacteristicOperationResponseParams simulates the response from -// the characteristic with |characteristicId| for a characteristic operation of -// |type|. The |code| value follows the Error Codes from Bluetooth Core -// Specification Vol 3 Part F 3.4.1.1 Error Response. The |data| is expected to -// exist when simulating a successful read operation response. +// SimulateCharacteristicOperationResponseParams are the parameters of the +// command BluetoothEmulation.simulateCharacteristicOperationResponse. type SimulateCharacteristicOperationResponseParams struct { CharacteristicID string `json:"characteristicId"` Type CharacteristicOperationType `json:"type"` Code int64 `json:"code"` - Data string `json:"data,omitempty,omitzero"` + Data []byte `json:"data,omitempty,omitzero"` } // SimulateCharacteristicOperationResponse simulates the response from the @@ -193,41 +99,15 @@ type SimulateCharacteristicOperationResponseParams struct { // exist when simulating a successful read operation response. // // See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#method-simulateCharacteristicOperationResponse -// -// parameters: -// -// characteristicID -// type -// code -func SimulateCharacteristicOperationResponse(characteristicID string, typeVal CharacteristicOperationType, code int64) *SimulateCharacteristicOperationResponseParams { - return &SimulateCharacteristicOperationResponseParams{ - CharacteristicID: characteristicID, - Type: typeVal, - Code: code, - } -} - -// WithData [no description]. -func (p SimulateCharacteristicOperationResponseParams) WithData(data string) *SimulateCharacteristicOperationResponseParams { - p.Data = data - return &p -} - -// Do executes BluetoothEmulation.simulateCharacteristicOperationResponse against the provided context. -func (p *SimulateCharacteristicOperationResponseParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSimulateCharacteristicOperationResponse, p, nil) -} +var SimulateCharacteristicOperationResponse = cdp.Command[SimulateCharacteristicOperationResponseParams, cdp.Empty]{Method: CommandSimulateCharacteristicOperationResponse} -// SimulateDescriptorOperationResponseParams simulates the response from the -// descriptor with |descriptorId| for a descriptor operation of |type|. The -// |code| value follows the Error Codes from Bluetooth Core Specification Vol 3 -// Part F 3.4.1.1 Error Response. The |data| is expected to exist when -// simulating a successful read operation response. +// SimulateDescriptorOperationResponseParams are the parameters of the +// command BluetoothEmulation.simulateDescriptorOperationResponse. type SimulateDescriptorOperationResponseParams struct { DescriptorID string `json:"descriptorId"` Type DescriptorOperationType `json:"type"` Code int64 `json:"code"` - Data string `json:"data,omitempty,omitzero"` + Data []byte `json:"data,omitempty,omitzero"` } // SimulateDescriptorOperationResponse simulates the response from the @@ -237,77 +117,29 @@ type SimulateDescriptorOperationResponseParams struct { // simulating a successful read operation response. // // See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#method-simulateDescriptorOperationResponse -// -// parameters: -// -// descriptorID -// type -// code -func SimulateDescriptorOperationResponse(descriptorID string, typeVal DescriptorOperationType, code int64) *SimulateDescriptorOperationResponseParams { - return &SimulateDescriptorOperationResponseParams{ - DescriptorID: descriptorID, - Type: typeVal, - Code: code, - } -} +var SimulateDescriptorOperationResponse = cdp.Command[SimulateDescriptorOperationResponseParams, cdp.Empty]{Method: CommandSimulateDescriptorOperationResponse} -// WithData [no description]. -func (p SimulateDescriptorOperationResponseParams) WithData(data string) *SimulateDescriptorOperationResponseParams { - p.Data = data - return &p -} - -// Do executes BluetoothEmulation.simulateDescriptorOperationResponse against the provided context. -func (p *SimulateDescriptorOperationResponseParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSimulateDescriptorOperationResponse, p, nil) -} - -// AddServiceParams adds a service with |serviceUuid| to the peripheral with -// |address|. +// AddServiceParams are the parameters of the command +// BluetoothEmulation.addService. type AddServiceParams struct { Address string `json:"address"` ServiceUUID string `json:"serviceUuid"` } -// AddService adds a service with |serviceUuid| to the peripheral with -// |address|. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#method-addService -// -// parameters: -// -// address -// serviceUUID -func AddService(address string, serviceUUID string) *AddServiceParams { - return &AddServiceParams{ - Address: address, - ServiceUUID: serviceUUID, - } -} - -// AddServiceReturns return values. -type AddServiceReturns struct { +// AddServiceResult is the result of the command +// BluetoothEmulation.addService. +type AddServiceResult struct { ServiceID string `json:"serviceId,omitempty,omitzero"` // An identifier that uniquely represents this service. } -// Do executes BluetoothEmulation.addService against the provided context. -// -// returns: +// AddService adds a service with |serviceUuid| to the peripheral with +// |address|. // -// serviceID - An identifier that uniquely represents this service. -func (p *AddServiceParams) Do(ctx context.Context) (serviceID string, err error) { - // execute - var res AddServiceReturns - err = cdp.Execute(ctx, CommandAddService, p, &res) - if err != nil { - return "", err - } - - return res.ServiceID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#method-addService +var AddService = cdp.Command[AddServiceParams, AddServiceResult]{Method: CommandAddService} -// RemoveServiceParams removes the service respresented by |serviceId| from -// the simulated central. +// RemoveServiceParams are the parameters of the command +// BluetoothEmulation.removeService. type RemoveServiceParams struct { ServiceID string `json:"serviceId"` } @@ -316,70 +148,30 @@ type RemoveServiceParams struct { // simulated central. // // See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#method-removeService -// -// parameters: -// -// serviceID -func RemoveService(serviceID string) *RemoveServiceParams { - return &RemoveServiceParams{ - ServiceID: serviceID, - } -} - -// Do executes BluetoothEmulation.removeService against the provided context. -func (p *RemoveServiceParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRemoveService, p, nil) -} +var RemoveService = cdp.Command[RemoveServiceParams, cdp.Empty]{Method: CommandRemoveService} -// AddCharacteristicParams adds a characteristic with |characteristicUuid| -// and |properties| to the service represented by |serviceId|. +// AddCharacteristicParams are the parameters of the command +// BluetoothEmulation.addCharacteristic. type AddCharacteristicParams struct { ServiceID string `json:"serviceId"` CharacteristicUUID string `json:"characteristicUuid"` Properties *CharacteristicProperties `json:"properties"` } -// AddCharacteristic adds a characteristic with |characteristicUuid| and -// |properties| to the service represented by |serviceId|. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#method-addCharacteristic -// -// parameters: -// -// serviceID -// characteristicUUID -// properties -func AddCharacteristic(serviceID string, characteristicUUID string, properties *CharacteristicProperties) *AddCharacteristicParams { - return &AddCharacteristicParams{ - ServiceID: serviceID, - CharacteristicUUID: characteristicUUID, - Properties: properties, - } -} - -// AddCharacteristicReturns return values. -type AddCharacteristicReturns struct { +// AddCharacteristicResult is the result of the command +// BluetoothEmulation.addCharacteristic. +type AddCharacteristicResult struct { CharacteristicID string `json:"characteristicId,omitempty,omitzero"` // An identifier that uniquely represents this characteristic. } -// Do executes BluetoothEmulation.addCharacteristic against the provided context. -// -// returns: +// AddCharacteristic adds a characteristic with |characteristicUuid| and +// |properties| to the service represented by |serviceId|. // -// characteristicID - An identifier that uniquely represents this characteristic. -func (p *AddCharacteristicParams) Do(ctx context.Context) (characteristicID string, err error) { - // execute - var res AddCharacteristicReturns - err = cdp.Execute(ctx, CommandAddCharacteristic, p, &res) - if err != nil { - return "", err - } - - return res.CharacteristicID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#method-addCharacteristic +var AddCharacteristic = cdp.Command[AddCharacteristicParams, AddCharacteristicResult]{Method: CommandAddCharacteristic} -// RemoveCharacteristicParams removes the characteristic respresented by -// |characteristicId| from the simulated central. +// RemoveCharacteristicParams are the parameters of the command +// BluetoothEmulation.removeCharacteristic. type RemoveCharacteristicParams struct { CharacteristicID string `json:"characteristicId"` } @@ -388,67 +180,29 @@ type RemoveCharacteristicParams struct { // |characteristicId| from the simulated central. // // See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#method-removeCharacteristic -// -// parameters: -// -// characteristicID -func RemoveCharacteristic(characteristicID string) *RemoveCharacteristicParams { - return &RemoveCharacteristicParams{ - CharacteristicID: characteristicID, - } -} - -// Do executes BluetoothEmulation.removeCharacteristic against the provided context. -func (p *RemoveCharacteristicParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRemoveCharacteristic, p, nil) -} +var RemoveCharacteristic = cdp.Command[RemoveCharacteristicParams, cdp.Empty]{Method: CommandRemoveCharacteristic} -// AddDescriptorParams adds a descriptor with |descriptorUuid| to the -// characteristic respresented by |characteristicId|. +// AddDescriptorParams are the parameters of the command +// BluetoothEmulation.addDescriptor. type AddDescriptorParams struct { CharacteristicID string `json:"characteristicId"` DescriptorUUID string `json:"descriptorUuid"` } -// AddDescriptor adds a descriptor with |descriptorUuid| to the -// characteristic respresented by |characteristicId|. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#method-addDescriptor -// -// parameters: -// -// characteristicID -// descriptorUUID -func AddDescriptor(characteristicID string, descriptorUUID string) *AddDescriptorParams { - return &AddDescriptorParams{ - CharacteristicID: characteristicID, - DescriptorUUID: descriptorUUID, - } -} - -// AddDescriptorReturns return values. -type AddDescriptorReturns struct { +// AddDescriptorResult is the result of the command +// BluetoothEmulation.addDescriptor. +type AddDescriptorResult struct { DescriptorID string `json:"descriptorId,omitempty,omitzero"` // An identifier that uniquely represents this descriptor. } -// Do executes BluetoothEmulation.addDescriptor against the provided context. -// -// returns: +// AddDescriptor adds a descriptor with |descriptorUuid| to the +// characteristic respresented by |characteristicId|. // -// descriptorID - An identifier that uniquely represents this descriptor. -func (p *AddDescriptorParams) Do(ctx context.Context) (descriptorID string, err error) { - // execute - var res AddDescriptorReturns - err = cdp.Execute(ctx, CommandAddDescriptor, p, &res) - if err != nil { - return "", err - } - - return res.DescriptorID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#method-addDescriptor +var AddDescriptor = cdp.Command[AddDescriptorParams, AddDescriptorResult]{Method: CommandAddDescriptor} -// RemoveDescriptorParams removes the descriptor with |descriptorId| from the -// simulated central. +// RemoveDescriptorParams are the parameters of the command +// BluetoothEmulation.removeDescriptor. type RemoveDescriptorParams struct { DescriptorID string `json:"descriptorId"` } @@ -457,23 +211,10 @@ type RemoveDescriptorParams struct { // simulated central. // // See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#method-removeDescriptor -// -// parameters: -// -// descriptorID -func RemoveDescriptor(descriptorID string) *RemoveDescriptorParams { - return &RemoveDescriptorParams{ - DescriptorID: descriptorID, - } -} +var RemoveDescriptor = cdp.Command[RemoveDescriptorParams, cdp.Empty]{Method: CommandRemoveDescriptor} -// Do executes BluetoothEmulation.removeDescriptor against the provided context. -func (p *RemoveDescriptorParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRemoveDescriptor, p, nil) -} - -// SimulateGATTDisconnectionParams simulates a GATT disconnection from the -// peripheral with |address|. +// SimulateGATTDisconnectionParams are the parameters of the command +// BluetoothEmulation.simulateGATTDisconnection. type SimulateGATTDisconnectionParams struct { Address string `json:"address"` } @@ -482,20 +223,27 @@ type SimulateGATTDisconnectionParams struct { // peripheral with |address|. // // See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#method-simulateGATTDisconnection +var SimulateGATTDisconnection = cdp.Command[SimulateGATTDisconnectionParams, cdp.Empty]{Method: CommandSimulateGATTDisconnection} + +// GattOperationReceived event for when a GATT operation of |type| to the +// peripheral with |address| happened. // -// parameters: +// See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#event-gattOperationReceived +var GattOperationReceived = cdp.Event[EventGattOperationReceived]{Method: "BluetoothEmulation.gattOperationReceived"} + +// CharacteristicOperationReceived event for when a characteristic operation +// of |type| to the characteristic respresented by |characteristicId| happened. +// |data| and |writeType| is expected to exist when |type| is write. // -// address -func SimulateGATTDisconnection(address string) *SimulateGATTDisconnectionParams { - return &SimulateGATTDisconnectionParams{ - Address: address, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#event-characteristicOperationReceived +var CharacteristicOperationReceived = cdp.Event[EventCharacteristicOperationReceived]{Method: "BluetoothEmulation.characteristicOperationReceived"} -// Do executes BluetoothEmulation.simulateGATTDisconnection against the provided context. -func (p *SimulateGATTDisconnectionParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSimulateGATTDisconnection, p, nil) -} +// DescriptorOperationReceived event for when a descriptor operation of +// |type| to the descriptor respresented by |descriptorId| happened. |data| is +// expected to exist when |type| is write. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#event-descriptorOperationReceived +var DescriptorOperationReceived = cdp.Event[EventDescriptorOperationReceived]{Method: "BluetoothEmulation.descriptorOperationReceived"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/bluetoothemulation/events.go b/vendor/github.com/chromedp/cdproto/bluetoothemulation/events.go index a59c858f8..083ffbb1e 100644 --- a/vendor/github.com/chromedp/cdproto/bluetoothemulation/events.go +++ b/vendor/github.com/chromedp/cdproto/bluetoothemulation/events.go @@ -1,6 +1,6 @@ -package bluetoothemulation +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package bluetoothemulation // EventGattOperationReceived event for when a GATT operation of |type| to // the peripheral with |address| happened. @@ -19,7 +19,7 @@ type EventGattOperationReceived struct { type EventCharacteristicOperationReceived struct { CharacteristicID string `json:"characteristicId"` Type CharacteristicOperationType `json:"type"` - Data string `json:"data,omitempty,omitzero"` + Data []byte `json:"data,omitempty,omitzero"` WriteType CharacteristicWriteType `json:"writeType,omitempty,omitzero"` } @@ -31,5 +31,5 @@ type EventCharacteristicOperationReceived struct { type EventDescriptorOperationReceived struct { DescriptorID string `json:"descriptorId"` Type DescriptorOperationType `json:"type"` - Data string `json:"data,omitempty,omitzero"` + Data []byte `json:"data,omitempty,omitzero"` } diff --git a/vendor/github.com/chromedp/cdproto/bluetoothemulation/types.go b/vendor/github.com/chromedp/cdproto/bluetoothemulation/types.go index 9d159b71a..e9bce7baa 100644 --- a/vendor/github.com/chromedp/cdproto/bluetoothemulation/types.go +++ b/vendor/github.com/chromedp/cdproto/bluetoothemulation/types.go @@ -1,11 +1,6 @@ -package bluetoothemulation - -import ( - "fmt" - "strings" -) +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package bluetoothemulation // CentralState indicates the various states of Central. // @@ -24,24 +19,6 @@ const ( CentralStatePoweredOn CentralState = "powered-on" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CentralState) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CentralState(s) { - case CentralStateAbsent: - *t = CentralStateAbsent - case CentralStatePoweredOff: - *t = CentralStatePoweredOff - case CentralStatePoweredOn: - *t = CentralStatePoweredOn - default: - return fmt.Errorf("unknown CentralState value: %v", s) - } - return nil -} - // GATTOperationType indicates the various types of GATT event. // // See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#type-GATTOperationType @@ -58,22 +35,6 @@ const ( GATTOperationTypeDiscovery GATTOperationType = "discovery" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *GATTOperationType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch GATTOperationType(s) { - case GATTOperationTypeConnection: - *t = GATTOperationTypeConnection - case GATTOperationTypeDiscovery: - *t = GATTOperationTypeDiscovery - default: - return fmt.Errorf("unknown GATTOperationType value: %v", s) - } - return nil -} - // CharacteristicWriteType indicates the various types of characteristic // write. // @@ -92,24 +53,6 @@ const ( CharacteristicWriteTypeWriteWithoutResponse CharacteristicWriteType = "write-without-response" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CharacteristicWriteType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CharacteristicWriteType(s) { - case CharacteristicWriteTypeWriteDefaultDeprecated: - *t = CharacteristicWriteTypeWriteDefaultDeprecated - case CharacteristicWriteTypeWriteWithResponse: - *t = CharacteristicWriteTypeWriteWithResponse - case CharacteristicWriteTypeWriteWithoutResponse: - *t = CharacteristicWriteTypeWriteWithoutResponse - default: - return fmt.Errorf("unknown CharacteristicWriteType value: %v", s) - } - return nil -} - // CharacteristicOperationType indicates the various types of characteristic // operation. // @@ -129,26 +72,6 @@ const ( CharacteristicOperationTypeUnsubscribeFromNotifications CharacteristicOperationType = "unsubscribe-from-notifications" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CharacteristicOperationType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CharacteristicOperationType(s) { - case CharacteristicOperationTypeRead: - *t = CharacteristicOperationTypeRead - case CharacteristicOperationTypeWrite: - *t = CharacteristicOperationTypeWrite - case CharacteristicOperationTypeSubscribeToNotifications: - *t = CharacteristicOperationTypeSubscribeToNotifications - case CharacteristicOperationTypeUnsubscribeFromNotifications: - *t = CharacteristicOperationTypeUnsubscribeFromNotifications - default: - return fmt.Errorf("unknown CharacteristicOperationType value: %v", s) - } - return nil -} - // DescriptorOperationType indicates the various types of descriptor // operation. // @@ -166,28 +89,12 @@ const ( DescriptorOperationTypeWrite DescriptorOperationType = "write" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DescriptorOperationType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DescriptorOperationType(s) { - case DescriptorOperationTypeRead: - *t = DescriptorOperationTypeRead - case DescriptorOperationTypeWrite: - *t = DescriptorOperationTypeWrite - default: - return fmt.Errorf("unknown DescriptorOperationType value: %v", s) - } - return nil -} - // ManufacturerData stores the manufacturer data. // // See: https://chromedevtools.github.io/devtools-protocol/tot/BluetoothEmulation#type-ManufacturerData type ManufacturerData struct { Key int64 `json:"key"` // Company identifier https://bitbucket.org/bluetooth-SIG/public/src/main/assigned_numbers/company_identifiers/company_identifiers.yaml https://usb.org/developers - Data string `json:"data"` // Manufacturer-specific data + Data []byte `json:"data"` // Manufacturer-specific data } // ScanRecord stores the byte data of the advertisement packet sent by a diff --git a/vendor/github.com/chromedp/cdproto/browser/browser.go b/vendor/github.com/chromedp/cdproto/browser/browser.go index bab14f4e2..7954388e4 100644 --- a/vendor/github.com/chromedp/cdproto/browser/browser.go +++ b/vendor/github.com/chromedp/cdproto/browser/browser.go @@ -1,22 +1,20 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package browser provides the Chrome DevTools Protocol // commands, types, and events for the Browser domain. // // The Browser domain defines methods and events for browser managing. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package browser -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/target" ) -// SetPermissionParams set permission settings for given embedding and -// embedded origins. +// SetPermissionParams are the parameters of the command +// Browser.setPermission. type SetPermissionParams struct { Permission *PermissionDescriptor `json:"permission"` // Descriptor of permission to override. Setting PermissionSetting `json:"setting"` // Setting of the permission. @@ -29,47 +27,10 @@ type SetPermissionParams struct { // origins. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-setPermission -// -// parameters: -// -// permission - Descriptor of permission to override. -// setting - Setting of the permission. -func SetPermission(permission *PermissionDescriptor, setting PermissionSetting) *SetPermissionParams { - return &SetPermissionParams{ - Permission: permission, - Setting: setting, - } -} - -// WithOrigin embedding origin the permission applies to, all origins if not -// specified. -func (p SetPermissionParams) WithOrigin(origin string) *SetPermissionParams { - p.Origin = origin - return &p -} - -// WithEmbeddedOrigin embedded origin the permission applies to. It is -// ignored unless the embedding origin is present and valid. If the embedding -// origin is provided but the embedded origin isn't, the embedding origin is -// used as the embedded origin. -func (p SetPermissionParams) WithEmbeddedOrigin(embeddedOrigin string) *SetPermissionParams { - p.EmbeddedOrigin = embeddedOrigin - return &p -} +var SetPermission = cdp.Command[SetPermissionParams, cdp.Empty]{Method: CommandSetPermission} -// WithBrowserContextID context to override. When omitted, default browser -// context is used. -func (p SetPermissionParams) WithBrowserContextID(browserContextID cdp.BrowserContextID) *SetPermissionParams { - p.BrowserContextID = browserContextID - return &p -} - -// Do executes Browser.setPermission against the provided context. -func (p *SetPermissionParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetPermission, p, nil) -} - -// ResetPermissionsParams reset all permission management for all origins. +// ResetPermissionsParams are the parameters of the command +// Browser.resetPermissions. type ResetPermissionsParams struct { BrowserContextID cdp.BrowserContextID `json:"browserContextId,omitempty,omitzero"` // BrowserContext to reset permissions. When omitted, default browser context is used. } @@ -77,72 +38,24 @@ type ResetPermissionsParams struct { // ResetPermissions reset all permission management for all origins. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-resetPermissions -// -// parameters: -func ResetPermissions() *ResetPermissionsParams { - return &ResetPermissionsParams{} -} - -// WithBrowserContextID browserContext to reset permissions. When omitted, -// default browser context is used. -func (p ResetPermissionsParams) WithBrowserContextID(browserContextID cdp.BrowserContextID) *ResetPermissionsParams { - p.BrowserContextID = browserContextID - return &p -} - -// Do executes Browser.resetPermissions against the provided context. -func (p *ResetPermissionsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandResetPermissions, p, nil) -} +var ResetPermissions = cdp.Command[ResetPermissionsParams, cdp.Empty]{Method: CommandResetPermissions} -// SetDownloadBehaviorParams set the behavior when downloading a file. +// SetDownloadBehaviorParams are the parameters of the command +// Browser.setDownloadBehavior. type SetDownloadBehaviorParams struct { Behavior SetDownloadBehaviorBehavior `json:"behavior"` // Whether to allow all or deny all download requests, or use default Chrome behavior if available (otherwise deny). |allowAndName| allows download and names files according to their download guids. BrowserContextID cdp.BrowserContextID `json:"browserContextId,omitempty,omitzero"` // BrowserContext to set download behavior. When omitted, default browser context is used. DownloadPath string `json:"downloadPath,omitempty,omitzero"` // The default path to save downloaded files to. This is required if behavior is set to 'allow' or 'allowAndName'. - EventsEnabled bool `json:"eventsEnabled"` // Whether to emit download events (defaults to false). + EventsEnabled *bool `json:"eventsEnabled,omitempty,omitzero"` // Whether to emit download events (defaults to false). } // SetDownloadBehavior set the behavior when downloading a file. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-setDownloadBehavior -// -// parameters: -// -// behavior - Whether to allow all or deny all download requests, or use default Chrome behavior if available (otherwise deny). |allowAndName| allows download and names files according to their download guids. -func SetDownloadBehavior(behavior SetDownloadBehaviorBehavior) *SetDownloadBehaviorParams { - return &SetDownloadBehaviorParams{ - Behavior: behavior, - EventsEnabled: false, - } -} - -// WithBrowserContextID browserContext to set download behavior. When -// omitted, default browser context is used. -func (p SetDownloadBehaviorParams) WithBrowserContextID(browserContextID cdp.BrowserContextID) *SetDownloadBehaviorParams { - p.BrowserContextID = browserContextID - return &p -} - -// WithDownloadPath the default path to save downloaded files to. This is -// required if behavior is set to 'allow' or 'allowAndName'. -func (p SetDownloadBehaviorParams) WithDownloadPath(downloadPath string) *SetDownloadBehaviorParams { - p.DownloadPath = downloadPath - return &p -} - -// WithEventsEnabled whether to emit download events (defaults to false). -func (p SetDownloadBehaviorParams) WithEventsEnabled(eventsEnabled bool) *SetDownloadBehaviorParams { - p.EventsEnabled = eventsEnabled - return &p -} - -// Do executes Browser.setDownloadBehavior against the provided context. -func (p *SetDownloadBehaviorParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetDownloadBehavior, p, nil) -} +var SetDownloadBehavior = cdp.Command[SetDownloadBehaviorParams, cdp.Empty]{Method: CommandSetDownloadBehavior} -// CancelDownloadParams cancel a download if in progress. +// CancelDownloadParams are the parameters of the command +// Browser.cancelDownload. type CancelDownloadParams struct { GUID string `json:"guid"` // Global unique identifier of the download. BrowserContextID cdp.BrowserContextID `json:"browserContextId,omitempty,omitzero"` // BrowserContext to perform the action in. When omitted, default browser context is used. @@ -151,85 +64,25 @@ type CancelDownloadParams struct { // CancelDownload cancel a download if in progress. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-cancelDownload -// -// parameters: -// -// guid - Global unique identifier of the download. -func CancelDownload(guid string) *CancelDownloadParams { - return &CancelDownloadParams{ - GUID: guid, - } -} - -// WithBrowserContextID browserContext to perform the action in. When -// omitted, default browser context is used. -func (p CancelDownloadParams) WithBrowserContextID(browserContextID cdp.BrowserContextID) *CancelDownloadParams { - p.BrowserContextID = browserContextID - return &p -} - -// Do executes Browser.cancelDownload against the provided context. -func (p *CancelDownloadParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandCancelDownload, p, nil) -} - -// CloseParams close browser gracefully. -type CloseParams struct{} +var CancelDownload = cdp.Command[CancelDownloadParams, cdp.Empty]{Method: CommandCancelDownload} // Close close browser gracefully. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-close -func Close() *CloseParams { - return &CloseParams{} -} - -// Do executes Browser.close against the provided context. -func (p *CloseParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClose, nil, nil) -} - -// CrashParams crashes browser on the main thread. -type CrashParams struct{} +var Close = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandClose} // Crash crashes browser on the main thread. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-crash -func Crash() *CrashParams { - return &CrashParams{} -} - -// Do executes Browser.crash against the provided context. -func (p *CrashParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandCrash, nil, nil) -} - -// CrashGPUProcessParams crashes GPU process. -type CrashGPUProcessParams struct{} +var Crash = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandCrash} // CrashGPUProcess crashes GPU process. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-crashGpuProcess -func CrashGPUProcess() *CrashGPUProcessParams { - return &CrashGPUProcessParams{} -} - -// Do executes Browser.crashGpuProcess against the provided context. -func (p *CrashGPUProcessParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandCrashGPUProcess, nil, nil) -} +var CrashGPUProcess = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandCrashGPUProcess} -// GetVersionParams returns version information. -type GetVersionParams struct{} - -// GetVersion returns version information. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-getVersion -func GetVersion() *GetVersionParams { - return &GetVersionParams{} -} - -// GetVersionReturns return values. -type GetVersionReturns struct { +// GetVersionResult is the result of the command Browser.getVersion. +type GetVersionResult struct { ProtocolVersion string `json:"protocolVersion,omitempty,omitzero"` // Protocol version. Product string `json:"product,omitempty,omitzero"` // Product name. Revision string `json:"revision,omitempty,omitzero"` // Product revision. @@ -237,244 +90,108 @@ type GetVersionReturns struct { JsVersion string `json:"jsVersion,omitempty,omitzero"` // V8 version. } -// Do executes Browser.getVersion against the provided context. -// -// returns: +// GetVersion returns version information. // -// protocolVersion - Protocol version. -// product - Product name. -// revision - Product revision. -// userAgent - User-Agent. -// jsVersion - V8 version. -func (p *GetVersionParams) Do(ctx context.Context) (protocolVersion string, product string, revision string, userAgent string, jsVersion string, err error) { - // execute - var res GetVersionReturns - err = cdp.Execute(ctx, CommandGetVersion, nil, &res) - if err != nil { - return "", "", "", "", "", err - } - - return res.ProtocolVersion, res.Product, res.Revision, res.UserAgent, res.JsVersion, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-getVersion +var GetVersion = cdp.Command[cdp.Empty, GetVersionResult]{Method: CommandGetVersion} -// GetBrowserCommandLineParams returns the command line switches for the -// browser process if, and only if --enable-automation is on the commandline. -type GetBrowserCommandLineParams struct{} +// GetBrowserCommandLineResult is the result of the command +// Browser.getBrowserCommandLine. +type GetBrowserCommandLineResult struct { + Arguments []string `json:"arguments,omitempty,omitzero"` // Commandline parameters +} // GetBrowserCommandLine returns the command line switches for the browser // process if, and only if --enable-automation is on the commandline. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-getBrowserCommandLine -func GetBrowserCommandLine() *GetBrowserCommandLineParams { - return &GetBrowserCommandLineParams{} -} +var GetBrowserCommandLine = cdp.Command[cdp.Empty, GetBrowserCommandLineResult]{Method: CommandGetBrowserCommandLine} -// GetBrowserCommandLineReturns return values. -type GetBrowserCommandLineReturns struct { - Arguments []string `json:"arguments,omitempty,omitzero"` // Commandline parameters +// AddMockCameraParams are the parameters of the command +// Browser.addMockCamera. +type AddMockCameraParams struct { + DeviceID string `json:"deviceId"` // Required non-empty identifier for the mock camera within the current DevTools session. Different sessions can use the same identifier without replacing each other's cameras. This is not the MediaDeviceInfo.deviceId exposed to the page. } -// Do executes Browser.getBrowserCommandLine against the provided context. -// -// returns: +// AddMockCamera adds or updates a mock camera in the shared video capture +// device list for test automation. The mock camera is not scoped to a +// particular page or frame and is removed when the DevTools session that +// created it disconnects. // -// arguments - Commandline parameters -func (p *GetBrowserCommandLineParams) Do(ctx context.Context) (arguments []string, err error) { - // execute - var res GetBrowserCommandLineReturns - err = cdp.Execute(ctx, CommandGetBrowserCommandLine, nil, &res) - if err != nil { - return nil, err - } - - return res.Arguments, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-addMockCamera +var AddMockCamera = cdp.Command[AddMockCameraParams, cdp.Empty]{Method: CommandAddMockCamera} -// GetHistogramsParams get Chrome histograms. +// GetHistogramsParams are the parameters of the command +// Browser.getHistograms. type GetHistogramsParams struct { Query string `json:"query,omitempty,omitzero"` // Requested substring in name. Only histograms which have query as a substring in their name are extracted. An empty or absent query returns all histograms. - Delta bool `json:"delta"` // If true, retrieve delta since last delta call. + Delta *bool `json:"delta,omitempty,omitzero"` // If true, retrieve delta since last delta call. } -// GetHistograms get Chrome histograms. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-getHistograms -// -// parameters: -func GetHistograms() *GetHistogramsParams { - return &GetHistogramsParams{ - Delta: false, - } -} - -// WithQuery requested substring in name. Only histograms which have query as -// a substring in their name are extracted. An empty or absent query returns all -// histograms. -func (p GetHistogramsParams) WithQuery(query string) *GetHistogramsParams { - p.Query = query - return &p -} - -// WithDelta if true, retrieve delta since last delta call. -func (p GetHistogramsParams) WithDelta(delta bool) *GetHistogramsParams { - p.Delta = delta - return &p -} - -// GetHistogramsReturns return values. -type GetHistogramsReturns struct { +// GetHistogramsResult is the result of the command Browser.getHistograms. +type GetHistogramsResult struct { Histograms []*Histogram `json:"histograms,omitempty,omitzero"` // Histograms. } -// Do executes Browser.getHistograms against the provided context. -// -// returns: +// GetHistograms get Chrome histograms. // -// histograms - Histograms. -func (p *GetHistogramsParams) Do(ctx context.Context) (histograms []*Histogram, err error) { - // execute - var res GetHistogramsReturns - err = cdp.Execute(ctx, CommandGetHistograms, p, &res) - if err != nil { - return nil, err - } - - return res.Histograms, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-getHistograms +var GetHistograms = cdp.Command[GetHistogramsParams, GetHistogramsResult]{Method: CommandGetHistograms} -// GetHistogramParams get a Chrome histogram by name. +// GetHistogramParams are the parameters of the command Browser.getHistogram. type GetHistogramParams struct { - Name string `json:"name"` // Requested histogram name. - Delta bool `json:"delta"` // If true, retrieve delta since last delta call. -} - -// GetHistogram get a Chrome histogram by name. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-getHistogram -// -// parameters: -// -// name - Requested histogram name. -func GetHistogram(name string) *GetHistogramParams { - return &GetHistogramParams{ - Name: name, - Delta: false, - } -} - -// WithDelta if true, retrieve delta since last delta call. -func (p GetHistogramParams) WithDelta(delta bool) *GetHistogramParams { - p.Delta = delta - return &p + Name string `json:"name"` // Requested histogram name. + Delta *bool `json:"delta,omitempty,omitzero"` // If true, retrieve delta since last delta call. } -// GetHistogramReturns return values. -type GetHistogramReturns struct { +// GetHistogramResult is the result of the command Browser.getHistogram. +type GetHistogramResult struct { Histogram *Histogram `json:"histogram,omitempty,omitzero"` // Histogram. } -// Do executes Browser.getHistogram against the provided context. -// -// returns: +// GetHistogram get a Chrome histogram by name. // -// histogram - Histogram. -func (p *GetHistogramParams) Do(ctx context.Context) (histogram *Histogram, err error) { - // execute - var res GetHistogramReturns - err = cdp.Execute(ctx, CommandGetHistogram, p, &res) - if err != nil { - return nil, err - } - - return res.Histogram, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-getHistogram +var GetHistogram = cdp.Command[GetHistogramParams, GetHistogramResult]{Method: CommandGetHistogram} -// GetWindowBoundsParams get position and size of the browser window. +// GetWindowBoundsParams are the parameters of the command +// Browser.getWindowBounds. type GetWindowBoundsParams struct { WindowID WindowID `json:"windowId"` // Browser window id. } -// GetWindowBounds get position and size of the browser window. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-getWindowBounds -// -// parameters: -// -// windowID - Browser window id. -func GetWindowBounds(windowID WindowID) *GetWindowBoundsParams { - return &GetWindowBoundsParams{ - WindowID: windowID, - } -} - -// GetWindowBoundsReturns return values. -type GetWindowBoundsReturns struct { +// GetWindowBoundsResult is the result of the command +// Browser.getWindowBounds. +type GetWindowBoundsResult struct { Bounds *Bounds `json:"bounds,omitempty,omitzero"` // Bounds information of the window. When window state is 'minimized', the restored window position and size are returned. } -// Do executes Browser.getWindowBounds against the provided context. -// -// returns: +// GetWindowBounds get position and size of the browser window. // -// bounds - Bounds information of the window. When window state is 'minimized', the restored window position and size are returned. -func (p *GetWindowBoundsParams) Do(ctx context.Context) (bounds *Bounds, err error) { - // execute - var res GetWindowBoundsReturns - err = cdp.Execute(ctx, CommandGetWindowBounds, p, &res) - if err != nil { - return nil, err - } - - return res.Bounds, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-getWindowBounds +var GetWindowBounds = cdp.Command[GetWindowBoundsParams, GetWindowBoundsResult]{Method: CommandGetWindowBounds} -// GetWindowForTargetParams get the browser window that contains the devtools -// target. +// GetWindowForTargetParams are the parameters of the command +// Browser.getWindowForTarget. type GetWindowForTargetParams struct { TargetID target.ID `json:"targetId,omitempty,omitzero"` // Devtools agent host id. If called as a part of the session, associated targetId is used. } -// GetWindowForTarget get the browser window that contains the devtools -// target. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-getWindowForTarget -// -// parameters: -func GetWindowForTarget() *GetWindowForTargetParams { - return &GetWindowForTargetParams{} -} - -// WithTargetID devtools agent host id. If called as a part of the session, -// associated targetId is used. -func (p GetWindowForTargetParams) WithTargetID(targetID target.ID) *GetWindowForTargetParams { - p.TargetID = targetID - return &p -} - -// GetWindowForTargetReturns return values. -type GetWindowForTargetReturns struct { +// GetWindowForTargetResult is the result of the command +// Browser.getWindowForTarget. +type GetWindowForTargetResult struct { WindowID WindowID `json:"windowId,omitempty,omitzero"` // Browser window id. Bounds *Bounds `json:"bounds,omitempty,omitzero"` // Bounds information of the window. When window state is 'minimized', the restored window position and size are returned. } -// Do executes Browser.getWindowForTarget against the provided context. -// -// returns: +// GetWindowForTarget get the browser window that contains the devtools +// target. // -// windowID - Browser window id. -// bounds - Bounds information of the window. When window state is 'minimized', the restored window position and size are returned. -func (p *GetWindowForTargetParams) Do(ctx context.Context) (windowID WindowID, bounds *Bounds, err error) { - // execute - var res GetWindowForTargetReturns - err = cdp.Execute(ctx, CommandGetWindowForTarget, p, &res) - if err != nil { - return 0, nil, err - } - - return res.WindowID, res.Bounds, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-getWindowForTarget +var GetWindowForTarget = cdp.Command[GetWindowForTargetParams, GetWindowForTargetResult]{Method: CommandGetWindowForTarget} -// SetWindowBoundsParams set position and/or size of the browser window. +// SetWindowBoundsParams are the parameters of the command +// Browser.setWindowBounds. type SetWindowBoundsParams struct { WindowID WindowID `json:"windowId"` // Browser window id. Bounds *Bounds `json:"bounds"` // New window bounds. The 'minimized', 'maximized' and 'fullscreen' states cannot be combined with 'left', 'top', 'width' or 'height'. Leaves unspecified fields unchanged. @@ -483,25 +200,10 @@ type SetWindowBoundsParams struct { // SetWindowBounds set position and/or size of the browser window. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-setWindowBounds -// -// parameters: -// -// windowID - Browser window id. -// bounds - New window bounds. The 'minimized', 'maximized' and 'fullscreen' states cannot be combined with 'left', 'top', 'width' or 'height'. Leaves unspecified fields unchanged. -func SetWindowBounds(windowID WindowID, bounds *Bounds) *SetWindowBoundsParams { - return &SetWindowBoundsParams{ - WindowID: windowID, - Bounds: bounds, - } -} - -// Do executes Browser.setWindowBounds against the provided context. -func (p *SetWindowBoundsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetWindowBounds, p, nil) -} +var SetWindowBounds = cdp.Command[SetWindowBoundsParams, cdp.Empty]{Method: CommandSetWindowBounds} -// SetContentsSizeParams set size of the browser contents resizing browser -// window as necessary. +// SetContentsSizeParams are the parameters of the command +// Browser.setContentsSize. type SetContentsSizeParams struct { WindowID WindowID `json:"windowId"` // Browser window id. Width int64 `json:"width,omitempty,omitzero"` // The window contents width in DIP. Assumes current width if omitted. Must be specified if 'height' is omitted. @@ -512,69 +214,21 @@ type SetContentsSizeParams struct { // as necessary. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-setContentsSize -// -// parameters: -// -// windowID - Browser window id. -func SetContentsSize(windowID WindowID) *SetContentsSizeParams { - return &SetContentsSizeParams{ - WindowID: windowID, - } -} - -// WithWidth the window contents width in DIP. Assumes current width if -// omitted. Must be specified if 'height' is omitted. -func (p SetContentsSizeParams) WithWidth(width int64) *SetContentsSizeParams { - p.Width = width - return &p -} - -// WithHeight the window contents height in DIP. Assumes current height if -// omitted. Must be specified if 'width' is omitted. -func (p SetContentsSizeParams) WithHeight(height int64) *SetContentsSizeParams { - p.Height = height - return &p -} - -// Do executes Browser.setContentsSize against the provided context. -func (p *SetContentsSizeParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetContentsSize, p, nil) -} +var SetContentsSize = cdp.Command[SetContentsSizeParams, cdp.Empty]{Method: CommandSetContentsSize} -// SetDockTileParams set dock tile details, platform-specific. +// SetDockTileParams are the parameters of the command Browser.setDockTile. type SetDockTileParams struct { BadgeLabel string `json:"badgeLabel,omitempty,omitzero"` - Image string `json:"image,omitempty,omitzero"` // Png encoded image. + Image []byte `json:"image,omitempty,omitzero"` // Png encoded image. } // SetDockTile set dock tile details, platform-specific. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-setDockTile -// -// parameters: -func SetDockTile() *SetDockTileParams { - return &SetDockTileParams{} -} +var SetDockTile = cdp.Command[SetDockTileParams, cdp.Empty]{Method: CommandSetDockTile} -// WithBadgeLabel [no description]. -func (p SetDockTileParams) WithBadgeLabel(badgeLabel string) *SetDockTileParams { - p.BadgeLabel = badgeLabel - return &p -} - -// WithImage png encoded image. -func (p SetDockTileParams) WithImage(image string) *SetDockTileParams { - p.Image = image - return &p -} - -// Do executes Browser.setDockTile against the provided context. -func (p *SetDockTileParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetDockTile, p, nil) -} - -// ExecuteBrowserCommandParams invoke custom browser commands used by -// telemetry. +// ExecuteBrowserCommandParams are the parameters of the command +// Browser.executeBrowserCommand. type ExecuteBrowserCommandParams struct { CommandID CommandID `json:"commandId"` } @@ -582,24 +236,10 @@ type ExecuteBrowserCommandParams struct { // ExecuteBrowserCommand invoke custom browser commands used by telemetry. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-executeBrowserCommand -// -// parameters: -// -// commandID -func ExecuteBrowserCommand(commandID CommandID) *ExecuteBrowserCommandParams { - return &ExecuteBrowserCommandParams{ - CommandID: commandID, - } -} - -// Do executes Browser.executeBrowserCommand against the provided context. -func (p *ExecuteBrowserCommandParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandExecuteBrowserCommand, p, nil) -} +var ExecuteBrowserCommand = cdp.Command[ExecuteBrowserCommandParams, cdp.Empty]{Method: CommandExecuteBrowserCommand} -// AddPrivacySandboxEnrollmentOverrideParams allows a site to use privacy -// sandbox features that require enrollment without the site actually being -// enrolled. Only supported on page targets. +// AddPrivacySandboxEnrollmentOverrideParams are the parameters of the +// command Browser.addPrivacySandboxEnrollmentOverride. type AddPrivacySandboxEnrollmentOverrideParams struct { URL string `json:"url"` } @@ -609,21 +249,50 @@ type AddPrivacySandboxEnrollmentOverrideParams struct { // Only supported on page targets. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-addPrivacySandboxEnrollmentOverride +var AddPrivacySandboxEnrollmentOverride = cdp.Command[AddPrivacySandboxEnrollmentOverrideParams, cdp.Empty]{Method: CommandAddPrivacySandboxEnrollmentOverride} + +// GetGlobalPrivacyControlResult is the result of the command +// Browser.getGlobalPrivacyControl. +type GetGlobalPrivacyControlResult struct { + Gpc bool `json:"gpc"` +} + +// GetGlobalPrivacyControl gets the current globally-applied privacy control +// status See https://www.w3.org/TR/gpc/#get-global-privacy-control. // -// parameters: -// -// url -func AddPrivacySandboxEnrollmentOverride(url string) *AddPrivacySandboxEnrollmentOverrideParams { - return &AddPrivacySandboxEnrollmentOverrideParams{ - URL: url, - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-getGlobalPrivacyControl +var GetGlobalPrivacyControl = cdp.Command[cdp.Empty, GetGlobalPrivacyControlResult]{Method: CommandGetGlobalPrivacyControl} + +// SetGlobalPrivacyControlParams are the parameters of the command +// Browser.setGlobalPrivacyControl. +type SetGlobalPrivacyControlParams struct { + Gpc bool `json:"gpc"` } -// Do executes Browser.addPrivacySandboxEnrollmentOverride against the provided context. -func (p *AddPrivacySandboxEnrollmentOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandAddPrivacySandboxEnrollmentOverride, p, nil) +// SetGlobalPrivacyControlResult is the result of the command +// Browser.setGlobalPrivacyControl. +type SetGlobalPrivacyControlResult struct { + Gpc bool `json:"gpc"` } +// SetGlobalPrivacyControl sets and then gets the current globally-applied +// privacy control status See +// https://www.w3.org/TR/gpc/#set-global-privacy-control. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-setGlobalPrivacyControl +var SetGlobalPrivacyControl = cdp.Command[SetGlobalPrivacyControlParams, SetGlobalPrivacyControlResult]{Method: CommandSetGlobalPrivacyControl} + +// DownloadWillBegin fired when page is about to start a download. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#event-downloadWillBegin +var DownloadWillBegin = cdp.Event[EventDownloadWillBegin]{Method: "Browser.downloadWillBegin"} + +// DownloadProgress fired when download makes progress. Last call has |done| +// == true. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#event-downloadProgress +var DownloadProgress = cdp.Event[EventDownloadProgress]{Method: "Browser.downloadProgress"} + // Command names. const ( CommandSetPermission = "Browser.setPermission" @@ -635,6 +304,7 @@ const ( CommandCrashGPUProcess = "Browser.crashGpuProcess" CommandGetVersion = "Browser.getVersion" CommandGetBrowserCommandLine = "Browser.getBrowserCommandLine" + CommandAddMockCamera = "Browser.addMockCamera" CommandGetHistograms = "Browser.getHistograms" CommandGetHistogram = "Browser.getHistogram" CommandGetWindowBounds = "Browser.getWindowBounds" @@ -644,4 +314,6 @@ const ( CommandSetDockTile = "Browser.setDockTile" CommandExecuteBrowserCommand = "Browser.executeBrowserCommand" CommandAddPrivacySandboxEnrollmentOverride = "Browser.addPrivacySandboxEnrollmentOverride" + CommandGetGlobalPrivacyControl = "Browser.getGlobalPrivacyControl" + CommandSetGlobalPrivacyControl = "Browser.setGlobalPrivacyControl" ) diff --git a/vendor/github.com/chromedp/cdproto/browser/events.go b/vendor/github.com/chromedp/cdproto/browser/events.go index 585942575..2822ff87c 100644 --- a/vendor/github.com/chromedp/cdproto/browser/events.go +++ b/vendor/github.com/chromedp/cdproto/browser/events.go @@ -1,6 +1,6 @@ -package browser +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package browser import ( "github.com/chromedp/cdproto/cdp" diff --git a/vendor/github.com/chromedp/cdproto/browser/types.go b/vendor/github.com/chromedp/cdproto/browser/types.go index 6ba68c2f8..6a7bf3242 100644 --- a/vendor/github.com/chromedp/cdproto/browser/types.go +++ b/vendor/github.com/chromedp/cdproto/browser/types.go @@ -1,11 +1,6 @@ -package browser - -import ( - "fmt" - "strings" -) +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package browser // WindowID [no description]. // @@ -35,32 +30,12 @@ const ( WindowStateFullscreen WindowState = "fullscreen" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *WindowState) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch WindowState(s) { - case WindowStateNormal: - *t = WindowStateNormal - case WindowStateMinimized: - *t = WindowStateMinimized - case WindowStateMaximized: - *t = WindowStateMaximized - case WindowStateFullscreen: - *t = WindowStateFullscreen - default: - return fmt.Errorf("unknown WindowState value: %v", s) - } - return nil -} - // Bounds browser window bounds information. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#type-Bounds type Bounds struct { - Left int64 `json:"left,omitempty,omitzero"` // The offset from the left edge of the screen to the window in pixels. - Top int64 `json:"top,omitempty,omitzero"` // The offset from the top edge of the screen to the window in pixels. + Left *int64 `json:"left,omitempty,omitzero"` // The offset from the left edge of the screen to the window in pixels. + Top *int64 `json:"top,omitempty,omitzero"` // The offset from the top edge of the screen to the window in pixels. Width int64 `json:"width,omitempty,omitzero"` // The window width in pixels. Height int64 `json:"height,omitempty,omitzero"` // The window height in pixels. WindowState WindowState `json:"windowState,omitempty,omitzero"` // The window state. Default to normal. @@ -119,96 +94,6 @@ const ( PermissionTypeWindowManagement PermissionType = "windowManagement" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *PermissionType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch PermissionType(s) { - case PermissionTypeAr: - *t = PermissionTypeAr - case PermissionTypeAudioCapture: - *t = PermissionTypeAudioCapture - case PermissionTypeAutomaticFullscreen: - *t = PermissionTypeAutomaticFullscreen - case PermissionTypeBackgroundFetch: - *t = PermissionTypeBackgroundFetch - case PermissionTypeBackgroundSync: - *t = PermissionTypeBackgroundSync - case PermissionTypeCameraPanTiltZoom: - *t = PermissionTypeCameraPanTiltZoom - case PermissionTypeCapturedSurfaceControl: - *t = PermissionTypeCapturedSurfaceControl - case PermissionTypeClipboardReadWrite: - *t = PermissionTypeClipboardReadWrite - case PermissionTypeClipboardSanitizedWrite: - *t = PermissionTypeClipboardSanitizedWrite - case PermissionTypeDisplayCapture: - *t = PermissionTypeDisplayCapture - case PermissionTypeDurableStorage: - *t = PermissionTypeDurableStorage - case PermissionTypeGeolocation: - *t = PermissionTypeGeolocation - case PermissionTypeHandTracking: - *t = PermissionTypeHandTracking - case PermissionTypeIdleDetection: - *t = PermissionTypeIdleDetection - case PermissionTypeKeyboardLock: - *t = PermissionTypeKeyboardLock - case PermissionTypeLocalFonts: - *t = PermissionTypeLocalFonts - case PermissionTypeLocalNetwork: - *t = PermissionTypeLocalNetwork - case PermissionTypeLocalNetworkAccess: - *t = PermissionTypeLocalNetworkAccess - case PermissionTypeLoopbackNetwork: - *t = PermissionTypeLoopbackNetwork - case PermissionTypeMidi: - *t = PermissionTypeMidi - case PermissionTypeMidiSysex: - *t = PermissionTypeMidiSysex - case PermissionTypeNfc: - *t = PermissionTypeNfc - case PermissionTypeNotifications: - *t = PermissionTypeNotifications - case PermissionTypePaymentHandler: - *t = PermissionTypePaymentHandler - case PermissionTypePeriodicBackgroundSync: - *t = PermissionTypePeriodicBackgroundSync - case PermissionTypePointerLock: - *t = PermissionTypePointerLock - case PermissionTypeProtectedMediaIdentifier: - *t = PermissionTypeProtectedMediaIdentifier - case PermissionTypeSensors: - *t = PermissionTypeSensors - case PermissionTypeSmartCard: - *t = PermissionTypeSmartCard - case PermissionTypeSpeakerSelection: - *t = PermissionTypeSpeakerSelection - case PermissionTypeStorageAccess: - *t = PermissionTypeStorageAccess - case PermissionTypeTopLevelStorageAccess: - *t = PermissionTypeTopLevelStorageAccess - case PermissionTypeVideoCapture: - *t = PermissionTypeVideoCapture - case PermissionTypeVr: - *t = PermissionTypeVr - case PermissionTypeWakeLockScreen: - *t = PermissionTypeWakeLockScreen - case PermissionTypeWakeLockSystem: - *t = PermissionTypeWakeLockSystem - case PermissionTypeWebAppInstallation: - *t = PermissionTypeWebAppInstallation - case PermissionTypeWebPrinting: - *t = PermissionTypeWebPrinting - case PermissionTypeWindowManagement: - *t = PermissionTypeWindowManagement - default: - return fmt.Errorf("unknown PermissionType value: %v", s) - } - return nil -} - // PermissionSetting [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#type-PermissionSetting @@ -226,24 +111,6 @@ const ( PermissionSettingPrompt PermissionSetting = "prompt" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *PermissionSetting) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch PermissionSetting(s) { - case PermissionSettingGranted: - *t = PermissionSettingGranted - case PermissionSettingDenied: - *t = PermissionSettingDenied - case PermissionSettingPrompt: - *t = PermissionSettingPrompt - default: - return fmt.Errorf("unknown PermissionSetting value: %v", s) - } - return nil -} - // PermissionDescriptor definition of PermissionDescriptor defined in the // Permissions API: https://w3c.github.io/permissions/#dom-permissiondescriptor. // @@ -274,24 +141,6 @@ const ( CommandIDOpenGlic CommandID = "openGlic" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CommandID) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CommandID(s) { - case CommandIDOpenTabSearch: - *t = CommandIDOpenTabSearch - case CommandIDCloseTabSearch: - *t = CommandIDCloseTabSearch - case CommandIDOpenGlic: - *t = CommandIDOpenGlic - default: - return fmt.Errorf("unknown CommandID value: %v", s) - } - return nil -} - // Bucket chrome histogram bucket. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#type-Bucket @@ -328,24 +177,6 @@ const ( DownloadProgressStateCanceled DownloadProgressState = "canceled" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DownloadProgressState) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DownloadProgressState(s) { - case DownloadProgressStateInProgress: - *t = DownloadProgressStateInProgress - case DownloadProgressStateCompleted: - *t = DownloadProgressStateCompleted - case DownloadProgressStateCanceled: - *t = DownloadProgressStateCanceled - default: - return fmt.Errorf("unknown DownloadProgressState value: %v", s) - } - return nil -} - // SetDownloadBehaviorBehavior whether to allow all or deny all download // requests, or use default Chrome behavior if available (otherwise deny). // |allowAndName| allows download and names files according to their download @@ -366,23 +197,3 @@ const ( SetDownloadBehaviorBehaviorAllowAndName SetDownloadBehaviorBehavior = "allowAndName" SetDownloadBehaviorBehaviorDefault SetDownloadBehaviorBehavior = "default" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SetDownloadBehaviorBehavior) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SetDownloadBehaviorBehavior(s) { - case SetDownloadBehaviorBehaviorDeny: - *t = SetDownloadBehaviorBehaviorDeny - case SetDownloadBehaviorBehaviorAllow: - *t = SetDownloadBehaviorBehaviorAllow - case SetDownloadBehaviorBehaviorAllowAndName: - *t = SetDownloadBehaviorBehaviorAllowAndName - case SetDownloadBehaviorBehaviorDefault: - *t = SetDownloadBehaviorBehaviorDefault - default: - return fmt.Errorf("unknown SetDownloadBehaviorBehavior value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/cachestorage/cachestorage.go b/vendor/github.com/chromedp/cdproto/cachestorage/cachestorage.go index 08ef2de69..ffac8a086 100644 --- a/vendor/github.com/chromedp/cdproto/cachestorage/cachestorage.go +++ b/vendor/github.com/chromedp/cdproto/cachestorage/cachestorage.go @@ -1,19 +1,18 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package cachestorage provides the Chrome DevTools Protocol // commands, types, and events for the CacheStorage domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package cachestorage -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/storage" ) -// DeleteCacheParams deletes a cache. +// DeleteCacheParams are the parameters of the command +// CacheStorage.deleteCache. type DeleteCacheParams struct { CacheID CacheID `json:"cacheId"` // Id of cache for deletion. } @@ -21,22 +20,10 @@ type DeleteCacheParams struct { // DeleteCache deletes a cache. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-deleteCache -// -// parameters: -// -// cacheID - Id of cache for deletion. -func DeleteCache(cacheID CacheID) *DeleteCacheParams { - return &DeleteCacheParams{ - CacheID: cacheID, - } -} - -// Do executes CacheStorage.deleteCache against the provided context. -func (p *DeleteCacheParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDeleteCache, p, nil) -} +var DeleteCache = cdp.Command[DeleteCacheParams, cdp.Empty]{Method: CommandDeleteCache} -// DeleteEntryParams deletes a cache entry. +// DeleteEntryParams are the parameters of the command +// CacheStorage.deleteEntry. type DeleteEntryParams struct { CacheID CacheID `json:"cacheId"` // Id of cache where the entry will be deleted. Request string `json:"request"` // URL spec of the request. @@ -45,126 +32,48 @@ type DeleteEntryParams struct { // DeleteEntry deletes a cache entry. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-deleteEntry -// -// parameters: -// -// cacheID - Id of cache where the entry will be deleted. -// request - URL spec of the request. -func DeleteEntry(cacheID CacheID, request string) *DeleteEntryParams { - return &DeleteEntryParams{ - CacheID: cacheID, - Request: request, - } -} +var DeleteEntry = cdp.Command[DeleteEntryParams, cdp.Empty]{Method: CommandDeleteEntry} -// Do executes CacheStorage.deleteEntry against the provided context. -func (p *DeleteEntryParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDeleteEntry, p, nil) -} - -// RequestCacheNamesParams requests cache names. +// RequestCacheNamesParams are the parameters of the command +// CacheStorage.requestCacheNames. type RequestCacheNamesParams struct { SecurityOrigin string `json:"securityOrigin,omitempty,omitzero"` // At least and at most one of securityOrigin, storageKey, storageBucket must be specified. Security origin. StorageKey string `json:"storageKey,omitempty,omitzero"` // Storage key. StorageBucket *storage.Bucket `json:"storageBucket,omitempty,omitzero"` // Storage bucket. If not specified, it uses the default bucket. } -// RequestCacheNames requests cache names. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestCacheNames -// -// parameters: -func RequestCacheNames() *RequestCacheNamesParams { - return &RequestCacheNamesParams{} -} - -// WithSecurityOrigin at least and at most one of securityOrigin, storageKey, -// storageBucket must be specified. Security origin. -func (p RequestCacheNamesParams) WithSecurityOrigin(securityOrigin string) *RequestCacheNamesParams { - p.SecurityOrigin = securityOrigin - return &p -} - -// WithStorageKey storage key. -func (p RequestCacheNamesParams) WithStorageKey(storageKey string) *RequestCacheNamesParams { - p.StorageKey = storageKey - return &p -} - -// WithStorageBucket storage bucket. If not specified, it uses the default -// bucket. -func (p RequestCacheNamesParams) WithStorageBucket(storageBucket *storage.Bucket) *RequestCacheNamesParams { - p.StorageBucket = storageBucket - return &p -} - -// RequestCacheNamesReturns return values. -type RequestCacheNamesReturns struct { +// RequestCacheNamesResult is the result of the command +// CacheStorage.requestCacheNames. +type RequestCacheNamesResult struct { Caches []*Cache `json:"caches,omitempty,omitzero"` // Caches for the security origin. } -// Do executes CacheStorage.requestCacheNames against the provided context. -// -// returns: +// RequestCacheNames requests cache names. // -// caches - Caches for the security origin. -func (p *RequestCacheNamesParams) Do(ctx context.Context) (caches []*Cache, err error) { - // execute - var res RequestCacheNamesReturns - err = cdp.Execute(ctx, CommandRequestCacheNames, p, &res) - if err != nil { - return nil, err - } - - return res.Caches, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestCacheNames +var RequestCacheNames = cdp.Command[RequestCacheNamesParams, RequestCacheNamesResult]{Method: CommandRequestCacheNames} -// RequestCachedResponseParams fetches cache entry. +// RequestCachedResponseParams are the parameters of the command +// CacheStorage.requestCachedResponse. type RequestCachedResponseParams struct { CacheID CacheID `json:"cacheId"` // Id of cache that contains the entry. RequestURL string `json:"requestURL"` // URL spec of the request. RequestHeaders []*Header `json:"requestHeaders"` // headers of the request. } -// RequestCachedResponse fetches cache entry. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestCachedResponse -// -// parameters: -// -// cacheID - Id of cache that contains the entry. -// requestURL - URL spec of the request. -// requestHeaders - headers of the request. -func RequestCachedResponse(cacheID CacheID, requestURL string, requestHeaders []*Header) *RequestCachedResponseParams { - return &RequestCachedResponseParams{ - CacheID: cacheID, - RequestURL: requestURL, - RequestHeaders: requestHeaders, - } -} - -// RequestCachedResponseReturns return values. -type RequestCachedResponseReturns struct { +// RequestCachedResponseResult is the result of the command +// CacheStorage.requestCachedResponse. +type RequestCachedResponseResult struct { Response *CachedResponse `json:"response,omitempty,omitzero"` // Response read from the cache. } -// Do executes CacheStorage.requestCachedResponse against the provided context. -// -// returns: +// RequestCachedResponse fetches cache entry. // -// response - Response read from the cache. -func (p *RequestCachedResponseParams) Do(ctx context.Context) (response *CachedResponse, err error) { - // execute - var res RequestCachedResponseReturns - err = cdp.Execute(ctx, CommandRequestCachedResponse, p, &res) - if err != nil { - return nil, err - } - - return res.Response, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestCachedResponse +var RequestCachedResponse = cdp.Command[RequestCachedResponseParams, RequestCachedResponseResult]{Method: CommandRequestCachedResponse} -// RequestEntriesParams requests data from cache. +// RequestEntriesParams are the parameters of the command +// CacheStorage.requestEntries. type RequestEntriesParams struct { CacheID CacheID `json:"cacheId"` // ID of cache to get entries from. SkipCount int64 `json:"skipCount,omitempty,omitzero"` // Number of records to skip. @@ -172,60 +81,17 @@ type RequestEntriesParams struct { PathFilter string `json:"pathFilter,omitempty,omitzero"` // If present, only return the entries containing this substring in the path } -// RequestEntries requests data from cache. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestEntries -// -// parameters: -// -// cacheID - ID of cache to get entries from. -func RequestEntries(cacheID CacheID) *RequestEntriesParams { - return &RequestEntriesParams{ - CacheID: cacheID, - } -} - -// WithSkipCount number of records to skip. -func (p RequestEntriesParams) WithSkipCount(skipCount int64) *RequestEntriesParams { - p.SkipCount = skipCount - return &p -} - -// WithPageSize number of records to fetch. -func (p RequestEntriesParams) WithPageSize(pageSize int64) *RequestEntriesParams { - p.PageSize = pageSize - return &p -} - -// WithPathFilter if present, only return the entries containing this -// substring in the path. -func (p RequestEntriesParams) WithPathFilter(pathFilter string) *RequestEntriesParams { - p.PathFilter = pathFilter - return &p -} - -// RequestEntriesReturns return values. -type RequestEntriesReturns struct { +// RequestEntriesResult is the result of the command +// CacheStorage.requestEntries. +type RequestEntriesResult struct { CacheDataEntries []*DataEntry `json:"cacheDataEntries,omitempty,omitzero"` // Array of object store data entries. ReturnCount float64 `json:"returnCount,omitempty,omitzero"` // Count of returned entries from this storage. If pathFilter is empty, it is the count of all entries from this storage. } -// Do executes CacheStorage.requestEntries against the provided context. -// -// returns: +// RequestEntries requests data from cache. // -// cacheDataEntries - Array of object store data entries. -// returnCount - Count of returned entries from this storage. If pathFilter is empty, it is the count of all entries from this storage. -func (p *RequestEntriesParams) Do(ctx context.Context) (cacheDataEntries []*DataEntry, returnCount float64, err error) { - // execute - var res RequestEntriesReturns - err = cdp.Execute(ctx, CommandRequestEntries, p, &res) - if err != nil { - return nil, 0, err - } - - return res.CacheDataEntries, res.ReturnCount, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestEntries +var RequestEntries = cdp.Command[RequestEntriesParams, RequestEntriesResult]{Method: CommandRequestEntries} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/cachestorage/types.go b/vendor/github.com/chromedp/cdproto/cachestorage/types.go index caa288929..55834ef0f 100644 --- a/vendor/github.com/chromedp/cdproto/cachestorage/types.go +++ b/vendor/github.com/chromedp/cdproto/cachestorage/types.go @@ -1,11 +1,8 @@ -package cachestorage +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package cachestorage import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/storage" ) @@ -39,30 +36,6 @@ const ( CachedResponseTypeOpaqueRedirect CachedResponseType = "opaqueRedirect" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CachedResponseType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CachedResponseType(s) { - case CachedResponseTypeBasic: - *t = CachedResponseTypeBasic - case CachedResponseTypeCors: - *t = CachedResponseTypeCors - case CachedResponseTypeDefault: - *t = CachedResponseTypeDefault - case CachedResponseTypeError: - *t = CachedResponseTypeError - case CachedResponseTypeOpaqueResponse: - *t = CachedResponseTypeOpaqueResponse - case CachedResponseTypeOpaqueRedirect: - *t = CachedResponseTypeOpaqueRedirect - default: - return fmt.Errorf("unknown CachedResponseType value: %v", s) - } - return nil -} - // DataEntry data entry. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#type-DataEntry @@ -100,5 +73,5 @@ type Header struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#type-CachedResponse type CachedResponse struct { - Body string `json:"body"` // Entry content, base64-encoded. + Body []byte `json:"body"` // Entry content, base64-encoded. } diff --git a/vendor/github.com/chromedp/cdproto/cast/cast.go b/vendor/github.com/chromedp/cdproto/cast/cast.go index a1b245f9e..feb748344 100644 --- a/vendor/github.com/chromedp/cdproto/cast/cast.go +++ b/vendor/github.com/chromedp/cdproto/cast/cast.go @@ -1,25 +1,19 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package cast provides the Chrome DevTools Protocol // commands, types, and events for the Cast domain. // // A domain for interacting with Cast, Presentation API, and Remote Playback // API functionalities. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package cast -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// EnableParams starts observing for sinks that can be used for tab -// mirroring, and if set, sinks compatible with |presentationUrl| as well. When -// sinks are found, a |sinksUpdated| event is fired. Also starts observing for -// issue messages. When an issue is added or removed, an |issueUpdated| event is -// fired. +// EnableParams are the parameters of the command Cast.enable. type EnableParams struct { PresentationURL string `json:"presentationUrl,omitempty,omitzero"` } @@ -31,41 +25,14 @@ type EnableParams struct { // fired. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Cast#method-enable -// -// parameters: -func Enable() *EnableParams { - return &EnableParams{} -} - -// WithPresentationURL [no description]. -func (p EnableParams) WithPresentationURL(presentationURL string) *EnableParams { - p.PresentationURL = presentationURL - return &p -} - -// Do executes Cast.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, p, nil) -} - -// DisableParams stops observing for sinks and issues. -type DisableParams struct{} +var Enable = cdp.Command[EnableParams, cdp.Empty]{Method: CommandEnable} // Disable stops observing for sinks and issues. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Cast#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes Cast.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} -// SetSinkToUseParams sets a sink to be used when the web page requests the -// browser to choose a sink via Presentation API, Remote Playback API, or Cast -// SDK. +// SetSinkToUseParams are the parameters of the command Cast.setSinkToUse. type SetSinkToUseParams struct { SinkName string `json:"sinkName"` } @@ -74,22 +41,10 @@ type SetSinkToUseParams struct { // to choose a sink via Presentation API, Remote Playback API, or Cast SDK. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Cast#method-setSinkToUse -// -// parameters: -// -// sinkName -func SetSinkToUse(sinkName string) *SetSinkToUseParams { - return &SetSinkToUseParams{ - SinkName: sinkName, - } -} +var SetSinkToUse = cdp.Command[SetSinkToUseParams, cdp.Empty]{Method: CommandSetSinkToUse} -// Do executes Cast.setSinkToUse against the provided context. -func (p *SetSinkToUseParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetSinkToUse, p, nil) -} - -// StartDesktopMirroringParams starts mirroring the desktop to the sink. +// StartDesktopMirroringParams are the parameters of the command +// Cast.startDesktopMirroring. type StartDesktopMirroringParams struct { SinkName string `json:"sinkName"` } @@ -97,22 +52,10 @@ type StartDesktopMirroringParams struct { // StartDesktopMirroring starts mirroring the desktop to the sink. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Cast#method-startDesktopMirroring -// -// parameters: -// -// sinkName -func StartDesktopMirroring(sinkName string) *StartDesktopMirroringParams { - return &StartDesktopMirroringParams{ - SinkName: sinkName, - } -} +var StartDesktopMirroring = cdp.Command[StartDesktopMirroringParams, cdp.Empty]{Method: CommandStartDesktopMirroring} -// Do executes Cast.startDesktopMirroring against the provided context. -func (p *StartDesktopMirroringParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStartDesktopMirroring, p, nil) -} - -// StartTabMirroringParams starts mirroring the tab to the sink. +// StartTabMirroringParams are the parameters of the command +// Cast.startTabMirroring. type StartTabMirroringParams struct { SinkName string `json:"sinkName"` } @@ -120,22 +63,9 @@ type StartTabMirroringParams struct { // StartTabMirroring starts mirroring the tab to the sink. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Cast#method-startTabMirroring -// -// parameters: -// -// sinkName -func StartTabMirroring(sinkName string) *StartTabMirroringParams { - return &StartTabMirroringParams{ - SinkName: sinkName, - } -} - -// Do executes Cast.startTabMirroring against the provided context. -func (p *StartTabMirroringParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStartTabMirroring, p, nil) -} +var StartTabMirroring = cdp.Command[StartTabMirroringParams, cdp.Empty]{Method: CommandStartTabMirroring} -// StopCastingParams stops the active Cast session on the sink. +// StopCastingParams are the parameters of the command Cast.stopCasting. type StopCastingParams struct { SinkName string `json:"sinkName"` } @@ -143,20 +73,19 @@ type StopCastingParams struct { // StopCasting stops the active Cast session on the sink. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Cast#method-stopCasting +var StopCasting = cdp.Command[StopCastingParams, cdp.Empty]{Method: CommandStopCasting} + +// SinksUpdated this is fired whenever the list of available sinks changes. A +// sink is a device or a software surface that you can cast to. // -// parameters: -// -// sinkName -func StopCasting(sinkName string) *StopCastingParams { - return &StopCastingParams{ - SinkName: sinkName, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Cast#event-sinksUpdated +var SinksUpdated = cdp.Event[EventSinksUpdated]{Method: "Cast.sinksUpdated"} -// Do executes Cast.stopCasting against the provided context. -func (p *StopCastingParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStopCasting, p, nil) -} +// IssueUpdated this is fired whenever the outstanding issue/error message +// changes. |issueMessage| is empty if there is no issue. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Cast#event-issueUpdated +var IssueUpdated = cdp.Event[EventIssueUpdated]{Method: "Cast.issueUpdated"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/cast/events.go b/vendor/github.com/chromedp/cdproto/cast/events.go index 8b368e231..2ef6d1b22 100644 --- a/vendor/github.com/chromedp/cdproto/cast/events.go +++ b/vendor/github.com/chromedp/cdproto/cast/events.go @@ -1,6 +1,6 @@ -package cast +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package cast // EventSinksUpdated this is fired whenever the list of available sinks // changes. A sink is a device or a software surface that you can cast to. diff --git a/vendor/github.com/chromedp/cdproto/cast/types.go b/vendor/github.com/chromedp/cdproto/cast/types.go index 5b606a1d1..4048398ae 100644 --- a/vendor/github.com/chromedp/cdproto/cast/types.go +++ b/vendor/github.com/chromedp/cdproto/cast/types.go @@ -1,6 +1,6 @@ -package cast +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package cast // Sink [no description]. // diff --git a/vendor/github.com/chromedp/cdproto/cdp/jsonv2/doc.go b/vendor/github.com/chromedp/cdproto/cdp/jsonv2/doc.go new file mode 100644 index 000000000..134dcc39d --- /dev/null +++ b/vendor/github.com/chromedp/cdproto/cdp/jsonv2/doc.go @@ -0,0 +1,34 @@ +// Code generated by pdlgen. DO NOT EDIT. + +// Package jsonv2 is the JSON layer of the module cdproto. It names the types +// and the funcs of version 2 of the JSON package that the generated code and +// the programs that use it need, with the same names as the standard library. +// +// The generated code reads and writes JSON with the packages encoding/json/v2 +// and encoding/json/jsontext. Go 1.27 has both packages in the standard library. +// Go 1.25 and Go 1.26 have them only when the GOEXPERIMENT environment variable +// is set to jsonv2. A program that does not set it cannot import them. To +// support these versions of Go, this package is the only place that imports a +// JSON package. It imports no other package of the module, so every other +// package can import it. +// +// The files json_std.go and json_compat.go define the same names. The build +// chooses one of them: +// +// - json_std.go builds with Go 1.27 or later, and with GOEXPERIMENT=jsonv2. +// It uses the packages of the standard library. Its types are aliases of the +// standard types, so a program on Go 1.27 can pass a [Value] to any +// function that takes a jsontext.Value. +// - json_compat.go builds with all other versions of Go. It uses the module +// github.com/go-json-experiment/json, which is the source of the standard +// packages. The module is pinned to a version that needs Go 1.25. +// +// The build tag cdproto_jsoncompat selects json_compat.go on every version of +// Go. Use it to test the second file with a newer toolchain. Go 1.27 turns the +// jsonv2 experiment on by default, and the pinned module does not build with +// the standard package of Go 1.27. On Go 1.27, set GOEXPERIMENT=nojsonv2 with +// the tag. +// +// The two files must behave the same. Both use the default options of version 2 +// of the JSON package, and neither one changes them. +package jsonv2 diff --git a/vendor/github.com/chromedp/cdproto/cdp/jsonv2/json_compat.go b/vendor/github.com/chromedp/cdproto/cdp/jsonv2/json_compat.go new file mode 100644 index 000000000..61ce64e82 --- /dev/null +++ b/vendor/github.com/chromedp/cdproto/cdp/jsonv2/json_compat.go @@ -0,0 +1,68 @@ +// Code generated by pdlgen. DO NOT EDIT. + +//go:build !(go1.27 || goexperiment.jsonv2) || cdproto_jsoncompat + +package jsonv2 + +import ( + v2 "github.com/go-json-experiment/json" + "github.com/go-json-experiment/json/jsontext" +) + +// This file defines the JSON layer with the module +// github.com/go-json-experiment/json. The file json_std.go defines the same +// names with the packages of the standard library. + +// Value is a raw JSON value. +type Value = jsontext.Value + +// Options is a set of options for the JSON encoder and decoder. +type Options = v2.Options + +// Decoder reads a stream of JSON values. +type Decoder = jsontext.Decoder + +// Encoder writes a stream of JSON values. +type Encoder = jsontext.Encoder + +// SyntacticError is the error for JSON text that is not valid. +type SyntacticError = jsontext.SyntacticError + +// Marshal encodes in as JSON with the options. +func Marshal(in any, opts ...Options) ([]byte, error) { + return v2.Marshal(in, opts...) +} + +// Unmarshal decodes the JSON text in into out with the options. +func Unmarshal(in []byte, out any, opts ...Options) error { + return v2.Unmarshal(in, out, opts...) +} + +// MarshalEncode encodes in as JSON to the encoder with the options. +func MarshalEncode(out *Encoder, in any, opts ...Options) error { + return v2.MarshalEncode(out, in, opts...) +} + +// UnmarshalDecode decodes the next JSON value of the decoder into out with the +// options. +func UnmarshalDecode(in *Decoder, out any, opts ...Options) error { + return v2.UnmarshalDecode(in, out, opts...) +} + +// JoinOptions combines the options into one set. An option that comes later +// replaces an option that comes earlier. +func JoinOptions(srcs ...Options) Options { + return v2.JoinOptions(srcs...) +} + +// DefaultOptionsV2 returns the options that define the behavior of version 2 of +// the JSON package. +func DefaultOptionsV2() Options { + return v2.DefaultOptionsV2() +} + +// AllowInvalidUTF8 returns the option that lets the encoder and the decoder +// accept text that is not valid UTF-8. +func AllowInvalidUTF8(v bool) Options { + return jsontext.AllowInvalidUTF8(v) +} diff --git a/vendor/github.com/chromedp/cdproto/cdp/jsonv2/json_std.go b/vendor/github.com/chromedp/cdproto/cdp/jsonv2/json_std.go new file mode 100644 index 000000000..7e12a57d0 --- /dev/null +++ b/vendor/github.com/chromedp/cdproto/cdp/jsonv2/json_std.go @@ -0,0 +1,67 @@ +// Code generated by pdlgen. DO NOT EDIT. + +//go:build (go1.27 || goexperiment.jsonv2) && !cdproto_jsoncompat + +package jsonv2 + +import ( + "encoding/json/jsontext" + v2 "encoding/json/v2" +) + +// This file defines the JSON layer with the packages of the standard library. +// The file json_compat.go defines the same names with another module. + +// Value is a raw JSON value. +type Value = jsontext.Value + +// Options is a set of options for the JSON encoder and decoder. +type Options = v2.Options + +// Decoder reads a stream of JSON values. +type Decoder = jsontext.Decoder + +// Encoder writes a stream of JSON values. +type Encoder = jsontext.Encoder + +// SyntacticError is the error for JSON text that is not valid. +type SyntacticError = jsontext.SyntacticError + +// Marshal encodes in as JSON with the options. +func Marshal(in any, opts ...Options) ([]byte, error) { + return v2.Marshal(in, opts...) +} + +// Unmarshal decodes the JSON text in into out with the options. +func Unmarshal(in []byte, out any, opts ...Options) error { + return v2.Unmarshal(in, out, opts...) +} + +// MarshalEncode encodes in as JSON to the encoder with the options. +func MarshalEncode(out *Encoder, in any, opts ...Options) error { + return v2.MarshalEncode(out, in, opts...) +} + +// UnmarshalDecode decodes the next JSON value of the decoder into out with the +// options. +func UnmarshalDecode(in *Decoder, out any, opts ...Options) error { + return v2.UnmarshalDecode(in, out, opts...) +} + +// JoinOptions combines the options into one set. An option that comes later +// replaces an option that comes earlier. +func JoinOptions(srcs ...Options) Options { + return v2.JoinOptions(srcs...) +} + +// DefaultOptionsV2 returns the options that define the behavior of version 2 of +// the JSON package. +func DefaultOptionsV2() Options { + return v2.DefaultOptionsV2() +} + +// AllowInvalidUTF8 returns the option that lets the encoder and the decoder +// accept text that is not valid UTF-8. +func AllowInvalidUTF8(v bool) Options { + return jsontext.AllowInvalidUTF8(v) +} diff --git a/vendor/github.com/chromedp/cdproto/cdp/types.go b/vendor/github.com/chromedp/cdproto/cdp/types.go index b81c01ff5..e5fc7232b 100644 --- a/vendor/github.com/chromedp/cdproto/cdp/types.go +++ b/vendor/github.com/chromedp/cdproto/cdp/types.go @@ -1,62 +1,22 @@ -package cdp +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package cdp import ( - "bytes" "context" "fmt" - "io" - "strconv" - "strings" - "sync" - "time" + "iter" - "github.com/chromedp/sysutil" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" ) -// Executor is the common interface for executing a command. -type Executor interface { - // Execute executes the command. - Execute(context.Context, string, any, any) error -} - -// contextKey is the context key type. -type contextKey int - -// context keys. -const ( - executorKey contextKey = iota -) - -// WithExecutor sets the message executor for the context. -func WithExecutor(parent context.Context, executor Executor) context.Context { - return context.WithValue(parent, executorKey, executor) -} - -// ExecutorFromContext returns the message executor for the context. -func ExecutorFromContext(ctx context.Context) Executor { - return ctx.Value(executorKey).(Executor) -} - -// Execute uses the context's message executor to send a command or event -// method marshaling the provided parameters, and unmarshaling to res. -func Execute(ctx context.Context, method string, params, res any) error { - if executor := ctx.Value(executorKey); executor != nil { - return executor.(Executor).Execute(ctx, method, params, res) - } - return ErrInvalidContext -} - -// Error is a error. +// Error is the type of the constant errors of this package. type Error string // Error values. const ( - // ErrInvalidContext is the invalid context error. - ErrInvalidContext Error = "invalid context" - - // ErrMsgMissingParamsOrResult is the msg missing params or result error. + // ErrMsgMissingParamsOrResult is the error for a message that has neither + // params nor a result. ErrMsgMissingParamsOrResult Error = "msg missing params or result" ) @@ -73,6 +33,87 @@ func (err ErrUnknownCommandOrEvent) Error() string { return fmt.Sprintf("unknown command or event %q", string(err)) } +// Empty is the parameters or the result of a command that has none. +type Empty struct{} + +// Command is a protocol command with the parameters P and the result R. The +// generated code has one value of this type for each command. +type Command[P, R any] struct { + // Method is the name of the command, such as "Page.navigate". + Method string +} + +// Event is a protocol event with the payload E. The generated code has one +// value of this type for each event. +type Event[E any] struct { + // Method is the name of the event, such as "Page.loadEventFired". + Method string +} + +// Session is a connection to a browser target, over which commands run and +// events arrive. +type Session interface { + // Call sends the command with the params, waits for the response, and decodes + // the result into result. Call returns an error from the browser as an + // error. + Call(ctx context.Context, method string, params, result any) error + + // Subscribe starts to buffer the events of the method, and returns the + // channel that they arrive on and a func that stops the subscription. A + // subscription starts when Subscribe returns, so no event that follows is + // lost. + Subscribe(method string) (events <-chan jsonv2.Value, cancel func()) +} + +// Call runs the command on the session, and returns its result. +func Call[P, R any](ctx context.Context, s Session, c Command[P, R], params P) (R, error) { + var res R + if err := s.Call(ctx, c.Method, params, &res); err != nil { + var zero R + return zero, err + } + return res, nil +} + +// Events subscribes to the event on the session and returns an iterator over +// the payloads. The session starts to buffer events when Events returns, not +// when the caller starts to range. A caller can therefore subscribe, trigger +// the event, and then range. +// +// The iterator stops when the caller breaks out of the loop or when the session +// closes. It also stops when the context ends, and it then yields the error of +// the context. A payload that does not decode yields the decode error and ends +// the iteration. +// +// A caller must range over the iterator or cancel the context. An iterator that +// nobody reads holds its subscription. +func Events[E any](ctx context.Context, s Session, e Event[E]) iter.Seq2[E, error] { + events, cancel := s.Subscribe(e.Method) + return func(yield func(E, error) bool) { + defer cancel() + var zero E + for { + select { + case <-ctx.Done(): + yield(zero, ctx.Err()) + return + case raw, ok := <-events: + if !ok { + return + } + var v E + if err := jsonv2.Unmarshal(raw, &v); err != nil { + yield(zero, fmt.Errorf("decoding %s: %w", e.Method, err)) + return + } + if !yield(v, nil) { + return + } + } + } + } +} + // BrowserContextID [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#type-BrowserContextID @@ -93,21 +134,6 @@ func (t NodeID) Int64() int64 { return int64(t) } -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *NodeID) UnmarshalJSON(buf []byte) error { - if l := len(buf); l > 2 && buf[0] == '"' && buf[l-1] == '"' { - buf = buf[1 : l-1] - } - - v, err := strconv.ParseInt(string(buf), 10, 64) - if err != nil { - return err - } - - *t = NodeID(v) - return nil -} - // BackendNodeID unique DOM node identifier used to reference a node that may // not have been pushed to the front-end. // @@ -119,21 +145,6 @@ func (t BackendNodeID) Int64() int64 { return int64(t) } -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *BackendNodeID) UnmarshalJSON(buf []byte) error { - if l := len(buf); l > 2 && buf[0] == '"' && buf[l-1] == '"' { - buf = buf[1 : l-1] - } - - v, err := strconv.ParseInt(string(buf), 10, 64) - if err != nil { - return err - } - - *t = BackendNodeID(v) - return nil -} - // StyleSheetID unique identifier for a CSS stylesheet. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#type-StyleSheetId @@ -148,7 +159,7 @@ func (t StyleSheetID) String() string { // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#type-BackendNode type BackendNode struct { - NodeType NodeType `json:"nodeType"` // Node's nodeType. + NodeType int64 `json:"nodeType"` // Node's nodeType. NodeName string `json:"nodeName"` // Node's nodeName. BackendNodeID BackendNodeID `json:"backendNodeId"` } @@ -211,106 +222,6 @@ const ( PseudoTypeSkeleton PseudoType = "skeleton" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *PseudoType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch PseudoType(s) { - case PseudoTypeFirstLine: - *t = PseudoTypeFirstLine - case PseudoTypeFirstLetter: - *t = PseudoTypeFirstLetter - case PseudoTypeCheckmark: - *t = PseudoTypeCheckmark - case PseudoTypeBefore: - *t = PseudoTypeBefore - case PseudoTypeAfter: - *t = PseudoTypeAfter - case PseudoTypeExpandIcon: - *t = PseudoTypeExpandIcon - case PseudoTypePickerIcon: - *t = PseudoTypePickerIcon - case PseudoTypeInterestButton: - *t = PseudoTypeInterestButton - case PseudoTypeMarker: - *t = PseudoTypeMarker - case PseudoTypeBackdrop: - *t = PseudoTypeBackdrop - case PseudoTypeColumn: - *t = PseudoTypeColumn - case PseudoTypeSelection: - *t = PseudoTypeSelection - case PseudoTypeSearchText: - *t = PseudoTypeSearchText - case PseudoTypeTargetText: - *t = PseudoTypeTargetText - case PseudoTypeSpellingError: - *t = PseudoTypeSpellingError - case PseudoTypeGrammarError: - *t = PseudoTypeGrammarError - case PseudoTypeHighlight: - *t = PseudoTypeHighlight - case PseudoTypeFirstLineInherited: - *t = PseudoTypeFirstLineInherited - case PseudoTypeScrollMarker: - *t = PseudoTypeScrollMarker - case PseudoTypeScrollMarkerGroup: - *t = PseudoTypeScrollMarkerGroup - case PseudoTypeScrollButton: - *t = PseudoTypeScrollButton - case PseudoTypeScrollbar: - *t = PseudoTypeScrollbar - case PseudoTypeScrollbarThumb: - *t = PseudoTypeScrollbarThumb - case PseudoTypeScrollbarButton: - *t = PseudoTypeScrollbarButton - case PseudoTypeScrollbarTrack: - *t = PseudoTypeScrollbarTrack - case PseudoTypeScrollbarTrackPiece: - *t = PseudoTypeScrollbarTrackPiece - case PseudoTypeScrollbarCorner: - *t = PseudoTypeScrollbarCorner - case PseudoTypeResizer: - *t = PseudoTypeResizer - case PseudoTypeInputListButton: - *t = PseudoTypeInputListButton - case PseudoTypeViewTransition: - *t = PseudoTypeViewTransition - case PseudoTypeViewTransitionGroup: - *t = PseudoTypeViewTransitionGroup - case PseudoTypeViewTransitionImagePair: - *t = PseudoTypeViewTransitionImagePair - case PseudoTypeViewTransitionGroupChildren: - *t = PseudoTypeViewTransitionGroupChildren - case PseudoTypeViewTransitionOld: - *t = PseudoTypeViewTransitionOld - case PseudoTypeViewTransitionNew: - *t = PseudoTypeViewTransitionNew - case PseudoTypePlaceholder: - *t = PseudoTypePlaceholder - case PseudoTypeFileSelectorButton: - *t = PseudoTypeFileSelectorButton - case PseudoTypeDetailsContent: - *t = PseudoTypeDetailsContent - case PseudoTypePicker: - *t = PseudoTypePicker - case PseudoTypeSelectListbox: - *t = PseudoTypeSelectListbox - case PseudoTypePermissionIcon: - *t = PseudoTypePermissionIcon - case PseudoTypeOverscrollAreaParent: - *t = PseudoTypeOverscrollAreaParent - case PseudoTypeOverscrollBackdrop: - *t = PseudoTypeOverscrollBackdrop - case PseudoTypeSkeleton: - *t = PseudoTypeSkeleton - default: - return fmt.Errorf("unknown PseudoType value: %v", s) - } - return nil -} - // ShadowRootType shadow root type. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#type-ShadowRootType @@ -328,24 +239,6 @@ const ( ShadowRootTypeClosed ShadowRootType = "closed" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ShadowRootType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ShadowRootType(s) { - case ShadowRootTypeUserAgent: - *t = ShadowRootTypeUserAgent - case ShadowRootTypeOpen: - *t = ShadowRootTypeOpen - case ShadowRootTypeClosed: - *t = ShadowRootTypeClosed - default: - return fmt.Errorf("unknown ShadowRootType value: %v", s) - } - return nil -} - // CompatibilityMode document compatibility mode. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#type-CompatibilityMode @@ -363,24 +256,6 @@ const ( CompatibilityModeNoQuirksMode CompatibilityMode = "NoQuirksMode" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CompatibilityMode) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CompatibilityMode(s) { - case CompatibilityModeQuirksMode: - *t = CompatibilityModeQuirksMode - case CompatibilityModeLimitedQuirksMode: - *t = CompatibilityModeLimitedQuirksMode - case CompatibilityModeNoQuirksMode: - *t = CompatibilityModeNoQuirksMode - default: - return fmt.Errorf("unknown CompatibilityMode value: %v", s) - } - return nil -} - // Node DOM interaction is implemented in terms of mirror objects that // represent the actual DOM nodes. DOMNode is a base node mirror type. // @@ -389,7 +264,7 @@ type Node struct { NodeID NodeID `json:"nodeId"` // Node identifier that is passed into the rest of the DOM messages as the nodeId. Backend will only push node with given id once. It is aware of all requested nodes and will only fire DOM events for nodes known to the client. ParentID NodeID `json:"parentId,omitempty,omitzero"` // The id of the parent node if any. BackendNodeID BackendNodeID `json:"backendNodeId"` // The BackendNodeId for this node. - NodeType NodeType `json:"nodeType"` // Node's nodeType. + NodeType int64 `json:"nodeType"` // Node's nodeType. NodeName string `json:"nodeName"` // Node's nodeName. LocalName string `json:"localName"` // Node's localName. NodeValue string `json:"nodeValue"` // Node's nodeValue. @@ -420,354 +295,16 @@ type Node struct { AffectedByStartingStyles bool `json:"affectedByStartingStyles"` AdoptedStyleSheets []StyleSheetID `json:"adoptedStyleSheets,omitempty,omitzero"` AdProvenance *AdProvenance `json:"adProvenance,omitempty,omitzero"` - Parent *Node `json:"-"` // Parent node. - Invalidated chan struct{} `json:"-"` // Invalidated channel. - State NodeState `json:"-"` // Node state. - sync.RWMutex `json:"-"` // Read write mutex. -} - -// AttributeValue returns the named attribute for the node. -func (n *Node) AttributeValue(name string) string { - value, _ := n.Attribute(name) - return value -} - -// Attribute returns the named attribute for the node and if it exists. -func (n *Node) Attribute(name string) (string, bool) { - n.RLock() - defer n.RUnlock() - - for i := 0; i < len(n.Attributes); i += 2 { - if n.Attributes[i] == name { - return n.Attributes[i+1], true - } - } - - return "", false -} - -// xpath builds the xpath string. -func (n *Node) xpath(stopAtDocument, stopAtID bool) string { - n.RLock() - defer n.RUnlock() - - p, pos, id := "", "", n.AttributeValue("id") - switch { - case n.Parent == nil: - return n.LocalName - - case stopAtDocument && n.NodeType == NodeTypeDocument: - return "" - - case stopAtID && id != "": - p = "/" - pos = `[@id='` + id + `']` - - case n.Parent != nil: - var i int - var found bool - - n.Parent.RLock() - for j := 0; j < len(n.Parent.Children); j++ { - if n.Parent.Children[j].LocalName == n.LocalName { - i++ - } - if n.Parent.Children[j].NodeID == n.NodeID { - found = true - break - } - } - n.Parent.RUnlock() - - if found { - pos = "[" + strconv.Itoa(i) + "]" - } - - p = n.Parent.xpath(stopAtDocument, stopAtID) - } - - localName := n.LocalName - if n.IsSVG { - localName = `*[local-name()='` + localName + `']` - } - return p + "/" + localName + pos -} - -// PartialXPathByID returns the partial XPath for the node, stopping at the -// first parent with an id attribute or at nearest parent document node. -func (n *Node) PartialXPathByID() string { - return n.xpath(true, true) -} - -// PartialXPath returns the partial XPath for the node, stopping at the nearest -// parent document node. -func (n *Node) PartialXPath() string { - return n.xpath(true, false) -} - -// FullXPathByID returns the full XPath for the node, stopping at the top most -// document root or at the closest parent node with an id attribute. -func (n *Node) FullXPathByID() string { - return n.xpath(false, true) -} - -// FullXPath returns the full XPath for the node, stopping only at the top most -// document root. -func (n *Node) FullXPath() string { - return n.xpath(false, false) -} - -// WriteTo writes a readable representation of the node and all its children to w. -func (n *Node) WriteTo(w io.Writer, prefix, indent string, nodeIDs bool) (int, error) { - if n == nil { - return w.Write([]byte(prefix + "")) - } - - n.RLock() - defer n.RUnlock() - - var err error - var nn, c int - - // prefix - if c, err = w.Write([]byte(prefix)); err != nil { - return nn + c, err - } - nn += c - - // node name - if n.LocalName != "" { - if c, err = w.Write([]byte(n.LocalName)); err != nil { - return nn + c, err - } - nn += c - } else { - if c, err = w.Write([]byte(n.NodeName)); err != nil { - return nn + c, err - } - nn += c - } - - // add #id - var hasID int - for i := 0; i < len(n.Attributes); i += 2 { - if strings.ToLower(n.Attributes[i]) == "id" { - if c, err = w.Write([]byte("#" + n.Attributes[i+1])); err != nil { - return nn + c, err - } - nn += c - hasID = 2 - break - } - } - - // node type - if n.NodeType != NodeTypeElement && n.NodeType != NodeTypeText { - if c, err = fmt.Fprintf(w, " <%s>", n.NodeType); err != nil { - return nn + c, err - } - nn += c - } - - // node value - if n.NodeType == NodeTypeText { - v := n.NodeValue - if len(v) > 15 { - v = v[:15] + "..." - } - if c, err = fmt.Fprintf(w, " %q", v); err != nil { - return nn + c, err - } - nn += c - } - - // attributes - if n.NodeType == NodeTypeElement && len(n.Attributes) > hasID { - if c, err = w.Write([]byte(" [")); err != nil { - return nn + c, err - } - nn += c - for i, space := 0, ""; i < len(n.Attributes); i += 2 { - if strings.ToLower(n.Attributes[i]) == "id" { - continue - } - if c, err = fmt.Fprintf(w, "%s%s=%q", space, n.Attributes[i], n.Attributes[i+1]); err != nil { - return nn + c, err - } - nn += c - if space == "" { - space = " " - } - } - if c, err = w.Write([]byte{']'}); err != nil { - return nn + c, err - } - nn += c - } - - // node id - if nodeIDs { - if c, err = fmt.Fprintf(w, " (%d)", n.NodeID); err != nil { - return nn + c, err - } - nn += c - } - - // children - for i := 0; i < len(n.Children); i++ { - if c, err = fmt.Fprintln(w); err != nil { - return nn + c, err - } - nn += c - if c, err = n.Children[i].WriteTo(w, prefix+indent, indent, nodeIDs); err != nil { - return nn + c, err - } - nn += c - } - return nn, nil -} - -// Dump builds a printable string representation of the node and its children. -func (n *Node) Dump(prefix, indent string, nodeIDs bool) string { - var buf bytes.Buffer - _, _ = n.WriteTo(&buf, prefix, indent, nodeIDs) - return buf.String() } -// NodeState is the state of a DOM node. -type NodeState uint8 - -// NodeState enum values. -const ( - NodeReady NodeState = 1 << (7 - iota) - NodeVisible - NodeHighlighted -) - -// nodeStateNames are the names of the node states. -var nodeStateNames = map[NodeState]string{ - NodeReady: "Ready", - NodeVisible: "Visible", - NodeHighlighted: "Highlighted", -} - -// String satisfies stringer interface. -func (ns NodeState) String() string { - var s []string - for k, v := range nodeStateNames { - if ns&k != 0 { - s = append(s, v) - } - } - return "[" + strings.Join(s, " ") + "]" -} - -// EmptyNodeID is the "non-existent" node id. -const EmptyNodeID = NodeID(0) - // RGBA a structure holding an RGBA color. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#type-RGBA type RGBA struct { - R int64 `json:"r"` // The red component, in the [0-255] range. - G int64 `json:"g"` // The green component, in the [0-255] range. - B int64 `json:"b"` // The blue component, in the [0-255] range. - A float64 `json:"a"` // The alpha component, in the [0-1] range (default: 1). -} - -// NodeType node type. -// -// See: https://developer.mozilla.org/en/docs/Web/API/Node/nodeType -type NodeType int64 - -// Int64 returns the NodeType as int64 value. -func (t NodeType) Int64() int64 { - return int64(t) -} - -// NodeType values. -const ( - NodeTypeElement NodeType = 1 - NodeTypeAttribute NodeType = 2 - NodeTypeText NodeType = 3 - NodeTypeCDATA NodeType = 4 - NodeTypeEntityReference NodeType = 5 - NodeTypeEntity NodeType = 6 - NodeTypeProcessingInstruction NodeType = 7 - NodeTypeComment NodeType = 8 - NodeTypeDocument NodeType = 9 - NodeTypeDocumentType NodeType = 10 - NodeTypeDocumentFragment NodeType = 11 - NodeTypeNotation NodeType = 12 -) - -// String satisfies the [fmt.Stringer] interface. -func (t NodeType) String() string { - switch t { - case NodeTypeElement: - return "Element" - case NodeTypeAttribute: - return "Attribute" - case NodeTypeText: - return "Text" - case NodeTypeCDATA: - return "CDATA" - case NodeTypeEntityReference: - return "EntityReference" - case NodeTypeEntity: - return "Entity" - case NodeTypeProcessingInstruction: - return "ProcessingInstruction" - case NodeTypeComment: - return "Comment" - case NodeTypeDocument: - return "Document" - case NodeTypeDocumentType: - return "DocumentType" - case NodeTypeDocumentFragment: - return "DocumentFragment" - case NodeTypeNotation: - return "Notation" - } - return fmt.Sprintf("NodeType(%d)", t) -} - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *NodeType) UnmarshalJSON(buf []byte) error { - s := string(buf) - v, err := strconv.ParseInt(s, 10, 64) - if err != nil { - return err - } - switch NodeType(v) { - case NodeTypeElement: - *t = NodeTypeElement - case NodeTypeAttribute: - *t = NodeTypeAttribute - case NodeTypeText: - *t = NodeTypeText - case NodeTypeCDATA: - *t = NodeTypeCDATA - case NodeTypeEntityReference: - *t = NodeTypeEntityReference - case NodeTypeEntity: - *t = NodeTypeEntity - case NodeTypeProcessingInstruction: - *t = NodeTypeProcessingInstruction - case NodeTypeComment: - *t = NodeTypeComment - case NodeTypeDocument: - *t = NodeTypeDocument - case NodeTypeDocumentType: - *t = NodeTypeDocumentType - case NodeTypeDocumentFragment: - *t = NodeTypeDocumentFragment - case NodeTypeNotation: - *t = NodeTypeNotation - default: - return fmt.Errorf("unknown NodeType value: %v", s) - } - return nil + R int64 `json:"r"` // The red component, in the [0-255] range. + G int64 `json:"g"` // The green component, in the [0-255] range. + B int64 `json:"b"` // The blue component, in the [0-255] range. + A float64 `json:"a,omitempty,omitzero"` // The alpha component, in the [0-1] range (default: 1). } // LoaderID unique loader identifier. @@ -783,63 +320,22 @@ func (t LoaderID) String() string { // TimeSinceEpoch UTC time in seconds, counted from January 1, 1970. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-TimeSinceEpoch -type TimeSinceEpoch time.Time - -// Time returns the TimeSinceEpoch as time.Time value. -func (t TimeSinceEpoch) Time() time.Time { - return time.Time(t) -} +type TimeSinceEpoch float64 -// MarshalJSON satisfies [json.Marshaler]. -func (t TimeSinceEpoch) MarshalJSON() ([]byte, error) { - v := float64(time.Time(t).UnixNano() / int64(time.Second)) - return strconv.AppendFloat(make([]byte, 0, 20), v, 'f', -1, 64), nil -} - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *TimeSinceEpoch) UnmarshalJSON(buf []byte) error { - f, err := strconv.ParseFloat(string(buf), 64) - if err != nil { - return err - } - *t = TimeSinceEpoch(time.Unix(0, int64(f*float64(time.Second)))) - return nil +// Float64 returns the TimeSinceEpoch as float64 value. +func (t TimeSinceEpoch) Float64() float64 { + return float64(t) } // MonotonicTime monotonically increasing time in seconds since an arbitrary // point in the past. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-MonotonicTime -type MonotonicTime time.Time - -// Time returns the MonotonicTime as time.Time value. -func (t MonotonicTime) Time() time.Time { - return time.Time(t) -} - -// MonotonicTimeEpoch is the MonotonicTime time epoch. -var MonotonicTimeEpoch *time.Time - -func init() { - // initialize epoch - bt := sysutil.BootTime() - MonotonicTimeEpoch = &bt -} - -// MarshalJSON satisfies [json.Marshaler]. -func (t MonotonicTime) MarshalJSON() ([]byte, error) { - v := float64(time.Time(t).Sub(*MonotonicTimeEpoch)) / float64(time.Second) - return strconv.AppendFloat(make([]byte, 0, 20), v, 'f', -1, 64), nil -} +type MonotonicTime float64 -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *MonotonicTime) UnmarshalJSON(buf []byte) error { - f, err := strconv.ParseFloat(string(buf), 64) - if err != nil { - return err - } - *t = MonotonicTime(MonotonicTimeEpoch.Add(time.Duration(f * float64(time.Second)))) - return nil +// Float64 returns the MonotonicTime as float64 value. +func (t MonotonicTime) Float64() float64 { + return float64(t) } // AdScriptIdentifier identifies the script on the stack that caused a @@ -873,34 +369,7 @@ type AdAncestry struct { // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-AdProvenance type AdProvenance struct { FilterlistRule string `json:"filterlistRule,omitempty,omitzero"` // The filterlist rule that matched, if any. - AdScriptAncestry *AdAncestry `json:"adScriptAncestry,omitempty,omitzero"` // The script ancestry that created the ad, if any. -} - -// TimeSinceEpochMilli special timestamp type for Response's responseTime -// field. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-TimeSinceEpochMilli -type TimeSinceEpochMilli time.Time - -// Time returns the TimeSinceEpochMilli as time.Time value. -func (t TimeSinceEpochMilli) Time() time.Time { - return time.Time(t) -} - -// MarshalJSON satisfies [json.Marshaler]. -func (t TimeSinceEpochMilli) MarshalJSON() ([]byte, error) { - v := float64(time.Time(t).UnixNano() / int64(time.Millisecond)) - return strconv.AppendFloat(make([]byte, 0, 20), v, 'f', -1, 64), nil -} - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *TimeSinceEpochMilli) UnmarshalJSON(buf []byte) error { - f, err := strconv.ParseFloat(string(buf), 64) - if err != nil { - return err - } - *t = TimeSinceEpochMilli(time.Unix(0, int64(f*float64(time.Millisecond)))) - return nil + AdScriptAncestry *AdAncestry `json:"adScriptAncestry,omitempty,omitzero"` // The script ancestry that created the ad, if any. Note: depending on the context, this may represent the full ancestry up to the root script, or it may contain only one script representing the immediate ancestor. } // FrameID unique frame identifier. @@ -913,16 +382,6 @@ func (t FrameID) String() string { return string(t) } -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *FrameID) UnmarshalJSON(buf []byte) error { - if l := len(buf); l > 2 && buf[0] == '"' && buf[l-1] == '"' { - buf = buf[1 : l-1] - } - - *t = FrameID(buf) - return nil -} - // AdFrameType indicates whether a frame has been identified as an ad. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-AdFrameType @@ -940,24 +399,6 @@ const ( AdFrameTypeRoot AdFrameType = "root" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *AdFrameType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch AdFrameType(s) { - case AdFrameTypeNone: - *t = AdFrameTypeNone - case AdFrameTypeChild: - *t = AdFrameTypeChild - case AdFrameTypeRoot: - *t = AdFrameTypeRoot - default: - return fmt.Errorf("unknown AdFrameType value: %v", s) - } - return nil -} - // AdFrameExplanation [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-AdFrameExplanation @@ -975,24 +416,6 @@ const ( AdFrameExplanationMatchedBlockingRule AdFrameExplanation = "MatchedBlockingRule" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *AdFrameExplanation) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch AdFrameExplanation(s) { - case AdFrameExplanationParentIsAd: - *t = AdFrameExplanationParentIsAd - case AdFrameExplanationCreatedByAdScript: - *t = AdFrameExplanationCreatedByAdScript - case AdFrameExplanationMatchedBlockingRule: - *t = AdFrameExplanationMatchedBlockingRule - default: - return fmt.Errorf("unknown AdFrameExplanation value: %v", s) - } - return nil -} - // AdFrameStatus indicates whether a frame has been identified as an ad and // why. // @@ -1021,26 +444,6 @@ const ( SecureContextTypeInsecureAncestor SecureContextType = "InsecureAncestor" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SecureContextType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SecureContextType(s) { - case SecureContextTypeSecure: - *t = SecureContextTypeSecure - case SecureContextTypeSecureLocalhost: - *t = SecureContextTypeSecureLocalhost - case SecureContextTypeInsecureScheme: - *t = SecureContextTypeInsecureScheme - case SecureContextTypeInsecureAncestor: - *t = SecureContextTypeInsecureAncestor - default: - return fmt.Errorf("unknown SecureContextType value: %v", s) - } - return nil -} - // CrossOriginIsolatedContextType indicates whether the frame is cross-origin // isolated and why it is the case. // @@ -1059,24 +462,6 @@ const ( CrossOriginIsolatedContextTypeNotIsolatedFeatureDisabled CrossOriginIsolatedContextType = "NotIsolatedFeatureDisabled" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CrossOriginIsolatedContextType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CrossOriginIsolatedContextType(s) { - case CrossOriginIsolatedContextTypeIsolated: - *t = CrossOriginIsolatedContextTypeIsolated - case CrossOriginIsolatedContextTypeNotIsolated: - *t = CrossOriginIsolatedContextTypeNotIsolated - case CrossOriginIsolatedContextTypeNotIsolatedFeatureDisabled: - *t = CrossOriginIsolatedContextTypeNotIsolatedFeatureDisabled - default: - return fmt.Errorf("unknown CrossOriginIsolatedContextType value: %v", s) - } - return nil -} - // GatedAPIFeatures [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-GatedAPIFeatures @@ -1095,26 +480,6 @@ const ( GatedAPIFeaturesPerformanceProfile GatedAPIFeatures = "PerformanceProfile" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *GatedAPIFeatures) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch GatedAPIFeatures(s) { - case GatedAPIFeaturesSharedArrayBuffers: - *t = GatedAPIFeaturesSharedArrayBuffers - case GatedAPIFeaturesSharedArrayBuffersTransferAllowed: - *t = GatedAPIFeaturesSharedArrayBuffersTransferAllowed - case GatedAPIFeaturesPerformanceMeasureMemory: - *t = GatedAPIFeaturesPerformanceMeasureMemory - case GatedAPIFeaturesPerformanceProfile: - *t = GatedAPIFeaturesPerformanceProfile - default: - return fmt.Errorf("unknown GatedAPIFeatures value: %v", s) - } - return nil -} - // OriginTrialTokenStatus origin // Trial(https://www.chromium.org/blink/origin-trials) support. Status for an // Origin Trial token. @@ -1143,42 +508,6 @@ const ( OriginTrialTokenStatusUnknownTrial OriginTrialTokenStatus = "UnknownTrial" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *OriginTrialTokenStatus) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch OriginTrialTokenStatus(s) { - case OriginTrialTokenStatusSuccess: - *t = OriginTrialTokenStatusSuccess - case OriginTrialTokenStatusNotSupported: - *t = OriginTrialTokenStatusNotSupported - case OriginTrialTokenStatusInsecure: - *t = OriginTrialTokenStatusInsecure - case OriginTrialTokenStatusExpired: - *t = OriginTrialTokenStatusExpired - case OriginTrialTokenStatusWrongOrigin: - *t = OriginTrialTokenStatusWrongOrigin - case OriginTrialTokenStatusInvalidSignature: - *t = OriginTrialTokenStatusInvalidSignature - case OriginTrialTokenStatusMalformed: - *t = OriginTrialTokenStatusMalformed - case OriginTrialTokenStatusWrongVersion: - *t = OriginTrialTokenStatusWrongVersion - case OriginTrialTokenStatusFeatureDisabled: - *t = OriginTrialTokenStatusFeatureDisabled - case OriginTrialTokenStatusTokenDisabled: - *t = OriginTrialTokenStatusTokenDisabled - case OriginTrialTokenStatusFeatureDisabledForUser: - *t = OriginTrialTokenStatusFeatureDisabledForUser - case OriginTrialTokenStatusUnknownTrial: - *t = OriginTrialTokenStatusUnknownTrial - default: - return fmt.Errorf("unknown OriginTrialTokenStatus value: %v", s) - } - return nil -} - // OriginTrialStatus status for an Origin Trial. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-OriginTrialStatus @@ -1197,26 +526,6 @@ const ( OriginTrialStatusTrialNotAllowed OriginTrialStatus = "TrialNotAllowed" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *OriginTrialStatus) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch OriginTrialStatus(s) { - case OriginTrialStatusEnabled: - *t = OriginTrialStatusEnabled - case OriginTrialStatusValidTokenNotProvided: - *t = OriginTrialStatusValidTokenNotProvided - case OriginTrialStatusOSNotSupported: - *t = OriginTrialStatusOSNotSupported - case OriginTrialStatusTrialNotAllowed: - *t = OriginTrialStatusTrialNotAllowed - default: - return fmt.Errorf("unknown OriginTrialStatus value: %v", s) - } - return nil -} - // OriginTrialUsageRestriction [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-OriginTrialUsageRestriction @@ -1233,22 +542,6 @@ const ( OriginTrialUsageRestrictionSubset OriginTrialUsageRestriction = "Subset" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *OriginTrialUsageRestriction) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch OriginTrialUsageRestriction(s) { - case OriginTrialUsageRestrictionNone: - *t = OriginTrialUsageRestrictionNone - case OriginTrialUsageRestrictionSubset: - *t = OriginTrialUsageRestrictionSubset - default: - return fmt.Errorf("unknown OriginTrialUsageRestriction value: %v", s) - } - return nil -} - // OriginTrialToken [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-OriginTrialToken @@ -1256,7 +549,7 @@ type OriginTrialToken struct { Origin string `json:"origin"` MatchSubDomains bool `json:"matchSubDomains"` TrialName string `json:"trialName"` - ExpiryTime *TimeSinceEpoch `json:"expiryTime"` + ExpiryTime TimeSinceEpoch `json:"expiryTime"` IsThirdParty bool `json:"isThirdParty"` UsageRestriction OriginTrialUsageRestriction `json:"usageRestriction"` } @@ -1306,49 +599,8 @@ type Frame struct { SecureContextType SecureContextType `json:"secureContextType"` // Indicates whether the main document is a secure context and explains why that is the case. CrossOriginIsolatedContextType CrossOriginIsolatedContextType `json:"crossOriginIsolatedContextType"` // Indicates whether this is a cross origin isolated context. GatedAPIFeatures []GatedAPIFeatures `json:"gatedAPIFeatures"` // Indicated which gated APIs / features are available. - State FrameState `json:"-"` // Frame state. - Root *Node `json:"-"` // Frame document root. - Nodes map[NodeID]*Node `json:"-"` // Frame nodes. - sync.RWMutex `json:"-"` // Read write mutex. -} - -// FrameState is the state of a Frame. -type FrameState uint16 - -// FrameState enum values. -const ( - FrameDOMContentEventFired FrameState = 1 << (15 - iota) - FrameLoadEventFired - FrameAttached - FrameNavigated - FrameLoading - FrameScheduledNavigation -) - -// frameStateNames are the names of the frame states. -var frameStateNames = map[FrameState]string{ - FrameDOMContentEventFired: "DOMContentEventFired", - FrameLoadEventFired: "LoadEventFired", - FrameAttached: "Attached", - FrameNavigated: "Navigated", - FrameLoading: "Loading", - FrameScheduledNavigation: "ScheduledNavigation", -} - -// String satisfies stringer interface. -func (fs FrameState) String() string { - var s []string - for k, v := range frameStateNames { - if fs&k != 0 { - s = append(s, v) - } - } - return "[" + strings.Join(s, " ") + "]" } -// EmptyFrameID is the "non-existent" frame id. -const EmptyFrameID = FrameID("") - // ScriptID unique script identifier. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#type-ScriptId diff --git a/vendor/github.com/chromedp/cdproto/cdproto.go b/vendor/github.com/chromedp/cdproto/cdproto.go index c2e6df1ed..6f1c54ddb 100644 --- a/vendor/github.com/chromedp/cdproto/cdproto.go +++ b/vendor/github.com/chromedp/cdproto/cdproto.go @@ -1,13 +1,13 @@ -// Package cdproto provides the Chrome DevTools Protocol -// commands, types, and events for the cdproto domain. -// -// Chrome DevTools Protocol types. +// Code generated by pdlgen. DO NOT EDIT. + +// Package cdproto holds the types of the Chrome DevTools Protocol that no +// domain owns: the message that a connection sends and reads, the error that +// the browser returns and the type of a method name. The sub-packages hold the +// domains, and the package cdp holds the typed API. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package cdproto -// Code generated by cdproto-gen. DO NOT EDIT. - import ( "fmt" "strings" @@ -23,6 +23,7 @@ import ( "github.com/chromedp/cdproto/cachestorage" "github.com/chromedp/cdproto/cast" "github.com/chromedp/cdproto/cdp" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" "github.com/chromedp/cdproto/crashreportcontext" "github.com/chromedp/cdproto/css" "github.com/chromedp/cdproto/debugger" @@ -39,6 +40,7 @@ import ( "github.com/chromedp/cdproto/fedcm" "github.com/chromedp/cdproto/fetch" "github.com/chromedp/cdproto/filesystem" + "github.com/chromedp/cdproto/findinpage" "github.com/chromedp/cdproto/headlessexperimental" "github.com/chromedp/cdproto/heapprofiler" "github.com/chromedp/cdproto/indexeddb" @@ -69,12 +71,10 @@ import ( "github.com/chromedp/cdproto/webaudio" "github.com/chromedp/cdproto/webauthn" "github.com/chromedp/cdproto/webmcp" - jsonv2 "github.com/go-json-experiment/json" - "github.com/go-json-experiment/json/jsontext" ) -// MethodType chrome DevTools Protocol method type (ie, event and command -// names). +// MethodType chrome DevTools Protocol method type (that is, event and +// command names). type MethodType string // String returns the MethodType as string value. @@ -100,6 +100,7 @@ const ( EventAccessibilityLoadComplete = "Accessibility.loadComplete" EventAccessibilityNodesUpdated = "Accessibility.nodesUpdated" CommandAdsGetAdMetrics = ads.CommandGetAdMetrics + CommandAdsGetAdScripts = ads.CommandGetAdScripts CommandAnimationDisable = animation.CommandDisable CommandAnimationEnable = animation.CommandEnable CommandAnimationGetCurrentTime = animation.CommandGetCurrentTime @@ -157,6 +158,7 @@ const ( CommandBrowserCrashGPUProcess = browser.CommandCrashGPUProcess CommandBrowserGetVersion = browser.CommandGetVersion CommandBrowserGetBrowserCommandLine = browser.CommandGetBrowserCommandLine + CommandBrowserAddMockCamera = browser.CommandAddMockCamera CommandBrowserGetHistograms = browser.CommandGetHistograms CommandBrowserGetHistogram = browser.CommandGetHistogram CommandBrowserGetWindowBounds = browser.CommandGetWindowBounds @@ -166,6 +168,8 @@ const ( CommandBrowserSetDockTile = browser.CommandSetDockTile CommandBrowserExecuteBrowserCommand = browser.CommandExecuteBrowserCommand CommandBrowserAddPrivacySandboxEnrollmentOverride = browser.CommandAddPrivacySandboxEnrollmentOverride + CommandBrowserGetGlobalPrivacyControl = browser.CommandGetGlobalPrivacyControl + CommandBrowserSetGlobalPrivacyControl = browser.CommandSetGlobalPrivacyControl EventBrowserDownloadWillBegin = "Browser.downloadWillBegin" EventBrowserDownloadProgress = "Browser.downloadProgress" CommandCSSAddRule = css.CommandAddRule @@ -175,6 +179,7 @@ const ( CommandCSSEnable = css.CommandEnable CommandCSSForcePseudoState = css.CommandForcePseudoState CommandCSSForceStartingStyle = css.CommandForceStartingStyle + CommandCSSForcePositionTryOption = css.CommandForcePositionTryOption CommandCSSGetBackgroundColors = css.CommandGetBackgroundColors CommandCSSGetComputedStyleForNode = css.CommandGetComputedStyleForNode CommandCSSResolveValues = css.CommandResolveValues @@ -275,6 +280,10 @@ const ( CommandDOMGetQueryingDescendantsForContainer = dom.CommandGetQueryingDescendantsForContainer CommandDOMGetAnchorElement = dom.CommandGetAnchorElement CommandDOMForceShowPopover = dom.CommandForceShowPopover + CommandDOMGetImplicitAnchorCandidates = dom.CommandGetImplicitAnchorCandidates + CommandDOMForceShowInterest = dom.CommandForceShowInterest + CommandDOMSetTextMarker = dom.CommandSetTextMarker + CommandDOMClearTextMarkers = dom.CommandClearTextMarkers EventDOMAttributeModified = "DOM.attributeModified" EventDOMAdoptedStyleSheetsModified = "DOM.adoptedStyleSheetsModified" EventDOMAttributeRemoved = "DOM.attributeRemoved" @@ -340,7 +349,6 @@ const ( CommandDebuggerSetBreakpointsActive = debugger.CommandSetBreakpointsActive CommandDebuggerSetPauseOnExceptions = debugger.CommandSetPauseOnExceptions CommandDebuggerSetReturnValue = debugger.CommandSetReturnValue - CommandDebuggerSetScriptSource = debugger.CommandSetScriptSource CommandDebuggerSetSkipAllPauses = debugger.CommandSetSkipAllPauses CommandDebuggerSetVariableValue = debugger.CommandSetVariableValue CommandDebuggerStepInto = debugger.CommandStepInto @@ -366,6 +374,7 @@ const ( CommandEmulationSetCPUThrottlingRate = emulation.CommandSetCPUThrottlingRate CommandEmulationSetDefaultBackgroundColorOverride = emulation.CommandSetDefaultBackgroundColorOverride CommandEmulationSetSafeAreaInsetsOverride = emulation.CommandSetSafeAreaInsetsOverride + CommandEmulationSetVirtualKeyboardGeometryOverride = emulation.CommandSetVirtualKeyboardGeometryOverride CommandEmulationSetDeviceMetricsOverride = emulation.CommandSetDeviceMetricsOverride CommandEmulationSetDevicePostureOverride = emulation.CommandSetDevicePostureOverride CommandEmulationClearDevicePostureOverride = emulation.CommandClearDevicePostureOverride @@ -394,6 +403,7 @@ const ( CommandEmulationSetDisabledImageTypes = emulation.CommandSetDisabledImageTypes CommandEmulationSetDataSaverOverride = emulation.CommandSetDataSaverOverride CommandEmulationSetHardwareConcurrencyOverride = emulation.CommandSetHardwareConcurrencyOverride + CommandEmulationSetCPUPerformanceOverride = emulation.CommandSetCPUPerformanceOverride CommandEmulationSetUserAgentOverride = emulation.CommandSetUserAgentOverride CommandEmulationSetAutomationOverride = emulation.CommandSetAutomationOverride CommandEmulationSetSmallViewportHeightDifferenceOverride = emulation.CommandSetSmallViewportHeightDifferenceOverride @@ -436,6 +446,10 @@ const ( EventFetchRequestPaused = "Fetch.requestPaused" EventFetchAuthRequired = "Fetch.authRequired" CommandFileSystemGetDirectory = filesystem.CommandGetDirectory + CommandFindInPageFindFirst = findinpage.CommandFindFirst + CommandFindInPageFindNext = findinpage.CommandFindNext + CommandFindInPageFindPrev = findinpage.CommandFindPrev + CommandFindInPageStop = findinpage.CommandStop CommandHeadlessExperimentalBeginFrame = headlessexperimental.CommandBeginFrame CommandHeapProfilerAddInspectedHeapObject = heapprofiler.CommandAddInspectedHeapObject CommandHeapProfilerCollectGarbage = heapprofiler.CommandCollectGarbage @@ -456,7 +470,6 @@ const ( EventHeapProfilerResetProfiles = "HeapProfiler.resetProfiles" CommandIOClose = io.CommandClose CommandIORead = io.CommandRead - CommandIOResolveBlob = io.CommandResolveBlob CommandIndexedDBClearObjectStore = indexeddb.CommandClearObjectStore CommandIndexedDBDeleteDatabase = indexeddb.CommandDeleteDatabase CommandIndexedDBDeleteObjectStoreEntries = indexeddb.CommandDeleteObjectStoreEntries @@ -521,8 +534,6 @@ const ( CommandMemoryGetAllTimeSamplingProfile = memory.CommandGetAllTimeSamplingProfile CommandMemoryGetBrowserSamplingProfile = memory.CommandGetBrowserSamplingProfile CommandMemoryGetSamplingProfile = memory.CommandGetSamplingProfile - CommandNetworkSetAcceptedEncodings = network.CommandSetAcceptedEncodings - CommandNetworkClearAcceptedEncodingsOverride = network.CommandClearAcceptedEncodingsOverride CommandNetworkClearBrowserCache = network.CommandClearBrowserCache CommandNetworkClearBrowserCookies = network.CommandClearBrowserCookies CommandNetworkDeleteCookies = network.CommandDeleteCookies @@ -535,8 +546,6 @@ const ( CommandNetworkGetCookies = network.CommandGetCookies CommandNetworkGetResponseBody = network.CommandGetResponseBody CommandNetworkGetRequestPostData = network.CommandGetRequestPostData - CommandNetworkGetResponseBodyForInterception = network.CommandGetResponseBodyForInterception - CommandNetworkTakeResponseBodyForInterceptionAsStream = network.CommandTakeResponseBodyForInterceptionAsStream CommandNetworkReplayXHR = network.CommandReplayXHR CommandNetworkSearchInResponseBody = network.CommandSearchInResponseBody CommandNetworkSetBlockedURLs = network.CommandSetBlockedURLs @@ -648,7 +657,10 @@ const ( CommandPageGetAppManifest = page.CommandGetAppManifest CommandPageGetInstallabilityErrors = page.CommandGetInstallabilityErrors CommandPageGetAppID = page.CommandGetAppID + CommandPageGetSubApps = page.CommandGetSubApps + CommandPageGetSiblingSubApps = page.CommandGetSiblingSubApps CommandPageGetAdScriptAncestry = page.CommandGetAdScriptAncestry + CommandPageGetSpellCheckCustomDictionary = page.CommandGetSpellCheckCustomDictionary CommandPageGetFrameTree = page.CommandGetFrameTree CommandPageGetLayoutMetrics = page.CommandGetLayoutMetrics CommandPageGetNavigationHistory = page.CommandGetNavigationHistory @@ -672,6 +684,8 @@ const ( CommandPageSetDocumentContent = page.CommandSetDocumentContent CommandPageSetLifecycleEventsEnabled = page.CommandSetLifecycleEventsEnabled CommandPageStartScreencast = page.CommandStartScreencast + CommandPageStartScreenRecording = page.CommandStartScreenRecording + CommandPageStopScreenRecording = page.CommandStopScreenRecording CommandPageStopLoading = page.CommandStopLoading CommandPageCrash = page.CommandCrash CommandPageClose = page.CommandClose @@ -687,6 +701,7 @@ const ( CommandPageSetInterceptFileChooserDialog = page.CommandSetInterceptFileChooserDialog CommandPageSetPrerenderingAllowed = page.CommandSetPrerenderingAllowed CommandPageGetAnnotatedPageContent = page.CommandGetAnnotatedPageContent + CommandPageSetInputVisualization = page.CommandSetInputVisualization EventPageDomContentEventFired = "Page.domContentEventFired" EventPageFileChooserOpened = "Page.fileChooserOpened" EventPageFrameAttached = "Page.frameAttached" @@ -830,25 +845,21 @@ const ( CommandStorageUntrackIndexedDBForStorageKey = storage.CommandUntrackIndexedDBForStorageKey CommandStorageGetTrustTokens = storage.CommandGetTrustTokens CommandStorageClearTrustTokens = storage.CommandClearTrustTokens - CommandStorageGetSharedStorageMetadata = storage.CommandGetSharedStorageMetadata - CommandStorageGetSharedStorageEntries = storage.CommandGetSharedStorageEntries - CommandStorageSetSharedStorageEntry = storage.CommandSetSharedStorageEntry - CommandStorageDeleteSharedStorageEntry = storage.CommandDeleteSharedStorageEntry - CommandStorageClearSharedStorageEntries = storage.CommandClearSharedStorageEntries - CommandStorageResetSharedStorageBudget = storage.CommandResetSharedStorageBudget - CommandStorageSetSharedStorageTracking = storage.CommandSetSharedStorageTracking + CommandStorageGetPrivateVerificationTokens = storage.CommandGetPrivateVerificationTokens + CommandStorageGetPrivateVerificationTokensIssuerConfigs = storage.CommandGetPrivateVerificationTokensIssuerConfigs + CommandStorageClearPrivateVerificationTokens = storage.CommandClearPrivateVerificationTokens + CommandStorageDeletePrivateVerificationToken = storage.CommandDeletePrivateVerificationToken + CommandStorageSetPrivateVerificationTokensTracking = storage.CommandSetPrivateVerificationTokensTracking CommandStorageSetStorageBucketTracking = storage.CommandSetStorageBucketTracking CommandStorageDeleteStorageBucket = storage.CommandDeleteStorageBucket CommandStorageRunBounceTrackingMitigations = storage.CommandRunBounceTrackingMitigations - CommandStorageGetRelatedWebsiteSets = storage.CommandGetRelatedWebsiteSets EventStorageCacheStorageContentUpdated = "Storage.cacheStorageContentUpdated" EventStorageCacheStorageListUpdated = "Storage.cacheStorageListUpdated" EventStorageIndexedDBContentUpdated = "Storage.indexedDBContentUpdated" EventStorageIndexedDBListUpdated = "Storage.indexedDBListUpdated" - EventStorageSharedStorageAccessed = "Storage.sharedStorageAccessed" - EventStorageSharedStorageWorkletOperationExecutionFinished = "Storage.sharedStorageWorkletOperationExecutionFinished" EventStorageStorageBucketCreatedOrUpdated = "Storage.storageBucketCreatedOrUpdated" EventStorageStorageBucketDeleted = "Storage.storageBucketDeleted" + EventStoragePrivateVerificationTokensUpdated = "Storage.privateVerificationTokensUpdated" CommandSystemInfoGetInfo = systeminfo.CommandGetInfo CommandSystemInfoGetFeatureState = systeminfo.CommandGetFeatureState CommandSystemInfoGetProcessInfo = systeminfo.CommandGetProcessInfo @@ -943,14 +954,14 @@ func (e *Error) Error() string { return fmt.Sprintf("%s (%d)", e.Message, e.Code) } -// Message chrome DevTools Protocol message sent/read over websocket -// connection. +// Message chrome DevTools Protocol message that the websocket connection +// sends or reads. type Message struct { ID int64 `json:"id,omitempty,omitzero"` // Unique message identifier. SessionID target.SessionID `json:"sessionId,omitempty,omitzero"` // Session that the message belongs to when using flat access. Method MethodType `json:"method,omitempty,omitzero"` // Event or command type. - Params jsontext.Value `json:"params,omitempty,omitzero"` // Event or command parameters. - Result jsontext.Value `json:"result,omitempty,omitzero"` // Command return values. + Params jsonv2.Value `json:"params,omitempty,omitzero"` // Event or command parameters. + Result jsonv2.Value `json:"result,omitempty,omitzero"` // Command return values. Error *Error `json:"error,omitempty,omitzero"` // Error message. } @@ -967,35 +978,37 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandAccessibilityEnable: return emptyVal, nil case CommandAccessibilityGetPartialAXTree: - v = new(accessibility.GetPartialAXTreeReturns) + v = new(accessibility.GetPartialAXTreeResult) case CommandAccessibilityGetFullAXTree: - v = new(accessibility.GetFullAXTreeReturns) + v = new(accessibility.GetFullAXTreeResult) case CommandAccessibilityGetRootAXNode: - v = new(accessibility.GetRootAXNodeReturns) + v = new(accessibility.GetRootAXNodeResult) case CommandAccessibilityGetAXNodeAndAncestors: - v = new(accessibility.GetAXNodeAndAncestorsReturns) + v = new(accessibility.GetAXNodeAndAncestorsResult) case CommandAccessibilityGetChildAXNodes: - v = new(accessibility.GetChildAXNodesReturns) + v = new(accessibility.GetChildAXNodesResult) case CommandAccessibilityQueryAXTree: - v = new(accessibility.QueryAXTreeReturns) + v = new(accessibility.QueryAXTreeResult) case EventAccessibilityLoadComplete: v = new(accessibility.EventLoadComplete) case EventAccessibilityNodesUpdated: v = new(accessibility.EventNodesUpdated) case CommandAdsGetAdMetrics: - v = new(ads.GetAdMetricsReturns) + v = new(ads.GetAdMetricsResult) + case CommandAdsGetAdScripts: + v = new(ads.GetAdScriptsResult) case CommandAnimationDisable: return emptyVal, nil case CommandAnimationEnable: return emptyVal, nil case CommandAnimationGetCurrentTime: - v = new(animation.GetCurrentTimeReturns) + v = new(animation.GetCurrentTimeResult) case CommandAnimationGetPlaybackRate: - v = new(animation.GetPlaybackRateReturns) + v = new(animation.GetPlaybackRateResult) case CommandAnimationReleaseAnimations: return emptyVal, nil case CommandAnimationResolveAnimation: - v = new(animation.ResolveAnimationReturns) + v = new(animation.ResolveAnimationResult) case CommandAnimationSeekAnimations: return emptyVal, nil case CommandAnimationSetPaused: @@ -1013,13 +1026,13 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case EventAnimationAnimationUpdated: v = new(animation.EventAnimationUpdated) case CommandAuditsGetEncodedResponse: - v = new(audits.GetEncodedResponseReturns) + v = new(audits.GetEncodedResponseResult) case CommandAuditsDisable: return emptyVal, nil case CommandAuditsEnable: return emptyVal, nil case CommandAuditsCheckFormsIssues: - v = new(audits.CheckFormsIssuesReturns) + v = new(audits.CheckFormsIssuesResult) case EventAuditsIssueAdded: v = new(audits.EventIssueAdded) case CommandAutofillTrigger: @@ -1061,15 +1074,15 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandBluetoothEmulationSimulateDescriptorOperationResponse: return emptyVal, nil case CommandBluetoothEmulationAddService: - v = new(bluetoothemulation.AddServiceReturns) + v = new(bluetoothemulation.AddServiceResult) case CommandBluetoothEmulationRemoveService: return emptyVal, nil case CommandBluetoothEmulationAddCharacteristic: - v = new(bluetoothemulation.AddCharacteristicReturns) + v = new(bluetoothemulation.AddCharacteristicResult) case CommandBluetoothEmulationRemoveCharacteristic: return emptyVal, nil case CommandBluetoothEmulationAddDescriptor: - v = new(bluetoothemulation.AddDescriptorReturns) + v = new(bluetoothemulation.AddDescriptorResult) case CommandBluetoothEmulationRemoveDescriptor: return emptyVal, nil case CommandBluetoothEmulationSimulateGATTDisconnection: @@ -1095,17 +1108,19 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandBrowserCrashGPUProcess: return emptyVal, nil case CommandBrowserGetVersion: - v = new(browser.GetVersionReturns) + v = new(browser.GetVersionResult) case CommandBrowserGetBrowserCommandLine: - v = new(browser.GetBrowserCommandLineReturns) + v = new(browser.GetBrowserCommandLineResult) + case CommandBrowserAddMockCamera: + return emptyVal, nil case CommandBrowserGetHistograms: - v = new(browser.GetHistogramsReturns) + v = new(browser.GetHistogramsResult) case CommandBrowserGetHistogram: - v = new(browser.GetHistogramReturns) + v = new(browser.GetHistogramResult) case CommandBrowserGetWindowBounds: - v = new(browser.GetWindowBoundsReturns) + v = new(browser.GetWindowBoundsResult) case CommandBrowserGetWindowForTarget: - v = new(browser.GetWindowForTargetReturns) + v = new(browser.GetWindowForTargetResult) case CommandBrowserSetWindowBounds: return emptyVal, nil case CommandBrowserSetContentsSize: @@ -1116,16 +1131,20 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { return emptyVal, nil case CommandBrowserAddPrivacySandboxEnrollmentOverride: return emptyVal, nil + case CommandBrowserGetGlobalPrivacyControl: + v = new(browser.GetGlobalPrivacyControlResult) + case CommandBrowserSetGlobalPrivacyControl: + v = new(browser.SetGlobalPrivacyControlResult) case EventBrowserDownloadWillBegin: v = new(browser.EventDownloadWillBegin) case EventBrowserDownloadProgress: v = new(browser.EventDownloadProgress) case CommandCSSAddRule: - v = new(css.AddRuleReturns) + v = new(css.AddRuleResult) case CommandCSSCollectClassNames: - v = new(css.CollectClassNamesReturns) + v = new(css.CollectClassNamesResult) case CommandCSSCreateStyleSheet: - v = new(css.CreateStyleSheetReturns) + v = new(css.CreateStyleSheetResult) case CommandCSSDisable: return emptyVal, nil case CommandCSSEnable: @@ -1134,66 +1153,68 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { return emptyVal, nil case CommandCSSForceStartingStyle: return emptyVal, nil + case CommandCSSForcePositionTryOption: + return emptyVal, nil case CommandCSSGetBackgroundColors: - v = new(css.GetBackgroundColorsReturns) + v = new(css.GetBackgroundColorsResult) case CommandCSSGetComputedStyleForNode: - v = new(css.GetComputedStyleForNodeReturns) + v = new(css.GetComputedStyleForNodeResult) case CommandCSSResolveValues: - v = new(css.ResolveValuesReturns) + v = new(css.ResolveValuesResult) case CommandCSSGetLonghandProperties: - v = new(css.GetLonghandPropertiesReturns) + v = new(css.GetLonghandPropertiesResult) case CommandCSSGetInlineStylesForNode: - v = new(css.GetInlineStylesForNodeReturns) + v = new(css.GetInlineStylesForNodeResult) case CommandCSSGetAnimatedStylesForNode: - v = new(css.GetAnimatedStylesForNodeReturns) + v = new(css.GetAnimatedStylesForNodeResult) case CommandCSSGetMatchedStylesForNode: - v = new(css.GetMatchedStylesForNodeReturns) + v = new(css.GetMatchedStylesForNodeResult) case CommandCSSGetEnvironmentVariables: - v = new(css.GetEnvironmentVariablesReturns) + v = new(css.GetEnvironmentVariablesResult) case CommandCSSGetMediaQueries: - v = new(css.GetMediaQueriesReturns) + v = new(css.GetMediaQueriesResult) case CommandCSSGetPlatformFontsForNode: - v = new(css.GetPlatformFontsForNodeReturns) + v = new(css.GetPlatformFontsForNodeResult) case CommandCSSGetStyleSheetText: - v = new(css.GetStyleSheetTextReturns) + v = new(css.GetStyleSheetTextResult) case CommandCSSGetLayersForNode: - v = new(css.GetLayersForNodeReturns) + v = new(css.GetLayersForNodeResult) case CommandCSSGetLocationForSelector: - v = new(css.GetLocationForSelectorReturns) + v = new(css.GetLocationForSelectorResult) case CommandCSSTrackComputedStyleUpdatesForNode: return emptyVal, nil case CommandCSSTrackComputedStyleUpdates: return emptyVal, nil case CommandCSSTakeComputedStyleUpdates: - v = new(css.TakeComputedStyleUpdatesReturns) + v = new(css.TakeComputedStyleUpdatesResult) case CommandCSSSetEffectivePropertyValueForNode: return emptyVal, nil case CommandCSSSetPropertyRulePropertyName: - v = new(css.SetPropertyRulePropertyNameReturns) + v = new(css.SetPropertyRulePropertyNameResult) case CommandCSSSetKeyframeKey: - v = new(css.SetKeyframeKeyReturns) + v = new(css.SetKeyframeKeyResult) case CommandCSSSetMediaText: - v = new(css.SetMediaTextReturns) + v = new(css.SetMediaTextResult) case CommandCSSSetContainerQueryConditionText: - v = new(css.SetContainerQueryConditionTextReturns) + v = new(css.SetContainerQueryConditionTextResult) case CommandCSSSetSupportsText: - v = new(css.SetSupportsTextReturns) + v = new(css.SetSupportsTextResult) case CommandCSSSetNavigationText: - v = new(css.SetNavigationTextReturns) + v = new(css.SetNavigationTextResult) case CommandCSSSetScopeText: - v = new(css.SetScopeTextReturns) + v = new(css.SetScopeTextResult) case CommandCSSSetRuleSelector: - v = new(css.SetRuleSelectorReturns) + v = new(css.SetRuleSelectorResult) case CommandCSSSetStyleSheetText: - v = new(css.SetStyleSheetTextReturns) + v = new(css.SetStyleSheetTextResult) case CommandCSSSetStyleTexts: - v = new(css.SetStyleTextsReturns) + v = new(css.SetStyleTextsResult) case CommandCSSStartRuleUsageTracking: return emptyVal, nil case CommandCSSStopRuleUsageTracking: - v = new(css.StopRuleUsageTrackingReturns) + v = new(css.StopRuleUsageTrackingResult) case CommandCSSTakeCoverageDelta: - v = new(css.TakeCoverageDeltaReturns) + v = new(css.TakeCoverageDeltaResult) case CommandCSSSetLocalFontsEnabled: return emptyVal, nil case EventCSSFontsUpdated: @@ -1213,11 +1234,11 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandCacheStorageDeleteEntry: return emptyVal, nil case CommandCacheStorageRequestCacheNames: - v = new(cachestorage.RequestCacheNamesReturns) + v = new(cachestorage.RequestCacheNamesResult) case CommandCacheStorageRequestCachedResponse: - v = new(cachestorage.RequestCachedResponseReturns) + v = new(cachestorage.RequestCachedResponseResult) case CommandCacheStorageRequestEntries: - v = new(cachestorage.RequestEntriesReturns) + v = new(cachestorage.RequestEntriesResult) case CommandCastEnable: return emptyVal, nil case CommandCastDisable: @@ -1235,13 +1256,13 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case EventCastIssueUpdated: v = new(cast.EventIssueUpdated) case CommandCrashReportContextGetEntries: - v = new(crashreportcontext.GetEntriesReturns) + v = new(crashreportcontext.GetEntriesResult) case CommandDOMCollectClassNamesFromSubtree: - v = new(dom.CollectClassNamesFromSubtreeReturns) + v = new(dom.CollectClassNamesFromSubtreeResult) case CommandDOMCopyTo: - v = new(dom.CopyToReturns) + v = new(dom.CopyToResult) case CommandDOMDescribeNode: - v = new(dom.DescribeNodeReturns) + v = new(dom.DescribeNodeResult) case CommandDOMScrollIntoViewIfNeeded: return emptyVal, nil case CommandDOMDisable: @@ -1253,41 +1274,41 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandDOMFocus: return emptyVal, nil case CommandDOMGetAttributes: - v = new(dom.GetAttributesReturns) + v = new(dom.GetAttributesResult) case CommandDOMGetBoxModel: - v = new(dom.GetBoxModelReturns) + v = new(dom.GetBoxModelResult) case CommandDOMGetContentQuads: - v = new(dom.GetContentQuadsReturns) + v = new(dom.GetContentQuadsResult) case CommandDOMGetDocument: - v = new(dom.GetDocumentReturns) + v = new(dom.GetDocumentResult) case CommandDOMGetNodesForSubtreeByStyle: - v = new(dom.GetNodesForSubtreeByStyleReturns) + v = new(dom.GetNodesForSubtreeByStyleResult) case CommandDOMGetNodeForLocation: - v = new(dom.GetNodeForLocationReturns) + v = new(dom.GetNodeForLocationResult) case CommandDOMGetOuterHTML: - v = new(dom.GetOuterHTMLReturns) + v = new(dom.GetOuterHTMLResult) case CommandDOMGetRelayoutBoundary: - v = new(dom.GetRelayoutBoundaryReturns) + v = new(dom.GetRelayoutBoundaryResult) case CommandDOMGetSearchResults: - v = new(dom.GetSearchResultsReturns) + v = new(dom.GetSearchResultsResult) case CommandDOMMarkUndoableState: return emptyVal, nil case CommandDOMMoveTo: - v = new(dom.MoveToReturns) + v = new(dom.MoveToResult) case CommandDOMPerformSearch: - v = new(dom.PerformSearchReturns) + v = new(dom.PerformSearchResult) case CommandDOMPushNodeByPathToFrontend: - v = new(dom.PushNodeByPathToFrontendReturns) + v = new(dom.PushNodeByPathToFrontendResult) case CommandDOMPushNodesByBackendIDsToFrontend: - v = new(dom.PushNodesByBackendIDsToFrontendReturns) + v = new(dom.PushNodesByBackendIDsToFrontendResult) case CommandDOMQuerySelector: - v = new(dom.QuerySelectorReturns) + v = new(dom.QuerySelectorResult) case CommandDOMQuerySelectorAll: - v = new(dom.QuerySelectorAllReturns) + v = new(dom.QuerySelectorAllResult) case CommandDOMGetTopLayerElements: - v = new(dom.GetTopLayerElementsReturns) + v = new(dom.GetTopLayerElementsResult) case CommandDOMGetElementByRelation: - v = new(dom.GetElementByRelationReturns) + v = new(dom.GetElementByRelationResult) case CommandDOMRedo: return emptyVal, nil case CommandDOMRemoveAttribute: @@ -1297,9 +1318,9 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandDOMRequestChildNodes: return emptyVal, nil case CommandDOMRequestNode: - v = new(dom.RequestNodeReturns) + v = new(dom.RequestNodeResult) case CommandDOMResolveNode: - v = new(dom.ResolveNodeReturns) + v = new(dom.ResolveNodeResult) case CommandDOMSetAttributeValue: return emptyVal, nil case CommandDOMSetAttributesAsText: @@ -1309,15 +1330,15 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandDOMSetNodeStackTracesEnabled: return emptyVal, nil case CommandDOMGetNodeStackTraces: - v = new(dom.GetNodeStackTracesReturns) + v = new(dom.GetNodeStackTracesResult) case CommandDOMGetFileInfo: - v = new(dom.GetFileInfoReturns) + v = new(dom.GetFileInfoResult) case CommandDOMGetDetachedDomNodes: - v = new(dom.GetDetachedDomNodesReturns) + v = new(dom.GetDetachedDomNodesResult) case CommandDOMSetInspectedNode: return emptyVal, nil case CommandDOMSetNodeName: - v = new(dom.SetNodeNameReturns) + v = new(dom.SetNodeNameResult) case CommandDOMSetNodeValue: return emptyVal, nil case CommandDOMSetOuterHTML: @@ -1325,15 +1346,23 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandDOMUndo: return emptyVal, nil case CommandDOMGetFrameOwner: - v = new(dom.GetFrameOwnerReturns) + v = new(dom.GetFrameOwnerResult) case CommandDOMGetContainerForNode: - v = new(dom.GetContainerForNodeReturns) + v = new(dom.GetContainerForNodeResult) case CommandDOMGetQueryingDescendantsForContainer: - v = new(dom.GetQueryingDescendantsForContainerReturns) + v = new(dom.GetQueryingDescendantsForContainerResult) case CommandDOMGetAnchorElement: - v = new(dom.GetAnchorElementReturns) + v = new(dom.GetAnchorElementResult) case CommandDOMForceShowPopover: - v = new(dom.ForceShowPopoverReturns) + v = new(dom.ForceShowPopoverResult) + case CommandDOMGetImplicitAnchorCandidates: + v = new(dom.GetImplicitAnchorCandidatesResult) + case CommandDOMForceShowInterest: + return emptyVal, nil + case CommandDOMSetTextMarker: + return emptyVal, nil + case CommandDOMClearTextMarkers: + return emptyVal, nil case EventDOMAttributeModified: v = new(dom.EventAttributeModified) case EventDOMAdoptedStyleSheetsModified: @@ -1373,7 +1402,7 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case EventDOMShadowRootPushed: v = new(dom.EventShadowRootPushed) case CommandDOMDebuggerGetEventListeners: - v = new(domdebugger.GetEventListenersReturns) + v = new(domdebugger.GetEventListenersResult) case CommandDOMDebuggerRemoveDOMBreakpoint: return emptyVal, nil case CommandDOMDebuggerRemoveEventListenerBreakpoint: @@ -1393,7 +1422,7 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandDOMSnapshotEnable: return emptyVal, nil case CommandDOMSnapshotCaptureSnapshot: - v = new(domsnapshot.CaptureSnapshotReturns) + v = new(domsnapshot.CaptureSnapshotResult) case CommandDOMStorageClear: return emptyVal, nil case CommandDOMStorageDisable: @@ -1401,7 +1430,7 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandDOMStorageEnable: return emptyVal, nil case CommandDOMStorageGetDOMStorageItems: - v = new(domstorage.GetDOMStorageItemsReturns) + v = new(domstorage.GetDOMStorageItemsResult) case CommandDOMStorageRemoveDOMStorageItem: return emptyVal, nil case CommandDOMStorageSetDOMStorageItem: @@ -1419,19 +1448,19 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandDebuggerDisable: return emptyVal, nil case CommandDebuggerEnable: - v = new(debugger.EnableReturns) + v = new(debugger.EnableResult) case CommandDebuggerEvaluateOnCallFrame: - v = new(debugger.EvaluateOnCallFrameReturns) + v = new(debugger.EvaluateOnCallFrameResult) case CommandDebuggerGetPossibleBreakpoints: - v = new(debugger.GetPossibleBreakpointsReturns) + v = new(debugger.GetPossibleBreakpointsResult) case CommandDebuggerGetScriptSource: - v = new(debugger.GetScriptSourceReturns) + v = new(debugger.GetScriptSourceResult) case CommandDebuggerDisassembleWasmModule: - v = new(debugger.DisassembleWasmModuleReturns) + v = new(debugger.DisassembleWasmModuleResult) case CommandDebuggerNextWasmDisassemblyChunk: - v = new(debugger.NextWasmDisassemblyChunkReturns) + v = new(debugger.NextWasmDisassemblyChunkResult) case CommandDebuggerGetStackTrace: - v = new(debugger.GetStackTraceReturns) + v = new(debugger.GetStackTraceResult) case CommandDebuggerPause: return emptyVal, nil case CommandDebuggerRemoveBreakpoint: @@ -1441,7 +1470,7 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandDebuggerResume: return emptyVal, nil case CommandDebuggerSearchInContent: - v = new(debugger.SearchInContentReturns) + v = new(debugger.SearchInContentResult) case CommandDebuggerSetAsyncCallStackDepth: return emptyVal, nil case CommandDebuggerSetBlackboxExecutionContexts: @@ -1451,21 +1480,19 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandDebuggerSetBlackboxedRanges: return emptyVal, nil case CommandDebuggerSetBreakpoint: - v = new(debugger.SetBreakpointReturns) + v = new(debugger.SetBreakpointResult) case CommandDebuggerSetInstrumentationBreakpoint: - v = new(debugger.SetInstrumentationBreakpointReturns) + v = new(debugger.SetInstrumentationBreakpointResult) case CommandDebuggerSetBreakpointByURL: - v = new(debugger.SetBreakpointByURLReturns) + v = new(debugger.SetBreakpointByURLResult) case CommandDebuggerSetBreakpointOnFunctionCall: - v = new(debugger.SetBreakpointOnFunctionCallReturns) + v = new(debugger.SetBreakpointOnFunctionCallResult) case CommandDebuggerSetBreakpointsActive: return emptyVal, nil case CommandDebuggerSetPauseOnExceptions: return emptyVal, nil case CommandDebuggerSetReturnValue: return emptyVal, nil - case CommandDebuggerSetScriptSource: - v = new(debugger.SetScriptSourceReturns) case CommandDebuggerSetSkipAllPauses: return emptyVal, nil case CommandDebuggerSetVariableValue: @@ -1516,6 +1543,8 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { return emptyVal, nil case CommandEmulationSetSafeAreaInsetsOverride: return emptyVal, nil + case CommandEmulationSetVirtualKeyboardGeometryOverride: + return emptyVal, nil case CommandEmulationSetDeviceMetricsOverride: return emptyVal, nil case CommandEmulationSetDevicePostureOverride: @@ -1541,7 +1570,7 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandEmulationSetGeolocationOverride: return emptyVal, nil case CommandEmulationGetOverriddenSensorInformation: - v = new(emulation.GetOverriddenSensorInformationReturns) + v = new(emulation.GetOverriddenSensorInformationResult) case CommandEmulationSetSensorOverrideEnabled: return emptyVal, nil case CommandEmulationSetSensorOverrideReadings: @@ -1561,7 +1590,7 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandEmulationSetTouchEmulationEnabled: return emptyVal, nil case CommandEmulationSetVirtualTimePolicy: - v = new(emulation.SetVirtualTimePolicyReturns) + v = new(emulation.SetVirtualTimePolicyResult) case CommandEmulationSetLocaleOverride: return emptyVal, nil case CommandEmulationSetTimezoneOverride: @@ -1572,6 +1601,8 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { return emptyVal, nil case CommandEmulationSetHardwareConcurrencyOverride: return emptyVal, nil + case CommandEmulationSetCPUPerformanceOverride: + return emptyVal, nil case CommandEmulationSetUserAgentOverride: return emptyVal, nil case CommandEmulationSetAutomationOverride: @@ -1579,11 +1610,11 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandEmulationSetSmallViewportHeightDifferenceOverride: return emptyVal, nil case CommandEmulationGetScreenInfos: - v = new(emulation.GetScreenInfosReturns) + v = new(emulation.GetScreenInfosResult) case CommandEmulationAddScreen: - v = new(emulation.AddScreenReturns) + v = new(emulation.AddScreenResult) case CommandEmulationUpdateScreen: - v = new(emulation.UpdateScreenReturns) + v = new(emulation.UpdateScreenResult) case CommandEmulationRemoveScreen: return emptyVal, nil case CommandEmulationSetPrimaryScreen: @@ -1601,13 +1632,13 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandExtensionsTriggerAction: return emptyVal, nil case CommandExtensionsLoadUnpacked: - v = new(extensions.LoadUnpackedReturns) + v = new(extensions.LoadUnpackedResult) case CommandExtensionsGetExtensions: - v = new(extensions.GetExtensionsReturns) + v = new(extensions.GetExtensionsResult) case CommandExtensionsUninstall: return emptyVal, nil case CommandExtensionsGetStorageItems: - v = new(extensions.GetStorageItemsReturns) + v = new(extensions.GetStorageItemsResult) case CommandExtensionsRemoveStorageItems: return emptyVal, nil case CommandExtensionsClearStorageItems: @@ -1647,17 +1678,25 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandFetchContinueResponse: return emptyVal, nil case CommandFetchGetResponseBody: - v = new(fetch.GetResponseBodyReturns) + v = new(fetch.GetResponseBodyResult) case CommandFetchTakeResponseBodyAsStream: - v = new(fetch.TakeResponseBodyAsStreamReturns) + v = new(fetch.TakeResponseBodyAsStreamResult) case EventFetchRequestPaused: v = new(fetch.EventRequestPaused) case EventFetchAuthRequired: v = new(fetch.EventAuthRequired) case CommandFileSystemGetDirectory: - v = new(filesystem.GetDirectoryReturns) + v = new(filesystem.GetDirectoryResult) + case CommandFindInPageFindFirst: + return emptyVal, nil + case CommandFindInPageFindNext: + return emptyVal, nil + case CommandFindInPageFindPrev: + return emptyVal, nil + case CommandFindInPageStop: + return emptyVal, nil case CommandHeadlessExperimentalBeginFrame: - v = new(headlessexperimental.BeginFrameReturns) + v = new(headlessexperimental.BeginFrameResult) case CommandHeapProfilerAddInspectedHeapObject: return emptyVal, nil case CommandHeapProfilerCollectGarbage: @@ -1667,17 +1706,17 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandHeapProfilerEnable: return emptyVal, nil case CommandHeapProfilerGetHeapObjectID: - v = new(heapprofiler.GetHeapObjectIDReturns) + v = new(heapprofiler.GetHeapObjectIDResult) case CommandHeapProfilerGetObjectByHeapObjectID: - v = new(heapprofiler.GetObjectByHeapObjectIDReturns) + v = new(heapprofiler.GetObjectByHeapObjectIDResult) case CommandHeapProfilerGetSamplingProfile: - v = new(heapprofiler.GetSamplingProfileReturns) + v = new(heapprofiler.GetSamplingProfileResult) case CommandHeapProfilerStartSampling: return emptyVal, nil case CommandHeapProfilerStartTrackingHeapObjects: return emptyVal, nil case CommandHeapProfilerStopSampling: - v = new(heapprofiler.StopSamplingReturns) + v = new(heapprofiler.StopSamplingResult) case CommandHeapProfilerStopTrackingHeapObjects: return emptyVal, nil case CommandHeapProfilerTakeHeapSnapshot: @@ -1695,9 +1734,7 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandIOClose: return emptyVal, nil case CommandIORead: - v = new(io.ReadReturns) - case CommandIOResolveBlob: - v = new(io.ResolveBlobReturns) + v = new(io.ReadResult) case CommandIndexedDBClearObjectStore: return emptyVal, nil case CommandIndexedDBDeleteDatabase: @@ -1709,13 +1746,13 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandIndexedDBEnable: return emptyVal, nil case CommandIndexedDBRequestData: - v = new(indexeddb.RequestDataReturns) + v = new(indexeddb.RequestDataResult) case CommandIndexedDBGetMetadata: - v = new(indexeddb.GetMetadataReturns) + v = new(indexeddb.GetMetadataResult) case CommandIndexedDBRequestDatabase: - v = new(indexeddb.RequestDatabaseReturns) + v = new(indexeddb.RequestDatabaseResult) case CommandIndexedDBRequestDatabaseNames: - v = new(indexeddb.RequestDatabaseNamesReturns) + v = new(indexeddb.RequestDatabaseNamesResult) case CommandInputDispatchDragEvent: return emptyVal, nil case CommandInputDispatchKeyEvent: @@ -1757,23 +1794,23 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case EventInspectorWorkerScriptLoaded: v = new(inspector.EventWorkerScriptLoaded) case CommandLayerTreeCompositingReasons: - v = new(layertree.CompositingReasonsReturns) + v = new(layertree.CompositingReasonsResult) case CommandLayerTreeDisable: return emptyVal, nil case CommandLayerTreeEnable: return emptyVal, nil case CommandLayerTreeLoadSnapshot: - v = new(layertree.LoadSnapshotReturns) + v = new(layertree.LoadSnapshotResult) case CommandLayerTreeMakeSnapshot: - v = new(layertree.MakeSnapshotReturns) + v = new(layertree.MakeSnapshotResult) case CommandLayerTreeProfileSnapshot: - v = new(layertree.ProfileSnapshotReturns) + v = new(layertree.ProfileSnapshotResult) case CommandLayerTreeReleaseSnapshot: return emptyVal, nil case CommandLayerTreeReplaySnapshot: - v = new(layertree.ReplaySnapshotReturns) + v = new(layertree.ReplaySnapshotResult) case CommandLayerTreeSnapshotCommandLog: - v = new(layertree.SnapshotCommandLogReturns) + v = new(layertree.SnapshotCommandLogResult) case EventLayerTreeLayerPainted: v = new(layertree.EventLayerPainted) case EventLayerTreeLayerTreeDidChange: @@ -1805,9 +1842,9 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case EventMediaPlayerCreated: v = new(media.EventPlayerCreated) case CommandMemoryGetDOMCounters: - v = new(memory.GetDOMCountersReturns) + v = new(memory.GetDOMCountersResult) case CommandMemoryGetDOMCountersForLeakDetection: - v = new(memory.GetDOMCountersForLeakDetectionReturns) + v = new(memory.GetDOMCountersForLeakDetectionResult) case CommandMemoryPrepareForLeakDetection: return emptyVal, nil case CommandMemoryForciblyPurgeJavaScriptMemory: @@ -1821,15 +1858,11 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandMemoryStopSampling: return emptyVal, nil case CommandMemoryGetAllTimeSamplingProfile: - v = new(memory.GetAllTimeSamplingProfileReturns) + v = new(memory.GetAllTimeSamplingProfileResult) case CommandMemoryGetBrowserSamplingProfile: - v = new(memory.GetBrowserSamplingProfileReturns) + v = new(memory.GetBrowserSamplingProfileResult) case CommandMemoryGetSamplingProfile: - v = new(memory.GetSamplingProfileReturns) - case CommandNetworkSetAcceptedEncodings: - return emptyVal, nil - case CommandNetworkClearAcceptedEncodingsOverride: - return emptyVal, nil + v = new(memory.GetSamplingProfileResult) case CommandNetworkClearBrowserCache: return emptyVal, nil case CommandNetworkClearBrowserCookies: @@ -1839,7 +1872,7 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandNetworkDisable: return emptyVal, nil case CommandNetworkEmulateNetworkConditionsByRule: - v = new(network.EmulateNetworkConditionsByRuleReturns) + v = new(network.EmulateNetworkConditionsByRuleResult) case CommandNetworkOverrideNetworkState: return emptyVal, nil case CommandNetworkEnable: @@ -1847,21 +1880,17 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandNetworkConfigureDurableMessages: return emptyVal, nil case CommandNetworkGetCertificate: - v = new(network.GetCertificateReturns) + v = new(network.GetCertificateResult) case CommandNetworkGetCookies: - v = new(network.GetCookiesReturns) + v = new(network.GetCookiesResult) case CommandNetworkGetResponseBody: - v = new(network.GetResponseBodyReturns) + v = new(network.GetResponseBodyResult) case CommandNetworkGetRequestPostData: - v = new(network.GetRequestPostDataReturns) - case CommandNetworkGetResponseBodyForInterception: - v = new(network.GetResponseBodyForInterceptionReturns) - case CommandNetworkTakeResponseBodyForInterceptionAsStream: - v = new(network.TakeResponseBodyForInterceptionAsStreamReturns) + v = new(network.GetRequestPostDataResult) case CommandNetworkReplayXHR: return emptyVal, nil case CommandNetworkSearchInResponseBody: - v = new(network.SearchInResponseBodyReturns) + v = new(network.SearchInResponseBodyResult) case CommandNetworkSetBlockedURLs: return emptyVal, nil case CommandNetworkSetBypassServiceWorker: @@ -1877,9 +1906,9 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandNetworkSetAttachDebugStack: return emptyVal, nil case CommandNetworkStreamResourceContent: - v = new(network.StreamResourceContentReturns) + v = new(network.StreamResourceContentResult) case CommandNetworkGetSecurityIsolationStatus: - v = new(network.GetSecurityIsolationStatusReturns) + v = new(network.GetSecurityIsolationStatusResult) case CommandNetworkEnableReportingAPI: return emptyVal, nil case CommandNetworkEnableDeviceBoundSessions: @@ -1887,9 +1916,9 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandNetworkDeleteDeviceBoundSession: return emptyVal, nil case CommandNetworkFetchSchemefulSite: - v = new(network.FetchSchemefulSiteReturns) + v = new(network.FetchSchemefulSiteResult) case CommandNetworkLoadNetworkResource: - v = new(network.LoadNetworkResourceReturns) + v = new(network.LoadNetworkResourceResult) case CommandNetworkSetCookieControls: return emptyVal, nil case EventNetworkDataReceived: @@ -1983,11 +2012,11 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandOverlayEnable: return emptyVal, nil case CommandOverlayGetHighlightObjectForTest: - v = new(overlay.GetHighlightObjectForTestReturns) + v = new(overlay.GetHighlightObjectForTestResult) case CommandOverlayGetGridHighlightObjectsForTest: - v = new(overlay.GetGridHighlightObjectsForTestReturns) + v = new(overlay.GetGridHighlightObjectsForTestResult) case CommandOverlayGetSourceOrderHighlightObjectForTest: - v = new(overlay.GetSourceOrderHighlightObjectForTestReturns) + v = new(overlay.GetSourceOrderHighlightObjectForTestResult) case CommandOverlayHideHighlight: return emptyVal, nil case CommandOverlayHighlightNode: @@ -2047,61 +2076,67 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case EventOverlayInspectModeCanceled: v = new(overlay.EventInspectModeCanceled) case CommandPWAGetOsAppState: - v = new(pwa.GetOsAppStateReturns) + v = new(pwa.GetOsAppStateResult) case CommandPWAInstall: return emptyVal, nil case CommandPWAUninstall: return emptyVal, nil case CommandPWALaunch: - v = new(pwa.LaunchReturns) + v = new(pwa.LaunchResult) case CommandPWALaunchFilesInApp: - v = new(pwa.LaunchFilesInAppReturns) + v = new(pwa.LaunchFilesInAppResult) case CommandPWAOpenCurrentPageInApp: return emptyVal, nil case CommandPWAChangeAppUserSettings: return emptyVal, nil case CommandPageAddScriptToEvaluateOnNewDocument: - v = new(page.AddScriptToEvaluateOnNewDocumentReturns) + v = new(page.AddScriptToEvaluateOnNewDocumentResult) case CommandPageBringToFront: return emptyVal, nil case CommandPageCaptureScreenshot: - v = new(page.CaptureScreenshotReturns) + v = new(page.CaptureScreenshotResult) case CommandPageCaptureSnapshot: - v = new(page.CaptureSnapshotReturns) + v = new(page.CaptureSnapshotResult) case CommandPageCreateIsolatedWorld: - v = new(page.CreateIsolatedWorldReturns) + v = new(page.CreateIsolatedWorldResult) case CommandPageDisable: return emptyVal, nil case CommandPageEnable: return emptyVal, nil case CommandPageGetAppManifest: - v = new(page.GetAppManifestReturns) + v = new(page.GetAppManifestResult) case CommandPageGetInstallabilityErrors: - v = new(page.GetInstallabilityErrorsReturns) + v = new(page.GetInstallabilityErrorsResult) case CommandPageGetAppID: - v = new(page.GetAppIDReturns) + v = new(page.GetAppIDResult) + case CommandPageGetSubApps: + v = new(page.GetSubAppsResult) + case CommandPageGetSiblingSubApps: + v = new(page.GetSiblingSubAppsResult) case CommandPageGetAdScriptAncestry: - v = new(page.GetAdScriptAncestryReturns) + v = new(page.GetAdScriptAncestryResult) + case CommandPageGetSpellCheckCustomDictionary: + v = new(page.GetSpellCheckCustomDictionaryResult) case CommandPageGetFrameTree: - v = new(page.GetFrameTreeReturns) + v = new(page.GetFrameTreeResult) case CommandPageGetLayoutMetrics: - v = new(page.GetLayoutMetricsReturns) + v = new(page.GetLayoutMetricsResult) case CommandPageGetNavigationHistory: - v = new(page.GetNavigationHistoryReturns) + v = new(page.GetNavigationHistoryResult) case CommandPageResetNavigationHistory: return emptyVal, nil case CommandPageGetResourceContent: - v = new(page.GetResourceContentReturns) + v = new(page.GetResourceContentResult) case CommandPageGetResourceTree: - v = new(page.GetResourceTreeReturns) + v = new(page.GetResourceTreeResult) case CommandPageHandleJavaScriptDialog: return emptyVal, nil case CommandPageNavigate: - v = new(page.NavigateReturns) + v = new(page.NavigateResult) case CommandPageNavigateToHistoryEntry: return emptyVal, nil case CommandPagePrintToPDF: - v = new(page.PrintToPDFReturns) + v = new(page.PrintToPDFResult) case CommandPageReload: return emptyVal, nil case CommandPageRemoveScriptToEvaluateOnNewDocument: @@ -2109,15 +2144,15 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandPageScreencastFrameAck: return emptyVal, nil case CommandPageSearchInResource: - v = new(page.SearchInResourceReturns) + v = new(page.SearchInResourceResult) case CommandPageSetAdBlockingEnabled: return emptyVal, nil case CommandPageSetBypassCSP: return emptyVal, nil case CommandPageGetPermissionsPolicyState: - v = new(page.GetPermissionsPolicyStateReturns) + v = new(page.GetPermissionsPolicyStateResult) case CommandPageGetOriginTrials: - v = new(page.GetOriginTrialsReturns) + v = new(page.GetOriginTrialsResult) case CommandPageSetFontFamilies: return emptyVal, nil case CommandPageSetFontSizes: @@ -2128,6 +2163,10 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { return emptyVal, nil case CommandPageStartScreencast: return emptyVal, nil + case CommandPageStartScreenRecording: + v = new(page.StartScreenRecordingResult) + case CommandPageStopScreenRecording: + v = new(page.StopScreenRecordingResult) case CommandPageStopLoading: return emptyVal, nil case CommandPageCrash: @@ -2157,7 +2196,9 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandPageSetPrerenderingAllowed: return emptyVal, nil case CommandPageGetAnnotatedPageContent: - v = new(page.GetAnnotatedPageContentReturns) + v = new(page.GetAnnotatedPageContentResult) + case CommandPageSetInputVisualization: + return emptyVal, nil case EventPageDomContentEventFired: v = new(page.EventDomContentEventFired) case EventPageFileChooserOpened: @@ -2211,7 +2252,7 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandPerformanceEnable: return emptyVal, nil case CommandPerformanceGetMetrics: - v = new(performance.GetMetricsReturns) + v = new(performance.GetMetricsResult) case EventPerformanceMetrics: v = new(performance.EventMetrics) case CommandPerformanceTimelineEnable: @@ -2239,19 +2280,19 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandProfilerEnable: return emptyVal, nil case CommandProfilerGetBestEffortCoverage: - v = new(profiler.GetBestEffortCoverageReturns) + v = new(profiler.GetBestEffortCoverageResult) case CommandProfilerSetSamplingInterval: return emptyVal, nil case CommandProfilerStart: return emptyVal, nil case CommandProfilerStartPreciseCoverage: - v = new(profiler.StartPreciseCoverageReturns) + v = new(profiler.StartPreciseCoverageResult) case CommandProfilerStop: - v = new(profiler.StopReturns) + v = new(profiler.StopResult) case CommandProfilerStopPreciseCoverage: return emptyVal, nil case CommandProfilerTakePreciseCoverage: - v = new(profiler.TakePreciseCoverageReturns) + v = new(profiler.TakePreciseCoverageResult) case EventProfilerConsoleProfileFinished: v = new(profiler.EventConsoleProfileFinished) case EventProfilerConsoleProfileStarted: @@ -2259,11 +2300,11 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case EventProfilerPreciseCoverageDeltaUpdate: v = new(profiler.EventPreciseCoverageDeltaUpdate) case CommandRuntimeAwaitPromise: - v = new(runtime.AwaitPromiseReturns) + v = new(runtime.AwaitPromiseResult) case CommandRuntimeCallFunctionOn: - v = new(runtime.CallFunctionOnReturns) + v = new(runtime.CallFunctionOnResult) case CommandRuntimeCompileScript: - v = new(runtime.CompileScriptReturns) + v = new(runtime.CompileScriptResult) case CommandRuntimeDisable: return emptyVal, nil case CommandRuntimeDiscardConsoleEntries: @@ -2271,17 +2312,17 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandRuntimeEnable: return emptyVal, nil case CommandRuntimeEvaluate: - v = new(runtime.EvaluateReturns) + v = new(runtime.EvaluateResult) case CommandRuntimeGetIsolateID: - v = new(runtime.GetIsolateIDReturns) + v = new(runtime.GetIsolateIDResult) case CommandRuntimeGetHeapUsage: - v = new(runtime.GetHeapUsageReturns) + v = new(runtime.GetHeapUsageResult) case CommandRuntimeGetProperties: - v = new(runtime.GetPropertiesReturns) + v = new(runtime.GetPropertiesResult) case CommandRuntimeGlobalLexicalScopeNames: - v = new(runtime.GlobalLexicalScopeNamesReturns) + v = new(runtime.GlobalLexicalScopeNamesResult) case CommandRuntimeQueryObjects: - v = new(runtime.QueryObjectsReturns) + v = new(runtime.QueryObjectsResult) case CommandRuntimeReleaseObject: return emptyVal, nil case CommandRuntimeReleaseObjectGroup: @@ -2289,7 +2330,7 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandRuntimeRunIfWaitingForDebugger: return emptyVal, nil case CommandRuntimeRunScript: - v = new(runtime.RunScriptReturns) + v = new(runtime.RunScriptResult) case CommandRuntimeSetCustomObjectFormatterEnabled: return emptyVal, nil case CommandRuntimeSetMaxCallStackSizeToCapture: @@ -2301,7 +2342,7 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandRuntimeRemoveBinding: return emptyVal, nil case CommandRuntimeGetExceptionDetails: - v = new(runtime.GetExceptionDetailsReturns) + v = new(runtime.GetExceptionDetailsResult) case EventRuntimeBindingCalled: v = new(runtime.EventBindingCalled) case EventRuntimeConsoleAPICalled: @@ -2409,19 +2450,19 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case EventSmartCardEmulationEndTransactionRequested: v = new(smartcardemulation.EventEndTransactionRequested) case CommandStorageGetStorageKey: - v = new(storage.GetStorageKeyReturns) + v = new(storage.GetStorageKeyResult) case CommandStorageClearDataForOrigin: return emptyVal, nil case CommandStorageClearDataForStorageKey: return emptyVal, nil case CommandStorageGetCookies: - v = new(storage.GetCookiesReturns) + v = new(storage.GetCookiesResult) case CommandStorageSetCookies: return emptyVal, nil case CommandStorageClearCookies: return emptyVal, nil case CommandStorageGetUsageAndQuota: - v = new(storage.GetUsageAndQuotaReturns) + v = new(storage.GetUsageAndQuotaResult) case CommandStorageOverrideQuotaForOrigin: return emptyVal, nil case CommandStorageTrackCacheStorageForOrigin: @@ -2441,31 +2482,25 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandStorageUntrackIndexedDBForStorageKey: return emptyVal, nil case CommandStorageGetTrustTokens: - v = new(storage.GetTrustTokensReturns) + v = new(storage.GetTrustTokensResult) case CommandStorageClearTrustTokens: - v = new(storage.ClearTrustTokensReturns) - case CommandStorageGetSharedStorageMetadata: - v = new(storage.GetSharedStorageMetadataReturns) - case CommandStorageGetSharedStorageEntries: - v = new(storage.GetSharedStorageEntriesReturns) - case CommandStorageSetSharedStorageEntry: - return emptyVal, nil - case CommandStorageDeleteSharedStorageEntry: - return emptyVal, nil - case CommandStorageClearSharedStorageEntries: + v = new(storage.ClearTrustTokensResult) + case CommandStorageGetPrivateVerificationTokens: + v = new(storage.GetPrivateVerificationTokensResult) + case CommandStorageGetPrivateVerificationTokensIssuerConfigs: + v = new(storage.GetPrivateVerificationTokensIssuerConfigsResult) + case CommandStorageClearPrivateVerificationTokens: return emptyVal, nil - case CommandStorageResetSharedStorageBudget: + case CommandStorageDeletePrivateVerificationToken: return emptyVal, nil - case CommandStorageSetSharedStorageTracking: + case CommandStorageSetPrivateVerificationTokensTracking: return emptyVal, nil case CommandStorageSetStorageBucketTracking: return emptyVal, nil case CommandStorageDeleteStorageBucket: return emptyVal, nil case CommandStorageRunBounceTrackingMitigations: - v = new(storage.RunBounceTrackingMitigationsReturns) - case CommandStorageGetRelatedWebsiteSets: - v = new(storage.GetRelatedWebsiteSetsReturns) + v = new(storage.RunBounceTrackingMitigationsResult) case EventStorageCacheStorageContentUpdated: v = new(storage.EventCacheStorageContentUpdated) case EventStorageCacheStorageListUpdated: @@ -2474,44 +2509,42 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { v = new(storage.EventIndexedDBContentUpdated) case EventStorageIndexedDBListUpdated: v = new(storage.EventIndexedDBListUpdated) - case EventStorageSharedStorageAccessed: - v = new(storage.EventSharedStorageAccessed) - case EventStorageSharedStorageWorkletOperationExecutionFinished: - v = new(storage.EventSharedStorageWorkletOperationExecutionFinished) case EventStorageStorageBucketCreatedOrUpdated: v = new(storage.EventStorageBucketCreatedOrUpdated) case EventStorageStorageBucketDeleted: v = new(storage.EventStorageBucketDeleted) + case EventStoragePrivateVerificationTokensUpdated: + v = new(storage.EventPrivateVerificationTokensUpdated) case CommandSystemInfoGetInfo: - v = new(systeminfo.GetInfoReturns) + v = new(systeminfo.GetInfoResult) case CommandSystemInfoGetFeatureState: - v = new(systeminfo.GetFeatureStateReturns) + v = new(systeminfo.GetFeatureStateResult) case CommandSystemInfoGetProcessInfo: - v = new(systeminfo.GetProcessInfoReturns) + v = new(systeminfo.GetProcessInfoResult) case CommandTargetActivateTarget: return emptyVal, nil case CommandTargetAttachToTarget: - v = new(target.AttachToTargetReturns) + v = new(target.AttachToTargetResult) case CommandTargetAttachToBrowserTarget: - v = new(target.AttachToBrowserTargetReturns) + v = new(target.AttachToBrowserTargetResult) case CommandTargetCloseTarget: return emptyVal, nil case CommandTargetExposeDevToolsProtocol: return emptyVal, nil case CommandTargetCreateBrowserContext: - v = new(target.CreateBrowserContextReturns) + v = new(target.CreateBrowserContextResult) case CommandTargetGetBrowserContexts: - v = new(target.GetBrowserContextsReturns) + v = new(target.GetBrowserContextsResult) case CommandTargetCreateTarget: - v = new(target.CreateTargetReturns) + v = new(target.CreateTargetResult) case CommandTargetDetachFromTarget: return emptyVal, nil case CommandTargetDisposeBrowserContext: return emptyVal, nil case CommandTargetGetTargetInfo: - v = new(target.GetTargetInfoReturns) + v = new(target.GetTargetInfoResult) case CommandTargetGetTargets: - v = new(target.GetTargetsReturns) + v = new(target.GetTargetsResult) case CommandTargetSetAutoAttach: return emptyVal, nil case CommandTargetAutoAttachRelated: @@ -2521,9 +2554,9 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandTargetSetRemoteLocations: return emptyVal, nil case CommandTargetGetDevToolsTarget: - v = new(target.GetDevToolsTargetReturns) + v = new(target.GetDevToolsTargetResult) case CommandTargetOpenDevTools: - v = new(target.OpenDevToolsReturns) + v = new(target.OpenDevToolsResult) case EventTargetAttachedToTarget: v = new(target.EventAttachedToTarget) case EventTargetDetachedFromTarget: @@ -2547,13 +2580,13 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandTracingEnd: return emptyVal, nil case CommandTracingGetCategories: - v = new(tracing.GetCategoriesReturns) + v = new(tracing.GetCategoriesResult) case CommandTracingGetTrackEventDescriptor: - v = new(tracing.GetTrackEventDescriptorReturns) + v = new(tracing.GetTrackEventDescriptorResult) case CommandTracingRecordClockSyncMarker: return emptyVal, nil case CommandTracingRequestMemoryDump: - v = new(tracing.RequestMemoryDumpReturns) + v = new(tracing.RequestMemoryDumpResult) case CommandTracingStart: return emptyVal, nil case EventTracingBufferUsage: @@ -2567,7 +2600,7 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandWebAudioDisable: return emptyVal, nil case CommandWebAudioGetRealtimeData: - v = new(webaudio.GetRealtimeDataReturns) + v = new(webaudio.GetRealtimeDataResult) case EventWebAudioContextCreated: v = new(webaudio.EventContextCreated) case EventWebAudioContextWillBeDestroyed: @@ -2599,7 +2632,7 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandWebAuthnDisable: return emptyVal, nil case CommandWebAuthnAddVirtualAuthenticator: - v = new(webauthn.AddVirtualAuthenticatorReturns) + v = new(webauthn.AddVirtualAuthenticatorResult) case CommandWebAuthnSetResponseOverrideBits: return emptyVal, nil case CommandWebAuthnRemoveVirtualAuthenticator: @@ -2607,9 +2640,9 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandWebAuthnAddCredential: return emptyVal, nil case CommandWebAuthnGetCredential: - v = new(webauthn.GetCredentialReturns) + v = new(webauthn.GetCredentialResult) case CommandWebAuthnGetCredentials: - v = new(webauthn.GetCredentialsReturns) + v = new(webauthn.GetCredentialsResult) case CommandWebAuthnRemoveCredential: return emptyVal, nil case CommandWebAuthnClearCredentials: @@ -2633,7 +2666,7 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { case CommandWebMCPDisable: return emptyVal, nil case CommandWebMCPInvokeTool: - v = new(webmcp.InvokeToolReturns) + v = new(webmcp.InvokeToolResult) case CommandWebMCPCancelInvocation: return emptyVal, nil case EventWebMCPToolsAdded: @@ -2648,7 +2681,7 @@ func UnmarshalMessage(msg *Message, opts ...jsonv2.Options) (any, error) { return nil, cdp.ErrUnknownCommandOrEvent(msg.Method) } - var buf jsontext.Value + var buf jsonv2.Value switch { case msg.Params != nil: buf = msg.Params diff --git a/vendor/github.com/chromedp/cdproto/crashreportcontext/crashreportcontext.go b/vendor/github.com/chromedp/cdproto/crashreportcontext/crashreportcontext.go index 28a04815b..3f5608a3c 100644 --- a/vendor/github.com/chromedp/cdproto/crashreportcontext/crashreportcontext.go +++ b/vendor/github.com/chromedp/cdproto/crashreportcontext/crashreportcontext.go @@ -1,51 +1,28 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package crashreportcontext provides the Chrome DevTools Protocol // commands, types, and events for the CrashReportContext domain. // // This domain exposes the current state of the CrashReportContext API. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package crashreportcontext -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// GetEntriesParams returns all entries in the CrashReportContext across all -// frames in the page. -type GetEntriesParams struct{} +// GetEntriesResult is the result of the command +// CrashReportContext.getEntries. +type GetEntriesResult struct { + Entries []*Entry `json:"entries,omitempty,omitzero"` +} // GetEntries returns all entries in the CrashReportContext across all frames // in the page. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CrashReportContext#method-getEntries -func GetEntries() *GetEntriesParams { - return &GetEntriesParams{} -} - -// GetEntriesReturns return values. -type GetEntriesReturns struct { - Entries []*Entry `json:"entries,omitempty,omitzero"` -} - -// Do executes CrashReportContext.getEntries against the provided context. -// -// returns: -// -// entries -func (p *GetEntriesParams) Do(ctx context.Context) (entries []*Entry, err error) { - // execute - var res GetEntriesReturns - err = cdp.Execute(ctx, CommandGetEntries, nil, &res) - if err != nil { - return nil, err - } - - return res.Entries, nil -} +var GetEntries = cdp.Command[cdp.Empty, GetEntriesResult]{Method: CommandGetEntries} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/crashreportcontext/types.go b/vendor/github.com/chromedp/cdproto/crashreportcontext/types.go index fdeb1caf2..b3be1473b 100644 --- a/vendor/github.com/chromedp/cdproto/crashreportcontext/types.go +++ b/vendor/github.com/chromedp/cdproto/crashreportcontext/types.go @@ -1,6 +1,6 @@ -package crashreportcontext +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package crashreportcontext import ( "github.com/chromedp/cdproto/cdp" diff --git a/vendor/github.com/chromedp/cdproto/css/css.go b/vendor/github.com/chromedp/cdproto/css/css.go index 12ad72f87..d9a00c8ce 100644 --- a/vendor/github.com/chromedp/cdproto/css/css.go +++ b/vendor/github.com/chromedp/cdproto/css/css.go @@ -1,3 +1,5 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package css provides the Chrome DevTools Protocol // commands, types, and events for the CSS domain. // @@ -10,20 +12,15 @@ // styleSheetAdded/styleSheetRemoved events and subsequently load the required // stylesheet contents using the getStyleSheet[Text]() methods. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package css -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" - "github.com/go-json-experiment/json/jsontext" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" ) -// AddRuleParams inserts a new rule with the given ruleText in a stylesheet -// with given styleSheetId, at the position specified by location. +// AddRuleParams are the parameters of the command CSS.addRule. type AddRuleParams struct { StyleSheetID cdp.StyleSheetID `json:"styleSheetId"` // The css style sheet identifier where a new rule should be inserted. RuleText string `json:"ruleText"` // The text of a new rule. @@ -31,181 +28,66 @@ type AddRuleParams struct { NodeForPropertySyntaxValidation cdp.NodeID `json:"nodeForPropertySyntaxValidation,omitempty,omitzero"` // NodeId for the DOM node in whose context custom property declarations for registered properties should be validated. If omitted, declarations in the new rule text can only be validated statically, which may produce incorrect results if the declaration contains a var() for example. } -// AddRule inserts a new rule with the given ruleText in a stylesheet with -// given styleSheetId, at the position specified by location. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-addRule -// -// parameters: -// -// styleSheetID - The css style sheet identifier where a new rule should be inserted. -// ruleText - The text of a new rule. -// location - Text position of a new rule in the target style sheet. -func AddRule(styleSheetID cdp.StyleSheetID, ruleText string, location *SourceRange) *AddRuleParams { - return &AddRuleParams{ - StyleSheetID: styleSheetID, - RuleText: ruleText, - Location: location, - } -} - -// WithNodeForPropertySyntaxValidation nodeId for the DOM node in whose -// context custom property declarations for registered properties should be -// validated. If omitted, declarations in the new rule text can only be -// validated statically, which may produce incorrect results if the declaration -// contains a var() for example. -func (p AddRuleParams) WithNodeForPropertySyntaxValidation(nodeForPropertySyntaxValidation cdp.NodeID) *AddRuleParams { - p.NodeForPropertySyntaxValidation = nodeForPropertySyntaxValidation - return &p -} - -// AddRuleReturns return values. -type AddRuleReturns struct { +// AddRuleResult is the result of the command CSS.addRule. +type AddRuleResult struct { Rule *Rule `json:"rule,omitempty,omitzero"` // The newly created rule. } -// Do executes CSS.addRule against the provided context. -// -// returns: +// AddRule inserts a new rule with the given ruleText in a stylesheet with +// given styleSheetId, at the position specified by location. // -// rule - The newly created rule. -func (p *AddRuleParams) Do(ctx context.Context) (rule *Rule, err error) { - // execute - var res AddRuleReturns - err = cdp.Execute(ctx, CommandAddRule, p, &res) - if err != nil { - return nil, err - } - - return res.Rule, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-addRule +var AddRule = cdp.Command[AddRuleParams, AddRuleResult]{Method: CommandAddRule} -// CollectClassNamesParams returns all class names from specified stylesheet. +// CollectClassNamesParams are the parameters of the command +// CSS.collectClassNames. type CollectClassNamesParams struct { StyleSheetID cdp.StyleSheetID `json:"styleSheetId"` } -// CollectClassNames returns all class names from specified stylesheet. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-collectClassNames -// -// parameters: -// -// styleSheetID -func CollectClassNames(styleSheetID cdp.StyleSheetID) *CollectClassNamesParams { - return &CollectClassNamesParams{ - StyleSheetID: styleSheetID, - } -} - -// CollectClassNamesReturns return values. -type CollectClassNamesReturns struct { +// CollectClassNamesResult is the result of the command +// CSS.collectClassNames. +type CollectClassNamesResult struct { ClassNames []string `json:"classNames,omitempty,omitzero"` // Class name list. } -// Do executes CSS.collectClassNames against the provided context. -// -// returns: +// CollectClassNames returns all class names from specified stylesheet. // -// classNames - Class name list. -func (p *CollectClassNamesParams) Do(ctx context.Context) (classNames []string, err error) { - // execute - var res CollectClassNamesReturns - err = cdp.Execute(ctx, CommandCollectClassNames, p, &res) - if err != nil { - return nil, err - } - - return res.ClassNames, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-collectClassNames +var CollectClassNames = cdp.Command[CollectClassNamesParams, CollectClassNamesResult]{Method: CommandCollectClassNames} -// CreateStyleSheetParams creates a new special "via-inspector" stylesheet in -// the frame with given frameId. +// CreateStyleSheetParams are the parameters of the command +// CSS.createStyleSheet. type CreateStyleSheetParams struct { - FrameID cdp.FrameID `json:"frameId"` // Identifier of the frame where "via-inspector" stylesheet should be created. - Force bool `json:"force"` // If true, creates a new stylesheet for every call. If false, returns a stylesheet previously created by a call with force=false for the frame's document if it exists or creates a new stylesheet (default: false). + FrameID cdp.FrameID `json:"frameId"` // Identifier of the frame where "via-inspector" stylesheet should be created. + Force *bool `json:"force,omitempty,omitzero"` // If true, creates a new stylesheet for every call. If false, returns a stylesheet previously created by a call with force=false for the frame's document if it exists or creates a new stylesheet (default: false). } -// CreateStyleSheet creates a new special "via-inspector" stylesheet in the -// frame with given frameId. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-createStyleSheet -// -// parameters: -// -// frameID - Identifier of the frame where "via-inspector" stylesheet should be created. -func CreateStyleSheet(frameID cdp.FrameID) *CreateStyleSheetParams { - return &CreateStyleSheetParams{ - FrameID: frameID, - Force: false, - } -} - -// WithForce if true, creates a new stylesheet for every call. If false, -// returns a stylesheet previously created by a call with force=false for the -// frame's document if it exists or creates a new stylesheet (default: false). -func (p CreateStyleSheetParams) WithForce(force bool) *CreateStyleSheetParams { - p.Force = force - return &p -} - -// CreateStyleSheetReturns return values. -type CreateStyleSheetReturns struct { +// CreateStyleSheetResult is the result of the command CSS.createStyleSheet. +type CreateStyleSheetResult struct { StyleSheetID cdp.StyleSheetID `json:"styleSheetId,omitempty,omitzero"` // Identifier of the created "via-inspector" stylesheet. } -// Do executes CSS.createStyleSheet against the provided context. -// -// returns: +// CreateStyleSheet creates a new special "via-inspector" stylesheet in the +// frame with given frameId. // -// styleSheetID - Identifier of the created "via-inspector" stylesheet. -func (p *CreateStyleSheetParams) Do(ctx context.Context) (styleSheetID cdp.StyleSheetID, err error) { - // execute - var res CreateStyleSheetReturns - err = cdp.Execute(ctx, CommandCreateStyleSheet, p, &res) - if err != nil { - return "", err - } - - return res.StyleSheetID, nil -} - -// DisableParams disables the CSS agent for the given page. -type DisableParams struct{} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-createStyleSheet +var CreateStyleSheet = cdp.Command[CreateStyleSheetParams, CreateStyleSheetResult]{Method: CommandCreateStyleSheet} // Disable disables the CSS agent for the given page. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes CSS.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// EnableParams enables the CSS agent for the given page. Clients should not -// assume that the CSS agent has been enabled until the result of this command -// is received. -type EnableParams struct{} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} // Enable enables the CSS agent for the given page. Clients should not assume // that the CSS agent has been enabled until the result of this command is // received. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} -// Do executes CSS.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) -} - -// ForcePseudoStateParams ensures that the given node will have specified -// pseudo-classes whenever its style is computed by the browser. +// ForcePseudoStateParams are the parameters of the command +// CSS.forcePseudoState. type ForcePseudoStateParams struct { NodeID cdp.NodeID `json:"nodeId"` // The element id for which to force the pseudo state. ForcedPseudoClasses []string `json:"forcedPseudoClasses"` // Element pseudo classes to force when computing the element's style. @@ -215,25 +97,10 @@ type ForcePseudoStateParams struct { // pseudo-classes whenever its style is computed by the browser. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-forcePseudoState -// -// parameters: -// -// nodeID - The element id for which to force the pseudo state. -// forcedPseudoClasses - Element pseudo classes to force when computing the element's style. -func ForcePseudoState(nodeID cdp.NodeID, forcedPseudoClasses []string) *ForcePseudoStateParams { - return &ForcePseudoStateParams{ - NodeID: nodeID, - ForcedPseudoClasses: forcedPseudoClasses, - } -} +var ForcePseudoState = cdp.Command[ForcePseudoStateParams, cdp.Empty]{Method: CommandForcePseudoState} -// Do executes CSS.forcePseudoState against the provided context. -func (p *ForcePseudoStateParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandForcePseudoState, p, nil) -} - -// ForceStartingStyleParams ensures that the given node is in its -// starting-style state. +// ForceStartingStyleParams are the parameters of the command +// CSS.forceStartingStyle. type ForceStartingStyleParams struct { NodeID cdp.NodeID `json:"nodeId"` // The element id for which to force the starting-style state. Forced bool `json:"forced"` // Boolean indicating if this is on or off. @@ -243,119 +110,59 @@ type ForceStartingStyleParams struct { // state. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-forceStartingStyle -// -// parameters: -// -// nodeID - The element id for which to force the starting-style state. -// forced - Boolean indicating if this is on or off. -func ForceStartingStyle(nodeID cdp.NodeID, forced bool) *ForceStartingStyleParams { - return &ForceStartingStyleParams{ - NodeID: nodeID, - Forced: forced, - } -} +var ForceStartingStyle = cdp.Command[ForceStartingStyleParams, cdp.Empty]{Method: CommandForceStartingStyle} -// Do executes CSS.forceStartingStyle against the provided context. -func (p *ForceStartingStyleParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandForceStartingStyle, p, nil) +// ForcePositionTryOptionParams are the parameters of the command +// CSS.forcePositionTryOption. +type ForcePositionTryOptionParams struct { + NodeID cdp.NodeID `json:"nodeId"` // The element id for which to force the position-try option. + Index *int64 `json:"index,omitempty,omitzero"` // The 1-based index of the position-try fallback option, 0 for base position (no fallback), or omitted to clear the forced state. } -// GetBackgroundColorsParams [no description]. +// ForcePositionTryOption forces a position-try option for the given node. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-forcePositionTryOption +var ForcePositionTryOption = cdp.Command[ForcePositionTryOptionParams, cdp.Empty]{Method: CommandForcePositionTryOption} + +// GetBackgroundColorsParams are the parameters of the command +// CSS.getBackgroundColors. type GetBackgroundColorsParams struct { NodeID cdp.NodeID `json:"nodeId"` // Id of the node to get background colors for. } -// GetBackgroundColors [no description]. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getBackgroundColors -// -// parameters: -// -// nodeID - Id of the node to get background colors for. -func GetBackgroundColors(nodeID cdp.NodeID) *GetBackgroundColorsParams { - return &GetBackgroundColorsParams{ - NodeID: nodeID, - } -} - -// GetBackgroundColorsReturns return values. -type GetBackgroundColorsReturns struct { +// GetBackgroundColorsResult is the result of the command +// CSS.getBackgroundColors. +type GetBackgroundColorsResult struct { BackgroundColors []string `json:"backgroundColors,omitempty,omitzero"` // The range of background colors behind this element, if it contains any visible text. If no visible text is present, this will be undefined. In the case of a flat background color, this will consist of simply that color. In the case of a gradient, this will consist of each of the color stops. For anything more complicated, this will be an empty array. Images will be ignored (as if the image had failed to load). ComputedFontSize string `json:"computedFontSize,omitempty,omitzero"` // The computed font size for this node, as a CSS computed value string (e.g. '12px'). ComputedFontWeight string `json:"computedFontWeight,omitempty,omitzero"` // The computed font weight for this node, as a CSS computed value string (e.g. 'normal' or '100'). } -// Do executes CSS.getBackgroundColors against the provided context. -// -// returns: +// GetBackgroundColors [no description]. // -// backgroundColors - The range of background colors behind this element, if it contains any visible text. If no visible text is present, this will be undefined. In the case of a flat background color, this will consist of simply that color. In the case of a gradient, this will consist of each of the color stops. For anything more complicated, this will be an empty array. Images will be ignored (as if the image had failed to load). -// computedFontSize - The computed font size for this node, as a CSS computed value string (e.g. '12px'). -// computedFontWeight - The computed font weight for this node, as a CSS computed value string (e.g. 'normal' or '100'). -func (p *GetBackgroundColorsParams) Do(ctx context.Context) (backgroundColors []string, computedFontSize string, computedFontWeight string, err error) { - // execute - var res GetBackgroundColorsReturns - err = cdp.Execute(ctx, CommandGetBackgroundColors, p, &res) - if err != nil { - return nil, "", "", err - } - - return res.BackgroundColors, res.ComputedFontSize, res.ComputedFontWeight, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getBackgroundColors +var GetBackgroundColors = cdp.Command[GetBackgroundColorsParams, GetBackgroundColorsResult]{Method: CommandGetBackgroundColors} -// GetComputedStyleForNodeParams returns the computed style for a DOM node -// identified by nodeId. +// GetComputedStyleForNodeParams are the parameters of the command +// CSS.getComputedStyleForNode. type GetComputedStyleForNodeParams struct { NodeID cdp.NodeID `json:"nodeId"` } -// GetComputedStyleForNode returns the computed style for a DOM node -// identified by nodeId. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getComputedStyleForNode -// -// parameters: -// -// nodeID -func GetComputedStyleForNode(nodeID cdp.NodeID) *GetComputedStyleForNodeParams { - return &GetComputedStyleForNodeParams{ - NodeID: nodeID, - } -} - -// GetComputedStyleForNodeReturns return values. -type GetComputedStyleForNodeReturns struct { +// GetComputedStyleForNodeResult is the result of the command +// CSS.getComputedStyleForNode. +type GetComputedStyleForNodeResult struct { ComputedStyle []*ComputedStyleProperty `json:"computedStyle,omitempty,omitzero"` // Computed style for the specified DOM node. ExtraFields *ComputedStyleExtraFields `json:"extraFields,omitempty,omitzero"` // A list of non-standard "extra fields" which blink stores alongside each computed style. } -// Do executes CSS.getComputedStyleForNode against the provided context. -// -// returns: +// GetComputedStyleForNode returns the computed style for a DOM node +// identified by nodeId. // -// computedStyle - Computed style for the specified DOM node. -// extraFields - A list of non-standard "extra fields" which blink stores alongside each computed style. -func (p *GetComputedStyleForNodeParams) Do(ctx context.Context) (computedStyle []*ComputedStyleProperty, extraFields *ComputedStyleExtraFields, err error) { - // execute - var res GetComputedStyleForNodeReturns - err = cdp.Execute(ctx, CommandGetComputedStyleForNode, p, &res) - if err != nil { - return nil, nil, err - } - - return res.ComputedStyle, res.ExtraFields, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getComputedStyleForNode +var GetComputedStyleForNode = cdp.Command[GetComputedStyleForNodeParams, GetComputedStyleForNodeResult]{Method: CommandGetComputedStyleForNode} -// ResolveValuesParams resolve the specified values in the context of the -// provided element. For example, a value of '1em' is evaluated according to the -// computed 'font-size' of the element and a value 'calc(1px + 2px)' will be -// resolved to '3px'. If the propertyName was specified the values are resolved -// as if they were property's declaration. If a value cannot be parsed according -// to the provided property syntax, the value is parsed using combined syntax as -// if null propertyName was provided. If the value cannot be resolved even then, -// return the provided value without any changes. Note: this function currently -// does not resolve CSS random() function, it returns unmodified random() -// function parts. +// ResolveValuesParams are the parameters of the command CSS.resolveValues. type ResolveValuesParams struct { Values []string `json:"values"` // Cascade-dependent keywords (revert/revert-layer) do not work. NodeID cdp.NodeID `json:"nodeId"` // Id of the node in whose context the expression is evaluated @@ -364,6 +171,11 @@ type ResolveValuesParams struct { PseudoIdentifier string `json:"pseudoIdentifier,omitempty,omitzero"` // Pseudo element custom ident. } +// ResolveValuesResult is the result of the command CSS.resolveValues. +type ResolveValuesResult struct { + Results []string `json:"results,omitempty,omitzero"` +} + // ResolveValues resolve the specified values in the context of the provided // element. For example, a value of '1em' is evaluated according to the computed // 'font-size' of the element and a value 'calc(1px + 2px)' will be resolved to @@ -376,214 +188,76 @@ type ResolveValuesParams struct { // function parts. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-resolveValues -// -// parameters: -// -// values - Cascade-dependent keywords (revert/revert-layer) do not work. -// nodeID - Id of the node in whose context the expression is evaluated -func ResolveValues(values []string, nodeID cdp.NodeID) *ResolveValuesParams { - return &ResolveValuesParams{ - Values: values, - NodeID: nodeID, - } -} - -// WithPropertyName only longhands and custom property names are accepted. -func (p ResolveValuesParams) WithPropertyName(propertyName string) *ResolveValuesParams { - p.PropertyName = propertyName - return &p -} +var ResolveValues = cdp.Command[ResolveValuesParams, ResolveValuesResult]{Method: CommandResolveValues} -// WithPseudoType pseudo element type, only works for pseudo elements that -// generate elements in the tree, such as ::before and ::after. -func (p ResolveValuesParams) WithPseudoType(pseudoType cdp.PseudoType) *ResolveValuesParams { - p.PseudoType = pseudoType - return &p -} - -// WithPseudoIdentifier pseudo element custom ident. -func (p ResolveValuesParams) WithPseudoIdentifier(pseudoIdentifier string) *ResolveValuesParams { - p.PseudoIdentifier = pseudoIdentifier - return &p -} - -// ResolveValuesReturns return values. -type ResolveValuesReturns struct { - Results []string `json:"results,omitempty,omitzero"` -} - -// Do executes CSS.resolveValues against the provided context. -// -// returns: -// -// results -func (p *ResolveValuesParams) Do(ctx context.Context) (results []string, err error) { - // execute - var res ResolveValuesReturns - err = cdp.Execute(ctx, CommandResolveValues, p, &res) - if err != nil { - return nil, err - } - - return res.Results, nil -} - -// GetLonghandPropertiesParams [no description]. +// GetLonghandPropertiesParams are the parameters of the command +// CSS.getLonghandProperties. type GetLonghandPropertiesParams struct { ShorthandName string `json:"shorthandName"` Value string `json:"value"` } -// GetLonghandProperties [no description]. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getLonghandProperties -// -// parameters: -// -// shorthandName -// value -func GetLonghandProperties(shorthandName string, value string) *GetLonghandPropertiesParams { - return &GetLonghandPropertiesParams{ - ShorthandName: shorthandName, - Value: value, - } -} - -// GetLonghandPropertiesReturns return values. -type GetLonghandPropertiesReturns struct { +// GetLonghandPropertiesResult is the result of the command +// CSS.getLonghandProperties. +type GetLonghandPropertiesResult struct { LonghandProperties []*Property `json:"longhandProperties,omitempty,omitzero"` } -// Do executes CSS.getLonghandProperties against the provided context. -// -// returns: +// GetLonghandProperties [no description]. // -// longhandProperties -func (p *GetLonghandPropertiesParams) Do(ctx context.Context) (longhandProperties []*Property, err error) { - // execute - var res GetLonghandPropertiesReturns - err = cdp.Execute(ctx, CommandGetLonghandProperties, p, &res) - if err != nil { - return nil, err - } - - return res.LonghandProperties, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getLonghandProperties +var GetLonghandProperties = cdp.Command[GetLonghandPropertiesParams, GetLonghandPropertiesResult]{Method: CommandGetLonghandProperties} -// GetInlineStylesForNodeParams returns the styles defined inline (explicitly -// in the "style" attribute and implicitly, using DOM attributes) for a DOM node -// identified by nodeId. +// GetInlineStylesForNodeParams are the parameters of the command +// CSS.getInlineStylesForNode. type GetInlineStylesForNodeParams struct { NodeID cdp.NodeID `json:"nodeId"` } -// GetInlineStylesForNode returns the styles defined inline (explicitly in -// the "style" attribute and implicitly, using DOM attributes) for a DOM node -// identified by nodeId. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getInlineStylesForNode -// -// parameters: -// -// nodeID -func GetInlineStylesForNode(nodeID cdp.NodeID) *GetInlineStylesForNodeParams { - return &GetInlineStylesForNodeParams{ - NodeID: nodeID, - } -} - -// GetInlineStylesForNodeReturns return values. -type GetInlineStylesForNodeReturns struct { +// GetInlineStylesForNodeResult is the result of the command +// CSS.getInlineStylesForNode. +type GetInlineStylesForNodeResult struct { InlineStyle *Style `json:"inlineStyle,omitempty,omitzero"` // Inline style for the specified DOM node. AttributesStyle *Style `json:"attributesStyle,omitempty,omitzero"` // Attribute-defined element style (e.g. resulting from "width=20 height=100%"). } -// Do executes CSS.getInlineStylesForNode against the provided context. -// -// returns: +// GetInlineStylesForNode returns the styles defined inline (explicitly in +// the "style" attribute and implicitly, using DOM attributes) for a DOM node +// identified by nodeId. // -// inlineStyle - Inline style for the specified DOM node. -// attributesStyle - Attribute-defined element style (e.g. resulting from "width=20 height=100%"). -func (p *GetInlineStylesForNodeParams) Do(ctx context.Context) (inlineStyle *Style, attributesStyle *Style, err error) { - // execute - var res GetInlineStylesForNodeReturns - err = cdp.Execute(ctx, CommandGetInlineStylesForNode, p, &res) - if err != nil { - return nil, nil, err - } - - return res.InlineStyle, res.AttributesStyle, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getInlineStylesForNode +var GetInlineStylesForNode = cdp.Command[GetInlineStylesForNodeParams, GetInlineStylesForNodeResult]{Method: CommandGetInlineStylesForNode} -// GetAnimatedStylesForNodeParams returns the styles coming from animations & -// transitions including the animation & transition styles coming from -// inheritance chain. +// GetAnimatedStylesForNodeParams are the parameters of the command +// CSS.getAnimatedStylesForNode. type GetAnimatedStylesForNodeParams struct { NodeID cdp.NodeID `json:"nodeId"` } -// GetAnimatedStylesForNode returns the styles coming from animations & -// transitions including the animation & transition styles coming from -// inheritance chain. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getAnimatedStylesForNode -// -// parameters: -// -// nodeID -func GetAnimatedStylesForNode(nodeID cdp.NodeID) *GetAnimatedStylesForNodeParams { - return &GetAnimatedStylesForNodeParams{ - NodeID: nodeID, - } -} - -// GetAnimatedStylesForNodeReturns return values. -type GetAnimatedStylesForNodeReturns struct { +// GetAnimatedStylesForNodeResult is the result of the command +// CSS.getAnimatedStylesForNode. +type GetAnimatedStylesForNodeResult struct { AnimationStyles []*AnimationStyle `json:"animationStyles,omitempty,omitzero"` // Styles coming from animations. TransitionsStyle *Style `json:"transitionsStyle,omitempty,omitzero"` // Style coming from transitions. Inherited []*InheritedAnimatedStyleEntry `json:"inherited,omitempty,omitzero"` // Inherited style entries for animationsStyle and transitionsStyle from the inheritance chain of the element. } -// Do executes CSS.getAnimatedStylesForNode against the provided context. -// -// returns: +// GetAnimatedStylesForNode returns the styles coming from animations & +// transitions including the animation & transition styles coming from +// inheritance chain. // -// animationStyles - Styles coming from animations. -// transitionsStyle - Style coming from transitions. -// inherited - Inherited style entries for animationsStyle and transitionsStyle from the inheritance chain of the element. -func (p *GetAnimatedStylesForNodeParams) Do(ctx context.Context) (animationStyles []*AnimationStyle, transitionsStyle *Style, inherited []*InheritedAnimatedStyleEntry, err error) { - // execute - var res GetAnimatedStylesForNodeReturns - err = cdp.Execute(ctx, CommandGetAnimatedStylesForNode, p, &res) - if err != nil { - return nil, nil, nil, err - } - - return res.AnimationStyles, res.TransitionsStyle, res.Inherited, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getAnimatedStylesForNode +var GetAnimatedStylesForNode = cdp.Command[GetAnimatedStylesForNodeParams, GetAnimatedStylesForNodeResult]{Method: CommandGetAnimatedStylesForNode} -// GetMatchedStylesForNodeParams returns requested styles for a DOM node -// identified by nodeId. +// GetMatchedStylesForNodeParams are the parameters of the command +// CSS.getMatchedStylesForNode. type GetMatchedStylesForNodeParams struct { NodeID cdp.NodeID `json:"nodeId"` } -// GetMatchedStylesForNode returns requested styles for a DOM node identified -// by nodeId. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getMatchedStylesForNode -// -// parameters: -// -// nodeID -func GetMatchedStylesForNode(nodeID cdp.NodeID) *GetMatchedStylesForNodeParams { - return &GetMatchedStylesForNodeParams{ - NodeID: nodeID, - } -} - -// GetMatchedStylesForNodeReturns return values. -type GetMatchedStylesForNodeReturns struct { +// GetMatchedStylesForNodeResult is the result of the command +// CSS.getMatchedStylesForNode. +type GetMatchedStylesForNodeResult struct { InlineStyle *Style `json:"inlineStyle,omitempty,omitzero"` // Inline style for the specified DOM node. AttributesStyle *Style `json:"attributesStyle,omitempty,omitzero"` // Attribute-defined element style (e.g. resulting from "width=20 height=100%"). MatchedCSSRules []*RuleMatch `json:"matchedCSSRules,omitempty,omitzero"` // CSS rules matching this node, from all applicable stylesheets. @@ -600,190 +274,80 @@ type GetMatchedStylesForNodeReturns struct { CSSFunctionRules []*FunctionRule `json:"cssFunctionRules,omitempty,omitzero"` // A list of CSS at-function rules referenced by styles of this node. } -// Do executes CSS.getMatchedStylesForNode against the provided context. -// -// returns: +// GetMatchedStylesForNode returns requested styles for a DOM node identified +// by nodeId. // -// inlineStyle - Inline style for the specified DOM node. -// attributesStyle - Attribute-defined element style (e.g. resulting from "width=20 height=100%"). -// matchedCSSRules - CSS rules matching this node, from all applicable stylesheets. -// pseudoElements - Pseudo style matches for this node. -// inherited - A chain of inherited styles (from the immediate node parent up to the DOM tree root). -// inheritedPseudoElements - A chain of inherited pseudo element styles (from the immediate node parent up to the DOM tree root). -// cssKeyframesRules - A list of CSS keyframed animations matching this node. -// cssPositionTryRules - A list of CSS @position-try rules matching this node, based on the position-try-fallbacks property. -// activePositionFallbackIndex - Index of the active fallback in the applied position-try-fallback property, will not be set if there is no active position-try fallback. -// cssPropertyRules - A list of CSS at-property rules matching this node. -// cssPropertyRegistrations - A list of CSS property registrations matching this node. -// cssAtRules - A list of simple @rules matching this node or its pseudo-elements. -// parentLayoutNodeID - Id of the first parent element that does not have display: contents. -// cssFunctionRules - A list of CSS at-function rules referenced by styles of this node. -func (p *GetMatchedStylesForNodeParams) Do(ctx context.Context) (inlineStyle *Style, attributesStyle *Style, matchedCSSRules []*RuleMatch, pseudoElements []*PseudoElementMatches, inherited []*InheritedStyleEntry, inheritedPseudoElements []*InheritedPseudoElementMatches, cssKeyframesRules []*KeyframesRule, cssPositionTryRules []*PositionTryRule, activePositionFallbackIndex int64, cssPropertyRules []*PropertyRule, cssPropertyRegistrations []*PropertyRegistration, cssAtRules []*AtRule, parentLayoutNodeID cdp.NodeID, cssFunctionRules []*FunctionRule, err error) { - // execute - var res GetMatchedStylesForNodeReturns - err = cdp.Execute(ctx, CommandGetMatchedStylesForNode, p, &res) - if err != nil { - return nil, nil, nil, nil, nil, nil, nil, nil, 0, nil, nil, nil, 0, nil, err - } - - return res.InlineStyle, res.AttributesStyle, res.MatchedCSSRules, res.PseudoElements, res.Inherited, res.InheritedPseudoElements, res.CSSKeyframesRules, res.CSSPositionTryRules, res.ActivePositionFallbackIndex, res.CSSPropertyRules, res.CSSPropertyRegistrations, res.CSSAtRules, res.ParentLayoutNodeID, res.CSSFunctionRules, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getMatchedStylesForNode +var GetMatchedStylesForNode = cdp.Command[GetMatchedStylesForNodeParams, GetMatchedStylesForNodeResult]{Method: CommandGetMatchedStylesForNode} -// GetEnvironmentVariablesParams returns the values of the default UA-defined -// environment variables used in env(). -type GetEnvironmentVariablesParams struct{} +// GetEnvironmentVariablesResult is the result of the command +// CSS.getEnvironmentVariables. +type GetEnvironmentVariablesResult struct { + EnvironmentVariables jsonv2.Value `json:"environmentVariables,omitempty,omitzero"` +} // GetEnvironmentVariables returns the values of the default UA-defined // environment variables used in env(). // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getEnvironmentVariables -func GetEnvironmentVariables() *GetEnvironmentVariablesParams { - return &GetEnvironmentVariablesParams{} -} - -// GetEnvironmentVariablesReturns return values. -type GetEnvironmentVariablesReturns struct { - EnvironmentVariables jsontext.Value `json:"environmentVariables,omitempty,omitzero"` -} +var GetEnvironmentVariables = cdp.Command[cdp.Empty, GetEnvironmentVariablesResult]{Method: CommandGetEnvironmentVariables} -// Do executes CSS.getEnvironmentVariables against the provided context. -// -// returns: -// -// environmentVariables -func (p *GetEnvironmentVariablesParams) Do(ctx context.Context) (environmentVariables jsontext.Value, err error) { - // execute - var res GetEnvironmentVariablesReturns - err = cdp.Execute(ctx, CommandGetEnvironmentVariables, nil, &res) - if err != nil { - return nil, err - } - - return res.EnvironmentVariables, nil +// GetMediaQueriesResult is the result of the command CSS.getMediaQueries. +type GetMediaQueriesResult struct { + Medias []*Media `json:"medias,omitempty,omitzero"` } -// GetMediaQueriesParams returns all media queries parsed by the rendering -// engine. -type GetMediaQueriesParams struct{} - // GetMediaQueries returns all media queries parsed by the rendering engine. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getMediaQueries -func GetMediaQueries() *GetMediaQueriesParams { - return &GetMediaQueriesParams{} -} - -// GetMediaQueriesReturns return values. -type GetMediaQueriesReturns struct { - Medias []*Media `json:"medias,omitempty,omitzero"` -} - -// Do executes CSS.getMediaQueries against the provided context. -// -// returns: -// -// medias -func (p *GetMediaQueriesParams) Do(ctx context.Context) (medias []*Media, err error) { - // execute - var res GetMediaQueriesReturns - err = cdp.Execute(ctx, CommandGetMediaQueries, nil, &res) - if err != nil { - return nil, err - } - - return res.Medias, nil -} +var GetMediaQueries = cdp.Command[cdp.Empty, GetMediaQueriesResult]{Method: CommandGetMediaQueries} -// GetPlatformFontsForNodeParams requests information about platform fonts -// which we used to render child TextNodes in the given node. +// GetPlatformFontsForNodeParams are the parameters of the command +// CSS.getPlatformFontsForNode. type GetPlatformFontsForNodeParams struct { NodeID cdp.NodeID `json:"nodeId"` } -// GetPlatformFontsForNode requests information about platform fonts which we -// used to render child TextNodes in the given node. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getPlatformFontsForNode -// -// parameters: -// -// nodeID -func GetPlatformFontsForNode(nodeID cdp.NodeID) *GetPlatformFontsForNodeParams { - return &GetPlatformFontsForNodeParams{ - NodeID: nodeID, - } -} - -// GetPlatformFontsForNodeReturns return values. -type GetPlatformFontsForNodeReturns struct { +// GetPlatformFontsForNodeResult is the result of the command +// CSS.getPlatformFontsForNode. +type GetPlatformFontsForNodeResult struct { Fonts []*PlatformFontUsage `json:"fonts,omitempty,omitzero"` // Usage statistics for every employed platform font. } -// Do executes CSS.getPlatformFontsForNode against the provided context. -// -// returns: +// GetPlatformFontsForNode requests information about platform fonts which we +// used to render child TextNodes in the given node. // -// fonts - Usage statistics for every employed platform font. -func (p *GetPlatformFontsForNodeParams) Do(ctx context.Context) (fonts []*PlatformFontUsage, err error) { - // execute - var res GetPlatformFontsForNodeReturns - err = cdp.Execute(ctx, CommandGetPlatformFontsForNode, p, &res) - if err != nil { - return nil, err - } - - return res.Fonts, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getPlatformFontsForNode +var GetPlatformFontsForNode = cdp.Command[GetPlatformFontsForNodeParams, GetPlatformFontsForNodeResult]{Method: CommandGetPlatformFontsForNode} -// GetStyleSheetTextParams returns the current textual content for a -// stylesheet. +// GetStyleSheetTextParams are the parameters of the command +// CSS.getStyleSheetText. type GetStyleSheetTextParams struct { StyleSheetID cdp.StyleSheetID `json:"styleSheetId"` } -// GetStyleSheetText returns the current textual content for a stylesheet. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getStyleSheetText -// -// parameters: -// -// styleSheetID -func GetStyleSheetText(styleSheetID cdp.StyleSheetID) *GetStyleSheetTextParams { - return &GetStyleSheetTextParams{ - StyleSheetID: styleSheetID, - } -} - -// GetStyleSheetTextReturns return values. -type GetStyleSheetTextReturns struct { +// GetStyleSheetTextResult is the result of the command +// CSS.getStyleSheetText. +type GetStyleSheetTextResult struct { Text string `json:"text,omitempty,omitzero"` // The stylesheet text. } -// Do executes CSS.getStyleSheetText against the provided context. -// -// returns: +// GetStyleSheetText returns the current textual content for a stylesheet. // -// text - The stylesheet text. -func (p *GetStyleSheetTextParams) Do(ctx context.Context) (text string, err error) { - // execute - var res GetStyleSheetTextReturns - err = cdp.Execute(ctx, CommandGetStyleSheetText, p, &res) - if err != nil { - return "", err - } - - return res.Text, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getStyleSheetText +var GetStyleSheetText = cdp.Command[GetStyleSheetTextParams, GetStyleSheetTextResult]{Method: CommandGetStyleSheetText} -// GetLayersForNodeParams returns all layers parsed by the rendering engine -// for the tree scope of a node. Given a DOM element identified by nodeId, -// getLayersForNode returns the root layer for the nearest ancestor document or -// shadow root. The layer root contains the full layer tree for the tree scope -// and their ordering. +// GetLayersForNodeParams are the parameters of the command +// CSS.getLayersForNode. type GetLayersForNodeParams struct { NodeID cdp.NodeID `json:"nodeId"` } +// GetLayersForNodeResult is the result of the command CSS.getLayersForNode. +type GetLayersForNodeResult struct { + RootLayer *LayerData `json:"rootLayer,omitempty,omitzero"` +} + // GetLayersForNode returns all layers parsed by the rendering engine for the // tree scope of a node. Given a DOM element identified by nodeId, // getLayersForNode returns the root layer for the nearest ancestor document or @@ -791,88 +355,30 @@ type GetLayersForNodeParams struct { // and their ordering. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getLayersForNode -// -// parameters: -// -// nodeID -func GetLayersForNode(nodeID cdp.NodeID) *GetLayersForNodeParams { - return &GetLayersForNodeParams{ - NodeID: nodeID, - } -} +var GetLayersForNode = cdp.Command[GetLayersForNodeParams, GetLayersForNodeResult]{Method: CommandGetLayersForNode} -// GetLayersForNodeReturns return values. -type GetLayersForNodeReturns struct { - RootLayer *LayerData `json:"rootLayer,omitempty,omitzero"` -} - -// Do executes CSS.getLayersForNode against the provided context. -// -// returns: -// -// rootLayer -func (p *GetLayersForNodeParams) Do(ctx context.Context) (rootLayer *LayerData, err error) { - // execute - var res GetLayersForNodeReturns - err = cdp.Execute(ctx, CommandGetLayersForNode, p, &res) - if err != nil { - return nil, err - } - - return res.RootLayer, nil -} - -// GetLocationForSelectorParams given a CSS selector text and a style sheet -// ID, getLocationForSelector returns an array of locations of the CSS selector -// in the style sheet. +// GetLocationForSelectorParams are the parameters of the command +// CSS.getLocationForSelector. type GetLocationForSelectorParams struct { StyleSheetID cdp.StyleSheetID `json:"styleSheetId"` SelectorText string `json:"selectorText"` } +// GetLocationForSelectorResult is the result of the command +// CSS.getLocationForSelector. +type GetLocationForSelectorResult struct { + Ranges []*SourceRange `json:"ranges,omitempty,omitzero"` +} + // GetLocationForSelector given a CSS selector text and a style sheet ID, // getLocationForSelector returns an array of locations of the CSS selector in // the style sheet. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getLocationForSelector -// -// parameters: -// -// styleSheetID -// selectorText -func GetLocationForSelector(styleSheetID cdp.StyleSheetID, selectorText string) *GetLocationForSelectorParams { - return &GetLocationForSelectorParams{ - StyleSheetID: styleSheetID, - SelectorText: selectorText, - } -} - -// GetLocationForSelectorReturns return values. -type GetLocationForSelectorReturns struct { - Ranges []*SourceRange `json:"ranges,omitempty,omitzero"` -} +var GetLocationForSelector = cdp.Command[GetLocationForSelectorParams, GetLocationForSelectorResult]{Method: CommandGetLocationForSelector} -// Do executes CSS.getLocationForSelector against the provided context. -// -// returns: -// -// ranges -func (p *GetLocationForSelectorParams) Do(ctx context.Context) (ranges []*SourceRange, err error) { - // execute - var res GetLocationForSelectorReturns - err = cdp.Execute(ctx, CommandGetLocationForSelector, p, &res) - if err != nil { - return nil, err - } - - return res.Ranges, nil -} - -// TrackComputedStyleUpdatesForNodeParams starts tracking the given node for -// the computed style updates and whenever the computed style is updated for -// node, it queues a computedStyleUpdated event with throttling. There can only -// be 1 node tracked for computed style updates so passing a new node id removes -// tracking from the previous node. Pass undefined to disable tracking. +// TrackComputedStyleUpdatesForNodeParams are the parameters of the command +// CSS.trackComputedStyleUpdatesForNode. type TrackComputedStyleUpdatesForNodeParams struct { NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` } @@ -884,31 +390,10 @@ type TrackComputedStyleUpdatesForNodeParams struct { // tracking from the previous node. Pass undefined to disable tracking. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-trackComputedStyleUpdatesForNode -// -// parameters: -func TrackComputedStyleUpdatesForNode() *TrackComputedStyleUpdatesForNodeParams { - return &TrackComputedStyleUpdatesForNodeParams{} -} - -// WithNodeID [no description]. -func (p TrackComputedStyleUpdatesForNodeParams) WithNodeID(nodeID cdp.NodeID) *TrackComputedStyleUpdatesForNodeParams { - p.NodeID = nodeID - return &p -} +var TrackComputedStyleUpdatesForNode = cdp.Command[TrackComputedStyleUpdatesForNodeParams, cdp.Empty]{Method: CommandTrackComputedStyleUpdatesForNode} -// Do executes CSS.trackComputedStyleUpdatesForNode against the provided context. -func (p *TrackComputedStyleUpdatesForNodeParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandTrackComputedStyleUpdatesForNode, p, nil) -} - -// TrackComputedStyleUpdatesParams starts tracking the given computed styles -// for updates. The specified array of properties replaces the one previously -// specified. Pass empty array to disable tracking. Use takeComputedStyleUpdates -// to retrieve the list of nodes that had properties modified. The changes to -// computed style properties are only tracked for nodes pushed to the front-end -// by the DOM agent. If no changes to the tracked properties occur after the -// node has been pushed to the front-end, no updates will be issued for the -// node. +// TrackComputedStyleUpdatesParams are the parameters of the command +// CSS.trackComputedStyleUpdates. type TrackComputedStyleUpdatesParams struct { PropertiesToTrack []*ComputedStyleProperty `json:"propertiesToTrack"` } @@ -923,55 +408,21 @@ type TrackComputedStyleUpdatesParams struct { // node. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-trackComputedStyleUpdates -// -// parameters: -// -// propertiesToTrack -func TrackComputedStyleUpdates(propertiesToTrack []*ComputedStyleProperty) *TrackComputedStyleUpdatesParams { - return &TrackComputedStyleUpdatesParams{ - PropertiesToTrack: propertiesToTrack, - } -} +var TrackComputedStyleUpdates = cdp.Command[TrackComputedStyleUpdatesParams, cdp.Empty]{Method: CommandTrackComputedStyleUpdates} -// Do executes CSS.trackComputedStyleUpdates against the provided context. -func (p *TrackComputedStyleUpdatesParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandTrackComputedStyleUpdates, p, nil) +// TakeComputedStyleUpdatesResult is the result of the command +// CSS.takeComputedStyleUpdates. +type TakeComputedStyleUpdatesResult struct { + NodeIDs []cdp.NodeID `json:"nodeIds,omitempty,omitzero"` // The list of node Ids that have their tracked computed styles updated. } -// TakeComputedStyleUpdatesParams polls the next batch of computed style -// updates. -type TakeComputedStyleUpdatesParams struct{} - // TakeComputedStyleUpdates polls the next batch of computed style updates. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-takeComputedStyleUpdates -func TakeComputedStyleUpdates() *TakeComputedStyleUpdatesParams { - return &TakeComputedStyleUpdatesParams{} -} - -// TakeComputedStyleUpdatesReturns return values. -type TakeComputedStyleUpdatesReturns struct { - NodeIDs []cdp.NodeID `json:"nodeIds,omitempty,omitzero"` // The list of node Ids that have their tracked computed styles updated. -} +var TakeComputedStyleUpdates = cdp.Command[cdp.Empty, TakeComputedStyleUpdatesResult]{Method: CommandTakeComputedStyleUpdates} -// Do executes CSS.takeComputedStyleUpdates against the provided context. -// -// returns: -// -// nodeIDs - The list of node Ids that have their tracked computed styles updated. -func (p *TakeComputedStyleUpdatesParams) Do(ctx context.Context) (nodeIDs []cdp.NodeID, err error) { - // execute - var res TakeComputedStyleUpdatesReturns - err = cdp.Execute(ctx, CommandTakeComputedStyleUpdates, nil, &res) - if err != nil { - return nil, err - } - - return res.NodeIDs, nil -} - -// SetEffectivePropertyValueForNodeParams find a rule with the given active -// property for the given node and set the new value for this property. +// SetEffectivePropertyValueForNodeParams are the parameters of the command +// CSS.setEffectivePropertyValueForNode. type SetEffectivePropertyValueForNodeParams struct { NodeID cdp.NodeID `json:"nodeId"` // The element id for which to set property. PropertyName string `json:"propertyName"` @@ -982,567 +433,220 @@ type SetEffectivePropertyValueForNodeParams struct { // property for the given node and set the new value for this property. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setEffectivePropertyValueForNode -// -// parameters: -// -// nodeID - The element id for which to set property. -// propertyName -// value -func SetEffectivePropertyValueForNode(nodeID cdp.NodeID, propertyName string, value string) *SetEffectivePropertyValueForNodeParams { - return &SetEffectivePropertyValueForNodeParams{ - NodeID: nodeID, - PropertyName: propertyName, - Value: value, - } -} +var SetEffectivePropertyValueForNode = cdp.Command[SetEffectivePropertyValueForNodeParams, cdp.Empty]{Method: CommandSetEffectivePropertyValueForNode} -// Do executes CSS.setEffectivePropertyValueForNode against the provided context. -func (p *SetEffectivePropertyValueForNodeParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetEffectivePropertyValueForNode, p, nil) -} - -// SetPropertyRulePropertyNameParams modifies the property rule property -// name. +// SetPropertyRulePropertyNameParams are the parameters of the command +// CSS.setPropertyRulePropertyName. type SetPropertyRulePropertyNameParams struct { StyleSheetID cdp.StyleSheetID `json:"styleSheetId"` Range *SourceRange `json:"range"` PropertyName string `json:"propertyName"` } -// SetPropertyRulePropertyName modifies the property rule property name. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setPropertyRulePropertyName -// -// parameters: -// -// styleSheetID -// range -// propertyName -func SetPropertyRulePropertyName(styleSheetID cdp.StyleSheetID, rangeVal *SourceRange, propertyName string) *SetPropertyRulePropertyNameParams { - return &SetPropertyRulePropertyNameParams{ - StyleSheetID: styleSheetID, - Range: rangeVal, - PropertyName: propertyName, - } -} - -// SetPropertyRulePropertyNameReturns return values. -type SetPropertyRulePropertyNameReturns struct { +// SetPropertyRulePropertyNameResult is the result of the command +// CSS.setPropertyRulePropertyName. +type SetPropertyRulePropertyNameResult struct { PropertyName *Value `json:"propertyName,omitempty,omitzero"` // The resulting key text after modification. } -// Do executes CSS.setPropertyRulePropertyName against the provided context. -// -// returns: +// SetPropertyRulePropertyName modifies the property rule property name. // -// propertyName - The resulting key text after modification. -func (p *SetPropertyRulePropertyNameParams) Do(ctx context.Context) (propertyName *Value, err error) { - // execute - var res SetPropertyRulePropertyNameReturns - err = cdp.Execute(ctx, CommandSetPropertyRulePropertyName, p, &res) - if err != nil { - return nil, err - } - - return res.PropertyName, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setPropertyRulePropertyName +var SetPropertyRulePropertyName = cdp.Command[SetPropertyRulePropertyNameParams, SetPropertyRulePropertyNameResult]{Method: CommandSetPropertyRulePropertyName} -// SetKeyframeKeyParams modifies the keyframe rule key text. +// SetKeyframeKeyParams are the parameters of the command CSS.setKeyframeKey. type SetKeyframeKeyParams struct { StyleSheetID cdp.StyleSheetID `json:"styleSheetId"` Range *SourceRange `json:"range"` KeyText string `json:"keyText"` } -// SetKeyframeKey modifies the keyframe rule key text. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setKeyframeKey -// -// parameters: -// -// styleSheetID -// range -// keyText -func SetKeyframeKey(styleSheetID cdp.StyleSheetID, rangeVal *SourceRange, keyText string) *SetKeyframeKeyParams { - return &SetKeyframeKeyParams{ - StyleSheetID: styleSheetID, - Range: rangeVal, - KeyText: keyText, - } -} - -// SetKeyframeKeyReturns return values. -type SetKeyframeKeyReturns struct { +// SetKeyframeKeyResult is the result of the command CSS.setKeyframeKey. +type SetKeyframeKeyResult struct { KeyText *Value `json:"keyText,omitempty,omitzero"` // The resulting key text after modification. } -// Do executes CSS.setKeyframeKey against the provided context. -// -// returns: +// SetKeyframeKey modifies the keyframe rule key text. // -// keyText - The resulting key text after modification. -func (p *SetKeyframeKeyParams) Do(ctx context.Context) (keyText *Value, err error) { - // execute - var res SetKeyframeKeyReturns - err = cdp.Execute(ctx, CommandSetKeyframeKey, p, &res) - if err != nil { - return nil, err - } - - return res.KeyText, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setKeyframeKey +var SetKeyframeKey = cdp.Command[SetKeyframeKeyParams, SetKeyframeKeyResult]{Method: CommandSetKeyframeKey} -// SetMediaTextParams modifies the rule selector. +// SetMediaTextParams are the parameters of the command CSS.setMediaText. type SetMediaTextParams struct { StyleSheetID cdp.StyleSheetID `json:"styleSheetId"` Range *SourceRange `json:"range"` Text string `json:"text"` } -// SetMediaText modifies the rule selector. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setMediaText -// -// parameters: -// -// styleSheetID -// range -// text -func SetMediaText(styleSheetID cdp.StyleSheetID, rangeVal *SourceRange, text string) *SetMediaTextParams { - return &SetMediaTextParams{ - StyleSheetID: styleSheetID, - Range: rangeVal, - Text: text, - } -} - -// SetMediaTextReturns return values. -type SetMediaTextReturns struct { +// SetMediaTextResult is the result of the command CSS.setMediaText. +type SetMediaTextResult struct { Media *Media `json:"media,omitempty,omitzero"` // The resulting CSS media rule after modification. } -// Do executes CSS.setMediaText against the provided context. -// -// returns: +// SetMediaText modifies the rule selector. // -// media - The resulting CSS media rule after modification. -func (p *SetMediaTextParams) Do(ctx context.Context) (media *Media, err error) { - // execute - var res SetMediaTextReturns - err = cdp.Execute(ctx, CommandSetMediaText, p, &res) - if err != nil { - return nil, err - } - - return res.Media, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setMediaText +var SetMediaText = cdp.Command[SetMediaTextParams, SetMediaTextResult]{Method: CommandSetMediaText} -// SetContainerQueryConditionTextParams [no description]. +// SetContainerQueryConditionTextParams are the parameters of the command +// CSS.setContainerQueryConditionText. type SetContainerQueryConditionTextParams struct { StyleSheetID cdp.StyleSheetID `json:"styleSheetId"` Range *SourceRange `json:"range"` Text string `json:"text"` } -// SetContainerQueryConditionText [no description]. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setContainerQueryConditionText -// -// parameters: -// -// styleSheetID -// range -// text -func SetContainerQueryConditionText(styleSheetID cdp.StyleSheetID, rangeVal *SourceRange, text string) *SetContainerQueryConditionTextParams { - return &SetContainerQueryConditionTextParams{ - StyleSheetID: styleSheetID, - Range: rangeVal, - Text: text, - } -} - -// SetContainerQueryConditionTextReturns return values. -type SetContainerQueryConditionTextReturns struct { +// SetContainerQueryConditionTextResult is the result of the command +// CSS.setContainerQueryConditionText. +type SetContainerQueryConditionTextResult struct { ContainerQuery *ContainerQuery `json:"containerQuery,omitempty,omitzero"` // The resulting CSS container query rule after modification. } -// Do executes CSS.setContainerQueryConditionText against the provided context. -// -// returns: +// SetContainerQueryConditionText [no description]. // -// containerQuery - The resulting CSS container query rule after modification. -func (p *SetContainerQueryConditionTextParams) Do(ctx context.Context) (containerQuery *ContainerQuery, err error) { - // execute - var res SetContainerQueryConditionTextReturns - err = cdp.Execute(ctx, CommandSetContainerQueryConditionText, p, &res) - if err != nil { - return nil, err - } - - return res.ContainerQuery, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setContainerQueryConditionText +var SetContainerQueryConditionText = cdp.Command[SetContainerQueryConditionTextParams, SetContainerQueryConditionTextResult]{Method: CommandSetContainerQueryConditionText} -// SetSupportsTextParams modifies the expression of a supports at-rule. +// SetSupportsTextParams are the parameters of the command +// CSS.setSupportsText. type SetSupportsTextParams struct { StyleSheetID cdp.StyleSheetID `json:"styleSheetId"` Range *SourceRange `json:"range"` Text string `json:"text"` } -// SetSupportsText modifies the expression of a supports at-rule. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setSupportsText -// -// parameters: -// -// styleSheetID -// range -// text -func SetSupportsText(styleSheetID cdp.StyleSheetID, rangeVal *SourceRange, text string) *SetSupportsTextParams { - return &SetSupportsTextParams{ - StyleSheetID: styleSheetID, - Range: rangeVal, - Text: text, - } -} - -// SetSupportsTextReturns return values. -type SetSupportsTextReturns struct { +// SetSupportsTextResult is the result of the command CSS.setSupportsText. +type SetSupportsTextResult struct { Supports *Supports `json:"supports,omitempty,omitzero"` // The resulting CSS Supports rule after modification. } -// Do executes CSS.setSupportsText against the provided context. -// -// returns: +// SetSupportsText modifies the expression of a supports at-rule. // -// supports - The resulting CSS Supports rule after modification. -func (p *SetSupportsTextParams) Do(ctx context.Context) (supports *Supports, err error) { - // execute - var res SetSupportsTextReturns - err = cdp.Execute(ctx, CommandSetSupportsText, p, &res) - if err != nil { - return nil, err - } - - return res.Supports, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setSupportsText +var SetSupportsText = cdp.Command[SetSupportsTextParams, SetSupportsTextResult]{Method: CommandSetSupportsText} -// SetNavigationTextParams modifies the expression of a navigation at-rule. +// SetNavigationTextParams are the parameters of the command +// CSS.setNavigationText. type SetNavigationTextParams struct { StyleSheetID cdp.StyleSheetID `json:"styleSheetId"` Range *SourceRange `json:"range"` Text string `json:"text"` } -// SetNavigationText modifies the expression of a navigation at-rule. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setNavigationText -// -// parameters: -// -// styleSheetID -// range -// text -func SetNavigationText(styleSheetID cdp.StyleSheetID, rangeVal *SourceRange, text string) *SetNavigationTextParams { - return &SetNavigationTextParams{ - StyleSheetID: styleSheetID, - Range: rangeVal, - Text: text, - } -} - -// SetNavigationTextReturns return values. -type SetNavigationTextReturns struct { +// SetNavigationTextResult is the result of the command +// CSS.setNavigationText. +type SetNavigationTextResult struct { Navigation *Navigation `json:"navigation,omitempty,omitzero"` // The resulting CSS Navigation rule after modification. } -// Do executes CSS.setNavigationText against the provided context. -// -// returns: +// SetNavigationText modifies the expression of a navigation at-rule. // -// navigation - The resulting CSS Navigation rule after modification. -func (p *SetNavigationTextParams) Do(ctx context.Context) (navigation *Navigation, err error) { - // execute - var res SetNavigationTextReturns - err = cdp.Execute(ctx, CommandSetNavigationText, p, &res) - if err != nil { - return nil, err - } - - return res.Navigation, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setNavigationText +var SetNavigationText = cdp.Command[SetNavigationTextParams, SetNavigationTextResult]{Method: CommandSetNavigationText} -// SetScopeTextParams modifies the expression of a scope at-rule. +// SetScopeTextParams are the parameters of the command CSS.setScopeText. type SetScopeTextParams struct { StyleSheetID cdp.StyleSheetID `json:"styleSheetId"` Range *SourceRange `json:"range"` Text string `json:"text"` } -// SetScopeText modifies the expression of a scope at-rule. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setScopeText -// -// parameters: -// -// styleSheetID -// range -// text -func SetScopeText(styleSheetID cdp.StyleSheetID, rangeVal *SourceRange, text string) *SetScopeTextParams { - return &SetScopeTextParams{ - StyleSheetID: styleSheetID, - Range: rangeVal, - Text: text, - } -} - -// SetScopeTextReturns return values. -type SetScopeTextReturns struct { +// SetScopeTextResult is the result of the command CSS.setScopeText. +type SetScopeTextResult struct { Scope *Scope `json:"scope,omitempty,omitzero"` // The resulting CSS Scope rule after modification. } -// Do executes CSS.setScopeText against the provided context. -// -// returns: +// SetScopeText modifies the expression of a scope at-rule. // -// scope - The resulting CSS Scope rule after modification. -func (p *SetScopeTextParams) Do(ctx context.Context) (scope *Scope, err error) { - // execute - var res SetScopeTextReturns - err = cdp.Execute(ctx, CommandSetScopeText, p, &res) - if err != nil { - return nil, err - } - - return res.Scope, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setScopeText +var SetScopeText = cdp.Command[SetScopeTextParams, SetScopeTextResult]{Method: CommandSetScopeText} -// SetRuleSelectorParams modifies the rule selector. +// SetRuleSelectorParams are the parameters of the command +// CSS.setRuleSelector. type SetRuleSelectorParams struct { StyleSheetID cdp.StyleSheetID `json:"styleSheetId"` Range *SourceRange `json:"range"` Selector string `json:"selector"` } -// SetRuleSelector modifies the rule selector. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setRuleSelector -// -// parameters: -// -// styleSheetID -// range -// selector -func SetRuleSelector(styleSheetID cdp.StyleSheetID, rangeVal *SourceRange, selector string) *SetRuleSelectorParams { - return &SetRuleSelectorParams{ - StyleSheetID: styleSheetID, - Range: rangeVal, - Selector: selector, - } -} - -// SetRuleSelectorReturns return values. -type SetRuleSelectorReturns struct { +// SetRuleSelectorResult is the result of the command CSS.setRuleSelector. +type SetRuleSelectorResult struct { SelectorList *SelectorList `json:"selectorList,omitempty,omitzero"` // The resulting selector list after modification. } -// Do executes CSS.setRuleSelector against the provided context. -// -// returns: +// SetRuleSelector modifies the rule selector. // -// selectorList - The resulting selector list after modification. -func (p *SetRuleSelectorParams) Do(ctx context.Context) (selectorList *SelectorList, err error) { - // execute - var res SetRuleSelectorReturns - err = cdp.Execute(ctx, CommandSetRuleSelector, p, &res) - if err != nil { - return nil, err - } - - return res.SelectorList, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setRuleSelector +var SetRuleSelector = cdp.Command[SetRuleSelectorParams, SetRuleSelectorResult]{Method: CommandSetRuleSelector} -// SetStyleSheetTextParams sets the new stylesheet text. +// SetStyleSheetTextParams are the parameters of the command +// CSS.setStyleSheetText. type SetStyleSheetTextParams struct { StyleSheetID cdp.StyleSheetID `json:"styleSheetId"` Text string `json:"text"` } -// SetStyleSheetText sets the new stylesheet text. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setStyleSheetText -// -// parameters: -// -// styleSheetID -// text -func SetStyleSheetText(styleSheetID cdp.StyleSheetID, text string) *SetStyleSheetTextParams { - return &SetStyleSheetTextParams{ - StyleSheetID: styleSheetID, - Text: text, - } -} - -// SetStyleSheetTextReturns return values. -type SetStyleSheetTextReturns struct { +// SetStyleSheetTextResult is the result of the command +// CSS.setStyleSheetText. +type SetStyleSheetTextResult struct { SourceMapURL string `json:"sourceMapURL,omitempty,omitzero"` // URL of source map associated with script (if any). } -// Do executes CSS.setStyleSheetText against the provided context. -// -// returns: +// SetStyleSheetText sets the new stylesheet text. // -// sourceMapURL - URL of source map associated with script (if any). -func (p *SetStyleSheetTextParams) Do(ctx context.Context) (sourceMapURL string, err error) { - // execute - var res SetStyleSheetTextReturns - err = cdp.Execute(ctx, CommandSetStyleSheetText, p, &res) - if err != nil { - return "", err - } - - return res.SourceMapURL, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setStyleSheetText +var SetStyleSheetText = cdp.Command[SetStyleSheetTextParams, SetStyleSheetTextResult]{Method: CommandSetStyleSheetText} -// SetStyleTextsParams applies specified style edits one after another in the -// given order. +// SetStyleTextsParams are the parameters of the command CSS.setStyleTexts. type SetStyleTextsParams struct { Edits []*StyleDeclarationEdit `json:"edits"` NodeForPropertySyntaxValidation cdp.NodeID `json:"nodeForPropertySyntaxValidation,omitempty,omitzero"` // NodeId for the DOM node in whose context custom property declarations for registered properties should be validated. If omitted, declarations in the new rule text can only be validated statically, which may produce incorrect results if the declaration contains a var() for example. } -// SetStyleTexts applies specified style edits one after another in the given -// order. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setStyleTexts -// -// parameters: -// -// edits -func SetStyleTexts(edits []*StyleDeclarationEdit) *SetStyleTextsParams { - return &SetStyleTextsParams{ - Edits: edits, - } -} - -// WithNodeForPropertySyntaxValidation nodeId for the DOM node in whose -// context custom property declarations for registered properties should be -// validated. If omitted, declarations in the new rule text can only be -// validated statically, which may produce incorrect results if the declaration -// contains a var() for example. -func (p SetStyleTextsParams) WithNodeForPropertySyntaxValidation(nodeForPropertySyntaxValidation cdp.NodeID) *SetStyleTextsParams { - p.NodeForPropertySyntaxValidation = nodeForPropertySyntaxValidation - return &p -} - -// SetStyleTextsReturns return values. -type SetStyleTextsReturns struct { +// SetStyleTextsResult is the result of the command CSS.setStyleTexts. +type SetStyleTextsResult struct { Styles []*Style `json:"styles,omitempty,omitzero"` // The resulting styles after modification. } -// Do executes CSS.setStyleTexts against the provided context. -// -// returns: +// SetStyleTexts applies specified style edits one after another in the given +// order. // -// styles - The resulting styles after modification. -func (p *SetStyleTextsParams) Do(ctx context.Context) (styles []*Style, err error) { - // execute - var res SetStyleTextsReturns - err = cdp.Execute(ctx, CommandSetStyleTexts, p, &res) - if err != nil { - return nil, err - } - - return res.Styles, nil -} - -// StartRuleUsageTrackingParams enables the selector recording. -type StartRuleUsageTrackingParams struct{} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setStyleTexts +var SetStyleTexts = cdp.Command[SetStyleTextsParams, SetStyleTextsResult]{Method: CommandSetStyleTexts} // StartRuleUsageTracking enables the selector recording. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-startRuleUsageTracking -func StartRuleUsageTracking() *StartRuleUsageTrackingParams { - return &StartRuleUsageTrackingParams{} -} +var StartRuleUsageTracking = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandStartRuleUsageTracking} -// Do executes CSS.startRuleUsageTracking against the provided context. -func (p *StartRuleUsageTrackingParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStartRuleUsageTracking, nil, nil) +// StopRuleUsageTrackingResult is the result of the command +// CSS.stopRuleUsageTracking. +type StopRuleUsageTrackingResult struct { + RuleUsage []*RuleUsage `json:"ruleUsage,omitempty,omitzero"` } -// StopRuleUsageTrackingParams stop tracking rule usage and return the list -// of rules that were used since last call to takeCoverageDelta (or since start -// of coverage instrumentation). -type StopRuleUsageTrackingParams struct{} - // StopRuleUsageTracking stop tracking rule usage and return the list of // rules that were used since last call to takeCoverageDelta (or since start of // coverage instrumentation). // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-stopRuleUsageTracking -func StopRuleUsageTracking() *StopRuleUsageTrackingParams { - return &StopRuleUsageTrackingParams{} -} - -// StopRuleUsageTrackingReturns return values. -type StopRuleUsageTrackingReturns struct { - RuleUsage []*RuleUsage `json:"ruleUsage,omitempty,omitzero"` -} +var StopRuleUsageTracking = cdp.Command[cdp.Empty, StopRuleUsageTrackingResult]{Method: CommandStopRuleUsageTracking} -// Do executes CSS.stopRuleUsageTracking against the provided context. -// -// returns: -// -// ruleUsage -func (p *StopRuleUsageTrackingParams) Do(ctx context.Context) (ruleUsage []*RuleUsage, err error) { - // execute - var res StopRuleUsageTrackingReturns - err = cdp.Execute(ctx, CommandStopRuleUsageTracking, nil, &res) - if err != nil { - return nil, err - } - - return res.RuleUsage, nil +// TakeCoverageDeltaResult is the result of the command +// CSS.takeCoverageDelta. +type TakeCoverageDeltaResult struct { + Coverage []*RuleUsage `json:"coverage,omitempty,omitzero"` + Timestamp float64 `json:"timestamp,omitempty,omitzero"` // Monotonically increasing time, in seconds. } -// TakeCoverageDeltaParams obtain list of rules that became used since last -// call to this method (or since start of coverage instrumentation). -type TakeCoverageDeltaParams struct{} - // TakeCoverageDelta obtain list of rules that became used since last call to // this method (or since start of coverage instrumentation). // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-takeCoverageDelta -func TakeCoverageDelta() *TakeCoverageDeltaParams { - return &TakeCoverageDeltaParams{} -} - -// TakeCoverageDeltaReturns return values. -type TakeCoverageDeltaReturns struct { - Coverage []*RuleUsage `json:"coverage,omitempty,omitzero"` - Timestamp float64 `json:"timestamp,omitempty,omitzero"` // Monotonically increasing time, in seconds. -} - -// Do executes CSS.takeCoverageDelta against the provided context. -// -// returns: -// -// coverage -// timestamp - Monotonically increasing time, in seconds. -func (p *TakeCoverageDeltaParams) Do(ctx context.Context) (coverage []*RuleUsage, timestamp float64, err error) { - // execute - var res TakeCoverageDeltaReturns - err = cdp.Execute(ctx, CommandTakeCoverageDelta, nil, &res) - if err != nil { - return nil, 0, err - } - - return res.Coverage, res.Timestamp, nil -} +var TakeCoverageDelta = cdp.Command[cdp.Empty, TakeCoverageDeltaResult]{Method: CommandTakeCoverageDelta} -// SetLocalFontsEnabledParams enables/disables rendering of local CSS fonts -// (enabled by default). +// SetLocalFontsEnabledParams are the parameters of the command +// CSS.setLocalFontsEnabled. type SetLocalFontsEnabledParams struct { Enabled bool `json:"enabled"` // Whether rendering of local fonts is enabled. } @@ -1551,20 +655,41 @@ type SetLocalFontsEnabledParams struct { // (enabled by default). // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setLocalFontsEnabled +var SetLocalFontsEnabled = cdp.Command[SetLocalFontsEnabledParams, cdp.Empty]{Method: CommandSetLocalFontsEnabled} + +// FontsUpdated fires whenever a web font is updated. A non-empty font +// parameter indicates a successfully loaded web font. // -// parameters: +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#event-fontsUpdated +var FontsUpdated = cdp.Event[EventFontsUpdated]{Method: "CSS.fontsUpdated"} + +// MediaQueryResultChanged fires whenever a MediaQuery result changes (for +// example, after a browser window has been resized.) The current implementation +// considers only viewport-dependent media features. // -// enabled - Whether rendering of local fonts is enabled. -func SetLocalFontsEnabled(enabled bool) *SetLocalFontsEnabledParams { - return &SetLocalFontsEnabledParams{ - Enabled: enabled, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#event-mediaQueryResultChanged +var MediaQueryResultChanged = cdp.Event[EventMediaQueryResultChanged]{Method: "CSS.mediaQueryResultChanged"} -// Do executes CSS.setLocalFontsEnabled against the provided context. -func (p *SetLocalFontsEnabledParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetLocalFontsEnabled, p, nil) -} +// StyleSheetAdded fired whenever an active document stylesheet is added. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#event-styleSheetAdded +var StyleSheetAdded = cdp.Event[EventStyleSheetAdded]{Method: "CSS.styleSheetAdded"} + +// StyleSheetChanged fired whenever a stylesheet is changed as a result of +// the client operation. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#event-styleSheetChanged +var StyleSheetChanged = cdp.Event[EventStyleSheetChanged]{Method: "CSS.styleSheetChanged"} + +// StyleSheetRemoved fired whenever an active document stylesheet is removed. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#event-styleSheetRemoved +var StyleSheetRemoved = cdp.Event[EventStyleSheetRemoved]{Method: "CSS.styleSheetRemoved"} + +// ComputedStyleUpdated [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#event-computedStyleUpdated +var ComputedStyleUpdated = cdp.Event[EventComputedStyleUpdated]{Method: "CSS.computedStyleUpdated"} // Command names. const ( @@ -1575,6 +700,7 @@ const ( CommandEnable = "CSS.enable" CommandForcePseudoState = "CSS.forcePseudoState" CommandForceStartingStyle = "CSS.forceStartingStyle" + CommandForcePositionTryOption = "CSS.forcePositionTryOption" CommandGetBackgroundColors = "CSS.getBackgroundColors" CommandGetComputedStyleForNode = "CSS.getComputedStyleForNode" CommandResolveValues = "CSS.resolveValues" diff --git a/vendor/github.com/chromedp/cdproto/css/events.go b/vendor/github.com/chromedp/cdproto/css/events.go index 97b04a555..f0523657a 100644 --- a/vendor/github.com/chromedp/cdproto/css/events.go +++ b/vendor/github.com/chromedp/cdproto/css/events.go @@ -1,6 +1,6 @@ -package css +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package css import ( "github.com/chromedp/cdproto/cdp" diff --git a/vendor/github.com/chromedp/cdproto/css/types.go b/vendor/github.com/chromedp/cdproto/css/types.go index 8f471a6ec..8d3f1ca2c 100644 --- a/vendor/github.com/chromedp/cdproto/css/types.go +++ b/vendor/github.com/chromedp/cdproto/css/types.go @@ -1,11 +1,8 @@ -package css +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package css import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/dom" ) @@ -31,26 +28,6 @@ const ( StyleSheetOriginRegular StyleSheetOrigin = "regular" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *StyleSheetOrigin) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch StyleSheetOrigin(s) { - case StyleSheetOriginInjected: - *t = StyleSheetOriginInjected - case StyleSheetOriginUserAgent: - *t = StyleSheetOriginUserAgent - case StyleSheetOriginInspector: - *t = StyleSheetOriginInspector - case StyleSheetOriginRegular: - *t = StyleSheetOriginRegular - default: - return fmt.Errorf("unknown StyleSheetOrigin value: %v", s) - } - return nil -} - // PseudoElementMatches CSS rule collection for a single pseudo style. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-PseudoElementMatches @@ -210,34 +187,6 @@ const ( RuleTypeNavigationRule RuleType = "NavigationRule" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *RuleType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch RuleType(s) { - case RuleTypeMediaRule: - *t = RuleTypeMediaRule - case RuleTypeSupportsRule: - *t = RuleTypeSupportsRule - case RuleTypeContainerRule: - *t = RuleTypeContainerRule - case RuleTypeLayerRule: - *t = RuleTypeLayerRule - case RuleTypeScopeRule: - *t = RuleTypeScopeRule - case RuleTypeStyleRule: - *t = RuleTypeStyleRule - case RuleTypeStartingStyleRule: - *t = RuleTypeStartingStyleRule - case RuleTypeNavigationRule: - *t = RuleTypeNavigationRule - default: - return fmt.Errorf("unknown RuleType value: %v", s) - } - return nil -} - // RuleUsage CSS coverage information. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-RuleUsage @@ -592,26 +541,6 @@ const ( MediaSourceInlineSheet MediaSource = "inlineSheet" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *MediaSource) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch MediaSource(s) { - case MediaSourceMediaRule: - *t = MediaSourceMediaRule - case MediaSourceImportRule: - *t = MediaSourceImportRule - case MediaSourceLinkedSheet: - *t = MediaSourceLinkedSheet - case MediaSourceInlineSheet: - *t = MediaSourceInlineSheet - default: - return fmt.Errorf("unknown MediaSource value: %v", s) - } - return nil -} - // AtRuleType type of at-rule. // // See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-CSSAtRule @@ -630,26 +559,6 @@ const ( AtRuleTypeCounterStyle AtRuleType = "counter-style" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *AtRuleType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch AtRuleType(s) { - case AtRuleTypeFontFace: - *t = AtRuleTypeFontFace - case AtRuleTypeFontFeatureValues: - *t = AtRuleTypeFontFeatureValues - case AtRuleTypeFontPaletteValues: - *t = AtRuleTypeFontPaletteValues - case AtRuleTypeCounterStyle: - *t = AtRuleTypeCounterStyle - default: - return fmt.Errorf("unknown AtRuleType value: %v", s) - } - return nil -} - // AtRuleSubsection subsection of font-feature-values, if this is a // subsection. // @@ -670,27 +579,3 @@ const ( AtRuleSubsectionStyleset AtRuleSubsection = "styleset" AtRuleSubsectionCharacterVariant AtRuleSubsection = "character-variant" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *AtRuleSubsection) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch AtRuleSubsection(s) { - case AtRuleSubsectionSwash: - *t = AtRuleSubsectionSwash - case AtRuleSubsectionAnnotation: - *t = AtRuleSubsectionAnnotation - case AtRuleSubsectionOrnaments: - *t = AtRuleSubsectionOrnaments - case AtRuleSubsectionStylistic: - *t = AtRuleSubsectionStylistic - case AtRuleSubsectionStyleset: - *t = AtRuleSubsectionStyleset - case AtRuleSubsectionCharacterVariant: - *t = AtRuleSubsectionCharacterVariant - default: - return fmt.Errorf("unknown AtRuleSubsection value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/debugger/debugger.go b/vendor/github.com/chromedp/cdproto/debugger/debugger.go index 96a5c071f..be6d57708 100644 --- a/vendor/github.com/chromedp/cdproto/debugger/debugger.go +++ b/vendor/github.com/chromedp/cdproto/debugger/debugger.go @@ -1,3 +1,5 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package debugger provides the Chrome DevTools Protocol // commands, types, and events for the Debugger domain. // @@ -5,21 +7,16 @@ // setting and removing breakpoints, stepping through execution, exploring stack // traces, etc. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package debugger -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "encoding/base64" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/runtime" ) -// ContinueToLocationParams continues execution until specific location is -// reached. +// ContinueToLocationParams are the parameters of the command +// Debugger.continueToLocation. type ContinueToLocationParams struct { Location *Location `json:"location"` // Location to continue to. TargetCallFrames ContinueToLocationTargetCallFrames `json:"targetCallFrames,omitempty,omitzero"` @@ -28,441 +25,157 @@ type ContinueToLocationParams struct { // ContinueToLocation continues execution until specific location is reached. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-continueToLocation -// -// parameters: -// -// location - Location to continue to. -func ContinueToLocation(location *Location) *ContinueToLocationParams { - return &ContinueToLocationParams{ - Location: location, - } -} - -// WithTargetCallFrames [no description]. -func (p ContinueToLocationParams) WithTargetCallFrames(targetCallFrames ContinueToLocationTargetCallFrames) *ContinueToLocationParams { - p.TargetCallFrames = targetCallFrames - return &p -} - -// Do executes Debugger.continueToLocation against the provided context. -func (p *ContinueToLocationParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandContinueToLocation, p, nil) -} - -// DisableParams disables debugger for given page. -type DisableParams struct{} +var ContinueToLocation = cdp.Command[ContinueToLocationParams, cdp.Empty]{Method: CommandContinueToLocation} // Disable disables debugger for given page. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} -// Do executes Debugger.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// EnableParams enables debugger for the given page. Clients should not -// assume that the debugging has been enabled until the result for this command -// is received. +// EnableParams are the parameters of the command Debugger.enable. type EnableParams struct { MaxScriptsCacheSize float64 `json:"maxScriptsCacheSize,omitempty,omitzero"` // The maximum size in bytes of collected scripts (not referenced by other heap objects) the debugger can hold. Puts no limit if parameter is omitted. } -// Enable enables debugger for the given page. Clients should not assume that -// the debugging has been enabled until the result for this command is received. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-enable -// -// parameters: -func Enable() *EnableParams { - return &EnableParams{} -} - -// WithMaxScriptsCacheSize the maximum size in bytes of collected scripts -// (not referenced by other heap objects) the debugger can hold. Puts no limit -// if parameter is omitted. -func (p EnableParams) WithMaxScriptsCacheSize(maxScriptsCacheSize float64) *EnableParams { - p.MaxScriptsCacheSize = maxScriptsCacheSize - return &p -} - -// EnableReturns return values. -type EnableReturns struct { +// EnableResult is the result of the command Debugger.enable. +type EnableResult struct { DebuggerID cdp.UniqueDebuggerID `json:"debuggerId,omitempty,omitzero"` // Unique identifier of the debugger. } -// Do executes Debugger.enable against the provided context. -// -// returns: +// Enable enables debugger for the given page. Clients should not assume that +// the debugging has been enabled until the result for this command is received. // -// debuggerID - Unique identifier of the debugger. -func (p *EnableParams) Do(ctx context.Context) (debuggerID cdp.UniqueDebuggerID, err error) { - // execute - var res EnableReturns - err = cdp.Execute(ctx, CommandEnable, p, &res) - if err != nil { - return "", err - } - - return res.DebuggerID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-enable +var Enable = cdp.Command[EnableParams, EnableResult]{Method: CommandEnable} -// EvaluateOnCallFrameParams evaluates expression on a given call frame. +// EvaluateOnCallFrameParams are the parameters of the command +// Debugger.evaluateOnCallFrame. type EvaluateOnCallFrameParams struct { - CallFrameID CallFrameID `json:"callFrameId"` // Call frame identifier to evaluate on. - Expression string `json:"expression"` // Expression to evaluate. - ObjectGroup string `json:"objectGroup,omitempty,omitzero"` // String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). - IncludeCommandLineAPI bool `json:"includeCommandLineAPI"` // Specifies whether command line API should be available to the evaluated expression, defaults to false. - Silent bool `json:"silent"` // In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. - ReturnByValue bool `json:"returnByValue"` // Whether the result is expected to be a JSON object that should be sent by value. - GeneratePreview bool `json:"generatePreview"` // Whether preview should be generated for the result. - ThrowOnSideEffect bool `json:"throwOnSideEffect"` // Whether to throw an exception if side effect cannot be ruled out during evaluation. - Timeout runtime.TimeDelta `json:"timeout,omitempty,omitzero"` // Terminate execution after timing out (number of milliseconds). + CallFrameID CallFrameID `json:"callFrameId"` // Call frame identifier to evaluate on. + Expression string `json:"expression"` // Expression to evaluate. + ObjectGroup string `json:"objectGroup,omitempty,omitzero"` // String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + IncludeCommandLineAPI *bool `json:"includeCommandLineAPI,omitempty,omitzero"` // Specifies whether command line API should be available to the evaluated expression, defaults to false. + Silent *bool `json:"silent,omitempty,omitzero"` // In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + ReturnByValue *bool `json:"returnByValue,omitempty,omitzero"` // Whether the result is expected to be a JSON object that should be sent by value. + GeneratePreview *bool `json:"generatePreview,omitempty,omitzero"` // Whether preview should be generated for the result. + ThrowOnSideEffect *bool `json:"throwOnSideEffect,omitempty,omitzero"` // Whether to throw an exception if side effect cannot be ruled out during evaluation. + Timeout runtime.TimeDelta `json:"timeout,omitempty,omitzero"` // Terminate execution after timing out (number of milliseconds). + ScopeNumber int64 `json:"scopeNumber,omitempty,omitzero"` // Specifies the scope number to evaluate the expression in (default: 0, innermost scope). +} + +// EvaluateOnCallFrameResult is the result of the command +// Debugger.evaluateOnCallFrame. +type EvaluateOnCallFrameResult struct { + Result *runtime.RemoteObject `json:"result,omitempty,omitzero"` // Object wrapper for the evaluation result. + ExceptionDetails *runtime.ExceptionDetails `json:"exceptionDetails,omitempty,omitzero"` // Exception details. } // EvaluateOnCallFrame evaluates expression on a given call frame. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-evaluateOnCallFrame -// -// parameters: -// -// callFrameID - Call frame identifier to evaluate on. -// expression - Expression to evaluate. -func EvaluateOnCallFrame(callFrameID CallFrameID, expression string) *EvaluateOnCallFrameParams { - return &EvaluateOnCallFrameParams{ - CallFrameID: callFrameID, - Expression: expression, - IncludeCommandLineAPI: false, - Silent: false, - ReturnByValue: false, - GeneratePreview: false, - ThrowOnSideEffect: false, - } -} - -// WithObjectGroup string object group name to put result into (allows rapid -// releasing resulting object handles using releaseObjectGroup). -func (p EvaluateOnCallFrameParams) WithObjectGroup(objectGroup string) *EvaluateOnCallFrameParams { - p.ObjectGroup = objectGroup - return &p -} +var EvaluateOnCallFrame = cdp.Command[EvaluateOnCallFrameParams, EvaluateOnCallFrameResult]{Method: CommandEvaluateOnCallFrame} -// WithIncludeCommandLineAPI specifies whether command line API should be -// available to the evaluated expression, defaults to false. -func (p EvaluateOnCallFrameParams) WithIncludeCommandLineAPI(includeCommandLineAPI bool) *EvaluateOnCallFrameParams { - p.IncludeCommandLineAPI = includeCommandLineAPI - return &p -} - -// WithSilent in silent mode exceptions thrown during evaluation are not -// reported and do not pause execution. Overrides setPauseOnException state. -func (p EvaluateOnCallFrameParams) WithSilent(silent bool) *EvaluateOnCallFrameParams { - p.Silent = silent - return &p -} - -// WithReturnByValue whether the result is expected to be a JSON object that -// should be sent by value. -func (p EvaluateOnCallFrameParams) WithReturnByValue(returnByValue bool) *EvaluateOnCallFrameParams { - p.ReturnByValue = returnByValue - return &p -} - -// WithGeneratePreview whether preview should be generated for the result. -func (p EvaluateOnCallFrameParams) WithGeneratePreview(generatePreview bool) *EvaluateOnCallFrameParams { - p.GeneratePreview = generatePreview - return &p -} - -// WithThrowOnSideEffect whether to throw an exception if side effect cannot -// be ruled out during evaluation. -func (p EvaluateOnCallFrameParams) WithThrowOnSideEffect(throwOnSideEffect bool) *EvaluateOnCallFrameParams { - p.ThrowOnSideEffect = throwOnSideEffect - return &p -} - -// WithTimeout terminate execution after timing out (number of milliseconds). -func (p EvaluateOnCallFrameParams) WithTimeout(timeout runtime.TimeDelta) *EvaluateOnCallFrameParams { - p.Timeout = timeout - return &p -} - -// EvaluateOnCallFrameReturns return values. -type EvaluateOnCallFrameReturns struct { - Result *runtime.RemoteObject `json:"result,omitempty,omitzero"` // Object wrapper for the evaluation result. - ExceptionDetails *runtime.ExceptionDetails `json:"exceptionDetails,omitempty,omitzero"` // Exception details. -} - -// Do executes Debugger.evaluateOnCallFrame against the provided context. -// -// returns: -// -// result - Object wrapper for the evaluation result. -// exceptionDetails - Exception details. -func (p *EvaluateOnCallFrameParams) Do(ctx context.Context) (result *runtime.RemoteObject, exceptionDetails *runtime.ExceptionDetails, err error) { - // execute - var res EvaluateOnCallFrameReturns - err = cdp.Execute(ctx, CommandEvaluateOnCallFrame, p, &res) - if err != nil { - return nil, nil, err - } - - return res.Result, res.ExceptionDetails, nil +// GetPossibleBreakpointsParams are the parameters of the command +// Debugger.getPossibleBreakpoints. +type GetPossibleBreakpointsParams struct { + Start *Location `json:"start"` // Start of range to search possible breakpoint locations in. + End *Location `json:"end,omitempty,omitzero"` // End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + RestrictToFunction *bool `json:"restrictToFunction,omitempty,omitzero"` // Only consider locations which are in the same (non-nested) function as start. } -// GetPossibleBreakpointsParams returns possible locations for breakpoint. -// scriptId in start and end range locations should be the same. -type GetPossibleBreakpointsParams struct { - Start *Location `json:"start"` // Start of range to search possible breakpoint locations in. - End *Location `json:"end,omitempty,omitzero"` // End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. - RestrictToFunction bool `json:"restrictToFunction"` // Only consider locations which are in the same (non-nested) function as start. +// GetPossibleBreakpointsResult is the result of the command +// Debugger.getPossibleBreakpoints. +type GetPossibleBreakpointsResult struct { + Locations []*BreakLocation `json:"locations,omitempty,omitzero"` // List of the possible breakpoint locations. } // GetPossibleBreakpoints returns possible locations for breakpoint. scriptId // in start and end range locations should be the same. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-getPossibleBreakpoints -// -// parameters: -// -// start - Start of range to search possible breakpoint locations in. -func GetPossibleBreakpoints(start *Location) *GetPossibleBreakpointsParams { - return &GetPossibleBreakpointsParams{ - Start: start, - RestrictToFunction: false, - } -} +var GetPossibleBreakpoints = cdp.Command[GetPossibleBreakpointsParams, GetPossibleBreakpointsResult]{Method: CommandGetPossibleBreakpoints} -// WithEnd end of range to search possible breakpoint locations in -// (excluding). When not specified, end of scripts is used as end of range. -func (p GetPossibleBreakpointsParams) WithEnd(end *Location) *GetPossibleBreakpointsParams { - p.End = end - return &p -} - -// WithRestrictToFunction only consider locations which are in the same -// (non-nested) function as start. -func (p GetPossibleBreakpointsParams) WithRestrictToFunction(restrictToFunction bool) *GetPossibleBreakpointsParams { - p.RestrictToFunction = restrictToFunction - return &p -} - -// GetPossibleBreakpointsReturns return values. -type GetPossibleBreakpointsReturns struct { - Locations []*BreakLocation `json:"locations,omitempty,omitzero"` // List of the possible breakpoint locations. -} - -// Do executes Debugger.getPossibleBreakpoints against the provided context. -// -// returns: -// -// locations - List of the possible breakpoint locations. -func (p *GetPossibleBreakpointsParams) Do(ctx context.Context) (locations []*BreakLocation, err error) { - // execute - var res GetPossibleBreakpointsReturns - err = cdp.Execute(ctx, CommandGetPossibleBreakpoints, p, &res) - if err != nil { - return nil, err - } - - return res.Locations, nil -} - -// GetScriptSourceParams returns source for the script with given id. +// GetScriptSourceParams are the parameters of the command +// Debugger.getScriptSource. type GetScriptSourceParams struct { ScriptID cdp.ScriptID `json:"scriptId"` // Id of the script to get source for. } -// GetScriptSource returns source for the script with given id. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-getScriptSource -// -// parameters: -// -// scriptID - Id of the script to get source for. -func GetScriptSource(scriptID cdp.ScriptID) *GetScriptSourceParams { - return &GetScriptSourceParams{ - ScriptID: scriptID, - } -} - -// GetScriptSourceReturns return values. -type GetScriptSourceReturns struct { +// GetScriptSourceResult is the result of the command +// Debugger.getScriptSource. +type GetScriptSourceResult struct { ScriptSource string `json:"scriptSource,omitempty,omitzero"` // Script source (empty in case of Wasm bytecode). - Bytecode string `json:"bytecode,omitempty,omitzero"` // Wasm bytecode. + Bytecode []byte `json:"bytecode,omitempty,omitzero"` // Wasm bytecode. } -// Do executes Debugger.getScriptSource against the provided context. -// -// returns: +// GetScriptSource returns source for the script with given id. // -// scriptSource - Script source (empty in case of Wasm bytecode). -// bytecode - Wasm bytecode. -func (p *GetScriptSourceParams) Do(ctx context.Context) (scriptSource string, bytecode []byte, err error) { - // execute - var res GetScriptSourceReturns - err = cdp.Execute(ctx, CommandGetScriptSource, p, &res) - if err != nil { - return "", nil, err - } - - // decode - var dec []byte - dec, err = base64.StdEncoding.DecodeString(res.Bytecode) - if err != nil { - return "", nil, err - } - return res.ScriptSource, dec, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-getScriptSource +var GetScriptSource = cdp.Command[GetScriptSourceParams, GetScriptSourceResult]{Method: CommandGetScriptSource} -// DisassembleWasmModuleParams [no description]. +// DisassembleWasmModuleParams are the parameters of the command +// Debugger.disassembleWasmModule. type DisassembleWasmModuleParams struct { ScriptID cdp.ScriptID `json:"scriptId"` // Id of the script to disassemble } -// DisassembleWasmModule [no description]. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-disassembleWasmModule -// -// parameters: -// -// scriptID - Id of the script to disassemble -func DisassembleWasmModule(scriptID cdp.ScriptID) *DisassembleWasmModuleParams { - return &DisassembleWasmModuleParams{ - ScriptID: scriptID, - } -} - -// DisassembleWasmModuleReturns return values. -type DisassembleWasmModuleReturns struct { +// DisassembleWasmModuleResult is the result of the command +// Debugger.disassembleWasmModule. +type DisassembleWasmModuleResult struct { StreamID string `json:"streamId,omitempty,omitzero"` // For large modules, return a stream from which additional chunks of disassembly can be read successively. TotalNumberOfLines int64 `json:"totalNumberOfLines,omitempty,omitzero"` // The total number of lines in the disassembly text. FunctionBodyOffsets []int64 `json:"functionBodyOffsets,omitempty,omitzero"` // The offsets of all function bodies, in the format [start1, end1, start2, end2, ...] where all ends are exclusive. Chunk *WasmDisassemblyChunk `json:"chunk,omitempty,omitzero"` // The first chunk of disassembly. } -// Do executes Debugger.disassembleWasmModule against the provided context. -// -// returns: +// DisassembleWasmModule [no description]. // -// streamID - For large modules, return a stream from which additional chunks of disassembly can be read successively. -// totalNumberOfLines - The total number of lines in the disassembly text. -// functionBodyOffsets - The offsets of all function bodies, in the format [start1, end1, start2, end2, ...] where all ends are exclusive. -// chunk - The first chunk of disassembly. -func (p *DisassembleWasmModuleParams) Do(ctx context.Context) (streamID string, totalNumberOfLines int64, functionBodyOffsets []int64, chunk *WasmDisassemblyChunk, err error) { - // execute - var res DisassembleWasmModuleReturns - err = cdp.Execute(ctx, CommandDisassembleWasmModule, p, &res) - if err != nil { - return "", 0, nil, nil, err - } - - return res.StreamID, res.TotalNumberOfLines, res.FunctionBodyOffsets, res.Chunk, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-disassembleWasmModule +var DisassembleWasmModule = cdp.Command[DisassembleWasmModuleParams, DisassembleWasmModuleResult]{Method: CommandDisassembleWasmModule} -// NextWasmDisassemblyChunkParams disassemble the next chunk of lines for the -// module corresponding to the stream. If disassembly is complete, this API will -// invalidate the streamId and return an empty chunk. Any subsequent calls for -// the now invalid stream will return errors. +// NextWasmDisassemblyChunkParams are the parameters of the command +// Debugger.nextWasmDisassemblyChunk. type NextWasmDisassemblyChunkParams struct { StreamID string `json:"streamId"` } +// NextWasmDisassemblyChunkResult is the result of the command +// Debugger.nextWasmDisassemblyChunk. +type NextWasmDisassemblyChunkResult struct { + Chunk *WasmDisassemblyChunk `json:"chunk,omitempty,omitzero"` // The next chunk of disassembly. +} + // NextWasmDisassemblyChunk disassemble the next chunk of lines for the // module corresponding to the stream. If disassembly is complete, this API will // invalidate the streamId and return an empty chunk. Any subsequent calls for // the now invalid stream will return errors. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-nextWasmDisassemblyChunk -// -// parameters: -// -// streamID -func NextWasmDisassemblyChunk(streamID string) *NextWasmDisassemblyChunkParams { - return &NextWasmDisassemblyChunkParams{ - StreamID: streamID, - } -} - -// NextWasmDisassemblyChunkReturns return values. -type NextWasmDisassemblyChunkReturns struct { - Chunk *WasmDisassemblyChunk `json:"chunk,omitempty,omitzero"` // The next chunk of disassembly. -} +var NextWasmDisassemblyChunk = cdp.Command[NextWasmDisassemblyChunkParams, NextWasmDisassemblyChunkResult]{Method: CommandNextWasmDisassemblyChunk} -// Do executes Debugger.nextWasmDisassemblyChunk against the provided context. -// -// returns: -// -// chunk - The next chunk of disassembly. -func (p *NextWasmDisassemblyChunkParams) Do(ctx context.Context) (chunk *WasmDisassemblyChunk, err error) { - // execute - var res NextWasmDisassemblyChunkReturns - err = cdp.Execute(ctx, CommandNextWasmDisassemblyChunk, p, &res) - if err != nil { - return nil, err - } - - return res.Chunk, nil -} - -// GetStackTraceParams returns stack trace with given stackTraceId. +// GetStackTraceParams are the parameters of the command +// Debugger.getStackTrace. type GetStackTraceParams struct { StackTraceID *runtime.StackTraceID `json:"stackTraceId"` } -// GetStackTrace returns stack trace with given stackTraceId. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-getStackTrace -// -// parameters: -// -// stackTraceID -func GetStackTrace(stackTraceID *runtime.StackTraceID) *GetStackTraceParams { - return &GetStackTraceParams{ - StackTraceID: stackTraceID, - } -} - -// GetStackTraceReturns return values. -type GetStackTraceReturns struct { +// GetStackTraceResult is the result of the command Debugger.getStackTrace. +type GetStackTraceResult struct { StackTrace *runtime.StackTrace `json:"stackTrace,omitempty,omitzero"` } -// Do executes Debugger.getStackTrace against the provided context. -// -// returns: +// GetStackTrace returns stack trace with given stackTraceId. // -// stackTrace -func (p *GetStackTraceParams) Do(ctx context.Context) (stackTrace *runtime.StackTrace, err error) { - // execute - var res GetStackTraceReturns - err = cdp.Execute(ctx, CommandGetStackTrace, p, &res) - if err != nil { - return nil, err - } - - return res.StackTrace, nil -} - -// PauseParams stops on the next JavaScript statement. -type PauseParams struct{} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-getStackTrace +var GetStackTrace = cdp.Command[GetStackTraceParams, GetStackTraceResult]{Method: CommandGetStackTrace} // Pause stops on the next JavaScript statement. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-pause -func Pause() *PauseParams { - return &PauseParams{} -} - -// Do executes Debugger.pause against the provided context. -func (p *PauseParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandPause, nil, nil) -} +var Pause = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandPause} -// RemoveBreakpointParams removes JavaScript breakpoint. +// RemoveBreakpointParams are the parameters of the command +// Debugger.removeBreakpoint. type RemoveBreakpointParams struct { BreakpointID BreakpointID `json:"breakpointId"` } @@ -470,31 +183,10 @@ type RemoveBreakpointParams struct { // RemoveBreakpoint removes JavaScript breakpoint. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-removeBreakpoint -// -// parameters: -// -// breakpointID -func RemoveBreakpoint(breakpointID BreakpointID) *RemoveBreakpointParams { - return &RemoveBreakpointParams{ - BreakpointID: breakpointID, - } -} - -// Do executes Debugger.removeBreakpoint against the provided context. -func (p *RemoveBreakpointParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRemoveBreakpoint, p, nil) -} +var RemoveBreakpoint = cdp.Command[RemoveBreakpointParams, cdp.Empty]{Method: CommandRemoveBreakpoint} -// RestartFrameParams restarts particular call frame from the beginning. The -// old, deprecated behavior of restartFrame is to stay paused and allow further -// CDP commands after a restart was scheduled. This can cause problems with -// restarting, so we now continue execution immediately after it has been -// scheduled until we reach the beginning of the restarted frame. To stay -// back-wards compatible, restartFrame now expects a mode parameter to be -// present. If the mode parameter is missing, restartFrame errors out. The -// various return values are deprecated and callFrames is always empty. Use the -// call frames from the Debugger#paused events instead, that fires once V8 -// pauses at the beginning of the restarted function. +// RestartFrameParams are the parameters of the command +// Debugger.restartFrame. type RestartFrameParams struct { CallFrameID CallFrameID `json:"callFrameId"` // Call frame identifier to evaluate on. Mode RestartFrameMode `json:"mode,omitempty,omitzero"` // The mode parameter must be present and set to 'StepInto', otherwise restartFrame will error out. @@ -512,119 +204,40 @@ type RestartFrameParams struct { // pauses at the beginning of the restarted function. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-restartFrame -// -// parameters: -// -// callFrameID - Call frame identifier to evaluate on. -func RestartFrame(callFrameID CallFrameID) *RestartFrameParams { - return &RestartFrameParams{ - CallFrameID: callFrameID, - } -} +var RestartFrame = cdp.Command[RestartFrameParams, cdp.Empty]{Method: CommandRestartFrame} -// WithMode the mode parameter must be present and set to 'StepInto', -// otherwise restartFrame will error out. -func (p RestartFrameParams) WithMode(mode RestartFrameMode) *RestartFrameParams { - p.Mode = mode - return &p -} - -// Do executes Debugger.restartFrame against the provided context. -func (p *RestartFrameParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRestartFrame, p, nil) -} - -// ResumeParams resumes JavaScript execution. +// ResumeParams are the parameters of the command Debugger.resume. type ResumeParams struct { - TerminateOnResume bool `json:"terminateOnResume"` // Set to true to terminate execution upon resuming execution. In contrast to Runtime.terminateExecution, this will allows to execute further JavaScript (i.e. via evaluation) until execution of the paused code is actually resumed, at which point termination is triggered. If execution is currently not paused, this parameter has no effect. + TerminateOnResume *bool `json:"terminateOnResume,omitempty,omitzero"` // Set to true to terminate execution upon resuming execution. In contrast to Runtime.terminateExecution, this will allows to execute further JavaScript (i.e. via evaluation) until execution of the paused code is actually resumed, at which point termination is triggered. If execution is currently not paused, this parameter has no effect. } // Resume resumes JavaScript execution. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-resume -// -// parameters: -func Resume() *ResumeParams { - return &ResumeParams{ - TerminateOnResume: false, - } -} - -// WithTerminateOnResume set to true to terminate execution upon resuming -// execution. In contrast to Runtime.terminateExecution, this will allows to -// execute further JavaScript (i.e. via evaluation) until execution of the -// paused code is actually resumed, at which point termination is triggered. If -// execution is currently not paused, this parameter has no effect. -func (p ResumeParams) WithTerminateOnResume(terminateOnResume bool) *ResumeParams { - p.TerminateOnResume = terminateOnResume - return &p -} - -// Do executes Debugger.resume against the provided context. -func (p *ResumeParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandResume, p, nil) -} +var Resume = cdp.Command[ResumeParams, cdp.Empty]{Method: CommandResume} -// SearchInContentParams searches for given string in script content. +// SearchInContentParams are the parameters of the command +// Debugger.searchInContent. type SearchInContentParams struct { - ScriptID cdp.ScriptID `json:"scriptId"` // Id of the script to search in. - Query string `json:"query"` // String to search for. - CaseSensitive bool `json:"caseSensitive"` // If true, search is case sensitive. - IsRegex bool `json:"isRegex"` // If true, treats string parameter as regex. -} - -// SearchInContent searches for given string in script content. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-searchInContent -// -// parameters: -// -// scriptID - Id of the script to search in. -// query - String to search for. -func SearchInContent(scriptID cdp.ScriptID, query string) *SearchInContentParams { - return &SearchInContentParams{ - ScriptID: scriptID, - Query: query, - CaseSensitive: false, - IsRegex: false, - } -} - -// WithCaseSensitive if true, search is case sensitive. -func (p SearchInContentParams) WithCaseSensitive(caseSensitive bool) *SearchInContentParams { - p.CaseSensitive = caseSensitive - return &p + ScriptID cdp.ScriptID `json:"scriptId"` // Id of the script to search in. + Query string `json:"query"` // String to search for. + CaseSensitive *bool `json:"caseSensitive,omitempty,omitzero"` // If true, search is case sensitive. + IsRegex *bool `json:"isRegex,omitempty,omitzero"` // If true, treats string parameter as regex. } -// WithIsRegex if true, treats string parameter as regex. -func (p SearchInContentParams) WithIsRegex(isRegex bool) *SearchInContentParams { - p.IsRegex = isRegex - return &p -} - -// SearchInContentReturns return values. -type SearchInContentReturns struct { +// SearchInContentResult is the result of the command +// Debugger.searchInContent. +type SearchInContentResult struct { Result []*SearchMatch `json:"result,omitempty,omitzero"` // List of search matches. } -// Do executes Debugger.searchInContent against the provided context. -// -// returns: +// SearchInContent searches for given string in script content. // -// result - List of search matches. -func (p *SearchInContentParams) Do(ctx context.Context) (result []*SearchMatch, err error) { - // execute - var res SearchInContentReturns - err = cdp.Execute(ctx, CommandSearchInContent, p, &res) - if err != nil { - return nil, err - } - - return res.Result, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-searchInContent +var SearchInContent = cdp.Command[SearchInContentParams, SearchInContentResult]{Method: CommandSearchInContent} -// SetAsyncCallStackDepthParams enables or disables async call stacks -// tracking. +// SetAsyncCallStackDepthParams are the parameters of the command +// Debugger.setAsyncCallStackDepth. type SetAsyncCallStackDepthParams struct { MaxDepth int64 `json:"maxDepth"` // Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). } @@ -632,26 +245,10 @@ type SetAsyncCallStackDepthParams struct { // SetAsyncCallStackDepth enables or disables async call stacks tracking. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setAsyncCallStackDepth -// -// parameters: -// -// maxDepth - Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). -func SetAsyncCallStackDepth(maxDepth int64) *SetAsyncCallStackDepthParams { - return &SetAsyncCallStackDepthParams{ - MaxDepth: maxDepth, - } -} - -// Do executes Debugger.setAsyncCallStackDepth against the provided context. -func (p *SetAsyncCallStackDepthParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetAsyncCallStackDepth, p, nil) -} +var SetAsyncCallStackDepth = cdp.Command[SetAsyncCallStackDepthParams, cdp.Empty]{Method: CommandSetAsyncCallStackDepth} -// SetBlackboxExecutionContextsParams replace previous blackbox execution -// contexts with passed ones. Forces backend to skip stepping/pausing in scripts -// in these execution contexts. VM will try to leave blackboxed script by -// performing 'step in' several times, finally resorting to 'step out' if -// unsuccessful. +// SetBlackboxExecutionContextsParams are the parameters of the command +// Debugger.setBlackboxExecutionContexts. type SetBlackboxExecutionContextsParams struct { UniqueIDs []string `json:"uniqueIds"` // Array of execution context unique ids for the debugger to ignore. } @@ -662,28 +259,13 @@ type SetBlackboxExecutionContextsParams struct { // 'step in' several times, finally resorting to 'step out' if unsuccessful. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setBlackboxExecutionContexts -// -// parameters: -// -// uniqueIDs - Array of execution context unique ids for the debugger to ignore. -func SetBlackboxExecutionContexts(uniqueIDs []string) *SetBlackboxExecutionContextsParams { - return &SetBlackboxExecutionContextsParams{ - UniqueIDs: uniqueIDs, - } -} - -// Do executes Debugger.setBlackboxExecutionContexts against the provided context. -func (p *SetBlackboxExecutionContextsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetBlackboxExecutionContexts, p, nil) -} +var SetBlackboxExecutionContexts = cdp.Command[SetBlackboxExecutionContextsParams, cdp.Empty]{Method: CommandSetBlackboxExecutionContexts} -// SetBlackboxPatternsParams 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. +// SetBlackboxPatternsParams are the parameters of the command +// Debugger.setBlackboxPatterns. type SetBlackboxPatternsParams struct { - Patterns []string `json:"patterns"` // Array of regexps that will be used to check script url for blackbox state. - SkipAnonymous bool `json:"skipAnonymous"` // If true, also ignore scripts with no source url. + Patterns []string `json:"patterns"` // Array of regexps that will be used to check script url for blackbox state. + SkipAnonymous *bool `json:"skipAnonymous,omitempty,omitzero"` // If true, also ignore scripts with no source url. } // SetBlackboxPatterns replace previous blackbox patterns with passed ones. @@ -692,33 +274,10 @@ type SetBlackboxPatternsParams struct { // several times, finally resorting to 'step out' if unsuccessful. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setBlackboxPatterns -// -// parameters: -// -// patterns - Array of regexps that will be used to check script url for blackbox state. -func SetBlackboxPatterns(patterns []string) *SetBlackboxPatternsParams { - return &SetBlackboxPatternsParams{ - Patterns: patterns, - SkipAnonymous: false, - } -} +var SetBlackboxPatterns = cdp.Command[SetBlackboxPatternsParams, cdp.Empty]{Method: CommandSetBlackboxPatterns} -// WithSkipAnonymous if true, also ignore scripts with no source url. -func (p SetBlackboxPatternsParams) WithSkipAnonymous(skipAnonymous bool) *SetBlackboxPatternsParams { - p.SkipAnonymous = skipAnonymous - return &p -} - -// Do executes Debugger.setBlackboxPatterns against the provided context. -func (p *SetBlackboxPatternsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetBlackboxPatterns, p, nil) -} - -// SetBlackboxedRangesParams 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. +// SetBlackboxedRangesParams are the parameters of the command +// Debugger.setBlackboxedRanges. type SetBlackboxedRangesParams struct { ScriptID cdp.ScriptID `json:"scriptId"` // Id of the script. Positions []*ScriptPosition `json:"positions"` @@ -731,127 +290,61 @@ type SetBlackboxedRangesParams struct { // blackboxed. Array should be sorted. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setBlackboxedRanges -// -// parameters: -// -// scriptID - Id of the script. -// positions -func SetBlackboxedRanges(scriptID cdp.ScriptID, positions []*ScriptPosition) *SetBlackboxedRangesParams { - return &SetBlackboxedRangesParams{ - ScriptID: scriptID, - Positions: positions, - } -} +var SetBlackboxedRanges = cdp.Command[SetBlackboxedRangesParams, cdp.Empty]{Method: CommandSetBlackboxedRanges} -// Do executes Debugger.setBlackboxedRanges against the provided context. -func (p *SetBlackboxedRangesParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetBlackboxedRanges, p, nil) -} - -// SetBreakpointParams sets JavaScript breakpoint at a given location. +// SetBreakpointParams are the parameters of the command +// Debugger.setBreakpoint. type SetBreakpointParams struct { Location *Location `json:"location"` // Location to set breakpoint in. Condition string `json:"condition,omitempty,omitzero"` // Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. } -// SetBreakpoint sets JavaScript breakpoint at a given location. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setBreakpoint -// -// parameters: -// -// location - Location to set breakpoint in. -func SetBreakpoint(location *Location) *SetBreakpointParams { - return &SetBreakpointParams{ - Location: location, - } -} - -// WithCondition expression to use as a breakpoint condition. When specified, -// debugger will only stop on the breakpoint if this expression evaluates to -// true. -func (p SetBreakpointParams) WithCondition(condition string) *SetBreakpointParams { - p.Condition = condition - return &p -} - -// SetBreakpointReturns return values. -type SetBreakpointReturns struct { +// SetBreakpointResult is the result of the command Debugger.setBreakpoint. +type SetBreakpointResult struct { BreakpointID BreakpointID `json:"breakpointId,omitempty,omitzero"` // Id of the created breakpoint for further reference. ActualLocation *Location `json:"actualLocation,omitempty,omitzero"` // Location this breakpoint resolved into. } -// Do executes Debugger.setBreakpoint against the provided context. -// -// returns: +// SetBreakpoint sets JavaScript breakpoint at a given location. // -// breakpointID - Id of the created breakpoint for further reference. -// actualLocation - Location this breakpoint resolved into. -func (p *SetBreakpointParams) Do(ctx context.Context) (breakpointID BreakpointID, actualLocation *Location, err error) { - // execute - var res SetBreakpointReturns - err = cdp.Execute(ctx, CommandSetBreakpoint, p, &res) - if err != nil { - return "", nil, err - } - - return res.BreakpointID, res.ActualLocation, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setBreakpoint +var SetBreakpoint = cdp.Command[SetBreakpointParams, SetBreakpointResult]{Method: CommandSetBreakpoint} -// SetInstrumentationBreakpointParams sets instrumentation breakpoint. +// SetInstrumentationBreakpointParams are the parameters of the command +// Debugger.setInstrumentationBreakpoint. type SetInstrumentationBreakpointParams struct { Instrumentation SetInstrumentationBreakpointInstrumentation `json:"instrumentation"` // Instrumentation name. } -// SetInstrumentationBreakpoint sets instrumentation breakpoint. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setInstrumentationBreakpoint -// -// parameters: -// -// instrumentation - Instrumentation name. -func SetInstrumentationBreakpoint(instrumentation SetInstrumentationBreakpointInstrumentation) *SetInstrumentationBreakpointParams { - return &SetInstrumentationBreakpointParams{ - Instrumentation: instrumentation, - } -} - -// SetInstrumentationBreakpointReturns return values. -type SetInstrumentationBreakpointReturns struct { +// SetInstrumentationBreakpointResult is the result of the command +// Debugger.setInstrumentationBreakpoint. +type SetInstrumentationBreakpointResult struct { BreakpointID BreakpointID `json:"breakpointId,omitempty,omitzero"` // Id of the created breakpoint for further reference. } -// Do executes Debugger.setInstrumentationBreakpoint against the provided context. -// -// returns: +// SetInstrumentationBreakpoint sets instrumentation breakpoint. // -// breakpointID - Id of the created breakpoint for further reference. -func (p *SetInstrumentationBreakpointParams) Do(ctx context.Context) (breakpointID BreakpointID, err error) { - // execute - var res SetInstrumentationBreakpointReturns - err = cdp.Execute(ctx, CommandSetInstrumentationBreakpoint, p, &res) - if err != nil { - return "", err - } - - return res.BreakpointID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setInstrumentationBreakpoint +var SetInstrumentationBreakpoint = cdp.Command[SetInstrumentationBreakpointParams, SetInstrumentationBreakpointResult]{Method: CommandSetInstrumentationBreakpoint} -// SetBreakpointByURLParams 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. +// SetBreakpointByURLParams are the parameters of the command +// Debugger.setBreakpointByUrl. type SetBreakpointByURLParams struct { LineNumber int64 `json:"lineNumber"` // Line number to set breakpoint at. URL string `json:"url,omitempty,omitzero"` // URL of the resources to set breakpoint on. URLRegex string `json:"urlRegex,omitempty,omitzero"` // Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. ScriptHash string `json:"scriptHash,omitempty,omitzero"` // Script hash of the resources to set breakpoint on. - ColumnNumber int64 `json:"columnNumber,omitempty,omitzero"` // Offset in the line to set breakpoint at. + ColumnNumber *int64 `json:"columnNumber,omitempty,omitzero"` // Offset in the line to set breakpoint at. Condition string `json:"condition,omitempty,omitzero"` // Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. } +// SetBreakpointByURLResult is the result of the command +// Debugger.setBreakpointByUrl. +type SetBreakpointByURLResult struct { + BreakpointID BreakpointID `json:"breakpointId,omitempty,omitzero"` // Id of the created breakpoint for further reference. + Locations []*Location `json:"locations,omitempty,omitzero"` // List of the locations this breakpoint resolved into upon addition. +} + // SetBreakpointByURL 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. @@ -859,125 +352,30 @@ type SetBreakpointByURLParams struct { // events issued. This logical breakpoint will survive page reloads. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setBreakpointByUrl -// -// parameters: -// -// lineNumber - Line number to set breakpoint at. -func SetBreakpointByURL(lineNumber int64) *SetBreakpointByURLParams { - return &SetBreakpointByURLParams{ - LineNumber: lineNumber, - } -} - -// WithURL URL of the resources to set breakpoint on. -func (p SetBreakpointByURLParams) WithURL(url string) *SetBreakpointByURLParams { - p.URL = url - return &p -} - -// WithURLRegex regex pattern for the URLs of the resources to set -// breakpoints on. Either url or urlRegex must be specified. -func (p SetBreakpointByURLParams) WithURLRegex(urlRegex string) *SetBreakpointByURLParams { - p.URLRegex = urlRegex - return &p -} - -// WithScriptHash script hash of the resources to set breakpoint on. -func (p SetBreakpointByURLParams) WithScriptHash(scriptHash string) *SetBreakpointByURLParams { - p.ScriptHash = scriptHash - return &p -} - -// WithColumnNumber offset in the line to set breakpoint at. -func (p SetBreakpointByURLParams) WithColumnNumber(columnNumber int64) *SetBreakpointByURLParams { - p.ColumnNumber = columnNumber - return &p -} - -// WithCondition expression to use as a breakpoint condition. When specified, -// debugger will only stop on the breakpoint if this expression evaluates to -// true. -func (p SetBreakpointByURLParams) WithCondition(condition string) *SetBreakpointByURLParams { - p.Condition = condition - return &p -} - -// SetBreakpointByURLReturns return values. -type SetBreakpointByURLReturns struct { - BreakpointID BreakpointID `json:"breakpointId,omitempty,omitzero"` // Id of the created breakpoint for further reference. - Locations []*Location `json:"locations,omitempty,omitzero"` // List of the locations this breakpoint resolved into upon addition. -} - -// Do executes Debugger.setBreakpointByUrl against the provided context. -// -// returns: -// -// breakpointID - Id of the created breakpoint for further reference. -// locations - List of the locations this breakpoint resolved into upon addition. -func (p *SetBreakpointByURLParams) Do(ctx context.Context) (breakpointID BreakpointID, locations []*Location, err error) { - // execute - var res SetBreakpointByURLReturns - err = cdp.Execute(ctx, CommandSetBreakpointByURL, p, &res) - if err != nil { - return "", nil, err - } - - return res.BreakpointID, res.Locations, nil -} +var SetBreakpointByURL = cdp.Command[SetBreakpointByURLParams, SetBreakpointByURLResult]{Method: CommandSetBreakpointByURL} -// SetBreakpointOnFunctionCallParams sets JavaScript breakpoint before each -// call to the given function. If another function was created from the same -// source as a given one, calling it will also trigger the breakpoint. +// SetBreakpointOnFunctionCallParams are the parameters of the command +// Debugger.setBreakpointOnFunctionCall. type SetBreakpointOnFunctionCallParams struct { ObjectID runtime.RemoteObjectID `json:"objectId"` // Function object id. Condition string `json:"condition,omitempty,omitzero"` // Expression to use as a breakpoint condition. When specified, debugger will stop on the breakpoint if this expression evaluates to true. } +// SetBreakpointOnFunctionCallResult is the result of the command +// Debugger.setBreakpointOnFunctionCall. +type SetBreakpointOnFunctionCallResult struct { + BreakpointID BreakpointID `json:"breakpointId,omitempty,omitzero"` // Id of the created breakpoint for further reference. +} + // SetBreakpointOnFunctionCall sets JavaScript breakpoint before each call to // the given function. If another function was created from the same source as a // given one, calling it will also trigger the breakpoint. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setBreakpointOnFunctionCall -// -// parameters: -// -// objectID - Function object id. -func SetBreakpointOnFunctionCall(objectID runtime.RemoteObjectID) *SetBreakpointOnFunctionCallParams { - return &SetBreakpointOnFunctionCallParams{ - ObjectID: objectID, - } -} - -// WithCondition expression to use as a breakpoint condition. When specified, -// debugger will stop on the breakpoint if this expression evaluates to true. -func (p SetBreakpointOnFunctionCallParams) WithCondition(condition string) *SetBreakpointOnFunctionCallParams { - p.Condition = condition - return &p -} - -// SetBreakpointOnFunctionCallReturns return values. -type SetBreakpointOnFunctionCallReturns struct { - BreakpointID BreakpointID `json:"breakpointId,omitempty,omitzero"` // Id of the created breakpoint for further reference. -} - -// Do executes Debugger.setBreakpointOnFunctionCall against the provided context. -// -// returns: -// -// breakpointID - Id of the created breakpoint for further reference. -func (p *SetBreakpointOnFunctionCallParams) Do(ctx context.Context) (breakpointID BreakpointID, err error) { - // execute - var res SetBreakpointOnFunctionCallReturns - err = cdp.Execute(ctx, CommandSetBreakpointOnFunctionCall, p, &res) - if err != nil { - return "", err - } - - return res.BreakpointID, nil -} +var SetBreakpointOnFunctionCall = cdp.Command[SetBreakpointOnFunctionCallParams, SetBreakpointOnFunctionCallResult]{Method: CommandSetBreakpointOnFunctionCall} -// SetBreakpointsActiveParams activates / deactivates all breakpoints on the -// page. +// SetBreakpointsActiveParams are the parameters of the command +// Debugger.setBreakpointsActive. type SetBreakpointsActiveParams struct { Active bool `json:"active"` // New value for breakpoints active state. } @@ -985,26 +383,12 @@ type SetBreakpointsActiveParams struct { // SetBreakpointsActive activates / deactivates all breakpoints on the page. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setBreakpointsActive -// -// parameters: -// -// active - New value for breakpoints active state. -func SetBreakpointsActive(active bool) *SetBreakpointsActiveParams { - return &SetBreakpointsActiveParams{ - Active: active, - } -} - -// Do executes Debugger.setBreakpointsActive against the provided context. -func (p *SetBreakpointsActiveParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetBreakpointsActive, p, nil) -} +var SetBreakpointsActive = cdp.Command[SetBreakpointsActiveParams, cdp.Empty]{Method: CommandSetBreakpointsActive} -// SetPauseOnExceptionsParams defines pause on exceptions state. Can be set -// to stop on all exceptions, uncaught exceptions, or caught exceptions, no -// exceptions. Initial pause on exceptions state is none. +// SetPauseOnExceptionsParams are the parameters of the command +// Debugger.setPauseOnExceptions. type SetPauseOnExceptionsParams struct { - State ExceptionsState `json:"state"` // Pause on exceptions mode. + State SetPauseOnExceptionsState `json:"state"` // Pause on exceptions mode. } // SetPauseOnExceptions defines pause on exceptions state. Can be set to stop @@ -1012,23 +396,10 @@ type SetPauseOnExceptionsParams struct { // Initial pause on exceptions state is none. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setPauseOnExceptions -// -// parameters: -// -// state - Pause on exceptions mode. -func SetPauseOnExceptions(state ExceptionsState) *SetPauseOnExceptionsParams { - return &SetPauseOnExceptionsParams{ - State: state, - } -} - -// Do executes Debugger.setPauseOnExceptions against the provided context. -func (p *SetPauseOnExceptionsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetPauseOnExceptions, p, nil) -} +var SetPauseOnExceptions = cdp.Command[SetPauseOnExceptionsParams, cdp.Empty]{Method: CommandSetPauseOnExceptions} -// SetReturnValueParams changes return value in top frame. Available only at -// return break position. +// SetReturnValueParams are the parameters of the command +// Debugger.setReturnValue. type SetReturnValueParams struct { NewValue *runtime.CallArgument `json:"newValue"` // New return value. } @@ -1037,96 +408,10 @@ type SetReturnValueParams struct { // break position. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setReturnValue -// -// parameters: -// -// newValue - New return value. -func SetReturnValue(newValue *runtime.CallArgument) *SetReturnValueParams { - return &SetReturnValueParams{ - NewValue: newValue, - } -} - -// Do executes Debugger.setReturnValue against the provided context. -func (p *SetReturnValueParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetReturnValue, p, nil) -} - -// SetScriptSourceParams edits JavaScript source live. In general, functions -// that are currently on the stack can not be edited with a single exception: If -// the edited function is the top-most stack frame and that is the only -// activation of that function on the stack. In this case the live edit will be -// successful and a Debugger.restartFrame for the top-most function is -// automatically triggered. -type SetScriptSourceParams struct { - ScriptID cdp.ScriptID `json:"scriptId"` // Id of the script to edit. - ScriptSource string `json:"scriptSource"` // New content of the script. - DryRun bool `json:"dryRun"` // If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. - AllowTopFrameEditing bool `json:"allowTopFrameEditing"` // If true, then scriptSource is allowed to change the function on top of the stack as long as the top-most stack frame is the only activation of that function. -} - -// SetScriptSource edits JavaScript source live. In general, functions that -// are currently on the stack can not be edited with a single exception: If the -// edited function is the top-most stack frame and that is the only activation -// of that function on the stack. In this case the live edit will be successful -// and a Debugger.restartFrame for the top-most function is automatically -// triggered. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setScriptSource -// -// parameters: -// -// scriptID - Id of the script to edit. -// scriptSource - New content of the script. -func SetScriptSource(scriptID cdp.ScriptID, scriptSource string) *SetScriptSourceParams { - return &SetScriptSourceParams{ - ScriptID: scriptID, - ScriptSource: scriptSource, - DryRun: false, - AllowTopFrameEditing: false, - } -} - -// WithDryRun if true the change will not actually be applied. Dry run may be -// used to get result description without actually modifying the code. -func (p SetScriptSourceParams) WithDryRun(dryRun bool) *SetScriptSourceParams { - p.DryRun = dryRun - return &p -} +var SetReturnValue = cdp.Command[SetReturnValueParams, cdp.Empty]{Method: CommandSetReturnValue} -// WithAllowTopFrameEditing if true, then scriptSource is allowed to change -// the function on top of the stack as long as the top-most stack frame is the -// only activation of that function. -func (p SetScriptSourceParams) WithAllowTopFrameEditing(allowTopFrameEditing bool) *SetScriptSourceParams { - p.AllowTopFrameEditing = allowTopFrameEditing - return &p -} - -// SetScriptSourceReturns return values. -type SetScriptSourceReturns struct { - Status SetScriptSourceStatus `json:"status,omitempty,omitzero"` // Whether the operation was successful or not. Only Ok denotes a successful live edit while the other enum variants denote why the live edit failed. - ExceptionDetails *runtime.ExceptionDetails `json:"exceptionDetails,omitempty,omitzero"` // Exception details if any. Only present when status is CompileError. -} - -// Do executes Debugger.setScriptSource against the provided context. -// -// returns: -// -// status - Whether the operation was successful or not. Only Ok denotes a successful live edit while the other enum variants denote why the live edit failed. -// exceptionDetails - Exception details if any. Only present when status is CompileError. -func (p *SetScriptSourceParams) Do(ctx context.Context) (status SetScriptSourceStatus, exceptionDetails *runtime.ExceptionDetails, err error) { - // execute - var res SetScriptSourceReturns - err = cdp.Execute(ctx, CommandSetScriptSource, p, &res) - if err != nil { - return "", nil, err - } - - return res.Status, res.ExceptionDetails, nil -} - -// SetSkipAllPausesParams makes page not interrupt on any pauses (breakpoint, -// exception, dom exception etc). +// SetSkipAllPausesParams are the parameters of the command +// Debugger.setSkipAllPauses. type SetSkipAllPausesParams struct { Skip bool `json:"skip"` // New value for skip pauses state. } @@ -1135,23 +420,10 @@ type SetSkipAllPausesParams struct { // exception, dom exception etc). // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setSkipAllPauses -// -// parameters: -// -// skip - New value for skip pauses state. -func SetSkipAllPauses(skip bool) *SetSkipAllPausesParams { - return &SetSkipAllPausesParams{ - Skip: skip, - } -} +var SetSkipAllPauses = cdp.Command[SetSkipAllPausesParams, cdp.Empty]{Method: CommandSetSkipAllPauses} -// Do executes Debugger.setSkipAllPauses against the provided context. -func (p *SetSkipAllPausesParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetSkipAllPauses, p, nil) -} - -// SetVariableValueParams changes value of variable in a callframe. -// Object-based scopes are not supported and must be mutated manually. +// SetVariableValueParams are the parameters of the command +// Debugger.setVariableValue. type SetVariableValueParams struct { ScopeNumber int64 `json:"scopeNumber"` // 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. VariableName string `json:"variableName"` // Variable name. @@ -1163,103 +435,56 @@ type SetVariableValueParams struct { // scopes are not supported and must be mutated manually. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setVariableValue -// -// parameters: -// -// scopeNumber - 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. -// variableName - Variable name. -// newValue - New variable value. -// callFrameID - Id of callframe that holds variable. -func SetVariableValue(scopeNumber int64, variableName string, newValue *runtime.CallArgument, callFrameID CallFrameID) *SetVariableValueParams { - return &SetVariableValueParams{ - ScopeNumber: scopeNumber, - VariableName: variableName, - NewValue: newValue, - CallFrameID: callFrameID, - } -} +var SetVariableValue = cdp.Command[SetVariableValueParams, cdp.Empty]{Method: CommandSetVariableValue} -// Do executes Debugger.setVariableValue against the provided context. -func (p *SetVariableValueParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetVariableValue, p, nil) -} - -// StepIntoParams steps into the function call. +// StepIntoParams are the parameters of the command Debugger.stepInto. type StepIntoParams struct { - BreakOnAsyncCall bool `json:"breakOnAsyncCall"` // Debugger will pause on the execution of the first async task which was scheduled before next pause. - SkipList []*LocationRange `json:"skipList,omitempty,omitzero"` // The skipList specifies location ranges that should be skipped on step into. + BreakOnAsyncCall *bool `json:"breakOnAsyncCall,omitempty,omitzero"` // Debugger will pause on the execution of the first async task which was scheduled before next pause. + SkipList []*LocationRange `json:"skipList,omitempty,omitzero"` // The skipList specifies location ranges that should be skipped on step into. } // StepInto steps into the function call. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-stepInto -// -// parameters: -func StepInto() *StepIntoParams { - return &StepIntoParams{ - BreakOnAsyncCall: false, - } -} - -// WithBreakOnAsyncCall debugger will pause on the execution of the first -// async task which was scheduled before next pause. -func (p StepIntoParams) WithBreakOnAsyncCall(breakOnAsyncCall bool) *StepIntoParams { - p.BreakOnAsyncCall = breakOnAsyncCall - return &p -} - -// WithSkipList the skipList specifies location ranges that should be skipped -// on step into. -func (p StepIntoParams) WithSkipList(skipList []*LocationRange) *StepIntoParams { - p.SkipList = skipList - return &p -} - -// Do executes Debugger.stepInto against the provided context. -func (p *StepIntoParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStepInto, p, nil) -} - -// StepOutParams steps out of the function call. -type StepOutParams struct{} +var StepInto = cdp.Command[StepIntoParams, cdp.Empty]{Method: CommandStepInto} // StepOut steps out of the function call. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-stepOut -func StepOut() *StepOutParams { - return &StepOutParams{} -} +var StepOut = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandStepOut} -// Do executes Debugger.stepOut against the provided context. -func (p *StepOutParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStepOut, nil, nil) -} - -// StepOverParams steps over the statement. +// StepOverParams are the parameters of the command Debugger.stepOver. type StepOverParams struct { - SkipList []*LocationRange `json:"skipList,omitempty,omitzero"` // The skipList specifies location ranges that should be skipped on step over. + SkipList []*LocationRange `json:"skipList,omitempty,omitzero"` // The skipList specifies location ranges that should be skipped on step over. + EnterRanges []*LocationRange `json:"enterRanges,omitempty,omitzero"` // Functions whose source range lies within one of the enterRanges are entered as if by stepInto, even when they are called (directly or indirectly) from a call that is stepped over. } // StepOver steps over the statement. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-stepOver +var StepOver = cdp.Command[StepOverParams, cdp.Empty]{Method: CommandStepOver} + +// Paused fired when the virtual machine stopped on breakpoint or exception +// or any other stop criteria. // -// parameters: -func StepOver() *StepOverParams { - return &StepOverParams{} -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#event-paused +var Paused = cdp.Event[EventPaused]{Method: "Debugger.paused"} -// WithSkipList the skipList specifies location ranges that should be skipped -// on step over. -func (p StepOverParams) WithSkipList(skipList []*LocationRange) *StepOverParams { - p.SkipList = skipList - return &p -} +// Resumed fired when the virtual machine resumed execution. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#event-resumed +var Resumed = cdp.Event[EventResumed]{Method: "Debugger.resumed"} -// Do executes Debugger.stepOver against the provided context. -func (p *StepOverParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStepOver, p, nil) -} +// ScriptFailedToParse fired when virtual machine fails to parse the script. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#event-scriptFailedToParse +var ScriptFailedToParse = cdp.Event[EventScriptFailedToParse]{Method: "Debugger.scriptFailedToParse"} + +// ScriptParsed fired when virtual machine parses script. This event is also +// fired for all known and uncollected scripts upon enabling debugger. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#event-scriptParsed +var ScriptParsed = cdp.Event[EventScriptParsed]{Method: "Debugger.scriptParsed"} // Command names. const ( @@ -1288,7 +513,6 @@ const ( CommandSetBreakpointsActive = "Debugger.setBreakpointsActive" CommandSetPauseOnExceptions = "Debugger.setPauseOnExceptions" CommandSetReturnValue = "Debugger.setReturnValue" - CommandSetScriptSource = "Debugger.setScriptSource" CommandSetSkipAllPauses = "Debugger.setSkipAllPauses" CommandSetVariableValue = "Debugger.setVariableValue" CommandStepInto = "Debugger.stepInto" diff --git a/vendor/github.com/chromedp/cdproto/debugger/events.go b/vendor/github.com/chromedp/cdproto/debugger/events.go index 8ae33a439..e1135cc5c 100644 --- a/vendor/github.com/chromedp/cdproto/debugger/events.go +++ b/vendor/github.com/chromedp/cdproto/debugger/events.go @@ -1,11 +1,11 @@ -package debugger +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package debugger import ( "github.com/chromedp/cdproto/cdp" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" "github.com/chromedp/cdproto/runtime" - "github.com/go-json-experiment/json/jsontext" ) // EventPaused fired when the virtual machine stopped on breakpoint or @@ -15,7 +15,7 @@ import ( type EventPaused struct { CallFrames []*CallFrame `json:"callFrames"` // Call stack the virtual machine stopped on. Reason PausedReason `json:"reason"` // Pause reason. - Data jsontext.Value `json:"data,omitempty,omitzero"` + Data jsonv2.Value `json:"data,omitempty,omitzero"` HitBreakpoints []string `json:"hitBreakpoints,omitempty,omitzero"` // Hit breakpoints IDs AsyncStackTrace *runtime.StackTrace `json:"asyncStackTrace,omitempty,omitzero"` // Async stack trace, if any. AsyncStackTraceID *runtime.StackTraceID `json:"asyncStackTraceId,omitempty,omitzero"` // Async stack trace, if any. @@ -40,7 +40,7 @@ type EventScriptFailedToParse struct { ExecutionContextID runtime.ExecutionContextID `json:"executionContextId"` // Specifies script creation context. Hash string `json:"hash"` // Content hash of the script, SHA-256. BuildID string `json:"buildId"` // For Wasm modules, the content of the build_id custom section. For JavaScript the debugId magic comment. - ExecutionContextAuxData jsontext.Value `json:"executionContextAuxData,omitempty,omitzero"` + ExecutionContextAuxData jsonv2.Value `json:"executionContextAuxData,omitempty,omitzero"` SourceMapURL string `json:"sourceMapURL,omitempty,omitzero"` // URL of source map associated with script (if any). HasSourceURL bool `json:"hasSourceURL"` // True, if this script has sourceURL. IsModule bool `json:"isModule"` // True, if this script is ES6 module. @@ -65,7 +65,7 @@ type EventScriptParsed struct { ExecutionContextID runtime.ExecutionContextID `json:"executionContextId"` // Specifies script creation context. Hash string `json:"hash"` // Content hash of the script, SHA-256. BuildID string `json:"buildId"` // For Wasm modules, the content of the build_id custom section. For JavaScript the debugId magic comment. - ExecutionContextAuxData jsontext.Value `json:"executionContextAuxData,omitempty,omitzero"` + ExecutionContextAuxData jsonv2.Value `json:"executionContextAuxData,omitempty,omitzero"` IsLiveEdit bool `json:"isLiveEdit"` // True, if this script is generated as a result of the live edit operation. SourceMapURL string `json:"sourceMapURL,omitempty,omitzero"` // URL of source map associated with script (if any). HasSourceURL bool `json:"hasSourceURL"` // True, if this script has sourceURL. diff --git a/vendor/github.com/chromedp/cdproto/debugger/types.go b/vendor/github.com/chromedp/cdproto/debugger/types.go index bab9d0f27..c568e640c 100644 --- a/vendor/github.com/chromedp/cdproto/debugger/types.go +++ b/vendor/github.com/chromedp/cdproto/debugger/types.go @@ -1,11 +1,8 @@ -package debugger +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package debugger import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/runtime" ) @@ -36,7 +33,7 @@ func (t CallFrameID) String() string { type Location struct { ScriptID cdp.ScriptID `json:"scriptId"` // Script identifier as reported in the Debugger.scriptParsed. LineNumber int64 `json:"lineNumber"` // Line number in the script (0-based). - ColumnNumber int64 `json:"columnNumber,omitempty,omitzero"` // Column number in the script (0-based). + ColumnNumber *int64 `json:"columnNumber,omitempty,omitzero"` // Column number in the script (0-based). } // ScriptPosition location in the source code. @@ -79,6 +76,7 @@ type Scope struct { Name string `json:"name,omitempty,omitzero"` StartLocation *Location `json:"startLocation,omitempty,omitzero"` // Location in the source code where scope starts EndLocation *Location `json:"endLocation,omitempty,omitzero"` // Location in the source code where scope ends + EmptyReason ScopeEmptyReason `json:"emptyReason,omitempty,omitzero"` // Present if the scope has no variable values to show. Absent means that the scope declares at least one variable with an available value. Empty scopes are retained in the scope chain because they can be targeted via evaluateOnCallFrame (using scopeNumber) or matched against scopes in source maps. } // SearchMatch search match for resource. @@ -123,22 +121,6 @@ const ( ScriptLanguageWebAssembly ScriptLanguage = "WebAssembly" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ScriptLanguage) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ScriptLanguage(s) { - case ScriptLanguageJavaScript: - *t = ScriptLanguageJavaScript - case ScriptLanguageWebAssembly: - *t = ScriptLanguageWebAssembly - default: - return fmt.Errorf("unknown ScriptLanguage value: %v", s) - } - return nil -} - // DebugSymbols debug symbols available for a wasm script. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#type-DebugSymbols @@ -179,38 +161,26 @@ const ( ScopeTypeWasmExpressionStack ScopeType = "wasm-expression-stack" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ScopeType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ScopeType(s) { - case ScopeTypeGlobal: - *t = ScopeTypeGlobal - case ScopeTypeLocal: - *t = ScopeTypeLocal - case ScopeTypeWith: - *t = ScopeTypeWith - case ScopeTypeClosure: - *t = ScopeTypeClosure - case ScopeTypeCatch: - *t = ScopeTypeCatch - case ScopeTypeBlock: - *t = ScopeTypeBlock - case ScopeTypeScript: - *t = ScopeTypeScript - case ScopeTypeEval: - *t = ScopeTypeEval - case ScopeTypeModule: - *t = ScopeTypeModule - case ScopeTypeWasmExpressionStack: - *t = ScopeTypeWasmExpressionStack - default: - return fmt.Errorf("unknown ScopeType value: %v", s) - } - return nil +// ScopeEmptyReason present if the scope has no variable values to show. +// Absent means that the scope declares at least one variable with an available +// value. Empty scopes are retained in the scope chain because they can be +// targeted via evaluateOnCallFrame (using scopeNumber) or matched against +// scopes in source maps. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#type-Scope +type ScopeEmptyReason string + +// String returns the ScopeEmptyReason as string value. +func (t ScopeEmptyReason) String() string { + return string(t) } +// ScopeEmptyReason values. +const ( + ScopeEmptyReasonNoVariables ScopeEmptyReason = "no-variables" + ScopeEmptyReasonAllUnavailable ScopeEmptyReason = "all-unavailable" +) + // BreakLocationType [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#type-BreakLocation @@ -228,24 +198,6 @@ const ( BreakLocationTypeReturn BreakLocationType = "return" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *BreakLocationType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch BreakLocationType(s) { - case BreakLocationTypeDebuggerStatement: - *t = BreakLocationTypeDebuggerStatement - case BreakLocationTypeCall: - *t = BreakLocationTypeCall - case BreakLocationTypeReturn: - *t = BreakLocationTypeReturn - default: - return fmt.Errorf("unknown BreakLocationType value: %v", s) - } - return nil -} - // DebugSymbolsType type of the debug symbols. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#type-DebugSymbols @@ -263,24 +215,6 @@ const ( DebugSymbolsTypeExternalDWARF DebugSymbolsType = "ExternalDWARF" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DebugSymbolsType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DebugSymbolsType(s) { - case DebugSymbolsTypeSourceMap: - *t = DebugSymbolsTypeSourceMap - case DebugSymbolsTypeEmbeddedDWARF: - *t = DebugSymbolsTypeEmbeddedDWARF - case DebugSymbolsTypeExternalDWARF: - *t = DebugSymbolsTypeExternalDWARF - default: - return fmt.Errorf("unknown DebugSymbolsType value: %v", s) - } - return nil -} - // PausedReason pause reason. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#event-paused @@ -308,44 +242,6 @@ const ( PausedReasonStep PausedReason = "step" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *PausedReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch PausedReason(s) { - case PausedReasonAmbiguous: - *t = PausedReasonAmbiguous - case PausedReasonAssert: - *t = PausedReasonAssert - case PausedReasonCSPViolation: - *t = PausedReasonCSPViolation - case PausedReasonDebugCommand: - *t = PausedReasonDebugCommand - case PausedReasonDOM: - *t = PausedReasonDOM - case PausedReasonEventListener: - *t = PausedReasonEventListener - case PausedReasonException: - *t = PausedReasonException - case PausedReasonInstrumentation: - *t = PausedReasonInstrumentation - case PausedReasonOOM: - *t = PausedReasonOOM - case PausedReasonOther: - *t = PausedReasonOther - case PausedReasonPromiseRejection: - *t = PausedReasonPromiseRejection - case PausedReasonXHR: - *t = PausedReasonXHR - case PausedReasonStep: - *t = PausedReasonStep - default: - return fmt.Errorf("unknown PausedReason value: %v", s) - } - return nil -} - // ContinueToLocationTargetCallFrames [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-continueToLocation @@ -362,22 +258,6 @@ const ( ContinueToLocationTargetCallFramesCurrent ContinueToLocationTargetCallFrames = "current" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ContinueToLocationTargetCallFrames) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ContinueToLocationTargetCallFrames(s) { - case ContinueToLocationTargetCallFramesAny: - *t = ContinueToLocationTargetCallFramesAny - case ContinueToLocationTargetCallFramesCurrent: - *t = ContinueToLocationTargetCallFramesCurrent - default: - return fmt.Errorf("unknown ContinueToLocationTargetCallFrames value: %v", s) - } - return nil -} - // RestartFrameMode the mode parameter must be present and set to 'StepInto', // otherwise restartFrame will error out. // @@ -394,20 +274,6 @@ const ( RestartFrameModeStepInto RestartFrameMode = "StepInto" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *RestartFrameMode) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch RestartFrameMode(s) { - case RestartFrameModeStepInto: - *t = RestartFrameModeStepInto - default: - return fmt.Errorf("unknown RestartFrameMode value: %v", s) - } - return nil -} - // SetInstrumentationBreakpointInstrumentation instrumentation name. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setInstrumentationBreakpoint @@ -424,99 +290,20 @@ const ( SetInstrumentationBreakpointInstrumentationBeforeScriptWithSourceMapExecution SetInstrumentationBreakpointInstrumentation = "beforeScriptWithSourceMapExecution" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SetInstrumentationBreakpointInstrumentation) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SetInstrumentationBreakpointInstrumentation(s) { - case SetInstrumentationBreakpointInstrumentationBeforeScriptExecution: - *t = SetInstrumentationBreakpointInstrumentationBeforeScriptExecution - case SetInstrumentationBreakpointInstrumentationBeforeScriptWithSourceMapExecution: - *t = SetInstrumentationBreakpointInstrumentationBeforeScriptWithSourceMapExecution - default: - return fmt.Errorf("unknown SetInstrumentationBreakpointInstrumentation value: %v", s) - } - return nil -} - -// ExceptionsState pause on exceptions mode. +// SetPauseOnExceptionsState pause on exceptions mode. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setPauseOnExceptions -type ExceptionsState string - -// String returns the ExceptionsState as string value. -func (t ExceptionsState) String() string { - return string(t) -} +type SetPauseOnExceptionsState string -// ExceptionsState values. -const ( - ExceptionsStateNone ExceptionsState = "none" - ExceptionsStateCaught ExceptionsState = "caught" - ExceptionsStateUncaught ExceptionsState = "uncaught" - ExceptionsStateAll ExceptionsState = "all" -) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ExceptionsState) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ExceptionsState(s) { - case ExceptionsStateNone: - *t = ExceptionsStateNone - case ExceptionsStateCaught: - *t = ExceptionsStateCaught - case ExceptionsStateUncaught: - *t = ExceptionsStateUncaught - case ExceptionsStateAll: - *t = ExceptionsStateAll - default: - return fmt.Errorf("unknown ExceptionsState value: %v", s) - } - return nil -} - -// SetScriptSourceStatus whether the operation was successful or not. Only Ok -// denotes a successful live edit while the other enum variants denote why the -// live edit failed. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setScriptSource -type SetScriptSourceStatus string - -// String returns the SetScriptSourceStatus as string value. -func (t SetScriptSourceStatus) String() string { +// String returns the SetPauseOnExceptionsState as string value. +func (t SetPauseOnExceptionsState) String() string { return string(t) } -// SetScriptSourceStatus values. +// SetPauseOnExceptionsState values. const ( - SetScriptSourceStatusOk SetScriptSourceStatus = "Ok" - SetScriptSourceStatusCompileError SetScriptSourceStatus = "CompileError" - SetScriptSourceStatusBlockedByActiveGenerator SetScriptSourceStatus = "BlockedByActiveGenerator" - SetScriptSourceStatusBlockedByActiveFunction SetScriptSourceStatus = "BlockedByActiveFunction" - SetScriptSourceStatusBlockedByTopLevelEsModuleChange SetScriptSourceStatus = "BlockedByTopLevelEsModuleChange" + SetPauseOnExceptionsStateNone SetPauseOnExceptionsState = "none" + SetPauseOnExceptionsStateCaught SetPauseOnExceptionsState = "caught" + SetPauseOnExceptionsStateUncaught SetPauseOnExceptionsState = "uncaught" + SetPauseOnExceptionsStateAll SetPauseOnExceptionsState = "all" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SetScriptSourceStatus) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SetScriptSourceStatus(s) { - case SetScriptSourceStatusOk: - *t = SetScriptSourceStatusOk - case SetScriptSourceStatusCompileError: - *t = SetScriptSourceStatusCompileError - case SetScriptSourceStatusBlockedByActiveGenerator: - *t = SetScriptSourceStatusBlockedByActiveGenerator - case SetScriptSourceStatusBlockedByActiveFunction: - *t = SetScriptSourceStatusBlockedByActiveFunction - case SetScriptSourceStatusBlockedByTopLevelEsModuleChange: - *t = SetScriptSourceStatusBlockedByTopLevelEsModuleChange - default: - return fmt.Errorf("unknown SetScriptSourceStatus value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/deviceaccess/deviceaccess.go b/vendor/github.com/chromedp/cdproto/deviceaccess/deviceaccess.go index cc1ea6e84..a676c6e5e 100644 --- a/vendor/github.com/chromedp/cdproto/deviceaccess/deviceaccess.go +++ b/vendor/github.com/chromedp/cdproto/deviceaccess/deviceaccess.go @@ -1,49 +1,27 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package deviceaccess provides the Chrome DevTools Protocol // commands, types, and events for the DeviceAccess domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package deviceaccess -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// EnableParams enable events in this domain. -type EnableParams struct{} - // Enable enable events in this domain. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DeviceAccess#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} - -// Do executes DeviceAccess.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) -} - -// DisableParams disable events in this domain. -type DisableParams struct{} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} // Disable disable events in this domain. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DeviceAccess#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} -// Do executes DeviceAccess.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// SelectPromptParams select a device in response to a -// DeviceAccess.deviceRequestPrompted event. +// SelectPromptParams are the parameters of the command +// DeviceAccess.selectPrompt. type SelectPromptParams struct { ID RequestID `json:"id"` DeviceID DeviceID `json:"deviceId"` @@ -53,25 +31,10 @@ type SelectPromptParams struct { // DeviceAccess.deviceRequestPrompted event. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DeviceAccess#method-selectPrompt -// -// parameters: -// -// id -// deviceID -func SelectPrompt(id RequestID, deviceID DeviceID) *SelectPromptParams { - return &SelectPromptParams{ - ID: id, - DeviceID: deviceID, - } -} +var SelectPrompt = cdp.Command[SelectPromptParams, cdp.Empty]{Method: CommandSelectPrompt} -// Do executes DeviceAccess.selectPrompt against the provided context. -func (p *SelectPromptParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSelectPrompt, p, nil) -} - -// CancelPromptParams cancel a prompt in response to a -// DeviceAccess.deviceRequestPrompted event. +// CancelPromptParams are the parameters of the command +// DeviceAccess.cancelPrompt. type CancelPromptParams struct { ID RequestID `json:"id"` } @@ -80,20 +43,13 @@ type CancelPromptParams struct { // DeviceAccess.deviceRequestPrompted event. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DeviceAccess#method-cancelPrompt -// -// parameters: -// -// id -func CancelPrompt(id RequestID) *CancelPromptParams { - return &CancelPromptParams{ - ID: id, - } -} +var CancelPrompt = cdp.Command[CancelPromptParams, cdp.Empty]{Method: CommandCancelPrompt} -// Do executes DeviceAccess.cancelPrompt against the provided context. -func (p *CancelPromptParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandCancelPrompt, p, nil) -} +// DeviceRequestPrompted a device request opened a user prompt to select a +// device. Respond with the selectPrompt or cancelPrompt command. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DeviceAccess#event-deviceRequestPrompted +var DeviceRequestPrompted = cdp.Event[EventDeviceRequestPrompted]{Method: "DeviceAccess.deviceRequestPrompted"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/deviceaccess/events.go b/vendor/github.com/chromedp/cdproto/deviceaccess/events.go index 53e0a0e3f..37a115102 100644 --- a/vendor/github.com/chromedp/cdproto/deviceaccess/events.go +++ b/vendor/github.com/chromedp/cdproto/deviceaccess/events.go @@ -1,6 +1,6 @@ -package deviceaccess +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package deviceaccess // EventDeviceRequestPrompted a device request opened a user prompt to select // a device. Respond with the selectPrompt or cancelPrompt command. diff --git a/vendor/github.com/chromedp/cdproto/deviceaccess/types.go b/vendor/github.com/chromedp/cdproto/deviceaccess/types.go index ea8baa1e9..73d873b0d 100644 --- a/vendor/github.com/chromedp/cdproto/deviceaccess/types.go +++ b/vendor/github.com/chromedp/cdproto/deviceaccess/types.go @@ -1,6 +1,6 @@ -package deviceaccess +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package deviceaccess // RequestID device request id. // diff --git a/vendor/github.com/chromedp/cdproto/deviceorientation/deviceorientation.go b/vendor/github.com/chromedp/cdproto/deviceorientation/deviceorientation.go index befec47e0..663a50d04 100644 --- a/vendor/github.com/chromedp/cdproto/deviceorientation/deviceorientation.go +++ b/vendor/github.com/chromedp/cdproto/deviceorientation/deviceorientation.go @@ -1,34 +1,22 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package deviceorientation provides the Chrome DevTools Protocol // commands, types, and events for the DeviceOrientation domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package deviceorientation -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// ClearDeviceOrientationOverrideParams clears the overridden Device -// Orientation. -type ClearDeviceOrientationOverrideParams struct{} - // ClearDeviceOrientationOverride clears the overridden Device Orientation. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DeviceOrientation#method-clearDeviceOrientationOverride -func ClearDeviceOrientationOverride() *ClearDeviceOrientationOverrideParams { - return &ClearDeviceOrientationOverrideParams{} -} - -// Do executes DeviceOrientation.clearDeviceOrientationOverride against the provided context. -func (p *ClearDeviceOrientationOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClearDeviceOrientationOverride, nil, nil) -} +var ClearDeviceOrientationOverride = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandClearDeviceOrientationOverride} -// SetDeviceOrientationOverrideParams overrides the Device Orientation. +// SetDeviceOrientationOverrideParams are the parameters of the command +// DeviceOrientation.setDeviceOrientationOverride. type SetDeviceOrientationOverrideParams struct { Alpha float64 `json:"alpha"` // Mock alpha Beta float64 `json:"beta"` // Mock beta @@ -38,24 +26,7 @@ type SetDeviceOrientationOverrideParams struct { // SetDeviceOrientationOverride overrides the Device Orientation. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DeviceOrientation#method-setDeviceOrientationOverride -// -// parameters: -// -// alpha - Mock alpha -// beta - Mock beta -// gamma - Mock gamma -func SetDeviceOrientationOverride(alpha float64, beta float64, gamma float64) *SetDeviceOrientationOverrideParams { - return &SetDeviceOrientationOverrideParams{ - Alpha: alpha, - Beta: beta, - Gamma: gamma, - } -} - -// Do executes DeviceOrientation.setDeviceOrientationOverride against the provided context. -func (p *SetDeviceOrientationOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetDeviceOrientationOverride, p, nil) -} +var SetDeviceOrientationOverride = cdp.Command[SetDeviceOrientationOverrideParams, cdp.Empty]{Method: CommandSetDeviceOrientationOverride} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/digitalcredentials/digitalcredentials.go b/vendor/github.com/chromedp/cdproto/digitalcredentials/digitalcredentials.go index 4ec992869..61300b1ac 100644 --- a/vendor/github.com/chromedp/cdproto/digitalcredentials/digitalcredentials.go +++ b/vendor/github.com/chromedp/cdproto/digitalcredentials/digitalcredentials.go @@ -1,27 +1,25 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package digitalcredentials provides the Chrome DevTools Protocol // commands, types, and events for the DigitalCredentials domain. // // This domain allows interacting with the Digital Credentials API for // automation. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package digitalcredentials -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" - "github.com/go-json-experiment/json/jsontext" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" ) -// SetVirtualWalletBehaviorParams sets the behavior of the virtual wallet for -// digital credential requests issued from this frame. +// SetVirtualWalletBehaviorParams are the parameters of the command +// DigitalCredentials.setVirtualWalletBehavior. type SetVirtualWalletBehaviorParams struct { Action VirtualWalletAction `json:"action"` // The action of the virtual wallet. Protocol string `json:"protocol,omitempty,omitzero"` // The protocol identifier (e.g. "openid4vp"). Required when |action| is "respond", forbidden otherwise. - Response jsontext.Value `json:"response,omitempty,omitzero"` + Response jsonv2.Value `json:"response,omitempty,omitzero"` FrameID cdp.FrameID `json:"frameId,omitempty,omitzero"` // The frame to scope the virtual wallet behavior to. } @@ -29,40 +27,7 @@ type SetVirtualWalletBehaviorParams struct { // digital credential requests issued from this frame. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DigitalCredentials#method-setVirtualWalletBehavior -// -// parameters: -// -// action - The action of the virtual wallet. -func SetVirtualWalletBehavior(action VirtualWalletAction) *SetVirtualWalletBehaviorParams { - return &SetVirtualWalletBehaviorParams{ - Action: action, - } -} - -// WithProtocol the protocol identifier (e.g. "openid4vp"). Required when -// |action| is "respond", forbidden otherwise. -func (p SetVirtualWalletBehaviorParams) WithProtocol(protocol string) *SetVirtualWalletBehaviorParams { - p.Protocol = protocol - return &p -} - -// WithResponse the response data object returned by the wallet. Required -// when |action| is "respond", forbidden otherwise. -func (p SetVirtualWalletBehaviorParams) WithResponse(response jsontext.Value) *SetVirtualWalletBehaviorParams { - p.Response = response - return &p -} - -// WithFrameID the frame to scope the virtual wallet behavior to. -func (p SetVirtualWalletBehaviorParams) WithFrameID(frameID cdp.FrameID) *SetVirtualWalletBehaviorParams { - p.FrameID = frameID - return &p -} - -// Do executes DigitalCredentials.setVirtualWalletBehavior against the provided context. -func (p *SetVirtualWalletBehaviorParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetVirtualWalletBehavior, p, nil) -} +var SetVirtualWalletBehavior = cdp.Command[SetVirtualWalletBehaviorParams, cdp.Empty]{Method: CommandSetVirtualWalletBehavior} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/digitalcredentials/types.go b/vendor/github.com/chromedp/cdproto/digitalcredentials/types.go index c47af0aae..c79e2bdf6 100644 --- a/vendor/github.com/chromedp/cdproto/digitalcredentials/types.go +++ b/vendor/github.com/chromedp/cdproto/digitalcredentials/types.go @@ -1,11 +1,6 @@ -package digitalcredentials - -import ( - "fmt" - "strings" -) +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package digitalcredentials // VirtualWalletAction the type of virtual wallet action. // @@ -24,23 +19,3 @@ const ( VirtualWalletActionWait VirtualWalletAction = "wait" VirtualWalletActionClear VirtualWalletAction = "clear" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *VirtualWalletAction) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch VirtualWalletAction(s) { - case VirtualWalletActionRespond: - *t = VirtualWalletActionRespond - case VirtualWalletActionDecline: - *t = VirtualWalletActionDecline - case VirtualWalletActionWait: - *t = VirtualWalletActionWait - case VirtualWalletActionClear: - *t = VirtualWalletActionClear - default: - return fmt.Errorf("unknown VirtualWalletAction value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/dom/dom.go b/vendor/github.com/chromedp/cdproto/dom/dom.go index d09039136..2ee50c5f2 100644 --- a/vendor/github.com/chromedp/cdproto/dom/dom.go +++ b/vendor/github.com/chromedp/cdproto/dom/dom.go @@ -1,3 +1,5 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package dom provides the Chrome DevTools Protocol // commands, types, and events for the DOM domain. // @@ -11,190 +13,72 @@ // client. Note that iframe owner elements will return corresponding document // elements as their child nodes. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package dom -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/runtime" ) -// CollectClassNamesFromSubtreeParams collects class names for the node with -// given id and all of it's child nodes. +// CollectClassNamesFromSubtreeParams are the parameters of the command +// DOM.collectClassNamesFromSubtree. type CollectClassNamesFromSubtreeParams struct { NodeID cdp.NodeID `json:"nodeId"` // Id of the node to collect class names. } -// CollectClassNamesFromSubtree collects class names for the node with given -// id and all of it's child nodes. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-collectClassNamesFromSubtree -// -// parameters: -// -// nodeID - Id of the node to collect class names. -func CollectClassNamesFromSubtree(nodeID cdp.NodeID) *CollectClassNamesFromSubtreeParams { - return &CollectClassNamesFromSubtreeParams{ - NodeID: nodeID, - } -} - -// CollectClassNamesFromSubtreeReturns return values. -type CollectClassNamesFromSubtreeReturns struct { +// CollectClassNamesFromSubtreeResult is the result of the command +// DOM.collectClassNamesFromSubtree. +type CollectClassNamesFromSubtreeResult struct { ClassNames []string `json:"classNames,omitempty,omitzero"` // Class name list. } -// Do executes DOM.collectClassNamesFromSubtree against the provided context. -// -// returns: +// CollectClassNamesFromSubtree collects class names for the node with given +// id and all of it's child nodes. // -// classNames - Class name list. -func (p *CollectClassNamesFromSubtreeParams) Do(ctx context.Context) (classNames []string, err error) { - // execute - var res CollectClassNamesFromSubtreeReturns - err = cdp.Execute(ctx, CommandCollectClassNamesFromSubtree, p, &res) - if err != nil { - return nil, err - } - - return res.ClassNames, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-collectClassNamesFromSubtree +var CollectClassNamesFromSubtree = cdp.Command[CollectClassNamesFromSubtreeParams, CollectClassNamesFromSubtreeResult]{Method: CommandCollectClassNamesFromSubtree} -// CopyToParams creates a deep copy of the specified node and places it into -// the target container before the given anchor. +// CopyToParams are the parameters of the command DOM.copyTo. type CopyToParams struct { NodeID cdp.NodeID `json:"nodeId"` // Id of the node to copy. TargetNodeID cdp.NodeID `json:"targetNodeId"` // Id of the element to drop the copy into. InsertBeforeNodeID cdp.NodeID `json:"insertBeforeNodeId,omitempty,omitzero"` // Drop the copy before this node (if absent, the copy becomes the last child of targetNodeId). } -// CopyTo creates a deep copy of the specified node and places it into the -// target container before the given anchor. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-copyTo -// -// parameters: -// -// nodeID - Id of the node to copy. -// targetNodeID - Id of the element to drop the copy into. -func CopyTo(nodeID cdp.NodeID, targetNodeID cdp.NodeID) *CopyToParams { - return &CopyToParams{ - NodeID: nodeID, - TargetNodeID: targetNodeID, - } -} - -// WithInsertBeforeNodeID drop the copy before this node (if absent, the copy -// becomes the last child of targetNodeId). -func (p CopyToParams) WithInsertBeforeNodeID(insertBeforeNodeID cdp.NodeID) *CopyToParams { - p.InsertBeforeNodeID = insertBeforeNodeID - return &p -} - -// CopyToReturns return values. -type CopyToReturns struct { +// CopyToResult is the result of the command DOM.copyTo. +type CopyToResult struct { NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Id of the node clone. } -// Do executes DOM.copyTo against the provided context. -// -// returns: +// CopyTo creates a deep copy of the specified node and places it into the +// target container before the given anchor. // -// nodeID - Id of the node clone. -func (p *CopyToParams) Do(ctx context.Context) (nodeID cdp.NodeID, err error) { - // execute - var res CopyToReturns - err = cdp.Execute(ctx, CommandCopyTo, p, &res) - if err != nil { - return 0, err - } - - return res.NodeID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-copyTo +var CopyTo = cdp.Command[CopyToParams, CopyToResult]{Method: CommandCopyTo} -// DescribeNodeParams describes node given its id, does not require domain to -// be enabled. Does not start tracking any objects, can be used for automation. +// DescribeNodeParams are the parameters of the command DOM.describeNode. type DescribeNodeParams struct { NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Identifier of the node. BackendNodeID cdp.BackendNodeID `json:"backendNodeId,omitempty,omitzero"` // Identifier of the backend node. ObjectID runtime.RemoteObjectID `json:"objectId,omitempty,omitzero"` // JavaScript object id of the node wrapper. - Depth int64 `json:"depth,omitempty,omitzero"` // The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the entire subtree or provide an integer larger than 0. - Pierce bool `json:"pierce"` // Whether or not iframes and shadow roots should be traversed when returning the subtree (default is false). -} - -// DescribeNode describes node given its id, does not require domain to be -// enabled. Does not start tracking any objects, can be used for automation. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-describeNode -// -// parameters: -func DescribeNode() *DescribeNodeParams { - return &DescribeNodeParams{ - Pierce: false, - } -} - -// WithNodeID identifier of the node. -func (p DescribeNodeParams) WithNodeID(nodeID cdp.NodeID) *DescribeNodeParams { - p.NodeID = nodeID - return &p -} - -// WithBackendNodeID identifier of the backend node. -func (p DescribeNodeParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *DescribeNodeParams { - p.BackendNodeID = backendNodeID - return &p -} - -// WithObjectID JavaScript object id of the node wrapper. -func (p DescribeNodeParams) WithObjectID(objectID runtime.RemoteObjectID) *DescribeNodeParams { - p.ObjectID = objectID - return &p -} - -// WithDepth the maximum depth at which children should be retrieved, -// defaults to 1. Use -1 for the entire subtree or provide an integer larger -// than 0. -func (p DescribeNodeParams) WithDepth(depth int64) *DescribeNodeParams { - p.Depth = depth - return &p + Depth *int64 `json:"depth,omitempty,omitzero"` // The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the entire subtree or provide an integer larger than 0. + Pierce *bool `json:"pierce,omitempty,omitzero"` // Whether or not iframes and shadow roots should be traversed when returning the subtree (default is false). } -// WithPierce whether or not iframes and shadow roots should be traversed -// when returning the subtree (default is false). -func (p DescribeNodeParams) WithPierce(pierce bool) *DescribeNodeParams { - p.Pierce = pierce - return &p -} - -// DescribeNodeReturns return values. -type DescribeNodeReturns struct { +// DescribeNodeResult is the result of the command DOM.describeNode. +type DescribeNodeResult struct { Node *cdp.Node `json:"node,omitempty,omitzero"` // Node description. } -// Do executes DOM.describeNode against the provided context. -// -// returns: +// DescribeNode describes node given its id, does not require domain to be +// enabled. Does not start tracking any objects, can be used for automation. // -// node - Node description. -func (p *DescribeNodeParams) Do(ctx context.Context) (node *cdp.Node, err error) { - // execute - var res DescribeNodeReturns - err = cdp.Execute(ctx, CommandDescribeNode, p, &res) - if err != nil { - return nil, err - } - - return res.Node, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-describeNode +var DescribeNode = cdp.Command[DescribeNodeParams, DescribeNodeResult]{Method: CommandDescribeNode} -// ScrollIntoViewIfNeededParams scrolls the specified rect of the given node -// into view if not already visible. Note: exactly one between nodeId, -// backendNodeId and objectId should be passed to identify the node. +// ScrollIntoViewIfNeededParams are the parameters of the command +// DOM.scrollIntoViewIfNeeded. type ScrollIntoViewIfNeededParams struct { NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Identifier of the node. BackendNodeID cdp.BackendNodeID `json:"backendNodeId,omitempty,omitzero"` // Identifier of the backend node. @@ -207,60 +91,15 @@ type ScrollIntoViewIfNeededParams struct { // and objectId should be passed to identify the node. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-scrollIntoViewIfNeeded -// -// parameters: -func ScrollIntoViewIfNeeded() *ScrollIntoViewIfNeededParams { - return &ScrollIntoViewIfNeededParams{} -} - -// WithNodeID identifier of the node. -func (p ScrollIntoViewIfNeededParams) WithNodeID(nodeID cdp.NodeID) *ScrollIntoViewIfNeededParams { - p.NodeID = nodeID - return &p -} - -// WithBackendNodeID identifier of the backend node. -func (p ScrollIntoViewIfNeededParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *ScrollIntoViewIfNeededParams { - p.BackendNodeID = backendNodeID - return &p -} - -// WithObjectID JavaScript object id of the node wrapper. -func (p ScrollIntoViewIfNeededParams) WithObjectID(objectID runtime.RemoteObjectID) *ScrollIntoViewIfNeededParams { - p.ObjectID = objectID - return &p -} - -// WithRect the rect to be scrolled into view, relative to the node's border -// box, in CSS pixels. When omitted, center of the node will be used, similar to -// Element.scrollIntoView. -func (p ScrollIntoViewIfNeededParams) WithRect(rect *Rect) *ScrollIntoViewIfNeededParams { - p.Rect = rect - return &p -} - -// Do executes DOM.scrollIntoViewIfNeeded against the provided context. -func (p *ScrollIntoViewIfNeededParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandScrollIntoViewIfNeeded, p, nil) -} - -// DisableParams disables DOM agent for the given page. -type DisableParams struct{} +var ScrollIntoViewIfNeeded = cdp.Command[ScrollIntoViewIfNeededParams, cdp.Empty]{Method: CommandScrollIntoViewIfNeeded} // Disable disables DOM agent for the given page. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes DOM.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} -// DiscardSearchResultsParams discards search results from the session with -// the given id. getSearchResults should no longer be called for that search. +// DiscardSearchResultsParams are the parameters of the command +// DOM.discardSearchResults. type DiscardSearchResultsParams struct { SearchID string `json:"searchId"` // Unique search session identifier. } @@ -269,22 +108,9 @@ type DiscardSearchResultsParams struct { // given id. getSearchResults should no longer be called for that search. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-discardSearchResults -// -// parameters: -// -// searchID - Unique search session identifier. -func DiscardSearchResults(searchID string) *DiscardSearchResultsParams { - return &DiscardSearchResultsParams{ - SearchID: searchID, - } -} - -// Do executes DOM.discardSearchResults against the provided context. -func (p *DiscardSearchResultsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDiscardSearchResults, p, nil) -} +var DiscardSearchResults = cdp.Command[DiscardSearchResultsParams, cdp.Empty]{Method: CommandDiscardSearchResults} -// EnableParams enables DOM agent for the given page. +// EnableParams are the parameters of the command DOM.enable. type EnableParams struct { IncludeWhitespace EnableIncludeWhitespace `json:"includeWhitespace,omitempty,omitzero"` // Whether to include whitespaces in the children array of returned Nodes. } @@ -292,25 +118,9 @@ type EnableParams struct { // Enable enables DOM agent for the given page. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-enable -// -// parameters: -func Enable() *EnableParams { - return &EnableParams{} -} +var Enable = cdp.Command[EnableParams, cdp.Empty]{Method: CommandEnable} -// WithIncludeWhitespace whether to include whitespaces in the children array -// of returned Nodes. -func (p EnableParams) WithIncludeWhitespace(includeWhitespace EnableIncludeWhitespace) *EnableParams { - p.IncludeWhitespace = includeWhitespace - return &p -} - -// Do executes DOM.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, p, nil) -} - -// FocusParams focuses the given element. +// FocusParams are the parameters of the command DOM.focus. type FocusParams struct { NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Identifier of the node. BackendNodeID cdp.BackendNodeID `json:"backendNodeId,omitempty,omitzero"` // Identifier of the backend node. @@ -320,587 +130,207 @@ type FocusParams struct { // Focus focuses the given element. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-focus -// -// parameters: -func Focus() *FocusParams { - return &FocusParams{} -} +var Focus = cdp.Command[FocusParams, cdp.Empty]{Method: CommandFocus} -// WithNodeID identifier of the node. -func (p FocusParams) WithNodeID(nodeID cdp.NodeID) *FocusParams { - p.NodeID = nodeID - return &p -} - -// WithBackendNodeID identifier of the backend node. -func (p FocusParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *FocusParams { - p.BackendNodeID = backendNodeID - return &p -} - -// WithObjectID JavaScript object id of the node wrapper. -func (p FocusParams) WithObjectID(objectID runtime.RemoteObjectID) *FocusParams { - p.ObjectID = objectID - return &p -} - -// Do executes DOM.focus against the provided context. -func (p *FocusParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandFocus, p, nil) -} - -// GetAttributesParams returns attributes for the specified node. +// GetAttributesParams are the parameters of the command DOM.getAttributes. type GetAttributesParams struct { NodeID cdp.NodeID `json:"nodeId"` // Id of the node to retrieve attributes for. } -// GetAttributes returns attributes for the specified node. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getAttributes -// -// parameters: -// -// nodeID - Id of the node to retrieve attributes for. -func GetAttributes(nodeID cdp.NodeID) *GetAttributesParams { - return &GetAttributesParams{ - NodeID: nodeID, - } -} - -// GetAttributesReturns return values. -type GetAttributesReturns struct { +// GetAttributesResult is the result of the command DOM.getAttributes. +type GetAttributesResult struct { Attributes []string `json:"attributes,omitempty,omitzero"` // An interleaved array of node attribute names and values. } -// Do executes DOM.getAttributes against the provided context. -// -// returns: +// GetAttributes returns attributes for the specified node. // -// attributes - An interleaved array of node attribute names and values. -func (p *GetAttributesParams) Do(ctx context.Context) (attributes []string, err error) { - // execute - var res GetAttributesReturns - err = cdp.Execute(ctx, CommandGetAttributes, p, &res) - if err != nil { - return nil, err - } - - return res.Attributes, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getAttributes +var GetAttributes = cdp.Command[GetAttributesParams, GetAttributesResult]{Method: CommandGetAttributes} -// GetBoxModelParams returns boxes for the given node. +// GetBoxModelParams are the parameters of the command DOM.getBoxModel. type GetBoxModelParams struct { NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Identifier of the node. BackendNodeID cdp.BackendNodeID `json:"backendNodeId,omitempty,omitzero"` // Identifier of the backend node. ObjectID runtime.RemoteObjectID `json:"objectId,omitempty,omitzero"` // JavaScript object id of the node wrapper. } -// GetBoxModel returns boxes for the given node. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getBoxModel -// -// parameters: -func GetBoxModel() *GetBoxModelParams { - return &GetBoxModelParams{} -} - -// WithNodeID identifier of the node. -func (p GetBoxModelParams) WithNodeID(nodeID cdp.NodeID) *GetBoxModelParams { - p.NodeID = nodeID - return &p -} - -// WithBackendNodeID identifier of the backend node. -func (p GetBoxModelParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *GetBoxModelParams { - p.BackendNodeID = backendNodeID - return &p -} - -// WithObjectID JavaScript object id of the node wrapper. -func (p GetBoxModelParams) WithObjectID(objectID runtime.RemoteObjectID) *GetBoxModelParams { - p.ObjectID = objectID - return &p -} - -// GetBoxModelReturns return values. -type GetBoxModelReturns struct { +// GetBoxModelResult is the result of the command DOM.getBoxModel. +type GetBoxModelResult struct { Model *BoxModel `json:"model,omitempty,omitzero"` // Box model for the node. } -// Do executes DOM.getBoxModel against the provided context. -// -// returns: +// GetBoxModel returns boxes for the given node. // -// model - Box model for the node. -func (p *GetBoxModelParams) Do(ctx context.Context) (model *BoxModel, err error) { - // execute - var res GetBoxModelReturns - err = cdp.Execute(ctx, CommandGetBoxModel, p, &res) - if err != nil { - return nil, err - } - - return res.Model, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getBoxModel +var GetBoxModel = cdp.Command[GetBoxModelParams, GetBoxModelResult]{Method: CommandGetBoxModel} -// GetContentQuadsParams returns quads that describe node position on the -// page. This method might return multiple quads for inline nodes. +// GetContentQuadsParams are the parameters of the command +// DOM.getContentQuads. type GetContentQuadsParams struct { NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Identifier of the node. BackendNodeID cdp.BackendNodeID `json:"backendNodeId,omitempty,omitzero"` // Identifier of the backend node. ObjectID runtime.RemoteObjectID `json:"objectId,omitempty,omitzero"` // JavaScript object id of the node wrapper. } -// GetContentQuads returns quads that describe node position on the page. -// This method might return multiple quads for inline nodes. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getContentQuads -// -// parameters: -func GetContentQuads() *GetContentQuadsParams { - return &GetContentQuadsParams{} -} - -// WithNodeID identifier of the node. -func (p GetContentQuadsParams) WithNodeID(nodeID cdp.NodeID) *GetContentQuadsParams { - p.NodeID = nodeID - return &p -} - -// WithBackendNodeID identifier of the backend node. -func (p GetContentQuadsParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *GetContentQuadsParams { - p.BackendNodeID = backendNodeID - return &p -} - -// WithObjectID JavaScript object id of the node wrapper. -func (p GetContentQuadsParams) WithObjectID(objectID runtime.RemoteObjectID) *GetContentQuadsParams { - p.ObjectID = objectID - return &p -} - -// GetContentQuadsReturns return values. -type GetContentQuadsReturns struct { +// GetContentQuadsResult is the result of the command DOM.getContentQuads. +type GetContentQuadsResult struct { Quads []Quad `json:"quads,omitempty,omitzero"` // Quads that describe node layout relative to viewport. } -// Do executes DOM.getContentQuads against the provided context. -// -// returns: +// GetContentQuads returns quads that describe node position on the page. +// This method might return multiple quads for inline nodes. // -// quads - Quads that describe node layout relative to viewport. -func (p *GetContentQuadsParams) Do(ctx context.Context) (quads []Quad, err error) { - // execute - var res GetContentQuadsReturns - err = cdp.Execute(ctx, CommandGetContentQuads, p, &res) - if err != nil { - return nil, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getContentQuads +var GetContentQuads = cdp.Command[GetContentQuadsParams, GetContentQuadsResult]{Method: CommandGetContentQuads} - return res.Quads, nil +// GetDocumentParams are the parameters of the command DOM.getDocument. +type GetDocumentParams struct { + Depth *int64 `json:"depth,omitempty,omitzero"` // The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the entire subtree or provide an integer larger than 0. + Pierce *bool `json:"pierce,omitempty,omitzero"` // Whether or not iframes and shadow roots should be traversed when returning the subtree (default is false). } -// GetDocumentParams returns the root DOM node (and optionally the subtree) -// to the caller. Implicitly enables the DOM domain events for the current -// target. -type GetDocumentParams struct { - Depth int64 `json:"depth,omitempty,omitzero"` // The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the entire subtree or provide an integer larger than 0. - Pierce bool `json:"pierce"` // Whether or not iframes and shadow roots should be traversed when returning the subtree (default is false). +// GetDocumentResult is the result of the command DOM.getDocument. +type GetDocumentResult struct { + Root *cdp.Node `json:"root,omitempty,omitzero"` // Resulting node. } // GetDocument returns the root DOM node (and optionally the subtree) to the // caller. Implicitly enables the DOM domain events for the current target. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getDocument -// -// parameters: -func GetDocument() *GetDocumentParams { - return &GetDocumentParams{ - Pierce: false, - } -} - -// WithDepth the maximum depth at which children should be retrieved, -// defaults to 1. Use -1 for the entire subtree or provide an integer larger -// than 0. -func (p GetDocumentParams) WithDepth(depth int64) *GetDocumentParams { - p.Depth = depth - return &p -} +var GetDocument = cdp.Command[GetDocumentParams, GetDocumentResult]{Method: CommandGetDocument} -// WithPierce whether or not iframes and shadow roots should be traversed -// when returning the subtree (default is false). -func (p GetDocumentParams) WithPierce(pierce bool) *GetDocumentParams { - p.Pierce = pierce - return &p -} - -// GetDocumentReturns return values. -type GetDocumentReturns struct { - Root *cdp.Node `json:"root,omitempty,omitzero"` // Resulting node. -} - -// Do executes DOM.getDocument against the provided context. -// -// returns: -// -// root - Resulting node. -func (p *GetDocumentParams) Do(ctx context.Context) (root *cdp.Node, err error) { - // execute - var res GetDocumentReturns - err = cdp.Execute(ctx, CommandGetDocument, p, &res) - if err != nil { - return nil, err - } - - return res.Root, nil +// GetNodesForSubtreeByStyleParams are the parameters of the command +// DOM.getNodesForSubtreeByStyle. +type GetNodesForSubtreeByStyleParams struct { + NodeID cdp.NodeID `json:"nodeId"` // Node ID pointing to the root of a subtree. + ComputedStyles []*CSSComputedStyleProperty `json:"computedStyles"` // The style to filter nodes by (includes nodes if any of properties matches). + Pierce *bool `json:"pierce,omitempty,omitzero"` // Whether or not iframes and shadow roots in the same target should be traversed when returning the results (default is false). } -// GetNodesForSubtreeByStyleParams finds nodes with a given computed style in -// a subtree. -type GetNodesForSubtreeByStyleParams struct { - NodeID cdp.NodeID `json:"nodeId"` // Node ID pointing to the root of a subtree. - ComputedStyles []*CSSComputedStyleProperty `json:"computedStyles"` // The style to filter nodes by (includes nodes if any of properties matches). - Pierce bool `json:"pierce"` // Whether or not iframes and shadow roots in the same target should be traversed when returning the results (default is false). +// GetNodesForSubtreeByStyleResult is the result of the command +// DOM.getNodesForSubtreeByStyle. +type GetNodesForSubtreeByStyleResult struct { + NodeIDs []cdp.NodeID `json:"nodeIds,omitempty,omitzero"` // Resulting nodes. } // GetNodesForSubtreeByStyle finds nodes with a given computed style in a // subtree. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getNodesForSubtreeByStyle -// -// parameters: -// -// nodeID - Node ID pointing to the root of a subtree. -// computedStyles - The style to filter nodes by (includes nodes if any of properties matches). -func GetNodesForSubtreeByStyle(nodeID cdp.NodeID, computedStyles []*CSSComputedStyleProperty) *GetNodesForSubtreeByStyleParams { - return &GetNodesForSubtreeByStyleParams{ - NodeID: nodeID, - ComputedStyles: computedStyles, - Pierce: false, - } -} - -// WithPierce whether or not iframes and shadow roots in the same target -// should be traversed when returning the results (default is false). -func (p GetNodesForSubtreeByStyleParams) WithPierce(pierce bool) *GetNodesForSubtreeByStyleParams { - p.Pierce = pierce - return &p -} - -// GetNodesForSubtreeByStyleReturns return values. -type GetNodesForSubtreeByStyleReturns struct { - NodeIDs []cdp.NodeID `json:"nodeIds,omitempty,omitzero"` // Resulting nodes. -} - -// Do executes DOM.getNodesForSubtreeByStyle against the provided context. -// -// returns: -// -// nodeIDs - Resulting nodes. -func (p *GetNodesForSubtreeByStyleParams) Do(ctx context.Context) (nodeIDs []cdp.NodeID, err error) { - // execute - var res GetNodesForSubtreeByStyleReturns - err = cdp.Execute(ctx, CommandGetNodesForSubtreeByStyle, p, &res) - if err != nil { - return nil, err - } +var GetNodesForSubtreeByStyle = cdp.Command[GetNodesForSubtreeByStyleParams, GetNodesForSubtreeByStyleResult]{Method: CommandGetNodesForSubtreeByStyle} - return res.NodeIDs, nil -} - -// GetNodeForLocationParams returns node id at given location. Depending on -// whether DOM domain is enabled, nodeId is either returned or not. +// GetNodeForLocationParams are the parameters of the command +// DOM.getNodeForLocation. type GetNodeForLocationParams struct { - X int64 `json:"x"` // X coordinate. - Y int64 `json:"y"` // Y coordinate. - IncludeUserAgentShadowDOM bool `json:"includeUserAgentShadowDOM"` // False to skip to the nearest non-UA shadow root ancestor (default: false). - IgnorePointerEventsNone bool `json:"ignorePointerEventsNone"` // Whether to ignore pointer-events: none on elements and hit test them. -} - -// GetNodeForLocation returns node id at given location. Depending on whether -// DOM domain is enabled, nodeId is either returned or not. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getNodeForLocation -// -// parameters: -// -// x - X coordinate. -// y - Y coordinate. -func GetNodeForLocation(x int64, y int64) *GetNodeForLocationParams { - return &GetNodeForLocationParams{ - X: x, - Y: y, - IncludeUserAgentShadowDOM: false, - IgnorePointerEventsNone: false, - } -} - -// WithIncludeUserAgentShadowDOM false to skip to the nearest non-UA shadow -// root ancestor (default: false). -func (p GetNodeForLocationParams) WithIncludeUserAgentShadowDOM(includeUserAgentShadowDOM bool) *GetNodeForLocationParams { - p.IncludeUserAgentShadowDOM = includeUserAgentShadowDOM - return &p -} - -// WithIgnorePointerEventsNone whether to ignore pointer-events: none on -// elements and hit test them. -func (p GetNodeForLocationParams) WithIgnorePointerEventsNone(ignorePointerEventsNone bool) *GetNodeForLocationParams { - p.IgnorePointerEventsNone = ignorePointerEventsNone - return &p + X int64 `json:"x"` // X coordinate. + Y int64 `json:"y"` // Y coordinate. + IncludeUserAgentShadowDOM *bool `json:"includeUserAgentShadowDOM,omitempty,omitzero"` // False to skip to the nearest non-UA shadow root ancestor (default: false). + IgnorePointerEventsNone *bool `json:"ignorePointerEventsNone,omitempty,omitzero"` // Whether to ignore pointer-events: none on elements and hit test them. } -// GetNodeForLocationReturns return values. -type GetNodeForLocationReturns struct { +// GetNodeForLocationResult is the result of the command +// DOM.getNodeForLocation. +type GetNodeForLocationResult struct { BackendNodeID cdp.BackendNodeID `json:"backendNodeId,omitempty,omitzero"` // Resulting node. FrameID cdp.FrameID `json:"frameId,omitempty,omitzero"` // Frame this node belongs to. NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Id of the node at given coordinates, only when enabled and requested document. } -// Do executes DOM.getNodeForLocation against the provided context. -// -// returns: +// GetNodeForLocation returns node id at given location. Depending on whether +// DOM domain is enabled, nodeId is either returned or not. // -// backendNodeID - Resulting node. -// frameID - Frame this node belongs to. -// nodeID - Id of the node at given coordinates, only when enabled and requested document. -func (p *GetNodeForLocationParams) Do(ctx context.Context) (backendNodeID cdp.BackendNodeID, frameID cdp.FrameID, nodeID cdp.NodeID, err error) { - // execute - var res GetNodeForLocationReturns - err = cdp.Execute(ctx, CommandGetNodeForLocation, p, &res) - if err != nil { - return 0, "", 0, err - } - - return res.BackendNodeID, res.FrameID, res.NodeID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getNodeForLocation +var GetNodeForLocation = cdp.Command[GetNodeForLocationParams, GetNodeForLocationResult]{Method: CommandGetNodeForLocation} -// GetOuterHTMLParams returns node's HTML markup. +// GetOuterHTMLParams are the parameters of the command DOM.getOuterHTML. type GetOuterHTMLParams struct { - NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Identifier of the node. - BackendNodeID cdp.BackendNodeID `json:"backendNodeId,omitempty,omitzero"` // Identifier of the backend node. - ObjectID runtime.RemoteObjectID `json:"objectId,omitempty,omitzero"` // JavaScript object id of the node wrapper. - IncludeShadowDOM bool `json:"includeShadowDOM"` // Include all shadow roots. Equals to false if not specified. -} - -// GetOuterHTML returns node's HTML markup. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getOuterHTML -// -// parameters: -func GetOuterHTML() *GetOuterHTMLParams { - return &GetOuterHTMLParams{ - IncludeShadowDOM: false, - } -} - -// WithNodeID identifier of the node. -func (p GetOuterHTMLParams) WithNodeID(nodeID cdp.NodeID) *GetOuterHTMLParams { - p.NodeID = nodeID - return &p -} - -// WithBackendNodeID identifier of the backend node. -func (p GetOuterHTMLParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *GetOuterHTMLParams { - p.BackendNodeID = backendNodeID - return &p -} - -// WithObjectID JavaScript object id of the node wrapper. -func (p GetOuterHTMLParams) WithObjectID(objectID runtime.RemoteObjectID) *GetOuterHTMLParams { - p.ObjectID = objectID - return &p -} - -// WithIncludeShadowDOM include all shadow roots. Equals to false if not -// specified. -func (p GetOuterHTMLParams) WithIncludeShadowDOM(includeShadowDOM bool) *GetOuterHTMLParams { - p.IncludeShadowDOM = includeShadowDOM - return &p + NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Identifier of the node. + BackendNodeID cdp.BackendNodeID `json:"backendNodeId,omitempty,omitzero"` // Identifier of the backend node. + ObjectID runtime.RemoteObjectID `json:"objectId,omitempty,omitzero"` // JavaScript object id of the node wrapper. + IncludeShadowDOM *bool `json:"includeShadowDOM,omitempty,omitzero"` // Include all shadow roots. Equals to false if not specified. } -// GetOuterHTMLReturns return values. -type GetOuterHTMLReturns struct { +// GetOuterHTMLResult is the result of the command DOM.getOuterHTML. +type GetOuterHTMLResult struct { OuterHTML string `json:"outerHTML,omitempty,omitzero"` // Outer HTML markup. } -// Do executes DOM.getOuterHTML against the provided context. -// -// returns: +// GetOuterHTML returns node's HTML markup. // -// outerHTML - Outer HTML markup. -func (p *GetOuterHTMLParams) Do(ctx context.Context) (outerHTML string, err error) { - // execute - var res GetOuterHTMLReturns - err = cdp.Execute(ctx, CommandGetOuterHTML, p, &res) - if err != nil { - return "", err - } - - return res.OuterHTML, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getOuterHTML +var GetOuterHTML = cdp.Command[GetOuterHTMLParams, GetOuterHTMLResult]{Method: CommandGetOuterHTML} -// GetRelayoutBoundaryParams returns the id of the nearest ancestor that is a -// relayout boundary. +// GetRelayoutBoundaryParams are the parameters of the command +// DOM.getRelayoutBoundary. type GetRelayoutBoundaryParams struct { NodeID cdp.NodeID `json:"nodeId"` // Id of the node. } -// GetRelayoutBoundary returns the id of the nearest ancestor that is a -// relayout boundary. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getRelayoutBoundary -// -// parameters: -// -// nodeID - Id of the node. -func GetRelayoutBoundary(nodeID cdp.NodeID) *GetRelayoutBoundaryParams { - return &GetRelayoutBoundaryParams{ - NodeID: nodeID, - } -} - -// GetRelayoutBoundaryReturns return values. -type GetRelayoutBoundaryReturns struct { +// GetRelayoutBoundaryResult is the result of the command +// DOM.getRelayoutBoundary. +type GetRelayoutBoundaryResult struct { NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Relayout boundary node id for the given node. } -// Do executes DOM.getRelayoutBoundary against the provided context. -// -// returns: +// GetRelayoutBoundary returns the id of the nearest ancestor that is a +// relayout boundary. // -// nodeID - Relayout boundary node id for the given node. -func (p *GetRelayoutBoundaryParams) Do(ctx context.Context) (nodeID cdp.NodeID, err error) { - // execute - var res GetRelayoutBoundaryReturns - err = cdp.Execute(ctx, CommandGetRelayoutBoundary, p, &res) - if err != nil { - return 0, err - } - - return res.NodeID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getRelayoutBoundary +var GetRelayoutBoundary = cdp.Command[GetRelayoutBoundaryParams, GetRelayoutBoundaryResult]{Method: CommandGetRelayoutBoundary} -// GetSearchResultsParams returns search results from given fromIndex to -// given toIndex from the search with the given identifier. +// GetSearchResultsParams are the parameters of the command +// DOM.getSearchResults. type GetSearchResultsParams struct { SearchID string `json:"searchId"` // Unique search session identifier. FromIndex int64 `json:"fromIndex"` // Start index of the search result to be returned. ToIndex int64 `json:"toIndex"` // End index of the search result to be returned. } -// GetSearchResults returns search results from given fromIndex to given -// toIndex from the search with the given identifier. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getSearchResults -// -// parameters: -// -// searchID - Unique search session identifier. -// fromIndex - Start index of the search result to be returned. -// toIndex - End index of the search result to be returned. -func GetSearchResults(searchID string, fromIndex int64, toIndex int64) *GetSearchResultsParams { - return &GetSearchResultsParams{ - SearchID: searchID, - FromIndex: fromIndex, - ToIndex: toIndex, - } -} - -// GetSearchResultsReturns return values. -type GetSearchResultsReturns struct { +// GetSearchResultsResult is the result of the command DOM.getSearchResults. +type GetSearchResultsResult struct { NodeIDs []cdp.NodeID `json:"nodeIds,omitempty,omitzero"` // Ids of the search result nodes. } -// Do executes DOM.getSearchResults against the provided context. -// -// returns: +// GetSearchResults returns search results from given fromIndex to given +// toIndex from the search with the given identifier. // -// nodeIDs - Ids of the search result nodes. -func (p *GetSearchResultsParams) Do(ctx context.Context) (nodeIDs []cdp.NodeID, err error) { - // execute - var res GetSearchResultsReturns - err = cdp.Execute(ctx, CommandGetSearchResults, p, &res) - if err != nil { - return nil, err - } - - return res.NodeIDs, nil -} - -// MarkUndoableStateParams marks last undoable state. -type MarkUndoableStateParams struct{} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getSearchResults +var GetSearchResults = cdp.Command[GetSearchResultsParams, GetSearchResultsResult]{Method: CommandGetSearchResults} // MarkUndoableState marks last undoable state. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-markUndoableState -func MarkUndoableState() *MarkUndoableStateParams { - return &MarkUndoableStateParams{} -} - -// Do executes DOM.markUndoableState against the provided context. -func (p *MarkUndoableStateParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandMarkUndoableState, nil, nil) -} +var MarkUndoableState = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandMarkUndoableState} -// MoveToParams moves node into the new container, places it before the given -// anchor. +// MoveToParams are the parameters of the command DOM.moveTo. type MoveToParams struct { NodeID cdp.NodeID `json:"nodeId"` // Id of the node to move. TargetNodeID cdp.NodeID `json:"targetNodeId"` // Id of the element to drop the moved node into. InsertBeforeNodeID cdp.NodeID `json:"insertBeforeNodeId,omitempty,omitzero"` // Drop node before this one (if absent, the moved node becomes the last child of targetNodeId). } -// MoveTo moves node into the new container, places it before the given -// anchor. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-moveTo -// -// parameters: -// -// nodeID - Id of the node to move. -// targetNodeID - Id of the element to drop the moved node into. -func MoveTo(nodeID cdp.NodeID, targetNodeID cdp.NodeID) *MoveToParams { - return &MoveToParams{ - NodeID: nodeID, - TargetNodeID: targetNodeID, - } -} - -// WithInsertBeforeNodeID drop node before this one (if absent, the moved -// node becomes the last child of targetNodeId). -func (p MoveToParams) WithInsertBeforeNodeID(insertBeforeNodeID cdp.NodeID) *MoveToParams { - p.InsertBeforeNodeID = insertBeforeNodeID - return &p -} - -// MoveToReturns return values. -type MoveToReturns struct { +// MoveToResult is the result of the command DOM.moveTo. +type MoveToResult struct { NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // New id of the moved node. } -// Do executes DOM.moveTo against the provided context. -// -// returns: +// MoveTo moves node into the new container, places it before the given +// anchor. // -// nodeID - New id of the moved node. -func (p *MoveToParams) Do(ctx context.Context) (nodeID cdp.NodeID, err error) { - // execute - var res MoveToReturns - err = cdp.Execute(ctx, CommandMoveTo, p, &res) - if err != nil { - return 0, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-moveTo +var MoveTo = cdp.Command[MoveToParams, MoveToResult]{Method: CommandMoveTo} - return res.NodeID, nil +// PerformSearchParams are the parameters of the command DOM.performSearch. +type PerformSearchParams struct { + Query string `json:"query"` // Plain text or query selector or XPath search query. + IncludeUserAgentShadowDOM *bool `json:"includeUserAgentShadowDOM,omitempty,omitzero"` // True to search in user agent shadow DOM. } -// PerformSearchParams searches for a given string in the DOM tree. Use -// getSearchResults to access search results or cancelSearch to end this search -// session. -type PerformSearchParams struct { - Query string `json:"query"` // Plain text or query selector or XPath search query. - IncludeUserAgentShadowDOM bool `json:"includeUserAgentShadowDOM"` // True to search in user agent shadow DOM. +// PerformSearchResult is the result of the command DOM.performSearch. +type PerformSearchResult struct { + SearchID string `json:"searchId,omitempty,omitzero"` // Unique search session identifier. + ResultCount int64 `json:"resultCount,omitempty,omitzero"` // Number of search results. } // PerformSearch searches for a given string in the DOM tree. Use @@ -908,308 +338,116 @@ type PerformSearchParams struct { // session. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-performSearch -// -// parameters: -// -// query - Plain text or query selector or XPath search query. -func PerformSearch(query string) *PerformSearchParams { - return &PerformSearchParams{ - Query: query, - IncludeUserAgentShadowDOM: false, - } -} +var PerformSearch = cdp.Command[PerformSearchParams, PerformSearchResult]{Method: CommandPerformSearch} -// WithIncludeUserAgentShadowDOM true to search in user agent shadow DOM. -func (p PerformSearchParams) WithIncludeUserAgentShadowDOM(includeUserAgentShadowDOM bool) *PerformSearchParams { - p.IncludeUserAgentShadowDOM = includeUserAgentShadowDOM - return &p -} - -// PerformSearchReturns return values. -type PerformSearchReturns struct { - SearchID string `json:"searchId,omitempty,omitzero"` // Unique search session identifier. - ResultCount int64 `json:"resultCount,omitempty,omitzero"` // Number of search results. -} - -// Do executes DOM.performSearch against the provided context. -// -// returns: -// -// searchID - Unique search session identifier. -// resultCount - Number of search results. -func (p *PerformSearchParams) Do(ctx context.Context) (searchID string, resultCount int64, err error) { - // execute - var res PerformSearchReturns - err = cdp.Execute(ctx, CommandPerformSearch, p, &res) - if err != nil { - return "", 0, err - } - - return res.SearchID, res.ResultCount, nil -} - -// PushNodeByPathToFrontendParams requests that the node is sent to the -// caller given its path. // FIXME, use XPath. +// PushNodeByPathToFrontendParams are the parameters of the command +// DOM.pushNodeByPathToFrontend. type PushNodeByPathToFrontendParams struct { Path string `json:"path"` // Path to node in the proprietary format. } -// PushNodeByPathToFrontend requests that the node is sent to the caller -// given its path. // FIXME, use XPath. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-pushNodeByPathToFrontend -// -// parameters: -// -// path - Path to node in the proprietary format. -func PushNodeByPathToFrontend(path string) *PushNodeByPathToFrontendParams { - return &PushNodeByPathToFrontendParams{ - Path: path, - } -} - -// PushNodeByPathToFrontendReturns return values. -type PushNodeByPathToFrontendReturns struct { +// PushNodeByPathToFrontendResult is the result of the command +// DOM.pushNodeByPathToFrontend. +type PushNodeByPathToFrontendResult struct { NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Id of the node for given path. } -// Do executes DOM.pushNodeByPathToFrontend against the provided context. -// -// returns: +// PushNodeByPathToFrontend requests that the node is sent to the caller +// given its path. // FIXME, use XPath. // -// nodeID - Id of the node for given path. -func (p *PushNodeByPathToFrontendParams) Do(ctx context.Context) (nodeID cdp.NodeID, err error) { - // execute - var res PushNodeByPathToFrontendReturns - err = cdp.Execute(ctx, CommandPushNodeByPathToFrontend, p, &res) - if err != nil { - return 0, err - } - - return res.NodeID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-pushNodeByPathToFrontend +var PushNodeByPathToFrontend = cdp.Command[PushNodeByPathToFrontendParams, PushNodeByPathToFrontendResult]{Method: CommandPushNodeByPathToFrontend} -// PushNodesByBackendIDsToFrontendParams requests that a batch of nodes is -// sent to the caller given their backend node ids. +// PushNodesByBackendIDsToFrontendParams are the parameters of the command +// DOM.pushNodesByBackendIdsToFrontend. type PushNodesByBackendIDsToFrontendParams struct { BackendNodeIDs []cdp.BackendNodeID `json:"backendNodeIds"` // The array of backend node ids. } -// PushNodesByBackendIDsToFrontend requests that a batch of nodes is sent to -// the caller given their backend node ids. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-pushNodesByBackendIdsToFrontend -// -// parameters: -// -// backendNodeIDs - The array of backend node ids. -func PushNodesByBackendIDsToFrontend(backendNodeIDs []cdp.BackendNodeID) *PushNodesByBackendIDsToFrontendParams { - return &PushNodesByBackendIDsToFrontendParams{ - BackendNodeIDs: backendNodeIDs, - } -} - -// PushNodesByBackendIDsToFrontendReturns return values. -type PushNodesByBackendIDsToFrontendReturns struct { +// PushNodesByBackendIDsToFrontendResult is the result of the command +// DOM.pushNodesByBackendIdsToFrontend. +type PushNodesByBackendIDsToFrontendResult struct { NodeIDs []cdp.NodeID `json:"nodeIds,omitempty,omitzero"` // The array of ids of pushed nodes that correspond to the backend ids specified in backendNodeIds. } -// Do executes DOM.pushNodesByBackendIdsToFrontend against the provided context. -// -// returns: +// PushNodesByBackendIDsToFrontend requests that a batch of nodes is sent to +// the caller given their backend node ids. // -// nodeIDs - The array of ids of pushed nodes that correspond to the backend ids specified in backendNodeIds. -func (p *PushNodesByBackendIDsToFrontendParams) Do(ctx context.Context) (nodeIDs []cdp.NodeID, err error) { - // execute - var res PushNodesByBackendIDsToFrontendReturns - err = cdp.Execute(ctx, CommandPushNodesByBackendIDsToFrontend, p, &res) - if err != nil { - return nil, err - } - - return res.NodeIDs, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-pushNodesByBackendIdsToFrontend +var PushNodesByBackendIDsToFrontend = cdp.Command[PushNodesByBackendIDsToFrontendParams, PushNodesByBackendIDsToFrontendResult]{Method: CommandPushNodesByBackendIDsToFrontend} -// QuerySelectorParams executes querySelector on a given node. +// QuerySelectorParams are the parameters of the command DOM.querySelector. type QuerySelectorParams struct { NodeID cdp.NodeID `json:"nodeId"` // Id of the node to query upon. Selector string `json:"selector"` // Selector string. } -// QuerySelector executes querySelector on a given node. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-querySelector -// -// parameters: -// -// nodeID - Id of the node to query upon. -// selector - Selector string. -func QuerySelector(nodeID cdp.NodeID, selector string) *QuerySelectorParams { - return &QuerySelectorParams{ - NodeID: nodeID, - Selector: selector, - } -} - -// QuerySelectorReturns return values. -type QuerySelectorReturns struct { +// QuerySelectorResult is the result of the command DOM.querySelector. +type QuerySelectorResult struct { NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Query selector result. } -// Do executes DOM.querySelector against the provided context. -// -// returns: +// QuerySelector executes querySelector on a given node. // -// nodeID - Query selector result. -func (p *QuerySelectorParams) Do(ctx context.Context) (nodeID cdp.NodeID, err error) { - // execute - var res QuerySelectorReturns - err = cdp.Execute(ctx, CommandQuerySelector, p, &res) - if err != nil { - return 0, err - } - - return res.NodeID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-querySelector +var QuerySelector = cdp.Command[QuerySelectorParams, QuerySelectorResult]{Method: CommandQuerySelector} -// QuerySelectorAllParams executes querySelectorAll on a given node. +// QuerySelectorAllParams are the parameters of the command +// DOM.querySelectorAll. type QuerySelectorAllParams struct { NodeID cdp.NodeID `json:"nodeId"` // Id of the node to query upon. Selector string `json:"selector"` // Selector string. } -// QuerySelectorAll executes querySelectorAll on a given node. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-querySelectorAll -// -// parameters: -// -// nodeID - Id of the node to query upon. -// selector - Selector string. -func QuerySelectorAll(nodeID cdp.NodeID, selector string) *QuerySelectorAllParams { - return &QuerySelectorAllParams{ - NodeID: nodeID, - Selector: selector, - } -} - -// QuerySelectorAllReturns return values. -type QuerySelectorAllReturns struct { +// QuerySelectorAllResult is the result of the command DOM.querySelectorAll. +type QuerySelectorAllResult struct { NodeIDs []cdp.NodeID `json:"nodeIds,omitempty,omitzero"` // Query selector result. } -// Do executes DOM.querySelectorAll against the provided context. -// -// returns: +// QuerySelectorAll executes querySelectorAll on a given node. // -// nodeIDs - Query selector result. -func (p *QuerySelectorAllParams) Do(ctx context.Context) (nodeIDs []cdp.NodeID, err error) { - // execute - var res QuerySelectorAllReturns - err = cdp.Execute(ctx, CommandQuerySelectorAll, p, &res) - if err != nil { - return nil, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-querySelectorAll +var QuerySelectorAll = cdp.Command[QuerySelectorAllParams, QuerySelectorAllResult]{Method: CommandQuerySelectorAll} - return res.NodeIDs, nil +// GetTopLayerElementsResult is the result of the command +// DOM.getTopLayerElements. +type GetTopLayerElementsResult struct { + NodeIDs []cdp.NodeID `json:"nodeIds,omitempty,omitzero"` // NodeIds of top layer elements } -// GetTopLayerElementsParams returns NodeIds of current top layer elements. -// Top layer is rendered closest to the user within a viewport, therefore its -// elements always appear on top of all other content. -type GetTopLayerElementsParams struct{} - // GetTopLayerElements returns NodeIds of current top layer elements. Top // layer is rendered closest to the user within a viewport, therefore its // elements always appear on top of all other content. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getTopLayerElements -func GetTopLayerElements() *GetTopLayerElementsParams { - return &GetTopLayerElementsParams{} -} - -// GetTopLayerElementsReturns return values. -type GetTopLayerElementsReturns struct { - NodeIDs []cdp.NodeID `json:"nodeIds,omitempty,omitzero"` // NodeIds of top layer elements -} - -// Do executes DOM.getTopLayerElements against the provided context. -// -// returns: -// -// nodeIDs - NodeIds of top layer elements -func (p *GetTopLayerElementsParams) Do(ctx context.Context) (nodeIDs []cdp.NodeID, err error) { - // execute - var res GetTopLayerElementsReturns - err = cdp.Execute(ctx, CommandGetTopLayerElements, nil, &res) - if err != nil { - return nil, err - } - - return res.NodeIDs, nil -} +var GetTopLayerElements = cdp.Command[cdp.Empty, GetTopLayerElementsResult]{Method: CommandGetTopLayerElements} -// GetElementByRelationParams returns the NodeId of the matched element -// according to certain relations. +// GetElementByRelationParams are the parameters of the command +// DOM.getElementByRelation. type GetElementByRelationParams struct { NodeID cdp.NodeID `json:"nodeId"` // Id of the node from which to query the relation. Relation GetElementByRelationRelation `json:"relation"` // Type of relation to get. } -// GetElementByRelation returns the NodeId of the matched element according -// to certain relations. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getElementByRelation -// -// parameters: -// -// nodeID - Id of the node from which to query the relation. -// relation - Type of relation to get. -func GetElementByRelation(nodeID cdp.NodeID, relation GetElementByRelationRelation) *GetElementByRelationParams { - return &GetElementByRelationParams{ - NodeID: nodeID, - Relation: relation, - } -} - -// GetElementByRelationReturns return values. -type GetElementByRelationReturns struct { +// GetElementByRelationResult is the result of the command +// DOM.getElementByRelation. +type GetElementByRelationResult struct { NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // NodeId of the element matching the queried relation. } -// Do executes DOM.getElementByRelation against the provided context. -// -// returns: +// GetElementByRelation returns the NodeId of the matched element according +// to certain relations. // -// nodeID - NodeId of the element matching the queried relation. -func (p *GetElementByRelationParams) Do(ctx context.Context) (nodeID cdp.NodeID, err error) { - // execute - var res GetElementByRelationReturns - err = cdp.Execute(ctx, CommandGetElementByRelation, p, &res) - if err != nil { - return 0, err - } - - return res.NodeID, nil -} - -// RedoParams re-does the last undone action. -type RedoParams struct{} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getElementByRelation +var GetElementByRelation = cdp.Command[GetElementByRelationParams, GetElementByRelationResult]{Method: CommandGetElementByRelation} // Redo re-does the last undone action. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-redo -func Redo() *RedoParams { - return &RedoParams{} -} +var Redo = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandRedo} -// Do executes DOM.redo against the provided context. -func (p *RedoParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRedo, nil, nil) -} - -// RemoveAttributeParams removes attribute with given name from an element -// with given id. +// RemoveAttributeParams are the parameters of the command +// DOM.removeAttribute. type RemoveAttributeParams struct { NodeID cdp.NodeID `json:"nodeId"` // Id of the element to remove attribute from. Name string `json:"name"` // Name of the attribute to remove. @@ -1218,25 +456,10 @@ type RemoveAttributeParams struct { // RemoveAttribute removes attribute with given name from an element with // given id. // -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-removeAttribute -// -// parameters: -// -// nodeID - Id of the element to remove attribute from. -// name - Name of the attribute to remove. -func RemoveAttribute(nodeID cdp.NodeID, name string) *RemoveAttributeParams { - return &RemoveAttributeParams{ - NodeID: nodeID, - Name: name, - } -} - -// Do executes DOM.removeAttribute against the provided context. -func (p *RemoveAttributeParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRemoveAttribute, p, nil) -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-removeAttribute +var RemoveAttribute = cdp.Command[RemoveAttributeParams, cdp.Empty]{Method: CommandRemoveAttribute} -// RemoveNodeParams removes node with given id. +// RemoveNodeParams are the parameters of the command DOM.removeNode. type RemoveNodeParams struct { NodeID cdp.NodeID `json:"nodeId"` // Id of the node to remove. } @@ -1244,29 +467,14 @@ type RemoveNodeParams struct { // RemoveNode removes node with given id. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-removeNode -// -// parameters: -// -// nodeID - Id of the node to remove. -func RemoveNode(nodeID cdp.NodeID) *RemoveNodeParams { - return &RemoveNodeParams{ - NodeID: nodeID, - } -} - -// Do executes DOM.removeNode against the provided context. -func (p *RemoveNodeParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRemoveNode, p, nil) -} +var RemoveNode = cdp.Command[RemoveNodeParams, cdp.Empty]{Method: CommandRemoveNode} -// RequestChildNodesParams requests that children of the node with given id -// are returned to the caller in form of setChildNodes events where not only -// immediate children are retrieved, but all children down to the specified -// depth. +// RequestChildNodesParams are the parameters of the command +// DOM.requestChildNodes. type RequestChildNodesParams struct { - NodeID cdp.NodeID `json:"nodeId"` // Id of the node to get children for. - Depth int64 `json:"depth,omitempty,omitzero"` // The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the entire subtree or provide an integer larger than 0. - Pierce bool `json:"pierce"` // Whether or not iframes and shadow roots should be traversed when returning the sub-tree (default is false). + NodeID cdp.NodeID `json:"nodeId"` // Id of the node to get children for. + Depth *int64 `json:"depth,omitempty,omitzero"` // The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the entire subtree or provide an integer larger than 0. + Pierce *bool `json:"pierce,omitempty,omitzero"` // Whether or not iframes and shadow roots should be traversed when returning the sub-tree (default is false). } // RequestChildNodes requests that children of the node with given id are @@ -1275,84 +483,27 @@ type RequestChildNodesParams struct { // depth. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-requestChildNodes -// -// parameters: -// -// nodeID - Id of the node to get children for. -func RequestChildNodes(nodeID cdp.NodeID) *RequestChildNodesParams { - return &RequestChildNodesParams{ - NodeID: nodeID, - Pierce: false, - } -} - -// WithDepth the maximum depth at which children should be retrieved, -// defaults to 1. Use -1 for the entire subtree or provide an integer larger -// than 0. -func (p RequestChildNodesParams) WithDepth(depth int64) *RequestChildNodesParams { - p.Depth = depth - return &p -} +var RequestChildNodes = cdp.Command[RequestChildNodesParams, cdp.Empty]{Method: CommandRequestChildNodes} -// WithPierce whether or not iframes and shadow roots should be traversed -// when returning the sub-tree (default is false). -func (p RequestChildNodesParams) WithPierce(pierce bool) *RequestChildNodesParams { - p.Pierce = pierce - return &p -} - -// Do executes DOM.requestChildNodes against the provided context. -func (p *RequestChildNodesParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRequestChildNodes, p, nil) -} - -// RequestNodeParams requests that the node is sent to the caller given the -// JavaScript node object reference. All nodes that form the path from the node -// to the root are also sent to the client as a series of setChildNodes -// notifications. +// RequestNodeParams are the parameters of the command DOM.requestNode. type RequestNodeParams struct { ObjectID runtime.RemoteObjectID `json:"objectId"` // JavaScript object id to convert into node. } +// RequestNodeResult is the result of the command DOM.requestNode. +type RequestNodeResult struct { + NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Node id for given object. +} + // RequestNode requests that the node is sent to the caller given the // JavaScript node object reference. All nodes that form the path from the node // to the root are also sent to the client as a series of setChildNodes // notifications. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-requestNode -// -// parameters: -// -// objectID - JavaScript object id to convert into node. -func RequestNode(objectID runtime.RemoteObjectID) *RequestNodeParams { - return &RequestNodeParams{ - ObjectID: objectID, - } -} - -// RequestNodeReturns return values. -type RequestNodeReturns struct { - NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Node id for given object. -} +var RequestNode = cdp.Command[RequestNodeParams, RequestNodeResult]{Method: CommandRequestNode} -// Do executes DOM.requestNode against the provided context. -// -// returns: -// -// nodeID - Node id for given object. -func (p *RequestNodeParams) Do(ctx context.Context) (nodeID cdp.NodeID, err error) { - // execute - var res RequestNodeReturns - err = cdp.Execute(ctx, CommandRequestNode, p, &res) - if err != nil { - return 0, err - } - - return res.NodeID, nil -} - -// ResolveNodeParams resolves the JavaScript node object for a given NodeId -// or BackendNodeId. +// ResolveNodeParams are the parameters of the command DOM.resolveNode. type ResolveNodeParams struct { NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Id of the node to resolve. BackendNodeID cdp.BackendNodeID `json:"backendNodeId,omitempty,omitzero"` // Backend identifier of the node to resolve. @@ -1360,63 +511,19 @@ type ResolveNodeParams struct { ExecutionContextID runtime.ExecutionContextID `json:"executionContextId,omitempty,omitzero"` // Execution context in which to resolve the node. } -// ResolveNode resolves the JavaScript node object for a given NodeId or -// BackendNodeId. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-resolveNode -// -// parameters: -func ResolveNode() *ResolveNodeParams { - return &ResolveNodeParams{} -} - -// WithNodeID ID of the node to resolve. -func (p ResolveNodeParams) WithNodeID(nodeID cdp.NodeID) *ResolveNodeParams { - p.NodeID = nodeID - return &p -} - -// WithBackendNodeID backend identifier of the node to resolve. -func (p ResolveNodeParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *ResolveNodeParams { - p.BackendNodeID = backendNodeID - return &p -} - -// WithObjectGroup symbolic group name that can be used to release multiple -// objects. -func (p ResolveNodeParams) WithObjectGroup(objectGroup string) *ResolveNodeParams { - p.ObjectGroup = objectGroup - return &p -} - -// WithExecutionContextID execution context in which to resolve the node. -func (p ResolveNodeParams) WithExecutionContextID(executionContextID runtime.ExecutionContextID) *ResolveNodeParams { - p.ExecutionContextID = executionContextID - return &p -} - -// ResolveNodeReturns return values. -type ResolveNodeReturns struct { +// ResolveNodeResult is the result of the command DOM.resolveNode. +type ResolveNodeResult struct { Object *runtime.RemoteObject `json:"object,omitempty,omitzero"` // JavaScript object wrapper for given node. } -// Do executes DOM.resolveNode against the provided context. -// -// returns: +// ResolveNode resolves the JavaScript node object for a given NodeId or +// BackendNodeId. // -// object - JavaScript object wrapper for given node. -func (p *ResolveNodeParams) Do(ctx context.Context) (object *runtime.RemoteObject, err error) { - // execute - var res ResolveNodeReturns - err = cdp.Execute(ctx, CommandResolveNode, p, &res) - if err != nil { - return nil, err - } - - return res.Object, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-resolveNode +var ResolveNode = cdp.Command[ResolveNodeParams, ResolveNodeResult]{Method: CommandResolveNode} -// SetAttributeValueParams sets attribute for an element with given id. +// SetAttributeValueParams are the parameters of the command +// DOM.setAttributeValue. type SetAttributeValueParams struct { NodeID cdp.NodeID `json:"nodeId"` // Id of the element to set attribute for. Name string `json:"name"` // Attribute name. @@ -1426,28 +533,10 @@ type SetAttributeValueParams struct { // SetAttributeValue sets attribute for an element with given id. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setAttributeValue -// -// parameters: -// -// nodeID - Id of the element to set attribute for. -// name - Attribute name. -// value - Attribute value. -func SetAttributeValue(nodeID cdp.NodeID, name string, value string) *SetAttributeValueParams { - return &SetAttributeValueParams{ - NodeID: nodeID, - Name: name, - Value: value, - } -} - -// Do executes DOM.setAttributeValue against the provided context. -func (p *SetAttributeValueParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetAttributeValue, p, nil) -} +var SetAttributeValue = cdp.Command[SetAttributeValueParams, cdp.Empty]{Method: CommandSetAttributeValue} -// SetAttributesAsTextParams sets attributes on element with given id. This -// method is useful when user edits some existing attribute value and types in -// several attribute name/value pairs. +// SetAttributesAsTextParams are the parameters of the command +// DOM.setAttributesAsText. type SetAttributesAsTextParams struct { NodeID cdp.NodeID `json:"nodeId"` // Id of the element to set attributes for. Text string `json:"text"` // Text with a number of attributes. Will parse this text using HTML parser. @@ -1459,31 +548,10 @@ type SetAttributesAsTextParams struct { // attribute name/value pairs. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setAttributesAsText -// -// parameters: -// -// nodeID - Id of the element to set attributes for. -// text - Text with a number of attributes. Will parse this text using HTML parser. -func SetAttributesAsText(nodeID cdp.NodeID, text string) *SetAttributesAsTextParams { - return &SetAttributesAsTextParams{ - NodeID: nodeID, - Text: text, - } -} - -// WithName attribute name to replace with new attributes derived from text -// in case text parsed successfully. -func (p SetAttributesAsTextParams) WithName(name string) *SetAttributesAsTextParams { - p.Name = name - return &p -} +var SetAttributesAsText = cdp.Command[SetAttributesAsTextParams, cdp.Empty]{Method: CommandSetAttributesAsText} -// Do executes DOM.setAttributesAsText against the provided context. -func (p *SetAttributesAsTextParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetAttributesAsText, p, nil) -} - -// SetFileInputFilesParams sets files for the given file input element. +// SetFileInputFilesParams are the parameters of the command +// DOM.setFileInputFiles. type SetFileInputFilesParams struct { Files []string `json:"files"` // Array of file paths to set. NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Identifier of the node. @@ -1494,41 +562,10 @@ type SetFileInputFilesParams struct { // SetFileInputFiles sets files for the given file input element. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setFileInputFiles -// -// parameters: -// -// files - Array of file paths to set. -func SetFileInputFiles(files []string) *SetFileInputFilesParams { - return &SetFileInputFilesParams{ - Files: files, - } -} - -// WithNodeID identifier of the node. -func (p SetFileInputFilesParams) WithNodeID(nodeID cdp.NodeID) *SetFileInputFilesParams { - p.NodeID = nodeID - return &p -} - -// WithBackendNodeID identifier of the backend node. -func (p SetFileInputFilesParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *SetFileInputFilesParams { - p.BackendNodeID = backendNodeID - return &p -} - -// WithObjectID JavaScript object id of the node wrapper. -func (p SetFileInputFilesParams) WithObjectID(objectID runtime.RemoteObjectID) *SetFileInputFilesParams { - p.ObjectID = objectID - return &p -} - -// Do executes DOM.setFileInputFiles against the provided context. -func (p *SetFileInputFilesParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetFileInputFiles, p, nil) -} +var SetFileInputFiles = cdp.Command[SetFileInputFilesParams, cdp.Empty]{Method: CommandSetFileInputFiles} -// SetNodeStackTracesEnabledParams sets if stack traces should be captured -// for Nodes. See Node.getNodeStackTraces. Default is disabled. +// SetNodeStackTracesEnabledParams are the parameters of the command +// DOM.setNodeStackTracesEnabled. type SetNodeStackTracesEnabledParams struct { Enable bool `json:"enable"` // Enable or disable. } @@ -1537,134 +574,54 @@ type SetNodeStackTracesEnabledParams struct { // Nodes. See Node.getNodeStackTraces. Default is disabled. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setNodeStackTracesEnabled -// -// parameters: -// -// enable - Enable or disable. -func SetNodeStackTracesEnabled(enable bool) *SetNodeStackTracesEnabledParams { - return &SetNodeStackTracesEnabledParams{ - Enable: enable, - } -} +var SetNodeStackTracesEnabled = cdp.Command[SetNodeStackTracesEnabledParams, cdp.Empty]{Method: CommandSetNodeStackTracesEnabled} -// Do executes DOM.setNodeStackTracesEnabled against the provided context. -func (p *SetNodeStackTracesEnabledParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetNodeStackTracesEnabled, p, nil) -} - -// GetNodeStackTracesParams gets stack traces associated with a Node. As of -// now, only provides stack trace for Node creation. +// GetNodeStackTracesParams are the parameters of the command +// DOM.getNodeStackTraces. type GetNodeStackTracesParams struct { NodeID cdp.NodeID `json:"nodeId"` // Id of the node to get stack traces for. } -// GetNodeStackTraces gets stack traces associated with a Node. As of now, -// only provides stack trace for Node creation. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getNodeStackTraces -// -// parameters: -// -// nodeID - Id of the node to get stack traces for. -func GetNodeStackTraces(nodeID cdp.NodeID) *GetNodeStackTracesParams { - return &GetNodeStackTracesParams{ - NodeID: nodeID, - } -} - -// GetNodeStackTracesReturns return values. -type GetNodeStackTracesReturns struct { +// GetNodeStackTracesResult is the result of the command +// DOM.getNodeStackTraces. +type GetNodeStackTracesResult struct { Creation *runtime.StackTrace `json:"creation,omitempty,omitzero"` // Creation stack trace, if available. } -// Do executes DOM.getNodeStackTraces against the provided context. -// -// returns: +// GetNodeStackTraces gets stack traces associated with a Node. As of now, +// only provides stack trace for Node creation. // -// creation - Creation stack trace, if available. -func (p *GetNodeStackTracesParams) Do(ctx context.Context) (creation *runtime.StackTrace, err error) { - // execute - var res GetNodeStackTracesReturns - err = cdp.Execute(ctx, CommandGetNodeStackTraces, p, &res) - if err != nil { - return nil, err - } - - return res.Creation, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getNodeStackTraces +var GetNodeStackTraces = cdp.Command[GetNodeStackTracesParams, GetNodeStackTracesResult]{Method: CommandGetNodeStackTraces} -// GetFileInfoParams returns file information for the given File wrapper. +// GetFileInfoParams are the parameters of the command DOM.getFileInfo. type GetFileInfoParams struct { ObjectID runtime.RemoteObjectID `json:"objectId"` // JavaScript object id of the node wrapper. } -// GetFileInfo returns file information for the given File wrapper. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getFileInfo -// -// parameters: -// -// objectID - JavaScript object id of the node wrapper. -func GetFileInfo(objectID runtime.RemoteObjectID) *GetFileInfoParams { - return &GetFileInfoParams{ - ObjectID: objectID, - } -} - -// GetFileInfoReturns return values. -type GetFileInfoReturns struct { +// GetFileInfoResult is the result of the command DOM.getFileInfo. +type GetFileInfoResult struct { Path string `json:"path,omitempty,omitzero"` } -// Do executes DOM.getFileInfo against the provided context. -// -// returns: +// GetFileInfo returns file information for the given File wrapper. // -// path -func (p *GetFileInfoParams) Do(ctx context.Context) (path string, err error) { - // execute - var res GetFileInfoReturns - err = cdp.Execute(ctx, CommandGetFileInfo, p, &res) - if err != nil { - return "", err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getFileInfo +var GetFileInfo = cdp.Command[GetFileInfoParams, GetFileInfoResult]{Method: CommandGetFileInfo} - return res.Path, nil +// GetDetachedDomNodesResult is the result of the command +// DOM.getDetachedDomNodes. +type GetDetachedDomNodesResult struct { + DetachedNodes []*DetachedElementInfo `json:"detachedNodes,omitempty,omitzero"` // The list of detached nodes } -// GetDetachedDomNodesParams returns list of detached nodes. -type GetDetachedDomNodesParams struct{} - // GetDetachedDomNodes returns list of detached nodes. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getDetachedDomNodes -func GetDetachedDomNodes() *GetDetachedDomNodesParams { - return &GetDetachedDomNodesParams{} -} - -// GetDetachedDomNodesReturns return values. -type GetDetachedDomNodesReturns struct { - DetachedNodes []*DetachedElementInfo `json:"detachedNodes,omitempty,omitzero"` // The list of detached nodes -} - -// Do executes DOM.getDetachedDomNodes against the provided context. -// -// returns: -// -// detachedNodes - The list of detached nodes -func (p *GetDetachedDomNodesParams) Do(ctx context.Context) (detachedNodes []*DetachedElementInfo, err error) { - // execute - var res GetDetachedDomNodesReturns - err = cdp.Execute(ctx, CommandGetDetachedDomNodes, nil, &res) - if err != nil { - return nil, err - } - - return res.DetachedNodes, nil -} +var GetDetachedDomNodes = cdp.Command[cdp.Empty, GetDetachedDomNodesResult]{Method: CommandGetDetachedDomNodes} -// SetInspectedNodeParams enables console to refer to the node with given id -// via $x (see Command Line API for more details $x functions). +// SetInspectedNodeParams are the parameters of the command +// DOM.setInspectedNode. type SetInspectedNodeParams struct { NodeID cdp.NodeID `json:"nodeId"` // DOM node id to be accessible by means of $x command line API. } @@ -1673,64 +630,25 @@ type SetInspectedNodeParams struct { // (see Command Line API for more details $x functions). // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setInspectedNode -// -// parameters: -// -// nodeID - DOM node id to be accessible by means of $x command line API. -func SetInspectedNode(nodeID cdp.NodeID) *SetInspectedNodeParams { - return &SetInspectedNodeParams{ - NodeID: nodeID, - } -} +var SetInspectedNode = cdp.Command[SetInspectedNodeParams, cdp.Empty]{Method: CommandSetInspectedNode} -// Do executes DOM.setInspectedNode against the provided context. -func (p *SetInspectedNodeParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetInspectedNode, p, nil) -} - -// SetNodeNameParams sets node name for a node with given id. +// SetNodeNameParams are the parameters of the command DOM.setNodeName. type SetNodeNameParams struct { NodeID cdp.NodeID `json:"nodeId"` // Id of the node to set name for. Name string `json:"name"` // New node's name. } -// SetNodeName sets node name for a node with given id. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setNodeName -// -// parameters: -// -// nodeID - Id of the node to set name for. -// name - New node's name. -func SetNodeName(nodeID cdp.NodeID, name string) *SetNodeNameParams { - return &SetNodeNameParams{ - NodeID: nodeID, - Name: name, - } -} - -// SetNodeNameReturns return values. -type SetNodeNameReturns struct { +// SetNodeNameResult is the result of the command DOM.setNodeName. +type SetNodeNameResult struct { NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // New node's id. } -// Do executes DOM.setNodeName against the provided context. -// -// returns: +// SetNodeName sets node name for a node with given id. // -// nodeID - New node's id. -func (p *SetNodeNameParams) Do(ctx context.Context) (nodeID cdp.NodeID, err error) { - // execute - var res SetNodeNameReturns - err = cdp.Execute(ctx, CommandSetNodeName, p, &res) - if err != nil { - return 0, err - } - - return res.NodeID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setNodeName +var SetNodeName = cdp.Command[SetNodeNameParams, SetNodeNameResult]{Method: CommandSetNodeName} -// SetNodeValueParams sets node value for a node with given id. +// SetNodeValueParams are the parameters of the command DOM.setNodeValue. type SetNodeValueParams struct { NodeID cdp.NodeID `json:"nodeId"` // Id of the node to set value for. Value string `json:"value"` // New node's value. @@ -1739,24 +657,9 @@ type SetNodeValueParams struct { // SetNodeValue sets node value for a node with given id. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setNodeValue -// -// parameters: -// -// nodeID - Id of the node to set value for. -// value - New node's value. -func SetNodeValue(nodeID cdp.NodeID, value string) *SetNodeValueParams { - return &SetNodeValueParams{ - NodeID: nodeID, - Value: value, - } -} - -// Do executes DOM.setNodeValue against the provided context. -func (p *SetNodeValueParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetNodeValue, p, nil) -} +var SetNodeValue = cdp.Command[SetNodeValueParams, cdp.Empty]{Method: CommandSetNodeValue} -// SetOuterHTMLParams sets node HTML markup, returns new node id. +// SetOuterHTMLParams are the parameters of the command DOM.setOuterHTML. type SetOuterHTMLParams struct { NodeID cdp.NodeID `json:"nodeId"` // Id of the node to set markup for. OuterHTML string `json:"outerHTML"` // Outer HTML markup to set. @@ -1765,93 +668,44 @@ type SetOuterHTMLParams struct { // SetOuterHTML sets node HTML markup, returns new node id. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setOuterHTML -// -// parameters: -// -// nodeID - Id of the node to set markup for. -// outerHTML - Outer HTML markup to set. -func SetOuterHTML(nodeID cdp.NodeID, outerHTML string) *SetOuterHTMLParams { - return &SetOuterHTMLParams{ - NodeID: nodeID, - OuterHTML: outerHTML, - } -} - -// Do executes DOM.setOuterHTML against the provided context. -func (p *SetOuterHTMLParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetOuterHTML, p, nil) -} - -// UndoParams undoes the last performed action. -type UndoParams struct{} +var SetOuterHTML = cdp.Command[SetOuterHTMLParams, cdp.Empty]{Method: CommandSetOuterHTML} // Undo undoes the last performed action. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-undo -func Undo() *UndoParams { - return &UndoParams{} -} - -// Do executes DOM.undo against the provided context. -func (p *UndoParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandUndo, nil, nil) -} +var Undo = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandUndo} -// GetFrameOwnerParams returns iframe node that owns iframe with the given -// domain. +// GetFrameOwnerParams are the parameters of the command DOM.getFrameOwner. type GetFrameOwnerParams struct { FrameID cdp.FrameID `json:"frameId"` } -// GetFrameOwner returns iframe node that owns iframe with the given domain. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getFrameOwner -// -// parameters: -// -// frameID -func GetFrameOwner(frameID cdp.FrameID) *GetFrameOwnerParams { - return &GetFrameOwnerParams{ - FrameID: frameID, - } -} - -// GetFrameOwnerReturns return values. -type GetFrameOwnerReturns struct { +// GetFrameOwnerResult is the result of the command DOM.getFrameOwner. +type GetFrameOwnerResult struct { BackendNodeID cdp.BackendNodeID `json:"backendNodeId,omitempty,omitzero"` // Resulting node. NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Id of the node at given coordinates, only when enabled and requested document. } -// Do executes DOM.getFrameOwner against the provided context. -// -// returns: +// GetFrameOwner returns iframe node that owns iframe with the given domain. // -// backendNodeID - Resulting node. -// nodeID - Id of the node at given coordinates, only when enabled and requested document. -func (p *GetFrameOwnerParams) Do(ctx context.Context) (backendNodeID cdp.BackendNodeID, nodeID cdp.NodeID, err error) { - // execute - var res GetFrameOwnerReturns - err = cdp.Execute(ctx, CommandGetFrameOwner, p, &res) - if err != nil { - return 0, 0, err - } - - return res.BackendNodeID, res.NodeID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getFrameOwner +var GetFrameOwner = cdp.Command[GetFrameOwnerParams, GetFrameOwnerResult]{Method: CommandGetFrameOwner} -// GetContainerForNodeParams returns the query container of the given node -// based on container query conditions: containerName, physical and logical -// axes, and whether it queries scroll-state or anchored elements. If no axes -// are provided and queriesScrollState is false, the style container is -// returned, which is the direct parent or the closest element with a matching -// container-name. +// GetContainerForNodeParams are the parameters of the command +// DOM.getContainerForNode. type GetContainerForNodeParams struct { NodeID cdp.NodeID `json:"nodeId"` ContainerName string `json:"containerName,omitempty,omitzero"` PhysicalAxes PhysicalAxes `json:"physicalAxes,omitempty,omitzero"` LogicalAxes LogicalAxes `json:"logicalAxes,omitempty,omitzero"` - QueriesScrollState bool `json:"queriesScrollState"` - QueriesAnchored bool `json:"queriesAnchored"` + QueriesScrollState *bool `json:"queriesScrollState,omitempty,omitzero"` + QueriesAnchored *bool `json:"queriesAnchored,omitempty,omitzero"` +} + +// GetContainerForNodeResult is the result of the command +// DOM.getContainerForNode. +type GetContainerForNodeResult struct { + NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // The container node for the given node, or null if not found. } // GetContainerForNode returns the query container of the given node based on @@ -1861,216 +715,220 @@ type GetContainerForNodeParams struct { // the direct parent or the closest element with a matching container-name. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getContainerForNode -// -// parameters: -// -// nodeID -func GetContainerForNode(nodeID cdp.NodeID) *GetContainerForNodeParams { - return &GetContainerForNodeParams{ - NodeID: nodeID, - QueriesScrollState: false, - QueriesAnchored: false, - } -} +var GetContainerForNode = cdp.Command[GetContainerForNodeParams, GetContainerForNodeResult]{Method: CommandGetContainerForNode} -// WithContainerName [no description]. -func (p GetContainerForNodeParams) WithContainerName(containerName string) *GetContainerForNodeParams { - p.ContainerName = containerName - return &p +// GetQueryingDescendantsForContainerParams are the parameters of the command +// DOM.getQueryingDescendantsForContainer. +type GetQueryingDescendantsForContainerParams struct { + NodeID cdp.NodeID `json:"nodeId"` // Id of the container node to find querying descendants from. } -// WithPhysicalAxes [no description]. -func (p GetContainerForNodeParams) WithPhysicalAxes(physicalAxes PhysicalAxes) *GetContainerForNodeParams { - p.PhysicalAxes = physicalAxes - return &p +// GetQueryingDescendantsForContainerResult is the result of the command +// DOM.getQueryingDescendantsForContainer. +type GetQueryingDescendantsForContainerResult struct { + NodeIDs []cdp.NodeID `json:"nodeIds,omitempty,omitzero"` // Descendant nodes with container queries against the given container. } -// WithLogicalAxes [no description]. -func (p GetContainerForNodeParams) WithLogicalAxes(logicalAxes LogicalAxes) *GetContainerForNodeParams { - p.LogicalAxes = logicalAxes - return &p +// GetQueryingDescendantsForContainer returns the descendants of a container +// query container that have container queries against this container. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getQueryingDescendantsForContainer +var GetQueryingDescendantsForContainer = cdp.Command[GetQueryingDescendantsForContainerParams, GetQueryingDescendantsForContainerResult]{Method: CommandGetQueryingDescendantsForContainer} + +// GetAnchorElementParams are the parameters of the command +// DOM.getAnchorElement. +type GetAnchorElementParams struct { + NodeID cdp.NodeID `json:"nodeId"` // Id of the positioned element from which to find the anchor. + AnchorSpecifier string `json:"anchorSpecifier,omitempty,omitzero"` // An optional anchor specifier, as defined in https://www.w3.org/TR/css-anchor-position-1/#anchor-specifier. If not provided, it will return the implicit anchor element for the given positioned element. } -// WithQueriesScrollState [no description]. -func (p GetContainerForNodeParams) WithQueriesScrollState(queriesScrollState bool) *GetContainerForNodeParams { - p.QueriesScrollState = queriesScrollState - return &p +// GetAnchorElementResult is the result of the command DOM.getAnchorElement. +type GetAnchorElementResult struct { + NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // The anchor element of the given anchor query. } -// WithQueriesAnchored [no description]. -func (p GetContainerForNodeParams) WithQueriesAnchored(queriesAnchored bool) *GetContainerForNodeParams { - p.QueriesAnchored = queriesAnchored - return &p +// GetAnchorElement returns the target anchor element of the given anchor +// query according to https://www.w3.org/TR/css-anchor-position-1/#target. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getAnchorElement +var GetAnchorElement = cdp.Command[GetAnchorElementParams, GetAnchorElementResult]{Method: CommandGetAnchorElement} + +// ForceShowPopoverParams are the parameters of the command +// DOM.forceShowPopover. +type ForceShowPopoverParams struct { + NodeID cdp.NodeID `json:"nodeId"` // Id of the popover HTMLElement + Enable bool `json:"enable"` // If true, opens the popover and keeps it open. If false, closes the popover if it was previously force-opened. + InvokerNodeID cdp.BackendNodeID `json:"invokerNodeId,omitempty,omitzero"` // Optional ID of the element invoking this popover, used to establish the implicit anchor. If not provided, it will fall back to the first invoker in the document, preferring elements with a popovertarget attribute over those with a commandfor attribute. Note that if there are multiple invokers, this is just an estimate. } -// GetContainerForNodeReturns return values. -type GetContainerForNodeReturns struct { - NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // The container node for the given node, or null if not found. +// ForceShowPopoverResult is the result of the command DOM.forceShowPopover. +type ForceShowPopoverResult struct { + NodeIDs []cdp.NodeID `json:"nodeIds,omitempty,omitzero"` // List of popovers that were closed in order to respect popover stacking order. } -// Do executes DOM.getContainerForNode against the provided context. -// -// returns: +// ForceShowPopover when enabling, this API force-opens the popover +// identified by nodeId and keeps it open until disabled. // -// nodeID - The container node for the given node, or null if not found. -func (p *GetContainerForNodeParams) Do(ctx context.Context) (nodeID cdp.NodeID, err error) { - // execute - var res GetContainerForNodeReturns - err = cdp.Execute(ctx, CommandGetContainerForNode, p, &res) - if err != nil { - return 0, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-forceShowPopover +var ForceShowPopover = cdp.Command[ForceShowPopoverParams, ForceShowPopoverResult]{Method: CommandForceShowPopover} - return res.NodeID, nil +// GetImplicitAnchorCandidatesParams are the parameters of the command +// DOM.getImplicitAnchorCandidates. +type GetImplicitAnchorCandidatesParams struct { + NodeID cdp.NodeID `json:"nodeId"` // Id of the popover HTMLElement. } -// GetQueryingDescendantsForContainerParams returns the descendants of a -// container query container that have container queries against this container. -type GetQueryingDescendantsForContainerParams struct { - NodeID cdp.NodeID `json:"nodeId"` // Id of the container node to find querying descendants from. +// GetImplicitAnchorCandidatesResult is the result of the command +// DOM.getImplicitAnchorCandidates. +type GetImplicitAnchorCandidatesResult struct { + BackendNodeIDs []cdp.BackendNodeID `json:"backendNodeIds,omitempty,omitzero"` // Candidate elements that can invoke this popover. } -// GetQueryingDescendantsForContainer returns the descendants of a container -// query container that have container queries against this container. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getQueryingDescendantsForContainer -// -// parameters: +// GetImplicitAnchorCandidates returns candidate nodes that are configured as +// triggers for the given popover. // -// nodeID - Id of the container node to find querying descendants from. -func GetQueryingDescendantsForContainer(nodeID cdp.NodeID) *GetQueryingDescendantsForContainerParams { - return &GetQueryingDescendantsForContainerParams{ - NodeID: nodeID, - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getImplicitAnchorCandidates +var GetImplicitAnchorCandidates = cdp.Command[GetImplicitAnchorCandidatesParams, GetImplicitAnchorCandidatesResult]{Method: CommandGetImplicitAnchorCandidates} + +// ForceShowInterestParams are the parameters of the command +// DOM.forceShowInterest. +type ForceShowInterestParams struct { + NodeID cdp.NodeID `json:"nodeId"` // Id of the interest invoker HTMLElement. + Enable bool `json:"enable"` // If true, opens and holds interest. If false, releases forced interest. } -// GetQueryingDescendantsForContainerReturns return values. -type GetQueryingDescendantsForContainerReturns struct { - NodeIDs []cdp.NodeID `json:"nodeIds,omitempty,omitzero"` // Descendant nodes with container queries against the given container. +// ForceShowInterest when enabling, this API forces an element to gain +// interest in its target, keeping interest active until disabled. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-forceShowInterest +var ForceShowInterest = cdp.Command[ForceShowInterestParams, cdp.Empty]{Method: CommandForceShowInterest} + +// SetTextMarkerParams are the parameters of the command DOM.setTextMarker. +type SetTextMarkerParams struct { + NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Identifier of the node. + BackendNodeID cdp.BackendNodeID `json:"backendNodeId,omitempty,omitzero"` // Identifier of the backend node. + ObjectID runtime.RemoteObjectID `json:"objectId,omitempty,omitzero"` // JavaScript object id of the node wrapper. + Type SetTextMarkerType `json:"type"` // The type of marker to set on the given range of text. + Start int64 `json:"start"` // Start offset into the element's rendered text in UTF-16 code units. For a text control, an offset into the control's value. Offsets count text in DOM order and do not enter shadow trees. To mark text inside a shadow tree, pass the element inside the shadow tree. + End int64 `json:"end"` // End offset (exclusive) in the same units and space as start. } -// Do executes DOM.getQueryingDescendantsForContainer against the provided context. +// SetTextMarker sets a spelling or grammar error marker on the given range +// of text. See +// https://github.com/Igalia/explainers/blob/main/force-spelling-grammar-markers/README.md +// Note: exactly one between nodeId, backendNodeId and objectId should be passed +// to identify the node. // -// returns: +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setTextMarker +var SetTextMarker = cdp.Command[SetTextMarkerParams, cdp.Empty]{Method: CommandSetTextMarker} + +// ClearTextMarkers clears the spelling and grammar error text markers +// overlapping the ranges set by setTextMarker in this session. These markers +// are also removed when the DOM domain is disabled or the session ends. // -// nodeIDs - Descendant nodes with container queries against the given container. -func (p *GetQueryingDescendantsForContainerParams) Do(ctx context.Context) (nodeIDs []cdp.NodeID, err error) { - // execute - var res GetQueryingDescendantsForContainerReturns - err = cdp.Execute(ctx, CommandGetQueryingDescendantsForContainer, p, &res) - if err != nil { - return nil, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-clearTextMarkers +var ClearTextMarkers = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandClearTextMarkers} - return res.NodeIDs, nil -} +// AttributeModified fired when Element's attribute is modified. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#event-attributeModified +var AttributeModified = cdp.Event[EventAttributeModified]{Method: "DOM.attributeModified"} -// GetAnchorElementParams returns the target anchor element of the given -// anchor query according to -// https://www.w3.org/TR/css-anchor-position-1/#target. -type GetAnchorElementParams struct { - NodeID cdp.NodeID `json:"nodeId"` // Id of the positioned element from which to find the anchor. - AnchorSpecifier string `json:"anchorSpecifier,omitempty,omitzero"` // An optional anchor specifier, as defined in https://www.w3.org/TR/css-anchor-position-1/#anchor-specifier. If not provided, it will return the implicit anchor element for the given positioned element. -} +// AdoptedStyleSheetsModified fired when Element's adoptedStyleSheets are +// modified. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#event-adoptedStyleSheetsModified +var AdoptedStyleSheetsModified = cdp.Event[EventAdoptedStyleSheetsModified]{Method: "DOM.adoptedStyleSheetsModified"} -// GetAnchorElement returns the target anchor element of the given anchor -// query according to https://www.w3.org/TR/css-anchor-position-1/#target. +// AttributeRemoved fired when Element's attribute is removed. // -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getAnchorElement +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#event-attributeRemoved +var AttributeRemoved = cdp.Event[EventAttributeRemoved]{Method: "DOM.attributeRemoved"} + +// CharacterDataModified mirrors DOMCharacterDataModified event. // -// parameters: +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#event-characterDataModified +var CharacterDataModified = cdp.Event[EventCharacterDataModified]{Method: "DOM.characterDataModified"} + +// ChildNodeCountUpdated fired when Container's child node count has changed. // -// nodeID - Id of the positioned element from which to find the anchor. -func GetAnchorElement(nodeID cdp.NodeID) *GetAnchorElementParams { - return &GetAnchorElementParams{ - NodeID: nodeID, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#event-childNodeCountUpdated +var ChildNodeCountUpdated = cdp.Event[EventChildNodeCountUpdated]{Method: "DOM.childNodeCountUpdated"} -// WithAnchorSpecifier an optional anchor specifier, as defined in -// https://www.w3.org/TR/css-anchor-position-1/#anchor-specifier. If not -// provided, it will return the implicit anchor element for the given positioned -// element. -func (p GetAnchorElementParams) WithAnchorSpecifier(anchorSpecifier string) *GetAnchorElementParams { - p.AnchorSpecifier = anchorSpecifier - return &p -} +// ChildNodeInserted mirrors DOMNodeInserted event. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#event-childNodeInserted +var ChildNodeInserted = cdp.Event[EventChildNodeInserted]{Method: "DOM.childNodeInserted"} -// GetAnchorElementReturns return values. -type GetAnchorElementReturns struct { - NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // The anchor element of the given anchor query. -} +// ChildNodeRemoved mirrors DOMNodeRemoved event. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#event-childNodeRemoved +var ChildNodeRemoved = cdp.Event[EventChildNodeRemoved]{Method: "DOM.childNodeRemoved"} -// Do executes DOM.getAnchorElement against the provided context. +// DistributedNodesUpdated called when distribution is changed. // -// returns: +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#event-distributedNodesUpdated +var DistributedNodesUpdated = cdp.Event[EventDistributedNodesUpdated]{Method: "DOM.distributedNodesUpdated"} + +// DocumentUpdated fired when Document has been totally updated. Node ids are +// no longer valid. // -// nodeID - The anchor element of the given anchor query. -func (p *GetAnchorElementParams) Do(ctx context.Context) (nodeID cdp.NodeID, err error) { - // execute - var res GetAnchorElementReturns - err = cdp.Execute(ctx, CommandGetAnchorElement, p, &res) - if err != nil { - return 0, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#event-documentUpdated +var DocumentUpdated = cdp.Event[EventDocumentUpdated]{Method: "DOM.documentUpdated"} - return res.NodeID, nil -} +// InlineStyleInvalidated fired when Element's inline style is modified via a +// CSS property modification. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#event-inlineStyleInvalidated +var InlineStyleInvalidated = cdp.Event[EventInlineStyleInvalidated]{Method: "DOM.inlineStyleInvalidated"} -// ForceShowPopoverParams when enabling, this API force-opens the popover -// identified by nodeId and keeps it open until disabled. -type ForceShowPopoverParams struct { - NodeID cdp.NodeID `json:"nodeId"` // Id of the popover HTMLElement - Enable bool `json:"enable"` // If true, opens the popover and keeps it open. If false, closes the popover if it was previously force-opened. - InvokerNodeID cdp.BackendNodeID `json:"invokerNodeId,omitempty,omitzero"` // Optional ID of the element invoking this popover, used to establish the implicit anchor. If not provided, it will fall back to the first invoker in the document, preferring elements with a popovertarget attribute over those with a commandfor attribute. Note that if there are multiple invokers, this is just an estimate. -} +// PseudoElementAdded called when a pseudo element is added to an element. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#event-pseudoElementAdded +var PseudoElementAdded = cdp.Event[EventPseudoElementAdded]{Method: "DOM.pseudoElementAdded"} -// ForceShowPopover when enabling, this API force-opens the popover -// identified by nodeId and keeps it open until disabled. +// TopLayerElementsUpdated called when top layer elements are changed. // -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-forceShowPopover +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#event-topLayerElementsUpdated +var TopLayerElementsUpdated = cdp.Event[EventTopLayerElementsUpdated]{Method: "DOM.topLayerElementsUpdated"} + +// ScrollableFlagUpdated fired when a node's scrollability state changes. // -// parameters: +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#event-scrollableFlagUpdated +var ScrollableFlagUpdated = cdp.Event[EventScrollableFlagUpdated]{Method: "DOM.scrollableFlagUpdated"} + +// AdRelatedStateUpdated fired when a node's ad related state changes. // -// nodeID - Id of the popover HTMLElement -// enable - If true, opens the popover and keeps it open. If false, closes the popover if it was previously force-opened. -func ForceShowPopover(nodeID cdp.NodeID, enable bool) *ForceShowPopoverParams { - return &ForceShowPopoverParams{ - NodeID: nodeID, - Enable: enable, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#event-adRelatedStateUpdated +var AdRelatedStateUpdated = cdp.Event[EventAdRelatedStateUpdated]{Method: "DOM.adRelatedStateUpdated"} -// WithInvokerNodeID optional ID of the element invoking this popover, used -// to establish the implicit anchor. If not provided, it will fall back to the -// first invoker in the document, preferring elements with a popovertarget -// attribute over those with a commandfor attribute. Note that if there are -// multiple invokers, this is just an estimate. -func (p ForceShowPopoverParams) WithInvokerNodeID(invokerNodeID cdp.BackendNodeID) *ForceShowPopoverParams { - p.InvokerNodeID = invokerNodeID - return &p -} +// AffectedByStartingStylesFlagUpdated fired when a node's starting styles +// changes. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#event-affectedByStartingStylesFlagUpdated +var AffectedByStartingStylesFlagUpdated = cdp.Event[EventAffectedByStartingStylesFlagUpdated]{Method: "DOM.affectedByStartingStylesFlagUpdated"} -// ForceShowPopoverReturns return values. -type ForceShowPopoverReturns struct { - NodeIDs []cdp.NodeID `json:"nodeIds,omitempty,omitzero"` // List of popovers that were closed in order to respect popover stacking order. -} +// PseudoElementRemoved called when a pseudo element is removed from an +// element. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#event-pseudoElementRemoved +var PseudoElementRemoved = cdp.Event[EventPseudoElementRemoved]{Method: "DOM.pseudoElementRemoved"} -// Do executes DOM.forceShowPopover against the provided context. +// SetChildNodes fired when backend wants to provide client with the missing +// DOM structure. This happens upon most of the calls requesting node ids. // -// returns: +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#event-setChildNodes +var SetChildNodes = cdp.Event[EventSetChildNodes]{Method: "DOM.setChildNodes"} + +// ShadowRootPopped called when shadow root is popped from the element. // -// nodeIDs - List of popovers that were closed in order to respect popover stacking order. -func (p *ForceShowPopoverParams) Do(ctx context.Context) (nodeIDs []cdp.NodeID, err error) { - // execute - var res ForceShowPopoverReturns - err = cdp.Execute(ctx, CommandForceShowPopover, p, &res) - if err != nil { - return nil, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#event-shadowRootPopped +var ShadowRootPopped = cdp.Event[EventShadowRootPopped]{Method: "DOM.shadowRootPopped"} - return res.NodeIDs, nil -} +// ShadowRootPushed called when shadow root is pushed into the element. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#event-shadowRootPushed +var ShadowRootPushed = cdp.Event[EventShadowRootPushed]{Method: "DOM.shadowRootPushed"} // Command names. const ( @@ -2123,4 +981,8 @@ const ( CommandGetQueryingDescendantsForContainer = "DOM.getQueryingDescendantsForContainer" CommandGetAnchorElement = "DOM.getAnchorElement" CommandForceShowPopover = "DOM.forceShowPopover" + CommandGetImplicitAnchorCandidates = "DOM.getImplicitAnchorCandidates" + CommandForceShowInterest = "DOM.forceShowInterest" + CommandSetTextMarker = "DOM.setTextMarker" + CommandClearTextMarkers = "DOM.clearTextMarkers" ) diff --git a/vendor/github.com/chromedp/cdproto/dom/events.go b/vendor/github.com/chromedp/cdproto/dom/events.go index 50883d442..29194a086 100644 --- a/vendor/github.com/chromedp/cdproto/dom/events.go +++ b/vendor/github.com/chromedp/cdproto/dom/events.go @@ -1,6 +1,6 @@ -package dom +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package dom import ( "github.com/chromedp/cdproto/cdp" diff --git a/vendor/github.com/chromedp/cdproto/dom/types.go b/vendor/github.com/chromedp/cdproto/dom/types.go index 35033d19b..d4cb7a62a 100644 --- a/vendor/github.com/chromedp/cdproto/dom/types.go +++ b/vendor/github.com/chromedp/cdproto/dom/types.go @@ -1,13 +1,10 @@ -package dom +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package dom import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/cdp" - "github.com/go-json-experiment/json/jsontext" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" ) // PhysicalAxes containerSelector physical axes. @@ -27,24 +24,6 @@ const ( PhysicalAxesBoth PhysicalAxes = "Both" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *PhysicalAxes) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch PhysicalAxes(s) { - case PhysicalAxesHorizontal: - *t = PhysicalAxesHorizontal - case PhysicalAxesVertical: - *t = PhysicalAxesVertical - case PhysicalAxesBoth: - *t = PhysicalAxesBoth - default: - return fmt.Errorf("unknown PhysicalAxes value: %v", s) - } - return nil -} - // LogicalAxes containerSelector logical axes. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#type-LogicalAxes @@ -62,24 +41,6 @@ const ( LogicalAxesBoth LogicalAxes = "Both" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *LogicalAxes) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch LogicalAxes(s) { - case LogicalAxesInline: - *t = LogicalAxesInline - case LogicalAxesBlock: - *t = LogicalAxesBlock - case LogicalAxesBoth: - *t = LogicalAxesBoth - default: - return fmt.Errorf("unknown LogicalAxes value: %v", s) - } - return nil -} - // ScrollOrientation physical scroll orientation. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#type-ScrollOrientation @@ -96,22 +57,6 @@ const ( ScrollOrientationVertical ScrollOrientation = "vertical" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ScrollOrientation) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ScrollOrientation(s) { - case ScrollOrientationHorizontal: - *t = ScrollOrientationHorizontal - case ScrollOrientationVertical: - *t = ScrollOrientationVertical - default: - return fmt.Errorf("unknown ScrollOrientation value: %v", s) - } - return nil -} - // DetachedElementInfo a structure to hold the top-level node of a detached // tree and an array of its retained descendants. // @@ -144,9 +89,9 @@ type BoxModel struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#type-ShapeOutsideInfo type ShapeOutsideInfo struct { - Bounds Quad `json:"bounds"` // Shape bounds - Shape []jsontext.Value `json:"shape"` // Shape coordinate details - MarginShape []jsontext.Value `json:"marginShape"` // Margin shape bounds + Bounds Quad `json:"bounds"` // Shape bounds + Shape []jsonv2.Value `json:"shape"` // Shape coordinate details + MarginShape []jsonv2.Value `json:"marginShape"` // Margin shape bounds } // Rect Rectangle. @@ -184,22 +129,6 @@ const ( EnableIncludeWhitespaceAll EnableIncludeWhitespace = "all" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *EnableIncludeWhitespace) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch EnableIncludeWhitespace(s) { - case EnableIncludeWhitespaceNone: - *t = EnableIncludeWhitespaceNone - case EnableIncludeWhitespaceAll: - *t = EnableIncludeWhitespaceAll - default: - return fmt.Errorf("unknown EnableIncludeWhitespace value: %v", s) - } - return nil -} - // GetElementByRelationRelation type of relation to get. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getElementByRelation @@ -217,20 +146,18 @@ const ( GetElementByRelationRelationCommandFor GetElementByRelationRelation = "CommandFor" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *GetElementByRelationRelation) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch GetElementByRelationRelation(s) { - case GetElementByRelationRelationPopoverTarget: - *t = GetElementByRelationRelationPopoverTarget - case GetElementByRelationRelationInterestTarget: - *t = GetElementByRelationRelationInterestTarget - case GetElementByRelationRelationCommandFor: - *t = GetElementByRelationRelationCommandFor - default: - return fmt.Errorf("unknown GetElementByRelationRelation value: %v", s) - } - return nil +// SetTextMarkerType the type of marker to set on the given range of text. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setTextMarker +type SetTextMarkerType string + +// String returns the SetTextMarkerType as string value. +func (t SetTextMarkerType) String() string { + return string(t) } + +// SetTextMarkerType values. +const ( + SetTextMarkerTypeSpelling SetTextMarkerType = "spelling" + SetTextMarkerTypeGrammar SetTextMarkerType = "grammar" +) diff --git a/vendor/github.com/chromedp/cdproto/domdebugger/domdebugger.go b/vendor/github.com/chromedp/cdproto/domdebugger/domdebugger.go index ee764f59e..d0de46daf 100644 --- a/vendor/github.com/chromedp/cdproto/domdebugger/domdebugger.go +++ b/vendor/github.com/chromedp/cdproto/domdebugger/domdebugger.go @@ -1,3 +1,5 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package domdebugger provides the Chrome DevTools Protocol // commands, types, and events for the DOMDebugger domain. // @@ -5,78 +7,35 @@ // events. JavaScript execution will stop on these operations as if there was a // regular breakpoint set. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package domdebugger -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/runtime" ) -// GetEventListenersParams returns event listeners of the given object. +// GetEventListenersParams are the parameters of the command +// DOMDebugger.getEventListeners. type GetEventListenersParams struct { - ObjectID runtime.RemoteObjectID `json:"objectId"` // Identifier of the object to return listeners for. - Depth int64 `json:"depth,omitempty,omitzero"` // The maximum depth at which Node children should be retrieved, defaults to 1. Use -1 for the entire subtree or provide an integer larger than 0. - Pierce bool `json:"pierce"` // Whether or not iframes and shadow roots should be traversed when returning the subtree (default is false). Reports listeners for all contexts if pierce is enabled. + ObjectID runtime.RemoteObjectID `json:"objectId"` // Identifier of the object to return listeners for. + Depth *int64 `json:"depth,omitempty,omitzero"` // The maximum depth at which Node children should be retrieved, defaults to 1. Use -1 for the entire subtree or provide an integer larger than 0. + Pierce *bool `json:"pierce,omitempty,omitzero"` // Whether or not iframes and shadow roots should be traversed when returning the subtree (default is false). Reports listeners for all contexts if pierce is enabled. } -// GetEventListeners returns event listeners of the given object. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#method-getEventListeners -// -// parameters: -// -// objectID - Identifier of the object to return listeners for. -func GetEventListeners(objectID runtime.RemoteObjectID) *GetEventListenersParams { - return &GetEventListenersParams{ - ObjectID: objectID, - Pierce: false, - } -} - -// WithDepth the maximum depth at which Node children should be retrieved, -// defaults to 1. Use -1 for the entire subtree or provide an integer larger -// than 0. -func (p GetEventListenersParams) WithDepth(depth int64) *GetEventListenersParams { - p.Depth = depth - return &p -} - -// WithPierce whether or not iframes and shadow roots should be traversed -// when returning the subtree (default is false). Reports listeners for all -// contexts if pierce is enabled. -func (p GetEventListenersParams) WithPierce(pierce bool) *GetEventListenersParams { - p.Pierce = pierce - return &p -} - -// GetEventListenersReturns return values. -type GetEventListenersReturns struct { +// GetEventListenersResult is the result of the command +// DOMDebugger.getEventListeners. +type GetEventListenersResult struct { Listeners []*EventListener `json:"listeners,omitempty,omitzero"` // Array of relevant listeners. } -// Do executes DOMDebugger.getEventListeners against the provided context. -// -// returns: +// GetEventListeners returns event listeners of the given object. // -// listeners - Array of relevant listeners. -func (p *GetEventListenersParams) Do(ctx context.Context) (listeners []*EventListener, err error) { - // execute - var res GetEventListenersReturns - err = cdp.Execute(ctx, CommandGetEventListeners, p, &res) - if err != nil { - return nil, err - } - - return res.Listeners, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#method-getEventListeners +var GetEventListeners = cdp.Command[GetEventListenersParams, GetEventListenersResult]{Method: CommandGetEventListeners} -// RemoveDOMBreakpointParams removes DOM breakpoint that was set using -// setDOMBreakpoint. +// RemoveDOMBreakpointParams are the parameters of the command +// DOMDebugger.removeDOMBreakpoint. type RemoveDOMBreakpointParams struct { NodeID cdp.NodeID `json:"nodeId"` // Identifier of the node to remove breakpoint from. Type DOMBreakpointType `json:"type"` // Type of the breakpoint to remove. @@ -86,25 +45,10 @@ type RemoveDOMBreakpointParams struct { // setDOMBreakpoint. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#method-removeDOMBreakpoint -// -// parameters: -// -// nodeID - Identifier of the node to remove breakpoint from. -// type - Type of the breakpoint to remove. -func RemoveDOMBreakpoint(nodeID cdp.NodeID, typeVal DOMBreakpointType) *RemoveDOMBreakpointParams { - return &RemoveDOMBreakpointParams{ - NodeID: nodeID, - Type: typeVal, - } -} +var RemoveDOMBreakpoint = cdp.Command[RemoveDOMBreakpointParams, cdp.Empty]{Method: CommandRemoveDOMBreakpoint} -// Do executes DOMDebugger.removeDOMBreakpoint against the provided context. -func (p *RemoveDOMBreakpointParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRemoveDOMBreakpoint, p, nil) -} - -// RemoveEventListenerBreakpointParams removes breakpoint on particular DOM -// event. +// RemoveEventListenerBreakpointParams are the parameters of the command +// DOMDebugger.removeEventListenerBreakpoint. type RemoveEventListenerBreakpointParams struct { EventName string `json:"eventName"` // Event name. TargetName string `json:"targetName,omitempty,omitzero"` // EventTarget interface name. @@ -113,28 +57,10 @@ type RemoveEventListenerBreakpointParams struct { // RemoveEventListenerBreakpoint removes breakpoint on particular DOM event. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#method-removeEventListenerBreakpoint -// -// parameters: -// -// eventName - Event name. -func RemoveEventListenerBreakpoint(eventName string) *RemoveEventListenerBreakpointParams { - return &RemoveEventListenerBreakpointParams{ - EventName: eventName, - } -} - -// WithTargetName eventTarget interface name. -func (p RemoveEventListenerBreakpointParams) WithTargetName(targetName string) *RemoveEventListenerBreakpointParams { - p.TargetName = targetName - return &p -} +var RemoveEventListenerBreakpoint = cdp.Command[RemoveEventListenerBreakpointParams, cdp.Empty]{Method: CommandRemoveEventListenerBreakpoint} -// Do executes DOMDebugger.removeEventListenerBreakpoint against the provided context. -func (p *RemoveEventListenerBreakpointParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRemoveEventListenerBreakpoint, p, nil) -} - -// RemoveXHRBreakpointParams removes breakpoint from XMLHttpRequest. +// RemoveXHRBreakpointParams are the parameters of the command +// DOMDebugger.removeXHRBreakpoint. type RemoveXHRBreakpointParams struct { URL string `json:"url"` // Resource URL substring. } @@ -142,22 +68,10 @@ type RemoveXHRBreakpointParams struct { // RemoveXHRBreakpoint removes breakpoint from XMLHttpRequest. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#method-removeXHRBreakpoint -// -// parameters: -// -// url - Resource URL substring. -func RemoveXHRBreakpoint(url string) *RemoveXHRBreakpointParams { - return &RemoveXHRBreakpointParams{ - URL: url, - } -} - -// Do executes DOMDebugger.removeXHRBreakpoint against the provided context. -func (p *RemoveXHRBreakpointParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRemoveXHRBreakpoint, p, nil) -} +var RemoveXHRBreakpoint = cdp.Command[RemoveXHRBreakpointParams, cdp.Empty]{Method: CommandRemoveXHRBreakpoint} -// SetBreakOnCSPViolationParams sets breakpoint on particular CSP violations. +// SetBreakOnCSPViolationParams are the parameters of the command +// DOMDebugger.setBreakOnCSPViolation. type SetBreakOnCSPViolationParams struct { ViolationTypes []CSPViolationType `json:"violationTypes"` // CSP Violations to stop upon. } @@ -165,22 +79,10 @@ type SetBreakOnCSPViolationParams struct { // SetBreakOnCSPViolation sets breakpoint on particular CSP violations. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#method-setBreakOnCSPViolation -// -// parameters: -// -// violationTypes - CSP Violations to stop upon. -func SetBreakOnCSPViolation(violationTypes []CSPViolationType) *SetBreakOnCSPViolationParams { - return &SetBreakOnCSPViolationParams{ - ViolationTypes: violationTypes, - } -} - -// Do executes DOMDebugger.setBreakOnCSPViolation against the provided context. -func (p *SetBreakOnCSPViolationParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetBreakOnCSPViolation, p, nil) -} +var SetBreakOnCSPViolation = cdp.Command[SetBreakOnCSPViolationParams, cdp.Empty]{Method: CommandSetBreakOnCSPViolation} -// SetDOMBreakpointParams sets breakpoint on particular operation with DOM. +// SetDOMBreakpointParams are the parameters of the command +// DOMDebugger.setDOMBreakpoint. type SetDOMBreakpointParams struct { NodeID cdp.NodeID `json:"nodeId"` // Identifier of the node to set breakpoint on. Type DOMBreakpointType `json:"type"` // Type of the operation to stop upon. @@ -189,24 +91,10 @@ type SetDOMBreakpointParams struct { // SetDOMBreakpoint sets breakpoint on particular operation with DOM. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#method-setDOMBreakpoint -// -// parameters: -// -// nodeID - Identifier of the node to set breakpoint on. -// type - Type of the operation to stop upon. -func SetDOMBreakpoint(nodeID cdp.NodeID, typeVal DOMBreakpointType) *SetDOMBreakpointParams { - return &SetDOMBreakpointParams{ - NodeID: nodeID, - Type: typeVal, - } -} +var SetDOMBreakpoint = cdp.Command[SetDOMBreakpointParams, cdp.Empty]{Method: CommandSetDOMBreakpoint} -// Do executes DOMDebugger.setDOMBreakpoint against the provided context. -func (p *SetDOMBreakpointParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetDOMBreakpoint, p, nil) -} - -// SetEventListenerBreakpointParams sets breakpoint on particular DOM event. +// SetEventListenerBreakpointParams are the parameters of the command +// DOMDebugger.setEventListenerBreakpoint. type SetEventListenerBreakpointParams struct { EventName string `json:"eventName"` // DOM Event name to stop on (any DOM event will do). TargetName string `json:"targetName,omitempty,omitzero"` // EventTarget interface name to stop on. If equal to "*" or not provided, will stop on any EventTarget. @@ -215,29 +103,10 @@ type SetEventListenerBreakpointParams struct { // SetEventListenerBreakpoint sets breakpoint on particular DOM event. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#method-setEventListenerBreakpoint -// -// parameters: -// -// eventName - DOM Event name to stop on (any DOM event will do). -func SetEventListenerBreakpoint(eventName string) *SetEventListenerBreakpointParams { - return &SetEventListenerBreakpointParams{ - EventName: eventName, - } -} - -// WithTargetName eventTarget interface name to stop on. If equal to "*" or -// not provided, will stop on any EventTarget. -func (p SetEventListenerBreakpointParams) WithTargetName(targetName string) *SetEventListenerBreakpointParams { - p.TargetName = targetName - return &p -} +var SetEventListenerBreakpoint = cdp.Command[SetEventListenerBreakpointParams, cdp.Empty]{Method: CommandSetEventListenerBreakpoint} -// Do executes DOMDebugger.setEventListenerBreakpoint against the provided context. -func (p *SetEventListenerBreakpointParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetEventListenerBreakpoint, p, nil) -} - -// SetXHRBreakpointParams sets breakpoint on XMLHttpRequest. +// SetXHRBreakpointParams are the parameters of the command +// DOMDebugger.setXHRBreakpoint. type SetXHRBreakpointParams struct { URL string `json:"url"` // Resource URL substring. All XHRs having this substring in the URL will get stopped upon. } @@ -245,20 +114,7 @@ type SetXHRBreakpointParams struct { // SetXHRBreakpoint sets breakpoint on XMLHttpRequest. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#method-setXHRBreakpoint -// -// parameters: -// -// url - Resource URL substring. All XHRs having this substring in the URL will get stopped upon. -func SetXHRBreakpoint(url string) *SetXHRBreakpointParams { - return &SetXHRBreakpointParams{ - URL: url, - } -} - -// Do executes DOMDebugger.setXHRBreakpoint against the provided context. -func (p *SetXHRBreakpointParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetXHRBreakpoint, p, nil) -} +var SetXHRBreakpoint = cdp.Command[SetXHRBreakpointParams, cdp.Empty]{Method: CommandSetXHRBreakpoint} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/domdebugger/types.go b/vendor/github.com/chromedp/cdproto/domdebugger/types.go index 79a65cd1b..f7591f90c 100644 --- a/vendor/github.com/chromedp/cdproto/domdebugger/types.go +++ b/vendor/github.com/chromedp/cdproto/domdebugger/types.go @@ -1,11 +1,8 @@ -package domdebugger +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package domdebugger import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/runtime" ) @@ -27,24 +24,6 @@ const ( DOMBreakpointTypeNodeRemoved DOMBreakpointType = "node-removed" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DOMBreakpointType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DOMBreakpointType(s) { - case DOMBreakpointTypeSubtreeModified: - *t = DOMBreakpointTypeSubtreeModified - case DOMBreakpointTypeAttributeModified: - *t = DOMBreakpointTypeAttributeModified - case DOMBreakpointTypeNodeRemoved: - *t = DOMBreakpointTypeNodeRemoved - default: - return fmt.Errorf("unknown DOMBreakpointType value: %v", s) - } - return nil -} - // CSPViolationType cSP Violation type. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#type-CSPViolationType @@ -61,22 +40,6 @@ const ( CSPViolationTypeTrustedtypePolicyViolation CSPViolationType = "trustedtype-policy-violation" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CSPViolationType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CSPViolationType(s) { - case CSPViolationTypeTrustedtypeSinkViolation: - *t = CSPViolationTypeTrustedtypeSinkViolation - case CSPViolationTypeTrustedtypePolicyViolation: - *t = CSPViolationTypeTrustedtypePolicyViolation - default: - return fmt.Errorf("unknown CSPViolationType value: %v", s) - } - return nil -} - // EventListener object event listener. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#type-EventListener diff --git a/vendor/github.com/chromedp/cdproto/domsnapshot/domsnapshot.go b/vendor/github.com/chromedp/cdproto/domsnapshot/domsnapshot.go index fe08b0732..3bc2893e0 100644 --- a/vendor/github.com/chromedp/cdproto/domsnapshot/domsnapshot.go +++ b/vendor/github.com/chromedp/cdproto/domsnapshot/domsnapshot.go @@ -1,61 +1,43 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package domsnapshot provides the Chrome DevTools Protocol // commands, types, and events for the DOMSnapshot domain. // // This domain facilitates obtaining document snapshots with DOM, layout, and // style information. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package domsnapshot -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// DisableParams disables DOM snapshot agent for the given page. -type DisableParams struct{} - // Disable disables DOM snapshot agent for the given page. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOMSnapshot#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes DOMSnapshot.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// EnableParams enables DOM snapshot agent for the given page. -type EnableParams struct{} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} // Enable enables DOM snapshot agent for the given page. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOMSnapshot#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} -// Do executes DOMSnapshot.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) +// CaptureSnapshotParams are the parameters of the command +// DOMSnapshot.captureSnapshot. +type CaptureSnapshotParams struct { + ComputedStyles []string `json:"computedStyles"` // Whitelist of computed styles to return. + IncludePaintOrder *bool `json:"includePaintOrder,omitempty,omitzero"` // Whether to include layout object paint orders into the snapshot. + IncludeDOMRects *bool `json:"includeDOMRects,omitempty,omitzero"` // Whether to include DOM rectangles (offsetRects, clientRects, scrollRects) into the snapshot + IncludeBlendedBackgroundColors *bool `json:"includeBlendedBackgroundColors,omitempty,omitzero"` // Whether to include blended background colors in the snapshot (default: false). Blended background color is achieved by blending background colors of all elements that overlap with the current element. + IncludeTextColorOpacities *bool `json:"includeTextColorOpacities,omitempty,omitzero"` // Whether to include text color opacity in the snapshot (default: false). An element might have the opacity property set that affects the text color of the element. The final text color opacity is computed based on the opacity of all overlapping elements. } -// CaptureSnapshotParams returns a document snapshot, including the full DOM -// tree of the root node (including iframes, template contents, and imported -// documents) in a flattened array, as well as layout and white-listed computed -// style information for the nodes. Shadow DOM in the returned DOM tree is -// flattened. -type CaptureSnapshotParams struct { - ComputedStyles []string `json:"computedStyles"` // Whitelist of computed styles to return. - IncludePaintOrder bool `json:"includePaintOrder"` // Whether to include layout object paint orders into the snapshot. - IncludeDOMRects bool `json:"includeDOMRects"` // Whether to include DOM rectangles (offsetRects, clientRects, scrollRects) into the snapshot - IncludeBlendedBackgroundColors bool `json:"includeBlendedBackgroundColors"` // Whether to include blended background colors in the snapshot (default: false). Blended background color is achieved by blending background colors of all elements that overlap with the current element. - IncludeTextColorOpacities bool `json:"includeTextColorOpacities"` // Whether to include text color opacity in the snapshot (default: false). An element might have the opacity property set that affects the text color of the element. The final text color opacity is computed based on the opacity of all overlapping elements. +// CaptureSnapshotResult is the result of the command +// DOMSnapshot.captureSnapshot. +type CaptureSnapshotResult struct { + Documents []*DocumentSnapshot `json:"documents,omitempty,omitzero"` // The nodes in the DOM tree. The DOMNode at index 0 corresponds to the root document. + Strings []string `json:"strings,omitempty,omitzero"` // Shared string table that all string properties refer to with indexes. } // CaptureSnapshot returns a document snapshot, including the full DOM tree @@ -65,74 +47,7 @@ type CaptureSnapshotParams struct { // flattened. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOMSnapshot#method-captureSnapshot -// -// parameters: -// -// computedStyles - Whitelist of computed styles to return. -func CaptureSnapshot(computedStyles []string) *CaptureSnapshotParams { - return &CaptureSnapshotParams{ - ComputedStyles: computedStyles, - IncludePaintOrder: false, - IncludeDOMRects: false, - IncludeBlendedBackgroundColors: false, - IncludeTextColorOpacities: false, - } -} - -// WithIncludePaintOrder whether to include layout object paint orders into -// the snapshot. -func (p CaptureSnapshotParams) WithIncludePaintOrder(includePaintOrder bool) *CaptureSnapshotParams { - p.IncludePaintOrder = includePaintOrder - return &p -} - -// WithIncludeDOMRects whether to include DOM rectangles (offsetRects, -// clientRects, scrollRects) into the snapshot. -func (p CaptureSnapshotParams) WithIncludeDOMRects(includeDOMRects bool) *CaptureSnapshotParams { - p.IncludeDOMRects = includeDOMRects - return &p -} - -// WithIncludeBlendedBackgroundColors whether to include blended background -// colors in the snapshot (default: false). Blended background color is achieved -// by blending background colors of all elements that overlap with the current -// element. -func (p CaptureSnapshotParams) WithIncludeBlendedBackgroundColors(includeBlendedBackgroundColors bool) *CaptureSnapshotParams { - p.IncludeBlendedBackgroundColors = includeBlendedBackgroundColors - return &p -} - -// WithIncludeTextColorOpacities whether to include text color opacity in the -// snapshot (default: false). An element might have the opacity property set -// that affects the text color of the element. The final text color opacity is -// computed based on the opacity of all overlapping elements. -func (p CaptureSnapshotParams) WithIncludeTextColorOpacities(includeTextColorOpacities bool) *CaptureSnapshotParams { - p.IncludeTextColorOpacities = includeTextColorOpacities - return &p -} - -// CaptureSnapshotReturns return values. -type CaptureSnapshotReturns struct { - Documents []*DocumentSnapshot `json:"documents,omitempty,omitzero"` // The nodes in the DOM tree. The DOMNode at index 0 corresponds to the root document. - Strings []string `json:"strings,omitempty,omitzero"` // Shared string table that all string properties refer to with indexes. -} - -// Do executes DOMSnapshot.captureSnapshot against the provided context. -// -// returns: -// -// documents - The nodes in the DOM tree. The DOMNode at index 0 corresponds to the root document. -// strings - Shared string table that all string properties refer to with indexes. -func (p *CaptureSnapshotParams) Do(ctx context.Context) (documents []*DocumentSnapshot, strings []string, err error) { - // execute - var res CaptureSnapshotReturns - err = cdp.Execute(ctx, CommandCaptureSnapshot, p, &res) - if err != nil { - return nil, nil, err - } - - return res.Documents, res.Strings, nil -} +var CaptureSnapshot = cdp.Command[CaptureSnapshotParams, CaptureSnapshotResult]{Method: CommandCaptureSnapshot} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/domsnapshot/types.go b/vendor/github.com/chromedp/cdproto/domsnapshot/types.go index 746e9ba4a..8886512c6 100644 --- a/vendor/github.com/chromedp/cdproto/domsnapshot/types.go +++ b/vendor/github.com/chromedp/cdproto/domsnapshot/types.go @@ -1,6 +1,6 @@ -package domsnapshot +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package domsnapshot import ( "github.com/chromedp/cdproto/cdp" @@ -12,7 +12,7 @@ import ( // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOMSnapshot#type-DOMNode type DOMNode struct { - NodeType cdp.NodeType `json:"nodeType"` // Node's nodeType. + NodeType int64 `json:"nodeType"` // Node's nodeType. NodeName string `json:"nodeName"` // Node's nodeName. NodeValue string `json:"nodeValue"` // Node's nodeValue. TextValue string `json:"textValue,omitempty,omitzero"` // Only set for textarea elements, contains the text value. diff --git a/vendor/github.com/chromedp/cdproto/domstorage/domstorage.go b/vendor/github.com/chromedp/cdproto/domstorage/domstorage.go index d1e12e7bd..6cb2b4162 100644 --- a/vendor/github.com/chromedp/cdproto/domstorage/domstorage.go +++ b/vendor/github.com/chromedp/cdproto/domstorage/domstorage.go @@ -1,20 +1,18 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package domstorage provides the Chrome DevTools Protocol // commands, types, and events for the DOMStorage domain. // // Query and modify DOM storage. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package domstorage -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// ClearParams [no description]. +// ClearParams are the parameters of the command DOMStorage.clear. type ClearParams struct { StorageID *StorageID `json:"storageId"` } @@ -22,95 +20,39 @@ type ClearParams struct { // Clear [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#method-clear -// -// parameters: -// -// storageID -func Clear(storageID *StorageID) *ClearParams { - return &ClearParams{ - StorageID: storageID, - } -} - -// Do executes DOMStorage.clear against the provided context. -func (p *ClearParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClear, p, nil) -} - -// DisableParams disables storage tracking, prevents storage events from -// being sent to the client. -type DisableParams struct{} +var Clear = cdp.Command[ClearParams, cdp.Empty]{Method: CommandClear} // Disable disables storage tracking, prevents storage events from being sent // to the client. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes DOMStorage.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// EnableParams enables storage tracking, storage events will now be -// delivered to the client. -type EnableParams struct{} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} // Enable enables storage tracking, storage events will now be delivered to // the client. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} - -// Do executes DOMStorage.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) -} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} -// GetDOMStorageItemsParams [no description]. +// GetDOMStorageItemsParams are the parameters of the command +// DOMStorage.getDOMStorageItems. type GetDOMStorageItemsParams struct { StorageID *StorageID `json:"storageId"` } -// GetDOMStorageItems [no description]. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#method-getDOMStorageItems -// -// parameters: -// -// storageID -func GetDOMStorageItems(storageID *StorageID) *GetDOMStorageItemsParams { - return &GetDOMStorageItemsParams{ - StorageID: storageID, - } -} - -// GetDOMStorageItemsReturns return values. -type GetDOMStorageItemsReturns struct { +// GetDOMStorageItemsResult is the result of the command +// DOMStorage.getDOMStorageItems. +type GetDOMStorageItemsResult struct { Entries []Item `json:"entries,omitempty,omitzero"` } -// Do executes DOMStorage.getDOMStorageItems against the provided context. -// -// returns: +// GetDOMStorageItems [no description]. // -// entries -func (p *GetDOMStorageItemsParams) Do(ctx context.Context) (entries []Item, err error) { - // execute - var res GetDOMStorageItemsReturns - err = cdp.Execute(ctx, CommandGetDOMStorageItems, p, &res) - if err != nil { - return nil, err - } - - return res.Entries, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#method-getDOMStorageItems +var GetDOMStorageItems = cdp.Command[GetDOMStorageItemsParams, GetDOMStorageItemsResult]{Method: CommandGetDOMStorageItems} -// RemoveDOMStorageItemParams [no description]. +// RemoveDOMStorageItemParams are the parameters of the command +// DOMStorage.removeDOMStorageItem. type RemoveDOMStorageItemParams struct { StorageID *StorageID `json:"storageId"` Key string `json:"key"` @@ -119,24 +61,10 @@ type RemoveDOMStorageItemParams struct { // RemoveDOMStorageItem [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#method-removeDOMStorageItem -// -// parameters: -// -// storageID -// key -func RemoveDOMStorageItem(storageID *StorageID, key string) *RemoveDOMStorageItemParams { - return &RemoveDOMStorageItemParams{ - StorageID: storageID, - Key: key, - } -} +var RemoveDOMStorageItem = cdp.Command[RemoveDOMStorageItemParams, cdp.Empty]{Method: CommandRemoveDOMStorageItem} -// Do executes DOMStorage.removeDOMStorageItem against the provided context. -func (p *RemoveDOMStorageItemParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRemoveDOMStorageItem, p, nil) -} - -// SetDOMStorageItemParams [no description]. +// SetDOMStorageItemParams are the parameters of the command +// DOMStorage.setDOMStorageItem. type SetDOMStorageItemParams struct { StorageID *StorageID `json:"storageId"` Key string `json:"key"` @@ -146,24 +74,27 @@ type SetDOMStorageItemParams struct { // SetDOMStorageItem [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#method-setDOMStorageItem +var SetDOMStorageItem = cdp.Command[SetDOMStorageItemParams, cdp.Empty]{Method: CommandSetDOMStorageItem} + +// DomStorageItemAdded [no description]. // -// parameters: +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#event-domStorageItemAdded +var DomStorageItemAdded = cdp.Event[EventDomStorageItemAdded]{Method: "DOMStorage.domStorageItemAdded"} + +// DomStorageItemRemoved [no description]. // -// storageID -// key -// value -func SetDOMStorageItem(storageID *StorageID, key string, value string) *SetDOMStorageItemParams { - return &SetDOMStorageItemParams{ - StorageID: storageID, - Key: key, - Value: value, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#event-domStorageItemRemoved +var DomStorageItemRemoved = cdp.Event[EventDomStorageItemRemoved]{Method: "DOMStorage.domStorageItemRemoved"} -// Do executes DOMStorage.setDOMStorageItem against the provided context. -func (p *SetDOMStorageItemParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetDOMStorageItem, p, nil) -} +// DomStorageItemUpdated [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#event-domStorageItemUpdated +var DomStorageItemUpdated = cdp.Event[EventDomStorageItemUpdated]{Method: "DOMStorage.domStorageItemUpdated"} + +// DomStorageItemsCleared [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#event-domStorageItemsCleared +var DomStorageItemsCleared = cdp.Event[EventDomStorageItemsCleared]{Method: "DOMStorage.domStorageItemsCleared"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/domstorage/events.go b/vendor/github.com/chromedp/cdproto/domstorage/events.go index bde61f852..93e724c56 100644 --- a/vendor/github.com/chromedp/cdproto/domstorage/events.go +++ b/vendor/github.com/chromedp/cdproto/domstorage/events.go @@ -1,6 +1,6 @@ -package domstorage +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package domstorage // EventDomStorageItemAdded [no description]. // diff --git a/vendor/github.com/chromedp/cdproto/domstorage/types.go b/vendor/github.com/chromedp/cdproto/domstorage/types.go index c64b590da..be992154d 100644 --- a/vendor/github.com/chromedp/cdproto/domstorage/types.go +++ b/vendor/github.com/chromedp/cdproto/domstorage/types.go @@ -1,6 +1,6 @@ -package domstorage +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package domstorage // SerializedStorageKey [no description]. // diff --git a/vendor/github.com/chromedp/cdproto/emulation/emulation.go b/vendor/github.com/chromedp/cdproto/emulation/emulation.go index 62e7548a7..de9b674f5 100644 --- a/vendor/github.com/chromedp/cdproto/emulation/emulation.go +++ b/vendor/github.com/chromedp/cdproto/emulation/emulation.go @@ -1,71 +1,38 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package emulation provides the Chrome DevTools Protocol // commands, types, and events for the Emulation domain. // // This domain emulates different environments for the page. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package emulation -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" + "github.com/chromedp/cdproto/dom" "github.com/chromedp/cdproto/page" ) -// ClearDeviceMetricsOverrideParams clears the overridden device metrics. -type ClearDeviceMetricsOverrideParams struct{} - // ClearDeviceMetricsOverride clears the overridden device metrics. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-clearDeviceMetricsOverride -func ClearDeviceMetricsOverride() *ClearDeviceMetricsOverrideParams { - return &ClearDeviceMetricsOverrideParams{} -} - -// Do executes Emulation.clearDeviceMetricsOverride against the provided context. -func (p *ClearDeviceMetricsOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClearDeviceMetricsOverride, nil, nil) -} - -// ClearGeolocationOverrideParams clears the overridden Geolocation Position -// and Error. -type ClearGeolocationOverrideParams struct{} +var ClearDeviceMetricsOverride = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandClearDeviceMetricsOverride} // ClearGeolocationOverride clears the overridden Geolocation Position and // Error. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-clearGeolocationOverride -func ClearGeolocationOverride() *ClearGeolocationOverrideParams { - return &ClearGeolocationOverrideParams{} -} - -// Do executes Emulation.clearGeolocationOverride against the provided context. -func (p *ClearGeolocationOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClearGeolocationOverride, nil, nil) -} - -// ResetPageScaleFactorParams requests that page scale factor is reset to -// initial values. -type ResetPageScaleFactorParams struct{} +var ClearGeolocationOverride = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandClearGeolocationOverride} // ResetPageScaleFactor requests that page scale factor is reset to initial // values. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-resetPageScaleFactor -func ResetPageScaleFactor() *ResetPageScaleFactorParams { - return &ResetPageScaleFactorParams{} -} - -// Do executes Emulation.resetPageScaleFactor against the provided context. -func (p *ResetPageScaleFactorParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandResetPageScaleFactor, nil, nil) -} +var ResetPageScaleFactor = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandResetPageScaleFactor} -// SetFocusEmulationEnabledParams enables or disables simulating a focused -// and active page. +// SetFocusEmulationEnabledParams are the parameters of the command +// Emulation.setFocusEmulationEnabled. type SetFocusEmulationEnabledParams struct { Enabled bool `json:"enabled"` // Whether to enable to disable focus emulation. } @@ -74,52 +41,22 @@ type SetFocusEmulationEnabledParams struct { // active page. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setFocusEmulationEnabled -// -// parameters: -// -// enabled - Whether to enable to disable focus emulation. -func SetFocusEmulationEnabled(enabled bool) *SetFocusEmulationEnabledParams { - return &SetFocusEmulationEnabledParams{ - Enabled: enabled, - } -} +var SetFocusEmulationEnabled = cdp.Command[SetFocusEmulationEnabledParams, cdp.Empty]{Method: CommandSetFocusEmulationEnabled} -// Do executes Emulation.setFocusEmulationEnabled against the provided context. -func (p *SetFocusEmulationEnabledParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetFocusEmulationEnabled, p, nil) -} - -// SetAutoDarkModeOverrideParams automatically render all web contents using -// a dark theme. +// SetAutoDarkModeOverrideParams are the parameters of the command +// Emulation.setAutoDarkModeOverride. type SetAutoDarkModeOverrideParams struct { - Enabled bool `json:"enabled"` // Whether to enable or disable automatic dark mode. If not specified, any existing override will be cleared. + Enabled *bool `json:"enabled,omitempty,omitzero"` // Whether to enable or disable automatic dark mode. If not specified, any existing override will be cleared. } // SetAutoDarkModeOverride automatically render all web contents using a dark // theme. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setAutoDarkModeOverride -// -// parameters: -func SetAutoDarkModeOverride() *SetAutoDarkModeOverrideParams { - return &SetAutoDarkModeOverrideParams{ - Enabled: false, - } -} - -// WithEnabled whether to enable or disable automatic dark mode. If not -// specified, any existing override will be cleared. -func (p SetAutoDarkModeOverrideParams) WithEnabled(enabled bool) *SetAutoDarkModeOverrideParams { - p.Enabled = enabled - return &p -} - -// Do executes Emulation.setAutoDarkModeOverride against the provided context. -func (p *SetAutoDarkModeOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetAutoDarkModeOverride, p, nil) -} +var SetAutoDarkModeOverride = cdp.Command[SetAutoDarkModeOverrideParams, cdp.Empty]{Method: CommandSetAutoDarkModeOverride} -// SetCPUThrottlingRateParams enables CPU throttling to emulate slow CPUs. +// SetCPUThrottlingRateParams are the parameters of the command +// Emulation.setCPUThrottlingRate. type SetCPUThrottlingRateParams struct { Rate float64 `json:"rate"` // Throttling rate as a slowdown factor (1 is no throttle, 2 is 2x slowdown, etc). } @@ -127,24 +64,10 @@ type SetCPUThrottlingRateParams struct { // SetCPUThrottlingRate enables CPU throttling to emulate slow CPUs. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setCPUThrottlingRate -// -// parameters: -// -// rate - Throttling rate as a slowdown factor (1 is no throttle, 2 is 2x slowdown, etc). -func SetCPUThrottlingRate(rate float64) *SetCPUThrottlingRateParams { - return &SetCPUThrottlingRateParams{ - Rate: rate, - } -} +var SetCPUThrottlingRate = cdp.Command[SetCPUThrottlingRateParams, cdp.Empty]{Method: CommandSetCPUThrottlingRate} -// Do executes Emulation.setCPUThrottlingRate against the provided context. -func (p *SetCPUThrottlingRateParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetCPUThrottlingRate, p, nil) -} - -// SetDefaultBackgroundColorOverrideParams sets or clears an override of the -// default background color of the frame. This override is used if the content -// does not specify one. +// SetDefaultBackgroundColorOverrideParams are the parameters of the command +// Emulation.setDefaultBackgroundColorOverride. type SetDefaultBackgroundColorOverrideParams struct { Color *cdp.RGBA `json:"color,omitempty,omitzero"` // RGBA of the default background color. If not specified, any existing override will be cleared. } @@ -154,28 +77,10 @@ type SetDefaultBackgroundColorOverrideParams struct { // does not specify one. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setDefaultBackgroundColorOverride -// -// parameters: -func SetDefaultBackgroundColorOverride() *SetDefaultBackgroundColorOverrideParams { - return &SetDefaultBackgroundColorOverrideParams{} -} +var SetDefaultBackgroundColorOverride = cdp.Command[SetDefaultBackgroundColorOverrideParams, cdp.Empty]{Method: CommandSetDefaultBackgroundColorOverride} -// WithColor rGBA of the default background color. If not specified, any -// existing override will be cleared. -func (p SetDefaultBackgroundColorOverrideParams) WithColor(color *cdp.RGBA) *SetDefaultBackgroundColorOverrideParams { - p.Color = color - return &p -} - -// Do executes Emulation.setDefaultBackgroundColorOverride against the provided context. -func (p *SetDefaultBackgroundColorOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetDefaultBackgroundColorOverride, p, nil) -} - -// SetSafeAreaInsetsOverrideParams overrides the values for -// env(safe-area-inset-*) and env(safe-area-max-inset-*). Unset values will -// cause the respective variables to be undefined, even if previously -// overridden. +// SetSafeAreaInsetsOverrideParams are the parameters of the command +// Emulation.setSafeAreaInsetsOverride. type SetSafeAreaInsetsOverrideParams struct { Insets *SafeAreaInsets `json:"insets"` } @@ -185,40 +90,44 @@ type SetSafeAreaInsetsOverrideParams struct { // variables to be undefined, even if previously overridden. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setSafeAreaInsetsOverride -// -// parameters: -// -// insets -func SetSafeAreaInsetsOverride(insets *SafeAreaInsets) *SetSafeAreaInsetsOverrideParams { - return &SetSafeAreaInsetsOverrideParams{ - Insets: insets, - } -} +var SetSafeAreaInsetsOverride = cdp.Command[SetSafeAreaInsetsOverrideParams, cdp.Empty]{Method: CommandSetSafeAreaInsetsOverride} -// Do executes Emulation.setSafeAreaInsetsOverride against the provided context. -func (p *SetSafeAreaInsetsOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetSafeAreaInsetsOverride, p, nil) +// SetVirtualKeyboardGeometryOverrideParams are the parameters of the command +// Emulation.setVirtualKeyboardGeometryOverride. +type SetVirtualKeyboardGeometryOverrideParams struct { + KeyboardRect *dom.Rect `json:"keyboardRect,omitempty,omitzero"` } -// SetDeviceMetricsOverrideParams overrides the values of device screen -// dimensions (window.screen.width, window.screen.height, window.innerWidth, -// window.innerHeight, and "device-width"/"device-height"-related CSS media -// query results). +// SetVirtualKeyboardGeometryOverride overrides virtual keyboard geometry in +// CSS pixels, relative to the top-level viewport. The provided rect is used for +// navigator.virtualKeyboard.boundingRect, geometrychange events, and +// env(keyboard-inset-*) values on the inspected frame. The override applies +// independently of navigator.virtualKeyboard.overlaysContent so clients can +// preview overlay geometry without mutating page state. Values are rounded to +// the nearest CSS pixel. Omitting the rect clears the override. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setVirtualKeyboardGeometryOverride +var SetVirtualKeyboardGeometryOverride = cdp.Command[SetVirtualKeyboardGeometryOverrideParams, cdp.Empty]{Method: CommandSetVirtualKeyboardGeometryOverride} + +// SetDeviceMetricsOverrideParams are the parameters of the command +// Emulation.setDeviceMetricsOverride. type SetDeviceMetricsOverrideParams struct { - Width int64 `json:"width"` // Overriding width value in pixels (minimum 0, maximum 10000000). 0 disables the override. - Height int64 `json:"height"` // Overriding height value in pixels (minimum 0, maximum 10000000). 0 disables the override. - DeviceScaleFactor float64 `json:"deviceScaleFactor"` // Overriding device scale factor value. 0 disables the override. - Mobile bool `json:"mobile"` // Whether to emulate mobile device. This includes viewport meta tag, overlay scrollbars, text autosizing and more. - Scale float64 `json:"scale,omitempty,omitzero"` // Scale to apply to resulting view image. - ScreenWidth int64 `json:"screenWidth,omitempty,omitzero"` // Overriding screen width value in pixels (minimum 0, maximum 10000000). - ScreenHeight int64 `json:"screenHeight,omitempty,omitzero"` // Overriding screen height value in pixels (minimum 0, maximum 10000000). - PositionX int64 `json:"positionX,omitempty,omitzero"` // Overriding view X position on screen in pixels (minimum 0, maximum 10000000). - PositionY int64 `json:"positionY,omitempty,omitzero"` // Overriding view Y position on screen in pixels (minimum 0, maximum 10000000). - DontSetVisibleSize bool `json:"dontSetVisibleSize"` // Do not set visible view size, rely upon explicit setVisibleSize call. - ScreenOrientation *ScreenOrientation `json:"screenOrientation,omitempty,omitzero"` // Screen orientation override. - Viewport *page.Viewport `json:"viewport,omitempty,omitzero"` // If set, the visible area of the page will be overridden to this viewport. This viewport change is not observed by the page, e.g. viewport-relative elements do not change positions. - ScrollbarType SetDeviceMetricsOverrideScrollbarType `json:"scrollbarType,omitempty,omitzero"` // Scrollbar type. Default: default. - ScreenOrientationLockEmulation bool `json:"screenOrientationLockEmulation"` // If set to true, enables screen orientation lock emulation, which intercepts screen.orientation.lock() calls from the page and reports orientation changes via screenOrientationLockChanged events. This is useful for emulating mobile device orientation lock behavior in responsive design mode. + Width int64 `json:"width"` // Overriding width value in pixels (minimum 0, maximum 10000000). 0 disables the override. + Height int64 `json:"height"` // Overriding height value in pixels (minimum 0, maximum 10000000). 0 disables the override. + DeviceScaleFactor float64 `json:"deviceScaleFactor"` // Overriding device scale factor value. 0 disables the override. + Mobile bool `json:"mobile"` // Whether to emulate mobile device. This includes viewport meta tag, overlay scrollbars, text autosizing and more. + Scale float64 `json:"scale,omitempty,omitzero"` // Scale to apply to resulting view image. + ScreenWidth int64 `json:"screenWidth,omitempty,omitzero"` // Overriding screen width value in pixels (minimum 0, maximum 10000000). + ScreenHeight int64 `json:"screenHeight,omitempty,omitzero"` // Overriding screen height value in pixels (minimum 0, maximum 10000000). + PositionX int64 `json:"positionX,omitempty,omitzero"` // Overriding view X position on screen in pixels (minimum 0, maximum 10000000). + PositionY int64 `json:"positionY,omitempty,omitzero"` // Overriding view Y position on screen in pixels (minimum 0, maximum 10000000). + DontSetVisibleSize *bool `json:"dontSetVisibleSize,omitempty,omitzero"` // Do not set visible view size, rely upon explicit setVisibleSize call. + ScreenOrientation *ScreenOrientation `json:"screenOrientation,omitempty,omitzero"` // Screen orientation override. + Viewport *page.Viewport `json:"viewport,omitempty,omitzero"` // If set, the visible area of the page will be overridden to this viewport. This viewport change is not observed by the page, e.g. viewport-relative elements do not change positions. + ScrollbarType SetDeviceMetricsOverrideScrollbarType `json:"scrollbarType,omitempty,omitzero"` // Scrollbar type. Default: default. + ScreenOrientationLockEmulation *bool `json:"screenOrientationLockEmulation,omitempty,omitzero"` // If set to true, enables screen orientation lock emulation, which intercepts screen.orientation.lock() calls from the page and reports orientation changes via screenOrientationLockChanged events. This is useful for emulating mobile device orientation lock behavior in responsive design mode. + ViewportMeta SetDeviceMetricsOverrideViewportMeta `json:"viewportMeta,omitempty,omitzero"` // Viewport meta tag behavior. Default: default. Note: if mobile is true, the viewport meta tag is always enabled. + TextLayoutMode SetDeviceMetricsOverrideTextLayoutMode `json:"textLayoutMode,omitempty,omitzero"` // Text layout mode. Default: default. Note: if mobile is true, mobile text layout mode (text autosizing) is always enabled. } // SetDeviceMetricsOverride overrides the values of device screen dimensions @@ -227,103 +136,10 @@ type SetDeviceMetricsOverrideParams struct { // query results). // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setDeviceMetricsOverride -// -// parameters: -// -// width - Overriding width value in pixels (minimum 0, maximum 10000000). 0 disables the override. -// height - Overriding height value in pixels (minimum 0, maximum 10000000). 0 disables the override. -// deviceScaleFactor - Overriding device scale factor value. 0 disables the override. -// mobile - Whether to emulate mobile device. This includes viewport meta tag, overlay scrollbars, text autosizing and more. -func SetDeviceMetricsOverride(width int64, height int64, deviceScaleFactor float64, mobile bool) *SetDeviceMetricsOverrideParams { - return &SetDeviceMetricsOverrideParams{ - Width: width, - Height: height, - DeviceScaleFactor: deviceScaleFactor, - Mobile: mobile, - DontSetVisibleSize: false, - ScreenOrientationLockEmulation: false, - } -} - -// WithScale scale to apply to resulting view image. -func (p SetDeviceMetricsOverrideParams) WithScale(scale float64) *SetDeviceMetricsOverrideParams { - p.Scale = scale - return &p -} - -// WithScreenWidth overriding screen width value in pixels (minimum 0, -// maximum 10000000). -func (p SetDeviceMetricsOverrideParams) WithScreenWidth(screenWidth int64) *SetDeviceMetricsOverrideParams { - p.ScreenWidth = screenWidth - return &p -} - -// WithScreenHeight overriding screen height value in pixels (minimum 0, -// maximum 10000000). -func (p SetDeviceMetricsOverrideParams) WithScreenHeight(screenHeight int64) *SetDeviceMetricsOverrideParams { - p.ScreenHeight = screenHeight - return &p -} - -// WithPositionX overriding view X position on screen in pixels (minimum 0, -// maximum 10000000). -func (p SetDeviceMetricsOverrideParams) WithPositionX(positionX int64) *SetDeviceMetricsOverrideParams { - p.PositionX = positionX - return &p -} - -// WithPositionY overriding view Y position on screen in pixels (minimum 0, -// maximum 10000000). -func (p SetDeviceMetricsOverrideParams) WithPositionY(positionY int64) *SetDeviceMetricsOverrideParams { - p.PositionY = positionY - return &p -} - -// WithDontSetVisibleSize do not set visible view size, rely upon explicit -// setVisibleSize call. -func (p SetDeviceMetricsOverrideParams) WithDontSetVisibleSize(dontSetVisibleSize bool) *SetDeviceMetricsOverrideParams { - p.DontSetVisibleSize = dontSetVisibleSize - return &p -} - -// WithScreenOrientation screen orientation override. -func (p SetDeviceMetricsOverrideParams) WithScreenOrientation(screenOrientation *ScreenOrientation) *SetDeviceMetricsOverrideParams { - p.ScreenOrientation = screenOrientation - return &p -} - -// WithViewport if set, the visible area of the page will be overridden to -// this viewport. This viewport change is not observed by the page, e.g. -// viewport-relative elements do not change positions. -func (p SetDeviceMetricsOverrideParams) WithViewport(viewport *page.Viewport) *SetDeviceMetricsOverrideParams { - p.Viewport = viewport - return &p -} - -// WithScrollbarType scrollbar type. Default: default. -func (p SetDeviceMetricsOverrideParams) WithScrollbarType(scrollbarType SetDeviceMetricsOverrideScrollbarType) *SetDeviceMetricsOverrideParams { - p.ScrollbarType = scrollbarType - return &p -} - -// WithScreenOrientationLockEmulation if set to true, enables screen -// orientation lock emulation, which intercepts screen.orientation.lock() calls -// from the page and reports orientation changes via -// screenOrientationLockChanged events. This is useful for emulating mobile -// device orientation lock behavior in responsive design mode. -func (p SetDeviceMetricsOverrideParams) WithScreenOrientationLockEmulation(screenOrientationLockEmulation bool) *SetDeviceMetricsOverrideParams { - p.ScreenOrientationLockEmulation = screenOrientationLockEmulation - return &p -} +var SetDeviceMetricsOverride = cdp.Command[SetDeviceMetricsOverrideParams, cdp.Empty]{Method: CommandSetDeviceMetricsOverride} -// Do executes Emulation.setDeviceMetricsOverride against the provided context. -func (p *SetDeviceMetricsOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetDeviceMetricsOverride, p, nil) -} - -// SetDevicePostureOverrideParams start reporting the given posture value to -// the Device Posture API. This override can also be set in -// setDeviceMetricsOverride(). +// SetDevicePostureOverrideParams are the parameters of the command +// Emulation.setDevicePostureOverride. type SetDevicePostureOverrideParams struct { Posture *DevicePosture `json:"posture"` } @@ -333,26 +149,7 @@ type SetDevicePostureOverrideParams struct { // setDeviceMetricsOverride(). // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setDevicePostureOverride -// -// parameters: -// -// posture -func SetDevicePostureOverride(posture *DevicePosture) *SetDevicePostureOverrideParams { - return &SetDevicePostureOverrideParams{ - Posture: posture, - } -} - -// Do executes Emulation.setDevicePostureOverride against the provided context. -func (p *SetDevicePostureOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetDevicePostureOverride, p, nil) -} - -// ClearDevicePostureOverrideParams clears a device posture override set with -// either setDeviceMetricsOverride() or setDevicePostureOverride() and starts -// using posture information from the platform again. Does nothing if no -// override is set. -type ClearDevicePostureOverrideParams struct{} +var SetDevicePostureOverride = cdp.Command[SetDevicePostureOverrideParams, cdp.Empty]{Method: CommandSetDevicePostureOverride} // ClearDevicePostureOverride clears a device posture override set with // either setDeviceMetricsOverride() or setDevicePostureOverride() and starts @@ -360,18 +157,10 @@ type ClearDevicePostureOverrideParams struct{} // override is set. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-clearDevicePostureOverride -func ClearDevicePostureOverride() *ClearDevicePostureOverrideParams { - return &ClearDevicePostureOverrideParams{} -} - -// Do executes Emulation.clearDevicePostureOverride against the provided context. -func (p *ClearDevicePostureOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClearDevicePostureOverride, nil, nil) -} +var ClearDevicePostureOverride = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandClearDevicePostureOverride} -// SetDisplayFeaturesOverrideParams start using the given display features to -// pupulate the Viewport Segments API. This override can also be set in -// setDeviceMetricsOverride(). +// SetDisplayFeaturesOverrideParams are the parameters of the command +// Emulation.setDisplayFeaturesOverride. type SetDisplayFeaturesOverrideParams struct { Features []*DisplayFeature `json:"features"` } @@ -381,26 +170,7 @@ type SetDisplayFeaturesOverrideParams struct { // setDeviceMetricsOverride(). // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setDisplayFeaturesOverride -// -// parameters: -// -// features -func SetDisplayFeaturesOverride(features []*DisplayFeature) *SetDisplayFeaturesOverrideParams { - return &SetDisplayFeaturesOverrideParams{ - Features: features, - } -} - -// Do executes Emulation.setDisplayFeaturesOverride against the provided context. -func (p *SetDisplayFeaturesOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetDisplayFeaturesOverride, p, nil) -} - -// ClearDisplayFeaturesOverrideParams clears the display features override -// set with either setDeviceMetricsOverride() or setDisplayFeaturesOverride() -// and starts using display features from the platform again. Does nothing if no -// override is set. -type ClearDisplayFeaturesOverrideParams struct{} +var SetDisplayFeaturesOverride = cdp.Command[SetDisplayFeaturesOverrideParams, cdp.Empty]{Method: CommandSetDisplayFeaturesOverride} // ClearDisplayFeaturesOverride clears the display features override set with // either setDeviceMetricsOverride() or setDisplayFeaturesOverride() and starts @@ -408,16 +178,10 @@ type ClearDisplayFeaturesOverrideParams struct{} // is set. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-clearDisplayFeaturesOverride -func ClearDisplayFeaturesOverride() *ClearDisplayFeaturesOverrideParams { - return &ClearDisplayFeaturesOverrideParams{} -} +var ClearDisplayFeaturesOverride = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandClearDisplayFeaturesOverride} -// Do executes Emulation.clearDisplayFeaturesOverride against the provided context. -func (p *ClearDisplayFeaturesOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClearDisplayFeaturesOverride, nil, nil) -} - -// SetScrollbarsHiddenParams [no description]. +// SetScrollbarsHiddenParams are the parameters of the command +// Emulation.setScrollbarsHidden. type SetScrollbarsHiddenParams struct { Hidden bool `json:"hidden"` // Whether scrollbars should be always hidden. } @@ -425,22 +189,10 @@ type SetScrollbarsHiddenParams struct { // SetScrollbarsHidden [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setScrollbarsHidden -// -// parameters: -// -// hidden - Whether scrollbars should be always hidden. -func SetScrollbarsHidden(hidden bool) *SetScrollbarsHiddenParams { - return &SetScrollbarsHiddenParams{ - Hidden: hidden, - } -} - -// Do executes Emulation.setScrollbarsHidden against the provided context. -func (p *SetScrollbarsHiddenParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetScrollbarsHidden, p, nil) -} +var SetScrollbarsHidden = cdp.Command[SetScrollbarsHiddenParams, cdp.Empty]{Method: CommandSetScrollbarsHidden} -// SetDocumentCookieDisabledParams [no description]. +// SetDocumentCookieDisabledParams are the parameters of the command +// Emulation.setDocumentCookieDisabled. type SetDocumentCookieDisabledParams struct { Disabled bool `json:"disabled"` // Whether document.coookie API should be disabled. } @@ -448,22 +200,10 @@ type SetDocumentCookieDisabledParams struct { // SetDocumentCookieDisabled [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setDocumentCookieDisabled -// -// parameters: -// -// disabled - Whether document.coookie API should be disabled. -func SetDocumentCookieDisabled(disabled bool) *SetDocumentCookieDisabledParams { - return &SetDocumentCookieDisabledParams{ - Disabled: disabled, - } -} - -// Do executes Emulation.setDocumentCookieDisabled against the provided context. -func (p *SetDocumentCookieDisabledParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetDocumentCookieDisabled, p, nil) -} +var SetDocumentCookieDisabled = cdp.Command[SetDocumentCookieDisabledParams, cdp.Empty]{Method: CommandSetDocumentCookieDisabled} -// SetEmitTouchEventsForMouseParams [no description]. +// SetEmitTouchEventsForMouseParams are the parameters of the command +// Emulation.setEmitTouchEventsForMouse. type SetEmitTouchEventsForMouseParams struct { Enabled bool `json:"enabled"` // Whether touch emulation based on mouse input should be enabled. Configuration SetEmitTouchEventsForMouseConfiguration `json:"configuration,omitempty,omitzero"` // Touch/gesture events configuration. Default: current platform. @@ -472,30 +212,10 @@ type SetEmitTouchEventsForMouseParams struct { // SetEmitTouchEventsForMouse [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setEmitTouchEventsForMouse -// -// parameters: -// -// enabled - Whether touch emulation based on mouse input should be enabled. -func SetEmitTouchEventsForMouse(enabled bool) *SetEmitTouchEventsForMouseParams { - return &SetEmitTouchEventsForMouseParams{ - Enabled: enabled, - } -} +var SetEmitTouchEventsForMouse = cdp.Command[SetEmitTouchEventsForMouseParams, cdp.Empty]{Method: CommandSetEmitTouchEventsForMouse} -// WithConfiguration touch/gesture events configuration. Default: current -// platform. -func (p SetEmitTouchEventsForMouseParams) WithConfiguration(configuration SetEmitTouchEventsForMouseConfiguration) *SetEmitTouchEventsForMouseParams { - p.Configuration = configuration - return &p -} - -// Do executes Emulation.setEmitTouchEventsForMouse against the provided context. -func (p *SetEmitTouchEventsForMouseParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetEmitTouchEventsForMouse, p, nil) -} - -// SetEmulatedMediaParams emulates the given media type or media feature for -// CSS media queries. +// SetEmulatedMediaParams are the parameters of the command +// Emulation.setEmulatedMedia. type SetEmulatedMediaParams struct { Media string `json:"media,omitempty,omitzero"` // Media type to emulate. Empty string disables the override. Features []*MediaFeature `json:"features,omitempty,omitzero"` // Media features to emulate. @@ -505,30 +225,10 @@ type SetEmulatedMediaParams struct { // media queries. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setEmulatedMedia -// -// parameters: -func SetEmulatedMedia() *SetEmulatedMediaParams { - return &SetEmulatedMediaParams{} -} - -// WithMedia media type to emulate. Empty string disables the override. -func (p SetEmulatedMediaParams) WithMedia(media string) *SetEmulatedMediaParams { - p.Media = media - return &p -} - -// WithFeatures media features to emulate. -func (p SetEmulatedMediaParams) WithFeatures(features []*MediaFeature) *SetEmulatedMediaParams { - p.Features = features - return &p -} - -// Do executes Emulation.setEmulatedMedia against the provided context. -func (p *SetEmulatedMediaParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetEmulatedMedia, p, nil) -} +var SetEmulatedMedia = cdp.Command[SetEmulatedMediaParams, cdp.Empty]{Method: CommandSetEmulatedMedia} -// SetEmulatedVisionDeficiencyParams emulates the given vision deficiency. +// SetEmulatedVisionDeficiencyParams are the parameters of the command +// Emulation.setEmulatedVisionDeficiency. type SetEmulatedVisionDeficiencyParams struct { Type SetEmulatedVisionDeficiencyType `json:"type"` // Vision deficiency to emulate. Order: best-effort emulations come first, followed by any physiologically accurate emulations for medically recognized color vision deficiencies. } @@ -536,22 +236,10 @@ type SetEmulatedVisionDeficiencyParams struct { // SetEmulatedVisionDeficiency emulates the given vision deficiency. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setEmulatedVisionDeficiency -// -// parameters: -// -// type - Vision deficiency to emulate. Order: best-effort emulations come first, followed by any physiologically accurate emulations for medically recognized color vision deficiencies. -func SetEmulatedVisionDeficiency(typeVal SetEmulatedVisionDeficiencyType) *SetEmulatedVisionDeficiencyParams { - return &SetEmulatedVisionDeficiencyParams{ - Type: typeVal, - } -} - -// Do executes Emulation.setEmulatedVisionDeficiency against the provided context. -func (p *SetEmulatedVisionDeficiencyParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetEmulatedVisionDeficiency, p, nil) -} +var SetEmulatedVisionDeficiency = cdp.Command[SetEmulatedVisionDeficiencyParams, cdp.Empty]{Method: CommandSetEmulatedVisionDeficiency} -// SetEmulatedOSTextScaleParams emulates the given OS text scale. +// SetEmulatedOSTextScaleParams are the parameters of the command +// Emulation.setEmulatedOSTextScale. type SetEmulatedOSTextScaleParams struct { Scale float64 `json:"scale,omitempty,omitzero"` } @@ -559,136 +247,45 @@ type SetEmulatedOSTextScaleParams struct { // SetEmulatedOSTextScale emulates the given OS text scale. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setEmulatedOSTextScale -// -// parameters: -func SetEmulatedOSTextScale() *SetEmulatedOSTextScaleParams { - return &SetEmulatedOSTextScaleParams{} -} - -// WithScale [no description]. -func (p SetEmulatedOSTextScaleParams) WithScale(scale float64) *SetEmulatedOSTextScaleParams { - p.Scale = scale - return &p -} - -// Do executes Emulation.setEmulatedOSTextScale against the provided context. -func (p *SetEmulatedOSTextScaleParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetEmulatedOSTextScale, p, nil) -} +var SetEmulatedOSTextScale = cdp.Command[SetEmulatedOSTextScaleParams, cdp.Empty]{Method: CommandSetEmulatedOSTextScale} -// SetGeolocationOverrideParams overrides the Geolocation Position or Error. -// Omitting latitude, longitude or accuracy emulates position unavailable. +// SetGeolocationOverrideParams are the parameters of the command +// Emulation.setGeolocationOverride. type SetGeolocationOverrideParams struct { - Latitude float64 `json:"latitude,omitempty,omitzero"` // Mock latitude - Longitude float64 `json:"longitude,omitempty,omitzero"` // Mock longitude - Accuracy float64 `json:"accuracy,omitempty,omitzero"` // Mock accuracy - Altitude float64 `json:"altitude,omitempty,omitzero"` // Mock altitude - AltitudeAccuracy float64 `json:"altitudeAccuracy,omitempty,omitzero"` // Mock altitudeAccuracy - Heading float64 `json:"heading,omitempty,omitzero"` // Mock heading - Speed float64 `json:"speed,omitempty,omitzero"` // Mock speed + Latitude *float64 `json:"latitude,omitempty,omitzero"` // Mock latitude + Longitude *float64 `json:"longitude,omitempty,omitzero"` // Mock longitude + Accuracy *float64 `json:"accuracy,omitempty,omitzero"` // Mock accuracy + Altitude *float64 `json:"altitude,omitempty,omitzero"` // Mock altitude + AltitudeAccuracy *float64 `json:"altitudeAccuracy,omitempty,omitzero"` // Mock altitudeAccuracy + Heading *float64 `json:"heading,omitempty,omitzero"` // Mock heading + Speed *float64 `json:"speed,omitempty,omitzero"` // Mock speed } // SetGeolocationOverride overrides the Geolocation Position or Error. // Omitting latitude, longitude or accuracy emulates position unavailable. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setGeolocationOverride -// -// parameters: -func SetGeolocationOverride() *SetGeolocationOverrideParams { - return &SetGeolocationOverrideParams{} -} - -// WithLatitude mock latitude. -func (p SetGeolocationOverrideParams) WithLatitude(latitude float64) *SetGeolocationOverrideParams { - p.Latitude = latitude - return &p -} +var SetGeolocationOverride = cdp.Command[SetGeolocationOverrideParams, cdp.Empty]{Method: CommandSetGeolocationOverride} -// WithLongitude mock longitude. -func (p SetGeolocationOverrideParams) WithLongitude(longitude float64) *SetGeolocationOverrideParams { - p.Longitude = longitude - return &p -} - -// WithAccuracy mock accuracy. -func (p SetGeolocationOverrideParams) WithAccuracy(accuracy float64) *SetGeolocationOverrideParams { - p.Accuracy = accuracy - return &p -} - -// WithAltitude mock altitude. -func (p SetGeolocationOverrideParams) WithAltitude(altitude float64) *SetGeolocationOverrideParams { - p.Altitude = altitude - return &p -} - -// WithAltitudeAccuracy mock altitudeAccuracy. -func (p SetGeolocationOverrideParams) WithAltitudeAccuracy(altitudeAccuracy float64) *SetGeolocationOverrideParams { - p.AltitudeAccuracy = altitudeAccuracy - return &p -} - -// WithHeading mock heading. -func (p SetGeolocationOverrideParams) WithHeading(heading float64) *SetGeolocationOverrideParams { - p.Heading = heading - return &p -} - -// WithSpeed mock speed. -func (p SetGeolocationOverrideParams) WithSpeed(speed float64) *SetGeolocationOverrideParams { - p.Speed = speed - return &p -} - -// Do executes Emulation.setGeolocationOverride against the provided context. -func (p *SetGeolocationOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetGeolocationOverride, p, nil) -} - -// GetOverriddenSensorInformationParams [no description]. +// GetOverriddenSensorInformationParams are the parameters of the command +// Emulation.getOverriddenSensorInformation. type GetOverriddenSensorInformationParams struct { Type SensorType `json:"type"` } -// GetOverriddenSensorInformation [no description]. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-getOverriddenSensorInformation -// -// parameters: -// -// type -func GetOverriddenSensorInformation(typeVal SensorType) *GetOverriddenSensorInformationParams { - return &GetOverriddenSensorInformationParams{ - Type: typeVal, - } -} - -// GetOverriddenSensorInformationReturns return values. -type GetOverriddenSensorInformationReturns struct { +// GetOverriddenSensorInformationResult is the result of the command +// Emulation.getOverriddenSensorInformation. +type GetOverriddenSensorInformationResult struct { RequestedSamplingFrequency float64 `json:"requestedSamplingFrequency,omitempty,omitzero"` } -// Do executes Emulation.getOverriddenSensorInformation against the provided context. -// -// returns: +// GetOverriddenSensorInformation [no description]. // -// requestedSamplingFrequency -func (p *GetOverriddenSensorInformationParams) Do(ctx context.Context) (requestedSamplingFrequency float64, err error) { - // execute - var res GetOverriddenSensorInformationReturns - err = cdp.Execute(ctx, CommandGetOverriddenSensorInformation, p, &res) - if err != nil { - return 0, err - } - - return res.RequestedSamplingFrequency, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-getOverriddenSensorInformation +var GetOverriddenSensorInformation = cdp.Command[GetOverriddenSensorInformationParams, GetOverriddenSensorInformationResult]{Method: CommandGetOverriddenSensorInformation} -// SetSensorOverrideEnabledParams overrides a platform sensor of a given -// type. If |enabled| is true, calls to Sensor.start() will use a virtual sensor -// as backend rather than fetching data from a real hardware sensor. Otherwise, -// existing virtual sensor-backend Sensor objects will fire an error event and -// new calls to Sensor.start() will attempt to use a real sensor instead. +// SetSensorOverrideEnabledParams are the parameters of the command +// Emulation.setSensorOverrideEnabled. type SetSensorOverrideEnabledParams struct { Enabled bool `json:"enabled"` Type SensorType `json:"type"` @@ -702,31 +299,10 @@ type SetSensorOverrideEnabledParams struct { // new calls to Sensor.start() will attempt to use a real sensor instead. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setSensorOverrideEnabled -// -// parameters: -// -// enabled -// type -func SetSensorOverrideEnabled(enabled bool, typeVal SensorType) *SetSensorOverrideEnabledParams { - return &SetSensorOverrideEnabledParams{ - Enabled: enabled, - Type: typeVal, - } -} - -// WithMetadata [no description]. -func (p SetSensorOverrideEnabledParams) WithMetadata(metadata *SensorMetadata) *SetSensorOverrideEnabledParams { - p.Metadata = metadata - return &p -} - -// Do executes Emulation.setSensorOverrideEnabled against the provided context. -func (p *SetSensorOverrideEnabledParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetSensorOverrideEnabled, p, nil) -} +var SetSensorOverrideEnabled = cdp.Command[SetSensorOverrideEnabledParams, cdp.Empty]{Method: CommandSetSensorOverrideEnabled} -// SetSensorOverrideReadingsParams updates the sensor readings reported by a -// sensor type previously overridden by setSensorOverrideEnabled. +// SetSensorOverrideReadingsParams are the parameters of the command +// Emulation.setSensorOverrideReadings. type SetSensorOverrideReadingsParams struct { Type SensorType `json:"type"` Reading *SensorReading `json:"reading"` @@ -736,27 +312,10 @@ type SetSensorOverrideReadingsParams struct { // type previously overridden by setSensorOverrideEnabled. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setSensorOverrideReadings -// -// parameters: -// -// type -// reading -func SetSensorOverrideReadings(typeVal SensorType, reading *SensorReading) *SetSensorOverrideReadingsParams { - return &SetSensorOverrideReadingsParams{ - Type: typeVal, - Reading: reading, - } -} +var SetSensorOverrideReadings = cdp.Command[SetSensorOverrideReadingsParams, cdp.Empty]{Method: CommandSetSensorOverrideReadings} -// Do executes Emulation.setSensorOverrideReadings against the provided context. -func (p *SetSensorOverrideReadingsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetSensorOverrideReadings, p, nil) -} - -// SetPressureSourceOverrideEnabledParams overrides a pressure source of a -// given type, as used by the Compute Pressure API, so that updates to -// PressureObserver.observe() are provided via setPressureStateOverride instead -// of being retrieved from platform-provided telemetry data. +// SetPressureSourceOverrideEnabledParams are the parameters of the command +// Emulation.setPressureSourceOverrideEnabled. type SetPressureSourceOverrideEnabledParams struct { Enabled bool `json:"enabled"` Source PressureSource `json:"source"` @@ -769,32 +328,10 @@ type SetPressureSourceOverrideEnabledParams struct { // of being retrieved from platform-provided telemetry data. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setPressureSourceOverrideEnabled -// -// parameters: -// -// enabled -// source -func SetPressureSourceOverrideEnabled(enabled bool, source PressureSource) *SetPressureSourceOverrideEnabledParams { - return &SetPressureSourceOverrideEnabledParams{ - Enabled: enabled, - Source: source, - } -} +var SetPressureSourceOverrideEnabled = cdp.Command[SetPressureSourceOverrideEnabledParams, cdp.Empty]{Method: CommandSetPressureSourceOverrideEnabled} -// WithMetadata [no description]. -func (p SetPressureSourceOverrideEnabledParams) WithMetadata(metadata *PressureMetadata) *SetPressureSourceOverrideEnabledParams { - p.Metadata = metadata - return &p -} - -// Do executes Emulation.setPressureSourceOverrideEnabled against the provided context. -func (p *SetPressureSourceOverrideEnabledParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetPressureSourceOverrideEnabled, p, nil) -} - -// SetPressureStateOverrideParams provides a given pressure state that will -// be processed and eventually be delivered to PressureObserver users. |source| -// must have been previously overridden by setPressureSourceOverrideEnabled. +// SetPressureStateOverrideParams are the parameters of the command +// Emulation.setPressureStateOverride. type SetPressureStateOverrideParams struct { Source PressureSource `json:"source"` State PressureState `json:"state"` @@ -805,24 +342,10 @@ type SetPressureStateOverrideParams struct { // must have been previously overridden by setPressureSourceOverrideEnabled. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setPressureStateOverride -// -// parameters: -// -// source -// state -func SetPressureStateOverride(source PressureSource, state PressureState) *SetPressureStateOverrideParams { - return &SetPressureStateOverrideParams{ - Source: source, - State: state, - } -} - -// Do executes Emulation.setPressureStateOverride against the provided context. -func (p *SetPressureStateOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetPressureStateOverride, p, nil) -} +var SetPressureStateOverride = cdp.Command[SetPressureStateOverrideParams, cdp.Empty]{Method: CommandSetPressureStateOverride} -// SetIdleOverrideParams overrides the Idle state. +// SetIdleOverrideParams are the parameters of the command +// Emulation.setIdleOverride. type SetIdleOverrideParams struct { IsUserActive bool `json:"isUserActive"` // Mock isUserActive IsScreenUnlocked bool `json:"isScreenUnlocked"` // Mock isScreenUnlocked @@ -831,39 +354,15 @@ type SetIdleOverrideParams struct { // SetIdleOverride overrides the Idle state. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setIdleOverride -// -// parameters: -// -// isUserActive - Mock isUserActive -// isScreenUnlocked - Mock isScreenUnlocked -func SetIdleOverride(isUserActive bool, isScreenUnlocked bool) *SetIdleOverrideParams { - return &SetIdleOverrideParams{ - IsUserActive: isUserActive, - IsScreenUnlocked: isScreenUnlocked, - } -} - -// Do executes Emulation.setIdleOverride against the provided context. -func (p *SetIdleOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetIdleOverride, p, nil) -} - -// ClearIdleOverrideParams clears Idle state overrides. -type ClearIdleOverrideParams struct{} +var SetIdleOverride = cdp.Command[SetIdleOverrideParams, cdp.Empty]{Method: CommandSetIdleOverride} // ClearIdleOverride clears Idle state overrides. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-clearIdleOverride -func ClearIdleOverride() *ClearIdleOverrideParams { - return &ClearIdleOverrideParams{} -} - -// Do executes Emulation.clearIdleOverride against the provided context. -func (p *ClearIdleOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClearIdleOverride, nil, nil) -} +var ClearIdleOverride = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandClearIdleOverride} -// SetPageScaleFactorParams sets a specified page scale factor. +// SetPageScaleFactorParams are the parameters of the command +// Emulation.setPageScaleFactor. type SetPageScaleFactorParams struct { PageScaleFactor float64 `json:"pageScaleFactor"` // Page scale factor. } @@ -871,22 +370,10 @@ type SetPageScaleFactorParams struct { // SetPageScaleFactor sets a specified page scale factor. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setPageScaleFactor -// -// parameters: -// -// pageScaleFactor - Page scale factor. -func SetPageScaleFactor(pageScaleFactor float64) *SetPageScaleFactorParams { - return &SetPageScaleFactorParams{ - PageScaleFactor: pageScaleFactor, - } -} - -// Do executes Emulation.setPageScaleFactor against the provided context. -func (p *SetPageScaleFactorParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetPageScaleFactor, p, nil) -} +var SetPageScaleFactor = cdp.Command[SetPageScaleFactorParams, cdp.Empty]{Method: CommandSetPageScaleFactor} -// SetScriptExecutionDisabledParams switches script execution in the page. +// SetScriptExecutionDisabledParams are the parameters of the command +// Emulation.setScriptExecutionDisabled. type SetScriptExecutionDisabledParams struct { Value bool `json:"value"` // Whether script execution should be disabled in the page. } @@ -894,23 +381,10 @@ type SetScriptExecutionDisabledParams struct { // SetScriptExecutionDisabled switches script execution in the page. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setScriptExecutionDisabled -// -// parameters: -// -// value - Whether script execution should be disabled in the page. -func SetScriptExecutionDisabled(value bool) *SetScriptExecutionDisabledParams { - return &SetScriptExecutionDisabledParams{ - Value: value, - } -} +var SetScriptExecutionDisabled = cdp.Command[SetScriptExecutionDisabledParams, cdp.Empty]{Method: CommandSetScriptExecutionDisabled} -// Do executes Emulation.setScriptExecutionDisabled against the provided context. -func (p *SetScriptExecutionDisabledParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetScriptExecutionDisabled, p, nil) -} - -// SetTouchEmulationEnabledParams enables touch on platforms which do not -// support them. +// SetTouchEmulationEnabledParams are the parameters of the command +// Emulation.setTouchEmulationEnabled. type SetTouchEmulationEnabledParams struct { Enabled bool `json:"enabled"` // Whether the touch event emulation should be enabled. MaxTouchPoints int64 `json:"maxTouchPoints,omitempty,omitzero"` // Maximum touch points supported. Defaults to one. @@ -920,35 +394,21 @@ type SetTouchEmulationEnabledParams struct { // them. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setTouchEmulationEnabled -// -// parameters: -// -// enabled - Whether the touch event emulation should be enabled. -func SetTouchEmulationEnabled(enabled bool) *SetTouchEmulationEnabledParams { - return &SetTouchEmulationEnabledParams{ - Enabled: enabled, - } -} - -// WithMaxTouchPoints maximum touch points supported. Defaults to one. -func (p SetTouchEmulationEnabledParams) WithMaxTouchPoints(maxTouchPoints int64) *SetTouchEmulationEnabledParams { - p.MaxTouchPoints = maxTouchPoints - return &p -} +var SetTouchEmulationEnabled = cdp.Command[SetTouchEmulationEnabledParams, cdp.Empty]{Method: CommandSetTouchEmulationEnabled} -// Do executes Emulation.setTouchEmulationEnabled against the provided context. -func (p *SetTouchEmulationEnabledParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetTouchEmulationEnabled, p, nil) +// SetVirtualTimePolicyParams are the parameters of the command +// Emulation.setVirtualTimePolicy. +type SetVirtualTimePolicyParams struct { + Policy VirtualTimePolicy `json:"policy"` + Budget *float64 `json:"budget,omitempty,omitzero"` // If set, after this many virtual milliseconds have elapsed virtual time will be paused and a virtualTimeBudgetExpired event is sent. + MaxVirtualTimeTaskStarvationCount int64 `json:"maxVirtualTimeTaskStarvationCount,omitempty,omitzero"` // If set this specifies the maximum number of tasks that can be run before virtual is forced forwards to prevent deadlock. + InitialVirtualTime cdp.TimeSinceEpoch `json:"initialVirtualTime,omitempty,omitzero"` // If set, base::Time::Now will be overridden to initially return this value. } -// SetVirtualTimePolicyParams turns on virtual time for all frames (replacing -// real-time with a synthetic time source) and sets the current virtual time -// policy. Note this supersedes any previous time budget. -type SetVirtualTimePolicyParams struct { - Policy VirtualTimePolicy `json:"policy"` - Budget float64 `json:"budget,omitempty,omitzero"` // If set, after this many virtual milliseconds have elapsed virtual time will be paused and a virtualTimeBudgetExpired event is sent. - MaxVirtualTimeTaskStarvationCount int64 `json:"maxVirtualTimeTaskStarvationCount,omitempty,omitzero"` // If set this specifies the maximum number of tasks that can be run before virtual is forced forwards to prevent deadlock. - InitialVirtualTime *cdp.TimeSinceEpoch `json:"initialVirtualTime,omitempty,omitzero"` // If set, base::Time::Now will be overridden to initially return this value. +// SetVirtualTimePolicyResult is the result of the command +// Emulation.setVirtualTimePolicy. +type SetVirtualTimePolicyResult struct { + VirtualTimeTicksBase float64 `json:"virtualTimeTicksBase,omitempty,omitzero"` // Absolute timestamp at which virtual time was first enabled (up time in milliseconds). } // SetVirtualTimePolicy turns on virtual time for all frames (replacing @@ -956,61 +416,10 @@ type SetVirtualTimePolicyParams struct { // policy. Note this supersedes any previous time budget. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setVirtualTimePolicy -// -// parameters: -// -// policy -func SetVirtualTimePolicy(policy VirtualTimePolicy) *SetVirtualTimePolicyParams { - return &SetVirtualTimePolicyParams{ - Policy: policy, - } -} +var SetVirtualTimePolicy = cdp.Command[SetVirtualTimePolicyParams, SetVirtualTimePolicyResult]{Method: CommandSetVirtualTimePolicy} -// WithBudget if set, after this many virtual milliseconds have elapsed -// virtual time will be paused and a virtualTimeBudgetExpired event is sent. -func (p SetVirtualTimePolicyParams) WithBudget(budget float64) *SetVirtualTimePolicyParams { - p.Budget = budget - return &p -} - -// WithMaxVirtualTimeTaskStarvationCount if set this specifies the maximum -// number of tasks that can be run before virtual is forced forwards to prevent -// deadlock. -func (p SetVirtualTimePolicyParams) WithMaxVirtualTimeTaskStarvationCount(maxVirtualTimeTaskStarvationCount int64) *SetVirtualTimePolicyParams { - p.MaxVirtualTimeTaskStarvationCount = maxVirtualTimeTaskStarvationCount - return &p -} - -// WithInitialVirtualTime if set, base::Time::Now will be overridden to -// initially return this value. -func (p SetVirtualTimePolicyParams) WithInitialVirtualTime(initialVirtualTime *cdp.TimeSinceEpoch) *SetVirtualTimePolicyParams { - p.InitialVirtualTime = initialVirtualTime - return &p -} - -// SetVirtualTimePolicyReturns return values. -type SetVirtualTimePolicyReturns struct { - VirtualTimeTicksBase float64 `json:"virtualTimeTicksBase,omitempty,omitzero"` // Absolute timestamp at which virtual time was first enabled (up time in milliseconds). -} - -// Do executes Emulation.setVirtualTimePolicy against the provided context. -// -// returns: -// -// virtualTimeTicksBase - Absolute timestamp at which virtual time was first enabled (up time in milliseconds). -func (p *SetVirtualTimePolicyParams) Do(ctx context.Context) (virtualTimeTicksBase float64, err error) { - // execute - var res SetVirtualTimePolicyReturns - err = cdp.Execute(ctx, CommandSetVirtualTimePolicy, p, &res) - if err != nil { - return 0, err - } - - return res.VirtualTimeTicksBase, nil -} - -// SetLocaleOverrideParams overrides default host system locale with the -// specified one. +// SetLocaleOverrideParams are the parameters of the command +// Emulation.setLocaleOverride. type SetLocaleOverrideParams struct { Locale string `json:"locale,omitempty,omitzero"` // ICU style C locale (e.g. "en_US"). If not specified or empty, disables the override and restores default host system locale. } @@ -1019,26 +428,10 @@ type SetLocaleOverrideParams struct { // one. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setLocaleOverride -// -// parameters: -func SetLocaleOverride() *SetLocaleOverrideParams { - return &SetLocaleOverrideParams{} -} +var SetLocaleOverride = cdp.Command[SetLocaleOverrideParams, cdp.Empty]{Method: CommandSetLocaleOverride} -// WithLocale iCU style C locale (e.g. "en_US"). If not specified or empty, -// disables the override and restores default host system locale. -func (p SetLocaleOverrideParams) WithLocale(locale string) *SetLocaleOverrideParams { - p.Locale = locale - return &p -} - -// Do executes Emulation.setLocaleOverride against the provided context. -func (p *SetLocaleOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetLocaleOverride, p, nil) -} - -// SetTimezoneOverrideParams overrides default host system timezone with the -// specified one. +// SetTimezoneOverrideParams are the parameters of the command +// Emulation.setTimezoneOverride. type SetTimezoneOverrideParams struct { TimezoneID string `json:"timezoneId"` // The timezone identifier. List of supported timezones: https://source.chromium.org/chromium/chromium/deps/icu.git/+/faee8bc70570192d82d2978a71e2a615788597d1:source/data/misc/metaZones.txt If empty, disables the override and restores default host system timezone. } @@ -1047,22 +440,10 @@ type SetTimezoneOverrideParams struct { // specified one. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setTimezoneOverride -// -// parameters: -// -// timezoneID - The timezone identifier. List of supported timezones: https://source.chromium.org/chromium/chromium/deps/icu.git/+/faee8bc70570192d82d2978a71e2a615788597d1:source/data/misc/metaZones.txt If empty, disables the override and restores default host system timezone. -func SetTimezoneOverride(timezoneID string) *SetTimezoneOverrideParams { - return &SetTimezoneOverrideParams{ - TimezoneID: timezoneID, - } -} - -// Do executes Emulation.setTimezoneOverride against the provided context. -func (p *SetTimezoneOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetTimezoneOverride, p, nil) -} +var SetTimezoneOverride = cdp.Command[SetTimezoneOverrideParams, cdp.Empty]{Method: CommandSetTimezoneOverride} -// SetDisabledImageTypesParams [no description]. +// SetDisabledImageTypesParams are the parameters of the command +// Emulation.setDisabledImageTypes. type SetDisabledImageTypesParams struct { ImageTypes []DisabledImageType `json:"imageTypes"` // Image types to disable. } @@ -1070,51 +451,21 @@ type SetDisabledImageTypesParams struct { // SetDisabledImageTypes [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setDisabledImageTypes -// -// parameters: -// -// imageTypes - Image types to disable. -func SetDisabledImageTypes(imageTypes []DisabledImageType) *SetDisabledImageTypesParams { - return &SetDisabledImageTypesParams{ - ImageTypes: imageTypes, - } -} - -// Do executes Emulation.setDisabledImageTypes against the provided context. -func (p *SetDisabledImageTypesParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetDisabledImageTypes, p, nil) -} +var SetDisabledImageTypes = cdp.Command[SetDisabledImageTypesParams, cdp.Empty]{Method: CommandSetDisabledImageTypes} -// SetDataSaverOverrideParams override the value of -// navigator.connection.saveData. +// SetDataSaverOverrideParams are the parameters of the command +// Emulation.setDataSaverOverride. type SetDataSaverOverrideParams struct { - DataSaverEnabled bool `json:"dataSaverEnabled"` // Override value. Omitting the parameter disables the override. + DataSaverEnabled *bool `json:"dataSaverEnabled,omitempty,omitzero"` // Override value. Omitting the parameter disables the override. } // SetDataSaverOverride override the value of navigator.connection.saveData. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setDataSaverOverride -// -// parameters: -func SetDataSaverOverride() *SetDataSaverOverrideParams { - return &SetDataSaverOverrideParams{ - DataSaverEnabled: false, - } -} +var SetDataSaverOverride = cdp.Command[SetDataSaverOverrideParams, cdp.Empty]{Method: CommandSetDataSaverOverride} -// WithDataSaverEnabled override value. Omitting the parameter disables the -// override. -func (p SetDataSaverOverrideParams) WithDataSaverEnabled(dataSaverEnabled bool) *SetDataSaverOverrideParams { - p.DataSaverEnabled = dataSaverEnabled - return &p -} - -// Do executes Emulation.setDataSaverOverride against the provided context. -func (p *SetDataSaverOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetDataSaverOverride, p, nil) -} - -// SetHardwareConcurrencyOverrideParams [no description]. +// SetHardwareConcurrencyOverrideParams are the parameters of the command +// Emulation.setHardwareConcurrencyOverride. type SetHardwareConcurrencyOverrideParams struct { HardwareConcurrency int64 `json:"hardwareConcurrency"` // Hardware concurrency to report } @@ -1122,23 +473,21 @@ type SetHardwareConcurrencyOverrideParams struct { // SetHardwareConcurrencyOverride [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setHardwareConcurrencyOverride -// -// parameters: -// -// hardwareConcurrency - Hardware concurrency to report -func SetHardwareConcurrencyOverride(hardwareConcurrency int64) *SetHardwareConcurrencyOverrideParams { - return &SetHardwareConcurrencyOverrideParams{ - HardwareConcurrency: hardwareConcurrency, - } -} +var SetHardwareConcurrencyOverride = cdp.Command[SetHardwareConcurrencyOverrideParams, cdp.Empty]{Method: CommandSetHardwareConcurrencyOverride} -// Do executes Emulation.setHardwareConcurrencyOverride against the provided context. -func (p *SetHardwareConcurrencyOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetHardwareConcurrencyOverride, p, nil) +// SetCPUPerformanceOverrideParams are the parameters of the command +// Emulation.setCPUPerformanceOverride. +type SetCPUPerformanceOverrideParams struct { + PerformanceTier SetCPUPerformanceOverridePerformanceTier `json:"performanceTier,omitempty,omitzero"` // Override value. Omitting the parameter disables the override. } -// SetUserAgentOverrideParams allows overriding user agent with the given -// string. userAgentMetadata must be set for Client Hint headers to be sent. +// SetCPUPerformanceOverride overrides the value of navigator.cpuPerformance. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setCPUPerformanceOverride +var SetCPUPerformanceOverride = cdp.Command[SetCPUPerformanceOverrideParams, cdp.Empty]{Method: CommandSetCPUPerformanceOverride} + +// SetUserAgentOverrideParams are the parameters of the command +// Emulation.setUserAgentOverride. type SetUserAgentOverrideParams struct { UserAgent string `json:"userAgent"` // User agent to use. AcceptLanguage string `json:"acceptLanguage,omitempty,omitzero"` // Browser language to emulate. @@ -1150,41 +499,10 @@ type SetUserAgentOverrideParams struct { // userAgentMetadata must be set for Client Hint headers to be sent. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setUserAgentOverride -// -// parameters: -// -// userAgent - User agent to use. -func SetUserAgentOverride(userAgent string) *SetUserAgentOverrideParams { - return &SetUserAgentOverrideParams{ - UserAgent: userAgent, - } -} +var SetUserAgentOverride = cdp.Command[SetUserAgentOverrideParams, cdp.Empty]{Method: CommandSetUserAgentOverride} -// WithAcceptLanguage browser language to emulate. -func (p SetUserAgentOverrideParams) WithAcceptLanguage(acceptLanguage string) *SetUserAgentOverrideParams { - p.AcceptLanguage = acceptLanguage - return &p -} - -// WithPlatform the platform navigator.platform should return. -func (p SetUserAgentOverrideParams) WithPlatform(platform string) *SetUserAgentOverrideParams { - p.Platform = platform - return &p -} - -// WithUserAgentMetadata to be sent in Sec-CH-UA-* headers and returned in -// navigator.userAgentData. -func (p SetUserAgentOverrideParams) WithUserAgentMetadata(userAgentMetadata *UserAgentMetadata) *SetUserAgentOverrideParams { - p.UserAgentMetadata = userAgentMetadata - return &p -} - -// Do executes Emulation.setUserAgentOverride against the provided context. -func (p *SetUserAgentOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetUserAgentOverride, p, nil) -} - -// SetAutomationOverrideParams allows overriding the automation flag. +// SetAutomationOverrideParams are the parameters of the command +// Emulation.setAutomationOverride. type SetAutomationOverrideParams struct { Enabled bool `json:"enabled"` // Whether the override should be enabled. } @@ -1192,25 +510,10 @@ type SetAutomationOverrideParams struct { // SetAutomationOverride allows overriding the automation flag. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setAutomationOverride -// -// parameters: -// -// enabled - Whether the override should be enabled. -func SetAutomationOverride(enabled bool) *SetAutomationOverrideParams { - return &SetAutomationOverrideParams{ - Enabled: enabled, - } -} +var SetAutomationOverride = cdp.Command[SetAutomationOverrideParams, cdp.Empty]{Method: CommandSetAutomationOverride} -// Do executes Emulation.setAutomationOverride against the provided context. -func (p *SetAutomationOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetAutomationOverride, p, nil) -} - -// SetSmallViewportHeightDifferenceOverrideParams allows overriding the -// difference between the small and large viewport sizes, which determine the -// value of the svh and lvh unit, respectively. Only supported for top-level -// frames. +// SetSmallViewportHeightDifferenceOverrideParams are the parameters of the +// command Emulation.setSmallViewportHeightDifferenceOverride. type SetSmallViewportHeightDifferenceOverrideParams struct { Difference int64 `json:"difference"` // This will cause an element of size 100svh to be difference pixels smaller than an element of size 100lvh. } @@ -1220,58 +523,22 @@ type SetSmallViewportHeightDifferenceOverrideParams struct { // svh and lvh unit, respectively. Only supported for top-level frames. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setSmallViewportHeightDifferenceOverride -// -// parameters: -// -// difference - This will cause an element of size 100svh to be difference pixels smaller than an element of size 100lvh. -func SetSmallViewportHeightDifferenceOverride(difference int64) *SetSmallViewportHeightDifferenceOverrideParams { - return &SetSmallViewportHeightDifferenceOverrideParams{ - Difference: difference, - } -} +var SetSmallViewportHeightDifferenceOverride = cdp.Command[SetSmallViewportHeightDifferenceOverrideParams, cdp.Empty]{Method: CommandSetSmallViewportHeightDifferenceOverride} -// Do executes Emulation.setSmallViewportHeightDifferenceOverride against the provided context. -func (p *SetSmallViewportHeightDifferenceOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetSmallViewportHeightDifferenceOverride, p, nil) +// GetScreenInfosResult is the result of the command +// Emulation.getScreenInfos. +type GetScreenInfosResult struct { + ScreenInfos []*ScreenInfo `json:"screenInfos,omitempty,omitzero"` } -// GetScreenInfosParams returns device's screen configuration. In headful -// mode, the physical screens configuration is returned, whereas in headless -// mode, a virtual headless screen configuration is provided instead. -type GetScreenInfosParams struct{} - // GetScreenInfos returns device's screen configuration. In headful mode, the // physical screens configuration is returned, whereas in headless mode, a // virtual headless screen configuration is provided instead. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-getScreenInfos -func GetScreenInfos() *GetScreenInfosParams { - return &GetScreenInfosParams{} -} - -// GetScreenInfosReturns return values. -type GetScreenInfosReturns struct { - ScreenInfos []*ScreenInfo `json:"screenInfos,omitempty,omitzero"` -} +var GetScreenInfos = cdp.Command[cdp.Empty, GetScreenInfosResult]{Method: CommandGetScreenInfos} -// Do executes Emulation.getScreenInfos against the provided context. -// -// returns: -// -// screenInfos -func (p *GetScreenInfosParams) Do(ctx context.Context) (screenInfos []*ScreenInfo, err error) { - // execute - var res GetScreenInfosReturns - err = cdp.Execute(ctx, CommandGetScreenInfos, nil, &res) - if err != nil { - return nil, err - } - - return res.ScreenInfos, nil -} - -// AddScreenParams add a new screen to the device. Only supported in headless -// mode. +// AddScreenParams are the parameters of the command Emulation.addScreen. type AddScreenParams struct { Left int64 `json:"left"` // Offset of the left edge of the screen in pixels. Top int64 `json:"top"` // Offset of the top edge of the screen in pixels. @@ -1282,206 +549,48 @@ type AddScreenParams struct { Rotation int64 `json:"rotation,omitempty,omitzero"` // Specifies the screen's rotation angle. Available values are 0, 90, 180 and 270. Default is 0. ColorDepth int64 `json:"colorDepth,omitempty,omitzero"` // Specifies the screen's color depth in bits. Default is 24. Label string `json:"label,omitempty,omitzero"` // Specifies the descriptive label for the screen. Default is none. - IsInternal bool `json:"isInternal"` // Indicates whether the screen is internal to the device or external, attached to the device. Default is false. + IsInternal *bool `json:"isInternal,omitempty,omitzero"` // Indicates whether the screen is internal to the device or external, attached to the device. Default is false. } -// AddScreen add a new screen to the device. Only supported in headless mode. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-addScreen -// -// parameters: -// -// left - Offset of the left edge of the screen in pixels. -// top - Offset of the top edge of the screen in pixels. -// width - The width of the screen in pixels. -// height - The height of the screen in pixels. -func AddScreen(left int64, top int64, width int64, height int64) *AddScreenParams { - return &AddScreenParams{ - Left: left, - Top: top, - Width: width, - Height: height, - IsInternal: false, - } -} - -// WithWorkAreaInsets specifies the screen's work area. Default is entire -// screen. -func (p AddScreenParams) WithWorkAreaInsets(workAreaInsets *WorkAreaInsets) *AddScreenParams { - p.WorkAreaInsets = workAreaInsets - return &p -} - -// WithDevicePixelRatio specifies the screen's device pixel ratio. Default is -// 1. -func (p AddScreenParams) WithDevicePixelRatio(devicePixelRatio float64) *AddScreenParams { - p.DevicePixelRatio = devicePixelRatio - return &p -} - -// WithRotation specifies the screen's rotation angle. Available values are -// 0, 90, 180 and 270. Default is 0. -func (p AddScreenParams) WithRotation(rotation int64) *AddScreenParams { - p.Rotation = rotation - return &p -} - -// WithColorDepth specifies the screen's color depth in bits. Default is 24. -func (p AddScreenParams) WithColorDepth(colorDepth int64) *AddScreenParams { - p.ColorDepth = colorDepth - return &p -} - -// WithLabel specifies the descriptive label for the screen. Default is none. -func (p AddScreenParams) WithLabel(label string) *AddScreenParams { - p.Label = label - return &p -} - -// WithIsInternal indicates whether the screen is internal to the device or -// external, attached to the device. Default is false. -func (p AddScreenParams) WithIsInternal(isInternal bool) *AddScreenParams { - p.IsInternal = isInternal - return &p -} - -// AddScreenReturns return values. -type AddScreenReturns struct { +// AddScreenResult is the result of the command Emulation.addScreen. +type AddScreenResult struct { ScreenInfo *ScreenInfo `json:"screenInfo,omitempty,omitzero"` } -// Do executes Emulation.addScreen against the provided context. -// -// returns: +// AddScreen add a new screen to the device. Only supported in headless mode. // -// screenInfo -func (p *AddScreenParams) Do(ctx context.Context) (screenInfo *ScreenInfo, err error) { - // execute - var res AddScreenReturns - err = cdp.Execute(ctx, CommandAddScreen, p, &res) - if err != nil { - return nil, err - } - - return res.ScreenInfo, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-addScreen +var AddScreen = cdp.Command[AddScreenParams, AddScreenResult]{Method: CommandAddScreen} -// UpdateScreenParams updates specified screen parameters. Only supported in -// headless mode. +// UpdateScreenParams are the parameters of the command +// Emulation.updateScreen. type UpdateScreenParams struct { ScreenID ScreenID `json:"screenId"` // Target screen identifier. - Left int64 `json:"left,omitempty,omitzero"` // Offset of the left edge of the screen in pixels. - Top int64 `json:"top,omitempty,omitzero"` // Offset of the top edge of the screen in pixels. + Left *int64 `json:"left,omitempty,omitzero"` // Offset of the left edge of the screen in pixels. + Top *int64 `json:"top,omitempty,omitzero"` // Offset of the top edge of the screen in pixels. Width int64 `json:"width,omitempty,omitzero"` // The width of the screen in pixels. Height int64 `json:"height,omitempty,omitzero"` // The height of the screen in pixels. WorkAreaInsets *WorkAreaInsets `json:"workAreaInsets,omitempty,omitzero"` // Specifies the screen's work area. DevicePixelRatio float64 `json:"devicePixelRatio,omitempty,omitzero"` // Specifies the screen's device pixel ratio. - Rotation int64 `json:"rotation,omitempty,omitzero"` // Specifies the screen's rotation angle. Available values are 0, 90, 180 and 270. + Rotation *int64 `json:"rotation,omitempty,omitzero"` // Specifies the screen's rotation angle. Available values are 0, 90, 180 and 270. ColorDepth int64 `json:"colorDepth,omitempty,omitzero"` // Specifies the screen's color depth in bits. Label string `json:"label,omitempty,omitzero"` // Specifies the descriptive label for the screen. - IsInternal bool `json:"isInternal"` // Indicates whether the screen is internal to the device or external, attached to the device. Default is false. -} - -// UpdateScreen updates specified screen parameters. Only supported in -// headless mode. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-updateScreen -// -// parameters: -// -// screenID - Target screen identifier. -func UpdateScreen(screenID ScreenID) *UpdateScreenParams { - return &UpdateScreenParams{ - ScreenID: screenID, - IsInternal: false, - } -} - -// WithLeft offset of the left edge of the screen in pixels. -func (p UpdateScreenParams) WithLeft(left int64) *UpdateScreenParams { - p.Left = left - return &p -} - -// WithTop offset of the top edge of the screen in pixels. -func (p UpdateScreenParams) WithTop(top int64) *UpdateScreenParams { - p.Top = top - return &p -} - -// WithWidth the width of the screen in pixels. -func (p UpdateScreenParams) WithWidth(width int64) *UpdateScreenParams { - p.Width = width - return &p -} - -// WithHeight the height of the screen in pixels. -func (p UpdateScreenParams) WithHeight(height int64) *UpdateScreenParams { - p.Height = height - return &p -} - -// WithWorkAreaInsets specifies the screen's work area. -func (p UpdateScreenParams) WithWorkAreaInsets(workAreaInsets *WorkAreaInsets) *UpdateScreenParams { - p.WorkAreaInsets = workAreaInsets - return &p -} - -// WithDevicePixelRatio specifies the screen's device pixel ratio. -func (p UpdateScreenParams) WithDevicePixelRatio(devicePixelRatio float64) *UpdateScreenParams { - p.DevicePixelRatio = devicePixelRatio - return &p -} - -// WithRotation specifies the screen's rotation angle. Available values are -// 0, 90, 180 and 270. -func (p UpdateScreenParams) WithRotation(rotation int64) *UpdateScreenParams { - p.Rotation = rotation - return &p + IsInternal *bool `json:"isInternal,omitempty,omitzero"` // Indicates whether the screen is internal to the device or external, attached to the device. Default is false. } -// WithColorDepth specifies the screen's color depth in bits. -func (p UpdateScreenParams) WithColorDepth(colorDepth int64) *UpdateScreenParams { - p.ColorDepth = colorDepth - return &p -} - -// WithLabel specifies the descriptive label for the screen. -func (p UpdateScreenParams) WithLabel(label string) *UpdateScreenParams { - p.Label = label - return &p -} - -// WithIsInternal indicates whether the screen is internal to the device or -// external, attached to the device. Default is false. -func (p UpdateScreenParams) WithIsInternal(isInternal bool) *UpdateScreenParams { - p.IsInternal = isInternal - return &p -} - -// UpdateScreenReturns return values. -type UpdateScreenReturns struct { +// UpdateScreenResult is the result of the command Emulation.updateScreen. +type UpdateScreenResult struct { ScreenInfo *ScreenInfo `json:"screenInfo,omitempty,omitzero"` } -// Do executes Emulation.updateScreen against the provided context. -// -// returns: +// UpdateScreen updates specified screen parameters. Only supported in +// headless mode. // -// screenInfo -func (p *UpdateScreenParams) Do(ctx context.Context) (screenInfo *ScreenInfo, err error) { - // execute - var res UpdateScreenReturns - err = cdp.Execute(ctx, CommandUpdateScreen, p, &res) - if err != nil { - return nil, err - } - - return res.ScreenInfo, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-updateScreen +var UpdateScreen = cdp.Command[UpdateScreenParams, UpdateScreenResult]{Method: CommandUpdateScreen} -// RemoveScreenParams remove screen from the device. Only supported in -// headless mode. +// RemoveScreenParams are the parameters of the command +// Emulation.removeScreen. type RemoveScreenParams struct { ScreenID ScreenID `json:"screenId"` } @@ -1490,25 +599,10 @@ type RemoveScreenParams struct { // mode. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-removeScreen -// -// parameters: -// -// screenID -func RemoveScreen(screenID ScreenID) *RemoveScreenParams { - return &RemoveScreenParams{ - ScreenID: screenID, - } -} - -// Do executes Emulation.removeScreen against the provided context. -func (p *RemoveScreenParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRemoveScreen, p, nil) -} +var RemoveScreen = cdp.Command[RemoveScreenParams, cdp.Empty]{Method: CommandRemoveScreen} -// SetPrimaryScreenParams set primary screen. Only supported in headless -// mode. Note that this changes the coordinate system origin to the top-left of -// the new primary screen, updating the bounds and work areas of all existing -// screens accordingly. +// SetPrimaryScreenParams are the parameters of the command +// Emulation.setPrimaryScreen. type SetPrimaryScreenParams struct { ScreenID ScreenID `json:"screenId"` } @@ -1519,20 +613,21 @@ type SetPrimaryScreenParams struct { // accordingly. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setPrimaryScreen +var SetPrimaryScreen = cdp.Command[SetPrimaryScreenParams, cdp.Empty]{Method: CommandSetPrimaryScreen} + +// VirtualTimeBudgetExpired notification sent after the virtual time budget +// for the current VirtualTimePolicy has run out. // -// parameters: -// -// screenID -func SetPrimaryScreen(screenID ScreenID) *SetPrimaryScreenParams { - return &SetPrimaryScreenParams{ - ScreenID: screenID, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#event-virtualTimeBudgetExpired +var VirtualTimeBudgetExpired = cdp.Event[EventVirtualTimeBudgetExpired]{Method: "Emulation.virtualTimeBudgetExpired"} -// Do executes Emulation.setPrimaryScreen against the provided context. -func (p *SetPrimaryScreenParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetPrimaryScreen, p, nil) -} +// ScreenOrientationLockChanged fired when a page calls +// screen.orientation.lock() or screen.orientation.unlock() while device +// emulation is enabled. This allows the DevTools frontend to update the +// emulated device orientation accordingly. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#event-screenOrientationLockChanged +var ScreenOrientationLockChanged = cdp.Event[EventScreenOrientationLockChanged]{Method: "Emulation.screenOrientationLockChanged"} // Command names. const ( @@ -1544,6 +639,7 @@ const ( CommandSetCPUThrottlingRate = "Emulation.setCPUThrottlingRate" CommandSetDefaultBackgroundColorOverride = "Emulation.setDefaultBackgroundColorOverride" CommandSetSafeAreaInsetsOverride = "Emulation.setSafeAreaInsetsOverride" + CommandSetVirtualKeyboardGeometryOverride = "Emulation.setVirtualKeyboardGeometryOverride" CommandSetDeviceMetricsOverride = "Emulation.setDeviceMetricsOverride" CommandSetDevicePostureOverride = "Emulation.setDevicePostureOverride" CommandClearDevicePostureOverride = "Emulation.clearDevicePostureOverride" @@ -1572,6 +668,7 @@ const ( CommandSetDisabledImageTypes = "Emulation.setDisabledImageTypes" CommandSetDataSaverOverride = "Emulation.setDataSaverOverride" CommandSetHardwareConcurrencyOverride = "Emulation.setHardwareConcurrencyOverride" + CommandSetCPUPerformanceOverride = "Emulation.setCPUPerformanceOverride" CommandSetUserAgentOverride = "Emulation.setUserAgentOverride" CommandSetAutomationOverride = "Emulation.setAutomationOverride" CommandSetSmallViewportHeightDifferenceOverride = "Emulation.setSmallViewportHeightDifferenceOverride" diff --git a/vendor/github.com/chromedp/cdproto/emulation/events.go b/vendor/github.com/chromedp/cdproto/emulation/events.go index cde6271b6..cd520b7c1 100644 --- a/vendor/github.com/chromedp/cdproto/emulation/events.go +++ b/vendor/github.com/chromedp/cdproto/emulation/events.go @@ -1,6 +1,6 @@ -package emulation +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package emulation // EventVirtualTimeBudgetExpired notification sent after the virtual time // budget for the current VirtualTimePolicy has run out. diff --git a/vendor/github.com/chromedp/cdproto/emulation/types.go b/vendor/github.com/chromedp/cdproto/emulation/types.go index 1e1c3c65b..8c85d4970 100644 --- a/vendor/github.com/chromedp/cdproto/emulation/types.go +++ b/vendor/github.com/chromedp/cdproto/emulation/types.go @@ -1,32 +1,27 @@ -package emulation - -import ( - "fmt" - "strings" -) +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package emulation // SafeAreaInsets [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#type-SafeAreaInsets type SafeAreaInsets struct { - Top int64 `json:"top,omitempty,omitzero"` // Overrides safe-area-inset-top. - TopMax int64 `json:"topMax,omitempty,omitzero"` // Overrides safe-area-max-inset-top. - Left int64 `json:"left,omitempty,omitzero"` // Overrides safe-area-inset-left. - LeftMax int64 `json:"leftMax,omitempty,omitzero"` // Overrides safe-area-max-inset-left. - Bottom int64 `json:"bottom,omitempty,omitzero"` // Overrides safe-area-inset-bottom. - BottomMax int64 `json:"bottomMax,omitempty,omitzero"` // Overrides safe-area-max-inset-bottom. - Right int64 `json:"right,omitempty,omitzero"` // Overrides safe-area-inset-right. - RightMax int64 `json:"rightMax,omitempty,omitzero"` // Overrides safe-area-max-inset-right. + Top *int64 `json:"top,omitempty,omitzero"` // Overrides safe-area-inset-top. + TopMax *int64 `json:"topMax,omitempty,omitzero"` // Overrides safe-area-max-inset-top. + Left *int64 `json:"left,omitempty,omitzero"` // Overrides safe-area-inset-left. + LeftMax *int64 `json:"leftMax,omitempty,omitzero"` // Overrides safe-area-max-inset-left. + Bottom *int64 `json:"bottom,omitempty,omitzero"` // Overrides safe-area-inset-bottom. + BottomMax *int64 `json:"bottomMax,omitempty,omitzero"` // Overrides safe-area-max-inset-bottom. + Right *int64 `json:"right,omitempty,omitzero"` // Overrides safe-area-inset-right. + RightMax *int64 `json:"rightMax,omitempty,omitzero"` // Overrides safe-area-max-inset-right. } // ScreenOrientation screen orientation. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#type-ScreenOrientation type ScreenOrientation struct { - Type OrientationType `json:"type"` // Orientation type. - Angle int64 `json:"angle"` // Orientation angle. + Type ScreenOrientationType `json:"type"` // Orientation type. + Angle int64 `json:"angle"` // Orientation angle. } // DisplayFeature [no description]. @@ -74,24 +69,6 @@ const ( VirtualTimePolicyPauseIfNetworkFetchesPending VirtualTimePolicy = "pauseIfNetworkFetchesPending" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *VirtualTimePolicy) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch VirtualTimePolicy(s) { - case VirtualTimePolicyAdvance: - *t = VirtualTimePolicyAdvance - case VirtualTimePolicyPause: - *t = VirtualTimePolicyPause - case VirtualTimePolicyPauseIfNetworkFetchesPending: - *t = VirtualTimePolicyPauseIfNetworkFetchesPending - default: - return fmt.Errorf("unknown VirtualTimePolicy value: %v", s) - } - return nil -} - // UserAgentBrandVersion used to specify User Agent Client Hints to emulate. // See https://wicg.github.io/ua-client-hints. // @@ -142,34 +119,6 @@ const ( SensorTypeRelativeOrientation SensorType = "relative-orientation" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SensorType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SensorType(s) { - case SensorTypeAbsoluteOrientation: - *t = SensorTypeAbsoluteOrientation - case SensorTypeAccelerometer: - *t = SensorTypeAccelerometer - case SensorTypeAmbientLight: - *t = SensorTypeAmbientLight - case SensorTypeGravity: - *t = SensorTypeGravity - case SensorTypeGyroscope: - *t = SensorTypeGyroscope - case SensorTypeLinearAcceleration: - *t = SensorTypeLinearAcceleration - case SensorTypeMagnetometer: - *t = SensorTypeMagnetometer - case SensorTypeRelativeOrientation: - *t = SensorTypeRelativeOrientation - default: - return fmt.Errorf("unknown SensorType value: %v", s) - } - return nil -} - // SensorMetadata [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#type-SensorMetadata @@ -229,20 +178,6 @@ const ( PressureSourceCPU PressureSource = "cpu" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *PressureSource) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch PressureSource(s) { - case PressureSourceCPU: - *t = PressureSourceCPU - default: - return fmt.Errorf("unknown PressureSource value: %v", s) - } - return nil -} - // PressureState [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#type-PressureState @@ -261,26 +196,6 @@ const ( PressureStateCritical PressureState = "critical" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *PressureState) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch PressureState(s) { - case PressureStateNominal: - *t = PressureStateNominal - case PressureStateFair: - *t = PressureStateFair - case PressureStateSerious: - *t = PressureStateSerious - case PressureStateCritical: - *t = PressureStateCritical - default: - return fmt.Errorf("unknown PressureState value: %v", s) - } - return nil -} - // PressureMetadata [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#type-PressureMetadata @@ -349,62 +264,24 @@ const ( DisabledImageTypeWebp DisabledImageType = "webp" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DisabledImageType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DisabledImageType(s) { - case DisabledImageTypeAvif: - *t = DisabledImageTypeAvif - case DisabledImageTypeJxl: - *t = DisabledImageTypeJxl - case DisabledImageTypeWebp: - *t = DisabledImageTypeWebp - default: - return fmt.Errorf("unknown DisabledImageType value: %v", s) - } - return nil -} - -// OrientationType orientation type. +// ScreenOrientationType orientation type. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#type-ScreenOrientation -type OrientationType string +type ScreenOrientationType string -// String returns the OrientationType as string value. -func (t OrientationType) String() string { +// String returns the ScreenOrientationType as string value. +func (t ScreenOrientationType) String() string { return string(t) } -// OrientationType values. +// ScreenOrientationType values. const ( - OrientationTypePortraitPrimary OrientationType = "portraitPrimary" - OrientationTypePortraitSecondary OrientationType = "portraitSecondary" - OrientationTypeLandscapePrimary OrientationType = "landscapePrimary" - OrientationTypeLandscapeSecondary OrientationType = "landscapeSecondary" + ScreenOrientationTypePortraitPrimary ScreenOrientationType = "portraitPrimary" + ScreenOrientationTypePortraitSecondary ScreenOrientationType = "portraitSecondary" + ScreenOrientationTypeLandscapePrimary ScreenOrientationType = "landscapePrimary" + ScreenOrientationTypeLandscapeSecondary ScreenOrientationType = "landscapeSecondary" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *OrientationType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch OrientationType(s) { - case OrientationTypePortraitPrimary: - *t = OrientationTypePortraitPrimary - case OrientationTypePortraitSecondary: - *t = OrientationTypePortraitSecondary - case OrientationTypeLandscapePrimary: - *t = OrientationTypeLandscapePrimary - case OrientationTypeLandscapeSecondary: - *t = OrientationTypeLandscapeSecondary - default: - return fmt.Errorf("unknown OrientationType value: %v", s) - } - return nil -} - // DisplayFeatureOrientation orientation of a display feature in relation to // screen. // @@ -422,22 +299,6 @@ const ( DisplayFeatureOrientationHorizontal DisplayFeatureOrientation = "horizontal" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DisplayFeatureOrientation) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DisplayFeatureOrientation(s) { - case DisplayFeatureOrientationVertical: - *t = DisplayFeatureOrientationVertical - case DisplayFeatureOrientationHorizontal: - *t = DisplayFeatureOrientationHorizontal - default: - return fmt.Errorf("unknown DisplayFeatureOrientation value: %v", s) - } - return nil -} - // DevicePostureType current posture of the device. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#type-DevicePosture @@ -454,22 +315,6 @@ const ( DevicePostureTypeFolded DevicePostureType = "folded" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DevicePostureType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DevicePostureType(s) { - case DevicePostureTypeContinuous: - *t = DevicePostureTypeContinuous - case DevicePostureTypeFolded: - *t = DevicePostureTypeFolded - default: - return fmt.Errorf("unknown DevicePostureType value: %v", s) - } - return nil -} - // SetDeviceMetricsOverrideScrollbarType scrollbar type. Default: default. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setDeviceMetricsOverride @@ -486,22 +331,41 @@ const ( SetDeviceMetricsOverrideScrollbarTypeDefault SetDeviceMetricsOverrideScrollbarType = "default" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SetDeviceMetricsOverrideScrollbarType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SetDeviceMetricsOverrideScrollbarType(s) { - case SetDeviceMetricsOverrideScrollbarTypeOverlay: - *t = SetDeviceMetricsOverrideScrollbarTypeOverlay - case SetDeviceMetricsOverrideScrollbarTypeDefault: - *t = SetDeviceMetricsOverrideScrollbarTypeDefault - default: - return fmt.Errorf("unknown SetDeviceMetricsOverrideScrollbarType value: %v", s) - } - return nil +// SetDeviceMetricsOverrideViewportMeta viewport meta tag behavior. Default: +// default. Note: if mobile is true, the viewport meta tag is always enabled. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setDeviceMetricsOverride +type SetDeviceMetricsOverrideViewportMeta string + +// String returns the SetDeviceMetricsOverrideViewportMeta as string value. +func (t SetDeviceMetricsOverrideViewportMeta) String() string { + return string(t) +} + +// SetDeviceMetricsOverrideViewportMeta values. +const ( + SetDeviceMetricsOverrideViewportMetaEnable SetDeviceMetricsOverrideViewportMeta = "enable" + SetDeviceMetricsOverrideViewportMetaDefault SetDeviceMetricsOverrideViewportMeta = "default" +) + +// SetDeviceMetricsOverrideTextLayoutMode text layout mode. Default: default. +// Note: if mobile is true, mobile text layout mode (text autosizing) is always +// enabled. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setDeviceMetricsOverride +type SetDeviceMetricsOverrideTextLayoutMode string + +// String returns the SetDeviceMetricsOverrideTextLayoutMode as string value. +func (t SetDeviceMetricsOverrideTextLayoutMode) String() string { + return string(t) } +// SetDeviceMetricsOverrideTextLayoutMode values. +const ( + SetDeviceMetricsOverrideTextLayoutModeMobile SetDeviceMetricsOverrideTextLayoutMode = "mobile" + SetDeviceMetricsOverrideTextLayoutModeDefault SetDeviceMetricsOverrideTextLayoutMode = "default" +) + // SetEmitTouchEventsForMouseConfiguration touch/gesture events // configuration. Default: current platform. // @@ -519,22 +383,6 @@ const ( SetEmitTouchEventsForMouseConfigurationDesktop SetEmitTouchEventsForMouseConfiguration = "desktop" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SetEmitTouchEventsForMouseConfiguration) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SetEmitTouchEventsForMouseConfiguration(s) { - case SetEmitTouchEventsForMouseConfigurationMobile: - *t = SetEmitTouchEventsForMouseConfigurationMobile - case SetEmitTouchEventsForMouseConfigurationDesktop: - *t = SetEmitTouchEventsForMouseConfigurationDesktop - default: - return fmt.Errorf("unknown SetEmitTouchEventsForMouseConfiguration value: %v", s) - } - return nil -} - // SetEmulatedVisionDeficiencyType vision deficiency to emulate. Order: // best-effort emulations come first, followed by any physiologically accurate // emulations for medically recognized color vision deficiencies. @@ -558,28 +406,22 @@ const ( SetEmulatedVisionDeficiencyTypeTritanopia SetEmulatedVisionDeficiencyType = "tritanopia" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SetEmulatedVisionDeficiencyType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SetEmulatedVisionDeficiencyType(s) { - case SetEmulatedVisionDeficiencyTypeNone: - *t = SetEmulatedVisionDeficiencyTypeNone - case SetEmulatedVisionDeficiencyTypeBlurredVision: - *t = SetEmulatedVisionDeficiencyTypeBlurredVision - case SetEmulatedVisionDeficiencyTypeReducedContrast: - *t = SetEmulatedVisionDeficiencyTypeReducedContrast - case SetEmulatedVisionDeficiencyTypeAchromatopsia: - *t = SetEmulatedVisionDeficiencyTypeAchromatopsia - case SetEmulatedVisionDeficiencyTypeDeuteranopia: - *t = SetEmulatedVisionDeficiencyTypeDeuteranopia - case SetEmulatedVisionDeficiencyTypeProtanopia: - *t = SetEmulatedVisionDeficiencyTypeProtanopia - case SetEmulatedVisionDeficiencyTypeTritanopia: - *t = SetEmulatedVisionDeficiencyTypeTritanopia - default: - return fmt.Errorf("unknown SetEmulatedVisionDeficiencyType value: %v", s) - } - return nil +// SetCPUPerformanceOverridePerformanceTier override value. Omitting the +// parameter disables the override. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setCPUPerformanceOverride +type SetCPUPerformanceOverridePerformanceTier string + +// String returns the SetCPUPerformanceOverridePerformanceTier as string value. +func (t SetCPUPerformanceOverridePerformanceTier) String() string { + return string(t) } + +// SetCPUPerformanceOverridePerformanceTier values. +const ( + SetCPUPerformanceOverridePerformanceTierUnknown SetCPUPerformanceOverridePerformanceTier = "unknown" + SetCPUPerformanceOverridePerformanceTierLow SetCPUPerformanceOverridePerformanceTier = "low" + SetCPUPerformanceOverridePerformanceTierMid SetCPUPerformanceOverridePerformanceTier = "mid" + SetCPUPerformanceOverridePerformanceTierHigh SetCPUPerformanceOverridePerformanceTier = "high" + SetCPUPerformanceOverridePerformanceTierUltra SetCPUPerformanceOverridePerformanceTier = "ultra" +) diff --git a/vendor/github.com/chromedp/cdproto/eventbreakpoints/eventbreakpoints.go b/vendor/github.com/chromedp/cdproto/eventbreakpoints/eventbreakpoints.go index ec9eff0f1..251ce8706 100644 --- a/vendor/github.com/chromedp/cdproto/eventbreakpoints/eventbreakpoints.go +++ b/vendor/github.com/chromedp/cdproto/eventbreakpoints/eventbreakpoints.go @@ -1,3 +1,5 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package eventbreakpoints provides the Chrome DevTools Protocol // commands, types, and events for the EventBreakpoints domain. // @@ -6,19 +8,15 @@ // hit, it is reported through Debugger domain, similarly to regular breakpoints // being hit. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package eventbreakpoints -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// SetInstrumentationBreakpointParams sets breakpoint on particular native -// event. +// SetInstrumentationBreakpointParams are the parameters of the command +// EventBreakpoints.setInstrumentationBreakpoint. type SetInstrumentationBreakpointParams struct { EventName string `json:"eventName"` // Instrumentation name to stop on. } @@ -26,23 +24,10 @@ type SetInstrumentationBreakpointParams struct { // SetInstrumentationBreakpoint sets breakpoint on particular native event. // // See: https://chromedevtools.github.io/devtools-protocol/tot/EventBreakpoints#method-setInstrumentationBreakpoint -// -// parameters: -// -// eventName - Instrumentation name to stop on. -func SetInstrumentationBreakpoint(eventName string) *SetInstrumentationBreakpointParams { - return &SetInstrumentationBreakpointParams{ - EventName: eventName, - } -} - -// Do executes EventBreakpoints.setInstrumentationBreakpoint against the provided context. -func (p *SetInstrumentationBreakpointParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetInstrumentationBreakpoint, p, nil) -} +var SetInstrumentationBreakpoint = cdp.Command[SetInstrumentationBreakpointParams, cdp.Empty]{Method: CommandSetInstrumentationBreakpoint} -// RemoveInstrumentationBreakpointParams removes breakpoint on particular -// native event. +// RemoveInstrumentationBreakpointParams are the parameters of the command +// EventBreakpoints.removeInstrumentationBreakpoint. type RemoveInstrumentationBreakpointParams struct { EventName string `json:"eventName"` // Instrumentation name to stop on. } @@ -51,35 +36,12 @@ type RemoveInstrumentationBreakpointParams struct { // event. // // See: https://chromedevtools.github.io/devtools-protocol/tot/EventBreakpoints#method-removeInstrumentationBreakpoint -// -// parameters: -// -// eventName - Instrumentation name to stop on. -func RemoveInstrumentationBreakpoint(eventName string) *RemoveInstrumentationBreakpointParams { - return &RemoveInstrumentationBreakpointParams{ - EventName: eventName, - } -} - -// Do executes EventBreakpoints.removeInstrumentationBreakpoint against the provided context. -func (p *RemoveInstrumentationBreakpointParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRemoveInstrumentationBreakpoint, p, nil) -} - -// DisableParams removes all breakpoints. -type DisableParams struct{} +var RemoveInstrumentationBreakpoint = cdp.Command[RemoveInstrumentationBreakpointParams, cdp.Empty]{Method: CommandRemoveInstrumentationBreakpoint} // Disable removes all breakpoints. // // See: https://chromedevtools.github.io/devtools-protocol/tot/EventBreakpoints#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes EventBreakpoints.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/extensions/extensions.go b/vendor/github.com/chromedp/cdproto/extensions/extensions.go index ea387727f..c78a45ac0 100644 --- a/vendor/github.com/chromedp/cdproto/extensions/extensions.go +++ b/vendor/github.com/chromedp/cdproto/extensions/extensions.go @@ -1,21 +1,20 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package extensions provides the Chrome DevTools Protocol // commands, types, and events for the Extensions domain. // // Defines commands and events for browser extensions. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package extensions -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" - "github.com/go-json-experiment/json/jsontext" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" ) -// TriggerActionParams runs an extension default action. +// TriggerActionParams are the parameters of the command +// Extensions.triggerAction. type TriggerActionParams struct { ID string `json:"id"` // Extension id. TargetID string `json:"targetId"` // A tab target ID to trigger the default extension action on. @@ -24,29 +23,18 @@ type TriggerActionParams struct { // TriggerAction runs an extension default action. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Extensions#method-triggerAction -// -// parameters: -// -// id - Extension id. -// targetID - A tab target ID to trigger the default extension action on. -func TriggerAction(id string, targetID string) *TriggerActionParams { - return &TriggerActionParams{ - ID: id, - TargetID: targetID, - } -} +var TriggerAction = cdp.Command[TriggerActionParams, cdp.Empty]{Method: CommandTriggerAction} -// Do executes Extensions.triggerAction against the provided context. -func (p *TriggerActionParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandTriggerAction, p, nil) +// LoadUnpackedParams are the parameters of the command +// Extensions.loadUnpacked. +type LoadUnpackedParams struct { + Path string `json:"path"` // Absolute file path. + EnableInIncognito *bool `json:"enableInIncognito,omitempty,omitzero"` // Enable the extension in incognito } -// LoadUnpackedParams installs an unpacked extension from the filesystem -// similar to --load-extension CLI flags. Returns extension ID once the -// extension has been installed. -type LoadUnpackedParams struct { - Path string `json:"path"` // Absolute file path. - EnableInIncognito bool `json:"enableInIncognito"` // Enable the extension in incognito +// LoadUnpackedResult is the result of the command Extensions.loadUnpacked. +type LoadUnpackedResult struct { + ID string `json:"id,omitempty,omitzero"` // Extension id. } // LoadUnpacked installs an unpacked extension from the filesystem similar to @@ -54,77 +42,19 @@ type LoadUnpackedParams struct { // installed. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Extensions#method-loadUnpacked -// -// parameters: -// -// path - Absolute file path. -func LoadUnpacked(path string) *LoadUnpackedParams { - return &LoadUnpackedParams{ - Path: path, - EnableInIncognito: false, - } -} - -// WithEnableInIncognito enable the extension in incognito. -func (p LoadUnpackedParams) WithEnableInIncognito(enableInIncognito bool) *LoadUnpackedParams { - p.EnableInIncognito = enableInIncognito - return &p -} - -// LoadUnpackedReturns return values. -type LoadUnpackedReturns struct { - ID string `json:"id,omitempty,omitzero"` // Extension id. -} +var LoadUnpacked = cdp.Command[LoadUnpackedParams, LoadUnpackedResult]{Method: CommandLoadUnpacked} -// Do executes Extensions.loadUnpacked against the provided context. -// -// returns: -// -// id - Extension id. -func (p *LoadUnpackedParams) Do(ctx context.Context) (id string, err error) { - // execute - var res LoadUnpackedReturns - err = cdp.Execute(ctx, CommandLoadUnpacked, p, &res) - if err != nil { - return "", err - } - - return res.ID, nil +// GetExtensionsResult is the result of the command Extensions.getExtensions. +type GetExtensionsResult struct { + Extensions []*ExtensionInfo `json:"extensions,omitempty,omitzero"` } -// GetExtensionsParams gets a list of all unpacked extensions. -type GetExtensionsParams struct{} - // GetExtensions gets a list of all unpacked extensions. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Extensions#method-getExtensions -func GetExtensions() *GetExtensionsParams { - return &GetExtensionsParams{} -} - -// GetExtensionsReturns return values. -type GetExtensionsReturns struct { - Extensions []*ExtensionInfo `json:"extensions,omitempty,omitzero"` -} - -// Do executes Extensions.getExtensions against the provided context. -// -// returns: -// -// extensions -func (p *GetExtensionsParams) Do(ctx context.Context) (extensions []*ExtensionInfo, err error) { - // execute - var res GetExtensionsReturns - err = cdp.Execute(ctx, CommandGetExtensions, nil, &res) - if err != nil { - return nil, err - } +var GetExtensions = cdp.Command[cdp.Empty, GetExtensionsResult]{Method: CommandGetExtensions} - return res.Extensions, nil -} - -// UninstallParams uninstalls an unpacked extension (others not supported) -// from the profile. +// UninstallParams are the parameters of the command Extensions.uninstall. type UninstallParams struct { ID string `json:"id"` // Extension id. } @@ -133,74 +63,30 @@ type UninstallParams struct { // profile. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Extensions#method-uninstall -// -// parameters: -// -// id - Extension id. -func Uninstall(id string) *UninstallParams { - return &UninstallParams{ - ID: id, - } -} - -// Do executes Extensions.uninstall against the provided context. -func (p *UninstallParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandUninstall, p, nil) -} +var Uninstall = cdp.Command[UninstallParams, cdp.Empty]{Method: CommandUninstall} -// GetStorageItemsParams gets data from extension storage in the given -// storageArea. If keys is specified, these are used to filter the result. +// GetStorageItemsParams are the parameters of the command +// Extensions.getStorageItems. type GetStorageItemsParams struct { ID string `json:"id"` // ID of extension. StorageArea StorageArea `json:"storageArea"` // StorageArea to retrieve data from. Keys []string `json:"keys,omitempty,omitzero"` // Keys to retrieve. } +// GetStorageItemsResult is the result of the command +// Extensions.getStorageItems. +type GetStorageItemsResult struct { + Data jsonv2.Value `json:"data,omitempty,omitzero"` +} + // GetStorageItems gets data from extension storage in the given storageArea. // If keys is specified, these are used to filter the result. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Extensions#method-getStorageItems -// -// parameters: -// -// id - ID of extension. -// storageArea - StorageArea to retrieve data from. -func GetStorageItems(id string, storageArea StorageArea) *GetStorageItemsParams { - return &GetStorageItemsParams{ - ID: id, - StorageArea: storageArea, - } -} - -// WithKeys keys to retrieve. -func (p GetStorageItemsParams) WithKeys(keys []string) *GetStorageItemsParams { - p.Keys = keys - return &p -} - -// GetStorageItemsReturns return values. -type GetStorageItemsReturns struct { - Data jsontext.Value `json:"data,omitempty,omitzero"` -} - -// Do executes Extensions.getStorageItems against the provided context. -// -// returns: -// -// data -func (p *GetStorageItemsParams) Do(ctx context.Context) (data jsontext.Value, err error) { - // execute - var res GetStorageItemsReturns - err = cdp.Execute(ctx, CommandGetStorageItems, p, &res) - if err != nil { - return nil, err - } - - return res.Data, nil -} +var GetStorageItems = cdp.Command[GetStorageItemsParams, GetStorageItemsResult]{Method: CommandGetStorageItems} -// RemoveStorageItemsParams removes keys from extension storage in the given -// storageArea. +// RemoveStorageItemsParams are the parameters of the command +// Extensions.removeStorageItems. type RemoveStorageItemsParams struct { ID string `json:"id"` // ID of extension. StorageArea StorageArea `json:"storageArea"` // StorageArea to remove data from. @@ -211,26 +97,10 @@ type RemoveStorageItemsParams struct { // storageArea. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Extensions#method-removeStorageItems -// -// parameters: -// -// id - ID of extension. -// storageArea - StorageArea to remove data from. -// keys - Keys to remove. -func RemoveStorageItems(id string, storageArea StorageArea, keys []string) *RemoveStorageItemsParams { - return &RemoveStorageItemsParams{ - ID: id, - StorageArea: storageArea, - Keys: keys, - } -} +var RemoveStorageItems = cdp.Command[RemoveStorageItemsParams, cdp.Empty]{Method: CommandRemoveStorageItems} -// Do executes Extensions.removeStorageItems against the provided context. -func (p *RemoveStorageItemsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRemoveStorageItems, p, nil) -} - -// ClearStorageItemsParams clears extension storage in the given storageArea. +// ClearStorageItemsParams are the parameters of the command +// Extensions.clearStorageItems. type ClearStorageItemsParams struct { ID string `json:"id"` // ID of extension. StorageArea StorageArea `json:"storageArea"` // StorageArea to remove data from. @@ -239,54 +109,21 @@ type ClearStorageItemsParams struct { // ClearStorageItems clears extension storage in the given storageArea. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Extensions#method-clearStorageItems -// -// parameters: -// -// id - ID of extension. -// storageArea - StorageArea to remove data from. -func ClearStorageItems(id string, storageArea StorageArea) *ClearStorageItemsParams { - return &ClearStorageItemsParams{ - ID: id, - StorageArea: storageArea, - } -} - -// Do executes Extensions.clearStorageItems against the provided context. -func (p *ClearStorageItemsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClearStorageItems, p, nil) -} +var ClearStorageItems = cdp.Command[ClearStorageItemsParams, cdp.Empty]{Method: CommandClearStorageItems} -// SetStorageItemsParams sets values in extension storage in the given -// storageArea. The provided values will be merged with existing values in the -// storage area. +// SetStorageItemsParams are the parameters of the command +// Extensions.setStorageItems. type SetStorageItemsParams struct { - ID string `json:"id"` // ID of extension. - StorageArea StorageArea `json:"storageArea"` // StorageArea to set data in. - Values jsontext.Value `json:"values"` + ID string `json:"id"` // ID of extension. + StorageArea StorageArea `json:"storageArea"` // StorageArea to set data in. + Values jsonv2.Value `json:"values"` } // SetStorageItems sets values in extension storage in the given storageArea. // The provided values will be merged with existing values in the storage area. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Extensions#method-setStorageItems -// -// parameters: -// -// id - ID of extension. -// storageArea - StorageArea to set data in. -// values - Values to set. -func SetStorageItems(id string, storageArea StorageArea, values jsontext.Value) *SetStorageItemsParams { - return &SetStorageItemsParams{ - ID: id, - StorageArea: storageArea, - Values: values, - } -} - -// Do executes Extensions.setStorageItems against the provided context. -func (p *SetStorageItemsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetStorageItems, p, nil) -} +var SetStorageItems = cdp.Command[SetStorageItemsParams, cdp.Empty]{Method: CommandSetStorageItems} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/extensions/types.go b/vendor/github.com/chromedp/cdproto/extensions/types.go index b522accda..66a1c332b 100644 --- a/vendor/github.com/chromedp/cdproto/extensions/types.go +++ b/vendor/github.com/chromedp/cdproto/extensions/types.go @@ -1,11 +1,6 @@ -package extensions - -import ( - "fmt" - "strings" -) +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package extensions // StorageArea storage areas. // @@ -25,26 +20,6 @@ const ( StorageAreaManaged StorageArea = "managed" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *StorageArea) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch StorageArea(s) { - case StorageAreaSession: - *t = StorageAreaSession - case StorageAreaLocal: - *t = StorageAreaLocal - case StorageAreaSync: - *t = StorageAreaSync - case StorageAreaManaged: - *t = StorageAreaManaged - default: - return fmt.Errorf("unknown StorageArea value: %v", s) - } - return nil -} - // ExtensionInfo detailed information about an extension. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Extensions#type-ExtensionInfo diff --git a/vendor/github.com/chromedp/cdproto/fedcm/events.go b/vendor/github.com/chromedp/cdproto/fedcm/events.go index 35d7f1687..0736e2899 100644 --- a/vendor/github.com/chromedp/cdproto/fedcm/events.go +++ b/vendor/github.com/chromedp/cdproto/fedcm/events.go @@ -1,6 +1,6 @@ -package fedcm +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package fedcm // EventDialogShown [no description]. // diff --git a/vendor/github.com/chromedp/cdproto/fedcm/fedcm.go b/vendor/github.com/chromedp/cdproto/fedcm/fedcm.go index f54667f98..335d98e4b 100644 --- a/vendor/github.com/chromedp/cdproto/fedcm/fedcm.go +++ b/vendor/github.com/chromedp/cdproto/fedcm/fedcm.go @@ -1,64 +1,33 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package fedcm provides the Chrome DevTools Protocol // commands, types, and events for the FedCm domain. // // This domain allows interacting with the FedCM dialog. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package fedcm -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// EnableParams [no description]. +// EnableParams are the parameters of the command FedCm.enable. type EnableParams struct { - DisableRejectionDelay bool `json:"disableRejectionDelay"` // Allows callers to disable the promise rejection delay that would normally happen, if this is unimportant to what's being tested. (step 4 of https://fedidcg.github.io/FedCM/#browser-api-rp-sign-in) + DisableRejectionDelay *bool `json:"disableRejectionDelay,omitempty,omitzero"` // Allows callers to disable the promise rejection delay that would normally happen, if this is unimportant to what's being tested. (step 4 of https://fedidcg.github.io/FedCM/#browser-api-rp-sign-in) } // Enable [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/FedCm#method-enable -// -// parameters: -func Enable() *EnableParams { - return &EnableParams{ - DisableRejectionDelay: false, - } -} - -// WithDisableRejectionDelay allows callers to disable the promise rejection -// delay that would normally happen, if this is unimportant to what's being -// tested. (step 4 of https://fedidcg.github.io/FedCM/#browser-api-rp-sign-in). -func (p EnableParams) WithDisableRejectionDelay(disableRejectionDelay bool) *EnableParams { - p.DisableRejectionDelay = disableRejectionDelay - return &p -} - -// Do executes FedCm.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, p, nil) -} - -// DisableParams [no description]. -type DisableParams struct{} +var Enable = cdp.Command[EnableParams, cdp.Empty]{Method: CommandEnable} // Disable [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/FedCm#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} -// Do executes FedCm.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// SelectAccountParams [no description]. +// SelectAccountParams are the parameters of the command FedCm.selectAccount. type SelectAccountParams struct { DialogID string `json:"dialogId"` AccountIndex int64 `json:"accountIndex"` @@ -67,24 +36,10 @@ type SelectAccountParams struct { // SelectAccount [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/FedCm#method-selectAccount -// -// parameters: -// -// dialogID -// accountIndex -func SelectAccount(dialogID string, accountIndex int64) *SelectAccountParams { - return &SelectAccountParams{ - DialogID: dialogID, - AccountIndex: accountIndex, - } -} +var SelectAccount = cdp.Command[SelectAccountParams, cdp.Empty]{Method: CommandSelectAccount} -// Do executes FedCm.selectAccount against the provided context. -func (p *SelectAccountParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSelectAccount, p, nil) -} - -// ClickDialogButtonParams [no description]. +// ClickDialogButtonParams are the parameters of the command +// FedCm.clickDialogButton. type ClickDialogButtonParams struct { DialogID string `json:"dialogId"` DialogButton DialogButton `json:"dialogButton"` @@ -93,24 +48,9 @@ type ClickDialogButtonParams struct { // ClickDialogButton [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/FedCm#method-clickDialogButton -// -// parameters: -// -// dialogID -// dialogButton -func ClickDialogButton(dialogID string, dialogButton DialogButton) *ClickDialogButtonParams { - return &ClickDialogButtonParams{ - DialogID: dialogID, - DialogButton: dialogButton, - } -} +var ClickDialogButton = cdp.Command[ClickDialogButtonParams, cdp.Empty]{Method: CommandClickDialogButton} -// Do executes FedCm.clickDialogButton against the provided context. -func (p *ClickDialogButtonParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClickDialogButton, p, nil) -} - -// OpenURLParams [no description]. +// OpenURLParams are the parameters of the command FedCm.openUrl. type OpenURLParams struct { DialogID string `json:"dialogId"` AccountIndex int64 `json:"accountIndex"` @@ -120,72 +60,35 @@ type OpenURLParams struct { // OpenURL [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/FedCm#method-openUrl -// -// parameters: -// -// dialogID -// accountIndex -// accountURLType -func OpenURL(dialogID string, accountIndex int64, accountURLType AccountURLType) *OpenURLParams { - return &OpenURLParams{ - DialogID: dialogID, - AccountIndex: accountIndex, - AccountURLType: accountURLType, - } -} +var OpenURL = cdp.Command[OpenURLParams, cdp.Empty]{Method: CommandOpenURL} -// Do executes FedCm.openUrl against the provided context. -func (p *OpenURLParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandOpenURL, p, nil) -} - -// DismissDialogParams [no description]. +// DismissDialogParams are the parameters of the command FedCm.dismissDialog. type DismissDialogParams struct { DialogID string `json:"dialogId"` - TriggerCooldown bool `json:"triggerCooldown"` + TriggerCooldown *bool `json:"triggerCooldown,omitempty,omitzero"` } // DismissDialog [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/FedCm#method-dismissDialog -// -// parameters: -// -// dialogID -func DismissDialog(dialogID string) *DismissDialogParams { - return &DismissDialogParams{ - DialogID: dialogID, - TriggerCooldown: false, - } -} - -// WithTriggerCooldown [no description]. -func (p DismissDialogParams) WithTriggerCooldown(triggerCooldown bool) *DismissDialogParams { - p.TriggerCooldown = triggerCooldown - return &p -} - -// Do executes FedCm.dismissDialog against the provided context. -func (p *DismissDialogParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDismissDialog, p, nil) -} - -// ResetCooldownParams resets the cooldown time, if any, to allow the next -// FedCM call to show a dialog even if one was recently dismissed by the user. -type ResetCooldownParams struct{} +var DismissDialog = cdp.Command[DismissDialogParams, cdp.Empty]{Method: CommandDismissDialog} // ResetCooldown resets the cooldown time, if any, to allow the next FedCM // call to show a dialog even if one was recently dismissed by the user. // // See: https://chromedevtools.github.io/devtools-protocol/tot/FedCm#method-resetCooldown -func ResetCooldown() *ResetCooldownParams { - return &ResetCooldownParams{} -} +var ResetCooldown = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandResetCooldown} -// Do executes FedCm.resetCooldown against the provided context. -func (p *ResetCooldownParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandResetCooldown, nil, nil) -} +// DialogShown [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/FedCm#event-dialogShown +var DialogShown = cdp.Event[EventDialogShown]{Method: "FedCm.dialogShown"} + +// DialogClosed triggered when a dialog is closed, either by user action, JS +// abort, or a command below. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/FedCm#event-dialogClosed +var DialogClosed = cdp.Event[EventDialogClosed]{Method: "FedCm.dialogClosed"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/fedcm/types.go b/vendor/github.com/chromedp/cdproto/fedcm/types.go index 639925019..dc73532df 100644 --- a/vendor/github.com/chromedp/cdproto/fedcm/types.go +++ b/vendor/github.com/chromedp/cdproto/fedcm/types.go @@ -1,11 +1,6 @@ -package fedcm - -import ( - "fmt" - "strings" -) +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package fedcm // LoginState whether this is a sign-up or sign-in action for this account, // i.e. whether this account has ever been used to sign in to this RP before. @@ -24,22 +19,6 @@ const ( LoginStateSignUp LoginState = "SignUp" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *LoginState) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch LoginState(s) { - case LoginStateSignIn: - *t = LoginStateSignIn - case LoginStateSignUp: - *t = LoginStateSignUp - default: - return fmt.Errorf("unknown LoginState value: %v", s) - } - return nil -} - // DialogType the types of FedCM dialogs. // // See: https://chromedevtools.github.io/devtools-protocol/tot/FedCm#type-DialogType @@ -58,26 +37,6 @@ const ( DialogTypeError DialogType = "Error" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DialogType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DialogType(s) { - case DialogTypeAccountChooser: - *t = DialogTypeAccountChooser - case DialogTypeAutoReauthn: - *t = DialogTypeAutoReauthn - case DialogTypeConfirmIdpLogin: - *t = DialogTypeConfirmIdpLogin - case DialogTypeError: - *t = DialogTypeError - default: - return fmt.Errorf("unknown DialogType value: %v", s) - } - return nil -} - // DialogButton the buttons on the FedCM dialog. // // See: https://chromedevtools.github.io/devtools-protocol/tot/FedCm#type-DialogButton @@ -95,24 +54,6 @@ const ( DialogButtonErrorMoreDetails DialogButton = "ErrorMoreDetails" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DialogButton) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DialogButton(s) { - case DialogButtonConfirmIdpLoginContinue: - *t = DialogButtonConfirmIdpLoginContinue - case DialogButtonErrorGotIt: - *t = DialogButtonErrorGotIt - case DialogButtonErrorMoreDetails: - *t = DialogButtonErrorMoreDetails - default: - return fmt.Errorf("unknown DialogButton value: %v", s) - } - return nil -} - // AccountURLType the URLs that each account has. // // See: https://chromedevtools.github.io/devtools-protocol/tot/FedCm#type-AccountUrlType @@ -129,22 +70,6 @@ const ( AccountURLTypePrivacyPolicy AccountURLType = "PrivacyPolicy" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *AccountURLType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch AccountURLType(s) { - case AccountURLTypeTermsOfService: - *t = AccountURLTypeTermsOfService - case AccountURLTypePrivacyPolicy: - *t = AccountURLTypePrivacyPolicy - default: - return fmt.Errorf("unknown AccountURLType value: %v", s) - } - return nil -} - // Account corresponds to IdentityRequestAccount. // // See: https://chromedevtools.github.io/devtools-protocol/tot/FedCm#type-Account diff --git a/vendor/github.com/chromedp/cdproto/fetch/events.go b/vendor/github.com/chromedp/cdproto/fetch/events.go index 5feb2a99d..11598d6ed 100644 --- a/vendor/github.com/chromedp/cdproto/fetch/events.go +++ b/vendor/github.com/chromedp/cdproto/fetch/events.go @@ -1,6 +1,6 @@ -package fetch +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package fetch import ( "github.com/chromedp/cdproto/cdp" diff --git a/vendor/github.com/chromedp/cdproto/fetch/fetch.go b/vendor/github.com/chromedp/cdproto/fetch/fetch.go index 23836b03a..9f749943f 100644 --- a/vendor/github.com/chromedp/cdproto/fetch/fetch.go +++ b/vendor/github.com/chromedp/cdproto/fetch/fetch.go @@ -1,44 +1,33 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package fetch provides the Chrome DevTools Protocol // commands, types, and events for the Fetch domain. // // A domain for letting clients substitute browser's network layer with // client code. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package fetch -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" "encoding/base64" + "fmt" "github.com/chromedp/cdproto/cdp" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" "github.com/chromedp/cdproto/io" "github.com/chromedp/cdproto/network" ) -// DisableParams disables the fetch domain. -type DisableParams struct{} - // Disable disables the fetch domain. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} -// Do executes Fetch.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// EnableParams enables issuing of requestPaused events. A request will be -// paused until client calls one of failRequest, fulfillRequest or -// continueRequest/continueWithAuth. +// EnableParams are the parameters of the command Fetch.enable. type EnableParams struct { - Patterns []*RequestPattern `json:"patterns,omitempty,omitzero"` // If specified, only requests matching any of these patterns will produce fetchRequested event and will be paused until clients response. If not set, all requests will be affected. - HandleAuthRequests bool `json:"handleAuthRequests"` // If true, authRequired events will be issued and requests will be paused expecting a call to continueWithAuth. + Patterns []*RequestPattern `json:"patterns,omitempty,omitzero"` // If specified, only requests matching any of these patterns will produce fetchRequested event and will be paused until clients response. If not set, all requests will be affected. + HandleAuthRequests *bool `json:"handleAuthRequests,omitempty,omitzero"` // If true, authRequired events will be issued and requests will be paused expecting a call to continueWithAuth. } // Enable enables issuing of requestPaused events. A request will be paused @@ -46,35 +35,9 @@ type EnableParams struct { // continueRequest/continueWithAuth. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#method-enable -// -// parameters: -func Enable() *EnableParams { - return &EnableParams{ - HandleAuthRequests: false, - } -} - -// WithPatterns if specified, only requests matching any of these patterns -// will produce fetchRequested event and will be paused until clients response. -// If not set, all requests will be affected. -func (p EnableParams) WithPatterns(patterns []*RequestPattern) *EnableParams { - p.Patterns = patterns - return &p -} +var Enable = cdp.Command[EnableParams, cdp.Empty]{Method: CommandEnable} -// WithHandleAuthRequests if true, authRequired events will be issued and -// requests will be paused expecting a call to continueWithAuth. -func (p EnableParams) WithHandleAuthRequests(handleAuthRequests bool) *EnableParams { - p.HandleAuthRequests = handleAuthRequests - return &p -} - -// Do executes Fetch.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, p, nil) -} - -// FailRequestParams causes the request to fail with specified reason. +// FailRequestParams are the parameters of the command Fetch.failRequest. type FailRequestParams struct { RequestID RequestID `json:"requestId"` // An id the client received in requestPaused event. ErrorReason network.ErrorReason `json:"errorReason"` // Causes the request to fail with the given reason. @@ -83,150 +46,43 @@ type FailRequestParams struct { // FailRequest causes the request to fail with specified reason. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#method-failRequest -// -// parameters: -// -// requestID - An id the client received in requestPaused event. -// errorReason - Causes the request to fail with the given reason. -func FailRequest(requestID RequestID, errorReason network.ErrorReason) *FailRequestParams { - return &FailRequestParams{ - RequestID: requestID, - ErrorReason: errorReason, - } -} - -// Do executes Fetch.failRequest against the provided context. -func (p *FailRequestParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandFailRequest, p, nil) -} +var FailRequest = cdp.Command[FailRequestParams, cdp.Empty]{Method: CommandFailRequest} -// FulfillRequestParams provides response to the request. +// FulfillRequestParams are the parameters of the command +// Fetch.fulfillRequest. type FulfillRequestParams struct { RequestID RequestID `json:"requestId"` // An id the client received in requestPaused event. ResponseCode int64 `json:"responseCode"` // An HTTP response code. ResponseHeaders []*HeaderEntry `json:"responseHeaders,omitempty,omitzero"` // Response headers. - BinaryResponseHeaders string `json:"binaryResponseHeaders,omitempty,omitzero"` // Alternative way of specifying response headers as a \0-separated series of name: value pairs. Prefer the above method unless you need to represent some non-UTF8 values that can't be transmitted over the protocol as text. - Body string `json:"body,omitempty,omitzero"` // A response body. If absent, original response body will be used if the request is intercepted at the response stage and empty body will be used if the request is intercepted at the request stage. + BinaryResponseHeaders []byte `json:"binaryResponseHeaders,omitempty,omitzero"` // Alternative way of specifying response headers as a \0-separated series of name: value pairs. Prefer the above method unless you need to represent some non-UTF8 values that can't be transmitted over the protocol as text. + Body []byte `json:"body,omitempty,omitzero"` // A response body. If absent, original response body will be used if the request is intercepted at the response stage and empty body will be used if the request is intercepted at the request stage. ResponsePhrase string `json:"responsePhrase,omitempty,omitzero"` // A textual representation of responseCode. If absent, a standard phrase matching responseCode is used. } // FulfillRequest provides response to the request. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#method-fulfillRequest -// -// parameters: -// -// requestID - An id the client received in requestPaused event. -// responseCode - An HTTP response code. -func FulfillRequest(requestID RequestID, responseCode int64) *FulfillRequestParams { - return &FulfillRequestParams{ - RequestID: requestID, - ResponseCode: responseCode, - } -} - -// WithResponseHeaders response headers. -func (p FulfillRequestParams) WithResponseHeaders(responseHeaders []*HeaderEntry) *FulfillRequestParams { - p.ResponseHeaders = responseHeaders - return &p -} - -// WithBinaryResponseHeaders alternative way of specifying response headers -// as a \0-separated series of name: value pairs. Prefer the above method unless -// you need to represent some non-UTF8 values that can't be transmitted over the -// protocol as text. -func (p FulfillRequestParams) WithBinaryResponseHeaders(binaryResponseHeaders string) *FulfillRequestParams { - p.BinaryResponseHeaders = binaryResponseHeaders - return &p -} - -// WithBody a response body. If absent, original response body will be used -// if the request is intercepted at the response stage and empty body will be -// used if the request is intercepted at the request stage. -func (p FulfillRequestParams) WithBody(body string) *FulfillRequestParams { - p.Body = body - return &p -} - -// WithResponsePhrase a textual representation of responseCode. If absent, a -// standard phrase matching responseCode is used. -func (p FulfillRequestParams) WithResponsePhrase(responsePhrase string) *FulfillRequestParams { - p.ResponsePhrase = responsePhrase - return &p -} - -// Do executes Fetch.fulfillRequest against the provided context. -func (p *FulfillRequestParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandFulfillRequest, p, nil) -} +var FulfillRequest = cdp.Command[FulfillRequestParams, cdp.Empty]{Method: CommandFulfillRequest} -// ContinueRequestParams continues the request, optionally modifying some of -// its parameters. +// ContinueRequestParams are the parameters of the command +// Fetch.continueRequest. type ContinueRequestParams struct { - RequestID RequestID `json:"requestId"` // An id the client received in requestPaused event. - URL string `json:"url,omitempty,omitzero"` // If set, the request url will be modified in a way that's not observable by page. - Method string `json:"method,omitempty,omitzero"` // If set, the request method is overridden. - PostData string `json:"postData,omitempty,omitzero"` // If set, overrides the post data in the request. - Headers []*HeaderEntry `json:"headers,omitempty,omitzero"` // If set, overrides the request headers. Note that the overrides do not extend to subsequent redirect hops, if a redirect happens. Another override may be applied to a different request produced by a redirect. - InterceptResponse bool `json:"interceptResponse"` // If set, overrides response interception behavior for this request. + RequestID RequestID `json:"requestId"` // An id the client received in requestPaused event. + URL string `json:"url,omitempty,omitzero"` // If set, the request url will be modified in a way that's not observable by page. + Method string `json:"method,omitempty,omitzero"` // If set, the request method is overridden. + PostData []byte `json:"postData,omitempty,omitzero"` // If set, overrides the post data in the request. + Headers []*HeaderEntry `json:"headers,omitempty,omitzero"` // If set, overrides the request headers. Note that the overrides do not extend to subsequent redirect hops, if a redirect happens. Another override may be applied to a different request produced by a redirect. + InterceptResponse *bool `json:"interceptResponse,omitempty,omitzero"` // If set, overrides response interception behavior for this request. } // ContinueRequest continues the request, optionally modifying some of its // parameters. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#method-continueRequest -// -// parameters: -// -// requestID - An id the client received in requestPaused event. -func ContinueRequest(requestID RequestID) *ContinueRequestParams { - return &ContinueRequestParams{ - RequestID: requestID, - InterceptResponse: false, - } -} - -// WithURL if set, the request url will be modified in a way that's not -// observable by page. -func (p ContinueRequestParams) WithURL(url string) *ContinueRequestParams { - p.URL = url - return &p -} - -// WithMethod if set, the request method is overridden. -func (p ContinueRequestParams) WithMethod(method string) *ContinueRequestParams { - p.Method = method - return &p -} +var ContinueRequest = cdp.Command[ContinueRequestParams, cdp.Empty]{Method: CommandContinueRequest} -// WithPostData if set, overrides the post data in the request. -func (p ContinueRequestParams) WithPostData(postData string) *ContinueRequestParams { - p.PostData = postData - return &p -} - -// WithHeaders if set, overrides the request headers. Note that the overrides -// do not extend to subsequent redirect hops, if a redirect happens. Another -// override may be applied to a different request produced by a redirect. -func (p ContinueRequestParams) WithHeaders(headers []*HeaderEntry) *ContinueRequestParams { - p.Headers = headers - return &p -} - -// WithInterceptResponse if set, overrides response interception behavior for -// this request. -func (p ContinueRequestParams) WithInterceptResponse(interceptResponse bool) *ContinueRequestParams { - p.InterceptResponse = interceptResponse - return &p -} - -// Do executes Fetch.continueRequest against the provided context. -func (p *ContinueRequestParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandContinueRequest, p, nil) -} - -// ContinueWithAuthParams continues a request supplying authChallengeResponse -// following authRequired event. +// ContinueWithAuthParams are the parameters of the command +// Fetch.continueWithAuth. type ContinueWithAuthParams struct { RequestID RequestID `json:"requestId"` // An id the client received in authRequired event. AuthChallengeResponse *AuthChallengeResponse `json:"authChallengeResponse"` // Response to with an authChallenge. @@ -236,32 +92,16 @@ type ContinueWithAuthParams struct { // following authRequired event. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#method-continueWithAuth -// -// parameters: -// -// requestID - An id the client received in authRequired event. -// authChallengeResponse - Response to with an authChallenge. -func ContinueWithAuth(requestID RequestID, authChallengeResponse *AuthChallengeResponse) *ContinueWithAuthParams { - return &ContinueWithAuthParams{ - RequestID: requestID, - AuthChallengeResponse: authChallengeResponse, - } -} - -// Do executes Fetch.continueWithAuth against the provided context. -func (p *ContinueWithAuthParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandContinueWithAuth, p, nil) -} +var ContinueWithAuth = cdp.Command[ContinueWithAuthParams, cdp.Empty]{Method: CommandContinueWithAuth} -// ContinueResponseParams continues loading of the paused response, -// optionally modifying the response headers. If either responseCode or headers -// are modified, all of them must be present. +// ContinueResponseParams are the parameters of the command +// Fetch.continueResponse. type ContinueResponseParams struct { RequestID RequestID `json:"requestId"` // An id the client received in requestPaused event. ResponseCode int64 `json:"responseCode,omitempty,omitzero"` // An HTTP response code. If absent, original response code will be used. ResponsePhrase string `json:"responsePhrase,omitempty,omitzero"` // A textual representation of responseCode. If absent, a standard phrase matching responseCode is used. ResponseHeaders []*HeaderEntry `json:"responseHeaders,omitempty,omitzero"` // Response headers. If absent, original response headers will be used. - BinaryResponseHeaders string `json:"binaryResponseHeaders,omitempty,omitzero"` // Alternative way of specifying response headers as a \0-separated series of name: value pairs. Prefer the above method unless you need to represent some non-UTF8 values that can't be transmitted over the protocol as text. + BinaryResponseHeaders []byte `json:"binaryResponseHeaders,omitempty,omitzero"` // Alternative way of specifying response headers as a \0-separated series of name: value pairs. Prefer the above method unless you need to represent some non-UTF8 values that can't be transmitted over the protocol as text. } // ContinueResponse continues loading of the paused response, optionally @@ -269,62 +109,41 @@ type ContinueResponseParams struct { // modified, all of them must be present. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#method-continueResponse -// -// parameters: -// -// requestID - An id the client received in requestPaused event. -func ContinueResponse(requestID RequestID) *ContinueResponseParams { - return &ContinueResponseParams{ - RequestID: requestID, - } -} - -// WithResponseCode an HTTP response code. If absent, original response code -// will be used. -func (p ContinueResponseParams) WithResponseCode(responseCode int64) *ContinueResponseParams { - p.ResponseCode = responseCode - return &p -} +var ContinueResponse = cdp.Command[ContinueResponseParams, cdp.Empty]{Method: CommandContinueResponse} -// WithResponsePhrase a textual representation of responseCode. If absent, a -// standard phrase matching responseCode is used. -func (p ContinueResponseParams) WithResponsePhrase(responsePhrase string) *ContinueResponseParams { - p.ResponsePhrase = responsePhrase - return &p -} - -// WithResponseHeaders response headers. If absent, original response headers -// will be used. -func (p ContinueResponseParams) WithResponseHeaders(responseHeaders []*HeaderEntry) *ContinueResponseParams { - p.ResponseHeaders = responseHeaders - return &p -} - -// WithBinaryResponseHeaders alternative way of specifying response headers -// as a \0-separated series of name: value pairs. Prefer the above method unless -// you need to represent some non-UTF8 values that can't be transmitted over the -// protocol as text. -func (p ContinueResponseParams) WithBinaryResponseHeaders(binaryResponseHeaders string) *ContinueResponseParams { - p.BinaryResponseHeaders = binaryResponseHeaders - return &p +// GetResponseBodyParams are the parameters of the command +// Fetch.getResponseBody. +type GetResponseBodyParams struct { + RequestID RequestID `json:"requestId"` // Identifier for the intercepted request to get body for. } -// Do executes Fetch.continueResponse against the provided context. -func (p *ContinueResponseParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandContinueResponse, p, nil) +// GetResponseBodyResult is the result of the command Fetch.getResponseBody. +type GetResponseBodyResult struct { + Body []byte `json:"body,omitempty,omitzero"` // Response body. + Base64encoded bool `json:"base64Encoded"` // True, if content was sent as base64. } -// GetResponseBodyParams causes the body of the response to be received from -// the server and returned as a single string. May only be issued for a request -// that is paused in the Response stage and is mutually exclusive with -// takeResponseBodyForInterceptionAsStream. Calling other methods that affect -// the request or disabling fetch domain before body is received results in an -// undefined behavior. Note that the response body is not available for -// redirects. Requests paused in the _redirect received_ state may be -// differentiated by responseCode and presence of location response header, see -// comments to requestPaused for details. -type GetResponseBodyParams struct { - RequestID RequestID `json:"requestId"` // Identifier for the intercepted request to get body for. +// UnmarshalJSON decodes the value. The browser sends body as text, or as +// base64 when r.Base64encoded, and Body holds the decoded bytes. +func (r *GetResponseBodyResult) UnmarshalJSON(buf []byte) error { + type plain GetResponseBodyResult + aux := struct { + *plain + Body string `json:"body"` + }{plain: (*plain)(r)} + if err := jsonv2.Unmarshal(buf, &aux); err != nil { + return err + } + if r.Base64encoded { + b, err := base64.StdEncoding.DecodeString(aux.Body) + if err != nil { + return fmt.Errorf("decoding body: %w", err) + } + r.Body = b + return nil + } + r.Body = []byte(aux.Body) + return nil } // GetResponseBody causes the body of the response to be received from the @@ -338,60 +157,20 @@ type GetResponseBodyParams struct { // comments to requestPaused for details. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#method-getResponseBody -// -// parameters: -// -// requestID - Identifier for the intercepted request to get body for. -func GetResponseBody(requestID RequestID) *GetResponseBodyParams { - return &GetResponseBodyParams{ - RequestID: requestID, - } -} - -// GetResponseBodyReturns return values. -type GetResponseBodyReturns struct { - Body string `json:"body,omitempty,omitzero"` // Response body. - Base64encoded bool `json:"base64Encoded"` // True, if content was sent as base64. -} - -// Do executes Fetch.getResponseBody against the provided context. -// -// returns: -// -// body - Response body. -func (p *GetResponseBodyParams) Do(ctx context.Context) (body []byte, err error) { - // execute - var res GetResponseBodyReturns - err = cdp.Execute(ctx, CommandGetResponseBody, p, &res) - if err != nil { - return nil, err - } +var GetResponseBody = cdp.Command[GetResponseBodyParams, GetResponseBodyResult]{Method: CommandGetResponseBody} - // decode - var dec []byte - if res.Base64encoded { - dec, err = base64.StdEncoding.DecodeString(res.Body) - if err != nil { - return nil, err - } - } else { - dec = []byte(res.Body) - } - return dec, nil -} - -// TakeResponseBodyAsStreamParams returns a handle to the stream representing -// the response body. The request must be paused in the HeadersReceived stage. -// Note that after this command the request can't be continued as is -- client -// either needs to cancel it or to provide the response body. The stream only -// supports sequential read, IO.read will fail if the position is specified. -// This method is mutually exclusive with getResponseBody. Calling other methods -// that affect the request or disabling fetch domain before body is received -// results in an undefined behavior. +// TakeResponseBodyAsStreamParams are the parameters of the command +// Fetch.takeResponseBodyAsStream. type TakeResponseBodyAsStreamParams struct { RequestID RequestID `json:"requestId"` } +// TakeResponseBodyAsStreamResult is the result of the command +// Fetch.takeResponseBodyAsStream. +type TakeResponseBodyAsStreamResult struct { + Stream io.StreamHandle `json:"stream,omitempty,omitzero"` +} + // TakeResponseBodyAsStream returns a handle to the stream representing the // response body. The request must be paused in the HeadersReceived stage. Note // that after this command the request can't be continued as is -- client either @@ -402,36 +181,28 @@ type TakeResponseBodyAsStreamParams struct { // undefined behavior. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#method-takeResponseBodyAsStream -// -// parameters: -// -// requestID -func TakeResponseBodyAsStream(requestID RequestID) *TakeResponseBodyAsStreamParams { - return &TakeResponseBodyAsStreamParams{ - RequestID: requestID, - } -} - -// TakeResponseBodyAsStreamReturns return values. -type TakeResponseBodyAsStreamReturns struct { - Stream io.StreamHandle `json:"stream,omitempty,omitzero"` -} - -// Do executes Fetch.takeResponseBodyAsStream against the provided context. -// -// returns: -// -// stream -func (p *TakeResponseBodyAsStreamParams) Do(ctx context.Context) (stream io.StreamHandle, err error) { - // execute - var res TakeResponseBodyAsStreamReturns - err = cdp.Execute(ctx, CommandTakeResponseBodyAsStream, p, &res) - if err != nil { - return "", err - } - - return res.Stream, nil -} +var TakeResponseBodyAsStream = cdp.Command[TakeResponseBodyAsStreamParams, TakeResponseBodyAsStreamResult]{Method: CommandTakeResponseBodyAsStream} + +// RequestPaused issued when the domain is enabled and the request URL +// matches the specified filter. The request is paused until the client responds +// with one of continueRequest, failRequest or fulfillRequest. The stage of the +// request can be determined by presence of responseErrorReason and +// responseStatusCode -- the request is at the response stage if either of these +// fields is present and in the request stage otherwise. Redirect responses and +// subsequent requests are reported similarly to regular responses and requests. +// Redirect responses may be distinguished by the value of responseStatusCode +// (which is one of 301, 302, 303, 307, 308) along with presence of the location +// header. Requests resulting from a redirect will have redirectedRequestId +// field set. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#event-requestPaused +var RequestPaused = cdp.Event[EventRequestPaused]{Method: "Fetch.requestPaused"} + +// AuthRequired issued when the domain is enabled with handleAuthRequests set +// to true. The request is paused until client responds with continueWithAuth. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#event-authRequired +var AuthRequired = cdp.Event[EventAuthRequired]{Method: "Fetch.authRequired"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/fetch/types.go b/vendor/github.com/chromedp/cdproto/fetch/types.go index fb91ec3e4..89bc34c2a 100644 --- a/vendor/github.com/chromedp/cdproto/fetch/types.go +++ b/vendor/github.com/chromedp/cdproto/fetch/types.go @@ -1,11 +1,8 @@ -package fetch +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package fetch import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/network" ) @@ -38,22 +35,6 @@ const ( RequestStageResponse RequestStage = "Response" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *RequestStage) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch RequestStage(s) { - case RequestStageRequest: - *t = RequestStageRequest - case RequestStageResponse: - *t = RequestStageResponse - default: - return fmt.Errorf("unknown RequestStage value: %v", s) - } - return nil -} - // RequestPattern [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#type-RequestPattern @@ -106,22 +87,6 @@ const ( AuthChallengeSourceProxy AuthChallengeSource = "Proxy" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *AuthChallengeSource) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch AuthChallengeSource(s) { - case AuthChallengeSourceServer: - *t = AuthChallengeSourceServer - case AuthChallengeSourceProxy: - *t = AuthChallengeSourceProxy - default: - return fmt.Errorf("unknown AuthChallengeSource value: %v", s) - } - return nil -} - // AuthChallengeResponseResponse the decision on what to do in response to // the authorization challenge. Default means deferring to the default behavior // of the net stack, which will likely either the Cancel authentication or @@ -141,21 +106,3 @@ const ( AuthChallengeResponseResponseCancelAuth AuthChallengeResponseResponse = "CancelAuth" AuthChallengeResponseResponseProvideCredentials AuthChallengeResponseResponse = "ProvideCredentials" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *AuthChallengeResponseResponse) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch AuthChallengeResponseResponse(s) { - case AuthChallengeResponseResponseDefault: - *t = AuthChallengeResponseResponseDefault - case AuthChallengeResponseResponseCancelAuth: - *t = AuthChallengeResponseResponseCancelAuth - case AuthChallengeResponseResponseProvideCredentials: - *t = AuthChallengeResponseResponseProvideCredentials - default: - return fmt.Errorf("unknown AuthChallengeResponseResponse value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/filesystem/filesystem.go b/vendor/github.com/chromedp/cdproto/filesystem/filesystem.go index b7b61bba2..b6ff58d64 100644 --- a/vendor/github.com/chromedp/cdproto/filesystem/filesystem.go +++ b/vendor/github.com/chromedp/cdproto/filesystem/filesystem.go @@ -1,55 +1,30 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package filesystem provides the Chrome DevTools Protocol // commands, types, and events for the FileSystem domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package filesystem -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// GetDirectoryParams [no description]. +// GetDirectoryParams are the parameters of the command +// FileSystem.getDirectory. type GetDirectoryParams struct { BucketFileSystemLocator *BucketFileSystemLocator `json:"bucketFileSystemLocator"` } -// GetDirectory [no description]. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/FileSystem#method-getDirectory -// -// parameters: -// -// bucketFileSystemLocator -func GetDirectory(bucketFileSystemLocator *BucketFileSystemLocator) *GetDirectoryParams { - return &GetDirectoryParams{ - BucketFileSystemLocator: bucketFileSystemLocator, - } -} - -// GetDirectoryReturns return values. -type GetDirectoryReturns struct { +// GetDirectoryResult is the result of the command FileSystem.getDirectory. +type GetDirectoryResult struct { Directory *Directory `json:"directory,omitempty,omitzero"` // Returns the directory object at the path. } -// Do executes FileSystem.getDirectory against the provided context. -// -// returns: +// GetDirectory [no description]. // -// directory - Returns the directory object at the path. -func (p *GetDirectoryParams) Do(ctx context.Context) (directory *Directory, err error) { - // execute - var res GetDirectoryReturns - err = cdp.Execute(ctx, CommandGetDirectory, p, &res) - if err != nil { - return nil, err - } - - return res.Directory, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/FileSystem#method-getDirectory +var GetDirectory = cdp.Command[GetDirectoryParams, GetDirectoryResult]{Method: CommandGetDirectory} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/filesystem/types.go b/vendor/github.com/chromedp/cdproto/filesystem/types.go index dc22e4ed8..069e7f2d6 100644 --- a/vendor/github.com/chromedp/cdproto/filesystem/types.go +++ b/vendor/github.com/chromedp/cdproto/filesystem/types.go @@ -1,6 +1,6 @@ -package filesystem +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package filesystem import ( "github.com/chromedp/cdproto/cdp" @@ -11,10 +11,10 @@ import ( // // See: https://chromedevtools.github.io/devtools-protocol/tot/FileSystem#type-File type File struct { - Name string `json:"name"` - LastModified *cdp.TimeSinceEpoch `json:"lastModified"` // Timestamp - Size float64 `json:"size"` // Size in bytes - Type string `json:"type"` + Name string `json:"name"` + LastModified cdp.TimeSinceEpoch `json:"lastModified"` // Timestamp + Size float64 `json:"size"` // Size in bytes + Type string `json:"type"` } // Directory [no description]. diff --git a/vendor/github.com/chromedp/cdproto/findinpage/findinpage.go b/vendor/github.com/chromedp/cdproto/findinpage/findinpage.go new file mode 100644 index 000000000..db8453a4a --- /dev/null +++ b/vendor/github.com/chromedp/cdproto/findinpage/findinpage.go @@ -0,0 +1,49 @@ +// Code generated by pdlgen. DO NOT EDIT. + +// Package findinpage provides the Chrome DevTools Protocol +// commands, types, and events for the FindInPage domain. +// +// This domain provides commands to trigger the "Find in page" feature. +// +// Generated by the pdlgen command. +package findinpage + +import ( + "github.com/chromedp/cdproto/cdp" +) + +// FindFirstParams are the parameters of the command FindInPage.findFirst. +type FindFirstParams struct { + Query string `json:"query"` +} + +// FindFirst forwards query to the find-in-page facility, starting a new find +// session. Where exactly the search starts from is implementation-specific. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/FindInPage#method-findFirst +var FindFirst = cdp.Command[FindFirstParams, cdp.Empty]{Method: CommandFindFirst} + +// FindNext moves to the next match for the query passed to the most recent +// findFirst() call. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/FindInPage#method-findNext +var FindNext = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandFindNext} + +// FindPrev moves to the previous match for the query passed to the most +// recent findFirst() call. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/FindInPage#method-findPrev +var FindPrev = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandFindPrev} + +// Stop ends the current find session, if any, and clears its highlighting. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/FindInPage#method-stop +var Stop = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandStop} + +// Command names. +const ( + CommandFindFirst = "FindInPage.findFirst" + CommandFindNext = "FindInPage.findNext" + CommandFindPrev = "FindInPage.findPrev" + CommandStop = "FindInPage.stop" +) diff --git a/vendor/github.com/chromedp/cdproto/headlessexperimental/headlessexperimental.go b/vendor/github.com/chromedp/cdproto/headlessexperimental/headlessexperimental.go index b30b6ae42..bb4d3f6f1 100644 --- a/vendor/github.com/chromedp/cdproto/headlessexperimental/headlessexperimental.go +++ b/vendor/github.com/chromedp/cdproto/headlessexperimental/headlessexperimental.go @@ -1,31 +1,32 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package headlessexperimental provides the Chrome DevTools Protocol // commands, types, and events for the HeadlessExperimental domain. // // This domain provides experimental commands only supported in headless // mode. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package headlessexperimental -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "encoding/base64" - "github.com/chromedp/cdproto/cdp" ) -// BeginFrameParams sends a BeginFrame to the target and returns when the -// frame was completed. Optionally captures a screenshot from the resulting -// frame. Requires that the target was created with enabled BeginFrameControl. -// Designed for use with --run-all-compositor-stages-before-draw, see also -// https://goo.gle/chrome-headless-rendering for more background. +// BeginFrameParams are the parameters of the command +// HeadlessExperimental.beginFrame. type BeginFrameParams struct { - FrameTimeTicks float64 `json:"frameTimeTicks,omitempty,omitzero"` // Timestamp of this BeginFrame in Renderer TimeTicks (milliseconds of uptime). If not set, the current time will be used. - Interval float64 `json:"interval,omitempty,omitzero"` // The interval between BeginFrames that is reported to the compositor, in milliseconds. Defaults to a 60 frames/second interval, i.e. about 16.666 milliseconds. - NoDisplayUpdates bool `json:"noDisplayUpdates"` // Whether updates should not be committed and drawn onto the display. False by default. If true, only side effects of the BeginFrame will be run, such as layout and animations, but any visual updates may not be visible on the display or in screenshots. - Screenshot *ScreenshotParams `json:"screenshot,omitempty,omitzero"` // If set, a screenshot of the frame will be captured and returned in the response. Otherwise, no screenshot will be captured. Note that capturing a screenshot can fail, for example, during renderer initialization. In such a case, no screenshot data will be returned. + FrameTimeTicks float64 `json:"frameTimeTicks,omitempty,omitzero"` // Timestamp of this BeginFrame in Renderer TimeTicks (milliseconds of uptime). If not set, the current time will be used. + Interval float64 `json:"interval,omitempty,omitzero"` // The interval between BeginFrames that is reported to the compositor, in milliseconds. Defaults to a 60 frames/second interval, i.e. about 16.666 milliseconds. + NoDisplayUpdates *bool `json:"noDisplayUpdates,omitempty,omitzero"` // Whether updates should not be committed and drawn onto the display. False by default. If true, only side effects of the BeginFrame will be run, such as layout and animations, but any visual updates may not be visible on the display or in screenshots. + Screenshot *ScreenshotParams `json:"screenshot,omitempty,omitzero"` // If set, a screenshot of the frame will be captured and returned in the response. Otherwise, no screenshot will be captured. Note that capturing a screenshot can fail, for example, during renderer initialization. In such a case, no screenshot data will be returned. +} + +// BeginFrameResult is the result of the command +// HeadlessExperimental.beginFrame. +type BeginFrameResult struct { + HasDamage bool `json:"hasDamage"` // Whether the BeginFrame resulted in damage and, thus, a new frame was committed to the display. Reported for diagnostic uses, may be removed in the future. + ScreenshotData []byte `json:"screenshotData,omitempty,omitzero"` // Base64-encoded image data of the screenshot, if one was requested and successfully taken. } // BeginFrame sends a BeginFrame to the target and returns when the frame was @@ -35,75 +36,7 @@ type BeginFrameParams struct { // https://goo.gle/chrome-headless-rendering for more background. // // See: https://chromedevtools.github.io/devtools-protocol/tot/HeadlessExperimental#method-beginFrame -// -// parameters: -func BeginFrame() *BeginFrameParams { - return &BeginFrameParams{ - NoDisplayUpdates: false, - } -} - -// WithFrameTimeTicks timestamp of this BeginFrame in Renderer TimeTicks -// (milliseconds of uptime). If not set, the current time will be used. -func (p BeginFrameParams) WithFrameTimeTicks(frameTimeTicks float64) *BeginFrameParams { - p.FrameTimeTicks = frameTimeTicks - return &p -} - -// WithInterval the interval between BeginFrames that is reported to the -// compositor, in milliseconds. Defaults to a 60 frames/second interval, i.e. -// about 16.666 milliseconds. -func (p BeginFrameParams) WithInterval(interval float64) *BeginFrameParams { - p.Interval = interval - return &p -} - -// WithNoDisplayUpdates whether updates should not be committed and drawn -// onto the display. False by default. If true, only side effects of the -// BeginFrame will be run, such as layout and animations, but any visual updates -// may not be visible on the display or in screenshots. -func (p BeginFrameParams) WithNoDisplayUpdates(noDisplayUpdates bool) *BeginFrameParams { - p.NoDisplayUpdates = noDisplayUpdates - return &p -} - -// WithScreenshot if set, a screenshot of the frame will be captured and -// returned in the response. Otherwise, no screenshot will be captured. Note -// that capturing a screenshot can fail, for example, during renderer -// initialization. In such a case, no screenshot data will be returned. -func (p BeginFrameParams) WithScreenshot(screenshot *ScreenshotParams) *BeginFrameParams { - p.Screenshot = screenshot - return &p -} - -// BeginFrameReturns return values. -type BeginFrameReturns struct { - HasDamage bool `json:"hasDamage"` // Whether the BeginFrame resulted in damage and, thus, a new frame was committed to the display. Reported for diagnostic uses, may be removed in the future. - ScreenshotData string `json:"screenshotData,omitempty,omitzero"` // Base64-encoded image data of the screenshot, if one was requested and successfully taken. -} - -// Do executes HeadlessExperimental.beginFrame against the provided context. -// -// returns: -// -// hasDamage - Whether the BeginFrame resulted in damage and, thus, a new frame was committed to the display. Reported for diagnostic uses, may be removed in the future. -// screenshotData - Base64-encoded image data of the screenshot, if one was requested and successfully taken. -func (p *BeginFrameParams) Do(ctx context.Context) (hasDamage bool, screenshotData []byte, err error) { - // execute - var res BeginFrameReturns - err = cdp.Execute(ctx, CommandBeginFrame, p, &res) - if err != nil { - return false, nil, err - } - - // decode - var dec []byte - dec, err = base64.StdEncoding.DecodeString(res.ScreenshotData) - if err != nil { - return false, nil, err - } - return res.HasDamage, dec, nil -} +var BeginFrame = cdp.Command[BeginFrameParams, BeginFrameResult]{Method: CommandBeginFrame} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/headlessexperimental/types.go b/vendor/github.com/chromedp/cdproto/headlessexperimental/types.go index 81880345d..7ba246ae1 100644 --- a/vendor/github.com/chromedp/cdproto/headlessexperimental/types.go +++ b/vendor/github.com/chromedp/cdproto/headlessexperimental/types.go @@ -1,18 +1,13 @@ -package headlessexperimental - -import ( - "fmt" - "strings" -) +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package headlessexperimental // ScreenshotParams encoding options for a screenshot. // // See: https://chromedevtools.github.io/devtools-protocol/tot/HeadlessExperimental#type-ScreenshotParams type ScreenshotParams struct { Format ScreenshotParamsFormat `json:"format,omitempty,omitzero"` // Image compression format (defaults to png). - Quality int64 `json:"quality,omitempty,omitzero"` // Compression quality from range [0..100] (jpeg and webp only). + Quality *int64 `json:"quality,omitempty,omitzero"` // Compression quality from range [0..100] (jpeg and webp only). OptimizeForSpeed bool `json:"optimizeForSpeed"` // Optimize image encoding for speed, not for resulting size (defaults to false) } @@ -32,21 +27,3 @@ const ( ScreenshotParamsFormatPng ScreenshotParamsFormat = "png" ScreenshotParamsFormatWebp ScreenshotParamsFormat = "webp" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ScreenshotParamsFormat) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ScreenshotParamsFormat(s) { - case ScreenshotParamsFormatJpeg: - *t = ScreenshotParamsFormatJpeg - case ScreenshotParamsFormatPng: - *t = ScreenshotParamsFormatPng - case ScreenshotParamsFormatWebp: - *t = ScreenshotParamsFormatWebp - default: - return fmt.Errorf("unknown ScreenshotParamsFormat value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/heapprofiler/events.go b/vendor/github.com/chromedp/cdproto/heapprofiler/events.go index c25e1ae2f..071ad1f2f 100644 --- a/vendor/github.com/chromedp/cdproto/heapprofiler/events.go +++ b/vendor/github.com/chromedp/cdproto/heapprofiler/events.go @@ -1,6 +1,6 @@ -package heapprofiler +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package heapprofiler // EventAddHeapSnapshotChunk [no description]. // diff --git a/vendor/github.com/chromedp/cdproto/heapprofiler/heapprofiler.go b/vendor/github.com/chromedp/cdproto/heapprofiler/heapprofiler.go index 52012c294..a1adeb33e 100644 --- a/vendor/github.com/chromedp/cdproto/heapprofiler/heapprofiler.go +++ b/vendor/github.com/chromedp/cdproto/heapprofiler/heapprofiler.go @@ -1,20 +1,18 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package heapprofiler provides the Chrome DevTools Protocol // commands, types, and events for the HeapProfiler domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package heapprofiler -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/runtime" ) -// AddInspectedHeapObjectParams enables console to refer to the node with -// given id via $x (see Command Line API for more details $x functions). +// AddInspectedHeapObjectParams are the parameters of the command +// HeapProfiler.addInspectedHeapObject. type AddInspectedHeapObjectParams struct { HeapObjectID HeapSnapshotObjectID `json:"heapObjectId"` // Heap snapshot object id to be accessible by means of $x command line API. } @@ -23,392 +21,158 @@ type AddInspectedHeapObjectParams struct { // via $x (see Command Line API for more details $x functions). // // See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-addInspectedHeapObject -// -// parameters: -// -// heapObjectID - Heap snapshot object id to be accessible by means of $x command line API. -func AddInspectedHeapObject(heapObjectID HeapSnapshotObjectID) *AddInspectedHeapObjectParams { - return &AddInspectedHeapObjectParams{ - HeapObjectID: heapObjectID, - } -} - -// Do executes HeapProfiler.addInspectedHeapObject against the provided context. -func (p *AddInspectedHeapObjectParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandAddInspectedHeapObject, p, nil) -} - -// CollectGarbageParams [no description]. -type CollectGarbageParams struct{} +var AddInspectedHeapObject = cdp.Command[AddInspectedHeapObjectParams, cdp.Empty]{Method: CommandAddInspectedHeapObject} // CollectGarbage [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-collectGarbage -func CollectGarbage() *CollectGarbageParams { - return &CollectGarbageParams{} -} - -// Do executes HeapProfiler.collectGarbage against the provided context. -func (p *CollectGarbageParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandCollectGarbage, nil, nil) -} - -// DisableParams [no description]. -type DisableParams struct{} +var CollectGarbage = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandCollectGarbage} // Disable [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes HeapProfiler.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// EnableParams [no description]. -type EnableParams struct{} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} // Enable [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} - -// Do executes HeapProfiler.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) -} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} -// GetHeapObjectIDParams [no description]. +// GetHeapObjectIDParams are the parameters of the command +// HeapProfiler.getHeapObjectId. type GetHeapObjectIDParams struct { ObjectID runtime.RemoteObjectID `json:"objectId"` // Identifier of the object to get heap object id for. } -// GetHeapObjectID [no description]. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-getHeapObjectId -// -// parameters: -// -// objectID - Identifier of the object to get heap object id for. -func GetHeapObjectID(objectID runtime.RemoteObjectID) *GetHeapObjectIDParams { - return &GetHeapObjectIDParams{ - ObjectID: objectID, - } -} - -// GetHeapObjectIDReturns return values. -type GetHeapObjectIDReturns struct { +// GetHeapObjectIDResult is the result of the command +// HeapProfiler.getHeapObjectId. +type GetHeapObjectIDResult struct { HeapSnapshotObjectID HeapSnapshotObjectID `json:"heapSnapshotObjectId,omitempty,omitzero"` // Id of the heap snapshot object corresponding to the passed remote object id. } -// Do executes HeapProfiler.getHeapObjectId against the provided context. -// -// returns: +// GetHeapObjectID [no description]. // -// heapSnapshotObjectID - Id of the heap snapshot object corresponding to the passed remote object id. -func (p *GetHeapObjectIDParams) Do(ctx context.Context) (heapSnapshotObjectID HeapSnapshotObjectID, err error) { - // execute - var res GetHeapObjectIDReturns - err = cdp.Execute(ctx, CommandGetHeapObjectID, p, &res) - if err != nil { - return "", err - } - - return res.HeapSnapshotObjectID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-getHeapObjectId +var GetHeapObjectID = cdp.Command[GetHeapObjectIDParams, GetHeapObjectIDResult]{Method: CommandGetHeapObjectID} -// GetObjectByHeapObjectIDParams [no description]. +// GetObjectByHeapObjectIDParams are the parameters of the command +// HeapProfiler.getObjectByHeapObjectId. type GetObjectByHeapObjectIDParams struct { ObjectID HeapSnapshotObjectID `json:"objectId"` ObjectGroup string `json:"objectGroup,omitempty,omitzero"` // Symbolic group name that can be used to release multiple objects. } -// GetObjectByHeapObjectID [no description]. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-getObjectByHeapObjectId -// -// parameters: -// -// objectID -func GetObjectByHeapObjectID(objectID HeapSnapshotObjectID) *GetObjectByHeapObjectIDParams { - return &GetObjectByHeapObjectIDParams{ - ObjectID: objectID, - } -} - -// WithObjectGroup symbolic group name that can be used to release multiple -// objects. -func (p GetObjectByHeapObjectIDParams) WithObjectGroup(objectGroup string) *GetObjectByHeapObjectIDParams { - p.ObjectGroup = objectGroup - return &p -} - -// GetObjectByHeapObjectIDReturns return values. -type GetObjectByHeapObjectIDReturns struct { +// GetObjectByHeapObjectIDResult is the result of the command +// HeapProfiler.getObjectByHeapObjectId. +type GetObjectByHeapObjectIDResult struct { Result *runtime.RemoteObject `json:"result,omitempty,omitzero"` // Evaluation result. } -// Do executes HeapProfiler.getObjectByHeapObjectId against the provided context. -// -// returns: +// GetObjectByHeapObjectID [no description]. // -// result - Evaluation result. -func (p *GetObjectByHeapObjectIDParams) Do(ctx context.Context) (result *runtime.RemoteObject, err error) { - // execute - var res GetObjectByHeapObjectIDReturns - err = cdp.Execute(ctx, CommandGetObjectByHeapObjectID, p, &res) - if err != nil { - return nil, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-getObjectByHeapObjectId +var GetObjectByHeapObjectID = cdp.Command[GetObjectByHeapObjectIDParams, GetObjectByHeapObjectIDResult]{Method: CommandGetObjectByHeapObjectID} - return res.Result, nil +// GetSamplingProfileResult is the result of the command +// HeapProfiler.getSamplingProfile. +type GetSamplingProfileResult struct { + Profile *SamplingHeapProfile `json:"profile,omitempty,omitzero"` // Return the sampling profile being collected. } -// GetSamplingProfileParams [no description]. -type GetSamplingProfileParams struct{} - // GetSamplingProfile [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-getSamplingProfile -func GetSamplingProfile() *GetSamplingProfileParams { - return &GetSamplingProfileParams{} -} - -// GetSamplingProfileReturns return values. -type GetSamplingProfileReturns struct { - Profile *SamplingHeapProfile `json:"profile,omitempty,omitzero"` // Return the sampling profile being collected. -} - -// Do executes HeapProfiler.getSamplingProfile against the provided context. -// -// returns: -// -// profile - Return the sampling profile being collected. -func (p *GetSamplingProfileParams) Do(ctx context.Context) (profile *SamplingHeapProfile, err error) { - // execute - var res GetSamplingProfileReturns - err = cdp.Execute(ctx, CommandGetSamplingProfile, nil, &res) - if err != nil { - return nil, err - } - - return res.Profile, nil -} +var GetSamplingProfile = cdp.Command[cdp.Empty, GetSamplingProfileResult]{Method: CommandGetSamplingProfile} -// StartSamplingParams [no description]. +// StartSamplingParams are the parameters of the command +// HeapProfiler.startSampling. type StartSamplingParams struct { - SamplingInterval float64 `json:"samplingInterval,omitempty,omitzero"` // Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. - StackDepth float64 `json:"stackDepth,omitempty,omitzero"` // Maximum stack depth. The default value is 128. - IncludeObjectsCollectedByMajorGC bool `json:"includeObjectsCollectedByMajorGC"` // By default, the sampling heap profiler reports only objects which are still alive when the profile is returned via getSamplingProfile or stopSampling, which is useful for determining what functions contribute the most to steady-state memory usage. This flag instructs the sampling heap profiler to also include information about objects discarded by major GC, which will show which functions cause large temporary memory usage or long GC pauses. - IncludeObjectsCollectedByMinorGC bool `json:"includeObjectsCollectedByMinorGC"` // By default, the sampling heap profiler reports only objects which are still alive when the profile is returned via getSamplingProfile or stopSampling, which is useful for determining what functions contribute the most to steady-state memory usage. This flag instructs the sampling heap profiler to also include information about objects discarded by minor GC, which is useful when tuning a latency-sensitive application for minimal GC activity. + SamplingInterval float64 `json:"samplingInterval,omitempty,omitzero"` // Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + StackDepth float64 `json:"stackDepth,omitempty,omitzero"` // Maximum stack depth. The default value is 128. + IncludeObjectsCollectedByMajorGC *bool `json:"includeObjectsCollectedByMajorGC,omitempty,omitzero"` // By default, the sampling heap profiler reports only objects which are still alive when the profile is returned via getSamplingProfile or stopSampling, which is useful for determining what functions contribute the most to steady-state memory usage. This flag instructs the sampling heap profiler to also include information about objects discarded by major GC, which will show which functions cause large temporary memory usage or long GC pauses. + IncludeObjectsCollectedByMinorGC *bool `json:"includeObjectsCollectedByMinorGC,omitempty,omitzero"` // By default, the sampling heap profiler reports only objects which are still alive when the profile is returned via getSamplingProfile or stopSampling, which is useful for determining what functions contribute the most to steady-state memory usage. This flag instructs the sampling heap profiler to also include information about objects discarded by minor GC, which is useful when tuning a latency-sensitive application for minimal GC activity. } // StartSampling [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-startSampling -// -// parameters: -func StartSampling() *StartSamplingParams { - return &StartSamplingParams{ - IncludeObjectsCollectedByMajorGC: false, - IncludeObjectsCollectedByMinorGC: false, - } -} - -// WithSamplingInterval average sample interval in bytes. Poisson -// distribution is used for the intervals. The default value is 32768 bytes. -func (p StartSamplingParams) WithSamplingInterval(samplingInterval float64) *StartSamplingParams { - p.SamplingInterval = samplingInterval - return &p -} - -// WithStackDepth maximum stack depth. The default value is 128. -func (p StartSamplingParams) WithStackDepth(stackDepth float64) *StartSamplingParams { - p.StackDepth = stackDepth - return &p -} - -// WithIncludeObjectsCollectedByMajorGC by default, the sampling heap -// profiler reports only objects which are still alive when the profile is -// returned via getSamplingProfile or stopSampling, which is useful for -// determining what functions contribute the most to steady-state memory usage. -// This flag instructs the sampling heap profiler to also include information -// about objects discarded by major GC, which will show which functions cause -// large temporary memory usage or long GC pauses. -func (p StartSamplingParams) WithIncludeObjectsCollectedByMajorGC(includeObjectsCollectedByMajorGC bool) *StartSamplingParams { - p.IncludeObjectsCollectedByMajorGC = includeObjectsCollectedByMajorGC - return &p -} - -// WithIncludeObjectsCollectedByMinorGC by default, the sampling heap -// profiler reports only objects which are still alive when the profile is -// returned via getSamplingProfile or stopSampling, which is useful for -// determining what functions contribute the most to steady-state memory usage. -// This flag instructs the sampling heap profiler to also include information -// about objects discarded by minor GC, which is useful when tuning a -// latency-sensitive application for minimal GC activity. -func (p StartSamplingParams) WithIncludeObjectsCollectedByMinorGC(includeObjectsCollectedByMinorGC bool) *StartSamplingParams { - p.IncludeObjectsCollectedByMinorGC = includeObjectsCollectedByMinorGC - return &p -} - -// Do executes HeapProfiler.startSampling against the provided context. -func (p *StartSamplingParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStartSampling, p, nil) -} +var StartSampling = cdp.Command[StartSamplingParams, cdp.Empty]{Method: CommandStartSampling} -// StartTrackingHeapObjectsParams [no description]. +// StartTrackingHeapObjectsParams are the parameters of the command +// HeapProfiler.startTrackingHeapObjects. type StartTrackingHeapObjectsParams struct { - TrackAllocations bool `json:"trackAllocations"` + TrackAllocations *bool `json:"trackAllocations,omitempty,omitzero"` } // StartTrackingHeapObjects [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-startTrackingHeapObjects -// -// parameters: -func StartTrackingHeapObjects() *StartTrackingHeapObjectsParams { - return &StartTrackingHeapObjectsParams{ - TrackAllocations: false, - } -} - -// WithTrackAllocations [no description]. -func (p StartTrackingHeapObjectsParams) WithTrackAllocations(trackAllocations bool) *StartTrackingHeapObjectsParams { - p.TrackAllocations = trackAllocations - return &p -} +var StartTrackingHeapObjects = cdp.Command[StartTrackingHeapObjectsParams, cdp.Empty]{Method: CommandStartTrackingHeapObjects} -// Do executes HeapProfiler.startTrackingHeapObjects against the provided context. -func (p *StartTrackingHeapObjectsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStartTrackingHeapObjects, p, nil) +// StopSamplingResult is the result of the command HeapProfiler.stopSampling. +type StopSamplingResult struct { + Profile *SamplingHeapProfile `json:"profile,omitempty,omitzero"` // Recorded sampling heap profile. } -// StopSamplingParams [no description]. -type StopSamplingParams struct{} - // StopSampling [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-stopSampling -func StopSampling() *StopSamplingParams { - return &StopSamplingParams{} -} - -// StopSamplingReturns return values. -type StopSamplingReturns struct { - Profile *SamplingHeapProfile `json:"profile,omitempty,omitzero"` // Recorded sampling heap profile. -} +var StopSampling = cdp.Command[cdp.Empty, StopSamplingResult]{Method: CommandStopSampling} -// Do executes HeapProfiler.stopSampling against the provided context. -// -// returns: -// -// profile - Recorded sampling heap profile. -func (p *StopSamplingParams) Do(ctx context.Context) (profile *SamplingHeapProfile, err error) { - // execute - var res StopSamplingReturns - err = cdp.Execute(ctx, CommandStopSampling, nil, &res) - if err != nil { - return nil, err - } - - return res.Profile, nil -} - -// StopTrackingHeapObjectsParams [no description]. +// StopTrackingHeapObjectsParams are the parameters of the command +// HeapProfiler.stopTrackingHeapObjects. type StopTrackingHeapObjectsParams struct { - ReportProgress bool `json:"reportProgress"` // If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. - CaptureNumericValue bool `json:"captureNumericValue"` // If true, numerical values are included in the snapshot - ExposeInternals bool `json:"exposeInternals"` // If true, exposes internals of the snapshot. + ReportProgress *bool `json:"reportProgress,omitempty,omitzero"` // If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + CaptureNumericValue *bool `json:"captureNumericValue,omitempty,omitzero"` // If true, numerical values are included in the snapshot + ExposeInternals *bool `json:"exposeInternals,omitempty,omitzero"` // If true, exposes internals of the snapshot. } // StopTrackingHeapObjects [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-stopTrackingHeapObjects -// -// parameters: -func StopTrackingHeapObjects() *StopTrackingHeapObjectsParams { - return &StopTrackingHeapObjectsParams{ - ReportProgress: false, - CaptureNumericValue: false, - ExposeInternals: false, - } -} - -// WithReportProgress if true 'reportHeapSnapshotProgress' events will be -// generated while snapshot is being taken when the tracking is stopped. -func (p StopTrackingHeapObjectsParams) WithReportProgress(reportProgress bool) *StopTrackingHeapObjectsParams { - p.ReportProgress = reportProgress - return &p -} - -// WithCaptureNumericValue if true, numerical values are included in the -// snapshot. -func (p StopTrackingHeapObjectsParams) WithCaptureNumericValue(captureNumericValue bool) *StopTrackingHeapObjectsParams { - p.CaptureNumericValue = captureNumericValue - return &p -} - -// WithExposeInternals if true, exposes internals of the snapshot. -func (p StopTrackingHeapObjectsParams) WithExposeInternals(exposeInternals bool) *StopTrackingHeapObjectsParams { - p.ExposeInternals = exposeInternals - return &p -} +var StopTrackingHeapObjects = cdp.Command[StopTrackingHeapObjectsParams, cdp.Empty]{Method: CommandStopTrackingHeapObjects} -// Do executes HeapProfiler.stopTrackingHeapObjects against the provided context. -func (p *StopTrackingHeapObjectsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStopTrackingHeapObjects, p, nil) -} - -// TakeHeapSnapshotParams [no description]. +// TakeHeapSnapshotParams are the parameters of the command +// HeapProfiler.takeHeapSnapshot. type TakeHeapSnapshotParams struct { - ReportProgress bool `json:"reportProgress"` // If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. - CaptureNumericValue bool `json:"captureNumericValue"` // If true, numerical values are included in the snapshot - ExposeInternals bool `json:"exposeInternals"` // If true, exposes internals of the snapshot. + ReportProgress *bool `json:"reportProgress,omitempty,omitzero"` // If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + CaptureNumericValue *bool `json:"captureNumericValue,omitempty,omitzero"` // If true, numerical values are included in the snapshot + ExposeInternals *bool `json:"exposeInternals,omitempty,omitzero"` // If true, exposes internals of the snapshot. } // TakeHeapSnapshot [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-takeHeapSnapshot +var TakeHeapSnapshot = cdp.Command[TakeHeapSnapshotParams, cdp.Empty]{Method: CommandTakeHeapSnapshot} + +// AddHeapSnapshotChunk [no description]. // -// parameters: -func TakeHeapSnapshot() *TakeHeapSnapshotParams { - return &TakeHeapSnapshotParams{ - ReportProgress: false, - CaptureNumericValue: false, - ExposeInternals: false, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#event-addHeapSnapshotChunk +var AddHeapSnapshotChunk = cdp.Event[EventAddHeapSnapshotChunk]{Method: "HeapProfiler.addHeapSnapshotChunk"} -// WithReportProgress if true 'reportHeapSnapshotProgress' events will be -// generated while snapshot is being taken. -func (p TakeHeapSnapshotParams) WithReportProgress(reportProgress bool) *TakeHeapSnapshotParams { - p.ReportProgress = reportProgress - return &p -} +// HeapStatsUpdate if heap objects tracking has been started then backend may +// send update for one or more fragments. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#event-heapStatsUpdate +var HeapStatsUpdate = cdp.Event[EventHeapStatsUpdate]{Method: "HeapProfiler.heapStatsUpdate"} -// WithCaptureNumericValue if true, numerical values are included in the -// snapshot. -func (p TakeHeapSnapshotParams) WithCaptureNumericValue(captureNumericValue bool) *TakeHeapSnapshotParams { - p.CaptureNumericValue = captureNumericValue - return &p -} +// LastSeenObjectID 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. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#event-lastSeenObjectId +var LastSeenObjectID = cdp.Event[EventLastSeenObjectID]{Method: "HeapProfiler.lastSeenObjectId"} -// WithExposeInternals if true, exposes internals of the snapshot. -func (p TakeHeapSnapshotParams) WithExposeInternals(exposeInternals bool) *TakeHeapSnapshotParams { - p.ExposeInternals = exposeInternals - return &p -} +// ReportHeapSnapshotProgress [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#event-reportHeapSnapshotProgress +var ReportHeapSnapshotProgress = cdp.Event[EventReportHeapSnapshotProgress]{Method: "HeapProfiler.reportHeapSnapshotProgress"} -// Do executes HeapProfiler.takeHeapSnapshot against the provided context. -func (p *TakeHeapSnapshotParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandTakeHeapSnapshot, p, nil) -} +// ResetProfiles [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#event-resetProfiles +var ResetProfiles = cdp.Event[EventResetProfiles]{Method: "HeapProfiler.resetProfiles"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/heapprofiler/types.go b/vendor/github.com/chromedp/cdproto/heapprofiler/types.go index c46163952..946493115 100644 --- a/vendor/github.com/chromedp/cdproto/heapprofiler/types.go +++ b/vendor/github.com/chromedp/cdproto/heapprofiler/types.go @@ -1,6 +1,6 @@ -package heapprofiler +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package heapprofiler import ( "github.com/chromedp/cdproto/runtime" diff --git a/vendor/github.com/chromedp/cdproto/indexeddb/indexeddb.go b/vendor/github.com/chromedp/cdproto/indexeddb/indexeddb.go index e22ad7bee..c0580793b 100644 --- a/vendor/github.com/chromedp/cdproto/indexeddb/indexeddb.go +++ b/vendor/github.com/chromedp/cdproto/indexeddb/indexeddb.go @@ -1,19 +1,18 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package indexeddb provides the Chrome DevTools Protocol // commands, types, and events for the IndexedDB domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package indexeddb -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/storage" ) -// ClearObjectStoreParams clears all entries from an object store. +// ClearObjectStoreParams are the parameters of the command +// IndexedDB.clearObjectStore. type ClearObjectStoreParams struct { SecurityOrigin string `json:"securityOrigin,omitempty,omitzero"` // At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. Security origin. StorageKey string `json:"storageKey,omitempty,omitzero"` // Storage key. @@ -25,44 +24,10 @@ type ClearObjectStoreParams struct { // ClearObjectStore clears all entries from an object store. // // See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-clearObjectStore -// -// parameters: -// -// databaseName - Database name. -// objectStoreName - Object store name. -func ClearObjectStore(databaseName string, objectStoreName string) *ClearObjectStoreParams { - return &ClearObjectStoreParams{ - DatabaseName: databaseName, - ObjectStoreName: objectStoreName, - } -} - -// WithSecurityOrigin at least and at most one of securityOrigin, storageKey, -// or storageBucket must be specified. Security origin. -func (p ClearObjectStoreParams) WithSecurityOrigin(securityOrigin string) *ClearObjectStoreParams { - p.SecurityOrigin = securityOrigin - return &p -} +var ClearObjectStore = cdp.Command[ClearObjectStoreParams, cdp.Empty]{Method: CommandClearObjectStore} -// WithStorageKey storage key. -func (p ClearObjectStoreParams) WithStorageKey(storageKey string) *ClearObjectStoreParams { - p.StorageKey = storageKey - return &p -} - -// WithStorageBucket storage bucket. If not specified, it uses the default -// bucket. -func (p ClearObjectStoreParams) WithStorageBucket(storageBucket *storage.Bucket) *ClearObjectStoreParams { - p.StorageBucket = storageBucket - return &p -} - -// Do executes IndexedDB.clearObjectStore against the provided context. -func (p *ClearObjectStoreParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClearObjectStore, p, nil) -} - -// DeleteDatabaseParams deletes a database. +// DeleteDatabaseParams are the parameters of the command +// IndexedDB.deleteDatabase. type DeleteDatabaseParams struct { SecurityOrigin string `json:"securityOrigin,omitempty,omitzero"` // At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. Security origin. StorageKey string `json:"storageKey,omitempty,omitzero"` // Storage key. @@ -73,43 +38,10 @@ type DeleteDatabaseParams struct { // DeleteDatabase deletes a database. // // See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-deleteDatabase -// -// parameters: -// -// databaseName - Database name. -func DeleteDatabase(databaseName string) *DeleteDatabaseParams { - return &DeleteDatabaseParams{ - DatabaseName: databaseName, - } -} - -// WithSecurityOrigin at least and at most one of securityOrigin, storageKey, -// or storageBucket must be specified. Security origin. -func (p DeleteDatabaseParams) WithSecurityOrigin(securityOrigin string) *DeleteDatabaseParams { - p.SecurityOrigin = securityOrigin - return &p -} - -// WithStorageKey storage key. -func (p DeleteDatabaseParams) WithStorageKey(storageKey string) *DeleteDatabaseParams { - p.StorageKey = storageKey - return &p -} - -// WithStorageBucket storage bucket. If not specified, it uses the default -// bucket. -func (p DeleteDatabaseParams) WithStorageBucket(storageBucket *storage.Bucket) *DeleteDatabaseParams { - p.StorageBucket = storageBucket - return &p -} +var DeleteDatabase = cdp.Command[DeleteDatabaseParams, cdp.Empty]{Method: CommandDeleteDatabase} -// Do executes IndexedDB.deleteDatabase against the provided context. -func (p *DeleteDatabaseParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDeleteDatabase, p, nil) -} - -// DeleteObjectStoreEntriesParams delete a range of entries from an object -// store. +// DeleteObjectStoreEntriesParams are the parameters of the command +// IndexedDB.deleteObjectStoreEntries. type DeleteObjectStoreEntriesParams struct { SecurityOrigin string `json:"securityOrigin,omitempty,omitzero"` // At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. Security origin. StorageKey string `json:"storageKey,omitempty,omitzero"` // Storage key. @@ -122,76 +54,19 @@ type DeleteObjectStoreEntriesParams struct { // DeleteObjectStoreEntries delete a range of entries from an object store. // // See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-deleteObjectStoreEntries -// -// parameters: -// -// databaseName -// objectStoreName -// keyRange - Range of entry keys to delete -func DeleteObjectStoreEntries(databaseName string, objectStoreName string, keyRange *KeyRange) *DeleteObjectStoreEntriesParams { - return &DeleteObjectStoreEntriesParams{ - DatabaseName: databaseName, - ObjectStoreName: objectStoreName, - KeyRange: keyRange, - } -} - -// WithSecurityOrigin at least and at most one of securityOrigin, storageKey, -// or storageBucket must be specified. Security origin. -func (p DeleteObjectStoreEntriesParams) WithSecurityOrigin(securityOrigin string) *DeleteObjectStoreEntriesParams { - p.SecurityOrigin = securityOrigin - return &p -} - -// WithStorageKey storage key. -func (p DeleteObjectStoreEntriesParams) WithStorageKey(storageKey string) *DeleteObjectStoreEntriesParams { - p.StorageKey = storageKey - return &p -} - -// WithStorageBucket storage bucket. If not specified, it uses the default -// bucket. -func (p DeleteObjectStoreEntriesParams) WithStorageBucket(storageBucket *storage.Bucket) *DeleteObjectStoreEntriesParams { - p.StorageBucket = storageBucket - return &p -} - -// Do executes IndexedDB.deleteObjectStoreEntries against the provided context. -func (p *DeleteObjectStoreEntriesParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDeleteObjectStoreEntries, p, nil) -} - -// DisableParams disables events from backend. -type DisableParams struct{} +var DeleteObjectStoreEntries = cdp.Command[DeleteObjectStoreEntriesParams, cdp.Empty]{Method: CommandDeleteObjectStoreEntries} // Disable disables events from backend. // // See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes IndexedDB.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// EnableParams enables events from backend. -type EnableParams struct{} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} // Enable enables events from backend. // // See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} -// Do executes IndexedDB.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) -} - -// RequestDataParams requests data from object store or index. +// RequestDataParams are the parameters of the command IndexedDB.requestData. type RequestDataParams struct { SecurityOrigin string `json:"securityOrigin,omitempty,omitzero"` // At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. Security origin. StorageKey string `json:"storageKey,omitempty,omitzero"` // Storage key. @@ -204,82 +79,18 @@ type RequestDataParams struct { KeyRange *KeyRange `json:"keyRange,omitempty,omitzero"` // Key range. } -// RequestData requests data from object store or index. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-requestData -// -// parameters: -// -// databaseName - Database name. -// objectStoreName - Object store name. -// skipCount - Number of records to skip. -// pageSize - Number of records to fetch. -func RequestData(databaseName string, objectStoreName string, skipCount int64, pageSize int64) *RequestDataParams { - return &RequestDataParams{ - DatabaseName: databaseName, - ObjectStoreName: objectStoreName, - SkipCount: skipCount, - PageSize: pageSize, - } -} - -// WithSecurityOrigin at least and at most one of securityOrigin, storageKey, -// or storageBucket must be specified. Security origin. -func (p RequestDataParams) WithSecurityOrigin(securityOrigin string) *RequestDataParams { - p.SecurityOrigin = securityOrigin - return &p -} - -// WithStorageKey storage key. -func (p RequestDataParams) WithStorageKey(storageKey string) *RequestDataParams { - p.StorageKey = storageKey - return &p -} - -// WithStorageBucket storage bucket. If not specified, it uses the default -// bucket. -func (p RequestDataParams) WithStorageBucket(storageBucket *storage.Bucket) *RequestDataParams { - p.StorageBucket = storageBucket - return &p -} - -// WithIndexName index name. If not specified, it performs an object store -// data request. -func (p RequestDataParams) WithIndexName(indexName string) *RequestDataParams { - p.IndexName = indexName - return &p -} - -// WithKeyRange key range. -func (p RequestDataParams) WithKeyRange(keyRange *KeyRange) *RequestDataParams { - p.KeyRange = keyRange - return &p -} - -// RequestDataReturns return values. -type RequestDataReturns struct { +// RequestDataResult is the result of the command IndexedDB.requestData. +type RequestDataResult struct { ObjectStoreDataEntries []*DataEntry `json:"objectStoreDataEntries,omitempty,omitzero"` // Array of object store data entries. HasMore bool `json:"hasMore"` // If true, there are more entries to fetch in the given range. } -// Do executes IndexedDB.requestData against the provided context. -// -// returns: +// RequestData requests data from object store or index. // -// objectStoreDataEntries - Array of object store data entries. -// hasMore - If true, there are more entries to fetch in the given range. -func (p *RequestDataParams) Do(ctx context.Context) (objectStoreDataEntries []*DataEntry, hasMore bool, err error) { - // execute - var res RequestDataReturns - err = cdp.Execute(ctx, CommandRequestData, p, &res) - if err != nil { - return nil, false, err - } - - return res.ObjectStoreDataEntries, res.HasMore, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-requestData +var RequestData = cdp.Command[RequestDataParams, RequestDataResult]{Method: CommandRequestData} -// GetMetadataParams gets metadata of an object store. +// GetMetadataParams are the parameters of the command IndexedDB.getMetadata. type GetMetadataParams struct { SecurityOrigin string `json:"securityOrigin,omitempty,omitzero"` // At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. Security origin. StorageKey string `json:"storageKey,omitempty,omitzero"` // Storage key. @@ -288,65 +99,19 @@ type GetMetadataParams struct { ObjectStoreName string `json:"objectStoreName"` // Object store name. } -// GetMetadata gets metadata of an object store. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-getMetadata -// -// parameters: -// -// databaseName - Database name. -// objectStoreName - Object store name. -func GetMetadata(databaseName string, objectStoreName string) *GetMetadataParams { - return &GetMetadataParams{ - DatabaseName: databaseName, - ObjectStoreName: objectStoreName, - } -} - -// WithSecurityOrigin at least and at most one of securityOrigin, storageKey, -// or storageBucket must be specified. Security origin. -func (p GetMetadataParams) WithSecurityOrigin(securityOrigin string) *GetMetadataParams { - p.SecurityOrigin = securityOrigin - return &p -} - -// WithStorageKey storage key. -func (p GetMetadataParams) WithStorageKey(storageKey string) *GetMetadataParams { - p.StorageKey = storageKey - return &p -} - -// WithStorageBucket storage bucket. If not specified, it uses the default -// bucket. -func (p GetMetadataParams) WithStorageBucket(storageBucket *storage.Bucket) *GetMetadataParams { - p.StorageBucket = storageBucket - return &p -} - -// GetMetadataReturns return values. -type GetMetadataReturns struct { +// GetMetadataResult is the result of the command IndexedDB.getMetadata. +type GetMetadataResult struct { EntriesCount float64 `json:"entriesCount,omitempty,omitzero"` // the entries count KeyGeneratorValue float64 `json:"keyGeneratorValue,omitempty,omitzero"` // the current value of key generator, to become the next inserted key into the object store. Valid if objectStore.autoIncrement is true. } -// Do executes IndexedDB.getMetadata against the provided context. -// -// returns: +// GetMetadata gets metadata of an object store. // -// entriesCount - the entries count -// keyGeneratorValue - the current value of key generator, to become the next inserted key into the object store. Valid if objectStore.autoIncrement is true. -func (p *GetMetadataParams) Do(ctx context.Context) (entriesCount float64, keyGeneratorValue float64, err error) { - // execute - var res GetMetadataReturns - err = cdp.Execute(ctx, CommandGetMetadata, p, &res) - if err != nil { - return 0, 0, err - } - - return res.EntriesCount, res.KeyGeneratorValue, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-getMetadata +var GetMetadata = cdp.Command[GetMetadataParams, GetMetadataResult]{Method: CommandGetMetadata} -// RequestDatabaseParams requests database with given name in given frame. +// RequestDatabaseParams are the parameters of the command +// IndexedDB.requestDatabase. type RequestDatabaseParams struct { SecurityOrigin string `json:"securityOrigin,omitempty,omitzero"` // At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. Security origin. StorageKey string `json:"storageKey,omitempty,omitzero"` // Storage key. @@ -354,117 +119,35 @@ type RequestDatabaseParams struct { DatabaseName string `json:"databaseName"` // Database name. } -// RequestDatabase requests database with given name in given frame. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-requestDatabase -// -// parameters: -// -// databaseName - Database name. -func RequestDatabase(databaseName string) *RequestDatabaseParams { - return &RequestDatabaseParams{ - DatabaseName: databaseName, - } -} - -// WithSecurityOrigin at least and at most one of securityOrigin, storageKey, -// or storageBucket must be specified. Security origin. -func (p RequestDatabaseParams) WithSecurityOrigin(securityOrigin string) *RequestDatabaseParams { - p.SecurityOrigin = securityOrigin - return &p -} - -// WithStorageKey storage key. -func (p RequestDatabaseParams) WithStorageKey(storageKey string) *RequestDatabaseParams { - p.StorageKey = storageKey - return &p -} - -// WithStorageBucket storage bucket. If not specified, it uses the default -// bucket. -func (p RequestDatabaseParams) WithStorageBucket(storageBucket *storage.Bucket) *RequestDatabaseParams { - p.StorageBucket = storageBucket - return &p -} - -// RequestDatabaseReturns return values. -type RequestDatabaseReturns struct { +// RequestDatabaseResult is the result of the command +// IndexedDB.requestDatabase. +type RequestDatabaseResult struct { DatabaseWithObjectStores *DatabaseWithObjectStores `json:"databaseWithObjectStores,omitempty,omitzero"` // Database with an array of object stores. } -// Do executes IndexedDB.requestDatabase against the provided context. -// -// returns: +// RequestDatabase requests database with given name in given frame. // -// databaseWithObjectStores - Database with an array of object stores. -func (p *RequestDatabaseParams) Do(ctx context.Context) (databaseWithObjectStores *DatabaseWithObjectStores, err error) { - // execute - var res RequestDatabaseReturns - err = cdp.Execute(ctx, CommandRequestDatabase, p, &res) - if err != nil { - return nil, err - } - - return res.DatabaseWithObjectStores, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-requestDatabase +var RequestDatabase = cdp.Command[RequestDatabaseParams, RequestDatabaseResult]{Method: CommandRequestDatabase} -// RequestDatabaseNamesParams requests database names for given security -// origin. +// RequestDatabaseNamesParams are the parameters of the command +// IndexedDB.requestDatabaseNames. type RequestDatabaseNamesParams struct { SecurityOrigin string `json:"securityOrigin,omitempty,omitzero"` // At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. Security origin. StorageKey string `json:"storageKey,omitempty,omitzero"` // Storage key. StorageBucket *storage.Bucket `json:"storageBucket,omitempty,omitzero"` // Storage bucket. If not specified, it uses the default bucket. } -// RequestDatabaseNames requests database names for given security origin. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-requestDatabaseNames -// -// parameters: -func RequestDatabaseNames() *RequestDatabaseNamesParams { - return &RequestDatabaseNamesParams{} -} - -// WithSecurityOrigin at least and at most one of securityOrigin, storageKey, -// or storageBucket must be specified. Security origin. -func (p RequestDatabaseNamesParams) WithSecurityOrigin(securityOrigin string) *RequestDatabaseNamesParams { - p.SecurityOrigin = securityOrigin - return &p -} - -// WithStorageKey storage key. -func (p RequestDatabaseNamesParams) WithStorageKey(storageKey string) *RequestDatabaseNamesParams { - p.StorageKey = storageKey - return &p -} - -// WithStorageBucket storage bucket. If not specified, it uses the default -// bucket. -func (p RequestDatabaseNamesParams) WithStorageBucket(storageBucket *storage.Bucket) *RequestDatabaseNamesParams { - p.StorageBucket = storageBucket - return &p -} - -// RequestDatabaseNamesReturns return values. -type RequestDatabaseNamesReturns struct { +// RequestDatabaseNamesResult is the result of the command +// IndexedDB.requestDatabaseNames. +type RequestDatabaseNamesResult struct { DatabaseNames []string `json:"databaseNames,omitempty,omitzero"` // Database names for origin. } -// Do executes IndexedDB.requestDatabaseNames against the provided context. -// -// returns: +// RequestDatabaseNames requests database names for given security origin. // -// databaseNames - Database names for origin. -func (p *RequestDatabaseNamesParams) Do(ctx context.Context) (databaseNames []string, err error) { - // execute - var res RequestDatabaseNamesReturns - err = cdp.Execute(ctx, CommandRequestDatabaseNames, p, &res) - if err != nil { - return nil, err - } - - return res.DatabaseNames, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-requestDatabaseNames +var RequestDatabaseNames = cdp.Command[RequestDatabaseNamesParams, RequestDatabaseNamesResult]{Method: CommandRequestDatabaseNames} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/indexeddb/types.go b/vendor/github.com/chromedp/cdproto/indexeddb/types.go index 448ee9d7f..7d00bed98 100644 --- a/vendor/github.com/chromedp/cdproto/indexeddb/types.go +++ b/vendor/github.com/chromedp/cdproto/indexeddb/types.go @@ -1,11 +1,8 @@ -package indexeddb +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package indexeddb import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/runtime" ) @@ -42,11 +39,11 @@ type ObjectStoreIndex struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#type-Key type Key struct { - Type KeyType `json:"type"` // Key type. - Number float64 `json:"number,omitempty,omitzero"` // Number value. - String string `json:"string,omitempty,omitzero"` // String value. - Date float64 `json:"date,omitempty,omitzero"` // Date value. - Array []*Key `json:"array,omitempty,omitzero"` // Array value. + Type KeyType `json:"type"` // Key type. + Number *float64 `json:"number,omitempty,omitzero"` // Number value. + String string `json:"string,omitempty,omitzero"` // String value. + Date *float64 `json:"date,omitempty,omitzero"` // Date value. + Array []*Key `json:"array,omitempty,omitzero"` // Array value. } // KeyRange key range. @@ -95,26 +92,6 @@ const ( KeyTypeArray KeyType = "array" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *KeyType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch KeyType(s) { - case KeyTypeNumber: - *t = KeyTypeNumber - case KeyTypeString: - *t = KeyTypeString - case KeyTypeDate: - *t = KeyTypeDate - case KeyTypeArray: - *t = KeyTypeArray - default: - return fmt.Errorf("unknown KeyType value: %v", s) - } - return nil -} - // KeyPathType key path type. // // See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#type-KeyPath @@ -131,21 +108,3 @@ const ( KeyPathTypeString KeyPathType = "string" KeyPathTypeArray KeyPathType = "array" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *KeyPathType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch KeyPathType(s) { - case KeyPathTypeNull: - *t = KeyPathTypeNull - case KeyPathTypeString: - *t = KeyPathTypeString - case KeyPathTypeArray: - *t = KeyPathTypeArray - default: - return fmt.Errorf("unknown KeyPathType value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/input/events.go b/vendor/github.com/chromedp/cdproto/input/events.go index e53e770aa..b52e754f2 100644 --- a/vendor/github.com/chromedp/cdproto/input/events.go +++ b/vendor/github.com/chromedp/cdproto/input/events.go @@ -1,6 +1,6 @@ -package input +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package input // EventDragIntercepted emitted only when Input.setInterceptDrags is enabled. // Use this data with Input.dispatchDragEvent to restore normal drag and drop diff --git a/vendor/github.com/chromedp/cdproto/input/input.go b/vendor/github.com/chromedp/cdproto/input/input.go index 3f5b746a7..5bdc29734 100644 --- a/vendor/github.com/chromedp/cdproto/input/input.go +++ b/vendor/github.com/chromedp/cdproto/input/input.go @@ -1,198 +1,56 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package input provides the Chrome DevTools Protocol // commands, types, and events for the Input domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package input -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// DispatchDragEventParams dispatches a drag event into the page. +// DispatchDragEventParams are the parameters of the command +// Input.dispatchDragEvent. type DispatchDragEventParams struct { Type DispatchDragEventType `json:"type"` // Type of the drag event. X float64 `json:"x"` // X coordinate of the event relative to the main frame's viewport in CSS pixels. Y float64 `json:"y"` // Y coordinate of the event relative to the main frame's viewport in CSS pixels. 0 refers to the top of the viewport and Y increases as it proceeds towards the bottom of the viewport. Data *DragData `json:"data"` - Modifiers Modifier `json:"modifiers"` // Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0). + Modifiers int64 `json:"modifiers,omitempty,omitzero"` // Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0). } // DispatchDragEvent dispatches a drag event into the page. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-dispatchDragEvent -// -// parameters: -// -// type - Type of the drag event. -// x - X coordinate of the event relative to the main frame's viewport in CSS pixels. -// y - Y coordinate of the event relative to the main frame's viewport in CSS pixels. 0 refers to the top of the viewport and Y increases as it proceeds towards the bottom of the viewport. -// data -func DispatchDragEvent(typeVal DispatchDragEventType, x float64, y float64, data *DragData) *DispatchDragEventParams { - return &DispatchDragEventParams{ - Type: typeVal, - X: x, - Y: y, - Data: data, - } -} +var DispatchDragEvent = cdp.Command[DispatchDragEventParams, cdp.Empty]{Method: CommandDispatchDragEvent} -// WithModifiers bit field representing pressed modifier keys. Alt=1, Ctrl=2, -// Meta/Command=4, Shift=8 (default: 0). -func (p DispatchDragEventParams) WithModifiers(modifiers Modifier) *DispatchDragEventParams { - p.Modifiers = modifiers - return &p -} - -// Do executes Input.dispatchDragEvent against the provided context. -func (p *DispatchDragEventParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDispatchDragEvent, p, nil) -} - -// DispatchKeyEventParams dispatches a key event to the page. +// DispatchKeyEventParams are the parameters of the command +// Input.dispatchKeyEvent. type DispatchKeyEventParams struct { - Type KeyType `json:"type"` // Type of the key event. - Modifiers Modifier `json:"modifiers"` // Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0). - Timestamp *TimeSinceEpoch `json:"timestamp,omitempty,omitzero"` // Time at which the event occurred. - Text string `json:"text,omitempty,omitzero"` // Text as generated by processing a virtual key code with a keyboard layout. Not needed for for keyUp and rawKeyDown events (default: "") - UnmodifiedText string `json:"unmodifiedText,omitempty,omitzero"` // Text that would have been generated by the keyboard if no modifiers were pressed (except for shift). Useful for shortcut (accelerator) key handling (default: ""). - KeyIdentifier string `json:"keyIdentifier,omitempty,omitzero"` // Unique key identifier (e.g., 'U+0041') (default: ""). - Code string `json:"code,omitempty,omitzero"` // Unique DOM defined string value for each physical key (e.g., 'KeyA') (default: ""). - Key string `json:"key,omitempty,omitzero"` // Unique DOM defined string value describing the meaning of the key in the context of active modifiers, keyboard layout, etc (e.g., 'AltGr') (default: ""). - WindowsVirtualKeyCode int64 `json:"windowsVirtualKeyCode,omitempty,omitzero"` // Windows virtual key code (default: 0). - NativeVirtualKeyCode int64 `json:"nativeVirtualKeyCode,omitempty,omitzero"` // Native virtual key code (default: 0). - AutoRepeat bool `json:"autoRepeat"` // Whether the event was generated from auto repeat (default: false). - IsKeypad bool `json:"isKeypad"` // Whether the event was generated from the keypad (default: false). - IsSystemKey bool `json:"isSystemKey"` // Whether the event was a system key event (default: false). - Location int64 `json:"location,omitempty,omitzero"` // Whether the event was from the left or right side of the keyboard. 1=Left, 2=Right (default: 0). - Commands []string `json:"commands,omitempty,omitzero"` // Editing commands to send with the key event (e.g., 'selectAll') (default: []). These are related to but not equal the command names used in document.execCommand and NSStandardKeyBindingResponding. See https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/editing/commands/editor_command_names.h for valid command names. + Type DispatchKeyEventType `json:"type"` // Type of the key event. + Modifiers int64 `json:"modifiers,omitempty,omitzero"` // Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0). + Timestamp TimeSinceEpoch `json:"timestamp,omitempty,omitzero"` // Time at which the event occurred. + Text string `json:"text,omitempty,omitzero"` // Text as generated by processing a virtual key code with a keyboard layout. Not needed for for keyUp and rawKeyDown events (default: "") + UnmodifiedText string `json:"unmodifiedText,omitempty,omitzero"` // Text that would have been generated by the keyboard if no modifiers were pressed (except for shift). Useful for shortcut (accelerator) key handling (default: ""). + KeyIdentifier string `json:"keyIdentifier,omitempty,omitzero"` // Unique key identifier (e.g., 'U+0041') (default: ""). + Code string `json:"code,omitempty,omitzero"` // Unique DOM defined string value for each physical key (e.g., 'KeyA') (default: ""). + Key string `json:"key,omitempty,omitzero"` // Unique DOM defined string value describing the meaning of the key in the context of active modifiers, keyboard layout, etc (e.g., 'AltGr') (default: ""). + WindowsVirtualKeyCode int64 `json:"windowsVirtualKeyCode,omitempty,omitzero"` // Windows virtual key code (default: 0). + NativeVirtualKeyCode int64 `json:"nativeVirtualKeyCode,omitempty,omitzero"` // Native virtual key code (default: 0). + AutoRepeat *bool `json:"autoRepeat,omitempty,omitzero"` // Whether the event was generated from auto repeat (default: false). + IsKeypad *bool `json:"isKeypad,omitempty,omitzero"` // Whether the event was generated from the keypad (default: false). + IsSystemKey *bool `json:"isSystemKey,omitempty,omitzero"` // Whether the event was a system key event (default: false). + Location int64 `json:"location,omitempty,omitzero"` // Whether the event was from the left or right side of the keyboard. 1=Left, 2=Right (default: 0). + Commands []string `json:"commands,omitempty,omitzero"` // Editing commands to send with the key event (e.g., 'selectAll') (default: []). These are related to but not equal the command names used in document.execCommand and NSStandardKeyBindingResponding. See https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/editing/commands/editor_command_names.h for valid command names. } // DispatchKeyEvent dispatches a key event to the page. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-dispatchKeyEvent -// -// parameters: -// -// type - Type of the key event. -func DispatchKeyEvent(typeVal KeyType) *DispatchKeyEventParams { - return &DispatchKeyEventParams{ - Type: typeVal, - AutoRepeat: false, - IsKeypad: false, - IsSystemKey: false, - } -} - -// WithModifiers bit field representing pressed modifier keys. Alt=1, Ctrl=2, -// Meta/Command=4, Shift=8 (default: 0). -func (p DispatchKeyEventParams) WithModifiers(modifiers Modifier) *DispatchKeyEventParams { - p.Modifiers = modifiers - return &p -} - -// WithTimestamp time at which the event occurred. -func (p DispatchKeyEventParams) WithTimestamp(timestamp *TimeSinceEpoch) *DispatchKeyEventParams { - p.Timestamp = timestamp - return &p -} - -// WithText text as generated by processing a virtual key code with a -// keyboard layout. Not needed for for keyUp and rawKeyDown events (default: -// ""). -func (p DispatchKeyEventParams) WithText(text string) *DispatchKeyEventParams { - p.Text = text - return &p -} - -// WithUnmodifiedText text that would have been generated by the keyboard if -// no modifiers were pressed (except for shift). Useful for shortcut -// (accelerator) key handling (default: ""). -func (p DispatchKeyEventParams) WithUnmodifiedText(unmodifiedText string) *DispatchKeyEventParams { - p.UnmodifiedText = unmodifiedText - return &p -} - -// WithKeyIdentifier unique key identifier (e.g., 'U+0041') (default: ""). -func (p DispatchKeyEventParams) WithKeyIdentifier(keyIdentifier string) *DispatchKeyEventParams { - p.KeyIdentifier = keyIdentifier - return &p -} - -// WithCode unique DOM defined string value for each physical key (e.g., -// 'KeyA') (default: ""). -func (p DispatchKeyEventParams) WithCode(code string) *DispatchKeyEventParams { - p.Code = code - return &p -} - -// WithKey unique DOM defined string value describing the meaning of the key -// in the context of active modifiers, keyboard layout, etc (e.g., 'AltGr') -// (default: ""). -func (p DispatchKeyEventParams) WithKey(key string) *DispatchKeyEventParams { - p.Key = key - return &p -} - -// WithWindowsVirtualKeyCode windows virtual key code (default: 0). -func (p DispatchKeyEventParams) WithWindowsVirtualKeyCode(windowsVirtualKeyCode int64) *DispatchKeyEventParams { - p.WindowsVirtualKeyCode = windowsVirtualKeyCode - return &p -} - -// WithNativeVirtualKeyCode native virtual key code (default: 0). -func (p DispatchKeyEventParams) WithNativeVirtualKeyCode(nativeVirtualKeyCode int64) *DispatchKeyEventParams { - p.NativeVirtualKeyCode = nativeVirtualKeyCode - return &p -} - -// WithAutoRepeat whether the event was generated from auto repeat (default: -// false). -func (p DispatchKeyEventParams) WithAutoRepeat(autoRepeat bool) *DispatchKeyEventParams { - p.AutoRepeat = autoRepeat - return &p -} +var DispatchKeyEvent = cdp.Command[DispatchKeyEventParams, cdp.Empty]{Method: CommandDispatchKeyEvent} -// WithIsKeypad whether the event was generated from the keypad (default: -// false). -func (p DispatchKeyEventParams) WithIsKeypad(isKeypad bool) *DispatchKeyEventParams { - p.IsKeypad = isKeypad - return &p -} - -// WithIsSystemKey whether the event was a system key event (default: false). -func (p DispatchKeyEventParams) WithIsSystemKey(isSystemKey bool) *DispatchKeyEventParams { - p.IsSystemKey = isSystemKey - return &p -} - -// WithLocation whether the event was from the left or right side of the -// keyboard. 1=Left, 2=Right (default: 0). -func (p DispatchKeyEventParams) WithLocation(location int64) *DispatchKeyEventParams { - p.Location = location - return &p -} - -// WithCommands editing commands to send with the key event (e.g., -// 'selectAll') (default: []). These are related to but not equal the command -// names used in document.execCommand and NSStandardKeyBindingResponding. See -// https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/editing/commands/editor_command_names.h -// for valid command names. -func (p DispatchKeyEventParams) WithCommands(commands []string) *DispatchKeyEventParams { - p.Commands = commands - return &p -} - -// Do executes Input.dispatchKeyEvent against the provided context. -func (p *DispatchKeyEventParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDispatchKeyEvent, p, nil) -} - -// InsertTextParams this method emulates inserting text that doesn't come -// from a key press, for example an emoji keyboard or an IME. +// InsertTextParams are the parameters of the command Input.insertText. type InsertTextParams struct { Text string `json:"text"` // The text to insert. } @@ -201,30 +59,16 @@ type InsertTextParams struct { // key press, for example an emoji keyboard or an IME. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-insertText -// -// parameters: -// -// text - The text to insert. -func InsertText(text string) *InsertTextParams { - return &InsertTextParams{ - Text: text, - } -} - -// Do executes Input.insertText against the provided context. -func (p *InsertTextParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandInsertText, p, nil) -} +var InsertText = cdp.Command[InsertTextParams, cdp.Empty]{Method: CommandInsertText} -// ImeSetCompositionParams this method sets the current candidate text for -// IME. Use imeCommitComposition to commit the final text. Use imeSetComposition -// with empty string as text to cancel composition. +// ImeSetCompositionParams are the parameters of the command +// Input.imeSetComposition. type ImeSetCompositionParams struct { Text string `json:"text"` // The text to insert SelectionStart int64 `json:"selectionStart"` // selection start SelectionEnd int64 `json:"selectionEnd"` // selection end - ReplacementStart int64 `json:"replacementStart,omitempty,omitzero"` // replacement start - ReplacementEnd int64 `json:"replacementEnd,omitempty,omitzero"` // replacement end + ReplacementStart *int64 `json:"replacementStart,omitempty,omitzero"` // replacement start + ReplacementEnd *int64 `json:"replacementEnd,omitempty,omitzero"` // replacement end } // ImeSetComposition this method sets the current candidate text for IME. Use @@ -232,44 +76,16 @@ type ImeSetCompositionParams struct { // empty string as text to cancel composition. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-imeSetComposition -// -// parameters: -// -// text - The text to insert -// selectionStart - selection start -// selectionEnd - selection end -func ImeSetComposition(text string, selectionStart int64, selectionEnd int64) *ImeSetCompositionParams { - return &ImeSetCompositionParams{ - Text: text, - SelectionStart: selectionStart, - SelectionEnd: selectionEnd, - } -} - -// WithReplacementStart replacement start. -func (p ImeSetCompositionParams) WithReplacementStart(replacementStart int64) *ImeSetCompositionParams { - p.ReplacementStart = replacementStart - return &p -} - -// WithReplacementEnd replacement end. -func (p ImeSetCompositionParams) WithReplacementEnd(replacementEnd int64) *ImeSetCompositionParams { - p.ReplacementEnd = replacementEnd - return &p -} +var ImeSetComposition = cdp.Command[ImeSetCompositionParams, cdp.Empty]{Method: CommandImeSetComposition} -// Do executes Input.imeSetComposition against the provided context. -func (p *ImeSetCompositionParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandImeSetComposition, p, nil) -} - -// DispatchMouseEventParams dispatches a mouse event to the page. +// DispatchMouseEventParams are the parameters of the command +// Input.dispatchMouseEvent. type DispatchMouseEventParams struct { - Type MouseType `json:"type"` // Type of the mouse event. + Type DispatchMouseEventType `json:"type"` // Type of the mouse event. X float64 `json:"x"` // X coordinate of the event relative to the main frame's viewport in CSS pixels. Y float64 `json:"y"` // Y coordinate of the event relative to the main frame's viewport in CSS pixels. 0 refers to the top of the viewport and Y increases as it proceeds towards the bottom of the viewport. - Modifiers Modifier `json:"modifiers"` // Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0). - Timestamp *TimeSinceEpoch `json:"timestamp,omitempty,omitzero"` // Time at which the event occurred. + Modifiers int64 `json:"modifiers,omitempty,omitzero"` // Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0). + Timestamp TimeSinceEpoch `json:"timestamp,omitempty,omitzero"` // Time at which the event occurred. Button MouseButton `json:"button,omitempty,omitzero"` // Mouse button (default: "none"). Buttons int64 `json:"buttons,omitempty,omitzero"` // A number indicating which buttons are pressed on the mouse when a mouse event is triggered. Left=1, Right=2, Middle=4, Back=8, Forward=16, None=0. ClickCount int64 `json:"clickCount,omitempty,omitzero"` // Number of times the mouse button was clicked (default: 0). @@ -278,249 +94,57 @@ type DispatchMouseEventParams struct { TiltX float64 `json:"tiltX,omitempty,omitzero"` // The plane angle between the Y-Z plane and the plane containing both the stylus axis and the Y axis, in degrees of the range [-90,90], a positive tiltX is to the right (default: 0). TiltY float64 `json:"tiltY,omitempty,omitzero"` // The plane angle between the X-Z plane and the plane containing both the stylus axis and the X axis, in degrees of the range [-90,90], a positive tiltY is towards the user (default: 0). Twist int64 `json:"twist,omitempty,omitzero"` // The clockwise rotation of a pen stylus around its own major axis, in degrees in the range [0,359] (default: 0). - DeltaX float64 `json:"deltaX"` // X delta in CSS pixels for mouse wheel event (default: 0). - DeltaY float64 `json:"deltaY"` // Y delta in CSS pixels for mouse wheel event (default: 0). + DeltaX float64 `json:"deltaX,omitempty,omitzero"` // X delta in CSS pixels for mouse wheel event (default: 0). + DeltaY float64 `json:"deltaY,omitempty,omitzero"` // Y delta in CSS pixels for mouse wheel event (default: 0). PointerType DispatchMouseEventPointerType `json:"pointerType,omitempty,omitzero"` // Pointer type (default: "mouse"). } // DispatchMouseEvent dispatches a mouse event to the page. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-dispatchMouseEvent -// -// parameters: -// -// type - Type of the mouse event. -// x - X coordinate of the event relative to the main frame's viewport in CSS pixels. -// y - Y coordinate of the event relative to the main frame's viewport in CSS pixels. 0 refers to the top of the viewport and Y increases as it proceeds towards the bottom of the viewport. -func DispatchMouseEvent(typeVal MouseType, x float64, y float64) *DispatchMouseEventParams { - return &DispatchMouseEventParams{ - Type: typeVal, - X: x, - Y: y, - } -} - -// WithModifiers bit field representing pressed modifier keys. Alt=1, Ctrl=2, -// Meta/Command=4, Shift=8 (default: 0). -func (p DispatchMouseEventParams) WithModifiers(modifiers Modifier) *DispatchMouseEventParams { - p.Modifiers = modifiers - return &p -} - -// WithTimestamp time at which the event occurred. -func (p DispatchMouseEventParams) WithTimestamp(timestamp *TimeSinceEpoch) *DispatchMouseEventParams { - p.Timestamp = timestamp - return &p -} - -// WithButton mouse button (default: "none"). -func (p DispatchMouseEventParams) WithButton(button MouseButton) *DispatchMouseEventParams { - p.Button = button - return &p -} +var DispatchMouseEvent = cdp.Command[DispatchMouseEventParams, cdp.Empty]{Method: CommandDispatchMouseEvent} -// WithButtons a number indicating which buttons are pressed on the mouse -// when a mouse event is triggered. Left=1, Right=2, Middle=4, Back=8, -// Forward=16, None=0. -func (p DispatchMouseEventParams) WithButtons(buttons int64) *DispatchMouseEventParams { - p.Buttons = buttons - return &p -} - -// WithClickCount number of times the mouse button was clicked (default: 0). -func (p DispatchMouseEventParams) WithClickCount(clickCount int64) *DispatchMouseEventParams { - p.ClickCount = clickCount - return &p -} - -// WithForce the normalized pressure, which has a range of [0,1] (default: -// 0). -func (p DispatchMouseEventParams) WithForce(force float64) *DispatchMouseEventParams { - p.Force = force - return &p -} - -// WithTangentialPressure the normalized tangential pressure, which has a -// range of [-1,1] (default: 0). -func (p DispatchMouseEventParams) WithTangentialPressure(tangentialPressure float64) *DispatchMouseEventParams { - p.TangentialPressure = tangentialPressure - return &p -} - -// WithTiltX the plane angle between the Y-Z plane and the plane containing -// both the stylus axis and the Y axis, in degrees of the range [-90,90], a -// positive tiltX is to the right (default: 0). -func (p DispatchMouseEventParams) WithTiltX(tiltX float64) *DispatchMouseEventParams { - p.TiltX = tiltX - return &p -} - -// WithTiltY the plane angle between the X-Z plane and the plane containing -// both the stylus axis and the X axis, in degrees of the range [-90,90], a -// positive tiltY is towards the user (default: 0). -func (p DispatchMouseEventParams) WithTiltY(tiltY float64) *DispatchMouseEventParams { - p.TiltY = tiltY - return &p -} - -// WithTwist the clockwise rotation of a pen stylus around its own major -// axis, in degrees in the range [0,359] (default: 0). -func (p DispatchMouseEventParams) WithTwist(twist int64) *DispatchMouseEventParams { - p.Twist = twist - return &p -} - -// WithDeltaX X delta in CSS pixels for mouse wheel event (default: 0). -func (p DispatchMouseEventParams) WithDeltaX(deltaX float64) *DispatchMouseEventParams { - p.DeltaX = deltaX - return &p -} - -// WithDeltaY Y delta in CSS pixels for mouse wheel event (default: 0). -func (p DispatchMouseEventParams) WithDeltaY(deltaY float64) *DispatchMouseEventParams { - p.DeltaY = deltaY - return &p -} - -// WithPointerType pointer type (default: "mouse"). -func (p DispatchMouseEventParams) WithPointerType(pointerType DispatchMouseEventPointerType) *DispatchMouseEventParams { - p.PointerType = pointerType - return &p -} - -// Do executes Input.dispatchMouseEvent against the provided context. -func (p *DispatchMouseEventParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDispatchMouseEvent, p, nil) -} - -// DispatchTouchEventParams dispatches a touch event to the page. +// DispatchTouchEventParams are the parameters of the command +// Input.dispatchTouchEvent. type DispatchTouchEventParams struct { - Type TouchType `json:"type"` // Type of the touch event. TouchEnd and TouchCancel must not contain any touch points, while TouchStart and TouchMove must contains at least one. - TouchPoints []*TouchPoint `json:"touchPoints"` // Active touch points on the touch device. One event per any changed point (compared to previous touch event in a sequence) is generated, emulating pressing/moving/releasing points one by one. - Modifiers Modifier `json:"modifiers"` // Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0). - Timestamp *TimeSinceEpoch `json:"timestamp,omitempty,omitzero"` // Time at which the event occurred. + Type DispatchTouchEventType `json:"type"` // Type of the touch event. TouchEnd and TouchCancel must not contain any touch points, while TouchStart and TouchMove must contains at least one. + TouchPoints []*TouchPoint `json:"touchPoints"` // Active touch points on the touch device. One event per any changed point (compared to previous touch event in a sequence) is generated, emulating pressing/moving/releasing points one by one. + Modifiers int64 `json:"modifiers,omitempty,omitzero"` // Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0). + Timestamp TimeSinceEpoch `json:"timestamp,omitempty,omitzero"` // Time at which the event occurred. } // DispatchTouchEvent dispatches a touch event to the page. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-dispatchTouchEvent -// -// parameters: -// -// type - Type of the touch event. TouchEnd and TouchCancel must not contain any touch points, while TouchStart and TouchMove must contains at least one. -// touchPoints - Active touch points on the touch device. One event per any changed point (compared to previous touch event in a sequence) is generated, emulating pressing/moving/releasing points one by one. -func DispatchTouchEvent(typeVal TouchType, touchPoints []*TouchPoint) *DispatchTouchEventParams { - return &DispatchTouchEventParams{ - Type: typeVal, - TouchPoints: touchPoints, - } -} - -// WithModifiers bit field representing pressed modifier keys. Alt=1, Ctrl=2, -// Meta/Command=4, Shift=8 (default: 0). -func (p DispatchTouchEventParams) WithModifiers(modifiers Modifier) *DispatchTouchEventParams { - p.Modifiers = modifiers - return &p -} - -// WithTimestamp time at which the event occurred. -func (p DispatchTouchEventParams) WithTimestamp(timestamp *TimeSinceEpoch) *DispatchTouchEventParams { - p.Timestamp = timestamp - return &p -} - -// Do executes Input.dispatchTouchEvent against the provided context. -func (p *DispatchTouchEventParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDispatchTouchEvent, p, nil) -} - -// CancelDraggingParams cancels any active dragging in the page. -type CancelDraggingParams struct{} +var DispatchTouchEvent = cdp.Command[DispatchTouchEventParams, cdp.Empty]{Method: CommandDispatchTouchEvent} // CancelDragging cancels any active dragging in the page. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-cancelDragging -func CancelDragging() *CancelDraggingParams { - return &CancelDraggingParams{} -} - -// Do executes Input.cancelDragging against the provided context. -func (p *CancelDraggingParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandCancelDragging, nil, nil) -} +var CancelDragging = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandCancelDragging} -// EmulateTouchFromMouseEventParams emulates touch event from the mouse event -// parameters. +// EmulateTouchFromMouseEventParams are the parameters of the command +// Input.emulateTouchFromMouseEvent. type EmulateTouchFromMouseEventParams struct { - Type MouseType `json:"type"` // Type of the mouse event. - X int64 `json:"x"` // X coordinate of the mouse pointer in DIP. - Y int64 `json:"y"` // Y coordinate of the mouse pointer in DIP. - Button MouseButton `json:"button"` // Mouse button. Only "none", "left", "right" are supported. - Timestamp *TimeSinceEpoch `json:"timestamp,omitempty,omitzero"` // Time at which the event occurred (default: current time). - DeltaX float64 `json:"deltaX"` // X delta in DIP for mouse wheel event (default: 0). - DeltaY float64 `json:"deltaY"` // Y delta in DIP for mouse wheel event (default: 0). - Modifiers Modifier `json:"modifiers"` // Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0). - ClickCount int64 `json:"clickCount,omitempty,omitzero"` // Number of times the mouse button was clicked (default: 0). + Type EmulateTouchFromMouseEventType `json:"type"` // Type of the mouse event. + X int64 `json:"x"` // X coordinate of the mouse pointer in DIP. + Y int64 `json:"y"` // Y coordinate of the mouse pointer in DIP. + Button MouseButton `json:"button"` // Mouse button. Only "none", "left", "right" are supported. + Timestamp TimeSinceEpoch `json:"timestamp,omitempty,omitzero"` // Time at which the event occurred (default: current time). + DeltaX float64 `json:"deltaX,omitempty,omitzero"` // X delta in DIP for mouse wheel event (default: 0). + DeltaY float64 `json:"deltaY,omitempty,omitzero"` // Y delta in DIP for mouse wheel event (default: 0). + Modifiers int64 `json:"modifiers,omitempty,omitzero"` // Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0). + ClickCount int64 `json:"clickCount,omitempty,omitzero"` // Number of times the mouse button was clicked (default: 0). } // EmulateTouchFromMouseEvent emulates touch event from the mouse event // parameters. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-emulateTouchFromMouseEvent -// -// parameters: -// -// type - Type of the mouse event. -// x - X coordinate of the mouse pointer in DIP. -// y - Y coordinate of the mouse pointer in DIP. -// button - Mouse button. Only "none", "left", "right" are supported. -func EmulateTouchFromMouseEvent(typeVal MouseType, x int64, y int64, button MouseButton) *EmulateTouchFromMouseEventParams { - return &EmulateTouchFromMouseEventParams{ - Type: typeVal, - X: x, - Y: y, - Button: button, - } -} - -// WithTimestamp time at which the event occurred (default: current time). -func (p EmulateTouchFromMouseEventParams) WithTimestamp(timestamp *TimeSinceEpoch) *EmulateTouchFromMouseEventParams { - p.Timestamp = timestamp - return &p -} - -// WithDeltaX X delta in DIP for mouse wheel event (default: 0). -func (p EmulateTouchFromMouseEventParams) WithDeltaX(deltaX float64) *EmulateTouchFromMouseEventParams { - p.DeltaX = deltaX - return &p -} +var EmulateTouchFromMouseEvent = cdp.Command[EmulateTouchFromMouseEventParams, cdp.Empty]{Method: CommandEmulateTouchFromMouseEvent} -// WithDeltaY Y delta in DIP for mouse wheel event (default: 0). -func (p EmulateTouchFromMouseEventParams) WithDeltaY(deltaY float64) *EmulateTouchFromMouseEventParams { - p.DeltaY = deltaY - return &p -} - -// WithModifiers bit field representing pressed modifier keys. Alt=1, Ctrl=2, -// Meta/Command=4, Shift=8 (default: 0). -func (p EmulateTouchFromMouseEventParams) WithModifiers(modifiers Modifier) *EmulateTouchFromMouseEventParams { - p.Modifiers = modifiers - return &p -} - -// WithClickCount number of times the mouse button was clicked (default: 0). -func (p EmulateTouchFromMouseEventParams) WithClickCount(clickCount int64) *EmulateTouchFromMouseEventParams { - p.ClickCount = clickCount - return &p -} - -// Do executes Input.emulateTouchFromMouseEvent against the provided context. -func (p *EmulateTouchFromMouseEventParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEmulateTouchFromMouseEvent, p, nil) -} - -// SetIgnoreInputEventsParams ignores input events (useful while auditing -// page). +// SetIgnoreInputEventsParams are the parameters of the command +// Input.setIgnoreInputEvents. type SetIgnoreInputEventsParams struct { Ignore bool `json:"ignore"` // Ignores input events processing when set to true. } @@ -528,24 +152,10 @@ type SetIgnoreInputEventsParams struct { // SetIgnoreInputEvents ignores input events (useful while auditing page). // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-setIgnoreInputEvents -// -// parameters: -// -// ignore - Ignores input events processing when set to true. -func SetIgnoreInputEvents(ignore bool) *SetIgnoreInputEventsParams { - return &SetIgnoreInputEventsParams{ - Ignore: ignore, - } -} +var SetIgnoreInputEvents = cdp.Command[SetIgnoreInputEventsParams, cdp.Empty]{Method: CommandSetIgnoreInputEvents} -// Do executes Input.setIgnoreInputEvents against the provided context. -func (p *SetIgnoreInputEventsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetIgnoreInputEvents, p, nil) -} - -// SetInterceptDragsParams prevents default drag and drop behavior and -// instead emits Input.dragIntercepted events. Drag and drop behavior can be -// directly controlled via Input.dispatchDragEvent. +// SetInterceptDragsParams are the parameters of the command +// Input.setInterceptDrags. type SetInterceptDragsParams struct { Enabled bool `json:"enabled"` } @@ -555,23 +165,10 @@ type SetInterceptDragsParams struct { // controlled via Input.dispatchDragEvent. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-setInterceptDrags -// -// parameters: -// -// enabled -func SetInterceptDrags(enabled bool) *SetInterceptDragsParams { - return &SetInterceptDragsParams{ - Enabled: enabled, - } -} +var SetInterceptDrags = cdp.Command[SetInterceptDragsParams, cdp.Empty]{Method: CommandSetInterceptDrags} -// Do executes Input.setInterceptDrags against the provided context. -func (p *SetInterceptDragsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetInterceptDrags, p, nil) -} - -// SynthesizePinchGestureParams synthesizes a pinch gesture over a time -// period by issuing appropriate touch events. +// SynthesizePinchGestureParams are the parameters of the command +// Input.synthesizePinchGesture. type SynthesizePinchGestureParams struct { X float64 `json:"x"` // X coordinate of the start of the gesture in CSS pixels. Y float64 `json:"y"` // Y coordinate of the start of the gesture in CSS pixels. @@ -584,41 +181,10 @@ type SynthesizePinchGestureParams struct { // issuing appropriate touch events. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-synthesizePinchGesture -// -// parameters: -// -// x - X coordinate of the start of the gesture in CSS pixels. -// y - Y coordinate of the start of the gesture in CSS pixels. -// scaleFactor - Relative scale factor after zooming (>1.0 zooms in, <1.0 zooms out). -func SynthesizePinchGesture(x float64, y float64, scaleFactor float64) *SynthesizePinchGestureParams { - return &SynthesizePinchGestureParams{ - X: x, - Y: y, - ScaleFactor: scaleFactor, - } -} +var SynthesizePinchGesture = cdp.Command[SynthesizePinchGestureParams, cdp.Empty]{Method: CommandSynthesizePinchGesture} -// WithRelativeSpeed relative pointer speed in pixels per second (default: -// 800). -func (p SynthesizePinchGestureParams) WithRelativeSpeed(relativeSpeed int64) *SynthesizePinchGestureParams { - p.RelativeSpeed = relativeSpeed - return &p -} - -// WithGestureSourceType which type of input events to be generated (default: -// 'default', which queries the platform for the preferred input type). -func (p SynthesizePinchGestureParams) WithGestureSourceType(gestureSourceType GestureSourceType) *SynthesizePinchGestureParams { - p.GestureSourceType = gestureSourceType - return &p -} - -// Do executes Input.synthesizePinchGesture against the provided context. -func (p *SynthesizePinchGestureParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSynthesizePinchGesture, p, nil) -} - -// SynthesizeScrollGestureParams synthesizes a scroll gesture over a time -// period by issuing appropriate touch events. +// SynthesizeScrollGestureParams are the parameters of the command +// Input.synthesizeScrollGesture. type SynthesizeScrollGestureParams struct { X float64 `json:"x"` // X coordinate of the start of the gesture in CSS pixels. Y float64 `json:"y"` // Y coordinate of the start of the gesture in CSS pixels. @@ -626,11 +192,11 @@ type SynthesizeScrollGestureParams struct { YDistance float64 `json:"yDistance,omitempty,omitzero"` // The distance to scroll along the Y axis (positive to scroll up). XOverscroll float64 `json:"xOverscroll,omitempty,omitzero"` // The number of additional pixels to scroll back along the X axis, in addition to the given distance. YOverscroll float64 `json:"yOverscroll,omitempty,omitzero"` // The number of additional pixels to scroll back along the Y axis, in addition to the given distance. - PreventFling bool `json:"preventFling"` // Prevent fling (default: true). + PreventFling *bool `json:"preventFling,omitempty,omitzero"` // Prevent fling (default: true). Speed int64 `json:"speed,omitempty,omitzero"` // Swipe speed in pixels per second (default: 800). GestureSourceType GestureSourceType `json:"gestureSourceType,omitempty,omitzero"` // Which type of input events to be generated (default: 'default', which queries the platform for the preferred input type). RepeatCount int64 `json:"repeatCount,omitempty,omitzero"` // The number of times to repeat the gesture (default: 0). - RepeatDelayMs int64 `json:"repeatDelayMs,omitempty,omitzero"` // The number of milliseconds delay between each repeat. (default: 250). + RepeatDelayMs *int64 `json:"repeatDelayMs,omitempty,omitzero"` // The number of milliseconds delay between each repeat. (default: 250). InteractionMarkerName string `json:"interactionMarkerName,omitempty,omitzero"` // The name of the interaction markers to generate, if not empty (default: ""). } @@ -638,97 +204,14 @@ type SynthesizeScrollGestureParams struct { // issuing appropriate touch events. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-synthesizeScrollGesture -// -// parameters: -// -// x - X coordinate of the start of the gesture in CSS pixels. -// y - Y coordinate of the start of the gesture in CSS pixels. -func SynthesizeScrollGesture(x float64, y float64) *SynthesizeScrollGestureParams { - return &SynthesizeScrollGestureParams{ - X: x, - Y: y, - PreventFling: true, - } -} - -// WithXDistance the distance to scroll along the X axis (positive to scroll -// left). -func (p SynthesizeScrollGestureParams) WithXDistance(xDistance float64) *SynthesizeScrollGestureParams { - p.XDistance = xDistance - return &p -} +var SynthesizeScrollGesture = cdp.Command[SynthesizeScrollGestureParams, cdp.Empty]{Method: CommandSynthesizeScrollGesture} -// WithYDistance the distance to scroll along the Y axis (positive to scroll -// up). -func (p SynthesizeScrollGestureParams) WithYDistance(yDistance float64) *SynthesizeScrollGestureParams { - p.YDistance = yDistance - return &p -} - -// WithXOverscroll the number of additional pixels to scroll back along the X -// axis, in addition to the given distance. -func (p SynthesizeScrollGestureParams) WithXOverscroll(xOverscroll float64) *SynthesizeScrollGestureParams { - p.XOverscroll = xOverscroll - return &p -} - -// WithYOverscroll the number of additional pixels to scroll back along the Y -// axis, in addition to the given distance. -func (p SynthesizeScrollGestureParams) WithYOverscroll(yOverscroll float64) *SynthesizeScrollGestureParams { - p.YOverscroll = yOverscroll - return &p -} - -// WithPreventFling prevent fling (default: true). -func (p SynthesizeScrollGestureParams) WithPreventFling(preventFling bool) *SynthesizeScrollGestureParams { - p.PreventFling = preventFling - return &p -} - -// WithSpeed swipe speed in pixels per second (default: 800). -func (p SynthesizeScrollGestureParams) WithSpeed(speed int64) *SynthesizeScrollGestureParams { - p.Speed = speed - return &p -} - -// WithGestureSourceType which type of input events to be generated (default: -// 'default', which queries the platform for the preferred input type). -func (p SynthesizeScrollGestureParams) WithGestureSourceType(gestureSourceType GestureSourceType) *SynthesizeScrollGestureParams { - p.GestureSourceType = gestureSourceType - return &p -} - -// WithRepeatCount the number of times to repeat the gesture (default: 0). -func (p SynthesizeScrollGestureParams) WithRepeatCount(repeatCount int64) *SynthesizeScrollGestureParams { - p.RepeatCount = repeatCount - return &p -} - -// WithRepeatDelayMs the number of milliseconds delay between each repeat. -// (default: 250). -func (p SynthesizeScrollGestureParams) WithRepeatDelayMs(repeatDelayMs int64) *SynthesizeScrollGestureParams { - p.RepeatDelayMs = repeatDelayMs - return &p -} - -// WithInteractionMarkerName the name of the interaction markers to generate, -// if not empty (default: ""). -func (p SynthesizeScrollGestureParams) WithInteractionMarkerName(interactionMarkerName string) *SynthesizeScrollGestureParams { - p.InteractionMarkerName = interactionMarkerName - return &p -} - -// Do executes Input.synthesizeScrollGesture against the provided context. -func (p *SynthesizeScrollGestureParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSynthesizeScrollGesture, p, nil) -} - -// SynthesizeTapGestureParams synthesizes a tap gesture over a time period by -// issuing appropriate touch events. +// SynthesizeTapGestureParams are the parameters of the command +// Input.synthesizeTapGesture. type SynthesizeTapGestureParams struct { X float64 `json:"x"` // X coordinate of the start of the gesture in CSS pixels. Y float64 `json:"y"` // Y coordinate of the start of the gesture in CSS pixels. - Duration int64 `json:"duration,omitempty,omitzero"` // Duration between touchdown and touchup events in ms (default: 50). + Duration *int64 `json:"duration,omitempty,omitzero"` // Duration between touchdown and touchup events in ms (default: 50). TapCount int64 `json:"tapCount,omitempty,omitzero"` // Number of times to perform the tap (e.g. 2 for double tap, default: 1). GestureSourceType GestureSourceType `json:"gestureSourceType,omitempty,omitzero"` // Which type of input events to be generated (default: 'default', which queries the platform for the preferred input type). } @@ -737,43 +220,14 @@ type SynthesizeTapGestureParams struct { // issuing appropriate touch events. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-synthesizeTapGesture -// -// parameters: -// -// x - X coordinate of the start of the gesture in CSS pixels. -// y - Y coordinate of the start of the gesture in CSS pixels. -func SynthesizeTapGesture(x float64, y float64) *SynthesizeTapGestureParams { - return &SynthesizeTapGestureParams{ - X: x, - Y: y, - } -} - -// WithDuration duration between touchdown and touchup events in ms (default: -// 50). -func (p SynthesizeTapGestureParams) WithDuration(duration int64) *SynthesizeTapGestureParams { - p.Duration = duration - return &p -} - -// WithTapCount number of times to perform the tap (e.g. 2 for double tap, -// default: 1). -func (p SynthesizeTapGestureParams) WithTapCount(tapCount int64) *SynthesizeTapGestureParams { - p.TapCount = tapCount - return &p -} - -// WithGestureSourceType which type of input events to be generated (default: -// 'default', which queries the platform for the preferred input type). -func (p SynthesizeTapGestureParams) WithGestureSourceType(gestureSourceType GestureSourceType) *SynthesizeTapGestureParams { - p.GestureSourceType = gestureSourceType - return &p -} +var SynthesizeTapGesture = cdp.Command[SynthesizeTapGestureParams, cdp.Empty]{Method: CommandSynthesizeTapGesture} -// Do executes Input.synthesizeTapGesture against the provided context. -func (p *SynthesizeTapGestureParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSynthesizeTapGesture, p, nil) -} +// DragIntercepted emitted only when Input.setInterceptDrags is enabled. Use +// this data with Input.dispatchDragEvent to restore normal drag and drop +// behavior. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Input#event-dragIntercepted +var DragIntercepted = cdp.Event[EventDragIntercepted]{Method: "Input.dragIntercepted"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/input/types.go b/vendor/github.com/chromedp/cdproto/input/types.go index f82e377ab..41d266871 100644 --- a/vendor/github.com/chromedp/cdproto/input/types.go +++ b/vendor/github.com/chromedp/cdproto/input/types.go @@ -1,29 +1,22 @@ -package input - -import ( - "fmt" - "strconv" - "strings" - "time" -) +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package input // TouchPoint [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#type-TouchPoint type TouchPoint struct { - X float64 `json:"x"` // X coordinate of the event relative to the main frame's viewport in CSS pixels. - Y float64 `json:"y"` // Y coordinate of the event relative to the main frame's viewport in CSS pixels. 0 refers to the top of the viewport and Y increases as it proceeds towards the bottom of the viewport. - RadiusX float64 `json:"radiusX,omitempty,omitzero"` // X radius of the touch area (default: 1.0). - RadiusY float64 `json:"radiusY,omitempty,omitzero"` // Y radius of the touch area (default: 1.0). - RotationAngle float64 `json:"rotationAngle,omitempty,omitzero"` // Rotation angle (default: 0.0). - Force float64 `json:"force,omitempty,omitzero"` // Force (default: 1.0). - TangentialPressure float64 `json:"tangentialPressure,omitempty,omitzero"` // The normalized tangential pressure, which has a range of [-1,1] (default: 0). - TiltX float64 `json:"tiltX,omitempty,omitzero"` // The plane angle between the Y-Z plane and the plane containing both the stylus axis and the Y axis, in degrees of the range [-90,90], a positive tiltX is to the right (default: 0) - TiltY float64 `json:"tiltY,omitempty,omitzero"` // The plane angle between the X-Z plane and the plane containing both the stylus axis and the X axis, in degrees of the range [-90,90], a positive tiltY is towards the user (default: 0). - Twist int64 `json:"twist,omitempty,omitzero"` // The clockwise rotation of a pen stylus around its own major axis, in degrees in the range [0,359] (default: 0). - ID float64 `json:"id,omitempty,omitzero"` // Identifier used to track touch sources between events, must be unique within an event. + X float64 `json:"x"` // X coordinate of the event relative to the main frame's viewport in CSS pixels. + Y float64 `json:"y"` // Y coordinate of the event relative to the main frame's viewport in CSS pixels. 0 refers to the top of the viewport and Y increases as it proceeds towards the bottom of the viewport. + RadiusX *float64 `json:"radiusX,omitempty,omitzero"` // X radius of the touch area (default: 1.0). + RadiusY *float64 `json:"radiusY,omitempty,omitzero"` // Y radius of the touch area (default: 1.0). + RotationAngle float64 `json:"rotationAngle,omitempty,omitzero"` // Rotation angle (default: 0.0). + Force *float64 `json:"force,omitempty,omitzero"` // Force (default: 1.0). + TangentialPressure float64 `json:"tangentialPressure,omitempty,omitzero"` // The normalized tangential pressure, which has a range of [-1,1] (default: 0). + TiltX float64 `json:"tiltX,omitempty,omitzero"` // The plane angle between the Y-Z plane and the plane containing both the stylus axis and the Y axis, in degrees of the range [-90,90], a positive tiltX is to the right (default: 0) + TiltY float64 `json:"tiltY,omitempty,omitzero"` // The plane angle between the X-Z plane and the plane containing both the stylus axis and the X axis, in degrees of the range [-90,90], a positive tiltY is towards the user (default: 0). + Twist int64 `json:"twist,omitempty,omitzero"` // The clockwise rotation of a pen stylus around its own major axis, in degrees in the range [0,359] (default: 0). + ID *float64 `json:"id,omitempty,omitzero"` // Identifier used to track touch sources between events, must be unique within an event. } // GestureSourceType [no description]. @@ -38,29 +31,11 @@ func (t GestureSourceType) String() string { // GestureSourceType values. const ( - GestureDefault GestureSourceType = "default" - GestureTouch GestureSourceType = "touch" - GestureMouse GestureSourceType = "mouse" + GestureSourceTypeDefault GestureSourceType = "default" + GestureSourceTypeTouch GestureSourceType = "touch" + GestureSourceTypeMouse GestureSourceType = "mouse" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *GestureSourceType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch GestureSourceType(s) { - case GestureDefault: - *t = GestureDefault - case GestureTouch: - *t = GestureTouch - case GestureMouse: - *t = GestureMouse - default: - return fmt.Errorf("unknown GestureSourceType value: %v", s) - } - return nil -} - // MouseButton [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#type-MouseButton @@ -73,62 +48,22 @@ func (t MouseButton) String() string { // MouseButton values. const ( - None MouseButton = "none" - Left MouseButton = "left" - Middle MouseButton = "middle" - Right MouseButton = "right" - Back MouseButton = "back" - Forward MouseButton = "forward" + MouseButtonNone MouseButton = "none" + MouseButtonLeft MouseButton = "left" + MouseButtonMiddle MouseButton = "middle" + MouseButtonRight MouseButton = "right" + MouseButtonBack MouseButton = "back" + MouseButtonForward MouseButton = "forward" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *MouseButton) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch MouseButton(s) { - case None: - *t = None - case Left: - *t = Left - case Middle: - *t = Middle - case Right: - *t = Right - case Back: - *t = Back - case Forward: - *t = Forward - default: - return fmt.Errorf("unknown MouseButton value: %v", s) - } - return nil -} - // TimeSinceEpoch UTC time in seconds, counted from January 1, 1970. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#type-TimeSinceEpoch -type TimeSinceEpoch time.Time - -// Time returns the TimeSinceEpoch as time.Time value. -func (t TimeSinceEpoch) Time() time.Time { - return time.Time(t) -} - -// MarshalJSON satisfies [json.Marshaler]. -func (t TimeSinceEpoch) MarshalJSON() ([]byte, error) { - v := float64(time.Time(t).UnixNano() / int64(time.Second)) - return strconv.AppendFloat(make([]byte, 0, 20), v, 'f', -1, 64), nil -} +type TimeSinceEpoch float64 -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *TimeSinceEpoch) UnmarshalJSON(buf []byte) error { - f, err := strconv.ParseFloat(string(buf), 64) - if err != nil { - return err - } - *t = TimeSinceEpoch(time.Unix(0, int64(f*float64(time.Second)))) - return nil +// Float64 returns the TimeSinceEpoch as float64 value. +func (t TimeSinceEpoch) Float64() float64 { + return float64(t) } // DragDataItem [no description]. @@ -150,69 +85,6 @@ type DragData struct { DragOperationsMask int64 `json:"dragOperationsMask"` // Bit field representing allowed drag operations. Copy = 1, Link = 2, Move = 16 } -// Modifier input key modifier type. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-dispatchKeyEvent -type Modifier int64 - -// Int64 returns the Modifier as int64 value. -func (t Modifier) Int64() int64 { - return int64(t) -} - -// Modifier values. -const ( - ModifierNone Modifier = 0 - ModifierAlt Modifier = 1 - ModifierCtrl Modifier = 2 - ModifierMeta Modifier = 4 - ModifierShift Modifier = 8 -) - -// String satisfies the [fmt.Stringer] interface. -func (t Modifier) String() string { - switch t { - case ModifierNone: - return "None" - case ModifierAlt: - return "Alt" - case ModifierCtrl: - return "Ctrl" - case ModifierMeta: - return "Meta" - case ModifierShift: - return "Shift" - } - return fmt.Sprintf("Modifier(%d)", t) -} - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *Modifier) UnmarshalJSON(buf []byte) error { - s := string(buf) - v, err := strconv.ParseInt(s, 10, 64) - if err != nil { - return err - } - switch Modifier(v) { - case ModifierNone: - *t = ModifierNone - case ModifierAlt: - *t = ModifierAlt - case ModifierCtrl: - *t = ModifierCtrl - case ModifierMeta: - *t = ModifierMeta - case ModifierShift: - *t = ModifierShift - default: - return fmt.Errorf("unknown Modifier value: %v", s) - } - return nil -} - -// ModifierCommand is an alias for ModifierMeta. -const ModifierCommand Modifier = ModifierMeta - // DispatchDragEventType type of the drag event. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-dispatchDragEvent @@ -225,108 +97,48 @@ func (t DispatchDragEventType) String() string { // DispatchDragEventType values. const ( - DragEnter DispatchDragEventType = "dragEnter" - DragOver DispatchDragEventType = "dragOver" - Drop DispatchDragEventType = "drop" - DragCancel DispatchDragEventType = "dragCancel" + DispatchDragEventTypeDragEnter DispatchDragEventType = "dragEnter" + DispatchDragEventTypeDragOver DispatchDragEventType = "dragOver" + DispatchDragEventTypeDrop DispatchDragEventType = "drop" + DispatchDragEventTypeDragCancel DispatchDragEventType = "dragCancel" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DispatchDragEventType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DispatchDragEventType(s) { - case DragEnter: - *t = DragEnter - case DragOver: - *t = DragOver - case Drop: - *t = Drop - case DragCancel: - *t = DragCancel - default: - return fmt.Errorf("unknown DispatchDragEventType value: %v", s) - } - return nil -} - -// KeyType type of the key event. +// DispatchKeyEventType type of the key event. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-dispatchKeyEvent -type KeyType string +type DispatchKeyEventType string -// String returns the KeyType as string value. -func (t KeyType) String() string { +// String returns the DispatchKeyEventType as string value. +func (t DispatchKeyEventType) String() string { return string(t) } -// KeyType values. +// DispatchKeyEventType values. const ( - KeyDown KeyType = "keyDown" - KeyUp KeyType = "keyUp" - KeyRawDown KeyType = "rawKeyDown" - KeyChar KeyType = "char" + DispatchKeyEventTypeKeyDown DispatchKeyEventType = "keyDown" + DispatchKeyEventTypeKeyUp DispatchKeyEventType = "keyUp" + DispatchKeyEventTypeRawKeyDown DispatchKeyEventType = "rawKeyDown" + DispatchKeyEventTypeChar DispatchKeyEventType = "char" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *KeyType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch KeyType(s) { - case KeyDown: - *t = KeyDown - case KeyUp: - *t = KeyUp - case KeyRawDown: - *t = KeyRawDown - case KeyChar: - *t = KeyChar - default: - return fmt.Errorf("unknown KeyType value: %v", s) - } - return nil -} - -// MouseType type of the mouse event. +// DispatchMouseEventType type of the mouse event. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-dispatchMouseEvent -type MouseType string +type DispatchMouseEventType string -// String returns the MouseType as string value. -func (t MouseType) String() string { +// String returns the DispatchMouseEventType as string value. +func (t DispatchMouseEventType) String() string { return string(t) } -// MouseType values. +// DispatchMouseEventType values. const ( - MousePressed MouseType = "mousePressed" - MouseReleased MouseType = "mouseReleased" - MouseMoved MouseType = "mouseMoved" - MouseWheel MouseType = "mouseWheel" + DispatchMouseEventTypeMousePressed DispatchMouseEventType = "mousePressed" + DispatchMouseEventTypeMouseReleased DispatchMouseEventType = "mouseReleased" + DispatchMouseEventTypeMouseMoved DispatchMouseEventType = "mouseMoved" + DispatchMouseEventTypeMouseWheel DispatchMouseEventType = "mouseWheel" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *MouseType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch MouseType(s) { - case MousePressed: - *t = MousePressed - case MouseReleased: - *t = MouseReleased - case MouseMoved: - *t = MouseMoved - case MouseWheel: - *t = MouseWheel - default: - return fmt.Errorf("unknown MouseType value: %v", s) - } - return nil -} - // DispatchMouseEventPointerType pointer type (default: "mouse"). // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-dispatchMouseEvent @@ -339,62 +151,44 @@ func (t DispatchMouseEventPointerType) String() string { // DispatchMouseEventPointerType values. const ( - Mouse DispatchMouseEventPointerType = "mouse" - Pen DispatchMouseEventPointerType = "pen" + DispatchMouseEventPointerTypeMouse DispatchMouseEventPointerType = "mouse" + DispatchMouseEventPointerTypePen DispatchMouseEventPointerType = "pen" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DispatchMouseEventPointerType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DispatchMouseEventPointerType(s) { - case Mouse: - *t = Mouse - case Pen: - *t = Pen - default: - return fmt.Errorf("unknown DispatchMouseEventPointerType value: %v", s) - } - return nil -} - -// TouchType type of the touch event. TouchEnd and TouchCancel must not -// contain any touch points, while TouchStart and TouchMove must contains at -// least one. +// DispatchTouchEventType type of the touch event. TouchEnd and TouchCancel +// must not contain any touch points, while TouchStart and TouchMove must +// contains at least one. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-dispatchTouchEvent -type TouchType string +type DispatchTouchEventType string -// String returns the TouchType as string value. -func (t TouchType) String() string { +// String returns the DispatchTouchEventType as string value. +func (t DispatchTouchEventType) String() string { return string(t) } -// TouchType values. +// DispatchTouchEventType values. const ( - TouchStart TouchType = "touchStart" - TouchEnd TouchType = "touchEnd" - TouchMove TouchType = "touchMove" - TouchCancel TouchType = "touchCancel" + DispatchTouchEventTypeTouchStart DispatchTouchEventType = "touchStart" + DispatchTouchEventTypeTouchEnd DispatchTouchEventType = "touchEnd" + DispatchTouchEventTypeTouchMove DispatchTouchEventType = "touchMove" + DispatchTouchEventTypeTouchCancel DispatchTouchEventType = "touchCancel" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *TouchType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) +// EmulateTouchFromMouseEventType type of the mouse event. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-emulateTouchFromMouseEvent +type EmulateTouchFromMouseEventType string - switch TouchType(s) { - case TouchStart: - *t = TouchStart - case TouchEnd: - *t = TouchEnd - case TouchMove: - *t = TouchMove - case TouchCancel: - *t = TouchCancel - default: - return fmt.Errorf("unknown TouchType value: %v", s) - } - return nil +// String returns the EmulateTouchFromMouseEventType as string value. +func (t EmulateTouchFromMouseEventType) String() string { + return string(t) } + +// EmulateTouchFromMouseEventType values. +const ( + EmulateTouchFromMouseEventTypeMousePressed EmulateTouchFromMouseEventType = "mousePressed" + EmulateTouchFromMouseEventTypeMouseReleased EmulateTouchFromMouseEventType = "mouseReleased" + EmulateTouchFromMouseEventTypeMouseMoved EmulateTouchFromMouseEventType = "mouseMoved" + EmulateTouchFromMouseEventTypeMouseWheel EmulateTouchFromMouseEventType = "mouseWheel" +) diff --git a/vendor/github.com/chromedp/cdproto/inspector/events.go b/vendor/github.com/chromedp/cdproto/inspector/events.go index 29e3dc40c..beee059da 100644 --- a/vendor/github.com/chromedp/cdproto/inspector/events.go +++ b/vendor/github.com/chromedp/cdproto/inspector/events.go @@ -1,13 +1,13 @@ -package inspector +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package inspector // EventDetached fired when remote debugging connection is about to be // terminated. Contains detach reason. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Inspector#event-detached type EventDetached struct { - Reason DetachReason `json:"reason"` // The reason why connection has been terminated. + Reason string `json:"reason"` // The reason why connection has been terminated. } // EventTargetCrashed fired when debugging target has crashed. diff --git a/vendor/github.com/chromedp/cdproto/inspector/inspector.go b/vendor/github.com/chromedp/cdproto/inspector/inspector.go index 4461dd69f..a3ba7303b 100644 --- a/vendor/github.com/chromedp/cdproto/inspector/inspector.go +++ b/vendor/github.com/chromedp/cdproto/inspector/inspector.go @@ -1,46 +1,47 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package inspector provides the Chrome DevTools Protocol // commands, types, and events for the Inspector domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package inspector -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// DisableParams disables inspector domain notifications. -type DisableParams struct{} - // Disable disables inspector domain notifications. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Inspector#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes Inspector.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// EnableParams enables inspector domain notifications. -type EnableParams struct{} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} // Enable enables inspector domain notifications. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Inspector#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} - -// Do executes Inspector.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) -} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} + +// Detached fired when remote debugging connection is about to be terminated. +// Contains detach reason. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Inspector#event-detached +var Detached = cdp.Event[EventDetached]{Method: "Inspector.detached"} + +// TargetCrashed fired when debugging target has crashed. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Inspector#event-targetCrashed +var TargetCrashed = cdp.Event[EventTargetCrashed]{Method: "Inspector.targetCrashed"} + +// TargetReloadedAfterCrash fired when debugging target has reloaded after +// crash. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Inspector#event-targetReloadedAfterCrash +var TargetReloadedAfterCrash = cdp.Event[EventTargetReloadedAfterCrash]{Method: "Inspector.targetReloadedAfterCrash"} + +// WorkerScriptLoaded fired on worker targets when main worker script and any +// imported scripts have been evaluated. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Inspector#event-workerScriptLoaded +var WorkerScriptLoaded = cdp.Event[EventWorkerScriptLoaded]{Method: "Inspector.workerScriptLoaded"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/inspector/types.go b/vendor/github.com/chromedp/cdproto/inspector/types.go deleted file mode 100644 index 1e47c2fb5..000000000 --- a/vendor/github.com/chromedp/cdproto/inspector/types.go +++ /dev/null @@ -1,46 +0,0 @@ -package inspector - -import ( - "fmt" - "strings" -) - -// Code generated by cdproto-gen. DO NOT EDIT. - -// DetachReason detach reason. -// -// See: ( -- none -- ) -type DetachReason string - -// String returns the DetachReason as string value. -func (t DetachReason) String() string { - return string(t) -} - -// DetachReason values. -const ( - DetachReasonTargetClosed DetachReason = "target_closed" - DetachReasonCanceledByUser DetachReason = "canceled_by_user" - DetachReasonReplacedWithDevtools DetachReason = "replaced_with_devtools" - DetachReasonRenderProcessGone DetachReason = "Render process gone." -) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DetachReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DetachReason(s) { - case DetachReasonTargetClosed: - *t = DetachReasonTargetClosed - case DetachReasonCanceledByUser: - *t = DetachReasonCanceledByUser - case DetachReasonReplacedWithDevtools: - *t = DetachReasonReplacedWithDevtools - case DetachReasonRenderProcessGone: - *t = DetachReasonRenderProcessGone - default: - return fmt.Errorf("unknown DetachReason value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/io/io.go b/vendor/github.com/chromedp/cdproto/io/io.go index 17cb95cf4..de45f7c19 100644 --- a/vendor/github.com/chromedp/cdproto/io/io.go +++ b/vendor/github.com/chromedp/cdproto/io/io.go @@ -1,21 +1,22 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package io provides the Chrome DevTools Protocol // commands, types, and events for the IO domain. // // Input/Output operations for streams produced by DevTools. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package io -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" + "encoding/base64" + "fmt" "github.com/chromedp/cdproto/cdp" - "github.com/chromedp/cdproto/runtime" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" ) -// CloseParams close the stream, discard any temporary backing storage. +// CloseParams are the parameters of the command IO.close. type CloseParams struct { Handle StreamHandle `json:"handle"` // Handle of the stream to close. } @@ -23,123 +24,52 @@ type CloseParams struct { // Close close the stream, discard any temporary backing storage. // // See: https://chromedevtools.github.io/devtools-protocol/tot/IO#method-close -// -// parameters: -// -// handle - Handle of the stream to close. -func Close(handle StreamHandle) *CloseParams { - return &CloseParams{ - Handle: handle, - } -} - -// Do executes IO.close against the provided context. -func (p *CloseParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClose, p, nil) -} +var Close = cdp.Command[CloseParams, cdp.Empty]{Method: CommandClose} -// ReadParams read a chunk of the stream. +// ReadParams are the parameters of the command IO.read. type ReadParams struct { Handle StreamHandle `json:"handle"` // Handle of the stream to read. - Offset int64 `json:"offset,omitempty,omitzero"` // 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 *int64 `json:"offset,omitempty,omitzero"` // 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. Size int64 `json:"size,omitempty,omitzero"` // Maximum number of bytes to read (left upon the agent discretion if not specified). } -// Read read a chunk of the stream. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/IO#method-read -// -// parameters: -// -// handle - Handle of the stream to read. -func Read(handle StreamHandle) *ReadParams { - return &ReadParams{ - Handle: handle, - } -} - -// WithOffset 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. -func (p ReadParams) WithOffset(offset int64) *ReadParams { - p.Offset = offset - return &p -} - -// WithSize maximum number of bytes to read (left upon the agent discretion -// if not specified). -func (p ReadParams) WithSize(size int64) *ReadParams { - p.Size = size - return &p -} - -// ReadReturns return values. -type ReadReturns struct { +// ReadResult is the result of the command IO.read. +type ReadResult struct { Base64encoded bool `json:"base64Encoded"` // Set if the data is base64-encoded - Data string `json:"data,omitempty,omitzero"` // Data that were read. + Data []byte `json:"data,omitempty,omitzero"` // Data that were read. EOF bool `json:"eof"` // Set if the end-of-file condition occurred while reading. } -// Do executes IO.read against the provided context. -// -// returns: -// -// data - Data that were read. -// eof - Set if the end-of-file condition occurred while reading. -func (p *ReadParams) Do(ctx context.Context) (data string, eof bool, err error) { - // execute - var res ReadReturns - err = cdp.Execute(ctx, CommandRead, p, &res) - if err != nil { - return "", false, err +// UnmarshalJSON decodes the value. The browser sends data as text, or as +// base64 when r.Base64encoded, and Data holds the decoded bytes. +func (r *ReadResult) UnmarshalJSON(buf []byte) error { + type plain ReadResult + aux := struct { + *plain + Data string `json:"data"` + }{plain: (*plain)(r)} + if err := jsonv2.Unmarshal(buf, &aux); err != nil { + return err } - - return res.Data, res.EOF, nil -} - -// ResolveBlobParams return UUID of Blob object specified by a remote object -// id. -type ResolveBlobParams struct { - ObjectID runtime.RemoteObjectID `json:"objectId"` // Object id of a Blob object wrapper. -} - -// ResolveBlob return UUID of Blob object specified by a remote object id. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/IO#method-resolveBlob -// -// parameters: -// -// objectID - Object id of a Blob object wrapper. -func ResolveBlob(objectID runtime.RemoteObjectID) *ResolveBlobParams { - return &ResolveBlobParams{ - ObjectID: objectID, + if r.Base64encoded { + b, err := base64.StdEncoding.DecodeString(aux.Data) + if err != nil { + return fmt.Errorf("decoding data: %w", err) + } + r.Data = b + return nil } + r.Data = []byte(aux.Data) + return nil } -// ResolveBlobReturns return values. -type ResolveBlobReturns struct { - UUID string `json:"uuid,omitempty,omitzero"` // UUID of the specified Blob. -} - -// Do executes IO.resolveBlob against the provided context. -// -// returns: +// Read read a chunk of the stream. // -// uuid - UUID of the specified Blob. -func (p *ResolveBlobParams) Do(ctx context.Context) (uuid string, err error) { - // execute - var res ResolveBlobReturns - err = cdp.Execute(ctx, CommandResolveBlob, p, &res) - if err != nil { - return "", err - } - - return res.UUID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/IO#method-read +var Read = cdp.Command[ReadParams, ReadResult]{Method: CommandRead} // Command names. const ( - CommandClose = "IO.close" - CommandRead = "IO.read" - CommandResolveBlob = "IO.resolveBlob" + CommandClose = "IO.close" + CommandRead = "IO.read" ) diff --git a/vendor/github.com/chromedp/cdproto/io/types.go b/vendor/github.com/chromedp/cdproto/io/types.go index 5f45a6c71..f297d292a 100644 --- a/vendor/github.com/chromedp/cdproto/io/types.go +++ b/vendor/github.com/chromedp/cdproto/io/types.go @@ -1,6 +1,6 @@ -package io +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package io // StreamHandle this is either obtained from another method or specified as // blob: where is an UUID of a Blob. diff --git a/vendor/github.com/chromedp/cdproto/layertree/events.go b/vendor/github.com/chromedp/cdproto/layertree/events.go index 517efe582..e90d614bb 100644 --- a/vendor/github.com/chromedp/cdproto/layertree/events.go +++ b/vendor/github.com/chromedp/cdproto/layertree/events.go @@ -1,6 +1,6 @@ -package layertree +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package layertree import ( "github.com/chromedp/cdproto/dom" diff --git a/vendor/github.com/chromedp/cdproto/layertree/layertree.go b/vendor/github.com/chromedp/cdproto/layertree/layertree.go index ac17497fb..a707a0794 100644 --- a/vendor/github.com/chromedp/cdproto/layertree/layertree.go +++ b/vendor/github.com/chromedp/cdproto/layertree/layertree.go @@ -1,171 +1,80 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package layertree provides the Chrome DevTools Protocol // commands, types, and events for the LayerTree domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package layertree -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" "github.com/chromedp/cdproto/dom" - "github.com/go-json-experiment/json/jsontext" ) -// CompositingReasonsParams provides the reasons why the given layer was -// composited. +// CompositingReasonsParams are the parameters of the command +// LayerTree.compositingReasons. type CompositingReasonsParams struct { LayerID LayerID `json:"layerId"` // The id of the layer for which we want to get the reasons it was composited. } -// CompositingReasons provides the reasons why the given layer was -// composited. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-compositingReasons -// -// parameters: -// -// layerID - The id of the layer for which we want to get the reasons it was composited. -func CompositingReasons(layerID LayerID) *CompositingReasonsParams { - return &CompositingReasonsParams{ - LayerID: layerID, - } -} - -// CompositingReasonsReturns return values. -type CompositingReasonsReturns struct { +// CompositingReasonsResult is the result of the command +// LayerTree.compositingReasons. +type CompositingReasonsResult struct { CompositingReasons []string `json:"compositingReasons,omitempty,omitzero"` // A list of strings specifying reasons for the given layer to become composited. CompositingReasonIDs []string `json:"compositingReasonIds,omitempty,omitzero"` // A list of strings specifying reason IDs for the given layer to become composited. } -// Do executes LayerTree.compositingReasons against the provided context. -// -// returns: +// CompositingReasons provides the reasons why the given layer was +// composited. // -// compositingReasons - A list of strings specifying reasons for the given layer to become composited. -// compositingReasonIDs - A list of strings specifying reason IDs for the given layer to become composited. -func (p *CompositingReasonsParams) Do(ctx context.Context) (compositingReasons []string, compositingReasonIDs []string, err error) { - // execute - var res CompositingReasonsReturns - err = cdp.Execute(ctx, CommandCompositingReasons, p, &res) - if err != nil { - return nil, nil, err - } - - return res.CompositingReasons, res.CompositingReasonIDs, nil -} - -// DisableParams disables compositing tree inspection. -type DisableParams struct{} +// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-compositingReasons +var CompositingReasons = cdp.Command[CompositingReasonsParams, CompositingReasonsResult]{Method: CommandCompositingReasons} // Disable disables compositing tree inspection. // // See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes LayerTree.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// EnableParams enables compositing tree inspection. -type EnableParams struct{} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} // Enable enables compositing tree inspection. // // See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} - -// Do executes LayerTree.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) -} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} -// LoadSnapshotParams returns the snapshot identifier. +// LoadSnapshotParams are the parameters of the command +// LayerTree.loadSnapshot. type LoadSnapshotParams struct { Tiles []*PictureTile `json:"tiles"` // An array of tiles composing the snapshot. } -// LoadSnapshot returns the snapshot identifier. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-loadSnapshot -// -// parameters: -// -// tiles - An array of tiles composing the snapshot. -func LoadSnapshot(tiles []*PictureTile) *LoadSnapshotParams { - return &LoadSnapshotParams{ - Tiles: tiles, - } -} - -// LoadSnapshotReturns return values. -type LoadSnapshotReturns struct { +// LoadSnapshotResult is the result of the command LayerTree.loadSnapshot. +type LoadSnapshotResult struct { SnapshotID SnapshotID `json:"snapshotId,omitempty,omitzero"` // The id of the snapshot. } -// Do executes LayerTree.loadSnapshot against the provided context. -// -// returns: +// LoadSnapshot returns the snapshot identifier. // -// snapshotID - The id of the snapshot. -func (p *LoadSnapshotParams) Do(ctx context.Context) (snapshotID SnapshotID, err error) { - // execute - var res LoadSnapshotReturns - err = cdp.Execute(ctx, CommandLoadSnapshot, p, &res) - if err != nil { - return "", err - } - - return res.SnapshotID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-loadSnapshot +var LoadSnapshot = cdp.Command[LoadSnapshotParams, LoadSnapshotResult]{Method: CommandLoadSnapshot} -// MakeSnapshotParams returns the layer snapshot identifier. +// MakeSnapshotParams are the parameters of the command +// LayerTree.makeSnapshot. type MakeSnapshotParams struct { LayerID LayerID `json:"layerId"` // The id of the layer. } -// MakeSnapshot returns the layer snapshot identifier. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-makeSnapshot -// -// parameters: -// -// layerID - The id of the layer. -func MakeSnapshot(layerID LayerID) *MakeSnapshotParams { - return &MakeSnapshotParams{ - LayerID: layerID, - } -} - -// MakeSnapshotReturns return values. -type MakeSnapshotReturns struct { +// MakeSnapshotResult is the result of the command LayerTree.makeSnapshot. +type MakeSnapshotResult struct { SnapshotID SnapshotID `json:"snapshotId,omitempty,omitzero"` // The id of the layer snapshot. } -// Do executes LayerTree.makeSnapshot against the provided context. -// -// returns: +// MakeSnapshot returns the layer snapshot identifier. // -// snapshotID - The id of the layer snapshot. -func (p *MakeSnapshotParams) Do(ctx context.Context) (snapshotID SnapshotID, err error) { - // execute - var res MakeSnapshotReturns - err = cdp.Execute(ctx, CommandMakeSnapshot, p, &res) - if err != nil { - return "", err - } - - return res.SnapshotID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-makeSnapshot +var MakeSnapshot = cdp.Command[MakeSnapshotParams, MakeSnapshotResult]{Method: CommandMakeSnapshot} -// ProfileSnapshotParams [no description]. +// ProfileSnapshotParams are the parameters of the command +// LayerTree.profileSnapshot. type ProfileSnapshotParams struct { SnapshotID SnapshotID `json:"snapshotId"` // The id of the layer snapshot. MinRepeatCount int64 `json:"minRepeatCount,omitempty,omitzero"` // The maximum number of times to replay the snapshot (1, if not specified). @@ -173,60 +82,19 @@ type ProfileSnapshotParams struct { ClipRect *dom.Rect `json:"clipRect,omitempty,omitzero"` // The clip rectangle to apply when replaying the snapshot. } -// ProfileSnapshot [no description]. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-profileSnapshot -// -// parameters: -// -// snapshotID - The id of the layer snapshot. -func ProfileSnapshot(snapshotID SnapshotID) *ProfileSnapshotParams { - return &ProfileSnapshotParams{ - SnapshotID: snapshotID, - } -} - -// WithMinRepeatCount the maximum number of times to replay the snapshot (1, -// if not specified). -func (p ProfileSnapshotParams) WithMinRepeatCount(minRepeatCount int64) *ProfileSnapshotParams { - p.MinRepeatCount = minRepeatCount - return &p -} - -// WithMinDuration the minimum duration (in seconds) to replay the snapshot. -func (p ProfileSnapshotParams) WithMinDuration(minDuration float64) *ProfileSnapshotParams { - p.MinDuration = minDuration - return &p -} - -// WithClipRect the clip rectangle to apply when replaying the snapshot. -func (p ProfileSnapshotParams) WithClipRect(clipRect *dom.Rect) *ProfileSnapshotParams { - p.ClipRect = clipRect - return &p -} - -// ProfileSnapshotReturns return values. -type ProfileSnapshotReturns struct { +// ProfileSnapshotResult is the result of the command +// LayerTree.profileSnapshot. +type ProfileSnapshotResult struct { Timings []PaintProfile `json:"timings,omitempty,omitzero"` // The array of paint profiles, one per run. } -// Do executes LayerTree.profileSnapshot against the provided context. -// -// returns: +// ProfileSnapshot [no description]. // -// timings - The array of paint profiles, one per run. -func (p *ProfileSnapshotParams) Do(ctx context.Context) (timings []PaintProfile, err error) { - // execute - var res ProfileSnapshotReturns - err = cdp.Execute(ctx, CommandProfileSnapshot, p, &res) - if err != nil { - return nil, err - } - - return res.Timings, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-profileSnapshot +var ProfileSnapshot = cdp.Command[ProfileSnapshotParams, ProfileSnapshotResult]{Method: CommandProfileSnapshot} -// ReleaseSnapshotParams releases layer snapshot captured by the back-end. +// ReleaseSnapshotParams are the parameters of the command +// LayerTree.releaseSnapshot. type ReleaseSnapshotParams struct { SnapshotID SnapshotID `json:"snapshotId"` // The id of the layer snapshot. } @@ -234,124 +102,55 @@ type ReleaseSnapshotParams struct { // ReleaseSnapshot releases layer snapshot captured by the back-end. // // See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-releaseSnapshot -// -// parameters: -// -// snapshotID - The id of the layer snapshot. -func ReleaseSnapshot(snapshotID SnapshotID) *ReleaseSnapshotParams { - return &ReleaseSnapshotParams{ - SnapshotID: snapshotID, - } -} +var ReleaseSnapshot = cdp.Command[ReleaseSnapshotParams, cdp.Empty]{Method: CommandReleaseSnapshot} -// Do executes LayerTree.releaseSnapshot against the provided context. -func (p *ReleaseSnapshotParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandReleaseSnapshot, p, nil) -} - -// ReplaySnapshotParams replays the layer snapshot and returns the resulting -// bitmap. +// ReplaySnapshotParams are the parameters of the command +// LayerTree.replaySnapshot. type ReplaySnapshotParams struct { SnapshotID SnapshotID `json:"snapshotId"` // The id of the layer snapshot. FromStep int64 `json:"fromStep,omitempty,omitzero"` // The first step to replay from (replay from the very start if not specified). - ToStep int64 `json:"toStep,omitempty,omitzero"` // The last step to replay to (replay till the end if not specified). + ToStep *int64 `json:"toStep,omitempty,omitzero"` // The last step to replay to (replay till the end if not specified). Scale float64 `json:"scale,omitempty,omitzero"` // The scale to apply while replaying (defaults to 1). } -// ReplaySnapshot replays the layer snapshot and returns the resulting -// bitmap. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-replaySnapshot -// -// parameters: -// -// snapshotID - The id of the layer snapshot. -func ReplaySnapshot(snapshotID SnapshotID) *ReplaySnapshotParams { - return &ReplaySnapshotParams{ - SnapshotID: snapshotID, - } -} - -// WithFromStep the first step to replay from (replay from the very start if -// not specified). -func (p ReplaySnapshotParams) WithFromStep(fromStep int64) *ReplaySnapshotParams { - p.FromStep = fromStep - return &p -} - -// WithToStep the last step to replay to (replay till the end if not -// specified). -func (p ReplaySnapshotParams) WithToStep(toStep int64) *ReplaySnapshotParams { - p.ToStep = toStep - return &p -} - -// WithScale the scale to apply while replaying (defaults to 1). -func (p ReplaySnapshotParams) WithScale(scale float64) *ReplaySnapshotParams { - p.Scale = scale - return &p -} - -// ReplaySnapshotReturns return values. -type ReplaySnapshotReturns struct { +// ReplaySnapshotResult is the result of the command +// LayerTree.replaySnapshot. +type ReplaySnapshotResult struct { DataURL string `json:"dataURL,omitempty,omitzero"` // A data: URL for resulting image. } -// Do executes LayerTree.replaySnapshot against the provided context. -// -// returns: +// ReplaySnapshot replays the layer snapshot and returns the resulting +// bitmap. // -// dataURL - A data: URL for resulting image. -func (p *ReplaySnapshotParams) Do(ctx context.Context) (dataURL string, err error) { - // execute - var res ReplaySnapshotReturns - err = cdp.Execute(ctx, CommandReplaySnapshot, p, &res) - if err != nil { - return "", err - } - - return res.DataURL, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-replaySnapshot +var ReplaySnapshot = cdp.Command[ReplaySnapshotParams, ReplaySnapshotResult]{Method: CommandReplaySnapshot} -// SnapshotCommandLogParams replays the layer snapshot and returns canvas -// log. +// SnapshotCommandLogParams are the parameters of the command +// LayerTree.snapshotCommandLog. type SnapshotCommandLogParams struct { SnapshotID SnapshotID `json:"snapshotId"` // The id of the layer snapshot. } +// SnapshotCommandLogResult is the result of the command +// LayerTree.snapshotCommandLog. +type SnapshotCommandLogResult struct { + CommandLog []jsonv2.Value `json:"commandLog,omitempty,omitzero"` // The array of canvas function calls. +} + // SnapshotCommandLog replays the layer snapshot and returns canvas log. // // See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-snapshotCommandLog -// -// parameters: -// -// snapshotID - The id of the layer snapshot. -func SnapshotCommandLog(snapshotID SnapshotID) *SnapshotCommandLogParams { - return &SnapshotCommandLogParams{ - SnapshotID: snapshotID, - } -} - -// SnapshotCommandLogReturns return values. -type SnapshotCommandLogReturns struct { - CommandLog []jsontext.Value `json:"commandLog,omitempty,omitzero"` // The array of canvas function calls. -} +var SnapshotCommandLog = cdp.Command[SnapshotCommandLogParams, SnapshotCommandLogResult]{Method: CommandSnapshotCommandLog} -// Do executes LayerTree.snapshotCommandLog against the provided context. +// LayerPainted [no description]. // -// returns: -// -// commandLog - The array of canvas function calls. -func (p *SnapshotCommandLogParams) Do(ctx context.Context) (commandLog []jsontext.Value, err error) { - // execute - var res SnapshotCommandLogReturns - err = cdp.Execute(ctx, CommandSnapshotCommandLog, p, &res) - if err != nil { - return nil, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#event-layerPainted +var LayerPainted = cdp.Event[EventLayerPainted]{Method: "LayerTree.layerPainted"} - return res.CommandLog, nil -} +// LayerTreeDidChange [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#event-layerTreeDidChange +var LayerTreeDidChange = cdp.Event[EventLayerTreeDidChange]{Method: "LayerTree.layerTreeDidChange"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/layertree/types.go b/vendor/github.com/chromedp/cdproto/layertree/types.go index bd4924d0b..df3db126c 100644 --- a/vendor/github.com/chromedp/cdproto/layertree/types.go +++ b/vendor/github.com/chromedp/cdproto/layertree/types.go @@ -1,11 +1,8 @@ -package layertree +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package layertree import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/dom" ) @@ -55,7 +52,7 @@ type StickyPositionConstraint struct { type PictureTile struct { X float64 `json:"x"` // Offset from owning layer left boundary Y float64 `json:"y"` // Offset from owning layer top boundary - Picture string `json:"picture"` // Base64-encoded snapshot data. + Picture []byte `json:"picture"` // Base64-encoded snapshot data. } // Layer information about a compositing layer. @@ -101,21 +98,3 @@ const ( ScrollRectTypeTouchEventHandler ScrollRectType = "TouchEventHandler" ScrollRectTypeWheelEventHandler ScrollRectType = "WheelEventHandler" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ScrollRectType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ScrollRectType(s) { - case ScrollRectTypeRepaintsOnScroll: - *t = ScrollRectTypeRepaintsOnScroll - case ScrollRectTypeTouchEventHandler: - *t = ScrollRectTypeTouchEventHandler - case ScrollRectTypeWheelEventHandler: - *t = ScrollRectTypeWheelEventHandler - default: - return fmt.Errorf("unknown ScrollRectType value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/log/events.go b/vendor/github.com/chromedp/cdproto/log/events.go index 8f9b4a9e0..1fc8b937a 100644 --- a/vendor/github.com/chromedp/cdproto/log/events.go +++ b/vendor/github.com/chromedp/cdproto/log/events.go @@ -1,6 +1,6 @@ -package log +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package log // EventEntryAdded issued when new message was logged. // diff --git a/vendor/github.com/chromedp/cdproto/log/log.go b/vendor/github.com/chromedp/cdproto/log/log.go index bce14422a..2e4bf0275 100644 --- a/vendor/github.com/chromedp/cdproto/log/log.go +++ b/vendor/github.com/chromedp/cdproto/log/log.go @@ -1,69 +1,36 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package log provides the Chrome DevTools Protocol // commands, types, and events for the Log domain. // // Provides access to log entries. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package log -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// ClearParams clears the log. -type ClearParams struct{} - // Clear clears the log. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Log#method-clear -func Clear() *ClearParams { - return &ClearParams{} -} - -// Do executes Log.clear against the provided context. -func (p *ClearParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClear, nil, nil) -} - -// DisableParams disables log domain, prevents further log entries from being -// reported to the client. -type DisableParams struct{} +var Clear = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandClear} // Disable disables log domain, prevents further log entries from being // reported to the client. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Log#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes Log.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// EnableParams enables log domain, sends the entries collected so far to the -// client by means of the entryAdded notification. -type EnableParams struct{} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} // Enable enables log domain, sends the entries collected so far to the // client by means of the entryAdded notification. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Log#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} - -// Do executes Log.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) -} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} -// StartViolationsReportParams start violation reporting. +// StartViolationsReportParams are the parameters of the command +// Log.startViolationsReport. type StartViolationsReportParams struct { Config []*ViolationSetting `json:"config"` // Configuration for violations. } @@ -71,35 +38,17 @@ type StartViolationsReportParams struct { // StartViolationsReport start violation reporting. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Log#method-startViolationsReport -// -// parameters: -// -// config - Configuration for violations. -func StartViolationsReport(config []*ViolationSetting) *StartViolationsReportParams { - return &StartViolationsReportParams{ - Config: config, - } -} - -// Do executes Log.startViolationsReport against the provided context. -func (p *StartViolationsReportParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStartViolationsReport, p, nil) -} - -// StopViolationsReportParams stop violation reporting. -type StopViolationsReportParams struct{} +var StartViolationsReport = cdp.Command[StartViolationsReportParams, cdp.Empty]{Method: CommandStartViolationsReport} // StopViolationsReport stop violation reporting. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Log#method-stopViolationsReport -func StopViolationsReport() *StopViolationsReportParams { - return &StopViolationsReportParams{} -} +var StopViolationsReport = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandStopViolationsReport} -// Do executes Log.stopViolationsReport against the provided context. -func (p *StopViolationsReportParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStopViolationsReport, nil, nil) -} +// EntryAdded issued when new message was logged. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Log#event-entryAdded +var EntryAdded = cdp.Event[EventEntryAdded]{Method: "Log.entryAdded"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/log/types.go b/vendor/github.com/chromedp/cdproto/log/types.go index 08e33cc31..738a68195 100644 --- a/vendor/github.com/chromedp/cdproto/log/types.go +++ b/vendor/github.com/chromedp/cdproto/log/types.go @@ -1,11 +1,8 @@ -package log +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package log import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/network" "github.com/chromedp/cdproto/runtime" ) @@ -14,11 +11,11 @@ import ( // // See: https://chromedevtools.github.io/devtools-protocol/tot/Log#type-LogEntry type Entry struct { - Source Source `json:"source"` // Log entry source. - Level Level `json:"level"` // Log entry severity. + Source EntrySource `json:"source"` // Log entry source. + Level EntryLevel `json:"level"` // Log entry severity. Text string `json:"text"` // Logged text. Category EntryCategory `json:"category,omitempty,omitzero"` - Timestamp *runtime.Timestamp `json:"timestamp"` // Timestamp when this entry was added. + Timestamp runtime.Timestamp `json:"timestamp"` // Timestamp when this entry was added. URL string `json:"url,omitempty,omitzero"` // URL of the resource if known. LineNumber int64 `json:"lineNumber,omitempty,omitzero"` // Line number in the resource. StackTrace *runtime.StackTrace `json:"stackTrace,omitempty,omitzero"` // JavaScript stack trace. @@ -31,113 +28,55 @@ type Entry struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Log#type-ViolationSetting type ViolationSetting struct { - Name Violation `json:"name"` // Violation type. - Threshold float64 `json:"threshold"` // Time threshold to trigger upon. + Name ViolationSettingName `json:"name"` // Violation type. + Threshold float64 `json:"threshold"` // Time threshold to trigger upon. } -// Source log entry source. +// EntrySource log entry source. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Log#type-LogEntry -type Source string +type EntrySource string -// String returns the Source as string value. -func (t Source) String() string { +// String returns the EntrySource as string value. +func (t EntrySource) String() string { return string(t) } -// Source values. +// EntrySource values. const ( - SourceXML Source = "xml" - SourceJavascript Source = "javascript" - SourceNetwork Source = "network" - SourceStorage Source = "storage" - SourceAppcache Source = "appcache" - SourceRendering Source = "rendering" - SourceSecurity Source = "security" - SourceDeprecation Source = "deprecation" - SourceWorker Source = "worker" - SourceViolation Source = "violation" - SourceIntervention Source = "intervention" - SourceRecommendation Source = "recommendation" - SourceOther Source = "other" + EntrySourceXML EntrySource = "xml" + EntrySourceJavascript EntrySource = "javascript" + EntrySourceNetwork EntrySource = "network" + EntrySourceStorage EntrySource = "storage" + EntrySourceAppcache EntrySource = "appcache" + EntrySourceRendering EntrySource = "rendering" + EntrySourceSecurity EntrySource = "security" + EntrySourceDeprecation EntrySource = "deprecation" + EntrySourceWorker EntrySource = "worker" + EntrySourceViolation EntrySource = "violation" + EntrySourceIntervention EntrySource = "intervention" + EntrySourceRecommendation EntrySource = "recommendation" + EntrySourceOther EntrySource = "other" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *Source) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch Source(s) { - case SourceXML: - *t = SourceXML - case SourceJavascript: - *t = SourceJavascript - case SourceNetwork: - *t = SourceNetwork - case SourceStorage: - *t = SourceStorage - case SourceAppcache: - *t = SourceAppcache - case SourceRendering: - *t = SourceRendering - case SourceSecurity: - *t = SourceSecurity - case SourceDeprecation: - *t = SourceDeprecation - case SourceWorker: - *t = SourceWorker - case SourceViolation: - *t = SourceViolation - case SourceIntervention: - *t = SourceIntervention - case SourceRecommendation: - *t = SourceRecommendation - case SourceOther: - *t = SourceOther - default: - return fmt.Errorf("unknown Source value: %v", s) - } - return nil -} - -// Level log entry severity. +// EntryLevel log entry severity. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Log#type-LogEntry -type Level string +type EntryLevel string -// String returns the Level as string value. -func (t Level) String() string { +// String returns the EntryLevel as string value. +func (t EntryLevel) String() string { return string(t) } -// Level values. +// EntryLevel values. const ( - LevelVerbose Level = "verbose" - LevelInfo Level = "info" - LevelWarning Level = "warning" - LevelError Level = "error" + EntryLevelVerbose EntryLevel = "verbose" + EntryLevelInfo EntryLevel = "info" + EntryLevelWarning EntryLevel = "warning" + EntryLevelError EntryLevel = "error" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *Level) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch Level(s) { - case LevelVerbose: - *t = LevelVerbose - case LevelInfo: - *t = LevelInfo - case LevelWarning: - *t = LevelWarning - case LevelError: - *t = LevelError - default: - return fmt.Errorf("unknown Level value: %v", s) - } - return nil -} - // EntryCategory [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Log#type-LogEntry @@ -153,63 +92,23 @@ const ( EntryCategoryCors EntryCategory = "cors" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *EntryCategory) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch EntryCategory(s) { - case EntryCategoryCors: - *t = EntryCategoryCors - default: - return fmt.Errorf("unknown EntryCategory value: %v", s) - } - return nil -} - -// Violation violation type. +// ViolationSettingName violation type. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Log#type-ViolationSetting -type Violation string +type ViolationSettingName string -// String returns the Violation as string value. -func (t Violation) String() string { +// String returns the ViolationSettingName as string value. +func (t ViolationSettingName) String() string { return string(t) } -// Violation values. +// ViolationSettingName values. const ( - ViolationLongTask Violation = "longTask" - ViolationLongLayout Violation = "longLayout" - ViolationBlockedEvent Violation = "blockedEvent" - ViolationBlockedParser Violation = "blockedParser" - ViolationDiscouragedAPIUse Violation = "discouragedAPIUse" - ViolationHandler Violation = "handler" - ViolationRecurringHandler Violation = "recurringHandler" + ViolationSettingNameLongTask ViolationSettingName = "longTask" + ViolationSettingNameLongLayout ViolationSettingName = "longLayout" + ViolationSettingNameBlockedEvent ViolationSettingName = "blockedEvent" + ViolationSettingNameBlockedParser ViolationSettingName = "blockedParser" + ViolationSettingNameDiscouragedAPIUse ViolationSettingName = "discouragedAPIUse" + ViolationSettingNameHandler ViolationSettingName = "handler" + ViolationSettingNameRecurringHandler ViolationSettingName = "recurringHandler" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *Violation) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch Violation(s) { - case ViolationLongTask: - *t = ViolationLongTask - case ViolationLongLayout: - *t = ViolationLongLayout - case ViolationBlockedEvent: - *t = ViolationBlockedEvent - case ViolationBlockedParser: - *t = ViolationBlockedParser - case ViolationDiscouragedAPIUse: - *t = ViolationDiscouragedAPIUse - case ViolationHandler: - *t = ViolationHandler - case ViolationRecurringHandler: - *t = ViolationRecurringHandler - default: - return fmt.Errorf("unknown Violation value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/media/events.go b/vendor/github.com/chromedp/cdproto/media/events.go index f7ef70e59..0541badb7 100644 --- a/vendor/github.com/chromedp/cdproto/media/events.go +++ b/vendor/github.com/chromedp/cdproto/media/events.go @@ -1,6 +1,6 @@ -package media +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package media // EventPlayerPropertiesChanged this can be called multiple times, and can be // used to set / override / remove player properties. A null propValue indicates diff --git a/vendor/github.com/chromedp/cdproto/media/media.go b/vendor/github.com/chromedp/cdproto/media/media.go index cd4b4ae5f..3fcacdbc6 100644 --- a/vendor/github.com/chromedp/cdproto/media/media.go +++ b/vendor/github.com/chromedp/cdproto/media/media.go @@ -1,48 +1,58 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package media provides the Chrome DevTools Protocol // commands, types, and events for the Media domain. // // This domain allows detailed inspection of media elements. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package media -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// EnableParams enables the Media domain. -type EnableParams struct{} - // Enable enables the Media domain. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Media#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} - -// Do executes Media.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) -} - -// DisableParams disables the Media domain. -type DisableParams struct{} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} // Disable disables the Media domain. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Media#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes Media.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} + +// PlayerPropertiesChanged this can be called multiple times, and can be used +// to set / override / remove player properties. A null propValue indicates +// removal. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Media#event-playerPropertiesChanged +var PlayerPropertiesChanged = cdp.Event[EventPlayerPropertiesChanged]{Method: "Media.playerPropertiesChanged"} + +// PlayerEventsAdded send events as a list, allowing them to be batched on +// the browser for less congestion. If batched, events must ALWAYS be in +// chronological order. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Media#event-playerEventsAdded +var PlayerEventsAdded = cdp.Event[EventPlayerEventsAdded]{Method: "Media.playerEventsAdded"} + +// PlayerMessagesLogged send a list of any messages that need to be +// delivered. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Media#event-playerMessagesLogged +var PlayerMessagesLogged = cdp.Event[EventPlayerMessagesLogged]{Method: "Media.playerMessagesLogged"} + +// PlayerErrorsRaised send a list of any errors that need to be delivered. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Media#event-playerErrorsRaised +var PlayerErrorsRaised = cdp.Event[EventPlayerErrorsRaised]{Method: "Media.playerErrorsRaised"} + +// PlayerCreated called whenever a player is created, or when a new agent +// joins and receives a list of active players. If an agent is restored, it will +// receive one event for each active player. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Media#event-playerCreated +var PlayerCreated = cdp.Event[EventPlayerCreated]{Method: "Media.playerCreated"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/media/types.go b/vendor/github.com/chromedp/cdproto/media/types.go index 0417c47bc..2ceefe737 100644 --- a/vendor/github.com/chromedp/cdproto/media/types.go +++ b/vendor/github.com/chromedp/cdproto/media/types.go @@ -1,13 +1,10 @@ -package media +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package media import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/cdp" - "github.com/go-json-experiment/json/jsontext" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" ) // PlayerID players will get an ID that is unique within the agent context. @@ -73,7 +70,7 @@ type PlayerError struct { Code int64 `json:"code"` // Code is the numeric enum entry for a specific set of error codes, such as PipelineStatusCodes in media/base/pipeline_status.h Stack []*PlayerErrorSourceLocation `json:"stack"` // A trace of where this error was caused / where it passed through. Cause []*PlayerError `json:"cause"` // Errors potentially have a root cause error, ie, a DecoderError might be caused by an WindowsError - Data jsontext.Value `json:"data"` + Data jsonv2.Value `json:"data"` } // Player [no description]. @@ -108,23 +105,3 @@ const ( PlayerMessageLevelInfo PlayerMessageLevel = "info" PlayerMessageLevelDebug PlayerMessageLevel = "debug" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *PlayerMessageLevel) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch PlayerMessageLevel(s) { - case PlayerMessageLevelError: - *t = PlayerMessageLevelError - case PlayerMessageLevelWarning: - *t = PlayerMessageLevelWarning - case PlayerMessageLevelInfo: - *t = PlayerMessageLevelInfo - case PlayerMessageLevelDebug: - *t = PlayerMessageLevelDebug - default: - return fmt.Errorf("unknown PlayerMessageLevel value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/memory/memory.go b/vendor/github.com/chromedp/cdproto/memory/memory.go index eb024cce9..28210b153 100644 --- a/vendor/github.com/chromedp/cdproto/memory/memory.go +++ b/vendor/github.com/chromedp/cdproto/memory/memory.go @@ -1,123 +1,54 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package memory provides the Chrome DevTools Protocol // commands, types, and events for the Memory domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package memory -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// GetDOMCountersParams retruns current DOM object counters. -type GetDOMCountersParams struct{} - -// GetDOMCounters retruns current DOM object counters. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-getDOMCounters -func GetDOMCounters() *GetDOMCountersParams { - return &GetDOMCountersParams{} -} - -// GetDOMCountersReturns return values. -type GetDOMCountersReturns struct { +// GetDOMCountersResult is the result of the command Memory.getDOMCounters. +type GetDOMCountersResult struct { Documents int64 `json:"documents,omitempty,omitzero"` Nodes int64 `json:"nodes,omitempty,omitzero"` JsEventListeners int64 `json:"jsEventListeners,omitempty,omitzero"` } -// Do executes Memory.getDOMCounters against the provided context. -// -// returns: +// GetDOMCounters retruns current DOM object counters. // -// documents -// nodes -// jsEventListeners -func (p *GetDOMCountersParams) Do(ctx context.Context) (documents int64, nodes int64, jsEventListeners int64, err error) { - // execute - var res GetDOMCountersReturns - err = cdp.Execute(ctx, CommandGetDOMCounters, nil, &res) - if err != nil { - return 0, 0, 0, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-getDOMCounters +var GetDOMCounters = cdp.Command[cdp.Empty, GetDOMCountersResult]{Method: CommandGetDOMCounters} - return res.Documents, res.Nodes, res.JsEventListeners, nil +// GetDOMCountersForLeakDetectionResult is the result of the command +// Memory.getDOMCountersForLeakDetection. +type GetDOMCountersForLeakDetectionResult struct { + Counters []*DOMCounter `json:"counters,omitempty,omitzero"` // DOM object counters. } -// GetDOMCountersForLeakDetectionParams retruns DOM object counters after -// preparing renderer for leak detection. -type GetDOMCountersForLeakDetectionParams struct{} - // GetDOMCountersForLeakDetection retruns DOM object counters after preparing // renderer for leak detection. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-getDOMCountersForLeakDetection -func GetDOMCountersForLeakDetection() *GetDOMCountersForLeakDetectionParams { - return &GetDOMCountersForLeakDetectionParams{} -} - -// GetDOMCountersForLeakDetectionReturns return values. -type GetDOMCountersForLeakDetectionReturns struct { - Counters []*DOMCounter `json:"counters,omitempty,omitzero"` // DOM object counters. -} - -// Do executes Memory.getDOMCountersForLeakDetection against the provided context. -// -// returns: -// -// counters - DOM object counters. -func (p *GetDOMCountersForLeakDetectionParams) Do(ctx context.Context) (counters []*DOMCounter, err error) { - // execute - var res GetDOMCountersForLeakDetectionReturns - err = cdp.Execute(ctx, CommandGetDOMCountersForLeakDetection, nil, &res) - if err != nil { - return nil, err - } - - return res.Counters, nil -} - -// PrepareForLeakDetectionParams prepares for leak detection by terminating -// workers, stopping spellcheckers, dropping non-essential internal caches, -// running garbage collections, etc. -type PrepareForLeakDetectionParams struct{} +var GetDOMCountersForLeakDetection = cdp.Command[cdp.Empty, GetDOMCountersForLeakDetectionResult]{Method: CommandGetDOMCountersForLeakDetection} // PrepareForLeakDetection prepares for leak detection by terminating // workers, stopping spellcheckers, dropping non-essential internal caches, // running garbage collections, etc. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-prepareForLeakDetection -func PrepareForLeakDetection() *PrepareForLeakDetectionParams { - return &PrepareForLeakDetectionParams{} -} - -// Do executes Memory.prepareForLeakDetection against the provided context. -func (p *PrepareForLeakDetectionParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandPrepareForLeakDetection, nil, nil) -} - -// ForciblyPurgeJavaScriptMemoryParams simulate OomIntervention by purging V8 -// memory. -type ForciblyPurgeJavaScriptMemoryParams struct{} +var PrepareForLeakDetection = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandPrepareForLeakDetection} // ForciblyPurgeJavaScriptMemory simulate OomIntervention by purging V8 // memory. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-forciblyPurgeJavaScriptMemory -func ForciblyPurgeJavaScriptMemory() *ForciblyPurgeJavaScriptMemoryParams { - return &ForciblyPurgeJavaScriptMemoryParams{} -} - -// Do executes Memory.forciblyPurgeJavaScriptMemory against the provided context. -func (p *ForciblyPurgeJavaScriptMemoryParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandForciblyPurgeJavaScriptMemory, nil, nil) -} +var ForciblyPurgeJavaScriptMemory = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandForciblyPurgeJavaScriptMemory} -// SetPressureNotificationsSuppressedParams enable/disable suppressing memory -// pressure notifications in all processes. +// SetPressureNotificationsSuppressedParams are the parameters of the command +// Memory.setPressureNotificationsSuppressed. type SetPressureNotificationsSuppressedParams struct { Suppressed bool `json:"suppressed"` // If true, memory pressure notifications will be suppressed. } @@ -126,23 +57,10 @@ type SetPressureNotificationsSuppressedParams struct { // pressure notifications in all processes. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-setPressureNotificationsSuppressed -// -// parameters: -// -// suppressed - If true, memory pressure notifications will be suppressed. -func SetPressureNotificationsSuppressed(suppressed bool) *SetPressureNotificationsSuppressedParams { - return &SetPressureNotificationsSuppressedParams{ - Suppressed: suppressed, - } -} +var SetPressureNotificationsSuppressed = cdp.Command[SetPressureNotificationsSuppressedParams, cdp.Empty]{Method: CommandSetPressureNotificationsSuppressed} -// Do executes Memory.setPressureNotificationsSuppressed against the provided context. -func (p *SetPressureNotificationsSuppressedParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetPressureNotificationsSuppressed, p, nil) -} - -// SimulatePressureNotificationParams simulate a memory pressure notification -// in all processes. +// SimulatePressureNotificationParams are the parameters of the command +// Memory.simulatePressureNotification. type SimulatePressureNotificationParams struct { Level PressureLevel `json:"level"` // Memory pressure level of the notification. } @@ -151,168 +69,60 @@ type SimulatePressureNotificationParams struct { // all processes. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-simulatePressureNotification -// -// parameters: -// -// level - Memory pressure level of the notification. -func SimulatePressureNotification(level PressureLevel) *SimulatePressureNotificationParams { - return &SimulatePressureNotificationParams{ - Level: level, - } -} - -// Do executes Memory.simulatePressureNotification against the provided context. -func (p *SimulatePressureNotificationParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSimulatePressureNotification, p, nil) -} +var SimulatePressureNotification = cdp.Command[SimulatePressureNotificationParams, cdp.Empty]{Method: CommandSimulatePressureNotification} -// StartSamplingParams start collecting native memory profile. +// StartSamplingParams are the parameters of the command +// Memory.startSampling. type StartSamplingParams struct { - SamplingInterval int64 `json:"samplingInterval,omitempty,omitzero"` // Average number of bytes between samples. - SuppressRandomness bool `json:"suppressRandomness"` // Do not randomize intervals between samples. + SamplingInterval int64 `json:"samplingInterval,omitempty,omitzero"` // Average number of bytes between samples. + SuppressRandomness *bool `json:"suppressRandomness,omitempty,omitzero"` // Do not randomize intervals between samples. } // StartSampling start collecting native memory profile. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-startSampling -// -// parameters: -func StartSampling() *StartSamplingParams { - return &StartSamplingParams{ - SuppressRandomness: false, - } -} - -// WithSamplingInterval average number of bytes between samples. -func (p StartSamplingParams) WithSamplingInterval(samplingInterval int64) *StartSamplingParams { - p.SamplingInterval = samplingInterval - return &p -} - -// WithSuppressRandomness do not randomize intervals between samples. -func (p StartSamplingParams) WithSuppressRandomness(suppressRandomness bool) *StartSamplingParams { - p.SuppressRandomness = suppressRandomness - return &p -} - -// Do executes Memory.startSampling against the provided context. -func (p *StartSamplingParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStartSampling, p, nil) -} - -// StopSamplingParams stop collecting native memory profile. -type StopSamplingParams struct{} +var StartSampling = cdp.Command[StartSamplingParams, cdp.Empty]{Method: CommandStartSampling} // StopSampling stop collecting native memory profile. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-stopSampling -func StopSampling() *StopSamplingParams { - return &StopSamplingParams{} -} +var StopSampling = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandStopSampling} -// Do executes Memory.stopSampling against the provided context. -func (p *StopSamplingParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStopSampling, nil, nil) +// GetAllTimeSamplingProfileResult is the result of the command +// Memory.getAllTimeSamplingProfile. +type GetAllTimeSamplingProfileResult struct { + Profile *SamplingProfile `json:"profile,omitempty,omitzero"` } -// GetAllTimeSamplingProfileParams retrieve native memory allocations profile -// collected since renderer process startup. -type GetAllTimeSamplingProfileParams struct{} - // GetAllTimeSamplingProfile retrieve native memory allocations profile // collected since renderer process startup. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-getAllTimeSamplingProfile -func GetAllTimeSamplingProfile() *GetAllTimeSamplingProfileParams { - return &GetAllTimeSamplingProfileParams{} -} +var GetAllTimeSamplingProfile = cdp.Command[cdp.Empty, GetAllTimeSamplingProfileResult]{Method: CommandGetAllTimeSamplingProfile} -// GetAllTimeSamplingProfileReturns return values. -type GetAllTimeSamplingProfileReturns struct { +// GetBrowserSamplingProfileResult is the result of the command +// Memory.getBrowserSamplingProfile. +type GetBrowserSamplingProfileResult struct { Profile *SamplingProfile `json:"profile,omitempty,omitzero"` } -// Do executes Memory.getAllTimeSamplingProfile against the provided context. -// -// returns: -// -// profile -func (p *GetAllTimeSamplingProfileParams) Do(ctx context.Context) (profile *SamplingProfile, err error) { - // execute - var res GetAllTimeSamplingProfileReturns - err = cdp.Execute(ctx, CommandGetAllTimeSamplingProfile, nil, &res) - if err != nil { - return nil, err - } - - return res.Profile, nil -} - -// GetBrowserSamplingProfileParams retrieve native memory allocations profile -// collected since browser process startup. -type GetBrowserSamplingProfileParams struct{} - // GetBrowserSamplingProfile retrieve native memory allocations profile // collected since browser process startup. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-getBrowserSamplingProfile -func GetBrowserSamplingProfile() *GetBrowserSamplingProfileParams { - return &GetBrowserSamplingProfileParams{} -} +var GetBrowserSamplingProfile = cdp.Command[cdp.Empty, GetBrowserSamplingProfileResult]{Method: CommandGetBrowserSamplingProfile} -// GetBrowserSamplingProfileReturns return values. -type GetBrowserSamplingProfileReturns struct { +// GetSamplingProfileResult is the result of the command +// Memory.getSamplingProfile. +type GetSamplingProfileResult struct { Profile *SamplingProfile `json:"profile,omitempty,omitzero"` } -// Do executes Memory.getBrowserSamplingProfile against the provided context. -// -// returns: -// -// profile -func (p *GetBrowserSamplingProfileParams) Do(ctx context.Context) (profile *SamplingProfile, err error) { - // execute - var res GetBrowserSamplingProfileReturns - err = cdp.Execute(ctx, CommandGetBrowserSamplingProfile, nil, &res) - if err != nil { - return nil, err - } - - return res.Profile, nil -} - -// GetSamplingProfileParams retrieve native memory allocations profile -// collected since last startSampling call. -type GetSamplingProfileParams struct{} - // GetSamplingProfile retrieve native memory allocations profile collected // since last startSampling call. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-getSamplingProfile -func GetSamplingProfile() *GetSamplingProfileParams { - return &GetSamplingProfileParams{} -} - -// GetSamplingProfileReturns return values. -type GetSamplingProfileReturns struct { - Profile *SamplingProfile `json:"profile,omitempty,omitzero"` -} - -// Do executes Memory.getSamplingProfile against the provided context. -// -// returns: -// -// profile -func (p *GetSamplingProfileParams) Do(ctx context.Context) (profile *SamplingProfile, err error) { - // execute - var res GetSamplingProfileReturns - err = cdp.Execute(ctx, CommandGetSamplingProfile, nil, &res) - if err != nil { - return nil, err - } - - return res.Profile, nil -} +var GetSamplingProfile = cdp.Command[cdp.Empty, GetSamplingProfileResult]{Method: CommandGetSamplingProfile} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/memory/types.go b/vendor/github.com/chromedp/cdproto/memory/types.go index d16858ade..734866a24 100644 --- a/vendor/github.com/chromedp/cdproto/memory/types.go +++ b/vendor/github.com/chromedp/cdproto/memory/types.go @@ -1,11 +1,6 @@ -package memory - -import ( - "fmt" - "strings" -) +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package memory // PressureLevel memory pressure level. // @@ -23,22 +18,6 @@ const ( PressureLevelCritical PressureLevel = "critical" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *PressureLevel) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch PressureLevel(s) { - case PressureLevelModerate: - *t = PressureLevelModerate - case PressureLevelCritical: - *t = PressureLevelCritical - default: - return fmt.Errorf("unknown PressureLevel value: %v", s) - } - return nil -} - // SamplingProfileNode heap profile sample. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#type-SamplingProfileNode diff --git a/vendor/github.com/chromedp/cdproto/network/events.go b/vendor/github.com/chromedp/cdproto/network/events.go index 2452f738d..515b5e007 100644 --- a/vendor/github.com/chromedp/cdproto/network/events.go +++ b/vendor/github.com/chromedp/cdproto/network/events.go @@ -1,6 +1,6 @@ -package network +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package network import ( "github.com/chromedp/cdproto/cdp" @@ -10,11 +10,11 @@ import ( // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-dataReceived type EventDataReceived struct { - RequestID RequestID `json:"requestId"` // Request identifier. - Timestamp *cdp.MonotonicTime `json:"timestamp"` // Timestamp. - DataLength int64 `json:"dataLength"` // Data chunk length. - EncodedDataLength int64 `json:"encodedDataLength"` // Actual bytes received (might be less than dataLength for compressed encodings). - Data string `json:"data,omitempty,omitzero"` // Data that was received. + RequestID RequestID `json:"requestId"` // Request identifier. + Timestamp cdp.MonotonicTime `json:"timestamp"` // Timestamp. + DataLength int64 `json:"dataLength"` // Data chunk length. + EncodedDataLength int64 `json:"encodedDataLength"` // Actual bytes received (might be less than dataLength for compressed encodings). + Data []byte `json:"data,omitempty,omitzero"` // Data that was received. } // EventEventSourceMessageReceived fired when EventSource message is @@ -22,33 +22,34 @@ type EventDataReceived struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-eventSourceMessageReceived type EventEventSourceMessageReceived struct { - RequestID RequestID `json:"requestId"` // Request identifier. - Timestamp *cdp.MonotonicTime `json:"timestamp"` // Timestamp. - EventName string `json:"eventName"` // Message type. - EventID string `json:"eventId"` // Message identifier. - Data string `json:"data"` // Message content. + RequestID RequestID `json:"requestId"` // Request identifier. + Timestamp cdp.MonotonicTime `json:"timestamp"` // Timestamp. + EventName string `json:"eventName"` // Message type. + EventID string `json:"eventId"` // Message identifier. + Data string `json:"data"` // Message content. } // EventLoadingFailed fired when HTTP request has failed to load. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-loadingFailed type EventLoadingFailed struct { - RequestID RequestID `json:"requestId"` // Request identifier. - Timestamp *cdp.MonotonicTime `json:"timestamp"` // Timestamp. - Type ResourceType `json:"type"` // Resource type. - ErrorText string `json:"errorText"` // Error message. List of network errors: https://cs.chromium.org/chromium/src/net/base/net_error_list.h - Canceled bool `json:"canceled"` // True if loading was canceled. - BlockedReason BlockedReason `json:"blockedReason,omitempty,omitzero"` // The reason why loading was blocked, if any. - CorsErrorStatus *CorsErrorStatus `json:"corsErrorStatus,omitempty,omitzero"` // The reason why loading was blocked by CORS, if any. + RequestID RequestID `json:"requestId"` // Request identifier. + Timestamp cdp.MonotonicTime `json:"timestamp"` // Timestamp. + Type ResourceType `json:"type"` // Resource type. + ErrorText string `json:"errorText"` // Error message. List of network errors: https://cs.chromium.org/chromium/src/net/base/net_error_list.h + Canceled bool `json:"canceled"` // True if loading was canceled. + BlockedReason BlockedReason `json:"blockedReason,omitempty,omitzero"` // The reason why loading was blocked, if any. + CorsErrorStatus *CorsErrorStatus `json:"corsErrorStatus,omitempty,omitzero"` // The reason why loading was blocked by CORS, if any. } // EventLoadingFinished fired when HTTP request has finished loading. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-loadingFinished type EventLoadingFinished struct { - RequestID RequestID `json:"requestId"` // Request identifier. - Timestamp *cdp.MonotonicTime `json:"timestamp"` // Timestamp. - EncodedDataLength float64 `json:"encodedDataLength"` // Total number of bytes received for this request. + RequestID RequestID `json:"requestId"` // Request identifier. + Timestamp cdp.MonotonicTime `json:"timestamp"` // Timestamp. + EncodedDataLength float64 `json:"encodedDataLength"` // Total number of bytes received for this request. + EncodedBodyLength float64 `json:"encodedBodyLength,omitempty,omitzero"` // Size of the response body before removing content encodings. Includes cached bodies, but excludes headers and transfer framing. } // EventRequestServedFromCache fired if request ended up loading from cache. @@ -66,8 +67,8 @@ type EventRequestWillBeSent struct { LoaderID cdp.LoaderID `json:"loaderId"` // Loader identifier. Empty string if the request is fetched from worker. DocumentURL string `json:"documentURL"` // URL of the document this request is loaded for. Request *Request `json:"request"` // Request data. - Timestamp *cdp.MonotonicTime `json:"timestamp"` // Timestamp. - WallTime *cdp.TimeSinceEpoch `json:"wallTime"` // Timestamp. + Timestamp cdp.MonotonicTime `json:"timestamp"` // Timestamp. + WallTime cdp.TimeSinceEpoch `json:"wallTime"` // Timestamp. Initiator *Initiator `json:"initiator"` // Request initiator. RedirectHasExtraInfo bool `json:"redirectHasExtraInfo"` // In the case that redirectResponse is populated, this flag indicates whether requestWillBeSentExtraInfo and responseReceivedExtraInfo events will be or were emitted for the request which was just redirected. RedirectResponse *Response `json:"redirectResponse,omitempty,omitzero"` // Redirect response data. @@ -82,9 +83,9 @@ type EventRequestWillBeSent struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-resourceChangedPriority type EventResourceChangedPriority struct { - RequestID RequestID `json:"requestId"` // Request identifier. - NewPriority ResourcePriority `json:"newPriority"` // New priority - Timestamp *cdp.MonotonicTime `json:"timestamp"` // Timestamp. + RequestID RequestID `json:"requestId"` // Request identifier. + NewPriority ResourcePriority `json:"newPriority"` // New priority + Timestamp cdp.MonotonicTime `json:"timestamp"` // Timestamp. } // EventSignedExchangeReceived fired when a signed exchange was received over @@ -100,21 +101,21 @@ type EventSignedExchangeReceived struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-responseReceived type EventResponseReceived struct { - RequestID RequestID `json:"requestId"` // Request identifier. - LoaderID cdp.LoaderID `json:"loaderId"` // Loader identifier. Empty string if the request is fetched from worker. - Timestamp *cdp.MonotonicTime `json:"timestamp"` // Timestamp. - Type ResourceType `json:"type"` // Resource type. - Response *Response `json:"response"` // Response data. - HasExtraInfo bool `json:"hasExtraInfo"` // Indicates whether requestWillBeSentExtraInfo and responseReceivedExtraInfo events will be or were emitted for this request. - FrameID cdp.FrameID `json:"frameId,omitempty,omitzero"` // Frame identifier. + RequestID RequestID `json:"requestId"` // Request identifier. + LoaderID cdp.LoaderID `json:"loaderId"` // Loader identifier. Empty string if the request is fetched from worker. + Timestamp cdp.MonotonicTime `json:"timestamp"` // Timestamp. + Type ResourceType `json:"type"` // Resource type. + Response *Response `json:"response"` // Response data. + HasExtraInfo bool `json:"hasExtraInfo"` // Indicates whether requestWillBeSentExtraInfo and responseReceivedExtraInfo events will be or were emitted for this request. + FrameID cdp.FrameID `json:"frameId,omitempty,omitzero"` // Frame identifier. } // EventWebSocketClosed fired when WebSocket is closed. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketClosed type EventWebSocketClosed struct { - RequestID RequestID `json:"requestId"` // Request identifier. - Timestamp *cdp.MonotonicTime `json:"timestamp"` // Timestamp. + RequestID RequestID `json:"requestId"` // Request identifier. + Timestamp cdp.MonotonicTime `json:"timestamp"` // Timestamp. } // EventWebSocketCreated fired upon WebSocket creation. @@ -130,27 +131,27 @@ type EventWebSocketCreated struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketFrameError type EventWebSocketFrameError struct { - RequestID RequestID `json:"requestId"` // Request identifier. - Timestamp *cdp.MonotonicTime `json:"timestamp"` // Timestamp. - ErrorMessage string `json:"errorMessage"` // WebSocket error message. + RequestID RequestID `json:"requestId"` // Request identifier. + Timestamp cdp.MonotonicTime `json:"timestamp"` // Timestamp. + ErrorMessage string `json:"errorMessage"` // WebSocket error message. } // EventWebSocketFrameReceived fired when WebSocket message is received. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketFrameReceived type EventWebSocketFrameReceived struct { - RequestID RequestID `json:"requestId"` // Request identifier. - Timestamp *cdp.MonotonicTime `json:"timestamp"` // Timestamp. - Response *WebSocketFrame `json:"response"` // WebSocket response data. + RequestID RequestID `json:"requestId"` // Request identifier. + Timestamp cdp.MonotonicTime `json:"timestamp"` // Timestamp. + Response *WebSocketFrame `json:"response"` // WebSocket response data. } // EventWebSocketFrameSent fired when WebSocket message is sent. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketFrameSent type EventWebSocketFrameSent struct { - RequestID RequestID `json:"requestId"` // Request identifier. - Timestamp *cdp.MonotonicTime `json:"timestamp"` // Timestamp. - Response *WebSocketFrame `json:"response"` // WebSocket response data. + RequestID RequestID `json:"requestId"` // Request identifier. + Timestamp cdp.MonotonicTime `json:"timestamp"` // Timestamp. + Response *WebSocketFrame `json:"response"` // WebSocket response data. } // EventWebSocketHandshakeResponseReceived fired when WebSocket handshake @@ -159,7 +160,7 @@ type EventWebSocketFrameSent struct { // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketHandshakeResponseReceived type EventWebSocketHandshakeResponseReceived struct { RequestID RequestID `json:"requestId"` // Request identifier. - Timestamp *cdp.MonotonicTime `json:"timestamp"` // Timestamp. + Timestamp cdp.MonotonicTime `json:"timestamp"` // Timestamp. Response *WebSocketResponse `json:"response"` // WebSocket response data. } @@ -168,20 +169,20 @@ type EventWebSocketHandshakeResponseReceived struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketWillSendHandshakeRequest type EventWebSocketWillSendHandshakeRequest struct { - RequestID RequestID `json:"requestId"` // Request identifier. - Timestamp *cdp.MonotonicTime `json:"timestamp"` // Timestamp. - WallTime *cdp.TimeSinceEpoch `json:"wallTime"` // UTC Timestamp. - Request *WebSocketRequest `json:"request"` // WebSocket request data. + RequestID RequestID `json:"requestId"` // Request identifier. + Timestamp cdp.MonotonicTime `json:"timestamp"` // Timestamp. + WallTime cdp.TimeSinceEpoch `json:"wallTime"` // UTC Timestamp. + Request *WebSocketRequest `json:"request"` // WebSocket request data. } // EventWebTransportCreated fired upon WebTransport creation. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webTransportCreated type EventWebTransportCreated struct { - TransportID RequestID `json:"transportId"` // WebTransport identifier. - URL string `json:"url"` // WebTransport request URL. - Timestamp *cdp.MonotonicTime `json:"timestamp"` // Timestamp. - Initiator *Initiator `json:"initiator,omitempty,omitzero"` // Request initiator. + TransportID RequestID `json:"transportId"` // WebTransport identifier. + URL string `json:"url"` // WebTransport request URL. + Timestamp cdp.MonotonicTime `json:"timestamp"` // Timestamp. + Initiator *Initiator `json:"initiator,omitempty,omitzero"` // Request initiator. } // EventWebTransportConnectionEstablished fired when WebTransport handshake @@ -189,16 +190,16 @@ type EventWebTransportCreated struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webTransportConnectionEstablished type EventWebTransportConnectionEstablished struct { - TransportID RequestID `json:"transportId"` // WebTransport identifier. - Timestamp *cdp.MonotonicTime `json:"timestamp"` // Timestamp. + TransportID RequestID `json:"transportId"` // WebTransport identifier. + Timestamp cdp.MonotonicTime `json:"timestamp"` // Timestamp. } // EventWebTransportClosed fired when WebTransport is disposed. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webTransportClosed type EventWebTransportClosed struct { - TransportID RequestID `json:"transportId"` // WebTransport identifier. - Timestamp *cdp.MonotonicTime `json:"timestamp"` // Timestamp. + TransportID RequestID `json:"transportId"` // WebTransport identifier. + Timestamp cdp.MonotonicTime `json:"timestamp"` // Timestamp. } // EventDirectTCPSocketCreated fired upon direct_socket.TCPSocket creation. @@ -209,7 +210,7 @@ type EventDirectTCPSocketCreated struct { RemoteAddr string `json:"remoteAddr"` RemotePort int64 `json:"remotePort"` // Unsigned int 16. Options *DirectTCPSocketOptions `json:"options"` - Timestamp *cdp.MonotonicTime `json:"timestamp"` + Timestamp cdp.MonotonicTime `json:"timestamp"` Initiator *Initiator `json:"initiator,omitempty,omitzero"` } @@ -218,29 +219,29 @@ type EventDirectTCPSocketCreated struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directTCPSocketOpened type EventDirectTCPSocketOpened struct { - Identifier RequestID `json:"identifier"` - RemoteAddr string `json:"remoteAddr"` - RemotePort int64 `json:"remotePort"` // Expected to be unsigned integer. - Timestamp *cdp.MonotonicTime `json:"timestamp"` - LocalAddr string `json:"localAddr,omitempty,omitzero"` - LocalPort int64 `json:"localPort,omitempty,omitzero"` // Expected to be unsigned integer. + Identifier RequestID `json:"identifier"` + RemoteAddr string `json:"remoteAddr"` + RemotePort int64 `json:"remotePort"` // Expected to be unsigned integer. + Timestamp cdp.MonotonicTime `json:"timestamp"` + LocalAddr string `json:"localAddr,omitempty,omitzero"` + LocalPort int64 `json:"localPort,omitempty,omitzero"` // Expected to be unsigned integer. } // EventDirectTCPSocketAborted fired when direct_socket.TCPSocket is aborted. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directTCPSocketAborted type EventDirectTCPSocketAborted struct { - Identifier RequestID `json:"identifier"` - ErrorMessage string `json:"errorMessage"` - Timestamp *cdp.MonotonicTime `json:"timestamp"` + Identifier RequestID `json:"identifier"` + ErrorMessage ErrorReason `json:"errorMessage"` + Timestamp cdp.MonotonicTime `json:"timestamp"` } // EventDirectTCPSocketClosed fired when direct_socket.TCPSocket is closed. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directTCPSocketClosed type EventDirectTCPSocketClosed struct { - Identifier RequestID `json:"identifier"` - Timestamp *cdp.MonotonicTime `json:"timestamp"` + Identifier RequestID `json:"identifier"` + Timestamp cdp.MonotonicTime `json:"timestamp"` } // EventDirectTCPSocketChunkSent fired when data is sent to tcp direct socket @@ -248,9 +249,9 @@ type EventDirectTCPSocketClosed struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directTCPSocketChunkSent type EventDirectTCPSocketChunkSent struct { - Identifier RequestID `json:"identifier"` - Data string `json:"data"` - Timestamp *cdp.MonotonicTime `json:"timestamp"` + Identifier RequestID `json:"identifier"` + Data []byte `json:"data"` + Timestamp cdp.MonotonicTime `json:"timestamp"` } // EventDirectTCPSocketChunkReceived fired when data is received from tcp @@ -258,9 +259,9 @@ type EventDirectTCPSocketChunkSent struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directTCPSocketChunkReceived type EventDirectTCPSocketChunkReceived struct { - Identifier RequestID `json:"identifier"` - Data string `json:"data"` - Timestamp *cdp.MonotonicTime `json:"timestamp"` + Identifier RequestID `json:"identifier"` + Data []byte `json:"data"` + Timestamp cdp.MonotonicTime `json:"timestamp"` } // EventDirectUDPSocketJoinedMulticastGroup [no description]. @@ -285,7 +286,7 @@ type EventDirectUDPSocketLeftMulticastGroup struct { type EventDirectUDPSocketCreated struct { Identifier RequestID `json:"identifier"` Options *DirectUDPSocketOptions `json:"options"` - Timestamp *cdp.MonotonicTime `json:"timestamp"` + Timestamp cdp.MonotonicTime `json:"timestamp"` Initiator *Initiator `json:"initiator,omitempty,omitzero"` } @@ -294,29 +295,29 @@ type EventDirectUDPSocketCreated struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directUDPSocketOpened type EventDirectUDPSocketOpened struct { - Identifier RequestID `json:"identifier"` - LocalAddr string `json:"localAddr"` - LocalPort int64 `json:"localPort"` // Expected to be unsigned integer. - Timestamp *cdp.MonotonicTime `json:"timestamp"` - RemoteAddr string `json:"remoteAddr,omitempty,omitzero"` - RemotePort int64 `json:"remotePort,omitempty,omitzero"` // Expected to be unsigned integer. + Identifier RequestID `json:"identifier"` + LocalAddr string `json:"localAddr"` + LocalPort int64 `json:"localPort"` // Expected to be unsigned integer. + Timestamp cdp.MonotonicTime `json:"timestamp"` + RemoteAddr string `json:"remoteAddr,omitempty,omitzero"` + RemotePort int64 `json:"remotePort,omitempty,omitzero"` // Expected to be unsigned integer. } // EventDirectUDPSocketAborted fired when direct_socket.UDPSocket is aborted. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directUDPSocketAborted type EventDirectUDPSocketAborted struct { - Identifier RequestID `json:"identifier"` - ErrorMessage string `json:"errorMessage"` - Timestamp *cdp.MonotonicTime `json:"timestamp"` + Identifier RequestID `json:"identifier"` + ErrorMessage ErrorReason `json:"errorMessage"` + Timestamp cdp.MonotonicTime `json:"timestamp"` } // EventDirectUDPSocketClosed fired when direct_socket.UDPSocket is closed. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directUDPSocketClosed type EventDirectUDPSocketClosed struct { - Identifier RequestID `json:"identifier"` - Timestamp *cdp.MonotonicTime `json:"timestamp"` + Identifier RequestID `json:"identifier"` + Timestamp cdp.MonotonicTime `json:"timestamp"` } // EventDirectUDPSocketChunkSent fired when message is sent to udp direct @@ -324,9 +325,9 @@ type EventDirectUDPSocketClosed struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directUDPSocketChunkSent type EventDirectUDPSocketChunkSent struct { - Identifier RequestID `json:"identifier"` - Message *DirectUDPMessage `json:"message"` - Timestamp *cdp.MonotonicTime `json:"timestamp"` + Identifier RequestID `json:"identifier"` + Message *DirectUDPMessage `json:"message"` + Timestamp cdp.MonotonicTime `json:"timestamp"` } // EventDirectUDPSocketChunkReceived fired when message is received from udp @@ -334,9 +335,9 @@ type EventDirectUDPSocketChunkSent struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directUDPSocketChunkReceived type EventDirectUDPSocketChunkReceived struct { - Identifier RequestID `json:"identifier"` - Message *DirectUDPMessage `json:"message"` - Timestamp *cdp.MonotonicTime `json:"timestamp"` + Identifier RequestID `json:"identifier"` + Message *DirectUDPMessage `json:"message"` + Timestamp cdp.MonotonicTime `json:"timestamp"` } // EventRequestWillBeSentExtraInfo fired when additional information about a diff --git a/vendor/github.com/chromedp/cdproto/network/network.go b/vendor/github.com/chromedp/cdproto/network/network.go index b49ee3ad9..5e1c5f63c 100644 --- a/vendor/github.com/chromedp/cdproto/network/network.go +++ b/vendor/github.com/chromedp/cdproto/network/network.go @@ -1,3 +1,5 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package network provides the Chrome DevTools Protocol // commands, types, and events for the Network domain. // @@ -5,94 +7,30 @@ // information about http, file, data and other requests and responses, their // headers, bodies, timing, etc. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package network -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" "encoding/base64" + "fmt" "github.com/chromedp/cdproto/cdp" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" "github.com/chromedp/cdproto/debugger" - "github.com/chromedp/cdproto/io" ) -// SetAcceptedEncodingsParams sets a list of content encodings that will be -// accepted. Empty list means no encoding is accepted. -type SetAcceptedEncodingsParams struct { - Encodings []ContentEncoding `json:"encodings"` // List of accepted content encodings. -} - -// SetAcceptedEncodings sets a list of content encodings that will be -// accepted. Empty list means no encoding is accepted. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setAcceptedEncodings -// -// parameters: -// -// encodings - List of accepted content encodings. -func SetAcceptedEncodings(encodings []ContentEncoding) *SetAcceptedEncodingsParams { - return &SetAcceptedEncodingsParams{ - Encodings: encodings, - } -} - -// Do executes Network.setAcceptedEncodings against the provided context. -func (p *SetAcceptedEncodingsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetAcceptedEncodings, p, nil) -} - -// ClearAcceptedEncodingsOverrideParams clears accepted encodings set by -// setAcceptedEncodings. -type ClearAcceptedEncodingsOverrideParams struct{} - -// ClearAcceptedEncodingsOverride clears accepted encodings set by -// setAcceptedEncodings. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-clearAcceptedEncodingsOverride -func ClearAcceptedEncodingsOverride() *ClearAcceptedEncodingsOverrideParams { - return &ClearAcceptedEncodingsOverrideParams{} -} - -// Do executes Network.clearAcceptedEncodingsOverride against the provided context. -func (p *ClearAcceptedEncodingsOverrideParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClearAcceptedEncodingsOverride, nil, nil) -} - -// ClearBrowserCacheParams clears browser cache. -type ClearBrowserCacheParams struct{} - // ClearBrowserCache clears browser cache. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-clearBrowserCache -func ClearBrowserCache() *ClearBrowserCacheParams { - return &ClearBrowserCacheParams{} -} - -// Do executes Network.clearBrowserCache against the provided context. -func (p *ClearBrowserCacheParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClearBrowserCache, nil, nil) -} - -// ClearBrowserCookiesParams clears browser cookies. -type ClearBrowserCookiesParams struct{} +var ClearBrowserCache = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandClearBrowserCache} // ClearBrowserCookies clears browser cookies. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-clearBrowserCookies -func ClearBrowserCookies() *ClearBrowserCookiesParams { - return &ClearBrowserCookiesParams{} -} +var ClearBrowserCookies = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandClearBrowserCookies} -// Do executes Network.clearBrowserCookies against the provided context. -func (p *ClearBrowserCookiesParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClearBrowserCookies, nil, nil) -} - -// DeleteCookiesParams deletes browser cookies with matching name and url or -// domain/path/partitionKey pair. +// DeleteCookiesParams are the parameters of the command +// Network.deleteCookies. type DeleteCookiesParams struct { Name string `json:"name"` // Name of the cookies to remove. URL string `json:"url,omitempty,omitzero"` // If specified, deletes all the cookies with the given name where domain and path match provided URL. @@ -105,73 +43,25 @@ type DeleteCookiesParams struct { // domain/path/partitionKey pair. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-deleteCookies -// -// parameters: -// -// name - Name of the cookies to remove. -func DeleteCookies(name string) *DeleteCookiesParams { - return &DeleteCookiesParams{ - Name: name, - } -} - -// WithURL if specified, deletes all the cookies with the given name where -// domain and path match provided URL. -func (p DeleteCookiesParams) WithURL(url string) *DeleteCookiesParams { - p.URL = url - return &p -} - -// WithDomain if specified, deletes only cookies with the exact domain. -func (p DeleteCookiesParams) WithDomain(domain string) *DeleteCookiesParams { - p.Domain = domain - return &p -} - -// WithPath if specified, deletes only cookies with the exact path. -func (p DeleteCookiesParams) WithPath(path string) *DeleteCookiesParams { - p.Path = path - return &p -} - -// WithPartitionKey if specified, deletes only cookies with the the given -// name and partitionKey where all partition key attributes match the cookie -// partition key attribute. -func (p DeleteCookiesParams) WithPartitionKey(partitionKey *CookiePartitionKey) *DeleteCookiesParams { - p.PartitionKey = partitionKey - return &p -} - -// Do executes Network.deleteCookies against the provided context. -func (p *DeleteCookiesParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDeleteCookies, p, nil) -} - -// DisableParams disables network tracking, prevents network events from -// being sent to the client. -type DisableParams struct{} +var DeleteCookies = cdp.Command[DeleteCookiesParams, cdp.Empty]{Method: CommandDeleteCookies} // Disable disables network tracking, prevents network events from being sent // to the client. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} -// Do executes Network.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) +// EmulateNetworkConditionsByRuleParams are the parameters of the command +// Network.emulateNetworkConditionsByRule. +type EmulateNetworkConditionsByRuleParams struct { + EmulateOfflineServiceWorker *bool `json:"emulateOfflineServiceWorker,omitempty,omitzero"` // True to emulate offline service worker. + MatchedNetworkConditions []*Conditions `json:"matchedNetworkConditions"` // Configure conditions for matching requests. If multiple entries match a request, the first entry wins. Global conditions can be configured by leaving the urlPattern for the conditions empty. These global conditions are also applied for throttling of p2p connections. } -// EmulateNetworkConditionsByRuleParams activates emulation of network -// conditions for individual requests using URL match patterns. Unlike the -// deprecated Network.emulateNetworkConditions this method does not affect -// navigator state. Use Network.overrideNetworkState to explicitly modify -// navigator behavior. -type EmulateNetworkConditionsByRuleParams struct { - EmulateOfflineServiceWorker bool `json:"emulateOfflineServiceWorker"` // True to emulate offline service worker. - MatchedNetworkConditions []*Conditions `json:"matchedNetworkConditions"` // Configure conditions for matching requests. If multiple entries match a request, the first entry wins. Global conditions can be configured by leaving the urlPattern for the conditions empty. These global conditions are also applied for throttling of p2p connections. +// EmulateNetworkConditionsByRuleResult is the result of the command +// Network.emulateNetworkConditionsByRule. +type EmulateNetworkConditionsByRuleResult struct { + RuleIDs []string `json:"ruleIds,omitempty,omitzero"` // An id for each entry in matchedNetworkConditions. The id will be included in the requestWillBeSentExtraInfo for requests affected by a rule. } // EmulateNetworkConditionsByRule activates emulation of network conditions @@ -180,46 +70,10 @@ type EmulateNetworkConditionsByRuleParams struct { // Use Network.overrideNetworkState to explicitly modify navigator behavior. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-emulateNetworkConditionsByRule -// -// parameters: -// -// matchedNetworkConditions - Configure conditions for matching requests. If multiple entries match a request, the first entry wins. Global conditions can be configured by leaving the urlPattern for the conditions empty. These global conditions are also applied for throttling of p2p connections. -func EmulateNetworkConditionsByRule(matchedNetworkConditions []*Conditions) *EmulateNetworkConditionsByRuleParams { - return &EmulateNetworkConditionsByRuleParams{ - EmulateOfflineServiceWorker: false, - MatchedNetworkConditions: matchedNetworkConditions, - } -} - -// WithEmulateOfflineServiceWorker true to emulate offline service worker. -func (p EmulateNetworkConditionsByRuleParams) WithEmulateOfflineServiceWorker(emulateOfflineServiceWorker bool) *EmulateNetworkConditionsByRuleParams { - p.EmulateOfflineServiceWorker = emulateOfflineServiceWorker - return &p -} - -// EmulateNetworkConditionsByRuleReturns return values. -type EmulateNetworkConditionsByRuleReturns struct { - RuleIDs []string `json:"ruleIds,omitempty,omitzero"` // An id for each entry in matchedNetworkConditions. The id will be included in the requestWillBeSentExtraInfo for requests affected by a rule. -} - -// Do executes Network.emulateNetworkConditionsByRule against the provided context. -// -// returns: -// -// ruleIDs - An id for each entry in matchedNetworkConditions. The id will be included in the requestWillBeSentExtraInfo for requests affected by a rule. -func (p *EmulateNetworkConditionsByRuleParams) Do(ctx context.Context) (ruleIDs []string, err error) { - // execute - var res EmulateNetworkConditionsByRuleReturns - err = cdp.Execute(ctx, CommandEmulateNetworkConditionsByRule, p, &res) - if err != nil { - return nil, err - } +var EmulateNetworkConditionsByRule = cdp.Command[EmulateNetworkConditionsByRuleParams, EmulateNetworkConditionsByRuleResult]{Method: CommandEmulateNetworkConditionsByRule} - return res.RuleIDs, nil -} - -// OverrideNetworkStateParams override the state of navigator.onLine and -// navigator.connection. +// OverrideNetworkStateParams are the parameters of the command +// Network.overrideNetworkState. type OverrideNetworkStateParams struct { Offline bool `json:"offline"` // True to emulate internet disconnection. Latency float64 `json:"latency"` // Minimum latency from request sent to response headers received (ms). @@ -232,107 +86,28 @@ type OverrideNetworkStateParams struct { // navigator.connection. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-overrideNetworkState -// -// parameters: -// -// offline - True to emulate internet disconnection. -// latency - Minimum latency from request sent to response headers received (ms). -// downloadThroughput - Maximal aggregated download throughput (bytes/sec). -1 disables download throttling. -// uploadThroughput - Maximal aggregated upload throughput (bytes/sec). -1 disables upload throttling. -func OverrideNetworkState(offline bool, latency float64, downloadThroughput float64, uploadThroughput float64) *OverrideNetworkStateParams { - return &OverrideNetworkStateParams{ - Offline: offline, - Latency: latency, - DownloadThroughput: downloadThroughput, - UploadThroughput: uploadThroughput, - } -} - -// WithConnectionType connection type if known. -func (p OverrideNetworkStateParams) WithConnectionType(connectionType ConnectionType) *OverrideNetworkStateParams { - p.ConnectionType = connectionType - return &p -} +var OverrideNetworkState = cdp.Command[OverrideNetworkStateParams, cdp.Empty]{Method: CommandOverrideNetworkState} -// Do executes Network.overrideNetworkState against the provided context. -func (p *OverrideNetworkStateParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandOverrideNetworkState, p, nil) -} - -// EnableParams enables network tracking, network events will now be -// delivered to the client. +// EnableParams are the parameters of the command Network.enable. type EnableParams struct { - MaxTotalBufferSize int64 `json:"maxTotalBufferSize,omitempty,omitzero"` // Buffer size in bytes to use when preserving network payloads (XHRs, etc). This is the maximum number of bytes that will be collected by this DevTools session. - MaxResourceBufferSize int64 `json:"maxResourceBufferSize,omitempty,omitzero"` // Per-resource buffer size in bytes to use when preserving network payloads (XHRs, etc). - MaxPostDataSize int64 `json:"maxPostDataSize,omitempty,omitzero"` // Longest post body size (in bytes) that would be included in requestWillBeSent notification - ReportDirectSocketTraffic bool `json:"reportDirectSocketTraffic"` // Whether DirectSocket chunk send/receive events should be reported. - EnableDurableMessages bool `json:"enableDurableMessages"` // Enable storing response bodies outside of renderer, so that these survive a cross-process navigation. Requires maxTotalBufferSize to be set. Currently defaults to false. This field is being deprecated in favor of the dedicated configureDurableMessages command, due to the possibility of deadlocks when awaiting Network.enable before issuing Runtime.runIfWaitingForDebugger. + MaxTotalBufferSize *int64 `json:"maxTotalBufferSize,omitempty,omitzero"` // Buffer size in bytes to use when preserving network payloads (XHRs, etc). This is the maximum number of bytes that will be collected by this DevTools session. + MaxResourceBufferSize *int64 `json:"maxResourceBufferSize,omitempty,omitzero"` // Per-resource buffer size in bytes to use when preserving network payloads (XHRs, etc). + MaxPostDataSize *int64 `json:"maxPostDataSize,omitempty,omitzero"` // Longest post body size (in bytes) that would be included in requestWillBeSent notification + ReportDirectSocketTraffic *bool `json:"reportDirectSocketTraffic,omitempty,omitzero"` // Whether DirectSocket chunk send/receive events should be reported. + EnableDurableMessages *bool `json:"enableDurableMessages,omitempty,omitzero"` // Enable storing response bodies outside of renderer, so that these survive a cross-process navigation. Requires maxTotalBufferSize to be set. Currently defaults to false. This field is being deprecated in favor of the dedicated configureDurableMessages command, due to the possibility of deadlocks when awaiting Network.enable before issuing Runtime.runIfWaitingForDebugger. } // Enable enables network tracking, network events will now be delivered to // the client. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-enable -// -// parameters: -func Enable() *EnableParams { - return &EnableParams{ - ReportDirectSocketTraffic: false, - EnableDurableMessages: false, - } -} - -// WithMaxTotalBufferSize buffer size in bytes to use when preserving network -// payloads (XHRs, etc). This is the maximum number of bytes that will be -// collected by this DevTools session. -func (p EnableParams) WithMaxTotalBufferSize(maxTotalBufferSize int64) *EnableParams { - p.MaxTotalBufferSize = maxTotalBufferSize - return &p -} - -// WithMaxResourceBufferSize per-resource buffer size in bytes to use when -// preserving network payloads (XHRs, etc). -func (p EnableParams) WithMaxResourceBufferSize(maxResourceBufferSize int64) *EnableParams { - p.MaxResourceBufferSize = maxResourceBufferSize - return &p -} - -// WithMaxPostDataSize longest post body size (in bytes) that would be -// included in requestWillBeSent notification. -func (p EnableParams) WithMaxPostDataSize(maxPostDataSize int64) *EnableParams { - p.MaxPostDataSize = maxPostDataSize - return &p -} - -// WithReportDirectSocketTraffic whether DirectSocket chunk send/receive -// events should be reported. -func (p EnableParams) WithReportDirectSocketTraffic(reportDirectSocketTraffic bool) *EnableParams { - p.ReportDirectSocketTraffic = reportDirectSocketTraffic - return &p -} - -// WithEnableDurableMessages enable storing response bodies outside of -// renderer, so that these survive a cross-process navigation. Requires -// maxTotalBufferSize to be set. Currently defaults to false. This field is -// being deprecated in favor of the dedicated configureDurableMessages command, -// due to the possibility of deadlocks when awaiting Network.enable before -// issuing Runtime.runIfWaitingForDebugger. -func (p EnableParams) WithEnableDurableMessages(enableDurableMessages bool) *EnableParams { - p.EnableDurableMessages = enableDurableMessages - return &p -} - -// Do executes Network.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, p, nil) -} +var Enable = cdp.Command[EnableParams, cdp.Empty]{Method: CommandEnable} -// ConfigureDurableMessagesParams configures storing response bodies outside -// of renderer, so that these survive a cross-process navigation. If -// maxTotalBufferSize is not set, durable messages are disabled. +// ConfigureDurableMessagesParams are the parameters of the command +// Network.configureDurableMessages. type ConfigureDurableMessagesParams struct { - MaxTotalBufferSize int64 `json:"maxTotalBufferSize,omitempty,omitzero"` // Buffer size in bytes to use when preserving network payloads (XHRs, etc). - MaxResourceBufferSize int64 `json:"maxResourceBufferSize,omitempty,omitzero"` // Per-resource buffer size in bytes to use when preserving network payloads (XHRs, etc). + MaxTotalBufferSize *int64 `json:"maxTotalBufferSize,omitempty,omitzero"` // Buffer size in bytes to use when preserving network payloads (XHRs, etc). + MaxResourceBufferSize *int64 `json:"maxResourceBufferSize,omitempty,omitzero"` // Per-resource buffer size in bytes to use when preserving network payloads (XHRs, etc). } // ConfigureDurableMessages configures storing response bodies outside of @@ -340,322 +115,125 @@ type ConfigureDurableMessagesParams struct { // maxTotalBufferSize is not set, durable messages are disabled. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-configureDurableMessages -// -// parameters: -func ConfigureDurableMessages() *ConfigureDurableMessagesParams { - return &ConfigureDurableMessagesParams{} -} - -// WithMaxTotalBufferSize buffer size in bytes to use when preserving network -// payloads (XHRs, etc). -func (p ConfigureDurableMessagesParams) WithMaxTotalBufferSize(maxTotalBufferSize int64) *ConfigureDurableMessagesParams { - p.MaxTotalBufferSize = maxTotalBufferSize - return &p -} - -// WithMaxResourceBufferSize per-resource buffer size in bytes to use when -// preserving network payloads (XHRs, etc). -func (p ConfigureDurableMessagesParams) WithMaxResourceBufferSize(maxResourceBufferSize int64) *ConfigureDurableMessagesParams { - p.MaxResourceBufferSize = maxResourceBufferSize - return &p -} +var ConfigureDurableMessages = cdp.Command[ConfigureDurableMessagesParams, cdp.Empty]{Method: CommandConfigureDurableMessages} -// Do executes Network.configureDurableMessages against the provided context. -func (p *ConfigureDurableMessagesParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandConfigureDurableMessages, p, nil) -} - -// GetCertificateParams returns the DER-encoded certificate. +// GetCertificateParams are the parameters of the command +// Network.getCertificate. type GetCertificateParams struct { Origin string `json:"origin"` // Origin to get certificate for. } -// GetCertificate returns the DER-encoded certificate. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCertificate -// -// parameters: -// -// origin - Origin to get certificate for. -func GetCertificate(origin string) *GetCertificateParams { - return &GetCertificateParams{ - Origin: origin, - } -} - -// GetCertificateReturns return values. -type GetCertificateReturns struct { +// GetCertificateResult is the result of the command Network.getCertificate. +type GetCertificateResult struct { TableNames []string `json:"tableNames,omitempty,omitzero"` } -// Do executes Network.getCertificate against the provided context. -// -// returns: +// GetCertificate returns the DER-encoded certificate. // -// tableNames -func (p *GetCertificateParams) Do(ctx context.Context) (tableNames []string, err error) { - // execute - var res GetCertificateReturns - err = cdp.Execute(ctx, CommandGetCertificate, p, &res) - if err != nil { - return nil, err - } - - return res.TableNames, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCertificate +var GetCertificate = cdp.Command[GetCertificateParams, GetCertificateResult]{Method: CommandGetCertificate} -// GetCookiesParams returns all browser cookies for the current URL. -// Depending on the backend support, will return detailed cookie information in -// the cookies field. +// GetCookiesParams are the parameters of the command Network.getCookies. type GetCookiesParams struct { URLs []string `json:"urls,omitempty,omitzero"` // The list of URLs for which applicable cookies will be fetched. If not specified, it's assumed to be set to the list containing the URLs of the page and all of its subframes. } +// GetCookiesResult is the result of the command Network.getCookies. +type GetCookiesResult struct { + Cookies []*Cookie `json:"cookies,omitempty,omitzero"` // Array of cookie objects. +} + // GetCookies returns all browser cookies for the current URL. Depending on // the backend support, will return detailed cookie information in the cookies // field. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCookies -// -// parameters: -func GetCookies() *GetCookiesParams { - return &GetCookiesParams{} -} +var GetCookies = cdp.Command[GetCookiesParams, GetCookiesResult]{Method: CommandGetCookies} -// WithURLs the list of URLs for which applicable cookies will be fetched. If -// not specified, it's assumed to be set to the list containing the URLs of the -// page and all of its subframes. -func (p GetCookiesParams) WithURLs(urls []string) *GetCookiesParams { - p.URLs = urls - return &p -} - -// GetCookiesReturns return values. -type GetCookiesReturns struct { - Cookies []*Cookie `json:"cookies,omitempty,omitzero"` // Array of cookie objects. -} - -// Do executes Network.getCookies against the provided context. -// -// returns: -// -// cookies - Array of cookie objects. -func (p *GetCookiesParams) Do(ctx context.Context) (cookies []*Cookie, err error) { - // execute - var res GetCookiesReturns - err = cdp.Execute(ctx, CommandGetCookies, p, &res) - if err != nil { - return nil, err - } - - return res.Cookies, nil -} - -// GetResponseBodyParams returns content served for the given request. +// GetResponseBodyParams are the parameters of the command +// Network.getResponseBody. type GetResponseBodyParams struct { RequestID RequestID `json:"requestId"` // Identifier of the network request to get content for. } -// GetResponseBody returns content served for the given request. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBody -// -// parameters: -// -// requestID - Identifier of the network request to get content for. -func GetResponseBody(requestID RequestID) *GetResponseBodyParams { - return &GetResponseBodyParams{ - RequestID: requestID, - } -} - -// GetResponseBodyReturns return values. -type GetResponseBodyReturns struct { - Body string `json:"body,omitempty,omitzero"` // Response body. +// GetResponseBodyResult is the result of the command +// Network.getResponseBody. +type GetResponseBodyResult struct { + Body []byte `json:"body,omitempty,omitzero"` // Response body. Base64encoded bool `json:"base64Encoded"` // True, if content was sent as base64. } -// Do executes Network.getResponseBody against the provided context. -// -// returns: -// -// body - Response body. -func (p *GetResponseBodyParams) Do(ctx context.Context) (body []byte, err error) { - // execute - var res GetResponseBodyReturns - err = cdp.Execute(ctx, CommandGetResponseBody, p, &res) - if err != nil { - return nil, err +// UnmarshalJSON decodes the value. The browser sends body as text, or as +// base64 when r.Base64encoded, and Body holds the decoded bytes. +func (r *GetResponseBodyResult) UnmarshalJSON(buf []byte) error { + type plain GetResponseBodyResult + aux := struct { + *plain + Body string `json:"body"` + }{plain: (*plain)(r)} + if err := jsonv2.Unmarshal(buf, &aux); err != nil { + return err } - - // decode - var dec []byte - if res.Base64encoded { - dec, err = base64.StdEncoding.DecodeString(res.Body) + if r.Base64encoded { + b, err := base64.StdEncoding.DecodeString(aux.Body) if err != nil { - return nil, err + return fmt.Errorf("decoding body: %w", err) } - } else { - dec = []byte(res.Body) + r.Body = b + return nil } - return dec, nil + r.Body = []byte(aux.Body) + return nil } -// GetRequestPostDataParams returns post data sent with the request. Returns -// an error when no data was sent with the request. +// GetResponseBody returns content served for the given request. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBody +var GetResponseBody = cdp.Command[GetResponseBodyParams, GetResponseBodyResult]{Method: CommandGetResponseBody} + +// GetRequestPostDataParams are the parameters of the command +// Network.getRequestPostData. type GetRequestPostDataParams struct { RequestID RequestID `json:"requestId"` // Identifier of the network request to get content for. } -// GetRequestPostData returns post data sent with the request. Returns an -// error when no data was sent with the request. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getRequestPostData -// -// parameters: -// -// requestID - Identifier of the network request to get content for. -func GetRequestPostData(requestID RequestID) *GetRequestPostDataParams { - return &GetRequestPostDataParams{ - RequestID: requestID, - } -} - -// GetRequestPostDataReturns return values. -type GetRequestPostDataReturns struct { - PostData string `json:"postData,omitempty,omitzero"` // Request body string, omitting files from multipart requests +// GetRequestPostDataResult is the result of the command +// Network.getRequestPostData. +type GetRequestPostDataResult struct { + PostData []byte `json:"postData,omitempty,omitzero"` // Request body string, omitting files from multipart requests Base64encoded bool `json:"base64Encoded"` // True, if content was sent as base64. } -// Do executes Network.getRequestPostData against the provided context. -// -// returns: -// -// postData - Request body string, omitting files from multipart requests -func (p *GetRequestPostDataParams) Do(ctx context.Context) (postData []byte, err error) { - // execute - var res GetRequestPostDataReturns - err = cdp.Execute(ctx, CommandGetRequestPostData, p, &res) - if err != nil { - return nil, err +// UnmarshalJSON decodes the value. The browser sends postData as text, or as +// base64 when r.Base64encoded, and PostData holds the decoded bytes. +func (r *GetRequestPostDataResult) UnmarshalJSON(buf []byte) error { + type plain GetRequestPostDataResult + aux := struct { + *plain + PostData string `json:"postData"` + }{plain: (*plain)(r)} + if err := jsonv2.Unmarshal(buf, &aux); err != nil { + return err } - - // decode - var dec []byte - if res.Base64encoded { - dec, err = base64.StdEncoding.DecodeString(res.PostData) + if r.Base64encoded { + b, err := base64.StdEncoding.DecodeString(aux.PostData) if err != nil { - return nil, err + return fmt.Errorf("decoding postData: %w", err) } - } else { - dec = []byte(res.PostData) - } - return dec, nil -} - -// GetResponseBodyForInterceptionParams returns content served for the given -// currently intercepted request. -type GetResponseBodyForInterceptionParams struct { - InterceptionID InterceptionID `json:"interceptionId"` // Identifier for the intercepted request to get body for. -} - -// GetResponseBodyForInterception returns content served for the given -// currently intercepted request. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBodyForInterception -// -// parameters: -// -// interceptionID - Identifier for the intercepted request to get body for. -func GetResponseBodyForInterception(interceptionID InterceptionID) *GetResponseBodyForInterceptionParams { - return &GetResponseBodyForInterceptionParams{ - InterceptionID: interceptionID, + r.PostData = b + return nil } + r.PostData = []byte(aux.PostData) + return nil } -// GetResponseBodyForInterceptionReturns return values. -type GetResponseBodyForInterceptionReturns struct { - Body string `json:"body,omitempty,omitzero"` // Response body. - Base64encoded bool `json:"base64Encoded"` // True, if content was sent as base64. -} - -// Do executes Network.getResponseBodyForInterception against the provided context. -// -// returns: -// -// body - Response body. -func (p *GetResponseBodyForInterceptionParams) Do(ctx context.Context) (body []byte, err error) { - // execute - var res GetResponseBodyForInterceptionReturns - err = cdp.Execute(ctx, CommandGetResponseBodyForInterception, p, &res) - if err != nil { - return nil, err - } - - // decode - var dec []byte - if res.Base64encoded { - dec, err = base64.StdEncoding.DecodeString(res.Body) - if err != nil { - return nil, err - } - } else { - dec = []byte(res.Body) - } - return dec, nil -} - -// TakeResponseBodyForInterceptionAsStreamParams returns a handle to the -// stream representing the response body. Note that after this command, the -// intercepted request can't be continued as is -- you either need to cancel it -// or to provide the response body. The stream only supports sequential read, -// IO.read will fail if the position is specified. -type TakeResponseBodyForInterceptionAsStreamParams struct { - InterceptionID InterceptionID `json:"interceptionId"` -} - -// TakeResponseBodyForInterceptionAsStream returns a handle to the stream -// representing the response body. Note that after this command, the intercepted -// request can't be continued as is -- you either need to cancel it or to -// provide the response body. The stream only supports sequential read, IO.read -// will fail if the position is specified. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-takeResponseBodyForInterceptionAsStream -// -// parameters: -// -// interceptionID -func TakeResponseBodyForInterceptionAsStream(interceptionID InterceptionID) *TakeResponseBodyForInterceptionAsStreamParams { - return &TakeResponseBodyForInterceptionAsStreamParams{ - InterceptionID: interceptionID, - } -} - -// TakeResponseBodyForInterceptionAsStreamReturns return values. -type TakeResponseBodyForInterceptionAsStreamReturns struct { - Stream io.StreamHandle `json:"stream,omitempty,omitzero"` -} - -// Do executes Network.takeResponseBodyForInterceptionAsStream against the provided context. -// -// returns: +// GetRequestPostData returns post data sent with the request. Returns an +// error when no data was sent with the request. // -// stream -func (p *TakeResponseBodyForInterceptionAsStreamParams) Do(ctx context.Context) (stream io.StreamHandle, err error) { - // execute - var res TakeResponseBodyForInterceptionAsStreamReturns - err = cdp.Execute(ctx, CommandTakeResponseBodyForInterceptionAsStream, p, &res) - if err != nil { - return "", err - } - - return res.Stream, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getRequestPostData +var GetRequestPostData = cdp.Command[GetRequestPostDataParams, GetRequestPostDataResult]{Method: CommandGetRequestPostData} -// ReplayXHRParams this method sends a new XMLHttpRequest which is identical -// to the original one. The following parameters should be identical: method, -// url, async, request body, extra headers, withCredentials attribute, user, -// password. +// ReplayXHRParams are the parameters of the command Network.replayXHR. type ReplayXHRParams struct { RequestID RequestID `json:"requestId"` // Identifier of XHR to replay. } @@ -666,80 +244,30 @@ type ReplayXHRParams struct { // password. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-replayXHR -// -// parameters: -// -// requestID - Identifier of XHR to replay. -func ReplayXHR(requestID RequestID) *ReplayXHRParams { - return &ReplayXHRParams{ - RequestID: requestID, - } -} +var ReplayXHR = cdp.Command[ReplayXHRParams, cdp.Empty]{Method: CommandReplayXHR} -// Do executes Network.replayXHR against the provided context. -func (p *ReplayXHRParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandReplayXHR, p, nil) -} - -// SearchInResponseBodyParams searches for given string in response content. +// SearchInResponseBodyParams are the parameters of the command +// Network.searchInResponseBody. type SearchInResponseBodyParams struct { - RequestID RequestID `json:"requestId"` // Identifier of the network response to search. - Query string `json:"query"` // String to search for. - CaseSensitive bool `json:"caseSensitive"` // If true, search is case sensitive. - IsRegex bool `json:"isRegex"` // If true, treats string parameter as regex. + RequestID RequestID `json:"requestId"` // Identifier of the network response to search. + Query string `json:"query"` // String to search for. + CaseSensitive *bool `json:"caseSensitive,omitempty,omitzero"` // If true, search is case sensitive. + IsRegex *bool `json:"isRegex,omitempty,omitzero"` // If true, treats string parameter as regex. } -// SearchInResponseBody searches for given string in response content. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-searchInResponseBody -// -// parameters: -// -// requestID - Identifier of the network response to search. -// query - String to search for. -func SearchInResponseBody(requestID RequestID, query string) *SearchInResponseBodyParams { - return &SearchInResponseBodyParams{ - RequestID: requestID, - Query: query, - CaseSensitive: false, - IsRegex: false, - } -} - -// WithCaseSensitive if true, search is case sensitive. -func (p SearchInResponseBodyParams) WithCaseSensitive(caseSensitive bool) *SearchInResponseBodyParams { - p.CaseSensitive = caseSensitive - return &p -} - -// WithIsRegex if true, treats string parameter as regex. -func (p SearchInResponseBodyParams) WithIsRegex(isRegex bool) *SearchInResponseBodyParams { - p.IsRegex = isRegex - return &p -} - -// SearchInResponseBodyReturns return values. -type SearchInResponseBodyReturns struct { +// SearchInResponseBodyResult is the result of the command +// Network.searchInResponseBody. +type SearchInResponseBodyResult struct { Result []*debugger.SearchMatch `json:"result,omitempty,omitzero"` // List of search matches. } -// Do executes Network.searchInResponseBody against the provided context. -// -// returns: +// SearchInResponseBody searches for given string in response content. // -// result - List of search matches. -func (p *SearchInResponseBodyParams) Do(ctx context.Context) (result []*debugger.SearchMatch, err error) { - // execute - var res SearchInResponseBodyReturns - err = cdp.Execute(ctx, CommandSearchInResponseBody, p, &res) - if err != nil { - return nil, err - } - - return res.Result, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-searchInResponseBody +var SearchInResponseBody = cdp.Command[SearchInResponseBodyParams, SearchInResponseBodyResult]{Method: CommandSearchInResponseBody} -// SetBlockedURLsParams blocks URLs from loading. +// SetBlockedURLsParams are the parameters of the command +// Network.setBlockedURLs. type SetBlockedURLsParams struct { URLPatterns []*BlockPattern `json:"urlPatterns,omitempty,omitzero"` // Patterns to match in the order in which they are given. These patterns also take precedence over any wildcard patterns defined in urls. } @@ -747,27 +275,10 @@ type SetBlockedURLsParams struct { // SetBlockedURLs blocks URLs from loading. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setBlockedURLs -// -// parameters: -func SetBlockedURLs() *SetBlockedURLsParams { - return &SetBlockedURLsParams{} -} +var SetBlockedURLs = cdp.Command[SetBlockedURLsParams, cdp.Empty]{Method: CommandSetBlockedURLs} -// WithURLPatterns patterns to match in the order in which they are given. -// These patterns also take precedence over any wildcard patterns defined in -// urls. -func (p SetBlockedURLsParams) WithURLPatterns(urlPatterns []*BlockPattern) *SetBlockedURLsParams { - p.URLPatterns = urlPatterns - return &p -} - -// Do executes Network.setBlockedURLs against the provided context. -func (p *SetBlockedURLsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetBlockedURLs, p, nil) -} - -// SetBypassServiceWorkerParams toggles ignoring of service worker for each -// request. +// SetBypassServiceWorkerParams are the parameters of the command +// Network.setBypassServiceWorker. type SetBypassServiceWorkerParams struct { Bypass bool `json:"bypass"` // Bypass service worker and load from network. } @@ -776,23 +287,10 @@ type SetBypassServiceWorkerParams struct { // request. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setBypassServiceWorker -// -// parameters: -// -// bypass - Bypass service worker and load from network. -func SetBypassServiceWorker(bypass bool) *SetBypassServiceWorkerParams { - return &SetBypassServiceWorkerParams{ - Bypass: bypass, - } -} +var SetBypassServiceWorker = cdp.Command[SetBypassServiceWorkerParams, cdp.Empty]{Method: CommandSetBypassServiceWorker} -// Do executes Network.setBypassServiceWorker against the provided context. -func (p *SetBypassServiceWorkerParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetBypassServiceWorker, p, nil) -} - -// SetCacheDisabledParams toggles ignoring cache for each request. If true, -// cache will not be used. +// SetCacheDisabledParams are the parameters of the command +// Network.setCacheDisabled. type SetCacheDisabledParams struct { CacheDisabled bool `json:"cacheDisabled"` // Cache disabled state. } @@ -801,33 +299,19 @@ type SetCacheDisabledParams struct { // will not be used. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCacheDisabled -// -// parameters: -// -// cacheDisabled - Cache disabled state. -func SetCacheDisabled(cacheDisabled bool) *SetCacheDisabledParams { - return &SetCacheDisabledParams{ - CacheDisabled: cacheDisabled, - } -} - -// Do executes Network.setCacheDisabled against the provided context. -func (p *SetCacheDisabledParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetCacheDisabled, p, nil) -} +var SetCacheDisabled = cdp.Command[SetCacheDisabledParams, cdp.Empty]{Method: CommandSetCacheDisabled} -// SetCookieParams sets a cookie with the given cookie data; may overwrite -// equivalent cookies if they exist. +// SetCookieParams are the parameters of the command Network.setCookie. type SetCookieParams struct { Name string `json:"name"` // Cookie name. Value string `json:"value"` // Cookie value. URL string `json:"url,omitempty,omitzero"` // The request-URI to associate with the setting of the cookie. This value can affect the default domain, path, source port, and source scheme values of the created cookie. Domain string `json:"domain,omitempty,omitzero"` // Cookie domain. Path string `json:"path,omitempty,omitzero"` // Cookie path. - Secure bool `json:"secure"` // True if cookie is secure. - HTTPOnly bool `json:"httpOnly"` // True if cookie is http-only. + Secure *bool `json:"secure,omitempty,omitzero"` // True if cookie is secure. + HTTPOnly *bool `json:"httpOnly,omitempty,omitzero"` // True if cookie is http-only. SameSite CookieSameSite `json:"sameSite,omitempty,omitzero"` // Cookie SameSite type. - Expires *cdp.TimeSinceEpoch `json:"expires,omitempty,omitzero"` // Cookie expiration date, session cookie if not set + Expires cdp.TimeSinceEpoch `json:"expires,omitempty,omitzero"` // Cookie expiration date, session cookie if not set Priority CookiePriority `json:"priority,omitempty,omitzero"` // Cookie Priority type. SourceScheme CookieSourceScheme `json:"sourceScheme,omitempty,omitzero"` // Cookie source scheme type. SourcePort int64 `json:"sourcePort,omitempty,omitzero"` // Cookie source port. Valid values are {-1, [1, 65535]}, -1 indicates an unspecified port. An unspecified port value allows protocol clients to emulate legacy cookie scope for the port. This is a temporary ability and it will be removed in the future. @@ -838,98 +322,9 @@ type SetCookieParams struct { // equivalent cookies if they exist. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookie -// -// parameters: -// -// name - Cookie name. -// value - Cookie value. -func SetCookie(name string, value string) *SetCookieParams { - return &SetCookieParams{ - Name: name, - Value: value, - Secure: false, - HTTPOnly: false, - } -} - -// WithURL the request-URI to associate with the setting of the cookie. This -// value can affect the default domain, path, source port, and source scheme -// values of the created cookie. -func (p SetCookieParams) WithURL(url string) *SetCookieParams { - p.URL = url - return &p -} - -// WithDomain cookie domain. -func (p SetCookieParams) WithDomain(domain string) *SetCookieParams { - p.Domain = domain - return &p -} - -// WithPath cookie path. -func (p SetCookieParams) WithPath(path string) *SetCookieParams { - p.Path = path - return &p -} - -// WithSecure true if cookie is secure. -func (p SetCookieParams) WithSecure(secure bool) *SetCookieParams { - p.Secure = secure - return &p -} - -// WithHTTPOnly true if cookie is http-only. -func (p SetCookieParams) WithHTTPOnly(httpOnly bool) *SetCookieParams { - p.HTTPOnly = httpOnly - return &p -} - -// WithSameSite cookie SameSite type. -func (p SetCookieParams) WithSameSite(sameSite CookieSameSite) *SetCookieParams { - p.SameSite = sameSite - return &p -} - -// WithExpires cookie expiration date, session cookie if not set. -func (p SetCookieParams) WithExpires(expires *cdp.TimeSinceEpoch) *SetCookieParams { - p.Expires = expires - return &p -} - -// WithPriority cookie Priority type. -func (p SetCookieParams) WithPriority(priority CookiePriority) *SetCookieParams { - p.Priority = priority - return &p -} - -// WithSourceScheme cookie source scheme type. -func (p SetCookieParams) WithSourceScheme(sourceScheme CookieSourceScheme) *SetCookieParams { - p.SourceScheme = sourceScheme - return &p -} - -// WithSourcePort cookie source port. Valid values are {-1, [1, 65535]}, -1 -// indicates an unspecified port. An unspecified port value allows protocol -// clients to emulate legacy cookie scope for the port. This is a temporary -// ability and it will be removed in the future. -func (p SetCookieParams) WithSourcePort(sourcePort int64) *SetCookieParams { - p.SourcePort = sourcePort - return &p -} - -// WithPartitionKey cookie partition key. If not set, the cookie will be set -// as not partitioned. -func (p SetCookieParams) WithPartitionKey(partitionKey *CookiePartitionKey) *SetCookieParams { - p.PartitionKey = partitionKey - return &p -} +var SetCookie = cdp.Command[SetCookieParams, cdp.Empty]{Method: CommandSetCookie} -// Do executes Network.setCookie against the provided context. -func (p *SetCookieParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetCookie, p, nil) -} - -// SetCookiesParams sets given cookies. +// SetCookiesParams are the parameters of the command Network.setCookies. type SetCookiesParams struct { Cookies []*CookieParam `json:"cookies"` // Cookies to be set. } @@ -937,23 +332,10 @@ type SetCookiesParams struct { // SetCookies sets given cookies. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookies -// -// parameters: -// -// cookies - Cookies to be set. -func SetCookies(cookies []*CookieParam) *SetCookiesParams { - return &SetCookiesParams{ - Cookies: cookies, - } -} - -// Do executes Network.setCookies against the provided context. -func (p *SetCookiesParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetCookies, p, nil) -} +var SetCookies = cdp.Command[SetCookiesParams, cdp.Empty]{Method: CommandSetCookies} -// SetExtraHTTPHeadersParams specifies whether to always send extra HTTP -// headers with the requests from this page. +// SetExtraHTTPHeadersParams are the parameters of the command +// Network.setExtraHTTPHeaders. type SetExtraHTTPHeadersParams struct { Headers Headers `json:"headers"` // Map with extra HTTP headers. } @@ -962,23 +344,10 @@ type SetExtraHTTPHeadersParams struct { // with the requests from this page. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setExtraHTTPHeaders -// -// parameters: -// -// headers - Map with extra HTTP headers. -func SetExtraHTTPHeaders(headers Headers) *SetExtraHTTPHeadersParams { - return &SetExtraHTTPHeadersParams{ - Headers: headers, - } -} - -// Do executes Network.setExtraHTTPHeaders against the provided context. -func (p *SetExtraHTTPHeadersParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetExtraHTTPHeaders, p, nil) -} +var SetExtraHTTPHeaders = cdp.Command[SetExtraHTTPHeadersParams, cdp.Empty]{Method: CommandSetExtraHTTPHeaders} -// SetAttachDebugStackParams specifies whether to attach a page script stack -// id in requests. +// SetAttachDebugStackParams are the parameters of the command +// Network.setAttachDebugStack. type SetAttachDebugStackParams struct { Enabled bool `json:"enabled"` // Whether to attach a page script stack for debugging purpose. } @@ -987,117 +356,47 @@ type SetAttachDebugStackParams struct { // requests. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setAttachDebugStack -// -// parameters: -// -// enabled - Whether to attach a page script stack for debugging purpose. -func SetAttachDebugStack(enabled bool) *SetAttachDebugStackParams { - return &SetAttachDebugStackParams{ - Enabled: enabled, - } -} +var SetAttachDebugStack = cdp.Command[SetAttachDebugStackParams, cdp.Empty]{Method: CommandSetAttachDebugStack} -// Do executes Network.setAttachDebugStack against the provided context. -func (p *SetAttachDebugStackParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetAttachDebugStack, p, nil) -} - -// StreamResourceContentParams enables streaming of the response for the -// given requestId. If enabled, the dataReceived event contains the data that -// was received during streaming. +// StreamResourceContentParams are the parameters of the command +// Network.streamResourceContent. type StreamResourceContentParams struct { RequestID RequestID `json:"requestId"` // Identifier of the request to stream. } +// StreamResourceContentResult is the result of the command +// Network.streamResourceContent. +type StreamResourceContentResult struct { + BufferedData []byte `json:"bufferedData,omitempty,omitzero"` // Data that has been buffered until streaming is enabled. +} + // StreamResourceContent enables streaming of the response for the given // requestId. If enabled, the dataReceived event contains the data that was // received during streaming. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-streamResourceContent -// -// parameters: -// -// requestID - Identifier of the request to stream. -func StreamResourceContent(requestID RequestID) *StreamResourceContentParams { - return &StreamResourceContentParams{ - RequestID: requestID, - } -} - -// StreamResourceContentReturns return values. -type StreamResourceContentReturns struct { - BufferedData string `json:"bufferedData,omitempty,omitzero"` // Data that has been buffered until streaming is enabled. -} - -// Do executes Network.streamResourceContent against the provided context. -// -// returns: -// -// bufferedData - Data that has been buffered until streaming is enabled. -func (p *StreamResourceContentParams) Do(ctx context.Context) (bufferedData []byte, err error) { - // execute - var res StreamResourceContentReturns - err = cdp.Execute(ctx, CommandStreamResourceContent, p, &res) - if err != nil { - return nil, err - } - - // decode - var dec []byte - dec, err = base64.StdEncoding.DecodeString(res.BufferedData) - if err != nil { - return nil, err - } - return dec, nil -} +var StreamResourceContent = cdp.Command[StreamResourceContentParams, StreamResourceContentResult]{Method: CommandStreamResourceContent} -// GetSecurityIsolationStatusParams returns information about the COEP/COOP -// isolation status. +// GetSecurityIsolationStatusParams are the parameters of the command +// Network.getSecurityIsolationStatus. type GetSecurityIsolationStatusParams struct { FrameID cdp.FrameID `json:"frameId,omitempty,omitzero"` // If no frameId is provided, the status of the target is provided. } -// GetSecurityIsolationStatus returns information about the COEP/COOP -// isolation status. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getSecurityIsolationStatus -// -// parameters: -func GetSecurityIsolationStatus() *GetSecurityIsolationStatusParams { - return &GetSecurityIsolationStatusParams{} -} - -// WithFrameID if no frameId is provided, the status of the target is -// provided. -func (p GetSecurityIsolationStatusParams) WithFrameID(frameID cdp.FrameID) *GetSecurityIsolationStatusParams { - p.FrameID = frameID - return &p -} - -// GetSecurityIsolationStatusReturns return values. -type GetSecurityIsolationStatusReturns struct { +// GetSecurityIsolationStatusResult is the result of the command +// Network.getSecurityIsolationStatus. +type GetSecurityIsolationStatusResult struct { Status *SecurityIsolationStatus `json:"status,omitempty,omitzero"` } -// Do executes Network.getSecurityIsolationStatus against the provided context. -// -// returns: +// GetSecurityIsolationStatus returns information about the COEP/COOP +// isolation status. // -// status -func (p *GetSecurityIsolationStatusParams) Do(ctx context.Context) (status *SecurityIsolationStatus, err error) { - // execute - var res GetSecurityIsolationStatusReturns - err = cdp.Execute(ctx, CommandGetSecurityIsolationStatus, p, &res) - if err != nil { - return nil, err - } - - return res.Status, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getSecurityIsolationStatus +var GetSecurityIsolationStatus = cdp.Command[GetSecurityIsolationStatusParams, GetSecurityIsolationStatusResult]{Method: CommandGetSecurityIsolationStatus} -// EnableReportingAPIParams enables tracking for the Reporting API, events -// generated by the Reporting API will now be delivered to the client. Enabling -// triggers 'reportingApiReportAdded' for all existing reports. +// EnableReportingAPIParams are the parameters of the command +// Network.enableReportingApi. type EnableReportingAPIParams struct { Enable bool `json:"enable"` // Whether to enable or disable events for the Reporting API } @@ -1107,23 +406,10 @@ type EnableReportingAPIParams struct { // triggers 'reportingApiReportAdded' for all existing reports. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-enableReportingApi -// -// parameters: -// -// enable - Whether to enable or disable events for the Reporting API -func EnableReportingAPI(enable bool) *EnableReportingAPIParams { - return &EnableReportingAPIParams{ - Enable: enable, - } -} - -// Do executes Network.enableReportingApi against the provided context. -func (p *EnableReportingAPIParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnableReportingAPI, p, nil) -} +var EnableReportingAPI = cdp.Command[EnableReportingAPIParams, cdp.Empty]{Method: CommandEnableReportingAPI} -// EnableDeviceBoundSessionsParams sets up tracking device bound sessions and -// fetching of initial set of sessions. +// EnableDeviceBoundSessionsParams are the parameters of the command +// Network.enableDeviceBoundSessions. type EnableDeviceBoundSessionsParams struct { Enable bool `json:"enable"` // Whether to enable or disable events. } @@ -1132,22 +418,10 @@ type EnableDeviceBoundSessionsParams struct { // fetching of initial set of sessions. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-enableDeviceBoundSessions -// -// parameters: -// -// enable - Whether to enable or disable events. -func EnableDeviceBoundSessions(enable bool) *EnableDeviceBoundSessionsParams { - return &EnableDeviceBoundSessionsParams{ - Enable: enable, - } -} - -// Do executes Network.enableDeviceBoundSessions against the provided context. -func (p *EnableDeviceBoundSessionsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnableDeviceBoundSessions, p, nil) -} +var EnableDeviceBoundSessions = cdp.Command[EnableDeviceBoundSessionsParams, cdp.Empty]{Method: CommandEnableDeviceBoundSessions} -// DeleteDeviceBoundSessionParams deletes a device bound session. +// DeleteDeviceBoundSessionParams are the parameters of the command +// Network.deleteDeviceBoundSession. type DeleteDeviceBoundSessionParams struct { Key *DeviceBoundSessionKey `json:"key"` } @@ -1155,168 +429,327 @@ type DeleteDeviceBoundSessionParams struct { // DeleteDeviceBoundSession deletes a device bound session. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-deleteDeviceBoundSession -// -// parameters: -// -// key -func DeleteDeviceBoundSession(key *DeviceBoundSessionKey) *DeleteDeviceBoundSessionParams { - return &DeleteDeviceBoundSessionParams{ - Key: key, - } -} - -// Do executes Network.deleteDeviceBoundSession against the provided context. -func (p *DeleteDeviceBoundSessionParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDeleteDeviceBoundSession, p, nil) -} +var DeleteDeviceBoundSession = cdp.Command[DeleteDeviceBoundSessionParams, cdp.Empty]{Method: CommandDeleteDeviceBoundSession} -// FetchSchemefulSiteParams fetches the schemeful site for a specific origin. +// FetchSchemefulSiteParams are the parameters of the command +// Network.fetchSchemefulSite. type FetchSchemefulSiteParams struct { Origin string `json:"origin"` // The URL origin. } -// FetchSchemefulSite fetches the schemeful site for a specific origin. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-fetchSchemefulSite -// -// parameters: -// -// origin - The URL origin. -func FetchSchemefulSite(origin string) *FetchSchemefulSiteParams { - return &FetchSchemefulSiteParams{ - Origin: origin, - } -} - -// FetchSchemefulSiteReturns return values. -type FetchSchemefulSiteReturns struct { +// FetchSchemefulSiteResult is the result of the command +// Network.fetchSchemefulSite. +type FetchSchemefulSiteResult struct { SchemefulSite string `json:"schemefulSite,omitempty,omitzero"` // The corresponding schemeful site. } -// Do executes Network.fetchSchemefulSite against the provided context. -// -// returns: +// FetchSchemefulSite fetches the schemeful site for a specific origin. // -// schemefulSite - The corresponding schemeful site. -func (p *FetchSchemefulSiteParams) Do(ctx context.Context) (schemefulSite string, err error) { - // execute - var res FetchSchemefulSiteReturns - err = cdp.Execute(ctx, CommandFetchSchemefulSite, p, &res) - if err != nil { - return "", err - } - - return res.SchemefulSite, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-fetchSchemefulSite +var FetchSchemefulSite = cdp.Command[FetchSchemefulSiteParams, FetchSchemefulSiteResult]{Method: CommandFetchSchemefulSite} -// LoadNetworkResourceParams fetches the resource and returns the content. +// LoadNetworkResourceParams are the parameters of the command +// Network.loadNetworkResource. type LoadNetworkResourceParams struct { FrameID cdp.FrameID `json:"frameId,omitempty,omitzero"` // Frame id to get the resource for. Mandatory for frame targets, and should be omitted for worker targets. URL string `json:"url"` // URL of the resource to get content for. Options *LoadNetworkResourceOptions `json:"options"` // Options for the request. } +// LoadNetworkResourceResult is the result of the command +// Network.loadNetworkResource. +type LoadNetworkResourceResult struct { + Resource *LoadNetworkResourcePageResult `json:"resource,omitempty,omitzero"` +} + // LoadNetworkResource fetches the resource and returns the content. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-loadNetworkResource +var LoadNetworkResource = cdp.Command[LoadNetworkResourceParams, LoadNetworkResourceResult]{Method: CommandLoadNetworkResource} + +// SetCookieControlsParams are the parameters of the command +// Network.setCookieControls. +type SetCookieControlsParams struct { + EnableThirdPartyCookieRestriction bool `json:"enableThirdPartyCookieRestriction"` // Whether 3pc restriction is enabled. +} + +// SetCookieControls sets Controls for third-party cookie access Page reload +// is required before the new cookie behavior will be observed. // -// parameters: +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookieControls +var SetCookieControls = cdp.Command[SetCookieControlsParams, cdp.Empty]{Method: CommandSetCookieControls} + +// DataReceived fired when data chunk was received over the network. // -// url - URL of the resource to get content for. -// options - Options for the request. -func LoadNetworkResource(url string, options *LoadNetworkResourceOptions) *LoadNetworkResourceParams { - return &LoadNetworkResourceParams{ - URL: url, - Options: options, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-dataReceived +var DataReceived = cdp.Event[EventDataReceived]{Method: "Network.dataReceived"} -// WithFrameID frame id to get the resource for. Mandatory for frame targets, -// and should be omitted for worker targets. -func (p LoadNetworkResourceParams) WithFrameID(frameID cdp.FrameID) *LoadNetworkResourceParams { - p.FrameID = frameID - return &p -} +// EventSourceMessageReceived fired when EventSource message is received. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-eventSourceMessageReceived +var EventSourceMessageReceived = cdp.Event[EventEventSourceMessageReceived]{Method: "Network.eventSourceMessageReceived"} -// LoadNetworkResourceReturns return values. -type LoadNetworkResourceReturns struct { - Resource *LoadNetworkResourcePageResult `json:"resource,omitempty,omitzero"` -} +// LoadingFailed fired when HTTP request has failed to load. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-loadingFailed +var LoadingFailed = cdp.Event[EventLoadingFailed]{Method: "Network.loadingFailed"} -// Do executes Network.loadNetworkResource against the provided context. +// LoadingFinished fired when HTTP request has finished loading. // -// returns: +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-loadingFinished +var LoadingFinished = cdp.Event[EventLoadingFinished]{Method: "Network.loadingFinished"} + +// RequestServedFromCache fired if request ended up loading from cache. // -// resource -func (p *LoadNetworkResourceParams) Do(ctx context.Context) (resource *LoadNetworkResourcePageResult, err error) { - // execute - var res LoadNetworkResourceReturns - err = cdp.Execute(ctx, CommandLoadNetworkResource, p, &res) - if err != nil { - return nil, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-requestServedFromCache +var RequestServedFromCache = cdp.Event[EventRequestServedFromCache]{Method: "Network.requestServedFromCache"} - return res.Resource, nil -} +// RequestWillBeSent fired when page is about to send HTTP request. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-requestWillBeSent +var RequestWillBeSent = cdp.Event[EventRequestWillBeSent]{Method: "Network.requestWillBeSent"} -// SetCookieControlsParams sets Controls for third-party cookie access Page -// reload is required before the new cookie behavior will be observed. -type SetCookieControlsParams struct { - EnableThirdPartyCookieRestriction bool `json:"enableThirdPartyCookieRestriction"` // Whether 3pc restriction is enabled. -} +// ResourceChangedPriority fired when resource loading priority is changed. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-resourceChangedPriority +var ResourceChangedPriority = cdp.Event[EventResourceChangedPriority]{Method: "Network.resourceChangedPriority"} -// SetCookieControls sets Controls for third-party cookie access Page reload -// is required before the new cookie behavior will be observed. +// SignedExchangeReceived fired when a signed exchange was received over the +// network. // -// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookieControls +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-signedExchangeReceived +var SignedExchangeReceived = cdp.Event[EventSignedExchangeReceived]{Method: "Network.signedExchangeReceived"} + +// ResponseReceived fired when HTTP response is available. // -// parameters: +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-responseReceived +var ResponseReceived = cdp.Event[EventResponseReceived]{Method: "Network.responseReceived"} + +// WebSocketClosed fired when WebSocket is closed. // -// enableThirdPartyCookieRestriction - Whether 3pc restriction is enabled. -func SetCookieControls(enableThirdPartyCookieRestriction bool) *SetCookieControlsParams { - return &SetCookieControlsParams{ - EnableThirdPartyCookieRestriction: enableThirdPartyCookieRestriction, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketClosed +var WebSocketClosed = cdp.Event[EventWebSocketClosed]{Method: "Network.webSocketClosed"} -// Do executes Network.setCookieControls against the provided context. -func (p *SetCookieControlsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetCookieControls, p, nil) -} +// WebSocketCreated fired upon WebSocket creation. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketCreated +var WebSocketCreated = cdp.Event[EventWebSocketCreated]{Method: "Network.webSocketCreated"} + +// WebSocketFrameError fired when WebSocket message error occurs. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketFrameError +var WebSocketFrameError = cdp.Event[EventWebSocketFrameError]{Method: "Network.webSocketFrameError"} + +// WebSocketFrameReceived fired when WebSocket message is received. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketFrameReceived +var WebSocketFrameReceived = cdp.Event[EventWebSocketFrameReceived]{Method: "Network.webSocketFrameReceived"} + +// WebSocketFrameSent fired when WebSocket message is sent. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketFrameSent +var WebSocketFrameSent = cdp.Event[EventWebSocketFrameSent]{Method: "Network.webSocketFrameSent"} + +// WebSocketHandshakeResponseReceived fired when WebSocket handshake response +// becomes available. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketHandshakeResponseReceived +var WebSocketHandshakeResponseReceived = cdp.Event[EventWebSocketHandshakeResponseReceived]{Method: "Network.webSocketHandshakeResponseReceived"} + +// WebSocketWillSendHandshakeRequest fired when WebSocket is about to +// initiate handshake. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketWillSendHandshakeRequest +var WebSocketWillSendHandshakeRequest = cdp.Event[EventWebSocketWillSendHandshakeRequest]{Method: "Network.webSocketWillSendHandshakeRequest"} + +// WebTransportCreated fired upon WebTransport creation. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webTransportCreated +var WebTransportCreated = cdp.Event[EventWebTransportCreated]{Method: "Network.webTransportCreated"} + +// WebTransportConnectionEstablished fired when WebTransport handshake is +// finished. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webTransportConnectionEstablished +var WebTransportConnectionEstablished = cdp.Event[EventWebTransportConnectionEstablished]{Method: "Network.webTransportConnectionEstablished"} + +// WebTransportClosed fired when WebTransport is disposed. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webTransportClosed +var WebTransportClosed = cdp.Event[EventWebTransportClosed]{Method: "Network.webTransportClosed"} + +// DirectTCPSocketCreated fired upon direct_socket.TCPSocket creation. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directTCPSocketCreated +var DirectTCPSocketCreated = cdp.Event[EventDirectTCPSocketCreated]{Method: "Network.directTCPSocketCreated"} + +// DirectTCPSocketOpened fired when direct_socket.TCPSocket connection is +// opened. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directTCPSocketOpened +var DirectTCPSocketOpened = cdp.Event[EventDirectTCPSocketOpened]{Method: "Network.directTCPSocketOpened"} + +// DirectTCPSocketAborted fired when direct_socket.TCPSocket is aborted. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directTCPSocketAborted +var DirectTCPSocketAborted = cdp.Event[EventDirectTCPSocketAborted]{Method: "Network.directTCPSocketAborted"} + +// DirectTCPSocketClosed fired when direct_socket.TCPSocket is closed. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directTCPSocketClosed +var DirectTCPSocketClosed = cdp.Event[EventDirectTCPSocketClosed]{Method: "Network.directTCPSocketClosed"} + +// DirectTCPSocketChunkSent fired when data is sent to tcp direct socket +// stream. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directTCPSocketChunkSent +var DirectTCPSocketChunkSent = cdp.Event[EventDirectTCPSocketChunkSent]{Method: "Network.directTCPSocketChunkSent"} + +// DirectTCPSocketChunkReceived fired when data is received from tcp direct +// socket stream. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directTCPSocketChunkReceived +var DirectTCPSocketChunkReceived = cdp.Event[EventDirectTCPSocketChunkReceived]{Method: "Network.directTCPSocketChunkReceived"} + +// DirectUDPSocketJoinedMulticastGroup [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directUDPSocketJoinedMulticastGroup +var DirectUDPSocketJoinedMulticastGroup = cdp.Event[EventDirectUDPSocketJoinedMulticastGroup]{Method: "Network.directUDPSocketJoinedMulticastGroup"} + +// DirectUDPSocketLeftMulticastGroup [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directUDPSocketLeftMulticastGroup +var DirectUDPSocketLeftMulticastGroup = cdp.Event[EventDirectUDPSocketLeftMulticastGroup]{Method: "Network.directUDPSocketLeftMulticastGroup"} + +// DirectUDPSocketCreated fired upon direct_socket.UDPSocket creation. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directUDPSocketCreated +var DirectUDPSocketCreated = cdp.Event[EventDirectUDPSocketCreated]{Method: "Network.directUDPSocketCreated"} + +// DirectUDPSocketOpened fired when direct_socket.UDPSocket connection is +// opened. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directUDPSocketOpened +var DirectUDPSocketOpened = cdp.Event[EventDirectUDPSocketOpened]{Method: "Network.directUDPSocketOpened"} + +// DirectUDPSocketAborted fired when direct_socket.UDPSocket is aborted. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directUDPSocketAborted +var DirectUDPSocketAborted = cdp.Event[EventDirectUDPSocketAborted]{Method: "Network.directUDPSocketAborted"} + +// DirectUDPSocketClosed fired when direct_socket.UDPSocket is closed. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directUDPSocketClosed +var DirectUDPSocketClosed = cdp.Event[EventDirectUDPSocketClosed]{Method: "Network.directUDPSocketClosed"} + +// DirectUDPSocketChunkSent fired when message is sent to udp direct socket +// stream. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directUDPSocketChunkSent +var DirectUDPSocketChunkSent = cdp.Event[EventDirectUDPSocketChunkSent]{Method: "Network.directUDPSocketChunkSent"} + +// DirectUDPSocketChunkReceived fired when message is received from udp +// direct socket stream. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-directUDPSocketChunkReceived +var DirectUDPSocketChunkReceived = cdp.Event[EventDirectUDPSocketChunkReceived]{Method: "Network.directUDPSocketChunkReceived"} + +// RequestWillBeSentExtraInfo fired when additional information about a +// requestWillBeSent event is available from the network stack. Not every +// requestWillBeSent event will have an additional requestWillBeSentExtraInfo +// fired for it, and there is no guarantee whether requestWillBeSent or +// requestWillBeSentExtraInfo will be fired first for the same request. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-requestWillBeSentExtraInfo +var RequestWillBeSentExtraInfo = cdp.Event[EventRequestWillBeSentExtraInfo]{Method: "Network.requestWillBeSentExtraInfo"} + +// ResponseReceivedExtraInfo fired when additional information about a +// responseReceived event is available from the network stack. Not every +// responseReceived event will have an additional responseReceivedExtraInfo for +// it, and responseReceivedExtraInfo may be fired before or after +// responseReceived. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-responseReceivedExtraInfo +var ResponseReceivedExtraInfo = cdp.Event[EventResponseReceivedExtraInfo]{Method: "Network.responseReceivedExtraInfo"} + +// ResponseReceivedEarlyHints fired when 103 Early Hints headers is received +// in addition to the common response. Not every responseReceived event will +// have an responseReceivedEarlyHints fired. Only one responseReceivedEarlyHints +// may be fired for eached responseReceived event. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-responseReceivedEarlyHints +var ResponseReceivedEarlyHints = cdp.Event[EventResponseReceivedEarlyHints]{Method: "Network.responseReceivedEarlyHints"} + +// TrustTokenOperationDone fired exactly once for each Trust Token operation. +// Depending on the type of the operation and whether the operation succeeded or +// failed, the event is fired before the corresponding request was sent or after +// the response was received. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-trustTokenOperationDone +var TrustTokenOperationDone = cdp.Event[EventTrustTokenOperationDone]{Method: "Network.trustTokenOperationDone"} + +// PolicyUpdated fired once security policy has been updated. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-policyUpdated +var PolicyUpdated = cdp.Event[EventPolicyUpdated]{Method: "Network.policyUpdated"} + +// ReportingAPIReportAdded is sent whenever a new report is added. And after +// 'enableReportingApi' for all existing reports. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-reportingApiReportAdded +var ReportingAPIReportAdded = cdp.Event[EventReportingAPIReportAdded]{Method: "Network.reportingApiReportAdded"} + +// ReportingAPIReportUpdated [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-reportingApiReportUpdated +var ReportingAPIReportUpdated = cdp.Event[EventReportingAPIReportUpdated]{Method: "Network.reportingApiReportUpdated"} + +// ReportingAPIEndpointsChangedForOrigin [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-reportingApiEndpointsChangedForOrigin +var ReportingAPIEndpointsChangedForOrigin = cdp.Event[EventReportingAPIEndpointsChangedForOrigin]{Method: "Network.reportingApiEndpointsChangedForOrigin"} + +// DeviceBoundSessionsAdded triggered when the initial set of device bound +// sessions is added. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-deviceBoundSessionsAdded +var DeviceBoundSessionsAdded = cdp.Event[EventDeviceBoundSessionsAdded]{Method: "Network.deviceBoundSessionsAdded"} + +// DeviceBoundSessionEventOccurred triggered when a device bound session +// event occurs. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#event-deviceBoundSessionEventOccurred +var DeviceBoundSessionEventOccurred = cdp.Event[EventDeviceBoundSessionEventOccurred]{Method: "Network.deviceBoundSessionEventOccurred"} // Command names. const ( - CommandSetAcceptedEncodings = "Network.setAcceptedEncodings" - CommandClearAcceptedEncodingsOverride = "Network.clearAcceptedEncodingsOverride" - CommandClearBrowserCache = "Network.clearBrowserCache" - CommandClearBrowserCookies = "Network.clearBrowserCookies" - CommandDeleteCookies = "Network.deleteCookies" - CommandDisable = "Network.disable" - CommandEmulateNetworkConditionsByRule = "Network.emulateNetworkConditionsByRule" - CommandOverrideNetworkState = "Network.overrideNetworkState" - CommandEnable = "Network.enable" - CommandConfigureDurableMessages = "Network.configureDurableMessages" - CommandGetCertificate = "Network.getCertificate" - CommandGetCookies = "Network.getCookies" - CommandGetResponseBody = "Network.getResponseBody" - CommandGetRequestPostData = "Network.getRequestPostData" - CommandGetResponseBodyForInterception = "Network.getResponseBodyForInterception" - CommandTakeResponseBodyForInterceptionAsStream = "Network.takeResponseBodyForInterceptionAsStream" - CommandReplayXHR = "Network.replayXHR" - CommandSearchInResponseBody = "Network.searchInResponseBody" - CommandSetBlockedURLs = "Network.setBlockedURLs" - CommandSetBypassServiceWorker = "Network.setBypassServiceWorker" - CommandSetCacheDisabled = "Network.setCacheDisabled" - CommandSetCookie = "Network.setCookie" - CommandSetCookies = "Network.setCookies" - CommandSetExtraHTTPHeaders = "Network.setExtraHTTPHeaders" - CommandSetAttachDebugStack = "Network.setAttachDebugStack" - CommandStreamResourceContent = "Network.streamResourceContent" - CommandGetSecurityIsolationStatus = "Network.getSecurityIsolationStatus" - CommandEnableReportingAPI = "Network.enableReportingApi" - CommandEnableDeviceBoundSessions = "Network.enableDeviceBoundSessions" - CommandDeleteDeviceBoundSession = "Network.deleteDeviceBoundSession" - CommandFetchSchemefulSite = "Network.fetchSchemefulSite" - CommandLoadNetworkResource = "Network.loadNetworkResource" - CommandSetCookieControls = "Network.setCookieControls" + CommandClearBrowserCache = "Network.clearBrowserCache" + CommandClearBrowserCookies = "Network.clearBrowserCookies" + CommandDeleteCookies = "Network.deleteCookies" + CommandDisable = "Network.disable" + CommandEmulateNetworkConditionsByRule = "Network.emulateNetworkConditionsByRule" + CommandOverrideNetworkState = "Network.overrideNetworkState" + CommandEnable = "Network.enable" + CommandConfigureDurableMessages = "Network.configureDurableMessages" + CommandGetCertificate = "Network.getCertificate" + CommandGetCookies = "Network.getCookies" + CommandGetResponseBody = "Network.getResponseBody" + CommandGetRequestPostData = "Network.getRequestPostData" + CommandReplayXHR = "Network.replayXHR" + CommandSearchInResponseBody = "Network.searchInResponseBody" + CommandSetBlockedURLs = "Network.setBlockedURLs" + CommandSetBypassServiceWorker = "Network.setBypassServiceWorker" + CommandSetCacheDisabled = "Network.setCacheDisabled" + CommandSetCookie = "Network.setCookie" + CommandSetCookies = "Network.setCookies" + CommandSetExtraHTTPHeaders = "Network.setExtraHTTPHeaders" + CommandSetAttachDebugStack = "Network.setAttachDebugStack" + CommandStreamResourceContent = "Network.streamResourceContent" + CommandGetSecurityIsolationStatus = "Network.getSecurityIsolationStatus" + CommandEnableReportingAPI = "Network.enableReportingApi" + CommandEnableDeviceBoundSessions = "Network.enableDeviceBoundSessions" + CommandDeleteDeviceBoundSession = "Network.deleteDeviceBoundSession" + CommandFetchSchemefulSite = "Network.fetchSchemefulSite" + CommandLoadNetworkResource = "Network.loadNetworkResource" + CommandSetCookieControls = "Network.setCookieControls" ) diff --git a/vendor/github.com/chromedp/cdproto/network/types.go b/vendor/github.com/chromedp/cdproto/network/types.go index 9b9a6bbd4..1b6ad5f87 100644 --- a/vendor/github.com/chromedp/cdproto/network/types.go +++ b/vendor/github.com/chromedp/cdproto/network/types.go @@ -1,19 +1,16 @@ -package network +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package network import ( - "bytes" - "encoding/json" + "encoding/base64" "fmt" - "strconv" - "strings" "github.com/chromedp/cdproto/cdp" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" "github.com/chromedp/cdproto/io" "github.com/chromedp/cdproto/runtime" "github.com/chromedp/cdproto/security" - "github.com/go-json-experiment/json/jsontext" ) // ResourceType resource type as it was perceived by the rendering engine. @@ -49,56 +46,6 @@ const ( ResourceTypeOther ResourceType = "Other" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ResourceType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ResourceType(s) { - case ResourceTypeDocument: - *t = ResourceTypeDocument - case ResourceTypeStylesheet: - *t = ResourceTypeStylesheet - case ResourceTypeImage: - *t = ResourceTypeImage - case ResourceTypeMedia: - *t = ResourceTypeMedia - case ResourceTypeFont: - *t = ResourceTypeFont - case ResourceTypeScript: - *t = ResourceTypeScript - case ResourceTypeTextTrack: - *t = ResourceTypeTextTrack - case ResourceTypeXHR: - *t = ResourceTypeXHR - case ResourceTypeFetch: - *t = ResourceTypeFetch - case ResourceTypePrefetch: - *t = ResourceTypePrefetch - case ResourceTypeEventSource: - *t = ResourceTypeEventSource - case ResourceTypeWebSocket: - *t = ResourceTypeWebSocket - case ResourceTypeManifest: - *t = ResourceTypeManifest - case ResourceTypeSignedExchange: - *t = ResourceTypeSignedExchange - case ResourceTypePing: - *t = ResourceTypePing - case ResourceTypeCSPViolationReport: - *t = ResourceTypeCSPViolationReport - case ResourceTypePreflight: - *t = ResourceTypePreflight - case ResourceTypeFedCM: - *t = ResourceTypeFedCM - case ResourceTypeOther: - *t = ResourceTypeOther - default: - return fmt.Errorf("unknown ResourceType value: %v", s) - } - return nil -} - // RequestID unique network request identifier. Note that this does not // identify individual HTTP requests that are part of a network request. // @@ -110,16 +57,6 @@ func (t RequestID) String() string { return string(t) } -// InterceptionID unique intercepted request identifier. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-InterceptionId -type InterceptionID string - -// String returns the InterceptionID as string value. -func (t InterceptionID) String() string { - return string(t) -} - // ErrorReason network level fetch failure reason. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-ErrorReason @@ -148,46 +85,6 @@ const ( ErrorReasonBlockedByResponse ErrorReason = "BlockedByResponse" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ErrorReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ErrorReason(s) { - case ErrorReasonFailed: - *t = ErrorReasonFailed - case ErrorReasonAborted: - *t = ErrorReasonAborted - case ErrorReasonTimedOut: - *t = ErrorReasonTimedOut - case ErrorReasonAccessDenied: - *t = ErrorReasonAccessDenied - case ErrorReasonConnectionClosed: - *t = ErrorReasonConnectionClosed - case ErrorReasonConnectionReset: - *t = ErrorReasonConnectionReset - case ErrorReasonConnectionRefused: - *t = ErrorReasonConnectionRefused - case ErrorReasonConnectionAborted: - *t = ErrorReasonConnectionAborted - case ErrorReasonConnectionFailed: - *t = ErrorReasonConnectionFailed - case ErrorReasonNameNotResolved: - *t = ErrorReasonNameNotResolved - case ErrorReasonInternetDisconnected: - *t = ErrorReasonInternetDisconnected - case ErrorReasonAddressUnreachable: - *t = ErrorReasonAddressUnreachable - case ErrorReasonBlockedByClient: - *t = ErrorReasonBlockedByClient - case ErrorReasonBlockedByResponse: - *t = ErrorReasonBlockedByResponse - default: - return fmt.Errorf("unknown ErrorReason value: %v", s) - } - return nil -} - // Headers request / response headers as keys / values of JSON object. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-Headers @@ -217,36 +114,6 @@ const ( ConnectionTypeOther ConnectionType = "other" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ConnectionType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ConnectionType(s) { - case ConnectionTypeNone: - *t = ConnectionTypeNone - case ConnectionTypeCellular2g: - *t = ConnectionTypeCellular2g - case ConnectionTypeCellular3g: - *t = ConnectionTypeCellular3g - case ConnectionTypeCellular4g: - *t = ConnectionTypeCellular4g - case ConnectionTypeBluetooth: - *t = ConnectionTypeBluetooth - case ConnectionTypeEthernet: - *t = ConnectionTypeEthernet - case ConnectionTypeWifi: - *t = ConnectionTypeWifi - case ConnectionTypeWimax: - *t = ConnectionTypeWimax - case ConnectionTypeOther: - *t = ConnectionTypeOther - default: - return fmt.Errorf("unknown ConnectionType value: %v", s) - } - return nil -} - // CookieSameSite represents the cookie's 'SameSite' status: // https://tools.ietf.org/html/draft-west-first-party-cookies. // @@ -265,24 +132,6 @@ const ( CookieSameSiteNone CookieSameSite = "None" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CookieSameSite) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CookieSameSite(s) { - case CookieSameSiteStrict: - *t = CookieSameSiteStrict - case CookieSameSiteLax: - *t = CookieSameSiteLax - case CookieSameSiteNone: - *t = CookieSameSiteNone - default: - return fmt.Errorf("unknown CookieSameSite value: %v", s) - } - return nil -} - // CookiePriority represents the cookie's 'Priority' status: // https://tools.ietf.org/html/draft-west-cookie-priority-00. // @@ -301,24 +150,6 @@ const ( CookiePriorityHigh CookiePriority = "High" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CookiePriority) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CookiePriority(s) { - case CookiePriorityLow: - *t = CookiePriorityLow - case CookiePriorityMedium: - *t = CookiePriorityMedium - case CookiePriorityHigh: - *t = CookiePriorityHigh - default: - return fmt.Errorf("unknown CookiePriority value: %v", s) - } - return nil -} - // CookieSourceScheme represents the source scheme of the origin that // originally set the cookie. A value of "Unset" allows protocol clients to // emulate legacy cookie scope for the scheme. This is a temporary ability and @@ -339,24 +170,6 @@ const ( CookieSourceSchemeSecure CookieSourceScheme = "Secure" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CookieSourceScheme) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CookieSourceScheme(s) { - case CookieSourceSchemeUnset: - *t = CookieSourceSchemeUnset - case CookieSourceSchemeNonSecure: - *t = CookieSourceSchemeNonSecure - case CookieSourceSchemeSecure: - *t = CookieSourceSchemeSecure - default: - return fmt.Errorf("unknown CookieSourceScheme value: %v", s) - } - return nil -} - // ResourceTiming timing information for the request. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-ResourceTiming @@ -403,28 +216,6 @@ const ( ResourcePriorityVeryHigh ResourcePriority = "VeryHigh" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ResourcePriority) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ResourcePriority(s) { - case ResourcePriorityVeryLow: - *t = ResourcePriorityVeryLow - case ResourcePriorityLow: - *t = ResourcePriorityLow - case ResourcePriorityMedium: - *t = ResourcePriorityMedium - case ResourcePriorityHigh: - *t = ResourcePriorityHigh - case ResourcePriorityVeryHigh: - *t = ResourcePriorityVeryHigh - default: - return fmt.Errorf("unknown ResourcePriority value: %v", s) - } - return nil -} - // RenderBlockingBehavior the render-blocking behavior of a resource request. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-RenderBlockingBehavior @@ -444,33 +235,11 @@ const ( RenderBlockingBehaviorPotentiallyBlocking RenderBlockingBehavior = "PotentiallyBlocking" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *RenderBlockingBehavior) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch RenderBlockingBehavior(s) { - case RenderBlockingBehaviorBlocking: - *t = RenderBlockingBehaviorBlocking - case RenderBlockingBehaviorInBodyParserBlocking: - *t = RenderBlockingBehaviorInBodyParserBlocking - case RenderBlockingBehaviorNonBlocking: - *t = RenderBlockingBehaviorNonBlocking - case RenderBlockingBehaviorNonBlockingDynamic: - *t = RenderBlockingBehaviorNonBlockingDynamic - case RenderBlockingBehaviorPotentiallyBlocking: - *t = RenderBlockingBehaviorPotentiallyBlocking - default: - return fmt.Errorf("unknown RenderBlockingBehavior value: %v", s) - } - return nil -} - // PostDataEntry post data entry for HTTP request. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-PostDataEntry type PostDataEntry struct { - Bytes string `json:"bytes,omitempty,omitzero"` + Bytes []byte `json:"bytes,omitempty,omitzero"` } // Request HTTP request data. @@ -485,7 +254,7 @@ type Request struct { PostDataEntries []*PostDataEntry `json:"postDataEntries,omitempty,omitzero"` // Request body elements (post data broken into individual entries). MixedContentType security.MixedContentType `json:"mixedContentType,omitempty,omitzero"` // The mixed content type of the request. InitialPriority ResourcePriority `json:"initialPriority"` // Priority of the resource request at the time request is sent. - ReferrerPolicy ReferrerPolicy `json:"referrerPolicy"` // The referrer policy of the request, as defined in https://www.w3.org/TR/referrer-policy/ + ReferrerPolicy RequestReferrerPolicy `json:"referrerPolicy"` // The referrer policy of the request, as defined in https://www.w3.org/TR/referrer-policy/ IsLinkPreload bool `json:"isLinkPreload"` // Whether is loaded via link preload. TrustTokenParams *TrustTokenParams `json:"trustTokenParams,omitempty,omitzero"` // Set for requests when the TrustToken API is used. Contains the parameters passed by the developer (e.g. via "fetch") as understood by the backend. IsSameSite bool `json:"isSameSite"` // True if this resource request is considered to be the 'same site' as the request corresponding to the main frame. @@ -520,8 +289,8 @@ type SecurityDetails struct { SubjectName string `json:"subjectName"` // Certificate subject name. SanList []string `json:"sanList"` // Subject Alternative Name (SAN) DNS names and IP addresses. Issuer string `json:"issuer"` // Name of the issuing CA. - ValidFrom *cdp.TimeSinceEpoch `json:"validFrom"` // Certificate valid from date. - ValidTo *cdp.TimeSinceEpoch `json:"validTo"` // Certificate valid to (expiration) date + ValidFrom cdp.TimeSinceEpoch `json:"validFrom"` // Certificate valid from date. + ValidTo cdp.TimeSinceEpoch `json:"validTo"` // Certificate valid to (expiration) date SignedCertificateTimestampList []*SignedCertificateTimestamp `json:"signedCertificateTimestampList"` // List of signed certificate timestamps (SCTs). CertificateTransparencyCompliance CertificateTransparencyCompliance `json:"certificateTransparencyCompliance"` // Whether the request complied with Certificate Transparency policy ServerSignatureAlgorithm int64 `json:"serverSignatureAlgorithm,omitempty,omitzero"` // The signature algorithm used by the server in the TLS server signature, represented as a TLS SignatureScheme code point. Omitted if not applicable or not known. @@ -546,24 +315,6 @@ const ( CertificateTransparencyComplianceCompliant CertificateTransparencyCompliance = "compliant" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CertificateTransparencyCompliance) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CertificateTransparencyCompliance(s) { - case CertificateTransparencyComplianceUnknown: - *t = CertificateTransparencyComplianceUnknown - case CertificateTransparencyComplianceNotCompliant: - *t = CertificateTransparencyComplianceNotCompliant - case CertificateTransparencyComplianceCompliant: - *t = CertificateTransparencyComplianceCompliant - default: - return fmt.Errorf("unknown CertificateTransparencyCompliance value: %v", s) - } - return nil -} - // BlockedReason the reason why request was blocked. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-BlockedReason @@ -594,50 +345,6 @@ const ( BlockedReasonSriMessageSignatureMismatch BlockedReason = "sri-message-signature-mismatch" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *BlockedReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch BlockedReason(s) { - case BlockedReasonOther: - *t = BlockedReasonOther - case BlockedReasonCsp: - *t = BlockedReasonCsp - case BlockedReasonMixedContent: - *t = BlockedReasonMixedContent - case BlockedReasonOrigin: - *t = BlockedReasonOrigin - case BlockedReasonInspector: - *t = BlockedReasonInspector - case BlockedReasonIntegrity: - *t = BlockedReasonIntegrity - case BlockedReasonSubresourceFilter: - *t = BlockedReasonSubresourceFilter - case BlockedReasonContentType: - *t = BlockedReasonContentType - case BlockedReasonCoepFrameResourceNeedsCoepHeader: - *t = BlockedReasonCoepFrameResourceNeedsCoepHeader - case BlockedReasonCoopSandboxedIframeCannotNavigateToCoopPage: - *t = BlockedReasonCoopSandboxedIframeCannotNavigateToCoopPage - case BlockedReasonCorpNotSameOrigin: - *t = BlockedReasonCorpNotSameOrigin - case BlockedReasonCorpNotSameOriginAfterDefaultedToSameOriginByCoep: - *t = BlockedReasonCorpNotSameOriginAfterDefaultedToSameOriginByCoep - case BlockedReasonCorpNotSameOriginAfterDefaultedToSameOriginByDip: - *t = BlockedReasonCorpNotSameOriginAfterDefaultedToSameOriginByDip - case BlockedReasonCorpNotSameOriginAfterDefaultedToSameOriginByCoepAndDip: - *t = BlockedReasonCorpNotSameOriginAfterDefaultedToSameOriginByCoepAndDip - case BlockedReasonCorpNotSameSite: - *t = BlockedReasonCorpNotSameSite - case BlockedReasonSriMessageSignatureMismatch: - *t = BlockedReasonSriMessageSignatureMismatch - default: - return fmt.Errorf("unknown BlockedReason value: %v", s) - } - return nil -} - // CorsError the reason why request was blocked. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-CorsError @@ -680,74 +387,6 @@ const ( CorsErrorLocalNetworkAccessPermissionDenied CorsError = "LocalNetworkAccessPermissionDenied" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CorsError) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CorsError(s) { - case CorsErrorDisallowedByMode: - *t = CorsErrorDisallowedByMode - case CorsErrorInvalidResponse: - *t = CorsErrorInvalidResponse - case CorsErrorWildcardOriginNotAllowed: - *t = CorsErrorWildcardOriginNotAllowed - case CorsErrorMissingAllowOriginHeader: - *t = CorsErrorMissingAllowOriginHeader - case CorsErrorMultipleAllowOriginValues: - *t = CorsErrorMultipleAllowOriginValues - case CorsErrorInvalidAllowOriginValue: - *t = CorsErrorInvalidAllowOriginValue - case CorsErrorAllowOriginMismatch: - *t = CorsErrorAllowOriginMismatch - case CorsErrorInvalidAllowCredentials: - *t = CorsErrorInvalidAllowCredentials - case CorsErrorCorsDisabledScheme: - *t = CorsErrorCorsDisabledScheme - case CorsErrorPreflightInvalidStatus: - *t = CorsErrorPreflightInvalidStatus - case CorsErrorPreflightDisallowedRedirect: - *t = CorsErrorPreflightDisallowedRedirect - case CorsErrorPreflightWildcardOriginNotAllowed: - *t = CorsErrorPreflightWildcardOriginNotAllowed - case CorsErrorPreflightMissingAllowOriginHeader: - *t = CorsErrorPreflightMissingAllowOriginHeader - case CorsErrorPreflightMultipleAllowOriginValues: - *t = CorsErrorPreflightMultipleAllowOriginValues - case CorsErrorPreflightInvalidAllowOriginValue: - *t = CorsErrorPreflightInvalidAllowOriginValue - case CorsErrorPreflightAllowOriginMismatch: - *t = CorsErrorPreflightAllowOriginMismatch - case CorsErrorPreflightInvalidAllowCredentials: - *t = CorsErrorPreflightInvalidAllowCredentials - case CorsErrorPreflightMissingAllowExternal: - *t = CorsErrorPreflightMissingAllowExternal - case CorsErrorPreflightInvalidAllowExternal: - *t = CorsErrorPreflightInvalidAllowExternal - case CorsErrorInvalidAllowMethodsPreflightResponse: - *t = CorsErrorInvalidAllowMethodsPreflightResponse - case CorsErrorInvalidAllowHeadersPreflightResponse: - *t = CorsErrorInvalidAllowHeadersPreflightResponse - case CorsErrorMethodDisallowedByPreflightResponse: - *t = CorsErrorMethodDisallowedByPreflightResponse - case CorsErrorHeaderDisallowedByPreflightResponse: - *t = CorsErrorHeaderDisallowedByPreflightResponse - case CorsErrorRedirectContainsCredentials: - *t = CorsErrorRedirectContainsCredentials - case CorsErrorInsecureLocalNetwork: - *t = CorsErrorInsecureLocalNetwork - case CorsErrorInvalidLocalNetworkAccess: - *t = CorsErrorInvalidLocalNetworkAccess - case CorsErrorNoCorsRedirectModeNotFollow: - *t = CorsErrorNoCorsRedirectModeNotFollow - case CorsErrorLocalNetworkAccessPermissionDenied: - *t = CorsErrorLocalNetworkAccessPermissionDenied - default: - return fmt.Errorf("unknown CorsError value: %v", s) - } - return nil -} - // CorsErrorStatus [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-CorsErrorStatus @@ -774,26 +413,6 @@ const ( ServiceWorkerResponseSourceNetwork ServiceWorkerResponseSource = "network" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ServiceWorkerResponseSource) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ServiceWorkerResponseSource(s) { - case ServiceWorkerResponseSourceCacheStorage: - *t = ServiceWorkerResponseSourceCacheStorage - case ServiceWorkerResponseSourceHTTPCache: - *t = ServiceWorkerResponseSourceHTTPCache - case ServiceWorkerResponseSourceFallbackCode: - *t = ServiceWorkerResponseSourceFallbackCode - case ServiceWorkerResponseSourceNetwork: - *t = ServiceWorkerResponseSourceNetwork - default: - return fmt.Errorf("unknown ServiceWorkerResponseSource value: %v", s) - } - return nil -} - // TrustTokenParams determines what type of Trust Token operation is executed // and depending on the type, some additional parameters. The values are // specified in third_party/blink/renderer/core/fetch/trust_token.idl. @@ -822,24 +441,6 @@ const ( TrustTokenOperationTypeSigning TrustTokenOperationType = "Signing" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *TrustTokenOperationType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch TrustTokenOperationType(s) { - case TrustTokenOperationTypeIssuance: - *t = TrustTokenOperationTypeIssuance - case TrustTokenOperationTypeRedemption: - *t = TrustTokenOperationTypeRedemption - case TrustTokenOperationTypeSigning: - *t = TrustTokenOperationTypeSigning - default: - return fmt.Errorf("unknown TrustTokenOperationType value: %v", s) - } - return nil -} - // AlternateProtocolUsage the reason why Chrome uses a specific transport // protocol for HTTP semantics. // @@ -863,34 +464,6 @@ const ( AlternateProtocolUsageUnspecifiedReason AlternateProtocolUsage = "unspecifiedReason" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *AlternateProtocolUsage) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch AlternateProtocolUsage(s) { - case AlternateProtocolUsageAlternativeJobWonWithoutRace: - *t = AlternateProtocolUsageAlternativeJobWonWithoutRace - case AlternateProtocolUsageAlternativeJobWonRace: - *t = AlternateProtocolUsageAlternativeJobWonRace - case AlternateProtocolUsageMainJobWonRace: - *t = AlternateProtocolUsageMainJobWonRace - case AlternateProtocolUsageMappingMissing: - *t = AlternateProtocolUsageMappingMissing - case AlternateProtocolUsageBroken: - *t = AlternateProtocolUsageBroken - case AlternateProtocolUsageDNSAlpnH3jobWonWithoutRace: - *t = AlternateProtocolUsageDNSAlpnH3jobWonWithoutRace - case AlternateProtocolUsageDNSAlpnH3jobWonRace: - *t = AlternateProtocolUsageDNSAlpnH3jobWonRace - case AlternateProtocolUsageUnspecifiedReason: - *t = AlternateProtocolUsageUnspecifiedReason - default: - return fmt.Errorf("unknown AlternateProtocolUsage value: %v", s) - } - return nil -} - // ServiceWorkerRouterSource source of service worker router. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-ServiceWorkerRouterSource @@ -910,28 +483,6 @@ const ( ServiceWorkerRouterSourceRaceNetworkAndCache ServiceWorkerRouterSource = "race-network-and-cache" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ServiceWorkerRouterSource) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ServiceWorkerRouterSource(s) { - case ServiceWorkerRouterSourceNetwork: - *t = ServiceWorkerRouterSourceNetwork - case ServiceWorkerRouterSourceCache: - *t = ServiceWorkerRouterSourceCache - case ServiceWorkerRouterSourceFetchEvent: - *t = ServiceWorkerRouterSourceFetchEvent - case ServiceWorkerRouterSourceRaceNetworkAndFetchHandler: - *t = ServiceWorkerRouterSourceRaceNetworkAndFetchHandler - case ServiceWorkerRouterSourceRaceNetworkAndCache: - *t = ServiceWorkerRouterSourceRaceNetworkAndCache - default: - return fmt.Errorf("unknown ServiceWorkerRouterSource value: %v", s) - } - return nil -} - // ServiceWorkerRouterInfo [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-ServiceWorkerRouterInfo @@ -964,7 +515,7 @@ type Response struct { EncodedDataLength float64 `json:"encodedDataLength"` // Total number of bytes received for this request so far. Timing *ResourceTiming `json:"timing,omitempty,omitzero"` // Timing information for the given request. ServiceWorkerResponseSource ServiceWorkerResponseSource `json:"serviceWorkerResponseSource,omitempty,omitzero"` // Response source of response from ServiceWorker. - ResponseTime *cdp.TimeSinceEpochMilli `json:"responseTime,omitempty,omitzero"` // The time at which the returned response was generated. + ResponseTime cdp.TimeSinceEpoch `json:"responseTime,omitempty,omitzero"` // The time at which the returned response was generated. CacheStorageCacheName string `json:"cacheStorageCacheName,omitempty,omitzero"` // Cache Storage Cache Name. Protocol string `json:"protocol,omitempty,omitzero"` // Protocol used to fetch this request. AlternateProtocolUsage AlternateProtocolUsage `json:"alternateProtocolUsage,omitempty,omitzero"` // The reason why Chrome uses a specific transport protocol for HTTP semantics. @@ -998,7 +549,30 @@ type WebSocketResponse struct { type WebSocketFrame struct { Opcode float64 `json:"opcode"` // WebSocket message opcode. Mask bool `json:"mask"` // WebSocket message mask. - PayloadData string `json:"payloadData"` // WebSocket message payload data. If the opcode is 1, this is a text message and payloadData is a UTF-8 string. If the opcode isn't 1, then payloadData is a base64 encoded string representing binary data. + PayloadData []byte `json:"payloadData"` // WebSocket message payload data. If the opcode is 1, this is a text message and payloadData is a UTF-8 string. If the opcode isn't 1, then payloadData is a base64 encoded string representing binary data. +} + +// UnmarshalJSON decodes the value. The browser sends payloadData as text, or as +// base64 when r.Opcode != 1, and PayloadData holds the decoded bytes. +func (r *WebSocketFrame) UnmarshalJSON(buf []byte) error { + type plain WebSocketFrame + aux := struct { + *plain + PayloadData string `json:"payloadData"` + }{plain: (*plain)(r)} + if err := jsonv2.Unmarshal(buf, &aux); err != nil { + return err + } + if r.Opcode != 1 { + b, err := base64.StdEncoding.DecodeString(aux.PayloadData) + if err != nil { + return fmt.Errorf("decoding payloadData: %w", err) + } + r.PayloadData = b + return nil + } + r.PayloadData = []byte(aux.PayloadData) + return nil } // CachedResource information about the cached resource. @@ -1033,24 +607,20 @@ type CookiePartitionKey struct { HasCrossSiteAncestor bool `json:"hasCrossSiteAncestor"` // Indicates if the cookie has any ancestors that are cross-site to the topLevelSite. } -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CookiePartitionKey) OrigUnmarshalJSON(buf []byte) error { - if l := len(buf); l > 2 && buf[0] == '"' && buf[l-1] == '"' { - var err error - t.TopLevelSite, err = strconv.Unquote(string(buf)) - return err - } - dec := json.NewDecoder(bytes.NewReader(buf)) - dec.DisallowUnknownFields() - var v struct { - TopLevelSite string `json:"topLevelSite"` - HasCrossSiteAncestor bool `json:"hasCrossSiteAncestor"` +// UnmarshalJSON decodes the partition key from an object, or from the plain +// string that older versions of the browser send. The string is the top level +// site. The type always encodes as an object. +func (t *CookiePartitionKey) UnmarshalJSON(buf []byte) error { + if jsonv2.Value(buf).Kind() == '"' { + var site string + if err := jsonv2.Unmarshal(buf, &site); err != nil { + return err + } + *t = CookiePartitionKey{TopLevelSite: site} + return nil } - if err := dec.Decode(&v); err != nil { - return err - } - t.TopLevelSite, t.HasCrossSiteAncestor = v.TopLevelSite, v.HasCrossSiteAncestor - return nil + type plain CookiePartitionKey + return jsonv2.Unmarshal(buf, (*plain)(t)) } // Cookie cookie object. @@ -1094,7 +664,6 @@ const ( SetCookieBlockedReasonSameSiteNoneInsecure SetCookieBlockedReason = "SameSiteNoneInsecure" SetCookieBlockedReasonUserPreferences SetCookieBlockedReason = "UserPreferences" SetCookieBlockedReasonThirdPartyPhaseout SetCookieBlockedReason = "ThirdPartyPhaseout" - SetCookieBlockedReasonThirdPartyBlockedInFirstPartySet SetCookieBlockedReason = "ThirdPartyBlockedInFirstPartySet" SetCookieBlockedReasonSyntaxError SetCookieBlockedReason = "SyntaxError" SetCookieBlockedReasonSchemeNotSupported SetCookieBlockedReason = "SchemeNotSupported" SetCookieBlockedReasonOverwriteSecure SetCookieBlockedReason = "OverwriteSecure" @@ -1109,58 +678,6 @@ const ( SetCookieBlockedReasonNoCookieContent SetCookieBlockedReason = "NoCookieContent" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SetCookieBlockedReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SetCookieBlockedReason(s) { - case SetCookieBlockedReasonSecureOnly: - *t = SetCookieBlockedReasonSecureOnly - case SetCookieBlockedReasonSameSiteStrict: - *t = SetCookieBlockedReasonSameSiteStrict - case SetCookieBlockedReasonSameSiteLax: - *t = SetCookieBlockedReasonSameSiteLax - case SetCookieBlockedReasonSameSiteUnspecifiedTreatedAsLax: - *t = SetCookieBlockedReasonSameSiteUnspecifiedTreatedAsLax - case SetCookieBlockedReasonSameSiteNoneInsecure: - *t = SetCookieBlockedReasonSameSiteNoneInsecure - case SetCookieBlockedReasonUserPreferences: - *t = SetCookieBlockedReasonUserPreferences - case SetCookieBlockedReasonThirdPartyPhaseout: - *t = SetCookieBlockedReasonThirdPartyPhaseout - case SetCookieBlockedReasonThirdPartyBlockedInFirstPartySet: - *t = SetCookieBlockedReasonThirdPartyBlockedInFirstPartySet - case SetCookieBlockedReasonSyntaxError: - *t = SetCookieBlockedReasonSyntaxError - case SetCookieBlockedReasonSchemeNotSupported: - *t = SetCookieBlockedReasonSchemeNotSupported - case SetCookieBlockedReasonOverwriteSecure: - *t = SetCookieBlockedReasonOverwriteSecure - case SetCookieBlockedReasonInvalidDomain: - *t = SetCookieBlockedReasonInvalidDomain - case SetCookieBlockedReasonInvalidPrefix: - *t = SetCookieBlockedReasonInvalidPrefix - case SetCookieBlockedReasonUnknownError: - *t = SetCookieBlockedReasonUnknownError - case SetCookieBlockedReasonSchemefulSameSiteStrict: - *t = SetCookieBlockedReasonSchemefulSameSiteStrict - case SetCookieBlockedReasonSchemefulSameSiteLax: - *t = SetCookieBlockedReasonSchemefulSameSiteLax - case SetCookieBlockedReasonSchemefulSameSiteUnspecifiedTreatedAsLax: - *t = SetCookieBlockedReasonSchemefulSameSiteUnspecifiedTreatedAsLax - case SetCookieBlockedReasonNameValuePairExceedsMaxSize: - *t = SetCookieBlockedReasonNameValuePairExceedsMaxSize - case SetCookieBlockedReasonDisallowedCharacter: - *t = SetCookieBlockedReasonDisallowedCharacter - case SetCookieBlockedReasonNoCookieContent: - *t = SetCookieBlockedReasonNoCookieContent - default: - return fmt.Errorf("unknown SetCookieBlockedReason value: %v", s) - } - return nil -} - // CookieBlockedReason types of reasons why a cookie may not be sent with a // request. // @@ -1183,7 +700,6 @@ const ( CookieBlockedReasonSameSiteNoneInsecure CookieBlockedReason = "SameSiteNoneInsecure" CookieBlockedReasonUserPreferences CookieBlockedReason = "UserPreferences" CookieBlockedReasonThirdPartyPhaseout CookieBlockedReason = "ThirdPartyPhaseout" - CookieBlockedReasonThirdPartyBlockedInFirstPartySet CookieBlockedReason = "ThirdPartyBlockedInFirstPartySet" CookieBlockedReasonUnknownError CookieBlockedReason = "UnknownError" CookieBlockedReasonSchemefulSameSiteStrict CookieBlockedReason = "SchemefulSameSiteStrict" CookieBlockedReasonSchemefulSameSiteLax CookieBlockedReason = "SchemefulSameSiteLax" @@ -1194,54 +710,6 @@ const ( CookieBlockedReasonAnonymousContext CookieBlockedReason = "AnonymousContext" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CookieBlockedReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CookieBlockedReason(s) { - case CookieBlockedReasonSecureOnly: - *t = CookieBlockedReasonSecureOnly - case CookieBlockedReasonNotOnPath: - *t = CookieBlockedReasonNotOnPath - case CookieBlockedReasonDomainMismatch: - *t = CookieBlockedReasonDomainMismatch - case CookieBlockedReasonSameSiteStrict: - *t = CookieBlockedReasonSameSiteStrict - case CookieBlockedReasonSameSiteLax: - *t = CookieBlockedReasonSameSiteLax - case CookieBlockedReasonSameSiteUnspecifiedTreatedAsLax: - *t = CookieBlockedReasonSameSiteUnspecifiedTreatedAsLax - case CookieBlockedReasonSameSiteNoneInsecure: - *t = CookieBlockedReasonSameSiteNoneInsecure - case CookieBlockedReasonUserPreferences: - *t = CookieBlockedReasonUserPreferences - case CookieBlockedReasonThirdPartyPhaseout: - *t = CookieBlockedReasonThirdPartyPhaseout - case CookieBlockedReasonThirdPartyBlockedInFirstPartySet: - *t = CookieBlockedReasonThirdPartyBlockedInFirstPartySet - case CookieBlockedReasonUnknownError: - *t = CookieBlockedReasonUnknownError - case CookieBlockedReasonSchemefulSameSiteStrict: - *t = CookieBlockedReasonSchemefulSameSiteStrict - case CookieBlockedReasonSchemefulSameSiteLax: - *t = CookieBlockedReasonSchemefulSameSiteLax - case CookieBlockedReasonSchemefulSameSiteUnspecifiedTreatedAsLax: - *t = CookieBlockedReasonSchemefulSameSiteUnspecifiedTreatedAsLax - case CookieBlockedReasonNameValuePairExceedsMaxSize: - *t = CookieBlockedReasonNameValuePairExceedsMaxSize - case CookieBlockedReasonPortMismatch: - *t = CookieBlockedReasonPortMismatch - case CookieBlockedReasonSchemeMismatch: - *t = CookieBlockedReasonSchemeMismatch - case CookieBlockedReasonAnonymousContext: - *t = CookieBlockedReasonAnonymousContext - default: - return fmt.Errorf("unknown CookieBlockedReason value: %v", s) - } - return nil -} - // CookieExemptionReason types of reasons why a cookie should have been // blocked by 3PCD but is exempted for the request. // @@ -1264,32 +732,6 @@ const ( CookieExemptionReasonSameSiteNoneCookiesInSandbox CookieExemptionReason = "SameSiteNoneCookiesInSandbox" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CookieExemptionReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CookieExemptionReason(s) { - case CookieExemptionReasonNone: - *t = CookieExemptionReasonNone - case CookieExemptionReasonUserSetting: - *t = CookieExemptionReasonUserSetting - case CookieExemptionReasonEnterprisePolicy: - *t = CookieExemptionReasonEnterprisePolicy - case CookieExemptionReasonStorageAccess: - *t = CookieExemptionReasonStorageAccess - case CookieExemptionReasonTopLevelStorageAccess: - *t = CookieExemptionReasonTopLevelStorageAccess - case CookieExemptionReasonScheme: - *t = CookieExemptionReasonScheme - case CookieExemptionReasonSameSiteNoneCookiesInSandbox: - *t = CookieExemptionReasonSameSiteNoneCookiesInSandbox - default: - return fmt.Errorf("unknown CookieExemptionReason value: %v", s) - } - return nil -} - // BlockedSetCookieWithReason a cookie which was not stored from a response // with the corresponding reason. // @@ -1334,7 +776,7 @@ type CookieParam struct { Secure bool `json:"secure"` // True if cookie is secure. HTTPOnly bool `json:"httpOnly"` // True if cookie is http-only. SameSite CookieSameSite `json:"sameSite,omitempty,omitzero"` // Cookie SameSite type. - Expires *cdp.TimeSinceEpoch `json:"expires,omitempty,omitzero"` // Cookie expiration date, session cookie if not set + Expires cdp.TimeSinceEpoch `json:"expires,omitempty,omitzero"` // Cookie expiration date, session cookie if not set Priority CookiePriority `json:"priority,omitempty,omitzero"` // Cookie Priority. SourceScheme CookieSourceScheme `json:"sourceScheme,omitempty,omitzero"` // Cookie source scheme type. SourcePort int64 `json:"sourcePort,omitempty,omitzero"` // Cookie source port. Valid values are {-1, [1, 65535]}, -1 indicates an unspecified port. An unspecified port value allows protocol clients to emulate legacy cookie scope for the port. This is a temporary ability and it will be removed in the future. @@ -1360,49 +802,6 @@ type AuthChallengeResponse struct { Password string `json:"password,omitempty,omitzero"` // The password to provide, possibly empty. Should only be set if response is ProvideCredentials. } -// InterceptionStage stages of the interception to begin intercepting. -// Request will intercept before the request is sent. Response will intercept -// after the response is received. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-InterceptionStage -type InterceptionStage string - -// String returns the InterceptionStage as string value. -func (t InterceptionStage) String() string { - return string(t) -} - -// InterceptionStage values. -const ( - InterceptionStageRequest InterceptionStage = "Request" - InterceptionStageHeadersReceived InterceptionStage = "HeadersReceived" -) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *InterceptionStage) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch InterceptionStage(s) { - case InterceptionStageRequest: - *t = InterceptionStageRequest - case InterceptionStageHeadersReceived: - *t = InterceptionStageHeadersReceived - default: - return fmt.Errorf("unknown InterceptionStage value: %v", s) - } - return nil -} - -// RequestPattern request pattern for interception. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-RequestPattern -type RequestPattern struct { - URLPattern string `json:"urlPattern,omitempty,omitzero"` // Wildcards ('*' -> zero or more, '?' -> exactly one) are allowed. Escape character is backslash. Omitting is equivalent to "*". - ResourceType ResourceType `json:"resourceType,omitempty,omitzero"` // If set, only requests for matching resource types will be intercepted. - InterceptionStage InterceptionStage `json:"interceptionStage,omitempty,omitzero"` // Stage at which to begin intercepting requests. Default is Request. -} - // SignedExchangeSignature information about a signed exchange signature. // https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#rfc.section.3.1. // @@ -1451,30 +850,6 @@ const ( SignedExchangeErrorFieldSignatureTimestamps SignedExchangeErrorField = "signatureTimestamps" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SignedExchangeErrorField) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SignedExchangeErrorField(s) { - case SignedExchangeErrorFieldSignatureSig: - *t = SignedExchangeErrorFieldSignatureSig - case SignedExchangeErrorFieldSignatureIntegrity: - *t = SignedExchangeErrorFieldSignatureIntegrity - case SignedExchangeErrorFieldSignatureCertURL: - *t = SignedExchangeErrorFieldSignatureCertURL - case SignedExchangeErrorFieldSignatureCertSha256: - *t = SignedExchangeErrorFieldSignatureCertSha256 - case SignedExchangeErrorFieldSignatureValidityURL: - *t = SignedExchangeErrorFieldSignatureValidityURL - case SignedExchangeErrorFieldSignatureTimestamps: - *t = SignedExchangeErrorFieldSignatureTimestamps - default: - return fmt.Errorf("unknown SignedExchangeErrorField value: %v", s) - } - return nil -} - // SignedExchangeError information about a signed exchange response. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-SignedExchangeError @@ -1495,44 +870,6 @@ type SignedExchangeInfo struct { Errors []*SignedExchangeError `json:"errors,omitempty,omitzero"` // Errors occurred while handling the signed exchange. } -// ContentEncoding list of content encodings supported by the backend. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-ContentEncoding -type ContentEncoding string - -// String returns the ContentEncoding as string value. -func (t ContentEncoding) String() string { - return string(t) -} - -// ContentEncoding values. -const ( - ContentEncodingDeflate ContentEncoding = "deflate" - ContentEncodingGzip ContentEncoding = "gzip" - ContentEncodingBr ContentEncoding = "br" - ContentEncodingZstd ContentEncoding = "zstd" -) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ContentEncoding) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ContentEncoding(s) { - case ContentEncodingDeflate: - *t = ContentEncodingDeflate - case ContentEncodingGzip: - *t = ContentEncodingGzip - case ContentEncodingBr: - *t = ContentEncodingBr - case ContentEncodingZstd: - *t = ContentEncodingZstd - default: - return fmt.Errorf("unknown ContentEncoding value: %v", s) - } - return nil -} - // Conditions [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-NetworkConditions @@ -1572,22 +909,6 @@ const ( DirectSocketDNSQueryTypeIpv6 DirectSocketDNSQueryType = "ipv6" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DirectSocketDNSQueryType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DirectSocketDNSQueryType(s) { - case DirectSocketDNSQueryTypeIpv4: - *t = DirectSocketDNSQueryTypeIpv4 - case DirectSocketDNSQueryTypeIpv6: - *t = DirectSocketDNSQueryTypeIpv6 - default: - return fmt.Errorf("unknown DirectSocketDNSQueryType value: %v", s) - } - return nil -} - // DirectTCPSocketOptions [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-DirectTCPSocketOptions @@ -1619,7 +940,7 @@ type DirectUDPSocketOptions struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-DirectUDPMessage type DirectUDPMessage struct { - Data string `json:"data"` + Data []byte `json:"data"` RemoteAddr string `json:"remoteAddr,omitempty,omitzero"` // Null for connected mode. RemotePort int64 `json:"remotePort,omitempty,omitzero"` // Null for connected mode. Expected to be unsigned integer. } @@ -1643,28 +964,6 @@ const ( LocalNetworkAccessRequestPolicyPermissionWarn LocalNetworkAccessRequestPolicy = "PermissionWarn" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *LocalNetworkAccessRequestPolicy) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch LocalNetworkAccessRequestPolicy(s) { - case LocalNetworkAccessRequestPolicyAllow: - *t = LocalNetworkAccessRequestPolicyAllow - case LocalNetworkAccessRequestPolicyBlockFromInsecureToMorePrivate: - *t = LocalNetworkAccessRequestPolicyBlockFromInsecureToMorePrivate - case LocalNetworkAccessRequestPolicyWarnFromInsecureToMorePrivate: - *t = LocalNetworkAccessRequestPolicyWarnFromInsecureToMorePrivate - case LocalNetworkAccessRequestPolicyPermissionBlock: - *t = LocalNetworkAccessRequestPolicyPermissionBlock - case LocalNetworkAccessRequestPolicyPermissionWarn: - *t = LocalNetworkAccessRequestPolicyPermissionWarn - default: - return fmt.Errorf("unknown LocalNetworkAccessRequestPolicy value: %v", s) - } - return nil -} - // IPAddressSpace [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-IPAddressSpace @@ -1683,26 +982,6 @@ const ( IPAddressSpaceUnknown IPAddressSpace = "Unknown" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *IPAddressSpace) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch IPAddressSpace(s) { - case IPAddressSpaceLoopback: - *t = IPAddressSpaceLoopback - case IPAddressSpaceLocal: - *t = IPAddressSpaceLocal - case IPAddressSpacePublic: - *t = IPAddressSpacePublic - case IPAddressSpaceUnknown: - *t = IPAddressSpaceUnknown - default: - return fmt.Errorf("unknown IPAddressSpace value: %v", s) - } - return nil -} - // ConnectTiming [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-ConnectTiming @@ -1740,32 +1019,6 @@ const ( CrossOriginOpenerPolicyValueNoopenerAllowPopups CrossOriginOpenerPolicyValue = "NoopenerAllowPopups" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CrossOriginOpenerPolicyValue) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CrossOriginOpenerPolicyValue(s) { - case CrossOriginOpenerPolicyValueSameOrigin: - *t = CrossOriginOpenerPolicyValueSameOrigin - case CrossOriginOpenerPolicyValueSameOriginAllowPopups: - *t = CrossOriginOpenerPolicyValueSameOriginAllowPopups - case CrossOriginOpenerPolicyValueRestrictProperties: - *t = CrossOriginOpenerPolicyValueRestrictProperties - case CrossOriginOpenerPolicyValueUnsafeNone: - *t = CrossOriginOpenerPolicyValueUnsafeNone - case CrossOriginOpenerPolicyValueSameOriginPlusCoep: - *t = CrossOriginOpenerPolicyValueSameOriginPlusCoep - case CrossOriginOpenerPolicyValueRestrictPropertiesPlusCoep: - *t = CrossOriginOpenerPolicyValueRestrictPropertiesPlusCoep - case CrossOriginOpenerPolicyValueNoopenerAllowPopups: - *t = CrossOriginOpenerPolicyValueNoopenerAllowPopups - default: - return fmt.Errorf("unknown CrossOriginOpenerPolicyValue value: %v", s) - } - return nil -} - // CrossOriginOpenerPolicyStatus [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-CrossOriginOpenerPolicyStatus @@ -1793,24 +1046,6 @@ const ( CrossOriginEmbedderPolicyValueRequireCorp CrossOriginEmbedderPolicyValue = "RequireCorp" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CrossOriginEmbedderPolicyValue) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CrossOriginEmbedderPolicyValue(s) { - case CrossOriginEmbedderPolicyValueNone: - *t = CrossOriginEmbedderPolicyValueNone - case CrossOriginEmbedderPolicyValueCredentialless: - *t = CrossOriginEmbedderPolicyValueCredentialless - case CrossOriginEmbedderPolicyValueRequireCorp: - *t = CrossOriginEmbedderPolicyValueRequireCorp - default: - return fmt.Errorf("unknown CrossOriginEmbedderPolicyValue value: %v", s) - } - return nil -} - // CrossOriginEmbedderPolicyStatus [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-CrossOriginEmbedderPolicyStatus @@ -1837,22 +1072,6 @@ const ( ContentSecurityPolicySourceMeta ContentSecurityPolicySource = "Meta" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ContentSecurityPolicySource) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ContentSecurityPolicySource(s) { - case ContentSecurityPolicySourceHTTP: - *t = ContentSecurityPolicySourceHTTP - case ContentSecurityPolicySourceMeta: - *t = ContentSecurityPolicySourceMeta - default: - return fmt.Errorf("unknown ContentSecurityPolicySource value: %v", s) - } - return nil -} - // ContentSecurityPolicyStatus [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-ContentSecurityPolicyStatus @@ -1889,26 +1108,6 @@ const ( ReportStatusSuccess ReportStatus = "Success" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ReportStatus) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ReportStatus(s) { - case ReportStatusQueued: - *t = ReportStatusQueued - case ReportStatusPending: - *t = ReportStatusPending - case ReportStatusMarkedForRemoval: - *t = ReportStatusMarkedForRemoval - case ReportStatusSuccess: - *t = ReportStatusSuccess - default: - return fmt.Errorf("unknown ReportStatus value: %v", s) - } - return nil -} - // ReportID [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-ReportId @@ -1924,15 +1123,15 @@ func (t ReportID) String() string { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-ReportingApiReport type ReportingAPIReport struct { - ID ReportID `json:"id"` - InitiatorURL string `json:"initiatorUrl"` // The URL of the document that triggered the report. - Destination string `json:"destination"` // The name of the endpoint group that should be used to deliver the report. - Type string `json:"type"` // The type of the report (specifies the set of data that is contained in the report body). - Timestamp *cdp.TimeSinceEpoch `json:"timestamp"` // When the report was generated. - Depth int64 `json:"depth"` // How many uploads deep the related request was. - CompletedAttempts int64 `json:"completedAttempts"` // The number of delivery attempts made so far, not including an active attempt. - Body jsontext.Value `json:"body"` - Status ReportStatus `json:"status"` + ID ReportID `json:"id"` + InitiatorURL string `json:"initiatorUrl"` // The URL of the document that triggered the report. + Destination string `json:"destination"` // The name of the endpoint group that should be used to deliver the report. + Type string `json:"type"` // The type of the report (specifies the set of data that is contained in the report body). + Timestamp cdp.TimeSinceEpoch `json:"timestamp"` // When the report was generated. + Depth int64 `json:"depth"` // How many uploads deep the related request was. + CompletedAttempts int64 `json:"completedAttempts"` // The number of delivery attempts made so far, not including an active attempt. + Body jsonv2.Value `json:"body"` + Status ReportStatus `json:"status"` } // ReportingAPIEndpoint [no description]. @@ -1998,7 +1197,7 @@ type DeviceBoundSession struct { RefreshURL string `json:"refreshUrl"` // See comments on net::device_bound_sessions::Session::refresh_url_. InclusionRules *DeviceBoundSessionInclusionRules `json:"inclusionRules"` // See comments on net::device_bound_sessions::Session::inclusion_rules_. CookieCravings []*DeviceBoundSessionCookieCraving `json:"cookieCravings"` // See comments on net::device_bound_sessions::Session::cookie_cravings_. - ExpiryDate *cdp.TimeSinceEpoch `json:"expiryDate"` // See comments on net::device_bound_sessions::Session::expiry_date_. + ExpiryDate cdp.TimeSinceEpoch `json:"expiryDate"` // See comments on net::device_bound_sessions::Session::expiry_date_. CachedChallenge string `json:"cachedChallenge,omitempty,omitzero"` // See comments on net::device_bound_sessions::Session::cached_challenge__. AllowedRefreshInitiators []string `json:"allowedRefreshInitiators"` // See comments on net::device_bound_sessions::Session::allowed_refresh_initiators_. } @@ -2101,168 +1300,10 @@ const ( DeviceBoundSessionFetchResultInvalidPreProvisionedKeyInitiatorMissing DeviceBoundSessionFetchResult = "InvalidPreProvisionedKeyInitiatorMissing" DeviceBoundSessionFetchResultPreProvisionedKeyAccessNotGranted DeviceBoundSessionFetchResult = "PreProvisionedKeyAccessNotGranted" DeviceBoundSessionFetchResultPreProvisionedKeyNotFound DeviceBoundSessionFetchResult = "PreProvisionedKeyNotFound" + DeviceBoundSessionFetchResultAttestationCertificationError DeviceBoundSessionFetchResult = "AttestationCertificationError" + DeviceBoundSessionFetchResultAttestationSigningError DeviceBoundSessionFetchResult = "AttestationSigningError" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DeviceBoundSessionFetchResult) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DeviceBoundSessionFetchResult(s) { - case DeviceBoundSessionFetchResultSuccess: - *t = DeviceBoundSessionFetchResultSuccess - case DeviceBoundSessionFetchResultSigningKeyGenerationError: - *t = DeviceBoundSessionFetchResultSigningKeyGenerationError - case DeviceBoundSessionFetchResultAttestationKeyGenerationError: - *t = DeviceBoundSessionFetchResultAttestationKeyGenerationError - case DeviceBoundSessionFetchResultSigningError: - *t = DeviceBoundSessionFetchResultSigningError - case DeviceBoundSessionFetchResultTransientSigningError: - *t = DeviceBoundSessionFetchResultTransientSigningError - case DeviceBoundSessionFetchResultServerRequestedTermination: - *t = DeviceBoundSessionFetchResultServerRequestedTermination - case DeviceBoundSessionFetchResultInvalidSessionID: - *t = DeviceBoundSessionFetchResultInvalidSessionID - case DeviceBoundSessionFetchResultInvalidChallenge: - *t = DeviceBoundSessionFetchResultInvalidChallenge - case DeviceBoundSessionFetchResultTooManyChallenges: - *t = DeviceBoundSessionFetchResultTooManyChallenges - case DeviceBoundSessionFetchResultInvalidFetcherURL: - *t = DeviceBoundSessionFetchResultInvalidFetcherURL - case DeviceBoundSessionFetchResultInvalidRefreshURL: - *t = DeviceBoundSessionFetchResultInvalidRefreshURL - case DeviceBoundSessionFetchResultTransientHTTPError: - *t = DeviceBoundSessionFetchResultTransientHTTPError - case DeviceBoundSessionFetchResultScopeOriginSameSiteMismatch: - *t = DeviceBoundSessionFetchResultScopeOriginSameSiteMismatch - case DeviceBoundSessionFetchResultRefreshURLSameSiteMismatch: - *t = DeviceBoundSessionFetchResultRefreshURLSameSiteMismatch - case DeviceBoundSessionFetchResultMismatchedSessionID: - *t = DeviceBoundSessionFetchResultMismatchedSessionID - case DeviceBoundSessionFetchResultMissingScope: - *t = DeviceBoundSessionFetchResultMissingScope - case DeviceBoundSessionFetchResultNoCredentials: - *t = DeviceBoundSessionFetchResultNoCredentials - case DeviceBoundSessionFetchResultSubdomainRegistrationWellKnownUnavailable: - *t = DeviceBoundSessionFetchResultSubdomainRegistrationWellKnownUnavailable - case DeviceBoundSessionFetchResultSubdomainRegistrationUnauthorized: - *t = DeviceBoundSessionFetchResultSubdomainRegistrationUnauthorized - case DeviceBoundSessionFetchResultSubdomainRegistrationWellKnownMalformed: - *t = DeviceBoundSessionFetchResultSubdomainRegistrationWellKnownMalformed - case DeviceBoundSessionFetchResultSessionProviderWellKnownUnavailable: - *t = DeviceBoundSessionFetchResultSessionProviderWellKnownUnavailable - case DeviceBoundSessionFetchResultRelyingPartyWellKnownUnavailable: - *t = DeviceBoundSessionFetchResultRelyingPartyWellKnownUnavailable - case DeviceBoundSessionFetchResultFederatedKeyThumbprintMismatch: - *t = DeviceBoundSessionFetchResultFederatedKeyThumbprintMismatch - case DeviceBoundSessionFetchResultInvalidFederatedSessionURL: - *t = DeviceBoundSessionFetchResultInvalidFederatedSessionURL - case DeviceBoundSessionFetchResultInvalidFederatedKey: - *t = DeviceBoundSessionFetchResultInvalidFederatedKey - case DeviceBoundSessionFetchResultTooManyRelyingOriginLabels: - *t = DeviceBoundSessionFetchResultTooManyRelyingOriginLabels - case DeviceBoundSessionFetchResultBoundCookieSetForbidden: - *t = DeviceBoundSessionFetchResultBoundCookieSetForbidden - case DeviceBoundSessionFetchResultNetError: - *t = DeviceBoundSessionFetchResultNetError - case DeviceBoundSessionFetchResultProxyError: - *t = DeviceBoundSessionFetchResultProxyError - case DeviceBoundSessionFetchResultEmptySessionConfig: - *t = DeviceBoundSessionFetchResultEmptySessionConfig - case DeviceBoundSessionFetchResultInvalidCredentialsConfig: - *t = DeviceBoundSessionFetchResultInvalidCredentialsConfig - case DeviceBoundSessionFetchResultInvalidCredentialsType: - *t = DeviceBoundSessionFetchResultInvalidCredentialsType - case DeviceBoundSessionFetchResultInvalidCredentialsEmptyName: - *t = DeviceBoundSessionFetchResultInvalidCredentialsEmptyName - case DeviceBoundSessionFetchResultInvalidCredentialsCookie: - *t = DeviceBoundSessionFetchResultInvalidCredentialsCookie - case DeviceBoundSessionFetchResultPersistentHTTPError: - *t = DeviceBoundSessionFetchResultPersistentHTTPError - case DeviceBoundSessionFetchResultRegistrationAttemptedChallenge: - *t = DeviceBoundSessionFetchResultRegistrationAttemptedChallenge - case DeviceBoundSessionFetchResultInvalidScopeOrigin: - *t = DeviceBoundSessionFetchResultInvalidScopeOrigin - case DeviceBoundSessionFetchResultScopeOriginContainsPath: - *t = DeviceBoundSessionFetchResultScopeOriginContainsPath - case DeviceBoundSessionFetchResultRefreshInitiatorNotString: - *t = DeviceBoundSessionFetchResultRefreshInitiatorNotString - case DeviceBoundSessionFetchResultRefreshInitiatorInvalidHostPattern: - *t = DeviceBoundSessionFetchResultRefreshInitiatorInvalidHostPattern - case DeviceBoundSessionFetchResultInvalidScopeSpecification: - *t = DeviceBoundSessionFetchResultInvalidScopeSpecification - case DeviceBoundSessionFetchResultMissingScopeSpecificationType: - *t = DeviceBoundSessionFetchResultMissingScopeSpecificationType - case DeviceBoundSessionFetchResultEmptyScopeSpecificationDomain: - *t = DeviceBoundSessionFetchResultEmptyScopeSpecificationDomain - case DeviceBoundSessionFetchResultEmptyScopeSpecificationPath: - *t = DeviceBoundSessionFetchResultEmptyScopeSpecificationPath - case DeviceBoundSessionFetchResultInvalidScopeSpecificationType: - *t = DeviceBoundSessionFetchResultInvalidScopeSpecificationType - case DeviceBoundSessionFetchResultInvalidScopeIncludeSite: - *t = DeviceBoundSessionFetchResultInvalidScopeIncludeSite - case DeviceBoundSessionFetchResultMissingScopeIncludeSite: - *t = DeviceBoundSessionFetchResultMissingScopeIncludeSite - case DeviceBoundSessionFetchResultFederatedNotAuthorizedByProvider: - *t = DeviceBoundSessionFetchResultFederatedNotAuthorizedByProvider - case DeviceBoundSessionFetchResultFederatedNotAuthorizedByRelyingParty: - *t = DeviceBoundSessionFetchResultFederatedNotAuthorizedByRelyingParty - case DeviceBoundSessionFetchResultSessionProviderWellKnownMalformed: - *t = DeviceBoundSessionFetchResultSessionProviderWellKnownMalformed - case DeviceBoundSessionFetchResultSessionProviderWellKnownHasProviderOrigin: - *t = DeviceBoundSessionFetchResultSessionProviderWellKnownHasProviderOrigin - case DeviceBoundSessionFetchResultRelyingPartyWellKnownMalformed: - *t = DeviceBoundSessionFetchResultRelyingPartyWellKnownMalformed - case DeviceBoundSessionFetchResultRelyingPartyWellKnownHasRelyingOrigins: - *t = DeviceBoundSessionFetchResultRelyingPartyWellKnownHasRelyingOrigins - case DeviceBoundSessionFetchResultInvalidFederatedSessionProviderSessionMissing: - *t = DeviceBoundSessionFetchResultInvalidFederatedSessionProviderSessionMissing - case DeviceBoundSessionFetchResultInvalidFederatedSessionWrongProviderOrigin: - *t = DeviceBoundSessionFetchResultInvalidFederatedSessionWrongProviderOrigin - case DeviceBoundSessionFetchResultInvalidCredentialsCookieCreationTime: - *t = DeviceBoundSessionFetchResultInvalidCredentialsCookieCreationTime - case DeviceBoundSessionFetchResultInvalidCredentialsCookieName: - *t = DeviceBoundSessionFetchResultInvalidCredentialsCookieName - case DeviceBoundSessionFetchResultInvalidCredentialsCookieParsing: - *t = DeviceBoundSessionFetchResultInvalidCredentialsCookieParsing - case DeviceBoundSessionFetchResultInvalidCredentialsCookieUnpermittedAttribute: - *t = DeviceBoundSessionFetchResultInvalidCredentialsCookieUnpermittedAttribute - case DeviceBoundSessionFetchResultInvalidCredentialsCookieInvalidDomain: - *t = DeviceBoundSessionFetchResultInvalidCredentialsCookieInvalidDomain - case DeviceBoundSessionFetchResultInvalidCredentialsCookiePrefix: - *t = DeviceBoundSessionFetchResultInvalidCredentialsCookiePrefix - case DeviceBoundSessionFetchResultInvalidScopeRulePath: - *t = DeviceBoundSessionFetchResultInvalidScopeRulePath - case DeviceBoundSessionFetchResultInvalidScopeRuleHostPattern: - *t = DeviceBoundSessionFetchResultInvalidScopeRuleHostPattern - case DeviceBoundSessionFetchResultScopeRuleOriginScopedHostPatternMismatch: - *t = DeviceBoundSessionFetchResultScopeRuleOriginScopedHostPatternMismatch - case DeviceBoundSessionFetchResultScopeRuleSiteScopedHostPatternMismatch: - *t = DeviceBoundSessionFetchResultScopeRuleSiteScopedHostPatternMismatch - case DeviceBoundSessionFetchResultSigningQuotaExceeded: - *t = DeviceBoundSessionFetchResultSigningQuotaExceeded - case DeviceBoundSessionFetchResultInvalidConfigJSON: - *t = DeviceBoundSessionFetchResultInvalidConfigJSON - case DeviceBoundSessionFetchResultInvalidFederatedSessionProviderFailedToRestoreKey: - *t = DeviceBoundSessionFetchResultInvalidFederatedSessionProviderFailedToRestoreKey - case DeviceBoundSessionFetchResultFailedToUnwrapKey: - *t = DeviceBoundSessionFetchResultFailedToUnwrapKey - case DeviceBoundSessionFetchResultSessionDeletedDuringRefresh: - *t = DeviceBoundSessionFetchResultSessionDeletedDuringRefresh - case DeviceBoundSessionFetchResultCrossOriginRegistrationSiteNotIncluded: - *t = DeviceBoundSessionFetchResultCrossOriginRegistrationSiteNotIncluded - case DeviceBoundSessionFetchResultInvalidPreProvisionedKeyInitiatorMissing: - *t = DeviceBoundSessionFetchResultInvalidPreProvisionedKeyInitiatorMissing - case DeviceBoundSessionFetchResultPreProvisionedKeyAccessNotGranted: - *t = DeviceBoundSessionFetchResultPreProvisionedKeyAccessNotGranted - case DeviceBoundSessionFetchResultPreProvisionedKeyNotFound: - *t = DeviceBoundSessionFetchResultPreProvisionedKeyNotFound - default: - return fmt.Errorf("unknown DeviceBoundSessionFetchResult value: %v", s) - } - return nil -} - // DeviceBoundSessionFailedRequest details about a failed device bound // session network request. // @@ -2287,8 +1328,8 @@ type CreationEventDetails struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-RefreshEventDetails type RefreshEventDetails struct { - RefreshResult RefreshEventDetailsRefreshResult `json:"refreshResult"` // The result of a refresh. - FetchResult DeviceBoundSessionFetchResult `json:"fetchResult,omitempty,omitzero"` // If there was a fetch attempt, the result of that. + RefreshResult RefreshEventDetailsRefreshResult `json:"refreshResult"` // The result of a refresh. LINT.IfChange(DeviceBoundSessionRefreshResult) + FetchResult DeviceBoundSessionFetchResult `json:"fetchResult,omitempty,omitzero"` // LINT.ThenChange(//net/device_bound_sessions/refresh_result.h:DeviceBoundSessionRefreshResult,//content/browser/devtools/protocol/network_handler.cc:DeviceBoundSessionRefreshResult) If there was a fetch attempt, the result of that. NewSession *DeviceBoundSession `json:"newSession,omitempty,omitzero"` // The session display if there was a newly created session. This is populated for any refresh event that modifies the session config. WasFullyProactiveRefresh bool `json:"wasFullyProactiveRefresh"` // See comments on net::device_bound_sessions::RefreshEventResult::was_fully_proactive_refresh. FailedRequest *DeviceBoundSessionFailedRequest `json:"failedRequest,omitempty,omitzero"` // Details about a failed device bound session network request if there was one. @@ -2331,57 +1372,29 @@ type LoadNetworkResourceOptions struct { IncludeCredentials bool `json:"includeCredentials"` } -// ReferrerPolicy the referrer policy of the request, as defined in +// RequestReferrerPolicy the referrer policy of the request, as defined in // https://www.w3.org/TR/referrer-policy/. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-Request -type ReferrerPolicy string +type RequestReferrerPolicy string -// String returns the ReferrerPolicy as string value. -func (t ReferrerPolicy) String() string { +// String returns the RequestReferrerPolicy as string value. +func (t RequestReferrerPolicy) String() string { return string(t) } -// ReferrerPolicy values. +// RequestReferrerPolicy values. const ( - ReferrerPolicyUnsafeURL ReferrerPolicy = "unsafe-url" - ReferrerPolicyNoReferrerWhenDowngrade ReferrerPolicy = "no-referrer-when-downgrade" - ReferrerPolicyNoReferrer ReferrerPolicy = "no-referrer" - ReferrerPolicyOrigin ReferrerPolicy = "origin" - ReferrerPolicyOriginWhenCrossOrigin ReferrerPolicy = "origin-when-cross-origin" - ReferrerPolicySameOrigin ReferrerPolicy = "same-origin" - ReferrerPolicyStrictOrigin ReferrerPolicy = "strict-origin" - ReferrerPolicyStrictOriginWhenCrossOrigin ReferrerPolicy = "strict-origin-when-cross-origin" + RequestReferrerPolicyUnsafeURL RequestReferrerPolicy = "unsafe-url" + RequestReferrerPolicyNoReferrerWhenDowngrade RequestReferrerPolicy = "no-referrer-when-downgrade" + RequestReferrerPolicyNoReferrer RequestReferrerPolicy = "no-referrer" + RequestReferrerPolicyOrigin RequestReferrerPolicy = "origin" + RequestReferrerPolicyOriginWhenCrossOrigin RequestReferrerPolicy = "origin-when-cross-origin" + RequestReferrerPolicySameOrigin RequestReferrerPolicy = "same-origin" + RequestReferrerPolicyStrictOrigin RequestReferrerPolicy = "strict-origin" + RequestReferrerPolicyStrictOriginWhenCrossOrigin RequestReferrerPolicy = "strict-origin-when-cross-origin" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ReferrerPolicy) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ReferrerPolicy(s) { - case ReferrerPolicyUnsafeURL: - *t = ReferrerPolicyUnsafeURL - case ReferrerPolicyNoReferrerWhenDowngrade: - *t = ReferrerPolicyNoReferrerWhenDowngrade - case ReferrerPolicyNoReferrer: - *t = ReferrerPolicyNoReferrer - case ReferrerPolicyOrigin: - *t = ReferrerPolicyOrigin - case ReferrerPolicyOriginWhenCrossOrigin: - *t = ReferrerPolicyOriginWhenCrossOrigin - case ReferrerPolicySameOrigin: - *t = ReferrerPolicySameOrigin - case ReferrerPolicyStrictOrigin: - *t = ReferrerPolicyStrictOrigin - case ReferrerPolicyStrictOriginWhenCrossOrigin: - *t = ReferrerPolicyStrictOriginWhenCrossOrigin - default: - return fmt.Errorf("unknown ReferrerPolicy value: %v", s) - } - return nil -} - // TrustTokenParamsRefreshPolicy only set for "token-redemption" operation // and determine whether to request a fresh SRR or use a still valid cached SRR. // @@ -2399,22 +1412,6 @@ const ( TrustTokenParamsRefreshPolicyRefresh TrustTokenParamsRefreshPolicy = "Refresh" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *TrustTokenParamsRefreshPolicy) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch TrustTokenParamsRefreshPolicy(s) { - case TrustTokenParamsRefreshPolicyUseCached: - *t = TrustTokenParamsRefreshPolicyUseCached - case TrustTokenParamsRefreshPolicyRefresh: - *t = TrustTokenParamsRefreshPolicyRefresh - default: - return fmt.Errorf("unknown TrustTokenParamsRefreshPolicy value: %v", s) - } - return nil -} - // InitiatorType type of this initiator. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-Initiator @@ -2436,32 +1433,6 @@ const ( InitiatorTypeOther InitiatorType = "other" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *InitiatorType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch InitiatorType(s) { - case InitiatorTypeParser: - *t = InitiatorTypeParser - case InitiatorTypeScript: - *t = InitiatorTypeScript - case InitiatorTypePreload: - *t = InitiatorTypePreload - case InitiatorTypeSignedExchange: - *t = InitiatorTypeSignedExchange - case InitiatorTypePreflight: - *t = InitiatorTypePreflight - case InitiatorTypeFedCM: - *t = InitiatorTypeFedCM - case InitiatorTypeOther: - *t = InitiatorTypeOther - default: - return fmt.Errorf("unknown InitiatorType value: %v", s) - } - return nil -} - // AuthChallengeSource source of the authentication challenge. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-AuthChallenge @@ -2478,22 +1449,6 @@ const ( AuthChallengeSourceProxy AuthChallengeSource = "Proxy" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *AuthChallengeSource) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch AuthChallengeSource(s) { - case AuthChallengeSourceServer: - *t = AuthChallengeSourceServer - case AuthChallengeSourceProxy: - *t = AuthChallengeSourceProxy - default: - return fmt.Errorf("unknown AuthChallengeSource value: %v", s) - } - return nil -} - // AuthChallengeResponseResponse the decision on what to do in response to // the authorization challenge. Default means deferring to the default behavior // of the net stack, which will likely either the Cancel authentication or @@ -2514,24 +1469,6 @@ const ( AuthChallengeResponseResponseProvideCredentials AuthChallengeResponseResponse = "ProvideCredentials" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *AuthChallengeResponseResponse) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch AuthChallengeResponseResponse(s) { - case AuthChallengeResponseResponseDefault: - *t = AuthChallengeResponseResponseDefault - case AuthChallengeResponseResponseCancelAuth: - *t = AuthChallengeResponseResponseCancelAuth - case AuthChallengeResponseResponseProvideCredentials: - *t = AuthChallengeResponseResponseProvideCredentials - default: - return fmt.Errorf("unknown AuthChallengeResponseResponse value: %v", s) - } - return nil -} - // DeviceBoundSessionWithUsageUsage how the session was used (or not used). // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-DeviceBoundSessionWithUsage @@ -2552,30 +1489,6 @@ const ( DeviceBoundSessionWithUsageUsageDeferred DeviceBoundSessionWithUsageUsage = "Deferred" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DeviceBoundSessionWithUsageUsage) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DeviceBoundSessionWithUsageUsage(s) { - case DeviceBoundSessionWithUsageUsageNotInScope: - *t = DeviceBoundSessionWithUsageUsageNotInScope - case DeviceBoundSessionWithUsageUsageInScopeRefreshNotYetNeeded: - *t = DeviceBoundSessionWithUsageUsageInScopeRefreshNotYetNeeded - case DeviceBoundSessionWithUsageUsageInScopeRefreshNotAllowed: - *t = DeviceBoundSessionWithUsageUsageInScopeRefreshNotAllowed - case DeviceBoundSessionWithUsageUsageProactiveRefreshNotPossible: - *t = DeviceBoundSessionWithUsageUsageProactiveRefreshNotPossible - case DeviceBoundSessionWithUsageUsageProactiveRefreshAttempted: - *t = DeviceBoundSessionWithUsageUsageProactiveRefreshAttempted - case DeviceBoundSessionWithUsageUsageDeferred: - *t = DeviceBoundSessionWithUsageUsageDeferred - default: - return fmt.Errorf("unknown DeviceBoundSessionWithUsageUsage value: %v", s) - } - return nil -} - // DeviceBoundSessionURLRuleRuleType see comments on // net::device_bound_sessions::SessionInclusionRules::UrlRule::rule_type. // @@ -2593,23 +1506,8 @@ const ( DeviceBoundSessionURLRuleRuleTypeInclude DeviceBoundSessionURLRuleRuleType = "Include" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DeviceBoundSessionURLRuleRuleType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DeviceBoundSessionURLRuleRuleType(s) { - case DeviceBoundSessionURLRuleRuleTypeExclude: - *t = DeviceBoundSessionURLRuleRuleTypeExclude - case DeviceBoundSessionURLRuleRuleTypeInclude: - *t = DeviceBoundSessionURLRuleRuleTypeInclude - default: - return fmt.Errorf("unknown DeviceBoundSessionURLRuleRuleType value: %v", s) - } - return nil -} - // RefreshEventDetailsRefreshResult the result of a refresh. +// LINT.IfChange(DeviceBoundSessionRefreshResult). // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-RefreshEventDetails type RefreshEventDetailsRefreshResult string @@ -2621,44 +1519,18 @@ func (t RefreshEventDetailsRefreshResult) String() string { // RefreshEventDetailsRefreshResult values. const ( - RefreshEventDetailsRefreshResultRefreshed RefreshEventDetailsRefreshResult = "Refreshed" - RefreshEventDetailsRefreshResultInitializedService RefreshEventDetailsRefreshResult = "InitializedService" - RefreshEventDetailsRefreshResultUnreachable RefreshEventDetailsRefreshResult = "Unreachable" - RefreshEventDetailsRefreshResultServerError RefreshEventDetailsRefreshResult = "ServerError" - RefreshEventDetailsRefreshResultFatalError RefreshEventDetailsRefreshResult = "FatalError" - RefreshEventDetailsRefreshResultSigningQuotaExceeded RefreshEventDetailsRefreshResult = "SigningQuotaExceeded" - RefreshEventDetailsRefreshResultRefreshedAsWaiter RefreshEventDetailsRefreshResult = "RefreshedAsWaiter" - RefreshEventDetailsRefreshResultTransientSigningError RefreshEventDetailsRefreshResult = "TransientSigningError" + RefreshEventDetailsRefreshResultRefreshed RefreshEventDetailsRefreshResult = "Refreshed" + RefreshEventDetailsRefreshResultInitializedService RefreshEventDetailsRefreshResult = "InitializedService" + RefreshEventDetailsRefreshResultUnreachable RefreshEventDetailsRefreshResult = "Unreachable" + RefreshEventDetailsRefreshResultServerError RefreshEventDetailsRefreshResult = "ServerError" + RefreshEventDetailsRefreshResultFatalError RefreshEventDetailsRefreshResult = "FatalError" + RefreshEventDetailsRefreshResultSigningQuotaExceeded RefreshEventDetailsRefreshResult = "SigningQuotaExceeded" + RefreshEventDetailsRefreshResultRefreshedAsWaiter RefreshEventDetailsRefreshResult = "RefreshedAsWaiter" + RefreshEventDetailsRefreshResultTransientSigningError RefreshEventDetailsRefreshResult = "TransientSigningError" + RefreshEventDetailsRefreshResultInScopeRefreshNotYetNeeded RefreshEventDetailsRefreshResult = "InScopeRefreshNotYetNeeded" + RefreshEventDetailsRefreshResultCanceled RefreshEventDetailsRefreshResult = "Canceled" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *RefreshEventDetailsRefreshResult) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch RefreshEventDetailsRefreshResult(s) { - case RefreshEventDetailsRefreshResultRefreshed: - *t = RefreshEventDetailsRefreshResultRefreshed - case RefreshEventDetailsRefreshResultInitializedService: - *t = RefreshEventDetailsRefreshResultInitializedService - case RefreshEventDetailsRefreshResultUnreachable: - *t = RefreshEventDetailsRefreshResultUnreachable - case RefreshEventDetailsRefreshResultServerError: - *t = RefreshEventDetailsRefreshResultServerError - case RefreshEventDetailsRefreshResultFatalError: - *t = RefreshEventDetailsRefreshResultFatalError - case RefreshEventDetailsRefreshResultSigningQuotaExceeded: - *t = RefreshEventDetailsRefreshResultSigningQuotaExceeded - case RefreshEventDetailsRefreshResultRefreshedAsWaiter: - *t = RefreshEventDetailsRefreshResultRefreshedAsWaiter - case RefreshEventDetailsRefreshResultTransientSigningError: - *t = RefreshEventDetailsRefreshResultTransientSigningError - default: - return fmt.Errorf("unknown RefreshEventDetailsRefreshResult value: %v", s) - } - return nil -} - // TerminationEventDetailsDeletionReason the reason for a session being // deleted. // @@ -2681,38 +1553,9 @@ const ( TerminationEventDetailsDeletionReasonInvalidSessionParams TerminationEventDetailsDeletionReason = "InvalidSessionParams" TerminationEventDetailsDeletionReasonRefreshFatalError TerminationEventDetailsDeletionReason = "RefreshFatalError" TerminationEventDetailsDeletionReasonDevTools TerminationEventDetailsDeletionReason = "DevTools" + TerminationEventDetailsDeletionReasonReplaced TerminationEventDetailsDeletionReason = "Replaced" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *TerminationEventDetailsDeletionReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch TerminationEventDetailsDeletionReason(s) { - case TerminationEventDetailsDeletionReasonExpired: - *t = TerminationEventDetailsDeletionReasonExpired - case TerminationEventDetailsDeletionReasonFailedToRestoreKey: - *t = TerminationEventDetailsDeletionReasonFailedToRestoreKey - case TerminationEventDetailsDeletionReasonFailedToUnwrapKey: - *t = TerminationEventDetailsDeletionReasonFailedToUnwrapKey - case TerminationEventDetailsDeletionReasonStoragePartitionCleared: - *t = TerminationEventDetailsDeletionReasonStoragePartitionCleared - case TerminationEventDetailsDeletionReasonClearBrowsingData: - *t = TerminationEventDetailsDeletionReasonClearBrowsingData - case TerminationEventDetailsDeletionReasonServerRequested: - *t = TerminationEventDetailsDeletionReasonServerRequested - case TerminationEventDetailsDeletionReasonInvalidSessionParams: - *t = TerminationEventDetailsDeletionReasonInvalidSessionParams - case TerminationEventDetailsDeletionReasonRefreshFatalError: - *t = TerminationEventDetailsDeletionReasonRefreshFatalError - case TerminationEventDetailsDeletionReasonDevTools: - *t = TerminationEventDetailsDeletionReasonDevTools - default: - return fmt.Errorf("unknown TerminationEventDetailsDeletionReason value: %v", s) - } - return nil -} - // ChallengeEventDetailsChallengeResult the result of a challenge. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-ChallengeEventDetails @@ -2731,26 +1574,6 @@ const ( ChallengeEventDetailsChallengeResultCantSetBoundCookie ChallengeEventDetailsChallengeResult = "CantSetBoundCookie" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ChallengeEventDetailsChallengeResult) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ChallengeEventDetailsChallengeResult(s) { - case ChallengeEventDetailsChallengeResultSuccess: - *t = ChallengeEventDetailsChallengeResultSuccess - case ChallengeEventDetailsChallengeResultNoSessionID: - *t = ChallengeEventDetailsChallengeResultNoSessionID - case ChallengeEventDetailsChallengeResultNoSessionMatch: - *t = ChallengeEventDetailsChallengeResultNoSessionMatch - case ChallengeEventDetailsChallengeResultCantSetBoundCookie: - *t = ChallengeEventDetailsChallengeResultCantSetBoundCookie - default: - return fmt.Errorf("unknown ChallengeEventDetailsChallengeResult value: %v", s) - } - return nil -} - // TrustTokenOperationDoneStatus detailed success or error status of the // operation. 'AlreadyExists' also signifies a successful operation, as the // result of the operation already exists und thus, the operation was abort @@ -2780,41 +1603,3 @@ const ( TrustTokenOperationDoneStatusFulfilledLocally TrustTokenOperationDoneStatus = "FulfilledLocally" TrustTokenOperationDoneStatusSiteIssuerLimit TrustTokenOperationDoneStatus = "SiteIssuerLimit" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *TrustTokenOperationDoneStatus) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch TrustTokenOperationDoneStatus(s) { - case TrustTokenOperationDoneStatusOk: - *t = TrustTokenOperationDoneStatusOk - case TrustTokenOperationDoneStatusInvalidArgument: - *t = TrustTokenOperationDoneStatusInvalidArgument - case TrustTokenOperationDoneStatusMissingIssuerKeys: - *t = TrustTokenOperationDoneStatusMissingIssuerKeys - case TrustTokenOperationDoneStatusFailedPrecondition: - *t = TrustTokenOperationDoneStatusFailedPrecondition - case TrustTokenOperationDoneStatusResourceExhausted: - *t = TrustTokenOperationDoneStatusResourceExhausted - case TrustTokenOperationDoneStatusAlreadyExists: - *t = TrustTokenOperationDoneStatusAlreadyExists - case TrustTokenOperationDoneStatusResourceLimited: - *t = TrustTokenOperationDoneStatusResourceLimited - case TrustTokenOperationDoneStatusUnauthorized: - *t = TrustTokenOperationDoneStatusUnauthorized - case TrustTokenOperationDoneStatusBadResponse: - *t = TrustTokenOperationDoneStatusBadResponse - case TrustTokenOperationDoneStatusInternalError: - *t = TrustTokenOperationDoneStatusInternalError - case TrustTokenOperationDoneStatusUnknownError: - *t = TrustTokenOperationDoneStatusUnknownError - case TrustTokenOperationDoneStatusFulfilledLocally: - *t = TrustTokenOperationDoneStatusFulfilledLocally - case TrustTokenOperationDoneStatusSiteIssuerLimit: - *t = TrustTokenOperationDoneStatusSiteIssuerLimit - default: - return fmt.Errorf("unknown TrustTokenOperationDoneStatus value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/overlay/events.go b/vendor/github.com/chromedp/cdproto/overlay/events.go index 44323b71d..d8b564d9f 100644 --- a/vendor/github.com/chromedp/cdproto/overlay/events.go +++ b/vendor/github.com/chromedp/cdproto/overlay/events.go @@ -1,6 +1,6 @@ -package overlay +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package overlay import ( "github.com/chromedp/cdproto/cdp" diff --git a/vendor/github.com/chromedp/cdproto/overlay/overlay.go b/vendor/github.com/chromedp/cdproto/overlay/overlay.go index 3a9e329f8..6492e0105 100644 --- a/vendor/github.com/chromedp/cdproto/overlay/overlay.go +++ b/vendor/github.com/chromedp/cdproto/overlay/overlay.go @@ -1,220 +1,93 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package overlay provides the Chrome DevTools Protocol // commands, types, and events for the Overlay domain. // // This domain provides various functionality related to drawing atop the // inspected page. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package overlay -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" "github.com/chromedp/cdproto/dom" "github.com/chromedp/cdproto/runtime" - "github.com/go-json-experiment/json/jsontext" ) -// DisableParams disables domain notifications. -type DisableParams struct{} - // Disable disables domain notifications. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes Overlay.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// EnableParams enables domain notifications. -type EnableParams struct{} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} // Enable enables domain notifications. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} -// Do executes Overlay.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) +// GetHighlightObjectForTestParams are the parameters of the command +// Overlay.getHighlightObjectForTest. +type GetHighlightObjectForTestParams struct { + NodeID cdp.NodeID `json:"nodeId"` // Id of the node to get highlight object for. + IncludeDistance *bool `json:"includeDistance,omitempty,omitzero"` // Whether to include distance info. + IncludeStyle *bool `json:"includeStyle,omitempty,omitzero"` // Whether to include style info. + ColorFormat ColorFormat `json:"colorFormat,omitempty,omitzero"` // The color format to get config with (default: hex). + ShowAccessibilityInfo *bool `json:"showAccessibilityInfo,omitempty,omitzero"` // Whether to show accessibility info (default: true). } -// GetHighlightObjectForTestParams for testing. -type GetHighlightObjectForTestParams struct { - NodeID cdp.NodeID `json:"nodeId"` // Id of the node to get highlight object for. - IncludeDistance bool `json:"includeDistance"` // Whether to include distance info. - IncludeStyle bool `json:"includeStyle"` // Whether to include style info. - ColorFormat ColorFormat `json:"colorFormat,omitempty,omitzero"` // The color format to get config with (default: hex). - ShowAccessibilityInfo bool `json:"showAccessibilityInfo"` // Whether to show accessibility info (default: true). +// GetHighlightObjectForTestResult is the result of the command +// Overlay.getHighlightObjectForTest. +type GetHighlightObjectForTestResult struct { + Highlight jsonv2.Value `json:"highlight,omitempty,omitzero"` } // GetHighlightObjectForTest for testing. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-getHighlightObjectForTest -// -// parameters: -// -// nodeID - Id of the node to get highlight object for. -func GetHighlightObjectForTest(nodeID cdp.NodeID) *GetHighlightObjectForTestParams { - return &GetHighlightObjectForTestParams{ - NodeID: nodeID, - IncludeDistance: false, - IncludeStyle: false, - ShowAccessibilityInfo: true, - } -} - -// WithIncludeDistance whether to include distance info. -func (p GetHighlightObjectForTestParams) WithIncludeDistance(includeDistance bool) *GetHighlightObjectForTestParams { - p.IncludeDistance = includeDistance - return &p -} - -// WithIncludeStyle whether to include style info. -func (p GetHighlightObjectForTestParams) WithIncludeStyle(includeStyle bool) *GetHighlightObjectForTestParams { - p.IncludeStyle = includeStyle - return &p -} - -// WithColorFormat the color format to get config with (default: hex). -func (p GetHighlightObjectForTestParams) WithColorFormat(colorFormat ColorFormat) *GetHighlightObjectForTestParams { - p.ColorFormat = colorFormat - return &p -} +var GetHighlightObjectForTest = cdp.Command[GetHighlightObjectForTestParams, GetHighlightObjectForTestResult]{Method: CommandGetHighlightObjectForTest} -// WithShowAccessibilityInfo whether to show accessibility info (default: -// true). -func (p GetHighlightObjectForTestParams) WithShowAccessibilityInfo(showAccessibilityInfo bool) *GetHighlightObjectForTestParams { - p.ShowAccessibilityInfo = showAccessibilityInfo - return &p -} - -// GetHighlightObjectForTestReturns return values. -type GetHighlightObjectForTestReturns struct { - Highlight jsontext.Value `json:"highlight,omitempty,omitzero"` -} - -// Do executes Overlay.getHighlightObjectForTest against the provided context. -// -// returns: -// -// highlight - Highlight data for the node. -func (p *GetHighlightObjectForTestParams) Do(ctx context.Context) (highlight jsontext.Value, err error) { - // execute - var res GetHighlightObjectForTestReturns - err = cdp.Execute(ctx, CommandGetHighlightObjectForTest, p, &res) - if err != nil { - return nil, err - } - - return res.Highlight, nil -} - -// GetGridHighlightObjectsForTestParams for Persistent Grid testing. +// GetGridHighlightObjectsForTestParams are the parameters of the command +// Overlay.getGridHighlightObjectsForTest. type GetGridHighlightObjectsForTestParams struct { NodeIDs []cdp.NodeID `json:"nodeIds"` // Ids of the node to get highlight object for. } -// GetGridHighlightObjectsForTest for Persistent Grid testing. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-getGridHighlightObjectsForTest -// -// parameters: -// -// nodeIDs - Ids of the node to get highlight object for. -func GetGridHighlightObjectsForTest(nodeIDs []cdp.NodeID) *GetGridHighlightObjectsForTestParams { - return &GetGridHighlightObjectsForTestParams{ - NodeIDs: nodeIDs, - } -} - -// GetGridHighlightObjectsForTestReturns return values. -type GetGridHighlightObjectsForTestReturns struct { - Highlights jsontext.Value `json:"highlights,omitempty,omitzero"` +// GetGridHighlightObjectsForTestResult is the result of the command +// Overlay.getGridHighlightObjectsForTest. +type GetGridHighlightObjectsForTestResult struct { + Highlights jsonv2.Value `json:"highlights,omitempty,omitzero"` } -// Do executes Overlay.getGridHighlightObjectsForTest against the provided context. -// -// returns: +// GetGridHighlightObjectsForTest for Persistent Grid testing. // -// highlights - Grid Highlight data for the node ids provided. -func (p *GetGridHighlightObjectsForTestParams) Do(ctx context.Context) (highlights jsontext.Value, err error) { - // execute - var res GetGridHighlightObjectsForTestReturns - err = cdp.Execute(ctx, CommandGetGridHighlightObjectsForTest, p, &res) - if err != nil { - return nil, err - } - - return res.Highlights, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-getGridHighlightObjectsForTest +var GetGridHighlightObjectsForTest = cdp.Command[GetGridHighlightObjectsForTestParams, GetGridHighlightObjectsForTestResult]{Method: CommandGetGridHighlightObjectsForTest} -// GetSourceOrderHighlightObjectForTestParams for Source Order Viewer -// testing. +// GetSourceOrderHighlightObjectForTestParams are the parameters of the +// command Overlay.getSourceOrderHighlightObjectForTest. type GetSourceOrderHighlightObjectForTestParams struct { NodeID cdp.NodeID `json:"nodeId"` // Id of the node to highlight. } -// GetSourceOrderHighlightObjectForTest for Source Order Viewer testing. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-getSourceOrderHighlightObjectForTest -// -// parameters: -// -// nodeID - Id of the node to highlight. -func GetSourceOrderHighlightObjectForTest(nodeID cdp.NodeID) *GetSourceOrderHighlightObjectForTestParams { - return &GetSourceOrderHighlightObjectForTestParams{ - NodeID: nodeID, - } -} - -// GetSourceOrderHighlightObjectForTestReturns return values. -type GetSourceOrderHighlightObjectForTestReturns struct { - Highlight jsontext.Value `json:"highlight,omitempty,omitzero"` +// GetSourceOrderHighlightObjectForTestResult is the result of the command +// Overlay.getSourceOrderHighlightObjectForTest. +type GetSourceOrderHighlightObjectForTestResult struct { + Highlight jsonv2.Value `json:"highlight,omitempty,omitzero"` } -// Do executes Overlay.getSourceOrderHighlightObjectForTest against the provided context. -// -// returns: +// GetSourceOrderHighlightObjectForTest for Source Order Viewer testing. // -// highlight - Source order highlight data for the node id provided. -func (p *GetSourceOrderHighlightObjectForTestParams) Do(ctx context.Context) (highlight jsontext.Value, err error) { - // execute - var res GetSourceOrderHighlightObjectForTestReturns - err = cdp.Execute(ctx, CommandGetSourceOrderHighlightObjectForTest, p, &res) - if err != nil { - return nil, err - } - - return res.Highlight, nil -} - -// HideHighlightParams hides any highlight. -type HideHighlightParams struct{} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-getSourceOrderHighlightObjectForTest +var GetSourceOrderHighlightObjectForTest = cdp.Command[GetSourceOrderHighlightObjectForTestParams, GetSourceOrderHighlightObjectForTestResult]{Method: CommandGetSourceOrderHighlightObjectForTest} // HideHighlight hides any highlight. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-hideHighlight -func HideHighlight() *HideHighlightParams { - return &HideHighlightParams{} -} +var HideHighlight = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandHideHighlight} -// Do executes Overlay.hideHighlight against the provided context. -func (p *HideHighlightParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandHideHighlight, nil, nil) -} - -// HighlightNodeParams highlights DOM node with given id or with the given -// JavaScript object wrapper. Either nodeId or objectId must be specified. +// HighlightNodeParams are the parameters of the command +// Overlay.highlightNode. type HighlightNodeParams struct { HighlightConfig *HighlightConfig `json:"highlightConfig"` // A descriptor for the highlight appearance. NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Identifier of the node to highlight. @@ -227,47 +100,10 @@ type HighlightNodeParams struct { // JavaScript object wrapper. Either nodeId or objectId must be specified. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-highlightNode -// -// parameters: -// -// highlightConfig - A descriptor for the highlight appearance. -func HighlightNode(highlightConfig *HighlightConfig) *HighlightNodeParams { - return &HighlightNodeParams{ - HighlightConfig: highlightConfig, - } -} - -// WithNodeID identifier of the node to highlight. -func (p HighlightNodeParams) WithNodeID(nodeID cdp.NodeID) *HighlightNodeParams { - p.NodeID = nodeID - return &p -} - -// WithBackendNodeID identifier of the backend node to highlight. -func (p HighlightNodeParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *HighlightNodeParams { - p.BackendNodeID = backendNodeID - return &p -} - -// WithObjectID JavaScript object id of the node to be highlighted. -func (p HighlightNodeParams) WithObjectID(objectID runtime.RemoteObjectID) *HighlightNodeParams { - p.ObjectID = objectID - return &p -} - -// WithSelector selectors to highlight relevant nodes. -func (p HighlightNodeParams) WithSelector(selector string) *HighlightNodeParams { - p.Selector = selector - return &p -} - -// Do executes Overlay.highlightNode against the provided context. -func (p *HighlightNodeParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandHighlightNode, p, nil) -} +var HighlightNode = cdp.Command[HighlightNodeParams, cdp.Empty]{Method: CommandHighlightNode} -// HighlightQuadParams highlights given quad. Coordinates are absolute with -// respect to the main frame viewport. +// HighlightQuadParams are the parameters of the command +// Overlay.highlightQuad. type HighlightQuadParams struct { Quad dom.Quad `json:"quad"` // Quad to highlight Color *cdp.RGBA `json:"color,omitempty,omitzero"` // The highlight fill color (default: transparent). @@ -278,37 +114,10 @@ type HighlightQuadParams struct { // to the main frame viewport. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-highlightQuad -// -// parameters: -// -// quad - Quad to highlight -func HighlightQuad(quad dom.Quad) *HighlightQuadParams { - return &HighlightQuadParams{ - Quad: quad, - } -} +var HighlightQuad = cdp.Command[HighlightQuadParams, cdp.Empty]{Method: CommandHighlightQuad} -// WithColor the highlight fill color (default: transparent). -func (p HighlightQuadParams) WithColor(color *cdp.RGBA) *HighlightQuadParams { - p.Color = color - return &p -} - -// WithOutlineColor the highlight outline color (default: transparent). -func (p HighlightQuadParams) WithOutlineColor(outlineColor *cdp.RGBA) *HighlightQuadParams { - p.OutlineColor = outlineColor - return &p -} - -// Do executes Overlay.highlightQuad against the provided context. -func (p *HighlightQuadParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandHighlightQuad, p, nil) -} - -// HighlightRectParams highlights given rectangle. Coordinates are absolute -// with respect to the main frame viewport. Issue: the method does not handle -// device pixel ratio (DPR) correctly. The coordinates currently have to be -// adjusted by the client if DPR is not 1 (see crbug.com/437807128). +// HighlightRectParams are the parameters of the command +// Overlay.highlightRect. type HighlightRectParams struct { X int64 `json:"x"` // X coordinate Y int64 `json:"y"` // Y coordinate @@ -324,42 +133,10 @@ type HighlightRectParams struct { // the client if DPR is not 1 (see crbug.com/437807128). // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-highlightRect -// -// parameters: -// -// x - X coordinate -// y - Y coordinate -// width - Rectangle width -// height - Rectangle height -func HighlightRect(x int64, y int64, width int64, height int64) *HighlightRectParams { - return &HighlightRectParams{ - X: x, - Y: y, - Width: width, - Height: height, - } -} - -// WithColor the highlight fill color (default: transparent). -func (p HighlightRectParams) WithColor(color *cdp.RGBA) *HighlightRectParams { - p.Color = color - return &p -} +var HighlightRect = cdp.Command[HighlightRectParams, cdp.Empty]{Method: CommandHighlightRect} -// WithOutlineColor the highlight outline color (default: transparent). -func (p HighlightRectParams) WithOutlineColor(outlineColor *cdp.RGBA) *HighlightRectParams { - p.OutlineColor = outlineColor - return &p -} - -// Do executes Overlay.highlightRect against the provided context. -func (p *HighlightRectParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandHighlightRect, p, nil) -} - -// HighlightSourceOrderParams highlights the source order of the children of -// the DOM node with given id or with the given JavaScript object wrapper. -// Either nodeId or objectId must be specified. +// HighlightSourceOrderParams are the parameters of the command +// Overlay.highlightSourceOrder. type HighlightSourceOrderParams struct { SourceOrderConfig *SourceOrderConfig `json:"sourceOrderConfig"` // A descriptor for the appearance of the overlay drawing. NodeID cdp.NodeID `json:"nodeId,omitempty,omitzero"` // Identifier of the node to highlight. @@ -372,42 +149,10 @@ type HighlightSourceOrderParams struct { // nodeId or objectId must be specified. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-highlightSourceOrder -// -// parameters: -// -// sourceOrderConfig - A descriptor for the appearance of the overlay drawing. -func HighlightSourceOrder(sourceOrderConfig *SourceOrderConfig) *HighlightSourceOrderParams { - return &HighlightSourceOrderParams{ - SourceOrderConfig: sourceOrderConfig, - } -} - -// WithNodeID identifier of the node to highlight. -func (p HighlightSourceOrderParams) WithNodeID(nodeID cdp.NodeID) *HighlightSourceOrderParams { - p.NodeID = nodeID - return &p -} - -// WithBackendNodeID identifier of the backend node to highlight. -func (p HighlightSourceOrderParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *HighlightSourceOrderParams { - p.BackendNodeID = backendNodeID - return &p -} - -// WithObjectID JavaScript object id of the node to be highlighted. -func (p HighlightSourceOrderParams) WithObjectID(objectID runtime.RemoteObjectID) *HighlightSourceOrderParams { - p.ObjectID = objectID - return &p -} - -// Do executes Overlay.highlightSourceOrder against the provided context. -func (p *HighlightSourceOrderParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandHighlightSourceOrder, p, nil) -} +var HighlightSourceOrder = cdp.Command[HighlightSourceOrderParams, cdp.Empty]{Method: CommandHighlightSourceOrder} -// SetInspectModeParams enters the 'inspect' mode. In this mode, elements -// that user is hovering over are highlighted. Backend then generates -// 'inspectNodeRequested' event upon element selection. +// SetInspectModeParams are the parameters of the command +// Overlay.setInspectMode. type SetInspectModeParams struct { Mode InspectMode `json:"mode"` // Set an inspection mode. HighlightConfig *HighlightConfig `json:"highlightConfig,omitempty,omitzero"` // A descriptor for the highlight appearance of hovered-over nodes. May be omitted if enabled == false. @@ -418,30 +163,10 @@ type SetInspectModeParams struct { // 'inspectNodeRequested' event upon element selection. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setInspectMode -// -// parameters: -// -// mode - Set an inspection mode. -func SetInspectMode(mode InspectMode) *SetInspectModeParams { - return &SetInspectModeParams{ - Mode: mode, - } -} - -// WithHighlightConfig a descriptor for the highlight appearance of -// hovered-over nodes. May be omitted if enabled == false. -func (p SetInspectModeParams) WithHighlightConfig(highlightConfig *HighlightConfig) *SetInspectModeParams { - p.HighlightConfig = highlightConfig - return &p -} +var SetInspectMode = cdp.Command[SetInspectModeParams, cdp.Empty]{Method: CommandSetInspectMode} -// Do executes Overlay.setInspectMode against the provided context. -func (p *SetInspectModeParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetInspectMode, p, nil) -} - -// SetShowAdHighlightsParams highlights owner element of all frames detected -// to be ads. +// SetShowAdHighlightsParams are the parameters of the command +// Overlay.setShowAdHighlights. type SetShowAdHighlightsParams struct { Show bool `json:"show"` // True for showing ad highlights } @@ -450,22 +175,10 @@ type SetShowAdHighlightsParams struct { // ads. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowAdHighlights -// -// parameters: -// -// show - True for showing ad highlights -func SetShowAdHighlights(show bool) *SetShowAdHighlightsParams { - return &SetShowAdHighlightsParams{ - Show: show, - } -} - -// Do executes Overlay.setShowAdHighlights against the provided context. -func (p *SetShowAdHighlightsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetShowAdHighlights, p, nil) -} +var SetShowAdHighlights = cdp.Command[SetShowAdHighlightsParams, cdp.Empty]{Method: CommandSetShowAdHighlights} -// SetPausedInDebuggerMessageParams [no description]. +// SetPausedInDebuggerMessageParams are the parameters of the command +// Overlay.setPausedInDebuggerMessage. type SetPausedInDebuggerMessageParams struct { Message string `json:"message,omitempty,omitzero"` // The message to display, also triggers resume and step over controls. } @@ -473,26 +186,10 @@ type SetPausedInDebuggerMessageParams struct { // SetPausedInDebuggerMessage [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setPausedInDebuggerMessage -// -// parameters: -func SetPausedInDebuggerMessage() *SetPausedInDebuggerMessageParams { - return &SetPausedInDebuggerMessageParams{} -} - -// WithMessage the message to display, also triggers resume and step over -// controls. -func (p SetPausedInDebuggerMessageParams) WithMessage(message string) *SetPausedInDebuggerMessageParams { - p.Message = message - return &p -} - -// Do executes Overlay.setPausedInDebuggerMessage against the provided context. -func (p *SetPausedInDebuggerMessageParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetPausedInDebuggerMessage, p, nil) -} +var SetPausedInDebuggerMessage = cdp.Command[SetPausedInDebuggerMessageParams, cdp.Empty]{Method: CommandSetPausedInDebuggerMessage} -// SetShowDebugBordersParams requests that backend shows debug borders on -// layers. +// SetShowDebugBordersParams are the parameters of the command +// Overlay.setShowDebugBorders. type SetShowDebugBordersParams struct { Show bool `json:"show"` // True for showing debug borders } @@ -500,22 +197,10 @@ type SetShowDebugBordersParams struct { // SetShowDebugBorders requests that backend shows debug borders on layers. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowDebugBorders -// -// parameters: -// -// show - True for showing debug borders -func SetShowDebugBorders(show bool) *SetShowDebugBordersParams { - return &SetShowDebugBordersParams{ - Show: show, - } -} +var SetShowDebugBorders = cdp.Command[SetShowDebugBordersParams, cdp.Empty]{Method: CommandSetShowDebugBorders} -// Do executes Overlay.setShowDebugBorders against the provided context. -func (p *SetShowDebugBordersParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetShowDebugBorders, p, nil) -} - -// SetShowFPSCounterParams requests that backend shows the FPS counter. +// SetShowFPSCounterParams are the parameters of the command +// Overlay.setShowFPSCounter. type SetShowFPSCounterParams struct { Show bool `json:"show"` // True for showing the FPS counter } @@ -523,23 +208,10 @@ type SetShowFPSCounterParams struct { // SetShowFPSCounter requests that backend shows the FPS counter. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowFPSCounter -// -// parameters: -// -// show - True for showing the FPS counter -func SetShowFPSCounter(show bool) *SetShowFPSCounterParams { - return &SetShowFPSCounterParams{ - Show: show, - } -} - -// Do executes Overlay.setShowFPSCounter against the provided context. -func (p *SetShowFPSCounterParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetShowFPSCounter, p, nil) -} +var SetShowFPSCounter = cdp.Command[SetShowFPSCounterParams, cdp.Empty]{Method: CommandSetShowFPSCounter} -// SetShowGridOverlaysParams highlight multiple elements with the CSS Grid -// overlay. +// SetShowGridOverlaysParams are the parameters of the command +// Overlay.setShowGridOverlays. type SetShowGridOverlaysParams struct { GridNodeHighlightConfigs []*GridNodeHighlightConfig `json:"gridNodeHighlightConfigs"` // An array of node identifiers and descriptors for the highlight appearance. } @@ -547,22 +219,10 @@ type SetShowGridOverlaysParams struct { // SetShowGridOverlays highlight multiple elements with the CSS Grid overlay. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowGridOverlays -// -// parameters: -// -// gridNodeHighlightConfigs - An array of node identifiers and descriptors for the highlight appearance. -func SetShowGridOverlays(gridNodeHighlightConfigs []*GridNodeHighlightConfig) *SetShowGridOverlaysParams { - return &SetShowGridOverlaysParams{ - GridNodeHighlightConfigs: gridNodeHighlightConfigs, - } -} +var SetShowGridOverlays = cdp.Command[SetShowGridOverlaysParams, cdp.Empty]{Method: CommandSetShowGridOverlays} -// Do executes Overlay.setShowGridOverlays against the provided context. -func (p *SetShowGridOverlaysParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetShowGridOverlays, p, nil) -} - -// SetShowFlexOverlaysParams [no description]. +// SetShowFlexOverlaysParams are the parameters of the command +// Overlay.setShowFlexOverlays. type SetShowFlexOverlaysParams struct { FlexNodeHighlightConfigs []*FlexNodeHighlightConfig `json:"flexNodeHighlightConfigs"` // An array of node identifiers and descriptors for the highlight appearance. } @@ -570,22 +230,10 @@ type SetShowFlexOverlaysParams struct { // SetShowFlexOverlays [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowFlexOverlays -// -// parameters: -// -// flexNodeHighlightConfigs - An array of node identifiers and descriptors for the highlight appearance. -func SetShowFlexOverlays(flexNodeHighlightConfigs []*FlexNodeHighlightConfig) *SetShowFlexOverlaysParams { - return &SetShowFlexOverlaysParams{ - FlexNodeHighlightConfigs: flexNodeHighlightConfigs, - } -} - -// Do executes Overlay.setShowFlexOverlays against the provided context. -func (p *SetShowFlexOverlaysParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetShowFlexOverlays, p, nil) -} +var SetShowFlexOverlays = cdp.Command[SetShowFlexOverlaysParams, cdp.Empty]{Method: CommandSetShowFlexOverlays} -// SetShowScrollSnapOverlaysParams [no description]. +// SetShowScrollSnapOverlaysParams are the parameters of the command +// Overlay.setShowScrollSnapOverlays. type SetShowScrollSnapOverlaysParams struct { ScrollSnapHighlightConfigs []*ScrollSnapHighlightConfig `json:"scrollSnapHighlightConfigs"` // An array of node identifiers and descriptors for the highlight appearance. } @@ -593,22 +241,10 @@ type SetShowScrollSnapOverlaysParams struct { // SetShowScrollSnapOverlays [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowScrollSnapOverlays -// -// parameters: -// -// scrollSnapHighlightConfigs - An array of node identifiers and descriptors for the highlight appearance. -func SetShowScrollSnapOverlays(scrollSnapHighlightConfigs []*ScrollSnapHighlightConfig) *SetShowScrollSnapOverlaysParams { - return &SetShowScrollSnapOverlaysParams{ - ScrollSnapHighlightConfigs: scrollSnapHighlightConfigs, - } -} +var SetShowScrollSnapOverlays = cdp.Command[SetShowScrollSnapOverlaysParams, cdp.Empty]{Method: CommandSetShowScrollSnapOverlays} -// Do executes Overlay.setShowScrollSnapOverlays against the provided context. -func (p *SetShowScrollSnapOverlaysParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetShowScrollSnapOverlays, p, nil) -} - -// SetShowContainerQueryOverlaysParams [no description]. +// SetShowContainerQueryOverlaysParams are the parameters of the command +// Overlay.setShowContainerQueryOverlays. type SetShowContainerQueryOverlaysParams struct { ContainerQueryHighlightConfigs []*ContainerQueryHighlightConfig `json:"containerQueryHighlightConfigs"` // An array of node identifiers and descriptors for the highlight appearance. } @@ -616,22 +252,10 @@ type SetShowContainerQueryOverlaysParams struct { // SetShowContainerQueryOverlays [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowContainerQueryOverlays -// -// parameters: -// -// containerQueryHighlightConfigs - An array of node identifiers and descriptors for the highlight appearance. -func SetShowContainerQueryOverlays(containerQueryHighlightConfigs []*ContainerQueryHighlightConfig) *SetShowContainerQueryOverlaysParams { - return &SetShowContainerQueryOverlaysParams{ - ContainerQueryHighlightConfigs: containerQueryHighlightConfigs, - } -} - -// Do executes Overlay.setShowContainerQueryOverlays against the provided context. -func (p *SetShowContainerQueryOverlaysParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetShowContainerQueryOverlays, p, nil) -} +var SetShowContainerQueryOverlays = cdp.Command[SetShowContainerQueryOverlaysParams, cdp.Empty]{Method: CommandSetShowContainerQueryOverlays} -// SetShowInspectedElementAnchorParams [no description]. +// SetShowInspectedElementAnchorParams are the parameters of the command +// Overlay.setShowInspectedElementAnchor. type SetShowInspectedElementAnchorParams struct { InspectedElementAnchorConfig *InspectedElementAnchorConfig `json:"inspectedElementAnchorConfig"` // Node identifier for which to show an anchor for. } @@ -639,22 +263,10 @@ type SetShowInspectedElementAnchorParams struct { // SetShowInspectedElementAnchor [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowInspectedElementAnchor -// -// parameters: -// -// inspectedElementAnchorConfig - Node identifier for which to show an anchor for. -func SetShowInspectedElementAnchor(inspectedElementAnchorConfig *InspectedElementAnchorConfig) *SetShowInspectedElementAnchorParams { - return &SetShowInspectedElementAnchorParams{ - InspectedElementAnchorConfig: inspectedElementAnchorConfig, - } -} - -// Do executes Overlay.setShowInspectedElementAnchor against the provided context. -func (p *SetShowInspectedElementAnchorParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetShowInspectedElementAnchor, p, nil) -} +var SetShowInspectedElementAnchor = cdp.Command[SetShowInspectedElementAnchorParams, cdp.Empty]{Method: CommandSetShowInspectedElementAnchor} -// SetShowPaintRectsParams requests that backend shows paint rectangles. +// SetShowPaintRectsParams are the parameters of the command +// Overlay.setShowPaintRects. type SetShowPaintRectsParams struct { Result bool `json:"result"` // True for showing paint rectangles } @@ -662,23 +274,10 @@ type SetShowPaintRectsParams struct { // SetShowPaintRects requests that backend shows paint rectangles. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowPaintRects -// -// parameters: -// -// result - True for showing paint rectangles -func SetShowPaintRects(result bool) *SetShowPaintRectsParams { - return &SetShowPaintRectsParams{ - Result: result, - } -} +var SetShowPaintRects = cdp.Command[SetShowPaintRectsParams, cdp.Empty]{Method: CommandSetShowPaintRects} -// Do executes Overlay.setShowPaintRects against the provided context. -func (p *SetShowPaintRectsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetShowPaintRects, p, nil) -} - -// SetShowLayoutShiftRegionsParams requests that backend shows layout shift -// regions. +// SetShowLayoutShiftRegionsParams are the parameters of the command +// Overlay.setShowLayoutShiftRegions. type SetShowLayoutShiftRegionsParams struct { Result bool `json:"result"` // True for showing layout shift regions } @@ -687,23 +286,10 @@ type SetShowLayoutShiftRegionsParams struct { // regions. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowLayoutShiftRegions -// -// parameters: -// -// result - True for showing layout shift regions -func SetShowLayoutShiftRegions(result bool) *SetShowLayoutShiftRegionsParams { - return &SetShowLayoutShiftRegionsParams{ - Result: result, - } -} - -// Do executes Overlay.setShowLayoutShiftRegions against the provided context. -func (p *SetShowLayoutShiftRegionsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetShowLayoutShiftRegions, p, nil) -} +var SetShowLayoutShiftRegions = cdp.Command[SetShowLayoutShiftRegionsParams, cdp.Empty]{Method: CommandSetShowLayoutShiftRegions} -// SetShowScrollBottleneckRectsParams requests that backend shows scroll -// bottleneck rects. +// SetShowScrollBottleneckRectsParams are the parameters of the command +// Overlay.setShowScrollBottleneckRects. type SetShowScrollBottleneckRectsParams struct { Show bool `json:"show"` // True for showing scroll bottleneck rects } @@ -712,23 +298,10 @@ type SetShowScrollBottleneckRectsParams struct { // rects. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowScrollBottleneckRects -// -// parameters: -// -// show - True for showing scroll bottleneck rects -func SetShowScrollBottleneckRects(show bool) *SetShowScrollBottleneckRectsParams { - return &SetShowScrollBottleneckRectsParams{ - Show: show, - } -} - -// Do executes Overlay.setShowScrollBottleneckRects against the provided context. -func (p *SetShowScrollBottleneckRectsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetShowScrollBottleneckRects, p, nil) -} +var SetShowScrollBottleneckRects = cdp.Command[SetShowScrollBottleneckRectsParams, cdp.Empty]{Method: CommandSetShowScrollBottleneckRects} -// SetShowViewportSizeOnResizeParams paints viewport size upon main frame -// resize. +// SetShowViewportSizeOnResizeParams are the parameters of the command +// Overlay.setShowViewportSizeOnResize. type SetShowViewportSizeOnResizeParams struct { Show bool `json:"show"` // Whether to paint size or not. } @@ -736,22 +309,9 @@ type SetShowViewportSizeOnResizeParams struct { // SetShowViewportSizeOnResize paints viewport size upon main frame resize. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowViewportSizeOnResize -// -// parameters: -// -// show - Whether to paint size or not. -func SetShowViewportSizeOnResize(show bool) *SetShowViewportSizeOnResizeParams { - return &SetShowViewportSizeOnResizeParams{ - Show: show, - } -} +var SetShowViewportSizeOnResize = cdp.Command[SetShowViewportSizeOnResizeParams, cdp.Empty]{Method: CommandSetShowViewportSizeOnResize} -// Do executes Overlay.setShowViewportSizeOnResize against the provided context. -func (p *SetShowViewportSizeOnResizeParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetShowViewportSizeOnResize, p, nil) -} - -// SetShowHingeParams add a dual screen device hinge. +// SetShowHingeParams are the parameters of the command Overlay.setShowHinge. type SetShowHingeParams struct { HingeConfig *HingeConfig `json:"hingeConfig,omitempty,omitzero"` // hinge data, null means hideHinge } @@ -759,24 +319,10 @@ type SetShowHingeParams struct { // SetShowHinge add a dual screen device hinge. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowHinge -// -// parameters: -func SetShowHinge() *SetShowHingeParams { - return &SetShowHingeParams{} -} - -// WithHingeConfig hinge data, null means hideHinge. -func (p SetShowHingeParams) WithHingeConfig(hingeConfig *HingeConfig) *SetShowHingeParams { - p.HingeConfig = hingeConfig - return &p -} +var SetShowHinge = cdp.Command[SetShowHingeParams, cdp.Empty]{Method: CommandSetShowHinge} -// Do executes Overlay.setShowHinge against the provided context. -func (p *SetShowHingeParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetShowHinge, p, nil) -} - -// SetShowDisplayCutoutParams add a display cutout overlay. +// SetShowDisplayCutoutParams are the parameters of the command +// Overlay.setShowDisplayCutout. type SetShowDisplayCutoutParams struct { DisplayCutoutConfig *DisplayCutoutConfig `json:"displayCutoutConfig,omitempty,omitzero"` // display cutout data, null means hide display cutout } @@ -784,26 +330,10 @@ type SetShowDisplayCutoutParams struct { // SetShowDisplayCutout add a display cutout overlay. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowDisplayCutout -// -// parameters: -func SetShowDisplayCutout() *SetShowDisplayCutoutParams { - return &SetShowDisplayCutoutParams{} -} +var SetShowDisplayCutout = cdp.Command[SetShowDisplayCutoutParams, cdp.Empty]{Method: CommandSetShowDisplayCutout} -// WithDisplayCutoutConfig display cutout data, null means hide display -// cutout. -func (p SetShowDisplayCutoutParams) WithDisplayCutoutConfig(displayCutoutConfig *DisplayCutoutConfig) *SetShowDisplayCutoutParams { - p.DisplayCutoutConfig = displayCutoutConfig - return &p -} - -// Do executes Overlay.setShowDisplayCutout against the provided context. -func (p *SetShowDisplayCutoutParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetShowDisplayCutout, p, nil) -} - -// SetShowIsolatedElementsParams show elements in isolation mode with -// overlays. +// SetShowIsolatedElementsParams are the parameters of the command +// Overlay.setShowIsolatedElements. type SetShowIsolatedElementsParams struct { IsolatedElementHighlightConfigs []*IsolatedElementHighlightConfig `json:"isolatedElementHighlightConfigs"` // An array of node identifiers and descriptors for the highlight appearance. } @@ -811,22 +341,10 @@ type SetShowIsolatedElementsParams struct { // SetShowIsolatedElements show elements in isolation mode with overlays. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowIsolatedElements -// -// parameters: -// -// isolatedElementHighlightConfigs - An array of node identifiers and descriptors for the highlight appearance. -func SetShowIsolatedElements(isolatedElementHighlightConfigs []*IsolatedElementHighlightConfig) *SetShowIsolatedElementsParams { - return &SetShowIsolatedElementsParams{ - IsolatedElementHighlightConfigs: isolatedElementHighlightConfigs, - } -} - -// Do executes Overlay.setShowIsolatedElements against the provided context. -func (p *SetShowIsolatedElementsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetShowIsolatedElements, p, nil) -} +var SetShowIsolatedElements = cdp.Command[SetShowIsolatedElementsParams, cdp.Empty]{Method: CommandSetShowIsolatedElements} -// SetShowWindowControlsOverlayParams show Window Controls Overlay for PWA. +// SetShowWindowControlsOverlayParams are the parameters of the command +// Overlay.setShowWindowControlsOverlay. type SetShowWindowControlsOverlayParams struct { WindowControlsOverlayConfig *WindowControlsOverlayConfig `json:"windowControlsOverlayConfig,omitempty,omitzero"` // Window Controls Overlay data, null means hide Window Controls Overlay } @@ -834,23 +352,41 @@ type SetShowWindowControlsOverlayParams struct { // SetShowWindowControlsOverlay show Window Controls Overlay for PWA. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowWindowControlsOverlay +var SetShowWindowControlsOverlay = cdp.Command[SetShowWindowControlsOverlayParams, cdp.Empty]{Method: CommandSetShowWindowControlsOverlay} + +// InspectNodeRequested fired when the node should be inspected. This happens +// after call to setInspectMode or when user manually inspects an element. // -// parameters: -func SetShowWindowControlsOverlay() *SetShowWindowControlsOverlayParams { - return &SetShowWindowControlsOverlayParams{} -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#event-inspectNodeRequested +var InspectNodeRequested = cdp.Event[EventInspectNodeRequested]{Method: "Overlay.inspectNodeRequested"} -// WithWindowControlsOverlayConfig window Controls Overlay data, null means -// hide Window Controls Overlay. -func (p SetShowWindowControlsOverlayParams) WithWindowControlsOverlayConfig(windowControlsOverlayConfig *WindowControlsOverlayConfig) *SetShowWindowControlsOverlayParams { - p.WindowControlsOverlayConfig = windowControlsOverlayConfig - return &p -} +// NodeHighlightRequested fired when the node should be highlighted. This +// happens after call to setInspectMode. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#event-nodeHighlightRequested +var NodeHighlightRequested = cdp.Event[EventNodeHighlightRequested]{Method: "Overlay.nodeHighlightRequested"} -// Do executes Overlay.setShowWindowControlsOverlay against the provided context. -func (p *SetShowWindowControlsOverlayParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetShowWindowControlsOverlay, p, nil) -} +// ScreenshotRequested fired when user asks to capture screenshot of some +// area on the page. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#event-screenshotRequested +var ScreenshotRequested = cdp.Event[EventScreenshotRequested]{Method: "Overlay.screenshotRequested"} + +// InspectPanelShowRequested fired when user asks to show the Inspect panel. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#event-inspectPanelShowRequested +var InspectPanelShowRequested = cdp.Event[EventInspectPanelShowRequested]{Method: "Overlay.inspectPanelShowRequested"} + +// InspectedElementWindowRestored fired when user asks to restore the +// Inspected Element floating window. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#event-inspectedElementWindowRestored +var InspectedElementWindowRestored = cdp.Event[EventInspectedElementWindowRestored]{Method: "Overlay.inspectedElementWindowRestored"} + +// InspectModeCanceled fired when user cancels the inspect mode. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#event-inspectModeCanceled +var InspectModeCanceled = cdp.Event[EventInspectModeCanceled]{Method: "Overlay.inspectModeCanceled"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/overlay/types.go b/vendor/github.com/chromedp/cdproto/overlay/types.go index 4749dae45..81cc06625 100644 --- a/vendor/github.com/chromedp/cdproto/overlay/types.go +++ b/vendor/github.com/chromedp/cdproto/overlay/types.go @@ -1,11 +1,8 @@ -package overlay +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package overlay import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/dom" ) @@ -102,22 +99,20 @@ const ( ContrastAlgorithmApca ContrastAlgorithm = "apca" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ContrastAlgorithm) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ContrastAlgorithm(s) { - case ContrastAlgorithmAa: - *t = ContrastAlgorithmAa - case ContrastAlgorithmAaa: - *t = ContrastAlgorithmAaa - case ContrastAlgorithmApca: - *t = ContrastAlgorithmApca - default: - return fmt.Errorf("unknown ContrastAlgorithm value: %v", s) - } - return nil +// ImcbHighlightConfig configuration for Inset-Modified Containing Block +// (IMCB) and CSS Anchor Positioning highlight. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#type-ImcbHighlightConfig +type ImcbHighlightConfig struct { + ImcbBorderColor *cdp.RGBA `json:"imcbBorderColor,omitempty,omitzero"` // Border color for the Inset-Modified Containing Block (default: transparent). + ImcbBackgroundColor *cdp.RGBA `json:"imcbBackgroundColor,omitempty,omitzero"` // Background fill color for the Inset-Modified Containing Block (default: transparent). + InsetsBackgroundColor *cdp.RGBA `json:"insetsBackgroundColor,omitempty,omitzero"` // Fill color for the inset modifiers area (difference between CB and IMCB). + InsetsHatchColor *cdp.RGBA `json:"insetsHatchColor,omitempty,omitzero"` // Hatch color for the inset modifiers area. + AnchorBorderColor *cdp.RGBA `json:"anchorBorderColor,omitempty,omitzero"` // Border color for the referenced target anchor element(s) (when element is anchor-positioned). + AnchorBackgroundColor *cdp.RGBA `json:"anchorBackgroundColor,omitempty,omitzero"` // Background fill color for the referenced target anchor element(s) (when element is anchor-positioned). + ShowPositionAreaGrid bool `json:"showPositionAreaGrid"` // Whether to render the 3x3 position-area grid lines when position-area is used. + PositionAreaGridLineColor *cdp.RGBA `json:"positionAreaGridLineColor,omitempty,omitzero"` // Line color for the 3x3 position-area grid lines. + PositionAreaActiveRegionColor *cdp.RGBA `json:"positionAreaActiveRegionColor,omitempty,omitzero"` // Fill color for the active region within the position-area grid. } // HighlightConfig configuration data for the highlighting of page elements. @@ -143,6 +138,7 @@ type HighlightConfig struct { FlexItemHighlightConfig *FlexItemHighlightConfig `json:"flexItemHighlightConfig,omitempty,omitzero"` // The flex item highlight configuration (default: all transparent). ContrastAlgorithm ContrastAlgorithm `json:"contrastAlgorithm,omitempty,omitzero"` // The contrast algorithm to use for the contrast ratio (default: aa). ContainerQueryContainerHighlightConfig *ContainerQueryContainerHighlightConfig `json:"containerQueryContainerHighlightConfig,omitempty,omitzero"` // The container query container highlight configuration (default: all transparent). + ImcbHighlightConfig *ImcbHighlightConfig `json:"imcbHighlightConfig,omitempty,omitzero"` // The IMCB highlight configuration (default: all transparent). } // ColorFormat [no description]. @@ -163,26 +159,6 @@ const ( ColorFormatHex ColorFormat = "hex" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ColorFormat) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ColorFormat(s) { - case ColorFormatRgb: - *t = ColorFormatRgb - case ColorFormatHsl: - *t = ColorFormatHsl - case ColorFormatHwb: - *t = ColorFormatHwb - case ColorFormatHex: - *t = ColorFormatHex - default: - return fmt.Errorf("unknown ColorFormat value: %v", s) - } - return nil -} - // GridNodeHighlightConfig configurations for Persistent Grid Highlight. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#type-GridNodeHighlightConfig @@ -244,26 +220,6 @@ const ( DisplayCutoutShapeRectangle DisplayCutoutShape = "rectangle" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DisplayCutoutShape) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DisplayCutoutShape(s) { - case DisplayCutoutShapePill: - *t = DisplayCutoutShapePill - case DisplayCutoutShapeNotch: - *t = DisplayCutoutShapeNotch - case DisplayCutoutShapeCircle: - *t = DisplayCutoutShapeCircle - case DisplayCutoutShapeRectangle: - *t = DisplayCutoutShapeRectangle - default: - return fmt.Errorf("unknown DisplayCutoutShape value: %v", s) - } - return nil -} - // DisplayCutoutConfig configuration for a display cutout. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#type-DisplayCutoutConfig @@ -273,8 +229,8 @@ type DisplayCutoutConfig struct { BorderRadius int64 `json:"borderRadius,omitempty,omitzero"` // Border radius for rounded cutout shapes. UpperRadius int64 `json:"upperRadius,omitempty,omitzero"` // Upper shoulder radius for notch cutout shapes. LowerRadius int64 `json:"lowerRadius,omitempty,omitzero"` // Lower transition radius for notch cutout shapes. - Cx int64 `json:"cx,omitempty,omitzero"` // Center x coordinate for circle cutout shapes. - Cy int64 `json:"cy,omitempty,omitzero"` // Center y coordinate for circle cutout shapes. + Cx *int64 `json:"cx,omitempty,omitzero"` // Center x coordinate for circle cutout shapes. + Cy *int64 `json:"cy,omitempty,omitzero"` // Center y coordinate for circle cutout shapes. Radius int64 `json:"radius,omitempty,omitzero"` // Radius for circle cutout shapes. ContentColor *cdp.RGBA `json:"contentColor,omitempty,omitzero"` // The cutout fill color (default: black). } @@ -339,26 +295,6 @@ const ( InspectModeNone InspectMode = "none" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *InspectMode) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch InspectMode(s) { - case InspectModeSearchForNode: - *t = InspectModeSearchForNode - case InspectModeSearchForUAShadowDOM: - *t = InspectModeSearchForUAShadowDOM - case InspectModeCaptureAreaScreenshot: - *t = InspectModeCaptureAreaScreenshot - case InspectModeNone: - *t = InspectModeNone - default: - return fmt.Errorf("unknown InspectMode value: %v", s) - } - return nil -} - // InspectedElementAnchorConfig [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#type-InspectedElementAnchorConfig @@ -382,19 +318,3 @@ const ( LineStylePatternDashed LineStylePattern = "dashed" LineStylePatternDotted LineStylePattern = "dotted" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *LineStylePattern) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch LineStylePattern(s) { - case LineStylePatternDashed: - *t = LineStylePatternDashed - case LineStylePatternDotted: - *t = LineStylePatternDotted - default: - return fmt.Errorf("unknown LineStylePattern value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/page/events.go b/vendor/github.com/chromedp/cdproto/page/events.go index 19944838a..91e302e5d 100644 --- a/vendor/github.com/chromedp/cdproto/page/events.go +++ b/vendor/github.com/chromedp/cdproto/page/events.go @@ -1,6 +1,6 @@ -package page +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package page import ( "github.com/chromedp/cdproto/cdp" @@ -11,7 +11,7 @@ import ( // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-domContentEventFired type EventDomContentEventFired struct { - Timestamp *cdp.MonotonicTime `json:"timestamp"` + Timestamp cdp.MonotonicTime `json:"timestamp"` } // EventFileChooserOpened emitted only when page.interceptFileChooser is @@ -149,10 +149,10 @@ type EventJavascriptDialogOpening struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-lifecycleEvent type EventLifecycleEvent struct { - FrameID cdp.FrameID `json:"frameId"` // Id of the frame. - LoaderID cdp.LoaderID `json:"loaderId"` // Loader identifier. Empty string if the request is fetched from worker. - Name string `json:"name"` - Timestamp *cdp.MonotonicTime `json:"timestamp"` + FrameID cdp.FrameID `json:"frameId"` // Id of the frame. + LoaderID cdp.LoaderID `json:"loaderId"` // Loader identifier. Empty string if the request is fetched from worker. + Name string `json:"name"` + Timestamp cdp.MonotonicTime `json:"timestamp"` } // EventBackForwardCacheNotUsed fired for failed bfcache history navigations @@ -173,7 +173,7 @@ type EventBackForwardCacheNotUsed struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-loadEventFired type EventLoadEventFired struct { - Timestamp *cdp.MonotonicTime `json:"timestamp"` + Timestamp cdp.MonotonicTime `json:"timestamp"` } // EventNavigatedWithinDocument fired when same-document navigation happens, @@ -191,7 +191,7 @@ type EventNavigatedWithinDocument struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-screencastFrame type EventScreencastFrame struct { - Data string `json:"data"` // Base64-encoded compressed image. + Data []byte `json:"data"` // Base64-encoded compressed image. Metadata *ScreencastFrameMetadata `json:"metadata"` // Screencast frame metadata. SessionID int64 `json:"sessionId"` // Frame number. } @@ -221,5 +221,5 @@ type EventWindowOpen struct { // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-compilationCacheProduced type EventCompilationCacheProduced struct { URL string `json:"url"` - Data string `json:"data"` // Base64-encoded data + Data []byte `json:"data"` // Base64-encoded data } diff --git a/vendor/github.com/chromedp/cdproto/page/page.go b/vendor/github.com/chromedp/cdproto/page/page.go index db6da1d6f..7dac95ce4 100644 --- a/vendor/github.com/chromedp/cdproto/page/page.go +++ b/vendor/github.com/chromedp/cdproto/page/page.go @@ -1,722 +1,329 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package page provides the Chrome DevTools Protocol // commands, types, and events for the Page domain. // // Actions and events related to the inspected page belong to the page // domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package page -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" "encoding/base64" + "fmt" "github.com/chromedp/cdproto/cdp" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" "github.com/chromedp/cdproto/debugger" "github.com/chromedp/cdproto/dom" "github.com/chromedp/cdproto/io" "github.com/chromedp/cdproto/runtime" ) -// AddScriptToEvaluateOnNewDocumentParams evaluates given script in every -// frame upon creation (before loading frame's scripts). +// AddScriptToEvaluateOnNewDocumentParams are the parameters of the command +// Page.addScriptToEvaluateOnNewDocument. type AddScriptToEvaluateOnNewDocumentParams struct { Source string `json:"source"` - WorldName string `json:"worldName,omitempty,omitzero"` // If specified, creates an isolated world with the given name and evaluates given script in it. This world name will be used as the ExecutionContextDescription::name when the corresponding event is emitted. - IncludeCommandLineAPI bool `json:"includeCommandLineAPI"` // Specifies whether command line API should be available to the script, defaults to false. - RunImmediately bool `json:"runImmediately"` // If true, runs the script immediately on existing execution contexts or worlds. Default: false. + WorldName string `json:"worldName,omitempty,omitzero"` // If specified, creates an isolated world with the given name and evaluates given script in it. This world name will be used as the ExecutionContextDescription::name when the corresponding event is emitted. + IncludeCommandLineAPI *bool `json:"includeCommandLineAPI,omitempty,omitzero"` // Specifies whether command line API should be available to the script, defaults to false. + RunImmediately *bool `json:"runImmediately,omitempty,omitzero"` // If true, runs the script immediately on existing execution contexts or worlds. Default: false. } -// AddScriptToEvaluateOnNewDocument evaluates given script in every frame -// upon creation (before loading frame's scripts). -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-addScriptToEvaluateOnNewDocument -// -// parameters: -// -// source -func AddScriptToEvaluateOnNewDocument(source string) *AddScriptToEvaluateOnNewDocumentParams { - return &AddScriptToEvaluateOnNewDocumentParams{ - Source: source, - IncludeCommandLineAPI: false, - RunImmediately: false, - } -} - -// WithWorldName if specified, creates an isolated world with the given name -// and evaluates given script in it. This world name will be used as the -// ExecutionContextDescription::name when the corresponding event is emitted. -func (p AddScriptToEvaluateOnNewDocumentParams) WithWorldName(worldName string) *AddScriptToEvaluateOnNewDocumentParams { - p.WorldName = worldName - return &p -} - -// WithIncludeCommandLineAPI specifies whether command line API should be -// available to the script, defaults to false. -func (p AddScriptToEvaluateOnNewDocumentParams) WithIncludeCommandLineAPI(includeCommandLineAPI bool) *AddScriptToEvaluateOnNewDocumentParams { - p.IncludeCommandLineAPI = includeCommandLineAPI - return &p -} - -// WithRunImmediately if true, runs the script immediately on existing -// execution contexts or worlds. Default: false. -func (p AddScriptToEvaluateOnNewDocumentParams) WithRunImmediately(runImmediately bool) *AddScriptToEvaluateOnNewDocumentParams { - p.RunImmediately = runImmediately - return &p -} - -// AddScriptToEvaluateOnNewDocumentReturns return values. -type AddScriptToEvaluateOnNewDocumentReturns struct { +// AddScriptToEvaluateOnNewDocumentResult is the result of the command +// Page.addScriptToEvaluateOnNewDocument. +type AddScriptToEvaluateOnNewDocumentResult struct { Identifier ScriptIdentifier `json:"identifier,omitempty,omitzero"` // Identifier of the added script. } -// Do executes Page.addScriptToEvaluateOnNewDocument against the provided context. -// -// returns: +// AddScriptToEvaluateOnNewDocument evaluates given script in every frame +// upon creation (before loading frame's scripts). // -// identifier - Identifier of the added script. -func (p *AddScriptToEvaluateOnNewDocumentParams) Do(ctx context.Context) (identifier ScriptIdentifier, err error) { - // execute - var res AddScriptToEvaluateOnNewDocumentReturns - err = cdp.Execute(ctx, CommandAddScriptToEvaluateOnNewDocument, p, &res) - if err != nil { - return "", err - } - - return res.Identifier, nil -} - -// BringToFrontParams brings page to front (activates tab). -type BringToFrontParams struct{} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-addScriptToEvaluateOnNewDocument +var AddScriptToEvaluateOnNewDocument = cdp.Command[AddScriptToEvaluateOnNewDocumentParams, AddScriptToEvaluateOnNewDocumentResult]{Method: CommandAddScriptToEvaluateOnNewDocument} // BringToFront brings page to front (activates tab). // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-bringToFront -func BringToFront() *BringToFrontParams { - return &BringToFrontParams{} -} +var BringToFront = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandBringToFront} -// Do executes Page.bringToFront against the provided context. -func (p *BringToFrontParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandBringToFront, nil, nil) +// CaptureScreenshotParams are the parameters of the command +// Page.captureScreenshot. +type CaptureScreenshotParams struct { + Format CaptureScreenshotFormat `json:"format,omitempty,omitzero"` // Image compression format (defaults to png). + Quality *int64 `json:"quality,omitempty,omitzero"` // Compression quality from range [0..100] (jpeg only). + Clip *Viewport `json:"clip,omitempty,omitzero"` // Capture the screenshot of a given region only. + FromSurface *bool `json:"fromSurface,omitempty,omitzero"` // Capture the screenshot from the surface, rather than the view. Defaults to true. + CaptureBeyondViewport *bool `json:"captureBeyondViewport,omitempty,omitzero"` // Capture the screenshot beyond the viewport. Defaults to false. + OptimizeForSpeed *bool `json:"optimizeForSpeed,omitempty,omitzero"` // Optimize image encoding for speed, not for resulting size (defaults to false) } -// CaptureScreenshotParams capture page screenshot. -type CaptureScreenshotParams struct { - Format CaptureScreenshotFormat `json:"format,omitempty,omitzero"` // Image compression format (defaults to png). - Quality int64 `json:"quality,omitempty,omitzero"` // Compression quality from range [0..100] (jpeg only). - Clip *Viewport `json:"clip,omitempty,omitzero"` // Capture the screenshot of a given region only. - FromSurface bool `json:"fromSurface"` // Capture the screenshot from the surface, rather than the view. Defaults to true. - CaptureBeyondViewport bool `json:"captureBeyondViewport"` // Capture the screenshot beyond the viewport. Defaults to false. - OptimizeForSpeed bool `json:"optimizeForSpeed"` // Optimize image encoding for speed, not for resulting size (defaults to false) +// CaptureScreenshotResult is the result of the command +// Page.captureScreenshot. +type CaptureScreenshotResult struct { + Data []byte `json:"data,omitempty,omitzero"` // Base64-encoded image data. } // CaptureScreenshot capture page screenshot. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-captureScreenshot -// -// parameters: -func CaptureScreenshot() *CaptureScreenshotParams { - return &CaptureScreenshotParams{ - FromSurface: true, - CaptureBeyondViewport: false, - OptimizeForSpeed: false, - } -} - -// WithFormat image compression format (defaults to png). -func (p CaptureScreenshotParams) WithFormat(format CaptureScreenshotFormat) *CaptureScreenshotParams { - p.Format = format - return &p -} - -// WithQuality compression quality from range [0..100] (jpeg only). -func (p CaptureScreenshotParams) WithQuality(quality int64) *CaptureScreenshotParams { - p.Quality = quality - return &p -} - -// WithClip capture the screenshot of a given region only. -func (p CaptureScreenshotParams) WithClip(clip *Viewport) *CaptureScreenshotParams { - p.Clip = clip - return &p -} +var CaptureScreenshot = cdp.Command[CaptureScreenshotParams, CaptureScreenshotResult]{Method: CommandCaptureScreenshot} -// WithFromSurface capture the screenshot from the surface, rather than the -// view. Defaults to true. -func (p CaptureScreenshotParams) WithFromSurface(fromSurface bool) *CaptureScreenshotParams { - p.FromSurface = fromSurface - return &p -} - -// WithCaptureBeyondViewport capture the screenshot beyond the viewport. -// Defaults to false. -func (p CaptureScreenshotParams) WithCaptureBeyondViewport(captureBeyondViewport bool) *CaptureScreenshotParams { - p.CaptureBeyondViewport = captureBeyondViewport - return &p -} - -// WithOptimizeForSpeed optimize image encoding for speed, not for resulting -// size (defaults to false). -func (p CaptureScreenshotParams) WithOptimizeForSpeed(optimizeForSpeed bool) *CaptureScreenshotParams { - p.OptimizeForSpeed = optimizeForSpeed - return &p -} - -// CaptureScreenshotReturns return values. -type CaptureScreenshotReturns struct { - Data string `json:"data,omitempty,omitzero"` // Base64-encoded image data. -} - -// Do executes Page.captureScreenshot against the provided context. -// -// returns: -// -// data - Base64-encoded image data. -func (p *CaptureScreenshotParams) Do(ctx context.Context) (data []byte, err error) { - // execute - var res CaptureScreenshotReturns - err = cdp.Execute(ctx, CommandCaptureScreenshot, p, &res) - if err != nil { - return nil, err - } - - // decode - var dec []byte - dec, err = base64.StdEncoding.DecodeString(res.Data) - if err != nil { - return nil, err - } - return dec, nil -} - -// CaptureSnapshotParams returns a snapshot of the page as a string. For -// MHTML format, the serialization includes iframes, shadow DOM, external -// resources, and element-inline styles. +// CaptureSnapshotParams are the parameters of the command +// Page.captureSnapshot. type CaptureSnapshotParams struct { Format CaptureSnapshotFormat `json:"format,omitempty,omitzero"` // Format (defaults to mhtml). } +// CaptureSnapshotResult is the result of the command Page.captureSnapshot. +type CaptureSnapshotResult struct { + Data string `json:"data,omitempty,omitzero"` // Serialized page data. +} + // CaptureSnapshot returns a snapshot of the page as a string. For MHTML // format, the serialization includes iframes, shadow DOM, external resources, // and element-inline styles. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-captureSnapshot -// -// parameters: -func CaptureSnapshot() *CaptureSnapshotParams { - return &CaptureSnapshotParams{} -} - -// WithFormat format (defaults to mhtml). -func (p CaptureSnapshotParams) WithFormat(format CaptureSnapshotFormat) *CaptureSnapshotParams { - p.Format = format - return &p -} - -// CaptureSnapshotReturns return values. -type CaptureSnapshotReturns struct { - Data string `json:"data,omitempty,omitzero"` // Serialized page data. -} - -// Do executes Page.captureSnapshot against the provided context. -// -// returns: -// -// data - Serialized page data. -func (p *CaptureSnapshotParams) Do(ctx context.Context) (data string, err error) { - // execute - var res CaptureSnapshotReturns - err = cdp.Execute(ctx, CommandCaptureSnapshot, p, &res) - if err != nil { - return "", err - } +var CaptureSnapshot = cdp.Command[CaptureSnapshotParams, CaptureSnapshotResult]{Method: CommandCaptureSnapshot} - return res.Data, nil -} - -// CreateIsolatedWorldParams creates an isolated world for the given frame. +// CreateIsolatedWorldParams are the parameters of the command +// Page.createIsolatedWorld. type CreateIsolatedWorldParams struct { FrameID cdp.FrameID `json:"frameId"` // Id of the frame in which the isolated world should be created. WorldName string `json:"worldName,omitempty,omitzero"` // An optional name which is reported in the Execution Context. - GrantUniveralAccess bool `json:"grantUniveralAccess"` // Whether or not universal access should be granted to the isolated world. This is a powerful option, use with caution. + GrantUniveralAccess *bool `json:"grantUniveralAccess,omitempty,omitzero"` // Whether or not universal access should be granted to the isolated world. This is a powerful option, use with caution. ContentSecurityPolicy string `json:"contentSecurityPolicy,omitempty,omitzero"` // An optional content security policy to set for the isolated world. If omitted, any existing CSP for the world will be cleared. Note that clearing or updating the CSP does not immediately affect the active context in the same document because LocalDOMWindow caches the ContentSecurityPolicy object. The change takes effect on subsequent navigations when a new window context is created. } -// CreateIsolatedWorld creates an isolated world for the given frame. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-createIsolatedWorld -// -// parameters: -// -// frameID - Id of the frame in which the isolated world should be created. -func CreateIsolatedWorld(frameID cdp.FrameID) *CreateIsolatedWorldParams { - return &CreateIsolatedWorldParams{ - FrameID: frameID, - GrantUniveralAccess: false, - } -} - -// WithWorldName an optional name which is reported in the Execution Context. -func (p CreateIsolatedWorldParams) WithWorldName(worldName string) *CreateIsolatedWorldParams { - p.WorldName = worldName - return &p -} - -// WithGrantUniveralAccess whether or not universal access should be granted -// to the isolated world. This is a powerful option, use with caution. -func (p CreateIsolatedWorldParams) WithGrantUniveralAccess(grantUniveralAccess bool) *CreateIsolatedWorldParams { - p.GrantUniveralAccess = grantUniveralAccess - return &p -} - -// WithContentSecurityPolicy an optional content security policy to set for -// the isolated world. If omitted, any existing CSP for the world will be -// cleared. Note that clearing or updating the CSP does not immediately affect -// the active context in the same document because LocalDOMWindow caches the -// ContentSecurityPolicy object. The change takes effect on subsequent -// navigations when a new window context is created. -func (p CreateIsolatedWorldParams) WithContentSecurityPolicy(contentSecurityPolicy string) *CreateIsolatedWorldParams { - p.ContentSecurityPolicy = contentSecurityPolicy - return &p -} - -// CreateIsolatedWorldReturns return values. -type CreateIsolatedWorldReturns struct { +// CreateIsolatedWorldResult is the result of the command +// Page.createIsolatedWorld. +type CreateIsolatedWorldResult struct { ExecutionContextID runtime.ExecutionContextID `json:"executionContextId,omitempty,omitzero"` // Execution context of the isolated world. } -// Do executes Page.createIsolatedWorld against the provided context. -// -// returns: +// CreateIsolatedWorld creates an isolated world for the given frame. // -// executionContextID - Execution context of the isolated world. -func (p *CreateIsolatedWorldParams) Do(ctx context.Context) (executionContextID runtime.ExecutionContextID, err error) { - // execute - var res CreateIsolatedWorldReturns - err = cdp.Execute(ctx, CommandCreateIsolatedWorld, p, &res) - if err != nil { - return 0, err - } - - return res.ExecutionContextID, nil -} - -// DisableParams disables page domain notifications. -type DisableParams struct{} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-createIsolatedWorld +var CreateIsolatedWorld = cdp.Command[CreateIsolatedWorldParams, CreateIsolatedWorldResult]{Method: CommandCreateIsolatedWorld} // Disable disables page domain notifications. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes Page.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} -// EnableParams enables page domain notifications. +// EnableParams are the parameters of the command Page.enable. type EnableParams struct { - EnableFileChooserOpenedEvent bool `json:"enableFileChooserOpenedEvent"` // If true, the Page.fileChooserOpened event will be emitted regardless of the state set by Page.setInterceptFileChooserDialog command (default: false). + EnableFileChooserOpenedEvent *bool `json:"enableFileChooserOpenedEvent,omitempty,omitzero"` // If true, the Page.fileChooserOpened event will be emitted regardless of the state set by Page.setInterceptFileChooserDialog command (default: false). } // Enable enables page domain notifications. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-enable -// -// parameters: -func Enable() *EnableParams { - return &EnableParams{ - EnableFileChooserOpenedEvent: false, - } -} +var Enable = cdp.Command[EnableParams, cdp.Empty]{Method: CommandEnable} -// WithEnableFileChooserOpenedEvent if true, the Page.fileChooserOpened event -// will be emitted regardless of the state set by -// Page.setInterceptFileChooserDialog command (default: false). -func (p EnableParams) WithEnableFileChooserOpenedEvent(enableFileChooserOpenedEvent bool) *EnableParams { - p.EnableFileChooserOpenedEvent = enableFileChooserOpenedEvent - return &p -} - -// Do executes Page.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, p, nil) -} - -// GetAppManifestParams gets the processed manifest for this current -// document. This API always waits for the manifest to be loaded. If manifestId -// is provided, and it does not match the manifest of the current document, this -// API errors out. If there is not a loaded page, this API errors out -// immediately. +// GetAppManifestParams are the parameters of the command +// Page.getAppManifest. type GetAppManifestParams struct { ManifestID string `json:"manifestId,omitempty,omitzero"` } -// GetAppManifest gets the processed manifest for this current document. This -// API always waits for the manifest to be loaded. If manifestId is provided, -// and it does not match the manifest of the current document, this API errors -// out. If there is not a loaded page, this API errors out immediately. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getAppManifest -// -// parameters: -func GetAppManifest() *GetAppManifestParams { - return &GetAppManifestParams{} -} - -// WithManifestID [no description]. -func (p GetAppManifestParams) WithManifestID(manifestID string) *GetAppManifestParams { - p.ManifestID = manifestID - return &p -} - -// GetAppManifestReturns return values. -type GetAppManifestReturns struct { +// GetAppManifestResult is the result of the command Page.getAppManifest. +type GetAppManifestResult struct { URL string `json:"url,omitempty,omitzero"` // Manifest location. Errors []*AppManifestError `json:"errors,omitempty,omitzero"` Data string `json:"data,omitempty,omitzero"` // Manifest content. Manifest *WebAppManifest `json:"manifest,omitempty,omitzero"` } -// Do executes Page.getAppManifest against the provided context. -// -// returns: +// GetAppManifest gets the processed manifest for this current document. This +// API always waits for the manifest to be loaded. If manifestId is provided, +// and it does not match the manifest of the current document, this API errors +// out. If there is not a loaded page, this API errors out immediately. // -// url - Manifest location. -// errors -// data - Manifest content. -// manifest -func (p *GetAppManifestParams) Do(ctx context.Context) (url string, errors []*AppManifestError, data string, manifest *WebAppManifest, err error) { - // execute - var res GetAppManifestReturns - err = cdp.Execute(ctx, CommandGetAppManifest, p, &res) - if err != nil { - return "", nil, "", nil, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getAppManifest +var GetAppManifest = cdp.Command[GetAppManifestParams, GetAppManifestResult]{Method: CommandGetAppManifest} - return res.URL, res.Errors, res.Data, res.Manifest, nil +// GetInstallabilityErrorsResult is the result of the command +// Page.getInstallabilityErrors. +type GetInstallabilityErrorsResult struct { + InstallabilityErrors []*InstallabilityError `json:"installabilityErrors,omitempty,omitzero"` } -// GetInstallabilityErrorsParams [no description]. -type GetInstallabilityErrorsParams struct{} - // GetInstallabilityErrors [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getInstallabilityErrors -func GetInstallabilityErrors() *GetInstallabilityErrorsParams { - return &GetInstallabilityErrorsParams{} -} +var GetInstallabilityErrors = cdp.Command[cdp.Empty, GetInstallabilityErrorsResult]{Method: CommandGetInstallabilityErrors} -// GetInstallabilityErrorsReturns return values. -type GetInstallabilityErrorsReturns struct { - InstallabilityErrors []*InstallabilityError `json:"installabilityErrors,omitempty,omitzero"` +// GetAppIDResult is the result of the command Page.getAppId. +type GetAppIDResult struct { + AppID string `json:"appId,omitempty,omitzero"` // App id, either from manifest's id attribute or computed from start_url + RecommendedID string `json:"recommendedId,omitempty,omitzero"` // Recommendation for manifest's id attribute to match current id computed from start_url + BundleID string `json:"bundleId,omitempty,omitzero"` // The bundle ID for an Isolated Web App (IWA) + ParentAppName string `json:"parentAppName,omitempty,omitzero"` // The name of the parent app if this app is a Sub-App } -// Do executes Page.getInstallabilityErrors against the provided context. +// GetAppID returns the unique (PWA) app id, along with IWA bundle ID and +// parent app info. Only returns values if the feature flag +// 'WebAppEnableManifestId' is enabled. // -// returns: -// -// installabilityErrors -func (p *GetInstallabilityErrorsParams) Do(ctx context.Context) (installabilityErrors []*InstallabilityError, err error) { - // execute - var res GetInstallabilityErrorsReturns - err = cdp.Execute(ctx, CommandGetInstallabilityErrors, nil, &res) - if err != nil { - return nil, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getAppId +var GetAppID = cdp.Command[cdp.Empty, GetAppIDResult]{Method: CommandGetAppID} - return res.InstallabilityErrors, nil +// GetSubAppsResult is the result of the command Page.getSubApps. +type GetSubAppsResult struct { + SubApps []*SubApp `json:"subApps,omitempty,omitzero"` } -// GetAppIDParams returns the unique (PWA) app id. Only returns values if the -// feature flag 'WebAppEnableManifestId' is enabled. -type GetAppIDParams struct{} - -// GetAppID returns the unique (PWA) app id. Only returns values if the -// feature flag 'WebAppEnableManifestId' is enabled. +// GetSubApps returns the list of installed child Sub-Apps for the inspected +// parent app. // -// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getAppId -func GetAppID() *GetAppIDParams { - return &GetAppIDParams{} -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getSubApps +var GetSubApps = cdp.Command[cdp.Empty, GetSubAppsResult]{Method: CommandGetSubApps} -// GetAppIDReturns return values. -type GetAppIDReturns struct { - AppID string `json:"appId,omitempty,omitzero"` // App id, either from manifest's id attribute or computed from start_url - RecommendedID string `json:"recommendedId,omitempty,omitzero"` // Recommendation for manifest's id attribute to match current id computed from start_url +// GetSiblingSubAppsResult is the result of the command +// Page.getSiblingSubApps. +type GetSiblingSubAppsResult struct { + SubApps []*SubApp `json:"subApps,omitempty,omitzero"` } -// Do executes Page.getAppId against the provided context. -// -// returns: +// GetSiblingSubApps returns the list of sibling Sub-Apps sharing the same +// parent app if the inspected context is a Sub-App. // -// appID - App id, either from manifest's id attribute or computed from start_url -// recommendedID - Recommendation for manifest's id attribute to match current id computed from start_url -func (p *GetAppIDParams) Do(ctx context.Context) (appID string, recommendedID string, err error) { - // execute - var res GetAppIDReturns - err = cdp.Execute(ctx, CommandGetAppID, nil, &res) - if err != nil { - return "", "", err - } - - return res.AppID, res.RecommendedID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getSiblingSubApps +var GetSiblingSubApps = cdp.Command[cdp.Empty, GetSiblingSubAppsResult]{Method: CommandGetSiblingSubApps} -// GetAdScriptAncestryParams [no description]. +// GetAdScriptAncestryParams are the parameters of the command +// Page.getAdScriptAncestry. type GetAdScriptAncestryParams struct { FrameID cdp.FrameID `json:"frameId"` } -// GetAdScriptAncestry [no description]. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getAdScriptAncestry -// -// parameters: -// -// frameID -func GetAdScriptAncestry(frameID cdp.FrameID) *GetAdScriptAncestryParams { - return &GetAdScriptAncestryParams{ - FrameID: frameID, - } -} - -// GetAdScriptAncestryReturns return values. -type GetAdScriptAncestryReturns struct { +// GetAdScriptAncestryResult is the result of the command +// Page.getAdScriptAncestry. +type GetAdScriptAncestryResult struct { AdScriptAncestry *cdp.AdAncestry `json:"adScriptAncestry,omitempty,omitzero"` // The ancestry chain of ad script identifiers leading to this frame's creation, along with the root script's filterlist rule. The ancestry chain is ordered from the most immediate script (in the frame creation stack) to more distant ancestors (that created the immediately preceding script). Only sent if frame is labelled as an ad and ids are available. } -// Do executes Page.getAdScriptAncestry against the provided context. -// -// returns: +// GetAdScriptAncestry [no description]. // -// adScriptAncestry - The ancestry chain of ad script identifiers leading to this frame's creation, along with the root script's filterlist rule. The ancestry chain is ordered from the most immediate script (in the frame creation stack) to more distant ancestors (that created the immediately preceding script). Only sent if frame is labelled as an ad and ids are available. -func (p *GetAdScriptAncestryParams) Do(ctx context.Context) (adScriptAncestry *cdp.AdAncestry, err error) { - // execute - var res GetAdScriptAncestryReturns - err = cdp.Execute(ctx, CommandGetAdScriptAncestry, p, &res) - if err != nil { - return nil, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getAdScriptAncestry +var GetAdScriptAncestry = cdp.Command[GetAdScriptAncestryParams, GetAdScriptAncestryResult]{Method: CommandGetAdScriptAncestry} - return res.AdScriptAncestry, nil +// GetSpellCheckCustomDictionaryParams are the parameters of the command +// Page.getSpellCheckCustomDictionary. +type GetSpellCheckCustomDictionaryParams struct { + FrameID cdp.FrameID `json:"frameId"` } -// GetFrameTreeParams returns present frame tree structure. -type GetFrameTreeParams struct{} +// GetSpellCheckCustomDictionaryResult is the result of the command +// Page.getSpellCheckCustomDictionary. +type GetSpellCheckCustomDictionaryResult struct { + Words []string `json:"words,omitempty,omitzero"` +} -// GetFrameTree returns present frame tree structure. +// GetSpellCheckCustomDictionary returns the words that the frame's document +// added to its spell check custom dictionary with +// document.spellCheckCustomDictionary.addWords(), sorted. Page script cannot +// read the dictionary back; this lets developers inspect it. // -// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getFrameTree -func GetFrameTree() *GetFrameTreeParams { - return &GetFrameTreeParams{} -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getSpellCheckCustomDictionary +var GetSpellCheckCustomDictionary = cdp.Command[GetSpellCheckCustomDictionaryParams, GetSpellCheckCustomDictionaryResult]{Method: CommandGetSpellCheckCustomDictionary} -// GetFrameTreeReturns return values. -type GetFrameTreeReturns struct { +// GetFrameTreeResult is the result of the command Page.getFrameTree. +type GetFrameTreeResult struct { FrameTree *FrameTree `json:"frameTree,omitempty,omitzero"` // Present frame tree structure. } -// Do executes Page.getFrameTree against the provided context. -// -// returns: +// GetFrameTree returns present frame tree structure. // -// frameTree - Present frame tree structure. -func (p *GetFrameTreeParams) Do(ctx context.Context) (frameTree *FrameTree, err error) { - // execute - var res GetFrameTreeReturns - err = cdp.Execute(ctx, CommandGetFrameTree, nil, &res) - if err != nil { - return nil, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getFrameTree +var GetFrameTree = cdp.Command[cdp.Empty, GetFrameTreeResult]{Method: CommandGetFrameTree} - return res.FrameTree, nil +// GetLayoutMetricsResult is the result of the command Page.getLayoutMetrics. +type GetLayoutMetricsResult struct { + CSSLayoutViewport *LayoutViewport `json:"cssLayoutViewport,omitempty,omitzero"` // Metrics relating to the layout viewport in CSS pixels. + CSSVisualViewport *VisualViewport `json:"cssVisualViewport,omitempty,omitzero"` // Metrics relating to the visual viewport in CSS pixels. + CSSContentSize *dom.Rect `json:"cssContentSize,omitempty,omitzero"` // Size of scrollable area in CSS pixels. } -// GetLayoutMetricsParams returns metrics relating to the layouting of the -// page, such as viewport bounds/scale. -type GetLayoutMetricsParams struct{} - // GetLayoutMetrics returns metrics relating to the layouting of the page, // such as viewport bounds/scale. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getLayoutMetrics -func GetLayoutMetrics() *GetLayoutMetricsParams { - return &GetLayoutMetricsParams{} -} - -// GetLayoutMetricsReturns return values. -type GetLayoutMetricsReturns struct { - LayoutViewport *LayoutViewport `json:"layoutViewport"` // Deprecated metrics relating to the layout viewport. Is in device pixels. Use cssLayoutViewport instead. - VisualViewport *VisualViewport `json:"visualViewport"` // Deprecated metrics relating to the visual viewport. Is in device pixels. Use cssVisualViewport instead. - ContentSize *dom.Rect `json:"contentSize"` // Deprecated size of scrollable area. Is in DP. Use cssContentSize instead. - CSSLayoutViewport *LayoutViewport `json:"cssLayoutViewport"` // Metrics relating to the layout viewport in CSS pixels. - CSSVisualViewport *VisualViewport `json:"cssVisualViewport"` // Metrics relating to the visual viewport in CSS pixels. - CSSContentSize *dom.Rect `json:"cssContentSize"` // Size of scrollable area in CSS pixels. -} - -// Do executes Page.getLayoutMetrics against the provided context. -// -// returns: -// -// layoutViewport - Deprecated metrics relating to the layout viewport. Is in device pixels. Use cssLayoutViewport instead. -// visualViewport - Deprecated metrics relating to the visual viewport. Is in device pixels. Use cssVisualViewport instead. -// contentSize - Deprecated size of scrollable area. Is in DP. Use cssContentSize instead. -// cssLayoutViewport - Metrics relating to the layout viewport in CSS pixels. -// cssVisualViewport - Metrics relating to the visual viewport in CSS pixels. -// cssContentSize - Size of scrollable area in CSS pixels. -func (p *GetLayoutMetricsParams) Do(ctx context.Context) (layoutViewport *LayoutViewport, visualViewport *VisualViewport, contentSize *dom.Rect, cssLayoutViewport *LayoutViewport, cssVisualViewport *VisualViewport, cssContentSize *dom.Rect, err error) { - // execute - var res GetLayoutMetricsReturns - err = cdp.Execute(ctx, CommandGetLayoutMetrics, nil, &res) - if err != nil { - return nil, nil, nil, nil, nil, nil, err - } - - return res.LayoutViewport, res.VisualViewport, res.ContentSize, res.CSSLayoutViewport, res.CSSVisualViewport, res.CSSContentSize, nil -} - -// GetNavigationHistoryParams returns navigation history for the current -// page. -type GetNavigationHistoryParams struct{} +var GetLayoutMetrics = cdp.Command[cdp.Empty, GetLayoutMetricsResult]{Method: CommandGetLayoutMetrics} -// GetNavigationHistory returns navigation history for the current page. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getNavigationHistory -func GetNavigationHistory() *GetNavigationHistoryParams { - return &GetNavigationHistoryParams{} -} - -// GetNavigationHistoryReturns return values. -type GetNavigationHistoryReturns struct { +// GetNavigationHistoryResult is the result of the command +// Page.getNavigationHistory. +type GetNavigationHistoryResult struct { CurrentIndex int64 `json:"currentIndex,omitempty,omitzero"` // Index of the current navigation history entry. Entries []*NavigationEntry `json:"entries,omitempty,omitzero"` // Array of navigation history entries. } -// Do executes Page.getNavigationHistory against the provided context. -// -// returns: +// GetNavigationHistory returns navigation history for the current page. // -// currentIndex - Index of the current navigation history entry. -// entries - Array of navigation history entries. -func (p *GetNavigationHistoryParams) Do(ctx context.Context) (currentIndex int64, entries []*NavigationEntry, err error) { - // execute - var res GetNavigationHistoryReturns - err = cdp.Execute(ctx, CommandGetNavigationHistory, nil, &res) - if err != nil { - return 0, nil, err - } - - return res.CurrentIndex, res.Entries, nil -} - -// ResetNavigationHistoryParams resets navigation history for the current -// page. -type ResetNavigationHistoryParams struct{} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getNavigationHistory +var GetNavigationHistory = cdp.Command[cdp.Empty, GetNavigationHistoryResult]{Method: CommandGetNavigationHistory} // ResetNavigationHistory resets navigation history for the current page. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-resetNavigationHistory -func ResetNavigationHistory() *ResetNavigationHistoryParams { - return &ResetNavigationHistoryParams{} -} - -// Do executes Page.resetNavigationHistory against the provided context. -func (p *ResetNavigationHistoryParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandResetNavigationHistory, nil, nil) -} +var ResetNavigationHistory = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandResetNavigationHistory} -// GetResourceContentParams returns content of the given resource. +// GetResourceContentParams are the parameters of the command +// Page.getResourceContent. type GetResourceContentParams struct { FrameID cdp.FrameID `json:"frameId"` // Frame id to get resource for. URL string `json:"url"` // URL of the resource to get content for. } -// GetResourceContent returns content of the given resource. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getResourceContent -// -// parameters: -// -// frameID - Frame id to get resource for. -// url - URL of the resource to get content for. -func GetResourceContent(frameID cdp.FrameID, url string) *GetResourceContentParams { - return &GetResourceContentParams{ - FrameID: frameID, - URL: url, - } -} - -// GetResourceContentReturns return values. -type GetResourceContentReturns struct { - Content string `json:"content,omitempty,omitzero"` // Resource content. +// GetResourceContentResult is the result of the command +// Page.getResourceContent. +type GetResourceContentResult struct { + Content []byte `json:"content,omitempty,omitzero"` // Resource content. Base64encoded bool `json:"base64Encoded"` // True, if content was served as base64. } -// Do executes Page.getResourceContent against the provided context. -// -// returns: -// -// content - Resource content. -func (p *GetResourceContentParams) Do(ctx context.Context) (content []byte, err error) { - // execute - var res GetResourceContentReturns - err = cdp.Execute(ctx, CommandGetResourceContent, p, &res) - if err != nil { - return nil, err +// UnmarshalJSON decodes the value. The browser sends content as text, or as +// base64 when r.Base64encoded, and Content holds the decoded bytes. +func (r *GetResourceContentResult) UnmarshalJSON(buf []byte) error { + type plain GetResourceContentResult + aux := struct { + *plain + Content string `json:"content"` + }{plain: (*plain)(r)} + if err := jsonv2.Unmarshal(buf, &aux); err != nil { + return err } - - // decode - var dec []byte - if res.Base64encoded { - dec, err = base64.StdEncoding.DecodeString(res.Content) + if r.Base64encoded { + b, err := base64.StdEncoding.DecodeString(aux.Content) if err != nil { - return nil, err + return fmt.Errorf("decoding content: %w", err) } - } else { - dec = []byte(res.Content) + r.Content = b + return nil } - return dec, nil + r.Content = []byte(aux.Content) + return nil } -// GetResourceTreeParams returns present frame / resource tree structure. -type GetResourceTreeParams struct{} - -// GetResourceTree returns present frame / resource tree structure. +// GetResourceContent returns content of the given resource. // -// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getResourceTree -func GetResourceTree() *GetResourceTreeParams { - return &GetResourceTreeParams{} -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getResourceContent +var GetResourceContent = cdp.Command[GetResourceContentParams, GetResourceContentResult]{Method: CommandGetResourceContent} -// GetResourceTreeReturns return values. -type GetResourceTreeReturns struct { +// GetResourceTreeResult is the result of the command Page.getResourceTree. +type GetResourceTreeResult struct { FrameTree *FrameResourceTree `json:"frameTree,omitempty,omitzero"` // Present frame / resource tree structure. } -// Do executes Page.getResourceTree against the provided context. -// -// returns: +// GetResourceTree returns present frame / resource tree structure. // -// frameTree - Present frame / resource tree structure. -func (p *GetResourceTreeParams) Do(ctx context.Context) (frameTree *FrameResourceTree, err error) { - // execute - var res GetResourceTreeReturns - err = cdp.Execute(ctx, CommandGetResourceTree, nil, &res) - if err != nil { - return nil, err - } - - return res.FrameTree, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getResourceTree +var GetResourceTree = cdp.Command[cdp.Empty, GetResourceTreeResult]{Method: CommandGetResourceTree} -// HandleJavaScriptDialogParams accepts or dismisses a JavaScript initiated -// dialog (alert, confirm, prompt, or onbeforeunload). +// HandleJavaScriptDialogParams are the parameters of the command +// Page.handleJavaScriptDialog. type HandleJavaScriptDialogParams struct { Accept bool `json:"accept"` // Whether to accept or dismiss the dialog. PromptText string `json:"promptText,omitempty,omitzero"` // The text to enter into the dialog prompt before accepting. Used only if this is a prompt dialog. @@ -726,29 +333,9 @@ type HandleJavaScriptDialogParams struct { // (alert, confirm, prompt, or onbeforeunload). // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-handleJavaScriptDialog -// -// parameters: -// -// accept - Whether to accept or dismiss the dialog. -func HandleJavaScriptDialog(accept bool) *HandleJavaScriptDialogParams { - return &HandleJavaScriptDialogParams{ - Accept: accept, - } -} - -// WithPromptText the text to enter into the dialog prompt before accepting. -// Used only if this is a prompt dialog. -func (p HandleJavaScriptDialogParams) WithPromptText(promptText string) *HandleJavaScriptDialogParams { - p.PromptText = promptText - return &p -} - -// Do executes Page.handleJavaScriptDialog against the provided context. -func (p *HandleJavaScriptDialogParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandHandleJavaScriptDialog, p, nil) -} +var HandleJavaScriptDialog = cdp.Command[HandleJavaScriptDialogParams, cdp.Empty]{Method: CommandHandleJavaScriptDialog} -// NavigateParams navigates current page to the given URL. +// NavigateParams are the parameters of the command Page.navigate. type NavigateParams struct { URL string `json:"url"` // URL to navigate the page to. Referrer string `json:"referrer,omitempty,omitzero"` // Referrer URL. @@ -757,73 +344,21 @@ type NavigateParams struct { ReferrerPolicy ReferrerPolicy `json:"referrerPolicy,omitempty,omitzero"` // Referrer-policy used for the navigation. } -// Navigate navigates current page to the given URL. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-navigate -// -// parameters: -// -// url - URL to navigate the page to. -func Navigate(url string) *NavigateParams { - return &NavigateParams{ - URL: url, - } -} - -// WithReferrer referrer URL. -func (p NavigateParams) WithReferrer(referrer string) *NavigateParams { - p.Referrer = referrer - return &p -} - -// WithTransitionType intended transition type. -func (p NavigateParams) WithTransitionType(transitionType TransitionType) *NavigateParams { - p.TransitionType = transitionType - return &p -} - -// WithFrameID frame id to navigate, if not specified navigates the top -// frame. -func (p NavigateParams) WithFrameID(frameID cdp.FrameID) *NavigateParams { - p.FrameID = frameID - return &p -} - -// WithReferrerPolicy referrer-policy used for the navigation. -func (p NavigateParams) WithReferrerPolicy(referrerPolicy ReferrerPolicy) *NavigateParams { - p.ReferrerPolicy = referrerPolicy - return &p -} - -// NavigateReturns return values. -type NavigateReturns struct { +// NavigateResult is the result of the command Page.navigate. +type NavigateResult struct { FrameID cdp.FrameID `json:"frameId,omitempty,omitzero"` // Frame id that has navigated (or failed to navigate) LoaderID cdp.LoaderID `json:"loaderId,omitempty,omitzero"` // Loader identifier. This is omitted in case of same-document navigation, as the previously committed loaderId would not change. ErrorText string `json:"errorText,omitempty,omitzero"` // User friendly error message, present if and only if navigation has failed. IsDownload bool `json:"isDownload"` // Whether the navigation resulted in a download. } -// Do executes Page.navigate against the provided context. -// -// returns: +// Navigate navigates current page to the given URL. // -// frameID - Frame id that has navigated (or failed to navigate) -// loaderID - Loader identifier. This is omitted in case of same-document navigation, as the previously committed loaderId would not change. -// errorText - User friendly error message, present if and only if navigation has failed. -// isDownload - Whether the navigation resulted in a download. -func (p *NavigateParams) Do(ctx context.Context) (frameID cdp.FrameID, loaderID cdp.LoaderID, errorText string, isDownload bool, err error) { - // execute - var res NavigateReturns - err = cdp.Execute(ctx, CommandNavigate, p, &res) - if err != nil { - return "", "", "", false, err - } - - return res.FrameID, res.LoaderID, res.ErrorText, res.IsDownload, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-navigate +var Navigate = cdp.Command[NavigateParams, NavigateResult]{Method: CommandNavigate} -// NavigateToHistoryEntryParams navigates current page to the given history -// entry. +// NavigateToHistoryEntryParams are the parameters of the command +// Page.navigateToHistoryEntry. type NavigateToHistoryEntryParams struct { EntryID int64 `json:"entryId"` // Unique id of the entry to navigate to. } @@ -831,208 +366,43 @@ type NavigateToHistoryEntryParams struct { // NavigateToHistoryEntry navigates current page to the given history entry. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-navigateToHistoryEntry -// -// parameters: -// -// entryID - Unique id of the entry to navigate to. -func NavigateToHistoryEntry(entryID int64) *NavigateToHistoryEntryParams { - return &NavigateToHistoryEntryParams{ - EntryID: entryID, - } -} +var NavigateToHistoryEntry = cdp.Command[NavigateToHistoryEntryParams, cdp.Empty]{Method: CommandNavigateToHistoryEntry} -// Do executes Page.navigateToHistoryEntry against the provided context. -func (p *NavigateToHistoryEntryParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandNavigateToHistoryEntry, p, nil) -} - -// PrintToPDFParams print page as PDF. +// PrintToPDFParams are the parameters of the command Page.printToPDF. type PrintToPDFParams struct { - Landscape bool `json:"landscape"` // Paper orientation. Defaults to false. - DisplayHeaderFooter bool `json:"displayHeaderFooter"` // Display header and footer. Defaults to false. - PrintBackground bool `json:"printBackground"` // Print background graphics. Defaults to false. - Scale float64 `json:"scale,omitempty,omitzero"` // Scale of the webpage rendering. Defaults to 1. - PaperWidth float64 `json:"paperWidth,omitempty,omitzero"` // Paper width in inches. Defaults to 8.5 inches. - PaperHeight float64 `json:"paperHeight,omitempty,omitzero"` // Paper height in inches. Defaults to 11 inches. - MarginTop float64 `json:"marginTop"` // Top margin in inches. Defaults to 1cm (~0.4 inches). - MarginBottom float64 `json:"marginBottom"` // Bottom margin in inches. Defaults to 1cm (~0.4 inches). - MarginLeft float64 `json:"marginLeft"` // Left margin in inches. Defaults to 1cm (~0.4 inches). - MarginRight float64 `json:"marginRight"` // Right margin in inches. Defaults to 1cm (~0.4 inches). - PageRanges string `json:"pageRanges,omitempty,omitzero"` // Paper ranges to print, one based, e.g., '1-5, 8, 11-13'. Pages are printed in the document order, not in the order specified, and no more than once. Defaults to empty string, which implies the entire document is printed. The page numbers are quietly capped to actual page count of the document, and ranges beyond the end of the document are ignored. If this results in no pages to print, an error is reported. It is an error to specify a range with start greater than end. - HeaderTemplate string `json:"headerTemplate,omitempty,omitzero"` // HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: - date: formatted print date - title: document title - url: document location - pageNumber: current page number - totalPages: total pages in the document For example, would generate span containing the title. - FooterTemplate string `json:"footerTemplate,omitempty,omitzero"` // HTML template for the print footer. Should use the same format as the headerTemplate. - PreferCSSPageSize bool `json:"preferCSSPageSize"` // Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size. - TransferMode PrintToPDFTransferMode `json:"transferMode,omitempty,omitzero"` // return as stream - GenerateTaggedPDF bool `json:"generateTaggedPDF"` // Whether or not to generate tagged (accessible) PDF. Defaults to embedder choice. - GenerateDocumentOutline bool `json:"generateDocumentOutline"` // Whether or not to embed the document outline into the PDF. -} - -// PrintToPDF print page as PDF. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-printToPDF -// -// parameters: -func PrintToPDF() *PrintToPDFParams { - return &PrintToPDFParams{ - Landscape: false, - DisplayHeaderFooter: false, - PrintBackground: false, - PreferCSSPageSize: false, - GenerateTaggedPDF: false, - GenerateDocumentOutline: false, - } -} - -// WithLandscape paper orientation. Defaults to false. -func (p PrintToPDFParams) WithLandscape(landscape bool) *PrintToPDFParams { - p.Landscape = landscape - return &p -} - -// WithDisplayHeaderFooter display header and footer. Defaults to false. -func (p PrintToPDFParams) WithDisplayHeaderFooter(displayHeaderFooter bool) *PrintToPDFParams { - p.DisplayHeaderFooter = displayHeaderFooter - return &p -} - -// WithPrintBackground print background graphics. Defaults to false. -func (p PrintToPDFParams) WithPrintBackground(printBackground bool) *PrintToPDFParams { - p.PrintBackground = printBackground - return &p -} - -// WithScale scale of the webpage rendering. Defaults to 1. -func (p PrintToPDFParams) WithScale(scale float64) *PrintToPDFParams { - p.Scale = scale - return &p -} - -// WithPaperWidth paper width in inches. Defaults to 8.5 inches. -func (p PrintToPDFParams) WithPaperWidth(paperWidth float64) *PrintToPDFParams { - p.PaperWidth = paperWidth - return &p -} - -// WithPaperHeight paper height in inches. Defaults to 11 inches. -func (p PrintToPDFParams) WithPaperHeight(paperHeight float64) *PrintToPDFParams { - p.PaperHeight = paperHeight - return &p -} - -// WithMarginTop top margin in inches. Defaults to 1cm (~0.4 inches). -func (p PrintToPDFParams) WithMarginTop(marginTop float64) *PrintToPDFParams { - p.MarginTop = marginTop - return &p -} - -// WithMarginBottom bottom margin in inches. Defaults to 1cm (~0.4 inches). -func (p PrintToPDFParams) WithMarginBottom(marginBottom float64) *PrintToPDFParams { - p.MarginBottom = marginBottom - return &p -} - -// WithMarginLeft left margin in inches. Defaults to 1cm (~0.4 inches). -func (p PrintToPDFParams) WithMarginLeft(marginLeft float64) *PrintToPDFParams { - p.MarginLeft = marginLeft - return &p -} - -// WithMarginRight right margin in inches. Defaults to 1cm (~0.4 inches). -func (p PrintToPDFParams) WithMarginRight(marginRight float64) *PrintToPDFParams { - p.MarginRight = marginRight - return &p -} - -// WithPageRanges paper ranges to print, one based, e.g., '1-5, 8, 11-13'. -// Pages are printed in the document order, not in the order specified, and no -// more than once. Defaults to empty string, which implies the entire document -// is printed. The page numbers are quietly capped to actual page count of the -// document, and ranges beyond the end of the document are ignored. If this -// results in no pages to print, an error is reported. It is an error to specify -// a range with start greater than end. -func (p PrintToPDFParams) WithPageRanges(pageRanges string) *PrintToPDFParams { - p.PageRanges = pageRanges - return &p -} - -// WithHeaderTemplate HTML template for the print header. Should be valid -// HTML markup with following classes used to inject printing values into them: -// - date: formatted print date - title: document title - url: document location -// - pageNumber: current page number - totalPages: total pages in the document -// For example, would generate span containing the -// title. -func (p PrintToPDFParams) WithHeaderTemplate(headerTemplate string) *PrintToPDFParams { - p.HeaderTemplate = headerTemplate - return &p -} - -// WithFooterTemplate HTML template for the print footer. Should use the same -// format as the headerTemplate. -func (p PrintToPDFParams) WithFooterTemplate(footerTemplate string) *PrintToPDFParams { - p.FooterTemplate = footerTemplate - return &p -} - -// WithPreferCSSPageSize whether or not to prefer page size as defined by -// css. Defaults to false, in which case the content will be scaled to fit the -// paper size. -func (p PrintToPDFParams) WithPreferCSSPageSize(preferCSSPageSize bool) *PrintToPDFParams { - p.PreferCSSPageSize = preferCSSPageSize - return &p -} - -// WithTransferMode return as stream. -func (p PrintToPDFParams) WithTransferMode(transferMode PrintToPDFTransferMode) *PrintToPDFParams { - p.TransferMode = transferMode - return &p -} - -// WithGenerateTaggedPDF whether or not to generate tagged (accessible) PDF. -// Defaults to embedder choice. -func (p PrintToPDFParams) WithGenerateTaggedPDF(generateTaggedPDF bool) *PrintToPDFParams { - p.GenerateTaggedPDF = generateTaggedPDF - return &p -} - -// WithGenerateDocumentOutline whether or not to embed the document outline -// into the PDF. -func (p PrintToPDFParams) WithGenerateDocumentOutline(generateDocumentOutline bool) *PrintToPDFParams { - p.GenerateDocumentOutline = generateDocumentOutline - return &p -} - -// PrintToPDFReturns return values. -type PrintToPDFReturns struct { - Data string `json:"data,omitempty,omitzero"` // Base64-encoded pdf data. Empty if |returnAsStream| is specified. + Landscape *bool `json:"landscape,omitempty,omitzero"` // Paper orientation. Defaults to false. + DisplayHeaderFooter *bool `json:"displayHeaderFooter,omitempty,omitzero"` // Display header and footer. Defaults to false. + PrintBackground *bool `json:"printBackground,omitempty,omitzero"` // Print background graphics. Defaults to false. + Scale float64 `json:"scale,omitempty,omitzero"` // Scale of the webpage rendering. Defaults to 1. + PaperWidth float64 `json:"paperWidth,omitempty,omitzero"` // Paper width in inches. Defaults to 8.5 inches. + PaperHeight float64 `json:"paperHeight,omitempty,omitzero"` // Paper height in inches. Defaults to 11 inches. + MarginTop *float64 `json:"marginTop,omitempty,omitzero"` // Top margin in inches. Defaults to 1cm (~0.4 inches). + MarginBottom *float64 `json:"marginBottom,omitempty,omitzero"` // Bottom margin in inches. Defaults to 1cm (~0.4 inches). + MarginLeft *float64 `json:"marginLeft,omitempty,omitzero"` // Left margin in inches. Defaults to 1cm (~0.4 inches). + MarginRight *float64 `json:"marginRight,omitempty,omitzero"` // Right margin in inches. Defaults to 1cm (~0.4 inches). + PageRanges string `json:"pageRanges,omitempty,omitzero"` // Paper ranges to print, one based, e.g., '1-5, 8, 11-13'. Pages are printed in the document order, not in the order specified, and no more than once. Defaults to empty string, which implies the entire document is printed. The page numbers are quietly capped to actual page count of the document, and ranges beyond the end of the document are ignored. If this results in no pages to print, an error is reported. It is an error to specify a range with start greater than end. + HeaderTemplate string `json:"headerTemplate,omitempty,omitzero"` // HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: - date: formatted print date - title: document title - url: document location - pageNumber: current page number - totalPages: total pages in the document For example, would generate span containing the title. + FooterTemplate string `json:"footerTemplate,omitempty,omitzero"` // HTML template for the print footer. Should use the same format as the headerTemplate. + PreferCSSPageSize *bool `json:"preferCSSPageSize,omitempty,omitzero"` // Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size. + TransferMode PrintToPDFTransferMode `json:"transferMode,omitempty,omitzero"` // return as stream + GenerateTaggedPDF *bool `json:"generateTaggedPDF,omitempty,omitzero"` // Whether or not to generate tagged (accessible) PDF. Defaults to embedder choice. + GenerateDocumentOutline *bool `json:"generateDocumentOutline,omitempty,omitzero"` // Whether or not to embed the document outline into the PDF. +} + +// PrintToPDFResult is the result of the command Page.printToPDF. +type PrintToPDFResult struct { + Data []byte `json:"data,omitempty,omitzero"` // Base64-encoded pdf data. Empty if |returnAsStream| is specified. Stream io.StreamHandle `json:"stream,omitempty,omitzero"` // A handle of the stream that holds resulting PDF data. } -// Do executes Page.printToPDF against the provided context. -// -// returns: -// -// data - Base64-encoded pdf data. Empty if |returnAsStream| is specified. -// stream - A handle of the stream that holds resulting PDF data. -func (p *PrintToPDFParams) Do(ctx context.Context) (data []byte, stream io.StreamHandle, err error) { - // execute - var res PrintToPDFReturns - err = cdp.Execute(ctx, CommandPrintToPDF, p, &res) - if err != nil { - return nil, "", err - } - - // decode - var dec []byte - dec, err = base64.StdEncoding.DecodeString(res.Data) - if err != nil { - return nil, "", err - } - return dec, res.Stream, nil -} - -// ReloadParams reloads given page optionally ignoring the cache. +// PrintToPDF print page as PDF. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-printToPDF +var PrintToPDF = cdp.Command[PrintToPDFParams, PrintToPDFResult]{Method: CommandPrintToPDF} + +// ReloadParams are the parameters of the command Page.reload. type ReloadParams struct { - IgnoreCache bool `json:"ignoreCache"` // If true, browser cache is ignored (as if the user pressed Shift+refresh). + IgnoreCache *bool `json:"ignoreCache,omitempty,omitzero"` // If true, browser cache is ignored (as if the user pressed Shift+refresh). ScriptToEvaluateOnLoad string `json:"scriptToEvaluateOnLoad,omitempty,omitzero"` // If set, the script will be injected into all frames of the inspected page after reload. Argument will be ignored if reloading dataURL origin. LoaderID cdp.LoaderID `json:"loaderId,omitempty,omitzero"` // If set, an error will be thrown if the target page's main frame's loader id does not match the provided id. This prevents accidentally reloading an unintended target in case there's a racing navigation. } @@ -1040,44 +410,10 @@ type ReloadParams struct { // Reload reloads given page optionally ignoring the cache. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-reload -// -// parameters: -func Reload() *ReloadParams { - return &ReloadParams{ - IgnoreCache: false, - } -} - -// WithIgnoreCache if true, browser cache is ignored (as if the user pressed -// Shift+refresh). -func (p ReloadParams) WithIgnoreCache(ignoreCache bool) *ReloadParams { - p.IgnoreCache = ignoreCache - return &p -} - -// WithScriptToEvaluateOnLoad if set, the script will be injected into all -// frames of the inspected page after reload. Argument will be ignored if -// reloading dataURL origin. -func (p ReloadParams) WithScriptToEvaluateOnLoad(scriptToEvaluateOnLoad string) *ReloadParams { - p.ScriptToEvaluateOnLoad = scriptToEvaluateOnLoad - return &p -} - -// WithLoaderID if set, an error will be thrown if the target page's main -// frame's loader id does not match the provided id. This prevents accidentally -// reloading an unintended target in case there's a racing navigation. -func (p ReloadParams) WithLoaderID(loaderID cdp.LoaderID) *ReloadParams { - p.LoaderID = loaderID - return &p -} - -// Do executes Page.reload against the provided context. -func (p *ReloadParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandReload, p, nil) -} +var Reload = cdp.Command[ReloadParams, cdp.Empty]{Method: CommandReload} -// RemoveScriptToEvaluateOnNewDocumentParams removes given script from the -// list. +// RemoveScriptToEvaluateOnNewDocumentParams are the parameters of the +// command Page.removeScriptToEvaluateOnNewDocument. type RemoveScriptToEvaluateOnNewDocumentParams struct { Identifier ScriptIdentifier `json:"identifier"` } @@ -1085,23 +421,10 @@ type RemoveScriptToEvaluateOnNewDocumentParams struct { // RemoveScriptToEvaluateOnNewDocument removes given script from the list. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-removeScriptToEvaluateOnNewDocument -// -// parameters: -// -// identifier -func RemoveScriptToEvaluateOnNewDocument(identifier ScriptIdentifier) *RemoveScriptToEvaluateOnNewDocumentParams { - return &RemoveScriptToEvaluateOnNewDocumentParams{ - Identifier: identifier, - } -} - -// Do executes Page.removeScriptToEvaluateOnNewDocument against the provided context. -func (p *RemoveScriptToEvaluateOnNewDocumentParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRemoveScriptToEvaluateOnNewDocument, p, nil) -} +var RemoveScriptToEvaluateOnNewDocument = cdp.Command[RemoveScriptToEvaluateOnNewDocumentParams, cdp.Empty]{Method: CommandRemoveScriptToEvaluateOnNewDocument} -// ScreencastFrameAckParams acknowledges that a screencast frame has been -// received by the frontend. +// ScreencastFrameAckParams are the parameters of the command +// Page.screencastFrameAck. type ScreencastFrameAckParams struct { SessionID int64 `json:"sessionId"` // Frame number. } @@ -1110,84 +433,30 @@ type ScreencastFrameAckParams struct { // by the frontend. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-screencastFrameAck -// -// parameters: -// -// sessionID - Frame number. -func ScreencastFrameAck(sessionID int64) *ScreencastFrameAckParams { - return &ScreencastFrameAckParams{ - SessionID: sessionID, - } -} - -// Do executes Page.screencastFrameAck against the provided context. -func (p *ScreencastFrameAckParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandScreencastFrameAck, p, nil) -} +var ScreencastFrameAck = cdp.Command[ScreencastFrameAckParams, cdp.Empty]{Method: CommandScreencastFrameAck} -// SearchInResourceParams searches for given string in resource content. +// SearchInResourceParams are the parameters of the command +// Page.searchInResource. type SearchInResourceParams struct { - FrameID cdp.FrameID `json:"frameId"` // Frame id for resource to search in. - URL string `json:"url"` // URL of the resource to search in. - Query string `json:"query"` // String to search for. - CaseSensitive bool `json:"caseSensitive"` // If true, search is case sensitive. - IsRegex bool `json:"isRegex"` // If true, treats string parameter as regex. -} - -// SearchInResource searches for given string in resource content. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-searchInResource -// -// parameters: -// -// frameID - Frame id for resource to search in. -// url - URL of the resource to search in. -// query - String to search for. -func SearchInResource(frameID cdp.FrameID, url string, query string) *SearchInResourceParams { - return &SearchInResourceParams{ - FrameID: frameID, - URL: url, - Query: query, - CaseSensitive: false, - IsRegex: false, - } -} - -// WithCaseSensitive if true, search is case sensitive. -func (p SearchInResourceParams) WithCaseSensitive(caseSensitive bool) *SearchInResourceParams { - p.CaseSensitive = caseSensitive - return &p + FrameID cdp.FrameID `json:"frameId"` // Frame id for resource to search in. + URL string `json:"url"` // URL of the resource to search in. + Query string `json:"query"` // String to search for. + CaseSensitive *bool `json:"caseSensitive,omitempty,omitzero"` // If true, search is case sensitive. + IsRegex *bool `json:"isRegex,omitempty,omitzero"` // If true, treats string parameter as regex. } -// WithIsRegex if true, treats string parameter as regex. -func (p SearchInResourceParams) WithIsRegex(isRegex bool) *SearchInResourceParams { - p.IsRegex = isRegex - return &p -} - -// SearchInResourceReturns return values. -type SearchInResourceReturns struct { +// SearchInResourceResult is the result of the command Page.searchInResource. +type SearchInResourceResult struct { Result []*debugger.SearchMatch `json:"result,omitempty,omitzero"` // List of search matches. } -// Do executes Page.searchInResource against the provided context. -// -// returns: +// SearchInResource searches for given string in resource content. // -// result - List of search matches. -func (p *SearchInResourceParams) Do(ctx context.Context) (result []*debugger.SearchMatch, err error) { - // execute - var res SearchInResourceReturns - err = cdp.Execute(ctx, CommandSearchInResource, p, &res) - if err != nil { - return nil, err - } - - return res.Result, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-searchInResource +var SearchInResource = cdp.Command[SearchInResourceParams, SearchInResourceResult]{Method: CommandSearchInResource} -// SetAdBlockingEnabledParams enable Chrome's experimental ad filter on all -// sites. +// SetAdBlockingEnabledParams are the parameters of the command +// Page.setAdBlockingEnabled. type SetAdBlockingEnabledParams struct { Enabled bool `json:"enabled"` // Whether to block ads. } @@ -1195,22 +464,9 @@ type SetAdBlockingEnabledParams struct { // SetAdBlockingEnabled enable Chrome's experimental ad filter on all sites. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setAdBlockingEnabled -// -// parameters: -// -// enabled - Whether to block ads. -func SetAdBlockingEnabled(enabled bool) *SetAdBlockingEnabledParams { - return &SetAdBlockingEnabledParams{ - Enabled: enabled, - } -} +var SetAdBlockingEnabled = cdp.Command[SetAdBlockingEnabledParams, cdp.Empty]{Method: CommandSetAdBlockingEnabled} -// Do executes Page.setAdBlockingEnabled against the provided context. -func (p *SetAdBlockingEnabledParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetAdBlockingEnabled, p, nil) -} - -// SetBypassCSPParams enable page Content Security Policy by-passing. +// SetBypassCSPParams are the parameters of the command Page.setBypassCSP. type SetBypassCSPParams struct { Enabled bool `json:"enabled"` // Whether to bypass page CSP. } @@ -1218,101 +474,43 @@ type SetBypassCSPParams struct { // SetBypassCSP enable page Content Security Policy by-passing. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setBypassCSP -// -// parameters: -// -// enabled - Whether to bypass page CSP. -func SetBypassCSP(enabled bool) *SetBypassCSPParams { - return &SetBypassCSPParams{ - Enabled: enabled, - } -} - -// Do executes Page.setBypassCSP against the provided context. -func (p *SetBypassCSPParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetBypassCSP, p, nil) -} +var SetBypassCSP = cdp.Command[SetBypassCSPParams, cdp.Empty]{Method: CommandSetBypassCSP} -// GetPermissionsPolicyStateParams get Permissions Policy state on given -// frame. +// GetPermissionsPolicyStateParams are the parameters of the command +// Page.getPermissionsPolicyState. type GetPermissionsPolicyStateParams struct { FrameID cdp.FrameID `json:"frameId"` } -// GetPermissionsPolicyState get Permissions Policy state on given frame. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getPermissionsPolicyState -// -// parameters: -// -// frameID -func GetPermissionsPolicyState(frameID cdp.FrameID) *GetPermissionsPolicyStateParams { - return &GetPermissionsPolicyStateParams{ - FrameID: frameID, - } -} - -// GetPermissionsPolicyStateReturns return values. -type GetPermissionsPolicyStateReturns struct { +// GetPermissionsPolicyStateResult is the result of the command +// Page.getPermissionsPolicyState. +type GetPermissionsPolicyStateResult struct { States []*PermissionsPolicyFeatureState `json:"states,omitempty,omitzero"` } -// Do executes Page.getPermissionsPolicyState against the provided context. -// -// returns: +// GetPermissionsPolicyState get Permissions Policy state on given frame. // -// states -func (p *GetPermissionsPolicyStateParams) Do(ctx context.Context) (states []*PermissionsPolicyFeatureState, err error) { - // execute - var res GetPermissionsPolicyStateReturns - err = cdp.Execute(ctx, CommandGetPermissionsPolicyState, p, &res) - if err != nil { - return nil, err - } - - return res.States, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getPermissionsPolicyState +var GetPermissionsPolicyState = cdp.Command[GetPermissionsPolicyStateParams, GetPermissionsPolicyStateResult]{Method: CommandGetPermissionsPolicyState} -// GetOriginTrialsParams get Origin Trials on given frame. +// GetOriginTrialsParams are the parameters of the command +// Page.getOriginTrials. type GetOriginTrialsParams struct { FrameID cdp.FrameID `json:"frameId"` } -// GetOriginTrials get Origin Trials on given frame. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getOriginTrials -// -// parameters: -// -// frameID -func GetOriginTrials(frameID cdp.FrameID) *GetOriginTrialsParams { - return &GetOriginTrialsParams{ - FrameID: frameID, - } -} - -// GetOriginTrialsReturns return values. -type GetOriginTrialsReturns struct { +// GetOriginTrialsResult is the result of the command Page.getOriginTrials. +type GetOriginTrialsResult struct { OriginTrials []*cdp.OriginTrial `json:"originTrials,omitempty,omitzero"` } -// Do executes Page.getOriginTrials against the provided context. -// -// returns: +// GetOriginTrials get Origin Trials on given frame. // -// originTrials -func (p *GetOriginTrialsParams) Do(ctx context.Context) (originTrials []*cdp.OriginTrial, err error) { - // execute - var res GetOriginTrialsReturns - err = cdp.Execute(ctx, CommandGetOriginTrials, p, &res) - if err != nil { - return nil, err - } - - return res.OriginTrials, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getOriginTrials +var GetOriginTrials = cdp.Command[GetOriginTrialsParams, GetOriginTrialsResult]{Method: CommandGetOriginTrials} -// SetFontFamiliesParams set generic font families. +// SetFontFamiliesParams are the parameters of the command +// Page.setFontFamilies. type SetFontFamiliesParams struct { FontFamilies *FontFamilies `json:"fontFamilies"` // Specifies font families to set. If a font family is not specified, it won't be changed. ForScripts []*ScriptFontFamilies `json:"forScripts,omitempty,omitzero"` // Specifies font families to set for individual scripts. @@ -1321,28 +519,9 @@ type SetFontFamiliesParams struct { // SetFontFamilies set generic font families. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setFontFamilies -// -// parameters: -// -// fontFamilies - Specifies font families to set. If a font family is not specified, it won't be changed. -func SetFontFamilies(fontFamilies *FontFamilies) *SetFontFamiliesParams { - return &SetFontFamiliesParams{ - FontFamilies: fontFamilies, - } -} +var SetFontFamilies = cdp.Command[SetFontFamiliesParams, cdp.Empty]{Method: CommandSetFontFamilies} -// WithForScripts specifies font families to set for individual scripts. -func (p SetFontFamiliesParams) WithForScripts(forScripts []*ScriptFontFamilies) *SetFontFamiliesParams { - p.ForScripts = forScripts - return &p -} - -// Do executes Page.setFontFamilies against the provided context. -func (p *SetFontFamiliesParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetFontFamilies, p, nil) -} - -// SetFontSizesParams set default font sizes. +// SetFontSizesParams are the parameters of the command Page.setFontSizes. type SetFontSizesParams struct { FontSizes *FontSizes `json:"fontSizes"` // Specifies font sizes to set. If a font size is not specified, it won't be changed. } @@ -1350,22 +529,10 @@ type SetFontSizesParams struct { // SetFontSizes set default font sizes. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setFontSizes -// -// parameters: -// -// fontSizes - Specifies font sizes to set. If a font size is not specified, it won't be changed. -func SetFontSizes(fontSizes *FontSizes) *SetFontSizesParams { - return &SetFontSizesParams{ - FontSizes: fontSizes, - } -} +var SetFontSizes = cdp.Command[SetFontSizesParams, cdp.Empty]{Method: CommandSetFontSizes} -// Do executes Page.setFontSizes against the provided context. -func (p *SetFontSizesParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetFontSizes, p, nil) -} - -// SetDocumentContentParams sets given markup as the document's HTML. +// SetDocumentContentParams are the parameters of the command +// Page.setDocumentContent. type SetDocumentContentParams struct { FrameID cdp.FrameID `json:"frameId"` // Frame id to set HTML for. HTML string `json:"html"` // HTML content to set. @@ -1374,25 +541,10 @@ type SetDocumentContentParams struct { // SetDocumentContent sets given markup as the document's HTML. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setDocumentContent -// -// parameters: -// -// frameID - Frame id to set HTML for. -// html - HTML content to set. -func SetDocumentContent(frameID cdp.FrameID, html string) *SetDocumentContentParams { - return &SetDocumentContentParams{ - FrameID: frameID, - HTML: html, - } -} - -// Do executes Page.setDocumentContent against the provided context. -func (p *SetDocumentContentParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetDocumentContent, p, nil) -} +var SetDocumentContent = cdp.Command[SetDocumentContentParams, cdp.Empty]{Method: CommandSetDocumentContent} -// SetLifecycleEventsEnabledParams controls whether page will emit lifecycle -// events. +// SetLifecycleEventsEnabledParams are the parameters of the command +// Page.setLifecycleEventsEnabled. type SetLifecycleEventsEnabledParams struct { Enabled bool `json:"enabled"` // If true, starts emitting lifecycle events. } @@ -1401,125 +553,74 @@ type SetLifecycleEventsEnabledParams struct { // events. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setLifecycleEventsEnabled -// -// parameters: -// -// enabled - If true, starts emitting lifecycle events. -func SetLifecycleEventsEnabled(enabled bool) *SetLifecycleEventsEnabledParams { - return &SetLifecycleEventsEnabledParams{ - Enabled: enabled, - } -} - -// Do executes Page.setLifecycleEventsEnabled against the provided context. -func (p *SetLifecycleEventsEnabledParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetLifecycleEventsEnabled, p, nil) -} +var SetLifecycleEventsEnabled = cdp.Command[SetLifecycleEventsEnabledParams, cdp.Empty]{Method: CommandSetLifecycleEventsEnabled} -// StartScreencastParams starts sending each frame using the screencastFrame -// event. +// StartScreencastParams are the parameters of the command +// Page.startScreencast. type StartScreencastParams struct { - Format ScreencastFormat `json:"format,omitempty,omitzero"` // Image compression format. - Quality int64 `json:"quality,omitempty,omitzero"` // Compression quality from range [0..100]. - MaxWidth int64 `json:"maxWidth,omitempty,omitzero"` // Maximum screenshot width. - MaxHeight int64 `json:"maxHeight,omitempty,omitzero"` // Maximum screenshot height. - EveryNthFrame int64 `json:"everyNthFrame,omitempty,omitzero"` // Send every n-th frame. + Format StartScreencastFormat `json:"format,omitempty,omitzero"` // Image compression format. + Quality *int64 `json:"quality,omitempty,omitzero"` // Compression quality from range [0..100]. + MaxWidth int64 `json:"maxWidth,omitempty,omitzero"` // Maximum screenshot width. + MaxHeight int64 `json:"maxHeight,omitempty,omitzero"` // Maximum screenshot height. + EveryNthFrame int64 `json:"everyNthFrame,omitempty,omitzero"` // Send every n-th frame. Must be a positive integer. + MaxFramesInFlight int64 `json:"maxFramesInFlight,omitempty,omitzero"` // Maximum number of frames sent until screencastFrameAck is required. Defaults to 3. Must be a positive integer. + SendLastFrame *bool `json:"sendLastFrame,omitempty,omitzero"` // By default, after screencastFrameAck arrives, the next produced frame is sent. Passing this flag enables storing the last produced frame in memory, which is immediately sent upon screencastFrameAck. This way, overall performance is traded for a better latency. } // StartScreencast starts sending each frame using the screencastFrame event. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-startScreencast -// -// parameters: -func StartScreencast() *StartScreencastParams { - return &StartScreencastParams{} -} - -// WithFormat image compression format. -func (p StartScreencastParams) WithFormat(format ScreencastFormat) *StartScreencastParams { - p.Format = format - return &p -} - -// WithQuality compression quality from range [0..100]. -func (p StartScreencastParams) WithQuality(quality int64) *StartScreencastParams { - p.Quality = quality - return &p -} +var StartScreencast = cdp.Command[StartScreencastParams, cdp.Empty]{Method: CommandStartScreencast} -// WithMaxWidth maximum screenshot width. -func (p StartScreencastParams) WithMaxWidth(maxWidth int64) *StartScreencastParams { - p.MaxWidth = maxWidth - return &p +// StartScreenRecordingParams are the parameters of the command +// Page.startScreenRecording. +type StartScreenRecordingParams struct { + Audio *bool `json:"audio,omitempty,omitzero"` + MaxWidth int64 `json:"maxWidth,omitempty,omitzero"` // Maximum frame width in pixels. + MaxHeight int64 `json:"maxHeight,omitempty,omitzero"` // Maximum frame height in pixels. + FrameRate int64 `json:"frameRate,omitempty,omitzero"` // Maximum frame rate in frames per second. } -// WithMaxHeight maximum screenshot height. -func (p StartScreencastParams) WithMaxHeight(maxHeight int64) *StartScreencastParams { - p.MaxHeight = maxHeight - return &p +// StartScreenRecordingResult is the result of the command +// Page.startScreenRecording. +type StartScreenRecordingResult struct { + Stream io.StreamHandle `json:"stream,omitempty,omitzero"` // A handle of the stream that holds resulting screencast data. } -// WithEveryNthFrame send every n-th frame. -func (p StartScreencastParams) WithEveryNthFrame(everyNthFrame int64) *StartScreencastParams { - p.EveryNthFrame = everyNthFrame - return &p -} +// StartScreenRecording starts screencast video recording. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-startScreenRecording +var StartScreenRecording = cdp.Command[StartScreenRecordingParams, StartScreenRecordingResult]{Method: CommandStartScreenRecording} -// Do executes Page.startScreencast against the provided context. -func (p *StartScreencastParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStartScreencast, p, nil) +// StopScreenRecordingResult is the result of the command +// Page.stopScreenRecording. +type StopScreenRecordingResult struct { + Stream io.StreamHandle `json:"stream,omitempty,omitzero"` // A handle of the stream that holds resulting screencast data. } -// StopLoadingParams force the page stop all navigations and pending resource -// fetches. -type StopLoadingParams struct{} +// StopScreenRecording stops screencast video recording. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-stopScreenRecording +var StopScreenRecording = cdp.Command[cdp.Empty, StopScreenRecordingResult]{Method: CommandStopScreenRecording} // StopLoading force the page stop all navigations and pending resource // fetches. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-stopLoading -func StopLoading() *StopLoadingParams { - return &StopLoadingParams{} -} - -// Do executes Page.stopLoading against the provided context. -func (p *StopLoadingParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStopLoading, nil, nil) -} - -// CrashParams crashes renderer on the IO thread, generates minidumps. -type CrashParams struct{} +var StopLoading = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandStopLoading} // Crash crashes renderer on the IO thread, generates minidumps. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-crash -func Crash() *CrashParams { - return &CrashParams{} -} - -// Do executes Page.crash against the provided context. -func (p *CrashParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandCrash, nil, nil) -} - -// CloseParams tries to close page, running its beforeunload hooks, if any. -type CloseParams struct{} +var Crash = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandCrash} // Close tries to close page, running its beforeunload hooks, if any. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-close -func Close() *CloseParams { - return &CloseParams{} -} - -// Do executes Page.close against the provided context. -func (p *CloseParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClose, nil, nil) -} +var Close = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandClose} -// SetWebLifecycleStateParams tries to update the web lifecycle state of the -// page. It will transition the page to the given state according to: -// https://github.com/WICG/web-lifecycle/. +// SetWebLifecycleStateParams are the parameters of the command +// Page.setWebLifecycleState. type SetWebLifecycleStateParams struct { State SetWebLifecycleStateState `json:"state"` // Target lifecycle state } @@ -1529,42 +630,15 @@ type SetWebLifecycleStateParams struct { // https://github.com/WICG/web-lifecycle/. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setWebLifecycleState -// -// parameters: -// -// state - Target lifecycle state -func SetWebLifecycleState(state SetWebLifecycleStateState) *SetWebLifecycleStateParams { - return &SetWebLifecycleStateParams{ - State: state, - } -} - -// Do executes Page.setWebLifecycleState against the provided context. -func (p *SetWebLifecycleStateParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetWebLifecycleState, p, nil) -} - -// StopScreencastParams stops sending each frame in the screencastFrame. -type StopScreencastParams struct{} +var SetWebLifecycleState = cdp.Command[SetWebLifecycleStateParams, cdp.Empty]{Method: CommandSetWebLifecycleState} // StopScreencast stops sending each frame in the screencastFrame. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-stopScreencast -func StopScreencast() *StopScreencastParams { - return &StopScreencastParams{} -} - -// Do executes Page.stopScreencast against the provided context. -func (p *StopScreencastParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStopScreencast, nil, nil) -} +var StopScreencast = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandStopScreencast} -// ProduceCompilationCacheParams requests backend to produce compilation -// cache for the specified scripts. scripts are appended to the list of scripts -// for which the cache would be produced. The list may be reset during page -// navigation. When script with a matching URL is encountered, the cache is -// optionally produced upon backend discretion, based on internal heuristics. -// See also: Page.compilationCacheProduced. +// ProduceCompilationCacheParams are the parameters of the command +// Page.produceCompilationCache. type ProduceCompilationCacheParams struct { Scripts []*CompilationCacheParams `json:"scripts"` } @@ -1577,67 +651,28 @@ type ProduceCompilationCacheParams struct { // Page.compilationCacheProduced. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-produceCompilationCache -// -// parameters: -// -// scripts -func ProduceCompilationCache(scripts []*CompilationCacheParams) *ProduceCompilationCacheParams { - return &ProduceCompilationCacheParams{ - Scripts: scripts, - } -} - -// Do executes Page.produceCompilationCache against the provided context. -func (p *ProduceCompilationCacheParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandProduceCompilationCache, p, nil) -} +var ProduceCompilationCache = cdp.Command[ProduceCompilationCacheParams, cdp.Empty]{Method: CommandProduceCompilationCache} -// AddCompilationCacheParams seeds compilation cache for given url. -// Compilation cache does not survive cross-process navigation. +// AddCompilationCacheParams are the parameters of the command +// Page.addCompilationCache. type AddCompilationCacheParams struct { URL string `json:"url"` - Data string `json:"data"` // Base64-encoded data + Data []byte `json:"data"` // Base64-encoded data } // AddCompilationCache seeds compilation cache for given url. Compilation // cache does not survive cross-process navigation. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-addCompilationCache -// -// parameters: -// -// url -// data - Base64-encoded data -func AddCompilationCache(url string, data string) *AddCompilationCacheParams { - return &AddCompilationCacheParams{ - URL: url, - Data: data, - } -} - -// Do executes Page.addCompilationCache against the provided context. -func (p *AddCompilationCacheParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandAddCompilationCache, p, nil) -} - -// ClearCompilationCacheParams clears seeded compilation cache. -type ClearCompilationCacheParams struct{} +var AddCompilationCache = cdp.Command[AddCompilationCacheParams, cdp.Empty]{Method: CommandAddCompilationCache} // ClearCompilationCache clears seeded compilation cache. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-clearCompilationCache -func ClearCompilationCache() *ClearCompilationCacheParams { - return &ClearCompilationCacheParams{} -} - -// Do executes Page.clearCompilationCache against the provided context. -func (p *ClearCompilationCacheParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClearCompilationCache, nil, nil) -} +var ClearCompilationCache = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandClearCompilationCache} -// SetSPCTransactionModeParams sets the Secure Payment Confirmation -// transaction mode. -// https://w3c.github.io/secure-payment-confirmation/#sctn-automation-set-spc-transaction-mode. +// SetSPCTransactionModeParams are the parameters of the command +// Page.setSPCTransactionMode. type SetSPCTransactionModeParams struct { Mode SetSPCTransactionModeMode `json:"mode"` } @@ -1647,23 +682,10 @@ type SetSPCTransactionModeParams struct { // https://w3c.github.io/secure-payment-confirmation/#sctn-automation-set-spc-transaction-mode. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setSPCTransactionMode -// -// parameters: -// -// mode -func SetSPCTransactionMode(mode SetSPCTransactionModeMode) *SetSPCTransactionModeParams { - return &SetSPCTransactionModeParams{ - Mode: mode, - } -} +var SetSPCTransactionMode = cdp.Command[SetSPCTransactionModeParams, cdp.Empty]{Method: CommandSetSPCTransactionMode} -// Do executes Page.setSPCTransactionMode against the provided context. -func (p *SetSPCTransactionModeParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetSPCTransactionMode, p, nil) -} - -// SetRPHRegistrationModeParams extensions for Custom Handlers API: -// https://html.spec.whatwg.org/multipage/system-state.html#rph-automation. +// SetRPHRegistrationModeParams are the parameters of the command +// Page.setRPHRegistrationMode. type SetRPHRegistrationModeParams struct { Mode SetRPHRegistrationModeMode `json:"mode"` } @@ -1672,22 +694,10 @@ type SetRPHRegistrationModeParams struct { // https://html.spec.whatwg.org/multipage/system-state.html#rph-automation. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setRPHRegistrationMode -// -// parameters: -// -// mode -func SetRPHRegistrationMode(mode SetRPHRegistrationModeMode) *SetRPHRegistrationModeParams { - return &SetRPHRegistrationModeParams{ - Mode: mode, - } -} - -// Do executes Page.setRPHRegistrationMode against the provided context. -func (p *SetRPHRegistrationModeParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetRPHRegistrationMode, p, nil) -} +var SetRPHRegistrationMode = cdp.Command[SetRPHRegistrationModeParams, cdp.Empty]{Method: CommandSetRPHRegistrationMode} -// GenerateTestReportParams generates a report for testing. +// GenerateTestReportParams are the parameters of the command +// Page.generateTestReport. type GenerateTestReportParams struct { Message string `json:"message"` // Message to be displayed in the report. Group string `json:"group,omitempty,omitzero"` // Specifies the endpoint group to deliver the report to. @@ -1696,51 +706,19 @@ type GenerateTestReportParams struct { // GenerateTestReport generates a report for testing. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-generateTestReport -// -// parameters: -// -// message - Message to be displayed in the report. -func GenerateTestReport(message string) *GenerateTestReportParams { - return &GenerateTestReportParams{ - Message: message, - } -} - -// WithGroup specifies the endpoint group to deliver the report to. -func (p GenerateTestReportParams) WithGroup(group string) *GenerateTestReportParams { - p.Group = group - return &p -} - -// Do executes Page.generateTestReport against the provided context. -func (p *GenerateTestReportParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandGenerateTestReport, p, nil) -} - -// WaitForDebuggerParams pauses page execution. Can be resumed using generic -// Runtime.runIfWaitingForDebugger. -type WaitForDebuggerParams struct{} +var GenerateTestReport = cdp.Command[GenerateTestReportParams, cdp.Empty]{Method: CommandGenerateTestReport} // WaitForDebugger pauses page execution. Can be resumed using generic // Runtime.runIfWaitingForDebugger. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-waitForDebugger -func WaitForDebugger() *WaitForDebuggerParams { - return &WaitForDebuggerParams{} -} +var WaitForDebugger = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandWaitForDebugger} -// Do executes Page.waitForDebugger against the provided context. -func (p *WaitForDebuggerParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandWaitForDebugger, nil, nil) -} - -// SetInterceptFileChooserDialogParams intercept file chooser requests and -// transfer control to protocol clients. When file chooser interception is -// enabled, native file chooser dialog is not shown. Instead, a protocol event -// Page.fileChooserOpened is emitted. +// SetInterceptFileChooserDialogParams are the parameters of the command +// Page.setInterceptFileChooserDialog. type SetInterceptFileChooserDialogParams struct { - Enabled bool `json:"enabled"` - Cancel bool `json:"cancel"` // If true, cancels the dialog by emitting relevant events (if any) in addition to not showing it if the interception is enabled (default: false). + Enabled bool `json:"enabled"` + Cancel *bool `json:"cancel,omitempty,omitzero"` // If true, cancels the dialog by emitting relevant events (if any) in addition to not showing it if the interception is enabled (default: false). } // SetInterceptFileChooserDialog intercept file chooser requests and transfer @@ -1749,35 +727,10 @@ type SetInterceptFileChooserDialogParams struct { // Page.fileChooserOpened is emitted. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setInterceptFileChooserDialog -// -// parameters: -// -// enabled -func SetInterceptFileChooserDialog(enabled bool) *SetInterceptFileChooserDialogParams { - return &SetInterceptFileChooserDialogParams{ - Enabled: enabled, - Cancel: false, - } -} - -// WithCancel if true, cancels the dialog by emitting relevant events (if -// any) in addition to not showing it if the interception is enabled (default: -// false). -func (p SetInterceptFileChooserDialogParams) WithCancel(cancel bool) *SetInterceptFileChooserDialogParams { - p.Cancel = cancel - return &p -} - -// Do executes Page.setInterceptFileChooserDialog against the provided context. -func (p *SetInterceptFileChooserDialogParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetInterceptFileChooserDialog, p, nil) -} +var SetInterceptFileChooserDialog = cdp.Command[SetInterceptFileChooserDialogParams, cdp.Empty]{Method: CommandSetInterceptFileChooserDialog} -// SetPrerenderingAllowedParams enable/disable prerendering manually. This -// command is a short-term solution for https://crbug.com/1440085. See -// https://docs.google.com/document/d/12HVmFxYj5Jc-eJr5OmWsa2bqTJsbgGLKI6ZIyx0_wpA -// for more details. TODO(https://crbug.com/1440085): Remove this once Puppeteer -// supports tab targets. +// SetPrerenderingAllowedParams are the parameters of the command +// Page.setPrerenderingAllowed. type SetPrerenderingAllowedParams struct { IsAllowed bool `json:"isAllowed"` } @@ -1789,72 +742,175 @@ type SetPrerenderingAllowedParams struct { // supports tab targets. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setPrerenderingAllowed -// -// parameters: -// -// isAllowed -func SetPrerenderingAllowed(isAllowed bool) *SetPrerenderingAllowedParams { - return &SetPrerenderingAllowedParams{ - IsAllowed: isAllowed, - } -} +var SetPrerenderingAllowed = cdp.Command[SetPrerenderingAllowedParams, cdp.Empty]{Method: CommandSetPrerenderingAllowed} -// Do executes Page.setPrerenderingAllowed against the provided context. -func (p *SetPrerenderingAllowedParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetPrerenderingAllowed, p, nil) +// GetAnnotatedPageContentParams are the parameters of the command +// Page.getAnnotatedPageContent. +type GetAnnotatedPageContentParams struct { + IncludeActionableInformation *bool `json:"includeActionableInformation,omitempty,omitzero"` // Whether to include actionable information. Defaults to true. } -// GetAnnotatedPageContentParams get the annotated page content for the main -// frame. This is an experimental command that is subject to change. -type GetAnnotatedPageContentParams struct { - IncludeActionableInformation bool `json:"includeActionableInformation"` // Whether to include actionable information. Defaults to true. +// GetAnnotatedPageContentResult is the result of the command +// Page.getAnnotatedPageContent. +type GetAnnotatedPageContentResult struct { + Content []byte `json:"content,omitempty,omitzero"` // The annotated page content as a base64 encoded protobuf. The format is defined by the AnnotatedPageContent message in components/optimization_guide/proto/features/common_quality_data.proto } // GetAnnotatedPageContent get the annotated page content for the main frame. // This is an experimental command that is subject to change. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getAnnotatedPageContent -// -// parameters: -func GetAnnotatedPageContent() *GetAnnotatedPageContentParams { - return &GetAnnotatedPageContentParams{ - IncludeActionableInformation: true, - } -} +var GetAnnotatedPageContent = cdp.Command[GetAnnotatedPageContentParams, GetAnnotatedPageContentResult]{Method: CommandGetAnnotatedPageContent} -// WithIncludeActionableInformation whether to include actionable -// information. Defaults to true. -func (p GetAnnotatedPageContentParams) WithIncludeActionableInformation(includeActionableInformation bool) *GetAnnotatedPageContentParams { - p.IncludeActionableInformation = includeActionableInformation - return &p +// SetInputVisualizationParams are the parameters of the command +// Page.setInputVisualization. +type SetInputVisualizationParams struct { + Clicks *bool `json:"clicks,omitempty,omitzero"` // Whether to enable click visualization. } -// GetAnnotatedPageContentReturns return values. -type GetAnnotatedPageContentReturns struct { - Content string `json:"content,omitempty,omitzero"` // The annotated page content as a base64 encoded protobuf. The format is defined by the AnnotatedPageContent message in components/optimization_guide/proto/features/common_quality_data.proto -} +// SetInputVisualization configures input visualization on the page. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setInputVisualization +var SetInputVisualization = cdp.Command[SetInputVisualizationParams, cdp.Empty]{Method: CommandSetInputVisualization} -// Do executes Page.getAnnotatedPageContent against the provided context. +// DomContentEventFired [no description]. // -// returns: +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-domContentEventFired +var DomContentEventFired = cdp.Event[EventDomContentEventFired]{Method: "Page.domContentEventFired"} + +// FileChooserOpened emitted only when page.interceptFileChooser is enabled. // -// content - The annotated page content as a base64 encoded protobuf. The format is defined by the AnnotatedPageContent message in components/optimization_guide/proto/features/common_quality_data.proto -func (p *GetAnnotatedPageContentParams) Do(ctx context.Context) (content []byte, err error) { - // execute - var res GetAnnotatedPageContentReturns - err = cdp.Execute(ctx, CommandGetAnnotatedPageContent, p, &res) - if err != nil { - return nil, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-fileChooserOpened +var FileChooserOpened = cdp.Event[EventFileChooserOpened]{Method: "Page.fileChooserOpened"} - // decode - var dec []byte - dec, err = base64.StdEncoding.DecodeString(res.Content) - if err != nil { - return nil, err - } - return dec, nil -} +// FrameAttached fired when frame has been attached to its parent. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-frameAttached +var FrameAttached = cdp.Event[EventFrameAttached]{Method: "Page.frameAttached"} + +// FrameDetached fired when frame has been detached from its parent. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-frameDetached +var FrameDetached = cdp.Event[EventFrameDetached]{Method: "Page.frameDetached"} + +// FrameSubtreeWillBeDetached fired before frame subtree is detached. Emitted +// before any frame of the subtree is actually detached. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-frameSubtreeWillBeDetached +var FrameSubtreeWillBeDetached = cdp.Event[EventFrameSubtreeWillBeDetached]{Method: "Page.frameSubtreeWillBeDetached"} + +// FrameNavigated fired once navigation of the frame has completed. Frame is +// now associated with the new loader. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-frameNavigated +var FrameNavigated = cdp.Event[EventFrameNavigated]{Method: "Page.frameNavigated"} + +// DocumentOpened fired when opening document to write to. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-documentOpened +var DocumentOpened = cdp.Event[EventDocumentOpened]{Method: "Page.documentOpened"} + +// FrameResized [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-frameResized +var FrameResized = cdp.Event[EventFrameResized]{Method: "Page.frameResized"} + +// FrameStartedNavigating fired when a navigation starts. This event is fired +// for both renderer-initiated and browser-initiated navigations. For +// renderer-initiated navigations, the event is fired after +// frameRequestedNavigation. Navigation may still be cancelled after the event +// is issued. Multiple events can be fired for a single navigation, for example, +// when a same-document navigation becomes a cross-document navigation (such as +// in the case of a frameset). +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-frameStartedNavigating +var FrameStartedNavigating = cdp.Event[EventFrameStartedNavigating]{Method: "Page.frameStartedNavigating"} + +// FrameRequestedNavigation fired when a renderer-initiated navigation is +// requested. Navigation may still be cancelled after the event is issued. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-frameRequestedNavigation +var FrameRequestedNavigation = cdp.Event[EventFrameRequestedNavigation]{Method: "Page.frameRequestedNavigation"} + +// FrameStartedLoading fired when frame has started loading. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-frameStartedLoading +var FrameStartedLoading = cdp.Event[EventFrameStartedLoading]{Method: "Page.frameStartedLoading"} + +// FrameStoppedLoading fired when frame has stopped loading. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-frameStoppedLoading +var FrameStoppedLoading = cdp.Event[EventFrameStoppedLoading]{Method: "Page.frameStoppedLoading"} + +// InterstitialHidden fired when interstitial page was hidden. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-interstitialHidden +var InterstitialHidden = cdp.Event[EventInterstitialHidden]{Method: "Page.interstitialHidden"} + +// InterstitialShown fired when interstitial page was shown. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-interstitialShown +var InterstitialShown = cdp.Event[EventInterstitialShown]{Method: "Page.interstitialShown"} + +// JavascriptDialogClosed fired when a JavaScript initiated dialog (alert, +// confirm, prompt, or onbeforeunload) has been closed. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-javascriptDialogClosed +var JavascriptDialogClosed = cdp.Event[EventJavascriptDialogClosed]{Method: "Page.javascriptDialogClosed"} + +// JavascriptDialogOpening fired when a JavaScript initiated dialog (alert, +// confirm, prompt, or onbeforeunload) is about to open. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-javascriptDialogOpening +var JavascriptDialogOpening = cdp.Event[EventJavascriptDialogOpening]{Method: "Page.javascriptDialogOpening"} + +// LifecycleEvent fired for lifecycle events (navigation, load, paint, etc) +// in the current target (including local frames). +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-lifecycleEvent +var LifecycleEvent = cdp.Event[EventLifecycleEvent]{Method: "Page.lifecycleEvent"} + +// BackForwardCacheNotUsed fired for failed bfcache history navigations if +// BackForwardCache feature is enabled. Do not assume any ordering with the +// Page.frameNavigated event. This event is fired only for main-frame history +// navigation where the document changes (non-same-document navigations), when +// bfcache navigation fails. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-backForwardCacheNotUsed +var BackForwardCacheNotUsed = cdp.Event[EventBackForwardCacheNotUsed]{Method: "Page.backForwardCacheNotUsed"} + +// LoadEventFired [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-loadEventFired +var LoadEventFired = cdp.Event[EventLoadEventFired]{Method: "Page.loadEventFired"} + +// NavigatedWithinDocument fired when same-document navigation happens, e.g. +// due to history API usage or anchor navigation. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-navigatedWithinDocument +var NavigatedWithinDocument = cdp.Event[EventNavigatedWithinDocument]{Method: "Page.navigatedWithinDocument"} + +// ScreencastFrame compressed image data requested by the startScreencast. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-screencastFrame +var ScreencastFrame = cdp.Event[EventScreencastFrame]{Method: "Page.screencastFrame"} + +// ScreencastVisibilityChanged fired when the page with currently enabled +// screencast was shown or hidden . +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-screencastVisibilityChanged +var ScreencastVisibilityChanged = cdp.Event[EventScreencastVisibilityChanged]{Method: "Page.screencastVisibilityChanged"} + +// WindowOpen fired when a new window is going to be opened, via +// window.open(), link click, form submission, etc. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-windowOpen +var WindowOpen = cdp.Event[EventWindowOpen]{Method: "Page.windowOpen"} + +// CompilationCacheProduced issued for every compilation cache generated. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-compilationCacheProduced +var CompilationCacheProduced = cdp.Event[EventCompilationCacheProduced]{Method: "Page.compilationCacheProduced"} // Command names. const ( @@ -1868,7 +924,10 @@ const ( CommandGetAppManifest = "Page.getAppManifest" CommandGetInstallabilityErrors = "Page.getInstallabilityErrors" CommandGetAppID = "Page.getAppId" + CommandGetSubApps = "Page.getSubApps" + CommandGetSiblingSubApps = "Page.getSiblingSubApps" CommandGetAdScriptAncestry = "Page.getAdScriptAncestry" + CommandGetSpellCheckCustomDictionary = "Page.getSpellCheckCustomDictionary" CommandGetFrameTree = "Page.getFrameTree" CommandGetLayoutMetrics = "Page.getLayoutMetrics" CommandGetNavigationHistory = "Page.getNavigationHistory" @@ -1892,6 +951,8 @@ const ( CommandSetDocumentContent = "Page.setDocumentContent" CommandSetLifecycleEventsEnabled = "Page.setLifecycleEventsEnabled" CommandStartScreencast = "Page.startScreencast" + CommandStartScreenRecording = "Page.startScreenRecording" + CommandStopScreenRecording = "Page.stopScreenRecording" CommandStopLoading = "Page.stopLoading" CommandCrash = "Page.crash" CommandClose = "Page.close" @@ -1907,4 +968,5 @@ const ( CommandSetInterceptFileChooserDialog = "Page.setInterceptFileChooserDialog" CommandSetPrerenderingAllowed = "Page.setPrerenderingAllowed" CommandGetAnnotatedPageContent = "Page.getAnnotatedPageContent" + CommandSetInputVisualization = "Page.setInputVisualization" ) diff --git a/vendor/github.com/chromedp/cdproto/page/types.go b/vendor/github.com/chromedp/cdproto/page/types.go index 557cee095..dfa44af40 100644 --- a/vendor/github.com/chromedp/cdproto/page/types.go +++ b/vendor/github.com/chromedp/cdproto/page/types.go @@ -1,11 +1,8 @@ -package page +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package page import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/network" ) @@ -25,347 +22,114 @@ func (t PermissionsPolicyFeature) String() string { // PermissionsPolicyFeature values. const ( - PermissionsPolicyFeatureAccelerometer PermissionsPolicyFeature = "accelerometer" - PermissionsPolicyFeatureAllScreensCapture PermissionsPolicyFeature = "all-screens-capture" - PermissionsPolicyFeatureAmbientLightSensor PermissionsPolicyFeature = "ambient-light-sensor" - PermissionsPolicyFeatureAriaNotify PermissionsPolicyFeature = "aria-notify" - PermissionsPolicyFeatureAutofill PermissionsPolicyFeature = "autofill" - PermissionsPolicyFeatureAutoplay PermissionsPolicyFeature = "autoplay" - PermissionsPolicyFeatureBluetooth PermissionsPolicyFeature = "bluetooth" - PermissionsPolicyFeatureBrowsingTopics PermissionsPolicyFeature = "browsing-topics" - PermissionsPolicyFeatureCamera PermissionsPolicyFeature = "camera" - PermissionsPolicyFeatureCapturedSurfaceControl PermissionsPolicyFeature = "captured-surface-control" - PermissionsPolicyFeatureChDpr PermissionsPolicyFeature = "ch-dpr" - PermissionsPolicyFeatureChDeviceMemory PermissionsPolicyFeature = "ch-device-memory" - PermissionsPolicyFeatureChDownlink PermissionsPolicyFeature = "ch-downlink" - PermissionsPolicyFeatureChEct PermissionsPolicyFeature = "ch-ect" - PermissionsPolicyFeatureChPrefersColorScheme PermissionsPolicyFeature = "ch-prefers-color-scheme" - PermissionsPolicyFeatureChPrefersReducedMotion PermissionsPolicyFeature = "ch-prefers-reduced-motion" - PermissionsPolicyFeatureChPrefersReducedTransparency PermissionsPolicyFeature = "ch-prefers-reduced-transparency" - PermissionsPolicyFeatureChRtt PermissionsPolicyFeature = "ch-rtt" - PermissionsPolicyFeatureChSaveData PermissionsPolicyFeature = "ch-save-data" - PermissionsPolicyFeatureChUa PermissionsPolicyFeature = "ch-ua" - PermissionsPolicyFeatureChUaArch PermissionsPolicyFeature = "ch-ua-arch" - PermissionsPolicyFeatureChUaBitness PermissionsPolicyFeature = "ch-ua-bitness" - PermissionsPolicyFeatureChUaHighEntropyValues PermissionsPolicyFeature = "ch-ua-high-entropy-values" - PermissionsPolicyFeatureChUaPlatform PermissionsPolicyFeature = "ch-ua-platform" - PermissionsPolicyFeatureChUaModel PermissionsPolicyFeature = "ch-ua-model" - PermissionsPolicyFeatureChUaMobile PermissionsPolicyFeature = "ch-ua-mobile" - PermissionsPolicyFeatureChUaFormFactors PermissionsPolicyFeature = "ch-ua-form-factors" - PermissionsPolicyFeatureChUaFullVersion PermissionsPolicyFeature = "ch-ua-full-version" - PermissionsPolicyFeatureChUaFullVersionList PermissionsPolicyFeature = "ch-ua-full-version-list" - PermissionsPolicyFeatureChUaPlatformVersion PermissionsPolicyFeature = "ch-ua-platform-version" - PermissionsPolicyFeatureChUaWow64 PermissionsPolicyFeature = "ch-ua-wow64" - PermissionsPolicyFeatureChViewportHeight PermissionsPolicyFeature = "ch-viewport-height" - PermissionsPolicyFeatureChViewportWidth PermissionsPolicyFeature = "ch-viewport-width" - PermissionsPolicyFeatureChWidth PermissionsPolicyFeature = "ch-width" - PermissionsPolicyFeatureClipboardRead PermissionsPolicyFeature = "clipboard-read" - PermissionsPolicyFeatureClipboardWrite PermissionsPolicyFeature = "clipboard-write" - PermissionsPolicyFeatureComputePressure PermissionsPolicyFeature = "compute-pressure" - PermissionsPolicyFeatureControlledFrame PermissionsPolicyFeature = "controlled-frame" - PermissionsPolicyFeatureCrossOriginIsolated PermissionsPolicyFeature = "cross-origin-isolated" - PermissionsPolicyFeatureDeferredFetch PermissionsPolicyFeature = "deferred-fetch" - PermissionsPolicyFeatureDeferredFetchMinimal PermissionsPolicyFeature = "deferred-fetch-minimal" - PermissionsPolicyFeatureDeviceAttributes PermissionsPolicyFeature = "device-attributes" - PermissionsPolicyFeatureDigitalCredentialsCreate PermissionsPolicyFeature = "digital-credentials-create" - PermissionsPolicyFeatureDigitalCredentialsGet PermissionsPolicyFeature = "digital-credentials-get" - PermissionsPolicyFeatureDirectSockets PermissionsPolicyFeature = "direct-sockets" - PermissionsPolicyFeatureDirectSocketsMulticast PermissionsPolicyFeature = "direct-sockets-multicast" - PermissionsPolicyFeatureDisplayCapture PermissionsPolicyFeature = "display-capture" - PermissionsPolicyFeatureDocumentDomain PermissionsPolicyFeature = "document-domain" - PermissionsPolicyFeatureEncryptedMedia PermissionsPolicyFeature = "encrypted-media" - PermissionsPolicyFeatureExecutionWhileOutOfViewport PermissionsPolicyFeature = "execution-while-out-of-viewport" - PermissionsPolicyFeatureExecutionWhileNotRendered PermissionsPolicyFeature = "execution-while-not-rendered" - PermissionsPolicyFeatureFocusWithoutUserActivation PermissionsPolicyFeature = "focus-without-user-activation" - PermissionsPolicyFeatureFullscreen PermissionsPolicyFeature = "fullscreen" - PermissionsPolicyFeatureFrobulate PermissionsPolicyFeature = "frobulate" - PermissionsPolicyFeatureGamepad PermissionsPolicyFeature = "gamepad" - PermissionsPolicyFeatureGeolocation PermissionsPolicyFeature = "geolocation" - PermissionsPolicyFeatureGyroscope PermissionsPolicyFeature = "gyroscope" - PermissionsPolicyFeatureHid PermissionsPolicyFeature = "hid" - PermissionsPolicyFeatureIdentityCredentialsGet PermissionsPolicyFeature = "identity-credentials-get" - PermissionsPolicyFeatureIdleDetection PermissionsPolicyFeature = "idle-detection" - PermissionsPolicyFeatureInterestCohort PermissionsPolicyFeature = "interest-cohort" - PermissionsPolicyFeatureJoinAdInterestGroup PermissionsPolicyFeature = "join-ad-interest-group" - PermissionsPolicyFeatureKeyboardMap PermissionsPolicyFeature = "keyboard-map" - PermissionsPolicyFeatureLanguageDetector PermissionsPolicyFeature = "language-detector" - PermissionsPolicyFeatureLanguageModel PermissionsPolicyFeature = "language-model" - PermissionsPolicyFeatureLocalFonts PermissionsPolicyFeature = "local-fonts" - PermissionsPolicyFeatureLocalNetwork PermissionsPolicyFeature = "local-network" - PermissionsPolicyFeatureLocalNetworkAccess PermissionsPolicyFeature = "local-network-access" - PermissionsPolicyFeatureLoopbackNetwork PermissionsPolicyFeature = "loopback-network" - PermissionsPolicyFeatureMagnetometer PermissionsPolicyFeature = "magnetometer" - PermissionsPolicyFeatureManualText PermissionsPolicyFeature = "manual-text" - PermissionsPolicyFeatureMediaPlaybackWhileNotVisible PermissionsPolicyFeature = "media-playback-while-not-visible" - PermissionsPolicyFeatureMicrophone PermissionsPolicyFeature = "microphone" - PermissionsPolicyFeatureMidi PermissionsPolicyFeature = "midi" - PermissionsPolicyFeatureOnDeviceSpeechRecognition PermissionsPolicyFeature = "on-device-speech-recognition" - PermissionsPolicyFeatureOtpCredentials PermissionsPolicyFeature = "otp-credentials" - PermissionsPolicyFeaturePayment PermissionsPolicyFeature = "payment" - PermissionsPolicyFeaturePictureInPicture PermissionsPolicyFeature = "picture-in-picture" - PermissionsPolicyFeaturePrivateAggregation PermissionsPolicyFeature = "private-aggregation" - PermissionsPolicyFeaturePrivateStateTokenIssuance PermissionsPolicyFeature = "private-state-token-issuance" - PermissionsPolicyFeaturePrivateStateTokenRedemption PermissionsPolicyFeature = "private-state-token-redemption" - PermissionsPolicyFeaturePublickeyCredentialsCreate PermissionsPolicyFeature = "publickey-credentials-create" - PermissionsPolicyFeaturePublickeyCredentialsGet PermissionsPolicyFeature = "publickey-credentials-get" - PermissionsPolicyFeatureRecordAdAuctionEvents PermissionsPolicyFeature = "record-ad-auction-events" - PermissionsPolicyFeatureRewriter PermissionsPolicyFeature = "rewriter" - PermissionsPolicyFeatureRunAdAuction PermissionsPolicyFeature = "run-ad-auction" - PermissionsPolicyFeatureScreenWakeLock PermissionsPolicyFeature = "screen-wake-lock" - PermissionsPolicyFeatureSerial PermissionsPolicyFeature = "serial" - PermissionsPolicyFeatureSharedStorage PermissionsPolicyFeature = "shared-storage" - PermissionsPolicyFeatureSharedStorageSelectURL PermissionsPolicyFeature = "shared-storage-select-url" - PermissionsPolicyFeatureSmartCard PermissionsPolicyFeature = "smart-card" - PermissionsPolicyFeatureSpeakerSelection PermissionsPolicyFeature = "speaker-selection" - PermissionsPolicyFeatureStorageAccess PermissionsPolicyFeature = "storage-access" - PermissionsPolicyFeatureSubApps PermissionsPolicyFeature = "sub-apps" - PermissionsPolicyFeatureSummarizer PermissionsPolicyFeature = "summarizer" - PermissionsPolicyFeatureSyncXhr PermissionsPolicyFeature = "sync-xhr" - PermissionsPolicyFeatureTools PermissionsPolicyFeature = "tools" - PermissionsPolicyFeatureTranslator PermissionsPolicyFeature = "translator" - PermissionsPolicyFeatureUnload PermissionsPolicyFeature = "unload" - PermissionsPolicyFeatureUsb PermissionsPolicyFeature = "usb" - PermissionsPolicyFeatureUsbUnrestricted PermissionsPolicyFeature = "usb-unrestricted" - PermissionsPolicyFeatureVerticalScroll PermissionsPolicyFeature = "vertical-scroll" - PermissionsPolicyFeatureWebAppInstallation PermissionsPolicyFeature = "web-app-installation" - PermissionsPolicyFeatureWebnn PermissionsPolicyFeature = "webnn" - PermissionsPolicyFeatureWebPrinting PermissionsPolicyFeature = "web-printing" - PermissionsPolicyFeatureWebShare PermissionsPolicyFeature = "web-share" - PermissionsPolicyFeatureWindowManagement PermissionsPolicyFeature = "window-management" - PermissionsPolicyFeatureWriter PermissionsPolicyFeature = "writer" - PermissionsPolicyFeatureXrSpatialTracking PermissionsPolicyFeature = "xr-spatial-tracking" + PermissionsPolicyFeatureAccelerometer PermissionsPolicyFeature = "accelerometer" + PermissionsPolicyFeatureAllScreensCapture PermissionsPolicyFeature = "all-screens-capture" + PermissionsPolicyFeatureAmbientLightSensor PermissionsPolicyFeature = "ambient-light-sensor" + PermissionsPolicyFeatureAriaNotify PermissionsPolicyFeature = "aria-notify" + PermissionsPolicyFeatureAutofill PermissionsPolicyFeature = "autofill" + PermissionsPolicyFeatureAutoplay PermissionsPolicyFeature = "autoplay" + PermissionsPolicyFeatureBluetooth PermissionsPolicyFeature = "bluetooth" + PermissionsPolicyFeatureBrowsingTopics PermissionsPolicyFeature = "browsing-topics" + PermissionsPolicyFeatureCamera PermissionsPolicyFeature = "camera" + PermissionsPolicyFeatureCapturedSurfaceControl PermissionsPolicyFeature = "captured-surface-control" + PermissionsPolicyFeatureChDpr PermissionsPolicyFeature = "ch-dpr" + PermissionsPolicyFeatureChDeviceMemory PermissionsPolicyFeature = "ch-device-memory" + PermissionsPolicyFeatureChDownlink PermissionsPolicyFeature = "ch-downlink" + PermissionsPolicyFeatureChEct PermissionsPolicyFeature = "ch-ect" + PermissionsPolicyFeatureChPrefersColorScheme PermissionsPolicyFeature = "ch-prefers-color-scheme" + PermissionsPolicyFeatureChPrefersReducedMotion PermissionsPolicyFeature = "ch-prefers-reduced-motion" + PermissionsPolicyFeatureChPrefersReducedTransparency PermissionsPolicyFeature = "ch-prefers-reduced-transparency" + PermissionsPolicyFeatureChRtt PermissionsPolicyFeature = "ch-rtt" + PermissionsPolicyFeatureChSaveData PermissionsPolicyFeature = "ch-save-data" + PermissionsPolicyFeatureChUa PermissionsPolicyFeature = "ch-ua" + PermissionsPolicyFeatureChUaArch PermissionsPolicyFeature = "ch-ua-arch" + PermissionsPolicyFeatureChUaBitness PermissionsPolicyFeature = "ch-ua-bitness" + PermissionsPolicyFeatureChUaHighEntropyValues PermissionsPolicyFeature = "ch-ua-high-entropy-values" + PermissionsPolicyFeatureChUaPlatform PermissionsPolicyFeature = "ch-ua-platform" + PermissionsPolicyFeatureChUaModel PermissionsPolicyFeature = "ch-ua-model" + PermissionsPolicyFeatureChUaMobile PermissionsPolicyFeature = "ch-ua-mobile" + PermissionsPolicyFeatureChUaFormFactors PermissionsPolicyFeature = "ch-ua-form-factors" + PermissionsPolicyFeatureChUaFullVersion PermissionsPolicyFeature = "ch-ua-full-version" + PermissionsPolicyFeatureChUaFullVersionList PermissionsPolicyFeature = "ch-ua-full-version-list" + PermissionsPolicyFeatureChUaPlatformVersion PermissionsPolicyFeature = "ch-ua-platform-version" + PermissionsPolicyFeatureChUaWow64 PermissionsPolicyFeature = "ch-ua-wow64" + PermissionsPolicyFeatureChViewportHeight PermissionsPolicyFeature = "ch-viewport-height" + PermissionsPolicyFeatureChViewportWidth PermissionsPolicyFeature = "ch-viewport-width" + PermissionsPolicyFeatureChWidth PermissionsPolicyFeature = "ch-width" + PermissionsPolicyFeatureClipboardRead PermissionsPolicyFeature = "clipboard-read" + PermissionsPolicyFeatureClipboardWrite PermissionsPolicyFeature = "clipboard-write" + PermissionsPolicyFeatureComputePressure PermissionsPolicyFeature = "compute-pressure" + PermissionsPolicyFeatureControlledFrame PermissionsPolicyFeature = "controlled-frame" + PermissionsPolicyFeatureCrossOriginIsolated PermissionsPolicyFeature = "cross-origin-isolated" + PermissionsPolicyFeatureDeferredFetch PermissionsPolicyFeature = "deferred-fetch" + PermissionsPolicyFeatureDeferredFetchMinimal PermissionsPolicyFeature = "deferred-fetch-minimal" + PermissionsPolicyFeatureDeviceAttributes PermissionsPolicyFeature = "device-attributes" + PermissionsPolicyFeatureDigitalCredentialsCreate PermissionsPolicyFeature = "digital-credentials-create" + PermissionsPolicyFeatureDigitalCredentialsGet PermissionsPolicyFeature = "digital-credentials-get" + PermissionsPolicyFeatureDirectSockets PermissionsPolicyFeature = "direct-sockets" + PermissionsPolicyFeatureDirectSocketsMulticast PermissionsPolicyFeature = "direct-sockets-multicast" + PermissionsPolicyFeatureDisplayCapture PermissionsPolicyFeature = "display-capture" + PermissionsPolicyFeatureDocumentDomain PermissionsPolicyFeature = "document-domain" + PermissionsPolicyFeatureEncryptedMedia PermissionsPolicyFeature = "encrypted-media" + PermissionsPolicyFeatureExecutionWhileOutOfViewport PermissionsPolicyFeature = "execution-while-out-of-viewport" + PermissionsPolicyFeatureExecutionWhileNotRendered PermissionsPolicyFeature = "execution-while-not-rendered" + PermissionsPolicyFeatureFocusWithoutUserActivation PermissionsPolicyFeature = "focus-without-user-activation" + PermissionsPolicyFeatureFullscreen PermissionsPolicyFeature = "fullscreen" + PermissionsPolicyFeatureFrobulate PermissionsPolicyFeature = "frobulate" + PermissionsPolicyFeatureGamepad PermissionsPolicyFeature = "gamepad" + PermissionsPolicyFeatureGeolocation PermissionsPolicyFeature = "geolocation" + PermissionsPolicyFeatureGyroscope PermissionsPolicyFeature = "gyroscope" + PermissionsPolicyFeatureHaptics PermissionsPolicyFeature = "haptics" + PermissionsPolicyFeatureHid PermissionsPolicyFeature = "hid" + PermissionsPolicyFeatureIdentityCredentialsGet PermissionsPolicyFeature = "identity-credentials-get" + PermissionsPolicyFeatureIdleDetection PermissionsPolicyFeature = "idle-detection" + PermissionsPolicyFeatureInterestCohort PermissionsPolicyFeature = "interest-cohort" + PermissionsPolicyFeatureKeyboardMap PermissionsPolicyFeature = "keyboard-map" + PermissionsPolicyFeatureLanguageDetector PermissionsPolicyFeature = "language-detector" + PermissionsPolicyFeatureLanguageModel PermissionsPolicyFeature = "language-model" + PermissionsPolicyFeatureLocalFonts PermissionsPolicyFeature = "local-fonts" + PermissionsPolicyFeatureLocalNetwork PermissionsPolicyFeature = "local-network" + PermissionsPolicyFeatureLocalNetworkAccess PermissionsPolicyFeature = "local-network-access" + PermissionsPolicyFeatureLoopbackNetwork PermissionsPolicyFeature = "loopback-network" + PermissionsPolicyFeatureMagnetometer PermissionsPolicyFeature = "magnetometer" + PermissionsPolicyFeatureManualText PermissionsPolicyFeature = "manual-text" + PermissionsPolicyFeatureMediaPlaybackWhileNotVisible PermissionsPolicyFeature = "media-playback-while-not-visible" + PermissionsPolicyFeatureMicrophone PermissionsPolicyFeature = "microphone" + PermissionsPolicyFeatureMidi PermissionsPolicyFeature = "midi" + PermissionsPolicyFeatureOnDeviceSpeechRecognition PermissionsPolicyFeature = "on-device-speech-recognition" + PermissionsPolicyFeatureOtpCredentials PermissionsPolicyFeature = "otp-credentials" + PermissionsPolicyFeaturePayment PermissionsPolicyFeature = "payment" + PermissionsPolicyFeaturePictureInPicture PermissionsPolicyFeature = "picture-in-picture" + PermissionsPolicyFeaturePrivateStateTokenIssuance PermissionsPolicyFeature = "private-state-token-issuance" + PermissionsPolicyFeaturePrivateStateTokenRedemption PermissionsPolicyFeature = "private-state-token-redemption" + PermissionsPolicyFeaturePublickeyCredentialsCreate PermissionsPolicyFeature = "publickey-credentials-create" + PermissionsPolicyFeaturePublickeyCredentialsGet PermissionsPolicyFeature = "publickey-credentials-get" + PermissionsPolicyFeaturePublickeyCredentialsRemoteClientDataJSON PermissionsPolicyFeature = "publickey-credentials-remote-client-data-json" + PermissionsPolicyFeatureRewriter PermissionsPolicyFeature = "rewriter" + PermissionsPolicyFeatureScreenWakeLock PermissionsPolicyFeature = "screen-wake-lock" + PermissionsPolicyFeatureSerial PermissionsPolicyFeature = "serial" + PermissionsPolicyFeatureSmartCard PermissionsPolicyFeature = "smart-card" + PermissionsPolicyFeatureSpeakerSelection PermissionsPolicyFeature = "speaker-selection" + PermissionsPolicyFeatureStorageAccess PermissionsPolicyFeature = "storage-access" + PermissionsPolicyFeatureSubApps PermissionsPolicyFeature = "sub-apps" + PermissionsPolicyFeatureSummarizer PermissionsPolicyFeature = "summarizer" + PermissionsPolicyFeatureSyncXhr PermissionsPolicyFeature = "sync-xhr" + PermissionsPolicyFeatureTools PermissionsPolicyFeature = "tools" + PermissionsPolicyFeatureTranslator PermissionsPolicyFeature = "translator" + PermissionsPolicyFeatureUnboundedElement PermissionsPolicyFeature = "unbounded-element" + PermissionsPolicyFeatureUnload PermissionsPolicyFeature = "unload" + PermissionsPolicyFeatureUsb PermissionsPolicyFeature = "usb" + PermissionsPolicyFeatureUsbUnrestricted PermissionsPolicyFeature = "usb-unrestricted" + PermissionsPolicyFeatureVerticalScroll PermissionsPolicyFeature = "vertical-scroll" + PermissionsPolicyFeatureWebAppInstallation PermissionsPolicyFeature = "web-app-installation" + PermissionsPolicyFeatureWebnn PermissionsPolicyFeature = "webnn" + PermissionsPolicyFeatureWebPrinting PermissionsPolicyFeature = "web-printing" + PermissionsPolicyFeatureWebShare PermissionsPolicyFeature = "web-share" + PermissionsPolicyFeatureWindowManagement PermissionsPolicyFeature = "window-management" + PermissionsPolicyFeatureWriter PermissionsPolicyFeature = "writer" + PermissionsPolicyFeatureXrSpatialTracking PermissionsPolicyFeature = "xr-spatial-tracking" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *PermissionsPolicyFeature) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch PermissionsPolicyFeature(s) { - case PermissionsPolicyFeatureAccelerometer: - *t = PermissionsPolicyFeatureAccelerometer - case PermissionsPolicyFeatureAllScreensCapture: - *t = PermissionsPolicyFeatureAllScreensCapture - case PermissionsPolicyFeatureAmbientLightSensor: - *t = PermissionsPolicyFeatureAmbientLightSensor - case PermissionsPolicyFeatureAriaNotify: - *t = PermissionsPolicyFeatureAriaNotify - case PermissionsPolicyFeatureAutofill: - *t = PermissionsPolicyFeatureAutofill - case PermissionsPolicyFeatureAutoplay: - *t = PermissionsPolicyFeatureAutoplay - case PermissionsPolicyFeatureBluetooth: - *t = PermissionsPolicyFeatureBluetooth - case PermissionsPolicyFeatureBrowsingTopics: - *t = PermissionsPolicyFeatureBrowsingTopics - case PermissionsPolicyFeatureCamera: - *t = PermissionsPolicyFeatureCamera - case PermissionsPolicyFeatureCapturedSurfaceControl: - *t = PermissionsPolicyFeatureCapturedSurfaceControl - case PermissionsPolicyFeatureChDpr: - *t = PermissionsPolicyFeatureChDpr - case PermissionsPolicyFeatureChDeviceMemory: - *t = PermissionsPolicyFeatureChDeviceMemory - case PermissionsPolicyFeatureChDownlink: - *t = PermissionsPolicyFeatureChDownlink - case PermissionsPolicyFeatureChEct: - *t = PermissionsPolicyFeatureChEct - case PermissionsPolicyFeatureChPrefersColorScheme: - *t = PermissionsPolicyFeatureChPrefersColorScheme - case PermissionsPolicyFeatureChPrefersReducedMotion: - *t = PermissionsPolicyFeatureChPrefersReducedMotion - case PermissionsPolicyFeatureChPrefersReducedTransparency: - *t = PermissionsPolicyFeatureChPrefersReducedTransparency - case PermissionsPolicyFeatureChRtt: - *t = PermissionsPolicyFeatureChRtt - case PermissionsPolicyFeatureChSaveData: - *t = PermissionsPolicyFeatureChSaveData - case PermissionsPolicyFeatureChUa: - *t = PermissionsPolicyFeatureChUa - case PermissionsPolicyFeatureChUaArch: - *t = PermissionsPolicyFeatureChUaArch - case PermissionsPolicyFeatureChUaBitness: - *t = PermissionsPolicyFeatureChUaBitness - case PermissionsPolicyFeatureChUaHighEntropyValues: - *t = PermissionsPolicyFeatureChUaHighEntropyValues - case PermissionsPolicyFeatureChUaPlatform: - *t = PermissionsPolicyFeatureChUaPlatform - case PermissionsPolicyFeatureChUaModel: - *t = PermissionsPolicyFeatureChUaModel - case PermissionsPolicyFeatureChUaMobile: - *t = PermissionsPolicyFeatureChUaMobile - case PermissionsPolicyFeatureChUaFormFactors: - *t = PermissionsPolicyFeatureChUaFormFactors - case PermissionsPolicyFeatureChUaFullVersion: - *t = PermissionsPolicyFeatureChUaFullVersion - case PermissionsPolicyFeatureChUaFullVersionList: - *t = PermissionsPolicyFeatureChUaFullVersionList - case PermissionsPolicyFeatureChUaPlatformVersion: - *t = PermissionsPolicyFeatureChUaPlatformVersion - case PermissionsPolicyFeatureChUaWow64: - *t = PermissionsPolicyFeatureChUaWow64 - case PermissionsPolicyFeatureChViewportHeight: - *t = PermissionsPolicyFeatureChViewportHeight - case PermissionsPolicyFeatureChViewportWidth: - *t = PermissionsPolicyFeatureChViewportWidth - case PermissionsPolicyFeatureChWidth: - *t = PermissionsPolicyFeatureChWidth - case PermissionsPolicyFeatureClipboardRead: - *t = PermissionsPolicyFeatureClipboardRead - case PermissionsPolicyFeatureClipboardWrite: - *t = PermissionsPolicyFeatureClipboardWrite - case PermissionsPolicyFeatureComputePressure: - *t = PermissionsPolicyFeatureComputePressure - case PermissionsPolicyFeatureControlledFrame: - *t = PermissionsPolicyFeatureControlledFrame - case PermissionsPolicyFeatureCrossOriginIsolated: - *t = PermissionsPolicyFeatureCrossOriginIsolated - case PermissionsPolicyFeatureDeferredFetch: - *t = PermissionsPolicyFeatureDeferredFetch - case PermissionsPolicyFeatureDeferredFetchMinimal: - *t = PermissionsPolicyFeatureDeferredFetchMinimal - case PermissionsPolicyFeatureDeviceAttributes: - *t = PermissionsPolicyFeatureDeviceAttributes - case PermissionsPolicyFeatureDigitalCredentialsCreate: - *t = PermissionsPolicyFeatureDigitalCredentialsCreate - case PermissionsPolicyFeatureDigitalCredentialsGet: - *t = PermissionsPolicyFeatureDigitalCredentialsGet - case PermissionsPolicyFeatureDirectSockets: - *t = PermissionsPolicyFeatureDirectSockets - case PermissionsPolicyFeatureDirectSocketsMulticast: - *t = PermissionsPolicyFeatureDirectSocketsMulticast - case PermissionsPolicyFeatureDisplayCapture: - *t = PermissionsPolicyFeatureDisplayCapture - case PermissionsPolicyFeatureDocumentDomain: - *t = PermissionsPolicyFeatureDocumentDomain - case PermissionsPolicyFeatureEncryptedMedia: - *t = PermissionsPolicyFeatureEncryptedMedia - case PermissionsPolicyFeatureExecutionWhileOutOfViewport: - *t = PermissionsPolicyFeatureExecutionWhileOutOfViewport - case PermissionsPolicyFeatureExecutionWhileNotRendered: - *t = PermissionsPolicyFeatureExecutionWhileNotRendered - case PermissionsPolicyFeatureFocusWithoutUserActivation: - *t = PermissionsPolicyFeatureFocusWithoutUserActivation - case PermissionsPolicyFeatureFullscreen: - *t = PermissionsPolicyFeatureFullscreen - case PermissionsPolicyFeatureFrobulate: - *t = PermissionsPolicyFeatureFrobulate - case PermissionsPolicyFeatureGamepad: - *t = PermissionsPolicyFeatureGamepad - case PermissionsPolicyFeatureGeolocation: - *t = PermissionsPolicyFeatureGeolocation - case PermissionsPolicyFeatureGyroscope: - *t = PermissionsPolicyFeatureGyroscope - case PermissionsPolicyFeatureHid: - *t = PermissionsPolicyFeatureHid - case PermissionsPolicyFeatureIdentityCredentialsGet: - *t = PermissionsPolicyFeatureIdentityCredentialsGet - case PermissionsPolicyFeatureIdleDetection: - *t = PermissionsPolicyFeatureIdleDetection - case PermissionsPolicyFeatureInterestCohort: - *t = PermissionsPolicyFeatureInterestCohort - case PermissionsPolicyFeatureJoinAdInterestGroup: - *t = PermissionsPolicyFeatureJoinAdInterestGroup - case PermissionsPolicyFeatureKeyboardMap: - *t = PermissionsPolicyFeatureKeyboardMap - case PermissionsPolicyFeatureLanguageDetector: - *t = PermissionsPolicyFeatureLanguageDetector - case PermissionsPolicyFeatureLanguageModel: - *t = PermissionsPolicyFeatureLanguageModel - case PermissionsPolicyFeatureLocalFonts: - *t = PermissionsPolicyFeatureLocalFonts - case PermissionsPolicyFeatureLocalNetwork: - *t = PermissionsPolicyFeatureLocalNetwork - case PermissionsPolicyFeatureLocalNetworkAccess: - *t = PermissionsPolicyFeatureLocalNetworkAccess - case PermissionsPolicyFeatureLoopbackNetwork: - *t = PermissionsPolicyFeatureLoopbackNetwork - case PermissionsPolicyFeatureMagnetometer: - *t = PermissionsPolicyFeatureMagnetometer - case PermissionsPolicyFeatureManualText: - *t = PermissionsPolicyFeatureManualText - case PermissionsPolicyFeatureMediaPlaybackWhileNotVisible: - *t = PermissionsPolicyFeatureMediaPlaybackWhileNotVisible - case PermissionsPolicyFeatureMicrophone: - *t = PermissionsPolicyFeatureMicrophone - case PermissionsPolicyFeatureMidi: - *t = PermissionsPolicyFeatureMidi - case PermissionsPolicyFeatureOnDeviceSpeechRecognition: - *t = PermissionsPolicyFeatureOnDeviceSpeechRecognition - case PermissionsPolicyFeatureOtpCredentials: - *t = PermissionsPolicyFeatureOtpCredentials - case PermissionsPolicyFeaturePayment: - *t = PermissionsPolicyFeaturePayment - case PermissionsPolicyFeaturePictureInPicture: - *t = PermissionsPolicyFeaturePictureInPicture - case PermissionsPolicyFeaturePrivateAggregation: - *t = PermissionsPolicyFeaturePrivateAggregation - case PermissionsPolicyFeaturePrivateStateTokenIssuance: - *t = PermissionsPolicyFeaturePrivateStateTokenIssuance - case PermissionsPolicyFeaturePrivateStateTokenRedemption: - *t = PermissionsPolicyFeaturePrivateStateTokenRedemption - case PermissionsPolicyFeaturePublickeyCredentialsCreate: - *t = PermissionsPolicyFeaturePublickeyCredentialsCreate - case PermissionsPolicyFeaturePublickeyCredentialsGet: - *t = PermissionsPolicyFeaturePublickeyCredentialsGet - case PermissionsPolicyFeatureRecordAdAuctionEvents: - *t = PermissionsPolicyFeatureRecordAdAuctionEvents - case PermissionsPolicyFeatureRewriter: - *t = PermissionsPolicyFeatureRewriter - case PermissionsPolicyFeatureRunAdAuction: - *t = PermissionsPolicyFeatureRunAdAuction - case PermissionsPolicyFeatureScreenWakeLock: - *t = PermissionsPolicyFeatureScreenWakeLock - case PermissionsPolicyFeatureSerial: - *t = PermissionsPolicyFeatureSerial - case PermissionsPolicyFeatureSharedStorage: - *t = PermissionsPolicyFeatureSharedStorage - case PermissionsPolicyFeatureSharedStorageSelectURL: - *t = PermissionsPolicyFeatureSharedStorageSelectURL - case PermissionsPolicyFeatureSmartCard: - *t = PermissionsPolicyFeatureSmartCard - case PermissionsPolicyFeatureSpeakerSelection: - *t = PermissionsPolicyFeatureSpeakerSelection - case PermissionsPolicyFeatureStorageAccess: - *t = PermissionsPolicyFeatureStorageAccess - case PermissionsPolicyFeatureSubApps: - *t = PermissionsPolicyFeatureSubApps - case PermissionsPolicyFeatureSummarizer: - *t = PermissionsPolicyFeatureSummarizer - case PermissionsPolicyFeatureSyncXhr: - *t = PermissionsPolicyFeatureSyncXhr - case PermissionsPolicyFeatureTools: - *t = PermissionsPolicyFeatureTools - case PermissionsPolicyFeatureTranslator: - *t = PermissionsPolicyFeatureTranslator - case PermissionsPolicyFeatureUnload: - *t = PermissionsPolicyFeatureUnload - case PermissionsPolicyFeatureUsb: - *t = PermissionsPolicyFeatureUsb - case PermissionsPolicyFeatureUsbUnrestricted: - *t = PermissionsPolicyFeatureUsbUnrestricted - case PermissionsPolicyFeatureVerticalScroll: - *t = PermissionsPolicyFeatureVerticalScroll - case PermissionsPolicyFeatureWebAppInstallation: - *t = PermissionsPolicyFeatureWebAppInstallation - case PermissionsPolicyFeatureWebnn: - *t = PermissionsPolicyFeatureWebnn - case PermissionsPolicyFeatureWebPrinting: - *t = PermissionsPolicyFeatureWebPrinting - case PermissionsPolicyFeatureWebShare: - *t = PermissionsPolicyFeatureWebShare - case PermissionsPolicyFeatureWindowManagement: - *t = PermissionsPolicyFeatureWindowManagement - case PermissionsPolicyFeatureWriter: - *t = PermissionsPolicyFeatureWriter - case PermissionsPolicyFeatureXrSpatialTracking: - *t = PermissionsPolicyFeatureXrSpatialTracking - default: - return fmt.Errorf("unknown PermissionsPolicyFeature value: %v", s) - } - return nil -} - // PermissionsPolicyBlockReason reason for a permissions policy feature to be // disabled. // @@ -385,26 +149,6 @@ const ( PermissionsPolicyBlockReasonInIsolatedApp PermissionsPolicyBlockReason = "InIsolatedApp" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *PermissionsPolicyBlockReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch PermissionsPolicyBlockReason(s) { - case PermissionsPolicyBlockReasonHeader: - *t = PermissionsPolicyBlockReasonHeader - case PermissionsPolicyBlockReasonIframeAttribute: - *t = PermissionsPolicyBlockReasonIframeAttribute - case PermissionsPolicyBlockReasonInFencedFrameTree: - *t = PermissionsPolicyBlockReasonInFencedFrameTree - case PermissionsPolicyBlockReasonInIsolatedApp: - *t = PermissionsPolicyBlockReasonInIsolatedApp - default: - return fmt.Errorf("unknown PermissionsPolicyBlockReason value: %v", s) - } - return nil -} - // PermissionsPolicyBlockLocator [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-PermissionsPolicyBlockLocator @@ -429,7 +173,7 @@ type FrameResource struct { URL string `json:"url"` // Resource URL. Type network.ResourceType `json:"type"` // Type of this resource. MimeType string `json:"mimeType"` // Resource mimeType as determined by the browser. - LastModified *cdp.TimeSinceEpoch `json:"lastModified,omitempty,omitzero"` // last-modified timestamp as reported by server. + LastModified cdp.TimeSinceEpoch `json:"lastModified,omitempty,omitzero"` // last-modified timestamp as reported by server. ContentSize float64 `json:"contentSize,omitempty,omitzero"` // Resource content size. Failed bool `json:"failed"` // True if the resource failed to load. Canceled bool `json:"canceled"` // True if the resource was canceled during loading. @@ -490,44 +234,6 @@ const ( TransitionTypeOther TransitionType = "other" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *TransitionType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch TransitionType(s) { - case TransitionTypeLink: - *t = TransitionTypeLink - case TransitionTypeTyped: - *t = TransitionTypeTyped - case TransitionTypeAddressBar: - *t = TransitionTypeAddressBar - case TransitionTypeAutoBookmark: - *t = TransitionTypeAutoBookmark - case TransitionTypeAutoSubframe: - *t = TransitionTypeAutoSubframe - case TransitionTypeManualSubframe: - *t = TransitionTypeManualSubframe - case TransitionTypeGenerated: - *t = TransitionTypeGenerated - case TransitionTypeAutoToplevel: - *t = TransitionTypeAutoToplevel - case TransitionTypeFormSubmit: - *t = TransitionTypeFormSubmit - case TransitionTypeReload: - *t = TransitionTypeReload - case TransitionTypeKeyword: - *t = TransitionTypeKeyword - case TransitionTypeKeywordGenerated: - *t = TransitionTypeKeywordGenerated - case TransitionTypeOther: - *t = TransitionTypeOther - default: - return fmt.Errorf("unknown TransitionType value: %v", s) - } - return nil -} - // NavigationEntry navigation history entry. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-NavigationEntry @@ -543,13 +249,14 @@ type NavigationEntry struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-ScreencastFrameMetadata type ScreencastFrameMetadata struct { - OffsetTop float64 `json:"offsetTop"` // Top offset in DIP. - PageScaleFactor float64 `json:"pageScaleFactor"` // Page scale factor. - DeviceWidth float64 `json:"deviceWidth"` // Device screen width in DIP. - DeviceHeight float64 `json:"deviceHeight"` // Device screen height in DIP. - ScrollOffsetX float64 `json:"scrollOffsetX"` // Position of horizontal scroll in CSS pixels. - ScrollOffsetY float64 `json:"scrollOffsetY"` // Position of vertical scroll in CSS pixels. - Timestamp *cdp.TimeSinceEpoch `json:"timestamp,omitempty,omitzero"` // Frame swap timestamp. + OffsetTop float64 `json:"offsetTop"` // Top offset in DIP. + PageScaleFactor float64 `json:"pageScaleFactor"` // Page scale factor. + DeviceWidth float64 `json:"deviceWidth"` // Device screen width in DIP. + DeviceHeight float64 `json:"deviceHeight"` // Device screen height in DIP. + ScrollOffsetX float64 `json:"scrollOffsetX"` // Position of horizontal scroll in CSS pixels. + ScrollOffsetY float64 `json:"scrollOffsetY"` // Position of vertical scroll in CSS pixels. + Timestamp cdp.TimeSinceEpoch `json:"timestamp,omitempty,omitzero"` // Frame swap timestamp. + MonotonicTimestamp cdp.MonotonicTime `json:"monotonicTimestamp,omitempty,omitzero"` // Frame swap timestamp as monotonic time. } // DialogType javascript dialog type. @@ -570,26 +277,6 @@ const ( DialogTypeBeforeunload DialogType = "beforeunload" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DialogType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DialogType(s) { - case DialogTypeAlert: - *t = DialogTypeAlert - case DialogTypeConfirm: - *t = DialogTypeConfirm - case DialogTypePrompt: - *t = DialogTypePrompt - case DialogTypeBeforeunload: - *t = DialogTypeBeforeunload - default: - return fmt.Errorf("unknown DialogType value: %v", s) - } - return nil -} - // AppManifestError error while paring app manifest. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-AppManifestError @@ -695,38 +382,6 @@ const ( ClientNavigationReasonScriptInitiated ClientNavigationReason = "scriptInitiated" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ClientNavigationReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ClientNavigationReason(s) { - case ClientNavigationReasonAnchorClick: - *t = ClientNavigationReasonAnchorClick - case ClientNavigationReasonFormSubmissionGet: - *t = ClientNavigationReasonFormSubmissionGet - case ClientNavigationReasonFormSubmissionPost: - *t = ClientNavigationReasonFormSubmissionPost - case ClientNavigationReasonHTTPHeaderRefresh: - *t = ClientNavigationReasonHTTPHeaderRefresh - case ClientNavigationReasonInitialFrameNavigation: - *t = ClientNavigationReasonInitialFrameNavigation - case ClientNavigationReasonMetaTagRefresh: - *t = ClientNavigationReasonMetaTagRefresh - case ClientNavigationReasonOther: - *t = ClientNavigationReasonOther - case ClientNavigationReasonPageBlockInterstitial: - *t = ClientNavigationReasonPageBlockInterstitial - case ClientNavigationReasonReload: - *t = ClientNavigationReasonReload - case ClientNavigationReasonScriptInitiated: - *t = ClientNavigationReasonScriptInitiated - default: - return fmt.Errorf("unknown ClientNavigationReason value: %v", s) - } - return nil -} - // ClientNavigationDisposition [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-ClientNavigationDisposition @@ -745,26 +400,6 @@ const ( ClientNavigationDispositionDownload ClientNavigationDisposition = "download" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ClientNavigationDisposition) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ClientNavigationDisposition(s) { - case ClientNavigationDispositionCurrentTab: - *t = ClientNavigationDispositionCurrentTab - case ClientNavigationDispositionNewTab: - *t = ClientNavigationDispositionNewTab - case ClientNavigationDispositionNewWindow: - *t = ClientNavigationDispositionNewWindow - case ClientNavigationDispositionDownload: - *t = ClientNavigationDispositionDownload - default: - return fmt.Errorf("unknown ClientNavigationDisposition value: %v", s) - } - return nil -} - // InstallabilityErrorArgument [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-InstallabilityErrorArgument @@ -803,34 +438,6 @@ const ( ReferrerPolicyUnsafeURL ReferrerPolicy = "unsafeUrl" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ReferrerPolicy) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ReferrerPolicy(s) { - case ReferrerPolicyNoReferrer: - *t = ReferrerPolicyNoReferrer - case ReferrerPolicyNoReferrerWhenDowngrade: - *t = ReferrerPolicyNoReferrerWhenDowngrade - case ReferrerPolicyOrigin: - *t = ReferrerPolicyOrigin - case ReferrerPolicyOriginWhenCrossOrigin: - *t = ReferrerPolicyOriginWhenCrossOrigin - case ReferrerPolicySameOrigin: - *t = ReferrerPolicySameOrigin - case ReferrerPolicyStrictOrigin: - *t = ReferrerPolicyStrictOrigin - case ReferrerPolicyStrictOriginWhenCrossOrigin: - *t = ReferrerPolicyStrictOriginWhenCrossOrigin - case ReferrerPolicyUnsafeURL: - *t = ReferrerPolicyUnsafeURL - default: - return fmt.Errorf("unknown ReferrerPolicy value: %v", s) - } - return nil -} - // CompilationCacheParams per-script compilation cache parameters for // Page.produceCompilationCache. // @@ -852,11 +459,10 @@ type FileFilter struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-FileHandler type FileHandler struct { - Action string `json:"action"` - Name string `json:"name"` - Icons []*ImageResource `json:"icons,omitempty,omitzero"` - Accepts []*FileFilter `json:"accepts,omitempty,omitzero"` // Mimic a map, name is the key, accepts is the value. - LaunchType string `json:"launchType"` // Won't repeat the enums, using string for easy comparison. Same as the other enums below. + Action string `json:"action"` + Name string `json:"name"` + Accepts []*FileFilter `json:"accepts,omitempty,omitzero"` // Mimic a map, name is the key, accepts is the value. + LaunchType string `json:"launchType"` // Won't repeat the enums, using string for easy comparison. Same as the other enums below. } // ImageResource the image definition used in both icon and screenshot. @@ -958,6 +564,16 @@ type WebAppManifest struct { ThemeColor string `json:"themeColor,omitempty,omitzero"` } +// SubApp [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-SubApp +type SubApp struct { + Name string `json:"name"` // Display name of the sub-app. + Scope string `json:"scope"` // Scope of the sub-app. + ManifestID string `json:"manifestId"` // Manifest id of the sub-app. + StartURL string `json:"startUrl"` // Start URL of the sub-app. +} + // NavigationType the type of a frameNavigated event. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-NavigationType @@ -974,22 +590,6 @@ const ( NavigationTypeBackForwardCacheRestore NavigationType = "BackForwardCacheRestore" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *NavigationType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch NavigationType(s) { - case NavigationTypeNavigation: - *t = NavigationTypeNavigation - case NavigationTypeBackForwardCacheRestore: - *t = NavigationTypeBackForwardCacheRestore - default: - return fmt.Errorf("unknown NavigationType value: %v", s) - } - return nil -} - // BackForwardCacheNotRestoredReason list of not restored reasons for // back-forward cache. // @@ -1146,6 +746,7 @@ const ( BackForwardCacheNotRestoredReasonEmbedderExtensionMessagingForOpenPort BackForwardCacheNotRestoredReason = "EmbedderExtensionMessagingForOpenPort" BackForwardCacheNotRestoredReasonEmbedderExtensionSentMessageToCachedFrame BackForwardCacheNotRestoredReason = "EmbedderExtensionSentMessageToCachedFrame" BackForwardCacheNotRestoredReasonEmbedderExtensionFrame BackForwardCacheNotRestoredReason = "EmbedderExtensionFrame" + BackForwardCacheNotRestoredReasonEmbedderPrivilegedWebContents BackForwardCacheNotRestoredReason = "EmbedderPrivilegedWebContents" BackForwardCacheNotRestoredReasonRequestedByWebViewClient BackForwardCacheNotRestoredReason = "RequestedByWebViewClient" BackForwardCacheNotRestoredReasonPostMessageByWebViewClient BackForwardCacheNotRestoredReason = "PostMessageByWebViewClient" BackForwardCacheNotRestoredReasonCacheControlNoStoreDeviceBoundSessionTerminated BackForwardCacheNotRestoredReason = "CacheControlNoStoreDeviceBoundSessionTerminated" @@ -1153,314 +754,6 @@ const ( BackForwardCacheNotRestoredReasonCacheLimitPrunedOnCriticalMemoryPressure BackForwardCacheNotRestoredReason = "CacheLimitPrunedOnCriticalMemoryPressure" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *BackForwardCacheNotRestoredReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch BackForwardCacheNotRestoredReason(s) { - case BackForwardCacheNotRestoredReasonNotPrimaryMainFrame: - *t = BackForwardCacheNotRestoredReasonNotPrimaryMainFrame - case BackForwardCacheNotRestoredReasonBackForwardCacheDisabled: - *t = BackForwardCacheNotRestoredReasonBackForwardCacheDisabled - case BackForwardCacheNotRestoredReasonRelatedActiveContentsExist: - *t = BackForwardCacheNotRestoredReasonRelatedActiveContentsExist - case BackForwardCacheNotRestoredReasonHTTPSTatusNotOK: - *t = BackForwardCacheNotRestoredReasonHTTPSTatusNotOK - case BackForwardCacheNotRestoredReasonSchemeNotHTTPOrHTTPS: - *t = BackForwardCacheNotRestoredReasonSchemeNotHTTPOrHTTPS - case BackForwardCacheNotRestoredReasonLoading: - *t = BackForwardCacheNotRestoredReasonLoading - case BackForwardCacheNotRestoredReasonWasGrantedMediaAccess: - *t = BackForwardCacheNotRestoredReasonWasGrantedMediaAccess - case BackForwardCacheNotRestoredReasonDisableForRenderFrameHostCalled: - *t = BackForwardCacheNotRestoredReasonDisableForRenderFrameHostCalled - case BackForwardCacheNotRestoredReasonDomainNotAllowed: - *t = BackForwardCacheNotRestoredReasonDomainNotAllowed - case BackForwardCacheNotRestoredReasonHTTPMethodNotGET: - *t = BackForwardCacheNotRestoredReasonHTTPMethodNotGET - case BackForwardCacheNotRestoredReasonSubframeIsNavigating: - *t = BackForwardCacheNotRestoredReasonSubframeIsNavigating - case BackForwardCacheNotRestoredReasonTimeout: - *t = BackForwardCacheNotRestoredReasonTimeout - case BackForwardCacheNotRestoredReasonCacheLimit: - *t = BackForwardCacheNotRestoredReasonCacheLimit - case BackForwardCacheNotRestoredReasonJavaScriptExecution: - *t = BackForwardCacheNotRestoredReasonJavaScriptExecution - case BackForwardCacheNotRestoredReasonRendererProcessKilled: - *t = BackForwardCacheNotRestoredReasonRendererProcessKilled - case BackForwardCacheNotRestoredReasonRendererProcessCrashed: - *t = BackForwardCacheNotRestoredReasonRendererProcessCrashed - case BackForwardCacheNotRestoredReasonSchedulerTrackedFeatureUsed: - *t = BackForwardCacheNotRestoredReasonSchedulerTrackedFeatureUsed - case BackForwardCacheNotRestoredReasonConflictingBrowsingInstance: - *t = BackForwardCacheNotRestoredReasonConflictingBrowsingInstance - case BackForwardCacheNotRestoredReasonCacheFlushed: - *t = BackForwardCacheNotRestoredReasonCacheFlushed - case BackForwardCacheNotRestoredReasonServiceWorkerVersionActivation: - *t = BackForwardCacheNotRestoredReasonServiceWorkerVersionActivation - case BackForwardCacheNotRestoredReasonSessionRestored: - *t = BackForwardCacheNotRestoredReasonSessionRestored - case BackForwardCacheNotRestoredReasonServiceWorkerPostMessage: - *t = BackForwardCacheNotRestoredReasonServiceWorkerPostMessage - case BackForwardCacheNotRestoredReasonEnteredBackForwardCacheBeforeServiceWorkerHostAdded: - *t = BackForwardCacheNotRestoredReasonEnteredBackForwardCacheBeforeServiceWorkerHostAdded - case BackForwardCacheNotRestoredReasonRenderFrameHostReusedSameSite: - *t = BackForwardCacheNotRestoredReasonRenderFrameHostReusedSameSite - case BackForwardCacheNotRestoredReasonRenderFrameHostReusedCrossSite: - *t = BackForwardCacheNotRestoredReasonRenderFrameHostReusedCrossSite - case BackForwardCacheNotRestoredReasonServiceWorkerClaim: - *t = BackForwardCacheNotRestoredReasonServiceWorkerClaim - case BackForwardCacheNotRestoredReasonIgnoreEventAndEvict: - *t = BackForwardCacheNotRestoredReasonIgnoreEventAndEvict - case BackForwardCacheNotRestoredReasonHaveInnerContents: - *t = BackForwardCacheNotRestoredReasonHaveInnerContents - case BackForwardCacheNotRestoredReasonTimeoutPuttingInCache: - *t = BackForwardCacheNotRestoredReasonTimeoutPuttingInCache - case BackForwardCacheNotRestoredReasonBackForwardCacheDisabledByLowMemory: - *t = BackForwardCacheNotRestoredReasonBackForwardCacheDisabledByLowMemory - case BackForwardCacheNotRestoredReasonBackForwardCacheDisabledByCommandLine: - *t = BackForwardCacheNotRestoredReasonBackForwardCacheDisabledByCommandLine - case BackForwardCacheNotRestoredReasonNetworkRequestDatapipeDrainedAsBytesConsumer: - *t = BackForwardCacheNotRestoredReasonNetworkRequestDatapipeDrainedAsBytesConsumer - case BackForwardCacheNotRestoredReasonNetworkRequestRedirected: - *t = BackForwardCacheNotRestoredReasonNetworkRequestRedirected - case BackForwardCacheNotRestoredReasonNetworkRequestTimeout: - *t = BackForwardCacheNotRestoredReasonNetworkRequestTimeout - case BackForwardCacheNotRestoredReasonNetworkExceedsBufferLimit: - *t = BackForwardCacheNotRestoredReasonNetworkExceedsBufferLimit - case BackForwardCacheNotRestoredReasonNavigationCancelledWhileRestoring: - *t = BackForwardCacheNotRestoredReasonNavigationCancelledWhileRestoring - case BackForwardCacheNotRestoredReasonNotMostRecentNavigationEntry: - *t = BackForwardCacheNotRestoredReasonNotMostRecentNavigationEntry - case BackForwardCacheNotRestoredReasonBackForwardCacheDisabledForPrerender: - *t = BackForwardCacheNotRestoredReasonBackForwardCacheDisabledForPrerender - case BackForwardCacheNotRestoredReasonUserAgentOverrideDiffers: - *t = BackForwardCacheNotRestoredReasonUserAgentOverrideDiffers - case BackForwardCacheNotRestoredReasonForegroundCacheLimit: - *t = BackForwardCacheNotRestoredReasonForegroundCacheLimit - case BackForwardCacheNotRestoredReasonForwardCacheDisabled: - *t = BackForwardCacheNotRestoredReasonForwardCacheDisabled - case BackForwardCacheNotRestoredReasonBrowsingInstanceNotSwapped: - *t = BackForwardCacheNotRestoredReasonBrowsingInstanceNotSwapped - case BackForwardCacheNotRestoredReasonBackForwardCacheDisabledForDelegate: - *t = BackForwardCacheNotRestoredReasonBackForwardCacheDisabledForDelegate - case BackForwardCacheNotRestoredReasonUnloadHandlerExistsInMainFrame: - *t = BackForwardCacheNotRestoredReasonUnloadHandlerExistsInMainFrame - case BackForwardCacheNotRestoredReasonUnloadHandlerExistsInSubFrame: - *t = BackForwardCacheNotRestoredReasonUnloadHandlerExistsInSubFrame - case BackForwardCacheNotRestoredReasonServiceWorkerUnregistration: - *t = BackForwardCacheNotRestoredReasonServiceWorkerUnregistration - case BackForwardCacheNotRestoredReasonCacheControlNoStore: - *t = BackForwardCacheNotRestoredReasonCacheControlNoStore - case BackForwardCacheNotRestoredReasonCacheControlNoStoreCookieModified: - *t = BackForwardCacheNotRestoredReasonCacheControlNoStoreCookieModified - case BackForwardCacheNotRestoredReasonCacheControlNoStoreHTTPOnlyCookieModified: - *t = BackForwardCacheNotRestoredReasonCacheControlNoStoreHTTPOnlyCookieModified - case BackForwardCacheNotRestoredReasonNoResponseHead: - *t = BackForwardCacheNotRestoredReasonNoResponseHead - case BackForwardCacheNotRestoredReasonUnknown: - *t = BackForwardCacheNotRestoredReasonUnknown - case BackForwardCacheNotRestoredReasonActivationNavigationsDisallowedForBug1234857: - *t = BackForwardCacheNotRestoredReasonActivationNavigationsDisallowedForBug1234857 - case BackForwardCacheNotRestoredReasonErrorDocument: - *t = BackForwardCacheNotRestoredReasonErrorDocument - case BackForwardCacheNotRestoredReasonFencedFramesEmbedder: - *t = BackForwardCacheNotRestoredReasonFencedFramesEmbedder - case BackForwardCacheNotRestoredReasonCookieDisabled: - *t = BackForwardCacheNotRestoredReasonCookieDisabled - case BackForwardCacheNotRestoredReasonHTTPAuthRequired: - *t = BackForwardCacheNotRestoredReasonHTTPAuthRequired - case BackForwardCacheNotRestoredReasonCookieFlushed: - *t = BackForwardCacheNotRestoredReasonCookieFlushed - case BackForwardCacheNotRestoredReasonBroadcastChannelOnMessage: - *t = BackForwardCacheNotRestoredReasonBroadcastChannelOnMessage - case BackForwardCacheNotRestoredReasonWebViewSettingsChanged: - *t = BackForwardCacheNotRestoredReasonWebViewSettingsChanged - case BackForwardCacheNotRestoredReasonWebViewJavaScriptObjectChanged: - *t = BackForwardCacheNotRestoredReasonWebViewJavaScriptObjectChanged - case BackForwardCacheNotRestoredReasonWebViewMessageListenerInjected: - *t = BackForwardCacheNotRestoredReasonWebViewMessageListenerInjected - case BackForwardCacheNotRestoredReasonWebViewSafeBrowsingAllowlistChanged: - *t = BackForwardCacheNotRestoredReasonWebViewSafeBrowsingAllowlistChanged - case BackForwardCacheNotRestoredReasonWebViewDocumentStartJavascriptChanged: - *t = BackForwardCacheNotRestoredReasonWebViewDocumentStartJavascriptChanged - case BackForwardCacheNotRestoredReasonWebSocket: - *t = BackForwardCacheNotRestoredReasonWebSocket - case BackForwardCacheNotRestoredReasonWebTransport: - *t = BackForwardCacheNotRestoredReasonWebTransport - case BackForwardCacheNotRestoredReasonWebRTC: - *t = BackForwardCacheNotRestoredReasonWebRTC - case BackForwardCacheNotRestoredReasonMainResourceHasCacheControlNoStore: - *t = BackForwardCacheNotRestoredReasonMainResourceHasCacheControlNoStore - case BackForwardCacheNotRestoredReasonMainResourceHasCacheControlNoCache: - *t = BackForwardCacheNotRestoredReasonMainResourceHasCacheControlNoCache - case BackForwardCacheNotRestoredReasonSubresourceHasCacheControlNoStore: - *t = BackForwardCacheNotRestoredReasonSubresourceHasCacheControlNoStore - case BackForwardCacheNotRestoredReasonSubresourceHasCacheControlNoCache: - *t = BackForwardCacheNotRestoredReasonSubresourceHasCacheControlNoCache - case BackForwardCacheNotRestoredReasonContainsPlugins: - *t = BackForwardCacheNotRestoredReasonContainsPlugins - case BackForwardCacheNotRestoredReasonDocumentLoaded: - *t = BackForwardCacheNotRestoredReasonDocumentLoaded - case BackForwardCacheNotRestoredReasonOutstandingNetworkRequestOthers: - *t = BackForwardCacheNotRestoredReasonOutstandingNetworkRequestOthers - case BackForwardCacheNotRestoredReasonRequestedMIDIPermission: - *t = BackForwardCacheNotRestoredReasonRequestedMIDIPermission - case BackForwardCacheNotRestoredReasonRequestedAudioCapturePermission: - *t = BackForwardCacheNotRestoredReasonRequestedAudioCapturePermission - case BackForwardCacheNotRestoredReasonRequestedVideoCapturePermission: - *t = BackForwardCacheNotRestoredReasonRequestedVideoCapturePermission - case BackForwardCacheNotRestoredReasonRequestedBackForwardCacheBlockedSensors: - *t = BackForwardCacheNotRestoredReasonRequestedBackForwardCacheBlockedSensors - case BackForwardCacheNotRestoredReasonRequestedBackgroundWorkPermission: - *t = BackForwardCacheNotRestoredReasonRequestedBackgroundWorkPermission - case BackForwardCacheNotRestoredReasonBroadcastChannel: - *t = BackForwardCacheNotRestoredReasonBroadcastChannel - case BackForwardCacheNotRestoredReasonWebXR: - *t = BackForwardCacheNotRestoredReasonWebXR - case BackForwardCacheNotRestoredReasonSharedWorker: - *t = BackForwardCacheNotRestoredReasonSharedWorker - case BackForwardCacheNotRestoredReasonSharedWorkerMessage: - *t = BackForwardCacheNotRestoredReasonSharedWorkerMessage - case BackForwardCacheNotRestoredReasonSharedWorkerWithNoActiveClient: - *t = BackForwardCacheNotRestoredReasonSharedWorkerWithNoActiveClient - case BackForwardCacheNotRestoredReasonWebLocks: - *t = BackForwardCacheNotRestoredReasonWebLocks - case BackForwardCacheNotRestoredReasonWebLocksContention: - *t = BackForwardCacheNotRestoredReasonWebLocksContention - case BackForwardCacheNotRestoredReasonWebHID: - *t = BackForwardCacheNotRestoredReasonWebHID - case BackForwardCacheNotRestoredReasonWebBluetooth: - *t = BackForwardCacheNotRestoredReasonWebBluetooth - case BackForwardCacheNotRestoredReasonWebShare: - *t = BackForwardCacheNotRestoredReasonWebShare - case BackForwardCacheNotRestoredReasonRequestedStorageAccessGrant: - *t = BackForwardCacheNotRestoredReasonRequestedStorageAccessGrant - case BackForwardCacheNotRestoredReasonWebNfc: - *t = BackForwardCacheNotRestoredReasonWebNfc - case BackForwardCacheNotRestoredReasonOutstandingNetworkRequestFetch: - *t = BackForwardCacheNotRestoredReasonOutstandingNetworkRequestFetch - case BackForwardCacheNotRestoredReasonOutstandingNetworkRequestXHR: - *t = BackForwardCacheNotRestoredReasonOutstandingNetworkRequestXHR - case BackForwardCacheNotRestoredReasonAppBanner: - *t = BackForwardCacheNotRestoredReasonAppBanner - case BackForwardCacheNotRestoredReasonPrinting: - *t = BackForwardCacheNotRestoredReasonPrinting - case BackForwardCacheNotRestoredReasonWebDatabase: - *t = BackForwardCacheNotRestoredReasonWebDatabase - case BackForwardCacheNotRestoredReasonPictureInPicture: - *t = BackForwardCacheNotRestoredReasonPictureInPicture - case BackForwardCacheNotRestoredReasonSpeechRecognizer: - *t = BackForwardCacheNotRestoredReasonSpeechRecognizer - case BackForwardCacheNotRestoredReasonIdleManager: - *t = BackForwardCacheNotRestoredReasonIdleManager - case BackForwardCacheNotRestoredReasonPaymentManager: - *t = BackForwardCacheNotRestoredReasonPaymentManager - case BackForwardCacheNotRestoredReasonSpeechSynthesis: - *t = BackForwardCacheNotRestoredReasonSpeechSynthesis - case BackForwardCacheNotRestoredReasonKeyboardLock: - *t = BackForwardCacheNotRestoredReasonKeyboardLock - case BackForwardCacheNotRestoredReasonWebOTPService: - *t = BackForwardCacheNotRestoredReasonWebOTPService - case BackForwardCacheNotRestoredReasonOutstandingNetworkRequestDirectSocket: - *t = BackForwardCacheNotRestoredReasonOutstandingNetworkRequestDirectSocket - case BackForwardCacheNotRestoredReasonInjectedJavascript: - *t = BackForwardCacheNotRestoredReasonInjectedJavascript - case BackForwardCacheNotRestoredReasonInjectedStyleSheet: - *t = BackForwardCacheNotRestoredReasonInjectedStyleSheet - case BackForwardCacheNotRestoredReasonKeepaliveRequest: - *t = BackForwardCacheNotRestoredReasonKeepaliveRequest - case BackForwardCacheNotRestoredReasonIndexedDBEvent: - *t = BackForwardCacheNotRestoredReasonIndexedDBEvent - case BackForwardCacheNotRestoredReasonDummy: - *t = BackForwardCacheNotRestoredReasonDummy - case BackForwardCacheNotRestoredReasonJsNetworkRequestReceivedCacheControlNoStoreResource: - *t = BackForwardCacheNotRestoredReasonJsNetworkRequestReceivedCacheControlNoStoreResource - case BackForwardCacheNotRestoredReasonWebRTCUsedWithCCNS: - *t = BackForwardCacheNotRestoredReasonWebRTCUsedWithCCNS - case BackForwardCacheNotRestoredReasonWebTransportUsedWithCCNS: - *t = BackForwardCacheNotRestoredReasonWebTransportUsedWithCCNS - case BackForwardCacheNotRestoredReasonWebSocketUsedWithCCNS: - *t = BackForwardCacheNotRestoredReasonWebSocketUsedWithCCNS - case BackForwardCacheNotRestoredReasonSmartCard: - *t = BackForwardCacheNotRestoredReasonSmartCard - case BackForwardCacheNotRestoredReasonLiveMediaStreamTrack: - *t = BackForwardCacheNotRestoredReasonLiveMediaStreamTrack - case BackForwardCacheNotRestoredReasonUnloadHandler: - *t = BackForwardCacheNotRestoredReasonUnloadHandler - case BackForwardCacheNotRestoredReasonParserAborted: - *t = BackForwardCacheNotRestoredReasonParserAborted - case BackForwardCacheNotRestoredReasonContentSecurityHandler: - *t = BackForwardCacheNotRestoredReasonContentSecurityHandler - case BackForwardCacheNotRestoredReasonContentWebAuthenticationAPI: - *t = BackForwardCacheNotRestoredReasonContentWebAuthenticationAPI - case BackForwardCacheNotRestoredReasonContentFileChooser: - *t = BackForwardCacheNotRestoredReasonContentFileChooser - case BackForwardCacheNotRestoredReasonContentSerial: - *t = BackForwardCacheNotRestoredReasonContentSerial - case BackForwardCacheNotRestoredReasonContentFileSystemAccess: - *t = BackForwardCacheNotRestoredReasonContentFileSystemAccess - case BackForwardCacheNotRestoredReasonContentMediaDevicesDispatcherHost: - *t = BackForwardCacheNotRestoredReasonContentMediaDevicesDispatcherHost - case BackForwardCacheNotRestoredReasonContentWebBluetooth: - *t = BackForwardCacheNotRestoredReasonContentWebBluetooth - case BackForwardCacheNotRestoredReasonContentWebUSB: - *t = BackForwardCacheNotRestoredReasonContentWebUSB - case BackForwardCacheNotRestoredReasonContentMediaSessionService: - *t = BackForwardCacheNotRestoredReasonContentMediaSessionService - case BackForwardCacheNotRestoredReasonContentScreenReader: - *t = BackForwardCacheNotRestoredReasonContentScreenReader - case BackForwardCacheNotRestoredReasonContentDiscarded: - *t = BackForwardCacheNotRestoredReasonContentDiscarded - case BackForwardCacheNotRestoredReasonEmbedderPopupBlockerTabHelper: - *t = BackForwardCacheNotRestoredReasonEmbedderPopupBlockerTabHelper - case BackForwardCacheNotRestoredReasonEmbedderSafeBrowsingTriggeredPopupBlocker: - *t = BackForwardCacheNotRestoredReasonEmbedderSafeBrowsingTriggeredPopupBlocker - case BackForwardCacheNotRestoredReasonEmbedderSafeBrowsingThreatDetails: - *t = BackForwardCacheNotRestoredReasonEmbedderSafeBrowsingThreatDetails - case BackForwardCacheNotRestoredReasonEmbedderAppBannerManager: - *t = BackForwardCacheNotRestoredReasonEmbedderAppBannerManager - case BackForwardCacheNotRestoredReasonEmbedderDomDistillerViewerSource: - *t = BackForwardCacheNotRestoredReasonEmbedderDomDistillerViewerSource - case BackForwardCacheNotRestoredReasonEmbedderDomDistillerSelfDeletingRequestDelegate: - *t = BackForwardCacheNotRestoredReasonEmbedderDomDistillerSelfDeletingRequestDelegate - case BackForwardCacheNotRestoredReasonEmbedderOomInterventionTabHelper: - *t = BackForwardCacheNotRestoredReasonEmbedderOomInterventionTabHelper - case BackForwardCacheNotRestoredReasonEmbedderOfflinePage: - *t = BackForwardCacheNotRestoredReasonEmbedderOfflinePage - case BackForwardCacheNotRestoredReasonEmbedderChromePasswordManagerClientBindCredentialManager: - *t = BackForwardCacheNotRestoredReasonEmbedderChromePasswordManagerClientBindCredentialManager - case BackForwardCacheNotRestoredReasonEmbedderPermissionRequestManager: - *t = BackForwardCacheNotRestoredReasonEmbedderPermissionRequestManager - case BackForwardCacheNotRestoredReasonEmbedderModalDialog: - *t = BackForwardCacheNotRestoredReasonEmbedderModalDialog - case BackForwardCacheNotRestoredReasonEmbedderExtensions: - *t = BackForwardCacheNotRestoredReasonEmbedderExtensions - case BackForwardCacheNotRestoredReasonEmbedderExtensionMessaging: - *t = BackForwardCacheNotRestoredReasonEmbedderExtensionMessaging - case BackForwardCacheNotRestoredReasonEmbedderExtensionMessagingForOpenPort: - *t = BackForwardCacheNotRestoredReasonEmbedderExtensionMessagingForOpenPort - case BackForwardCacheNotRestoredReasonEmbedderExtensionSentMessageToCachedFrame: - *t = BackForwardCacheNotRestoredReasonEmbedderExtensionSentMessageToCachedFrame - case BackForwardCacheNotRestoredReasonEmbedderExtensionFrame: - *t = BackForwardCacheNotRestoredReasonEmbedderExtensionFrame - case BackForwardCacheNotRestoredReasonRequestedByWebViewClient: - *t = BackForwardCacheNotRestoredReasonRequestedByWebViewClient - case BackForwardCacheNotRestoredReasonPostMessageByWebViewClient: - *t = BackForwardCacheNotRestoredReasonPostMessageByWebViewClient - case BackForwardCacheNotRestoredReasonCacheControlNoStoreDeviceBoundSessionTerminated: - *t = BackForwardCacheNotRestoredReasonCacheControlNoStoreDeviceBoundSessionTerminated - case BackForwardCacheNotRestoredReasonCacheLimitPrunedOnModerateMemoryPressure: - *t = BackForwardCacheNotRestoredReasonCacheLimitPrunedOnModerateMemoryPressure - case BackForwardCacheNotRestoredReasonCacheLimitPrunedOnCriticalMemoryPressure: - *t = BackForwardCacheNotRestoredReasonCacheLimitPrunedOnCriticalMemoryPressure - default: - return fmt.Errorf("unknown BackForwardCacheNotRestoredReason value: %v", s) - } - return nil -} - // BackForwardCacheNotRestoredReasonType types of not restored reasons for // back-forward cache. // @@ -1479,24 +772,6 @@ const ( BackForwardCacheNotRestoredReasonTypeCircumstantial BackForwardCacheNotRestoredReasonType = "Circumstantial" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *BackForwardCacheNotRestoredReasonType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch BackForwardCacheNotRestoredReasonType(s) { - case BackForwardCacheNotRestoredReasonTypeSupportPending: - *t = BackForwardCacheNotRestoredReasonTypeSupportPending - case BackForwardCacheNotRestoredReasonTypePageSupportNeeded: - *t = BackForwardCacheNotRestoredReasonTypePageSupportNeeded - case BackForwardCacheNotRestoredReasonTypeCircumstantial: - *t = BackForwardCacheNotRestoredReasonTypeCircumstantial - default: - return fmt.Errorf("unknown BackForwardCacheNotRestoredReasonType value: %v", s) - } - return nil -} - // BackForwardCacheBlockingDetails [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-BackForwardCacheBlockingDetails @@ -1542,22 +817,6 @@ const ( FileChooserOpenedModeSelectMultiple FileChooserOpenedMode = "selectMultiple" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *FileChooserOpenedMode) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch FileChooserOpenedMode(s) { - case FileChooserOpenedModeSelectSingle: - *t = FileChooserOpenedModeSelectSingle - case FileChooserOpenedModeSelectMultiple: - *t = FileChooserOpenedModeSelectMultiple - default: - return fmt.Errorf("unknown FileChooserOpenedMode value: %v", s) - } - return nil -} - // FrameDetachedReason [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-frameDetached @@ -1574,22 +833,6 @@ const ( FrameDetachedReasonSwap FrameDetachedReason = "swap" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *FrameDetachedReason) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch FrameDetachedReason(s) { - case FrameDetachedReasonRemove: - *t = FrameDetachedReasonRemove - case FrameDetachedReasonSwap: - *t = FrameDetachedReasonSwap - default: - return fmt.Errorf("unknown FrameDetachedReason value: %v", s) - } - return nil -} - // FrameStartedNavigatingNavigationType [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-frameStartedNavigating @@ -1612,34 +855,6 @@ const ( FrameStartedNavigatingNavigationTypeDifferentDocument FrameStartedNavigatingNavigationType = "differentDocument" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *FrameStartedNavigatingNavigationType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch FrameStartedNavigatingNavigationType(s) { - case FrameStartedNavigatingNavigationTypeReload: - *t = FrameStartedNavigatingNavigationTypeReload - case FrameStartedNavigatingNavigationTypeReloadBypassingCache: - *t = FrameStartedNavigatingNavigationTypeReloadBypassingCache - case FrameStartedNavigatingNavigationTypeRestore: - *t = FrameStartedNavigatingNavigationTypeRestore - case FrameStartedNavigatingNavigationTypeRestoreWithPost: - *t = FrameStartedNavigatingNavigationTypeRestoreWithPost - case FrameStartedNavigatingNavigationTypeHistorySameDocument: - *t = FrameStartedNavigatingNavigationTypeHistorySameDocument - case FrameStartedNavigatingNavigationTypeHistoryDifferentDocument: - *t = FrameStartedNavigatingNavigationTypeHistoryDifferentDocument - case FrameStartedNavigatingNavigationTypeSameDocument: - *t = FrameStartedNavigatingNavigationTypeSameDocument - case FrameStartedNavigatingNavigationTypeDifferentDocument: - *t = FrameStartedNavigatingNavigationTypeDifferentDocument - default: - return fmt.Errorf("unknown FrameStartedNavigatingNavigationType value: %v", s) - } - return nil -} - // NavigatedWithinDocumentNavigationType navigation type. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#event-navigatedWithinDocument @@ -1657,24 +872,6 @@ const ( NavigatedWithinDocumentNavigationTypeOther NavigatedWithinDocumentNavigationType = "other" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *NavigatedWithinDocumentNavigationType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch NavigatedWithinDocumentNavigationType(s) { - case NavigatedWithinDocumentNavigationTypeFragment: - *t = NavigatedWithinDocumentNavigationTypeFragment - case NavigatedWithinDocumentNavigationTypeHistoryAPI: - *t = NavigatedWithinDocumentNavigationTypeHistoryAPI - case NavigatedWithinDocumentNavigationTypeOther: - *t = NavigatedWithinDocumentNavigationTypeOther - default: - return fmt.Errorf("unknown NavigatedWithinDocumentNavigationType value: %v", s) - } - return nil -} - // CaptureScreenshotFormat image compression format (defaults to png). // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-captureScreenshot @@ -1692,24 +889,6 @@ const ( CaptureScreenshotFormatWebp CaptureScreenshotFormat = "webp" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CaptureScreenshotFormat) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CaptureScreenshotFormat(s) { - case CaptureScreenshotFormatJpeg: - *t = CaptureScreenshotFormatJpeg - case CaptureScreenshotFormatPng: - *t = CaptureScreenshotFormatPng - case CaptureScreenshotFormatWebp: - *t = CaptureScreenshotFormatWebp - default: - return fmt.Errorf("unknown CaptureScreenshotFormat value: %v", s) - } - return nil -} - // CaptureSnapshotFormat format (defaults to mhtml). // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-captureSnapshot @@ -1725,20 +904,6 @@ const ( CaptureSnapshotFormatMhtml CaptureSnapshotFormat = "mhtml" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CaptureSnapshotFormat) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CaptureSnapshotFormat(s) { - case CaptureSnapshotFormatMhtml: - *t = CaptureSnapshotFormatMhtml - default: - return fmt.Errorf("unknown CaptureSnapshotFormat value: %v", s) - } - return nil -} - // PrintToPDFTransferMode return as stream. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-printToPDF @@ -1755,54 +920,22 @@ const ( PrintToPDFTransferModeReturnAsStream PrintToPDFTransferMode = "ReturnAsStream" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *PrintToPDFTransferMode) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch PrintToPDFTransferMode(s) { - case PrintToPDFTransferModeReturnAsBase64: - *t = PrintToPDFTransferModeReturnAsBase64 - case PrintToPDFTransferModeReturnAsStream: - *t = PrintToPDFTransferModeReturnAsStream - default: - return fmt.Errorf("unknown PrintToPDFTransferMode value: %v", s) - } - return nil -} - -// ScreencastFormat image compression format. +// StartScreencastFormat image compression format. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-startScreencast -type ScreencastFormat string +type StartScreencastFormat string -// String returns the ScreencastFormat as string value. -func (t ScreencastFormat) String() string { +// String returns the StartScreencastFormat as string value. +func (t StartScreencastFormat) String() string { return string(t) } -// ScreencastFormat values. +// StartScreencastFormat values. const ( - ScreencastFormatJpeg ScreencastFormat = "jpeg" - ScreencastFormatPng ScreencastFormat = "png" + StartScreencastFormatJpeg StartScreencastFormat = "jpeg" + StartScreencastFormatPng StartScreencastFormat = "png" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ScreencastFormat) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ScreencastFormat(s) { - case ScreencastFormatJpeg: - *t = ScreencastFormatJpeg - case ScreencastFormatPng: - *t = ScreencastFormatPng - default: - return fmt.Errorf("unknown ScreencastFormat value: %v", s) - } - return nil -} - // SetWebLifecycleStateState target lifecycle state. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setWebLifecycleState @@ -1819,22 +952,6 @@ const ( SetWebLifecycleStateStateActive SetWebLifecycleStateState = "active" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SetWebLifecycleStateState) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SetWebLifecycleStateState(s) { - case SetWebLifecycleStateStateFrozen: - *t = SetWebLifecycleStateStateFrozen - case SetWebLifecycleStateStateActive: - *t = SetWebLifecycleStateStateActive - default: - return fmt.Errorf("unknown SetWebLifecycleStateState value: %v", s) - } - return nil -} - // SetSPCTransactionModeMode [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setSPCTransactionMode @@ -1854,28 +971,6 @@ const ( SetSPCTransactionModeModeAutoOptOut SetSPCTransactionModeMode = "autoOptOut" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SetSPCTransactionModeMode) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SetSPCTransactionModeMode(s) { - case SetSPCTransactionModeModeNone: - *t = SetSPCTransactionModeModeNone - case SetSPCTransactionModeModeAutoAccept: - *t = SetSPCTransactionModeModeAutoAccept - case SetSPCTransactionModeModeAutoChooseToAuthAnotherWay: - *t = SetSPCTransactionModeModeAutoChooseToAuthAnotherWay - case SetSPCTransactionModeModeAutoReject: - *t = SetSPCTransactionModeModeAutoReject - case SetSPCTransactionModeModeAutoOptOut: - *t = SetSPCTransactionModeModeAutoOptOut - default: - return fmt.Errorf("unknown SetSPCTransactionModeMode value: %v", s) - } - return nil -} - // SetRPHRegistrationModeMode [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setRPHRegistrationMode @@ -1892,21 +987,3 @@ const ( SetRPHRegistrationModeModeAutoAccept SetRPHRegistrationModeMode = "autoAccept" SetRPHRegistrationModeModeAutoReject SetRPHRegistrationModeMode = "autoReject" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SetRPHRegistrationModeMode) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SetRPHRegistrationModeMode(s) { - case SetRPHRegistrationModeModeNone: - *t = SetRPHRegistrationModeModeNone - case SetRPHRegistrationModeModeAutoAccept: - *t = SetRPHRegistrationModeModeAutoAccept - case SetRPHRegistrationModeModeAutoReject: - *t = SetRPHRegistrationModeModeAutoReject - default: - return fmt.Errorf("unknown SetRPHRegistrationModeMode value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/performance/events.go b/vendor/github.com/chromedp/cdproto/performance/events.go index ad2200704..9bc2a7a90 100644 --- a/vendor/github.com/chromedp/cdproto/performance/events.go +++ b/vendor/github.com/chromedp/cdproto/performance/events.go @@ -1,6 +1,6 @@ -package performance +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package performance // EventMetrics current values of the metrics. // diff --git a/vendor/github.com/chromedp/cdproto/performance/performance.go b/vendor/github.com/chromedp/cdproto/performance/performance.go index 367b0c0f7..9a71cd6eb 100644 --- a/vendor/github.com/chromedp/cdproto/performance/performance.go +++ b/vendor/github.com/chromedp/cdproto/performance/performance.go @@ -1,33 +1,21 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package performance provides the Chrome DevTools Protocol // commands, types, and events for the Performance domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package performance -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// DisableParams disable collecting and reporting metrics. -type DisableParams struct{} - // Disable disable collecting and reporting metrics. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Performance#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} -// Do executes Performance.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// EnableParams enable collecting and reporting metrics. +// EnableParams are the parameters of the command Performance.enable. type EnableParams struct { TimeDomain EnableTimeDomain `json:"timeDomain,omitempty,omitzero"` // Time domain to use for collecting and reporting duration metrics. } @@ -35,54 +23,22 @@ type EnableParams struct { // Enable enable collecting and reporting metrics. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Performance#method-enable -// -// parameters: -func Enable() *EnableParams { - return &EnableParams{} -} - -// WithTimeDomain time domain to use for collecting and reporting duration -// metrics. -func (p EnableParams) WithTimeDomain(timeDomain EnableTimeDomain) *EnableParams { - p.TimeDomain = timeDomain - return &p -} +var Enable = cdp.Command[EnableParams, cdp.Empty]{Method: CommandEnable} -// Do executes Performance.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, p, nil) +// GetMetricsResult is the result of the command Performance.getMetrics. +type GetMetricsResult struct { + Metrics []*Metric `json:"metrics,omitempty,omitzero"` // Current values for run-time metrics. } -// GetMetricsParams retrieve current values of run-time metrics. -type GetMetricsParams struct{} - // GetMetrics retrieve current values of run-time metrics. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Performance#method-getMetrics -func GetMetrics() *GetMetricsParams { - return &GetMetricsParams{} -} - -// GetMetricsReturns return values. -type GetMetricsReturns struct { - Metrics []*Metric `json:"metrics,omitempty,omitzero"` // Current values for run-time metrics. -} +var GetMetrics = cdp.Command[cdp.Empty, GetMetricsResult]{Method: CommandGetMetrics} -// Do executes Performance.getMetrics against the provided context. -// -// returns: +// Metrics current values of the metrics. // -// metrics - Current values for run-time metrics. -func (p *GetMetricsParams) Do(ctx context.Context) (metrics []*Metric, err error) { - // execute - var res GetMetricsReturns - err = cdp.Execute(ctx, CommandGetMetrics, nil, &res) - if err != nil { - return nil, err - } - - return res.Metrics, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Performance#event-metrics +var Metrics = cdp.Event[EventMetrics]{Method: "Performance.metrics"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/performance/types.go b/vendor/github.com/chromedp/cdproto/performance/types.go index acb0ed01a..45cebf945 100644 --- a/vendor/github.com/chromedp/cdproto/performance/types.go +++ b/vendor/github.com/chromedp/cdproto/performance/types.go @@ -1,11 +1,6 @@ -package performance - -import ( - "fmt" - "strings" -) +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package performance // Metric run-time execution metric. // @@ -31,19 +26,3 @@ const ( EnableTimeDomainTimeTicks EnableTimeDomain = "timeTicks" EnableTimeDomainThreadTicks EnableTimeDomain = "threadTicks" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *EnableTimeDomain) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch EnableTimeDomain(s) { - case EnableTimeDomainTimeTicks: - *t = EnableTimeDomainTimeTicks - case EnableTimeDomainThreadTicks: - *t = EnableTimeDomainThreadTicks - default: - return fmt.Errorf("unknown EnableTimeDomain value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/performancetimeline/events.go b/vendor/github.com/chromedp/cdproto/performancetimeline/events.go index 740d0e45f..d3d6b0d33 100644 --- a/vendor/github.com/chromedp/cdproto/performancetimeline/events.go +++ b/vendor/github.com/chromedp/cdproto/performancetimeline/events.go @@ -1,6 +1,6 @@ -package performancetimeline +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package performancetimeline // EventTimelineEventAdded sent when a performance timeline event is added. // See reportPerformanceTimeline method. diff --git a/vendor/github.com/chromedp/cdproto/performancetimeline/performancetimeline.go b/vendor/github.com/chromedp/cdproto/performancetimeline/performancetimeline.go index d2b8f5b75..979eab211 100644 --- a/vendor/github.com/chromedp/cdproto/performancetimeline/performancetimeline.go +++ b/vendor/github.com/chromedp/cdproto/performancetimeline/performancetimeline.go @@ -1,22 +1,19 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package performancetimeline provides the Chrome DevTools Protocol // commands, types, and events for the PerformanceTimeline domain. // // Reporting of performance timeline events, as specified in // https://w3c.github.io/performance-timeline/#dom-performanceobserver. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package performancetimeline -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// EnableParams previously buffered events would be reported before method -// returns. See also: timelineEventAdded. +// EnableParams are the parameters of the command PerformanceTimeline.enable. type EnableParams struct { EventTypes []string `json:"eventTypes"` // The types of event to report, as specified in https://w3c.github.io/performance-timeline/#dom-performanceentry-entrytype The specified filter overrides any previous filters, passing empty filter disables recording. Note that not all types exposed to the web platform are currently supported. } @@ -25,20 +22,13 @@ type EnableParams struct { // See also: timelineEventAdded. // // See: https://chromedevtools.github.io/devtools-protocol/tot/PerformanceTimeline#method-enable -// -// parameters: -// -// eventTypes - The types of event to report, as specified in https://w3c.github.io/performance-timeline/#dom-performanceentry-entrytype The specified filter overrides any previous filters, passing empty filter disables recording. Note that not all types exposed to the web platform are currently supported. -func Enable(eventTypes []string) *EnableParams { - return &EnableParams{ - EventTypes: eventTypes, - } -} +var Enable = cdp.Command[EnableParams, cdp.Empty]{Method: CommandEnable} -// Do executes PerformanceTimeline.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, p, nil) -} +// TimelineEventAdded sent when a performance timeline event is added. See +// reportPerformanceTimeline method. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/PerformanceTimeline#event-timelineEventAdded +var TimelineEventAdded = cdp.Event[EventTimelineEventAdded]{Method: "PerformanceTimeline.timelineEventAdded"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/performancetimeline/types.go b/vendor/github.com/chromedp/cdproto/performancetimeline/types.go index 6c5252167..fcfd24c3d 100644 --- a/vendor/github.com/chromedp/cdproto/performancetimeline/types.go +++ b/vendor/github.com/chromedp/cdproto/performancetimeline/types.go @@ -1,6 +1,6 @@ -package performancetimeline +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package performancetimeline import ( "github.com/chromedp/cdproto/cdp" @@ -12,12 +12,12 @@ import ( // // See: https://chromedevtools.github.io/devtools-protocol/tot/PerformanceTimeline#type-LargestContentfulPaint type LargestContentfulPaint struct { - RenderTime *cdp.TimeSinceEpoch `json:"renderTime"` - LoadTime *cdp.TimeSinceEpoch `json:"loadTime"` - Size float64 `json:"size"` // The number of pixels being painted. - ElementID string `json:"elementId,omitempty,omitzero"` // The id attribute of the element, if available. - URL string `json:"url,omitempty,omitzero"` // The URL of the image (may be trimmed). - NodeID cdp.BackendNodeID `json:"nodeId,omitempty,omitzero"` + RenderTime cdp.TimeSinceEpoch `json:"renderTime"` + LoadTime cdp.TimeSinceEpoch `json:"loadTime"` + Size float64 `json:"size"` // The number of pixels being painted. + ElementID string `json:"elementId,omitempty,omitzero"` // The id attribute of the element, if available. + URL string `json:"url,omitempty,omitzero"` // The URL of the image (may be trimmed). + NodeID cdp.BackendNodeID `json:"nodeId,omitempty,omitzero"` } // LayoutShiftAttribution [no description]. @@ -37,7 +37,7 @@ type LayoutShiftAttribution struct { type LayoutShift struct { Value float64 `json:"value"` // Score increment produced by this event. HadRecentInput bool `json:"hadRecentInput"` - LastInputTime *cdp.TimeSinceEpoch `json:"lastInputTime"` + LastInputTime cdp.TimeSinceEpoch `json:"lastInputTime"` Sources []*LayoutShiftAttribution `json:"sources"` } @@ -48,7 +48,7 @@ type TimelineEvent struct { FrameID cdp.FrameID `json:"frameId"` // Identifies the frame that this event is related to. Empty for non-frame targets. Type string `json:"type"` // The event type, as specified in https://w3c.github.io/performance-timeline/#dom-performanceentry-entrytype This determines which of the optional "details" fields is present. Name string `json:"name"` // Name may be empty depending on the type. - Time *cdp.TimeSinceEpoch `json:"time"` // Time in seconds since Epoch, monotonically increasing within document lifetime. + Time cdp.TimeSinceEpoch `json:"time"` // Time in seconds since Epoch, monotonically increasing within document lifetime. Duration float64 `json:"duration,omitempty,omitzero"` // Event duration, if applicable. LcpDetails *LargestContentfulPaint `json:"lcpDetails,omitempty,omitzero"` LayoutShiftDetails *LayoutShift `json:"layoutShiftDetails,omitempty,omitzero"` diff --git a/vendor/github.com/chromedp/cdproto/preload/events.go b/vendor/github.com/chromedp/cdproto/preload/events.go index 3a9d349da..461d2cc01 100644 --- a/vendor/github.com/chromedp/cdproto/preload/events.go +++ b/vendor/github.com/chromedp/cdproto/preload/events.go @@ -1,6 +1,6 @@ -package preload +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package preload import ( "github.com/chromedp/cdproto/cdp" @@ -54,6 +54,7 @@ type EventPrerenderStatusUpdated struct { Key *IngAttemptKey `json:"key"` PipelineID PipelineID `json:"pipelineId"` Status IngStatus `json:"status"` + EffectiveAction SpeculationAction `json:"effectiveAction,omitempty,omitzero"` // The action currently performed by this attempt. This differs from key.action after a prerender-until-script attempt is upgraded in place to a full prerender. PrerenderStatus PrerenderFinalStatus `json:"prerenderStatus,omitempty,omitzero"` DisallowedMojoInterface string `json:"disallowedMojoInterface,omitempty,omitzero"` // This is used to give users more information about the name of Mojo interface that is incompatible with prerender and has caused the cancellation of the attempt. MismatchedHeaders []*PrerenderMismatchedHeaders `json:"mismatchedHeaders,omitempty,omitzero"` diff --git a/vendor/github.com/chromedp/cdproto/preload/preload.go b/vendor/github.com/chromedp/cdproto/preload/preload.go index 27eef5844..13deeef5b 100644 --- a/vendor/github.com/chromedp/cdproto/preload/preload.go +++ b/vendor/github.com/chromedp/cdproto/preload/preload.go @@ -1,46 +1,56 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package preload provides the Chrome DevTools Protocol // commands, types, and events for the Preload domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package preload -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// EnableParams [no description]. -type EnableParams struct{} - // Enable [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Preload#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} - -// Do executes Preload.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) -} - -// DisableParams [no description]. -type DisableParams struct{} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} // Disable [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Preload#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes Preload.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} + +// RuleSetUpdated upsert. Currently, it is only emitted when a rule set +// added. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Preload#event-ruleSetUpdated +var RuleSetUpdated = cdp.Event[EventRuleSetUpdated]{Method: "Preload.ruleSetUpdated"} + +// RuleSetRemoved [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Preload#event-ruleSetRemoved +var RuleSetRemoved = cdp.Event[EventRuleSetRemoved]{Method: "Preload.ruleSetRemoved"} + +// PreloadEnabledStateUpdated fired when a preload enabled state is updated. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Preload#event-preloadEnabledStateUpdated +var PreloadEnabledStateUpdated = cdp.Event[EventPreloadEnabledStateUpdated]{Method: "Preload.preloadEnabledStateUpdated"} + +// PrefetchStatusUpdated fired when a prefetch attempt is updated. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Preload#event-prefetchStatusUpdated +var PrefetchStatusUpdated = cdp.Event[EventPrefetchStatusUpdated]{Method: "Preload.prefetchStatusUpdated"} + +// PrerenderStatusUpdated fired when a prerender attempt is updated. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Preload#event-prerenderStatusUpdated +var PrerenderStatusUpdated = cdp.Event[EventPrerenderStatusUpdated]{Method: "Preload.prerenderStatusUpdated"} + +// PreloadingAttemptSourcesUpdated send a list of sources for all preloading +// attempts in a document. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Preload#event-preloadingAttemptSourcesUpdated +var PreloadingAttemptSourcesUpdated = cdp.Event[EventPreloadingAttemptSourcesUpdated]{Method: "Preload.preloadingAttemptSourcesUpdated"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/preload/types.go b/vendor/github.com/chromedp/cdproto/preload/types.go index 1f565409d..a09e4aa1d 100644 --- a/vendor/github.com/chromedp/cdproto/preload/types.go +++ b/vendor/github.com/chromedp/cdproto/preload/types.go @@ -1,11 +1,8 @@ -package preload +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package preload import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/network" ) @@ -51,24 +48,6 @@ const ( RuleSetErrorTypeInvalidRulesetLevelTag RuleSetErrorType = "InvalidRulesetLevelTag" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *RuleSetErrorType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch RuleSetErrorType(s) { - case RuleSetErrorTypeSourceIsNotJSONObject: - *t = RuleSetErrorTypeSourceIsNotJSONObject - case RuleSetErrorTypeInvalidRulesSkipped: - *t = RuleSetErrorTypeInvalidRulesSkipped - case RuleSetErrorTypeInvalidRulesetLevelTag: - *t = RuleSetErrorTypeInvalidRulesetLevelTag - default: - return fmt.Errorf("unknown RuleSetErrorType value: %v", s) - } - return nil -} - // SpeculationAction the type of preloading attempted. It corresponds to // mojom::SpeculationAction (although PrefetchWithSubresources is omitted as it // isn't being used by clients). @@ -88,24 +67,6 @@ const ( SpeculationActionPrerenderUntilScript SpeculationAction = "PrerenderUntilScript" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SpeculationAction) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SpeculationAction(s) { - case SpeculationActionPrefetch: - *t = SpeculationActionPrefetch - case SpeculationActionPrerender: - *t = SpeculationActionPrerender - case SpeculationActionPrerenderUntilScript: - *t = SpeculationActionPrerenderUntilScript - default: - return fmt.Errorf("unknown SpeculationAction value: %v", s) - } - return nil -} - // SpeculationTargetHint corresponds to mojom::SpeculationTargetHint. See // https://github.com/WICG/nav-speculation/blob/main/triggers.md#window-name-targeting-hints. // @@ -123,22 +84,6 @@ const ( SpeculationTargetHintSelf SpeculationTargetHint = "Self" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SpeculationTargetHint) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SpeculationTargetHint(s) { - case SpeculationTargetHintBlank: - *t = SpeculationTargetHintBlank - case SpeculationTargetHintSelf: - *t = SpeculationTargetHintSelf - default: - return fmt.Errorf("unknown SpeculationTargetHint value: %v", s) - } - return nil -} - // IngAttemptKey a key that identifies a preloading attempt. The url used is // the url specified by the trigger (i.e. the initial URL), and not the final // url that is navigated to. For example, prerendering allows same-origin main @@ -271,170 +216,6 @@ const ( PrerenderFinalStatusCrossDocumentRestart PrerenderFinalStatus = "CrossDocumentRestart" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *PrerenderFinalStatus) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch PrerenderFinalStatus(s) { - case PrerenderFinalStatusActivated: - *t = PrerenderFinalStatusActivated - case PrerenderFinalStatusDestroyed: - *t = PrerenderFinalStatusDestroyed - case PrerenderFinalStatusLowEndDevice: - *t = PrerenderFinalStatusLowEndDevice - case PrerenderFinalStatusInvalidSchemeRedirect: - *t = PrerenderFinalStatusInvalidSchemeRedirect - case PrerenderFinalStatusInvalidSchemeNavigation: - *t = PrerenderFinalStatusInvalidSchemeNavigation - case PrerenderFinalStatusNavigationRequestBlockedByCsp: - *t = PrerenderFinalStatusNavigationRequestBlockedByCsp - case PrerenderFinalStatusMojoBinderPolicy: - *t = PrerenderFinalStatusMojoBinderPolicy - case PrerenderFinalStatusRendererProcessCrashed: - *t = PrerenderFinalStatusRendererProcessCrashed - case PrerenderFinalStatusRendererProcessKilled: - *t = PrerenderFinalStatusRendererProcessKilled - case PrerenderFinalStatusDownload: - *t = PrerenderFinalStatusDownload - case PrerenderFinalStatusTriggerDestroyed: - *t = PrerenderFinalStatusTriggerDestroyed - case PrerenderFinalStatusNavigationNotCommitted: - *t = PrerenderFinalStatusNavigationNotCommitted - case PrerenderFinalStatusNavigationBadHTTPStatus: - *t = PrerenderFinalStatusNavigationBadHTTPStatus - case PrerenderFinalStatusClientCertRequested: - *t = PrerenderFinalStatusClientCertRequested - case PrerenderFinalStatusNavigationRequestNetworkError: - *t = PrerenderFinalStatusNavigationRequestNetworkError - case PrerenderFinalStatusCancelAllHostsForTesting: - *t = PrerenderFinalStatusCancelAllHostsForTesting - case PrerenderFinalStatusDidFailLoad: - *t = PrerenderFinalStatusDidFailLoad - case PrerenderFinalStatusStop: - *t = PrerenderFinalStatusStop - case PrerenderFinalStatusSslCertificateError: - *t = PrerenderFinalStatusSslCertificateError - case PrerenderFinalStatusLoginAuthRequested: - *t = PrerenderFinalStatusLoginAuthRequested - case PrerenderFinalStatusUaChangeRequiresReload: - *t = PrerenderFinalStatusUaChangeRequiresReload - case PrerenderFinalStatusBlockedByClient: - *t = PrerenderFinalStatusBlockedByClient - case PrerenderFinalStatusAudioOutputDeviceRequested: - *t = PrerenderFinalStatusAudioOutputDeviceRequested - case PrerenderFinalStatusMixedContent: - *t = PrerenderFinalStatusMixedContent - case PrerenderFinalStatusTriggerBackgrounded: - *t = PrerenderFinalStatusTriggerBackgrounded - case PrerenderFinalStatusMemoryLimitExceeded: - *t = PrerenderFinalStatusMemoryLimitExceeded - case PrerenderFinalStatusDataSaverEnabled: - *t = PrerenderFinalStatusDataSaverEnabled - case PrerenderFinalStatusTriggerURLHasEffectiveURL: - *t = PrerenderFinalStatusTriggerURLHasEffectiveURL - case PrerenderFinalStatusActivatedBeforeStarted: - *t = PrerenderFinalStatusActivatedBeforeStarted - case PrerenderFinalStatusInactivePageRestriction: - *t = PrerenderFinalStatusInactivePageRestriction - case PrerenderFinalStatusStartFailed: - *t = PrerenderFinalStatusStartFailed - case PrerenderFinalStatusTimeoutBackgrounded: - *t = PrerenderFinalStatusTimeoutBackgrounded - case PrerenderFinalStatusCrossSiteRedirectInInitialNavigation: - *t = PrerenderFinalStatusCrossSiteRedirectInInitialNavigation - case PrerenderFinalStatusCrossSiteNavigationInInitialNavigation: - *t = PrerenderFinalStatusCrossSiteNavigationInInitialNavigation - case PrerenderFinalStatusSameSiteCrossOriginRedirectNotOptInInInitialNavigation: - *t = PrerenderFinalStatusSameSiteCrossOriginRedirectNotOptInInInitialNavigation - case PrerenderFinalStatusSameSiteCrossOriginNavigationNotOptInInInitialNavigation: - *t = PrerenderFinalStatusSameSiteCrossOriginNavigationNotOptInInInitialNavigation - case PrerenderFinalStatusActivationNavigationParameterMismatch: - *t = PrerenderFinalStatusActivationNavigationParameterMismatch - case PrerenderFinalStatusActivatedInBackground: - *t = PrerenderFinalStatusActivatedInBackground - case PrerenderFinalStatusEmbedderHostDisallowed: - *t = PrerenderFinalStatusEmbedderHostDisallowed - case PrerenderFinalStatusActivationNavigationDestroyedBeforeSuccess: - *t = PrerenderFinalStatusActivationNavigationDestroyedBeforeSuccess - case PrerenderFinalStatusTabClosedByUserGesture: - *t = PrerenderFinalStatusTabClosedByUserGesture - case PrerenderFinalStatusTabClosedWithoutUserGesture: - *t = PrerenderFinalStatusTabClosedWithoutUserGesture - case PrerenderFinalStatusPrimaryMainFrameRendererProcessCrashed: - *t = PrerenderFinalStatusPrimaryMainFrameRendererProcessCrashed - case PrerenderFinalStatusPrimaryMainFrameRendererProcessKilled: - *t = PrerenderFinalStatusPrimaryMainFrameRendererProcessKilled - case PrerenderFinalStatusActivationFramePolicyNotCompatible: - *t = PrerenderFinalStatusActivationFramePolicyNotCompatible - case PrerenderFinalStatusPreloadingDisabled: - *t = PrerenderFinalStatusPreloadingDisabled - case PrerenderFinalStatusBatterySaverEnabled: - *t = PrerenderFinalStatusBatterySaverEnabled - case PrerenderFinalStatusActivatedDuringMainFrameNavigation: - *t = PrerenderFinalStatusActivatedDuringMainFrameNavigation - case PrerenderFinalStatusPreloadingUnsupportedByWebContents: - *t = PrerenderFinalStatusPreloadingUnsupportedByWebContents - case PrerenderFinalStatusCrossSiteRedirectInMainFrameNavigation: - *t = PrerenderFinalStatusCrossSiteRedirectInMainFrameNavigation - case PrerenderFinalStatusCrossSiteNavigationInMainFrameNavigation: - *t = PrerenderFinalStatusCrossSiteNavigationInMainFrameNavigation - case PrerenderFinalStatusSameSiteCrossOriginRedirectNotOptInInMainFrameNavigation: - *t = PrerenderFinalStatusSameSiteCrossOriginRedirectNotOptInInMainFrameNavigation - case PrerenderFinalStatusSameSiteCrossOriginNavigationNotOptInInMainFrameNavigation: - *t = PrerenderFinalStatusSameSiteCrossOriginNavigationNotOptInInMainFrameNavigation - case PrerenderFinalStatusMemoryPressureOnTrigger: - *t = PrerenderFinalStatusMemoryPressureOnTrigger - case PrerenderFinalStatusMemoryPressureAfterTriggered: - *t = PrerenderFinalStatusMemoryPressureAfterTriggered - case PrerenderFinalStatusPrerenderingDisabledByDevTools: - *t = PrerenderFinalStatusPrerenderingDisabledByDevTools - case PrerenderFinalStatusSpeculationRuleRemoved: - *t = PrerenderFinalStatusSpeculationRuleRemoved - case PrerenderFinalStatusActivatedWithAuxiliaryBrowsingContexts: - *t = PrerenderFinalStatusActivatedWithAuxiliaryBrowsingContexts - case PrerenderFinalStatusMaxNumOfRunningEagerPrerendersExceeded: - *t = PrerenderFinalStatusMaxNumOfRunningEagerPrerendersExceeded - case PrerenderFinalStatusMaxNumOfRunningNonEagerPrerendersExceeded: - *t = PrerenderFinalStatusMaxNumOfRunningNonEagerPrerendersExceeded - case PrerenderFinalStatusMaxNumOfRunningEmbedderPrerendersExceeded: - *t = PrerenderFinalStatusMaxNumOfRunningEmbedderPrerendersExceeded - case PrerenderFinalStatusPrerenderingURLHasEffectiveURL: - *t = PrerenderFinalStatusPrerenderingURLHasEffectiveURL - case PrerenderFinalStatusRedirectedPrerenderingURLHasEffectiveURL: - *t = PrerenderFinalStatusRedirectedPrerenderingURLHasEffectiveURL - case PrerenderFinalStatusActivationURLHasEffectiveURL: - *t = PrerenderFinalStatusActivationURLHasEffectiveURL - case PrerenderFinalStatusJavaScriptInterfaceAdded: - *t = PrerenderFinalStatusJavaScriptInterfaceAdded - case PrerenderFinalStatusJavaScriptInterfaceRemoved: - *t = PrerenderFinalStatusJavaScriptInterfaceRemoved - case PrerenderFinalStatusAllPrerenderingCanceled: - *t = PrerenderFinalStatusAllPrerenderingCanceled - case PrerenderFinalStatusWindowClosed: - *t = PrerenderFinalStatusWindowClosed - case PrerenderFinalStatusSlowNetwork: - *t = PrerenderFinalStatusSlowNetwork - case PrerenderFinalStatusOtherPrerenderedPageActivated: - *t = PrerenderFinalStatusOtherPrerenderedPageActivated - case PrerenderFinalStatusV8optimizerDisabled: - *t = PrerenderFinalStatusV8optimizerDisabled - case PrerenderFinalStatusPrerenderFailedDuringPrefetch: - *t = PrerenderFinalStatusPrerenderFailedDuringPrefetch - case PrerenderFinalStatusBrowsingDataRemoved: - *t = PrerenderFinalStatusBrowsingDataRemoved - case PrerenderFinalStatusPrerenderHostReused: - *t = PrerenderFinalStatusPrerenderHostReused - case PrerenderFinalStatusFormSubmitWhenPrerendering: - *t = PrerenderFinalStatusFormSubmitWhenPrerendering - case PrerenderFinalStatusCrossDocumentRestart: - *t = PrerenderFinalStatusCrossDocumentRestart - default: - return fmt.Errorf("unknown PrerenderFinalStatus value: %v", s) - } - return nil -} - // IngStatus preloading status values, see also PreloadingTriggeringOutcome. // This status is shared by prefetchStatusUpdated and prerenderStatusUpdated. // @@ -456,30 +237,6 @@ const ( IngStatusNotSupported IngStatus = "NotSupported" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *IngStatus) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch IngStatus(s) { - case IngStatusPending: - *t = IngStatusPending - case IngStatusRunning: - *t = IngStatusRunning - case IngStatusReady: - *t = IngStatusReady - case IngStatusSuccess: - *t = IngStatusSuccess - case IngStatusFailure: - *t = IngStatusFailure - case IngStatusNotSupported: - *t = IngStatusNotSupported - default: - return fmt.Errorf("unknown IngStatus value: %v", s) - } - return nil -} - // PrefetchStatus tODO(https://crbug.com/1384419): revisit the list of // PrefetchStatus and filter out the ones that aren't necessary to the // developers. @@ -509,6 +266,7 @@ const ( PrefetchStatusPrefetchIsStale PrefetchStatus = "PrefetchIsStale" PrefetchStatusPrefetchNotEligibleBlockedByConnectionAllowlist PrefetchStatus = "PrefetchNotEligibleBlockedByConnectionAllowlist" PrefetchStatusPrefetchNotEligibleBrowserContextOffTheRecord PrefetchStatus = "PrefetchNotEligibleBrowserContextOffTheRecord" + PrefetchStatusPrefetchNotEligibleCrossOrigin PrefetchStatus = "PrefetchNotEligibleCrossOrigin" PrefetchStatusPrefetchNotEligibleDataSaverEnabled PrefetchStatus = "PrefetchNotEligibleDataSaverEnabled" PrefetchStatusPrefetchNotEligibleExistingProxy PrefetchStatus = "PrefetchNotEligibleExistingProxy" PrefetchStatusPrefetchNotEligibleHostIsNonUnique PrefetchStatus = "PrefetchNotEligibleHostIsNonUnique" @@ -532,90 +290,6 @@ const ( PrefetchStatusPrefetchCancelledOnUserNavigation PrefetchStatus = "PrefetchCancelledOnUserNavigation" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *PrefetchStatus) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch PrefetchStatus(s) { - case PrefetchStatusPrefetchAllowed: - *t = PrefetchStatusPrefetchAllowed - case PrefetchStatusPrefetchFailedIneligibleRedirect: - *t = PrefetchStatusPrefetchFailedIneligibleRedirect - case PrefetchStatusPrefetchFailedInvalidRedirect: - *t = PrefetchStatusPrefetchFailedInvalidRedirect - case PrefetchStatusPrefetchFailedMIMENotSupported: - *t = PrefetchStatusPrefetchFailedMIMENotSupported - case PrefetchStatusPrefetchFailedNetError: - *t = PrefetchStatusPrefetchFailedNetError - case PrefetchStatusPrefetchFailedNon2xX: - *t = PrefetchStatusPrefetchFailedNon2xX - case PrefetchStatusPrefetchEvictedAfterBrowsingDataRemoved: - *t = PrefetchStatusPrefetchEvictedAfterBrowsingDataRemoved - case PrefetchStatusPrefetchEvictedAfterCandidateRemoved: - *t = PrefetchStatusPrefetchEvictedAfterCandidateRemoved - case PrefetchStatusPrefetchEvictedForNewerPrefetch: - *t = PrefetchStatusPrefetchEvictedForNewerPrefetch - case PrefetchStatusPrefetchHeldback: - *t = PrefetchStatusPrefetchHeldback - case PrefetchStatusPrefetchIneligibleRetryAfter: - *t = PrefetchStatusPrefetchIneligibleRetryAfter - case PrefetchStatusPrefetchIsPrivacyDecoy: - *t = PrefetchStatusPrefetchIsPrivacyDecoy - case PrefetchStatusPrefetchIsStale: - *t = PrefetchStatusPrefetchIsStale - case PrefetchStatusPrefetchNotEligibleBlockedByConnectionAllowlist: - *t = PrefetchStatusPrefetchNotEligibleBlockedByConnectionAllowlist - case PrefetchStatusPrefetchNotEligibleBrowserContextOffTheRecord: - *t = PrefetchStatusPrefetchNotEligibleBrowserContextOffTheRecord - case PrefetchStatusPrefetchNotEligibleDataSaverEnabled: - *t = PrefetchStatusPrefetchNotEligibleDataSaverEnabled - case PrefetchStatusPrefetchNotEligibleExistingProxy: - *t = PrefetchStatusPrefetchNotEligibleExistingProxy - case PrefetchStatusPrefetchNotEligibleHostIsNonUnique: - *t = PrefetchStatusPrefetchNotEligibleHostIsNonUnique - case PrefetchStatusPrefetchNotEligibleNonDefaultStoragePartition: - *t = PrefetchStatusPrefetchNotEligibleNonDefaultStoragePartition - case PrefetchStatusPrefetchNotEligibleSameSiteCrossOriginPrefetchRequiredProxy: - *t = PrefetchStatusPrefetchNotEligibleSameSiteCrossOriginPrefetchRequiredProxy - case PrefetchStatusPrefetchNotEligibleSchemeIsNotHTTPS: - *t = PrefetchStatusPrefetchNotEligibleSchemeIsNotHTTPS - case PrefetchStatusPrefetchNotEligibleUserHasCookies: - *t = PrefetchStatusPrefetchNotEligibleUserHasCookies - case PrefetchStatusPrefetchNotEligibleUserHasServiceWorker: - *t = PrefetchStatusPrefetchNotEligibleUserHasServiceWorker - case PrefetchStatusPrefetchNotEligibleUserHasServiceWorkerNoFetchHandler: - *t = PrefetchStatusPrefetchNotEligibleUserHasServiceWorkerNoFetchHandler - case PrefetchStatusPrefetchNotEligibleRedirectFromServiceWorker: - *t = PrefetchStatusPrefetchNotEligibleRedirectFromServiceWorker - case PrefetchStatusPrefetchNotEligibleRedirectToServiceWorker: - *t = PrefetchStatusPrefetchNotEligibleRedirectToServiceWorker - case PrefetchStatusPrefetchNotEligibleBatterySaverEnabled: - *t = PrefetchStatusPrefetchNotEligibleBatterySaverEnabled - case PrefetchStatusPrefetchNotEligiblePreloadingDisabled: - *t = PrefetchStatusPrefetchNotEligiblePreloadingDisabled - case PrefetchStatusPrefetchNotFinishedInTime: - *t = PrefetchStatusPrefetchNotFinishedInTime - case PrefetchStatusPrefetchNotStarted: - *t = PrefetchStatusPrefetchNotStarted - case PrefetchStatusPrefetchNotUsedCookiesChanged: - *t = PrefetchStatusPrefetchNotUsedCookiesChanged - case PrefetchStatusPrefetchProxyNotAvailable: - *t = PrefetchStatusPrefetchProxyNotAvailable - case PrefetchStatusPrefetchResponseUsed: - *t = PrefetchStatusPrefetchResponseUsed - case PrefetchStatusPrefetchSuccessfulButNotUsed: - *t = PrefetchStatusPrefetchSuccessfulButNotUsed - case PrefetchStatusPrefetchNotUsedProbeFailed: - *t = PrefetchStatusPrefetchNotUsedProbeFailed - case PrefetchStatusPrefetchCancelledOnUserNavigation: - *t = PrefetchStatusPrefetchCancelledOnUserNavigation - default: - return fmt.Errorf("unknown PrefetchStatus value: %v", s) - } - return nil -} - // PrerenderMismatchedHeaders information of headers to be displayed when the // header mismatch occurred. // diff --git a/vendor/github.com/chromedp/cdproto/profiler/events.go b/vendor/github.com/chromedp/cdproto/profiler/events.go index ddea94821..53a28ce22 100644 --- a/vendor/github.com/chromedp/cdproto/profiler/events.go +++ b/vendor/github.com/chromedp/cdproto/profiler/events.go @@ -1,6 +1,6 @@ -package profiler +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package profiler import ( "github.com/chromedp/cdproto/debugger" diff --git a/vendor/github.com/chromedp/cdproto/profiler/profiler.go b/vendor/github.com/chromedp/cdproto/profiler/profiler.go index ba5e0e8d1..bbbae8e0a 100644 --- a/vendor/github.com/chromedp/cdproto/profiler/profiler.go +++ b/vendor/github.com/chromedp/cdproto/profiler/profiler.go @@ -1,82 +1,39 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package profiler provides the Chrome DevTools Protocol // commands, types, and events for the Profiler domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package profiler -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// DisableParams [no description]. -type DisableParams struct{} - // Disable [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes Profiler.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// EnableParams [no description]. -type EnableParams struct{} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} // Enable [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} -// Do executes Profiler.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) +// GetBestEffortCoverageResult is the result of the command +// Profiler.getBestEffortCoverage. +type GetBestEffortCoverageResult struct { + Result []*ScriptCoverage `json:"result,omitempty,omitzero"` // Coverage data for the current isolate. } -// GetBestEffortCoverageParams collect coverage data for the current isolate. -// The coverage data may be incomplete due to garbage collection. -type GetBestEffortCoverageParams struct{} - // GetBestEffortCoverage collect coverage data for the current isolate. The // coverage data may be incomplete due to garbage collection. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-getBestEffortCoverage -func GetBestEffortCoverage() *GetBestEffortCoverageParams { - return &GetBestEffortCoverageParams{} -} - -// GetBestEffortCoverageReturns return values. -type GetBestEffortCoverageReturns struct { - Result []*ScriptCoverage `json:"result,omitempty,omitzero"` // Coverage data for the current isolate. -} - -// Do executes Profiler.getBestEffortCoverage against the provided context. -// -// returns: -// -// result - Coverage data for the current isolate. -func (p *GetBestEffortCoverageParams) Do(ctx context.Context) (result []*ScriptCoverage, err error) { - // execute - var res GetBestEffortCoverageReturns - err = cdp.Execute(ctx, CommandGetBestEffortCoverage, nil, &res) - if err != nil { - return nil, err - } +var GetBestEffortCoverage = cdp.Command[cdp.Empty, GetBestEffortCoverageResult]{Method: CommandGetBestEffortCoverage} - return res.Result, nil -} - -// SetSamplingIntervalParams changes CPU profiler sampling interval. Must be -// called before CPU profiles recording started. +// SetSamplingIntervalParams are the parameters of the command +// Profiler.setSamplingInterval. type SetSamplingIntervalParams struct { Interval int64 `json:"interval"` // New sampling interval in microseconds. } @@ -85,43 +42,25 @@ type SetSamplingIntervalParams struct { // before CPU profiles recording started. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-setSamplingInterval -// -// parameters: -// -// interval - New sampling interval in microseconds. -func SetSamplingInterval(interval int64) *SetSamplingIntervalParams { - return &SetSamplingIntervalParams{ - Interval: interval, - } -} - -// Do executes Profiler.setSamplingInterval against the provided context. -func (p *SetSamplingIntervalParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetSamplingInterval, p, nil) -} - -// StartParams [no description]. -type StartParams struct{} +var SetSamplingInterval = cdp.Command[SetSamplingIntervalParams, cdp.Empty]{Method: CommandSetSamplingInterval} // Start [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-start -func Start() *StartParams { - return &StartParams{} -} +var Start = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandStart} -// Do executes Profiler.start against the provided context. -func (p *StartParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStart, nil, nil) +// StartPreciseCoverageParams are the parameters of the command +// Profiler.startPreciseCoverage. +type StartPreciseCoverageParams struct { + CallCount *bool `json:"callCount,omitempty,omitzero"` // Collect accurate call counts beyond simple 'covered' or 'not covered'. + Detailed *bool `json:"detailed,omitempty,omitzero"` // Collect block-based coverage. + AllowTriggeredUpdates *bool `json:"allowTriggeredUpdates,omitempty,omitzero"` // Allow the backend to send updates on its own initiative } -// StartPreciseCoverageParams 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. -type StartPreciseCoverageParams struct { - CallCount bool `json:"callCount"` // Collect accurate call counts beyond simple 'covered' or 'not covered'. - Detailed bool `json:"detailed"` // Collect block-based coverage. - AllowTriggeredUpdates bool `json:"allowTriggeredUpdates"` // Allow the backend to send updates on its own initiative +// StartPreciseCoverageResult is the result of the command +// Profiler.startPreciseCoverage. +type StartPreciseCoverageResult struct { + Timestamp float64 `json:"timestamp,omitempty,omitzero"` // Monotonically increasing time (in seconds) when the coverage update was taken in the backend. } // StartPreciseCoverage enable precise code coverage. Coverage data for @@ -129,140 +68,56 @@ type StartPreciseCoverageParams struct { // Enabling prevents running optimized code and resets execution counters. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-startPreciseCoverage -// -// parameters: -func StartPreciseCoverage() *StartPreciseCoverageParams { - return &StartPreciseCoverageParams{ - CallCount: false, - Detailed: false, - AllowTriggeredUpdates: false, - } -} - -// WithCallCount collect accurate call counts beyond simple 'covered' or 'not -// covered'. -func (p StartPreciseCoverageParams) WithCallCount(callCount bool) *StartPreciseCoverageParams { - p.CallCount = callCount - return &p -} - -// WithDetailed collect block-based coverage. -func (p StartPreciseCoverageParams) WithDetailed(detailed bool) *StartPreciseCoverageParams { - p.Detailed = detailed - return &p -} - -// WithAllowTriggeredUpdates allow the backend to send updates on its own -// initiative. -func (p StartPreciseCoverageParams) WithAllowTriggeredUpdates(allowTriggeredUpdates bool) *StartPreciseCoverageParams { - p.AllowTriggeredUpdates = allowTriggeredUpdates - return &p -} - -// StartPreciseCoverageReturns return values. -type StartPreciseCoverageReturns struct { - Timestamp float64 `json:"timestamp,omitempty,omitzero"` // Monotonically increasing time (in seconds) when the coverage update was taken in the backend. -} - -// Do executes Profiler.startPreciseCoverage against the provided context. -// -// returns: -// -// timestamp - Monotonically increasing time (in seconds) when the coverage update was taken in the backend. -func (p *StartPreciseCoverageParams) Do(ctx context.Context) (timestamp float64, err error) { - // execute - var res StartPreciseCoverageReturns - err = cdp.Execute(ctx, CommandStartPreciseCoverage, p, &res) - if err != nil { - return 0, err - } +var StartPreciseCoverage = cdp.Command[StartPreciseCoverageParams, StartPreciseCoverageResult]{Method: CommandStartPreciseCoverage} - return res.Timestamp, nil +// StopResult is the result of the command Profiler.stop. +type StopResult struct { + Profile *Profile `json:"profile,omitempty,omitzero"` // Recorded profile. } -// StopParams [no description]. -type StopParams struct{} - // Stop [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-stop -func Stop() *StopParams { - return &StopParams{} -} - -// StopReturns return values. -type StopReturns struct { - Profile *Profile `json:"profile,omitempty,omitzero"` // Recorded profile. -} - -// Do executes Profiler.stop against the provided context. -// -// returns: -// -// profile - Recorded profile. -func (p *StopParams) Do(ctx context.Context) (profile *Profile, err error) { - // execute - var res StopReturns - err = cdp.Execute(ctx, CommandStop, nil, &res) - if err != nil { - return nil, err - } - - return res.Profile, nil -} - -// StopPreciseCoverageParams disable precise code coverage. Disabling -// releases unnecessary execution count records and allows executing optimized -// code. -type StopPreciseCoverageParams struct{} +var Stop = cdp.Command[cdp.Empty, StopResult]{Method: CommandStop} // StopPreciseCoverage disable precise code coverage. Disabling releases // unnecessary execution count records and allows executing optimized code. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-stopPreciseCoverage -func StopPreciseCoverage() *StopPreciseCoverageParams { - return &StopPreciseCoverageParams{} -} +var StopPreciseCoverage = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandStopPreciseCoverage} -// Do executes Profiler.stopPreciseCoverage against the provided context. -func (p *StopPreciseCoverageParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStopPreciseCoverage, nil, nil) +// TakePreciseCoverageResult is the result of the command +// Profiler.takePreciseCoverage. +type TakePreciseCoverageResult struct { + Result []*ScriptCoverage `json:"result,omitempty,omitzero"` // Coverage data for the current isolate. + Timestamp float64 `json:"timestamp,omitempty,omitzero"` // Monotonically increasing time (in seconds) when the coverage update was taken in the backend. } -// TakePreciseCoverageParams collect coverage data for the current isolate, -// and resets execution counters. Precise code coverage needs to have started. -type TakePreciseCoverageParams struct{} - // TakePreciseCoverage collect coverage data for the current isolate, and // resets execution counters. Precise code coverage needs to have started. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-takePreciseCoverage -func TakePreciseCoverage() *TakePreciseCoverageParams { - return &TakePreciseCoverageParams{} -} - -// TakePreciseCoverageReturns return values. -type TakePreciseCoverageReturns struct { - Result []*ScriptCoverage `json:"result,omitempty,omitzero"` // Coverage data for the current isolate. - Timestamp float64 `json:"timestamp,omitempty,omitzero"` // Monotonically increasing time (in seconds) when the coverage update was taken in the backend. -} +var TakePreciseCoverage = cdp.Command[cdp.Empty, TakePreciseCoverageResult]{Method: CommandTakePreciseCoverage} -// Do executes Profiler.takePreciseCoverage against the provided context. +// ConsoleProfileFinished [no description]. // -// returns: +// See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#event-consoleProfileFinished +var ConsoleProfileFinished = cdp.Event[EventConsoleProfileFinished]{Method: "Profiler.consoleProfileFinished"} + +// ConsoleProfileStarted sent when new profile recording is started using +// console.profile() call. // -// result - Coverage data for the current isolate. -// timestamp - Monotonically increasing time (in seconds) when the coverage update was taken in the backend. -func (p *TakePreciseCoverageParams) Do(ctx context.Context) (result []*ScriptCoverage, timestamp float64, err error) { - // execute - var res TakePreciseCoverageReturns - err = cdp.Execute(ctx, CommandTakePreciseCoverage, nil, &res) - if err != nil { - return nil, 0, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#event-consoleProfileStarted +var ConsoleProfileStarted = cdp.Event[EventConsoleProfileStarted]{Method: "Profiler.consoleProfileStarted"} - return res.Result, res.Timestamp, nil -} +// PreciseCoverageDeltaUpdate reports coverage delta since the last poll +// (either from an event like this, or from takePreciseCoverage for the current +// isolate. May only be sent if precise code coverage has been started. This +// event can be trigged by the embedder to, for example, trigger collection of +// coverage data immediately at a certain point in time. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#event-preciseCoverageDeltaUpdate +var PreciseCoverageDeltaUpdate = cdp.Event[EventPreciseCoverageDeltaUpdate]{Method: "Profiler.preciseCoverageDeltaUpdate"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/profiler/types.go b/vendor/github.com/chromedp/cdproto/profiler/types.go index 7e89c8912..5d3214c8c 100644 --- a/vendor/github.com/chromedp/cdproto/profiler/types.go +++ b/vendor/github.com/chromedp/cdproto/profiler/types.go @@ -1,6 +1,6 @@ -package profiler +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package profiler import ( "github.com/chromedp/cdproto/cdp" diff --git a/vendor/github.com/chromedp/cdproto/pwa/pwa.go b/vendor/github.com/chromedp/cdproto/pwa/pwa.go index 918d38f41..4a372b8a3 100644 --- a/vendor/github.com/chromedp/cdproto/pwa/pwa.go +++ b/vendor/github.com/chromedp/cdproto/pwa/pwa.go @@ -1,78 +1,35 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package pwa provides the Chrome DevTools Protocol // commands, types, and events for the PWA domain. // // This domain allows interacting with the browser to control PWAs. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package pwa -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/target" ) -// GetOsAppStateParams returns the following OS state for the given manifest -// id. +// GetOsAppStateParams are the parameters of the command PWA.getOsAppState. type GetOsAppStateParams struct { ManifestID string `json:"manifestId"` // The id from the webapp's manifest file, commonly it's the url of the site installing the webapp. See https://web.dev/learn/pwa/web-app-manifest. } -// GetOsAppState returns the following OS state for the given manifest id. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/PWA#method-getOsAppState -// -// parameters: -// -// manifestID - The id from the webapp's manifest file, commonly it's the url of the site installing the webapp. See https://web.dev/learn/pwa/web-app-manifest. -func GetOsAppState(manifestID string) *GetOsAppStateParams { - return &GetOsAppStateParams{ - ManifestID: manifestID, - } -} - -// GetOsAppStateReturns return values. -type GetOsAppStateReturns struct { +// GetOsAppStateResult is the result of the command PWA.getOsAppState. +type GetOsAppStateResult struct { BadgeCount int64 `json:"badgeCount,omitempty,omitzero"` FileHandlers []*FileHandler `json:"fileHandlers,omitempty,omitzero"` } -// Do executes PWA.getOsAppState against the provided context. -// -// returns: +// GetOsAppState returns the following OS state for the given manifest id. // -// badgeCount -// fileHandlers -func (p *GetOsAppStateParams) Do(ctx context.Context) (badgeCount int64, fileHandlers []*FileHandler, err error) { - // execute - var res GetOsAppStateReturns - err = cdp.Execute(ctx, CommandGetOsAppState, p, &res) - if err != nil { - return 0, nil, err - } - - return res.BadgeCount, res.FileHandlers, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/PWA#method-getOsAppState +var GetOsAppState = cdp.Command[GetOsAppStateParams, GetOsAppStateResult]{Method: CommandGetOsAppState} -// InstallParams installs the given manifest identity, optionally using the -// given installUrlOrBundleUrl IWA-specific install description: manifestId -// corresponds to isolated-app:// + web_package::SignedWebBundleId File -// installation mode: The installUrlOrBundleUrl can be either file:// or -// http(s):// pointing to a signed web bundle (.swbn). In this case -// SignedWebBundleId must correspond to The .swbn file's signing key. Dev proxy -// installation mode: installUrlOrBundleUrl must be http(s):// that serves dev -// mode IWA. web_package::SignedWebBundleId must be of type dev proxy. The -// advantage of dev proxy mode is that all changes to IWA automatically will be -// reflected in the running app without reinstallation. To generate bundle id -// for proxy mode: 1. Generate 32 random bytes. 2. Add a specific suffix at the -// end following the documentation -// https://github.com/WICG/isolated-web-apps/blob/main/Scheme.md#suffix 3. -// Encode the entire sequence using Base32 without padding. If Chrome is not in -// IWA dev mode, the installation will fail, regardless of the state of the -// allowlist. +// InstallParams are the parameters of the command PWA.install. type InstallParams struct { ManifestID string `json:"manifestId"` InstallURLOrBundleURL string `json:"installUrlOrBundleUrl,omitempty,omitzero"` // The location of the app or bundle overriding the one derived from the manifestId. @@ -96,30 +53,9 @@ type InstallParams struct { // allowlist. // // See: https://chromedevtools.github.io/devtools-protocol/tot/PWA#method-install -// -// parameters: -// -// manifestID -func Install(manifestID string) *InstallParams { - return &InstallParams{ - ManifestID: manifestID, - } -} - -// WithInstallURLOrBundleURL the location of the app or bundle overriding the -// one derived from the manifestId. -func (p InstallParams) WithInstallURLOrBundleURL(installURLOrBundleURL string) *InstallParams { - p.InstallURLOrBundleURL = installURLOrBundleURL - return &p -} +var Install = cdp.Command[InstallParams, cdp.Empty]{Method: CommandInstall} -// Do executes PWA.install against the provided context. -func (p *InstallParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandInstall, p, nil) -} - -// UninstallParams uninstalls the given manifest_id and closes any opened app -// windows. +// UninstallParams are the parameters of the command PWA.uninstall. type UninstallParams struct { ManifestID string `json:"manifestId"` } @@ -128,89 +64,39 @@ type UninstallParams struct { // windows. // // See: https://chromedevtools.github.io/devtools-protocol/tot/PWA#method-uninstall -// -// parameters: -// -// manifestID -func Uninstall(manifestID string) *UninstallParams { - return &UninstallParams{ - ManifestID: manifestID, - } -} +var Uninstall = cdp.Command[UninstallParams, cdp.Empty]{Method: CommandUninstall} -// Do executes PWA.uninstall against the provided context. -func (p *UninstallParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandUninstall, p, nil) -} - -// LaunchParams launches the installed web app, or an url in the same web app -// instead of the default start url if it is provided. Returns a page -// Target.TargetID which can be used to attach to via Target.attachToTarget or -// similar APIs. +// LaunchParams are the parameters of the command PWA.launch. type LaunchParams struct { ManifestID string `json:"manifestId"` URL string `json:"url,omitempty,omitzero"` } +// LaunchResult is the result of the command PWA.launch. +type LaunchResult struct { + TargetID target.ID `json:"targetId,omitempty,omitzero"` // ID of the tab target created as a result. +} + // Launch launches the installed web app, or an url in the same web app // instead of the default start url if it is provided. Returns a page // Target.TargetID which can be used to attach to via Target.attachToTarget or // similar APIs. // // See: https://chromedevtools.github.io/devtools-protocol/tot/PWA#method-launch -// -// parameters: -// -// manifestID -func Launch(manifestID string) *LaunchParams { - return &LaunchParams{ - ManifestID: manifestID, - } -} - -// WithURL [no description]. -func (p LaunchParams) WithURL(url string) *LaunchParams { - p.URL = url - return &p -} - -// LaunchReturns return values. -type LaunchReturns struct { - TargetID target.ID `json:"targetId,omitempty,omitzero"` // ID of the tab target created as a result. -} +var Launch = cdp.Command[LaunchParams, LaunchResult]{Method: CommandLaunch} -// Do executes PWA.launch against the provided context. -// -// returns: -// -// targetID - ID of the tab target created as a result. -func (p *LaunchParams) Do(ctx context.Context) (targetID target.ID, err error) { - // execute - var res LaunchReturns - err = cdp.Execute(ctx, CommandLaunch, p, &res) - if err != nil { - return "", err - } - - return res.TargetID, nil -} - -// LaunchFilesInAppParams opens one or more local files from an installed web -// app identified by its manifestId. The web app needs to have file handlers -// registered to process the files. The API returns one or more page -// Target.TargetIDs which can be used to attach to via Target.attachToTarget or -// similar APIs. If some files in the parameters cannot be handled by the web -// app, they will be ignored. If none of the files can be handled, this API -// returns an error. If no files are provided as the parameter, this API also -// returns an error. According to the definition of the file handlers in the -// manifest file, one Target.TargetID may represent a page handling one or more -// files. The order of the returned Target.TargetIDs is not guaranteed. -// TODO(crbug.com/339454034): Check the existences of the input files. +// LaunchFilesInAppParams are the parameters of the command +// PWA.launchFilesInApp. type LaunchFilesInAppParams struct { ManifestID string `json:"manifestId"` Files []string `json:"files"` } +// LaunchFilesInAppResult is the result of the command PWA.launchFilesInApp. +type LaunchFilesInAppResult struct { + TargetIDs []target.ID `json:"targetIds,omitempty,omitzero"` // IDs of the tab targets created as the result. +} + // LaunchFilesInApp opens one or more local files from an installed web app // identified by its manifestId. The web app needs to have file handlers // registered to process the files. The API returns one or more page @@ -224,42 +110,10 @@ type LaunchFilesInAppParams struct { // TODO(crbug.com/339454034): Check the existences of the input files. // // See: https://chromedevtools.github.io/devtools-protocol/tot/PWA#method-launchFilesInApp -// -// parameters: -// -// manifestID -// files -func LaunchFilesInApp(manifestID string, files []string) *LaunchFilesInAppParams { - return &LaunchFilesInAppParams{ - ManifestID: manifestID, - Files: files, - } -} - -// LaunchFilesInAppReturns return values. -type LaunchFilesInAppReturns struct { - TargetIDs []target.ID `json:"targetIds,omitempty,omitzero"` // IDs of the tab targets created as the result. -} - -// Do executes PWA.launchFilesInApp against the provided context. -// -// returns: -// -// targetIDs - IDs of the tab targets created as the result. -func (p *LaunchFilesInAppParams) Do(ctx context.Context) (targetIDs []target.ID, err error) { - // execute - var res LaunchFilesInAppReturns - err = cdp.Execute(ctx, CommandLaunchFilesInApp, p, &res) - if err != nil { - return nil, err - } - - return res.TargetIDs, nil -} +var LaunchFilesInApp = cdp.Command[LaunchFilesInAppParams, LaunchFilesInAppResult]{Method: CommandLaunchFilesInApp} -// OpenCurrentPageInAppParams opens the current page in its web app -// identified by the manifest id, needs to be called on a page target. This -// function returns immediately without waiting for the app to finish loading. +// OpenCurrentPageInAppParams are the parameters of the command +// PWA.openCurrentPageInApp. type OpenCurrentPageInAppParams struct { ManifestID string `json:"manifestId"` } @@ -269,31 +123,13 @@ type OpenCurrentPageInAppParams struct { // immediately without waiting for the app to finish loading. // // See: https://chromedevtools.github.io/devtools-protocol/tot/PWA#method-openCurrentPageInApp -// -// parameters: -// -// manifestID -func OpenCurrentPageInApp(manifestID string) *OpenCurrentPageInAppParams { - return &OpenCurrentPageInAppParams{ - ManifestID: manifestID, - } -} - -// Do executes PWA.openCurrentPageInApp against the provided context. -func (p *OpenCurrentPageInAppParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandOpenCurrentPageInApp, p, nil) -} +var OpenCurrentPageInApp = cdp.Command[OpenCurrentPageInAppParams, cdp.Empty]{Method: CommandOpenCurrentPageInApp} -// ChangeAppUserSettingsParams changes user settings of the web app -// identified by its manifestId. If the app was not installed, this command -// returns an error. Unset parameters will be ignored; unrecognized values will -// cause an error. Unlike the ones defined in the manifest files of the web -// apps, these settings are provided by the browser and controlled by the users, -// they impact the way the browser handling the web apps. See the comment of -// each parameter. +// ChangeAppUserSettingsParams are the parameters of the command +// PWA.changeAppUserSettings. type ChangeAppUserSettingsParams struct { ManifestID string `json:"manifestId"` - LinkCapturing bool `json:"linkCapturing"` // If user allows the links clicked on by the user in the app's scope, or extended scope if the manifest has scope extensions and the flags DesktopPWAsLinkCapturingWithScopeExtensions and WebAppEnableScopeExtensions are enabled. Note, the API does not support resetting the linkCapturing to the initial value, uninstalling and installing the web app again will reset it. TODO(crbug.com/339453269): Setting this value on ChromeOS is not supported yet. + LinkCapturing *bool `json:"linkCapturing,omitempty,omitzero"` // If user allows the links clicked on by the user in the app's scope, or extended scope if the manifest has scope extensions and the flags DesktopPWAsLinkCapturingWithScopeExtensions and WebAppEnableScopeExtensions are enabled. Note, the API does not support resetting the linkCapturing to the initial value, uninstalling and installing the web app again will reset it. TODO(crbug.com/339453269): Setting this value on ChromeOS is not supported yet. DisplayMode DisplayMode `json:"displayMode,omitempty,omitzero"` } @@ -305,39 +141,7 @@ type ChangeAppUserSettingsParams struct { // the browser handling the web apps. See the comment of each parameter. // // See: https://chromedevtools.github.io/devtools-protocol/tot/PWA#method-changeAppUserSettings -// -// parameters: -// -// manifestID -func ChangeAppUserSettings(manifestID string) *ChangeAppUserSettingsParams { - return &ChangeAppUserSettingsParams{ - ManifestID: manifestID, - LinkCapturing: false, - } -} - -// WithLinkCapturing if user allows the links clicked on by the user in the -// app's scope, or extended scope if the manifest has scope extensions and the -// flags DesktopPWAsLinkCapturingWithScopeExtensions and -// WebAppEnableScopeExtensions are enabled. Note, the API does not support -// resetting the linkCapturing to the initial value, uninstalling and installing -// the web app again will reset it. TODO(crbug.com/339453269): Setting this -// value on ChromeOS is not supported yet. -func (p ChangeAppUserSettingsParams) WithLinkCapturing(linkCapturing bool) *ChangeAppUserSettingsParams { - p.LinkCapturing = linkCapturing - return &p -} - -// WithDisplayMode [no description]. -func (p ChangeAppUserSettingsParams) WithDisplayMode(displayMode DisplayMode) *ChangeAppUserSettingsParams { - p.DisplayMode = displayMode - return &p -} - -// Do executes PWA.changeAppUserSettings against the provided context. -func (p *ChangeAppUserSettingsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandChangeAppUserSettings, p, nil) -} +var ChangeAppUserSettings = cdp.Command[ChangeAppUserSettingsParams, cdp.Empty]{Method: CommandChangeAppUserSettings} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/pwa/types.go b/vendor/github.com/chromedp/cdproto/pwa/types.go index dc60d13ab..d734493a3 100644 --- a/vendor/github.com/chromedp/cdproto/pwa/types.go +++ b/vendor/github.com/chromedp/cdproto/pwa/types.go @@ -1,11 +1,6 @@ -package pwa - -import ( - "fmt" - "strings" -) +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package pwa // FileHandlerAccept the following types are the replica of // https://crsrc.org/c/chrome/browser/web_applications/proto/web_app_os_integration_state.proto;drc=9910d3be894c8f142c977ba1023f30a656bc13fc;l=67. @@ -40,19 +35,3 @@ const ( DisplayModeStandalone DisplayMode = "standalone" DisplayModeBrowser DisplayMode = "browser" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DisplayMode) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DisplayMode(s) { - case DisplayModeStandalone: - *t = DisplayModeStandalone - case DisplayModeBrowser: - *t = DisplayModeBrowser - default: - return fmt.Errorf("unknown DisplayMode value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/runtime/events.go b/vendor/github.com/chromedp/cdproto/runtime/events.go index 5136279c4..8ae894b8a 100644 --- a/vendor/github.com/chromedp/cdproto/runtime/events.go +++ b/vendor/github.com/chromedp/cdproto/runtime/events.go @@ -1,9 +1,9 @@ -package runtime +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package runtime import ( - "github.com/go-json-experiment/json/jsontext" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" ) // EventBindingCalled notification is issued every time when binding is @@ -20,12 +20,12 @@ type EventBindingCalled struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-consoleAPICalled type EventConsoleAPICalled struct { - Type APIType `json:"type"` // Type of the call. - Args []*RemoteObject `json:"args"` // Call arguments. - ExecutionContextID ExecutionContextID `json:"executionContextId"` // Identifier of the context where the call was made. - Timestamp *Timestamp `json:"timestamp"` // Call timestamp. - StackTrace *StackTrace `json:"stackTrace,omitempty,omitzero"` // Stack trace captured when the call was made. The async stack chain is automatically reported for the following call types: assert, error, trace, warning. For other types the async call chain can be retrieved using Debugger.getStackTrace and stackTrace.parentId field. - Context string `json:"context,omitempty,omitzero"` // 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. + Type ConsoleAPICalledType `json:"type"` // Type of the call. + Args []*RemoteObject `json:"args"` // Call arguments. + ExecutionContextID ExecutionContextID `json:"executionContextId"` // Identifier of the context where the call was made. + Timestamp Timestamp `json:"timestamp"` // Call timestamp. + StackTrace *StackTrace `json:"stackTrace,omitempty,omitzero"` // Stack trace captured when the call was made. The async stack chain is automatically reported for the following call types: assert, error, trace, warning. For other types the async call chain can be retrieved using Debugger.getStackTrace and stackTrace.parentId field. + Context string `json:"context,omitempty,omitzero"` // 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. } // EventExceptionRevoked issued when unhandled exception was revoked. @@ -40,7 +40,7 @@ type EventExceptionRevoked struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-exceptionThrown type EventExceptionThrown struct { - Timestamp *Timestamp `json:"timestamp"` // Timestamp of the exception. + Timestamp Timestamp `json:"timestamp"` // Timestamp of the exception. ExceptionDetails *ExceptionDetails `json:"exceptionDetails"` } @@ -55,8 +55,7 @@ type EventExecutionContextCreated struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-executionContextDestroyed type EventExecutionContextDestroyed struct { - ExecutionContextID ExecutionContextID `json:"executionContextId"` // Id of the destroyed context - ExecutionContextUniqueID string `json:"executionContextUniqueId"` // Unique Id of the destroyed context + ExecutionContextUniqueID string `json:"executionContextUniqueId"` // Unique Id of the destroyed context } // EventExecutionContextsCleared issued when all executionContexts were @@ -71,6 +70,6 @@ type EventExecutionContextsCleared struct{} // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-inspectRequested type EventInspectRequested struct { Object *RemoteObject `json:"object"` - Hints jsontext.Value `json:"hints"` + Hints jsonv2.Value `json:"hints"` ExecutionContextID ExecutionContextID `json:"executionContextId,omitempty,omitzero"` // Identifier of the context where the call was made. } diff --git a/vendor/github.com/chromedp/cdproto/runtime/runtime.go b/vendor/github.com/chromedp/cdproto/runtime/runtime.go index 20c482ea7..5939a5f23 100644 --- a/vendor/github.com/chromedp/cdproto/runtime/runtime.go +++ b/vendor/github.com/chromedp/cdproto/runtime/runtime.go @@ -1,3 +1,5 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package runtime provides the Chrome DevTools Protocol // commands, types, and events for the Runtime domain. // @@ -8,226 +10,63 @@ // unless they are either explicitly released or are released along with the // other objects in their object group. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package runtime -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// AwaitPromiseParams add handler to promise with given promise object id. +// AwaitPromiseParams are the parameters of the command Runtime.awaitPromise. type AwaitPromiseParams struct { - PromiseObjectID RemoteObjectID `json:"promiseObjectId"` // Identifier of the promise. - ReturnByValue bool `json:"returnByValue"` // Whether the result is expected to be a JSON object that should be sent by value. - GeneratePreview bool `json:"generatePreview"` // Whether preview should be generated for the result. -} - -// AwaitPromise add handler to promise with given promise object id. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-awaitPromise -// -// parameters: -// -// promiseObjectID - Identifier of the promise. -func AwaitPromise(promiseObjectID RemoteObjectID) *AwaitPromiseParams { - return &AwaitPromiseParams{ - PromiseObjectID: promiseObjectID, - ReturnByValue: false, - GeneratePreview: false, - } -} - -// WithReturnByValue whether the result is expected to be a JSON object that -// should be sent by value. -func (p AwaitPromiseParams) WithReturnByValue(returnByValue bool) *AwaitPromiseParams { - p.ReturnByValue = returnByValue - return &p -} - -// WithGeneratePreview whether preview should be generated for the result. -func (p AwaitPromiseParams) WithGeneratePreview(generatePreview bool) *AwaitPromiseParams { - p.GeneratePreview = generatePreview - return &p + PromiseObjectID RemoteObjectID `json:"promiseObjectId"` // Identifier of the promise. + ReturnByValue *bool `json:"returnByValue,omitempty,omitzero"` // Whether the result is expected to be a JSON object that should be sent by value. + GeneratePreview *bool `json:"generatePreview,omitempty,omitzero"` // Whether preview should be generated for the result. } -// AwaitPromiseReturns return values. -type AwaitPromiseReturns struct { +// AwaitPromiseResult is the result of the command Runtime.awaitPromise. +type AwaitPromiseResult struct { Result *RemoteObject `json:"result,omitempty,omitzero"` // Promise result. Will contain rejected value if promise was rejected. ExceptionDetails *ExceptionDetails `json:"exceptionDetails,omitempty,omitzero"` // Exception details if stack strace is available. } -// Do executes Runtime.awaitPromise against the provided context. -// -// returns: +// AwaitPromise add handler to promise with given promise object id. // -// result - Promise result. Will contain rejected value if promise was rejected. -// exceptionDetails - Exception details if stack strace is available. -func (p *AwaitPromiseParams) Do(ctx context.Context) (result *RemoteObject, exceptionDetails *ExceptionDetails, err error) { - // execute - var res AwaitPromiseReturns - err = cdp.Execute(ctx, CommandAwaitPromise, p, &res) - if err != nil { - return nil, nil, err - } - - return res.Result, res.ExceptionDetails, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-awaitPromise +var AwaitPromise = cdp.Command[AwaitPromiseParams, AwaitPromiseResult]{Method: CommandAwaitPromise} -// CallFunctionOnParams calls function with given declaration on the given -// object. Object group of the result is inherited from the target object. +// CallFunctionOnParams are the parameters of the command +// Runtime.callFunctionOn. type CallFunctionOnParams struct { FunctionDeclaration string `json:"functionDeclaration"` // Declaration of the function to call. ObjectID RemoteObjectID `json:"objectId,omitempty,omitzero"` // Identifier of the object to call function on. Either objectId or executionContextId should be specified. Arguments []*CallArgument `json:"arguments,omitempty,omitzero"` // Call arguments. All call arguments must belong to the same JavaScript world as the target object. - Silent bool `json:"silent"` // In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. - ReturnByValue bool `json:"returnByValue"` // Whether the result is expected to be a JSON object which should be sent by value. Can be overridden by serializationOptions. - GeneratePreview bool `json:"generatePreview"` // Whether preview should be generated for the result. - UserGesture bool `json:"userGesture"` // Whether execution should be treated as initiated by user in the UI. - AwaitPromise bool `json:"awaitPromise"` // Whether execution should await for resulting value and return once awaited promise is resolved. + Silent *bool `json:"silent,omitempty,omitzero"` // In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + ReturnByValue *bool `json:"returnByValue,omitempty,omitzero"` // Whether the result is expected to be a JSON object which should be sent by value. Can be overridden by serializationOptions. + GeneratePreview *bool `json:"generatePreview,omitempty,omitzero"` // Whether preview should be generated for the result. + UserGesture *bool `json:"userGesture,omitempty,omitzero"` // Whether execution should be treated as initiated by user in the UI. + AwaitPromise *bool `json:"awaitPromise,omitempty,omitzero"` // Whether execution should await for resulting value and return once awaited promise is resolved. ExecutionContextID ExecutionContextID `json:"executionContextId,omitempty,omitzero"` // Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. ObjectGroup string `json:"objectGroup,omitempty,omitzero"` // 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. - ThrowOnSideEffect bool `json:"throwOnSideEffect"` // Whether to throw an exception if side effect cannot be ruled out during evaluation. + ThrowOnSideEffect *bool `json:"throwOnSideEffect,omitempty,omitzero"` // Whether to throw an exception if side effect cannot be ruled out during evaluation. UniqueContextID string `json:"uniqueContextId,omitempty,omitzero"` // An alternative way to specify the execution context to call function on. Compared to contextId that may be reused across processes, this is guaranteed to be system-unique, so it can be used to prevent accidental function call in context different than intended (e.g. as a result of navigation across process boundaries). This is mutually exclusive with executionContextId. SerializationOptions *SerializationOptions `json:"serializationOptions,omitempty,omitzero"` // Specifies the result serialization. If provided, overrides generatePreview and returnByValue. } -// CallFunctionOn calls function with given declaration on the given object. -// Object group of the result is inherited from the target object. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-callFunctionOn -// -// parameters: -// -// functionDeclaration - Declaration of the function to call. -func CallFunctionOn(functionDeclaration string) *CallFunctionOnParams { - return &CallFunctionOnParams{ - FunctionDeclaration: functionDeclaration, - Silent: false, - ReturnByValue: false, - GeneratePreview: false, - UserGesture: false, - AwaitPromise: false, - ThrowOnSideEffect: false, - } -} - -// WithObjectID identifier of the object to call function on. Either objectId -// or executionContextId should be specified. -func (p CallFunctionOnParams) WithObjectID(objectID RemoteObjectID) *CallFunctionOnParams { - p.ObjectID = objectID - return &p -} - -// WithArguments call arguments. All call arguments must belong to the same -// JavaScript world as the target object. -func (p CallFunctionOnParams) WithArguments(arguments []*CallArgument) *CallFunctionOnParams { - p.Arguments = arguments - return &p -} - -// WithSilent in silent mode exceptions thrown during evaluation are not -// reported and do not pause execution. Overrides setPauseOnException state. -func (p CallFunctionOnParams) WithSilent(silent bool) *CallFunctionOnParams { - p.Silent = silent - return &p -} - -// WithReturnByValue whether the result is expected to be a JSON object which -// should be sent by value. Can be overridden by serializationOptions. -func (p CallFunctionOnParams) WithReturnByValue(returnByValue bool) *CallFunctionOnParams { - p.ReturnByValue = returnByValue - return &p -} - -// WithGeneratePreview whether preview should be generated for the result. -func (p CallFunctionOnParams) WithGeneratePreview(generatePreview bool) *CallFunctionOnParams { - p.GeneratePreview = generatePreview - return &p -} - -// WithUserGesture whether execution should be treated as initiated by user -// in the UI. -func (p CallFunctionOnParams) WithUserGesture(userGesture bool) *CallFunctionOnParams { - p.UserGesture = userGesture - return &p -} - -// WithAwaitPromise whether execution should await for resulting value and -// return once awaited promise is resolved. -func (p CallFunctionOnParams) WithAwaitPromise(awaitPromise bool) *CallFunctionOnParams { - p.AwaitPromise = awaitPromise - return &p -} - -// WithExecutionContextID specifies execution context which global object -// will be used to call function on. Either executionContextId or objectId -// should be specified. -func (p CallFunctionOnParams) WithExecutionContextID(executionContextID ExecutionContextID) *CallFunctionOnParams { - p.ExecutionContextID = executionContextID - return &p -} - -// WithObjectGroup 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. -func (p CallFunctionOnParams) WithObjectGroup(objectGroup string) *CallFunctionOnParams { - p.ObjectGroup = objectGroup - return &p -} - -// WithThrowOnSideEffect whether to throw an exception if side effect cannot -// be ruled out during evaluation. -func (p CallFunctionOnParams) WithThrowOnSideEffect(throwOnSideEffect bool) *CallFunctionOnParams { - p.ThrowOnSideEffect = throwOnSideEffect - return &p -} - -// WithUniqueContextID an alternative way to specify the execution context to -// call function on. Compared to contextId that may be reused across processes, -// this is guaranteed to be system-unique, so it can be used to prevent -// accidental function call in context different than intended (e.g. as a result -// of navigation across process boundaries). This is mutually exclusive with -// executionContextId. -func (p CallFunctionOnParams) WithUniqueContextID(uniqueContextID string) *CallFunctionOnParams { - p.UniqueContextID = uniqueContextID - return &p -} - -// WithSerializationOptions specifies the result serialization. If provided, -// overrides generatePreview and returnByValue. -func (p CallFunctionOnParams) WithSerializationOptions(serializationOptions *SerializationOptions) *CallFunctionOnParams { - p.SerializationOptions = serializationOptions - return &p -} - -// CallFunctionOnReturns return values. -type CallFunctionOnReturns struct { +// CallFunctionOnResult is the result of the command Runtime.callFunctionOn. +type CallFunctionOnResult struct { Result *RemoteObject `json:"result,omitempty,omitzero"` // Call result. ExceptionDetails *ExceptionDetails `json:"exceptionDetails,omitempty,omitzero"` // Exception details. } -// Do executes Runtime.callFunctionOn against the provided context. -// -// returns: +// CallFunctionOn calls function with given declaration on the given object. +// Object group of the result is inherited from the target object. // -// result - Call result. -// exceptionDetails - Exception details. -func (p *CallFunctionOnParams) Do(ctx context.Context) (result *RemoteObject, exceptionDetails *ExceptionDetails, err error) { - // execute - var res CallFunctionOnReturns - err = cdp.Execute(ctx, CommandCallFunctionOn, p, &res) - if err != nil { - return nil, nil, err - } - - return res.Result, res.ExceptionDetails, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-callFunctionOn +var CallFunctionOn = cdp.Command[CallFunctionOnParams, CallFunctionOnResult]{Method: CommandCallFunctionOn} -// CompileScriptParams compiles expression. +// CompileScriptParams are the parameters of the command +// Runtime.compileScript. type CompileScriptParams struct { Expression string `json:"expression"` // Expression to compile. SourceURL string `json:"sourceURL"` // Source url to be set for the script. @@ -235,526 +74,149 @@ type CompileScriptParams struct { ExecutionContextID ExecutionContextID `json:"executionContextId,omitempty,omitzero"` // 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. } -// CompileScript compiles expression. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-compileScript -// -// parameters: -// -// expression - Expression to compile. -// sourceURL - Source url to be set for the script. -// persistScript - Specifies whether the compiled script should be persisted. -func CompileScript(expression string, sourceURL string, persistScript bool) *CompileScriptParams { - return &CompileScriptParams{ - Expression: expression, - SourceURL: sourceURL, - PersistScript: persistScript, - } -} - -// WithExecutionContextID 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. -func (p CompileScriptParams) WithExecutionContextID(executionContextID ExecutionContextID) *CompileScriptParams { - p.ExecutionContextID = executionContextID - return &p -} - -// CompileScriptReturns return values. -type CompileScriptReturns struct { +// CompileScriptResult is the result of the command Runtime.compileScript. +type CompileScriptResult struct { ScriptID cdp.ScriptID `json:"scriptId,omitempty,omitzero"` // Id of the script. ExceptionDetails *ExceptionDetails `json:"exceptionDetails,omitempty,omitzero"` // Exception details. } -// Do executes Runtime.compileScript against the provided context. -// -// returns: +// CompileScript compiles expression. // -// scriptID - Id of the script. -// exceptionDetails - Exception details. -func (p *CompileScriptParams) Do(ctx context.Context) (scriptID cdp.ScriptID, exceptionDetails *ExceptionDetails, err error) { - // execute - var res CompileScriptReturns - err = cdp.Execute(ctx, CommandCompileScript, p, &res) - if err != nil { - return "", nil, err - } - - return res.ScriptID, res.ExceptionDetails, nil -} - -// DisableParams disables reporting of execution contexts creation. -type DisableParams struct{} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-compileScript +var CompileScript = cdp.Command[CompileScriptParams, CompileScriptResult]{Method: CommandCompileScript} // Disable disables reporting of execution contexts creation. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes Runtime.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// DiscardConsoleEntriesParams discards collected exceptions and console API -// calls. -type DiscardConsoleEntriesParams struct{} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} // DiscardConsoleEntries discards collected exceptions and console API calls. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-discardConsoleEntries -func DiscardConsoleEntries() *DiscardConsoleEntriesParams { - return &DiscardConsoleEntriesParams{} -} - -// Do executes Runtime.discardConsoleEntries against the provided context. -func (p *DiscardConsoleEntriesParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDiscardConsoleEntries, nil, nil) -} - -// EnableParams 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. -type EnableParams struct{} +var DiscardConsoleEntries = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDiscardConsoleEntries} // Enable 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. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} -// Do executes Runtime.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) -} - -// EvaluateParams evaluates expression on global object. +// EvaluateParams are the parameters of the command Runtime.evaluate. type EvaluateParams struct { - Expression string `json:"expression"` // Expression to evaluate. - ObjectGroup string `json:"objectGroup,omitempty,omitzero"` // Symbolic group name that can be used to release multiple objects. - IncludeCommandLineAPI bool `json:"includeCommandLineAPI"` // Determines whether Command Line API should be available during the evaluation. - Silent bool `json:"silent"` // In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. - ContextID ExecutionContextID `json:"contextId,omitempty,omitzero"` // 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. This is mutually exclusive with uniqueContextId, which offers an alternative way to identify the execution context that is more reliable in a multi-process environment. - ReturnByValue bool `json:"returnByValue"` // Whether the result is expected to be a JSON object that should be sent by value. - GeneratePreview bool `json:"generatePreview"` // Whether preview should be generated for the result. - UserGesture bool `json:"userGesture"` // Whether execution should be treated as initiated by user in the UI. - AwaitPromise bool `json:"awaitPromise"` // Whether execution should await for resulting value and return once awaited promise is resolved. - ThrowOnSideEffect bool `json:"throwOnSideEffect"` // Whether to throw an exception if side effect cannot be ruled out during evaluation. This implies disableBreaks below. - Timeout TimeDelta `json:"timeout,omitempty,omitzero"` // Terminate execution after timing out (number of milliseconds). - DisableBreaks bool `json:"disableBreaks"` // Disable breakpoints during execution. - ReplMode bool `json:"replMode"` // Setting this flag to true enables let re-declaration and top-level await. Note that let variables can only be re-declared if they originate from replMode themselves. - AllowUnsafeEvalBlockedByCSP bool `json:"allowUnsafeEvalBlockedByCSP"` // The Content Security Policy (CSP) for the target might block 'unsafe-eval' which includes eval(), Function(), setTimeout() and setInterval() when called with non-callable arguments. This flag bypasses CSP for this evaluation and allows unsafe-eval. Defaults to true. - UniqueContextID string `json:"uniqueContextId,omitempty,omitzero"` // An alternative way to specify the execution context to evaluate in. Compared to contextId that may be reused across processes, this is guaranteed to be system-unique, so it can be used to prevent accidental evaluation of the expression in context different than intended (e.g. as a result of navigation across process boundaries). This is mutually exclusive with contextId. - SerializationOptions *SerializationOptions `json:"serializationOptions,omitempty,omitzero"` // Specifies the result serialization. If provided, overrides generatePreview and returnByValue. -} - -// Evaluate evaluates expression on global object. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-evaluate -// -// parameters: -// -// expression - Expression to evaluate. -func Evaluate(expression string) *EvaluateParams { - return &EvaluateParams{ - Expression: expression, - IncludeCommandLineAPI: false, - Silent: false, - ReturnByValue: false, - GeneratePreview: false, - UserGesture: false, - AwaitPromise: false, - ThrowOnSideEffect: false, - DisableBreaks: false, - ReplMode: false, - AllowUnsafeEvalBlockedByCSP: true, - } -} - -// WithObjectGroup symbolic group name that can be used to release multiple -// objects. -func (p EvaluateParams) WithObjectGroup(objectGroup string) *EvaluateParams { - p.ObjectGroup = objectGroup - return &p -} - -// WithIncludeCommandLineAPI determines whether Command Line API should be -// available during the evaluation. -func (p EvaluateParams) WithIncludeCommandLineAPI(includeCommandLineAPI bool) *EvaluateParams { - p.IncludeCommandLineAPI = includeCommandLineAPI - return &p -} - -// WithSilent in silent mode exceptions thrown during evaluation are not -// reported and do not pause execution. Overrides setPauseOnException state. -func (p EvaluateParams) WithSilent(silent bool) *EvaluateParams { - p.Silent = silent - return &p -} - -// WithContextID 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. This is mutually exclusive with uniqueContextId, which -// offers an alternative way to identify the execution context that is more -// reliable in a multi-process environment. -func (p EvaluateParams) WithContextID(contextID ExecutionContextID) *EvaluateParams { - p.ContextID = contextID - return &p -} - -// WithReturnByValue whether the result is expected to be a JSON object that -// should be sent by value. -func (p EvaluateParams) WithReturnByValue(returnByValue bool) *EvaluateParams { - p.ReturnByValue = returnByValue - return &p -} - -// WithGeneratePreview whether preview should be generated for the result. -func (p EvaluateParams) WithGeneratePreview(generatePreview bool) *EvaluateParams { - p.GeneratePreview = generatePreview - return &p -} - -// WithUserGesture whether execution should be treated as initiated by user -// in the UI. -func (p EvaluateParams) WithUserGesture(userGesture bool) *EvaluateParams { - p.UserGesture = userGesture - return &p -} - -// WithAwaitPromise whether execution should await for resulting value and -// return once awaited promise is resolved. -func (p EvaluateParams) WithAwaitPromise(awaitPromise bool) *EvaluateParams { - p.AwaitPromise = awaitPromise - return &p -} - -// WithThrowOnSideEffect whether to throw an exception if side effect cannot -// be ruled out during evaluation. This implies disableBreaks below. -func (p EvaluateParams) WithThrowOnSideEffect(throwOnSideEffect bool) *EvaluateParams { - p.ThrowOnSideEffect = throwOnSideEffect - return &p -} - -// WithTimeout terminate execution after timing out (number of milliseconds). -func (p EvaluateParams) WithTimeout(timeout TimeDelta) *EvaluateParams { - p.Timeout = timeout - return &p -} - -// WithDisableBreaks disable breakpoints during execution. -func (p EvaluateParams) WithDisableBreaks(disableBreaks bool) *EvaluateParams { - p.DisableBreaks = disableBreaks - return &p -} - -// WithReplMode setting this flag to true enables let re-declaration and -// top-level await. Note that let variables can only be re-declared if they -// originate from replMode themselves. -func (p EvaluateParams) WithReplMode(replMode bool) *EvaluateParams { - p.ReplMode = replMode - return &p -} - -// WithAllowUnsafeEvalBlockedByCSP the Content Security Policy (CSP) for the -// target might block 'unsafe-eval' which includes eval(), Function(), -// setTimeout() and setInterval() when called with non-callable arguments. This -// flag bypasses CSP for this evaluation and allows unsafe-eval. Defaults to -// true. -func (p EvaluateParams) WithAllowUnsafeEvalBlockedByCSP(allowUnsafeEvalBlockedByCSP bool) *EvaluateParams { - p.AllowUnsafeEvalBlockedByCSP = allowUnsafeEvalBlockedByCSP - return &p -} - -// WithUniqueContextID an alternative way to specify the execution context to -// evaluate in. Compared to contextId that may be reused across processes, this -// is guaranteed to be system-unique, so it can be used to prevent accidental -// evaluation of the expression in context different than intended (e.g. as a -// result of navigation across process boundaries). This is mutually exclusive -// with contextId. -func (p EvaluateParams) WithUniqueContextID(uniqueContextID string) *EvaluateParams { - p.UniqueContextID = uniqueContextID - return &p -} - -// WithSerializationOptions specifies the result serialization. If provided, -// overrides generatePreview and returnByValue. -func (p EvaluateParams) WithSerializationOptions(serializationOptions *SerializationOptions) *EvaluateParams { - p.SerializationOptions = serializationOptions - return &p -} - -// EvaluateReturns return values. -type EvaluateReturns struct { + Expression string `json:"expression"` // Expression to evaluate. + ObjectGroup string `json:"objectGroup,omitempty,omitzero"` // Symbolic group name that can be used to release multiple objects. + IncludeCommandLineAPI *bool `json:"includeCommandLineAPI,omitempty,omitzero"` // Determines whether Command Line API should be available during the evaluation. + Silent *bool `json:"silent,omitempty,omitzero"` // In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + ContextID ExecutionContextID `json:"contextId,omitempty,omitzero"` // 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. This is mutually exclusive with uniqueContextId, which offers an alternative way to identify the execution context that is more reliable in a multi-process environment. + ReturnByValue *bool `json:"returnByValue,omitempty,omitzero"` // Whether the result is expected to be a JSON object that should be sent by value. + GeneratePreview *bool `json:"generatePreview,omitempty,omitzero"` // Whether preview should be generated for the result. + UserGesture *bool `json:"userGesture,omitempty,omitzero"` // Whether execution should be treated as initiated by user in the UI. + AwaitPromise *bool `json:"awaitPromise,omitempty,omitzero"` // Whether execution should await for resulting value and return once awaited promise is resolved. + ThrowOnSideEffect *bool `json:"throwOnSideEffect,omitempty,omitzero"` // Whether to throw an exception if side effect cannot be ruled out during evaluation. This implies disableBreaks below. + Timeout TimeDelta `json:"timeout,omitempty,omitzero"` // Terminate execution after timing out (number of milliseconds). + DisableBreaks *bool `json:"disableBreaks,omitempty,omitzero"` // Disable breakpoints during execution. + ReplMode *bool `json:"replMode,omitempty,omitzero"` // Setting this flag to true enables let re-declaration and top-level await. Note that let variables can only be re-declared if they originate from replMode themselves. + AllowUnsafeEvalBlockedByCSP *bool `json:"allowUnsafeEvalBlockedByCSP,omitempty,omitzero"` // The Content Security Policy (CSP) for the target might block 'unsafe-eval' which includes eval(), Function(), setTimeout() and setInterval() when called with non-callable arguments. This flag bypasses CSP for this evaluation and allows unsafe-eval. Defaults to true. + UniqueContextID string `json:"uniqueContextId,omitempty,omitzero"` // An alternative way to specify the execution context to evaluate in. Compared to contextId that may be reused across processes, this is guaranteed to be system-unique, so it can be used to prevent accidental evaluation of the expression in context different than intended (e.g. as a result of navigation across process boundaries). This is mutually exclusive with contextId. + SerializationOptions *SerializationOptions `json:"serializationOptions,omitempty,omitzero"` // Specifies the result serialization. If provided, overrides generatePreview and returnByValue. +} + +// EvaluateResult is the result of the command Runtime.evaluate. +type EvaluateResult struct { Result *RemoteObject `json:"result,omitempty,omitzero"` // Evaluation result. ExceptionDetails *ExceptionDetails `json:"exceptionDetails,omitempty,omitzero"` // Exception details. } -// Do executes Runtime.evaluate against the provided context. -// -// returns: +// Evaluate evaluates expression on global object. // -// result - Evaluation result. -// exceptionDetails - Exception details. -func (p *EvaluateParams) Do(ctx context.Context) (result *RemoteObject, exceptionDetails *ExceptionDetails, err error) { - // execute - var res EvaluateReturns - err = cdp.Execute(ctx, CommandEvaluate, p, &res) - if err != nil { - return nil, nil, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-evaluate +var Evaluate = cdp.Command[EvaluateParams, EvaluateResult]{Method: CommandEvaluate} - return res.Result, res.ExceptionDetails, nil +// GetIsolateIDResult is the result of the command Runtime.getIsolateId. +type GetIsolateIDResult struct { + ID string `json:"id,omitempty,omitzero"` // The isolate id. } -// GetIsolateIDParams returns the isolate id. -type GetIsolateIDParams struct{} - // GetIsolateID returns the isolate id. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getIsolateId -func GetIsolateID() *GetIsolateIDParams { - return &GetIsolateIDParams{} -} - -// GetIsolateIDReturns return values. -type GetIsolateIDReturns struct { - ID string `json:"id,omitempty,omitzero"` // The isolate id. -} - -// Do executes Runtime.getIsolateId against the provided context. -// -// returns: -// -// id - The isolate id. -func (p *GetIsolateIDParams) Do(ctx context.Context) (id string, err error) { - // execute - var res GetIsolateIDReturns - err = cdp.Execute(ctx, CommandGetIsolateID, nil, &res) - if err != nil { - return "", err - } - - return res.ID, nil -} - -// GetHeapUsageParams returns the JavaScript heap usage. It is the total -// usage of the corresponding isolate not scoped to a particular Runtime. -type GetHeapUsageParams struct{} - -// GetHeapUsage returns the JavaScript heap usage. It is the total usage of -// the corresponding isolate not scoped to a particular Runtime. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getHeapUsage -func GetHeapUsage() *GetHeapUsageParams { - return &GetHeapUsageParams{} -} +var GetIsolateID = cdp.Command[cdp.Empty, GetIsolateIDResult]{Method: CommandGetIsolateID} -// GetHeapUsageReturns return values. -type GetHeapUsageReturns struct { +// GetHeapUsageResult is the result of the command Runtime.getHeapUsage. +type GetHeapUsageResult struct { UsedSize float64 `json:"usedSize,omitempty,omitzero"` // Used JavaScript heap size in bytes. TotalSize float64 `json:"totalSize,omitempty,omitzero"` // Allocated JavaScript heap size in bytes. EmbedderHeapUsedSize float64 `json:"embedderHeapUsedSize,omitempty,omitzero"` // Used size in bytes in the embedder's garbage-collected heap. BackingStorageSize float64 `json:"backingStorageSize,omitempty,omitzero"` // Size in bytes of backing storage for array buffers and external strings. } -// Do executes Runtime.getHeapUsage against the provided context. -// -// returns: +// GetHeapUsage returns the JavaScript heap usage. It is the total usage of +// the corresponding isolate not scoped to a particular Runtime. // -// usedSize - Used JavaScript heap size in bytes. -// totalSize - Allocated JavaScript heap size in bytes. -// embedderHeapUsedSize - Used size in bytes in the embedder's garbage-collected heap. -// backingStorageSize - Size in bytes of backing storage for array buffers and external strings. -func (p *GetHeapUsageParams) Do(ctx context.Context) (usedSize float64, totalSize float64, embedderHeapUsedSize float64, backingStorageSize float64, err error) { - // execute - var res GetHeapUsageReturns - err = cdp.Execute(ctx, CommandGetHeapUsage, nil, &res) - if err != nil { - return 0, 0, 0, 0, err - } - - return res.UsedSize, res.TotalSize, res.EmbedderHeapUsedSize, res.BackingStorageSize, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getHeapUsage +var GetHeapUsage = cdp.Command[cdp.Empty, GetHeapUsageResult]{Method: CommandGetHeapUsage} -// GetPropertiesParams returns properties of a given object. Object group of -// the result is inherited from the target object. +// GetPropertiesParams are the parameters of the command +// Runtime.getProperties. type GetPropertiesParams struct { - ObjectID RemoteObjectID `json:"objectId"` // Identifier of the object to return properties for. - OwnProperties bool `json:"ownProperties"` // If true, returns properties belonging only to the element itself, not to its prototype chain. - AccessorPropertiesOnly bool `json:"accessorPropertiesOnly"` // If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. - GeneratePreview bool `json:"generatePreview"` // Whether preview should be generated for the results. - NonIndexedPropertiesOnly bool `json:"nonIndexedPropertiesOnly"` // If true, returns non-indexed properties only. -} - -// GetProperties returns properties of a given object. Object group of the -// result is inherited from the target object. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getProperties -// -// parameters: -// -// objectID - Identifier of the object to return properties for. -func GetProperties(objectID RemoteObjectID) *GetPropertiesParams { - return &GetPropertiesParams{ - ObjectID: objectID, - OwnProperties: false, - AccessorPropertiesOnly: false, - GeneratePreview: false, - NonIndexedPropertiesOnly: false, - } -} - -// WithOwnProperties if true, returns properties belonging only to the -// element itself, not to its prototype chain. -func (p GetPropertiesParams) WithOwnProperties(ownProperties bool) *GetPropertiesParams { - p.OwnProperties = ownProperties - return &p + ObjectID RemoteObjectID `json:"objectId"` // Identifier of the object to return properties for. + OwnProperties *bool `json:"ownProperties,omitempty,omitzero"` // If true, returns properties belonging only to the element itself, not to its prototype chain. + AccessorPropertiesOnly *bool `json:"accessorPropertiesOnly,omitempty,omitzero"` // If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + GeneratePreview *bool `json:"generatePreview,omitempty,omitzero"` // Whether preview should be generated for the results. + NonIndexedPropertiesOnly *bool `json:"nonIndexedPropertiesOnly,omitempty,omitzero"` // If true, returns non-indexed properties only. } -// WithAccessorPropertiesOnly if true, returns accessor properties (with -// getter/setter) only; internal properties are not returned either. -func (p GetPropertiesParams) WithAccessorPropertiesOnly(accessorPropertiesOnly bool) *GetPropertiesParams { - p.AccessorPropertiesOnly = accessorPropertiesOnly - return &p -} - -// WithGeneratePreview whether preview should be generated for the results. -func (p GetPropertiesParams) WithGeneratePreview(generatePreview bool) *GetPropertiesParams { - p.GeneratePreview = generatePreview - return &p -} - -// WithNonIndexedPropertiesOnly if true, returns non-indexed properties only. -func (p GetPropertiesParams) WithNonIndexedPropertiesOnly(nonIndexedPropertiesOnly bool) *GetPropertiesParams { - p.NonIndexedPropertiesOnly = nonIndexedPropertiesOnly - return &p -} - -// GetPropertiesReturns return values. -type GetPropertiesReturns struct { +// GetPropertiesResult is the result of the command Runtime.getProperties. +type GetPropertiesResult struct { Result []*PropertyDescriptor `json:"result,omitempty,omitzero"` // Object properties. InternalProperties []*InternalPropertyDescriptor `json:"internalProperties,omitempty,omitzero"` // Internal object properties (only of the element itself). PrivateProperties []*PrivatePropertyDescriptor `json:"privateProperties,omitempty,omitzero"` // Object private properties. ExceptionDetails *ExceptionDetails `json:"exceptionDetails,omitempty,omitzero"` // Exception details. } -// Do executes Runtime.getProperties against the provided context. -// -// returns: +// GetProperties returns properties of a given object. Object group of the +// result is inherited from the target object. // -// result - Object properties. -// internalProperties - Internal object properties (only of the element itself). -// privateProperties - Object private properties. -// exceptionDetails - Exception details. -func (p *GetPropertiesParams) Do(ctx context.Context) (result []*PropertyDescriptor, internalProperties []*InternalPropertyDescriptor, privateProperties []*PrivatePropertyDescriptor, exceptionDetails *ExceptionDetails, err error) { - // execute - var res GetPropertiesReturns - err = cdp.Execute(ctx, CommandGetProperties, p, &res) - if err != nil { - return nil, nil, nil, nil, err - } - - return res.Result, res.InternalProperties, res.PrivateProperties, res.ExceptionDetails, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getProperties +var GetProperties = cdp.Command[GetPropertiesParams, GetPropertiesResult]{Method: CommandGetProperties} -// GlobalLexicalScopeNamesParams returns all let, const and class variables -// from global scope. +// GlobalLexicalScopeNamesParams are the parameters of the command +// Runtime.globalLexicalScopeNames. type GlobalLexicalScopeNamesParams struct { ExecutionContextID ExecutionContextID `json:"executionContextId,omitempty,omitzero"` // Specifies in which execution context to lookup global scope variables. } -// GlobalLexicalScopeNames returns all let, const and class variables from -// global scope. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-globalLexicalScopeNames -// -// parameters: -func GlobalLexicalScopeNames() *GlobalLexicalScopeNamesParams { - return &GlobalLexicalScopeNamesParams{} -} - -// WithExecutionContextID specifies in which execution context to lookup -// global scope variables. -func (p GlobalLexicalScopeNamesParams) WithExecutionContextID(executionContextID ExecutionContextID) *GlobalLexicalScopeNamesParams { - p.ExecutionContextID = executionContextID - return &p -} - -// GlobalLexicalScopeNamesReturns return values. -type GlobalLexicalScopeNamesReturns struct { +// GlobalLexicalScopeNamesResult is the result of the command +// Runtime.globalLexicalScopeNames. +type GlobalLexicalScopeNamesResult struct { Names []string `json:"names,omitempty,omitzero"` } -// Do executes Runtime.globalLexicalScopeNames against the provided context. -// -// returns: +// GlobalLexicalScopeNames returns all let, const and class variables from +// global scope. // -// names -func (p *GlobalLexicalScopeNamesParams) Do(ctx context.Context) (names []string, err error) { - // execute - var res GlobalLexicalScopeNamesReturns - err = cdp.Execute(ctx, CommandGlobalLexicalScopeNames, p, &res) - if err != nil { - return nil, err - } - - return res.Names, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-globalLexicalScopeNames +var GlobalLexicalScopeNames = cdp.Command[GlobalLexicalScopeNamesParams, GlobalLexicalScopeNamesResult]{Method: CommandGlobalLexicalScopeNames} -// QueryObjectsParams [no description]. +// QueryObjectsParams are the parameters of the command Runtime.queryObjects. type QueryObjectsParams struct { PrototypeObjectID RemoteObjectID `json:"prototypeObjectId"` // Identifier of the prototype to return objects for. ObjectGroup string `json:"objectGroup,omitempty,omitzero"` // Symbolic group name that can be used to release the results. } -// QueryObjects [no description]. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-queryObjects -// -// parameters: -// -// prototypeObjectID - Identifier of the prototype to return objects for. -func QueryObjects(prototypeObjectID RemoteObjectID) *QueryObjectsParams { - return &QueryObjectsParams{ - PrototypeObjectID: prototypeObjectID, - } -} - -// WithObjectGroup symbolic group name that can be used to release the -// results. -func (p QueryObjectsParams) WithObjectGroup(objectGroup string) *QueryObjectsParams { - p.ObjectGroup = objectGroup - return &p -} - -// QueryObjectsReturns return values. -type QueryObjectsReturns struct { +// QueryObjectsResult is the result of the command Runtime.queryObjects. +type QueryObjectsResult struct { Objects *RemoteObject `json:"objects,omitempty,omitzero"` // Array with objects. } -// Do executes Runtime.queryObjects against the provided context. -// -// returns: +// QueryObjects [no description]. // -// objects - Array with objects. -func (p *QueryObjectsParams) Do(ctx context.Context) (objects *RemoteObject, err error) { - // execute - var res QueryObjectsReturns - err = cdp.Execute(ctx, CommandQueryObjects, p, &res) - if err != nil { - return nil, err - } - - return res.Objects, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-queryObjects +var QueryObjects = cdp.Command[QueryObjectsParams, QueryObjectsResult]{Method: CommandQueryObjects} -// ReleaseObjectParams releases remote object with given id. +// ReleaseObjectParams are the parameters of the command +// Runtime.releaseObject. type ReleaseObjectParams struct { ObjectID RemoteObjectID `json:"objectId"` // Identifier of the object to release. } @@ -762,23 +224,10 @@ type ReleaseObjectParams struct { // ReleaseObject releases remote object with given id. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-releaseObject -// -// parameters: -// -// objectID - Identifier of the object to release. -func ReleaseObject(objectID RemoteObjectID) *ReleaseObjectParams { - return &ReleaseObjectParams{ - ObjectID: objectID, - } -} - -// Do executes Runtime.releaseObject against the provided context. -func (p *ReleaseObjectParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandReleaseObject, p, nil) -} +var ReleaseObject = cdp.Command[ReleaseObjectParams, cdp.Empty]{Method: CommandReleaseObject} -// ReleaseObjectGroupParams releases all remote objects that belong to a -// given group. +// ReleaseObjectGroupParams are the parameters of the command +// Runtime.releaseObjectGroup. type ReleaseObjectGroupParams struct { ObjectGroup string `json:"objectGroup"` // Symbolic object group name. } @@ -787,141 +236,39 @@ type ReleaseObjectGroupParams struct { // group. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-releaseObjectGroup -// -// parameters: -// -// objectGroup - Symbolic object group name. -func ReleaseObjectGroup(objectGroup string) *ReleaseObjectGroupParams { - return &ReleaseObjectGroupParams{ - ObjectGroup: objectGroup, - } -} - -// Do executes Runtime.releaseObjectGroup against the provided context. -func (p *ReleaseObjectGroupParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandReleaseObjectGroup, p, nil) -} - -// RunIfWaitingForDebuggerParams tells inspected instance to run if it was -// waiting for debugger to attach. -type RunIfWaitingForDebuggerParams struct{} +var ReleaseObjectGroup = cdp.Command[ReleaseObjectGroupParams, cdp.Empty]{Method: CommandReleaseObjectGroup} // RunIfWaitingForDebugger tells inspected instance to run if it was waiting // for debugger to attach. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-runIfWaitingForDebugger -func RunIfWaitingForDebugger() *RunIfWaitingForDebuggerParams { - return &RunIfWaitingForDebuggerParams{} -} +var RunIfWaitingForDebugger = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandRunIfWaitingForDebugger} -// Do executes Runtime.runIfWaitingForDebugger against the provided context. -func (p *RunIfWaitingForDebuggerParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRunIfWaitingForDebugger, nil, nil) -} - -// RunScriptParams runs script with given id in a given context. +// RunScriptParams are the parameters of the command Runtime.runScript. type RunScriptParams struct { - ScriptID cdp.ScriptID `json:"scriptId"` // Id of the script to run. - ExecutionContextID ExecutionContextID `json:"executionContextId,omitempty,omitzero"` // 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. - ObjectGroup string `json:"objectGroup,omitempty,omitzero"` // Symbolic group name that can be used to release multiple objects. - Silent bool `json:"silent"` // In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. - IncludeCommandLineAPI bool `json:"includeCommandLineAPI"` // Determines whether Command Line API should be available during the evaluation. - ReturnByValue bool `json:"returnByValue"` // Whether the result is expected to be a JSON object which should be sent by value. - GeneratePreview bool `json:"generatePreview"` // Whether preview should be generated for the result. - AwaitPromise bool `json:"awaitPromise"` // Whether execution should await for resulting value and return once awaited promise is resolved. -} - -// RunScript runs script with given id in a given context. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-runScript -// -// parameters: -// -// scriptID - Id of the script to run. -func RunScript(scriptID cdp.ScriptID) *RunScriptParams { - return &RunScriptParams{ - ScriptID: scriptID, - Silent: false, - IncludeCommandLineAPI: false, - ReturnByValue: false, - GeneratePreview: false, - AwaitPromise: false, - } -} - -// WithExecutionContextID 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. -func (p RunScriptParams) WithExecutionContextID(executionContextID ExecutionContextID) *RunScriptParams { - p.ExecutionContextID = executionContextID - return &p -} - -// WithObjectGroup symbolic group name that can be used to release multiple -// objects. -func (p RunScriptParams) WithObjectGroup(objectGroup string) *RunScriptParams { - p.ObjectGroup = objectGroup - return &p -} - -// WithSilent in silent mode exceptions thrown during evaluation are not -// reported and do not pause execution. Overrides setPauseOnException state. -func (p RunScriptParams) WithSilent(silent bool) *RunScriptParams { - p.Silent = silent - return &p -} - -// WithIncludeCommandLineAPI determines whether Command Line API should be -// available during the evaluation. -func (p RunScriptParams) WithIncludeCommandLineAPI(includeCommandLineAPI bool) *RunScriptParams { - p.IncludeCommandLineAPI = includeCommandLineAPI - return &p -} - -// WithReturnByValue whether the result is expected to be a JSON object which -// should be sent by value. -func (p RunScriptParams) WithReturnByValue(returnByValue bool) *RunScriptParams { - p.ReturnByValue = returnByValue - return &p -} - -// WithGeneratePreview whether preview should be generated for the result. -func (p RunScriptParams) WithGeneratePreview(generatePreview bool) *RunScriptParams { - p.GeneratePreview = generatePreview - return &p -} - -// WithAwaitPromise whether execution should await for resulting value and -// return once awaited promise is resolved. -func (p RunScriptParams) WithAwaitPromise(awaitPromise bool) *RunScriptParams { - p.AwaitPromise = awaitPromise - return &p -} - -// RunScriptReturns return values. -type RunScriptReturns struct { + ScriptID cdp.ScriptID `json:"scriptId"` // Id of the script to run. + ExecutionContextID ExecutionContextID `json:"executionContextId,omitempty,omitzero"` // 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. + ObjectGroup string `json:"objectGroup,omitempty,omitzero"` // Symbolic group name that can be used to release multiple objects. + Silent *bool `json:"silent,omitempty,omitzero"` // In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + IncludeCommandLineAPI *bool `json:"includeCommandLineAPI,omitempty,omitzero"` // Determines whether Command Line API should be available during the evaluation. + ReturnByValue *bool `json:"returnByValue,omitempty,omitzero"` // Whether the result is expected to be a JSON object which should be sent by value. + GeneratePreview *bool `json:"generatePreview,omitempty,omitzero"` // Whether preview should be generated for the result. + AwaitPromise *bool `json:"awaitPromise,omitempty,omitzero"` // Whether execution should await for resulting value and return once awaited promise is resolved. +} + +// RunScriptResult is the result of the command Runtime.runScript. +type RunScriptResult struct { Result *RemoteObject `json:"result,omitempty,omitzero"` // Run result. ExceptionDetails *ExceptionDetails `json:"exceptionDetails,omitempty,omitzero"` // Exception details. } -// Do executes Runtime.runScript against the provided context. -// -// returns: +// RunScript runs script with given id in a given context. // -// result - Run result. -// exceptionDetails - Exception details. -func (p *RunScriptParams) Do(ctx context.Context) (result *RemoteObject, exceptionDetails *ExceptionDetails, err error) { - // execute - var res RunScriptReturns - err = cdp.Execute(ctx, CommandRunScript, p, &res) - if err != nil { - return nil, nil, err - } - - return res.Result, res.ExceptionDetails, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-runScript +var RunScript = cdp.Command[RunScriptParams, RunScriptResult]{Method: CommandRunScript} -// SetCustomObjectFormatterEnabledParams [no description]. +// SetCustomObjectFormatterEnabledParams are the parameters of the command +// Runtime.setCustomObjectFormatterEnabled. type SetCustomObjectFormatterEnabledParams struct { Enabled bool `json:"enabled"` } @@ -929,22 +276,10 @@ type SetCustomObjectFormatterEnabledParams struct { // SetCustomObjectFormatterEnabled [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-setCustomObjectFormatterEnabled -// -// parameters: -// -// enabled -func SetCustomObjectFormatterEnabled(enabled bool) *SetCustomObjectFormatterEnabledParams { - return &SetCustomObjectFormatterEnabledParams{ - Enabled: enabled, - } -} +var SetCustomObjectFormatterEnabled = cdp.Command[SetCustomObjectFormatterEnabledParams, cdp.Empty]{Method: CommandSetCustomObjectFormatterEnabled} -// Do executes Runtime.setCustomObjectFormatterEnabled against the provided context. -func (p *SetCustomObjectFormatterEnabledParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetCustomObjectFormatterEnabled, p, nil) -} - -// SetMaxCallStackSizeToCaptureParams [no description]. +// SetMaxCallStackSizeToCaptureParams are the parameters of the command +// Runtime.setMaxCallStackSizeToCapture. type SetMaxCallStackSizeToCaptureParams struct { Size int64 `json:"size"` } @@ -952,44 +287,15 @@ type SetMaxCallStackSizeToCaptureParams struct { // SetMaxCallStackSizeToCapture [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-setMaxCallStackSizeToCapture -// -// parameters: -// -// size -func SetMaxCallStackSizeToCapture(size int64) *SetMaxCallStackSizeToCaptureParams { - return &SetMaxCallStackSizeToCaptureParams{ - Size: size, - } -} - -// Do executes Runtime.setMaxCallStackSizeToCapture against the provided context. -func (p *SetMaxCallStackSizeToCaptureParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetMaxCallStackSizeToCapture, p, nil) -} - -// TerminateExecutionParams terminate current or next JavaScript execution. -// Will cancel the termination when the outer-most script execution ends. -type TerminateExecutionParams struct{} +var SetMaxCallStackSizeToCapture = cdp.Command[SetMaxCallStackSizeToCaptureParams, cdp.Empty]{Method: CommandSetMaxCallStackSizeToCapture} // TerminateExecution terminate current or next JavaScript execution. Will // cancel the termination when the outer-most script execution ends. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-terminateExecution -func TerminateExecution() *TerminateExecutionParams { - return &TerminateExecutionParams{} -} +var TerminateExecution = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandTerminateExecution} -// Do executes Runtime.terminateExecution against the provided context. -func (p *TerminateExecutionParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandTerminateExecution, nil, nil) -} - -// AddBindingParams if executionContextId is empty, adds binding with the -// given name on the global objects of all inspected contexts, including those -// created later, bindings survive reloads. Binding function takes exactly one -// argument, this argument should be string, in case of any other input, -// function throws an exception. Each binding function call produces -// Runtime.bindingCalled notification. +// AddBindingParams are the parameters of the command Runtime.addBinding. type AddBindingParams struct { Name string `json:"name"` ExecutionContextName string `json:"executionContextName,omitempty,omitzero"` // If specified, the binding is exposed to the executionContext with matching name, even for contexts created after the binding is added. See also ExecutionContext.name and worldName parameter to Page.addScriptToEvaluateOnNewDocument. This parameter is mutually exclusive with executionContextId. @@ -1003,34 +309,10 @@ type AddBindingParams struct { // notification. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-addBinding -// -// parameters: -// -// name -func AddBinding(name string) *AddBindingParams { - return &AddBindingParams{ - Name: name, - } -} - -// WithExecutionContextName if specified, the binding is exposed to the -// executionContext with matching name, even for contexts created after the -// binding is added. See also ExecutionContext.name and worldName parameter to -// Page.addScriptToEvaluateOnNewDocument. This parameter is mutually exclusive -// with executionContextId. -func (p AddBindingParams) WithExecutionContextName(executionContextName string) *AddBindingParams { - p.ExecutionContextName = executionContextName - return &p -} - -// Do executes Runtime.addBinding against the provided context. -func (p *AddBindingParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandAddBinding, p, nil) -} +var AddBinding = cdp.Command[AddBindingParams, cdp.Empty]{Method: CommandAddBinding} -// RemoveBindingParams this method does not remove binding function from -// global object but unsubscribes current runtime agent from -// Runtime.bindingCalled notifications. +// RemoveBindingParams are the parameters of the command +// Runtime.removeBinding. type RemoveBindingParams struct { Name string `json:"name"` } @@ -1040,65 +322,69 @@ type RemoveBindingParams struct { // notifications. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-removeBinding -// -// parameters: -// -// name -func RemoveBinding(name string) *RemoveBindingParams { - return &RemoveBindingParams{ - Name: name, - } -} +var RemoveBinding = cdp.Command[RemoveBindingParams, cdp.Empty]{Method: CommandRemoveBinding} -// Do executes Runtime.removeBinding against the provided context. -func (p *RemoveBindingParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRemoveBinding, p, nil) -} - -// GetExceptionDetailsParams this method tries to lookup and populate -// exception details for a JavaScript Error object. Note that the stackTrace -// portion of the resulting exceptionDetails will only be populated if the -// Runtime domain was enabled at the time when the Error was thrown. +// GetExceptionDetailsParams are the parameters of the command +// Runtime.getExceptionDetails. type GetExceptionDetailsParams struct { ErrorObjectID RemoteObjectID `json:"errorObjectId"` // The error object for which to resolve the exception details. } +// GetExceptionDetailsResult is the result of the command +// Runtime.getExceptionDetails. +type GetExceptionDetailsResult struct { + ExceptionDetails *ExceptionDetails `json:"exceptionDetails,omitempty,omitzero"` +} + // GetExceptionDetails this method tries to lookup and populate exception // details for a JavaScript Error object. Note that the stackTrace portion of // the resulting exceptionDetails will only be populated if the Runtime domain // was enabled at the time when the Error was thrown. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getExceptionDetails +var GetExceptionDetails = cdp.Command[GetExceptionDetailsParams, GetExceptionDetailsResult]{Method: CommandGetExceptionDetails} + +// BindingCalled notification is issued every time when binding is called. // -// parameters: +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-bindingCalled +var BindingCalled = cdp.Event[EventBindingCalled]{Method: "Runtime.bindingCalled"} + +// ConsoleAPICalled issued when console API was called. // -// errorObjectID - The error object for which to resolve the exception details. -func GetExceptionDetails(errorObjectID RemoteObjectID) *GetExceptionDetailsParams { - return &GetExceptionDetailsParams{ - ErrorObjectID: errorObjectID, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-consoleAPICalled +var ConsoleAPICalled = cdp.Event[EventConsoleAPICalled]{Method: "Runtime.consoleAPICalled"} -// GetExceptionDetailsReturns return values. -type GetExceptionDetailsReturns struct { - ExceptionDetails *ExceptionDetails `json:"exceptionDetails,omitempty,omitzero"` -} +// ExceptionRevoked issued when unhandled exception was revoked. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-exceptionRevoked +var ExceptionRevoked = cdp.Event[EventExceptionRevoked]{Method: "Runtime.exceptionRevoked"} -// Do executes Runtime.getExceptionDetails against the provided context. +// ExceptionThrown issued when exception was thrown and unhandled. // -// returns: +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-exceptionThrown +var ExceptionThrown = cdp.Event[EventExceptionThrown]{Method: "Runtime.exceptionThrown"} + +// ExecutionContextCreated issued when new execution context is created. // -// exceptionDetails -func (p *GetExceptionDetailsParams) Do(ctx context.Context) (exceptionDetails *ExceptionDetails, err error) { - // execute - var res GetExceptionDetailsReturns - err = cdp.Execute(ctx, CommandGetExceptionDetails, p, &res) - if err != nil { - return nil, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-executionContextCreated +var ExecutionContextCreated = cdp.Event[EventExecutionContextCreated]{Method: "Runtime.executionContextCreated"} - return res.ExceptionDetails, nil -} +// ExecutionContextDestroyed issued when execution context is destroyed. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-executionContextDestroyed +var ExecutionContextDestroyed = cdp.Event[EventExecutionContextDestroyed]{Method: "Runtime.executionContextDestroyed"} + +// ExecutionContextsCleared issued when all executionContexts were cleared in +// browser. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-executionContextsCleared +var ExecutionContextsCleared = cdp.Event[EventExecutionContextsCleared]{Method: "Runtime.executionContextsCleared"} + +// InspectRequested issued when object should be inspected (for example, as a +// result of inspect() command line API call). +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-inspectRequested +var InspectRequested = cdp.Event[EventInspectRequested]{Method: "Runtime.inspectRequested"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/runtime/types.go b/vendor/github.com/chromedp/cdproto/runtime/types.go index a3a1b0c1c..e908883b1 100644 --- a/vendor/github.com/chromedp/cdproto/runtime/types.go +++ b/vendor/github.com/chromedp/cdproto/runtime/types.go @@ -1,15 +1,10 @@ -package runtime +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package runtime import ( - "fmt" - "strconv" - "strings" - "time" - "github.com/chromedp/cdproto/cdp" - "github.com/go-json-experiment/json/jsontext" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" ) // SerializationOptions represents options for serialization. Overrides @@ -18,8 +13,8 @@ import ( // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#type-SerializationOptions type SerializationOptions struct { Serialization SerializationOptionsSerialization `json:"serialization"` - MaxDepth int64 `json:"maxDepth,omitempty,omitzero"` // Deep serialization depth. Default is full depth. Respected only in deep serialization mode. - AdditionalParameters jsontext.Value `json:"additionalParameters,omitempty,omitzero"` + MaxDepth *int64 `json:"maxDepth,omitempty,omitzero"` // Deep serialization depth. Default is full depth. Respected only in deep serialization mode. + AdditionalParameters jsonv2.Value `json:"additionalParameters,omitempty,omitzero"` } // DeepSerializedValue represents deep serialized value. @@ -27,7 +22,7 @@ type SerializationOptions struct { // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#type-DeepSerializedValue type DeepSerializedValue struct { Type DeepSerializedValueType `json:"type"` - Value jsontext.Value `json:"value,omitempty,omitzero"` + Value jsonv2.Value `json:"value,omitempty,omitzero"` ObjectID string `json:"objectId,omitempty,omitzero"` WeakLocalObjectReference int64 `json:"weakLocalObjectReference,omitempty,omitzero"` // Set if value reference met more then once during serialization. In such case, value is provided only to one of the serialized values. Unique per value in the scope of one CDP call. } @@ -57,10 +52,10 @@ func (t UnserializableValue) String() string { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#type-RemoteObject type RemoteObject struct { - Type Type `json:"type"` // Object type. - Subtype Subtype `json:"subtype,omitempty,omitzero"` // Object subtype hint. Specified for object type values only. NOTE: If you change anything here, make sure to also update subtype in ObjectPreview and PropertyPreview below. + Type RemoteObjectType `json:"type"` // Object type. + Subtype RemoteObjectSubtype `json:"subtype,omitempty,omitzero"` // Object subtype hint. Specified for object type values only. NOTE: If you change anything here, make sure to also update subtype in ObjectPreview and PropertyPreview below. ClassName string `json:"className,omitempty,omitzero"` // Object class (constructor) name. Specified for object type values only. - Value jsontext.Value `json:"value,omitempty,omitzero"` // Remote object value in case of primitive values or JSON values (if it was requested). + Value jsonv2.Value `json:"value,omitempty,omitzero"` // Remote object value in case of primitive values or JSON values (if it was requested). UnserializableValue UnserializableValue `json:"unserializableValue,omitempty,omitzero"` // Primitive value which can not be JSON-stringified does not have value, but gets this property. Description string `json:"description,omitempty,omitzero"` // String representation of the object. DeepSerializedValue *DeepSerializedValue `json:"deepSerializedValue,omitempty,omitzero"` // Deep serialized value. @@ -81,23 +76,23 @@ type CustomPreview struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#type-ObjectPreview type ObjectPreview struct { - Type Type `json:"type"` // Object type. - Subtype Subtype `json:"subtype,omitempty,omitzero"` // Object subtype hint. Specified for object type values only. - Description string `json:"description,omitempty,omitzero"` // String representation of the object. - Overflow bool `json:"overflow"` // True iff some of the properties or entries of the original object did not fit. - Properties []*PropertyPreview `json:"properties"` // List of the properties. - Entries []*EntryPreview `json:"entries,omitempty,omitzero"` // List of the entries. Specified for map and set subtype values only. + Type ObjectPreviewType `json:"type"` // Object type. + Subtype ObjectPreviewSubtype `json:"subtype,omitempty,omitzero"` // Object subtype hint. Specified for object type values only. + Description string `json:"description,omitempty,omitzero"` // String representation of the object. + Overflow bool `json:"overflow"` // True iff some of the properties or entries of the original object did not fit. + Properties []*PropertyPreview `json:"properties"` // List of the properties. + Entries []*EntryPreview `json:"entries,omitempty,omitzero"` // List of the entries. Specified for map and set subtype values only. } // PropertyPreview [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#type-PropertyPreview type PropertyPreview struct { - Name string `json:"name"` // Property name. - Type Type `json:"type"` // Object type. Accessor means that the property itself is an accessor property. - Value string `json:"value,omitempty,omitzero"` // User-friendly property value string. - ValuePreview *ObjectPreview `json:"valuePreview,omitempty,omitzero"` // Nested value preview. - Subtype Subtype `json:"subtype,omitempty,omitzero"` // Object subtype hint. Specified for object type values only. + Name string `json:"name"` // Property name. + Type PropertyPreviewType `json:"type"` // Object type. Accessor means that the property itself is an accessor property. + Value string `json:"value,omitempty,omitzero"` // User-friendly property value string. + ValuePreview *ObjectPreview `json:"valuePreview,omitempty,omitzero"` // Nested value preview. + Subtype PropertyPreviewSubtype `json:"subtype,omitempty,omitzero"` // Object subtype hint. Specified for object type values only. } // EntryPreview [no description]. @@ -149,7 +144,7 @@ type PrivatePropertyDescriptor struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#type-CallArgument type CallArgument struct { - Value jsontext.Value `json:"value,omitempty,omitzero"` // Primitive value or serializable javascript object. + Value jsonv2.Value `json:"value,omitempty,omitzero"` // Primitive value or serializable javascript object. UnserializableValue UnserializableValue `json:"unserializableValue,omitempty,omitzero"` // Primitive value which can not be JSON-stringified. ObjectID RemoteObjectID `json:"objectId,omitempty,omitzero"` // Remote object handle. } @@ -172,7 +167,7 @@ type ExecutionContextDescription struct { Origin string `json:"origin"` // Execution context origin. Name string `json:"name"` // Human readable name describing given context. UniqueID string `json:"uniqueId"` // A system-unique execution context identifier. Unlike the id, this is unique across multiple processes, so can be reliably used to identify specific context while backend performs a cross-process navigation. - AuxData jsontext.Value `json:"auxData,omitempty,omitzero"` + AuxData jsonv2.Value `json:"auxData,omitempty,omitzero"` } // ExceptionDetails detailed information about exception (or error) that was @@ -189,45 +184,17 @@ type ExceptionDetails struct { StackTrace *StackTrace `json:"stackTrace,omitempty,omitzero"` // JavaScript stack trace if available. Exception *RemoteObject `json:"exception,omitempty,omitzero"` // Exception object if available. ExecutionContextID ExecutionContextID `json:"executionContextId,omitempty,omitzero"` // Identifier of the context where exception happened. - ExceptionMetaData jsontext.Value `json:"exceptionMetaData,omitempty,omitzero"` -} - -// Error satisfies the error interface. -func (e *ExceptionDetails) Error() string { - var b strings.Builder - // TODO: watch script parsed events and match the ExceptionDetails.ScriptID - // to the name/location of the actual code and display here - fmt.Fprintf(&b, "exception %q (%d:%d)", e.Text, e.LineNumber, e.ColumnNumber) - if obj := e.Exception; obj != nil { - fmt.Fprintf(&b, ": %s", obj.Description) - } - return b.String() + ExceptionMetaData jsonv2.Value `json:"exceptionMetaData,omitempty,omitzero"` } // Timestamp number of milliseconds since epoch. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#type-Timestamp -type Timestamp time.Time - -// Time returns the Timestamp as time.Time value. -func (t Timestamp) Time() time.Time { - return time.Time(t) -} - -// MarshalJSON satisfies [json.Marshaler]. -func (t Timestamp) MarshalJSON() ([]byte, error) { - v := float64(time.Time(t).UnixNano() / int64(time.Millisecond)) - return strconv.AppendFloat(make([]byte, 0, 20), v, 'f', -1, 64), nil -} +type Timestamp float64 -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *Timestamp) UnmarshalJSON(buf []byte) error { - f, err := strconv.ParseFloat(string(buf), 64) - if err != nil { - return err - } - *t = Timestamp(time.Unix(0, int64(f*float64(time.Millisecond)))) - return nil +// Float64 returns the Timestamp as float64 value. +func (t Timestamp) Float64() float64 { + return float64(t) } // TimeDelta number of milliseconds. @@ -288,24 +255,6 @@ const ( SerializationOptionsSerializationIDOnly SerializationOptionsSerialization = "idOnly" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SerializationOptionsSerialization) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SerializationOptionsSerialization(s) { - case SerializationOptionsSerializationDeep: - *t = SerializationOptionsSerializationDeep - case SerializationOptionsSerializationJSON: - *t = SerializationOptionsSerializationJSON - case SerializationOptionsSerializationIDOnly: - *t = SerializationOptionsSerializationIDOnly - default: - return fmt.Errorf("unknown SerializationOptionsSerialization value: %v", s) - } - return nil -} - // DeepSerializedValueType [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#type-DeepSerializedValue @@ -344,283 +293,211 @@ const ( DeepSerializedValueTypeGenerator DeepSerializedValueType = "generator" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *DeepSerializedValueType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch DeepSerializedValueType(s) { - case DeepSerializedValueTypeUndefined: - *t = DeepSerializedValueTypeUndefined - case DeepSerializedValueTypeNull: - *t = DeepSerializedValueTypeNull - case DeepSerializedValueTypeString: - *t = DeepSerializedValueTypeString - case DeepSerializedValueTypeNumber: - *t = DeepSerializedValueTypeNumber - case DeepSerializedValueTypeBoolean: - *t = DeepSerializedValueTypeBoolean - case DeepSerializedValueTypeBigint: - *t = DeepSerializedValueTypeBigint - case DeepSerializedValueTypeRegexp: - *t = DeepSerializedValueTypeRegexp - case DeepSerializedValueTypeDate: - *t = DeepSerializedValueTypeDate - case DeepSerializedValueTypeSymbol: - *t = DeepSerializedValueTypeSymbol - case DeepSerializedValueTypeArray: - *t = DeepSerializedValueTypeArray - case DeepSerializedValueTypeObject: - *t = DeepSerializedValueTypeObject - case DeepSerializedValueTypeFunction: - *t = DeepSerializedValueTypeFunction - case DeepSerializedValueTypeMap: - *t = DeepSerializedValueTypeMap - case DeepSerializedValueTypeSet: - *t = DeepSerializedValueTypeSet - case DeepSerializedValueTypeWeakmap: - *t = DeepSerializedValueTypeWeakmap - case DeepSerializedValueTypeWeakset: - *t = DeepSerializedValueTypeWeakset - case DeepSerializedValueTypeError: - *t = DeepSerializedValueTypeError - case DeepSerializedValueTypeProxy: - *t = DeepSerializedValueTypeProxy - case DeepSerializedValueTypePromise: - *t = DeepSerializedValueTypePromise - case DeepSerializedValueTypeTypedarray: - *t = DeepSerializedValueTypeTypedarray - case DeepSerializedValueTypeArraybuffer: - *t = DeepSerializedValueTypeArraybuffer - case DeepSerializedValueTypeNode: - *t = DeepSerializedValueTypeNode - case DeepSerializedValueTypeWindow: - *t = DeepSerializedValueTypeWindow - case DeepSerializedValueTypeGenerator: - *t = DeepSerializedValueTypeGenerator - default: - return fmt.Errorf("unknown DeepSerializedValueType value: %v", s) - } - return nil +// RemoteObjectType object type. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#type-RemoteObject +type RemoteObjectType string + +// String returns the RemoteObjectType as string value. +func (t RemoteObjectType) String() string { + return string(t) } -// Type object type. +// RemoteObjectType values. +const ( + RemoteObjectTypeObject RemoteObjectType = "object" + RemoteObjectTypeFunction RemoteObjectType = "function" + RemoteObjectTypeUndefined RemoteObjectType = "undefined" + RemoteObjectTypeString RemoteObjectType = "string" + RemoteObjectTypeNumber RemoteObjectType = "number" + RemoteObjectTypeBoolean RemoteObjectType = "boolean" + RemoteObjectTypeSymbol RemoteObjectType = "symbol" + RemoteObjectTypeBigint RemoteObjectType = "bigint" +) + +// RemoteObjectSubtype object subtype hint. Specified for object type values +// only. NOTE: If you change anything here, make sure to also update subtype in +// ObjectPreview and PropertyPreview below. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#type-RemoteObject -type Type string +type RemoteObjectSubtype string -// String returns the Type as string value. -func (t Type) String() string { +// String returns the RemoteObjectSubtype as string value. +func (t RemoteObjectSubtype) String() string { return string(t) } -// Type values. +// RemoteObjectSubtype values. const ( - TypeObject Type = "object" - TypeFunction Type = "function" - TypeUndefined Type = "undefined" - TypeString Type = "string" - TypeNumber Type = "number" - TypeBoolean Type = "boolean" - TypeSymbol Type = "symbol" - TypeBigint Type = "bigint" - TypeAccessor Type = "accessor" + RemoteObjectSubtypeArray RemoteObjectSubtype = "array" + RemoteObjectSubtypeNull RemoteObjectSubtype = "null" + RemoteObjectSubtypeNode RemoteObjectSubtype = "node" + RemoteObjectSubtypeRegexp RemoteObjectSubtype = "regexp" + RemoteObjectSubtypeDate RemoteObjectSubtype = "date" + RemoteObjectSubtypeMap RemoteObjectSubtype = "map" + RemoteObjectSubtypeSet RemoteObjectSubtype = "set" + RemoteObjectSubtypeWeakmap RemoteObjectSubtype = "weakmap" + RemoteObjectSubtypeWeakset RemoteObjectSubtype = "weakset" + RemoteObjectSubtypeIterator RemoteObjectSubtype = "iterator" + RemoteObjectSubtypeGenerator RemoteObjectSubtype = "generator" + RemoteObjectSubtypeError RemoteObjectSubtype = "error" + RemoteObjectSubtypeProxy RemoteObjectSubtype = "proxy" + RemoteObjectSubtypePromise RemoteObjectSubtype = "promise" + RemoteObjectSubtypeTypedarray RemoteObjectSubtype = "typedarray" + RemoteObjectSubtypeArraybuffer RemoteObjectSubtype = "arraybuffer" + RemoteObjectSubtypeDataview RemoteObjectSubtype = "dataview" + RemoteObjectSubtypeWebassemblymemory RemoteObjectSubtype = "webassemblymemory" + RemoteObjectSubtypeWasmvalue RemoteObjectSubtype = "wasmvalue" + RemoteObjectSubtypeDeferredmodule RemoteObjectSubtype = "deferredmodule" + RemoteObjectSubtypeTrustedtype RemoteObjectSubtype = "trustedtype" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *Type) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch Type(s) { - case TypeObject: - *t = TypeObject - case TypeFunction: - *t = TypeFunction - case TypeUndefined: - *t = TypeUndefined - case TypeString: - *t = TypeString - case TypeNumber: - *t = TypeNumber - case TypeBoolean: - *t = TypeBoolean - case TypeSymbol: - *t = TypeSymbol - case TypeBigint: - *t = TypeBigint - case TypeAccessor: - *t = TypeAccessor - default: - return fmt.Errorf("unknown Type value: %v", s) - } - return nil +// ObjectPreviewType object type. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#type-ObjectPreview +type ObjectPreviewType string + +// String returns the ObjectPreviewType as string value. +func (t ObjectPreviewType) String() string { + return string(t) } -// Subtype object subtype hint. Specified for object type values only. NOTE: -// If you change anything here, make sure to also update subtype in -// ObjectPreview and PropertyPreview below. +// ObjectPreviewType values. +const ( + ObjectPreviewTypeObject ObjectPreviewType = "object" + ObjectPreviewTypeFunction ObjectPreviewType = "function" + ObjectPreviewTypeUndefined ObjectPreviewType = "undefined" + ObjectPreviewTypeString ObjectPreviewType = "string" + ObjectPreviewTypeNumber ObjectPreviewType = "number" + ObjectPreviewTypeBoolean ObjectPreviewType = "boolean" + ObjectPreviewTypeSymbol ObjectPreviewType = "symbol" + ObjectPreviewTypeBigint ObjectPreviewType = "bigint" +) + +// ObjectPreviewSubtype object subtype hint. Specified for object type values +// only. // -// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#type-RemoteObject -type Subtype string +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#type-ObjectPreview +type ObjectPreviewSubtype string -// String returns the Subtype as string value. -func (t Subtype) String() string { +// String returns the ObjectPreviewSubtype as string value. +func (t ObjectPreviewSubtype) String() string { return string(t) } -// Subtype values. +// ObjectPreviewSubtype values. const ( - SubtypeArray Subtype = "array" - SubtypeNull Subtype = "null" - SubtypeNode Subtype = "node" - SubtypeRegexp Subtype = "regexp" - SubtypeDate Subtype = "date" - SubtypeMap Subtype = "map" - SubtypeSet Subtype = "set" - SubtypeWeakmap Subtype = "weakmap" - SubtypeWeakset Subtype = "weakset" - SubtypeIterator Subtype = "iterator" - SubtypeGenerator Subtype = "generator" - SubtypeError Subtype = "error" - SubtypeProxy Subtype = "proxy" - SubtypePromise Subtype = "promise" - SubtypeTypedarray Subtype = "typedarray" - SubtypeArraybuffer Subtype = "arraybuffer" - SubtypeDataview Subtype = "dataview" - SubtypeWebassemblymemory Subtype = "webassemblymemory" - SubtypeWasmvalue Subtype = "wasmvalue" - SubtypeTrustedtype Subtype = "trustedtype" + ObjectPreviewSubtypeArray ObjectPreviewSubtype = "array" + ObjectPreviewSubtypeNull ObjectPreviewSubtype = "null" + ObjectPreviewSubtypeNode ObjectPreviewSubtype = "node" + ObjectPreviewSubtypeRegexp ObjectPreviewSubtype = "regexp" + ObjectPreviewSubtypeDate ObjectPreviewSubtype = "date" + ObjectPreviewSubtypeMap ObjectPreviewSubtype = "map" + ObjectPreviewSubtypeSet ObjectPreviewSubtype = "set" + ObjectPreviewSubtypeWeakmap ObjectPreviewSubtype = "weakmap" + ObjectPreviewSubtypeWeakset ObjectPreviewSubtype = "weakset" + ObjectPreviewSubtypeIterator ObjectPreviewSubtype = "iterator" + ObjectPreviewSubtypeGenerator ObjectPreviewSubtype = "generator" + ObjectPreviewSubtypeError ObjectPreviewSubtype = "error" + ObjectPreviewSubtypeProxy ObjectPreviewSubtype = "proxy" + ObjectPreviewSubtypePromise ObjectPreviewSubtype = "promise" + ObjectPreviewSubtypeTypedarray ObjectPreviewSubtype = "typedarray" + ObjectPreviewSubtypeArraybuffer ObjectPreviewSubtype = "arraybuffer" + ObjectPreviewSubtypeDataview ObjectPreviewSubtype = "dataview" + ObjectPreviewSubtypeWebassemblymemory ObjectPreviewSubtype = "webassemblymemory" + ObjectPreviewSubtypeWasmvalue ObjectPreviewSubtype = "wasmvalue" + ObjectPreviewSubtypeDeferredmodule ObjectPreviewSubtype = "deferredmodule" + ObjectPreviewSubtypeTrustedtype ObjectPreviewSubtype = "trustedtype" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *Subtype) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch Subtype(s) { - case SubtypeArray: - *t = SubtypeArray - case SubtypeNull: - *t = SubtypeNull - case SubtypeNode: - *t = SubtypeNode - case SubtypeRegexp: - *t = SubtypeRegexp - case SubtypeDate: - *t = SubtypeDate - case SubtypeMap: - *t = SubtypeMap - case SubtypeSet: - *t = SubtypeSet - case SubtypeWeakmap: - *t = SubtypeWeakmap - case SubtypeWeakset: - *t = SubtypeWeakset - case SubtypeIterator: - *t = SubtypeIterator - case SubtypeGenerator: - *t = SubtypeGenerator - case SubtypeError: - *t = SubtypeError - case SubtypeProxy: - *t = SubtypeProxy - case SubtypePromise: - *t = SubtypePromise - case SubtypeTypedarray: - *t = SubtypeTypedarray - case SubtypeArraybuffer: - *t = SubtypeArraybuffer - case SubtypeDataview: - *t = SubtypeDataview - case SubtypeWebassemblymemory: - *t = SubtypeWebassemblymemory - case SubtypeWasmvalue: - *t = SubtypeWasmvalue - case SubtypeTrustedtype: - *t = SubtypeTrustedtype - default: - return fmt.Errorf("unknown Subtype value: %v", s) - } - return nil +// PropertyPreviewType object type. Accessor means that the property itself +// is an accessor property. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#type-PropertyPreview +type PropertyPreviewType string + +// String returns the PropertyPreviewType as string value. +func (t PropertyPreviewType) String() string { + return string(t) } -// APIType type of the call. +// PropertyPreviewType values. +const ( + PropertyPreviewTypeObject PropertyPreviewType = "object" + PropertyPreviewTypeFunction PropertyPreviewType = "function" + PropertyPreviewTypeUndefined PropertyPreviewType = "undefined" + PropertyPreviewTypeString PropertyPreviewType = "string" + PropertyPreviewTypeNumber PropertyPreviewType = "number" + PropertyPreviewTypeBoolean PropertyPreviewType = "boolean" + PropertyPreviewTypeSymbol PropertyPreviewType = "symbol" + PropertyPreviewTypeAccessor PropertyPreviewType = "accessor" + PropertyPreviewTypeBigint PropertyPreviewType = "bigint" +) + +// PropertyPreviewSubtype object subtype hint. Specified for object type +// values only. // -// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-consoleAPICalled -type APIType string +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#type-PropertyPreview +type PropertyPreviewSubtype string -// String returns the APIType as string value. -func (t APIType) String() string { +// String returns the PropertyPreviewSubtype as string value. +func (t PropertyPreviewSubtype) String() string { return string(t) } -// APIType values. +// PropertyPreviewSubtype values. const ( - APITypeLog APIType = "log" - APITypeDebug APIType = "debug" - APITypeInfo APIType = "info" - APITypeError APIType = "error" - APITypeWarning APIType = "warning" - APITypeDir APIType = "dir" - APITypeDirxml APIType = "dirxml" - APITypeTable APIType = "table" - APITypeTrace APIType = "trace" - APITypeClear APIType = "clear" - APITypeStartGroup APIType = "startGroup" - APITypeStartGroupCollapsed APIType = "startGroupCollapsed" - APITypeEndGroup APIType = "endGroup" - APITypeAssert APIType = "assert" - APITypeProfile APIType = "profile" - APITypeProfileEnd APIType = "profileEnd" - APITypeCount APIType = "count" - APITypeTimeEnd APIType = "timeEnd" + PropertyPreviewSubtypeArray PropertyPreviewSubtype = "array" + PropertyPreviewSubtypeNull PropertyPreviewSubtype = "null" + PropertyPreviewSubtypeNode PropertyPreviewSubtype = "node" + PropertyPreviewSubtypeRegexp PropertyPreviewSubtype = "regexp" + PropertyPreviewSubtypeDate PropertyPreviewSubtype = "date" + PropertyPreviewSubtypeMap PropertyPreviewSubtype = "map" + PropertyPreviewSubtypeSet PropertyPreviewSubtype = "set" + PropertyPreviewSubtypeWeakmap PropertyPreviewSubtype = "weakmap" + PropertyPreviewSubtypeWeakset PropertyPreviewSubtype = "weakset" + PropertyPreviewSubtypeIterator PropertyPreviewSubtype = "iterator" + PropertyPreviewSubtypeGenerator PropertyPreviewSubtype = "generator" + PropertyPreviewSubtypeError PropertyPreviewSubtype = "error" + PropertyPreviewSubtypeProxy PropertyPreviewSubtype = "proxy" + PropertyPreviewSubtypePromise PropertyPreviewSubtype = "promise" + PropertyPreviewSubtypeTypedarray PropertyPreviewSubtype = "typedarray" + PropertyPreviewSubtypeArraybuffer PropertyPreviewSubtype = "arraybuffer" + PropertyPreviewSubtypeDataview PropertyPreviewSubtype = "dataview" + PropertyPreviewSubtypeWebassemblymemory PropertyPreviewSubtype = "webassemblymemory" + PropertyPreviewSubtypeWasmvalue PropertyPreviewSubtype = "wasmvalue" + PropertyPreviewSubtypeDeferredmodule PropertyPreviewSubtype = "deferredmodule" + PropertyPreviewSubtypeTrustedtype PropertyPreviewSubtype = "trustedtype" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *APIType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch APIType(s) { - case APITypeLog: - *t = APITypeLog - case APITypeDebug: - *t = APITypeDebug - case APITypeInfo: - *t = APITypeInfo - case APITypeError: - *t = APITypeError - case APITypeWarning: - *t = APITypeWarning - case APITypeDir: - *t = APITypeDir - case APITypeDirxml: - *t = APITypeDirxml - case APITypeTable: - *t = APITypeTable - case APITypeTrace: - *t = APITypeTrace - case APITypeClear: - *t = APITypeClear - case APITypeStartGroup: - *t = APITypeStartGroup - case APITypeStartGroupCollapsed: - *t = APITypeStartGroupCollapsed - case APITypeEndGroup: - *t = APITypeEndGroup - case APITypeAssert: - *t = APITypeAssert - case APITypeProfile: - *t = APITypeProfile - case APITypeProfileEnd: - *t = APITypeProfileEnd - case APITypeCount: - *t = APITypeCount - case APITypeTimeEnd: - *t = APITypeTimeEnd - default: - return fmt.Errorf("unknown APIType value: %v", s) - } - return nil +// ConsoleAPICalledType type of the call. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-consoleAPICalled +type ConsoleAPICalledType string + +// String returns the ConsoleAPICalledType as string value. +func (t ConsoleAPICalledType) String() string { + return string(t) } + +// ConsoleAPICalledType values. +const ( + ConsoleAPICalledTypeLog ConsoleAPICalledType = "log" + ConsoleAPICalledTypeDebug ConsoleAPICalledType = "debug" + ConsoleAPICalledTypeInfo ConsoleAPICalledType = "info" + ConsoleAPICalledTypeError ConsoleAPICalledType = "error" + ConsoleAPICalledTypeWarning ConsoleAPICalledType = "warning" + ConsoleAPICalledTypeDir ConsoleAPICalledType = "dir" + ConsoleAPICalledTypeDirxml ConsoleAPICalledType = "dirxml" + ConsoleAPICalledTypeTable ConsoleAPICalledType = "table" + ConsoleAPICalledTypeTrace ConsoleAPICalledType = "trace" + ConsoleAPICalledTypeClear ConsoleAPICalledType = "clear" + ConsoleAPICalledTypeStartGroup ConsoleAPICalledType = "startGroup" + ConsoleAPICalledTypeStartGroupCollapsed ConsoleAPICalledType = "startGroupCollapsed" + ConsoleAPICalledTypeEndGroup ConsoleAPICalledType = "endGroup" + ConsoleAPICalledTypeAssert ConsoleAPICalledType = "assert" + ConsoleAPICalledTypeProfile ConsoleAPICalledType = "profile" + ConsoleAPICalledTypeProfileEnd ConsoleAPICalledType = "profileEnd" + ConsoleAPICalledTypeCount ConsoleAPICalledType = "count" + ConsoleAPICalledTypeTimeEnd ConsoleAPICalledType = "timeEnd" +) diff --git a/vendor/github.com/chromedp/cdproto/security/events.go b/vendor/github.com/chromedp/cdproto/security/events.go index 3897564e6..c645ca951 100644 --- a/vendor/github.com/chromedp/cdproto/security/events.go +++ b/vendor/github.com/chromedp/cdproto/security/events.go @@ -1,6 +1,6 @@ -package security +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package security // EventVisibleSecurityStateChanged the security state of the page changed. // diff --git a/vendor/github.com/chromedp/cdproto/security/security.go b/vendor/github.com/chromedp/cdproto/security/security.go index cef4704b7..0818950ff 100644 --- a/vendor/github.com/chromedp/cdproto/security/security.go +++ b/vendor/github.com/chromedp/cdproto/security/security.go @@ -1,49 +1,27 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package security provides the Chrome DevTools Protocol // commands, types, and events for the Security domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package security -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// DisableParams disables tracking security state changes. -type DisableParams struct{} - // Disable disables tracking security state changes. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Security#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes Security.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// EnableParams enables tracking security state changes. -type EnableParams struct{} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} // Enable enables tracking security state changes. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Security#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} - -// Do executes Security.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) -} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} -// SetIgnoreCertificateErrorsParams enable/disable whether all certificate -// errors should be ignored. +// SetIgnoreCertificateErrorsParams are the parameters of the command +// Security.setIgnoreCertificateErrors. type SetIgnoreCertificateErrorsParams struct { Ignore bool `json:"ignore"` // If true, all certificate errors will be ignored. } @@ -52,20 +30,12 @@ type SetIgnoreCertificateErrorsParams struct { // should be ignored. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Security#method-setIgnoreCertificateErrors -// -// parameters: -// -// ignore - If true, all certificate errors will be ignored. -func SetIgnoreCertificateErrors(ignore bool) *SetIgnoreCertificateErrorsParams { - return &SetIgnoreCertificateErrorsParams{ - Ignore: ignore, - } -} +var SetIgnoreCertificateErrors = cdp.Command[SetIgnoreCertificateErrorsParams, cdp.Empty]{Method: CommandSetIgnoreCertificateErrors} -// Do executes Security.setIgnoreCertificateErrors against the provided context. -func (p *SetIgnoreCertificateErrorsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetIgnoreCertificateErrors, p, nil) -} +// VisibleSecurityStateChanged the security state of the page changed. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Security#event-visibleSecurityStateChanged +var VisibleSecurityStateChanged = cdp.Event[EventVisibleSecurityStateChanged]{Method: "Security.visibleSecurityStateChanged"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/security/types.go b/vendor/github.com/chromedp/cdproto/security/types.go index 84dbfea7b..dde3000da 100644 --- a/vendor/github.com/chromedp/cdproto/security/types.go +++ b/vendor/github.com/chromedp/cdproto/security/types.go @@ -1,11 +1,8 @@ -package security +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package security import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/cdp" ) @@ -37,24 +34,6 @@ const ( MixedContentTypeNone MixedContentType = "none" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *MixedContentType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch MixedContentType(s) { - case MixedContentTypeBlockable: - *t = MixedContentTypeBlockable - case MixedContentTypeOptionallyBlockable: - *t = MixedContentTypeOptionallyBlockable - case MixedContentTypeNone: - *t = MixedContentTypeNone - default: - return fmt.Errorf("unknown MixedContentType value: %v", s) - } - return nil -} - // State the security level of a page or resource. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Security#type-SecurityState @@ -75,53 +54,29 @@ const ( StateInsecureBroken State = "insecure-broken" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *State) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch State(s) { - case StateUnknown: - *t = StateUnknown - case StateNeutral: - *t = StateNeutral - case StateInsecure: - *t = StateInsecure - case StateSecure: - *t = StateSecure - case StateInfo: - *t = StateInfo - case StateInsecureBroken: - *t = StateInsecureBroken - default: - return fmt.Errorf("unknown State value: %v", s) - } - return nil -} - // CertificateSecurityState details about the security state of the page // certificate. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Security#type-CertificateSecurityState type CertificateSecurityState struct { - Protocol string `json:"protocol"` // Protocol name (e.g. "TLS 1.2" or "QUIC"). - KeyExchange string `json:"keyExchange"` // Key Exchange used by the connection, or the empty string if not applicable. - KeyExchangeGroup string `json:"keyExchangeGroup,omitempty,omitzero"` // (EC)DH group used by the connection, if applicable. - Cipher string `json:"cipher"` // Cipher name. - Mac string `json:"mac,omitempty,omitzero"` // TLS MAC. Note that AEAD ciphers do not have separate MACs. - Certificate []string `json:"certificate"` // Page certificate. - SubjectName string `json:"subjectName"` // Certificate subject name. - Issuer string `json:"issuer"` // Name of the issuing CA. - ValidFrom *cdp.TimeSinceEpoch `json:"validFrom"` // Certificate valid from date. - ValidTo *cdp.TimeSinceEpoch `json:"validTo"` // Certificate valid to (expiration) date - CertificateNetworkError string `json:"certificateNetworkError,omitempty,omitzero"` // The highest priority network error code, if the certificate has an error. - CertificateHasWeakSignature bool `json:"certificateHasWeakSignature"` // True if the certificate uses a weak signature algorithm. - CertificateHasSha1signature bool `json:"certificateHasSha1Signature"` // True if the certificate has a SHA1 signature in the chain. - ModernSSL bool `json:"modernSSL"` // True if modern SSL - ObsoleteSslProtocol bool `json:"obsoleteSslProtocol"` // True if the connection is using an obsolete SSL protocol. - ObsoleteSslKeyExchange bool `json:"obsoleteSslKeyExchange"` // True if the connection is using an obsolete SSL key exchange. - ObsoleteSslCipher bool `json:"obsoleteSslCipher"` // True if the connection is using an obsolete SSL cipher. - ObsoleteSslSignature bool `json:"obsoleteSslSignature"` // True if the connection is using an obsolete SSL signature. + Protocol string `json:"protocol"` // Protocol name (e.g. "TLS 1.2" or "QUIC"). + KeyExchange string `json:"keyExchange"` // Key Exchange used by the connection, or the empty string if not applicable. + KeyExchangeGroup string `json:"keyExchangeGroup,omitempty,omitzero"` // (EC)DH group used by the connection, if applicable. + Cipher string `json:"cipher"` // Cipher name. + Mac string `json:"mac,omitempty,omitzero"` // TLS MAC. Note that AEAD ciphers do not have separate MACs. + Certificate []string `json:"certificate"` // Page certificate. + SubjectName string `json:"subjectName"` // Certificate subject name. + Issuer string `json:"issuer"` // Name of the issuing CA. + ValidFrom cdp.TimeSinceEpoch `json:"validFrom"` // Certificate valid from date. + ValidTo cdp.TimeSinceEpoch `json:"validTo"` // Certificate valid to (expiration) date + CertificateNetworkError string `json:"certificateNetworkError,omitempty,omitzero"` // The highest priority network error code, if the certificate has an error. + CertificateHasWeakSignature bool `json:"certificateHasWeakSignature"` // True if the certificate uses a weak signature algorithm. + CertificateHasSha1signature bool `json:"certificateHasSha1Signature"` // True if the certificate has a SHA1 signature in the chain. + ModernSSL bool `json:"modernSSL"` // True if modern SSL + ObsoleteSslProtocol bool `json:"obsoleteSslProtocol"` // True if the connection is using an obsolete SSL protocol. + ObsoleteSslKeyExchange bool `json:"obsoleteSslKeyExchange"` // True if the connection is using an obsolete SSL key exchange. + ObsoleteSslCipher bool `json:"obsoleteSslCipher"` // True if the connection is using an obsolete SSL cipher. + ObsoleteSslSignature bool `json:"obsoleteSslSignature"` // True if the connection is using an obsolete SSL signature. } // SafetyTipStatus [no description]. @@ -140,22 +95,6 @@ const ( SafetyTipStatusLookalike SafetyTipStatus = "lookalike" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SafetyTipStatus) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SafetyTipStatus(s) { - case SafetyTipStatusBadReputation: - *t = SafetyTipStatusBadReputation - case SafetyTipStatusLookalike: - *t = SafetyTipStatusLookalike - default: - return fmt.Errorf("unknown SafetyTipStatus value: %v", s) - } - return nil -} - // SafetyTipInfo [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Security#type-SafetyTipInfo @@ -205,19 +144,3 @@ const ( CertificateErrorActionContinue CertificateErrorAction = "continue" CertificateErrorActionCancel CertificateErrorAction = "cancel" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *CertificateErrorAction) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch CertificateErrorAction(s) { - case CertificateErrorActionContinue: - *t = CertificateErrorActionContinue - case CertificateErrorActionCancel: - *t = CertificateErrorActionCancel - default: - return fmt.Errorf("unknown CertificateErrorAction value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/serviceworker/events.go b/vendor/github.com/chromedp/cdproto/serviceworker/events.go index 0852bd055..559756f4a 100644 --- a/vendor/github.com/chromedp/cdproto/serviceworker/events.go +++ b/vendor/github.com/chromedp/cdproto/serviceworker/events.go @@ -1,6 +1,6 @@ -package serviceworker +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package serviceworker // EventWorkerErrorReported [no description]. // diff --git a/vendor/github.com/chromedp/cdproto/serviceworker/serviceworker.go b/vendor/github.com/chromedp/cdproto/serviceworker/serviceworker.go index 8502e6e6f..32b675a13 100644 --- a/vendor/github.com/chromedp/cdproto/serviceworker/serviceworker.go +++ b/vendor/github.com/chromedp/cdproto/serviceworker/serviceworker.go @@ -1,18 +1,17 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package serviceworker provides the Chrome DevTools Protocol // commands, types, and events for the ServiceWorker domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package serviceworker -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// DeliverPushMessageParams [no description]. +// DeliverPushMessageParams are the parameters of the command +// ServiceWorker.deliverPushMessage. type DeliverPushMessageParams struct { Origin string `json:"origin"` RegistrationID RegistrationID `json:"registrationId"` @@ -22,41 +21,15 @@ type DeliverPushMessageParams struct { // DeliverPushMessage [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-deliverPushMessage -// -// parameters: -// -// origin -// registrationID -// data -func DeliverPushMessage(origin string, registrationID RegistrationID, data string) *DeliverPushMessageParams { - return &DeliverPushMessageParams{ - Origin: origin, - RegistrationID: registrationID, - Data: data, - } -} - -// Do executes ServiceWorker.deliverPushMessage against the provided context. -func (p *DeliverPushMessageParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDeliverPushMessage, p, nil) -} - -// DisableParams [no description]. -type DisableParams struct{} +var DeliverPushMessage = cdp.Command[DeliverPushMessageParams, cdp.Empty]{Method: CommandDeliverPushMessage} // Disable [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes ServiceWorker.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} -// DispatchSyncEventParams [no description]. +// DispatchSyncEventParams are the parameters of the command +// ServiceWorker.dispatchSyncEvent. type DispatchSyncEventParams struct { Origin string `json:"origin"` RegistrationID RegistrationID `json:"registrationId"` @@ -67,28 +40,10 @@ type DispatchSyncEventParams struct { // DispatchSyncEvent [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-dispatchSyncEvent -// -// parameters: -// -// origin -// registrationID -// tag -// lastChance -func DispatchSyncEvent(origin string, registrationID RegistrationID, tag string, lastChance bool) *DispatchSyncEventParams { - return &DispatchSyncEventParams{ - Origin: origin, - RegistrationID: registrationID, - Tag: tag, - LastChance: lastChance, - } -} +var DispatchSyncEvent = cdp.Command[DispatchSyncEventParams, cdp.Empty]{Method: CommandDispatchSyncEvent} -// Do executes ServiceWorker.dispatchSyncEvent against the provided context. -func (p *DispatchSyncEventParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDispatchSyncEvent, p, nil) -} - -// DispatchPeriodicSyncEventParams [no description]. +// DispatchPeriodicSyncEventParams are the parameters of the command +// ServiceWorker.dispatchPeriodicSyncEvent. type DispatchPeriodicSyncEventParams struct { Origin string `json:"origin"` RegistrationID RegistrationID `json:"registrationId"` @@ -98,41 +53,15 @@ type DispatchPeriodicSyncEventParams struct { // DispatchPeriodicSyncEvent [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-dispatchPeriodicSyncEvent -// -// parameters: -// -// origin -// registrationID -// tag -func DispatchPeriodicSyncEvent(origin string, registrationID RegistrationID, tag string) *DispatchPeriodicSyncEventParams { - return &DispatchPeriodicSyncEventParams{ - Origin: origin, - RegistrationID: registrationID, - Tag: tag, - } -} - -// Do executes ServiceWorker.dispatchPeriodicSyncEvent against the provided context. -func (p *DispatchPeriodicSyncEventParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDispatchPeriodicSyncEvent, p, nil) -} - -// EnableParams [no description]. -type EnableParams struct{} +var DispatchPeriodicSyncEvent = cdp.Command[DispatchPeriodicSyncEventParams, cdp.Empty]{Method: CommandDispatchPeriodicSyncEvent} // Enable [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} - -// Do executes ServiceWorker.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) -} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} -// SetForceUpdateOnPageLoadParams [no description]. +// SetForceUpdateOnPageLoadParams are the parameters of the command +// ServiceWorker.setForceUpdateOnPageLoad. type SetForceUpdateOnPageLoadParams struct { ForceUpdateOnPageLoad bool `json:"forceUpdateOnPageLoad"` } @@ -140,22 +69,10 @@ type SetForceUpdateOnPageLoadParams struct { // SetForceUpdateOnPageLoad [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-setForceUpdateOnPageLoad -// -// parameters: -// -// forceUpdateOnPageLoad -func SetForceUpdateOnPageLoad(forceUpdateOnPageLoad bool) *SetForceUpdateOnPageLoadParams { - return &SetForceUpdateOnPageLoadParams{ - ForceUpdateOnPageLoad: forceUpdateOnPageLoad, - } -} - -// Do executes ServiceWorker.setForceUpdateOnPageLoad against the provided context. -func (p *SetForceUpdateOnPageLoadParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetForceUpdateOnPageLoad, p, nil) -} +var SetForceUpdateOnPageLoad = cdp.Command[SetForceUpdateOnPageLoadParams, cdp.Empty]{Method: CommandSetForceUpdateOnPageLoad} -// SkipWaitingParams [no description]. +// SkipWaitingParams are the parameters of the command +// ServiceWorker.skipWaiting. type SkipWaitingParams struct { ScopeURL string `json:"scopeURL"` } @@ -163,22 +80,10 @@ type SkipWaitingParams struct { // SkipWaiting [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-skipWaiting -// -// parameters: -// -// scopeURL -func SkipWaiting(scopeURL string) *SkipWaitingParams { - return &SkipWaitingParams{ - ScopeURL: scopeURL, - } -} +var SkipWaiting = cdp.Command[SkipWaitingParams, cdp.Empty]{Method: CommandSkipWaiting} -// Do executes ServiceWorker.skipWaiting against the provided context. -func (p *SkipWaitingParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSkipWaiting, p, nil) -} - -// StartWorkerParams [no description]. +// StartWorkerParams are the parameters of the command +// ServiceWorker.startWorker. type StartWorkerParams struct { ScopeURL string `json:"scopeURL"` } @@ -186,37 +91,15 @@ type StartWorkerParams struct { // StartWorker [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-startWorker -// -// parameters: -// -// scopeURL -func StartWorker(scopeURL string) *StartWorkerParams { - return &StartWorkerParams{ - ScopeURL: scopeURL, - } -} - -// Do executes ServiceWorker.startWorker against the provided context. -func (p *StartWorkerParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStartWorker, p, nil) -} - -// StopAllWorkersParams [no description]. -type StopAllWorkersParams struct{} +var StartWorker = cdp.Command[StartWorkerParams, cdp.Empty]{Method: CommandStartWorker} // StopAllWorkers [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-stopAllWorkers -func StopAllWorkers() *StopAllWorkersParams { - return &StopAllWorkersParams{} -} - -// Do executes ServiceWorker.stopAllWorkers against the provided context. -func (p *StopAllWorkersParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStopAllWorkers, nil, nil) -} +var StopAllWorkers = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandStopAllWorkers} -// StopWorkerParams [no description]. +// StopWorkerParams are the parameters of the command +// ServiceWorker.stopWorker. type StopWorkerParams struct { VersionID string `json:"versionId"` } @@ -224,22 +107,10 @@ type StopWorkerParams struct { // StopWorker [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-stopWorker -// -// parameters: -// -// versionID -func StopWorker(versionID string) *StopWorkerParams { - return &StopWorkerParams{ - VersionID: versionID, - } -} - -// Do executes ServiceWorker.stopWorker against the provided context. -func (p *StopWorkerParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStopWorker, p, nil) -} +var StopWorker = cdp.Command[StopWorkerParams, cdp.Empty]{Method: CommandStopWorker} -// UnregisterParams [no description]. +// UnregisterParams are the parameters of the command +// ServiceWorker.unregister. type UnregisterParams struct { ScopeURL string `json:"scopeURL"` } @@ -247,22 +118,10 @@ type UnregisterParams struct { // Unregister [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-unregister -// -// parameters: -// -// scopeURL -func Unregister(scopeURL string) *UnregisterParams { - return &UnregisterParams{ - ScopeURL: scopeURL, - } -} +var Unregister = cdp.Command[UnregisterParams, cdp.Empty]{Method: CommandUnregister} -// Do executes ServiceWorker.unregister against the provided context. -func (p *UnregisterParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandUnregister, p, nil) -} - -// UpdateRegistrationParams [no description]. +// UpdateRegistrationParams are the parameters of the command +// ServiceWorker.updateRegistration. type UpdateRegistrationParams struct { ScopeURL string `json:"scopeURL"` } @@ -270,20 +129,22 @@ type UpdateRegistrationParams struct { // UpdateRegistration [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-updateRegistration +var UpdateRegistration = cdp.Command[UpdateRegistrationParams, cdp.Empty]{Method: CommandUpdateRegistration} + +// WorkerErrorReported [no description]. // -// parameters: +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#event-workerErrorReported +var WorkerErrorReported = cdp.Event[EventWorkerErrorReported]{Method: "ServiceWorker.workerErrorReported"} + +// WorkerRegistrationUpdated [no description]. // -// scopeURL -func UpdateRegistration(scopeURL string) *UpdateRegistrationParams { - return &UpdateRegistrationParams{ - ScopeURL: scopeURL, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#event-workerRegistrationUpdated +var WorkerRegistrationUpdated = cdp.Event[EventWorkerRegistrationUpdated]{Method: "ServiceWorker.workerRegistrationUpdated"} -// Do executes ServiceWorker.updateRegistration against the provided context. -func (p *UpdateRegistrationParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandUpdateRegistration, p, nil) -} +// WorkerVersionUpdated [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#event-workerVersionUpdated +var WorkerVersionUpdated = cdp.Event[EventWorkerVersionUpdated]{Method: "ServiceWorker.workerVersionUpdated"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/serviceworker/types.go b/vendor/github.com/chromedp/cdproto/serviceworker/types.go index da6a392ee..d90fd4c88 100644 --- a/vendor/github.com/chromedp/cdproto/serviceworker/types.go +++ b/vendor/github.com/chromedp/cdproto/serviceworker/types.go @@ -1,11 +1,8 @@ -package serviceworker +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package serviceworker import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/target" ) @@ -46,26 +43,6 @@ const ( VersionRunningStatusStopping VersionRunningStatus = "stopping" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *VersionRunningStatus) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch VersionRunningStatus(s) { - case VersionRunningStatusStopped: - *t = VersionRunningStatusStopped - case VersionRunningStatusStarting: - *t = VersionRunningStatusStarting - case VersionRunningStatusRunning: - *t = VersionRunningStatusRunning - case VersionRunningStatusStopping: - *t = VersionRunningStatusStopping - default: - return fmt.Errorf("unknown VersionRunningStatus value: %v", s) - } - return nil -} - // VersionStatus [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#type-ServiceWorkerVersionStatus @@ -86,28 +63,67 @@ const ( VersionStatusRedundant VersionStatus = "redundant" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *VersionStatus) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch VersionStatus(s) { - case VersionStatusNew: - *t = VersionStatusNew - case VersionStatusInstalling: - *t = VersionStatusInstalling - case VersionStatusInstalled: - *t = VersionStatusInstalled - case VersionStatusActivating: - *t = VersionStatusActivating - case VersionStatusActivated: - *t = VersionStatusActivated - case VersionStatusRedundant: - *t = VersionStatusRedundant - default: - return fmt.Errorf("unknown VersionStatus value: %v", s) - } - return nil +// RouterCondition mostly corresponds to RouterCondition in ServiceWorker +// spec (https://www.w3.org/TR/service-workers/#dictdef-routercondition). +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#type-ServiceWorkerRouterCondition +type RouterCondition struct { + URLPattern string `json:"urlPattern,omitempty,omitzero"` // Plain text, or JSON serialization of URLPatternInit or URLPattern + RequestMethod string `json:"requestMethod,omitempty,omitzero"` + RequestMode string `json:"requestMode,omitempty,omitzero"` + RequestDestination string `json:"requestDestination,omitempty,omitzero"` + RunningStatus VersionRunningStatus `json:"runningStatus,omitempty,omitzero"` + Or []*RouterCondition `json:"or,omitempty,omitzero"` + Not *RouterCondition `json:"not,omitempty,omitzero"` +} + +// RouterSourceType [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#type-ServiceWorkerRouterSourceType +type RouterSourceType string + +// String returns the RouterSourceType as string value. +func (t RouterSourceType) String() string { + return string(t) +} + +// RouterSourceType values. +const ( + RouterSourceTypeCache RouterSourceType = "cache" + RouterSourceTypeFetchEvent RouterSourceType = "fetchEvent" + RouterSourceTypeNetwork RouterSourceType = "network" + RouterSourceTypeRaceNetworkAndFetchHandler RouterSourceType = "raceNetworkAndFetchHandler" + RouterSourceTypeRaceNetworkAndCache RouterSourceType = "raceNetworkAndCache" + RouterSourceTypeSourceDict RouterSourceType = "sourceDict" +) + +// RouterSourceDict +// https://www.w3.org/TR/service-workers/#dictdef-routersourcedict. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#type-ServiceWorkerRouterSourceDict +type RouterSourceDict struct { + CacheName string `json:"cacheName"` +} + +// RouterSource corresponds to RouterSource in the spec while the +// representation is different as follows. +// (https://www.w3.org/TR/service-workers/#typedefdef-routersource) - +// RouterSourceEnum: type equals cache, sourceDict is null. - RouterSourceDict: +// type equals sourceDict, sourceDict has valid value. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#type-ServiceWorkerRouterSource +type RouterSource struct { + Type RouterSourceType `json:"type"` + SourceDict *RouterSourceDict `json:"sourceDict,omitempty,omitzero"` // Non-empty iff type equals "sourceDict". +} + +// RouterRule [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#type-ServiceWorkerRouterRule +type RouterRule struct { + Condition *RouterCondition `json:"condition"` + Source *RouterSource `json:"source"` + ID int64 `json:"id"` // Rule ID assigned by the browser. Unique within each ServiceWorkerVersion. } // Version serviceWorker version. @@ -123,7 +139,8 @@ type Version struct { ScriptResponseTime float64 `json:"scriptResponseTime,omitempty,omitzero"` // The time at which the response headers of the main script were received from the server. For cached script it is the last time the cache entry was validated. ControlledClients []target.ID `json:"controlledClients,omitempty,omitzero"` TargetID target.ID `json:"targetId,omitempty,omitzero"` - RouterRules string `json:"routerRules,omitempty,omitzero"` + RouterRules string `json:"routerRules,omitempty,omitzero"` // Migration to typedRouterRules is in progress. The browser sends either routerRules or typedRouterRules. TODO(crbug.com/540469610): Remove routerRules after the migration. + TypedRouterRules []*RouterRule `json:"typedRouterRules,omitempty,omitzero"` } // ErrorMessage serviceWorker error message. diff --git a/vendor/github.com/chromedp/cdproto/smartcardemulation/events.go b/vendor/github.com/chromedp/cdproto/smartcardemulation/events.go index bb508c697..a63387114 100644 --- a/vendor/github.com/chromedp/cdproto/smartcardemulation/events.go +++ b/vendor/github.com/chromedp/cdproto/smartcardemulation/events.go @@ -1,6 +1,6 @@ -package smartcardemulation +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package smartcardemulation // EventEstablishContextRequested fired when |SCardEstablishContext| is // called. This maps to: PC/SC Lite: @@ -101,7 +101,7 @@ type EventDisconnectRequested struct { type EventTransmitRequested struct { RequestID string `json:"requestId"` Handle int64 `json:"handle"` - Data string `json:"data"` + Data []byte `json:"data"` Protocol Protocol `json:"protocol,omitempty,omitzero"` } @@ -116,7 +116,7 @@ type EventControlRequested struct { RequestID string `json:"requestId"` Handle int64 `json:"handle"` ControlCode int64 `json:"controlCode"` - Data string `json:"data"` + Data []byte `json:"data"` } // EventGetAttribRequested fired when |SCardGetAttrib| is called. This maps @@ -143,7 +143,7 @@ type EventSetAttribRequested struct { RequestID string `json:"requestId"` Handle int64 `json:"handle"` AttribID int64 `json:"attribId"` - Data string `json:"data"` + Data []byte `json:"data"` } // EventStatusRequested fired when |SCardStatus| is called. This maps to: diff --git a/vendor/github.com/chromedp/cdproto/smartcardemulation/smartcardemulation.go b/vendor/github.com/chromedp/cdproto/smartcardemulation/smartcardemulation.go index fa16561e0..c6c97418a 100644 --- a/vendor/github.com/chromedp/cdproto/smartcardemulation/smartcardemulation.go +++ b/vendor/github.com/chromedp/cdproto/smartcardemulation/smartcardemulation.go @@ -1,52 +1,27 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package smartcardemulation provides the Chrome DevTools Protocol // commands, types, and events for the SmartCardEmulation domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package smartcardemulation -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// EnableParams enables the |SmartCardEmulation| domain. -type EnableParams struct{} - // Enable enables the |SmartCardEmulation| domain. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} - -// Do executes SmartCardEmulation.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) -} - -// DisableParams disables the |SmartCardEmulation| domain. -type DisableParams struct{} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} // Disable disables the |SmartCardEmulation| domain. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} -// Do executes SmartCardEmulation.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// ReportEstablishContextResultParams reports the successful result of a -// |SCardEstablishContext| call. This maps to: PC/SC Lite: -// https://pcsclite.apdu.fr/api/group__API.html#gaa1b8970169fd4883a6dc4a8f43f19b67 -// Microsoft: -// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardestablishcontext. +// ReportEstablishContextResultParams are the parameters of the command +// SmartCardEmulation.reportEstablishContextResult. type ReportEstablishContextResultParams struct { RequestID string `json:"requestId"` ContextID int64 `json:"contextId"` @@ -59,28 +34,10 @@ type ReportEstablishContextResultParams struct { // https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardestablishcontext. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#method-reportEstablishContextResult -// -// parameters: -// -// requestID -// contextID -func ReportEstablishContextResult(requestID string, contextID int64) *ReportEstablishContextResultParams { - return &ReportEstablishContextResultParams{ - RequestID: requestID, - ContextID: contextID, - } -} +var ReportEstablishContextResult = cdp.Command[ReportEstablishContextResultParams, cdp.Empty]{Method: CommandReportEstablishContextResult} -// Do executes SmartCardEmulation.reportEstablishContextResult against the provided context. -func (p *ReportEstablishContextResultParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandReportEstablishContextResult, p, nil) -} - -// ReportReleaseContextResultParams reports the successful result of a -// |SCardReleaseContext| call. This maps to: PC/SC Lite: -// https://pcsclite.apdu.fr/api/group__API.html#ga6aabcba7744c5c9419fdd6404f73a934 -// Microsoft: -// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardreleasecontext. +// ReportReleaseContextResultParams are the parameters of the command +// SmartCardEmulation.reportReleaseContextResult. type ReportReleaseContextResultParams struct { RequestID string `json:"requestId"` } @@ -92,26 +49,10 @@ type ReportReleaseContextResultParams struct { // https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardreleasecontext. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#method-reportReleaseContextResult -// -// parameters: -// -// requestID -func ReportReleaseContextResult(requestID string) *ReportReleaseContextResultParams { - return &ReportReleaseContextResultParams{ - RequestID: requestID, - } -} +var ReportReleaseContextResult = cdp.Command[ReportReleaseContextResultParams, cdp.Empty]{Method: CommandReportReleaseContextResult} -// Do executes SmartCardEmulation.reportReleaseContextResult against the provided context. -func (p *ReportReleaseContextResultParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandReportReleaseContextResult, p, nil) -} - -// ReportListReadersResultParams reports the successful result of a -// |SCardListReaders| call. This maps to: PC/SC Lite: -// https://pcsclite.apdu.fr/api/group__API.html#ga93b07815789b3cf2629d439ecf20f0d9 -// Microsoft: -// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardlistreadersa. +// ReportListReadersResultParams are the parameters of the command +// SmartCardEmulation.reportListReadersResult. type ReportListReadersResultParams struct { RequestID string `json:"requestId"` Readers []string `json:"readers"` @@ -124,28 +65,10 @@ type ReportListReadersResultParams struct { // https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardlistreadersa. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#method-reportListReadersResult -// -// parameters: -// -// requestID -// readers -func ReportListReadersResult(requestID string, readers []string) *ReportListReadersResultParams { - return &ReportListReadersResultParams{ - RequestID: requestID, - Readers: readers, - } -} +var ReportListReadersResult = cdp.Command[ReportListReadersResultParams, cdp.Empty]{Method: CommandReportListReadersResult} -// Do executes SmartCardEmulation.reportListReadersResult against the provided context. -func (p *ReportListReadersResultParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandReportListReadersResult, p, nil) -} - -// ReportGetStatusChangeResultParams reports the successful result of a -// |SCardGetStatusChange| call. This maps to: PC/SC Lite: -// https://pcsclite.apdu.fr/api/group__API.html#ga33247d5d1257d59e55647c3bb717db24 -// Microsoft: -// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardgetstatuschangea. +// ReportGetStatusChangeResultParams are the parameters of the command +// SmartCardEmulation.reportGetStatusChangeResult. type ReportGetStatusChangeResultParams struct { RequestID string `json:"requestId"` ReaderStates []*ReaderStateOut `json:"readerStates"` @@ -158,29 +81,10 @@ type ReportGetStatusChangeResultParams struct { // https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardgetstatuschangea. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#method-reportGetStatusChangeResult -// -// parameters: -// -// requestID -// readerStates -func ReportGetStatusChangeResult(requestID string, readerStates []*ReaderStateOut) *ReportGetStatusChangeResultParams { - return &ReportGetStatusChangeResultParams{ - RequestID: requestID, - ReaderStates: readerStates, - } -} - -// Do executes SmartCardEmulation.reportGetStatusChangeResult against the provided context. -func (p *ReportGetStatusChangeResultParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandReportGetStatusChangeResult, p, nil) -} +var ReportGetStatusChangeResult = cdp.Command[ReportGetStatusChangeResultParams, cdp.Empty]{Method: CommandReportGetStatusChangeResult} -// ReportBeginTransactionResultParams reports the result of a -// |SCardBeginTransaction| call. On success, this creates a new transaction -// object. This maps to: PC/SC Lite: -// https://pcsclite.apdu.fr/api/group__API.html#gaddb835dce01a0da1d6ca02d33ee7d861 -// Microsoft: -// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardbegintransaction. +// ReportBeginTransactionResultParams are the parameters of the command +// SmartCardEmulation.reportBeginTransactionResult. type ReportBeginTransactionResultParams struct { RequestID string `json:"requestId"` Handle int64 `json:"handle"` @@ -194,42 +98,10 @@ type ReportBeginTransactionResultParams struct { // https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardbegintransaction. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#method-reportBeginTransactionResult -// -// parameters: -// -// requestID -// handle -func ReportBeginTransactionResult(requestID string, handle int64) *ReportBeginTransactionResultParams { - return &ReportBeginTransactionResultParams{ - RequestID: requestID, - Handle: handle, - } -} - -// Do executes SmartCardEmulation.reportBeginTransactionResult against the provided context. -func (p *ReportBeginTransactionResultParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandReportBeginTransactionResult, p, nil) -} +var ReportBeginTransactionResult = cdp.Command[ReportBeginTransactionResultParams, cdp.Empty]{Method: CommandReportBeginTransactionResult} -// ReportPlainResultParams reports the successful result of a call that -// returns only a result code. Used for: |SCardCancel|, |SCardDisconnect|, -// |SCardSetAttrib|, |SCardEndTransaction|. This maps to: 1. SCardCancel PC/SC -// Lite: -// https://pcsclite.apdu.fr/api/group__API.html#gaacbbc0c6d6c0cbbeb4f4debf6fbeeee6 -// Microsoft: -// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardcancel -// 2. SCardDisconnect PC/SC Lite: -// https://pcsclite.apdu.fr/api/group__API.html#ga4be198045c73ec0deb79e66c0ca1738a -// Microsoft: -// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scarddisconnect -// 3. SCardSetAttrib PC/SC Lite: -// https://pcsclite.apdu.fr/api/group__API.html#ga060f0038a4ddfd5dd2b8fadf3c3a2e4f -// Microsoft: -// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardsetattrib -// 4. SCardEndTransaction PC/SC Lite: -// https://pcsclite.apdu.fr/api/group__API.html#gae8742473b404363e5c587f570d7e2f3b -// Microsoft: -// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardendtransaction. +// ReportPlainResultParams are the parameters of the command +// SmartCardEmulation.reportPlainResult. type ReportPlainResultParams struct { RequestID string `json:"requestId"` } @@ -255,26 +127,10 @@ type ReportPlainResultParams struct { // https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardendtransaction. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#method-reportPlainResult -// -// parameters: -// -// requestID -func ReportPlainResult(requestID string) *ReportPlainResultParams { - return &ReportPlainResultParams{ - RequestID: requestID, - } -} +var ReportPlainResult = cdp.Command[ReportPlainResultParams, cdp.Empty]{Method: CommandReportPlainResult} -// Do executes SmartCardEmulation.reportPlainResult against the provided context. -func (p *ReportPlainResultParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandReportPlainResult, p, nil) -} - -// ReportConnectResultParams reports the successful result of a -// |SCardConnect| call. This maps to: PC/SC Lite: -// https://pcsclite.apdu.fr/api/group__API.html#ga4e515829752e0a8dbc4d630696a8d6a5 -// Microsoft: -// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardconnecta. +// ReportConnectResultParams are the parameters of the command +// SmartCardEmulation.reportConnectResult. type ReportConnectResultParams struct { RequestID string `json:"requestId"` Handle int64 `json:"handle"` @@ -288,46 +144,13 @@ type ReportConnectResultParams struct { // https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardconnecta. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#method-reportConnectResult -// -// parameters: -// -// requestID -// handle -func ReportConnectResult(requestID string, handle int64) *ReportConnectResultParams { - return &ReportConnectResultParams{ - RequestID: requestID, - Handle: handle, - } -} - -// WithActiveProtocol [no description]. -func (p ReportConnectResultParams) WithActiveProtocol(activeProtocol Protocol) *ReportConnectResultParams { - p.ActiveProtocol = activeProtocol - return &p -} - -// Do executes SmartCardEmulation.reportConnectResult against the provided context. -func (p *ReportConnectResultParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandReportConnectResult, p, nil) -} +var ReportConnectResult = cdp.Command[ReportConnectResultParams, cdp.Empty]{Method: CommandReportConnectResult} -// ReportDataResultParams reports the successful result of a call that sends -// back data on success. Used for |SCardTransmit|, |SCardControl|, and -// |SCardGetAttrib|. This maps to: 1. SCardTransmit PC/SC Lite: -// https://pcsclite.apdu.fr/api/group__API.html#ga9a2d77242a271310269065e64633ab99 -// Microsoft: -// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardtransmit -// 2. SCardControl PC/SC Lite: -// https://pcsclite.apdu.fr/api/group__API.html#gac3454d4657110fd7f753b2d3d8f4e32f -// Microsoft: -// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardcontrol -// 3. SCardGetAttrib PC/SC Lite: -// https://pcsclite.apdu.fr/api/group__API.html#gaacfec51917255b7a25b94c5104961602 -// Microsoft: -// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardgetattrib. +// ReportDataResultParams are the parameters of the command +// SmartCardEmulation.reportDataResult. type ReportDataResultParams struct { RequestID string `json:"requestId"` - Data string `json:"data"` + Data []byte `json:"data"` } // ReportDataResult reports the successful result of a call that sends back @@ -346,33 +169,15 @@ type ReportDataResultParams struct { // https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardgetattrib. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#method-reportDataResult -// -// parameters: -// -// requestID -// data -func ReportDataResult(requestID string, data string) *ReportDataResultParams { - return &ReportDataResultParams{ - RequestID: requestID, - Data: data, - } -} - -// Do executes SmartCardEmulation.reportDataResult against the provided context. -func (p *ReportDataResultParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandReportDataResult, p, nil) -} +var ReportDataResult = cdp.Command[ReportDataResultParams, cdp.Empty]{Method: CommandReportDataResult} -// ReportStatusResultParams reports the successful result of a |SCardStatus| -// call. This maps to: PC/SC Lite: -// https://pcsclite.apdu.fr/api/group__API.html#gae49c3c894ad7ac12a5b896bde70d0382 -// Microsoft: -// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardstatusa. +// ReportStatusResultParams are the parameters of the command +// SmartCardEmulation.reportStatusResult. type ReportStatusResultParams struct { RequestID string `json:"requestId"` ReaderName string `json:"readerName"` State ConnectionState `json:"state"` - Atr string `json:"atr"` + Atr []byte `json:"atr"` Protocol Protocol `json:"protocol,omitempty,omitzero"` } @@ -383,34 +188,10 @@ type ReportStatusResultParams struct { // https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardstatusa. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#method-reportStatusResult -// -// parameters: -// -// requestID -// readerName -// state -// atr -func ReportStatusResult(requestID string, readerName string, state ConnectionState, atr string) *ReportStatusResultParams { - return &ReportStatusResultParams{ - RequestID: requestID, - ReaderName: readerName, - State: state, - Atr: atr, - } -} - -// WithProtocol [no description]. -func (p ReportStatusResultParams) WithProtocol(protocol Protocol) *ReportStatusResultParams { - p.Protocol = protocol - return &p -} +var ReportStatusResult = cdp.Command[ReportStatusResultParams, cdp.Empty]{Method: CommandReportStatusResult} -// Do executes SmartCardEmulation.reportStatusResult against the provided context. -func (p *ReportStatusResultParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandReportStatusResult, p, nil) -} - -// ReportErrorParams reports an error result for the given request. +// ReportErrorParams are the parameters of the command +// SmartCardEmulation.reportError. type ReportErrorParams struct { RequestID string `json:"requestId"` ResultCode ResultCode `json:"resultCode"` @@ -419,22 +200,133 @@ type ReportErrorParams struct { // ReportError reports an error result for the given request. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#method-reportError +var ReportError = cdp.Command[ReportErrorParams, cdp.Empty]{Method: CommandReportError} + +// EstablishContextRequested fired when |SCardEstablishContext| is called. +// This maps to: PC/SC Lite: +// https://pcsclite.apdu.fr/api/group__API.html#gaa1b8970169fd4883a6dc4a8f43f19b67 +// Microsoft: +// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardestablishcontext. // -// parameters: +// See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#event-establishContextRequested +var EstablishContextRequested = cdp.Event[EventEstablishContextRequested]{Method: "SmartCardEmulation.establishContextRequested"} + +// ReleaseContextRequested fired when |SCardReleaseContext| is called. This +// maps to: PC/SC Lite: +// https://pcsclite.apdu.fr/api/group__API.html#ga6aabcba7744c5c9419fdd6404f73a934 +// Microsoft: +// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardreleasecontext. // -// requestID -// resultCode -func ReportError(requestID string, resultCode ResultCode) *ReportErrorParams { - return &ReportErrorParams{ - RequestID: requestID, - ResultCode: resultCode, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#event-releaseContextRequested +var ReleaseContextRequested = cdp.Event[EventReleaseContextRequested]{Method: "SmartCardEmulation.releaseContextRequested"} -// Do executes SmartCardEmulation.reportError against the provided context. -func (p *ReportErrorParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandReportError, p, nil) -} +// ListReadersRequested fired when |SCardListReaders| is called. This maps +// to: PC/SC Lite: +// https://pcsclite.apdu.fr/api/group__API.html#ga93b07815789b3cf2629d439ecf20f0d9 +// Microsoft: +// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardlistreadersa. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#event-listReadersRequested +var ListReadersRequested = cdp.Event[EventListReadersRequested]{Method: "SmartCardEmulation.listReadersRequested"} + +// GetStatusChangeRequested fired when |SCardGetStatusChange| is called. +// Timeout is specified in milliseconds. This maps to: PC/SC Lite: +// https://pcsclite.apdu.fr/api/group__API.html#ga33247d5d1257d59e55647c3bb717db24 +// Microsoft: +// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardgetstatuschangea. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#event-getStatusChangeRequested +var GetStatusChangeRequested = cdp.Event[EventGetStatusChangeRequested]{Method: "SmartCardEmulation.getStatusChangeRequested"} + +// CancelRequested fired when |SCardCancel| is called. This maps to: PC/SC +// Lite: +// https://pcsclite.apdu.fr/api/group__API.html#gaacbbc0c6d6c0cbbeb4f4debf6fbeeee6 +// Microsoft: +// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardcancel. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#event-cancelRequested +var CancelRequested = cdp.Event[EventCancelRequested]{Method: "SmartCardEmulation.cancelRequested"} + +// ConnectRequested fired when |SCardConnect| is called. This maps to: PC/SC +// Lite: +// https://pcsclite.apdu.fr/api/group__API.html#ga4e515829752e0a8dbc4d630696a8d6a5 +// Microsoft: +// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardconnecta. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#event-connectRequested +var ConnectRequested = cdp.Event[EventConnectRequested]{Method: "SmartCardEmulation.connectRequested"} + +// DisconnectRequested fired when |SCardDisconnect| is called. This maps to: +// PC/SC Lite: +// https://pcsclite.apdu.fr/api/group__API.html#ga4be198045c73ec0deb79e66c0ca1738a +// Microsoft: +// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scarddisconnect. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#event-disconnectRequested +var DisconnectRequested = cdp.Event[EventDisconnectRequested]{Method: "SmartCardEmulation.disconnectRequested"} + +// TransmitRequested fired when |SCardTransmit| is called. This maps to: +// PC/SC Lite: +// https://pcsclite.apdu.fr/api/group__API.html#ga9a2d77242a271310269065e64633ab99 +// Microsoft: +// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardtransmit. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#event-transmitRequested +var TransmitRequested = cdp.Event[EventTransmitRequested]{Method: "SmartCardEmulation.transmitRequested"} + +// ControlRequested fired when |SCardControl| is called. This maps to: PC/SC +// Lite: +// https://pcsclite.apdu.fr/api/group__API.html#gac3454d4657110fd7f753b2d3d8f4e32f +// Microsoft: +// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardcontrol. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#event-controlRequested +var ControlRequested = cdp.Event[EventControlRequested]{Method: "SmartCardEmulation.controlRequested"} + +// GetAttribRequested fired when |SCardGetAttrib| is called. This maps to: +// PC/SC Lite: +// https://pcsclite.apdu.fr/api/group__API.html#gaacfec51917255b7a25b94c5104961602 +// Microsoft: +// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardgetattrib. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#event-getAttribRequested +var GetAttribRequested = cdp.Event[EventGetAttribRequested]{Method: "SmartCardEmulation.getAttribRequested"} + +// SetAttribRequested fired when |SCardSetAttrib| is called. This maps to: +// PC/SC Lite: +// https://pcsclite.apdu.fr/api/group__API.html#ga060f0038a4ddfd5dd2b8fadf3c3a2e4f +// Microsoft: +// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardsetattrib. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#event-setAttribRequested +var SetAttribRequested = cdp.Event[EventSetAttribRequested]{Method: "SmartCardEmulation.setAttribRequested"} + +// StatusRequested fired when |SCardStatus| is called. This maps to: PC/SC +// Lite: +// https://pcsclite.apdu.fr/api/group__API.html#gae49c3c894ad7ac12a5b896bde70d0382 +// Microsoft: +// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardstatusa. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#event-statusRequested +var StatusRequested = cdp.Event[EventStatusRequested]{Method: "SmartCardEmulation.statusRequested"} + +// BeginTransactionRequested fired when |SCardBeginTransaction| is called. +// This maps to: PC/SC Lite: +// https://pcsclite.apdu.fr/api/group__API.html#gaddb835dce01a0da1d6ca02d33ee7d861 +// Microsoft: +// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardbegintransaction. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#event-beginTransactionRequested +var BeginTransactionRequested = cdp.Event[EventBeginTransactionRequested]{Method: "SmartCardEmulation.beginTransactionRequested"} + +// EndTransactionRequested fired when |SCardEndTransaction| is called. This +// maps to: PC/SC Lite: +// https://pcsclite.apdu.fr/api/group__API.html#gae8742473b404363e5c587f570d7e2f3b +// Microsoft: +// https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardendtransaction. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#event-endTransactionRequested +var EndTransactionRequested = cdp.Event[EventEndTransactionRequested]{Method: "SmartCardEmulation.endTransactionRequested"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/smartcardemulation/types.go b/vendor/github.com/chromedp/cdproto/smartcardemulation/types.go index 3636fe0a3..3fcd4d112 100644 --- a/vendor/github.com/chromedp/cdproto/smartcardemulation/types.go +++ b/vendor/github.com/chromedp/cdproto/smartcardemulation/types.go @@ -1,11 +1,6 @@ -package smartcardemulation - -import ( - "fmt" - "strings" -) +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package smartcardemulation // ResultCode indicates the PC/SC error code. This maps to: PC/SC Lite: // https://pcsclite.apdu.fr/api/group__ErrorCodes.html Microsoft: @@ -55,82 +50,6 @@ const ( ResultCodeUnknown ResultCode = "unknown" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ResultCode) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ResultCode(s) { - case ResultCodeSuccess: - *t = ResultCodeSuccess - case ResultCodeRemovedCard: - *t = ResultCodeRemovedCard - case ResultCodeResetCard: - *t = ResultCodeResetCard - case ResultCodeUnpoweredCard: - *t = ResultCodeUnpoweredCard - case ResultCodeUnresponsiveCard: - *t = ResultCodeUnresponsiveCard - case ResultCodeUnsupportedCard: - *t = ResultCodeUnsupportedCard - case ResultCodeReaderUnavailable: - *t = ResultCodeReaderUnavailable - case ResultCodeSharingViolation: - *t = ResultCodeSharingViolation - case ResultCodeNotTransacted: - *t = ResultCodeNotTransacted - case ResultCodeNoSmartcard: - *t = ResultCodeNoSmartcard - case ResultCodeProtoMismatch: - *t = ResultCodeProtoMismatch - case ResultCodeSystemCancelled: - *t = ResultCodeSystemCancelled - case ResultCodeNotReady: - *t = ResultCodeNotReady - case ResultCodeCancelled: - *t = ResultCodeCancelled - case ResultCodeInsufficientBuffer: - *t = ResultCodeInsufficientBuffer - case ResultCodeInvalidHandle: - *t = ResultCodeInvalidHandle - case ResultCodeInvalidParameter: - *t = ResultCodeInvalidParameter - case ResultCodeInvalidValue: - *t = ResultCodeInvalidValue - case ResultCodeNoMemory: - *t = ResultCodeNoMemory - case ResultCodeTimeout: - *t = ResultCodeTimeout - case ResultCodeUnknownReader: - *t = ResultCodeUnknownReader - case ResultCodeUnsupportedFeature: - *t = ResultCodeUnsupportedFeature - case ResultCodeNoReadersAvailable: - *t = ResultCodeNoReadersAvailable - case ResultCodeServiceStopped: - *t = ResultCodeServiceStopped - case ResultCodeNoService: - *t = ResultCodeNoService - case ResultCodeCommError: - *t = ResultCodeCommError - case ResultCodeInternalError: - *t = ResultCodeInternalError - case ResultCodeServerTooBusy: - *t = ResultCodeServerTooBusy - case ResultCodeUnexpected: - *t = ResultCodeUnexpected - case ResultCodeShutdown: - *t = ResultCodeShutdown - case ResultCodeUnknownCard: - *t = ResultCodeUnknownCard - case ResultCodeUnknown: - *t = ResultCodeUnknown - default: - return fmt.Errorf("unknown ResultCode value: %v", s) - } - return nil -} - // ShareMode maps to the |SCARD_SHARE_*| values. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#type-ShareMode @@ -148,24 +67,6 @@ const ( ShareModeDirect ShareMode = "direct" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ShareMode) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ShareMode(s) { - case ShareModeShared: - *t = ShareModeShared - case ShareModeExclusive: - *t = ShareModeExclusive - case ShareModeDirect: - *t = ShareModeDirect - default: - return fmt.Errorf("unknown ShareMode value: %v", s) - } - return nil -} - // Disposition indicates what the reader should do with the card. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#type-Disposition @@ -184,26 +85,6 @@ const ( DispositionEjectCard Disposition = "eject-card" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *Disposition) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch Disposition(s) { - case DispositionLeaveCard: - *t = DispositionLeaveCard - case DispositionResetCard: - *t = DispositionResetCard - case DispositionUnpowerCard: - *t = DispositionUnpowerCard - case DispositionEjectCard: - *t = DispositionEjectCard - default: - return fmt.Errorf("unknown Disposition value: %v", s) - } - return nil -} - // ConnectionState maps to |SCARD_*| connection state values. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#type-ConnectionState @@ -224,30 +105,6 @@ const ( ConnectionStateSpecific ConnectionState = "specific" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ConnectionState) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ConnectionState(s) { - case ConnectionStateAbsent: - *t = ConnectionStateAbsent - case ConnectionStatePresent: - *t = ConnectionStatePresent - case ConnectionStateSwallowed: - *t = ConnectionStateSwallowed - case ConnectionStatePowered: - *t = ConnectionStatePowered - case ConnectionStateNegotiable: - *t = ConnectionStateNegotiable - case ConnectionStateSpecific: - *t = ConnectionStateSpecific - default: - return fmt.Errorf("unknown ConnectionState value: %v", s) - } - return nil -} - // ReaderStateFlags maps to the |SCARD_STATE_*| flags. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#type-ReaderStateFlags @@ -291,24 +148,6 @@ const ( ProtocolRaw Protocol = "raw" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *Protocol) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch Protocol(s) { - case ProtocolT0: - *t = ProtocolT0 - case ProtocolT1: - *t = ProtocolT1 - case ProtocolRaw: - *t = ProtocolRaw - default: - return fmt.Errorf("unknown Protocol value: %v", s) - } - return nil -} - // ReaderStateIn [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SmartCardEmulation#type-ReaderStateIn @@ -325,5 +164,5 @@ type ReaderStateOut struct { Reader string `json:"reader"` EventState *ReaderStateFlags `json:"eventState"` EventCount int64 `json:"eventCount"` - Atr string `json:"atr"` + Atr []byte `json:"atr"` } diff --git a/vendor/github.com/chromedp/cdproto/storage/events.go b/vendor/github.com/chromedp/cdproto/storage/events.go index c714552b4..b31f7f672 100644 --- a/vendor/github.com/chromedp/cdproto/storage/events.go +++ b/vendor/github.com/chromedp/cdproto/storage/events.go @@ -1,11 +1,6 @@ -package storage - -// Code generated by cdproto-gen. DO NOT EDIT. +// Code generated by pdlgen. DO NOT EDIT. -import ( - "github.com/chromedp/cdproto/cdp" - "github.com/chromedp/cdproto/target" -) +package storage // EventCacheStorageContentUpdated a cache's contents have been modified. // @@ -48,35 +43,6 @@ type EventIndexedDBListUpdated struct { BucketID string `json:"bucketId"` // Storage bucket to update. } -// EventSharedStorageAccessed shared storage was accessed by the associated -// page. The following parameters are included in all events. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#event-sharedStorageAccessed -type EventSharedStorageAccessed struct { - AccessTime *cdp.TimeSinceEpoch `json:"accessTime"` // Time of the access. - Scope SharedStorageAccessScope `json:"scope"` // Enum value indicating the access scope. - Method SharedStorageAccessMethod `json:"method"` // Enum value indicating the Shared Storage API method invoked. - MainFrameID cdp.FrameID `json:"mainFrameId"` // DevTools Frame Token for the primary frame tree's root. - OwnerOrigin string `json:"ownerOrigin"` // Serialization of the origin owning the Shared Storage data. - OwnerSite string `json:"ownerSite"` // Serialization of the site owning the Shared Storage data. - Params *SharedStorageAccessParams `json:"params"` // The sub-parameters wrapped by params are all optional and their presence/absence depends on type. -} - -// EventSharedStorageWorkletOperationExecutionFinished a shared storage run -// or selectURL operation finished its execution. The following parameters are -// included in all events. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#event-sharedStorageWorkletOperationExecutionFinished -type EventSharedStorageWorkletOperationExecutionFinished struct { - FinishedTime *cdp.TimeSinceEpoch `json:"finishedTime"` // Time that the operation finished. - ExecutionTime int64 `json:"executionTime"` // Time, in microseconds, from start of shared storage JS API call until end of operation execution in the worklet. - Method SharedStorageAccessMethod `json:"method"` // Enum value indicating the Shared Storage API method invoked. - OperationID string `json:"operationId"` // ID of the operation call. - WorkletTargetID target.ID `json:"workletTargetId"` // Hex representation of the DevTools token used as the TargetID for the associated shared storage worklet. - MainFrameID cdp.FrameID `json:"mainFrameId"` // DevTools Frame Token for the primary frame tree's root. - OwnerOrigin string `json:"ownerOrigin"` // Serialization of the origin owning the Shared Storage data. -} - // EventStorageBucketCreatedOrUpdated [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#event-storageBucketCreatedOrUpdated @@ -90,3 +56,9 @@ type EventStorageBucketCreatedOrUpdated struct { type EventStorageBucketDeleted struct { BucketID string `json:"bucketId"` } + +// EventPrivateVerificationTokensUpdated private Verification Tokens have +// been stored or deleted. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#event-privateVerificationTokensUpdated +type EventPrivateVerificationTokensUpdated struct{} diff --git a/vendor/github.com/chromedp/cdproto/storage/storage.go b/vendor/github.com/chromedp/cdproto/storage/storage.go index b6f7c4eaa..c93e8a975 100644 --- a/vendor/github.com/chromedp/cdproto/storage/storage.go +++ b/vendor/github.com/chromedp/cdproto/storage/storage.go @@ -1,63 +1,35 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package storage provides the Chrome DevTools Protocol // commands, types, and events for the Storage domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package storage -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/network" ) -// GetStorageKeyParams returns storage key for the given frame. If no frame -// ID is provided, the storage key of the target executing this command is -// returned. +// GetStorageKeyParams are the parameters of the command +// Storage.getStorageKey. type GetStorageKeyParams struct { FrameID cdp.FrameID `json:"frameId,omitempty,omitzero"` } -// GetStorageKey returns storage key for the given frame. If no frame ID is -// provided, the storage key of the target executing this command is returned. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getStorageKey -// -// parameters: -func GetStorageKey() *GetStorageKeyParams { - return &GetStorageKeyParams{} -} - -// WithFrameID [no description]. -func (p GetStorageKeyParams) WithFrameID(frameID cdp.FrameID) *GetStorageKeyParams { - p.FrameID = frameID - return &p -} - -// GetStorageKeyReturns return values. -type GetStorageKeyReturns struct { +// GetStorageKeyResult is the result of the command Storage.getStorageKey. +type GetStorageKeyResult struct { StorageKey SerializedStorageKey `json:"storageKey,omitempty,omitzero"` } -// Do executes Storage.getStorageKey against the provided context. -// -// returns: +// GetStorageKey returns storage key for the given frame. If no frame ID is +// provided, the storage key of the target executing this command is returned. // -// storageKey -func (p *GetStorageKeyParams) Do(ctx context.Context) (storageKey SerializedStorageKey, err error) { - // execute - var res GetStorageKeyReturns - err = cdp.Execute(ctx, CommandGetStorageKey, p, &res) - if err != nil { - return "", err - } - - return res.StorageKey, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getStorageKey +var GetStorageKey = cdp.Command[GetStorageKeyParams, GetStorageKeyResult]{Method: CommandGetStorageKey} -// ClearDataForOriginParams clears storage for origin. +// ClearDataForOriginParams are the parameters of the command +// Storage.clearDataForOrigin. type ClearDataForOriginParams struct { Origin string `json:"origin"` // Security origin. StorageTypes string `json:"storageTypes"` // Comma separated list of StorageType to clear. @@ -66,24 +38,10 @@ type ClearDataForOriginParams struct { // ClearDataForOrigin clears storage for origin. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-clearDataForOrigin -// -// parameters: -// -// origin - Security origin. -// storageTypes - Comma separated list of StorageType to clear. -func ClearDataForOrigin(origin string, storageTypes string) *ClearDataForOriginParams { - return &ClearDataForOriginParams{ - Origin: origin, - StorageTypes: storageTypes, - } -} +var ClearDataForOrigin = cdp.Command[ClearDataForOriginParams, cdp.Empty]{Method: CommandClearDataForOrigin} -// Do executes Storage.clearDataForOrigin against the provided context. -func (p *ClearDataForOriginParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClearDataForOrigin, p, nil) -} - -// ClearDataForStorageKeyParams clears storage for storage key. +// ClearDataForStorageKeyParams are the parameters of the command +// Storage.clearDataForStorageKey. type ClearDataForStorageKeyParams struct { StorageKey string `json:"storageKey"` // Storage key. StorageTypes string `json:"storageTypes"` // Comma separated list of StorageType to clear. @@ -92,66 +50,24 @@ type ClearDataForStorageKeyParams struct { // ClearDataForStorageKey clears storage for storage key. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-clearDataForStorageKey -// -// parameters: -// -// storageKey - Storage key. -// storageTypes - Comma separated list of StorageType to clear. -func ClearDataForStorageKey(storageKey string, storageTypes string) *ClearDataForStorageKeyParams { - return &ClearDataForStorageKeyParams{ - StorageKey: storageKey, - StorageTypes: storageTypes, - } -} - -// Do executes Storage.clearDataForStorageKey against the provided context. -func (p *ClearDataForStorageKeyParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClearDataForStorageKey, p, nil) -} +var ClearDataForStorageKey = cdp.Command[ClearDataForStorageKeyParams, cdp.Empty]{Method: CommandClearDataForStorageKey} -// GetCookiesParams returns all browser cookies. +// GetCookiesParams are the parameters of the command Storage.getCookies. type GetCookiesParams struct { BrowserContextID cdp.BrowserContextID `json:"browserContextId,omitempty,omitzero"` // Browser context to use when called on the browser endpoint. } -// GetCookies returns all browser cookies. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getCookies -// -// parameters: -func GetCookies() *GetCookiesParams { - return &GetCookiesParams{} -} - -// WithBrowserContextID browser context to use when called on the browser -// endpoint. -func (p GetCookiesParams) WithBrowserContextID(browserContextID cdp.BrowserContextID) *GetCookiesParams { - p.BrowserContextID = browserContextID - return &p -} - -// GetCookiesReturns return values. -type GetCookiesReturns struct { +// GetCookiesResult is the result of the command Storage.getCookies. +type GetCookiesResult struct { Cookies []*network.Cookie `json:"cookies,omitempty,omitzero"` // Array of cookie objects. } -// Do executes Storage.getCookies against the provided context. -// -// returns: +// GetCookies returns all browser cookies. // -// cookies - Array of cookie objects. -func (p *GetCookiesParams) Do(ctx context.Context) (cookies []*network.Cookie, err error) { - // execute - var res GetCookiesReturns - err = cdp.Execute(ctx, CommandGetCookies, p, &res) - if err != nil { - return nil, err - } - - return res.Cookies, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getCookies +var GetCookies = cdp.Command[GetCookiesParams, GetCookiesResult]{Method: CommandGetCookies} -// SetCookiesParams sets given cookies. +// SetCookiesParams are the parameters of the command Storage.setCookies. type SetCookiesParams struct { Cookies []*network.CookieParam `json:"cookies"` // Cookies to be set. BrowserContextID cdp.BrowserContextID `json:"browserContextId,omitempty,omitzero"` // Browser context to use when called on the browser endpoint. @@ -160,29 +76,9 @@ type SetCookiesParams struct { // SetCookies sets given cookies. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-setCookies -// -// parameters: -// -// cookies - Cookies to be set. -func SetCookies(cookies []*network.CookieParam) *SetCookiesParams { - return &SetCookiesParams{ - Cookies: cookies, - } -} - -// WithBrowserContextID browser context to use when called on the browser -// endpoint. -func (p SetCookiesParams) WithBrowserContextID(browserContextID cdp.BrowserContextID) *SetCookiesParams { - p.BrowserContextID = browserContextID - return &p -} +var SetCookies = cdp.Command[SetCookiesParams, cdp.Empty]{Method: CommandSetCookies} -// Do executes Storage.setCookies against the provided context. -func (p *SetCookiesParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetCookies, p, nil) -} - -// ClearCookiesParams clears cookies. +// ClearCookiesParams are the parameters of the command Storage.clearCookies. type ClearCookiesParams struct { BrowserContextID cdp.BrowserContextID `json:"browserContextId,omitempty,omitzero"` // Browser context to use when called on the browser endpoint. } @@ -190,107 +86,42 @@ type ClearCookiesParams struct { // ClearCookies clears cookies. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-clearCookies -// -// parameters: -func ClearCookies() *ClearCookiesParams { - return &ClearCookiesParams{} -} - -// WithBrowserContextID browser context to use when called on the browser -// endpoint. -func (p ClearCookiesParams) WithBrowserContextID(browserContextID cdp.BrowserContextID) *ClearCookiesParams { - p.BrowserContextID = browserContextID - return &p -} +var ClearCookies = cdp.Command[ClearCookiesParams, cdp.Empty]{Method: CommandClearCookies} -// Do executes Storage.clearCookies against the provided context. -func (p *ClearCookiesParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClearCookies, p, nil) -} - -// GetUsageAndQuotaParams returns usage and quota in bytes. +// GetUsageAndQuotaParams are the parameters of the command +// Storage.getUsageAndQuota. type GetUsageAndQuotaParams struct { Origin string `json:"origin"` // Security origin. } -// GetUsageAndQuota returns usage and quota in bytes. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getUsageAndQuota -// -// parameters: -// -// origin - Security origin. -func GetUsageAndQuota(origin string) *GetUsageAndQuotaParams { - return &GetUsageAndQuotaParams{ - Origin: origin, - } -} - -// GetUsageAndQuotaReturns return values. -type GetUsageAndQuotaReturns struct { +// GetUsageAndQuotaResult is the result of the command +// Storage.getUsageAndQuota. +type GetUsageAndQuotaResult struct { Usage float64 `json:"usage,omitempty,omitzero"` // Storage usage (bytes). Quota float64 `json:"quota,omitempty,omitzero"` // Storage quota (bytes). OverrideActive bool `json:"overrideActive"` // Whether or not the origin has an active storage quota override UsageBreakdown []*UsageForType `json:"usageBreakdown,omitempty,omitzero"` // Storage usage per type (bytes). } -// Do executes Storage.getUsageAndQuota against the provided context. -// -// returns: +// GetUsageAndQuota returns usage and quota in bytes. // -// usage - Storage usage (bytes). -// quota - Storage quota (bytes). -// overrideActive - Whether or not the origin has an active storage quota override -// usageBreakdown - Storage usage per type (bytes). -func (p *GetUsageAndQuotaParams) Do(ctx context.Context) (usage float64, quota float64, overrideActive bool, usageBreakdown []*UsageForType, err error) { - // execute - var res GetUsageAndQuotaReturns - err = cdp.Execute(ctx, CommandGetUsageAndQuota, p, &res) - if err != nil { - return 0, 0, false, nil, err - } - - return res.Usage, res.Quota, res.OverrideActive, res.UsageBreakdown, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getUsageAndQuota +var GetUsageAndQuota = cdp.Command[GetUsageAndQuotaParams, GetUsageAndQuotaResult]{Method: CommandGetUsageAndQuota} -// OverrideQuotaForOriginParams override quota for the specified origin. +// OverrideQuotaForOriginParams are the parameters of the command +// Storage.overrideQuotaForOrigin. type OverrideQuotaForOriginParams struct { - Origin string `json:"origin"` // Security origin. - QuotaSize float64 `json:"quotaSize,omitempty,omitzero"` // The quota size (in bytes) to override the original quota with. If this is called multiple times, the overridden quota will be equal to the quotaSize provided in the final call. If this is called without specifying a quotaSize, the quota will be reset to the default value for the specified origin. If this is called multiple times with different origins, the override will be maintained for each origin until it is disabled (called without a quotaSize). + Origin string `json:"origin"` // Security origin. + QuotaSize *float64 `json:"quotaSize,omitempty,omitzero"` // The quota size (in bytes) to override the original quota with. If this is called multiple times, the overridden quota will be equal to the quotaSize provided in the final call. If this is called without specifying a quotaSize, the quota will be reset to the default value for the specified origin. If this is called multiple times with different origins, the override will be maintained for each origin until it is disabled (called without a quotaSize). } // OverrideQuotaForOrigin override quota for the specified origin. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-overrideQuotaForOrigin -// -// parameters: -// -// origin - Security origin. -func OverrideQuotaForOrigin(origin string) *OverrideQuotaForOriginParams { - return &OverrideQuotaForOriginParams{ - Origin: origin, - } -} - -// WithQuotaSize the quota size (in bytes) to override the original quota -// with. If this is called multiple times, the overridden quota will be equal to -// the quotaSize provided in the final call. If this is called without -// specifying a quotaSize, the quota will be reset to the default value for the -// specified origin. If this is called multiple times with different origins, -// the override will be maintained for each origin until it is disabled (called -// without a quotaSize). -func (p OverrideQuotaForOriginParams) WithQuotaSize(quotaSize float64) *OverrideQuotaForOriginParams { - p.QuotaSize = quotaSize - return &p -} - -// Do executes Storage.overrideQuotaForOrigin against the provided context. -func (p *OverrideQuotaForOriginParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandOverrideQuotaForOrigin, p, nil) -} +var OverrideQuotaForOrigin = cdp.Command[OverrideQuotaForOriginParams, cdp.Empty]{Method: CommandOverrideQuotaForOrigin} -// TrackCacheStorageForOriginParams registers origin to be notified when an -// update occurs to its cache storage list. +// TrackCacheStorageForOriginParams are the parameters of the command +// Storage.trackCacheStorageForOrigin. type TrackCacheStorageForOriginParams struct { Origin string `json:"origin"` // Security origin. } @@ -299,23 +130,10 @@ type TrackCacheStorageForOriginParams struct { // occurs to its cache storage list. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-trackCacheStorageForOrigin -// -// parameters: -// -// origin - Security origin. -func TrackCacheStorageForOrigin(origin string) *TrackCacheStorageForOriginParams { - return &TrackCacheStorageForOriginParams{ - Origin: origin, - } -} - -// Do executes Storage.trackCacheStorageForOrigin against the provided context. -func (p *TrackCacheStorageForOriginParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandTrackCacheStorageForOrigin, p, nil) -} +var TrackCacheStorageForOrigin = cdp.Command[TrackCacheStorageForOriginParams, cdp.Empty]{Method: CommandTrackCacheStorageForOrigin} -// TrackCacheStorageForStorageKeyParams registers storage key to be notified -// when an update occurs to its cache storage list. +// TrackCacheStorageForStorageKeyParams are the parameters of the command +// Storage.trackCacheStorageForStorageKey. type TrackCacheStorageForStorageKeyParams struct { StorageKey string `json:"storageKey"` // Storage key. } @@ -324,23 +142,10 @@ type TrackCacheStorageForStorageKeyParams struct { // an update occurs to its cache storage list. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-trackCacheStorageForStorageKey -// -// parameters: -// -// storageKey - Storage key. -func TrackCacheStorageForStorageKey(storageKey string) *TrackCacheStorageForStorageKeyParams { - return &TrackCacheStorageForStorageKeyParams{ - StorageKey: storageKey, - } -} +var TrackCacheStorageForStorageKey = cdp.Command[TrackCacheStorageForStorageKeyParams, cdp.Empty]{Method: CommandTrackCacheStorageForStorageKey} -// Do executes Storage.trackCacheStorageForStorageKey against the provided context. -func (p *TrackCacheStorageForStorageKeyParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandTrackCacheStorageForStorageKey, p, nil) -} - -// TrackIndexedDBForOriginParams registers origin to be notified when an -// update occurs to its IndexedDB. +// TrackIndexedDBForOriginParams are the parameters of the command +// Storage.trackIndexedDBForOrigin. type TrackIndexedDBForOriginParams struct { Origin string `json:"origin"` // Security origin. } @@ -349,23 +154,10 @@ type TrackIndexedDBForOriginParams struct { // occurs to its IndexedDB. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-trackIndexedDBForOrigin -// -// parameters: -// -// origin - Security origin. -func TrackIndexedDBForOrigin(origin string) *TrackIndexedDBForOriginParams { - return &TrackIndexedDBForOriginParams{ - Origin: origin, - } -} +var TrackIndexedDBForOrigin = cdp.Command[TrackIndexedDBForOriginParams, cdp.Empty]{Method: CommandTrackIndexedDBForOrigin} -// Do executes Storage.trackIndexedDBForOrigin against the provided context. -func (p *TrackIndexedDBForOriginParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandTrackIndexedDBForOrigin, p, nil) -} - -// TrackIndexedDBForStorageKeyParams registers storage key to be notified -// when an update occurs to its IndexedDB. +// TrackIndexedDBForStorageKeyParams are the parameters of the command +// Storage.trackIndexedDBForStorageKey. type TrackIndexedDBForStorageKeyParams struct { StorageKey string `json:"storageKey"` // Storage key. } @@ -374,23 +166,10 @@ type TrackIndexedDBForStorageKeyParams struct { // update occurs to its IndexedDB. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-trackIndexedDBForStorageKey -// -// parameters: -// -// storageKey - Storage key. -func TrackIndexedDBForStorageKey(storageKey string) *TrackIndexedDBForStorageKeyParams { - return &TrackIndexedDBForStorageKeyParams{ - StorageKey: storageKey, - } -} - -// Do executes Storage.trackIndexedDBForStorageKey against the provided context. -func (p *TrackIndexedDBForStorageKeyParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandTrackIndexedDBForStorageKey, p, nil) -} +var TrackIndexedDBForStorageKey = cdp.Command[TrackIndexedDBForStorageKeyParams, cdp.Empty]{Method: CommandTrackIndexedDBForStorageKey} -// UntrackCacheStorageForOriginParams unregisters origin from receiving -// notifications for cache storage. +// UntrackCacheStorageForOriginParams are the parameters of the command +// Storage.untrackCacheStorageForOrigin. type UntrackCacheStorageForOriginParams struct { Origin string `json:"origin"` // Security origin. } @@ -399,23 +178,10 @@ type UntrackCacheStorageForOriginParams struct { // notifications for cache storage. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-untrackCacheStorageForOrigin -// -// parameters: -// -// origin - Security origin. -func UntrackCacheStorageForOrigin(origin string) *UntrackCacheStorageForOriginParams { - return &UntrackCacheStorageForOriginParams{ - Origin: origin, - } -} +var UntrackCacheStorageForOrigin = cdp.Command[UntrackCacheStorageForOriginParams, cdp.Empty]{Method: CommandUntrackCacheStorageForOrigin} -// Do executes Storage.untrackCacheStorageForOrigin against the provided context. -func (p *UntrackCacheStorageForOriginParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandUntrackCacheStorageForOrigin, p, nil) -} - -// UntrackCacheStorageForStorageKeyParams unregisters storage key from -// receiving notifications for cache storage. +// UntrackCacheStorageForStorageKeyParams are the parameters of the command +// Storage.untrackCacheStorageForStorageKey. type UntrackCacheStorageForStorageKeyParams struct { StorageKey string `json:"storageKey"` // Storage key. } @@ -424,23 +190,10 @@ type UntrackCacheStorageForStorageKeyParams struct { // notifications for cache storage. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-untrackCacheStorageForStorageKey -// -// parameters: -// -// storageKey - Storage key. -func UntrackCacheStorageForStorageKey(storageKey string) *UntrackCacheStorageForStorageKeyParams { - return &UntrackCacheStorageForStorageKeyParams{ - StorageKey: storageKey, - } -} - -// Do executes Storage.untrackCacheStorageForStorageKey against the provided context. -func (p *UntrackCacheStorageForStorageKeyParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandUntrackCacheStorageForStorageKey, p, nil) -} +var UntrackCacheStorageForStorageKey = cdp.Command[UntrackCacheStorageForStorageKeyParams, cdp.Empty]{Method: CommandUntrackCacheStorageForStorageKey} -// UntrackIndexedDBForOriginParams unregisters origin from receiving -// notifications for IndexedDB. +// UntrackIndexedDBForOriginParams are the parameters of the command +// Storage.untrackIndexedDBForOrigin. type UntrackIndexedDBForOriginParams struct { Origin string `json:"origin"` // Security origin. } @@ -449,23 +202,10 @@ type UntrackIndexedDBForOriginParams struct { // for IndexedDB. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-untrackIndexedDBForOrigin -// -// parameters: -// -// origin - Security origin. -func UntrackIndexedDBForOrigin(origin string) *UntrackIndexedDBForOriginParams { - return &UntrackIndexedDBForOriginParams{ - Origin: origin, - } -} +var UntrackIndexedDBForOrigin = cdp.Command[UntrackIndexedDBForOriginParams, cdp.Empty]{Method: CommandUntrackIndexedDBForOrigin} -// Do executes Storage.untrackIndexedDBForOrigin against the provided context. -func (p *UntrackIndexedDBForOriginParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandUntrackIndexedDBForOrigin, p, nil) -} - -// UntrackIndexedDBForStorageKeyParams unregisters storage key from receiving -// notifications for IndexedDB. +// UntrackIndexedDBForStorageKeyParams are the parameters of the command +// Storage.untrackIndexedDBForStorageKey. type UntrackIndexedDBForStorageKeyParams struct { StorageKey string `json:"storageKey"` // Storage key. } @@ -474,322 +214,100 @@ type UntrackIndexedDBForStorageKeyParams struct { // notifications for IndexedDB. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-untrackIndexedDBForStorageKey -// -// parameters: -// -// storageKey - Storage key. -func UntrackIndexedDBForStorageKey(storageKey string) *UntrackIndexedDBForStorageKeyParams { - return &UntrackIndexedDBForStorageKeyParams{ - StorageKey: storageKey, - } -} +var UntrackIndexedDBForStorageKey = cdp.Command[UntrackIndexedDBForStorageKeyParams, cdp.Empty]{Method: CommandUntrackIndexedDBForStorageKey} -// Do executes Storage.untrackIndexedDBForStorageKey against the provided context. -func (p *UntrackIndexedDBForStorageKeyParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandUntrackIndexedDBForStorageKey, p, nil) +// GetTrustTokensResult is the result of the command Storage.getTrustTokens. +type GetTrustTokensResult struct { + Tokens []*TrustTokens `json:"tokens,omitempty,omitzero"` } -// GetTrustTokensParams returns the number of stored Trust Tokens per issuer -// for the current browsing context. -type GetTrustTokensParams struct{} - // GetTrustTokens returns the number of stored Trust Tokens per issuer for // the current browsing context. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getTrustTokens -func GetTrustTokens() *GetTrustTokensParams { - return &GetTrustTokensParams{} -} - -// GetTrustTokensReturns return values. -type GetTrustTokensReturns struct { - Tokens []*TrustTokens `json:"tokens,omitempty,omitzero"` -} - -// Do executes Storage.getTrustTokens against the provided context. -// -// returns: -// -// tokens -func (p *GetTrustTokensParams) Do(ctx context.Context) (tokens []*TrustTokens, err error) { - // execute - var res GetTrustTokensReturns - err = cdp.Execute(ctx, CommandGetTrustTokens, nil, &res) - if err != nil { - return nil, err - } - - return res.Tokens, nil -} +var GetTrustTokens = cdp.Command[cdp.Empty, GetTrustTokensResult]{Method: CommandGetTrustTokens} -// ClearTrustTokensParams removes all Trust Tokens issued by the provided -// issuerOrigin. Leaves other stored data, including the issuer's Redemption -// Records, intact. +// ClearTrustTokensParams are the parameters of the command +// Storage.clearTrustTokens. type ClearTrustTokensParams struct { IssuerOrigin string `json:"issuerOrigin"` } +// ClearTrustTokensResult is the result of the command +// Storage.clearTrustTokens. +type ClearTrustTokensResult struct { + DidDeleteTokens bool `json:"didDeleteTokens"` // True if any tokens were deleted, false otherwise. +} + // ClearTrustTokens removes all Trust Tokens issued by the provided // issuerOrigin. Leaves other stored data, including the issuer's Redemption // Records, intact. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-clearTrustTokens -// -// parameters: -// -// issuerOrigin -func ClearTrustTokens(issuerOrigin string) *ClearTrustTokensParams { - return &ClearTrustTokensParams{ - IssuerOrigin: issuerOrigin, - } -} - -// ClearTrustTokensReturns return values. -type ClearTrustTokensReturns struct { - DidDeleteTokens bool `json:"didDeleteTokens"` // True if any tokens were deleted, false otherwise. -} - -// Do executes Storage.clearTrustTokens against the provided context. -// -// returns: -// -// didDeleteTokens - True if any tokens were deleted, false otherwise. -func (p *ClearTrustTokensParams) Do(ctx context.Context) (didDeleteTokens bool, err error) { - // execute - var res ClearTrustTokensReturns - err = cdp.Execute(ctx, CommandClearTrustTokens, p, &res) - if err != nil { - return false, err - } +var ClearTrustTokens = cdp.Command[ClearTrustTokensParams, ClearTrustTokensResult]{Method: CommandClearTrustTokens} - return res.DidDeleteTokens, nil +// GetPrivateVerificationTokensResult is the result of the command +// Storage.getPrivateVerificationTokens. +type GetPrivateVerificationTokensResult struct { + Tokens []*PrivateVerificationToken `json:"tokens,omitempty,omitzero"` } -// GetSharedStorageMetadataParams gets metadata for an origin's shared -// storage. -type GetSharedStorageMetadataParams struct { - OwnerOrigin string `json:"ownerOrigin"` -} - -// GetSharedStorageMetadata gets metadata for an origin's shared storage. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getSharedStorageMetadata -// -// parameters: -// -// ownerOrigin -func GetSharedStorageMetadata(ownerOrigin string) *GetSharedStorageMetadataParams { - return &GetSharedStorageMetadataParams{ - OwnerOrigin: ownerOrigin, - } -} - -// GetSharedStorageMetadataReturns return values. -type GetSharedStorageMetadataReturns struct { - Metadata *SharedStorageMetadata `json:"metadata,omitempty,omitzero"` -} - -// Do executes Storage.getSharedStorageMetadata against the provided context. -// -// returns: -// -// metadata -func (p *GetSharedStorageMetadataParams) Do(ctx context.Context) (metadata *SharedStorageMetadata, err error) { - // execute - var res GetSharedStorageMetadataReturns - err = cdp.Execute(ctx, CommandGetSharedStorageMetadata, p, &res) - if err != nil { - return nil, err - } - - return res.Metadata, nil -} - -// GetSharedStorageEntriesParams gets the entries in an given origin's shared -// storage. -type GetSharedStorageEntriesParams struct { - OwnerOrigin string `json:"ownerOrigin"` -} - -// GetSharedStorageEntries gets the entries in an given origin's shared -// storage. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getSharedStorageEntries -// -// parameters: +// GetPrivateVerificationTokens returns all stored Private Verification +// Tokens for the current browsing context. // -// ownerOrigin -func GetSharedStorageEntries(ownerOrigin string) *GetSharedStorageEntriesParams { - return &GetSharedStorageEntriesParams{ - OwnerOrigin: ownerOrigin, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getPrivateVerificationTokens +var GetPrivateVerificationTokens = cdp.Command[cdp.Empty, GetPrivateVerificationTokensResult]{Method: CommandGetPrivateVerificationTokens} -// GetSharedStorageEntriesReturns return values. -type GetSharedStorageEntriesReturns struct { - Entries []*SharedStorageEntry `json:"entries,omitempty,omitzero"` +// GetPrivateVerificationTokensIssuerConfigsResult is the result of the +// command Storage.getPrivateVerificationTokensIssuerConfigs. +type GetPrivateVerificationTokensIssuerConfigsResult struct { + Configs []*PrivateVerificationTokensIssuerConfig `json:"configs,omitempty,omitzero"` } -// Do executes Storage.getSharedStorageEntries against the provided context. -// -// returns: +// GetPrivateVerificationTokensIssuerConfigs returns the configured Private +// Verification Tokens issuers and their redeemer origins. // -// entries -func (p *GetSharedStorageEntriesParams) Do(ctx context.Context) (entries []*SharedStorageEntry, err error) { - // execute - var res GetSharedStorageEntriesReturns - err = cdp.Execute(ctx, CommandGetSharedStorageEntries, p, &res) - if err != nil { - return nil, err - } - - return res.Entries, nil -} - -// SetSharedStorageEntryParams sets entry with key and value for a given -// origin's shared storage. -type SetSharedStorageEntryParams struct { - OwnerOrigin string `json:"ownerOrigin"` - Key string `json:"key"` - Value string `json:"value"` - IgnoreIfPresent bool `json:"ignoreIfPresent"` // If ignoreIfPresent is included and true, then only sets the entry if key doesn't already exist. -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getPrivateVerificationTokensIssuerConfigs +var GetPrivateVerificationTokensIssuerConfigs = cdp.Command[cdp.Empty, GetPrivateVerificationTokensIssuerConfigsResult]{Method: CommandGetPrivateVerificationTokensIssuerConfigs} -// SetSharedStorageEntry sets entry with key and value for a given origin's -// shared storage. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-setSharedStorageEntry -// -// parameters: -// -// ownerOrigin -// key -// value -func SetSharedStorageEntry(ownerOrigin string, key string, value string) *SetSharedStorageEntryParams { - return &SetSharedStorageEntryParams{ - OwnerOrigin: ownerOrigin, - Key: key, - Value: value, - IgnoreIfPresent: false, - } -} - -// WithIgnoreIfPresent if ignoreIfPresent is included and true, then only -// sets the entry if key doesn't already exist. -func (p SetSharedStorageEntryParams) WithIgnoreIfPresent(ignoreIfPresent bool) *SetSharedStorageEntryParams { - p.IgnoreIfPresent = ignoreIfPresent - return &p -} - -// Do executes Storage.setSharedStorageEntry against the provided context. -func (p *SetSharedStorageEntryParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetSharedStorageEntry, p, nil) -} - -// DeleteSharedStorageEntryParams deletes entry for key (if it exists) for a -// given origin's shared storage. -type DeleteSharedStorageEntryParams struct { - OwnerOrigin string `json:"ownerOrigin"` - Key string `json:"key"` -} - -// DeleteSharedStorageEntry deletes entry for key (if it exists) for a given -// origin's shared storage. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-deleteSharedStorageEntry -// -// parameters: -// -// ownerOrigin -// key -func DeleteSharedStorageEntry(ownerOrigin string, key string) *DeleteSharedStorageEntryParams { - return &DeleteSharedStorageEntryParams{ - OwnerOrigin: ownerOrigin, - Key: key, - } -} - -// Do executes Storage.deleteSharedStorageEntry against the provided context. -func (p *DeleteSharedStorageEntryParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDeleteSharedStorageEntry, p, nil) -} - -// ClearSharedStorageEntriesParams clears all entries for a given origin's -// shared storage. -type ClearSharedStorageEntriesParams struct { - OwnerOrigin string `json:"ownerOrigin"` +// ClearPrivateVerificationTokensParams are the parameters of the command +// Storage.clearPrivateVerificationTokens. +type ClearPrivateVerificationTokensParams struct { + IssuerOrigin string `json:"issuerOrigin"` } -// ClearSharedStorageEntries clears all entries for a given origin's shared -// storage. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-clearSharedStorageEntries +// ClearPrivateVerificationTokens removes all Private Verification Tokens +// issued by the provided issuerOrigin. // -// parameters: -// -// ownerOrigin -func ClearSharedStorageEntries(ownerOrigin string) *ClearSharedStorageEntriesParams { - return &ClearSharedStorageEntriesParams{ - OwnerOrigin: ownerOrigin, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-clearPrivateVerificationTokens +var ClearPrivateVerificationTokens = cdp.Command[ClearPrivateVerificationTokensParams, cdp.Empty]{Method: CommandClearPrivateVerificationTokens} -// Do executes Storage.clearSharedStorageEntries against the provided context. -func (p *ClearSharedStorageEntriesParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClearSharedStorageEntries, p, nil) +// DeletePrivateVerificationTokenParams are the parameters of the command +// Storage.deletePrivateVerificationToken. +type DeletePrivateVerificationTokenParams struct { + TokenID string `json:"tokenId"` } -// ResetSharedStorageBudgetParams resets the budget for ownerOrigin by -// clearing all budget withdrawals. -type ResetSharedStorageBudgetParams struct { - OwnerOrigin string `json:"ownerOrigin"` -} - -// ResetSharedStorageBudget resets the budget for ownerOrigin by clearing all -// budget withdrawals. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-resetSharedStorageBudget +// DeletePrivateVerificationToken removes a specific Private Verification +// Token by its ID. // -// parameters: -// -// ownerOrigin -func ResetSharedStorageBudget(ownerOrigin string) *ResetSharedStorageBudgetParams { - return &ResetSharedStorageBudgetParams{ - OwnerOrigin: ownerOrigin, - } -} - -// Do executes Storage.resetSharedStorageBudget against the provided context. -func (p *ResetSharedStorageBudgetParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandResetSharedStorageBudget, p, nil) -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-deletePrivateVerificationToken +var DeletePrivateVerificationToken = cdp.Command[DeletePrivateVerificationTokenParams, cdp.Empty]{Method: CommandDeletePrivateVerificationToken} -// SetSharedStorageTrackingParams enables/disables issuing of -// sharedStorageAccessed events. -type SetSharedStorageTrackingParams struct { +// SetPrivateVerificationTokensTrackingParams are the parameters of the +// command Storage.setPrivateVerificationTokensTracking. +type SetPrivateVerificationTokensTrackingParams struct { Enable bool `json:"enable"` } -// SetSharedStorageTracking enables/disables issuing of sharedStorageAccessed -// events. +// SetPrivateVerificationTokensTracking set tracking for Private Verification +// Tokens. // -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-setSharedStorageTracking -// -// parameters: -// -// enable -func SetSharedStorageTracking(enable bool) *SetSharedStorageTrackingParams { - return &SetSharedStorageTrackingParams{ - Enable: enable, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-setPrivateVerificationTokensTracking +var SetPrivateVerificationTokensTracking = cdp.Command[SetPrivateVerificationTokensTrackingParams, cdp.Empty]{Method: CommandSetPrivateVerificationTokensTracking} -// Do executes Storage.setSharedStorageTracking against the provided context. -func (p *SetSharedStorageTrackingParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetSharedStorageTracking, p, nil) -} - -// SetStorageBucketTrackingParams set tracking for a storage key's buckets. +// SetStorageBucketTrackingParams are the parameters of the command +// Storage.setStorageBucketTracking. type SetStorageBucketTrackingParams struct { StorageKey string `json:"storageKey"` Enable bool `json:"enable"` @@ -798,25 +316,10 @@ type SetStorageBucketTrackingParams struct { // SetStorageBucketTracking set tracking for a storage key's buckets. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-setStorageBucketTracking -// -// parameters: -// -// storageKey -// enable -func SetStorageBucketTracking(storageKey string, enable bool) *SetStorageBucketTrackingParams { - return &SetStorageBucketTrackingParams{ - StorageKey: storageKey, - Enable: enable, - } -} - -// Do executes Storage.setStorageBucketTracking against the provided context. -func (p *SetStorageBucketTrackingParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetStorageBucketTracking, p, nil) -} +var SetStorageBucketTracking = cdp.Command[SetStorageBucketTrackingParams, cdp.Empty]{Method: CommandSetStorageBucketTracking} -// DeleteStorageBucketParams deletes the Storage Bucket with the given -// storage key and bucket name. +// DeleteStorageBucketParams are the parameters of the command +// Storage.deleteStorageBucket. type DeleteStorageBucketParams struct { Bucket *Bucket `json:"bucket"` } @@ -825,118 +328,84 @@ type DeleteStorageBucketParams struct { // and bucket name. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-deleteStorageBucket -// -// parameters: -// -// bucket -func DeleteStorageBucket(bucket *Bucket) *DeleteStorageBucketParams { - return &DeleteStorageBucketParams{ - Bucket: bucket, - } -} +var DeleteStorageBucket = cdp.Command[DeleteStorageBucketParams, cdp.Empty]{Method: CommandDeleteStorageBucket} -// Do executes Storage.deleteStorageBucket against the provided context. -func (p *DeleteStorageBucketParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDeleteStorageBucket, p, nil) +// RunBounceTrackingMitigationsResult is the result of the command +// Storage.runBounceTrackingMitigations. +type RunBounceTrackingMitigationsResult struct { + DeletedSites []string `json:"deletedSites,omitempty,omitzero"` } -// RunBounceTrackingMitigationsParams deletes state for sites identified as -// potential bounce trackers, immediately. -type RunBounceTrackingMitigationsParams struct{} - // RunBounceTrackingMitigations deletes state for sites identified as // potential bounce trackers, immediately. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-runBounceTrackingMitigations -func RunBounceTrackingMitigations() *RunBounceTrackingMitigationsParams { - return &RunBounceTrackingMitigationsParams{} -} +var RunBounceTrackingMitigations = cdp.Command[cdp.Empty, RunBounceTrackingMitigationsResult]{Method: CommandRunBounceTrackingMitigations} -// RunBounceTrackingMitigationsReturns return values. -type RunBounceTrackingMitigationsReturns struct { - DeletedSites []string `json:"deletedSites,omitempty,omitzero"` -} - -// Do executes Storage.runBounceTrackingMitigations against the provided context. -// -// returns: +// CacheStorageContentUpdated a cache's contents have been modified. // -// deletedSites -func (p *RunBounceTrackingMitigationsParams) Do(ctx context.Context) (deletedSites []string, err error) { - // execute - var res RunBounceTrackingMitigationsReturns - err = cdp.Execute(ctx, CommandRunBounceTrackingMitigations, nil, &res) - if err != nil { - return nil, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#event-cacheStorageContentUpdated +var CacheStorageContentUpdated = cdp.Event[EventCacheStorageContentUpdated]{Method: "Storage.cacheStorageContentUpdated"} - return res.DeletedSites, nil -} - -// GetRelatedWebsiteSetsParams returns the effective Related Website Sets in -// use by this profile for the browser session. The effective Related Website -// Sets will not change during a browser session. -type GetRelatedWebsiteSetsParams struct{} +// CacheStorageListUpdated a cache has been added/deleted. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#event-cacheStorageListUpdated +var CacheStorageListUpdated = cdp.Event[EventCacheStorageListUpdated]{Method: "Storage.cacheStorageListUpdated"} -// GetRelatedWebsiteSets returns the effective Related Website Sets in use by -// this profile for the browser session. The effective Related Website Sets will -// not change during a browser session. +// IndexedDBContentUpdated the origin's IndexedDB object store has been +// modified. // -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getRelatedWebsiteSets -func GetRelatedWebsiteSets() *GetRelatedWebsiteSetsParams { - return &GetRelatedWebsiteSetsParams{} -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#event-indexedDBContentUpdated +var IndexedDBContentUpdated = cdp.Event[EventIndexedDBContentUpdated]{Method: "Storage.indexedDBContentUpdated"} -// GetRelatedWebsiteSetsReturns return values. -type GetRelatedWebsiteSetsReturns struct { - Sets []*RelatedWebsiteSet `json:"sets,omitempty,omitzero"` -} +// IndexedDBListUpdated the origin's IndexedDB database list has been +// modified. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#event-indexedDBListUpdated +var IndexedDBListUpdated = cdp.Event[EventIndexedDBListUpdated]{Method: "Storage.indexedDBListUpdated"} -// Do executes Storage.getRelatedWebsiteSets against the provided context. +// StorageBucketCreatedOrUpdated [no description]. // -// returns: +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#event-storageBucketCreatedOrUpdated +var StorageBucketCreatedOrUpdated = cdp.Event[EventStorageBucketCreatedOrUpdated]{Method: "Storage.storageBucketCreatedOrUpdated"} + +// StorageBucketDeleted [no description]. // -// sets -func (p *GetRelatedWebsiteSetsParams) Do(ctx context.Context) (sets []*RelatedWebsiteSet, err error) { - // execute - var res GetRelatedWebsiteSetsReturns - err = cdp.Execute(ctx, CommandGetRelatedWebsiteSets, nil, &res) - if err != nil { - return nil, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#event-storageBucketDeleted +var StorageBucketDeleted = cdp.Event[EventStorageBucketDeleted]{Method: "Storage.storageBucketDeleted"} - return res.Sets, nil -} +// PrivateVerificationTokensUpdated private Verification Tokens have been +// stored or deleted. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#event-privateVerificationTokensUpdated +var PrivateVerificationTokensUpdated = cdp.Event[EventPrivateVerificationTokensUpdated]{Method: "Storage.privateVerificationTokensUpdated"} // Command names. const ( - CommandGetStorageKey = "Storage.getStorageKey" - CommandClearDataForOrigin = "Storage.clearDataForOrigin" - CommandClearDataForStorageKey = "Storage.clearDataForStorageKey" - CommandGetCookies = "Storage.getCookies" - CommandSetCookies = "Storage.setCookies" - CommandClearCookies = "Storage.clearCookies" - CommandGetUsageAndQuota = "Storage.getUsageAndQuota" - CommandOverrideQuotaForOrigin = "Storage.overrideQuotaForOrigin" - CommandTrackCacheStorageForOrigin = "Storage.trackCacheStorageForOrigin" - CommandTrackCacheStorageForStorageKey = "Storage.trackCacheStorageForStorageKey" - CommandTrackIndexedDBForOrigin = "Storage.trackIndexedDBForOrigin" - CommandTrackIndexedDBForStorageKey = "Storage.trackIndexedDBForStorageKey" - CommandUntrackCacheStorageForOrigin = "Storage.untrackCacheStorageForOrigin" - CommandUntrackCacheStorageForStorageKey = "Storage.untrackCacheStorageForStorageKey" - CommandUntrackIndexedDBForOrigin = "Storage.untrackIndexedDBForOrigin" - CommandUntrackIndexedDBForStorageKey = "Storage.untrackIndexedDBForStorageKey" - CommandGetTrustTokens = "Storage.getTrustTokens" - CommandClearTrustTokens = "Storage.clearTrustTokens" - CommandGetSharedStorageMetadata = "Storage.getSharedStorageMetadata" - CommandGetSharedStorageEntries = "Storage.getSharedStorageEntries" - CommandSetSharedStorageEntry = "Storage.setSharedStorageEntry" - CommandDeleteSharedStorageEntry = "Storage.deleteSharedStorageEntry" - CommandClearSharedStorageEntries = "Storage.clearSharedStorageEntries" - CommandResetSharedStorageBudget = "Storage.resetSharedStorageBudget" - CommandSetSharedStorageTracking = "Storage.setSharedStorageTracking" - CommandSetStorageBucketTracking = "Storage.setStorageBucketTracking" - CommandDeleteStorageBucket = "Storage.deleteStorageBucket" - CommandRunBounceTrackingMitigations = "Storage.runBounceTrackingMitigations" - CommandGetRelatedWebsiteSets = "Storage.getRelatedWebsiteSets" + CommandGetStorageKey = "Storage.getStorageKey" + CommandClearDataForOrigin = "Storage.clearDataForOrigin" + CommandClearDataForStorageKey = "Storage.clearDataForStorageKey" + CommandGetCookies = "Storage.getCookies" + CommandSetCookies = "Storage.setCookies" + CommandClearCookies = "Storage.clearCookies" + CommandGetUsageAndQuota = "Storage.getUsageAndQuota" + CommandOverrideQuotaForOrigin = "Storage.overrideQuotaForOrigin" + CommandTrackCacheStorageForOrigin = "Storage.trackCacheStorageForOrigin" + CommandTrackCacheStorageForStorageKey = "Storage.trackCacheStorageForStorageKey" + CommandTrackIndexedDBForOrigin = "Storage.trackIndexedDBForOrigin" + CommandTrackIndexedDBForStorageKey = "Storage.trackIndexedDBForStorageKey" + CommandUntrackCacheStorageForOrigin = "Storage.untrackCacheStorageForOrigin" + CommandUntrackCacheStorageForStorageKey = "Storage.untrackCacheStorageForStorageKey" + CommandUntrackIndexedDBForOrigin = "Storage.untrackIndexedDBForOrigin" + CommandUntrackIndexedDBForStorageKey = "Storage.untrackIndexedDBForStorageKey" + CommandGetTrustTokens = "Storage.getTrustTokens" + CommandClearTrustTokens = "Storage.clearTrustTokens" + CommandGetPrivateVerificationTokens = "Storage.getPrivateVerificationTokens" + CommandGetPrivateVerificationTokensIssuerConfigs = "Storage.getPrivateVerificationTokensIssuerConfigs" + CommandClearPrivateVerificationTokens = "Storage.clearPrivateVerificationTokens" + CommandDeletePrivateVerificationToken = "Storage.deletePrivateVerificationToken" + CommandSetPrivateVerificationTokensTracking = "Storage.setPrivateVerificationTokensTracking" + CommandSetStorageBucketTracking = "Storage.setStorageBucketTracking" + CommandDeleteStorageBucket = "Storage.deleteStorageBucket" + CommandRunBounceTrackingMitigations = "Storage.runBounceTrackingMitigations" ) diff --git a/vendor/github.com/chromedp/cdproto/storage/types.go b/vendor/github.com/chromedp/cdproto/storage/types.go index 077dda21e..f4291f0ce 100644 --- a/vendor/github.com/chromedp/cdproto/storage/types.go +++ b/vendor/github.com/chromedp/cdproto/storage/types.go @@ -1,13 +1,9 @@ -package storage +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package storage import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/cdp" - "github.com/chromedp/cdproto/target" ) // SerializedStorageKey [no description]. @@ -40,51 +36,11 @@ const ( TypeWebsql Type = "websql" TypeServiceWorkers Type = "service_workers" TypeCacheStorage Type = "cache_storage" - TypeInterestGroups Type = "interest_groups" - TypeSharedStorage Type = "shared_storage" TypeStorageBuckets Type = "storage_buckets" TypeAll Type = "all" TypeOther Type = "other" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *Type) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch Type(s) { - case TypeCookies: - *t = TypeCookies - case TypeFileSystems: - *t = TypeFileSystems - case TypeIndexeddb: - *t = TypeIndexeddb - case TypeLocalStorage: - *t = TypeLocalStorage - case TypeShaderCache: - *t = TypeShaderCache - case TypeWebsql: - *t = TypeWebsql - case TypeServiceWorkers: - *t = TypeServiceWorkers - case TypeCacheStorage: - *t = TypeCacheStorage - case TypeInterestGroups: - *t = TypeInterestGroups - case TypeSharedStorage: - *t = TypeSharedStorage - case TypeStorageBuckets: - *t = TypeStorageBuckets - case TypeAll: - *t = TypeAll - case TypeOther: - *t = TypeOther - default: - return fmt.Errorf("unknown Type value: %v", s) - } - return nil -} - // UsageForType usage for a storage type. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#type-UsageForType @@ -102,182 +58,26 @@ type TrustTokens struct { Count float64 `json:"count"` } -// SharedStorageAccessScope enum of shared storage access scopes. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#type-SharedStorageAccessScope -type SharedStorageAccessScope string - -// String returns the SharedStorageAccessScope as string value. -func (t SharedStorageAccessScope) String() string { - return string(t) -} - -// SharedStorageAccessScope values. -const ( - SharedStorageAccessScopeWindow SharedStorageAccessScope = "window" - SharedStorageAccessScopeSharedStorageWorklet SharedStorageAccessScope = "sharedStorageWorklet" - SharedStorageAccessScopeHeader SharedStorageAccessScope = "header" -) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SharedStorageAccessScope) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SharedStorageAccessScope(s) { - case SharedStorageAccessScopeWindow: - *t = SharedStorageAccessScopeWindow - case SharedStorageAccessScopeSharedStorageWorklet: - *t = SharedStorageAccessScopeSharedStorageWorklet - case SharedStorageAccessScopeHeader: - *t = SharedStorageAccessScopeHeader - default: - return fmt.Errorf("unknown SharedStorageAccessScope value: %v", s) - } - return nil -} - -// SharedStorageAccessMethod enum of shared storage access methods. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#type-SharedStorageAccessMethod -type SharedStorageAccessMethod string - -// String returns the SharedStorageAccessMethod as string value. -func (t SharedStorageAccessMethod) String() string { - return string(t) -} - -// SharedStorageAccessMethod values. -const ( - SharedStorageAccessMethodAddModule SharedStorageAccessMethod = "addModule" - SharedStorageAccessMethodCreateWorklet SharedStorageAccessMethod = "createWorklet" - SharedStorageAccessMethodSelectURL SharedStorageAccessMethod = "selectURL" - SharedStorageAccessMethodRun SharedStorageAccessMethod = "run" - SharedStorageAccessMethodBatchUpdate SharedStorageAccessMethod = "batchUpdate" - SharedStorageAccessMethodSet SharedStorageAccessMethod = "set" - SharedStorageAccessMethodAppend SharedStorageAccessMethod = "append" - SharedStorageAccessMethodDelete SharedStorageAccessMethod = "delete" - SharedStorageAccessMethodClear SharedStorageAccessMethod = "clear" - SharedStorageAccessMethodGet SharedStorageAccessMethod = "get" - SharedStorageAccessMethodKeys SharedStorageAccessMethod = "keys" - SharedStorageAccessMethodValues SharedStorageAccessMethod = "values" - SharedStorageAccessMethodEntries SharedStorageAccessMethod = "entries" - SharedStorageAccessMethodLength SharedStorageAccessMethod = "length" - SharedStorageAccessMethodRemainingBudget SharedStorageAccessMethod = "remainingBudget" -) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SharedStorageAccessMethod) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SharedStorageAccessMethod(s) { - case SharedStorageAccessMethodAddModule: - *t = SharedStorageAccessMethodAddModule - case SharedStorageAccessMethodCreateWorklet: - *t = SharedStorageAccessMethodCreateWorklet - case SharedStorageAccessMethodSelectURL: - *t = SharedStorageAccessMethodSelectURL - case SharedStorageAccessMethodRun: - *t = SharedStorageAccessMethodRun - case SharedStorageAccessMethodBatchUpdate: - *t = SharedStorageAccessMethodBatchUpdate - case SharedStorageAccessMethodSet: - *t = SharedStorageAccessMethodSet - case SharedStorageAccessMethodAppend: - *t = SharedStorageAccessMethodAppend - case SharedStorageAccessMethodDelete: - *t = SharedStorageAccessMethodDelete - case SharedStorageAccessMethodClear: - *t = SharedStorageAccessMethodClear - case SharedStorageAccessMethodGet: - *t = SharedStorageAccessMethodGet - case SharedStorageAccessMethodKeys: - *t = SharedStorageAccessMethodKeys - case SharedStorageAccessMethodValues: - *t = SharedStorageAccessMethodValues - case SharedStorageAccessMethodEntries: - *t = SharedStorageAccessMethodEntries - case SharedStorageAccessMethodLength: - *t = SharedStorageAccessMethodLength - case SharedStorageAccessMethodRemainingBudget: - *t = SharedStorageAccessMethodRemainingBudget - default: - return fmt.Errorf("unknown SharedStorageAccessMethod value: %v", s) - } - return nil -} - -// SharedStorageEntry struct for a single key-value pair in an origin's -// shared storage. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#type-SharedStorageEntry -type SharedStorageEntry struct { - Key string `json:"key"` - Value string `json:"value"` -} - -// SharedStorageMetadata details for an origin's shared storage. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#type-SharedStorageMetadata -type SharedStorageMetadata struct { - CreationTime *cdp.TimeSinceEpoch `json:"creationTime"` // Time when the origin's shared storage was last created. - Length int64 `json:"length"` // Number of key-value pairs stored in origin's shared storage. - RemainingBudget float64 `json:"remainingBudget"` // Current amount of bits of entropy remaining in the navigation budget. - BytesUsed int64 `json:"bytesUsed"` // Total number of bytes stored as key-value pairs in origin's shared storage. -} - -// SharedStoragePrivateAggregationConfig represents a dictionary object -// passed in as privateAggregationConfig to run or selectURL. +// PrivateVerificationToken details of a stored Private Verification Token. // -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#type-SharedStoragePrivateAggregationConfig -type SharedStoragePrivateAggregationConfig struct { - AggregationCoordinatorOrigin string `json:"aggregationCoordinatorOrigin,omitempty,omitzero"` // The chosen aggregation service deployment. - ContextID string `json:"contextId,omitempty,omitzero"` // The context ID provided. - FilteringIDMaxBytes int64 `json:"filteringIdMaxBytes"` // Configures the maximum size allowed for filtering IDs. - MaxContributions int64 `json:"maxContributions,omitempty,omitzero"` // The limit on the number of contributions in the final report. +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#type-PrivateVerificationToken +type PrivateVerificationToken struct { + ID string `json:"id"` // Unique identifier of the token in the database. + IssuerOrigin string `json:"issuerOrigin"` // Origin of the token issuer. + KeyID int64 `json:"keyId"` // Public key ID used to issue the token. + Expiration cdp.TimeSinceEpoch `json:"expiration"` // Expiration timestamp in seconds since the epoch. + CreationTime cdp.TimeSinceEpoch `json:"creationTime"` // Token creation timestamp in seconds since the epoch. + Version int64 `json:"version"` // Token protocol version. + Token []byte `json:"token"` // Base64-encoded serialized token. } -// SharedStorageReportingMetadata pair of reporting metadata details for a -// candidate URL for selectURL(). +// PrivateVerificationTokensIssuerConfig configuration for a Private +// Verification Tokens issuer. // -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#type-SharedStorageReportingMetadata -type SharedStorageReportingMetadata struct { - EventType string `json:"eventType"` - ReportingURL string `json:"reportingUrl"` -} - -// SharedStorageURLWithMetadata bundles a candidate URL with its reporting -// metadata. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#type-SharedStorageUrlWithMetadata -type SharedStorageURLWithMetadata struct { - URL string `json:"url"` // Spec of candidate URL. - ReportingMetadata []*SharedStorageReportingMetadata `json:"reportingMetadata"` // Any associated reporting metadata. -} - -// SharedStorageAccessParams bundles the parameters for shared storage access -// events whose presence/absence can vary according to SharedStorageAccessType. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#type-SharedStorageAccessParams -type SharedStorageAccessParams struct { - ScriptSourceURL string `json:"scriptSourceUrl,omitempty,omitzero"` // Spec of the module script URL. Present only for SharedStorageAccessMethods: addModule and createWorklet. - DataOrigin string `json:"dataOrigin,omitempty,omitzero"` // String denoting "context-origin", "script-origin", or a custom origin to be used as the worklet's data origin. Present only for SharedStorageAccessMethod: createWorklet. - OperationName string `json:"operationName,omitempty,omitzero"` // Name of the registered operation to be run. Present only for SharedStorageAccessMethods: run and selectURL. - OperationID string `json:"operationId,omitempty,omitzero"` // ID of the operation call. Present only for SharedStorageAccessMethods: run and selectURL. - KeepAlive bool `json:"keepAlive"` // Whether or not to keep the worket alive for future run or selectURL calls. Present only for SharedStorageAccessMethods: run and selectURL. - PrivateAggregationConfig *SharedStoragePrivateAggregationConfig `json:"privateAggregationConfig,omitempty,omitzero"` // Configures the private aggregation options. Present only for SharedStorageAccessMethods: run and selectURL. - SerializedData string `json:"serializedData,omitempty,omitzero"` // The operation's serialized data in bytes (converted to a string). Present only for SharedStorageAccessMethods: run and selectURL. TODO(crbug.com/401011862): Consider updating this parameter to binary. - URLsWithMetadata []*SharedStorageURLWithMetadata `json:"urlsWithMetadata,omitempty,omitzero"` // Array of candidate URLs' specs, along with any associated metadata. Present only for SharedStorageAccessMethod: selectURL. - UrnUUID string `json:"urnUuid,omitempty,omitzero"` // Spec of the URN:UUID generated for a selectURL call. Present only for SharedStorageAccessMethod: selectURL. - Key string `json:"key,omitempty,omitzero"` // Key for a specific entry in an origin's shared storage. Present only for SharedStorageAccessMethods: set, append, delete, and get. - Value string `json:"value,omitempty,omitzero"` // Value for a specific entry in an origin's shared storage. Present only for SharedStorageAccessMethods: set and append. - IgnoreIfPresent bool `json:"ignoreIfPresent"` // Whether or not to set an entry for a key if that key is already present. Present only for SharedStorageAccessMethod: set. - WorkletOrdinal int64 `json:"workletOrdinal,omitempty,omitzero"` // A number denoting the (0-based) order of the worklet's creation relative to all other shared storage worklets created by documents using the current storage partition. Present only for SharedStorageAccessMethods: addModule, createWorklet. - WorkletTargetID target.ID `json:"workletTargetId,omitempty,omitzero"` // Hex representation of the DevTools token used as the TargetID for the associated shared storage worklet. Present only for SharedStorageAccessMethods: addModule, createWorklet, run, selectURL, and any other SharedStorageAccessMethod when the SharedStorageAccessScope is sharedStorageWorklet. - WithLock string `json:"withLock,omitempty,omitzero"` // Name of the lock to be acquired, if present. Optionally present only for SharedStorageAccessMethods: batchUpdate, set, append, delete, and clear. - BatchUpdateID string `json:"batchUpdateId,omitempty,omitzero"` // If the method has been called as part of a batchUpdate, then this number identifies the batch to which it belongs. Optionally present only for SharedStorageAccessMethods: batchUpdate (required), set, append, delete, and clear. - BatchSize int64 `json:"batchSize,omitempty,omitzero"` // Number of modifier methods sent in batch. Present only for SharedStorageAccessMethod: batchUpdate. +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#type-PrivateVerificationTokensIssuerConfig +type PrivateVerificationTokensIssuerConfig struct { + IssuerOrigin string `json:"issuerOrigin"` // Origin of the token issuer. + RedeemerOrigins []string `json:"redeemerOrigins"` // Origins authorized to redeem tokens from this issuer. } // BucketsDurability [no description]. @@ -296,22 +96,6 @@ const ( BucketsDurabilityStrict BucketsDurability = "strict" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *BucketsDurability) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch BucketsDurability(s) { - case BucketsDurabilityRelaxed: - *t = BucketsDurabilityRelaxed - case BucketsDurabilityStrict: - *t = BucketsDurabilityStrict - default: - return fmt.Errorf("unknown BucketsDurability value: %v", s) - } - return nil -} - // Bucket [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#type-StorageBucket @@ -324,19 +108,10 @@ type Bucket struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#type-StorageBucketInfo type BucketInfo struct { - Bucket *Bucket `json:"bucket"` - ID string `json:"id"` - Expiration *cdp.TimeSinceEpoch `json:"expiration"` - Quota float64 `json:"quota"` // Storage quota (bytes). - Persistent bool `json:"persistent"` - Durability BucketsDurability `json:"durability"` -} - -// RelatedWebsiteSet a single Related Website Set object. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#type-RelatedWebsiteSet -type RelatedWebsiteSet struct { - PrimarySites []string `json:"primarySites"` // The primary site of this set, along with the ccTLDs if there is any. - AssociatedSites []string `json:"associatedSites"` // The associated sites of this set, along with the ccTLDs if there is any. - ServiceSites []string `json:"serviceSites"` // The service sites of this set, along with the ccTLDs if there is any. + Bucket *Bucket `json:"bucket"` + ID string `json:"id"` + Expiration cdp.TimeSinceEpoch `json:"expiration"` + Quota float64 `json:"quota"` // Storage quota (bytes). + Persistent bool `json:"persistent"` + Durability BucketsDurability `json:"durability"` } diff --git a/vendor/github.com/chromedp/cdproto/systeminfo/systeminfo.go b/vendor/github.com/chromedp/cdproto/systeminfo/systeminfo.go index d3580ebb4..008a6bf62 100644 --- a/vendor/github.com/chromedp/cdproto/systeminfo/systeminfo.go +++ b/vendor/github.com/chromedp/cdproto/systeminfo/systeminfo.go @@ -1,126 +1,58 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package systeminfo provides the Chrome DevTools Protocol // commands, types, and events for the SystemInfo domain. // // The SystemInfo domain defines methods and events for querying low-level // system information. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package systeminfo -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// GetInfoParams returns information about the system. -type GetInfoParams struct{} - -// GetInfo returns information about the system. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/SystemInfo#method-getInfo -func GetInfo() *GetInfoParams { - return &GetInfoParams{} -} - -// GetInfoReturns return values. -type GetInfoReturns struct { +// GetInfoResult is the result of the command SystemInfo.getInfo. +type GetInfoResult struct { GPU *GPUInfo `json:"gpu,omitempty,omitzero"` // Information about the GPUs on the system. ModelName string `json:"modelName,omitempty,omitzero"` // A platform-dependent description of the model of the machine. On Mac OS, this is, for example, 'MacBookPro'. Will be the empty string if not supported. ModelVersion string `json:"modelVersion,omitempty,omitzero"` // A platform-dependent description of the version of the machine. On Mac OS, this is, for example, '10.1'. Will be the empty string if not supported. CommandLine string `json:"commandLine,omitempty,omitzero"` // The command line string used to launch the browser. Will be the empty string if not supported. } -// Do executes SystemInfo.getInfo against the provided context. -// -// returns: +// GetInfo returns information about the system. // -// gpu - Information about the GPUs on the system. -// modelName - A platform-dependent description of the model of the machine. On Mac OS, this is, for example, 'MacBookPro'. Will be the empty string if not supported. -// modelVersion - A platform-dependent description of the version of the machine. On Mac OS, this is, for example, '10.1'. Will be the empty string if not supported. -// commandLine - The command line string used to launch the browser. Will be the empty string if not supported. -func (p *GetInfoParams) Do(ctx context.Context) (gpu *GPUInfo, modelName string, modelVersion string, commandLine string, err error) { - // execute - var res GetInfoReturns - err = cdp.Execute(ctx, CommandGetInfo, nil, &res) - if err != nil { - return nil, "", "", "", err - } - - return res.GPU, res.ModelName, res.ModelVersion, res.CommandLine, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/SystemInfo#method-getInfo +var GetInfo = cdp.Command[cdp.Empty, GetInfoResult]{Method: CommandGetInfo} -// GetFeatureStateParams returns information about the feature state. +// GetFeatureStateParams are the parameters of the command +// SystemInfo.getFeatureState. type GetFeatureStateParams struct { FeatureState string `json:"featureState"` } -// GetFeatureState returns information about the feature state. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/SystemInfo#method-getFeatureState -// -// parameters: -// -// featureState -func GetFeatureState(featureState string) *GetFeatureStateParams { - return &GetFeatureStateParams{ - FeatureState: featureState, - } -} - -// GetFeatureStateReturns return values. -type GetFeatureStateReturns struct { +// GetFeatureStateResult is the result of the command +// SystemInfo.getFeatureState. +type GetFeatureStateResult struct { FeatureEnabled bool `json:"featureEnabled"` } -// Do executes SystemInfo.getFeatureState against the provided context. -// -// returns: +// GetFeatureState returns information about the feature state. // -// featureEnabled -func (p *GetFeatureStateParams) Do(ctx context.Context) (featureEnabled bool, err error) { - // execute - var res GetFeatureStateReturns - err = cdp.Execute(ctx, CommandGetFeatureState, p, &res) - if err != nil { - return false, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/SystemInfo#method-getFeatureState +var GetFeatureState = cdp.Command[GetFeatureStateParams, GetFeatureStateResult]{Method: CommandGetFeatureState} - return res.FeatureEnabled, nil +// GetProcessInfoResult is the result of the command +// SystemInfo.getProcessInfo. +type GetProcessInfoResult struct { + ProcessInfo []*ProcessInfo `json:"processInfo,omitempty,omitzero"` // An array of process info blocks. } -// GetProcessInfoParams returns information about all running processes. -type GetProcessInfoParams struct{} - // GetProcessInfo returns information about all running processes. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SystemInfo#method-getProcessInfo -func GetProcessInfo() *GetProcessInfoParams { - return &GetProcessInfoParams{} -} - -// GetProcessInfoReturns return values. -type GetProcessInfoReturns struct { - ProcessInfo []*ProcessInfo `json:"processInfo,omitempty,omitzero"` // An array of process info blocks. -} - -// Do executes SystemInfo.getProcessInfo against the provided context. -// -// returns: -// -// processInfo - An array of process info blocks. -func (p *GetProcessInfoParams) Do(ctx context.Context) (processInfo []*ProcessInfo, err error) { - // execute - var res GetProcessInfoReturns - err = cdp.Execute(ctx, CommandGetProcessInfo, nil, &res) - if err != nil { - return nil, err - } - - return res.ProcessInfo, nil -} +var GetProcessInfo = cdp.Command[cdp.Empty, GetProcessInfoResult]{Method: CommandGetProcessInfo} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/systeminfo/types.go b/vendor/github.com/chromedp/cdproto/systeminfo/types.go index f932b64b4..6f473dadf 100644 --- a/vendor/github.com/chromedp/cdproto/systeminfo/types.go +++ b/vendor/github.com/chromedp/cdproto/systeminfo/types.go @@ -1,12 +1,9 @@ -package systeminfo +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package systeminfo import ( - "fmt" - "strings" - - "github.com/go-json-experiment/json/jsontext" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" ) // GPUDevice describes a single graphics processor (GPU). @@ -69,24 +66,6 @@ const ( SubsamplingFormatYuv444 SubsamplingFormat = "yuv444" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *SubsamplingFormat) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch SubsamplingFormat(s) { - case SubsamplingFormatYuv420: - *t = SubsamplingFormatYuv420 - case SubsamplingFormatYuv422: - *t = SubsamplingFormatYuv422 - case SubsamplingFormatYuv444: - *t = SubsamplingFormatYuv444 - default: - return fmt.Errorf("unknown SubsamplingFormat value: %v", s) - } - return nil -} - // ImageType image format of a given image. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SystemInfo#type-ImageType @@ -104,31 +83,13 @@ const ( ImageTypeUnknown ImageType = "unknown" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ImageType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ImageType(s) { - case ImageTypeJpeg: - *t = ImageTypeJpeg - case ImageTypeWebp: - *t = ImageTypeWebp - case ImageTypeUnknown: - *t = ImageTypeUnknown - default: - return fmt.Errorf("unknown ImageType value: %v", s) - } - return nil -} - // GPUInfo provides information about the GPU(s) on the system. // // See: https://chromedevtools.github.io/devtools-protocol/tot/SystemInfo#type-GPUInfo type GPUInfo struct { Devices []*GPUDevice `json:"devices"` // The graphics devices on the system. Element 0 is the primary GPU. - AuxAttributes jsontext.Value `json:"auxAttributes,omitempty,omitzero"` - FeatureStatus jsontext.Value `json:"featureStatus,omitempty,omitzero"` + AuxAttributes jsonv2.Value `json:"auxAttributes,omitempty,omitzero"` + FeatureStatus jsonv2.Value `json:"featureStatus,omitempty,omitzero"` DriverBugWorkarounds []string `json:"driverBugWorkarounds"` // An optional array of GPU driver bug workarounds. VideoDecoding []*VideoDecodeAcceleratorCapability `json:"videoDecoding"` // Supported accelerated video decoding capabilities. VideoEncoding []*VideoEncodeAcceleratorCapability `json:"videoEncoding"` // Supported accelerated video encoding capabilities. diff --git a/vendor/github.com/chromedp/cdproto/target/events.go b/vendor/github.com/chromedp/cdproto/target/events.go index 114a4288d..59fee35dc 100644 --- a/vendor/github.com/chromedp/cdproto/target/events.go +++ b/vendor/github.com/chromedp/cdproto/target/events.go @@ -1,6 +1,6 @@ -package target +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package target // EventAttachedToTarget issued when attached to target because of // auto-attach or attachToTarget command. diff --git a/vendor/github.com/chromedp/cdproto/target/target.go b/vendor/github.com/chromedp/cdproto/target/target.go index d145c4d27..2b6789dd5 100644 --- a/vendor/github.com/chromedp/cdproto/target/target.go +++ b/vendor/github.com/chromedp/cdproto/target/target.go @@ -1,20 +1,19 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package target provides the Chrome DevTools Protocol // commands, types, and events for the Target domain. // // Supports additional targets discovery and allows to attach to them. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package target -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// ActivateTargetParams activates (focuses) the target. +// ActivateTargetParams are the parameters of the command +// Target.activateTarget. type ActivateTargetParams struct { TargetID ID `json:"targetId"` } @@ -22,105 +21,38 @@ type ActivateTargetParams struct { // ActivateTarget activates (focuses) the target. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-activateTarget -// -// parameters: -// -// targetID -func ActivateTarget(targetID ID) *ActivateTargetParams { - return &ActivateTargetParams{ - TargetID: targetID, - } -} +var ActivateTarget = cdp.Command[ActivateTargetParams, cdp.Empty]{Method: CommandActivateTarget} -// Do executes Target.activateTarget against the provided context. -func (p *ActivateTargetParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandActivateTarget, p, nil) +// AttachToTargetParams are the parameters of the command +// Target.attachToTarget. +type AttachToTargetParams struct { + TargetID ID `json:"targetId"` + Flatten *bool `json:"flatten,omitempty,omitzero"` // Enables "flat" access to the session via specifying sessionId attribute in the commands. We plan to make this the default, deprecate non-flattened mode, and eventually retire it. See crbug.com/991325. } -// AttachToTargetParams attaches to the target with given id. -type AttachToTargetParams struct { - TargetID ID `json:"targetId"` - Flatten bool `json:"flatten"` // Enables "flat" access to the session via specifying sessionId attribute in the commands. We plan to make this the default, deprecate non-flattened mode, and eventually retire it. See crbug.com/991325. +// AttachToTargetResult is the result of the command Target.attachToTarget. +type AttachToTargetResult struct { + SessionID SessionID `json:"sessionId,omitempty,omitzero"` // Id assigned to the session. } // AttachToTarget attaches to the target with given id. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-attachToTarget -// -// parameters: -// -// targetID -func AttachToTarget(targetID ID) *AttachToTargetParams { - return &AttachToTargetParams{ - TargetID: targetID, - Flatten: false, - } -} - -// WithFlatten enables "flat" access to the session via specifying sessionId -// attribute in the commands. We plan to make this the default, deprecate -// non-flattened mode, and eventually retire it. See crbug.com/991325. -func (p AttachToTargetParams) WithFlatten(flatten bool) *AttachToTargetParams { - p.Flatten = flatten - return &p -} +var AttachToTarget = cdp.Command[AttachToTargetParams, AttachToTargetResult]{Method: CommandAttachToTarget} -// AttachToTargetReturns return values. -type AttachToTargetReturns struct { +// AttachToBrowserTargetResult is the result of the command +// Target.attachToBrowserTarget. +type AttachToBrowserTargetResult struct { SessionID SessionID `json:"sessionId,omitempty,omitzero"` // Id assigned to the session. } -// Do executes Target.attachToTarget against the provided context. -// -// returns: -// -// sessionID - Id assigned to the session. -func (p *AttachToTargetParams) Do(ctx context.Context) (sessionID SessionID, err error) { - // execute - var res AttachToTargetReturns - err = cdp.Execute(ctx, CommandAttachToTarget, p, &res) - if err != nil { - return "", err - } - - return res.SessionID, nil -} - -// AttachToBrowserTargetParams attaches to the browser target, only uses flat -// sessionId mode. -type AttachToBrowserTargetParams struct{} - // AttachToBrowserTarget attaches to the browser target, only uses flat // sessionId mode. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-attachToBrowserTarget -func AttachToBrowserTarget() *AttachToBrowserTargetParams { - return &AttachToBrowserTargetParams{} -} - -// AttachToBrowserTargetReturns return values. -type AttachToBrowserTargetReturns struct { - SessionID SessionID `json:"sessionId,omitempty,omitzero"` // Id assigned to the session. -} - -// Do executes Target.attachToBrowserTarget against the provided context. -// -// returns: -// -// sessionID - Id assigned to the session. -func (p *AttachToBrowserTargetParams) Do(ctx context.Context) (sessionID SessionID, err error) { - // execute - var res AttachToBrowserTargetReturns - err = cdp.Execute(ctx, CommandAttachToBrowserTarget, nil, &res) - if err != nil { - return "", err - } - - return res.SessionID, nil -} +var AttachToBrowserTarget = cdp.Command[cdp.Empty, AttachToBrowserTargetResult]{Method: CommandAttachToBrowserTarget} -// CloseTargetParams closes the target. If the target is a page that gets -// closed too. +// CloseTargetParams are the parameters of the command Target.closeTarget. type CloseTargetParams struct { TargetID ID `json:"targetId"` } @@ -129,31 +61,14 @@ type CloseTargetParams struct { // too. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-closeTarget -// -// parameters: -// -// targetID -func CloseTarget(targetID ID) *CloseTargetParams { - return &CloseTargetParams{ - TargetID: targetID, - } -} +var CloseTarget = cdp.Command[CloseTargetParams, cdp.Empty]{Method: CommandCloseTarget} -// Do executes Target.closeTarget against the provided context. -func (p *CloseTargetParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandCloseTarget, p, nil) -} - -// ExposeDevToolsProtocolParams inject object to the target's main frame that -// provides a communication channel with browser target. Injected object will be -// available as window[bindingName]. The object has the following API: - -// binding.send(json) - a method to send messages over the remote debugging -// protocol - binding.onmessage = json => handleMessage(json) - a callback that -// will be called for the protocol notifications and command responses. +// ExposeDevToolsProtocolParams are the parameters of the command +// Target.exposeDevToolsProtocol. type ExposeDevToolsProtocolParams struct { TargetID ID `json:"targetId"` - BindingName string `json:"bindingName,omitempty,omitzero"` // Binding name, 'cdp' if not specified. - InheritPermissions bool `json:"inheritPermissions"` // If true, inherits the current root session's permissions (default: false). + BindingName string `json:"bindingName,omitempty,omitzero"` // Binding name, 'cdp' if not specified. + InheritPermissions *bool `json:"inheritPermissions,omitempty,omitzero"` // If true, inherits the current root session's permissions (default: false). } // ExposeDevToolsProtocol inject object to the target's main frame that @@ -164,289 +79,71 @@ type ExposeDevToolsProtocolParams struct { // will be called for the protocol notifications and command responses. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-exposeDevToolsProtocol -// -// parameters: -// -// targetID -func ExposeDevToolsProtocol(targetID ID) *ExposeDevToolsProtocolParams { - return &ExposeDevToolsProtocolParams{ - TargetID: targetID, - InheritPermissions: false, - } -} +var ExposeDevToolsProtocol = cdp.Command[ExposeDevToolsProtocolParams, cdp.Empty]{Method: CommandExposeDevToolsProtocol} -// WithBindingName binding name, 'cdp' if not specified. -func (p ExposeDevToolsProtocolParams) WithBindingName(bindingName string) *ExposeDevToolsProtocolParams { - p.BindingName = bindingName - return &p -} - -// WithInheritPermissions if true, inherits the current root session's -// permissions (default: false). -func (p ExposeDevToolsProtocolParams) WithInheritPermissions(inheritPermissions bool) *ExposeDevToolsProtocolParams { - p.InheritPermissions = inheritPermissions - return &p -} - -// Do executes Target.exposeDevToolsProtocol against the provided context. -func (p *ExposeDevToolsProtocolParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandExposeDevToolsProtocol, p, nil) -} - -// CreateBrowserContextParams creates a new empty BrowserContext. Similar to -// an incognito profile but you can have more than one. +// CreateBrowserContextParams are the parameters of the command +// Target.createBrowserContext. type CreateBrowserContextParams struct { - DisposeOnDetach bool `json:"disposeOnDetach"` // If specified, disposes this context when debugging session disconnects. + DisposeOnDetach *bool `json:"disposeOnDetach,omitempty,omitzero"` // If specified, disposes this context when debugging session disconnects. ProxyServer string `json:"proxyServer,omitempty,omitzero"` // Proxy server, similar to the one passed to --proxy-server ProxyBypassList string `json:"proxyBypassList,omitempty,omitzero"` // Proxy bypass list, similar to the one passed to --proxy-bypass-list OriginsWithUniversalNetworkAccess []string `json:"originsWithUniversalNetworkAccess,omitempty,omitzero"` // An optional list of origins to grant unlimited cross-origin access to. Parts of the URL other than those constituting origin are ignored. } +// CreateBrowserContextResult is the result of the command +// Target.createBrowserContext. +type CreateBrowserContextResult struct { + BrowserContextID cdp.BrowserContextID `json:"browserContextId,omitempty,omitzero"` // The id of the context created. +} + // CreateBrowserContext creates a new empty BrowserContext. Similar to an // incognito profile but you can have more than one. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-createBrowserContext -// -// parameters: -func CreateBrowserContext() *CreateBrowserContextParams { - return &CreateBrowserContextParams{ - DisposeOnDetach: false, - } -} - -// WithDisposeOnDetach if specified, disposes this context when debugging -// session disconnects. -func (p CreateBrowserContextParams) WithDisposeOnDetach(disposeOnDetach bool) *CreateBrowserContextParams { - p.DisposeOnDetach = disposeOnDetach - return &p -} +var CreateBrowserContext = cdp.Command[CreateBrowserContextParams, CreateBrowserContextResult]{Method: CommandCreateBrowserContext} -// WithProxyServer proxy server, similar to the one passed to --proxy-server. -func (p CreateBrowserContextParams) WithProxyServer(proxyServer string) *CreateBrowserContextParams { - p.ProxyServer = proxyServer - return &p -} - -// WithProxyBypassList proxy bypass list, similar to the one passed to -// --proxy-bypass-list. -func (p CreateBrowserContextParams) WithProxyBypassList(proxyBypassList string) *CreateBrowserContextParams { - p.ProxyBypassList = proxyBypassList - return &p -} - -// WithOriginsWithUniversalNetworkAccess an optional list of origins to grant -// unlimited cross-origin access to. Parts of the URL other than those -// constituting origin are ignored. -func (p CreateBrowserContextParams) WithOriginsWithUniversalNetworkAccess(originsWithUniversalNetworkAccess []string) *CreateBrowserContextParams { - p.OriginsWithUniversalNetworkAccess = originsWithUniversalNetworkAccess - return &p -} - -// CreateBrowserContextReturns return values. -type CreateBrowserContextReturns struct { - BrowserContextID cdp.BrowserContextID `json:"browserContextId,omitempty,omitzero"` // The id of the context created. -} - -// Do executes Target.createBrowserContext against the provided context. -// -// returns: -// -// browserContextID - The id of the context created. -func (p *CreateBrowserContextParams) Do(ctx context.Context) (browserContextID cdp.BrowserContextID, err error) { - // execute - var res CreateBrowserContextReturns - err = cdp.Execute(ctx, CommandCreateBrowserContext, p, &res) - if err != nil { - return "", err - } - - return res.BrowserContextID, nil +// GetBrowserContextsResult is the result of the command +// Target.getBrowserContexts. +type GetBrowserContextsResult struct { + BrowserContextIDs []cdp.BrowserContextID `json:"browserContextIds,omitempty,omitzero"` // An array of browser context ids. + DefaultBrowserContextID cdp.BrowserContextID `json:"defaultBrowserContextId,omitempty,omitzero"` // The id of the default browser context if available. } -// GetBrowserContextsParams returns all browser contexts created with -// Target.createBrowserContext method. -type GetBrowserContextsParams struct{} - // GetBrowserContexts returns all browser contexts created with // Target.createBrowserContext method. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-getBrowserContexts -func GetBrowserContexts() *GetBrowserContextsParams { - return &GetBrowserContextsParams{} -} +var GetBrowserContexts = cdp.Command[cdp.Empty, GetBrowserContextsResult]{Method: CommandGetBrowserContexts} -// GetBrowserContextsReturns return values. -type GetBrowserContextsReturns struct { - BrowserContextIDs []cdp.BrowserContextID `json:"browserContextIds,omitempty,omitzero"` // An array of browser context ids. - DefaultBrowserContextID cdp.BrowserContextID `json:"defaultBrowserContextId,omitempty,omitzero"` // The id of the default browser context if available. -} - -// Do executes Target.getBrowserContexts against the provided context. -// -// returns: -// -// browserContextIDs - An array of browser context ids. -// defaultBrowserContextID - The id of the default browser context if available. -func (p *GetBrowserContextsParams) Do(ctx context.Context) (browserContextIDs []cdp.BrowserContextID, defaultBrowserContextID cdp.BrowserContextID, err error) { - // execute - var res GetBrowserContextsReturns - err = cdp.Execute(ctx, CommandGetBrowserContexts, nil, &res) - if err != nil { - return nil, "", err - } - - return res.BrowserContextIDs, res.DefaultBrowserContextID, nil -} - -// CreateTargetParams creates a new page. +// CreateTargetParams are the parameters of the command Target.createTarget. type CreateTargetParams struct { - URL string `json:"url"` // The initial URL the page will be navigated to. An empty string indicates about:blank. - Left int64 `json:"left,omitempty,omitzero"` // Frame left origin in DIP (requires newWindow to be true or headless shell). - Top int64 `json:"top,omitempty,omitzero"` // Frame top origin in DIP (requires newWindow to be true or headless shell). - Width int64 `json:"width,omitempty,omitzero"` // Frame width in DIP (requires newWindow to be true or headless shell). - Height int64 `json:"height,omitempty,omitzero"` // Frame height in DIP (requires newWindow to be true or headless shell). - WindowState WindowState `json:"windowState,omitempty,omitzero"` // Frame window state (requires newWindow to be true or headless shell). Default is normal. - BrowserContextID cdp.BrowserContextID `json:"browserContextId,omitempty,omitzero"` // The browser context to create the page in. - EnableBeginFrameControl bool `json:"enableBeginFrameControl"` // Whether BeginFrames for this target will be controlled via DevTools (headless shell only, not supported on MacOS yet, false by default). - NewWindow bool `json:"newWindow"` // Whether to create a new Window or Tab (false by default, not supported by headless shell). - Background bool `json:"background"` // Whether to create the target in background or foreground (false by default, not supported by headless shell). - ForTab bool `json:"forTab"` // Whether to create the target of type "tab". - Hidden bool `json:"hidden"` // Whether to create a hidden target. The hidden target is observable via protocol, but not present in the tab UI strip. Cannot be created with forTab: true, newWindow: true or background: false. The life-time of the tab is limited to the life-time of the session. - Focus bool `json:"focus"` // If specified, determines whether the new target should be focused. By default, the focus behavior depends on the background parameter: - If background is false (default) and focus is omitted, the new target is focused and the browser window is brought to the foreground. - If background is false and focus is false, the target is opened but the browser window's focus remains unchanged (e.g., if the window was in the background, it stays there). - If background is true, setting focus to true is not supported and will result in an error. + URL string `json:"url"` // The initial URL the page will be navigated to. An empty string indicates about:blank. + Left *int64 `json:"left,omitempty,omitzero"` // Frame left origin in DIP (requires newWindow to be true or headless shell). + Top *int64 `json:"top,omitempty,omitzero"` // Frame top origin in DIP (requires newWindow to be true or headless shell). + Width int64 `json:"width,omitempty,omitzero"` // Frame width in DIP (requires newWindow to be true or headless shell). + Height int64 `json:"height,omitempty,omitzero"` // Frame height in DIP (requires newWindow to be true or headless shell). + WindowState WindowState `json:"windowState,omitempty,omitzero"` // Frame window state (requires newWindow to be true or headless shell). Default is normal. + BrowserContextID cdp.BrowserContextID `json:"browserContextId,omitempty,omitzero"` // The browser context to create the page in. + EnableBeginFrameControl *bool `json:"enableBeginFrameControl,omitempty,omitzero"` // Whether BeginFrames for this target will be controlled via DevTools (headless shell only, not supported on MacOS yet, false by default). + NewWindow *bool `json:"newWindow,omitempty,omitzero"` // Whether to create a new Window or Tab (false by default, not supported by headless shell). + Background *bool `json:"background,omitempty,omitzero"` // Whether to create the target in background or foreground (false by default, not supported by headless shell). + ForTab *bool `json:"forTab,omitempty,omitzero"` // Whether to create the target of type "tab". + Hidden *bool `json:"hidden,omitempty,omitzero"` // Whether to create a hidden target. The hidden target is observable via protocol, but not present in the tab UI strip. Cannot be created with forTab: true, newWindow: true or background: false. The life-time of the tab is limited to the life-time of the session. + Focus *bool `json:"focus,omitempty,omitzero"` // If specified, determines whether the new target should be focused. By default, the focus behavior depends on the background parameter: - If background is false (default) and focus is omitted, the new target is focused and the browser window is brought to the foreground. - If background is false and focus is false, the target is opened but the browser window's focus remains unchanged (e.g., if the window was in the background, it stays there). - If background is true, setting focus to true is not supported and will result in an error. +} + +// CreateTargetResult is the result of the command Target.createTarget. +type CreateTargetResult struct { + TargetID ID `json:"targetId,omitempty,omitzero"` // The id of the page opened. } // CreateTarget creates a new page. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-createTarget -// -// parameters: -// -// url - The initial URL the page will be navigated to. An empty string indicates about:blank. -func CreateTarget(url string) *CreateTargetParams { - return &CreateTargetParams{ - URL: url, - EnableBeginFrameControl: false, - NewWindow: false, - Background: false, - ForTab: false, - Hidden: false, - Focus: false, - } -} - -// WithLeft frame left origin in DIP (requires newWindow to be true or -// headless shell). -func (p CreateTargetParams) WithLeft(left int64) *CreateTargetParams { - p.Left = left - return &p -} - -// WithTop frame top origin in DIP (requires newWindow to be true or headless -// shell). -func (p CreateTargetParams) WithTop(top int64) *CreateTargetParams { - p.Top = top - return &p -} - -// WithWidth frame width in DIP (requires newWindow to be true or headless -// shell). -func (p CreateTargetParams) WithWidth(width int64) *CreateTargetParams { - p.Width = width - return &p -} - -// WithHeight frame height in DIP (requires newWindow to be true or headless -// shell). -func (p CreateTargetParams) WithHeight(height int64) *CreateTargetParams { - p.Height = height - return &p -} - -// WithWindowState frame window state (requires newWindow to be true or -// headless shell). Default is normal. -func (p CreateTargetParams) WithWindowState(windowState WindowState) *CreateTargetParams { - p.WindowState = windowState - return &p -} - -// WithBrowserContextID the browser context to create the page in. -func (p CreateTargetParams) WithBrowserContextID(browserContextID cdp.BrowserContextID) *CreateTargetParams { - p.BrowserContextID = browserContextID - return &p -} - -// WithEnableBeginFrameControl whether BeginFrames for this target will be -// controlled via DevTools (headless shell only, not supported on MacOS yet, -// false by default). -func (p CreateTargetParams) WithEnableBeginFrameControl(enableBeginFrameControl bool) *CreateTargetParams { - p.EnableBeginFrameControl = enableBeginFrameControl - return &p -} - -// WithNewWindow whether to create a new Window or Tab (false by default, not -// supported by headless shell). -func (p CreateTargetParams) WithNewWindow(newWindow bool) *CreateTargetParams { - p.NewWindow = newWindow - return &p -} - -// WithBackground whether to create the target in background or foreground -// (false by default, not supported by headless shell). -func (p CreateTargetParams) WithBackground(background bool) *CreateTargetParams { - p.Background = background - return &p -} - -// WithForTab whether to create the target of type "tab". -func (p CreateTargetParams) WithForTab(forTab bool) *CreateTargetParams { - p.ForTab = forTab - return &p -} - -// WithHidden whether to create a hidden target. The hidden target is -// observable via protocol, but not present in the tab UI strip. Cannot be -// created with forTab: true, newWindow: true or background: false. The -// life-time of the tab is limited to the life-time of the session. -func (p CreateTargetParams) WithHidden(hidden bool) *CreateTargetParams { - p.Hidden = hidden - return &p -} - -// WithFocus if specified, determines whether the new target should be -// focused. By default, the focus behavior depends on the background parameter: -// - If background is false (default) and focus is omitted, the new target is -// focused and the browser window is brought to the foreground. - If background -// is false and focus is false, the target is opened but the browser window's -// focus remains unchanged (e.g., if the window was in the background, it stays -// there). - If background is true, setting focus to true is not supported and -// will result in an error. -func (p CreateTargetParams) WithFocus(focus bool) *CreateTargetParams { - p.Focus = focus - return &p -} - -// CreateTargetReturns return values. -type CreateTargetReturns struct { - TargetID ID `json:"targetId,omitempty,omitzero"` // The id of the page opened. -} +var CreateTarget = cdp.Command[CreateTargetParams, CreateTargetResult]{Method: CommandCreateTarget} -// Do executes Target.createTarget against the provided context. -// -// returns: -// -// targetID - The id of the page opened. -func (p *CreateTargetParams) Do(ctx context.Context) (targetID ID, err error) { - // execute - var res CreateTargetReturns - err = cdp.Execute(ctx, CommandCreateTarget, p, &res) - if err != nil { - return "", err - } - - return res.TargetID, nil -} - -// DetachFromTargetParams detaches session with given id. +// DetachFromTargetParams are the parameters of the command +// Target.detachFromTarget. type DetachFromTargetParams struct { SessionID SessionID `json:"sessionId,omitempty,omitzero"` // Session to detach. } @@ -454,25 +151,10 @@ type DetachFromTargetParams struct { // DetachFromTarget detaches session with given id. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-detachFromTarget -// -// parameters: -func DetachFromTarget() *DetachFromTargetParams { - return &DetachFromTargetParams{} -} - -// WithSessionID session to detach. -func (p DetachFromTargetParams) WithSessionID(sessionID SessionID) *DetachFromTargetParams { - p.SessionID = sessionID - return &p -} +var DetachFromTarget = cdp.Command[DetachFromTargetParams, cdp.Empty]{Method: CommandDetachFromTarget} -// Do executes Target.detachFromTarget against the provided context. -func (p *DetachFromTargetParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDetachFromTarget, p, nil) -} - -// DisposeBrowserContextParams deletes a BrowserContext. All the belonging -// pages will be closed without calling their beforeunload hooks. +// DisposeBrowserContextParams are the parameters of the command +// Target.disposeBrowserContext. type DisposeBrowserContextParams struct { BrowserContextID cdp.BrowserContextID `json:"browserContextId"` } @@ -481,118 +163,46 @@ type DisposeBrowserContextParams struct { // will be closed without calling their beforeunload hooks. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-disposeBrowserContext -// -// parameters: -// -// browserContextID -func DisposeBrowserContext(browserContextID cdp.BrowserContextID) *DisposeBrowserContextParams { - return &DisposeBrowserContextParams{ - BrowserContextID: browserContextID, - } -} - -// Do executes Target.disposeBrowserContext against the provided context. -func (p *DisposeBrowserContextParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisposeBrowserContext, p, nil) -} +var DisposeBrowserContext = cdp.Command[DisposeBrowserContextParams, cdp.Empty]{Method: CommandDisposeBrowserContext} -// GetTargetInfoParams returns information about a target. +// GetTargetInfoParams are the parameters of the command +// Target.getTargetInfo. type GetTargetInfoParams struct { TargetID ID `json:"targetId,omitempty,omitzero"` } -// GetTargetInfo returns information about a target. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-getTargetInfo -// -// parameters: -func GetTargetInfo() *GetTargetInfoParams { - return &GetTargetInfoParams{} -} - -// WithTargetID [no description]. -func (p GetTargetInfoParams) WithTargetID(targetID ID) *GetTargetInfoParams { - p.TargetID = targetID - return &p -} - -// GetTargetInfoReturns return values. -type GetTargetInfoReturns struct { +// GetTargetInfoResult is the result of the command Target.getTargetInfo. +type GetTargetInfoResult struct { TargetInfo *Info `json:"targetInfo,omitempty,omitzero"` } -// Do executes Target.getTargetInfo against the provided context. -// -// returns: +// GetTargetInfo returns information about a target. // -// targetInfo -func (p *GetTargetInfoParams) Do(ctx context.Context) (targetInfo *Info, err error) { - // execute - var res GetTargetInfoReturns - err = cdp.Execute(ctx, CommandGetTargetInfo, p, &res) - if err != nil { - return nil, err - } - - return res.TargetInfo, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-getTargetInfo +var GetTargetInfo = cdp.Command[GetTargetInfoParams, GetTargetInfoResult]{Method: CommandGetTargetInfo} -// GetTargetsParams retrieves a list of available targets. +// GetTargetsParams are the parameters of the command Target.getTargets. type GetTargetsParams struct { Filter Filter `json:"filter,omitempty,omitzero"` // Only targets matching filter will be reported. If filter is not specified and target discovery is currently enabled, a filter used for target discovery is used for consistency. } -// GetTargets retrieves a list of available targets. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-getTargets -// -// parameters: -func GetTargets() *GetTargetsParams { - return &GetTargetsParams{} -} - -// WithFilter only targets matching filter will be reported. If filter is not -// specified and target discovery is currently enabled, a filter used for target -// discovery is used for consistency. -func (p GetTargetsParams) WithFilter(filter Filter) *GetTargetsParams { - p.Filter = filter - return &p -} - -// GetTargetsReturns return values. -type GetTargetsReturns struct { +// GetTargetsResult is the result of the command Target.getTargets. +type GetTargetsResult struct { TargetInfos []*Info `json:"targetInfos,omitempty,omitzero"` // The list of targets. } -// Do executes Target.getTargets against the provided context. -// -// returns: +// GetTargets retrieves a list of available targets. // -// targetInfos - The list of targets. -func (p *GetTargetsParams) Do(ctx context.Context) (targetInfos []*Info, err error) { - // execute - var res GetTargetsReturns - err = cdp.Execute(ctx, CommandGetTargets, p, &res) - if err != nil { - return nil, err - } - - return res.TargetInfos, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-getTargets +var GetTargets = cdp.Command[GetTargetsParams, GetTargetsResult]{Method: CommandGetTargets} -// SetAutoAttachParams controls whether to automatically attach to new -// targets which are considered to be directly related to this one (for example, -// iframes or workers). When turned on, attaches to all existing related targets -// as well. When turned off, automatically detaches from all currently attached -// targets. This also clears all targets added by autoAttachRelated from the -// list of targets to watch for creation of related targets. You might want to -// call this recursively for auto-attached targets to attach to all available -// targets. +// SetAutoAttachParams are the parameters of the command +// Target.setAutoAttach. type SetAutoAttachParams struct { - AutoAttach bool `json:"autoAttach"` // Whether to auto-attach to related targets. - WaitForDebuggerOnStart bool `json:"waitForDebuggerOnStart"` // Whether to pause new targets when attaching to them. Use Runtime.runIfWaitingForDebugger to run paused targets. - Flatten bool `json:"flatten"` // Enables "flat" access to the session via specifying sessionId attribute in the commands. We plan to make this the default, deprecate non-flattened mode, and eventually retire it. See crbug.com/991325. - Filter Filter `json:"filter,omitempty,omitzero"` // Only targets matching filter will be attached. + AutoAttach bool `json:"autoAttach"` // Whether to auto-attach to related targets. + WaitForDebuggerOnStart bool `json:"waitForDebuggerOnStart"` // Whether to pause new targets when attaching to them. Use Runtime.runIfWaitingForDebugger to run paused targets. + Flatten *bool `json:"flatten,omitempty,omitzero"` // Enables "flat" access to the session via specifying sessionId attribute in the commands. We plan to make this the default, deprecate non-flattened mode, and eventually retire it. See crbug.com/991325. + Filter Filter `json:"filter,omitempty,omitzero"` // Only targets matching filter will be attached. } // SetAutoAttach controls whether to automatically attach to new targets @@ -605,44 +215,10 @@ type SetAutoAttachParams struct { // targets. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-setAutoAttach -// -// parameters: -// -// autoAttach - Whether to auto-attach to related targets. -// waitForDebuggerOnStart - Whether to pause new targets when attaching to them. Use Runtime.runIfWaitingForDebugger to run paused targets. -func SetAutoAttach(autoAttach bool, waitForDebuggerOnStart bool) *SetAutoAttachParams { - return &SetAutoAttachParams{ - AutoAttach: autoAttach, - WaitForDebuggerOnStart: waitForDebuggerOnStart, - Flatten: false, - } -} - -// WithFlatten enables "flat" access to the session via specifying sessionId -// attribute in the commands. We plan to make this the default, deprecate -// non-flattened mode, and eventually retire it. See crbug.com/991325. -func (p SetAutoAttachParams) WithFlatten(flatten bool) *SetAutoAttachParams { - p.Flatten = flatten - return &p -} - -// WithFilter only targets matching filter will be attached. -func (p SetAutoAttachParams) WithFilter(filter Filter) *SetAutoAttachParams { - p.Filter = filter - return &p -} +var SetAutoAttach = cdp.Command[SetAutoAttachParams, cdp.Empty]{Method: CommandSetAutoAttach} -// Do executes Target.setAutoAttach against the provided context. -func (p *SetAutoAttachParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetAutoAttach, p, nil) -} - -// AutoAttachRelatedParams adds the specified target to the list of targets -// that will be monitored for any related target creation (such as child frames, -// child workers and new versions of service worker) and reported through -// attachedToTarget. The specified target is also auto-attached. This cancels -// the effect of any previous setAutoAttach and is also cancelled by subsequent -// setAutoAttach. Only available at the Browser target. +// AutoAttachRelatedParams are the parameters of the command +// Target.autoAttachRelated. type AutoAttachRelatedParams struct { TargetID ID `json:"targetId"` WaitForDebuggerOnStart bool `json:"waitForDebuggerOnStart"` // Whether to pause new targets when attaching to them. Use Runtime.runIfWaitingForDebugger to run paused targets. @@ -657,31 +233,10 @@ type AutoAttachRelatedParams struct { // setAutoAttach. Only available at the Browser target. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-autoAttachRelated -// -// parameters: -// -// targetID -// waitForDebuggerOnStart - Whether to pause new targets when attaching to them. Use Runtime.runIfWaitingForDebugger to run paused targets. -func AutoAttachRelated(targetID ID, waitForDebuggerOnStart bool) *AutoAttachRelatedParams { - return &AutoAttachRelatedParams{ - TargetID: targetID, - WaitForDebuggerOnStart: waitForDebuggerOnStart, - } -} - -// WithFilter only targets matching filter will be attached. -func (p AutoAttachRelatedParams) WithFilter(filter Filter) *AutoAttachRelatedParams { - p.Filter = filter - return &p -} +var AutoAttachRelated = cdp.Command[AutoAttachRelatedParams, cdp.Empty]{Method: CommandAutoAttachRelated} -// Do executes Target.autoAttachRelated against the provided context. -func (p *AutoAttachRelatedParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandAutoAttachRelated, p, nil) -} - -// SetDiscoverTargetsParams controls whether to discover available targets -// and notify via targetCreated/targetInfoChanged/targetDestroyed events. +// SetDiscoverTargetsParams are the parameters of the command +// Target.setDiscoverTargets. type SetDiscoverTargetsParams struct { Discover bool `json:"discover"` // Whether to discover available targets. Filter Filter `json:"filter,omitempty,omitzero"` // Only targets matching filter will be attached. If discover is false, filter must be omitted or empty. @@ -691,30 +246,10 @@ type SetDiscoverTargetsParams struct { // notify via targetCreated/targetInfoChanged/targetDestroyed events. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-setDiscoverTargets -// -// parameters: -// -// discover - Whether to discover available targets. -func SetDiscoverTargets(discover bool) *SetDiscoverTargetsParams { - return &SetDiscoverTargetsParams{ - Discover: discover, - } -} - -// WithFilter only targets matching filter will be attached. If discover is -// false, filter must be omitted or empty. -func (p SetDiscoverTargetsParams) WithFilter(filter Filter) *SetDiscoverTargetsParams { - p.Filter = filter - return &p -} +var SetDiscoverTargets = cdp.Command[SetDiscoverTargetsParams, cdp.Empty]{Method: CommandSetDiscoverTargets} -// Do executes Target.setDiscoverTargets against the provided context. -func (p *SetDiscoverTargetsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetDiscoverTargets, p, nil) -} - -// SetRemoteLocationsParams enables target discovery for the specified -// locations, when setDiscoverTargets was set to true. +// SetRemoteLocationsParams are the parameters of the command +// Target.setRemoteLocations. type SetRemoteLocationsParams struct { Locations []*RemoteLocation `json:"locations"` // List of remote locations. } @@ -723,110 +258,81 @@ type SetRemoteLocationsParams struct { // when setDiscoverTargets was set to true. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-setRemoteLocations -// -// parameters: -// -// locations - List of remote locations. -func SetRemoteLocations(locations []*RemoteLocation) *SetRemoteLocationsParams { - return &SetRemoteLocationsParams{ - Locations: locations, - } -} - -// Do executes Target.setRemoteLocations against the provided context. -func (p *SetRemoteLocationsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetRemoteLocations, p, nil) -} +var SetRemoteLocations = cdp.Command[SetRemoteLocationsParams, cdp.Empty]{Method: CommandSetRemoteLocations} -// GetDevToolsTargetParams gets the targetId of the DevTools page target -// opened for the given target (if any). +// GetDevToolsTargetParams are the parameters of the command +// Target.getDevToolsTarget. type GetDevToolsTargetParams struct { TargetID ID `json:"targetId"` // Page or tab target ID. } -// GetDevToolsTarget gets the targetId of the DevTools page target opened for -// the given target (if any). -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-getDevToolsTarget -// -// parameters: -// -// targetID - Page or tab target ID. -func GetDevToolsTarget(targetID ID) *GetDevToolsTargetParams { - return &GetDevToolsTargetParams{ - TargetID: targetID, - } -} - -// GetDevToolsTargetReturns return values. -type GetDevToolsTargetReturns struct { +// GetDevToolsTargetResult is the result of the command +// Target.getDevToolsTarget. +type GetDevToolsTargetResult struct { TargetID ID `json:"targetId,omitempty,omitzero"` // The targetId of DevTools page target if exists. } -// Do executes Target.getDevToolsTarget against the provided context. -// -// returns: +// GetDevToolsTarget gets the targetId of the DevTools page target opened for +// the given target (if any). // -// targetID - The targetId of DevTools page target if exists. -func (p *GetDevToolsTargetParams) Do(ctx context.Context) (targetID ID, err error) { - // execute - var res GetDevToolsTargetReturns - err = cdp.Execute(ctx, CommandGetDevToolsTarget, p, &res) - if err != nil { - return "", err - } - - return res.TargetID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-getDevToolsTarget +var GetDevToolsTarget = cdp.Command[GetDevToolsTargetParams, GetDevToolsTargetResult]{Method: CommandGetDevToolsTarget} -// OpenDevToolsParams opens a DevTools window for the target. +// OpenDevToolsParams are the parameters of the command Target.openDevTools. type OpenDevToolsParams struct { TargetID ID `json:"targetId"` // This can be the page or tab target ID. PanelID string `json:"panelId,omitempty,omitzero"` // The id of the panel we want DevTools to open initially. Currently supported panels are elements, console, network, sources, resources, timeline, chrome-recorder, heap-profiler, lighthouse, and security. } +// OpenDevToolsResult is the result of the command Target.openDevTools. +type OpenDevToolsResult struct { + TargetID ID `json:"targetId,omitempty,omitzero"` // The targetId of DevTools page target. +} + // OpenDevTools opens a DevTools window for the target. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-openDevTools +var OpenDevTools = cdp.Command[OpenDevToolsParams, OpenDevToolsResult]{Method: CommandOpenDevTools} + +// AttachedToTarget issued when attached to target because of auto-attach or +// attachToTarget command. // -// parameters: +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#event-attachedToTarget +var AttachedToTarget = cdp.Event[EventAttachedToTarget]{Method: "Target.attachedToTarget"} + +// DetachedFromTarget issued when detached from target for any reason +// (including detachFromTarget command). Can be issued multiple times per target +// if multiple sessions have been attached to it. // -// targetID - This can be the page or tab target ID. -func OpenDevTools(targetID ID) *OpenDevToolsParams { - return &OpenDevToolsParams{ - TargetID: targetID, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#event-detachedFromTarget +var DetachedFromTarget = cdp.Event[EventDetachedFromTarget]{Method: "Target.detachedFromTarget"} -// WithPanelID the id of the panel we want DevTools to open initially. -// Currently supported panels are elements, console, network, sources, -// resources, timeline, chrome-recorder, heap-profiler, lighthouse, and -// security. -func (p OpenDevToolsParams) WithPanelID(panelID string) *OpenDevToolsParams { - p.PanelID = panelID - return &p -} +// ReceivedMessageFromTarget notifies about a new protocol message received +// from the session (as reported in attachedToTarget event). +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#event-receivedMessageFromTarget +var ReceivedMessageFromTarget = cdp.Event[EventReceivedMessageFromTarget]{Method: "Target.receivedMessageFromTarget"} -// OpenDevToolsReturns return values. -type OpenDevToolsReturns struct { - TargetID ID `json:"targetId,omitempty,omitzero"` // The targetId of DevTools page target. -} +// TargetCreated issued when a possible inspection target is created. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#event-targetCreated +var TargetCreated = cdp.Event[EventTargetCreated]{Method: "Target.targetCreated"} + +// TargetDestroyed issued when a target is destroyed. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#event-targetDestroyed +var TargetDestroyed = cdp.Event[EventTargetDestroyed]{Method: "Target.targetDestroyed"} -// Do executes Target.openDevTools against the provided context. +// TargetCrashed issued when a target has crashed. // -// returns: +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#event-targetCrashed +var TargetCrashed = cdp.Event[EventTargetCrashed]{Method: "Target.targetCrashed"} + +// TargetInfoChanged issued when some information about a target has changed. +// This only happens between targetCreated and targetDestroyed. // -// targetID - The targetId of DevTools page target. -func (p *OpenDevToolsParams) Do(ctx context.Context) (targetID ID, err error) { - // execute - var res OpenDevToolsReturns - err = cdp.Execute(ctx, CommandOpenDevTools, p, &res) - if err != nil { - return "", err - } - - return res.TargetID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#event-targetInfoChanged +var TargetInfoChanged = cdp.Event[EventTargetInfoChanged]{Method: "Target.targetInfoChanged"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/target/types.go b/vendor/github.com/chromedp/cdproto/target/types.go index fde534f5b..1e92d6318 100644 --- a/vendor/github.com/chromedp/cdproto/target/types.go +++ b/vendor/github.com/chromedp/cdproto/target/types.go @@ -1,13 +1,10 @@ -package target +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package target import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/cdp" - "github.com/go-json-experiment/json/jsontext" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" ) // ID [no description]. @@ -46,7 +43,7 @@ type Info struct { ParentFrameID cdp.FrameID `json:"parentFrameId,omitempty,omitzero"` // Id of the parent frame, present for "iframe" and "worker" targets. For nested workers, this is the "ancestor" frame that created the first worker in the nested chain. BrowserContextID cdp.BrowserContextID `json:"browserContextId,omitempty,omitzero"` Subtype string `json:"subtype,omitempty,omitzero"` // Provides additional details for specific target types. For example, for the type of "page", this may be set to "prerender". - EmbedderData jsontext.Value `json:"embedderData,omitempty,omitzero"` + EmbedderData jsonv2.Value `json:"embedderData,omitempty,omitzero"` } // FilterEntry a filter used by target query/discovery/auto-attach @@ -95,23 +92,3 @@ const ( WindowStateMaximized WindowState = "maximized" WindowStateFullscreen WindowState = "fullscreen" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *WindowState) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch WindowState(s) { - case WindowStateNormal: - *t = WindowStateNormal - case WindowStateMinimized: - *t = WindowStateMinimized - case WindowStateMaximized: - *t = WindowStateMaximized - case WindowStateFullscreen: - *t = WindowStateFullscreen - default: - return fmt.Errorf("unknown WindowState value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/tethering/events.go b/vendor/github.com/chromedp/cdproto/tethering/events.go index 06e9576db..d0976c703 100644 --- a/vendor/github.com/chromedp/cdproto/tethering/events.go +++ b/vendor/github.com/chromedp/cdproto/tethering/events.go @@ -1,6 +1,6 @@ -package tethering +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package tethering // EventAccepted informs that port was successfully bound and got a specified // connection id. diff --git a/vendor/github.com/chromedp/cdproto/tethering/tethering.go b/vendor/github.com/chromedp/cdproto/tethering/tethering.go index 4b520142c..d83277f80 100644 --- a/vendor/github.com/chromedp/cdproto/tethering/tethering.go +++ b/vendor/github.com/chromedp/cdproto/tethering/tethering.go @@ -1,20 +1,18 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package tethering provides the Chrome DevTools Protocol // commands, types, and events for the Tethering domain. // // The Tethering domain defines methods and events for browser port binding. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package tethering -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// BindParams request browser port binding. +// BindParams are the parameters of the command Tethering.bind. type BindParams struct { Port int64 `json:"port"` // Port number to bind. } @@ -22,22 +20,9 @@ type BindParams struct { // Bind request browser port binding. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Tethering#method-bind -// -// parameters: -// -// port - Port number to bind. -func Bind(port int64) *BindParams { - return &BindParams{ - Port: port, - } -} +var Bind = cdp.Command[BindParams, cdp.Empty]{Method: CommandBind} -// Do executes Tethering.bind against the provided context. -func (p *BindParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandBind, p, nil) -} - -// UnbindParams request browser port unbinding. +// UnbindParams are the parameters of the command Tethering.unbind. type UnbindParams struct { Port int64 `json:"port"` // Port number to unbind. } @@ -45,20 +30,13 @@ type UnbindParams struct { // Unbind request browser port unbinding. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Tethering#method-unbind -// -// parameters: -// -// port - Port number to unbind. -func Unbind(port int64) *UnbindParams { - return &UnbindParams{ - Port: port, - } -} +var Unbind = cdp.Command[UnbindParams, cdp.Empty]{Method: CommandUnbind} -// Do executes Tethering.unbind against the provided context. -func (p *UnbindParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandUnbind, p, nil) -} +// Accepted informs that port was successfully bound and got a specified +// connection id. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Tethering#event-accepted +var Accepted = cdp.Event[EventAccepted]{Method: "Tethering.accepted"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/tracing/events.go b/vendor/github.com/chromedp/cdproto/tracing/events.go index c37764893..0be925dce 100644 --- a/vendor/github.com/chromedp/cdproto/tracing/events.go +++ b/vendor/github.com/chromedp/cdproto/tracing/events.go @@ -1,10 +1,10 @@ -package tracing +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package tracing import ( + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" "github.com/chromedp/cdproto/io" - "github.com/go-json-experiment/json/jsontext" ) // EventBufferUsage [no description]. @@ -22,7 +22,7 @@ type EventBufferUsage struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#event-dataCollected type EventDataCollected struct { - Value []jsontext.Value `json:"value"` + Value []jsonv2.Value `json:"value"` } // EventTracingComplete signals that tracing is stopped and there is no trace diff --git a/vendor/github.com/chromedp/cdproto/tracing/tracing.go b/vendor/github.com/chromedp/cdproto/tracing/tracing.go index 023512cfa..44d80a0c8 100644 --- a/vendor/github.com/chromedp/cdproto/tracing/tracing.go +++ b/vendor/github.com/chromedp/cdproto/tracing/tracing.go @@ -1,104 +1,44 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package tracing provides the Chrome DevTools Protocol // commands, types, and events for the Tracing domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package tracing -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "encoding/base64" - "github.com/chromedp/cdproto/cdp" ) -// EndParams stop trace events collection. -type EndParams struct{} - // End stop trace events collection. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-end -func End() *EndParams { - return &EndParams{} -} +var End = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnd} -// Do executes Tracing.end against the provided context. -func (p *EndParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnd, nil, nil) +// GetCategoriesResult is the result of the command Tracing.getCategories. +type GetCategoriesResult struct { + Categories []string `json:"categories,omitempty,omitzero"` // A list of supported tracing categories. } -// GetCategoriesParams gets supported tracing categories. -type GetCategoriesParams struct{} - // GetCategories gets supported tracing categories. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-getCategories -func GetCategories() *GetCategoriesParams { - return &GetCategoriesParams{} -} +var GetCategories = cdp.Command[cdp.Empty, GetCategoriesResult]{Method: CommandGetCategories} -// GetCategoriesReturns return values. -type GetCategoriesReturns struct { - Categories []string `json:"categories,omitempty,omitzero"` // A list of supported tracing categories. +// GetTrackEventDescriptorResult is the result of the command +// Tracing.getTrackEventDescriptor. +type GetTrackEventDescriptorResult struct { + Descriptor []byte `json:"descriptor,omitempty,omitzero"` // Base64-encoded serialized perfetto.protos.TrackEventDescriptor protobuf message. } -// Do executes Tracing.getCategories against the provided context. -// -// returns: -// -// categories - A list of supported tracing categories. -func (p *GetCategoriesParams) Do(ctx context.Context) (categories []string, err error) { - // execute - var res GetCategoriesReturns - err = cdp.Execute(ctx, CommandGetCategories, nil, &res) - if err != nil { - return nil, err - } - - return res.Categories, nil -} - -// GetTrackEventDescriptorParams return a descriptor for all available -// tracing categories. -type GetTrackEventDescriptorParams struct{} - // GetTrackEventDescriptor return a descriptor for all available tracing // categories. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-getTrackEventDescriptor -func GetTrackEventDescriptor() *GetTrackEventDescriptorParams { - return &GetTrackEventDescriptorParams{} -} +var GetTrackEventDescriptor = cdp.Command[cdp.Empty, GetTrackEventDescriptorResult]{Method: CommandGetTrackEventDescriptor} -// GetTrackEventDescriptorReturns return values. -type GetTrackEventDescriptorReturns struct { - Descriptor string `json:"descriptor,omitempty,omitzero"` // Base64-encoded serialized perfetto.protos.TrackEventDescriptor protobuf message. -} - -// Do executes Tracing.getTrackEventDescriptor against the provided context. -// -// returns: -// -// descriptor - Base64-encoded serialized perfetto.protos.TrackEventDescriptor protobuf message. -func (p *GetTrackEventDescriptorParams) Do(ctx context.Context) (descriptor []byte, err error) { - // execute - var res GetTrackEventDescriptorReturns - err = cdp.Execute(ctx, CommandGetTrackEventDescriptor, nil, &res) - if err != nil { - return nil, err - } - - // decode - var dec []byte - dec, err = base64.StdEncoding.DecodeString(res.Descriptor) - if err != nil { - return nil, err - } - return dec, nil -} - -// RecordClockSyncMarkerParams record a clock sync marker in the trace. +// RecordClockSyncMarkerParams are the parameters of the command +// Tracing.recordClockSyncMarker. type RecordClockSyncMarkerParams struct { SyncID string `json:"syncId"` // The ID of this clock sync marker } @@ -106,83 +46,35 @@ type RecordClockSyncMarkerParams struct { // RecordClockSyncMarker record a clock sync marker in the trace. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-recordClockSyncMarker -// -// parameters: -// -// syncID - The ID of this clock sync marker -func RecordClockSyncMarker(syncID string) *RecordClockSyncMarkerParams { - return &RecordClockSyncMarkerParams{ - SyncID: syncID, - } -} - -// Do executes Tracing.recordClockSyncMarker against the provided context. -func (p *RecordClockSyncMarkerParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRecordClockSyncMarker, p, nil) -} +var RecordClockSyncMarker = cdp.Command[RecordClockSyncMarkerParams, cdp.Empty]{Method: CommandRecordClockSyncMarker} -// RequestMemoryDumpParams request a global memory dump. +// RequestMemoryDumpParams are the parameters of the command +// Tracing.requestMemoryDump. type RequestMemoryDumpParams struct { - Deterministic bool `json:"deterministic"` // Enables more deterministic results by forcing garbage collection + Deterministic *bool `json:"deterministic,omitempty,omitzero"` // Enables more deterministic results by forcing garbage collection LevelOfDetail MemoryDumpLevelOfDetail `json:"levelOfDetail,omitempty,omitzero"` // Specifies level of details in memory dump. Defaults to "detailed". } -// RequestMemoryDump request a global memory dump. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-requestMemoryDump -// -// parameters: -func RequestMemoryDump() *RequestMemoryDumpParams { - return &RequestMemoryDumpParams{ - Deterministic: false, - } -} - -// WithDeterministic enables more deterministic results by forcing garbage -// collection. -func (p RequestMemoryDumpParams) WithDeterministic(deterministic bool) *RequestMemoryDumpParams { - p.Deterministic = deterministic - return &p -} - -// WithLevelOfDetail specifies level of details in memory dump. Defaults to -// "detailed". -func (p RequestMemoryDumpParams) WithLevelOfDetail(levelOfDetail MemoryDumpLevelOfDetail) *RequestMemoryDumpParams { - p.LevelOfDetail = levelOfDetail - return &p -} - -// RequestMemoryDumpReturns return values. -type RequestMemoryDumpReturns struct { +// RequestMemoryDumpResult is the result of the command +// Tracing.requestMemoryDump. +type RequestMemoryDumpResult struct { DumpGUID string `json:"dumpGuid,omitempty,omitzero"` // GUID of the resulting global memory dump. Success bool `json:"success"` // True iff the global memory dump succeeded. } -// Do executes Tracing.requestMemoryDump against the provided context. -// -// returns: +// RequestMemoryDump request a global memory dump. // -// dumpGUID - GUID of the resulting global memory dump. -// success - True iff the global memory dump succeeded. -func (p *RequestMemoryDumpParams) Do(ctx context.Context) (dumpGUID string, success bool, err error) { - // execute - var res RequestMemoryDumpReturns - err = cdp.Execute(ctx, CommandRequestMemoryDump, p, &res) - if err != nil { - return "", false, err - } - - return res.DumpGUID, res.Success, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-requestMemoryDump +var RequestMemoryDump = cdp.Command[RequestMemoryDumpParams, RequestMemoryDumpResult]{Method: CommandRequestMemoryDump} -// StartParams start trace events collection. +// StartParams are the parameters of the command Tracing.start. type StartParams struct { BufferUsageReportingInterval float64 `json:"bufferUsageReportingInterval,omitempty,omitzero"` // If set, the agent will issue bufferUsage events at this interval, specified in milliseconds - TransferMode TransferMode `json:"transferMode,omitempty,omitzero"` // Whether to report trace events as series of dataCollected events or to save trace to a stream (defaults to ReportEvents). + TransferMode StartTransferMode `json:"transferMode,omitempty,omitzero"` // Whether to report trace events as series of dataCollected events or to save trace to a stream (defaults to ReportEvents). StreamFormat StreamFormat `json:"streamFormat,omitempty,omitzero"` // Trace data format to use. This only applies when using ReturnAsStream transfer mode (defaults to json). StreamCompression StreamCompression `json:"streamCompression,omitempty,omitzero"` // Compression format to use. This only applies when using ReturnAsStream transfer mode (defaults to none) TraceConfig *TraceConfig `json:"traceConfig,omitempty,omitzero"` - PerfettoConfig string `json:"perfettoConfig,omitempty,omitzero"` // Base64-encoded serialized perfetto.protos.TraceConfig protobuf message When specified, the parameters categories, options, traceConfig are ignored. + PerfettoConfig []byte `json:"perfettoConfig,omitempty,omitzero"` // Base64-encoded serialized perfetto.protos.TraceConfig protobuf message When specified, the parameters categories, options, traceConfig are ignored. TracingBackend Backend `json:"tracingBackend,omitempty,omitzero"` // Backend type (defaults to auto) ScreenshotMaxSize int64 `json:"screenshotMaxSize,omitempty,omitzero"` // Maximum width and height (in pixels) of each captured screenshot. Only used when the disabled-by-default-devtools.screenshot category is enabled. Defaults to 500. The combined memory footprint of screenshots (screenshotMaxSize * screenshotMaxSize * 4 * screenshotMaxCount) is clamped to the existing per-session budget. ScreenshotMaxCount int64 `json:"screenshotMaxCount,omitempty,omitzero"` // Maximum number of screenshots captured during a single tracing session. Only used when the disabled-by-default-devtools.screenshot category is enabled. Defaults to 450. Clamped together with screenshotMaxSize to stay within the per-session screenshot memory budget. @@ -191,85 +83,25 @@ type StartParams struct { // Start start trace events collection. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-start -// -// parameters: -func Start() *StartParams { - return &StartParams{} -} - -// WithBufferUsageReportingInterval if set, the agent will issue bufferUsage -// events at this interval, specified in milliseconds. -func (p StartParams) WithBufferUsageReportingInterval(bufferUsageReportingInterval float64) *StartParams { - p.BufferUsageReportingInterval = bufferUsageReportingInterval - return &p -} - -// WithTransferMode whether to report trace events as series of dataCollected -// events or to save trace to a stream (defaults to ReportEvents). -func (p StartParams) WithTransferMode(transferMode TransferMode) *StartParams { - p.TransferMode = transferMode - return &p -} +var Start = cdp.Command[StartParams, cdp.Empty]{Method: CommandStart} -// WithStreamFormat trace data format to use. This only applies when using -// ReturnAsStream transfer mode (defaults to json). -func (p StartParams) WithStreamFormat(streamFormat StreamFormat) *StartParams { - p.StreamFormat = streamFormat - return &p -} - -// WithStreamCompression compression format to use. This only applies when -// using ReturnAsStream transfer mode (defaults to none). -func (p StartParams) WithStreamCompression(streamCompression StreamCompression) *StartParams { - p.StreamCompression = streamCompression - return &p -} - -// WithTraceConfig [no description]. -func (p StartParams) WithTraceConfig(traceConfig *TraceConfig) *StartParams { - p.TraceConfig = traceConfig - return &p -} - -// WithPerfettoConfig base64-encoded serialized perfetto.protos.TraceConfig -// protobuf message When specified, the parameters categories, options, -// traceConfig are ignored. -func (p StartParams) WithPerfettoConfig(perfettoConfig string) *StartParams { - p.PerfettoConfig = perfettoConfig - return &p -} - -// WithTracingBackend backend type (defaults to auto). -func (p StartParams) WithTracingBackend(tracingBackend Backend) *StartParams { - p.TracingBackend = tracingBackend - return &p -} - -// WithScreenshotMaxSize maximum width and height (in pixels) of each -// captured screenshot. Only used when the -// disabled-by-default-devtools.screenshot category is enabled. Defaults to 500. -// The combined memory footprint of screenshots (screenshotMaxSize * -// screenshotMaxSize * 4 * screenshotMaxCount) is clamped to the existing -// per-session budget. -func (p StartParams) WithScreenshotMaxSize(screenshotMaxSize int64) *StartParams { - p.ScreenshotMaxSize = screenshotMaxSize - return &p -} +// BufferUsage [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#event-bufferUsage +var BufferUsage = cdp.Event[EventBufferUsage]{Method: "Tracing.bufferUsage"} -// WithScreenshotMaxCount maximum number of screenshots captured during a -// single tracing session. Only used when the -// disabled-by-default-devtools.screenshot category is enabled. Defaults to 450. -// Clamped together with screenshotMaxSize to stay within the per-session -// screenshot memory budget. -func (p StartParams) WithScreenshotMaxCount(screenshotMaxCount int64) *StartParams { - p.ScreenshotMaxCount = screenshotMaxCount - return &p -} +// DataCollected contains a bucket of collected trace events. When tracing is +// stopped collected events will be sent as a sequence of dataCollected events +// followed by tracingComplete event. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#event-dataCollected +var DataCollected = cdp.Event[EventDataCollected]{Method: "Tracing.dataCollected"} -// Do executes Tracing.start against the provided context. -func (p *StartParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandStart, p, nil) -} +// TracingComplete signals that tracing is stopped and there is no trace +// buffers pending flush, all data were delivered via dataCollected events. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#event-tracingComplete +var TracingComplete = cdp.Event[EventTracingComplete]{Method: "Tracing.tracingComplete"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/tracing/types.go b/vendor/github.com/chromedp/cdproto/tracing/types.go index 4fed6caeb..b38aa1535 100644 --- a/vendor/github.com/chromedp/cdproto/tracing/types.go +++ b/vendor/github.com/chromedp/cdproto/tracing/types.go @@ -1,31 +1,26 @@ -package tracing - -import ( - "fmt" - "strings" -) +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package tracing // MemoryDumpConfig configuration for memory dump. Used only when // "memory-infra" category is enabled. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#type-MemoryDumpConfig -type MemoryDumpConfig struct{} +type MemoryDumpConfig map[string]any // TraceConfig [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#type-TraceConfig type TraceConfig struct { - RecordMode RecordMode `json:"recordMode,omitempty,omitzero"` // Controls how the trace buffer stores data. The default is recordUntilFull. - TraceBufferSizeInKb float64 `json:"traceBufferSizeInKb,omitempty,omitzero"` // Size of the trace buffer in kilobytes. If not specified or zero is passed, a default value of 200 MB would be used. - EnableSampling bool `json:"enableSampling"` // Turns on JavaScript stack sampling. - EnableSystrace bool `json:"enableSystrace"` // Turns on system tracing. - EnableArgumentFilter bool `json:"enableArgumentFilter"` // Turns on argument filter. - IncludedCategories []string `json:"includedCategories,omitempty,omitzero"` // Included category filters. - ExcludedCategories []string `json:"excludedCategories,omitempty,omitzero"` // Excluded category filters. - SyntheticDelays []string `json:"syntheticDelays,omitempty,omitzero"` // Configuration to synthesize the delays in tracing. - MemoryDumpConfig *MemoryDumpConfig `json:"memoryDumpConfig,omitempty,omitzero"` // Configuration for memory dump triggers. Used only when "memory-infra" category is enabled. + RecordMode TraceConfigRecordMode `json:"recordMode,omitempty,omitzero"` // Controls how the trace buffer stores data. The default is recordUntilFull. + TraceBufferSizeInKb float64 `json:"traceBufferSizeInKb,omitempty,omitzero"` // Size of the trace buffer in kilobytes. If not specified or zero is passed, a default value of 200 MB would be used. + EnableSampling bool `json:"enableSampling"` // Turns on JavaScript stack sampling. + EnableSystrace bool `json:"enableSystrace"` // Turns on system tracing. + EnableArgumentFilter bool `json:"enableArgumentFilter"` // Turns on argument filter. + IncludedCategories []string `json:"includedCategories,omitempty,omitzero"` // Included category filters. + ExcludedCategories []string `json:"excludedCategories,omitempty,omitzero"` // Excluded category filters. + SyntheticDelays []string `json:"syntheticDelays,omitempty,omitzero"` // Configuration to synthesize the delays in tracing. + MemoryDumpConfig MemoryDumpConfig `json:"memoryDumpConfig,omitempty,omitzero"` // Configuration for memory dump triggers. Used only when "memory-infra" category is enabled. } // StreamFormat data format of a trace. Can be either the legacy JSON format @@ -46,22 +41,6 @@ const ( StreamFormatProto StreamFormat = "proto" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *StreamFormat) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch StreamFormat(s) { - case StreamFormatJSON: - *t = StreamFormatJSON - case StreamFormatProto: - *t = StreamFormatProto - default: - return fmt.Errorf("unknown StreamFormat value: %v", s) - } - return nil -} - // StreamCompression compression type to use for traces returned via streams. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#type-StreamCompression @@ -78,22 +57,6 @@ const ( StreamCompressionGzip StreamCompression = "gzip" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *StreamCompression) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch StreamCompression(s) { - case StreamCompressionNone: - *t = StreamCompressionNone - case StreamCompressionGzip: - *t = StreamCompressionGzip - default: - return fmt.Errorf("unknown StreamCompression value: %v", s) - } - return nil -} - // MemoryDumpLevelOfDetail details exposed when memory request explicitly // declared. Keep consistent with memory_dump_request_args.h and // memory_instrumentation.mojom. @@ -113,24 +76,6 @@ const ( MemoryDumpLevelOfDetailDetailed MemoryDumpLevelOfDetail = "detailed" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *MemoryDumpLevelOfDetail) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch MemoryDumpLevelOfDetail(s) { - case MemoryDumpLevelOfDetailBackground: - *t = MemoryDumpLevelOfDetailBackground - case MemoryDumpLevelOfDetailLight: - *t = MemoryDumpLevelOfDetailLight - case MemoryDumpLevelOfDetailDetailed: - *t = MemoryDumpLevelOfDetailDetailed - default: - return fmt.Errorf("unknown MemoryDumpLevelOfDetail value: %v", s) - } - return nil -} - // Backend backend type to use for tracing. chrome uses the Chrome-integrated // tracing service and is supported on all platforms. system is only supported // on Chrome OS and uses the Perfetto system tracing service. auto chooses @@ -152,92 +97,38 @@ const ( BackendSystem Backend = "system" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *Backend) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch Backend(s) { - case BackendAuto: - *t = BackendAuto - case BackendChrome: - *t = BackendChrome - case BackendSystem: - *t = BackendSystem - default: - return fmt.Errorf("unknown Backend value: %v", s) - } - return nil -} - -// RecordMode controls how the trace buffer stores data. The default is -// recordUntilFull. +// TraceConfigRecordMode controls how the trace buffer stores data. The +// default is recordUntilFull. // // See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#type-TraceConfig -type RecordMode string +type TraceConfigRecordMode string -// String returns the RecordMode as string value. -func (t RecordMode) String() string { +// String returns the TraceConfigRecordMode as string value. +func (t TraceConfigRecordMode) String() string { return string(t) } -// RecordMode values. +// TraceConfigRecordMode values. const ( - RecordModeRecordUntilFull RecordMode = "recordUntilFull" - RecordModeRecordContinuously RecordMode = "recordContinuously" - RecordModeRecordAsMuchAsPossible RecordMode = "recordAsMuchAsPossible" - RecordModeEchoToConsole RecordMode = "echoToConsole" + TraceConfigRecordModeRecordUntilFull TraceConfigRecordMode = "recordUntilFull" + TraceConfigRecordModeRecordContinuously TraceConfigRecordMode = "recordContinuously" + TraceConfigRecordModeRecordAsMuchAsPossible TraceConfigRecordMode = "recordAsMuchAsPossible" + TraceConfigRecordModeEchoToConsole TraceConfigRecordMode = "echoToConsole" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *RecordMode) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch RecordMode(s) { - case RecordModeRecordUntilFull: - *t = RecordModeRecordUntilFull - case RecordModeRecordContinuously: - *t = RecordModeRecordContinuously - case RecordModeRecordAsMuchAsPossible: - *t = RecordModeRecordAsMuchAsPossible - case RecordModeEchoToConsole: - *t = RecordModeEchoToConsole - default: - return fmt.Errorf("unknown RecordMode value: %v", s) - } - return nil -} - -// TransferMode whether to report trace events as series of dataCollected -// events or to save trace to a stream (defaults to ReportEvents). +// StartTransferMode whether to report trace events as series of +// dataCollected events or to save trace to a stream (defaults to ReportEvents). // // See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-start -type TransferMode string +type StartTransferMode string -// String returns the TransferMode as string value. -func (t TransferMode) String() string { +// String returns the StartTransferMode as string value. +func (t StartTransferMode) String() string { return string(t) } -// TransferMode values. +// StartTransferMode values. const ( - TransferModeReportEvents TransferMode = "ReportEvents" - TransferModeReturnAsStream TransferMode = "ReturnAsStream" + StartTransferModeReportEvents StartTransferMode = "ReportEvents" + StartTransferModeReturnAsStream StartTransferMode = "ReturnAsStream" ) - -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *TransferMode) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch TransferMode(s) { - case TransferModeReportEvents: - *t = TransferModeReportEvents - case TransferModeReturnAsStream: - *t = TransferModeReturnAsStream - default: - return fmt.Errorf("unknown TransferMode value: %v", s) - } - return nil -} diff --git a/vendor/github.com/chromedp/cdproto/version.go b/vendor/github.com/chromedp/cdproto/version.go new file mode 100644 index 000000000..477bc2b17 --- /dev/null +++ b/vendor/github.com/chromedp/cdproto/version.go @@ -0,0 +1,23 @@ +// Code generated by pdlgen. DO NOT EDIT. + +package cdproto + +// The versions of the protocol definitions that the generator read to write +// this package. +const ( + chromiumVersion = "158.0.8110.1" + v8Version = "15.8.17" +) + +// ChromiumVersion returns the Chromium version of the browser protocol +// definitions (browser_protocol.pdl) that the generator read to write this +// package. +func ChromiumVersion() string { + return chromiumVersion +} + +// V8Version returns the V8 version of the JavaScript protocol definitions +// (js_protocol.pdl) that the generator read to write this package. +func V8Version() string { + return v8Version +} diff --git a/vendor/github.com/chromedp/cdproto/webaudio/events.go b/vendor/github.com/chromedp/cdproto/webaudio/events.go index 37a6ddaf0..330dce38e 100644 --- a/vendor/github.com/chromedp/cdproto/webaudio/events.go +++ b/vendor/github.com/chromedp/cdproto/webaudio/events.go @@ -1,6 +1,6 @@ -package webaudio +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package webaudio // EventContextCreated notifies that a new BaseAudioContext has been created. // diff --git a/vendor/github.com/chromedp/cdproto/webaudio/types.go b/vendor/github.com/chromedp/cdproto/webaudio/types.go index a49e7d862..d51a4bb55 100644 --- a/vendor/github.com/chromedp/cdproto/webaudio/types.go +++ b/vendor/github.com/chromedp/cdproto/webaudio/types.go @@ -1,13 +1,6 @@ -package webaudio - -// Code generated by cdproto-gen. DO NOT EDIT. - -import ( - "fmt" - "strings" +// Code generated by pdlgen. DO NOT EDIT. - "github.com/chromedp/cdproto/cdp" -) +package webaudio // GraphObjectID an unique ID for a graph object (AudioContext, AudioNode, // AudioParam) in Web Audio API. @@ -36,22 +29,6 @@ const ( ContextTypeOffline ContextType = "offline" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ContextType) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ContextType(s) { - case ContextTypeRealtime: - *t = ContextTypeRealtime - case ContextTypeOffline: - *t = ContextTypeOffline - default: - return fmt.Errorf("unknown ContextType value: %v", s) - } - return nil -} - // ContextState enum of AudioContextState from the spec. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#type-ContextState @@ -70,26 +47,6 @@ const ( ContextStateInterrupted ContextState = "interrupted" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ContextState) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ContextState(s) { - case ContextStateSuspended: - *t = ContextStateSuspended - case ContextStateRunning: - *t = ContextStateRunning - case ContextStateClosed: - *t = ContextStateClosed - case ContextStateInterrupted: - *t = ContextStateInterrupted - default: - return fmt.Errorf("unknown ContextState value: %v", s) - } - return nil -} - // NodeType enum of AudioNode types. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#type-NodeType @@ -117,24 +74,6 @@ const ( ChannelCountModeMax ChannelCountMode = "max" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ChannelCountMode) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ChannelCountMode(s) { - case ChannelCountModeClampedMax: - *t = ChannelCountModeClampedMax - case ChannelCountModeExplicit: - *t = ChannelCountModeExplicit - case ChannelCountModeMax: - *t = ChannelCountModeMax - default: - return fmt.Errorf("unknown ChannelCountMode value: %v", s) - } - return nil -} - // ChannelInterpretation enum of AudioNode::ChannelInterpretation from the // spec. // @@ -152,22 +91,6 @@ const ( ChannelInterpretationSpeakers ChannelInterpretation = "speakers" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *ChannelInterpretation) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch ChannelInterpretation(s) { - case ChannelInterpretationDiscrete: - *t = ChannelInterpretationDiscrete - case ChannelInterpretationSpeakers: - *t = ChannelInterpretationSpeakers - default: - return fmt.Errorf("unknown ChannelInterpretation value: %v", s) - } - return nil -} - // ParamType enum of AudioParam types. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#type-ParamType @@ -194,22 +117,6 @@ const ( AutomationRateKRate AutomationRate = "k-rate" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *AutomationRate) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch AutomationRate(s) { - case AutomationRateARate: - *t = AutomationRateARate - case AutomationRateKRate: - *t = AutomationRateKRate - default: - return fmt.Errorf("unknown AutomationRate value: %v", s) - } - return nil -} - // ContextRealtimeData fields in AudioContext that change in real-time. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#type-ContextRealtimeData @@ -231,6 +138,7 @@ type BaseAudioContext struct { CallbackBufferSize float64 `json:"callbackBufferSize"` // Platform-dependent callback buffer size. MaxOutputChannelCount float64 `json:"maxOutputChannelCount"` // Number of output channels supported by audio hardware in use. SampleRate float64 `json:"sampleRate"` // Context sample rate. + RenderQuantumSize float64 `json:"renderQuantumSize"` } // AudioListener protocol object for AudioListener. @@ -247,7 +155,7 @@ type AudioListener struct { type AudioNode struct { NodeID GraphObjectID `json:"nodeId"` ContextID GraphObjectID `json:"contextId"` - NodeType cdp.NodeType `json:"nodeType"` + NodeType NodeType `json:"nodeType"` NumberOfInputs float64 `json:"numberOfInputs"` NumberOfOutputs float64 `json:"numberOfOutputs"` ChannelCount float64 `json:"channelCount"` diff --git a/vendor/github.com/chromedp/cdproto/webaudio/webaudio.go b/vendor/github.com/chromedp/cdproto/webaudio/webaudio.go index 7d6f65f6e..3d30069da 100644 --- a/vendor/github.com/chromedp/cdproto/webaudio/webaudio.go +++ b/vendor/github.com/chromedp/cdproto/webaudio/webaudio.go @@ -1,91 +1,120 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package webaudio provides the Chrome DevTools Protocol // commands, types, and events for the WebAudio domain. // // This domain allows inspection of Web Audio API. // https://webaudio.github.io/web-audio-api/. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package webaudio -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// EnableParams enables the WebAudio domain and starts sending context -// lifetime events. -type EnableParams struct{} - // Enable enables the WebAudio domain and starts sending context lifetime // events. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} - -// Do executes WebAudio.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) -} - -// DisableParams disables the WebAudio domain. -type DisableParams struct{} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} // Disable disables the WebAudio domain. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} -// Do executes WebAudio.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} - -// GetRealtimeDataParams fetch the realtime data from the registered -// contexts. +// GetRealtimeDataParams are the parameters of the command +// WebAudio.getRealtimeData. type GetRealtimeDataParams struct { ContextID GraphObjectID `json:"contextId"` } +// GetRealtimeDataResult is the result of the command +// WebAudio.getRealtimeData. +type GetRealtimeDataResult struct { + RealtimeData *ContextRealtimeData `json:"realtimeData,omitempty,omitzero"` +} + // GetRealtimeData fetch the realtime data from the registered contexts. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#method-getRealtimeData +var GetRealtimeData = cdp.Command[GetRealtimeDataParams, GetRealtimeDataResult]{Method: CommandGetRealtimeData} + +// ContextCreated notifies that a new BaseAudioContext has been created. // -// parameters: +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#event-contextCreated +var ContextCreated = cdp.Event[EventContextCreated]{Method: "WebAudio.contextCreated"} + +// ContextWillBeDestroyed notifies that an existing BaseAudioContext will be +// destroyed. // -// contextID -func GetRealtimeData(contextID GraphObjectID) *GetRealtimeDataParams { - return &GetRealtimeDataParams{ - ContextID: contextID, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#event-contextWillBeDestroyed +var ContextWillBeDestroyed = cdp.Event[EventContextWillBeDestroyed]{Method: "WebAudio.contextWillBeDestroyed"} -// GetRealtimeDataReturns return values. -type GetRealtimeDataReturns struct { - RealtimeData *ContextRealtimeData `json:"realtimeData,omitempty,omitzero"` -} +// ContextChanged notifies that existing BaseAudioContext has changed some +// properties (id stays the same).. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#event-contextChanged +var ContextChanged = cdp.Event[EventContextChanged]{Method: "WebAudio.contextChanged"} -// Do executes WebAudio.getRealtimeData against the provided context. +// AudioListenerCreated notifies that the construction of an AudioListener +// has finished. // -// returns: +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#event-audioListenerCreated +var AudioListenerCreated = cdp.Event[EventAudioListenerCreated]{Method: "WebAudio.audioListenerCreated"} + +// AudioListenerWillBeDestroyed notifies that a new AudioListener has been +// created. // -// realtimeData -func (p *GetRealtimeDataParams) Do(ctx context.Context) (realtimeData *ContextRealtimeData, err error) { - // execute - var res GetRealtimeDataReturns - err = cdp.Execute(ctx, CommandGetRealtimeData, p, &res) - if err != nil { - return nil, err - } +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#event-audioListenerWillBeDestroyed +var AudioListenerWillBeDestroyed = cdp.Event[EventAudioListenerWillBeDestroyed]{Method: "WebAudio.audioListenerWillBeDestroyed"} - return res.RealtimeData, nil -} +// AudioNodeCreated notifies that a new AudioNode has been created. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#event-audioNodeCreated +var AudioNodeCreated = cdp.Event[EventAudioNodeCreated]{Method: "WebAudio.audioNodeCreated"} + +// AudioNodeWillBeDestroyed notifies that an existing AudioNode has been +// destroyed. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#event-audioNodeWillBeDestroyed +var AudioNodeWillBeDestroyed = cdp.Event[EventAudioNodeWillBeDestroyed]{Method: "WebAudio.audioNodeWillBeDestroyed"} + +// AudioParamCreated notifies that a new AudioParam has been created. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#event-audioParamCreated +var AudioParamCreated = cdp.Event[EventAudioParamCreated]{Method: "WebAudio.audioParamCreated"} + +// AudioParamWillBeDestroyed notifies that an existing AudioParam has been +// destroyed. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#event-audioParamWillBeDestroyed +var AudioParamWillBeDestroyed = cdp.Event[EventAudioParamWillBeDestroyed]{Method: "WebAudio.audioParamWillBeDestroyed"} + +// NodesConnected notifies that two AudioNodes are connected. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#event-nodesConnected +var NodesConnected = cdp.Event[EventNodesConnected]{Method: "WebAudio.nodesConnected"} + +// NodesDisconnected notifies that AudioNodes are disconnected. The +// destination can be null, and it means all the outgoing connections from the +// source are disconnected. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#event-nodesDisconnected +var NodesDisconnected = cdp.Event[EventNodesDisconnected]{Method: "WebAudio.nodesDisconnected"} + +// NodeParamConnected notifies that an AudioNode is connected to an +// AudioParam. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#event-nodeParamConnected +var NodeParamConnected = cdp.Event[EventNodeParamConnected]{Method: "WebAudio.nodeParamConnected"} + +// NodeParamDisconnected notifies that an AudioNode is disconnected to an +// AudioParam. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#event-nodeParamDisconnected +var NodeParamDisconnected = cdp.Event[EventNodeParamDisconnected]{Method: "WebAudio.nodeParamDisconnected"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/webauthn/events.go b/vendor/github.com/chromedp/cdproto/webauthn/events.go index f25d5cd83..568271aa8 100644 --- a/vendor/github.com/chromedp/cdproto/webauthn/events.go +++ b/vendor/github.com/chromedp/cdproto/webauthn/events.go @@ -1,6 +1,6 @@ -package webauthn +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package webauthn // EventCredentialAdded triggered when a credential is added to an // authenticator. @@ -17,7 +17,7 @@ type EventCredentialAdded struct { // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#event-credentialDeleted type EventCredentialDeleted struct { AuthenticatorID AuthenticatorID `json:"authenticatorId"` - CredentialID string `json:"credentialId"` + CredentialID []byte `json:"credentialId"` } // EventCredentialUpdated triggered when a credential is updated, e.g. diff --git a/vendor/github.com/chromedp/cdproto/webauthn/types.go b/vendor/github.com/chromedp/cdproto/webauthn/types.go index f898c0c94..2e68938c5 100644 --- a/vendor/github.com/chromedp/cdproto/webauthn/types.go +++ b/vendor/github.com/chromedp/cdproto/webauthn/types.go @@ -1,11 +1,6 @@ -package webauthn - -import ( - "fmt" - "strings" -) +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package webauthn // AuthenticatorID [no description]. // @@ -33,22 +28,6 @@ const ( AuthenticatorProtocolCtap2 AuthenticatorProtocol = "ctap2" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *AuthenticatorProtocol) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch AuthenticatorProtocol(s) { - case AuthenticatorProtocolU2f: - *t = AuthenticatorProtocolU2f - case AuthenticatorProtocolCtap2: - *t = AuthenticatorProtocolCtap2 - default: - return fmt.Errorf("unknown AuthenticatorProtocol value: %v", s) - } - return nil -} - // Ctap2version [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#type-Ctap2Version @@ -66,25 +45,7 @@ const ( Ctap2versionCtap22 Ctap2version = "ctap2_2" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *Ctap2version) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch Ctap2version(s) { - case Ctap2versionCtap20: - *t = Ctap2versionCtap20 - case Ctap2versionCtap21: - *t = Ctap2versionCtap21 - case Ctap2versionCtap22: - *t = Ctap2versionCtap22 - default: - return fmt.Errorf("unknown Ctap2version value: %v", s) - } - return nil -} - -// AuthenticatorTransport [no description]. +// AuthenticatorTransport LINT.IfChange(AuthenticatorTransport). // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#type-AuthenticatorTransport type AuthenticatorTransport string @@ -96,35 +57,15 @@ func (t AuthenticatorTransport) String() string { // AuthenticatorTransport values. const ( - AuthenticatorTransportUsb AuthenticatorTransport = "usb" - AuthenticatorTransportNfc AuthenticatorTransport = "nfc" - AuthenticatorTransportBle AuthenticatorTransport = "ble" - AuthenticatorTransportCable AuthenticatorTransport = "cable" - AuthenticatorTransportInternal AuthenticatorTransport = "internal" + AuthenticatorTransportUsb AuthenticatorTransport = "usb" + AuthenticatorTransportNfc AuthenticatorTransport = "nfc" + AuthenticatorTransportBle AuthenticatorTransport = "ble" + AuthenticatorTransportCable AuthenticatorTransport = "cable" + AuthenticatorTransportHybrid AuthenticatorTransport = "hybrid" + AuthenticatorTransportSmartCard AuthenticatorTransport = "smart-card" + AuthenticatorTransportInternal AuthenticatorTransport = "internal" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *AuthenticatorTransport) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch AuthenticatorTransport(s) { - case AuthenticatorTransportUsb: - *t = AuthenticatorTransportUsb - case AuthenticatorTransportNfc: - *t = AuthenticatorTransportNfc - case AuthenticatorTransportBle: - *t = AuthenticatorTransportBle - case AuthenticatorTransportCable: - *t = AuthenticatorTransportCable - case AuthenticatorTransportInternal: - *t = AuthenticatorTransportInternal - default: - return fmt.Errorf("unknown AuthenticatorTransport value: %v", s) - } - return nil -} - // VirtualAuthenticatorOptions [no description]. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#type-VirtualAuthenticatorOptions @@ -140,6 +81,7 @@ type VirtualAuthenticatorOptions struct { HasPrf bool `json:"hasPrf"` // If set to true, the authenticator will support the prf extension. https://w3c.github.io/webauthn/#prf-extension Defaults to false. HasHmacSecret bool `json:"hasHmacSecret"` // If set to true, the authenticator will support the hmac-secret extension. https://fidoalliance.org/specs/fido-v2.1-ps-20210615/fido-client-to-authenticator-protocol-v2.1-ps-20210615.html#sctn-hmac-secret-extension Defaults to false. HasHmacSecretMc bool `json:"hasHmacSecretMc"` // If set to true, the authenticator will support the hmac-secret-mc extension. https://fidoalliance.org/specs/fido-v2.2-rd-20241003/fido-client-to-authenticator-protocol-v2.2-rd-20241003.html#sctn-hmac-secret-make-cred-extension Defaults to false. + HasCmtgKey bool `json:"hasCmtgKey"` // If set to true, the authenticator will support the cmtgKey (Credential Manager Trust Group Key) extension. https://github.com/w3c/webauthn/pull/2377 Defaults to false. AutomaticPresenceSimulation bool `json:"automaticPresenceSimulation"` // If set to true, tests of user presence will succeed immediately. Otherwise, they will not be resolved. Defaults to true. IsUserVerified bool `json:"isUserVerified"` // Sets whether User Verification succeeds or fails for an authenticator. Defaults to false. DefaultBackupEligibility bool `json:"defaultBackupEligibility"` // Credentials created by this authenticator will have the backup eligibility (BE) flag set to this value. Defaults to false. https://w3c.github.io/webauthn/#sctn-credential-backup @@ -150,15 +92,18 @@ type VirtualAuthenticatorOptions struct { // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#type-Credential type Credential struct { - CredentialID string `json:"credentialId"` - IsResidentCredential bool `json:"isResidentCredential"` - RpID string `json:"rpId,omitempty,omitzero"` // Relying Party ID the credential is scoped to. Must be set when adding a credential. - PrivateKey string `json:"privateKey"` // The ECDSA P-256 private key in PKCS#8 format. - UserHandle string `json:"userHandle,omitempty,omitzero"` // An opaque byte sequence with a maximum size of 64 bytes mapping the credential to a specific user. - SignCount int64 `json:"signCount"` // Signature counter. This is incremented by one for each successful assertion. See https://w3c.github.io/webauthn/#signature-counter - LargeBlob string `json:"largeBlob,omitempty,omitzero"` // The large blob associated with the credential. See https://w3c.github.io/webauthn/#sctn-large-blob-extension - BackupEligibility bool `json:"backupEligibility"` // Assertions returned by this credential will have the backup eligibility (BE) flag set to this value. Defaults to the authenticator's defaultBackupEligibility value. - BackupState bool `json:"backupState"` // Assertions returned by this credential will have the backup state (BS) flag set to this value. Defaults to the authenticator's defaultBackupState value. - UserName string `json:"userName,omitempty,omitzero"` // The credential's user.name property. Equivalent to empty if not set. https://w3c.github.io/webauthn/#dom-publickeycredentialentity-name - UserDisplayName string `json:"userDisplayName,omitempty,omitzero"` // The credential's user.displayName property. Equivalent to empty if not set. https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-displayname + CredentialID []byte `json:"credentialId"` + IsResidentCredential bool `json:"isResidentCredential"` + RpID string `json:"rpId,omitempty,omitzero"` // Relying Party ID the credential is scoped to. Must be set when adding a credential. + PrivateKey []byte `json:"privateKey"` // The ECDSA P-256 private key in PKCS#8 format. + UserHandle []byte `json:"userHandle,omitempty,omitzero"` // An opaque byte sequence with a maximum size of 64 bytes mapping the credential to a specific user. + SignCount float64 `json:"signCount"` // Signature counter. Must be equal to or greater than -1. If -1, the credential won't have an associated signature counter, and every assertion operation will report a value of 0. See https://w3c.github.io/webauthn/#signature-counter + LargeBlob []byte `json:"largeBlob,omitempty,omitzero"` // The large blob associated with the credential. See https://w3c.github.io/webauthn/#sctn-large-blob-extension + BackupEligibility bool `json:"backupEligibility"` // Assertions returned by this credential will have the backup eligibility (BE) flag set to this value. Defaults to the authenticator's defaultBackupEligibility value. + BackupState bool `json:"backupState"` // Assertions returned by this credential will have the backup state (BS) flag set to this value. Defaults to the authenticator's defaultBackupState value. + UserName string `json:"userName,omitempty,omitzero"` // The credential's user.name property. Equivalent to empty if not set. https://w3c.github.io/webauthn/#dom-publickeycredentialentity-name + UserDisplayName string `json:"userDisplayName,omitempty,omitzero"` // The credential's user.displayName property. Equivalent to empty if not set. https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-displayname + CmtgKeys [][]byte `json:"cmtgKeys,omitempty,omitzero"` // The CMTG keys associated with the credential. + ActiveCmtgKeyIndex *int64 `json:"activeCmtgKeyIndex,omitempty,omitzero"` // The 0-based index of the active key in cmtgKeys. + GenerateCmtgKeyOnNextOperation bool `json:"generateCmtgKeyOnNextOperation"` // If true, the authenticator will generate a new CMTG key on the next operation. } diff --git a/vendor/github.com/chromedp/cdproto/webauthn/webauthn.go b/vendor/github.com/chromedp/cdproto/webauthn/webauthn.go index 9bd972216..2bfbdaf53 100644 --- a/vendor/github.com/chromedp/cdproto/webauthn/webauthn.go +++ b/vendor/github.com/chromedp/cdproto/webauthn/webauthn.go @@ -1,159 +1,68 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package webauthn provides the Chrome DevTools Protocol // commands, types, and events for the WebAuthn domain. // // This domain allows configuring virtual authenticators to test the WebAuthn // API. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package webauthn -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" ) -// EnableParams enable the WebAuthn domain and start intercepting credential -// storage and retrieval with a virtual authenticator. +// EnableParams are the parameters of the command WebAuthn.enable. type EnableParams struct { - EnableUI bool `json:"enableUI"` // Whether to enable the WebAuthn user interface. Enabling the UI is recommended for debugging and demo purposes, as it is closer to the real experience. Disabling the UI is recommended for automated testing. Supported at the embedder's discretion if UI is available. Defaults to false. + EnableUI *bool `json:"enableUI,omitempty,omitzero"` // Whether to enable the WebAuthn user interface. Enabling the UI is recommended for debugging and demo purposes, as it is closer to the real experience. Disabling the UI is recommended for automated testing. Supported at the embedder's discretion if UI is available. Defaults to false. } // Enable enable the WebAuthn domain and start intercepting credential // storage and retrieval with a virtual authenticator. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-enable -// -// parameters: -func Enable() *EnableParams { - return &EnableParams{ - EnableUI: false, - } -} - -// WithEnableUI whether to enable the WebAuthn user interface. Enabling the -// UI is recommended for debugging and demo purposes, as it is closer to the -// real experience. Disabling the UI is recommended for automated testing. -// Supported at the embedder's discretion if UI is available. Defaults to false. -func (p EnableParams) WithEnableUI(enableUI bool) *EnableParams { - p.EnableUI = enableUI - return &p -} - -// Do executes WebAuthn.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, p, nil) -} - -// DisableParams disable the WebAuthn domain. -type DisableParams struct{} +var Enable = cdp.Command[EnableParams, cdp.Empty]{Method: CommandEnable} // Disable disable the WebAuthn domain. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes WebAuthn.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} -// AddVirtualAuthenticatorParams creates and adds a virtual authenticator. +// AddVirtualAuthenticatorParams are the parameters of the command +// WebAuthn.addVirtualAuthenticator. type AddVirtualAuthenticatorParams struct { Options *VirtualAuthenticatorOptions `json:"options"` } -// AddVirtualAuthenticator creates and adds a virtual authenticator. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-addVirtualAuthenticator -// -// parameters: -// -// options -func AddVirtualAuthenticator(options *VirtualAuthenticatorOptions) *AddVirtualAuthenticatorParams { - return &AddVirtualAuthenticatorParams{ - Options: options, - } -} - -// AddVirtualAuthenticatorReturns return values. -type AddVirtualAuthenticatorReturns struct { +// AddVirtualAuthenticatorResult is the result of the command +// WebAuthn.addVirtualAuthenticator. +type AddVirtualAuthenticatorResult struct { AuthenticatorID AuthenticatorID `json:"authenticatorId,omitempty,omitzero"` } -// Do executes WebAuthn.addVirtualAuthenticator against the provided context. -// -// returns: +// AddVirtualAuthenticator creates and adds a virtual authenticator. // -// authenticatorID -func (p *AddVirtualAuthenticatorParams) Do(ctx context.Context) (authenticatorID AuthenticatorID, err error) { - // execute - var res AddVirtualAuthenticatorReturns - err = cdp.Execute(ctx, CommandAddVirtualAuthenticator, p, &res) - if err != nil { - return "", err - } - - return res.AuthenticatorID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-addVirtualAuthenticator +var AddVirtualAuthenticator = cdp.Command[AddVirtualAuthenticatorParams, AddVirtualAuthenticatorResult]{Method: CommandAddVirtualAuthenticator} -// SetResponseOverrideBitsParams resets parameters isBogusSignature, isBadUV, -// isBadUP to false if they are not present. +// SetResponseOverrideBitsParams are the parameters of the command +// WebAuthn.setResponseOverrideBits. type SetResponseOverrideBitsParams struct { AuthenticatorID AuthenticatorID `json:"authenticatorId"` - IsBogusSignature bool `json:"isBogusSignature"` // If isBogusSignature is set, overrides the signature in the authenticator response to be zero. Defaults to false. - IsBadUV bool `json:"isBadUV"` // If isBadUV is set, overrides the UV bit in the flags in the authenticator response to be zero. Defaults to false. - IsBadUP bool `json:"isBadUP"` // If isBadUP is set, overrides the UP bit in the flags in the authenticator response to be zero. Defaults to false. + IsBogusSignature *bool `json:"isBogusSignature,omitempty,omitzero"` // If isBogusSignature is set, overrides the signature in the authenticator response to be zero. Defaults to false. + IsBadUV *bool `json:"isBadUV,omitempty,omitzero"` // If isBadUV is set, overrides the UV bit in the flags in the authenticator response to be zero. Defaults to false. + IsBadUP *bool `json:"isBadUP,omitempty,omitzero"` // If isBadUP is set, overrides the UP bit in the flags in the authenticator response to be zero. Defaults to false. } // SetResponseOverrideBits resets parameters isBogusSignature, isBadUV, // isBadUP to false if they are not present. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-setResponseOverrideBits -// -// parameters: -// -// authenticatorID -func SetResponseOverrideBits(authenticatorID AuthenticatorID) *SetResponseOverrideBitsParams { - return &SetResponseOverrideBitsParams{ - AuthenticatorID: authenticatorID, - IsBogusSignature: false, - IsBadUV: false, - IsBadUP: false, - } -} - -// WithIsBogusSignature if isBogusSignature is set, overrides the signature -// in the authenticator response to be zero. Defaults to false. -func (p SetResponseOverrideBitsParams) WithIsBogusSignature(isBogusSignature bool) *SetResponseOverrideBitsParams { - p.IsBogusSignature = isBogusSignature - return &p -} - -// WithIsBadUV if isBadUV is set, overrides the UV bit in the flags in the -// authenticator response to be zero. Defaults to false. -func (p SetResponseOverrideBitsParams) WithIsBadUV(isBadUV bool) *SetResponseOverrideBitsParams { - p.IsBadUV = isBadUV - return &p -} +var SetResponseOverrideBits = cdp.Command[SetResponseOverrideBitsParams, cdp.Empty]{Method: CommandSetResponseOverrideBits} -// WithIsBadUP if isBadUP is set, overrides the UP bit in the flags in the -// authenticator response to be zero. Defaults to false. -func (p SetResponseOverrideBitsParams) WithIsBadUP(isBadUP bool) *SetResponseOverrideBitsParams { - p.IsBadUP = isBadUP - return &p -} - -// Do executes WebAuthn.setResponseOverrideBits against the provided context. -func (p *SetResponseOverrideBitsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetResponseOverrideBits, p, nil) -} - -// RemoveVirtualAuthenticatorParams removes the given authenticator. +// RemoveVirtualAuthenticatorParams are the parameters of the command +// WebAuthn.removeVirtualAuthenticator. type RemoveVirtualAuthenticatorParams struct { AuthenticatorID AuthenticatorID `json:"authenticatorId"` } @@ -161,22 +70,10 @@ type RemoveVirtualAuthenticatorParams struct { // RemoveVirtualAuthenticator removes the given authenticator. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-removeVirtualAuthenticator -// -// parameters: -// -// authenticatorID -func RemoveVirtualAuthenticator(authenticatorID AuthenticatorID) *RemoveVirtualAuthenticatorParams { - return &RemoveVirtualAuthenticatorParams{ - AuthenticatorID: authenticatorID, - } -} - -// Do executes WebAuthn.removeVirtualAuthenticator against the provided context. -func (p *RemoveVirtualAuthenticatorParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRemoveVirtualAuthenticator, p, nil) -} +var RemoveVirtualAuthenticator = cdp.Command[RemoveVirtualAuthenticatorParams, cdp.Empty]{Method: CommandRemoveVirtualAuthenticator} -// AddCredentialParams adds the credential to the specified authenticator. +// AddCredentialParams are the parameters of the command +// WebAuthn.addCredential. type AddCredentialParams struct { AuthenticatorID AuthenticatorID `json:"authenticatorId"` Credential *Credential `json:"credential"` @@ -185,136 +82,57 @@ type AddCredentialParams struct { // AddCredential adds the credential to the specified authenticator. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-addCredential -// -// parameters: -// -// authenticatorID -// credential -func AddCredential(authenticatorID AuthenticatorID, credential *Credential) *AddCredentialParams { - return &AddCredentialParams{ - AuthenticatorID: authenticatorID, - Credential: credential, - } -} +var AddCredential = cdp.Command[AddCredentialParams, cdp.Empty]{Method: CommandAddCredential} -// Do executes WebAuthn.addCredential against the provided context. -func (p *AddCredentialParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandAddCredential, p, nil) -} - -// GetCredentialParams returns a single credential stored in the given -// virtual authenticator that matches the credential ID. +// GetCredentialParams are the parameters of the command +// WebAuthn.getCredential. type GetCredentialParams struct { AuthenticatorID AuthenticatorID `json:"authenticatorId"` - CredentialID string `json:"credentialId"` -} - -// GetCredential returns a single credential stored in the given virtual -// authenticator that matches the credential ID. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-getCredential -// -// parameters: -// -// authenticatorID -// credentialID -func GetCredential(authenticatorID AuthenticatorID, credentialID string) *GetCredentialParams { - return &GetCredentialParams{ - AuthenticatorID: authenticatorID, - CredentialID: credentialID, - } + CredentialID []byte `json:"credentialId"` } -// GetCredentialReturns return values. -type GetCredentialReturns struct { +// GetCredentialResult is the result of the command WebAuthn.getCredential. +type GetCredentialResult struct { Credential *Credential `json:"credential,omitempty,omitzero"` } -// Do executes WebAuthn.getCredential against the provided context. -// -// returns: +// GetCredential returns a single credential stored in the given virtual +// authenticator that matches the credential ID. // -// credential -func (p *GetCredentialParams) Do(ctx context.Context) (credential *Credential, err error) { - // execute - var res GetCredentialReturns - err = cdp.Execute(ctx, CommandGetCredential, p, &res) - if err != nil { - return nil, err - } - - return res.Credential, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-getCredential +var GetCredential = cdp.Command[GetCredentialParams, GetCredentialResult]{Method: CommandGetCredential} -// GetCredentialsParams returns all the credentials stored in the given -// virtual authenticator. +// GetCredentialsParams are the parameters of the command +// WebAuthn.getCredentials. type GetCredentialsParams struct { AuthenticatorID AuthenticatorID `json:"authenticatorId"` } -// GetCredentials returns all the credentials stored in the given virtual -// authenticator. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-getCredentials -// -// parameters: -// -// authenticatorID -func GetCredentials(authenticatorID AuthenticatorID) *GetCredentialsParams { - return &GetCredentialsParams{ - AuthenticatorID: authenticatorID, - } -} - -// GetCredentialsReturns return values. -type GetCredentialsReturns struct { +// GetCredentialsResult is the result of the command WebAuthn.getCredentials. +type GetCredentialsResult struct { Credentials []*Credential `json:"credentials,omitempty,omitzero"` } -// Do executes WebAuthn.getCredentials against the provided context. -// -// returns: +// GetCredentials returns all the credentials stored in the given virtual +// authenticator. // -// credentials -func (p *GetCredentialsParams) Do(ctx context.Context) (credentials []*Credential, err error) { - // execute - var res GetCredentialsReturns - err = cdp.Execute(ctx, CommandGetCredentials, p, &res) - if err != nil { - return nil, err - } - - return res.Credentials, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-getCredentials +var GetCredentials = cdp.Command[GetCredentialsParams, GetCredentialsResult]{Method: CommandGetCredentials} -// RemoveCredentialParams removes a credential from the authenticator. +// RemoveCredentialParams are the parameters of the command +// WebAuthn.removeCredential. type RemoveCredentialParams struct { AuthenticatorID AuthenticatorID `json:"authenticatorId"` - CredentialID string `json:"credentialId"` + CredentialID []byte `json:"credentialId"` } // RemoveCredential removes a credential from the authenticator. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-removeCredential -// -// parameters: -// -// authenticatorID -// credentialID -func RemoveCredential(authenticatorID AuthenticatorID, credentialID string) *RemoveCredentialParams { - return &RemoveCredentialParams{ - AuthenticatorID: authenticatorID, - CredentialID: credentialID, - } -} - -// Do executes WebAuthn.removeCredential against the provided context. -func (p *RemoveCredentialParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandRemoveCredential, p, nil) -} +var RemoveCredential = cdp.Command[RemoveCredentialParams, cdp.Empty]{Method: CommandRemoveCredential} -// ClearCredentialsParams clears all the credentials from the specified -// device. +// ClearCredentialsParams are the parameters of the command +// WebAuthn.clearCredentials. type ClearCredentialsParams struct { AuthenticatorID AuthenticatorID `json:"authenticatorId"` } @@ -322,23 +140,10 @@ type ClearCredentialsParams struct { // ClearCredentials clears all the credentials from the specified device. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-clearCredentials -// -// parameters: -// -// authenticatorID -func ClearCredentials(authenticatorID AuthenticatorID) *ClearCredentialsParams { - return &ClearCredentialsParams{ - AuthenticatorID: authenticatorID, - } -} +var ClearCredentials = cdp.Command[ClearCredentialsParams, cdp.Empty]{Method: CommandClearCredentials} -// Do executes WebAuthn.clearCredentials against the provided context. -func (p *ClearCredentialsParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandClearCredentials, p, nil) -} - -// SetUserVerifiedParams sets whether User Verification succeeds or fails for -// an authenticator. The default is true. +// SetUserVerifiedParams are the parameters of the command +// WebAuthn.setUserVerified. type SetUserVerifiedParams struct { AuthenticatorID AuthenticatorID `json:"authenticatorId"` IsUserVerified bool `json:"isUserVerified"` @@ -348,26 +153,10 @@ type SetUserVerifiedParams struct { // authenticator. The default is true. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-setUserVerified -// -// parameters: -// -// authenticatorID -// isUserVerified -func SetUserVerified(authenticatorID AuthenticatorID, isUserVerified bool) *SetUserVerifiedParams { - return &SetUserVerifiedParams{ - AuthenticatorID: authenticatorID, - IsUserVerified: isUserVerified, - } -} - -// Do executes WebAuthn.setUserVerified against the provided context. -func (p *SetUserVerifiedParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetUserVerified, p, nil) -} +var SetUserVerified = cdp.Command[SetUserVerifiedParams, cdp.Empty]{Method: CommandSetUserVerified} -// SetAutomaticPresenceSimulationParams sets whether tests of user presence -// will succeed immediately (if true) or fail to resolve (if false) for an -// authenticator. The default is true. +// SetAutomaticPresenceSimulationParams are the parameters of the command +// WebAuthn.setAutomaticPresenceSimulation. type SetAutomaticPresenceSimulationParams struct { AuthenticatorID AuthenticatorID `json:"authenticatorId"` Enabled bool `json:"enabled"` @@ -378,66 +167,48 @@ type SetAutomaticPresenceSimulationParams struct { // authenticator. The default is true. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-setAutomaticPresenceSimulation -// -// parameters: -// -// authenticatorID -// enabled -func SetAutomaticPresenceSimulation(authenticatorID AuthenticatorID, enabled bool) *SetAutomaticPresenceSimulationParams { - return &SetAutomaticPresenceSimulationParams{ - AuthenticatorID: authenticatorID, - Enabled: enabled, - } -} - -// Do executes WebAuthn.setAutomaticPresenceSimulation against the provided context. -func (p *SetAutomaticPresenceSimulationParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetAutomaticPresenceSimulation, p, nil) -} +var SetAutomaticPresenceSimulation = cdp.Command[SetAutomaticPresenceSimulationParams, cdp.Empty]{Method: CommandSetAutomaticPresenceSimulation} -// SetCredentialPropertiesParams allows setting credential properties. -// https://w3c.github.io/webauthn/#sctn-automation-set-credential-properties. +// SetCredentialPropertiesParams are the parameters of the command +// WebAuthn.setCredentialProperties. type SetCredentialPropertiesParams struct { - AuthenticatorID AuthenticatorID `json:"authenticatorId"` - CredentialID string `json:"credentialId"` - BackupEligibility bool `json:"backupEligibility"` - BackupState bool `json:"backupState"` + AuthenticatorID AuthenticatorID `json:"authenticatorId"` + CredentialID []byte `json:"credentialId"` + BackupEligibility *bool `json:"backupEligibility,omitempty,omitzero"` + BackupState *bool `json:"backupState,omitempty,omitzero"` + ActiveCmtgKeyIndex *int64 `json:"activeCmtgKeyIndex,omitempty,omitzero"` + GenerateCmtgKeyOnNextOperation *bool `json:"generateCmtgKeyOnNextOperation,omitempty,omitzero"` + SignCount *float64 `json:"signCount,omitempty,omitzero"` // Must be equal to or greater than -1. If -1, the signature counter is removed from the credential, and every assertion operation will report a value of 0. See https://w3c.github.io/webauthn/#signature-counter } // SetCredentialProperties allows setting credential properties. // https://w3c.github.io/webauthn/#sctn-automation-set-credential-properties. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-setCredentialProperties +var SetCredentialProperties = cdp.Command[SetCredentialPropertiesParams, cdp.Empty]{Method: CommandSetCredentialProperties} + +// CredentialAdded triggered when a credential is added to an authenticator. // -// parameters: -// -// authenticatorID -// credentialID -func SetCredentialProperties(authenticatorID AuthenticatorID, credentialID string) *SetCredentialPropertiesParams { - return &SetCredentialPropertiesParams{ - AuthenticatorID: authenticatorID, - CredentialID: credentialID, - BackupEligibility: false, - BackupState: false, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#event-credentialAdded +var CredentialAdded = cdp.Event[EventCredentialAdded]{Method: "WebAuthn.credentialAdded"} -// WithBackupEligibility [no description]. -func (p SetCredentialPropertiesParams) WithBackupEligibility(backupEligibility bool) *SetCredentialPropertiesParams { - p.BackupEligibility = backupEligibility - return &p -} +// CredentialDeleted triggered when a credential is deleted, e.g. through +// PublicKeyCredential.signalUnknownCredential(). +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#event-credentialDeleted +var CredentialDeleted = cdp.Event[EventCredentialDeleted]{Method: "WebAuthn.credentialDeleted"} -// WithBackupState [no description]. -func (p SetCredentialPropertiesParams) WithBackupState(backupState bool) *SetCredentialPropertiesParams { - p.BackupState = backupState - return &p -} +// CredentialUpdated triggered when a credential is updated, e.g. through +// PublicKeyCredential.signalCurrentUserDetails(). +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#event-credentialUpdated +var CredentialUpdated = cdp.Event[EventCredentialUpdated]{Method: "WebAuthn.credentialUpdated"} -// Do executes WebAuthn.setCredentialProperties against the provided context. -func (p *SetCredentialPropertiesParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandSetCredentialProperties, p, nil) -} +// CredentialAsserted triggered when a credential is used in a webauthn +// assertion. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#event-credentialAsserted +var CredentialAsserted = cdp.Event[EventCredentialAsserted]{Method: "WebAuthn.credentialAsserted"} // Command names. const ( diff --git a/vendor/github.com/chromedp/cdproto/webmcp/events.go b/vendor/github.com/chromedp/cdproto/webmcp/events.go index d96df9145..641fe084b 100644 --- a/vendor/github.com/chromedp/cdproto/webmcp/events.go +++ b/vendor/github.com/chromedp/cdproto/webmcp/events.go @@ -1,11 +1,11 @@ -package webmcp +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package webmcp import ( "github.com/chromedp/cdproto/cdp" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" "github.com/chromedp/cdproto/runtime" - "github.com/go-json-experiment/json/jsontext" ) // EventToolsAdded event fired when new tools are added. @@ -38,7 +38,7 @@ type EventToolInvoked struct { type EventToolResponded struct { InvocationID string `json:"invocationId"` // Invocation identifier. Status InvocationStatus `json:"status"` // Status of the invocation. - Output jsontext.Value `json:"output,omitempty,omitzero"` // Output or error delivered as delivered to the agent. Missing if status is anything other than Completed. Note: The output is untrusted and poses a prompt injection risk. Clients should treat this as potentially malicious user input. + Output jsonv2.Value `json:"output,omitempty,omitzero"` // Output or error delivered as delivered to the agent. Missing if status is anything other than Completed. Note: The output is untrusted and poses a prompt injection risk. Clients should treat this as potentially malicious user input. ErrorText string `json:"errorText,omitempty,omitzero"` // Error text for protocol users. Exception *runtime.RemoteObject `json:"exception,omitempty,omitzero"` // The exception object, if the javascript tool threw an error> } diff --git a/vendor/github.com/chromedp/cdproto/webmcp/types.go b/vendor/github.com/chromedp/cdproto/webmcp/types.go index e2290c13d..a7c513642 100644 --- a/vendor/github.com/chromedp/cdproto/webmcp/types.go +++ b/vendor/github.com/chromedp/cdproto/webmcp/types.go @@ -1,14 +1,11 @@ -package webmcp +// Code generated by pdlgen. DO NOT EDIT. -// Code generated by cdproto-gen. DO NOT EDIT. +package webmcp import ( - "fmt" - "strings" - "github.com/chromedp/cdproto/cdp" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" "github.com/chromedp/cdproto/runtime" - "github.com/go-json-experiment/json/jsontext" ) // Annotation tool annotations. @@ -17,6 +14,8 @@ import ( type Annotation struct { ReadOnly bool `json:"readOnly"` // A hint indicating that the tool does not modify any state. UntrustedContent bool `json:"untrustedContent"` // A hint indicating that the tool output may contain untrusted content, ex: UGC, 3rd party data. + Consequential bool `json:"consequential"` // A hint indicating that executing the tool will result in consequential actions, ex: booking a flight, transferring money. + Debugging bool `json:"debugging"` // If true, indicates that the tool is intended for debugging and developer tooling rather than end-user interactions. Autosubmit bool `json:"autosubmit"` // If the declarative tool was declared with the autosubmit attribute. } @@ -37,31 +36,13 @@ const ( InvocationStatusError InvocationStatus = "Error" ) -// UnmarshalJSON satisfies [json.Unmarshaler]. -func (t *InvocationStatus) UnmarshalJSON(buf []byte) error { - s := string(buf) - s = strings.TrimSuffix(strings.TrimPrefix(s, `"`), `"`) - - switch InvocationStatus(s) { - case InvocationStatusCompleted: - *t = InvocationStatusCompleted - case InvocationStatusCanceled: - *t = InvocationStatusCanceled - case InvocationStatusError: - *t = InvocationStatusError - default: - return fmt.Errorf("unknown InvocationStatus value: %v", s) - } - return nil -} - // Tool definition of a tool that can be invoked. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebMCP#type-Tool type Tool struct { Name string `json:"name"` // Tool name. Description string `json:"description"` // Tool description. - InputSchema jsontext.Value `json:"inputSchema,omitempty,omitzero"` + InputSchema jsonv2.Value `json:"inputSchema,omitempty,omitzero"` Annotations *Annotation `json:"annotations,omitempty,omitzero"` // Optional annotations for the tool. FrameID cdp.FrameID `json:"frameId"` // Frame identifier associated with the tool registration. BackendNodeID cdp.BackendNodeID `json:"backendNodeId,omitempty,omitzero"` // Optional node ID for declarative tools. diff --git a/vendor/github.com/chromedp/cdproto/webmcp/webmcp.go b/vendor/github.com/chromedp/cdproto/webmcp/webmcp.go index 6c0430a6f..e2b27f4d6 100644 --- a/vendor/github.com/chromedp/cdproto/webmcp/webmcp.go +++ b/vendor/github.com/chromedp/cdproto/webmcp/webmcp.go @@ -1,97 +1,46 @@ +// Code generated by pdlgen. DO NOT EDIT. + // Package webmcp provides the Chrome DevTools Protocol // commands, types, and events for the WebMCP domain. // -// Generated by the cdproto-gen command. +// Generated by the pdlgen command. package webmcp -// Code generated by cdproto-gen. DO NOT EDIT. - import ( - "context" - "github.com/chromedp/cdproto/cdp" - "github.com/go-json-experiment/json/jsontext" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" ) -// EnableParams enables the WebMCP domain, allowing events to be sent. -// Enabling the domain will trigger a toolsAdded event for all currently -// registered tools. -type EnableParams struct{} - // Enable enables the WebMCP domain, allowing events to be sent. Enabling the // domain will trigger a toolsAdded event for all currently registered tools. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebMCP#method-enable -func Enable() *EnableParams { - return &EnableParams{} -} - -// Do executes WebMCP.enable against the provided context. -func (p *EnableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandEnable, nil, nil) -} - -// DisableParams disables the WebMCP domain. -type DisableParams struct{} +var Enable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandEnable} // Disable disables the WebMCP domain. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebMCP#method-disable -func Disable() *DisableParams { - return &DisableParams{} -} - -// Do executes WebMCP.disable against the provided context. -func (p *DisableParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandDisable, nil, nil) -} +var Disable = cdp.Command[cdp.Empty, cdp.Empty]{Method: CommandDisable} -// InvokeToolParams invokes a registered tool. +// InvokeToolParams are the parameters of the command WebMCP.invokeTool. type InvokeToolParams struct { - FrameID cdp.FrameID `json:"frameId"` // Frame in which to invoke the tool. - ToolName string `json:"toolName"` // Name of the tool to invoke. - Input jsontext.Value `json:"input"` -} - -// InvokeTool invokes a registered tool. -// -// See: https://chromedevtools.github.io/devtools-protocol/tot/WebMCP#method-invokeTool -// -// parameters: -// -// frameID - Frame in which to invoke the tool. -// toolName - Name of the tool to invoke. -// input - Input parameters for the tool, matching the tool's inputSchema. -func InvokeTool(frameID cdp.FrameID, toolName string, input jsontext.Value) *InvokeToolParams { - return &InvokeToolParams{ - FrameID: frameID, - ToolName: toolName, - Input: input, - } + FrameID cdp.FrameID `json:"frameId"` // Frame in which to invoke the tool. + ToolName string `json:"toolName"` // Name of the tool to invoke. + Input jsonv2.Value `json:"input"` } -// InvokeToolReturns return values. -type InvokeToolReturns struct { +// InvokeToolResult is the result of the command WebMCP.invokeTool. +type InvokeToolResult struct { InvocationID string `json:"invocationId,omitempty,omitzero"` // Unique identifier for this invocation. Response is sent before tool events. } -// Do executes WebMCP.invokeTool against the provided context. -// -// returns: +// InvokeTool invokes a registered tool. // -// invocationID - Unique identifier for this invocation. Response is sent before tool events. -func (p *InvokeToolParams) Do(ctx context.Context) (invocationID string, err error) { - // execute - var res InvokeToolReturns - err = cdp.Execute(ctx, CommandInvokeTool, p, &res) - if err != nil { - return "", err - } - - return res.InvocationID, nil -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebMCP#method-invokeTool +var InvokeTool = cdp.Command[InvokeToolParams, InvokeToolResult]{Method: CommandInvokeTool} -// CancelInvocationParams cancels a pending tool invocation. +// CancelInvocationParams are the parameters of the command +// WebMCP.cancelInvocation. type CancelInvocationParams struct { InvocationID string `json:"invocationId"` // Invocation identifier to cancel. } @@ -99,20 +48,27 @@ type CancelInvocationParams struct { // CancelInvocation cancels a pending tool invocation. // // See: https://chromedevtools.github.io/devtools-protocol/tot/WebMCP#method-cancelInvocation +var CancelInvocation = cdp.Command[CancelInvocationParams, cdp.Empty]{Method: CommandCancelInvocation} + +// ToolsAdded event fired when new tools are added. // -// parameters: +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebMCP#event-toolsAdded +var ToolsAdded = cdp.Event[EventToolsAdded]{Method: "WebMCP.toolsAdded"} + +// ToolsRemoved event fired when tools are removed. // -// invocationID - Invocation identifier to cancel. -func CancelInvocation(invocationID string) *CancelInvocationParams { - return &CancelInvocationParams{ - InvocationID: invocationID, - } -} +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebMCP#event-toolsRemoved +var ToolsRemoved = cdp.Event[EventToolsRemoved]{Method: "WebMCP.toolsRemoved"} -// Do executes WebMCP.cancelInvocation against the provided context. -func (p *CancelInvocationParams) Do(ctx context.Context) (err error) { - return cdp.Execute(ctx, CommandCancelInvocation, p, nil) -} +// ToolInvoked event fired when a tool invocation starts. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebMCP#event-toolInvoked +var ToolInvoked = cdp.Event[EventToolInvoked]{Method: "WebMCP.toolInvoked"} + +// ToolResponded event fired when a tool invocation completes or fails. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebMCP#event-toolResponded +var ToolResponded = cdp.Event[EventToolResponded]{Method: "WebMCP.toolResponded"} // Command names. const ( diff --git a/vendor/github.com/chromedp/chromedp/.gitattributes b/vendor/github.com/chromedp/chromedp/.gitattributes new file mode 100644 index 000000000..9cb651638 --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/.gitattributes @@ -0,0 +1,6 @@ +# Every text file is LF on every checkout, including a checkout on Windows. +# +# Git for Windows writes CRLF by default. The golden images and the +# JavaScript snippets that chromedp embeds must keep the same bytes on every +# machine. +* text=auto eol=lf diff --git a/vendor/github.com/chromedp/chromedp/.gitignore b/vendor/github.com/chromedp/chromedp/.gitignore index 81aa601da..9688da15e 100644 --- a/vendor/github.com/chromedp/chromedp/.gitignore +++ b/vendor/github.com/chromedp/chromedp/.gitignore @@ -5,9 +5,14 @@ cdp-*.log cdp-*.txt *.out -/chromedp.test -/chromedp.test.exe +chromedp.test +chromedp.test.exe /*.jpeg /*.png /*.pdf + +# The Claude Code permissions of one person. +.claude/settings.local.json +go.work +go.work.sum diff --git a/vendor/github.com/chromedp/chromedp/AGENTS.md b/vendor/github.com/chromedp/chromedp/AGENTS.md new file mode 100644 index 000000000..f1e5514e7 --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/AGENTS.md @@ -0,0 +1,287 @@ +# chromedp + +`chromedp` is a Go package that drives Chrome and other browsers that speak +the Chrome DevTools Protocol. The protocol is the JSON message format that +Chrome uses for remote control. `chromedp` needs no external driver. It +starts the browser or connects to one, then sends protocol commands over a +pipe or a WebSocket. + +The generated protocol types live in a separate module, `cdproto`, which +`pdlgen` writes. The core module of this repository holds the high level API on +top of it: allocators, contexts, actions, selectors, input and screenshots. The +core uses only the Go standard library and `cdproto`. See +`docs/decisions/2026-10-04-the-core-uses-only-the-standard-library.md`. + +The repository holds two modules: + +| Directory | Module | Holds | +| --- | --- | --- | +| the root | `github.com/chromedp/chromedp` | the core, with the pipe transport, and the package `remote` in `remote/` | +| `test/` | `github.com/chromedp/chromedp/test` | the tests that need `pdf` or `pixelmatch` | + +The package `remote` is not a module. It is a package of the core module, and it +has its own WebSocket client, so it needs no library. See +`docs/decisions/2026-10-11-remote-is-a-package-of-the-core-module.md`. + +## Standing rules + +These hold in every `chromedp` repository, for every coding agent. + +1. Stage changes for review. Commit and push only when the maintainer says so. +2. Load the `simple-english` skill before you write text that a person reads. + Examples are a document, a code comment, an error message and a commit + message. Follow the skill for that text. +3. Load the `go-pedantry` skill before you write or review Go code. Follow it + where it does not conflict with a rule in this file. A rule here wins. + +Questions and feature ideas go to GitHub Discussions, and bugs go to issues. Do +not open an issue for a question. See +`docs/decisions/2026-10-03-questions-and-ideas-go-to-discussions.md`. + +`CLAUDE.md` holds one line that imports this file, so that Claude Code and +every other agent read the same rules. Edit this file, not that one. + +## Which document to read + +Read `docs/PLAN.md` first. It describes the purpose and the architecture. Its +last section lists the open questions. Do not decide an open question on your +own. Ask the maintainer. + +`docs/decisions/README.md` is the index of every decision. A decision is one +file named by its date and a short title. Read the status of a decision before +you trust it, because a later decision can amend or replace it. + +| If you are | Read | +| --- | --- | +| starting work | `docs/PLAN.md`, then `docs/PROGRESS.md` | +| looking for known work that is not done | `docs/BACKLOG.md` | +| asking why something is the way it is | the index in `docs/decisions/README.md` | +| changing the public API | `docs/PLAN.md` under Architecture, `docs/API.md`, `docs/MIGRATION.md`, then the decisions in `docs/decisions/` | +| looking for the old and the new name of an API | `docs/MIGRATION.md` | +| looking for the API with before and after code | `docs/API.md` | +| changing the cdproto dependency | `docs/decisions/2026-10-03-stop-relying-on-removed-cdproto-helpers.md` | +| changing the README | `docs/decisions/2026-10-03-readme-shows-the-gear-logo-and-discord-badge.md` | +| recording a decision | `docs/decisions/README.md` and `docs/decisions/2026-10-03-use-dated-decision-files.md` | +| running the tests | the section Before you commit, in this file | + +## Hard rules + +1. Do not run the tests in a session that has no browser. They need Chrome or + the `chromedp/headless-shell` container. A session without one must run + `go build ./...`, `go vet ./...` and `go test ./docs/` only. +2. Do not edit `kb/kb.go` or `device/device.go` by hand. `go generate` writes + them from `kb/gen.go` and `device/gen.go`. Change the generator and run it. +3. Hold the lock before you read a field of a `chromedp.Node` or a + `chromedp.Frame`. The code in `query.go` and `target.go` calls `RLock` + first, because the target updates the node tree from events while an action + reads it. +4. Run an action with `chromedp.Run` or `chromedp.Do`. They start the browser + and the tab when the context has none, and they pass the `Target` to the + action. Do not call an action with a `Target` that these funcs did not + prepare. +5. Wrap every error with `%w`. See the decision + `docs/decisions/2021-04-29-wrap-errors-with-w.md`. +6. Keep the tests compatible with `headless-shell`. CI runs them against Chrome on + Linux, Windows and macOS, and against the `chromedp/headless-shell` image on + Linux. A test that fails on one + of them must skip with a comment that says why. `input_test.go` shows how. +7. Embed JavaScript from the `js/` folder with `go:embed`. Do not write + JavaScript inside a Go string. +8. Do not change the type `Action[T]` or the signature of an exported + function without asking the maintainer. See `docs/decisions/2026-10-03-generic-iterator-api-instead-of-action.md`. +9. Do not add a helper that the `cdproto` module is dropping. See + `docs/decisions/2026-10-03-stop-relying-on-removed-cdproto-helpers.md`. + +## Layout + +The root package `chromedp` holds the API. The files group by topic. + +| Path | Holds | +| --- | --- | +| `allocate.go`, `allocate_linux.go`, `allocate_other.go`, `allocate_pipe.go`, `allocate_detach_unix.go`, `allocate_detach_windows.go`, `keepopen.go` | `Allocator`, `ExecAllocator`, `Dialer` and `Attacher`, which start or reach a browser, and the options that keep a browser open | +| `browser.go`, `pipe.go`, `pipe_unix.go`, `pipe_windows.go` | `Browser`, the `Transport` interface, the pipe connection and the way each platform passes the pipes to the browser | +| `remote/` | the package `remote`: the WebSocket connection `Conn`, the remote `Allocator`, `WebSocket` and `WithKeepOpen` | +| `remote/internal/websocket/` | the WebSocket client of RFC 6455, with its tests, its fuzz test and its benchmarks | +| `remote/internal/wstest/` | the WebSocket server that the tests use. It shares no code with the client | +| `test/` | the module `test`: the screenshot tests and the PDF text test, with their `testdata/` | +| `internal/testenv/`, `internal/chromedptest/` | the variables and the helpers that the tests of the core, of `remote` and of `test` share | +| `chromedp.go`, `action.go` | `Context`, `NewContext`, `RunResponse`, `Action[T]`, `Run`, `Do` and the events | +| `target.go`, `util.go` | `Target`, which tracks frames and the DOM tree from events | +| `frame.go`, `node.go` | `Frame` and `Node`, which add the tree state to the protocol types | +| `session.go` | the event subscriptions of a `Browser` and of a `Target` | +| `errors.go` | the error values and `ExceptionError` | +| `query.go` | selectors, query options and the element actions | +| `nav.go`, `input.go`, `drag.go`, `console.go`, `expose.go`, `pdf.go`, `emulate.go`, `screenshot.go`, `eval.go`, `call.go`, `poll.go` | actions by topic | +| `js.go`, `js/` | embedded JavaScript snippets | +| `kb/` | keyboard key definitions, generated | +| `device/` | device descriptors for emulation, generated | +| `testdata/` | HTML pages for the tests of the core. `remote/testdata/` and `test/testdata/` hold the files of `remote` and of `test` | +| `contrib/docker-test.sh` | runs the tests inside the `headless-shell` image | +| `docs/` | plan, progress, backlog, API and migration guides, and decisions | + +The root of the repository holds `README.md`, `AGENTS.md`, `CLAUDE.md`, +`CONTRIBUTING.md` and `LICENSE` as text documents. Every other document goes +in `docs/`. + +## Terms + +These words have one meaning in every document and in every Go comment. + +- Maintainer: the person who owns the project and decides the open questions. +- Target: a page, a tab or a worker that the browser exposes. The `Target` type + tracks one. +- Tab: a target of the type page, as a person sees it in the browser. Text for + users says tab. Text about the code says target. +- Session: a channel that sends commands and receives events for one scope. + `cdp.Session` is the interface. `Browser` and `Target` implement it. +- Action: a func of the type `Action[T]` that runs against a target and returns + a value of the type `T`. +- Selector: the value that picks the elements of a query action. It is a + `Selectable`, a string type or a `[]cdp.NodeID` type. The type chooses the + lookup. A plain string is a `Search`. + +## Go conventions + +The module needs Go 1.25 or newer, as `go.mod` says. Do not use a feature of +Go 1.26 or later, such as `new(true)` or `errors.AsType`. Use the helper `ptr` +for a pointer to a value. Import the JSON types from +`github.com/chromedp/cdproto/cdp/jsonv2` and never from `encoding/json/v2`. +CI runs Go 1.25, 1.26 and the newest stable release. See +`docs/decisions/2026-10-06-support-go-1-25-and-later.md`. + +Wrap every error with `%w`, never `%s` or `%v`: + +```go +if err != nil { + return fmt.Errorf("reading the node tree: %w", err) +} +``` + +Write error messages in lower case. Name the object that failed. Do not start +with "failed to" or "error". + +Put `context.Context` first in every parameter list and name it `ctx`. The +`Context` type of `chromedp` is not a `context.Context` and it is not the same +thing. Never store a `context.Context` in a struct. + +Accept interfaces and return concrete structs. Name a receiver with one or two +lower case letters. Use the same name on every method of the type. Group struct +fields by purpose, with exported fields first and a blank line between groups. + +Run `gofmt` on every file. The history shows `go fix` and `modernize` runs, so +keep the code in the form they produce. + +## Linting + +No linter configuration exists in this repository. There is no +`.golangci.yml` and CI runs no linter. Use `gofmt` and `go vet`. Adding a +linter configuration is in `docs/BACKLOG.md`. + +## Before you commit + +Run these commands in the repository root, which is the core module: + +```bash +gofmt -l . +go vet ./... +go build ./... +go test ./docs/ +``` + +`gofmt -l .` must print nothing. Run `go vet ./...` in `test/` too. Run +`GOOS=windows go vet ./...` and `GOOS=darwin go vet ./...` in the root. + +`go.mod` of the core requires the released typed `cdproto`, so these commands +need no other setup. The core must import no library other than the standard +library and `cdproto`. Check it with `go list -deps ./...`, and do not add a +module to its `go.mod`. + +Never commit a `go.work` file or a `go.work.sum` file, in this repository or in +any other. `.gitignore` lists them. The maintainer can try an unreleased +`cdproto` with a local `go.work` file. Do not add a `replace` directive to the +`go.mod` of the core. + +The `go.mod` of `test/` requires a released version of the core, +`github.com/chromedp/chromedp v0.20.0` at this time, and holds no `replace` +directive. To try a change of the core in `test`, add +`replace github.com/chromedp/chromedp => ../` to that `go.mod` while you work, +and never commit it. CI adds the directive at run time, so that `test` runs +against the core of the commit under test. Before the maintainer tags the core, +make sure that no `go.mod` holds a `replace` directive, and set the version of +the core in `test/go.mod` to the newest tag. Do not create a tag. + +The full test suite needs a browser, and it is the only way to test the +package. Run it where Chrome is installed. Each module runs in its own +directory, with `GOWORK=off` when a `go.work` file exists. The first command +runs the package `remote` too, because it is part of the core module: + +```bash +go test -v ./... +(cd test && go test -v ./...) +``` + +The tests of the WebSocket client in `remote/internal/websocket/` need no +browser. Run them with `go test -race ./remote/...`. The fuzz test runs with +`go test -fuzz FuzzReadFrame -fuzztime 30s ./remote/internal/websocket/`. + +If Chrome is not on the machine, use the container. The script builds the test +binary of the core, of `remote` and of `test`, and runs each inside the +`chromedp/headless-shell` image. It uses `docker`, or `podman` when it is +installed: + +```bash +./contrib/docker-test.sh +``` + +The `IMAGE` variable chooses another image. CI runs the first command on Linux, +Windows and macOS, on every push and pull request. Linux runs Go 1.25, Go 1.26 +and the newest stable release, and Windows and macOS run the newest stable +release. The container script runs on Linux with the newest stable release only. +Two more Linux jobs test `cdproto/cdp/jsonv2`: one with Go 1.25 and +`GOEXPERIMENT=jsonv2`, and one with the tag `cdproto_jsoncompat` and +`GOEXPERIMENT=nojsonv2`. CI runs the two modules in turn, each one in its own directory. The +steps of `test` and the container run even when an earlier step failed, so that +one run shows every failure. See `.github/workflows/test.yml`. +A second workflow, `.github/workflows/nightly.yml`, runs the container script every +night at 04:17 UTC, and when you start it by hand, against the three channels of +the image: `stable` (the same as `latest`), `beta` and `dev`. It runs on Linux +amd64. The tests print a +line that starts with `browser:` with the version of each channel. +If the repository gets a Dependabot configuration, it must list the two +directories `/` and `/test`. + +The tests of `test/` use the exported API of the core only. The helpers that +the tests share are in `internal/chromedptest/`, and the core tests, which +cannot import that package, read the variables through `internal/testenv/`. + +These variables change the tests: + +- `CHROMEDP_TEST_RUNNER` names the browser binary. +- `CHROMEDP_VISIBLEWINDOW` shows the window. The old name `CHROMEDP_NO_HEADLESS` works in the tests too. +- `CHROMEDP_NO_SANDBOX`, set to `false`, turns the sandbox on. +- `CHROMEDP_DEBUG` logs every message. +- `CI` and `HEADLESS_SHELL` make the test `TestKillLeftoversSkipsKeepOpen` skip itself. It is not stable on a CI runner, and the headless-shell image has no `sh`. +- `HEADLESS_SHELL` also makes `TestWithNewWindow/SharedWindow` and `/Inherited` skip, because headless-shell gives each target its own window. + +A CI runner is slow when many tests run at once. Give a limit in a test enough time for a slow start, because a limit only matters when the test fails. + +## Writing documentation + +Follow the `simple-english` skill for every word. Write sentences of 20 words +or fewer for a procedure, and 25 words or fewer for a description. + +Record a decision in a file in `docs/decisions/`. Name it +`YYYY-MM-DD-short-slug.md` with the date of the decision. Open it with +`# `, a blank line and `Status: Decided.`. Use `Proposed.`, `Open.`, +`Amends <file>.` or `Superseded by <file>.` when that is the status. Refer to a +decision by its file name, never by a number. State an amendment in both +files. Add a row to `docs/decisions/README.md`. + +`go test ./docs/` tests the links, the decision index, the root layout, the +skill copies, and the prose rules in the documents and in the Go comments. It +needs no browser. + +The skills live in `.agents/skills` and `.claude/skills` as identical copies. +Never replace a copy with a symbolic link. `skills-lock.json` names the source +of each skill. The Claude Code permissions of one person go in +`.claude/settings.local.json`, which `.gitignore` lists. diff --git a/vendor/github.com/chromedp/chromedp/CLAUDE.md b/vendor/github.com/chromedp/chromedp/CLAUDE.md new file mode 100644 index 000000000..43c994c2d --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/vendor/github.com/chromedp/chromedp/CONTRIBUTING.md b/vendor/github.com/chromedp/chromedp/CONTRIBUTING.md new file mode 100644 index 000000000..de8b7e8bb --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/CONTRIBUTING.md @@ -0,0 +1,48 @@ +# Contributing to chromedp + +`chromedp` is a Go package that drives Chrome through the Chrome DevTools +Protocol. Read these three things before you change anything. + +[`AGENTS.md`](AGENTS.md) holds the rules, the layout, the Go conventions and +the test commands. It is written for a coding agent and everything in it +applies to a person. + +[`docs/PLAN.md`](docs/PLAN.md) describes the purpose and the architecture. +Its last section lists the open questions. Do not decide an open question on +your own. Ask the maintainer. + +[`docs/decisions/`](docs/decisions/README.md) holds every decision, one file +each, named by date. Read the status of a decision before you trust it. + +## Before you send a change + +```bash +gofmt -l . +go vet ./... +go test -v ./... +``` + +`gofmt -l .` must print nothing. The tests need Chrome. If Chrome is not on +your machine, run `./contrib/docker-test.sh`. It runs the tests inside the +`chromedp/headless-shell` image. CI runs the tests with Chrome on Linux, Windows and macOS, and with the image on Linux only, on every push. + +If you do not have a browser, run `go test ./docs/`. It needs none and tests +the documents and the Go comments. + +## Writing + +Write in plain English. Use short sentences and the active voice. The +`simple-english` skill in `.agents/skills` has the full rules, and +`go test ./docs/` finds the violations that a machine can find, in the +documents and in the Go comments. + +To record a decision, add a file to `docs/decisions/`. Name it with the date, as +in `2026-10-03-short-title.md`. Then add its row to the index. The test prints +the row for you. + +## Questions + +Ask in [Discussions](https://github.com/chromedp/chromedp/discussions), and not +in an issue. The issue tracker is for bugs, and a new issue starts from the bug +report template. Suggest a feature in Discussions first. The +[README](README.md) links the project resources. diff --git a/vendor/github.com/chromedp/chromedp/LICENSE b/vendor/github.com/chromedp/chromedp/LICENSE index b9ba4a540..7c49e6c89 100644 --- a/vendor/github.com/chromedp/chromedp/LICENSE +++ b/vendor/github.com/chromedp/chromedp/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2016-2025 Kenneth Shaw +Copyright (c) 2016-2026 Kenneth Shaw Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/github.com/chromedp/chromedp/README.md b/vendor/github.com/chromedp/chromedp/README.md index 97dffe65a..472da6952 100644 --- a/vendor/github.com/chromedp/chromedp/README.md +++ b/vendor/github.com/chromedp/chromedp/README.md @@ -1,75 +1,468 @@ # About chromedp -Package `chromedp` is a faster, simpler way to drive browsers supporting the -[Chrome DevTools Protocol][devtools-protocol] in Go without external dependencies. +<p align="center"> + <img src="https://raw.githubusercontent.com/chromedp/logo/main/chromedp.svg" alt="chromedp logo" width="160"> +</p> + +Package `chromedp` drives browsers that speak the +[Chrome DevTools Protocol][devtools-protocol] from Go. It needs no external +driver. [![Unit Tests][chromedp-ci-status]][chromedp-ci] [![Go Reference][goref-chromedp-status]][goref-chromedp] [![Releases][release-status]][releases] +[![Discord Discussion][discord-status]][discord] ## Installing -Install in the usual Go way: +Install the package with `go get`. The module needs Go 1.25 or newer. The JSON +types come from `github.com/chromedp/cdproto/cdp/jsonv2`. They are aliases of +the types of the standard library package `encoding/json/v2` on Go 1.27 and +later, or on Go 1.25 and 1.26 with `GOEXPERIMENT=jsonv2`. Otherwise they are +aliases of the types of `github.com/go-json-experiment/json`. Version v0.20.0 +uses the typed `cdproto` v0.157.8 and has the generic and iterator API. The +earlier versions of `cdproto`, v0.157.0, v0.157.1 and v0.157.2, have the old API. ```sh -$ go get -u github.com/chromedp/chromedp +go get -u github.com/chromedp/chromedp +``` + +The module uses only the Go standard library and `cdproto`. It starts a +browser and talks to it through a pipe. Code that needs a websocket is in the +package `github.com/chromedp/chromedp/remote`, which has its own WebSocket +client. It is part of the same module, so `go get` installs it with the rest. +Import it only when you connect to a browser that runs already, when you want +the exec allocator to use a websocket, or when you keep the browser open after +the program ends. + +## Usage + +An action is a func that runs against a browser tab and returns a value. +`chromedp.Do` runs actions that return nothing, and `chromedp.Run` runs one +action and returns its value: + +```go +ctx, cancel := chromedp.NewContext(context.Background()) +defer cancel() + +if err := chromedp.Do(ctx, chromedp.Navigate(`https://pkg.go.dev/`)); err != nil { + log.Fatal(err) +} +title, err := chromedp.Run(ctx, chromedp.Title()) +if err != nil { + log.Fatal(err) +} +fmt.Println(title) +``` + +A page event is an iterator. `chromedp.Events` subscribes when it returns, so +a program can subscribe, trigger the event, and then read it: + +```go +loaded := chromedp.Events(ctx, page.LoadEventFired) +if err := chromedp.Do(ctx, chromedp.Navigate(`https://pkg.go.dev/`)); err != nil { + log.Fatal(err) +} +for ev, err := range loaded { + if err != nil { + log.Fatal(err) + } + fmt.Println(ev.Timestamp) + break +} ``` -## Examples +[`docs/API.md`](docs/API.md) describes the API. It has 27 examples that show the +old code and the new code side by side. [`docs/MIGRATION.md`](docs/MIGRATION.md) +lists every renamed and removed name. + +See the [Go reference][goref-chromedp] for the documentation and examples. + +## More examples + +The [examples][chromedp-examples] repository has 43 programs for larger tasks. +Each program is one `main.go` file. Run one with `go run`, for example +`go run github.com/chromedp/examples/tabs@latest`. Every program takes the flag `-v` +to print the protocol messages. Every program except `remote` takes the flag +`-visible` to show the browser window. Most programs take the flag +`-visible-on-terminal` to draw the page in the terminal while they run, with +[`termcast`](#show-the-browser-in-the-terminal). Every program except `fast` +reads local content and needs no internet. Some programs take the flag `-url` to +read another site. The program `termcast` takes the flag `-fps` instead of +`-visible-on-terminal`. + +Read pages and fill forms: + +- [click](https://github.com/chromedp/examples/tree/main/click) clicks an element that a selector finds. +- [text](https://github.com/chromedp/examples/tree/main/text) reads the text of an element. +- [eval](https://github.com/chromedp/examples/tree/main/eval) runs JavaScript in the page and decodes the result. +- [structeval](https://github.com/chromedp/examples/tree/main/structeval) decodes JavaScript results into Go structs, slices and maps, and shows the errors. +- [logic](https://github.com/chromedp/examples/tree/main/logic) mixes actions and Go code to read a list. +- [subtree](https://github.com/chromedp/examples/tree/main/subtree) walks a subtree of the DOM. +- [selectors](https://github.com/chromedp/examples/tree/main/selectors) shows the typed selectors side by side. +- [frames](https://github.com/chromedp/examples/tree/main/frames) reaches elements inside an iframe and a shadow root. +- [submit](https://github.com/chromedp/examples/tree/main/submit) fills out and submits a form. +- [keys](https://github.com/chromedp/examples/tree/main/keys) sends key events to an element. +- [upload](https://github.com/chromedp/examples/tree/main/upload) uploads a file on a form. +- [visible](https://github.com/chromedp/examples/tree/main/visible) waits until an element is visible. +- [dragdrop](https://github.com/chromedp/examples/tree/main/dragdrop) drags and drops with the mouse and with HTML5 drag and drop. + +Network, sessions and files: + +- [cookie](https://github.com/chromedp/examples/tree/main/cookie) sets cookies on requests. +- [headers](https://github.com/chromedp/examples/tree/main/headers) adds extra HTTP headers. +- [proxy](https://github.com/chromedp/examples/tree/main/proxy) signs in to a proxy server that needs a password. +- [intercept](https://github.com/chromedp/examples/tree/main/intercept) blocks, mocks and changes requests with the Fetch domain. +- [session](https://github.com/chromedp/examples/tree/main/session) saves a login session and restores it in another browser. +- [har](https://github.com/chromedp/examples/tree/main/har) writes a HAR file from the network events of a page. +- [download_file](https://github.com/chromedp/examples/tree/main/download_file) downloads a file with a headless browser. +- [download_image](https://github.com/chromedp/examples/tree/main/download_image) downloads an image from the network response. + +Events and the protocol: + +- [eventsiter](https://github.com/chromedp/examples/tree/main/eventsiter) reads the events of a page with iterators, and waits for the network to be idle. +- [console](https://github.com/chromedp/examples/tree/main/console) reads the console and the uncaught exceptions of a page. +- [dialogs](https://github.com/chromedp/examples/tree/main/dialogs) answers alert, confirm, prompt and beforeunload dialogs. +- [popups](https://github.com/chromedp/examples/tree/main/popups) works with popups and several targets, and with browser contexts. +- [exposefunc](https://github.com/chromedp/examples/tree/main/exposefunc) calls Go functions from the page. +- [extension](https://github.com/chromedp/examples/tree/main/extension) loads a browser extension, uBlock Origin Lite, from a folder on disk and shows that it blocks the ads of a page. +- [latlon](https://github.com/chromedp/examples/tree/main/latlon) drives a map and reads the latitude and the longitude from the URL of the page. +- [rawcall](https://github.com/chromedp/examples/tree/main/rawcall) sends protocol commands that have no action, such as timezone, locale, geolocation and throttling. + +Screens and devices: + +- [screenshot](https://github.com/chromedp/examples/tree/main/screenshot) takes a screenshot of an element and of the whole page. +- [pdf](https://github.com/chromedp/examples/tree/main/pdf) prints a page to a PDF file. +- [pdfoptions](https://github.com/chromedp/examples/tree/main/pdfoptions) prints a page to PDF files with different options. +- [pdfstream](https://github.com/chromedp/examples/tree/main/pdfstream) reads a printed PDF as a stream. +- [emulate](https://github.com/chromedp/examples/tree/main/emulate) emulates a device, such as an iPhone. +- [screencast](https://github.com/chromedp/examples/tree/main/screencast) saves the frames of a page as JPEG files. +- [termcast](https://github.com/chromedp/examples/tree/main/termcast) plays an animated SVG and streams the screen of the browser to the terminal with `termcast`. + +Several tabs and browsers: -Refer to the [Go reference][goref-chromedp] for the documentation and examples. -Additionally, the [examples][chromedp-examples] repository contains more -examples on complex actions, and other common high-level tasks such as taking -full page screenshots. +- [tabs](https://github.com/chromedp/examples/tree/main/tabs) uses several tabs of one browser, with or without a window for each tab, and switches between them. +- [workers](https://github.com/chromedp/examples/tree/main/workers) runs many jobs at the same time in one browser with a pool of goroutines. +- [multi](https://github.com/chromedp/examples/tree/main/multi) uses the headless-shell image in a container. +- [remote](https://github.com/chromedp/examples/tree/main/remote) connects to a browser that is already running, with the package `remote`. + +The program [fast](https://github.com/chromedp/examples/tree/main/fast) reads a live site, `fast.com`, and draws an image in the terminal. It can fail when the site changes. The programs [forecast](https://github.com/chromedp/examples/tree/main/forecast) and [geoip](https://github.com/chromedp/examples/tree/main/geoip) also draw an image in the terminal. Run these programs in a terminal that can show images. +The tags of the examples repository follow the tags of `chromedp`. + +## Show the browser in the terminal + +[`termcast`][termcast] streams the screen of a `chromedp` page to a terminal +that can show images (Kitty, iTerm2 or Sixel). It uses the screencast of the +Chrome DevTools Protocol, so it works with a headless browser, also over `ssh`. +Start the browser first, and then start the stream with the context. + +```go +ctx, cancel := chromedp.NewContext(context.Background()) +defer cancel() +chromedp.Do(ctx, chromedp.Navigate("https://example.com")) // starts the browser +s, err := termcast.Start(ctx) // draws 4 frames each second +if err != nil { + log.Fatal(err) // termcast.ErrNoGraphics when the terminal has no graphics +} +defer s.Stop() +``` + +To draw one element and not the whole page, add +`termcast.WithElement(chromedp.CSS("#chart"))` to the call of `termcast.Start`. +The module `termcast` needs Go 1.25 or newer. The stream clears the terminal at +each redraw. It holds the log lines while it +runs, and prints them after the final frame. The type `termcast.Flags` adds the +flags `-visible-on-terminal` and `-terminal-fps` to a program, as the programs +in the [examples][chromedp-examples] repository have them. + +## Visible browser + +By default, `chromedp` runs Chrome in headless mode, so no window opens. To see +the browser, add `WithVisibleWindow`. Set the variable `CHROMEDP_VISIBLEWINDOW=1` +to get the same result with no change in the code. On Linux, a visible window +needs `DISPLAY` or `WAYLAND_DISPLAY`. Without them, the first `Run` returns +`chromedp.ErrNoDisplay`. + +```go +ctx, cancel := chromedp.NewContext(context.Background(), chromedp.WithVisibleWindow()) +defer cancel() +chromedp.Do(ctx, chromedp.Navigate("https://example.com")) +chromedp.WaitClosed(ctx) // block until the user closes the window +``` + +To leave the browser open after the program ends, add `remote.WithKeepOpen` from +the package `github.com/chromedp/chromedp/remote`. The program can print the +address, and another program can attach to it with `remote.NewAllocator`. The +profile directory stays on disk, and you must delete it yourself. + +```go +ctx, _ := chromedp.NewContext(context.Background(), chromedp.WithVisibleWindow(), remote.WithKeepOpen()) +chromedp.Do(ctx, chromedp.Navigate("https://example.com")) +wsURL, profile := chromedp.KeptOpen(ctx) +fmt.Println("attach to", wsURL, "profile", profile) +// The program ends here. The browser stays open. +``` + +## Remote browser + +To connect to a browser that runs already, such as a container or a hosted +service, use `remote.NewAllocator` with the websocket address of the browser: + +```go +allocCtx, cancel := remote.NewAllocator(context.Background(), "ws://127.0.0.1:9222/") +defer cancel() +ctx, cancel := chromedp.NewContext(allocCtx) +defer cancel() +title, err := chromedp.Run(ctx, chromedp.Title()) +``` + +A hosted service can need a header on the websocket request. Give the full +address of the browser and the options `remote.NoModifyURL` and +`remote.WithDialHTTPHeader`. ## Frequently Asked Questions -> I can't see any Chrome browser window +> I cannot see any Chrome browser window + +By default, `chromedp` runs Chrome in headless mode. See +[Visible browser](#visible-browser). See also +`DefaultExecAllocatorOptions`, and see [an example][goref-chromedp-exec-allocator] +that overrides the default options. + +> I see "context canceled" errors -By default, Chrome is run in headless mode. See `DefaultExecAllocatorOptions`, and -[an example][goref-chromedp-exec-allocator] to override the default options. +When the connection to the browser is lost, `chromedp` cancels the context. This +can cause the error. It happens, for example, when someone closes the browser by +hand, or when something kills the browser process. When the browser process +dies on its own, the error also holds the exit error of the process. Use +`errors.As` with an `*exec.ExitError` to read the signal or the exit status. -> I'm seeing "context canceled" errors +> How does chromedp talk to the browser it starts? -When the connection to the browser is lost, `chromedp` cancels the context, and -it may result in this error. This occurs, for example, if the browser is closed -manually, or if the browser process has been killed or otherwise terminated. +By default, through a pipe. `chromedp` starts Chrome with `--remote-debugging-pipe` +and two pipes, so Chrome opens no debugging port. On Windows the pipes are +handles that the switch `--remote-debugging-io-pipes` names. To use a +websocket and a debugging port instead, add the `remote.WebSocket` option of the +package `github.com/chromedp/chromedp/remote` to the exec allocator. A +`remote-debugging-port` or `remote-debugging-address` flag also selects the +websocket, and so does `KeepOpen`, and they all need `remote.WebSocket`. A +program for Windows needs no `remote` package for the default pipe. > Chrome exits as soon as my Go program finishes -On Linux, `chromedp` is configured to avoid leaking resources by force-killing -any started Chrome child processes. If you need to launch a long-running Chrome -instance, manually start Chrome and connect using `RemoteAllocator`. +On Linux, `chromedp` kills the Chrome child processes that it started, so that no +resources leak. To leave Chrome open, add `remote.WithKeepOpen`. See +[Visible browser](#visible-browser). You can also start Chrome yourself and +connect with `remote.NewAllocator`. + +> Calling an action or a command results in "invalid context" + +`chromedp.Do`, `chromedp.Run` and `chromedp.Call` need a context that came from +`chromedp.NewContext`, because the context holds the browser and the tab. Any +other context gives `ErrInvalidContext`. + +> How do I send a protocol command that has no action? + +Call it with `chromedp.Call`, which runs the command on the tab of the context: + +```go +ctx, cancel := chromedp.NewContext(context.Background()) +defer cancel() + +res, err := chromedp.Call(ctx, page.GetFrameTree, cdp.Empty{}) +``` + +Inside an action, call `cdp.Call(ctx, t, command, params)` with the target `t` +that the action receives. The target is the tab of the context. The commands and +their parameter structs are in `github.com/chromedp/cdproto`. + +> I have an action of the old kind + +Wrap it with `chromedp.Legacy`. The old kind is a value with a `Do(context.Context) error` +method. + +> Is it safe to use one context from several goroutines? + +Contexts that share one browser run in separate tabs, and they are safe to use +in parallel. Call `chromedp.Run` once on a parent context so that it has a +browser, and then make a child context for each goroutine with +`chromedp.NewContext`. A child of a context that has no browser yet starts a +browser of its own. + +Do not share one context between goroutines. The actions of one context run in +one tab, so they can race. For example, two `Navigate` actions on the same tab +can fail. The first `Run` on a context starts the browser, and it must +not run at the same time as another `Run` on that context. + +```go +ctx, cancel := chromedp.NewContext(context.Background()) +defer cancel() +if err := chromedp.Do(ctx); err != nil { // starts the browser + log.Fatal(err) +} +var wg sync.WaitGroup +for _, url := range urls { + wg.Go(func() { + tabCtx, cancel := chromedp.NewContext(ctx) // a new tab + defer cancel() + if err := chromedp.Do(tabCtx, chromedp.Navigate(url)); err != nil { + log.Println(url, err) + } + }) +} +wg.Wait() +``` + +> I cannot reach an element or the network events of an iframe + +Chrome runs an iframe from another site (a cross-site iframe) in its own +process, as a separate target of the type `iframe`. The DOM tree of the page does +not hold its content. The node of the `iframe` element has no `ContentDocument`, +so a query with `FromNode` finds nothing and waits until the context ends. +`chromedp` does not attach to the iframe target by itself, so the network events +of the iframe do not reach the context of the page. An iframe from the same site +is not affected. -> Executing an action without `Run` results in "invalid context" +To work in the iframe, find its target with `chromedp.Targets` and attach to it +with `chromedp.WithTargetID`. The new context runs actions in the iframe and +gets its events. The parent context must have run once, so that it has a +browser. -By default, a `chromedp` context does not have an executor, however one can be -specified manually if necessary; see [issue #326][github-326] -for an example. +```go +infos, err := chromedp.Targets(ctx) +if err != nil { + log.Fatal(err) +} +for _, info := range infos { + if info.Type == "iframe" && strings.HasPrefix(info.URL, "https://other.example/") { + frameCtx, cancel := chromedp.NewContext(ctx, chromedp.WithTargetID(info.TargetID)) + defer cancel() + text, err := chromedp.Run(frameCtx, chromedp.Text(chromedp.CSS("#inner"))) + // ... + } +} +``` -> I can't use an `Action` with `Run` because it returns many values +The other way is to turn off site isolation, so that the iframe stays in the +process of the page. Add `Flag("disable-features", "SitePerProcess,IsolateOrigins")` +and `Flag("disable-site-isolation-trials", true)` to the options of the exec +allocator. Then `FromNode` and the events of the page reach the iframe. This +turns off a security feature of Chrome. Use it only for pages that you trust. See +[`docs/decisions/2026-10-04-keep-site-isolation-on.md`](docs/decisions/2026-10-04-keep-site-isolation-on.md). -Wrap it with an `ActionFunc`: +> SendKeys with a new line inserts two line breaks + +`SendKeys` sends the character `\n` as the Enter key, in the form `\r`. That is a +keyDown event, a char event with the text `\r`, and a keyUp event. The key +`kb.Enter` is the same as `\r`, so it sends the same events and does not help. An +editor that handles Enter on keydown and cancels the default, such as Lexical, +can insert two line breaks, because the char event inserts one more. To send the +Enter key with no char event, send a rawKeyDown event and a keyUp event with +`input.DispatchKeyEvent`, and send the text before and after it with `SendKeys`: + +```go +enter := chromedp.Func(func(ctx context.Context, t *chromedp.Target) error { + for _, typ := range []input.DispatchKeyEventType{ + input.DispatchKeyEventTypeRawKeyDown, input.DispatchKeyEventTypeKeyUp, + } { + _, err := cdp.Call(ctx, t, input.DispatchKeyEvent, input.DispatchKeyEventParams{ + Type: typ, Key: "Enter", Code: "Enter", + WindowsVirtualKeyCode: 13, NativeVirtualKeyCode: 13, + }) + if err != nil { + return err + } + } + return nil +}) +err := chromedp.Do(ctx, + chromedp.SendKeys(sel, "Hello"), + enter, + chromedp.SendKeys(sel, "World"), +) +``` + +> The browser closes when the timeout of my context ends + +The first `Run` on a context starts the browser, and it binds the life of the +browser to the context that you pass to that call. When that context ends, the +browser stops. So a context from `context.WithTimeout` that you use for the +first `Run` closes the browser when the timeout ends, and every later call on the +parent context fails with `context canceled`. + +To limit one action, start the browser first with a context that has no timeout. +Then run the action with a context that you derive from it. When the timeout +ends, `Run` returns an error that wraps `context.DeadlineExceeded`. The tab and +the browser stay open, and `ctx` still works. `Run` has no option for the timeout +of one action. ```go ctx, cancel := chromedp.NewContext(context.Background()) defer cancel() -chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error { - _, err := domain.SomeAction().Do(ctx) - return err -})) +if err := chromedp.Do(ctx); err != nil { // starts the browser, with no timeout + log.Fatal(err) +} + +tctx, tcancel := context.WithTimeout(ctx, 5*time.Second) +defer tcancel() +err := chromedp.Do(tctx, chromedp.Navigate(url)) // only this call has the timeout +``` + +> Why does chromedp pass disable-dev-shm-usage, and can I turn it off? + +`DefaultExecAllocatorOptions` sets `disable-dev-shm-usage` to true. Chrome then +keeps the files of its shared memory in the temporary directory, such as `/tmp`, +and not in `/dev/shm`. The flag is on because `/dev/shm` is small in many +containers (64 MB in a default Docker container), and Chrome crashes when it +fills the space. + +The cost is that the shared memory files are file-backed memory in the temporary +directory. They can be slower, and a program that runs for a long time and opens +many pages can see growing memory. If `/dev/shm` is large enough, for example a +memory volume that you mount in a container, turn the flag off after the default +options: + +```go +opts := append(chromedp.DefaultExecAllocatorOptions[:], + chromedp.Flag("disable-dev-shm-usage", false), +) +allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...) +defer cancel() ``` > I want to use chromedp on a headless environment -The simplest way is to run the Go program that uses chromedp inside the -[chromedp/headless-shell][docker-headless-shell] image. That image contains -`headless-shell`, a smaller headless build of Chrome, which `chromedp` is able -to find out of the box. +Run the Go program that uses `chromedp` inside the +[chromedp/headless-shell][docker-headless-shell] image. The image has +`headless-shell`, a smaller headless build of Chrome. `chromedp` finds it by +default. + +## Contributing + +Read [CONTRIBUTING.md](CONTRIBUTING.md) before you send a change. +[AGENTS.md](AGENTS.md) holds the rules for people and coding agents. The tests +need Chrome or the `headless-shell` image. The repository holds two modules, and +[AGENTS.md](AGENTS.md) tells how to test each one. + +These documents are in `docs/`: + +| Document | Holds | +| --- | --- | +| [`docs/PLAN.md`](docs/PLAN.md) | the purpose, the architecture and the open questions | +| [`docs/PROGRESS.md`](docs/PROGRESS.md) | where the work stands | +| [`docs/BACKLOG.md`](docs/BACKLOG.md) | known work that is not done | +| [`docs/API.md`](docs/API.md) | the new API, with old and new code side by side | +| [`docs/MIGRATION.md`](docs/MIGRATION.md) | every renamed and removed name | +| [`docs/decisions/README.md`](docs/decisions/README.md) | the index of every recorded decision | + +## Questions and ideas + +Ask a question, or suggest a feature, in [Discussions][discussions]. The issue +tracker is for bugs. You can also chat on [Discord][discord]. ## Resources -* [`headless-shell`][docker-headless-shell] - A build of `headless-shell` that is used for testing `chromedp` +* [`headless-shell`][docker-headless-shell] - A build of `headless-shell` that the tests use * [chromedp: A New Way to Drive the Web][gophercon-2017-presentation] - GopherCon SG 2017 talk * [Chrome DevTools Protocol][devtools-protocol] - Chrome DevTools Protocol reference * [chromedp examples][chromedp-examples] - More complicated examples for `chromedp` @@ -80,11 +473,14 @@ to find out of the box. [chromedp-ci]: https://github.com/chromedp/chromedp/actions/workflows/test.yml (Test CI) [chromedp-ci-status]: https://github.com/chromedp/chromedp/actions/workflows/test.yml/badge.svg (Test CI) [chromedp-examples]: https://github.com/chromedp/examples +[termcast]: https://github.com/chromedp/termcast [chromedp-pdlgen]: https://github.com/chromedp/pdlgen [chromedp-proxy]: https://github.com/chromedp/chromedp-proxy +[discussions]: https://github.com/chromedp/chromedp/discussions +[discord]: https://discord.gg/WDWAgXwJqN "Discord Discussion" +[discord-status]: https://img.shields.io/discord/829150509658013727.svg?label=Discord&logo=Discord&colorB=7289da&style=flat-square "Discord Discussion" [devtools-protocol]: https://chromedevtools.github.io/devtools-protocol/ [docker-headless-shell]: https://hub.docker.com/r/chromedp/headless-shell/ -[github-326]: https://github.com/chromedp/chromedp/issues/326 [gophercon-2017-presentation]: https://www.youtube.com/watch?v=_7pWCg94sKw [goref-cdproto]: https://pkg.go.dev/github.com/chromedp/cdproto [goref-chromedp-exec-allocator]: https://pkg.go.dev/github.com/chromedp/chromedp#example-ExecAllocator diff --git a/vendor/github.com/chromedp/chromedp/action.go b/vendor/github.com/chromedp/chromedp/action.go new file mode 100644 index 000000000..80a8654b2 --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/action.go @@ -0,0 +1,231 @@ +package chromedp + +import ( + "context" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" + "iter" + "time" + + "github.com/chromedp/cdproto/cdp" +) + +// Void is the result type of an action that returns no value. +type Void = struct{} + +// Action is a step that runs against the target of a chromedp context and +// returns a value of the type T. An action that returns no value has the type +// Action[Void]. +// +// An action is a plain func, so a program can write its own: +// +// title := func(ctx context.Context, t *chromedp.Target) (string, error) { +// res, err := cdp.Call(ctx, t, runtime.Evaluate, runtime.EvaluateParams{ +// Expression: "document.title", +// ReturnByValue: ptr(true), +// }) +// ... +// } +// +// The target t is a [cdp.Session]. Use it with [cdp.Call] to send a protocol +// command, and with [cdp.Events] to receive protocol events. +type Action[T any] func(ctx context.Context, t *Target) (T, error) + +// Run runs the action against the target of the context, and returns its +// value. The context must be a chromedp context, typically made with +// [NewContext]. +// +// The first time that you call Run on a context, Run allocates a browser with +// the Allocator, and the browser lives as long as the context of that call. Do +// not set a timeout on the context of that first call, because the timeout +// stops the whole browser. To limit one action, run it with a context that you +// derive with [context.WithTimeout] from a context that has run once. See +// [NewContext]. +// +// For example: +// +// title, err := chromedp.Run(ctx, chromedp.Title()) +// +// If the browser process dies while nobody has asked it to stop, for example +// when it crashes or when the system kills it for lack of memory, then Run +// returns an error that wraps the exit error of the process and the error of +// the context. Use [errors.As] with a pointer to an [os/exec.ExitError] to read +// the signal or the status. +// +// Use [Do] to run several actions that return no value. +// +// Contexts that share a browser run in separate tabs, so goroutines can call +// Run in parallel when each one has its own context. Actions on one context +// share one tab, so they can race. See [NewContext]. +func Run[T any](ctx context.Context, a Action[T]) (T, error) { + c, err := initContextTarget(ctx) + if err != nil { + var zero T + return zero, FromContext(ctx).withExitError(err) + } + v, err := a(ctx, c.Target) + return v, c.withExitError(err) +} + +// Do runs the actions against the target of the context, in order. It stops at +// the first error. See [Run] for the rules about the context. +// +// For example: +// +// err := chromedp.Do(ctx, +// chromedp.Navigate("https://example.com"), +// chromedp.Click(chromedp.CSS("a")), +// ) +func Do(ctx context.Context, steps ...Action[Void]) error { + _, err := Run(ctx, Steps(steps...)) + return err +} + +// Steps joins the actions into one action that runs them in order and stops at +// the first error. It replaces the type Tasks. +func Steps(steps ...Action[Void]) Action[Void] { + return func(ctx context.Context, t *Target) (Void, error) { + for _, a := range steps { + if _, err := a(ctx, t); err != nil { + return Void{}, err + } + } + return Void{}, nil + } +} + +// Func makes an action that returns no value from a func that returns only an +// error. +func Func(f func(ctx context.Context, t *Target) error) Action[Void] { + return func(ctx context.Context, t *Target) (Void, error) { + return Void{}, f(ctx, t) + } +} + +// OldAction is the interface of an action of the previous version of chromedp. +// The previous version named it Action. +type OldAction interface { + // Do runs the action. The context holds the chromedp context. + Do(context.Context) error +} + +// Legacy makes an action from an action of the previous version. The old +// action receives the same context, so [Call] and [CallBrowser] work inside +// it. +func Legacy(a OldAction) Action[Void] { + return func(ctx context.Context, t *Target) (Void, error) { + return Void{}, a.Do(ctx) + } +} + +// Events subscribes to the event on the target of the context, and returns an +// iterator over its payloads. It replaces ListenTarget. +// +// The subscription starts when Events returns, and not when the caller starts +// to range. A caller can subscribe, trigger the event, and then range, so that +// no event is lost: +// +// events := chromedp.Events(ctx, page.LoadEventFired) +// if err := chromedp.Do(ctx, chromedp.Navigate(url)); err != nil { +// return err +// } +// for ev, err := range events { +// ... +// } +// +// As [Run] does, Events starts the browser and opens the target when the +// context has none yet. If that fails, the iterator yields the error. See +// [cdp.Events] for the rules about ending the iteration. To stop, cancel the +// context or break out of the loop. Both end the subscription, also when the +// program never ranged over the iterator. The queue of the events has no limit, +// so a reader that does not read makes it grow until the subscription ends. +func Events[E any](ctx context.Context, ev cdp.Event[E]) iter.Seq2[E, error] { + c, err := initContextTarget(ctx) + if err != nil { + return failed[E](err) + } + return cdp.Events(ctx, endWith(ctx, c.Target), ev) +} + +// BrowserEvents is like [Events] for the events of the browser, such as the +// events of the target domain. It replaces ListenBrowser. +func BrowserEvents[E any](ctx context.Context, ev cdp.Event[E]) iter.Seq2[E, error] { + c, err := initContextBrowser(ctx) + if err != nil { + return failed[E](err) + } + return cdp.Events(ctx, endWith(ctx, c.Browser), ev) +} + +// endingSession is a [cdp.Session] that ends each subscription when a context +// ends, also when nobody ranges over the iterator. +type endingSession struct { + cdp.Session + ctx context.Context +} + +// endWith returns the session s with subscriptions that end when ctx ends. +// Without it, an iterator that nobody reads keeps its subscription, and a +// goroutine that waits to deliver a queued event, for ever. +func endWith(ctx context.Context, s cdp.Session) cdp.Session { + return endingSession{Session: s, ctx: ctx} +} + +// Subscribe subscribes on the session, and ends the subscription when the +// context ends. +func (e endingSession) Subscribe(method string) (<-chan jsonv2.Value, func()) { + events, cancel := e.Session.Subscribe(method) + stop := context.AfterFunc(e.ctx, cancel) + return events, func() { + stop() + cancel() + } +} + +// failed returns an iterator that yields the error and ends. +func failed[E any](err error) iter.Seq2[E, error] { + return func(yield func(E, error) bool) { + var zero E + yield(zero, err) + } +} + +// WaitEvent makes an action that waits for an event. It subscribes to the +// event, runs the trigger action, and then returns the first payload for which +// match returns true. A nil match accepts every payload. The trigger runs after +// the subscription, so the event cannot arrive too early. +// +// For example, to wait for the load event that a click causes: +// +// _, err := chromedp.Run(ctx, chromedp.WaitEvent(page.LoadEventFired, nil, +// chromedp.Click(chromedp.CSS("a")))) +// +// When the context ends before a matching event arrives, WaitEvent returns the +// error of the context. +func WaitEvent[E, T any](ev cdp.Event[E], match func(E) bool, trigger Action[T]) Action[E] { + return func(ctx context.Context, t *Target) (E, error) { + lctx, cancel := context.WithCancel(ctx) + defer cancel() + events := cdp.Events(lctx, t, ev) + if _, err := trigger(ctx, t); err != nil { + var zero E + return zero, err + } + for e, err := range events { + if err != nil { + return e, err + } + if match == nil || match(e) { + return e, nil + } + } + var zero E + return zero, ErrChannelClosed + } +} + +// Sleep is an action that waits for the duration, or until the context ends. +func Sleep(d time.Duration) Action[Void] { + return func(ctx context.Context, t *Target) (Void, error) { + return Void{}, sleepContext(ctx, d) + } +} diff --git a/vendor/github.com/chromedp/chromedp/allocate.go b/vendor/github.com/chromedp/chromedp/allocate.go index 82acf0d68..535fe482d 100644 --- a/vendor/github.com/chromedp/chromedp/allocate.go +++ b/vendor/github.com/chromedp/chromedp/allocate.go @@ -4,36 +4,52 @@ import ( "bufio" "bytes" "context" - "errors" "fmt" "io" "os" "os/exec" "path/filepath" "runtime" + "slices" + "strings" "sync" "time" ) -// An Allocator is responsible for creating and managing a number of browsers. +// An Allocator creates and manages a number of browsers. // -// This interface abstracts away how the browser process is actually run. For -// example, an Allocator implementation may reuse browser processes, or connect -// to already-running browsers on remote machines. +// This interface hides how the browser process runs. For example, an Allocator +// can reuse browser processes, or connect to browsers that already run on +// remote machines. type Allocator interface { - // Allocate creates a new browser. It can be cancelled via the provided - // context, at which point all the resources used by the browser (such - // as temporary directories) will be freed. + // Allocate creates a new browser. Canceling the provided context frees all + // resources of the browser, such as temporary directories. Allocate(context.Context, ...BrowserOption) (*Browser, error) - // Wait blocks until an allocator has freed all of its resources. - // Cancelling the allocator context will already perform this operation, - // so normally there's no need to call Wait directly. + // Wait blocks until the allocator has freed all of its resources. + // Canceling the allocator context does this too, so normally you do not + // need to call Wait. Wait() } -// setupExecAllocator is similar to NewExecAllocator, but it allows NewContext -// to create the allocator without the unnecessary context layer. +// An Attacher is an optional interface of an Allocator. An allocator that +// implements it connects to a browser that already runs, and it does not start +// the browser itself. NewContext then treats the context of such an allocator +// as a new tab of that browser, and not as the owner of a browser process. The +// allocator of the package github.com/chromedp/chromedp/remote implements it. +type Attacher interface { + // Attaches reports whether the allocator attaches to a browser that + // runs already. + Attaches() bool +} + +// A Dialer connects to the websocket address of a browser and returns the +// connection as a Transport. The package github.com/chromedp/chromedp/remote +// has a Dialer. See [WithDialer]. +type Dialer = func(ctx context.Context, wsURL string) (Transport, error) + +// setupExecAllocator is like NewExecAllocator, but NewContext uses it to +// create the allocator without an extra context layer. func setupExecAllocator(opts ...ExecAllocatorOption) *ExecAllocator { ep := &ExecAllocator{ initFlags: make(map[string]any), @@ -48,9 +64,27 @@ func setupExecAllocator(opts ...ExecAllocatorOption) *ExecAllocator { return ep } -// DefaultExecAllocatorOptions are the ExecAllocator options used by NewContext -// if the given parent context doesn't have an allocator set up. Do not modify -// this global; instead, use NewExecAllocator. See [ExampleExecAllocator]. +// DefaultExecAllocatorOptions are the ExecAllocator options that NewContext +// uses when the parent context has no allocator. Do not modify this global. +// Use NewExecAllocator instead. See [ExampleExecAllocator]. +// +// The list runs the browser in headless mode. To get a visible window, add +// [VisibleWindow] to a copy of the list, or give [WithVisibleWindow] to +// NewContext. +// +// The list sets disable-dev-shm-usage to true. Chrome then keeps the files of +// its shared memory in the temporary directory, such as /tmp, and not in +// /dev/shm. The flag is on because /dev/shm is small in many containers, for +// example 64 MB in a default Docker container, and Chrome crashes when it fills +// the space. The cost is that these files are file-backed memory in the +// temporary directory, which can be slower, and which a program that runs for a +// long time and opens many pages can see as growing memory. If /dev/shm is large +// enough, turn the flag off with Flag("disable-dev-shm-usage", false) after the +// default options: +// +// opts := append(chromedp.DefaultExecAllocatorOptions[:], +// chromedp.Flag("disable-dev-shm-usage", false), +// ) // // [ExampleExecAllocator]: https://pkg.go.dev/github.com/chromedp/chromedp#example-ExecAllocator var DefaultExecAllocatorOptions = [...]ExecAllocatorOption{ @@ -68,7 +102,7 @@ var DefaultExecAllocatorOptions = [...]ExecAllocatorOption{ Flag("disable-default-apps", true), Flag("disable-dev-shm-usage", true), Flag("disable-extensions", true), - Flag("disable-features", "site-per-process,Translate,BlinkGenPropertyTrees"), + Flag("disable-features", "Translate,BlinkGenPropertyTrees"), Flag("disable-hang-monitor", true), Flag("disable-ipc-flooding-protection", true), Flag("disable-popup-blocking", true), @@ -83,8 +117,20 @@ var DefaultExecAllocatorOptions = [...]ExecAllocatorOption{ Flag("use-mock-keychain", true), } -// NewExecAllocator creates a new context set up with an ExecAllocator, suitable -// for use with NewContext. +// defaultExecAllocatorOptions returns the options that NewContext uses to make +// the default allocator. It is the only place that builds that list from +// DefaultExecAllocatorOptions, so that the options of NewContext and the options +// that a caller of NewExecAllocator builds from the same list cannot drift. +func defaultExecAllocatorOptions(visibleWindow bool, extra []ExecAllocatorOption) []ExecAllocatorOption { + opts := slices.Clone(DefaultExecAllocatorOptions[:]) + if visibleWindow { + opts = append(opts, VisibleWindow) + } + return append(opts, extra...) +} + +// NewExecAllocator creates a new context with an ExecAllocator. Use it with +// NewContext. func NewExecAllocator(parent context.Context, opts ...ExecAllocatorOption) (context.Context, context.CancelFunc) { ctx, cancel := context.WithCancel(parent) c := &Context{Allocator: setupExecAllocator(opts...)} @@ -97,6 +143,17 @@ func NewExecAllocator(parent context.Context, opts ...ExecAllocatorOption) (cont return ctx, cancelWait } +// NewAllocatorContext creates a new context that holds the allocator a. Use it +// with NewContext, as with the context of NewExecAllocator. It is for an +// Allocator that another package implements, such as the allocator of the package +// github.com/chromedp/chromedp/remote. +// +// The cancel func cancels the context. It does not call the Wait method of a. +func NewAllocatorContext(parent context.Context, a Allocator) (context.Context, context.CancelFunc) { + ctx, cancel := context.WithCancel(parent) + return context.WithValue(ctx, contextKey{}, &Context{Allocator: a}), cancel +} + // ExecAllocatorOption is an exec allocator option. type ExecAllocatorOption = func(*ExecAllocator) @@ -107,44 +164,70 @@ type ExecAllocator struct { initFlags map[string]any initEnv []string - // Chrome will sometimes fail to print the websocket, or run for a long - // time, without properly exiting. To avoid blocking forever in those - // cases, give up after a specified timeout. + // noInheritEnv is set by NoInheritEnv. + noInheritEnv bool + + // flagOrder holds the names of initFlags in the order of their first + // set. Chrome needs some flags in order, such as --flag-switches-begin + // and --flag-switches-end around the switches of chrome://flags, and a + // map has no order. + flagOrder []string + + // dialer is set by WithDialer. The allocator then connects to the browser + // with a websocket instead of a pipe. + dialer Dialer + + // Chrome sometimes does not print the websocket address, or runs for a + // long time without exit. Give up after a timeout, so that we do not block + // forever. It only applies to the websocket mode. wsURLReadTimeout time.Duration modifyCmdFunc func(cmd *exec.Cmd) + // keepOpen is set by KeepOpen. See keepopen.go. + keepOpen bool + + // visibleWindow is set by VisibleWindow. Allocate then checks for a + // display before it starts the browser. + visibleWindow bool + wg sync.WaitGroup combinedOutputWriter io.Writer } -// allocTempDir is used to group all ExecAllocator temporary user data dirs in -// the same location, useful for the tests. If left empty, the system's default -// temporary directory is used. +// allocTempDir is the location of all temporary user data directories of +// ExecAllocator. The tests use it. If it is empty, ExecAllocator uses the +// default temporary directory of the system. var allocTempDir string -// Allocate satisfies the Allocator interface. +// Allocate satisfies the Allocator interface. It returns [ErrNoDialer] when the +// allocator needs a websocket and has no dialer. func (a *ExecAllocator) Allocate(ctx context.Context, opts ...BrowserOption) (*Browser, error) { c := FromContext(ctx) if c == nil { return nil, ErrInvalidContext } - var args []string - for name, value := range a.initFlags { - switch value := value.(type) { - case string: - args = append(args, fmt.Sprintf("--%s=%s", name, value)) - case bool: - if value { - args = append(args, fmt.Sprintf("--%s", name)) - } - default: - return nil, fmt.Errorf("invalid exec pool flag") + if a.visibleWindow { + if err := checkDisplay(); err != nil { + return nil, err } } + if !a.usesPipe() && a.dialer == nil { + return nil, ErrNoDialer + } + + if a.keepOpen { + return a.allocateKeepOpen(ctx, c, opts) + } + + args, err := a.flagArgs() + if err != nil { + return nil, err + } + removeDir := false dataDir, ok := a.initFlags["user-data-dir"].(string) if !ok { @@ -157,75 +240,120 @@ func (a *ExecAllocator) Allocate(ctx context.Context, opts ...BrowserOption) (*B removeDir = true } if _, ok := a.initFlags["no-sandbox"]; !ok && os.Getuid() == 0 { - // Running as root, for example in a Linux container. Chrome - // needs --no-sandbox when running as root, so make that the - // default, unless the user set Flag("no-sandbox", false). + // We run as root, for example in a Linux container. Chrome needs + // --no-sandbox as root, so make that the default, unless the user set + // Flag("no-sandbox", false). args = append(args, "--no-sandbox") } - if _, ok := a.initFlags["remote-debugging-port"]; !ok { + pipe := a.usesPipe() + if pipe { + if v, _ := a.initFlags["remote-debugging-pipe"].(bool); !v { + args = append(args, "--remote-debugging-pipe") + } + } else if _, ok := a.initFlags["remote-debugging-port"]; !ok { args = append(args, "--remote-debugging-port=0") } - // Force the first page to be blank, instead of the welcome page; - // --no-first-run doesn't enforce that. + // Force the first page to be blank, and not the welcome page. + // --no-first-run does not do that. args = append(args, "about:blank") cmd := exec.CommandContext(ctx, a.execPath, args...) defer func() { if removeDir && cmd.Process == nil { - // We couldn't start the process, so we didn't get to - // the goroutine that handles RemoveAll below. Remove it - // to not leave an empty directory. + // The process did not start, so we do not reach the goroutine that + // calls RemoveAll below. Remove the directory here, so that no + // empty directory stays. os.RemoveAll(dataDir) } }() + // In the pipe mode, the pipes are set up before ModifyCmdFunc runs, so + // that the function can see them. + var pf *pipeFiles + connected := false + if pipe { + var err error + if pf, err = newPipeFiles(cmd); err != nil { + return nil, err + } + // The browser process has its own copies after it starts. + defer pf.closeChild() + defer func() { + if !connected { + pf.closeParent() + } + }() + } + if a.modifyCmdFunc != nil { a.modifyCmdFunc(cmd) } else { allocateCmdOptions(cmd) } - stdout, err := cmd.StdoutPipe() - if err != nil { - return nil, err + var stdout io.ReadCloser + if !pipe { + var err error + if stdout, err = cmd.StdoutPipe(); err != nil { + return nil, err + } + cmd.Stderr = cmd.Stdout } - cmd.Stderr = cmd.Stdout - // Preserve environment variables set in the (lowest priority) existing - // environment, OverrideCmdFunc(), and Env (highest priority) - if len(a.initEnv) > 0 || len(cmd.Env) > 0 { - cmd.Env = append(os.Environ(), cmd.Env...) - cmd.Env = append(cmd.Env, a.initEnv...) + a.setCmdEnv(cmd) + + // A canceled context must give its own error. On Windows, os/exec + // reports a program that it cannot find before it looks at the context. + if err := ctx.Err(); err != nil { + return nil, err } - // We must start the cmd before calling cmd.Wait, as otherwise the two - // can run into a data race. - if err := cmd.Start(); err != nil { + // The goroutine of startCmd starts the browser and waits for it. + run := startCmd(cmd) + if err := <-run.started; err != nil { return nil, err } select { case <-ctx.Done(): + // Chrome started, but nothing else will remove its directory. The + // context is done, so Chrome is killed. + <-run.done + if removeDir { + killLeftovers(dataDir) + removeAllRetry(dataDir) + } return nil, ctx.Err() case <-c.allocated: // for this browser's root context } + var out *browserOutput + if pipe { + // The browser has its own copy of the child ends now. + pf.closeChild() + out = startBrowserOutput(&a.wg, pf.outR, a.combinedOutputWriter) + } + exited := make(chan struct{}) a.wg.Add(1) // for the entire allocator go func() { - // First wait for the process to be finished. - // TODO: do we care about this error in any scenario? if the - // user cancelled the context and killed chrome, this will most - // likely just be "signal: killed", which isn't interesting. - cmd.Wait() + // First wait for the process to finish. + <-run.done + if out != nil { + out.finish() + } + close(exited) // Then delete the temporary user data directory, if needed. if removeDir { - // Sometimes files/directories are still created in the user data - // directory at this point. I can not reproduce it with strace, so - // the reason is unknown yet. As a workaround, we will just wait a - // little while before removing the directory. + // Child processes of Chrome can outlive it, and write in the + // directory after it is removed. + killLeftovers(dataDir) + // Sometimes Chrome still creates files or directories in the user + // data directory at this point. We cannot reproduce it with strace, + // so the reason is unknown. As a workaround, wait a short time + // before we remove the directory. <-time.After(10 * time.Millisecond) - if err := os.RemoveAll(dataDir); c.cancelErr == nil { + if err := removeAllRetry(dataDir); c.cancelErr == nil { c.cancelErr = err } } @@ -233,11 +361,115 @@ func (a *ExecAllocator) Allocate(ctx context.Context, opts ...BrowserOption) (*B close(c.allocated) }() + var browser *Browser + if pipe { + var err error + browser, err = connectPipe(ctx, pf, cmd, out, exited, opts) + if err != nil { + return nil, err + } + connected = true + } else { + var err error + if browser, err = a.connectWebSocket(ctx, stdout, opts); err != nil { + return nil, err + } + } + go func() { + // If the browser loses the connection, kill the whole process and the + // handler at once. Do not use Cancel, because Cancel tries to close the + // browser gracefully, and that hangs. + // Do not cancel in the middle of a graceful Close, because Chrome must + // shut itself down when it finishes. + <-browser.LostConnection + select { + case <-browser.closingGracefully: + default: + browser.noteLost(ctx) + c.cancel() + } + }() + browser.process = cmd.Process + browser.userDataDir = dataDir + browser.exited = exited + browser.reaped = run.done + browser.exitErr = &run.err + return browser, nil +} + +// cmdRun is a browser process that startCmd started. +type cmdRun struct { + // started receives the error of cmd.Start. It receives nil when the + // process runs. + started chan error + + // done closes when the process exits. It never closes when Start failed. + done chan struct{} + + // err is the error of cmd.Wait. It is valid after done closes. It is an + // *exec.ExitError when the process ended with a signal or with a status + // other than zero. + err error +} + +// startCmd starts cmd and waits for it in one goroutine, which it locks to its +// OS thread. +// +// On Linux, the option Pdeathsig of the allocator makes the kernel kill the +// browser when the OS thread that started it exits, and not when the process +// exits. A goroutine can move to another thread, and a thread can end, for +// example when a locked goroutine ends without an unlock. So the browser must +// start from a goroutine that stays on its thread until the browser exits. See +// https://go.dev/issue/27505 and the issue 1566 of chromedp. +func startCmd(cmd *exec.Cmd) *cmdRun { + r := &cmdRun{ + started: make(chan error, 1), + done: make(chan struct{}), + } + go func() { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + // Start the process before Wait, as the two race otherwise. + err := cmd.Start() + r.started <- err + if err != nil { + return + } + r.err = cmd.Wait() + close(r.done) + }() + return r +} + +// flagArgs returns the command line arguments for the flags of the allocator. +func (a *ExecAllocator) flagArgs() ([]string, error) { + var args []string + for _, name := range a.flagOrder { + switch value := a.initFlags[name].(type) { + case string: + args = append(args, fmt.Sprintf("--%s=%s", name, value)) + case bool: + if value { + args = append(args, fmt.Sprintf("--%s", name)) + } + default: + return nil, fmt.Errorf("invalid exec pool flag") + } + } + return args, nil +} + +// connectWebSocket waits for the websocket address in the output of the +// browser, and connects to it. +func (a *ExecAllocator) connectWebSocket(ctx context.Context, stdout io.ReadCloser, opts []BrowserOption) (*Browser, error) { var wsURL string wsURLChan := make(chan struct{}) var copy func() + var output syncBuffer + var err error go func() { - wsURL, copy, err = readOutput(stdout, a.combinedOutputWriter) + wsURL, copy, err = readOutputTo(stdout, a.combinedOutputWriter, &output) close(wsURLChan) }() select { @@ -247,7 +479,7 @@ func (a *ExecAllocator) Allocate(ctx context.Context, opts ...BrowserOption) (*B } case <-time.After(a.wsURLReadTimeout): - return nil, errors.New("websocket url timeout reached") + return nil, fmt.Errorf("websocket url timeout reached after %v, chrome printed:\n%s", a.wsURLReadTimeout, output.String()) } if a.combinedOutputWriter != nil && copy != nil { @@ -256,42 +488,96 @@ func (a *ExecAllocator) Allocate(ctx context.Context, opts ...BrowserOption) (*B }) } - browser, err := NewBrowser(ctx, wsURL, opts...) + return a.dial(ctx, wsURL, opts) +} + +// dial connects to the websocket address wsURL with the dialer of the +// allocator, and returns a browser that uses the connection. +func (a *ExecAllocator) dial(ctx context.Context, wsURL string, opts []BrowserOption) (*Browser, error) { + tr, err := a.dialer(ctx, wsURL) if err != nil { - return nil, err + return nil, fmt.Errorf("could not dial %q: %w", wsURL, err) } - go func() { - // If the browser loses connection, kill the entire process and - // handler at once. Don't use Cancel, as that will attempt to - // gracefully close the browser, which will hang. - // Don't cancel if we're in the middle of a graceful Close, - // since we want to let Chrome shut itself when it is fully - // finished. - <-browser.LostConnection - select { - case <-browser.closingGracefully: - default: - c.cancel() + return NewBrowserTransport(ctx, tr, opts...) +} + +// usesPipe reports whether Allocate connects to the browser with a pipe. It +// does not when the allocator has a dialer or the KeepOpen option is set, or +// when the flags ask for a debugging port or address. +func (a *ExecAllocator) usesPipe() bool { + if a.dialer != nil || a.keepOpen { + return false + } + for _, name := range []string{"remote-debugging-port", "remote-debugging-address"} { + if _, ok := a.initFlags[name]; ok { + return false } - }() - browser.process = cmd.Process - browser.userDataDir = dataDir - return browser, nil + } + return true } -// readOutput grabs the websocket address from chrome's output, returning as -// soon as it is found. All read output is forwarded to forward, if non-nil. -// done is used to signal that the asynchronous io.Copy is done, if any. +// removeAllRetry removes dir like os.RemoveAll. Chrome child processes, such as +// the crashpad handler, can still write files in dir after the main process +// exits. Then os.RemoveAll fails with "directory not empty". So +// removeAllRetry tries again for a few seconds. +func removeAllRetry(dir string) error { + return retryRemove(dir, os.RemoveAll, 5*time.Second, 20*time.Millisecond) +} + +// retryRemove calls remove with dir until it returns nil, or until the limit +// is over. It waits pause between two calls, and returns the last error. +func retryRemove(dir string, remove func(string) error, limit, pause time.Duration) error { + deadline := time.Now().Add(limit) + for { + err := remove(dir) + if err == nil || !time.Now().Before(deadline) { + return err + } + time.Sleep(pause) + } +} + +// readOutput reads the websocket address from the output of Chrome and returns +// as soon as it finds the address. It forwards all output that it reads to +// forward, if forward is not nil. It signals on done when the asynchronous +// io.Copy ends, if there is one. func readOutput(rc io.ReadCloser, forward io.Writer) (wsURL string, _ func(), _ error) { + return readOutputTo(rc, forward, new(syncBuffer)) +} + +// syncBuffer is a bytes.Buffer that is safe to use from more than one +// goroutine. +type syncBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +// Write satisfies the io.Writer interface. +func (b *syncBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +// String returns the text that was written. +func (b *syncBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +// readOutputTo is like readOutput. It also writes the output that it read +// before the websocket address to accumulated. A caller that gives up can then +// show what the browser printed. +func readOutputTo(rc io.ReadCloser, forward io.Writer, accumulated *syncBuffer) (wsURL string, _ func(), _ error) { prefix := []byte("DevTools listening on") - var accumulated bytes.Buffer bufr := bufio.NewReader(rc) readLoop: for { line, err := bufr.ReadBytes('\n') if err != nil { return "", nil, fmt.Errorf("chrome failed to start:\n%s", - accumulated.Bytes()) + accumulated.String()) } if forward != nil { if _, err := forward.Write(line); err != nil { @@ -310,12 +596,12 @@ readLoop: } copy := func() {} if forward == nil { - // We don't need the process's output anymore. + // We do not need the process's output anymore. rc.Close() } else { - // Return a function that will be called later to - // copy the rest of the output in a separate goroutine, as we - // need to return with the websocket URL. + // Return a func that the caller calls later to copy the rest of the + // output in a separate goroutine. We must return the websocket URL + // now. copy = func() { io.Copy(forward, bufr) } } return wsURL, copy, nil @@ -326,9 +612,9 @@ func (a *ExecAllocator) Wait() { a.wg.Wait() } -// ExecPath returns an ExecAllocatorOption which uses the given path to execute -// browser processes. The given path can be an absolute path to a binary, or -// just the name of the program to find via exec.LookPath. +// ExecPath returns an ExecAllocatorOption that uses the given path to run +// browser processes. The path can be an absolute path to a binary, or the name +// of a program that exec.LookPath finds. func ExecPath(path string) ExecAllocatorOption { return func(a *ExecAllocator) { // Convert to an absolute path if possible, to avoid @@ -341,13 +627,28 @@ func ExecPath(path string) ExecAllocatorOption { } } -// findExecPath tries to find the Chrome browser somewhere in the current -// system. It finds in different locations on different OS systems. -// It could perform a rather aggressive search. That may make it a bit slow, -// but it will only be run when creating a new ExecAllocator. +// findExecPath looks for the Chrome browser on the system. It looks in +// different places on different operating systems. The search can be +// aggressive and a bit slow, but it runs only when you create a new +// ExecAllocator. On Windows, it looks for Chrome first and for Microsoft Edge +// after it. func findExecPath() string { + for _, path := range execLocations(runtime.GOOS) { + found, err := exec.LookPath(path) + if err == nil { + return found + } + } + // Fall back to something simple and sensible, to give a useful error + // message. + return "google-chrome" +} + +// execLocations returns the names and paths that findExecPath tries for the +// operating system goos, in order. +func execLocations(goos string) []string { var locations []string - switch runtime.GOOS { + switch goos { case "darwin": locations = []string{ // Mac @@ -363,6 +664,12 @@ func findExecPath() string { `C:\Program Files\Google\Chrome\Application\chrome.exe`, filepath.Join(os.Getenv("USERPROFILE"), `AppData\Local\Google\Chrome\Application\chrome.exe`), filepath.Join(os.Getenv("USERPROFILE"), `AppData\Local\Chromium\Application\chrome.exe`), + // Microsoft Edge is built on Chromium. Windows has it on every + // machine, so use it when no Chrome is installed. + "msedge", + "msedge.exe", // in case PATHEXT is misconfigured + `C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe`, + `C:\Program Files\Microsoft\Edge\Application\msedge.exe`, } default: locations = []string{ @@ -382,50 +689,94 @@ func findExecPath() string { } } - for _, path := range locations { - found, err := exec.LookPath(path) - if err == nil { - return found - } - } - // Fall back to something simple and sensible, to give a useful error - // message. - return "google-chrome" + return locations } -// Flag is a generic command line option to pass a flag to Chrome. If the value -// is a string, it will be passed as --name=value. If it's a boolean, it will be -// passed as --name if value is true. +// Flag is a generic command line option that passes a flag to Chrome. If the +// value is a string, Flag passes --name=value. If it is a boolean, Flag passes +// --name when the value is true. +// +// The flags go to Chrome in the order of the options. Set a flag again, and it +// keeps its first place with the new value. This order matters for the flags +// --flag-switches-begin and --flag-switches-end, which must surround the +// switches that Chrome takes as the switches of chrome://flags. When you add to +// a copy of [DefaultExecAllocatorOptions], the default flags come first. func Flag(name string, value any) ExecAllocatorOption { return func(a *ExecAllocator) { - a.initFlags[name] = value + a.setFlag(name, value) + } +} + +// setFlag sets the flag name. A flag that is set again keeps its place. +func (a *ExecAllocator) setFlag(name string, value any) { + if _, ok := a.initFlags[name]; !ok { + a.flagOrder = append(a.flagOrder, name) + } + a.initFlags[name] = value +} + +// deleteFlag removes the flag name, if it is set. +func (a *ExecAllocator) deleteFlag(name string) { + if _, ok := a.initFlags[name]; !ok { + return } + delete(a.initFlags, name) + a.flagOrder = slices.DeleteFunc(a.flagOrder, func(n string) bool { return n == name }) } -// Env is a list of generic environment variables in the form NAME=value -// to pass into the new Chrome process. These will be appended to the -// environment of the Go process as retrieved by os.Environ. +// Env sets environment variables, in the form NAME=value, for the new Chrome +// process. They add to the environment of the Go process, which os.Environ +// returns. To start the browser with only these variables, add [NoInheritEnv]. func Env(vars ...string) ExecAllocatorOption { return func(a *ExecAllocator) { a.initEnv = append(a.initEnv, vars...) } } -// ModifyCmdFunc allows for running an arbitrary function on the -// browser exec.Cmd object. This overrides the default version -// of the command which sends SIGKILL to any open browsers when -// the Go program exits. +// NoInheritEnv is an allocator option that starts the browser with only the +// variables that [Env] gives, and the variables that a func of [ModifyCmdFunc] +// sets in cmd.Env. The browser does not get the environment of the Go process. +// Use it to keep the secrets of the program away from the browser. +// +// On Linux, the browser then starts with an empty environment. A program can +// want to pass HOME, PATH, DISPLAY (or WAYLAND_DISPLAY) for a headed browser, +// and XDG_RUNTIME_DIR. On Windows, [os/exec] adds SYSTEMROOT by itself, and a +// browser can also need TEMP, LOCALAPPDATA and USERPROFILE. Give each variable +// that the browser needs to [Env]. Without the option, the browser gets the +// whole environment of the Go process, as before. +func NoInheritEnv(a *ExecAllocator) { + a.noInheritEnv = true +} + +// setCmdEnv sets the environment of the command of the browser. The lowest +// priority is the environment of the Go process, unless NoInheritEnv is set. +// Then come the variables that ModifyCmdFunc set, and then those of Env. +func (a *ExecAllocator) setCmdEnv(cmd *exec.Cmd) { + switch { + case a.noInheritEnv: + // A nil Env makes the process inherit the environment, so the slice + // must not be nil. + env := make([]string, 0, len(cmd.Env)+len(a.initEnv)) + env = append(env, cmd.Env...) + cmd.Env = append(env, a.initEnv...) + case len(a.initEnv) > 0 || len(cmd.Env) > 0: + cmd.Env = append(os.Environ(), cmd.Env...) + cmd.Env = append(cmd.Env, a.initEnv...) + } +} + +// ModifyCmdFunc runs a func on the exec.Cmd of the browser. It replaces the +// default func, which sends SIGKILL to any open browsers when the Go program +// exits. func ModifyCmdFunc(f func(cmd *exec.Cmd)) ExecAllocatorOption { return func(a *ExecAllocator) { a.modifyCmdFunc = f } } -// UserDataDir is the command line option to set the user data dir. -// -// Note: set this option to manually set the profile directory used by Chrome. -// When this is not set, then a default path will be created in the /tmp -// directory. +// UserDataDir is the command line option to set the user data directory. Use +// it to choose the profile directory of Chrome. Without it, ExecAllocator +// creates a default path in the /tmp directory. func UserDataDir(dir string) ExecAllocatorOption { return Flag("user-data-dir", dir) } @@ -435,9 +786,8 @@ func ProxyServer(proxy string) ExecAllocatorOption { return Flag("proxy-server", proxy) } -// IgnoreCertErrors is the command line option to ignore certificate-related -// errors. This option is useful when you need to access an HTTPS website -// through a proxy. +// IgnoreCertErrors is the command line option to ignore certificate errors. +// Use it to access an HTTPS website through a proxy. func IgnoreCertErrors(a *ExecAllocator) { Flag("ignore-certificate-errors", true)(a) } @@ -470,8 +820,8 @@ func NoDefaultBrowserCheck(a *ExecAllocator) { Flag("no-default-browser-check", true)(a) } -// Headless is the command line option to run in headless mode. On top of -// setting the headless flag, it also hides scrollbars and mutes audio. +// Headless is the command line option to run in headless mode. It sets the +// headless flag, hides scrollbars, and mutes audio. func Headless(a *ExecAllocator) { Flag("headless", true)(a) // Like in Puppeteer. @@ -479,135 +829,100 @@ func Headless(a *ExecAllocator) { Flag("mute-audio", true)(a) } +// VisibleWindow is the command line option to run the browser with a visible +// window. It removes the flags that make the browser quiet or hidden, and it +// starts the window maximized. +// +// It removes these flags: headless, hide-scrollbars, mute-audio, +// enable-automation (the infobar that says that software controls the +// browser) and disable-extensions. It keeps every other flag, and it adds +// start-maximized. It does not open the developer tools. To open them for every +// tab, add Flag("auto-open-devtools-for-tabs", true). +// +// Add VisibleWindow after the options that it must change. It only removes the +// flags that exist when it runs. For example: +// +// opts := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.VisibleWindow) +// ctx, cancel := chromedp.NewExecAllocator(context.Background(), opts...) +// +// On Linux, Allocate returns ErrNoDisplay when the environment variables +// DISPLAY and WAYLAND_DISPLAY are both empty. The allocator never falls back to +// headless mode. Allocate does no such check on macOS and Windows. +func VisibleWindow(a *ExecAllocator) { + for _, name := range []string{ + "headless", + "hide-scrollbars", + "mute-audio", + "enable-automation", + "disable-extensions", + } { + a.deleteFlag(name) + } + Flag("start-maximized", true)(a) + a.visibleWindow = true +} + +// visibleWindowEnv is the name of the environment variable that has the same +// effect as WithVisibleWindow. +const visibleWindowEnv = "CHROMEDP_VISIBLEWINDOW" + +// visibleWindowFromEnv reports whether the environment variable +// CHROMEDP_VISIBLEWINDOW asks for a visible window. Any value other than the +// empty string, "false" and "0" does. +func visibleWindowFromEnv() bool { + v := os.Getenv(visibleWindowEnv) + return v != "" && v != "0" && !strings.EqualFold(v, "false") +} + // DisableGPU is the command line option to disable the GPU process. // -// The --disable-gpu option is a temporary workaround for a few bugs -// in headless mode. According to the references below, it's no longer required: +// The --disable-gpu option is a temporary workaround for a few bugs in +// headless mode. The references below say that it is no longer required: // - https://bugs.chromium.org/p/chromium/issues/detail?id=737678 // - https://github.com/puppeteer/puppeteer/pull/2908 // - https://github.com/puppeteer/puppeteer/pull/4523 // -// But according to this reported issue, it's still required in some cases: +// But this issue says that it is still required in some cases: // - https://github.com/chromedp/chromedp/issues/904 // -// Chromium 139+ doesn't provide fallback to Swiftshader unless the -// --enable-unsafe-swiftshader option is passed: +// Chromium 139 and later has no fallback to Swiftshader, unless you pass the +// --enable-unsafe-swiftshader option: // - https://chromestatus.com/feature/5166674414927872 func DisableGPU(a *ExecAllocator) { Flag("disable-gpu", true)(a) Flag("enable-unsafe-swiftshader", true)(a) } -// CombinedOutput is used to set an io.Writer where stdout and stderr -// from the browser will be sent +// CombinedOutput sets the io.Writer that receives the stdout and stderr of the +// browser. func CombinedOutput(w io.Writer) ExecAllocatorOption { return func(a *ExecAllocator) { a.combinedOutputWriter = w } } -// WSURLReadTimeout sets the waiting time for reading the WebSocket URL. -// The default value is 20 seconds. -func WSURLReadTimeout(t time.Duration) ExecAllocatorOption { - return func(a *ExecAllocator) { - a.wsURLReadTimeout = t - } -} - -// NewRemoteAllocator creates a new context set up with a RemoteAllocator, -// suitable for use with NewContext. The url should point to the browser's -// websocket address, such as "ws://127.0.0.1:$PORT/devtools/browser/...". -// -// If the url does not contain "/devtools/browser/", it will try to detect -// the correct one by sending a request to "http://$HOST:$PORT/json/version". -// -// The url with the following formats are accepted: -// - ws://127.0.0.1:9222/ -// - http://127.0.0.1:9222/ -// -// But "ws://127.0.0.1:9222/devtools/browser/" are not accepted. -// Because the allocator won't try to modify it and it's obviously invalid. +// WithDialer is an ExecAllocatorOption that makes the allocator connect to the +// browser with a websocket, as chromedp did before the pipe became the default. +// The allocator starts the browser with a debugging port, reads the websocket +// address, and calls d to connect to it. // -// Use chromedp.NoModifyURL to prevent it from modifying the url. -func NewRemoteAllocator(parent context.Context, url string, opts ...RemoteAllocatorOption) (context.Context, context.CancelFunc) { - a := &RemoteAllocator{ - wsURL: url, - modifyURLFunc: modifyURL, - } - for _, o := range opts { - o(a) +// The core module has no websocket code, so it needs a dialer. The function +// WebSocket of the package github.com/chromedp/chromedp/remote makes the +// ExecAllocatorOption that sets one. Use a dialer when the browser must open a +// debugging port, for example to let a second program connect to it. The Flag +// options "remote-debugging-port" and "remote-debugging-address" also need a +// dialer. +func WithDialer(d Dialer) ExecAllocatorOption { + return func(a *ExecAllocator) { + a.dialer = d } - c := &Context{Allocator: a} - - ctx, cancel := context.WithCancel(parent) - ctx = context.WithValue(ctx, contextKey{}, c) - return ctx, cancel -} - -// RemoteAllocatorOption is a remote allocator option. -type RemoteAllocatorOption = func(*RemoteAllocator) - -// RemoteAllocator is an Allocator which connects to an already running Chrome -// process via a websocket URL. -type RemoteAllocator struct { - wsURL string - modifyURLFunc func(ctx context.Context, wsURL string) (string, error) - - wg sync.WaitGroup } -// Allocate satisfies the Allocator interface. -func (a *RemoteAllocator) Allocate(ctx context.Context, opts ...BrowserOption) (*Browser, error) { - c := FromContext(ctx) - if c == nil { - return nil, ErrInvalidContext - } - - wsURL := a.wsURL - var err error - if a.modifyURLFunc != nil { - wsURL, err = a.modifyURLFunc(ctx, wsURL) - if err != nil { - return nil, fmt.Errorf("failed to modify wsURL: %w", err) - } - } - - // Use a different context for the websocket, so we can have a chance at - // closing the relevant pages before closing the websocket connection. - wctx, cancel := context.WithCancel(context.Background()) - - close(c.allocated) - // for the entire allocator - a.wg.Go(func() { - <-ctx.Done() - Cancel(ctx) // block until all pages are closed - cancel() // close the websocket connection - }) - - browser, err := NewBrowser(wctx, wsURL, opts...) - if err != nil { - return nil, err +// WSURLReadTimeout sets how long ExecAllocator waits to read the WebSocket +// URL. The default is 20 seconds. It only applies to the websocket mode, see +// [WithDialer]. +func WSURLReadTimeout(t time.Duration) ExecAllocatorOption { + return func(a *ExecAllocator) { + a.wsURLReadTimeout = t } - go func() { - // If the browser loses connection, kill the entire process and - // handler at once. - <-browser.LostConnection - select { - case <-browser.closingGracefully: - default: - Cancel(ctx) - } - }() - return browser, nil -} - -// Wait satisfies the Allocator interface. -func (a *RemoteAllocator) Wait() { - a.wg.Wait() -} - -// NoModifyURL is a RemoteAllocatorOption that prevents the remote allocator -// from modifying the websocket debugger URL passed to it. -func NoModifyURL(a *RemoteAllocator) { - a.modifyURLFunc = nil } diff --git a/vendor/github.com/chromedp/chromedp/allocate_darwin.go b/vendor/github.com/chromedp/chromedp/allocate_darwin.go new file mode 100644 index 000000000..bee25e433 --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/allocate_darwin.go @@ -0,0 +1,81 @@ +//go:build darwin + +package chromedp + +import ( + "os" + "os/exec" + "strconv" + "strings" + "syscall" + "time" +) + +// checkDisplay does nothing on this platform. +func checkDisplay() error { + return nil +} + +func allocateCmdOptions(cmd *exec.Cmd) { +} + +// killLeftovers kills the processes that still have the user data directory +// dir in their command line, after the main process of a browser exited. +// +// Chrome starts helper processes. They can outlive the main process, for +// example when a program kills it, and they create files in the directory +// again. The function repeats until it finds none for a few passes. +// +// It never kills the processes of a browser that started with KeepOpen. That +// browser must outlive the program, and a later run must not kill it. +func killLeftovers(dir string) { + if isKeepOpenDir(dir) { + return + } + const ( + quietPasses = 3 + pause = 10 * time.Millisecond + limit = 2 * time.Second + ) + deadline := time.Now().Add(limit) + for quiet := 0; quiet < quietPasses && time.Now().Before(deadline); time.Sleep(pause) { + if killProcessesUsing(dir) == 0 { + quiet++ + } else { + quiet = 0 + } + } +} + +// killProcessesUsing kills the processes that have the user data directory dir +// in their command line, and returns how many it found. macOS has no /proc, so +// it reads the list of processes from the command ps. +func killProcessesUsing(dir string) int { + out, err := exec.Command("ps", "-ax", "-o", "pid=,command=").Output() + if err != nil { + return 0 + } + // The command line of a process is one string. An argument ends at a space + // or at the end of the line. + want := "--user-data-dir=" + dir + self := os.Getpid() + var n int + for line := range strings.SplitSeq(string(out), "\n") { + line = strings.TrimSpace(line) + pidText, command, ok := strings.Cut(line, " ") + if !ok { + continue + } + pid, err := strconv.Atoi(pidText) + if err != nil || pid == self { + continue + } + if !strings.Contains(command+" ", want+" ") { + continue + } + if syscall.Kill(pid, syscall.SIGKILL) == nil { + n++ + } + } + return n +} diff --git a/vendor/github.com/chromedp/chromedp/allocate_detach_unix.go b/vendor/github.com/chromedp/chromedp/allocate_detach_unix.go new file mode 100644 index 000000000..c1e2e4f31 --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/allocate_detach_unix.go @@ -0,0 +1,17 @@ +//go:build !windows + +package chromedp + +import ( + "os/exec" + "syscall" +) + +// detachCmd makes the process of cmd start in a new session. The browser then +// keeps running when the Go program exits or when the terminal closes. +func detachCmd(cmd *exec.Cmd) { + if cmd.SysProcAttr == nil { + cmd.SysProcAttr = new(syscall.SysProcAttr) + } + cmd.SysProcAttr.Setsid = true +} diff --git a/vendor/github.com/chromedp/chromedp/allocate_detach_windows.go b/vendor/github.com/chromedp/chromedp/allocate_detach_windows.go new file mode 100644 index 000000000..66b8d2ef8 --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/allocate_detach_windows.go @@ -0,0 +1,21 @@ +//go:build windows + +package chromedp + +import ( + "os/exec" + "syscall" +) + +// detachedProcess is the Windows process creation flag DETACHED_PROCESS. The +// syscall package does not define it. +const detachedProcess = 0x00000008 + +// detachCmd makes the process of cmd start detached from the console and in a +// new process group. The browser then keeps running when the Go program exits. +func detachCmd(cmd *exec.Cmd) { + if cmd.SysProcAttr == nil { + cmd.SysProcAttr = new(syscall.SysProcAttr) + } + cmd.SysProcAttr.CreationFlags |= syscall.CREATE_NEW_PROCESS_GROUP | detachedProcess +} diff --git a/vendor/github.com/chromedp/chromedp/allocate_linux.go b/vendor/github.com/chromedp/chromedp/allocate_linux.go index 8382f51a8..759551ab2 100644 --- a/vendor/github.com/chromedp/chromedp/allocate_linux.go +++ b/vendor/github.com/chromedp/chromedp/allocate_linux.go @@ -3,11 +3,23 @@ package chromedp import ( + "bytes" "os" "os/exec" + "strconv" "syscall" + "time" ) +// checkDisplay returns ErrNoDisplay when the environment has no X11 and no +// Wayland display. +func checkDisplay() error { + if os.Getenv("DISPLAY") == "" && os.Getenv("WAYLAND_DISPLAY") == "" { + return ErrNoDisplay + } + return nil +} + func allocateCmdOptions(cmd *exec.Cmd) { if _, ok := os.LookupEnv("LAMBDA_TASK_ROOT"); ok { // do nothing on AWS Lambda @@ -19,3 +31,67 @@ func allocateCmdOptions(cmd *exec.Cmd) { // When the parent process dies (Go), kill the child as well. cmd.SysProcAttr.Pdeathsig = syscall.SIGKILL } + +// killLeftovers kills the processes that still use dir as the user data +// directory of a Chrome that started with it. +// +// Chrome child processes, such as the network service and the zygote, can +// outlive the main process when someone kills it. They can write files in the +// user data directory after it is removed. A child can also fork just as the +// main process dies, and show up after the first look. So killLeftovers looks +// again until it finds nothing for a few passes in a row. Chrome passes +// --user-data-dir to every child, and the directory of a temporary allocation +// is unique. So the command line finds the leftovers without a process group. +// A process group does not work: on the CI runner Chrome did not start in its +// own group. +// +// It never kills the processes of a browser that started with KeepOpen. That +// browser must outlive the program, and a later run must not kill it. +func killLeftovers(dir string) { + if isKeepOpenDir(dir) { + return + } + const ( + quietPasses = 3 + pause = 10 * time.Millisecond + limit = 2 * time.Second + ) + deadline := time.Now().Add(limit) + for quiet := 0; quiet < quietPasses && time.Now().Before(deadline); time.Sleep(pause) { + if killProcessesUsing(dir) == 0 { + quiet++ + } else { + quiet = 0 + } + } +} + +// killProcessesUsing kills the processes that have the user data directory dir +// in their command line, and returns how many it found. +func killProcessesUsing(dir string) int { + want := "--user-data-dir=" + dir + entries, err := os.ReadDir("/proc") + if err != nil { + return 0 + } + self := os.Getpid() + var n int + for _, entry := range entries { + pid, err := strconv.Atoi(entry.Name()) + if err != nil || pid == self { + continue + } + cmdline, err := os.ReadFile("/proc/" + entry.Name() + "/cmdline") + if err != nil { + continue + } + for arg := range bytes.SplitSeq(cmdline, []byte{0}) { + if string(arg) == want { + syscall.Kill(pid, syscall.SIGKILL) + n++ + break + } + } + } + return n +} diff --git a/vendor/github.com/chromedp/chromedp/allocate_other.go b/vendor/github.com/chromedp/chromedp/allocate_other.go index 963e2a3fc..9ecb6ebf8 100644 --- a/vendor/github.com/chromedp/chromedp/allocate_other.go +++ b/vendor/github.com/chromedp/chromedp/allocate_other.go @@ -1,8 +1,17 @@ -//go:build !linux +//go:build !linux && !darwin package chromedp import "os/exec" +// checkDisplay does nothing on this platform. +func checkDisplay() error { + return nil +} + func allocateCmdOptions(cmd *exec.Cmd) { } + +// killLeftovers does nothing on this platform. +func killLeftovers(dir string) { +} diff --git a/vendor/github.com/chromedp/chromedp/allocate_pipe.go b/vendor/github.com/chromedp/chromedp/allocate_pipe.go new file mode 100644 index 000000000..9fd9134e2 --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/allocate_pipe.go @@ -0,0 +1,236 @@ +package chromedp + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "os/exec" + "sync" + "time" + + "github.com/chromedp/cdproto/browser" +) + +const ( + // maxStartOutput is the most output of the browser that an ExecAllocator + // keeps to show in the error of a failed start. + maxStartOutput = 64 << 10 + + // outputGrace is how long an ExecAllocator waits for the rest of the + // output of the browser after the process exits. A leftover child + // process can hold the pipe open for much longer. + outputGrace = time.Second + + // exitGrace is how long an ExecAllocator waits for the browser process + // to exit after the pipe closed during the start. A busy machine can need + // several seconds to load the browser, and the process prints its reason + // before it exits. A browser that does not exit in this time is killed, and + // then the error has no reason. + exitGrace = 10 * time.Second +) + +// pipeFiles holds the files of the pipe transport of an ExecAllocator. +type pipeFiles struct { + // childR and childW are the ends that the browser uses. On Unix they are + // its file descriptors 3 and 4. + childR, childW *os.File + + // parentW writes the commands, and parentR reads the responses and the + // events. + parentW, parentR *os.File + + // outW and outR are the pipe of the standard output and the standard + // error of the browser. + outW, outR *os.File +} + +// newPipeFiles creates the pipes and gives the ends of the browser and the +// output of the browser to cmd. +// The caller must call closeChild after the process starts, or when it does +// not start, and closeParent when it does not use the pipes. +func newPipeFiles(cmd *exec.Cmd) (*pipeFiles, error) { + p := new(pipeFiles) + var err error + if p.childR, p.parentW, err = os.Pipe(); err != nil { + return nil, fmt.Errorf("creating the command pipe: %w", err) + } + if p.parentR, p.childW, err = os.Pipe(); err != nil { + p.closeChild() + p.closeParent() + return nil, fmt.Errorf("creating the response pipe: %w", err) + } + if p.outR, p.outW, err = os.Pipe(); err != nil { + p.closeChild() + p.closeParent() + return nil, fmt.Errorf("creating the output pipe: %w", err) + } + cmd.Stdout = p.outW + cmd.Stderr = p.outW + if err := setChildPipes(cmd, p); err != nil { + p.closeChild() + p.closeParent() + return nil, err + } + return p, nil +} + +// closeChild closes the ends that only the browser process needs. Calling it +// more than once is safe. +func (p *pipeFiles) closeChild() { + for _, f := range []*os.File{p.childR, p.childW, p.outW} { + if f != nil { + f.Close() + } + } +} + +// closeParent closes the ends of the parent process. Calling it more than once +// is safe. +func (p *pipeFiles) closeParent() { + for _, f := range []*os.File{p.parentR, p.parentW, p.outR} { + if f != nil { + f.Close() + } + } +} + +// limitedBuffer is a buffer that is safe to use from more than one goroutine. +// It keeps the first max bytes that are written to it and drops the rest. +type limitedBuffer struct { + mu sync.Mutex + buf []byte + max int +} + +// Write satisfies the io.Writer interface. It never fails. +func (b *limitedBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + if room := b.max - len(b.buf); room > 0 { + b.buf = append(b.buf, p[:min(room, len(p))]...) + } + return len(p), nil +} + +// String returns the text that was kept. +func (b *limitedBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return string(b.buf) +} + +// browserOutput copies the output of the browser to a buffer and to the +// combined output writer. +type browserOutput struct { + src io.ReadCloser + buf limitedBuffer + dst io.Writer + done chan struct{} +} + +// startBrowserOutput starts to copy src. The goroutine is part of wg, so that +// the allocator waits for it. +func startBrowserOutput(wg *sync.WaitGroup, src io.ReadCloser, dst io.Writer) *browserOutput { + o := &browserOutput{ + src: src, + buf: limitedBuffer{max: maxStartOutput}, + dst: dst, + done: make(chan struct{}), + } + wg.Go(o.copy) + return o +} + +func (o *browserOutput) copy() { + defer close(o.done) + defer o.src.Close() + p := make([]byte, 32<<10) + for { + n, err := o.src.Read(p) + if n > 0 { + o.buf.Write(p[:n]) + if o.dst != nil { + if _, werr := o.dst.Write(p[:n]); werr != nil { + // Keep reading, so that the browser does + // not block on a full pipe. + o.dst = nil + } + } + } + if err != nil { + return + } + } +} + +// finish waits for the rest of the output after the browser process exited. +// A leftover child process can keep the pipe open, so it gives up after +// outputGrace and closes the pipe. +func (o *browserOutput) finish() { + select { + case <-o.done: + case <-time.After(outputGrace): + o.src.Close() + <-o.done + } +} + +// String returns the output that was kept. +func (o *browserOutput) String() string { + return o.buf.String() +} + +// connectPipe makes a browser that talks to the process through pf, and waits +// for the first answer of the process. If the pipe closes first, it returns an +// error with the output of the process. +// +// exited is closed when the process exited and out is complete. +func connectPipe(ctx context.Context, pf *pipeFiles, cmd *exec.Cmd, out *browserOutput, exited <-chan struct{}, opts []BrowserOption) (*Browser, error) { + tr := NewPipeConn(pf.parentR, pf.parentW) + b, err := NewBrowserTransport(ctx, tr, opts...) + if err != nil { + tr.Close() + return nil, err + } + + first := make(chan error, 1) + go func() { + first <- b.execute(ctx, browser.CommandGetVersion, nil, nil) + }() + select { + case err := <-first: + if err != nil { + return nil, fmt.Errorf("starting the browser: %w", err) + } + return b, nil + case <-b.LostConnection: + } + + // The answer and the end of the pipe can come at almost the same time. + select { + case err := <-first: + if err == nil { + return b, nil + } + case <-time.After(100 * time.Millisecond): + } + + // Let the process exit, so that its output is complete. + select { + case <-exited: + case <-time.After(exitGrace): + if err := cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) { + return nil, fmt.Errorf("killing the browser that did not start: %w", err) + } + <-exited + } + // A canceled or expired context kills the process. The error of the + // context is the cause then, and the output only shows the processes + // that notice the death of their parent. + if err := ctx.Err(); err != nil { + return nil, fmt.Errorf("starting the browser: %w", err) + } + return nil, fmt.Errorf("chrome failed to start:\n%s", out.String()) +} diff --git a/vendor/github.com/chromedp/chromedp/browser.go b/vendor/github.com/chromedp/chromedp/browser.go index e85effb96..4d44ab1d7 100644 --- a/vendor/github.com/chromedp/chromedp/browser.go +++ b/vendor/github.com/chromedp/chromedp/browser.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "io" "log" "os" "sync" @@ -13,61 +14,88 @@ import ( "github.com/chromedp/cdproto" "github.com/chromedp/cdproto/browser" "github.com/chromedp/cdproto/cdp" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" "github.com/chromedp/cdproto/runtime" "github.com/chromedp/cdproto/target" - jsonv2 "github.com/go-json-experiment/json" - "github.com/go-json-experiment/json/jsontext" ) var ( // DefaultUnmarshalOptions are default unmarshal options. DefaultUnmarshalOptions = jsonv2.JoinOptions( jsonv2.DefaultOptionsV2(), - jsontext.AllowInvalidUTF8(true), + jsonv2.AllowInvalidUTF8(true), ) // DefaultMarshalOptions are default marshal options. DefaultMarshalOptions = jsonv2.JoinOptions( jsonv2.DefaultOptionsV2(), - jsontext.AllowInvalidUTF8(true), + jsonv2.AllowInvalidUTF8(true), ) ) -// Browser is the high-level Chrome DevTools Protocol browser manager, handling -// the browser process runner, WebSocket clients, associated targets, and -// network, page, and DOM events. +// Transport is the common interface to send and receive the protocol messages +// of a browser. [PipeConn] implements it, and so does the websocket connection +// of the package github.com/chromedp/chromedp/remote. Browser reads and writes +// its messages through it, and NewBrowserTransport accepts any Transport. +// +// A Transport can also have the method SetDebugf(func(string, ...any)). +// NewBrowserTransport then calls it with the protocol logger of the browser. +type Transport interface { + Read(context.Context, *cdproto.Message) error + Write(context.Context, *cdproto.Message) error + io.Closer +} + +// Browser manages a browser through the Chrome DevTools Protocol. It handles +// the browser process runner, the connection to the browser, the targets, and +// the network, page, and DOM events. The connection is a pipe or a websocket. type Browser struct { // next is the next message id. - // NOTE: needs to be 64-bit aligned for 32-bit targets too, so be careful when moving this field. - // This will be eventually done by the compiler once https://github.com/golang/go/issues/599 is fixed. + // NOTE: it must be 64-bit aligned on 32-bit targets too, so be careful when you move this field. + // The compiler will do this when https://github.com/golang/go/issues/599 is fixed. next int64 - // LostConnection is closed when the websocket connection to Chrome is - // dropped. This can be useful to make sure that Browser's context is - // cancelled (and the handler stopped) once the connection has failed. + // LostConnection is closed when the connection to Chrome drops. The + // connection is a pipe or a websocket. + // Use it to make sure that the context of the Browser is canceled (and the + // handler stopped) after the connection fails. LostConnection chan struct{} - // closingGracefully is closed by Close before gracefully shutting down - // the browser. This way, when the connection to the browser is lost and - // LostConnection is closed, we will know not to immediately kill the - // Chrome process. This is important to let the browser shut itself off, - // saving its state to disk. + // closingGracefully is closed by Close before it shuts the browser down + // gracefully. If the connection to the browser is lost and LostConnection + // is closed, we then know not to kill the Chrome process at once. This is + // important, because the browser must shut itself off and save its state + // to disk. closingGracefully chan struct{} - dialTimeout time.Duration + // lostReason is the error that ended the connection to the browser. It + // is valid after LostConnection closes. + lostReason error + + // diedUnexpectedly is true when the connection to the browser process + // dropped while nobody had asked the browser to stop. The caller did not + // cancel the context, and did not close the browser. See noteLost. + diedUnexpectedly atomic.Bool - // pages keeps track of the attached targets, indexed by each's session - // ID. The only reason this is a field is so that the tests can check the - // map once a browser is closed. + // exitErr points to the error of the wait for the browser process. It is + // nil for a browser that this program did not start. The error is valid + // after exited closes. + exitErr *error + + // pages tracks the attached targets by session ID. It is a field only so + // that the tests can read the map after a browser closes. pages map[target.SessionID]*Target listenersMu sync.Mutex listeners []cancelableListener + // events holds the subscriptions made with Subscribe. + events subscribers + conn Transport - // newTabQueue is the queue used to create new target handlers, once a new - // tab is created and attached to. The newly created Target is sent back - // via newTabResult. + // newTabQueue is the queue of requests to create new target handlers, + // after a new tab is created and attached. The new Target is sent back on + // newTabResult. newTabQueue chan *Target // cmdQueue is the outgoing command queue. @@ -78,26 +106,54 @@ type Browser struct { errf func(string, ...any) dbgf func(string, ...any) - // The optional fields below are helpful for some tests. + // The optional fields below help some tests. - // process can be initialized by the allocators which start a process - // when allocating a browser. + // process can be set by the allocators that start a process when they + // allocate a browser. process *os.Process - // userDataDir can be initialized by the allocators which set up user - // data dirs directly. + // userDataDir can be set by the allocators that set user data directories + // directly. userDataDir string + + // exited is closed when the browser process exits. It is nil when the + // allocator does not start the process. WaitClosed uses it. + exited <-chan struct{} + + // reaped is closed when the wait for the browser process returns, and + // exitErr is valid then. It can close before exited, because exited also + // waits for the output of the browser. Child processes of the browser can + // hold the output open for a while, especially on Windows. + reaped <-chan struct{} + + // keptOpen is true when the allocator started the browser with KeepOpen. + // wsURL is then the websocket address of the browser. + keptOpen bool + wsURL string +} + +// NewBrowserTransport creates a new browser that uses tr, a connection to a +// browser that is already open, such as a [*PipeConn]. The browser closes tr +// when it stops. Typically you do not call it directly, because the Allocator +// interface does it. +func NewBrowserTransport(ctx context.Context, tr Transport, opts ...BrowserOption) (*Browser, error) { + b := newBrowser(opts) + if s, ok := tr.(interface{ SetDebugf(func(string, ...any)) }); ok { + s.SetDebugf(b.dbgf) + } + b.conn = tr + + go b.run(ctx) + return b, nil } -// NewBrowser creates a new browser. Typically, this function wouldn't be called -// directly, as the Allocator interface takes care of it. -func NewBrowser(ctx context.Context, urlstr string, opts ...BrowserOption) (*Browser, error) { +// newBrowser returns a browser with the options applied, and without a +// connection. +func newBrowser(opts []BrowserOption) *Browser { b := &Browser{ LostConnection: make(chan struct{}), closingGracefully: make(chan struct{}), - dialTimeout: 10 * time.Second, - newTabQueue: make(chan *Target), // Fit some jobs without blocking, to reduce blocking in Execute. @@ -109,33 +165,19 @@ func NewBrowser(ctx context.Context, urlstr string, opts ...BrowserOption) (*Bro for _, o := range opts { o(b) } - // ensure errf is set + // make sure that errf is set if b.errf == nil { b.errf = func(s string, v ...any) { b.logf("ERROR: "+s, v...) } } - - dialCtx := ctx - if b.dialTimeout > 0 { - var cancel context.CancelFunc - dialCtx, cancel = context.WithTimeout(ctx, b.dialTimeout) - defer cancel() - } - - var err error - b.conn, err = DialContext(dialCtx, urlstr, WithConnDebugf(b.dbgf)) - if err != nil { - return nil, fmt.Errorf("could not dial %q: %w", urlstr, err) - } - - go b.run(ctx) - return b, nil + return b } // Process returns the process object of the browser. // -// It could be nil when the browser is allocated with RemoteAllocator. -// It could be useful for a monitoring system to collect process metrics of the browser process. -// (See [prometheus.NewProcessCollector] for an example). +// It is nil when the browser was allocated by an allocator that attaches to a +// browser that runs already, such as the allocator of the remote package. A monitoring +// system can use it to collect process metrics of the browser process (see +// [prometheus.NewProcessCollector] for an example). // // Example: // @@ -148,7 +190,7 @@ func (b *Browser) Process() *os.Process { return b.process } -func (b *Browser) newExecutorForTarget(ctx context.Context, targetID target.ID, sessionID target.SessionID) (*Target, error) { +func (b *Browser) newTarget(ctx context.Context, targetID target.ID, sessionID target.SessionID) (*Target, error) { if targetID == "" { return nil, errors.New("empty target ID") } @@ -160,17 +202,18 @@ func (b *Browser) newExecutorForTarget(ctx context.Context, targetID target.ID, TargetID: targetID, SessionID: sessionID, - messageQueue: make(chan *cdproto.Message, 1024), - frames: make(map[cdp.FrameID]*cdp.Frame), - execContexts: make(map[cdp.FrameID]runtime.ExecutionContextID), - cur: cdp.FrameID(targetID), + messageQueue: make(chan *cdproto.Message, 1024), + frames: make(map[cdp.FrameID]*Frame), + execContexts: make(map[cdp.FrameID]runtime.ExecutionContextID), + execUniqueIDs: make(map[cdp.FrameID]string), + cur: cdp.FrameID(targetID), logf: b.logf, errf: b.errf, } - // This send should be blocking, to ensure the tab is inserted into the - // map before any more target events are routed. + // This send must block, so that the tab is in the map before any more + // target events are routed. select { case <-ctx.Done(): return nil, ctx.Err() @@ -179,14 +222,27 @@ func (b *Browser) newExecutorForTarget(ctx context.Context, targetID target.ID, return t, nil } -func (b *Browser) Execute(ctx context.Context, method string, params, res any) error { - // Certain methods aren't available to the user directly. +// Call sends the command to the browser, waits for the response, and decodes +// the result into res. It satisfies [cdp.Session]. +// +// Call returns a browser error as a [*cdproto.Error]. It returns an error when +// the connection to the browser is lost, also when ctx never ends. The error +// wraps the reason of the loss and [context.Canceled]. +func (b *Browser) Call(ctx context.Context, method string, params, res any) error { + // Certain methods are not available to the user directly. if method == browser.CommandClose { return fmt.Errorf("to close the browser gracefully, use chromedp.Cancel") } return b.execute(ctx, method, params, res) } +// Subscribe starts to buffer the browser events with the method, and returns +// the channel that the raw event parameters arrive on. It satisfies +// [cdp.Session]. +func (b *Browser) Subscribe(method string) (<-chan jsonv2.Value, func()) { + return b.events.subscribe(method) +} + func (b *Browser) execute(ctx context.Context, method string, params, res any) error { id := atomic.AddInt64(&b.next, 1) lctx, cancel := context.WithCancel(ctx) @@ -220,6 +276,8 @@ func (b *Browser) execute(ctx context.Context, method string, params, res any) e select { case <-ctx.Done(): return ctx.Err() + case <-b.LostConnection: + return b.lostError(ctx) case b.cmdQueue <- cmd: } @@ -227,21 +285,58 @@ func (b *Browser) execute(ctx context.Context, method string, params, res any) e select { case <-ctx.Done(): return ctx.Err() - case msg := <-ch: - switch { - case msg == nil: - return ErrChannelClosed - case msg.Error != nil: - return msg.Error - case res != nil: - return jsonv2.Unmarshal(msg.Result, res, DefaultUnmarshalOptions) + case <-b.LostConnection: + // The reply can arrive just before the loss is known. + select { + case msg := <-ch: + if msg != nil { + return decodeReply(msg, res) + } + default: } + return b.lostError(ctx) + case msg := <-ch: + return decodeReply(msg, res) + } +} + +// decodeReply returns the error of a reply to a command, or decodes its result +// into res. A nil msg means that the channel of the reply closed. +func decodeReply(msg *cdproto.Message, res any) error { + switch { + case msg == nil: + return ErrChannelClosed + case msg.Error != nil: + return msg.Error + case res != nil: + return jsonv2.Unmarshal(msg.Result, res, DefaultUnmarshalOptions) } return nil } +// lostError returns the error of a call that cannot finish, because the +// connection to the browser is lost. It wraps the reason that the connection +// gave. It wraps [context.Canceled] too, because the allocator cancels the +// context of the browser when the connection drops, and an earlier version +// returned the error of that context. Call it only after LostConnection is +// closed. +// +// A canceled ctx wins, so that a call with a context that the program canceled +// returns the error of that context, as before. +func (b *Browser) lostError(ctx context.Context) error { + if err := ctx.Err(); err != nil { + return err + } + reason := b.lostReason + if reason == nil { + reason = io.EOF + } + return fmt.Errorf("lost the connection to the browser: %w: %w", reason, context.Canceled) +} + func (b *Browser) run(ctx context.Context) { defer b.conn.Close() + defer b.events.close() // incomingQueue is the queue of incoming target events, to be routed by // their session ID. @@ -249,9 +344,9 @@ func (b *Browser) run(ctx context.Context) { delTabQueue := make(chan target.SessionID, 1) - // This goroutine continuously reads events from the websocket - // connection. The separate goroutine is needed since a websocket read - // is blocking, so it cannot be used in a select statement. + // This goroutine reads events from the websocket connection all the time. + // It needs its own goroutine, because a websocket read blocks and cannot + // be part of a select statement. go func() { // Signal to run and exit the browser cleanup goroutine. defer close(b.LostConnection) @@ -259,9 +354,11 @@ func (b *Browser) run(ctx context.Context) { for { msg := new(cdproto.Message) if err := b.conn.Read(ctx, msg); err != nil { - if _, ok := errors.AsType[*jsontext.SyntacticError](err); ok { + var syntaxErr *jsonv2.SyntacticError + if errors.As(err, &syntaxErr) { b.errf("%s", err) } + b.noteReadError(ctx, err) return } @@ -269,11 +366,13 @@ func (b *Browser) run(ctx context.Context) { case msg.SessionID != "" && (msg.Method != "" || msg.ID != 0): select { case <-ctx.Done(): + b.lostReason = ctx.Err() return case incomingQueue <- msg: } case msg.Method != "": + b.events.publish(string(msg.Method), msg.Params) ev, err := cdproto.UnmarshalMessage(msg, DefaultUnmarshalOptions) if err != nil { b.errf("%s", err) @@ -325,7 +424,7 @@ func (b *Browser) run(ctx context.Context) { case m := <-incomingQueue: page, ok := b.pages[m.SessionID] if !ok { - // A page we recently closed still sending events. + // A page that we closed recently still sends events. continue } @@ -341,35 +440,104 @@ func (b *Browser) run(ctx context.Context) { } } +// noteReadError records why the connection to the browser is lost. The reader +// goroutine calls it before it closes LostConnection, so that a call that sees +// the loss can read the reason and the flag diedUnexpectedly. See noteLost. +func (b *Browser) noteReadError(ctx context.Context, err error) { + b.lostReason = err + select { + case <-b.closingGracefully: + default: + b.noteLost(ctx) + } +} + +// noteLost records that the connection to the browser process dropped. The +// allocator calls it when the connection drops without a graceful close. If +// the context ctx of the allocation is done, the program stopped the browser, +// so the loss is no surprise. Otherwise the process died, for example when the +// kernel killed it for lack of memory, or when it crashed. +// +// The allocator calls noteLost before it cancels the context. A call that +// fails because of the cancellation then sees the flag. +func (b *Browser) noteLost(ctx context.Context) { + select { + case <-ctx.Done(): + default: + b.diedUnexpectedly.Store(true) + } +} + +// browserExitError is the error of a call that failed because the browser +// process died. It holds the error of the call and the exit error of the +// process. +type browserExitError struct { + // exit is the error of the wait for the process, such as "signal: killed". + exit error + // err is the error that the call returned. + err error +} + +// Error satisfies the error interface. +func (e *browserExitError) Error() string { + return fmt.Sprintf("browser process exited: %v: %v", e.exit, e.err) +} + +// Unwrap returns the exit error and the error of the call, so that errors.Is +// and errors.As find both. For example, errors.As finds the *exec.ExitError, +// and errors.Is finds context.Canceled. +func (e *browserExitError) Unwrap() []error { + return []error{e.exit, e.err} +} + +// withExitError returns err with the exit error of the browser process, when +// the process died while nobody had asked the browser to stop. Otherwise it +// returns err. It waits a short time for the process to be reaped. +func (b *Browser) withExitError(err error) error { + if err == nil || b == nil || !b.diedUnexpectedly.Load() || b.reaped == nil || b.exitErr == nil { + return err + } + var exitErr *browserExitError + if errors.As(err, &exitErr) { + return err + } + select { + case <-b.reaped: + case <-time.After(time.Second): + return err + } + exit := *b.exitErr + if exit == nil { + exit = errors.New("exit status 0") + } + return &browserExitError{exit: exit, err: err} +} + // BrowserOption is a browser option. type BrowserOption = func(*Browser) -// WithBrowserLogf is a browser option to specify a func to receive general logging. +// WithBrowserLogf is a browser option that sets the func that receives general +// log messages. func WithBrowserLogf(f func(string, ...any)) BrowserOption { return func(b *Browser) { b.logf = f } } -// WithBrowserErrorf is a browser option to specify a func to receive error logging. +// WithBrowserErrorf is a browser option that sets the func that receives error +// messages. func WithBrowserErrorf(f func(string, ...any)) BrowserOption { return func(b *Browser) { b.errf = f } } -// WithBrowserDebugf is a browser option to specify a func to log actual -// websocket messages. +// WithBrowserDebugf is a browser option that sets the func that receives the +// protocol messages. func WithBrowserDebugf(f func(string, ...any)) BrowserOption { return func(b *Browser) { b.dbgf = f } } -// WithConsolef is a browser option to specify a func to receive chrome log events. +// WithConsolef is a browser option that sets the func that receives chrome log +// events. // -// Note: NOT YET IMPLEMENTED. +// Note: it is not implemented yet. func WithConsolef(f func(string, ...any)) BrowserOption { return func(b *Browser) {} } - -// WithDialTimeout is a browser option to specify the timeout when dialing a -// browser's websocket address. The default is ten seconds; use a zero duration -// to not use a timeout. -func WithDialTimeout(d time.Duration) BrowserOption { - return func(b *Browser) { b.dialTimeout = d } -} diff --git a/vendor/github.com/chromedp/chromedp/call.go b/vendor/github.com/chromedp/chromedp/call.go index 51e0ece76..2265148b3 100644 --- a/vendor/github.com/chromedp/chromedp/call.go +++ b/vendor/github.com/chromedp/chromedp/call.go @@ -3,45 +3,83 @@ package chromedp import ( "context" + "github.com/chromedp/cdproto/cdp" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" "github.com/chromedp/cdproto/runtime" - jsonv2 "github.com/go-json-experiment/json" ) -// CallAction are actions that calls a JavaScript function using -// runtime.CallFunctionOn. -type CallAction Action +// Call runs the protocol command with the params on the target of the chromedp +// context, and returns its result. As [Run] does, it starts the browser and +// opens the target when the context has none yet. +// +// Use it where only the context is at hand, for example in code that runs +// under [Legacy]. An [Action] receives its target, and calls [cdp.Call] with +// it: +// +// res, err := chromedp.Call(ctx, page.Navigate, page.NavigateParams{URL: urlstr}) +// +// It returns [ErrInvalidContext] when ctx is not a chromedp context. +func Call[P, R any](ctx context.Context, cmd cdp.Command[P, R], params P) (R, error) { + c, err := initContextTarget(ctx) + if err != nil { + var zero R + return zero, FromContext(ctx).withExitError(err) + } + v, err := cdp.Call(ctx, c.Target, cmd, params) + return v, c.withExitError(err) +} -// CallFunctionOn is an action to call a JavaScript function, unmarshaling -// the result of the function to res. +// CallBrowser runs the protocol command with the params on the browser of the +// chromedp context, and returns its result. Use it for the commands of the +// browser and target domains. As [Run] does, it starts the browser when the +// context has none yet. // -// The handling of res is the same as that of Evaluate. +// It returns [ErrInvalidContext] when ctx is not a chromedp context. +func CallBrowser[P, R any](ctx context.Context, cmd cdp.Command[P, R], params P) (R, error) { + c, err := initContextBrowser(ctx) + if err != nil { + var zero R + return zero, FromContext(ctx).withExitError(err) + } + v, err := cdp.Call(ctx, c.Browser, cmd, params) + return v, c.withExitError(err) +} + +// CallFunctionOn is an action that calls a JavaScript function and decodes the +// result of the function into the type T. +// +// T is handled as in [Evaluate]. A function that returns null gives +// [ErrJSNull] when T cannot be nil. // -// Do not call the following methods on runtime.CallFunctionOnParams: -// - WithReturnByValue: it will be set depending on the type of res; -// - WithArguments: pass the arguments with args instead. +// Do not set these fields of runtime.CallFunctionOnParams: +// - ReturnByValue: CallFunctionOn sets it from the type T. +// - Arguments: pass the arguments with args instead. // -// Note: any exception encountered will be returned as an error. -func CallFunctionOn(functionDeclaration string, res any, opt CallOption, args ...any) CallAction { - return ActionFunc(func(ctx context.Context) error { - _, err := callFunctionOn(ctx, functionDeclaration, res, opt, args...) - return err - }) +// If the function throws an exception, CallFunctionOn returns it as an error. +func CallFunctionOn[T any](functionDeclaration string, opt CallOption, args ...any) Action[T] { + return func(ctx context.Context, t *Target) (T, error) { + res, _, err := callFunctionOn[T](ctx, t, functionDeclaration, opt, args...) + return res, err + } } -func callFunctionOn(ctx context.Context, functionDeclaration string, res any, opt CallOption, args ...any) (*runtime.RemoteObject, error) { - // set up parameters - p := runtime.CallFunctionOn(functionDeclaration). - WithSilent(true) +// callFunctionOn calls the function, and returns the decoded result and the +// remote object of the result. +func callFunctionOn[T any](ctx context.Context, t *Target, functionDeclaration string, opt CallOption, args ...any) (T, *runtime.RemoteObject, error) { + var zero T - switch res.(type) { - case **runtime.RemoteObject: - default: - p = p.WithReturnByValue(true) + // set up parameters + p := &runtime.CallFunctionOnParams{ + FunctionDeclaration: functionDeclaration, + Silent: ptr(true), + } + if !wantsRemoteObject[T]() { + p.ReturnByValue = ptr(true) } // apply opt if opt != nil { - p = opt(p) + opt(p) } // arguments @@ -51,40 +89,39 @@ func callFunctionOn(ctx context.Context, functionDeclaration string, res any, op ea.append(arg) } if ea.err != nil { - return nil, ea.err + return zero, nil, ea.err } - p = p.WithArguments(ea.args) + p.Arguments = ea.args } // call - v, exp, err := p.Do(ctx) + r, err := cdp.Call(ctx, t, runtime.CallFunctionOn, *p) if err != nil { - return nil, err + return zero, nil, err } - if exp != nil { - return nil, exp + if r.ExceptionDetails != nil { + return zero, nil, &ExceptionError{r.ExceptionDetails} } - return v, parseRemoteObject(v, res) + res, err := parseRemoteObject[T](r.Result) + return res, r.Result, err } -// CallOption is a function to modify the runtime.CallFunctionOnParams to -// provide more information. -type CallOption = func(params *runtime.CallFunctionOnParams) *runtime.CallFunctionOnParams +// CallOption is a func that changes the runtime.CallFunctionOnParams of a +// call. +type CallOption = func(params *runtime.CallFunctionOnParams) -// errAppender is to help accumulating the arguments and simplifying error checks. -// -// see https://blog.golang.org/errors-are-values +// errAppender collects the arguments of a call and keeps the first error, so +// that the caller makes one error check. See +// https://blog.golang.org/errors-are-values. type errAppender struct { args []*runtime.CallArgument err error } -// append method calls the jsonv2.Marshal method to marshal the value and -// appends it to the slice. It records the first error for future reference. -// -// As soon as an error occurs, the append method becomes a no-op but the error -// value is saved. +// append calls the jsonv2.Marshal func on the value and appends the result to +// the slice. It records the first error. After an error, append does nothing +// and the error stays. func (ea *errAppender) append(v any) { if ea.err != nil { return diff --git a/vendor/github.com/chromedp/chromedp/chromedp.go b/vendor/github.com/chromedp/chromedp/chromedp.go index 32df89a1c..f513050ac 100644 --- a/vendor/github.com/chromedp/chromedp/chromedp.go +++ b/vendor/github.com/chromedp/chromedp/chromedp.go @@ -1,23 +1,27 @@ -// Package chromedp is a high level Chrome DevTools Protocol client that -// simplifies driving browsers for scraping, unit testing, or profiling web -// pages using the CDP. +// Package chromedp is a high level Chrome DevTools Protocol client. It drives +// browsers to scrape web pages, to test them, and to profile them. // -// chromedp requires no third-party dependencies, implementing the async Chrome -// DevTools Protocol entirely in Go. +// chromedp needs no external driver. It implements the asynchronous protocol +// in Go. // -// This package includes a number of simple examples. Additionally, -// [chromedp/examples] contains more complex examples. +// This package includes a number of simple examples. The module +// [chromedp/examples] has more complex examples. The module [chromedp/termcast] +// draws the screen of a page in a terminal that shows images. // // [chromedp/examples]: https://github.com/chromedp/examples +// [chromedp/termcast]: https://github.com/chromedp/termcast package chromedp import ( "context" + "errors" "fmt" + "slices" "strings" "sync" "time" + "github.com/chromedp/cdproto" "github.com/chromedp/cdproto/browser" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/css" @@ -30,95 +34,156 @@ import ( "github.com/chromedp/cdproto/target" ) -// Context is attached to any context.Context which is valid for use with Run. +// closeTargetTimeout is how long the cancellation of a tab waits for the +// browser to detach from the tab and to close it. +const closeTargetTimeout = 5 * time.Second + +// Context is the data that NewContext stores in a context.Context. Run needs +// it. type Context struct { - // Allocator is used to create new browsers. It is inherited from the - // parent context when using NewContext. + // Allocator creates new browsers. A child context inherits it from the + // parent context. Allocator Allocator - // Browser is the browser being used in the context. It is inherited - // from the parent context when using NewContext. + // Browser is the browser of the context. A child context inherits it from + // the parent context. Browser *Browser - // Target is the target to run actions (commands) against. It is not - // inherited from the parent context, and typically each context will - // have its own unique Target pointing to a separate browser tab (page). + // Target is the target that actions run against. A child context does not + // inherit it. Typically each context has its own Target, which points to a + // separate browser tab (page). Target *Target - // targetID is set up by WithTargetID. If nil, Run will pick the only - // unused page target, or create a new one. + // targetMu protects the write of Target in attachTarget and the read of + // Target in the cancellation watcher of NewContext. The watcher runs on + // its own goroutine, and the context can end while attachTarget runs. The + // goroutine that runs the actions needs no lock to read Target, because it + // is the only one that writes it. + targetMu sync.Mutex + + // targetID is set by WithTargetID. If it is nil, Run uses the only unused + // page target, or creates a new one. targetID target.ID - // createBrowserContextParams is set up by WithNewBrowserContext. It is used + // createBrowserContextParams is set by WithNewBrowserContext. Run uses it // to create a new BrowserContext. createBrowserContextParams *target.CreateBrowserContextParams - // browserContextOwner indicates whether this context is a BrowserContext - // owner. The owner is responsible for disposing the BrowserContext once - // the context is done. + // sharedWindow is set by WithNewWindow(false). A new tab then opens in + // the window of the browser and not in a new window. A child context + // inherits it. + sharedWindow bool + + // detachOnCancel is set by WithDetachOnCancel. The cancellation then + // detaches from the target and leaves the tab and its BrowserContext. + detachOnCancel bool + + // browserContextOwner is true when this context owns its BrowserContext. + // The owner disposes the BrowserContext when the context is done. browserContextOwner bool - // BrowserContextID is set up by WithExistingBrowserContext. + // BrowserContextID is set by WithExistingBrowserContext. // - // Otherwise, BrowserContextID holds a non-empty value in the following cases: + // Otherwise, BrowserContextID is not empty in these cases: // - // 1. if the context is created with the WithNewBrowserContext option, a new - // BrowserContext is created on its first run, and BrowserContextID holds - // the id of that new BrowserContext; + // 1. The context was made with WithNewBrowserContext. Its first run creates + // a new BrowserContext, and BrowserContextID holds the id of that + // BrowserContext. // - // 2. if the context is not created with the WithTargetID option, and its - // parent context has a non-empty BrowserContextID, this context's - // BrowserContextID is copied from the parent context. + // 2. The context was not made with WithTargetID, and the parent context + // has a BrowserContextID that is not empty. The context copies it from the + // parent context. BrowserContextID cdp.BrowserContextID - browserListeners []cancelableListener - targetListeners []cancelableListener - - // browserOpts holds the browser options passed to NewContext via - // WithBrowserOption, so that they can later be used when allocating a - // browser in Run. + // browserOpts holds the browser options that NewContext receives from + // WithBrowserOption. Run uses them when it allocates a browser. browserOpts []BrowserOption - // cancel simply cancels the context that was used to start Browser. - // This is useful to stop all activity and avoid deadlocks if we detect - // that the browser was closed or happened to crash. Note that this - // cancel function doesn't do any waiting. + // cancel cancels the context that started Browser. Use it to stop all + // activity and to prevent deadlocks when the browser closes or crashes. It + // does not wait for anything. cancel func() - // first records whether this context created a brand new Chrome - // process. This is important, because its cancellation should stop the - // entire browser and its handler, and not just a portion of its pages. + // first is true when this context started a new Chrome process. Its + // cancellation then stops the whole browser and its handler, and not only + // some of its pages. first bool - // closedTarget allows waiting for a target's page to be closed on - // cancellation. + // allocatorOptions is set by WithAllocatorOptions. NewContext adds them to + // the default allocator in the same way as visibleWindow. + allocatorOptions []ExecAllocatorOption + + // attachReleased is true after initContextBrowser closed allocated for an + // allocator that attaches to a running browser. + attachReleased bool + + // visibleWindow is set by WithVisibleWindow. NewContext uses it to build + // the default allocator. It has no effect on an allocator that the caller + // made. + visibleWindow bool + + // closedTarget lets a cancellation wait until the page of a target is + // closed. closedTarget sync.WaitGroup - // allocated is closed when an allocated browser completely stops. If no - // browser needs to be allocated, the channel is simply not initialized - // and remains nil. + // allocated is closed when an allocated browser stops completely. It is + // nil when no browser needs allocation. allocated chan struct{} - - // cancelErr is the first error encountered when cancelling this - // context, for example if a browser's temporary user data directory - // couldn't be deleted. + // cancelErr is the first error that the cancellation of this context met. + // For example, the context failed to delete the temporary user data + // directory of a browser. cancelErr error } -// NewContext creates a chromedp context from the parent context. The parent -// context's Allocator is inherited, defaulting to an ExecAllocator with -// DefaultExecAllocatorOptions. +// NewContext creates a chromedp context from the parent context. The context +// inherits the Allocator of the parent. By default, that is an ExecAllocator +// with DefaultExecAllocatorOptions. +// +// If the parent context holds an allocated Browser, the child context inherits +// it, and its first Run creates a new tab on that browser. Otherwise, its +// first Run allocates a new browser. +// +// Canceling the returned context closes a tab or a whole browser, as the +// rules above describe. To cancel a context and read the errors, see [Cancel]. +// +// NewContext does not allocate or start a browser. That happens the first time +// that you call Run on the context. // -// If the parent context contains an allocated Browser, the child context -// inherits it, and its first Run creates a new tab on that browser. Otherwise, -// its first Run will allocate a new browser. +// # The lifetime of the browser +// +// The first call of [Run] on a context starts the browser, and it binds the life +// of the browser to the context that you pass to that call. When that context +// ends, the browser stops. So a context from [context.WithTimeout] that you +// use for the first Run closes the browser when the timeout ends, and every +// later call on the parent context fails with context.Canceled. +// +// To limit one action, start the browser first with a context that has no +// timeout. Then run the action with a context that you derive from it: +// +// if err := chromedp.Do(ctx); err != nil { // starts the browser +// return err +// } +// tctx, cancel := context.WithTimeout(ctx, 5*time.Second) +// defer cancel() +// err := chromedp.Do(tctx, chromedp.Navigate(url)) // -// Cancelling the returned context will close a tab or an entire browser, -// depending on the logic described above. To cancel a context while checking -// for errors, see [Cancel]. +// When the timeout ends, Run returns an error that wraps +// context.DeadlineExceeded. The tab and the browser stay open, and ctx still +// works. Run has no option for the timeout of one action. // -// Note that NewContext doesn't allocate nor start a browser; that happens the -// first time Run is used on the context. +// # Use from several goroutines +// +// Contexts that share one browser run in separate tabs, and they are safe to +// use in parallel. To get them, call [Run] once on a parent context so that it +// has a browser, and then make a child context for each goroutine with +// NewContext. A child of a context that has no browser yet starts a browser of +// its own. +// +// Do not share one context between goroutines. The actions of one context run +// in one tab, so they can race. For example, two [Navigate] actions on the same +// tab can fail. The first call of [Run] on a context starts the +// browser, and it must not run at the same time as another call on that +// context. func NewContext(parent context.Context, opts ...ContextOption) (context.Context, context.CancelFunc) { ctx, cancel := context.WithCancel(parent) @@ -128,13 +193,13 @@ func NewContext(parent context.Context, opts ...ContextOption) (context.Context, c.Allocator = pc.Allocator c.Browser = pc.Browser parentBrowserContextID = pc.BrowserContextID - // don't inherit Target, so that NewContext can be used to + c.sharedWindow = pc.sharedWindow + // do not inherit Target, so that NewContext can be used to // create a new tab on the same browser. c.first = c.Browser == nil - // TODO: make this more generic somehow. - if _, ok := c.Allocator.(*RemoteAllocator); ok { + if isAttacher(c.Allocator) { c.first = false } } @@ -165,7 +230,8 @@ func NewContext(parent context.Context, opts ...ContextOption) (context.Context, } if c.Allocator == nil { - c.Allocator = setupExecAllocator(DefaultExecAllocatorOptions[:]...) + c.Allocator = setupExecAllocator(defaultExecAllocatorOptions( + c.visibleWindow || visibleWindowFromEnv(), c.allocatorOptions)...) } ctx = context.WithValue(ctx, contextKey{}, c) @@ -179,33 +245,56 @@ func NewContext(parent context.Context, opts ...ContextOption) (context.Context, return } - if c.Target == nil { - // This is a new tab, but we didn't create it and attach + c.targetMu.Lock() + tgt := c.Target + c.targetMu.Unlock() + if tgt == nil { + // This is a new tab, but we did not create it and attach // to it yet. Nothing to do. return } - // Not the original browser tab; simply detach and close it. - // We need a new context, as ctx is cancelled; use a 1s timeout. - ctx, cancel := context.WithTimeout(context.Background(), time.Second) + // This is not the original browser tab. Detach and close it. + // The context ctx is canceled, so make a new context with a timeout. + // A busy machine, such as a CI runner, can need more than a second + // to answer. + ctx, cancel := context.WithTimeout(context.Background(), closeTargetTimeout) defer cancel() - browserExecutor := cdp.WithExecutor(ctx, c.Browser) - if id := c.Target.SessionID; id != "" { - action := target.DetachFromTarget().WithSessionID(id) - if err := action.Do(browserExecutor); c.cancelErr == nil && err != nil { - c.cancelErr = err + if id := tgt.SessionID; id != "" { + _, err := cdp.Call(ctx, c.Browser, target.DetachFromTarget, target.DetachFromTargetParams{SessionID: id}) + if c.cancelErr == nil && err != nil { + c.cancelErr = fmt.Errorf("detaching from the target %s: %w", tgt.TargetID, err) } } - if id := c.Target.TargetID; id != "" { - action := target.CloseTarget(id) - if err := action.Do(browserExecutor); c.cancelErr == nil && err != nil { - c.cancelErr = err + if c.detachOnCancel { + // Leave the tab open. A BrowserContext that this context owns + // stays too, because disposing of it closes its tabs. + return + } + if id := tgt.TargetID; id != "" { + if _, err := cdp.Call(ctx, c.Browser, target.CloseTarget, target.CloseTargetParams{TargetID: id}); err != nil { + if c.cancelErr == nil { + c.cancelErr = fmt.Errorf("closing the target %s: %w", id, err) + } + } else { + // Current Chrome answers CloseTarget before the + // target is gone. Wait until it is not listed. + // A destroyed event is not enough, because a + // browser connection can miss it. + // A tab with a request that never ends can stay + // for a long time, so give up after a short time. + wctx, wcancel := context.WithTimeout(ctx, 500*time.Millisecond) + err := waitTargetGone(wctx, c.Browser, id) + wcancel() + if err != nil && !errors.Is(err, context.DeadlineExceeded) && c.cancelErr == nil { + c.cancelErr = err + } } } if c.browserContextOwner { - action := target.DisposeBrowserContext(c.BrowserContextID) - if err := action.Do(browserExecutor); c.cancelErr == nil && err != nil { - c.cancelErr = err + _, err := cdp.Call(ctx, c.Browser, target.DisposeBrowserContext, target.DisposeBrowserContextParams{BrowserContextID: c.BrowserContextID}) + if c.cancelErr == nil && err != nil { + c.cancelErr = fmt.Errorf("disposing of the browser context %s: %w", c.BrowserContextID, err) } } }() @@ -220,36 +309,45 @@ func NewContext(parent context.Context, opts ...ContextOption) (context.Context, return ctx, cancelWait } +// withExitError adds the exit error of the browser process to err. See +// [Browser.withExitError]. It accepts a nil Context. +func (c *Context) withExitError(err error) error { + if c == nil { + return err + } + return c.Browser.withExitError(err) +} + type contextKey struct{} -// FromContext extracts the Context data stored inside a context.Context. +// FromContext returns the Context that a context.Context holds, or nil. func FromContext(ctx context.Context) *Context { c, _ := ctx.Value(contextKey{}).(*Context) return c } -// Cancel cancels a chromedp context, waits for its resources to be cleaned up, -// and returns any error encountered during that process. +// Cancel cancels a chromedp context, waits until the context frees its +// resources, and returns any error that occurred. // -// If the context allocated a browser, the browser will be closed gracefully by -// Cancel. A timeout can be attached to this context to determine how long to -// wait for the browser to close itself: +// If the context allocated a browser, Cancel closes the browser gracefully. To +// limit how long Cancel waits for the browser to close, give the context a +// timeout: // // tctx, tcancel := context.WithTimeout(ctx, 10 * time.Second) // defer tcancel() // chromedp.Cancel(tctx) // -// Usually a "defer cancel()" will be enough for most use cases. However, Cancel -// is the better option if one wants to gracefully close a browser, or catch -// underlying errors happening during cancellation. +// A "defer cancel()" is enough in most cases. Use Cancel to close a browser +// gracefully, or to get the errors that occur during the cancellation. func Cancel(ctx context.Context) error { c := FromContext(ctx) - // c.cancel is nil when Cancel is wrongly called with a context returned - // by chromedp.NewExecAllocator or chromedp.NewRemoteAllocator. + // c.cancel is nil when the caller passes to Cancel a context from + // NewExecAllocator or by an allocator of another package. if c == nil || c.cancel == nil { return ErrInvalidContext } - graceful := c.first && c.Browser != nil + // A browser that was kept open must stay open, so Cancel does not close it. + graceful := c.first && c.Browser != nil && !c.Browser.keptOpen if graceful { close(c.Browser.closingGracefully) if err := c.Browser.execute(ctx, browser.CommandClose, nil, nil); err != nil { @@ -269,18 +367,17 @@ func Cancel(ctx context.Context) error { case <-ctx.Done(): } } - // If this was a graceful close, cancel the entire context, in case any - // goroutines or resources are left, or if we hit the timeout above and - // the browser hasn't finished yet. Note that, in the non-graceful path, - // we already called c.cancel above. + // After a graceful close, cancel the whole context. This frees any + // goroutines or resources that are left, and it stops a browser that did + // not finish before the timeout above. The non-graceful path already + // called c.cancel above. if graceful { c.cancel() } - // If we allocated and we hit ctx.Done earlier, we can't rely on - // cancelErr being ready until the allocated channel is closed, as that - // is racy. If we didn't hit ctx.Done earlier, then c.allocated was - // already cancelled then, so this will be a no-op. + // If we allocated and hit ctx.Done earlier, cancelErr is not ready until + // the allocated channel is closed, because the two race. If we did not hit + // ctx.Done earlier, c.allocated was already closed, so this does nothing. if !ready && c.allocated != nil { <-c.allocated } @@ -289,50 +386,63 @@ func Cancel(ctx context.Context) error { func initContextBrowser(ctx context.Context) (*Context, error) { c := FromContext(ctx) - // If c is nil, it's not a chromedp context. - // If c.Allocator is nil, NewContext wasn't used properly. - // If c.cancel is nil, Run is being called directly with an allocator - // context. + // If c is nil, it is not a chromedp context. + // If c.Allocator is nil, NewContext was not used properly. + // If c.cancel is nil, the caller passed an allocator context to Run + // directly. if c == nil || c.Allocator == nil || c.cancel == nil { return nil, ErrInvalidContext } if c.Browser == nil { + attach := isAttacher(c.Allocator) + if attach && !c.attachReleased { + // The allocator starts no process, so nothing waits for the + // context to stop a browser. See Cancel. + c.attachReleased = true + close(c.allocated) + } b, err := c.Allocator.Allocate(ctx, c.browserOpts...) if err != nil { return nil, err } c.Browser = b - c.Browser.listeners = append(c.Browser.listeners, c.browserListeners...) + if attach { + go func() { + // If the browser loses the connection, stop the context at + // once. Do not stop it in the middle of a graceful close. + <-b.LostConnection + select { + case <-b.closingGracefully: + default: + b.noteLost(ctx) + c.cancel() + } + }() + } } return c, nil } -// Run runs an action against context. The provided context must be a valid -// chromedp context, typically created via NewContext. -// -// Note that the first time Run is called on a context, a browser will be -// allocated via Allocator. Thus, it's generally a bad idea to use a context -// timeout on the first Run call, as it will stop the entire browser. -// -// Also note that the actions are run with the Target executor. In the case that -// a Browser executor is required, the action can be written like this: -// -// err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error { -// c := chromedp.FromContext(ctx) -// id, err := target.CreateBrowserContext().Do(cdp.WithExecutor(ctx, c.Browser)) -// return err -// })) -func Run(ctx context.Context, actions ...Action) error { +// isAttacher reports whether a attaches to a browser that runs already. See +// [Attacher]. +func isAttacher(a Allocator) bool { + at, ok := a.(Attacher) + return ok && at.Attaches() +} + +// initContextTarget is like initContextBrowser, and also attaches the target +// of the context when it has none yet. +func initContextTarget(ctx context.Context) (*Context, error) { c, err := initContextBrowser(ctx) if err != nil { - return err + return nil, err } if c.Target == nil { if err := c.newTarget(ctx); err != nil { - return err + return nil, err } } - return Tasks(actions).Do(cdp.WithExecutor(ctx, c.Target)) + return c, nil } func (c *Context) newTarget(ctx context.Context) error { @@ -340,21 +450,19 @@ func (c *Context) newTarget(ctx context.Context) error { if err := c.attachTarget(ctx, c.targetID); err != nil { return err } - // This new page might have already loaded its top-level frame - // already, in which case we wouldn't see the frameNavigated and - // documentUpdated events. Load them here. - // Since at the time of writing this (2020-1-27), Page.* CDP methods are - // not implemented in worker targets, we need to skip this step when we - // attach to workers. + // A new page can load its top-level frame before we listen. Then we do + // not see the frameNavigated and documentUpdated events, so load them + // here. As of 2020-1-27, worker targets do not implement the Page.* + // methods, so skip this step for workers. if !c.Target.isWorker { - tree, err := page.GetFrameTree().Do(cdp.WithExecutor(ctx, c.Target)) + tree, err := cdp.Call(ctx, c.Target, page.GetFrameTree, cdp.Empty{}) if err != nil { return err } c.Target.frameMu.Lock() - c.Target.frames[tree.Frame.ID] = tree.Frame - c.Target.cur = tree.Frame.ID + c.Target.frames[tree.FrameTree.Frame.ID] = &Frame{Frame: tree.FrameTree.Frame} + c.Target.cur = tree.FrameTree.Frame.ID c.Target.frameMu.Unlock() c.Target.documentUpdated(ctx) @@ -362,30 +470,54 @@ func (c *Context) newTarget(ctx context.Context) error { return nil } if !c.first { - var err error - browserExecutor := cdp.WithExecutor(ctx, c.Browser) + newWindow := !c.sharedWindow if c.createBrowserContextParams != nil { - c.BrowserContextID, err = c.createBrowserContextParams.Do(browserExecutor) + params := *c.createBrowserContextParams + if c.detachOnCancel { + // Chrome disposes of a browser context that disposeOnDetach + // marks when the context detaches, and that closes the tab. + params.DisposeOnDetach = nil + } + res, err := cdp.Call(ctx, c.Browser, target.CreateBrowserContext, params) if err != nil { return err } + c.BrowserContextID = res.BrowserContextID c.browserContextOwner = true c.createBrowserContextParams = nil + // A new browser context has no window yet, so its first tab + // needs a window of its own. + newWindow = true + } + create := func(newWindow bool) (target.CreateTargetResult, error) { + return cdp.Call(ctx, c.Browser, target.CreateTarget, target.CreateTargetParams{ + URL: "about:blank", + BrowserContextID: c.BrowserContextID, + // A tab in a shared window is hidden when another tab is + // active. A hidden page gets no animation frames, so Poll + // never returns. By default, each target gets its own + // window. See WithNewWindow. + NewWindow: &newWindow, + }) + } + res, err := create(newWindow) + var cerr *cdproto.Error + if err != nil && !newWindow && errors.As(err, &cerr) && strings.Contains(cerr.Message, "no browser is open") { + // The browser context has no window to put a tab in. This is + // the case of a context that WithExistingBrowserContext names. + res, err = create(true) } - c.targetID, err = target. - CreateTarget("about:blank"). - WithBrowserContextID(c.BrowserContextID). - Do(browserExecutor) if err != nil { return err } + c.targetID = res.TargetID return c.attachTarget(ctx, c.targetID) } // This is like WaitNewTarget, but for the entire browser. ch := make(chan target.ID, 1) lctx, cancel := context.WithCancel(ctx) - ListenBrowser(lctx, func(ev any) { + c.Browser.listen(lctx, func(ev any) { var info *target.Info switch ev := ev.(type) { case *target.EventTargetCreated: @@ -395,14 +527,13 @@ func (c *Context) newTarget(ctx context.Context) error { default: return } - // In the following cases, the browser will start with a non-blank tab: - // 1. with the "--app" option (should disable headless mode); - // 2. URL other than "about:blank" is placed in the command line arguments. - // So we should not require that the URL to be "about:blank". + // The browser starts with a tab that is not blank in these cases: + // 1. The "--app" option is used (this disables headless mode). + // 2. The command line arguments hold a URL other than "about:blank". + // So do not require that the URL is "about:blank". // See issue https://github.com/chromedp/chromedp/issues/1076 - // In any cases that the browser starts with multiple tabs open, - // it should be okay to attach to any one of them (no matter whether it - // is blank). + // When the browser starts with several tabs, attach to any one of them, + // blank or not. if info.Type == "page" { select { case <-lctx.Done(): @@ -413,8 +544,7 @@ func (c *Context) newTarget(ctx context.Context) error { }) // wait for the first tab to appear - action := target.SetDiscoverTargets(true) - if err := action.Do(cdp.WithExecutor(ctx, c.Browser)); err != nil { + if _, err := cdp.Call(ctx, c.Browser, target.SetDiscoverTargets, target.SetDiscoverTargetsParams{Discover: true}); err != nil { return err } select { @@ -426,52 +556,61 @@ func (c *Context) newTarget(ctx context.Context) error { } func (c *Context) attachTarget(ctx context.Context, targetID target.ID) error { - sessionID, err := target.AttachToTarget(targetID).WithFlatten(true).Do(cdp.WithExecutor(ctx, c.Browser)) + res, err := cdp.Call(ctx, c.Browser, target.AttachToTarget, target.AttachToTargetParams{ + TargetID: targetID, + Flatten: ptr(true), + }) if err != nil { return err } - c.Target, err = c.Browser.newExecutorForTarget(ctx, targetID, sessionID) + t, err := c.Browser.newTarget(ctx, targetID, res.SessionID) if err != nil { return err } + c.targetMu.Lock() + c.Target = t + c.targetMu.Unlock() - c.Target.listeners = append(c.Target.listeners, c.targetListeners...) go c.Target.run(ctx) - // Check if this is a worker target. We cannot use Target.getTargetInfo or - // Target.getTargets in a worker, so we check if "self" refers to a - // WorkerGlobalScope or ServiceWorkerGlobalScope. - if err := runtime.Enable().Do(cdp.WithExecutor(ctx, c.Target)); err != nil { + // Find out whether this is a worker target. A worker cannot use + // Target.getTargetInfo or Target.getTargets, so find out whether "self" + // refers to a WorkerGlobalScope or a ServiceWorkerGlobalScope. + if _, err := cdp.Call(ctx, c.Target, runtime.Enable, cdp.Empty{}); err != nil { return err } - res, _, err := runtime.Evaluate("self").Do(cdp.WithExecutor(ctx, c.Target)) + self, err := cdp.Call(ctx, c.Target, runtime.Evaluate, runtime.EvaluateParams{Expression: "self"}) if err != nil { return err } - c.Target.isWorker = strings.Contains(res.ClassName, "WorkerGlobalScope") + c.Target.isWorker = strings.Contains(self.Result.ClassName, "WorkerGlobalScope") // Enable available domains and discover targets. - actions := []Action{ - log.Enable(), - network.Enable(), + type step struct { + method string + params any + } + steps := []step{ + {log.Enable.Method, cdp.Empty{}}, + {network.Enable.Method, network.EnableParams{}}, } - // These actions are not available on a worker target. + // These steps are not available on a worker target. if !c.Target.isWorker { - actions = append(actions, []Action{ - inspector.Enable(), - page.Enable(), - dom.Enable(), - css.Enable(), - target.SetDiscoverTargets(true), - target.SetAutoAttach(true, false).WithFlatten(true), - page.SetLifecycleEventsEnabled(true), - }...) + steps = append(steps, + step{inspector.Enable.Method, cdp.Empty{}}, + step{page.Enable.Method, page.EnableParams{}}, + step{dom.Enable.Method, dom.EnableParams{}}, + step{css.Enable.Method, cdp.Empty{}}, + step{target.SetDiscoverTargets.Method, target.SetDiscoverTargetsParams{Discover: true}}, + step{target.SetAutoAttach.Method, target.SetAutoAttachParams{AutoAttach: true, Flatten: ptr(true)}}, + step{page.SetLifecycleEventsEnabled.Method, page.SetLifecycleEventsEnabledParams{Enabled: true}}, + ) } - for _, action := range actions { - if err := action.Do(cdp.WithExecutor(ctx, c.Target)); err != nil { - return fmt.Errorf("unable to execute %T: %w", action, err) + for _, s := range steps { + if err := c.Target.Call(ctx, s.method, s.params, nil); err != nil { + return fmt.Errorf("unable to execute %s: %w", s.method, err) } } return nil @@ -480,35 +619,134 @@ func (c *Context) attachTarget(ctx context.Context, targetID target.ID) error { // ContextOption is a context option. type ContextOption = func(*Context) -// WithTargetID sets up a context to be attached to an existing target, instead -// of creating a new one. +// WithVisibleWindow makes NewContext build the default allocator with +// [VisibleWindow] and without Headless, so that the browser opens a visible +// window. The window stays open until the context ends. See also [KeepOpen] +// and [WaitClosed]. +// +// The environment variable CHROMEDP_VISIBLEWINDOW has the same effect with no +// change in the code. Any value other than the empty string, "false" and "0" +// turns it on. +// +// The option only applies when the parent context has no allocator, because +// then NewContext builds the allocator. It has no effect on an allocator that +// the caller made, and it has no effect on a context that inherits a browser. For an allocator that you make, +// add [VisibleWindow] to the options of NewExecAllocator instead. +// +// On Linux, the first Run returns [ErrNoDisplay] when the environment has no +// display. +func WithVisibleWindow() ContextOption { + return func(c *Context) { c.visibleWindow = true } +} + +// WithAllocatorOptions makes NewContext add opts to the options of the default +// allocator, after [DefaultExecAllocatorOptions] and after [VisibleWindow]. The +// package github.com/chromedp/chromedp/remote uses it for its own WithKeepOpen. +// +// The option only applies when the parent context has no allocator. It has no +// effect on an allocator that the caller made, and it has no effect on a +// context that inherits a browser. For an allocator that you make, add the +// options to NewExecAllocator instead. +func WithAllocatorOptions(opts ...ExecAllocatorOption) ContextOption { + return func(c *Context) { + c.allocatorOptions = append(c.allocatorOptions, opts...) + } +} + +// WithNewWindow chooses where a new tab opens. By default, the first Run of a +// context that creates a tab opens it in a new window, so that each tab is +// visible and gets animation frames. WithNewWindow(false) opens the tab in the +// window of the browser, as a real tab. A child context inherits the choice. +// +// Chrome hides every tab of a window except the active one, and a hidden page +// gets no animation frames. So an action that waits for a frame, such as +// [Poll] and the actions that use it, can wait for ever on a tab that is not +// active. Make a tab active with the command [target.ActivateTarget], or with +// [page.BringToFront] in the tab, before you run such an action on it. +// +// WithNewWindow has no effect on the first context of a browser, which uses the +// tab that the browser opens, or on a context that attaches to an existing +// target with WithTargetID. +func WithNewWindow(newWindow bool) ContextOption { + return func(c *Context) { + c.sharedWindow = !newWindow + } +} + +// WithDetachOnCancel makes the cancellation of the context detach from its tab +// and leave the tab open. By default, the cancellation closes the tab that the +// context created or attached to with [WithTargetID], and it disposes of a +// BrowserContext that [WithNewBrowserContext] made. +// +// Use it with a remote browser that keeps its tabs when a client leaves, so +// that a later client can attach to the tab again with [WithTargetID]. Read the +// ID of the tab from the Target field of [FromContext] after the first Run. +// With this option, the context also keeps a BrowserContext that it owns, +// because disposing of it closes the tab. It creates that BrowserContext +// without the setting disposeOnDetach. The program must dispose of it with the +// command [target.DisposeBrowserContext] when it no longer needs it. +// +// The option has no effect on the first context of a browser that the exec +// allocator starts, because the cancellation stops that browser. It is not +// inherited by a child context. +func WithDetachOnCancel() ContextOption { + return func(c *Context) { c.detachOnCancel = true } +} + +// WithTargetID makes a context attach to an existing target, and not create a +// new one. +// +// It also works for an iframe from another site (a cross-site iframe). Chrome +// runs such an iframe in its own process, and lists it as a target of the type +// "iframe" in [Targets]. [FromNode] and the DOM tree of the page do not reach +// it, and the network events of the iframe do not arrive in the context of the +// page, because chromedp does not attach to the iframe by itself. A context +// that WithTargetID attaches to the iframe runs actions in the iframe and gets +// its events. The parent context must have run already, so that it has a +// browser. For example: +// +// infos, _ := chromedp.Targets(ctx) +// for _, info := range infos { +// if info.Type == "iframe" && strings.HasPrefix(info.URL, "https://other.example/") { +// frameCtx, cancel := chromedp.NewContext(ctx, chromedp.WithTargetID(info.TargetID)) +// defer cancel() +// text, err := chromedp.Run(frameCtx, chromedp.Text(chromedp.CSS("#inner"))) +// } +// } +// +// The other way is to turn off site isolation in the browser. Give the exec +// allocator Flag("disable-features", "SitePerProcess,IsolateOrigins") and +// Flag("disable-site-isolation-trials", true). The iframe then stays in the page +// process, and [FromNode] and the events of the page reach it. This turns off a +// security feature of Chrome. See +// docs/decisions/2026-10-04-keep-site-isolation-on.md. func WithTargetID(id target.ID) ContextOption { return func(c *Context) { c.targetID = id } } -// CreateBrowserContextOption is a BrowserContext creation options. -type CreateBrowserContextOption = func(*target.CreateBrowserContextParams) *target.CreateBrowserContextParams +// CreateBrowserContextOption is an option for the creation of a BrowserContext. +type CreateBrowserContextOption = func(*target.CreateBrowserContextParams) -// WithNewBrowserContext sets up a context to create a new BrowserContext, and -// create a new target in this BrowserContext. A child context will create its -// target in this BrowserContext too, unless it's set up with other options. -// The new BrowserContext will be disposed when the context is done. +// WithNewBrowserContext makes a context create a new BrowserContext and a new +// target in it. A child context creates its target in this BrowserContext too, +// unless another option applies. The context disposes the new BrowserContext +// when the context is done. func WithNewBrowserContext(options ...CreateBrowserContextOption) ContextOption { return func(c *Context) { if c.first { panic("WithNewBrowserContext can not be used before Browser is initialized") } - params := target.CreateBrowserContext().WithDisposeOnDetach(true) + params := &target.CreateBrowserContextParams{DisposeOnDetach: ptr(true)} for _, o := range options { - params = o(params) + o(params) } c.createBrowserContextParams = params } } -// WithExistingBrowserContext sets up a context to create a new target in the -// specified browser context. +// WithExistingBrowserContext makes a context create a new target in the given +// BrowserContext. func WithExistingBrowserContext(id cdp.BrowserContextID) ContextOption { return func(c *Context) { if c.first { @@ -533,9 +771,9 @@ func WithDebugf(f func(string, ...any)) ContextOption { return WithBrowserOption(WithBrowserDebugf(f)) } -// WithBrowserOption allows passing a number of browser options to the allocator -// when allocating a new browser. As such, this context option can only be used -// when NewContext is allocating a new browser. +// WithBrowserOption passes browser options to the allocator when it allocates +// a new browser. As a result, you can use this option only when the context +// allocates a new browser. func WithBrowserOption(opts ...BrowserOption) ContextOption { return func(c *Context) { if c.Browser != nil { @@ -545,32 +783,31 @@ func WithBrowserOption(opts ...BrowserOption) ContextOption { } } -// RunResponse is an alternative to Run which can be used with a list of actions -// that trigger a page navigation, such as clicking on a link or button. +// RunResponse is an alternative to [Do] for a list of actions that trigger a +// page navigation, such as a click on a link or a button. // -// RunResponse will run the actions and block until a page loads, returning the -// HTTP response information for its HTML document. This can be useful to wait -// for the page to be ready, or to catch 404 status codes, for example. +// RunResponse runs the actions and blocks until a page loads. Then it returns +// the HTTP response of the HTML document. Use it to wait for the page, or to +// catch 404 status codes. // -// Note that if the actions trigger multiple navigations, only the first is -// used. And if the actions trigger no navigations at all, RunResponse will -// block until the context is cancelled. -func RunResponse(ctx context.Context, actions ...Action) (*network.Response, error) { - var resp *network.Response - if err := Run(ctx, responseAction(&resp, actions...)); err != nil { - return nil, err - } - return resp, nil +// If the actions trigger several navigations, RunResponse uses only the first. +// If the actions trigger no navigation, RunResponse blocks until the context +// is canceled. +func RunResponse(ctx context.Context, steps ...Action[Void]) (*network.Response, error) { + return Run(ctx, responseAction(steps...)) } -func responseAction(resp **network.Response, actions ...Action) Action { - return ActionFunc(func(ctx context.Context) error { - // loaderID lets us filter the requests from the currently - // loading navigation. +// responseAction makes an action that runs the steps, waits until the page +// loads, and returns the response of the HTML document. +func responseAction(steps ...Action[Void]) Action[*network.Response] { + return func(ctx context.Context, t *Target) (*network.Response, error) { + var resp *network.Response + // loaderID lets us filter the requests of the navigation that + // loads now. var loaderID cdp.LoaderID - // reqID is the request we're currently looking at. This can - // go through multiple values, e.g. if the page redirects. + // reqID is the request that we look at now. It can go through + // several values, for example when the page redirects. var reqID network.RequestID // frameID corresponds to the target's root frame. @@ -580,10 +817,12 @@ func responseAction(resp **network.Response, actions ...Action) Action { hasInit := false finished := false - // First, set up the function to handle events. - // We are listening for lifecycle events, so we will use those to - // make sure we grab the response for a request initiated by the - // loaderID that we want. + // First, set up the func that handles events. + // It listens for lifecycle events. It uses them to make sure that we + // get the response of a request from the loaderID that we want. + // + // The events of several methods must arrive in order, so this uses the + // internal listener and not one subscription for each method. lctx, lcancel := context.WithCancel(ctx) defer lcancel() @@ -595,8 +834,8 @@ func responseAction(resp **network.Response, actions ...Action) Action { } case *network.EventLoadingFailed: if ev.RequestID == reqID { - loadErr = fmt.Errorf("page load error %s", ev.ErrorText) - // If Canceled is true, we won't receive a + loadErr = &LoadError{ErrorText: ev.ErrorText} + // If Canceled is true, we will not receive a // loadEventFired at all. if ev.Canceled { finished = true @@ -604,8 +843,8 @@ func responseAction(resp **network.Response, actions ...Action) Action { } } case *network.EventResponseReceived: - if ev.RequestID == reqID && resp != nil { - *resp = ev.Response + if ev.RequestID == reqID { + resp = ev.Response } case *page.EventLifecycleEvent: if ev.FrameID == frameID && ev.Name == "init" { @@ -625,17 +864,16 @@ func responseAction(resp **network.Response, actions ...Action) Action { } } } - // earlyEvents is a buffered list of events which happened - // before we knew what loaderID to look for. + // earlyEvents buffers the events that arrive before we know which loaderID + // to look for. var earlyEvents []any // Obtain frameID from the target. - c := FromContext(ctx) - c.Target.frameMu.RLock() - frameID = c.Target.cur - c.Target.frameMu.RUnlock() + t.frameMu.RLock() + frameID = t.cur + t.frameMu.RUnlock() - ListenTarget(lctx, func(ev any) { + t.listen(lctx, func(ev any) { if loaderID != "" { handleEvent(ev) return @@ -648,11 +886,11 @@ func responseAction(resp **network.Response, actions ...Action) Action { frameID = ev.Frame.ID } case *network.EventRequestWillBeSent: - // Under some circumstances like ERR_TOO_MANY_REDIRECTS, we never - // see the "init" lifecycle event we want. Those "lone" requests - // also tend to have a loaderID that matches their requestID, for - // some reason. If such a request is seen, use it. - // TODO: research this some more when we have the time. + // In some cases, such as ERR_TOO_MANY_REDIRECTS, we never see the + // "init" lifecycle event that we want. Such "lone" requests also + // tend to have a loaderID that matches their requestID, for an + // unknown reason. If we see such a request, use it. + // TODO: research this more when we have the time. if ev.FrameID == frameID && string(ev.LoaderID) == string(ev.RequestID) { loaderID = ev.LoaderID } @@ -661,7 +899,7 @@ func responseAction(resp **network.Response, actions ...Action) Action { loaderID = ev.LoaderID } case *page.EventNavigatedWithinDocument: - // A fragment navigation doesn't need extra steps. + // A fragment navigation does not need extra steps. finished = true lcancel() } @@ -674,87 +912,59 @@ func responseAction(resp **network.Response, actions ...Action) Action { }) // Second, run the actions. - if err := Run(ctx, actions...); err != nil { - return err + if _, err := Steps(steps...)(ctx, t); err != nil { + return nil, err } // Third, block until we have finished loading. select { case <-lctx.Done(): if loadErr != nil { - return loadErr + return nil, loadErr } - // If the ctx parameter was cancelled by the caller (or - // by a timeout etc.) the select will race between - // lctx.Done and ctx.Done, since lctx is a sub-context - // of ctx. So we can't return nil here, as otherwise - // that race would mean that we would drop 50% of the - // parent context cancellation errors. + // If the caller canceled ctx (or a timeout ended it), the select + // races between lctx.Done and ctx.Done, because lctx is a + // sub-context of ctx. So we cannot return nil here. Otherwise the + // race drops 50% of the cancellation errors of the parent context. if !finished { - return ctx.Err() + return nil, ctx.Err() } - return nil + return resp, nil case <-ctx.Done(): - return ctx.Err() + return nil, ctx.Err() } - }) + } +} + +// waitLoad makes an action that runs the steps and waits until the page loads. +// It does not return the response. +func waitLoad(steps ...Action[Void]) Action[Void] { + r := responseAction(steps...) + return func(ctx context.Context, t *Target) (Void, error) { + _, err := r(ctx, t) + return Void{}, err + } } -// Targets lists all the targets in the browser attached to the given context. +// Targets lists the targets of the browser of the context. func Targets(ctx context.Context) ([]*target.Info, error) { c, err := initContextBrowser(ctx) if err != nil { return nil, err } - // TODO: If this is a new browser, the initial target (tab) might not be - // ready yet. Should we block until at least one target is available? - // Right now, the caller has to add retries with a timeout. - return target.GetTargets().Do(cdp.WithExecutor(ctx, c.Browser)) -} - -// Action is the common interface for an action that will be executed against a -// context and frame handler. -type Action interface { - // Do executes the action using the provided context and frame handler. - Do(context.Context) error -} - -// ActionFunc is an adapter to allow the use of ordinary func's as an Action. -type ActionFunc func(context.Context) error - -// Do executes the func f using the provided context and frame handler. -func (f ActionFunc) Do(ctx context.Context) error { - return f(ctx) -} - -// Tasks is a sequential list of Actions that can be used as a single Action. -type Tasks []Action - -// Do executes the list of Actions sequentially, using the provided context and -// frame handler. -func (t Tasks) Do(ctx context.Context) error { - for _, a := range t { - if err := a.Do(ctx); err != nil { - return err - } + // TODO: The initial target (tab) of a new browser can be not ready yet. + // Do we block until at least one target is available? Right now, the + // caller has to retry with a timeout. + res, err := cdp.Call(ctx, c.Browser, target.GetTargets, target.GetTargetsParams{}) + if err != nil { + return nil, err } - return nil -} - -// Sleep is an empty action that calls time.Sleep with the specified duration. -// -// Note: this is a temporary action definition for convenience, and will likely -// be marked for deprecation in the future, after the remaining Actions have -// been able to be written/tested. -func Sleep(d time.Duration) Action { - return ActionFunc(func(ctx context.Context) error { - return sleepContext(ctx, d) - }) + return res.TargetInfos, nil } // sleepContext sleeps for the specified duration. It returns ctx.Err() immediately -// if the context is cancelled. +// if the context is canceled. func sleepContext(ctx context.Context, d time.Duration) error { timer := time.NewTimer(d) select { @@ -768,8 +978,8 @@ func sleepContext(ctx context.Context, d time.Duration) error { } } -// retryWithSleep reties the execution of the specified func until the func returns -// true (means to stop) or a non-nil error. +// retryWithSleep calls f again and again, with a sleep of d between the calls, +// until f returns true (stop) or a non-nil error. func retryWithSleep(ctx context.Context, d time.Duration, f func(ctx context.Context) (bool, error)) error { for { toStop, err := f(ctx) @@ -788,60 +998,38 @@ type cancelableListener struct { fn func(ev any) } -// ListenBrowser adds a function which will be called whenever a browser event -// is received on the chromedp context. Note that this only includes browser -// events; command responses and target events are not included. Cancelling ctx -// stops the listener from receiving any more events. +// listen adds a func that the target calls for each event. Canceling ctx +// stops the calls. // -// Note that the function is called synchronously when handling events. The -// function should avoid blocking at all costs. For example, any Actions must be -// run via a separate goroutine (otherwise, it could result in a deadlock if the -// action sends CDP messages). -func ListenBrowser(ctx context.Context, fn func(ev any)) { - c := FromContext(ctx) - if c == nil { - panic(ErrInvalidContext) - } - cl := cancelableListener{ctx, fn} - if c.Browser != nil { - c.Browser.listenersMu.Lock() - c.Browser.listeners = append(c.Browser.listeners, cl) - c.Browser.listenersMu.Unlock() - } else { - c.browserListeners = append(c.browserListeners, cl) - } +// The target calls the func synchronously, so the func must not block. Unlike +// the subscriptions of [Events], the func sees the events of all methods in +// the order in which they arrive. +func (t *Target) listen(ctx context.Context, fn func(ev any)) { + t.listenersMu.Lock() + t.listeners = append(t.listeners, cancelableListener{ctx, fn}) + t.listenersMu.Unlock() } -// ListenTarget adds a function which will be called whenever a target event is -// received on the chromedp context. Cancelling ctx stops the listener from -// receiving any more events. -// -// Note that the function is called synchronously when handling events. The -// function should avoid blocking at all costs. For example, any Actions must be -// run via a separate goroutine (otherwise, it could result in a deadlock if the -// action sends CDP messages). -func ListenTarget(ctx context.Context, fn func(ev any)) { - c := FromContext(ctx) - if c == nil { - panic(ErrInvalidContext) - } - cl := cancelableListener{ctx, fn} - if c.Target != nil { - c.Target.listenersMu.Lock() - c.Target.listeners = append(c.Target.listeners, cl) - c.Target.listenersMu.Unlock() - } else { - c.targetListeners = append(c.targetListeners, cl) - } +// listen is like [Target.listen] for the events of the browser. +func (b *Browser) listen(ctx context.Context, fn func(ev any)) { + b.listenersMu.Lock() + b.listeners = append(b.listeners, cancelableListener{ctx, fn}) + b.listenersMu.Unlock() } -// WaitNewTarget can be used to wait for the current target to open a new -// target. Once fn matches a new unattached target, its target ID is sent via -// the returned channel. +// WaitNewTarget waits for the current target to open a new target. When fn +// matches a new target that is not attached, WaitNewTarget sends its target ID +// on the returned channel. The channel closes without a value when the context +// has no valid target. func WaitNewTarget(ctx context.Context, fn func(*target.Info) bool) <-chan target.ID { ch := make(chan target.ID, 1) + c, err := initContextTarget(ctx) + if err != nil { + close(ch) + return ch + } lctx, cancel := context.WithCancel(ctx) - ListenTarget(lctx, func(ev any) { + c.Target.listen(lctx, func(ev any) { var info *target.Info switch ev := ev.(type) { case *target.EventTargetCreated: @@ -855,7 +1043,7 @@ func WaitNewTarget(ctx context.Context, fn func(*target.Info) bool) <-chan targe return // not a child target } if info.Attached { - return // already attached; not a new target + return // already attached, so not a new target } if fn(info) { select { @@ -868,3 +1056,20 @@ func WaitNewTarget(ctx context.Context, fn func(*target.Info) bool) <-chan targe }) return ch } + +// waitTargetGone polls the browser until the target with the given id is no +// longer listed, or until ctx is done. +func waitTargetGone(ctx context.Context, browser cdp.Session, id target.ID) error { + for { + res, err := cdp.Call(ctx, browser, target.GetTargets, target.GetTargetsParams{}) + if err != nil { + return err + } + if !slices.ContainsFunc(res.TargetInfos, func(info *target.Info) bool { return info.TargetID == id }) { + return nil + } + if err := sleepContext(ctx, 5*time.Millisecond); err != nil { + return err + } + } +} diff --git a/vendor/github.com/chromedp/chromedp/conn.go b/vendor/github.com/chromedp/chromedp/conn.go deleted file mode 100644 index a58e11c8e..000000000 --- a/vendor/github.com/chromedp/chromedp/conn.go +++ /dev/null @@ -1,152 +0,0 @@ -package chromedp - -import ( - "bytes" - "context" - "io" - "net" - - "github.com/chromedp/cdproto" - jsonv2 "github.com/go-json-experiment/json" - "github.com/go-json-experiment/json/jsontext" - "github.com/gobwas/ws" - "github.com/gobwas/ws/wsutil" -) - -// Transport is the common interface to send/receive messages to a target. -// -// This interface is currently used internally by Browser, but it is exposed as -// it will be useful as part of the public API in the future. -type Transport interface { - Read(context.Context, *cdproto.Message) error - Write(context.Context, *cdproto.Message) error - io.Closer -} - -// Conn implements Transport with a gobwas/ws websocket connection. -type Conn struct { - conn net.Conn - - // reuse the websocket reader and writer to avoid an alloc per - // Read/Write. - reader wsutil.Reader - writer wsutil.Writer - - // reuse the easyjson structs to avoid allocs per Read/Write. - decoder jsontext.Decoder - encoder jsontext.Encoder - - debugf func(string, ...any) -} - -// DialContext dials the specified websocket URL using gobwas/ws. -func DialContext(ctx context.Context, urlstr string, opts ...DialOption) (*Conn, error) { - // connect - conn, br, _, err := ws.Dial(ctx, urlstr) - if err != nil { - return nil, err - } - if br != nil { - panic("br should be nil") - } - - // apply opts - c := &Conn{ - conn: conn, - // pass 0 to use the default initial buffer size (4KiB). - // github.com/gobwas/ws will grow the buffer size if needed. - writer: *wsutil.NewWriterBufferSize(conn, ws.StateClientSide, ws.OpText, 0), - } - for _, o := range opts { - o(c) - } - - return c, nil -} - -// Close satisfies the io.Closer interface. -func (c *Conn) Close() error { - return c.conn.Close() -} - -// Read reads the next message. -func (c *Conn) Read(_ context.Context, msg *cdproto.Message) error { - // get websocket reader - c.reader = wsutil.Reader{Source: c.conn, State: ws.StateClientSide} - h, err := c.reader.NextFrame() - if err != nil { - return err - } - - if h.OpCode == ws.OpPing { // ping - if c.debugf != nil { - c.debugf("received ping frame, ignoring...") - } - return nil - } else if h.OpCode == ws.OpClose { // close - if c.debugf != nil { - c.debugf("received close frame") - } - return io.EOF - } else if h.OpCode != ws.OpText { - if c.debugf != nil { - c.debugf("unknown OpCode: %s", h.OpCode) - } - return ErrInvalidWebsocketMessage - } - - var b bytes.Buffer - if _, err := b.ReadFrom(&c.reader); err != nil { - return err - } - - if c.debugf != nil { - c.debugf("<- %s", b.Bytes()) - } - - // unmarshal, reusing decoder - c.decoder.Reset(&b, DefaultUnmarshalOptions) - return jsonv2.UnmarshalDecode(&c.decoder, msg, DefaultUnmarshalOptions) -} - -// Write writes a message. -func (c *Conn) Write(_ context.Context, msg *cdproto.Message) error { - c.writer.Reset(c.conn, ws.StateClientSide, ws.OpText) - // Chrome doesn't support fragmentation of incoming websocket messages. To - // compensate this, they support single-fragment messages of up to 100MiB. - // - // See https://github.com/ChromeDevTools/devtools-protocol/issues/175. - // - // And according to https://bugs.chromium.org/p/chromium/issues/detail?id=1069431, - // it seems like that fragmentation won't be supported very soon. - // Luckily, now github.com/gobwas/ws will grow the buffer if needed. - // The func name DisableFlush is a little misleading, - // but it do make it grow the buffer if needed. - c.writer.DisableFlush() - - // Perform marshal, reusing encoder - var b bytes.Buffer - c.encoder.Reset(&b, DefaultMarshalOptions) - if err := jsonv2.MarshalEncode(&c.encoder, msg, DefaultMarshalOptions); err != nil { - return err - } - - // Write the bytes to the websocket. - if c.debugf != nil { - c.debugf("-> %s", b.Bytes()) - } - if _, err := b.WriteTo(&c.writer); err != nil { - return err - } - return c.writer.Flush() -} - -// DialOption is a dial option. -type DialOption = func(*Conn) - -// WithConnDebugf is a dial option to set a protocol logger. -func WithConnDebugf(f func(string, ...any)) DialOption { - return func(c *Conn) { - c.debugf = f - } -} diff --git a/vendor/github.com/chromedp/chromedp/console.go b/vendor/github.com/chromedp/chromedp/console.go new file mode 100644 index 000000000..1488cf4b5 --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/console.go @@ -0,0 +1,447 @@ +package chromedp + +import ( + "context" + "fmt" + "iter" + "strconv" + "strings" + "time" + + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" + "github.com/chromedp/cdproto/log" + "github.com/chromedp/cdproto/runtime" +) + +// ConsoleType is the kind of a [ConsoleMessage]. The values for a call of the +// console API are the names of the protocol, such as "log", "warning" and +// "error". The package defines a constant for the common ones. +type ConsoleType string + +// Console message types. +const ( + ConsoleLog ConsoleType = "log" + ConsoleDebug ConsoleType = "debug" + ConsoleInfo ConsoleType = "info" + ConsoleWarning ConsoleType = "warning" + ConsoleError ConsoleType = "error" + ConsoleException ConsoleType = "exception" +) + +// ConsoleMessage is a message that the page wrote to the console. It is a call +// of the console API, an exception that nothing caught, or an entry of the +// browser log. +type ConsoleMessage struct { + // Type is the kind of the message. An uncaught exception and an unhandled + // promise rejection have the type [ConsoleException]. An entry of the browser + // log has the type "debug", "info", "warning" or "error", for the levels + // verbose, info, warning and error. + Type ConsoleType + + // Text is the text that the DevTools console shows. A string argument is + // there as it is, and another value has its description or a short form of + // its properties. A format such as %s and %d in the first argument takes the + // arguments that follow it. For an exception, the text is the error and its + // message, and the stack is in Stack. + Text string + + // Args are the arguments of the call to the console API, as the protocol + // reports them. The objects have no value, only a description and a + // preview. Use [runtime.GetProperties] with the object id to read one. Args + // is empty for an exception and for an entry of the browser log. + Args []*runtime.RemoteObject + + // Time is the time of the message, as the browser reports it. + Time time.Time + + // URL, Line and Column tell where the message came from. A call of the + // console API has the place of the call. An exception has the place of the + // throw. They can be empty. The line and the column start at 0, as in the + // protocol. + URL string + Line int64 + Column int64 + + // Stack is the stack trace of the call or of the exception. It is nil when + // the browser reports none. + Stack *runtime.StackTrace + + // Exception holds the details of an exception, and it is nil for another + // message. + Exception *runtime.ExceptionDetails + + // Source tells which part of the browser wrote a message of the browser + // log, for example "network" or "security". It is empty for a call of the + // console API and for an exception. + Source string +} + +// IsException reports whether the message is an uncaught exception or an +// unhandled promise rejection. +func (m ConsoleMessage) IsException() bool { + return m.Type == ConsoleException +} + +// String returns the type and the text of the message. +func (m ConsoleMessage) String() string { + return string(m.Type) + ": " + m.Text +} + +// Console subscribes to the console of the target of the context, and returns +// an iterator over its messages. A message is a call of the console API such +// as console.log, an uncaught exception, an unhandled promise rejection, or an +// entry of the browser log. The iterator keeps the order of the messages. +// +// Console reads the events [runtime.ConsoleAPICalled], [runtime.ExceptionThrown] +// and [log.EntryAdded]. [Events] gives the same events one by one, as the +// protocol sends them, and Console joins them in one stream of simple values. +// The old API used [ListenTarget] with a func that tested the type of each +// event. +// +// As [Events] does, Console subscribes when it returns, and not when the +// caller starts to range. A caller can subscribe, run the actions, and then +// range, so that no message is lost: +// +// messages := chromedp.Console(ctx) +// if err := chromedp.Do(ctx, chromedp.Navigate(url)); err != nil { +// return err +// } +// for m, err := range messages { +// if err != nil { +// break +// } +// fmt.Println(m) +// } +// +// A browser sends the messages only from the moment that the target exists, so +// a message that the page wrote before the first call of Console or of [Run] +// is lost. If the browser cannot start, the iterator yields the error. See +// [cdp.Events] for the rules about ending the iteration. +// +// To stop, cancel the context or break out of the loop. Both end the +// subscription and free its queue, also when the program never ranged over the +// iterator. +// +// The queue of the messages has no limit, so that a slow reader never blocks +// the page. The page keeps working when the program does not read the messages, +// but the queue grows with each message until the subscription ends. A program +// that reads slowly or stops to read must cancel the context or break out of +// the loop. +func Console(ctx context.Context) iter.Seq2[ConsoleMessage, error] { + c, err := initContextTarget(ctx) + if err != nil { + return failed[ConsoleMessage](err) + } + events, unsubscribe := c.Target.events.subscribeMany( + runtime.ConsoleAPICalled.Method, + runtime.ExceptionThrown.Method, + log.EntryAdded.Method, + ) + // End the subscription when the context ends, also when nobody ranges + // over the iterator. + stop := context.AfterFunc(ctx, unsubscribe) + return func(yield func(ConsoleMessage, error) bool) { + defer unsubscribe() + defer stop() + for { + select { + case <-ctx.Done(): + yield(ConsoleMessage{}, ctx.Err()) + return + case raw, ok := <-events: + if !ok { + return + } + m, err := decodeConsole(raw) + if err != nil { + yield(ConsoleMessage{}, err) + return + } + if !yield(m, nil) { + return + } + } + } + } +} + +// decodeConsole turns a tagged event into a message. +func decodeConsole(raw jsonv2.Value) (ConsoleMessage, error) { + var ev struct { + Method string `json:"method"` + Params jsonv2.Value `json:"params"` + } + if err := jsonv2.Unmarshal(raw, &ev, DefaultUnmarshalOptions); err != nil { + return ConsoleMessage{}, fmt.Errorf("decoding a console event: %w", err) + } + switch ev.Method { + case runtime.ConsoleAPICalled.Method: + var e runtime.EventConsoleAPICalled + if err := jsonv2.Unmarshal(ev.Params, &e, DefaultUnmarshalOptions); err != nil { + return ConsoleMessage{}, fmt.Errorf("decoding %s: %w", ev.Method, err) + } + return consoleCall(&e), nil + case runtime.ExceptionThrown.Method: + var e runtime.EventExceptionThrown + if err := jsonv2.Unmarshal(ev.Params, &e, DefaultUnmarshalOptions); err != nil { + return ConsoleMessage{}, fmt.Errorf("decoding %s: %w", ev.Method, err) + } + return consoleException(&e), nil + default: + var e log.EventEntryAdded + if err := jsonv2.Unmarshal(ev.Params, &e, DefaultUnmarshalOptions); err != nil { + return ConsoleMessage{}, fmt.Errorf("decoding %s: %w", ev.Method, err) + } + return consoleLog(&e), nil + } +} + +// consoleTime converts a protocol timestamp, in milliseconds, to a time. +func consoleTime(ts runtime.Timestamp) time.Time { + ms := float64(ts) + return time.Unix(int64(ms/1000), int64(ms*1e6)%1e9) +} + +func consoleCall(e *runtime.EventConsoleAPICalled) ConsoleMessage { + m := ConsoleMessage{ + Type: ConsoleType(e.Type), + Text: consoleText(e.Args), + Args: e.Args, + Time: consoleTime(e.Timestamp), + Stack: e.StackTrace, + } + if st := e.StackTrace; st != nil && len(st.CallFrames) > 0 { + f := st.CallFrames[0] + m.URL, m.Line, m.Column = f.URL, f.LineNumber, f.ColumnNumber + } + return m +} + +func consoleException(e *runtime.EventExceptionThrown) ConsoleMessage { + d := e.ExceptionDetails + m := ConsoleMessage{ + Type: ConsoleException, + Text: d.Text, + Time: consoleTime(e.Timestamp), + URL: d.URL, + Line: d.LineNumber, + Column: d.ColumnNumber, + Stack: d.StackTrace, + Exception: d, + } + if obj := d.Exception; obj != nil { + // The text is "Uncaught" or "Uncaught (in promise)", and the object is + // the error. The description of an error holds its stack, which + // is in Stack as well. + desc, _, _ := strings.Cut(consoleValue(obj), "\n at ") + m.Text = strings.TrimSpace(d.Text + " " + desc) + } + if m.URL == "" && d.StackTrace != nil && len(d.StackTrace.CallFrames) > 0 { + m.URL = d.StackTrace.CallFrames[0].URL + } + return m +} + +func consoleLog(e *log.EventEntryAdded) ConsoleMessage { + en := e.Entry + m := ConsoleMessage{ + Text: en.Text, + Args: en.Args, + Time: consoleTime(en.Timestamp), + URL: en.URL, + Line: en.LineNumber, + Stack: en.StackTrace, + Source: string(en.Source), + } + switch en.Level { + case log.EntryLevelVerbose: + m.Type = ConsoleDebug + default: + m.Type = ConsoleType(en.Level) + } + return m +} + +// consoleText renders the arguments of a call of the console API as the +// DevTools console does. +func consoleText(args []*runtime.RemoteObject) string { + if len(args) == 0 { + return "" + } + var parts []string + rest := args + if first := args[0]; first.Type == runtime.RemoteObjectTypeString { + var s string + if err := jsonv2.Unmarshal(first.Value, &s); err == nil { + if strings.Contains(s, "%") { + var n int + s, n = consoleFormat(s, args[1:]) + rest = args[1+n:] + } else { + rest = args[1:] + } + parts = append(parts, s) + } + } + for _, a := range rest { + parts = append(parts, consoleValue(a)) + } + return strings.Join(parts, " ") +} + +// consoleFormat applies the format specifiers %s, %d, %i, %f, %o, %O, %c and +// %% of the format to the arguments. It returns the text and the number of +// arguments that it used. +func consoleFormat(format string, args []*runtime.RemoteObject) (string, int) { + var b strings.Builder + used := 0 + for i := 0; i < len(format); i++ { + c := format[i] + if c != '%' || i+1 == len(format) { + b.WriteByte(c) + continue + } + verb := format[i+1] + if verb == '%' { + b.WriteByte('%') + i++ + continue + } + if !strings.ContainsRune("sdifoOc", rune(verb)) || used == len(args) { + b.WriteByte(c) + continue + } + a := args[used] + used++ + i++ + switch verb { + case 's': + if a.Type == runtime.RemoteObjectTypeString { + var s string + if jsonv2.Unmarshal(a.Value, &s) == nil { + b.WriteString(s) + continue + } + } + b.WriteString(consoleValue(a)) + case 'd', 'i': + b.WriteString(consoleNumber(a, verb == 'i')) + case 'f': + b.WriteString(consoleNumber(a, false)) + case 'o', 'O': + b.WriteString(consoleValue(a)) + } + // The verb c sets a CSS style. It prints nothing. + } + return b.String(), used +} + +// consoleNumber renders an argument for %d, %i and %f. +func consoleNumber(a *runtime.RemoteObject, integer bool) string { + if a.Type != runtime.RemoteObjectTypeNumber { + return "NaN" + } + if a.UnserializableValue != "" { + return string(a.UnserializableValue) + } + f, err := strconv.ParseFloat(string(a.Value), 64) + if err != nil { + return "NaN" + } + if integer { + f = float64(int64(f)) + } + return strconv.FormatFloat(f, 'f', -1, 64) +} + +// consoleValue renders one value. A string stays as it is, a primitive has its +// value, and an object has its description, or a short form of its +// properties when the browser sent a preview. +func consoleValue(o *runtime.RemoteObject) string { + if o == nil { + return "null" + } + switch o.Type { + case runtime.RemoteObjectTypeString: + var s string + if err := jsonv2.Unmarshal(o.Value, &s); err == nil { + return s + } + case runtime.RemoteObjectTypeUndefined: + return "undefined" + case runtime.RemoteObjectTypeObject: + if o.Subtype == runtime.RemoteObjectSubtypeNull { + return "null" + } + if o.Preview != nil && o.Subtype != runtime.RemoteObjectSubtypeError { + return consolePreview(o.Preview) + } + } + if o.UnserializableValue != "" { + return string(o.UnserializableValue) + } + if o.Description != "" { + return o.Description + } + if len(o.Value) > 0 { + return string(o.Value) + } + return string(o.Type) +} + +// consolePreview renders the preview of an object, for example {a: 1, b: "x"} +// or [1, 2, 3]. A property that does not fit ends the list with an ellipsis. +func consolePreview(p *runtime.ObjectPreview) string { + var items []string + isArray := p.Subtype == runtime.ObjectPreviewSubtypeArray + for _, prop := range p.Properties { + v := consolePropertyValue(prop) + if isArray { + items = append(items, v) + } else { + items = append(items, prop.Name+": "+v) + } + } + for _, e := range p.Entries { + v := consoleNested(e.Value) + if e.Key != nil { + v = consoleNested(e.Key) + " => " + v + } + items = append(items, v) + } + if p.Overflow { + items = append(items, "…") + } + body := strings.Join(items, ", ") + switch { + case isArray: + return "[" + body + "]" + case p.Description == "Object": + return "{" + body + "}" + default: + return p.Description + " {" + body + "}" + } +} + +func consolePropertyValue(prop *runtime.PropertyPreview) string { + if prop.ValuePreview != nil { + return consolePreview(prop.ValuePreview) + } + if prop.Type == runtime.PropertyPreviewTypeString { + return strconv.Quote(prop.Value) + } + return prop.Value +} + +func consoleNested(p *runtime.ObjectPreview) string { + if p == nil { + return "" + } + if p.Type == runtime.ObjectPreviewTypeString { + return strconv.Quote(p.Description) + } + if p.Type == runtime.ObjectPreviewTypeObject && len(p.Properties) > 0 { + return consolePreview(p) + } + return p.Description +} diff --git a/vendor/github.com/chromedp/chromedp/device/device.go b/vendor/github.com/chromedp/chromedp/device/device.go index 152865e33..6563ee711 100644 --- a/vendor/github.com/chromedp/chromedp/device/device.go +++ b/vendor/github.com/chromedp/chromedp/device/device.go @@ -208,6 +208,12 @@ const ( // IPhoneSElandscape is the "iPhone SE landscape" device. IPhoneSElandscape + // IPhoneSE3rdgen is the "iPhone SE (3rd gen)" device. + IPhoneSE3rdgen + + // IPhoneSE3rdgenlandscape is the "iPhone SE (3rd gen) landscape" device. + IPhoneSE3rdgenlandscape + // IPhoneX is the "iPhone X" device. IPhoneX @@ -334,6 +340,66 @@ const ( // IPhone15ProMaxlandscape is the "iPhone 15 Pro Max landscape" device. IPhone15ProMaxlandscape + // IPhone16 is the "iPhone 16" device. + IPhone16 + + // IPhone16landscape is the "iPhone 16 landscape" device. + IPhone16landscape + + // IPhone16Plus is the "iPhone 16 Plus" device. + IPhone16Plus + + // IPhone16Pluslandscape is the "iPhone 16 Plus landscape" device. + IPhone16Pluslandscape + + // IPhone16Pro is the "iPhone 16 Pro" device. + IPhone16Pro + + // IPhone16Prolandscape is the "iPhone 16 Pro landscape" device. + IPhone16Prolandscape + + // IPhone16ProMax is the "iPhone 16 Pro Max" device. + IPhone16ProMax + + // IPhone16ProMaxlandscape is the "iPhone 16 Pro Max landscape" device. + IPhone16ProMaxlandscape + + // IPhone16e is the "iPhone 16e" device. + IPhone16e + + // IPhone16elandscape is the "iPhone 16e landscape" device. + IPhone16elandscape + + // IPhone17 is the "iPhone 17" device. + IPhone17 + + // IPhone17landscape is the "iPhone 17 landscape" device. + IPhone17landscape + + // IPhoneAir is the "iPhone Air" device. + IPhoneAir + + // IPhoneAirlandscape is the "iPhone Air landscape" device. + IPhoneAirlandscape + + // IPhone17Pro is the "iPhone 17 Pro" device. + IPhone17Pro + + // IPhone17Prolandscape is the "iPhone 17 Pro landscape" device. + IPhone17Prolandscape + + // IPhone17ProMax is the "iPhone 17 Pro Max" device. + IPhone17ProMax + + // IPhone17ProMaxlandscape is the "iPhone 17 Pro Max landscape" device. + IPhone17ProMaxlandscape + + // IPhone17e is the "iPhone 17e" device. + IPhone17e + + // IPhone17elandscape is the "iPhone 17e landscape" device. + IPhone17elandscape + // JioPhone2 is the "JioPhone 2" device. JioPhone2 @@ -509,6 +575,8 @@ var devices = [...]Info{ {"iPhone 8 Plus landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 736, 414, 3.000000, true, true, true}, {"iPhone SE", "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1", 320, 568, 2.000000, false, true, true}, {"iPhone SE landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1", 568, 320, 2.000000, true, true, true}, + {"iPhone SE (3rd gen)", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/26.5 Mobile/19E241 Safari/602.1", 375, 667, 2.000000, false, true, true}, + {"iPhone SE (3rd gen) landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/26.5 Mobile/19E241 Safari/602.1", 667, 375, 2.000000, true, true, true}, {"iPhone X", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 375, 812, 3.000000, false, true, true}, {"iPhone X landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 812, 375, 3.000000, true, true, true}, {"iPhone XR", "Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1", 414, 896, 3.000000, false, true, true}, @@ -551,6 +619,26 @@ var devices = [...]Info{ {"iPhone 15 Pro landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1", 734, 343, 3.000000, true, true, true}, {"iPhone 15 Pro Max", "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1", 430, 739, 3.000000, false, true, true}, {"iPhone 15 Pro Max landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1", 814, 380, 3.000000, true, true, true}, + {"iPhone 16", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 393, 659, 3.000000, false, true, true}, + {"iPhone 16 landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 734, 343, 3.000000, true, true, true}, + {"iPhone 16 Plus", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 430, 739, 3.000000, false, true, true}, + {"iPhone 16 Plus landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 814, 380, 3.000000, true, true, true}, + {"iPhone 16 Pro", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 402, 681, 3.000000, false, true, true}, + {"iPhone 16 Pro landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 756, 352, 3.000000, true, true, true}, + {"iPhone 16 Pro Max", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 440, 763, 3.000000, false, true, true}, + {"iPhone 16 Pro Max landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 838, 390, 3.000000, true, true, true}, + {"iPhone 16e", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 390, 651, 3.000000, false, true, true}, + {"iPhone 16e landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 726, 340, 3.000000, true, true, true}, + {"iPhone 17", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 402, 681, 3.000000, false, true, true}, + {"iPhone 17 landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 756, 352, 3.000000, true, true, true}, + {"iPhone Air", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 420, 719, 3.000000, false, true, true}, + {"iPhone Air landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 794, 370, 3.000000, true, true, true}, + {"iPhone 17 Pro", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 402, 681, 3.000000, false, true, true}, + {"iPhone 17 Pro landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 756, 352, 3.000000, true, true, true}, + {"iPhone 17 Pro Max", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 440, 763, 3.000000, false, true, true}, + {"iPhone 17 Pro Max landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 838, 390, 3.000000, true, true, true}, + {"iPhone 17e", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 390, 651, 3.000000, false, true, true}, + {"iPhone 17e landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Mobile/15E148 Safari/604.1", 726, 340, 3.000000, true, true, true}, {"JioPhone 2", "Mozilla/5.0 (Mobile; LYF/F300B/LYF-F300B-001-01-15-130718-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.5", 240, 320, 1.000000, false, true, true}, {"JioPhone 2 landscape", "Mozilla/5.0 (Mobile; LYF/F300B/LYF-F300B-001-01-15-130718-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.5", 320, 240, 1.000000, true, true, true}, {"Kindle Fire HDX", "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", 800, 1280, 2.000000, false, true, true}, diff --git a/vendor/github.com/chromedp/chromedp/drag.go b/vendor/github.com/chromedp/chromedp/drag.go new file mode 100644 index 000000000..db5a8963a --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/drag.go @@ -0,0 +1,299 @@ +package chromedp + +import ( + "context" + "fmt" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" + "time" + + "github.com/chromedp/cdproto/cdp" + "github.com/chromedp/cdproto/dom" + "github.com/chromedp/cdproto/input" + "github.com/chromedp/cdproto/page" + "github.com/chromedp/cdproto/runtime" +) + +const ( + // defaultDragSteps is the number of mouse moves of a drag when the caller + // gives none. + defaultDragSteps = 10 + + // dragInterceptWait is how long a drag waits after the last mouse move for + // the browser to report a native drag. The report can arrive after the + // answer to the mouse move. + dragInterceptWait = 100 * time.Millisecond + + // dragDraggableWait is how long a drag waits for the report of a native drag + // when the element at the start point can start one, such as an element + // with draggable="true". A slow machine needs more than dragInterceptWait. + // The wait ends as soon as the report arrives. + dragDraggableWait = 2 * time.Second +) + +// DragAndDrop is an element query action that drags the first element node that +// matches from, and drops it on the first element node that matches to. It +// presses the left mouse button at the center of the first node, moves the +// mouse to the center of the second node in several steps, and releases the +// button. See [DragAndDropXY] for the details. +// +// The two selectors can have different types. The query options apply to both +// queries. Both nodes must be in the viewport at the same time, because the +// action does not scroll while it drags. When they do not fit, the action +// returns [ErrDragOutsideViewport] and does not drag. +// +// For example, to move a handle to the end of a slider: +// +// err := chromedp.Do(ctx, chromedp.DragAndDrop(chromedp.CSS("#handle"), chromedp.CSS("#end"))) +func DragAndDrop[S, T Selectable](from S, to T, opts ...QueryOption) Action[Void] { + return func(ctx context.Context, t *Target) (Void, error) { + // Scroll each node into view. Scrolling the second node can move the + // first node, so read the centers only after both scrolls. + fromNode, err := queryScrolled(from, opts)(ctx, t) + if err != nil { + return Void{}, err + } + toNode, err := queryScrolled(to, opts)(ctx, t) + if err != nil { + return Void{}, err + } + fx, fy, err := quadCenter(ctx, t, fromNode) + if err != nil { + return Void{}, err + } + tx, ty, err := quadCenter(ctx, t, toNode) + if err != nil { + return Void{}, err + } + if err := checkInViewport(ctx, t, [2]float64{fx, fy}, [2]float64{tx, ty}); err != nil { + return Void{}, err + } + return DragAndDropXY(fx, fy, tx, ty)(ctx, t) + } +} + +// ErrDragOutsideViewport is the error of [DragAndDrop] when the two nodes do +// not fit in the viewport at the same time. The action does not scroll while +// it drags, so a drag between two such nodes does nothing. +const ErrDragOutsideViewport Error = "the nodes of the drag are not in the viewport at the same time" + +// checkInViewport returns ErrDragOutsideViewport when a point is outside the +// visual viewport. +func checkInViewport(ctx context.Context, t *Target, points ...[2]float64) error { + m, err := cdp.Call(ctx, t, page.GetLayoutMetrics, cdp.Empty{}) + if err != nil { + return err + } + vp := m.CSSVisualViewport + if vp == nil { + return nil + } + for _, p := range points { + if p[0] < 0 || p[1] < 0 || p[0] > vp.ClientWidth || p[1] > vp.ClientHeight { + return ErrDragOutsideViewport + } + } + return nil +} + +// queryScrolled is an element query action that scrolls the first element node +// that matches the selector into view, and returns the node. +func queryScrolled[S Selectable](sel S, opts []QueryOption) Action[*Node] { + return QueryAfter(sel, func(ctx context.Context, t *Target, nodes []*Node) (*Node, error) { + n, err := first(sel, nodes) + if err != nil { + return nil, err + } + if _, err := cdp.Call(ctx, t, dom.ScrollIntoViewIfNeeded, dom.ScrollIntoViewIfNeededParams{NodeID: n.NodeID}); err != nil { + return nil, err + } + return n, nil + }, withOpts(opts, NodeVisible)...) +} + +// draggableAt reports whether the element at the point can start a native +// drag: an element inside a node with draggable="true", a link or an image. It +// returns false when it cannot tell. +func draggableAt(ctx context.Context, t *Target, x, y float64) bool { + expr := fmt.Sprintf(`(function(x, y) { + var e = document.elementFromPoint(x, y); + return !!(e && e.closest('[draggable="true"], a[href], img')); + })(%v, %v)`, x, y) + res, err := cdp.Call(ctx, t, runtime.Evaluate, runtime.EvaluateParams{Expression: expr, ReturnByValue: ptr(true)}) + if err != nil || res.ExceptionDetails != nil || res.Result == nil { + return false + } + return string(res.Result.Value) == "true" +} + +// DragAndDropXY is an action that drags from the point fromX, fromY and drops +// at the point toX, toY. The points are in CSS pixels, relative to the +// viewport. The optional steps value is the number of mouse moves between the +// two points. The default is 10, and a value below 1 means 1. +// +// The action works for two kinds of page. It handles both with the same calls, +// and the page decides which one it is: +// +// - A page that listens for mouse events, such as a slider, a drag handle or +// a sortable list, gets a mousePressed event, the mouseMoved events and a +// mouseReleased event. +// - A page that uses HTML5 drag and drop, with draggable elements and the +// events dragstart, dragover and drop, gets the same mouse events up to +// the start of the drag. Then the browser starts a native drag, which a +// headless browser does not always finish with mouse events. So the action turns +// on [input.SetInterceptDrags], reads the data of the drag from the event +// [input.DragIntercepted], and sends the events dragEnter, dragOver and drop +// with [input.DispatchDragEvent]. The page sees them as the real events, +// with a DataTransfer that holds the data of the drag. +// +// The action turns the interception off when it returns. When an error ends the +// drag after the mouse button went down, for example when the context ends, the +// action still releases the button at the last point of the mouse. It uses a new +// context with a limit of 5 seconds for the release, and ignores an error of the +// release. A drag that a page +// starts with a distance that is shorter than the drag threshold of the +// browser, a few pixels, does not start. Use points that are at least 10 +// pixels apart. +func DragAndDropXY(fromX, fromY, toX, toY float64, steps ...int) Action[Void] { + n := defaultDragSteps + if len(steps) > 0 { + n = max(steps[0], 1) + } + return Func(func(ctx context.Context, t *Target) (err error) { + if _, err := cdp.Call(ctx, t, input.SetInterceptDrags, input.SetInterceptDragsParams{Enabled: true}); err != nil { + return err + } + defer func() { + // Turn the interception off, also when the context ended. + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + if _, off := cdp.Call(ctx, t, input.SetInterceptDrags, input.SetInterceptDragsParams{Enabled: false}); off != nil && err == nil { + err = off + } + }() + + // The subscription holds each event from now on. + intercepted, cancel := t.Subscribe(input.DragIntercepted.Method) + defer cancel() + + // Track the button, so that an error between the press and the release + // does not leave the button down in the browser. + var pressed bool + var lastX, lastY float64 + defer func() { + if !pressed { + return + } + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + p := input.DispatchMouseEventParams{Type: MouseReleased, X: lastX, Y: lastY, Button: input.MouseButtonLeft, ClickCount: 1} + _, _ = cdp.Call(ctx, t, input.DispatchMouseEvent, p) + }() + + mouse := func(typ input.DispatchMouseEventType, x, y float64) error { + switch typ { + case MousePressed: + pressed = true + case MouseReleased: + // Do not send a second release, also when this one fails. + pressed = false + } + lastX, lastY = x, y + p := input.DispatchMouseEventParams{Type: typ, X: x, Y: y, Button: input.MouseButtonLeft} + switch typ { + case MousePressed: + p.Buttons, p.ClickCount = 1, 1 + case MouseMoved: + p.Buttons = 1 + case MouseReleased: + p.ClickCount = 1 + } + _, err := cdp.Call(ctx, t, input.DispatchMouseEvent, p) + return err + } + + // intercept returns the data of a native drag, when the browser + // reported one within the wait. + intercept := func(wait time.Duration) (*input.DragData, error) { + var raw jsonv2.Value + if wait <= 0 { + select { + case raw = <-intercepted: + default: + return nil, nil + } + } else { + timer := time.NewTimer(wait) + defer timer.Stop() + select { + case raw = <-intercepted: + case <-timer.C: + return nil, nil + case <-ctx.Done(): + return nil, ctx.Err() + } + } + var ev input.EventDragIntercepted + if err := jsonv2.Unmarshal(raw, &ev, DefaultUnmarshalOptions); err != nil { + return nil, fmt.Errorf("decoding %s: %w", input.DragIntercepted.Method, err) + } + return ev.Data, nil + } + + // An element that can start a native drag gets a longer wait for the + // report of the drag. Other elements keep the short wait. + lastWait := dragInterceptWait + if draggableAt(ctx, t, fromX, fromY) { + lastWait = dragDraggableWait + } + + if err := mouse(MousePressed, fromX, fromY); err != nil { + return err + } + for i := 1; i <= n; i++ { + x := fromX + (toX-fromX)*float64(i)/float64(n) + y := fromY + (toY-fromY)*float64(i)/float64(n) + if err := mouse(MouseMoved, x, y); err != nil { + return err + } + wait := time.Duration(0) + if i == n { + wait = lastWait + } + data, err := intercept(wait) + if err != nil { + return err + } + if data != nil { + return dragNative(ctx, t, data, mouse, [2]float64{x, y}, [2]float64{toX, toY}, n-i) + } + } + return mouse(MouseReleased, toX, toY) + }) +} + +// dragNative continues a drag that the browser intercepted. The mouse is at +// the point from, and the drag ends at the point to after the given number of +// steps. +func dragNative(ctx context.Context, t *Target, data *input.DragData, mouse func(input.DispatchMouseEventType, float64, float64) error, from, to [2]float64, steps int) error { + send := func(typ input.DispatchDragEventType, x, y float64) error { + _, err := cdp.Call(ctx, t, input.DispatchDragEvent, input.DispatchDragEventParams{Type: typ, X: x, Y: y, Data: data}) + return err + } + if err := send(input.DispatchDragEventTypeDragEnter, from[0], from[1]); err != nil { + return err + } + for i := 1; i <= steps; i++ { + x := from[0] + (to[0]-from[0])*float64(i)/float64(steps) + y := from[1] + (to[1]-from[1])*float64(i)/float64(steps) + if err := send(input.DispatchDragEventTypeDragOver, x, y); err != nil { + return err + } + } + if err := send(input.DispatchDragEventTypeDragOver, to[0], to[1]); err != nil { + return err + } + if err := send(input.DispatchDragEventTypeDrop, to[0], to[1]); err != nil { + return err + } + return mouse(MouseReleased, to[0], to[1]) +} diff --git a/vendor/github.com/chromedp/chromedp/emulate.go b/vendor/github.com/chromedp/chromedp/emulate.go index b50973bdd..b2c34b952 100644 --- a/vendor/github.com/chromedp/chromedp/emulate.go +++ b/vendor/github.com/chromedp/chromedp/emulate.go @@ -1,30 +1,35 @@ package chromedp import ( + "context" + + "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/emulation" "github.com/chromedp/chromedp/device" ) -// EmulateAction are actions that change the emulation settings for the -// browser. -type EmulateAction Action - -// EmulateViewport is an action to change the browser viewport. +// EmulateViewport is an action that changes the browser viewport. // -// Wraps calls to emulation.SetDeviceMetricsOverride and emulation.SetTouchEmulationEnabled. +// It wraps calls to emulation.SetDeviceMetricsOverride and +// emulation.SetTouchEmulationEnabled. // -// Note: this has the effect of setting/forcing the screen orientation to -// landscape, and will disable mobile and touch emulation by default. If this -// is not the desired behavior, use the emulate viewport options -// EmulateOrientation (or EmulateLandscape/EmulatePortrait), EmulateMobile, and -// EmulateTouch, respectively. -func EmulateViewport(width, height int64, opts ...EmulateViewportOption) EmulateAction { - p1 := emulation.SetDeviceMetricsOverride(width, height, 1.0, false) - p2 := emulation.SetTouchEmulationEnabled(false) +// Note: by default, this action sets the screen orientation to landscape and +// disables mobile and touch emulation. To change that, use the emulate +// viewport options EmulateOrientation (or EmulateLandscape or +// EmulatePortrait), EmulateMobile, and EmulateTouch. +func EmulateViewport(width, height int64, opts ...EmulateViewportOption) Action[Void] { + p1 := &emulation.SetDeviceMetricsOverrideParams{Width: width, Height: height, DeviceScaleFactor: 1.0} + p2 := &emulation.SetTouchEmulationEnabledParams{} for _, o := range opts { o(p1, p2) } - return Tasks{p1, p2} + return Func(func(ctx context.Context, t *Target) error { + if _, err := cdp.Call(ctx, t, emulation.SetDeviceMetricsOverride, *p1); err != nil { + return err + } + _, err := cdp.Call(ctx, t, emulation.SetTouchEmulationEnabled, *p2) + return err + }) } // EmulateViewportOption is the type for emulate viewport options. @@ -40,7 +45,7 @@ func EmulateScale(scale float64) EmulateViewportOption { // EmulateOrientation is an emulate viewport option to set the device viewport // screen orientation. -func EmulateOrientation(orientation emulation.OrientationType, angle int64) EmulateViewportOption { +func EmulateOrientation(orientation emulation.ScreenOrientationType, angle int64) EmulateViewportOption { return func(p1 *emulation.SetDeviceMetricsOverrideParams, p2 *emulation.SetTouchEmulationEnabledParams) { p1.ScreenOrientation = &emulation.ScreenOrientation{ Type: orientation, @@ -52,13 +57,13 @@ func EmulateOrientation(orientation emulation.OrientationType, angle int64) Emul // EmulateLandscape is an emulate viewport option to set the device viewport // screen orientation in landscape primary mode and an angle of 90. func EmulateLandscape(p1 *emulation.SetDeviceMetricsOverrideParams, p2 *emulation.SetTouchEmulationEnabledParams) { - EmulateOrientation(emulation.OrientationTypeLandscapePrimary, 90)(p1, p2) + EmulateOrientation(emulation.ScreenOrientationTypeLandscapePrimary, 90)(p1, p2) } // EmulatePortrait is an emulate viewport option to set the device viewport // screen orientation in portrait primary mode and an angle of 0. func EmulatePortrait(p1 *emulation.SetDeviceMetricsOverrideParams, p2 *emulation.SetTouchEmulationEnabledParams) { - EmulateOrientation(emulation.OrientationTypePortraitPrimary, 0)(p1, p2) + EmulateOrientation(emulation.ScreenOrientationTypePortraitPrimary, 0)(p1, p2) } // EmulateMobile is an emulate viewport option to toggle the device viewport to @@ -72,17 +77,17 @@ func EmulateTouch(p1 *emulation.SetDeviceMetricsOverrideParams, p2 *emulation.Se p2.Enabled = true } -// ResetViewport is an action to reset the browser viewport to the default -// values the browser was started with. +// ResetViewport is an action that resets the browser viewport to the values +// that the browser started with. // -// Note: does not modify / change the browser's emulated User-Agent, if any. -func ResetViewport() EmulateAction { +// Note: it does not change the emulated User-Agent of the browser, if any. +func ResetViewport() Action[Void] { return EmulateViewport(0, 0, EmulatePortrait) } // Device is the shared interface for known device types. // -// See [device] for a set of off-the-shelf devices and modes. +// See [device] for a set of ready-made devices and modes. type Device interface { // Device returns the device info. Device() device.Info @@ -90,32 +95,42 @@ type Device interface { // Emulate is an action to emulate a specific device. // -// See [device] for a set of off-the-shelf devices and modes. -func Emulate(device Device) EmulateAction { +// See [device] for a set of ready-made devices and modes. +func Emulate(device Device) Action[Void] { d := device.Device() var angle int64 - orientation := emulation.OrientationTypePortraitPrimary + orientation := emulation.ScreenOrientationTypePortraitPrimary if d.Landscape { - orientation, angle = emulation.OrientationTypeLandscapePrimary, 90 + orientation, angle = emulation.ScreenOrientationTypeLandscapePrimary, 90 } - return Tasks{ - emulation.SetUserAgentOverride(d.UserAgent), - emulation.SetDeviceMetricsOverride(d.Width, d.Height, d.Scale, d.Mobile). - WithScreenOrientation(&emulation.ScreenOrientation{ + return Func(func(ctx context.Context, t *Target) error { + if _, err := cdp.Call(ctx, t, emulation.SetUserAgentOverride, emulation.SetUserAgentOverrideParams{UserAgent: d.UserAgent}); err != nil { + return err + } + if _, err := cdp.Call(ctx, t, emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{ + Width: d.Width, + Height: d.Height, + DeviceScaleFactor: d.Scale, + Mobile: d.Mobile, + ScreenOrientation: &emulation.ScreenOrientation{ Type: orientation, Angle: angle, - }), - emulation.SetTouchEmulationEnabled(d.Touch), - } + }, + }); err != nil { + return err + } + _, err := cdp.Call(ctx, t, emulation.SetTouchEmulationEnabled, emulation.SetTouchEmulationEnabledParams{Enabled: d.Touch}) + return err + }) } -// EmulateReset is an action to reset the device emulation. +// EmulateReset is an action that resets the device emulation. // -// Resets the browser's viewport, screen orientation, user-agent, and -// mobile/touch emulation settings to the original values the browser was -// started with. -func EmulateReset() EmulateAction { +// It resets the viewport, the screen orientation, the user agent, and the +// mobile and touch emulation. The new values are the original values from the +// start of the browser. +func EmulateReset() Action[Void] { return Emulate(device.Reset) } diff --git a/vendor/github.com/chromedp/chromedp/errors.go b/vendor/github.com/chromedp/chromedp/errors.go index d9ff23862..f6daab3e4 100644 --- a/vendor/github.com/chromedp/chromedp/errors.go +++ b/vendor/github.com/chromedp/chromedp/errors.go @@ -1,5 +1,56 @@ package chromedp +import ( + "fmt" + "strings" + + "github.com/chromedp/cdproto/runtime" +) + +// ExceptionError is the error for a JavaScript exception. It wraps the +// protocol details of the exception. +type ExceptionError struct { + *runtime.ExceptionDetails +} + +// Error satisfies the error interface. +func (e *ExceptionError) Error() string { + return exceptionString(e.ExceptionDetails) +} + +// exceptionString returns a readable description of an exception. +func exceptionString(e *runtime.ExceptionDetails) string { + var b strings.Builder + fmt.Fprintf(&b, "exception %q (%d:%d)", e.Text, e.LineNumber, e.ColumnNumber) + if obj := e.Exception; obj != nil { + fmt.Fprintf(&b, ": %s", obj.Description) + } + return b.String() +} + +// LoadError is the error for a page that did not load. Navigate and +// RunResponse return it when the browser reports an error for the request of +// the page, for example when the host name does not exist. Use [errors.As] to +// read the text of the browser, or [errors.Is] with [ErrPageLoad] to test for +// any load error. +type LoadError struct { + // ErrorText is the error text of the browser, such as + // "net::ERR_NAME_NOT_RESOLVED". Chromium lists these texts in + // net/base/net_error_list.h. + ErrorText string +} + +// Error satisfies the error interface. The text is the same as in earlier +// versions. +func (e *LoadError) Error() string { + return "page load error " + e.ErrorText +} + +// Unwrap returns ErrPageLoad, so that errors.Is finds it. +func (e *LoadError) Unwrap() error { + return ErrPageLoad +} + // Error is a chromedp error. type Error string @@ -10,8 +61,9 @@ func (err Error) Error() string { // Error types. const ( - // ErrInvalidWebsocketMessage is the invalid websocket message. - ErrInvalidWebsocketMessage Error = "invalid websocket message" + // ErrNoDialer is the error of an ExecAllocator that needs a websocket and + // has no dialer. See [WithDialer]. + ErrNoDialer Error = "the allocator needs a websocket, so it needs a dialer: add remote.WebSocket from the package github.com/chromedp/chromedp/remote to its options" // ErrInvalidDimensions is the invalid dimensions error. ErrInvalidDimensions Error = "invalid dimensions" @@ -43,10 +95,17 @@ const ( // ErrInvalidTarget is the invalid target error. ErrInvalidTarget Error = "invalid target" + // ErrPageLoad is the error that every [LoadError] wraps. + ErrPageLoad Error = "page load error" + + // ErrNoDisplay is the error when a visible window is requested on Linux + // and the environment has no display. + ErrNoDisplay Error = "a visible window needs a display, but DISPLAY and WAYLAND_DISPLAY are not set: start a display, or unset CHROMEDP_VISIBLEWINDOW and remove WithVisibleWindow and VisibleWindow to run headless" + // ErrInvalidContext is the invalid context error. ErrInvalidContext Error = "invalid context" - // ErrPollingTimeout is the error that the timeout reached before the pageFunction returns a truthy value. + // ErrPollingTimeout is the error when the timeout ends before the pageFunction returns a truthy value. ErrPollingTimeout Error = "waiting for function failed: timeout" // ErrJSUndefined is the error that the type of RemoteObject is "undefined". diff --git a/vendor/github.com/chromedp/chromedp/eval.go b/vendor/github.com/chromedp/chromedp/eval.go index 830875c24..01535bc2b 100644 --- a/vendor/github.com/chromedp/chromedp/eval.go +++ b/vendor/github.com/chromedp/chromedp/eval.go @@ -1,145 +1,168 @@ package chromedp import ( + "bytes" "context" "encoding/json" "reflect" + "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/runtime" ) -// EvaluateAction are actions that evaluate JavaScript expressions using -// runtime.Evaluate. -type EvaluateAction Action - -// Evaluate is an action to evaluate the JavaScript expression, unmarshaling -// the result of the script evaluation to res. +// Evaluate is an action that evaluates the JavaScript expression and decodes +// the result of the script into the type T. +// +// When T is [Void], Evaluate ignores the script result. // -// When res is nil, the script result will be ignored. +// When T is []byte, the result is the raw JSON-encoded value of the script +// result. // -// When res is a *[]byte, the raw JSON-encoded value of the script -// result will be placed in res. +// When T is *runtime.RemoteObject, the result is the low-level protocol type, +// and Evaluate does not convert it. The original objects can stay in memory +// until the page navigates or closes. Use `runtime.ReleaseObject` or +// `runtime.ReleaseObjectGroup` to ask the browser to release them. // -// When res is a **runtime.RemoteObject, res will be set to the low-level -// protocol type, and no attempt will be made to convert the result. -// The original objects could be maintained in memory until the page is -// navigated or closed. `runtime.ReleaseObject` or `runtime.ReleaseObjectGroup` -// can be used to ask the browser to release the original objects. +// For all other types, the script returns the result "by value" (that is, +// JSON-encoded). Evaluate then decodes it into a value of type T. Only a chan, +// func, interface, map, pointer, or slice type can be nil. When the script +// result is "undefined" or "null" and T cannot be nil, the action returns +// [ErrJSUndefined] or [ErrJSNull] respectively. The expression `null` gives +// [ErrJSNull] for an int, and a nil pointer for a *int. The expression +// `Promise.resolve(1)` needs the option [EvalAwaitPromise]. // -// For all other cases, the result of the script will be returned "by value" (i.e., -// JSON-encoded), and subsequently an attempt will be made to json.Unmarshal -// the script result to res. When the script result is "undefined" or "null", -// and the value that res points to can not be nil (only the value of a chan, -// func, interface, map, pointer, or slice can be nil), it returns [ErrJSUndefined] -// or [ErrJSNull] respectively. -func Evaluate(expression string, res any, opts ...EvaluateOption) EvaluateAction { - return ActionFunc(func(ctx context.Context) error { +// For example: +// +// n, err := chromedp.Run(ctx, chromedp.Evaluate[int](`1 + 2`)) +func Evaluate[T any](expression string, opts ...EvaluateOption) Action[T] { + return func(ctx context.Context, t *Target) (T, error) { + var zero T + // set up parameters - p := runtime.Evaluate(expression) - switch res.(type) { - case **runtime.RemoteObject: - default: - p = p.WithReturnByValue(true) + p := &runtime.EvaluateParams{Expression: expression} + if !wantsRemoteObject[T]() { + p.ReturnByValue = ptr(true) } // apply opts for _, o := range opts { - p = o(p) + o(p) } // evaluate - v, exp, err := p.Do(ctx) + r, err := cdp.Call(ctx, t, runtime.Evaluate, *p) if err != nil { - return err + return zero, err } - if exp != nil { - return exp + if r.ExceptionDetails != nil { + return zero, &ExceptionError{r.ExceptionDetails} } - return parseRemoteObject(v, res) - }) + return parseRemoteObject[T](r.Result) + } } -func parseRemoteObject(v *runtime.RemoteObject, res any) (err error) { - if res == nil { - return - } +// wantsRemoteObject reports whether the type T is *runtime.RemoteObject. +func wantsRemoteObject[T any]() bool { + var v T + _, ok := any(&v).(**runtime.RemoteObject) + return ok +} + +// parseRemoteObject decodes the remote object into a value of the type T. +func parseRemoteObject[T any](v *runtime.RemoteObject) (T, error) { + var res T + switch x := any(&res).(type) { + case *Void: + return res, nil - switch x := res.(type) { case **runtime.RemoteObject: *x = v - return + return res, nil case *[]byte: *x = v.Value - return + return res, nil } value := v.Value - if value == nil { - rv := reflect.ValueOf(res) - if rv.Kind() == reflect.Pointer { - switch rv.Elem().Kind() { - // Common kinds that can be nil. - case reflect.Pointer, reflect.Map, reflect.Slice: - // It's weird that res is a pointer to the following kinds, - // but they can be nil too. - case reflect.Chan, reflect.Func, reflect.Interface: - default: - // When the value that `res` points to can not be set to nil, - // return [ErrJSUndefined] or [ErrJSNull] respectively. - if v.Type == "undefined" { - return ErrJSUndefined - } - return ErrJSNull + if value == nil || isJSONNull(value) { + switch reflect.TypeFor[T]().Kind() { + // Common kinds that can be nil. + case reflect.Pointer, reflect.Map, reflect.Slice: + // These kinds are unusual for T, but they can be nil too. + case reflect.Chan, reflect.Func, reflect.Interface: + default: + // When the value of the type T cannot be nil, return + // [ErrJSUndefined] or [ErrJSNull] respectively. + if v.Type == "undefined" { + return res, ErrJSUndefined } + return res, ErrJSNull } - // Change the value to the json literal null to make json.Unmarshal happy. + // Change the value to the JSON literal null, so that json.Unmarshal accepts it. value = []byte("null") } - return json.Unmarshal(value, res) + err := json.Unmarshal(value, &res) + return res, err +} + +// isJSONNull reports whether value is the JSON literal null. +func isJSONNull(value []byte) bool { + return string(bytes.TrimSpace(value)) == "null" } // EvaluateAsDevTools is an action that evaluates a JavaScript expression as -// Chrome DevTools would, evaluating the expression in the "console" context, -// and making the Command Line API available to the script. +// Chrome DevTools does. It evaluates the expression in the "console" context +// and makes the Command Line API available to the script. // -// See [Evaluate] for more information on how script expressions are evaluated. +// See [Evaluate] for how the expressions are evaluated. // -// Note: this should not be used with untrusted JavaScript. -func EvaluateAsDevTools(expression string, res any, opts ...EvaluateOption) EvaluateAction { - return Evaluate(expression, res, append(opts, EvalObjectGroup("console"), EvalWithCommandLineAPI)...) +// Note: do not use this with untrusted JavaScript. +func EvaluateAsDevTools[T any](expression string, opts ...EvaluateOption) Action[T] { + return Evaluate[T](expression, append(opts[:len(opts):len(opts)], EvalObjectGroup("console"), EvalWithCommandLineAPI)...) } // EvaluateOption is the type for JavaScript evaluation options. -type EvaluateOption = func(*runtime.EvaluateParams) *runtime.EvaluateParams +type EvaluateOption = func(*runtime.EvaluateParams) // EvalObjectGroup is an evaluate option to set the object group. func EvalObjectGroup(objectGroup string) EvaluateOption { - return func(p *runtime.EvaluateParams) *runtime.EvaluateParams { - return p.WithObjectGroup(objectGroup) + return func(p *runtime.EvaluateParams) { + p.ObjectGroup = objectGroup } } -// EvalWithCommandLineAPI is an evaluate option to make the DevTools Command +// EvalWithCommandLineAPI is an evaluate option that makes the DevTools Command // Line API available to the evaluated script. // -// See [Evaluate] for more information on how evaluate actions work. +// See [Evaluate] for how evaluate actions work. // -// Note: this should not be used with untrusted JavaScript. -func EvalWithCommandLineAPI(p *runtime.EvaluateParams) *runtime.EvaluateParams { - return p.WithIncludeCommandLineAPI(true) +// Note: do not use this with untrusted JavaScript. +func EvalWithCommandLineAPI(p *runtime.EvaluateParams) { + p.IncludeCommandLineAPI = ptr(true) } -// EvalIgnoreExceptions is an evaluate option that will cause JavaScript -// evaluation to ignore exceptions. -func EvalIgnoreExceptions(p *runtime.EvaluateParams) *runtime.EvaluateParams { - return p.WithSilent(true) +// EvalIgnoreExceptions is an evaluate option that makes the evaluation ignore +// exceptions. +func EvalIgnoreExceptions(p *runtime.EvaluateParams) { + p.Silent = ptr(true) +} + +// EvalAwaitPromise is an evaluate option that makes the evaluation wait for a +// promise that the expression returns, and use its result. A promise that is +// rejected makes the action return an [*ExceptionError]. Without the option, +// the result of an expression that returns a promise is the promise object, and +// not its value. +// +// v, err := chromedp.Run(ctx, chromedp.Evaluate[string](`fetch("/api").then(r => r.text())`, chromedp.EvalAwaitPromise)) +func EvalAwaitPromise(p *runtime.EvaluateParams) { + p.AwaitPromise = ptr(true) } -// EvalAsValue is an evaluate option that will cause the evaluated JavaScript -// expression to encode the result of the expression as a JSON-encoded value. -func EvalAsValue(p *runtime.EvaluateParams) *runtime.EvaluateParams { - return p.WithReturnByValue(true) +// EvalAsValue is an evaluate option that makes the evaluation encode the +// result of the expression as a JSON-encoded value. +func EvalAsValue(p *runtime.EvaluateParams) { + p.ReturnByValue = ptr(true) } diff --git a/vendor/github.com/chromedp/chromedp/expose.go b/vendor/github.com/chromedp/chromedp/expose.go new file mode 100644 index 000000000..3dfe79e20 --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/expose.go @@ -0,0 +1,254 @@ +package chromedp + +import ( + "context" + "errors" + "fmt" + "reflect" + "strconv" + "strings" + "time" + + "github.com/chromedp/cdproto/cdp" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" + "github.com/chromedp/cdproto/page" + "github.com/chromedp/cdproto/runtime" +) + +// exposePrefix is the start of the name of each binding that ExposeFunc adds. +// The name of an exposed func cannot start with it. +const exposePrefix = "__chromedp_" + +// ExposeFunc is an action that makes the Go func fn available to the page as +// window.<name>. A page script calls it like an async function. The call +// returns a promise that the browser settles with the result of fn, or rejects +// with an Error when fn returns an error. It is like exposeFunction in +// Puppeteer. +// +// The function is there in the current document and in every document that the +// target loads later, for the main frame and for every iframe of the same +// site, so it survives a navigation. An iframe of another site runs in another +// process and is another target, so the function is not there. It stays until +// the target ends. The listener for the calls +// stops when the context of the target ends. A second call of ExposeFunc with +// the same name on the same target returns an error. So does a name that is +// empty, that is not valid UTF-8, or that starts with "__chromedp_", the prefix +// of the private names of the package. +// +// A script passes its arguments as JSON, so a value such as a function or a +// DOM node does not work. How the arguments reach fn depends on the type A: +// +// - When A is a slice type, such as []any or []float64, fn gets all the +// arguments of the call in the slice. Use it for a call with several +// arguments, or with none. +// - For every other A, the call must have one argument, and the action +// decodes it into A. Use a struct for an object, or a basic type. A call +// with no argument gives the zero value of A, and a call with more than one +// argument is an error that rejects the promise. +// +// The action encodes the result of fn as JSON for the page. When R is [Void], +// the promise resolves with undefined. +// +// The action runs fn in a new goroutine for each call, so fn can run several +// times at the same time and must be safe for that. The ctx of fn has the +// values of the context that ExposeFunc received, and it ends when the target +// ends. If fn panics, the promise rejects with an Error whose message is "panic:" +// and the panic value, for example "panic: boom". The message of an error that +// fn returns replaces each byte that is not valid UTF-8 with U+FFFD. +// +// For example, a page that calls window.square(7): +// +// err := chromedp.Do(ctx, +// chromedp.ExposeFunc("square", func(ctx context.Context, n float64) (float64, error) { +// return n * n, nil +// }), +// chromedp.Navigate(url), +// ) +func ExposeFunc[A, R any](name string, fn func(ctx context.Context, arg A) (R, error)) Action[Void] { + return Func(func(ctx context.Context, t *Target) (err error) { + if name == "" { + return errors.New("exposing a func: the name is empty") + } + if strings.HasPrefix(name, exposePrefix) { + return fmt.Errorf("exposing func %q: the name starts with %q", name, exposePrefix) + } + jsName, err := jsonv2.Marshal(name) + if err != nil { + return fmt.Errorf("exposing func %q: the name is not valid: %w", name, err) + } + t.exposedMu.Lock() + if _, ok := t.exposed[name]; ok { + t.exposedMu.Unlock() + return fmt.Errorf("exposing func %q: the name is in use already", name) + } + if t.exposed == nil { + t.exposed = make(map[string]struct{}) + } + t.exposed[name] = struct{}{} + t.exposedSeq++ + // The binding has a number and not the name, so that no two names make + // the same binding or the same reply func. + binding := exposePrefix + strconv.Itoa(t.exposedSeq) + t.exposedMu.Unlock() + defer func() { + if err != nil { + t.exposedMu.Lock() + delete(t.exposed, name) + t.exposedMu.Unlock() + } + }() + + // The page script calls a private binding. The wrapper script defines + // window[name] on top of it. + jsBinding, err := jsonv2.Marshal(binding) + if err != nil { + return fmt.Errorf("exposing func %q: %w", name, err) + } + script := "(" + exposeFuncJS + ")(" + string(jsName) + "," + string(jsBinding) + ")" + + // Subscribe first, so that no call is lost. + lctx, stop := context.WithCancel(context.WithoutCancel(ctx)) + calls, unsubscribe := t.Subscribe(runtime.BindingCalled.Method) + var undo []func(context.Context) + defer func() { + if err != nil { + unsubscribe() + stop() + // Take back the binding and the script, so that a retry starts + // clean. The context of the call can be the reason for the + // failure, so the cleanup has its own context. + cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + for i := len(undo) - 1; i >= 0; i-- { + undo[i](cctx) + } + } + }() + + if _, err := cdp.Call(ctx, t, runtime.AddBinding, runtime.AddBindingParams{Name: binding}); err != nil { + return fmt.Errorf("exposing func %q: %w", name, err) + } + undo = append(undo, func(ctx context.Context) { + _, _ = cdp.Call(ctx, t, runtime.RemoveBinding, runtime.RemoveBindingParams{Name: binding}) + }) + if !t.isWorker { + // Run the script in each new document. Where the browser knows + // the flag, it runs the script in the open documents, such as an + // iframe that is there already. + added, err := cdp.Call(ctx, t, page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{ + Source: script, + RunImmediately: ptr(true), + }) + if err != nil { + return fmt.Errorf("exposing func %q: %w", name, err) + } + undo = append(undo, func(ctx context.Context) { + _, _ = cdp.Call(ctx, t, page.RemoveScriptToEvaluateOnNewDocument, page.RemoveScriptToEvaluateOnNewDocumentParams{Identifier: added.Identifier}) + }) + } + // The main document is open already. The script does nothing the second + // time that it runs in a document. + res, err := cdp.Call(ctx, t, runtime.Evaluate, runtime.EvaluateParams{Expression: script}) + if err != nil { + return fmt.Errorf("exposing func %q: %w", name, err) + } + if res.ExceptionDetails != nil { + return fmt.Errorf("exposing func %q: %w", name, &ExceptionError{res.ExceptionDetails}) + } + + go func() { + // The channel closes when the target ends. + defer unsubscribe() + defer stop() + for raw := range calls { + var ev runtime.EventBindingCalled + if err := jsonv2.Unmarshal(raw, &ev, DefaultUnmarshalOptions); err != nil || ev.Name != binding { + continue + } + go exposedCall(lctx, t, binding, &ev, fn) + } + }() + return nil + }) +} + +// exposedCall runs one call of an exposed func, and sends the result back to +// the context of the page that made the call. +func exposedCall[A, R any](ctx context.Context, t *Target, binding string, ev *runtime.EventBindingCalled, fn func(context.Context, A) (R, error)) { + var call struct { + ID int64 `json:"id"` + Args []jsonv2.Value `json:"args"` + } + if err := jsonv2.Unmarshal([]byte(ev.Payload), &call, DefaultUnmarshalOptions); err != nil { + // Without the id the promise cannot settle, and the payload did not come + // from the wrapper. + return + } + + res, err := func() (res R, err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("panic: %v", r) + } + }() + arg, err := exposedArg[A](call.Args) + if err != nil { + return res, err + } + return fn(ctx, arg) + }() + + ok, value := "true", "undefined" + if err != nil { + ok = "false" + b, merr := jsonv2.Marshal(strings.ToValidUTF8(err.Error(), "\uFFFD")) + if merr != nil { + b = []byte(`"the error message is not valid"`) + } + value = string(b) + } else if reflect.TypeFor[R]() != reflect.TypeFor[Void]() { + b, merr := jsonv2.Marshal(res, DefaultMarshalOptions) + if merr != nil { + ok = "false" + b, _ = jsonv2.Marshal(fmt.Sprintf("encoding the result: %v", merr)) + } + value = string(b) + } + reply, merr := jsonv2.Marshal(binding + "_reply") + if merr != nil { + return + } + expr := "window[" + string(reply) + "](" + strconv.FormatInt(call.ID, 10) + "," + ok + "," + value + ")" + // The page can be gone, for example after a navigation. Then nobody waits + // for the result, and the error does not matter. + _, _ = cdp.Call(ctx, t, runtime.Evaluate, runtime.EvaluateParams{ + Expression: expr, + ContextID: ev.ExecutionContextID, + Silent: ptr(true), + }) +} + +// exposedArg decodes the arguments of a call into the type A. +func exposedArg[A any](args []jsonv2.Value) (A, error) { + var arg A + if reflect.TypeFor[A]().Kind() == reflect.Slice { + b, err := jsonv2.Marshal(args) + if err != nil { + return arg, err + } + if err := jsonv2.Unmarshal(b, &arg, DefaultUnmarshalOptions); err != nil { + return arg, fmt.Errorf("decoding the arguments: %w", err) + } + return arg, nil + } + switch len(args) { + case 0: + return arg, nil + case 1: + if err := jsonv2.Unmarshal(args[0], &arg, DefaultUnmarshalOptions); err != nil { + return arg, fmt.Errorf("decoding the argument: %w", err) + } + return arg, nil + } + return arg, fmt.Errorf("expected one argument, got %d", len(args)) +} diff --git a/vendor/github.com/chromedp/chromedp/frame.go b/vendor/github.com/chromedp/chromedp/frame.go new file mode 100644 index 000000000..22a5a6f4b --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/frame.go @@ -0,0 +1,63 @@ +package chromedp + +import ( + "strings" + "sync" + + "github.com/chromedp/cdproto/cdp" +) + +// Frame is a frame of a page. It embeds the protocol frame and adds the node +// tree of the frame and the state that chromedp keeps up to date from the +// browser events. +// +// Hold the lock of a Frame before you read a field that chromedp updates. +type Frame struct { + *cdp.Frame + + // State is the state of the frame. + State FrameState + // Root is the document root of the frame. + Root *Node + // Nodes holds the nodes of the frame by node id. + Nodes map[cdp.NodeID]*Node + + sync.RWMutex +} + +// FrameState is the state of a Frame. +type FrameState uint16 + +// FrameState enum values. +const ( + FrameDOMContentEventFired FrameState = 1 << (15 - iota) + FrameLoadEventFired + FrameAttached + FrameNavigated + FrameLoading + FrameScheduledNavigation +) + +// frameStateNames are the names of the frame states. +var frameStateNames = map[FrameState]string{ + FrameDOMContentEventFired: "DOMContentEventFired", + FrameLoadEventFired: "LoadEventFired", + FrameAttached: "Attached", + FrameNavigated: "Navigated", + FrameLoading: "Loading", + FrameScheduledNavigation: "ScheduledNavigation", +} + +// String satisfies stringer interface. +func (fs FrameState) String() string { + var s []string + for k, v := range frameStateNames { + if fs&k != 0 { + s = append(s, v) + } + } + return "[" + strings.Join(s, " ") + "]" +} + +// EmptyFrameID is the "non-existent" frame id. +const EmptyFrameID = cdp.FrameID("") diff --git a/vendor/github.com/chromedp/chromedp/input.go b/vendor/github.com/chromedp/chromedp/input.go index 82c14e408..3243e6cac 100644 --- a/vendor/github.com/chromedp/chromedp/input.go +++ b/vendor/github.com/chromedp/chromedp/input.go @@ -9,92 +9,151 @@ import ( "github.com/chromedp/chromedp/kb" ) -// MouseAction are mouse input event actions -type MouseAction Action +// Mouse event types for MouseEvent. +const ( + MousePressed = input.DispatchMouseEventTypeMousePressed + MouseReleased = input.DispatchMouseEventTypeMouseReleased + MouseMoved = input.DispatchMouseEventTypeMouseMoved + MouseWheel = input.DispatchMouseEventTypeMouseWheel +) + +// Modifier is a bit field of pressed modifier keys. +type Modifier = kb.Modifier + +// Modifier values. +const ( + ModifierNone = kb.ModifierNone + ModifierAlt = kb.ModifierAlt + ModifierCtrl = kb.ModifierCtrl + ModifierMeta = kb.ModifierMeta + ModifierShift = kb.ModifierShift + ModifierCommand = kb.ModifierCommand +) // MouseEvent is a mouse event action to dispatch the specified mouse event // type at coordinates x, y. -func MouseEvent(typ input.MouseType, x, y float64, opts ...MouseOption) MouseAction { - p := input.DispatchMouseEvent(typ, x, y) - // apply opts - for _, o := range opts { - p = o(p) - } - return p +func MouseEvent(typ input.DispatchMouseEventType, x, y float64, opts ...MouseOption) Action[Void] { + return Func(func(ctx context.Context, t *Target) error { + p := &input.DispatchMouseEventParams{Type: typ, X: x, Y: y} + // apply opts + for _, o := range opts { + o(p) + } + _, err := cdp.Call(ctx, t, input.DispatchMouseEvent, *p) + return err + }) } -// MouseClickXY is an action that sends a left mouse button click (i.e., -// mousePressed and mouseReleased event) to the X, Y location. -func MouseClickXY(x, y float64, opts ...MouseOption) MouseAction { - return ActionFunc(func(ctx context.Context) error { +// MouseClickXY is an action that sends a left mouse button click (that is, a +// mousePressed and a mouseReleased event) to the X, Y location. +func MouseClickXY(x, y float64, opts ...MouseOption) Action[Void] { + return Func(func(ctx context.Context, t *Target) error { p := &input.DispatchMouseEventParams{ - Type: input.MousePressed, + Type: MousePressed, X: x, Y: y, - Button: input.Left, + Button: input.MouseButtonLeft, ClickCount: 1, } // apply opts for _, o := range opts { - p = o(p) + o(p) } - if err := p.Do(ctx); err != nil { + if _, err := cdp.Call(ctx, t, input.DispatchMouseEvent, *p); err != nil { return err } - p.Type = input.MouseReleased - return p.Do(ctx) + p.Type = MouseReleased + _, err := cdp.Call(ctx, t, input.DispatchMouseEvent, *p) + return err }) } -// MouseClickNode is an action that dispatches a mouse left button click event -// at the center of a specified node. +// MouseClickNode is an action that dispatches a left mouse button click event +// at the center of a node. // -// Note that the window will be scrolled if the node is not within the window's -// viewport. -func MouseClickNode(n *cdp.Node, opts ...MouseOption) MouseAction { - return ActionFunc(func(ctx context.Context) error { - t := cdp.ExecutorFromContext(ctx).(*Target) - if t == nil { - return ErrInvalidTarget - } - - if err := dom.ScrollIntoViewIfNeeded().WithNodeID(n.NodeID).Do(ctx); err != nil { - return err - } - - boxes, err := dom.GetContentQuads().WithNodeID(n.NodeID).Do(ctx) +// Note: the action scrolls the window if the node is not within the viewport +// of the window. +func MouseClickNode(n *Node, opts ...MouseOption) Action[Void] { + return Func(func(ctx context.Context, t *Target) error { + x, y, err := nodeCenter(ctx, t, n) if err != nil { return err } - if len(boxes) == 0 { - return ErrInvalidDimensions - } + _, err = MouseClickXY(x, y, opts...)(ctx, t) + return err + }) +} - content := boxes[0] +// nodeCenter scrolls the node into view and returns the center of its first +// content quad. +func nodeCenter(ctx context.Context, t *Target, n *Node) (x, y float64, err error) { + if _, err := cdp.Call(ctx, t, dom.ScrollIntoViewIfNeeded, dom.ScrollIntoViewIfNeededParams{NodeID: n.NodeID}); err != nil { + return 0, 0, err + } + return quadCenter(ctx, t, n) +} - c := len(content) - if c%2 != 0 || c < 1 { - return ErrInvalidDimensions - } +// quadCenter returns the center of the node in the viewport, as it is now. It +// does not scroll. +func quadCenter(ctx context.Context, t *Target, n *Node) (x, y float64, err error) { + res, err := cdp.Call(ctx, t, dom.GetContentQuads, dom.GetContentQuadsParams{NodeID: n.NodeID}) + if err != nil { + return 0, 0, err + } + + if len(res.Quads) == 0 { + return 0, 0, ErrInvalidDimensions + } + + content := res.Quads[0] + + c := len(content) + if c%2 != 0 || c < 1 { + return 0, 0, ErrInvalidDimensions + } - var x, y float64 - for i := 0; i < c; i += 2 { - x += content[i] - y += content[i+1] + for i := 0; i < c; i += 2 { + x += content[i] + y += content[i+1] + } + return x / float64(c/2), y / float64(c/2), nil +} + +// TapXY is an action that sends a touch tap to the X, Y location. It sends a +// touchStart event and then a touchEnd event with one touch point. The browser +// turns the touch into a click event, if the page runs with touch emulation. +// See [EmulateTouch]. +func TapXY(x, y float64) Action[Void] { + return Func(func(ctx context.Context, t *Target) error { + p := input.DispatchTouchEventParams{ + Type: input.DispatchTouchEventTypeTouchStart, + TouchPoints: []*input.TouchPoint{{ + X: x, + Y: y, + RadiusX: ptr(1.0), + RadiusY: ptr(1.0), + Force: ptr(1.0), + ID: ptr(0.0), + }}, + } + if _, err := cdp.Call(ctx, t, input.DispatchTouchEvent, p); err != nil { + return err } - x /= float64(c / 2) - y /= float64(c / 2) - return MouseClickXY(x, y, opts...).Do(ctx) + // A touchEnd event has no touch points. + p.Type = input.DispatchTouchEventTypeTouchEnd + p.TouchPoints = []*input.TouchPoint{} + _, err := cdp.Call(ctx, t, input.DispatchTouchEvent, p) + return err }) } // MouseOption is a mouse action option. -type MouseOption = func(*input.DispatchMouseEventParams) *input.DispatchMouseEventParams +type MouseOption = func(*input.DispatchMouseEventParams) // Button is a mouse action option to set the button to click from a string. func Button(btn string) MouseOption { @@ -103,74 +162,76 @@ func Button(btn string) MouseOption { // ButtonType is a mouse action option to set the button to click. func ButtonType(button input.MouseButton) MouseOption { - return func(p *input.DispatchMouseEventParams) *input.DispatchMouseEventParams { - return p.WithButton(button) + return func(p *input.DispatchMouseEventParams) { + p.Button = button } } // ButtonLeft is a mouse action option to set the button clicked as the left // mouse button. -func ButtonLeft(p *input.DispatchMouseEventParams) *input.DispatchMouseEventParams { - return p.WithButton(input.Left) +func ButtonLeft(p *input.DispatchMouseEventParams) { + p.Button = input.MouseButtonLeft } // ButtonMiddle is a mouse action option to set the button clicked as the middle // mouse button. -func ButtonMiddle(p *input.DispatchMouseEventParams) *input.DispatchMouseEventParams { - return p.WithButton(input.Middle) +func ButtonMiddle(p *input.DispatchMouseEventParams) { + p.Button = input.MouseButtonMiddle } // ButtonRight is a mouse action option to set the button clicked as the right // mouse button. -func ButtonRight(p *input.DispatchMouseEventParams) *input.DispatchMouseEventParams { - return p.WithButton(input.Right) +func ButtonRight(p *input.DispatchMouseEventParams) { + p.Button = input.MouseButtonRight } // ButtonNone is a mouse action option to set the button clicked as none (used // for mouse movements). -func ButtonNone(p *input.DispatchMouseEventParams) *input.DispatchMouseEventParams { - return p.WithButton(input.None) +func ButtonNone(p *input.DispatchMouseEventParams) { + p.Button = input.MouseButtonNone } -// ButtonModifiers is a mouse action option to add additional input modifiers -// for a button click. -func ButtonModifiers(modifiers ...input.Modifier) MouseOption { - return func(p *input.DispatchMouseEventParams) *input.DispatchMouseEventParams { +// ButtonModifiers is a mouse action option to add input modifiers for a button +// click. +func ButtonModifiers(modifiers ...Modifier) MouseOption { + return func(p *input.DispatchMouseEventParams) { for _, m := range modifiers { - p.Modifiers |= m + p.Modifiers |= int64(m) } - return p } } // ClickCount is a mouse action option to set the click count. func ClickCount(n int) MouseOption { - return func(p *input.DispatchMouseEventParams) *input.DispatchMouseEventParams { - return p.WithClickCount(int64(n)) + return func(p *input.DispatchMouseEventParams) { + p.ClickCount = int64(n) } } -// KeyAction are keyboard (key) input event actions. -type KeyAction Action - // KeyEvent is a key action that synthesizes a keyDown, char, and keyUp event -// for each rune contained in keys along with any supplied key options. +// for each rune in keys, with any key options. // -// Only well-known, "printable" characters will have char events synthesized. +// Only well-known, "printable" characters get char events. A key with the +// modifier Ctrl, Alt or Meta gets no char event, because the char event types +// the character on top of the shortcut. For example, Ctrl+A selects the +// text and types no "a". A key with the modifier Shift keeps its char event. // // See the [SendKeys] action to synthesize key events for a specific element // node. // -// See the [kb] package for implementation details and list of -// well-known keys. -func KeyEvent(keys string, opts ...KeyOption) KeyAction { - return ActionFunc(func(ctx context.Context) error { +// See the [kb] package for implementation details and a list of well-known +// keys. +func KeyEvent(keys string, opts ...KeyOption) Action[Void] { + return Func(func(ctx context.Context, t *Target) error { for _, r := range keys { for _, k := range kb.Encode(r) { for _, o := range opts { o(k) } - if err := k.Do(ctx); err != nil { + if k.Type == kb.KeyChar && k.Modifiers&^int64(ModifierShift) != 0 { + continue + } + if _, err := cdp.Call(ctx, t, input.DispatchKeyEvent, *k); err != nil { return err } } @@ -181,27 +242,25 @@ func KeyEvent(keys string, opts ...KeyOption) KeyAction { } // KeyEventNode is a key action that dispatches a key event on an element node. -func KeyEventNode(n *cdp.Node, keys string, opts ...KeyOption) KeyAction { - return ActionFunc(func(ctx context.Context) error { - err := dom.Focus().WithNodeID(n.NodeID).Do(ctx) - if err != nil { +func KeyEventNode(n *Node, keys string, opts ...KeyOption) Action[Void] { + return Func(func(ctx context.Context, t *Target) error { + if _, err := cdp.Call(ctx, t, dom.Focus, dom.FocusParams{NodeID: n.NodeID}); err != nil { return err } - return KeyEvent(keys, opts...).Do(ctx) + _, err := KeyEvent(keys, opts...)(ctx, t) + return err }) } // KeyOption is a key action option. -type KeyOption = func(*input.DispatchKeyEventParams) *input.DispatchKeyEventParams +type KeyOption = func(*input.DispatchKeyEventParams) -// KeyModifiers is a key action option to add additional modifiers on the key -// press. -func KeyModifiers(modifiers ...input.Modifier) KeyOption { - return func(p *input.DispatchKeyEventParams) *input.DispatchKeyEventParams { +// KeyModifiers is a key action option to add modifiers to the key press. +func KeyModifiers(modifiers ...Modifier) KeyOption { + return func(p *input.DispatchKeyEventParams) { for _, m := range modifiers { - p.Modifiers |= m + p.Modifiers |= int64(m) } - return p } } diff --git a/vendor/github.com/chromedp/chromedp/js.go b/vendor/github.com/chromedp/chromedp/js.go index e93cc26bc..98c0d1bf7 100644 --- a/vendor/github.com/chromedp/chromedp/js.go +++ b/vendor/github.com/chromedp/chromedp/js.go @@ -6,7 +6,7 @@ import ( var ( // textJS is a JavaScript snippet that returns the innerText of the specified - // visible (i.e., offsetWidth || offsetHeight || getClientRects().length ) element. + // visible (that is, offsetWidth || offsetHeight || getClientRects().length ) element. //go:embed js/text.js textJS string @@ -19,13 +19,13 @@ var ( //go:embed js/blur.js blurJS string - // submitJS is a JavaScript snippet that will call the containing form's - // submit function, returning true or false if the call was successful. + // submitJS is a JavaScript snippet that calls the submit function of the + // form that contains the element. It returns true if the call succeeded. //go:embed js/submit.js submitJS string - // resetJS is a JavaScript snippet that will call the containing form's - // reset function, returning true or false if the call was successful. + // resetJS is a JavaScript snippet that calls the reset function of the form + // that contains the element. It returns true if the call succeeded. //go:embed js/reset.js resetJS string @@ -39,9 +39,9 @@ var ( //go:embed js/setAttribute.js setAttributeJS string - // visibleJS is a JavaScript snippet that returns true or false depending on if - // the specified node's offsetWidth, offsetHeight or getClientRects().length is - // not null. + // visibleJS is a JavaScript snippet that returns true when the offsetWidth, + // the offsetHeight, or getClientRects().length of the node is not null, and + // false otherwise. //go:embed js/visible.js visibleJS string @@ -50,10 +50,16 @@ var ( //go:embed js/getClientRect.js getClientRectJS string - // waitForPredicatePageFunction is a JavaScript snippet that runs the polling in the - // browser. It's copied from puppeteer. See + // exposeFuncJS is a JavaScript function that defines window[name]. A call + // of that function sends its arguments to the binding and returns a + // promise. The Go side settles the promise with window[binding + "_reply"]. + //go:embed js/exposeFunc.js + exposeFuncJS string + + // waitForPredicatePageFunction is a JavaScript snippet that runs the + // polling in the browser. It is copied from puppeteer. See // https://github.com/puppeteer/puppeteer/blob/669f04a7a6e96cc8353a8cb152898edbc25e7c15/src/common/DOMWorld.ts#L870-L944 - // It's modified to make mutation polling respect timeout even when there is not a DOM mutation. + // It is modified so that mutation polling respects the timeout even when the DOM does not mutate. //go:embed js/waitForPredicatePageFunction.js waitForPredicatePageFunction string ) diff --git a/vendor/github.com/chromedp/chromedp/js/exposeFunc.js b/vendor/github.com/chromedp/chromedp/js/exposeFunc.js new file mode 100644 index 000000000..4c3108304 --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/js/exposeFunc.js @@ -0,0 +1,46 @@ +function exposeFunc(name, binding) { + var reply = binding + '_reply'; + var send = window[binding]; + if (Object.prototype.hasOwnProperty.call(window, reply) || typeof send !== 'function') { + return; + } + var pending = new Map(); + var last = 0; + var fn = function () { + var args = Array.prototype.slice.call(arguments); + return new Promise(function (resolve, reject) { + var id = ++last; + pending.set(id, {resolve: resolve, reject: reject}); + try { + send(JSON.stringify({id: id, args: args})); + } catch (e) { + pending.delete(id); + reject(e); + } + }); + }; + // Define the property, and do not assign it, so that a name such as + // __proto__ or a name with a setter on window does not act on the page. + // The reply func comes last. It marks the script as done, so a script that + // fails here runs again, and the error reaches ExposeFunc. + Object.defineProperty(window, name, { + value: fn, + writable: true, + configurable: true, + enumerable: true, + }); + Object.defineProperty(window, reply, { + value: function (id, ok, value) { + var call = pending.get(id); + if (!call) { + return; + } + pending.delete(id); + if (ok) { + call.resolve(value); + } else { + call.reject(new Error(value)); + } + }, + }); +} diff --git a/vendor/github.com/chromedp/chromedp/js/text.js b/vendor/github.com/chromedp/chromedp/js/text.js index 6a6ada96c..7a8c8ea17 100644 --- a/vendor/github.com/chromedp/chromedp/js/text.js +++ b/vendor/github.com/chromedp/chromedp/js/text.js @@ -1,6 +1,9 @@ function text() { - if (this.offsetWidth || this.offsetHeight || this.getClientRects().length) { - return this.innerText; + // A text node has no layout of its own and no innerText, so use the + // element that holds it. + const el = this.nodeType === 1 ? this : this.parentElement; + if (el && (el.offsetWidth || el.offsetHeight || el.getClientRects().length)) { + return this.nodeType === 1 ? this.innerText : this.nodeValue; } return ''; } diff --git a/vendor/github.com/chromedp/chromedp/kb/event.go b/vendor/github.com/chromedp/chromedp/kb/event.go new file mode 100644 index 000000000..d49332ee7 --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/kb/event.go @@ -0,0 +1,53 @@ +package kb + +import ( + "strconv" + + "github.com/chromedp/cdproto/input" +) + +// Key event types for the Type field of an input.DispatchKeyEventParams. +const ( + KeyDown = input.DispatchKeyEventTypeKeyDown + KeyUp = input.DispatchKeyEventTypeKeyUp + KeyRawDown = input.DispatchKeyEventTypeRawKeyDown + KeyChar = input.DispatchKeyEventTypeChar +) + +// Modifier is a bit field of pressed modifier keys. Convert it with int64 to +// set the Modifiers field of an input event. +type Modifier int64 + +// Modifier values. +const ( + ModifierNone Modifier = 0 + ModifierAlt Modifier = 1 + ModifierCtrl Modifier = 2 + ModifierMeta Modifier = 4 + ModifierShift Modifier = 8 + + // ModifierCommand is an alias for ModifierMeta. + ModifierCommand = ModifierMeta +) + +// Int64 returns the Modifier as an int64 value. +func (m Modifier) Int64() int64 { + return int64(m) +} + +// String returns the Modifier as a string value. +func (m Modifier) String() string { + switch m { + case ModifierNone: + return "None" + case ModifierAlt: + return "Alt" + case ModifierCtrl: + return "Ctrl" + case ModifierMeta: + return "Meta" + case ModifierShift: + return "Shift" + } + return "Modifier(" + strconv.FormatInt(int64(m), 10) + ")" +} diff --git a/vendor/github.com/chromedp/chromedp/kb/kb.go b/vendor/github.com/chromedp/chromedp/kb/kb.go index cf32ebb54..e2cd7b460 100644 --- a/vendor/github.com/chromedp/chromedp/kb/kb.go +++ b/vendor/github.com/chromedp/chromedp/kb/kb.go @@ -41,10 +41,10 @@ type Key struct { Native int64 // Windows is the Windows scan code. Windows int64 - // Shift indicates whether or not the Shift modifier should be sent. + // Shift indicates whether the Shift modifier is sent. Shift bool - // Print indicates whether or not the character is a printable character - // (i.e., should a "char" event be generated). + // Print indicates whether the character is a printable character + // (that is, whether a "char" event is generated). Print bool } @@ -54,15 +54,15 @@ func EncodeUnidentified(r rune) []*input.DispatchKeyEventParams { // create keyDown := input.DispatchKeyEventParams{ Key: "Unidentified", - /*NativeVirtualKeyCode: int64(r), // not sure if should be specifying the key code or not ... + /*NativeVirtualKeyCode: int64(r), // not sure whether to specify the key code ... WindowsVirtualKeyCode: int64(r),*/ } keyUp := keyDown - keyDown.Type, keyUp.Type = input.KeyDown, input.KeyUp + keyDown.Type, keyUp.Type = KeyDown, KeyUp // printable, so create char event if unicode.IsPrint(r) { keyChar := keyDown - keyChar.Type = input.KeyChar + keyChar.Type = KeyChar keyChar.Text = string(r) keyChar.UnmodifiedText = string(r) @@ -93,18 +93,18 @@ func Encode(r rune) []*input.DispatchKeyEventParams { keyDown.NativeVirtualKeyCode = 0 } if v.Shift { - keyDown.Modifiers |= input.ModifierShift + keyDown.Modifiers |= int64(ModifierShift) } keyUp := keyDown - keyDown.Type, keyUp.Type = input.KeyDown, input.KeyUp + keyDown.Type, keyUp.Type = KeyDown, KeyUp // printable, so create char event if v.Print { keyChar := keyDown - keyChar.Type = input.KeyChar + keyChar.Type = KeyChar keyChar.Text = v.Text keyChar.UnmodifiedText = v.Unmodified - // the virtual key code for char events for printable characters will - // be different than the defined keycode when not shifted... + // the virtual key code of a char event for a printable character + // differs from the defined keycode when the key is not shifted. // // specifically, it always sends the ascii value as the scan code, // which is available as the rune. @@ -360,7 +360,7 @@ var Keys = map[rune]*Key{ '\u0102': &Key{"AltLeft", "Alt", "", "", 164, 164, false, false}, '\u0104': &Key{"CapsLock", "CapsLock", "", "", 20, 20, false, false}, '\u0105': &Key{"ControlLeft", "Control", "", "", 162, 162, false, false}, - '\u0106': &Key{"Fn", "Fn", "", "", 0, 0, false, false}, + '\u0106': &Key{"Fn", "Fn", "", "", 255, 0, false, false}, '\u0107': &Key{"FnLock", "FnLock", "", "", 0, 0, false, false}, '\u0108': &Key{"Hyper", "Hyper", "", "", 0, 0, false, false}, '\u0109': &Key{"MetaLeft", "Meta", "", "", 91, 91, false, false}, diff --git a/vendor/github.com/chromedp/chromedp/keepopen.go b/vendor/github.com/chromedp/chromedp/keepopen.go new file mode 100644 index 000000000..53d27f02e --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/keepopen.go @@ -0,0 +1,274 @@ +package chromedp + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "time" +) + +// closedGrace is how long WaitClosed waits for the browser process to exit +// after its context ends. A browser that closes its last window also ends the +// context, because the connection drops a moment before the process exits. +const closedGrace = 500 * time.Millisecond + +// keepOpenPrefix starts the name of the default user data directory of a +// browser that KeepOpen started. +const keepOpenPrefix = "keepopen-" + +// KeepOpen is an ExecAllocatorOption that leaves the browser open when the Go +// program ends or when the context is canceled. Use it to look at the page +// after the program is done. See also [KeptOpen] and [VisibleWindow]. +// +// The allocator needs a dialer for a kept browser, as it connects with a +// websocket. Without one, Allocate returns [ErrNoDialer]. Add [WithDialer], or +// WebSocket of the package github.com/chromedp/chromedp/remote, to the options. +// For the default allocator of NewContext, give the option WithKeepOpen of that +// package to NewContext. +// +// The browser must outlive the program, so KeepOpen changes how the allocator +// starts it: +// - The allocator uses the websocket and not the pipe, because the pipe +// closes when the Go process exits, and Chrome then exits too. It starts +// Chrome with --remote-debugging-port=0 and reads the address from the file +// DevToolsActivePort in the user data directory. The allocator of the +// remote package can connect to that address later. +// - The process starts detached: in a new session on Unix, and detached from +// the console and in a new process group on Windows. A func from +// [ModifyCmdFunc] runs first, and the detach settings come after it. +// - The allocator does not kill the process when the context ends. It waits +// for the process in a goroutine, so that no zombie process stays while the +// program runs. +// - The allocator never removes the user data directory. Unless you set +// [UserDataDir], the directory is "keepopen-PID" in the directory +// "chromedp" of os.UserCacheDir, where PID is the process ID of the Go +// program. Each program run leaves one such directory, and you must remove +// it yourself. Two browsers of one program share the directory, so set +// UserDataDir when a program keeps more than one browser open. +// - [Cancel] does not close the browser. The output of the browser goes +// nowhere, so [CombinedOutput] has no effect. The library prints nothing. +// [KeptOpen] returns the address and the directory, so that the program can +// print them. +// +// To close a kept browser, close its window, or kill its process. The process +// is available as Process of the Browser. +func KeepOpen(a *ExecAllocator) { + a.keepOpen = true +} + +// KeptOpen returns the websocket address of the browser of the context and the +// user data directory of the browser, so that a program can print them. Another +// program can attach to the address with the allocator of the package +// github.com/chromedp/chromedp/remote. The user can delete the directory when +// the browser is closed. +// +// KeptOpen returns two empty strings when the context has no browser yet, or +// when the allocator did not start the browser with [KeepOpen]. The browser +// starts at the first Run, so call KeptOpen after it. +func KeptOpen(ctx context.Context) (wsURL, userDataDir string) { + c := FromContext(ctx) + if c == nil || c.Browser == nil || !c.Browser.keptOpen { + return "", "" + } + return c.Browser.wsURL, c.Browser.userDataDir +} + +// WaitClosed blocks until the browser process of the context exits, for +// example when the user closes the last window, or until ctx ends. It returns +// nil when the process exited, and the error of ctx otherwise. Use it in a +// program that must stay alive while the user looks at the window. +// +// If the context has no browser yet, WaitClosed starts one, as Run does. For a +// browser that an allocator of the remote package reaches, WaitClosed waits +// until the connection drops, because there is no process to watch. +func WaitClosed(ctx context.Context) error { + c, err := initContextBrowser(ctx) + if err != nil { + return err + } + closed := c.Browser.exited + if closed == nil { + closed = c.Browser.LostConnection + } + select { + case <-closed: + return nil + case <-ctx.Done(): + } + // The connection of a browser that exits can end the context just before + // the process exits. Give the process a short time before reporting it. + select { + case <-closed: + return nil + case <-time.After(closedGrace): + return ctx.Err() + } +} + +// keptDirs holds the user data directories of the browsers that this program +// started with KeepOpen. +var keptDirs sync.Map + +// keepOpenRoot returns the directory that holds the default user data +// directories of KeepOpen. +func keepOpenRoot() (string, error) { + cache, err := os.UserCacheDir() + if err != nil { + return "", fmt.Errorf("finding the cache directory: %w", err) + } + return filepath.Join(cache, "chromedp"), nil +} + +// isKeepOpenDir reports whether dir is the user data directory of a browser +// that KeepOpen started, in this program or in another one. +func isKeepOpenDir(dir string) bool { + if _, ok := keptDirs.Load(dir); ok { + return true + } + root, err := keepOpenRoot() + if err != nil { + return false + } + return filepath.Dir(dir) == root && strings.HasPrefix(filepath.Base(dir), keepOpenPrefix) +} + +// allocateKeepOpen is Allocate for an allocator with KeepOpen. +func (a *ExecAllocator) allocateKeepOpen(ctx context.Context, c *Context, opts []BrowserOption) (*Browser, error) { + args, err := a.flagArgs() + if err != nil { + return nil, err + } + + dataDir, ok := a.initFlags["user-data-dir"].(string) + if !ok { + root, err := keepOpenRoot() + if err != nil { + return nil, err + } + dataDir = filepath.Join(root, fmt.Sprintf("%s%d", keepOpenPrefix, os.Getpid())) + args = append(args, "--user-data-dir="+dataDir) + } + if err := os.MkdirAll(dataDir, 0o700); err != nil { + return nil, fmt.Errorf("creating the user data directory: %w", err) + } + keptDirs.Store(dataDir, struct{}{}) + // A file from an earlier browser has an address that does not work. + portFile := filepath.Join(dataDir, "DevToolsActivePort") + if err := os.Remove(portFile); err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, fmt.Errorf("removing the old address file: %w", err) + } + + if _, ok := a.initFlags["no-sandbox"]; !ok && os.Getuid() == 0 { + // See Allocate. + args = append(args, "--no-sandbox") + } + if _, ok := a.initFlags["remote-debugging-port"]; !ok { + args = append(args, "--remote-debugging-port=0") + } + args = append(args, "about:blank") + + // Do not use exec.CommandContext. It kills the process when ctx ends. + cmd := exec.Command(a.execPath, args...) + if a.modifyCmdFunc != nil { + a.modifyCmdFunc(cmd) + } + detachCmd(cmd) + a.setCmdEnv(cmd) + if err := cmd.Start(); err != nil { + return nil, err + } + // Reap the process, so that it does not stay as a zombie. + exited := make(chan struct{}) + var waitErr error + go func() { + waitErr = cmd.Wait() + close(exited) + }() + stop := func() { + cmd.Process.Kill() + <-exited + } + + select { + case <-ctx.Done(): + stop() + return nil, ctx.Err() + case <-c.allocated: // for this browser's root context + } + a.wg.Add(1) // for the entire allocator + go func() { + // The process keeps running after the context ends. So the browser is + // done for the Go program when the context ends or the process exits. + select { + case <-exited: + case <-ctx.Done(): + } + a.wg.Done() + close(c.allocated) + }() + + wsURL, err := a.waitActivePort(ctx, portFile, exited) + if err != nil { + stop() + return nil, err + } + browser, err := a.dial(ctx, wsURL, opts) + if err != nil { + stop() + return nil, err + } + go func() { + // See Allocate. The browser keeps running, so only the handler stops. + <-browser.LostConnection + select { + case <-browser.closingGracefully: + default: + browser.noteLost(ctx) + c.cancel() + } + }() + browser.process = cmd.Process + browser.userDataDir = dataDir + browser.exited = exited + browser.reaped = exited + browser.exitErr = &waitErr + browser.keptOpen = true + browser.wsURL = wsURL + return browser, nil +} + +// waitActivePort waits until the browser writes the file DevToolsActivePort, +// and returns the websocket address in it. The first line of the file is the +// port, and the second line is the path. +func (a *ExecAllocator) waitActivePort(ctx context.Context, file string, exited <-chan struct{}) (string, error) { + timeout := time.NewTimer(a.wsURLReadTimeout) + defer timeout.Stop() + tick := time.NewTicker(20 * time.Millisecond) + defer tick.Stop() + for { + if data, err := os.ReadFile(file); err == nil { + lines := strings.Split(strings.TrimSpace(string(data)), "\n") + if len(lines) >= 2 { + port := strings.TrimSpace(lines[0]) + path := strings.TrimSpace(lines[1]) + if port != "" && path != "" { + return "ws://127.0.0.1:" + port + path, nil + } + } + } + select { + case <-tick.C: + case <-exited: + return "", fmt.Errorf("chrome exited before it wrote %s", file) + case <-ctx.Done(): + return "", ctx.Err() + case <-timeout.C: + return "", fmt.Errorf("address file timeout reached after %v: %s", a.wsURLReadTimeout, file) + } + } +} diff --git a/vendor/github.com/chromedp/chromedp/nav.go b/vendor/github.com/chromedp/chromedp/nav.go index 1a936c3e1..9efd76f03 100644 --- a/vendor/github.com/chromedp/chromedp/nav.go +++ b/vendor/github.com/chromedp/chromedp/nav.go @@ -3,109 +3,124 @@ package chromedp import ( "context" "errors" - "fmt" + "github.com/chromedp/cdproto/cdp" + "github.com/chromedp/cdproto/network" "github.com/chromedp/cdproto/page" ) -// NavigateAction are actions which always trigger a page navigation, waiting -// for the page to load. +// Navigate is an action that navigates the current frame and waits for the +// page to load. // -// Note that these actions don't collect HTTP response information; for that, -// see [RunResponse]. -type NavigateAction Action - -// Navigate is an action that navigates the current frame. -func Navigate(urlstr string) NavigateAction { - return responseAction(nil, ActionFunc(func(ctx context.Context) error { - switch _, _, errorText, _, err := page.Navigate(urlstr).Do(ctx); { +// This action does not collect HTTP response information. To get it, use +// [NavigateResponse] or [RunResponse]. +func Navigate(urlstr string) Action[Void] { + return waitLoad(navigate(urlstr)) +} + +// NavigateResponse is like [Navigate], and returns the HTTP response of the +// HTML document. +func NavigateResponse(urlstr string) Action[*network.Response] { + return responseAction(navigate(urlstr)) +} + +// navigate is the action that sends Page.navigate, without waiting for the +// page to load. +func navigate(urlstr string) Action[Void] { + return Func(func(ctx context.Context, t *Target) error { + switch res, err := cdp.Call(ctx, t, page.Navigate, page.NavigateParams{URL: urlstr}); { case err != nil: return err - case errorText != "": - return fmt.Errorf("page load error %s", errorText) + case res.ErrorText != "": + return &LoadError{ErrorText: res.ErrorText} } return nil - })) + }) } // NavigationEntries is an action that retrieves the page's navigation history -// entries. -func NavigationEntries(currentIndex *int64, entries *[]*page.NavigationEntry) Action { - if currentIndex == nil || entries == nil { - panic("currentIndex and entries cannot be nil") +// entries. The result holds the index of the current entry and the entries. +func NavigationEntries() Action[page.GetNavigationHistoryResult] { + return func(ctx context.Context, t *Target) (page.GetNavigationHistoryResult, error) { + return cdp.Call(ctx, t, page.GetNavigationHistory, cdp.Empty{}) } - - return ActionFunc(func(ctx context.Context) error { - var err error - *currentIndex, *entries, err = page.GetNavigationHistory().Do(ctx) - return err - }) } // NavigateToHistoryEntry is an action to navigate to the specified navigation -// entry. -func NavigateToHistoryEntry(entryID int64) NavigateAction { - return responseAction(nil, page.NavigateToHistoryEntry(entryID)) +// entry, and wait for the page to load. +func NavigateToHistoryEntry(entryID int64) Action[Void] { + return waitLoad(navigateToHistoryEntry(entryID)) } // NavigateBack is an action that navigates the current frame backwards in its -// history. -func NavigateBack() NavigateAction { - return responseAction(nil, ActionFunc(func(ctx context.Context) error { - cur, entries, err := page.GetNavigationHistory().Do(ctx) +// history, and waits for the page to load. +func NavigateBack() Action[Void] { + return waitLoad(Func(func(ctx context.Context, t *Target) error { + res, err := cdp.Call(ctx, t, page.GetNavigationHistory, cdp.Empty{}) if err != nil { return err } + cur, entries := res.CurrentIndex, res.Entries if cur <= 0 || cur > int64(len(entries)-1) { return errors.New("invalid navigation entry") } - entryID := entries[cur-1].ID - return page.NavigateToHistoryEntry(entryID).Do(ctx) + _, err = navigateToHistoryEntry(entries[cur-1].ID)(ctx, t) + return err })) } // NavigateForward is an action that navigates the current frame forwards in -// its history. -func NavigateForward() NavigateAction { - return responseAction(nil, ActionFunc(func(ctx context.Context) error { - cur, entries, err := page.GetNavigationHistory().Do(ctx) +// its history, and waits for the page to load. +func NavigateForward() Action[Void] { + return waitLoad(Func(func(ctx context.Context, t *Target) error { + res, err := cdp.Call(ctx, t, page.GetNavigationHistory, cdp.Empty{}) if err != nil { return err } + cur, entries := res.CurrentIndex, res.Entries if cur < 0 || cur >= int64(len(entries)-1) { return errors.New("invalid navigation entry") } - entryID := entries[cur+1].ID - return page.NavigateToHistoryEntry(entryID).Do(ctx) + _, err = navigateToHistoryEntry(entries[cur+1].ID)(ctx, t) + return err })) } -// Reload is an action that reloads the current page. -func Reload() NavigateAction { - return responseAction(nil, page.Reload()) +// Reload is an action that reloads the current page, and waits for the page to +// load. +func Reload() Action[Void] { + return waitLoad(Func(func(ctx context.Context, t *Target) error { + _, err := cdp.Call(ctx, t, page.Reload, page.ReloadParams{}) + return err + })) } // Stop is an action that stops all navigation and pending resource retrieval. -func Stop() Action { - return page.StopLoading() +func Stop() Action[Void] { + return Func(func(ctx context.Context, t *Target) error { + _, err := cdp.Call(ctx, t, page.StopLoading, cdp.Empty{}) + return err + }) +} + +// navigateToHistoryEntry is an action that sends Page.navigateToHistoryEntry. +func navigateToHistoryEntry(entryID int64) Action[Void] { + return Func(func(ctx context.Context, t *Target) error { + _, err := cdp.Call(ctx, t, page.NavigateToHistoryEntry, page.NavigateToHistoryEntryParams{EntryID: entryID}) + return err + }) } // Location is an action that retrieves the document location. -func Location(urlstr *string) Action { - if urlstr == nil { - panic("urlstr cannot be nil") - } - return EvaluateAsDevTools(`document.location.toString()`, urlstr) +func Location() Action[string] { + return EvaluateAsDevTools[string](`document.location.toString()`) } // Title is an action that retrieves the document title. -func Title(title *string) Action { - if title == nil { - panic("title cannot be nil") - } - return EvaluateAsDevTools(`document.title`, title) +func Title() Action[string] { + return EvaluateAsDevTools[string](`document.title`) } diff --git a/vendor/github.com/chromedp/chromedp/node.go b/vendor/github.com/chromedp/chromedp/node.go new file mode 100644 index 000000000..a62491f22 --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/node.go @@ -0,0 +1,363 @@ +package chromedp + +import ( + "bytes" + "fmt" + "io" + "strconv" + "strings" + "sync" + + "github.com/chromedp/cdproto/cdp" +) + +// Node is a DOM node in the node tree of a frame. It embeds the protocol node +// and adds the tree links and the state that chromedp keeps up to date from +// the browser events. +// +// Hold the lock of a Node before you read a field of the tree. +type Node struct { + *cdp.Node + + // Parent is the parent node. + Parent *Node + // Children shadows the Children field of the protocol node. + Children []*Node + // ContentDocument shadows the ContentDocument field of the protocol node. + ContentDocument *Node + // ShadowRoots shadows the ShadowRoots field of the protocol node. + ShadowRoots []*Node + // TemplateContent shadows the TemplateContent field of the protocol node. + TemplateContent *Node + // PseudoElements shadows the PseudoElements field of the protocol node. + PseudoElements []*Node + + // Invalidated is closed when the node is no longer valid. + Invalidated chan struct{} + // State is the state of the node. + State NodeState + + sync.RWMutex +} + +// newNode converts a protocol node and its descendants into a Node tree. It +// moves the child links from the protocol nodes to the new nodes. +func newNode(n *cdp.Node) *Node { + if n == nil { + return nil + } + nn := &Node{ + Node: n, + Children: newNodes(n.Children), + ContentDocument: newNode(n.ContentDocument), + ShadowRoots: newNodes(n.ShadowRoots), + TemplateContent: newNode(n.TemplateContent), + PseudoElements: newNodes(n.PseudoElements), + } + n.Children, n.ContentDocument, n.ShadowRoots = nil, nil, nil + n.TemplateContent, n.PseudoElements = nil, nil + return nn +} + +// newNodes converts a list of protocol nodes with newNode. +func newNodes(nodes []*cdp.Node) []*Node { + if len(nodes) == 0 { + return nil + } + res := make([]*Node, len(nodes)) + for i, n := range nodes { + res[i] = newNode(n) + } + return res +} + +// AttributeValue returns the named attribute for the node. +func (n *Node) AttributeValue(name string) string { + value, _ := n.Attribute(name) + return value +} + +// Attribute returns the named attribute for the node and if it exists. +func (n *Node) Attribute(name string) (string, bool) { + n.RLock() + defer n.RUnlock() + + for i := 0; i+1 < len(n.Attributes); i += 2 { + if n.Attributes[i] == name { + return n.Attributes[i+1], true + } + } + return "", false +} + +// xpath builds the xpath string. +func (n *Node) xpath(stopAtDocument, stopAtID bool) string { + n.RLock() + defer n.RUnlock() + + p, pos := "", "" + id := n.attributeValueLocked("id") + switch { + case n.Parent == nil: + return n.LocalName + + case stopAtDocument && n.NodeType == NodeTypeDocument: + return "" + + case stopAtID && id != "": + p = "/" + pos = `[@id='` + id + `']` + + case n.Parent != nil: + var i int + var found bool + + n.Parent.RLock() + for j := 0; j < len(n.Parent.Children); j++ { + if n.Parent.Children[j].LocalName == n.LocalName { + i++ + } + if n.Parent.Children[j].NodeID == n.NodeID { + found = true + break + } + } + n.Parent.RUnlock() + + if found { + pos = "[" + strconv.Itoa(i) + "]" + } + + p = n.Parent.xpath(stopAtDocument, stopAtID) + } + + localName := n.LocalName + if n.IsSVG { + localName = `*[local-name()='` + localName + `']` + } + return p + "/" + localName + pos +} + +// attributeValueLocked returns the named attribute. The caller must hold the +// lock of the node. +func (n *Node) attributeValueLocked(name string) string { + for i := 0; i+1 < len(n.Attributes); i += 2 { + if n.Attributes[i] == name { + return n.Attributes[i+1] + } + } + return "" +} + +// PartialXPathByID returns the partial XPath for the node. It stops at the +// first parent with an id attribute or at the nearest parent document node. +func (n *Node) PartialXPathByID() string { + return n.xpath(true, true) +} + +// PartialXPath returns the partial XPath for the node. It stops at the nearest +// parent document node. +func (n *Node) PartialXPath() string { + return n.xpath(true, false) +} + +// FullXPathByID returns the full XPath for the node. It stops at the top most +// document root or at the closest parent node with an id attribute. +func (n *Node) FullXPathByID() string { + return n.xpath(false, true) +} + +// FullXPath returns the full XPath for the node. It stops only at the top most +// document root. +func (n *Node) FullXPath() string { + return n.xpath(false, false) +} + +// WriteTo writes a readable representation of the node and all its children to w. +func (n *Node) WriteTo(w io.Writer, prefix, indent string, nodeIDs bool) (int, error) { + if n == nil { + return w.Write([]byte(prefix + "<nil>")) + } + + n.RLock() + defer n.RUnlock() + + var err error + var nn, c int + + // prefix + if c, err = w.Write([]byte(prefix)); err != nil { + return nn + c, err + } + nn += c + + // node name + name := n.NodeName + if n.LocalName != "" { + name = n.LocalName + } + if c, err = w.Write([]byte(name)); err != nil { + return nn + c, err + } + nn += c + + // add #id + var hasID int + for i := 0; i+1 < len(n.Attributes); i += 2 { + if strings.ToLower(n.Attributes[i]) == "id" { + if c, err = w.Write([]byte("#" + n.Attributes[i+1])); err != nil { + return nn + c, err + } + nn += c + hasID = 2 + break + } + } + + // node type + if n.NodeType != NodeTypeElement && n.NodeType != NodeTypeText { + if c, err = fmt.Fprintf(w, " <%s>", NodeType(n.NodeType)); err != nil { + return nn + c, err + } + nn += c + } + + // node value + if n.NodeType == NodeTypeText { + v := n.NodeValue + if len(v) > 15 { + v = v[:15] + "..." + } + if c, err = fmt.Fprintf(w, " %q", v); err != nil { + return nn + c, err + } + nn += c + } + + // attributes + if n.NodeType == NodeTypeElement && len(n.Attributes) > hasID { + if c, err = w.Write([]byte(" [")); err != nil { + return nn + c, err + } + nn += c + for i, space := 0, ""; i+1 < len(n.Attributes); i += 2 { + if strings.ToLower(n.Attributes[i]) == "id" { + continue + } + if c, err = fmt.Fprintf(w, "%s%s=%q", space, n.Attributes[i], n.Attributes[i+1]); err != nil { + return nn + c, err + } + nn += c + if space == "" { + space = " " + } + } + if c, err = w.Write([]byte{']'}); err != nil { + return nn + c, err + } + nn += c + } + + // node id + if nodeIDs { + if c, err = fmt.Fprintf(w, " (%d)", n.NodeID); err != nil { + return nn + c, err + } + nn += c + } + + // children + for _, child := range n.Children { + if c, err = fmt.Fprintln(w); err != nil { + return nn + c, err + } + nn += c + if c, err = child.WriteTo(w, prefix+indent, indent, nodeIDs); err != nil { + return nn + c, err + } + nn += c + } + return nn, nil +} + +// Dump builds a printable string representation of the node and its children. +func (n *Node) Dump(prefix, indent string, nodeIDs bool) string { + var buf bytes.Buffer + _, _ = n.WriteTo(&buf, prefix, indent, nodeIDs) + return buf.String() +} + +// NodeType is the type of a DOM node. It is the value of the NodeType field of +// the protocol node. +type NodeType int64 + +// NodeType values. +const ( + NodeTypeElement = 1 + NodeTypeAttribute = 2 + NodeTypeText = 3 + NodeTypeCDATA = 4 + NodeTypeEntityReference = 5 + NodeTypeEntity = 6 + NodeTypeProcessingInstruction = 7 + NodeTypeComment = 8 + NodeTypeDocument = 9 + NodeTypeDocumentType = 10 + NodeTypeDocumentFragment = 11 + NodeTypeNotation = 12 +) + +// nodeTypeNames are the names of the node types. +var nodeTypeNames = map[NodeType]string{ + NodeTypeElement: "Element", + NodeTypeAttribute: "Attribute", + NodeTypeText: "Text", + NodeTypeCDATA: "CDATA", + NodeTypeEntityReference: "EntityReference", + NodeTypeEntity: "Entity", + NodeTypeProcessingInstruction: "ProcessingInstruction", + NodeTypeComment: "Comment", + NodeTypeDocument: "Document", + NodeTypeDocumentType: "DocumentType", + NodeTypeDocumentFragment: "DocumentFragment", + NodeTypeNotation: "Notation", +} + +// String returns the name of the node type. +func (t NodeType) String() string { + if s, ok := nodeTypeNames[t]; ok { + return s + } + return "NodeType(" + strconv.FormatInt(int64(t), 10) + ")" +} + +// NodeState is the state of a DOM node. +type NodeState uint8 + +// NodeState enum values. +const ( + NodeStateReady NodeState = 1 << (7 - iota) + NodeStateVisible + NodeStateHighlighted +) + +// nodeStateNames are the names of the node states. +var nodeStateNames = map[NodeState]string{ + NodeStateReady: "Ready", + NodeStateVisible: "Visible", + NodeStateHighlighted: "Highlighted", +} + +// String satisfies stringer interface. +func (ns NodeState) String() string { + var s []string + for k, v := range nodeStateNames { + if ns&k != 0 { + s = append(s, v) + } + } + return "[" + strings.Join(s, " ") + "]" +} + +// EmptyNodeID is the "non-existent" node id. +const EmptyNodeID = cdp.NodeID(0) diff --git a/vendor/github.com/chromedp/chromedp/pdf.go b/vendor/github.com/chromedp/chromedp/pdf.go new file mode 100644 index 000000000..182f1b384 --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/pdf.go @@ -0,0 +1,203 @@ +package chromedp + +import ( + "bytes" + "context" + "fmt" + "time" + + "github.com/chromedp/cdproto/cdp" + cdpio "github.com/chromedp/cdproto/io" + "github.com/chromedp/cdproto/page" +) + +// PaperSize is the size of a sheet of paper in inches. Use it with [PDFPaper]. +// A field that is 0 gives the default of the browser for that field, so +// PaperSize{Width: 5} is 5 inches wide and 11 inches high, and the zero value +// is Letter paper. +type PaperSize struct { + Width, Height float64 +} + +// Common paper sizes, in inches. +var ( + PaperLetter = PaperSize{8.5, 11} + PaperLegal = PaperSize{8.5, 14} + PaperTabloid = PaperSize{11, 17} + PaperA3 = PaperSize{11.69, 16.54} + PaperA4 = PaperSize{8.27, 11.69} + PaperA5 = PaperSize{5.83, 8.27} +) + +// PDFOption is an option of [PrintToPDF]. It changes the parameters of the +// protocol command [page.PrintToPDF]. +type PDFOption = func(*page.PrintToPDFParams) + +// PrintToPDF is an action that prints the page to a PDF file, and returns the +// bytes of the file. With no option, the browser prints on Letter paper, in +// portrait, with the margins of 1 cm, and with no header, footer or +// background. +// +// A length is in inches, and a CSS pixel is 1/96 of an inch. For example, a +// landscape A4 page with a header and a page number: +// +// buf, err := chromedp.Run(ctx, chromedp.PrintToPDF( +// chromedp.PDFPaper(chromedp.PaperA4), +// chromedp.PDFLandscape(), +// chromedp.PDFMargin(0.5), +// chromedp.PDFPrintBackground(), +// chromedp.PDFHeaderTemplate(`<div style="font-size:8px"><span class="title"></span></div>`), +// chromedp.PDFFooterTemplate(`<div style="font-size:8px"><span class="pageNumber"></span></div>`), +// )) +// +// For a field that no option sets, send [page.PrintToPDF] yourself with +// [cdp.Call], and give an option that changes the parameters. An option is a +// func, so it can do that: +// +// func(p *page.PrintToPDFParams) { p.TransferMode = page.PrintToPDFTransferModeReturnAsStream } +// +// The browser returns an error when the page ranges select no page. Wait for +// the page to load before the call. +func PrintToPDF(opts ...PDFOption) Action[[]byte] { + return func(ctx context.Context, t *Target) ([]byte, error) { + var p page.PrintToPDFParams + for _, o := range opts { + o(&p) + } + res, err := cdp.Call(ctx, t, page.PrintToPDF, p) + if err != nil { + return nil, err + } + if p.TransferMode != page.PrintToPDFTransferModeReturnAsStream { + return res.Data, nil + } + return readStream(ctx, t, res.Stream) + } +} + +// readStream reads a whole stream of the browser, and closes it. It closes the +// stream also when the read fails or the context ended, with a new context that +// has a limit of 5 seconds, because the browser keeps the stream until then. +func readStream(ctx context.Context, t *Target, h cdpio.StreamHandle) (data []byte, err error) { + defer func() { + cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + if _, cerr := cdp.Call(cctx, t, cdpio.Close, cdpio.CloseParams{Handle: h}); cerr != nil && err == nil { + data, err = nil, fmt.Errorf("closing the stream of the PDF: %w", cerr) + } + }() + var buf bytes.Buffer + for { + res, err := cdp.Call(ctx, t, cdpio.Read, cdpio.ReadParams{Handle: h}) + if err != nil { + return nil, fmt.Errorf("reading the stream of the PDF: %w", err) + } + buf.Write(res.Data) + if res.EOF { + return buf.Bytes(), nil + } + } +} + +// PDFLandscape is an option of [PrintToPDF] that prints in landscape. The +// width and the height of the paper swap. +func PDFLandscape() PDFOption { + return func(p *page.PrintToPDFParams) { p.Landscape = ptr(true) } +} + +// PDFPaper is an option of [PrintToPDF] that sets the size of the paper. Give +// one of the sizes of the package, such as [PaperA4], or a [PaperSize] of your +// own. The default is [PaperLetter]. A zero width or height gives the default +// for that side, so PDFPaper(PaperSize{}) changes nothing. The size is for +// portrait, and [PDFLandscape] swaps it. +func PDFPaper(size PaperSize) PDFOption { + return func(p *page.PrintToPDFParams) { + p.PaperWidth, p.PaperHeight = size.Width, size.Height + } +} + +// PDFMargin is an option of [PrintToPDF] that sets the four margins to the same +// length in inches. The default is 1 cm, which is about 0.4 inches. A margin of +// 0 is valid. +func PDFMargin(inches float64) PDFOption { + return PDFMargins(inches, inches, inches, inches) +} + +// PDFMargins is an option of [PrintToPDF] that sets the margins in inches. The +// order is the same as in CSS: top, right, bottom and left. +func PDFMargins(top, right, bottom, left float64) PDFOption { + return func(p *page.PrintToPDFParams) { + p.MarginTop, p.MarginRight, p.MarginBottom, p.MarginLeft = &top, &right, &bottom, &left + } +} + +// PDFScale is an option of [PrintToPDF] that sets the scale of the page. The +// default is 1, and 0 gives the default, so PDFScale(0) changes nothing. The +// browser accepts 0.1 to 2. +func PDFScale(scale float64) PDFOption { + return func(p *page.PrintToPDFParams) { p.Scale = scale } +} + +// PDFPageRanges is an option of [PrintToPDF] that selects the pages to print, +// for example "1-3, 5". The numbers start at 1. The default is all pages. +func PDFPageRanges(ranges string) PDFOption { + return func(p *page.PrintToPDFParams) { p.PageRanges = ranges } +} + +// PDFPreferCSSPageSize is an option of [PrintToPDF] that uses the page size of +// the CSS rule @page, when the page has one. Otherwise the browser scales the +// content to fit the paper. +func PDFPreferCSSPageSize() PDFOption { + return func(p *page.PrintToPDFParams) { p.PreferCSSPageSize = ptr(true) } +} + +// PDFPrintBackground is an option of [PrintToPDF] that prints the background +// colors and images. By default, the browser leaves them out. +func PDFPrintBackground() PDFOption { + return func(p *page.PrintToPDFParams) { p.PrintBackground = ptr(true) } +} + +// PDFHeaderTemplate is an option of [PrintToPDF] that sets the HTML of the +// header, and turns on the header and the footer. The template can use these +// classes, and the browser puts the value in an element that has one: date, +// title, url, pageNumber and totalPages. The font size of the browser for a +// header is 0, so the template must set one. The header and the footer use +// the page margins, so a margin that is too small hides them. +// +// When you give only a header, the browser prints its own footer. Give +// [PDFFooterTemplate] with `<span></span>` to print no footer. +func PDFHeaderTemplate(html string) PDFOption { + return func(p *page.PrintToPDFParams) { + p.HeaderTemplate = html + p.DisplayHeaderFooter = ptr(true) + } +} + +// PDFFooterTemplate is like [PDFHeaderTemplate] for the footer. +func PDFFooterTemplate(html string) PDFOption { + return func(p *page.PrintToPDFParams) { + p.FooterTemplate = html + p.DisplayHeaderFooter = ptr(true) + } +} + +// PDFOutlineAndTagged is an option of [PrintToPDF] that adds the outline of +// the document, which is a table of contents that a PDF viewer shows for the +// headings, and that makes a tagged PDF, which holds the structure of the +// document for a screen reader. Chrome 154 and later make a tagged PDF by +// default, so with them the option adds the outline. +func PDFOutlineAndTagged() PDFOption { + return func(p *page.PrintToPDFParams) { + p.GenerateDocumentOutline = ptr(true) + p.GenerateTaggedPDF = ptr(true) + } +} + +// PDFStream is an option of [PrintToPDF] that makes the browser send the file as +// a stream that the action reads in pieces, and not in one message. Use it for +// a large file. The result is the same. +func PDFStream() PDFOption { + return func(p *page.PrintToPDFParams) { + p.TransferMode = page.PrintToPDFTransferModeReturnAsStream + } +} diff --git a/vendor/github.com/chromedp/chromedp/pipe.go b/vendor/github.com/chromedp/chromedp/pipe.go new file mode 100644 index 000000000..a29cd70e2 --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/pipe.go @@ -0,0 +1,136 @@ +package chromedp + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "io" + "sync" + + "github.com/chromedp/cdproto" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" +) + +// PipeConn implements Transport with the two pipes of a browser that was +// started with the --remote-debugging-pipe flag. +// +// On Unix, the browser reads the commands from its file descriptor 3 and writes +// the responses and the events to its file descriptor 4. On Windows, it uses two +// handles. Each JSON message ends with one zero byte, in both directions. +type PipeConn struct { + // r is the end of the pipe that the browser writes to. + r io.ReadCloser + // w is the end of the pipe that the browser reads from. + w io.WriteCloser + + // br buffers r. Only one goroutine can call Read at a time. + br *bufio.Reader + + // decoder is reused by Read. + decoder jsonv2.Decoder + + // writeMu makes Write safe to call from more than one goroutine. It + // also protects encoder and wbuf. + writeMu sync.Mutex + encoder jsonv2.Encoder + wbuf bytes.Buffer + + closeOnce sync.Once + closeErr error + + debugf func(string, ...any) +} + +// NewPipeConn returns a Transport that reads the messages of the browser from +// r and writes the messages for the browser to w. Close closes both r and w. +func NewPipeConn(r io.ReadCloser, w io.WriteCloser, opts ...PipeOption) *PipeConn { + c := &PipeConn{ + r: r, + w: w, + br: bufio.NewReader(r), + } + for _, o := range opts { + o(c) + } + return c +} + +// Close satisfies the io.Closer interface. It closes both ends of the pipe, +// which makes the browser exit. +func (c *PipeConn) Close() error { + c.closeOnce.Do(func() { + c.closeErr = errors.Join(c.r.Close(), c.w.Close()) + }) + return c.closeErr +} + +// Read reads the next message. It returns io.EOF when the browser closes its +// end of the pipe. +func (c *PipeConn) Read(_ context.Context, msg *cdproto.Message) error { + for { + // A message can be larger than the buffer of c.br, and a read + // can return part of a message, so read up to the zero byte. + b, err := c.br.ReadBytes(0) + if err != nil { + if err == io.EOF && len(b) > 0 { + return io.ErrUnexpectedEOF + } + return err + } + b = bytes.TrimSuffix(b, []byte{0}) + if len(bytes.TrimSpace(b)) == 0 { + continue + } + + if c.debugf != nil { + c.debugf("<- %s", b) + } + + c.decoder.Reset(bytes.NewReader(b), DefaultUnmarshalOptions) + return jsonv2.UnmarshalDecode(&c.decoder, msg, DefaultUnmarshalOptions) + } +} + +// Write writes a message. It is safe to call from more than one goroutine. +func (c *PipeConn) Write(_ context.Context, msg *cdproto.Message) error { + c.writeMu.Lock() + defer c.writeMu.Unlock() + + c.wbuf.Reset() + c.encoder.Reset(&c.wbuf, DefaultMarshalOptions) + if err := jsonv2.MarshalEncode(&c.encoder, msg, DefaultMarshalOptions); err != nil { + return fmt.Errorf("encoding message: %w", err) + } + // The encoder ends a value with a newline. The pipe protocol needs one + // zero byte instead. + b := bytes.TrimRight(c.wbuf.Bytes(), "\n") + if c.debugf != nil { + c.debugf("-> %s", b) + } + c.wbuf.Truncate(len(b)) + c.wbuf.WriteByte(0) + + // One Write call, so that the message is not split by another writer. + if _, err := c.w.Write(c.wbuf.Bytes()); err != nil { + return fmt.Errorf("writing message: %w", err) + } + return nil +} + +// SetDebugf sets the protocol logger. NewBrowserTransport calls it with the +// logger of the browser. +func (c *PipeConn) SetDebugf(f func(string, ...any)) { + c.debugf = f +} + +// PipeOption is an option of NewPipeConn. +type PipeOption = func(*PipeConn) + +// WithPipeDebugf is a pipe option to set a protocol logger. +func WithPipeDebugf(f func(string, ...any)) PipeOption { + return func(c *PipeConn) { + c.debugf = f + } +} diff --git a/vendor/github.com/chromedp/chromedp/pipe_unix.go b/vendor/github.com/chromedp/chromedp/pipe_unix.go new file mode 100644 index 000000000..96b135f38 --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/pipe_unix.go @@ -0,0 +1,17 @@ +//go:build !windows + +package chromedp + +import ( + "os" + "os/exec" +) + +// setChildPipes gives the ends of the pipes that the browser uses to cmd. On +// Unix, the browser reads the commands from its file descriptor 3 and writes +// the responses and the events to its file descriptor 4. The os/exec package +// numbers the files of ExtraFiles from 3. +func setChildPipes(cmd *exec.Cmd, p *pipeFiles) error { + cmd.ExtraFiles = []*os.File{p.childR, p.childW} + return nil +} diff --git a/vendor/github.com/chromedp/chromedp/pipe_windows.go b/vendor/github.com/chromedp/chromedp/pipe_windows.go new file mode 100644 index 000000000..9f00c7d8a --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/pipe_windows.go @@ -0,0 +1,42 @@ +//go:build windows + +package chromedp + +import ( + "fmt" + "os" + "os/exec" + "slices" + "strconv" + "syscall" +) + +// setChildPipes gives the ends of the pipes that the browser uses to cmd. The +// browser has no file descriptors 3 and 4 on Windows. Chromium takes the +// handles from the switch --remote-debugging-io-pipes. The switch lists the +// handle that the browser reads the commands from, and then the handle that it +// writes the responses and the events to. A handle has the same value in the +// browser process as in this process. +// +// The function os.Pipe makes inheritable handles. Only the two ends of the +// browser must pass to the process, so setChildPipes makes the other ends +// non-inheritable. Then no other process that this program starts can get them. +func setChildPipes(cmd *exec.Cmd, p *pipeFiles) error { + for _, f := range []*os.File{p.parentR, p.parentW, p.outR} { + h := syscall.Handle(f.Fd()) + if err := syscall.SetHandleInformation(h, syscall.HANDLE_FLAG_INHERIT, 0); err != nil { + return fmt.Errorf("making the parent end of a pipe private: %w", err) + } + } + hr := syscall.Handle(p.childR.Fd()) + hw := syscall.Handle(p.childW.Fd()) + if cmd.SysProcAttr == nil { + cmd.SysProcAttr = new(syscall.SysProcAttr) + } + cmd.SysProcAttr.AdditionalInheritedHandles = append(cmd.SysProcAttr.AdditionalInheritedHandles, hr, hw) + flag := "--remote-debugging-io-pipes=" + strconv.FormatUint(uint64(hr), 10) + "," + strconv.FormatUint(uint64(hw), 10) + // Put the switch first, before the URL, so that every parser reads it as a + // switch. + cmd.Args = slices.Insert(cmd.Args, 1, flag) + return nil +} diff --git a/vendor/github.com/chromedp/chromedp/poll.go b/vendor/github.com/chromedp/chromedp/poll.go index 1fcd303ca..4e75a3594 100644 --- a/vendor/github.com/chromedp/chromedp/poll.go +++ b/vendor/github.com/chromedp/chromedp/poll.go @@ -5,36 +5,26 @@ import ( "fmt" "time" - "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/runtime" ) -// PollAction are actions that will wait for a general JavaScript predicate. +// pollTask holds the data of a poll task. // -// See [Poll] for details on building poll tasks. -type PollAction Action - -// pollTask holds information pertaining to a poll task. -// -// See Poll for details on building poll tasks. +// See Poll for how to build poll tasks. type pollTask struct { - frame *cdp.Node // the frame to evaluate the predicate, defaults to the root page + frame *Node // the frame to evaluate the predicate, defaults to the root page predicate string polling string // the polling mode, defaults to "raf" (triggered by requestAnimationFrame) interval time.Duration // the interval when the poll is triggered by a timer timeout time.Duration // the poll timeout, defaults to 30 seconds args []any - res any } -// Do executes the poll task in the browser, -// until the predicate either returns truthy value or the timeout happens. -func (p *pollTask) Do(ctx context.Context) error { - t := cdp.ExecutorFromContext(ctx).(*Target) - if t == nil { - return ErrInvalidTarget - } +// run executes the poll task in the browser until the predicate returns a +// truthy value or the timeout ends. +func runPoll[T any](ctx context.Context, t *Target, p *pollTask) (T, error) { var ( + zero T execCtx runtime.ExecutionContextID ok bool ) @@ -45,7 +35,7 @@ func (p *pollTask) Do(ctx context.Context) error { break } if err := sleepContext(ctx, 5*time.Millisecond); err != nil { - return err + return zero, err } } @@ -66,83 +56,87 @@ func (p *pollTask) Do(ctx context.Context) error { args = append(args, p.timeout.Milliseconds()) args = append(args, p.args...) - r, err := callFunctionOn(ctx, waitForPredicatePageFunction, p.res, - func(p *runtime.CallFunctionOnParams) *runtime.CallFunctionOnParams { - return p.WithExecutionContextID(execCtx). - WithAwaitPromise(true). - WithUserGesture(true) + res, r, err := callFunctionOn[T](ctx, t, waitForPredicatePageFunction, + func(p *runtime.CallFunctionOnParams) { + p.ExecutionContextID = execCtx + p.AwaitPromise = ptr(true) + p.UserGesture = ptr(true) }, args..., ) if r != nil && r.Type == "undefined" { - return ErrPollingTimeout + return zero, ErrPollingTimeout } - return err + return res, err } -// Poll is a poll action that will wait for a general JavaScript predicate. +// Poll is a poll action that waits for a general JavaScript predicate. // It builds the predicate from a JavaScript expression. // -// This is a copy of puppeteer's [page.waitForFunction]. -// It's named Poll intentionally to avoid messing up with the Wait* query actions. +// This is a copy of [page.waitForFunction] of puppeteer. +// It is named Poll on purpose, so that it does not mix with the Wait* query actions. // The behavior is not guaranteed to be compatible. -// For example, our implementation makes the poll task not survive from a navigation, -// and an error is raised in this case (see unit test TestPoll/NotSurviveNavigation). +// For example, in our implementation the poll task does not survive a navigation. +// In this case the action returns an error (see unit test TestPoll/NotSurviveNavigation). // // # Polling Options // -// The default polling mode is "raf", to constantly execute pageFunction in requestAnimationFrame callback. -// This is the tightest polling mode which is suitable to observe styling changes. -// The WithPollingInterval option makes it to poll the predicate with a specified interval. -// The WithPollingMutation option makes it to poll the predicate on every DOM mutation. +// The default polling mode is "raf". It runs pageFunction in a requestAnimationFrame callback all the time. +// This is the tightest polling mode, and it is suitable to observe styling changes. +// The WithPollingInterval option polls the predicate at a given interval. +// The WithPollingMutation option polls the predicate on every DOM mutation. // -// The WithPollingTimeout option specifies the maximum time to wait for the predicate returns truthy value. -// It defaults to 30 seconds. Pass 0 to disable timeout. +// The WithPollingTimeout option sets the maximum time to wait until the predicate returns a truthy value. +// It defaults to 30 seconds. Pass 0 to disable the timeout. // -// The WithPollingInFrame option specifies the frame in which to evaluate the predicate. -// If not specified, it will be evaluated in the root page of the current tab. +// The WithPollingInFrame option sets the frame in which to evaluate the predicate. +// Without it, the action evaluates the predicate in the root page of the current tab. // -// The WithPollingArgs option provides extra arguments to pass to the predicate. -// Only apply this option when the predicate is built from a function. +// The WithPollingArgs option gives extra arguments to the predicate. +// Use this option only when the predicate is built from a function. // See [PollFunction]. // +// The action returns the truthy value of the predicate, decoded into the type +// T. T is handled as in [Evaluate]. Use [Void] when the value does not matter. +// // [page.waitForFunction]: https://github.com/puppeteer/puppeteer/blob/v8.0.0/docs/api.md#pagewaitforfunctionpagefunction-options-args -func Poll(expression string, res any, opts ...PollOption) PollAction { +func Poll[T any](expression string, opts ...PollOption) Action[T] { predicate := fmt.Sprintf(`return (%s);`, expression) - return poll(predicate, res, opts...) + return poll[T](predicate, opts...) } -// PollFunction is a poll action that will wait for a general JavaScript predicate. +// PollFunction is a poll action that waits for a general JavaScript predicate. // It builds the predicate from a JavaScript function. // -// See [Poll] for details on building poll tasks. -func PollFunction(pageFunction string, res any, opts ...PollOption) PollAction { +// See [Poll] for how to build poll tasks. +func PollFunction[T any](pageFunction string, opts ...PollOption) Action[T] { predicate := fmt.Sprintf(`return (%s)(...args);`, pageFunction) - return poll(predicate, res, opts...) + return poll[T](predicate, opts...) } -func poll(predicate string, res any, opts ...PollOption) PollAction { +func poll[T any](predicate string, opts ...PollOption) Action[T] { p := &pollTask{ predicate: predicate, polling: "raf", timeout: 30 * time.Second, - res: res, } // apply options for _, o := range opts { o(p) } - return p + return func(ctx context.Context, t *Target) (T, error) { + return runPoll[T](ctx, t, p) + } } // PollOption is a poll task option. type PollOption = func(task *pollTask) -// WithPollingInterval makes it to poll the predicate with the specified interval. +// WithPollingInterval polls the predicate at the given interval. func WithPollingInterval(interval time.Duration) PollOption { return func(w *pollTask) { w.polling = "" @@ -150,7 +144,7 @@ func WithPollingInterval(interval time.Duration) PollOption { } } -// WithPollingMutation makes it to poll the predicate on every DOM mutation. +// WithPollingMutation polls the predicate on every DOM mutation. func WithPollingMutation() PollOption { return func(w *pollTask) { w.polling = "mutation" @@ -158,17 +152,17 @@ func WithPollingMutation() PollOption { } } -// WithPollingTimeout specifies the maximum time to wait for the predicate returns truthy value. -// It defaults to 30 seconds. Pass 0 to disable timeout. +// WithPollingTimeout sets the maximum time to wait until the predicate returns a truthy value. +// It defaults to 30 seconds. Pass 0 to disable the timeout. func WithPollingTimeout(timeout time.Duration) PollOption { return func(w *pollTask) { w.timeout = timeout } } -// WithPollingInFrame specifies the frame in which to evaluate the predicate. -// If not specified, it will be evaluated in the root page of the current tab. -func WithPollingInFrame(frame *cdp.Node) PollOption { +// WithPollingInFrame sets the frame in which to evaluate the predicate. +// Without it, the action evaluates the predicate in the root page of the current tab. +func WithPollingInFrame(frame *Node) PollOption { return func(w *pollTask) { w.frame = frame } diff --git a/vendor/github.com/chromedp/chromedp/query.go b/vendor/github.com/chromedp/chromedp/query.go index 7e4ac1582..d18567756 100644 --- a/vendor/github.com/chromedp/chromedp/query.go +++ b/vendor/github.com/chromedp/chromedp/query.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "io" + "reflect" "strconv" "strings" "sync" @@ -17,134 +18,233 @@ import ( "github.com/chromedp/cdproto/runtime" ) -// QueryAction are element query actions that select node elements from the -// browser's DOM for retrieval or manipulation. +// Selectable is what an element query accepts as the selector. The type of the +// selector chooses the lookup. A plain string is a [Search]. A named string +// type that this package does not define also counts as a [Search]. // -// See [Query] for details on building element query selectors. -type QueryAction Action +// The set of selector types is closed. A type that you define cannot add a new +// lookup. For a custom lookup, use the option [ByFunc]. It replaces the lookup +// of the selector with a func that receives the [Target] of the tab and the +// [Node] where the query starts, and returns the node IDs of the elements. The +// target is a session for [cdp.Call]. The start node is the root of the +// document, or the node of [FromNode]. The selector is then only a label in +// error messages, so pass "" or any string. For example, this lookup finds the +// elements with a data-testid attribute: +// +// func byTestID(id string) chromedp.QueryOption { +// return chromedp.ByFunc(func(ctx context.Context, t *chromedp.Target, n *chromedp.Node) ([]cdp.NodeID, error) { +// res, err := cdp.Call(ctx, t, dom.QuerySelectorAll, dom.QuerySelectorAllParams{ +// NodeID: n.NodeID, +// Selector: fmt.Sprintf("[data-testid=%q]", id), +// }) +// return res.NodeIDs, err +// }) +// } +// +// err := chromedp.Do(ctx, chromedp.Click("", byTestID("submit"))) +type Selectable interface { + ~string | ~[]cdp.NodeID +} + +// Search is a selector that the browser resolves with DOM.performSearch. It +// matches nodes by plain text, CSS selector or XPath query. It is the lookup of +// a plain string. +type Search string + +// CSS is a selector for the first element that matches a CSS selector. It uses +// DOM.querySelector. +type CSS string + +// CSSAll is a selector for every element that matches a CSS selector. It uses +// DOM.querySelectorAll. +type CSSAll string + +// ID is a selector for the element with this id. A leading "#" is optional. It +// uses DOM.querySelector. +type ID string + +// JSPath is a selector for the elements that a JavaScript expression gives. It +// uses Runtime.evaluate. Use it only with trusted values, because chromedp +// passes the expression to the browser without a check. +type JSPath string -// Selector holds information pertaining to an element selection query. +// NodeIDs is a selector for the elements with these node IDs. +type NodeIDs []cdp.NodeID + +// Selector holds the data of an element selection query. // -// See [Query] for information on building an element selector and relevant -// options. +// See [Query] for how to build an element selector and its options. type Selector struct { - sel any - fromNode *cdp.Node + text string + ids []cdp.NodeID + fromNode *Node retryInterval time.Duration exp int - by func(context.Context, *cdp.Node) ([]cdp.NodeID, error) - wait func(context.Context, *cdp.Frame, runtime.ExecutionContextID, ...cdp.NodeID) ([]*cdp.Node, error) - after []func(context.Context, runtime.ExecutionContextID, ...*cdp.Node) error + by func(context.Context, *Target, *Node) ([]cdp.NodeID, error) + wait func(context.Context, *Target, *Frame, runtime.ExecutionContextID, ...cdp.NodeID) ([]*Node, error) + after []func(context.Context, *Target, []*Node) error } -// Query is a query action that queries the browser for specific element -// node(s) matching the criteria. +// Query is an action that queries the browser for element nodes that match the +// criteria, and waits until they meet the node conditions. It returns no +// value. To get the nodes, see [Nodes]. // -// Query actions that target a browser DOM element node (or nodes) make use of -// Query, in conjunction with the [After] option to retrieve data or -// to modify the element(s) selected by the query. +// Query actions that target element nodes share one selector. Use the [After] +// option or [QueryAfter] to read data from the selected elements or to change +// them. // // For example: // -// chromedp.Run(ctx, chromedp.SendKeys(`thing`, chromedp.ByID)) +// chromedp.Do(ctx, chromedp.SendKeys(chromedp.ID("thing"), "hello")) // -// The above will perform a [SendKeys] action on the first element matching a -// browser CSS query for "#thing". +// This runs a [SendKeys] action on the first element that has the id "thing". // -// [Element] selection queries work in conjunction with specific actions and form -// the primary way of automating [Tasks] in the browser. They are typically -// written in the following form: +// Element selection queries work with specific actions. They are the main way +// to automate steps in the browser. They have this form: // -// Action(selector[, parameter1, ...parameterN][,result][, queryOptions...]) +// Action(selector[, parameter1, ...parameterN][, queryOptions...]) // // Where: // -// - Action - the action to perform -// - selector - element query selection (typically a string), that any matching node(s) will have the action applied -// - parameter[1-N] - parameter(s) needed for the individual action (if any) -// - result - pointer to a result (if any) -// - queryOptions - changes how queries are executed, or how nodes are waited for +// - Action - the action to run +// - selector - the element query, a [Selectable] value. The action applies to every node that matches it. +// - parameter[1-N] - the parameters that the action needs (if any) +// - queryOptions - change how the query runs, or how it waits for nodes // -// # Query Options +// An action that reads a value returns it. For example, [Text] returns the +// text as a string. +// +// # Selectors +// +// The type of the selector chooses the lookup that the browser runs. A plain +// string, or any other string type that this package does not define, is a +// [Search]. // -// By* options specify the type of element query used By the browser to perform -// the selection query. When not specified, element queries will use [BySearch] -// (a wrapper for DOM.performSearch). +// The [Search] type (the default) queries elements by plain text, CSS +// selector, or XPath query. It wraps DOM.performSearch. // -// Node* options specify node conditions that cause the query to wait until the -// specified condition is true. When not specified, queries will use the -// [NodeReady] wait condition. +// The [ID] type queries a single element by its CSS ID. It wraps +// DOM.querySelector. ID is like document.querySelector('#' + ID) in the +// browser. // -// The [AtLeast] option alters the minimum number of nodes that must be returned -// by the element query. If not specified, the default value is 1. +// The [CSS] type queries a single element with a CSS selector. It wraps +// DOM.querySelector. CSS is like document.querySelector() in the browser. // -// The [After] option is used to specify a func that will be executed when -// element query has returned one or more elements, and after the node condition is -// true. +// The [CSSAll] type queries elements with a CSS selector. It wraps +// DOM.querySelectorAll. CSSAll is like document.querySelectorAll() in the +// browser. // -// # By Options +// The [JSPath] type queries a single element by its "JS Path" value. It wraps +// Runtime.evaluate. JSPath is like a JavaScript snippet that returns an +// element in the browser. Use it only with trusted element queries. chromedp +// passes the query directly to Runtime.evaluate and does not sanitize it. The +// type is useful for DOM elements that the other types cannot retrieve, such +// as ShadowDOM elements. The expression can give a node, an array or a NodeList +// of nodes, or null or undefined. Null, undefined and an empty list select no +// element, so [WaitNotPresent] succeeds and the other waits keep waiting. Any +// other value is an error, and the query returns it at once. // -// The [BySearch] (default) option enables querying for elements by plain text, -// CSS selector or XPath query, wrapping DOM.performSearch. +// The [NodeIDs] type selects the elements with the given node IDs. It uses +// DOM.requestChildNodes to retrieve them. // -// The [ByID] option enables querying for a single element with the matching CSS -// ID, wrapping DOM.querySelector. ByID is similar to calling -// document.querySelector('#' + ID) from within the browser. +// A type outside the [Selectable] set, such as an int or a *[Node], does not +// compile. // -// The [ByQuery] option enables querying for a single element using a CSS -// selector, wrapping DOM.querySelector. ByQuery is similar to calling -// document.querySelector() from within the browser. +// # Query Options +// +// The Node* options set node conditions. The query waits until the condition +// is true. Without a Node* option, the query uses the [NodeReady] condition. // -// The [ByQueryAll] option enables querying for elements using a CSS selector, -// wrapping DOM.querySelectorAll. ByQueryAll is similar to calling -// document.querySelectorAll() from within the browser. +// The [AtLeast] option sets the minimum number of nodes that the query must +// return. The default is 1. // -// The [ByJSPath] option enables querying for a single element using its "JS -// Path" value, wrapping Runtime.evaluate. ByJSPath is similar to executing a -// JavaScript snippet that returns an element from within the browser. ByJSPath -// should be used only with trusted element queries, as it is passed directly -// to Runtime.evaluate, and no attempt is made to sanitize the query. Useful -// for querying DOM elements that cannot be retrieved using other By* funcs, -// such as ShadowDOM elements. +// The [After] option sets a func that runs after the query returns one or more +// elements and the node condition is true. +// +// The [ByFunc] option replaces the lookup of the selector with a custom func. // // # Node Options // -// The [NodeReady] (default) option causes the query to wait until all element -// nodes matching the selector have been retrieved from the browser. +// The [NodeReady] option (the default) makes the query wait until the browser +// has returned all element nodes that match the selector. // -// The [NodeVisible] option causes the query to wait until all element nodes -// matching the selector have been retrieved from the browser, and are visible. +// The [NodeVisible] option makes the query wait until the browser has returned +// all element nodes that match the selector, and they are visible. // -// The [NodeNotVisible] option causes the query to wait until all element nodes -// matching the selector have been retrieved from the browser, and are not +// The [NodeNotVisible] option makes the query wait until the browser has +// returned all element nodes that match the selector, and they are not // visible. // -// The [NodeEnabled] option causes the query to wait until all element nodes -// matching the selector have been retrieved from the browser, and are enabled -// (i.e., do not have a 'disabled' attribute). +// The [NodeEnabled] option makes the query wait until the browser has returned +// all element nodes that match the selector. The nodes must be enabled (that +// is, they have no 'disabled' attribute). // -// The [NodeSelected] option causes the query to wait until all element nodes -// matching the selector have been retrieved from the browser, and are -// selected (i.e., has a 'selected' attribute). +// The [NodeSelected] option makes the query wait until the browser has +// returned all element nodes that match the selector. The nodes must be +// selected (that is, they have a 'selected' attribute). // -// The [NodeNotPresent] option causes the query to wait until there are no -// element nodes matching the selector. -func Query(sel any, opts ...QueryOption) QueryAction { +// The [NodeNotPresent] option makes the query wait until no element node +// matches the selector. +func Query[S Selectable](sel S, opts ...QueryOption) Action[Void] { + return queryDo(sel, nil, opts...) +} + +// QueryAfter is an element query action that queries the browser for selector +// sel. It waits until the node conditions of the query are met, then runs f +// and returns its value. +func QueryAfter[T any, S Selectable](sel S, f func(ctx context.Context, t *Target, nodes []*Node) (T, error), opts ...QueryOption) Action[T] { + s := newSelector(sel, opts) + return func(ctx context.Context, t *Target) (T, error) { + var res T + err := s.run(ctx, t, func(ctx context.Context, nodes []*Node) error { + var err error + res, err = f(ctx, t, nodes) + return err + }) + return res, err + } +} + +// queryDo is like QueryAfter for a func that returns no value. A nil f only +// waits for the nodes. +func queryDo[S Selectable](sel S, f func(ctx context.Context, t *Target, nodes []*Node) error, opts ...QueryOption) Action[Void] { + return QueryAfter(sel, func(ctx context.Context, t *Target, nodes []*Node) (Void, error) { + if f == nil { + return Void{}, nil + } + return Void{}, f(ctx, t, nodes) + }, opts...) +} + +// first returns the first node of the query result, or an error when the query +// matched no node. +func first[S Selectable](sel S, nodes []*Node) (*Node, error) { + if len(nodes) < 1 { + return nil, fmt.Errorf("selector %q did not return any nodes", describe(sel)) + } + return nodes[0], nil +} + +// withOpts returns the options followed by the extra options, without changing +// the array of opts. +func withOpts(opts []QueryOption, extra ...QueryOption) []QueryOption { + return append(opts[:len(opts):len(opts)], extra...) +} + +// newSelector builds the selector of sel and applies the options. The type of +// sel chooses the lookup. The option [ByFunc] can replace it. +func newSelector[S Selectable](sel S, opts []QueryOption) *Selector { s := &Selector{ - sel: sel, exp: 1, retryInterval: 5 * time.Millisecond, } + s.text, s.ids, s.by = lookup(sel) // apply options for _, o := range opts { o(s) } - if s.by == nil { - BySearch(s) - } - if s.wait == nil { NodeReady(s) } @@ -152,13 +252,10 @@ func Query(sel any, opts ...QueryOption) QueryAction { return s } -// Do executes the selector, only finishing if the selector's by, wait, and -// after funcs succeed, or if the context is cancelled. -func (s *Selector) Do(ctx context.Context) error { - t := cdp.ExecutorFromContext(ctx).(*Target) - if t == nil { - return ErrInvalidTarget - } +// run executes the selector. It finishes only when the by, wait, after, and +// last funcs succeed, or when the context is canceled. The last func can be +// nil. +func (s *Selector) run(ctx context.Context, t *Target, last func(context.Context, []*Node) error) error { return retryWithSleep(ctx, s.retryInterval, func(ctx context.Context) (bool, error) { frame, root, execCtx, ok := t.ensureFrame() if !ok { @@ -175,8 +272,8 @@ func (s *Selector) Do(ctx context.Context) error { t.frameMu.RUnlock() // TODO: we probably want to use the nested frame - // instead, but note that util.go stores the nested - // frame's nodes in the root frame's Nodes map. + // instead. Note that util.go stores the nodes of the + // nested frame in the Nodes map of the root frame. // frame = t.frames[fromNode.FrameID] // if frame == nil { // return fmt.Errorf("FromNode provided does not belong to any active frame") @@ -190,30 +287,39 @@ func (s *Selector) Do(ctx context.Context) error { fromNode = doc } - ids, err := s.by(ctx, fromNode) + ids, err := s.by(ctx, t, fromNode) if err != nil { var e *cdproto.Error - // When the selector is invalid (for example, "#a:b" or "#3"), it will - // always fail with "DOM Error while querying". It does not make sense - // to retry in this case. - // Maybe "DOM Error while querying" is also used for other errors other - // than invalid selector. But the response does not contain anything - // else that can be used to distinguish them. So we have to go with it. + // When the selector is invalid (for example, "#a:b" or "#3"), the + // browser always fails with "DOM Error while querying". It makes no + // sense to retry in this case. + // "DOM Error while querying" can also mean other errors. But the + // response has nothing else that tells them apart. So we have to go + // with it. if errors.As(err, &e) && e.Message == "DOM Error while querying" { return true, err } + // A JSPath value of the wrong type does not change by itself. + if errors.Is(err, errNotNode) { + return true, err + } return false, nil } if len(ids) < s.exp { return false, nil } - nodes, err := s.wait(ctx, frame, execCtx, ids...) - // if nodes==nil, we're not yet ready + nodes, err := s.wait(ctx, t, frame, execCtx, ids...) + // if nodes==nil, we are not yet ready if nodes == nil || err != nil { return false, nil } for _, f := range s.after { - if err := f(ctx, execCtx, nodes...); err != nil { + if err := f(ctx, t, nodes); err != nil { + return true, err + } + } + if last != nil { + if err := last(ctx, nodes); err != nil { return true, err } } @@ -221,18 +327,10 @@ func (s *Selector) Do(ctx context.Context) error { }) } -// selAsString forces sel into a string. -func (s *Selector) selAsString() string { - if sel, ok := s.sel.(string); ok { - return sel - } - return fmt.Sprintf("%s", s.sel) -} - // waitReady waits for the specified nodes to be ready. -func (s *Selector) waitReady(check func(context.Context, runtime.ExecutionContextID, *cdp.Node) error) func(context.Context, *cdp.Frame, runtime.ExecutionContextID, ...cdp.NodeID) ([]*cdp.Node, error) { - return func(ctx context.Context, cur *cdp.Frame, execCtx runtime.ExecutionContextID, ids ...cdp.NodeID) ([]*cdp.Node, error) { - nodes := make([]*cdp.Node, len(ids)) +func (s *Selector) waitReady(check func(context.Context, *Target, runtime.ExecutionContextID, *Node) error) func(context.Context, *Target, *Frame, runtime.ExecutionContextID, ...cdp.NodeID) ([]*Node, error) { + return func(ctx context.Context, t *Target, cur *Frame, execCtx runtime.ExecutionContextID, ids ...cdp.NodeID) ([]*Node, error) { + nodes := make([]*Node, len(ids)) cur.RLock() for i, id := range ids { nodes[i] = cur.Nodes[id] @@ -247,11 +345,11 @@ func (s *Selector) waitReady(check func(context.Context, runtime.ExecutionContex if check != nil { errc := make(chan error, 1) for _, n := range nodes { - go func(n *cdp.Node) { + go func(n *Node) { select { case <-ctx.Done(): errc <- ctx.Err() - case errc <- check(ctx, execCtx, n): + case errc <- check(ctx, t, execCtx, n): } }(n) } @@ -271,200 +369,271 @@ func (s *Selector) waitReady(check func(context.Context, runtime.ExecutionContex } } -// QueryAfter is an element query action that queries the browser for selector -// sel. Waits until the visibility conditions of the query have been met, after -// which executes f. -func QueryAfter(sel any, f func(context.Context, runtime.ExecutionContextID, ...*cdp.Node) error, opts ...QueryOption) QueryAction { - return Query(sel, append(opts, After(f))...) -} - // QueryOption is an element query action option. type QueryOption = func(*Selector) -// FromNode is an element query action option where a query will be run. That -// is, the query will only look at the node's element sub-tree. By default, or -// when passed nil, the document's root element will be used. +// FromNode is an element query action option that sets the node where the +// query runs. That is, the query looks only at the element sub-tree of the +// node. By default, or when you pass nil, the query uses the root element of +// the document. +// +// Note: [Search] and [JSPath] selectors do not support FromNode now. The +// option is mainly useful for [CSS] selectors. // -// Note that, at present, BySearch and ByJSPath do not support FromNode; this -// option is mainly useful for ByQuery selectors. -func FromNode(node *cdp.Node) QueryOption { +// FromNode does not reach into an iframe from another site. Chrome runs such an +// iframe in its own process, as a separate target, and the node of the iframe +// element has no ContentDocument. A query from that node finds nothing and +// waits until its context ends. See [WithTargetID] for how to attach to the +// iframe. +func FromNode(node *Node) QueryOption { return func(s *Selector) { s.fromNode = node } } -// ByFunc is an element query action option to set the func used to select elements. -func ByFunc(f func(context.Context, *cdp.Node) ([]cdp.NodeID, error)) QueryOption { +// ByFunc is an element query action option that sets the func that selects +// elements. It replaces the lookup that the type of the selector chooses. The +// selector is then only a label in error messages, so pass "" or any string. +func ByFunc(f func(context.Context, *Target, *Node) ([]cdp.NodeID, error)) QueryOption { return func(s *Selector) { s.by = f } } -// ByQuery is an element query action option to select a single element by the -// DOM.querySelector command. -// -// Similar to calling document.querySelector() in the browser. -func ByQuery(s *Selector) { - ByFunc(func(ctx context.Context, n *cdp.Node) ([]cdp.NodeID, error) { - nodeID, err := dom.QuerySelector(n.NodeID, s.selAsString()).Do(ctx) +// lookupFunc finds the element node IDs of a query. It starts at the node n. +type lookupFunc = func(ctx context.Context, t *Target, n *Node) ([]cdp.NodeID, error) + +// lookup returns what a selector of the type S needs. These are the text for +// error messages, the node IDs and the func that selects the elements. A string +// type that this package does not define counts as a [Search]. +func lookup[S Selectable](sel S) (text string, ids []cdp.NodeID, by lookupFunc) { + switch v := any(sel).(type) { + case CSS: + return string(v), nil, queryOne(string(v)) + case CSSAll: + return string(v), nil, queryAll(string(v)) + case ID: + return string(v), nil, queryOne("#" + strings.TrimPrefix(string(v), "#")) + case JSPath: + return string(v), nil, evaluatePath(string(v)) + case NodeIDs: + return fmt.Sprint([]cdp.NodeID(v)), v, requestNodes(v) + case Search: + return string(v), nil, search(string(v)) + case string: + return v, nil, search(v) + case []cdp.NodeID: + return fmt.Sprint(v), v, requestNodes(v) + } + + // The type is a string type or a node ID slice type that the user + // defined. + v := reflect.ValueOf(sel) + if v.Kind() == reflect.String { + return v.String(), nil, search(v.String()) + } + ids = v.Convert(reflect.TypeFor[[]cdp.NodeID]()).Interface().([]cdp.NodeID) + return fmt.Sprint(ids), ids, requestNodes(ids) +} + +// describe returns the text of a selector for error messages. +func describe[S Selectable](sel S) string { + text, _, _ := lookup(sel) + return text +} + +// queryOne selects a single element by the DOM.querySelector command. +func queryOne(selector string) lookupFunc { + return func(ctx context.Context, t *Target, n *Node) ([]cdp.NodeID, error) { + res, err := cdp.Call(ctx, t, dom.QuerySelector, dom.QuerySelectorParams{NodeID: n.NodeID, Selector: selector}) if err != nil { return nil, err } - if nodeID == cdp.EmptyNodeID { + if res.NodeID == EmptyNodeID { return []cdp.NodeID{}, nil } - return []cdp.NodeID{nodeID}, nil - })(s) -} - -// ByQueryAll is an element query action option to select elements by the -// DOM.querySelectorAll command. -// -// Similar to calling document.querySelectorAll() in the browser. -func ByQueryAll(s *Selector) { - ByFunc(func(ctx context.Context, n *cdp.Node) ([]cdp.NodeID, error) { - return dom.QuerySelectorAll(n.NodeID, s.selAsString()).Do(ctx) - })(s) + return []cdp.NodeID{res.NodeID}, nil + } } -// ByID is an element query option to select a single element by its CSS #id. -// -// Similar to calling document.querySelector('#' + ID) in the browser. -func ByID(s *Selector) { - s.sel = "#" + strings.TrimPrefix(s.selAsString(), "#") - ByQuery(s) +// queryAll selects elements by the DOM.querySelectorAll command. +func queryAll(selector string) lookupFunc { + return func(ctx context.Context, t *Target, n *Node) ([]cdp.NodeID, error) { + res, err := cdp.Call(ctx, t, dom.QuerySelectorAll, dom.QuerySelectorAllParams{NodeID: n.NodeID, Selector: selector}) + return res.NodeIDs, err + } } -// BySearch is an element query option to select elements by the DOM.performSearch -// command. It matches nodes by plain text, CSS selector or XPath query. -func BySearch(s *Selector) { - ByFunc(func(ctx context.Context, n *cdp.Node) ([]cdp.NodeID, error) { - id, count, err := dom.PerformSearch(s.selAsString()).Do(ctx) +// search selects elements by the DOM.performSearch command. It matches nodes by +// plain text, CSS selector or XPath query. +func search(query string) lookupFunc { + return func(ctx context.Context, t *Target, n *Node) ([]cdp.NodeID, error) { + found, err := cdp.Call(ctx, t, dom.PerformSearch, dom.PerformSearchParams{Query: query}) if err != nil { return nil, err } defer func() { - _ = dom.DiscardSearchResults(id).Do(ctx) + _, _ = cdp.Call(ctx, t, dom.DiscardSearchResults, dom.DiscardSearchResultsParams{SearchID: found.SearchID}) }() - if count < 1 { + if found.ResultCount < 1 { return []cdp.NodeID{}, nil } - nodes, err := dom.GetSearchResults(id, 0, count).Do(ctx) + res, err := cdp.Call(ctx, t, dom.GetSearchResults, dom.GetSearchResultsParams{ + SearchID: found.SearchID, + ToIndex: found.ResultCount, + }) if err != nil { return nil, err } - return nodes, nil - })(s) + return res.NodeIDs, nil + } } -// ByJSPath is an element query option to select elements by the "JS Path" -// value (as shown in the Chrome DevTools UI). -// -// Allows for the direct querying of DOM elements that otherwise cannot be -// retrieved using the other By* funcs, such as ShadowDOM elements. -// -// Note: Do not use with an untrusted selector value, as any defined selector -// will be passed to runtime.Evaluate. -func ByJSPath(s *Selector) { - ByFunc(func(ctx context.Context, n *cdp.Node) ([]cdp.NodeID, error) { - // set up eval command - p := runtime.Evaluate(s.selAsString()). - WithAwaitPromise(true). - WithObjectGroup("console"). - WithIncludeCommandLineAPI(true) - - // execute - v, exp, err := p.Do(ctx) +// evaluatePath selects the elements that a JavaScript expression gives, by the +// Runtime.evaluate command. The expression can give a node, an array or a +// NodeList of nodes, or null or undefined. The last one and an empty list select +// no element, so that [NodeNotPresent] succeeds and the other conditions wait. +// Any other value is an error that [Selector.run] does not retry. +func evaluatePath(expression string) lookupFunc { + return func(ctx context.Context, t *Target, n *Node) ([]cdp.NodeID, error) { + v, err := cdp.Call(ctx, t, runtime.Evaluate, runtime.EvaluateParams{ + Expression: expression, + AwaitPromise: ptr(true), + ObjectGroup: "console", + IncludeCommandLineAPI: ptr(true), + }) if err != nil { return nil, err } - if exp != nil { - return nil, exp + if v.ExceptionDetails != nil { + return nil, &ExceptionError{v.ExceptionDetails} + } + + obj := v.Result + switch { + case obj.Type == runtime.RemoteObjectTypeUndefined, obj.Subtype == runtime.RemoteObjectSubtypeNull: + return []cdp.NodeID{}, nil + case obj.Subtype == runtime.RemoteObjectSubtypeNode && obj.ObjectID != "": + return requestNode(ctx, t, obj.ObjectID) + case obj.Subtype != runtime.RemoteObjectSubtypeArray || obj.ObjectID == "": + return nil, fmt.Errorf("JSPath %q gave a %s and not a node: %w", expression, valueKind(obj), errNotNode) } - // use the ObjectID from the evaluation to get the nodeID - nodeID, err := dom.RequestNode(v.ObjectID).Do(ctx) + // An array or a NodeList: its indexes are its own properties. + props, err := cdp.Call(ctx, t, runtime.GetProperties, runtime.GetPropertiesParams{ + ObjectID: obj.ObjectID, + OwnProperties: ptr(true), + }) if err != nil { return nil, err } - - if nodeID == cdp.EmptyNodeID { - return []cdp.NodeID{}, nil + ids := []cdp.NodeID{} + for _, p := range props.Result { + if _, err := strconv.ParseUint(p.Name, 10, 32); err != nil || p.Value == nil { + continue + } + if p.Value.Subtype != runtime.RemoteObjectSubtypeNode { + return nil, fmt.Errorf("JSPath %q gave a list with a value that is not a node: %w", expression, errNotNode) + } + nodeIDs, err := requestNode(ctx, t, p.Value.ObjectID) + if err != nil { + return nil, err + } + ids = append(ids, nodeIDs...) } + return ids, nil + } +} - return []cdp.NodeID{nodeID}, nil - })(s) +// valueKind names the kind of a value for an error message. +func valueKind(obj *runtime.RemoteObject) string { + if obj.ClassName != "" { + return obj.ClassName + } + return string(obj.Type) } -// ByNodeID is an element query option to select elements by their node IDs. -// -// Uses DOM.requestChildNodes to retrieve elements with specific node IDs. -// -// Note: must be used with []cdp.NodeID. -func ByNodeID(s *Selector) { - ids, ok := s.sel.([]cdp.NodeID) - if !ok { - panic("ByNodeID can only work on []cdp.NodeID") +// errNotNode marks the error of a JSPath expression that gave a value that is +// not a node, an array or NodeList of nodes, null or undefined. A retry gives +// the same error, so [Selector.run] returns it at once. +var errNotNode = errors.New("not a node") + +// requestNode returns the ID of the node that the object is. +func requestNode(ctx context.Context, t *Target, id runtime.RemoteObjectID) ([]cdp.NodeID, error) { + res, err := cdp.Call(ctx, t, dom.RequestNode, dom.RequestNodeParams{ObjectID: id}) + if err != nil { + return nil, err } + if res.NodeID == EmptyNodeID { + return []cdp.NodeID{}, nil + } + return []cdp.NodeID{res.NodeID}, nil +} - ByFunc(func(ctx context.Context, n *cdp.Node) ([]cdp.NodeID, error) { +// requestNodes selects the elements with the given node IDs. It uses the +// DOM.requestChildNodes command. +func requestNodes(ids []cdp.NodeID) lookupFunc { + return func(ctx context.Context, t *Target, n *Node) ([]cdp.NodeID, error) { for _, id := range ids { - err := dom.RequestChildNodes(id).WithPierce(true).Do(ctx) + _, err := cdp.Call(ctx, t, dom.RequestChildNodes, dom.RequestChildNodesParams{NodeID: id, Pierce: ptr(true)}) if err != nil { return nil, err } } return ids, nil - })(s) + } } // WaitFunc is an element query option to set a custom node condition wait. -func WaitFunc(wait func(context.Context, *cdp.Frame, runtime.ExecutionContextID, ...cdp.NodeID) ([]*cdp.Node, error)) QueryOption { +func WaitFunc(wait func(context.Context, *Target, *Frame, runtime.ExecutionContextID, ...cdp.NodeID) ([]*Node, error)) QueryOption { return func(s *Selector) { s.wait = wait } } -// NodeReady is an element query option to wait until all queried element nodes -// have been sent by the browser. +// NodeReady is an element query option that waits until the browser has sent +// all queried element nodes. func NodeReady(s *Selector) { WaitFunc(s.waitReady(nil))(s) } -func callFunctionOnNode(ctx context.Context, node *cdp.Node, function string, res any, args ...any) error { - r, err := dom.ResolveNode().WithNodeID(node.NodeID).Do(ctx) +// callFunctionOnNode calls the function with the node as its "this" value, and +// returns the decoded result. +func callFunctionOnNode[T any](ctx context.Context, t *Target, node *Node, function string, args ...any) (T, error) { + var zero T + r, err := cdp.Call(ctx, t, dom.ResolveNode, dom.ResolveNodeParams{NodeID: node.NodeID}) if err != nil { - return err + return zero, err } - err = CallFunctionOn(function, res, - func(p *runtime.CallFunctionOnParams) *runtime.CallFunctionOnParams { - return p.WithObjectID(r.ObjectID) + res, _, err := callFunctionOn[T](ctx, t, function, + func(p *runtime.CallFunctionOnParams) { + p.ObjectID = r.Object.ObjectID }, args..., - ).Do(ctx) - if err != nil { - return err - } + ) - // Try to release the remote object. - // It will fail if the page is navigated or closed, - // and it's okay to ignore the error in this case. - _ = runtime.ReleaseObject(r.ObjectID).Do(ctx) + // Try to release the remote object, also when the call failed. + // It fails if the page navigated or closed, + // and we can ignore the error in this case. + _, _ = cdp.Call(ctx, t, runtime.ReleaseObject, runtime.ReleaseObjectParams{ObjectID: r.Object.ObjectID}) - return nil + if err != nil { + return zero, err + } + return res, nil } -// NodeVisible is an element query option to wait until all queried element -// nodes have been sent by the browser and are visible. +// NodeVisible is an element query option that waits until the browser has sent +// all queried element nodes and they are visible. func NodeVisible(s *Selector) { - WaitFunc(s.waitReady(func(ctx context.Context, execCtx runtime.ExecutionContextID, n *cdp.Node) error { - // check box model - _, err := dom.GetBoxModel().WithNodeID(n.NodeID).Do(ctx) + WaitFunc(s.waitReady(func(ctx context.Context, t *Target, execCtx runtime.ExecutionContextID, n *Node) error { + // get the box model + _, err := cdp.Call(ctx, t, dom.GetBoxModel, dom.GetBoxModelParams{NodeID: n.NodeID}) if err != nil { if isCouldNotComputeBoxModelError(err) { return ErrNotVisible @@ -473,9 +642,8 @@ func NodeVisible(s *Selector) { return err } - // check visibility - var res bool - err = callFunctionOnNode(ctx, n, visibleJS, &res) + // make sure that the visibility is as expected + res, err := callFunctionOnNode[bool](ctx, t, n, visibleJS) if err != nil { return err } @@ -486,12 +654,12 @@ func NodeVisible(s *Selector) { }))(s) } -// NodeNotVisible is an element query option to wait until all queried element -// nodes have been sent by the browser and are not visible. +// NodeNotVisible is an element query option that waits until the browser has +// sent all queried element nodes and they are not visible. func NodeNotVisible(s *Selector) { - WaitFunc(s.waitReady(func(ctx context.Context, execCtx runtime.ExecutionContextID, n *cdp.Node) error { - // check box model - _, err := dom.GetBoxModel().WithNodeID(n.NodeID).Do(ctx) + WaitFunc(s.waitReady(func(ctx context.Context, t *Target, execCtx runtime.ExecutionContextID, n *Node) error { + // get the box model + _, err := cdp.Call(ctx, t, dom.GetBoxModel, dom.GetBoxModelParams{NodeID: n.NodeID}) if err != nil { if isCouldNotComputeBoxModelError(err) { return nil @@ -500,9 +668,8 @@ func NodeNotVisible(s *Selector) { return err } - // check visibility - var res bool - err = callFunctionOnNode(ctx, n, visibleJS, &res) + // make sure that the visibility is as expected + res, err := callFunctionOnNode[bool](ctx, t, n, visibleJS) if err != nil { return err } @@ -513,11 +680,11 @@ func NodeNotVisible(s *Selector) { }))(s) } -// NodeEnabled is an element query option to wait until all queried element -// nodes have been sent by the browser and are enabled (i.e., do not have a +// NodeEnabled is an element query option that waits until the browser has sent +// all queried element nodes. The nodes must be enabled (that is, they have no // 'disabled' attribute). func NodeEnabled(s *Selector) { - WaitFunc(s.waitReady(func(ctx context.Context, execCtx runtime.ExecutionContextID, n *cdp.Node) error { + WaitFunc(s.waitReady(func(ctx context.Context, t *Target, execCtx runtime.ExecutionContextID, n *Node) error { n.RLock() defer n.RUnlock() @@ -531,11 +698,11 @@ func NodeEnabled(s *Selector) { }))(s) } -// NodeSelected is an element query option to wait until all queried element -// nodes have been sent by the browser and are selected (i.e., has 'selected' -// attribute). +// NodeSelected is an element query option that waits until the browser has +// sent all queried element nodes. The nodes must be selected (that is, they +// have a 'selected' attribute). func NodeSelected(s *Selector) { - WaitFunc(s.waitReady(func(ctx context.Context, execCtx runtime.ExecutionContextID, n *cdp.Node) error { + WaitFunc(s.waitReady(func(ctx context.Context, t *Target, execCtx runtime.ExecutionContextID, n *Node) error { n.RLock() defer n.RUnlock() @@ -549,66 +716,66 @@ func NodeSelected(s *Selector) { }))(s) } -// NodeNotPresent is an element query option to wait until no elements are -// present that match the query. +// NodeNotPresent is an element query option that waits until no element +// matches the query. // -// Note: forces the expected number of element nodes to be 0. +// Note: it sets the expected number of element nodes to 0. func NodeNotPresent(s *Selector) { s.exp = 0 - WaitFunc(func(ctx context.Context, cur *cdp.Frame, execCtx runtime.ExecutionContextID, ids ...cdp.NodeID) ([]*cdp.Node, error) { + WaitFunc(func(ctx context.Context, t *Target, cur *Frame, execCtx runtime.ExecutionContextID, ids ...cdp.NodeID) ([]*Node, error) { if len(ids) != 0 { return nil, ErrHasResults } - return []*cdp.Node{}, nil + return []*Node{}, nil })(s) } -// AtLeast is an element query option to set a minimum number of elements that -// must be returned by the query. +// AtLeast is an element query option that sets the minimum number of elements +// that the query must return. // -// By default, a query will have a value of 1. +// By default, a query needs 1. func AtLeast(n int) QueryOption { return func(s *Selector) { s.exp = n } } -// RetryInterval is an element query action option to set the retry interval to specify -// how often it should retry when it failed to select the target element(s). +// RetryInterval is an element query action option that sets how often the +// query retries when it fails to select the target elements. // -// The default value is 5ms. +// The default is 5ms. func RetryInterval(interval time.Duration) QueryOption { return func(s *Selector) { s.retryInterval = interval } } -// After is an element query option that sets a func to execute after the -// matched nodes have been returned by the browser, and after the node -// condition is true. -func After(f func(context.Context, runtime.ExecutionContextID, ...*cdp.Node) error) QueryOption { +// After is an element query option that sets a func to run when the browser +// has returned the matched nodes and the node condition is true. +func After(f func(ctx context.Context, t *Target, nodes []*Node) error) QueryOption { return func(s *Selector) { s.after = append(s.after, f) } } -// Populate is an element query option that causes the queried nodes to be -// retrieved for later use. Use a depth of -1 to retrieve all child nodes. When -// pierce is true, will pierce child containers (e.g. iframes and the like) +// Populate is an element query option that retrieves the queried nodes for +// later use. Use a depth of -1 to retrieve all child nodes. When pierce is +// true, it also pierces child containers (for example iframes). // -// NOTE: this could be extremely resource intensive. Avoid doing this unless -// necessary. +// NOTE: this can use a lot of resources. Use it only when necessary. func Populate(depth int64, pierce bool, opts ...PopulateOption) QueryOption { - return After(func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { + return After(func(ctx context.Context, t *Target, nodes []*Node) error { var d time.Duration for _, o := range opts { o(&d) } for _, n := range nodes { - if err := dom.RequestChildNodes(n.NodeID). - WithDepth(depth). - WithPierce(pierce). - Do(ctx); err != nil { + _, err := cdp.Call(ctx, t, dom.RequestChildNodes, dom.RequestChildNodesParams{ + NodeID: n.NodeID, + Depth: &depth, + Pierce: &pierce, + }) + if err != nil { return err } } @@ -622,110 +789,101 @@ func Populate(depth int64, pierce bool, opts ...PopulateOption) QueryOption { // PopulateOption is an element populate action option. type PopulateOption = func(*time.Duration) -// PopulateWait is populate option to set a wait interval after requesting -// child nodes. +// PopulateWait is a populate option that sets a wait interval after the +// request for child nodes. func PopulateWait(wait time.Duration) PopulateOption { return func(d *time.Duration) { *d = wait } } -// WaitReady is an element query action that waits until the element matching -// the selector is ready (i.e., has been "loaded"). -func WaitReady(sel any, opts ...QueryOption) QueryAction { +// WaitReady is an element query action that waits until the element that +// matches the selector is ready (that is, "loaded"). +func WaitReady[S Selectable](sel S, opts ...QueryOption) Action[Void] { return Query(sel, opts...) } // WaitVisible is an element query action that waits until the element matching // the selector is visible. -func WaitVisible(sel any, opts ...QueryOption) QueryAction { - return Query(sel, append(opts, NodeVisible)...) +func WaitVisible[S Selectable](sel S, opts ...QueryOption) Action[Void] { + return Query(sel, withOpts(opts, NodeVisible)...) } // WaitNotVisible is an element query action that waits until the element // matching the selector is not visible. -func WaitNotVisible(sel any, opts ...QueryOption) QueryAction { - return Query(sel, append(opts, NodeNotVisible)...) +func WaitNotVisible[S Selectable](sel S, opts ...QueryOption) Action[Void] { + return Query(sel, withOpts(opts, NodeNotVisible)...) } -// WaitEnabled is an element query action that waits until the element matching -// the selector is enabled (i.e., does not have attribute 'disabled'). -func WaitEnabled(sel any, opts ...QueryOption) QueryAction { - return Query(sel, append(opts, NodeEnabled)...) +// WaitEnabled is an element query action that waits until the element that +// matches the selector is enabled (that is, it has no attribute 'disabled'). +func WaitEnabled[S Selectable](sel S, opts ...QueryOption) Action[Void] { + return Query(sel, withOpts(opts, NodeEnabled)...) } -// WaitSelected is an element query action that waits until the element -// matching the selector is selected (i.e., has attribute 'selected'). -func WaitSelected(sel any, opts ...QueryOption) QueryAction { - return Query(sel, append(opts, NodeSelected)...) +// WaitSelected is an element query action that waits until the element that +// matches the selector is selected (that is, it has the attribute 'selected'). +func WaitSelected[S Selectable](sel S, opts ...QueryOption) Action[Void] { + return Query(sel, withOpts(opts, NodeSelected)...) } -// WaitNotPresent is an element query action that waits until no elements are -// present matching the selector. -func WaitNotPresent(sel any, opts ...QueryOption) QueryAction { - return Query(sel, append(opts, NodeNotPresent)...) +// WaitNotPresent is an element query action that waits until no element +// that matches the selector is present. +func WaitNotPresent[S Selectable](sel S, opts ...QueryOption) Action[Void] { + return Query(sel, withOpts(opts, NodeNotPresent)...) } // Nodes is an element query action that retrieves the document element nodes // matching the selector. -func Nodes(sel any, nodes *[]*cdp.Node, opts ...QueryOption) QueryAction { - if nodes == nil { - panic("nodes cannot be nil") - } - - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, n ...*cdp.Node) error { - *nodes = n - return nil +func Nodes[S Selectable](sel S, opts ...QueryOption) Action[[]*Node] { + return QueryAfter(sel, func(ctx context.Context, t *Target, nodes []*Node) ([]*Node, error) { + return nodes, nil }, opts...) } -// NodeIDs is an element query action that retrieves the element node IDs matching the -// selector. -func NodeIDs(sel any, ids *[]cdp.NodeID, opts ...QueryOption) QueryAction { - if ids == nil { - panic("nodes cannot be nil") - } - - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { +// QueryNodeIDs is an element query action that retrieves the element node IDs +// matching the selector. +func QueryNodeIDs[S Selectable](sel S, opts ...QueryOption) Action[[]cdp.NodeID] { + return QueryAfter(sel, func(ctx context.Context, t *Target, nodes []*Node) ([]cdp.NodeID, error) { nodeIDs := make([]cdp.NodeID, len(nodes)) for i, n := range nodes { nodeIDs[i] = n.NodeID } - *ids = nodeIDs - - return nil + return nodeIDs, nil }, opts...) } // Focus is an element query action that focuses the first element node matching the // selector. -func Focus(sel any, opts ...QueryOption) QueryAction { - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +func Focus[S Selectable](sel S, opts ...QueryOption) Action[Void] { + return queryDo(sel, func(ctx context.Context, t *Target, nodes []*Node) error { + n, err := first(sel, nodes) + if err != nil { + return err } - return dom.Focus().WithNodeID(nodes[0].NodeID).Do(ctx) + _, err = cdp.Call(ctx, t, dom.Focus, dom.FocusParams{NodeID: n.NodeID}) + return err }, opts...) } // Blur is an element query action that unfocuses (blurs) the first element node // matching the selector. -func Blur(sel any, opts ...QueryOption) QueryAction { - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +func Blur[S Selectable](sel S, opts ...QueryOption) Action[Void] { + return queryDo(sel, func(ctx context.Context, t *Target, nodes []*Node) error { + n, err := first(sel, nodes) + if err != nil { + return err } - var res bool - err := callFunctionOnNode(ctx, nodes[0], blurJS, &res) + res, err := callFunctionOnNode[bool](ctx, t, n, blurJS) if err != nil { return err } if !res { - return fmt.Errorf("could not blur node %d", nodes[0].NodeID) + return fmt.Errorf("could not blur node %d", n.NodeID) } return nil @@ -734,63 +892,57 @@ func Blur(sel any, opts ...QueryOption) QueryAction { // Dimensions is an element query action that retrieves the box model dimensions for the // first element node matching the selector. -func Dimensions(sel any, model **dom.BoxModel, opts ...QueryOption) QueryAction { - if model == nil { - panic("model cannot be nil") - } - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +func Dimensions[S Selectable](sel S, opts ...QueryOption) Action[*dom.BoxModel] { + return QueryAfter(sel, func(ctx context.Context, t *Target, nodes []*Node) (*dom.BoxModel, error) { + n, err := first(sel, nodes) + if err != nil { + return nil, err } - var err error - *model, err = dom.GetBoxModel().WithNodeID(nodes[0].NodeID).Do(ctx) - return err + res, err := cdp.Call(ctx, t, dom.GetBoxModel, dom.GetBoxModelParams{NodeID: n.NodeID}) + if err != nil { + return nil, err + } + return res.Model, nil }, opts...) } // Text is an element query action that retrieves the visible text of the first element // node matching the selector. -func Text(sel any, text *string, opts ...QueryOption) QueryAction { - if text == nil { - panic("text cannot be nil") - } - - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +func Text[S Selectable](sel S, opts ...QueryOption) Action[string] { + return QueryAfter(sel, func(ctx context.Context, t *Target, nodes []*Node) (string, error) { + n, err := first(sel, nodes) + if err != nil { + return "", err } - return callFunctionOnNode(ctx, nodes[0], textJS, text) + return callFunctionOnNode[string](ctx, t, n, textJS) }, opts...) } // TextContent is an element query action that retrieves the text content of the first element // node matching the selector. -func TextContent(sel any, text *string, opts ...QueryOption) QueryAction { - if text == nil { - panic("text cannot be nil") - } - - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +func TextContent[S Selectable](sel S, opts ...QueryOption) Action[string] { + return QueryAfter(sel, func(ctx context.Context, t *Target, nodes []*Node) (string, error) { + n, err := first(sel, nodes) + if err != nil { + return "", err } - return callFunctionOnNode(ctx, nodes[0], textContentJS, text) + return callFunctionOnNode[string](ctx, t, n, textContentJS) }, opts...) } // Clear is an element query action that clears the values of any input/textarea element // nodes matching the selector. -func Clear(sel any, opts ...QueryOption) QueryAction { - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +func Clear[S Selectable](sel S, opts ...QueryOption) Action[Void] { + return queryDo(sel, func(ctx context.Context, t *Target, nodes []*Node) error { + if _, err := first(sel, nodes); err != nil { + return err } for _, n := range nodes { - if n.NodeType != cdp.NodeTypeElement || (n.NodeName != "INPUT" && n.NodeName != "TEXTAREA") { - return fmt.Errorf("selector %q matched node %d with name %s", sel, n.NodeID, strings.ToLower(n.NodeName)) + if n.NodeType != NodeTypeElement || (n.NodeName != "INPUT" && n.NodeName != "TEXTAREA") { + return fmt.Errorf("selector %q matched node %d with name %s", describe(sel), n.NodeID, strings.ToLower(n.NodeName)) } } @@ -798,18 +950,17 @@ func Clear(sel any, opts ...QueryOption) QueryAction { var wg sync.WaitGroup for i, n := range nodes { wg.Add(1) - go func(i int, n *cdp.Node) { + go func(i int, n *Node) { defer wg.Done() - var a Action if n.NodeName == "INPUT" { - a = dom.SetAttributeValue(n.NodeID, "value", "") + _, errs[i] = cdp.Call(ctx, t, dom.SetAttributeValue, dom.SetAttributeValueParams{NodeID: n.NodeID, Name: "value"}) } else { // find textarea's child #text node var textID cdp.NodeID var found bool for _, c := range n.Children { - if c.NodeType == cdp.NodeTypeText { + if c.NodeType == NodeTypeText { textID = c.NodeID found = true break @@ -821,9 +972,8 @@ func Clear(sel any, opts ...QueryOption) QueryAction { return } - a = dom.SetNodeValue(textID, "") + _, errs[i] = cdp.Call(ctx, t, dom.SetNodeValue, dom.SetNodeValueParams{NodeID: textID}) } - errs[i] = a.Do(ctx) }(i, n) } wg.Wait() @@ -841,84 +991,70 @@ func Clear(sel any, opts ...QueryOption) QueryAction { // Value is an element query action that retrieves the JavaScript value field of the // first element node matching the selector. // -// Useful for retrieving an element's JavaScript value, namely form, input, -// textarea, select, or any other element with a '.value' field. -func Value(sel any, value *string, opts ...QueryOption) QueryAction { - if value == nil { - panic("value cannot be nil") - } - - return JavascriptAttribute(sel, "value", value, opts...) +// Use it to read the JavaScript value of a form, input, textarea, select, or +// other element with a '.value' field. +// +// Value follows [JavascriptAttribute]. An element without a '.value' field +// gives an error that wraps [ErrJSUndefined]. +func Value[S Selectable](sel S, opts ...QueryOption) Action[string] { + return JavascriptAttribute[string](sel, "value", opts...) } // SetValue is an element query action that sets the JavaScript value of the first // element node matching the selector. // -// Useful for setting an element's JavaScript value, namely form, input, -// textarea, select, or other element with a '.value' field. -func SetValue(sel any, value string, opts ...QueryOption) QueryAction { +// Use it to set the JavaScript value of a form, input, textarea, select, or +// other element with a '.value' field. +func SetValue[S Selectable](sel S, value string, opts ...QueryOption) Action[Void] { return SetJavascriptAttribute(sel, "value", value, opts...) } -// Attributes is an element query action that retrieves the element attributes for the -// first element node matching the selector. -func Attributes(sel any, attributes *map[string]string, opts ...QueryOption) QueryAction { - if attributes == nil { - panic("attributes cannot be nil") - } - - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) - } +// attributeMap returns the attributes of the node as a map. +func attributeMap(n *Node) map[string]string { + n.RLock() + defer n.RUnlock() - nodes[0].RLock() - defer nodes[0].RUnlock() + m := make(map[string]string) + attrs := n.Attributes + for i := 0; i < len(attrs); i += 2 { + m[attrs[i]] = attrs[i+1] + } + return m +} - m := make(map[string]string) - attrs := nodes[0].Attributes - for i := 0; i < len(attrs); i += 2 { - m[attrs[i]] = attrs[i+1] +// Attributes is an element query action that retrieves the element attributes for the +// first element node matching the selector. +func Attributes[S Selectable](sel S, opts ...QueryOption) Action[map[string]string] { + return QueryAfter(sel, func(ctx context.Context, t *Target, nodes []*Node) (map[string]string, error) { + n, err := first(sel, nodes) + if err != nil { + return nil, err } - - *attributes = m - - return nil + return attributeMap(n), nil }, opts...) } // AttributesAll is an element query action that retrieves the element attributes for // all element nodes matching the selector. -// -// Note: this should be used with the ByQueryAll query option. -func AttributesAll(sel any, attributes *[]map[string]string, opts ...QueryOption) QueryAction { - if attributes == nil { - panic("attributes cannot be nil") - } - - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +// Note: use it with a [CSSAll] selector. +func AttributesAll[S Selectable](sel S, opts ...QueryOption) Action[[]map[string]string] { + return QueryAfter(sel, func(ctx context.Context, t *Target, nodes []*Node) ([]map[string]string, error) { + if _, err := first(sel, nodes); err != nil { + return nil, err } - for _, node := range nodes { - node.RLock() - m := make(map[string]string) - attrs := node.Attributes - for i := 0; i < len(attrs); i += 2 { - m[attrs[i]] = attrs[i+1] - } - *attributes = append(*attributes, m) - node.RUnlock() + all := make([]map[string]string, 0, len(nodes)) + for _, n := range nodes { + all = append(all, attributeMap(n)) } - return nil + return all, nil }, opts...) } // SetAttributes is an element query action that sets the element attributes for the // first element node matching the selector. -func SetAttributes(sel any, attributes map[string]string, opts ...QueryOption) QueryAction { - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { +func SetAttributes[S Selectable](sel S, attributes map[string]string, opts ...QueryOption) Action[Void] { + return queryDo(sel, func(ctx context.Context, t *Target, nodes []*Node) error { if len(nodes) < 1 { return errors.New("expected at least one element") } @@ -929,20 +1065,31 @@ func SetAttributes(sel any, attributes map[string]string, opts ...QueryOption) Q i++ } - return dom.SetAttributesAsText(nodes[0].NodeID, strings.Join(attrs, " ")).Do(ctx) + _, err := cdp.Call(ctx, t, dom.SetAttributesAsText, dom.SetAttributesAsTextParams{ + NodeID: nodes[0].NodeID, + Text: strings.Join(attrs, " "), + }) + return err }, opts...) } -// AttributeValue is an element query action that retrieves the element attribute value -// for the first element node matching the selector. -func AttributeValue(sel any, name string, value *string, ok *bool, opts ...QueryOption) QueryAction { - if value == nil { - panic("value cannot be nil") - } +// AttributeResult is the result of the [AttributeValue] action. +type AttributeResult struct { + // Value is the value of the attribute. It is empty when the attribute + // does not exist. + Value string + + // Exists is true when the element has the attribute. + Exists bool +} - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { +// AttributeValue is an element query action that retrieves the element attribute value +// for the first element node matching the selector. The result tells whether the +// attribute exists. +func AttributeValue[S Selectable](sel S, name string, opts ...QueryOption) Action[AttributeResult] { + return QueryAfter(sel, func(ctx context.Context, t *Target, nodes []*Node) (AttributeResult, error) { if len(nodes) < 1 { - return errors.New("expected at least one element") + return AttributeResult{}, errors.New("expected at least one element") } nodes[0].RLock() @@ -951,80 +1098,84 @@ func AttributeValue(sel any, name string, value *string, ok *bool, opts ...Query attrs := nodes[0].Attributes for i := 0; i < len(attrs); i += 2 { if attrs[i] == name { - *value = attrs[i+1] - if ok != nil { - *ok = true - } - return nil + return AttributeResult{Value: attrs[i+1], Exists: true}, nil } } - if ok != nil { - *ok = false - } - - return nil + return AttributeResult{}, nil }, opts...) } // SetAttributeValue is an element query action that sets the element attribute with // name to value for the first element node matching the selector. -func SetAttributeValue(sel any, name, value string, opts ...QueryOption) QueryAction { - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +func SetAttributeValue[S Selectable](sel S, name, value string, opts ...QueryOption) Action[Void] { + return queryDo(sel, func(ctx context.Context, t *Target, nodes []*Node) error { + n, err := first(sel, nodes) + if err != nil { + return err } - return dom.SetAttributeValue(nodes[0].NodeID, name, value).Do(ctx) + _, err = cdp.Call(ctx, t, dom.SetAttributeValue, dom.SetAttributeValueParams{NodeID: n.NodeID, Name: name, Value: value}) + return err }, opts...) } // RemoveAttribute is an element query action that removes the element attribute with // name from the first element node matching the selector. -func RemoveAttribute(sel any, name string, opts ...QueryOption) QueryAction { - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +func RemoveAttribute[S Selectable](sel S, name string, opts ...QueryOption) Action[Void] { + return queryDo(sel, func(ctx context.Context, t *Target, nodes []*Node) error { + n, err := first(sel, nodes) + if err != nil { + return err } - return dom.RemoveAttribute(nodes[0].NodeID, name).Do(ctx) + _, err = cdp.Call(ctx, t, dom.RemoveAttribute, dom.RemoveAttributeParams{NodeID: n.NodeID, Name: name}) + return err }, opts...) } // JavascriptAttribute is an element query action that retrieves the JavaScript -// attribute for the first element node matching the selector. -func JavascriptAttribute(sel any, name string, res any, opts ...QueryOption) QueryAction { - if res == nil { - panic("res cannot be nil") - } - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +// attribute for the first element node matching the selector. It decodes the +// attribute into the type T, as [Evaluate] does, with one difference. When the +// attribute is null, for example "onclick" with no handler, JavascriptAttribute +// returns the zero value of T and no error, and it does not return [ErrJSNull]. +// An attribute that the element does not have is undefined, and the action +// returns an error that wraps [ErrJSUndefined] for a type that cannot be nil. +func JavascriptAttribute[T any, S Selectable](sel S, name string, opts ...QueryOption) Action[T] { + return QueryAfter(sel, func(ctx context.Context, t *Target, nodes []*Node) (T, error) { + var zero T + n, err := first(sel, nodes) + if err != nil { + return zero, err } - if err := callFunctionOnNode(ctx, nodes[0], attributeJS, res, name); err != nil { - return fmt.Errorf("could not retrieve attribute %q: %w", name, err) + res, err := callFunctionOnNode[T](ctx, t, n, attributeJS, name) + if errors.Is(err, ErrJSNull) { + return zero, nil + } + if err != nil { + return zero, fmt.Errorf("could not retrieve attribute %q: %w", name, err) } - return nil + return res, nil }, opts...) } // SetJavascriptAttribute is an element query action that sets the JavaScript attribute // for the first element node matching the selector. -func SetJavascriptAttribute(sel any, name, value string, opts ...QueryOption) QueryAction { - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +func SetJavascriptAttribute[S Selectable](sel S, name, value string, opts ...QueryOption) Action[Void] { + return queryDo(sel, func(ctx context.Context, t *Target, nodes []*Node) error { + n, err := first(sel, nodes) + if err != nil { + return err } - var res string - err := callFunctionOnNode(ctx, nodes[0], setAttributeJS, &res, name, value) + res, err := callFunctionOnNode[string](ctx, t, n, setAttributeJS, name, value) if err != nil { return err } if res != value { - return fmt.Errorf("could not set value on node %d", nodes[0].NodeID) + return fmt.Errorf("could not set value on node %d", n.NodeID) } return nil @@ -1033,64 +1184,111 @@ func SetJavascriptAttribute(sel any, name, value string, opts ...QueryOption) Qu // OuterHTML is an element query action that retrieves the outer html of the first // element node matching the selector. -func OuterHTML(sel any, html *string, opts ...QueryOption) QueryAction { - if html == nil { - panic("html cannot be nil") - } - return JavascriptAttribute(sel, "outerHTML", html, opts...) +func OuterHTML[S Selectable](sel S, opts ...QueryOption) Action[string] { + return JavascriptAttribute[string](sel, "outerHTML", opts...) } // InnerHTML is an element query action that retrieves the inner html of the first // element node matching the selector. -func InnerHTML(sel any, html *string, opts ...QueryOption) QueryAction { - if html == nil { - panic("html cannot be nil") - } - return JavascriptAttribute(sel, "innerHTML", html, opts...) +func InnerHTML[S Selectable](sel S, opts ...QueryOption) Action[string] { + return JavascriptAttribute[string](sel, "innerHTML", opts...) } // Click is an element query action that sends a mouse click event to the first element // node matching the selector. -func Click(sel any, opts ...QueryOption) QueryAction { - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +func Click[S Selectable](sel S, opts ...QueryOption) Action[Void] { + return queryDo(sel, func(ctx context.Context, t *Target, nodes []*Node) error { + n, err := first(sel, nodes) + if err != nil { + return err + } + + _, err = MouseClickNode(n)(ctx, t) + return err + }, withOpts(opts, NodeVisible)...) +} + +// Tap is an element query action that sends a touch tap to the center of the +// first element node matching the selector. The action scrolls the node into +// view, and then sends a touchStart event and a touchEnd event. See [TapXY]. +// +// The browser sends the touch events and the click event to the page only when +// touch emulation is on. Use [EmulateViewport] with [EmulateTouch] for it. +func Tap[S Selectable](sel S, opts ...QueryOption) Action[Void] { + return queryDo(sel, func(ctx context.Context, t *Target, nodes []*Node) error { + n, err := first(sel, nodes) + if err != nil { + return err + } + + x, y, err := nodeCenter(ctx, t, n) + if err != nil { + return err } - return MouseClickNode(nodes[0]).Do(ctx) - }, append(opts, NodeVisible)...) + _, err = TapXY(x, y)(ctx, t) + return err + }, withOpts(opts, NodeVisible)...) } // DoubleClick is an element query action that sends a mouse double click event to the // first element node matching the selector. -func DoubleClick(sel any, opts ...QueryOption) QueryAction { - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +func DoubleClick[S Selectable](sel S, opts ...QueryOption) Action[Void] { + return queryDo(sel, func(ctx context.Context, t *Target, nodes []*Node) error { + n, err := first(sel, nodes) + if err != nil { + return err } - return MouseClickNode(nodes[0], ClickCount(2)).Do(ctx) - }, append(opts, NodeVisible)...) + _, err = MouseClickNode(n, ClickCount(2))(ctx, t) + return err + }, withOpts(opts, NodeVisible)...) } -// SendKeys is an element query action that synthesizes the key up, char, and down -// events as needed for the runes in v, sending them to the first element node -// matching the selector. +// SendKeys is an element query action that sends key events to the first +// element node that matches the selector. It synthesizes the key down, char, +// and key up events that the runes in v need. // -// See the [keys] for a complete example on how to use SendKeys. +// See [keys] for a complete example of how to use SendKeys. // -// Note: when the element query matches an input[type="file"] node, then -// dom.SetFileInputFiles is used to set the upload path of the input node to v. +// Note: when the element query matches an input[type="file"] node, SendKeys +// uses dom.SetFileInputFiles to set the upload path of the input node to v. // -// [keys]: https://github.com/chromedp/examples/tree/master/keys -func SendKeys(sel any, v string, opts ...QueryOption) QueryAction { - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +// A "\n" in v is the Enter key. SendKeys sends it as "\r", which is the same as +// [kb.Enter]: a keyDown event, a char event with the text "\r", and a keyUp +// event. An editor that handles Enter on keydown and cancels the default, such +// as Lexical, can then insert two line breaks, because the char event inserts +// one more. To send the Enter key with no char event, send a rawKeyDown event +// and a keyUp event with the command [input.DispatchKeyEvent]: +// +// enter := chromedp.Func(func(ctx context.Context, t *chromedp.Target) error { +// for _, typ := range []input.DispatchKeyEventType{ +// input.DispatchKeyEventTypeRawKeyDown, input.DispatchKeyEventTypeKeyUp, +// } { +// _, err := cdp.Call(ctx, t, input.DispatchKeyEvent, input.DispatchKeyEventParams{ +// Type: typ, Key: "Enter", Code: "Enter", +// WindowsVirtualKeyCode: 13, NativeVirtualKeyCode: 13, +// }) +// if err != nil { +// return err +// } +// } +// return nil +// }) +// err := chromedp.Do(ctx, +// chromedp.SendKeys(sel, "Hello"), +// enter, +// chromedp.SendKeys(sel, "World"), +// ) +// +// [keys]: https://github.com/chromedp/examples/tree/main/keys +func SendKeys[S Selectable](sel S, v string, opts ...QueryOption) Action[Void] { + return queryDo(sel, func(ctx context.Context, t *Target, nodes []*Node) error { + n, err := first(sel, nodes) + if err != nil { + return err } - n := nodes[0] - // grab type attribute from node typ, attrs := "", n.Attributes n.RLock() @@ -1103,41 +1301,46 @@ func SendKeys(sel any, v string, opts ...QueryOption) QueryAction { // when working with input[type="file"], call dom.SetFileInputFiles if n.NodeName == "INPUT" && typ == "file" { - return dom.SetFileInputFiles([]string{v}).WithNodeID(n.NodeID).Do(ctx) + _, err := cdp.Call(ctx, t, dom.SetFileInputFiles, dom.SetFileInputFilesParams{Files: []string{v}, NodeID: n.NodeID}) + return err } - return KeyEventNode(n, v).Do(ctx) - }, append(opts, NodeVisible)...) + _, err = KeyEventNode(n, v)(ctx, t) + return err + }, withOpts(opts, NodeVisible)...) } -// SetUploadFiles is an element query action that sets the files to upload (i.e., for a -// input[type="file"] node) for the first element node matching the selector. -func SetUploadFiles(sel any, files []string, opts ...QueryOption) QueryAction { - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +// SetUploadFiles is an element query action that sets the files to upload for +// the first element node matching the selector. The node must be an +// input[type="file"] node. +func SetUploadFiles[S Selectable](sel S, files []string, opts ...QueryOption) Action[Void] { + return queryDo(sel, func(ctx context.Context, t *Target, nodes []*Node) error { + n, err := first(sel, nodes) + if err != nil { + return err } - return dom.SetFileInputFiles(files).WithNodeID(nodes[0].NodeID).Do(ctx) + _, err = cdp.Call(ctx, t, dom.SetFileInputFiles, dom.SetFileInputFilesParams{Files: files, NodeID: n.NodeID}) + return err }, opts...) } // Submit is an element query action that submits the parent form of the first element // node matching the selector. -func Submit(sel any, opts ...QueryOption) QueryAction { - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +func Submit[S Selectable](sel S, opts ...QueryOption) Action[Void] { + return queryDo(sel, func(ctx context.Context, t *Target, nodes []*Node) error { + n, err := first(sel, nodes) + if err != nil { + return err } - var res bool - err := callFunctionOnNode(ctx, nodes[0], submitJS, &res) + res, err := callFunctionOnNode[bool](ctx, t, n, submitJS) if err != nil { return err } if !res { - return fmt.Errorf("could not call submit on node %d", nodes[0].NodeID) + return fmt.Errorf("could not call submit on node %d", n.NodeID) } return nil @@ -1146,20 +1349,20 @@ func Submit(sel any, opts ...QueryOption) QueryAction { // Reset is an element query action that resets the parent form of the first element // node matching the selector. -func Reset(sel any, opts ...QueryOption) QueryAction { - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +func Reset[S Selectable](sel S, opts ...QueryOption) Action[Void] { + return queryDo(sel, func(ctx context.Context, t *Target, nodes []*Node) error { + n, err := first(sel, nodes) + if err != nil { + return err } - var res bool - err := callFunctionOnNode(ctx, nodes[0], resetJS, &res) + res, err := callFunctionOnNode[bool](ctx, t, n, resetJS) if err != nil { return err } if !res { - return fmt.Errorf("could not call reset on node %d", nodes[0].NodeID) + return fmt.Errorf("could not call reset on node %d", n.NodeID) } return nil @@ -1168,75 +1371,64 @@ func Reset(sel any, opts ...QueryOption) QueryAction { // ComputedStyle is an element query action that retrieves the computed style of the // first element node matching the selector. -func ComputedStyle(sel any, style *[]*css.ComputedStyleProperty, opts ...QueryOption) QueryAction { - if style == nil { - panic("style cannot be nil") - } - - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +func ComputedStyle[S Selectable](sel S, opts ...QueryOption) Action[[]*css.ComputedStyleProperty] { + return QueryAfter(sel, func(ctx context.Context, t *Target, nodes []*Node) ([]*css.ComputedStyleProperty, error) { + n, err := first(sel, nodes) + if err != nil { + return nil, err } - computed, _, err := css.GetComputedStyleForNode(nodes[0].NodeID).Do(ctx) + res, err := cdp.Call(ctx, t, css.GetComputedStyleForNode, css.GetComputedStyleForNodeParams{NodeID: n.NodeID}) if err != nil { - return err + return nil, err } - *style = computed - - return nil + return res.ComputedStyle, nil }, opts...) } // MatchedStyle is an element query action that retrieves the matched style information // for the first element node matching the selector. -func MatchedStyle(sel any, style **css.GetMatchedStylesForNodeReturns, opts ...QueryOption) QueryAction { - if style == nil { - panic("style cannot be nil") - } - - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +func MatchedStyle[S Selectable](sel S, opts ...QueryOption) Action[*css.GetMatchedStylesForNodeResult] { + return QueryAfter(sel, func(ctx context.Context, t *Target, nodes []*Node) (*css.GetMatchedStylesForNodeResult, error) { + n, err := first(sel, nodes) + if err != nil { + return nil, err } - var err error - ret := &css.GetMatchedStylesForNodeReturns{} - p := css.GetMatchedStylesForNode(nodes[0].NodeID) - err = cdp.Execute(ctx, css.CommandGetMatchedStylesForNode, p, ret) + res, err := cdp.Call(ctx, t, css.GetMatchedStylesForNode, css.GetMatchedStylesForNodeParams{NodeID: n.NodeID}) if err != nil { - return err + return nil, err } - *style = ret - - return nil + return &res, nil }, opts...) } // ScrollIntoView is an element query action that scrolls the window to the // first element node matching the selector. -func ScrollIntoView(sel any, opts ...QueryOption) QueryAction { - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +func ScrollIntoView[S Selectable](sel S, opts ...QueryOption) Action[Void] { + return queryDo(sel, func(ctx context.Context, t *Target, nodes []*Node) error { + n, err := first(sel, nodes) + if err != nil { + return err } - return dom.ScrollIntoViewIfNeeded().WithNodeID(nodes[0].NodeID).Do(ctx) + _, err = cdp.Call(ctx, t, dom.ScrollIntoViewIfNeeded, dom.ScrollIntoViewIfNeededParams{NodeID: n.NodeID}) + return err }, opts...) } // DumpTo is an element query action that writes a readable tree of the first -// element node matching the selector and its children, up to the specified -// depth. +// element node matching the selector and its children. The tree ends at the +// specified depth. // // See [Dump] for a simpler interface. -func DumpTo(sel any, w io.Writer, prefix, indent string, nodeIDs bool, depth int64, pierce bool, wait time.Duration, opts ...QueryOption) QueryAction { - return Query(sel, append(opts, +func DumpTo[S Selectable](sel S, w io.Writer, prefix, indent string, nodeIDs bool, depth int64, pierce bool, wait time.Duration, opts ...QueryOption) Action[Void] { + return Query(sel, withOpts(opts, Populate(depth, pierce, PopulateWait(wait)), - After(func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - var n *cdp.Node + After(func(ctx context.Context, t *Target, nodes []*Node) error { + var n *Node if len(nodes) > 0 { n = nodes[0] } @@ -1247,11 +1439,10 @@ func DumpTo(sel any, w io.Writer, prefix, indent string, nodeIDs bool, depth int } // Dump is an element query action that writes a readable tree of the first -// element node matching the selector and its children, up to the specified -// depth. +// element node matching the selector and its children. The tree ends at the +// specified depth. // -// See [DumpTo] for more configurable options, which includes the ability to -// set the sleep wait timeout. -func Dump(sel any, w io.Writer, opts ...QueryOption) QueryAction { +// See [DumpTo] for more options, which include the sleep wait timeout. +func Dump[S Selectable](sel S, w io.Writer, opts ...QueryOption) Action[Void] { return DumpTo(sel, w, "", " ", false, -1, true, 80*time.Millisecond, opts...) } diff --git a/vendor/github.com/chromedp/chromedp/screenshot.go b/vendor/github.com/chromedp/chromedp/screenshot.go index d7a6bebfb..b9a5a3b8d 100644 --- a/vendor/github.com/chromedp/chromedp/screenshot.go +++ b/vendor/github.com/chromedp/chromedp/screenshot.go @@ -2,84 +2,74 @@ package chromedp import ( "context" - "fmt" "math" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/page" - "github.com/chromedp/cdproto/runtime" ) -// Screenshot is an element query action that takes a screenshot of the first element -// node matching the selector. +// Screenshot is an element query action that takes a screenshot of the first +// element node that matches the selector. // -// It's supposed to act the same as the command "Capture node screenshot" in Chrome. +// It acts like the command "Capture node screenshot" in Chrome. // -// Behavior notes: the Protocol Monitor shows that the command sends the following -// CDP commands too: +// Behavior notes: the Protocol Monitor shows that the command also sends these +// protocol commands: // - Emulation.clearDeviceMetricsOverride // - Network.setUserAgentOverride with {"userAgent": ""} // - Overlay.setShowViewportSizeOnResize with {"show": false} // -// These CDP commands are not sent by chromedp. If it does not work as expected, -// you can try to send those commands yourself. +// chromedp does not send these protocol commands. If the result is not what +// you expect, send them yourself. // -// See [CaptureScreenshot] for capturing a screenshot of the browser viewport. +// To capture the browser viewport, see [CaptureScreenshot]. // -// See [screenshot] for an example of taking a screenshot of the entire page. +// For an example that takes a screenshot of the entire page, see [screenshot]. // -// [screenshot]: https://github.com/chromedp/examples/tree/master/screenshot -func Screenshot(sel any, picbuf *[]byte, opts ...QueryOption) QueryAction { - return ScreenshotScale(sel, 1, picbuf, opts...) +// [screenshot]: https://github.com/chromedp/examples/tree/main/screenshot +func Screenshot[S Selectable](sel S, opts ...QueryOption) Action[[]byte] { + return ScreenshotScale(sel, 1, opts...) } -// ScreenshotScale is like [Screenshot] but accepts a scale parameter that -// specifies the page scale factor. -func ScreenshotScale(sel any, scale float64, picbuf *[]byte, opts ...QueryOption) QueryAction { - if picbuf == nil { - panic("picbuf cannot be nil") - } - - return QueryAfter(sel, func(ctx context.Context, execCtx runtime.ExecutionContextID, nodes ...*cdp.Node) error { - if len(nodes) < 1 { - return fmt.Errorf("selector %q did not return any nodes", sel) +// ScreenshotScale is like [Screenshot] but takes a scale parameter, which is +// the page scale factor. +func ScreenshotScale[S Selectable](sel S, scale float64, opts ...QueryOption) Action[[]byte] { + return QueryAfter(sel, func(ctx context.Context, t *Target, nodes []*Node) ([]byte, error) { + if _, err := first(sel, nodes); err != nil { + return nil, err } - return ScreenshotNodes(nodes, scale, picbuf).Do(ctx) - }, append(opts, NodeVisible)...) + return ScreenshotNodes(nodes, scale)(ctx, t) + }, withOpts(opts, NodeVisible)...) } -// ScreenshotNodes is an action that captures/takes a screenshot of the -// specified nodes, by calculating the extents of the top most left node and -// bottom most right node. -func ScreenshotNodes(nodes []*cdp.Node, scale float64, picbuf *[]byte) Action { +// ScreenshotNodes is an action that takes a screenshot of the specified nodes. +// It calculates the extents from the top most left node and the bottom most +// right node. +func ScreenshotNodes(nodes []*Node, scale float64) Action[[]byte] { if len(nodes) == 0 { panic("nodes must be non-empty") } - if picbuf == nil { - panic("picbuf cannot be nil") - } - - return ActionFunc(func(ctx context.Context) error { - var clip page.Viewport + return func(ctx context.Context, t *Target) ([]byte, error) { // get box model of first node - if err := callFunctionOnNode(ctx, nodes[0], getClientRectJS, &clip); err != nil { - return err + clip, err := callFunctionOnNode[page.Viewport](ctx, t, nodes[0], getClientRectJS) + if err != nil { + return nil, err } // remainder for _, node := range nodes[1:] { - var v page.Viewport - // get box model of first node - if err := callFunctionOnNode(ctx, node, getClientRectJS, &v); err != nil { - return err + // get box model of the node + v, err := callFunctionOnNode[page.Viewport](ctx, t, node, getClientRectJS) + if err != nil { + return nil, err } clip.X, clip.Width = extents(clip.X, clip.Width, v.X, v.Width) clip.Y, clip.Height = extents(clip.Y, clip.Height, v.Y, v.Height) } - // The "Capture node screenshot" command does not handle fractional dimensions properly. - // Let's align with puppeteer: + // The "Capture node screenshot" command does not handle fractional dimensions correctly. + // Do the same as puppeteer: // https://github.com/puppeteer/puppeteer/blob/bba3f41286908ced8f03faf98242d4c3359a5efc/src/common/Page.ts#L2002-L2011 x, y := math.Round(clip.X), math.Round(clip.Y) clip.Width, clip.Height = math.Round(clip.Width+clip.X-x), math.Round(clip.Height+clip.Y-y) @@ -88,77 +78,69 @@ func ScreenshotNodes(nodes []*cdp.Node, scale float64, picbuf *[]byte) Action { clip.Scale = scale // take screenshot of the box - buf, err := page.CaptureScreenshot(). - WithFormat(page.CaptureScreenshotFormatPng). - WithCaptureBeyondViewport(true). - WithFromSurface(true). - WithClip(&clip). - Do(ctx) + res, err := cdp.Call(ctx, t, page.CaptureScreenshot, page.CaptureScreenshotParams{ + Format: page.CaptureScreenshotFormatPng, + CaptureBeyondViewport: ptr(true), + FromSurface: ptr(true), + Clip: &clip, + }) if err != nil { - return err + return nil, err } - *picbuf = buf - return nil - }) + return res.Data, nil + } } -// CaptureScreenshot is an action that captures/takes a screenshot of the -// current browser viewport. +// CaptureScreenshot is an action that takes a screenshot of the current browser +// viewport. // -// It's supposed to act the same as the command "Capture screenshot" in -// Chrome. See the behavior notes of Screenshot for more information. +// It acts like the command "Capture screenshot" in Chrome. See the behavior +// notes of Screenshot for more information. // -// See the [Screenshot] action to take a screenshot of a specific element. +// To take a screenshot of one element, use the [Screenshot] action. // -// See [screenshot] for an example of taking a screenshot of the entire page. +// For an example that takes a screenshot of the entire page, see [screenshot]. // -// [screenshot]: https://github.com/chromedp/examples/tree/master/screenshot -func CaptureScreenshot(res *[]byte) Action { - if res == nil { - panic("res cannot be nil") +// [screenshot]: https://github.com/chromedp/examples/tree/main/screenshot +func CaptureScreenshot() Action[[]byte] { + return func(ctx context.Context, t *Target) ([]byte, error) { + r, err := cdp.Call(ctx, t, page.CaptureScreenshot, page.CaptureScreenshotParams{FromSurface: ptr(true)}) + if err != nil { + return nil, err + } + return r.Data, nil } - - return ActionFunc(func(ctx context.Context) error { - var err error - *res, err = page.CaptureScreenshot(). - WithFromSurface(true). - Do(ctx) - return err - }) } -// FullScreenshot takes a full screenshot with the specified image quality of -// the entire browser viewport. +// FullScreenshot takes a full screenshot of the entire browser viewport, with +// the given image quality. // -// It's supposed to act the same as the command "Capture full size screenshot" -// in Chrome. See the behavior notes of Screenshot for more information. +// It acts like the command "Capture full size screenshot" in Chrome. See the +// behavior notes of Screenshot for more information. // -// The valid range of the compression quality is [0..100]. When this value is -// 100, the image format is png; otherwise, the image format is jpeg. -func FullScreenshot(res *[]byte, quality int) EmulateAction { - if res == nil { - panic("res cannot be nil") - } - return ActionFunc(func(ctx context.Context) error { +// The valid range of the compression quality is [0..100]. When the quality is +// 100, the image format is png. Otherwise the image format is jpeg. +func FullScreenshot(quality int) Action[[]byte] { + return func(ctx context.Context, t *Target) ([]byte, error) { format := page.CaptureScreenshotFormatPng if quality != 100 { format = page.CaptureScreenshotFormatJpeg } // capture screenshot - var err error - *res, err = page.CaptureScreenshot(). - WithCaptureBeyondViewport(true). - WithFromSurface(true). - WithFormat(format). - WithQuality(int64(quality)). - Do(ctx) + q := int64(quality) + r, err := cdp.Call(ctx, t, page.CaptureScreenshot, page.CaptureScreenshotParams{ + CaptureBeyondViewport: ptr(true), + FromSurface: ptr(true), + Format: format, + Quality: &q, + }) if err != nil { - return err + return nil, err } - return nil - }) + return r.Data, nil + } } func extents(m, n, o, p float64) (float64, float64) { diff --git a/vendor/github.com/chromedp/chromedp/session.go b/vendor/github.com/chromedp/chromedp/session.go new file mode 100644 index 000000000..35adcb25d --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/session.go @@ -0,0 +1,199 @@ +package chromedp + +import ( + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" + "strconv" + "sync" +) + +// subscribers holds the event subscriptions of a session, indexed by the +// method of the event. +type subscribers struct { + mu sync.Mutex + subs map[string]map[*subscription]struct{} + closed bool +} + +// subscribe adds a subscription for the events with the method. It buffers +// every event from the moment that it returns. The returned func stops the +// subscription and closes the channel. +func (s *subscribers) subscribe(method string) (<-chan jsonv2.Value, func()) { + sub := &subscription{ + out: make(chan jsonv2.Value), + wake: make(chan struct{}, 1), + done: make(chan struct{}), + } + s.mu.Lock() + if s.closed { + sub.stop() + } else { + if s.subs == nil { + s.subs = make(map[string]map[*subscription]struct{}) + } + if s.subs[method] == nil { + s.subs[method] = make(map[*subscription]struct{}) + } + s.subs[method][sub] = struct{}{} + } + s.mu.Unlock() + go sub.pump() + + return sub.out, func() { + s.mu.Lock() + delete(s.subs[method], sub) + s.mu.Unlock() + sub.stop() + } +} + +// subscribeMany is like subscribe for several methods, with one queue. The +// channel gets the events of all the methods in the order that they arrived. +// Each value is a JSON object with the fields method and params, because a +// reader cannot tell the method from the parameters alone. +func (s *subscribers) subscribeMany(methods ...string) (<-chan jsonv2.Value, func()) { + sub := &subscription{ + out: make(chan jsonv2.Value), + wake: make(chan struct{}, 1), + done: make(chan struct{}), + tagged: true, + } + s.mu.Lock() + if s.closed { + sub.stop() + } else { + if s.subs == nil { + s.subs = make(map[string]map[*subscription]struct{}) + } + for _, method := range methods { + if s.subs[method] == nil { + s.subs[method] = make(map[*subscription]struct{}) + } + s.subs[method][sub] = struct{}{} + } + } + s.mu.Unlock() + go sub.pump() + + return sub.out, func() { + s.mu.Lock() + for _, method := range methods { + delete(s.subs[method], sub) + } + s.mu.Unlock() + sub.stop() + } +} + +// publish hands the raw parameters of an event to the subscriptions for the +// method. It never blocks. +func (s *subscribers) publish(method string, params jsonv2.Value) { + s.mu.Lock() + defer s.mu.Unlock() + for sub := range s.subs[method] { + if sub.tagged { + sub.push(tagEvent(method, params)) + continue + } + sub.push(params) + } +} + +// tagEvent wraps the parameters of an event in a JSON object with the method. +func tagEvent(method string, params jsonv2.Value) jsonv2.Value { + b := append([]byte(`{"method":`), strconv.Quote(method)...) + b = append(b, `,"params":`...) + if len(params) == 0 { + params = jsonv2.Value("null") + } + b = append(b, params...) + return append(b, '}') +} + +// close ends all subscriptions, and makes later subscriptions end at once. A +// subscription first delivers the events that it already holds, so that a +// reader sees every event up to the end of the session. +func (s *subscribers) close() { + s.mu.Lock() + defer s.mu.Unlock() + s.closed = true + for _, m := range s.subs { + for sub := range m { + sub.finish() + } + } + s.subs = nil +} + +// subscription is one subscriber. It keeps the events in a queue without a +// limit, so that publishing never blocks the handling of the browser events. +// A goroutine moves the events to the channel of the subscriber. +type subscription struct { + out chan jsonv2.Value + wake chan struct{} + done chan struct{} + + // tagged makes publish wrap each event with its method. + tagged bool + + mu sync.Mutex + queue []jsonv2.Value + finished bool + stopOnce sync.Once +} + +func (s *subscription) push(v jsonv2.Value) { + s.mu.Lock() + s.queue = append(s.queue, v) + s.mu.Unlock() + select { + case s.wake <- struct{}{}: + default: + } +} + +// finish ends the subscription after it delivered the queued events. +func (s *subscription) finish() { + s.mu.Lock() + s.finished = true + s.mu.Unlock() + select { + case s.wake <- struct{}{}: + default: + } +} + +// stop ends the subscription at once, and drops the queued events. It is safe +// to call more than once. +func (s *subscription) stop() { + s.stopOnce.Do(func() { close(s.done) }) +} + +// pump sends the queued events to the channel, until the subscription ends. +func (s *subscription) pump() { + defer close(s.out) + for { + s.mu.Lock() + queue, finished := s.queue, s.finished + s.queue = nil + s.mu.Unlock() + + for _, v := range queue { + select { + case s.out <- v: + case <-s.done: + return + } + } + if len(queue) > 0 { + continue + } + if finished { + return + } + select { + case <-s.wake: + case <-s.done: + return + } + } +} diff --git a/vendor/github.com/chromedp/chromedp/skills-lock.json b/vendor/github.com/chromedp/chromedp/skills-lock.json new file mode 100644 index 000000000..33a9eebb8 --- /dev/null +++ b/vendor/github.com/chromedp/chromedp/skills-lock.json @@ -0,0 +1,17 @@ +{ + "version": 1, + "skills": { + "go-pedantry": { + "source": "oborchers/fractional-cto", + "sourceType": "github", + "skillPath": "pedantic-coder/skills/go-pedantry/SKILL.md", + "computedHash": "31d2344d7292bd589b1b37959b72bad61ea53cb0bc7d187d0ce1b2fe0ec9bf3e" + }, + "simple-english": { + "source": "AminBlg/SimpleEnglish", + "sourceType": "github", + "skillPath": "skills/simple-english/SKILL.md", + "computedHash": "27ecd9fcbf49b035da6463dc2aa3459167ae2f2536b65d17eaf52afbaac87f7c" + } + } +} diff --git a/vendor/github.com/chromedp/chromedp/target.go b/vendor/github.com/chromedp/chromedp/target.go index 6bdbe63fb..b0abafa22 100644 --- a/vendor/github.com/chromedp/chromedp/target.go +++ b/vendor/github.com/chromedp/chromedp/target.go @@ -9,11 +9,11 @@ import ( "github.com/chromedp/cdproto" "github.com/chromedp/cdproto/cdp" + jsonv2 "github.com/chromedp/cdproto/cdp/jsonv2" "github.com/chromedp/cdproto/dom" "github.com/chromedp/cdproto/page" "github.com/chromedp/cdproto/runtime" "github.com/chromedp/cdproto/target" - jsonv2 "github.com/go-json-experiment/json" ) // Target manages a Chrome DevTools Protocol target. @@ -27,22 +27,34 @@ type Target struct { messageQueue chan *cdproto.Message + // events holds the subscriptions made with Subscribe. + events subscribers + + // exposedMu protects exposed, the names of the funcs that ExposeFunc made + // available to the page, and exposedSeq, the number of the last binding. + exposedMu sync.Mutex + exposed map[string]struct{} + exposedSeq int + // frameMu protects frames, execContexts, and cur. frameMu sync.RWMutex // frames is the set of encountered frames. - frames map[cdp.FrameID]*cdp.Frame + frames map[cdp.FrameID]*Frame execContexts map[cdp.FrameID]runtime.ExecutionContextID + // execUniqueIDs holds the unique id of each execution context in + // execContexts, because the destroyed event names a context by it. + execUniqueIDs map[cdp.FrameID]string // cur is the current top level frame. cur cdp.FrameID // logging funcs logf, errf func(string, ...any) - // Indicates if the target is a worker target. + // isWorker is true when the target is a worker target. isWorker bool } -func (t *Target) enclosingFrame(node *cdp.Node) cdp.FrameID { +func (t *Target) enclosingFrame(node *Node) cdp.FrameID { t.frameMu.RLock() top := t.frames[t.cur] t.frameMu.RUnlock() @@ -50,8 +62,8 @@ func (t *Target) enclosingFrame(node *cdp.Node) cdp.FrameID { defer top.RUnlock() for { if node == nil { - // Avoid crashing. This can happen if we're using an old - // node that has been replaced, for example. + // Avoid crashing. This can happen if we are using an old + // node that the browser replaced, for example. return "" } if node.FrameID != "" { @@ -62,16 +74,16 @@ func (t *Target) enclosingFrame(node *cdp.Node) cdp.FrameID { return node.FrameID } -// ensureFrame ensures the top frame of this target is loaded and returns the top frame, -// the root node and the ExecutionContextID of this top frame; otherwise, it will return -// false as its last return value. -func (t *Target) ensureFrame() (*cdp.Frame, *cdp.Node, runtime.ExecutionContextID, bool) { +// ensureFrame makes sure that the top frame of this target is loaded. It +// returns the top frame, the root node, and the ExecutionContextID of the top +// frame. Otherwise it returns false as its last return value. +func (t *Target) ensureFrame() (*Frame, *Node, runtime.ExecutionContextID, bool) { t.frameMu.RLock() frame := t.frames[t.cur] execCtx := t.execContexts[t.cur] t.frameMu.RUnlock() - // the frame hasn't loaded yet. + // the frame has not loaded yet. if frame == nil || execCtx == 0 { return nil, nil, 0, false } @@ -93,15 +105,16 @@ func (t *Target) run(ctx context.Context) { value any } // syncEventQueue is used to handle events synchronously within Target. - // TODO: If this queue gets full, the goroutine below could get stuck on - // a send, and response callbacks would never run, resulting in a - // deadlock. Can we fix this without potentially using lots of memory? + // TODO: If this queue gets full, the goroutine below can get stuck on a + // send. Then the response callbacks never run, and this causes a deadlock. + // Can we fix this without potentially using lots of memory? syncEventQueue := make(chan eventValue, 4096) // This goroutine receives events from the browser, calls listeners, and // then passes the events onto the main goroutine for the target handler // to update itself. go func() { + defer t.events.close() for { select { case <-ctx.Done(): @@ -114,11 +127,12 @@ func (t *Target) run(ctx context.Context) { t.listenersMu.Unlock() continue } + t.events.publish(string(msg.Method), msg.Params) ev, err := cdproto.UnmarshalMessage(msg, DefaultUnmarshalOptions) if err != nil { if _, ok := err.(cdp.ErrUnknownCommandOrEvent); ok { - // This is most likely an event received from an older - // Chrome which a newer cdproto doesn't have, as it is + // This is most likely an event from an older Chrome + // that a newer cdproto does not have, because it is // deprecated. Ignore that error. continue } @@ -158,7 +172,13 @@ func (t *Target) run(ctx context.Context) { } } -func (t *Target) Execute(ctx context.Context, method string, params, res any) error { +// Call sends the command to the target, waits for the response, and decodes +// the result into res. It satisfies [cdp.Session]. +// +// Call returns a browser error as a [*cdproto.Error]. It returns an error when +// the connection to the browser is lost, also when ctx never ends. The error +// wraps the reason of the loss and [context.Canceled]. +func (t *Target) Call(ctx context.Context, method string, params, res any) error { if method == target.CommandCloseTarget { return errors.New("to close the target, cancel its context or use chromedp.Cancel") } @@ -196,6 +216,8 @@ func (t *Target) Execute(ctx context.Context, method string, params, res any) er select { case <-ctx.Done(): return ctx.Err() + case <-t.browser.LostConnection: + return t.browser.lostError(ctx) case t.browser.cmdQueue <- cmd: } @@ -203,17 +225,26 @@ func (t *Target) Execute(ctx context.Context, method string, params, res any) er select { case <-ctx.Done(): return ctx.Err() - case msg := <-ch: - switch { - case msg == nil: - return ErrChannelClosed - case msg.Error != nil: - return msg.Error - case res != nil: - return jsonv2.Unmarshal(msg.Result, res, DefaultUnmarshalOptions) + case <-t.browser.LostConnection: + // The reply can arrive just before the loss is known. + select { + case msg := <-ch: + if msg != nil { + return decodeReply(msg, res) + } + default: } + return t.browser.lostError(ctx) + case msg := <-ch: + return decodeReply(msg, res) } - return nil +} + +// Subscribe starts to buffer the target events with the method, and returns +// the channel that the raw event parameters arrive on. It satisfies +// [cdp.Session]. +func (t *Target) Subscribe(method string) (<-chan jsonv2.Value, func()) { + return t.events.subscribe(method) } // runtimeEvent handles incoming runtime events. @@ -233,27 +264,28 @@ func (t *Target) runtimeEvent(ev any) { if aux.FrameID != "" { t.frameMu.Lock() t.execContexts[aux.FrameID] = ev.Context.ID + t.execUniqueIDs[aux.FrameID] = ev.Context.UniqueID t.frameMu.Unlock() } case *runtime.EventExecutionContextDestroyed: t.frameMu.Lock() - for frameID, ctxID := range t.execContexts { - if ctxID == ev.ExecutionContextID { + for frameID, uniqueID := range t.execUniqueIDs { + if uniqueID == ev.ExecutionContextUniqueID { delete(t.execContexts, frameID) + delete(t.execUniqueIDs, frameID) } } t.frameMu.Unlock() case *runtime.EventExecutionContextsCleared: t.frameMu.Lock() - for frameID := range t.execContexts { - delete(t.execContexts, frameID) - } + clear(t.execContexts) + clear(t.execUniqueIDs) t.frameMu.Unlock() } } -// documentUpdated handles the document updated event, retrieving the document -// root for the root frame. +// documentUpdated handles the document updated event. It retrieves the +// document root for the root frame. func (t *Target) documentUpdated(ctx context.Context) { t.frameMu.RLock() f := t.frames[t.cur] @@ -272,16 +304,16 @@ func (t *Target) documentUpdated(ctx context.Context) { close(f.Root.Invalidated) } - f.Nodes = make(map[cdp.NodeID]*cdp.Node) - var err error - f.Root, err = dom.GetDocument().Do(cdp.WithExecutor(ctx, t)) - if err == context.Canceled { + f.Nodes = make(map[cdp.NodeID]*Node) + res, err := cdp.Call(ctx, t, dom.GetDocument, dom.GetDocumentParams{}) + if errors.Is(err, context.Canceled) { return // TODO: perhaps not necessary, but useful to keep the tests less noisy } if err != nil { t.errf("could not retrieve document root for %s: %v", f.ID, err) return } + f.Root = newNode(res.Root) f.Root.Invalidated = make(chan struct{}) walk(f.Nodes, f.Root) } @@ -294,7 +326,7 @@ func (t *Target) pageEvent(ev any) { switch e := ev.(type) { case *page.EventFrameNavigated: t.frameMu.Lock() - t.frames[e.Frame.ID] = e.Frame + t.frames[e.Frame.ID] = &Frame{Frame: e.Frame} if e.Frame.ParentID == "" { // This frame is only the new top-level frame if it has // no parent. @@ -346,9 +378,9 @@ func (t *Target) pageEvent(ev any) { f := t.frames[id] if f == nil { // This can happen if a frame is attached or starts loading - // before it's ever navigated to. We won't have all the frame - // details just yet, but that's okay. - f = &cdp.Frame{ID: id} + // before it is ever navigated to. We do not have all the frame + // details yet, but that is fine. + f = &Frame{Frame: &cdp.Frame{ID: id}} t.frames[id] = f } t.frameMu.Unlock() @@ -373,7 +405,7 @@ func (t *Target) domEvent(ctx context.Context, ev any) { return case *dom.EventSetChildNodes: - id, op = e.ParentID, setChildNodes(f.Nodes, e.Nodes) + id, op = e.ParentID, setChildNodes(f.Nodes, newNodes(e.Nodes)) case *dom.EventAttributeModified: id, op = e.NodeID, attributeModified(e.Name, e.Value) @@ -395,19 +427,19 @@ func (t *Target) domEvent(ctx context.Context, ev any) { id, op = e.NodeID, childNodeCountUpdated(e.ChildNodeCount) case *dom.EventChildNodeInserted: - id, op = e.ParentNodeID, childNodeInserted(f.Nodes, e.PreviousNodeID, e.Node) + id, op = e.ParentNodeID, childNodeInserted(f.Nodes, e.PreviousNodeID, newNode(e.Node)) case *dom.EventChildNodeRemoved: id, op = e.ParentNodeID, childNodeRemoved(f.Nodes, e.NodeID) case *dom.EventShadowRootPushed: - id, op = e.HostID, shadowRootPushed(f.Nodes, e.Root) + id, op = e.HostID, shadowRootPushed(f.Nodes, newNode(e.Root)) case *dom.EventShadowRootPopped: id, op = e.HostID, shadowRootPopped(f.Nodes, e.RootID) case *dom.EventPseudoElementAdded: - id, op = e.ParentID, pseudoElementAdded(f.Nodes, e.PseudoElement) + id, op = e.ParentID, pseudoElementAdded(f.Nodes, newNode(e.PseudoElement)) case *dom.EventPseudoElementRemoved: id, op = e.ParentID, pseudoElementRemoved(f.Nodes, e.PseudoElementID) @@ -416,7 +448,23 @@ func (t *Target) domEvent(ctx context.Context, ev any) { id, op = e.InsertionPointID, distributedNodesUpdated(e.DistributedNodes) case *dom.EventScrollableFlagUpdated: - id, op = e.NodeID, scrollableFlagUpdated(f.Nodes, e.NodeID) + id, op = e.NodeID, scrollableFlagUpdated(e.IsScrollable) + + case *dom.EventAdRelatedStateUpdated: + id, op = e.NodeID, adRelatedStateUpdated(e.AdProvenance) + + case *dom.EventAdoptedStyleSheetsModified: + id, op = e.NodeID, adoptedStyleSheetsModified(e.AdoptedStyleSheets) + + case *dom.EventAffectedByStartingStylesFlagUpdated: + id, op = e.NodeID, affectedByStartingStylesFlagUpdated(e.AffectedByStartingStyles) + + // ignored events + case *dom.EventTopLayerElementsUpdated: + // The event has no parameters and names no node. The top layer + // holds the elements that a page shows above all others, and + // chromedp does not keep it. + return default: t.errf("unhandled node event %T", ev) @@ -425,7 +473,7 @@ func (t *Target) domEvent(ctx context.Context, ev any) { n, ok := f.Nodes[id] if !ok { - // Node ID has been invalidated. Nothing to do. + // The node ID is no longer valid. Nothing to do. return } diff --git a/vendor/github.com/chromedp/chromedp/util.go b/vendor/github.com/chromedp/chromedp/util.go index bc39efba0..0f1ef080a 100644 --- a/vendor/github.com/chromedp/chromedp/util.go +++ b/vendor/github.com/chromedp/chromedp/util.go @@ -1,125 +1,11 @@ package chromedp import ( - "context" - "encoding/json" - "net" - "net/http" - "net/url" - "strings" - "time" - "github.com/chromedp/cdproto" "github.com/chromedp/cdproto/cdp" "slices" ) -// forceIP tries to force the host component in urlstr to be an IP address. -// -// Since Chrome 66+, Chrome DevTools Protocol clients connecting to a browser -// must send the "Host:" header as either an IP address, or "localhost". -// See https://github.com/chromium/chromium/commit/0e914b95f7cae6e8238e4e9075f248f801c686e6. -func forceIP(ctx context.Context, urlstr string) (string, error) { - u, err := url.Parse(urlstr) - if err != nil { - return "", err - } - host, port, err := net.SplitHostPort(u.Host) - if err != nil { - return "", err - } - host, err = resolveHost(ctx, host) - if err != nil { - return "", err - } - u.Host = net.JoinHostPort(host, port) - return u.String(), nil -} - -// resolveHost tries to resolve a host to be an IP address. If the host is -// an IP address or "localhost", it returns the host directly. -func resolveHost(ctx context.Context, host string) (string, error) { - if host == "localhost" { - return host, nil - } - ip := net.ParseIP(host) - if ip != nil { - return host, nil - } - - addrs, err := net.DefaultResolver.LookupIPAddr(ctx, host) - if err != nil { - return "", err - } - - return addrs[0].IP.String(), nil -} - -// modifyURL modifies the websocket debugger URL if the provided URL is not a -// valid websocket debugger URL. -// -// A websocket debugger URL containing "/devtools/browser/" are considered -// valid. In this case, urlstr will only be modified by forceIP. -// -// Otherwise, it will construct a URL like http://[host]:[port]/json/version -// and query the valid websocket debugger URL from this endpoint. The [host] -// and [port] are parsed from the urlstr. If the host component is not an IP, -// it will be resolved to an IP first. Example parameters: -// - ws://127.0.0.1:9222/ -// - http://127.0.0.1:9222/ -// - http://container-name:9222/ -func modifyURL(ctx context.Context, urlstr string) (string, error) { - lctx, cancel := context.WithTimeout(ctx, 20*time.Second) - defer cancel() - - if strings.Contains(urlstr, "/devtools/browser/") { - return forceIP(lctx, urlstr) - } - - // replace the scheme and path to construct a URL like: - // http://127.0.0.1:9222/json/version - u, err := url.Parse(urlstr) - if err != nil { - return "", err - } - u.Scheme = "http" - host, port, err := net.SplitHostPort(u.Host) - if err != nil { - return "", err - } - host, err = resolveHost(ctx, host) - if err != nil { - return "", err - } - u.Host = net.JoinHostPort(host, port) - u.Path = "/json/version" - - // to get "webSocketDebuggerUrl" in the response - req, err := http.NewRequestWithContext(lctx, "GET", u.String(), nil) - if err != nil { - return "", err - } - resp, err := http.DefaultClient.Do(req) - if err != nil { - return "", err - } - defer resp.Body.Close() - - var result map[string]any - if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { - return "", err - } - // the browser will construct the debugger URL using the "host" header of - // the /json/version request. For example, run headless-shell in a container: - // docker run -d -p 9000:9222 chromedp/headless-shell:latest - // then: - // curl http://127.0.0.1:9000/json/version - // and the websocket debugger URL will be something like: - // ws://127.0.0.1:9000/devtools/browser/... - wsURL := result["webSocketDebuggerUrl"].(string) - return wsURL, nil -} - func runListeners(list []cancelableListener, ev any) []cancelableListener { for i := 0; i < len(list); { listener := list[i] @@ -136,42 +22,42 @@ func runListeners(list []cancelableListener, ev any) []cancelableListener { } // frameOp is a frame manipulation operation. -type frameOp func(*cdp.Frame) +type frameOp func(*Frame) func frameAttached(id cdp.FrameID) frameOp { - return func(f *cdp.Frame) { + return func(f *Frame) { f.ParentID = id - setFrameState(f, cdp.FrameAttached) + setFrameState(f, FrameAttached) } } -func frameDetached(f *cdp.Frame) { - f.ParentID = cdp.EmptyFrameID - clearFrameState(f, cdp.FrameAttached) +func frameDetached(f *Frame) { + f.ParentID = EmptyFrameID + clearFrameState(f, FrameAttached) } -func frameStartedLoading(f *cdp.Frame) { - setFrameState(f, cdp.FrameLoading) +func frameStartedLoading(f *Frame) { + setFrameState(f, FrameLoading) } -func frameStoppedLoading(f *cdp.Frame) { - clearFrameState(f, cdp.FrameLoading) +func frameStoppedLoading(f *Frame) { + clearFrameState(f, FrameLoading) } // setFrameState sets the frame state via bitwise or (|). -func setFrameState(f *cdp.Frame, fs cdp.FrameState) { +func setFrameState(f *Frame, fs FrameState) { f.State |= fs } // clearFrameState clears the frame state via bit clear (&^). -func clearFrameState(f *cdp.Frame, fs cdp.FrameState) { +func clearFrameState(f *Frame, fs FrameState) { f.State &^= fs } // nodeOp is a node manipulation operation. -type nodeOp func(*cdp.Node) +type nodeOp func(*Node) -func walk(m map[cdp.NodeID]*cdp.Node, n *cdp.Node) { +func walk(m map[cdp.NodeID]*Node, n *Node) { n.RLock() defer n.RUnlock() m[n.NodeID] = n @@ -203,7 +89,7 @@ func walk(m map[cdp.NodeID]*cdp.Node, n *cdp.Node) { walk(m, c) } - for _, c := range []*cdp.Node{n.ContentDocument, n.TemplateContent} { + for _, c := range []*Node{n.ContentDocument, n.TemplateContent} { if c == nil { continue } @@ -217,8 +103,8 @@ func walk(m map[cdp.NodeID]*cdp.Node, n *cdp.Node) { } } -func setChildNodes(m map[cdp.NodeID]*cdp.Node, nodes []*cdp.Node) nodeOp { - return func(n *cdp.Node) { +func setChildNodes(m map[cdp.NodeID]*Node, nodes []*Node) nodeOp { + return func(n *Node) { n.Lock() n.Children = nodes n.Unlock() @@ -228,7 +114,7 @@ func setChildNodes(m map[cdp.NodeID]*cdp.Node, nodes []*cdp.Node) nodeOp { } func attributeModified(name, value string) nodeOp { - return func(n *cdp.Node) { + return func(n *Node) { n.Lock() defer n.Unlock() @@ -251,7 +137,7 @@ func attributeModified(name, value string) nodeOp { } func attributeRemoved(name string) nodeOp { - return func(n *cdp.Node) { + return func(n *Node) { n.Lock() defer n.Unlock() @@ -267,12 +153,12 @@ func attributeRemoved(name string) nodeOp { } func inlineStyleInvalidated(ids []cdp.NodeID) nodeOp { - return func(n *cdp.Node) { + return func(n *Node) { } } func characterDataModified(characterData string) nodeOp { - return func(n *cdp.Node) { + return func(n *Node) { n.Lock() defer n.Unlock() @@ -281,7 +167,7 @@ func characterDataModified(characterData string) nodeOp { } func childNodeCountUpdated(count int64) nodeOp { - return func(n *cdp.Node) { + return func(n *Node) { n.Lock() defer n.Unlock() @@ -289,8 +175,8 @@ func childNodeCountUpdated(count int64) nodeOp { } } -func childNodeInserted(m map[cdp.NodeID]*cdp.Node, prevID cdp.NodeID, c *cdp.Node) nodeOp { - return func(n *cdp.Node) { +func childNodeInserted(m map[cdp.NodeID]*Node, prevID cdp.NodeID, c *Node) nodeOp { + return func(n *Node) { n.Lock() n.Children = insertNode(n.Children, prevID, c) n.Unlock() @@ -299,8 +185,8 @@ func childNodeInserted(m map[cdp.NodeID]*cdp.Node, prevID cdp.NodeID, c *cdp.Nod } } -func childNodeRemoved(m map[cdp.NodeID]*cdp.Node, id cdp.NodeID) nodeOp { - return func(n *cdp.Node) { +func childNodeRemoved(m map[cdp.NodeID]*Node, id cdp.NodeID) nodeOp { + return func(n *Node) { n.Lock() defer n.Unlock() @@ -309,8 +195,8 @@ func childNodeRemoved(m map[cdp.NodeID]*cdp.Node, id cdp.NodeID) nodeOp { } } -func shadowRootPushed(m map[cdp.NodeID]*cdp.Node, c *cdp.Node) nodeOp { - return func(n *cdp.Node) { +func shadowRootPushed(m map[cdp.NodeID]*Node, c *Node) nodeOp { + return func(n *Node) { n.Lock() n.ShadowRoots = append(n.ShadowRoots, c) n.Unlock() @@ -319,8 +205,8 @@ func shadowRootPushed(m map[cdp.NodeID]*cdp.Node, c *cdp.Node) nodeOp { } } -func shadowRootPopped(m map[cdp.NodeID]*cdp.Node, id cdp.NodeID) nodeOp { - return func(n *cdp.Node) { +func shadowRootPopped(m map[cdp.NodeID]*Node, id cdp.NodeID) nodeOp { + return func(n *Node) { n.Lock() defer n.Unlock() @@ -329,8 +215,8 @@ func shadowRootPopped(m map[cdp.NodeID]*cdp.Node, id cdp.NodeID) nodeOp { } } -func pseudoElementAdded(m map[cdp.NodeID]*cdp.Node, c *cdp.Node) nodeOp { - return func(n *cdp.Node) { +func pseudoElementAdded(m map[cdp.NodeID]*Node, c *Node) nodeOp { + return func(n *Node) { n.Lock() n.PseudoElements = append(n.PseudoElements, c) n.Unlock() @@ -339,8 +225,8 @@ func pseudoElementAdded(m map[cdp.NodeID]*cdp.Node, c *cdp.Node) nodeOp { } } -func pseudoElementRemoved(m map[cdp.NodeID]*cdp.Node, id cdp.NodeID) nodeOp { - return func(n *cdp.Node) { +func pseudoElementRemoved(m map[cdp.NodeID]*Node, id cdp.NodeID) nodeOp { + return func(n *Node) { n.Lock() defer n.Unlock() @@ -350,7 +236,7 @@ func pseudoElementRemoved(m map[cdp.NodeID]*cdp.Node, id cdp.NodeID) nodeOp { } func distributedNodesUpdated(nodes []*cdp.BackendNode) nodeOp { - return func(n *cdp.Node) { + return func(n *Node) { n.Lock() defer n.Unlock() @@ -358,12 +244,43 @@ func distributedNodesUpdated(nodes []*cdp.BackendNode) nodeOp { } } -func scrollableFlagUpdated(m map[cdp.NodeID]*cdp.Node, id cdp.NodeID) nodeOp { - return func(n *cdp.Node) { +func scrollableFlagUpdated(isScrollable bool) nodeOp { + return func(n *Node) { + n.Lock() + defer n.Unlock() + + n.IsScrollable = isScrollable + } +} + +func adRelatedStateUpdated(provenance *cdp.AdProvenance) nodeOp { + return func(n *Node) { + n.Lock() + defer n.Unlock() + + n.AdProvenance = provenance + } +} + +func adoptedStyleSheetsModified(ids []cdp.StyleSheetID) nodeOp { + return func(n *Node) { + n.Lock() + defer n.Unlock() + + n.AdoptedStyleSheets = ids + } +} + +func affectedByStartingStylesFlagUpdated(affected bool) nodeOp { + return func(n *Node) { + n.Lock() + defer n.Unlock() + + n.AffectedByStartingStyles = affected } } -func insertNode(n []*cdp.Node, prevID cdp.NodeID, c *cdp.Node) []*cdp.Node { +func insertNode(n []*Node, prevID cdp.NodeID, c *Node) []*Node { var i int var found bool for ; i < len(n); i++ { @@ -374,7 +291,7 @@ func insertNode(n []*cdp.Node, prevID cdp.NodeID, c *cdp.Node) []*cdp.Node { } if !found { - return append([]*cdp.Node{c}, n...) + return append([]*Node{c}, n...) } i++ @@ -385,7 +302,7 @@ func insertNode(n []*cdp.Node, prevID cdp.NodeID, c *cdp.Node) []*cdp.Node { return n } -func removeNode(n []*cdp.Node, id cdp.NodeID) []*cdp.Node { +func removeNode(n []*Node, id cdp.NodeID) []*Node { if len(n) == 0 { return n } @@ -412,3 +329,9 @@ func isCouldNotComputeBoxModelError(err error) bool { e, ok := err.(*cdproto.Error) return ok && e.Code == -32000 && e.Message == "Could not compute box model." } + +// ptr returns a pointer to a copy of v. It sets the optional fields of the +// protocol types, which are pointers. +func ptr[T any](v T) *T { + return &v +} diff --git a/vendor/github.com/chromedp/sysutil/.travis.yml b/vendor/github.com/chromedp/sysutil/.travis.yml deleted file mode 100644 index aea88dca6..000000000 --- a/vendor/github.com/chromedp/sysutil/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -dist: bionic -language: go -go: - - 1.13.x -script: - - go test -v -coverprofile=coverage.out diff --git a/vendor/github.com/chromedp/sysutil/LICENSE b/vendor/github.com/chromedp/sysutil/LICENSE deleted file mode 100644 index 8e2e6c25e..000000000 --- a/vendor/github.com/chromedp/sysutil/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016-2017 Kenneth Shaw - -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/vendor/github.com/chromedp/sysutil/README.md b/vendor/github.com/chromedp/sysutil/README.md deleted file mode 100644 index 578d0f40e..000000000 --- a/vendor/github.com/chromedp/sysutil/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# About sysutil - -Package sysutil provides some utilities for working with cross platform -systems. - -Inspired by the Go version of Sigar, but written to be "idiomatic" Go. diff --git a/vendor/github.com/chromedp/sysutil/sysutil.go b/vendor/github.com/chromedp/sysutil/sysutil.go deleted file mode 100644 index ae8505718..000000000 --- a/vendor/github.com/chromedp/sysutil/sysutil.go +++ /dev/null @@ -1,17 +0,0 @@ -package sysutil - -import ( - "time" -) - -var btime time.Time - -// BootTime returns the time the system was started. -func BootTime() time.Time { - return btime -} - -// Uptime returns the duration the system has been up. -func Uptime() time.Duration { - return time.Since(btime) -} diff --git a/vendor/github.com/chromedp/sysutil/sysutil_bsd.go b/vendor/github.com/chromedp/sysutil/sysutil_bsd.go deleted file mode 100644 index c6c74483e..000000000 --- a/vendor/github.com/chromedp/sysutil/sysutil_bsd.go +++ /dev/null @@ -1,26 +0,0 @@ -//go:build darwin || freebsd || openbsd || netbsd - -package sysutil - -import ( - "bytes" - "encoding/binary" - "syscall" - "time" -) - -func init() { - // get boot time - res, err := syscall.Sysctl("kern.boottime") - if err != nil { - btime = time.Now() - return - } - // decode - var t timeval - if err = binary.Read(bytes.NewBuffer([]byte(res)), binary.LittleEndian, &t); err != nil { - btime = time.Now() - return - } - btime = time.Unix(int64(t.Sec), int64(t.Usec)) -} diff --git a/vendor/github.com/chromedp/sysutil/sysutil_linux.go b/vendor/github.com/chromedp/sysutil/sysutil_linux.go deleted file mode 100644 index e1b02c82a..000000000 --- a/vendor/github.com/chromedp/sysutil/sysutil_linux.go +++ /dev/null @@ -1,34 +0,0 @@ -//go:build linux - -package sysutil - -import ( - "bytes" - "os" - "strconv" - "time" -) - -var ( - btimePrefix = []byte("btime ") - lineEnd = []byte("\n") -) - -func init() { - buf, err := os.ReadFile("/proc/stat") - if err != nil { - btime = time.Now() - return - } - for _, line := range bytes.SplitN(buf, lineEnd, -1) { - if bytes.HasPrefix(line, btimePrefix) { - t, err := strconv.ParseInt(string(line[len(btimePrefix):]), 10, 64) - if err != nil { - btime = time.Now() - return - } - btime = time.Unix(t, 0) - break - } - } -} diff --git a/vendor/github.com/chromedp/sysutil/sysutil_other.go b/vendor/github.com/chromedp/sysutil/sysutil_other.go deleted file mode 100644 index 8dc93318c..000000000 --- a/vendor/github.com/chromedp/sysutil/sysutil_other.go +++ /dev/null @@ -1,9 +0,0 @@ -//go:build !linux && !windows && !darwin && !freebsd && !openbsd && !netbsd - -package sysutil - -import "time" - -func init() { - btime = time.Now() -} diff --git a/vendor/github.com/chromedp/sysutil/sysutil_windows.go b/vendor/github.com/chromedp/sysutil/sysutil_windows.go deleted file mode 100644 index cc58491a8..000000000 --- a/vendor/github.com/chromedp/sysutil/sysutil_windows.go +++ /dev/null @@ -1,22 +0,0 @@ -//go:build windows - -package sysutil - -import ( - "syscall" - "time" -) - -var ( - kernel32DLL = syscall.MustLoadDLL("kernel32") - procGetTickCount64 = kernel32DLL.MustFindProc("GetTickCount64") -) - -func init() { - res, _, err := syscall.Syscall(procGetTickCount64.Addr(), 0, 0, 0, 0) - if err != 0 { - btime = time.Now() - return - } - btime = time.Now().Add(time.Duration(-res) * time.Millisecond) -} diff --git a/vendor/github.com/chromedp/sysutil/timeval.go b/vendor/github.com/chromedp/sysutil/timeval.go deleted file mode 100644 index 63e0c6222..000000000 --- a/vendor/github.com/chromedp/sysutil/timeval.go +++ /dev/null @@ -1,9 +0,0 @@ -//go:build openbsd || netbsd - -package sysutil - -import ( - "syscall" -) - -type timeval syscall.Timeval diff --git a/vendor/github.com/chromedp/sysutil/timeval32.go b/vendor/github.com/chromedp/sysutil/timeval32.go deleted file mode 100644 index d8ce8e32d..000000000 --- a/vendor/github.com/chromedp/sysutil/timeval32.go +++ /dev/null @@ -1,8 +0,0 @@ -//go:build darwin || freebsd - -package sysutil - -type timeval struct { - Sec int32 - Usec int32 -} diff --git a/vendor/github.com/gobwas/httphead/LICENSE b/vendor/github.com/gobwas/httphead/LICENSE deleted file mode 100644 index 274431766..000000000 --- a/vendor/github.com/gobwas/httphead/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2017 Sergey Kamardin - -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/vendor/github.com/gobwas/httphead/README.md b/vendor/github.com/gobwas/httphead/README.md deleted file mode 100644 index 67a97fdbe..000000000 --- a/vendor/github.com/gobwas/httphead/README.md +++ /dev/null @@ -1,63 +0,0 @@ -# httphead.[go](https://golang.org) - -[![GoDoc][godoc-image]][godoc-url] - -> Tiny HTTP header value parsing library in go. - -## Overview - -This library contains low-level functions for scanning HTTP RFC2616 compatible header value grammars. - -## Install - -```shell - go get github.com/gobwas/httphead -``` - -## Example - -The example below shows how multiple-choise HTTP header value could be parsed with this library: - -```go - options, ok := httphead.ParseOptions([]byte(`foo;bar=1,baz`), nil) - fmt.Println(options, ok) - // Output: [{foo map[bar:1]} {baz map[]}] true -``` - -The low-level example below shows how to optimize keys skipping and selection -of some key: - -```go - // The right part of full header line like: - // X-My-Header: key;foo=bar;baz,key;baz - header := []byte(`foo;a=0,foo;a=1,foo;a=2,foo;a=3`) - - // We want to search key "foo" with an "a" parameter that equal to "2". - var ( - foo = []byte(`foo`) - a = []byte(`a`) - v = []byte(`2`) - ) - var found bool - httphead.ScanOptions(header, func(i int, key, param, value []byte) Control { - if !bytes.Equal(key, foo) { - return ControlSkip - } - if !bytes.Equal(param, a) { - if bytes.Equal(value, v) { - // Found it! - found = true - return ControlBreak - } - return ControlSkip - } - return ControlContinue - }) -``` - -For more usage examples please see [docs][godoc-url] or package tests. - -[godoc-image]: https://godoc.org/github.com/gobwas/httphead?status.svg -[godoc-url]: https://godoc.org/github.com/gobwas/httphead -[travis-image]: https://travis-ci.org/gobwas/httphead.svg?branch=master -[travis-url]: https://travis-ci.org/gobwas/httphead diff --git a/vendor/github.com/gobwas/httphead/cookie.go b/vendor/github.com/gobwas/httphead/cookie.go deleted file mode 100644 index 05c9a1fb6..000000000 --- a/vendor/github.com/gobwas/httphead/cookie.go +++ /dev/null @@ -1,200 +0,0 @@ -package httphead - -import ( - "bytes" -) - -// ScanCookie scans cookie pairs from data using DefaultCookieScanner.Scan() -// method. -func ScanCookie(data []byte, it func(key, value []byte) bool) bool { - return DefaultCookieScanner.Scan(data, it) -} - -// DefaultCookieScanner is a CookieScanner which is used by ScanCookie(). -// Note that it is intended to have the same behavior as http.Request.Cookies() -// has. -var DefaultCookieScanner = CookieScanner{} - -// CookieScanner contains options for scanning cookie pairs. -// See https://tools.ietf.org/html/rfc6265#section-4.1.1 -type CookieScanner struct { - // DisableNameValidation disables name validation of a cookie. If false, - // only RFC2616 "tokens" are accepted. - DisableNameValidation bool - - // DisableValueValidation disables value validation of a cookie. If false, - // only RFC6265 "cookie-octet" characters are accepted. - // - // Note that Strict option also affects validation of a value. - // - // If Strict is false, then scanner begins to allow space and comma - // characters inside the value for better compatibility with non standard - // cookies implementations. - DisableValueValidation bool - - // BreakOnPairError sets scanner to immediately return after first pair syntax - // validation error. - // If false, scanner will try to skip invalid pair bytes and go ahead. - BreakOnPairError bool - - // Strict enables strict RFC6265 mode scanning. It affects name and value - // validation, as also some other rules. - // If false, it is intended to bring the same behavior as - // http.Request.Cookies(). - Strict bool -} - -// Scan maps data to name and value pairs. Usually data represents value of the -// Cookie header. -func (c CookieScanner) Scan(data []byte, it func(name, value []byte) bool) bool { - lexer := &Scanner{data: data} - - const ( - statePair = iota - stateBefore - ) - - state := statePair - - for lexer.Buffered() > 0 { - switch state { - case stateBefore: - // Pairs separated by ";" and space, according to the RFC6265: - // cookie-pair *( ";" SP cookie-pair ) - // - // Cookie pairs MUST be separated by (";" SP). So our only option - // here is to fail as syntax error. - a, b := lexer.Peek2() - if a != ';' { - return false - } - - state = statePair - - advance := 1 - if b == ' ' { - advance++ - } else if c.Strict { - return false - } - - lexer.Advance(advance) - - case statePair: - if !lexer.FetchUntil(';') { - return false - } - - var value []byte - name := lexer.Bytes() - if i := bytes.IndexByte(name, '='); i != -1 { - value = name[i+1:] - name = name[:i] - } else if c.Strict { - if !c.BreakOnPairError { - goto nextPair - } - return false - } - - if !c.Strict { - trimLeft(name) - } - if !c.DisableNameValidation && !ValidCookieName(name) { - if !c.BreakOnPairError { - goto nextPair - } - return false - } - - if !c.Strict { - value = trimRight(value) - } - value = stripQuotes(value) - if !c.DisableValueValidation && !ValidCookieValue(value, c.Strict) { - if !c.BreakOnPairError { - goto nextPair - } - return false - } - - if !it(name, value) { - return true - } - - nextPair: - state = stateBefore - } - } - - return true -} - -// ValidCookieValue reports whether given value is a valid RFC6265 -// "cookie-octet" bytes. -// -// cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E -// ; US-ASCII characters excluding CTLs, -// ; whitespace DQUOTE, comma, semicolon, -// ; and backslash -// -// Note that the false strict parameter disables errors on space 0x20 and comma -// 0x2c. This could be useful to bring some compatibility with non-compliant -// clients/servers in the real world. -// It acts the same as standard library cookie parser if strict is false. -func ValidCookieValue(value []byte, strict bool) bool { - if len(value) == 0 { - return true - } - for _, c := range value { - switch c { - case '"', ';', '\\': - return false - case ',', ' ': - if strict { - return false - } - default: - if c <= 0x20 { - return false - } - if c >= 0x7f { - return false - } - } - } - return true -} - -// ValidCookieName reports wheter given bytes is a valid RFC2616 "token" bytes. -func ValidCookieName(name []byte) bool { - for _, c := range name { - if !OctetTypes[c].IsToken() { - return false - } - } - return true -} - -func stripQuotes(bts []byte) []byte { - if last := len(bts) - 1; last > 0 && bts[0] == '"' && bts[last] == '"' { - return bts[1:last] - } - return bts -} - -func trimLeft(p []byte) []byte { - var i int - for i < len(p) && OctetTypes[p[i]].IsSpace() { - i++ - } - return p[i:] -} - -func trimRight(p []byte) []byte { - j := len(p) - for j > 0 && OctetTypes[p[j-1]].IsSpace() { - j-- - } - return p[:j] -} diff --git a/vendor/github.com/gobwas/httphead/head.go b/vendor/github.com/gobwas/httphead/head.go deleted file mode 100644 index a50e907dd..000000000 --- a/vendor/github.com/gobwas/httphead/head.go +++ /dev/null @@ -1,275 +0,0 @@ -package httphead - -import ( - "bufio" - "bytes" -) - -// Version contains protocol major and minor version. -type Version struct { - Major int - Minor int -} - -// RequestLine contains parameters parsed from the first request line. -type RequestLine struct { - Method []byte - URI []byte - Version Version -} - -// ResponseLine contains parameters parsed from the first response line. -type ResponseLine struct { - Version Version - Status int - Reason []byte -} - -// SplitRequestLine splits given slice of bytes into three chunks without -// parsing. -func SplitRequestLine(line []byte) (method, uri, version []byte) { - return split3(line, ' ') -} - -// ParseRequestLine parses http request line like "GET / HTTP/1.0". -func ParseRequestLine(line []byte) (r RequestLine, ok bool) { - var i int - for i = 0; i < len(line); i++ { - c := line[i] - if !OctetTypes[c].IsToken() { - if i > 0 && c == ' ' { - break - } - return - } - } - if i == len(line) { - return - } - - var proto []byte - r.Method = line[:i] - r.URI, proto = split2(line[i+1:], ' ') - if len(r.URI) == 0 { - return - } - if major, minor, ok := ParseVersion(proto); ok { - r.Version.Major = major - r.Version.Minor = minor - return r, true - } - - return r, false -} - -// SplitResponseLine splits given slice of bytes into three chunks without -// parsing. -func SplitResponseLine(line []byte) (version, status, reason []byte) { - return split3(line, ' ') -} - -// ParseResponseLine parses first response line into ResponseLine struct. -func ParseResponseLine(line []byte) (r ResponseLine, ok bool) { - var ( - proto []byte - status []byte - ) - proto, status, r.Reason = split3(line, ' ') - if major, minor, ok := ParseVersion(proto); ok { - r.Version.Major = major - r.Version.Minor = minor - } else { - return r, false - } - if n, ok := IntFromASCII(status); ok { - r.Status = n - } else { - return r, false - } - // TODO(gobwas): parse here r.Reason fot TEXT rule: - // TEXT = <any OCTET except CTLs, - // but including LWS> - return r, true -} - -var ( - httpVersion10 = []byte("HTTP/1.0") - httpVersion11 = []byte("HTTP/1.1") - httpVersionPrefix = []byte("HTTP/") -) - -// ParseVersion parses major and minor version of HTTP protocol. -// It returns parsed values and true if parse is ok. -func ParseVersion(bts []byte) (major, minor int, ok bool) { - switch { - case bytes.Equal(bts, httpVersion11): - return 1, 1, true - case bytes.Equal(bts, httpVersion10): - return 1, 0, true - case len(bts) < 8: - return - case !bytes.Equal(bts[:5], httpVersionPrefix): - return - } - - bts = bts[5:] - - dot := bytes.IndexByte(bts, '.') - if dot == -1 { - return - } - major, ok = IntFromASCII(bts[:dot]) - if !ok { - return - } - minor, ok = IntFromASCII(bts[dot+1:]) - if !ok { - return - } - - return major, minor, true -} - -// ReadLine reads line from br. It reads until '\n' and returns bytes without -// '\n' or '\r\n' at the end. -// It returns err if and only if line does not end in '\n'. Note that read -// bytes returned in any case of error. -// -// It is much like the textproto/Reader.ReadLine() except the thing that it -// returns raw bytes, instead of string. That is, it avoids copying bytes read -// from br. -// -// textproto/Reader.ReadLineBytes() is also makes copy of resulting bytes to be -// safe with future I/O operations on br. -// -// We could control I/O operations on br and do not need to make additional -// copy for safety. -func ReadLine(br *bufio.Reader) ([]byte, error) { - var line []byte - for { - bts, err := br.ReadSlice('\n') - if err == bufio.ErrBufferFull { - // Copy bytes because next read will discard them. - line = append(line, bts...) - continue - } - // Avoid copy of single read. - if line == nil { - line = bts - } else { - line = append(line, bts...) - } - if err != nil { - return line, err - } - // Size of line is at least 1. - // In other case bufio.ReadSlice() returns error. - n := len(line) - // Cut '\n' or '\r\n'. - if n > 1 && line[n-2] == '\r' { - line = line[:n-2] - } else { - line = line[:n-1] - } - return line, nil - } -} - -// ParseHeaderLine parses HTTP header as key-value pair. It returns parsed -// values and true if parse is ok. -func ParseHeaderLine(line []byte) (k, v []byte, ok bool) { - colon := bytes.IndexByte(line, ':') - if colon == -1 { - return - } - k = trim(line[:colon]) - for _, c := range k { - if !OctetTypes[c].IsToken() { - return nil, nil, false - } - } - v = trim(line[colon+1:]) - return k, v, true -} - -// IntFromASCII converts ascii encoded decimal numeric value from HTTP entities -// to an integer. -func IntFromASCII(bts []byte) (ret int, ok bool) { - // ASCII numbers all start with the high-order bits 0011. - // If you see that, and the next bits are 0-9 (0000 - 1001) you can grab those - // bits and interpret them directly as an integer. - var n int - if n = len(bts); n < 1 { - return 0, false - } - for i := 0; i < n; i++ { - if bts[i]&0xf0 != 0x30 { - return 0, false - } - ret += int(bts[i]&0xf) * pow(10, n-i-1) - } - return ret, true -} - -const ( - toLower = 'a' - 'A' // for use with OR. - toUpper = ^byte(toLower) // for use with AND. -) - -// CanonicalizeHeaderKey is like standard textproto/CanonicalMIMEHeaderKey, -// except that it operates with slice of bytes and modifies it inplace without -// copying. -func CanonicalizeHeaderKey(k []byte) { - upper := true - for i, c := range k { - if upper && 'a' <= c && c <= 'z' { - k[i] &= toUpper - } else if !upper && 'A' <= c && c <= 'Z' { - k[i] |= toLower - } - upper = c == '-' - } -} - -// pow for integers implementation. -// See Donald Knuth, The Art of Computer Programming, Volume 2, Section 4.6.3 -func pow(a, b int) int { - p := 1 - for b > 0 { - if b&1 != 0 { - p *= a - } - b >>= 1 - a *= a - } - return p -} - -func split3(p []byte, sep byte) (p1, p2, p3 []byte) { - a := bytes.IndexByte(p, sep) - b := bytes.IndexByte(p[a+1:], sep) - if a == -1 || b == -1 { - return p, nil, nil - } - b += a + 1 - return p[:a], p[a+1 : b], p[b+1:] -} - -func split2(p []byte, sep byte) (p1, p2 []byte) { - i := bytes.IndexByte(p, sep) - if i == -1 { - return p, nil - } - return p[:i], p[i+1:] -} - -func trim(p []byte) []byte { - var i, j int - for i = 0; i < len(p) && (p[i] == ' ' || p[i] == '\t'); { - i++ - } - for j = len(p); j > i && (p[j-1] == ' ' || p[j-1] == '\t'); { - j-- - } - return p[i:j] -} diff --git a/vendor/github.com/gobwas/httphead/httphead.go b/vendor/github.com/gobwas/httphead/httphead.go deleted file mode 100644 index 2387e8033..000000000 --- a/vendor/github.com/gobwas/httphead/httphead.go +++ /dev/null @@ -1,331 +0,0 @@ -// Package httphead contains utils for parsing HTTP and HTTP-grammar compatible -// text protocols headers. -// -// That is, this package first aim is to bring ability to easily parse -// constructions, described here https://tools.ietf.org/html/rfc2616#section-2 -package httphead - -import ( - "bytes" - "strings" -) - -// ScanTokens parses data in this form: -// -// list = 1#token -// -// It returns false if data is malformed. -func ScanTokens(data []byte, it func([]byte) bool) bool { - lexer := &Scanner{data: data} - - var ok bool - for lexer.Next() { - switch lexer.Type() { - case ItemToken: - ok = true - if !it(lexer.Bytes()) { - return true - } - case ItemSeparator: - if !isComma(lexer.Bytes()) { - return false - } - default: - return false - } - } - - return ok && !lexer.err -} - -// ParseOptions parses all header options and appends it to given slice of -// Option. It returns flag of successful (wellformed input) parsing. -// -// Note that appended options are all consist of subslices of data. That is, -// mutation of data will mutate appended options. -func ParseOptions(data []byte, options []Option) ([]Option, bool) { - var i int - index := -1 - return options, ScanOptions(data, func(idx int, name, attr, val []byte) Control { - if idx != index { - index = idx - i = len(options) - options = append(options, Option{Name: name}) - } - if attr != nil { - options[i].Parameters.Set(attr, val) - } - return ControlContinue - }) -} - -// SelectFlag encodes way of options selection. -type SelectFlag byte - -// String represetns flag as string. -func (f SelectFlag) String() string { - var flags [2]string - var n int - if f&SelectCopy != 0 { - flags[n] = "copy" - n++ - } - if f&SelectUnique != 0 { - flags[n] = "unique" - n++ - } - return "[" + strings.Join(flags[:n], "|") + "]" -} - -const ( - // SelectCopy causes selector to copy selected option before appending it - // to resulting slice. - // If SelectCopy flag is not passed to selector, then appended options will - // contain sub-slices of the initial data. - SelectCopy SelectFlag = 1 << iota - - // SelectUnique causes selector to append only not yet existing option to - // resulting slice. Unique is checked by comparing option names. - SelectUnique -) - -// OptionSelector contains configuration for selecting Options from header value. -type OptionSelector struct { - // Check is a filter function that applied to every Option that possibly - // could be selected. - // If Check is nil all options will be selected. - Check func(Option) bool - - // Flags contains flags for options selection. - Flags SelectFlag - - // Alloc used to allocate slice of bytes when selector is configured with - // SelectCopy flag. It will be called with number of bytes needed for copy - // of single Option. - // If Alloc is nil make is used. - Alloc func(n int) []byte -} - -// Select parses header data and appends it to given slice of Option. -// It also returns flag of successful (wellformed input) parsing. -func (s OptionSelector) Select(data []byte, options []Option) ([]Option, bool) { - var current Option - var has bool - index := -1 - - alloc := s.Alloc - if alloc == nil { - alloc = defaultAlloc - } - check := s.Check - if check == nil { - check = defaultCheck - } - - ok := ScanOptions(data, func(idx int, name, attr, val []byte) Control { - if idx != index { - if has && check(current) { - if s.Flags&SelectCopy != 0 { - current = current.Copy(alloc(current.Size())) - } - options = append(options, current) - has = false - } - if s.Flags&SelectUnique != 0 { - for i := len(options) - 1; i >= 0; i-- { - if bytes.Equal(options[i].Name, name) { - return ControlSkip - } - } - } - index = idx - current = Option{Name: name} - has = true - } - if attr != nil { - current.Parameters.Set(attr, val) - } - - return ControlContinue - }) - if has && check(current) { - if s.Flags&SelectCopy != 0 { - current = current.Copy(alloc(current.Size())) - } - options = append(options, current) - } - - return options, ok -} - -func defaultAlloc(n int) []byte { return make([]byte, n) } -func defaultCheck(Option) bool { return true } - -// Control represents operation that scanner should perform. -type Control byte - -const ( - // ControlContinue causes scanner to continue scan tokens. - ControlContinue Control = iota - // ControlBreak causes scanner to stop scan tokens. - ControlBreak - // ControlSkip causes scanner to skip current entity. - ControlSkip -) - -// ScanOptions parses data in this form: -// -// values = 1#value -// value = token *( ";" param ) -// param = token [ "=" (token | quoted-string) ] -// -// It calls given callback with the index of the option, option itself and its -// parameter (attribute and its value, both could be nil). Index is useful when -// header contains multiple choises for the same named option. -// -// Given callback should return one of the defined Control* values. -// ControlSkip means that passed key is not in caller's interest. That is, all -// parameters of that key will be skipped. -// ControlBreak means that no more keys and parameters should be parsed. That -// is, it must break parsing immediately. -// ControlContinue means that caller want to receive next parameter and its -// value or the next key. -// -// It returns false if data is malformed. -func ScanOptions(data []byte, it func(index int, option, attribute, value []byte) Control) bool { - lexer := &Scanner{data: data} - - var ok bool - var state int - const ( - stateKey = iota - stateParamBeforeName - stateParamName - stateParamBeforeValue - stateParamValue - ) - - var ( - index int - key, param, value []byte - mustCall bool - ) - for lexer.Next() { - var ( - call bool - growIndex int - ) - - t := lexer.Type() - v := lexer.Bytes() - - switch t { - case ItemToken: - switch state { - case stateKey, stateParamBeforeName: - key = v - state = stateParamBeforeName - mustCall = true - case stateParamName: - param = v - state = stateParamBeforeValue - mustCall = true - case stateParamValue: - value = v - state = stateParamBeforeName - call = true - default: - return false - } - - case ItemString: - if state != stateParamValue { - return false - } - value = v - state = stateParamBeforeName - call = true - - case ItemSeparator: - switch { - case isComma(v) && state == stateKey: - // Nothing to do. - - case isComma(v) && state == stateParamBeforeName: - state = stateKey - // Make call only if we have not called this key yet. - call = mustCall - if !call { - // If we have already called callback with the key - // that just ended. - index++ - } else { - // Else grow the index after calling callback. - growIndex = 1 - } - - case isComma(v) && state == stateParamBeforeValue: - state = stateKey - growIndex = 1 - call = true - - case isSemicolon(v) && state == stateParamBeforeName: - state = stateParamName - - case isSemicolon(v) && state == stateParamBeforeValue: - state = stateParamName - call = true - - case isEquality(v) && state == stateParamBeforeValue: - state = stateParamValue - - default: - return false - } - - default: - return false - } - - if call { - switch it(index, key, param, value) { - case ControlBreak: - // User want to stop to parsing parameters. - return true - - case ControlSkip: - // User want to skip current param. - state = stateKey - lexer.SkipEscaped(',') - - case ControlContinue: - // User is interested in rest of parameters. - // Nothing to do. - - default: - panic("unexpected control value") - } - ok = true - param = nil - value = nil - mustCall = false - index += growIndex - } - } - if mustCall { - ok = true - it(index, key, param, value) - } - - return ok && !lexer.err -} - -func isComma(b []byte) bool { - return len(b) == 1 && b[0] == ',' -} -func isSemicolon(b []byte) bool { - return len(b) == 1 && b[0] == ';' -} -func isEquality(b []byte) bool { - return len(b) == 1 && b[0] == '=' -} diff --git a/vendor/github.com/gobwas/httphead/lexer.go b/vendor/github.com/gobwas/httphead/lexer.go deleted file mode 100644 index 729855ed0..000000000 --- a/vendor/github.com/gobwas/httphead/lexer.go +++ /dev/null @@ -1,360 +0,0 @@ -package httphead - -import ( - "bytes" -) - -// ItemType encodes type of the lexing token. -type ItemType int - -const ( - // ItemUndef reports that token is undefined. - ItemUndef ItemType = iota - // ItemToken reports that token is RFC2616 token. - ItemToken - // ItemSeparator reports that token is RFC2616 separator. - ItemSeparator - // ItemString reports that token is RFC2616 quouted string. - ItemString - // ItemComment reports that token is RFC2616 comment. - ItemComment - // ItemOctet reports that token is octet slice. - ItemOctet -) - -// Scanner represents header tokens scanner. -// See https://tools.ietf.org/html/rfc2616#section-2 -type Scanner struct { - data []byte - pos int - - itemType ItemType - itemBytes []byte - - err bool -} - -// NewScanner creates new RFC2616 data scanner. -func NewScanner(data []byte) *Scanner { - return &Scanner{data: data} -} - -// Next scans for next token. It returns true on successful scanning, and false -// on error or EOF. -func (l *Scanner) Next() bool { - c, ok := l.nextChar() - if !ok { - return false - } - switch c { - case '"': // quoted-string; - return l.fetchQuotedString() - - case '(': // comment; - return l.fetchComment() - - case '\\', ')': // unexpected chars; - l.err = true - return false - - default: - return l.fetchToken() - } -} - -// FetchUntil fetches ItemOctet from current scanner position to first -// occurence of the c or to the end of the underlying data. -func (l *Scanner) FetchUntil(c byte) bool { - l.resetItem() - if l.pos == len(l.data) { - return false - } - return l.fetchOctet(c) -} - -// Peek reads byte at current position without advancing it. On end of data it -// returns 0. -func (l *Scanner) Peek() byte { - if l.pos == len(l.data) { - return 0 - } - return l.data[l.pos] -} - -// Peek2 reads two first bytes at current position without advancing it. -// If there not enough data it returs 0. -func (l *Scanner) Peek2() (a, b byte) { - if l.pos == len(l.data) { - return 0, 0 - } - if l.pos+1 == len(l.data) { - return l.data[l.pos], 0 - } - return l.data[l.pos], l.data[l.pos+1] -} - -// Buffered reporst how many bytes there are left to scan. -func (l *Scanner) Buffered() int { - return len(l.data) - l.pos -} - -// Advance moves current position index at n bytes. It returns true on -// successful move. -func (l *Scanner) Advance(n int) bool { - l.pos += n - if l.pos > len(l.data) { - l.pos = len(l.data) - return false - } - return true -} - -// Skip skips all bytes until first occurence of c. -func (l *Scanner) Skip(c byte) { - if l.err { - return - } - // Reset scanner state. - l.resetItem() - - if i := bytes.IndexByte(l.data[l.pos:], c); i == -1 { - // Reached the end of data. - l.pos = len(l.data) - } else { - l.pos += i + 1 - } -} - -// SkipEscaped skips all bytes until first occurence of non-escaped c. -func (l *Scanner) SkipEscaped(c byte) { - if l.err { - return - } - // Reset scanner state. - l.resetItem() - - if i := ScanUntil(l.data[l.pos:], c); i == -1 { - // Reached the end of data. - l.pos = len(l.data) - } else { - l.pos += i + 1 - } -} - -// Type reports current token type. -func (l *Scanner) Type() ItemType { - return l.itemType -} - -// Bytes returns current token bytes. -func (l *Scanner) Bytes() []byte { - return l.itemBytes -} - -func (l *Scanner) nextChar() (byte, bool) { - // Reset scanner state. - l.resetItem() - - if l.err { - return 0, false - } - l.pos += SkipSpace(l.data[l.pos:]) - if l.pos == len(l.data) { - return 0, false - } - return l.data[l.pos], true -} - -func (l *Scanner) resetItem() { - l.itemType = ItemUndef - l.itemBytes = nil -} - -func (l *Scanner) fetchOctet(c byte) bool { - i := l.pos - if j := bytes.IndexByte(l.data[l.pos:], c); j == -1 { - // Reached the end of data. - l.pos = len(l.data) - } else { - l.pos += j - } - - l.itemType = ItemOctet - l.itemBytes = l.data[i:l.pos] - - return true -} - -func (l *Scanner) fetchToken() bool { - n, t := ScanToken(l.data[l.pos:]) - if n == -1 { - l.err = true - return false - } - - l.itemType = t - l.itemBytes = l.data[l.pos : l.pos+n] - l.pos += n - - return true -} - -func (l *Scanner) fetchQuotedString() (ok bool) { - l.pos++ - - n := ScanUntil(l.data[l.pos:], '"') - if n == -1 { - l.err = true - return false - } - - l.itemType = ItemString - l.itemBytes = RemoveByte(l.data[l.pos:l.pos+n], '\\') - l.pos += n + 1 - - return true -} - -func (l *Scanner) fetchComment() (ok bool) { - l.pos++ - - n := ScanPairGreedy(l.data[l.pos:], '(', ')') - if n == -1 { - l.err = true - return false - } - - l.itemType = ItemComment - l.itemBytes = RemoveByte(l.data[l.pos:l.pos+n], '\\') - l.pos += n + 1 - - return true -} - -// ScanUntil scans for first non-escaped character c in given data. -// It returns index of matched c and -1 if c is not found. -func ScanUntil(data []byte, c byte) (n int) { - for { - i := bytes.IndexByte(data[n:], c) - if i == -1 { - return -1 - } - n += i - if n == 0 || data[n-1] != '\\' { - break - } - n++ - } - return -} - -// ScanPairGreedy scans for complete pair of opening and closing chars in greedy manner. -// Note that first opening byte must not be present in data. -func ScanPairGreedy(data []byte, open, close byte) (n int) { - var m int - opened := 1 - for { - i := bytes.IndexByte(data[n:], close) - if i == -1 { - return -1 - } - n += i - // If found index is not escaped then it is the end. - if n == 0 || data[n-1] != '\\' { - opened-- - } - - for m < i { - j := bytes.IndexByte(data[m:i], open) - if j == -1 { - break - } - m += j + 1 - opened++ - } - - if opened == 0 { - break - } - - n++ - m = n - } - return -} - -// RemoveByte returns data without c. If c is not present in data it returns -// the same slice. If not, it copies data without c. -func RemoveByte(data []byte, c byte) []byte { - j := bytes.IndexByte(data, c) - if j == -1 { - return data - } - - n := len(data) - 1 - - // If character is present, than allocate slice with n-1 capacity. That is, - // resulting bytes could be at most n-1 length. - result := make([]byte, n) - k := copy(result, data[:j]) - - for i := j + 1; i < n; { - j = bytes.IndexByte(data[i:], c) - if j != -1 { - k += copy(result[k:], data[i:i+j]) - i = i + j + 1 - } else { - k += copy(result[k:], data[i:]) - break - } - } - - return result[:k] -} - -// SkipSpace skips spaces and lws-sequences from p. -// It returns number ob bytes skipped. -func SkipSpace(p []byte) (n int) { - for len(p) > 0 { - switch { - case len(p) >= 3 && - p[0] == '\r' && - p[1] == '\n' && - OctetTypes[p[2]].IsSpace(): - p = p[3:] - n += 3 - case OctetTypes[p[0]].IsSpace(): - p = p[1:] - n++ - default: - return - } - } - return -} - -// ScanToken scan for next token in p. It returns length of the token and its -// type. It do not trim p. -func ScanToken(p []byte) (n int, t ItemType) { - if len(p) == 0 { - return 0, ItemUndef - } - - c := p[0] - switch { - case OctetTypes[c].IsSeparator(): - return 1, ItemSeparator - - case OctetTypes[c].IsToken(): - for n = 1; n < len(p); n++ { - c := p[n] - if !OctetTypes[c].IsToken() { - break - } - } - return n, ItemToken - - default: - return -1, ItemUndef - } -} diff --git a/vendor/github.com/gobwas/httphead/octet.go b/vendor/github.com/gobwas/httphead/octet.go deleted file mode 100644 index 2a04cdd09..000000000 --- a/vendor/github.com/gobwas/httphead/octet.go +++ /dev/null @@ -1,83 +0,0 @@ -package httphead - -// OctetType desribes character type. -// -// From the "Basic Rules" chapter of RFC2616 -// See https://tools.ietf.org/html/rfc2616#section-2.2 -// -// OCTET = <any 8-bit sequence of data> -// CHAR = <any US-ASCII character (octets 0 - 127)> -// UPALPHA = <any US-ASCII uppercase letter "A".."Z"> -// LOALPHA = <any US-ASCII lowercase letter "a".."z"> -// ALPHA = UPALPHA | LOALPHA -// DIGIT = <any US-ASCII digit "0".."9"> -// CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)> -// CR = <US-ASCII CR, carriage return (13)> -// LF = <US-ASCII LF, linefeed (10)> -// SP = <US-ASCII SP, space (32)> -// HT = <US-ASCII HT, horizontal-tab (9)> -// <"> = <US-ASCII double-quote mark (34)> -// CRLF = CR LF -// LWS = [CRLF] 1*( SP | HT ) -// -// Many HTTP/1.1 header field values consist of words separated by LWS -// or special characters. These special characters MUST be in a quoted -// string to be used within a parameter value (as defined in section -// 3.6). -// -// token = 1*<any CHAR except CTLs or separators> -// separators = "(" | ")" | "<" | ">" | "@" -// | "," | ";" | ":" | "\" | <"> -// | "/" | "[" | "]" | "?" | "=" -// | "{" | "}" | SP | HT -type OctetType byte - -// IsChar reports whether octet is CHAR. -func (t OctetType) IsChar() bool { return t&octetChar != 0 } - -// IsControl reports whether octet is CTL. -func (t OctetType) IsControl() bool { return t&octetControl != 0 } - -// IsSeparator reports whether octet is separator. -func (t OctetType) IsSeparator() bool { return t&octetSeparator != 0 } - -// IsSpace reports whether octet is space (SP or HT). -func (t OctetType) IsSpace() bool { return t&octetSpace != 0 } - -// IsToken reports whether octet is token. -func (t OctetType) IsToken() bool { return t&octetToken != 0 } - -const ( - octetChar OctetType = 1 << iota - octetControl - octetSpace - octetSeparator - octetToken -) - -// OctetTypes is a table of octets. -var OctetTypes [256]OctetType - -func init() { - for c := 32; c < 256; c++ { - var t OctetType - if c <= 127 { - t |= octetChar - } - if 0 <= c && c <= 31 || c == 127 { - t |= octetControl - } - switch c { - case '(', ')', '<', '>', '@', ',', ';', ':', '"', '/', '[', ']', '?', '=', '{', '}', '\\': - t |= octetSeparator - case ' ', '\t': - t |= octetSpace | octetSeparator - } - - if t.IsChar() && !t.IsControl() && !t.IsSeparator() && !t.IsSpace() { - t |= octetToken - } - - OctetTypes[c] = t - } -} diff --git a/vendor/github.com/gobwas/httphead/option.go b/vendor/github.com/gobwas/httphead/option.go deleted file mode 100644 index 0a18c7c7c..000000000 --- a/vendor/github.com/gobwas/httphead/option.go +++ /dev/null @@ -1,193 +0,0 @@ -package httphead - -import ( - "bytes" - "sort" -) - -// Option represents a header option. -type Option struct { - Name []byte - Parameters Parameters -} - -// Size returns number of bytes need to be allocated for use in opt.Copy. -func (opt Option) Size() int { - return len(opt.Name) + opt.Parameters.bytes -} - -// Copy copies all underlying []byte slices into p and returns new Option. -// Note that p must be at least of opt.Size() length. -func (opt Option) Copy(p []byte) Option { - n := copy(p, opt.Name) - opt.Name = p[:n] - opt.Parameters, p = opt.Parameters.Copy(p[n:]) - return opt -} - -// Clone is a shorthand for making slice of opt.Size() sequenced with Copy() -// call. -func (opt Option) Clone() Option { - return opt.Copy(make([]byte, opt.Size())) -} - -// String represents option as a string. -func (opt Option) String() string { - return "{" + string(opt.Name) + " " + opt.Parameters.String() + "}" -} - -// NewOption creates named option with given parameters. -func NewOption(name string, params map[string]string) Option { - p := Parameters{} - for k, v := range params { - p.Set([]byte(k), []byte(v)) - } - return Option{ - Name: []byte(name), - Parameters: p, - } -} - -// Equal reports whether option is equal to b. -func (opt Option) Equal(b Option) bool { - if bytes.Equal(opt.Name, b.Name) { - return opt.Parameters.Equal(b.Parameters) - } - return false -} - -// Parameters represents option's parameters. -type Parameters struct { - pos int - bytes int - arr [8]pair - dyn []pair -} - -// Equal reports whether a equal to b. -func (p Parameters) Equal(b Parameters) bool { - switch { - case p.dyn == nil && b.dyn == nil: - case p.dyn != nil && b.dyn != nil: - default: - return false - } - - ad, bd := p.data(), b.data() - if len(ad) != len(bd) { - return false - } - - sort.Sort(pairs(ad)) - sort.Sort(pairs(bd)) - - for i := 0; i < len(ad); i++ { - av, bv := ad[i], bd[i] - if !bytes.Equal(av.key, bv.key) || !bytes.Equal(av.value, bv.value) { - return false - } - } - return true -} - -// Size returns number of bytes that needed to copy p. -func (p *Parameters) Size() int { - return p.bytes -} - -// Copy copies all underlying []byte slices into dst and returns new -// Parameters. -// Note that dst must be at least of p.Size() length. -func (p *Parameters) Copy(dst []byte) (Parameters, []byte) { - ret := Parameters{ - pos: p.pos, - bytes: p.bytes, - } - if p.dyn != nil { - ret.dyn = make([]pair, len(p.dyn)) - for i, v := range p.dyn { - ret.dyn[i], dst = v.copy(dst) - } - } else { - for i, p := range p.arr { - ret.arr[i], dst = p.copy(dst) - } - } - return ret, dst -} - -// Get returns value by key and flag about existence such value. -func (p *Parameters) Get(key string) (value []byte, ok bool) { - for _, v := range p.data() { - if string(v.key) == key { - return v.value, true - } - } - return nil, false -} - -// Set sets value by key. -func (p *Parameters) Set(key, value []byte) { - p.bytes += len(key) + len(value) - - if p.pos < len(p.arr) { - p.arr[p.pos] = pair{key, value} - p.pos++ - return - } - - if p.dyn == nil { - p.dyn = make([]pair, len(p.arr), len(p.arr)+1) - copy(p.dyn, p.arr[:]) - } - p.dyn = append(p.dyn, pair{key, value}) -} - -// ForEach iterates over parameters key-value pairs and calls cb for each one. -func (p *Parameters) ForEach(cb func(k, v []byte) bool) { - for _, v := range p.data() { - if !cb(v.key, v.value) { - break - } - } -} - -// String represents parameters as a string. -func (p *Parameters) String() (ret string) { - ret = "[" - for i, v := range p.data() { - if i > 0 { - ret += " " - } - ret += string(v.key) + ":" + string(v.value) - } - return ret + "]" -} - -func (p *Parameters) data() []pair { - if p.dyn != nil { - return p.dyn - } - return p.arr[:p.pos] -} - -type pair struct { - key, value []byte -} - -func (p pair) copy(dst []byte) (pair, []byte) { - n := copy(dst, p.key) - p.key = dst[:n] - m := n + copy(dst[n:], p.value) - p.value = dst[n:m] - - dst = dst[m:] - - return p, dst -} - -type pairs []pair - -func (p pairs) Len() int { return len(p) } -func (p pairs) Less(a, b int) bool { return bytes.Compare(p[a].key, p[b].key) == -1 } -func (p pairs) Swap(a, b int) { p[a], p[b] = p[b], p[a] } diff --git a/vendor/github.com/gobwas/httphead/writer.go b/vendor/github.com/gobwas/httphead/writer.go deleted file mode 100644 index e5df3ddf4..000000000 --- a/vendor/github.com/gobwas/httphead/writer.go +++ /dev/null @@ -1,101 +0,0 @@ -package httphead - -import "io" - -var ( - comma = []byte{','} - equality = []byte{'='} - semicolon = []byte{';'} - quote = []byte{'"'} - escape = []byte{'\\'} -) - -// WriteOptions write options list to the dest. -// It uses the same form as {Scan,Parse}Options functions: -// values = 1#value -// value = token *( ";" param ) -// param = token [ "=" (token | quoted-string) ] -// -// It wraps valuse into the quoted-string sequence if it contains any -// non-token characters. -func WriteOptions(dest io.Writer, options []Option) (n int, err error) { - w := writer{w: dest} - for i, opt := range options { - if i > 0 { - w.write(comma) - } - - writeTokenSanitized(&w, opt.Name) - - for _, p := range opt.Parameters.data() { - w.write(semicolon) - writeTokenSanitized(&w, p.key) - if len(p.value) != 0 { - w.write(equality) - writeTokenSanitized(&w, p.value) - } - } - } - return w.result() -} - -// writeTokenSanitized writes token as is or as quouted string if it contains -// non-token characters. -// -// Note that is is not expects LWS sequnces be in s, cause LWS is used only as -// header field continuation: -// "A CRLF is allowed in the definition of TEXT only as part of a header field -// continuation. It is expected that the folding LWS will be replaced with a -// single SP before interpretation of the TEXT value." -// See https://tools.ietf.org/html/rfc2616#section-2 -// -// That is we sanitizing s for writing, so there could not be any header field -// continuation. -// That is any CRLF will be escaped as any other control characters not allowd in TEXT. -func writeTokenSanitized(bw *writer, bts []byte) { - var qt bool - var pos int - for i := 0; i < len(bts); i++ { - c := bts[i] - if !OctetTypes[c].IsToken() && !qt { - qt = true - bw.write(quote) - } - if OctetTypes[c].IsControl() || c == '"' { - if !qt { - qt = true - bw.write(quote) - } - bw.write(bts[pos:i]) - bw.write(escape) - bw.write(bts[i : i+1]) - pos = i + 1 - } - } - if !qt { - bw.write(bts) - } else { - bw.write(bts[pos:]) - bw.write(quote) - } -} - -type writer struct { - w io.Writer - n int - err error -} - -func (w *writer) write(p []byte) { - if w.err != nil { - return - } - var n int - n, w.err = w.w.Write(p) - w.n += n - return -} - -func (w *writer) result() (int, error) { - return w.n, w.err -} diff --git a/vendor/github.com/gobwas/pool/LICENSE b/vendor/github.com/gobwas/pool/LICENSE deleted file mode 100644 index c41ffde6f..000000000 --- a/vendor/github.com/gobwas/pool/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2017-2019 Sergey Kamardin <gobwas@gmail.com> - -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/vendor/github.com/gobwas/pool/README.md b/vendor/github.com/gobwas/pool/README.md deleted file mode 100644 index 45685581d..000000000 --- a/vendor/github.com/gobwas/pool/README.md +++ /dev/null @@ -1,107 +0,0 @@ -# pool - -[![GoDoc][godoc-image]][godoc-url] - -> Tiny memory reuse helpers for Go. - -## generic - -Without use of subpackages, `pool` allows to reuse any struct distinguishable -by size in generic way: - -```go -package main - -import "github.com/gobwas/pool" - -func main() { - x, n := pool.Get(100) // Returns object with size 128 or nil. - if x == nil { - // Create x somehow with knowledge that n is 128. - } - defer pool.Put(x, n) - - // Work with x. -} -``` - -Pool allows you to pass specific options for constructing custom pool: - -```go -package main - -import "github.com/gobwas/pool" - -func main() { - p := pool.Custom( - pool.WithLogSizeMapping(), // Will ceil size n passed to Get(n) to nearest power of two. - pool.WithLogSizeRange(64, 512), // Will reuse objects in logarithmic range [64, 512]. - pool.WithSize(65536), // Will reuse object with size 65536. - ) - x, n := p.Get(1000) // Returns nil and 1000 because mapped size 1000 => 1024 is not reusing by the pool. - defer pool.Put(x, n) // Will not reuse x. - - // Work with x. -} -``` - -Note that there are few non-generic pooling implementations inside subpackages. - -## pbytes - -Subpackage `pbytes` is intended for `[]byte` reuse. - -```go -package main - -import "github.com/gobwas/pool/pbytes" - -func main() { - bts := pbytes.GetCap(100) // Returns make([]byte, 0, 128). - defer pbytes.Put(bts) - - // Work with bts. -} -``` - -You can also create your own range for pooling: - -```go -package main - -import "github.com/gobwas/pool/pbytes" - -func main() { - // Reuse only slices whose capacity is 128, 256, 512 or 1024. - pool := pbytes.New(128, 1024) - - bts := pool.GetCap(100) // Returns make([]byte, 0, 128). - defer pool.Put(bts) - - // Work with bts. -} -``` - -## pbufio - -Subpackage `pbufio` is intended for `*bufio.{Reader, Writer}` reuse. - -```go -package main - -import "github.com/gobwas/pool/pbufio" - -func main() { - bw := pbufio.GetWriter(os.Stdout, 100) // Returns bufio.NewWriterSize(128). - defer pbufio.PutWriter(bw) - - // Work with bw. -} -``` - -Like with `pbytes`, you can also create pool with custom reuse bounds. - - - -[godoc-image]: https://godoc.org/github.com/gobwas/pool?status.svg -[godoc-url]: https://godoc.org/github.com/gobwas/pool diff --git a/vendor/github.com/gobwas/pool/generic.go b/vendor/github.com/gobwas/pool/generic.go deleted file mode 100644 index d40b36245..000000000 --- a/vendor/github.com/gobwas/pool/generic.go +++ /dev/null @@ -1,87 +0,0 @@ -package pool - -import ( - "sync" - - "github.com/gobwas/pool/internal/pmath" -) - -var DefaultPool = New(128, 65536) - -// Get pulls object whose generic size is at least of given size. It also -// returns a real size of x for further pass to Put(). It returns -1 as real -// size for nil x. Size >-1 does not mean that x is non-nil, so checks must be -// done. -// -// Note that size could be ceiled to the next power of two. -// -// Get is a wrapper around DefaultPool.Get(). -func Get(size int) (interface{}, int) { return DefaultPool.Get(size) } - -// Put takes x and its size for future reuse. -// Put is a wrapper around DefaultPool.Put(). -func Put(x interface{}, size int) { DefaultPool.Put(x, size) } - -// Pool contains logic of reusing objects distinguishable by size in generic -// way. -type Pool struct { - pool map[int]*sync.Pool - size func(int) int -} - -// New creates new Pool that reuses objects which size is in logarithmic range -// [min, max]. -// -// Note that it is a shortcut for Custom() constructor with Options provided by -// WithLogSizeMapping() and WithLogSizeRange(min, max) calls. -func New(min, max int) *Pool { - return Custom( - WithLogSizeMapping(), - WithLogSizeRange(min, max), - ) -} - -// Custom creates new Pool with given options. -func Custom(opts ...Option) *Pool { - p := &Pool{ - pool: make(map[int]*sync.Pool), - size: pmath.Identity, - } - - c := (*poolConfig)(p) - for _, opt := range opts { - opt(c) - } - - return p -} - -// Get pulls object whose generic size is at least of given size. -// It also returns a real size of x for further pass to Put() even if x is nil. -// Note that size could be ceiled to the next power of two. -func (p *Pool) Get(size int) (interface{}, int) { - n := p.size(size) - if pool := p.pool[n]; pool != nil { - return pool.Get(), n - } - return nil, size -} - -// Put takes x and its size for future reuse. -func (p *Pool) Put(x interface{}, size int) { - if pool := p.pool[size]; pool != nil { - pool.Put(x) - } -} - -type poolConfig Pool - -// AddSize adds size n to the map. -func (p *poolConfig) AddSize(n int) { - p.pool[n] = new(sync.Pool) -} - -// SetSizeMapping sets up incoming size mapping function. -func (p *poolConfig) SetSizeMapping(size func(int) int) { - p.size = size -} diff --git a/vendor/github.com/gobwas/pool/internal/pmath/pmath.go b/vendor/github.com/gobwas/pool/internal/pmath/pmath.go deleted file mode 100644 index df152ed12..000000000 --- a/vendor/github.com/gobwas/pool/internal/pmath/pmath.go +++ /dev/null @@ -1,65 +0,0 @@ -package pmath - -const ( - bitsize = 32 << (^uint(0) >> 63) - maxint = int(1<<(bitsize-1) - 1) - maxintHeadBit = 1 << (bitsize - 2) -) - -// LogarithmicRange iterates from ceiled to power of two min to max, -// calling cb on each iteration. -func LogarithmicRange(min, max int, cb func(int)) { - if min == 0 { - min = 1 - } - for n := CeilToPowerOfTwo(min); n <= max; n <<= 1 { - cb(n) - } -} - -// IsPowerOfTwo reports whether given integer is a power of two. -func IsPowerOfTwo(n int) bool { - return n&(n-1) == 0 -} - -// Identity is identity. -func Identity(n int) int { - return n -} - -// CeilToPowerOfTwo returns the least power of two integer value greater than -// or equal to n. -func CeilToPowerOfTwo(n int) int { - if n&maxintHeadBit != 0 && n > maxintHeadBit { - panic("argument is too large") - } - if n <= 2 { - return n - } - n-- - n = fillBits(n) - n++ - return n -} - -// FloorToPowerOfTwo returns the greatest power of two integer value less than -// or equal to n. -func FloorToPowerOfTwo(n int) int { - if n <= 2 { - return n - } - n = fillBits(n) - n >>= 1 - n++ - return n -} - -func fillBits(n int) int { - n |= n >> 1 - n |= n >> 2 - n |= n >> 4 - n |= n >> 8 - n |= n >> 16 - n |= n >> 32 - return n -} diff --git a/vendor/github.com/gobwas/pool/option.go b/vendor/github.com/gobwas/pool/option.go deleted file mode 100644 index d6e42b700..000000000 --- a/vendor/github.com/gobwas/pool/option.go +++ /dev/null @@ -1,43 +0,0 @@ -package pool - -import "github.com/gobwas/pool/internal/pmath" - -// Option configures pool. -type Option func(Config) - -// Config describes generic pool configuration. -type Config interface { - AddSize(n int) - SetSizeMapping(func(int) int) -} - -// WithSizeLogRange returns an Option that will add logarithmic range of -// pooling sizes containing [min, max] values. -func WithLogSizeRange(min, max int) Option { - return func(c Config) { - pmath.LogarithmicRange(min, max, func(n int) { - c.AddSize(n) - }) - } -} - -// WithSize returns an Option that will add given pooling size to the pool. -func WithSize(n int) Option { - return func(c Config) { - c.AddSize(n) - } -} - -func WithSizeMapping(sz func(int) int) Option { - return func(c Config) { - c.SetSizeMapping(sz) - } -} - -func WithLogSizeMapping() Option { - return WithSizeMapping(pmath.CeilToPowerOfTwo) -} - -func WithIdentitySizeMapping() Option { - return WithSizeMapping(pmath.Identity) -} diff --git a/vendor/github.com/gobwas/pool/pbufio/pbufio.go b/vendor/github.com/gobwas/pool/pbufio/pbufio.go deleted file mode 100644 index d526bd80d..000000000 --- a/vendor/github.com/gobwas/pool/pbufio/pbufio.go +++ /dev/null @@ -1,106 +0,0 @@ -// Package pbufio contains tools for pooling bufio.Reader and bufio.Writers. -package pbufio - -import ( - "bufio" - "io" - - "github.com/gobwas/pool" -) - -var ( - DefaultWriterPool = NewWriterPool(256, 65536) - DefaultReaderPool = NewReaderPool(256, 65536) -) - -// GetWriter returns bufio.Writer whose buffer has at least size bytes. -// Note that size could be ceiled to the next power of two. -// GetWriter is a wrapper around DefaultWriterPool.Get(). -func GetWriter(w io.Writer, size int) *bufio.Writer { return DefaultWriterPool.Get(w, size) } - -// PutWriter takes bufio.Writer for future reuse. -// It does not reuse bufio.Writer which underlying buffer size is not power of -// PutWriter is a wrapper around DefaultWriterPool.Put(). -func PutWriter(bw *bufio.Writer) { DefaultWriterPool.Put(bw) } - -// GetReader returns bufio.Reader whose buffer has at least size bytes. It returns -// its capacity for further pass to Put(). -// Note that size could be ceiled to the next power of two. -// GetReader is a wrapper around DefaultReaderPool.Get(). -func GetReader(w io.Reader, size int) *bufio.Reader { return DefaultReaderPool.Get(w, size) } - -// PutReader takes bufio.Reader and its size for future reuse. -// It does not reuse bufio.Reader if size is not power of two or is out of pool -// min/max range. -// PutReader is a wrapper around DefaultReaderPool.Put(). -func PutReader(bw *bufio.Reader) { DefaultReaderPool.Put(bw) } - -// WriterPool contains logic of *bufio.Writer reuse with various size. -type WriterPool struct { - pool *pool.Pool -} - -// NewWriterPool creates new WriterPool that reuses writers which size is in -// logarithmic range [min, max]. -func NewWriterPool(min, max int) *WriterPool { - return &WriterPool{pool.New(min, max)} -} - -// CustomWriterPool creates new WriterPool with given options. -func CustomWriterPool(opts ...pool.Option) *WriterPool { - return &WriterPool{pool.Custom(opts...)} -} - -// Get returns bufio.Writer whose buffer has at least size bytes. -func (wp *WriterPool) Get(w io.Writer, size int) *bufio.Writer { - v, n := wp.pool.Get(size) - if v != nil { - bw := v.(*bufio.Writer) - bw.Reset(w) - return bw - } - return bufio.NewWriterSize(w, n) -} - -// Put takes ownership of bufio.Writer for further reuse. -func (wp *WriterPool) Put(bw *bufio.Writer) { - // Should reset even if we do Reset() inside Get(). - // This is done to prevent locking underlying io.Writer from GC. - bw.Reset(nil) - wp.pool.Put(bw, writerSize(bw)) -} - -// ReaderPool contains logic of *bufio.Reader reuse with various size. -type ReaderPool struct { - pool *pool.Pool -} - -// NewReaderPool creates new ReaderPool that reuses writers which size is in -// logarithmic range [min, max]. -func NewReaderPool(min, max int) *ReaderPool { - return &ReaderPool{pool.New(min, max)} -} - -// CustomReaderPool creates new ReaderPool with given options. -func CustomReaderPool(opts ...pool.Option) *ReaderPool { - return &ReaderPool{pool.Custom(opts...)} -} - -// Get returns bufio.Reader whose buffer has at least size bytes. -func (rp *ReaderPool) Get(r io.Reader, size int) *bufio.Reader { - v, n := rp.pool.Get(size) - if v != nil { - br := v.(*bufio.Reader) - br.Reset(r) - return br - } - return bufio.NewReaderSize(r, n) -} - -// Put takes ownership of bufio.Reader for further reuse. -func (rp *ReaderPool) Put(br *bufio.Reader) { - // Should reset even if we do Reset() inside Get(). - // This is done to prevent locking underlying io.Reader from GC. - br.Reset(nil) - rp.pool.Put(br, readerSize(br)) -} diff --git a/vendor/github.com/gobwas/pool/pbufio/pbufio_go110.go b/vendor/github.com/gobwas/pool/pbufio/pbufio_go110.go deleted file mode 100644 index c736ae56e..000000000 --- a/vendor/github.com/gobwas/pool/pbufio/pbufio_go110.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build go1.10 - -package pbufio - -import "bufio" - -func writerSize(bw *bufio.Writer) int { - return bw.Size() -} - -func readerSize(br *bufio.Reader) int { - return br.Size() -} diff --git a/vendor/github.com/gobwas/pool/pbufio/pbufio_go19.go b/vendor/github.com/gobwas/pool/pbufio/pbufio_go19.go deleted file mode 100644 index e71dd447d..000000000 --- a/vendor/github.com/gobwas/pool/pbufio/pbufio_go19.go +++ /dev/null @@ -1,27 +0,0 @@ -// +build !go1.10 - -package pbufio - -import "bufio" - -func writerSize(bw *bufio.Writer) int { - return bw.Available() + bw.Buffered() -} - -// readerSize returns buffer size of the given buffered reader. -// NOTE: current workaround implementation resets underlying io.Reader. -func readerSize(br *bufio.Reader) int { - br.Reset(sizeReader) - br.ReadByte() - n := br.Buffered() + 1 - br.Reset(nil) - return n -} - -var sizeReader optimisticReader - -type optimisticReader struct{} - -func (optimisticReader) Read(p []byte) (int, error) { - return len(p), nil -} diff --git a/vendor/github.com/gobwas/pool/pbytes/pbytes.go b/vendor/github.com/gobwas/pool/pbytes/pbytes.go deleted file mode 100644 index 919705b10..000000000 --- a/vendor/github.com/gobwas/pool/pbytes/pbytes.go +++ /dev/null @@ -1,24 +0,0 @@ -// Package pbytes contains tools for pooling byte pool. -// Note that by default it reuse slices with capacity from 128 to 65536 bytes. -package pbytes - -// DefaultPool is used by pacakge level functions. -var DefaultPool = New(128, 65536) - -// Get returns probably reused slice of bytes with at least capacity of c and -// exactly len of n. -// Get is a wrapper around DefaultPool.Get(). -func Get(n, c int) []byte { return DefaultPool.Get(n, c) } - -// GetCap returns probably reused slice of bytes with at least capacity of n. -// GetCap is a wrapper around DefaultPool.GetCap(). -func GetCap(c int) []byte { return DefaultPool.GetCap(c) } - -// GetLen returns probably reused slice of bytes with at least capacity of n -// and exactly len of n. -// GetLen is a wrapper around DefaultPool.GetLen(). -func GetLen(n int) []byte { return DefaultPool.GetLen(n) } - -// Put returns given slice to reuse pool. -// Put is a wrapper around DefaultPool.Put(). -func Put(p []byte) { DefaultPool.Put(p) } diff --git a/vendor/github.com/gobwas/pool/pbytes/pool.go b/vendor/github.com/gobwas/pool/pbytes/pool.go deleted file mode 100644 index 1dde225f3..000000000 --- a/vendor/github.com/gobwas/pool/pbytes/pool.go +++ /dev/null @@ -1,59 +0,0 @@ -// +build !pool_sanitize - -package pbytes - -import "github.com/gobwas/pool" - -// Pool contains logic of reusing byte slices of various size. -type Pool struct { - pool *pool.Pool -} - -// New creates new Pool that reuses slices which size is in logarithmic range -// [min, max]. -// -// Note that it is a shortcut for Custom() constructor with Options provided by -// pool.WithLogSizeMapping() and pool.WithLogSizeRange(min, max) calls. -func New(min, max int) *Pool { - return &Pool{pool.New(min, max)} -} - -// New creates new Pool with given options. -func Custom(opts ...pool.Option) *Pool { - return &Pool{pool.Custom(opts...)} -} - -// Get returns probably reused slice of bytes with at least capacity of c and -// exactly len of n. -func (p *Pool) Get(n, c int) []byte { - if n > c { - panic("requested length is greater than capacity") - } - - v, x := p.pool.Get(c) - if v != nil { - bts := v.([]byte) - bts = bts[:n] - return bts - } - - return make([]byte, n, x) -} - -// Put returns given slice to reuse pool. -// It does not reuse bytes whose size is not power of two or is out of pool -// min/max range. -func (p *Pool) Put(bts []byte) { - p.pool.Put(bts, cap(bts)) -} - -// GetCap returns probably reused slice of bytes with at least capacity of n. -func (p *Pool) GetCap(c int) []byte { - return p.Get(0, c) -} - -// GetLen returns probably reused slice of bytes with at least capacity of n -// and exactly len of n. -func (p *Pool) GetLen(n int) []byte { - return p.Get(n, n) -} diff --git a/vendor/github.com/gobwas/pool/pbytes/pool_sanitize.go b/vendor/github.com/gobwas/pool/pbytes/pool_sanitize.go deleted file mode 100644 index fae9af49b..000000000 --- a/vendor/github.com/gobwas/pool/pbytes/pool_sanitize.go +++ /dev/null @@ -1,121 +0,0 @@ -// +build pool_sanitize - -package pbytes - -import ( - "reflect" - "runtime" - "sync/atomic" - "syscall" - "unsafe" - - "golang.org/x/sys/unix" -) - -const magic = uint64(0x777742) - -type guard struct { - magic uint64 - size int - owners int32 -} - -const guardSize = int(unsafe.Sizeof(guard{})) - -type Pool struct { - min, max int -} - -func New(min, max int) *Pool { - return &Pool{min, max} -} - -// Get returns probably reused slice of bytes with at least capacity of c and -// exactly len of n. -func (p *Pool) Get(n, c int) []byte { - if n > c { - panic("requested length is greater than capacity") - } - - pageSize := syscall.Getpagesize() - pages := (c+guardSize)/pageSize + 1 - size := pages * pageSize - - bts := alloc(size) - - g := (*guard)(unsafe.Pointer(&bts[0])) - *g = guard{ - magic: magic, - size: size, - owners: 1, - } - - return bts[guardSize : guardSize+n] -} - -func (p *Pool) GetCap(c int) []byte { return p.Get(0, c) } -func (p *Pool) GetLen(n int) []byte { return Get(n, n) } - -// Put returns given slice to reuse pool. -func (p *Pool) Put(bts []byte) { - hdr := *(*reflect.SliceHeader)(unsafe.Pointer(&bts)) - ptr := hdr.Data - uintptr(guardSize) - - g := (*guard)(unsafe.Pointer(ptr)) - if g.magic != magic { - panic("unknown slice returned to the pool") - } - if n := atomic.AddInt32(&g.owners, -1); n < 0 { - panic("multiple Put() detected") - } - - // Disable read and write on bytes memory pages. This will cause panic on - // incorrect access to returned slice. - mprotect(ptr, false, false, g.size) - - runtime.SetFinalizer(&bts, func(b *[]byte) { - mprotect(ptr, true, true, g.size) - free(*(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{ - Data: ptr, - Len: g.size, - Cap: g.size, - }))) - }) -} - -func alloc(n int) []byte { - b, err := unix.Mmap(-1, 0, n, unix.PROT_READ|unix.PROT_WRITE|unix.PROT_EXEC, unix.MAP_SHARED|unix.MAP_ANONYMOUS) - if err != nil { - panic(err.Error()) - } - return b -} - -func free(b []byte) { - if err := unix.Munmap(b); err != nil { - panic(err.Error()) - } -} - -func mprotect(ptr uintptr, r, w bool, size int) { - // Need to avoid "EINVAL addr is not a valid pointer, - // or not a multiple of PAGESIZE." - start := ptr & ^(uintptr(syscall.Getpagesize() - 1)) - - prot := uintptr(syscall.PROT_EXEC) - switch { - case r && w: - prot |= syscall.PROT_READ | syscall.PROT_WRITE - case r: - prot |= syscall.PROT_READ - case w: - prot |= syscall.PROT_WRITE - } - - _, _, err := syscall.Syscall(syscall.SYS_MPROTECT, - start, uintptr(size), prot, - ) - if err != 0 { - panic(err.Error()) - } -} diff --git a/vendor/github.com/gobwas/pool/pool.go b/vendor/github.com/gobwas/pool/pool.go deleted file mode 100644 index 1fe9e602f..000000000 --- a/vendor/github.com/gobwas/pool/pool.go +++ /dev/null @@ -1,25 +0,0 @@ -// Package pool contains helpers for pooling structures distinguishable by -// size. -// -// Quick example: -// -// import "github.com/gobwas/pool" -// -// func main() { -// // Reuse objects in logarithmic range from 0 to 64 (0,1,2,4,6,8,16,32,64). -// p := pool.New(0, 64) -// -// buf, n := p.Get(10) // Returns buffer with 16 capacity. -// if buf == nil { -// buf = bytes.NewBuffer(make([]byte, n)) -// } -// defer p.Put(buf, n) -// -// // Work with buf. -// } -// -// There are non-generic implementations for pooling: -// - pool/pbytes for []byte reuse; -// - pool/pbufio for *bufio.Reader and *bufio.Writer reuse; -// -package pool diff --git a/vendor/github.com/gobwas/ws/.gitignore b/vendor/github.com/gobwas/ws/.gitignore deleted file mode 100644 index e3e2b1080..000000000 --- a/vendor/github.com/gobwas/ws/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -bin/ -reports/ -cpu.out -mem.out -ws.test diff --git a/vendor/github.com/gobwas/ws/LICENSE b/vendor/github.com/gobwas/ws/LICENSE deleted file mode 100644 index ca6dfd9e1..000000000 --- a/vendor/github.com/gobwas/ws/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2017-2021 Sergey Kamardin <gobwas@gmail.com> - -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/vendor/github.com/gobwas/ws/Makefile b/vendor/github.com/gobwas/ws/Makefile deleted file mode 100644 index 6d89f78c0..000000000 --- a/vendor/github.com/gobwas/ws/Makefile +++ /dev/null @@ -1,54 +0,0 @@ -BENCH ?=. -BENCH_BASE?=master - -clean: - rm -f bin/reporter - rm -fr autobahn/report/* - -bin/reporter: - go build -o bin/reporter ./autobahn - -bin/gocovmerge: - go build -o bin/gocovmerge github.com/wadey/gocovmerge - -.PHONY: autobahn -autobahn: clean bin/reporter - ./autobahn/script/test.sh --build --follow-logs - bin/reporter $(PWD)/autobahn/report/index.json - -.PHONY: autobahn/report -autobahn/report: bin/reporter - ./bin/reporter -http localhost:5555 ./autobahn/report/index.json - -test: - go test -coverprofile=ws.coverage . - go test -coverprofile=wsutil.coverage ./wsutil - go test -coverprofile=wsfalte.coverage ./wsflate - # No statements to cover in ./tests (there are only tests). - go test ./tests - -cover: bin/gocovmerge test autobahn - bin/gocovmerge ws.coverage wsutil.coverage wsflate.coverage autobahn/report/server.coverage > total.coverage - -benchcmp: BENCH_BRANCH=$(shell git rev-parse --abbrev-ref HEAD) -benchcmp: BENCH_OLD:=$(shell mktemp -t old.XXXX) -benchcmp: BENCH_NEW:=$(shell mktemp -t new.XXXX) -benchcmp: - if [ ! -z "$(shell git status -s)" ]; then\ - echo "could not compare with $(BENCH_BASE) – found unstaged changes";\ - exit 1;\ - fi;\ - if [ "$(BENCH_BRANCH)" == "$(BENCH_BASE)" ]; then\ - echo "comparing the same branches";\ - exit 1;\ - fi;\ - echo "benchmarking $(BENCH_BRANCH)...";\ - go test -run=none -bench=$(BENCH) -benchmem > $(BENCH_NEW);\ - echo "benchmarking $(BENCH_BASE)...";\ - git checkout -q $(BENCH_BASE);\ - go test -run=none -bench=$(BENCH) -benchmem > $(BENCH_OLD);\ - git checkout -q $(BENCH_BRANCH);\ - echo "\nresults:";\ - echo "========\n";\ - benchcmp $(BENCH_OLD) $(BENCH_NEW);\ - diff --git a/vendor/github.com/gobwas/ws/README.md b/vendor/github.com/gobwas/ws/README.md deleted file mode 100644 index 0bd0f6b0a..000000000 --- a/vendor/github.com/gobwas/ws/README.md +++ /dev/null @@ -1,541 +0,0 @@ -# ws - -[![GoDoc][godoc-image]][godoc-url] -[![CI][ci-badge]][ci-url] - -> [RFC6455][rfc-url] WebSocket implementation in Go. - -# Features - -- Zero-copy upgrade -- No intermediate allocations during I/O -- Low-level API which allows to build your own logic of packet handling and - buffers reuse -- High-level wrappers and helpers around API in `wsutil` package, which allow - to start fast without digging the protocol internals - -# Documentation - -[GoDoc][godoc-url]. - -# Why - -Existing WebSocket implementations do not allow users to reuse I/O buffers -between connections in clear way. This library aims to export efficient -low-level interface for working with the protocol without forcing only one way -it could be used. - -By the way, if you want get the higher-level tools, you can use `wsutil` -package. - -# Status - -Library is tagged as `v1*` so its API must not be broken during some -improvements or refactoring. - -This implementation of RFC6455 passes [Autobahn Test -Suite](https://github.com/crossbario/autobahn-testsuite) and currently has -about 78% coverage. - -# Examples - -Example applications using `ws` are developed in separate repository -[ws-examples](https://github.com/gobwas/ws-examples). - -# Usage - -The higher-level example of WebSocket echo server: - -```go -package main - -import ( - "net/http" - - "github.com/gobwas/ws" - "github.com/gobwas/ws/wsutil" -) - -func main() { - http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - conn, _, _, err := ws.UpgradeHTTP(r, w) - if err != nil { - // handle error - } - go func() { - defer conn.Close() - - for { - msg, op, err := wsutil.ReadClientData(conn) - if err != nil { - // handle error - } - err = wsutil.WriteServerMessage(conn, op, msg) - if err != nil { - // handle error - } - } - }() - })) -} -``` - -Lower-level, but still high-level example: - - -```go -import ( - "net/http" - "io" - - "github.com/gobwas/ws" - "github.com/gobwas/ws/wsutil" -) - -func main() { - http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - conn, _, _, err := ws.UpgradeHTTP(r, w) - if err != nil { - // handle error - } - go func() { - defer conn.Close() - - var ( - state = ws.StateServerSide - reader = wsutil.NewReader(conn, state) - writer = wsutil.NewWriter(conn, state, ws.OpText) - ) - for { - header, err := reader.NextFrame() - if err != nil { - // handle error - } - - // Reset writer to write frame with right operation code. - writer.Reset(conn, state, header.OpCode) - - if _, err = io.Copy(writer, reader); err != nil { - // handle error - } - if err = writer.Flush(); err != nil { - // handle error - } - } - }() - })) -} -``` - -We can apply the same pattern to read and write structured responses through a JSON encoder and decoder.: - -```go - ... - var ( - r = wsutil.NewReader(conn, ws.StateServerSide) - w = wsutil.NewWriter(conn, ws.StateServerSide, ws.OpText) - decoder = json.NewDecoder(r) - encoder = json.NewEncoder(w) - ) - for { - hdr, err = r.NextFrame() - if err != nil { - return err - } - if hdr.OpCode == ws.OpClose { - return io.EOF - } - var req Request - if err := decoder.Decode(&req); err != nil { - return err - } - var resp Response - if err := encoder.Encode(&resp); err != nil { - return err - } - if err = w.Flush(); err != nil { - return err - } - } - ... -``` - -The lower-level example without `wsutil`: - -```go -package main - -import ( - "net" - "io" - - "github.com/gobwas/ws" -) - -func main() { - ln, err := net.Listen("tcp", "localhost:8080") - if err != nil { - log.Fatal(err) - } - - for { - conn, err := ln.Accept() - if err != nil { - // handle error - } - _, err = ws.Upgrade(conn) - if err != nil { - // handle error - } - - go func() { - defer conn.Close() - - for { - header, err := ws.ReadHeader(conn) - if err != nil { - // handle error - } - - payload := make([]byte, header.Length) - _, err = io.ReadFull(conn, payload) - if err != nil { - // handle error - } - if header.Masked { - ws.Cipher(payload, header.Mask, 0) - } - - // Reset the Masked flag, server frames must not be masked as - // RFC6455 says. - header.Masked = false - - if err := ws.WriteHeader(conn, header); err != nil { - // handle error - } - if _, err := conn.Write(payload); err != nil { - // handle error - } - - if header.OpCode == ws.OpClose { - return - } - } - }() - } -} -``` - -# Zero-copy upgrade - -Zero-copy upgrade helps to avoid unnecessary allocations and copying while -handling HTTP Upgrade request. - -Processing of all non-websocket headers is made in place with use of registered -user callbacks whose arguments are only valid until callback returns. - -The simple example looks like this: - -```go -package main - -import ( - "net" - "log" - - "github.com/gobwas/ws" -) - -func main() { - ln, err := net.Listen("tcp", "localhost:8080") - if err != nil { - log.Fatal(err) - } - u := ws.Upgrader{ - OnHeader: func(key, value []byte) (err error) { - log.Printf("non-websocket header: %q=%q", key, value) - return - }, - } - for { - conn, err := ln.Accept() - if err != nil { - // handle error - } - - _, err = u.Upgrade(conn) - if err != nil { - // handle error - } - } -} -``` - -Usage of `ws.Upgrader` here brings ability to control incoming connections on -tcp level and simply not to accept them by some logic. - -Zero-copy upgrade is for high-load services which have to control many -resources such as connections buffers. - -The real life example could be like this: - -```go -package main - -import ( - "fmt" - "io" - "log" - "net" - "net/http" - "runtime" - - "github.com/gobwas/httphead" - "github.com/gobwas/ws" -) - -func main() { - ln, err := net.Listen("tcp", "localhost:8080") - if err != nil { - // handle error - } - - // Prepare handshake header writer from http.Header mapping. - header := ws.HandshakeHeaderHTTP(http.Header{ - "X-Go-Version": []string{runtime.Version()}, - }) - - u := ws.Upgrader{ - OnHost: func(host []byte) error { - if string(host) == "github.com" { - return nil - } - return ws.RejectConnectionError( - ws.RejectionStatus(403), - ws.RejectionHeader(ws.HandshakeHeaderString( - "X-Want-Host: github.com\r\n", - )), - ) - }, - OnHeader: func(key, value []byte) error { - if string(key) != "Cookie" { - return nil - } - ok := httphead.ScanCookie(value, func(key, value []byte) bool { - // Check session here or do some other stuff with cookies. - // Maybe copy some values for future use. - return true - }) - if ok { - return nil - } - return ws.RejectConnectionError( - ws.RejectionReason("bad cookie"), - ws.RejectionStatus(400), - ) - }, - OnBeforeUpgrade: func() (ws.HandshakeHeader, error) { - return header, nil - }, - } - for { - conn, err := ln.Accept() - if err != nil { - log.Fatal(err) - } - _, err = u.Upgrade(conn) - if err != nil { - log.Printf("upgrade error: %s", err) - } - } -} -``` - -# Compression - -There is a `ws/wsflate` package to support [Permessage-Deflate Compression -Extension][rfc-pmce]. - -It provides minimalistic I/O wrappers to be used in conjunction with any -deflate implementation (for example, the standard library's -[compress/flate][compress/flate]). - -It is also compatible with `wsutil`'s reader and writer by providing -`wsflate.MessageState` type, which implements `wsutil.SendExtension` and -`wsutil.RecvExtension` interfaces. - -```go -package main - -import ( - "bytes" - "log" - "net" - - "github.com/gobwas/ws" - "github.com/gobwas/ws/wsflate" -) - -func main() { - ln, err := net.Listen("tcp", "localhost:8080") - if err != nil { - // handle error - } - e := wsflate.Extension{ - // We are using default parameters here since we use - // wsflate.{Compress,Decompress}Frame helpers below in the code. - // This assumes that we use standard compress/flate package as flate - // implementation. - Parameters: wsflate.DefaultParameters, - } - u := ws.Upgrader{ - Negotiate: e.Negotiate, - } - for { - conn, err := ln.Accept() - if err != nil { - log.Fatal(err) - } - - // Reset extension after previous upgrades. - e.Reset() - - _, err = u.Upgrade(conn) - if err != nil { - log.Printf("upgrade error: %s", err) - continue - } - if _, ok := e.Accepted(); !ok { - log.Printf("didn't negotiate compression for %s", conn.RemoteAddr()) - conn.Close() - continue - } - - go func() { - defer conn.Close() - for { - frame, err := ws.ReadFrame(conn) - if err != nil { - // Handle error. - return - } - - frame = ws.UnmaskFrameInPlace(frame) - - if wsflate.IsCompressed(frame.Header) { - // Note that even after successful negotiation of - // compression extension, both sides are able to send - // non-compressed messages. - frame, err = wsflate.DecompressFrame(frame) - if err != nil { - // Handle error. - return - } - } - - // Do something with frame... - - ack := ws.NewTextFrame([]byte("this is an acknowledgement")) - - // Compress response unconditionally. - ack, err = wsflate.CompressFrame(ack) - if err != nil { - // Handle error. - return - } - if err = ws.WriteFrame(conn, ack); err != nil { - // Handle error. - return - } - } - }() - } -} -``` - -You can use compression with `wsutil` package this way: - -```go - // Upgrade somehow and negotiate compression to get the conn... - - // Initialize flate reader. We are using nil as a source io.Reader because - // we will Reset() it in the message i/o loop below. - fr := wsflate.NewReader(nil, func(r io.Reader) wsflate.Decompressor { - return flate.NewReader(r) - }) - // Initialize flate writer. We are using nil as a destination io.Writer - // because we will Reset() it in the message i/o loop below. - fw := wsflate.NewWriter(nil, func(w io.Writer) wsflate.Compressor { - f, _ := flate.NewWriter(w, 9) - return f - }) - - // Declare compression message state variable. - // - // It has two goals: - // - Allow users to check whether received message is compressed or not. - // - Help wsutil.Reader and wsutil.Writer to set/unset appropriate - // WebSocket header bits while writing next frame to the wire (it - // implements wsutil.RecvExtension and wsutil.SendExtension). - var msg wsflate.MessageState - - // Initialize WebSocket reader as previously. - // Please note the use of Reader.Extensions field as well as - // of ws.StateExtended flag. - rd := &wsutil.Reader{ - Source: conn, - State: ws.StateServerSide | ws.StateExtended, - Extensions: []wsutil.RecvExtension{ - &msg, - }, - } - - // Initialize WebSocket writer with ws.StateExtended flag as well. - wr := wsutil.NewWriter(conn, ws.StateServerSide|ws.StateExtended, 0) - // Use the message state as wsutil.SendExtension. - wr.SetExtensions(&msg) - - for { - h, err := rd.NextFrame() - if err != nil { - // handle error. - } - if h.OpCode.IsControl() { - // handle control frame. - } - if !msg.IsCompressed() { - // handle uncompressed frame (skipped for the sake of example - // simplicity). - } - - // Reset the writer to echo same op code. - wr.Reset(h.OpCode) - - // Reset both flate reader and writer to start the new round of i/o. - fr.Reset(rd) - fw.Reset(wr) - - // Copy whole message from reader to writer decompressing it and - // compressing again. - if _, err := io.Copy(fw, fr); err != nil { - // handle error. - } - // Flush any remaining buffers from flate writer to WebSocket writer. - if err := fw.Close(); err != nil { - // handle error. - } - // Flush the whole WebSocket message to the wire. - if err := wr.Flush(); err != nil { - // handle error. - } - } -``` - - -[rfc-url]: https://tools.ietf.org/html/rfc6455 -[rfc-pmce]: https://tools.ietf.org/html/rfc7692#section-7 -[godoc-image]: https://godoc.org/github.com/gobwas/ws?status.svg -[godoc-url]: https://godoc.org/github.com/gobwas/ws -[compress/flate]: https://golang.org/pkg/compress/flate/ -[ci-badge]: https://github.com/gobwas/ws/workflows/CI/badge.svg -[ci-url]: https://github.com/gobwas/ws/actions?query=workflow%3ACI diff --git a/vendor/github.com/gobwas/ws/check.go b/vendor/github.com/gobwas/ws/check.go deleted file mode 100644 index 8aa0df8cc..000000000 --- a/vendor/github.com/gobwas/ws/check.go +++ /dev/null @@ -1,145 +0,0 @@ -package ws - -import "unicode/utf8" - -// State represents state of websocket endpoint. -// It used by some functions to be more strict when checking compatibility with RFC6455. -type State uint8 - -const ( - // StateServerSide means that endpoint (caller) is a server. - StateServerSide State = 0x1 << iota - // StateClientSide means that endpoint (caller) is a client. - StateClientSide - // StateExtended means that extension was negotiated during handshake. - StateExtended - // StateFragmented means that endpoint (caller) has received fragmented - // frame and waits for continuation parts. - StateFragmented -) - -// Is checks whether the s has v enabled. -func (s State) Is(v State) bool { - return uint8(s)&uint8(v) != 0 -} - -// Set enables v state on s. -func (s State) Set(v State) State { - return s | v -} - -// Clear disables v state on s. -func (s State) Clear(v State) State { - return s & (^v) -} - -// ServerSide reports whether states represents server side. -func (s State) ServerSide() bool { return s.Is(StateServerSide) } - -// ClientSide reports whether state represents client side. -func (s State) ClientSide() bool { return s.Is(StateClientSide) } - -// Extended reports whether state is extended. -func (s State) Extended() bool { return s.Is(StateExtended) } - -// Fragmented reports whether state is fragmented. -func (s State) Fragmented() bool { return s.Is(StateFragmented) } - -// ProtocolError describes error during checking/parsing websocket frames or -// headers. -type ProtocolError string - -// Error implements error interface. -func (p ProtocolError) Error() string { return string(p) } - -// Errors used by the protocol checkers. -var ( - ErrProtocolOpCodeReserved = ProtocolError("use of reserved op code") - ErrProtocolControlPayloadOverflow = ProtocolError("control frame payload limit exceeded") - ErrProtocolControlNotFinal = ProtocolError("control frame is not final") - ErrProtocolNonZeroRsv = ProtocolError("non-zero rsv bits with no extension negotiated") - ErrProtocolMaskRequired = ProtocolError("frames from client to server must be masked") - ErrProtocolMaskUnexpected = ProtocolError("frames from server to client must be not masked") - ErrProtocolContinuationExpected = ProtocolError("unexpected non-continuation data frame") - ErrProtocolContinuationUnexpected = ProtocolError("unexpected continuation data frame") - ErrProtocolStatusCodeNotInUse = ProtocolError("status code is not in use") - ErrProtocolStatusCodeApplicationLevel = ProtocolError("status code is only application level") - ErrProtocolStatusCodeNoMeaning = ProtocolError("status code has no meaning yet") - ErrProtocolStatusCodeUnknown = ProtocolError("status code is not defined in spec") - ErrProtocolInvalidUTF8 = ProtocolError("invalid utf8 sequence in close reason") -) - -// CheckHeader checks h to contain valid header data for given state s. -// -// Note that zero state (0) means that state is clean, -// neither server or client side, nor fragmented, nor extended. -func CheckHeader(h Header, s State) error { - if h.OpCode.IsReserved() { - return ErrProtocolOpCodeReserved - } - if h.OpCode.IsControl() { - if h.Length > MaxControlFramePayloadSize { - return ErrProtocolControlPayloadOverflow - } - if !h.Fin { - return ErrProtocolControlNotFinal - } - } - - switch { - // [RFC6455]: MUST be 0 unless an extension is negotiated that defines meanings for - // non-zero values. If a nonzero value is received and none of the - // negotiated extensions defines the meaning of such a nonzero value, the - // receiving endpoint MUST _Fail the WebSocket Connection_. - case h.Rsv != 0 && !s.Extended(): - return ErrProtocolNonZeroRsv - - // [RFC6455]: The server MUST close the connection upon receiving a frame that is not masked. - // In this case, a server MAY send a Close frame with a status code of 1002 (protocol error) - // as defined in Section 7.4.1. A server MUST NOT mask any frames that it sends to the client. - // A client MUST close a connection if it detects a masked frame. In this case, it MAY use the - // status code 1002 (protocol error) as defined in Section 7.4.1. - case s.ServerSide() && !h.Masked: - return ErrProtocolMaskRequired - case s.ClientSide() && h.Masked: - return ErrProtocolMaskUnexpected - - // [RFC6455]: See detailed explanation in 5.4 section. - case s.Fragmented() && !h.OpCode.IsControl() && h.OpCode != OpContinuation: - return ErrProtocolContinuationExpected - case !s.Fragmented() && h.OpCode == OpContinuation: - return ErrProtocolContinuationUnexpected - - default: - return nil - } -} - -// CheckCloseFrameData checks received close information -// to be valid RFC6455 compatible close info. -// -// Note that code.Empty() or code.IsAppLevel() will raise error. -// -// If endpoint sends close frame without status code (with frame.Length = 0), -// application should not check its payload. -func CheckCloseFrameData(code StatusCode, reason string) error { - switch { - case code.IsNotUsed(): - return ErrProtocolStatusCodeNotInUse - - case code.IsProtocolReserved(): - return ErrProtocolStatusCodeApplicationLevel - - case code == StatusNoMeaningYet: - return ErrProtocolStatusCodeNoMeaning - - case code.IsProtocolSpec() && !code.IsProtocolDefined(): - return ErrProtocolStatusCodeUnknown - - case !utf8.ValidString(reason): - return ErrProtocolInvalidUTF8 - - default: - return nil - } -} diff --git a/vendor/github.com/gobwas/ws/cipher.go b/vendor/github.com/gobwas/ws/cipher.go deleted file mode 100644 index ffe41619a..000000000 --- a/vendor/github.com/gobwas/ws/cipher.go +++ /dev/null @@ -1,61 +0,0 @@ -package ws - -import ( - "encoding/binary" -) - -// Cipher applies XOR cipher to the payload using mask. -// Offset is used to cipher chunked data (e.g. in io.Reader implementations). -// -// To convert masked data into unmasked data, or vice versa, the following -// algorithm is applied. The same algorithm applies regardless of the -// direction of the translation, e.g., the same steps are applied to -// mask the data as to unmask the data. -func Cipher(payload []byte, mask [4]byte, offset int) { - n := len(payload) - if n < 8 { - for i := 0; i < n; i++ { - payload[i] ^= mask[(offset+i)%4] - } - return - } - - // Calculate position in mask due to previously processed bytes number. - mpos := offset % 4 - // Count number of bytes will processed one by one from the beginning of payload. - ln := remain[mpos] - // Count number of bytes will processed one by one from the end of payload. - // This is done to process payload by 16 bytes in each iteration of main loop. - rn := (n - ln) % 16 - - for i := 0; i < ln; i++ { - payload[i] ^= mask[(mpos+i)%4] - } - for i := n - rn; i < n; i++ { - payload[i] ^= mask[(mpos+i)%4] - } - - // NOTE: we use here binary.LittleEndian regardless of what is real - // endianness on machine is. To do so, we have to use binary.LittleEndian in - // the masking loop below as well. - var ( - m = binary.LittleEndian.Uint32(mask[:]) - m2 = uint64(m)<<32 | uint64(m) - ) - // Skip already processed right part. - // Get number of uint64 parts remaining to process. - n = (n - ln - rn) >> 4 - j := ln - for i := 0; i < n; i++ { - chunk := payload[j : j+16] - p := binary.LittleEndian.Uint64(chunk) ^ m2 - p2 := binary.LittleEndian.Uint64(chunk[8:]) ^ m2 - binary.LittleEndian.PutUint64(chunk, p) - binary.LittleEndian.PutUint64(chunk[8:], p2) - j += 16 - } -} - -// remain maps position in masking key [0,4) to number -// of bytes that need to be processed manually inside Cipher(). -var remain = [4]int{0, 3, 2, 1} diff --git a/vendor/github.com/gobwas/ws/dialer.go b/vendor/github.com/gobwas/ws/dialer.go deleted file mode 100644 index e66678e4c..000000000 --- a/vendor/github.com/gobwas/ws/dialer.go +++ /dev/null @@ -1,573 +0,0 @@ -package ws - -import ( - "bufio" - "bytes" - "context" - "crypto/tls" - "fmt" - "io" - "net" - "net/http" - "net/url" - "strconv" - "strings" - "time" - - "github.com/gobwas/httphead" - "github.com/gobwas/pool/pbufio" -) - -// Constants used by Dialer. -const ( - DefaultClientReadBufferSize = 4096 - DefaultClientWriteBufferSize = 4096 -) - -// Handshake represents handshake result. -type Handshake struct { - // Protocol is the subprotocol selected during handshake. - Protocol string - - // Extensions is the list of negotiated extensions. - Extensions []httphead.Option -} - -// Errors used by the websocket client. -var ( - ErrHandshakeBadStatus = fmt.Errorf("unexpected http status") - ErrHandshakeBadSubProtocol = fmt.Errorf("unexpected protocol in %q header", headerSecProtocol) - ErrHandshakeBadExtensions = fmt.Errorf("unexpected extensions in %q header", headerSecProtocol) -) - -// DefaultDialer is dialer that holds no options and is used by Dial function. -var DefaultDialer Dialer - -// Dial is like Dialer{}.Dial(). -func Dial(ctx context.Context, urlstr string) (net.Conn, *bufio.Reader, Handshake, error) { - return DefaultDialer.Dial(ctx, urlstr) -} - -// Dialer contains options for establishing websocket connection to an url. -type Dialer struct { - // ReadBufferSize and WriteBufferSize is an I/O buffer sizes. - // They used to read and write http data while upgrading to WebSocket. - // Allocated buffers are pooled with sync.Pool to avoid extra allocations. - // - // If a size is zero then default value is used. - ReadBufferSize, WriteBufferSize int - - // Timeout is the maximum amount of time a Dial() will wait for a connect - // and an handshake to complete. - // - // The default is no timeout. - Timeout time.Duration - - // Protocols is the list of subprotocols that the client wants to speak, - // ordered by preference. - // - // See https://tools.ietf.org/html/rfc6455#section-4.1 - Protocols []string - - // Extensions is the list of extensions that client wants to speak. - // - // Note that if server decides to use some of this extensions, Dial() will - // return Handshake struct containing a slice of items, which are the - // shallow copies of the items from this list. That is, internals of - // Extensions items are shared during Dial(). - // - // See https://tools.ietf.org/html/rfc6455#section-4.1 - // See https://tools.ietf.org/html/rfc6455#section-9.1 - Extensions []httphead.Option - - // Header is an optional HandshakeHeader instance that could be used to - // write additional headers to the handshake request. - // - // It used instead of any key-value mappings to avoid allocations in user - // land. - Header HandshakeHeader - - // Host is an optional string that could be used to specify the host during - // HTTP upgrade request by setting 'Host' header. - // - // Default value is an empty string, which results in setting 'Host' header - // equal to the URL hostname given to Dialer.Dial(). - Host string - - // OnStatusError is the callback that will be called after receiving non - // "101 Continue" HTTP response status. It receives an io.Reader object - // representing server response bytes. That is, it gives ability to parse - // HTTP response somehow (probably with http.ReadResponse call) and make a - // decision of further logic. - // - // The arguments are only valid until the callback returns. - OnStatusError func(status int, reason []byte, resp io.Reader) - - // OnHeader is the callback that will be called after successful parsing of - // header, that is not used during WebSocket handshake procedure. That is, - // it will be called with non-websocket headers, which could be relevant - // for application-level logic. - // - // The arguments are only valid until the callback returns. - // - // Returned value could be used to prevent processing response. - OnHeader func(key, value []byte) (err error) - - // NetDial is the function that is used to get plain tcp connection. - // If it is not nil, then it is used instead of net.Dialer. - NetDial func(ctx context.Context, network, addr string) (net.Conn, error) - - // TLSClient is the callback that will be called after successful dial with - // received connection and its remote host name. If it is nil, then the - // default tls.Client() will be used. - // If it is not nil, then TLSConfig field is ignored. - TLSClient func(conn net.Conn, hostname string) net.Conn - - // TLSConfig is passed to tls.Client() to start TLS over established - // connection. If TLSClient is not nil, then it is ignored. If TLSConfig is - // non-nil and its ServerName is empty, then for every Dial() it will be - // cloned and appropriate ServerName will be set. - TLSConfig *tls.Config - - // WrapConn is the optional callback that will be called when connection is - // ready for an i/o. That is, it will be called after successful dial and - // TLS initialization (for "wss" schemes). It may be helpful for different - // user land purposes such as end to end encryption. - // - // Note that for debugging purposes of an http handshake (e.g. sent request - // and received response), there is an wsutil.DebugDialer struct. - WrapConn func(conn net.Conn) net.Conn -} - -// Dial connects to the url host and upgrades connection to WebSocket. -// -// If server has sent frames right after successful handshake then returned -// buffer will be non-nil. In other cases buffer is always nil. For better -// memory efficiency received non-nil bufio.Reader should be returned to the -// inner pool with PutReader() function after use. -// -// Note that Dialer does not implement IDNA (RFC5895) logic as net/http does. -// If you want to dial non-ascii host name, take care of its name serialization -// avoiding bad request issues. For more info see net/http Request.Write() -// implementation, especially cleanHost() function. -func (d Dialer) Dial(ctx context.Context, urlstr string) (conn net.Conn, br *bufio.Reader, hs Handshake, err error) { - u, err := url.ParseRequestURI(urlstr) - if err != nil { - return nil, nil, hs, err - } - - // Prepare context to dial with. Initially it is the same as original, but - // if d.Timeout is non-zero and points to time that is before ctx.Deadline, - // we use more shorter context for dial. - dialctx := ctx - - var deadline time.Time - if t := d.Timeout; t != 0 { - deadline = time.Now().Add(t) - if d, ok := ctx.Deadline(); !ok || deadline.Before(d) { - var cancel context.CancelFunc - dialctx, cancel = context.WithDeadline(ctx, deadline) - defer cancel() - } - } - if conn, err = d.dial(dialctx, u); err != nil { - return conn, nil, hs, err - } - defer func() { - if err != nil { - conn.Close() - } - }() - if ctx == context.Background() { - // No need to start I/O interrupter goroutine which is not zero-cost. - conn.SetDeadline(deadline) - defer conn.SetDeadline(noDeadline) - } else { - // Context could be canceled or its deadline could be exceeded. - // Start the interrupter goroutine to handle context cancelation. - done := setupContextDeadliner(ctx, conn) - defer func() { - // Map Upgrade() error to a possible context expiration error. That - // is, even if Upgrade() err is nil, context could be already - // expired and connection be "poisoned" by SetDeadline() call. - // In that case we must not return ctx.Err() error. - done(&err) - }() - } - - br, hs, err = d.Upgrade(conn, u) - - return conn, br, hs, err -} - -var ( - // netEmptyDialer is a net.Dialer without options, used in Dialer.dial() if - // Dialer.NetDial is not provided. - netEmptyDialer net.Dialer - // tlsEmptyConfig is an empty tls.Config used as default one. - tlsEmptyConfig tls.Config -) - -func tlsDefaultConfig() *tls.Config { - return &tlsEmptyConfig -} - -func hostport(host, defaultPort string) (hostname, addr string) { - var ( - colon = strings.LastIndexByte(host, ':') - bracket = strings.IndexByte(host, ']') - ) - if colon > bracket { - return host[:colon], host - } - return host, host + defaultPort -} - -func (d Dialer) dial(ctx context.Context, u *url.URL) (conn net.Conn, err error) { - dial := d.NetDial - if dial == nil { - dial = netEmptyDialer.DialContext - } - switch u.Scheme { - case "ws": - _, addr := hostport(u.Host, ":80") - conn, err = dial(ctx, "tcp", addr) - case "wss": - hostname, addr := hostport(u.Host, ":443") - conn, err = dial(ctx, "tcp", addr) - if err != nil { - return nil, err - } - tlsClient := d.TLSClient - if tlsClient == nil { - tlsClient = d.tlsClient - } - conn = tlsClient(conn, hostname) - default: - return nil, fmt.Errorf("unexpected websocket scheme: %q", u.Scheme) - } - if wrap := d.WrapConn; wrap != nil { - conn = wrap(conn) - } - return conn, err -} - -func (d Dialer) tlsClient(conn net.Conn, hostname string) net.Conn { - config := d.TLSConfig - if config == nil { - config = tlsDefaultConfig() - } - if config.ServerName == "" { - config = tlsCloneConfig(config) - config.ServerName = hostname - } - // Do not make conn.Handshake() here because downstairs we will prepare - // i/o on this conn with proper context's timeout handling. - return tls.Client(conn, config) -} - -var ( - // This variables are set like in net/net.go. - // noDeadline is just zero value for readability. - noDeadline = time.Time{} - // aLongTimeAgo is a non-zero time, far in the past, used for immediate - // cancelation of dials. - aLongTimeAgo = time.Unix(42, 0) -) - -// Upgrade writes an upgrade request to the given io.ReadWriter conn at given -// url u and reads a response from it. -// -// It is a caller responsibility to manage I/O deadlines on conn. -// -// It returns handshake info and some bytes which could be written by the peer -// right after response and be caught by us during buffered read. -func (d Dialer) Upgrade(conn io.ReadWriter, u *url.URL) (br *bufio.Reader, hs Handshake, err error) { - // headerSeen constants helps to report whether or not some header was seen - // during reading request bytes. - const ( - headerSeenUpgrade = 1 << iota - headerSeenConnection - headerSeenSecAccept - - // headerSeenAll is the value that we expect to receive at the end of - // headers read/parse loop. - headerSeenAll = 0 | - headerSeenUpgrade | - headerSeenConnection | - headerSeenSecAccept - ) - - br = pbufio.GetReader(conn, - nonZero(d.ReadBufferSize, DefaultClientReadBufferSize), - ) - bw := pbufio.GetWriter(conn, - nonZero(d.WriteBufferSize, DefaultClientWriteBufferSize), - ) - defer func() { - pbufio.PutWriter(bw) - if br.Buffered() == 0 || err != nil { - // Server does not wrote additional bytes to the connection or - // error occurred. That is, no reason to return buffer. - pbufio.PutReader(br) - br = nil - } - }() - - nonce := make([]byte, nonceSize) - initNonce(nonce) - - httpWriteUpgradeRequest(bw, u, nonce, d.Protocols, d.Extensions, d.Header, d.Host) - if err := bw.Flush(); err != nil { - return br, hs, err - } - - // Read HTTP status line like "HTTP/1.1 101 Switching Protocols". - sl, err := readLine(br) - if err != nil { - return br, hs, err - } - // Begin validation of the response. - // See https://tools.ietf.org/html/rfc6455#section-4.2.2 - // Parse request line data like HTTP version, uri and method. - resp, err := httpParseResponseLine(sl) - if err != nil { - return br, hs, err - } - // Even if RFC says "1.1 or higher" without mentioning the part of the - // version, we apply it only to minor part. - if resp.major != 1 || resp.minor < 1 { - err = ErrHandshakeBadProtocol - return br, hs, err - } - if resp.status != http.StatusSwitchingProtocols { - err = StatusError(resp.status) - if onStatusError := d.OnStatusError; onStatusError != nil { - // Invoke callback with multireader of status-line bytes br. - onStatusError(resp.status, resp.reason, - io.MultiReader( - bytes.NewReader(sl), - strings.NewReader(crlf), - br, - ), - ) - } - return br, hs, err - } - // If response status is 101 then we expect all technical headers to be - // valid. If not, then we stop processing response without giving user - // ability to read non-technical headers. That is, we do not distinguish - // technical errors (such as parsing error) and protocol errors. - var headerSeen byte - for { - line, e := readLine(br) - if e != nil { - err = e - return br, hs, err - } - if len(line) == 0 { - // Blank line, no more lines to read. - break - } - - k, v, ok := httpParseHeaderLine(line) - if !ok { - err = ErrMalformedResponse - return br, hs, err - } - - switch btsToString(k) { - case headerUpgradeCanonical: - headerSeen |= headerSeenUpgrade - if !bytes.Equal(v, specHeaderValueUpgrade) && !bytes.EqualFold(v, specHeaderValueUpgrade) { - err = ErrHandshakeBadUpgrade - return br, hs, err - } - - case headerConnectionCanonical: - headerSeen |= headerSeenConnection - // Note that as RFC6455 says: - // > A |Connection| header field with value "Upgrade". - // That is, in server side, "Connection" header could contain - // multiple token. But in response it must contains exactly one. - if !bytes.Equal(v, specHeaderValueConnection) && !bytes.EqualFold(v, specHeaderValueConnection) { - err = ErrHandshakeBadConnection - return br, hs, err - } - - case headerSecAcceptCanonical: - headerSeen |= headerSeenSecAccept - if !checkAcceptFromNonce(v, nonce) { - err = ErrHandshakeBadSecAccept - return br, hs, err - } - - case headerSecProtocolCanonical: - // RFC6455 1.3: - // "The server selects one or none of the acceptable protocols - // and echoes that value in its handshake to indicate that it has - // selected that protocol." - for _, want := range d.Protocols { - if string(v) == want { - hs.Protocol = want - break - } - } - if hs.Protocol == "" { - // Server echoed subprotocol that is not present in client - // requested protocols. - err = ErrHandshakeBadSubProtocol - return br, hs, err - } - - case headerSecExtensionsCanonical: - hs.Extensions, err = matchSelectedExtensions(v, d.Extensions, hs.Extensions) - if err != nil { - return br, hs, err - } - - default: - if onHeader := d.OnHeader; onHeader != nil { - if e := onHeader(k, v); e != nil { - err = e - return br, hs, err - } - } - } - } - if err == nil && headerSeen != headerSeenAll { - switch { - case headerSeen&headerSeenUpgrade == 0: - err = ErrHandshakeBadUpgrade - case headerSeen&headerSeenConnection == 0: - err = ErrHandshakeBadConnection - case headerSeen&headerSeenSecAccept == 0: - err = ErrHandshakeBadSecAccept - default: - panic("unknown headers state") - } - } - return br, hs, err -} - -// PutReader returns bufio.Reader instance to the inner reuse pool. -// It is useful in rare cases, when Dialer.Dial() returns non-nil buffer which -// contains unprocessed buffered data, that was sent by the server quickly -// right after handshake. -func PutReader(br *bufio.Reader) { - pbufio.PutReader(br) -} - -// StatusError contains an unexpected status-line code from the server. -type StatusError int - -func (s StatusError) Error() string { - return "unexpected HTTP response status: " + strconv.Itoa(int(s)) -} - -func isTimeoutError(err error) bool { - t, ok := err.(net.Error) - return ok && t.Timeout() -} - -func matchSelectedExtensions(selected []byte, wanted, received []httphead.Option) ([]httphead.Option, error) { - if len(selected) == 0 { - return received, nil - } - var ( - index int - option httphead.Option - err error - ) - index = -1 - match := func() (ok bool) { - for _, want := range wanted { - // A server accepts one or more extensions by including a - // |Sec-WebSocket-Extensions| header field containing one or more - // extensions that were requested by the client. - // - // The interpretation of any extension parameters, and what - // constitutes a valid response by a server to a requested set of - // parameters by a client, will be defined by each such extension. - if bytes.Equal(option.Name, want.Name) { - // Check parsed extension to be present in client - // requested extensions. We move matched extension - // from client list to avoid allocation of httphead.Option.Name, - // httphead.Option.Parameters have to be copied from the header - want.Parameters, _ = option.Parameters.Copy(make([]byte, option.Parameters.Size())) - received = append(received, want) - return true - } - } - return false - } - ok := httphead.ScanOptions(selected, func(i int, name, attr, val []byte) httphead.Control { - if i != index { - // Met next option. - index = i - if i != 0 && !match() { - // Server returned non-requested extension. - err = ErrHandshakeBadExtensions - return httphead.ControlBreak - } - option = httphead.Option{Name: name} - } - if attr != nil { - option.Parameters.Set(attr, val) - } - return httphead.ControlContinue - }) - if !ok { - err = ErrMalformedResponse - return received, err - } - if !match() { - return received, ErrHandshakeBadExtensions - } - return received, err -} - -// setupContextDeadliner is a helper function that starts connection I/O -// interrupter goroutine. -// -// Started goroutine calls SetDeadline() with long time ago value when context -// become expired to make any I/O operations failed. It returns done function -// that stops started goroutine and maps error received from conn I/O methods -// to possible context expiration error. -// -// In concern with possible SetDeadline() call inside interrupter goroutine, -// caller passes pointer to its I/O error (even if it is nil) to done(&err). -// That is, even if I/O error is nil, context could be already expired and -// connection "poisoned" by SetDeadline() call. In that case done(&err) will -// store at *err ctx.Err() result. If err is caused not by timeout, it will -// leaved untouched. -func setupContextDeadliner(ctx context.Context, conn net.Conn) (done func(*error)) { - var ( - quit = make(chan struct{}) - interrupt = make(chan error, 1) - ) - go func() { - select { - case <-quit: - interrupt <- nil - case <-ctx.Done(): - // Cancel i/o immediately. - conn.SetDeadline(aLongTimeAgo) - interrupt <- ctx.Err() - } - }() - return func(err *error) { - close(quit) - // If ctx.Err() is non-nil and the original err is net.Error with - // Timeout() == true, then it means that I/O was canceled by us by - // SetDeadline(aLongTimeAgo) call, or by somebody else previously - // by conn.SetDeadline(x). - // - // Even on race condition when both deadlines are expired - // (SetDeadline() made not by us and context's), we prefer ctx.Err() to - // be returned. - if ctxErr := <-interrupt; ctxErr != nil && (*err == nil || isTimeoutError(*err)) { - *err = ctxErr - } - } -} diff --git a/vendor/github.com/gobwas/ws/dialer_tls_go17.go b/vendor/github.com/gobwas/ws/dialer_tls_go17.go deleted file mode 100644 index b606e0ad9..000000000 --- a/vendor/github.com/gobwas/ws/dialer_tls_go17.go +++ /dev/null @@ -1,35 +0,0 @@ -// +build !go1.8 - -package ws - -import "crypto/tls" - -func tlsCloneConfig(c *tls.Config) *tls.Config { - // NOTE: we copying SessionTicketsDisabled and SessionTicketKey here - // without calling inner c.initOnceServer somehow because we only could get - // here from the ws.Dialer code, which is obviously a client and makes - // tls.Client() when it gets new net.Conn. - return &tls.Config{ - Rand: c.Rand, - Time: c.Time, - Certificates: c.Certificates, - NameToCertificate: c.NameToCertificate, - GetCertificate: c.GetCertificate, - RootCAs: c.RootCAs, - NextProtos: c.NextProtos, - ServerName: c.ServerName, - ClientAuth: c.ClientAuth, - ClientCAs: c.ClientCAs, - InsecureSkipVerify: c.InsecureSkipVerify, - CipherSuites: c.CipherSuites, - PreferServerCipherSuites: c.PreferServerCipherSuites, - SessionTicketsDisabled: c.SessionTicketsDisabled, - SessionTicketKey: c.SessionTicketKey, - ClientSessionCache: c.ClientSessionCache, - MinVersion: c.MinVersion, - MaxVersion: c.MaxVersion, - CurvePreferences: c.CurvePreferences, - DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled, - Renegotiation: c.Renegotiation, - } -} diff --git a/vendor/github.com/gobwas/ws/dialer_tls_go18.go b/vendor/github.com/gobwas/ws/dialer_tls_go18.go deleted file mode 100644 index 5589ee5e7..000000000 --- a/vendor/github.com/gobwas/ws/dialer_tls_go18.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build go1.8 -// +build go1.8 - -package ws - -import "crypto/tls" - -func tlsCloneConfig(c *tls.Config) *tls.Config { - return c.Clone() -} diff --git a/vendor/github.com/gobwas/ws/doc.go b/vendor/github.com/gobwas/ws/doc.go deleted file mode 100644 index 0118ce2cb..000000000 --- a/vendor/github.com/gobwas/ws/doc.go +++ /dev/null @@ -1,81 +0,0 @@ -/* -Package ws implements a client and server for the WebSocket protocol as -specified in RFC 6455. - -The main purpose of this package is to provide simple low-level API for -efficient work with protocol. - -Overview. - -Upgrade to WebSocket (or WebSocket handshake) can be done in two ways. - -The first way is to use `net/http` server: - - http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - conn, _, _, err := ws.UpgradeHTTP(r, w) - }) - -The second and much more efficient way is so-called "zero-copy upgrade". It -avoids redundant allocations and copying of not used headers or other request -data. User decides by himself which data should be copied. - - ln, err := net.Listen("tcp", ":8080") - if err != nil { - // handle error - } - - conn, err := ln.Accept() - if err != nil { - // handle error - } - - handshake, err := ws.Upgrade(conn) - if err != nil { - // handle error - } - -For customization details see `ws.Upgrader` documentation. - -After WebSocket handshake you can work with connection in multiple ways. -That is, `ws` does not force the only one way of how to work with WebSocket: - - header, err := ws.ReadHeader(conn) - if err != nil { - // handle err - } - - buf := make([]byte, header.Length) - _, err := io.ReadFull(conn, buf) - if err != nil { - // handle err - } - - resp := ws.NewBinaryFrame([]byte("hello, world!")) - if err := ws.WriteFrame(conn, frame); err != nil { - // handle err - } - -As you can see, it stream friendly: - - const N = 42 - - ws.WriteHeader(ws.Header{ - Fin: true, - Length: N, - OpCode: ws.OpBinary, - }) - - io.CopyN(conn, rand.Reader, N) - -Or: - - header, err := ws.ReadHeader(conn) - if err != nil { - // handle err - } - - io.CopyN(ioutil.Discard, conn, header.Length) - -For more info see the documentation. -*/ -package ws diff --git a/vendor/github.com/gobwas/ws/errors.go b/vendor/github.com/gobwas/ws/errors.go deleted file mode 100644 index f5668b2be..000000000 --- a/vendor/github.com/gobwas/ws/errors.go +++ /dev/null @@ -1,59 +0,0 @@ -package ws - -// RejectOption represents an option used to control the way connection is -// rejected. -type RejectOption func(*ConnectionRejectedError) - -// RejectionReason returns an option that makes connection to be rejected with -// given reason. -func RejectionReason(reason string) RejectOption { - return func(err *ConnectionRejectedError) { - err.reason = reason - } -} - -// RejectionStatus returns an option that makes connection to be rejected with -// given HTTP status code. -func RejectionStatus(code int) RejectOption { - return func(err *ConnectionRejectedError) { - err.code = code - } -} - -// RejectionHeader returns an option that makes connection to be rejected with -// given HTTP headers. -func RejectionHeader(h HandshakeHeader) RejectOption { - return func(err *ConnectionRejectedError) { - err.header = h - } -} - -// RejectConnectionError constructs an error that could be used to control the -// way handshake is rejected by Upgrader. -func RejectConnectionError(options ...RejectOption) error { - err := new(ConnectionRejectedError) - for _, opt := range options { - opt(err) - } - return err -} - -// ConnectionRejectedError represents a rejection of connection during -// WebSocket handshake error. -// -// It can be returned by Upgrader's On* hooks to indicate that WebSocket -// handshake should be rejected. -type ConnectionRejectedError struct { - reason string - code int - header HandshakeHeader -} - -// Error implements error interface. -func (r *ConnectionRejectedError) Error() string { - return r.reason -} - -func (r *ConnectionRejectedError) StatusCode() int { - return r.code -} diff --git a/vendor/github.com/gobwas/ws/frame.go b/vendor/github.com/gobwas/ws/frame.go deleted file mode 100644 index ae10144e1..000000000 --- a/vendor/github.com/gobwas/ws/frame.go +++ /dev/null @@ -1,420 +0,0 @@ -package ws - -import ( - "bytes" - "encoding/binary" - "math/rand" -) - -// Constants defined by specification. -const ( - // All control frames MUST have a payload length of 125 bytes or less and MUST NOT be fragmented. - MaxControlFramePayloadSize = 125 -) - -// OpCode represents operation code. -type OpCode byte - -// Operation codes defined by specification. -// See https://tools.ietf.org/html/rfc6455#section-5.2 -const ( - OpContinuation OpCode = 0x0 - OpText OpCode = 0x1 - OpBinary OpCode = 0x2 - OpClose OpCode = 0x8 - OpPing OpCode = 0x9 - OpPong OpCode = 0xa -) - -// IsControl checks whether the c is control operation code. -// See https://tools.ietf.org/html/rfc6455#section-5.5 -func (c OpCode) IsControl() bool { - // RFC6455: Control frames are identified by opcodes where - // the most significant bit of the opcode is 1. - // - // Note that OpCode is only 4 bit length. - return c&0x8 != 0 -} - -// IsData checks whether the c is data operation code. -// See https://tools.ietf.org/html/rfc6455#section-5.6 -func (c OpCode) IsData() bool { - // RFC6455: Data frames (e.g., non-control frames) are identified by opcodes - // where the most significant bit of the opcode is 0. - // - // Note that OpCode is only 4 bit length. - return c&0x8 == 0 -} - -// IsReserved checks whether the c is reserved operation code. -// See https://tools.ietf.org/html/rfc6455#section-5.2 -func (c OpCode) IsReserved() bool { - // RFC6455: - // %x3-7 are reserved for further non-control frames - // %xB-F are reserved for further control frames - return (0x3 <= c && c <= 0x7) || (0xb <= c && c <= 0xf) -} - -// StatusCode represents the encoded reason for closure of websocket connection. -// -// There are few helper methods on StatusCode that helps to define a range in -// which given code is lay in. accordingly to ranges defined in specification. -// -// See https://tools.ietf.org/html/rfc6455#section-7.4 -type StatusCode uint16 - -// StatusCodeRange describes range of StatusCode values. -type StatusCodeRange struct { - Min, Max StatusCode -} - -// Status code ranges defined by specification. -// See https://tools.ietf.org/html/rfc6455#section-7.4.2 -var ( - StatusRangeNotInUse = StatusCodeRange{0, 999} - StatusRangeProtocol = StatusCodeRange{1000, 2999} - StatusRangeApplication = StatusCodeRange{3000, 3999} - StatusRangePrivate = StatusCodeRange{4000, 4999} -) - -// Status codes defined by specification. -// See https://tools.ietf.org/html/rfc6455#section-7.4.1 -const ( - StatusNormalClosure StatusCode = 1000 - StatusGoingAway StatusCode = 1001 - StatusProtocolError StatusCode = 1002 - StatusUnsupportedData StatusCode = 1003 - StatusNoMeaningYet StatusCode = 1004 - StatusInvalidFramePayloadData StatusCode = 1007 - StatusPolicyViolation StatusCode = 1008 - StatusMessageTooBig StatusCode = 1009 - StatusMandatoryExt StatusCode = 1010 - StatusInternalServerError StatusCode = 1011 - StatusTLSHandshake StatusCode = 1015 - - // StatusAbnormalClosure is a special code designated for use in - // applications. - StatusAbnormalClosure StatusCode = 1006 - - // StatusNoStatusRcvd is a special code designated for use in applications. - StatusNoStatusRcvd StatusCode = 1005 -) - -// In reports whether the code is defined in given range. -func (s StatusCode) In(r StatusCodeRange) bool { - return r.Min <= s && s <= r.Max -} - -// Empty reports whether the code is empty. -// Empty code has no any meaning neither app level codes nor other. -// This method is useful just to check that code is golang default value 0. -func (s StatusCode) Empty() bool { - return s == 0 -} - -// IsNotUsed reports whether the code is predefined in not used range. -func (s StatusCode) IsNotUsed() bool { - return s.In(StatusRangeNotInUse) -} - -// IsApplicationSpec reports whether the code should be defined by -// application, framework or libraries specification. -func (s StatusCode) IsApplicationSpec() bool { - return s.In(StatusRangeApplication) -} - -// IsPrivateSpec reports whether the code should be defined privately. -func (s StatusCode) IsPrivateSpec() bool { - return s.In(StatusRangePrivate) -} - -// IsProtocolSpec reports whether the code should be defined by protocol specification. -func (s StatusCode) IsProtocolSpec() bool { - return s.In(StatusRangeProtocol) -} - -// IsProtocolDefined reports whether the code is already defined by protocol specification. -func (s StatusCode) IsProtocolDefined() bool { - switch s { - case StatusNormalClosure, - StatusGoingAway, - StatusProtocolError, - StatusUnsupportedData, - StatusInvalidFramePayloadData, - StatusPolicyViolation, - StatusMessageTooBig, - StatusMandatoryExt, - StatusInternalServerError, - StatusNoStatusRcvd, - StatusAbnormalClosure, - StatusTLSHandshake: - return true - } - return false -} - -// IsProtocolReserved reports whether the code is defined by protocol specification -// to be reserved only for application usage purpose. -func (s StatusCode) IsProtocolReserved() bool { - switch s { - // [RFC6455]: {1005,1006,1015} is a reserved value and MUST NOT be set as a status code in a - // Close control frame by an endpoint. - case StatusNoStatusRcvd, StatusAbnormalClosure, StatusTLSHandshake: - return true - default: - return false - } -} - -// Compiled control frames for common use cases. -// For construct-serialize optimizations. -var ( - CompiledPing = MustCompileFrame(NewPingFrame(nil)) - CompiledPong = MustCompileFrame(NewPongFrame(nil)) - CompiledClose = MustCompileFrame(NewCloseFrame(nil)) - - CompiledCloseNormalClosure = MustCompileFrame(closeFrameNormalClosure) - CompiledCloseGoingAway = MustCompileFrame(closeFrameGoingAway) - CompiledCloseProtocolError = MustCompileFrame(closeFrameProtocolError) - CompiledCloseUnsupportedData = MustCompileFrame(closeFrameUnsupportedData) - CompiledCloseNoMeaningYet = MustCompileFrame(closeFrameNoMeaningYet) - CompiledCloseInvalidFramePayloadData = MustCompileFrame(closeFrameInvalidFramePayloadData) - CompiledClosePolicyViolation = MustCompileFrame(closeFramePolicyViolation) - CompiledCloseMessageTooBig = MustCompileFrame(closeFrameMessageTooBig) - CompiledCloseMandatoryExt = MustCompileFrame(closeFrameMandatoryExt) - CompiledCloseInternalServerError = MustCompileFrame(closeFrameInternalServerError) - CompiledCloseTLSHandshake = MustCompileFrame(closeFrameTLSHandshake) -) - -// Header represents websocket frame header. -// See https://tools.ietf.org/html/rfc6455#section-5.2 -type Header struct { - Fin bool - Rsv byte - OpCode OpCode - Masked bool - Mask [4]byte - Length int64 -} - -// Rsv1 reports whether the header has first rsv bit set. -func (h Header) Rsv1() bool { return h.Rsv&bit5 != 0 } - -// Rsv2 reports whether the header has second rsv bit set. -func (h Header) Rsv2() bool { return h.Rsv&bit6 != 0 } - -// Rsv3 reports whether the header has third rsv bit set. -func (h Header) Rsv3() bool { return h.Rsv&bit7 != 0 } - -// Rsv creates rsv byte representation from bits. -func Rsv(r1, r2, r3 bool) (rsv byte) { - if r1 { - rsv |= bit5 - } - if r2 { - rsv |= bit6 - } - if r3 { - rsv |= bit7 - } - return rsv -} - -// RsvBits returns rsv bits from bytes representation. -func RsvBits(rsv byte) (r1, r2, r3 bool) { - r1 = rsv&bit5 != 0 - r2 = rsv&bit6 != 0 - r3 = rsv&bit7 != 0 - return r1, r2, r3 -} - -// Frame represents websocket frame. -// See https://tools.ietf.org/html/rfc6455#section-5.2 -type Frame struct { - Header Header - Payload []byte -} - -// NewFrame creates frame with given operation code, -// flag of completeness and payload bytes. -func NewFrame(op OpCode, fin bool, p []byte) Frame { - return Frame{ - Header: Header{ - Fin: fin, - OpCode: op, - Length: int64(len(p)), - }, - Payload: p, - } -} - -// NewTextFrame creates text frame with p as payload. -// Note that p is not copied. -func NewTextFrame(p []byte) Frame { - return NewFrame(OpText, true, p) -} - -// NewBinaryFrame creates binary frame with p as payload. -// Note that p is not copied. -func NewBinaryFrame(p []byte) Frame { - return NewFrame(OpBinary, true, p) -} - -// NewPingFrame creates ping frame with p as payload. -// Note that p is not copied. -// Note that p must have length of MaxControlFramePayloadSize bytes or less due -// to RFC. -func NewPingFrame(p []byte) Frame { - return NewFrame(OpPing, true, p) -} - -// NewPongFrame creates pong frame with p as payload. -// Note that p is not copied. -// Note that p must have length of MaxControlFramePayloadSize bytes or less due -// to RFC. -func NewPongFrame(p []byte) Frame { - return NewFrame(OpPong, true, p) -} - -// NewCloseFrame creates close frame with given close body. -// Note that p is not copied. -// Note that p must have length of MaxControlFramePayloadSize bytes or less due -// to RFC. -func NewCloseFrame(p []byte) Frame { - return NewFrame(OpClose, true, p) -} - -// NewCloseFrameBody encodes a closure code and a reason into a binary -// representation. -// -// It returns slice which is at most MaxControlFramePayloadSize bytes length. -// If the reason is too big it will be cropped to fit the limit defined by the -// spec. -// -// See https://tools.ietf.org/html/rfc6455#section-5.5 -func NewCloseFrameBody(code StatusCode, reason string) []byte { - n := min(2+len(reason), MaxControlFramePayloadSize) - p := make([]byte, n) - - crop := min(MaxControlFramePayloadSize-2, len(reason)) - PutCloseFrameBody(p, code, reason[:crop]) - - return p -} - -// PutCloseFrameBody encodes code and reason into buf. -// -// It will panic if the buffer is too small to accommodate a code or a reason. -// -// PutCloseFrameBody does not check buffer to be RFC compliant, but note that -// by RFC it must be at most MaxControlFramePayloadSize. -func PutCloseFrameBody(p []byte, code StatusCode, reason string) { - _ = p[1+len(reason)] - binary.BigEndian.PutUint16(p, uint16(code)) - copy(p[2:], reason) -} - -// MaskFrame masks frame and returns frame with masked payload and Mask header's field set. -// Note that it copies f payload to prevent collisions. -// For less allocations you could use MaskFrameInPlace or construct frame manually. -func MaskFrame(f Frame) Frame { - return MaskFrameWith(f, NewMask()) -} - -// MaskFrameWith masks frame with given mask and returns frame -// with masked payload and Mask header's field set. -// Note that it copies f payload to prevent collisions. -// For less allocations you could use MaskFrameInPlaceWith or construct frame manually. -func MaskFrameWith(f Frame, mask [4]byte) Frame { - // TODO(gobwas): check CopyCipher ws copy() Cipher(). - p := make([]byte, len(f.Payload)) - copy(p, f.Payload) - f.Payload = p - return MaskFrameInPlaceWith(f, mask) -} - -// MaskFrameInPlace masks frame and returns frame with masked payload and Mask -// header's field set. -// Note that it applies xor cipher to f.Payload without copying, that is, it -// modifies f.Payload inplace. -func MaskFrameInPlace(f Frame) Frame { - return MaskFrameInPlaceWith(f, NewMask()) -} - -var zeroMask [4]byte - -// UnmaskFrame unmasks frame and returns frame with unmasked payload and Mask -// header's field cleared. -// Note that it copies f payload. -func UnmaskFrame(f Frame) Frame { - p := make([]byte, len(f.Payload)) - copy(p, f.Payload) - f.Payload = p - return UnmaskFrameInPlace(f) -} - -// UnmaskFrameInPlace unmasks frame and returns frame with unmasked payload and -// Mask header's field cleared. -// Note that it applies xor cipher to f.Payload without copying, that is, it -// modifies f.Payload inplace. -func UnmaskFrameInPlace(f Frame) Frame { - Cipher(f.Payload, f.Header.Mask, 0) - f.Header.Masked = false - f.Header.Mask = zeroMask - return f -} - -// MaskFrameInPlaceWith masks frame with given mask and returns frame -// with masked payload and Mask header's field set. -// Note that it applies xor cipher to f.Payload without copying, that is, it -// modifies f.Payload inplace. -func MaskFrameInPlaceWith(f Frame, m [4]byte) Frame { - f.Header.Masked = true - f.Header.Mask = m - Cipher(f.Payload, m, 0) - return f -} - -// NewMask creates new random mask. -func NewMask() (ret [4]byte) { - binary.BigEndian.PutUint32(ret[:], rand.Uint32()) - return ret -} - -// CompileFrame returns byte representation of given frame. -// In terms of memory consumption it is useful to precompile static frames -// which are often used. -func CompileFrame(f Frame) (bts []byte, err error) { - buf := bytes.NewBuffer(make([]byte, 0, 16)) - err = WriteFrame(buf, f) - bts = buf.Bytes() - return bts, err -} - -// MustCompileFrame is like CompileFrame but panics if frame can not be -// encoded. -func MustCompileFrame(f Frame) []byte { - bts, err := CompileFrame(f) - if err != nil { - panic(err) - } - return bts -} - -func makeCloseFrame(code StatusCode) Frame { - return NewCloseFrame(NewCloseFrameBody(code, "")) -} - -var ( - closeFrameNormalClosure = makeCloseFrame(StatusNormalClosure) - closeFrameGoingAway = makeCloseFrame(StatusGoingAway) - closeFrameProtocolError = makeCloseFrame(StatusProtocolError) - closeFrameUnsupportedData = makeCloseFrame(StatusUnsupportedData) - closeFrameNoMeaningYet = makeCloseFrame(StatusNoMeaningYet) - closeFrameInvalidFramePayloadData = makeCloseFrame(StatusInvalidFramePayloadData) - closeFramePolicyViolation = makeCloseFrame(StatusPolicyViolation) - closeFrameMessageTooBig = makeCloseFrame(StatusMessageTooBig) - closeFrameMandatoryExt = makeCloseFrame(StatusMandatoryExt) - closeFrameInternalServerError = makeCloseFrame(StatusInternalServerError) - closeFrameTLSHandshake = makeCloseFrame(StatusTLSHandshake) -) diff --git a/vendor/github.com/gobwas/ws/hijack_go119.go b/vendor/github.com/gobwas/ws/hijack_go119.go deleted file mode 100644 index 6ac556c10..000000000 --- a/vendor/github.com/gobwas/ws/hijack_go119.go +++ /dev/null @@ -1,18 +0,0 @@ -//go:build !go1.20 -// +build !go1.20 - -package ws - -import ( - "bufio" - "net" - "net/http" -) - -func hijack(w http.ResponseWriter) (net.Conn, *bufio.ReadWriter, error) { - hj, ok := w.(http.Hijacker) - if ok { - return hj.Hijack() - } - return nil, nil, ErrNotHijacker -} diff --git a/vendor/github.com/gobwas/ws/hijack_go120.go b/vendor/github.com/gobwas/ws/hijack_go120.go deleted file mode 100644 index e67b439de..000000000 --- a/vendor/github.com/gobwas/ws/hijack_go120.go +++ /dev/null @@ -1,19 +0,0 @@ -//go:build go1.20 -// +build go1.20 - -package ws - -import ( - "bufio" - "errors" - "net" - "net/http" -) - -func hijack(w http.ResponseWriter) (net.Conn, *bufio.ReadWriter, error) { - conn, rw, err := http.NewResponseController(w).Hijack() - if errors.Is(err, http.ErrNotSupported) { - return nil, nil, ErrNotHijacker - } - return conn, rw, err -} diff --git a/vendor/github.com/gobwas/ws/http.go b/vendor/github.com/gobwas/ws/http.go deleted file mode 100644 index a3a682d34..000000000 --- a/vendor/github.com/gobwas/ws/http.go +++ /dev/null @@ -1,507 +0,0 @@ -package ws - -import ( - "bufio" - "bytes" - "io" - "net/http" - "net/url" - "strconv" - - "github.com/gobwas/httphead" -) - -const ( - crlf = "\r\n" - colonAndSpace = ": " - commaAndSpace = ", " -) - -const ( - textHeadUpgrade = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" -) - -var ( - textHeadBadRequest = statusText(http.StatusBadRequest) - textHeadInternalServerError = statusText(http.StatusInternalServerError) - textHeadUpgradeRequired = statusText(http.StatusUpgradeRequired) - - textTailErrHandshakeBadProtocol = errorText(ErrHandshakeBadProtocol) - textTailErrHandshakeBadMethod = errorText(ErrHandshakeBadMethod) - textTailErrHandshakeBadHost = errorText(ErrHandshakeBadHost) - textTailErrHandshakeBadUpgrade = errorText(ErrHandshakeBadUpgrade) - textTailErrHandshakeBadConnection = errorText(ErrHandshakeBadConnection) - textTailErrHandshakeBadSecAccept = errorText(ErrHandshakeBadSecAccept) - textTailErrHandshakeBadSecKey = errorText(ErrHandshakeBadSecKey) - textTailErrHandshakeBadSecVersion = errorText(ErrHandshakeBadSecVersion) - textTailErrUpgradeRequired = errorText(ErrHandshakeUpgradeRequired) -) - -const ( - // Every new header must be added to TestHeaderNames test. - headerHost = "Host" - headerUpgrade = "Upgrade" - headerConnection = "Connection" - headerSecVersion = "Sec-WebSocket-Version" - headerSecProtocol = "Sec-WebSocket-Protocol" - headerSecExtensions = "Sec-WebSocket-Extensions" - headerSecKey = "Sec-WebSocket-Key" - headerSecAccept = "Sec-WebSocket-Accept" - - headerHostCanonical = headerHost - headerUpgradeCanonical = headerUpgrade - headerConnectionCanonical = headerConnection - headerSecVersionCanonical = "Sec-Websocket-Version" - headerSecProtocolCanonical = "Sec-Websocket-Protocol" - headerSecExtensionsCanonical = "Sec-Websocket-Extensions" - headerSecKeyCanonical = "Sec-Websocket-Key" - headerSecAcceptCanonical = "Sec-Websocket-Accept" -) - -var ( - specHeaderValueUpgrade = []byte("websocket") - specHeaderValueConnection = []byte("Upgrade") - specHeaderValueConnectionLower = []byte("upgrade") - specHeaderValueSecVersion = []byte("13") -) - -var ( - httpVersion1_0 = []byte("HTTP/1.0") - httpVersion1_1 = []byte("HTTP/1.1") - httpVersionPrefix = []byte("HTTP/") -) - -type httpRequestLine struct { - method, uri []byte - major, minor int -} - -type httpResponseLine struct { - major, minor int - status int - reason []byte -} - -// httpParseRequestLine parses http request line like "GET / HTTP/1.0". -func httpParseRequestLine(line []byte) (req httpRequestLine, err error) { - var proto []byte - req.method, req.uri, proto = bsplit3(line, ' ') - - var ok bool - req.major, req.minor, ok = httpParseVersion(proto) - if !ok { - err = ErrMalformedRequest - } - return req, err -} - -func httpParseResponseLine(line []byte) (resp httpResponseLine, err error) { - var ( - proto []byte - status []byte - ) - proto, status, resp.reason = bsplit3(line, ' ') - - var ok bool - resp.major, resp.minor, ok = httpParseVersion(proto) - if !ok { - return resp, ErrMalformedResponse - } - - var convErr error - resp.status, convErr = asciiToInt(status) - if convErr != nil { - return resp, ErrMalformedResponse - } - - return resp, nil -} - -// httpParseVersion parses major and minor version of HTTP protocol. It returns -// parsed values and true if parse is ok. -func httpParseVersion(bts []byte) (major, minor int, ok bool) { - switch { - case bytes.Equal(bts, httpVersion1_0): - return 1, 0, true - case bytes.Equal(bts, httpVersion1_1): - return 1, 1, true - case len(bts) < 8: - return 0, 0, false - case !bytes.Equal(bts[:5], httpVersionPrefix): - return 0, 0, false - } - - bts = bts[5:] - - dot := bytes.IndexByte(bts, '.') - if dot == -1 { - return 0, 0, false - } - var err error - major, err = asciiToInt(bts[:dot]) - if err != nil { - return major, 0, false - } - minor, err = asciiToInt(bts[dot+1:]) - if err != nil { - return major, minor, false - } - - return major, minor, true -} - -// httpParseHeaderLine parses HTTP header as key-value pair. It returns parsed -// values and true if parse is ok. -func httpParseHeaderLine(line []byte) (k, v []byte, ok bool) { - colon := bytes.IndexByte(line, ':') - if colon == -1 { - return nil, nil, false - } - - k = btrim(line[:colon]) - // TODO(gobwas): maybe use just lower here? - canonicalizeHeaderKey(k) - - v = btrim(line[colon+1:]) - - return k, v, true -} - -// httpGetHeader is the same as textproto.MIMEHeader.Get, except the thing, -// that key is already canonical. This helps to increase performance. -func httpGetHeader(h http.Header, key string) string { - if h == nil { - return "" - } - v := h[key] - if len(v) == 0 { - return "" - } - return v[0] -} - -// The request MAY include a header field with the name -// |Sec-WebSocket-Protocol|. If present, this value indicates one or more -// comma-separated subprotocol the client wishes to speak, ordered by -// preference. The elements that comprise this value MUST be non-empty strings -// with characters in the range U+0021 to U+007E not including separator -// characters as defined in [RFC2616] and MUST all be unique strings. The ABNF -// for the value of this header field is 1#token, where the definitions of -// constructs and rules are as given in [RFC2616]. -func strSelectProtocol(h string, check func(string) bool) (ret string, ok bool) { - ok = httphead.ScanTokens(strToBytes(h), func(v []byte) bool { - if check(btsToString(v)) { - ret = string(v) - return false - } - return true - }) - return ret, ok -} - -func btsSelectProtocol(h []byte, check func([]byte) bool) (ret string, ok bool) { - var selected []byte - ok = httphead.ScanTokens(h, func(v []byte) bool { - if check(v) { - selected = v - return false - } - return true - }) - if ok && selected != nil { - return string(selected), true - } - return ret, ok -} - -func btsSelectExtensions(h []byte, selected []httphead.Option, check func(httphead.Option) bool) ([]httphead.Option, bool) { - s := httphead.OptionSelector{ - Flags: httphead.SelectCopy, - Check: check, - } - return s.Select(h, selected) -} - -func negotiateMaybe(in httphead.Option, dest []httphead.Option, f func(httphead.Option) (httphead.Option, error)) ([]httphead.Option, error) { - if in.Size() == 0 { - return dest, nil - } - opt, err := f(in) - if err != nil { - return nil, err - } - if opt.Size() > 0 { - dest = append(dest, opt) - } - return dest, nil -} - -func negotiateExtensions( - h []byte, dest []httphead.Option, - f func(httphead.Option) (httphead.Option, error), -) (_ []httphead.Option, err error) { - index := -1 - var current httphead.Option - ok := httphead.ScanOptions(h, func(i int, name, attr, val []byte) httphead.Control { - if i != index { - dest, err = negotiateMaybe(current, dest, f) - if err != nil { - return httphead.ControlBreak - } - index = i - current = httphead.Option{Name: name} - } - if attr != nil { - current.Parameters.Set(attr, val) - } - return httphead.ControlContinue - }) - if !ok { - return nil, ErrMalformedRequest - } - return negotiateMaybe(current, dest, f) -} - -func httpWriteHeader(bw *bufio.Writer, key, value string) { - httpWriteHeaderKey(bw, key) - bw.WriteString(value) - bw.WriteString(crlf) -} - -func httpWriteHeaderBts(bw *bufio.Writer, key string, value []byte) { - httpWriteHeaderKey(bw, key) - bw.Write(value) - bw.WriteString(crlf) -} - -func httpWriteHeaderKey(bw *bufio.Writer, key string) { - bw.WriteString(key) - bw.WriteString(colonAndSpace) -} - -func httpWriteUpgradeRequest( - bw *bufio.Writer, - u *url.URL, - nonce []byte, - protocols []string, - extensions []httphead.Option, - header HandshakeHeader, - host string, -) { - bw.WriteString("GET ") - bw.WriteString(u.RequestURI()) - bw.WriteString(" HTTP/1.1\r\n") - - if host == "" { - host = u.Host - } - httpWriteHeader(bw, headerHost, host) - - httpWriteHeaderBts(bw, headerUpgrade, specHeaderValueUpgrade) - httpWriteHeaderBts(bw, headerConnection, specHeaderValueConnection) - httpWriteHeaderBts(bw, headerSecVersion, specHeaderValueSecVersion) - - // NOTE: write nonce bytes as a string to prevent heap allocation – - // WriteString() copy given string into its inner buffer, unlike Write() - // which may write p directly to the underlying io.Writer – which in turn - // will lead to p escape. - httpWriteHeader(bw, headerSecKey, btsToString(nonce)) - - if len(protocols) > 0 { - httpWriteHeaderKey(bw, headerSecProtocol) - for i, p := range protocols { - if i > 0 { - bw.WriteString(commaAndSpace) - } - bw.WriteString(p) - } - bw.WriteString(crlf) - } - - if len(extensions) > 0 { - httpWriteHeaderKey(bw, headerSecExtensions) - httphead.WriteOptions(bw, extensions) - bw.WriteString(crlf) - } - - if header != nil { - header.WriteTo(bw) - } - - bw.WriteString(crlf) -} - -func httpWriteResponseUpgrade(bw *bufio.Writer, nonce []byte, hs Handshake, header HandshakeHeaderFunc) { - bw.WriteString(textHeadUpgrade) - - httpWriteHeaderKey(bw, headerSecAccept) - writeAccept(bw, nonce) - bw.WriteString(crlf) - - if hs.Protocol != "" { - httpWriteHeader(bw, headerSecProtocol, hs.Protocol) - } - if len(hs.Extensions) > 0 { - httpWriteHeaderKey(bw, headerSecExtensions) - httphead.WriteOptions(bw, hs.Extensions) - bw.WriteString(crlf) - } - if header != nil { - header(bw) - } - - bw.WriteString(crlf) -} - -func httpWriteResponseError(bw *bufio.Writer, err error, code int, header HandshakeHeaderFunc) { - switch code { - case http.StatusBadRequest: - bw.WriteString(textHeadBadRequest) - case http.StatusInternalServerError: - bw.WriteString(textHeadInternalServerError) - case http.StatusUpgradeRequired: - bw.WriteString(textHeadUpgradeRequired) - default: - writeStatusText(bw, code) - } - - // Write custom headers. - if header != nil { - header(bw) - } - - switch err { - case ErrHandshakeBadProtocol: - bw.WriteString(textTailErrHandshakeBadProtocol) - case ErrHandshakeBadMethod: - bw.WriteString(textTailErrHandshakeBadMethod) - case ErrHandshakeBadHost: - bw.WriteString(textTailErrHandshakeBadHost) - case ErrHandshakeBadUpgrade: - bw.WriteString(textTailErrHandshakeBadUpgrade) - case ErrHandshakeBadConnection: - bw.WriteString(textTailErrHandshakeBadConnection) - case ErrHandshakeBadSecAccept: - bw.WriteString(textTailErrHandshakeBadSecAccept) - case ErrHandshakeBadSecKey: - bw.WriteString(textTailErrHandshakeBadSecKey) - case ErrHandshakeBadSecVersion: - bw.WriteString(textTailErrHandshakeBadSecVersion) - case ErrHandshakeUpgradeRequired: - bw.WriteString(textTailErrUpgradeRequired) - case nil: - bw.WriteString(crlf) - default: - writeErrorText(bw, err) - } -} - -func writeStatusText(bw *bufio.Writer, code int) { - bw.WriteString("HTTP/1.1 ") - bw.WriteString(strconv.Itoa(code)) - bw.WriteByte(' ') - bw.WriteString(http.StatusText(code)) - bw.WriteString(crlf) - bw.WriteString("Content-Type: text/plain; charset=utf-8") - bw.WriteString(crlf) -} - -func writeErrorText(bw *bufio.Writer, err error) { - body := err.Error() - bw.WriteString("Content-Length: ") - bw.WriteString(strconv.Itoa(len(body))) - bw.WriteString(crlf) - bw.WriteString(crlf) - bw.WriteString(body) -} - -// httpError is like the http.Error with WebSocket context exception. -func httpError(w http.ResponseWriter, body string, code int) { - w.Header().Set("Content-Type", "text/plain; charset=utf-8") - w.Header().Set("Content-Length", strconv.Itoa(len(body))) - w.WriteHeader(code) - w.Write([]byte(body)) -} - -// statusText is a non-performant status text generator. -// NOTE: Used only to generate constants. -func statusText(code int) string { - var buf bytes.Buffer - bw := bufio.NewWriter(&buf) - writeStatusText(bw, code) - bw.Flush() - return buf.String() -} - -// errorText is a non-performant error text generator. -// NOTE: Used only to generate constants. -func errorText(err error) string { - var buf bytes.Buffer - bw := bufio.NewWriter(&buf) - writeErrorText(bw, err) - bw.Flush() - return buf.String() -} - -// HandshakeHeader is the interface that writes both upgrade request or -// response headers into a given io.Writer. -type HandshakeHeader interface { - io.WriterTo -} - -// HandshakeHeaderString is an adapter to allow the use of headers represented -// by ordinary string as HandshakeHeader. -type HandshakeHeaderString string - -// WriteTo implements HandshakeHeader (and io.WriterTo) interface. -func (s HandshakeHeaderString) WriteTo(w io.Writer) (int64, error) { - n, err := io.WriteString(w, string(s)) - return int64(n), err -} - -// HandshakeHeaderBytes is an adapter to allow the use of headers represented -// by ordinary slice of bytes as HandshakeHeader. -type HandshakeHeaderBytes []byte - -// WriteTo implements HandshakeHeader (and io.WriterTo) interface. -func (b HandshakeHeaderBytes) WriteTo(w io.Writer) (int64, error) { - n, err := w.Write(b) - return int64(n), err -} - -// HandshakeHeaderFunc is an adapter to allow the use of headers represented by -// ordinary function as HandshakeHeader. -type HandshakeHeaderFunc func(io.Writer) (int64, error) - -// WriteTo implements HandshakeHeader (and io.WriterTo) interface. -func (f HandshakeHeaderFunc) WriteTo(w io.Writer) (int64, error) { - return f(w) -} - -// HandshakeHeaderHTTP is an adapter to allow the use of http.Header as -// HandshakeHeader. -type HandshakeHeaderHTTP http.Header - -// WriteTo implements HandshakeHeader (and io.WriterTo) interface. -func (h HandshakeHeaderHTTP) WriteTo(w io.Writer) (int64, error) { - wr := writer{w: w} - err := http.Header(h).Write(&wr) - return wr.n, err -} - -type writer struct { - n int64 - w io.Writer -} - -func (w *writer) WriteString(s string) (int, error) { - n, err := io.WriteString(w.w, s) - w.n += int64(n) - return n, err -} - -func (w *writer) Write(p []byte) (int, error) { - n, err := w.w.Write(p) - w.n += int64(n) - return n, err -} diff --git a/vendor/github.com/gobwas/ws/nonce.go b/vendor/github.com/gobwas/ws/nonce.go deleted file mode 100644 index 7b0edd972..000000000 --- a/vendor/github.com/gobwas/ws/nonce.go +++ /dev/null @@ -1,78 +0,0 @@ -package ws - -import ( - "bufio" - "bytes" - "crypto/sha1" - "encoding/base64" - "fmt" - "math/rand" -) - -const ( - // RFC6455: The value of this header field MUST be a nonce consisting of a - // randomly selected 16-byte value that has been base64-encoded (see - // Section 4 of [RFC4648]). The nonce MUST be selected randomly for each - // connection. - nonceKeySize = 16 - nonceSize = 24 // base64.StdEncoding.EncodedLen(nonceKeySize) - - // RFC6455: The value of this header field is constructed by concatenating - // /key/, defined above in step 4 in Section 4.2.2, with the string - // "258EAFA5- E914-47DA-95CA-C5AB0DC85B11", taking the SHA-1 hash of this - // concatenated value to obtain a 20-byte value and base64- encoding (see - // Section 4 of [RFC4648]) this 20-byte hash. - acceptSize = 28 // base64.StdEncoding.EncodedLen(sha1.Size) -) - -// initNonce fills given slice with random base64-encoded nonce bytes. -func initNonce(dst []byte) { - // NOTE: bts does not escape. - bts := make([]byte, nonceKeySize) - if _, err := rand.Read(bts); err != nil { - panic(fmt.Sprintf("rand read error: %s", err)) - } - base64.StdEncoding.Encode(dst, bts) -} - -// checkAcceptFromNonce reports whether given accept bytes are valid for given -// nonce bytes. -func checkAcceptFromNonce(accept, nonce []byte) bool { - if len(accept) != acceptSize { - return false - } - // NOTE: expect does not escape. - expect := make([]byte, acceptSize) - initAcceptFromNonce(expect, nonce) - return bytes.Equal(expect, accept) -} - -// initAcceptFromNonce fills given slice with accept bytes generated from given -// nonce bytes. Given buffer should be exactly acceptSize bytes. -func initAcceptFromNonce(accept, nonce []byte) { - const magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" - - if len(accept) != acceptSize { - panic("accept buffer is invalid") - } - if len(nonce) != nonceSize { - panic("nonce is invalid") - } - - p := make([]byte, nonceSize+len(magic)) - copy(p[:nonceSize], nonce) - copy(p[nonceSize:], magic) - - sum := sha1.Sum(p) - base64.StdEncoding.Encode(accept, sum[:]) -} - -func writeAccept(bw *bufio.Writer, nonce []byte) (int, error) { - accept := make([]byte, acceptSize) - initAcceptFromNonce(accept, nonce) - // NOTE: write accept bytes as a string to prevent heap allocation – - // WriteString() copy given string into its inner buffer, unlike Write() - // which may write p directly to the underlying io.Writer – which in turn - // will lead to p escape. - return bw.WriteString(btsToString(accept)) -} diff --git a/vendor/github.com/gobwas/ws/read.go b/vendor/github.com/gobwas/ws/read.go deleted file mode 100644 index 1771816a1..000000000 --- a/vendor/github.com/gobwas/ws/read.go +++ /dev/null @@ -1,147 +0,0 @@ -package ws - -import ( - "encoding/binary" - "fmt" - "io" -) - -// Errors used by frame reader. -var ( - ErrHeaderLengthMSB = fmt.Errorf("header error: the most significant bit must be 0") - ErrHeaderLengthUnexpected = fmt.Errorf("header error: unexpected payload length bits") -) - -// ReadHeader reads a frame header from r. -func ReadHeader(r io.Reader) (h Header, err error) { - // Make slice of bytes with capacity 12 that could hold any header. - // - // The maximum header size is 14, but due to the 2 hop reads, - // after first hop that reads first 2 constant bytes, we could reuse 2 bytes. - // So 14 - 2 = 12. - bts := make([]byte, 2, MaxHeaderSize-2) - - // Prepare to hold first 2 bytes to choose size of next read. - _, err = io.ReadFull(r, bts) - if err != nil { - return h, err - } - - h.Fin = bts[0]&bit0 != 0 - h.Rsv = (bts[0] & 0x70) >> 4 - h.OpCode = OpCode(bts[0] & 0x0f) - - var extra int - - if bts[1]&bit0 != 0 { - h.Masked = true - extra += 4 - } - - length := bts[1] & 0x7f - switch { - case length < 126: - h.Length = int64(length) - - case length == 126: - extra += 2 - - case length == 127: - extra += 8 - - default: - err = ErrHeaderLengthUnexpected - return h, err - } - - if extra == 0 { - return h, err - } - - // Increase len of bts to extra bytes need to read. - // Overwrite first 2 bytes that was read before. - bts = bts[:extra] - _, err = io.ReadFull(r, bts) - if err != nil { - return h, err - } - - switch { - case length == 126: - h.Length = int64(binary.BigEndian.Uint16(bts[:2])) - bts = bts[2:] - - case length == 127: - if bts[0]&0x80 != 0 { - err = ErrHeaderLengthMSB - return h, err - } - h.Length = int64(binary.BigEndian.Uint64(bts[:8])) - bts = bts[8:] - } - - if h.Masked { - copy(h.Mask[:], bts) - } - - return h, nil -} - -// ReadFrame reads a frame from r. -// It is not designed for high optimized use case cause it makes allocation -// for frame.Header.Length size inside to read frame payload into. -// -// Note that ReadFrame does not unmask payload. -func ReadFrame(r io.Reader) (f Frame, err error) { - f.Header, err = ReadHeader(r) - if err != nil { - return f, err - } - - if f.Header.Length > 0 { - // int(f.Header.Length) is safe here cause we have - // checked it for overflow above in ReadHeader. - f.Payload = make([]byte, int(f.Header.Length)) - _, err = io.ReadFull(r, f.Payload) - } - - return f, err -} - -// MustReadFrame is like ReadFrame but panics if frame can not be read. -func MustReadFrame(r io.Reader) Frame { - f, err := ReadFrame(r) - if err != nil { - panic(err) - } - return f -} - -// ParseCloseFrameData parses close frame status code and closure reason if any provided. -// If there is no status code in the payload -// the empty status code is returned (code.Empty()) with empty string as a reason. -func ParseCloseFrameData(payload []byte) (code StatusCode, reason string) { - if len(payload) < 2 { - // We returning empty StatusCode here, preventing the situation - // when endpoint really sent code 1005 and we should return ProtocolError on that. - // - // In other words, we ignoring this rule [RFC6455:7.1.5]: - // If this Close control frame contains no status code, _The WebSocket - // Connection Close Code_ is considered to be 1005. - return code, reason - } - code = StatusCode(binary.BigEndian.Uint16(payload)) - reason = string(payload[2:]) - return code, reason -} - -// ParseCloseFrameDataUnsafe is like ParseCloseFrameData except the thing -// that it does not copies payload bytes into reason, but prepares unsafe cast. -func ParseCloseFrameDataUnsafe(payload []byte) (code StatusCode, reason string) { - if len(payload) < 2 { - return code, reason - } - code = StatusCode(binary.BigEndian.Uint16(payload)) - reason = btsToString(payload[2:]) - return code, reason -} diff --git a/vendor/github.com/gobwas/ws/server.go b/vendor/github.com/gobwas/ws/server.go deleted file mode 100644 index 863bb229c..000000000 --- a/vendor/github.com/gobwas/ws/server.go +++ /dev/null @@ -1,658 +0,0 @@ -package ws - -import ( - "bufio" - "bytes" - "fmt" - "io" - "net" - "net/http" - "strings" - "time" - - "github.com/gobwas/httphead" - "github.com/gobwas/pool/pbufio" -) - -// Constants used by ConnUpgrader. -const ( - DefaultServerReadBufferSize = 4096 - DefaultServerWriteBufferSize = 512 -) - -// Errors used by both client and server when preparing WebSocket handshake. -var ( - ErrHandshakeBadProtocol = RejectConnectionError( - RejectionStatus(http.StatusHTTPVersionNotSupported), - RejectionReason("handshake error: bad HTTP protocol version"), - ) - ErrHandshakeBadMethod = RejectConnectionError( - RejectionStatus(http.StatusMethodNotAllowed), - RejectionReason("handshake error: bad HTTP request method"), - ) - ErrHandshakeBadHost = RejectConnectionError( - RejectionStatus(http.StatusBadRequest), - RejectionReason(fmt.Sprintf("handshake error: bad %q header", headerHost)), - ) - ErrHandshakeBadUpgrade = RejectConnectionError( - RejectionStatus(http.StatusBadRequest), - RejectionReason(fmt.Sprintf("handshake error: bad %q header", headerUpgrade)), - ) - ErrHandshakeBadConnection = RejectConnectionError( - RejectionStatus(http.StatusBadRequest), - RejectionReason(fmt.Sprintf("handshake error: bad %q header", headerConnection)), - ) - ErrHandshakeBadSecAccept = RejectConnectionError( - RejectionStatus(http.StatusBadRequest), - RejectionReason(fmt.Sprintf("handshake error: bad %q header", headerSecAccept)), - ) - ErrHandshakeBadSecKey = RejectConnectionError( - RejectionStatus(http.StatusBadRequest), - RejectionReason(fmt.Sprintf("handshake error: bad %q header", headerSecKey)), - ) - ErrHandshakeBadSecVersion = RejectConnectionError( - RejectionStatus(http.StatusBadRequest), - RejectionReason(fmt.Sprintf("handshake error: bad %q header", headerSecVersion)), - ) -) - -// ErrMalformedResponse is returned by Dialer to indicate that server response -// can not be parsed. -var ErrMalformedResponse = fmt.Errorf("malformed HTTP response") - -// ErrMalformedRequest is returned when HTTP request can not be parsed. -var ErrMalformedRequest = RejectConnectionError( - RejectionStatus(http.StatusBadRequest), - RejectionReason("malformed HTTP request"), -) - -// ErrHandshakeUpgradeRequired is returned by Upgrader to indicate that -// connection is rejected because given WebSocket version is malformed. -// -// According to RFC6455: -// If this version does not match a version understood by the server, the -// server MUST abort the WebSocket handshake described in this section and -// instead send an appropriate HTTP error code (such as 426 Upgrade Required) -// and a |Sec-WebSocket-Version| header field indicating the version(s) the -// server is capable of understanding. -var ErrHandshakeUpgradeRequired = RejectConnectionError( - RejectionStatus(http.StatusUpgradeRequired), - RejectionHeader(HandshakeHeaderString(headerSecVersion+": 13\r\n")), - RejectionReason(fmt.Sprintf("handshake error: bad %q header", headerSecVersion)), -) - -// ErrNotHijacker is an error returned when http.ResponseWriter does not -// implement http.Hijacker interface. -var ErrNotHijacker = RejectConnectionError( - RejectionStatus(http.StatusInternalServerError), - RejectionReason("given http.ResponseWriter is not a http.Hijacker"), -) - -// DefaultHTTPUpgrader is an HTTPUpgrader that holds no options and is used by -// UpgradeHTTP function. -var DefaultHTTPUpgrader HTTPUpgrader - -// UpgradeHTTP is like HTTPUpgrader{}.Upgrade(). -func UpgradeHTTP(r *http.Request, w http.ResponseWriter) (net.Conn, *bufio.ReadWriter, Handshake, error) { - return DefaultHTTPUpgrader.Upgrade(r, w) -} - -// DefaultUpgrader is an Upgrader that holds no options and is used by Upgrade -// function. -var DefaultUpgrader Upgrader - -// Upgrade is like Upgrader{}.Upgrade(). -func Upgrade(conn io.ReadWriter) (Handshake, error) { - return DefaultUpgrader.Upgrade(conn) -} - -// HTTPUpgrader contains options for upgrading connection to websocket from -// net/http Handler arguments. -type HTTPUpgrader struct { - // Timeout is the maximum amount of time an Upgrade() will spent while - // writing handshake response. - // - // The default is no timeout. - Timeout time.Duration - - // Header is an optional http.Header mapping that could be used to - // write additional headers to the handshake response. - // - // Note that if present, it will be written in any result of handshake. - Header http.Header - - // Protocol is the select function that is used to select subprotocol from - // list requested by client. If this field is set, then the first matched - // protocol is sent to a client as negotiated. - Protocol func(string) bool - - // Extension is the select function that is used to select extensions from - // list requested by client. If this field is set, then the all matched - // extensions are sent to a client as negotiated. - // - // Deprecated: use Negotiate instead. - Extension func(httphead.Option) bool - - // Negotiate is the callback that is used to negotiate extensions from - // the client's offer. If this field is set, then the returned non-zero - // extensions are sent to the client as accepted extensions in the - // response. - // - // The argument is only valid until the Negotiate callback returns. - // - // If returned error is non-nil then connection is rejected and response is - // sent with appropriate HTTP error code and body set to error message. - // - // RejectConnectionError could be used to get more control on response. - Negotiate func(httphead.Option) (httphead.Option, error) -} - -// Upgrade upgrades http connection to the websocket connection. -// -// It hijacks net.Conn from w and returns received net.Conn and -// bufio.ReadWriter. On successful handshake it returns Handshake struct -// describing handshake info. -func (u HTTPUpgrader) Upgrade(r *http.Request, w http.ResponseWriter) (conn net.Conn, rw *bufio.ReadWriter, hs Handshake, err error) { - // Hijack connection first to get the ability to write rejection errors the - // same way as in Upgrader. - conn, rw, err = hijack(w) - if err != nil { - httpError(w, err.Error(), http.StatusInternalServerError) - return conn, rw, hs, err - } - - // See https://tools.ietf.org/html/rfc6455#section-4.1 - // The method of the request MUST be GET, and the HTTP version MUST be at least 1.1. - var nonce string - if r.Method != http.MethodGet { - err = ErrHandshakeBadMethod - } else if r.ProtoMajor < 1 || (r.ProtoMajor == 1 && r.ProtoMinor < 1) { - err = ErrHandshakeBadProtocol - } else if r.Host == "" { - err = ErrHandshakeBadHost - } else if u := httpGetHeader(r.Header, headerUpgradeCanonical); u != "websocket" && !strings.EqualFold(u, "websocket") { - err = ErrHandshakeBadUpgrade - } else if c := httpGetHeader(r.Header, headerConnectionCanonical); c != "Upgrade" && !strHasToken(c, "upgrade") { - err = ErrHandshakeBadConnection - } else if nonce = httpGetHeader(r.Header, headerSecKeyCanonical); len(nonce) != nonceSize { - err = ErrHandshakeBadSecKey - } else if v := httpGetHeader(r.Header, headerSecVersionCanonical); v != "13" { - // According to RFC6455: - // - // If this version does not match a version understood by the server, - // the server MUST abort the WebSocket handshake described in this - // section and instead send an appropriate HTTP error code (such as 426 - // Upgrade Required) and a |Sec-WebSocket-Version| header field - // indicating the version(s) the server is capable of understanding. - // - // So we branching here cause empty or not present version does not - // meet the ABNF rules of RFC6455: - // - // version = DIGIT | (NZDIGIT DIGIT) | - // ("1" DIGIT DIGIT) | ("2" DIGIT DIGIT) - // ; Limited to 0-255 range, with no leading zeros - // - // That is, if version is really invalid – we sent 426 status, if it - // not present or empty – it is 400. - if v != "" { - err = ErrHandshakeUpgradeRequired - } else { - err = ErrHandshakeBadSecVersion - } - } - if check := u.Protocol; err == nil && check != nil { - ps := r.Header[headerSecProtocolCanonical] - for i := 0; i < len(ps) && err == nil && hs.Protocol == ""; i++ { - var ok bool - hs.Protocol, ok = strSelectProtocol(ps[i], check) - if !ok { - err = ErrMalformedRequest - } - } - } - if f := u.Negotiate; err == nil && f != nil { - for _, h := range r.Header[headerSecExtensionsCanonical] { - hs.Extensions, err = negotiateExtensions(strToBytes(h), hs.Extensions, f) - if err != nil { - break - } - } - } - // DEPRECATED path. - if check := u.Extension; err == nil && check != nil && u.Negotiate == nil { - xs := r.Header[headerSecExtensionsCanonical] - for i := 0; i < len(xs) && err == nil; i++ { - var ok bool - hs.Extensions, ok = btsSelectExtensions(strToBytes(xs[i]), hs.Extensions, check) - if !ok { - err = ErrMalformedRequest - } - } - } - - // Clear deadlines set by server. - conn.SetDeadline(noDeadline) - if t := u.Timeout; t != 0 { - conn.SetWriteDeadline(time.Now().Add(t)) - defer conn.SetWriteDeadline(noDeadline) - } - - var header handshakeHeader - if h := u.Header; h != nil { - header[0] = HandshakeHeaderHTTP(h) - } - if err == nil { - httpWriteResponseUpgrade(rw.Writer, strToBytes(nonce), hs, header.WriteTo) - err = rw.Writer.Flush() - } else { - var code int - if rej, ok := err.(*ConnectionRejectedError); ok { - code = rej.code - header[1] = rej.header - } - if code == 0 { - code = http.StatusInternalServerError - } - httpWriteResponseError(rw.Writer, err, code, header.WriteTo) - // Do not store Flush() error to not override already existing one. - _ = rw.Writer.Flush() - } - return conn, rw, hs, err -} - -// Upgrader contains options for upgrading connection to websocket. -type Upgrader struct { - // ReadBufferSize and WriteBufferSize is an I/O buffer sizes. - // They used to read and write http data while upgrading to WebSocket. - // Allocated buffers are pooled with sync.Pool to avoid extra allocations. - // - // If a size is zero then default value is used. - // - // Usually it is useful to set read buffer size bigger than write buffer - // size because incoming request could contain long header values, such as - // Cookie. Response, in other way, could be big only if user write multiple - // custom headers. Usually response takes less than 256 bytes. - ReadBufferSize, WriteBufferSize int - - // Protocol is a select function that is used to select subprotocol - // from list requested by client. If this field is set, then the first matched - // protocol is sent to a client as negotiated. - // - // The argument is only valid until the callback returns. - Protocol func([]byte) bool - - // ProtocolCustrom allow user to parse Sec-WebSocket-Protocol header manually. - // Note that returned bytes must be valid until Upgrade returns. - // If ProtocolCustom is set, it used instead of Protocol function. - ProtocolCustom func([]byte) (string, bool) - - // Extension is a select function that is used to select extensions - // from list requested by client. If this field is set, then the all matched - // extensions are sent to a client as negotiated. - // - // Note that Extension may be called multiple times and implementations - // must track uniqueness of accepted extensions manually. - // - // The argument is only valid until the callback returns. - // - // According to the RFC6455 order of extensions passed by a client is - // significant. That is, returning true from this function means that no - // other extension with the same name should be checked because server - // accepted the most preferable extension right now: - // "Note that the order of extensions is significant. Any interactions between - // multiple extensions MAY be defined in the documents defining the extensions. - // In the absence of such definitions, the interpretation is that the header - // fields listed by the client in its request represent a preference of the - // header fields it wishes to use, with the first options listed being most - // preferable." - // - // Deprecated: use Negotiate instead. - Extension func(httphead.Option) bool - - // ExtensionCustom allow user to parse Sec-WebSocket-Extensions header - // manually. - // - // If ExtensionCustom() decides to accept received extension, it must - // append appropriate option to the given slice of httphead.Option. - // It returns results of append() to the given slice and a flag that - // reports whether given header value is wellformed or not. - // - // Note that ExtensionCustom may be called multiple times and - // implementations must track uniqueness of accepted extensions manually. - // - // Note that returned options should be valid until Upgrade returns. - // If ExtensionCustom is set, it used instead of Extension function. - ExtensionCustom func([]byte, []httphead.Option) ([]httphead.Option, bool) - - // Negotiate is the callback that is used to negotiate extensions from - // the client's offer. If this field is set, then the returned non-zero - // extensions are sent to the client as accepted extensions in the - // response. - // - // The argument is only valid until the Negotiate callback returns. - // - // If returned error is non-nil then connection is rejected and response is - // sent with appropriate HTTP error code and body set to error message. - // - // RejectConnectionError could be used to get more control on response. - Negotiate func(httphead.Option) (httphead.Option, error) - - // Header is an optional HandshakeHeader instance that could be used to - // write additional headers to the handshake response. - // - // It used instead of any key-value mappings to avoid allocations in user - // land. - // - // Note that if present, it will be written in any result of handshake. - Header HandshakeHeader - - // OnRequest is a callback that will be called after request line - // successful parsing. - // - // The arguments are only valid until the callback returns. - // - // If returned error is non-nil then connection is rejected and response is - // sent with appropriate HTTP error code and body set to error message. - // - // RejectConnectionError could be used to get more control on response. - OnRequest func(uri []byte) error - - // OnHost is a callback that will be called after "Host" header successful - // parsing. - // - // It is separated from OnHeader callback because the Host header must be - // present in each request since HTTP/1.1. Thus Host header is non-optional - // and required for every WebSocket handshake. - // - // The arguments are only valid until the callback returns. - // - // If returned error is non-nil then connection is rejected and response is - // sent with appropriate HTTP error code and body set to error message. - // - // RejectConnectionError could be used to get more control on response. - OnHost func(host []byte) error - - // OnHeader is a callback that will be called after successful parsing of - // header, that is not used during WebSocket handshake procedure. That is, - // it will be called with non-websocket headers, which could be relevant - // for application-level logic. - // - // The arguments are only valid until the callback returns. - // - // If returned error is non-nil then connection is rejected and response is - // sent with appropriate HTTP error code and body set to error message. - // - // RejectConnectionError could be used to get more control on response. - OnHeader func(key, value []byte) error - - // OnBeforeUpgrade is a callback that will be called before sending - // successful upgrade response. - // - // Setting OnBeforeUpgrade allows user to make final application-level - // checks and decide whether this connection is allowed to successfully - // upgrade to WebSocket. - // - // It must return non-nil either HandshakeHeader or error and never both. - // - // If returned error is non-nil then connection is rejected and response is - // sent with appropriate HTTP error code and body set to error message. - // - // RejectConnectionError could be used to get more control on response. - OnBeforeUpgrade func() (header HandshakeHeader, err error) -} - -// Upgrade zero-copy upgrades connection to WebSocket. It interprets given conn -// as connection with incoming HTTP Upgrade request. -// -// It is a caller responsibility to manage i/o timeouts on conn. -// -// Non-nil error means that request for the WebSocket upgrade is invalid or -// malformed and usually connection should be closed. -// Even when error is non-nil Upgrade will write appropriate response into -// connection in compliance with RFC. -func (u Upgrader) Upgrade(conn io.ReadWriter) (hs Handshake, err error) { - // headerSeen constants helps to report whether or not some header was seen - // during reading request bytes. - const ( - headerSeenHost = 1 << iota - headerSeenUpgrade - headerSeenConnection - headerSeenSecVersion - headerSeenSecKey - - // headerSeenAll is the value that we expect to receive at the end of - // headers read/parse loop. - headerSeenAll = 0 | - headerSeenHost | - headerSeenUpgrade | - headerSeenConnection | - headerSeenSecVersion | - headerSeenSecKey - ) - - // Prepare I/O buffers. - // TODO(gobwas): make it configurable. - br := pbufio.GetReader(conn, - nonZero(u.ReadBufferSize, DefaultServerReadBufferSize), - ) - bw := pbufio.GetWriter(conn, - nonZero(u.WriteBufferSize, DefaultServerWriteBufferSize), - ) - defer func() { - pbufio.PutReader(br) - pbufio.PutWriter(bw) - }() - - // Read HTTP request line like "GET /ws HTTP/1.1". - rl, err := readLine(br) - if err != nil { - return hs, err - } - // Parse request line data like HTTP version, uri and method. - req, err := httpParseRequestLine(rl) - if err != nil { - return hs, err - } - - // Prepare stack-based handshake header list. - header := handshakeHeader{ - 0: u.Header, - } - - // Parse and check HTTP request. - // As RFC6455 says: - // The client's opening handshake consists of the following parts. If the - // server, while reading the handshake, finds that the client did not - // send a handshake that matches the description below (note that as per - // [RFC2616], the order of the header fields is not important), including - // but not limited to any violations of the ABNF grammar specified for - // the components of the handshake, the server MUST stop processing the - // client's handshake and return an HTTP response with an appropriate - // error code (such as 400 Bad Request). - // - // See https://tools.ietf.org/html/rfc6455#section-4.2.1 - - // An HTTP/1.1 or higher GET request, including a "Request-URI". - // - // Even if RFC says "1.1 or higher" without mentioning the part of the - // version, we apply it only to minor part. - switch { - case req.major != 1 || req.minor < 1: - // Abort processing the whole request because we do not even know how - // to actually parse it. - err = ErrHandshakeBadProtocol - - case btsToString(req.method) != http.MethodGet: - err = ErrHandshakeBadMethod - - default: - if onRequest := u.OnRequest; onRequest != nil { - err = onRequest(req.uri) - } - } - // Start headers read/parse loop. - var ( - // headerSeen reports which header was seen by setting corresponding - // bit on. - headerSeen byte - - nonce = make([]byte, nonceSize) - ) - for err == nil { - line, e := readLine(br) - if e != nil { - return hs, e - } - if len(line) == 0 { - // Blank line, no more lines to read. - break - } - - k, v, ok := httpParseHeaderLine(line) - if !ok { - err = ErrMalformedRequest - break - } - - switch btsToString(k) { - case headerHostCanonical: - headerSeen |= headerSeenHost - if onHost := u.OnHost; onHost != nil { - err = onHost(v) - } - - case headerUpgradeCanonical: - headerSeen |= headerSeenUpgrade - if !bytes.Equal(v, specHeaderValueUpgrade) && !bytes.EqualFold(v, specHeaderValueUpgrade) { - err = ErrHandshakeBadUpgrade - } - - case headerConnectionCanonical: - headerSeen |= headerSeenConnection - if !bytes.Equal(v, specHeaderValueConnection) && !btsHasToken(v, specHeaderValueConnectionLower) { - err = ErrHandshakeBadConnection - } - - case headerSecVersionCanonical: - headerSeen |= headerSeenSecVersion - if !bytes.Equal(v, specHeaderValueSecVersion) { - err = ErrHandshakeUpgradeRequired - } - - case headerSecKeyCanonical: - headerSeen |= headerSeenSecKey - if len(v) != nonceSize { - err = ErrHandshakeBadSecKey - } else { - copy(nonce, v) - } - - case headerSecProtocolCanonical: - if custom, check := u.ProtocolCustom, u.Protocol; hs.Protocol == "" && (custom != nil || check != nil) { - var ok bool - if custom != nil { - hs.Protocol, ok = custom(v) - } else { - hs.Protocol, ok = btsSelectProtocol(v, check) - } - if !ok { - err = ErrMalformedRequest - } - } - - case headerSecExtensionsCanonical: - if f := u.Negotiate; err == nil && f != nil { - hs.Extensions, err = negotiateExtensions(v, hs.Extensions, f) - } - // DEPRECATED path. - if custom, check := u.ExtensionCustom, u.Extension; u.Negotiate == nil && (custom != nil || check != nil) { - var ok bool - if custom != nil { - hs.Extensions, ok = custom(v, hs.Extensions) - } else { - hs.Extensions, ok = btsSelectExtensions(v, hs.Extensions, check) - } - if !ok { - err = ErrMalformedRequest - } - } - - default: - if onHeader := u.OnHeader; onHeader != nil { - err = onHeader(k, v) - } - } - } - switch { - case err == nil && headerSeen != headerSeenAll: - switch { - case headerSeen&headerSeenHost == 0: - // As RFC2616 says: - // A client MUST include a Host header field in all HTTP/1.1 - // request messages. If the requested URI does not include an - // Internet host name for the service being requested, then the - // Host header field MUST be given with an empty value. An - // HTTP/1.1 proxy MUST ensure that any request message it - // forwards does contain an appropriate Host header field that - // identifies the service being requested by the proxy. All - // Internet-based HTTP/1.1 servers MUST respond with a 400 (Bad - // Request) status code to any HTTP/1.1 request message which - // lacks a Host header field. - err = ErrHandshakeBadHost - case headerSeen&headerSeenUpgrade == 0: - err = ErrHandshakeBadUpgrade - case headerSeen&headerSeenConnection == 0: - err = ErrHandshakeBadConnection - case headerSeen&headerSeenSecVersion == 0: - // In case of empty or not present version we do not send 426 status, - // because it does not meet the ABNF rules of RFC6455: - // - // version = DIGIT | (NZDIGIT DIGIT) | - // ("1" DIGIT DIGIT) | ("2" DIGIT DIGIT) - // ; Limited to 0-255 range, with no leading zeros - // - // That is, if version is really invalid – we sent 426 status as above, if it - // not present – it is 400. - err = ErrHandshakeBadSecVersion - case headerSeen&headerSeenSecKey == 0: - err = ErrHandshakeBadSecKey - default: - panic("unknown headers state") - } - - case err == nil && u.OnBeforeUpgrade != nil: - header[1], err = u.OnBeforeUpgrade() - } - if err != nil { - var code int - if rej, ok := err.(*ConnectionRejectedError); ok { - code = rej.code - header[1] = rej.header - } - if code == 0 { - code = http.StatusInternalServerError - } - httpWriteResponseError(bw, err, code, header.WriteTo) - // Do not store Flush() error to not override already existing one. - _ = bw.Flush() - return hs, err - } - - httpWriteResponseUpgrade(bw, nonce, hs, header.WriteTo) - err = bw.Flush() - - return hs, err -} - -type handshakeHeader [2]HandshakeHeader - -func (hs handshakeHeader) WriteTo(w io.Writer) (n int64, err error) { - for i := 0; i < len(hs) && err == nil; i++ { - if h := hs[i]; h != nil { - var m int64 - m, err = h.WriteTo(w) - n += m - } - } - return n, err -} diff --git a/vendor/github.com/gobwas/ws/util.go b/vendor/github.com/gobwas/ws/util.go deleted file mode 100644 index 1dd5aa608..000000000 --- a/vendor/github.com/gobwas/ws/util.go +++ /dev/null @@ -1,199 +0,0 @@ -package ws - -import ( - "bufio" - "bytes" - "fmt" - - "github.com/gobwas/httphead" -) - -// SelectFromSlice creates accept function that could be used as Protocol/Extension -// select during upgrade. -func SelectFromSlice(accept []string) func(string) bool { - if len(accept) > 16 { - mp := make(map[string]struct{}, len(accept)) - for _, p := range accept { - mp[p] = struct{}{} - } - return func(p string) bool { - _, ok := mp[p] - return ok - } - } - return func(p string) bool { - for _, ok := range accept { - if p == ok { - return true - } - } - return false - } -} - -// SelectEqual creates accept function that could be used as Protocol/Extension -// select during upgrade. -func SelectEqual(v string) func(string) bool { - return func(p string) bool { - return v == p - } -} - -// asciiToInt converts bytes to int. -func asciiToInt(bts []byte) (ret int, err error) { - // ASCII numbers all start with the high-order bits 0011. - // If you see that, and the next bits are 0-9 (0000 - 1001) you can grab those - // bits and interpret them directly as an integer. - var n int - if n = len(bts); n < 1 { - return 0, fmt.Errorf("converting empty bytes to int") - } - for i := 0; i < n; i++ { - if bts[i]&0xf0 != 0x30 { - return 0, fmt.Errorf("%s is not a numeric character", string(bts[i])) - } - ret += int(bts[i]&0xf) * pow(10, n-i-1) - } - return ret, nil -} - -// pow for integers implementation. -// See Donald Knuth, The Art of Computer Programming, Volume 2, Section 4.6.3. -func pow(a, b int) int { - p := 1 - for b > 0 { - if b&1 != 0 { - p *= a - } - b >>= 1 - a *= a - } - return p -} - -func bsplit3(bts []byte, sep byte) (b1, b2, b3 []byte) { - a := bytes.IndexByte(bts, sep) - b := bytes.IndexByte(bts[a+1:], sep) - if a == -1 || b == -1 { - return bts, nil, nil - } - b += a + 1 - return bts[:a], bts[a+1 : b], bts[b+1:] -} - -func btrim(bts []byte) []byte { - var i, j int - for i = 0; i < len(bts) && (bts[i] == ' ' || bts[i] == '\t'); { - i++ - } - for j = len(bts); j > i && (bts[j-1] == ' ' || bts[j-1] == '\t'); { - j-- - } - return bts[i:j] -} - -func strHasToken(header, token string) (has bool) { - return btsHasToken(strToBytes(header), strToBytes(token)) -} - -func btsHasToken(header, token []byte) (has bool) { - httphead.ScanTokens(header, func(v []byte) bool { - has = bytes.EqualFold(v, token) - return !has - }) - return has -} - -const ( - toLower = 'a' - 'A' // for use with OR. - toUpper = ^byte(toLower) // for use with AND. - toLower8 = uint64(toLower) | - uint64(toLower)<<8 | - uint64(toLower)<<16 | - uint64(toLower)<<24 | - uint64(toLower)<<32 | - uint64(toLower)<<40 | - uint64(toLower)<<48 | - uint64(toLower)<<56 -) - -// Algorithm below is like standard textproto/CanonicalMIMEHeaderKey, except -// that it operates with slice of bytes and modifies it inplace without copying. -func canonicalizeHeaderKey(k []byte) { - upper := true - for i, c := range k { - if upper && 'a' <= c && c <= 'z' { - k[i] &= toUpper - } else if !upper && 'A' <= c && c <= 'Z' { - k[i] |= toLower - } - upper = c == '-' - } -} - -// readLine reads line from br. It reads until '\n' and returns bytes without -// '\n' or '\r\n' at the end. -// It returns err if and only if line does not end in '\n'. Note that read -// bytes returned in any case of error. -// -// It is much like the textproto/Reader.ReadLine() except the thing that it -// returns raw bytes, instead of string. That is, it avoids copying bytes read -// from br. -// -// textproto/Reader.ReadLineBytes() is also makes copy of resulting bytes to be -// safe with future I/O operations on br. -// -// We could control I/O operations on br and do not need to make additional -// copy for safety. -// -// NOTE: it may return copied flag to notify that returned buffer is safe to -// use. -func readLine(br *bufio.Reader) ([]byte, error) { - var line []byte - for { - bts, err := br.ReadSlice('\n') - if err == bufio.ErrBufferFull { - // Copy bytes because next read will discard them. - line = append(line, bts...) - continue - } - - // Avoid copy of single read. - if line == nil { - line = bts - } else { - line = append(line, bts...) - } - - if err != nil { - return line, err - } - - // Size of line is at least 1. - // In other case bufio.ReadSlice() returns error. - n := len(line) - - // Cut '\n' or '\r\n'. - if n > 1 && line[n-2] == '\r' { - line = line[:n-2] - } else { - line = line[:n-1] - } - - return line, nil - } -} - -func min(a, b int) int { - if a < b { - return a - } - return b -} - -func nonZero(a, b int) int { - if a != 0 { - return a - } - return b -} diff --git a/vendor/github.com/gobwas/ws/util_purego.go b/vendor/github.com/gobwas/ws/util_purego.go deleted file mode 100644 index 449b3fdfa..000000000 --- a/vendor/github.com/gobwas/ws/util_purego.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build purego -// +build purego - -package ws - -func strToBytes(str string) (bts []byte) { - return []byte(str) -} - -func btsToString(bts []byte) (str string) { - return string(bts) -} diff --git a/vendor/github.com/gobwas/ws/util_unsafe.go b/vendor/github.com/gobwas/ws/util_unsafe.go deleted file mode 100644 index b732297ce..000000000 --- a/vendor/github.com/gobwas/ws/util_unsafe.go +++ /dev/null @@ -1,22 +0,0 @@ -//go:build !purego -// +build !purego - -package ws - -import ( - "reflect" - "unsafe" -) - -func strToBytes(str string) (bts []byte) { - s := (*reflect.StringHeader)(unsafe.Pointer(&str)) - b := (*reflect.SliceHeader)(unsafe.Pointer(&bts)) - b.Data = s.Data - b.Len = s.Len - b.Cap = s.Len - return bts -} - -func btsToString(bts []byte) (str string) { - return *(*string)(unsafe.Pointer(&bts)) -} diff --git a/vendor/github.com/gobwas/ws/write.go b/vendor/github.com/gobwas/ws/write.go deleted file mode 100644 index 94557c696..000000000 --- a/vendor/github.com/gobwas/ws/write.go +++ /dev/null @@ -1,104 +0,0 @@ -package ws - -import ( - "encoding/binary" - "io" -) - -// Header size length bounds in bytes. -const ( - MaxHeaderSize = 14 - MinHeaderSize = 2 -) - -const ( - bit0 = 0x80 - bit1 = 0x40 - bit2 = 0x20 - bit3 = 0x10 - bit4 = 0x08 - bit5 = 0x04 - bit6 = 0x02 - bit7 = 0x01 - - len7 = int64(125) - len16 = int64(^(uint16(0))) - len64 = int64(^(uint64(0)) >> 1) -) - -// HeaderSize returns number of bytes that are needed to encode given header. -// It returns -1 if header is malformed. -func HeaderSize(h Header) (n int) { - switch { - case h.Length < 126: - n = 2 - case h.Length <= len16: - n = 4 - case h.Length <= len64: - n = 10 - default: - return -1 - } - if h.Masked { - n += len(h.Mask) - } - return n -} - -// WriteHeader writes header binary representation into w. -func WriteHeader(w io.Writer, h Header) error { - // Make slice of bytes with capacity 14 that could hold any header. - bts := make([]byte, MaxHeaderSize) - - if h.Fin { - bts[0] |= bit0 - } - bts[0] |= h.Rsv << 4 - bts[0] |= byte(h.OpCode) - - var n int - switch { - case h.Length <= len7: - bts[1] = byte(h.Length) - n = 2 - - case h.Length <= len16: - bts[1] = 126 - binary.BigEndian.PutUint16(bts[2:4], uint16(h.Length)) - n = 4 - - case h.Length <= len64: - bts[1] = 127 - binary.BigEndian.PutUint64(bts[2:10], uint64(h.Length)) - n = 10 - - default: - return ErrHeaderLengthUnexpected - } - - if h.Masked { - bts[1] |= bit0 - n += copy(bts[n:], h.Mask[:]) - } - - _, err := w.Write(bts[:n]) - - return err -} - -// WriteFrame writes frame binary representation into w. -func WriteFrame(w io.Writer, f Frame) error { - err := WriteHeader(w, f.Header) - if err != nil { - return err - } - _, err = w.Write(f.Payload) - return err -} - -// MustWriteFrame is like WriteFrame but panics if frame can not be read. -func MustWriteFrame(w io.Writer, f Frame) { - if err := WriteFrame(w, f); err != nil { - panic(err) - } -} diff --git a/vendor/github.com/gobwas/ws/wsutil/cipher.go b/vendor/github.com/gobwas/ws/wsutil/cipher.go deleted file mode 100644 index bc25064f5..000000000 --- a/vendor/github.com/gobwas/ws/wsutil/cipher.go +++ /dev/null @@ -1,72 +0,0 @@ -package wsutil - -import ( - "io" - - "github.com/gobwas/pool/pbytes" - "github.com/gobwas/ws" -) - -// CipherReader implements io.Reader that applies xor-cipher to the bytes read -// from source. -// It could help to unmask WebSocket frame payload on the fly. -type CipherReader struct { - r io.Reader - mask [4]byte - pos int -} - -// NewCipherReader creates xor-cipher reader from r with given mask. -func NewCipherReader(r io.Reader, mask [4]byte) *CipherReader { - return &CipherReader{r, mask, 0} -} - -// Reset resets CipherReader to read from r with given mask. -func (c *CipherReader) Reset(r io.Reader, mask [4]byte) { - c.r = r - c.mask = mask - c.pos = 0 -} - -// Read implements io.Reader interface. It applies mask given during -// initialization to every read byte. -func (c *CipherReader) Read(p []byte) (n int, err error) { - n, err = c.r.Read(p) - ws.Cipher(p[:n], c.mask, c.pos) - c.pos += n - return n, err -} - -// CipherWriter implements io.Writer that applies xor-cipher to the bytes -// written to the destination writer. It does not modify the original bytes. -type CipherWriter struct { - w io.Writer - mask [4]byte - pos int -} - -// NewCipherWriter creates xor-cipher writer to w with given mask. -func NewCipherWriter(w io.Writer, mask [4]byte) *CipherWriter { - return &CipherWriter{w, mask, 0} -} - -// Reset reset CipherWriter to write to w with given mask. -func (c *CipherWriter) Reset(w io.Writer, mask [4]byte) { - c.w = w - c.mask = mask - c.pos = 0 -} - -// Write implements io.Writer interface. It applies masking during -// initialization to every sent byte. It does not modify original slice. -func (c *CipherWriter) Write(p []byte) (n int, err error) { - cp := pbytes.GetLen(len(p)) - defer pbytes.Put(cp) - - copy(cp, p) - ws.Cipher(cp, c.mask, c.pos) - n, err = c.w.Write(cp) - c.pos += n - - return n, err -} diff --git a/vendor/github.com/gobwas/ws/wsutil/dialer.go b/vendor/github.com/gobwas/ws/wsutil/dialer.go deleted file mode 100644 index 4f8788fb0..000000000 --- a/vendor/github.com/gobwas/ws/wsutil/dialer.go +++ /dev/null @@ -1,147 +0,0 @@ -package wsutil - -import ( - "bufio" - "bytes" - "context" - "io" - "io/ioutil" - "net" - "net/http" - - "github.com/gobwas/ws" -) - -// DebugDialer is a wrapper around ws.Dialer. It tracks i/o of WebSocket -// handshake. That is, it gives ability to receive copied HTTP request and -// response bytes that made inside Dialer.Dial(). -// -// Note that it must not be used in production applications that requires -// Dial() to be efficient. -type DebugDialer struct { - // Dialer contains WebSocket connection establishment options. - Dialer ws.Dialer - - // OnRequest and OnResponse are the callbacks that will be called with the - // HTTP request and response respectively. - OnRequest, OnResponse func([]byte) -} - -// Dial connects to the url host and upgrades connection to WebSocket. It makes -// it by calling d.Dialer.Dial(). -func (d *DebugDialer) Dial(ctx context.Context, urlstr string) (conn net.Conn, br *bufio.Reader, hs ws.Handshake, err error) { - // Need to copy Dialer to prevent original object mutation. - dialer := d.Dialer - var ( - reqBuf bytes.Buffer - resBuf bytes.Buffer - - resContentLength int64 - ) - userWrap := dialer.WrapConn - dialer.WrapConn = func(c net.Conn) net.Conn { - if userWrap != nil { - c = userWrap(c) - } - - // Save the pointer to the raw connection. - conn = c - - var ( - r io.Reader = conn - w io.Writer = conn - ) - if d.OnResponse != nil { - r = &prefetchResponseReader{ - source: conn, - buffer: &resBuf, - contentLength: &resContentLength, - } - } - if d.OnRequest != nil { - w = io.MultiWriter(conn, &reqBuf) - } - return rwConn{conn, r, w} - } - - _, br, hs, err = dialer.Dial(ctx, urlstr) - - if onRequest := d.OnRequest; onRequest != nil { - onRequest(reqBuf.Bytes()) - } - if onResponse := d.OnResponse; onResponse != nil { - // We must split response inside buffered bytes from other received - // bytes from server. - p := resBuf.Bytes() - n := bytes.Index(p, headEnd) - h := n + len(headEnd) // Head end index. - n = h + int(resContentLength) // Body end index. - - onResponse(p[:n]) - - if br != nil { - // If br is non-nil, then it mean two things. First is that - // handshake is OK and server has sent additional bytes – probably - // immediate sent frames (or weird but possible response body). - // Second, the bad one, is that br buffer's source is now rwConn - // instance from above WrapConn call. It is incorrect, so we must - // fix it. - var r io.Reader = conn - if len(p) > h { - // Buffer contains more than just HTTP headers bytes. - r = io.MultiReader( - bytes.NewReader(p[h:]), - conn, - ) - } - br.Reset(r) - // Must make br.Buffered() to be non-zero. - br.Peek(len(p[h:])) - } - } - - return conn, br, hs, err -} - -type rwConn struct { - net.Conn - - r io.Reader - w io.Writer -} - -func (rwc rwConn) Read(p []byte) (int, error) { - return rwc.r.Read(p) -} - -func (rwc rwConn) Write(p []byte) (int, error) { - return rwc.w.Write(p) -} - -var headEnd = []byte("\r\n\r\n") - -type prefetchResponseReader struct { - source io.Reader // Original connection source. - reader io.Reader // Wrapped reader used to read from by clients. - buffer *bytes.Buffer - - contentLength *int64 -} - -func (r *prefetchResponseReader) Read(p []byte) (int, error) { - if r.reader == nil { - resp, err := http.ReadResponse(bufio.NewReader( - io.TeeReader(r.source, r.buffer), - ), nil) - if err == nil { - *r.contentLength, _ = io.Copy(ioutil.Discard, resp.Body) - resp.Body.Close() - } - bts := r.buffer.Bytes() - r.reader = io.MultiReader( - bytes.NewReader(bts), - r.source, - ) - } - return r.reader.Read(p) -} diff --git a/vendor/github.com/gobwas/ws/wsutil/extenstion.go b/vendor/github.com/gobwas/ws/wsutil/extenstion.go deleted file mode 100644 index 6e1ebbf4b..000000000 --- a/vendor/github.com/gobwas/ws/wsutil/extenstion.go +++ /dev/null @@ -1,31 +0,0 @@ -package wsutil - -import "github.com/gobwas/ws" - -// RecvExtension is an interface for clearing fragment header RSV bits. -type RecvExtension interface { - UnsetBits(ws.Header) (ws.Header, error) -} - -// RecvExtensionFunc is an adapter to allow the use of ordinary functions as -// RecvExtension. -type RecvExtensionFunc func(ws.Header) (ws.Header, error) - -// BitsRecv implements RecvExtension. -func (fn RecvExtensionFunc) UnsetBits(h ws.Header) (ws.Header, error) { - return fn(h) -} - -// SendExtension is an interface for setting fragment header RSV bits. -type SendExtension interface { - SetBits(ws.Header) (ws.Header, error) -} - -// SendExtensionFunc is an adapter to allow the use of ordinary functions as -// SendExtension. -type SendExtensionFunc func(ws.Header) (ws.Header, error) - -// BitsSend implements SendExtension. -func (fn SendExtensionFunc) SetBits(h ws.Header) (ws.Header, error) { - return fn(h) -} diff --git a/vendor/github.com/gobwas/ws/wsutil/handler.go b/vendor/github.com/gobwas/ws/wsutil/handler.go deleted file mode 100644 index 44fd360ef..000000000 --- a/vendor/github.com/gobwas/ws/wsutil/handler.go +++ /dev/null @@ -1,219 +0,0 @@ -package wsutil - -import ( - "errors" - "io" - "io/ioutil" - "strconv" - - "github.com/gobwas/pool/pbytes" - "github.com/gobwas/ws" -) - -// ClosedError returned when peer has closed the connection with appropriate -// code and a textual reason. -type ClosedError struct { - Code ws.StatusCode - Reason string -} - -// Error implements error interface. -func (err ClosedError) Error() string { - return "ws closed: " + strconv.FormatUint(uint64(err.Code), 10) + " " + err.Reason -} - -// ControlHandler contains logic of handling control frames. -// -// The intentional way to use it is to read the next frame header from the -// connection, optionally check its validity via ws.CheckHeader() and if it is -// not a ws.OpText of ws.OpBinary (or ws.OpContinuation) – pass it to Handle() -// method. -// -// That is, passed header should be checked to get rid of unexpected errors. -// -// The Handle() method will read out all control frame payload (if any) and -// write necessary bytes as a rfc compatible response. -type ControlHandler struct { - Src io.Reader - Dst io.Writer - State ws.State - - // DisableSrcCiphering disables unmasking payload data read from Src. - // It is useful when wsutil.Reader is used or when frame payload already - // pulled and ciphered out from the connection (and introduced by - // bytes.Reader, for example). - DisableSrcCiphering bool -} - -// ErrNotControlFrame is returned by ControlHandler to indicate that given -// header could not be handled. -var ErrNotControlFrame = errors.New("not a control frame") - -// Handle handles control frames regarding to the c.State and writes responses -// to the c.Dst when needed. -// -// It returns ErrNotControlFrame when given header is not of ws.OpClose, -// ws.OpPing or ws.OpPong operation code. -func (c ControlHandler) Handle(h ws.Header) error { - switch h.OpCode { - case ws.OpPing: - return c.HandlePing(h) - case ws.OpPong: - return c.HandlePong(h) - case ws.OpClose: - return c.HandleClose(h) - } - return ErrNotControlFrame -} - -// HandlePing handles ping frame and writes specification compatible response -// to the c.Dst. -func (c ControlHandler) HandlePing(h ws.Header) error { - if h.Length == 0 { - // The most common case when ping is empty. - // Note that when sending masked frame the mask for empty payload is - // just four zero bytes. - return ws.WriteHeader(c.Dst, ws.Header{ - Fin: true, - OpCode: ws.OpPong, - Masked: c.State.ClientSide(), - }) - } - - // In other way reply with Pong frame with copied payload. - p := pbytes.GetLen(int(h.Length) + ws.HeaderSize(ws.Header{ - Length: h.Length, - Masked: c.State.ClientSide(), - })) - defer pbytes.Put(p) - - // Deal with ciphering i/o: - // Masking key is used to mask the "Payload data" defined in the same - // section as frame-payload-data, which includes "Extension data" and - // "Application data". - // - // See https://tools.ietf.org/html/rfc6455#section-5.3 - // - // NOTE: We prefer ControlWriter with preallocated buffer to - // ws.WriteHeader because it performs one syscall instead of two. - w := NewControlWriterBuffer(c.Dst, c.State, ws.OpPong, p) - r := c.Src - if c.State.ServerSide() && !c.DisableSrcCiphering { - r = NewCipherReader(r, h.Mask) - } - - _, err := io.Copy(w, r) - if err == nil { - err = w.Flush() - } - - return err -} - -// HandlePong handles pong frame by discarding it. -func (c ControlHandler) HandlePong(h ws.Header) error { - if h.Length == 0 { - return nil - } - - buf := pbytes.GetLen(int(h.Length)) - defer pbytes.Put(buf) - - // Discard pong message according to the RFC6455: - // A Pong frame MAY be sent unsolicited. This serves as a - // unidirectional heartbeat. A response to an unsolicited Pong frame - // is not expected. - _, err := io.CopyBuffer(ioutil.Discard, c.Src, buf) - - return err -} - -// HandleClose handles close frame, makes protocol validity checks and writes -// specification compatible response to the c.Dst. -func (c ControlHandler) HandleClose(h ws.Header) error { - if h.Length == 0 { - err := ws.WriteHeader(c.Dst, ws.Header{ - Fin: true, - OpCode: ws.OpClose, - Masked: c.State.ClientSide(), - }) - if err != nil { - return err - } - - // Due to RFC, we should interpret the code as no status code - // received: - // If this Close control frame contains no status code, _The WebSocket - // Connection Close Code_ is considered to be 1005. - // - // See https://tools.ietf.org/html/rfc6455#section-7.1.5 - return ClosedError{ - Code: ws.StatusNoStatusRcvd, - } - } - - // Prepare bytes both for reading reason and sending response. - p := pbytes.GetLen(int(h.Length) + ws.HeaderSize(ws.Header{ - Length: h.Length, - Masked: c.State.ClientSide(), - })) - defer pbytes.Put(p) - - // Get the subslice to read the frame payload out. - subp := p[:h.Length] - - r := c.Src - if c.State.ServerSide() && !c.DisableSrcCiphering { - r = NewCipherReader(r, h.Mask) - } - if _, err := io.ReadFull(r, subp); err != nil { - return err - } - - code, reason := ws.ParseCloseFrameData(subp) - if err := ws.CheckCloseFrameData(code, reason); err != nil { - // Here we could not use the prepared bytes because there is no - // guarantee that it may fit our protocol error closure code and a - // reason. - c.closeWithProtocolError(err) - return err - } - - // Deal with ciphering i/o: - // Masking key is used to mask the "Payload data" defined in the same - // section as frame-payload-data, which includes "Extension data" and - // "Application data". - // - // See https://tools.ietf.org/html/rfc6455#section-5.3 - // - // NOTE: We prefer ControlWriter with preallocated buffer to - // ws.WriteHeader because it performs one syscall instead of two. - w := NewControlWriterBuffer(c.Dst, c.State, ws.OpClose, p) - - // RFC6455#5.5.1: - // If an endpoint receives a Close frame and did not previously - // send a Close frame, the endpoint MUST send a Close frame in - // response. (When sending a Close frame in response, the endpoint - // typically echoes the status code it received.) - _, err := w.Write(p[:2]) - if err != nil { - return err - } - if err := w.Flush(); err != nil { - return err - } - return ClosedError{ - Code: code, - Reason: reason, - } -} - -func (c ControlHandler) closeWithProtocolError(reason error) error { - f := ws.NewCloseFrame(ws.NewCloseFrameBody( - ws.StatusProtocolError, reason.Error(), - )) - if c.State.ClientSide() { - ws.MaskFrameInPlace(f) - } - return ws.WriteFrame(c.Dst, f) -} diff --git a/vendor/github.com/gobwas/ws/wsutil/helper.go b/vendor/github.com/gobwas/ws/wsutil/helper.go deleted file mode 100644 index 231760bc9..000000000 --- a/vendor/github.com/gobwas/ws/wsutil/helper.go +++ /dev/null @@ -1,279 +0,0 @@ -package wsutil - -import ( - "bytes" - "io" - "io/ioutil" - - "github.com/gobwas/ws" -) - -// Message represents a message from peer, that could be presented in one or -// more frames. That is, it contains payload of all message fragments and -// operation code of initial frame for this message. -type Message struct { - OpCode ws.OpCode - Payload []byte -} - -// ReadMessage is a helper function that reads next message from r. It appends -// received message(s) to the third argument and returns the result of it and -// an error if some failure happened. That is, it probably could receive more -// than one message when peer sending fragmented message in multiple frames and -// want to send some control frame between fragments. Then returned slice will -// contain those control frames at first, and then result of gluing fragments. -// -// TODO(gobwas): add DefaultReader with buffer size options. -func ReadMessage(r io.Reader, s ws.State, m []Message) ([]Message, error) { - rd := Reader{ - Source: r, - State: s, - CheckUTF8: true, - OnIntermediate: func(hdr ws.Header, src io.Reader) error { - bts, err := ioutil.ReadAll(src) - if err != nil { - return err - } - m = append(m, Message{hdr.OpCode, bts}) - return nil - }, - } - h, err := rd.NextFrame() - if err != nil { - return m, err - } - var p []byte - if h.Fin { - // No more frames will be read. Use fixed sized buffer to read payload. - p = make([]byte, h.Length) - // It is not possible to receive io.EOF here because Reader does not - // return EOF if frame payload was successfully fetched. - // Thus we consistent here with io.Reader behavior. - _, err = io.ReadFull(&rd, p) - } else { - // Frame is fragmented, thus use ioutil.ReadAll behavior. - var buf bytes.Buffer - _, err = buf.ReadFrom(&rd) - p = buf.Bytes() - } - if err != nil { - return m, err - } - return append(m, Message{h.OpCode, p}), nil -} - -// ReadClientMessage reads next message from r, considering that caller -// represents server side. -// It is a shortcut for ReadMessage(r, ws.StateServerSide, m). -func ReadClientMessage(r io.Reader, m []Message) ([]Message, error) { - return ReadMessage(r, ws.StateServerSide, m) -} - -// ReadServerMessage reads next message from r, considering that caller -// represents client side. -// It is a shortcut for ReadMessage(r, ws.StateClientSide, m). -func ReadServerMessage(r io.Reader, m []Message) ([]Message, error) { - return ReadMessage(r, ws.StateClientSide, m) -} - -// ReadData is a helper function that reads next data (non-control) message -// from rw. -// It takes care on handling all control frames. It will write response on -// control frames to the write part of rw. It blocks until some data frame -// will be received. -// -// Note this may handle and write control frames into the writer part of a -// given io.ReadWriter. -func ReadData(rw io.ReadWriter, s ws.State) ([]byte, ws.OpCode, error) { - return readData(rw, s, ws.OpText|ws.OpBinary) -} - -// ReadClientData reads next data message from rw, considering that caller -// represents server side. It is a shortcut for ReadData(rw, ws.StateServerSide). -// -// Note this may handle and write control frames into the writer part of a -// given io.ReadWriter. -func ReadClientData(rw io.ReadWriter) ([]byte, ws.OpCode, error) { - return ReadData(rw, ws.StateServerSide) -} - -// ReadClientText reads next text message from rw, considering that caller -// represents server side. It is a shortcut for ReadData(rw, ws.StateServerSide). -// It discards received binary messages. -// -// Note this may handle and write control frames into the writer part of a -// given io.ReadWriter. -func ReadClientText(rw io.ReadWriter) ([]byte, error) { - p, _, err := readData(rw, ws.StateServerSide, ws.OpText) - return p, err -} - -// ReadClientBinary reads next binary message from rw, considering that caller -// represents server side. It is a shortcut for ReadData(rw, ws.StateServerSide). -// It discards received text messages. -// -// Note this may handle and write control frames into the writer part of a given -// io.ReadWriter. -func ReadClientBinary(rw io.ReadWriter) ([]byte, error) { - p, _, err := readData(rw, ws.StateServerSide, ws.OpBinary) - return p, err -} - -// ReadServerData reads next data message from rw, considering that caller -// represents client side. It is a shortcut for ReadData(rw, ws.StateClientSide). -// -// Note this may handle and write control frames into the writer part of a -// given io.ReadWriter. -func ReadServerData(rw io.ReadWriter) ([]byte, ws.OpCode, error) { - return ReadData(rw, ws.StateClientSide) -} - -// ReadServerText reads next text message from rw, considering that caller -// represents client side. It is a shortcut for ReadData(rw, ws.StateClientSide). -// It discards received binary messages. -// -// Note this may handle and write control frames into the writer part of a given -// io.ReadWriter. -func ReadServerText(rw io.ReadWriter) ([]byte, error) { - p, _, err := readData(rw, ws.StateClientSide, ws.OpText) - return p, err -} - -// ReadServerBinary reads next binary message from rw, considering that caller -// represents client side. It is a shortcut for ReadData(rw, ws.StateClientSide). -// It discards received text messages. -// -// Note this may handle and write control frames into the writer part of a -// given io.ReadWriter. -func ReadServerBinary(rw io.ReadWriter) ([]byte, error) { - p, _, err := readData(rw, ws.StateClientSide, ws.OpBinary) - return p, err -} - -// WriteMessage is a helper function that writes message to the w. It -// constructs single frame with given operation code and payload. -// It uses given state to prepare side-dependent things, like cipher -// payload bytes from client to server. It will not mutate p bytes if -// cipher must be made. -// -// If you want to write message in fragmented frames, use Writer instead. -func WriteMessage(w io.Writer, s ws.State, op ws.OpCode, p []byte) error { - return writeFrame(w, s, op, true, p) -} - -// WriteServerMessage writes message to w, considering that caller -// represents server side. -func WriteServerMessage(w io.Writer, op ws.OpCode, p []byte) error { - return WriteMessage(w, ws.StateServerSide, op, p) -} - -// WriteServerText is the same as WriteServerMessage with -// ws.OpText. -func WriteServerText(w io.Writer, p []byte) error { - return WriteServerMessage(w, ws.OpText, p) -} - -// WriteServerBinary is the same as WriteServerMessage with -// ws.OpBinary. -func WriteServerBinary(w io.Writer, p []byte) error { - return WriteServerMessage(w, ws.OpBinary, p) -} - -// WriteClientMessage writes message to w, considering that caller -// represents client side. -func WriteClientMessage(w io.Writer, op ws.OpCode, p []byte) error { - return WriteMessage(w, ws.StateClientSide, op, p) -} - -// WriteClientText is the same as WriteClientMessage with -// ws.OpText. -func WriteClientText(w io.Writer, p []byte) error { - return WriteClientMessage(w, ws.OpText, p) -} - -// WriteClientBinary is the same as WriteClientMessage with -// ws.OpBinary. -func WriteClientBinary(w io.Writer, p []byte) error { - return WriteClientMessage(w, ws.OpBinary, p) -} - -// HandleClientControlMessage handles control frame from conn and writes -// response when needed. -// -// It considers that caller represents server side. -func HandleClientControlMessage(conn io.Writer, msg Message) error { - return HandleControlMessage(conn, ws.StateServerSide, msg) -} - -// HandleServerControlMessage handles control frame from conn and writes -// response when needed. -// -// It considers that caller represents client side. -func HandleServerControlMessage(conn io.Writer, msg Message) error { - return HandleControlMessage(conn, ws.StateClientSide, msg) -} - -// HandleControlMessage handles message which was read by ReadMessage() -// functions. -// -// That is, it is expected, that payload is already unmasked and frame header -// were checked by ws.CheckHeader() call. -func HandleControlMessage(conn io.Writer, state ws.State, msg Message) error { - return (ControlHandler{ - DisableSrcCiphering: true, - Src: bytes.NewReader(msg.Payload), - Dst: conn, - State: state, - }).Handle(ws.Header{ - Length: int64(len(msg.Payload)), - OpCode: msg.OpCode, - Fin: true, - Masked: state.ServerSide(), - }) -} - -// ControlFrameHandler returns FrameHandlerFunc for handling control frames. -// For more info see ControlHandler docs. -func ControlFrameHandler(w io.Writer, state ws.State) FrameHandlerFunc { - return func(h ws.Header, r io.Reader) error { - return (ControlHandler{ - DisableSrcCiphering: true, - Src: r, - Dst: w, - State: state, - }).Handle(h) - } -} - -func readData(rw io.ReadWriter, s ws.State, want ws.OpCode) ([]byte, ws.OpCode, error) { - controlHandler := ControlFrameHandler(rw, s) - rd := Reader{ - Source: rw, - State: s, - CheckUTF8: true, - SkipHeaderCheck: false, - OnIntermediate: controlHandler, - } - for { - hdr, err := rd.NextFrame() - if err != nil { - return nil, 0, err - } - if hdr.OpCode.IsControl() { - if err := controlHandler(hdr, &rd); err != nil { - return nil, 0, err - } - continue - } - if hdr.OpCode&want == 0 { - if err := rd.Discard(); err != nil { - return nil, 0, err - } - continue - } - - bts, err := ioutil.ReadAll(&rd) - - return bts, hdr.OpCode, err - } -} diff --git a/vendor/github.com/gobwas/ws/wsutil/reader.go b/vendor/github.com/gobwas/ws/wsutil/reader.go deleted file mode 100644 index f2710af65..000000000 --- a/vendor/github.com/gobwas/ws/wsutil/reader.go +++ /dev/null @@ -1,373 +0,0 @@ -package wsutil - -import ( - "encoding/binary" - "errors" - "io" - "io/ioutil" - - "github.com/gobwas/ws" -) - -// ErrNoFrameAdvance means that Reader's Read() method was called without -// preceding NextFrame() call. -var ErrNoFrameAdvance = errors.New("no frame advance") - -// ErrFrameTooLarge indicates that a message of length higher than -// MaxFrameSize was being read. -var ErrFrameTooLarge = errors.New("frame too large") - -// FrameHandlerFunc handles parsed frame header and its body represented by -// io.Reader. -// -// Note that reader represents already unmasked body. -type FrameHandlerFunc func(ws.Header, io.Reader) error - -// Reader is a wrapper around source io.Reader which represents WebSocket -// connection. It contains options for reading messages from source. -// -// Reader implements io.Reader, which Read() method reads payload of incoming -// WebSocket frames. It also takes care on fragmented frames and possibly -// intermediate control frames between them. -// -// Note that Reader's methods are not goroutine safe. -type Reader struct { - Source io.Reader - State ws.State - - // SkipHeaderCheck disables checking header bits to be RFC6455 compliant. - SkipHeaderCheck bool - - // CheckUTF8 enables UTF-8 checks for text frames payload. If incoming - // bytes are not valid UTF-8 sequence, ErrInvalidUTF8 returned. - CheckUTF8 bool - - // Extensions is a list of negotiated extensions for reader Source. - // It is used to meet the specs and clear appropriate bits in fragment - // header RSV segment. - Extensions []RecvExtension - - // MaxFrameSize controls the maximum frame size in bytes - // that can be read. A message exceeding that size will return - // a ErrFrameTooLarge to the application. - // - // Not setting this field means there is no limit. - MaxFrameSize int64 - - OnContinuation FrameHandlerFunc - OnIntermediate FrameHandlerFunc - - opCode ws.OpCode // Used to store message op code on fragmentation. - frame io.Reader // Used to as frame reader. - raw io.LimitedReader // Used to discard frames without cipher. - utf8 UTF8Reader // Used to check UTF8 sequences if CheckUTF8 is true. - tmp [ws.MaxHeaderSize - 2]byte // Used for reading headers. - cr *CipherReader // Used by NextFrame() to unmask frame payload. -} - -// NewReader creates new frame reader that reads from r keeping given state to -// make some protocol validity checks when it needed. -func NewReader(r io.Reader, s ws.State) *Reader { - return &Reader{ - Source: r, - State: s, - } -} - -// NewClientSideReader is a helper function that calls NewReader with r and -// ws.StateClientSide. -func NewClientSideReader(r io.Reader) *Reader { - return NewReader(r, ws.StateClientSide) -} - -// NewServerSideReader is a helper function that calls NewReader with r and -// ws.StateServerSide. -func NewServerSideReader(r io.Reader) *Reader { - return NewReader(r, ws.StateServerSide) -} - -// Read implements io.Reader. It reads the next message payload into p. -// It takes care on fragmented messages. -// -// The error is io.EOF only if all of message bytes were read. -// If an io.EOF happens during reading some but not all the message bytes -// Read() returns io.ErrUnexpectedEOF. -// -// The error is ErrNoFrameAdvance if no NextFrame() call was made before -// reading next message bytes. -func (r *Reader) Read(p []byte) (n int, err error) { - if r.frame == nil { - if !r.fragmented() { - // Every new Read() must be preceded by NextFrame() call. - return 0, ErrNoFrameAdvance - } - // Read next continuation or intermediate control frame. - _, err := r.NextFrame() - if err != nil { - return 0, err - } - if r.frame == nil { - // We handled intermediate control and now got nothing to read. - return 0, nil - } - } - - n, err = r.frame.Read(p) - if err != nil && err != io.EOF { - return n, err - } - if err == nil && r.raw.N != 0 { - return n, nil - } - - // EOF condition (either err is io.EOF or r.raw.N is zero). - switch { - case r.raw.N != 0: - err = io.ErrUnexpectedEOF - - case r.fragmented(): - err = nil - r.resetFragment() - - case r.CheckUTF8 && !r.utf8.Valid(): - // NOTE: check utf8 only when full message received, since partial - // reads may be invalid. - n = r.utf8.Accepted() - err = ErrInvalidUTF8 - - default: - r.reset() - err = io.EOF - } - - return n, err -} - -// Discard discards current message unread bytes. -// It discards all frames of fragmented message. -func (r *Reader) Discard() (err error) { - for { - _, err = io.Copy(ioutil.Discard, &r.raw) - if err != nil { - break - } - if !r.fragmented() { - break - } - if _, err = r.NextFrame(); err != nil { - break - } - } - r.reset() - return err -} - -// NextFrame prepares r to read next message. It returns received frame header -// and non-nil error on failure. -// -// Note that next NextFrame() call must be done after receiving or discarding -// all current message bytes. -func (r *Reader) NextFrame() (hdr ws.Header, err error) { - hdr, err = r.readHeader(r.Source) - if err == io.EOF && r.fragmented() { - // If we are in fragmented state EOF means that is was totally - // unexpected. - // - // NOTE: This is necessary to prevent callers such that - // ioutil.ReadAll to receive some amount of bytes without an error. - // ReadAll() ignores an io.EOF error, thus caller may think that - // whole message fetched, but actually only part of it. - err = io.ErrUnexpectedEOF - } - if err == nil && !r.SkipHeaderCheck { - err = ws.CheckHeader(hdr, r.State) - } - if err != nil { - return hdr, err - } - - if n := r.MaxFrameSize; n > 0 && hdr.Length > n { - return hdr, ErrFrameTooLarge - } - - // Save raw reader to use it on discarding frame without ciphering and - // other streaming checks. - r.raw = io.LimitedReader{ - R: r.Source, - N: hdr.Length, - } - - frame := io.Reader(&r.raw) - if hdr.Masked { - if r.cr == nil { - r.cr = NewCipherReader(frame, hdr.Mask) - } else { - r.cr.Reset(frame, hdr.Mask) - } - frame = r.cr - } - - for _, x := range r.Extensions { - hdr, err = x.UnsetBits(hdr) - if err != nil { - return hdr, err - } - } - - if r.fragmented() { - if hdr.OpCode.IsControl() { - if cb := r.OnIntermediate; cb != nil { - err = cb(hdr, frame) - } - if err == nil { - // Ensure that src is empty. - _, err = io.Copy(ioutil.Discard, &r.raw) - } - return hdr, err - } - } else { - r.opCode = hdr.OpCode - } - if r.CheckUTF8 && (hdr.OpCode == ws.OpText || (r.fragmented() && r.opCode == ws.OpText)) { - r.utf8.Source = frame - frame = &r.utf8 - } - - // Save reader with ciphering and other streaming checks. - r.frame = frame - - if hdr.OpCode == ws.OpContinuation { - if cb := r.OnContinuation; cb != nil { - err = cb(hdr, frame) - } - } - - if hdr.Fin { - r.State = r.State.Clear(ws.StateFragmented) - } else { - r.State = r.State.Set(ws.StateFragmented) - } - - return hdr, err -} - -func (r *Reader) fragmented() bool { - return r.State.Fragmented() -} - -func (r *Reader) resetFragment() { - r.raw = io.LimitedReader{} - r.frame = nil - // Reset source of the UTF8Reader, but not the state. - r.utf8.Source = nil -} - -func (r *Reader) reset() { - r.raw = io.LimitedReader{} - r.frame = nil - r.utf8 = UTF8Reader{} - r.opCode = 0 -} - -// readHeader reads a frame header from in. -func (r *Reader) readHeader(in io.Reader) (h ws.Header, err error) { - // Make slice of bytes with capacity 12 that could hold any header. - // - // The maximum header size is 14, but due to the 2 hop reads, - // after first hop that reads first 2 constant bytes, we could reuse 2 bytes. - // So 14 - 2 = 12. - bts := r.tmp[:2] - - // Prepare to hold first 2 bytes to choose size of next read. - _, err = io.ReadFull(in, bts) - if err != nil { - return h, err - } - const bit0 = 0x80 - - h.Fin = bts[0]&bit0 != 0 - h.Rsv = (bts[0] & 0x70) >> 4 - h.OpCode = ws.OpCode(bts[0] & 0x0f) - - var extra int - - if bts[1]&bit0 != 0 { - h.Masked = true - extra += 4 - } - - length := bts[1] & 0x7f - switch { - case length < 126: - h.Length = int64(length) - - case length == 126: - extra += 2 - - case length == 127: - extra += 8 - - default: - err = ws.ErrHeaderLengthUnexpected - return h, err - } - - if extra == 0 { - return h, err - } - - // Increase len of bts to extra bytes need to read. - // Overwrite first 2 bytes that was read before. - bts = bts[:extra] - _, err = io.ReadFull(in, bts) - if err != nil { - return h, err - } - - switch { - case length == 126: - h.Length = int64(binary.BigEndian.Uint16(bts[:2])) - bts = bts[2:] - - case length == 127: - if bts[0]&0x80 != 0 { - err = ws.ErrHeaderLengthMSB - return h, err - } - h.Length = int64(binary.BigEndian.Uint64(bts[:8])) - bts = bts[8:] - } - - if h.Masked { - copy(h.Mask[:], bts) - } - - return h, nil -} - -// NextReader prepares next message read from r. It returns header that -// describes the message and io.Reader to read message's payload. It returns -// non-nil error when it is not possible to read message's initial frame. -// -// Note that next NextReader() on the same r should be done after reading all -// bytes from previously returned io.Reader. For more performant way to discard -// message use Reader and its Discard() method. -// -// Note that it will not handle any "intermediate" frames, that possibly could -// be received between text/binary continuation frames. That is, if peer sent -// text/binary frame with fin flag "false", then it could send ping frame, and -// eventually remaining part of text/binary frame with fin "true" – with -// NextReader() the ping frame will be dropped without any notice. To handle -// this rare, but possible situation (and if you do not know exactly which -// frames peer could send), you could use Reader with OnIntermediate field set. -func NextReader(r io.Reader, s ws.State) (ws.Header, io.Reader, error) { - rd := &Reader{ - Source: r, - State: s, - } - header, err := rd.NextFrame() - if err != nil { - return header, nil, err - } - return header, rd, nil -} diff --git a/vendor/github.com/gobwas/ws/wsutil/upgrader.go b/vendor/github.com/gobwas/ws/wsutil/upgrader.go deleted file mode 100644 index 2ed351e08..000000000 --- a/vendor/github.com/gobwas/ws/wsutil/upgrader.go +++ /dev/null @@ -1,68 +0,0 @@ -package wsutil - -import ( - "bufio" - "bytes" - "io" - "io/ioutil" - "net/http" - - "github.com/gobwas/ws" -) - -// DebugUpgrader is a wrapper around ws.Upgrader. It tracks I/O of a -// WebSocket handshake. -// -// Note that it must not be used in production applications that requires -// Upgrade() to be efficient. -type DebugUpgrader struct { - // Upgrader contains upgrade to WebSocket options. - Upgrader ws.Upgrader - - // OnRequest and OnResponse are the callbacks that will be called with the - // HTTP request and response respectively. - OnRequest, OnResponse func([]byte) -} - -// Upgrade calls Upgrade() on underlying ws.Upgrader and tracks I/O on conn. -func (d *DebugUpgrader) Upgrade(conn io.ReadWriter) (hs ws.Handshake, err error) { - var ( - // Take the Reader and Writer parts from conn to be probably replaced - // below. - r io.Reader = conn - w io.Writer = conn - ) - if onRequest := d.OnRequest; onRequest != nil { - var buf bytes.Buffer - // First, we must read the entire request. - req, err := http.ReadRequest(bufio.NewReader( - io.TeeReader(conn, &buf), - )) - if err == nil { - // Fulfill the buffer with the response body. - io.Copy(ioutil.Discard, req.Body) - req.Body.Close() - } - onRequest(buf.Bytes()) - - r = io.MultiReader( - &buf, conn, - ) - } - - if onResponse := d.OnResponse; onResponse != nil { - var buf bytes.Buffer - // Intercept the response stream written by the Upgrade(). - w = io.MultiWriter( - conn, &buf, - ) - defer func() { - onResponse(buf.Bytes()) - }() - } - - return d.Upgrader.Upgrade(struct { - io.Reader - io.Writer - }{r, w}) -} diff --git a/vendor/github.com/gobwas/ws/wsutil/utf8.go b/vendor/github.com/gobwas/ws/wsutil/utf8.go deleted file mode 100644 index b8dc7264e..000000000 --- a/vendor/github.com/gobwas/ws/wsutil/utf8.go +++ /dev/null @@ -1,140 +0,0 @@ -package wsutil - -import ( - "fmt" - "io" -) - -// ErrInvalidUTF8 is returned by UTF8 reader on invalid utf8 sequence. -var ErrInvalidUTF8 = fmt.Errorf("invalid utf8") - -// UTF8Reader implements io.Reader that calculates utf8 validity state after -// every read byte from Source. -// -// Note that in some cases client must call r.Valid() after all bytes are read -// to ensure that all of them are valid utf8 sequences. That is, some io helper -// functions such io.ReadAtLeast or io.ReadFull could discard the error -// information returned by the reader when they receive all of requested bytes. -// For example, the last read sequence is invalid and UTF8Reader returns number -// of bytes read and an error. But helper function decides to discard received -// error due to all requested bytes are completely read from the source. -// -// Another possible case is when some valid sequence become split by the read -// bound. Then UTF8Reader can not make decision about validity of the last -// sequence cause it is not fully read yet. And if the read stops, Valid() will -// return false, even if Read() by itself dit not. -type UTF8Reader struct { - Source io.Reader - - accepted int - - state uint32 - codep uint32 -} - -// NewUTF8Reader creates utf8 reader that reads from r. -func NewUTF8Reader(r io.Reader) *UTF8Reader { - return &UTF8Reader{ - Source: r, - } -} - -// Reset resets utf8 reader to read from r. -func (u *UTF8Reader) Reset(r io.Reader) { - u.Source = r - u.state = 0 - u.codep = 0 -} - -// Read implements io.Reader. -func (u *UTF8Reader) Read(p []byte) (n int, err error) { - n, err = u.Source.Read(p) - - accepted := 0 - s, c := u.state, u.codep - for i := 0; i < n; i++ { - c, s = decode(s, c, p[i]) - if s == utf8Reject { - u.state = s - return accepted, ErrInvalidUTF8 - } - if s == utf8Accept { - accepted = i + 1 - } - } - u.state, u.codep = s, c - u.accepted = accepted - - return n, err -} - -// Valid checks current reader state. It returns true if all read bytes are -// valid UTF-8 sequences, and false if not. -func (u *UTF8Reader) Valid() bool { - return u.state == utf8Accept -} - -// Accepted returns number of valid bytes in last Read(). -func (u *UTF8Reader) Accepted() int { - return u.accepted -} - -// Below is port of UTF-8 decoder from http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ -// -// Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de> -// -// 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. - -const ( - utf8Accept = 0 - utf8Reject = 12 -) - -var utf8d = [...]byte{ - // The first part of the table maps bytes to character classes that - // to reduce the size of the transition table and create bitmasks. - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 10, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, 11, 6, 6, 6, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - - // The second part is a transition table that maps a combination - // of a state of the automaton and a character class to a state. - 0, 12, 24, 36, 60, 96, 84, 12, 12, 12, 48, 72, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, - 12, 0, 12, 12, 12, 12, 12, 0, 12, 0, 12, 12, 12, 24, 12, 12, 12, 12, 12, 24, 12, 24, 12, 12, - 12, 12, 12, 12, 12, 12, 12, 24, 12, 12, 12, 12, 12, 24, 12, 12, 12, 12, 12, 12, 12, 24, 12, 12, - 12, 12, 12, 12, 12, 12, 12, 36, 12, 36, 12, 12, 12, 36, 12, 12, 12, 12, 12, 36, 12, 36, 12, 12, - 12, 36, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, -} - -func decode(state, codep uint32, b byte) (uint32, uint32) { - t := uint32(utf8d[b]) - - if state != utf8Accept { - codep = (uint32(b) & 0x3f) | (codep << 6) - } else { - codep = (0xff >> t) & uint32(b) - } - - return codep, uint32(utf8d[256+state+t]) -} diff --git a/vendor/github.com/gobwas/ws/wsutil/writer.go b/vendor/github.com/gobwas/ws/wsutil/writer.go deleted file mode 100644 index 6a837cf65..000000000 --- a/vendor/github.com/gobwas/ws/wsutil/writer.go +++ /dev/null @@ -1,599 +0,0 @@ -package wsutil - -import ( - "fmt" - "io" - - "github.com/gobwas/pool" - "github.com/gobwas/pool/pbytes" - "github.com/gobwas/ws" -) - -// DefaultWriteBuffer contains size of Writer's default buffer. It used by -// Writer constructor functions. -var DefaultWriteBuffer = 4096 - -var ( - // ErrNotEmpty is returned by Writer.WriteThrough() to indicate that buffer is - // not empty and write through could not be done. That is, caller should call - // Writer.FlushFragment() to make buffer empty. - ErrNotEmpty = fmt.Errorf("writer not empty") - - // ErrControlOverflow is returned by ControlWriter.Write() to indicate that - // no more data could be written to the underlying io.Writer because - // MaxControlFramePayloadSize limit is reached. - ErrControlOverflow = fmt.Errorf("control frame payload overflow") -) - -// Constants which are represent frame length ranges. -const ( - len7 = int64(125) // 126 and 127 are reserved values - len16 = int64(^uint16(0)) - len64 = int64((^uint64(0)) >> 1) -) - -// ControlWriter is a wrapper around Writer that contains some guards for -// buffered writes of control frames. -type ControlWriter struct { - w *Writer - limit int - n int -} - -// NewControlWriter contains ControlWriter with Writer inside whose buffer size -// is at most ws.MaxControlFramePayloadSize + ws.MaxHeaderSize. -func NewControlWriter(dest io.Writer, state ws.State, op ws.OpCode) *ControlWriter { - return &ControlWriter{ - w: NewWriterSize(dest, state, op, ws.MaxControlFramePayloadSize), - limit: ws.MaxControlFramePayloadSize, - } -} - -// NewControlWriterBuffer returns a new ControlWriter with buf as a buffer. -// -// Note that it reserves x bytes of buf for header data, where x could be -// ws.MinHeaderSize or ws.MinHeaderSize+4 (depending on state). At most -// (ws.MaxControlFramePayloadSize + x) bytes of buf will be used. -// -// It panics if len(buf) <= ws.MinHeaderSize + x. -func NewControlWriterBuffer(dest io.Writer, state ws.State, op ws.OpCode, buf []byte) *ControlWriter { - max := ws.MaxControlFramePayloadSize + headerSize(state, ws.MaxControlFramePayloadSize) - if len(buf) > max { - buf = buf[:max] - } - - w := NewWriterBuffer(dest, state, op, buf) - - return &ControlWriter{ - w: w, - limit: len(w.buf), - } -} - -// Write implements io.Writer. It writes to the underlying Writer until it -// returns error or until ControlWriter write limit will be exceeded. -func (c *ControlWriter) Write(p []byte) (n int, err error) { - if c.n+len(p) > c.limit { - return 0, ErrControlOverflow - } - return c.w.Write(p) -} - -// Flush flushes all buffered data to the underlying io.Writer. -func (c *ControlWriter) Flush() error { - return c.w.Flush() -} - -var writers = pool.New(128, 65536) - -// GetWriter tries to reuse Writer getting it from the pool. -// -// This function is intended for memory consumption optimizations, because -// NewWriter*() functions make allocations for inner buffer. -// -// Note the it ceils n to the power of two. -// -// If you have your own bytes buffer pool you could use NewWriterBuffer to use -// pooled bytes in writer. -func GetWriter(dest io.Writer, state ws.State, op ws.OpCode, n int) *Writer { - x, m := writers.Get(n) - if x != nil { - w := x.(*Writer) - w.Reset(dest, state, op) - return w - } - // NOTE: we use m instead of n, because m is an attempt to reuse w of such - // size in the future. - return NewWriterBufferSize(dest, state, op, m) -} - -// PutWriter puts w for future reuse by GetWriter(). -func PutWriter(w *Writer) { - w.Reset(nil, 0, 0) - writers.Put(w, w.Size()) -} - -// Writer contains logic of buffering output data into a WebSocket fragments. -// It is much the same as bufio.Writer, except the thing that it works with -// WebSocket frames, not the raw data. -// -// Writer writes frames with specified OpCode. -// It uses ws.State to decide whether the output frames must be masked. -// -// Note that it does not check control frame size or other RFC rules. -// That is, it must be used with special care to write control frames without -// violation of RFC. You could use ControlWriter that wraps Writer and contains -// some guards for writing control frames. -// -// If an error occurs writing to a Writer, no more data will be accepted and -// all subsequent writes will return the error. -// -// After all data has been written, the client should call the Flush() method -// to guarantee all data has been forwarded to the underlying io.Writer. -type Writer struct { - // dest specifies a destination of buffer flushes. - dest io.Writer - - // op specifies the WebSocket operation code used in flushed frames. - op ws.OpCode - - // state specifies the state of the Writer. - state ws.State - - // extensions is a list of negotiated extensions for writer Dest. - // It is used to meet the specs and set appropriate bits in fragment - // header RSV segment. - extensions []SendExtension - - // noFlush reports whether buffer must grow instead of being flushed. - noFlush bool - - // Raw representation of the buffer, including reserved header bytes. - raw []byte - - // Writeable part of buffer, without reserved header bytes. - // Resetting this to nil will not result in reallocation if raw is not nil. - // And vice versa: if buf is not nil, then Writer is assumed as ready and - // initialized. - buf []byte - - // Buffered bytes counter. - n int - - dirty bool - fseq int - err error -} - -// NewWriter returns a new Writer whose buffer has the DefaultWriteBuffer size. -func NewWriter(dest io.Writer, state ws.State, op ws.OpCode) *Writer { - return NewWriterBufferSize(dest, state, op, 0) -} - -// NewWriterSize returns a new Writer whose buffer size is at most n + ws.MaxHeaderSize. -// That is, output frames payload length could be up to n, except the case when -// Write() is called on empty Writer with len(p) > n. -// -// If n <= 0 then the default buffer size is used as Writer's buffer size. -func NewWriterSize(dest io.Writer, state ws.State, op ws.OpCode, n int) *Writer { - if n > 0 { - n += headerSize(state, n) - } - return NewWriterBufferSize(dest, state, op, n) -} - -// NewWriterBufferSize returns a new Writer whose buffer size is equal to n. -// If n <= ws.MinHeaderSize then the default buffer size is used. -// -// Note that Writer will reserve x bytes for header data, where x is in range -// [ws.MinHeaderSize,ws.MaxHeaderSize]. That is, frames flushed by Writer -// will not have payload length equal to n, except the case when Write() is -// called on empty Writer with len(p) > n. -func NewWriterBufferSize(dest io.Writer, state ws.State, op ws.OpCode, n int) *Writer { - if n <= ws.MinHeaderSize { - n = DefaultWriteBuffer - } - return NewWriterBuffer(dest, state, op, make([]byte, n)) -} - -// NewWriterBuffer returns a new Writer with buf as a buffer. -// -// Note that it reserves x bytes of buf for header data, where x is in range -// [ws.MinHeaderSize,ws.MaxHeaderSize] (depending on state and buf size). -// -// You could use ws.HeaderSize() to calculate number of bytes needed to store -// header data. -// -// It panics if len(buf) is too small to fit header and payload data. -func NewWriterBuffer(dest io.Writer, state ws.State, op ws.OpCode, buf []byte) *Writer { - w := &Writer{ - dest: dest, - state: state, - op: op, - raw: buf, - } - w.initBuf() - return w -} - -func (w *Writer) initBuf() { - offset := reserve(w.state, len(w.raw)) - if len(w.raw) <= offset { - panic("wsutil: writer buffer is too small") - } - w.buf = w.raw[offset:] -} - -// Reset resets Writer as it was created by New() methods. -// Note that Reset does reset extensions and other options was set after -// Writer initialization. -func (w *Writer) Reset(dest io.Writer, state ws.State, op ws.OpCode) { - w.dest = dest - w.state = state - w.op = op - - w.initBuf() - - w.n = 0 - w.dirty = false - w.fseq = 0 - w.extensions = w.extensions[:0] - w.noFlush = false -} - -// ResetOp is an quick version of Reset(). -// ResetOp does reset unwritten fragments and does not reset results of -// SetExtensions() or DisableFlush() methods. -func (w *Writer) ResetOp(op ws.OpCode) { - w.op = op - w.n = 0 - w.dirty = false - w.fseq = 0 -} - -// SetExtensions adds xs as extensions to be used during writes. -func (w *Writer) SetExtensions(xs ...SendExtension) { - w.extensions = xs -} - -// DisableFlush denies Writer to write fragments. -func (w *Writer) DisableFlush() { - w.noFlush = true -} - -// Size returns the size of the underlying buffer in bytes (not including -// WebSocket header bytes). -func (w *Writer) Size() int { - return len(w.buf) -} - -// Available returns how many bytes are unused in the buffer. -func (w *Writer) Available() int { - return len(w.buf) - w.n -} - -// Buffered returns the number of bytes that have been written into the current -// buffer. -func (w *Writer) Buffered() int { - return w.n -} - -// Write implements io.Writer. -// -// Note that even if the Writer was created to have N-sized buffer, Write() -// with payload of N bytes will not fit into that buffer. Writer reserves some -// space to fit WebSocket header data. -func (w *Writer) Write(p []byte) (n int, err error) { - // Even empty p may make a sense. - w.dirty = true - - var nn int - for len(p) > w.Available() && w.err == nil { - if w.noFlush { - w.Grow(len(p)) - continue - } - if w.Buffered() == 0 { - // Large write, empty buffer. Write directly from p to avoid copy. - // Trade off here is that we make additional Write() to underlying - // io.Writer when writing frame header. - // - // On large buffers additional write is better than copying. - nn, _ = w.WriteThrough(p) - } else { - nn = copy(w.buf[w.n:], p) - w.n += nn - w.FlushFragment() - } - n += nn - p = p[nn:] - } - if w.err != nil { - return n, w.err - } - nn = copy(w.buf[w.n:], p) - w.n += nn - n += nn - - // Even if w.Available() == 0 we will not flush buffer preventively because - // this could bring unwanted fragmentation. That is, user could create - // buffer with size that fits exactly all further Write() call, and then - // call Flush(), excepting that single and not fragmented frame will be - // sent. With preemptive flush this case will produce two frames – last one - // will be empty and just to set fin = true. - - return n, w.err -} - -func ceilPowerOfTwo(n int) int { - n |= n >> 1 - n |= n >> 2 - n |= n >> 4 - n |= n >> 8 - n |= n >> 16 - n |= n >> 32 - n++ - return n -} - -// Grow grows Writer's internal buffer capacity to guarantee space for another -// n bytes of _payload_ -- that is, frame header is not included in n. -func (w *Writer) Grow(n int) { - // NOTE: we must respect the possibility of header reserved bytes grow. - var ( - size = len(w.raw) - prevOffset = len(w.raw) - len(w.buf) - nextOffset = len(w.raw) - len(w.buf) - buffered = w.Buffered() - ) - for cap := size - nextOffset - buffered; cap < n; { - // This loop runs twice only at split cases, when reservation of raw - // buffer space for the header shrinks capacity of new buffer such that - // it still less than n. - // - // Loop is safe here because: - // - (offset + buffered + n) is greater than size, otherwise (cap < n) - // would be false: - // size = offset + buffered + freeSpace (cap) - // size' = offset + buffered + wantSpace (n) - // Since (cap < n) is true in the loop condition, size' is guaranteed - // to be greater => no infinite loop. - size = ceilPowerOfTwo(nextOffset + buffered + n) - nextOffset = reserve(w.state, size) - cap = size - nextOffset - buffered - } - if size < len(w.raw) { - panic("wsutil: buffer grow leads to its reduce") - } - if size == len(w.raw) { - return - } - p := make([]byte, size) - copy(p[nextOffset-prevOffset:], w.raw[:prevOffset+buffered]) - w.raw = p - w.buf = w.raw[nextOffset:] -} - -// WriteThrough writes data bypassing the buffer. -// Note that Writer's buffer must be empty before calling WriteThrough(). -func (w *Writer) WriteThrough(p []byte) (n int, err error) { - if w.err != nil { - return 0, w.err - } - if w.Buffered() != 0 { - return 0, ErrNotEmpty - } - - var frame ws.Frame - frame.Header = ws.Header{ - OpCode: w.opCode(), - Fin: false, - Length: int64(len(p)), - } - for _, x := range w.extensions { - frame.Header, err = x.SetBits(frame.Header) - if err != nil { - return 0, err - } - } - if w.state.ClientSide() { - // Should copy bytes to prevent corruption of caller data. - payload := pbytes.GetLen(len(p)) - defer pbytes.Put(payload) - copy(payload, p) - - frame.Payload = payload - frame = ws.MaskFrameInPlace(frame) - } else { - frame.Payload = p - } - - w.err = ws.WriteFrame(w.dest, frame) - if w.err == nil { - n = len(p) - } - - w.dirty = true - w.fseq++ - - return n, w.err -} - -// ReadFrom implements io.ReaderFrom. -func (w *Writer) ReadFrom(src io.Reader) (n int64, err error) { - var nn int - for err == nil { - if w.Available() == 0 { - if w.noFlush { - w.Grow(w.Buffered()) // Twice bigger. - } else { - err = w.FlushFragment() - } - continue - } - - // We copy the behavior of bufio.Writer here. - // Also, from the docs on io.ReaderFrom: - // ReadFrom reads data from r until EOF or error. - // - // See https://codereview.appspot.com/76400048/#ps1 - const maxEmptyReads = 100 - var nr int - for nr < maxEmptyReads { - nn, err = src.Read(w.buf[w.n:]) - if nn != 0 || err != nil { - break - } - nr++ - } - if nr == maxEmptyReads { - return n, io.ErrNoProgress - } - - w.n += nn - n += int64(nn) - } - if err == io.EOF { - // NOTE: Do not flush preemptively. - // See the Write() sources for more info. - err = nil - w.dirty = true - } - return n, err -} - -// Flush writes any buffered data to the underlying io.Writer. -// It sends the frame with "fin" flag set to true. -// -// If no Write() or ReadFrom() was made, then Flush() does nothing. -func (w *Writer) Flush() error { - if (!w.dirty && w.Buffered() == 0) || w.err != nil { - return w.err - } - - w.err = w.flushFragment(true) - w.n = 0 - w.dirty = false - w.fseq = 0 - - return w.err -} - -// FlushFragment writes any buffered data to the underlying io.Writer. -// It sends the frame with "fin" flag set to false. -func (w *Writer) FlushFragment() error { - if w.Buffered() == 0 || w.err != nil { - return w.err - } - - w.err = w.flushFragment(false) - w.n = 0 - w.fseq++ - - return w.err -} - -func (w *Writer) flushFragment(fin bool) (err error) { - var ( - payload = w.buf[:w.n] - header = ws.Header{ - OpCode: w.opCode(), - Fin: fin, - Length: int64(len(payload)), - } - ) - for _, ext := range w.extensions { - header, err = ext.SetBits(header) - if err != nil { - return err - } - } - if w.state.ClientSide() { - header.Masked = true - header.Mask = ws.NewMask() - ws.Cipher(payload, header.Mask, 0) - } - // Write header to the header segment of the raw buffer. - var ( - offset = len(w.raw) - len(w.buf) - skip = offset - ws.HeaderSize(header) - ) - buf := bytesWriter{ - buf: w.raw[skip:offset], - } - if err := ws.WriteHeader(&buf, header); err != nil { - // Must never be reached. - panic("dump header error: " + err.Error()) - } - _, err = w.dest.Write(w.raw[skip : offset+w.n]) - return err -} - -func (w *Writer) opCode() ws.OpCode { - if w.fseq > 0 { - return ws.OpContinuation - } - return w.op -} - -var errNoSpace = fmt.Errorf("not enough buffer space") - -type bytesWriter struct { - buf []byte - pos int -} - -func (w *bytesWriter) Write(p []byte) (int, error) { - n := copy(w.buf[w.pos:], p) - w.pos += n - if n != len(p) { - return n, errNoSpace - } - return n, nil -} - -func writeFrame(w io.Writer, s ws.State, op ws.OpCode, fin bool, p []byte) error { - var frame ws.Frame - if s.ClientSide() { - // Should copy bytes to prevent corruption of caller data. - payload := pbytes.GetLen(len(p)) - defer pbytes.Put(payload) - - copy(payload, p) - - frame = ws.NewFrame(op, fin, payload) - frame = ws.MaskFrameInPlace(frame) - } else { - frame = ws.NewFrame(op, fin, p) - } - - return ws.WriteFrame(w, frame) -} - -// reserve calculates number of bytes need to be reserved for frame header. -// -// Note that instead of ws.HeaderSize() it does calculation based on the buffer -// size, not the payload size. -func reserve(state ws.State, n int) (offset int) { - var mask int - if state.ClientSide() { - mask = 4 - } - switch { - case n <= int(len7)+mask+2: - return mask + 2 - case n <= int(len16)+mask+4: - return mask + 4 - default: - return mask + 10 - } -} - -// headerSize returns number of bytes needed to encode header of a frame with -// given state and length. -func headerSize(s ws.State, n int) int { - return ws.HeaderSize(ws.Header{ - Length: int64(n), - Masked: s.ClientSide(), - }) -} diff --git a/vendor/github.com/gobwas/ws/wsutil/wsutil.go b/vendor/github.com/gobwas/ws/wsutil/wsutil.go deleted file mode 100644 index 86211f3e5..000000000 --- a/vendor/github.com/gobwas/ws/wsutil/wsutil.go +++ /dev/null @@ -1,57 +0,0 @@ -/* -Package wsutil provides utilities for working with WebSocket protocol. - -Overview: - - // Read masked text message from peer and check utf8 encoding. - header, err := ws.ReadHeader(conn) - if err != nil { - // handle err - } - - // Prepare to read payload. - r := io.LimitReader(conn, header.Length) - r = wsutil.NewCipherReader(r, header.Mask) - r = wsutil.NewUTF8Reader(r) - - payload, err := ioutil.ReadAll(r) - if err != nil { - // handle err - } - -You could get the same behavior using just `wsutil.Reader`: - - r := wsutil.Reader{ - Source: conn, - CheckUTF8: true, - } - - payload, err := ioutil.ReadAll(r) - if err != nil { - // handle err - } - -Or even simplest: - - payload, err := wsutil.ReadClientText(conn) - if err != nil { - // handle err - } - -Package is also exports tools for buffered writing: - - // Create buffered writer, that will buffer output bytes and send them as - // 128-length fragments (with exception on large writes, see the doc). - writer := wsutil.NewWriterSize(conn, ws.StateServerSide, ws.OpText, 128) - - _, err := io.CopyN(writer, rand.Reader, 100) - if err == nil { - err = writer.Flush() - } - if err != nil { - // handle error - } - -For more utils and helpers see the documentation. -*/ -package wsutil diff --git a/vendor/modules.txt b/vendor/modules.txt index c60ab145e..5c789d901 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -99,8 +99,8 @@ github.com/cenkalti/backoff/v5 # github.com/cespare/xxhash/v2 v2.3.0 ## explicit; go 1.11 github.com/cespare/xxhash/v2 -# github.com/chromedp/cdproto v0.0.0-20260719223732-95f6af754cfe -## explicit; go 1.26 +# github.com/chromedp/cdproto v0.158.2 +## explicit; go 1.25 github.com/chromedp/cdproto github.com/chromedp/cdproto/accessibility github.com/chromedp/cdproto/ads @@ -113,6 +113,7 @@ github.com/chromedp/cdproto/browser github.com/chromedp/cdproto/cachestorage github.com/chromedp/cdproto/cast github.com/chromedp/cdproto/cdp +github.com/chromedp/cdproto/cdp/jsonv2 github.com/chromedp/cdproto/crashreportcontext github.com/chromedp/cdproto/css github.com/chromedp/cdproto/debugger @@ -129,6 +130,7 @@ github.com/chromedp/cdproto/extensions github.com/chromedp/cdproto/fedcm github.com/chromedp/cdproto/fetch github.com/chromedp/cdproto/filesystem +github.com/chromedp/cdproto/findinpage github.com/chromedp/cdproto/headlessexperimental github.com/chromedp/cdproto/heapprofiler github.com/chromedp/cdproto/indexeddb @@ -159,14 +161,11 @@ github.com/chromedp/cdproto/tracing github.com/chromedp/cdproto/webaudio github.com/chromedp/cdproto/webauthn github.com/chromedp/cdproto/webmcp -# github.com/chromedp/chromedp v0.16.0 -## explicit; go 1.26 +# github.com/chromedp/chromedp v0.21.0 +## explicit; go 1.25 github.com/chromedp/chromedp github.com/chromedp/chromedp/device github.com/chromedp/chromedp/kb -# github.com/chromedp/sysutil v1.1.0 -## explicit; go 1.23 -github.com/chromedp/sysutil # github.com/cloudwego/base64x v0.1.7 ## explicit; go 1.17 github.com/cloudwego/base64x @@ -347,19 +346,6 @@ github.com/go-playground/validator/v10 # github.com/go-sql-driver/mysql v1.10.1 ## explicit; go 1.24.0 github.com/go-sql-driver/mysql -# github.com/gobwas/httphead v0.1.0 -## explicit; go 1.15 -github.com/gobwas/httphead -# github.com/gobwas/pool v0.2.1 -## explicit -github.com/gobwas/pool -github.com/gobwas/pool/internal/pmath -github.com/gobwas/pool/pbufio -github.com/gobwas/pool/pbytes -# github.com/gobwas/ws v1.4.0 -## explicit; go 1.16 -github.com/gobwas/ws -github.com/gobwas/ws/wsutil # github.com/goccy/go-json v0.11.2 ## explicit; go 1.23 github.com/goccy/go-json