mirror of
https://github.com/lightpanda-io/browser.git
synced 2026-04-03 08:00:34 +00:00
Compare commits
385 Commits
v0.2.4
...
wp/mrdimid
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98124e97aa | ||
|
|
dd1c758c0e | ||
|
|
0d87c352b2 | ||
|
|
918f6ce0e6 | ||
|
|
6c5efe6ce0 | ||
|
|
f0be6675e7 | ||
|
|
6a8174a15c | ||
|
|
40c3f1b618 | ||
|
|
6dd2dac049 | ||
|
|
b39bbb557f | ||
|
|
f7682cba67 | ||
|
|
f94c07160a | ||
|
|
bbe6692580 | ||
|
|
9266a1c4d9 | ||
|
|
220d80f05f | ||
|
|
9144c909dd | ||
|
|
7981fcec84 | ||
|
|
71264c56fc | ||
|
|
ca0f77bdee | ||
|
|
fc8b1b8549 | ||
|
|
bc8c44f62f | ||
|
|
01fab5c92a | ||
|
|
1c07d786a0 | ||
|
|
6f0cd87d1c | ||
|
|
e44308cba2 | ||
|
|
50245c5157 | ||
|
|
9ca5188e12 | ||
|
|
e25c33eaa6 | ||
|
|
56cc881ac0 | ||
|
|
7bddc0a89c | ||
|
|
50896bdc9d | ||
|
|
8dd4567828 | ||
|
|
06ef6d3e6a | ||
|
|
14b58e8062 | ||
|
|
eee232c12c | ||
|
|
febe321aef | ||
|
|
28777ac717 | ||
|
|
13b008b56c | ||
|
|
403f42bf38 | ||
|
|
523efbd85a | ||
|
|
fcacc8bfc6 | ||
|
|
b2e301418f | ||
|
|
334a2e44a1 | ||
|
|
252b3c3bf6 | ||
|
|
c9121a03d2 | ||
|
|
cc93180d57 | ||
|
|
24221748e1 | ||
|
|
4062a425cb | ||
|
|
cce533ebb6 | ||
|
|
48df38cbfe | ||
|
|
f982f073df | ||
|
|
34999f12ca | ||
|
|
c8d5665653 | ||
|
|
ddebaf87d0 | ||
|
|
6b80cd6109 | ||
|
|
7635d8d2a5 | ||
|
|
141ae053db | ||
|
|
10ec4ff814 | ||
|
|
d2da0b7c0e | ||
|
|
7d0548406e | ||
|
|
634e3e35a0 | ||
|
|
da3dc58199 | ||
|
|
4f99df694b | ||
|
|
c121dbbd67 | ||
|
|
c1c0a7d494 | ||
|
|
0749f60702 | ||
|
|
982b8e2d72 | ||
|
|
6e7c8d7ae2 | ||
|
|
3c858f522b | ||
|
|
f2a30f8cdd | ||
|
|
43785bfab4 | ||
|
|
78edf6d324 | ||
|
|
73565c4493 | ||
|
|
ca0ef18bdf | ||
|
|
6ed011e2f8 | ||
|
|
23d322452a | ||
|
|
5d3b965d28 | ||
|
|
d9794d72c7 | ||
|
|
524b5be937 | ||
|
|
ac2e276a6a | ||
|
|
4f4dbc0c22 | ||
|
|
8c37cac957 | ||
|
|
eceab76b6f | ||
|
|
1f81b6ddc4 | ||
|
|
52c3aadd24 | ||
|
|
ad87573d09 | ||
|
|
20fbfc8544 | ||
|
|
7695c8403f | ||
|
|
421983d06e | ||
|
|
328c681a8f | ||
|
|
48d94d0f68 | ||
|
|
10ad5d763e | ||
|
|
2a78c946e4 | ||
|
|
a7872aa054 | ||
|
|
5c228ae0a1 | ||
|
|
ce73f7ac5a | ||
|
|
64107f5957 | ||
|
|
8a1795d56f | ||
|
|
b104c3bfe8 | ||
|
|
82e3f126ff | ||
|
|
175488563e | ||
|
|
da51cdd11d | ||
|
|
a8a47b138f | ||
|
|
b63d4cf675 | ||
|
|
03b999c592 | ||
|
|
a91afab038 | ||
|
|
d4747b5386 | ||
|
|
41b81c8b05 | ||
|
|
552831364d | ||
|
|
42b5e32473 | ||
|
|
e9c36fd6f8 | ||
|
|
952dfbef36 | ||
|
|
254984b600 | ||
|
|
8cbc58d257 | ||
|
|
e6cc3e8c34 | ||
|
|
516335e0ed | ||
|
|
01798ed7f8 | ||
|
|
fcad67a854 | ||
|
|
e359ffead0 | ||
|
|
eb09041859 | ||
|
|
b3d52c966d | ||
|
|
3fb8a14348 | ||
|
|
84a949e7c7 | ||
|
|
eaf1cb26b2 | ||
|
|
f37962d3de | ||
|
|
511e957d4b | ||
|
|
71df03b729 | ||
|
|
839052f4b8 | ||
|
|
7c18d857f0 | ||
|
|
947e672d18 | ||
|
|
96942960a9 | ||
|
|
8b0118e2c8 | ||
|
|
5f9a7a5381 | ||
|
|
6897d72c3e | ||
|
|
aae9a505e0 | ||
|
|
45196e022b | ||
|
|
b9e4c44d63 | ||
|
|
0a9e5b66ee | ||
|
|
8b99e82743 | ||
|
|
059fb85e22 | ||
|
|
8997df861a | ||
|
|
e65667963f | ||
|
|
3d51667fc8 | ||
|
|
7fc6e97cd8 | ||
|
|
1473e58a41 | ||
|
|
2394b2f44f | ||
|
|
516bd98198 | ||
|
|
7d8688a130 | ||
|
|
631ec70058 | ||
|
|
6fd51cfdc0 | ||
|
|
6857b74623 | ||
|
|
5ec4305a9f | ||
|
|
88baff96d0 | ||
|
|
e871f0002b | ||
|
|
7358d48e35 | ||
|
|
178fbf0fca | ||
|
|
a50597ff27 | ||
|
|
e4cb78abee | ||
|
|
732884a3b2 | ||
|
|
80f2c42c69 | ||
|
|
49a5a39659 | ||
|
|
a4a7040b98 | ||
|
|
de5a7d5b99 | ||
|
|
3f92e388be | ||
|
|
25c941b847 | ||
|
|
24b6934d3b | ||
|
|
d286ab406c | ||
|
|
ef6a7a6904 | ||
|
|
c61eda0d24 | ||
|
|
ad226b6fb1 | ||
|
|
24491f0dfe | ||
|
|
870fd1654d | ||
|
|
38bc912e4e | ||
|
|
315c9a2d92 | ||
|
|
a14ad6f700 | ||
|
|
d56e63a91b | ||
|
|
76dcdfb98c | ||
|
|
99c09ba8a1 | ||
|
|
0f18b76813 | ||
|
|
8504e4cd22 | ||
|
|
ebe793e0e7 | ||
|
|
965c6cf4d9 | ||
|
|
2b1ab3184e | ||
|
|
e7d21c2dbe | ||
|
|
11906d9d71 | ||
|
|
ac5a64d77a | ||
|
|
c86c851c60 | ||
|
|
721cf98486 | ||
|
|
84bbb6efd4 | ||
|
|
f897cda6cd | ||
|
|
2da8b25b09 | ||
|
|
3f94fd90dd | ||
|
|
bc6be22cb4 | ||
|
|
e23604e08d | ||
|
|
be858ac9ce | ||
|
|
137ab4a557 | ||
|
|
bad0fc386d | ||
|
|
641c7b2c89 | ||
|
|
21be3db51f | ||
|
|
e978857820 | ||
|
|
3bf596c54c | ||
|
|
aedb823b4d | ||
|
|
7a417435cc | ||
|
|
497d6e80f7 | ||
|
|
ae6ab34e72 | ||
|
|
4c26161728 | ||
|
|
1731dca5dd | ||
|
|
ee2caff46e | ||
|
|
db8fb8b05d | ||
|
|
bec7e141dc | ||
|
|
ab85b4b129 | ||
|
|
b030049b40 | ||
|
|
1338a3d89d | ||
|
|
181178296f | ||
|
|
df7888d6fb | ||
|
|
dd15f5e052 | ||
|
|
f348d85b11 | ||
|
|
8c8a05b8c1 | ||
|
|
34d2fc1503 | ||
|
|
9b3fa809bf | ||
|
|
59535c112e | ||
|
|
04e5a6425a | ||
|
|
424dddf67b | ||
|
|
f0d6ae2a00 | ||
|
|
25298a32fa | ||
|
|
ba28bf01b7 | ||
|
|
d15c29b1a3 | ||
|
|
b083910a51 | ||
|
|
235aad32a6 | ||
|
|
a818560344 | ||
|
|
8f179becf7 | ||
|
|
e1695a0874 | ||
|
|
af7498d283 | ||
|
|
3e2a4d8053 | ||
|
|
29982e2caf | ||
|
|
5fea1df42b | ||
|
|
a041162b32 | ||
|
|
32cd3981d8 | ||
|
|
ca5af87196 | ||
|
|
a8164f612f | ||
|
|
d3bb0b6ff0 | ||
|
|
0ef10c1e13 | ||
|
|
4017911373 | ||
|
|
048034d4b1 | ||
|
|
fcb3f08bcb | ||
|
|
d2a05bb622 | ||
|
|
f7254ee169 | ||
|
|
a0e5c9d570 | ||
|
|
8291e4ba73 | ||
|
|
b324be3b0b | ||
|
|
6ba0ba7126 | ||
|
|
1d8e0629af | ||
|
|
42df54869f | ||
|
|
7b758b85ec | ||
|
|
82987ec401 | ||
|
|
71707b5aa7 | ||
|
|
ca2df83928 | ||
|
|
085771c2f0 | ||
|
|
607a638858 | ||
|
|
5f6d06d05d | ||
|
|
19ecb87b07 | ||
|
|
2a332c0883 | ||
|
|
bb773c6c13 | ||
|
|
238de489c1 | ||
|
|
6b4db330d8 | ||
|
|
ea5d7c0dee | ||
|
|
0f189f1af3 | ||
|
|
0f1b8dd51a | ||
|
|
d7e6946a78 | ||
|
|
255b7b1a54 | ||
|
|
79e1c751a1 | ||
|
|
fc745b9614 | ||
|
|
95b1baebd2 | ||
|
|
56fe1ceb97 | ||
|
|
863a51e556 | ||
|
|
69b3064b45 | ||
|
|
fb3eab1aa8 | ||
|
|
32c7399f26 | ||
|
|
955351b5bd | ||
|
|
75f6c67b6e | ||
|
|
700a3e6ed9 | ||
|
|
00702448c7 | ||
|
|
5074827d51 | ||
|
|
ceb0711e42 | ||
|
|
ddb5824b58 | ||
|
|
39f9209374 | ||
|
|
5fea4cf760 | ||
|
|
0e5ec86ca9 | ||
|
|
8b95211055 | ||
|
|
a27339b954 | ||
|
|
028b728760 | ||
|
|
18e63df01e | ||
|
|
5f459c0901 | ||
|
|
a90bcde38c | ||
|
|
603e7d922e | ||
|
|
861126f810 | ||
|
|
eb9b706ebc | ||
|
|
de9cbae0b2 | ||
|
|
25e890986f | ||
|
|
f66627dd04 | ||
|
|
924eb33b3f | ||
|
|
1b288c541a | ||
|
|
2612b8c86f | ||
|
|
3e2796d456 | ||
|
|
7092913863 | ||
|
|
67625fc347 | ||
|
|
eb55030b06 | ||
|
|
6e1b2d50f2 | ||
|
|
c6f72c44b8 | ||
|
|
d38ded0f26 | ||
|
|
ec20b7bd3a | ||
|
|
0766cf464a | ||
|
|
867f00e091 | ||
|
|
c823b8d7ae | ||
|
|
393d4d336c | ||
|
|
2cb3f2d03d | ||
|
|
279f2dd633 | ||
|
|
dec051a6e0 | ||
|
|
790fdd320c | ||
|
|
feb4a364a7 | ||
|
|
1140149e1e | ||
|
|
2ee9599b6e | ||
|
|
188d45e002 | ||
|
|
7c4c2f7860 | ||
|
|
90b7f2ff3b | ||
|
|
d3f0041e93 | ||
|
|
9d60142828 | ||
|
|
68d5edca60 | ||
|
|
1b369489df | ||
|
|
600ddfbf2d | ||
|
|
415d4dde2a | ||
|
|
1867245ed3 | ||
|
|
71d34592d9 | ||
|
|
db2927eea7 | ||
|
|
bb01a5cb31 | ||
|
|
815319140f | ||
|
|
6e6082119f | ||
|
|
da48ffe05c | ||
|
|
081979be3b | ||
|
|
3673956c1c | ||
|
|
bdd3c274ed | ||
|
|
423034d5c4 | ||
|
|
19fd2b12c0 | ||
|
|
21cd17873f | ||
|
|
9870fa9e34 | ||
|
|
938cd5e136 | ||
|
|
e8025ad4b3 | ||
|
|
07fa141aaa | ||
|
|
18bdf1e8b3 | ||
|
|
5be977005e | ||
|
|
282b64278e | ||
|
|
7263d484de | ||
|
|
bdb059b6c9 | ||
|
|
de3f5011bc | ||
|
|
de9faffa33 | ||
|
|
f67ca69e05 | ||
|
|
dd19e880c5 | ||
|
|
b5e8fa007c | ||
|
|
c3555bfcab | ||
|
|
0383db8788 | ||
|
|
d7af122c18 | ||
|
|
e15b8145b1 | ||
|
|
d75f5f9231 | ||
|
|
9939797792 | ||
|
|
5248b9fc6f | ||
|
|
96cfdebced | ||
|
|
944f34b833 | ||
|
|
1023b2ca9c | ||
|
|
16318bb9f6 | ||
|
|
350586335d | ||
|
|
9d809499a5 | ||
|
|
1461d029db | ||
|
|
e37d4a6756 | ||
|
|
e2a1ce623c | ||
|
|
0ff243266c | ||
|
|
645da2e307 | ||
|
|
84ffffb3f3 | ||
|
|
90138ed574 | ||
|
|
338580087e | ||
|
|
37ecd5cdef | ||
|
|
c4391ff058 | ||
|
|
3822e3f8d9 | ||
|
|
f8f99f3878 | ||
|
|
e77e4acea9 | ||
|
|
c6de444d0b |
2
.github/actions/install/action.yml
vendored
2
.github/actions/install/action.yml
vendored
@@ -13,7 +13,7 @@ inputs:
|
||||
zig-v8:
|
||||
description: 'zig v8 version to install'
|
||||
required: false
|
||||
default: 'v0.2.9'
|
||||
default: 'v0.3.1'
|
||||
v8:
|
||||
description: 'v8 version to install'
|
||||
required: false
|
||||
|
||||
2
.github/workflows/e2e-integration-test.yml
vendored
2
.github/workflows/e2e-integration-test.yml
vendored
@@ -63,6 +63,6 @@ jobs:
|
||||
|
||||
- name: run end to end integration tests
|
||||
run: |
|
||||
./lightpanda serve & echo $! > LPD.pid
|
||||
./lightpanda serve --log_level error & echo $! > LPD.pid
|
||||
go run integration/main.go
|
||||
kill `cat LPD.pid`
|
||||
|
||||
88
.github/workflows/wpt.yml
vendored
88
.github/workflows/wpt.yml
vendored
@@ -15,11 +15,11 @@ on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
wpt:
|
||||
name: web platform tests json output
|
||||
wpt-build-release:
|
||||
name: zig build release
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
@@ -30,11 +30,85 @@ jobs:
|
||||
|
||||
- uses: ./.github/actions/install
|
||||
|
||||
- name: build wpt
|
||||
run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -- version
|
||||
- name: zig build release
|
||||
run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dcpu=x86_64 -Dgit_commit=$(git rev-parse --short ${{ github.sha }})
|
||||
|
||||
- name: upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: lightpanda-build-release
|
||||
path: |
|
||||
zig-out/bin/lightpanda
|
||||
retention-days: 1
|
||||
|
||||
wpt-build-runner:
|
||||
name: build wpt runner
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
repository: 'lightpanda-io/demo'
|
||||
fetch-depth: 0
|
||||
|
||||
- run: |
|
||||
cd ./wptrunner
|
||||
CGO_ENABLED=0 go build
|
||||
|
||||
- name: upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: wptrunner
|
||||
path: |
|
||||
wptrunner/wptrunner
|
||||
retention-days: 1
|
||||
|
||||
run-wpt:
|
||||
name: web platform tests json output
|
||||
needs:
|
||||
- wpt-build-release
|
||||
- wpt-build-runner
|
||||
|
||||
# use a self host runner.
|
||||
runs-on: lpd-bench-hetzner
|
||||
timeout-minutes: 120
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
ref: fork
|
||||
repository: 'lightpanda-io/wpt'
|
||||
fetch-depth: 0
|
||||
|
||||
# The hosts are configured manually on the self host runner.
|
||||
# - name: create custom hosts
|
||||
# run: ./wpt make-hosts-file | sudo tee -a /etc/hosts
|
||||
|
||||
- name: generate manifest
|
||||
run: ./wpt manifest
|
||||
|
||||
- name: download lightpanda release
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: lightpanda-build-release
|
||||
|
||||
- run: chmod a+x ./lightpanda
|
||||
|
||||
- name: download wptrunner
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: wptrunner
|
||||
|
||||
- run: chmod a+x ./wptrunner
|
||||
|
||||
- name: run test with json output
|
||||
run: zig-out/bin/lightpanda-wpt --json > wpt.json
|
||||
run: |
|
||||
./wpt serve 2> /dev/null & echo $! > WPT.pid
|
||||
sleep 10s
|
||||
./wptrunner -lpd-path ./lightpanda -json -concurrency 3 > wpt.json
|
||||
kill `cat WPT.pid`
|
||||
|
||||
- name: write commit
|
||||
run: |
|
||||
@@ -51,7 +125,7 @@ jobs:
|
||||
|
||||
perf-fmt:
|
||||
name: perf-fmt
|
||||
needs: wpt
|
||||
needs: run-wpt
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
5
.gitignore
vendored
5
.gitignore
vendored
@@ -1,11 +1,6 @@
|
||||
zig-cache
|
||||
/.zig-cache/
|
||||
/.lp-cache/
|
||||
zig-out
|
||||
/vendor/netsurf/out
|
||||
/vendor/libiconv/
|
||||
lightpanda.id
|
||||
/v8/
|
||||
/build/
|
||||
/src/html5ever/target/
|
||||
src/snapshot.bin
|
||||
|
||||
15
.gitmodules
vendored
15
.gitmodules
vendored
@@ -1,15 +0,0 @@
|
||||
[submodule "tests/wpt"]
|
||||
path = tests/wpt
|
||||
url = https://github.com/lightpanda-io/wpt
|
||||
[submodule "vendor/nghttp2"]
|
||||
path = vendor/nghttp2
|
||||
url = https://github.com/nghttp2/nghttp2.git
|
||||
[submodule "vendor/zlib"]
|
||||
path = vendor/zlib
|
||||
url = https://github.com/madler/zlib.git
|
||||
[submodule "vendor/curl"]
|
||||
path = vendor/curl
|
||||
url = https://github.com/curl/curl.git
|
||||
[submodule "vendor/brotli"]
|
||||
path = vendor/brotli
|
||||
url = https://github.com/google/brotli
|
||||
@@ -3,7 +3,7 @@ FROM debian:stable-slim
|
||||
ARG MINISIG=0.12
|
||||
ARG ZIG_MINISIG=RWSGOq2NVecA2UPNdBUZykf1CCb147pkmdtYxgb3Ti+JO/wCYvhbAb/U
|
||||
ARG V8=14.0.365.4
|
||||
ARG ZIG_V8=v0.2.9
|
||||
ARG ZIG_V8=v0.3.1
|
||||
ARG TARGETPLATFORM
|
||||
|
||||
RUN apt-get update -yq && \
|
||||
|
||||
18
Makefile
18
Makefile
@@ -47,7 +47,7 @@ help:
|
||||
|
||||
# $(ZIG) commands
|
||||
# ------------
|
||||
.PHONY: build build-v8-snapshot build-dev run run-release shell test bench wpt data end2end
|
||||
.PHONY: build build-v8-snapshot build-dev run run-release shell test bench data end2end
|
||||
|
||||
## Build v8 snapshot
|
||||
build-v8-snapshot:
|
||||
@@ -82,15 +82,6 @@ shell:
|
||||
@printf "\033[36mBuilding shell...\033[0m\n"
|
||||
@$(ZIG) build shell || (printf "\033[33mBuild ERROR\033[0m\n"; exit 1;)
|
||||
|
||||
## Run WPT tests
|
||||
wpt:
|
||||
@printf "\033[36mBuilding wpt...\033[0m\n"
|
||||
@$(ZIG) build wpt -- $(filter-out $@,$(MAKECMDGOALS)) || (printf "\033[33mBuild ERROR\033[0m\n"; exit 1;)
|
||||
|
||||
wpt-summary:
|
||||
@printf "\033[36mBuilding wpt...\033[0m\n"
|
||||
@$(ZIG) build wpt -- --summary $(filter-out $@,$(MAKECMDGOALS)) || (printf "\033[33mBuild ERROR\033[0m\n"; exit 1;)
|
||||
|
||||
## Test - `grep` is used to filter out the huge compile command on build
|
||||
ifeq ($(OS), macos)
|
||||
test:
|
||||
@@ -111,13 +102,8 @@ end2end:
|
||||
# ------------
|
||||
.PHONY: install
|
||||
|
||||
## Install and build dependencies for release
|
||||
install: install-submodule
|
||||
install: build
|
||||
|
||||
data:
|
||||
cd src/data && go run public_suffix_list_gen.go > public_suffix_list.zig
|
||||
|
||||
## Init and update git submodule
|
||||
install-submodule:
|
||||
@git submodule init && \
|
||||
git submodule update
|
||||
|
||||
76
README.md
76
README.md
@@ -220,18 +220,6 @@ For **MacOS**, you need cmake and [Rust](https://rust-lang.org/tools/install/).
|
||||
brew install cmake
|
||||
```
|
||||
|
||||
### Install Git submodules
|
||||
|
||||
The project uses git submodules for dependencies.
|
||||
|
||||
To init or update the submodules in the `vendor/` directory:
|
||||
|
||||
```
|
||||
make install-submodule
|
||||
```
|
||||
|
||||
This is an alias for `git submodule init && git submodule update`.
|
||||
|
||||
### Build and run
|
||||
|
||||
You an build the entire browser with `make build` or `make build-dev` for debug
|
||||
@@ -281,35 +269,75 @@ make end2end
|
||||
Lightpanda is tested against the standardized [Web Platform
|
||||
Tests](https://web-platform-tests.org/).
|
||||
|
||||
The relevant tests cases are committed in a [dedicated repository](https://github.com/lightpanda-io/wpt) which is fetched by the `make install-submodule` command.
|
||||
|
||||
All the tests cases executed are located in the `tests/wpt` sub-directory.
|
||||
We use [a fork](https://github.com/lightpanda-io/wpt/tree/fork) including a custom
|
||||
[`testharnessreport.js`](https://github.com/lightpanda-io/wpt/commit/01a3115c076a3ad0c84849dbbf77a6e3d199c56f).
|
||||
|
||||
For reference, you can easily execute a WPT test case with your browser via
|
||||
[wpt.live](https://wpt.live).
|
||||
|
||||
#### Configure WPT HTTP server
|
||||
|
||||
To run the test, you must clone the repository, configure the custom hosts and generate the
|
||||
`MANIFEST.json` file.
|
||||
|
||||
Clone the repository with the `fork` branch.
|
||||
```
|
||||
git clone -b fork --depth=1 git@github.com:lightpanda-io/wpt.git
|
||||
```
|
||||
|
||||
Enter into the `wpt/` dir.
|
||||
|
||||
Install custom domains in your `/etc/hosts`
|
||||
```
|
||||
./wpt make-hosts-file | sudo tee -a /etc/hosts
|
||||
```
|
||||
|
||||
Generate `MANIFEST.json`
|
||||
```
|
||||
./wpt manifest
|
||||
```
|
||||
Use the [WPT's setup
|
||||
guide](https://web-platform-tests.org/running-tests/from-local-system.html) for
|
||||
details.
|
||||
|
||||
#### Run WPT test suite
|
||||
|
||||
To run all the tests:
|
||||
An external [Go](https://go.dev) runner is provided by
|
||||
[github.com/lightpanda-io/demo/](https://github.com/lightpanda-io/demo/)
|
||||
repository, located into `wptrunner/` dir.
|
||||
You need to clone the project first.
|
||||
|
||||
First start the WPT's HTTP server from your `wpt/` clone dir.
|
||||
```
|
||||
./wpt serve
|
||||
```
|
||||
|
||||
Run a Lightpanda browser
|
||||
|
||||
```
|
||||
make wpt
|
||||
zig build run -- --insecure_disable_tls_host_verification
|
||||
```
|
||||
|
||||
Then you can start the wptrunner from the Demo's clone dir:
|
||||
```
|
||||
cd wptrunner && go run .
|
||||
```
|
||||
|
||||
Or one specific test:
|
||||
|
||||
```
|
||||
make wpt Node-childNodes.html
|
||||
cd wptrunner && go run . Node-childNodes.html
|
||||
```
|
||||
|
||||
#### Add a new WPT test case
|
||||
`wptrunner` command accepts `--summary` and `--json` options modifying output.
|
||||
Also `--concurrency` define the concurrency limit.
|
||||
|
||||
We add new relevant tests cases files when we implemented changes in Lightpanda.
|
||||
:warning: Running the whole test suite will take a long time. In this case,
|
||||
it's useful to build in `releaseFast` mode to make tests faster.
|
||||
|
||||
To add a new test, copy the file you want from the [WPT
|
||||
repo](https://github.com/web-platform-tests/wpt) into the `tests/wpt` directory.
|
||||
|
||||
:warning: Please keep the original directory tree structure of `tests/wpt`.
|
||||
```
|
||||
zig build -Doptimize=ReleaseFast run
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
|
||||
@@ -1,18 +1,36 @@
|
||||
.{
|
||||
.name = .browser,
|
||||
.paths = .{""},
|
||||
.version = "0.0.0",
|
||||
.fingerprint = 0xda130f3af836cea0, // Changing this has security and trust implications.
|
||||
.minimum_zig_version = "0.15.2",
|
||||
.dependencies = .{
|
||||
.v8 = .{
|
||||
.url = "https://github.com/lightpanda-io/zig-v8-fork/archive/refs/tags/v0.2.9.tar.gz",
|
||||
.hash = "v8-0.0.0-xddH689vBACgpqFVEhT2wxRin-qQQSOcKJoM37MVo0rU",
|
||||
.url = "https://github.com/lightpanda-io/zig-v8-fork/archive/refs/tags/v0.3.1.tar.gz",
|
||||
.hash = "v8-0.0.0-xddH64J7BAC81mkf6G9RbEJxS-W3TIRl5iFnShwbqCqy",
|
||||
|
||||
},
|
||||
//.v8 = .{ .path = "../zig-v8-fork" },
|
||||
.brotli = .{
|
||||
// v1.2.0
|
||||
.url = "https://github.com/google/brotli/archive/028fb5a23661f123017c060daa546b55cf4bde29.tar.gz",
|
||||
.hash = "N-V-__8AAJudKgCQCuIiH6MJjAiIJHfg_tT_Ew-0vZwVkCo_",
|
||||
},
|
||||
.zlib = .{
|
||||
.url = "https://github.com/madler/zlib/releases/download/v1.3.2/zlib-1.3.2.tar.gz",
|
||||
.hash = "N-V-__8AAJ2cNgAgfBtAw33Bxfu1IWISDeKKSr3DAqoAysIJ",
|
||||
},
|
||||
.nghttp2 = .{
|
||||
.url = "https://github.com/nghttp2/nghttp2/releases/download/v1.68.0/nghttp2-1.68.0.tar.gz",
|
||||
.hash = "N-V-__8AAL15vQCI63ZL6Zaz5hJg6JTEgYXGbLnMFSnf7FT3",
|
||||
},
|
||||
.@"boringssl-zig" = .{
|
||||
.url = "git+https://github.com/Syndica/boringssl-zig.git#c53df00d06b02b755ad88bbf4d1202ed9687b096",
|
||||
.hash = "boringssl-0.1.0-VtJeWehMAAA4RNnwRnzEvKcS9rjsR1QVRw1uJrwXxmVK",
|
||||
},
|
||||
.curl = .{
|
||||
.url = "https://github.com/curl/curl/releases/download/curl-8_18_0/curl-8.18.0.tar.gz",
|
||||
.hash = "N-V-__8AALp9QAGn6CCHZ6fK_FfMyGtG824LSHYHHasM3w-y",
|
||||
},
|
||||
},
|
||||
.paths = .{""},
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ pub fn init(allocator: Allocator, config: *const Config) !*App {
|
||||
app.telemetry = try Telemetry.init(app, config.mode);
|
||||
errdefer app.telemetry.deinit();
|
||||
|
||||
app.arena_pool = ArenaPool.init(allocator);
|
||||
app.arena_pool = ArenaPool.init(allocator, 512, 1024 * 16);
|
||||
errdefer app.arena_pool.deinit();
|
||||
|
||||
return app;
|
||||
|
||||
@@ -36,12 +36,12 @@ const Entry = struct {
|
||||
arena: ArenaAllocator,
|
||||
};
|
||||
|
||||
pub fn init(allocator: Allocator) ArenaPool {
|
||||
pub fn init(allocator: Allocator, free_list_max: u16, retain_bytes: usize) ArenaPool {
|
||||
return .{
|
||||
.allocator = allocator,
|
||||
.free_list_max = 512, // TODO make configurable
|
||||
.retain_bytes = 1024 * 16, // TODO make configurable
|
||||
.entry_pool = std.heap.MemoryPool(Entry).init(allocator),
|
||||
.free_list_max = free_list_max,
|
||||
.retain_bytes = retain_bytes,
|
||||
.entry_pool = .init(allocator),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -99,3 +99,114 @@ pub fn reset(_: *const ArenaPool, allocator: Allocator, retain: usize) void {
|
||||
const arena: *std.heap.ArenaAllocator = @ptrCast(@alignCast(allocator.ptr));
|
||||
_ = arena.reset(.{ .retain_with_limit = retain });
|
||||
}
|
||||
|
||||
const testing = std.testing;
|
||||
|
||||
test "arena pool - basic acquire and use" {
|
||||
var pool = ArenaPool.init(testing.allocator, 512, 1024 * 16);
|
||||
defer pool.deinit();
|
||||
|
||||
const alloc = try pool.acquire();
|
||||
const buf = try alloc.alloc(u8, 64);
|
||||
@memset(buf, 0xAB);
|
||||
try testing.expectEqual(@as(u8, 0xAB), buf[0]);
|
||||
|
||||
pool.release(alloc);
|
||||
}
|
||||
|
||||
test "arena pool - reuse entry after release" {
|
||||
var pool = ArenaPool.init(testing.allocator, 512, 1024 * 16);
|
||||
defer pool.deinit();
|
||||
|
||||
const alloc1 = try pool.acquire();
|
||||
try testing.expectEqual(@as(u16, 0), pool.free_list_len);
|
||||
|
||||
pool.release(alloc1);
|
||||
try testing.expectEqual(@as(u16, 1), pool.free_list_len);
|
||||
|
||||
// The same entry should be returned from the free list.
|
||||
const alloc2 = try pool.acquire();
|
||||
try testing.expectEqual(@as(u16, 0), pool.free_list_len);
|
||||
try testing.expectEqual(alloc1.ptr, alloc2.ptr);
|
||||
|
||||
pool.release(alloc2);
|
||||
}
|
||||
|
||||
test "arena pool - multiple concurrent arenas" {
|
||||
var pool = ArenaPool.init(testing.allocator, 512, 1024 * 16);
|
||||
defer pool.deinit();
|
||||
|
||||
const a1 = try pool.acquire();
|
||||
const a2 = try pool.acquire();
|
||||
const a3 = try pool.acquire();
|
||||
|
||||
// All three must be distinct arenas.
|
||||
try testing.expect(a1.ptr != a2.ptr);
|
||||
try testing.expect(a2.ptr != a3.ptr);
|
||||
try testing.expect(a1.ptr != a3.ptr);
|
||||
|
||||
_ = try a1.alloc(u8, 16);
|
||||
_ = try a2.alloc(u8, 32);
|
||||
_ = try a3.alloc(u8, 48);
|
||||
|
||||
pool.release(a1);
|
||||
pool.release(a2);
|
||||
pool.release(a3);
|
||||
|
||||
try testing.expectEqual(@as(u16, 3), pool.free_list_len);
|
||||
}
|
||||
|
||||
test "arena pool - free list respects max limit" {
|
||||
// Cap the free list at 1 so the second release discards its arena.
|
||||
var pool = ArenaPool.init(testing.allocator, 1, 1024 * 16);
|
||||
defer pool.deinit();
|
||||
|
||||
const a1 = try pool.acquire();
|
||||
const a2 = try pool.acquire();
|
||||
|
||||
pool.release(a1);
|
||||
try testing.expectEqual(@as(u16, 1), pool.free_list_len);
|
||||
|
||||
// The free list is full; a2's arena should be destroyed, not queued.
|
||||
pool.release(a2);
|
||||
try testing.expectEqual(@as(u16, 1), pool.free_list_len);
|
||||
}
|
||||
|
||||
test "arena pool - reset clears memory without releasing" {
|
||||
var pool = ArenaPool.init(testing.allocator, 512, 1024 * 16);
|
||||
defer pool.deinit();
|
||||
|
||||
const alloc = try pool.acquire();
|
||||
|
||||
const buf = try alloc.alloc(u8, 128);
|
||||
@memset(buf, 0xFF);
|
||||
|
||||
// reset() frees arena memory but keeps the allocator in-flight.
|
||||
pool.reset(alloc, 0);
|
||||
|
||||
// The free list must stay empty; the allocator was not released.
|
||||
try testing.expectEqual(@as(u16, 0), pool.free_list_len);
|
||||
|
||||
// Allocating again through the same arena must still work.
|
||||
const buf2 = try alloc.alloc(u8, 64);
|
||||
@memset(buf2, 0x00);
|
||||
try testing.expectEqual(@as(u8, 0x00), buf2[0]);
|
||||
|
||||
pool.release(alloc);
|
||||
}
|
||||
|
||||
test "arena pool - deinit with entries in free list" {
|
||||
// Verifies that deinit properly cleans up free-listed arenas (no leaks
|
||||
// detected by the test allocator).
|
||||
var pool = ArenaPool.init(testing.allocator, 512, 1024 * 16);
|
||||
|
||||
const a1 = try pool.acquire();
|
||||
const a2 = try pool.acquire();
|
||||
_ = try a1.alloc(u8, 256);
|
||||
_ = try a2.alloc(u8, 512);
|
||||
pool.release(a1);
|
||||
pool.release(a2);
|
||||
try testing.expectEqual(@as(u16, 2), pool.free_list_len);
|
||||
|
||||
pool.deinit();
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ pub const RunMode = enum {
|
||||
fetch,
|
||||
serve,
|
||||
version,
|
||||
mcp,
|
||||
};
|
||||
|
||||
pub const CDP_MAX_HTTP_REQUEST_SIZE = 4096;
|
||||
@@ -59,56 +60,56 @@ pub fn deinit(self: *const Config, allocator: Allocator) void {
|
||||
|
||||
pub fn tlsVerifyHost(self: *const Config) bool {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch => |opts| opts.common.tls_verify_host,
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.tls_verify_host,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn obeyRobots(self: *const Config) bool {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch => |opts| opts.common.obey_robots,
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.obey_robots,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn httpProxy(self: *const Config) ?[:0]const u8 {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch => |opts| opts.common.http_proxy,
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.http_proxy,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn proxyBearerToken(self: *const Config) ?[:0]const u8 {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch => |opts| opts.common.proxy_bearer_token,
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.proxy_bearer_token,
|
||||
.help, .version => null,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn httpMaxConcurrent(self: *const Config) u8 {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch => |opts| opts.common.http_max_concurrent orelse 10,
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.http_max_concurrent orelse 10,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn httpMaxHostOpen(self: *const Config) u8 {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch => |opts| opts.common.http_max_host_open orelse 4,
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.http_max_host_open orelse 4,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn httpConnectTimeout(self: *const Config) u31 {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch => |opts| opts.common.http_connect_timeout orelse 0,
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.http_connect_timeout orelse 0,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn httpTimeout(self: *const Config) u31 {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch => |opts| opts.common.http_timeout orelse 5000,
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.http_timeout orelse 5000,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
@@ -119,35 +120,35 @@ pub fn httpMaxRedirects(_: *const Config) u8 {
|
||||
|
||||
pub fn httpMaxResponseSize(self: *const Config) ?usize {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch => |opts| opts.common.http_max_response_size,
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.http_max_response_size,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn logLevel(self: *const Config) ?log.Level {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch => |opts| opts.common.log_level,
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.log_level,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn logFormat(self: *const Config) ?log.Format {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch => |opts| opts.common.log_format,
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.log_format,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn logFilterScopes(self: *const Config) ?[]const log.Scope {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch => |opts| opts.common.log_filter_scopes,
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.log_filter_scopes,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn userAgentSuffix(self: *const Config) ?[]const u8 {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch => |opts| opts.common.user_agent_suffix,
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.user_agent_suffix,
|
||||
.help, .version => null,
|
||||
};
|
||||
}
|
||||
@@ -171,6 +172,7 @@ pub const Mode = union(RunMode) {
|
||||
fetch: Fetch,
|
||||
serve: Serve,
|
||||
version: void,
|
||||
mcp: Mcp,
|
||||
};
|
||||
|
||||
pub const Serve = struct {
|
||||
@@ -182,16 +184,22 @@ pub const Serve = struct {
|
||||
common: Common = .{},
|
||||
};
|
||||
|
||||
pub const Mcp = struct {
|
||||
common: Common = .{},
|
||||
};
|
||||
|
||||
pub const DumpFormat = enum {
|
||||
html,
|
||||
markdown,
|
||||
wpt,
|
||||
};
|
||||
|
||||
pub const Fetch = struct {
|
||||
url: [:0]const u8,
|
||||
dump_mode: ?DumpFormat = null,
|
||||
common: Common = .{},
|
||||
withbase: bool = false,
|
||||
with_base: bool = false,
|
||||
with_frames: bool = false,
|
||||
strip: dump.Opts.Strip = .{},
|
||||
};
|
||||
|
||||
@@ -322,7 +330,7 @@ pub fn printUsageAndExit(self: *const Config, success: bool) void {
|
||||
const usage =
|
||||
\\usage: {s} command [options] [URL]
|
||||
\\
|
||||
\\Command can be either 'fetch', 'serve' or 'help'
|
||||
\\Command can be either 'fetch', 'serve', 'mcp' or 'help'
|
||||
\\
|
||||
\\fetch command
|
||||
\\Fetches the specified URL
|
||||
@@ -342,6 +350,8 @@ pub fn printUsageAndExit(self: *const Config, success: bool) void {
|
||||
\\
|
||||
\\--with_base Add a <base> tag in dump. Defaults to false.
|
||||
\\
|
||||
\\--with_frames Includes the contents of iframes. Defaults to false.
|
||||
\\
|
||||
++ common_options ++
|
||||
\\
|
||||
\\serve command
|
||||
@@ -366,6 +376,12 @@ pub fn printUsageAndExit(self: *const Config, success: bool) void {
|
||||
\\ Maximum pending connections in the accept queue.
|
||||
\\ Defaults to 128.
|
||||
\\
|
||||
++ common_options ++
|
||||
\\
|
||||
\\mcp command
|
||||
\\Starts an MCP (Model Context Protocol) server over stdio
|
||||
\\Example: {s} mcp
|
||||
\\
|
||||
++ common_options ++
|
||||
\\
|
||||
\\version command
|
||||
@@ -375,7 +391,7 @@ pub fn printUsageAndExit(self: *const Config, success: bool) void {
|
||||
\\Displays this message
|
||||
\\
|
||||
;
|
||||
std.debug.print(usage, .{ self.exec_name, self.exec_name, self.exec_name, self.exec_name });
|
||||
std.debug.print(usage, .{ self.exec_name, self.exec_name, self.exec_name, self.exec_name, self.exec_name });
|
||||
if (success) {
|
||||
return std.process.cleanExit();
|
||||
}
|
||||
@@ -410,6 +426,8 @@ pub fn parseArgs(allocator: Allocator) !Config {
|
||||
return init(allocator, exec_name, .{ .help = false }) },
|
||||
.fetch => .{ .fetch = parseFetchArgs(allocator, &args) catch
|
||||
return init(allocator, exec_name, .{ .help = false }) },
|
||||
.mcp => .{ .mcp = parseMcpArgs(allocator, &args) catch
|
||||
return init(allocator, exec_name, .{ .help = false }) },
|
||||
.version => .{ .version = {} },
|
||||
};
|
||||
return init(allocator, exec_name, mode);
|
||||
@@ -440,6 +458,10 @@ fn inferMode(opt: []const u8) ?RunMode {
|
||||
return .fetch;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, opt, "--with_frames")) {
|
||||
return .fetch;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, opt, "--host")) {
|
||||
return .serve;
|
||||
}
|
||||
@@ -534,12 +556,31 @@ fn parseServeArgs(
|
||||
return serve;
|
||||
}
|
||||
|
||||
fn parseMcpArgs(
|
||||
allocator: Allocator,
|
||||
args: *std.process.ArgIterator,
|
||||
) !Mcp {
|
||||
var mcp: Mcp = .{};
|
||||
|
||||
while (args.next()) |opt| {
|
||||
if (try parseCommonArg(allocator, opt, args, &mcp.common)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
log.fatal(.mcp, "unknown argument", .{ .mode = "mcp", .arg = opt });
|
||||
return error.UnkownOption;
|
||||
}
|
||||
|
||||
return mcp;
|
||||
}
|
||||
|
||||
fn parseFetchArgs(
|
||||
allocator: Allocator,
|
||||
args: *std.process.ArgIterator,
|
||||
) !Fetch {
|
||||
var dump_mode: ?DumpFormat = null;
|
||||
var withbase: bool = false;
|
||||
var with_base: bool = false;
|
||||
var with_frames: bool = false;
|
||||
var url: ?[:0]const u8 = null;
|
||||
var common: Common = .{};
|
||||
var strip: dump.Opts.Strip = .{};
|
||||
@@ -570,7 +611,12 @@ fn parseFetchArgs(
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--with_base", opt)) {
|
||||
withbase = true;
|
||||
with_base = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--with_frames", opt)) {
|
||||
with_frames = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -626,7 +672,8 @@ fn parseFetchArgs(
|
||||
.dump_mode = dump_mode,
|
||||
.strip = strip,
|
||||
.common = common,
|
||||
.withbase = withbase,
|
||||
.with_base = with_base,
|
||||
.with_frames = with_frames,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
1707
src/Net.zig
Normal file
1707
src/Net.zig
Normal file
File diff suppressed because it is too large
Load Diff
@@ -73,6 +73,7 @@ const EventListeners = struct {
|
||||
page_navigated: List = .{},
|
||||
page_network_idle: List = .{},
|
||||
page_network_almost_idle: List = .{},
|
||||
page_frame_created: List = .{},
|
||||
http_request_fail: List = .{},
|
||||
http_request_start: List = .{},
|
||||
http_request_intercept: List = .{},
|
||||
@@ -89,6 +90,7 @@ const Events = union(enum) {
|
||||
page_navigated: *const PageNavigated,
|
||||
page_network_idle: *const PageNetworkIdle,
|
||||
page_network_almost_idle: *const PageNetworkAlmostIdle,
|
||||
page_frame_created: *const PageFrameCreated,
|
||||
http_request_fail: *const RequestFail,
|
||||
http_request_start: *const RequestStart,
|
||||
http_request_intercept: *const RequestIntercept,
|
||||
@@ -102,24 +104,36 @@ const EventType = std.meta.FieldEnum(Events);
|
||||
pub const PageRemove = struct {};
|
||||
|
||||
pub const PageNavigate = struct {
|
||||
req_id: usize,
|
||||
req_id: u32,
|
||||
frame_id: u32,
|
||||
timestamp: u64,
|
||||
url: [:0]const u8,
|
||||
opts: Page.NavigateOpts,
|
||||
};
|
||||
|
||||
pub const PageNavigated = struct {
|
||||
req_id: usize,
|
||||
req_id: u32,
|
||||
frame_id: u32,
|
||||
timestamp: u64,
|
||||
url: [:0]const u8,
|
||||
opts: Page.NavigatedOpts,
|
||||
};
|
||||
|
||||
pub const PageNetworkIdle = struct {
|
||||
req_id: u32,
|
||||
frame_id: u32,
|
||||
timestamp: u64,
|
||||
};
|
||||
|
||||
pub const PageNetworkAlmostIdle = struct {
|
||||
req_id: u32,
|
||||
frame_id: u32,
|
||||
timestamp: u64,
|
||||
};
|
||||
|
||||
pub const PageFrameCreated = struct {
|
||||
frame_id: u32,
|
||||
parent_id: u32,
|
||||
timestamp: u64,
|
||||
};
|
||||
|
||||
@@ -305,6 +319,7 @@ test "Notification" {
|
||||
|
||||
// noop
|
||||
notifier.dispatch(.page_navigate, &.{
|
||||
.frame_id = 0,
|
||||
.req_id = 1,
|
||||
.timestamp = 4,
|
||||
.url = undefined,
|
||||
@@ -315,6 +330,7 @@ test "Notification" {
|
||||
|
||||
try notifier.register(.page_navigate, &tc, TestClient.pageNavigate);
|
||||
notifier.dispatch(.page_navigate, &.{
|
||||
.frame_id = 0,
|
||||
.req_id = 1,
|
||||
.timestamp = 4,
|
||||
.url = undefined,
|
||||
@@ -324,6 +340,7 @@ test "Notification" {
|
||||
|
||||
notifier.unregisterAll(&tc);
|
||||
notifier.dispatch(.page_navigate, &.{
|
||||
.frame_id = 0,
|
||||
.req_id = 1,
|
||||
.timestamp = 10,
|
||||
.url = undefined,
|
||||
@@ -334,23 +351,25 @@ test "Notification" {
|
||||
try notifier.register(.page_navigate, &tc, TestClient.pageNavigate);
|
||||
try notifier.register(.page_navigated, &tc, TestClient.pageNavigated);
|
||||
notifier.dispatch(.page_navigate, &.{
|
||||
.frame_id = 0,
|
||||
.req_id = 1,
|
||||
.timestamp = 10,
|
||||
.url = undefined,
|
||||
.opts = .{},
|
||||
});
|
||||
notifier.dispatch(.page_navigated, &.{ .req_id = 1, .timestamp = 6, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .frame_id = 0, .req_id = 1, .timestamp = 6, .url = undefined, .opts = .{} });
|
||||
try testing.expectEqual(14, tc.page_navigate);
|
||||
try testing.expectEqual(6, tc.page_navigated);
|
||||
|
||||
notifier.unregisterAll(&tc);
|
||||
notifier.dispatch(.page_navigate, &.{
|
||||
.frame_id = 0,
|
||||
.req_id = 1,
|
||||
.timestamp = 100,
|
||||
.url = undefined,
|
||||
.opts = .{},
|
||||
});
|
||||
notifier.dispatch(.page_navigated, &.{ .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .frame_id = 0, .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
try testing.expectEqual(14, tc.page_navigate);
|
||||
try testing.expectEqual(6, tc.page_navigated);
|
||||
|
||||
@@ -358,27 +377,27 @@ test "Notification" {
|
||||
// unregister
|
||||
try notifier.register(.page_navigate, &tc, TestClient.pageNavigate);
|
||||
try notifier.register(.page_navigated, &tc, TestClient.pageNavigated);
|
||||
notifier.dispatch(.page_navigate, &.{ .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .req_id = 1, .timestamp = 1000, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigate, &.{ .frame_id = 0, .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .frame_id = 0, .req_id = 1, .timestamp = 1000, .url = undefined, .opts = .{} });
|
||||
try testing.expectEqual(114, tc.page_navigate);
|
||||
try testing.expectEqual(1006, tc.page_navigated);
|
||||
|
||||
notifier.unregister(.page_navigate, &tc);
|
||||
notifier.dispatch(.page_navigate, &.{ .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .req_id = 1, .timestamp = 1000, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigate, &.{ .frame_id = 0, .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .frame_id = 0, .req_id = 1, .timestamp = 1000, .url = undefined, .opts = .{} });
|
||||
try testing.expectEqual(114, tc.page_navigate);
|
||||
try testing.expectEqual(2006, tc.page_navigated);
|
||||
|
||||
notifier.unregister(.page_navigated, &tc);
|
||||
notifier.dispatch(.page_navigate, &.{ .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .req_id = 1, .timestamp = 1000, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigate, &.{ .frame_id = 0, .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .frame_id = 0, .req_id = 1, .timestamp = 1000, .url = undefined, .opts = .{} });
|
||||
try testing.expectEqual(114, tc.page_navigate);
|
||||
try testing.expectEqual(2006, tc.page_navigated);
|
||||
|
||||
// already unregistered, try anyways
|
||||
notifier.unregister(.page_navigated, &tc);
|
||||
notifier.dispatch(.page_navigate, &.{ .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .req_id = 1, .timestamp = 1000, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigate, &.{ .frame_id = 0, .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .frame_id = 0, .req_id = 1, .timestamp = 1000, .url = undefined, .opts = .{} });
|
||||
try testing.expectEqual(114, tc.page_navigate);
|
||||
try testing.expectEqual(2006, tc.page_navigated);
|
||||
}
|
||||
|
||||
781
src/Server.zig
781
src/Server.zig
@@ -30,6 +30,7 @@ const log = @import("log.zig");
|
||||
const App = @import("App.zig");
|
||||
const Config = @import("Config.zig");
|
||||
const CDP = @import("cdp/cdp.zig").CDP;
|
||||
const Net = @import("Net.zig");
|
||||
const Http = @import("http/Http.zig");
|
||||
const HttpClient = @import("http/Client.zig");
|
||||
|
||||
@@ -120,26 +121,52 @@ pub fn run(self: *Server, address: net.Address, timeout_ms: u32) !void {
|
||||
try posix.listen(listener, self.app.config.maxPendingConnections());
|
||||
|
||||
log.info(.app, "server running", .{ .address = address });
|
||||
while (!self.shutdown.load(.acquire)) {
|
||||
const socket = posix.accept(listener, null, null, posix.SOCK.NONBLOCK) catch |err| {
|
||||
switch (err) {
|
||||
error.SocketNotListening, error.ConnectionAborted => {
|
||||
log.info(.app, "server stopped", .{});
|
||||
break;
|
||||
},
|
||||
error.WouldBlock => {
|
||||
std.Thread.sleep(10 * std.time.ns_per_ms);
|
||||
continue;
|
||||
},
|
||||
else => {
|
||||
log.err(.app, "CDP accept", .{ .err = err });
|
||||
std.Thread.sleep(std.time.ns_per_s);
|
||||
continue;
|
||||
},
|
||||
}
|
||||
|
||||
var runtime = try Net.Runtime.init(self.allocator);
|
||||
defer runtime.deinit();
|
||||
|
||||
var accept_ctx: AcceptCtx = .{
|
||||
.server = self,
|
||||
.timeout_ms = timeout_ms,
|
||||
};
|
||||
|
||||
try runtime.add(listener, Net.Runtime.READABLE, &accept_ctx, onListenerEvent);
|
||||
defer runtime.remove(listener);
|
||||
|
||||
runtime.run(self, shouldStopRuntime) catch |err| {
|
||||
return err;
|
||||
};
|
||||
|
||||
log.info(.app, "server stopped", .{});
|
||||
}
|
||||
|
||||
const AcceptCtx = struct {
|
||||
server: *Server,
|
||||
timeout_ms: u32,
|
||||
};
|
||||
|
||||
fn shouldStopRuntime(ctx: *anyopaque) bool {
|
||||
const self: *Server = @ptrCast(@alignCast(ctx));
|
||||
return self.shutdown.load(.acquire);
|
||||
}
|
||||
|
||||
fn onListenerEvent(ctx: *anyopaque, event: Net.RuntimeEvent) !void {
|
||||
_ = event;
|
||||
const accept_ctx: *AcceptCtx = @ptrCast(@alignCast(ctx));
|
||||
const self = accept_ctx.server;
|
||||
const listener = self.listener orelse return;
|
||||
|
||||
while (true) {
|
||||
const socket = posix.accept(listener, null, null, posix.SOCK.NONBLOCK) catch |err| switch (err) {
|
||||
error.WouldBlock => return,
|
||||
error.SocketNotListening, error.ConnectionAborted => return,
|
||||
else => {
|
||||
log.err(.app, "CDP accept", .{ .err = err });
|
||||
return;
|
||||
},
|
||||
};
|
||||
|
||||
self.spawnWorker(socket, timeout_ms) catch |err| {
|
||||
self.spawnWorker(socket, accept_ctx.timeout_ms) catch |err| {
|
||||
log.err(.app, "CDP spawn", .{ .err = err });
|
||||
posix.close(socket);
|
||||
};
|
||||
@@ -265,21 +292,7 @@ pub const Client = struct {
|
||||
allocator: Allocator,
|
||||
app: *App,
|
||||
http: *HttpClient,
|
||||
json_version_response: []const u8,
|
||||
reader: Reader(true),
|
||||
socket: posix.socket_t,
|
||||
socket_flags: usize,
|
||||
send_arena: ArenaAllocator,
|
||||
timeout_ms: u32,
|
||||
|
||||
const EMPTY_PONG = [_]u8{ 138, 0 };
|
||||
|
||||
// CLOSE, 2 length, code
|
||||
const CLOSE_NORMAL = [_]u8{ 136, 2, 3, 232 }; // code: 1000
|
||||
const CLOSE_TOO_BIG = [_]u8{ 136, 2, 3, 241 }; // 1009
|
||||
const CLOSE_PROTOCOL_ERROR = [_]u8{ 136, 2, 3, 234 }; //code: 1002
|
||||
// "private-use" close codes must be from 4000-49999
|
||||
const CLOSE_TIMEOUT = [_]u8{ 136, 2, 15, 160 }; // code: 4000
|
||||
ws: Net.WsConnection,
|
||||
|
||||
fn init(
|
||||
socket: posix.socket_t,
|
||||
@@ -288,40 +301,32 @@ pub const Client = struct {
|
||||
json_version_response: []const u8,
|
||||
timeout_ms: u32,
|
||||
) !Client {
|
||||
var ws = try Net.WsConnection.init(socket, allocator, json_version_response, timeout_ms);
|
||||
errdefer ws.deinit();
|
||||
|
||||
if (log.enabled(.app, .info)) {
|
||||
var client_address: std.net.Address = undefined;
|
||||
var socklen: posix.socklen_t = @sizeOf(net.Address);
|
||||
try std.posix.getsockname(socket, &client_address.any, &socklen);
|
||||
const client_address = ws.getAddress() catch null;
|
||||
log.info(.app, "client connected", .{ .ip = client_address });
|
||||
}
|
||||
|
||||
const socket_flags = try posix.fcntl(socket, posix.F.GETFL, 0);
|
||||
const nonblocking = @as(u32, @bitCast(posix.O{ .NONBLOCK = true }));
|
||||
// we expect the socket to come to us as nonblocking
|
||||
lp.assert(socket_flags & nonblocking == nonblocking, "Client.init blocking", .{});
|
||||
|
||||
var reader = try Reader(true).init(allocator);
|
||||
errdefer reader.deinit();
|
||||
|
||||
const http = try app.http.createClient(allocator);
|
||||
errdefer http.deinit();
|
||||
|
||||
return .{
|
||||
.socket = socket,
|
||||
.allocator = allocator,
|
||||
.app = app,
|
||||
.http = http,
|
||||
.json_version_response = json_version_response,
|
||||
.reader = reader,
|
||||
.ws = ws,
|
||||
.mode = .{ .http = {} },
|
||||
.socket_flags = socket_flags,
|
||||
.send_arena = ArenaAllocator.init(allocator),
|
||||
.timeout_ms = timeout_ms,
|
||||
};
|
||||
}
|
||||
|
||||
fn stop(self: *Client) void {
|
||||
posix.shutdown(self.socket, .recv) catch {};
|
||||
switch (self.mode) {
|
||||
.http => {},
|
||||
.cdp => |*cdp| cdp.browser.env.terminate(),
|
||||
}
|
||||
self.ws.shutdown();
|
||||
}
|
||||
|
||||
fn deinit(self: *Client) void {
|
||||
@@ -329,15 +334,14 @@ pub const Client = struct {
|
||||
.cdp => |*cdp| cdp.deinit(),
|
||||
.http => {},
|
||||
}
|
||||
self.reader.deinit();
|
||||
self.send_arena.deinit();
|
||||
self.ws.deinit();
|
||||
self.http.deinit();
|
||||
}
|
||||
|
||||
fn start(self: *Client) void {
|
||||
const http = self.http;
|
||||
http.cdp_client = .{
|
||||
.socket = self.socket,
|
||||
.socket = self.ws.socket,
|
||||
.ctx = self,
|
||||
.blocking_read_start = Client.blockingReadStart,
|
||||
.blocking_read = Client.blockingRead,
|
||||
@@ -352,8 +356,9 @@ pub const Client = struct {
|
||||
|
||||
fn httpLoop(self: *Client, http: *HttpClient) !void {
|
||||
lp.assert(self.mode == .http, "Client.httpLoop invalid mode", .{});
|
||||
|
||||
while (true) {
|
||||
const status = http.tick(self.timeout_ms) catch |err| {
|
||||
const status = http.tick(self.ws.timeout_ms) catch |err| {
|
||||
log.err(.app, "http tick", .{ .err = err });
|
||||
return;
|
||||
};
|
||||
@@ -371,13 +376,9 @@ pub const Client = struct {
|
||||
}
|
||||
}
|
||||
|
||||
return self.cdpLoop(http);
|
||||
}
|
||||
|
||||
fn cdpLoop(self: *Client, http: *HttpClient) !void {
|
||||
var cdp = &self.mode.cdp;
|
||||
var last_message = timestamp(.monotonic);
|
||||
var ms_remaining = self.timeout_ms;
|
||||
var ms_remaining = self.ws.timeout_ms;
|
||||
|
||||
while (true) {
|
||||
switch (cdp.pageWait(ms_remaining)) {
|
||||
@@ -386,7 +387,7 @@ pub const Client = struct {
|
||||
return;
|
||||
}
|
||||
last_message = timestamp(.monotonic);
|
||||
ms_remaining = self.timeout_ms;
|
||||
ms_remaining = self.ws.timeout_ms;
|
||||
},
|
||||
.no_page => {
|
||||
const status = http.tick(ms_remaining) catch |err| {
|
||||
@@ -401,7 +402,7 @@ pub const Client = struct {
|
||||
return;
|
||||
}
|
||||
last_message = timestamp(.monotonic);
|
||||
ms_remaining = self.timeout_ms;
|
||||
ms_remaining = self.ws.timeout_ms;
|
||||
},
|
||||
.done => {
|
||||
const elapsed = timestamp(.monotonic) - last_message;
|
||||
@@ -417,7 +418,7 @@ pub const Client = struct {
|
||||
|
||||
fn blockingReadStart(ctx: *anyopaque) bool {
|
||||
const self: *Client = @ptrCast(@alignCast(ctx));
|
||||
_ = posix.fcntl(self.socket, posix.F.SETFL, self.socket_flags & ~@as(u32, @bitCast(posix.O{ .NONBLOCK = true }))) catch |err| {
|
||||
self.ws.setBlocking(true) catch |err| {
|
||||
log.warn(.app, "CDP blockingReadStart", .{ .err = err });
|
||||
return false;
|
||||
};
|
||||
@@ -431,7 +432,7 @@ pub const Client = struct {
|
||||
|
||||
fn blockingReadStop(ctx: *anyopaque) bool {
|
||||
const self: *Client = @ptrCast(@alignCast(ctx));
|
||||
_ = posix.fcntl(self.socket, posix.F.SETFL, self.socket_flags) catch |err| {
|
||||
self.ws.setBlocking(false) catch |err| {
|
||||
log.warn(.app, "CDP blockingReadStop", .{ .err = err });
|
||||
return false;
|
||||
};
|
||||
@@ -439,7 +440,7 @@ pub const Client = struct {
|
||||
}
|
||||
|
||||
fn readSocket(self: *Client) bool {
|
||||
const n = posix.read(self.socket, self.readBuf()) catch |err| {
|
||||
const n = self.ws.read() catch |err| {
|
||||
log.warn(.app, "CDP read", .{ .err = err });
|
||||
return false;
|
||||
};
|
||||
@@ -449,16 +450,10 @@ pub const Client = struct {
|
||||
return false;
|
||||
}
|
||||
|
||||
return self.processData(n) catch false;
|
||||
return self.processData() catch false;
|
||||
}
|
||||
|
||||
fn readBuf(self: *Client) []u8 {
|
||||
return self.reader.readBuf();
|
||||
}
|
||||
|
||||
fn processData(self: *Client, len: usize) !bool {
|
||||
self.reader.len += len;
|
||||
|
||||
fn processData(self: *Client) !bool {
|
||||
switch (self.mode) {
|
||||
.cdp => |*cdp| return self.processWebsocketMessage(cdp),
|
||||
.http => return self.processHTTPRequest(),
|
||||
@@ -466,8 +461,8 @@ pub const Client = struct {
|
||||
}
|
||||
|
||||
fn processHTTPRequest(self: *Client) !bool {
|
||||
lp.assert(self.reader.pos == 0, "Client.HTTP pos", .{ .pos = self.reader.pos });
|
||||
const request = self.reader.buf[0..self.reader.len];
|
||||
lp.assert(self.ws.reader.pos == 0, "Client.HTTP pos", .{ .pos = self.ws.reader.pos });
|
||||
const request = self.ws.reader.buf[0..self.ws.reader.len];
|
||||
|
||||
if (request.len > Config.CDP_MAX_HTTP_REQUEST_SIZE) {
|
||||
self.writeHTTPErrorResponse(413, "Request too large");
|
||||
@@ -481,7 +476,7 @@ pub const Client = struct {
|
||||
}
|
||||
|
||||
// the next incoming data can go to the front of our buffer
|
||||
defer self.reader.len = 0;
|
||||
defer self.ws.reader.len = 0;
|
||||
return self.handleHTTPRequest(request) catch |err| {
|
||||
switch (err) {
|
||||
error.NotFound => self.writeHTTPErrorResponse(404, "Not found"),
|
||||
@@ -521,15 +516,15 @@ pub const Client = struct {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, url, "/json/version")) {
|
||||
try self.send(self.json_version_response);
|
||||
if (std.mem.eql(u8, url, "/json/version") or std.mem.eql(u8, url, "/json/version/")) {
|
||||
try self.ws.send(self.ws.json_version_response);
|
||||
// Chromedp (a Go driver) does an http request to /json/version
|
||||
// then to / (websocket upgrade) using a different connection.
|
||||
// Since we only allow 1 connection at a time, the 2nd one (the
|
||||
// websocket upgrade) blocks until the first one times out.
|
||||
// We can avoid that by closing the connection. json_version_response
|
||||
// has a Connection: Close header too.
|
||||
try posix.shutdown(self.socket, .recv);
|
||||
self.ws.shutdown();
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -537,581 +532,31 @@ pub const Client = struct {
|
||||
}
|
||||
|
||||
fn upgradeConnection(self: *Client, request: []u8) !void {
|
||||
// our caller already confirmed that we have a trailing \r\n\r\n
|
||||
const request_line_end = std.mem.indexOfScalar(u8, request, '\r') orelse unreachable;
|
||||
const request_line = request[0..request_line_end];
|
||||
|
||||
if (!std.ascii.endsWithIgnoreCase(request_line, "http/1.1")) {
|
||||
return error.InvalidProtocol;
|
||||
}
|
||||
|
||||
// we need to extract the sec-websocket-key value
|
||||
var key: []const u8 = "";
|
||||
|
||||
// we need to make sure that we got all the necessary headers + values
|
||||
var required_headers: u8 = 0;
|
||||
|
||||
// can't std.mem.split because it forces the iterated value to be const
|
||||
// (we could @constCast...)
|
||||
|
||||
var buf = request[request_line_end + 2 ..];
|
||||
|
||||
while (buf.len > 4) {
|
||||
const index = std.mem.indexOfScalar(u8, buf, '\r') orelse unreachable;
|
||||
const separator = std.mem.indexOfScalar(u8, buf[0..index], ':') orelse return error.InvalidRequest;
|
||||
|
||||
const name = std.mem.trim(u8, toLower(buf[0..separator]), &std.ascii.whitespace);
|
||||
const value = std.mem.trim(u8, buf[(separator + 1)..index], &std.ascii.whitespace);
|
||||
|
||||
if (std.mem.eql(u8, name, "upgrade")) {
|
||||
if (!std.ascii.eqlIgnoreCase("websocket", value)) {
|
||||
return error.InvalidUpgradeHeader;
|
||||
}
|
||||
required_headers |= 1;
|
||||
} else if (std.mem.eql(u8, name, "sec-websocket-version")) {
|
||||
if (value.len != 2 or value[0] != '1' or value[1] != '3') {
|
||||
return error.InvalidVersionHeader;
|
||||
}
|
||||
required_headers |= 2;
|
||||
} else if (std.mem.eql(u8, name, "connection")) {
|
||||
// find if connection header has upgrade in it, example header:
|
||||
// Connection: keep-alive, Upgrade
|
||||
if (std.ascii.indexOfIgnoreCase(value, "upgrade") == null) {
|
||||
return error.InvalidConnectionHeader;
|
||||
}
|
||||
required_headers |= 4;
|
||||
} else if (std.mem.eql(u8, name, "sec-websocket-key")) {
|
||||
key = value;
|
||||
required_headers |= 8;
|
||||
}
|
||||
|
||||
const next = index + 2;
|
||||
buf = buf[next..];
|
||||
}
|
||||
|
||||
if (required_headers != 15) {
|
||||
return error.MissingHeaders;
|
||||
}
|
||||
|
||||
// our caller has already made sure this request ended in \r\n\r\n
|
||||
// so it isn't something we need to check again
|
||||
|
||||
const allocator = self.send_arena.allocator();
|
||||
|
||||
const response = blk: {
|
||||
// Response to an ugprade request is always this, with
|
||||
// the Sec-Websocket-Accept value a spacial sha1 hash of the
|
||||
// request "sec-websocket-version" and a magic value.
|
||||
|
||||
const template =
|
||||
"HTTP/1.1 101 Switching Protocols\r\n" ++
|
||||
"Upgrade: websocket\r\n" ++
|
||||
"Connection: upgrade\r\n" ++
|
||||
"Sec-Websocket-Accept: 0000000000000000000000000000\r\n\r\n";
|
||||
|
||||
// The response will be sent via the IO Loop and thus has to have its
|
||||
// own lifetime.
|
||||
const res = try allocator.dupe(u8, template);
|
||||
|
||||
// magic response
|
||||
const key_pos = res.len - 32;
|
||||
var h: [20]u8 = undefined;
|
||||
var hasher = std.crypto.hash.Sha1.init(.{});
|
||||
hasher.update(key);
|
||||
// websocket spec always used this value
|
||||
hasher.update("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
|
||||
hasher.final(&h);
|
||||
|
||||
_ = std.base64.standard.Encoder.encode(res[key_pos .. key_pos + 28], h[0..]);
|
||||
|
||||
break :blk res;
|
||||
};
|
||||
|
||||
try self.ws.upgrade(request);
|
||||
self.mode = .{ .cdp = try CDP.init(self.app, self.http, self) };
|
||||
return self.send(response);
|
||||
}
|
||||
|
||||
fn writeHTTPErrorResponse(self: *Client, comptime status: u16, comptime body: []const u8) void {
|
||||
const response = std.fmt.comptimePrint(
|
||||
"HTTP/1.1 {d} \r\nConnection: Close\r\nContent-Length: {d}\r\n\r\n{s}",
|
||||
.{ status, body.len, body },
|
||||
);
|
||||
|
||||
// we're going to close this connection anyways, swallowing any
|
||||
// error seems safe
|
||||
self.send(response) catch {};
|
||||
self.ws.sendHttpError(status, body);
|
||||
}
|
||||
|
||||
fn processWebsocketMessage(self: *Client, cdp: *CDP) !bool {
|
||||
var reader = &self.reader;
|
||||
while (true) {
|
||||
const msg = reader.next() catch |err| {
|
||||
switch (err) {
|
||||
error.TooLarge => self.send(&CLOSE_TOO_BIG) catch {},
|
||||
error.NotMasked => self.send(&CLOSE_PROTOCOL_ERROR) catch {},
|
||||
error.ReservedFlags => self.send(&CLOSE_PROTOCOL_ERROR) catch {},
|
||||
error.InvalidMessageType => self.send(&CLOSE_PROTOCOL_ERROR) catch {},
|
||||
error.ControlTooLarge => self.send(&CLOSE_PROTOCOL_ERROR) catch {},
|
||||
error.InvalidContinuation => self.send(&CLOSE_PROTOCOL_ERROR) catch {},
|
||||
error.NestedFragementation => self.send(&CLOSE_PROTOCOL_ERROR) catch {},
|
||||
error.OutOfMemory => {}, // don't borther trying to send an error in this case
|
||||
}
|
||||
return err;
|
||||
} orelse break;
|
||||
|
||||
switch (msg.type) {
|
||||
.pong => {},
|
||||
.ping => try self.sendPong(msg.data),
|
||||
.close => {
|
||||
self.send(&CLOSE_NORMAL) catch {};
|
||||
return false;
|
||||
},
|
||||
.text, .binary => if (cdp.handleMessage(msg.data) == false) {
|
||||
return false;
|
||||
},
|
||||
}
|
||||
if (msg.cleanup_fragment) {
|
||||
reader.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
// We might have read part of the next message. Our reader potentially
|
||||
// has to move data around in its buffer to make space.
|
||||
reader.compact();
|
||||
return true;
|
||||
return self.ws.processMessages(cdp);
|
||||
}
|
||||
|
||||
fn sendPong(self: *Client, data: []const u8) !void {
|
||||
if (data.len == 0) {
|
||||
return self.send(&EMPTY_PONG);
|
||||
}
|
||||
var header_buf: [10]u8 = undefined;
|
||||
const header = websocketHeader(&header_buf, .pong, data.len);
|
||||
|
||||
const allocator = self.send_arena.allocator();
|
||||
var framed = try allocator.alloc(u8, header.len + data.len);
|
||||
@memcpy(framed[0..header.len], header);
|
||||
@memcpy(framed[header.len..], data);
|
||||
return self.send(framed);
|
||||
pub fn sendAllocator(self: *Client) Allocator {
|
||||
return self.ws.send_arena.allocator();
|
||||
}
|
||||
|
||||
// called by CDP
|
||||
// Websocket frames have a variable length header. For server-client,
|
||||
// it could be anywhere from 2 to 10 bytes. Our IO.Loop doesn't have
|
||||
// writev, so we need to get creative. We'll JSON serialize to a
|
||||
// buffer, where the first 10 bytes are reserved. We can then backfill
|
||||
// the header and send the slice.
|
||||
pub fn sendJSON(self: *Client, message: anytype, opts: std.json.Stringify.Options) !void {
|
||||
const allocator = self.send_arena.allocator();
|
||||
|
||||
var aw = try std.Io.Writer.Allocating.initCapacity(allocator, 512);
|
||||
|
||||
// reserve space for the maximum possible header
|
||||
try aw.writer.writeAll(&.{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
|
||||
try std.json.Stringify.value(message, opts, &aw.writer);
|
||||
const framed = fillWebsocketHeader(aw.toArrayList());
|
||||
return self.send(framed);
|
||||
return self.ws.sendJSON(message, opts);
|
||||
}
|
||||
|
||||
pub fn sendJSONRaw(
|
||||
self: *Client,
|
||||
buf: std.ArrayList(u8),
|
||||
) !void {
|
||||
// Dangerous API!. We assume the caller has reserved the first 10
|
||||
// bytes in `buf`.
|
||||
const framed = fillWebsocketHeader(buf);
|
||||
return self.send(framed);
|
||||
}
|
||||
|
||||
fn send(self: *Client, data: []const u8) !void {
|
||||
var pos: usize = 0;
|
||||
var changed_to_blocking: bool = false;
|
||||
defer _ = self.send_arena.reset(.{ .retain_with_limit = 1024 * 32 });
|
||||
|
||||
defer if (changed_to_blocking) {
|
||||
// We had to change our socket to blocking me to get our write out
|
||||
// We need to change it back to non-blocking.
|
||||
_ = posix.fcntl(self.socket, posix.F.SETFL, self.socket_flags) catch |err| {
|
||||
log.err(.app, "CDP restore nonblocking", .{ .err = err });
|
||||
};
|
||||
};
|
||||
|
||||
LOOP: while (pos < data.len) {
|
||||
const written = posix.write(self.socket, data[pos..]) catch |err| switch (err) {
|
||||
error.WouldBlock => {
|
||||
// self.socket is nonblocking, because we don't want to block
|
||||
// reads. But our life is a lot easier if we block writes,
|
||||
// largely, because we don't have to maintain a queue of pending
|
||||
// writes (which would each need their own allocations). So
|
||||
// if we get a WouldBlock error, we'll switch the socket to
|
||||
// blocking and switch it back to non-blocking after the write
|
||||
// is complete. Doesn't seem particularly efficiently, but
|
||||
// this should virtually never happen.
|
||||
lp.assert(changed_to_blocking == false, "Client.double block", .{});
|
||||
changed_to_blocking = true;
|
||||
_ = try posix.fcntl(self.socket, posix.F.SETFL, self.socket_flags & ~@as(u32, @bitCast(posix.O{ .NONBLOCK = true })));
|
||||
continue :LOOP;
|
||||
},
|
||||
else => return err,
|
||||
};
|
||||
|
||||
if (written == 0) {
|
||||
return error.Closed;
|
||||
}
|
||||
pos += written;
|
||||
}
|
||||
pub fn sendJSONRaw(self: *Client, buf: std.ArrayList(u8)) !void {
|
||||
return self.ws.sendJSONRaw(buf);
|
||||
}
|
||||
};
|
||||
|
||||
// WebSocket message reader. Given websocket message, acts as an iterator that
|
||||
// can return zero or more Messages. When next returns null, any incomplete
|
||||
// message will remain in reader.data
|
||||
fn Reader(comptime EXPECT_MASK: bool) type {
|
||||
return struct {
|
||||
allocator: Allocator,
|
||||
|
||||
// position in buf of the start of the next message
|
||||
pos: usize = 0,
|
||||
|
||||
// position in buf up until where we have valid data
|
||||
// (any new reads must be placed after this)
|
||||
len: usize = 0,
|
||||
|
||||
// we add 140 to allow 1 control message (ping/pong/close) to be
|
||||
// fragmented into a normal message.
|
||||
buf: []u8,
|
||||
|
||||
fragments: ?Fragments = null,
|
||||
|
||||
const Self = @This();
|
||||
|
||||
fn init(allocator: Allocator) !Self {
|
||||
const buf = try allocator.alloc(u8, 16 * 1024);
|
||||
return .{
|
||||
.buf = buf,
|
||||
.allocator = allocator,
|
||||
};
|
||||
}
|
||||
|
||||
fn deinit(self: *Self) void {
|
||||
self.cleanup();
|
||||
self.allocator.free(self.buf);
|
||||
}
|
||||
|
||||
fn cleanup(self: *Self) void {
|
||||
if (self.fragments) |*f| {
|
||||
f.message.deinit(self.allocator);
|
||||
self.fragments = null;
|
||||
}
|
||||
}
|
||||
|
||||
fn readBuf(self: *Self) []u8 {
|
||||
// We might have read a partial http or websocket message.
|
||||
// Subsequent reads must read from where we left off.
|
||||
return self.buf[self.len..];
|
||||
}
|
||||
|
||||
fn next(self: *Self) !?Message {
|
||||
LOOP: while (true) {
|
||||
var buf = self.buf[self.pos..self.len];
|
||||
|
||||
const length_of_len, const message_len = extractLengths(buf) orelse {
|
||||
// we don't have enough bytes
|
||||
return null;
|
||||
};
|
||||
|
||||
const byte1 = buf[0];
|
||||
|
||||
if (byte1 & 112 != 0) {
|
||||
return error.ReservedFlags;
|
||||
}
|
||||
|
||||
if (comptime EXPECT_MASK) {
|
||||
if (buf[1] & 128 != 128) {
|
||||
// client -> server messages _must_ be masked
|
||||
return error.NotMasked;
|
||||
}
|
||||
} else if (buf[1] & 128 != 0) {
|
||||
// server -> client are never masked
|
||||
return error.Masked;
|
||||
}
|
||||
|
||||
var is_control = false;
|
||||
var is_continuation = false;
|
||||
var message_type: Message.Type = undefined;
|
||||
switch (byte1 & 15) {
|
||||
0 => is_continuation = true,
|
||||
1 => message_type = .text,
|
||||
2 => message_type = .binary,
|
||||
8 => {
|
||||
is_control = true;
|
||||
message_type = .close;
|
||||
},
|
||||
9 => {
|
||||
is_control = true;
|
||||
message_type = .ping;
|
||||
},
|
||||
10 => {
|
||||
is_control = true;
|
||||
message_type = .pong;
|
||||
},
|
||||
else => return error.InvalidMessageType,
|
||||
}
|
||||
|
||||
if (is_control) {
|
||||
if (message_len > 125) {
|
||||
return error.ControlTooLarge;
|
||||
}
|
||||
} else if (message_len > Config.CDP_MAX_MESSAGE_SIZE) {
|
||||
return error.TooLarge;
|
||||
} else if (message_len > self.buf.len) {
|
||||
const len = self.buf.len;
|
||||
self.buf = try growBuffer(self.allocator, self.buf, message_len);
|
||||
buf = self.buf[0..len];
|
||||
// we need more data
|
||||
return null;
|
||||
} else if (buf.len < message_len) {
|
||||
// we need more data
|
||||
return null;
|
||||
}
|
||||
|
||||
// prefix + length_of_len + mask
|
||||
const header_len = 2 + length_of_len + if (comptime EXPECT_MASK) 4 else 0;
|
||||
|
||||
const payload = buf[header_len..message_len];
|
||||
if (comptime EXPECT_MASK) {
|
||||
mask(buf[header_len - 4 .. header_len], payload);
|
||||
}
|
||||
|
||||
// whatever happens after this, we know where the next message starts
|
||||
self.pos += message_len;
|
||||
|
||||
const fin = byte1 & 128 == 128;
|
||||
|
||||
if (is_continuation) {
|
||||
const fragments = &(self.fragments orelse return error.InvalidContinuation);
|
||||
if (fragments.message.items.len + message_len > Config.CDP_MAX_MESSAGE_SIZE) {
|
||||
return error.TooLarge;
|
||||
}
|
||||
|
||||
try fragments.message.appendSlice(self.allocator, payload);
|
||||
|
||||
if (fin == false) {
|
||||
// maybe we have more parts of the message waiting
|
||||
continue :LOOP;
|
||||
}
|
||||
|
||||
// this continuation is done!
|
||||
return .{
|
||||
.type = fragments.type,
|
||||
.data = fragments.message.items,
|
||||
.cleanup_fragment = true,
|
||||
};
|
||||
}
|
||||
|
||||
const can_be_fragmented = message_type == .text or message_type == .binary;
|
||||
if (self.fragments != null and can_be_fragmented) {
|
||||
// if this isn't a continuation, then we can't have fragments
|
||||
return error.NestedFragementation;
|
||||
}
|
||||
|
||||
if (fin == false) {
|
||||
if (can_be_fragmented == false) {
|
||||
return error.InvalidContinuation;
|
||||
}
|
||||
|
||||
// not continuation, and not fin. It has to be the first message
|
||||
// in a fragmented message.
|
||||
var fragments = Fragments{ .message = .{}, .type = message_type };
|
||||
try fragments.message.appendSlice(self.allocator, payload);
|
||||
self.fragments = fragments;
|
||||
continue :LOOP;
|
||||
}
|
||||
|
||||
return .{
|
||||
.data = payload,
|
||||
.type = message_type,
|
||||
.cleanup_fragment = false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn extractLengths(buf: []const u8) ?struct { usize, usize } {
|
||||
if (buf.len < 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const length_of_len: usize = switch (buf[1] & 127) {
|
||||
126 => 2,
|
||||
127 => 8,
|
||||
else => 0,
|
||||
};
|
||||
|
||||
if (buf.len < length_of_len + 2) {
|
||||
// we definitely don't have enough buf yet
|
||||
return null;
|
||||
}
|
||||
|
||||
const message_len = switch (length_of_len) {
|
||||
2 => @as(u16, @intCast(buf[3])) | @as(u16, @intCast(buf[2])) << 8,
|
||||
8 => @as(u64, @intCast(buf[9])) | @as(u64, @intCast(buf[8])) << 8 | @as(u64, @intCast(buf[7])) << 16 | @as(u64, @intCast(buf[6])) << 24 | @as(u64, @intCast(buf[5])) << 32 | @as(u64, @intCast(buf[4])) << 40 | @as(u64, @intCast(buf[3])) << 48 | @as(u64, @intCast(buf[2])) << 56,
|
||||
else => buf[1] & 127,
|
||||
} + length_of_len + 2 + if (comptime EXPECT_MASK) 4 else 0; // +2 for header prefix, +4 for mask;
|
||||
|
||||
return .{ length_of_len, message_len };
|
||||
}
|
||||
|
||||
// This is called after we've processed complete websocket messages (this
|
||||
// only applies to websocket messages).
|
||||
// There are three cases:
|
||||
// 1 - We don't have any incomplete data (for a subsequent message) in buf.
|
||||
// This is the easier to handle, we can set pos & len to 0.
|
||||
// 2 - We have part of the next message, but we know it'll fit in the
|
||||
// remaining buf. We don't need to do anything
|
||||
// 3 - We have part of the next message, but either it won't fight into the
|
||||
// remaining buffer, or we don't know (because we don't have enough
|
||||
// of the header to tell the length). We need to "compact" the buffer
|
||||
fn compact(self: *Self) void {
|
||||
const pos = self.pos;
|
||||
const len = self.len;
|
||||
|
||||
lp.assert(pos <= len, "Client.Reader.compact precondition", .{ .pos = pos, .len = len });
|
||||
|
||||
// how many (if any) partial bytes do we have
|
||||
const partial_bytes = len - pos;
|
||||
|
||||
if (partial_bytes == 0) {
|
||||
// We have no partial bytes. Setting these to 0 ensures that we
|
||||
// get the best utilization of our buffer
|
||||
self.pos = 0;
|
||||
self.len = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
const partial = self.buf[pos..len];
|
||||
|
||||
// If we have enough bytes of the next message to tell its length
|
||||
// we'll be able to figure out whether we need to do anything or not.
|
||||
if (extractLengths(partial)) |length_meta| {
|
||||
const next_message_len = length_meta.@"1";
|
||||
// if this isn't true, then we have a full message and it
|
||||
// should have been processed.
|
||||
lp.assert(pos <= len, "Client.Reader.compact postcondition", .{ .next_len = next_message_len, .partial = partial_bytes });
|
||||
|
||||
const missing_bytes = next_message_len - partial_bytes;
|
||||
|
||||
const free_space = self.buf.len - len;
|
||||
if (missing_bytes < free_space) {
|
||||
// we have enough space in our buffer, as is,
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// We're here because we either don't have enough bytes of the next
|
||||
// message, or we know that it won't fit in our buffer as-is.
|
||||
std.mem.copyForwards(u8, self.buf, partial);
|
||||
self.pos = 0;
|
||||
self.len = partial_bytes;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fn growBuffer(allocator: Allocator, buf: []u8, required_capacity: usize) ![]u8 {
|
||||
// from std.ArrayList
|
||||
var new_capacity = buf.len;
|
||||
while (true) {
|
||||
new_capacity +|= new_capacity / 2 + 8;
|
||||
if (new_capacity >= required_capacity) break;
|
||||
}
|
||||
|
||||
log.debug(.app, "CDP buffer growth", .{ .from = buf.len, .to = new_capacity });
|
||||
|
||||
if (allocator.resize(buf, new_capacity)) {
|
||||
return buf.ptr[0..new_capacity];
|
||||
}
|
||||
const new_buffer = try allocator.alloc(u8, new_capacity);
|
||||
@memcpy(new_buffer[0..buf.len], buf);
|
||||
allocator.free(buf);
|
||||
return new_buffer;
|
||||
}
|
||||
|
||||
const Fragments = struct {
|
||||
type: Message.Type,
|
||||
message: std.ArrayList(u8),
|
||||
};
|
||||
|
||||
const Message = struct {
|
||||
type: Type,
|
||||
data: []const u8,
|
||||
cleanup_fragment: bool,
|
||||
|
||||
const Type = enum {
|
||||
text,
|
||||
binary,
|
||||
close,
|
||||
ping,
|
||||
pong,
|
||||
};
|
||||
};
|
||||
|
||||
// These are the only websocket types that we're currently sending
|
||||
const OpCode = enum(u8) {
|
||||
text = 128 | 1,
|
||||
close = 128 | 8,
|
||||
pong = 128 | 10,
|
||||
};
|
||||
|
||||
fn fillWebsocketHeader(buf: std.ArrayList(u8)) []const u8 {
|
||||
// can't use buf[0..10] here, because the header length
|
||||
// is variable. If it's just 2 bytes, for example, we need the
|
||||
// framed message to be:
|
||||
// h1, h2, data
|
||||
// If we use buf[0..10], we'd get:
|
||||
// h1, h2, 0, 0, 0, 0, 0, 0, 0, 0, data
|
||||
|
||||
var header_buf: [10]u8 = undefined;
|
||||
|
||||
// -10 because we reserved 10 bytes for the header above
|
||||
const header = websocketHeader(&header_buf, .text, buf.items.len - 10);
|
||||
const start = 10 - header.len;
|
||||
|
||||
const message = buf.items;
|
||||
@memcpy(message[start..10], header);
|
||||
return message[start..];
|
||||
}
|
||||
|
||||
// makes the assumption that our caller reserved the first
|
||||
// 10 bytes for the header
|
||||
fn websocketHeader(buf: []u8, op_code: OpCode, payload_len: usize) []const u8 {
|
||||
lp.assert(buf.len == 10, "Websocket.Header", .{ .len = buf.len });
|
||||
|
||||
const len = payload_len;
|
||||
buf[0] = 128 | @intFromEnum(op_code); // fin | opcode
|
||||
|
||||
if (len <= 125) {
|
||||
buf[1] = @intCast(len);
|
||||
return buf[0..2];
|
||||
}
|
||||
|
||||
if (len < 65536) {
|
||||
buf[1] = 126;
|
||||
buf[2] = @intCast((len >> 8) & 0xFF);
|
||||
buf[3] = @intCast(len & 0xFF);
|
||||
return buf[0..4];
|
||||
}
|
||||
|
||||
buf[1] = 127;
|
||||
buf[2] = 0;
|
||||
buf[3] = 0;
|
||||
buf[4] = 0;
|
||||
buf[5] = 0;
|
||||
buf[6] = @intCast((len >> 24) & 0xFF);
|
||||
buf[7] = @intCast((len >> 16) & 0xFF);
|
||||
buf[8] = @intCast((len >> 8) & 0xFF);
|
||||
buf[9] = @intCast(len & 0xFF);
|
||||
return buf[0..10];
|
||||
}
|
||||
|
||||
// Utils
|
||||
// --------
|
||||
|
||||
@@ -1139,48 +584,6 @@ fn buildJSONVersionResponse(
|
||||
|
||||
pub const timestamp = @import("datetime.zig").timestamp;
|
||||
|
||||
// In-place string lowercase
|
||||
fn toLower(str: []u8) []u8 {
|
||||
for (str, 0..) |c, i| {
|
||||
str[i] = std.ascii.toLower(c);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
// Zig is in a weird backend transition right now. Need to determine if
|
||||
// SIMD is even available.
|
||||
const backend_supports_vectors = switch (builtin.zig_backend) {
|
||||
.stage2_llvm, .stage2_c => true,
|
||||
else => false,
|
||||
};
|
||||
|
||||
// Websocket messages from client->server are masked using a 4 byte XOR mask
|
||||
fn mask(m: []const u8, payload: []u8) void {
|
||||
var data = payload;
|
||||
|
||||
if (!comptime backend_supports_vectors) return simpleMask(m, data);
|
||||
|
||||
const vector_size = std.simd.suggestVectorLength(u8) orelse @sizeOf(usize);
|
||||
if (data.len >= vector_size) {
|
||||
const mask_vector = std.simd.repeat(vector_size, @as(@Vector(4, u8), m[0..4].*));
|
||||
while (data.len >= vector_size) {
|
||||
const slice = data[0..vector_size];
|
||||
const masked_data_slice: @Vector(vector_size, u8) = slice.*;
|
||||
slice.* = masked_data_slice ^ mask_vector;
|
||||
data = data[vector_size..];
|
||||
}
|
||||
}
|
||||
simpleMask(m, data);
|
||||
}
|
||||
|
||||
// Used when SIMD isn't available, or for any remaining part of the message
|
||||
// which is too small to effectively use SIMD.
|
||||
fn simpleMask(m: []const u8, payload: []u8) void {
|
||||
for (payload, 0..) |b, i| {
|
||||
payload[i] = b ^ m[i & 3];
|
||||
}
|
||||
}
|
||||
|
||||
const testing = std.testing;
|
||||
test "server: buildJSONVersionResponse" {
|
||||
const address = try net.Address.parseIp4("127.0.0.1", 9001);
|
||||
@@ -1391,22 +794,6 @@ test "Client: close message" {
|
||||
);
|
||||
}
|
||||
|
||||
test "server: mask" {
|
||||
var buf: [4000]u8 = undefined;
|
||||
const messages = [_][]const u8{ "1234", "1234" ** 99, "1234" ** 999 };
|
||||
for (messages) |message| {
|
||||
// we need the message to be mutable since mask operates in-place
|
||||
const payload = buf[0..message.len];
|
||||
@memcpy(payload, message);
|
||||
|
||||
mask(&.{ 1, 2, 200, 240 }, payload);
|
||||
try testing.expectEqual(false, std.mem.eql(u8, payload, message));
|
||||
|
||||
mask(&.{ 1, 2, 200, 240 }, payload);
|
||||
try testing.expectEqual(true, std.mem.eql(u8, payload, message));
|
||||
}
|
||||
}
|
||||
|
||||
test "server: 404" {
|
||||
var c = try createTestClient();
|
||||
defer c.deinit();
|
||||
@@ -1542,7 +929,7 @@ fn createTestClient() !TestClient {
|
||||
const TestClient = struct {
|
||||
stream: std.net.Stream,
|
||||
buf: [1024]u8 = undefined,
|
||||
reader: Reader(false),
|
||||
reader: Net.Reader(false),
|
||||
|
||||
fn deinit(self: *TestClient) void {
|
||||
self.stream.close();
|
||||
@@ -1609,7 +996,7 @@ const TestClient = struct {
|
||||
"Sec-Websocket-Accept: flzHu2DevQ2dSCSVqKSii5e9C2o=\r\n\r\n", res);
|
||||
}
|
||||
|
||||
fn readWebsocketMessage(self: *TestClient) !?Message {
|
||||
fn readWebsocketMessage(self: *TestClient) !?Net.Message {
|
||||
while (true) {
|
||||
const n = try self.stream.read(self.reader.readBuf());
|
||||
if (n == 0) {
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const URL = @import("browser/URL.zig");
|
||||
|
||||
const TestHTTPServer = @This();
|
||||
|
||||
@@ -97,7 +98,10 @@ fn handleConnection(self: *TestHTTPServer, conn: std.net.Server.Connection) !voi
|
||||
}
|
||||
|
||||
pub fn sendFile(req: *std.http.Server.Request, file_path: []const u8) !void {
|
||||
var file = std.fs.cwd().openFile(file_path, .{}) catch |err| switch (err) {
|
||||
var url_buf: [1024]u8 = undefined;
|
||||
var fba = std.heap.FixedBufferAllocator.init(&url_buf);
|
||||
const unescaped_file_path = try URL.unescape(fba.allocator(), file_path);
|
||||
var file = std.fs.cwd().openFile(unescaped_file_path, .{}) catch |err| switch (err) {
|
||||
error.FileNotFound => return req.respond("server error", .{ .status = .not_found }),
|
||||
else => return err,
|
||||
};
|
||||
|
||||
@@ -87,19 +87,29 @@ pub fn closeSession(self: *Browser) void {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn runMicrotasks(self: *const Browser) void {
|
||||
pub fn runMicrotasks(self: *Browser) void {
|
||||
self.env.runMicrotasks();
|
||||
}
|
||||
|
||||
pub fn runMacrotasks(self: *Browser) !?u64 {
|
||||
return try self.env.runMacrotasks();
|
||||
const env = &self.env;
|
||||
|
||||
const time_to_next = try self.env.runMacrotasks();
|
||||
env.pumpMessageLoop();
|
||||
|
||||
// either of the above could have queued more microtasks
|
||||
env.runMicrotasks();
|
||||
|
||||
return time_to_next;
|
||||
}
|
||||
|
||||
pub fn runMessageLoop(self: *const Browser) void {
|
||||
while (self.env.pumpMessageLoop()) {
|
||||
if (comptime IS_DEBUG) {
|
||||
log.debug(.browser, "pumpMessageLoop", .{});
|
||||
}
|
||||
}
|
||||
pub fn hasBackgroundTasks(self: *Browser) bool {
|
||||
return self.env.hasBackgroundTasks();
|
||||
}
|
||||
pub fn waitForBackgroundTasks(self: *Browser) void {
|
||||
self.env.waitForBackgroundTasks();
|
||||
}
|
||||
|
||||
pub fn runIdleTasks(self: *const Browser) void {
|
||||
self.env.runIdleTasks();
|
||||
}
|
||||
|
||||
@@ -56,7 +56,12 @@ pub const EventManager = @This();
|
||||
|
||||
page: *Page,
|
||||
arena: Allocator,
|
||||
// Used as an optimization in Page._documentIsComplete. If we know there are no
|
||||
// 'load' listeners in the document, we can skip dispatching the per-resource
|
||||
// 'load' event (e.g. amazon product page has no listener and ~350 resources)
|
||||
has_dom_load_listener: bool,
|
||||
listener_pool: std.heap.MemoryPool(Listener),
|
||||
ignore_list: std.ArrayList(*Listener),
|
||||
list_pool: std.heap.MemoryPool(std.DoublyLinkedList),
|
||||
lookup: std.HashMapUnmanaged(
|
||||
EventKey,
|
||||
@@ -72,10 +77,12 @@ pub fn init(arena: Allocator, page: *Page) EventManager {
|
||||
.page = page,
|
||||
.lookup = .{},
|
||||
.arena = arena,
|
||||
.ignore_list = .{},
|
||||
.list_pool = .init(arena),
|
||||
.listener_pool = .init(arena),
|
||||
.dispatch_depth = 0,
|
||||
.deferred_removals = .{},
|
||||
.has_dom_load_listener = false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -106,6 +113,10 @@ pub fn register(self: *EventManager, target: *EventTarget, typ: []const u8, call
|
||||
// Allocate the type string we'll use in both listener and key
|
||||
const type_string = try String.init(self.arena, typ, .{});
|
||||
|
||||
if (type_string.eql(comptime .wrap("load")) and target._type == .node) {
|
||||
self.has_dom_load_listener = true;
|
||||
}
|
||||
|
||||
const gop = try self.lookup.getOrPut(self.arena, .{
|
||||
.type_string = type_string,
|
||||
.event_target = @intFromPtr(target),
|
||||
@@ -146,6 +157,11 @@ pub fn register(self: *EventManager, target: *EventTarget, typ: []const u8, call
|
||||
};
|
||||
// append the listener to the list of listeners for this target
|
||||
gop.value_ptr.*.append(&listener.node);
|
||||
|
||||
// Track load listeners for script execution ignore list
|
||||
if (type_string.eql(comptime .wrap("load"))) {
|
||||
try self.ignore_list.append(self.arena, listener);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remove(self: *EventManager, target: *EventTarget, typ: []const u8, callback: Callback, use_capture: bool) void {
|
||||
@@ -158,6 +174,10 @@ pub fn remove(self: *EventManager, target: *EventTarget, typ: []const u8, callba
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clearIgnoreList(self: *EventManager) void {
|
||||
self.ignore_list.clearRetainingCapacity();
|
||||
}
|
||||
|
||||
// Dispatching can be recursive from the compiler's point of view, so we need to
|
||||
// give it an explicit error set so that other parts of the code can use and
|
||||
// inferred error.
|
||||
@@ -169,42 +189,31 @@ const DispatchError = error{
|
||||
ExecutionError,
|
||||
JsException,
|
||||
};
|
||||
|
||||
pub const DispatchOpts = struct {
|
||||
// A "load" event triggered by a script (in ScriptManager) should not trigger
|
||||
// a "load" listener added within that script. Therefore, any "load" listener
|
||||
// that we add go into an ignore list until after the script finishes executing.
|
||||
// The ignore list is only checked when apply_ignore == true, which is only
|
||||
// set by the ScriptManager when raising the script's "load" event.
|
||||
apply_ignore: bool = false,
|
||||
};
|
||||
|
||||
pub fn dispatch(self: *EventManager, target: *EventTarget, event: *Event) DispatchError!void {
|
||||
return self.dispatchOpts(target, event, .{});
|
||||
}
|
||||
|
||||
pub fn dispatchOpts(self: *EventManager, target: *EventTarget, event: *Event, comptime opts: DispatchOpts) DispatchError!void {
|
||||
event.acquireRef();
|
||||
defer event.deinit(false, self.page);
|
||||
|
||||
if (comptime IS_DEBUG) {
|
||||
log.debug(.event, "eventManager.dispatch", .{ .type = event._type_string.str(), .bubbles = event._bubbles });
|
||||
}
|
||||
|
||||
event._target = target;
|
||||
event._dispatch_target = target; // Store original target for composedPath()
|
||||
var was_handled = false;
|
||||
|
||||
defer if (was_handled) {
|
||||
var ls: js.Local.Scope = undefined;
|
||||
self.page.js.localScope(&ls);
|
||||
defer ls.deinit();
|
||||
ls.local.runMicrotasks();
|
||||
};
|
||||
|
||||
switch (target._type) {
|
||||
.node => |node| try self.dispatchNode(node, event, &was_handled),
|
||||
.xhr,
|
||||
.window,
|
||||
.abort_signal,
|
||||
.media_query_list,
|
||||
.message_port,
|
||||
.text_track_cue,
|
||||
.navigation,
|
||||
.screen,
|
||||
.screen_orientation,
|
||||
.visual_viewport,
|
||||
.generic,
|
||||
=> {
|
||||
const list = self.lookup.get(.{
|
||||
.event_target = @intFromPtr(target),
|
||||
.type_string = event._type_string,
|
||||
}) orelse return;
|
||||
try self.dispatchAll(list, target, event, &was_handled);
|
||||
},
|
||||
.node => |node| try self.dispatchNode(node, event, opts),
|
||||
else => try self.dispatchDirect(target, event, null, .{ .context = "dispatch" }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -213,13 +222,22 @@ pub fn dispatch(self: *EventManager, target: *EventTarget, event: *Event) Dispat
|
||||
// property is just a shortcut for calling addEventListener, but they are distinct.
|
||||
// An event set via property cannot be removed by removeEventListener. If you
|
||||
// set both the property and add a listener, they both execute.
|
||||
const DispatchWithFunctionOptions = struct {
|
||||
const DispatchDirectOptions = struct {
|
||||
context: []const u8,
|
||||
inject_target: bool = true,
|
||||
};
|
||||
pub fn dispatchWithFunction(self: *EventManager, target: *EventTarget, event: *Event, function_: ?js.Function, comptime opts: DispatchWithFunctionOptions) !void {
|
||||
|
||||
// Direct dispatch for non-DOM targets (Window, XHR, AbortSignal) or DOM nodes with
|
||||
// property handlers. No propagation - just calls the handler and registered listeners.
|
||||
// Handler can be: null, ?js.Function.Global, ?js.Function.Temp, or js.Function
|
||||
pub fn dispatchDirect(self: *EventManager, target: *EventTarget, event: *Event, handler: anytype, comptime opts: DispatchDirectOptions) !void {
|
||||
const page = self.page;
|
||||
|
||||
event.acquireRef();
|
||||
defer event.deinit(false, page);
|
||||
|
||||
if (comptime IS_DEBUG) {
|
||||
log.debug(.event, "dispatchWithFunction", .{ .type = event._type_string.str(), .context = opts.context, .has_function = function_ != null });
|
||||
log.debug(.event, "dispatchDirect", .{ .type = event._type_string, .context = opts.context });
|
||||
}
|
||||
|
||||
if (comptime opts.inject_target) {
|
||||
@@ -228,14 +246,15 @@ pub fn dispatchWithFunction(self: *EventManager, target: *EventTarget, event: *E
|
||||
}
|
||||
|
||||
var was_dispatched = false;
|
||||
defer if (was_dispatched) {
|
||||
var ls: js.Local.Scope = undefined;
|
||||
self.page.js.localScope(&ls);
|
||||
defer ls.deinit();
|
||||
ls.local.runMicrotasks();
|
||||
};
|
||||
|
||||
if (function_) |func| {
|
||||
var ls: js.Local.Scope = undefined;
|
||||
page.js.localScope(&ls);
|
||||
defer {
|
||||
ls.local.runMicrotasks();
|
||||
ls.deinit();
|
||||
}
|
||||
|
||||
if (getFunction(handler, &ls.local)) |func| {
|
||||
event._current_target = target;
|
||||
if (func.callWithThis(void, target, .{event})) {
|
||||
was_dispatched = true;
|
||||
@@ -245,23 +264,139 @@ pub fn dispatchWithFunction(self: *EventManager, target: *EventTarget, event: *E
|
||||
}
|
||||
}
|
||||
|
||||
// listeners reigstered via addEventListener
|
||||
const list = self.lookup.get(.{
|
||||
.event_target = @intFromPtr(target),
|
||||
.type_string = event._type_string,
|
||||
}) orelse return;
|
||||
try self.dispatchAll(list, target, event, &was_dispatched);
|
||||
|
||||
// This is a slightly simplified version of what you'll find in dispatchPhase
|
||||
// It is simpler because, for direct dispatching, we know there's no ancestors
|
||||
// and only the single target phase.
|
||||
|
||||
// Track dispatch depth for deferred removal
|
||||
self.dispatch_depth += 1;
|
||||
defer {
|
||||
const dispatch_depth = self.dispatch_depth;
|
||||
// Only destroy deferred listeners when we exit the outermost dispatch
|
||||
if (dispatch_depth == 1) {
|
||||
for (self.deferred_removals.items) |removal| {
|
||||
removal.list.remove(&removal.listener.node);
|
||||
self.listener_pool.destroy(removal.listener);
|
||||
}
|
||||
self.deferred_removals.clearRetainingCapacity();
|
||||
} else {
|
||||
self.dispatch_depth = dispatch_depth - 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Use the last listener in the list as sentinel - listeners added during dispatch will be after it
|
||||
const last_node = list.last orelse return;
|
||||
const last_listener: *Listener = @alignCast(@fieldParentPtr("node", last_node));
|
||||
|
||||
// Iterate through the list, stopping after we've encountered the last_listener
|
||||
var node = list.first;
|
||||
var is_done = false;
|
||||
while (node) |n| {
|
||||
if (is_done) {
|
||||
break;
|
||||
}
|
||||
|
||||
const listener: *Listener = @alignCast(@fieldParentPtr("node", n));
|
||||
is_done = (listener == last_listener);
|
||||
node = n.next;
|
||||
|
||||
// Skip removed listeners
|
||||
if (listener.removed) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// If the listener has an aborted signal, remove it and skip
|
||||
if (listener.signal) |signal| {
|
||||
if (signal.getAborted()) {
|
||||
self.removeListener(list, listener);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Remove "once" listeners BEFORE calling them so nested dispatches don't see them
|
||||
if (listener.once) {
|
||||
self.removeListener(list, listener);
|
||||
}
|
||||
|
||||
was_dispatched = true;
|
||||
event._current_target = target;
|
||||
|
||||
switch (listener.function) {
|
||||
.value => |value| try ls.toLocal(value).callWithThis(void, target, .{event}),
|
||||
.string => |string| {
|
||||
const str = try page.call_arena.dupeZ(u8, string.str());
|
||||
try ls.local.eval(str, null);
|
||||
},
|
||||
.object => |obj_global| {
|
||||
const obj = ls.toLocal(obj_global);
|
||||
if (try obj.getFunction("handleEvent")) |handleEvent| {
|
||||
try handleEvent.callWithThis(void, obj, .{event});
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
if (event._stop_immediate_propagation) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatchNode(self: *EventManager, target: *Node, event: *Event, was_handled: *bool) !void {
|
||||
fn getFunction(handler: anytype, local: *const js.Local) ?js.Function {
|
||||
const T = @TypeOf(handler);
|
||||
const ti = @typeInfo(T);
|
||||
|
||||
if (ti == .null) {
|
||||
return null;
|
||||
}
|
||||
if (ti == .optional) {
|
||||
return getFunction(handler orelse return null, local);
|
||||
}
|
||||
return switch (T) {
|
||||
js.Function => handler,
|
||||
js.Function.Temp => local.toLocal(handler),
|
||||
js.Function.Global => local.toLocal(handler),
|
||||
else => @compileError("handler must be null or \\??js.Function(\\.(Temp|Global))?"),
|
||||
};
|
||||
}
|
||||
|
||||
fn dispatchNode(self: *EventManager, target: *Node, event: *Event, comptime opts: DispatchOpts) !void {
|
||||
const ShadowRoot = @import("webapi/ShadowRoot.zig");
|
||||
|
||||
{
|
||||
const et = target.asEventTarget();
|
||||
event._target = et;
|
||||
event._dispatch_target = et; // Store original target for composedPath()
|
||||
}
|
||||
|
||||
const page = self.page;
|
||||
var was_handled = false;
|
||||
|
||||
// Create a single scope for all event handlers in this dispatch.
|
||||
// This ensures function handles passed to queueMicrotask remain valid
|
||||
// throughout the entire dispatch, preventing crashes when microtasks run.
|
||||
var ls: js.Local.Scope = undefined;
|
||||
page.js.localScope(&ls);
|
||||
defer {
|
||||
if (was_handled) {
|
||||
ls.local.runMicrotasks();
|
||||
}
|
||||
ls.deinit();
|
||||
}
|
||||
|
||||
const activation_state = ActivationState.create(event, target, page);
|
||||
|
||||
// Defer runs even on early return - ensures event phase is reset
|
||||
// and default actions execute (unless prevented)
|
||||
defer {
|
||||
event._event_phase = .none;
|
||||
event._stop_propagation = false;
|
||||
event._stop_immediate_propagation = false;
|
||||
// Handle checkbox/radio activation rollback or commit
|
||||
if (activation_state) |state| {
|
||||
state.restore(event, page);
|
||||
@@ -307,11 +442,14 @@ fn dispatchNode(self: *EventManager, target: *Node, event: *Event, was_handled:
|
||||
node = n._parent;
|
||||
}
|
||||
|
||||
// Even though the window isn't part of the DOM, events always propagate
|
||||
// Even though the window isn't part of the DOM, most events propagate
|
||||
// through it in the capture phase (unless we stopped at a shadow boundary)
|
||||
if (path_len < path_buffer.len) {
|
||||
path_buffer[path_len] = page.window.asEventTarget();
|
||||
path_len += 1;
|
||||
// The only explicit exception is "load"
|
||||
if (event._type_string.eql(comptime .wrap("load")) == false) {
|
||||
if (path_len < path_buffer.len) {
|
||||
path_buffer[path_len] = page.window.asEventTarget();
|
||||
path_len += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const path = path_buffer[0..path_len];
|
||||
@@ -322,32 +460,27 @@ fn dispatchNode(self: *EventManager, target: *Node, event: *Event, was_handled:
|
||||
var i: usize = path_len;
|
||||
while (i > 1) {
|
||||
i -= 1;
|
||||
if (event._stop_propagation) return;
|
||||
const current_target = path[i];
|
||||
if (self.lookup.get(.{
|
||||
.event_target = @intFromPtr(current_target),
|
||||
.type_string = event._type_string,
|
||||
})) |list| {
|
||||
try self.dispatchPhase(list, current_target, event, was_handled, true);
|
||||
if (event._stop_propagation) {
|
||||
return;
|
||||
}
|
||||
try self.dispatchPhase(list, current_target, event, &was_handled, &ls.local, comptime .init(true, opts));
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 2: At target
|
||||
if (event._stop_propagation) return;
|
||||
event._event_phase = .at_target;
|
||||
const target_et = target.asEventTarget();
|
||||
|
||||
blk: {
|
||||
// Get inline handler (e.g., onclick property) for this target
|
||||
if (self.getInlineHandler(target_et, event)) |inline_handler| {
|
||||
was_handled.* = true;
|
||||
was_handled = true;
|
||||
event._current_target = target_et;
|
||||
|
||||
var ls: js.Local.Scope = undefined;
|
||||
self.page.js.localScope(&ls);
|
||||
defer ls.deinit();
|
||||
|
||||
try ls.toLocal(inline_handler).callWithThis(void, target_et, .{event});
|
||||
|
||||
if (event._stop_propagation) {
|
||||
@@ -363,7 +496,7 @@ fn dispatchNode(self: *EventManager, target: *Node, event: *Event, was_handled:
|
||||
.type_string = event._type_string,
|
||||
.event_target = @intFromPtr(target_et),
|
||||
})) |list| {
|
||||
try self.dispatchPhase(list, target_et, event, was_handled, null);
|
||||
try self.dispatchPhase(list, target_et, event, &was_handled, &ls.local, comptime .init(null, opts));
|
||||
if (event._stop_propagation) {
|
||||
return;
|
||||
}
|
||||
@@ -375,20 +508,30 @@ fn dispatchNode(self: *EventManager, target: *Node, event: *Event, was_handled:
|
||||
if (event._bubbles) {
|
||||
event._event_phase = .bubbling_phase;
|
||||
for (path[1..]) |current_target| {
|
||||
if (event._stop_propagation) break;
|
||||
if (self.lookup.get(.{
|
||||
.type_string = event._type_string,
|
||||
.event_target = @intFromPtr(current_target),
|
||||
})) |list| {
|
||||
try self.dispatchPhase(list, current_target, event, was_handled, false);
|
||||
if (event._stop_propagation) {
|
||||
break;
|
||||
}
|
||||
try self.dispatchPhase(list, current_target, event, &was_handled, &ls.local, comptime .init(false, opts));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatchPhase(self: *EventManager, list: *std.DoublyLinkedList, current_target: *EventTarget, event: *Event, was_handled: *bool, comptime capture_only: ?bool) !void {
|
||||
const DispatchPhaseOpts = struct {
|
||||
capture_only: ?bool = null,
|
||||
apply_ignore: bool = false,
|
||||
|
||||
fn init(capture_only: ?bool, opts: DispatchOpts) DispatchPhaseOpts {
|
||||
return .{
|
||||
.capture_only = capture_only,
|
||||
.apply_ignore = opts.apply_ignore,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
fn dispatchPhase(self: *EventManager, list: *std.DoublyLinkedList, current_target: *EventTarget, event: *Event, was_handled: *bool, local: *const js.Local, comptime opts: DispatchPhaseOpts) !void {
|
||||
const page = self.page;
|
||||
|
||||
// Track dispatch depth for deferred removal
|
||||
@@ -414,7 +557,7 @@ fn dispatchPhase(self: *EventManager, list: *std.DoublyLinkedList, current_targe
|
||||
// Iterate through the list, stopping after we've encountered the last_listener
|
||||
var node = list.first;
|
||||
var is_done = false;
|
||||
while (node) |n| {
|
||||
node_loop: while (node) |n| {
|
||||
if (is_done) {
|
||||
break;
|
||||
}
|
||||
@@ -424,7 +567,7 @@ fn dispatchPhase(self: *EventManager, list: *std.DoublyLinkedList, current_targe
|
||||
node = n.next;
|
||||
|
||||
// Skip non-matching listeners
|
||||
if (comptime capture_only) |capture| {
|
||||
if (comptime opts.capture_only) |capture| {
|
||||
if (listener.capture != capture) {
|
||||
continue;
|
||||
}
|
||||
@@ -443,6 +586,14 @@ fn dispatchPhase(self: *EventManager, list: *std.DoublyLinkedList, current_targe
|
||||
}
|
||||
}
|
||||
|
||||
if (comptime opts.apply_ignore) {
|
||||
for (self.ignore_list.items) |ignored| {
|
||||
if (ignored == listener) {
|
||||
continue :node_loop;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove "once" listeners BEFORE calling them so nested dispatches don't see them
|
||||
if (listener.once) {
|
||||
self.removeListener(list, listener);
|
||||
@@ -457,18 +608,14 @@ fn dispatchPhase(self: *EventManager, list: *std.DoublyLinkedList, current_targe
|
||||
event._target = getAdjustedTarget(original_target, current_target);
|
||||
}
|
||||
|
||||
var ls: js.Local.Scope = undefined;
|
||||
page.js.localScope(&ls);
|
||||
defer ls.deinit();
|
||||
|
||||
switch (listener.function) {
|
||||
.value => |value| try ls.toLocal(value).callWithThis(void, current_target, .{event}),
|
||||
.value => |value| try local.toLocal(value).callWithThis(void, current_target, .{event}),
|
||||
.string => |string| {
|
||||
const str = try page.call_arena.dupeZ(u8, string.str());
|
||||
try ls.local.eval(str, null);
|
||||
try local.eval(str, null);
|
||||
},
|
||||
.object => |obj_global| {
|
||||
const obj = ls.toLocal(obj_global);
|
||||
const obj = local.toLocal(obj_global);
|
||||
if (try obj.getFunction("handleEvent")) |handleEvent| {
|
||||
try handleEvent.callWithThis(void, obj, .{event});
|
||||
}
|
||||
@@ -486,22 +633,20 @@ fn dispatchPhase(self: *EventManager, list: *std.DoublyLinkedList, current_targe
|
||||
}
|
||||
}
|
||||
|
||||
// Non-Node dispatching (XHR, Window without propagation)
|
||||
fn dispatchAll(self: *EventManager, list: *std.DoublyLinkedList, current_target: *EventTarget, event: *Event, was_handled: *bool) !void {
|
||||
return self.dispatchPhase(list, current_target, event, was_handled, null);
|
||||
}
|
||||
|
||||
fn getInlineHandler(self: *EventManager, target: *EventTarget, event: *Event) ?js.Function.Global {
|
||||
const global_event_handlers = @import("webapi/global_event_handlers.zig");
|
||||
const handler_type = global_event_handlers.fromEventType(event._type_string.str()) orelse return null;
|
||||
|
||||
// Look up the inline handler for this target
|
||||
const element = switch (target._type) {
|
||||
.node => |n| n.is(Element) orelse return null,
|
||||
const html_element = switch (target._type) {
|
||||
.node => |n| n.is(Element.Html) orelse return null,
|
||||
else => return null,
|
||||
};
|
||||
|
||||
return self.page.getAttrListener(element, handler_type);
|
||||
return html_element.getAttributeFunction(handler_type, self.page) catch |err| {
|
||||
log.warn(.event, "inline html callback", .{ .type = handler_type, .err = err });
|
||||
return null;
|
||||
};
|
||||
}
|
||||
|
||||
fn removeListener(self: *EventManager, list: *std.DoublyLinkedList, listener: *Listener) void {
|
||||
@@ -682,9 +827,10 @@ const ActivationState = struct {
|
||||
}
|
||||
|
||||
// Commit: fire input and change events only if state actually changed
|
||||
// and the element is connected to a document (detached elements don't fire).
|
||||
// For checkboxes, state always changes. For radios, only if was unchecked.
|
||||
const state_changed = (input._input_type == .checkbox) or !self.old_checked;
|
||||
if (state_changed) {
|
||||
if (state_changed and input.asElement().asNode().isConnected()) {
|
||||
fireEvent(page, input, "input") catch |err| {
|
||||
log.warn(.event, "input event", .{ .err = err });
|
||||
};
|
||||
@@ -754,7 +900,6 @@ const ActivationState = struct {
|
||||
.bubbles = true,
|
||||
.cancelable = false,
|
||||
}, page);
|
||||
defer if (!event._v8_handoff) event.deinit(false);
|
||||
|
||||
const target = input.asElement().asEventTarget();
|
||||
try page._event_manager.dispatch(target, event);
|
||||
|
||||
@@ -42,12 +42,96 @@ const Allocator = std.mem.Allocator;
|
||||
const IS_DEBUG = builtin.mode == .Debug;
|
||||
const assert = std.debug.assert;
|
||||
|
||||
// Shared across all frames of a Page.
|
||||
const Factory = @This();
|
||||
|
||||
_page: *Page,
|
||||
_arena: Allocator,
|
||||
_slab: SlabAllocator,
|
||||
|
||||
pub fn init(arena: Allocator) !*Factory {
|
||||
const self = try arena.create(Factory);
|
||||
self.* = .{
|
||||
._arena = arena,
|
||||
._slab = SlabAllocator.init(arena, 128),
|
||||
};
|
||||
return self;
|
||||
}
|
||||
|
||||
// this is a root object
|
||||
pub fn eventTarget(self: *Factory, child: anytype) !*@TypeOf(child) {
|
||||
return self.eventTargetWithAllocator(self._slab.allocator(), child);
|
||||
}
|
||||
|
||||
pub fn eventTargetWithAllocator(_: *const Factory, allocator: Allocator, child: anytype) !*@TypeOf(child) {
|
||||
const chain = try PrototypeChain(
|
||||
&.{ EventTarget, @TypeOf(child) },
|
||||
).allocate(allocator);
|
||||
|
||||
const event_ptr = chain.get(0);
|
||||
event_ptr.* = .{
|
||||
._type = unionInit(EventTarget.Type, chain.get(1)),
|
||||
};
|
||||
chain.setLeaf(1, child);
|
||||
|
||||
return chain.get(1);
|
||||
}
|
||||
|
||||
pub fn standaloneEventTarget(self: *Factory, child: anytype) !*EventTarget {
|
||||
const allocator = self._slab.allocator();
|
||||
const et = try allocator.create(EventTarget);
|
||||
et.* = .{ ._type = unionInit(EventTarget.Type, child) };
|
||||
return et;
|
||||
}
|
||||
|
||||
// this is a root object
|
||||
pub fn event(_: *const Factory, arena: Allocator, typ: String, child: anytype) !*@TypeOf(child) {
|
||||
const chain = try PrototypeChain(
|
||||
&.{ Event, @TypeOf(child) },
|
||||
).allocate(arena);
|
||||
|
||||
// Special case: Event has a _type_string field, so we need manual setup
|
||||
const event_ptr = chain.get(0);
|
||||
event_ptr.* = try eventInit(arena, typ, chain.get(1));
|
||||
chain.setLeaf(1, child);
|
||||
|
||||
return chain.get(1);
|
||||
}
|
||||
|
||||
pub fn uiEvent(_: *const Factory, arena: Allocator, typ: String, child: anytype) !*@TypeOf(child) {
|
||||
const chain = try PrototypeChain(
|
||||
&.{ Event, UIEvent, @TypeOf(child) },
|
||||
).allocate(arena);
|
||||
|
||||
// Special case: Event has a _type_string field, so we need manual setup
|
||||
const event_ptr = chain.get(0);
|
||||
event_ptr.* = try eventInit(arena, typ, chain.get(1));
|
||||
chain.setMiddle(1, UIEvent.Type);
|
||||
chain.setLeaf(2, child);
|
||||
|
||||
return chain.get(2);
|
||||
}
|
||||
|
||||
pub fn mouseEvent(_: *const Factory, arena: Allocator, typ: String, mouse: MouseEvent, child: anytype) !*@TypeOf(child) {
|
||||
const chain = try PrototypeChain(
|
||||
&.{ Event, UIEvent, MouseEvent, @TypeOf(child) },
|
||||
).allocate(arena);
|
||||
|
||||
// Special case: Event has a _type_string field, so we need manual setup
|
||||
const event_ptr = chain.get(0);
|
||||
event_ptr.* = try eventInit(arena, typ, chain.get(1));
|
||||
chain.setMiddle(1, UIEvent.Type);
|
||||
|
||||
// Set MouseEvent with all its fields
|
||||
const mouse_ptr = chain.get(2);
|
||||
mouse_ptr.* = mouse;
|
||||
mouse_ptr._proto = chain.get(1);
|
||||
mouse_ptr._type = unionInit(MouseEvent.Type, chain.get(3));
|
||||
|
||||
chain.setLeaf(3, child);
|
||||
|
||||
return chain.get(3);
|
||||
}
|
||||
|
||||
fn PrototypeChain(comptime types: []const type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
@@ -151,94 +235,14 @@ fn AutoPrototypeChain(comptime types: []const type) type {
|
||||
};
|
||||
}
|
||||
|
||||
pub fn init(arena: Allocator, page: *Page) Factory {
|
||||
return .{
|
||||
._page = page,
|
||||
._arena = arena,
|
||||
._slab = SlabAllocator.init(arena, 128),
|
||||
};
|
||||
}
|
||||
|
||||
// this is a root object
|
||||
pub fn eventTarget(self: *Factory, child: anytype) !*@TypeOf(child) {
|
||||
const allocator = self._slab.allocator();
|
||||
const chain = try PrototypeChain(
|
||||
&.{ EventTarget, @TypeOf(child) },
|
||||
).allocate(allocator);
|
||||
|
||||
const event_ptr = chain.get(0);
|
||||
event_ptr.* = .{
|
||||
._type = unionInit(EventTarget.Type, chain.get(1)),
|
||||
};
|
||||
chain.setLeaf(1, child);
|
||||
|
||||
return chain.get(1);
|
||||
}
|
||||
|
||||
pub fn standaloneEventTarget(self: *Factory, child: anytype) !*EventTarget {
|
||||
const allocator = self._slab.allocator();
|
||||
const et = try allocator.create(EventTarget);
|
||||
et.* = .{ ._type = unionInit(EventTarget.Type, child) };
|
||||
return et;
|
||||
}
|
||||
|
||||
// this is a root object
|
||||
pub fn event(self: *Factory, arena: Allocator, typ: String, child: anytype) !*@TypeOf(child) {
|
||||
const chain = try PrototypeChain(
|
||||
&.{ Event, @TypeOf(child) },
|
||||
).allocate(arena);
|
||||
|
||||
// Special case: Event has a _type_string field, so we need manual setup
|
||||
const event_ptr = chain.get(0);
|
||||
event_ptr.* = try self.eventInit(arena, typ, chain.get(1));
|
||||
chain.setLeaf(1, child);
|
||||
|
||||
return chain.get(1);
|
||||
}
|
||||
|
||||
pub fn uiEvent(self: *Factory, arena: Allocator, typ: String, child: anytype) !*@TypeOf(child) {
|
||||
const chain = try PrototypeChain(
|
||||
&.{ Event, UIEvent, @TypeOf(child) },
|
||||
).allocate(arena);
|
||||
|
||||
// Special case: Event has a _type_string field, so we need manual setup
|
||||
const event_ptr = chain.get(0);
|
||||
event_ptr.* = try self.eventInit(arena, typ, chain.get(1));
|
||||
chain.setMiddle(1, UIEvent.Type);
|
||||
chain.setLeaf(2, child);
|
||||
|
||||
return chain.get(2);
|
||||
}
|
||||
|
||||
pub fn mouseEvent(self: *Factory, arena: Allocator, typ: String, mouse: MouseEvent, child: anytype) !*@TypeOf(child) {
|
||||
const chain = try PrototypeChain(
|
||||
&.{ Event, UIEvent, MouseEvent, @TypeOf(child) },
|
||||
).allocate(arena);
|
||||
|
||||
// Special case: Event has a _type_string field, so we need manual setup
|
||||
const event_ptr = chain.get(0);
|
||||
event_ptr.* = try self.eventInit(arena, typ, chain.get(1));
|
||||
chain.setMiddle(1, UIEvent.Type);
|
||||
|
||||
// Set MouseEvent with all its fields
|
||||
const mouse_ptr = chain.get(2);
|
||||
mouse_ptr.* = mouse;
|
||||
mouse_ptr._proto = chain.get(1);
|
||||
mouse_ptr._type = unionInit(MouseEvent.Type, chain.get(3));
|
||||
|
||||
chain.setLeaf(3, child);
|
||||
|
||||
return chain.get(3);
|
||||
}
|
||||
|
||||
fn eventInit(self: *const Factory, arena: Allocator, typ: String, value: anytype) !Event {
|
||||
fn eventInit(arena: Allocator, typ: String, value: anytype) !Event {
|
||||
// Round to 2ms for privacy (browsers do this)
|
||||
const raw_timestamp = @import("../datetime.zig").milliTimestamp(.monotonic);
|
||||
const time_stamp = (raw_timestamp / 2) * 2;
|
||||
|
||||
return .{
|
||||
._rc = 0,
|
||||
._arena = arena,
|
||||
._page = self._page,
|
||||
._type = unionInit(Event.Type, value),
|
||||
._type_string = typ,
|
||||
._time_stamp = time_stamp,
|
||||
@@ -384,7 +388,7 @@ pub fn destroy(self: *Factory, value: anytype) void {
|
||||
}
|
||||
|
||||
if (comptime @hasField(S, "_proto")) {
|
||||
self.destroyChain(value, true, 0, std.mem.Alignment.@"1");
|
||||
self.destroyChain(value, 0, std.mem.Alignment.@"1");
|
||||
} else {
|
||||
self.destroyStandalone(value);
|
||||
}
|
||||
@@ -398,7 +402,6 @@ pub fn destroyStandalone(self: *Factory, value: anytype) void {
|
||||
fn destroyChain(
|
||||
self: *Factory,
|
||||
value: anytype,
|
||||
comptime first: bool,
|
||||
old_size: usize,
|
||||
old_align: std.mem.Alignment,
|
||||
) void {
|
||||
@@ -410,23 +413,8 @@ fn destroyChain(
|
||||
const new_size = current_size + @sizeOf(S);
|
||||
const new_align = std.mem.Alignment.max(old_align, std.mem.Alignment.of(S));
|
||||
|
||||
// This is initially called from a deinit. We don't want to call that
|
||||
// same deinit. So when this is the first time destroyChain is called
|
||||
// we don't call deinit (because we're in that deinit)
|
||||
if (!comptime first) {
|
||||
// But if it isn't the first time
|
||||
if (@hasDecl(S, "deinit")) {
|
||||
// And it has a deinit, we'll call it
|
||||
switch (@typeInfo(@TypeOf(S.deinit)).@"fn".params.len) {
|
||||
1 => value.deinit(),
|
||||
2 => value.deinit(self._page),
|
||||
else => @compileLog(@typeName(S) ++ " has an invalid deinit function"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (@hasField(S, "_proto")) {
|
||||
self.destroyChain(value._proto, false, new_size, new_align);
|
||||
self.destroyChain(value._proto, new_size, new_align);
|
||||
} else {
|
||||
// no proto so this is the head of the chain.
|
||||
// we use this as the ptr to the start of the chain.
|
||||
|
||||
@@ -24,10 +24,11 @@ params: []const u8 = "",
|
||||
// IANA defines max. charset value length as 40.
|
||||
// We keep 41 for null-termination since HTML parser expects in this format.
|
||||
charset: [41]u8 = default_charset,
|
||||
charset_len: usize = 5,
|
||||
charset_len: usize = default_charset_len,
|
||||
|
||||
/// String "UTF-8" continued by null characters.
|
||||
pub const default_charset = .{ 'U', 'T', 'F', '-', '8' } ++ .{0} ** 36;
|
||||
const default_charset = .{ 'U', 'T', 'F', '-', '8' } ++ .{0} ** 36;
|
||||
const default_charset_len = 5;
|
||||
|
||||
/// Mime with unknown Content-Type, empty params and empty charset.
|
||||
pub const unknown = Mime{ .content_type = .{ .unknown = {} } };
|
||||
@@ -127,17 +128,17 @@ pub fn parse(input: []u8) !Mime {
|
||||
|
||||
const params = trimLeft(normalized[type_len..]);
|
||||
|
||||
var charset: [41]u8 = undefined;
|
||||
var charset_len: usize = undefined;
|
||||
var charset: [41]u8 = default_charset;
|
||||
var charset_len: usize = default_charset_len;
|
||||
|
||||
var it = std.mem.splitScalar(u8, params, ';');
|
||||
while (it.next()) |attr| {
|
||||
const i = std.mem.indexOfScalarPos(u8, attr, 0, '=') orelse return error.Invalid;
|
||||
const i = std.mem.indexOfScalarPos(u8, attr, 0, '=') orelse continue;
|
||||
const name = trimLeft(attr[0..i]);
|
||||
|
||||
const value = trimRight(attr[i + 1 ..]);
|
||||
if (value.len == 0) {
|
||||
return error.Invalid;
|
||||
continue;
|
||||
}
|
||||
|
||||
const attribute_name = std.meta.stringToEnum(enum {
|
||||
@@ -150,7 +151,7 @@ pub fn parse(input: []u8) !Mime {
|
||||
break;
|
||||
}
|
||||
|
||||
const attribute_value = try parseCharset(value);
|
||||
const attribute_value = parseCharset(value) catch continue;
|
||||
@memcpy(charset[0..attribute_value.len], attribute_value);
|
||||
// Null-terminate right after attribute value.
|
||||
charset[attribute_value.len] = 0;
|
||||
@@ -334,6 +335,19 @@ test "Mime: invalid" {
|
||||
"text/ html",
|
||||
"text / html",
|
||||
"text/html other",
|
||||
};
|
||||
|
||||
for (invalids) |invalid| {
|
||||
const mutable_input = try testing.arena_allocator.dupe(u8, invalid);
|
||||
try testing.expectError(error.Invalid, Mime.parse(mutable_input));
|
||||
}
|
||||
}
|
||||
|
||||
test "Mime: malformed parameters are ignored" {
|
||||
defer testing.reset();
|
||||
|
||||
// These should all parse successfully as text/html with malformed params ignored
|
||||
const valid_with_malformed_params = [_][]const u8{
|
||||
"text/html; x",
|
||||
"text/html; x=",
|
||||
"text/html; x= ",
|
||||
@@ -342,11 +356,13 @@ test "Mime: invalid" {
|
||||
"text/html; charset=\"\"",
|
||||
"text/html; charset=\"",
|
||||
"text/html; charset=\"\\",
|
||||
"text/html;\"",
|
||||
};
|
||||
|
||||
for (invalids) |invalid| {
|
||||
const mutable_input = try testing.arena_allocator.dupe(u8, invalid);
|
||||
try testing.expectError(error.Invalid, Mime.parse(mutable_input));
|
||||
for (valid_with_malformed_params) |input| {
|
||||
const mutable_input = try testing.arena_allocator.dupe(u8, input);
|
||||
const mime = try Mime.parse(mutable_input);
|
||||
try testing.expectEqual(.text_html, std.meta.activeTag(mime.content_type));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -435,6 +451,12 @@ test "Mime: parse charset" {
|
||||
.charset = "custom-non-standard-charset-value",
|
||||
.params = "charset=\"custom-non-standard-charset-value\"",
|
||||
}, "text/xml;charset=\"custom-non-standard-charset-value\"");
|
||||
|
||||
try expect(.{
|
||||
.content_type = .{ .text_html = {} },
|
||||
.charset = "UTF-8",
|
||||
.params = "x=\"",
|
||||
}, "text/html;x=\"");
|
||||
}
|
||||
|
||||
test "Mime: isHTML" {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -20,13 +20,14 @@ const std = @import("std");
|
||||
const lp = @import("lightpanda");
|
||||
const builtin = @import("builtin");
|
||||
|
||||
const js = @import("js/js.zig");
|
||||
const log = @import("../log.zig");
|
||||
const Http = @import("../http/Http.zig");
|
||||
const String = @import("../string.zig").String;
|
||||
|
||||
const js = @import("js/js.zig");
|
||||
const URL = @import("URL.zig");
|
||||
const Page = @import("Page.zig");
|
||||
const Browser = @import("Browser.zig");
|
||||
const Http = @import("../http/Http.zig");
|
||||
|
||||
const Element = @import("webapi/Element.zig");
|
||||
|
||||
@@ -83,6 +84,10 @@ imported_modules: std.StringHashMapUnmanaged(ImportedModule),
|
||||
// importmap contains resolved urls.
|
||||
importmap: std.StringHashMapUnmanaged([:0]const u8),
|
||||
|
||||
// have we notified the page that all scripts are loaded (used to fire the "load"
|
||||
// event).
|
||||
page_notified_of_completion: bool,
|
||||
|
||||
pub fn init(allocator: Allocator, http_client: *Http.Client, page: *Page) ScriptManager {
|
||||
return .{
|
||||
.page = page,
|
||||
@@ -96,6 +101,7 @@ pub fn init(allocator: Allocator, http_client: *Http.Client, page: *Page) Script
|
||||
.client = http_client,
|
||||
.static_scripts_done = false,
|
||||
.buffer_pool = BufferPool.init(allocator, 5),
|
||||
.page_notified_of_completion = false,
|
||||
.script_pool = std.heap.MemoryPool(Script).init(allocator),
|
||||
};
|
||||
}
|
||||
@@ -259,6 +265,7 @@ pub fn addFromElement(self: *ScriptManager, comptime from_parser: bool, script_e
|
||||
.url = url,
|
||||
.ctx = script,
|
||||
.method = .GET,
|
||||
.frame_id = page._frame_id,
|
||||
.headers = try self.getHeaders(url),
|
||||
.blocking = is_blocking,
|
||||
.cookie_jar = &page._session.cookie_jar,
|
||||
@@ -358,9 +365,11 @@ pub fn preloadImport(self: *ScriptManager, url: [:0]const u8, referrer: []const
|
||||
.manager = self,
|
||||
};
|
||||
|
||||
const page = self.page;
|
||||
|
||||
if (comptime IS_DEBUG) {
|
||||
var ls: js.Local.Scope = undefined;
|
||||
self.page.js.localScope(&ls);
|
||||
page.js.localScope(&ls);
|
||||
defer ls.deinit();
|
||||
|
||||
log.debug(.http, "script queue", .{
|
||||
@@ -375,10 +384,11 @@ pub fn preloadImport(self: *ScriptManager, url: [:0]const u8, referrer: []const
|
||||
.url = url,
|
||||
.ctx = script,
|
||||
.method = .GET,
|
||||
.frame_id = page._frame_id,
|
||||
.headers = try self.getHeaders(url),
|
||||
.cookie_jar = &self.page._session.cookie_jar,
|
||||
.cookie_jar = &page._session.cookie_jar,
|
||||
.resource_type = .script,
|
||||
.notification = self.page._session.notification,
|
||||
.notification = page._session.notification,
|
||||
.start_callback = if (log.enabled(.http, .debug)) Script.startCallback else null,
|
||||
.header_callback = Script.headerCallback,
|
||||
.data_callback = Script.dataCallback,
|
||||
@@ -451,9 +461,10 @@ pub fn getAsyncImport(self: *ScriptManager, url: [:0]const u8, cb: ImportAsync.C
|
||||
} },
|
||||
};
|
||||
|
||||
const page = self.page;
|
||||
if (comptime IS_DEBUG) {
|
||||
var ls: js.Local.Scope = undefined;
|
||||
self.page.js.localScope(&ls);
|
||||
page.js.localScope(&ls);
|
||||
defer ls.deinit();
|
||||
|
||||
log.debug(.http, "script queue", .{
|
||||
@@ -476,11 +487,12 @@ pub fn getAsyncImport(self: *ScriptManager, url: [:0]const u8, cb: ImportAsync.C
|
||||
try self.client.request(.{
|
||||
.url = url,
|
||||
.method = .GET,
|
||||
.frame_id = page._frame_id,
|
||||
.headers = try self.getHeaders(url),
|
||||
.ctx = script,
|
||||
.resource_type = .script,
|
||||
.cookie_jar = &self.page._session.cookie_jar,
|
||||
.notification = self.page._session.notification,
|
||||
.cookie_jar = &page._session.cookie_jar,
|
||||
.notification = page._session.notification,
|
||||
.start_callback = if (log.enabled(.http, .debug)) Script.startCallback else null,
|
||||
.header_callback = Script.headerCallback,
|
||||
.data_callback = Script.dataCallback,
|
||||
@@ -564,19 +576,12 @@ fn evaluate(self: *ScriptManager) void {
|
||||
// Page makes this safe to call multiple times.
|
||||
page.documentIsLoaded();
|
||||
|
||||
if (self.async_scripts.first == null) {
|
||||
// Looks like all async scripts are done too!
|
||||
// Page makes this safe to call multiple times.
|
||||
page.documentIsComplete();
|
||||
if (self.async_scripts.first == null and self.page_notified_of_completion == false) {
|
||||
self.page_notified_of_completion = true;
|
||||
page.scriptsCompletedLoading();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn isDone(self: *const ScriptManager) bool {
|
||||
return self.static_scripts_done and // page is done processing initial html
|
||||
self.defer_scripts.first == null and // no deferred scripts
|
||||
self.async_scripts.first == null; // no async scripts
|
||||
}
|
||||
|
||||
fn parseImportmap(self: *ScriptManager, script: *const Script) !void {
|
||||
const content = script.source.content();
|
||||
|
||||
@@ -617,8 +622,21 @@ pub const Script = struct {
|
||||
node: std.DoublyLinkedList.Node,
|
||||
script_element: ?*Element.Html.Script,
|
||||
manager: *ScriptManager,
|
||||
|
||||
// for debugging a rare production issue
|
||||
header_callback_called: bool = false,
|
||||
|
||||
// for debugging a rare production issue
|
||||
debug_transfer_id: u32 = 0,
|
||||
debug_transfer_tries: u8 = 0,
|
||||
debug_transfer_aborted: bool = false,
|
||||
debug_transfer_bytes_received: usize = 0,
|
||||
debug_transfer_notified_fail: bool = false,
|
||||
debug_transfer_redirecting: bool = false,
|
||||
debug_transfer_intercept_state: u8 = 0,
|
||||
debug_transfer_auth_challenge: bool = false,
|
||||
debug_transfer_easy_id: usize = 0,
|
||||
|
||||
const Kind = enum {
|
||||
module,
|
||||
javascript,
|
||||
@@ -686,8 +704,37 @@ pub const Script = struct {
|
||||
// temp debug, trying to figure out why the next assert sometimes
|
||||
// fails. Is the buffer just corrupt or is headerCallback really
|
||||
// being called twice?
|
||||
lp.assert(self.header_callback_called == false, "ScriptManager.Header recall", .{});
|
||||
lp.assert(self.header_callback_called == false, "ScriptManager.Header recall", .{
|
||||
.m = @tagName(std.meta.activeTag(self.mode)),
|
||||
.a1 = self.debug_transfer_id,
|
||||
.a2 = self.debug_transfer_tries,
|
||||
.a3 = self.debug_transfer_aborted,
|
||||
.a4 = self.debug_transfer_bytes_received,
|
||||
.a5 = self.debug_transfer_notified_fail,
|
||||
.a6 = self.debug_transfer_redirecting,
|
||||
.a7 = self.debug_transfer_intercept_state,
|
||||
.a8 = self.debug_transfer_auth_challenge,
|
||||
.a9 = self.debug_transfer_easy_id,
|
||||
.b1 = transfer.id,
|
||||
.b2 = transfer._tries,
|
||||
.b3 = transfer.aborted,
|
||||
.b4 = transfer.bytes_received,
|
||||
.b5 = transfer._notified_fail,
|
||||
.b6 = transfer._redirecting,
|
||||
.b7 = @intFromEnum(transfer._intercept_state),
|
||||
.b8 = transfer._auth_challenge != null,
|
||||
.b9 = if (transfer._conn) |c| @intFromPtr(c.easy) else 0,
|
||||
});
|
||||
self.header_callback_called = true;
|
||||
self.debug_transfer_id = transfer.id;
|
||||
self.debug_transfer_tries = transfer._tries;
|
||||
self.debug_transfer_aborted = transfer.aborted;
|
||||
self.debug_transfer_bytes_received = transfer.bytes_received;
|
||||
self.debug_transfer_notified_fail = transfer._notified_fail;
|
||||
self.debug_transfer_redirecting = transfer._redirecting;
|
||||
self.debug_transfer_intercept_state = @intFromEnum(transfer._intercept_state);
|
||||
self.debug_transfer_auth_challenge = transfer._auth_challenge != null;
|
||||
self.debug_transfer_easy_id = if (transfer._conn) |c| @intFromPtr(c.easy) else 0;
|
||||
}
|
||||
|
||||
lp.assert(self.source.remote.capacity == 0, "ScriptManager.Header buffer", .{ .capacity = self.source.remote.capacity });
|
||||
@@ -820,13 +867,15 @@ pub const Script = struct {
|
||||
.kind = self.kind,
|
||||
.cacheable = cacheable,
|
||||
});
|
||||
self.executeCallback("error", local.toLocal(script_element._on_error), page);
|
||||
self.executeCallback(comptime .wrap("error"), page);
|
||||
return;
|
||||
};
|
||||
self.executeCallback("load", local.toLocal(script_element._on_load), page);
|
||||
self.executeCallback(comptime .wrap("load"), page);
|
||||
return;
|
||||
}
|
||||
|
||||
defer page._event_manager.clearIgnoreList();
|
||||
|
||||
var try_catch: js.TryCatch = undefined;
|
||||
try_catch.init(local);
|
||||
defer try_catch.deinit();
|
||||
@@ -845,19 +894,18 @@ pub const Script = struct {
|
||||
};
|
||||
|
||||
if (comptime IS_DEBUG) {
|
||||
log.debug(.browser, "executed script", .{ .src = url, .success = success, .on_load = script_element._on_load != null });
|
||||
log.debug(.browser, "executed script", .{ .src = url, .success = success });
|
||||
}
|
||||
|
||||
defer {
|
||||
// We should run microtasks even if script execution fails.
|
||||
local.runMicrotasks();
|
||||
local.runMacrotasks(); // also runs microtasks
|
||||
_ = page.js.scheduler.run() catch |err| {
|
||||
log.err(.page, "scheduler", .{ .err = err });
|
||||
};
|
||||
}
|
||||
|
||||
if (success) {
|
||||
self.executeCallback("load", local.toLocal(script_element._on_load), page);
|
||||
self.executeCallback(comptime .wrap("load"), page);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -868,14 +916,12 @@ pub const Script = struct {
|
||||
.cacheable = cacheable,
|
||||
});
|
||||
|
||||
self.executeCallback("error", local.toLocal(script_element._on_error), page);
|
||||
self.executeCallback(comptime .wrap("error"), page);
|
||||
}
|
||||
|
||||
fn executeCallback(self: *const Script, comptime typ: []const u8, cb_: ?js.Function, page: *Page) void {
|
||||
const cb = cb_ orelse return;
|
||||
|
||||
fn executeCallback(self: *const Script, typ: String, page: *Page) void {
|
||||
const Event = @import("webapi/Event.zig");
|
||||
const event = Event.initTrusted(comptime .wrap(typ), .{}, page) catch |err| {
|
||||
const event = Event.initTrusted(typ, .{}, page) catch |err| {
|
||||
log.warn(.js, "script internal callback", .{
|
||||
.url = self.url,
|
||||
.type = typ,
|
||||
@@ -883,14 +929,11 @@ pub const Script = struct {
|
||||
});
|
||||
return;
|
||||
};
|
||||
defer if (!event._v8_handoff) event.deinit(false);
|
||||
|
||||
var caught: js.TryCatch.Caught = undefined;
|
||||
cb.tryCall(void, .{event}, &caught) catch {
|
||||
page._event_manager.dispatchOpts(self.script_element.?.asNode().asEventTarget(), event, .{ .apply_ignore = true }) catch |err| {
|
||||
log.warn(.js, "script callback", .{
|
||||
.url = self.url,
|
||||
.type = typ,
|
||||
.caught = caught,
|
||||
.err = err,
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -1010,23 +1053,35 @@ fn parseDataURI(allocator: Allocator, src: []const u8) !?[]const u8 {
|
||||
|
||||
const uri = src[5..];
|
||||
const data_starts = std.mem.indexOfScalar(u8, uri, ',') orelse return null;
|
||||
const data = uri[data_starts + 1 ..];
|
||||
|
||||
var data = uri[data_starts + 1 ..];
|
||||
const unescaped = try URL.unescape(allocator, data);
|
||||
|
||||
// Extract the encoding.
|
||||
const metadata = uri[0..data_starts];
|
||||
if (std.mem.endsWith(u8, metadata, ";base64")) {
|
||||
const decoder = std.base64.standard.Decoder;
|
||||
const decoded_size = try decoder.calcSizeForSlice(data);
|
||||
|
||||
const buffer = try allocator.alloc(u8, decoded_size);
|
||||
errdefer allocator.free(buffer);
|
||||
|
||||
try decoder.decode(buffer, data);
|
||||
data = buffer;
|
||||
if (std.mem.endsWith(u8, metadata, ";base64") == false) {
|
||||
return unescaped;
|
||||
}
|
||||
|
||||
return data;
|
||||
// Forgiving base64 decode per WHATWG spec:
|
||||
// https://infra.spec.whatwg.org/#forgiving-base64-decode
|
||||
// Step 1: Remove all ASCII whitespace
|
||||
var stripped = try std.ArrayList(u8).initCapacity(allocator, unescaped.len);
|
||||
for (unescaped) |c| {
|
||||
if (!std.ascii.isWhitespace(c)) {
|
||||
stripped.appendAssumeCapacity(c);
|
||||
}
|
||||
}
|
||||
const trimmed = std.mem.trimRight(u8, stripped.items, "=");
|
||||
|
||||
// Length % 4 == 1 is invalid
|
||||
if (trimmed.len % 4 == 1) {
|
||||
return error.InvalidCharacterError;
|
||||
}
|
||||
|
||||
const decoded_size = std.base64.standard_no_pad.Decoder.calcSizeForSlice(trimmed) catch return error.InvalidCharacterError;
|
||||
const buffer = try allocator.alloc(u8, decoded_size);
|
||||
std.base64.standard_no_pad.Decoder.decode(buffer, trimmed) catch return error.InvalidCharacterError;
|
||||
return buffer;
|
||||
}
|
||||
|
||||
const testing = @import("../testing.zig");
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
const std = @import("std");
|
||||
const lp = @import("lightpanda");
|
||||
const builtin = @import("builtin");
|
||||
|
||||
const log = @import("../log.zig");
|
||||
|
||||
@@ -31,7 +32,7 @@ const Browser = @import("Browser.zig");
|
||||
const Notification = @import("../Notification.zig");
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
const IS_DEBUG = @import("builtin").mode == .Debug;
|
||||
const IS_DEBUG = builtin.mode == .Debug;
|
||||
|
||||
// Session is like a browser's tab.
|
||||
// It owns the js env and the loader for all the pages of the session.
|
||||
@@ -45,16 +46,6 @@ notification: *Notification,
|
||||
// Used to create our Inspector and in the BrowserContext.
|
||||
arena: Allocator,
|
||||
|
||||
// The page's arena is unsuitable for data that has to existing while
|
||||
// navigating from one page to another. For example, if we're clicking
|
||||
// on an HREF, the URL exists in the original page (where the click
|
||||
// originated) but also has to exist in the new page.
|
||||
// While we could use the Session's arena, this could accumulate a lot of
|
||||
// memory if we do many navigation events. The `transfer_arena` is meant to
|
||||
// bridge the gap: existing long enough to store any data needed to end one
|
||||
// page and start another.
|
||||
transfer_arena: Allocator,
|
||||
|
||||
cookie_jar: storage.Cookie.Jar,
|
||||
storage_shed: storage.Shed,
|
||||
|
||||
@@ -63,24 +54,23 @@ navigation: Navigation,
|
||||
|
||||
page: ?Page,
|
||||
|
||||
frame_id_gen: u32,
|
||||
|
||||
pub fn init(self: *Session, browser: *Browser, notification: *Notification) !void {
|
||||
const allocator = browser.app.allocator;
|
||||
const arena = try browser.arena_pool.acquire();
|
||||
errdefer browser.arena_pool.release(arena);
|
||||
|
||||
const transfer_arena = try browser.arena_pool.acquire();
|
||||
errdefer browser.arena_pool.release(transfer_arena);
|
||||
|
||||
self.* = .{
|
||||
.page = null,
|
||||
.arena = arena,
|
||||
.history = .{},
|
||||
.frame_id_gen = 0,
|
||||
// The prototype (EventTarget) for Navigation is created when a Page is created.
|
||||
.navigation = .{ ._proto = undefined },
|
||||
.storage_shed = .{},
|
||||
.browser = browser,
|
||||
.notification = notification,
|
||||
.transfer_arena = transfer_arena,
|
||||
.cookie_jar = storage.Cookie.Jar.init(allocator),
|
||||
};
|
||||
}
|
||||
@@ -93,7 +83,6 @@ pub fn deinit(self: *Session) void {
|
||||
|
||||
self.cookie_jar.deinit();
|
||||
self.storage_shed.deinit(browser.app.allocator);
|
||||
browser.arena_pool.release(self.transfer_arena);
|
||||
browser.arena_pool.release(self.arena);
|
||||
}
|
||||
|
||||
@@ -104,7 +93,7 @@ pub fn createPage(self: *Session) !*Page {
|
||||
|
||||
self.page = @as(Page, undefined);
|
||||
const page = &self.page.?;
|
||||
try Page.init(page, self);
|
||||
try Page.init(page, self.nextFrameId(), self, null);
|
||||
|
||||
// Creates a new NavigationEventTarget for this page.
|
||||
try self.navigation.onNewPage(page);
|
||||
@@ -140,12 +129,17 @@ pub fn replacePage(self: *Session) !*Page {
|
||||
}
|
||||
|
||||
lp.assert(self.page != null, "Session.replacePage null page", .{});
|
||||
self.page.?.deinit();
|
||||
|
||||
var current = self.page.?;
|
||||
const frame_id = current._frame_id;
|
||||
const parent = current.parent;
|
||||
current.deinit();
|
||||
|
||||
self.browser.env.memoryPressureNotification(.moderate);
|
||||
|
||||
self.page = @as(Page, undefined);
|
||||
const page = &self.page.?;
|
||||
try Page.init(page, self);
|
||||
try Page.init(page, frame_id, self, parent);
|
||||
return page;
|
||||
}
|
||||
|
||||
@@ -159,53 +153,232 @@ pub const WaitResult = enum {
|
||||
cdp_socket,
|
||||
};
|
||||
|
||||
pub fn findPage(self: *Session, frame_id: u32) ?*Page {
|
||||
const page = self.currentPage() orelse return null;
|
||||
return if (page._frame_id == frame_id) page else null;
|
||||
}
|
||||
|
||||
pub fn wait(self: *Session, wait_ms: u32) WaitResult {
|
||||
var page = &(self.page orelse return .no_page);
|
||||
while (true) {
|
||||
if (self.page) |*page| {
|
||||
switch (page.wait(wait_ms)) {
|
||||
.done => {
|
||||
if (page._queued_navigation == null) {
|
||||
return .done;
|
||||
}
|
||||
self.processScheduledNavigation() catch return .done;
|
||||
},
|
||||
else => |result| return result,
|
||||
const wait_result = self._wait(page, wait_ms) catch |err| {
|
||||
switch (err) {
|
||||
error.JsError => {}, // already logged (with hopefully more context)
|
||||
else => log.err(.browser, "session wait", .{
|
||||
.err = err,
|
||||
.url = page.url,
|
||||
}),
|
||||
}
|
||||
} else {
|
||||
return .no_page;
|
||||
return .done;
|
||||
};
|
||||
|
||||
switch (wait_result) {
|
||||
.done => {
|
||||
if (page._queued_navigation == null) {
|
||||
return .done;
|
||||
}
|
||||
page = self.processScheduledNavigation(page) catch return .done;
|
||||
},
|
||||
else => |result| return result,
|
||||
}
|
||||
// if we've successfull navigated, we'll give the new page another
|
||||
// page.wait(wait_ms)
|
||||
}
|
||||
}
|
||||
|
||||
fn processScheduledNavigation(self: *Session) !void {
|
||||
defer self.browser.arena_pool.reset(self.transfer_arena, 4 * 1024);
|
||||
const url, const opts = blk: {
|
||||
const qn = self.page.?._queued_navigation.?;
|
||||
// qn might not be safe to use after self.removePage is called, hence
|
||||
// this block;
|
||||
const url = qn.url;
|
||||
const opts = qn.opts;
|
||||
fn _wait(self: *Session, page: *Page, wait_ms: u32) !WaitResult {
|
||||
var timer = try std.time.Timer.start();
|
||||
var ms_remaining = wait_ms;
|
||||
|
||||
// This was already aborted on the page, but it would be pretty
|
||||
// bad if old requests went to the new page, so let's make double sure
|
||||
self.browser.http_client.abort();
|
||||
const browser = self.browser;
|
||||
var http_client = browser.http_client;
|
||||
|
||||
// I'd like the page to know NOTHING about cdp_socket / CDP, but the
|
||||
// fact is that the behavior of wait changes depending on whether or
|
||||
// not we're using CDP.
|
||||
// If we aren't using CDP, as soon as we think there's nothing left
|
||||
// to do, we can exit - we'de done.
|
||||
// But if we are using CDP, we should wait for the whole `wait_ms`
|
||||
// because the http_click.tick() also monitors the CDP socket. And while
|
||||
// we could let CDP poll http (like it does for HTTP requests), the fact
|
||||
// is that we know more about the timing of stuff (e.g. how long to
|
||||
// poll/sleep) in the page.
|
||||
const exit_when_done = http_client.cdp_client == null;
|
||||
|
||||
while (true) {
|
||||
switch (page._parse_state) {
|
||||
.pre, .raw, .text, .image => {
|
||||
// The main page hasn't started/finished navigating.
|
||||
// There's no JS to run, and no reason to run the scheduler.
|
||||
if (http_client.active == 0 and exit_when_done) {
|
||||
// haven't started navigating, I guess.
|
||||
return .done;
|
||||
}
|
||||
// Either we have active http connections, or we're in CDP
|
||||
// mode with an extra socket. Either way, we're waiting
|
||||
// for http traffic
|
||||
if (try http_client.tick(@intCast(ms_remaining)) == .cdp_socket) {
|
||||
// exit_when_done is explicitly set when there isn't
|
||||
// an extra socket, so it should not be possibl to
|
||||
// get an cdp_socket message when exit_when_done
|
||||
// is true.
|
||||
if (IS_DEBUG) {
|
||||
std.debug.assert(exit_when_done == false);
|
||||
}
|
||||
|
||||
// data on a socket we aren't handling, return to caller
|
||||
return .cdp_socket;
|
||||
}
|
||||
},
|
||||
.html, .complete => {
|
||||
if (page._queued_navigation != null) {
|
||||
return .done;
|
||||
}
|
||||
|
||||
// The HTML page was parsed. We now either have JS scripts to
|
||||
// download, or scheduled tasks to execute, or both.
|
||||
|
||||
// scheduler.run could trigger new http transfers, so do not
|
||||
// store http_client.active BEFORE this call and then use
|
||||
// it AFTER.
|
||||
const ms_to_next_task = try browser.runMacrotasks();
|
||||
|
||||
// Each call to this runs scheduled load events.
|
||||
try page.dispatchLoad();
|
||||
|
||||
const http_active = http_client.active;
|
||||
const total_network_activity = http_active + http_client.intercepted;
|
||||
if (page._notified_network_almost_idle.check(total_network_activity <= 2)) {
|
||||
page.notifyNetworkAlmostIdle();
|
||||
}
|
||||
if (page._notified_network_idle.check(total_network_activity == 0)) {
|
||||
page.notifyNetworkIdle();
|
||||
}
|
||||
|
||||
if (http_active == 0 and exit_when_done) {
|
||||
// we don't need to consider http_client.intercepted here
|
||||
// because exit_when_done is true, and that can only be
|
||||
// the case when interception isn't possible.
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(http_client.intercepted == 0);
|
||||
}
|
||||
|
||||
const ms: u64 = ms_to_next_task orelse blk: {
|
||||
if (wait_ms - ms_remaining < 100) {
|
||||
if (comptime builtin.is_test) {
|
||||
return .done;
|
||||
}
|
||||
// Look, we want to exit ASAP, but we don't want
|
||||
// to exit so fast that we've run none of the
|
||||
// background jobs.
|
||||
break :blk 50;
|
||||
}
|
||||
|
||||
if (browser.hasBackgroundTasks()) {
|
||||
// _we_ have nothing to run, but v8 is working on
|
||||
// background tasks. We'll wait for them.
|
||||
browser.waitForBackgroundTasks();
|
||||
break :blk 20;
|
||||
}
|
||||
|
||||
// No http transfers, no cdp extra socket, no
|
||||
// scheduled tasks, we're done.
|
||||
return .done;
|
||||
};
|
||||
|
||||
if (ms > ms_remaining) {
|
||||
// Same as above, except we have a scheduled task,
|
||||
// it just happens to be too far into the future
|
||||
// compared to how long we were told to wait.
|
||||
return .done;
|
||||
}
|
||||
|
||||
// We have a task to run in the not-so-distant future.
|
||||
// You might think we can just sleep until that task is
|
||||
// ready, but we should continue to run lowPriority tasks
|
||||
// in the meantime, and that could unblock things. So
|
||||
// we'll just sleep for a bit, and then restart our wait
|
||||
// loop to see if anything new can be processed.
|
||||
std.Thread.sleep(std.time.ns_per_ms * @as(u64, @intCast(@min(ms, 20))));
|
||||
} else {
|
||||
// We're here because we either have active HTTP
|
||||
// connections, or exit_when_done == false (aka, there's
|
||||
// an cdp_socket registered with the http client).
|
||||
// We should continue to run lowPriority tasks, so we
|
||||
// minimize how long we'll poll for network I/O.
|
||||
var ms_to_wait = @min(200, ms_to_next_task orelse 200);
|
||||
if (ms_to_wait > 10 and browser.hasBackgroundTasks()) {
|
||||
// if we have background tasks, we don't want to wait too
|
||||
// long for a message from the client. We want to go back
|
||||
// to the top of the loop and run macrotasks.
|
||||
ms_to_wait = 10;
|
||||
}
|
||||
if (try http_client.tick(@min(ms_remaining, ms_to_wait)) == .cdp_socket) {
|
||||
// data on a socket we aren't handling, return to caller
|
||||
return .cdp_socket;
|
||||
}
|
||||
}
|
||||
},
|
||||
.err => |err| {
|
||||
page._parse_state = .{ .raw_done = @errorName(err) };
|
||||
return err;
|
||||
},
|
||||
.raw_done => {
|
||||
if (exit_when_done) {
|
||||
return .done;
|
||||
}
|
||||
// we _could_ http_client.tick(ms_to_wait), but this has
|
||||
// the same result, and I feel is more correct.
|
||||
return .no_page;
|
||||
},
|
||||
}
|
||||
|
||||
const ms_elapsed = timer.lap() / 1_000_000;
|
||||
if (ms_elapsed >= ms_remaining) {
|
||||
return .done;
|
||||
}
|
||||
ms_remaining -= @intCast(ms_elapsed);
|
||||
}
|
||||
}
|
||||
|
||||
fn processScheduledNavigation(self: *Session, current_page: *Page) !*Page {
|
||||
const browser = self.browser;
|
||||
|
||||
const qn = current_page._queued_navigation.?;
|
||||
// take ownership of the page's queued navigation
|
||||
current_page._queued_navigation = null;
|
||||
defer browser.arena_pool.release(qn.arena);
|
||||
|
||||
const frame_id, const parent = blk: {
|
||||
const page = &self.page.?;
|
||||
const frame_id = page._frame_id;
|
||||
const parent = page.parent;
|
||||
|
||||
browser.http_client.abort();
|
||||
self.removePage();
|
||||
|
||||
break :blk .{ url, opts };
|
||||
break :blk .{ frame_id, parent };
|
||||
};
|
||||
|
||||
const page = self.createPage() catch |err| {
|
||||
log.err(.browser, "queued navigation page error", .{
|
||||
.err = err,
|
||||
.url = url,
|
||||
});
|
||||
self.page = @as(Page, undefined);
|
||||
const page = &self.page.?;
|
||||
try Page.init(page, frame_id, self, parent);
|
||||
|
||||
// Creates a new NavigationEventTarget for this page.
|
||||
try self.navigation.onNewPage(page);
|
||||
|
||||
// start JS env
|
||||
// Inform CDP the main page has been created such that additional context for other Worlds can be created as well
|
||||
self.notification.dispatch(.page_created, page);
|
||||
|
||||
page.navigate(qn.url, qn.opts) catch |err| {
|
||||
log.err(.browser, "queued navigation error", .{ .err = err, .url = qn.url });
|
||||
return err;
|
||||
};
|
||||
|
||||
page.navigate(url, opts) catch |err| {
|
||||
log.err(.browser, "queued navigation error", .{ .err = err, .url = url });
|
||||
return err;
|
||||
};
|
||||
return page;
|
||||
}
|
||||
|
||||
pub fn nextFrameId(self: *Session) u32 {
|
||||
const id = self.frame_id_gen +% 1;
|
||||
self.frame_id_gen = id;
|
||||
return id;
|
||||
}
|
||||
|
||||
@@ -20,44 +20,61 @@ const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const ResolveOpts = struct {
|
||||
encode: bool = false,
|
||||
always_dupe: bool = false,
|
||||
};
|
||||
|
||||
// path is anytype, so that it can be used with both []const u8 and [:0]const u8
|
||||
pub fn resolve(allocator: Allocator, base: [:0]const u8, path: anytype, comptime opts: ResolveOpts) ![:0]const u8 {
|
||||
const PT = @TypeOf(path);
|
||||
if (base.len == 0 or isCompleteHTTPUrl(path)) {
|
||||
if (comptime opts.always_dupe or !isNullTerminated(PT)) {
|
||||
return allocator.dupeZ(u8, path);
|
||||
const duped = try allocator.dupeZ(u8, path);
|
||||
return processResolved(allocator, duped, opts);
|
||||
}
|
||||
if (comptime opts.encode) {
|
||||
return processResolved(allocator, path, opts);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
if (path.len == 0) {
|
||||
if (comptime opts.always_dupe) {
|
||||
return allocator.dupeZ(u8, base);
|
||||
const duped = try allocator.dupeZ(u8, base);
|
||||
return processResolved(allocator, duped, opts);
|
||||
}
|
||||
if (comptime opts.encode) {
|
||||
return processResolved(allocator, base, opts);
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
if (path[0] == '?') {
|
||||
const base_path_end = std.mem.indexOfAny(u8, base, "?#") orelse base.len;
|
||||
return std.mem.joinZ(allocator, "", &.{ base[0..base_path_end], path });
|
||||
const result = try std.mem.joinZ(allocator, "", &.{ base[0..base_path_end], path });
|
||||
return processResolved(allocator, result, opts);
|
||||
}
|
||||
if (path[0] == '#') {
|
||||
const base_fragment_start = std.mem.indexOfScalar(u8, base, '#') orelse base.len;
|
||||
return std.mem.joinZ(allocator, "", &.{ base[0..base_fragment_start], path });
|
||||
const result = try std.mem.joinZ(allocator, "", &.{ base[0..base_fragment_start], path });
|
||||
return processResolved(allocator, result, opts);
|
||||
}
|
||||
|
||||
if (std.mem.startsWith(u8, path, "//")) {
|
||||
// network-path reference
|
||||
const index = std.mem.indexOfScalar(u8, base, ':') orelse {
|
||||
if (comptime isNullTerminated(PT)) {
|
||||
if (comptime opts.encode) {
|
||||
return processResolved(allocator, path, opts);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
return allocator.dupeZ(u8, path);
|
||||
const duped = try allocator.dupeZ(u8, path);
|
||||
return processResolved(allocator, duped, opts);
|
||||
};
|
||||
const protocol = base[0 .. index + 1];
|
||||
return std.mem.joinZ(allocator, "", &.{ protocol, path });
|
||||
const result = try std.mem.joinZ(allocator, "", &.{ protocol, path });
|
||||
return processResolved(allocator, result, opts);
|
||||
}
|
||||
|
||||
const scheme_end = std.mem.indexOf(u8, base, "://");
|
||||
@@ -65,7 +82,8 @@ pub fn resolve(allocator: Allocator, base: [:0]const u8, path: anytype, comptime
|
||||
const path_start = std.mem.indexOfScalarPos(u8, base, authority_start, '/') orelse base.len;
|
||||
|
||||
if (path[0] == '/') {
|
||||
return std.mem.joinZ(allocator, "", &.{ base[0..path_start], path });
|
||||
const result = try std.mem.joinZ(allocator, "", &.{ base[0..path_start], path });
|
||||
return processResolved(allocator, result, opts);
|
||||
}
|
||||
|
||||
var normalized_base: []const u8 = base[0..path_start];
|
||||
@@ -127,7 +145,119 @@ pub fn resolve(allocator: Allocator, base: [:0]const u8, path: anytype, comptime
|
||||
|
||||
// we always have an extra space
|
||||
out[out_i] = 0;
|
||||
return out[0..out_i :0];
|
||||
return processResolved(allocator, out[0..out_i :0], opts);
|
||||
}
|
||||
|
||||
fn processResolved(allocator: Allocator, url: [:0]const u8, comptime opts: ResolveOpts) ![:0]const u8 {
|
||||
if (!comptime opts.encode) {
|
||||
return url;
|
||||
}
|
||||
return ensureEncoded(allocator, url);
|
||||
}
|
||||
|
||||
pub fn ensureEncoded(allocator: Allocator, url: [:0]const u8) ![:0]const u8 {
|
||||
const scheme_end = std.mem.indexOf(u8, url, "://");
|
||||
const authority_start = if (scheme_end) |end| end + 3 else 0;
|
||||
const path_start = std.mem.indexOfScalarPos(u8, url, authority_start, '/') orelse return url;
|
||||
|
||||
const query_start = std.mem.indexOfScalarPos(u8, url, path_start, '?');
|
||||
const fragment_start = std.mem.indexOfScalarPos(u8, url, query_start orelse path_start, '#');
|
||||
|
||||
const path_end = query_start orelse fragment_start orelse url.len;
|
||||
const query_end = if (query_start) |_| (fragment_start orelse url.len) else path_end;
|
||||
|
||||
const path_to_encode = url[path_start..path_end];
|
||||
const encoded_path = try percentEncodeSegment(allocator, path_to_encode, true);
|
||||
|
||||
const encoded_query = if (query_start) |qs| blk: {
|
||||
const query_to_encode = url[qs + 1 .. query_end];
|
||||
const encoded = try percentEncodeSegment(allocator, query_to_encode, false);
|
||||
break :blk encoded;
|
||||
} else null;
|
||||
|
||||
const encoded_fragment = if (fragment_start) |fs| blk: {
|
||||
const fragment_to_encode = url[fs + 1 ..];
|
||||
const encoded = try percentEncodeSegment(allocator, fragment_to_encode, false);
|
||||
break :blk encoded;
|
||||
} else null;
|
||||
|
||||
if (encoded_path.ptr == path_to_encode.ptr and
|
||||
(encoded_query == null or encoded_query.?.ptr == url[query_start.? + 1 .. query_end].ptr) and
|
||||
(encoded_fragment == null or encoded_fragment.?.ptr == url[fragment_start.? + 1 ..].ptr))
|
||||
{
|
||||
// nothing has changed
|
||||
return url;
|
||||
}
|
||||
|
||||
var buf = try std.ArrayList(u8).initCapacity(allocator, url.len + 20);
|
||||
try buf.appendSlice(allocator, url[0..path_start]);
|
||||
try buf.appendSlice(allocator, encoded_path);
|
||||
if (encoded_query) |eq| {
|
||||
try buf.append(allocator, '?');
|
||||
try buf.appendSlice(allocator, eq);
|
||||
}
|
||||
if (encoded_fragment) |ef| {
|
||||
try buf.append(allocator, '#');
|
||||
try buf.appendSlice(allocator, ef);
|
||||
}
|
||||
try buf.append(allocator, 0);
|
||||
return buf.items[0 .. buf.items.len - 1 :0];
|
||||
}
|
||||
|
||||
fn percentEncodeSegment(allocator: Allocator, segment: []const u8, comptime is_path: bool) ![]const u8 {
|
||||
// Check if encoding is needed
|
||||
var needs_encoding = false;
|
||||
for (segment) |c| {
|
||||
if (shouldPercentEncode(c, is_path)) {
|
||||
needs_encoding = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!needs_encoding) {
|
||||
return segment;
|
||||
}
|
||||
|
||||
var buf = try std.ArrayList(u8).initCapacity(allocator, segment.len + 10);
|
||||
|
||||
var i: usize = 0;
|
||||
while (i < segment.len) : (i += 1) {
|
||||
const c = segment[i];
|
||||
|
||||
// Check if this is an already-encoded sequence (%XX)
|
||||
if (c == '%' and i + 2 < segment.len) {
|
||||
const end = i + 2;
|
||||
const h1 = segment[i + 1];
|
||||
const h2 = segment[end];
|
||||
if (std.ascii.isHex(h1) and std.ascii.isHex(h2)) {
|
||||
try buf.appendSlice(allocator, segment[i .. end + 1]);
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldPercentEncode(c, is_path)) {
|
||||
try buf.writer(allocator).print("%{X:0>2}", .{c});
|
||||
} else {
|
||||
try buf.append(allocator, c);
|
||||
}
|
||||
}
|
||||
|
||||
return buf.items;
|
||||
}
|
||||
|
||||
fn shouldPercentEncode(c: u8, comptime is_path: bool) bool {
|
||||
return switch (c) {
|
||||
// Unreserved characters (RFC 3986)
|
||||
'A'...'Z', 'a'...'z', '0'...'9', '-', '.', '_', '~' => false,
|
||||
// sub-delims allowed in both path and query
|
||||
'!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=' => false,
|
||||
// Separators allowed in both path and query
|
||||
'/', ':', '@' => false,
|
||||
// Query-specific: '?' is allowed in queries but not in paths
|
||||
'?' => comptime is_path,
|
||||
// Everything else needs encoding (including space)
|
||||
else => true,
|
||||
};
|
||||
}
|
||||
|
||||
fn isNullTerminated(comptime value: type) bool {
|
||||
@@ -512,6 +642,33 @@ pub fn getRobotsUrl(arena: Allocator, url: [:0]const u8) ![:0]const u8 {
|
||||
);
|
||||
}
|
||||
|
||||
pub fn unescape(arena: Allocator, input: []const u8) ![]const u8 {
|
||||
if (std.mem.indexOfScalar(u8, input, '%') == null) {
|
||||
return input;
|
||||
}
|
||||
|
||||
var result = try std.ArrayList(u8).initCapacity(arena, input.len);
|
||||
|
||||
var i: usize = 0;
|
||||
while (i < input.len) {
|
||||
if (input[i] == '%' and i + 2 < input.len) {
|
||||
const hex = input[i + 1 .. i + 3];
|
||||
const byte = std.fmt.parseInt(u8, hex, 16) catch {
|
||||
result.appendAssumeCapacity(input[i]);
|
||||
i += 1;
|
||||
continue;
|
||||
};
|
||||
result.appendAssumeCapacity(byte);
|
||||
i += 3;
|
||||
} else {
|
||||
result.appendAssumeCapacity(input[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return result.items;
|
||||
}
|
||||
|
||||
const testing = @import("../testing.zig");
|
||||
test "URL: isCompleteHTTPUrl" {
|
||||
try testing.expectEqual(true, isCompleteHTTPUrl("http://example.com/about"));
|
||||
@@ -691,6 +848,297 @@ test "URL: resolve" {
|
||||
}
|
||||
}
|
||||
|
||||
test "URL: ensureEncoded" {
|
||||
defer testing.reset();
|
||||
|
||||
const Case = struct {
|
||||
url: [:0]const u8,
|
||||
expected: [:0]const u8,
|
||||
};
|
||||
|
||||
const cases = [_]Case{
|
||||
.{
|
||||
.url = "https://example.com/over 9000!",
|
||||
.expected = "https://example.com/over%209000!",
|
||||
},
|
||||
.{
|
||||
.url = "http://example.com/hello world.html",
|
||||
.expected = "http://example.com/hello%20world.html",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/file[1].html",
|
||||
.expected = "https://example.com/file%5B1%5D.html",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/file{name}.html",
|
||||
.expected = "https://example.com/file%7Bname%7D.html",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/page?query=hello world",
|
||||
.expected = "https://example.com/page?query=hello%20world",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/page?a=1&b=value with spaces",
|
||||
.expected = "https://example.com/page?a=1&b=value%20with%20spaces",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/page#section one",
|
||||
.expected = "https://example.com/page#section%20one",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/my path?query=my value#my anchor",
|
||||
.expected = "https://example.com/my%20path?query=my%20value#my%20anchor",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/already%20encoded",
|
||||
.expected = "https://example.com/already%20encoded",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/file%5B1%5D.html",
|
||||
.expected = "https://example.com/file%5B1%5D.html",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/caf%C3%A9",
|
||||
.expected = "https://example.com/caf%C3%A9",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/page?query=already%20encoded",
|
||||
.expected = "https://example.com/page?query=already%20encoded",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/page?a=1&b=value%20here",
|
||||
.expected = "https://example.com/page?a=1&b=value%20here",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/page#section%20one",
|
||||
.expected = "https://example.com/page#section%20one",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/part%20encoded and not",
|
||||
.expected = "https://example.com/part%20encoded%20and%20not",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/page?a=encoded%20value&b=not encoded",
|
||||
.expected = "https://example.com/page?a=encoded%20value&b=not%20encoded",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/my%20path?query=not encoded#encoded%20anchor",
|
||||
.expected = "https://example.com/my%20path?query=not%20encoded#encoded%20anchor",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/fully%20encoded?query=also%20encoded#and%20this",
|
||||
.expected = "https://example.com/fully%20encoded?query=also%20encoded#and%20this",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/path-with_under~tilde",
|
||||
.expected = "https://example.com/path-with_under~tilde",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/sub-delims!$&'()*+,;=",
|
||||
.expected = "https://example.com/sub-delims!$&'()*+,;=",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com",
|
||||
.expected = "https://example.com",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com?query=value",
|
||||
.expected = "https://example.com?query=value",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/clean/path",
|
||||
.expected = "https://example.com/clean/path",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/path?clean=query#clean-fragment",
|
||||
.expected = "https://example.com/path?clean=query#clean-fragment",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/100% complete",
|
||||
.expected = "https://example.com/100%25%20complete",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/path?value=100% done",
|
||||
.expected = "https://example.com/path?value=100%25%20done",
|
||||
},
|
||||
.{
|
||||
.url = "about:blank",
|
||||
.expected = "about:blank",
|
||||
},
|
||||
};
|
||||
|
||||
for (cases) |case| {
|
||||
const result = try ensureEncoded(testing.arena_allocator, case.url);
|
||||
try testing.expectString(case.expected, result);
|
||||
}
|
||||
}
|
||||
|
||||
test "URL: resolve with encoding" {
|
||||
defer testing.reset();
|
||||
|
||||
const Case = struct {
|
||||
base: [:0]const u8,
|
||||
path: [:0]const u8,
|
||||
expected: [:0]const u8,
|
||||
};
|
||||
|
||||
const cases = [_]Case{
|
||||
// Spaces should be encoded as %20, but ! is allowed
|
||||
.{
|
||||
.base = "https://example.com/dir/",
|
||||
.path = "over 9000!",
|
||||
.expected = "https://example.com/dir/over%209000!",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "hello world.html",
|
||||
.expected = "https://example.com/hello%20world.html",
|
||||
},
|
||||
// Multiple spaces
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "path with multiple spaces",
|
||||
.expected = "https://example.com/path%20with%20%20multiple%20%20%20spaces",
|
||||
},
|
||||
// Special characters that need encoding
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file[1].html",
|
||||
.expected = "https://example.com/file%5B1%5D.html",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file{name}.html",
|
||||
.expected = "https://example.com/file%7Bname%7D.html",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file<test>.html",
|
||||
.expected = "https://example.com/file%3Ctest%3E.html",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file\"quote\".html",
|
||||
.expected = "https://example.com/file%22quote%22.html",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file|pipe.html",
|
||||
.expected = "https://example.com/file%7Cpipe.html",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file\\backslash.html",
|
||||
.expected = "https://example.com/file%5Cbackslash.html",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file^caret.html",
|
||||
.expected = "https://example.com/file%5Ecaret.html",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file`backtick`.html",
|
||||
.expected = "https://example.com/file%60backtick%60.html",
|
||||
},
|
||||
// Characters that should NOT be encoded
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "path-with_under~tilde.html",
|
||||
.expected = "https://example.com/path-with_under~tilde.html",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "path/with/slashes",
|
||||
.expected = "https://example.com/path/with/slashes",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "sub-delims!$&'()*+,;=.html",
|
||||
.expected = "https://example.com/sub-delims!$&'()*+,;=.html",
|
||||
},
|
||||
// Already encoded characters should not be double-encoded
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "already%20encoded",
|
||||
.expected = "https://example.com/already%20encoded",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file%5B1%5D.html",
|
||||
.expected = "https://example.com/file%5B1%5D.html",
|
||||
},
|
||||
// Mix of encoded and unencoded
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "part%20encoded and not",
|
||||
.expected = "https://example.com/part%20encoded%20and%20not",
|
||||
},
|
||||
// Query strings and fragments ARE encoded
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file name.html?query=value with spaces",
|
||||
.expected = "https://example.com/file%20name.html?query=value%20with%20spaces",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file name.html#anchor with spaces",
|
||||
.expected = "https://example.com/file%20name.html#anchor%20with%20spaces",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file.html?hello=world !",
|
||||
.expected = "https://example.com/file.html?hello=world%20!",
|
||||
},
|
||||
// Query structural characters should NOT be encoded
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file.html?a=1&b=2",
|
||||
.expected = "https://example.com/file.html?a=1&b=2",
|
||||
},
|
||||
// Relative paths with encoding
|
||||
.{
|
||||
.base = "https://example.com/dir/page.html",
|
||||
.path = "../other dir/file.html",
|
||||
.expected = "https://example.com/other%20dir/file.html",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/dir/",
|
||||
.path = "./sub dir/file.html",
|
||||
.expected = "https://example.com/dir/sub%20dir/file.html",
|
||||
},
|
||||
// Absolute paths with encoding
|
||||
.{
|
||||
.base = "https://example.com/some/path",
|
||||
.path = "/absolute path/file.html",
|
||||
.expected = "https://example.com/absolute%20path/file.html",
|
||||
},
|
||||
// Unicode/high bytes (though ideally these should be UTF-8 encoded first)
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "café",
|
||||
.expected = "https://example.com/caf%C3%A9",
|
||||
},
|
||||
// Empty path
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "",
|
||||
.expected = "https://example.com/",
|
||||
},
|
||||
// Complete URL as path (should not be encoded)
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "https://other.com/path with spaces",
|
||||
.expected = "https://other.com/path%20with%20spaces",
|
||||
},
|
||||
};
|
||||
|
||||
for (cases) |case| {
|
||||
const result = try resolve(testing.arena_allocator, case.base, case.path, .{ .encode = true });
|
||||
try testing.expectString(case.expected, result);
|
||||
}
|
||||
}
|
||||
|
||||
test "URL: eqlDocument" {
|
||||
defer testing.reset();
|
||||
{
|
||||
@@ -816,3 +1264,68 @@ test "URL: getRobotsUrl" {
|
||||
try testing.expectString("https://example.com/robots.txt", url);
|
||||
}
|
||||
}
|
||||
|
||||
test "URL: unescape" {
|
||||
defer testing.reset();
|
||||
const arena = testing.arena_allocator;
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "hello world");
|
||||
try testing.expectEqual("hello world", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "hello%20world");
|
||||
try testing.expectEqual("hello world", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "%48%65%6c%6c%6f");
|
||||
try testing.expectEqual("Hello", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "%48%65%6C%6C%6F");
|
||||
try testing.expectEqual("Hello", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "a%3Db");
|
||||
try testing.expectEqual("a=b", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "a%3DB");
|
||||
try testing.expectEqual("a=B", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "ZDIgPSAndHdvJzs%3D");
|
||||
try testing.expectEqual("ZDIgPSAndHdvJzs=", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "%5a%44%4d%67%50%53%41%6e%64%47%68%79%5a%57%55%6e%4f%77%3D%3D");
|
||||
try testing.expectEqual("ZDMgPSAndGhyZWUnOw==", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "hello%2world");
|
||||
try testing.expectEqual("hello%2world", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "hello%ZZworld");
|
||||
try testing.expectEqual("hello%ZZworld", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "hello%");
|
||||
try testing.expectEqual("hello%", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "hello%2");
|
||||
try testing.expectEqual("hello%2", result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -480,10 +480,11 @@ fn consumeName(self: *Tokenizer) []const u8 {
|
||||
self.consumeEscape();
|
||||
},
|
||||
0x0 => self.advance(1),
|
||||
'\x80'...'\xBF', '\xC0'...'\xEF', '\xF0'...'\xFF' => {
|
||||
// This byte *is* part of a multi-byte code point,
|
||||
// we’ll end up copying the whole code point before this loop does something else.
|
||||
self.advance(1);
|
||||
'\x80'...'\xFF' => {
|
||||
// Non-ASCII: advance over the complete UTF-8 code point in one step.
|
||||
// Using consumeChar() instead of advance(1) ensures we never land on
|
||||
// a continuation byte, which advance() asserts against.
|
||||
self.consumeChar();
|
||||
},
|
||||
else => {
|
||||
if (self.hasNonAsciiAt(0)) {
|
||||
@@ -583,7 +584,7 @@ fn consumeNumeric(self: *Tokenizer) Token {
|
||||
};
|
||||
|
||||
self.advance(2);
|
||||
} else if (self.hasAtLeast(1) and std.ascii.isDigit(self.byteAt(2))) {
|
||||
} else if (self.hasAtLeast(2) and std.ascii.isDigit(self.byteAt(2))) {
|
||||
self.advance(1);
|
||||
} else {
|
||||
break :blk;
|
||||
|
||||
@@ -20,16 +20,15 @@ const std = @import("std");
|
||||
const Page = @import("Page.zig");
|
||||
const Node = @import("webapi/Node.zig");
|
||||
const Slot = @import("webapi/element/html/Slot.zig");
|
||||
const IFrame = @import("webapi/element/html/IFrame.zig");
|
||||
|
||||
pub const RootOpts = struct {
|
||||
with_base: bool = false,
|
||||
strip: Opts.Strip = .{},
|
||||
shadow: Opts.Shadow = .rendered,
|
||||
};
|
||||
const IS_DEBUG = @import("builtin").mode == .Debug;
|
||||
|
||||
pub const Opts = struct {
|
||||
strip: Strip = .{},
|
||||
shadow: Shadow = .rendered,
|
||||
with_base: bool = false,
|
||||
with_frames: bool = false,
|
||||
strip: Opts.Strip = .{},
|
||||
shadow: Opts.Shadow = .rendered,
|
||||
|
||||
pub const Strip = struct {
|
||||
js: bool = false,
|
||||
@@ -49,7 +48,7 @@ pub const Opts = struct {
|
||||
};
|
||||
};
|
||||
|
||||
pub fn root(doc: *Node.Document, opts: RootOpts, writer: *std.Io.Writer, page: *Page) !void {
|
||||
pub fn root(doc: *Node.Document, opts: Opts, writer: *std.Io.Writer, page: *Page) !void {
|
||||
if (doc.is(Node.Document.HTMLDocument)) |html_doc| {
|
||||
blk: {
|
||||
// Ideally we just render the doctype which is part of the document
|
||||
@@ -71,7 +70,7 @@ pub fn root(doc: *Node.Document, opts: RootOpts, writer: *std.Io.Writer, page: *
|
||||
}
|
||||
}
|
||||
|
||||
return deep(doc.asNode(), .{ .strip = opts.strip, .shadow = opts.shadow }, writer, page);
|
||||
return deep(doc.asNode(), opts, writer, page);
|
||||
}
|
||||
|
||||
pub fn deep(node: *Node, opts: Opts, writer: *std.Io.Writer, page: *Page) error{WriteFailed}!void {
|
||||
@@ -83,19 +82,19 @@ fn _deep(node: *Node, opts: Opts, comptime force_slot: bool, writer: *std.Io.Wri
|
||||
.cdata => |cd| {
|
||||
if (node.is(Node.CData.Comment)) |_| {
|
||||
try writer.writeAll("<!--");
|
||||
try writer.writeAll(cd.getData());
|
||||
try writer.writeAll(cd.getData().str());
|
||||
try writer.writeAll("-->");
|
||||
} else if (node.is(Node.CData.ProcessingInstruction)) |pi| {
|
||||
try writer.writeAll("<?");
|
||||
try writer.writeAll(pi._target);
|
||||
try writer.writeAll(" ");
|
||||
try writer.writeAll(cd.getData());
|
||||
try writer.writeAll(cd.getData().str());
|
||||
try writer.writeAll("?>");
|
||||
} else {
|
||||
if (shouldEscapeText(node._parent)) {
|
||||
try writeEscapedText(cd.getData(), writer);
|
||||
try writeEscapedText(cd.getData().str(), writer);
|
||||
} else {
|
||||
try writer.writeAll(cd.getData());
|
||||
try writer.writeAll(cd.getData().str());
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -140,7 +139,24 @@ fn _deep(node: *Node, opts: Opts, comptime force_slot: bool, writer: *std.Io.Wri
|
||||
}
|
||||
}
|
||||
|
||||
try children(node, opts, writer, page);
|
||||
if (opts.with_frames and el.is(IFrame) != null) {
|
||||
const frame = el.as(IFrame);
|
||||
if (frame.getContentDocument()) |doc| {
|
||||
// A frame's document should always ahave a page, but
|
||||
// I'm not willing to crash a release build on that assertion.
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(doc._page != null);
|
||||
}
|
||||
if (doc._page) |frame_page| {
|
||||
try writer.writeByte('\n');
|
||||
root(doc, opts, writer, frame_page) catch return error.WriteFailed;
|
||||
try writer.writeByte('\n');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
try children(node, opts, writer, page);
|
||||
}
|
||||
|
||||
if (!isVoidElement(el)) {
|
||||
try writer.writeAll("</");
|
||||
try writer.writeAll(el.getTagNameDump());
|
||||
@@ -172,7 +188,11 @@ fn _deep(node: *Node, opts: Opts, comptime force_slot: bool, writer: *std.Io.Wri
|
||||
try writer.writeAll(">\n");
|
||||
},
|
||||
.document_fragment => try children(node, opts, writer, page),
|
||||
.attribute => unreachable,
|
||||
.attribute => {
|
||||
// Not called normally, but can be called via XMLSerializer.serializeToString
|
||||
// in which case it should return an empty string
|
||||
try writer.writeAll("");
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -294,6 +314,12 @@ fn shouldEscapeText(node_: ?*Node) bool {
|
||||
if (node.is(Node.Element.Html.Script) != null) {
|
||||
return false;
|
||||
}
|
||||
// When scripting is enabled, <noscript> is a raw text element per the HTML spec
|
||||
// (https://html.spec.whatwg.org/multipage/parsing.html#serialising-html-fragments).
|
||||
// Its text content must not be HTML-escaped during serialization.
|
||||
if (node.is(Node.Element.Html.Generic)) |generic| {
|
||||
if (generic._tag == .noscript) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
fn writeEscapedText(text: []const u8, writer: *std.Io.Writer) !void {
|
||||
|
||||
@@ -60,6 +60,11 @@ fn initWithContext(self: *Caller, ctx: *Context, v8_context: *const v8.Context)
|
||||
ctx.local = &self.local;
|
||||
}
|
||||
|
||||
pub fn initFromHandle(self: *Caller, handle: ?*const v8.FunctionCallbackInfo) void {
|
||||
const isolate = v8.v8__FunctionCallbackInfo__GetIsolate(handle).?;
|
||||
self.init(isolate);
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Caller) void {
|
||||
const ctx = self.local.ctx;
|
||||
const call_depth = ctx.call_depth - 1;
|
||||
@@ -251,7 +256,33 @@ fn _deleteNamedIndex(comptime T: type, local: *const Local, func: anytype, name:
|
||||
return handleIndexedReturn(T, F, false, local, ret, info, opts);
|
||||
}
|
||||
|
||||
fn handleIndexedReturn(comptime T: type, comptime F: type, comptime getter: bool, local: *const Local, ret: anytype, info: PropertyCallbackInfo, comptime opts: CallOpts) !u8 {
|
||||
pub fn getEnumerator(self: *Caller, comptime T: type, func: anytype, handle: *const v8.PropertyCallbackInfo, comptime opts: CallOpts) u8 {
|
||||
const local = &self.local;
|
||||
|
||||
var hs: js.HandleScope = undefined;
|
||||
hs.init(local.isolate);
|
||||
defer hs.deinit();
|
||||
|
||||
const info = PropertyCallbackInfo{ .handle = handle };
|
||||
return _getEnumerator(T, local, func, info, opts) catch |err| {
|
||||
handleError(T, @TypeOf(func), local, err, info, opts);
|
||||
// not intercepted
|
||||
return 0;
|
||||
};
|
||||
}
|
||||
|
||||
fn _getEnumerator(comptime T: type, local: *const Local, func: anytype, info: PropertyCallbackInfo, comptime opts: CallOpts) !u8 {
|
||||
const F = @TypeOf(func);
|
||||
var args: ParameterTypes(F) = undefined;
|
||||
@field(args, "0") = try TaggedOpaque.fromJS(*T, info.getThis());
|
||||
if (@typeInfo(F).@"fn".params.len == 2) {
|
||||
@field(args, "1") = local.ctx.page;
|
||||
}
|
||||
const ret = @call(.auto, func, args);
|
||||
return handleIndexedReturn(T, F, true, local, ret, info, opts);
|
||||
}
|
||||
|
||||
fn handleIndexedReturn(comptime T: type, comptime F: type, comptime with_value: bool, local: *const Local, ret: anytype, info: PropertyCallbackInfo, comptime opts: CallOpts) !u8 {
|
||||
// need to unwrap this error immediately for when opts.null_as_undefined == true
|
||||
// and we need to compare it to null;
|
||||
const non_error_ret = switch (@typeInfo(@TypeOf(ret))) {
|
||||
@@ -274,7 +305,7 @@ fn handleIndexedReturn(comptime T: type, comptime F: type, comptime getter: bool
|
||||
else => ret,
|
||||
};
|
||||
|
||||
if (comptime getter) {
|
||||
if (comptime with_value) {
|
||||
info.getReturnValue().set(try local.zigValueToJs(non_error_ret, opts));
|
||||
}
|
||||
// intercepted
|
||||
@@ -302,15 +333,20 @@ fn nameToString(local: *const Local, comptime T: type, name: *const v8.Name) !T
|
||||
fn handleError(comptime T: type, comptime F: type, local: *const Local, err: anyerror, info: anytype, comptime opts: CallOpts) void {
|
||||
const isolate = local.isolate;
|
||||
|
||||
if (comptime @import("builtin").mode == .Debug and @TypeOf(info) == FunctionCallbackInfo) {
|
||||
if (log.enabled(.js, .warn)) {
|
||||
logFunctionCallError(local, @typeName(T), @typeName(F), err, info);
|
||||
if (comptime IS_DEBUG and @TypeOf(info) == FunctionCallbackInfo) {
|
||||
if (log.enabled(.js, .debug)) {
|
||||
const DOMException = @import("../webapi/DOMException.zig");
|
||||
if (DOMException.fromError(err) == null) {
|
||||
// This isn't a DOMException, let's log it
|
||||
logFunctionCallError(local, @typeName(T), @typeName(F), err, info);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const js_err: *const v8.Value = switch (err) {
|
||||
error.TryCatchRethrow => return,
|
||||
error.InvalidArgument => isolate.createTypeError("invalid argument"),
|
||||
error.TypeError => isolate.createTypeError(""),
|
||||
error.OutOfMemory => isolate.createError("out of memory"),
|
||||
error.IllegalConstructor => isolate.createError("Illegal Contructor"),
|
||||
else => blk: {
|
||||
@@ -333,7 +369,7 @@ fn handleError(comptime T: type, comptime F: type, local: *const Local, err: any
|
||||
// this can add as much as 10 seconds of compilation time.
|
||||
fn logFunctionCallError(local: *const Local, type_name: []const u8, func: []const u8, err: anyerror, info: FunctionCallbackInfo) void {
|
||||
const args_dump = serializeFunctionArgs(local, info) catch "failed to serialize args";
|
||||
log.info(.js, "function call error", .{
|
||||
log.debug(.js, "function call error", .{
|
||||
.type = type_name,
|
||||
.func = func,
|
||||
.err = err,
|
||||
@@ -410,6 +446,11 @@ pub const FunctionCallbackInfo = struct {
|
||||
return .{ .local = local, .handle = v8.v8__FunctionCallbackInfo__INDEX(self.handle, @intCast(index)).? };
|
||||
}
|
||||
|
||||
pub fn getData(self: FunctionCallbackInfo) ?*anyopaque {
|
||||
const data = v8.v8__FunctionCallbackInfo__Data(self.handle) orelse return null;
|
||||
return v8.v8__External__Value(@ptrCast(data));
|
||||
}
|
||||
|
||||
pub fn getThis(self: FunctionCallbackInfo) *const v8.Object {
|
||||
return v8.v8__FunctionCallbackInfo__This(self.handle).?;
|
||||
}
|
||||
@@ -462,11 +503,13 @@ const ReturnValue = struct {
|
||||
|
||||
pub const Function = struct {
|
||||
pub const Opts = struct {
|
||||
noop: bool = false,
|
||||
static: bool = false,
|
||||
dom_exception: bool = false,
|
||||
as_typed_array: bool = false,
|
||||
null_as_undefined: bool = false,
|
||||
cache: ?Caching = null,
|
||||
embedded_receiver: bool = false,
|
||||
|
||||
// We support two ways to cache a value directly into a v8::Object. The
|
||||
// difference between the two is like the difference between a Map
|
||||
@@ -537,6 +580,9 @@ pub const Function = struct {
|
||||
var args: ParameterTypes(F) = undefined;
|
||||
if (comptime opts.static) {
|
||||
args = try getArgs(F, 0, local, info);
|
||||
} else if (comptime opts.embedded_receiver) {
|
||||
args = try getArgs(F, 1, local, info);
|
||||
@field(args, "0") = @ptrCast(@alignCast(info.getData() orelse unreachable));
|
||||
} else {
|
||||
args = try getArgs(F, 1, local, info);
|
||||
@field(args, "0") = try TaggedOpaque.fromJS(*T, info.getThis());
|
||||
|
||||
@@ -43,13 +43,13 @@ env: *Env,
|
||||
page: *Page,
|
||||
isolate: js.Isolate,
|
||||
|
||||
// Per-context microtask queue for isolation between contexts
|
||||
microtask_queue: *v8.MicrotaskQueue,
|
||||
|
||||
// The v8::Global<v8::Context>. When necessary, we can create a v8::Local<<v8::Context>>
|
||||
// from this, and we can free it when the context is done.
|
||||
handle: v8.Global,
|
||||
|
||||
// True if the context is auto-entered,
|
||||
entered: bool,
|
||||
|
||||
cpu_profiler: ?*v8.CpuProfiler = null,
|
||||
|
||||
heap_profiler: ?*v8.HeapProfiler = null,
|
||||
@@ -124,10 +124,6 @@ script_manager: ?*ScriptManager,
|
||||
// Our macrotasks
|
||||
scheduler: Scheduler,
|
||||
|
||||
// Prevents us from enqueuing a microtask for this context while we're shutting
|
||||
// down.
|
||||
shutting_down: bool = false,
|
||||
|
||||
unknown_properties: (if (IS_DEBUG) std.StringHashMapUnmanaged(UnknownPropertyStat) else void) = if (IS_DEBUG) .{} else {},
|
||||
|
||||
const ModuleEntry = struct {
|
||||
@@ -149,16 +145,11 @@ const ModuleEntry = struct {
|
||||
};
|
||||
|
||||
pub fn fromC(c_context: *const v8.Context) *Context {
|
||||
const data = v8.v8__Context__GetEmbedderData(c_context, 1).?;
|
||||
const big_int = js.BigInt{ .handle = @ptrCast(data) };
|
||||
return @ptrFromInt(big_int.getUint64());
|
||||
return @ptrCast(@alignCast(v8.v8__Context__GetAlignedPointerFromEmbedderData(c_context, 1)));
|
||||
}
|
||||
|
||||
pub fn fromIsolate(isolate: js.Isolate) *Context {
|
||||
const v8_context = v8.v8__Isolate__GetCurrentContext(isolate.handle).?;
|
||||
const data = v8.v8__Context__GetEmbedderData(v8_context, 1).?;
|
||||
const big_int = js.BigInt{ .handle = @ptrCast(data) };
|
||||
return @ptrFromInt(big_int.getUint64());
|
||||
return fromC(v8.v8__Isolate__GetCurrentContext(isolate.handle).?);
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Context) void {
|
||||
@@ -172,21 +163,15 @@ pub fn deinit(self: *Context) void {
|
||||
});
|
||||
}
|
||||
}
|
||||
defer self.env.app.arena_pool.release(self.arena);
|
||||
|
||||
const env = self.env;
|
||||
defer env.app.arena_pool.release(self.arena);
|
||||
|
||||
var hs: js.HandleScope = undefined;
|
||||
const entered = self.enter(&hs);
|
||||
defer entered.exit();
|
||||
|
||||
// We might have microtasks in the isolate that refence this context. The
|
||||
// only option we have is to run them. But a microtask could queue another
|
||||
// microtask, so we set the shutting_down flag, so that any such microtask
|
||||
// will be a noop (this isn't automatic, when v8 calls our microtask callback
|
||||
// the first thing we'll check is if self.shutting_down == true).
|
||||
self.shutting_down = true;
|
||||
self.env.runMicrotasks();
|
||||
|
||||
// can release objects
|
||||
// this can release objects
|
||||
self.scheduler.deinit();
|
||||
|
||||
{
|
||||
@@ -248,11 +233,12 @@ pub fn deinit(self: *Context) void {
|
||||
}
|
||||
}
|
||||
|
||||
if (self.entered) {
|
||||
v8.v8__Context__Exit(@ptrCast(v8.v8__Global__Get(&self.handle, self.isolate.handle)));
|
||||
}
|
||||
|
||||
v8.v8__Global__Reset(&self.handle);
|
||||
env.isolate.notifyContextDisposed();
|
||||
// There can be other tasks associated with this context that we need to
|
||||
// purge while the context is still alive.
|
||||
_ = env.pumpMessageLoop();
|
||||
v8.v8__MicrotaskQueue__DELETE(self.microtask_queue);
|
||||
}
|
||||
|
||||
pub fn weakRef(self: *Context, obj: anytype) void {
|
||||
@@ -333,11 +319,14 @@ pub fn localScope(self: *Context, ls: *js.Local.Scope) void {
|
||||
const isolate = self.isolate;
|
||||
js.HandleScope.init(&ls.handle_scope, isolate);
|
||||
|
||||
const local_v8_context: *const v8.Context = @ptrCast(v8.v8__Global__Get(&self.handle, isolate.handle));
|
||||
v8.v8__Context__Enter(local_v8_context);
|
||||
|
||||
// TODO: add and init ls.hs for the handlescope
|
||||
ls.local = .{
|
||||
.ctx = self,
|
||||
.handle = @ptrCast(v8.v8__Global__Get(&self.handle, isolate.handle)),
|
||||
.isolate = isolate,
|
||||
.handle = local_v8_context,
|
||||
.call_arena = self.call_arena,
|
||||
};
|
||||
}
|
||||
@@ -364,7 +353,6 @@ pub fn stringToPersistedFunction(self: *Context, str: []const u8) !js.Function.G
|
||||
extra = "(e)";
|
||||
}
|
||||
const full = try std.fmt.allocPrintSentinel(self.call_arena, "(function(e) {{ {s}{s} }})", .{ normalized, extra }, 0);
|
||||
|
||||
const js_val = try ls.local.compileAndRun(full, null);
|
||||
if (!js_val.isFunction()) {
|
||||
return error.StringFunctionError;
|
||||
@@ -612,9 +600,18 @@ pub fn dynamicModuleCallback(
|
||||
.isolate = self.isolate,
|
||||
};
|
||||
|
||||
const resource = js.String.toSliceZ(.{ .local = &local, .handle = resource_name.? }) catch |err| {
|
||||
log.err(.app, "OOM", .{ .err = err, .src = "dynamicModuleCallback1" });
|
||||
return @constCast((local.rejectPromise("Out of memory") catch return null).handle);
|
||||
const resource = blk: {
|
||||
const resource_value = js.Value{ .handle = resource_name.?, .local = &local };
|
||||
if (resource_value.isNullOrUndefined()) {
|
||||
// will only be null / undefined in extreme cases (e.g. WPT tests)
|
||||
// where you're
|
||||
break :blk self.page.base();
|
||||
}
|
||||
|
||||
break :blk js.String.toSliceZ(.{ .local = &local, .handle = resource_name.? }) catch |err| {
|
||||
log.err(.app, "OOM", .{ .err = err, .src = "dynamicModuleCallback1" });
|
||||
return @constCast((local.rejectPromise("Out of memory") catch return null).handle);
|
||||
};
|
||||
};
|
||||
|
||||
const specifier = js.String.toSliceZ(.{ .local = &local, .handle = v8_specifier.? }) catch |err| {
|
||||
@@ -789,9 +786,16 @@ fn _dynamicModuleCallback(self: *Context, specifier: [:0]const u8, referrer: []c
|
||||
entry.module_promise = try module_resolver.promise().persist();
|
||||
} else {
|
||||
// the module was loaded, but not evaluated, we _have_ to evaluate it now
|
||||
if (status == .kUninstantiated) {
|
||||
if (try mod.instantiate(resolveModuleCallback) == false) {
|
||||
_ = resolver.reject("module instantiation", local.newString("Module instantiation failed"));
|
||||
return promise;
|
||||
}
|
||||
}
|
||||
|
||||
const evaluated = mod.evaluate() catch {
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(status == .kErrored);
|
||||
std.debug.assert(mod.getStatus() == .kErrored);
|
||||
}
|
||||
_ = resolver.reject("module evaluation", local.newString("Module evaluation failed"));
|
||||
return promise;
|
||||
@@ -871,13 +875,12 @@ fn resolveDynamicModule(self: *Context, state: *DynamicModuleResolveState, modul
|
||||
|
||||
const then_callback = newFunctionWithData(local, struct {
|
||||
pub fn callback(callback_handle: ?*const v8.FunctionCallbackInfo) callconv(.c) void {
|
||||
const isolate = v8.v8__FunctionCallbackInfo__GetIsolate(callback_handle).?;
|
||||
var c: Caller = undefined;
|
||||
c.init(isolate);
|
||||
c.initFromHandle(callback_handle);
|
||||
defer c.deinit();
|
||||
|
||||
const info_data = v8.v8__FunctionCallbackInfo__Data(callback_handle).?;
|
||||
const s: *DynamicModuleResolveState = @ptrCast(@alignCast(v8.v8__External__Value(@ptrCast(info_data))));
|
||||
const info = Caller.FunctionCallbackInfo{ .handle = callback_handle.? };
|
||||
const s: *DynamicModuleResolveState = @ptrCast(@alignCast(info.getData() orelse return));
|
||||
|
||||
if (s.context_id != c.local.ctx.id) {
|
||||
// The microtask is tied to the isolate, not the context
|
||||
@@ -896,17 +899,15 @@ fn resolveDynamicModule(self: *Context, state: *DynamicModuleResolveState, modul
|
||||
|
||||
const catch_callback = newFunctionWithData(local, struct {
|
||||
pub fn callback(callback_handle: ?*const v8.FunctionCallbackInfo) callconv(.c) void {
|
||||
const isolate = v8.v8__FunctionCallbackInfo__GetIsolate(callback_handle).?;
|
||||
var c: Caller = undefined;
|
||||
c.init(isolate);
|
||||
c.initFromHandle(callback_handle);
|
||||
defer c.deinit();
|
||||
|
||||
const info_data = v8.v8__FunctionCallbackInfo__Data(callback_handle).?;
|
||||
const s: *DynamicModuleResolveState = @ptrCast(@alignCast(v8.v8__External__Value(@ptrCast(info_data))));
|
||||
const info = Caller.FunctionCallbackInfo{ .handle = callback_handle.? };
|
||||
const s: *DynamicModuleResolveState = @ptrCast(@alignCast(info.getData() orelse return));
|
||||
|
||||
const l = &c.local;
|
||||
const ctx = l.ctx;
|
||||
if (s.context_id != ctx.id) {
|
||||
if (s.context_id != l.ctx.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -998,13 +999,10 @@ pub fn queueSlotchangeDelivery(self: *Context) !void {
|
||||
// But for these Context microtasks, we want to (a) make sure the context isn't
|
||||
// being shut down and (b) that it's entered.
|
||||
fn enqueueMicrotask(self: *Context, callback: anytype) void {
|
||||
self.isolate.enqueueMicrotask(struct {
|
||||
// Use context-specific microtask queue instead of isolate queue
|
||||
v8.v8__MicrotaskQueue__EnqueueMicrotask(self.microtask_queue, self.isolate.handle, struct {
|
||||
fn run(data: ?*anyopaque) callconv(.c) void {
|
||||
const ctx: *Context = @ptrCast(@alignCast(data.?));
|
||||
if (ctx.shutting_down) {
|
||||
return;
|
||||
}
|
||||
|
||||
var hs: js.HandleScope = undefined;
|
||||
const entered = ctx.enter(&hs);
|
||||
defer entered.exit();
|
||||
@@ -1013,11 +1011,19 @@ fn enqueueMicrotask(self: *Context, callback: anytype) void {
|
||||
}.run, self);
|
||||
}
|
||||
|
||||
// There's an assumption here: the js.Function will be alive when microtasks are
|
||||
// run. If we're Env.runMicrotasks in all the places that we're supposed to, then
|
||||
// this should be safe (I think). In whatever HandleScope a microtask is enqueued,
|
||||
// PerformCheckpoint should be run. So the v8::Local<v8::Function> should remain
|
||||
// valid. If we have problems with this, a simple solution is to provide a Zig
|
||||
// wrapper for these callbacks which references a js.Function.Temp, on callback
|
||||
// it executes the function and then releases the global.
|
||||
pub fn queueMicrotaskFunc(self: *Context, cb: js.Function) void {
|
||||
self.isolate.enqueueMicrotaskFunc(cb);
|
||||
// Use context-specific microtask queue instead of isolate queue
|
||||
v8.v8__MicrotaskQueue__EnqueueMicrotaskFunc(self.microtask_queue, self.isolate.handle, cb.handle);
|
||||
}
|
||||
|
||||
pub fn createFinalizerCallback(self: *Context, global: v8.Global, ptr: *anyopaque, finalizerFn: *const fn (ptr: *anyopaque) void) !*FinalizerCallback {
|
||||
pub fn createFinalizerCallback(self: *Context, global: v8.Global, ptr: *anyopaque, finalizerFn: *const fn (ptr: *anyopaque, page: *Page) void) !*FinalizerCallback {
|
||||
const fc = try self.finalizer_callback_pool.create();
|
||||
fc.* = .{
|
||||
.ctx = self,
|
||||
@@ -1037,10 +1043,10 @@ pub const FinalizerCallback = struct {
|
||||
ctx: *Context,
|
||||
ptr: *anyopaque,
|
||||
global: v8.Global,
|
||||
finalizerFn: *const fn (ptr: *anyopaque) void,
|
||||
finalizerFn: *const fn (ptr: *anyopaque, page: *Page) void,
|
||||
|
||||
pub fn deinit(self: *FinalizerCallback) void {
|
||||
self.finalizerFn(self.ptr);
|
||||
self.finalizerFn(self.ptr, self.ctx.page);
|
||||
self.ctx.finalizer_callback_pool.destroy(self);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -62,7 +62,8 @@ platform: *const Platform,
|
||||
// the global isolate
|
||||
isolate: js.Isolate,
|
||||
|
||||
contexts: std.ArrayList(*js.Context),
|
||||
contexts: [64]*Context,
|
||||
context_count: usize,
|
||||
|
||||
// just kept around because we need to free it on deinit
|
||||
isolate_params: *v8.CreateParams,
|
||||
@@ -85,6 +86,8 @@ inspector: ?*Inspector,
|
||||
// which an be created once per isolaet.
|
||||
private_symbols: PrivateSymbols,
|
||||
|
||||
microtask_queues_are_running: bool,
|
||||
|
||||
pub const InitOpts = struct {
|
||||
with_inspector: bool = false,
|
||||
};
|
||||
@@ -175,8 +178,23 @@ pub fn init(app: *App, opts: InitOpts) !Env {
|
||||
.data = null,
|
||||
.flags = v8.kOnlyInterceptStrings | v8.kNonMasking,
|
||||
});
|
||||
// I don't 100% understand this. We actually set this up in the snapshot,
|
||||
// but for the global instance, it doesn't work. SetIndexedHandler and
|
||||
// SetNamedHandler are set on the Instance template, and that's the key
|
||||
// difference. The context has its own global instance, so we need to set
|
||||
// these back up directly on it. There might be a better way to do this.
|
||||
v8.v8__ObjectTemplate__SetIndexedHandler(global_template_local, &.{
|
||||
.getter = Window.JsApi.index.getter,
|
||||
.setter = null,
|
||||
.query = null,
|
||||
.deleter = null,
|
||||
.enumerator = null,
|
||||
.definer = null,
|
||||
.descriptor = null,
|
||||
.data = null,
|
||||
.flags = 0,
|
||||
});
|
||||
v8.v8__Eternal__New(isolate_handle, @ptrCast(global_template_local), &global_eternal);
|
||||
|
||||
private_symbols = PrivateSymbols.init(isolate_handle);
|
||||
}
|
||||
|
||||
@@ -188,7 +206,8 @@ pub fn init(app: *App, opts: InitOpts) !Env {
|
||||
return .{
|
||||
.app = app,
|
||||
.context_id = 0,
|
||||
.contexts = .empty,
|
||||
.contexts = undefined,
|
||||
.context_count = 0,
|
||||
.isolate = isolate,
|
||||
.platform = &app.platform,
|
||||
.templates = templates,
|
||||
@@ -196,15 +215,16 @@ pub fn init(app: *App, opts: InitOpts) !Env {
|
||||
.inspector = inspector,
|
||||
.global_template = global_eternal,
|
||||
.private_symbols = private_symbols,
|
||||
.microtask_queues_are_running = false,
|
||||
.eternal_function_templates = eternal_function_templates,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Env) void {
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(self.contexts.items.len == 0);
|
||||
std.debug.assert(self.context_count == 0);
|
||||
}
|
||||
for (self.contexts.items) |ctx| {
|
||||
for (self.contexts[0..self.context_count]) |ctx| {
|
||||
ctx.deinit();
|
||||
}
|
||||
|
||||
@@ -213,8 +233,6 @@ pub fn deinit(self: *Env) void {
|
||||
i.deinit(allocator);
|
||||
}
|
||||
|
||||
self.contexts.deinit(allocator);
|
||||
|
||||
allocator.free(self.templates);
|
||||
allocator.free(self.eternal_function_templates);
|
||||
self.private_symbols.deinit();
|
||||
@@ -225,7 +243,7 @@ pub fn deinit(self: *Env) void {
|
||||
allocator.destroy(self.isolate_params);
|
||||
}
|
||||
|
||||
pub fn createContext(self: *Env, page: *Page, enter: bool) !*Context {
|
||||
pub fn createContext(self: *Env, page: *Page) !*Context {
|
||||
const context_arena = try self.app.arena_pool.acquire();
|
||||
errdefer self.app.arena_pool.release(context_arena);
|
||||
|
||||
@@ -234,10 +252,19 @@ pub fn createContext(self: *Env, page: *Page, enter: bool) !*Context {
|
||||
hs.init(isolate);
|
||||
defer hs.deinit();
|
||||
|
||||
// Create a per-context microtask queue for isolation
|
||||
const microtask_queue = v8.v8__MicrotaskQueue__New(isolate.handle, v8.kExplicit).?;
|
||||
errdefer v8.v8__MicrotaskQueue__DELETE(microtask_queue);
|
||||
|
||||
// Get the global template that was created once per isolate
|
||||
const global_template: *const v8.ObjectTemplate = @ptrCast(@alignCast(v8.v8__Eternal__Get(&self.global_template, isolate.handle).?));
|
||||
v8.v8__ObjectTemplate__SetInternalFieldCount(global_template, comptime Snapshot.countInternalFields(Window.JsApi));
|
||||
const v8_context = v8.v8__Context__New(isolate.handle, global_template, null).?;
|
||||
|
||||
const v8_context = v8.v8__Context__New__Config(isolate.handle, &.{
|
||||
.global_template = global_template,
|
||||
.global_object = null,
|
||||
.microtask_queue = microtask_queue,
|
||||
}).?;
|
||||
|
||||
// Create the v8::Context and wrap it in a v8::Global
|
||||
var context_global: v8.Global = undefined;
|
||||
@@ -264,13 +291,6 @@ pub fn createContext(self: *Env, page: *Page, enter: bool) !*Context {
|
||||
var global_global: v8.Global = undefined;
|
||||
v8.v8__Global__New(isolate.handle, global_obj, &global_global);
|
||||
|
||||
if (enter) {
|
||||
v8.v8__Context__Enter(v8_context);
|
||||
}
|
||||
errdefer if (enter) {
|
||||
v8.v8__Context__Exit(v8_context);
|
||||
};
|
||||
|
||||
const context_id = self.context_id;
|
||||
self.context_id = context_id + 1;
|
||||
|
||||
@@ -279,12 +299,12 @@ pub fn createContext(self: *Env, page: *Page, enter: bool) !*Context {
|
||||
.env = self,
|
||||
.page = page,
|
||||
.id = context_id,
|
||||
.entered = enter,
|
||||
.isolate = isolate,
|
||||
.arena = context_arena,
|
||||
.handle = context_global,
|
||||
.templates = self.templates,
|
||||
.call_arena = page.call_arena,
|
||||
.microtask_queue = microtask_queue,
|
||||
.script_manager = &page._script_manager,
|
||||
.scheduler = .init(context_arena),
|
||||
.finalizer_callback_pool = std.heap.MemoryPool(Context.FinalizerCallback).init(self.app.allocator),
|
||||
@@ -293,17 +313,24 @@ pub fn createContext(self: *Env, page: *Page, enter: bool) !*Context {
|
||||
|
||||
// Store a pointer to our context inside the v8 context so that, given
|
||||
// a v8 context, we can get our context out
|
||||
const data = isolate.initBigInt(@intFromPtr(context));
|
||||
v8.v8__Context__SetEmbedderData(v8_context, 1, @ptrCast(data.handle));
|
||||
v8.v8__Context__SetAlignedPointerInEmbedderData(v8_context, 1, @ptrCast(context));
|
||||
|
||||
const count = self.context_count;
|
||||
if (count >= self.contexts.len) {
|
||||
return error.TooManyContexts;
|
||||
}
|
||||
self.contexts[count] = context;
|
||||
self.context_count = count + 1;
|
||||
|
||||
try self.contexts.append(self.app.allocator, context);
|
||||
return context;
|
||||
}
|
||||
|
||||
pub fn destroyContext(self: *Env, context: *Context) void {
|
||||
for (self.contexts.items, 0..) |ctx, i| {
|
||||
for (self.contexts[0..self.context_count], 0..) |ctx, i| {
|
||||
if (ctx == context) {
|
||||
_ = self.contexts.swapRemove(i);
|
||||
// Swap with last element and decrement count
|
||||
self.context_count -= 1;
|
||||
self.contexts[i] = self.contexts[self.context_count];
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
@@ -321,16 +348,26 @@ pub fn destroyContext(self: *Env, context: *Context) void {
|
||||
}
|
||||
|
||||
context.deinit();
|
||||
isolate.notifyContextDisposed();
|
||||
}
|
||||
|
||||
pub fn runMicrotasks(self: *const Env) void {
|
||||
self.isolate.performMicrotasksCheckpoint();
|
||||
pub fn runMicrotasks(self: *Env) void {
|
||||
if (self.microtask_queues_are_running == false) {
|
||||
const v8_isolate = self.isolate.handle;
|
||||
|
||||
self.microtask_queues_are_running = true;
|
||||
defer self.microtask_queues_are_running = false;
|
||||
|
||||
var i: usize = 0;
|
||||
while (i < self.context_count) : (i += 1) {
|
||||
const ctx = self.contexts[i];
|
||||
v8.v8__MicrotaskQueue__PerformCheckpoint(ctx.microtask_queue, v8_isolate);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn runMacrotasks(self: *Env) !?u64 {
|
||||
var ms_to_next_task: ?u64 = null;
|
||||
for (self.contexts.items) |ctx| {
|
||||
for (self.contexts[0..self.context_count]) |ctx| {
|
||||
if (comptime builtin.is_test == false) {
|
||||
// I hate this comptime check as much as you do. But we have tests
|
||||
// which rely on short execution before shutdown. In real world, it's
|
||||
@@ -353,12 +390,31 @@ pub fn runMacrotasks(self: *Env) !?u64 {
|
||||
return ms_to_next_task;
|
||||
}
|
||||
|
||||
pub fn pumpMessageLoop(self: *const Env) bool {
|
||||
pub fn pumpMessageLoop(self: *const Env) void {
|
||||
var hs: v8.HandleScope = undefined;
|
||||
v8.v8__HandleScope__CONSTRUCT(&hs, self.isolate.handle);
|
||||
defer v8.v8__HandleScope__DESTRUCT(&hs);
|
||||
|
||||
return v8.v8__Platform__PumpMessageLoop(self.platform.handle, self.isolate.handle, false);
|
||||
const isolate = self.isolate.handle;
|
||||
const platform = self.platform.handle;
|
||||
while (v8.v8__Platform__PumpMessageLoop(platform, isolate, false)) {}
|
||||
}
|
||||
|
||||
pub fn hasBackgroundTasks(self: *const Env) bool {
|
||||
return v8.v8__Isolate__HasPendingBackgroundTasks(self.isolate.handle);
|
||||
}
|
||||
|
||||
pub fn waitForBackgroundTasks(self: *Env) void {
|
||||
var hs: v8.HandleScope = undefined;
|
||||
v8.v8__HandleScope__CONSTRUCT(&hs, self.isolate.handle);
|
||||
defer v8.v8__HandleScope__DESTRUCT(&hs);
|
||||
|
||||
const isolate = self.isolate.handle;
|
||||
const platform = self.platform.handle;
|
||||
while (v8.v8__Isolate__HasPendingBackgroundTasks(isolate)) {
|
||||
_ = v8.v8__Platform__PumpMessageLoop(platform, isolate, true);
|
||||
self.runMicrotasks();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn runIdleTasks(self: *const Env) void {
|
||||
@@ -414,6 +470,10 @@ pub fn dumpMemoryStats(self: *Env) void {
|
||||
, .{ stats.total_heap_size, stats.total_heap_size_executable, stats.total_physical_size, stats.total_available_size, stats.used_heap_size, stats.heap_size_limit, stats.malloced_memory, stats.external_memory, stats.peak_malloced_memory, stats.number_of_native_contexts, stats.number_of_detached_contexts, stats.total_global_handles_size, stats.used_global_handles_size, stats.does_zap_garbage });
|
||||
}
|
||||
|
||||
pub fn terminate(self: *const Env) void {
|
||||
v8.v8__Isolate__TerminateExecution(self.isolate.handle);
|
||||
}
|
||||
|
||||
fn promiseRejectCallback(message_handle: v8.PromiseRejectMessage) callconv(.c) void {
|
||||
const promise_handle = v8.v8__PromiseRejectMessage__GetPromise(&message_handle).?;
|
||||
const v8_isolate = v8.v8__Object__GetIsolate(@ptrCast(promise_handle)).?;
|
||||
|
||||
@@ -241,8 +241,6 @@ pub const Session = struct {
|
||||
msg.ptr,
|
||||
msg.len,
|
||||
);
|
||||
|
||||
v8.v8__Isolate__PerformMicrotaskCheckpoint(isolate);
|
||||
}
|
||||
|
||||
// Gets a value by object ID regardless of which context it is in.
|
||||
|
||||
@@ -41,18 +41,6 @@ pub fn exit(self: Isolate) void {
|
||||
v8.v8__Isolate__Exit(self.handle);
|
||||
}
|
||||
|
||||
pub fn performMicrotasksCheckpoint(self: Isolate) void {
|
||||
v8.v8__Isolate__PerformMicrotaskCheckpoint(self.handle);
|
||||
}
|
||||
|
||||
pub fn enqueueMicrotask(self: Isolate, callback: anytype, data: anytype) void {
|
||||
v8.v8__Isolate__EnqueueMicrotask(self.handle, callback, data);
|
||||
}
|
||||
|
||||
pub fn enqueueMicrotaskFunc(self: Isolate, function: js.Function) void {
|
||||
v8.v8__Isolate__EnqueueMicrotaskFunc(self.handle, function.handle);
|
||||
}
|
||||
|
||||
pub fn lowMemoryNotification(self: Isolate) void {
|
||||
v8.v8__Isolate__LowMemoryNotification(self.handle);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const Page = @import("../Page.zig");
|
||||
const log = @import("../../log.zig");
|
||||
const string = @import("../../string.zig");
|
||||
|
||||
@@ -81,8 +82,28 @@ pub fn createTypedArray(self: *const Local, comptime array_type: js.ArrayType, s
|
||||
return .init(self, size);
|
||||
}
|
||||
|
||||
pub fn newCallback(
|
||||
self: *const Local,
|
||||
callback: anytype,
|
||||
data: anytype,
|
||||
) js.Function {
|
||||
const external = self.isolate.createExternal(data);
|
||||
const handle = v8.v8__Function__New__DEFAULT2(self.handle, struct {
|
||||
fn wrap(info_handle: ?*const js.v8.FunctionCallbackInfo) callconv(.c) void {
|
||||
Caller.Function.call(@TypeOf(data), info_handle.?, callback, .{ .embedded_receiver = true });
|
||||
}
|
||||
}.wrap, @ptrCast(external)).?;
|
||||
return .{ .local = self, .handle = handle };
|
||||
}
|
||||
|
||||
pub fn runMacrotasks(self: *const Local) void {
|
||||
const env = self.ctx.env;
|
||||
env.pumpMessageLoop();
|
||||
env.runMicrotasks(); // macrotasks can cause microtasks to queue
|
||||
}
|
||||
|
||||
pub fn runMicrotasks(self: *const Local) void {
|
||||
self.isolate.performMicrotasksCheckpoint();
|
||||
self.ctx.env.runMicrotasks();
|
||||
}
|
||||
|
||||
// == Executors ==
|
||||
@@ -216,7 +237,7 @@ pub fn mapZigInstanceToJs(self: *const Local, js_obj_handle: ?*const v8.Object,
|
||||
try ctx.finalizer_callbacks.put(ctx.arena, @intFromPtr(resolved.ptr), fc);
|
||||
}
|
||||
|
||||
conditionallyFlagHandoff(value);
|
||||
conditionallyReference(value);
|
||||
if (@hasDecl(JsApi.Meta, "weak")) {
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(JsApi.Meta.weak == true);
|
||||
@@ -322,6 +343,7 @@ pub fn zigValueToJs(self: *const Local, value: anytype, comptime opts: CallOpts)
|
||||
},
|
||||
|
||||
inline
|
||||
js.Array,
|
||||
js.Function,
|
||||
js.Object,
|
||||
js.Promise,
|
||||
@@ -453,6 +475,13 @@ pub fn jsValueToZig(self: *const Local, comptime T: type, js_val: js.Value) !T {
|
||||
return js_val;
|
||||
}
|
||||
|
||||
if (comptime o.child == js.NullableString) {
|
||||
if (js_val.isUndefined()) {
|
||||
return null;
|
||||
}
|
||||
return .{ .value = try js_val.toStringSlice() };
|
||||
}
|
||||
|
||||
if (comptime o.child == js.Object) {
|
||||
return js.Object{
|
||||
.local = self,
|
||||
@@ -1054,7 +1083,7 @@ const Resolved = struct {
|
||||
class_id: u16,
|
||||
prototype_chain: []const @import("TaggedOpaque.zig").PrototypeChainEntry,
|
||||
finalizer_from_v8: ?*const fn (handle: ?*const v8.WeakCallbackInfo) callconv(.c) void = null,
|
||||
finalizer_from_zig: ?*const fn (ptr: *anyopaque) void = null,
|
||||
finalizer_from_zig: ?*const fn (ptr: *anyopaque, page: *Page) void = null,
|
||||
};
|
||||
pub fn resolveValue(value: anytype) Resolved {
|
||||
const T = bridge.Struct(@TypeOf(value));
|
||||
@@ -1093,14 +1122,14 @@ fn resolveT(comptime T: type, value: *anyopaque) Resolved {
|
||||
};
|
||||
}
|
||||
|
||||
fn conditionallyFlagHandoff(value: anytype) void {
|
||||
fn conditionallyReference(value: anytype) void {
|
||||
const T = bridge.Struct(@TypeOf(value));
|
||||
if (@hasField(T, "_v8_handoff")) {
|
||||
value._v8_handoff = true;
|
||||
if (@hasDecl(T, "acquireRef")) {
|
||||
value.acquireRef();
|
||||
return;
|
||||
}
|
||||
if (@hasField(T, "_proto")) {
|
||||
conditionallyFlagHandoff(value._proto);
|
||||
conditionallyReference(value._proto);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1201,13 +1230,20 @@ fn _debugValue(self: *const Local, js_val: js.Value, seen: *std.AutoHashMapUnman
|
||||
gop.value_ptr.* = {};
|
||||
}
|
||||
|
||||
const names_arr = js_obj.getOwnPropertyNames();
|
||||
const len = names_arr.len();
|
||||
|
||||
if (depth > 20) {
|
||||
return writer.writeAll("...deeply nested object...");
|
||||
}
|
||||
const own_len = js_obj.getOwnPropertyNames().len();
|
||||
|
||||
const names_arr = js_obj.getOwnPropertyNames() catch {
|
||||
return writer.writeAll("...invalid object...");
|
||||
};
|
||||
const len = names_arr.len();
|
||||
|
||||
const own_len = blk: {
|
||||
const own_names = js_obj.getOwnPropertyNames() catch break :blk 0;
|
||||
break :blk own_names.len();
|
||||
};
|
||||
|
||||
if (own_len == 0) {
|
||||
const js_val_str = try js_val.toStringSlice();
|
||||
if (js_val_str.len > 2000) {
|
||||
@@ -1326,6 +1362,7 @@ pub const Scope = struct {
|
||||
handle_scope: js.HandleScope,
|
||||
|
||||
pub fn deinit(self: *Scope) void {
|
||||
v8.v8__Context__Exit(self.local.handle);
|
||||
self.handle_scope.deinit();
|
||||
}
|
||||
|
||||
|
||||
@@ -129,8 +129,14 @@ pub fn isNullOrUndefined(self: Object) bool {
|
||||
return v8.v8__Value__IsNullOrUndefined(@ptrCast(self.handle));
|
||||
}
|
||||
|
||||
pub fn getOwnPropertyNames(self: Object) js.Array {
|
||||
const handle = v8.v8__Object__GetOwnPropertyNames(self.handle, self.local.handle).?;
|
||||
pub fn getOwnPropertyNames(self: Object) !js.Array {
|
||||
const handle = v8.v8__Object__GetOwnPropertyNames(self.handle, self.local.handle) orelse {
|
||||
// This is almost always a fatal error case. Either we're in some exception
|
||||
// and things are messy, or we're shutting down, or someone has messed up
|
||||
// the object (like some WPT tests do).
|
||||
return error.TypeError;
|
||||
};
|
||||
|
||||
return .{
|
||||
.local = self.local,
|
||||
.handle = handle,
|
||||
@@ -145,8 +151,11 @@ pub fn getPropertyNames(self: Object) js.Array {
|
||||
};
|
||||
}
|
||||
|
||||
pub fn nameIterator(self: Object) NameIterator {
|
||||
const handle = v8.v8__Object__GetPropertyNames(self.handle, self.local.handle).?;
|
||||
pub fn nameIterator(self: Object) !NameIterator {
|
||||
const handle = v8.v8__Object__GetPropertyNames(self.handle, self.local.handle) orelse {
|
||||
// see getOwnPropertyNames above
|
||||
return error.TypeError;
|
||||
};
|
||||
const count = v8.v8__Array__Length(handle);
|
||||
|
||||
return .{
|
||||
|
||||
@@ -282,9 +282,13 @@ fn hasNamedIndexedGetter(comptime JsApi: type) bool {
|
||||
fn countExternalReferences() comptime_int {
|
||||
@setEvalBranchQuota(100_000);
|
||||
|
||||
// +1 for the illegal constructor callback
|
||||
var count: comptime_int = 1;
|
||||
var has_non_template_property: bool = false;
|
||||
var count: comptime_int = 0;
|
||||
|
||||
// +1 for the illegal constructor callback shared by various types
|
||||
count += 1;
|
||||
|
||||
// +1 for the noop function shared by various types
|
||||
count += 1;
|
||||
|
||||
inline for (JsApis) |JsApi| {
|
||||
// Constructor (only if explicit)
|
||||
@@ -304,17 +308,18 @@ fn countExternalReferences() comptime_int {
|
||||
const T = @TypeOf(value);
|
||||
if (T == bridge.Accessor) {
|
||||
count += 1; // getter
|
||||
if (value.setter != null) count += 1; // setter
|
||||
if (value.setter != null) {
|
||||
count += 1;
|
||||
}
|
||||
} else if (T == bridge.Function) {
|
||||
count += 1;
|
||||
} else if (T == bridge.Property) {
|
||||
if (value.template == false) {
|
||||
has_non_template_property = true;
|
||||
}
|
||||
} else if (T == bridge.Iterator) {
|
||||
count += 1;
|
||||
} else if (T == bridge.Indexed) {
|
||||
count += 1;
|
||||
if (value.enumerator != null) {
|
||||
count += 1;
|
||||
}
|
||||
} else if (T == bridge.NamedIndexed) {
|
||||
count += 1; // getter
|
||||
if (value.setter != null) count += 1;
|
||||
@@ -323,10 +328,6 @@ fn countExternalReferences() comptime_int {
|
||||
}
|
||||
}
|
||||
|
||||
if (has_non_template_property) {
|
||||
count += 1;
|
||||
}
|
||||
|
||||
// In debug mode, add unknown property callbacks for types without NamedIndexed
|
||||
if (comptime IS_DEBUG) {
|
||||
inline for (JsApis) |JsApi| {
|
||||
@@ -346,7 +347,8 @@ fn collectExternalReferences() [countExternalReferences()]isize {
|
||||
references[idx] = @bitCast(@intFromPtr(&illegalConstructorCallback));
|
||||
idx += 1;
|
||||
|
||||
var has_non_template_property = false;
|
||||
references[idx] = @bitCast(@intFromPtr(&bridge.Function.noopFunction));
|
||||
idx += 1;
|
||||
|
||||
inline for (JsApis) |JsApi| {
|
||||
if (@hasDecl(JsApi, "constructor")) {
|
||||
@@ -373,16 +375,16 @@ fn collectExternalReferences() [countExternalReferences()]isize {
|
||||
} else if (T == bridge.Function) {
|
||||
references[idx] = @bitCast(@intFromPtr(value.func));
|
||||
idx += 1;
|
||||
} else if (T == bridge.Property) {
|
||||
if (value.template == false) {
|
||||
has_non_template_property = true;
|
||||
}
|
||||
} else if (T == bridge.Iterator) {
|
||||
references[idx] = @bitCast(@intFromPtr(value.func));
|
||||
idx += 1;
|
||||
} else if (T == bridge.Indexed) {
|
||||
references[idx] = @bitCast(@intFromPtr(value.getter));
|
||||
idx += 1;
|
||||
if (value.enumerator) |enumerator| {
|
||||
references[idx] = @bitCast(@intFromPtr(enumerator));
|
||||
idx += 1;
|
||||
}
|
||||
} else if (T == bridge.NamedIndexed) {
|
||||
references[idx] = @bitCast(@intFromPtr(value.getter));
|
||||
idx += 1;
|
||||
@@ -398,11 +400,6 @@ fn collectExternalReferences() [countExternalReferences()]isize {
|
||||
}
|
||||
}
|
||||
|
||||
if (has_non_template_property) {
|
||||
references[idx] = @bitCast(@intFromPtr(&bridge.Property.getter));
|
||||
idx += 1;
|
||||
}
|
||||
|
||||
// In debug mode, collect unknown property callbacks for types without NamedIndexed
|
||||
if (comptime IS_DEBUG) {
|
||||
inline for (JsApis) |JsApi| {
|
||||
@@ -486,8 +483,8 @@ pub fn countInternalFields(comptime JsApi: type) u8 {
|
||||
|
||||
// Attaches JsApi members to the prototype template (normal case)
|
||||
fn attachClass(comptime JsApi: type, isolate: *v8.Isolate, template: *v8.FunctionTemplate) void {
|
||||
const target = v8.v8__FunctionTemplate__PrototypeTemplate(template);
|
||||
const instance = v8.v8__FunctionTemplate__InstanceTemplate(template);
|
||||
const prototype = v8.v8__FunctionTemplate__PrototypeTemplate(template);
|
||||
|
||||
const declarations = @typeInfo(JsApi).@"struct".decls;
|
||||
var has_named_index_getter = false;
|
||||
@@ -505,14 +502,14 @@ fn attachClass(comptime JsApi: type, isolate: *v8.Isolate, template: *v8.Functio
|
||||
if (value.static) {
|
||||
v8.v8__Template__SetAccessorProperty__DEFAULT(@ptrCast(template), js_name, getter_callback);
|
||||
} else {
|
||||
v8.v8__ObjectTemplate__SetAccessorProperty__DEFAULT(target, js_name, getter_callback);
|
||||
v8.v8__ObjectTemplate__SetAccessorProperty__DEFAULT(prototype, js_name, getter_callback);
|
||||
}
|
||||
} else {
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(value.static == false);
|
||||
}
|
||||
const setter_callback = @constCast(v8.v8__FunctionTemplate__New__Config(isolate, &.{ .callback = value.setter.? }).?);
|
||||
v8.v8__ObjectTemplate__SetAccessorProperty__DEFAULT2(target, js_name, getter_callback, setter_callback);
|
||||
v8.v8__ObjectTemplate__SetAccessorProperty__DEFAULT2(prototype, js_name, getter_callback, setter_callback);
|
||||
}
|
||||
},
|
||||
bridge.Function => {
|
||||
@@ -521,16 +518,16 @@ fn attachClass(comptime JsApi: type, isolate: *v8.Isolate, template: *v8.Functio
|
||||
if (value.static) {
|
||||
v8.v8__Template__Set(@ptrCast(template), js_name, @ptrCast(function_template), v8.None);
|
||||
} else {
|
||||
v8.v8__Template__Set(@ptrCast(target), js_name, @ptrCast(function_template), v8.None);
|
||||
v8.v8__Template__Set(@ptrCast(prototype), js_name, @ptrCast(function_template), v8.None);
|
||||
}
|
||||
},
|
||||
bridge.Indexed => {
|
||||
var configuration: v8.IndexedPropertyHandlerConfiguration = .{
|
||||
.getter = value.getter,
|
||||
.enumerator = value.enumerator,
|
||||
.setter = null,
|
||||
.query = null,
|
||||
.deleter = null,
|
||||
.enumerator = null,
|
||||
.definer = null,
|
||||
.descriptor = null,
|
||||
.data = null,
|
||||
@@ -559,7 +556,7 @@ fn attachClass(comptime JsApi: type, isolate: *v8.Isolate, template: *v8.Functio
|
||||
v8.v8__Symbol__GetAsyncIterator(isolate)
|
||||
else
|
||||
v8.v8__Symbol__GetIterator(isolate);
|
||||
v8.v8__Template__Set(@ptrCast(target), js_name, @ptrCast(function_template), v8.None);
|
||||
v8.v8__Template__Set(@ptrCast(prototype), js_name, @ptrCast(function_template), v8.None);
|
||||
},
|
||||
bridge.Property => {
|
||||
const js_value = switch (value.value) {
|
||||
@@ -568,22 +565,14 @@ fn attachClass(comptime JsApi: type, isolate: *v8.Isolate, template: *v8.Functio
|
||||
};
|
||||
const js_name = v8.v8__String__NewFromUtf8(isolate, name.ptr, v8.kNormal, @intCast(name.len));
|
||||
|
||||
if (value.template == false) {
|
||||
// not defined on the template, only on the instance. This
|
||||
// is like an Accessor, but because the value is known at
|
||||
// compile time, we skip _a lot_ of code and quickly return
|
||||
// the hard-coded value
|
||||
const getter_callback = @constCast(v8.v8__FunctionTemplate__New__Config(isolate, &.{
|
||||
.callback = bridge.Property.getter,
|
||||
.data = js_value,
|
||||
.side_effect_type = v8.kSideEffectType_HasSideEffectToReceiver,
|
||||
}));
|
||||
v8.v8__ObjectTemplate__SetAccessorProperty__DEFAULT(target, js_name, getter_callback);
|
||||
} else {
|
||||
// apply it both to the type itself
|
||||
{
|
||||
const flags = if (value.readonly) v8.ReadOnly + v8.DontDelete else 0;
|
||||
v8.v8__Template__Set(@ptrCast(prototype), js_name, js_value, flags);
|
||||
}
|
||||
|
||||
if (value.template) {
|
||||
// apply it both to the type itself (e.g. Node.Elem)
|
||||
v8.v8__Template__Set(@ptrCast(template), js_name, js_value, v8.ReadOnly + v8.DontDelete);
|
||||
// and to instances of the type
|
||||
v8.v8__Template__Set(@ptrCast(target), js_name, js_value, v8.ReadOnly + v8.DontDelete);
|
||||
}
|
||||
},
|
||||
bridge.Constructor => {}, // already handled in generateConstructor
|
||||
|
||||
@@ -134,4 +134,17 @@ pub const Caught = struct {
|
||||
try writer.write(prefix ++ ".line", self.line);
|
||||
try writer.write(prefix ++ ".caught", self.caught);
|
||||
}
|
||||
|
||||
pub fn jsonStringify(self: Caught, jw: anytype) !void {
|
||||
try jw.beginObject();
|
||||
try jw.objectField("exception");
|
||||
try jw.write(self.exception);
|
||||
try jw.objectField("stack");
|
||||
try jw.write(self.stack);
|
||||
try jw.objectField("line");
|
||||
try jw.write(self.line);
|
||||
try jw.objectField("caught");
|
||||
try jw.write(self.caught);
|
||||
try jw.endObject();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -46,8 +46,8 @@ pub fn Builder(comptime T: type) type {
|
||||
return Function.init(T, func, opts);
|
||||
}
|
||||
|
||||
pub fn indexed(comptime getter_func: anytype, comptime opts: Indexed.Opts) Indexed {
|
||||
return Indexed.init(T, getter_func, opts);
|
||||
pub fn indexed(comptime getter_func: anytype, comptime enumerator_func: anytype, comptime opts: Indexed.Opts) Indexed {
|
||||
return Indexed.init(T, getter_func, enumerator_func, opts);
|
||||
}
|
||||
|
||||
pub fn namedIndexed(comptime getter_func: anytype, setter_func: anytype, deleter_func: anytype, comptime opts: NamedIndexed.Opts) NamedIndexed {
|
||||
@@ -104,11 +104,11 @@ pub fn Builder(comptime T: type) type {
|
||||
return entries;
|
||||
}
|
||||
|
||||
pub fn finalizer(comptime func: *const fn (self: *T, shutdown: bool) void) Finalizer {
|
||||
pub fn finalizer(comptime func: *const fn (self: *T, shutdown: bool, page: *Page) void) Finalizer {
|
||||
return .{
|
||||
.from_zig = struct {
|
||||
fn wrap(ptr: *anyopaque) void {
|
||||
func(@ptrCast(@alignCast(ptr)), true);
|
||||
fn wrap(ptr: *anyopaque, page: *Page) void {
|
||||
func(@ptrCast(@alignCast(ptr)), true, page);
|
||||
}
|
||||
}.wrap,
|
||||
|
||||
@@ -120,7 +120,7 @@ pub fn Builder(comptime T: type) type {
|
||||
const ctx = fc.ctx;
|
||||
const value_ptr = fc.ptr;
|
||||
if (ctx.finalizer_callbacks.contains(@intFromPtr(value_ptr))) {
|
||||
func(@ptrCast(@alignCast(value_ptr)), false);
|
||||
func(@ptrCast(@alignCast(value_ptr)), false, ctx.page);
|
||||
ctx.release(value_ptr);
|
||||
} else {
|
||||
// A bit weird, but v8 _requires_ that we release it
|
||||
@@ -160,6 +160,7 @@ pub const Constructor = struct {
|
||||
pub const Function = struct {
|
||||
static: bool,
|
||||
arity: usize,
|
||||
noop: bool = false,
|
||||
cache: ?Caller.Function.Opts.Caching = null,
|
||||
func: *const fn (?*const v8.FunctionCallbackInfo) callconv(.c) void,
|
||||
|
||||
@@ -168,7 +169,7 @@ pub const Function = struct {
|
||||
.cache = opts.cache,
|
||||
.static = opts.static,
|
||||
.arity = getArity(@TypeOf(func)),
|
||||
.func = struct {
|
||||
.func = if (opts.noop) noopFunction else struct {
|
||||
fn wrap(handle: ?*const v8.FunctionCallbackInfo) callconv(.c) void {
|
||||
Caller.Function.call(T, handle.?, func, opts);
|
||||
}
|
||||
@@ -176,6 +177,8 @@ pub const Function = struct {
|
||||
};
|
||||
}
|
||||
|
||||
pub fn noopFunction(_: ?*const v8.FunctionCallbackInfo) callconv(.c) void {}
|
||||
|
||||
fn getArity(comptime T: type) usize {
|
||||
var count: usize = 0;
|
||||
var params = @typeInfo(T).@"fn".params;
|
||||
@@ -227,26 +230,44 @@ pub const Accessor = struct {
|
||||
|
||||
pub const Indexed = struct {
|
||||
getter: *const fn (idx: u32, handle: ?*const v8.PropertyCallbackInfo) callconv(.c) u8,
|
||||
enumerator: ?*const fn (handle: ?*const v8.PropertyCallbackInfo) callconv(.c) u8,
|
||||
|
||||
const Opts = struct {
|
||||
as_typed_array: bool = false,
|
||||
null_as_undefined: bool = false,
|
||||
};
|
||||
|
||||
fn init(comptime T: type, comptime getter: anytype, comptime opts: Opts) Indexed {
|
||||
return .{ .getter = struct {
|
||||
fn wrap(idx: u32, handle: ?*const v8.PropertyCallbackInfo) callconv(.c) u8 {
|
||||
const v8_isolate = v8.v8__PropertyCallbackInfo__GetIsolate(handle).?;
|
||||
var caller: Caller = undefined;
|
||||
caller.init(v8_isolate);
|
||||
defer caller.deinit();
|
||||
fn init(comptime T: type, comptime getter: anytype, comptime enumerator: anytype, comptime opts: Opts) Indexed {
|
||||
var indexed = Indexed{
|
||||
.enumerator = null,
|
||||
.getter = struct {
|
||||
fn wrap(idx: u32, handle: ?*const v8.PropertyCallbackInfo) callconv(.c) u8 {
|
||||
const v8_isolate = v8.v8__PropertyCallbackInfo__GetIsolate(handle).?;
|
||||
var caller: Caller = undefined;
|
||||
caller.init(v8_isolate);
|
||||
defer caller.deinit();
|
||||
|
||||
return caller.getIndex(T, getter, idx, handle.?, .{
|
||||
.as_typed_array = opts.as_typed_array,
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
}
|
||||
}.wrap };
|
||||
return caller.getIndex(T, getter, idx, handle.?, .{
|
||||
.as_typed_array = opts.as_typed_array,
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
}
|
||||
}.wrap,
|
||||
};
|
||||
|
||||
if (@typeInfo(@TypeOf(enumerator)) != .null) {
|
||||
indexed.enumerator = struct {
|
||||
fn wrap(handle: ?*const v8.PropertyCallbackInfo) callconv(.c) u8 {
|
||||
const v8_isolate = v8.v8__PropertyCallbackInfo__GetIsolate(handle).?;
|
||||
var caller: Caller = undefined;
|
||||
caller.init(v8_isolate);
|
||||
defer caller.deinit();
|
||||
return caller.getEnumerator(T, enumerator, handle.?, .{});
|
||||
}
|
||||
}.wrap;
|
||||
}
|
||||
|
||||
return indexed;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -367,6 +388,7 @@ pub const Callable = struct {
|
||||
pub const Property = struct {
|
||||
value: Value,
|
||||
template: bool,
|
||||
readonly: bool,
|
||||
|
||||
const Value = union(enum) {
|
||||
null,
|
||||
@@ -378,27 +400,22 @@ pub const Property = struct {
|
||||
|
||||
const Opts = struct {
|
||||
template: bool,
|
||||
readonly: bool = true,
|
||||
};
|
||||
|
||||
fn init(value: Value, opts: Opts) Property {
|
||||
return .{
|
||||
.value = value,
|
||||
.template = opts.template,
|
||||
.readonly = opts.readonly,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn getter(handle: ?*const v8.FunctionCallbackInfo) callconv(.c) void {
|
||||
const value = v8.v8__FunctionCallbackInfo__Data(handle.?);
|
||||
var rv: v8.ReturnValue = undefined;
|
||||
v8.v8__FunctionCallbackInfo__GetReturnValue(handle.?, &rv);
|
||||
v8.v8__ReturnValue__Set(rv, value);
|
||||
}
|
||||
};
|
||||
|
||||
const Finalizer = struct {
|
||||
// The finalizer wrapper when called fro Zig. This is only called on
|
||||
// Context.deinit
|
||||
from_zig: *const fn (ctx: *anyopaque) void,
|
||||
from_zig: *const fn (ctx: *anyopaque, page: *Page) void,
|
||||
|
||||
// The finalizer wrapper when called from V8. This may never be called
|
||||
// (hence why we fallback to calling in Context.denit). If it is called,
|
||||
@@ -713,6 +730,7 @@ pub const JsApis = flattenTypes(&.{
|
||||
@import("../webapi/css/CSSStyleRule.zig"),
|
||||
@import("../webapi/css/CSSStyleSheet.zig"),
|
||||
@import("../webapi/css/CSSStyleProperties.zig"),
|
||||
@import("../webapi/css/FontFaceSet.zig"),
|
||||
@import("../webapi/css/MediaQueryList.zig"),
|
||||
@import("../webapi/css/StyleSheetList.zig"),
|
||||
@import("../webapi/Document.zig"),
|
||||
@@ -749,6 +767,7 @@ pub const JsApis = flattenTypes(&.{
|
||||
@import("../webapi/element/html/Custom.zig"),
|
||||
@import("../webapi/element/html/Data.zig"),
|
||||
@import("../webapi/element/html/DataList.zig"),
|
||||
@import("../webapi/element/html/Details.zig"),
|
||||
@import("../webapi/element/html/Dialog.zig"),
|
||||
@import("../webapi/element/html/Directory.zig"),
|
||||
@import("../webapi/element/html/DList.zig"),
|
||||
@@ -808,6 +827,8 @@ pub const JsApis = flattenTypes(&.{
|
||||
@import("../webapi/element/svg/Generic.zig"),
|
||||
@import("../webapi/encoding/TextDecoder.zig"),
|
||||
@import("../webapi/encoding/TextEncoder.zig"),
|
||||
@import("../webapi/encoding/TextEncoderStream.zig"),
|
||||
@import("../webapi/encoding/TextDecoderStream.zig"),
|
||||
@import("../webapi/Event.zig"),
|
||||
@import("../webapi/event/CompositionEvent.zig"),
|
||||
@import("../webapi/event/CustomEvent.zig"),
|
||||
@@ -844,6 +865,10 @@ pub const JsApis = flattenTypes(&.{
|
||||
@import("../webapi/streams/ReadableStream.zig"),
|
||||
@import("../webapi/streams/ReadableStreamDefaultReader.zig"),
|
||||
@import("../webapi/streams/ReadableStreamDefaultController.zig"),
|
||||
@import("../webapi/streams/WritableStream.zig"),
|
||||
@import("../webapi/streams/WritableStreamDefaultWriter.zig"),
|
||||
@import("../webapi/streams/WritableStreamDefaultController.zig"),
|
||||
@import("../webapi/streams/TransformStream.zig"),
|
||||
@import("../webapi/Node.zig"),
|
||||
@import("../webapi/storage/storage.zig"),
|
||||
@import("../webapi/URL.zig"),
|
||||
@@ -857,6 +882,7 @@ pub const JsApis = flattenTypes(&.{
|
||||
@import("../webapi/IdleDeadline.zig"),
|
||||
@import("../webapi/Blob.zig"),
|
||||
@import("../webapi/File.zig"),
|
||||
@import("../webapi/FileReader.zig"),
|
||||
@import("../webapi/Screen.zig"),
|
||||
@import("../webapi/VisualViewport.zig"),
|
||||
@import("../webapi/PerformanceObserver.zig"),
|
||||
@@ -865,6 +891,8 @@ pub const JsApis = flattenTypes(&.{
|
||||
@import("../webapi/navigation/NavigationActivation.zig"),
|
||||
@import("../webapi/canvas/CanvasRenderingContext2D.zig"),
|
||||
@import("../webapi/canvas/WebGLRenderingContext.zig"),
|
||||
@import("../webapi/canvas/OffscreenCanvas.zig"),
|
||||
@import("../webapi/canvas/OffscreenCanvasRenderingContext2D.zig"),
|
||||
@import("../webapi/SubtleCrypto.zig"),
|
||||
@import("../webapi/Selection.zig"),
|
||||
@import("../webapi/ImageData.zig"),
|
||||
|
||||
@@ -168,6 +168,16 @@ pub fn ArrayBufferRef(comptime kind: ArrayType) type {
|
||||
};
|
||||
}
|
||||
|
||||
// If a WebAPI takes a []const u8, then we'll coerce any JS value to that string
|
||||
// so null -> "null". But if a WebAPI takes an optional string, ?[]const u8,
|
||||
// how should we handle null? If the parameter _isn't_ passed, then it's obvious
|
||||
// that it should be null, but what if `null` is passed? It's ambiguous, should
|
||||
// that be null, or "null"? It could depend on the api. So, `null` passed to
|
||||
// ?[]const u8 will be `null`. If you want it to be "null", use a `.js.NullableString`.
|
||||
pub const NullableString = struct {
|
||||
value: []const u8,
|
||||
};
|
||||
|
||||
pub const Exception = struct {
|
||||
local: *const Local,
|
||||
handle: *const v8.Value,
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
const std = @import("std");
|
||||
|
||||
const Page = @import("Page.zig");
|
||||
const CData = @import("webapi/CData.zig");
|
||||
const Element = @import("webapi/Element.zig");
|
||||
const Node = @import("webapi/Node.zig");
|
||||
|
||||
@@ -35,7 +36,6 @@ const State = struct {
|
||||
|
||||
list_depth: usize = 0,
|
||||
list_stack: [32]ListState = undefined,
|
||||
in_pre: bool = false,
|
||||
pre_node: ?*Node = null,
|
||||
in_code: bool = false,
|
||||
in_table: bool = false,
|
||||
@@ -46,7 +46,7 @@ const State = struct {
|
||||
|
||||
fn isBlock(tag: Element.Tag) bool {
|
||||
return switch (tag) {
|
||||
.p, .div, .section, .article, .header, .footer, .nav, .aside, .h1, .h2, .h3, .h4, .h5, .h6, .ul, .ol, .blockquote, .pre, .table, .hr => true,
|
||||
.p, .div, .section, .article, .main, .header, .footer, .nav, .aside, .h1, .h2, .h3, .h4, .h5, .h6, .ul, .ol, .blockquote, .pre, .table, .hr => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
@@ -58,6 +58,67 @@ fn shouldAddSpacing(tag: Element.Tag) bool {
|
||||
};
|
||||
}
|
||||
|
||||
fn isLayoutBlock(tag: Element.Tag) bool {
|
||||
return switch (tag) {
|
||||
.main, .section, .article, .nav, .aside, .header, .footer, .div, .ul, .ol => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
fn isStandaloneAnchor(el: *Element) bool {
|
||||
const node = el.asNode();
|
||||
const parent = node.parentNode() orelse return false;
|
||||
const parent_el = parent.is(Element) orelse return false;
|
||||
|
||||
if (!isLayoutBlock(parent_el.getTag())) return false;
|
||||
|
||||
var prev = node.previousSibling();
|
||||
while (prev) |p| : (prev = p.previousSibling()) {
|
||||
if (isSignificantText(p)) return false;
|
||||
if (p.is(Element)) |pe| {
|
||||
if (isVisibleElement(pe)) break;
|
||||
}
|
||||
}
|
||||
|
||||
var next = node.nextSibling();
|
||||
while (next) |n| : (next = n.nextSibling()) {
|
||||
if (isSignificantText(n)) return false;
|
||||
if (n.is(Element)) |ne| {
|
||||
if (isVisibleElement(ne)) break;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
fn isSignificantText(node: *Node) bool {
|
||||
const text = node.is(Node.CData.Text) orelse return false;
|
||||
return !isAllWhitespace(text.getWholeText());
|
||||
}
|
||||
|
||||
fn isVisibleElement(el: *Element) bool {
|
||||
return switch (el.getTag()) {
|
||||
.script, .style, .noscript, .template, .head, .meta, .link, .title, .svg => false,
|
||||
else => true,
|
||||
};
|
||||
}
|
||||
|
||||
fn isAllWhitespace(text: []const u8) bool {
|
||||
return for (text) |c| {
|
||||
if (!std.ascii.isWhitespace(c)) break false;
|
||||
} else true;
|
||||
}
|
||||
|
||||
fn hasBlockDescendant(node: *Node) bool {
|
||||
var it = node.childrenIterator();
|
||||
return while (it.next()) |child| {
|
||||
if (child.is(Element)) |el| {
|
||||
if (isBlock(el.getTag())) break true;
|
||||
if (hasBlockDescendant(child)) break true;
|
||||
}
|
||||
} else false;
|
||||
}
|
||||
|
||||
fn ensureNewline(state: *State, writer: *std.Io.Writer) !void {
|
||||
if (!state.last_char_was_newline) {
|
||||
try writer.writeByte('\n');
|
||||
@@ -84,18 +145,16 @@ fn render(node: *Node, state: *State, writer: *std.Io.Writer, page: *Page) error
|
||||
},
|
||||
.cdata => |cd| {
|
||||
if (node.is(Node.CData.Text)) |_| {
|
||||
var text = cd.getData();
|
||||
if (state.in_pre) {
|
||||
if (state.pre_node) |pre| {
|
||||
if (node.parentNode() == pre and node.nextSibling() == null) {
|
||||
text = std.mem.trimRight(u8, text, " \t\r\n");
|
||||
}
|
||||
var text = cd.getData().str();
|
||||
if (state.pre_node) |pre| {
|
||||
if (node.parentNode() == pre and node.nextSibling() == null) {
|
||||
text = std.mem.trimRight(u8, text, " \t\r\n");
|
||||
}
|
||||
}
|
||||
try renderText(text, state, writer);
|
||||
}
|
||||
},
|
||||
else => {}, // Ignore other node types
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,22 +168,15 @@ fn renderChildren(parent: *Node, state: *State, writer: *std.Io.Writer, page: *P
|
||||
fn renderElement(el: *Element, state: *State, writer: *std.Io.Writer, page: *Page) !void {
|
||||
const tag = el.getTag();
|
||||
|
||||
// Skip hidden/metadata elements
|
||||
switch (tag) {
|
||||
.script, .style, .noscript, .template, .head, .meta, .link, .title, .svg => return,
|
||||
else => {},
|
||||
}
|
||||
if (!isVisibleElement(el)) return;
|
||||
|
||||
// --- Opening Tag Logic ---
|
||||
|
||||
// Ensure block elements start on a new line (double newline for paragraphs etc)
|
||||
if (isBlock(tag)) {
|
||||
if (!state.in_table) {
|
||||
try ensureNewline(state, writer);
|
||||
if (shouldAddSpacing(tag)) {
|
||||
// Add an extra newline for spacing between blocks
|
||||
try writer.writeByte('\n');
|
||||
}
|
||||
if (isBlock(tag) and !state.in_table) {
|
||||
try ensureNewline(state, writer);
|
||||
if (shouldAddSpacing(tag)) {
|
||||
try writer.writeByte('\n');
|
||||
}
|
||||
} else if (tag == .li or tag == .tr) {
|
||||
try ensureNewline(state, writer);
|
||||
@@ -154,14 +206,10 @@ fn renderElement(el: *Element, state: *State, writer: *std.Io.Writer, page: *Pag
|
||||
const indent = if (state.list_depth > 0) state.list_depth - 1 else 0;
|
||||
for (0..indent) |_| try writer.writeAll(" ");
|
||||
|
||||
if (state.list_depth > 0) {
|
||||
if (state.list_depth > 0 and state.list_stack[state.list_depth - 1].type == .ordered) {
|
||||
const current_list = &state.list_stack[state.list_depth - 1];
|
||||
if (current_list.type == .ordered) {
|
||||
try writer.print("{d}. ", .{current_list.index});
|
||||
current_list.index += 1;
|
||||
} else {
|
||||
try writer.writeAll("- ");
|
||||
}
|
||||
try writer.print("{d}. ", .{current_list.index});
|
||||
current_list.index += 1;
|
||||
} else {
|
||||
try writer.writeAll("- ");
|
||||
}
|
||||
@@ -187,12 +235,11 @@ fn renderElement(el: *Element, state: *State, writer: *std.Io.Writer, page: *Pag
|
||||
},
|
||||
.pre => {
|
||||
try writer.writeAll("```\n");
|
||||
state.in_pre = true;
|
||||
state.pre_node = el.asNode();
|
||||
state.last_char_was_newline = true;
|
||||
},
|
||||
.code => {
|
||||
if (!state.in_pre) {
|
||||
if (state.pre_node == null) {
|
||||
try writer.writeByte('`');
|
||||
state.in_code = true;
|
||||
state.last_char_was_newline = false;
|
||||
@@ -213,7 +260,7 @@ fn renderElement(el: *Element, state: *State, writer: *std.Io.Writer, page: *Pag
|
||||
.hr => {
|
||||
try writer.writeAll("---\n");
|
||||
state.last_char_was_newline = true;
|
||||
return; // Void element
|
||||
return;
|
||||
},
|
||||
.br => {
|
||||
if (state.in_table) {
|
||||
@@ -222,7 +269,7 @@ fn renderElement(el: *Element, state: *State, writer: *std.Io.Writer, page: *Pag
|
||||
try writer.writeByte('\n');
|
||||
state.last_char_was_newline = true;
|
||||
}
|
||||
return; // Void element
|
||||
return;
|
||||
},
|
||||
.img => {
|
||||
try writer.writeAll(";
|
||||
try writer.writeAll(href);
|
||||
try writer.writeAll("))\n");
|
||||
state.last_char_was_newline = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (isStandaloneAnchor(el)) {
|
||||
if (!state.last_char_was_newline) try writer.writeByte('\n');
|
||||
try writer.writeByte('[');
|
||||
try renderChildren(el.asNode(), state, writer, page);
|
||||
try writer.writeAll("](");
|
||||
if (el.getAttributeSafe(comptime .wrap("href"))) |href| {
|
||||
try writer.writeAll(href);
|
||||
}
|
||||
try writer.writeAll(")\n");
|
||||
state.last_char_was_newline = true;
|
||||
return;
|
||||
}
|
||||
|
||||
try writer.writeByte('[');
|
||||
try renderChildren(el.asNode(), state, writer, page);
|
||||
try writer.writeAll("](");
|
||||
@@ -249,15 +322,11 @@ fn renderElement(el: *Element, state: *State, writer: *std.Io.Writer, page: *Pag
|
||||
return;
|
||||
},
|
||||
.input => {
|
||||
if (el.getAttributeSafe(comptime .wrap("type"))) |type_attr| {
|
||||
if (std.ascii.eqlIgnoreCase(type_attr, "checkbox")) {
|
||||
if (el.getAttributeSafe(comptime .wrap("checked"))) |_| {
|
||||
try writer.writeAll("[x] ");
|
||||
} else {
|
||||
try writer.writeAll("[ ] ");
|
||||
}
|
||||
state.last_char_was_newline = false;
|
||||
}
|
||||
const type_attr = el.getAttributeSafe(comptime .wrap("type")) orelse return;
|
||||
if (std.ascii.eqlIgnoreCase(type_attr, "checkbox")) {
|
||||
const checked = el.getAttributeSafe(comptime .wrap("checked")) != null;
|
||||
try writer.writeAll(if (checked) "[x] " else "[ ] ");
|
||||
state.last_char_was_newline = false;
|
||||
}
|
||||
return;
|
||||
},
|
||||
@@ -276,12 +345,11 @@ fn renderElement(el: *Element, state: *State, writer: *std.Io.Writer, page: *Pag
|
||||
try writer.writeByte('\n');
|
||||
}
|
||||
try writer.writeAll("```\n");
|
||||
state.in_pre = false;
|
||||
state.pre_node = null;
|
||||
state.last_char_was_newline = true;
|
||||
},
|
||||
.code => {
|
||||
if (!state.in_pre) {
|
||||
if (state.pre_node == null) {
|
||||
try writer.writeByte('`');
|
||||
state.in_code = false;
|
||||
state.last_char_was_newline = false;
|
||||
@@ -310,8 +378,7 @@ fn renderElement(el: *Element, state: *State, writer: *std.Io.Writer, page: *Pag
|
||||
try writer.writeByte('\n');
|
||||
if (state.table_row_index == 0) {
|
||||
try writer.writeByte('|');
|
||||
var i: usize = 0;
|
||||
while (i < state.table_col_count) : (i += 1) {
|
||||
for (0..state.table_col_count) |_| {
|
||||
try writer.writeAll("---|");
|
||||
}
|
||||
try writer.writeByte('\n');
|
||||
@@ -328,32 +395,22 @@ fn renderElement(el: *Element, state: *State, writer: *std.Io.Writer, page: *Pag
|
||||
}
|
||||
|
||||
// Post-block newlines
|
||||
if (isBlock(tag)) {
|
||||
if (!state.in_table) {
|
||||
try ensureNewline(state, writer);
|
||||
}
|
||||
if (isBlock(tag) and !state.in_table) {
|
||||
try ensureNewline(state, writer);
|
||||
}
|
||||
}
|
||||
|
||||
fn renderText(text: []const u8, state: *State, writer: *std.Io.Writer) !void {
|
||||
if (text.len == 0) return;
|
||||
|
||||
if (state.in_pre) {
|
||||
if (state.pre_node) |_| {
|
||||
try writer.writeAll(text);
|
||||
if (text.len > 0 and text[text.len - 1] == '\n') {
|
||||
state.last_char_was_newline = true;
|
||||
} else {
|
||||
state.last_char_was_newline = false;
|
||||
}
|
||||
state.last_char_was_newline = text[text.len - 1] == '\n';
|
||||
return;
|
||||
}
|
||||
|
||||
// Check for pure whitespace
|
||||
const is_all_whitespace = for (text) |c| {
|
||||
if (!std.ascii.isWhitespace(c)) break false;
|
||||
} else true;
|
||||
|
||||
if (is_all_whitespace) {
|
||||
if (isAllWhitespace(text)) {
|
||||
if (!state.last_char_was_newline) {
|
||||
try writer.writeByte(' ');
|
||||
}
|
||||
@@ -364,13 +421,7 @@ fn renderText(text: []const u8, state: *State, writer: *std.Io.Writer) !void {
|
||||
var it = std.mem.tokenizeAny(u8, text, " \t\n\r");
|
||||
var first = true;
|
||||
while (it.next()) |word| {
|
||||
if (first) {
|
||||
if (!state.last_char_was_newline) {
|
||||
if (text.len > 0 and std.ascii.isWhitespace(text[0])) {
|
||||
try writer.writeByte(' ');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!first or (!state.last_char_was_newline and std.ascii.isWhitespace(text[0]))) {
|
||||
try writer.writeByte(' ');
|
||||
}
|
||||
|
||||
@@ -380,10 +431,8 @@ fn renderText(text: []const u8, state: *State, writer: *std.Io.Writer) !void {
|
||||
}
|
||||
|
||||
// Handle trailing whitespace from the original text
|
||||
if (!first and !state.last_char_was_newline) {
|
||||
if (text.len > 0 and std.ascii.isWhitespace(text[text.len - 1])) {
|
||||
try writer.writeByte(' ');
|
||||
}
|
||||
if (!first and !state.last_char_was_newline and std.ascii.isWhitespace(text[text.len - 1])) {
|
||||
try writer.writeByte(' ');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -415,35 +464,35 @@ fn testMarkdownHTML(html: []const u8, expected: []const u8) !void {
|
||||
try testing.expectString(expected, aw.written());
|
||||
}
|
||||
|
||||
test "markdown: basic" {
|
||||
test "browser.markdown: basic" {
|
||||
try testMarkdownHTML("Hello world", "Hello world\n");
|
||||
}
|
||||
|
||||
test "markdown: whitespace" {
|
||||
test "browser.markdown: whitespace" {
|
||||
try testMarkdownHTML("<span>A</span> <span>B</span>", "A B\n");
|
||||
}
|
||||
|
||||
test "markdown: escaping" {
|
||||
test "browser.markdown: escaping" {
|
||||
try testMarkdownHTML("<p># Not a header</p>", "\n\\# Not a header\n");
|
||||
}
|
||||
|
||||
test "markdown: strikethrough" {
|
||||
test "browser.markdown: strikethrough" {
|
||||
try testMarkdownHTML("<s>deleted</s>", "~~deleted~~\n");
|
||||
}
|
||||
|
||||
test "markdown: task list" {
|
||||
test "browser.markdown: task list" {
|
||||
try testMarkdownHTML(
|
||||
\\<input type="checkbox" checked><input type="checkbox">
|
||||
, "[x] [ ] \n");
|
||||
}
|
||||
|
||||
test "markdown: ordered list" {
|
||||
test "browser.markdown: ordered list" {
|
||||
try testMarkdownHTML(
|
||||
\\<ol><li>First</li><li>Second</li></ol>
|
||||
, "1. First\n2. Second\n");
|
||||
}
|
||||
|
||||
test "markdown: table" {
|
||||
test "browser.markdown: table" {
|
||||
try testMarkdownHTML(
|
||||
\\<table><thead><tr><th>Head 1</th><th>Head 2</th></tr></thead>
|
||||
\\<tbody><tr><td>Cell 1</td><td>Cell 2</td></tr></tbody></table>
|
||||
@@ -456,7 +505,7 @@ test "markdown: table" {
|
||||
);
|
||||
}
|
||||
|
||||
test "markdown: nested lists" {
|
||||
test "browser.markdown: nested lists" {
|
||||
try testMarkdownHTML(
|
||||
\\<ul><li>Parent<ul><li>Child</li></ul></li></ul>
|
||||
,
|
||||
@@ -466,19 +515,19 @@ test "markdown: nested lists" {
|
||||
);
|
||||
}
|
||||
|
||||
test "markdown: blockquote" {
|
||||
test "browser.markdown: blockquote" {
|
||||
try testMarkdownHTML("<blockquote>Hello world</blockquote>", "\n> Hello world\n");
|
||||
}
|
||||
|
||||
test "markdown: links" {
|
||||
test "browser.markdown: links" {
|
||||
try testMarkdownHTML("<a href=\"https://lightpanda.io\">Lightpanda</a>", "[Lightpanda](https://lightpanda.io)\n");
|
||||
}
|
||||
|
||||
test "markdown: images" {
|
||||
test "browser.markdown: images" {
|
||||
try testMarkdownHTML("<img src=\"logo.png\" alt=\"Logo\">", "\n");
|
||||
}
|
||||
|
||||
test "markdown: headings" {
|
||||
test "browser.markdown: headings" {
|
||||
try testMarkdownHTML("<h1>Title</h1><h2>Subtitle</h2>",
|
||||
\\
|
||||
\\# Title
|
||||
@@ -488,7 +537,7 @@ test "markdown: headings" {
|
||||
);
|
||||
}
|
||||
|
||||
test "markdown: code" {
|
||||
test "browser.markdown: code" {
|
||||
try testMarkdownHTML(
|
||||
\\<p>Use git push</p>
|
||||
\\<pre><code>line 1
|
||||
@@ -504,3 +553,55 @@ test "markdown: code" {
|
||||
\\
|
||||
);
|
||||
}
|
||||
|
||||
test "browser.markdown: block link" {
|
||||
try testMarkdownHTML(
|
||||
\\<a href="https://example.com">
|
||||
\\ <h3>Title</h3>
|
||||
\\ <p>Description</p>
|
||||
\\</a>
|
||||
,
|
||||
\\
|
||||
\\### Title
|
||||
\\
|
||||
\\Description
|
||||
\\([Link](https://example.com))
|
||||
\\
|
||||
);
|
||||
}
|
||||
|
||||
test "browser.markdown: inline link" {
|
||||
try testMarkdownHTML(
|
||||
\\<p>Visit <a href="https://example.com">Example</a>.</p>
|
||||
,
|
||||
\\
|
||||
\\Visit [Example](https://example.com).
|
||||
\\
|
||||
);
|
||||
}
|
||||
|
||||
test "browser.markdown: standalone anchors" {
|
||||
// Inside main, with whitespace between anchors -> treated as blocks
|
||||
try testMarkdownHTML(
|
||||
\\<main>
|
||||
\\ <a href="1">Link 1</a>
|
||||
\\ <a href="2">Link 2</a>
|
||||
\\</main>
|
||||
,
|
||||
\\[Link 1](1)
|
||||
\\[Link 2](2)
|
||||
\\
|
||||
);
|
||||
}
|
||||
|
||||
test "browser.markdown: mixed anchors in main" {
|
||||
// Anchors surrounded by text should remain inline
|
||||
try testMarkdownHTML(
|
||||
\\<main>
|
||||
\\ Welcome <a href="1">Link 1</a>.
|
||||
\\</main>
|
||||
,
|
||||
\\Welcome [Link 1](1).
|
||||
\\
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,13 +3,67 @@
|
||||
|
||||
<script id=animation>
|
||||
let a1 = document.createElement('div').animate(null, null);
|
||||
testing.expectEqual('finished', a1.playState);
|
||||
testing.expectEqual('idle', a1.playState);
|
||||
|
||||
let cb = [];
|
||||
a1.ready.then(() => { cb.push('ready') });
|
||||
a1.finished.then((x) => {
|
||||
cb.push('finished');
|
||||
cb.push(a1.playState);
|
||||
cb.push(x == a1);
|
||||
});
|
||||
testing.eventually(() => testing.expectEqual(['finished', true], cb));
|
||||
a1.ready.then(() => {
|
||||
cb.push(a1.playState);
|
||||
a1.play();
|
||||
cb.push(a1.playState);
|
||||
});
|
||||
testing.eventually(() => testing.expectEqual(['idle', 'running', 'finished', true], cb));
|
||||
</script>
|
||||
|
||||
<script id=startTime>
|
||||
let a2 = document.createElement('div').animate(null, null);
|
||||
// startTime defaults to null
|
||||
testing.expectEqual(null, a2.startTime);
|
||||
// startTime is settable
|
||||
a2.startTime = 42.5;
|
||||
testing.expectEqual(42.5, a2.startTime);
|
||||
// startTime can be reset to null
|
||||
a2.startTime = null;
|
||||
testing.expectEqual(null, a2.startTime);
|
||||
</script>
|
||||
|
||||
<script id=onfinish>
|
||||
let a3 = document.createElement('div').animate(null, null);
|
||||
// onfinish defaults to null
|
||||
testing.expectEqual(null, a3.onfinish);
|
||||
|
||||
let calls = [];
|
||||
// onfinish callback should be scheduled and called asynchronously
|
||||
a3.onfinish = function() { calls.push('finish'); };
|
||||
a3.play();
|
||||
testing.eventually(() => testing.expectEqual(['finish'], calls));
|
||||
</script>
|
||||
|
||||
<script id=pause>
|
||||
let a4 = document.createElement('div').animate(null, null);
|
||||
let cb4 = [];
|
||||
a4.finished.then((x) => { cb4.push(a4.playState) });
|
||||
a4.ready.then(() => {
|
||||
a4.play();
|
||||
cb4.push(a4.playState)
|
||||
a4.pause();
|
||||
cb4.push(a4.playState)
|
||||
});
|
||||
testing.eventually(() => testing.expectEqual(['running', 'paused'], cb4));
|
||||
</script>
|
||||
|
||||
<script id=finish>
|
||||
let a5 = document.createElement('div').animate(null, null);
|
||||
testing.expectEqual('idle', a5.playState);
|
||||
|
||||
let cb5 = [];
|
||||
a5.finished.then((x) => { cb5.push(a5.playState) });
|
||||
a5.ready.then(() => {
|
||||
cb5.push(a5.playState);
|
||||
a5.play();
|
||||
});
|
||||
testing.eventually(() => testing.expectEqual(['idle', 'finished'], cb5));
|
||||
</script>
|
||||
|
||||
@@ -33,3 +33,70 @@
|
||||
testing.expectEqual(ctx.fillStyle, "rgba(255, 0, 0, 0.06)");
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CanvasRenderingContext2D#createImageData(width, height)">
|
||||
{
|
||||
const element = document.createElement("canvas");
|
||||
const ctx = element.getContext("2d");
|
||||
|
||||
const imageData = ctx.createImageData(100, 200);
|
||||
testing.expectEqual(true, imageData instanceof ImageData);
|
||||
testing.expectEqual(imageData.width, 100);
|
||||
testing.expectEqual(imageData.height, 200);
|
||||
testing.expectEqual(imageData.data.length, 100 * 200 * 4);
|
||||
testing.expectEqual(true, imageData.data instanceof Uint8ClampedArray);
|
||||
|
||||
// All pixels should be initialized to 0.
|
||||
testing.expectEqual(imageData.data[0], 0);
|
||||
testing.expectEqual(imageData.data[1], 0);
|
||||
testing.expectEqual(imageData.data[2], 0);
|
||||
testing.expectEqual(imageData.data[3], 0);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CanvasRenderingContext2D#createImageData(imageData)">
|
||||
{
|
||||
const element = document.createElement("canvas");
|
||||
const ctx = element.getContext("2d");
|
||||
|
||||
const source = ctx.createImageData(50, 75);
|
||||
const imageData = ctx.createImageData(source);
|
||||
testing.expectEqual(true, imageData instanceof ImageData);
|
||||
testing.expectEqual(imageData.width, 50);
|
||||
testing.expectEqual(imageData.height, 75);
|
||||
testing.expectEqual(imageData.data.length, 50 * 75 * 4);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CanvasRenderingContext2D#putImageData">
|
||||
{
|
||||
const element = document.createElement("canvas");
|
||||
const ctx = element.getContext("2d");
|
||||
|
||||
const imageData = ctx.createImageData(10, 10);
|
||||
testing.expectEqual(true, imageData instanceof ImageData);
|
||||
// Modify some pixel data.
|
||||
imageData.data[0] = 255;
|
||||
imageData.data[1] = 0;
|
||||
imageData.data[2] = 0;
|
||||
imageData.data[3] = 255;
|
||||
|
||||
// putImageData should not throw.
|
||||
ctx.putImageData(imageData, 0, 0);
|
||||
ctx.putImageData(imageData, 10, 20);
|
||||
// With dirty rect parameters.
|
||||
ctx.putImageData(imageData, 0, 0, 0, 0, 5, 5);
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
<script id="getter">
|
||||
{
|
||||
const element = document.createElement("canvas");
|
||||
const ctx = element.getContext("2d");
|
||||
testing.expectEqual('10px sans-serif', ctx.font);
|
||||
ctx.font = 'bold 48px serif'
|
||||
testing.expectEqual('bold 48px serif', ctx.font);
|
||||
|
||||
}
|
||||
</script>
|
||||
|
||||
64
src/browser/tests/canvas/offscreen_canvas.html
Normal file
64
src/browser/tests/canvas/offscreen_canvas.html
Normal file
@@ -0,0 +1,64 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<script id=OffscreenCanvas>
|
||||
{
|
||||
const canvas = new OffscreenCanvas(256, 256);
|
||||
testing.expectEqual(true, canvas instanceof OffscreenCanvas);
|
||||
testing.expectEqual(canvas.width, 256);
|
||||
testing.expectEqual(canvas.height, 256);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=OffscreenCanvas#width>
|
||||
{
|
||||
const canvas = new OffscreenCanvas(100, 200);
|
||||
testing.expectEqual(canvas.width, 100);
|
||||
canvas.width = 300;
|
||||
testing.expectEqual(canvas.width, 300);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=OffscreenCanvas#height>
|
||||
{
|
||||
const canvas = new OffscreenCanvas(100, 200);
|
||||
testing.expectEqual(canvas.height, 200);
|
||||
canvas.height = 400;
|
||||
testing.expectEqual(canvas.height, 400);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=OffscreenCanvas#getContext>
|
||||
{
|
||||
const canvas = new OffscreenCanvas(64, 64);
|
||||
const ctx = canvas.getContext("2d");
|
||||
testing.expectEqual(true, ctx instanceof OffscreenCanvasRenderingContext2D);
|
||||
// We can't really test rendering but let's try to call it at least.
|
||||
ctx.fillRect(0, 0, 10, 10);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=OffscreenCanvas#convertToBlob>
|
||||
{
|
||||
const canvas = new OffscreenCanvas(64, 64);
|
||||
const promise = canvas.convertToBlob();
|
||||
testing.expectEqual(true, promise instanceof Promise);
|
||||
// The promise should resolve to a Blob (even if empty)
|
||||
promise.then(blob => {
|
||||
testing.expectEqual(true, blob instanceof Blob);
|
||||
testing.expectEqual(blob.size, 0); // Empty since no rendering
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=HTMLCanvasElement#transferControlToOffscreen>
|
||||
{
|
||||
const htmlCanvas = document.createElement("canvas");
|
||||
htmlCanvas.width = 128;
|
||||
htmlCanvas.height = 96;
|
||||
const offscreen = htmlCanvas.transferControlToOffscreen();
|
||||
testing.expectEqual(true, offscreen instanceof OffscreenCanvas);
|
||||
testing.expectEqual(offscreen.width, 128);
|
||||
testing.expectEqual(offscreen.height, 96);
|
||||
}
|
||||
</script>
|
||||
@@ -4,4 +4,6 @@
|
||||
<script id=comment>
|
||||
testing.expectEqual('', new Comment().data);
|
||||
testing.expectEqual('over 9000! ', new Comment('over 9000! ').data);
|
||||
|
||||
testing.expectEqual('null', new Comment(null).data);
|
||||
</script>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<!DOCTYPE html>
|
||||
<a id="link" href="foo" class="ok">OK</a>
|
||||
|
||||
<script src="../../testing.js"></script>
|
||||
<script src="../testing.js"></script>
|
||||
<script id=text>
|
||||
let t = new Text('foo');
|
||||
testing.expectEqual('foo', t.data);
|
||||
@@ -16,4 +16,7 @@
|
||||
let split = text.splitText('OK'.length);
|
||||
testing.expectEqual(' modified', split.data);
|
||||
testing.expectEqual('OK', text.data);
|
||||
|
||||
let x = new Text(null);
|
||||
testing.expectEqual("null", x.data);
|
||||
</script>
|
||||
@@ -69,3 +69,11 @@
|
||||
testing.expectEqual(true, CSS.supports('z-index', '10'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="escape_null_character">
|
||||
{
|
||||
testing.expectEqual('\uFFFD', CSS.escape('\x00'));
|
||||
testing.expectEqual('test\uFFFDvalue', CSS.escape('test\x00value'));
|
||||
testing.expectEqual('\uFFFDabc', CSS.escape('\x00abc'));
|
||||
}
|
||||
</script>
|
||||
|
||||
58
src/browser/tests/css/font_face_set.html
Normal file
58
src/browser/tests/css/font_face_set.html
Normal file
@@ -0,0 +1,58 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<script id="document_fonts_exists">
|
||||
{
|
||||
testing.expectTrue(document.fonts !== undefined);
|
||||
testing.expectTrue(document.fonts !== null);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="document_fonts_same_instance">
|
||||
{
|
||||
// Should return same instance each time
|
||||
const f1 = document.fonts;
|
||||
const f2 = document.fonts;
|
||||
testing.expectTrue(f1 === f2);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="document_fonts_status">
|
||||
{
|
||||
testing.expectEqual('loaded', document.fonts.status);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="document_fonts_size">
|
||||
{
|
||||
testing.expectEqual(0, document.fonts.size);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="document_fonts_ready_is_promise">
|
||||
{
|
||||
const ready = document.fonts.ready;
|
||||
testing.expectTrue(ready instanceof Promise);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="document_fonts_ready_resolves">
|
||||
{
|
||||
let resolved = false;
|
||||
document.fonts.ready.then(() => { resolved = true; });
|
||||
// Promise resolution is async; just confirm .then() does not throw
|
||||
testing.expectTrue(typeof document.fonts.ready.then === 'function');
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="document_fonts_check">
|
||||
{
|
||||
testing.expectTrue(document.fonts.check('16px sans-serif'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="document_fonts_constructor_name">
|
||||
{
|
||||
testing.expectEqual('FontFaceSet', document.fonts.constructor.name);
|
||||
}
|
||||
</script>
|
||||
@@ -205,3 +205,73 @@
|
||||
testing.expectEqual('', style.getPropertyPriority('content'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_style_syncs_to_attribute">
|
||||
{
|
||||
// JS style modifications must be reflected in getAttribute.
|
||||
const div = document.createElement('div');
|
||||
|
||||
// Named property assignment (element.style.X = ...)
|
||||
div.style.opacity = '0';
|
||||
testing.expectEqual('opacity: 0;', div.getAttribute('style'));
|
||||
|
||||
// Update existing property
|
||||
div.style.opacity = '1';
|
||||
testing.expectEqual('opacity: 1;', div.getAttribute('style'));
|
||||
|
||||
// Add a second property
|
||||
div.style.color = 'red';
|
||||
testing.expectTrue(div.getAttribute('style').includes('opacity: 1'));
|
||||
testing.expectTrue(div.getAttribute('style').includes('color: red'));
|
||||
|
||||
// removeProperty syncs back
|
||||
div.style.removeProperty('opacity');
|
||||
testing.expectTrue(!div.getAttribute('style').includes('opacity'));
|
||||
testing.expectTrue(div.getAttribute('style').includes('color: red'));
|
||||
|
||||
// setCssText syncs back
|
||||
div.style.cssText = 'filter: blur(0px)';
|
||||
testing.expectEqual('filter: blur(0px);', div.getAttribute('style'));
|
||||
|
||||
// setCssText with empty string clears attribute
|
||||
div.style.cssText = '';
|
||||
testing.expectEqual('', div.getAttribute('style'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_outerHTML_reflects_style_changes">
|
||||
{
|
||||
// outerHTML must reflect JS-modified styles (regression test for
|
||||
// DOM serialization reading stale HTML-parsed attribute values).
|
||||
const div = document.createElement('div');
|
||||
div.setAttribute('style', 'filter:blur(10px);opacity:0');
|
||||
|
||||
div.style.filter = 'blur(0px)';
|
||||
div.style.opacity = '1';
|
||||
|
||||
const html = div.outerHTML;
|
||||
testing.expectTrue(html.includes('filter: blur(0px)'));
|
||||
testing.expectTrue(html.includes('opacity: 1'));
|
||||
testing.expectTrue(!html.includes('blur(10px)'));
|
||||
testing.expectTrue(!html.includes('opacity:0'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_non_ascii_custom_property">
|
||||
{
|
||||
// Regression test: accessing element.style must not crash when the inline
|
||||
// style attribute contains CSS custom properties with non-ASCII (UTF-8
|
||||
// multibyte) names, such as French accented characters.
|
||||
// The CSS Tokenizer's consumeName() must advance over whole UTF-8 sequences
|
||||
// rather than byte-by-byte to avoid landing on a continuation byte.
|
||||
const div = document.createElement('div');
|
||||
div.setAttribute('style',
|
||||
'--color-store-bulles-\u00e9t\u00e9-fg: #6a818f;' +
|
||||
'--color-store-soir\u00e9es-odl-fg: #56b3b3;' +
|
||||
'color: red;'
|
||||
);
|
||||
|
||||
// Must not crash, and ASCII properties that follow non-ASCII ones must be readable.
|
||||
testing.expectEqual('red', div.style.getPropertyValue('color'));
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -53,3 +53,22 @@
|
||||
testing.expectEqual('NO-CONSTRUCTOR-ELEMENT', el.tagName);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div id=clone_container></div>
|
||||
|
||||
<script id=clone>
|
||||
{
|
||||
let calls = 0;
|
||||
class MyCloneElementA extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
calls += 1;
|
||||
$('#clone_container').appendChild(this);
|
||||
}
|
||||
}
|
||||
customElements.define('my-clone_element_a', MyCloneElementA);
|
||||
const original = document.createElement('my-clone_element_a');
|
||||
$('#clone_container').cloneNode(true);
|
||||
testing.expectEqual(2, calls);
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -7,9 +7,11 @@
|
||||
testing.expectEqual(true, htmlDiv1 instanceof HTMLDivElement);
|
||||
testing.expectEqual('http://www.w3.org/1999/xhtml', htmlDiv1.namespaceURI);
|
||||
|
||||
// Per spec, createElementNS does NOT lowercase — 'DIV' != 'div', so this
|
||||
// creates an HTMLUnknownElement, not an HTMLDivElement.
|
||||
const htmlDiv2 = document.createElementNS('http://www.w3.org/1999/xhtml', 'DIV');
|
||||
testing.expectEqual('DIV', htmlDiv2.tagName);
|
||||
testing.expectEqual(true, htmlDiv2 instanceof HTMLDivElement);
|
||||
testing.expectEqual(false, htmlDiv2 instanceof HTMLDivElement);
|
||||
testing.expectEqual('http://www.w3.org/1999/xhtml', htmlDiv2.namespaceURI);
|
||||
|
||||
const svgRect = document.createElementNS('http://www.w3.org/2000/svg', 'RecT');
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<!DOCTYPE html>
|
||||
<head id="the_head">
|
||||
<meta charset="UTF-8">
|
||||
<title>Test Document Title</title>
|
||||
<script src="../testing.js"></script>
|
||||
</head>
|
||||
@@ -11,7 +12,7 @@
|
||||
testing.expectEqual(10, document.childNodes[0].nodeType);
|
||||
testing.expectEqual(null, document.parentNode);
|
||||
testing.expectEqual(undefined, document.getCurrentScript);
|
||||
testing.expectEqual("http://127.0.0.1:9582/src/browser/tests/document/document.html", document.URL);
|
||||
testing.expectEqual(testing.BASE_URL + 'document/document.html', document.URL);
|
||||
testing.expectEqual(window, document.defaultView);
|
||||
testing.expectEqual(false, document.hidden);
|
||||
testing.expectEqual("visible", document.visibilityState);
|
||||
@@ -56,7 +57,7 @@
|
||||
testing.expectEqual('CSS1Compat', document.compatMode);
|
||||
testing.expectEqual(document.URL, document.documentURI);
|
||||
testing.expectEqual('', document.referrer);
|
||||
testing.expectEqual('127.0.0.1', document.domain);
|
||||
testing.expectEqual(testing.HOST, document.domain);
|
||||
</script>
|
||||
|
||||
<script id=programmatic_document_metadata>
|
||||
@@ -69,7 +70,7 @@
|
||||
testing.expectEqual('CSS1Compat', doc.compatMode);
|
||||
testing.expectEqual('', doc.referrer);
|
||||
// Programmatic document should have empty domain (no URL/origin)
|
||||
testing.expectEqual('127.0.0.1', doc.domain);
|
||||
testing.expectEqual(testing.HOST, doc.domain);
|
||||
</script>
|
||||
|
||||
<!-- Test anchors and links -->
|
||||
@@ -176,15 +177,111 @@
|
||||
testing.expectEqual(initialLength, anchors.length);
|
||||
</script>
|
||||
|
||||
<script id=cookie>
|
||||
testing.expectEqual('', document.cookie);
|
||||
document.cookie = 'name=Oeschger;';
|
||||
document.cookie = 'favorite_food=tripe;';
|
||||
<script id=cookie_basic>
|
||||
// Basic cookie operations
|
||||
document.cookie = 'testbasic1=Oeschger';
|
||||
testing.expectEqual(true, document.cookie.includes('testbasic1=Oeschger'));
|
||||
|
||||
testing.expectEqual('name=Oeschger; favorite_food=tripe', document.cookie);
|
||||
// "" should be returned, but the framework overrules it atm
|
||||
document.cookie = 'testbasic2=tripe';
|
||||
testing.expectEqual(true, document.cookie.includes('testbasic1=Oeschger'));
|
||||
testing.expectEqual(true, document.cookie.includes('testbasic2=tripe'));
|
||||
|
||||
// HttpOnly should be ignored from JavaScript
|
||||
const beforeHttp = document.cookie;
|
||||
document.cookie = 'IgnoreMy=Ghost; HttpOnly';
|
||||
testing.expectEqual('name=Oeschger; favorite_food=tripe', document.cookie);
|
||||
testing.expectEqual(false, document.cookie.includes('IgnoreMy=Ghost'));
|
||||
|
||||
// Clean up
|
||||
document.cookie = 'testbasic1=; Max-Age=0';
|
||||
document.cookie = 'testbasic2=; Max-Age=0';
|
||||
</script>
|
||||
|
||||
<script id=cookie_special_chars>
|
||||
// Test special characters in cookie values
|
||||
document.cookie = 'testspaces=hello world';
|
||||
testing.expectEqual(true, document.cookie.includes('testspaces=hello world'));
|
||||
document.cookie = 'testspaces=; Max-Age=0';
|
||||
|
||||
// Test various allowed special characters
|
||||
document.cookie = 'testspecial=!#$%&\'()*+-./';
|
||||
testing.expectEqual(true, document.cookie.includes('testspecial='));
|
||||
document.cookie = 'testspecial=; Max-Age=0';
|
||||
|
||||
// Semicolon terminates the cookie value
|
||||
document.cookie = 'testsemi=before;after';
|
||||
testing.expectEqual(true, document.cookie.includes('testsemi=before'));
|
||||
testing.expectEqual(false, document.cookie.includes('after'));
|
||||
document.cookie = 'testsemi=; Max-Age=0';
|
||||
</script>
|
||||
|
||||
<script id=cookie_empty_name>
|
||||
// Cookie with empty name (just a value)
|
||||
document.cookie = 'teststandalone';
|
||||
testing.expectEqual(true, document.cookie.includes('teststandalone'));
|
||||
document.cookie = 'teststandalone; Max-Age=0';
|
||||
</script>
|
||||
|
||||
<script id=cookie_whitespace>
|
||||
// Names and values should be trimmed
|
||||
document.cookie = ' testtrim = trimmed_value ';
|
||||
testing.expectEqual(true, document.cookie.includes('testtrim=trimmed_value'));
|
||||
document.cookie = 'testtrim=; Max-Age=0';
|
||||
</script>
|
||||
|
||||
<script id=cookie_max_age>
|
||||
// Max-Age=0 should immediately delete
|
||||
document.cookie = 'testtemp0=value; Max-Age=0';
|
||||
testing.expectEqual(false, document.cookie.includes('testtemp0=value'));
|
||||
|
||||
// Negative Max-Age should also delete
|
||||
document.cookie = 'testinstant=value';
|
||||
testing.expectEqual(true, document.cookie.includes('testinstant=value'));
|
||||
document.cookie = 'testinstant=value; Max-Age=-1';
|
||||
testing.expectEqual(false, document.cookie.includes('testinstant=value'));
|
||||
|
||||
// Positive Max-Age should keep cookie
|
||||
document.cookie = 'testkept=value; Max-Age=3600';
|
||||
testing.expectEqual(true, document.cookie.includes('testkept=value'));
|
||||
document.cookie = 'testkept=; Max-Age=0';
|
||||
</script>
|
||||
|
||||
<script id=cookie_overwrite>
|
||||
// Setting a cookie with the same name should overwrite
|
||||
document.cookie = 'testoverwrite=first';
|
||||
testing.expectEqual(true, document.cookie.includes('testoverwrite=first'));
|
||||
|
||||
document.cookie = 'testoverwrite=second';
|
||||
testing.expectEqual(true, document.cookie.includes('testoverwrite=second'));
|
||||
testing.expectEqual(false, document.cookie.includes('testoverwrite=first'));
|
||||
|
||||
document.cookie = 'testoverwrite=; Max-Age=0';
|
||||
</script>
|
||||
|
||||
<script id=cookie_path>
|
||||
// Path attribute
|
||||
document.cookie = 'testpath1=value; Path=/';
|
||||
testing.expectEqual(true, document.cookie.includes('testpath1=value'));
|
||||
|
||||
// Different path cookie should coexist
|
||||
document.cookie = 'testpath2=value2; Path=/src';
|
||||
testing.expectEqual(true, document.cookie.includes('testpath1=value'));
|
||||
|
||||
document.cookie = 'testpath1=; Max-Age=0; Path=/';
|
||||
document.cookie = 'testpath2=; Max-Age=0; Path=/src';
|
||||
</script>
|
||||
|
||||
<script id=cookie_invalid_chars>
|
||||
// Control characters (< 32 or > 126) should be rejected
|
||||
const beforeBad = document.cookie;
|
||||
|
||||
document.cookie = 'testbad1\x00=value';
|
||||
testing.expectEqual(false, document.cookie.includes('testbad1'));
|
||||
|
||||
document.cookie = 'testbad2\x1F=value';
|
||||
testing.expectEqual(false, document.cookie.includes('testbad2'));
|
||||
|
||||
document.cookie = 'testbad3=val\x7F';
|
||||
testing.expectEqual(false, document.cookie.includes('testbad3'));
|
||||
</script>
|
||||
|
||||
<script id=createAttribute>
|
||||
|
||||
@@ -297,3 +297,25 @@
|
||||
testing.expectEqual(btn, document.activeElement);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="focus_disconnected_no_blur">
|
||||
{
|
||||
const input1 = $('#input1');
|
||||
|
||||
if (document.activeElement) {
|
||||
document.activeElement.blur();
|
||||
}
|
||||
|
||||
input1.focus();
|
||||
testing.expectEqual(input1, document.activeElement);
|
||||
|
||||
let blurCount = 0;
|
||||
input1.addEventListener('blur', () => { blurCount++ });
|
||||
|
||||
// Focusing a disconnected element should be a no-op:
|
||||
// blur must not fire on the currently focused element
|
||||
document.createElement('a').focus();
|
||||
testing.expectEqual(input1, document.activeElement);
|
||||
testing.expectEqual(0, blurCount);
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -27,7 +27,9 @@
|
||||
testing.expectEqual(expected.length, result.length);
|
||||
testing.expectEqual(expected, Array.from(result).map((e) => e.textContent));
|
||||
testing.expectEqual(expected, Array.from(result.values()).map((e) => e.textContent));
|
||||
|
||||
testing.expectEqual(expected.map((e, i) => i), Array.from(result.keys()));
|
||||
testing.expectEqual(expected.map((e, i) => i.toString()), Object.keys(result));
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -376,3 +378,93 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<form id="form-validity-test">
|
||||
<input id="vi-required-empty" type="text" required>
|
||||
<input id="vi-optional" type="text">
|
||||
<input id="vi-hidden-required" type="hidden" required>
|
||||
<fieldset id="vi-fieldset">
|
||||
<input id="vi-nested-required" type="text" required>
|
||||
<select id="vi-select-required" required>
|
||||
<option value="">Pick one</option>
|
||||
<option value="a">A</option>
|
||||
</select>
|
||||
</fieldset>
|
||||
</form>
|
||||
<input id="vi-checkbox" type="checkbox">
|
||||
|
||||
<script id=invalidPseudo>
|
||||
{
|
||||
// Inputs with required + empty value are :invalid
|
||||
testing.expectEqual(true, document.getElementById('vi-required-empty').matches(':invalid'));
|
||||
testing.expectEqual(false, document.getElementById('vi-required-empty').matches(':valid'));
|
||||
|
||||
// Inputs without required are :valid
|
||||
testing.expectEqual(false, document.getElementById('vi-optional').matches(':invalid'));
|
||||
testing.expectEqual(true, document.getElementById('vi-optional').matches(':valid'));
|
||||
|
||||
// hidden inputs are not candidates for constraint validation
|
||||
testing.expectEqual(false, document.getElementById('vi-hidden-required').matches(':invalid'));
|
||||
testing.expectEqual(false, document.getElementById('vi-hidden-required').matches(':valid'));
|
||||
|
||||
// select with required and empty selected value is :invalid
|
||||
testing.expectEqual(true, document.getElementById('vi-select-required').matches(':invalid'));
|
||||
testing.expectEqual(false, document.getElementById('vi-select-required').matches(':valid'));
|
||||
|
||||
// fieldset containing invalid controls is :invalid
|
||||
testing.expectEqual(true, document.getElementById('vi-fieldset').matches(':invalid'));
|
||||
testing.expectEqual(false, document.getElementById('vi-fieldset').matches(':valid'));
|
||||
|
||||
// form containing invalid controls is :invalid
|
||||
testing.expectEqual(true, document.getElementById('form-validity-test').matches(':invalid'));
|
||||
testing.expectEqual(false, document.getElementById('form-validity-test').matches(':valid'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=validAfterValueSet>
|
||||
{
|
||||
// After setting a value, a required input becomes :valid
|
||||
const input = document.getElementById('vi-required-empty');
|
||||
input.value = 'hello';
|
||||
testing.expectEqual(false, input.matches(':invalid'));
|
||||
testing.expectEqual(true, input.matches(':valid'));
|
||||
input.value = '';
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=indeterminatePseudo>
|
||||
{
|
||||
const cb = document.getElementById('vi-checkbox');
|
||||
testing.expectEqual(false, cb.matches(':indeterminate'));
|
||||
cb.indeterminate = true;
|
||||
testing.expectEqual(true, cb.matches(':indeterminate'));
|
||||
cb.indeterminate = false;
|
||||
testing.expectEqual(false, cb.matches(':indeterminate'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=iterator_list_lifetime>
|
||||
// This test is intended to ensure that a list remains alive as long as it
|
||||
// must, i.e. as long as any iterator referencing the list is alive.
|
||||
// This test depends on being able to force the v8 GC to cleanup, which
|
||||
// we have no way of controlling. At worst, the test will pass without
|
||||
// actually testing correct lifetime. But it was at least manually verified
|
||||
// for me that this triggers plenty of GCs.
|
||||
const expected = Array.from(document.querySelectorAll('*')).length;
|
||||
{
|
||||
let keys = [];
|
||||
|
||||
// Phase 1: Create many lists+iterators to fill up the arena pool
|
||||
for (let i = 0; i < 1000; i++) {
|
||||
let list = document.querySelectorAll('*');
|
||||
keys.push(list.keys());
|
||||
|
||||
// Create an Event every iteration to compete for arenas
|
||||
new Event('arena_compete');
|
||||
}
|
||||
|
||||
for (let k of keys) {
|
||||
const result = Array.from(k);
|
||||
testing.expectEqual(expected, result.length);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -111,3 +111,15 @@
|
||||
const containerDataTest = document.querySelector('#container [data-test]');
|
||||
testing.expectEqual('First', containerDataTest.innerText);
|
||||
</script>
|
||||
|
||||
<link rel="preload" as="image" imagesrcset="url1.png 1x, url2.png 2x" id="preload-link">
|
||||
|
||||
<script id="commaInAttrValue">
|
||||
// Commas inside quoted attribute values must not be treated as selector separators
|
||||
const el = document.querySelector('link[rel="preload"][as="image"][imagesrcset="url1.png 1x, url2.png 2x"]');
|
||||
testing.expectEqual('preload-link', el.id);
|
||||
|
||||
// Also test with single quotes inside selector
|
||||
const el2 = document.querySelector("link[imagesrcset='url1.png 1x, url2.png 2x']");
|
||||
testing.expectEqual('preload-link', el2.id);
|
||||
</script>
|
||||
|
||||
@@ -108,6 +108,20 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=createHTMLDocument_nulll_title>
|
||||
{
|
||||
const impl = document.implementation;
|
||||
const doc = impl.createHTMLDocument(null);
|
||||
|
||||
testing.expectEqual('null', doc.title);
|
||||
|
||||
// Should have title element in head
|
||||
const titleElement = doc.head.querySelector('title');
|
||||
testing.expectEqual(true, titleElement !== null);
|
||||
testing.expectEqual('null', titleElement.textContent);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=createHTMLDocument_structure>
|
||||
{
|
||||
const impl = document.implementation;
|
||||
|
||||
@@ -154,3 +154,11 @@
|
||||
testing.expectEqual(true, typeof div.style.getPropertyPriority === 'function');
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
<div id=crash1 style="background-position: 5% .1em"></div>
|
||||
<script id="crash_case_1">
|
||||
{
|
||||
testing.expectEqual('5% .1em', $('#crash1').style.backgroundPosition);
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -11,11 +11,11 @@
|
||||
<script id=empty_href>
|
||||
testing.expectEqual('', $('#a0').href);
|
||||
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/element/anchor1.html', $('#a1').href);
|
||||
testing.expectEqual('http://127.0.0.1:9582/hello/world/anchor2.html', $('#a2').href);
|
||||
testing.expectEqual(testing.BASE_URL + 'element/anchor1.html', $('#a1').href);
|
||||
testing.expectEqual(testing.ORIGIN + 'hello/world/anchor2.html', $('#a2').href);
|
||||
testing.expectEqual('https://www.openmymind.net/Elixirs-With-Statement/', $('#a3').href);
|
||||
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/element/html/foo', $('#link').href);
|
||||
testing.expectEqual(testing.BASE_URL + 'element/html/foo', $('#link').href);
|
||||
</script>
|
||||
|
||||
<script id=dynamic_anchor_defaults>
|
||||
@@ -129,7 +129,7 @@
|
||||
testing.expectEqual('https://foo.bar/?q=bar#frag', link.href);
|
||||
|
||||
link.href = 'foo';
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/element/html/foo', link.href);
|
||||
testing.expectEqual(testing.BASE_URL + 'element/html/foo', link.href);
|
||||
|
||||
testing.expectEqual('', link.type);
|
||||
link.type = 'text/html';
|
||||
@@ -245,3 +245,11 @@
|
||||
testing.expectEqual('', b.toString());
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=url_encode>
|
||||
{
|
||||
let a = document.createElement('a');
|
||||
a.href = 'over 9000!';
|
||||
testing.expectEqual(testing.BASE_URL + 'element/html/over%209000!', a.href);
|
||||
}
|
||||
</script>
|
||||
|
||||
63
src/browser/tests/element/html/details.html
Normal file
63
src/browser/tests/element/html/details.html
Normal file
@@ -0,0 +1,63 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../../testing.js"></script>
|
||||
|
||||
<!-- Details elements -->
|
||||
<details id="details1">
|
||||
<summary>Summary</summary>
|
||||
Content
|
||||
</details>
|
||||
<details id="details2" open>
|
||||
<summary>Open Summary</summary>
|
||||
Content
|
||||
</details>
|
||||
|
||||
<script id="instanceof">
|
||||
{
|
||||
const details = document.createElement('details')
|
||||
testing.expectTrue(details instanceof HTMLDetailsElement)
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="open_initial">
|
||||
testing.expectEqual(false, $('#details1').open)
|
||||
testing.expectEqual(true, $('#details2').open)
|
||||
</script>
|
||||
|
||||
<script id="open_set">
|
||||
{
|
||||
$('#details1').open = true
|
||||
testing.expectEqual(true, $('#details1').open)
|
||||
|
||||
$('#details2').open = false
|
||||
testing.expectEqual(false, $('#details2').open)
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="open_reflects_attribute">
|
||||
{
|
||||
const details = document.createElement('details')
|
||||
testing.expectEqual(null, details.getAttribute('open'))
|
||||
|
||||
details.open = true
|
||||
testing.expectEqual('', details.getAttribute('open'))
|
||||
|
||||
details.open = false
|
||||
testing.expectEqual(null, details.getAttribute('open'))
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="name_initial">
|
||||
{
|
||||
const details = document.createElement('details')
|
||||
testing.expectEqual('', details.name)
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="name_set">
|
||||
{
|
||||
const details = document.createElement('details')
|
||||
details.name = 'group1'
|
||||
testing.expectEqual('group1', details.name)
|
||||
testing.expectEqual('group1', details.getAttribute('name'))
|
||||
}
|
||||
</script>
|
||||
@@ -143,6 +143,29 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="js_setter_null_clears_listener">
|
||||
{
|
||||
// Setting an event handler property to null must silently clear it (not throw).
|
||||
// Browsers also accept undefined and non-function values without throwing.
|
||||
const div = document.createElement('div');
|
||||
|
||||
div.onload = () => 42;
|
||||
testing.expectEqual('function', typeof div.onload);
|
||||
|
||||
// Setting to null removes the listener; getter returns null
|
||||
div.onload = null;
|
||||
testing.expectEqual(null, div.onload);
|
||||
|
||||
div.onerror = () => {};
|
||||
div.onerror = null;
|
||||
testing.expectEqual(null, div.onerror);
|
||||
|
||||
div.onclick = () => {};
|
||||
div.onclick = null;
|
||||
testing.expectEqual(null, div.onclick);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="different_event_types_independent">
|
||||
{
|
||||
// Test that different event types are stored independently
|
||||
|
||||
@@ -32,12 +32,12 @@
|
||||
|
||||
img.src = 'test.png';
|
||||
// src property returns resolved absolute URL
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/element/html/test.png', img.src);
|
||||
testing.expectEqual(testing.BASE_URL + 'element/html/test.png', img.src);
|
||||
// getAttribute returns the raw attribute value
|
||||
testing.expectEqual('test.png', img.getAttribute('src'));
|
||||
|
||||
img.src = '/absolute/path.png';
|
||||
testing.expectEqual('http://127.0.0.1:9582/absolute/path.png', img.src);
|
||||
testing.expectEqual(testing.ORIGIN + 'absolute/path.png', img.src);
|
||||
testing.expectEqual('/absolute/path.png', img.getAttribute('src'));
|
||||
|
||||
img.src = 'https://example.com/image.png';
|
||||
@@ -114,48 +114,15 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="load-trigger-event">
|
||||
<body></body>
|
||||
|
||||
<script id="img-load-event">
|
||||
{
|
||||
// An img fires a load event when src is set.
|
||||
const img = document.createElement("img");
|
||||
let count = 0;
|
||||
img.addEventListener("load", ({ bubbles, cancelBubble, cancelable, composed, isTrusted, target }) => {
|
||||
testing.expectEqual(true, count < 3);
|
||||
count++;
|
||||
|
||||
testing.expectEqual(false, bubbles);
|
||||
testing.expectEqual(false, cancelBubble);
|
||||
testing.expectEqual(false, cancelable);
|
||||
testing.expectEqual(false, composed);
|
||||
testing.expectEqual(true, isTrusted);
|
||||
testing.expectEqual(img, target);
|
||||
});
|
||||
|
||||
for (let i = 0; i < 3; i++) {
|
||||
img.src = "https://cdn.lightpanda.io/website/assets/images/docs/hn.png";
|
||||
testing.expectEqual("https://cdn.lightpanda.io/website/assets/images/docs/hn.png", img.src);
|
||||
}
|
||||
|
||||
// Make sure count is incremented asynchronously.
|
||||
testing.expectEqual(0, count);
|
||||
}
|
||||
</script>
|
||||
|
||||
<img
|
||||
id="inline-img"
|
||||
src="https://cdn.lightpanda.io/website/assets/images/docs/hn.png"
|
||||
onload="(() => testing.expectEqual(true, true))()"
|
||||
/>
|
||||
|
||||
<script id="inline-on-load">
|
||||
{
|
||||
const img = document.getElementById("inline-img");
|
||||
testing.expectEqual(true, img.onload instanceof Function);
|
||||
// Also call inline to double check.
|
||||
img.onload();
|
||||
|
||||
// Make sure ones attached with `addEventListener` also executed.
|
||||
let result = false;
|
||||
testing.async(async () => {
|
||||
const result = await new Promise(resolve => {
|
||||
await new Promise(resolve => {
|
||||
img.addEventListener("load", ({ bubbles, cancelBubble, cancelable, composed, isTrusted, target }) => {
|
||||
testing.expectEqual(false, bubbles);
|
||||
testing.expectEqual(false, cancelBubble);
|
||||
@@ -163,12 +130,46 @@
|
||||
testing.expectEqual(false, composed);
|
||||
testing.expectEqual(true, isTrusted);
|
||||
testing.expectEqual(img, target);
|
||||
|
||||
return resolve(true);
|
||||
result = true;
|
||||
return resolve();
|
||||
});
|
||||
img.src = "https://cdn.lightpanda.io/website/assets/images/docs/hn.png";
|
||||
});
|
||||
|
||||
testing.expectEqual(true, result);
|
||||
});
|
||||
|
||||
testing.eventually(() => testing.expectEqual(true, result));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="img-no-load-without-src">
|
||||
{
|
||||
// An img without src should not fire a load event.
|
||||
let fired = false;
|
||||
const img = document.createElement("img");
|
||||
img.addEventListener("load", () => { fired = true; });
|
||||
document.body.appendChild(img);
|
||||
testing.eventually(() => testing.expectEqual(false, fired));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="lazy-src-set">
|
||||
{
|
||||
// Append to DOM first, then set src — load should still fire.
|
||||
const img = document.createElement("img");
|
||||
let result = false;
|
||||
img.onload = () => result = true;
|
||||
document.body.appendChild(img);
|
||||
img.src = "https://cdn.lightpanda.io/website/assets/images/docs/hn.png";
|
||||
|
||||
testing.eventually(() => testing.expectEqual(true, result));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=url_encode>
|
||||
{
|
||||
let img = document.createElement('img');
|
||||
img.src = 'over 9000!?hello=world !';
|
||||
testing.expectEqual('over 9000!?hello=world !', img.getAttribute('src'));
|
||||
testing.expectEqual(testing.BASE_URL + 'element/html/over%209000!?hello=world%20!', img.src);
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -46,7 +46,7 @@
|
||||
testing.expectEqual(5, input.maxLength);
|
||||
input.maxLength = 'banana';
|
||||
testing.expectEqual(0, input.maxLength);
|
||||
testing.expectError('Error: NegativeValueNotAllowed', () => { input.maxLength = -45;});
|
||||
testing.expectError('IndexSizeError: Index or size is negative or greater than the allowed amount', () => { input.maxLength = -45;});
|
||||
|
||||
testing.expectEqual(20, input.size);
|
||||
input.size = 5;
|
||||
@@ -57,9 +57,9 @@
|
||||
|
||||
testing.expectEqual('', input.src);
|
||||
input.src = 'foo'
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/element/html/foo', input.src);
|
||||
testing.expectEqual(testing.BASE_URL + 'element/html/foo', input.src);
|
||||
input.src = '-3'
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/element/html/-3', input.src);
|
||||
testing.expectEqual(testing.BASE_URL + 'element/html/-3', input.src);
|
||||
input.src = ''
|
||||
}
|
||||
</script>
|
||||
@@ -221,6 +221,44 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="select_event">
|
||||
{
|
||||
const input = document.createElement('input');
|
||||
input.value = 'Hello World';
|
||||
document.body.appendChild(input);
|
||||
|
||||
let eventCount = 0;
|
||||
let lastEvent = null;
|
||||
|
||||
input.addEventListener('select', (e) => {
|
||||
eventCount++;
|
||||
lastEvent = e;
|
||||
});
|
||||
|
||||
let onselectFired = false;
|
||||
input.onselect = () => { onselectFired = true; };
|
||||
|
||||
let bubbledToBody = false;
|
||||
document.body.addEventListener('select', () => {
|
||||
bubbledToBody = true;
|
||||
});
|
||||
|
||||
testing.expectEqual(0, eventCount);
|
||||
|
||||
input.select();
|
||||
|
||||
testing.eventually(() => {
|
||||
testing.expectEqual(1, eventCount);
|
||||
testing.expectEqual('select', lastEvent.type);
|
||||
testing.expectEqual(input, lastEvent.target);
|
||||
testing.expectEqual(true, lastEvent.bubbles);
|
||||
testing.expectEqual(false, lastEvent.cancelable);
|
||||
testing.expectEqual(true, bubbledToBody);
|
||||
testing.expectEqual(true, onselectFired);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="defaultChecked">
|
||||
testing.expectEqual(true, $('#check1').defaultChecked)
|
||||
testing.expectEqual(false, $('#check2').defaultChecked)
|
||||
|
||||
@@ -16,3 +16,59 @@
|
||||
testing.expectEqual('', l2.htmlFor);
|
||||
}
|
||||
</script>
|
||||
|
||||
<label id="l2" for="input1"><span>Name</span></label>
|
||||
<input id="input2" type="text">
|
||||
<input id="input-hidden" type="hidden">
|
||||
<select id="sel1"><option>a</option></select>
|
||||
<button id="btn1">Click</button>
|
||||
<label id="l3"><input id="input3"><span>desc</span></label>
|
||||
<label id="l4"><span>no control here</span></label>
|
||||
<label id="l5"><label id="l5-inner"><input id="input5"></label></label>
|
||||
|
||||
<script id="control">
|
||||
{
|
||||
// for attribute pointing to a text input
|
||||
const l2 = document.getElementById('l2');
|
||||
testing.expectEqual('input1', l2.control.id);
|
||||
|
||||
// for attribute pointing to a non-existent id
|
||||
const lMissing = document.createElement('label');
|
||||
lMissing.htmlFor = 'does-not-exist';
|
||||
testing.expectEqual(null, lMissing.control);
|
||||
|
||||
// for attribute pointing to a hidden input -> not labelable, returns null
|
||||
const lHidden = document.createElement('label');
|
||||
lHidden.htmlFor = 'input-hidden';
|
||||
document.body.appendChild(lHidden);
|
||||
testing.expectEqual(null, lHidden.control);
|
||||
|
||||
// for attribute pointing to a select
|
||||
const lSel = document.createElement('label');
|
||||
lSel.htmlFor = 'sel1';
|
||||
document.body.appendChild(lSel);
|
||||
testing.expectEqual('sel1', lSel.control.id);
|
||||
|
||||
// for attribute pointing to a button
|
||||
const lBtn = document.createElement('label');
|
||||
lBtn.htmlFor = 'btn1';
|
||||
document.body.appendChild(lBtn);
|
||||
testing.expectEqual('btn1', lBtn.control.id);
|
||||
|
||||
// no for attribute: first labelable descendant
|
||||
const l3 = document.getElementById('l3');
|
||||
testing.expectEqual('input3', l3.control.id);
|
||||
|
||||
// no for attribute: no labelable descendant -> null
|
||||
const l4 = document.getElementById('l4');
|
||||
testing.expectEqual(null, l4.control);
|
||||
|
||||
// no for attribute: nested labels, first labelable in tree order
|
||||
const l5 = document.getElementById('l5');
|
||||
testing.expectEqual('input5', l5.control.id);
|
||||
|
||||
// label with no for and not in document -> null
|
||||
const lDetached = document.createElement('label');
|
||||
testing.expectEqual(null, lDetached.control);
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
testing.expectEqual('https://lightpanda.io/opensource-browser/15', l2.href);
|
||||
|
||||
l2.href = '/over/9000';
|
||||
testing.expectEqual('http://127.0.0.1:9582/over/9000', l2.href);
|
||||
testing.expectEqual(testing.ORIGIN + 'over/9000', l2.href);
|
||||
|
||||
l2.crossOrigin = 'nope';
|
||||
testing.expectEqual('anonymous', l2.crossOrigin);
|
||||
@@ -19,3 +19,68 @@
|
||||
l2.crossOrigin = '';
|
||||
testing.expectEqual('anonymous', l2.crossOrigin);
|
||||
</script>
|
||||
|
||||
<script id="link-load-event">
|
||||
{
|
||||
// A link with rel=stylesheet and a non-empty href fires a load event when appended to the DOM
|
||||
const link = document.createElement('link');
|
||||
link.rel = 'stylesheet';
|
||||
link.href = 'https://lightpanda.io/opensource-browser/15';
|
||||
|
||||
testing.async(async () => {
|
||||
const result = await new Promise(resolve => {
|
||||
link.addEventListener('load', ({ bubbles, cancelBubble, cancelable, composed, isTrusted, target }) => {
|
||||
testing.expectEqual(false, bubbles);
|
||||
testing.expectEqual(false, cancelBubble);
|
||||
testing.expectEqual(false, cancelable);
|
||||
testing.expectEqual(false, composed);
|
||||
testing.expectEqual(true, isTrusted);
|
||||
testing.expectEqual(link, target);
|
||||
resolve(true);
|
||||
});
|
||||
document.head.appendChild(link);
|
||||
});
|
||||
testing.expectEqual(true, result);
|
||||
});
|
||||
testing.expectEqual(true, true);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="link-no-load-without-href">
|
||||
{
|
||||
// A link with rel=stylesheet but no href should not fire a load event
|
||||
let fired = false;
|
||||
const link = document.createElement('link');
|
||||
link.rel = 'stylesheet';
|
||||
link.addEventListener('load', () => { fired = true; });
|
||||
document.head.appendChild(link);
|
||||
testing.eventually(() => testing.expectEqual(false, fired));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="link-no-load-wrong-rel">
|
||||
{
|
||||
// A link without rel=stylesheet should not fire a load event
|
||||
let fired = false;
|
||||
const link = document.createElement('link');
|
||||
link.href = 'https://lightpanda.io/opensource-browser/15';
|
||||
link.addEventListener('load', () => { fired = true; });
|
||||
document.head.appendChild(link);
|
||||
testing.eventually(() => testing.expectEqual(false, fired));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="lazy-href-set">
|
||||
{
|
||||
let result = false;
|
||||
const link = document.createElement("link");
|
||||
link.rel = "stylesheet";
|
||||
link.onload = () => result = true;
|
||||
// Append to DOM,
|
||||
document.head.appendChild(link);
|
||||
// then set href.
|
||||
link.href = 'https://lightpanda.io/opensource-browser/15';
|
||||
|
||||
testing.eventually(() => testing.expectEqual(true, result));
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -238,7 +238,7 @@
|
||||
testing.expectEqual('', audio.src);
|
||||
|
||||
audio.src = 'test.mp3';
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/element/html/test.mp3', audio.src);
|
||||
testing.expectEqual(testing.BASE_URL + 'element/html/test.mp3', audio.src);
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -248,7 +248,7 @@
|
||||
testing.expectEqual('', video.poster);
|
||||
|
||||
video.poster = 'poster.jpg';
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/element/html/poster.jpg', video.poster);
|
||||
testing.expectEqual(testing.BASE_URL + 'element/html/poster.jpg', video.poster);
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
@@ -29,6 +29,12 @@
|
||||
testing.expectEqual('Text 3', $('#opt3').text)
|
||||
</script>
|
||||
|
||||
<script id="text_set">
|
||||
$('#opt1').text = 'New Text 1'
|
||||
testing.expectEqual('New Text 1', $('#opt1').text)
|
||||
testing.expectEqual('New Text 1', $('#opt1').textContent)
|
||||
</script>
|
||||
|
||||
<script id="selected">
|
||||
testing.expectEqual(false, $('#opt1').selected)
|
||||
testing.expectEqual(true, $('#opt2').selected)
|
||||
|
||||
0
src/browser/tests/element/html/script/empty.js
Normal file
0
src/browser/tests/element/html/script/empty.js
Normal file
@@ -2,11 +2,28 @@
|
||||
<script src="../../../testing.js"></script>
|
||||
|
||||
<script id="script">
|
||||
{
|
||||
let s = document.createElement('script');
|
||||
testing.expectEqual('', s.src);
|
||||
{
|
||||
let dom_load = false;
|
||||
let attribute_load = false;
|
||||
|
||||
s.src = '/over.9000.js';
|
||||
testing.expectEqual('http://127.0.0.1:9582/over.9000.js', s.src);
|
||||
let s = document.createElement('script');
|
||||
document.documentElement.addEventListener('load', (e) => {
|
||||
testing.expectEqual(s, e.target);
|
||||
dom_load = true;
|
||||
}, true);
|
||||
|
||||
testing.expectEqual('', s.src);
|
||||
s.onload = function(e) {
|
||||
testing.expectEqual(s, e.target);
|
||||
attribute_load = true;
|
||||
}
|
||||
s.src = 'empty.js';
|
||||
testing.expectEqual(testing.BASE_URL + 'element/html/script/empty.js', s.src);
|
||||
document.head.appendChild(s);
|
||||
|
||||
testing.eventually(() => {
|
||||
testing.expectEqual(true, dom_load);
|
||||
testing.expectEqual(true, attribute_load);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -106,3 +106,28 @@
|
||||
testing.expectEqual(true, style.disabled);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="style-load-event">
|
||||
{
|
||||
// A style element fires a load event when appended to the DOM.
|
||||
const style = document.createElement("style");
|
||||
let result = false;
|
||||
testing.async(async () => {
|
||||
await new Promise(resolve => {
|
||||
style.addEventListener("load", ({ bubbles, cancelBubble, cancelable, composed, isTrusted, target }) => {
|
||||
testing.expectEqual(false, bubbles);
|
||||
testing.expectEqual(false, cancelBubble);
|
||||
testing.expectEqual(false, cancelable);
|
||||
testing.expectEqual(false, composed);
|
||||
testing.expectEqual(true, isTrusted);
|
||||
testing.expectEqual(style, target);
|
||||
result = true;
|
||||
return resolve();
|
||||
});
|
||||
document.head.appendChild(style);
|
||||
});
|
||||
});
|
||||
|
||||
testing.eventually(() => testing.expectEqual(true, result));
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -230,6 +230,44 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="select_event">
|
||||
{
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.value = 'Hello World';
|
||||
document.body.appendChild(textarea);
|
||||
|
||||
let eventCount = 0;
|
||||
let lastEvent = null;
|
||||
|
||||
textarea.addEventListener('select', (e) => {
|
||||
eventCount++;
|
||||
lastEvent = e;
|
||||
});
|
||||
|
||||
let onselectFired = false;
|
||||
textarea.onselect = () => { onselectFired = true; };
|
||||
|
||||
let bubbledToBody = false;
|
||||
document.body.addEventListener('select', () => {
|
||||
bubbledToBody = true;
|
||||
});
|
||||
|
||||
testing.expectEqual(0, eventCount);
|
||||
|
||||
textarea.select();
|
||||
|
||||
testing.eventually(() => {
|
||||
testing.expectEqual(1, eventCount);
|
||||
testing.expectEqual('select', lastEvent.type);
|
||||
testing.expectEqual(textarea, lastEvent.target);
|
||||
testing.expectEqual(true, lastEvent.bubbles);
|
||||
testing.expectEqual(false, lastEvent.cancelable);
|
||||
testing.expectEqual(true, bubbledToBody);
|
||||
testing.expectEqual(true, onselectFired);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="selectionchange_event">
|
||||
{
|
||||
const textarea = document.createElement('textarea');
|
||||
|
||||
75
src/browser/tests/element/html/track.html
Normal file
75
src/browser/tests/element/html/track.html
Normal file
@@ -0,0 +1,75 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../../testing.js"></script>
|
||||
|
||||
<video id="video1">
|
||||
<track id="track1" kind="subtitles">
|
||||
<track id="track2" kind="captions">
|
||||
<track id="track3" kind="invalid-kind">
|
||||
</video>
|
||||
|
||||
<script id="instanceof">
|
||||
{
|
||||
const track = document.createElement("track");
|
||||
testing.expectEqual(true, track instanceof HTMLTrackElement);
|
||||
testing.expectEqual("[object HTMLTrackElement]", track.toString());
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="kind_default">
|
||||
{
|
||||
const track = document.createElement("track");
|
||||
testing.expectEqual("subtitles", track.kind);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="kind_valid_values">
|
||||
{
|
||||
const track = document.createElement("track");
|
||||
|
||||
track.kind = "captions";
|
||||
testing.expectEqual("captions", track.kind);
|
||||
|
||||
track.kind = "descriptions";
|
||||
testing.expectEqual("descriptions", track.kind);
|
||||
|
||||
track.kind = "chapters";
|
||||
testing.expectEqual("chapters", track.kind);
|
||||
|
||||
track.kind = "metadata";
|
||||
testing.expectEqual("metadata", track.kind);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="kind_invalid">
|
||||
{
|
||||
const track = document.createElement("track");
|
||||
|
||||
track.kind = null;
|
||||
testing.expectEqual("metadata", track.kind);
|
||||
|
||||
track.kind = "Subtitles";
|
||||
testing.expectEqual("subtitles", track.kind);
|
||||
|
||||
track.kind = "";
|
||||
testing.expectEqual("metadata", track.kind);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="constants">
|
||||
{
|
||||
const track = document.createElement("track");
|
||||
testing.expectEqual(0, track.NONE);
|
||||
testing.expectEqual(1, track.LOADING);
|
||||
testing.expectEqual(2, track.LOADED);
|
||||
testing.expectEqual(3, track.ERROR);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="constants_static">
|
||||
{
|
||||
testing.expectEqual(0, HTMLTrackElement.NONE);
|
||||
testing.expectEqual(1, HTMLTrackElement.LOADING);
|
||||
testing.expectEqual(2, HTMLTrackElement.LOADED);
|
||||
testing.expectEqual(3, HTMLTrackElement.ERROR);
|
||||
}
|
||||
</script>
|
||||
@@ -45,7 +45,6 @@
|
||||
testing.expectEqual('hi', $('#link').innerText);
|
||||
|
||||
d1.innerHTML = '';
|
||||
testing.todo(null, $('#link'));
|
||||
</script>
|
||||
|
||||
<script id=attributeSerialization>
|
||||
|
||||
@@ -103,3 +103,16 @@
|
||||
document.dispatchEvent(new KeyboardEvent('keytest', {key: 'b'}));
|
||||
testing.expectEqual(false, keyIsTrusted);
|
||||
</script>
|
||||
|
||||
<script id=non_keyboard_keydown>
|
||||
// this used to crash
|
||||
{
|
||||
let called = false;
|
||||
const div = document.createElement('div')
|
||||
div.addEventListener('keydown', () => {
|
||||
called = true;
|
||||
});
|
||||
div.dispatchEvent(new Event('keydown'));
|
||||
testing.expectEqual(true, called);
|
||||
}
|
||||
</script>
|
||||
|
||||
197
src/browser/tests/file_reader.html
Normal file
197
src/browser/tests/file_reader.html
Normal file
@@ -0,0 +1,197 @@
|
||||
<!DOCTYPE html>
|
||||
<meta charset="UTF-8">
|
||||
<script src="./testing.js"></script>
|
||||
|
||||
<script id=basic>
|
||||
{
|
||||
const reader = new FileReader();
|
||||
testing.expectEqual(0, reader.readyState);
|
||||
testing.expectEqual(null, reader.result);
|
||||
testing.expectEqual(null, reader.error);
|
||||
}
|
||||
|
||||
// Constants
|
||||
testing.expectEqual(0, FileReader.EMPTY);
|
||||
testing.expectEqual(1, FileReader.LOADING);
|
||||
testing.expectEqual(2, FileReader.DONE);
|
||||
</script>
|
||||
|
||||
<script id=readAsText>
|
||||
testing.async(async () => {
|
||||
const reader = new FileReader();
|
||||
const blob = new Blob(["Hello, World!"], { type: "text/plain" });
|
||||
|
||||
let loadstartFired = false;
|
||||
let progressFired = false;
|
||||
let loadFired = false;
|
||||
let loadendFired = false;
|
||||
|
||||
const promise = new Promise((resolve) => {
|
||||
reader.onloadstart = function(e) {
|
||||
loadstartFired = true;
|
||||
testing.expectEqual("loadstart", e.type);
|
||||
testing.expectEqual(1, reader.readyState);
|
||||
};
|
||||
|
||||
reader.onprogress = function(e) {
|
||||
progressFired = true;
|
||||
testing.expectEqual(13, e.loaded);
|
||||
testing.expectEqual(13, e.total);
|
||||
};
|
||||
|
||||
reader.onload = function(e) {
|
||||
loadFired = true;
|
||||
testing.expectEqual(2, reader.readyState);
|
||||
testing.expectEqual("Hello, World!", reader.result);
|
||||
};
|
||||
|
||||
reader.onloadend = function(e) {
|
||||
loadendFired = true;
|
||||
testing.expectEqual(true, loadstartFired);
|
||||
testing.expectEqual(true, progressFired);
|
||||
testing.expectEqual(true, loadFired);
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
|
||||
reader.readAsText(blob);
|
||||
await promise;
|
||||
});
|
||||
</script>
|
||||
|
||||
<script id=readAsDataURL>
|
||||
testing.async(async () => {
|
||||
const reader = new FileReader();
|
||||
const blob = new Blob(["test"], { type: "text/plain" });
|
||||
|
||||
const promise = new Promise((resolve) => {
|
||||
reader.onload = function() {
|
||||
testing.expectEqual("data:text/plain;base64,dGVzdA==", reader.result);
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
|
||||
reader.readAsDataURL(blob);
|
||||
await promise;
|
||||
});
|
||||
|
||||
// Empty MIME type
|
||||
testing.async(async () => {
|
||||
const reader = new FileReader();
|
||||
const blob = new Blob(["test"]);
|
||||
|
||||
const promise = new Promise((resolve) => {
|
||||
reader.onload = function() {
|
||||
testing.expectEqual("data:application/octet-stream;base64,dGVzdA==", reader.result);
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
|
||||
reader.readAsDataURL(blob);
|
||||
await promise;
|
||||
});
|
||||
</script>
|
||||
|
||||
<script id=readAsArrayBuffer>
|
||||
testing.async(async () => {
|
||||
const reader = new FileReader();
|
||||
const blob = new Blob([new Uint8Array([65, 66, 67])]);
|
||||
|
||||
const promise = new Promise((resolve) => {
|
||||
reader.onload = function() {
|
||||
const result = reader.result;
|
||||
testing.expectEqual(true, result instanceof ArrayBuffer);
|
||||
testing.expectEqual(3, result.byteLength);
|
||||
|
||||
const view = new Uint8Array(result);
|
||||
testing.expectEqual(65, view[0]);
|
||||
testing.expectEqual(66, view[1]);
|
||||
testing.expectEqual(67, view[2]);
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
|
||||
reader.readAsArrayBuffer(blob);
|
||||
await promise;
|
||||
});
|
||||
</script>
|
||||
|
||||
<script id=readAsBinaryString>
|
||||
testing.async(async () => {
|
||||
const reader = new FileReader();
|
||||
const blob = new Blob(["ABC"]);
|
||||
|
||||
const promise = new Promise((resolve) => {
|
||||
reader.onload = function() {
|
||||
testing.expectEqual("ABC", reader.result);
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
|
||||
reader.readAsBinaryString(blob);
|
||||
await promise;
|
||||
});
|
||||
</script>
|
||||
|
||||
<script id=abort>
|
||||
// Test aborting when not loading (should do nothing)
|
||||
{
|
||||
const reader = new FileReader();
|
||||
reader.abort(); // Should not throw
|
||||
testing.expectEqual(0, reader.readyState);
|
||||
}
|
||||
|
||||
// Note: Testing abort during read is implementation-dependent.
|
||||
// In synchronous implementations (like ours), the read completes before abort can be called.
|
||||
// In async implementations (like Firefox), you can abort during the read.
|
||||
// We test that abort() at least doesn't throw and maintains correct state.
|
||||
</script>
|
||||
|
||||
<script id=multipleReads>
|
||||
testing.async(async () => {
|
||||
const reader = new FileReader();
|
||||
const blob1 = new Blob(["first"]);
|
||||
const blob2 = new Blob(["second"]);
|
||||
|
||||
// First read
|
||||
const promise1 = new Promise((resolve) => {
|
||||
reader.onload = function() {
|
||||
testing.expectEqual("first", reader.result);
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
reader.readAsText(blob1);
|
||||
await promise1;
|
||||
|
||||
// Second read - should work after first completes
|
||||
const promise2 = new Promise((resolve) => {
|
||||
reader.onload = function() {
|
||||
testing.expectEqual("second", reader.result);
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
reader.readAsText(blob2);
|
||||
await promise2;
|
||||
});
|
||||
</script>
|
||||
|
||||
<script id=addEventListener>
|
||||
testing.async(async () => {
|
||||
const reader = new FileReader();
|
||||
const blob = new Blob(["test"]);
|
||||
|
||||
let loadFired = false;
|
||||
|
||||
const promise = new Promise((resolve) => {
|
||||
reader.addEventListener("load", function() {
|
||||
loadFired = true;
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
reader.readAsText(blob);
|
||||
await promise;
|
||||
|
||||
testing.expectEqual(true, loadFired);
|
||||
});
|
||||
</script>
|
||||
94
src/browser/tests/frames/frames.html
Normal file
94
src/browser/tests/frames/frames.html
Normal file
@@ -0,0 +1,94 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<script>
|
||||
function frame1Onload() {
|
||||
window.f1_onload = 'f1_onload_loaded';
|
||||
}
|
||||
</script>
|
||||
|
||||
<iframe id=f1 onload="frame1Onload" src="support/sub 1.html"></iframe>
|
||||
<iframe id=f2 src="support/sub2.html"></iframe>
|
||||
|
||||
<script id="basic">
|
||||
// reload it
|
||||
$('#f2').src = 'support/sub2.html';
|
||||
|
||||
testing.eventually(() => {
|
||||
testing.expectEqual(undefined, window[10]);
|
||||
|
||||
testing.expectEqual(window, window[0].top);
|
||||
testing.expectEqual(window, window[0].parent);
|
||||
testing.expectEqual(false, window === window[0]);
|
||||
|
||||
testing.expectEqual(window, window[1].top);
|
||||
testing.expectEqual(window, window[1].parent);
|
||||
testing.expectEqual(false, window === window[1]);
|
||||
testing.expectEqual(false, window[0] === window[1]);
|
||||
|
||||
testing.expectEqual(0, $('#f1').childNodes.length);
|
||||
|
||||
testing.expectEqual(testing.BASE_URL + 'frames/support/sub%201.html', $('#f1').src);
|
||||
testing.expectEqual(window[0], $('#f1').contentWindow);
|
||||
testing.expectEqual(window[1], $('#f2').contentWindow);
|
||||
|
||||
testing.expectEqual(window[0].document, $('#f1').contentDocument);
|
||||
testing.expectEqual(window[1].document, $('#f2').contentDocument);
|
||||
|
||||
// sibling frames share the same top
|
||||
testing.expectEqual(window[0].top, window[1].top);
|
||||
|
||||
// child frames have no sub-frames
|
||||
testing.expectEqual(0, window[0].length);
|
||||
testing.expectEqual(0, window[1].length);
|
||||
|
||||
// self and window are self-referential on child frames
|
||||
testing.expectEqual(window[0], window[0].self);
|
||||
testing.expectEqual(window[0], window[0].window);
|
||||
testing.expectEqual(window[1], window[1].self);
|
||||
|
||||
// child frame's top.parent is itself (root has no parent)
|
||||
testing.expectEqual(window, window[0].top.parent);
|
||||
|
||||
// Todo: Context security tokens
|
||||
// testing.expectEqual(true, window.sub1_loaded);
|
||||
// testing.expectEqual(true, window.sub2_loaded);
|
||||
// testing.expectEqual(1, window.sub1_count);
|
||||
// testing.expectEqual(2, window.sub2_count);
|
||||
});
|
||||
</script>
|
||||
|
||||
<script id=onload>
|
||||
{
|
||||
let f3_load_event = false;
|
||||
let f3 = document.createElement('iframe');
|
||||
f3.addEventListener('load', () => {
|
||||
f3_load_event = true;
|
||||
});
|
||||
f3.src = 'invalid'; // still fires load!
|
||||
document.documentElement.appendChild(f3);
|
||||
|
||||
testing.eventually(() => {
|
||||
testing.expectEqual('f1_onload_loaded', window.f1_onload);
|
||||
testing.expectEqual(true, f3_load_event);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=onload>
|
||||
{
|
||||
let f4 = document.createElement('iframe');
|
||||
f4.src = "about:blank";
|
||||
document.documentElement.appendChild(f4);
|
||||
|
||||
testing.eventually(() => {
|
||||
testing.expectEqual("<html><head></head><body></body></html>", f4.contentDocument.documentElement.outerHTML);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=count>
|
||||
testing.eventually(() => {
|
||||
testing.expectEqual(4, window.length);
|
||||
});
|
||||
</script>
|
||||
7
src/browser/tests/frames/support/sub 1.html
Normal file
7
src/browser/tests/frames/support/sub 1.html
Normal file
@@ -0,0 +1,7 @@
|
||||
<!DOCTYPE html>
|
||||
<div id=div-1>sub1 div1</div>
|
||||
<script>
|
||||
// should not have access to the parent's JS context
|
||||
window.top.sub1_loaded = window.testing == undefined;
|
||||
window.top.sub1_count = (window.top.sub1_count || 0) + 1;
|
||||
</script>
|
||||
8
src/browser/tests/frames/support/sub2.html
Normal file
8
src/browser/tests/frames/support/sub2.html
Normal file
@@ -0,0 +1,8 @@
|
||||
<!DOCTYPE html>
|
||||
<div id=div-1>sub2 div1</div>
|
||||
|
||||
<script>
|
||||
// should not have access to the parent's JS context
|
||||
window.top.sub2_loaded = window.testing == undefined;
|
||||
window.top.sub2_count = (window.top.sub2_count || 0) + 1;
|
||||
</script>
|
||||
@@ -59,10 +59,6 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=constructor-invalid-colorspace>
|
||||
testing.expectError("TypeError", () => {
|
||||
new ImageData(5, 5, { colorSpace: "display-p3" });
|
||||
});
|
||||
</script>
|
||||
|
||||
<script id=single-pixel>
|
||||
@@ -73,3 +69,7 @@
|
||||
testing.expectEqual(1, img.height);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=too-large>
|
||||
testing.expectError("IndexSizeError", () => new ImageData(2_147_483_648, 2_147_483_648));
|
||||
</script>
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
testing.expectEqual(5, input.maxLength);
|
||||
input.maxLength = 'banana';
|
||||
testing.expectEqual(0, input.maxLength);
|
||||
testing.expectError('Error: NegativeValueNotAllowed', () => { input.maxLength = -45;});
|
||||
testing.expectError('IndexSizeError: Index or size is negative or greater than the allowed amount', () => { input.maxLength = -45;});
|
||||
|
||||
testing.expectEqual(20, input.size);
|
||||
input.size = 5;
|
||||
|
||||
@@ -19,3 +19,13 @@
|
||||
</script>
|
||||
|
||||
<script id=datauri src="data:text/plain;charset=utf-8;base64,dGVzdGluZy5leHBlY3RFcXVhbCh0cnVlLCB0cnVlKTs="></script>
|
||||
|
||||
<script id=datauri_url_encoded_text src="data:text/javascript,testing.expectEqual(3, 3);"></script>
|
||||
|
||||
<script id=datauri_encoded_padding src="data:text/javascript;base64,dGVzdGluZy5leHBlY3RFcXVhbCgxLCAxKTs%3D"></script>
|
||||
|
||||
<script id=datauri_fully_encoded src="data:text/javascript;base64,%64%47%56%7a%64%47%6c%75%5a%79%35%6c%65%48%42%6c%59%33%52%46%63%58%56%68%62%43%67%79%4c%43%41%79%4b%54%73%3d"></script>
|
||||
|
||||
<script id=datauri_with_whitespace src="data:text/javascript;base64,%20ZD%20Qg%0D%0APS%20An%20Zm91cic%0D%0A%207%20"></script>
|
||||
|
||||
<script id=datauri_url_encoded_unicode src="data:text/javascript,testing.expectEqual(4%2C%204)%3B"></script>
|
||||
|
||||
@@ -180,6 +180,13 @@
|
||||
|
||||
testing.expectEqual(true, response.body !== null);
|
||||
testing.expectEqual(true, response.body instanceof ReadableStream);
|
||||
|
||||
const buf = await response.arrayBuffer()
|
||||
restore();
|
||||
|
||||
const uint8array = new Uint8Array(buf);
|
||||
const decoder = new TextDecoder('utf-8');
|
||||
testing.expectEqual('1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890', decoder.decode(uint8array));
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -602,6 +602,114 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=disabledFieldset>
|
||||
{
|
||||
// Elements inside a disabled fieldset should not be included
|
||||
const form = document.createElement('form');
|
||||
|
||||
const fieldset = document.createElement('fieldset');
|
||||
fieldset.disabled = true;
|
||||
|
||||
const inside = document.createElement('input');
|
||||
inside.name = 'inside';
|
||||
inside.value = 'nope';
|
||||
fieldset.appendChild(inside);
|
||||
|
||||
const outside = document.createElement('input');
|
||||
outside.name = 'outside';
|
||||
outside.value = 'yes';
|
||||
|
||||
form.appendChild(fieldset);
|
||||
form.appendChild(outside);
|
||||
|
||||
const fd = new FormData(form);
|
||||
testing.expectEqual(null, fd.get('inside'));
|
||||
testing.expectEqual('yes', fd.get('outside'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=disabledFieldsetLegendExemption>
|
||||
{
|
||||
// Elements inside the FIRST legend of a disabled fieldset are NOT disabled
|
||||
const form = document.createElement('form');
|
||||
|
||||
const fieldset = document.createElement('fieldset');
|
||||
fieldset.disabled = true;
|
||||
|
||||
const legend = document.createElement('legend');
|
||||
const inLegend = document.createElement('input');
|
||||
inLegend.name = 'in-legend';
|
||||
inLegend.value = 'exempt';
|
||||
legend.appendChild(inLegend);
|
||||
|
||||
const notInLegend = document.createElement('input');
|
||||
notInLegend.name = 'not-in-legend';
|
||||
notInLegend.value = 'nope';
|
||||
|
||||
fieldset.appendChild(legend);
|
||||
fieldset.appendChild(notInLegend);
|
||||
form.appendChild(fieldset);
|
||||
|
||||
const fd = new FormData(form);
|
||||
testing.expectEqual('exempt', fd.get('in-legend'));
|
||||
testing.expectEqual(null, fd.get('not-in-legend'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=disabledFieldsetSecondLegend>
|
||||
{
|
||||
// Only the FIRST legend gets the exemption; second legend inputs are still disabled
|
||||
const form = document.createElement('form');
|
||||
|
||||
const fieldset = document.createElement('fieldset');
|
||||
fieldset.disabled = true;
|
||||
|
||||
const legend1 = document.createElement('legend');
|
||||
const inLegend1 = document.createElement('input');
|
||||
inLegend1.name = 'first-legend';
|
||||
inLegend1.value = 'exempt';
|
||||
legend1.appendChild(inLegend1);
|
||||
|
||||
const legend2 = document.createElement('legend');
|
||||
const inLegend2 = document.createElement('input');
|
||||
inLegend2.name = 'second-legend';
|
||||
inLegend2.value = 'nope';
|
||||
legend2.appendChild(inLegend2);
|
||||
|
||||
fieldset.appendChild(legend1);
|
||||
fieldset.appendChild(legend2);
|
||||
form.appendChild(fieldset);
|
||||
|
||||
const fd = new FormData(form);
|
||||
testing.expectEqual('exempt', fd.get('first-legend'));
|
||||
testing.expectEqual(null, fd.get('second-legend'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=disabledFieldsetNested>
|
||||
{
|
||||
// Outer fieldset disabled: inner enabled fieldset's elements are still disabled
|
||||
const form = document.createElement('form');
|
||||
|
||||
const outer = document.createElement('fieldset');
|
||||
outer.disabled = true;
|
||||
|
||||
const inner = document.createElement('fieldset');
|
||||
// inner is NOT disabled itself
|
||||
|
||||
const input = document.createElement('input');
|
||||
input.name = 'deep';
|
||||
input.value = 'nope';
|
||||
inner.appendChild(input);
|
||||
|
||||
outer.appendChild(inner);
|
||||
form.appendChild(outer);
|
||||
|
||||
const fd = new FormData(form);
|
||||
testing.expectEqual(null, fd.get('deep'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=imageWithoutName>
|
||||
{
|
||||
// Test that image input without name still submits x and y coordinates
|
||||
|
||||
@@ -111,7 +111,7 @@
|
||||
<script id=legacy>
|
||||
{
|
||||
let request = new Request("flower.png");
|
||||
testing.expectEqual("http://127.0.0.1:9582/src/browser/tests/net/flower.png", request.url);
|
||||
testing.expectEqual(testing.BASE_URL + 'net/flower.png', request.url);
|
||||
testing.expectEqual("GET", request.method);
|
||||
|
||||
let request2 = new Request("https://google.com", {
|
||||
|
||||
@@ -252,3 +252,34 @@
|
||||
testing.expectEqual(XMLHttpRequest.UNSENT, req.readyState);
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
<script id=xhr_abort_callback_nobody>
|
||||
testing.async(async (restore) => {
|
||||
const req = new XMLHttpRequest();
|
||||
let abortFired = false;
|
||||
let errorFired = false;
|
||||
let loadEndFired = false;
|
||||
|
||||
await new Promise((resolve) => {
|
||||
req.onabort = () => { abortFired = true; };
|
||||
req.onerror = () => { errorFired = true; };
|
||||
req.onloadend = () => {
|
||||
loadEndFired = true;
|
||||
resolve();
|
||||
};
|
||||
|
||||
req.open('GET', 'http://127.0.0.1:9582/xhr_empty');
|
||||
req.onreadystatechange = (e) => {
|
||||
req.abort();
|
||||
}
|
||||
req.send();
|
||||
});
|
||||
|
||||
restore();
|
||||
testing.expectEqual(true, abortFired);
|
||||
testing.expectEqual(true, errorFired);
|
||||
testing.expectEqual(true, loadEndFired);
|
||||
testing.expectEqual(XMLHttpRequest.UNSENT, req.readyState);
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<a href="foo" id="foo">foo</a>
|
||||
|
||||
<script id=baseURI>
|
||||
testing.expectEqual("http://127.0.0.1:9582/src/browser/tests/node/base_uri.html", document.URL);
|
||||
testing.expectEqual(testing.BASE_URL + 'node/base_uri.html', document.URL);
|
||||
testing.expectEqual("https://example.com/", document.baseURI);
|
||||
|
||||
const link = $('#foo');
|
||||
|
||||
24
src/browser/tests/node/noscript_serialization.html
Normal file
24
src/browser/tests/node/noscript_serialization.html
Normal file
@@ -0,0 +1,24 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<!-- When scripting is enabled the HTML parser treats <noscript> as a raw text
|
||||
element: its entire content is stored as a single text node containing the
|
||||
raw markup. Serializing it back (outerHTML / innerHTML) must output that
|
||||
markup as-is without HTML-escaping the angle brackets. -->
|
||||
<noscript id="ns1"><h1>Hello</h1><p>World</p></noscript>
|
||||
<noscript id="ns2"><div id="bsky_post_summary"><h3>Post</h3><p id="bsky_display_name">Henri Helvetica</p></div></noscript>
|
||||
|
||||
<script id="noscript-outerHTML">
|
||||
const ns1 = document.getElementById('ns1');
|
||||
testing.expectEqual('<noscript id="ns1"><h1>Hello</h1><p>World</p></noscript>', ns1.outerHTML);
|
||||
</script>
|
||||
|
||||
<script id="noscript-innerHTML">
|
||||
const ns2 = document.getElementById('ns2');
|
||||
testing.expectEqual('<div id="bsky_post_summary"><h3>Post</h3><p id="bsky_display_name">Henri Helvetica</p></div>', ns2.innerHTML);
|
||||
</script>
|
||||
|
||||
<script id="noscript-textContent">
|
||||
// The raw text node content must be the literal HTML markup (not parsed DOM)
|
||||
testing.expectEqual('<h1>Hello</h1><p>World</p>', ns1.firstChild.nodeValue);
|
||||
</script>
|
||||
@@ -252,6 +252,72 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=measure_with_navigation_timing_marks>
|
||||
{
|
||||
// performance.measure() must accept PerformanceTiming attribute names
|
||||
// (e.g. "fetchStart") as start/end marks per the W3C User Timing Level 2 spec.
|
||||
// https://www.w3.org/TR/user-timing/#dom-performance-measure
|
||||
performance.clearMarks();
|
||||
performance.clearMeasures();
|
||||
|
||||
performance.mark("mark-dataComplete");
|
||||
let m = performance.measure("dataComplete", "fetchStart", "mark-dataComplete");
|
||||
testing.expectEqual('dataComplete', m.name);
|
||||
testing.expectEqual('measure', m.entryType);
|
||||
testing.expectEqual(true, m.duration >= 0);
|
||||
|
||||
// navigationStart is also a valid mark name (was already supported)
|
||||
performance.mark("mark-end");
|
||||
let m2 = performance.measure("fromNav", "navigationStart", "mark-end");
|
||||
testing.expectEqual('fromNav', m2.name);
|
||||
testing.expectEqual(true, m2.duration >= 0);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=performance_timing_exists>
|
||||
{
|
||||
// performance.timing must not be undefined (used by sites like Bing)
|
||||
testing.expectEqual(true, performance.timing !== undefined);
|
||||
testing.expectEqual(true, performance.timing !== null);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=performance_timing_navigationStart>
|
||||
{
|
||||
// navigationStart must be a number (sites access performance.timing.navigationStart)
|
||||
const timing = performance.timing;
|
||||
testing.expectEqual('number', typeof timing.navigationStart);
|
||||
testing.expectEqual(0, timing.navigationStart);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=performance_timing_all_properties>
|
||||
{
|
||||
// All PerformanceTiming properties must be accessible and return numbers
|
||||
const timing = performance.timing;
|
||||
const props = [
|
||||
'navigationStart', 'unloadEventStart', 'unloadEventEnd',
|
||||
'redirectStart', 'redirectEnd', 'fetchStart',
|
||||
'domainLookupStart', 'domainLookupEnd',
|
||||
'connectStart', 'connectEnd', 'secureConnectionStart',
|
||||
'requestStart', 'responseStart', 'responseEnd',
|
||||
'domLoading', 'domInteractive',
|
||||
'domContentLoadedEventStart', 'domContentLoadedEventEnd',
|
||||
'domComplete', 'loadEventStart', 'loadEventEnd',
|
||||
];
|
||||
for (const prop of props) {
|
||||
testing.expectEqual('number', typeof timing[prop]);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=performance_timing_same_object>
|
||||
{
|
||||
// performance.timing should return the same object on each access
|
||||
testing.expectEqual(true, performance.timing === performance.timing);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=mixed_marks_and_measures>
|
||||
{
|
||||
performance.clearMarks();
|
||||
@@ -280,3 +346,50 @@
|
||||
testing.expectEqual(0, remainingMarks.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=performance_timing_exists>
|
||||
{
|
||||
// Navigation Timing Level 1: performance.timing must be an object, not undefined
|
||||
testing.expectEqual('object', typeof performance.timing);
|
||||
testing.expectEqual(false, performance.timing === null);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=performance_timing_navigationStart>
|
||||
{
|
||||
// The most commonly used property — must be a number (not undefined)
|
||||
testing.expectEqual('number', typeof performance.timing.navigationStart);
|
||||
testing.expectEqual(0, performance.timing.navigationStart);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=performance_navigation_exists>
|
||||
{
|
||||
// Navigation Timing Level 1: performance.navigation must be an object, not undefined
|
||||
testing.expectEqual('object', typeof performance.navigation);
|
||||
testing.expectEqual(false, performance.navigation === null);
|
||||
testing.expectEqual('number', typeof performance.navigation.type);
|
||||
testing.expectEqual('number', typeof performance.navigation.redirectCount);
|
||||
testing.expectEqual(0, performance.navigation.type);
|
||||
testing.expectEqual(0, performance.navigation.redirectCount);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=performance_timing_all_properties>
|
||||
{
|
||||
const t = performance.timing;
|
||||
const props = [
|
||||
'navigationStart', 'unloadEventStart', 'unloadEventEnd',
|
||||
'redirectStart', 'redirectEnd', 'fetchStart',
|
||||
'domainLookupStart', 'domainLookupEnd',
|
||||
'connectStart', 'connectEnd', 'secureConnectionStart',
|
||||
'requestStart', 'responseStart', 'responseEnd',
|
||||
'domLoading', 'domInteractive',
|
||||
'domContentLoadedEventStart', 'domContentLoadedEventEnd',
|
||||
'domComplete', 'loadEventStart', 'loadEventEnd',
|
||||
];
|
||||
for (const prop of props) {
|
||||
testing.expectEqual('number', typeof t[prop]);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -546,14 +546,14 @@
|
||||
{
|
||||
const sel = window.getSelection();
|
||||
sel.removeAllRanges();
|
||||
|
||||
let eventCount = 0;
|
||||
let lastEvent = null;
|
||||
|
||||
document.addEventListener('selectionchange', (e) => {
|
||||
const listener = (e) => {
|
||||
eventCount++;
|
||||
lastEvent = e;
|
||||
});
|
||||
};
|
||||
document.addEventListener('selectionchange', listener);
|
||||
|
||||
const p1 = document.getElementById("p1");
|
||||
const textNode = p1.firstChild;
|
||||
@@ -563,27 +563,25 @@
|
||||
sel.extend(textNode, 10);
|
||||
sel.collapseToStart();
|
||||
sel.collapseToEnd();
|
||||
|
||||
sel.removeAllRanges();
|
||||
const range = document.createRange();
|
||||
range.setStart(textNode, 4);
|
||||
range.setEnd(textNode, 15);
|
||||
sel.addRange(range);
|
||||
|
||||
sel.removeRange(range);
|
||||
|
||||
const newRange = document.createRange();
|
||||
newRange.selectNodeContents(p1);
|
||||
sel.addRange(newRange);
|
||||
sel.removeAllRanges();
|
||||
|
||||
sel.selectAllChildren(nested);
|
||||
sel.setBaseAndExtent(textNode, 4, textNode, 15);
|
||||
|
||||
sel.collapse(textNode, 5);
|
||||
sel.extend(textNode, 10);
|
||||
sel.deleteFromDocument();
|
||||
|
||||
document.removeEventListener('selectionchange', listener);
|
||||
textNode.textContent = "The quick brown fox";
|
||||
|
||||
testing.eventually(() => {
|
||||
testing.expectEqual(14, eventCount);
|
||||
testing.expectEqual('selectionchange', lastEvent.type);
|
||||
@@ -593,3 +591,149 @@
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=modifyCharacterForward>
|
||||
{
|
||||
const sel = window.getSelection();
|
||||
const p1 = document.getElementById("p1");
|
||||
const textNode = p1.firstChild; // "The quick brown fox"
|
||||
|
||||
// Collapse to position 4 (after "The ")
|
||||
sel.collapse(textNode, 4);
|
||||
testing.expectEqual(4, sel.anchorOffset);
|
||||
|
||||
// Move forward one character
|
||||
sel.modify("move", "forward", "character");
|
||||
testing.expectEqual(5, sel.anchorOffset);
|
||||
testing.expectEqual(true, sel.isCollapsed);
|
||||
testing.expectEqual("none", sel.direction);
|
||||
|
||||
// Move forward again
|
||||
sel.modify("move", "forward", "character");
|
||||
testing.expectEqual(6, sel.anchorOffset);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=modifyWordForward>
|
||||
{
|
||||
const sel = window.getSelection();
|
||||
const p1 = document.getElementById("p1");
|
||||
const textNode = p1.firstChild; // "The quick brown fox"
|
||||
|
||||
// Collapse to start
|
||||
sel.collapse(textNode, 0);
|
||||
|
||||
// Move forward one word - should land at end of "The"
|
||||
sel.modify("move", "forward", "word");
|
||||
testing.expectEqual(3, sel.anchorOffset);
|
||||
testing.expectEqual(true, sel.isCollapsed);
|
||||
|
||||
// Move forward again - should skip space and land at end of "quick"
|
||||
sel.modify("move", "forward", "word");
|
||||
testing.expectEqual(9, sel.anchorOffset);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=modifyCharacterBackward>
|
||||
{
|
||||
const sel = window.getSelection();
|
||||
const p1 = document.getElementById("p1");
|
||||
const textNode = p1.firstChild; // "The quick brown fox"
|
||||
|
||||
// Collapse to position 6
|
||||
sel.collapse(textNode, 6);
|
||||
testing.expectEqual(6, sel.anchorOffset);
|
||||
|
||||
// Move backward one character
|
||||
sel.modify("move", "backward", "character");
|
||||
testing.expectEqual(5, sel.anchorOffset);
|
||||
testing.expectEqual(true, sel.isCollapsed);
|
||||
testing.expectEqual("none", sel.direction);
|
||||
|
||||
// Move backward again
|
||||
sel.modify("move", "backward", "character");
|
||||
testing.expectEqual(4, sel.anchorOffset);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=modifyWordBackward>
|
||||
{
|
||||
const sel = window.getSelection();
|
||||
const p1 = document.getElementById("p1");
|
||||
const textNode = p1.firstChild; // "The quick brown fox"
|
||||
|
||||
// Collapse to end of "quick" (offset 9)
|
||||
sel.collapse(textNode, 9);
|
||||
|
||||
// Move backward one word - should land at start of "quick"
|
||||
sel.modify("move", "backward", "word");
|
||||
testing.expectEqual(4, sel.anchorOffset);
|
||||
testing.expectEqual(true, sel.isCollapsed);
|
||||
|
||||
// Move backward again - should land at start of "The"
|
||||
sel.modify("move", "backward", "word");
|
||||
testing.expectEqual(0, sel.anchorOffset);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=modifyCharacterForwardFromElementNode>
|
||||
{
|
||||
const sel = window.getSelection();
|
||||
const p1 = document.getElementById("p1");
|
||||
sel.collapse(p1, 1);
|
||||
|
||||
testing.expectEqual(p1, sel.anchorNode);
|
||||
testing.expectEqual(1, sel.anchorOffset);
|
||||
testing.expectEqual(true, sel.isCollapsed);
|
||||
|
||||
sel.modify("move", "forward", "character");
|
||||
|
||||
testing.expectEqual(3, sel.anchorNode.nodeType);
|
||||
testing.expectEqual(true, sel.anchorNode !== p1.firstChild);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=modifyCharacterForwardFromElementNodeMidChildren>
|
||||
{
|
||||
const sel = window.getSelection();
|
||||
const nested = document.getElementById("nested");
|
||||
|
||||
sel.collapse(nested, nested.childNodes.length);
|
||||
|
||||
testing.expectEqual(nested, sel.anchorNode);
|
||||
testing.expectEqual(nested.childNodes.length, sel.anchorOffset);
|
||||
|
||||
sel.modify("move", "forward", "character");
|
||||
|
||||
// Must land on a text node strictly after #nested
|
||||
testing.expectEqual(3, sel.anchorNode.nodeType);
|
||||
testing.expectEqual(false, nested.contains(sel.anchorNode));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=modifyWordForwardFromElementNode>
|
||||
{
|
||||
const sel = window.getSelection();
|
||||
const p1 = document.getElementById("p1");
|
||||
sel.collapse(p1, 1);
|
||||
|
||||
sel.modify("move", "forward", "word");
|
||||
|
||||
// Must land on a text node strictly after p1
|
||||
testing.expectEqual(3, sel.anchorNode.nodeType);
|
||||
testing.expectEqual(false, p1.contains(sel.anchorNode));
|
||||
testing.expectEqual(true, sel.isCollapsed);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=modifyCharacterForwardNewNodeOffsetNotElement>
|
||||
{
|
||||
const sel = window.getSelection();
|
||||
const p1 = document.getElementById("p1");
|
||||
|
||||
sel.collapse(p1, 1);
|
||||
sel.modify("move", "forward", "character");
|
||||
|
||||
testing.expectEqual(3, sel.anchorNode.nodeType);
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -88,3 +88,12 @@
|
||||
localStorage.clear();
|
||||
testing.expectEqual(0, localStorage.length)
|
||||
</script>
|
||||
|
||||
<script id="localstorage_limits">
|
||||
localStorage.clear();
|
||||
for (i = 0; i < 5; i++) {
|
||||
const v = "v".repeat(1024 * 1024);
|
||||
localStorage.setItem(v, v);
|
||||
}
|
||||
testing.expectError("QuotaExceededError", () => localStorage.setItem("last", "v"));
|
||||
</script>
|
||||
|
||||
@@ -301,3 +301,74 @@
|
||||
testing.expectEqual(false, data3.done);
|
||||
})();
|
||||
</script>
|
||||
|
||||
<script id=enqueue_preserves_number>
|
||||
(async function() {
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(42);
|
||||
controller.enqueue(0);
|
||||
controller.enqueue(3.14);
|
||||
controller.close();
|
||||
}
|
||||
});
|
||||
|
||||
const reader = stream.getReader();
|
||||
|
||||
const r1 = await reader.read();
|
||||
testing.expectEqual(false, r1.done);
|
||||
testing.expectEqual('number', typeof r1.value);
|
||||
testing.expectEqual(42, r1.value);
|
||||
|
||||
const r2 = await reader.read();
|
||||
testing.expectEqual('number', typeof r2.value);
|
||||
testing.expectEqual(0, r2.value);
|
||||
|
||||
const r3 = await reader.read();
|
||||
testing.expectEqual('number', typeof r3.value);
|
||||
testing.expectEqual(3.14, r3.value);
|
||||
|
||||
const r4 = await reader.read();
|
||||
testing.expectEqual(true, r4.done);
|
||||
})();
|
||||
</script>
|
||||
|
||||
<script id=enqueue_preserves_bool>
|
||||
(async function() {
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(true);
|
||||
controller.enqueue(false);
|
||||
controller.close();
|
||||
}
|
||||
});
|
||||
|
||||
const reader = stream.getReader();
|
||||
|
||||
const r1 = await reader.read();
|
||||
testing.expectEqual('boolean', typeof r1.value);
|
||||
testing.expectEqual(true, r1.value);
|
||||
|
||||
const r2 = await reader.read();
|
||||
testing.expectEqual('boolean', typeof r2.value);
|
||||
testing.expectEqual(false, r2.value);
|
||||
})();
|
||||
</script>
|
||||
|
||||
<script id=enqueue_preserves_object>
|
||||
(async function() {
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue({ key: 'value', num: 7 });
|
||||
controller.close();
|
||||
}
|
||||
});
|
||||
|
||||
const reader = stream.getReader();
|
||||
|
||||
const r1 = await reader.read();
|
||||
testing.expectEqual('object', typeof r1.value);
|
||||
testing.expectEqual('value', r1.value.key);
|
||||
testing.expectEqual(7, r1.value.num);
|
||||
})();
|
||||
</script>
|
||||
|
||||
82
src/browser/tests/streams/text_decoder_stream.html
Normal file
82
src/browser/tests/streams/text_decoder_stream.html
Normal file
@@ -0,0 +1,82 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<script id=text_decoder_stream_encoding>
|
||||
{
|
||||
const tds = new TextDecoderStream();
|
||||
testing.expectEqual('utf-8', tds.encoding);
|
||||
testing.expectEqual('object', typeof tds.readable);
|
||||
testing.expectEqual('object', typeof tds.writable);
|
||||
testing.expectEqual(false, tds.fatal);
|
||||
testing.expectEqual(false, tds.ignoreBOM);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=text_decoder_stream_with_label>
|
||||
{
|
||||
const tds = new TextDecoderStream('utf-8');
|
||||
testing.expectEqual('utf-8', tds.encoding);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=text_decoder_stream_with_opts>
|
||||
{
|
||||
const tds = new TextDecoderStream('utf-8', { fatal: true, ignoreBOM: true });
|
||||
testing.expectEqual(true, tds.fatal);
|
||||
testing.expectEqual(true, tds.ignoreBOM);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=text_decoder_stream_invalid_label>
|
||||
{
|
||||
let errorThrown = false;
|
||||
try {
|
||||
new TextDecoderStream('windows-1252');
|
||||
} catch (e) {
|
||||
errorThrown = true;
|
||||
}
|
||||
testing.expectEqual(true, errorThrown);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=text_decoder_stream_decode>
|
||||
(async function() {
|
||||
const tds = new TextDecoderStream();
|
||||
|
||||
const writer = tds.writable.getWriter();
|
||||
const reader = tds.readable.getReader();
|
||||
|
||||
// 'hello' in UTF-8 bytes
|
||||
const bytes = new Uint8Array([104, 101, 108, 108, 111]);
|
||||
await writer.write(bytes);
|
||||
await writer.close();
|
||||
|
||||
const result = await reader.read();
|
||||
testing.expectEqual(false, result.done);
|
||||
testing.expectEqual('hello', result.value);
|
||||
|
||||
const result2 = await reader.read();
|
||||
testing.expectEqual(true, result2.done);
|
||||
})();
|
||||
</script>
|
||||
|
||||
<script id=text_decoder_stream_empty_chunk>
|
||||
(async function() {
|
||||
const tds = new TextDecoderStream();
|
||||
const writer = tds.writable.getWriter();
|
||||
const reader = tds.readable.getReader();
|
||||
|
||||
// Write an empty chunk followed by real data
|
||||
await writer.write(new Uint8Array([]));
|
||||
await writer.write(new Uint8Array([104, 105]));
|
||||
await writer.close();
|
||||
|
||||
// Empty chunk should be filtered out; first read gets "hi"
|
||||
const result = await reader.read();
|
||||
testing.expectEqual(false, result.done);
|
||||
testing.expectEqual('hi', result.value);
|
||||
|
||||
const result2 = await reader.read();
|
||||
testing.expectEqual(true, result2.done);
|
||||
})();
|
||||
</script>
|
||||
164
src/browser/tests/streams/transform_stream.html
Normal file
164
src/browser/tests/streams/transform_stream.html
Normal file
@@ -0,0 +1,164 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<script id=transform_stream_basic>
|
||||
{
|
||||
const ts = new TransformStream();
|
||||
testing.expectEqual('object', typeof ts);
|
||||
testing.expectEqual('object', typeof ts.readable);
|
||||
testing.expectEqual('object', typeof ts.writable);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=transform_stream_with_transformer>
|
||||
(async function() {
|
||||
const ts = new TransformStream({
|
||||
transform(chunk, controller) {
|
||||
controller.enqueue(chunk.toUpperCase());
|
||||
}
|
||||
});
|
||||
|
||||
const writer = ts.writable.getWriter();
|
||||
const reader = ts.readable.getReader();
|
||||
|
||||
await writer.write('hello');
|
||||
await writer.close();
|
||||
|
||||
const result = await reader.read();
|
||||
testing.expectEqual(false, result.done);
|
||||
testing.expectEqual('HELLO', result.value);
|
||||
|
||||
const result2 = await reader.read();
|
||||
testing.expectEqual(true, result2.done);
|
||||
})();
|
||||
</script>
|
||||
|
||||
<script id=writable_stream_basic>
|
||||
{
|
||||
const ws = new WritableStream();
|
||||
testing.expectEqual('object', typeof ws);
|
||||
testing.expectEqual(false, ws.locked);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=writable_stream_writer>
|
||||
{
|
||||
const ws = new WritableStream();
|
||||
const writer = ws.getWriter();
|
||||
testing.expectEqual('object', typeof writer);
|
||||
testing.expectEqual(true, ws.locked);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=writable_stream_writer_desired_size>
|
||||
{
|
||||
const ws = new WritableStream();
|
||||
const writer = ws.getWriter();
|
||||
testing.expectEqual(1, writer.desiredSize);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=text_encoder_stream_encoding>
|
||||
{
|
||||
const tes = new TextEncoderStream();
|
||||
testing.expectEqual('utf-8', tes.encoding);
|
||||
testing.expectEqual('object', typeof tes.readable);
|
||||
testing.expectEqual('object', typeof tes.writable);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=text_encoder_stream_encode>
|
||||
(async function() {
|
||||
const tes = new TextEncoderStream();
|
||||
|
||||
const writer = tes.writable.getWriter();
|
||||
const reader = tes.readable.getReader();
|
||||
|
||||
await writer.write('hi');
|
||||
await writer.close();
|
||||
|
||||
const result = await reader.read();
|
||||
testing.expectEqual(false, result.done);
|
||||
testing.expectEqual(true, result.value instanceof Uint8Array);
|
||||
// 'hi' in UTF-8 is [104, 105]
|
||||
testing.expectEqual(104, result.value[0]);
|
||||
testing.expectEqual(105, result.value[1]);
|
||||
testing.expectEqual(2, result.value.length);
|
||||
|
||||
const result2 = await reader.read();
|
||||
testing.expectEqual(true, result2.done);
|
||||
})();
|
||||
</script>
|
||||
|
||||
<script id=pipe_through_basic>
|
||||
(async function() {
|
||||
const input = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue('hello');
|
||||
controller.close();
|
||||
}
|
||||
});
|
||||
|
||||
const ts = new TransformStream({
|
||||
transform(chunk, controller) {
|
||||
controller.enqueue(chunk.toUpperCase());
|
||||
}
|
||||
});
|
||||
|
||||
const output = input.pipeThrough(ts);
|
||||
const reader = output.getReader();
|
||||
|
||||
const result = await reader.read();
|
||||
testing.expectEqual(false, result.done);
|
||||
testing.expectEqual('HELLO', result.value);
|
||||
|
||||
const result2 = await reader.read();
|
||||
testing.expectEqual(true, result2.done);
|
||||
})();
|
||||
</script>
|
||||
|
||||
<script id=pipe_to_basic>
|
||||
(async function() {
|
||||
const chunks = [];
|
||||
const input = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue('a');
|
||||
controller.enqueue('b');
|
||||
controller.close();
|
||||
}
|
||||
});
|
||||
|
||||
const ws = new WritableStream({
|
||||
write(chunk) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
});
|
||||
|
||||
await input.pipeTo(ws);
|
||||
testing.expectEqual(2, chunks.length);
|
||||
testing.expectEqual('a', chunks[0]);
|
||||
testing.expectEqual('b', chunks[1]);
|
||||
})();
|
||||
</script>
|
||||
|
||||
<script id=pipe_through_text_decoder>
|
||||
(async function() {
|
||||
const bytes = new Uint8Array([104, 101, 108, 108, 111]);
|
||||
const input = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(bytes);
|
||||
controller.close();
|
||||
}
|
||||
});
|
||||
|
||||
const output = input.pipeThrough(new TextDecoderStream());
|
||||
const reader = output.getReader();
|
||||
|
||||
const result = await reader.read();
|
||||
testing.expectEqual(false, result.done);
|
||||
testing.expectEqual('hello', result.value);
|
||||
|
||||
const result2 = await reader.read();
|
||||
testing.expectEqual(true, result2.done);
|
||||
})();
|
||||
</script>
|
||||
@@ -99,6 +99,9 @@
|
||||
}
|
||||
}
|
||||
|
||||
// our test runner sets this to true
|
||||
const IS_TEST_RUNNER = window._lightpanda_skip_auto_assert === true;
|
||||
|
||||
window.testing = {
|
||||
fail: fail,
|
||||
async: async,
|
||||
@@ -109,9 +112,24 @@
|
||||
expectError: expectError,
|
||||
withError: withError,
|
||||
eventually: eventually,
|
||||
todo: function(){},
|
||||
IS_TEST_RUNNER: IS_TEST_RUNNER,
|
||||
HOST: '127.0.0.1',
|
||||
ORIGIN: 'http://127.0.0.1:9582/',
|
||||
BASE_URL: 'http://127.0.0.1:9582/src/browser/tests/',
|
||||
};
|
||||
|
||||
if (!IS_TEST_RUNNER) {
|
||||
// The page is running in a different browser. Probably a developer making sure
|
||||
// a test is correct. There are a few tweaks we need to do to make this a
|
||||
// seemless, namely around adapting paths/urls.
|
||||
console.warn(`The page is not being executed in the test runner, certain behavior has been adjusted`);
|
||||
window.testing.HOST = location.hostname;
|
||||
window.testing.ORIGIN = location.origin + '/';
|
||||
window.testing.BASE_URL = location.origin + '/src/browser/tests/';
|
||||
window.addEventListener('load', testing.assertOk);
|
||||
}
|
||||
|
||||
|
||||
window.$ = function(sel) {
|
||||
return document.querySelector(sel);
|
||||
}
|
||||
|
||||
@@ -656,3 +656,45 @@
|
||||
testing.expectEqual("?a=%7E&b=%7E&c=foo", url.search);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=objectURL>
|
||||
{
|
||||
// Test createObjectURL with Blob
|
||||
const blob = new Blob(['<html><body>Hello</body></html>'], { type: 'text/html' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
|
||||
testing.expectEqual('string', typeof url);
|
||||
testing.expectEqual(true, url.startsWith('blob:'));
|
||||
testing.expectEqual(true, url.includes('http'));
|
||||
}
|
||||
|
||||
{
|
||||
// Test revokeObjectURL
|
||||
const blob = new Blob(['test'], { type: 'text/plain' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
|
||||
testing.expectEqual(true, url.startsWith('blob:'));
|
||||
|
||||
URL.revokeObjectURL(url);
|
||||
URL.revokeObjectURL(url); // Second revoke should be safe
|
||||
}
|
||||
|
||||
{
|
||||
// Test with non-blob URL (should be safe/silent)
|
||||
URL.revokeObjectURL('http://example.com/notblob');
|
||||
URL.revokeObjectURL('');
|
||||
testing.expectEqual(true, true);
|
||||
}
|
||||
|
||||
{
|
||||
// Test uniqueness
|
||||
const blob1 = new Blob(['test1']);
|
||||
const blob2 = new Blob(['test2']);
|
||||
const url1 = URL.createObjectURL(blob1);
|
||||
const url2 = URL.createObjectURL(blob2);
|
||||
|
||||
testing.expectEqual(false, url1 === url2);
|
||||
testing.expectEqual(true, url1.startsWith('blob:'));
|
||||
testing.expectEqual(true, url2.startsWith('blob:'));
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -2,24 +2,24 @@
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<script id=location>
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/window/location.html', window.location.href);
|
||||
testing.expectEqual(testing.BASE_URL + 'window/location.html', window.location.href);
|
||||
testing.expectEqual(document.location, window.location);
|
||||
</script>
|
||||
|
||||
<script id=location_hash>
|
||||
location.hash = "";
|
||||
testing.expectEqual("", location.hash);
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/window/location.html', location.href);
|
||||
testing.expectEqual(testing.BASE_URL + 'window/location.html', location.href);
|
||||
|
||||
location.hash = "#abcdef";
|
||||
testing.expectEqual("#abcdef", location.hash);
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/window/location.html#abcdef', location.href);
|
||||
testing.expectEqual(testing.BASE_URL + 'window/location.html#abcdef', location.href);
|
||||
|
||||
location.hash = "xyzxyz";
|
||||
testing.expectEqual("#xyzxyz", location.hash);
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/window/location.html#xyzxyz', location.href);
|
||||
testing.expectEqual(testing.BASE_URL + 'window/location.html#xyzxyz', location.href);
|
||||
|
||||
location.hash = "";
|
||||
testing.expectEqual("", location.hash);
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/window/location.html', location.href);
|
||||
testing.expectEqual(testing.BASE_URL + 'window/location.html', location.href);
|
||||
</script>
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
|
||||
<script id=screen>
|
||||
let screen = window.screen;
|
||||
testing.expectEqual(1920, screen.width);
|
||||
testing.expectEqual(1080, screen.height);
|
||||
if (testing.IS_TEST_RUNNER) {
|
||||
testing.expectEqual(1920, screen.width);
|
||||
testing.expectEqual(1080, screen.height);
|
||||
}
|
||||
|
||||
let orientation = screen.orientation;
|
||||
testing.expectEqual(0, orientation.angle);
|
||||
|
||||
@@ -37,6 +37,12 @@
|
||||
|
||||
restore();
|
||||
testing.expectEqual(2, scrollevt);
|
||||
testing.expectEqual(1, scrollendevt);
|
||||
// This test used to assert that scrollendevt == 1. The idea being that
|
||||
// the above resolve() would stop the test running after "scroll" fires but
|
||||
// before "scrollend" fires. That timing is pretty sensitive/fragile. If
|
||||
// the browser gets delayed and doesn't figure the scroll event exactly when
|
||||
// schedule, it could easily execute in the same sheduler.run call as the
|
||||
// scrollend.
|
||||
testing.expectEqual(true, scrollendevt === 1 || scrollendevt === 2);
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
<script id=setTimeout>
|
||||
testing.expectEqual(1, window.setTimeout.length);
|
||||
let wst2 = 1;
|
||||
@@ -32,3 +31,11 @@
|
||||
}, 1, 2, 3);
|
||||
testing.eventually(() => testing.expectEqual(5, wst2));
|
||||
</script>
|
||||
|
||||
<script id=invalid-timer-clear>
|
||||
// Surprisingly, these don't fail but silently ignored.
|
||||
clearTimeout(-1);
|
||||
clearInterval(-2);
|
||||
clearImmediate(-3);
|
||||
testing.expectEqual(true, true);
|
||||
</script>
|
||||
|
||||
@@ -75,6 +75,16 @@
|
||||
testing.expectEqual('abc', atob('YWJj'));
|
||||
testing.expectEqual('0123456789', atob('MDEyMzQ1Njc4OQ=='));
|
||||
testing.expectEqual('The quick brown fox jumps over the lazy dog', atob('VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZw=='));
|
||||
|
||||
// atob must accept unpadded base64 (forgiving-base64 decode per HTML spec)
|
||||
testing.expectEqual('a', atob('YQ')); // 2 chars, len%4==2, needs '=='
|
||||
testing.expectEqual('ab', atob('YWI')); // 3 chars, len%4==3, needs '='
|
||||
testing.expectEqual('ceil', atob('Y2VpbA')); // 6 chars, len%4==2, needs '=='
|
||||
|
||||
// length % 4 == 1 must still throw
|
||||
testing.expectError('Error: InvalidCharacterError', () => {
|
||||
atob('Y');
|
||||
});
|
||||
</script>
|
||||
|
||||
<script id=btoa_atob_roundtrip>
|
||||
|
||||
36
src/browser/tests/window_scroll.html
Normal file
36
src/browser/tests/window_scroll.html
Normal file
@@ -0,0 +1,36 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="testing.js"></script>
|
||||
|
||||
<script id=scrollBy_exists>
|
||||
testing.expectEqual('function', typeof window.scrollBy);
|
||||
</script>
|
||||
|
||||
<script id=scrollBy_xy>
|
||||
window.scrollTo(0, 0);
|
||||
testing.expectEqual(0, window.scrollX);
|
||||
testing.expectEqual(0, window.scrollY);
|
||||
window.scrollBy(100, 200);
|
||||
testing.expectEqual(100, window.scrollX);
|
||||
testing.expectEqual(200, window.scrollY);
|
||||
</script>
|
||||
|
||||
<script id=scrollBy_relative>
|
||||
window.scrollTo(100, 100);
|
||||
window.scrollBy(50, 50);
|
||||
testing.expectEqual(150, window.scrollX);
|
||||
testing.expectEqual(150, window.scrollY);
|
||||
</script>
|
||||
|
||||
<script id=scrollBy_opts>
|
||||
window.scrollTo(0, 0);
|
||||
window.scrollBy({ left: 30, top: 40 });
|
||||
testing.expectEqual(30, window.scrollX);
|
||||
testing.expectEqual(40, window.scrollY);
|
||||
</script>
|
||||
|
||||
<script id=scrollBy_negative_clamp>
|
||||
window.scrollTo(10, 10);
|
||||
window.scrollBy(-100, -100);
|
||||
testing.expectEqual(0, window.scrollX);
|
||||
testing.expectEqual(0, window.scrollY);
|
||||
</script>
|
||||
@@ -129,3 +129,14 @@
|
||||
testing.expectEqual(original, serialized);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=serializeAttribute>
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
div.setAttribute('over', '9000');
|
||||
|
||||
const serializer = new XMLSerializer();
|
||||
const serialized = serializer.serializeToString(div.getAttributeNode('over'));
|
||||
testing.expectEqual('', serialized);
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -38,7 +38,7 @@ pub fn getSignal(self: *const AbortController) *AbortSignal {
|
||||
}
|
||||
|
||||
pub fn abort(self: *AbortController, reason_: ?js.Value.Global, page: *Page) !void {
|
||||
try self._signal.abort(if (reason_) |r| .{ .js_val = r } else null, page.js.local.?, page);
|
||||
try self._signal.abort(if (reason_) |r| .{ .js_val = r } else null, page);
|
||||
}
|
||||
|
||||
pub const JsApi = struct {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user