Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8842355fb | ||
|
|
e9c888d8e8 | ||
|
|
c7c7285557 | ||
|
|
da503f254a | ||
|
|
43a3197d89 | ||
|
|
ce79a51417 | ||
|
|
d9c21dd67b | ||
|
|
64f76b2d94 | ||
|
|
808c8f8c97 | ||
|
|
a42d863e48 | ||
|
|
f62bf3f6dc | ||
|
|
eadf95b90a | ||
|
|
b81f1561c5 | ||
|
|
61d2ee29d5 | ||
|
|
882c0f3a0e | ||
|
|
dde60415d7 | ||
|
|
be60e4d7e4 | ||
|
|
8c2dcbf570 | ||
|
|
4fddee2d46 | ||
|
|
87f48c9b8a | ||
|
|
7d702fb188 | ||
|
|
42cbc45da2 | ||
|
|
97faaa84f2 | ||
|
|
e5cb8934a2 | ||
|
|
16abec2c09 | ||
|
|
742281ec3a | ||
|
|
c5e89a85d2 | ||
|
|
a8da4b117f | ||
|
|
4ba1cefcdd | ||
|
|
3378b8f3e2 | ||
|
|
07a03e41e9 | ||
|
|
22a098843a | ||
|
|
e76c63a6cb | ||
|
|
caae1ea0aa | ||
|
|
acb073dda7 | ||
|
|
081b3a1aa0 | ||
|
|
9460e8eb86 | ||
|
|
3abd710393 | ||
|
|
80034c9c84 | ||
|
|
820d88e8eb | ||
|
|
558a402fa9 | ||
|
|
2b3cbe0795 | ||
|
|
3dd1424a0a | ||
|
|
5847dfe87a | ||
|
|
622b6e82a7 | ||
|
|
4355274838 | ||
|
|
97f8663ec6 | ||
|
|
ce68aea668 | ||
|
|
dab71bd637 | ||
|
|
0c043d580e | ||
|
|
0421f95adf | ||
|
|
284a840ebe | ||
|
|
eb8b415635 | ||
|
|
e508c10e9d | ||
|
|
7a4e7c4d0a | ||
|
|
3824a2e03e | ||
|
|
fb5c3a403c | ||
|
|
eb2be0e88d | ||
|
|
621a396def | ||
|
|
2afb1cc349 | ||
|
|
b0dc24031c | ||
|
|
d87cc4e3b6 | ||
|
|
8eb28c2ada | ||
|
|
09eeb004d1 | ||
|
|
632490aa50 | ||
|
|
6c0cfdb610 | ||
|
|
9a98c0060b | ||
|
|
4b9e28a879 | ||
|
|
6383f21dbb | ||
|
|
6080c06bd9 | ||
|
|
ae947139d8 | ||
|
|
e1f1659776 | ||
|
|
02bd688896 | ||
|
|
c6dca80401 | ||
|
|
f03164e7e0 | ||
|
|
0236afb11d | ||
|
|
af932640b8 | ||
|
|
fd22249b65 | ||
|
|
c84c8c32a5 | ||
|
|
a5ad308e4a | ||
|
|
c30e07ee9f | ||
|
|
85cc5d10e6 | ||
|
|
7c23e4377d | ||
|
|
0418f37dbb | ||
|
|
0dc42b6380 | ||
|
|
f4381155bd | ||
|
|
bec6e5f835 | ||
|
|
d9dca5b498 | ||
|
|
469e1692a7 | ||
|
|
44a3eed971 | ||
|
|
77b192eba5 | ||
|
|
49e4e3a133 | ||
|
|
4a0bd76768 | ||
|
|
6de45423d1 | ||
|
|
20f8a43693 | ||
|
|
00d8154ef8 | ||
|
|
12d1cc7308 | ||
|
|
2e1b91b196 | ||
|
|
c11c04b30e | ||
|
|
29a5c7a516 | ||
|
|
00ad6d702f | ||
|
|
9fb0f20dbc | ||
|
|
254b2dce1d | ||
|
|
2ee9f100bf | ||
|
|
d5a50275ea | ||
|
|
b02c79f279 | ||
|
|
4a69d25254 | ||
|
|
7b783cf892 | ||
|
|
455f0cf0e1 | ||
|
|
655d99020a | ||
|
|
4b61bea3fa | ||
|
|
ffad787af9 | ||
|
|
cc3bce2f58 | ||
|
|
33940459f7 | ||
|
|
dc9ff53e78 | ||
|
|
4ad30e5079 | ||
|
|
e94863c79d | ||
|
|
151c314c05 | ||
|
|
8bbc41162b | ||
|
|
58fd0c8d93 | ||
|
|
edaf224417 | ||
|
|
07a55bfc85 | ||
|
|
1bac4b6f8b | ||
|
|
47dabed289 | ||
|
|
a1312941eb | ||
|
|
5b762bab65 | ||
|
|
920292760a | ||
|
|
0afe5737fa | ||
|
|
9a1501af7a | ||
|
|
fb56fde88d | ||
|
|
88d3f7a513 | ||
|
|
1504d95ed3 | ||
|
|
9927c974da | ||
|
|
632f023b8c | ||
|
|
0dd99b7638 | ||
|
|
0433b18aa7 | ||
|
|
b40535b344 | ||
|
|
3986b4ccce | ||
|
|
bc3d777f59 | ||
|
|
6dd3e5af82 | ||
|
|
f7cd0cc378 | ||
|
|
36003250a4 | ||
|
|
47ee59da22 | ||
|
|
eaa044fef7 | ||
|
|
82565e0c98 | ||
|
|
3dac7702ba | ||
|
|
48770e590e | ||
|
|
c1835182ed | ||
|
|
bf9af85830 | ||
|
|
a61169c830 | ||
|
|
1839425da6 | ||
|
|
2aa4292458 | ||
|
|
102913d5bf | ||
|
|
49e4d73de2 | ||
|
|
857de63b48 | ||
|
|
70285c5bc3 | ||
|
|
be0620f2ee | ||
|
|
91ea73bb54 | ||
|
|
7d86ba00bd | ||
|
|
a279231512 | ||
|
|
35951a1420 | ||
|
|
e164432db0 | ||
|
|
51b6602526 | ||
|
|
e93d16fd4b | ||
|
|
b03fa50a1a | ||
|
|
93acb6cb13 | ||
|
|
65dfbd5957 | ||
|
|
5925cecdf5 | ||
|
|
06f06d5cec | ||
|
|
ce97476fa8 | ||
|
|
ac98613882 | ||
|
|
b817217d2e | ||
|
|
8c33d56c58 | ||
|
|
992ad3dff2 | ||
|
|
0819cd4e23 | ||
|
|
fa7ccba296 | ||
|
|
51fbe23431 | ||
|
|
a22d34b423 | ||
|
|
17baf3c6a8 | ||
|
|
cbf061a28d | ||
|
|
9d1635bdc5 | ||
|
|
40dad414f1 | ||
|
|
92184c6834 | ||
|
|
fad3d56cba | ||
|
|
0683e74e45 | ||
|
|
b02cde7ffb | ||
|
|
d4df15396d | ||
|
|
d606c4ee4b | ||
|
|
b7458ba3e0 | ||
|
|
0aed66de2f | ||
|
|
c279fb1632 | ||
|
|
a310439f1f | ||
|
|
9fc1d25b37 | ||
|
|
f6f4377685 | ||
|
|
7c48af1fcf | ||
|
|
4fa406fc45 | ||
|
|
0bacbdf066 | ||
|
|
13766fe836 | ||
|
|
878794f099 | ||
|
|
b29531d643 | ||
|
|
b35a837c50 | ||
|
|
30c0bf4044 | ||
|
|
2c4913a122 | ||
|
|
54dd95b151 | ||
|
|
1d730d1275 | ||
|
|
91c1b3c92f | ||
|
|
de4ed775bd | ||
|
|
9da47ce395 | ||
|
|
27f7deb309 | ||
|
|
460caeccae | ||
|
|
d94b0350de | ||
|
|
ca4c55ac55 | ||
|
|
bb336142f2 | ||
|
|
6288d90719 | ||
|
|
6d9b01a0ce | ||
|
|
c61e4d73a9 | ||
|
|
321809009a | ||
|
|
f8b80c40b5 | ||
|
|
b562cb8078 | ||
|
|
7717bd6f3e | ||
|
|
bf77af0198 | ||
|
|
609c22fe8d | ||
|
|
a1f28bd774 | ||
|
|
7529122385 | ||
|
|
9e9bda4e07 | ||
|
|
c937930b31 | ||
|
|
d187e3683f | ||
|
|
cb3ca7846c | ||
|
|
850b4d63ea | ||
|
|
3b6101ad37 | ||
|
|
f8661f0a8c | ||
|
|
4cc4cc1979 | ||
|
|
822bd50811 | ||
|
|
a76e01fada | ||
|
|
ea8d049d6a | ||
|
|
0f0d4ffcc2 | ||
|
|
47e71541a5 | ||
|
|
a86ac08ca7 | ||
|
|
e151bb8a3e | ||
|
|
aa8dca67c6 | ||
|
|
3c44f046f4 | ||
|
|
2992056827 | ||
|
|
93d243c8e9 | ||
|
|
7f2f42310d | ||
|
|
314b9b6cc9 | ||
|
|
cf8c3f8303 | ||
|
|
6c8c66aec8 | ||
|
|
31969d5e3b | ||
|
|
b6d24ebbbf | ||
|
|
1c4d8859ae | ||
|
|
b09d23c05b | ||
|
|
97bf5ddf94 | ||
|
|
c6c38ab327 | ||
|
|
a00b421298 | ||
|
|
ab5f6a98b0 | ||
|
|
1a46abb6b8 | ||
|
|
e28658a75a | ||
|
|
b7af7a0f02 | ||
|
|
f43f0a60a6 | ||
|
|
720cbf4799 | ||
|
|
ddb7058f2b | ||
|
|
1fae640048 | ||
|
|
080b6ffdaa | ||
|
|
9833d053fa | ||
|
|
84146233e4 |
No files matched your search
@@ -42,7 +42,7 @@ body:
|
||||
id: install_cmd
|
||||
attributes:
|
||||
label: How you installed
|
||||
placeholder: pip install invisible_playwright
|
||||
placeholder: uv add invisible-playwright
|
||||
validations:
|
||||
required: true
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# counters.yml - the daily snapshot of the launch counter, and the README badges.
|
||||
#
|
||||
# GitHub keeps only the running total of a release asset's downloads, so the
|
||||
# launches of a day exist only if someone records the total every day. This is
|
||||
# that someone: no machine and no personal token, just the scheduler and the
|
||||
# built-in GITHUB_TOKEN. A run that fails sends GitHub's failure mail, and the
|
||||
# run's log warns when a day between two snapshots is missing.
|
||||
#
|
||||
# Everything it writes lives on the `badges` branch, which is not protected:
|
||||
# counters/history.csv date,key,value - every counter, once a day
|
||||
# counters/launches_daily.csv day_utc,launches - one row per measured day
|
||||
# docs/badges/launches.svg, docs/badges/stars.svg
|
||||
#
|
||||
# 00:10 UTC, so the snapshot dated D closes calendar day D-1.
|
||||
name: counters
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "10 0 * * *"
|
||||
workflow_dispatch: {}
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
concurrency:
|
||||
group: counters
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
snapshot:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Check out the script (main)
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
path: main
|
||||
|
||||
- name: Check out the badges branch
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: badges
|
||||
path: badges
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Self-test
|
||||
run: python main/scripts/launch_counters.py --selftest
|
||||
|
||||
- name: Record today's counters and redraw the badges
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: >
|
||||
python main/scripts/launch_counters.py
|
||||
--history badges/counters/history.csv
|
||||
--daily badges/counters/launches_daily.csv
|
||||
--badges badges/docs/badges
|
||||
|
||||
- name: Commit to the badges branch
|
||||
working-directory: badges
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git config user.name "feder-cr"
|
||||
git config user.email "85809106+feder-cr@users.noreply.github.com"
|
||||
git add counters docs/badges
|
||||
if git diff --cached --quiet; then
|
||||
echo "nothing changed"
|
||||
exit 0
|
||||
fi
|
||||
total=$(awk -F, '$2=="launches_total"{v=$3} END{print v}' counters/history.csv)
|
||||
git commit -q -m "counters: $(date -u +%F), browser launches at ${total}"
|
||||
git push origin HEAD:badges
|
||||
@@ -50,6 +50,14 @@ concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
# Engine and GeoIP downloads go through the release API with this token.
|
||||
# Anonymous requests share a 60-an-hour limit per runner address and are the
|
||||
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
|
||||
# unauthenticated users failed the gates three times). user-install.yml stays
|
||||
# anonymous on purpose: it is the user's path.
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
hunt:
|
||||
name: hunt (${{ inputs.os }})
|
||||
|
||||
@@ -47,6 +47,14 @@ concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
# Engine and GeoIP downloads go through the release API with this token.
|
||||
# Anonymous requests share a 60-an-hour limit per runner address and are the
|
||||
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
|
||||
# unauthenticated users failed the gates three times). user-install.yml stays
|
||||
# anonymous on purpose: it is the user's path.
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
# The install below resolves `invisible-core==N.M.0` from the package index,
|
||||
# and the core is published BEFORE this package. This gate answers whether it
|
||||
@@ -90,6 +98,16 @@ jobs:
|
||||
sudo "$(which python)" -m playwright install-deps firefox
|
||||
- name: Fetch the published firefox binary
|
||||
run: echo "FF=$(python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
- name: The protocol mirror agrees with the engine it is pinned to
|
||||
# `invisible_core.juggler.protocol` is generated from the Protocol.js INSIDE the
|
||||
# shipped binary, and nothing used to tie the two together after a pin
|
||||
# bump: the mirror sat at 71 commands while the pinned engine declared
|
||||
# 75, with the unit test that fixes the count green the whole time,
|
||||
# because a count checks the mirror against itself. This is the only
|
||||
# job that has the binary, so this is where the comparison belongs.
|
||||
# The generator moved into the core with the module it writes (0.30.0),
|
||||
# so the check runs against the core this package installs.
|
||||
run: python -m invisible_core.juggler._gen_protocol --check --binary "$(dirname "$FF")"
|
||||
- name: Run the full e2e suite under a virtual display
|
||||
# PYTHONUNBUFFERED, and it is not a nicety. Without it Python block-buffers
|
||||
# stdout when it is a pipe, and this step printed NOTHING for 39 minutes
|
||||
|
||||
@@ -28,6 +28,14 @@ on:
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Engine and GeoIP downloads go through the release API with this token.
|
||||
# Anonymous requests share a 60-an-hour limit per runner address and are the
|
||||
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
|
||||
# unauthenticated users failed the gates three times). user-install.yml stays
|
||||
# anonymous on purpose: it is the user's path.
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
# `pip install .` below resolves `invisible-core==N.M.0` from the package
|
||||
# index, and the core is published BEFORE this package. This gate answers
|
||||
|
||||
@@ -30,6 +30,26 @@ on:
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# One publish at a time per repository, whatever started it and on whatever
|
||||
# ref. Two runs of one tag (a delayed delivery, or a dispatch plus the push)
|
||||
# would both pass the already-published check before either had uploaded, and
|
||||
# both would upload. Keyed on the ref, a dispatch on a branch and a push of the
|
||||
# tag would not wait for each other, so the group is the workflow alone.
|
||||
# Serialised, the second run waits for the first and then finds the version on
|
||||
# the index, so it ends as a no-op. Never cancelled in progress: an upload that
|
||||
# has started must be allowed to finish.
|
||||
concurrency:
|
||||
group: publish
|
||||
cancel-in-progress: false
|
||||
|
||||
# Engine and GeoIP downloads go through the release API with this token.
|
||||
# Anonymous requests share a 60-an-hour limit per runner address and are the
|
||||
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
|
||||
# unauthenticated users failed the gates three times). user-install.yml stays
|
||||
# anonymous on purpose: it is the user's path.
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
# Asked of the INDEX, first, because a tag can legitimately name a version that
|
||||
# is already published: a tag backfilled for a hand-published release, a tag
|
||||
@@ -62,6 +82,11 @@ jobs:
|
||||
needs: already-published
|
||||
if: needs.already-published.outputs.present != 'yes'
|
||||
runs-on: ubuntu-latest
|
||||
# `checks: read` for the step below, which asks what the e2e concluded on
|
||||
# this commit. Job level rather than workflow level: no other job needs it.
|
||||
permissions:
|
||||
contents: read
|
||||
checks: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -84,6 +109,29 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: the e2e is GREEN on the commit being tagged
|
||||
# ⛔ THE SUITE BELOW IS THE DEFAULT SELECTION, WHICH DESELECTS `e2e`. So
|
||||
# until this step existed, the job that decides whether a release goes
|
||||
# out had never looked at the suite that drives a browser: a red there
|
||||
# stopped neither a merge nor a tag. 0.22.1 was tagged from a main whose
|
||||
# e2e was red, and nothing said so because nothing was looking.
|
||||
#
|
||||
# It ASKS rather than re-runs. The e2e has already run on this commit;
|
||||
# running it again here would cost five minutes to learn what one API
|
||||
# call answers. What was missing was not a second measurement, it was
|
||||
# somebody reading the first one.
|
||||
#
|
||||
# The selftest runs first, because a gate that has only ever printed
|
||||
# PASS is not a gate - and this one's verdict is a pure function, so its
|
||||
# ten known-bad cases cost nothing and need no network.
|
||||
if: github.event_name == 'push'
|
||||
shell: bash
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
python scripts/e2e_is_green.py --selftest
|
||||
python scripts/e2e_is_green.py --repo "$GITHUB_REPOSITORY" --sha "$GITHUB_SHA"
|
||||
|
||||
- name: the pinned invisible-core is ON THE INDEX
|
||||
# THE ordering rule, as a gate instead of a sentence in a runbook. This
|
||||
# package declares `invisible-core==X.Y.Z`, so pip resolves the PUBLISHED
|
||||
@@ -125,6 +173,19 @@ jobs:
|
||||
python -m pip install --upgrade pip
|
||||
pip install -e ".[dev]"
|
||||
|
||||
- name: version gate
|
||||
# The version and the ledger against what the index serves, as the
|
||||
# pre-push hook checks them: in layers, not as alternatives, because the
|
||||
# hook is per clone and can be missing or skipped, and this cannot
|
||||
# ([B353]). Exit codes: 0 pass, 1 refused, 2 gate broken, 4 no usable
|
||||
# ledger; only 0 continues. The check builds the package to compare
|
||||
# it, without isolation, so the build backend is installed here: the
|
||||
# dev extra carries `build` and not `hatchling`, and without it the
|
||||
# check stopped as "gate broken" on the first tag (v0.40.0).
|
||||
run: |
|
||||
python -m pip install build hatchling
|
||||
python -m invisible_core.release check --verify-index
|
||||
|
||||
- name: arm the pre-push gates
|
||||
# The suite asserts core.hooksPath is set and a fresh checkout has none.
|
||||
run: python scripts/install_hooks.py
|
||||
@@ -213,6 +274,18 @@ jobs:
|
||||
git config user.name "feder-cr"
|
||||
git config user.email "85809106+feder-cr@users.noreply.github.com"
|
||||
git add PUBLISHED.json
|
||||
# `record` also realigns this version's CHANGELOG heading to the upload
|
||||
# date the index reports, and this is the repository that keeps a
|
||||
# changelog, so this is where it matters. A file rewritten on the
|
||||
# runner's disk that nobody stages is a change that never happened, and
|
||||
# the whole point is that the date stops being written by hand: 0.16.2
|
||||
# shipped dated a day ahead because the heading is typed at bump time,
|
||||
# hours before the upload it claims to describe, in whatever timezone
|
||||
# the author is in. Conditional to match the release notes step below,
|
||||
# and because `git add` on a missing path fails under `bash -e`.
|
||||
if [ -f CHANGELOG.md ]; then
|
||||
git add CHANGELOG.md
|
||||
fi
|
||||
git commit -m "record $VERSION as published"
|
||||
BRANCH="${{ github.event.repository.default_branch }}"
|
||||
if git push origin "HEAD:refs/heads/$BRANCH"; then
|
||||
|
||||
@@ -19,6 +19,14 @@ concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
# Engine and GeoIP downloads go through the release API with this token.
|
||||
# Anonymous requests share a 60-an-hour limit per runner address and are the
|
||||
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
|
||||
# unauthenticated users failed the gates three times). user-install.yml stays
|
||||
# anonymous on purpose: it is the user's path.
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
# The gate was written FOR this repository on 2026-08-27, after 549 lines of
|
||||
# Italian shipped here in one subsystem and 852 more were found in 33 files
|
||||
@@ -60,6 +68,83 @@ jobs:
|
||||
python -m invisible_core.english --selftest
|
||||
python -m invisible_core.english
|
||||
|
||||
# A README that promises to beat everything was live here on 2026-09-22 ("it
|
||||
# passes every bot detection test"), and the check that found it ran by hand,
|
||||
# from outside the repository, after the text was public. The logic is
|
||||
# `invisible_core.claims` since core 34.29.0, shared with the MCP server's
|
||||
# repository; what this one reads is declared in `[tool.invisible.claims]`,
|
||||
# and without a declaration it is the README, which is also what PyPI shows.
|
||||
claims:
|
||||
name: the README promises nothing it cannot support
|
||||
needs: core-on-index
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- name: install the pinned core, which carries the gate
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -e .
|
||||
- name: check the claims
|
||||
# --selftest first, for the same reason as the language gate: a check
|
||||
# that has only ever printed "clean" may have gone blind.
|
||||
run: |
|
||||
python -m invisible_core.claims --selftest
|
||||
python -m invisible_core.claims
|
||||
|
||||
# The way in is uv (the owner, 2026-09-06 and "uv everywhere" on 2026-10-17),
|
||||
# and on that day this repository still taught pip in its README, its
|
||||
# CONTRIBUTING, its docs and the messages its code prints, with nothing
|
||||
# comparing any of them with the decision. `invisible_core.way_in` since core
|
||||
# 49.45.0 refuses an install instruction that is not uv, in the tracked
|
||||
# Markdown, the issue templates and the string literals of src/.
|
||||
way-in:
|
||||
name: every install instruction is uv
|
||||
needs: core-on-index
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- name: install the pinned core, which carries the gate
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -e .
|
||||
- name: check the way in
|
||||
# --selftest first: a check that has only ever printed "clean" may
|
||||
# have gone blind.
|
||||
run: |
|
||||
python -m invisible_core.way_in --selftest
|
||||
python -m invisible_core.way_in
|
||||
|
||||
# The user-install job installs what was published, as a user would. It ran
|
||||
# on `release: published`, which never fires: the Release is created with
|
||||
# GITHUB_TOKEN, and an event that token causes starts no other workflow
|
||||
# ([B347], core 50.48.0). `invisible_core.install_job` judges this tree: the
|
||||
# job runs on the ledger pull request, its wait for the index is scoped to it
|
||||
# and bounded, and every test file it runs keeps out, in a `_LEAKS`, every
|
||||
# variable the pinned core's library reads.
|
||||
install-job:
|
||||
name: the user-install job runs on the ledger pull request
|
||||
needs: core-on-index
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- name: install the pinned core, which carries the gate
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -e .
|
||||
- name: check the install job
|
||||
run: |
|
||||
python -m invisible_core.install_job --selftest
|
||||
python -m invisible_core.install_job
|
||||
|
||||
# `pip install -e ".[dev]"` below resolves `invisible-core==N.M.0` from the
|
||||
# package index. The core is published BEFORE this package, so between the
|
||||
# first push of this repo and that upload there is a window in which no
|
||||
@@ -240,7 +325,7 @@ jobs:
|
||||
# exits 1 without saying which of five inputs went red is a gate somebody has
|
||||
# to open five tabs to read.
|
||||
gate:
|
||||
needs: [core-on-index, unit, docs-api, english, version]
|
||||
needs: [core-on-index, unit, docs-api, english, claims, version, way-in, install-job]
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
@@ -250,7 +335,10 @@ jobs:
|
||||
echo "unit: ${{ needs.unit.result }}"
|
||||
echo "docs-api: ${{ needs.docs-api.result }}"
|
||||
echo "english: ${{ needs.english.result }}"
|
||||
echo "claims: ${{ needs.claims.result }}"
|
||||
echo "way-in: ${{ needs.way-in.result }}"
|
||||
echo "version: ${{ needs.version.result }}"
|
||||
echo "install-job: ${{ needs.install-job.result }}"
|
||||
case "${{ needs.unit.result }}" in
|
||||
failure|cancelled) echo "the suite did not pass"; exit 1 ;;
|
||||
esac
|
||||
@@ -263,9 +351,18 @@ jobs:
|
||||
case "${{ needs.english.result }}" in
|
||||
failure|cancelled) echo "the repository is not English"; exit 1 ;;
|
||||
esac
|
||||
case "${{ needs.claims.result }}" in
|
||||
failure|cancelled) echo "the README promises what no measurement supports"; exit 1 ;;
|
||||
esac
|
||||
case "${{ needs.way-in.result }}" in
|
||||
failure|cancelled) echo "an install instruction is not uv"; exit 1 ;;
|
||||
esac
|
||||
case "${{ needs.version.result }}" in
|
||||
failure|cancelled) echo "the version this change proposes is already taken"; exit 1 ;;
|
||||
esac
|
||||
case "${{ needs.install-job.result }}" in
|
||||
failure|cancelled) echo "the user-install job would not run on a release, or leaks"; exit 1 ;;
|
||||
esac
|
||||
echo "ok"
|
||||
|
||||
# Measured 2026-09-04: 0.10.0 was on the index while main sat on 0.10.0 with
|
||||
|
||||
@@ -15,12 +15,16 @@
|
||||
# * installing a blessed `playwright==<pin>` afterwards REPAIRS the venv. If
|
||||
# the declared range resolves to a client the shipped Juggler cannot speak,
|
||||
# that manual line turns the job green while every fresh install is broken.
|
||||
# What a user gets is what pip resolves from the declaration, and that is
|
||||
# what has to be under test.
|
||||
# What a user gets is what the installer resolves from the declaration,
|
||||
# and that is what has to be under test.
|
||||
#
|
||||
# So this workflow installs nothing from the checkout except the test files. It
|
||||
# takes `pip install invisible-playwright` from the index, in an empty venv, and
|
||||
# runs it the way somebody's first script would.
|
||||
# So this workflow installs nothing from the checkout except the test files.
|
||||
# test_release_e2e.py runs the README's install block for the runner's system
|
||||
# as written - uv from its own installer, `uv init`, `uv add
|
||||
# invisible-playwright` from the index, `fetch` - and then drives the browser
|
||||
# from the project it made, the way somebody's first script would.
|
||||
# test_upgrade_e2e.py stays on pip on purpose: it is the path of the people who
|
||||
# installed before the README said uv, and they are still there.
|
||||
#
|
||||
# WHY IT MUST NOT BE MADE TOLERANT.
|
||||
# There is a real window in which this cannot pass: between publishing the core
|
||||
@@ -54,8 +58,16 @@ on:
|
||||
# here, so a run triggered only by pushes would never see them. Weekly is
|
||||
# enough to catch that drift without adding a Windows job to the queue daily.
|
||||
- cron: "17 6 * * 1"
|
||||
release:
|
||||
types: [published]
|
||||
# ⛔ THE LEDGER PULL REQUEST, not `release: published` ([B347], core
|
||||
# 50.48.0). The Release is created by the publish workflow with GITHUB_TOKEN,
|
||||
# and an event that token causes starts no other workflow: on `release:` this
|
||||
# job had never run at release time. The ledger PR exists only after the
|
||||
# upload and `record`, and merging it waits for this run, so a release does
|
||||
# not close before what it published installs. `python -m
|
||||
# invisible_core.install_job` checks the wiring (tests.yml).
|
||||
pull_request:
|
||||
paths:
|
||||
- PUBLISHED.json
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -88,7 +100,8 @@ jobs:
|
||||
run: python -m pip install --upgrade pip pytest packaging
|
||||
|
||||
# PyPI does not serve a new version to pip the instant twine finishes, and
|
||||
# this workflow runs on `release:` - which fires seconds after the upload.
|
||||
# this workflow runs on the ledger pull request, which the publish run
|
||||
# opens seconds after the upload (it ran on `release:`, just as soon).
|
||||
# MEASURED 2026-07-28: invisible-firefox 0.2.6 was uploaded, the release was
|
||||
# created about forty seconds later, and the pip install below still resolved
|
||||
# 0.2.5. The job reported a forgotten publish that had happened two minutes
|
||||
@@ -99,10 +112,11 @@ jobs:
|
||||
# PER-VERSION endpoint is the authority; the aggregate `info.version` lags it
|
||||
# by minutes and has its own trap, so this asks for the exact URL.
|
||||
#
|
||||
# Only on `release:`. A scheduled or dispatched run is not racing anything,
|
||||
# and a wait there would hide a real absence behind five minutes of polling.
|
||||
# Only on the ledger pull request. A scheduled or dispatched run is not
|
||||
# racing anything, and a wait there would hide a real absence behind five
|
||||
# minutes of polling.
|
||||
- name: wait for the index to serve this version
|
||||
if: github.event_name == 'release'
|
||||
if: github.event_name == 'pull_request'
|
||||
shell: bash
|
||||
run: |
|
||||
python - <<'PY'
|
||||
|
||||
@@ -6,9 +6,11 @@ name: webrtc-e2e
|
||||
# carries the WebRTC fixes (synthetic srflx in genuine nICEr form + the
|
||||
# default-route fallback behind a proxy). Run it after publishing such a
|
||||
# binary - it is the release gate for "WebRTC looks real behind a proxy".
|
||||
# Until that binary ships, test_not_blocked_behind_tcp_only_socks is EXPECTED
|
||||
# to fail (the old binary is fully blocked behind a SOCKS proxy), which is the
|
||||
# whole point of the gate.
|
||||
# On this Linux runner an engine older than firefox-35 never gets the synthetic
|
||||
# srflx behind a SOCKS proxy (the wildcard default-route probe, fixed in
|
||||
# firefox-35): test_not_blocked_behind_tcp_only_socks skips on it, naming that
|
||||
# defect, and the floor below turns the skip red. From firefox-35 on, a
|
||||
# missing srflx fails the test itself.
|
||||
#
|
||||
# No external proxy provider, no credentials: the "behind a proxy" condition is faked by an
|
||||
# in-process TCP-only SOCKS5 server (refuses UDP ASSOCIATE) and the egress IP
|
||||
@@ -20,6 +22,14 @@ on:
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Engine and GeoIP downloads go through the release API with this token.
|
||||
# Anonymous requests share a 60-an-hour limit per runner address and are the
|
||||
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
|
||||
# unauthenticated users failed the gates three times). user-install.yml stays
|
||||
# anonymous on purpose: it is the user's path.
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
# `pip install -e ".[dev]"` below resolves `invisible-core==N.M.0` from the
|
||||
# package index, and the core is published BEFORE this package. This gate
|
||||
|
||||
@@ -4,8 +4,7 @@ Thanks for your interest in improving this project. Contributions are welcome vi
|
||||
|
||||
## Quick links
|
||||
|
||||
- **Bug?** Open a [bug report](https://github.com/feder-cr/invisible_playwright/issues/new?template=bug_report.yml).
|
||||
- **Idea?** Open a [feature request](https://github.com/feder-cr/invisible_playwright/issues/new?template=feature_request.yml).
|
||||
- **Bug or idea?** Open an [issue](https://github.com/feder-cr/invisible_playwright/issues/new/choose).
|
||||
- **Security issue?** Do **not** open a public issue - see [SECURITY.md](SECURITY.md).
|
||||
- **The C++ patches** live in the companion repo [feder-cr/firefox_antidetect_patch](https://github.com/feder-cr/firefox_antidetect_patch) (branch `stealth/151`). Bugs in fingerprint spoofing usually belong there.
|
||||
|
||||
@@ -13,11 +12,12 @@ Thanks for your interest in improving this project. Contributions are welcome vi
|
||||
|
||||
This repository ships the **Python wrapper** (`invisible_playwright`) around a pre-built patched Firefox. In scope:
|
||||
|
||||
- The `InvisiblePlaywright` sync/async API and launcher
|
||||
- The fingerprint sampler (`_fpforge`)
|
||||
- Binary download/caching, CLI, proxy plumbing
|
||||
- The `InvisiblePlaywright` sync and async API, and its Playwright compatibility layer
|
||||
- The CLI (`invisible-playwright fetch`, `invisible-playwright version`)
|
||||
- Tests, docs, examples, packaging
|
||||
|
||||
The fingerprint, the engine download and the browser protocol client are shared by every wrapper and live in [invisible_core](https://github.com/feder-cr/invisible_core).
|
||||
|
||||
Out of scope (belongs in `firefox_antidetect_patch`):
|
||||
|
||||
- Changes to the Firefox C++ source
|
||||
@@ -26,19 +26,19 @@ Out of scope (belongs in `firefox_antidetect_patch`):
|
||||
|
||||
## Development setup
|
||||
|
||||
To *use* the package you do not need any of this: `pip install invisible-playwright`.
|
||||
The steps below are for working on the code.
|
||||
To *use* the package you do not need any of this: see [Install](README.md#install) in the README.
|
||||
The steps below are for working on the code, with [uv](https://docs.astral.sh/uv/).
|
||||
|
||||
```bash
|
||||
git clone https://github.com/feder-cr/invisible_playwright.git
|
||||
cd invisible_playwright
|
||||
python -m venv .venv
|
||||
uv venv
|
||||
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
||||
pip install -e ".[dev]"
|
||||
python -m invisible_playwright fetch # download the patched Firefox binary
|
||||
uv pip install -e ".[dev]"
|
||||
invisible-playwright fetch # download the patched Firefox binary
|
||||
```
|
||||
|
||||
Requires Python 3.11+ and one of: Windows x86_64, Linux x86_64.
|
||||
One of: Windows x86_64, Linux x86_64.
|
||||
|
||||
## Running tests
|
||||
|
||||
@@ -72,7 +72,7 @@ Before opening, please:
|
||||
|
||||
Include:
|
||||
|
||||
- OS and version, Python version, `invisible_playwright` version (`invisible_playwright version`)
|
||||
- OS and version, Python version, the output of `invisible-playwright version`
|
||||
- A minimal reproduction
|
||||
- Expected vs actual behavior
|
||||
- Relevant logs / stack traces
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
<div align="center">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/banner-dark.png">
|
||||
<img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/banner-light.png" alt="invisible_playwright" width="720">
|
||||
<source media="(max-width: 374px) and (prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/banner-small-dark.gif">
|
||||
<source media="(max-width: 374px)" srcset="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/banner-small-light.gif">
|
||||
<source media="(max-width: 1239px) and (prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/banner-phone-dark.gif">
|
||||
<source media="(max-width: 1239px)" srcset="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/banner-phone-light.gif">
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/banner-dark.gif">
|
||||
<img alt="invisible_playwright, Playwright on an anti-detect Firefox. An animation: the two-line switch from Playwright, the fingerprint set inside the engine, a mouse that moves like a hand, and the bot tests it passes." src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/banner-light.gif" width="100%">
|
||||
</picture>
|
||||
<h3 align="center">Free antidetect browser stealth for Playwright: undetected Firefox fingerprint, headless or headed.<br>
|
||||
Python web scraping and captcha bypass. Open source, and it passes every bot detection test.</h3>
|
||||
<h3 align="center">Playwright gets caught by anti-bots and captchas.<br>
|
||||
This one runs on an anti-detect Firefox with an undetected fingerprint, compatible with your existing Playwright code.</h3>
|
||||
</div>
|
||||
|
||||

|
||||
@@ -27,20 +31,37 @@ Anti-bots ask two questions, and reCAPTCHA, hCaptcha and Cloudflare Turnstile sc
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright
|
||||
python -m invisible_playwright fetch # one-time download, sha256-verified: 240 MB (Windows) / 262 MB (Linux x86_64) / 253 MB (Linux arm64), about 550 MB unpacked
|
||||
Windows, in PowerShell:
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
|
||||
$env:Path = "$env:USERPROFILE\.local\bin;$env:Path"
|
||||
uv init --python ">=3.11" my-project
|
||||
cd my-project
|
||||
uv add invisible-playwright
|
||||
uv run invisible-playwright fetch # one-time download, sha256-verified: 240 MB, about 550 MB unpacked
|
||||
```
|
||||
|
||||
Requires **Python 3.11 or newer**.
|
||||
Linux:
|
||||
|
||||
Supported platforms: **Windows x86_64**, **Linux x86_64 / arm64**.
|
||||
```bash
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
source $HOME/.local/bin/env
|
||||
uv init --python ">=3.11" my-project
|
||||
cd my-project
|
||||
uv add invisible-playwright
|
||||
uv run invisible-playwright fetch # one-time download, sha256-verified: 262 MB, about 550 MB unpacked
|
||||
```
|
||||
|
||||
Supported platforms: **Windows x86_64**, **Linux x86_64**. Linux arm64 is no longer supported from firefox-56 (firefox-55 is the last engine built for it).
|
||||
|
||||
Then save one of the examples below as `main.py` in `my-project` and run it with `uv run main.py`.
|
||||
|
||||
---
|
||||
|
||||
## Usage
|
||||
### Random fingerprint per session
|
||||
**100% Playwright-compatible** - sync and async, all methods, zero API changes. If you already use Playwright, switching is two lines:
|
||||
**Playwright's API, sync and async, with no code changes.** The same objects, the same calls, the same return values. A few surfaces are out of scope - tracing, HAR, CDP, the API request context - and each one refuses with a sentence saying why rather than misbehaving quietly. If you already use Playwright, switching is two lines:
|
||||
|
||||
```diff
|
||||
- from playwright.sync_api import sync_playwright
|
||||
@@ -301,7 +322,7 @@ This project is for educational purposes only. It is provided as-is, with no war
|
||||
<a href="https://github.com/feder-cr/invisible_playwright/actions/workflows/tests.yml"><img src="https://github.com/feder-cr/invisible_playwright/actions/workflows/tests.yml/badge.svg" alt="tests"></a>
|
||||
<a href="https://github.com/feder-cr/invisible_playwright/blob/main/LICENSE"><img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/badges/license.svg" alt="License: MIT"></a>
|
||||
<a href="https://www.python.org/downloads/"><img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/badges/python.svg" alt="Python 3.11+"></a>
|
||||
<a href="https://github.com/feder-cr/firefox_antidetect_patch/releases"><img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/badges/firefox.svg" alt="Firefox 151.0"></a>
|
||||
<a href="https://github.com/feder-cr/firefox_antidetect_patch/releases"><img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/badges/firefox.svg" alt="Firefox 159.0"></a>
|
||||
<img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/badges/docs/badges/launches.svg" alt="browser launches">
|
||||
<a href="https://github.com/feder-cr/invisible_playwright/stargazers"><img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/badges/docs/badges/stars.svg" alt="GitHub stars"></a>
|
||||
</p>
|
||||
@@ -1,5 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="99" height="20" role="img" aria-label="Firefox: 151.0">
|
||||
<title>Firefox: 151.0</title>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="99" height="20" role="img" aria-label="Firefox: 159.0">
|
||||
<title>Firefox: 159.0</title>
|
||||
<linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient>
|
||||
<clipPath id="r"><rect width="99" height="20" rx="3" fill="#fff"/></clipPath>
|
||||
<g clip-path="url(#r)">
|
||||
@@ -10,7 +10,7 @@
|
||||
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
|
||||
<text x="28.0" y="15" fill="#010101" fill-opacity=".3">Firefox</text>
|
||||
<text x="28.0" y="14">Firefox</text>
|
||||
<text x="77.5" y="15" fill="#010101" fill-opacity=".3">151.0</text>
|
||||
<text x="77.5" y="14">151.0</text>
|
||||
<text x="77.5" y="15" fill="#010101" fill-opacity=".3">159.0</text>
|
||||
<text x="77.5" y="14">159.0</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 855 B After Width: | Height: | Size: 855 B |
|
After Width: | Height: | Size: 2.0 MiB |
|
Before Width: | Height: | Size: 102 KiB After Width: | Height: | Size: 107 KiB |
|
After Width: | Height: | Size: 2.1 MiB |
|
Before Width: | Height: | Size: 103 KiB After Width: | Height: | Size: 107 KiB |
|
After Width: | Height: | Size: 1.8 MiB |
|
After Width: | Height: | Size: 1.9 MiB |
|
After Width: | Height: | Size: 1.9 MiB |
|
After Width: | Height: | Size: 1.9 MiB |
@@ -92,20 +92,21 @@ anyone who needs it.
|
||||
|
||||
The cost is real and you should know it before you enable this anywhere:
|
||||
|
||||
**[`go_back()`](https://playwright.dev/python/docs/api/class-page#page-go-back) waiting
|
||||
for `load` can time out.** A bfcache restore does not fire `load`,
|
||||
because nothing loaded. Code that navigates back and waits for that event will sit there
|
||||
until the timeout expires.
|
||||
**`go_back()` used to time out here, and does not any more.** A bfcache restore does not
|
||||
fire `load`, so code waiting for that event sat there until the deadline. The engine
|
||||
reports the navigation from firefox-31, and the driver stopped caching the injected
|
||||
script across a restore in 0.19.0, which was the second half of the same problem: the
|
||||
page came back and the driver was still holding a handle into the world it had left.
|
||||
|
||||
```python
|
||||
# fragile once bfcache is enabled
|
||||
page.go_back() # may wait for a load that never comes
|
||||
|
||||
# robust either way
|
||||
page.go_back(wait_until="domcontentloaded")
|
||||
# fine now
|
||||
page.go_back()
|
||||
page.wait_for_selector("#something-on-the-previous-page")
|
||||
```
|
||||
|
||||
Waiting for something you can see is still more robust than waiting for a lifecycle
|
||||
event on a restore, because the lifecycle events genuinely do not fire again.
|
||||
|
||||
Waiting for something you can see is more robust than
|
||||
[waiting for a lifecycle event](how-to-wait-for-page-load-playwright.md) anyway, and it
|
||||
works whether or not the page was restored.
|
||||
@@ -151,8 +152,9 @@ in Firefox explicitly and in Chromium effectively.
|
||||
never restore, which is not how consumer browsers behave. It is a weak signal on its own
|
||||
and it belongs to a family of weak behavioural signals.
|
||||
|
||||
**Why does `go_back()` hang after I enable bfcache?** Because a restore does not fire
|
||||
`load`. Wait for `domcontentloaded` or for an element instead.
|
||||
**Does `go_back()` still hang?** No, since firefox-31 for the navigation and 0.19.0 for
|
||||
the driver side. Wait for an element rather than for `load`, which does not fire again
|
||||
on a restore.
|
||||
|
||||
**Should I enable it?** For realistic sessions yes, for deterministic test suites
|
||||
probably not.
|
||||
@@ -174,7 +176,7 @@ for where behavioural signals sit in the wider picture.
|
||||
and [MDN: the `pageshow` event](https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event),
|
||||
which documents `persisted`.
|
||||
- Playwright's documented [`go_back()`](https://playwright.dev/python/docs/api/class-page#page-go-back)
|
||||
and its `wait_until` values, including `domcontentloaded`.
|
||||
and its `wait_until` values.
|
||||
- The Playwright tracker's open items on bfcache behaviour and on enabling it under
|
||||
Chromium.
|
||||
- This project's driver, which reads a preference before disabling the cache and leaves
|
||||
|
||||
@@ -119,7 +119,8 @@ step so the download never lands on a request path:
|
||||
|
||||
```dockerfile
|
||||
FROM python:3.12-slim
|
||||
RUN pip install invisible-playwright
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /bin/
|
||||
RUN uv pip install --system invisible-playwright
|
||||
# Unpack the engine at BUILD time, not per request.
|
||||
RUN python -m invisible_playwright fetch
|
||||
# ... your worker entrypoint ...
|
||||
|
||||
@@ -71,7 +71,8 @@ row is for a specific situation.
|
||||
|
||||
| Variable | When you need it |
|
||||
|---|---|
|
||||
| `INVISIBLE_PLAYWRIGHT_CACHE_DIR` | Put the cached engine somewhere else - another drive, a shared location, a path your CI already caches |
|
||||
| `INVISIBLE_PLAYWRIGHT_CACHE_DIR` | Put the cache somewhere else - another drive, a shared location, a path your CI already caches. It holds the engine and this machine's state (the GeoIP database, the font manifest) |
|
||||
| `INVISIBLE_PLAYWRIGHT_ENGINE_DIR` | Keep the engine apart from the state, for example on a read-only disk built once per release: `invisible-playwright fetch` with it set fills it, and a launch only reads it. The cache directory must still be writable |
|
||||
| `INVPW_BINARY_PATH` | Point at a binary you already have, and skip the download |
|
||||
| `STEALTHFOX_GITHUB_TOKEN` | A rate-limited or corporate network that refuses anonymous GitHub downloads |
|
||||
| `INVISIBLE_PLAYWRIGHT_SKEW=allow` | Run a Playwright version outside the tested range anyway |
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
title: "Differences from Playwright"
|
||||
description: "Where invisible-playwright deliberately behaves differently from upstream Playwright, what it refuses, and why each one is a choice rather than a gap."
|
||||
parent: "Documentation"
|
||||
nav_order: 6
|
||||
---
|
||||
|
||||
|
||||
# Differences from Playwright
|
||||
|
||||
invisible-playwright adds nothing to Playwright's API: every method, option and
|
||||
argument is Playwright's own. Where it cannot do what Playwright does without leaving
|
||||
something a page can see, or without claiming to have done something it did not, it
|
||||
says so with an error instead of pretending. This page lists those places.
|
||||
|
||||
## Objects that are not implemented
|
||||
|
||||
These exist only so the object tree is well formed. Every call on them raises an error
|
||||
that names the reason.
|
||||
|
||||
| Object | Why |
|
||||
|---|---|
|
||||
| `Tracing` | It records a session for the trace viewer and drives none of it. `tracing.stop()` is accepted and does nothing, so code that always stops a trace keeps working. |
|
||||
| `APIRequestContext` (`context.request`, `playwright.request`) | It sends HTTP from outside the page, without the browser's fingerprint, which is the opposite of what this package is for. |
|
||||
|
||||
## Calls that are refused
|
||||
|
||||
| Call | What happens | Why |
|
||||
|---|---|---|
|
||||
| `set_input_files()` with a folder | Error | The engine takes files. Pass the files inside the folder. |
|
||||
| `set_input_files()` with an in-memory payload | Works, but `mimeType` is ignored | The payload is written to a file and handed over the way a user's pick is, so Firefox derives the type from the file name, as it does for a real pick. |
|
||||
| `drop()` with an explicit data payload | Error | The engine builds the `DataTransfer` from a real pointer drag. Use `drag_and_drop()`. |
|
||||
| `route_web_socket()` | Error | The engine reports WebSocket frames but cannot hold or rewrite one, so a route would look like it worked and pass everything through. |
|
||||
| Screencast to a video file | Error | The engine streams JPEG frames and has no encoder. Pass `on_frame=` to receive the frames. |
|
||||
| `register_selector_engine()` or `set_test_id_attribute()` after a page exists | Error | Both are built into the page's injected script when it is created. Call them before the first page. |
|
||||
| `expose_binding()`, `expose_function()` | Error, not implemented yet | The page-facing half is easy; the reply path into the page's promise is not wired, and a binding that never answers would hang the page. |
|
||||
| `set_storage_state()` with per-origin `localStorage` | Error, not implemented yet | Restoring only the cookies would look like success and leave half the session missing. |
|
||||
| `response.body()` on a very large or old response | Error | The engine keeps at most 100 MB of response bodies per tab and 10 MB per response. Read the body sooner. |
|
||||
|
||||
## Behaviour that differs on purpose
|
||||
|
||||
- **`service_workers="block"`** is honoured by the engine itself, per context, with
|
||||
no page script: `register()` fails the way it fails when the worker's script is
|
||||
unreachable, and `navigator.serviceWorker` stays native. Playwright does it with a
|
||||
page script whose source names Playwright. On a persistent profile, turning the
|
||||
block on removes the service workers the profile had saved for that context, and
|
||||
they do not come back when the block is turned off.
|
||||
- **Language.** `locale="auto"` (the default) declares the language of a Firefox
|
||||
build people in the proxy's country actually run. An explicit `locale` is
|
||||
`navigator.language`, followed by the fallbacks Firefox itself adds
|
||||
(`en-AU, en-US, en`).
|
||||
- **Human input.** With `humanize=True` (the default) the pointer moves along a paced
|
||||
path, typing pauses before the first key, and a file chooser waits as a person
|
||||
looking for the file does. Calls take longer than in Playwright, and the page sees a
|
||||
person's timing.
|
||||
- **The server speaks to this client only.** The bundled Playwright client and the
|
||||
bundled server are versioned together; a stock Playwright client cannot drive the
|
||||
server directly.
|
||||
@@ -141,7 +141,7 @@ Playwright method works unchanged because there is no wrapped subset to learn.
|
||||
Install is the ordinary way, and the engine downloads itself on first use:
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright
|
||||
uv add invisible-playwright
|
||||
```
|
||||
|
||||
That is the engine layer, in full, scriptable. What it does not print is a
|
||||
|
||||
@@ -81,6 +81,18 @@ All three are page-visible because they live in the document or the global scope
|
||||
them is the control channel. Fixing them is a matter of not writing them into the page in
|
||||
the first place, which is a design decision, not a runtime patch.
|
||||
|
||||
There is a fourth, and it is the one you control rather than one the browser decides:
|
||||
**an init script of your own that throws reaches the page.** A script added with
|
||||
`page.add_init_script()` runs in the page's own realm, so a callback it registers - an
|
||||
event listener, a timer, a promise - throws into that realm like any other page code.
|
||||
An uncaught one reaches the page's `window.onerror` with `"eval code"` as its source,
|
||||
which is a string a document that never calls `eval` has no other way to produce. The
|
||||
browser's own injection does not do this: measured on a page that installs `onerror`,
|
||||
a capturing `error` listener and `unhandledrejection` before anything else, then reads
|
||||
every surface this package spoofs, nothing surfaces across repeated loads, reloads and
|
||||
an iframe. So keep your own init scripts inside `try { } catch { }`, especially the
|
||||
callbacks they leave behind, and prefer feature checks over assuming a property exists.
|
||||
|
||||
## Chromium injects cdc_ into the document; Firefox through Juggler does not
|
||||
|
||||
Chromium-based tooling writes `cdc_`-prefixed properties into the page; Firefox driven
|
||||
|
||||
@@ -112,7 +112,7 @@ The launch is the same two lines for both agents. The seed makes the identity
|
||||
reproducible, so a failing run can be replayed rather than guessed at.
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright
|
||||
uv add invisible-playwright
|
||||
```
|
||||
|
||||
A DOM-reading agent reads structure and acts on a selector:
|
||||
|
||||
@@ -223,9 +223,9 @@ deploy on. A blank or changing emoji is a failure, not a pass.
|
||||
|
||||
## Sources
|
||||
|
||||
- This project's font architecture and its cross-OS font gate, which runs the
|
||||
browser on a Linux host with no Windows fonts and reads what it renders,
|
||||
including colour emoji (decision log, 2026-06-20).
|
||||
- This project's font architecture and its cross-OS host gate, which runs the
|
||||
browser on a Linux host with no Windows fonts and compares what a page reads,
|
||||
colour emoji included, with the Windows build (decision log, 2026-06-20).
|
||||
- Firefox's use of a bundled colour-emoji font in place of the platform emoji
|
||||
font, verified against a stock build on more than one operating system.
|
||||
- [`HTMLCanvasElement.toDataURL()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL)
|
||||
|
||||
@@ -97,7 +97,7 @@ a Playwright page directly. Because invisible_playwright hands you a genuine
|
||||
Playwright `Page`, the port attaches to it with no adapter:
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright python-ghost-cursor
|
||||
uv add invisible-playwright python-ghost-cursor
|
||||
```
|
||||
|
||||
```python
|
||||
|
||||
@@ -44,7 +44,7 @@ override from the page, because the page is not where the tell originates.
|
||||
- [Execution context was destroyed, and when it means detection](execution-context-destroyed.md) - Usually a race condition, but sometimes a redirect to a challenge; how to tell the two apart.
|
||||
- [Why content_frame() returns None for a cross-origin iframe](cross-origin-iframe-unreachable.md) - One shared cause behind None, throws and timeouts: process isolation, not a permissions bug.
|
||||
|
||||
- [Running Playwright Firefox on ARM64 Linux](playwright-firefox-arm64-linux.md) - What ships per architecture on ARM64 Linux, the emulation trap, and the memory ceiling.
|
||||
- [Running Playwright Firefox on ARM64 Linux](playwright-firefox-arm64-linux.md) - What ships per architecture on ARM64 Linux, the emulation trap, and the memory ceiling (this project no longer ships a Linux arm64 engine from firefox-56).
|
||||
|
||||
## Human-like input and interaction
|
||||
|
||||
|
||||
@@ -113,8 +113,9 @@ time, so point it at a persisted path:
|
||||
|
||||
```dockerfile
|
||||
FROM python:3.12-slim
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /bin/
|
||||
|
||||
RUN pip install invisible-playwright
|
||||
RUN uv pip install --system invisible-playwright
|
||||
|
||||
# keep the cached engine on a mounted volume so it downloads once
|
||||
ENV INVISIBLE_PLAYWRIGHT_CACHE_DIR=/engines
|
||||
|
||||
@@ -70,15 +70,17 @@ what this project does when you ask for `headless=True`.
|
||||
The browser is launched **headed** and the window is hidden, by a different mechanism on
|
||||
each platform:
|
||||
|
||||
- **Windows.** The browser cloaks its own windows through the compositor, so they render
|
||||
on the real GPU and never appear on screen, in the taskbar or in the switcher.
|
||||
- **macOS.** The window is kept fully transparent with occlusion checks pinned, so the
|
||||
system does not stop drawing it.
|
||||
- **Windows.** A fresh desktop object is created for the session and the browser process
|
||||
is created *on* it, so the whole tree - launcher, parent, GPU and content processes -
|
||||
lives on a desktop nobody switches to. It renders on the real GPU and never appears on
|
||||
screen, in the taskbar or in the switcher. The browser binary is not involved in the
|
||||
hiding at all.
|
||||
- **Linux.** A private virtual display is started for the session and the browser is
|
||||
pointed at it, because X11 and Wayland have no per-window equivalent that keeps the
|
||||
GPU rendering.
|
||||
|
||||
The point of all three is the same: stay on the code path a visible browser uses.
|
||||
The point of both is the same: stay on the code path a visible browser uses, and hide
|
||||
the screen rather than the window.
|
||||
|
||||
Being straight about the limits, because they matter:
|
||||
|
||||
@@ -108,27 +110,39 @@ same process level passed throughout, which is exactly why this went unnoticed:
|
||||
thing validating the behaviour and the thing shipping it were not using the same
|
||||
mechanism.
|
||||
|
||||
The fix is a compositor-level cloak, set on the window itself rather than on any
|
||||
thread or process, which is also why it needs to live in the browser binary: only the
|
||||
window's own owning process can set that attribute. Validated
|
||||
afterward against a visible, headful window on the same machine: identical fingerprint
|
||||
surface (no `visibilityState`, focus, canvas or WebGL tell), a real GPU-composited
|
||||
screenshot, and a passing result on a commercial detector that specifically checks for
|
||||
masked headless state. A per-platform automated check now asserts the underlying
|
||||
window attribute directly - the cloak flag on Windows, the transparency and occlusion
|
||||
state on macOS - rather than trusting a screenshot alone.
|
||||
The first fix was a compositor-level cloak, set on the window itself from inside the
|
||||
browser binary, because only the window's own owning process can set that attribute.
|
||||
It worked, and it was validated against a visible, headful window on the same machine:
|
||||
identical fingerprint surface, a real GPU-composited screenshot, a passing result on a
|
||||
commercial detector that specifically checks for masked headless state.
|
||||
|
||||
**The same fix closed a second, unrelated-looking bug for free.** An earlier hiding
|
||||
approach had put the browser's main process on one virtual desktop and left its
|
||||
sandboxed content processes on a different one by default. Ordinary page loads never
|
||||
noticed. A page that triggered a cross-process navigation - handing the active tab from
|
||||
one content process to another mid-session - did notice: the window being reparented
|
||||
expected both processes on the same desktop, found them split across two, and the tab
|
||||
crashed. Because the compositor-level cloak keeps every process on the single real
|
||||
desktop and hides at the window level instead, that split stopped existing as a
|
||||
possibility, and the crash went away as a side effect of fixing something else
|
||||
entirely. It's a reminder that "which mechanism hides the window" and "which processes
|
||||
can actually talk to each other" are not as separate as they look.
|
||||
It was replaced anyway, for a reason that has nothing to do with whether it worked: it
|
||||
was a patch inside the browser on a surface that has nothing to do with fingerprinting,
|
||||
and the fewer of those a modified browser carries, the less there is to diverge from
|
||||
the original. The current mechanism puts the hiding back where the operating system
|
||||
already offers it. A desktop object is created per session and the browser *process*
|
||||
is created on it - the process, not the thread, which is exactly the scope the latent
|
||||
bug above had got wrong. Every child inherits it. Nothing in the browser knows it is
|
||||
hidden, because from where it stands it is not: it has a desktop, a compositor and a
|
||||
GPU like any other window. Validated the same way, same seed hidden against headed:
|
||||
focus, visibility, inner and outer size, screen position, screen geometry, pixel ratio
|
||||
and the WebGL renderer string all identical, one window on the session's desktop and
|
||||
none on the interactive one.
|
||||
|
||||
**Two things a separate desktop changes, and why they are handled rather than hoped
|
||||
away.** A browser's process sandbox assumes its parent lives on the interactive
|
||||
desktop. Its GPU process cannot parent the compositor window across desktops under the
|
||||
default sandbox level, and its content processes above a certain level are placed on
|
||||
the sandbox's own window station. Left alone, the first means a software renderer under
|
||||
a hardware renderer string, and the second means a tab that dies on the first
|
||||
cross-process navigation - handing the active tab from one content process to another
|
||||
mid-session - because the window being reparented expects both processes on the same
|
||||
desktop and finds them split across two. Both were measured, and both are closed by
|
||||
two sandbox settings the session applies only when it actually created a desktop:
|
||||
never from the platform name, always from the fact. An automated check asserts the
|
||||
result directly - a headed window found on the interactive desktop as the control, then
|
||||
a hidden one absent from it and present on its own, still rendering - rather than
|
||||
trusting a screenshot alone.
|
||||
|
||||
## How to find out which one is your problem
|
||||
|
||||
|
||||
@@ -116,7 +116,7 @@ Switching from stock Playwright is the launch line; every method after it is sta
|
||||
Playwright. Install it first:
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright
|
||||
uv add invisible-playwright
|
||||
```
|
||||
|
||||
Then gather ICE candidates through the proxy and assert the positive form. The `seed`
|
||||
|
||||
@@ -95,7 +95,7 @@ Strip everything that is not part of the number, then parse the digits and separ
|
||||
with the page's locale rather than guessing. Babel does the locale-aware step:
|
||||
|
||||
```bash
|
||||
pip install babel
|
||||
uv add babel
|
||||
```
|
||||
|
||||
```python
|
||||
@@ -127,7 +127,7 @@ Relative and localized dates need the page's language to read the words and the
|
||||
timezone to anchor the arithmetic. `dateparser` takes both:
|
||||
|
||||
```bash
|
||||
pip install dateparser
|
||||
uv add dateparser
|
||||
```
|
||||
|
||||
```python
|
||||
|
||||
@@ -93,7 +93,7 @@ the main content block and discard the rest. The `readability-lxml` package is
|
||||
a direct port of the well-known algorithm and takes an HTML string:
|
||||
|
||||
```bash
|
||||
pip install readability-lxml lxml
|
||||
uv add readability-lxml lxml
|
||||
```
|
||||
|
||||
```python
|
||||
|
||||
@@ -69,11 +69,12 @@ Chromium-specific plumbing you have to translate.
|
||||
|
||||
```dockerfile
|
||||
FROM python:3.11-slim
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /bin/
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
RUN uv pip install --system --no-cache -r requirements.txt
|
||||
|
||||
# Bake the patched engine into the image at build time, not at container
|
||||
# start. This is a one-time ~238 MB download (~544 MB unpacked), sha256-verified
|
||||
@@ -92,7 +93,7 @@ invisible-playwright
|
||||
|
||||
That builds and runs. It also, by itself, still describes a machine with no GPU, a
|
||||
tiny font set and no audio device, for the reason above: none of those come from
|
||||
`pip install`, they come from the base image. The next two sections are what actually
|
||||
the package install, they come from the base image. The next two sections are what actually
|
||||
changes that.
|
||||
|
||||
## The part a Dockerfile cannot fix by itself
|
||||
|
||||
@@ -55,15 +55,15 @@ with InvisiblePlaywright(seed=42, headless=True) as browser:
|
||||
`browser` here is a real Playwright `Browser`, so every standard method works exactly
|
||||
as documented upstream. What is different is what `headless=True` means underneath:
|
||||
this engine renders on the code path a visible window uses, and hides the window
|
||||
itself rather than switching to a stripped rendering mode. On Windows that is a
|
||||
compositor-level cloak on the window; on Linux it is a private virtual display; on
|
||||
macOS the window stays transparent with occlusion checks pinned. The point of all
|
||||
three is the same, and it is worth being specific about it because the same product
|
||||
did not always get this right: for several releases, `headless=True` on Windows
|
||||
rendered the browser on the real desktop anyway, because the hiding mechanism moved
|
||||
the launching *thread* to an invisible desktop while the browser's own child
|
||||
processes inherited the *parent process's* desktop instead, and stayed visible
|
||||
regardless. The fix had to move to the window itself, in the browser binary, because
|
||||
itself rather than switching to a stripped rendering mode. On Windows the browser
|
||||
process is created on a fresh desktop object nobody switches to; on Linux it is a
|
||||
private virtual display. The point of both is the same, and it is worth being specific
|
||||
about it because the same product did not always get this right: for several releases,
|
||||
`headless=True` on Windows rendered the browser on the real desktop anyway, because
|
||||
the hiding mechanism moved the launching *thread* to an invisible desktop while the
|
||||
browser's own child processes inherited the *parent process's* desktop instead, and
|
||||
stayed visible regardless. The fix is to name the desktop when the process is created,
|
||||
so the whole tree is born there - the browser binary is not involved, because
|
||||
only the window's own owning process can set that attribute. See
|
||||
[headless vs headful](headless-vs-headful.md) for the full account and why it stayed
|
||||
unnoticed for as long as it did.
|
||||
|
||||
@@ -51,7 +51,7 @@ The launch is stock Playwright. If you have driven Playwright before, the only c
|
||||
the two lines that open the browser:
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright
|
||||
uv add invisible-playwright
|
||||
```
|
||||
|
||||
```python
|
||||
|
||||
@@ -53,7 +53,7 @@ already in it. Wrap that string in `io.StringIO` (pandas asks for a file-like ob
|
||||
literal HTML) and pass it in.
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright pandas lxml
|
||||
uv add invisible-playwright pandas lxml
|
||||
```
|
||||
|
||||
```python
|
||||
|
||||
@@ -259,7 +259,7 @@ port and that you confirm the exit inside the browser rather than assuming it. A
|
||||
minimal install for the container it runs in:
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright
|
||||
uv add invisible-playwright
|
||||
```
|
||||
|
||||
The engine downloads and caches itself on first use, so the first run in a fresh
|
||||
|
||||
@@ -165,7 +165,8 @@ scheduler calls it. A minimal container runs the job and exits:
|
||||
|
||||
```dockerfile
|
||||
FROM python:3.12-slim
|
||||
RUN pip install invisible-playwright
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /bin/
|
||||
RUN uv pip install --system invisible-playwright
|
||||
COPY monitor.py .
|
||||
CMD ["python", "monitor.py"]
|
||||
```
|
||||
|
||||
@@ -10,8 +10,8 @@ nav_order: 7
|
||||
# How to use invisible_playwright in Docker
|
||||
|
||||
To run `invisible_playwright` in Docker, start from a maintained Playwright
|
||||
base image for the OS-level shared libraries, `pip install
|
||||
invisible-playwright`, fetch the patched Firefox engine at build time, and
|
||||
base image for the OS-level shared libraries, install
|
||||
`invisible-playwright` with uv, fetch the patched Firefox engine at build time, and
|
||||
run the container with `--shm-size=1gb`. The fingerprint itself needs
|
||||
nothing container-specific: the same seed produces the same machine on a
|
||||
desktop or inside a container.
|
||||
@@ -39,6 +39,7 @@ packages that may not match your distro:
|
||||
|
||||
```dockerfile
|
||||
FROM mcr.microsoft.com/playwright/python:v1.47.0-jammy
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /bin/
|
||||
|
||||
WORKDIR /app
|
||||
```
|
||||
@@ -50,17 +51,21 @@ libraries, not the browsers it ships alongside them.
|
||||
|
||||
## Installing invisible-playwright
|
||||
|
||||
Installing `invisible-playwright` in a container is the same two-step
|
||||
install as on a desktop: `pip install invisible-playwright` for the
|
||||
package, then a separate `fetch` step to download the patched engine. See
|
||||
[installation](installation.md) for why the two steps are kept separate:
|
||||
Installing `invisible-playwright` in a container takes the same two steps
|
||||
as on a desktop: install the package with uv, then a separate `fetch` step
|
||||
to download the patched engine. See [installation](installation.md) for why
|
||||
the two steps are kept separate:
|
||||
|
||||
```dockerfile
|
||||
RUN pip install --no-cache-dir invisible-playwright
|
||||
RUN uv venv --python ">=3.11" /opt/venv
|
||||
ENV VIRTUAL_ENV=/opt/venv PATH="/opt/venv/bin:$PATH"
|
||||
RUN uv pip install --no-cache invisible-playwright
|
||||
```
|
||||
|
||||
Nothing container-specific here yet. The wheel is small; the part that
|
||||
needs a build-time decision is the next step.
|
||||
The venv is not decoration: the Python in this base image is 3.10, older
|
||||
than the 3.11 the package needs, so uv brings an interpreter that can run it.
|
||||
The wheel is small; the part that needs a build-time decision is the next
|
||||
step.
|
||||
|
||||
## Fetching the patched engine at build time
|
||||
|
||||
|
||||
@@ -93,7 +93,7 @@ a browser and read back what the server saw. A public HTTP/2 fingerprint endpoin
|
||||
the frames it received as JSON.
|
||||
|
||||
```bash
|
||||
pip install "httpx[http2]"
|
||||
uv add "httpx[http2]"
|
||||
```
|
||||
|
||||
```python
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: "Installation"
|
||||
description: "Install the wrapper from PyPI, then fetch the patched Firefox binary separately - a one-time, sha256-verified download. Supported on Windows, Linux and macOS."
|
||||
description: "Install the wrapper with uv, then fetch the patched Firefox binary separately - a one-time, sha256-verified download. Supported on Windows and Linux."
|
||||
parent: "Documentation"
|
||||
nav_order: 1
|
||||
---
|
||||
@@ -8,31 +8,28 @@ nav_order: 1
|
||||
|
||||
# Installation
|
||||
|
||||
Install invisible-playwright in two steps: `pip install invisible-playwright` for
|
||||
the Python wrapper, then `python -m invisible_playwright fetch` to download the
|
||||
Install invisible-playwright in two steps: `uv add invisible-playwright` for
|
||||
the Python wrapper, then `uv run invisible-playwright fetch` to download the
|
||||
patched Firefox binary it drives. The steps are separate on purpose - the Python
|
||||
package is small, the browser is not.
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright
|
||||
python -m invisible_playwright fetch # one-time ~238 MB download (~544 MB unpacked), sha256-verified
|
||||
uv add invisible-playwright
|
||||
uv run invisible-playwright fetch # one-time ~238 MB download (~544 MB unpacked), sha256-verified
|
||||
```
|
||||
|
||||
`pip install` gets you the wrapper and its API. `fetch` downloads the patched Firefox
|
||||
If you do not have a uv project yet, [the README's install steps](https://github.com/feder-cr/invisible_playwright#install) create one.
|
||||
|
||||
`uv add` gets you the wrapper and its API. `fetch` downloads the patched Firefox
|
||||
binary itself, verifies it against a sha256 shipped inside `invisible-core`, and caches
|
||||
it. You only pay that cost once per engine version - later runs use the cached copy
|
||||
without a network call.
|
||||
|
||||
## Supported platforms
|
||||
|
||||
**Windows x86_64**, **Linux x86_64 / arm64**, **macOS arm64 / x86_64**.
|
||||
|
||||
On macOS the app is ad-hoc signed, not notarized. If Gatekeeper complains the first
|
||||
time it runs, clear the quarantine flag once:
|
||||
|
||||
```bash
|
||||
xattr -dr com.apple.quarantine /path/to/cached/Firefox.app
|
||||
```
|
||||
**Windows x86_64**, **Linux x86_64**. There is no macOS engine: its
|
||||
build ended on 2026-08-26. Linux arm64 is no longer supported from firefox-56:
|
||||
firefox-55 is the last engine built for it.
|
||||
|
||||
`invisible-playwright version` prints the cache location, and
|
||||
`invisible-playwright fetch` prints the exact binary path as its last line.
|
||||
@@ -66,7 +63,7 @@ the [CLI reference](cli-reference.md).
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Do I need to install Firefox myself?** No. `python -m invisible_playwright fetch`
|
||||
**Do I need to install Firefox myself?** No. `uv run invisible-playwright fetch`
|
||||
downloads the patched binary for you, verifies it, and caches it - there is nothing
|
||||
to install separately.
|
||||
|
||||
@@ -83,9 +80,7 @@ Point `INVPW_BINARY_PATH` at a binary you already have to skip the download
|
||||
entirely. [Configuration](configuration.md) lists the other environment variables,
|
||||
including the ones for corporate networks and CI.
|
||||
|
||||
**Which platforms are supported?** Windows x86_64, Linux x86_64/arm64, and macOS
|
||||
arm64/x86_64. macOS needs the quarantine flag cleared once if Gatekeeper complains
|
||||
on first launch.
|
||||
**Which platforms are supported?** Windows x86_64 and Linux x86_64. Linux arm64 is no longer supported from firefox-56.
|
||||
|
||||
**See also:** [Configuration](configuration.md) for proxy, timezone and environment
|
||||
variables, [CLI reference](cli-reference.md) for what `fetch` and `version` do in
|
||||
|
||||
@@ -25,11 +25,13 @@ The engine and the identity come from the Python package even though the tests a
|
||||
JavaScript. Get them once:
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright
|
||||
invisible-playwright fetch # downloads it if missing, prints the binary path as its last line
|
||||
python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
|
||||
uv add invisible-playwright
|
||||
uv run invisible-playwright fetch # downloads it if missing, prints the binary path as its last line
|
||||
uv run python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
|
||||
```
|
||||
|
||||
Run them in a uv project; [the README's install steps](https://github.com/feder-cr/invisible_playwright#install) create one.
|
||||
|
||||
Regenerate `prefs.json` when you upgrade the package: the pref set moves with the
|
||||
engine. Keep the seed written down next to it, because that number is the identity.
|
||||
|
||||
|
||||
@@ -27,11 +27,13 @@ The engine and the identity are produced by the Python package even though the
|
||||
crawler is Node. Get them once, at install or deploy time:
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright
|
||||
invisible-playwright fetch > .browser-path
|
||||
python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
|
||||
uv add invisible-playwright
|
||||
uv run invisible-playwright fetch > .browser-path
|
||||
uv run python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
|
||||
```
|
||||
|
||||
Run them in a uv project; [the README's install steps](https://github.com/feder-cr/invisible_playwright#install) create one.
|
||||
|
||||
Yes, a Python dependency in a Node project. That is the real cost of this route,
|
||||
and if it is unacceptable, the answer is a Chromium-based tool rather than a
|
||||
workaround.
|
||||
|
||||
@@ -20,7 +20,7 @@ check the signature before blaming the engine.
|
||||
## What you need
|
||||
|
||||
```bash
|
||||
pip install crawlee[playwright] invisible-playwright
|
||||
uv add crawlee[playwright] invisible-playwright
|
||||
```
|
||||
|
||||
The patched Firefox binary is downloaded on first launch and cached, so the first
|
||||
|
||||
@@ -29,11 +29,13 @@ Verified 2026-07-27 by reading each binding's own launch options.
|
||||
|
||||
## Step one: get the two values
|
||||
|
||||
Run the commands below in a uv project; [the README's install steps](https://github.com/feder-cr/invisible_playwright#install) create one.
|
||||
|
||||
The binary has a CLI:
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright
|
||||
invisible-playwright fetch # downloads and caches it once, prints the absolute path
|
||||
uv add invisible-playwright
|
||||
uv run invisible-playwright fetch # downloads and caches it once, prints the absolute path
|
||||
```
|
||||
|
||||
The preferences do not, and that is a real gap instead of an omission from this
|
||||
@@ -41,7 +43,7 @@ page: there is no `prefs` subcommand today, so you generate them with a one-line
|
||||
and keep the JSON.
|
||||
|
||||
```bash
|
||||
python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
|
||||
uv run python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
|
||||
```
|
||||
|
||||
Regenerate it when you upgrade the package, since the pref set moves with the engine.
|
||||
|
||||
@@ -32,10 +32,12 @@ Written against `microsoft/playwright-mcp` as of 2026-07-27.
|
||||
## The short version
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright
|
||||
python -c "from invisible_playwright import ensure_binary; print(ensure_binary())"
|
||||
uv add invisible-playwright
|
||||
uv run python -c "from invisible_playwright import ensure_binary; print(ensure_binary())"
|
||||
```
|
||||
|
||||
Run them in a uv project; [the README's install steps](https://github.com/feder-cr/invisible_playwright#install) create one.
|
||||
|
||||
The second command downloads the patched Firefox on first run, caches it, and prints
|
||||
the path. Give that path to the MCP server:
|
||||
|
||||
|
||||
@@ -31,10 +31,10 @@ The engine and the identity come from the Python package, which suits Robot Fram
|
||||
since it is Python underneath anyway.
|
||||
|
||||
```bash
|
||||
pip install robotframework-browser invisible-playwright
|
||||
rfbrowser init
|
||||
invisible-playwright fetch # downloads if needed, prints the path as its last line
|
||||
python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
|
||||
uv add robotframework-browser invisible-playwright
|
||||
uv run rfbrowser init
|
||||
uv run invisible-playwright fetch # downloads if needed, prints the path as its last line
|
||||
uv run python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
|
||||
```
|
||||
|
||||
Regenerate `prefs.json` when you upgrade the package. Keep the seed written next to
|
||||
|
||||
@@ -22,7 +22,7 @@ is the reference; this one explains which route to pick and what each one costs.
|
||||
## Install
|
||||
|
||||
```bash
|
||||
pip install "scrapy-playwright>=0.0.48" invisible-playwright
|
||||
uv add "scrapy-playwright>=0.0.48" invisible-playwright
|
||||
```
|
||||
|
||||
The patched Firefox is downloaded on first launch and cached. You do not need
|
||||
|
||||
@@ -26,11 +26,13 @@ build's own defaults on every launch, which is a different product from
|
||||
Get the two values first, the same way for all four:
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright
|
||||
invisible-playwright fetch
|
||||
python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
|
||||
uv add invisible-playwright
|
||||
uv run invisible-playwright fetch
|
||||
uv run python -c "import json;from invisible_playwright import get_default_stealth_prefs;print(json.dumps(get_default_stealth_prefs(seed=1, humanize=True)))" > prefs.json
|
||||
```
|
||||
|
||||
Run them in a uv project; [the README's install steps](https://github.com/feder-cr/invisible_playwright#install) create one.
|
||||
|
||||
## Cypress
|
||||
|
||||
Cypress launches Firefox through geckodriver and builds a `moz:firefoxOptions` with
|
||||
|
||||
@@ -132,7 +132,7 @@ Do not assume, read it. The launch is a two-line change from stock Playwright, a
|
||||
every method after it is standard Playwright. Install it first:
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright
|
||||
uv add invisible-playwright
|
||||
```
|
||||
|
||||
Then ask an IP-echo endpoint, from inside the proxied browser, which address it saw,
|
||||
|
||||
@@ -42,7 +42,7 @@ I/O-bound, so this rarely matters in practice, but it is not universally true.
|
||||
|
||||
**Distribution to non-technical end users.** A Python automation script needs
|
||||
a Python environment, or a packaging step (PyInstaller and similar), to reach
|
||||
someone who is not going to run `pip install`. If the deliverable is a
|
||||
someone who is not going to run a package installer. If the deliverable is a
|
||||
double-clickable app for someone else's machine, this is real friction that a
|
||||
compiled or web-based alternative does not have.
|
||||
|
||||
|
||||
@@ -18,7 +18,8 @@ types at a fixed interval has a single spike. The spike is the signal.
|
||||
|
||||
This page is about the behavioural layer, not the fingerprint one. It answers the
|
||||
question honestly: a real browser emitting real key events gets you past every check
|
||||
that reads the *events*, and none of the checks that read the *rhythm*. The rhythm is
|
||||
that reads the *events*, and a real event says nothing about the *rhythm*. Inside one
|
||||
typing call the package keeps a rhythm of its own; between your calls the rhythm is
|
||||
code you write, and this page is about writing it well.
|
||||
|
||||
## Yes, and it is a different question from your fingerprint
|
||||
@@ -38,9 +39,12 @@ because the engine does not decide when your loop calls the next keypress. You d
|
||||
|
||||
invisible_playwright is built to answer the first question the way a real browser does.
|
||||
It drives a genuine Firefox, patched at the C++ level, so the key events are real,
|
||||
OS-level, trusted events rather than synthesized DOM dispatches. It does nothing about
|
||||
the second question, and it cannot, which is the honest and slightly annoying core of
|
||||
this whole topic.
|
||||
OS-level, trusted events rather than synthesized DOM dispatches. It answers part of the
|
||||
second question too: with `humanize` on, which is the default, `fill()`, `type()` and
|
||||
`press_sequentially()` hold each key and wait between keys on a rhythm drawn from the
|
||||
session's seed, and pause before the first key of a field. What it cannot pace is your
|
||||
loop, the time between one call and the next, and that is the honest and slightly
|
||||
annoying core of this whole topic.
|
||||
|
||||
## What a keystroke detector actually measures
|
||||
|
||||
@@ -150,10 +154,16 @@ stops to think, which a flat jitter never does. If you want dwell variance too,
|
||||
some keys fractionally longer by pressing `down` and `up` separately with a short sleep
|
||||
between them, rather than the atomic `press`.
|
||||
|
||||
The seed still does its job here. `seed=42` fixes the fingerprint so the *machine* is
|
||||
reproducible; the typing rhythm is deliberately not seeded, because the point of a
|
||||
rhythm is that it differs every time. If you need a failing run to be reproducible while
|
||||
you debug, seed the `random` module too, and unseed it in production.
|
||||
The seed does two jobs here. `seed=42` fixes the fingerprint, so the *machine* is
|
||||
reproducible, and it fixes the package's own typist: how long each key is held, the gaps
|
||||
inside a `type()` call made without a `delay`, and the pause before a field's first key
|
||||
are all drawn from it. Measured on one machine, two sessions with seed 42 typing the same
|
||||
text opened with gaps of 221, 111, 105, 162, 76 and 303 ms and of 209, 103, 99, 163, 77
|
||||
and 303 ms, the same draw under a few milliseconds of latency, while seed 43 opened with
|
||||
104, 89, 160, 59, 142 and 456. Inside one session nothing repeats: each field, each call
|
||||
and each tab gets its own draw. The `random` calls in `human_type` above are yours, and
|
||||
nothing seeds them. If you need a failing run of that loop to be reproducible while you
|
||||
debug, seed the `random` module too, and unseed it in production.
|
||||
|
||||
## What invisible_playwright fixes here, and what it does not
|
||||
|
||||
@@ -167,9 +177,10 @@ from a physical keyboard. The fingerprint, the TLS handshake and the driver laye
|
||||
read as a genuine Firefox, which is *why* the browser passes most detection: it is not
|
||||
pretending to be real, it is real. That is the whole design.
|
||||
|
||||
What it does not fix, and cannot: the cadence. The browser cannot make your loop pause
|
||||
like a person, because your loop is upstream of the browser. If you script a uniform
|
||||
`delay`, you ship a uniform histogram, and a genuine browser emitting it does not make
|
||||
What it does not fix, and cannot: the cadence of your loop. The package paces the keys
|
||||
inside one typing call; it cannot make the time between your calls look like a person,
|
||||
because your loop is upstream of the browser. If you script a uniform sleep between
|
||||
presses, you ship a uniform histogram, and a genuine browser emitting it does not make
|
||||
it look human. The same honesty applies to everything outside the browser process. A
|
||||
real browser does not clean up a datacenter IP, reset a per-account quota, respect a
|
||||
rate limit, or slow down a session that clicks faster than a person reads. Those are
|
||||
@@ -202,8 +213,8 @@ identical gaps, which is the single strongest bot signal there is. Real events,
|
||||
rhythm.
|
||||
|
||||
**Is the problem that the events are fake?** Not with invisible_playwright. The events
|
||||
are real, trusted, OS-level key events. The problem is purely the timing, which you
|
||||
control.
|
||||
are real, trusted, OS-level key events. The problem is the timing: inside one typing
|
||||
call the package draws it from the session's seed, and between your calls it is yours.
|
||||
|
||||
**What distribution should I use for the gaps?** A right-skewed one, centred around
|
||||
100 to 130 ms with a long tail, plus an occasional longer stall. Not a flat uniform
|
||||
|
||||
@@ -129,16 +129,14 @@ enough that there is no reason to open that window.
|
||||
|
||||
## What happens when the lookup fails
|
||||
|
||||
When resolution fails, the fallback depends on whether a proxy is in play, and the two
|
||||
cases have opposite risks. Behind a proxy the wrapper fails early at launch rather than
|
||||
ship a mismatch; without a proxy it falls back to the host timezone and the session
|
||||
continues. The interesting part of any resolution step is what it does when it cannot
|
||||
resolve, so both cases are set out below.
|
||||
When resolution fails, the launch fails, with a proxy or without one. The interesting part
|
||||
of any resolution step is what it does when it cannot resolve, so both cases are set out
|
||||
below.
|
||||
|
||||
| Situation | On a failed resolution | Why |
|
||||
|---|---|---|
|
||||
| Proxy set | Fails early at launch | A foreign exit paired with the host timezone is a mismatch worth stopping for |
|
||||
| No proxy | Falls back to the host timezone, continues | The host address is what the session presents, so the host timezone is correct |
|
||||
| No proxy | Fails early at launch | The host's timezone can disagree with the host's own address, which is why it is resolved at all |
|
||||
|
||||
**With a proxy**, a failed resolution fails early. The reason is precise: if resolution
|
||||
fell back to the host's own timezone while the traffic exits through a foreign proxy, the
|
||||
@@ -147,14 +145,16 @@ to prevent, and it would do so silently. A foreign exit paired with the host tim
|
||||
`timezone_mismatch` waiting to be scored, so the wrapper refuses rather than ship it. You
|
||||
find out at launch, not from a block three requests later.
|
||||
|
||||
**Without a proxy**, there is no exit to disagree with. The session presents the host's own
|
||||
address, so the host's own timezone is the correct answer, and a transient failure to read
|
||||
it should never take the launch down. In that case resolution falls back to the host
|
||||
timezone and the session proceeds.
|
||||
**Without a proxy**, the session presents the host's own address, and the timezone is still
|
||||
resolved from that address rather than read from the host. The reason is the case this
|
||||
section used to wave through: a server kept in UTC whose public address is in another
|
||||
country. Until invisible-core 47.41.0 a failed resolution here fell back to the host
|
||||
timezone and the session went on, which handed exactly that server a timezone contradicting
|
||||
its own IP, with nothing said. Now it fails at launch and names the cause. To launch with
|
||||
no network at all, pass an explicit IANA zone, which asks the network nothing.
|
||||
|
||||
So the fallback is not a single policy applied everywhere. It is chosen so that the only
|
||||
time resolution is allowed to fail loudly is the only time a quiet fallback would have been
|
||||
a fingerprint bug. This matters most when you
|
||||
So the rule is a single one: a resolution that cannot be honoured is an error, never a
|
||||
quiet guess. This matters most when you
|
||||
[rotate proxies across sessions](how-to-rotate-proxies-playwright.md) or run
|
||||
[a different exit per browser context](playwright-proxy-per-context.md), because each new
|
||||
exit is a fresh resolution, and each one either agrees with its browser or refuses to start.
|
||||
@@ -220,9 +220,10 @@ explicit IANA identifier only when you want to override that.
|
||||
once, over the proxy, and maps it against a local database. There is no per-launch call to a
|
||||
geolocation service.
|
||||
|
||||
**Will my session break if the timezone lookup fails?** Behind a proxy it fails early, on
|
||||
purpose, because a foreign exit with the host timezone is a mismatch worth stopping for.
|
||||
Without a proxy it falls back to the host timezone and the session continues.
|
||||
**Will my session break if the timezone lookup fails?** Yes, on purpose, with a proxy or
|
||||
without one: a timezone that contradicts the exit is a mismatch worth stopping for, and the
|
||||
host's own timezone can contradict the host's own address. Pass an explicit IANA zone to
|
||||
launch without the lookup.
|
||||
|
||||
**How does the offline database stay current?** Each launch makes one cheap, unmetered check
|
||||
against a permalink to the newest build and downloads only when the cache is behind. There is
|
||||
|
||||
@@ -18,7 +18,7 @@ from invisible_playwright import InvisiblePlaywright
|
||||
with InvisiblePlaywright(
|
||||
seed=42,
|
||||
pin={
|
||||
"gpu.renderer": "ANGLE (NVIDIA, NVIDIA GeForce RTX 4090 Direct3D11)",
|
||||
"gpu.renderer": "ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0, D3D11)",
|
||||
"gpu.vendor": "Google Inc. (NVIDIA)",
|
||||
"screen.width": 2560,
|
||||
"screen.height": 1440,
|
||||
@@ -39,7 +39,7 @@ When you pin a field:
|
||||
1. The pinned value is written directly, bypassing the sampler.
|
||||
2. **Unpinned children are still sampled from their conditionals** - using the parent's original posterior, not the pinned value.
|
||||
|
||||
That last point is the subtle one: pinning breaks the conditional chain. If you pin `gpu.renderer` to an RTX 4090 string but leave `screen` unpinned, the sampler will pick `screen` from the seed-derived tier (which might be `low_end`), producing a physically implausible "RTX 4090 + 1366x768" pairing.
|
||||
That last point is the subtle one, and `gpu.*` is the exception to it: a GPU pin selects a whole persona, so the class of the persona you picked conditions the screen, concurrency and storage still being drawn (see the `gpu.*` section below). Where an implausible pairing can still be built is by pinning both halves, because a value you write explicitly is never re-drawn: put a `low_end` persona next to `screen.width: 3840, screen.height: 2160` and you get exactly that, on a tier that draws a 4K screen zero times in 200 seeds.
|
||||
|
||||
**Rule of thumb:** pin correlated fields together, or just trust the sampler.
|
||||
|
||||
@@ -108,6 +108,7 @@ profile disagree with the browser, on about 12% of seeds.
|
||||
| `screen.height` | int | `1440` |
|
||||
| `screen.dpr` | float | `1.0`, `1.25`, `1.5`, `2.0` |
|
||||
| `screen.color_depth` | int | `24` | `screen.colorDepth` and `screen.pixelDepth`. Declared rather than read off the panel: the engine only returned a fixed 24 when resistFingerprinting was on, which we do not turn on because it is itself a tell, so before this it reported the real display - 30 on a wide-gamut monitor, and a persona claiming an office laptop with a 30-bit panel is a contradiction a page can read. |
|
||||
| `screen.refresh_hz` | int | `60`, `144` | The monitor's refresh rate, which is the cadence of `requestAnimationFrame`: a page reads it from the gap between two frame timestamps. Without it the engine follows the host's display, so one persona answered about 120 on one machine and 58 on another. Not sampled: 60 is what an office laptop or monitor runs at, and a 144 Hz persona is one pin away. |
|
||||
|
||||
### `hardware.*`
|
||||
|
||||
@@ -116,16 +117,15 @@ profile disagree with the browser, on about 12% of seeds.
|
||||
| `hardware.concurrency` | int | `16` | [`navigator.hardwareConcurrency`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/hardwareConcurrency). |
|
||||
| `hardware.storage_quota_mb` | int | `10_000` | `navigator.storage.estimate().quota / 1024**2`. |
|
||||
| `hardware.max_touch_points` | int | `0` | `navigator.maxTouchPoints`. `0` is what a desktop without a touchscreen reports, which is what the personas claim; it was a constant compiled into the binary until 2026-08-08, correct but not inspectable and not overridable. |
|
||||
| `hardware.voices` | str | *(five en-US voices)* | The speechSynthesis voice list, as the engine parses it: `name\|lang\|default\|localService`, comma separated. Always the English (United States) set today, whatever locale the session resolved to - a real Windows machine running in Italian reports Italian voices, so an it-IT session declaring only American ones contradicts itself. The per-locale tables have to be measured on a real install of each locale, not invented; this field is the level at which that becomes possible. |
|
||||
| `hardware.voices` | str | *(the session language's voices)* | The speechSynthesis voice list, as the engine parses it: `name\|lang\|default\|localService`, comma separated. Unpinned, it follows the session's first language: English gives the English (United States) set, Italian the set of a Windows with English UI and Italian added, as measured on one; a language without a measured set keeps the English one, because a table has to be measured on a real install, not invented. A pin wins over the table. |
|
||||
| `hardware.fake_media_devices` | bool | `True` | One fake audio input and one fake video input on every host, so `enumerateDevices` does not report the machine's real hardware. Measured in a secure context (about:blank is not one, and measuring there made the two hosts look like they agreed because both returned nothing): Linux enumerated 0 real devices and Windows 2. |
|
||||
| `hardware.media_enumeration_ms` | int | `412` | How long the first `navigator.mediaDevices.enumerateDevices()` of a session takes, in ms. With `fake_media_devices` the engine no longer asks the host's audio stack for its speakers, whose time it was (15-40 ms on Linux, about 300 on Windows), and answers after this long on every host; later calls are fast, as in Firefox. Drawn from the seed between 240 and 640, the range retail Windows Firefox took on one machine in two states. Ignored with real devices. Needs firefox-45. |
|
||||
| `hardware.storage_enabled` | bool | `True` | Whether cookies, localStorage, sessionStorage and indexedDB all work. One field for four booleans because Gecko exposes them through two levers, not four. They used to be true because nobody touched `network.cookie.cookieBehavior` or `dom.storage.enabled`, i.e. because the upstream defaults happened to be right. |
|
||||
| `hardware.generics` | str | *(20 rows)* | The CSS generic families, as `generic\|lang\|family` records separated by newlines. It was ten rows compiled into gfxPlatformFontList.cpp; the `x-math` row is load-bearing and easy to lose, because without it every MathML glyph renders in Times New Roman on every host, which no cross-OS gate can see. |
|
||||
| `hardware.accessibility_overrides` | bool | `False` | Reduced motion, reduced transparency and inverted colours. Content-exposed media features that read the HOST through different code on each platform. They agreed across our two builds when measured - by luck, both machines having no accessibility settings on - and nothing declared them. Costs nothing to close: Firefox reads these generic prefs before the native path. |
|
||||
| `screen.taskbar_px` | int | `48` | How much shorter `availHeight` is than `height`. It was the literal 48 in three places - the generator, nsScreen.cpp and nsGlobalWindowOuter.cpp - kept in step by hand. |
|
||||
| `screen.chrome_w` | int | `0` | `outerWidth - innerWidth`, i.e. how much wider the window is than the page. Zero, because a real Firefox has no horizontal chrome: measured against stock 151, it answers 0 and this wrapper answered 14 for months. It was a module constant in `launcher.py`, so nothing could pin it and nothing could compare it to anything. |
|
||||
| `screen.chrome_h` | int | `85` | `outerHeight - innerHeight`: tab strip plus navigation toolbar. Also measured against stock 151, which answers 85 where we answered 91. Pin it if a persona needs a bookmarks toolbar or a different tab density. |
|
||||
| `screen.window_x` | int | `0` | `window.screenX`, and with it `screenLeft` and `mozInnerScreenX`. `outerWidth` already claims a maximized window filling the screen, and a maximized window is at the origin - but the position was never declared, so it stayed whatever the OS gave the headless widget: `(4,4)` on Windows, which put the right edge of a 1920-wide window at 1924 on a 1920 screen. That is impossible on a real machine and takes one addition to spot. |
|
||||
| `screen.window_y` | int | `0` | `window.screenY` / `screenTop`, and the base of `mozInnerScreenY` (`window_y + chrome_h`). Pin both this and `window_x` together with a smaller viewport if you want a window that is not maximized. |
|
||||
|
||||
The window around the page is not a pin: since 0.29.0 (core 38) it is a frame measured on Windows Firefox at each display scale, so `outerWidth`, `screenX` and `mozInnerScreenY` follow `screen.dpr`, which takes 1, 1.25, 1.5 or 2. A maximized window answers `screenX` -8 and is 16 wider than the work area at 100%, and a popup answers its own frame. The keys `screen.chrome_w`, `screen.chrome_h`, `screen.window_x` and `screen.window_y` are gone.
|
||||
|
||||
### `audio.*`
|
||||
|
||||
@@ -168,7 +168,8 @@ would be the signal. They are pinnable for A/B work, not for realism.
|
||||
|
||||
| Key | Type | Example | Notes |
|
||||
|-----|------|---------|-------|
|
||||
| `font.ui_family` | str | `"Segoe UI"` | Family behind `font: menu`, `font: caption`, and the `-moz-` widget fonts. |
|
||||
| `font.ui_family` | str | `"Segoe UI"` | Family behind `font: menu` and `font: caption`. The form-control fonts take `font.dialog_family`. |
|
||||
| `font.dialog_family` | str | `"MS Shell Dlg 2"` | The family of the form-control fonts, `-moz-button`, `-moz-field` and `-moz-list`, which is not the shell font: Windows Firefox builds them from the message font under the name "MS Shell Dlg 2", and a page reads it with one `getComputedStyle(input).fontFamily`. |
|
||||
| `font.ui_size` | str | `"12"` | **A string, not an int.** Gecko reads this pref through `Preferences::GetFloat`, which parses the value from its text form; an int is not rejected, it is ignored, and the UI silently falls back to 16px. |
|
||||
| `font.monospace_size` | int | `13` | Default monospace size. Firefox ships 13 on Windows and 12 in its Unix block, and the gap is directly readable as the width of the `monospace` generic at the default size. |
|
||||
| `font.alpha_ladder` | tuple of int | `(0, 18, 35, ..., 255)` | The distinct alpha levels a Windows rasteriser leaves on an antialiased glyph edge, ascending, first `0` and last `255` so a fully transparent or fully opaque pixel never moves. Canvas readback snaps onto these. An empty tuple disables the snap, which is what you want when measuring what the unsnapped edge looks like. |
|
||||
@@ -180,15 +181,43 @@ would be the signal. They are pinnable for A/B work, not for realism.
|
||||
| `font.cleartype_rendering_mode` | int | `5` | DirectWrite rendering mode. |
|
||||
| `font.freetype_gamma` | int | `220` | The FreeType equivalent of `cleartype_gamma`, x100. Declared so the Linux build rasterises with Windows' curve instead of Skia's linear default. |
|
||||
| `font.freetype_contrast` | int | `100` | The FreeType equivalent of `cleartype_contrast`, x100. |
|
||||
| `font.system_text_quality` | int | `5` | The text quality the engine would otherwise ask the host for: `0` none, `4` standard antialiasing, `5` ClearType. It decides whether the ClearType parameters above apply at all, so on a machine with ClearType off (an RDP session, a VM, a Server) the same binary would draw different text from the same declaration. Declared, never asked of the machine. Any other value is refused. |
|
||||
|
||||
### `desktop.*`
|
||||
|
||||
The Windows desktop settings a page can read, declared instead of asked of the
|
||||
machine. Each one is a value whose engine default either reads the host or
|
||||
differs between Windows and Linux, so without it the same persona answered
|
||||
with the machine it ran on. The defaults are a Windows 11 desktop at its
|
||||
defaults, and they are not sampled.
|
||||
|
||||
| Key | Type | Default | Notes |
|
||||
|-----|------|---------|-------|
|
||||
| `desktop.text_scale` | int | `100` | Windows' "Text size" slider, in percent. It multiplies the device pixel ratio, so `100` is the value that leaves `screen.dpr` the one number for it. |
|
||||
| `desktop.overlay_scrollbars` | bool | `True` | Windows 11's "Automatically hide scroll bars": scrollbars draw over the content, so a scrolling box loses no width (`offsetWidth - clientWidth` is 0). Off, they take `desktop.scrollbar_size`. |
|
||||
| `desktop.scrollbar_style` | int | `5` | How scrollbars are drawn: 5 Windows 11, 4 Windows 10, 2 GTK. |
|
||||
| `desktop.scrollbar_size` | int | `17` | The width a scrollbar takes when it is not an overlay, at 96 dpi. |
|
||||
| `desktop.drag_threshold` | int | `3` | How far the pointer moves before `dragstart`. |
|
||||
| `desktop.scroll_to_click` | bool | `False` | A click in a scrollbar's track jumps there instead of paging. |
|
||||
| `desktop.document_colors` | int | `0` | When the page's colours give way to the system's: `0`, the Windows default, only under a high-contrast theme. |
|
||||
| `desktop.select_styling` | bool | `True` | A page may style a `<select>`'s popup, as on Windows. |
|
||||
| `desktop.word_select_eats_space` | bool | `True` | A double click selects the word and the space after it, as on Windows; a page reads it with `getSelection()` after a real double click. |
|
||||
| `desktop.srgb_output` | bool | `True` | Tagged images are converted to sRGB instead of the host monitor's colour profile, which a small canvas reads back. |
|
||||
| `desktop.os_client_certs` | bool | `False` | Whether the operating system's personal certificates answer a server that asks for one. Off: the persona has none. |
|
||||
| `desktop.theme_accent` | bool | `False` | Whether the page-visible `AccentColor` follows the desktop theme's accent; on Windows it does not. |
|
||||
| `desktop.hour_cycle` | int | `0` | The clock format, `0` meaning the locale decides, as on Windows; otherwise the host's 12/24-hour setting changes every `toLocaleTimeString()`. |
|
||||
| `desktop.select_on_focus` | bool | `True` | Tabbing into a pre-filled field selects all of it, as on Windows. |
|
||||
| `desktop.palette` | str | *(the Windows palette)* | The system colours, light and dark, as `ui.<name>\|<light>\|<dark>` records, one per line, the dark part empty where the scheme does not move it. Every persona carries both schemes; `dark_theme` says which one it uses. |
|
||||
|
||||
### Top-level
|
||||
|
||||
| Key | Type | Example | Notes |
|
||||
|-----|------|---------|-------|
|
||||
| `dark_theme` | bool | `False` | [`prefers-color-scheme: dark`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme). Real traffic is ~85% light, 15% dark. |
|
||||
| `branding` | str | `"official"`, `"unofficial"`, `"C:/brand/branding.zip"` | The branding a page can read at `chrome://branding/content/` and `resource://usercontext-content/branding/`: the about dialog's stylesheet, the wordmarks' boxes, the logos' sizes. `"official"` (the default) is the retail Firefox's files, `"unofficial"` those of a build without the trademark, and an absolute path is a zip archive of your own holding exactly the same 16 file names at its root; anything else raises when the profile is built. An archive and not a folder because the engine serves it the way Firefox serves its own branding, from inside an archive: served from a folder, a page could tell the difference. The engine keeps no copy of its own. Needs firefox-48. |
|
||||
|
||||
`dark_theme` is the ONLY top-level key. Anything else raises `ValueError: pin key
|
||||
'...' is not valid`.
|
||||
`dark_theme` and `branding` are the ONLY top-level keys. Anything else raises
|
||||
`ValueError: pin key '...' is not valid`.
|
||||
|
||||
**`fonts` is not one of them, and no longer exists as an axis.** This table used
|
||||
to list a per-profile font allowlist ("the sampler usually picks 14-24 system
|
||||
@@ -226,7 +255,7 @@ Pin the whole visible tuple - GPU, screen, concurrency, audio:
|
||||
```python
|
||||
pin = {
|
||||
"gpu.vendor": "Google Inc. (Intel)",
|
||||
"gpu.renderer": "ANGLE (Intel, Intel(R) Iris(R) Xe Graphics Direct3D11)",
|
||||
"gpu.renderer": "ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)",
|
||||
"gpu.class_tier": "mid_range",
|
||||
"screen.width": 1920,
|
||||
"screen.height": 1080,
|
||||
|
||||
@@ -23,8 +23,8 @@ is the fastest way to tell the three apart.
|
||||
|
||||
## Cause 1: the browsers were never downloaded
|
||||
|
||||
The library and the binaries are decoupled on purpose, so `pip install playwright` or
|
||||
`npm install playwright` alone leaves you with a client and no browser to drive:
|
||||
The library and the binaries are decoupled on purpose, so installing the `playwright`
|
||||
package from PyPI or npm alone leaves you with a client and no browser to drive:
|
||||
|
||||
```bash
|
||||
playwright install # every browser Playwright supports
|
||||
@@ -144,7 +144,7 @@ changing anything, since the fix for each is different and none of them is guess
|
||||
a specific cache path and did not find a runnable one there. The message names the exact
|
||||
path it checked.
|
||||
|
||||
**Does `npm install playwright` or `pip install playwright` include the browsers?**
|
||||
**Does installing the `playwright` package from npm or PyPI include the browsers?**
|
||||
No. The package is the client library; `playwright install` is a separate, required step
|
||||
that downloads the actual browser binaries.
|
||||
|
||||
|
||||
@@ -43,9 +43,11 @@ Most current Debian and Ubuntu base images are published as multi-architecture m
|
||||
|
||||
```dockerfile
|
||||
FROM --platform=linux/arm64 debian:bookworm-slim
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
python3 python3-pip ca-certificates
|
||||
RUN pip install invisible-playwright
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /bin/
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates
|
||||
RUN uv venv --python ">=3.11" /opt/venv
|
||||
ENV VIRTUAL_ENV=/opt/venv PATH="/opt/venv/bin:$PATH"
|
||||
RUN uv pip install --no-cache invisible-playwright
|
||||
```
|
||||
|
||||
The `--platform` flag pins the build explicitly rather than relying on the Docker daemon's default, which matters if you build on one machine and deploy to another. For a real GPU, font set, or screen presented to the browser instead of a bare container's defaults, see [How to run Playwright in Docker without getting detected](how-to-run-playwright-docker-undetected.md); it applies the same way on arm64, only the base image and engine differ by architecture.
|
||||
@@ -76,7 +78,7 @@ One caveat: Python's own `platform.machine()` inside your automation does not pr
|
||||
|
||||
## What this project ships, and does not
|
||||
|
||||
This project currently builds and publishes engines for Linux on both x86_64 and arm64, and for Windows on x86_64. There is no macOS build; macOS support was discontinued after the engine build for it ended, so a macOS host has no engine to download here regardless of its own CPU architecture.
|
||||
This project builds and publishes engines for Linux x86_64 and Windows x86_64. Linux arm64 is no longer supported from firefox-56: firefox-55 is the last engine built for it. There is no macOS build; macOS support was discontinued after the engine build for it ended, so a macOS host has no engine to download here regardless of its own CPU architecture.
|
||||
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
@@ -90,7 +92,7 @@ It usually starts under emulation, but runs slower and less predictably, which m
|
||||
Run `file` on the resolved browser binary to see its real architecture, and compare it to the host's own `uname -m` or your cloud provider's listed instance type, rather than trusting the image tag alone.
|
||||
|
||||
**Does invisible_playwright support ARM64?**
|
||||
Yes, on Linux: separate engine builds for x86_64 and arm64, alongside a Windows x86_64 build. There is currently no macOS build.
|
||||
Not on Linux from firefox-56: firefox-55 is the last engine built for Linux arm64. The engines are Linux x86_64 and Windows x86_64. There is currently no macOS build.
|
||||
|
||||
**Is WebKit's ARM64 Linux support as mature as Chromium and Firefox?**
|
||||
Playwright's own system requirements name Debian 12 and 13 and Ubuntu 22.04, 24.04 and 26.04 on "x86-64 or arm64" without splitting the list per browser, so confirm the browser you need actually downloads on your distribution before you build around it.
|
||||
|
||||
@@ -34,6 +34,7 @@ Debian and Ubuntu-based images, which most Playwright containers are, ship almos
|
||||
|
||||
```dockerfile
|
||||
FROM python:3.11-slim
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /bin/
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
fonts-noto \
|
||||
@@ -46,7 +47,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
|
||||
WORKDIR /app
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
RUN uv pip install --system --no-cache -r requirements.txt
|
||||
|
||||
RUN python -m invisible_playwright fetch
|
||||
|
||||
|
||||
@@ -108,7 +108,7 @@ anecdotal. Fix the seed, capture, and assert two things at once: the screenshot
|
||||
is a sane size and it is a real image, not a wall of noise.
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright
|
||||
uv add invisible-playwright
|
||||
```
|
||||
|
||||
```python
|
||||
|
||||
@@ -132,10 +132,11 @@ to add, because the engine downloads itself on first use:
|
||||
|
||||
```dockerfile
|
||||
FROM python:3.12-slim
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /bin/
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends xvfb \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
RUN pip install invisible-playwright
|
||||
RUN uv pip install --system invisible-playwright
|
||||
COPY scrape.py .
|
||||
CMD ["python", "scrape.py"]
|
||||
```
|
||||
|
||||
@@ -55,8 +55,9 @@ jobs:
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- uses: astral-sh/setup-uv@v6
|
||||
- name: Install
|
||||
run: pip install invisible-playwright
|
||||
run: uv pip install --system invisible-playwright
|
||||
- name: Run
|
||||
run: python scrape.py
|
||||
```
|
||||
|
||||
@@ -199,7 +199,8 @@ describe:
|
||||
|
||||
```dockerfile
|
||||
FROM python:3.12-slim
|
||||
RUN pip install invisible-playwright
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.12.10 /uv /uvx /bin/
|
||||
RUN uv pip install --system invisible-playwright
|
||||
ENV INVISIBLE_PLAYWRIGHT_CACHE_DIR=/engines
|
||||
VOLUME /engines
|
||||
COPY scrape_job.py /srv/scrape_job.py
|
||||
|
||||
@@ -93,6 +93,30 @@ This is the same shape as every other suppression in this subject: the value you
|
||||
was less interesting than the absence you created. If you can leave them enabled, leave
|
||||
them enabled, and handle the interception complexity rather than trading it for a signal.
|
||||
|
||||
### Engine-native blocking for request guards
|
||||
|
||||
`browser.new_context(service_workers="block")` and
|
||||
`firefox.launch_persistent_context(..., service_workers="block")` are honoured by the
|
||||
engine itself (`Browser.setServiceWorkersBlocked`, from firefox-37). The wrapper never
|
||||
uses a page script or `dom.serviceWorkers.enabled=false`: the latter also disables
|
||||
Firefox's request-interception hook, so `route()` refuses in that configuration.
|
||||
|
||||
Juggler cancels service-worker script downloads in the parent
|
||||
process, scoped by `originAttributes.userContextId`. `register()` rejects with Firefox's
|
||||
native network-failure exception; no request for the main script reaches the server.
|
||||
The container and its prototype are unchanged, and `register.toString()` still reports
|
||||
native code. This removes the page-script automation artefact, **not the observable
|
||||
absence of a worker**.
|
||||
|
||||
Before acknowledging the option, Juggler shuts down and unregisters existing workers
|
||||
for that context, including registrations saved in a persistent profile. That removal
|
||||
is permanent; turning blocking off does not restore them. A registration listener also
|
||||
removes later registrations. Requests in a blocked context are never handed to a
|
||||
service-worker intercept controller, while normal page requests still reach `route()`.
|
||||
Other contexts and ordinary workers (including their `importScripts()`) are unchanged.
|
||||
Apply the option at context creation, before opening or navigating pages; it cannot
|
||||
undo requests sent before the policy was applied.
|
||||
|
||||
## What a browser context does and does not separate
|
||||
|
||||
A browser context separates storage but nothing about the machine. Two contexts get
|
||||
|
||||
@@ -43,7 +43,7 @@ That directness is the whole reason the fixture pair works cleanly:
|
||||
Install what you need first:
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright pytest pytest-asyncio
|
||||
uv add invisible-playwright pytest pytest-asyncio
|
||||
```
|
||||
|
||||
And turn on pytest-asyncio's auto mode so you do not decorate every test by hand. In
|
||||
|
||||
@@ -102,8 +102,8 @@ How this project does it, because the details are the part that bites:
|
||||
request per launch announcing that a new session started.
|
||||
- The **same** lookup feeds the locale and the WebRTC public address, so those three
|
||||
cannot drift apart. They come from one answer, not three.
|
||||
- **On failure with a proxy configured, it fails the launch** instead of falling back
|
||||
to the host timezone. That fallback is the exact mismatch you set out to avoid, and a
|
||||
- **On failure it fails the launch**, with a proxy or without one, instead of falling
|
||||
back to the host timezone. That fallback is the exact mismatch you set out to avoid, and a
|
||||
silent fallback to it is worse than an error.
|
||||
|
||||
That last one is a small decision that took a while to get right. A fallback that
|
||||
|
||||
@@ -146,7 +146,7 @@ with InvisiblePlaywright(seed=42, proxy=proxy) as browser:
|
||||
```
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright
|
||||
uv add invisible-playwright
|
||||
```
|
||||
|
||||
If your project is committed to Chrome and to an async Python API of its own, and
|
||||
|
||||
@@ -105,7 +105,7 @@ Switching from plain Playwright is the same two-line change it always is, and th
|
||||
object is a real Playwright `Browser` with every method intact:
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright
|
||||
uv add invisible-playwright
|
||||
```
|
||||
|
||||
```python
|
||||
|
||||
@@ -191,7 +191,7 @@ authentication](playwright-socks5-proxy-authentication.md).
|
||||
A minimal install to run the snippet:
|
||||
|
||||
```bash
|
||||
pip install invisible-playwright
|
||||
uv add invisible-playwright
|
||||
```
|
||||
|
||||
## Conclusion
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "invisible_playwright"
|
||||
version = "0.16.2"
|
||||
version = "0.47.1"
|
||||
description = "Playwright wrapper for a patched Firefox with deterministic stealth profile."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
@@ -69,10 +69,10 @@ dependencies = [
|
||||
# metadata; nothing in src/ hardcodes a second copy (tests/test_core_pin.py
|
||||
# fails if one appears). What stays invisible to install-time machinery is the
|
||||
# --no-deps / lockfile residue, and _pin.py is the only layer that sees it.
|
||||
"invisible_core==30.23.0",
|
||||
"invisible_core==58.56.0",
|
||||
# ⛔ playwright is NO LONGER a dependency: since the full fork, the Python
|
||||
# client lives in src/invisible_playwright/_pw/ and the Node driver in
|
||||
# src/invisible_playwright/_driver/. Reintroducing it would not visibly
|
||||
# client lives in src/invisible_playwright/_pw/ and its server in
|
||||
# src/invisible_playwright/_juggler/ (no Node driver). Reintroducing it would not visibly
|
||||
# break anything - that is the problem - because the two packages coexist
|
||||
# without colliding: one of them would simply never run, and whoever
|
||||
# reads the pyproject would believe the opposite.
|
||||
@@ -117,7 +117,7 @@ dependencies = [
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = ["pytest>=7", "build>=1", "ruff>=0.6", "pytest-rerunfailures>=14", "pytest-timeout>=2", "pytest-xdist>=3", "playwright==1.61.0"]
|
||||
dev = ["pytest>=7", "build>=1", "ruff>=0.6", "pytest-rerunfailures>=14", "pytest-timeout>=2", "pytest-xdist>=3", "playwright==1.61.0", "cryptography>=41"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
markers = [
|
||||
@@ -138,13 +138,15 @@ markers = [
|
||||
# invisible_core's addopts said `not slow` while never declaring `slow`,
|
||||
# so the exclusion matched nothing and the word meant nothing.
|
||||
#
|
||||
# The blocks are byte-identical on purpose, and
|
||||
# The lists are identical on purpose, and
|
||||
# invisible_core/tests/test_marker_vocabulary.py fails when they drift.
|
||||
# (It compares the parsed lists, so this comment may differ per repo.)
|
||||
"unit: pure logic - no I/O, no network, no subprocess, no browser",
|
||||
"integration: several modules together, in process - no network, no browser",
|
||||
"e2e: needs something outside this process - the network, the real patched binary, or a display",
|
||||
"slow: builds a wheel or an sdist - opt-in only",
|
||||
"linux_only: requires Linux",
|
||||
"wall_clock: its verdict reads a wall-clock duration - the e2e run gives it the machine alone, after the parallel tests",
|
||||
]
|
||||
# Both exclusions in ONE addopts: declaring the key twice is a TOML error, not
|
||||
# a merge, and pytest then sees neither value.
|
||||
@@ -232,16 +234,15 @@ release_tags = ["v"]
|
||||
# gained the `.js/.css/.html` coverage AIHawk's did.
|
||||
#
|
||||
# Vendored upstream Playwright is excluded as a FOLDER, but our own patches
|
||||
# inside it are still read: they are found by the marker. `injected.js` is
|
||||
# extracted from the upstream bundle. `test_fork.py` carries Italian ON
|
||||
# inside it are still read: they are found by the marker. (`injected.js`,
|
||||
# extracted from the upstream bundle, moved to invisible-core with the Juggler
|
||||
# client in 0.30.0, and its exclusion with it.) `test_fork.py` carries Italian ON
|
||||
# PURPOSE - its known-bad fixture reproduces a JavaScript comment whose defect
|
||||
# IS the trailing apostrophe of an Italian word; translate it and the mutation
|
||||
# stops reproducing the bug. Named file by file, never by folder: an
|
||||
# exclusion that names nothing is refused by the gate.
|
||||
[tool.invisible.english]
|
||||
excluded = [
|
||||
"src/invisible_playwright/_pw/",
|
||||
"src/invisible_playwright/_juggler/injected.js",
|
||||
"tests/test_fork.py",
|
||||
]
|
||||
marker = "MODIFIED by invisible_playwright"
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Builds tests/data/canvas_icc_ref/refs.json, the reference of the canvas ICC readback test.
|
||||
|
||||
One measurement of retail Firefox 159.0 on Windows with the default prefs (the run
|
||||
``a_win_default``: qcms converts a tagged image to the monitor profile, here the stock
|
||||
"sRGB Color Space Profile.icm"), and one control run on the same machine with
|
||||
gfx.color_management.force_srgb=true (``b_win_force_srgb``: the bytes without that
|
||||
conversion), both made by index.html and the images of gen_images.py:
|
||||
|
||||
python -I scripts/build_canvas_icc_refs.py <a_win_default.json> <b_win_force_srgb.json> \
|
||||
--repeat <a2_win_default_repeat.json> --host-profile <host_display_profile.json> \
|
||||
--source <name of the capture> [--out tests/data/canvas_icc_ref/refs.json]
|
||||
|
||||
The script stops if the repeat run has other hashes than the reference run, if the runs
|
||||
were not made on the same Firefox build, or if the prefs of the two runs are not the default
|
||||
and force_srgb=true. The probes are the 72 of the page: for each of the 10 images drawImage,
|
||||
drawImage at 32 px, createImageBitmap with the default colour space conversion and with
|
||||
``none``; the 22 fill colours; the canvas colorSpace probe; the 9 environment values.
|
||||
|
||||
Standard library only: it does not import invisible_core, and the repository holds no PNG
|
||||
and no run's pixel hex, only hashes and sizes.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_OUT = Path(__file__).resolve().parents[1] / "tests" / "data" / "canvas_icc_ref" / "refs.json"
|
||||
IMAGE_PROBES = ("drawImage", "drawImage_scaled32", "bitmap_default", "bitmap_none")
|
||||
#: Value probes that are not colour management: the host's theme, which the retail machine
|
||||
#: had dark; the test does not compare it (the persona's colour scheme is checked elsewhere).
|
||||
NOT_COMPARED = ("env | prefers-color-scheme:dark",)
|
||||
|
||||
|
||||
GEN_IMAGES = DEFAULT_OUT.parent / "gen_images.py"
|
||||
|
||||
|
||||
def image_files():
|
||||
"""{image id: {file, bytes, sha256}} of the ten images gen_images.py writes: the reference
|
||||
names them, so a generator that drifts is seen before the engine is blamed."""
|
||||
spec = importlib.util.spec_from_file_location("gen_images", GEN_IMAGES)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
imgs, _profiles = mod.build_images()
|
||||
return {iid: {"file": "images/%s.%s" % (iid, ext), "bytes": len(data),
|
||||
"sha256": hashlib.sha256(data).hexdigest()}
|
||||
for iid, ext, data, _what in imgs}
|
||||
|
||||
|
||||
class RefError(ValueError):
|
||||
"""The runs cannot be one reference."""
|
||||
|
||||
|
||||
def env_sha256(value):
|
||||
"""The hash of an environment value: SHA-256 of its compact JSON (as JSON.stringify)."""
|
||||
return hashlib.sha256(json.dumps(value, separators=(",", ":")).encode()).hexdigest()
|
||||
|
||||
|
||||
def probes(R):
|
||||
"""{probe name: {kind, sha256, bytes (pixel probes), value (env)}} of a page result R
|
||||
(``window.R`` of index.html). ``bytes`` is the RGBA length: 4 x width x height."""
|
||||
out = {}
|
||||
for iid, v in R["images"].items():
|
||||
for k in IMAGE_PROBES:
|
||||
e = v.get(k)
|
||||
if not isinstance(e, dict) or "sha256" not in e:
|
||||
raise RefError("image %s probe %s has no hash: %r" % (iid, k, e))
|
||||
size = 32 if k == "drawImage_scaled32" else 16
|
||||
out["%s | %s" % (iid, k)] = {"kind": "image", "sha256": e["sha256"],
|
||||
"bytes": 4 * size * size}
|
||||
for f, v in R["fills"].items():
|
||||
if "sha256" not in v:
|
||||
raise RefError("fill %s has no hash: %r" % (f, v))
|
||||
out["fill | " + f] = {"kind": "fill", "sha256": v["sha256"], "bytes": 4 * 16 * 16}
|
||||
p3 = R["canvas_colorspace"].get("p3_fill_p3_canvas") or {}
|
||||
if "sha256" not in p3:
|
||||
raise RefError("the canvas colorSpace probe has no hash")
|
||||
out["canvas colorSpace p3 fill"] = {"kind": "colorspace", "sha256": p3["sha256"],
|
||||
"bytes": 4 * 16 * 16}
|
||||
for k, v in R["env"].items():
|
||||
out["env | " + k] = {"kind": "env", "sha256": env_sha256(v), "value": v}
|
||||
return out
|
||||
|
||||
|
||||
def build(a, b, repeat, host_profile, source):
|
||||
"""The reference from the default run ``a``, the control run ``b`` (force_srgb), the
|
||||
repeat of ``a`` and the host profile description; all as loaded JSON."""
|
||||
for key in ("buildid", "exe_sha256", "version", "os"):
|
||||
if a["firefox"][key] != b["firefox"][key] or a["firefox"][key] != repeat["firefox"][key]:
|
||||
raise RefError("the runs differ in the Firefox %s" % key)
|
||||
pa, pb, pr = probes(a["R"]), probes(b["R"]), probes(repeat["R"])
|
||||
if pa != pr:
|
||||
bad = sorted(k for k in pa if pa[k] != pr.get(k))
|
||||
raise RefError("the repeat run differs from the reference run on %d probes: %s"
|
||||
% (len(bad), ", ".join(bad[:5])))
|
||||
if set(pa) != set(pb):
|
||||
raise RefError("the control run has other probes than the reference run")
|
||||
prefs_a, prefs_b = a["prefs_read_back"], b["prefs_read_back"]
|
||||
if prefs_a.get("gfx.color_management.display_profile") not in ("", None):
|
||||
raise RefError("the reference run has a display_profile pref: it must read the host's")
|
||||
if prefs_a.get("gfx.color_management.force_srgb") is not False:
|
||||
raise RefError("the reference run is not made with the default force_srgb (false)")
|
||||
if prefs_b.get("gfx.color_management.force_srgb") is not True:
|
||||
raise RefError("the control run is not made with force_srgb=true")
|
||||
for k, v in prefs_a.items():
|
||||
if k != "gfx.color_management.force_srgb" and prefs_b.get(k) != v:
|
||||
raise RefError("the control run differs in %s" % k)
|
||||
|
||||
out = {}
|
||||
dependent = []
|
||||
for name, p in pa.items():
|
||||
e = dict(p)
|
||||
if pb[name]["sha256"] != p["sha256"]:
|
||||
e["without_conversion_sha256"] = pb[name]["sha256"]
|
||||
dependent.append(name)
|
||||
if name in NOT_COMPARED:
|
||||
e["compared"] = False
|
||||
out[name] = e
|
||||
return {
|
||||
"test_page": "index.html",
|
||||
"image_generator": "gen_images.py",
|
||||
"source": {
|
||||
"capture": source,
|
||||
"reference_run": "runs/a_win_default.json",
|
||||
"repeat_run": "runs/a2_win_default_repeat.json (same hashes on all probes)",
|
||||
"control_run": "runs/b_win_force_srgb.json (gfx.color_management.force_srgb=true)",
|
||||
"date": "2026-11-09",
|
||||
},
|
||||
"firefox": {**a["firefox"], "prefs": prefs_a},
|
||||
"display_profile": {"file": host_profile["file"], "size": host_profile["size"],
|
||||
"sha256": host_profile["sha256"], "api": "GetICMProfileW"},
|
||||
"images": image_files(),
|
||||
"probe_count": len(out),
|
||||
"profile_dependent_count": len(dependent),
|
||||
"profile_dependent": sorted(dependent),
|
||||
"probes": out,
|
||||
}
|
||||
|
||||
|
||||
def main(argv):
|
||||
ap = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("reference", help="run json of the retail default run (a_win_default)")
|
||||
ap.add_argument("control", help="run json of the force_srgb run (b_win_force_srgb)")
|
||||
ap.add_argument("--repeat", required=True, help="run json of the repeat of the default run")
|
||||
ap.add_argument("--host-profile", required=True, help="host_display_profile.json")
|
||||
ap.add_argument("--source", default="canvas-color/canvas-color-icc-readback",
|
||||
help="name of the capture the runs come from")
|
||||
ap.add_argument("--out", default=str(DEFAULT_OUT))
|
||||
a = ap.parse_args(argv[1:])
|
||||
|
||||
def load(p):
|
||||
return json.loads(Path(p).read_text(encoding="utf-8"))
|
||||
|
||||
try:
|
||||
refs = build(load(a.reference), load(a.control), load(a.repeat),
|
||||
load(a.host_profile), a.source)
|
||||
except RefError as e:
|
||||
print("error: %s" % e, file=sys.stderr)
|
||||
return 1
|
||||
Path(a.out).write_text(json.dumps(refs, ensure_ascii=False, indent=1) + "\n",
|
||||
encoding="utf-8")
|
||||
print("%d probes (%d depend on the display profile) -> %s"
|
||||
% (refs["probe_count"], refs["profile_dependent_count"], a.out))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Builds tests/data/canvas_text_ref/refs.json, the one reference of the canvas text test.
|
||||
|
||||
Two measurements of retail Firefox 159.0 on Windows, made with the same page code, the same
|
||||
bundled font files and the same machine, are merged by case id:
|
||||
|
||||
python -I scripts/build_canvas_text_refs.py <canvas_ref_bundle/refs.json> \
|
||||
<canvas_ref_ext/refs.json> [--out tests/data/canvas_text_ref/refs.json]
|
||||
|
||||
The bundle file has the base cases (no ``gruppo`` field: they become group ``0_base``), the
|
||||
extension file has the cases of the other groups. A case id that is in both files is kept
|
||||
once, with the extension's group; the script stops if the two hashes of such a case differ,
|
||||
or if the two files were not measured on the same Firefox build, with the same ClearType
|
||||
state and the same font files. Fields that name a file of the measuring machine (the PNG
|
||||
paths) are dropped: the repository holds no PNG and no font.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
BASE_GROUP = "0_base"
|
||||
DEFAULT_OUT = Path(__file__).resolve().parents[1] / "tests" / "data" / "canvas_text_ref" / "refs.json"
|
||||
_DROP = ("png",)
|
||||
|
||||
|
||||
class MergeError(ValueError):
|
||||
"""The two measurements cannot be one reference."""
|
||||
|
||||
|
||||
def _case(case, group):
|
||||
out = {k: v for k, v in case.items() if k not in _DROP}
|
||||
out.setdefault("alpha", True)
|
||||
out.setdefault("stretch", "normal")
|
||||
out.setdefault("text", "TEXT")
|
||||
out["gruppo"] = group
|
||||
return out
|
||||
|
||||
|
||||
def merge(bundle, ext):
|
||||
"""One reference from the bundle measurement and the extension measurement."""
|
||||
for key in ("firefox", "canvas", "cleartype", "text"):
|
||||
if bundle[key] != ext[key]:
|
||||
raise MergeError("the two measurements differ in %r: %r vs %r"
|
||||
% (key, bundle[key], ext[key]))
|
||||
ext_fonts = {f["bundle_file"]: f for f in ext["fonts"]}
|
||||
for f in bundle["fonts"]:
|
||||
other = ext_fonts.get(f["bundle_file"])
|
||||
if other is None or other["sha256"] != f["sha256"]:
|
||||
raise MergeError("font %s is not the same file in the two measurements"
|
||||
% f["bundle_file"])
|
||||
|
||||
cases = {}
|
||||
for cid, c in bundle["cases"].items():
|
||||
cases[cid] = _case(c, c.get("gruppo") or BASE_GROUP)
|
||||
for cid, c in ext["cases"].items():
|
||||
if not c.get("gruppo"):
|
||||
raise MergeError("extension case %r has no group" % cid)
|
||||
if cid in cases and cases[cid]["sha256"] != c["sha256"]:
|
||||
raise MergeError("case %r has two different hashes: %s and %s"
|
||||
% (cid, cases[cid]["sha256"], c["sha256"]))
|
||||
cases[cid] = _case(c, c["gruppo"])
|
||||
|
||||
groups = {}
|
||||
for c in cases.values():
|
||||
groups[c["gruppo"]] = groups.get(c["gruppo"], 0) + 1
|
||||
status = {**bundle.get("font_load_status", {}), **ext.get("font_load_status", {})}
|
||||
return {
|
||||
"test_page": "index.html",
|
||||
"font_source": "bundle",
|
||||
"text": bundle["text"],
|
||||
"firefox": bundle["firefox"],
|
||||
"canvas": bundle["canvas"],
|
||||
"cleartype": bundle["cleartype"],
|
||||
"fonts": ext["fonts"],
|
||||
"font_load_status": status,
|
||||
"case_count": len(cases),
|
||||
"groups": dict(sorted(groups.items())),
|
||||
"cases": cases,
|
||||
}
|
||||
|
||||
|
||||
def main(argv):
|
||||
ap = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("bundle", help="refs.json of the base measurement (canvas_ref_bundle)")
|
||||
ap.add_argument("ext", help="refs.json of the extension measurement (canvas_ref_ext)")
|
||||
ap.add_argument("--out", default=str(DEFAULT_OUT))
|
||||
a = ap.parse_args(argv[1:])
|
||||
load = lambda p: json.loads(Path(p).read_text(encoding="utf-8"))
|
||||
try:
|
||||
refs = merge(load(a.bundle), load(a.ext))
|
||||
except MergeError as e:
|
||||
print("error: %s" % e, file=sys.stderr)
|
||||
return 1
|
||||
Path(a.out).write_text(json.dumps(refs, ensure_ascii=False, indent=1) + "\n",
|
||||
encoding="utf-8")
|
||||
print("%d cases -> %s" % (refs["case_count"], a.out))
|
||||
for g, n in refs["groups"].items():
|
||||
print(" %-30s %3d" % (g, n))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -60,9 +60,31 @@ Exit 0 + "DRIVE GATE OK ..." on success; non-zero with a reason on failure.
|
||||
from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import json
|
||||
import shutil
|
||||
import socketserver
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
# ⛔ THE FIRST RUN IS DECLARED HERE, A COPY OF THE CORE'S, written into the
|
||||
# profile's user.js. Since firefox-55 the engine leaves Mozilla's first-run
|
||||
# lines and invisible_core declares the state (terms of use accepted long ago,
|
||||
# pre-onboarding off). This job installs only Playwright, so nothing declared
|
||||
# it: measured 2026-11-02 on run 41388672849, Windows showed the terms-of-use
|
||||
# modal ("the page did not handle mouse event") and Linux opened
|
||||
# https://www.mozilla.org/en-US/privacy/firefox/ in a second tab (the legacy
|
||||
# data-reporting flow) ("Unexpected number of tabs in the new window: 2").
|
||||
# Upstream Playwright sends its own defaults in Browser.enable, which this
|
||||
# engine refuses, so a raw launch runs on Mozilla's lines alone. With these
|
||||
# three in user.js, both legs drive. tests/test_ci_drive_gate_first_run.py
|
||||
# ties the copy to the core.
|
||||
FIRST_RUN = {
|
||||
"browser.preonboarding.enabled": False,
|
||||
"termsofuse.acceptedVersion": 4,
|
||||
"termsofuse.acceptedDate": "1785573000000",
|
||||
}
|
||||
|
||||
HTML = (
|
||||
"<!doctype html><html><head><title>dt</title></head><body>"
|
||||
@@ -135,10 +157,16 @@ def _drive(exe: str, url: str, level: str) -> str:
|
||||
full = level == "full"
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
# A user.js is read at startup, before the window that would carry the
|
||||
# modal; a persistent context is the only way to hand Playwright a profile.
|
||||
profile_dir = Path(tempfile.mkdtemp(prefix="ci-drive-gate-"))
|
||||
(profile_dir / "user.js").write_bytes(
|
||||
"".join("user_pref(%s, %s);\n" % (json.dumps(k), json.dumps(v))
|
||||
for k, v in sorted(FIRST_RUN.items())).encode("utf-8"))
|
||||
with sync_playwright() as p:
|
||||
browser = p.firefox.launch(executable_path=exe, headless=True)
|
||||
ctx = p.firefox.launch_persistent_context(str(profile_dir), executable_path=exe, headless=True)
|
||||
try:
|
||||
page = browser.new_page()
|
||||
page = ctx.new_page()
|
||||
resp = page.goto(url, wait_until="load")
|
||||
assert resp and resp.ok, f"navigation to {url} failed: {resp.status if resp else 'no response'}"
|
||||
ua = page.evaluate("() => navigator.userAgent")
|
||||
@@ -163,7 +191,8 @@ def _drive(exe: str, url: str, level: str) -> str:
|
||||
inter["langs"] = page.evaluate("() => navigator.languages.length")
|
||||
inter["plugins"] = page.evaluate("() => navigator.plugins instanceof PluginArray")
|
||||
finally:
|
||||
browser.close()
|
||||
ctx.close()
|
||||
shutil.rmtree(profile_dir, ignore_errors=True)
|
||||
|
||||
# SMOKE asserts (always).
|
||||
assert "Firefox" in ua, f"unexpected UA (binary not driving correctly): {ua!r}"
|
||||
@@ -171,7 +200,7 @@ def _drive(exe: str, url: str, level: str) -> str:
|
||||
assert not webdriver, f"navigator.webdriver leaked True (stealth regression): {webdriver!r}"
|
||||
|
||||
if interacts:
|
||||
assert inter["clicked"] == 1, "page.click() did not fire the click listener - mouse-event synthesis broken (firefox-2 class), or a chrome overlay is swallowing input (terms-of-use modal: see browser/app/profile/firefox.js, termsofuse.acceptedDate)"
|
||||
assert inter["clicked"] == 1, "page.click() did not fire the click listener - mouse-event synthesis broken (firefox-2 class), or a chrome overlay is swallowing input (terms-of-use modal: see FIRST_RUN above)"
|
||||
assert inter["moves"] >= 1, "page.mouse.move() produced no mousemove - jugglerSendMouseEvent regression, or a chrome overlay is swallowing input"
|
||||
if full:
|
||||
assert inter["typed"] == "ok", f"page.keyboard.type() failed: {inter['typed']!r}"
|
||||
|
||||
@@ -1,417 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""CI font gate - assert the patched binary exposes exactly the Windows font
|
||||
persona on EVERY host OS (Windows / Linux / macOS), with zero host-font leak.
|
||||
|
||||
The patched binary is bundle-only: at font-list construction it drops every host
|
||||
system font and exposes only the bundled Windows-11 family set (the exposed set
|
||||
IS the bundle). This gate launches the binary on its NATIVE runner - so
|
||||
macOS/CoreText, Linux/fontconfig and Windows/DWrite are each tested for real -
|
||||
enumerates the visible families with the same width-probe web detectors use, and
|
||||
asserts three things:
|
||||
|
||||
1. the detected family set == the canonical Windows set (EXPECTED): the SAME
|
||||
set on all three platforms. A leaked host font or a missing Windows one
|
||||
fails here. This is the "identical on every OS" contract.
|
||||
2. no known host family is visible (macOS: Helvetica Neue / Geneva / Menlo ...;
|
||||
Linux: DejaVu / Ubuntu ...) - a POSITIVE proof that block-at-birth ran for
|
||||
this platform's backend, not just "no obvious tell".
|
||||
3. the CSS generics resolve to Windows fonts (serif=Times New Roman,
|
||||
sans-serif=Arial, monospace=Consolas) and system-ui=Segoe UI.
|
||||
|
||||
This is the macOS validator the local Win/Linux gate cannot be - there is no
|
||||
local Mac, so CoreText is only ever exercised here. Headless, no proxy, no
|
||||
secrets, loopback-free (about:blank + arrow-function evaluate, which is not
|
||||
eval and carries no CSP problem) -> safe in public CI.
|
||||
|
||||
Usage: python ci_font_gate.py <firefox-binary>
|
||||
Exit 0 + "FONT GATE OK ..." on success; non-zero + the diff on failure.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
# The canonical Windows-11 family set the bundle exposes. Verified byte-for-byte
|
||||
# identical on Windows/DWrite and Linux/fontconfig; macOS/CoreText must match it
|
||||
# too. These are the `F|` records that `invisible_core` declares.
|
||||
#
|
||||
# ⛔ THIS IS A LITERAL, and the reason is NOT laziness: verified 2026-08-17 by
|
||||
# reading the workflow that runs it. The font gate runs inside `release.yml`
|
||||
# of the SOURCE repo, in a job that checks out THIS repo but installs only
|
||||
# `playwright==...` and nothing else. Deriving it from `invisible_core` is the
|
||||
# form rule 16 asks for, was written and tried, works locally, and kills EVERY
|
||||
# release with an ImportError.
|
||||
#
|
||||
# And there is a second reason, which survives even if that job someday
|
||||
# installed the core: when the pipeline runs, the PUBLISHED core is still the
|
||||
# one from the previous release, because the core is published AFTER the
|
||||
# binary exists (17-release-seal-spec.md §9). Deriving from there would
|
||||
# measure the new binary against the old declaration.
|
||||
#
|
||||
# What keeps the literal honest is not the attention of whoever edits it: it
|
||||
# is `test_the_family_list_in_the_gate_matches_the_core_manifest`, in
|
||||
# `tests/test_ci_font_gate_declaration.py` of this repo, where the core IS
|
||||
# present. That test did not exist: it was DOCUMENTED as existing and nothing
|
||||
# more, and that is exactly why the list was able to stay at 68 while the
|
||||
# manifest moved to 71 (the two icon Segoes plus Twemoji Mozilla).
|
||||
#
|
||||
# ⛔ AND THE DRIFT DOES NOT GIVE A RED, IT GIVES A GREEN: measured 2026-08-17
|
||||
# on the real binary. The probe queries `EXPECTED + HOST_MUST_BE_ABSENT` and
|
||||
# nothing else, so a family removed from here also stops being LOOKED FOR:
|
||||
# with the three missing, the gate printed `detected 68 families (expected
|
||||
# 68)` and `FONT GATE OK`, exit 0, on a binary that exposes 71. A gate that
|
||||
# agrees with itself cannot see its own drift.
|
||||
EXPECTED = [
|
||||
"Arial", "Bahnschrift", "Calibri", "Cambria", "Cambria Math", "Candara",
|
||||
"Comic Sans MS", "Consolas", "Constantia", "Corbel", "Courier New",
|
||||
"Ebrima", "Franklin Gothic", "Gabriola", "Gadugi", "Georgia", "Impact",
|
||||
"Ink Free", "Javanese Text", "Leelawadee", "Leelawadee UI",
|
||||
"Lucida Console", "Lucida Sans Unicode", "MS Gothic", "MS PGothic",
|
||||
"MS UI Gothic", "MV Boli", "Malgun Gothic", "Marlett",
|
||||
"Microsoft Himalaya", "Microsoft JhengHei", "Microsoft JhengHei UI",
|
||||
"Microsoft New Tai Lue", "Microsoft PhagsPa", "Microsoft Sans Serif",
|
||||
"Microsoft Tai Le", "Microsoft Uighur", "Microsoft YaHei",
|
||||
"Microsoft YaHei UI", "Microsoft Yi Baiti", "MingLiU-ExtB",
|
||||
"Mongolian Baiti", "Myanmar Text", "NSimSun", "Nirmala UI",
|
||||
"PMingLiU-ExtB", "Palatino Linotype", "Segoe Fluent Icons",
|
||||
"Segoe MDL2 Assets", "Segoe Print", "Segoe Script", "Segoe UI",
|
||||
"Segoe UI Emoji", "Segoe UI Historic", "Segoe UI Symbol", "SimSun",
|
||||
"SimSun-ExtB", "Sitka Small", "Sylfaen", "Symbol", "Tahoma",
|
||||
"Times New Roman", "Trebuchet MS", "Twemoji Mozilla", "Verdana",
|
||||
"Webdings", "Wingdings", "Wingdings 2", "Wingdings 3", "Yu Gothic",
|
||||
"Yu Gothic UI",
|
||||
]
|
||||
|
||||
# Host families that must NEVER be visible - one per backend. Their presence is a
|
||||
# hard fail (block-at-birth did not run for this OS). These are decoys added to
|
||||
# the probe list; they must all come back absent.
|
||||
HOST_MUST_BE_ABSENT = [
|
||||
# macOS / CoreText
|
||||
"Helvetica Neue", "Geneva", "Menlo", "Monaco", "Avenir", "Lucida Grande",
|
||||
"Apple SD Gothic Neo", "PingFang SC",
|
||||
# Linux / fontconfig
|
||||
"DejaVu Sans", "Liberation Sans", "Ubuntu", "Nimbus Sans", "Noto Sans",
|
||||
# Office / non-standard families intentionally dropped from the bundle
|
||||
"Century Gothic", "Agency FB", "Monotype Corsiva", "Pristina",
|
||||
]
|
||||
|
||||
# CSS generic -> the Windows family it must resolve to under bundle-only.
|
||||
GENERICS = {
|
||||
"serif": "Times New Roman",
|
||||
"sans-serif": "Arial",
|
||||
"monospace": "Consolas",
|
||||
"system-ui": "Segoe UI",
|
||||
}
|
||||
|
||||
# Families that live inside a .ttc TrueType Collection (several faces packed in
|
||||
# one file). Being *listed* is not enough: without a per-face index the table
|
||||
# lookup reads the first font of the collection, so every other face silently
|
||||
# falls back to a default one. That is invisible to the presence probe below
|
||||
# (the family is registered either way) but wrecks the persona for CJK text.
|
||||
# The FF150->151 rebase dropped exactly that fix and only 7 of these loaded.
|
||||
#
|
||||
# Calibrated on firefox-17, the known-good release: these are the families that
|
||||
# demonstrably render the CJK sample with their own face there. Deliberately
|
||||
# NOT listed: "SimSun-ExtB" (covers Unicode Ext-B, not the BMP characters in
|
||||
# the sample, so it legitimately falls back) and the "... UI" variants of YaHei
|
||||
# and JhengHei (they already fall back on firefox-17, so requiring them would
|
||||
# fail the known-good build). Keep this list as a regression detector, not an
|
||||
# aspiration: everything here loads on firefox-17 and must keep loading.
|
||||
#: A fixed seed, because the declared metrics depend on the profile and a
|
||||
#: gate that changes numbers on every run is not a gate.
|
||||
_SEED = 970411
|
||||
|
||||
#: COPY of zoom.stealth.fonts.generics as invisible_core declares it.
|
||||
#: Constant across seeds (verified on 5). Tied to the core by the test
|
||||
#: test_ci_font_gate_generics_match_the_core, which turns red if they diverge.
|
||||
GENERICS_DECL = (
|
||||
"cursive||Comic Sans MS\n"
|
||||
"serif|x-math|Cambria Math\n"
|
||||
"sans-serif|ja|Yu Gothic UI\n"
|
||||
"serif|ja|Yu Gothic UI\n"
|
||||
"monospace|ja|Yu Gothic UI\n"
|
||||
"sans-serif|ko|Malgun Gothic\n"
|
||||
"serif|ko|Malgun Gothic\n"
|
||||
"monospace|ko|Malgun Gothic\n"
|
||||
"sans-serif|zh-CN|Microsoft YaHei UI\n"
|
||||
"serif|zh-CN|Microsoft YaHei UI\n"
|
||||
"monospace|zh-CN|Microsoft YaHei UI\n"
|
||||
"sans-serif|zh-TW|Microsoft JhengHei UI\n"
|
||||
"serif|zh-TW|Microsoft JhengHei UI\n"
|
||||
"monospace|zh-TW|Microsoft JhengHei UI\n"
|
||||
"sans-serif|zh-HK|Microsoft JhengHei UI\n"
|
||||
"serif|zh-HK|Microsoft JhengHei UI\n"
|
||||
"monospace|zh-HK|Microsoft JhengHei UI\n"
|
||||
"serif||Times New Roman\n"
|
||||
"sans-serif||Arial\n"
|
||||
"monospace||Consolas"
|
||||
)
|
||||
|
||||
|
||||
|
||||
TTC_FAMILIES = [
|
||||
"Microsoft YaHei", "Microsoft YaHei UI",
|
||||
"Microsoft JhengHei", "Microsoft JhengHei UI",
|
||||
"MS Gothic", "MS PGothic", "MS UI Gothic",
|
||||
"SimSun", "NSimSun",
|
||||
"Yu Gothic", "Yu Gothic UI", "Malgun Gothic",
|
||||
"MingLiU-ExtB", "PMingLiU-ExtB",
|
||||
]
|
||||
|
||||
#: The families above grouped by FACE, measured from the ink box. This is the
|
||||
#: invariant the check rests on, and it says two things at once: that every
|
||||
#: face loads (a face that does not load falls into the fallback group, and
|
||||
#: the grouping changes) and that the two platforms answer the same way (the
|
||||
#: values are identical, not just the groups).
|
||||
#:
|
||||
#: The FALLBACK group contains YaHei because YaHei IS the CJK fallback face -
|
||||
#: measured at the pixel level: asking for a nonexistent font produces exactly
|
||||
#: its glyphs. MingLiU-ExtB and PMingLiU-ExtB sit there for a different and
|
||||
#: equally correct reason: they are Extension-B fonts and their cmap does NOT
|
||||
#: cover any of the probe's characters, so the fallback draws as it should.
|
||||
#: The old check asked "does this family measure differently from NO font?"
|
||||
#: and on these four it answered no, deducing that the face had not loaded:
|
||||
#: the question was ill-posed, because the fallback face is itself one of the
|
||||
#: bundled families.
|
||||
EXPECTED_FACE_GROUPS = [
|
||||
# The FALLBACK group. Contains YaHei because YaHei IS the CJK fallback
|
||||
# face, measured at the pixel level: asking for a nonexistent font
|
||||
# produces exactly its glyphs. MingLiU-ExtB and PMingLiU-ExtB sit here for
|
||||
# a different and equally correct reason: they are Extension-B faces and
|
||||
# their cmap does not cover ANY of the probe's characters (verified by
|
||||
# reading the cmap of the bundled files), so the fallback draws as it
|
||||
# should.
|
||||
{"Microsoft YaHei", "Microsoft YaHei UI", "MingLiU-ExtB",
|
||||
"PMingLiU-ExtB", "__NoSuchFontXYZ__"},
|
||||
{"Microsoft JhengHei", "Microsoft JhengHei UI"},
|
||||
{"SimSun", "NSimSun"},
|
||||
{"MS Gothic"},
|
||||
{"MS PGothic"},
|
||||
{"MS UI Gothic"},
|
||||
{"Yu Gothic"},
|
||||
{"Yu Gothic UI"},
|
||||
{"Malgun Gothic"},
|
||||
]
|
||||
|
||||
# Width+height probe (the offsetWidth method real detectors use): a family is
|
||||
# "present" if styling text in it renders at a different size than the three CSS
|
||||
# base generics. For the generics, return the measured size of each generic and
|
||||
# of its target Windows family so the caller can assert they coincide.
|
||||
DETECT_JS = r"""(arg) => {
|
||||
const bases = ['monospace', 'sans-serif', 'serif'];
|
||||
const sample = 'mmmmmmmmmmlli WwQ 0123456789 gjpqy';
|
||||
const sp = document.createElement('span');
|
||||
sp.style.cssText =
|
||||
'position:absolute;left:-9999px;font-size:72px;white-space:nowrap;';
|
||||
sp.textContent = sample;
|
||||
document.body.appendChild(sp);
|
||||
const size = (ff) => { sp.style.fontFamily = ff; return sp.offsetWidth + 'x' + sp.offsetHeight; };
|
||||
const bw = {};
|
||||
for (const b of bases) bw[b] = size(b);
|
||||
const present = {};
|
||||
for (const f of arg.cands) {
|
||||
present[f] = bases.some((b) => size("'" + f + "'," + b) !== bw[b]);
|
||||
}
|
||||
const gen = {};
|
||||
for (const g of arg.generics) gen[g] = size(g);
|
||||
const genref = {};
|
||||
for (const w of arg.targets) genref[w] = size("'" + w + "'");
|
||||
// The INK box of measureText for a CJK string, family by family. Not the
|
||||
// pixels and not the line height, for two measured reasons:
|
||||
// - line height is a value WE DECLARE, so different families can
|
||||
// legitimately share it and the comparison stops distinguishing
|
||||
// anything;
|
||||
// - the pixels of a canvas with text are not readable on Linux (entry
|
||||
// 2026-08-11 in 70-known-bugs.md).
|
||||
// The ink box is geometry derived from the glyphs: measured 2026-08-11 it
|
||||
// is identical to the third digit between Windows and Linux.
|
||||
const c = document.createElement('canvas');
|
||||
const cx = c.getContext('2d');
|
||||
const inkbox = {};
|
||||
for (const f of arg.ttc.concat(['__NoSuchFontXYZ__'])) {
|
||||
cx.font = "56px '" + f + "', '__NoSuchFontXYZ__'";
|
||||
const m = cx.measureText(arg.cjk);
|
||||
inkbox[f] = [m.width, m.actualBoundingBoxAscent, m.actualBoundingBoxDescent,
|
||||
m.actualBoundingBoxLeft, m.actualBoundingBoxRight]
|
||||
.map((v) => Math.round(v * 1000) / 1000).join('|');
|
||||
}
|
||||
document.body.removeChild(sp);
|
||||
return { present, gen, genref, inkbox };
|
||||
}"""
|
||||
|
||||
# ⛔ FOUR PREFS THAT DISABLED THE NEWTAB USED TO SIT HERE, removed 2026-08-20
|
||||
# with the newtab revert, for the same reason as `ci_drive_gate.py`: the
|
||||
# product no longer ships them, and a bench that runs in a configuration
|
||||
# different from what ships measures a different thing.
|
||||
#
|
||||
# The comment used to say "mirrors ci_drive_gate", and that was already false:
|
||||
# it was FOUR here against SIX there, diverged who knows since when. This
|
||||
# removal closes the defect at its root instead of realigning it: now there is
|
||||
# no list to keep in sync, because there is no list at all.
|
||||
#
|
||||
# The race these prefs meant to avoid no longer exists anywhere: it was not
|
||||
# Fission, it was the preallocated new-tab browser grabbing the page's
|
||||
# channel, and it has been fixed in the engine since 2026-08-23
|
||||
# (`20-our-patches.md` §5.2w). No gate waits on anything anymore.
|
||||
_PREFS: dict = {}
|
||||
|
||||
|
||||
# ── The structural limit of this gate, measured and not inferred ─────────
|
||||
#
|
||||
# A page cannot ENUMERATE the system fonts: it can only ask name by name. So
|
||||
# the probe queries `EXPECTED + HOST_MUST_BE_ABSENT` and nothing else, and
|
||||
# from that follows something that needs to be said rather than discovered:
|
||||
# **a family removed from EXPECTED also stops being LOOKED FOR**, so the count
|
||||
# comes out even and the gate passes. Verified 2026-08-11 as a mutation:
|
||||
# deleting "Georgia" from the list, the gate answered "detected 67 families
|
||||
# (expected 67)" and OK.
|
||||
#
|
||||
# It cannot be fixed from the inside: it is the reason the list exists. The
|
||||
# practical consequence is that HOST_MUST_BE_ABSENT must stay GENEROUS,
|
||||
# because it is the only place from which the discovery of an unexpected host
|
||||
# font can arrive. A name that is in neither list is invisible to this gate
|
||||
# by construction.
|
||||
|
||||
|
||||
def main(exe: str) -> int:
|
||||
|
||||
cands = EXPECTED + HOST_MUST_BE_ABSENT
|
||||
arg = {
|
||||
"cands": cands,
|
||||
"generics": list(GENERICS.keys()),
|
||||
"targets": list(GENERICS.values()),
|
||||
"ttc": TTC_FAMILIES,
|
||||
"cjk": "中文字体測試あア漢字",
|
||||
}
|
||||
# RAW launch, and a hand-delivered declaration. The CI gate job installs
|
||||
# only Playwright: invisible_core is not there and cannot be without
|
||||
# changing the workflow, i.e. without rebuilding the five archives.
|
||||
#
|
||||
# The only thing missing from a rawly-launched engine is the generics map.
|
||||
# Measured 2026-08-11 on the same binary: without it,
|
||||
# serif/sans-serif/monospace/cursive/fantasy ALL collapse onto Arial on
|
||||
# Linux (not on Windows, because there Gecko's defaults happen to coincide
|
||||
# with the persona we declare); with it, they map onto Times New Roman,
|
||||
# Arial, Consolas and Comic Sans on BOTH, with the same numbers.
|
||||
#
|
||||
# GENERICS_DECL below is a COPY of what invisible_core declares, and it is
|
||||
# the only one in the project. It cannot diverge silently: it is tied by
|
||||
# the test test_ci_font_gate_generics_match_the_core, which compares this
|
||||
# string against the one the core produces and turns red if they part
|
||||
# ways.
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
prefs = dict(_PREFS)
|
||||
prefs["zoom.stealth.fonts.generics"] = GENERICS_DECL
|
||||
|
||||
# ⛔ Prefs are written into the PROFILE, not sent over the protocol.
|
||||
# Through firefox-20 this was `launch(firefox_user_prefs=prefs)`, which
|
||||
# Playwright delivers to the browser inside `Browser.enable` - i.e. AFTER
|
||||
# startup. From firefox-21 the engine REFUSES it instead of applying it
|
||||
# late:
|
||||
#
|
||||
# Browser.enable no longer applies preferences. They are written into
|
||||
# the profile before startup...
|
||||
#
|
||||
# and that is the right refusal. Applying them after startup means the
|
||||
# first launch initializes gfx and fonts with the defaults and the second
|
||||
# with the prefs active: two different paths, which are the cause of
|
||||
# [B150]. And ignoring them would be worse - a browser without the prefs
|
||||
# the caller believes it set, and no error.
|
||||
#
|
||||
# A `user.js` in the profile is read at STARTUP, so the generics map is
|
||||
# already there when gfx initializes: a single path.
|
||||
profile_dir = Path(tempfile.mkdtemp(prefix="ci-font-gate-"))
|
||||
(profile_dir / "user.js").write_bytes(
|
||||
("".join("user_pref(%s, %s);\n" % (json.dumps(k), json.dumps(v))
|
||||
for k, v in sorted(prefs.items()))).encode("utf-8"))
|
||||
with sync_playwright() as p:
|
||||
ctx = p.firefox.launch_persistent_context(
|
||||
str(profile_dir), executable_path=exe, headless=True)
|
||||
try:
|
||||
page = ctx.new_page()
|
||||
page.goto("about:blank")
|
||||
r = page.evaluate(DETECT_JS, arg)
|
||||
finally:
|
||||
ctx.close()
|
||||
shutil.rmtree(profile_dir, ignore_errors=True)
|
||||
|
||||
detected = {f for f, v in r["present"].items() if v}
|
||||
expected = set(EXPECTED)
|
||||
missing = sorted(expected - detected)
|
||||
# Anything detected that isn't in EXPECTED (host leaks land here too).
|
||||
extra = sorted(detected - expected)
|
||||
leaked_host = [h for h in HOST_MUST_BE_ABSENT if r["present"].get(h)]
|
||||
gen_bad = []
|
||||
for g, want in GENERICS.items():
|
||||
got, ref = r["gen"].get(g), r["genref"].get(want)
|
||||
if got != ref:
|
||||
gen_bad.append(f"{g} -> {got} (expected {want} = {ref})")
|
||||
|
||||
n = len(detected)
|
||||
print(f"[font-gate] {exe}")
|
||||
print(f"[font-gate] detected {n} families (expected {len(EXPECTED)})")
|
||||
if missing:
|
||||
print(f"[font-gate] MISSING (in bundle, not exposed): {missing}")
|
||||
if extra:
|
||||
print(f"[font-gate] UNEXPECTED (exposed, not in canonical set): {extra}")
|
||||
if leaked_host:
|
||||
print(f"[font-gate] HOST LEAK (block-at-birth did not run!): {leaked_host}")
|
||||
if gen_bad:
|
||||
print(f"[font-gate] GENERIC MISMATCH: {gen_bad}")
|
||||
# The face groups, measured now, against the expected ones. A grouping
|
||||
# that changes says a face fell into the fallback; a VALUE that changes
|
||||
# says the declared metrics have shifted, or that the two platforms no
|
||||
# longer answer the same way. These are two different defects and the
|
||||
# message keeps them apart.
|
||||
ink = r.get("inkbox", {})
|
||||
seen = {}
|
||||
for fam, box in ink.items():
|
||||
seen.setdefault(box, []).append(fam)
|
||||
# The STRUCTURE is compared - which families share a face - not the
|
||||
# values. The values are identical between Windows and Linux only when the
|
||||
# browser receives all its declarations, and this gate launches it raw
|
||||
# because the CI job has no invisible_core: on a raw launch Linux returns
|
||||
# integer bounds (FreeType's grid-fit) while Windows returns fractions.
|
||||
# The structure coincides instead, and it is what answers the question
|
||||
# "did this face load?" - a face that does not load FALLS into the
|
||||
# fallback group and the grouping changes. Cross-OS parity of the values
|
||||
# is a different check, one that has to be done under the wrapper where
|
||||
# all the declarations are present.
|
||||
measured = [set(f) for f in seen.values()]
|
||||
face_bad = []
|
||||
for expected_group in EXPECTED_FACE_GROUPS:
|
||||
if expected_group not in measured:
|
||||
nearest = max(measured, key=lambda g: len(g & expected_group), default=set())
|
||||
face_bad.append(f"expected group {sorted(expected_group)} not found; "
|
||||
f"the closest measured is {sorted(nearest)}")
|
||||
for g in measured:
|
||||
if g not in EXPECTED_FACE_GROUPS:
|
||||
face_bad.append(f"unexpected group: {sorted(g)}")
|
||||
if face_bad:
|
||||
print("[font-gate] FACES: the grouping is not the expected one")
|
||||
for line in face_bad:
|
||||
print(f"[font-gate] {line}")
|
||||
|
||||
ok = (not missing and not extra and not leaked_host and not gen_bad
|
||||
and not face_bad)
|
||||
if ok:
|
||||
print(f"FONT GATE OK - exactly the {n} Windows families, host-leak 0, "
|
||||
f"generics map to Windows (serif/sans/mono/system-ui), "
|
||||
f"{len(EXPECTED_FACE_GROUPS)} face groups over "
|
||||
f"{len(TTC_FAMILIES)} CJK families (every declared face draws "
|
||||
f"its own glyphs).")
|
||||
return 0
|
||||
print("FONT GATE FAILED - the exposed set does not match the Windows "
|
||||
"persona on this OS (see the diff above).")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) < 2:
|
||||
print("usage: python ci_font_gate.py <firefox-binary>", file=sys.stderr)
|
||||
raise SystemExit(2)
|
||||
raise SystemExit(main(sys.argv[1]))
|
||||
@@ -0,0 +1,606 @@
|
||||
#!/usr/bin/env python3
|
||||
"""CI host gate: what a page reads is a function of the declared identity and of
|
||||
Firefox's code, never of the machine the browser runs on.
|
||||
|
||||
Two properties follow, and they are checked for every value the page dumps
|
||||
(whole APIs, not a hand-picked list), so the gate needs no knowledge of where
|
||||
the next leak will be:
|
||||
|
||||
1. HOST-INDEPENDENCE. The same identity on different hosts (the Windows and
|
||||
Linux x86_64 legs) gives the same bytes.
|
||||
2. RETAIL EQUALITY. A value that does not depend on the identity equals what
|
||||
retail Firefox for Windows answers on the same page, at the same device
|
||||
pixel ratio.
|
||||
|
||||
Values are compared leaf by leaf: an object the page reads (navigator, screen)
|
||||
mixes fields the identity decides with fields it does not, and each is held to
|
||||
its own property.
|
||||
|
||||
Which values depend on the identity is measured AND declared. Each leg visits
|
||||
the page with several seeds at a fixed DPR; a value that changes with the seed
|
||||
depends on the identity and is held to property 1 only. A value the identity
|
||||
decides can still come out the same for every seed (16 cores, a 1920x1080
|
||||
screen), so those are declared as well.
|
||||
|
||||
The only exceptions live in host_gate/exceptions.json, each with its reason:
|
||||
- identity: values the declared identity decides; exempt from property 2,
|
||||
never from property 1;
|
||||
- noise: values that differ between two launches of retail itself;
|
||||
- network: values the identity takes from the network (language and zone
|
||||
from the egress IP), which CI without a proxy cannot reproduce;
|
||||
- measurement: values that record how the reference was taken rather than
|
||||
what Firefox answers (focus, on the hidden desktop retail ran on);
|
||||
- known_defects: open divergences with the work that closes them. This list
|
||||
only shrinks: an entry that no longer matches a difference fails the gate,
|
||||
so it is removed when its fix lands.
|
||||
|
||||
Values under the diag. prefix are not held to either property. They are
|
||||
information the page records about the host (diag.webgl: whether WebGL2 and
|
||||
multisampling exist there and, when not, the message Firefox gives): the legs
|
||||
legitimately differ on them and the retail reference does not record them.
|
||||
compare() skips them by name; dump() prints them into the job log, so a run
|
||||
tells why without its artifacts being downloaded.
|
||||
|
||||
Values under the state. prefix are the window in the states a page can drive
|
||||
it to: state.normal, state.fullscreen (entered through a real click, a user
|
||||
gesture) and state.after_fullscreen. The dump measures them after the page is
|
||||
done (drive_states). Besides the two properties they are held to INVARIANTS:
|
||||
relations between values that hold on every host, for every identity and
|
||||
whatever the reference says, because a window that breaks them cannot exist
|
||||
(an outer window smaller than its viewport, a fullscreen window off the
|
||||
screen's origin). Each value can look plausible on its own; only the relation
|
||||
shows the defect, so these are checked even where nothing else is.
|
||||
|
||||
This replaces ci_font_gate.py, which checked one surface (the font list) of
|
||||
the same rule.
|
||||
|
||||
python ci_host_gate.py dump <firefox> --leg linux-x86_64 --out dumps/
|
||||
python ci_host_gate.py compare dumps/ (reference: host_gate/reference/firefox-159)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import fnmatch
|
||||
import gzip
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from typing import Callable, NamedTuple
|
||||
|
||||
HERE = Path(__file__).resolve().parent / "host_gate"
|
||||
PAGE = HERE / "host_gate_page.html"
|
||||
EXCEPTIONS = HERE / "exceptions.json"
|
||||
REFERENCE = HERE / "reference" / "firefox-159"
|
||||
FORMAT = "host-gate/1"
|
||||
|
||||
#: DPRs the reference is recorded at, and the seeds visited at each. Three seeds
|
||||
#: so that a value that depends on the identity is very unlikely to look
|
||||
#: constant by chance.
|
||||
DPRS = (1.0, 1.5)
|
||||
SEEDS = (11, 12, 13)
|
||||
|
||||
#: The leg every other leg is compared with: the platform the identity claims.
|
||||
ANCHOR = "win-x86_64"
|
||||
|
||||
#: Keys under this prefix are information, never compared (see the module docstring).
|
||||
DIAG = "diag."
|
||||
|
||||
|
||||
def is_diag(key: str) -> bool:
|
||||
return key.startswith(DIAG)
|
||||
|
||||
|
||||
def diag_lines(items: dict, before: dict | None = None) -> list:
|
||||
"""The diag. leaves of one visit as 'key = value' lines; with before (an
|
||||
earlier visit's diag leaves), only the keys whose value changed."""
|
||||
now = {k: v for k, v in leaves(items).items() if is_diag(k)}
|
||||
lines = [" %s = %s" % (k, json.dumps(v, sort_keys=True)) for k, v in now.items()
|
||||
if before is None or before.get(k, "<missing>") != v]
|
||||
return lines + [" %s = <missing>" % k for k in (before or {}) if k not in now]
|
||||
|
||||
|
||||
def diag_report(visit: str, items: dict, first: dict | None) -> list:
|
||||
"""What dump() prints for one visit: every diag. value on the leg's first
|
||||
visit (first is None), then only what changed from it."""
|
||||
if first is None:
|
||||
return ["diag %s:" % visit] + (diag_lines(items) or [" (the page recorded no diag. keys)"])
|
||||
changed = diag_lines(items, first)
|
||||
return ["diag %s: %s" % (visit, "changed from the first visit:" if changed else "as the first visit")] + changed
|
||||
|
||||
|
||||
# -
|
||||
# States: the window driven to fullscreen and back with real input, and the
|
||||
# relations its values must keep in every state.
|
||||
|
||||
STATE = "state."
|
||||
|
||||
#: The states drive_states measures, in the order it reaches them.
|
||||
STATES = ("normal", "fullscreen", "after_fullscreen")
|
||||
|
||||
#: How long the page waits for fullscreenchange before recording 'timeout'.
|
||||
STATE_TIMEOUT_MS = 5000
|
||||
|
||||
#: Retail equality for these namespaces waits for the reference to record them.
|
||||
#: The firefox-159 reference was taken before the dump drove any state, so it has
|
||||
#: no state.* key; until it has, a state.* value is held to host-independence and
|
||||
#: to INVARIANTS only, and compare() notes it. The session that produces the
|
||||
#: reference adds, to the items of each dpr<x>.json.gz, the three items
|
||||
#: state.normal, state.fullscreen and state.after_fullscreen, shaped exactly as
|
||||
#: drive_states returns them, by running drive_states on retail Firefox for
|
||||
#: Windows on this page with evaluate = run the expression in the page, and move
|
||||
#: and click = OS-level input at those viewport (CSS px) points, e.g. SendInput:
|
||||
#: a click a script dispatches is not a user gesture and requestFullscreen
|
||||
#: refuses it. From the first reference that has state.*, these values are
|
||||
#: compared with retail like every other; the window geometry is declared
|
||||
#: identity in exceptions.json, the rest (display-mode, fullscreenElement,
|
||||
#: window.fullScreen, how the transition went) is held to retail.
|
||||
REFERENCE_PENDING = (STATE,)
|
||||
|
||||
|
||||
def drive_states(evaluate: Callable, move: Callable, click: Callable,
|
||||
timeout_ms: int = STATE_TIMEOUT_MS) -> dict:
|
||||
"""The page's window in each of STATES, as items {state.<name>: values}.
|
||||
|
||||
evaluate runs an expression in the page and returns its (awaited) value;
|
||||
move and click are real input at a viewport point. In each state the mouse
|
||||
moves twice and clicks on the middle of the viewport, so every value of the
|
||||
state comes with the screen - client offsets of real mouse events.
|
||||
Fullscreen is entered by clicking the page's button (its handler calls
|
||||
requestFullscreen) and left with document.exitFullscreen(); each transition
|
||||
records how it ended (fullscreenchange, fullscreenerror, timeout). Whatever
|
||||
raises leaves {"error": ...} in the states not measured yet, which the
|
||||
'measured' invariant reports.
|
||||
"""
|
||||
states = {}
|
||||
|
||||
def measure(name, transition=None):
|
||||
evaluate("__hostGateStates.clear()")
|
||||
w, h = evaluate("[innerWidth, innerHeight]")
|
||||
x, y = w // 2, h // 2
|
||||
move(x - 20, y)
|
||||
move(x, y + 20)
|
||||
click(x, y + 20)
|
||||
values = evaluate("__hostGateStates.measure()")
|
||||
if transition is not None:
|
||||
values["transition"] = transition
|
||||
states[name] = values
|
||||
|
||||
try:
|
||||
button = evaluate("__hostGateStates.prepare()")
|
||||
measure("normal")
|
||||
evaluate("__hostGateStates.arm(%d)" % timeout_ms)
|
||||
click(button["x"], button["y"])
|
||||
measure("fullscreen", evaluate("__hostGateStates.wait()"))
|
||||
evaluate("__hostGateStates.leave(%d)" % timeout_ms)
|
||||
measure("after_fullscreen", evaluate("__hostGateStates.wait()"))
|
||||
except Exception as e: # noqa: BLE001 - recorded, and failed by the 'measured' invariant
|
||||
for name in STATES:
|
||||
states.setdefault(name, {"error": "%s: %s" % (type(e).__name__, str(e)[:300])})
|
||||
return {STATE + name: states[name] for name in STATES}
|
||||
|
||||
|
||||
#: What a state is made of; the screen is {width, height, availWidth, availHeight}.
|
||||
POSITION = ("innerWidth", "innerHeight", "outerWidth", "outerHeight", "screenX", "screenY",
|
||||
"mozInnerScreenX", "mozInnerScreenY", "screen")
|
||||
FIELDS = POSITION + ("display_mode_fullscreen", "fullscreen_element", "events")
|
||||
|
||||
|
||||
def _measured(s, states):
|
||||
if "error" in s:
|
||||
return "not measured: %s" % s["error"]
|
||||
missing = [f for f in FIELDS if f not in s]
|
||||
missing += ["%s as a number" % f for f in POSITION[:-1]
|
||||
if f in s and (isinstance(s[f], bool) or not isinstance(s[f], (int, float)))]
|
||||
if not isinstance(s.get("screen"), dict) or not {"width", "height", "availWidth", "availHeight"} <= set(s["screen"]):
|
||||
missing.append("screen.width/height/availWidth/availHeight")
|
||||
if not isinstance(s.get("events"), dict):
|
||||
missing.append("events as {type: [[dx, dy]]}")
|
||||
return missing and "not measured: no %s" % ", ".join(missing)
|
||||
|
||||
|
||||
def _transition(s, states):
|
||||
t = s.get("transition")
|
||||
if not isinstance(t, dict) or t.get("how") != "fullscreenchange" or not t.get("settled"):
|
||||
return "the transition did not complete: %s" % json.dumps(t, sort_keys=True)
|
||||
|
||||
|
||||
def _outer_holds_inner(s, states):
|
||||
bad = ["outer%s %s < inner%s %s" % (d, s["outer" + d], d, s["inner" + d])
|
||||
for d in ("Width", "Height") if s["outer" + d] < s["inner" + d]]
|
||||
return "; ".join(bad)
|
||||
|
||||
|
||||
def _is_the_screen(s, states):
|
||||
w, h = s["screen"]["width"], s["screen"]["height"]
|
||||
bad = ["%s %s" % (k, s[k]) for k, want in (("innerWidth", w), ("outerWidth", w),
|
||||
("innerHeight", h), ("outerHeight", h)) if s[k] != want]
|
||||
return bad and "%s, screen %sx%s (avail %sx%s)" % (", ".join(bad), w, h,
|
||||
s["screen"]["availWidth"], s["screen"]["availHeight"])
|
||||
|
||||
|
||||
def _at_origin(s, states):
|
||||
bad = ["%s %s" % (k, s[k]) for k in ("screenX", "screenY", "mozInnerScreenX", "mozInnerScreenY") if s[k] != 0]
|
||||
return ", ".join(bad)
|
||||
|
||||
|
||||
def _declares(fullscreen):
|
||||
def check(s, states):
|
||||
bad = ["%s %s" % (k, json.dumps(s[k])) for k in ("display_mode_fullscreen", "fullscreen_element")
|
||||
if s[k] is not fullscreen]
|
||||
return ", ".join(bad)
|
||||
return check
|
||||
|
||||
|
||||
def _offset_matches(offset, inner_screen):
|
||||
# MouseEvent.screenX and clientX are each rounded to a whole CSS px, while
|
||||
# mozInnerScreenX is the viewport's exact offset, fractional when the DPR
|
||||
# does not divide the window's device position (85.33 at 1.5): the
|
||||
# difference of the two rounded values is then within 1 px of it. A whole
|
||||
# offset has nothing to round and must match exactly.
|
||||
if float(inner_screen).is_integer():
|
||||
return offset == inner_screen
|
||||
return abs(offset - inner_screen) <= 1
|
||||
|
||||
|
||||
def _events_at_inner_screen(s, states):
|
||||
if not any(s["events"].values()):
|
||||
return "no mouse event was recorded"
|
||||
inner = (s["mozInnerScreenX"], s["mozInnerScreenY"])
|
||||
bad = ["%s (%s, %s)" % (typ, dx, dy) for typ, pairs in sorted(s["events"].items()) for dx, dy in pairs
|
||||
if not (_offset_matches(dx, inner[0]) and _offset_matches(dy, inner[1]))]
|
||||
return bad and "screen - client of %s, mozInnerScreen (%s, %s)" % (", ".join(bad), inner[0], inner[1])
|
||||
|
||||
|
||||
def _screen_stays(s, states):
|
||||
normal = states.get("normal")
|
||||
if not isinstance(normal, dict) or not isinstance(normal.get("screen"), dict):
|
||||
return None # the normal state's own 'measured' failure says why
|
||||
bad = ["screen.%s %s (normal %s)" % (k, s["screen"][k], normal["screen"].get(k))
|
||||
for k in ("width", "height") if s["screen"][k] != normal["screen"].get(k)]
|
||||
return ", ".join(bad)
|
||||
|
||||
|
||||
def _back_to_normal(s, states):
|
||||
normal = states.get("normal")
|
||||
if not isinstance(normal, dict) or _measured(normal, states):
|
||||
return None # the normal state's own 'measured' failure says why
|
||||
bad = ["%s %s (normal %s)" % (k, json.dumps(s[k]), json.dumps(normal[k])) for k in POSITION if s[k] != normal[k]]
|
||||
return ", ".join(bad)
|
||||
|
||||
|
||||
class Invariant(NamedTuple):
|
||||
name: str
|
||||
states: tuple
|
||||
check: Callable # (state values, every state's values) -> failure message, or a false value
|
||||
why: str
|
||||
|
||||
|
||||
#: Every relation the states are held to, the only place they are declared.
|
||||
#: 'measured' runs first: the others assume the state's fields are there.
|
||||
INVARIANTS = (
|
||||
Invariant("measured", STATES, _measured,
|
||||
"a state the dump could not reach or read is a failure, never a silent pass"),
|
||||
Invariant("transition", ("fullscreen", "after_fullscreen"), _transition,
|
||||
"a real click is a user gesture, so retail enters and leaves fullscreen and the window then holds still; "
|
||||
"a timeout or fullscreenerror means the window did not do what a user's does"),
|
||||
Invariant("outer_holds_inner", STATES, _outer_holds_inner,
|
||||
"the outer window contains the viewport: a smaller outer window cannot exist "
|
||||
"(the defect it was written for: 1936x1048 outer under a 1920x1080 viewport in fullscreen)"),
|
||||
Invariant("fullscreen_is_the_screen", ("fullscreen",), _is_the_screen,
|
||||
"in fullscreen retail has no frame, toolbar or taskbar: viewport, window and screen are one rectangle "
|
||||
"(a viewport at availHeight is a window that never really went fullscreen)"),
|
||||
Invariant("fullscreen_at_origin", ("fullscreen",), _at_origin,
|
||||
"a fullscreen window sits at the screen's origin and its viewport at the window's: "
|
||||
"screenX/Y and mozInnerScreenX/Y are 0 (not a maximized window's -8/-8 and 85)"),
|
||||
Invariant("fullscreen_declared", ("fullscreen",), _declares(True),
|
||||
"the page entered fullscreen, so CSS (display-mode) and the DOM (fullscreenElement) say so"),
|
||||
Invariant("not_fullscreen", ("normal", "after_fullscreen"), _declares(False),
|
||||
"outside fullscreen neither CSS nor the DOM may claim it; it also keeps 'back_to_normal' "
|
||||
"from passing with both states stuck in fullscreen"),
|
||||
Invariant("events_at_inner_screen", STATES, _events_at_inner_screen,
|
||||
"an event's screen point is its client point plus where the viewport sits on the screen, "
|
||||
"which is mozInnerScreenX/Y: screen - client of every mouse event equals it"),
|
||||
Invariant("screen_stays", ("fullscreen", "after_fullscreen"), _screen_stays,
|
||||
"fullscreen changes the window, not the monitor: screen.width/height are the normal state's"),
|
||||
Invariant("back_to_normal", ("after_fullscreen",), _back_to_normal,
|
||||
"leaving fullscreen puts the window back as it was: every size and position is the normal state's"),
|
||||
)
|
||||
|
||||
|
||||
def check_invariants(states: dict) -> list:
|
||||
"""Every broken invariant of one visit as (invariant, state, message).
|
||||
states maps each of STATES to its values (None when the dump has none)."""
|
||||
broken = []
|
||||
for state in STATES:
|
||||
s = states.get(state)
|
||||
if not isinstance(s, dict):
|
||||
s = {"error": "the dump has no %s%s" % (STATE, state)}
|
||||
for inv in INVARIANTS:
|
||||
if state not in inv.states:
|
||||
continue
|
||||
message = inv.check(s, states)
|
||||
if message:
|
||||
broken.append((inv, state, message))
|
||||
if inv.name == "measured":
|
||||
break
|
||||
return broken
|
||||
|
||||
|
||||
def visit_states(items: dict) -> dict:
|
||||
return {name: items.get(STATE + name) for name in STATES}
|
||||
|
||||
|
||||
def invariant_lines(visit: str, items: dict) -> list:
|
||||
return ["invariant %s %s %s%s: %s (why: %s)" % (inv.name, visit, STATE, state, message, inv.why)
|
||||
for inv, state, message in check_invariants(visit_states(items))]
|
||||
|
||||
|
||||
# -
|
||||
# Dump: one leg, every (dpr, seed) visit, the way the reference was measured:
|
||||
# the page over http://127.0.0.1 (a secure context), en-US, the zone the retail
|
||||
# reference reported (retail on Windows ignores TZ and answers the machine's),
|
||||
# the device pixel ratio pinned in the persona, no drawn cursor.
|
||||
|
||||
class _Page(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
body = PAGE.read_bytes()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_POST(self): # the page also posts its result; the dump reads it from the page
|
||||
self.rfile.read(int(self.headers.get("Content-Length") or 0))
|
||||
self.send_response(204)
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def reference_items(reference: Path, dpr: float) -> dict | None:
|
||||
"""Retail's items at one DPR, from dpr<x>.json.gz (or a plain dpr<x>.json)."""
|
||||
for name in ("dpr%s.json.gz" % dpr, "dpr%s.json" % dpr):
|
||||
path = reference / name
|
||||
if path.is_file():
|
||||
raw = path.read_bytes()
|
||||
return json.loads(gzip.decompress(raw) if name.endswith(".gz") else raw)["items"]
|
||||
return None
|
||||
|
||||
|
||||
def reference_zone(reference: Path) -> str:
|
||||
return reference_items(reference, 1.0)["surface.intl"]["DateTimeFormat"]["timeZone"]
|
||||
|
||||
|
||||
def visit_options(firefox: str, seed: int, dpr: float, zone: str) -> dict:
|
||||
"""The launch of one (dpr, seed) visit. The DPR is PINNED in the persona
|
||||
(screen.dpr), so the core declares a screen, a work area and a window made
|
||||
at that scale. It used to be forced through
|
||||
extra_prefs={"layout.css.devPixelsPerPx": ...} on whatever persona the seed
|
||||
drew: a 100% persona at 1.5 read innerWidth 1920 inside an outerWidth of
|
||||
1291 (run 41325657085), an identity no machine has, which the engine now
|
||||
refuses to start with."""
|
||||
return {"seed": seed, "binary_path": firefox, "headless": True, "show_cursor": False,
|
||||
"locale": "en-US", "timezone": zone, "pin": {"screen.dpr": dpr}}
|
||||
|
||||
|
||||
def dump(firefox: str, leg: str, out: Path, reference: Path, timeout_ms: int = 180_000) -> int:
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), _Page)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
zone = reference_zone(reference)
|
||||
first_diag = None
|
||||
try:
|
||||
for dpr in DPRS:
|
||||
for seed in SEEDS:
|
||||
with InvisiblePlaywright(**visit_options(firefox, seed, dpr, zone)) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
# The same budget as the wait below: a cold Windows runner took
|
||||
# more than goto's default 30 s to reach `load` on the first
|
||||
# visit (candidate 42410156024), and passed locally 6/6.
|
||||
page.goto("http://127.0.0.1:%d/?dpr%s" % (server.server_address[1], dpr),
|
||||
timeout=timeout_ms)
|
||||
page.wait_for_function("document.title === 'done'", timeout=timeout_ms)
|
||||
result = page.evaluate("window.__hostGate")
|
||||
if result.get("format") == FORMAT:
|
||||
result["items"].update(drive_states(page.evaluate, page.mouse.move, page.mouse.click))
|
||||
if result.get("format") != FORMAT:
|
||||
print("the page answered format %r, not %r" % (result.get("format"), FORMAT))
|
||||
return 2
|
||||
path = out / ("%s_dpr%s_seed%d.json" % (leg, dpr, seed))
|
||||
path.write_text(json.dumps({"leg": leg, "dpr": dpr, "seed": seed, "result": result}),
|
||||
encoding="utf-8")
|
||||
print("dumped %s: %d items" % (path.name, len(result["items"])))
|
||||
visit = "%s dpr %s seed %d" % (leg, dpr, seed)
|
||||
for line in diag_report(visit, result["items"], first_diag):
|
||||
print(line)
|
||||
# told here too, so the job log says it without the compare step
|
||||
for line in invariant_lines(visit, result["items"]):
|
||||
print(line)
|
||||
sys.stdout.flush()
|
||||
if first_diag is None:
|
||||
first_diag = {k: v for k, v in leaves(result["items"]).items() if is_diag(k)}
|
||||
finally:
|
||||
server.shutdown()
|
||||
return 0
|
||||
|
||||
|
||||
# -
|
||||
# Compare: every leg, every visit, against each other and against retail.
|
||||
|
||||
KINDS = ("identity", "noise", "network", "measurement", "known_defects")
|
||||
|
||||
|
||||
def load_exceptions(path: Path = EXCEPTIONS) -> dict:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
unknown = set(data) - set(KINDS)
|
||||
if unknown:
|
||||
raise SystemExit("exceptions.json: unknown kinds %s" % sorted(unknown))
|
||||
for kind in KINDS:
|
||||
for entry in data.get(kind, []):
|
||||
if not entry.get("keys") or not entry.get("why"):
|
||||
raise SystemExit("exceptions.json: every %s entry needs keys and why" % kind)
|
||||
return data
|
||||
|
||||
|
||||
def matching(entries: list, key: str, leg: str | None = None) -> list:
|
||||
return [e for e in entries
|
||||
if any(fnmatch.fnmatchcase(key, p) for p in e["keys"])
|
||||
and (leg is None or not e.get("legs") or leg in e["legs"])]
|
||||
|
||||
|
||||
def is_image(value) -> bool:
|
||||
return isinstance(value, dict) and "data" in value and "enc" in value
|
||||
|
||||
|
||||
def leaves(items: dict) -> dict:
|
||||
"""Every value as a leaf with a dotted key; an image stays one value."""
|
||||
out = {}
|
||||
|
||||
def walk(key, value):
|
||||
if isinstance(value, dict) and value and not is_image(value):
|
||||
for k, v in value.items():
|
||||
walk("%s.%s" % (key, k), v)
|
||||
else:
|
||||
out[key] = value
|
||||
|
||||
for key, value in items.items():
|
||||
walk(key, value)
|
||||
return out
|
||||
|
||||
|
||||
def describe(a, b) -> str:
|
||||
"""A short account of a difference; for images, how many bytes differ."""
|
||||
if isinstance(a, dict) and isinstance(b, dict) and "data" in a and "data" in b:
|
||||
x, y = base64.b64decode(a["data"]), base64.b64decode(b["data"])
|
||||
if len(x) != len(y) or (a.get("w"), a.get("h")) != (b.get("w"), b.get("h")):
|
||||
return "image %sx%s vs %sx%s" % (a.get("w"), a.get("h"), b.get("w"), b.get("h"))
|
||||
diff = [abs(p - q) for p, q in zip(x, y) if p != q]
|
||||
return "image: %d of %d bytes differ, max delta %d" % (len(diff), len(x), max(diff, default=0))
|
||||
text = lambda v: json.dumps(v, sort_keys=True)[:120]
|
||||
return "%s vs %s" % (text(a), text(b))
|
||||
|
||||
|
||||
def compare(dumps: Path, reference: Path, exceptions: dict, notes: list | None = None) -> list:
|
||||
"""Every failure as one line. Empty means the gate passes. notes, when
|
||||
given, receives what was not checked and why (REFERENCE_PENDING)."""
|
||||
visits = {} # (leg, dpr, seed) -> items
|
||||
failures = []
|
||||
for path in sorted(dumps.glob("*.json")):
|
||||
d = json.loads(path.read_text(encoding="utf-8"))
|
||||
items = d["result"]["items"]
|
||||
visits[(d["leg"], d["dpr"], d["seed"])] = {k: v for k, v in leaves(items).items() if not is_diag(k)}
|
||||
# the invariants: every leg, every visit, every state; no exception and no reference applies
|
||||
failures += invariant_lines("%s dpr %s seed %d" % (d["leg"], d["dpr"], d["seed"]), items)
|
||||
if not visits:
|
||||
return ["no dumps in %s" % dumps]
|
||||
legs = sorted({k[0] for k in visits})
|
||||
refs = {}
|
||||
pending = {} # dpr -> the REFERENCE_PENDING namespaces the reference does not record yet
|
||||
for dpr in DPRS:
|
||||
items = reference_items(reference, dpr)
|
||||
if items is None:
|
||||
return ["no retail reference for dpr %s in %s" % (dpr, reference)]
|
||||
refs[dpr] = {k: v for k, v in leaves(items).items() if not is_diag(k)}
|
||||
pending[dpr] = tuple(p for p in REFERENCE_PENDING if not any(k.startswith(p) for k in refs[dpr]))
|
||||
for p in pending[dpr]:
|
||||
if notes is not None:
|
||||
notes.append("the retail reference has no %s* at dpr %s: those values are held to "
|
||||
"host-independence and the invariants, not to retail" % (p, dpr))
|
||||
|
||||
identity = exceptions.get("identity", [])
|
||||
excusable = exceptions.get("noise", []) + exceptions.get("network", []) + exceptions.get("measurement", [])
|
||||
known = exceptions.get("known_defects", [])
|
||||
used = set()
|
||||
|
||||
def excused(key, leg):
|
||||
if matching(excusable, key):
|
||||
return True
|
||||
hit = matching(known, key, leg)
|
||||
for e in hit:
|
||||
used.add(id(e))
|
||||
return bool(hit)
|
||||
|
||||
for dpr in DPRS:
|
||||
for leg in legs:
|
||||
missing = [s for s in SEEDS if (leg, dpr, s) not in visits]
|
||||
if missing:
|
||||
failures.append("%s dpr %s: no dump for seeds %s" % (leg, dpr, missing))
|
||||
present = [(leg, s) for leg in legs for s in SEEDS if (leg, dpr, s) in visits]
|
||||
keys = sorted(set().union(*(visits[(l, dpr, s)].keys() for l, s in present)) | set(refs[dpr]))
|
||||
for key in keys:
|
||||
# 1. host-independence: for each seed, every leg gives the Windows
|
||||
# leg's value. Windows is the anchor because it is the platform the
|
||||
# identity claims: a leg that differs from it is the one that moved.
|
||||
for seed in SEEDS:
|
||||
values = {leg: visits[(leg, dpr, seed)].get(key, "<missing>")
|
||||
for leg in legs if (leg, dpr, seed) in visits}
|
||||
base = ANCHOR if ANCHOR in values else next(iter(values), None)
|
||||
for leg, value in values.items():
|
||||
if leg != base and value != values[base] and not excused(key, leg):
|
||||
failures.append("host %s dpr %s seed %d: %s differs from %s: %s"
|
||||
% (key, dpr, seed, leg, base, describe(value, values[base])))
|
||||
# 1b. host-independence among the legs of one OS (two Linux
|
||||
# distributions): a known defect excuses a difference from Windows,
|
||||
# never one between two machines of the same system, whose libraries
|
||||
# (FreeType, fontconfig, Mesa) are the host's and must not show.
|
||||
for seed in SEEDS:
|
||||
for family in sorted({l.split("-")[0] for l in legs}):
|
||||
same_os = [l for l in legs if l.split("-")[0] == family and (l, dpr, seed) in visits]
|
||||
for leg in same_os[1:]:
|
||||
value = visits[(leg, dpr, seed)].get(key, "<missing>")
|
||||
first = visits[(same_os[0], dpr, seed)].get(key, "<missing>")
|
||||
if value != first and not matching(excusable, key):
|
||||
failures.append("host %s dpr %s seed %d: %s differs from %s (same OS): %s"
|
||||
% (key, dpr, seed, leg, same_os[0], describe(value, first)))
|
||||
# 2. retail equality, for a value that is the same for every seed
|
||||
if key.startswith(pending[dpr]):
|
||||
continue
|
||||
for leg in legs:
|
||||
per_seed = [visits[(leg, dpr, s)].get(key, "<missing>")
|
||||
for s in SEEDS if (leg, dpr, s) in visits]
|
||||
if len({json.dumps(v, sort_keys=True) for v in per_seed}) != 1 or matching(identity, key):
|
||||
continue # depends on the identity: property 1 only
|
||||
retail = refs[dpr].get(key, "<missing>")
|
||||
if per_seed[0] != retail and not excused(key, leg):
|
||||
failures.append("retail %s dpr %s on %s: %s"
|
||||
% (key, dpr, leg, describe(per_seed[0], retail)))
|
||||
|
||||
for e in known:
|
||||
if id(e) not in used:
|
||||
failures.append("known defect no longer seen, remove it from exceptions.json: %s (%s)"
|
||||
% (e["keys"], e["why"]))
|
||||
return failures
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
d = sub.add_parser("dump")
|
||||
d.add_argument("firefox")
|
||||
d.add_argument("--leg", required=True)
|
||||
d.add_argument("--out", type=Path, required=True)
|
||||
d.add_argument("--reference", type=Path, default=REFERENCE)
|
||||
c = sub.add_parser("compare")
|
||||
c.add_argument("dumps", type=Path)
|
||||
c.add_argument("--reference", type=Path, default=REFERENCE)
|
||||
args = ap.parse_args(argv)
|
||||
if args.cmd == "dump":
|
||||
return dump(args.firefox, args.leg, args.out, args.reference)
|
||||
notes = []
|
||||
failures = compare(args.dumps, args.reference, load_exceptions(), notes)
|
||||
for n in notes:
|
||||
print("NOTE " + n)
|
||||
for f in failures:
|
||||
print("FAIL " + f)
|
||||
print("HOST GATE %s: %d failures" % ("OK" if not failures else "FAILED", len(failures)))
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Which canvas text cases two runs draw differently.
|
||||
|
||||
tests/test_canvas_text_is_windows_e2e.py writes canvas_text_<tag>.json (case id -> SHA-256
|
||||
of the RGBA bytes) into INVISIBLE_CANVAS_TEXT_OUT. Run it on Debian 12 and on Ubuntu 24.04
|
||||
(and the retail reference, tests/data/canvas_text_ref/refs.json, is accepted too), then:
|
||||
|
||||
python scripts/compare_canvas_text_runs.py debian.json ubuntu.json
|
||||
|
||||
The exit status is 0 when every case is equal on both sides and both draw the same set.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
|
||||
|
||||
def load(path):
|
||||
"""case id -> sha256, from a run file or from refs.json."""
|
||||
data = json.loads(open(path, encoding="utf-8").read())
|
||||
if "cases" in data:
|
||||
return {k: v["sha256"] for k, v in data["cases"].items()}
|
||||
return data
|
||||
|
||||
|
||||
def compare(a, b):
|
||||
"""(only in a, only in b, ids whose hash differs)."""
|
||||
only_a = sorted(set(a) - set(b))
|
||||
only_b = sorted(set(b) - set(a))
|
||||
differ = sorted(k for k in set(a) & set(b) if a[k] != b[k])
|
||||
return only_a, only_b, differ
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) != 3:
|
||||
print(__doc__)
|
||||
return 2
|
||||
a, b = load(argv[1]), load(argv[2])
|
||||
only_a, only_b, differ = compare(a, b)
|
||||
for label, ids in (("only in %s" % argv[1], only_a), ("only in %s" % argv[2], only_b),
|
||||
("differ", differ)):
|
||||
if ids:
|
||||
print("%s (%d):" % (label, len(ids)))
|
||||
for k in ids:
|
||||
print(" " + k)
|
||||
print("%d cases compared, %d differ" % (len(set(a) & set(b)), len(differ)))
|
||||
return 1 if (only_a or only_b or differ) else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -0,0 +1,181 @@
|
||||
#!/usr/bin/env python
|
||||
"""Refuse a release when the browser-driving e2e is not green on the commit
|
||||
being tagged.
|
||||
|
||||
python scripts/e2e_is_green.py --repo owner/name --sha <sha>
|
||||
python scripts/e2e_is_green.py --selftest
|
||||
|
||||
⛔ WHY THIS EXISTS. `publish.yml`'s gate runs `python -m pytest -q`, which is the
|
||||
DEFAULT selection, and the default selection deselects `e2e`. So the job that
|
||||
decides whether a release goes out has never looked at the suite that drives a
|
||||
browser. The e2e runs on every push and every pull request, and no gate reads
|
||||
it: a red there stops neither a merge nor a tag.
|
||||
|
||||
It has already happened. 0.22.1 was tagged from a main whose e2e was red, and
|
||||
nothing said so, because nothing was looking. That is the same shape as the
|
||||
`-m unit` false green the project forbids elsewhere, sitting inside the workflow
|
||||
that publishes.
|
||||
|
||||
⛔ AND IT ASKS RATHER THAN RE-RUNS. The e2e has already run on that commit, and
|
||||
running it again here would cost five minutes to learn something the API can
|
||||
answer in one call. What is missing is not a second measurement: it is somebody
|
||||
reading the first one.
|
||||
|
||||
The three verdicts, and the middle one is the one that gets written wrong:
|
||||
|
||||
- a check-run concluded badly -> REFUSE, naming it
|
||||
- NO e2e check-run exists for that commit -> REFUSE
|
||||
- still running -> wait, then refuse on the deadline
|
||||
|
||||
⛔ ZERO CHECK-RUNS IS NOT A VERDICT. An empty list is indistinguishable from
|
||||
"the workflow was renamed", "it never started" and "nobody configured one", and
|
||||
mapping it to a pass turns this gate into decoration exactly when it is most
|
||||
needed. Measured the hard way on a different gate: a poller read an empty result
|
||||
as DONE and reported a conclusion that the next iteration contradicted.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
#: What counts as a conclusion that does not block. `skipped` and `neutral` are
|
||||
#: here because a matrix leg can legitimately not run; `cancelled` is NOT, since
|
||||
#: a cancelled run measured nothing and saying otherwise is the same lie as an
|
||||
#: empty list.
|
||||
FINE = ("success", "skipped", "neutral")
|
||||
|
||||
REFUSED_RED = 1
|
||||
REFUSED_ABSENT = 2
|
||||
REFUSED_TIMEOUT = 3
|
||||
|
||||
|
||||
def verdict(runs, pattern):
|
||||
"""(code, message) for the check-runs of one commit. Pure: no network.
|
||||
|
||||
Separated from the fetching so its known-bad cases can run without a token,
|
||||
a repository or a network, which is what `--selftest` exercises.
|
||||
"""
|
||||
ours = [c for c in runs if str(c.get("name", "")).startswith(pattern)]
|
||||
if not ours:
|
||||
return REFUSED_ABSENT, (
|
||||
"no check-run whose name starts with %r exists for this commit.\n"
|
||||
"That is not a pass: an empty list reads the same whether the job\n"
|
||||
"was renamed, never started, or was never configured. If the e2e\n"
|
||||
"workflow no longer produces that name, fix the name here rather\n"
|
||||
"than letting a release go out unmeasured." % pattern)
|
||||
|
||||
running = [c["name"] for c in ours if c.get("status") != "completed"]
|
||||
if running:
|
||||
return None, "still running: %s" % ", ".join(sorted(running))
|
||||
|
||||
bad = [(c["name"], c.get("conclusion")) for c in ours
|
||||
if c.get("conclusion") not in FINE]
|
||||
if bad:
|
||||
return REFUSED_RED, (
|
||||
"the e2e is not green on the commit being tagged:\n" +
|
||||
"\n".join(" %s: %s" % (n, c) for n, c in sorted(bad)) +
|
||||
"\nA release from here ships code the browser-driving suite\n"
|
||||
"rejected. Fix it, or re-run the job and let it say so itself.")
|
||||
|
||||
return 0, "e2e green on this commit: %s" % ", ".join(
|
||||
sorted(c["name"] for c in ours))
|
||||
|
||||
|
||||
def fetch(repo, sha, token):
|
||||
url = ("https://api.github.com/repos/%s/commits/%s/check-runs?per_page=100"
|
||||
% (repo, sha))
|
||||
req = urllib.request.Request(url, headers={
|
||||
"Accept": "application/vnd.github+json",
|
||||
"Authorization": "Bearer %s" % token,
|
||||
"X-GitHub-Api-Version": "2022-11-28",
|
||||
})
|
||||
with urllib.request.urlopen(req, timeout=30) as r:
|
||||
return json.load(r).get("check_runs", [])
|
||||
|
||||
|
||||
SELFTEST = [
|
||||
("a green leg passes", 0,
|
||||
[{"name": "e2e (linux, xvfb)", "status": "completed", "conclusion": "success"}]),
|
||||
("a red leg refuses", REFUSED_RED,
|
||||
[{"name": "e2e (linux, xvfb)", "status": "completed", "conclusion": "failure"}]),
|
||||
("a cancelled leg refuses, because it measured nothing", REFUSED_RED,
|
||||
[{"name": "e2e (linux, xvfb)", "status": "completed", "conclusion": "cancelled"}]),
|
||||
("timed_out refuses", REFUSED_RED,
|
||||
[{"name": "e2e (linux, xvfb)", "status": "completed", "conclusion": "timed_out"}]),
|
||||
("no check-run at all refuses", REFUSED_ABSENT, []),
|
||||
("other jobs alone are not an e2e", REFUSED_ABSENT,
|
||||
[{"name": "tests (3.12)", "status": "completed", "conclusion": "success"}]),
|
||||
("one green leg does not excuse a red one", REFUSED_RED,
|
||||
[{"name": "e2e (linux, xvfb)", "status": "completed", "conclusion": "success"},
|
||||
{"name": "e2e (macos)", "status": "completed", "conclusion": "failure"}]),
|
||||
("a skipped leg is allowed", 0,
|
||||
[{"name": "e2e (linux, xvfb)", "status": "completed", "conclusion": "skipped"}]),
|
||||
("still running is neither a pass nor a refusal", None,
|
||||
[{"name": "e2e (linux, xvfb)", "status": "in_progress", "conclusion": None}]),
|
||||
("running beside a red one waits rather than guessing", None,
|
||||
[{"name": "e2e (a)", "status": "in_progress", "conclusion": None},
|
||||
{"name": "e2e (b)", "status": "completed", "conclusion": "failure"}]),
|
||||
]
|
||||
|
||||
|
||||
def selftest():
|
||||
bad = 0
|
||||
for label, want, runs in SELFTEST:
|
||||
got, _ = verdict(runs, "e2e")
|
||||
ok = got == want
|
||||
bad += not ok
|
||||
print(" %-56s %s" % (label, "ok" if ok else
|
||||
"WRONG (wanted %r, got %r)" % (want, got)))
|
||||
print("%d/%d known-bad cases behave" % (len(SELFTEST) - bad, len(SELFTEST)))
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="e2e_is_green.py")
|
||||
ap.add_argument("--repo", help="owner/name")
|
||||
ap.add_argument("--sha", help="the commit being tagged")
|
||||
ap.add_argument("--pattern", default="e2e",
|
||||
help="check-run name prefix to look for (default: e2e)")
|
||||
ap.add_argument("--wait-minutes", type=float, default=30.0,
|
||||
help="how long to wait while a leg is still running")
|
||||
ap.add_argument("--selftest", action="store_true")
|
||||
a = ap.parse_args(argv)
|
||||
|
||||
if a.selftest:
|
||||
return selftest()
|
||||
if not (a.repo and a.sha):
|
||||
ap.error("--repo and --sha are required without --selftest")
|
||||
|
||||
token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
|
||||
if not token:
|
||||
print("GITHUB_TOKEN is not set, so this gate cannot read the checks.\n"
|
||||
"A gate that cannot run is a refusal, not a pass.", file=sys.stderr)
|
||||
return REFUSED_ABSENT
|
||||
|
||||
deadline = time.time() + a.wait_minutes * 60
|
||||
while True:
|
||||
try:
|
||||
runs = fetch(a.repo, a.sha, token)
|
||||
except urllib.error.HTTPError as e:
|
||||
print("the checks API answered %s: %s" % (e.code, e.reason),
|
||||
file=sys.stderr)
|
||||
return REFUSED_ABSENT
|
||||
code, message = verdict(runs, a.pattern)
|
||||
if code is not None:
|
||||
print(message, file=sys.stderr if code else sys.stdout)
|
||||
return code
|
||||
if time.time() >= deadline:
|
||||
print("%s\nstill not finished after %g minutes. Refusing rather "
|
||||
"than assuming." % (message, a.wait_minutes), file=sys.stderr)
|
||||
return REFUSED_TIMEOUT
|
||||
print("%s - waiting" % message)
|
||||
time.sleep(30)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,139 +0,0 @@
|
||||
"""Extracts the injected script from the driver bundle into
|
||||
`_juggler/injected.js`.
|
||||
|
||||
WHY WE EXTRACT AND DO NOT REWRITE. That JavaScript is the selector engines
|
||||
(css, xpath, text, role, testid, label), actionability, the ARIA snapshot and
|
||||
`expect`: thousands of lines of subtle DOM logic that **runs in the page**
|
||||
and that no Python rewrite could replace, because Python is not in the page.
|
||||
It is not work to redo: it is cargo to carry over.
|
||||
|
||||
⛔ BUT IT IS NOT VIRGIN UPSTREAM. It already carries our own fixes -
|
||||
`markTargetElements` emptied out, `__pwClock` read via a descriptor,
|
||||
`Symbol.hasInstance` captured, and since 2026-08-27 listener installs
|
||||
guarded by `_isUtilityWorld`. Extracting it from a bundle other than THIS
|
||||
one loses all of them, silently. See `31-client-fork.md` §3.
|
||||
|
||||
⛔ AND IT IS NOT YET TRIMMED. The chosen perimeter
|
||||
(`32-stacco-da-playwright.md` §1) leaves out the ARIA snapshot,
|
||||
`locatorGenerators`, `highlight` and `consoleApi`, that is **87,468 bytes
|
||||
out of 311,365**. Here we extract the WHOLE thing: the trim is a step of
|
||||
its own, and it has to be done on the real module boundaries, which in the
|
||||
emitted bundle **are not boundaries** (§3.3).
|
||||
|
||||
python scripts/gen_injected_source.py (extracts)
|
||||
python scripts/gen_injected_source.py --check (regenerates and compares)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
ANCHOR = "source4 = '"
|
||||
|
||||
|
||||
def extract(bundle: str) -> str:
|
||||
"""The value of the `source4` string, de-escaped.
|
||||
|
||||
⛔ It is a SINGLE-QUOTE string on ONE physical line of three hundred
|
||||
thousand characters. It is scanned by hand respecting backslashes: a
|
||||
greedy regex would grab all the way to the last quote in the FILE, and
|
||||
a lazy one would stop at the first apostrophe inside a comment.
|
||||
"""
|
||||
i = bundle.index(ANCHOR) + len(ANCHOR)
|
||||
bs = chr(92)
|
||||
j = i
|
||||
n = len(bundle)
|
||||
while j < n:
|
||||
if bundle[j] == bs:
|
||||
j += 2
|
||||
continue
|
||||
if bundle[j] == "'":
|
||||
break
|
||||
j += 1
|
||||
else:
|
||||
raise SystemExit("the source4 string never closes: corrupted bundle?")
|
||||
raw = bundle[i:j]
|
||||
# De-escape: the string is JavaScript, but the escapes it uses are the
|
||||
# ones `unicode_escape` understands. We go through latin-1 so as not to
|
||||
# break the high bytes.
|
||||
return raw.encode("latin-1", "backslashreplace").decode("unicode_escape")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
here = pathlib.Path(__file__).resolve().parent.parent
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--bundle", default=str(
|
||||
here / "src" / "invisible_playwright" / "_driver" / "package" / "lib" / "coreBundle.js"))
|
||||
ap.add_argument("--out", default=str(
|
||||
here / "src" / "invisible_playwright" / "_juggler" / "injected.js"))
|
||||
ap.add_argument("--check", action="store_true")
|
||||
a = ap.parse_args()
|
||||
|
||||
# ⛔ A MISSING BUNDLE IS A STATE, NOT A CRASH. Since the Node driver was
|
||||
# removed there may be no bundle in the tree at all, and the extracted
|
||||
# `injected.js` is COMMITTED - it stays valid without one. What is gone is
|
||||
# the ability to RE-DERIVE it, and letting that arrive as
|
||||
# `FileNotFoundError` from a path deep in an argparse default sends the
|
||||
# reader looking for a broken script instead of a deleted folder.
|
||||
named = os.environ.get("INVPW_DRIVER_BUNDLE")
|
||||
path = pathlib.Path(named) if named else pathlib.Path(a.bundle)
|
||||
if not path.exists():
|
||||
print("NOT COMPARABLE: no driver bundle at %s." % path)
|
||||
print(" `injected.js` is committed and still valid - what is gone is "
|
||||
"the ability to re-derive it.")
|
||||
print(" To get one back: git worktree add <dir> <the last commit that "
|
||||
"carried _driver/>, then")
|
||||
print(" INVPW_DRIVER_BUNDLE=<dir>/src/invisible_playwright/_driver/"
|
||||
"package/lib/coreBundle.js")
|
||||
return 2
|
||||
|
||||
bundle = path.read_bytes().decode("utf-8", "replace")
|
||||
source = extract(bundle)
|
||||
|
||||
# Proof that what we extracted is REALLY the injected script, not some
|
||||
# random string that happens to start the same way. A check on what it
|
||||
# MUST contain costs nothing and stops us from shipping the wrong blob.
|
||||
EXPECTED = ("InjectedScript", "internal:role", "internal:testid",
|
||||
"_setupHitTargetInterceptors", "createRoleEngine")
|
||||
missing = [x for x in EXPECTED if x not in source]
|
||||
if missing:
|
||||
raise SystemExit("the extract does not look like the injected script: "
|
||||
"missing %s" % ", ".join(missing))
|
||||
# And that it carries OUR fixes: an upstream bundle would lose all of
|
||||
# them without anything raising an error.
|
||||
#
|
||||
# NOTE: the marker below is a LITERAL, not prose. It has to match the
|
||||
# actual bytes of the comments `injected.js` carries, so it is compared
|
||||
# exactly and never reworded. It was `MODIFICATO da invisible_playwright`
|
||||
# until 2026-08-27, when the whole repository moved to English.
|
||||
if "MODIFIED by invisible_playwright" not in source:
|
||||
raise SystemExit("the extract does NOT carry invisible_playwright's "
|
||||
"changes: it is an upstream bundle, not ours")
|
||||
|
||||
print("extracted: %d bytes, %d lines" % (len(source.encode("utf-8")),
|
||||
source.count(chr(10))))
|
||||
print(" our changes marked: %d"
|
||||
% source.count("MODIFIED by invisible_playwright"))
|
||||
|
||||
out = pathlib.Path(a.out)
|
||||
new_bytes = source.encode("utf-8")
|
||||
if a.check:
|
||||
if not out.is_file():
|
||||
print("MISSING: %s" % out)
|
||||
return 1
|
||||
if out.read_bytes() == new_bytes:
|
||||
print("INJECTED SCRIPT ALIGNED")
|
||||
return 0
|
||||
print("DRIFT: the extract does not match the file in the tree")
|
||||
return 1
|
||||
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_bytes(new_bytes)
|
||||
print("wrote %s" % out)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,466 +0,0 @@
|
||||
"""Generates `_juggler/protocol.py` from Juggler's `Protocol.js`.
|
||||
|
||||
WHY IT IS GENERATED AND NOT HAND-WRITTEN. `Protocol.js` is the
|
||||
machine-readable schema of the protocol, and the browser enforces it in a
|
||||
CLOSED WORLD: an undeclared field is not ignored, it is REJECTED at
|
||||
runtime, and the session dies at context creation with a green build. The
|
||||
measured cost of that class of failure in this project is 97 tests out of
|
||||
133. A hand-written table next to a file that already holds the truth is a
|
||||
second source that drifts on its own.
|
||||
|
||||
⛔ IT READS THE **SHIPPED** PROTOCOL.JS, NOT THE ONE IN THE TREE. They are
|
||||
two different files that happen to coincide today: generating from the
|
||||
tree produces a client for a browser no user runs, and the way it fails is
|
||||
the closed-world way. The default is therefore a binary, not a source
|
||||
path.
|
||||
|
||||
⛔ AND JUGGLER LIVES IN TWO LAYOUTS: `omni.ja` (Windows) and the loose tree
|
||||
`./chrome/juggler/` (Linux). Both are tried, and it says which one
|
||||
answered.
|
||||
|
||||
⛔ THIS DOES NOT REPLACE `protocol_drift_check.py`. That gate compares
|
||||
what a REAL client sends against our declaration, and remains the only
|
||||
thing that knows how to answer that question. Generating both sides from
|
||||
the same source does not make drift impossible: it makes it UNOBSERVABLE.
|
||||
See `docs/firefox-stealth-architecture/32-stacco-da-playwright.md` §3.2.
|
||||
|
||||
python scripts/gen_juggler_protocol.py --binary <firefox folder>
|
||||
python scripts/gen_juggler_protocol.py --check (regenerate and compare)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import pprint
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
JAR_MEMBER = "chrome/juggler/content/protocol/Protocol.js"
|
||||
LOOSE_TREE = "chrome/juggler/content/protocol/Protocol.js"
|
||||
|
||||
# The combinators that `Protocol.js` actually uses. The vocabulary
|
||||
# declared in PrimitiveTypes.js has 11; these 8 are the ones exercised. If
|
||||
# another one shows up one day, the generator REJECTS instead of guessing.
|
||||
COMBINATORS = {"String", "Number", "Boolean", "Any", "Enum",
|
||||
"Nullable", "Optional", "Array"}
|
||||
|
||||
|
||||
# ── reading ──────────────────────────────────────────────────────────────────
|
||||
|
||||
def protocol_source(binary: str) -> tuple[str, str]:
|
||||
"""(label, text) of the SHIPPED Protocol.js. Tries both layouts."""
|
||||
base = pathlib.Path(binary)
|
||||
loose = base / LOOSE_TREE
|
||||
if loose.is_file():
|
||||
return ("loose tree: %s" % loose,
|
||||
loose.read_bytes().decode("utf-8", "replace"))
|
||||
for name in ("omni.ja", os.path.join("browser", "omni.ja")):
|
||||
jar = base / name
|
||||
if not jar.is_file():
|
||||
continue
|
||||
try:
|
||||
with zipfile.ZipFile(jar) as z:
|
||||
if JAR_MEMBER in z.namelist():
|
||||
return ("%s!%s" % (jar, JAR_MEMBER),
|
||||
z.read(JAR_MEMBER).decode("utf-8", "replace"))
|
||||
except zipfile.BadZipFile:
|
||||
# Firefox may package an optimized jar that zipfile cannot
|
||||
# read. Not a case to swallow: say which file and why.
|
||||
raise SystemExit(
|
||||
"jar %s does not open with zipfile (optimized jar). "
|
||||
"Extract it with 7z and pass --proto." % jar)
|
||||
raise SystemExit(
|
||||
"Protocol.js not found in %s: neither loose tree nor omni.ja"
|
||||
% binary)
|
||||
|
||||
|
||||
def strip_comments(s: str) -> str:
|
||||
"""Removes // and /* */ without touching what is inside strings."""
|
||||
out, i, n = [], 0, len(s)
|
||||
while i < n:
|
||||
c = s[i]
|
||||
if c in ("'", '"', "`"):
|
||||
j = i + 1
|
||||
while j < n:
|
||||
if s[j] == chr(92):
|
||||
j += 2
|
||||
continue
|
||||
if s[j] == c:
|
||||
break
|
||||
j += 1
|
||||
out.append(s[i:j + 1])
|
||||
i = j + 1
|
||||
elif s.startswith("//", i):
|
||||
j = s.find(chr(10), i)
|
||||
i = n if j < 0 else j
|
||||
elif s.startswith("/*", i):
|
||||
j = s.find("*/", i)
|
||||
i = n if j < 0 else j + 2
|
||||
else:
|
||||
out.append(c)
|
||||
i += 1
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def block(s: str, start: int) -> str:
|
||||
"""The balanced block from the first '{' at `start`, skipping strings."""
|
||||
i = s.index("{", start)
|
||||
d, j, n = 0, i, len(s)
|
||||
while j < n:
|
||||
c = s[j]
|
||||
if c in ("'", '"', "`"):
|
||||
k = j + 1
|
||||
while k < n:
|
||||
if s[k] == chr(92):
|
||||
k += 2
|
||||
continue
|
||||
if s[k] == c:
|
||||
break
|
||||
k += 1
|
||||
j = k + 1
|
||||
continue
|
||||
if c == "{":
|
||||
d += 1
|
||||
elif c == "}":
|
||||
d -= 1
|
||||
if d == 0:
|
||||
return s[i:j + 1]
|
||||
j += 1
|
||||
raise SystemExit("unbalanced block starting at %d" % start)
|
||||
|
||||
|
||||
def entries(body: str) -> list[tuple[str, str]]:
|
||||
"""The TOP-level key/value pairs of a { ... } block."""
|
||||
inner = body[1:-1]
|
||||
out, i, n = [], 0, len(inner)
|
||||
while i < n:
|
||||
m = re.compile(r"\s*'?([A-Za-z_$][\w$]*)'?\s*:\s*").match(inner, i)
|
||||
if not m:
|
||||
i += 1
|
||||
continue
|
||||
key, i = m.group(1), m.end()
|
||||
d, j, start = 0, i, i
|
||||
while j < n:
|
||||
c = inner[j]
|
||||
if c in ("'", '"', "`"):
|
||||
k = j + 1
|
||||
while k < n:
|
||||
if inner[k] == chr(92):
|
||||
k += 2
|
||||
continue
|
||||
if inner[k] == c:
|
||||
break
|
||||
k += 1
|
||||
j = k + 1
|
||||
continue
|
||||
if c in "{[(":
|
||||
d += 1
|
||||
elif c in "}])":
|
||||
d -= 1
|
||||
elif c == "," and d == 0:
|
||||
break
|
||||
j += 1
|
||||
out.append((key, inner[start:j].strip()))
|
||||
i = j + 1
|
||||
return out
|
||||
|
||||
|
||||
# ── types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
def parse_type_expr(expr: str, tables: dict) -> dict:
|
||||
"""A type expression -> a JSON-serializable structure."""
|
||||
e = expr.strip()
|
||||
if e.startswith("{"):
|
||||
return {"k": "Object",
|
||||
"fields": {c: parse_type_expr(v, tables)
|
||||
for c, v in entries(block(e, 0))}}
|
||||
m = re.match(r"t\.(\w+)\s*\((.*)\)\s*$", e, re.S)
|
||||
if m:
|
||||
name, inner = m.group(1), m.group(2)
|
||||
if name not in COMBINATORS:
|
||||
raise SystemExit("unexpected combinator: t.%s" % name)
|
||||
if name == "Enum":
|
||||
return {"k": "Enum", "values": re.findall(r"'([^']*)'", inner)}
|
||||
return {"k": name, "of": parse_type_expr(inner, tables)}
|
||||
m = re.match(r"t\.(\w+)\s*$", e)
|
||||
if m:
|
||||
if m.group(1) not in COMBINATORS:
|
||||
raise SystemExit("unexpected combinator: t.%s" % m.group(1))
|
||||
return {"k": m.group(1)}
|
||||
m = re.match(r"(\w+)\.(\w+)\s*$", e)
|
||||
if m and m.group(1) in tables and m.group(2) in tables[m.group(1)]:
|
||||
return dict(tables[m.group(1)][m.group(2)], ref="%s.%s" % m.groups())
|
||||
raise SystemExit("unparseable type expression: %r" % e[:90])
|
||||
|
||||
|
||||
# ── parsing ──────────────────────────────────────────────────────────────────
|
||||
|
||||
def parse_type(text: str) -> dict:
|
||||
s = strip_comments(text)
|
||||
tables: dict = {}
|
||||
for m in re.finditer(r"^const (\w+Types) = \{\};", s, re.M):
|
||||
tables[m.group(1)] = {}
|
||||
for name in list(tables):
|
||||
for m in re.finditer(r"^%s\.(\w+) = " % re.escape(name), s, re.M):
|
||||
tables[name][m.group(1)] = parse_type_expr(
|
||||
block(s, m.end() - 1), tables)
|
||||
|
||||
domains: dict = {}
|
||||
for m in re.finditer(r"^const ([A-Z]\w*) = \{", s, re.M):
|
||||
domain = m.group(1)
|
||||
body = block(s, m.end() - 1)
|
||||
if "methods:" not in body and "events:" not in body:
|
||||
continue
|
||||
d = {"commands": {}, "events": {}}
|
||||
for key, value in entries(body):
|
||||
if key not in ("methods", "events"):
|
||||
continue
|
||||
where = "commands" if key == "methods" else "events"
|
||||
for name, body2 in entries(value):
|
||||
if where == "events":
|
||||
d["events"][name] = parse_type_expr(body2, tables)
|
||||
else:
|
||||
parts = dict(entries(body2))
|
||||
d["commands"][name] = {
|
||||
"params": (
|
||||
parse_type_expr(parts["params"], tables)
|
||||
if "params" in parts else None),
|
||||
"returns": (
|
||||
parse_type_expr(parts["returns"], tables)
|
||||
if "returns" in parts else None),
|
||||
}
|
||||
domains[domain] = d
|
||||
return domains
|
||||
|
||||
|
||||
# ── emission ─────────────────────────────────────────────────────────────────
|
||||
|
||||
HEADER = '''"""GENERATED by scripts/gen_juggler_protocol.py.
|
||||
Do not edit by hand.
|
||||
|
||||
Source: %s
|
||||
Commands: %d Events: %d
|
||||
|
||||
The browser enforces this schema in a CLOSED WORLD: an undeclared field is
|
||||
REJECTED at runtime, not ignored. It therefore serves to verify what WE
|
||||
SEND before it goes out, not to document.
|
||||
|
||||
⛔ Does not replace `protocol_drift_check.py` in the source repo: that
|
||||
gate asks what a REAL client sends, and that is a question this file
|
||||
cannot ask, because it is generated from the same source it should be
|
||||
checking.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
'''
|
||||
|
||||
|
||||
def stable_source(source: str) -> str:
|
||||
"""The source line in the generated file must not contain an absolute
|
||||
path: it would change from one machine to another and every
|
||||
regeneration would look like a change. And Windows backslashes inside
|
||||
a docstring are ESCAPES: `C:\\Users` raises `truncated \\UXXXXXXXX
|
||||
escape` and the generated file does not import. It happened on
|
||||
2026-08-27, and the way it was noticed was that the file did not
|
||||
import, not that the generator failed."""
|
||||
f = source.replace(chr(92), "/")
|
||||
return (f.split("/")[-1] if "!" not in f
|
||||
else "omni.ja!" + f.split("!", 1)[1])
|
||||
|
||||
|
||||
def render(domains: dict, source: str) -> str:
|
||||
source = stable_source(source)
|
||||
n_cmd = sum(len(d["commands"]) for d in domains.values())
|
||||
n_ev = sum(len(d["events"]) for d in domains.values())
|
||||
commands, events = {}, {}
|
||||
for domain, d in sorted(domains.items()):
|
||||
for name, spec in sorted(d["commands"].items()):
|
||||
commands["%s.%s" % (domain, name)] = spec
|
||||
for name, spec in sorted(d["events"].items()):
|
||||
events["%s.%s" % (domain, name)] = spec
|
||||
# ⛔ pprint and not json.dumps: json emits `null`/`true`/`false`,
|
||||
# which do not exist in Python, and the generated file does not
|
||||
# IMPORT. The generator, though, still exits 0, so the failure only
|
||||
# shows up when importing - which is why this generator's test
|
||||
# imports the file instead of looking at its bytes.
|
||||
body = HEADER % (source, n_cmd, n_ev)
|
||||
body += "DOMAINS = %s\n\n" % pprint.pformat(sorted(domains), width=78)
|
||||
body += "COMMANDS = %s\n\n" % pprint.pformat(commands, width=88,
|
||||
sort_dicts=True)
|
||||
body += "EVENTS = %s\n" % pprint.pformat(events, width=88,
|
||||
sort_dicts=True)
|
||||
return body
|
||||
|
||||
|
||||
def _selftest(text: str) -> int:
|
||||
"""Known-bad mutations on Protocol.js, without a browser and without a
|
||||
network.
|
||||
|
||||
The question: if the SHIPPED Protocol.js changes, does `--check`
|
||||
notice? The text is mutated in memory, regenerated, and compared
|
||||
against the body produced from the intact text. A mutation that does
|
||||
not move the body is a hole.
|
||||
"""
|
||||
base = render(parse_type(text), "base")
|
||||
|
||||
def body(t):
|
||||
i = t.find("DOMAINS = ")
|
||||
return t[i:] if i >= 0 else t
|
||||
|
||||
MUTATIONS = [
|
||||
("a command REMOVED",
|
||||
lambda s: s.replace(
|
||||
" 'collectGarbage': {\n params: {},\n },\n",
|
||||
"", 1)),
|
||||
("a command ADDED",
|
||||
lambda s: s.replace(
|
||||
" 'collectGarbage': {",
|
||||
" 'invented': {\n params: {},\n },\n"
|
||||
" 'collectGarbage': {", 1)),
|
||||
("a field removed from a command",
|
||||
lambda s: s.replace(
|
||||
" attachToDefaultContext: t.Boolean,\n", "", 1)),
|
||||
("a type changed: String -> Number",
|
||||
lambda s: s.replace(
|
||||
" url: t.String,", " url: t.Number,", 1)),
|
||||
("an Optional becomes required",
|
||||
lambda s: s.replace(
|
||||
" browserContextId: t.Optional(t.String),",
|
||||
" browserContextId: t.String,", 1)),
|
||||
("a value removed from an Enum",
|
||||
lambda s: s.replace(
|
||||
"t.Enum(['reduce', 'no-preference'])",
|
||||
"t.Enum(['no-preference'])", 1)),
|
||||
("an event RENAMED",
|
||||
lambda s: s.replace(
|
||||
" 'ready': {", " 'renamedReady': {", 1)),
|
||||
("an event REMOVED",
|
||||
lambda s: s.replace(
|
||||
" 'crashed': {" + chr(10) + " }," + chr(10), "", 1)),
|
||||
]
|
||||
print("known-bad mutations on Protocol.js:")
|
||||
survived = 0
|
||||
for description, mutate in MUTATIONS:
|
||||
mutated = mutate(text)
|
||||
if mutated == text:
|
||||
print(" INERT MUTATION %-42s (did not touch the text)"
|
||||
% description)
|
||||
survived += 1
|
||||
continue
|
||||
try:
|
||||
different = body(render(parse_type(mutated), "base")) != body(base)
|
||||
except SystemExit as e:
|
||||
different, description = (
|
||||
True, description + " -> the generator REJECTS: %s" % e)
|
||||
if different:
|
||||
print(" killed %s" % description[:70])
|
||||
else:
|
||||
print(" SURVIVED %s" % description)
|
||||
survived += 1
|
||||
|
||||
print()
|
||||
print("and the cases that must NOT trigger:")
|
||||
false_positives = 0
|
||||
if body(render(parse_type(text), "another source")) == body(base):
|
||||
print(" PASSES same text, different source in the header")
|
||||
else:
|
||||
print(" WRONGLY REJECTED same text with another source")
|
||||
false_positives += 1
|
||||
# An extra space inside an empty block is a reformat, not a drift: if
|
||||
# the gate tripped here it would be red on every touch-up of the
|
||||
# source, and a gate that is always red teaches people to route
|
||||
# around it.
|
||||
reformatted = text.replace(" params: {},", " params: { },", 1)
|
||||
if reformatted == text:
|
||||
print(" WRONGLY REJECTED no empty block to reformat: "
|
||||
"case not exercised")
|
||||
false_positives += 1
|
||||
elif body(render(parse_type(reformatted), "base")) == body(base):
|
||||
print(" PASSES one extra space is not a drift")
|
||||
else:
|
||||
print(" WRONGLY REJECTED one extra space")
|
||||
false_positives += 1
|
||||
# And a new COMMENT is not a drift: the parser strips comments.
|
||||
commented = text.replace(
|
||||
"const Heap = {", "// a note\nconst Heap = {", 1)
|
||||
if (commented != text
|
||||
and body(render(parse_type(commented), "base")) == body(base)):
|
||||
print(" PASSES a new comment is not a drift")
|
||||
else:
|
||||
print(" WRONGLY REJECTED a new comment")
|
||||
false_positives += 1
|
||||
|
||||
print()
|
||||
print("survived: %d of %d, wrongly rejected: %d"
|
||||
% (survived, len(MUTATIONS), false_positives))
|
||||
return 1 if (survived or false_positives) else 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
here = pathlib.Path(__file__).resolve().parent.parent
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--binary", help="folder of the SHIPPED firefox")
|
||||
ap.add_argument("--proto",
|
||||
help="an already-extracted Protocol.js "
|
||||
"(for a jar that will not open)")
|
||||
ap.add_argument("--out", default=str(
|
||||
here / "src" / "invisible_playwright" / "_juggler" / "protocol.py"))
|
||||
ap.add_argument("--check", action="store_true",
|
||||
help="regenerate and compare, without writing")
|
||||
ap.add_argument("--selftest", action="store_true",
|
||||
help="known-bad mutations on Protocol.js, "
|
||||
"without a browser")
|
||||
a = ap.parse_args()
|
||||
|
||||
if a.proto:
|
||||
source, text = (
|
||||
a.proto,
|
||||
pathlib.Path(a.proto).read_bytes().decode("utf-8", "replace"))
|
||||
elif a.binary:
|
||||
source, text = protocol_source(a.binary)
|
||||
else:
|
||||
ap.error("need --binary (the shipped firefox) or --proto")
|
||||
|
||||
if a.selftest:
|
||||
return _selftest(text)
|
||||
|
||||
domains = parse_type(text)
|
||||
n_cmd = sum(len(d["commands"]) for d in domains.values())
|
||||
n_ev = sum(len(d["events"]) for d in domains.values())
|
||||
new = render(domains, source)
|
||||
|
||||
print("source: %s" % source)
|
||||
for domain in sorted(domains):
|
||||
print(" %-10s %3d commands %3d events"
|
||||
% (domain, len(domains[domain]["commands"]),
|
||||
len(domains[domain]["events"])))
|
||||
print(" %-10s %3d commands %3d events" % ("TOTAL", n_cmd, n_ev))
|
||||
|
||||
out = pathlib.Path(a.out)
|
||||
if a.check:
|
||||
if not out.is_file():
|
||||
print("MISSING: %s" % out)
|
||||
return 1
|
||||
old = out.read_bytes().decode("utf-8")
|
||||
# compares the BODY, not the header: the source line carries a
|
||||
# path that changes from one machine to another.
|
||||
def body(t):
|
||||
i = t.find("DOMAINS = ")
|
||||
return t[i:] if i >= 0 else t
|
||||
if body(old) == body(new):
|
||||
print("PROTOCOL ALIGNED")
|
||||
return 0
|
||||
print("DRIFT: the generated file does not match the shipped "
|
||||
"Protocol.js")
|
||||
return 1
|
||||
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_bytes(new.encode("utf-8"))
|
||||
print("wrote %s (%d bytes)" % (out, len(new)))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,317 +0,0 @@
|
||||
"""Extracts the US keyboard layout from the driver bundle into `_juggler/keylayout.py`.
|
||||
|
||||
⛔ NEVER HAND-EDIT THIS. `Page.dispatchKeyEvent` expects `key`, `code`,
|
||||
`keyCode` and `location` together, and there are ~230 entries: a
|
||||
hand-copied table has two ways to go wrong that no test catches. The
|
||||
first is a wrong `keyCode`, which the page reads back in
|
||||
`event.keyCode` without the action failing. The second, worse one, is
|
||||
an INCOMPLETE table: a missing key raises no error, it produces
|
||||
`keyCode: 0` for a key that on every real Firefox has a number, and
|
||||
that is a tell that lives in a field nobody looks at.
|
||||
|
||||
It has the same shape as `gen_juggler_protocol.py` and
|
||||
`gen_injected_source.py`: a single source, generated, never two
|
||||
numbers for the same thing (rule 16).
|
||||
|
||||
python scripts/gen_key_layout.py # regenerates _juggler/keylayout.py
|
||||
python scripts/gen_key_layout.py --check # 1 if the tree file is stale
|
||||
python scripts/gen_key_layout.py --selftest # 6 mutations, plus 2 that must NOT trigger
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||||
BUNDLE = ROOT / "src/invisible_playwright/_driver/package/lib/coreBundle.js"
|
||||
OUTPUT = ROOT / "src/invisible_playwright/_juggler/keylayout.py"
|
||||
|
||||
#: The literal starts here. ⛔ It anchors on the variable NAME, not on
|
||||
#: a table entry: anchoring on `"KeyA"` would tie the extraction to a
|
||||
#: key that could move to a different line someday.
|
||||
START = re.compile(r"USKeyboardLayout\s*=\s*\{")
|
||||
|
||||
|
||||
#: The escapes the bundle actually uses. Whatever is not here is
|
||||
#: passed through as-is, which is the right behavior for `\'` and
|
||||
#: `\"`: the escape disappears and the character remains.
|
||||
#:
|
||||
#: ⛔ SPELLED WITH `chr()`, and not because it reads better. A literal that
|
||||
#: EVALUATES to a control character is the same defect class as a Windows path
|
||||
#: written in a non-raw string: the bytes on disk look fine and the value the
|
||||
#: program uses is a formfeed. `test_marker_vocabulary.py` reads the resolved
|
||||
#: value with `ast` precisely to catch that, and it caught this table -
|
||||
#: correctly, because nothing here distinguishes a deliberate 0x08 from an
|
||||
#: accidental one except saying so.
|
||||
ESCAPES = {"n": chr(10), "r": chr(13), "t": chr(9), "b": chr(8),
|
||||
"f": chr(12), "0": chr(0), chr(92): chr(92)}
|
||||
|
||||
|
||||
class ExtractionFailed(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _literal(text: str) -> str:
|
||||
"""The balanced `{...}` body that follows `USKeyboardLayout =`.
|
||||
|
||||
⛔ Counts braces instead of looking for the first `};`: the value
|
||||
contains strings with braces inside (`"key": "{"` really exists,
|
||||
it is BracketLeft with shift) and a naive search would cut the
|
||||
table in half with no error.
|
||||
"""
|
||||
m = START.search(text)
|
||||
if not m:
|
||||
raise ExtractionFailed(
|
||||
"`USKeyboardLayout = {` does not appear in the bundle. If "
|
||||
"the bundler renamed the variable, the anchor should be "
|
||||
"changed here, not worked around.")
|
||||
i = m.end() - 1
|
||||
depth, j, in_str, quote, escape = 0, i, False, "", False
|
||||
while j < len(text):
|
||||
c = text[j]
|
||||
if in_str:
|
||||
if escape:
|
||||
escape = False
|
||||
elif c == chr(92):
|
||||
escape = True
|
||||
elif c == quote:
|
||||
in_str = False
|
||||
elif c in "\"'":
|
||||
in_str, quote = True, c
|
||||
elif c == "{":
|
||||
depth += 1
|
||||
elif c == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return text[i:j + 1]
|
||||
j += 1
|
||||
raise ExtractionFailed("unbalanced braces starting at USKeyboardLayout")
|
||||
|
||||
|
||||
def _to_json(literal: str) -> str:
|
||||
"""From JS literal to JSON, in a single pass that SCANS.
|
||||
|
||||
Three things a regex cannot do well, and all three show up in the
|
||||
real bundle:
|
||||
|
||||
1. ⛔ **Single quotes.** `"Quote": { "shiftKey": '"' }` is valid JS
|
||||
and JSON does not accept it. They must be rewritten as JSON
|
||||
strings, not substituted character by character: the content
|
||||
can contain a double quote, which is exactly this case.
|
||||
2. ⛔ **Comments.** Stripping them with `//[^\\n]*` also deletes a
|
||||
`//` INSIDE a string. It does not happen here, but the failure
|
||||
mode is silent - it shortens a value instead of raising an
|
||||
error - and it is not worth keeping.
|
||||
3. Trailing commas before a brace, which JS accepts and JSON does
|
||||
not.
|
||||
"""
|
||||
out, i = [], 0
|
||||
while i < len(literal):
|
||||
c = literal[i]
|
||||
if c == "/" and literal[i + 1:i + 2] == "/":
|
||||
i = literal.find("\n", i)
|
||||
if i < 0:
|
||||
break
|
||||
continue
|
||||
if c in "\"'":
|
||||
quote, j, inside = c, i + 1, []
|
||||
while j < len(literal):
|
||||
d = literal[j]
|
||||
if d == chr(92):
|
||||
# ⛔ It gets DECODED here instead of re-quoting the
|
||||
# raw text. Re-quoting it would double an already
|
||||
# escaped `\"`, and the character the bundle
|
||||
# writes with a single quote is exactly the double
|
||||
# quote.
|
||||
seg = literal[j + 1:j + 2]
|
||||
if seg == "u":
|
||||
inside.append(chr(int(literal[j + 2:j + 6], 16)))
|
||||
j += 6
|
||||
else:
|
||||
inside.append(ESCAPES.get(seg, seg))
|
||||
j += 2
|
||||
continue
|
||||
if d == quote:
|
||||
break
|
||||
inside.append(d)
|
||||
j += 1
|
||||
out.append(json.dumps("".join(inside)))
|
||||
i = j + 1
|
||||
continue
|
||||
out.append(c)
|
||||
i += 1
|
||||
return re.sub(r",(\s*[}\]])", r"\1", "".join(out))
|
||||
|
||||
|
||||
def extract(text: str) -> dict:
|
||||
data = json.loads(_to_json(_literal(text)))
|
||||
if not isinstance(data, dict) or not data:
|
||||
raise ExtractionFailed("the table is empty")
|
||||
# ⛔ The SANITY check is here and not in the caller: a table that
|
||||
# extracts but does not contain the keys every layout has is an
|
||||
# extraction that got lucky with the braces.
|
||||
missing = [k for k in ("KeyA", "Enter", "Backspace", "Digit0", "Space",
|
||||
"ShiftLeft", "ArrowLeft", "Tab", "Escape")
|
||||
if k not in data]
|
||||
if missing:
|
||||
raise ExtractionFailed(
|
||||
"extracted but incomplete: missing %s. It is not the US "
|
||||
"layout." % ", ".join(missing))
|
||||
return data
|
||||
|
||||
|
||||
def render(data: dict) -> str:
|
||||
body = json.dumps(data, indent=4, sort_keys=True, ensure_ascii=False)
|
||||
body = body.replace("true", "True").replace("false", "False") \
|
||||
.replace(": null", ": None")
|
||||
# ⛔ A control character in the DATA becomes `chr(n)`, never an escape.
|
||||
# `NumpadDecimal` really carries a NUL as its `key` upstream, and written
|
||||
# as an escape the generated file holds a literal that EVALUATES to 0x00 -
|
||||
# the defect class `test_marker_vocabulary.py` exists to catch, and it
|
||||
# cannot tell a deliberate NUL from a mangled Windows path. The pattern is
|
||||
# built from `chr(92)` so this source has no backslash of its own.
|
||||
body = re.sub(chr(92) + r'"' + chr(92) + chr(92) + r'u000([0-9a-fA-F])"',
|
||||
lambda m: "chr(%d)" % int(m.group(1), 16), body)
|
||||
return (
|
||||
'"""The US keyboard layout, EXTRACTED from the driver bundle.\n'
|
||||
"\n"
|
||||
"GENERATED by `python scripts/gen_key_layout.py`. Do not\n"
|
||||
"hand-edit: the `--check` gate rejects a tree where this file\n"
|
||||
"and the bundle no longer agree, and a hand-fixed entry would\n"
|
||||
"be undone on the next regenerate.\n"
|
||||
"\n"
|
||||
"Each entry is indexed by `code` (the PHYSICAL key) and\n"
|
||||
"carries `keyCode`, the unshifted `key` and, where it exists,\n"
|
||||
"`shiftKey`. That is what `Page.dispatchKeyEvent` expects:\n"
|
||||
"four fields together, and a wrong one does not fail the\n"
|
||||
"action - it just lies in `event.keyCode`.\n"
|
||||
'"""\n'
|
||||
"from __future__ import annotations\n"
|
||||
"\n"
|
||||
"#: %d entries, indexed by `code`.\n" % len(data) +
|
||||
"LAYOUT = " + body + "\n"
|
||||
"\n"
|
||||
"#: unshifted `key` -> `code`. Used for `press(\"a\")` and for\n"
|
||||
"#: typing: a character is looked up here first, then among\n"
|
||||
"#: the shifted ones.\n"
|
||||
"BY_KEY = {v[\"key\"]: k for k, v in LAYOUT.items() if \"key\" in v}\n"
|
||||
"\n"
|
||||
"#: `shiftKey` -> `code`. `A`, `!`, `{` live here and NOT in\n"
|
||||
"#: BY_KEY.\n"
|
||||
"BY_SHIFTED_KEY = {v[\"shiftKey\"]: k for k, v in LAYOUT.items()\n"
|
||||
" if \"shiftKey\" in v}\n")
|
||||
|
||||
|
||||
# ── the selftest ──────────────────────────────────────────────────────────
|
||||
def selftest() -> int:
|
||||
good = ('var x = 1;\n'
|
||||
'USKeyboardLayout = {\n'
|
||||
' // first line\n'
|
||||
' "KeyA": { "keyCode": 65, "shiftKey": "A", "key": "a" },\n'
|
||||
' "Digit0": { "keyCode": 48, "shiftKey": ")", "key": "0" },\n'
|
||||
' "BracketLeft": { "keyCode": 219, "shiftKey": "{", "key": "[" },\n'
|
||||
' "Enter": { "keyCode": 13, "key": "Enter", "text": "\\r" },\n'
|
||||
' "Backspace": { "keyCode": 8, "key": "Backspace" },\n'
|
||||
' "Space": { "keyCode": 32, "key": " " },\n'
|
||||
' "ShiftLeft": { "keyCode": 16, "key": "Shift", "location": 1 },\n'
|
||||
' "ArrowLeft": { "keyCode": 37, "key": "ArrowLeft" },\n'
|
||||
' "Tab": { "keyCode": 9, "key": "Tab" },\n'
|
||||
' "Escape": { "keyCode": 27, "key": "Escape" },\n'
|
||||
'};\nvar after = 2;\n')
|
||||
|
||||
def try_case(name, text, should_raise=True):
|
||||
try:
|
||||
d = extract(text)
|
||||
except Exception as e:
|
||||
if should_raise:
|
||||
print(" killed: %s (%s)" % (name, str(e).splitlines()[0][:60]))
|
||||
return 0
|
||||
print(" FALSE POSITIVE: %s -> %s" % (name, e))
|
||||
return 1
|
||||
if should_raise:
|
||||
print(" SURVIVED: %s -> extracted %d entries" % (name, len(d)))
|
||||
return 1
|
||||
print(" silenced: %s (%d entries)" % (name, len(d)))
|
||||
return 0
|
||||
|
||||
print("--- mutations that MUST trigger ---")
|
||||
bad = 0
|
||||
bad += try_case("the variable renamed by the bundler",
|
||||
good.replace("USKeyboardLayout", "UsKbLayout"))
|
||||
bad += try_case("the table truncated: keys every layout has are missing",
|
||||
'USKeyboardLayout = {\n "KeyA": { "keyCode": 65, "key": "a" },\n};')
|
||||
bad += try_case("unbalanced braces",
|
||||
good.replace('"Escape": { "keyCode": 27, "key": "Escape" },\n};',
|
||||
'"Escape": { "keyCode": 27, "key": "Escape" },\n'))
|
||||
bad += try_case("the empty table",
|
||||
good[:good.index("{", good.index("USKeyboardLayout")) + 1] + "};")
|
||||
# ⛔ This is the mutation that justified counting braces: with a
|
||||
# search for the first `};` the table gets cut at BracketLeft,
|
||||
# which contains a brace INSIDE a string, and the extraction
|
||||
# half-succeeds.
|
||||
truncated = good.replace('"Enter": { "keyCode": 13, "key": "Enter", "text": "\\r" },\n', "")
|
||||
bad += try_case("Enter removed: incomplete but syntactically valid", truncated)
|
||||
bad += try_case("the literal replaced by an array",
|
||||
good.replace("USKeyboardLayout = {", "USKeyboardLayout = ["))
|
||||
|
||||
print("--- cases that must NOT trigger ---")
|
||||
bad += try_case("the good bundle", good, should_raise=False)
|
||||
bad += try_case("a brace inside a string does not close the table",
|
||||
good.replace('"shiftKey": "{"', '"shiftKey": "}"'),
|
||||
should_raise=False)
|
||||
print()
|
||||
print("selftest: %s" % ("ALL GOOD" if not bad else "%d PROBLEMS" % bad))
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
p.add_argument("--check", action="store_true")
|
||||
p.add_argument("--selftest", action="store_true")
|
||||
a = p.parse_args()
|
||||
if a.selftest:
|
||||
return selftest()
|
||||
bundle = BUNDLE
|
||||
named = os.environ.get("INVPW_DRIVER_BUNDLE")
|
||||
if named:
|
||||
bundle = pathlib.Path(named)
|
||||
if not bundle.exists():
|
||||
# ⛔ TWO IS NOT ENOUGH HERE: "cannot compare" and "stale" are
|
||||
# different answers, and collapsing them makes a missing bundle look
|
||||
# like a broken tree. The generated file is COMMITTED and stays valid
|
||||
# without a bundle; what is lost is the ability to re-derive it, and
|
||||
# that is what this says.
|
||||
print("NOT COMPARABLE: no driver bundle at %s." % bundle)
|
||||
print(" The generated file is committed and still valid - what is "
|
||||
"gone is the ability to re-derive it.")
|
||||
print(" To get one back: git worktree add <dir> <the last commit "
|
||||
"that carried _driver/>, then")
|
||||
print(" INVPW_DRIVER_BUNDLE=<dir>/src/invisible_playwright/_driver/"
|
||||
"package/lib/coreBundle.js")
|
||||
return 2
|
||||
try:
|
||||
data = extract(bundle.read_text(encoding="utf-8", errors="replace"))
|
||||
except ExtractionFailed as failure:
|
||||
print("extraction failed: %s" % failure)
|
||||
return 2
|
||||
text = render(data)
|
||||
if a.check:
|
||||
current = OUTPUT.read_bytes().decode("utf-8") if OUTPUT.exists() else ""
|
||||
if current != text:
|
||||
print("keylayout.py does not match the bundle (%d entries "
|
||||
"extracted). `python scripts/gen_key_layout.py`" % len(data))
|
||||
return 1
|
||||
print("keylayout.py matches: %d entries" % len(data))
|
||||
return 0
|
||||
# ⛔ `write_bytes`: `write_text` on Windows would translate every newline.
|
||||
OUTPUT.write_bytes(text.encode("utf-8"))
|
||||
print("wrote %s: %d entries" % (OUTPUT.name, len(data)))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -37,6 +37,13 @@ import urllib.error
|
||||
# Conventional-commit prefixes that never belong in user-facing release notes.
|
||||
_SKIP = re.compile(r"^(docs|chore|ci|test|style|build)(\(|:)", re.I)
|
||||
|
||||
#: Where the install commands live. ⛔ NOT RESTATED HERE: the body used to carry
|
||||
#: its own `pip install invisible-playwright`, a second copy of the README's
|
||||
#: install block that nothing kept in step with it. A command written in two
|
||||
#: places is two commands the day one of them changes; the release points at the
|
||||
#: one the README keeps.
|
||||
INSTALL_DOC = "https://github.com/feder-cr/invisible_playwright#install"
|
||||
|
||||
|
||||
def _api(url: str, token: str | None) -> dict:
|
||||
headers = {"Accept": "application/vnd.github+json",
|
||||
@@ -102,12 +109,10 @@ def build_body(tag: str, current_sha: str, bullets: list[str],
|
||||
parts += [f"- {b}" for b in bullets]
|
||||
parts.append("")
|
||||
parts += [
|
||||
"Builds: Linux x86_64, Linux arm64, Windows x86_64.",
|
||||
"Builds: Linux x86_64, Windows x86_64.",
|
||||
"",
|
||||
"Most people won't grab these by hand. The wrapper fetches the right one for "
|
||||
"your platform on first run:",
|
||||
"",
|
||||
" pip install invisible-playwright",
|
||||
"your platform on first run; how to install it is in " + INSTALL_DOC + ".",
|
||||
"",
|
||||
"If you do download manually, `checksums.txt` has the SHA256s.",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"identity": [
|
||||
{"keys": ["surface.screen.*", "surface.window.innerWidth", "surface.window.innerHeight",
|
||||
"surface.window.outerWidth", "surface.window.outerHeight", "surface.window.screen*",
|
||||
"surface.window.mozInnerScreen*", "surface.visualViewport.width", "surface.visualViewport.height",
|
||||
"surface.computedStyle.body.width", "surface.computedStyle.body.inline-size",
|
||||
"surface.computedStyle.body.perspective-origin", "surface.computedStyle.body.transform-origin"],
|
||||
"why": "the declared screen and window; the body is as wide as the window"},
|
||||
{"keys": ["state.*.innerWidth", "state.*.innerHeight", "state.*.outerWidth", "state.*.outerHeight",
|
||||
"state.*.screenX", "state.*.screenY", "state.*.screen.*", "state.*.mozInnerScreen*", "state.*.events.*"],
|
||||
"why": "the declared screen and window in each driven state (ci_host_gate.py INVARIANTS hold their relations); an event's screen - client is where the window puts the viewport"},
|
||||
{"keys": ["surface.navigator.hardwareConcurrency", "surface.worker.hc"],
|
||||
"why": "the declared core count"},
|
||||
{"keys": ["surface.voices"],
|
||||
"why": "the declared speech voices"},
|
||||
{"keys": ["surface.webgl*.unmasked", "surface.webgl*.parameters.RENDERER",
|
||||
"surface.webgl*.extension_parameters.WEBGL_debug_renderer_info.*",
|
||||
"surface.webgl*.parameters.MAX_*", "surface.webgl*.extension_parameters.*.MAX_*",
|
||||
"surface.webgpu.adapters.*"],
|
||||
"why": "the declared GPU: its name and its limits (ANGLE gives NVIDIA one vertex uniform vector less)"}
|
||||
],
|
||||
"noise": [],
|
||||
"network": [],
|
||||
"measurement": [
|
||||
{"keys": ["surface.document.hasFocus"],
|
||||
"why": "retail was measured on a hidden desktop, where its window never has focus"}
|
||||
],
|
||||
"known_defects": [
|
||||
{"keys": ["blend.*", "text.canvas.*", "text.char.*", "text.emoji.*", "text.fallback.*",
|
||||
"text.pixelscan.*", "text.svg.*", "text.metrics.*.width", "text.metrics.*.actualBoundingBoxLeft",
|
||||
"text.metrics.*.actualBoundingBoxRight", "text.fallbackwidth.*.serif",
|
||||
"text.fallbackwidth.*.monospace"],
|
||||
"why": "phase 4: text from idwr (DWrite 26100) on every OS; today Windows asks the host's DWrite and Linux FreeType. Only the rasterised glyphs, their advances and ink extents and the serif/monospace fallback widths differ (firefox-59 dumps): text.adjust, text.fonts, text.rect, text.units and the vertical metrics are held"},
|
||||
{"keys": ["control.webgl1", "control.webgl2"], "legs": ["linux-x86_64", "linux-x86_64-debian12"],
|
||||
"why": "WebGL draws through the host's driver (llvmpipe here, ANGLE on Windows); a host-independent rasterizer is its own project"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
<!doctype html>
|
||||
<meta charset=utf-8>
|
||||
<title>host-gate</title>
|
||||
<body>
|
||||
<script>
|
||||
// host-gate/1: everything a page can read that the theory says is f(identity, Firefox code).
|
||||
// TEXT (text.*), CONTROL (control.*), BLEND (blend.*), SURFACE (surface.*): whole APIs, not chosen fields.
|
||||
// noise.*: only what varies between two launches of the same official build.
|
||||
// diag.*: information for the job log (why a host answers what it does); the gate never compares it.
|
||||
// Must be served from a secure context (http://127.0.0.1 or https) for WebGPU and media APIs.
|
||||
(async () => {
|
||||
const G = {format: 'host-gate/1', meta: {devicePixelRatio: window.devicePixelRatio, userAgent: navigator.userAgent}, items: {}, noise: {}};
|
||||
const put = (k, v) => { G.items[k] = v; };
|
||||
const noise = (k, v) => { G.noise[k] = v; };
|
||||
const errs = e => 'ERR ' + ((e && e.name) || '') + ': ' + ((e && e.message) || String(e));
|
||||
const safe = async (k, f) => { try { put(k, await f()); } catch (e) { put(k, errs(e)); } };
|
||||
const b64 = u8 => { let s = ''; for (let i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000)); return btoa(s); };
|
||||
const alphaOf = (g, w, h) => { const d = g.getImageData(0, 0, w, h).data, a = new Uint8Array(w * h); for (let i = 0; i < a.length; i++) a[i] = d[i * 4 + 3]; return a; };
|
||||
const img = (g, w, h, rgba) => ({w, h, enc: rgba ? 'rgba8' : 'alpha8', data: rgba ? b64(new Uint8Array(g.getImageData(0, 0, w, h).data.buffer)) : b64(alphaOf(g, w, h))});
|
||||
const canvas = (w, h, fn) => { const c = document.createElement('canvas'); c.width = w; c.height = h; const g = c.getContext('2d'); fn(g, c); return [g, c]; };
|
||||
// a plain, comparable copy of any object: own + inherited enumerable data, functions as "function"
|
||||
const plain = (o, depth = 2) => {
|
||||
if (o === null || o === undefined) return o;
|
||||
const t = typeof o;
|
||||
if (t === 'number' || t === 'string' || t === 'boolean') return o;
|
||||
if (t === 'function') return 'function';
|
||||
if (t === 'bigint') return String(o);
|
||||
if (depth < 0) return '…';
|
||||
if (Array.isArray(o) || ArrayBuffer.isView(o)) return Array.from(o, v => plain(v, depth - 1));
|
||||
const out = {}; for (const k in o) { try { out[k] = plain(o[k], depth - 1); } catch (e) { out[k] = errs(e); } }
|
||||
return out;
|
||||
};
|
||||
const names = o => { try { return Object.getOwnPropertyNames(o).sort(); } catch (e) { return errs(e); } };
|
||||
|
||||
// ================================================================= TEXT
|
||||
const PIX = "\u{1F6CD}1>'`amlρiюदे來˦\u{25578}に◌\u{2003E}ԩԨ";
|
||||
const FONTS = ['Segoe UI', 'Arial', 'Times New Roman', 'Calibri', 'Consolas', 'Microsoft New Tai Lue', 'Myanmar Text', 'Microsoft PhagsPa',
|
||||
'Segoe UI Emoji', 'Segoe UI Symbol', 'sans-serif', 'serif', 'monospace', 'system-ui'];
|
||||
const PPEM = [4, 5, 6, 7, 8, 9, 10, 11, 12, 16, 20, 32];
|
||||
const TEXTS = {H: 'H', o: 'o', word: 'Hamburgefonstiv', digits: '0123456789', pixelscan: PIX};
|
||||
const fam = f => /^(sans-serif|serif|monospace|system-ui)$/.test(f) ? f : `"${f}"`;
|
||||
const drawText = (font, px, s, rgba) => {
|
||||
const p = document.createElement('canvas').getContext('2d'); p.font = `${px}px ${font}`;
|
||||
const w = Math.ceil(p.measureText(s).width) + 8, h = Math.ceil(px * 2) + 4;
|
||||
const [g] = canvas(w, h, g => { g.fillStyle = 'black'; g.font = `${px}px ${font}`; g.fillText(s, 4, Math.ceil(px) + 2); });
|
||||
return img(g, w, h, rgba);
|
||||
};
|
||||
const TM = ['width', 'actualBoundingBoxLeft', 'actualBoundingBoxRight', 'actualBoundingBoxAscent', 'actualBoundingBoxDescent',
|
||||
'fontBoundingBoxAscent', 'fontBoundingBoxDescent', 'emHeightAscent', 'emHeightDescent', 'hangingBaseline', 'alphabeticBaseline', 'ideographicBaseline'];
|
||||
const metrics = (font, px, s) => { const g = document.createElement('canvas').getContext('2d'); g.font = `${px}px ${font}`; const m = g.measureText(s);
|
||||
return Object.fromEntries(TM.map(k => [k, m[k]])); };
|
||||
for (const f of FONTS) { const F = fam(f);
|
||||
for (const px of PPEM) for (const [t, s] of Object.entries(TEXTS)) { put(`text.canvas.${f}.${px}.${t}`, drawText(F, px, s)); put(`text.metrics.${f}.${px}.${t}`, metrics(F, px, s)); }
|
||||
for (const px of [4, 8, 16]) [...PIX].forEach((ch, i) => put(`text.char.${f}.${px}.${i}`, drawText(F, px, ch)));
|
||||
}
|
||||
const EMOJI = {shop: '\u{1F6CD}', grin: '\u{1F600}', flag: '\u{1F1EE}\u{1F1F9}', family: '\u{1F468}\u{1F469}\u{1F467}', heart: '❤️', skin: '\u{1F44D}\u{1F3FD}'};
|
||||
for (const f of ['Segoe UI Emoji', 'sans-serif']) for (const px of [8, 16, 32]) for (const [n, s] of Object.entries(EMOJI)) put(`text.emoji.${f}.${px}.${n}`, drawText(fam(f), px, s, true));
|
||||
const PIXFONTS = ['Arial', 'Calibri', 'Cambria Math', 'Cambria', 'Candara', 'Comic Sans MS', 'Consolas', 'Constantia', 'Corbel', 'Courier New', 'Ebrima', 'Franklin Gothic', 'Gabriola', 'Georgia', 'Impact', 'Lucida Console', 'Lucida Sans Unicode', 'MS Gothic', 'MS PGothic', 'MV Boli', 'Malgun Gothic', 'Marlett', 'Microsoft Himalaya', 'Microsoft JhengHei', 'Microsoft New Tai Lue', 'Microsoft PhagsPa', 'Microsoft Sans Serif', 'Microsoft YaHei', 'Microsoft Yi Baiti', 'MingLiU-ExtB', 'Mongolian Baiti', 'PMingLiU-ExtB', 'Palatino Linotype', 'Segoe Print', 'Segoe Script', 'Segoe UI Symbol', 'Segoe UI', 'SimSun', 'SimSun-ExtB', 'Sylfaen', 'Trebuchet MS', 'Verdana', 'Webdings', 'Gadugi', 'Javanese Text', 'Microsoft JhengHei UI', 'Myanmar Text', 'Sitka Small', 'Yu Gothic'];
|
||||
{ const seen = new Set();
|
||||
for (const f of PIXFONTS) { const [g] = canvas(80, 10, g => { g.fillStyle = 'red'; g.font = 'normal 4px ' + f; g.fillText(PIX, 5, 5); });
|
||||
const a = img(g, 80, 10); put(`text.pixelscan.${f}`, a); seen.add(a.data); }
|
||||
put('text.pixelscan.distinct', seen.size); }
|
||||
{ const box = document.createElement('div'); box.style.cssText = 'position:absolute;left:0;top:0;white-space:nowrap'; document.body.appendChild(box);
|
||||
const span = (css, s) => { const e = document.createElement('span'); e.style.cssText = css; e.textContent = s; box.appendChild(e); const r = e.getBoundingClientRect();
|
||||
const out = [r.x, r.y, r.width, r.height, e.offsetWidth, e.offsetHeight]; e.remove(); return out; };
|
||||
for (const f of FONTS) { const F = fam(f).replace(/"/g, "'");
|
||||
for (const [t, s] of Object.entries(TEXTS)) put(`text.rect.${f}.${t}`, span(`font:16px ${F}`, s));
|
||||
const u = {}; for (const unit of ['ex', 'cap', 'ch', 'ic', 'lh', 'rex', 'rcap', 'rch', 'ric', 'rlh']) { const e = document.createElement('div'); e.style.cssText = `font:16px ${F};width:1${unit};height:1px`;
|
||||
box.appendChild(e); u[unit] = e.getBoundingClientRect().width; e.remove(); } put(`text.units.${f}`, u);
|
||||
for (const mode of ['0.5', 'ex-height 0.5', 'cap-height 0.7', 'ch-width 0.6', 'ic-width 1', 'from-font'])
|
||||
put(`text.adjust.${f}.${mode}`, span(`font:16px ${F};font-size-adjust:${mode}`, TEXTS.word));
|
||||
}
|
||||
box.remove(); }
|
||||
put('text.fonts.check', Object.fromEntries([...new Set([...FONTS, ...PIXFONTS])].map(f => [f, document.fonts.check(`16px ${fam(f)}`)])));
|
||||
put('text.fonts.size', document.fonts.size);
|
||||
const svgDraw = (attr, family, s) => new Promise(res => {
|
||||
const src = `<svg xmlns="http://www.w3.org/2000/svg" width="240" height="40"><text x="4" y="26" font-family="${family}" font-size="18" ${attr}>${s}</text></svg>`;
|
||||
const im = new Image(); im.onload = () => { const [g] = canvas(240, 40, g => g.drawImage(im, 0, 0)); try { res(img(g, 240, 40)); } catch (e) { res(errs(e)); } };
|
||||
im.onerror = () => res('ERR load'); im.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(src); });
|
||||
for (const f of ['Segoe UI', 'Arial', 'Times New Roman', 'serif'])
|
||||
for (const [n, a] of Object.entries({plain: '', underline: 'text-decoration="underline"', linethrough: 'text-decoration="line-through"', overline: 'text-decoration="overline"'}))
|
||||
put(`text.svg.${f}.${n}`, await svgDraw(a, f, TEXTS.word));
|
||||
put('text.svg.emoji', await svgDraw('', 'Segoe UI Emoji', EMOJI.grin + EMOJI.flag));
|
||||
const SCRIPTS = {latin: 'Hamburg', greek: 'αβγδε', cyrillic: 'жизнь', arabic: 'مرحبا', hebrew: 'שלום', devanagari: 'नमस्ते', bengali: 'বাংলা',
|
||||
thai: 'สวัสดี', lao: 'ສະບາຍ', khmer: 'សួស្តី', myanmar: 'မင်္ဂလာ', sinhala: 'සිංහල', tamil: 'தமிழ்', ethiopic: 'ሰላም', tibetan: 'བོད་ཡིག',
|
||||
georgian: 'ქართული', armenian: 'Հայերեն', cjk: '漢字中文', cjkextb: '\u{20000}\u{25578}', hiragana: 'ひらがな', hangul: '한국어', mongolian: 'ᠮᠣᠩᠭᠣᠯ',
|
||||
cherokee: 'ᏣᎳᎩ', math: '∑∫√∞≠', arrows: '←↑→↓↔', box: '┌─┐│└┘', pua: '', symbols: '☀☂☃★♠'};
|
||||
for (const g of ['sans-serif', 'serif', 'monospace']) for (const [n, s] of Object.entries(SCRIPTS)) {
|
||||
put(`text.fallback.${n}.${g}`, drawText(g, 16, s)); put(`text.fallbackwidth.${n}.${g}`, metrics(g, 16, s).width); }
|
||||
|
||||
// ================================================================= CONTROL (no text)
|
||||
const ctl = (k, w, h, fn) => { const [g] = canvas(w, h, fn); put(`control.${k}`, img(g, w, h, true)); };
|
||||
ctl('rects', 64, 64, g => { g.fillStyle = '#c33'; g.fillRect(3.5, 3.5, 30, 20); g.strokeStyle = 'rgba(0,80,200,.6)'; g.lineWidth = 2.5; g.strokeRect(10.25, 15.75, 40, 30); });
|
||||
ctl('arcs', 64, 64, g => { g.beginPath(); g.arc(32, 32, 20.3, 0, Math.PI * 1.7); g.lineWidth = 3; g.strokeStyle = '#080'; g.stroke();
|
||||
g.beginPath(); g.ellipse(30, 30, 12, 7, 0.6, 0, 2 * Math.PI); g.fillStyle = 'rgba(200,100,0,.5)'; g.fill(); });
|
||||
ctl('beziers', 64, 64, g => { g.beginPath(); g.moveTo(2, 60); g.bezierCurveTo(10, 0, 50, 70, 62, 4); g.quadraticCurveTo(40, 40, 5, 30);
|
||||
g.lineWidth = 1.7; g.lineJoin = 'round'; g.lineCap = 'round'; g.setLineDash([4, 3]); g.stroke(); });
|
||||
ctl('linear', 64, 32, g => { const l = g.createLinearGradient(0, 0, 64, 32); l.addColorStop(0, '#f00'); l.addColorStop(.5, 'rgba(0,255,0,.5)'); l.addColorStop(1, '#00f'); g.fillStyle = l; g.fillRect(0, 0, 64, 32); });
|
||||
ctl('radial', 64, 64, g => { const r = g.createRadialGradient(20, 20, 2, 32, 32, 30); r.addColorStop(0, '#fff'); r.addColorStop(1, '#048'); g.fillStyle = r; g.fillRect(0, 0, 64, 64); });
|
||||
ctl('conic', 64, 64, g => { const c = g.createConicGradient(0.3, 32, 32); c.addColorStop(0, 'red'); c.addColorStop(.5, 'yellow'); c.addColorStop(1, 'red'); g.fillStyle = c; g.fillRect(0, 0, 64, 64); });
|
||||
ctl('pattern', 64, 64, g => { const [, p] = canvas(5, 5, h => { h.fillStyle = '#123'; h.fillRect(0, 0, 3, 3); }); g.fillStyle = g.createPattern(p, 'repeat'); g.translate(.5, .3); g.rotate(.2); g.fillRect(0, 0, 70, 70); });
|
||||
ctl('shadow', 64, 64, g => { g.shadowColor = 'rgba(0,0,0,.6)'; g.shadowBlur = 6; g.shadowOffsetX = 3; g.shadowOffsetY = 2; g.fillStyle = '#e91'; g.fillRect(12, 12, 30, 30); });
|
||||
for (const op of ['source-over', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity', 'xor', 'lighter'])
|
||||
ctl(`composite.${op}`, 32, 32, g => { g.fillStyle = 'rgba(30,140,220,.8)'; g.fillRect(2, 2, 20, 20); g.globalCompositeOperation = op; g.fillStyle = 'rgba(240,60,40,.7)'; g.beginPath(); g.arc(20, 20, 10, 0, 7); g.fill(); });
|
||||
ctl('image_scaled', 48, 48, g => { const [, s] = canvas(7, 7, h => { for (let i = 0; i < 49; i++) { h.fillStyle = `rgb(${i * 5},${255 - i * 5},${(i * 37) % 255})`; h.fillRect(i % 7, (i / 7) | 0, 1, 1); } });
|
||||
g.imageSmoothingEnabled = true; g.imageSmoothingQuality = 'high'; g.drawImage(s, 0, 0, 48, 48); });
|
||||
ctl('filter', 48, 48, g => { g.filter = 'blur(2px) hue-rotate(40deg)'; g.fillStyle = '#3a6'; g.fillRect(8, 8, 30, 30); });
|
||||
{ // toDataURL: the PNG with its per-launch "deBG" chunk taken out (that chunk is noise.png_deBG)
|
||||
const [, c] = canvas(16, 16, g => { g.fillStyle = 'rgba(10,20,30,.5)'; g.fillRect(1, 1, 9, 9); });
|
||||
const bin = atob(c.toDataURL().split(',')[1]); const u = Uint8Array.from(bin, ch => ch.charCodeAt(0));
|
||||
const keep = [u.subarray(0, 8)]; let i = 8, deBG = null;
|
||||
while (i < u.length) { const n = (u[i] << 24 | u[i + 1] << 16 | u[i + 2] << 8 | u[i + 3]) >>> 0; const t = String.fromCharCode(...u.subarray(i + 4, i + 8));
|
||||
if (t === 'deBG') deBG = String.fromCharCode(...u.subarray(i + 8, i + 8 + n)); else keep.push(u.subarray(i, i + 12 + n)); i += 12 + n; }
|
||||
const out = new Uint8Array(keep.reduce((a, x) => a + x.length, 0)); let o = 0; for (const k of keep) { out.set(k, o); o += k.length; }
|
||||
put('control.toDataURL', {w: 16, h: 16, enc: 'png', data: b64(out)});
|
||||
put('control.toDataURL_deBG_shape', deBG === null ? 'absent' : (/^[0-9A-F]{16}$/.test(deBG) ? 'hex16' : 'other:' + deBG.length));
|
||||
noise('png_deBG', deBG); }
|
||||
const glScene = version => { const c = document.createElement('canvas'); c.width = 32; c.height = 32;
|
||||
const gl = c.getContext(version, {preserveDrawingBuffer: true, antialias: false}); if (!gl) return 'no ' + version;
|
||||
const sh = (type, src) => { const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s); return s; };
|
||||
const pr = gl.createProgram(); gl.attachShader(pr, sh(gl.VERTEX_SHADER, 'attribute vec2 p; varying vec2 v; void main(){ v = p; gl_Position = vec4(p, 0.0, 1.0); }'));
|
||||
gl.attachShader(pr, sh(gl.FRAGMENT_SHADER, 'precision mediump float; varying vec2 v; void main(){ gl_FragColor = vec4(fract(v.x*3.7), abs(sin(v.y*5.0)), 0.5+0.5*v.x*v.y, 1.0); }'));
|
||||
gl.linkProgram(pr); gl.useProgram(pr);
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-0.9, -0.8, 0.85, -0.7, 0.1, 0.95]), gl.STATIC_DRAW);
|
||||
const loc = gl.getAttribLocation(pr, 'p'); gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
|
||||
gl.clearColor(0.1, 0.2, 0.3, 1); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 3);
|
||||
const px = new Uint8Array(32 * 32 * 4); gl.readPixels(0, 0, 32, 32, gl.RGBA, gl.UNSIGNED_BYTE, px); return {w: 32, h: 32, enc: 'rgba8', data: b64(px)}; };
|
||||
put('control.webgl1', glScene('webgl')); put('control.webgl2', glScene('webgl2'));
|
||||
|
||||
// ================================================================= BLEND (Skia CPU blending of text)
|
||||
const BL = {red: g => { g.fillStyle = '#d22'; }, alpha: g => { g.fillStyle = 'rgba(0,0,0,.45)'; }, global: g => { g.globalAlpha = .6; g.fillStyle = '#226'; },
|
||||
overcolour: g => { g.fillStyle = '#9cf'; g.fillRect(0, 0, 200, 40); g.fillStyle = 'rgba(200,30,30,.7)'; }};
|
||||
for (const f of ['Segoe UI', 'Arial', 'Times New Roman']) for (const px of [8, 16]) for (const [n, set] of Object.entries(BL)) {
|
||||
const [g] = canvas(200, 40, g => { set(g); g.font = `${px}px "${f}"`; g.fillText('Hamburgefonstiv 0123', 4, 26); }); put(`blend.${f}.${px}.${n}`, img(g, 200, 40, true)); }
|
||||
|
||||
// ================================================================= SURFACE (whole APIs)
|
||||
put('surface.window_own', names(window));
|
||||
for (const n of ['Navigator', 'Document', 'HTMLDocument', 'Element', 'HTMLElement', 'Node', 'EventTarget', 'Screen', 'ScreenOrientation', 'Performance',
|
||||
'HTMLCanvasElement', 'CanvasRenderingContext2D', 'OffscreenCanvas', 'WebGLRenderingContext', 'WebGL2RenderingContext', 'AudioContext', 'BaseAudioContext',
|
||||
'MediaDevices', 'Permissions', 'Notification', 'GPU', 'GPUAdapter', 'GPUDevice', 'StorageManager', 'Crypto', 'SubtleCrypto', 'CSS', 'History', 'Location',
|
||||
'PluginArray', 'MimeTypeArray', 'MouseEvent', 'PointerEvent', 'KeyboardEvent', 'Worker', 'ServiceWorkerContainer', 'RTCPeerConnection', 'SpeechSynthesis',
|
||||
'VisualViewport', 'FontFaceSet', 'Clipboard', 'ImageDecoder', 'VideoDecoder', 'AudioDecoder', 'VideoEncoder', 'WebTransport', 'LockManager', 'WakeLock', 'Gamepad',
|
||||
'Scheduler', 'CookieStore', 'NetworkInformation', 'MediaCapabilities', 'MediaSource', 'MediaRecorder', 'IntersectionObserver', 'ResizeObserver', 'TextMetrics',
|
||||
'CustomElementRegistry', 'Window'])
|
||||
put(`surface.proto.${n}`, typeof window[n] === 'undefined' ? 'absent' : (window[n].prototype ? names(window[n].prototype) : names(window[n])));
|
||||
put('surface.navigator', plain(navigator, 1));
|
||||
put('surface.navigator.plugins', [...navigator.plugins].map(p => [p.name, p.filename, p.description, [...p].map(m => m.type)]));
|
||||
put('surface.navigator.mimeTypes', [...navigator.mimeTypes].map(m => [m.type, m.suffixes, m.description]));
|
||||
put('surface.screen', plain(screen, 1));
|
||||
put('surface.screen.orientation', screen.orientation ? [screen.orientation.type, screen.orientation.angle] : 'absent');
|
||||
put('surface.window', Object.fromEntries(['innerWidth', 'innerHeight', 'outerWidth', 'outerHeight', 'screenX', 'screenY', 'screenLeft', 'screenTop',
|
||||
'devicePixelRatio', 'mozInnerScreenX', 'mozInnerScreenY', 'scrollMaxX', 'scrollMaxY', 'isSecureContext', 'crossOriginIsolated', 'name', 'closed', 'length']
|
||||
.map(k => [k, window[k]])));
|
||||
// the origin without its port: the port is the gate server's, not the browser's
|
||||
put('surface.window.origin_scheme_host', location.protocol + '//' + location.hostname);
|
||||
put('surface.visualViewport', window.visualViewport ? plain(visualViewport, 0) : 'absent');
|
||||
put('surface.document', Object.fromEntries(['characterSet', 'compatMode', 'contentType', 'designMode', 'dir', 'visibilityState', 'hidden', 'fullscreenEnabled',
|
||||
'pictureInPictureEnabled', 'pointerLockElement', 'hasStorageAccess'].map(k => [k, typeof document[k] === 'function' ? 'function' : document[k]])));
|
||||
put('surface.document.hasFocus', document.hasFocus());
|
||||
{ const Q = {}; const feat = {'prefers-color-scheme': ['light', 'dark'], 'prefers-reduced-motion': ['no-preference', 'reduce'], 'prefers-contrast': ['no-preference', 'more', 'less', 'custom'],
|
||||
'prefers-reduced-transparency': ['no-preference', 'reduce'], 'forced-colors': ['none', 'active'], 'inverted-colors': ['none', 'inverted'], pointer: ['none', 'coarse', 'fine'],
|
||||
hover: ['none', 'hover'], 'any-pointer': ['none', 'coarse', 'fine'], 'any-hover': ['none', 'hover'], 'color-gamut': ['srgb', 'p3', 'rec2020'], 'dynamic-range': ['standard', 'high'],
|
||||
'video-dynamic-range': ['standard', 'high'], 'display-mode': ['browser', 'fullscreen', 'standalone', 'minimal-ui'], update: ['none', 'slow', 'fast'], scripting: ['none', 'initial-only', 'enabled'],
|
||||
'overflow-block': ['none', 'scroll', 'paged'], 'overflow-inline': ['none', 'scroll'], orientation: ['portrait', 'landscape'], grid: ['0', '1'], monochrome: ['0'],
|
||||
'-moz-platform': ['windows', 'macos', 'linux', 'android'], '-moz-windows-non-native-menus': ['0', '1'], '-moz-overlay-scrollbars': ['0', '1'], 'prefers-reduced-data': ['no-preference', 'reduce']};
|
||||
for (const [f, vs] of Object.entries(feat)) Q[f] = vs.filter(v => matchMedia(`(${f}: ${v})`).matches);
|
||||
for (const f of ['color', 'color-index', 'resolution', 'device-pixel-ratio']) Q['supports-' + f] = matchMedia(`(${f})`).matches;
|
||||
Q.color_bits = [1, 2, 4, 6, 8, 10, 12, 16].filter(n => matchMedia(`(color: ${n})`).matches);
|
||||
put('surface.mq', Q); }
|
||||
{ const I = {}; const ctors = ['DateTimeFormat', 'NumberFormat', 'Collator', 'PluralRules', 'RelativeTimeFormat', 'ListFormat', 'Segmenter', 'DisplayNames', 'DurationFormat'];
|
||||
for (const c of ctors) { try { I[c] = Intl[c] ? new Intl[c](undefined, c === 'DisplayNames' ? {type: 'region'} : undefined).resolvedOptions() : 'absent'; } catch (e) { I[c] = errs(e); } }
|
||||
for (const k of ['calendar', 'collation', 'currency', 'numberingSystem', 'timeZone', 'unit']) { try { I['supported_' + k] = Intl.supportedValuesOf(k); } catch (e) { I['supported_' + k] = errs(e); } }
|
||||
const d = new Date(Date.UTC(2026, 0, 15, 12, 0, 0)), s = new Date(Date.UTC(2026, 6, 15, 12, 0, 0));
|
||||
I.offsets = [d.getTimezoneOffset(), s.getTimezoneOffset()]; I.strings = [d.toString(), s.toString(), d.toLocaleString(), (1234567.891).toLocaleString(), d.toLocaleDateString(undefined, {dateStyle: 'full'})];
|
||||
I.languages = navigator.languages; put('surface.intl', I); }
|
||||
const glAll = version => { const c = document.createElement('canvas'); const gl = c.getContext(version); if (!gl) return 'no ' + version;
|
||||
const P = {}, proto = Object.getPrototypeOf(gl);
|
||||
for (const k of Object.getOwnPropertyNames(proto.constructor)) if (/^[A-Z0-9_]+$/.test(k) && typeof gl[k] === 'number') {
|
||||
const v = gl.getParameter(gl[k]); gl.getError(); if (v !== null && v !== undefined) P[k] = plain(v, 1); }
|
||||
const ext = gl.getSupportedExtensions() || []; const E = {};
|
||||
for (const e of ext) { const o = gl.getExtension(e); if (!o) continue; const ep = {};
|
||||
for (const k in o) if (/^[A-Z0-9_]+$/.test(k) && typeof o[k] === 'number') { const v = gl.getParameter(o[k]); gl.getError(); if (v !== null && v !== undefined) ep[k] = plain(v, 1); }
|
||||
E[e] = ep; }
|
||||
const prec = {}; for (const st of ['VERTEX_SHADER', 'FRAGMENT_SHADER']) for (const pt of ['LOW_FLOAT', 'MEDIUM_FLOAT', 'HIGH_FLOAT', 'LOW_INT', 'MEDIUM_INT', 'HIGH_INT']) {
|
||||
const p = gl.getShaderPrecisionFormat(gl[st], gl[pt]); prec[`${st}.${pt}`] = [p.rangeMin, p.rangeMax, p.precision]; }
|
||||
const dbg = gl.getExtension('WEBGL_debug_renderer_info');
|
||||
return {parameters: P, extensions: ext, extension_parameters: E, precisions: prec, attributes: gl.getContextAttributes(),
|
||||
unmasked: dbg ? [gl.getParameter(dbg.UNMASKED_VENDOR_WEBGL), gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL)] : 'absent'}; };
|
||||
await safe('surface.webgl1', () => glAll('webgl')); await safe('surface.webgl2', () => glAll('webgl2'));
|
||||
// getParameter must answer only where Firefox would: WebGL2-only enums on a WebGL1 context and the
|
||||
// enums of extensions not enabled, each as [value, getError()] (official: null + INVALID_ENUM)
|
||||
await safe('surface.webgl_invalid_enums', () => {
|
||||
const val = x => (x === null || x === undefined) ? x : (typeof x === 'object' ? (ArrayBuffer.isView(x) || Array.isArray(x) ? Array.from(x) : String(x)) : x);
|
||||
const ask = (gl, enums) => { const o = {}; gl.getError(); for (const [n, e] of enums) { let v; try { v = val(gl.getParameter(e)); } catch (x) { v = 'THROW ' + x.name; } o[n] = [v, gl.getError()]; } return o; };
|
||||
const g1 = new Set(Object.getOwnPropertyNames(WebGLRenderingContext));
|
||||
const only2 = Object.getOwnPropertyNames(WebGL2RenderingContext).filter(k => /^[A-Z0-9_]+$/.test(k) && !g1.has(k)).map(k => [k, WebGL2RenderingContext[k]]);
|
||||
const EXT = Object.entries({MAX_TEXTURE_MAX_ANISOTROPY_EXT: 0x84FF, TEXTURE_MAX_ANISOTROPY_EXT: 0x84FE, MAX_VIEWS_OVR: 0x9631, UNMASKED_VENDOR_WEBGL: 0x9245,
|
||||
UNMASKED_RENDERER_WEBGL: 0x9246, MAX_DRAW_BUFFERS_WEBGL: 0x8824, MAX_COLOR_ATTACHMENTS_WEBGL: 0x8CDF, FRAGMENT_SHADER_DERIVATIVE_HINT_OES: 0x8B8B,
|
||||
VERTEX_ARRAY_BINDING_OES: 0x85B5, TIMESTAMP_EXT: 0x8E28, GPU_DISJOINT_EXT: 0x8FBB, QUERY_COUNTER_BITS_EXT: 0x8864, MAX_CLIP_DISTANCES_WEBGL: 0x0D32,
|
||||
MAX_CULL_DISTANCES_WEBGL: 0x82F9, MAX_COMBINED_CLIP_AND_CULL_DISTANCES_WEBGL: 0x82FA, PROVOKING_VERTEX_WEBGL: 0x8E4F, POLYGON_OFFSET_CLAMP_EXT: 0x8E1B,
|
||||
CLIP_ORIGIN_EXT: 0x935C, CLIP_DEPTH_MODE_EXT: 0x935D, MAX_DUAL_SOURCE_DRAW_BUFFERS_WEBGL: 0x88FC, DEPTH_CLAMP_EXT: 0x864F});
|
||||
const c1 = document.createElement('canvas').getContext('webgl'), c2 = document.createElement('canvas').getContext('webgl2');
|
||||
return {webgl1_webgl2only: ask(c1, only2), webgl1_ext_not_enabled: ask(c1, EXT), webgl2_ext_not_enabled: ask(c2, EXT)}; });
|
||||
await safe('surface.webgpu', async () => { if (!navigator.gpu) return 'absent'; const W = {preferredCanvasFormat: navigator.gpu.getPreferredCanvasFormat(),
|
||||
wgslLanguageFeatures: [...navigator.gpu.wgslLanguageFeatures].sort(), adapters: {}};
|
||||
for (const [n, o] of Object.entries({none: undefined, low_power: {powerPreference: 'low-power'}, high_performance: {powerPreference: 'high-performance'}, fallback: {forceFallbackAdapter: true}})) {
|
||||
const a = await navigator.gpu.requestAdapter(o); if (!a) { W.adapters[n] = null; continue; }
|
||||
const L = {}; for (const k in a.limits) L[k] = a.limits[k];
|
||||
const A = {features: [...a.features].sort(), limits: L, info: plain(a.info, 0)};
|
||||
try { const d = await a.requestDevice({requiredFeatures: A.features}); A.device = 'ok'; d.destroy(); } catch (e) { A.device = errs(e); }
|
||||
W.adapters[n] = A; }
|
||||
return W; });
|
||||
{ const types = ['video/mp4', 'video/webm', 'video/ogg', 'audio/mpeg', 'audio/mp4', 'audio/webm', 'audio/ogg', 'audio/wav', 'audio/flac', 'audio/aac',
|
||||
'video/mp4; codecs="avc1.42E01E"', 'video/mp4; codecs="avc1.640028"', 'video/mp4; codecs="hev1.1.6.L93.B0"', 'video/mp4; codecs="hvc1.1.6.L93.B0"',
|
||||
'video/mp4; codecs="av01.0.05M.08"', 'video/webm; codecs="av01.0.05M.08"', 'video/mp4; codecs="vp09.00.10.08"', 'video/webm; codecs="vp9"', 'video/webm; codecs="vp8"',
|
||||
'video/webm; codecs="vp8, vorbis"', 'audio/mp4; codecs="mp4a.40.2"', 'audio/mp4; codecs="opus"', 'audio/webm; codecs="opus"', 'audio/ogg; codecs="vorbis"',
|
||||
'audio/mp4; codecs="flac"', 'audio/mp4; codecs="ec-3"', 'audio/mp4; codecs="ac-3"', 'video/x-matroska', 'application/x-mpegURL', 'application/vnd.apple.mpegurl'];
|
||||
const v = document.createElement('video');
|
||||
put('surface.media.canPlayType', Object.fromEntries(types.map(t => [t, v.canPlayType(t)])));
|
||||
put('surface.media.MediaSource', window.MediaSource ? Object.fromEntries(types.map(t => [t, MediaSource.isTypeSupported(t)])) : 'absent');
|
||||
put('surface.media.MediaRecorder', window.MediaRecorder ? Object.fromEntries(types.map(t => [t, MediaRecorder.isTypeSupported(t)])) : 'absent');
|
||||
const D = {}; const vcodecs = {avc: 'video/mp4; codecs="avc1.640028"', hevc: 'video/mp4; codecs="hvc1.1.6.L93.B0"', vp8: 'video/webm; codecs="vp8"', vp9: 'video/webm; codecs="vp09.00.10.08"',
|
||||
av1: 'video/mp4; codecs="av01.0.05M.08"'};
|
||||
for (const [n, ct] of Object.entries(vcodecs)) for (const type of ['file', 'media-source']) for (const [w, h, fr, br] of [[1280, 720, 30, 2e6], [1920, 1080, 60, 8e6], [3840, 2160, 30, 2e7]]) {
|
||||
try { const r = await navigator.mediaCapabilities.decodingInfo({type, video: {contentType: ct, width: w, height: h, bitrate: br, framerate: fr}}); D[`${type}.${n}.${h}p${fr}`] = [r.supported, r.smooth, r.powerEfficient]; }
|
||||
catch (e) { D[`${type}.${n}.${h}p${fr}`] = errs(e); } }
|
||||
for (const ct of ['video/VP8', 'video/VP9', 'video/AV1', 'video/H264']) {
|
||||
try { const r = await navigator.mediaCapabilities.decodingInfo({type: 'webrtc', video: {contentType: ct, width: 1280, height: 720, bitrate: 1e6, framerate: 30}}); D['webrtc.' + ct] = [r.supported, r.smooth, r.powerEfficient]; }
|
||||
catch (e) { D['webrtc.' + ct] = errs(e); }
|
||||
try { const r = await navigator.mediaCapabilities.encodingInfo({type: 'webrtc', video: {contentType: ct, width: 1280, height: 720, bitrate: 1e6, framerate: 30}}); D['webrtc-encode.' + ct] = [r.supported, r.smooth, r.powerEfficient]; }
|
||||
catch (e) { D['webrtc-encode.' + ct] = errs(e); } }
|
||||
for (const [n, ct] of Object.entries({aac: 'audio/mp4; codecs="mp4a.40.2"', opus: 'audio/webm; codecs="opus"', flac: 'audio/flac', mp3: 'audio/mpeg'})) {
|
||||
try { const r = await navigator.mediaCapabilities.decodingInfo({type: 'file', audio: {contentType: ct, channels: '2', bitrate: 128000, samplerate: 48000}}); D['audio.' + n] = [r.supported, r.smooth, r.powerEfficient]; }
|
||||
catch (e) { D['audio.' + n] = errs(e); } }
|
||||
put('surface.media.capabilities', D); }
|
||||
await safe('surface.audio', async () => { const c = new AudioContext(); const o = {sampleRate: c.sampleRate, baseLatency: c.baseLatency, state: c.state,
|
||||
destination: plain(c.destination, 0), listener: Object.keys(plain(c.listener, 0)).length}; await c.close();
|
||||
const oc = new OfflineAudioContext(1, 5000, 44100), an = oc.createAnalyser(), os = oc.createOscillator(), dc = oc.createDynamicsCompressor();
|
||||
os.type = 'triangle'; os.frequency.value = 10000; dc.threshold.value = -50; dc.knee.value = 40; dc.attack.value = 0;
|
||||
os.connect(dc); dc.connect(an); dc.connect(oc.destination); os.start(0); const buf = await oc.startRendering();
|
||||
const ch = buf.getChannelData(0); let s = 0; for (let i = 4500; i < 5000; i++) s += Math.abs(ch[i]);
|
||||
o.offline_sum = s; o.offline_reduction = dc.reduction; o.offline_head = Array.from(ch.subarray(4500, 4520)); return o; });
|
||||
await safe('surface.voices', () => new Promise(res => { const get = () => speechSynthesis.getVoices().map(v => [v.name, v.lang, v.localService, v.default, v.voiceURI]);
|
||||
const now = get(); if (now.length) return res(now); speechSynthesis.onvoiceschanged = () => res(get()); setTimeout(() => res(get()), 3000); }));
|
||||
await safe('surface.permissions', async () => { const P = {}; for (const n of ['geolocation', 'notifications', 'push', 'persistent-storage', 'camera', 'microphone', 'midi',
|
||||
'clipboard-read', 'clipboard-write', 'screen-wake-lock', 'storage-access', 'background-sync', 'accelerometer', 'gyroscope', 'magnetometer', 'local-fonts', 'payment-handler']) {
|
||||
try { P[n] = (await navigator.permissions.query({name: n})).state; } catch (e) { P[n] = errs(e); } } return P; });
|
||||
await safe('surface.storage', async () => { const e = await navigator.storage.estimate(); noise('storage_usage', e.usage); return {quota: e.quota, persisted: await navigator.storage.persisted()}; });
|
||||
await safe('surface.devices', async () => (await navigator.mediaDevices.enumerateDevices()).map(d => [d.kind, d.label, d.deviceId === '' ? '' : 'id', d.groupId === '' ? '' : 'id']));
|
||||
{ const style = el => { document.body.appendChild(el); const cs = getComputedStyle(el); const o = {}; for (let i = 0; i < cs.length; i++) o[cs[i]] = cs.getPropertyValue(cs[i]); el.remove(); return o; };
|
||||
for (const [n, mk] of Object.entries({body: () => document.createElement('div'), button: () => document.createElement('button'), input: () => document.createElement('input'),
|
||||
select: () => document.createElement('select'), textarea: () => document.createElement('textarea'), a: () => Object.assign(document.createElement('a'), {href: '#'})}))
|
||||
put(`surface.computedStyle.${n}`, style(mk()));
|
||||
const SC = ['AccentColor', 'AccentColorText', 'ActiveText', 'ButtonBorder', 'ButtonFace', 'ButtonText', 'Canvas', 'CanvasText', 'Field', 'FieldText', 'GrayText', 'Highlight',
|
||||
'HighlightText', 'LinkText', 'Mark', 'MarkText', 'SelectedItem', 'SelectedItemText', 'VisitedText', 'ActiveBorder', 'ActiveCaption', 'AppWorkspace', 'Background',
|
||||
'ButtonHighlight', 'ButtonShadow', 'CaptionText', 'InactiveBorder', 'InactiveCaption', 'InactiveCaptionText', 'InfoBackground', 'InfoText', 'Menu', 'MenuText',
|
||||
'Scrollbar', 'ThreeDDarkShadow', 'ThreeDFace', 'ThreeDHighlight', 'ThreeDLightShadow', 'ThreeDShadow', 'Window', 'WindowFrame', 'WindowText',
|
||||
'-moz-buttonhoverface', '-moz-buttonhovertext', '-moz-cellhighlight', '-moz-dialog', '-moz-dialogtext', '-moz-oddtreerow'];
|
||||
const e = document.createElement('div'); document.body.appendChild(e); const C = {};
|
||||
for (const c of SC) { e.style.color = ''; e.style.color = c; C[c] = getComputedStyle(e).color; } e.remove(); put('surface.systemColors', C);
|
||||
const F = {}; const f = document.createElement('div'); document.body.appendChild(f);
|
||||
for (const k of ['caption', 'icon', 'menu', 'message-box', 'small-caption', 'status-bar', '-moz-button', '-moz-field', '-moz-list', '-moz-pull-down-menu', 'system-ui'])
|
||||
{ f.style.font = ''; f.style.font = k === 'system-ui' ? '16px system-ui' : k; const cs = getComputedStyle(f); F[k] = [cs.fontFamily, cs.fontSize, cs.fontWeight, cs.fontStyle]; }
|
||||
f.remove(); put('surface.systemFonts', F); }
|
||||
{ const M = {}; for (const [n, x] of Object.entries({acos: .123, acosh: 1e308, asin: .123, asinh: 1, atanh: .5, atan: 2, sin: -1e300, sinh: 1, cos: 10.000000000123, cosh: 1,
|
||||
tan: -1e300, tanh: 1, exp: 1, expm1: 1, log1p: 10, cbrt: 100, pow: 2}))
|
||||
M[n] = n === 'pow' ? Math.pow(Math.PI, -100) : Math[n](x);
|
||||
put('surface.math', M); }
|
||||
{ const E = {}; const tries = {undef: () => null.x, call: () => (1)(), reduce: () => [].reduce((a, b) => a), json: () => JSON.parse('{'), range: () => new Array(-1), stack: () => { throw new Error('x'); }};
|
||||
for (const [n, f] of Object.entries(tries)) { try { f(); } catch (e) { E[n] = [e.name, e.message, (e.stack || '').split('\n')[0].replace(/@.*$/, '@<page>')]; } }
|
||||
put('surface.errors', E); }
|
||||
await safe('surface.worker', () => new Promise(res => {
|
||||
const src = `const t0 = performance.now(); postMessage({ua: navigator.userAgent, hc: navigator.hardwareConcurrency, lang: navigator.languages, platform: navigator.platform,
|
||||
gpu: 'gpu' in navigator, tz: Intl.DateTimeFormat().resolvedOptions().timeZone, t0});`;
|
||||
const w = new Worker(URL.createObjectURL(new Blob([src], {type: 'text/javascript'}))); const t = performance.now();
|
||||
w.onmessage = e => { noise('worker_start_ms', Math.round(performance.now() - t)); const d = e.data; delete d.t0; res(d); w.terminate(); };
|
||||
setTimeout(() => res('timeout'), 5000); }));
|
||||
await safe('surface.branding', () => Promise.all(['chrome://branding/locale/brand.properties', 'chrome://branding/content/about-logo.png',
|
||||
'resource://app/localization/en-US/branding/brand.ftl'].map(u => new Promise(res => { const s = document.createElement('script'); let done = false;
|
||||
const fin = v => { if (!done) { done = true; res([u, v]); } }; s.onload = () => fin('load'); s.onerror = () => fin('error'); s.src = u; document.head.appendChild(s); setTimeout(() => fin('timeout'), 3000); }))));
|
||||
noise('history_length', history.length);
|
||||
noise('main_loop_ms', await new Promise(r => { const t = performance.now(); setTimeout(() => r(Math.round(performance.now() - t)), 20); }));
|
||||
|
||||
// ================================================================= DIAG (information, never compared)
|
||||
// diag.*: why this host's WebGL is what it is (no WebGL2, no MSAA). Last, so its extra contexts
|
||||
// cannot disturb anything measured above; each is lost again once read.
|
||||
await safe('diag.webgl', async () => {
|
||||
const probe = async (version, attrs) => {
|
||||
const c = document.createElement('canvas'), creation_errors = [];
|
||||
c.addEventListener('webglcontextcreationerror', e => creation_errors.push(e.statusMessage));
|
||||
let gl = null; const o = {};
|
||||
try { gl = attrs ? c.getContext(version, attrs) : c.getContext(version); } catch (e) { o.thrown = errs(e); }
|
||||
await new Promise(r => setTimeout(r, 0));
|
||||
o.is_null = !gl; o.creation_errors = creation_errors;
|
||||
if (!gl) return o;
|
||||
const ask = e => { gl.getError(); let v; try { v = gl.getParameter(e); } catch (x) { return 'THROW ' + x.name; } const err = gl.getError(); return err ? 'GL error ' + err : plain(v, 1); };
|
||||
o.attributes = gl.getContextAttributes();
|
||||
o.strings = Object.fromEntries(['VENDOR', 'RENDERER', 'VERSION', 'SHADING_LANGUAGE_VERSION'].map(k => [k, ask(gl[k])]));
|
||||
const dbg = gl.getExtension('WEBGL_debug_renderer_info');
|
||||
o.unmasked = dbg ? [ask(dbg.UNMASKED_VENDOR_WEBGL), ask(dbg.UNMASKED_RENDERER_WEBGL)] : 'absent';
|
||||
o.SAMPLES = ask(gl.SAMPLES); o.SAMPLE_BUFFERS = ask(gl.SAMPLE_BUFFERS);
|
||||
o.MAX_SAMPLES = 'MAX_SAMPLES' in gl ? ask(gl.MAX_SAMPLES) : 'absent';
|
||||
const lose = gl.getExtension('WEBGL_lose_context'); if (lose) lose.loseContext();
|
||||
return o; };
|
||||
return {webgl1: await probe('webgl'), webgl1_fail_if_caveat: await probe('webgl', {failIfMajorPerformanceCaveat: true}),
|
||||
webgl2: await probe('webgl2'), webgl2_fail_if_caveat: await probe('webgl2', {failIfMajorPerformanceCaveat: true})}; });
|
||||
|
||||
// ================================================================= STATES (state.*)
|
||||
// The window in the states a page can drive it to: normal, fullscreen, back. Nothing here runs on load:
|
||||
// fullscreen needs a user gesture, so the dump (ci_host_gate.py drive_states) calls these after 'done'
|
||||
// and gives every click and move as real input. Defined last so surface.window_own does not list it.
|
||||
window.__hostGateStates = (() => {
|
||||
let events = {}, request = null, pending = null;
|
||||
// each event type keeps the distinct (screen - client) offsets it was seen with
|
||||
const record = e => { const p = [e.screenX - e.clientX, e.screenY - e.clientY], l = (events[e.type] = events[e.type] || []);
|
||||
if (!l.some(q => q[0] === p[0] && q[1] === p[1])) l.push(p); };
|
||||
const geometry = () => ({innerWidth, innerHeight, outerWidth, outerHeight, screenX, screenY, mozInnerScreenX, mozInnerScreenY,
|
||||
screen: {width: screen.width, height: screen.height, availWidth: screen.availWidth, availHeight: screen.availHeight},
|
||||
display_mode_fullscreen: matchMedia('(display-mode: fullscreen)').matches,
|
||||
fullscreen_element: document.fullscreenElement !== null,
|
||||
window_fullScreen: typeof window.fullScreen === 'boolean' ? window.fullScreen : 'absent'});
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
// the geometry once it holds for 4 polls in a row (a transition resizes in steps); false if it never does in 3 s
|
||||
const settle = async () => { let last = JSON.stringify(geometry()), still = 0;
|
||||
for (let i = 0; i < 60 && still < 4; i++) { await sleep(50); const g = JSON.stringify(geometry()); still = g === last ? still + 1 : 0; last = g; }
|
||||
return still >= 4; };
|
||||
// the next fullscreenchange or fullscreenerror, or 'timeout' after ms: a failure is recorded, never waited on
|
||||
const arm = ms => { request = null; pending = new Promise(res => {
|
||||
let t = null;
|
||||
const fin = how => { clearTimeout(t); document.removeEventListener('fullscreenchange', ok); document.removeEventListener('fullscreenerror', bad); res(how); };
|
||||
const ok = () => fin('fullscreenchange'), bad = () => fin('fullscreenerror');
|
||||
document.addEventListener('fullscreenchange', ok); document.addEventListener('fullscreenerror', bad);
|
||||
t = setTimeout(() => fin('timeout'), ms); }); };
|
||||
const asked = p => { request = 'pending'; p.then(() => { request = 'resolved'; }, e => { request = errs(e); }); };
|
||||
return {
|
||||
// listens to the mouse and adds the button whose click asks for fullscreen; returns its centre
|
||||
prepare() {
|
||||
for (const t of ['mousemove', 'mousedown', 'mouseup', 'click']) addEventListener(t, record, true);
|
||||
const b = document.createElement('button'); b.textContent = 'fullscreen';
|
||||
b.style.cssText = 'position:fixed;left:20px;top:20px;width:160px;height:40px;margin:0;z-index:2147483647';
|
||||
b.addEventListener('click', () => asked(document.documentElement.requestFullscreen()));
|
||||
document.body.appendChild(b);
|
||||
const r = b.getBoundingClientRect(); return {x: r.left + r.width / 2, y: r.top + r.height / 2}; },
|
||||
arm,
|
||||
leave(ms) { arm(ms); asked(document.exitFullscreen()); },
|
||||
async wait() { const how = await pending; const settled = await settle(); return {how, request: request === null ? 'not asked' : request, settled}; },
|
||||
clear() { events = {}; },
|
||||
measure() { return Object.assign(geometry(), {events}); },
|
||||
};
|
||||
})();
|
||||
|
||||
window.__hostGate = G;
|
||||
if (location.protocol.startsWith('http')) { try { await fetch('/result' + location.search, {method: 'POST', body: JSON.stringify(G)}); } catch (e) {} }
|
||||
document.title = 'done';
|
||||
})();
|
||||
</script>
|
||||
@@ -38,7 +38,7 @@ ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||||
#: information. These are the ones that drive a browser through the seam.
|
||||
FILES = [
|
||||
"tests/test_juggler_transport.py",
|
||||
"tests/test_cloak.py",
|
||||
"tests/test_hidden_desktop.py",
|
||||
"tests/test_new_page_defaults.py",
|
||||
"tests/test_cross_origin_iframe.py",
|
||||
"tests/test_file_chooser.py",
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Daily snapshot of the public counters, and the two README badges drawn from it.
|
||||
|
||||
python scripts/launch_counters.py --history H.csv --daily D.csv --badges DIR
|
||||
python scripts/launch_counters.py --selftest
|
||||
|
||||
Run once a day by .github/workflows/counters.yml, which keeps the files on the
|
||||
unprotected `badges` branch. Nothing here needs a person or a machine of ours:
|
||||
every input is a public GitHub API answer and every output is a file on that
|
||||
branch.
|
||||
|
||||
WHAT A LAUNCH IS. Every browser process the engine starts makes one GET to a
|
||||
fixed release asset (platform/launch-counter in the engine series), and GitHub
|
||||
counts the fetches as that asset's `download_count`. GitHub keeps only the
|
||||
running total, never a history, which is why this snapshot exists: a day's
|
||||
launches are the difference between two consecutive daily totals, and a day
|
||||
nobody recorded is lost for good.
|
||||
|
||||
THE TOTAL IS A SUM, and its terms are fixed history:
|
||||
* LAUNCHES_BASELINE_V3 is everything counted before the counter moved to the
|
||||
two live assets below; those earlier assets no longer exist.
|
||||
* usage_counter_v3 is the wrapper repo's asset, counted from zero. Engines
|
||||
whose core does not declare the address ping it.
|
||||
* usage_counter_v4 is the engine repo's asset above the value it already held
|
||||
when it came back into use (USAGE_COUNTER_RESUMED_AT). Current cores point
|
||||
every session at it.
|
||||
The two populations are disjoint, so the launches are the sum.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import urllib.request
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
ENGINE_REPO = "feder-cr/firefox_antidetect_patch"
|
||||
WRAPPER_REPO = "feder-cr/invisible_playwright"
|
||||
COUNTER_TAG = "usage-counter"
|
||||
|
||||
LAUNCHES_BASELINE_V3 = 2_084_136
|
||||
USAGE_COUNTER_RESUMED_AT = 1_162_840
|
||||
|
||||
Api = Callable[[str], object]
|
||||
|
||||
|
||||
def github_api(token: str | None) -> Api:
|
||||
def get(path: str):
|
||||
req = urllib.request.Request("https://api.github.com" + path)
|
||||
req.add_header("Accept", "application/vnd.github+json")
|
||||
if token:
|
||||
req.add_header("Authorization", "Bearer " + token)
|
||||
with urllib.request.urlopen(req, timeout=60) as r:
|
||||
return json.load(r)
|
||||
return get
|
||||
|
||||
|
||||
def _releases(api: Api, repo: str) -> list[dict]:
|
||||
out: list[dict] = []
|
||||
page = 1
|
||||
while True:
|
||||
batch = api(f"/repos/{repo}/releases?per_page=100&page={page}")
|
||||
if not batch:
|
||||
return out
|
||||
out.extend(batch)
|
||||
page += 1
|
||||
|
||||
|
||||
def _counter(api: Api, repo: str) -> int:
|
||||
rel = api(f"/repos/{repo}/releases/tags/{COUNTER_TAG}")
|
||||
return sum(a["download_count"] for a in rel["assets"])
|
||||
|
||||
|
||||
def launches_total(usage_counter: int, usage_counter_v3: int) -> int:
|
||||
return (LAUNCHES_BASELINE_V3 + usage_counter_v3
|
||||
+ max(0, usage_counter - USAGE_COUNTER_RESUMED_AT))
|
||||
|
||||
|
||||
def collect(api: Api) -> dict[str, int]:
|
||||
"""Every key the history has always carried, read fresh."""
|
||||
out: dict[str, int] = {}
|
||||
binaries = 0
|
||||
for r in _releases(api, ENGINE_REPO):
|
||||
tag = r["tag_name"]
|
||||
if tag == COUNTER_TAG:
|
||||
continue
|
||||
n = sum(a["download_count"] for a in r["assets"]
|
||||
if a["name"].endswith((".zip", ".tar.gz")))
|
||||
if n or tag.startswith("firefox-"):
|
||||
out[tag] = n
|
||||
binaries += n
|
||||
out["total_binaries"] = binaries
|
||||
out["usage_counter"] = _counter(api, ENGINE_REPO)
|
||||
out["usage_counter_v3"] = _counter(api, WRAPPER_REPO)
|
||||
out["usage_counter_v4"] = max(0, out["usage_counter"] - USAGE_COUNTER_RESUMED_AT)
|
||||
out["launches_total"] = launches_total(out["usage_counter"], out["usage_counter_v3"])
|
||||
out["stars"] = api(f"/repos/{WRAPPER_REPO}")["stargazers_count"]
|
||||
return out
|
||||
|
||||
|
||||
# ── history ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def read_history(path: Path) -> dict[str, dict[str, int]]:
|
||||
out: dict[str, dict[str, int]] = {}
|
||||
if path.exists():
|
||||
with path.open(encoding="utf-8", newline="") as f:
|
||||
for row in csv.DictReader(f):
|
||||
out.setdefault(row["date"], {})[row["key"]] = int(float(row["value"]))
|
||||
return out
|
||||
|
||||
|
||||
def append_snapshot(path: Path, day: str, data: dict[str, int]) -> list[str]:
|
||||
"""Append today's rows. Idempotent per (date, key): a rerun the same day
|
||||
writes only keys that are not there yet, and never a second value."""
|
||||
seen = set(read_history(path).get(day, {}))
|
||||
fresh = {k: v for k, v in data.items() if k not in seen}
|
||||
if not fresh:
|
||||
return []
|
||||
new = not path.exists()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open("a", encoding="utf-8", newline="") as f:
|
||||
w = csv.writer(f, lineterminator="\n")
|
||||
if new:
|
||||
w.writerow(["date", "key", "value"])
|
||||
ff = sorted((k for k in fresh if re.fullmatch(r"firefox-\d+", k)),
|
||||
key=lambda k: int(k.split("-")[1]))
|
||||
rest = sorted(k for k in fresh if k not in ff)
|
||||
for k in ff + rest:
|
||||
w.writerow([day, k, fresh[k]])
|
||||
return list(fresh)
|
||||
|
||||
|
||||
def launches_per_day(history: dict[str, dict[str, int]]) -> list[tuple[str, int]]:
|
||||
"""(day counted, launches) for each pair of snapshots ONE day apart.
|
||||
|
||||
The snapshot dated D is taken just after midnight UTC, so the difference
|
||||
from D-1 is the launches of calendar day D-1. A gap between snapshots is
|
||||
not a day and is never spread over the missing days.
|
||||
"""
|
||||
dates = sorted(d for d in history if "launches_total" in history[d])
|
||||
out = []
|
||||
for a, b in zip(dates, dates[1:]):
|
||||
if (dt.date.fromisoformat(b) - dt.date.fromisoformat(a)).days != 1:
|
||||
continue
|
||||
delta = history[b]["launches_total"] - history[a]["launches_total"]
|
||||
if delta > 0:
|
||||
out.append((a, delta))
|
||||
return out
|
||||
|
||||
|
||||
def write_daily(path: Path, history: dict[str, dict[str, int]]) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open("w", encoding="utf-8", newline="") as f:
|
||||
w = csv.writer(f, lineterminator="\n")
|
||||
w.writerow(["day_utc", "launches"])
|
||||
w.writerows(launches_per_day(history))
|
||||
|
||||
|
||||
# ── badges ──────────────────────────────────────────────────────────────────
|
||||
|
||||
VALUE_PAD = 6
|
||||
COLOUR_LABEL = "#555"
|
||||
CHAR_W = {".": 4.0, "M": 10.0, "k": 6.0} # Verdana 11px advances
|
||||
DIGIT_W = 7.0
|
||||
SAFE_VALUE = re.compile(r"^[0-9]+(\.[0-9]+)?[kM]?$")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Badge:
|
||||
label: str
|
||||
label_box: int # measured from the committed SVG
|
||||
colour: str
|
||||
file_name: str
|
||||
key: str
|
||||
|
||||
|
||||
BADGES = [
|
||||
Badge("browser launches", 116, "#007ec6", "launches.svg", "launches_total"),
|
||||
Badge("Stars", 43, "#e8a317", "stars.svg", "stars"),
|
||||
]
|
||||
|
||||
|
||||
def format_count(n: int) -> str:
|
||||
"""Two decimals, TRUNCATED: an adoption figure is never rounded up."""
|
||||
if n < 1000:
|
||||
return str(n)
|
||||
scaled, suffix = (n / 1000, "k") if n < 1_000_000 else (n / 1_000_000, "M")
|
||||
text = f"{int(scaled * 100) / 100:.2f}".rstrip("0").rstrip(".")
|
||||
return text + suffix
|
||||
|
||||
|
||||
def render(value: str, badge: Badge) -> bytes:
|
||||
if not SAFE_VALUE.match(value):
|
||||
raise ValueError(f"refusing to draw an unexpected value: {value!r}")
|
||||
box = int(sum(CHAR_W.get(c, DIGIT_W) for c in value) + VALUE_PAD)
|
||||
total = badge.label_box + box
|
||||
lx, vx = badge.label_box / 2, badge.label_box + box / 2
|
||||
aria = f"{badge.label}: {value}"
|
||||
lines = [
|
||||
f'<svg xmlns="http://www.w3.org/2000/svg" width="{total}" height="20"'
|
||||
f' role="img" aria-label="{aria}">',
|
||||
f"<title>{aria}</title>",
|
||||
'<linearGradient id="s" x2="0" y2="100%"><stop offset="0"'
|
||||
' stop-color="#bbb" stop-opacity=".1"/><stop offset="1"'
|
||||
' stop-opacity=".1"/></linearGradient>',
|
||||
f'<clipPath id="r"><rect width="{total}" height="20" rx="3"'
|
||||
' fill="#fff"/></clipPath>',
|
||||
'<g clip-path="url(#r)">',
|
||||
f'<rect width="{badge.label_box}" height="20" fill="{COLOUR_LABEL}"/>',
|
||||
f'<rect x="{badge.label_box}" width="{box}" height="20"'
|
||||
f' fill="{badge.colour}"/>',
|
||||
f'<rect width="{total}" height="20" fill="url(#s)"/>',
|
||||
"</g>",
|
||||
'<g fill="#fff" text-anchor="middle"'
|
||||
' font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">',
|
||||
f'<text x="{lx:.1f}" y="15" fill="#010101" fill-opacity=".3">{badge.label}</text>',
|
||||
f'<text x="{lx:.1f}" y="14">{badge.label}</text>',
|
||||
f'<text x="{vx:.1f}" y="15" fill="#010101" fill-opacity=".3">{value}</text>',
|
||||
f'<text x="{vx:.1f}" y="14">{value}</text>',
|
||||
"</g>",
|
||||
"</svg>",
|
||||
]
|
||||
return "\n".join(lines).encode("utf-8")
|
||||
|
||||
|
||||
def write_badges(directory: Path, history: dict[str, dict[str, int]]) -> None:
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
for b in BADGES:
|
||||
days = [d for d in history if b.key in history[d]]
|
||||
if not days:
|
||||
raise SystemExit(f"no {b.key} in the history")
|
||||
(directory / b.file_name).write_bytes(
|
||||
render(format_count(history[max(days)][b.key]), b))
|
||||
|
||||
|
||||
# ── entry point ─────────────────────────────────────────────────────────────
|
||||
|
||||
def run(api: Api, history: Path, daily: Path, badges: Path, today: dt.date) -> int:
|
||||
day = today.isoformat()
|
||||
before = read_history(history)
|
||||
written = append_snapshot(history, day, collect(api))
|
||||
after = read_history(history)
|
||||
write_daily(daily, after)
|
||||
write_badges(badges, after)
|
||||
print(f"[counters] {day}: wrote {len(written)} keys, "
|
||||
f"launches_total={after[day]['launches_total']}")
|
||||
previous = sorted(d for d in before if d < day)
|
||||
if previous and (today - dt.date.fromisoformat(previous[-1])).days > 1:
|
||||
# Recorded anyway, but a hole is a lost measurement: say it in the run.
|
||||
print(f"::warning::no snapshot between {previous[-1]} and {day}: "
|
||||
f"those days cannot be split")
|
||||
return 0
|
||||
|
||||
|
||||
def selftest() -> int:
|
||||
import tempfile
|
||||
fails = []
|
||||
# The row of 2026-11-04 as recorded: the sum must give its total back.
|
||||
if launches_total(2_758_110, 937_317) != 4_616_723:
|
||||
fails.append("sum")
|
||||
if format_count(4_616_723) != "4.61M" or format_count(2554) != "2.55k":
|
||||
fails.append("format")
|
||||
hist = {"2026-11-01": {"launches_total": 100}, "2026-11-02": {"launches_total": 160},
|
||||
"2026-11-04": {"launches_total": 300}}
|
||||
if launches_per_day(hist) != [("2026-11-01", 60)]:
|
||||
fails.append("gap")
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
p = Path(t) / "h.csv"
|
||||
append_snapshot(p, "2026-11-08", {"stars": 1})
|
||||
if append_snapshot(p, "2026-11-08", {"stars": 2}) or read_history(p)["2026-11-08"]["stars"] != 1:
|
||||
fails.append("idempotent")
|
||||
print("selftest:", "OK" if not fails else "FAIL " + ", ".join(fails))
|
||||
return 1 if fails else 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--selftest", action="store_true")
|
||||
ap.add_argument("--history", type=Path)
|
||||
ap.add_argument("--daily", type=Path)
|
||||
ap.add_argument("--badges", type=Path)
|
||||
a = ap.parse_args()
|
||||
if a.selftest:
|
||||
return selftest()
|
||||
if not (a.history and a.daily and a.badges):
|
||||
ap.error("--history, --daily and --badges are required")
|
||||
api = github_api(os.environ.get("GITHUB_TOKEN"))
|
||||
return run(api, a.history, a.daily, a.badges, dt.datetime.now(dt.timezone.utc).date())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,47 @@
|
||||
import socket,json,subprocess,time,os,sys,base64
|
||||
base=os.getcwd(); prof=base+'/prof'; os.makedirs(prof,exist_ok=True)
|
||||
exe=base+'/ex3/core/firefox.exe'
|
||||
open(prof+'/user.js','w').write('user_pref("marionette.port",2828);user_pref("browser.shell.checkDefaultBrowser",false);user_pref("datareporting.policy.dataSubmissionEnabled",false);user_pref("app.update.auto",false);user_pref("app.update.enabled",false);\n')
|
||||
p=subprocess.Popen([exe,'-headless','-marionette','-remote-allow-system-access','-no-remote','-profile',prof,'about:blank'],env=dict(os.environ,MOZ_REMOTE_ALLOW_SYSTEM_ACCESS='1'),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||
try:
|
||||
s=None
|
||||
for i in range(60):
|
||||
try:
|
||||
s=socket.create_connection(('127.0.0.1',2828),timeout=5);break
|
||||
except Exception: time.sleep(1)
|
||||
f=s.makefile('rwb',buffering=0)
|
||||
def rd():
|
||||
n=b''
|
||||
while True:
|
||||
c=s.recv(1)
|
||||
if c==b':':break
|
||||
n+=c
|
||||
n=int(n);d=b''
|
||||
while len(d)<n: d+=s.recv(n-len(d))
|
||||
return json.loads(d)
|
||||
mid=[0]
|
||||
def cmd(name,params=None):
|
||||
mid[0]+=1
|
||||
m=json.dumps([0,mid[0],name,params or {}]).encode()
|
||||
s.sendall(str(len(m)).encode()+b':'+m)
|
||||
while True:
|
||||
r=rd()
|
||||
if r[0]==1 and r[1]==mid[0]: return r[2] if r[2] else r[3]
|
||||
s.settimeout(60)
|
||||
rd()
|
||||
cmd('WebDriver:NewSession',{'capabilities':{}})
|
||||
h=cmd('WebDriver:GetWindowHandles'); cmd('WebDriver:SwitchToWindow',{'handle':h[0]})
|
||||
cmd('WebDriver:Navigate',{'url':'data:text/html,<body><p id=p>text</p>'})
|
||||
js="""
|
||||
const fonts=['menu','caption','icon','message-box','small-caption','status-bar','system-ui'];
|
||||
const colors=['Canvas','CanvasText','LinkText','VisitedText','ActiveText','ButtonFace','ButtonText','ButtonBorder','Field','FieldText','GrayText','Highlight','HighlightText','Mark','MarkText','SelectedItem','SelectedItemText','AccentColor','AccentColorText','ActiveBorder','ActiveCaption','AppWorkspace','Background','ButtonHighlight','ButtonShadow','CaptionText','InactiveBorder','InactiveCaption','InactiveCaptionText','InfoBackground','InfoText','Menu','MenuText','Scrollbar','ThreeDDarkShadow','ThreeDFace','ThreeDHighlight','ThreeDLightShadow','ThreeDShadow','Window','WindowFrame','WindowText'];
|
||||
const o={fonts:{},light:{},dark:{},selection:{}};
|
||||
for(const f of fonts){const d=document.createElement('div');d.style.font=f==='system-ui'?'16px system-ui':f;document.body.appendChild(d);const c=getComputedStyle(d);o.fonts[f]={family:c.fontFamily,size:c.fontSize,weight:c.fontWeight,style:c.fontStyle,stretch:c.fontStretch};d.remove();}
|
||||
for(const sch of ['light','dark']){for(const k of colors){const d=document.createElement('div');d.style.colorScheme=sch;d.style.color=k;d.style.backgroundColor=k;document.body.appendChild(d);o[sch][k]=getComputedStyle(d).color;d.remove();}
|
||||
const d=document.createElement('div');d.style.colorScheme=sch;d.textContent='x';document.body.appendChild(d);const c=getComputedStyle(d,'::selection');o.selection[sch]={color:c.color,bg:c.backgroundColor};d.remove();}
|
||||
return o;"""
|
||||
r=cmd('WebDriver:ExecuteScript',{'script':js,'args':[]})
|
||||
json.dump(r['value'] if 'value' in r else r,open(base+'/retail_theme.json','w'),indent=1)
|
||||
print(json.dumps(r)[:1500])
|
||||
finally:
|
||||
subprocess.run(['taskkill','/F','/T','/PID',str(p.pid)],capture_output=True)
|
||||
@@ -1,201 +1,24 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the FULL e2e suite (every test that opens the browser) against a binary.
|
||||
"""Run this repository's FULL e2e suite (every test that opens the browser)
|
||||
against a binary: the mandatory pre-release e2e gate of a firefox-N.
|
||||
|
||||
Every ``@pytest.mark.e2e`` test is excluded from the default `pytest` run
|
||||
(`addopts = -m 'not slow and not e2e'`) because they need a real Firefox binary
|
||||
and a display, and they skip themselves when no binary is available. That makes
|
||||
them easy to forget - and "we can't afford for something to not work". This is
|
||||
the gate that runs them all, deliberately, against a chosen binary.
|
||||
|
||||
It is the MANDATORY pre-release e2e gate: run it green against the freshly-built
|
||||
release binary BEFORE un-drafting a firefox-N (alongside the fppro + WebRTC
|
||||
realness gates). It is NOT in the public CI drive-gate - the hosted runners are
|
||||
content-process unstable under a heavy headless interaction sequence (see
|
||||
70-known-bugs / 60-ci-release-pipeline); this runs locally on reliable hardware.
|
||||
|
||||
Flake-resilience: under full-suite load a couple of interaction tests (dblclick,
|
||||
hover/mouseenter) can flake even though they pass 3/3 in isolation, so failures
|
||||
are reran up to twice on the known transient signatures. A genuinely broken
|
||||
binary fails all attempts. The webrtc e2e fake a TCP-only SOCKS locally (no
|
||||
proxy/secrets), so the whole suite is offline.
|
||||
|
||||
The run opens FOUR browsers at once by default. `--dist loadfile` is not
|
||||
negotiable and the reason is on the line that sets it: two properties of this
|
||||
suite depend on a file staying whole on one worker, and both were measured
|
||||
failing when it did not.
|
||||
The run itself - which tests, how many browsers at once, the rerun rules, the
|
||||
deadline, and why each is what it is - lives ONCE, in
|
||||
`invisible_core.testing.e2e`, for the three clients of the core. This file is
|
||||
the entry the workflows and the documents call.
|
||||
|
||||
Usage:
|
||||
python scripts/run_e2e.py <firefox-binary>
|
||||
python scripts/run_e2e.py # uses $INVPW_BINARY_PATH
|
||||
python scripts/run_e2e.py <binary> -n 8 # eight browsers at once
|
||||
python scripts/run_e2e.py <binary> -n 1 # the old serial path, unchanged
|
||||
python scripts/run_e2e.py <binary> -n 1 # the serial path, no xdist
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_RERUN_SIGNATURES = "Timeout|context was destroyed|was detached|not visible|because of a navigation|TargetClosed"
|
||||
|
||||
#: Browsers opened at once. Four was asked for and four is what the default is;
|
||||
#: it is not a measured optimum and there is no reason to believe one number
|
||||
#: fits every machine, so `-n` moves it and `-n 1` puts the run back exactly on
|
||||
#: the serial path this script had before parallelism existed.
|
||||
_DEFAULT_PROCS = "4"
|
||||
|
||||
|
||||
def _take_procs(argv: list[str]) -> tuple[str, list[str]]:
|
||||
"""Pull `-n/--procs` out of the arguments, leaving the rest for pytest.
|
||||
|
||||
Hand-parsed rather than argparse because everything this script does not
|
||||
recognise is forwarded to pytest verbatim, and argparse would have to be
|
||||
taught every pytest flag in order to not eat one.
|
||||
|
||||
The value is kept as a STRING and handed to xdist unread, so `auto` and any
|
||||
future spelling xdist accepts keep working without this function learning
|
||||
about them. Only `0` and `1` are interpreted here, and they mean the same
|
||||
thing: do not load xdist at all. That is not the same as `-n 1`, which
|
||||
still runs the tests inside a worker subprocess - a difference that matters
|
||||
the day this script is used to compare a parallel run against a serial one,
|
||||
because then the serial arm must be the ORIGINAL path and not a
|
||||
one-worker variant of the new one.
|
||||
"""
|
||||
procs, rest, i = _DEFAULT_PROCS, [], 0
|
||||
while i < len(argv):
|
||||
if argv[i] in ("-n", "--procs"):
|
||||
if i + 1 >= len(argv):
|
||||
print("run_e2e.py: -n needs a value (1 = serial)", file=sys.stderr)
|
||||
raise SystemExit(2)
|
||||
procs, i = argv[i + 1], i + 2
|
||||
continue
|
||||
rest.append(argv[i])
|
||||
i += 1
|
||||
return procs, rest
|
||||
|
||||
|
||||
def main() -> int:
|
||||
procs, extra = _take_procs(sys.argv[1:])
|
||||
binary = extra[0] if extra else os.environ.get("INVPW_BINARY_PATH")
|
||||
extra = extra[1:] if extra else []
|
||||
if not binary:
|
||||
print("usage: run_e2e.py <firefox-binary> (or set INVPW_BINARY_PATH)", file=sys.stderr)
|
||||
return 2
|
||||
if not Path(binary).exists():
|
||||
print(f"ERROR: binary not found: {binary}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
# An escape hatch in the environment is not neutral here: one e2e ASSERTS
|
||||
# the behaviour it disables.
|
||||
#
|
||||
# `INVISIBLE_CORE_PIN=allow` tells the core to run a mismatched pair instead
|
||||
# of repairing it. It is the normal way to drive a locally built engine, so
|
||||
# it is often already exported in the shell that starts this run - and it is
|
||||
# INHERITED by the venv subprocess that
|
||||
# `test_the_mismatch_repairs_itself_at_import_without_a_restart` spawns.
|
||||
# That test deliberately breaks an environment and requires importing the
|
||||
# wrapper to fix it. With the variable set, the repair correctly declines,
|
||||
# the version does not move, and the test fails for a reason that has
|
||||
# nothing to do with the binary under test.
|
||||
#
|
||||
# Measured 2026-08-16: 1 failed / 143 passed in 14 minutes, and the same
|
||||
# file re-run with the variable unset gave 4 passed in 2 minutes. Refusing
|
||||
# up front costs a second; discovering it costs the whole run plus the time
|
||||
# spent believing the product was broken.
|
||||
#
|
||||
# It is stripped, not merely warned about: a warning at the top of a
|
||||
# 14-minute run scrolls away long before the failure appears.
|
||||
env = {k: v for k, v in os.environ.items() if k != "INVISIBLE_CORE_PIN"}
|
||||
if "INVISIBLE_CORE_PIN" in os.environ:
|
||||
print("[run_e2e] INVISIBLE_CORE_PIN is set in this shell and has been "
|
||||
"STRIPPED for the run: one e2e asserts the pin repair that the "
|
||||
"variable disables, and it would fail for that reason alone.",
|
||||
file=sys.stderr)
|
||||
|
||||
# One setting drives the whole suite: conftest's firefox_binary fixture and
|
||||
# the webrtc e2e both resolve from these.
|
||||
env["INVPW_BINARY_PATH"] = binary
|
||||
env["STEALTHFOX_E2E_BINARY"] = binary
|
||||
|
||||
repo = Path(__file__).resolve().parent.parent
|
||||
|
||||
# ⛔ `--dist loadfile` IS NOT A TUNING CHOICE, IT IS A CORRECTNESS ONE, and
|
||||
# xdist's default (`--dist load`, which hands out one test at a time) breaks
|
||||
# this suite in two measured ways.
|
||||
#
|
||||
# 1. MODULE-SCOPED BROWSERS. `test_fingerprint_consistency.py` is 65 of the
|
||||
# 193 e2e tests and opens ONE browser for all of them, from a
|
||||
# module-scoped fixture. Scattered test-by-test across four workers, each
|
||||
# worker that receives any of those tests builds its own copy of that
|
||||
# fixture: four browsers where the file wants one, and the identity those
|
||||
# 65 tests exist to prove is no longer being read off a single session.
|
||||
#
|
||||
# 2. TESTS THAT DEPEND ON AN EARLIER TEST IN THEIR OWN FILE.
|
||||
# `test_binary_executes_after_fetch` fails 2 out of 2 in isolation and
|
||||
# passes 9 out of 9 when its module runs whole, because a prior test in
|
||||
# that file populates the venv it uses. Measured 2026-08-29, and it very
|
||||
# nearly got recorded as a deterministic failure of the product.
|
||||
#
|
||||
# `loadfile` keeps every file whole on one worker, so both properties
|
||||
# survive. The price is the ceiling: the longest single FILE is now the
|
||||
# floor of the whole run, and with 65 of 193 tests in one file this run
|
||||
# cannot go faster than that file no matter how many workers are asked for.
|
||||
# That is why raising `-n` past a certain point buys nothing here, and the
|
||||
# fix for it would be splitting that file, not adding workers.
|
||||
parallel = [] if procs in ("0", "1") else ["-n", procs, "--dist", "loadfile"]
|
||||
|
||||
cmd = [
|
||||
sys.executable, "-m", "pytest",
|
||||
"-m", "e2e",
|
||||
"-o", "addopts=", # override the default 'not e2e' deselection
|
||||
"--reruns", "2", "--reruns-delay", "1",
|
||||
"--only-rerun", _RERUN_SIGNATURES,
|
||||
# A DEADLINE is not a flake, and retrying one multiplies it by three.
|
||||
# `Timeout` in the signatures above was written for Playwright's
|
||||
# TimeoutError, but it also matches `subprocess.TimeoutExpired` -
|
||||
# measured, 2 tests produced 4 reruns - and the release/upgrade e2e
|
||||
# spend their time in `pip install` calls whose timeouts run to 300s
|
||||
# each. Retried twice that is 900s for one test, and the two files sum
|
||||
# to 10050s of timeout budget against a 2400s job. That is how the job
|
||||
# was killed at 40 minutes twice with nothing to show for it.
|
||||
"--rerun-except", "TimeoutExpired", # a subprocess deadline
|
||||
"--rerun-except", "Timeout >", # pytest-timeout's own deadline
|
||||
# And a per-test deadline, so a hang FAILS WITH A NAME instead of eating
|
||||
# the job. 420s is 4.5x the slowest legitimate test measured on CI
|
||||
# (test_webgl_readpixels_no_masking_signature, 94.4s; the second slowest
|
||||
# is 11.4s and the whole suite is 318s), and 1/6 of the job budget.
|
||||
# METHOD=thread, not the signal default, and that is the whole point.
|
||||
# Measured 2026-08-13 on the run of this very change: the suite wedged in
|
||||
# `test_hover_triggers_mouseenter` and the 420s signal deadline came and
|
||||
# went with NOTHING at 19.3 minutes, 21 minutes, 40. SIGALRM is delivered
|
||||
# to the main thread and Python runs the handler at the next bytecode
|
||||
# boundary; Playwright's sync API is blocked in a greenlet waiting on the
|
||||
# driver socket, so that boundary never arrives. A watchdog THREAD does
|
||||
# not need the hung thread to cooperate: it dumps every thread's stack
|
||||
# and ends the process. The suite does not carry on, which is the price,
|
||||
# and in exchange a hang stops being anonymous.
|
||||
"--timeout", "420",
|
||||
"--timeout-method", "thread",
|
||||
"-p", "no:cacheprovider",
|
||||
# -v, not -q, and the reason is a hang we could not name twice.
|
||||
# Under -q pytest emits one character per test and the line only
|
||||
# reaches the log when it is full, so a run that dies mid-line says
|
||||
# nothing about where it died. Measured 2026-08-12 on two runs of the
|
||||
# SAME commit: both printed the identical `.s....[ 50%]` line at 78
|
||||
# seconds, one then finished in 4:47 and the other was killed by the
|
||||
# 40-minute timeout with no second line - so the hang was somewhere in
|
||||
# tests 73-141 and that is as close as the log could get. Same symptom
|
||||
# on 2026-08-04. PYTHONUNBUFFERED was already set and is not the
|
||||
# missing piece: the output does stream, the GRANULARITY was wrong.
|
||||
# One line per test costs 141 lines and names the last one that ran.
|
||||
"-v", "--tb=short",
|
||||
] + parallel + extra
|
||||
print(f"[run_e2e] binary={binary}")
|
||||
print(f"[run_e2e] browsers at once: {procs if parallel else '1 (serial)'}")
|
||||
print(f"[run_e2e] {' '.join(cmd)}")
|
||||
return subprocess.run(cmd, cwd=repo, env=env).returncode
|
||||
|
||||
from invisible_core.testing.e2e import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
sys.exit(main(sys.argv[1:], repo=Path(__file__).resolve().parent.parent))
|
||||
@@ -0,0 +1,218 @@
|
||||
"""The expected values of tests/test_css_calc_is_windows_e2e.py.
|
||||
|
||||
Run it with `python -I`. Two steps, because a number is only worth testing if
|
||||
the two C libraries give a different page-visible text for it:
|
||||
|
||||
python -I scripts/ucrt_css_calc.py dump OUT # on Windows: ucrtbase.dll's f32 functions
|
||||
python -I scripts/ucrt_css_calc.py dump OUT # on Linux: the host's libm
|
||||
python -I scripts/ucrt_css_calc.py pick WIN LINUX tests/data/ucrt_css_calc.txt
|
||||
|
||||
`dump` computes, for a fixed grid of inputs, what the style engine (Servo's
|
||||
calc.rs) makes of ``calc(1px * sin(x))`` and the others, and the text it then
|
||||
serializes. The style engine does every step in f32 (CSSFloat): the library
|
||||
function is the f32 one (sinf, cosf, tanf, asinf, acosf, atanf, atan2f, expf,
|
||||
logf, powf), an angle is converted to degrees with one f32 multiplication, and
|
||||
a number is written by cssparser's dtoa_short: the shortest decimal that
|
||||
reads back as that f32, rounded half up to 6 significant digits. So two
|
||||
libraries whose results differ in the last f32 bit only show on the page when
|
||||
that bit moves the 6th digit - which `pick` looks for.
|
||||
|
||||
`pick` keeps every input whose text differs between the two dumps, and a few
|
||||
that do not (the control: the same text from both libraries), in the format
|
||||
the test reads:
|
||||
|
||||
<fn> <args...> <text on Windows>
|
||||
|
||||
The reference is ucrtbase's FMA3 code path, the one every Windows 11 CPU runs
|
||||
(the same one idwr_math reproduces); the SSE2 fallback of older CPUs can differ in
|
||||
the last bit and is not what a page on Windows 11 reads.
|
||||
|
||||
Inputs are exact in f32 (multiples of a power of two), so the page and this
|
||||
script read the same number whatever the CSS parser does with decimals.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import math
|
||||
import struct
|
||||
import sys
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
from pathlib import Path
|
||||
|
||||
#: Rust's f32::to_degrees multiplier, as an f32.
|
||||
RAD_TO_DEG = struct.unpack("<f", struct.pack("<f", 57.2957795130823208767981548141051703))[0]
|
||||
|
||||
#: How many differing inputs of each function `pick` keeps, and how many of the
|
||||
#: ones that agree.
|
||||
KEEP_DIFFERENT = 6
|
||||
KEEP_SAME = 3
|
||||
|
||||
|
||||
def f32(x: float) -> float:
|
||||
return struct.unpack("<f", struct.pack("<f", x))[0]
|
||||
|
||||
|
||||
def load_libm():
|
||||
if sys.platform == "win32":
|
||||
lib = ctypes.CDLL("ucrtbase.dll")
|
||||
else:
|
||||
lib = ctypes.CDLL("libm.so.6")
|
||||
funcs = {}
|
||||
for name, nargs in (("sinf", 1), ("cosf", 1), ("tanf", 1), ("asinf", 1), ("acosf", 1),
|
||||
("atanf", 1), ("atan2f", 2), ("expf", 1), ("logf", 1), ("powf", 2)):
|
||||
fn = getattr(lib, name)
|
||||
fn.restype = ctypes.c_float
|
||||
fn.argtypes = [ctypes.c_float] * nargs
|
||||
funcs[name] = fn
|
||||
return funcs
|
||||
|
||||
|
||||
def shortest_f32(x: float) -> str:
|
||||
"""The shortest decimal text that reads back as this f32."""
|
||||
for digits in range(1, 10):
|
||||
text = "%.*e" % (digits - 1, x)
|
||||
if f32(float(text)) == x:
|
||||
return text
|
||||
return "%.8e" % x
|
||||
|
||||
|
||||
def serialize(x: float) -> str:
|
||||
"""cssparser's number text for an f32: 6 significant digits, half up,
|
||||
no trailing zeros, no exponent in the range the grid stays in."""
|
||||
if x == 0:
|
||||
return "0"
|
||||
d = Decimal(shortest_f32(x))
|
||||
exp = d.adjusted()
|
||||
q = d.quantize(Decimal(1).scaleb(exp - 5), rounding=ROUND_HALF_UP)
|
||||
text = format(q.normalize(), "f")
|
||||
return "0" if text in ("-0", "") else text
|
||||
|
||||
|
||||
def decimal(k: int, shift: int) -> str:
|
||||
"""k / 2**shift as an exact decimal text."""
|
||||
d = Decimal(k) / Decimal(2 ** shift)
|
||||
return format(d.normalize(), "f")
|
||||
|
||||
|
||||
def grid():
|
||||
"""(fn, args as texts) for every case of the dump."""
|
||||
out = []
|
||||
for fn, lim, shift in (("sin", 16, 10), ("cos", 16, 10), ("tan", 16, 10)):
|
||||
for k in range(-lim << shift, (lim << shift) + 1):
|
||||
out.append((fn, [decimal(k, shift)]))
|
||||
# Finer, over the stretch where the functions bend the most.
|
||||
for k in range(-(4 << 13), (4 << 13) + 1):
|
||||
out.append(("tan", [decimal(k, 13)]))
|
||||
for k in range(-(8 << 12), (8 << 12) + 1):
|
||||
out.append(("atan", [decimal(k, 12)]))
|
||||
for k in range(-(4 << 12), (4 << 12) + 1):
|
||||
out.append(("exp", [decimal(k, 12)]))
|
||||
for k in range(1, 32 * 1024 + 1):
|
||||
out.append(("log", [decimal(k, 10)]))
|
||||
for a in range(-128, 129):
|
||||
for b in range(-128, 129):
|
||||
if a or b:
|
||||
out.append(("atan2", [decimal(a, 6), decimal(b, 6)]))
|
||||
for k in range(-4096, 4097):
|
||||
out.append(("asin", [decimal(k, 12)]))
|
||||
out.append(("acos", [decimal(k, 12)]))
|
||||
for k in range(-8 * 512, 8 * 512 + 1):
|
||||
out.append(("atan", [decimal(k, 9)]))
|
||||
for a in range(-64, 65):
|
||||
for b in range(-64, 65):
|
||||
if a or b:
|
||||
out.append(("atan2", [decimal(a, 4), decimal(b, 4)]))
|
||||
for k in range(-10 * 256, 10 * 256 + 1):
|
||||
out.append(("exp", [decimal(k, 8)]))
|
||||
for k in range(1, 64 * 64 + 1):
|
||||
out.append(("log", [decimal(k, 6)]))
|
||||
for a in range(2, 513):
|
||||
for b in (2, 3, 5, 7, 10):
|
||||
out.append(("log", [decimal(a, 3), str(b)]))
|
||||
for a in range(-32, 33):
|
||||
for b in range(-32, 33):
|
||||
out.append(("hypot", [decimal(a * 3, 4), decimal(b * 5, 4)]))
|
||||
for a in range(4, 257):
|
||||
for b in range(-64, 65):
|
||||
out.append(("pow", [decimal(a, 4), decimal(b, 4)]))
|
||||
return out
|
||||
|
||||
|
||||
def evaluate(lib, fn, args):
|
||||
"""(text, unit) the page shows, from f32 steps."""
|
||||
v = [f32(float(a)) for a in args]
|
||||
if fn in ("sin", "cos", "tan", "exp"):
|
||||
return serialize(f32(lib[fn + "f"](v[0]))), "px"
|
||||
if fn == "log":
|
||||
if len(v) == 1:
|
||||
return serialize(f32(lib["logf"](v[0]))), "px"
|
||||
return serialize(f32(f32(lib["logf"](v[0])) / f32(lib["logf"](v[1])))), "px"
|
||||
if fn == "hypot":
|
||||
# powi(2) is a product, the sum is f32, sqrt is exact in IEEE: no library
|
||||
# function here, so no difference between the two - the control.
|
||||
return serialize(f32(math.sqrt(f32(f32(v[0] * v[0]) + f32(v[1] * v[1]))))), "px"
|
||||
if fn == "pow":
|
||||
return serialize(f32(lib["powf"](v[0], v[1]))), "px"
|
||||
if fn in ("asin", "acos", "atan"):
|
||||
return serialize(f32(f32(lib[fn + "f"](v[0])) * RAD_TO_DEG)), "deg"
|
||||
if fn == "atan2":
|
||||
return serialize(f32(f32(lib["atan2f"](v[0], v[1])) * RAD_TO_DEG)), "deg"
|
||||
raise ValueError(fn)
|
||||
|
||||
|
||||
def dump(out: Path) -> None:
|
||||
lib = load_libm()
|
||||
lines = []
|
||||
for fn, args in grid():
|
||||
text, unit = evaluate(lib, fn, args)
|
||||
if text in ("nan", "inf", "-inf") or "e" in text.lower():
|
||||
continue
|
||||
lines.append("%s %s %s%s" % (fn, " ".join(args), text, unit))
|
||||
out.write_text("\n".join(lines) + "\n")
|
||||
print("wrote %s: %d cases (%s)" % (out, len(lines), sys.platform))
|
||||
|
||||
|
||||
def read(path: Path) -> dict:
|
||||
cases = {}
|
||||
for line in path.read_text().splitlines():
|
||||
parts = line.split()
|
||||
cases[tuple(parts[:-1])] = parts[-1]
|
||||
return cases
|
||||
|
||||
|
||||
def pick(win: Path, linux: Path, out: Path) -> None:
|
||||
a, b = read(win), read(linux)
|
||||
chosen = ["# Expected text of getComputedStyle for calc(1px * f(args)) (word-spacing)",
|
||||
"# and of rotate: f(args) for the angle functions, from ucrtbase.dll's f32",
|
||||
"# functions. Generated by scripts/ucrt_css_calc.py (python -I) - do not edit.",
|
||||
"# <fn> <args...> <text on Windows>"]
|
||||
stats = []
|
||||
for fn in ("sin", "cos", "tan", "asin", "acos", "atan", "atan2", "exp", "log", "pow", "hypot"):
|
||||
keys = sorted(k for k in a if k[0] == fn and k in b)
|
||||
different = [k for k in keys if a[k] != b[k]]
|
||||
same = [k for k in keys if a[k] == b[k]]
|
||||
# Spread over the list, not the first ones.
|
||||
step_d = max(1, len(different) // KEEP_DIFFERENT)
|
||||
quarter = max(1, len(same) // 4)
|
||||
take = different[::step_d][:KEEP_DIFFERENT] + same[quarter::quarter][:KEEP_SAME]
|
||||
stats.append("%s: %d of %d differ" % (fn, len(different), len(keys)))
|
||||
for k in take:
|
||||
chosen.append("%s %s" % (" ".join(k), a[k]))
|
||||
out.write_text("\n".join(chosen) + "\n")
|
||||
print("\n".join(stats))
|
||||
print("wrote %s" % out)
|
||||
|
||||
|
||||
def main(argv) -> int:
|
||||
if len(argv) == 3 and argv[1] == "dump":
|
||||
dump(Path(argv[2]))
|
||||
elif len(argv) == 5 and argv[1] == "pick":
|
||||
pick(Path(argv[2]), Path(argv[3]), Path(argv[4]))
|
||||
else:
|
||||
print(__doc__)
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -194,7 +194,12 @@ def main() -> int:
|
||||
import os
|
||||
env = dict(os.environ)
|
||||
env["INVPW_BINARY_PATH"] = a.binary
|
||||
env["PYTHONPATH"] = str(ROOT)
|
||||
# ⛔ THIS CHECKOUT'S `src` TOO, or the suite measures whatever wrapper is
|
||||
# INSTALLED: `ROOT` alone only makes `scripts._upstream_alias` importable,
|
||||
# and `invisible_playwright` then resolves to the editable install, which
|
||||
# from a worktree is somebody else's tree on somebody else's commit. A
|
||||
# branch measured that way reports main's numbers as its own.
|
||||
env["PYTHONPATH"] = os.pathsep.join([str(ROOT), str(ROOT / "src")])
|
||||
|
||||
if not a.per_file:
|
||||
print("running: %s" % " ".join(argv[3:]))
|
||||
|
||||
@@ -11,7 +11,7 @@ the user receives.
|
||||
|
||||
| folder | what it is | license |
|
||||
|---|---|---|
|
||||
| `_pw/` | Playwright's Python client, version **1.61.1** | Apache-2.0 (`_pw/LICENSE`) |
|
||||
| `_pw/` | Playwright's Python client, version **1.61.0** | Apache-2.0 (`_pw/LICENSE`) |
|
||||
|
||||
The client's namespace is `invisible_playwright._pw` instead of `playwright`, so
|
||||
it does not collide with a stock `playwright` that might be installed alongside
|
||||
@@ -50,7 +50,8 @@ did so on evidence rather than on the code looking finished:
|
||||
- The ability to RE-DERIVE three things that were extracted from the bundle.
|
||||
All three artefacts are committed and still valid; what is gone is
|
||||
regenerating them. `injected.js` (the selector engines, actionability and
|
||||
`expect` that run in the page), `_juggler/keylayout.py`, and the four rules
|
||||
`expect` that run in the page), `keylayout.py` (both in `invisible_core.juggler`
|
||||
since 0.30.0, with their extractors in the core's `scripts/`), and the four rules
|
||||
`prefs_byte_parity.py` compares our `user.js` writer against - now frozen in
|
||||
`tests/gates/driver_prefs_rules.json` with the sha of the bundle and of the
|
||||
exact window they came from.
|
||||
@@ -79,7 +80,8 @@ They are history now, kept because they say what the fork was for:
|
||||
- **Neutralized `_exposeConsoleApi`** and **removed `console.debug`** from the
|
||||
injected code, both because a page could observe them. ⛔ Not lost: those
|
||||
changes are in `injected.js`, which is extracted, committed, and still what
|
||||
the server injects. `gen_injected_source.py --check` refuses any bundle that
|
||||
the server injects (from `invisible_core.juggler` since 0.30.0). The core's
|
||||
`scripts/gen_injected_source.py --check` refuses any bundle that
|
||||
does not carry the `MODIFIED by invisible_playwright` markers, so an upstream
|
||||
bundle can never be mistaken for ours.
|
||||
|
||||
|
||||
@@ -69,14 +69,13 @@ from invisible_core import GeoTimezoneError, resolve_session_timezone
|
||||
from invisible_core import ensure_binary, ensure_geoip_mmdb
|
||||
from .launcher import InvisiblePlaywright
|
||||
|
||||
from importlib.metadata import PackageNotFoundError, version as _pkg_version
|
||||
|
||||
try:
|
||||
__version__ = _pkg_version("invisible-playwright")
|
||||
except PackageNotFoundError:
|
||||
# Editable / source checkout without an install record: fall back to a
|
||||
# marker rather than risk shipping a stale hardcoded string.
|
||||
__version__ = "0.0.0+unknown"
|
||||
# `__version__` describes the CODE that is about to run; the install record is
|
||||
# a different fact and keeps a name that says so, the way `invisible_core` does.
|
||||
# ⛔ It used to be `importlib.metadata.version("invisible-playwright")`, which
|
||||
# describes the INSTALL: an editable one freezes that number and the code keeps
|
||||
# moving, measured here at 0.16.2 against a tree declaring 0.22.1 with the
|
||||
# checkout up to date. See `_version.py`.
|
||||
from ._version import __install_record_version__, __version__
|
||||
|
||||
__all__ = [
|
||||
"InvisiblePlaywright",
|
||||
@@ -89,4 +88,5 @@ __all__ = [
|
||||
"BINARY_VERSION",
|
||||
"FIREFOX_UPSTREAM_VERSION",
|
||||
"__version__",
|
||||
"__install_record_version__",
|
||||
]
|
||||
@@ -117,14 +117,20 @@ import asyncio
|
||||
import inspect
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
import warnings
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple
|
||||
from weakref import WeakKeyDictionary
|
||||
|
||||
from . import _behaviour
|
||||
from invisible_core.juggler import (
|
||||
DONE, SLEEP, Ev as _Ev, Pacer, PointerPersona, Step,
|
||||
clamp_to_viewport as _clamp, fine_timer as _fine_timer,
|
||||
fit_timeline as _fit_timeline, initial_pointer, landing_point,
|
||||
plan_aimless_move, plan_approach, plan_idle, plan_scroll,
|
||||
steps_from_waypoints, tail_within,
|
||||
)
|
||||
from invisible_core.seedmix import sub_seed
|
||||
|
||||
# The escape hatch. ``INVPW_CURSOR_ENGINE`` picks who generates the motion:
|
||||
# "python" (default) - this module, seeded from the session seed
|
||||
@@ -228,8 +234,10 @@ def _reset_warnings() -> None:
|
||||
# Anything else is treated as "no generator available" and the session falls
|
||||
# back to the browser's own expansion, which is always a working browser.
|
||||
try: # pragma: no cover - exercised by the import-failure test via monkeypatch
|
||||
from . import _motion as _motion_mod # type: ignore[attr-defined]
|
||||
except Exception as _motion_exc: # noqa: BLE001 - a broken _motion must not break launching
|
||||
# The package that publishes the generator: `_motion_factory` looks the
|
||||
# factory up on it by name, and the tests put a stub module here.
|
||||
from invisible_core import juggler as _motion_mod # type: ignore[attr-defined]
|
||||
except Exception as _motion_exc: # noqa: BLE001 - a broken generator must not break launching
|
||||
_motion_mod = None # type: ignore[assignment]
|
||||
_MOTION_IMPORT_ERROR: Optional[BaseException] = _motion_exc
|
||||
else:
|
||||
@@ -241,11 +249,10 @@ else:
|
||||
#: physical fact is the shape this project keeps finding, and the looser one
|
||||
#: silently won wherever it happened to be applied last.
|
||||
#:
|
||||
#: The fallback is only reached when _motion failed to import, in which case
|
||||
#: the session is already falling back to the browser's own expansion; keeping
|
||||
#: a floor here rather than None means _fit_timeline still refuses to emit a
|
||||
#: rate no device produces.
|
||||
MIN_EVENT_INTERVAL_MS = float(getattr(_motion_mod, "SAMPLE_FLOOR_MS", 8.0)) if _motion_mod is not None else 8.0
|
||||
#: It moved into _pacing on 2026-09-16, with the discipline that reads it, so
|
||||
#: the server's drag obeys the same floor as the client's cursor. Re-exported
|
||||
#: here because it is part of this module's published surface.
|
||||
from invisible_core.juggler import MIN_EVENT_INTERVAL_MS # noqa: E402 - re-exported, see above
|
||||
|
||||
|
||||
_MOTION_FACTORY_NAMES = ("CursorMotion", "MotionProfile", "new_motion")
|
||||
@@ -267,7 +274,7 @@ def _motion_factory() -> Optional[Callable[..., Any]]:
|
||||
_warn_once(
|
||||
"no-motion",
|
||||
"no cursor motion generator found "
|
||||
"(invisible_playwright._motion.CursorMotion)" + detail + "; falling "
|
||||
"(invisible_core.juggler.CursorMotion)" + detail + "; falling "
|
||||
"back to the browser's own motion for this process. This is a broken "
|
||||
"install, not a configuration.",
|
||||
)
|
||||
@@ -356,66 +363,6 @@ class _RealTimer:
|
||||
|
||||
_TIMER: Any = _RealTimer()
|
||||
|
||||
# Windows quantises a waited-on timer to the system tick, which is 15.6 ms by
|
||||
# default: a 12 ms sleep comes back at 16.7 ms (measured, p50), and there is no
|
||||
# scheduling policy that can recover a resolution the platform will not give.
|
||||
# Asking for a 1 ms period brings the same sleep back at 12.5 ms. It is
|
||||
# reference-counted by the OS and released as soon as the movement is over, and
|
||||
# it is the difference between dispatching the plan and dispatching a rounded
|
||||
# copy of it - which matters here because per-seed differentiation is carried
|
||||
# largely by timing.
|
||||
TIMER_ENV = "INVPW_CURSOR_TIMER"
|
||||
|
||||
_timer_period_depth = 0
|
||||
_winmm: Any = None
|
||||
_winmm_tried = False
|
||||
|
||||
|
||||
def _timer_resolution_available() -> Any:
|
||||
global _winmm, _winmm_tried
|
||||
if _winmm_tried:
|
||||
return _winmm
|
||||
_winmm_tried = True
|
||||
if (os.environ.get(TIMER_ENV) or "").strip().lower() in ("off", "0", "false"):
|
||||
return None
|
||||
if not sys.platform.startswith("win"):
|
||||
return None
|
||||
try:
|
||||
import ctypes
|
||||
|
||||
_winmm = ctypes.WinDLL("winmm") # type: ignore[attr-defined]
|
||||
except (OSError, ImportError): # no winmm is simply a coarser clock
|
||||
_winmm = None
|
||||
return _winmm
|
||||
|
||||
|
||||
class _fine_timer:
|
||||
"""Raise the system timer resolution for the length of one burst."""
|
||||
|
||||
def __enter__(self) -> "_fine_timer":
|
||||
global _timer_period_depth
|
||||
dll = _timer_resolution_available()
|
||||
if dll is not None:
|
||||
if _timer_period_depth == 0:
|
||||
try:
|
||||
dll.timeBeginPeriod(1)
|
||||
except (OSError, AttributeError):
|
||||
return self
|
||||
_timer_period_depth += 1
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc: Any) -> None:
|
||||
global _timer_period_depth
|
||||
if _timer_period_depth <= 0:
|
||||
return
|
||||
_timer_period_depth -= 1
|
||||
if _timer_period_depth == 0 and _winmm is not None:
|
||||
try:
|
||||
_winmm.timeEndPeriod(1)
|
||||
except (OSError, AttributeError):
|
||||
pass
|
||||
|
||||
|
||||
# ── per-page seeding ────────────────────────────────────────────────────────
|
||||
|
||||
def page_motion_seed(session_seed: int, ordinal: int) -> int:
|
||||
@@ -426,9 +373,21 @@ def page_motion_seed(session_seed: int, ordinal: int) -> int:
|
||||
in which tabs happened to move. Same session seed plus same tab ordinal
|
||||
gives the same path, which is what makes a replayed seed replay the
|
||||
cursor. Kept inside int31 for consistency with the rest of the seeding.
|
||||
|
||||
⛔ EVERY BIT OF THE ORDINAL COUNTS, not only the low 16. A page the site
|
||||
opened is numbered in a space of its own above bit 62 (`_behaviour.
|
||||
popup_number`), and with the old mask two popups shared a path whenever
|
||||
their numbers agreed on 16 bits. The higher bits are folded in only when
|
||||
there are any, so the pages the script asks for (0, 1, 2 ...) keep the
|
||||
seeds they always had.
|
||||
"""
|
||||
ordinal = int(ordinal)
|
||||
h = (int(session_seed) & 0xFFFFFFFF) * 0x9E3779B1
|
||||
h = (h ^ ((int(ordinal) & 0xFFFF) * 0x85EBCA6B)) & 0xFFFFFFFF
|
||||
h = (h ^ ((ordinal & 0xFFFF) * 0x85EBCA6B)) & 0xFFFFFFFF
|
||||
high = ordinal >> 16
|
||||
while high > 0:
|
||||
h = ((h ^ (high & 0xFFFF)) * 0xC2B2AE35) & 0xFFFFFFFF
|
||||
high >>= 16
|
||||
h ^= h >> 16
|
||||
return h & 0x7FFFFFFF
|
||||
|
||||
@@ -436,17 +395,25 @@ def page_motion_seed(session_seed: int, ordinal: int) -> int:
|
||||
class _Session:
|
||||
"""Everything a session hands to the pages underneath it."""
|
||||
|
||||
__slots__ = ("seed", "max_seconds", "_ordinal")
|
||||
__slots__ = ("seed", "max_seconds")
|
||||
|
||||
def __init__(self, seed: int, max_seconds: float) -> None:
|
||||
self.seed = int(seed)
|
||||
self.max_seconds = float(max_seconds)
|
||||
self._ordinal = 0
|
||||
|
||||
def next_ordinal(self) -> int:
|
||||
n = self._ordinal
|
||||
self._ordinal += 1
|
||||
return n
|
||||
|
||||
def page_number(page: Any) -> int:
|
||||
"""The page's number in the session, as the server gave it.
|
||||
|
||||
⛔ READ FROM THE PAGE, NEVER COUNTED HERE. The server sends it in the
|
||||
page's initializer (`PageDispatcher.number`: the number the client
|
||||
reserved at the `new_page()` call, or a popup's derived one), and the
|
||||
server draws the page's acts under it. This cursor used to count its own,
|
||||
at each page's FIRST MOVEMENT: a script that created two pages and moved
|
||||
on the second first gave the second page 0 here and 1 there - two
|
||||
counters for one fact, with two different orders ([B237]).
|
||||
"""
|
||||
return int(page._initializer["pageNumber"])
|
||||
|
||||
|
||||
class _PageCursor:
|
||||
@@ -459,7 +426,7 @@ class _PageCursor:
|
||||
self.seed = int(seed)
|
||||
self.max_seconds = float(max_seconds)
|
||||
self._profile = _build_profile(factory, self.seed, self.max_seconds)
|
||||
self.persona = _behaviour.PointerPersona.from_seed(self.seed)
|
||||
self.persona = PointerPersona.from_seed(self.seed)
|
||||
self.x: Optional[float] = None
|
||||
self.y: Optional[float] = None
|
||||
self.busy = False
|
||||
@@ -504,7 +471,7 @@ class _PageCursor:
|
||||
"using the behaviour planner's instead."
|
||||
% (type(exc).__name__, exc),
|
||||
)
|
||||
return _behaviour.initial_pointer(self.seed, (float(w), float(h)))
|
||||
return initial_pointer(self.seed, (float(w), float(h)))
|
||||
|
||||
def here(self, page: Any) -> Tuple[float, float]:
|
||||
"""Current pointer position, placing it first if it has never moved."""
|
||||
@@ -551,7 +518,7 @@ class _PageCursor:
|
||||
float(getattr(p, "y", None) if hasattr(p, "y") else p[1]),
|
||||
nominal)
|
||||
for p in raw]
|
||||
return _behaviour.steps_from_waypoints(
|
||||
return steps_from_waypoints(
|
||||
raw, kind=kind, lead_ms=lead_ms, bounds=bounds
|
||||
)
|
||||
|
||||
@@ -560,7 +527,7 @@ class _PageCursor:
|
||||
def rng(self, tag: str) -> random.Random:
|
||||
"""A per-(page, action, purpose) stream. Reproducible from the seed."""
|
||||
return random.Random(
|
||||
_behaviour._sub_seed(self.seed, "%s:%d" % (tag, self.action))
|
||||
sub_seed(self.seed, "%s:%d" % (tag, self.action))
|
||||
)
|
||||
|
||||
|
||||
@@ -574,28 +541,6 @@ class _PageCursor:
|
||||
# stretch. Per-seed differentiation is carried largely by timing, so that
|
||||
# stretch was quietly deleting the thing the seeding is for.
|
||||
|
||||
class _Ev:
|
||||
"""One dispatchable instant."""
|
||||
|
||||
__slots__ = ("t_ms", "x", "y", "kind", "dx", "dy")
|
||||
|
||||
def __init__(self, t_ms: float, x: float, y: float, kind: str = "move",
|
||||
dx: float = 0.0, dy: float = 0.0) -> None:
|
||||
self.t_ms = float(t_ms)
|
||||
self.x = float(x)
|
||||
self.y = float(y)
|
||||
self.kind = kind
|
||||
self.dx = float(dx)
|
||||
self.dy = float(dy)
|
||||
|
||||
@property
|
||||
def is_wheel(self) -> bool:
|
||||
return self.kind == "wheel"
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover - debugging aid
|
||||
return "_Ev(%.1f, %.1f, %.1f, %s)" % (self.t_ms, self.x, self.y, self.kind)
|
||||
|
||||
|
||||
def _timeline(steps: Iterable[Any]) -> List[_Ev]:
|
||||
"""Turn a ``_behaviour`` Step list (relative delays) into absolute times."""
|
||||
out: List[_Ev] = []
|
||||
@@ -609,57 +554,6 @@ def _timeline(steps: Iterable[Any]) -> List[_Ev]:
|
||||
return out
|
||||
|
||||
|
||||
def _fit_timeline(evs: List[_Ev], budget_s: float) -> List[_Ev]:
|
||||
"""Fit a timeline inside ``budget_s`` and inside what hardware can report.
|
||||
|
||||
Two rules, in this order:
|
||||
|
||||
* if the plan is longer than the budget, every timestamp is scaled - the
|
||||
same movement performed faster, not a movement that stops half way;
|
||||
* events closer together than :data:`MIN_EVENT_INTERVAL_MS` are then
|
||||
DROPPED, not squeezed. Scaling alone is what produced impossible event
|
||||
rates: the waypoint count never changed, so a tighter cap simply meant
|
||||
more events per second, without limit. The last event of the timeline
|
||||
and every wheel notch survive regardless - the first is where the
|
||||
movement has to end, the second carries a delta that would be lost.
|
||||
"""
|
||||
if not evs:
|
||||
return []
|
||||
total = evs[-1].t_ms
|
||||
if budget_s > 0 and total > budget_s * 1000.0:
|
||||
scale = (budget_s * 1000.0) / total
|
||||
for ev in evs:
|
||||
ev.t_ms *= scale
|
||||
out: List[_Ev] = []
|
||||
last_t = -MIN_EVENT_INTERVAL_MS
|
||||
for i, ev in enumerate(evs):
|
||||
if out and not ev.is_wheel and not out[-1].is_wheel \
|
||||
and ev.t_ms == out[-1].t_ms:
|
||||
# Two positions at one instant are one sample, and the sample a
|
||||
# device reports is the newest one it has.
|
||||
out[-1] = ev
|
||||
continue
|
||||
is_last = i == len(evs) - 1
|
||||
keep = (
|
||||
ev.is_wheel
|
||||
or is_last
|
||||
or ev.t_ms - last_t >= MIN_EVENT_INTERVAL_MS
|
||||
)
|
||||
if not keep:
|
||||
continue
|
||||
if is_last and out and not ev.is_wheel and not out[-1].is_wheel and ev.t_ms - last_t < MIN_EVENT_INTERVAL_MS:
|
||||
# The destination must be dispatched, so its PREDECESSOR goes
|
||||
# instead. Keeping both unconditionally is what let this function
|
||||
# emit a gap under its own floor - measured at 1.83 ms, 547 Hz,
|
||||
# with a tight time cap. A movement that stops one sample short of
|
||||
# where it was asked to go is a worse defect than one sample fewer.
|
||||
out.pop()
|
||||
last_t = out[-1].t_ms if out else -MIN_EVENT_INTERVAL_MS
|
||||
out.append(ev)
|
||||
last_t = ev.t_ms
|
||||
return out
|
||||
|
||||
|
||||
def _normalise_waypoints(raw: Iterable[Any], max_seconds: float) -> List[Tuple[float, float, float]]:
|
||||
"""Reduce whatever the generator returns to ``(x, y, delay_seconds)``.
|
||||
|
||||
@@ -717,64 +611,38 @@ async def _dispatch(
|
||||
*,
|
||||
timer: Any = None,
|
||||
emit_last: bool = True,
|
||||
origin: Optional[Tuple[float, float]] = None,
|
||||
) -> int:
|
||||
"""Walk a timeline against ABSOLUTE deadlines. Returns events delivered.
|
||||
"""The ASYNCHRONOUS driver of :class:`invisible_core.juggler.Pacer`. Returns events sent.
|
||||
|
||||
Every deadline is measured from one ``t0``, so oversleeping on one event
|
||||
does not push the next one out: lateness cannot accumulate.
|
||||
|
||||
When the platform cannot deliver an event on time - Windows quantises a
|
||||
short sleep to the system timer, so a 12 ms request routinely returns after
|
||||
16 - the event is DROPPED rather than sent late. The rule is
|
||||
parameter-free: an event is skipped when the NEXT event is already due,
|
||||
because sending it then would be sending two events at one instant and
|
||||
would push the whole rest of the movement backwards. What survives is a
|
||||
stream whose timestamps still land where the plan put them, at whatever
|
||||
density the machine can actually produce.
|
||||
|
||||
The last event is never dropped (it is where the movement ends) and neither
|
||||
is a wheel notch (it carries a delta nobody else will send).
|
||||
The rules it obeys - absolute deadlines from one ``t0``, drop rather than
|
||||
send late while the drop stays within reach, never two events in one
|
||||
instant - are not written here: they are in :mod:`._pacing`, because the
|
||||
server's drag is synchronous and has to obey the same ones. This function
|
||||
supplies a clock, a way of waiting and where the pointer starts from; it
|
||||
makes no decision the pacer has not already made.
|
||||
"""
|
||||
tm = timer if timer is not None else _TIMER
|
||||
if not evs:
|
||||
return 0
|
||||
min_gap = MIN_EVENT_INTERVAL_MS / 1000.0
|
||||
delivered = 0
|
||||
n = len(evs)
|
||||
pacer = Pacer(evs, emit_last=emit_last, origin=origin)
|
||||
with _fine_timer():
|
||||
t0 = tm.now()
|
||||
last_emit: Optional[float] = None
|
||||
for i, ev in enumerate(evs):
|
||||
last = i == n - 1
|
||||
droppable = not last and not ev.is_wheel
|
||||
deadline = t0 + ev.t_ms / 1000.0
|
||||
wait = deadline - tm.now()
|
||||
if wait > 0:
|
||||
await tm.sleep(wait)
|
||||
elif droppable and i + 1 < n:
|
||||
if tm.now() >= t0 + evs[i + 1].t_ms / 1000.0:
|
||||
continue # superseded: the next point is already due
|
||||
# Catching up after an overslept deadline must not produce two
|
||||
# events in the same instant: that is an event rate no device
|
||||
# reports, and it is as visible as being late was.
|
||||
if last_emit is not None:
|
||||
behind = min_gap - (tm.now() - last_emit)
|
||||
if behind > 0:
|
||||
if droppable:
|
||||
continue
|
||||
await tm.sleep(behind)
|
||||
if last and not emit_last:
|
||||
while True:
|
||||
what, arg = pacer.step(tm.now())
|
||||
if what == DONE:
|
||||
break
|
||||
if ev.is_wheel:
|
||||
if emit_wheel is not None:
|
||||
await emit_wheel(ev.dx, ev.dy)
|
||||
delivered += 1
|
||||
last_emit = tm.now()
|
||||
if what == SLEEP:
|
||||
await tm.sleep(arg)
|
||||
continue
|
||||
await emit_move(ev.x, ev.y)
|
||||
delivered += 1
|
||||
last_emit = tm.now()
|
||||
return delivered
|
||||
if arg.is_wheel:
|
||||
if emit_wheel is None:
|
||||
pacer.dropped() # nothing here can carry a notch
|
||||
continue
|
||||
await emit_wheel(arg.dx, arg.dy)
|
||||
else:
|
||||
await emit_move(arg.x, arg.y)
|
||||
pacer.emitted(tm.now())
|
||||
return pacer.delivered
|
||||
|
||||
|
||||
# ── registry ────────────────────────────────────────────────────────────────
|
||||
@@ -836,9 +704,10 @@ def _cursor_for_page(page: Any) -> Optional[_PageCursor]:
|
||||
factory = _motion_factory()
|
||||
if factory is None:
|
||||
return None
|
||||
seed = page_motion_seed(session.seed, page_number(page))
|
||||
try:
|
||||
cursor = _PageCursor(
|
||||
page_motion_seed(session.seed, session.next_ordinal()),
|
||||
seed,
|
||||
session.max_seconds,
|
||||
factory,
|
||||
)
|
||||
@@ -888,13 +757,6 @@ def _inside(x: float, y: float, w: Optional[float], h: Optional[float]) -> bool:
|
||||
return 0.0 <= x < float(w) and 0.0 <= y < float(h)
|
||||
|
||||
|
||||
def _clamp(x: float, y: float, w: Optional[float], h: Optional[float]) -> Tuple[float, float]:
|
||||
if not w or not h:
|
||||
return x, y
|
||||
return (
|
||||
min(max(x, 0.0), float(w) - 1.0),
|
||||
min(max(y, 0.0), float(h) - 1.0),
|
||||
)
|
||||
|
||||
|
||||
# The errors a page can legitimately produce while we are only *aiming*: the
|
||||
@@ -970,20 +832,29 @@ async def _target_point(frame: Any, selector: str, position: Any) -> Optional[Tu
|
||||
|
||||
|
||||
async def _hits(handle: Any, x: float, y: float) -> bool:
|
||||
"""Does (x, y) actually land on this element?
|
||||
"""Does (x, y), in the same main-frame space as the box, land on this element?
|
||||
|
||||
A bounding box is not the element. An inline link that wraps across two
|
||||
lines, a rotated control, a rounded button: all of them have points inside
|
||||
their box that belong to something else. The centre is checked by the
|
||||
automation layer itself; a point we chose has to be checked by us, or we
|
||||
would be turning working clicks into hit-target failures.
|
||||
|
||||
⛔ THE QUESTION GOES TO THE SERVER, WHICH ANSWERS IT FOR THE ACTION TOO
|
||||
(`Actions.hit_target`). It used to be answered here with
|
||||
`document.elementFromPoint`, in the element's own document but at the
|
||||
main frame's coordinates: in a nested frame that asked about another
|
||||
place, and in a shadow root the hit is the host, never the control. Both
|
||||
rejected every off-centre point, so those clicks went to the exact
|
||||
geometric centre, one number for every install. `checkHitTarget` is a
|
||||
method of this package's server, not of Playwright's protocol: the Node
|
||||
driver arm (`INVPW_TRANSPORT=driver`) refuses it, and there the landing
|
||||
falls back to the centre.
|
||||
"""
|
||||
try:
|
||||
return bool(await handle.evaluate(
|
||||
"(el, p) => { const e = document.elementFromPoint(p.x, p.y);"
|
||||
" return !!e && (e === el || el.contains(e) || e.contains(el)); }",
|
||||
{"x": x, "y": y},
|
||||
))
|
||||
return bool(await handle._channel.send(
|
||||
"checkHitTarget", None, {"point": {"x": x, "y": y}},
|
||||
is_internal=True))
|
||||
except _page_errors():
|
||||
return False
|
||||
|
||||
@@ -1049,7 +920,8 @@ async def _travel(
|
||||
await raw_move(x, y)
|
||||
cursor.x, cursor.y = x, y
|
||||
|
||||
await _dispatch(evs, emit, timer=timer, emit_last=False)
|
||||
await _dispatch(evs, emit, timer=timer, emit_last=False,
|
||||
origin=(cursor.x, cursor.y))
|
||||
cursor.x, cursor.y = to_x, to_y
|
||||
cursor.last_event_at = (timer or _TIMER).now()
|
||||
return 0.0
|
||||
@@ -1074,7 +946,8 @@ async def _run_steps(
|
||||
await emit_move(x, y)
|
||||
cursor.x, cursor.y = x, y
|
||||
|
||||
await _dispatch(evs, move, emit_wheel, timer=timer, emit_last=emit_last)
|
||||
await _dispatch(evs, move, emit_wheel, timer=timer, emit_last=emit_last,
|
||||
origin=(cursor.x, cursor.y))
|
||||
if not emit_last and evs:
|
||||
cursor.x, cursor.y = evs[-1].x, evs[-1].y
|
||||
cursor.last_event_at = (timer or _TIMER).now()
|
||||
@@ -1117,16 +990,16 @@ def _plan_fidget(cursor: _PageCursor, page: Any, timer: Any) -> List[Any]:
|
||||
# A movement that ends nowhere in particular. If every movement of a
|
||||
# session terminates on a control then the SET OF ENDPOINTS is a
|
||||
# signature on its own, whatever the paths between them look like.
|
||||
steps = _behaviour.plan_aimless_move(
|
||||
steps = plan_aimless_move(
|
||||
cursor.seed, cursor.persona, here, bounds,
|
||||
nonce=cursor.action, render=cursor.renderer(bounds),
|
||||
)
|
||||
return _behaviour.tail_within(steps, budget, here, bounds)
|
||||
steps = _behaviour.plan_idle(
|
||||
return tail_within(steps, budget, here, bounds)
|
||||
steps = plan_idle(
|
||||
cursor.seed, cursor.persona, here, bounds, gap_ms,
|
||||
nonce=cursor.action, render=cursor.renderer(bounds),
|
||||
)
|
||||
return _behaviour.tail_within(steps, budget, here, bounds)
|
||||
return tail_within(steps, budget, here, bounds)
|
||||
|
||||
|
||||
# ── the wrappers ────────────────────────────────────────────────────────────
|
||||
@@ -1239,6 +1112,13 @@ async def _approach(frame: Any, args: Sequence[Any], kwargs: dict,
|
||||
"""
|
||||
# A trial run performs the actionability checks without touching anything,
|
||||
# so it must not move a real cursor either.
|
||||
#
|
||||
# ⛔ AND THIS IS NOT WHERE `trial` IS HONOURED, which matters because for a
|
||||
# long time it was the only place that read the word at all. The action
|
||||
# itself ran regardless, so skipping the approach here made the outcome
|
||||
# WORSE: the click still went out, now with no pointer movement in front of
|
||||
# it. It is honoured in `Actions._retry`, where actionability lives; this
|
||||
# line only keeps the cursor still while that happens.
|
||||
if kwargs.get("trial"):
|
||||
return None
|
||||
page = _page_of_frame(frame)
|
||||
@@ -1314,7 +1194,7 @@ async def _choose_landing(frame: Any, cursor: Any, selector: str,
|
||||
return _Aim(box, (box["x"] + float(position["x"]),
|
||||
box["y"] + float(position["y"])), None)
|
||||
|
||||
landing = _behaviour.landing_point(
|
||||
landing = landing_point(
|
||||
(box["x"], box["y"], box["width"], box["height"]),
|
||||
cursor.rng("cursor:landing"),
|
||||
spread=_LANDING_SPREAD, keep=_LANDING_KEEP,
|
||||
@@ -1357,7 +1237,7 @@ async def _walk_onto(cursor: Any, page: Any, aim: _Aim, move: Any,
|
||||
await _run_steps(cursor, fidget, raw, budget_s=spent, timer=timer)
|
||||
budget = max(budget - spent, 0.2)
|
||||
|
||||
steps = _behaviour.plan_approach(
|
||||
steps = plan_approach(
|
||||
cursor.seed, cursor.persona, cursor.here(page), aim.rect, bounds,
|
||||
nonce=cursor.action, landing=aim.landing,
|
||||
render=cursor.renderer(bounds),
|
||||
@@ -1468,7 +1348,7 @@ def _scroll_plan(cursor: _PageCursor, page: Any, delta_x: float, delta_y: float
|
||||
if ticks < 2:
|
||||
return []
|
||||
bounds = _bounds(page)
|
||||
steps = _behaviour.plan_scroll(
|
||||
steps = plan_scroll(
|
||||
cursor.seed, cursor.persona, cursor.here(page), bounds,
|
||||
ticks=ticks, tick_dy=1.0, nonce=cursor.action,
|
||||
render=cursor.renderer(bounds),
|
||||
@@ -1492,7 +1372,7 @@ def _scroll_plan(cursor: _PageCursor, page: Any, delta_x: float, delta_y: float
|
||||
dx, dy = delta_x * frac, delta_y * frac
|
||||
used_x += dx
|
||||
used_y += dy
|
||||
out.append(_behaviour.Step(x=s.x, y=s.y, delay_ms=s.delay_ms,
|
||||
out.append(Step(x=s.x, y=s.y, delay_ms=s.delay_ms,
|
||||
kind="wheel", dx=dx, dy=dy))
|
||||
return out
|
||||
|
||||
|
||||
@@ -98,11 +98,17 @@ def assert_playwright_range() -> None:
|
||||
|
||||
if t(seal.playwright_min) <= t(have) <= t(seal.playwright_max):
|
||||
return
|
||||
# Spelled by the tool that installed this package (`invisible_core.installer`):
|
||||
# a written `pip install` is a command the venv the README makes does not have.
|
||||
from invisible_core.installer import install
|
||||
from invisible_core.pin import format_command
|
||||
|
||||
fix = format_command(install("invisible-playwright", f"playwright=={seal.playwright_max}"))
|
||||
msg = (f"playwright {have} is outside the range this engine was tested with "
|
||||
f"({seal.playwright_min} .. {seal.playwright_max}, from the seal for {seal.tag}).\n"
|
||||
f"The Juggler protocol schema is closed-world: an untested client can kill every "
|
||||
f"session at context creation.\n"
|
||||
f'Run: pip install "playwright=={seal.playwright_max}" '
|
||||
f"Run: {fix} "
|
||||
f"(or set INVISIBLE_PLAYWRIGHT_SKEW=allow to proceed anyway)")
|
||||
if os.environ.get("INVISIBLE_PLAYWRIGHT_SKEW") == "allow":
|
||||
warnings.warn(msg, RuntimeWarning, stacklevel=2)
|
||||
|
||||
@@ -1,20 +1,23 @@
|
||||
"""The Juggler client in Python: the break from Playwright, piece by piece.
|
||||
"""The Playwright side of the engine: a server that speaks Playwright's protocol and drives Juggler.
|
||||
|
||||
| module | what it does |
|
||||
|---|---|
|
||||
| `protocol.py` | GENERATED by `scripts/gen_juggler_protocol.py` reading the `Protocol.js` that lives inside the SHIPPED binary: 71 commands, 34 events |
|
||||
| `connection.py` | the pipe to Juggler. JSON delimited by a zero byte; fd 3/4 on POSIX, inheritable HANDLEs on Windows |
|
||||
| `lifecycle.py` | frame tree, navigations, the four load states |
|
||||
| `injected.py` | loads `injected.js` into the UTILITY world and calls it: selectors and actionability |
|
||||
| `injected.js` | extracted from the bundle with `scripts/gen_injected_source.py`. It is not upstream: it carries the fork's stealth fixes |
|
||||
| `server.py` | the Playwright channel: browsers, contexts, pages, frames, routes; every call ends in the Juggler client |
|
||||
| `dispatcher.py` | the object tree Playwright's client talks to, and the guids it names them by |
|
||||
| `_marshal.py` | values across the channel, both ways |
|
||||
| `transport.py` | the in-process transport between the client and this server |
|
||||
| `perimeter.py` | what the server refuses on purpose, said as errors rather than pretended |
|
||||
|
||||
⛔ **No product module imports this package yet**: it is inert by
|
||||
construction, and stays that way until `_impl` leans on it. What is missing
|
||||
lives in `docs/firefox-stealth-architecture/32-stacco-da-playwright.md` §6,
|
||||
which is also the only place where the design and the inventory of
|
||||
constraints live.
|
||||
⛔ THE JUGGLER CLIENT ITSELF IS NOT HERE. Since 0.30.0 the pipe, the protocol
|
||||
mirror, the frame lifecycle, the injected script, the input actions, the
|
||||
keyboard and the human rhythm (`connection`, `protocol`, `lifecycle`,
|
||||
`injected`, `actions`, `keyboard`, `keylayout`, `_profile`, `_behaviour`,
|
||||
`_motion`, `_pacing`) live once in `invisible_core.juggler`, shared with
|
||||
invisible-selenium and invisible-puppeteer (decision D85). A copy of any of them
|
||||
in this folder is the defect that move removed, and
|
||||
`tests/test_juggler_lives_in_the_core.py` refuses it.
|
||||
|
||||
⛔ **What lives here REACHES the user**, because it sits under
|
||||
⛔ What lives here REACHES the user, because it sits under
|
||||
`src/invisible_playwright/`. A tool that only serves us goes in `scripts/`,
|
||||
which the wheel does not include.
|
||||
"""
|
||||