diff --git a/.gitattributes b/.gitattributes index cc16521c..6efadabb 100644 --- a/.gitattributes +++ b/.gitattributes @@ -69,3 +69,6 @@ js/developer/tools/* text eol=lf js/developer/scripts/* text eol=lf js/developer/webfront.project.json text eol=lf js/developer/webfront-packages.lock.json text eol=lf + +# The starters of the environment are hashed inputs and starter archives too. +js/developer/starters/** text eol=lf diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index ba66995e..9e19c234 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -49,6 +49,11 @@ build needs neither tool. Current build/test commands are in [AGENTS.md](../AGEN and developer-environment publication is described in [PUBLISHING.md](../js/developer/tools/PUBLISHING.md). +With GCC 13, building WebFront's tests in Release mode can produce false positive +`-Wnull-dereference` warnings in libstdc++. Configure with +`-DWARNINGS_AS_ERRORS=OFF` to build the tests; GCC 13 is not currently covered +by a dedicated test job. + - **File-level documentation:** Use `@brief` only, no `@file` or `@author` tags. - **Class documentation:** Include `@brief` with detailed description and usage examples. - **Method documentation:** @@ -105,9 +110,30 @@ To ensure consistency, we use `.clang-format` and `clang-tidy` to enforce our co Please run these tools on your code before submitting a pull request. +## Changelog format + +[`docs/CHANGELOG.md`](../docs/CHANGELOG.md) answers three questions quickly: what changes for me, is anything breaking, and +what must I do to migrate. It is not an implementation journal: that belongs to the ADRs, the guides under `docs/`, the pull +request description and the Git history, and a changelog entry points there. + +- Versions are listed newest first, as `## [x.y.z] - YYYY-MM-DD`, under `## Unreleased`. Each has a comparison link at the + foot of the file (`[0.9.0]: https://github.com/ambroise-leclerc/WebFront/compare/v0.8.0...v0.9.0`). +- A version opens with a summary of three to five lines: what to remember, and whether there is a breaking change or a + migration (say "No breaking change" when there is none). +- Categories, in this order and omitted when empty: `Breaking`, `Added`, `Changed`, `Fixed`, `Security`. A breaking change + states the migration in its line. +- One entry is one line, two at most, in the imperative, saying the effect for the user rather than the mechanism, and ending + with its references: `(#NNN)`, an ADR or a guide. Error codes, platform paths and internals go to the ADR or the guide. +- A recent version stays within about 50 lines. Detail the summary leaves out belongs to the ADR, the guide or the pull + request, and the GitHub release keeps the history. +- Do not generate the changelog from commit messages. + +The `ChangelogFormat` CTest case (`test/cmake/CheckChangelogFormat.cmake`) checks the headings, categories and their order, +the entry length, the references (from 0.7.0 on, and always in `Unreleased`) and the comparison links, for `Unreleased` too. + ## Pull Requests -- **One commit per pull request.** +- **One commit per pull request on `develop`:** pull requests are merged with a squash merge. Before the merge, a branch carries as many commits as needed; add follow-up commits instead of amending or force-pushing. - The pull request (PR) title must reference the related issue or feature (e.g., `Add CameraManager class [#42]`). - Provide a clear description of the changes and the motivation. - Ensure your branch is up to date with `develop` before submitting. diff --git a/.github/actions/setup-cmake/action.yml b/.github/actions/setup-cmake/action.yml index 60235d23..8864b5ba 100644 --- a/.github/actions/setup-cmake/action.yml +++ b/.github/actions/setup-cmake/action.yml @@ -16,7 +16,13 @@ runs: run: | set -euo pipefail case "$RUNNER_OS" in - Linux) platform=linux-x86_64; extension=tar.gz; bin=bin ;; + Linux) + case "$(uname -m)" in + x86_64) platform=linux-x86_64 ;; + aarch64) platform=linux-aarch64 ;; + *) echo "::error::No CMake archive for Linux $(uname -m)"; exit 1 ;; + esac + extension=tar.gz; bin=bin ;; macOS) platform=macos-universal; extension=tar.gz; bin=CMake.app/Contents/bin ;; Windows) platform=windows-x86_64; extension=zip; bin=bin ;; *) echo "::error::No CMake archive for $RUNNER_OS"; exit 1 ;; @@ -25,9 +31,11 @@ runs: # From cmake--SHA-256.txt of each Kitware release. case "$name.$extension" in cmake-4.4.4-linux-x86_64.tar.gz) expected=e5bb807f7728cb60cd8b27ebc97a2edb469b68655f21e844a600c3575b76f5bb ;; + cmake-4.4.4-linux-aarch64.tar.gz) expected=a1b6cc63636a0e55c63257cf3315a8a5f129e42fade25db1afea4ff8ab06f25e ;; cmake-4.4.4-macos-universal.tar.gz) expected=4b7b73704b1db9b374e5c9ab8e17ac6148b817b6396ee75cd94a852cbac9d305 ;; cmake-4.4.4-windows-x86_64.zip) expected=bace36e94b31c68ab6fa295f26dfa11219e0701cf7c94b0284a7d1cb13dac536 ;; cmake-4.3.1-linux-x86_64.tar.gz) expected=208d76804009cbe8ec9aea0aa052c857c6e59bd289b43b9941c99324dc78b1d8 ;; + cmake-4.3.1-linux-aarch64.tar.gz) expected=2c0eca48ac7d0e3a8b4120b801d48903b0630c8ff1e73c44a90398a300dec1ac ;; cmake-4.3.1-macos-universal.tar.gz) expected=c21fe4ade82a6a236aae0b9fbd8263c7ac6824a3fb32d03594456e30b06f3b7f ;; cmake-4.3.1-windows-x86_64.zip) expected=03a610be931546474e46a442d171ef10532f4fc847de9cf76b7a8065bbef6a23 ;; *) echo "::error::No pinned SHA-256 for $name.$extension: add it to .github/actions/setup-cmake/action.yml"; exit 1 ;; diff --git a/.github/actions/wf-driver/action.yml b/.github/actions/wf-driver/action.yml index 438cd55e..7043be1e 100644 --- a/.github/actions/wf-driver/action.yml +++ b/.github/actions/wf-driver/action.yml @@ -13,20 +13,31 @@ runs: - name: Install GCC 16 and WebKitGTK shell: bash run: | - # The hosted runner's Azure mirror can trickle large GCC packages until the job times out. - # Keep Ubuntu's suites and package verification, using its primary archive instead. - if [ -f /etc/apt/apt-mirrors.txt ]; then - sudo sed -i 's|azure\.archive\.ubuntu\.com|archive.ubuntu.com|g' /etc/apt/apt-mirrors.txt + # The hosted runner's Azure mirror can trickle large GCC packages until the job times out, and so can Ubuntu's + # primary archive. Keep Ubuntu's suites and package verification, start with the primary archive, bound the + # attempt and fall back to the runner's own mirror. Both attempts and the repair between them take at most + # 11 minutes, inside the 15 minutes of the shortest job that uses this action; an install takes under a minute. + mirrors=/etc/apt/apt-mirrors.txt + install() { + sudo timeout 60 apt-get update && sudo timeout 240 apt-get install -y --no-install-recommends -o Acquire::Retries=3 -o Acquire::http::Timeout=15 gcc-16 g++-16 libwebkitgtk-6.0-dev + } + if [ -f "$mirrors" ]; then + sudo cp "$mirrors" "$mirrors.hosted" + sudo sed -i 's|azure\.archive\.ubuntu\.com|archive.ubuntu.com|g' "$mirrors" + fi + if ! install; then + echo "::warning::The primary Ubuntu archive did not deliver the packages in time; using the runner's mirror" + if [ -f "$mirrors.hosted" ]; then sudo cp "$mirrors.hosted" "$mirrors"; fi + sudo timeout 60 dpkg --configure -a || echo "::warning::The interrupted installation could not be repaired in time" + install fi - sudo apt-get update - sudo apt-get install -y --no-install-recommends -o Acquire::Retries=3 gcc-16 g++-16 libwebkitgtk-6.0-dev echo "CC=gcc-16" >> "$GITHUB_ENV" echo "CXX=g++-16" >> "$GITHUB_ENV" - name: Build webfront-wf shell: bash run: | cmake -S . -B build-driver -G Ninja -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_EMBED_CEF=OFF -DWEBFRONT_ENABLE_TESTING=ON \ - -DWEBFRONT_EMBED_WEBKITGTK=ON -DWEBFRONT_WEBTEST_FRONTEND=WebKitGTK \ + -DWEBFRONT_EMBED_WEBKITGTK=ON -DWEBFRONT_WEBTEST_FRONTEND=WebKitGTK -DWEBFRONT_TEST_REPRODUCIBILITY=ON \ -DCMAKE_CXX_SCAN_FOR_MODULES=OFF cmake --build build-driver --target webfront-wf --parallel 2 - name: Install the wf command diff --git a/.github/scripts/check-no-ai-attribution.sh b/.github/scripts/check-no-ai-attribution.sh index c66c95ba..bdd05bc4 100755 --- a/.github/scripts/check-no-ai-attribution.sh +++ b/.github/scripts/check-no-ai-attribution.sh @@ -27,7 +27,9 @@ if [ -n "$base" ]; then fi # One Git process supplies all records. Bash matches each line directly, avoiding four grep # processes and two git-show processes per regression case (especially costly on macOS). -if ! git log --no-show-signature --no-notes --no-decorate --no-patch --no-color --no-graph -z --format='%H%x00%an <%ae>%n%cn <%ce>%x00%B' "$revision" >"$commits"; then +# Graph output requires a command-line option; log.graphColors only chooses its colors. +# Do not add --no-graph: Git 2.34 rejects it, and no config setting enables --graph. +if ! git log --no-show-signature --no-notes --no-decorate --no-patch --no-color -z --format='%H%x00%an <%ae>%n%cn <%ce>%x00%B' "$revision" >"$commits"; then echo "::error::unable to list the commits in $revision" exit 1 fi diff --git a/.github/scripts/jetson-orin.sh b/.github/scripts/jetson-orin.sh new file mode 100755 index 00000000..58a0dc3c --- /dev/null +++ b/.github/scripts/jetson-orin.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# Trusted workflow only. The service supplies PATH, CC/CXX and CUDAHOSTCXX where needed. +set -euo pipefail +umask 077 +test "$(uname -m)" = aarch64 +test -r /etc/nv_tegra_release +: "${WEBFRONT_JETSON_CACHE:?Set an absolute cache directory owned by the runner}" +[[ "$WEBFRONT_JETSON_CACHE" = /* ]] +export CCACHE_DIR="$WEBFRONT_JETSON_CACHE/ccache" +export CPM_SOURCE_CACHE="$WEBFRONT_JETSON_CACHE/cpm" +export CUDA_CACHE_PATH="$WEBFRONT_JETSON_CACHE/cuda" +export CUDA_CACHE_MAXSIZE=268435456 +export WEBFRONT_TEST_TIMEOUT_FACTOR=2 +mkdir -p "$CCACHE_DIR" "$CPM_SOURCE_CACHE" "$CUDA_CACHE_PATH" +ccache --max-size 6G +# Never inherit a desktop display or a software-renderer override. CTest creates Xvfb. +unset DISPLAY WAYLAND_DISPLAY GSK_RENDERER LIBGL_ALWAYS_SOFTWARE WEBKIT_DISABLE_DMABUF_RENDERER +{ + echo '### Jetson Orin hardware validation' + echo '```text' + cat /etc/nv_tegra_release + dpkg-query -W nvidia-jetpack nvidia-l4t-core 2>/dev/null || true + uname -a + "${CXX:-c++}" --version + cmake --version + pkg-config --modversion webkitgtk-6.0 + nvcc --version + nvpmodel -q + echo '```' +} >> "${GITHUB_STEP_SUMMARY:-/dev/stdout}" +# Fixed names, no user input; stale/interrupted builds are removed on the next job too. +rm -rf -- build-jetson-core build-jetson-webkitgtk +# CPM has no LRU. Clear only this dedicated cache above its 8 GiB high-water mark. +if (( $(du -sm "$CPM_SOURCE_CACHE" | cut -f1) > 8192 )); then + find "$CPM_SOURCE_CACHE" -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + +fi +common=(-G Ninja -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_ENABLE_TESTING=ON + -DWEBFRONT_EMBED_CEF=OFF -DWARNINGS_AS_ERRORS=OFF -DENABLE_CACHE=OFF + -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_SCAN_FOR_MODULES=OFF + -DCMAKE_JOB_POOLS=jetson_compile=1 -DCMAKE_JOB_POOL_COMPILE=jetson_compile + -DWEBFRONT_HOST_LOOP_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=87) +cmake -S . -B build-jetson-core "${common[@]}" -DWEBFRONT_EMBED_WEBKITGTK=OFF +cmake --build build-jetson-core --parallel 2 +# Select one scenario directly: Bdd exits 4 if it skips for lack of a GPU. CTest permits skips. +build-jetson-core/test/unit/tests --exact 'Host loop: CUDA computes the image of the CPU, within the rounding of the device' +ctest --test-dir build-jetson-core --output-on-failure --no-tests=error --parallel 2 \ + --output-junit core-results.xml +cmake -S . -B build-jetson-webkitgtk "${common[@]}" -DWEBFRONT_EMBED_WEBKITGTK=ON \ + -DWEBFRONT_WEBTEST_FRONTEND=WebKitGTK -DWEBFRONT_BUILD_EXAMPLES=OFF +cmake --build build-jetson-webkitgtk --target webtest developer_integration webfront-wf --parallel 2 +ctest --test-dir build-jetson-webkitgtk -L web-integration --output-on-failure --no-tests=error \ + --parallel 2 --output-junit webkitgtk-results.xml +ccache --show-stats diff --git a/.github/scripts/test-no-ai-attribution.sh b/.github/scripts/test-no-ai-attribution.sh index 147f5231..e8c0f400 100755 --- a/.github/scripts/test-no-ai-attribution.sh +++ b/.github/scripts/test-no-ai-attribution.sh @@ -64,6 +64,7 @@ chmod +x "$work/verify-signature" git config gpg.program "$work/verify-signature" git config log.showSignature true git config log.decorate full +git config log.graphColors red,green git config log.showNotes true git config format.pretty oneline signed_clean="$(signed "$clean" 'Ordinary signed change')" @@ -80,6 +81,7 @@ fi git config --unset gpg.program git config --unset log.showSignature git config --unset log.decorate +git config --unset log.graphColors git config --unset log.showNotes git config --unset format.pretty diff --git a/.github/workflows/BuildAndTest.yml b/.github/workflows/BuildAndTest.yml index 8049ae9c..64bb0b0c 100644 --- a/.github/workflows/BuildAndTest.yml +++ b/.github/workflows/BuildAndTest.yml @@ -9,16 +9,36 @@ on: - cron: '23 4 * * 1' workflow_dispatch: inputs: + jetson_orin: + description: 'Validate a trusted branch on the Jetson hardware runner (maintainer only)' + type: boolean + default: false + gcc13_arm64: + description: 'Also run GCC 13 ARM64 and its ASan/UBSan fast tests' + type: boolean + default: false + cef_arm64: + description: 'Also run the CEF linuxarm64 browser integration (GCC 13)' + type: boolean + default: false + webkitgtk_arm64: + description: 'Also run the WebKitGTK aarch64 browser integration (GCC 13)' + type: boolean + default: false repeat_desktop_tests: - description: 'Also run the desktop matrix, repeating the complete CTest suite three times' + description: 'Also run the desktop matrix, repeating the complete CTest suite desktop_passes times' type: boolean default: false + desktop_passes: + description: 'Passes of the complete desktop suite when repeat_desktop_tests is set (20 qualifies a reliability fix)' + type: number + default: 3 permissions: contents: read concurrency: - group: build-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + group: build-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-${{ inputs.jetson_orin && 'jetson' || 'hosted' }} # Never cancel a push to a release branch: its coverage upload must complete. cancel-in-progress: ${{ github.event_name == 'pull_request' }} @@ -31,6 +51,36 @@ env: # Third-party actions are pinned to commit SHAs; GitHub-owned actions/* use version tags. jobs: + # Pre-merge entry point: the standalone workflow cannot be dispatched until it is on the default branch. + jetson-validation: + if: >- + github.repository == 'ambroise-leclerc/WebFront' && !cancelled() && github.event_name == 'workflow_dispatch' && + github.actor == 'ambroise-leclerc' && github.ref_type == 'branch' && inputs.jetson_orin + runs-on: [self-hosted, linux, arm64, jetson-orin] + timeout-minutes: 180 + concurrency: + group: jetson-orin + cancel-in-progress: false + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - name: Build and test at low priority + run: nice -n 15 ionice -c 3 bash .github/scripts/jetson-orin.sh + - name: Retain diagnostics + if: always() + uses: actions/upload-artifact@v4 + with: + name: jetson-orin-${{ github.run_id }} + path: | + build-jetson-*/Testing/Temporary/LastTest.log + build-jetson-*/*results.xml + retention-days: 14 + if-no-files-found: ignore + - name: Remove job build directories + if: always() + run: rm -rf -- build-jetson-core build-jetson-webkitgtk + # The Linux toolchain image is tagged with the hash of its Dockerfile and built only when that tag is missing from ghcr.io, # so a change of the Dockerfile is validated by the very run that carries it. A pull request from a fork cannot push it # (read-only token): its Linux job then fails at the pull, which a maintainer re-run on a branch of this repository fixes. @@ -69,7 +119,7 @@ jobs: # Only Linux waits for its image. Native desktops below start immediately and reuse these steps. if: ${{ !cancelled() && (github.event_name != 'workflow_dispatch' || inputs.repeat_desktop_tests) }} # No `name:` expression: a skipped matrix job would display it unevaluated. - timeout-minutes: 25 + timeout-minutes: ${{ github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests && (inputs.desktop_passes > 3 && 300 || 90) || 25 }} strategy: fail-fast: false matrix: @@ -104,6 +154,20 @@ jobs: fi echo "Reproducibility builds: $reproducibility" echo "WEBFRONT_REPRODUCIBILITY=$reproducibility" >> "$GITHUB_ENV" + # The cases that configure a CMake project (label `configuration`, about 75 s of worker time on Windows) test the build + # system: a pull request into develop runs them only when it changes the build system or this workflow. A push to + # develop and the full tier always run them. + - name: Decide whether the configuration checks run + shell: bash + run: | + configuration=true + if [ "$FULL_TIER" != true ] && [ "$GITHUB_EVENT_NAME" = pull_request ]; then + if ! git diff --name-only HEAD^1 HEAD | grep -qE '^(cmake/|CMakeLists\.txt|js/core/[^/]*\.cmake|test/cmake/|test/unit/CMakeLists\.txt|\.github/actions/|\.github/workflows/BuildAndTest\.yml)'; then + configuration=false + fi + fi + echo "Configuration checks: $configuration" + echo "WEBFRONT_CONFIGURATION=$configuration" >> "$GITHUB_ENV" # No step of a build or of its tests needs a JavaScript runtime or package manager: the runner has none from here on. - uses: ./.github/actions/remove-node - uses: ./.github/actions/setup-cmake @@ -141,6 +205,8 @@ jobs: sccache --version # ENABLE_CACHE controls automatic ccache discovery; the explicit sccache launcher stays enabled. # The heavy unit tests are compiled four to a file (docs/BUILD_TIME_STUDY.md); the portability and sanitizer jobs keep one object per test file. + # No job relies on a default of the test options: the defaults are those of a quick local build (docs/TEST_TIERS.md). + # The unit tests run as four shards instead of one process per scenario (docs/TEST_TIERS.md). - name: Configure run: >- cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=${{ matrix.build_type }} @@ -148,11 +214,12 @@ jobs: -DENABLE_CACHE=OFF -DCMAKE_CXX_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_SCAN_FOR_MODULES=OFF -DWEBFRONT_TEST_UNITY_BATCH=4 + -DWEBFRONT_TEST_UNIT_SHARDS=4 -DWEBFRONT_TEST_REPRODUCIBILITY=${{ env.WEBFRONT_REPRODUCIBILITY }} - ${{ env.FULL_TIER == 'true' && '' || '-DWEBFRONT_MSVC_ANALYZE=OFF -DWEBFRONT_BUILD_EXAMPLES=OFF' }} + ${{ env.FULL_TIER == 'true' && '-DWEBFRONT_MSVC_ANALYZE=ON -DWEBFRONT_BUILD_EXAMPLES=ON' || '-DWEBFRONT_MSVC_ANALYZE=OFF -DWEBFRONT_BUILD_EXAMPLES=OFF' }} ${{ matrix.options }} - name: Build - run: python3 test/tools/MeasureCommand.py --output build/build-resources.json -- cmake --build build --config ${{ matrix.build_type }} --parallel 4 + run: cmake --build build --config ${{ matrix.build_type }} --parallel 4 ${{ runner.os == 'Windows' && '-- -k 0' || '' }} - name: Ensure WebView2 Evergreen runtime if: runner.os == 'Windows' shell: pwsh @@ -183,74 +250,31 @@ jobs: # The fast tier (docs/TEST_TIERS.md): unit tests only, so a plain regression is reported before the browser suite starts. - name: Fast tests shell: bash - run: ctest --test-dir build -C ${{ matrix.build_type }} -L fast --parallel 4 --output-on-failure --no-tests=error - - name: Capture CTest dependency graph - shell: bash - run: ctest --test-dir build --show-only=json-v1 > build/ctest-graph.json + run: >- + ctest --test-dir build -C ${{ matrix.build_type }} -L fast ${{ env.WEBFRONT_CONFIGURATION != 'true' && '-LE configuration' || '' }} + --parallel 4 --output-on-failure --no-tests=error --output-junit "$PWD/build/fast-results.xml" - name: Test C++ and native browser integration + id: desktop_suite + # The fast tier has just run: a single pass does not run it again; the three passes of the complete tier do. # Only Linux trusted fixtures need the sandbox opt-out on hosted runners. env: ${{ matrix.test_env }} run: >- - python3 test/tools/MeasureCommand.py --output build/suite-resources.json -- cmake -DBUILD_DIR=build -DCONFIG=${{ matrix.build_type }} - -DREPEAT=${{ (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.base_ref == 'master') || (github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests)) && '3' || '1' }} - -DLABEL_EXCLUDE=${{ (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.base_ref == 'master') || (github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests)) && 'none' || 'portability' }} + -DREPEAT=${{ (github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests) && inputs.desktop_passes || ((github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.base_ref == 'master')) && '3' || '1') }} + '-DLABEL_EXCLUDE=${{ (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.base_ref == 'master') || (github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests)) && 'none' || (env.WEBFRONT_CONFIGURATION == 'true' && '^(portability|fast)$' || '^(portability|fast|configuration)$') }}' -P test/cmake/RunTestSuite.cmake - - name: Repeat WebKitGTK pointer tests with suite display sharing enabled - if: runner.os == 'Linux' - env: ${{ matrix.test_env }} - # These tests must still get private displays when invoked from the shared-display suite runner. - run: >- - xvfb-run -a env WEBFRONT_TEST_SHARED_DISPLAY=1 - ctest --test-dir build --output-on-failure --no-tests=error - -R '^WebKitGTKAdapter-(choose-file|cancel-choose|close-with-dialog)$' --repeat until-fail:5 - - name: Analyze CTest timings - if: always() - shell: bash - run: python3 test/tools/ProfileTests.py build/ctest-graph.json build/test-results-*.xml --workers 4 --log build/Testing/Temporary/LastTest.log --ninja-log build/.ninja_log --output build/test-profile.txt - - name: Probe compiler cache on the embedded builds - # Diagnostic (#388): do the Life embedded translation units hit the compiler cache once the suite has warmed it? - if: ${{ !cancelled() }} - continue-on-error: true - shell: bash - run: | - { - echo "Before the probe (whole run):" - sccache --show-stats | grep -E '^(Compile requests|Cache hits|Cache misses) ' - for target in life_embedded life_journey; do - sccache --zero-stats > /dev/null - start=$(date +%s) - cmake --build build --config ${{ matrix.build_type }} --target "$target" --clean-first > "build/probe-$target.log" 2>&1 || tail -n 20 "build/probe-$target.log" - echo "$target clean rebuild: $(( $(date +%s) - start )) s" - sccache --show-stats | grep -E '^(Compile requests|Cache hits|Cache misses) ' - done - # The consumer project of AddSubdirectoryConsumer: its single translation unit against the warm cache. - sccache --zero-stats > /dev/null - start=$(date +%s) - cmake --build build/test/unit/consumer-build --config ${{ matrix.build_type }} --clean-first > build/probe-consumer.log 2>&1 || tail -n 20 build/probe-consumer.log - echo "consumer clean rebuild: $(( $(date +%s) - start )) s" - sccache --show-stats | grep -E '^(Compile requests|Cache hits|Cache misses) ' - } 2>&1 | tee build/embedded-cache-probe.txt + # Nothing consumes the capture of a pull request, which only lists it in its log: it runs on a push to develop or master + # and in the full tier. The pull request still builds and runs the instrumented tests. - name: Collect coverage - if: runner.os == 'Linux' + if: runner.os == 'Linux' && (github.event_name == 'push' || env.FULL_TIER == 'true') shell: bash working-directory: build - env: - BENCHMARK_COVERAGE: ${{ github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests }} run: | set -euo pipefail # lcov 2 on Ubuntu 26.04 rejects the benign line/function hit inconsistencies GCC emits for templates. - if [[ "$BENCHMARK_COVERAGE" == true ]]; then - /usr/bin/time -v -o coverage-pp-capture.txt lcov --rc lcov_json_module=JSON::PP --ignore-errors inconsistent,inconsistent --gcov-tool gcov-16 --capture --directory . --output-file coverage-pp.info - fi - perl -MJSON::XS -e 'print "Fast JSON backend JSON::XS $JSON::XS::VERSION\n"' - /usr/bin/time -v -o coverage-capture.txt lcov --verbose --rc lcov_json_module=JSON::XS --ignore-errors inconsistent,inconsistent --gcov-tool gcov-16 --capture --directory . --output-file coverage.info 2>&1 | tee coverage-capture.log - grep -F 'Using JSON module JSON::XS' coverage-capture.log - if [[ "$BENCHMARK_COVERAGE" == true ]]; then - python3 ../test/tools/CompareCoverage.py coverage-pp.info coverage.info - fi - /usr/bin/time -v -o coverage-filter.txt lcov --ignore-errors inconsistent,inconsistent --remove coverage.info '/usr/*' '*/examples/*' --output-file coverage.info - /usr/bin/time -v -o coverage-list.txt lcov --list coverage.info + lcov --rc lcov_json_module=JSON::XS --ignore-errors inconsistent,inconsistent --gcov-tool gcov-16 --capture --directory . --output-file coverage.info + lcov --ignore-errors inconsistent,inconsistent --remove coverage.info '/usr/*' '*/examples/*' --output-file coverage.info + lcov --list coverage.info - name: Collect macOS browser crash diagnostics if: failure() && runner.os == 'macOS' timeout-minutes: 1 @@ -277,13 +301,9 @@ jobs: name: test-log-${{ runner.os }} path: | build/test-results-*.xml - build/ctest-graph.json - build/embedded-cache-probe.txt + build/fast-results.xml + build/unit-results-*.xml build/test/unit/consumer-build/.ninja_log - build/test-profile* - build/*-resources.json - build/coverage-*.txt - build/coverage-capture.log build/Testing/Temporary/LastTest*.log build/diagnostics/ if-no-files-found: ignore @@ -292,7 +312,8 @@ jobs: if: github.event_name != 'workflow_dispatch' || inputs.repeat_desktop_tests permissions: contents: read - timeout-minutes: 25 + # The explicit qualification includes a cold analysis build and desktop_passes complete graphs. + timeout-minutes: ${{ github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests && (inputs.desktop_passes > 3 && 300 || 90) || 25 }} strategy: fail-fast: false matrix: @@ -352,14 +373,205 @@ jobs: sudo apt-get install -y clang-23 lld-23 echo "CC=clang-23" >> "$GITHUB_ENV" echo "CXX=clang++-23" >> "$GITHUB_ENV" + - name: Report the selected compiler + shell: bash + run: | + if [ "$RUNNER_OS" = Windows ]; then cl 2>&1 || true; else "${CXX:-c++}" --version; fi # No compiler cache: a new user compiles everything. - name: Configure shell: bash - run: cmake -S . -B build -G "${{ matrix.generator }}" -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_EMBED_CEF=OFF -DWEBFRONT_ENABLE_TESTING=ON -DENABLE_CACHE=OFF -DCMAKE_CXX_SCAN_FOR_MODULES=OFF + run: cmake -S . -B build -G "${{ matrix.generator }}" -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_EMBED_CEF=OFF -DWEBFRONT_ENABLE_TESTING=ON -DENABLE_CACHE=OFF -DCMAKE_CXX_SCAN_FOR_MODULES=OFF -DWEBFRONT_TEST_UNITY_BATCH=0 -DWEBFRONT_MSVC_ANALYZE=ON -DWEBFRONT_TEST_REPRODUCIBILITY=ON - name: Portability tests shell: bash run: ctest --test-dir build -C Release -L portability --output-on-failure --no-tests=error + # GCC 13 on Linux aarch64 (#548): the default compiler of Ubuntu 24.04, JetPack 7.2 and Yocto Scarthgap, on the architecture of + # the Jetson boards. It builds the library, the examples and every test with the hosted ubuntu-24.04-arm image, then runs the fast + # tier. Warnings are not errors here: libstdc++ 13 reports false -Wnull-dereference positives (#526), so -Werror stays with the + # reference compiler (#525). A browser frontend needs a display and CEF has no aarch64 job yet, so both are off. + gcc13-arm64: + if: github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.base_ref == 'master') || (github.event_name == 'workflow_dispatch' && (inputs.repeat_desktop_tests || inputs.gcc13_arm64)) + runs-on: ubuntu-24.04-arm + timeout-minutes: 60 + env: + CC: gcc-13 + CXX: g++-13 + ASAN_OPTIONS: detect_leaks=1:abort_on_error=1 + UBSAN_OPTIONS: print_stacktrace=1:halt_on_error=1 + steps: + - uses: actions/checkout@v7 + - uses: ./.github/actions/remove-node + - uses: ./.github/actions/setup-cmake + with: + version: '4.4.4' + - uses: actions/cache@v4 + with: + path: .cache/CPM + key: cpm-extended-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('CMakeLists.txt', 'cmake/*.cmake') }} + restore-keys: cpm-extended-${{ runner.os }}-${{ runner.arch }}- + - name: Install GCC 13 + run: | + sudo apt-get update + sudo apt-get install -y g++-13 ninja-build + # An image change must not move the compiler silently: fail unless this really is GCC 13 on aarch64. + - name: Verify the compiler + run: | + g++-13 --version + test "$(uname -m)" = aarch64 + case "$(g++-13 -dumpfullversion)" in 13.*) ;; *) echo "::error::Expected GCC 13, got $(g++-13 -dumpfullversion)"; exit 1 ;; esac + - name: Configure + run: >- + cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release + -DWEBFRONT_EMBED_CEF=OFF -DWEBFRONT_EMBED_WEBKITGTK=OFF -DWEBFRONT_ENABLE_TESTING=ON + -DWARNINGS_AS_ERRORS=OFF -DENABLE_CACHE=OFF -DCMAKE_CXX_SCAN_FOR_MODULES=OFF + - name: Build + run: cmake --build build --parallel 4 + - name: Fast tests + run: ctest --test-dir build -L fast --output-on-failure --no-tests=error --parallel 4 + # Exercise coroutine lifetimes with the oldest supported compiler as well (#525). + - name: Configure GCC 13 ASan and UBSan + env: + WEBFRONT_TEST_TIMEOUT_FACTOR: '2' + run: >- + cmake -S . -B build-sanitizers -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo + -DWEBFRONT_EMBED_CEF=OFF -DWEBFRONT_EMBED_WEBKITGTK=OFF -DWEBFRONT_ENABLE_TESTING=ON + -DWEBFRONT_BUILD_EXAMPLES=OFF -DWARNINGS_AS_ERRORS=OFF -DENABLE_CACHE=OFF + -DCMAKE_CXX_SCAN_FOR_MODULES=OFF + -DWEBFRONT_ENABLE_SANITIZER_ADDRESS=ON -DWEBFRONT_ENABLE_SANITIZER_UNDEFINED_BEHAVIOR=ON + - name: Build GCC 13 sanitizer tests + run: cmake --build build-sanitizers --parallel 2 + - name: GCC 13 sanitizer fast tests + run: ctest --test-dir build-sanitizers -L fast --output-on-failure --no-tests=error --parallel 4 + - name: Retain GCC 13 test diagnostics + if: always() + uses: actions/upload-artifact@v4 + with: + name: test-log-gcc13-arm64 + path: | + build/Testing/Temporary/LastTest.log + build-sanitizers/Testing/Temporary/LastTest.log + if-no-files-found: ignore + + # CEF on Linux aarch64 (#524): the pinned CEF picks its linuxarm64 archive from the target, so the browser integration suite runs + # natively on the hosted arm runner with GCC 13 and Xvfb, once a week (on demand with cef_arm64), not on every pull request. + # A Jetson Orin Nano qualification passed the same cases as x86-64; this job guards against drift. + cef-arm64: + if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.cef_arm64) + timeout-minutes: 60 + runs-on: ubuntu-24.04-arm + env: + CC: gcc-13 + CXX: g++-13 + steps: + - uses: actions/checkout@v7 + - uses: actions/cache@v4 + with: + path: .cache/CPM + key: cpm-extended-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('CMakeLists.txt', 'cmake/*.cmake') }} + restore-keys: cpm-extended-${{ runner.os }}-${{ runner.arch }}- + - uses: actions/cache@v4 + with: + path: | + build-cef/bootstrap + build-cef/registry-archives + key: inputs-web-integration-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('cmake/WebFrontBootstrap.cmake', 'test/web/registry-packages.json') }} + - uses: ./.github/actions/remove-node + - uses: ./.github/actions/setup-cmake + with: + version: '4.4.4' + - name: Install GCC 13 and Xvfb + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends g++-13 ninja-build xvfb + - name: Verify the compiler + run: | + test "$(uname -m)" = aarch64 + case "$(g++-13 -dumpfullversion)" in 13.*) ;; *) echo "::error::Expected GCC 13, got $(g++-13 -dumpfullversion)"; exit 1 ;; esac + - name: Configure CEF integration build + run: >- + cmake -S . -B build-cef -G Ninja -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_EMBED_CEF=ON -DWEBFRONT_BUILD_EXAMPLES=OFF + -DWEBFRONT_ENABLE_TESTING=ON -DWARNINGS_AS_ERRORS=OFF -DENABLE_CACHE=OFF -DCMAKE_CXX_SCAN_FOR_MODULES=OFF + # The suite must not pass against an x86-64 archive by accident. + - name: Verify the CEF architecture + run: | + lib="$(find build-cef/_deps/cef_binaries-src -name libcef.so -print -quit)" + test -n "$lib" + file "$lib" | grep -q aarch64 || { echo "::error::CEF is not linuxarm64: $(file "$lib")"; exit 1; } + - name: Build browser test + run: cmake --build build-cef --target webtest developer_integration webfront-wf --parallel 4 + - name: Run Jasmine bridge test + run: >- + ctest --test-dir build-cef -L web-integration --output-on-failure --no-tests=error --parallel 2 + --output-junit "${{ github.workspace }}/build-cef/test-results.xml" + - name: Retain test timings and diagnostics + if: always() + uses: actions/upload-artifact@v4 + with: + name: test-log-cef-arm64 + path: | + build-cef/test-results.xml + build-cef/Testing/Temporary/LastTest.log + if-no-files-found: ignore + + # WebKitGTK 6.0 on Linux aarch64 (#524): the system WebKitGTK of Ubuntu 24.04 with GCC 13 and Xvfb, running the same + # web-integration suite as the CEF job through the WebKitGTK frontend. Weekly and on demand with webkitgtk_arm64, not on + # pull requests, like the CEF job; the sandbox opt-out is confined to this test step and its trusted fixtures. + webkitgtk-arm64: + if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.webkitgtk_arm64) + timeout-minutes: 60 + runs-on: ubuntu-24.04-arm + env: + CC: gcc-13 + CXX: g++-13 + steps: + - uses: actions/checkout@v7 + - uses: actions/cache@v4 + with: + path: .cache/CPM + key: cpm-extended-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('CMakeLists.txt', 'cmake/*.cmake') }} + restore-keys: cpm-extended-${{ runner.os }}-${{ runner.arch }}- + - uses: actions/cache@v4 + with: + path: | + build-webkitgtk/bootstrap + build-webkitgtk/registry-archives + key: inputs-webkitgtk-arm64-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('cmake/WebFrontBootstrap.cmake', 'test/web/registry-packages.json') }} + - uses: ./.github/actions/remove-node + - uses: ./.github/actions/setup-cmake + with: + version: '4.4.4' + - name: Install GCC 13, WebKitGTK and Xvfb + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends g++-13 ninja-build xvfb libwebkitgtk-6.0-dev + - name: Verify the compiler + run: | + test "$(uname -m)" = aarch64 + case "$(g++-13 -dumpfullversion)" in 13.*) ;; *) echo "::error::Expected GCC 13, got $(g++-13 -dumpfullversion)"; exit 1 ;; esac + pkg-config --modversion webkitgtk-6.0 + - name: Configure WebKitGTK integration build + run: >- + cmake -S . -B build-webkitgtk -G Ninja -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_EMBED_CEF=OFF -DWEBFRONT_EMBED_WEBKITGTK=ON + -DWEBFRONT_WEBTEST_FRONTEND=WebKitGTK -DWEBFRONT_BUILD_EXAMPLES=OFF -DWEBFRONT_ENABLE_TESTING=ON + -DWARNINGS_AS_ERRORS=OFF -DENABLE_CACHE=OFF -DCMAKE_CXX_SCAN_FOR_MODULES=OFF + - name: Build browser test + run: cmake --build build-webkitgtk --target webtest developer_integration webfront-wf --parallel 4 + - name: Run Jasmine bridge test + env: + WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS: '1' + run: >- + ctest --test-dir build-webkitgtk -L web-integration --output-on-failure --no-tests=error --parallel 2 + --output-junit "${{ github.workspace }}/build-webkitgtk/test-results.xml" + - name: Retain test timings and diagnostics + if: always() + uses: actions/upload-artifact@v4 + with: + name: test-log-webkitgtk-arm64 + path: | + build-webkitgtk/test-results.xml + build-webkitgtk/Testing/Temporary/LastTest.log + if-no-files-found: ignore + sanitizers: if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && github.base_ref == 'master') runs-on: ubuntu-24.04 @@ -409,6 +621,7 @@ jobs: cmake -S . -B build-sanitizers -DCMAKE_BUILD_TYPE=RelWithDebInfo -DWEBFRONT_EMBED_CEF=OFF -DWEBFRONT_BUILD_EXAMPLES=OFF -DWEBFRONT_ENABLE_TESTING=ON -DENABLE_CACHE=OFF -DCMAKE_CXX_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_SCAN_FOR_MODULES=OFF + -DWEBFRONT_TEST_UNITY_BATCH=0 -DWEBFRONT_TEST_REPRODUCIBILITY=ON ${{ matrix.sanitizer == 'thread' && '-DCMAKE_CXX_FLAGS=-stdlib=libc++ -DWEBFRONT_ENABLE_SANITIZER_THREAD=ON' || '-DWEBFRONT_ENABLE_SANITIZER_ADDRESS=ON -DWEBFRONT_ENABLE_SANITIZER_UNDEFINED_BEHAVIOR=ON -DWEBFRONT_ENABLE_FUZZING=ON -DWEBFRONT_GZIP_DIFFERENTIAL=ON' }} - name: Build run: cmake --build build-sanitizers --parallel 2 @@ -491,7 +704,7 @@ jobs: # The registry packages and the pinned bootstrap environment are downloaded and verified here; wf then builds the rest. - name: Configure CEF integration build - run: cmake . -B ${{github.workspace}}/build-cef -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_EMBED_CEF=ON -DWEBFRONT_BUILD_EXAMPLES=OFF -DWEBFRONT_ENABLE_TESTING=ON -DENABLE_CACHE=OFF -DCMAKE_CXX_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_SCAN_FOR_MODULES=OFF + run: cmake . -B ${{github.workspace}}/build-cef -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_EMBED_CEF=ON -DWEBFRONT_BUILD_EXAMPLES=OFF -DWEBFRONT_ENABLE_TESTING=ON -DWEBFRONT_TEST_REPRODUCIBILITY=ON -DENABLE_CACHE=OFF -DCMAKE_CXX_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_SCAN_FOR_MODULES=OFF - name: Build browser test run: cmake --build ${{github.workspace}}/build-cef --target webtest developer_integration webfront-wf --parallel 2 diff --git a/.github/workflows/DeveloperDistribution.yml b/.github/workflows/DeveloperDistribution.yml index 912011c5..e946e61a 100644 --- a/.github/workflows/DeveloperDistribution.yml +++ b/.github/workflows/DeveloperDistribution.yml @@ -68,7 +68,7 @@ jobs: run: | wf run build build-distribution wf run build build-distribution-repeat - for name in environment.tgz life-starter.tgz provision.json DeveloperReleaseData.hpp; do + for name in environment.tgz app-starter.tgz life-starter.tgz provision.json DeveloperReleaseData.hpp; do cmp "build-distribution/$name" "build-distribution-repeat/$name" done echo "environment.tgz sha512-$(openssl dgst -sha512 -binary build-distribution/environment.tgz | base64 -w0)" @@ -97,6 +97,7 @@ jobs: if-no-files-found: error path: | build-distribution/environment.tgz + build-distribution/app-starter.tgz build-distribution/life-starter.tgz build-distribution/provision.json build-distribution/DeveloperReleaseData.hpp diff --git a/.github/workflows/JetsonOrin.yml b/.github/workflows/JetsonOrin.yml new file mode 100644 index 00000000..2e25d617 --- /dev/null +++ b/.github/workflows/JetsonOrin.yml @@ -0,0 +1,43 @@ +name: Jetson Orin + +on: + schedule: + - cron: '17 1 * * 1' + push: + branches: [master] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: jetson-orin + cancel-in-progress: false + +jobs: + jetson-orin: + if: >- + github.repository == 'ambroise-leclerc/WebFront' && !cancelled() && + (github.event_name == 'schedule' || (github.event_name == 'push' && github.ref == 'refs/heads/master') || + (github.event_name == 'workflow_dispatch' && github.actor == 'ambroise-leclerc' && github.ref_type == 'branch')) + runs-on: [self-hosted, linux, arm64, jetson-orin] + timeout-minutes: 180 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - name: Build and test at low priority + run: nice -n 15 ionice -c 3 bash .github/scripts/jetson-orin.sh + - name: Retain diagnostics + if: always() + uses: actions/upload-artifact@v4 + with: + name: jetson-orin-${{ github.run_id }} + path: | + build-jetson-*/Testing/Temporary/LastTest.log + build-jetson-*/*results.xml + retention-days: 14 + if-no-files-found: ignore + - name: Remove job build directories + if: always() + run: rm -rf -- build-jetson-core build-jetson-webkitgtk diff --git a/.github/workflows/ReleaseDeveloper.yml b/.github/workflows/ReleaseDeveloper.yml index 18722906..2f8530f9 100644 --- a/.github/workflows/ReleaseDeveloper.yml +++ b/.github/workflows/ReleaseDeveloper.yml @@ -9,7 +9,7 @@ on: workflow_dispatch: inputs: version: - description: Version of the environment to release (MAJOR.MINOR.PATCH, greater than the one of distribution.json) + description: Version of the environment to release (MAJOR.MINOR.PATCH, greater than the published one and not lower than the one of distribution.json) type: string required: true publish: @@ -56,12 +56,10 @@ jobs: run: echo "commit=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" - name: Check the requested version run: | - [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "::error::Version must be MAJOR.MINOR.PATCH"; exit 1; } - current=$(jq -r .version js/developer/tools/distribution.json) - if [ "$(printf '%s\n%s\n' "$current" "$VERSION" | sort -V | tail -n 1)" != "$VERSION" ] || [ "$current" = "$VERSION" ]; then - echo "::error::Version $VERSION must be greater than the current $current" - exit 1 - fi + # The sources may already name the version under development; the published version is never released again. + sources=$(jq -r .version js/developer/tools/distribution.json) + pinned=$(sed -n 's/.*version{"\([^"]*\)"}.*/\1/p' include/webfront/system/DeveloperReleaseData.hpp) + bash js/developer/tools/check-release-version.sh "$VERSION" "$sources" "$pinned" - uses: ./.github/actions/remove-node - uses: ./.github/actions/wf-driver - name: Set the version and close a migration @@ -76,7 +74,7 @@ jobs: run: | wf run build build-distribution --refresh-bootstrap wf run build build-distribution-repeat - for name in environment.tgz life-starter.tgz provision.json DeveloperReleaseData.hpp; do + for name in environment.tgz app-starter.tgz life-starter.tgz provision.json DeveloperReleaseData.hpp; do cmp "build-distribution/$name" "build-distribution-repeat/$name" done cmp include/webfront/system/DeveloperReleaseData.hpp build-distribution/DeveloperReleaseData.hpp @@ -125,6 +123,7 @@ jobs: if-no-files-found: error path: | build-distribution/environment.tgz + build-distribution/app-starter.tgz build-distribution/life-starter.tgz build-distribution/provision.json build-distribution/DeveloperReleaseData.hpp diff --git a/AGENTS.md b/AGENTS.md index 749f14a8..a9c66cc5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,7 @@ WebFront is a C++23 header-only library for serving a browser UI from a C++ appl - C++ calls browser functions with `ui.jsFunction(name)(arguments...)`, which is fire-and-forget and ignores the result, or with `ui.jsFunction(name)(arguments...)`, which returns a `std::future`. Only the untyped C++ form is fire-and-forget. - `webFront.ready` resolves after the WebSocket handshake acknowledgement and rejects if the initial connection fails or closes. -WebFront also ships a standalone developer environment (`NativeApp::bootstrap("developer")`): a terminal whose `wf` commands (`init`, `create`, `install`, `restore`, `run`, `exec`, `check`, `test`, `build`, `dev`, `preview`, `embed`, `list`, `help`) manage a project manifest and lock, compile TS/TSX, type-check, run Jasmine specs and generate the application's embedded provider, with no JavaScript runtime or package manager on the developer's machine. It is not a sandbox. See `docs/DEVELOPER_ENVIRONMENT.md`. +WebFront also ships a standalone developer environment (`NativeApp::bootstrap("developer")`): a terminal whose `wf` commands (`init`, `create`, `install`, `restore`, `run`, `exec`, `check`, `test`, `build`, `dev`, `preview`, `embed`, `list`, `why`, `info`, `help`) manage a project manifest and lock, compile TS/TSX, type-check, run Jasmine specs and generate the application's embedded provider, with no JavaScript runtime or package manager on the developer's machine. It is not a sandbox. See `docs/DEVELOPER_ENVIRONMENT.md`. The README introduces WebFront through the Game of Life walkthrough, demonstrating the developer bootstrap, reactive TypeScript UI and embedded distribution. The minimal `HelloWorld` example remains available under `examples/hello-world/`. Native modules and the bridge are covered by the Jasmine browser integration test. The optional `ui.document()` API provides per-connection DOM islands, batched writes, events (callbacks or awaitable `node.next(name)`) and grouped sender reads; see `docs/DOM.md`. The optional React store and `Island` adapter, including its support policy and coordinated unmount contract, is described in `docs/REACT.md`; `examples/life/react/` demonstrates it. Application coroutines use `webfront::Task` and `app.spawn(task)`/`ui.spawn(task)`; retain a `TaskHandle` to request individual cancellation. WebFront owns and drains these tasks. Spawn is callable from any thread while the application lives; a call rejected during shutdown returns a stopped handle. Destructors wait for outstanding operations; explicit shutdown reports a stalled join. Typed C++ sender calls support local cancellation; futures and JavaScript Promises do not expose cancellation. @@ -21,16 +21,18 @@ The README introduces WebFront through the Game of Life walkthrough, demonstrati - `include/webfront/weblink/`: bridge message encoding and routing. - `include/webfront/system/`: layered virtual filesystems and the embedded web resources, a closed list guarded by the `MinimalCoreAssets` CTest case (normative list and 150 KiB decoded budget in ADR-016; changing it means amending the ADR and `test/cmake/CheckMinimalCoreAssets.cmake` together). - `include/webfront/frontend/`: system-browser, CEF, optional Windows WebView2 and macOS WKWebView frontend adapters. -- `examples/`: only Hello World (`hello-world/`) and Game of Life (`life/`, with console, developer and embedded stages, plus the `life/react/` variant with a C++ panel inside React). +- `examples/`: only Hello World (`hello-world/`), the host loop (`host-loop/`: an application that keeps its own loop, `app.start()` or a host thread beside a native window; it ray-traces a Boing Ball on the CPU or with an optional CUDA unit, see `docs/HOST_LOOP_EXAMPLE.md`) and Game of Life (`life/`, with console, developer and embedded stages, plus the `life/react/` variant with a C++ panel inside React). - `js/core/`: readable browser bridge, fallback and bootstrap loader compiled into `include/webfront/`, plus the embedding CMake modules; `js/developer/`: developer environment (its terminal and `wf`), the wf scripts that build it (`scripts/`), build and publication tools. The repository is itself a `wf` project (`js/developer/webfront.project.json` and its lock, selected with `--manifest-dir js/developer`): the environment builds itself, and its pure JavaScript specs (`test/developer/`) run with `wf test`. Production C++ remains header-only in `include/webfront/`. +- `js/developer/starters/`: the sources of the `app` starter and `agent-guide.md`, the `AGENTS.md` that `wf create` puts beside a starter and that `webfront_write_agent_guide()` (`cmake/WebFrontAgentGuide.cmake`) writes in a consuming project. - `js/services/`: optional `@webfront/services` package, the browser side of the system services (ADR-020; a skeleton so far), built like `@webfront/react` by `wf run services-package`; outside the core's embedded resource list. - `js/react/`: optional `@webfront/react` package (`createStore`, `useStore`, `Island`), declarations and package-local license. `wf run react-package` assembles it; tests verify the exact archive installed by the registry. It is outside the core's embedded resource list. - `test/fixtures/`, `test/web/fixtures/`: retained regression fixtures, not public example applications. -- `test/unit/`: Catch2 unit tests; `test/web/`: real-browser integration (`suite/` is the WebFront project of the Jasmine specs, run by `webtest` through `wf test`); `test/driver/`: `webfront-wf`, the non-interactive `wf` driver for tests; `test/fuzz/`, `test/fixtures/`; `test/cmake/`: CMake test scripts and sub-projects. The `RepositoryLayout` CTest case pins the tracked root. +- `test/unit/`: C++ unit tests, written with `test/unit/Bdd.hpp` (a single-header BDD framework); `test/web/`: real-browser integration (`suite/` is the WebFront project of the Jasmine specs, run by `webtest` through `wf test`); `test/driver/`: `webfront-wf`, the non-interactive `wf` driver for tests; `test/fuzz/`, `test/fixtures/`; `test/cmake/`: CMake test scripts and sub-projects. The `RepositoryLayout` CTest case pins the tracked root. - `cmake/`: build modules (frontends, CEF, CPM, compiler options); `.github/`: workflows, `.github/CONTRIBUTING.md`. - `docs/`: current reference guides, architecture decisions and `docs/CHANGELOG.md`. - `docs/PROJECT_STATUS.md`: current supported paths, validation scope and known limitations; completed work belongs in the changelog and Git history. - `docs/adr/README.md`: architecture decision index, Git history, tradeoffs and implementation rules; read the relevant ADRs before changing their contracts. +- `docs/DEVELOPING_WITH_AGENTS.md`: what an agent developing a consuming application reads first (the model, the loop, each `wf` command in JSON and MCP); the README section, `wf help agents`, the starters' `AGENTS.md` and the `AgentGuidance` CTest case keep to it. - `docs/DEVELOPER_ENVIRONMENT.md`: the reference of the developer environment (`wf` commands, manifest and lock, TypeScript and `wf check`, tests, limits, distribution); `docs/EMBEDDED_ASSETS.md`: the core's embedded resources and their regeneration. The historical `webfront/` prototype and the former top-level `webtest/` are gone: use `test/unit/` for current C++ tests and `test/web/` for browser tests. Do not revive legacy code without a specific issue and regression coverage. @@ -53,7 +55,7 @@ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release \ cmake --build build --parallel ctest --test-dir build --output-on-failure --parallel 4 -# Run one Catch2 scenario directly +# Run one unit-test scenario directly (`tests --help` lists the filters) ./build/test/unit/tests "Scenario: JsFunction" # Linux real-browser integration test: configure downloads and verifies the pinned bootstrap environment and the packages @@ -80,18 +82,20 @@ Important CMake options: The headers of the embedded assets are generated, and checked by CTest, in pure CMake (`js/core/EmbedAsset.cmake`; the `webfront-embedded-assets` target regenerates them). Normal C++ builds consume the versioned headers. Configuring with `WEBFRONT_ENABLE_TESTING=ON` downloads the pinned bootstrap environment and the packages of the test registry, each verified -against its SHA-512; `-DWEBFRONT_BOOTSTRAP_DIR` and `-DWEBFRONT_REGISTRY_DIR` replace those downloads on a machine -without network access. +against its SHA-512, tried three times and kept once per machine (`WEBFRONT_DOWNLOAD_CACHE`, by default in CPM's cache or +the user's cache directory), so a new build tree links them instead of downloading them again; `-DWEBFRONT_BOOTSTRAP_DIR` +and `-DWEBFRONT_REGISTRY_DIR` replace those downloads on a machine without network access. - `WEBFRONT_EMBED_CEF=OFF` (default): CEF is unavailable; this is the normal unit-test build. `ON` downloads/links CEF and enables the automated browser test; it makes `CEFFrontend` available but does not select it: `webfront::WebFront` always uses the system browser. - `WEBFRONT_EMBED_WEBVIEW2=OFF` (default): Windows-only opt-in SDK and static loader for `WebView2Frontend`; requires the separately installed Evergreen runtime. Select it explicitly with `WebFrontWithFrontend`. With tests enabled, `WEBFRONT_WEBTEST_FRONTEND=WebView2` runs the shared Jasmine suite and lifecycle cases. - `WEBFRONT_EMBED_WKWEBVIEW=OFF` (default): macOS 13.3+ opt-in Cocoa/WebKit frontend, with no engine download. Select `WebFrontWithFrontend` on the main thread; `WEBFRONT_WEBTEST_FRONTEND=WKWebView` runs Jasmine and lifecycle coverage. -- `WEBFRONT_ENABLE_TESTING=ON` (default `OFF`): build Catch2 and Jasmine test targets. CI and contributor commands must pass it explicitly. The test, fuzzing, coverage and sanitizer options (`WEBFRONT_ENABLE_SANITIZER_*`) carry the `WEBFRONT_` prefix so that a parent's own `ENABLE_TESTING` or `ENABLE_SANITIZER_ADDRESS` never builds or instruments WebFront's tests; the former unprefixed names no longer configure WebFront (`cmake/WebFrontTestOptions.cmake` documents the options). +- `WEBFRONT_ENABLE_TESTING=ON` (default `OFF`): build the C++ unit-test and Jasmine test targets. CI and contributor commands must pass it explicitly. The test, fuzzing, coverage and sanitizer options (`WEBFRONT_ENABLE_SANITIZER_*`) carry the `WEBFRONT_` prefix so that a parent's own `ENABLE_TESTING` or `ENABLE_SANITIZER_ADDRESS` never builds or instruments WebFront's tests; the former unprefixed names no longer configure WebFront (`cmake/WebFrontTestOptions.cmake` documents the options). - `WEBFRONT_BUILD_EXAMPLES` (default `ON` only for the top-level project): build the examples. As a subproject (`add_subdirectory`), link `WebFront::WebFront`; no examples, tests or global compiler settings are added. - `WEBFRONT_ENABLE_COVERAGE=ON`: add GCC/Clang coverage instrumentation to the C++ tests. +- The project has no CMake presets: the defaults are the quick local build (`WEBFRONT_TEST_UNITY_BATCH=4`, `WEBFRONT_MSVC_ANALYZE=OFF`, `WEBFRONT_TEST_REPRODUCIBILITY=OFF`) and every CI job passes these options explicitly (`docs/TEST_TIERS.md`). -If the environment provides a read-only default ccache directory, set `CCACHE_DIR` to a writable temporary directory for local builds. Do not encode machine-specific cache paths in project files. In CI, `ENABLE_CACHE=OFF` disables automatic cache discovery while `CMAKE_CXX_COMPILER_LAUNCHER=sccache` explicitly enables sccache; a PATH/version probe runs on all three platforms. The combined Linux job uses Debug with GCC coverage on every PR; Windows and macOS use Release. The WebKitGTK sandbox opt-out is confined to the Linux test step and trusted fixtures. +If the environment provides a read-only default ccache directory, set `CCACHE_DIR` to a writable temporary directory for local builds. Do not encode machine-specific cache paths in project files. In CI, `ENABLE_CACHE=OFF` disables automatic cache discovery while `CMAKE_CXX_COMPILER_LAUNCHER=sccache` explicitly enables sccache; a PATH/version probe runs on all three platforms. The combined Linux job uses Debug with GCC coverage on every PR; Windows and macOS use Release. WebKitGTK defaults to development mode, with its sandbox disabled only while constructing the native view context; the environment is restored afterward. Distribution builds require the sandbox (`WEBFRONT_DISTRIBUTION=ON` or explicitly selected native UI targets). See `docs/WEBKITGTK.md`. ## Architecture and invariants @@ -99,7 +103,7 @@ If the environment provides a read-only default ccache directory, set `CCACHE_DI The HTTP server connections and the WebSocket read/write loops are coroutines (`networking::Task`) awaiting the senders a network provider returns (`Receive`, `Send`, `Accept`; `networking::TCPStdnet` forwards them to stdnet). A stop request cancels them from any thread and they unwind on the io_context thread, so I/O objects are never closed from another thread. The server owns a `counting_scope` for HTTP, WebSocket and application tasks. `shutdown()` stops and joins owned work; call it outside server callbacks, after external run callers have returned. Whoever owns the objects the tasks use must run `Server::drain()` before destroying them (`~BasicWF` does): it closes, stops and joins the scope while pumping the context. Low-level WebSocket/WebLink users pass an external `TaskScope&` and drain it before releasing dependencies. -`webfront::WebFront` is default-constructible (`WebFrontConfig`: loopback address, port `9002`, no document root) and `show(page = "index.html")` opens a page. Without a document root no local file access happens; `WebFrontConfig::documentRoot` serves local files for development only, after the embedded `WebFront.js` (which a root can never override) and before the embedded fallback page. +`webfront::WebFront` is default-constructible (`WebFrontConfig`: loopback address, port `9002`, no document root) and `show(page = "index.html")` opens a page. `show()` keeps its calling thread; an application with its own loop uses `start()` (system browser, returns at once), `requestClose()` (ends `show()` from any thread) or `webfront::UIThread` (secondary thread, refused at compile time for main-thread frontends), as `docs/HOST_INTEGRATION.md` describes. Without a document root no local file access happens; `WebFrontConfig::documentRoot` serves local files for development only, after the embedded `WebFront.js` (which a root can never override) and before the embedded fallback page. Filesystems implement `open(std::filesystem::path) -> std::optional` and are composed with `fs::Multi<>`; the first provider returning a file wins. `NativeDebugFS` is development-only and must not be presented as a production sandbox. @@ -112,9 +116,9 @@ Exception: a purely C++ change that reuses an existing encoding, introduces no n ## Coding and testing conventions - Use C++23, four-space indentation, the `.clang-format` of the directory (`include/webfront/`, `test/`, `examples/`), and the naming rules in `.github/CONTRIBUTING.md`. -- Keep production implementation header-only under `include/`; `examples/` contains the two public examples; browser resources live in `js/`. +- Keep production implementation header-only under `include/`; `examples/` contains the three public examples; browser resources live in `js/`. - Prefer standard-library facilities and explicit ownership. Keep public headers ODR-safe (`inline`/templates as appropriate). -- Catch2 tests use `SCENARIO`/`GIVEN`/`WHEN`/`THEN` and deterministic mocks. +- Unit tests are named `const Scenario` objects whose `given`/`when`/`then` sections are lambdas, checked with `require`/`check` (`test/unit/Bdd.hpp`), and use deterministic mocks. - Jasmine specs are the project `test/web/suite/`, built by esbuild-wasm and run by `wf test` under the locked `jasmine-core` (installed from the local registry by `WebSuiteInstall`); `webtest` is the `webfront-wf` driver plus the C++ callbacks of the specs. The specs tell C++ they are done (`specsFinished`), the process status is that of `wf test` (or 1 when C++ did not observe every call), and the CTest case has a timeout. The registry the suite installs from is built by `wf run test-registry` (the `TestRegistry` case), from the packages that configure downloaded. - Every bug fix needs a failing regression test at the lowest useful level. Bridge changes also need the browser integration test. - Tests must not require user input, a fixed pre-existing browser session, or public network access after dependencies are configured. diff --git a/CMakeLists.txt b/CMakeLists.txt index c887ce97..7bb06543 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,10 @@ # The embedding project's CMP0155 setting (module scanning by default), read before this file's own # cmake_minimum_required resets the policies; empty when unknown or set. +if(CMAKE_VERSION VERSION_LESS "3.31") + message(FATAL_ERROR + "WebFront requires CMake 3.31 or newer (found ${CMAKE_VERSION}). " + "See README.md#build-tools-on-lts-distributions for installation instructions.") +endif() cmake_policy(GET CMP0155 WEBFRONT_PARENT_CMP0155) cmake_minimum_required (VERSION 3.31) @@ -13,6 +18,7 @@ endif() option(BUILD_SHARED_LIBS "Enable compilation of shared libraries" OFF) option(WEBFRONT_BUILD_AUTOMATION "Build the optional local developer CLI/MCP launcher" OFF) option(WEBFRONT_BUILD_EXAMPLES "Build the example applications" ${WEBFRONT_IS_TOP_LEVEL}) +option(WEBFRONT_DISTRIBUTION "Require WebKitGTK sandboxing for distribution (development disables it by default)" OFF) option(WEBFRONT_GZIP_DIFFERENTIAL "Build test-only gzip/zlib differential checks" OFF) option(WEBFRONT_USE_MDDLOG "Use the compiled mddlog diagnostic adapter" OFF) # The experimental gate must be selected before project() probes the compiler. @@ -49,6 +55,17 @@ find_package(Threads REQUIRED) add_library(WebFront INTERFACE) add_library(WebFront::WebFront ALIAS WebFront) +if(WEBFRONT_DISTRIBUTION) + target_compile_definitions(WebFront INTERFACE WEBFRONT_DISTRIBUTION=1) +endif() +include(cmake/WebFrontDistribution.cmake) +if(WEBFRONT_EMBED_WEBKITGTK AND WEBFRONT_IS_TOP_LEVEL) + if(WEBFRONT_DISTRIBUTION) + message(NOTICE "WebFront WebKitGTK: DISTRIBUTION mode, sandbox required. Package the application profile; see docs/WEBKITGTK.md.") + else() + message(NOTICE "WebFront WebKitGTK default: DEVELOPMENT (per-target distribution may override), sandbox disabled for native views. Select -DWEBFRONT_DISTRIBUTION=ON for distribution; see docs/WEBKITGTK.md.") + endif() +endif() target_link_libraries(WebFront INTERFACE Threads::Threads) # dlopen/dlsym: the frontends' run-time loaded toolkits and the system browser's UI loop (needs -ldl before glibc 2.34) target_link_libraries(WebFront INTERFACE ${CMAKE_DL_LIBS}) @@ -149,6 +166,9 @@ if(WEBFRONT_BUILD_AUTOMATION OR (WEBFRONT_ENABLE_TESTING AND endif() # Public helper for a parent project: checks the launcher target and optionally installs it. include(WebFrontAgent) +# What an agent configuring a project must learn at once: the development model, and how it runs wf itself. +include(WebFrontAgentGuide) +webfront_announce_agent_support() if(WEBFRONT_ENABLE_TESTING OR WEBFRONT_ENABLE_FUZZING) include(TestHardening) @@ -158,6 +178,12 @@ if(WEBFRONT_ENABLE_FUZZING) add_subdirectory(test/fuzz) endif() +# The host-loop example and its tests share one optional CUDA unit; the language is enabled here, above both. +if(WEBFRONT_ENABLE_TESTING OR WEBFRONT_BUILD_EXAMPLES) + include(BoingCuda) + webfront_enable_host_loop_cuda() +endif() + if(WEBFRONT_ENABLE_TESTING) enable_testing() add_subdirectory(test/unit) diff --git a/README.fr.md b/README.fr.md new file mode 100644 index 00000000..a79202f7 --- /dev/null +++ b/README.fr.md @@ -0,0 +1,469 @@ +# WebFront + + +[![CI](https://github.com/ambroise-leclerc/WebFront/actions/workflows/BuildAndTest.yml/badge.svg?branch=develop)](https://github.com/ambroise-leclerc/WebFront/actions/workflows/BuildAndTest.yml) +[![Windows · MSVC](https://img.shields.io/badge/CI-Windows%20%C2%B7%20MSVC-0078D4)](https://github.com/ambroise-leclerc/WebFront/actions/workflows/BuildAndTest.yml) +[![macOS · Apple Clang](https://img.shields.io/badge/CI-macOS%20%C2%B7%20Apple%20Clang-555555)](https://github.com/ambroise-leclerc/WebFront/actions/workflows/BuildAndTest.yml) +[![Linux · GCC](https://img.shields.io/badge/CI-Linux%20%C2%B7%20GCC-E95420)](https://github.com/ambroise-leclerc/WebFront/actions/workflows/BuildAndTest.yml) +[![Linux · aarch64](https://img.shields.io/badge/CI-Linux%20%C2%B7%20aarch64%20%C2%B7%20GCC%2013-E95420)](https://github.com/ambroise-leclerc/WebFront/actions/workflows/BuildAndTest.yml) +[![Jetson Orin](https://img.shields.io/badge/CI-Jetson%20Orin-76B900)](docs/JETSON.md) +[![C++23](https://img.shields.io/badge/C%2B%2B-23-00599C)](CMakeLists.txt) +[![Header-only](https://img.shields.io/badge/library-header--only-2EA043)](include/) + +[English](README.md) · [Français](README.fr.md) + +WebFront est une **bibliothèque C++23 header-only pour créer des interfaces utilisateur riches et modernes.** Conservez la logique applicative en C++ et créez des interfaces réactives avec TypeScript, React et les paquets de l’écosystème JavaScript. WebFront intègre les outils de développement d’interfaces à votre application : aucun environnement de développement TypeScript séparé n’est à installer. + +WebFront n’a aucune dépendance et peut être déployé sur tout appareil disposant d’une bibliothèque standard C++ récente. + +Parcours du jeu de la vie : application C++, terminal wf, installation des dépendances et aperçu React + +L'animation présente le programme C++ et l'interface ; les temps d'attente sont condensés et l'aperçu agrandi pour la lisibilité. Le [parcours ci-dessous](#jeu-de-la-vie--du-calcul-c-à-lapplication-native) utilise les sources compilées du dépôt. + +- **Intégrez WebFront à une application existante.** Conservez votre simulation, le contrôle de vos appareils, vos calculs SIMD, vos noyaux CUDA… et vos threads de travail en C++. Utilisez une fenêtre native ou même un navigateur web tout en gardant la maîtrise de votre boucle d’événements. [Intégration à l’application hôte →](docs/HOST_INTEGRATION.md) +- **Équipez les développeurs et les agents de programmation.** Les outils `wf` intégrés compilent l’interface, vérifient les types, exécutent les tests et embarquent ses ressources. Un serveur MCP activable à la demande et une interface en ligne de commande JSON permettent aux agents de piloter la fenêtre de votre application et d’exécuter les vérifications et les fonctions de rappel autorisées. [Développer avec un agent →](#développer-avec-un-agent) +- **Transférez directement les données numériques.** Les tableaux typés et les ensembles de bits compactés transitent par une passerelle WebSocket binaire, sans conversion en JSON ou en base64. Coroutines, futures et senders relient les appels asynchrones de l’interface aux traitements natifs. [Modèle d’exécution →](docs/ASYNC_EXECUTION.md) +- **Préparez votre application pour la distribution.** Embarquez les ressources, verrouillez les versions des paquets et vérifiez les téléchargements ; l’application obtenue fonctionne hors ligne. Les cibles CMake destinées aux projets utilisateurs et les tests dans le navigateur facilitent les compilations reproductibles et l’intégration continue. [Intégration →](#intégrer-webfront-dans-votre-projet) · [Tests →](#tester-votre-application) +- **Choisissez vos technologies d’interface.** Utilisez TypeScript, React et des paquets compatibles avec les navigateurs, ou créez des îlots DOM directement en C++. Des composants optionnels permettent de générer des formulaires et des inspecteurs à partir de descripteurs de types C++. [DOM →](docs/DOM.md) · [React →](docs/REACT.md) · [Formulaires →](docs/FORMS.md) + + + +**Site et livre : [webfront.fr](https://webfront.fr/fr/)** · [Le livre WebFront](https://webfront.fr/fr/book/) · [Documentation](docs/) · [Historique des versions](docs/CHANGELOG.md) + +## Plateformes et déploiement + +| Cible | Interfaces possibles | Périmètre de validation | +| --- | --- | --- | +| Windows | Navigateur système, WebView2 natif, CEF optionnel | CI desktop avec MSVC ; WebView2 nécessite le runtime Evergreen | +| macOS 13.3+ pour la fenêtre native | Navigateur système, WKWebView système, CEF optionnel | CI desktop avec AppleClang | +| Linux | Navigateur système, WebKitGTK 6.0 natif, CEF optionnel | CI desktop avec GCC ; couverture Clang étendue | +| Linux ARM64 / NVIDIA Jetson | Navigateur système, WebKitGTK ou CEF selon disponibilité | CI ARM64 avec GCC 13 et validation sur **Orin Nano Super 8 Go** ; voir le [guide Jetson](docs/JETSON.md) | + +Conçu pour suivre le C++ standard sur les différentes plateformes, le cœur utilise ses mécanismes et un fournisseur réseau remplaçable. Le chemin navigateur système évite de lier un toolkit graphique ou un moteur de fenêtre web natif. La cible doit fournir un **compilateur et une bibliothèque standard C++23 adaptés, le réseau et les threads du système, ainsi qu'un navigateur**. GCC 13 est le minimum avec support au mieux ; la [politique de support](docs/adr/ADR-022-profils-et-niveaux-de-support.md) précise les chaînes testées et leurs engagements. + +**Sans dépendance. Aucun runtime WebFront séparé.** Le cœur suit le modèle du réseau et de l'exécution du C++ standard. En attendant la standardisation et la disponibilité de ces mécanismes dans les bibliothèques standard, CMake fournit des implémentations externes épinglées : la couche réseau `stdnet` maintenue pour cette transition et, si nécessaire, `stdexec` pour les senders. Elles assurent l'intérim à la compilation ; aucun binaire de bibliothèque WebFront n'est à installer. Les fenêtres natives conservent les prérequis de leur plateforme ; CEF est optionnel. L'environnement de développement met ses outils et paquets vérifiés en cache au premier usage ; la version de production embarquée n'a besoin ni de ce cache ni des sources de l'interface. + +### CUDA et applications embarquées + +**Gardez CUDA dans votre application C++, y compris sur NVIDIA Jetson Orin Nano.** WebFront n'impose pas le moteur de calcul : votre boucle hôte ou vos workers exécutent le code CPU ou CUDA, tandis que l'interface modifie les paramètres et affiche les résultats par tableaux typés. Isolez les unités `.cu` des en-têtes C++23 de WebFront lorsque le compilateur CUDA l'exige. Aucun toolkit CUDA n'est nécessaire aux applications qui ne l'utilisent pas. + +**L'[exemple Boing Ball fourni](docs/HOST_LOOP_EXAMPLE.md) fonctionne sur CPU ou CUDA.** Une balle à damier rebondit au-dessus d'un sol réfléchissant ; passez au verre teinté pour découvrir réflexion, réfraction et faisceaux de lumière colorée. Chaque pixel est calculé par l'hôte C++, tandis que la page affiche le tableau typé sur un canvas. La même boucle hôte fonctionne avec une fenêtre native ou le navigateur système. + +![Animation CUDA de la Boing Ball dans une fenêtre native sur Jetson Orin Nano : balle à damier, puis verre illuminé](docs/images/host-loop-boing.gif) + +```bash +cmake --build build --target WebFrontHostLoop --parallel 2 +build/examples/WebFrontHostLoop --quality 0 +# Avec un moteur CUDA compilé et un GPU disponible : +build/examples/WebFrontHostLoop --engine cuda --glass --stats +``` + +Avec un générateur multi-configuration comme Visual Studio, remplacez `build/examples/` dans les commandes ci-dessus par `build/examples/Debug/`, ou `build/examples/Release/` après une construction avec `--config Release`. L’exécutable se nomme `WebFrontHostLoop.exe`. + +Ces commandes partent de la racine du dépôt, après configuration. CUDA est détecté automatiquement ; `-DWEBFRONT_HOST_LOOP_CUDA=OFF` construit l'exemple CPU complet sans toolkit. Ajoutez `--browser` pour choisir le navigateur système. Le [guide de l'exemple](docs/HOST_LOOP_EXAMPLE.md) décrit qualité, benchmark et configuration du compilateur CUDA séparé. + +**Qualifié sur Jetson Orin Nano Super 8 Go :** constructions sur carte réelle, rendu CPU/CUDA, tests de fenêtre native et du pont, vérifications d'une distribution avec sandbox. Un [workflow de validation matérielle](docs/JETSON_RUNNER.md) de confiance complète la CI ARM64 hébergée. La [qualification de la carte](docs/JETSON.md) et les [mesures de rendu](docs/HOST_LOOP_EXAMPLE.md) précisent la pile testée et le périmètre. NX/AGX et les autres versions JetPack demandent leur propre qualification ; ces résultats n'établissent pas l'accélération du rendu à l'intérieur du sandbox WebKit. + +Sous Linux, WebKitGTK utilise par défaut le mode développement, avec son sandbox désactivé. Pour distribuer, sélectionnez `-DWEBFRONT_DISTRIBUTION=ON` et incluez le profil de sandbox de l'application lorsque nécessaire. [Développement et distribution →](docs/WEBKITGTK.md#development-and-distribution) + +## Des mécanismes conçus pour les performances + +Conservez les calculs lourds dans le code natif et transmettez les données utiles à l'interface : les buffers numériques restent typés, les bitsets empaquetés et les appels asynchrones. Le serveur possède son thread ; votre boucle de calcul et vos workers restent indépendants. L'adaptateur React optionnel regroupe les mises à jour des instantanés C++ par navigateur, et l'API DOM regroupe les écritures. + +Ces mécanismes permettent de maîtriser sérialisation, fréquence des mises à jour et coût de l'interface. Les performances complètes dépendent aussi de la taille des messages, du rendu et du matériel. Mesurez séparément calcul, transport et affichage ; le [guide d'exécution](docs/ASYNC_EXECUTION.md) précise où tourne le travail et comment garder les callbacks réactifs. + +Exemple mesuré sur **Orin Nano Super 8 Go à 25 W**, dans une fenêtre WebKitGTK 2.52.6 avec sandbox : + +| Scène | CPU (6 threads) | CUDA | +| --- | ---: | ---: | +| Balle opaque | 12 images/s | 21 images/s | +| Verre et faisceaux lumineux | Environ 0,6 image/s | 12 images/s | + +Scène de 960 × 720, quatre rayons par pixel ; fenêtre de 800 × 600 pixels CSS. Construction Release, GCC 13.3, CUDA 13.2.86, L4T R39.2.1. Ces observations sont propres à cette carte, sans garantie universelle de débit. Le [rapport de mesure](docs/HOST_LOOP_EXAMPLE.md#system-browser-and-distribution-follow-up) distingue calcul, copie, transport et affichage, et compare navigateur système et fenêtre native. + +## Par où commencer ? + +- **Évaluer la bibliothèque :** [Hello World](#hello-world), puis le [parcours du jeu de la vie](#jeu-de-la-vie--du-calcul-c-à-lapplication-native). +- **Ajouter une interface à un logiciel existant :** [intégration CMake](#intégrer-webfront-dans-votre-projet) et [exemple de boucle hôte](examples/host-loop/HostLoop.cpp). +- **Travailler avec un agent :** [parcours de développement](#développer-avec-un-agent) et [automation de l'application](#laisser-un-agent-piloter-votre-application). +- **Préparer la production :** [tests](#tester-votre-application), [contrats et limites](#contrats-et-limites) et [état du support](docs/PROJECT_STATUS.md). + +## Développer avec un agent + +Une application WebFront est un programme C++ dont l'interface TypeScript/TSX se trouve dans **`ui/`** (`ui/main.ts` ou `ui/main.tsx`). Elle se développe avec **`wf dev`**, dans le terminal ouvert par `app.bootstrap("developer")`. Des pages HTML et JavaScript servies par `documentRoot` restent possibles, mais ne constituent pas ce parcours outillé. + +Avec l'environnement épinglé, l'ordre est : `wf create app` (nom du starter, pas du projet), `wf init`, `wf install ` pour les dépendances navigateur, puis `wf dev ui/main.ts`. Terminez par `wf check`, `wf test` et `wf embed` selon la configuration du projet. `wf create life` fournit le starter React du parcours ci-dessous ; `wf help agents` décrit la marche à suivre. + +**L'agent exécute les commandes lui-même**, sans demander à l'utilisateur de les saisir. Configurez avec `-DWEBFRONT_BUILD_AUTOMATION=ON` pour construire `webfront-agent`. L'application partage sa session explicitement avec `webfront::automation::enableAutomation(app, {.grants = {...}, .listen = directory})` ; les autorisations restent choisies par son propriétaire. + +```sh +webfront-agent --list +webfront-agent --attach DIRECTORY --operation create --starter app +webfront-agent --attach DIRECTORY --operation preview --entry ui/main.ts +webfront-agent --print-mcp-config --attach DIRECTORY > .mcp.json +``` + +Après chaque modification, l'agent utilise `preview` à la place de la session interactive `wf dev`. La même interface est disponible en MCP : + +```json +{"mcpServers": {"webfront": {"command": "/path/to/webfront-agent", "args": ["--attach", "/path/to/directory", "--mcp"]}}} +``` + +Dans un projet consommateur, `webfront_write_agent_guide()` écrit un `AGENTS.md` à la racine ; `wf create` le place à côté des sources du starter. Le [guide des agents](docs/DEVELOPING_WITH_AGENTS.md) détaille ce contrat. + +## Du C++ à une interface réactive + +Enregistrez votre calcul, ouvrez les outils, puis construisez l'interface dans le terminal de l'application. `life-project` désigne le répertoire de travail de l'interface. + +## Hello World + +Le programme minimal [HelloWorld.cpp](examples/hello-world/HelloWorld.cpp) sert la page embarquée et l'ouvre dans le navigateur système. `webfront::WebFront` sélectionne toujours ce navigateur. + +```cpp +#include + +int main() { + webfront::WebFront app; + app.show(); +} +``` + +```bash +mkdir build +cd build +cmake .. +cmake --build . +examples/HelloWorld +``` + +Avec Visual Studio, lancez `examples\Debug\HelloWorld.exe` ; `--config Release` sélectionne `examples\Release\`. Appuyez sur Entrée dans le terminal pour arrêter le serveur. + +L'[API DOM](docs/DOM.md) permet aussi de construire la page en C++, sans fichiers d'interface : + +```cpp +#include + +int main() { + webfront::WebFront app; + app.onUIStarted([](auto ui) { + auto doc = ui.document(); + auto root = doc.island(); + auto button = doc.element("button"); + auto label = doc.text("Cliquez ici"); + button.append(label); + button.listen("click", [label](std::string) { label.setText("Cliqué"); }); + root.append(button); + }); + app.show(); +} +``` + +## Jeu de la vie : du calcul C++ à l'application native + +L'exemple part d'une simulation C++, ajoute une interface React puis l'embarque dans l'exécutable. Prérequis : Git, CMake **3.31+** et un compilateur C++23 (GCC **13+**, avec support S2 au mieux pour GCC 13). Voir les [outils des distributions LTS](#outils-de-construction-sur-les-distributions-lts) et la [politique compilateur](docs/adr/ADR-022-profils-et-niveaux-de-support.md). + +La première configuration CMake, le premier bootstrap et les premières installations de paquets nécessitent Internet. Les ressources téléchargées sont ensuite mises en cache et vérifiables hors ligne. + +```bash +git clone https://github.com/ambroise-leclerc/WebFront.git +cd WebFront +mkdir build +cd build +cmake .. +cmake --build . +``` + +Aucune option n'est nécessaire. Les commandes suivantes partent de ce répertoire `build`. Avec Visual Studio, les exécutables sont dans `examples\Debug\`, ou `examples\Release\` avec `--config Release`. + +### 1. Partir du calcul C++ + +[Life.hpp](examples/life/Life.hpp) applique les règles B3/S23 de Conway sur une grille torique de 32 × 32 cellules. Chaque génération produit un `std::bitset<1024>`. [LifeConsole.cpp](examples/life/LifeConsole.cpp) l'exécute sans interface : + +```bash +examples/WebFrontLifeConsole +``` + +Avec Visual Studio, lancez `examples\Debug\WebFrontLifeConsole.exe`, ou `examples\Release\WebFrontLifeConsole.exe` après une construction avec `--config Release`. + +### 2. Ajouter la fenêtre et les outils + +L'ajout essentiel de [LifeDeveloper.cpp](examples/life/LifeDeveloper.cpp) est : + +```cpp +#include "LifeFrontend.hpp" + +webfront::demo::LifeApp app{"life-project"}; +app.cppFunction("life.step", &webfront::demo::nextLife); +app.bootstrap("developer"); +app.show(); +``` + +Lancez l'application : + +```bash +examples/WebFrontLifeDeveloper +``` + +Avec Visual Studio, lancez `examples\Debug\WebFrontLifeDeveloper.exe`, ou `examples\Release\WebFrontLifeDeveloper.exe` après une construction avec `--config Release`. + +L'exemple crée `life-project` dans le répertoire courant s'il manque et réutilise un projet existant sans écraser ses fichiers. `bootstrap("developer")` charge la version épinglée de l'environnement, vérifie son SHA-512 et la met en cache. Le terminal fournit les commandes `wf`, ainsi que `ls`, `cat`, `tree` et `mounts`, sans exposer de shell système. + +**Fenêtre native détectée automatiquement :** + +| Plateforme | Moteur | Condition | +| --- | --- | --- | +| Windows | WebView2 Evergreen | Compilateur compatible MSVC ; SDK téléchargé et runtime Evergreen vérifié au démarrage | +| macOS 13.3+ | Cocoa / WebKit système | Clang et cible de déploiement d'au moins 13.3 | +| Linux | WebKitGTK 6.0 | Détection par `pkg-config webkitgtk-6.0` ; [installation](docs/WEBKITGTK.md) | + +Si le moteur manque, CMake indique quoi installer et l'exemple ouvre le navigateur système. Installez le prérequis et relancez `cmake ..` pour obtenir la fenêtre native. CEF (`-DWEBFRONT_EMBED_CEF=ON`) rend son frontend disponible, mais les exemples ne le sélectionnent pas. + +La fenêtre native est construite et affichée sur le thread principal ; le serveur possède son thread. Fermer la fenêtre arrête le serveur. Un échec au démarrage renvoie un statut non nul. + +**Options avancées :** `-DWEBFRONT_EMBED_WEBVIEW2=ON|OFF`, `-DWEBFRONT_EMBED_WKWEBVIEW=ON|OFF` et `-DWEBFRONT_EMBED_WEBKITGTK=ON|OFF` imposent le choix ; `-DWEBFRONT_AUTODETECT_NATIVE=OFF` désactive la détection. Une valeur explicite est conservée. `cmake .. -UWEBFRONT_EMBED_WKWEBVIEW` rétablit la détection macOS ; adaptez le nom pour les autres moteurs. Les constructions de tests conservent une sélection explicite. + +Un autre projet et une autre archive vérifiée peuvent être fournis : `examples/WebFrontLifeDeveloper [ ]`. Voir la [référence de l'environnement](docs/DEVELOPER_ENVIRONMENT.md). + +### 3. Créer l'interface React + +Dans le terminal de l'application : + +```text +wf create life +wf init +wf install react@19.3.1 react-dom@19.3.1 +wf dev ui/main.tsx +``` + +`wf create life` écrit le [starter TSX et CSS](examples/life/ui) dans `ui/` sans écraser un répertoire existant. `wf init` crée le manifeste `webfront.project.json`. `wf install` résout et vérifie les paquets, puis verrouille leurs versions dans `webfront-packages.lock.json`, sans lancer de scripts d'installation. `wf restore` reconstruit le cache depuis ce verrou ; `wf restore --offline` le vérifie sans réseau. + +`wf dev` compile le TSX avec esbuild-wasm, ouvre l'interface et la reconstruit à chaque sauvegarde. Les erreurs apparaissent dans le terminal et l'aperçu, qui conserve sa dernière version valide. Ctrl+C l'arrête ; `wf build` compile une fois. + +Éditez `life-project/ui/main.tsx` et `style.css` avec votre éditeur habituel. React dessine la grille ; chaque génération attend C++ : + +```js +await webFront.ready; +const step = webFront.cppFunction('life.step'); +const next = await step(cells); +``` + +`cells` et `next` sont des `Uint8Array` de 128 octets correspondant à `std::bitset<1024>`, bit de poids faible en premier dans chaque octet. Tout appel JavaScript vers C++ renvoie une Promise : attendez-la ou traitez son rejet. Les règles du jeu restent en C++. + +### 4. Tester et vérifier les types + +Installez Jasmine et créez `life-project/tests/life.spec.js` : + +```text +wf install jasmine-core@7.0.2 +``` + +```js +describe('la grille Life', () => { + it('encode 32 fois 32 cellules dans 128 octets', () => { + const cells = new Uint8Array(32 * 32 / 8); + for (const i of [330, 331, 332]) cells[i >> 3] |= 1 << (i & 7); + expect(cells.length).toBe(128); + expect(cells[41]).toBe(0b00011100); + }); +}); +``` + +Ajoutez ce champ au manifeste (`wf init` ne copie pas cette recette) : + +```json +"test": {"specs": ["tests/life.spec.js"]} +``` + +Puis lancez : + +```text +wf test +``` + +Les specs tournent dans la fenêtre avec la version verrouillée de Jasmine. Un échec renvoie un code non nul. + +La compilation TSX retire les types sans les vérifier ; `wf check` utilise le compilateur TypeScript verrouillé par le projet. Créez `life-project/tsconfig.json` : + +```json +{ + "compilerOptions": { + "strict": true, + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "jsx": "react-jsx", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "noEmit": true + }, + "include": ["ui"] +} +``` + +```text +wf install typescript@5.9.3 @types/react@19.3.0 @types/react-dom@19.3.0 +wf check +``` + +### 5. Essayer le résultat + +![Jeu de la vie dans une fenêtre native](docs/images/life-preview.jpg) + +Lancez ou suspendez la simulation, avancez d'une génération, dessinez des cellules, changez de motif, de vitesse ou de vue. Les compteurs reflètent le calcul C++. Une seule demande de génération est en cours à la fois ; un échec arrête la lecture et s'affiche dans l'interface. + +### 6. Embarquer pour distribuer + +Déclarez l'entrée et le provider dans le manifeste (`"entries": {"main": "ui/main.tsx"}` et `"providers": {"LifeUI": {"entry": "main", "output": "generated/LifeUI.hpp"}}`), ou passez-les explicitement : + +```text +wf embed ui/main.tsx --output generated/LifeUI.hpp +``` + +La commande compile et rassemble ressources et notices des dépendances dans un en-tête C++ compressé. Fermez la fenêtre de développement, puis reconfigurez le même répertoire `build` : + +```bash +cmake .. -DWEBFRONT_LIFE_ASSETS="$PWD/life-project/generated/LifeUI.hpp" +cmake --build . --target WebFrontLifeEmbedded +examples/WebFrontLifeEmbedded +``` + +Avec Visual Studio, lancez `examples\Debug\WebFrontLifeEmbedded.exe`, ou `examples\Release\WebFrontLifeEmbedded.exe` après une construction avec `--config Release`. + +[LifeEmbedded.cpp](examples/life/LifeEmbedded.cpp) remplace le projet de développement par le provider généré : + +```cpp +#include "LifeFrontend.hpp" + +webfront::demo::LifeAppWithAssets app; +app.cppFunction("life.step", &webfront::demo::nextLife); +app.show(); +``` + +La recompilation est explicite. L'application fonctionne ensuite hors ligne, sans répertoire projet, callbacks de développement ni cache d'outils. Les prérequis de déploiement du moteur natif restent applicables : ceci ne fabrique pas un installateur. + +[LifeFrontend.hpp](examples/life/LifeFrontend.hpp) sélectionne `NativeOrBrowserFrontend` : fenêtre native disponible, sinon navigateur. Votre application peut choisir `NativeApp` ou `NativeAppWithAssets` lorsqu'une fenêtre native est obligatoire. + +## Laisser un agent piloter votre application + +Un agent peut vérifier les types, construire, prévisualiser, inspecter et cliquer l'interface de **votre application**, dans sa fenêtre et avec ses callbacks C++. Rien n'est activé par défaut. + +Transcription animée : découverte de session, vérification, compilation, aperçu, clic et appel d'un callback autorisé ; refus d'un callback privé + +*Transcription abrégée du test de régression `AutomationConsumerWindow`, exécuté sur une application réelle.* + +Les autorisations sont fixées dans le code natif : + +```cpp +#include + +webfront::NativeApp app{project}; +app.bootstrap("developer"); +app.cppFunction("bf.render", render); +auto automation = webfront::automation::enableAutomation( + app, {.grants = {"check", "build", "preview", "inspect", "interact", "call"}, + .callbacks = {"bf.render"}, + .listen = privateEndpointDirectory}); +app.show(automation->launchPage()); +automation->close(); +app.shutdown(); +``` + +- **Visible.** Le terminal annonce les autorisations et la manière de se connecter. +- **Découvrable.** `webfront-agent --list` liste les sessions partagées sans exposer leur secret de connexion ; `--print-mcp-config --attach ` génère la configuration du client MCP. `--schema` et `--agent-help` décrivent le contrat. +- **Borné.** Chaque opération demande son autorisation ; seuls les callbacks nommément déclarés sont appelables. Des délais natifs arrêtent un renderer bloqué. Le code du projet conserve les droits de l'utilisateur : ce n'est pas un sandbox. +- **Optionnel.** Sans `enableAutomation`, aucun endpoint n'est enregistré. `webfront_add_agent()` construit et installe le lanceur pour les consommateurs CMake. + +Le [guide d'automation](docs/AUTOMATION.md#automating-your-own-application) décrit permissions, découverte, délais et profil MCP. + +## Intégrer WebFront dans votre projet + +L'implémentation réside dans `include/`. CMake apporte les implémentations C++ de transition et les réglages de plateforme : + +```cmake +add_subdirectory(path/to/WebFront) +add_executable(MyApp main.cpp) +target_link_libraries(MyApp PRIVATE WebFront::WebFront) +``` + +En sous-projet, exemples et tests sont désactivés par défaut et les réglages de compilation internes ne se propagent pas à vos cibles. `WEBFRONT_BUILD_EXAMPLES=OFF` désactive aussi les exemples en construction autonome. + +Avec GCC 16, l'analyse des modules C++ de CMake peut faire planter le compilateur dans stdexec. Pour une cible sans modules, ajoutez `webfront_disable_module_scan(MyApp)` après sa création. Si aucun de vos projets n'utilise les modules, `set(CMAKE_CXX_SCAN_FOR_MODULES OFF)` avant de créer les cibles est une autre possibilité. Voir les [détails en anglais](README.md#use-webfront-in-your-project). + +Pour activer la fenêtre native détectée : + +```cmake +webfront_use_native_window(MyApp) +``` + +Puis sélectionnez le type d'application : + +```cpp +#include + +#if defined(WEBFRONT_NATIVE_WINDOW) +using App = webfront::WebFrontWithFrontend; +#else +using App = webfront::WebFront; +#endif + +int main() { + App app; + app.show(); +} +``` + +Pour revenir au navigateur lorsqu'aucune session native ne peut s'ouvrir (SSH, conteneur ou CI, par exemple), choisissez `WebFrontWithFrontend` sans `#if`. La raison du repli est annoncée. Les helpers fonctionnent aussi après CPM ; la [référence des frontends](docs/FRONTENDS.md) décrit les sélections explicites. + +Une application qui possède sa boucle utilise `app.start()` avec le navigateur système. Les fenêtres natives imposent leurs règles de thread : `show()` sur le thread principal pour WKWebView, WebKitGTK et CEF ; `UIThread` possible avec WebView2. Voir [l'intégration hôte](docs/HOST_INTEGRATION.md) et [HostLoop.cpp](examples/host-loop/HostLoop.cpp). + +## Tester votre application + +L'intégration optionnelle [Jasmine et CTest](docs/CONSUMER_TESTING.md) exécute des specs sur la page réelle de l'application. Elle permet captures PNG, séquences d'images et lancement de programmes natifs explicitement autorisés par le propriétaire des tests, dans des espaces temporaires privés. Le parcours navigateur avec programmes natifs est validé sur Linux avec CEF ; le guide précise les autres limites. Ces programmes conservent les droits de l'utilisateur. + +`webfront::embeddedFrontendAvailable` indique si un moteur embarqué est compilé ; `webfront::EmbeddedWebFront` le sélectionne. + +## Construire et tester la bibliothèque + +```bash +cmake -S . -B build -DCMAKE_BUILD_TYPE=Release \ + -DWEBFRONT_EMBED_CEF=OFF -DWEBFRONT_ENABLE_TESTING=ON +cmake --build build --parallel 2 +ctest --test-dir build --output-on-failure --parallel 4 +``` + +La configuration des tests télécharge et vérifie par SHA-512 l'environnement épinglé et les paquets du registre de test. Les ressources du cœur sont générées et vérifiées par CMake seul ; les constructions normales utilisent les en-têtes versionnés. Les tests navigateur demandent un moteur activé ; sous Linux, ils nécessitent Xvfb. Désactivez explicitement WebKitGTK avec `-DWEBFRONT_EMBED_WEBKITGTK=OFF` pour un parcours uniquement C++ si nécessaire. + +`ctest -L fast` sélectionne les tests rapides. Les [tiers de tests](docs/TEST_TIERS.md) précisent la matrice desktop par PR, les validations étendues et la CI ARM64. Le [guide contributeur](AGENTS.md) contient les commandes, et les [mesures de tests](docs/TEST_PERFORMANCE.md) expliquent le parallélisme et les verrous de ressources. + +## Outils de construction sur les distributions LTS + +CMake **3.31+** est requis, y compris en sous-projet sans tests. Ubuntu 22.04 fournit CMake 3.22.1 et Ubuntu 24.04 CMake 3.28.3 : installez une version plus récente. Git 2.34.1 convient aux contrôles du dépôt. + +Une installation Python isolée évite de remplacer l'outil système. Installez `python3-venv` si nécessaire, puis : + +```bash +python3 -m venv "$HOME/.local/share/webfront-tools" +"$HOME/.local/share/webfront-tools/bin/python" -m pip install 'cmake>=3.31,<4' +export PATH="$HOME/.local/share/webfront-tools/bin:$PATH" +cmake --version +ctest --version +``` + +L'installation de CMake elle-même ne demande pas de droits root. Répétez l'export de `PATH` dans chaque shell de construction, ou placez-le dans votre profil. Le [dépôt APT Kitware](https://apt.kitware.com/) est une alternative. Mettre CMake à jour ne met pas le compilateur à jour : GCC 11 fourni par défaut sous Ubuntu 22.04 reste insuffisant. Voir la [décision sur les outils](docs/adr/ADR-022-profils-et-niveaux-de-support.md). + +## Contrats et limites + +- Le serveur HTTP/WebSocket appartient à WebFront et tourne en arrière-plan. Les callbacks s'exécutent séquentiellement sur son thread : évitez de le bloquer. Les appels navigateur peuvent partir des threads hôtes pendant la vie de l'application. Les coroutines applicatives appartiennent à `app.spawn` ou `ui.spawn` ; voir [exécution et annulation](docs/ASYNC_EXECUTION.md). +- Les appels JavaScript vers C++ renvoient toujours des Promises. En C++, `ui.jsFunction(name)(...)` est sans retour ; `ui.jsFunction(name)(...)` renvoie un `std::future`. Fonction absente, exception, réponse mal formée et déconnexion font échouer l'appel typé. Les futures et Promises n'exposent pas d'annulation ; les senders typés proposent une annulation locale. +- Le pont transporte scalaires, chaînes, tuples, tableaux numériques typés, bitsets et listes homogènes de valeurs composées prises en charge. Il ne transporte pas d'objets arbitraires. Chaînes et messages sont bornés par la politique de taille (64 Mio par défaut) ; à partir de 65 536 octets, les chaînes utilisent l'encodage long. +- L'environnement de développement et l'accès aux fichiers du projet sont destinés au code local de confiance, sans sandbox. Seuls les paquets compatibles navigateur sont pris en charge ; ni scripts d'installation ni extensions natives ne sont exécutés. `wf check` vérifie les types séparément de la compilation. +- L'adaptateur optionnel [`@webfront/react`](docs/REACT.md) apporte stores C++ avec regroupement des mises à jour et îlots React. `WebFrontLifeReact` montre un panneau C++ dans React ; son archive est préparée localement pour publication au registre. +- Linux embarqué dispose d'une CI ARM64 et de preuves sur Orin Nano. Les autres cartes, cibles sans OS et microcontrôleurs ne sont pas qualifiés globalement. Le transport local ne fournit ni TLS ni authentification client ; un accès distant demande une conception de sécurité propre à l'application. +- Packaging, accessibilité et déploiement des moteurs natifs restent propres au produit. L'[état du projet](docs/PROJECT_STATUS.md) fait référence pour les validations et limites ; l'[historique](docs/CHANGELOG.md) décrit les migrations et ruptures de compatibilité. + +## Licence + +WebFront est proposé sous double licence **Apache-2.0 OU CECILL-B**, au choix. Vous pouvez l'utiliser, le modifier et le redistribuer sous l'une de ces licences sans devoir respecter les deux simultanément. [LICENSE](LICENSE) contient les textes complets, dont les versions française et anglaise de CeCILL-B. + +Les composants tiers conservent leurs licences et notices ; le choix de licence WebFront ne les remplace pas. + +[Site](https://webfront.fr/fr/) · [Livre](https://webfront.fr/fr/book/) · [Environnement de développement](docs/DEVELOPER_ENVIRONMENT.md) · [Décisions d'architecture](docs/adr/README.md) · [Contribuer](.github/CONTRIBUTING.md) diff --git a/README.md b/README.md index d274e97e..fea5ac0f 100644 --- a/README.md +++ b/README.md @@ -4,28 +4,114 @@ [![Windows · MSVC](https://img.shields.io/badge/CI-Windows%20%C2%B7%20MSVC-0078D4)](https://github.com/ambroise-leclerc/WebFront/actions/workflows/BuildAndTest.yml) [![macOS · Apple Clang](https://img.shields.io/badge/CI-macOS%20%C2%B7%20Apple%20Clang-555555)](https://github.com/ambroise-leclerc/WebFront/actions/workflows/BuildAndTest.yml) [![Linux · GCC](https://img.shields.io/badge/CI-Linux%20%C2%B7%20GCC-E95420)](https://github.com/ambroise-leclerc/WebFront/actions/workflows/BuildAndTest.yml) +[![Linux · aarch64](https://img.shields.io/badge/CI-Linux%20%C2%B7%20aarch64%20%C2%B7%20GCC%2013-E95420)](https://github.com/ambroise-leclerc/WebFront/actions/workflows/BuildAndTest.yml) +[![Jetson Orin](https://img.shields.io/badge/CI-Jetson%20Orin-76B900)](docs/JETSON.md) [![C++23](https://img.shields.io/badge/C%2B%2B-23-00599C)](CMakeLists.txt) [![Header-only](https://img.shields.io/badge/library-header--only-2EA043)](include/) -**WebFront is a header-only C++23 library for building rich, modern user interfaces.** -Keep application logic in C++ and create reactive interfaces with TypeScript, React and the existing JavaScript package ecosystem. WebFront brings the UI tools into your application: there is no separate JavaScript development environment to install. +[English](README.md) · [Français](README.fr.md) -**Website and book: [webfront.fr](https://webfront.fr/en/)** ([en français](https://webfront.fr/fr/)) · [The WebFront Book](https://webfront.fr/en/book/) · [Documentation](docs/) · [Changelog](docs/CHANGELOG.md) +WebFront is a **header-only C++23 library for building rich, modern user interfaces.** Keep application logic in C++ and create reactive interfaces with TypeScript, React and the existing JavaScript package ecosystem. WebFront brings UI development tools into your application: there is no separate TypeScript development environment to install. -- **C++ in front, web technologies for the screen.** Functions registered with `cppFunction` are called from TypeScript over an asynchronous binary bridge; C++ calls browser functions with `ui.jsFunction`. -- **Native window or browser, same sources.** WebView2 (Windows), WKWebView (macOS), WebKitGTK (Linux), optional CEF, or the system browser as fallback. -- **A development environment inside your application.** `wf` installs dependencies, compiles TS/TSX, type-checks, runs Jasmine specs and previews on save, with no Node.js or package manager on the machine. -- **One executable to ship.** `wf embed` packages the interface into a C++ header; the distributed build runs offline without the development tools. -- **Ready for AI harnesses.** An optional local launcher (MCP or JSON CLI) lets an agent create, check, build and test a screen under explicit grants. +WebFront has no dependencies and can be deployed on any device with a recent C++ standard library. -Desktop Windows, macOS and Linux are the qualified platforms; embedded targets and microcontrollers are not. WebFront already drives a real application: [SiliconForge](https://github.com/ambroise-leclerc/SiliconForge), a microcontroller simulator. +Game of Life walkthrough: the C++ application beside the WebFront window, where wf create life, dependency installation and wf preview bring the React interface up below the terminal + +The animation shows the C++ application and the Game of Life example, with terminal output and timing condensed and the preview expanded for readability. [Follow the walkthrough below ↓](#game-of-life-from-console-to-native-application) + +- **Integrate into an existing application.** Keep your simulation, device control, SIMD computations, CUDA kernels... and worker threads in C++. Use a native window or even a web browser without surrendering your event loop. [Host integration →](docs/HOST_INTEGRATION.md) +- **Support human developers and coding agents.** The integrated `wf` tools compile, type-check, test and embed the UI. An opt-in MCP server and JSON CLI let coding agents operate your application's own window and run permitted checks and callbacks. [Agent workflow →](#developing-with-an-agent) +- **Move numerical data directly.** Typed arrays and packed bitsets cross a binary WebSocket bridge without JSON or base64 conversion. Coroutines, futures and senders connect asynchronous UI calls to native work. [Execution model →](docs/ASYNC_EXECUTION.md) +- **Build for distribution.** Embed assets, pin package versions and verify downloads; run the resulting application offline. CMake consumer targets and browser tests support repeatable builds and CI. [Integrate →](#use-webfront-in-your-project) · [Test →](#test-your-application) +- **Choose your UI stack.** Use TypeScript, React and browser-compatible packages, or build DOM islands directly from C++. Optional forms and inspectors derive from C++ type descriptors. [DOM →](docs/DOM.md) · [React →](docs/REACT.md) · [Forms →](docs/FORMS.md) + + + +**Website and book: [webfront.fr](https://webfront.fr/en/)** · [The WebFront Book](https://webfront.fr/en/book/) · [Documentation](docs/) · [Changelog](docs/CHANGELOG.md) + +## Platforms and deployment + +| Target | Interface options | Validation scope | +| --- | --- | --- | +| Windows | System browser, native WebView2, optional CEF | Desktop CI with MSVC; WebView2 needs the Evergreen runtime | +| macOS 13.3+ for the native window | System browser, system WKWebView, optional CEF | Desktop CI with AppleClang | +| Linux | System browser, native WebKitGTK 6.0, optional CEF | Desktop CI with GCC; extended Clang coverage | +| Linux ARM64 / NVIDIA Jetson | System browser, WebKitGTK or CEF where available | GCC 13 ARM64 CI and on-board **Orin Nano Super 8 GB** validation; see the [Jetson guide](docs/JETSON.md) | + +Designed to follow standard C++ across platforms, the core uses standard facilities and a replaceable networking provider. The default browser path avoids linking a native GUI toolkit or web-view engine. A target needs a suitable **C++23 compiler and standard library, OS networking and threads, and a browser**. GCC 13 is the best-effort minimum; the [support policy](docs/adr/ADR-022-profils-et-niveaux-de-support.md) defines tested toolchains and support levels. + +**No dependencies. No separate WebFront runtime.** The core follows the standard C++ networking and execution model. While these facilities are being standardized and adopted by standard libraries, CMake supplies pinned external implementations: the maintained `stdnet` networking layer and, when needed, `stdexec` for senders. These provide the interim implementation at build time; there is no WebFront library binary to install. Native web views retain their platform requirements, and CEF is optional. The developer environment caches verified tools and packages on first use; the embedded production build needs neither that cache nor the UI sources. + +### CUDA and embedded applications + +**Keep CUDA in your C++ application, including on NVIDIA Jetson Orin Nano.** WebFront does not prescribe the compute backend: your host loop or workers run CPU or CUDA code, while the web interface changes parameters and displays results through typed arrays. Keep `.cu` translation units separate from the C++23 WebFront headers when the CUDA compiler requires it. No CUDA toolkit is needed for applications that do not use CUDA. + +**The included [Boing Ball example](docs/HOST_LOOP_EXAMPLE.md) runs on CPU or CUDA.** A checkered ball bounces above a reflective floor; switch to tinted glass to reveal reflection, refraction and coloured light beams. Every pixel is computed by the C++ host, while the page displays the resulting typed array on a canvas. The same host loop works with a native window or the system browser. + +![CUDA Boing Ball animation in a native window on Jetson Orin Nano: checkered ball, then illuminated glass](docs/images/host-loop-boing.gif) + +```bash +cmake --build build --target WebFrontHostLoop --parallel 2 +build/examples/WebFrontHostLoop --quality 0 +# On a CUDA-equipped build and device: +build/examples/WebFrontHostLoop --engine cuda --glass --stats +``` + +With a multi-configuration generator such as Visual Studio, replace `build/examples/` in the commands above with `build/examples/Debug/`, or `build/examples/Release/` after building with `--config Release`. The executable is named `WebFrontHostLoop.exe`. + +Run these commands from the repository root after configuration. CUDA detection is automatic; `-DWEBFRONT_HOST_LOOP_CUDA=OFF` builds the complete CPU example without the toolkit. Add `--browser` to select the system browser. The [example guide](docs/HOST_LOOP_EXAMPLE.md) covers quality, benchmarking and the separate CUDA compiler configuration. + +**Qualified on Jetson Orin Nano Super 8 GB:** real-board builds, CPU/CUDA rendering, native-window and bridge tests, and sandboxed distribution checks. A trusted [hardware validation workflow](docs/JETSON_RUNNER.md) complements hosted ARM64 CI. See the [board qualification](docs/JETSON.md) and [rendering measurements](docs/HOST_LOOP_EXAMPLE.md) for the tested software stack and scope. NX/AGX and other JetPack versions require their own qualification; accelerated rendering inside WebKit's sandbox is not established by these results. + +On Linux, WebKitGTK defaults to development mode with its sandbox disabled. For distribution, select `-DWEBFRONT_DISTRIBUTION=ON` and package the application's sandbox profile where required. [Development and distribution →](docs/WEBKITGTK.md#development-and-distribution) + +## Performance by design + +Keep heavy computation native and send the data the interface needs: numeric buffers stay typed, bitsets stay packed, and bridge calls are asynchronous. The server has its own thread; your compute loop and workers remain independent. The optional React adapter coalesces C++ snapshots per browser, and the DOM API batches writes. + +These mechanisms help control serialization, update frequency and UI overhead. End-to-end performance still depends on message size, rendering and the target hardware. Measure computation, transport and display separately; the [execution guide](docs/ASYNC_EXECUTION.md) explains where work runs and how to keep callbacks responsive. + +For a measured example, the Boing Ball on **Orin Nano Super 8 GB at 25 W**, with a sandboxed WebKitGTK 2.52.6 window, displays: + +| Scene | CPU (6 threads) | CUDA | +| --- | ---: | ---: | +| Opaque ball | 12 images/s | 21 images/s | +| Glass and light beams | About 0.6 images/s | 12 images/s | + +Scene: 960 × 720, four rays per pixel; window: 800 × 600 CSS pixels. Release build, GCC 13.3, CUDA 13.2.86, L4T R39.2.1. These are board-specific observations, not universal throughput guarantees. The [measurement report](docs/HOST_LOOP_EXAMPLE.md#system-browser-and-distribution-follow-up) separates compute, copy, transport and display, and compares the system browser with the native window. + +## Find your starting point + +- **Evaluate the library:** [Hello World](#hello-world), then the [Game of Life walkthrough](#game-of-life-from-console-to-native-application). +- **Add a UI to existing software:** [CMake integration](#use-webfront-in-your-project) and the [host loop example](examples/host-loop/HostLoop.cpp). +- **Work with a coding agent:** [developer workflow](#developing-with-an-agent) and [application automation](#let-an-agent-drive-your-application). +- **Plan production:** [testing](#test-your-application), [contracts and limitations](#contracts-and-limitations) and [support status](docs/PROJECT_STATUS.md). + +## Developing with an agent + +If you are a coding agent, or work with one, read this before anything else. The [agent guide](docs/DEVELOPING_WITH_AGENTS.md) has the details. + +- **The model.** A WebFront application is a C++ program whose interface is TypeScript/TSX. The interface lives in **`ui/`** of the project directory (`ui/main.ts` or `ui/main.tsx`) and is developed with **`wf dev`**, in the terminal that `app.bootstrap("developer")` opens in the application's window. Pages of hand-written HTML and classic JavaScript served through `documentRoot` are not the development path: none of the tools apply to them. +- **The sequence.** With the pinned developer environment: `wf create app` (the starter name, not your project's name), `wf init`, `wf install ` for browser dependencies, then `wf dev ui/main.ts`. Finish with `wf check`, `wf test` and `wf embed` using the project's configuration. Use `wf create life` for the React walkthrough. `wf help agents` prints the workflow. +- **An agent runs `wf` itself, in JSON or MCP.** Do not ask a person to type the commands. Configure with `-DWEBFRONT_BUILD_AUTOMATION=ON` to build `webfront-agent`; the application opts in with `webfront::automation::enableAutomation(app, {.grants = {...}, .listen = directory})`, whose grants stay the owner's; then: + +```sh +webfront-agent --list # the sessions shared with agents +webfront-agent --attach DIRECTORY --operation create --starter app +webfront-agent --attach DIRECTORY --operation preview --entry ui/main.ts # after each edit, in place of wf dev +webfront-agent --print-mcp-config --attach DIRECTORY > .mcp.json # the same operations as an MCP server +``` + +```json +{"mcpServers": {"webfront": {"command": "/path/to/webfront-agent", "args": ["--attach", "/path/to/directory", "--mcp"]}}} +``` + +In a project that embeds WebFront, `webfront_write_agent_guide()` writes these rules as `AGENTS.md` at its root, and `wf create` writes them beside the starter's sources. ## From C++ to a reactive UI Register your simulation, bootstrap the tools, then build the interface in the application's terminal. `life-project` is the working directory for the UI sources: -Game of Life walkthrough: the C++ application beside the WebFront window, where wf create life, dependency installation and wf preview bring the React interface up below the terminal -
The C++ application of the animation, as text @@ -65,8 +151,6 @@ int main() {
-The animation shows the C++ application and the Game of Life example, with terminal output and timing condensed and the preview expanded for readability. [Follow the walkthrough below ↓](#game-of-life-from-console-to-native-application) - ## Hello World The smallest program, [HelloWorld.cpp](examples/hello-world/HelloWorld.cpp), serves the embedded page and opens it in your browser (`WebFront` always uses the system browser): @@ -112,7 +196,7 @@ int main() { ## Game of Life: from console to native application -The example starts with a C++ simulation, adds a React interface, then embeds that interface in the executable. You need Git, CMake **3.31+** and a C++23 compiler. The initial CMake configuration, the first bootstrap and the first `wf install` need internet access; afterwards the downloaded environment and packages are cached and can be verified offline. +The example starts with a C++ simulation, adds a React interface, then embeds that interface in the executable. You need Git, CMake **3.31+** and a C++23 compiler (GCC **13+**; GCC 13 has best-effort S2 support). See [build tools on LTS distributions](#build-tools-on-lts-distributions) when your distribution supplies an older CMake, and the [compiler support policy](docs/adr/ADR-022-profils-et-niveaux-de-support.md) for the tested toolchains and limits. The initial CMake configuration, the first bootstrap and the first `wf install` need internet access; afterwards the downloaded environment and packages are cached and can be verified offline. ```bash git clone https://github.com/ambroise-leclerc/WebFront.git @@ -148,7 +232,7 @@ app.bootstrap("developer"); app.show(); ``` -The project directory gives the application access to its development files. `bootstrap("developer")` opens the integrated terminal and loads the version-pinned developer environment, checking its SHA-512 integrity. Downloads are cached, so later launches work offline. The terminal runs `wf` commands; no system shell is exposed and nothing is installed on your machine. +The project directory gives the application access to its development files. `bootstrap("developer")` opens the integrated terminal and loads the version-pinned developer environment, checking its SHA-512 integrity. Downloads are cached, so later launches work offline. The terminal runs `wf` commands on the project and has `ls`, `cat`, `tree` and `mounts` to look at it; no system shell is exposed. Tools and packages are cached for this environment, without a host JavaScript installation. The build you made above is enough. Start the example from the `build` directory: @@ -173,12 +257,15 @@ explicitly enabling WKWebView with such a target fails configuration. See [the m When the engine is missing, configuration still succeeds. CMake prints a `Native window: no native engine will be built` notice that says what to install, and `WebFrontLifeDeveloper` is compiled for the default browser: at start it prints that notice, serves the same application and opens it in your system browser. Install the dependency and run `cmake ..` again to get the native window. CEF (`-DWEBFRONT_EMBED_CEF=ON`) makes `CEFFrontend` available to your own applications; the examples do not select it. -**Advanced options.** +
+Advanced native engine and environment options - Choose the engine yourself with `-DWEBFRONT_EMBED_WEBVIEW2=ON|OFF`, `-DWEBFRONT_EMBED_WKWEBVIEW=ON|OFF` or `-DWEBFRONT_EMBED_WEBKITGTK=ON|OFF`; an explicit value is never replaced by the detection. `-DWEBFRONT_AUTODETECT_NATIVE=OFF` disables it. Test builds (`-DWEBFRONT_ENABLE_TESTING=ON`) keep the explicit selection. - Automatic engine choices are recalculated on each configuration and do not create an engine option in the cache. To return from an explicit macOS choice to automatic detection, run `cmake .. -UWEBFRONT_EMBED_WKWEBVIEW` (or remove the corresponding engine option on another platform). - Another project directory, and another environment archive, can be passed: `examples/WebFrontLifeDeveloper [ ]`, for instance an environment [built from the sources](docs/DEVELOPER_ENVIRONMENT.md#environment-distribution-and-offline-tests-maintainers). +
+ The example reports startup failures with a nonzero exit status. ### 3. Create the project and install its dependencies @@ -192,7 +279,7 @@ wf install react@19.3.1 react-dom@19.3.1 wf dev ui/main.tsx ``` -- `wf create life` writes the editable [TSX and CSS starter](examples/life/ui) into `ui/`; it never overwrites an existing directory. +- `wf create life` writes the editable [TSX and CSS starter](examples/life/ui) into `ui/`; it never overwrites an existing directory. The argument names a starter, not your project: `wf create app` writes a minimal TypeScript interface for a new application instead. - `wf init` writes `webfront.project.json`, the manifest every other command reads: dependencies, entries, providers, scripts and permissions. - `wf install` resolves the packages and their dependencies from the registry, verifies their integrity and records exact versions in `webfront-packages.lock.json`. It does not run the installation scripts of packages. `wf restore` rebuilds the cache from the lock on another machine, and `wf restore --offline` verifies it without any network. - `wf dev` compiles the TSX with esbuild-wasm, opens the interface inside the application and rebuilds it whenever you save a source. A build error appears in the terminal and over the preview, which keeps its last good version. Ctrl+C stops it; `wf build` compiles once without opening anything. @@ -255,17 +342,6 @@ The builds remove TypeScript types without checking them; `wf check` runs the Ty The type packages come next: `wf install typescript@5.9.3 @types/react@19.3.0 @types/react-dom@19.3.0` then `wf check` type-check the starter. Both commands are described in the [developer environment reference](docs/DEVELOPER_ENVIRONMENT.md). -An optional native [automation launcher](docs/AUTOMATION.md) exposes the developer window through -local stdio MCP or a JSON CLI, with explicit permissions for check/build/test/preview and bounded -UI inspection/actions. It requires an environment containing automation API v1 (0.6.3 or later), -built from the sources or obtained from a verified published distribution. - -An agent finds what it may drive without being told: `webfront-agent --list` prints the sessions their owners shared -(project, grants, process and endpoint, never the attachment capability), `webfront-agent --print-mcp-config --attach ` -prints a ready `.mcp.json`, and `webfront-agent --schema` / `--agent-help` describe the contract. Your own application opts in -with `webfront::automation::enableAutomation(app, {.grants = {...}, .listen = dir})`, so that the agent drives *its* window -and callbacks; see [automation of your own application](docs/AUTOMATION.md#automating-your-own-application). - ### 5. Try the result ![Game of Life running in a native window](docs/images/life-preview.jpg) @@ -338,15 +414,27 @@ app.shutdown(); The [automation guide](docs/AUTOMATION.md#automating-your-own-application) covers grants, callbacks, discovery, deadlines and the MCP profile. -## What's new since 0.5.0 +## Capabilities for production projects -The [changelog](docs/CHANGELOG.md) is exhaustive; the main additions are: +Beyond the basic bridge, WebFront provides [owned application coroutines and cancellation](docs/ASYNC_EXECUTION.md), broadcasts to connected browsers, [C++ DOM islands](docs/DOM.md), [forms and TypeScript declarations](docs/FORMS.md), and the optional [React store and `Island` adapter](docs/REACT.md). Adopt these independently; React is not required by the core. -- **0.6.0.** `ui.document()` for [DOM islands from C++](docs/DOM.md); [forms and inspectors](docs/FORMS.md) generated from type descriptions (with an optional C++26 reflection layer); the [`@webfront/react` adapter](docs/REACT.md) with coalesced C++ stores and `Island`; `app.broadcast(...)` and `app.forEachUI(...)` to reach every browser from any thread; connection generations that reject a stale `UI`; local [automation](docs/AUTOMATION.md) (`webfront-agent`, stdio MCP and JSON CLI). -- **0.7.0.** **Breaking:** test, fuzzing, coverage and sanitizer CMake options require the `WEBFRONT_` prefix (`WEBFRONT_ENABLE_TESTING`, ...); several agent shutdown fixes; faster pull-request CI. -- **0.8.0.** Authorized native programs and private temporary files from [Jasmine specs](docs/CONSUMER_TESTING.md); PNG screenshots and image sequences of the web view (`webFrontCapture`); `webfront::embeddedFrontendAvailable` and `webfront::EmbeddedWebFront`; `init`, `create`, `install`, `restore` and `embed` available to automation. -- **0.9.0.** The last minor revision before 1.0, with the developer environment at the same number. System services groundwork ([ADR-020](docs/adr/README.md)): writable storage confined to declared roots, typed access to the native window and an interface-thread executor for every frontend, dynamic and ranged HTTP routes, file inputs and downloads in the embedded frontends, automation of an application's own window, and the `@webfront/services` package skeleton. Developer environment 0.9.0 is the first published by the `release-developer` workflow. -- **Developer distribution.** The developer environment is served from `dist.webfront.fr` ([ADR-021](docs/adr/README.md)). Libraries older than the sources' pin keep the former address, which no longer works for the developer bootstrap: rebuild against the current sources. +For release history, migration notes and breaking changes, see the [changelog](docs/CHANGELOG.md). The [project status](docs/PROJECT_STATUS.md) records current validation and limitations; it is the reference when selecting a platform or frontend for production. + +## Build tools on LTS distributions + +WebFront requires CMake **3.31+** for both standalone builds and `add_subdirectory`/CPM consumers, including builds with tests disabled. Ubuntu 22.04 supplies CMake 3.22.1 and Ubuntu 24.04 supplies 3.28.3, so install a newer CMake before configuring. Git 2.34.1, as supplied by Ubuntu 22.04, works with the repository's commit checks. The [tooling decision and audit](docs/adr/ADR-022-profils-et-niveaux-de-support.md#outils-de-construction-distributions-lts-527) explain the common CMake floor; optional mddlog has [separate requirements](docs/mddlog-integration.md). + +One option is an isolated Python environment. On Ubuntu, install its prerequisite with `sudo apt-get install python3-venv` if needed, then run: + +```bash +python3 -m venv "$HOME/.local/share/webfront-tools" +"$HOME/.local/share/webfront-tools/bin/python" -m pip install 'cmake>=3.31,<4' +export PATH="$HOME/.local/share/webfront-tools/bin:$PATH" +cmake --version +ctest --version +``` + +The CMake installation itself needs no root access. Run the `export PATH=...` line in each build shell (or add it to your shell profile); it selects the matching `cmake` and `ctest`. Then use the build commands below or the Game of Life walkthrough above. Alternatively, follow the [Kitware APT repository instructions](https://apt.kitware.com/) for your Ubuntu release. A newer CMake does not supply a newer C++ compiler: Ubuntu 22.04's default GCC 11 still needs replacing with a toolchain from the support policy. ## Use WebFront in your project @@ -360,6 +448,9 @@ target_link_libraries(MyApp PRIVATE WebFront::WebFront) As a subproject, examples and tests are off by default and compiler settings do not leak into your targets. `WEBFRONT_BUILD_EXAMPLES=OFF` disables examples in a standalone build too. +
+GCC 16 and C++ module scanning + GCC 16 crashes inside stdexec (`internal compiler error: Segmentation fault` in `__query.hpp`) when CMake scans C++ modules and adds `-fmodules-ts`, which happens by default for C++20 and later targets (CMP0155, Ninja). WebFront is header-only and needs no module scan. Turn it off for the targets that link WebFront and use no C++ modules, after creating them: ```cmake @@ -372,7 +463,9 @@ Alternatively, `set(CMAKE_CXX_SCAN_FOR_MODULES OFF)` before creating your target Configuring WebFront as a subproject with GCC 16 and scanning enabled prints a warning naming each affected target, with these workarounds. -`webfront::WebFront` always uses the system browser. For a native window with the same browser fallback as the examples, add this after linking your target (also works after `CPMAddPackage`): +
+ +`webfront::WebFront` always uses the system browser. For a native window with the same browser fallback as the Life examples, add this after linking your target (also works after `CPMAddPackage`): ```cmake webfront_use_native_window(MyApp) @@ -423,16 +516,16 @@ shared projects and nested builds retain resource locks. See [test timings and parallelism](docs/TEST_PERFORMANCE.md) for measurements and constraints. `ctest -L fast` runs the unit tests in about a second; [test tiers](docs/TEST_TIERS.md) describes what CI runs on each pull request, weekly and before a merge into `master`. -CI runs one combined C++ / native-browser job per desktop platform on each code change. The Linux job also collects and prints GCC line coverage (no external upload). Linux Clang, sanitizers, fuzzing and CEF compatibility run weekly, on demand and on pull requests into `master`. Manual dispatch with `repeat_desktop_tests=true` also runs the complete desktop CTest suite three times, recreating its fixtures on each pass. Workflow concurrency cancels superseded runs; dependency and compiler caches avoid repeated work. Platform badges above identify the configured matrix; the CI badge reports its aggregate status. Execution times depend on cache state and runner availability. +CI exercises C++ and native-browser paths on Windows, macOS and Linux. Extended jobs cover Clang, sanitizers, fuzzing, CEF and Linux ARM64, including ARM64 CEF/WebKitGTK browser runs. The [test tiers](docs/TEST_TIERS.md) define the exact schedule and required gates; the [workflow](.github/workflows/BuildAndTest.yml) records toolchains and options. Hosted ARM64 coverage and [real Jetson board qualification](docs/JETSON.md) are separate evidence. Platform badges identify the configured matrix; the CI badge reports its aggregate status. ## Contracts and limitations -- WebFront owns an HTTP/WebSocket server on a background thread. Callbacks run there, one at a time; avoid blocking it. Browser calls (`jsFunction`, `app.broadcast(name)(...)`) can be made from any thread and never wait for it; see [threads](docs/ASYNC_EXECUTION.md#threads). Native windows must be created and shown on the main thread. Application coroutines use `app.spawn(task)` or `ui.spawn(task)`; see [execution and cancellation](docs/ASYNC_EXECUTION.md). +- WebFront owns an HTTP/WebSocket server on a background thread. Callbacks run there, one at a time; avoid blocking it. Browser calls (`jsFunction`, `app.broadcast(name)(...)`) can be made from any thread and never wait for it; see [threads](docs/ASYNC_EXECUTION.md#threads). Most native windows (WKWebView, WebKitGTK, CEF) must be created and shown on the main thread; WebView2 accepts a secondary thread. An application that keeps its own loop uses `app.start()` (system browser, returns at once), `app.requestClose()` or `webfront::UIThread`; see [host integration](docs/HOST_INTEGRATION.md). Application coroutines use `app.spawn(task)` or `ui.spawn(task)`; see [execution and cancellation](docs/ASYNC_EXECUTION.md). - JavaScript calls to C++ always return Promises. C++ `ui.jsFunction(name)(...)` is fire-and-forget; `ui.jsFunction(name)(...)` returns `std::future`. Missing functions, exceptions, malformed replies and disconnects fail the typed call. -- The binary bridge supports scalars, strings, tuples, numeric typed arrays and packed bitsets. Arbitrary objects do not cross it. Strings have a 16-bit encoded length limit. +- The binary bridge supports scalars, strings, tuples, numeric typed arrays, packed bitsets and homogeneous lists of supported compound values. Arbitrary objects do not cross it. Strings and messages are bounded by the message-size policy (64 MiB by default); strings of 65,536 bytes or more use the long-string encoding. See [the bridge contract](docs/adr/ADR-003-protocole-binaire-et-bornes.md). - Development project access is explicit and intended for trusted local code. Downloaded tools run with the application's bridge authority, and script permissions frame only the `context` API: neither is a sandbox. Only packages that run in a browser are supported; installation scripts and native add-ons are not executed. Builds transform TypeScript without type checking; `wf check` type-checks with the compiler the project locks. - The optional [`@webfront/react` adapter](docs/REACT.md) supplies coalesced C++ stores and empty React islands. `WebFrontLifeReact` demonstrates a C++ panel within the Game of Life React UI; its package archive is prepared locally for registry publication. -- Embedded targets and microcontrollers are not qualified (C++23 support, memory, networking and remote transport security are unreviewed). +- Embedded Linux has ARM64 CI coverage and specific Orin Nano board evidence; other boards, bare-metal targets and microcontrollers are not generally qualified. Check C++23, memory, networking and browser requirements for your target. The default local transport supplies neither TLS nor client authentication; remote deployment needs an application-specific security design. - Packaging, accessibility and native-engine deployment still need application-specific work. The optional [`ui.document()` API](docs/DOM.md) provides DOM islands, automatically batched writes, event callbacks and grouped sender reads. See [project status](docs/PROJECT_STATUS.md) for known limitations. ## License diff --git a/cmake/BoingCuda.cmake b/cmake/BoingCuda.cmake new file mode 100644 index 00000000..53f73e16 --- /dev/null +++ b/cmake/BoingCuda.cmake @@ -0,0 +1,43 @@ +# The optional CUDA renderer of the host-loop example (examples/host-loop/BoingCuda.cu). Without a usable toolkit the +# example and its tests are built with the CPU renderer alone, which computes the same pixels. +# +# nvcc does not compile C++23: the renderer is one .cu unit, compiled at C++17, that includes no WebFront header and +# shares BoingScene.hpp with the CPU renderer. nvcc also bounds the host compiler it accepts: when it refuses the +# default one, CMAKE_CUDA_HOST_COMPILER (or the CUDAHOSTCXX environment variable) names another. +set(WEBFRONT_HOST_LOOP_CUDA "AUTO" CACHE STRING "CUDA renderer of the host-loop example: AUTO (when a working toolkit is found), ON or OFF") +set_property(CACHE WEBFRONT_HOST_LOOP_CUDA PROPERTY STRINGS AUTO ON OFF) + +# A macro: enable_language() must run in the scope of the top-level CMakeLists.txt, above every directory whose +# targets link the CUDA unit. Defines WebFront_boing, which a target computing the scene links: nothing on a CPU-only +# build, the CUDA unit and WEBFRONT_BOING_CUDA otherwise. +macro(webfront_enable_host_loop_cuda) + if(NOT WEBFRONT_HOST_LOOP_CUDA MATCHES "^(AUTO|ON|OFF)$") + message(FATAL_ERROR "WEBFRONT_HOST_LOOP_CUDA must be AUTO, ON or OFF, not '${WEBFRONT_HOST_LOOP_CUDA}'") + endif() + set(WEBFRONT_HOST_LOOP_CUDA_ENABLED OFF) + if(WEBFRONT_HOST_LOOP_CUDA STREQUAL "ON") + enable_language(CUDA) + set(WEBFRONT_HOST_LOOP_CUDA_ENABLED ON) + elseif(WEBFRONT_HOST_LOOP_CUDA STREQUAL "AUTO") + include(CheckLanguage) + check_language(CUDA) + if(CMAKE_CUDA_COMPILER) + enable_language(CUDA) + set(WEBFRONT_HOST_LOOP_CUDA_ENABLED ON) + endif() + endif() + if(WEBFRONT_HOST_LOOP_CUDA_ENABLED) + message(STATUS "Host-loop example: CUDA ${CMAKE_CUDA_COMPILER_VERSION} renderer enabled (${CMAKE_CUDA_COMPILER})") + else() + message(STATUS "Host-loop example: CPU renderer only (WEBFRONT_HOST_LOOP_CUDA=${WEBFRONT_HOST_LOOP_CUDA}, no working CUDA compiler)") + endif() + + add_library(WebFront_boing INTERFACE) + if(WEBFRONT_HOST_LOOP_CUDA_ENABLED) + add_library(WebFront_boing_cuda STATIC "${PROJECT_SOURCE_DIR}/examples/host-loop/BoingCuda.cu") + target_compile_features(WebFront_boing_cuda PRIVATE cuda_std_17) + target_compile_definitions(WebFront_boing_cuda PUBLIC WEBFRONT_BOING_CUDA=1) + set_target_properties(WebFront_boing_cuda PROPERTIES POSITION_INDEPENDENT_CODE ON) + target_link_libraries(WebFront_boing INTERFACE WebFront_boing_cuda) + endif() +endmacro() diff --git a/cmake/CEFIntegration.cmake b/cmake/CEFIntegration.cmake index 3aebdf61..9c8e9e55 100644 --- a/cmake/CEFIntegration.cmake +++ b/cmake/CEFIntegration.cmake @@ -30,7 +30,7 @@ message(STATUS "WebFront: Embedded CEF window support enabled") set(CEF_USE_SANDBOX OFF CACHE BOOL "Disable CEF sandbox" FORCE) set(CEF_WRAPPER_BUILD_SKIP OFF CACHE BOOL "Enable CEF wrapper build" FORCE) -# Inherited SDK flags; CEF 154 does not honor all of them. CPM below controls CTest registration. +# Inherited SDK flags; CEF 156 does not honor all of them. CPM below controls CTest registration. set(CEF_SKIP_TESTS ON CACHE BOOL "Skip CEF tests" FORCE) set(CEF_BUILD_TESTS OFF CACHE BOOL "Disable CEF test building" FORCE) set(BUILD_CEF_TESTS OFF CACHE BOOL "Disable CEF test building" FORCE) @@ -50,7 +50,7 @@ set(WITH_TESTS OFF CACHE BOOL "Disable all tests" FORCE) # This scopes the normal binding, not arbitrary cache writes inside a dependency. Recheck CEF's # BUILD_TESTING handling on SDK upgrades; CACHE FORCE could still modify the caller's cache. CPMAddPackage( - URI "gh:ambroise-leclerc/CEF@154.0.34" + URI "gh:ambroise-leclerc/CEF@156.0.28" OPTIONS "BUILD_TESTING OFF" ) @@ -60,7 +60,7 @@ if(MSVC) target_compile_definitions(WebFront INTERFACE _ITERATOR_DEBUG_LEVEL=0 _HAS_ITERATOR_DEBUGGING=0) endif() -# CEF 154 creates its demo targets unconditionally. Keep them out of the default build; +# CEF 156 creates its demo targets unconditionally. Keep them out of the default build; # BUILD_TESTING=OFF above prevents CEF's own CTest registration on the first configure. foreach(_webfront_cef_test_target cef_sanity_test cef_resources_test cef_window_test) if(TARGET ${_webfront_cef_test_target}) diff --git a/cmake/CompilerWarnings.cmake b/cmake/CompilerWarnings.cmake index 2657516a..f0eedc24 100644 --- a/cmake/CompilerWarnings.cmake +++ b/cmake/CompilerWarnings.cmake @@ -4,8 +4,8 @@ function(set_project_warnings project_name) option(WARNINGS_AS_ERRORS "Treat compiler warnings as errors" ON) - # MSVC /analyze roughly doubles the front-end work of every unit (#435): OFF is for measuring that cost, not for CI. - option(WEBFRONT_MSVC_ANALYZE "Run the MSVC code analysis while compiling" ON) + # MSVC /analyze roughly doubles the front-end work of every unit (#435): a local build leaves it out, and the + # advanced CI tier turns it on (docs/TEST_TIERS.md). set(MSVC_WARNINGS /W4 # Baseline reasonable warnings diff --git a/cmake/DeveloperCompatibility.cmake b/cmake/DeveloperCompatibility.cmake index 1d8fc7b7..650f510c 100644 --- a/cmake/DeveloperCompatibility.cmake +++ b/cmake/DeveloperCompatibility.cmake @@ -6,6 +6,11 @@ # freezes the "unreleased" row into a row of that library version (the preparation of a library release) # # The table lies between the markers below; a row is "| library | environment | minimum api |". +if(CMAKE_VERSION VERSION_LESS "3.31") + message(FATAL_ERROR + "WebFront requires CMake 3.31 or newer (found ${CMAKE_VERSION}). " + "See README.md#build-tools-on-lts-distributions for installation instructions.") +endif() cmake_minimum_required(VERSION 3.31) if(NOT ROOT OR NOT MODE) message(FATAL_ERROR "ROOT and MODE (unreleased or freeze) are required") diff --git a/cmake/Frontends.cmake b/cmake/Frontends.cmake index e8b4d304..e57bdf28 100644 --- a/cmake/Frontends.cmake +++ b/cmake/Frontends.cmake @@ -203,7 +203,7 @@ webfront_register_frontend(WebKitGTK TEST_SETUP webfront_add_webkitgtk_tests) webfront_register_frontend(CEF OPTION WEBFRONT_EMBED_CEF POLICY lenient - DESCRIPTION "Download and link CEF so CEFFrontend is available (Windows, Linux and macOS only). Other platforms fail at configure time" + DESCRIPTION "Download and link CEF so CEFFrontend is available (Windows, Linux x86_64 and aarch64, and macOS only). Other platforms fail at configure time" PLATFORMS Windows Linux Darwin SUPPORT CEFIntegration SETUP setup_cef_for_target TEST_PLATFORMS Linux TEST_NAME WebFrontBrowserIntegration TEST_TIMEOUT 60 XVFB_LINUX) @@ -436,7 +436,11 @@ function(webfront_add_browser_tests target frontend assets_directory lifecycle_t set(lifecycle_command "${XVFB_RUN_EXECUTABLE}" -a ${lifecycle_command}) endif() set(lifecycle_modes no-bridge early-close rejected-ready navigation-failure path-encoding content-policy navigation-allow-list view-association stage-report) - list(APPEND lifecycle_modes ui-executor native-window second-open) + list(APPEND lifecycle_modes ui-executor native-window second-open host-close) + # CEF neither supports nor checks a secondary thread: nothing to observe there (docs/HOST_INTEGRATION.md). + if(NOT frontend STREQUAL "CEF") + list(APPEND lifecycle_modes host-thread) + endif() foreach(mode ${lifecycle_modes}) set(lifecycle_name "${frontend}Lifecycle-${mode}") add_test(NAME ${lifecycle_name} COMMAND ${lifecycle_command} ${mode}) diff --git a/cmake/WKWebViewSupport.cmake b/cmake/WKWebViewSupport.cmake index 51d9e147..6efe1c01 100644 --- a/cmake/WKWebViewSupport.cmake +++ b/cmake/WKWebViewSupport.cmake @@ -18,7 +18,7 @@ function(webfront_add_wkwebview_tests) add_executable(wkwebview_lifecycle "${webtest_source_dir}/WKWebViewLifecycle.cpp" "${webtest_source_dir}/WKWebViewHeaderConsumer.cpp") target_link_libraries(wkwebview_lifecycle PRIVATE WebFront WebFront_warnings WebFront_options) - foreach(mode repeated-show main-thread native-close quit navigation-diagnostic startup-timeout settings redirect-policy missing-response committed-navigation agent-application download choose-file cancel-choose replaced-download choose-in-blank choose-in-srcdoc close-with-open-panel close-with-save-panel script-dialogs close-with-script-dialog sandboxed-script-dialog) + foreach(mode repeated-show main-thread native-close quit navigation-diagnostic startup-timeout settings hidden-scheduling redirect-policy missing-response committed-navigation agent-application download choose-file cancel-choose replaced-download choose-in-blank choose-in-srcdoc close-with-open-panel close-with-save-panel script-dialogs close-with-script-dialog sandboxed-script-dialog) add_test(NAME WKWebViewLifecycle-${mode} COMMAND wkwebview_lifecycle ${mode}) webfront_set_browser_test_properties("WKWebViewLifecycle-${mode}" "${webtest_source_dir}" 90) endforeach() diff --git a/cmake/WebFrontAgentGuide.cmake b/cmake/WebFrontAgentGuide.cmake new file mode 100644 index 00000000..45593716 --- /dev/null +++ b/cmake/WebFrontAgentGuide.cmake @@ -0,0 +1,70 @@ +# Public helpers that tell an agent, from the first configuration, how a WebFront application is developed. +include_guard(GLOBAL) + +# The paths are computed inside the functions, from CMAKE_CURRENT_FUNCTION_LIST_DIR: a variable set here would belong to the +# scope that included this file, and the functions are called from its parent (add_subdirectory, FetchContent). + +# webfront_write_agent_guide([DIRECTORY dir] [NAME file]) +# +# Writes the agent guide of a WebFront application (the same text `wf create` puts beside a starter's sources) as +# AGENTS.md at the root of the calling project: the model (C++ with a TypeScript/TSX interface in ui/, developed with +# `wf dev`) and how an agent runs wf itself in JSON or MCP. Coding agents read that file before anything else. +# +# add_subdirectory(WebFront) # or FetchContent / CPM +# webfront_write_agent_guide() # /AGENTS.md, once +# +# An existing file is never replaced or appended to, whatever wrote it: the function then says in one line where the +# guide is, so that a project with its own AGENTS.md can refer to it. DIRECTORY defaults to the top-level source +# directory, NAME to AGENTS.md (CLAUDE.md, for instance, for a client that reads that name). +function(webfront_write_agent_guide) + cmake_parse_arguments(ARG "" "DIRECTORY;NAME" "" ${ARGN}) + if(ARG_UNPARSED_ARGUMENTS OR ARG_KEYWORDS_MISSING_VALUES) + message(FATAL_ERROR "webfront_write_agent_guide: invalid arguments (unknown: ${ARG_UNPARSED_ARGUMENTS}; keywords without a value: ${ARG_KEYWORDS_MISSING_VALUES})") + endif() + if(NOT ARG_DIRECTORY) + set(ARG_DIRECTORY "${CMAKE_SOURCE_DIR}") + endif() + if(NOT ARG_NAME) + set(ARG_NAME AGENTS.md) + endif() + if(NOT ARG_NAME MATCHES "^[A-Za-z0-9._-]+$" OR ARG_NAME MATCHES "^[.]+$") + message(FATAL_ERROR "webfront_write_agent_guide: NAME must be a plain file name (got '${ARG_NAME}')") + endif() + cmake_path(ABSOLUTE_PATH ARG_DIRECTORY BASE_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" NORMALIZE) + if(NOT IS_DIRECTORY "${ARG_DIRECTORY}") + message(FATAL_ERROR "webfront_write_agent_guide: ${ARG_DIRECTORY} is not a directory") + endif() + cmake_path(NORMAL_PATH CMAKE_CURRENT_FUNCTION_LIST_DIR OUTPUT_VARIABLE here) + set(source "${here}/../js/developer/starters/agent-guide.md") + cmake_path(NORMAL_PATH source) + set(destination "${ARG_DIRECTORY}/${ARG_NAME}") + # EXISTS follows links: a dangling link is a file somebody placed there too. + if(EXISTS "${destination}" OR IS_SYMLINK "${destination}") + message(STATUS "WebFront: ${destination} exists and is left unchanged; the agent guide is ${source}") + return() + endif() + file(COPY_FILE "${source}" "${destination}") + message(STATUS "WebFront: wrote the agent guide ${destination}") +endfunction() + +# One notice per configuration, for whoever reads the configure output first: the development model, the guide, and +# either how to attach to the launcher that is built or the option that builds it. +function(webfront_announce_agent_support) + get_property(announced GLOBAL PROPERTY WEBFRONT_AGENT_SUPPORT_ANNOUNCED) + if(announced) + return() + endif() + set_property(GLOBAL PROPERTY WEBFRONT_AGENT_SUPPORT_ANNOUNCED ON) + set(guide "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../docs/DEVELOPING_WITH_AGENTS.md") + cmake_path(NORMAL_PATH guide) + if(TARGET webfront-agent) + set(launcher "the webfront-agent target runs wf for an agent in JSON or MCP (webfront-agent --agent-help)") + else() + set(launcher "webfront-agent, which runs wf for an agent in JSON or MCP, is not built: " + "configure with -DWEBFRONT_BUILD_AUTOMATION=ON") + string(JOIN "" launcher ${launcher}) + endif() + message(STATUS "WebFront for agents: an application is C++ with a TypeScript/TSX interface in ui/, developed with `wf dev` " + "(not pages served from documentRoot); ${launcher}. Guide: ${guide}" + "; webfront_write_agent_guide() writes it as AGENTS.md in your project.") +endfunction() diff --git a/cmake/WebFrontBootstrap.cmake b/cmake/WebFrontBootstrap.cmake index dba1b6fb..152b1bd0 100644 --- a/cmake/WebFrontBootstrap.cmake +++ b/cmake/WebFrontBootstrap.cmake @@ -15,6 +15,124 @@ set(WEBFRONT_BOOTSTRAP_INTEGRITY "sha512-qaSYOJvxcXtKIbrjfjZFFvfoQrda5NfBq24ttQ7 # A directory holding environment.tgz (the pinned archive) replaces the download on a machine without network access. set(WEBFRONT_BOOTSTRAP_DIR "" CACHE PATH "Directory with the pinned bootstrap environment.tgz, instead of downloading it") +# The verified downloads of the configure, kept once per machine: a new build tree links them instead of downloading them +# again. WEBFRONT_DOWNLOAD_CACHE or CPM's cache chooses the place; WebFront's own build otherwise uses the user's cache +# directory, and a project that consumes WebFront keeps each download in its build tree unless it asks. An environment +# variable set to nothing counts as unset, so that it never makes a path at the root; -DWEBFRONT_DOWNLOAD_CACHE= disables +# the cache. +get_filename_component(_webfront_source "${CMAKE_CURRENT_LIST_DIR}/.." ABSOLUTE) +set(_webfront_download_cache "") +if(NOT "$ENV{WEBFRONT_DOWNLOAD_CACHE}" STREQUAL "") + set(_webfront_download_cache "$ENV{WEBFRONT_DOWNLOAD_CACHE}") +elseif(NOT "$ENV{CPM_SOURCE_CACHE}" STREQUAL "") + set(_webfront_download_cache "$ENV{CPM_SOURCE_CACHE}/webfront-downloads") +elseif(NOT CMAKE_SOURCE_DIR STREQUAL _webfront_source) + # A consuming project: each download stays in its build tree. +elseif(CMAKE_HOST_WIN32 AND NOT "$ENV{LOCALAPPDATA}" STREQUAL "") + set(_webfront_download_cache "$ENV{LOCALAPPDATA}/WebFront/downloads") +elseif(CMAKE_HOST_APPLE AND NOT "$ENV{HOME}" STREQUAL "") + set(_webfront_download_cache "$ENV{HOME}/Library/Caches/WebFront/downloads") +elseif(NOT "$ENV{XDG_CACHE_HOME}" STREQUAL "") + set(_webfront_download_cache "$ENV{XDG_CACHE_HOME}/webfront/downloads") +elseif(NOT "$ENV{HOME}" STREQUAL "") + set(_webfront_download_cache "$ENV{HOME}/.cache/webfront/downloads") +endif() +set(WEBFRONT_DOWNLOAD_CACHE "${_webfront_download_cache}" CACHE PATH "Directory keeping the verified configure downloads for every build tree (empty: none)") +# A download that fails is tried again, WEBFRONT_DOWNLOAD_ATTEMPTS times in all, WEBFRONT_DOWNLOAD_RETRY_DELAY seconds apart. +if(NOT DEFINED WEBFRONT_DOWNLOAD_ATTEMPTS) + set(WEBFRONT_DOWNLOAD_ATTEMPTS 3) +endif() +if(NOT DEFINED WEBFRONT_DOWNLOAD_RETRY_DELAY) + set(WEBFRONT_DOWNLOAD_RETRY_DELAY 5) +endif() + +# Sets to TRUE when a file can be created in , which is created when missing. An existing directory +# may still refuse files (a read-only cache, a mount of another user's): a probe file tells. +function(_webfront_writable_directory directory output) + set(${output} FALSE PARENT_SCOPE) + file(MAKE_DIRECTORY "${directory}" RESULT made) + if(NOT made EQUAL 0) + return() + endif() + string(RANDOM LENGTH 12 suffix) + set(probe "${directory}/.webfront-probe-${suffix}") + execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${probe}" RESULT_VARIABLE touched OUTPUT_QUIET ERROR_QUIET) + if(touched EQUAL 0 AND EXISTS "${probe}") + file(REMOVE "${probe}") + set(${output} TRUE PARENT_SCOPE) + endif() +endfunction() + +# webfront_download_verified( URL SHA512 FAILURE MISMATCH ): makes a file whose SHA-512 +# is . A file already there with that digest is kept. Otherwise the machine's download cache provides it, a download +# filling the cache first; is then a link to the cached file, or a copy where a link cannot be made. A download that +# fails is tried again; when it still fails, the configure stops with FAILURE and the reason, and with MISMATCH when the +# data it brought has another digest. No file without the expected digest is ever left at or in the cache. +function(webfront_download_verified path) + cmake_parse_arguments(ARG "" "URL;SHA512;FAILURE;MISMATCH" "" ${ARGN}) + if(EXISTS "${path}") + file(SHA512 "${path}" actual) + if(actual STREQUAL ARG_SHA512) + return() + endif() + file(REMOVE "${path}") + endif() + get_filename_component(name "${path}" NAME) + get_filename_component(destination "${path}" DIRECTORY) + file(MAKE_DIRECTORY "${destination}") + set(target "${path}") + if(WEBFRONT_DOWNLOAD_CACHE) + # The first half of the digest names the entry: two files of the same name and version never meet. + string(SUBSTRING "${ARG_SHA512}" 0 32 key) + set(entry "${WEBFRONT_DOWNLOAD_CACHE}/${key}/${name}") + # A verified entry serves even a cache that cannot be written, such as a shared read-only one. + if(EXISTS "${entry}") + file(SHA512 "${entry}" actual) + if(actual STREQUAL ARG_SHA512) + file(CREATE_LINK "${entry}" "${path}" COPY_ON_ERROR) + return() + endif() + endif() + # A download fills the cache only where a file can be created; a damaged entry is replaced once verified. + _webfront_writable_directory("${WEBFRONT_DOWNLOAD_CACHE}/${key}" writable) + if(writable) + set(target "${entry}") + else() + message(WARNING "The download cache ${WEBFRONT_DOWNLOAD_CACHE} cannot be written: ${name} is kept in the build tree only") + endif() + endif() + set(present FALSE) + foreach(attempt RANGE 1 ${WEBFRONT_DOWNLOAD_ATTEMPTS}) + # Written aside, then renamed once verified: a concurrent configure never reads a partial file. + string(RANDOM LENGTH 12 suffix) + set(partial "${target}.${suffix}.partial") + file(DOWNLOAD "${ARG_URL}" "${partial}" STATUS result TLS_VERIFY ON INACTIVITY_TIMEOUT 60 TIMEOUT 600) + list(GET result 0 code) + if(code EQUAL 0) + file(SHA512 "${partial}" actual) + if(NOT actual STREQUAL ARG_SHA512) + file(REMOVE "${partial}") + message(FATAL_ERROR "${ARG_MISMATCH}") + endif() + file(RENAME "${partial}" "${target}") + set(present TRUE) + break() + endif() + file(REMOVE "${partial}") + list(GET result 1 reason) + if(attempt LESS WEBFRONT_DOWNLOAD_ATTEMPTS) + message(STATUS "Download of ${ARG_URL} failed (${reason}); trying again in ${WEBFRONT_DOWNLOAD_RETRY_DELAY} s") + execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep ${WEBFRONT_DOWNLOAD_RETRY_DELAY}) + endif() + endforeach() + if(NOT present) + message(FATAL_ERROR "${ARG_FAILURE}: ${reason} (${WEBFRONT_DOWNLOAD_ATTEMPTS} attempts)") + endif() + if(NOT target STREQUAL path) + file(CREATE_LINK "${target}" "${path}" COPY_ON_ERROR) + endif() +endfunction() + # Converts a base64 value to lowercase hexadecimal bytes. function(webfront_base64_to_hex value output) set(alphabet "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") @@ -86,24 +204,9 @@ function(webfront_provision_bootstrap archive) endif() else() set(path "${ARG_DESTINATION}/${name}") - set(present FALSE) - if(EXISTS "${path}") - file(SHA512 "${path}" actual) - if(actual STREQUAL expected) - set(present TRUE) - endif() - endif() - if(NOT present) - file(MAKE_DIRECTORY "${ARG_DESTINATION}") - file(DOWNLOAD "${ARG_URL}" "${path}" STATUS result TLS_VERIFY ON INACTIVITY_TIMEOUT 60 TIMEOUT 600) - list(GET result 0 code) - if(NOT code EQUAL 0) - file(REMOVE "${path}") - list(GET result 1 reason) - message(FATAL_ERROR "Cannot download the bootstrap environment ${ARG_URL}: ${reason}. " - "Provision it with -DWEBFRONT_BOOTSTRAP_DIR=.") - endif() - endif() + webfront_download_verified("${path}" URL "${ARG_URL}" SHA512 "${expected}" + FAILURE "Cannot download the bootstrap environment ${ARG_URL}. Provision it with -DWEBFRONT_BOOTSTRAP_DIR=" + MISMATCH "Bootstrap environment integrity check failed for ${ARG_URL}: expected ${ARG_INTEGRITY}") endif() file(SHA512 "${path}" actual) if(NOT actual STREQUAL expected) diff --git a/cmake/WebFrontDistribution.cmake b/cmake/WebFrontDistribution.cmake new file mode 100644 index 00000000..c537ed88 --- /dev/null +++ b/cmake/WebFrontDistribution.cmake @@ -0,0 +1,77 @@ +# Build policy and package integration for native WebKitGTK applications. No runtime is added. +include_guard(GLOBAL) + +function(_webfront_distribution_executable target operation) + if(NOT TARGET "${target}") + message(FATAL_ERROR "${operation}: unknown target '${target}'") + endif() + get_target_property(kind "${target}" TYPE) + if(NOT kind STREQUAL "EXECUTABLE") + message(FATAL_ERROR "${operation} requires an executable target") + endif() +endfunction() + +# Select every target compiling the native UI; library requirements propagate to their consumers. +function(webfront_use_distribution) + if(NOT ARGC) + message(FATAL_ERROR "webfront_use_distribution requires at least one target") + endif() + foreach(target IN LISTS ARGN) + if(NOT TARGET "${target}") + message(FATAL_ERROR "webfront_use_distribution: unknown target '${target}'") + endif() + get_target_property(imported "${target}" IMPORTED) + get_target_property(kind "${target}" TYPE) + if(imported OR kind STREQUAL "UTILITY") + message(FATAL_ERROR "webfront_use_distribution requires a buildable application or library target") + endif() + if(kind STREQUAL "EXECUTABLE") + set(scope PRIVATE) + elseif(kind STREQUAL "INTERFACE_LIBRARY") + set(scope INTERFACE) + else() + set(scope PUBLIC) + endif() + target_compile_definitions("${target}" ${scope} WEBFRONT_DISTRIBUTION=1) + message(STATUS "WebFront ${target}: DISTRIBUTION policy (WebKitGTK sandbox required)") + endforeach() +endfunction() + +# webfront_generate_webkitgtk_profile(APPARMOR_ABI 4.0 TARGET app EXECUTABLE /usr/bin/app OUTPUT generated/profile) +# EXECUTABLE is the final installed path, not the build path. Packaging owns installation/reload (dh_apparmor). +# Generating the file never changes the target mode, installs it or changes the host's AppArmor policy. +function(webfront_generate_webkitgtk_profile) + cmake_parse_arguments(PARSE_ARGV 0 ARG "" "TARGET;EXECUTABLE;OUTPUT;APPARMOR_ABI" "") + if(ARG_UNPARSED_ARGUMENTS OR ARG_KEYWORDS_MISSING_VALUES OR NOT ARG_TARGET OR NOT ARG_EXECUTABLE OR NOT ARG_OUTPUT) + message(FATAL_ERROR "webfront_generate_webkitgtk_profile requires TARGET, EXECUTABLE and OUTPUT") + endif() + if(NOT ARG_APPARMOR_ABI STREQUAL "4.0") + message(FATAL_ERROR "webfront_generate_webkitgtk_profile requires APPARMOR_ABI 4.0 for the target OS; older AppArmor releases do not use this userns authorization profile") + endif() + if(NOT ARG_TARGET MATCHES "^[A-Za-z0-9_.-]+$") + message(FATAL_ERROR "webfront_generate_webkitgtk_profile: target must have a literal profile name") + endif() + # AppArmor attachment patterns and substitutions must never widen this per-executable grant. + if(NOT ARG_EXECUTABLE MATCHES "^/[A-Za-z0-9_./+ -]+$" OR ARG_EXECUTABLE MATCHES "(^|/)\\.\\.(/|$)") + message(FATAL_ERROR "webfront_generate_webkitgtk_profile: EXECUTABLE must be an absolute literal installed path without patterns") + endif() + _webfront_distribution_executable("${ARG_TARGET}" webfront_generate_webkitgtk_profile) + string(SHA256 executable_hash "${ARG_EXECUTABLE}") + string(SUBSTRING "${executable_hash}" 0 16 executable_hash) + get_filename_component(output "${ARG_OUTPUT}" ABSOLUTE BASE_DIR "${CMAKE_CURRENT_BINARY_DIR}") + get_filename_component(profile_file "${output}" NAME) + if(NOT profile_file MATCHES "^[A-Za-z0-9_.-]+$") + message(FATAL_ERROR "webfront_generate_webkitgtk_profile: OUTPUT must have a literal profile filename") + endif() + get_filename_component(directory "${output}" DIRECTORY) + file(MAKE_DIRECTORY "${directory}") + file(CONFIGURE OUTPUT "${output}" CONTENT +"# Installed with the application; enables WebKit's own sandbox, not application confinement. +abi , +include +profile webfront-@ARG_TARGET@-@executable_hash@ \"@ARG_EXECUTABLE@\" flags=(unconfined) { + userns, + include if exists +} +" @ONLY) +endfunction() diff --git a/cmake/WebFrontRegistry.cmake b/cmake/WebFrontRegistry.cmake index be76d82c..3b670b89 100644 --- a/cmake/WebFrontRegistry.cmake +++ b/cmake/WebFrontRegistry.cmake @@ -25,6 +25,7 @@ function(webfront_provision_registry output list directory) set(name "${CMAKE_MATCH_1}-${name}") endif() set(path "${directory}/${name}") + # A verified archive already in the build tree is kept: the offline directory need not stay mounted. set(present FALSE) if(EXISTS "${path}") file(SHA512 "${path}" actual) @@ -32,21 +33,17 @@ function(webfront_provision_registry output list directory) set(present TRUE) endif() endif() - if(NOT present) - if(WEBFRONT_REGISTRY_DIR) - if(NOT EXISTS "${WEBFRONT_REGISTRY_DIR}/${name}") - message(FATAL_ERROR "Test registry archive ${WEBFRONT_REGISTRY_DIR}/${name} is missing: WEBFRONT_REGISTRY_DIR must hold it") - endif() - file(COPY_FILE "${WEBFRONT_REGISTRY_DIR}/${name}" "${path}" ONLY_IF_DIFFERENT) - else() - file(DOWNLOAD "${url}" "${path}" STATUS result TLS_VERIFY ON INACTIVITY_TIMEOUT 60 TIMEOUT 600) - list(GET result 0 code) - if(NOT code EQUAL 0) - file(REMOVE "${path}") - list(GET result 1 reason) - message(FATAL_ERROR "Cannot download ${url}: ${reason}. Provision the archives with -DWEBFRONT_REGISTRY_DIR=.") - endif() + if(present) + continue() + elseif(WEBFRONT_REGISTRY_DIR) + if(NOT EXISTS "${WEBFRONT_REGISTRY_DIR}/${name}") + message(FATAL_ERROR "Test registry archive ${WEBFRONT_REGISTRY_DIR}/${name} is missing: WEBFRONT_REGISTRY_DIR must hold it") endif() + file(COPY_FILE "${WEBFRONT_REGISTRY_DIR}/${name}" "${path}" ONLY_IF_DIFFERENT) + else() + webfront_download_verified("${path}" URL "${url}" SHA512 "${expected}" + FAILURE "Cannot download ${url}. Provision the archives with -DWEBFRONT_REGISTRY_DIR=" + MISMATCH "Integrity check failed for ${name}: expected ${integrity}") endif() file(SHA512 "${path}" actual) if(NOT actual STREQUAL expected) diff --git a/cmake/WebFrontTestOptions.cmake b/cmake/WebFrontTestOptions.cmake index 843ab263..886bc163 100644 --- a/cmake/WebFrontTestOptions.cmake +++ b/cmake/WebFrontTestOptions.cmake @@ -1,5 +1,9 @@ # WebFront options are independent of an embedding project's generic ENABLE_* variables. function(webfront_declare_test_options is_top_level) + # Keep the quick-build defaults here so the lightweight configuration fixture tests the actual declarations. + set(WEBFRONT_TEST_UNITY_BATCH 4 CACHE STRING "Compile the heavy unit tests this many to a file; 0 compiles each file alone") + option(WEBFRONT_MSVC_ANALYZE "Run the MSVC code analysis while compiling" OFF) + option(WEBFRONT_TEST_REPRODUCIBILITY "Build the self-built environment again, to prove it reproducible and equal to the checked-in bundles" OFF) option(WEBFRONT_ENABLE_TESTING "Build WebFront's tests" OFF) option(WEBFRONT_ENABLE_FUZZING "Build WebFront's fuzzers" OFF) option(WEBFRONT_ENABLE_COVERAGE "Instrument WebFront's tests for GCC/Clang coverage" OFF) diff --git a/cmake/WebKitGTKSupport.cmake b/cmake/WebKitGTKSupport.cmake index e9bb2ceb..3add3cee 100644 --- a/cmake/WebKitGTKSupport.cmake +++ b/cmake/WebKitGTKSupport.cmake @@ -12,6 +12,10 @@ endif() # The adapter uses dlopen rather than linking GTK into all executables (including CEF subprocesses). # Do not propagate its SDK include paths or GTK/GLib headers through WebFront. target_compile_definitions(WebFront INTERFACE WEBFRONT_EMBED_WEBKITGTK) +find_program(WEBFRONT_WEBKITGTK_BWRAP_EXECUTABLE NAMES bwrap DOC "Bubblewrap path compiled into the target WebKitGTK engine") +if(WEBFRONT_WEBKITGTK_BWRAP_EXECUTABLE) + target_compile_definitions(WebFront INTERFACE WEBFRONT_WEBKITGTK_BWRAP_EXECUTABLE="${WEBFRONT_WEBKITGTK_BWRAP_EXECUTABLE}") +endif() include("${CMAKE_CURRENT_LIST_DIR}/../test/cmake/WebKitGTKTestEnvironment.cmake") @@ -24,7 +28,7 @@ function(webfront_add_webkitgtk_tests) target_link_libraries(webkitgtk_lifecycle PRIVATE WebFront_test_hardening WebFront WebFront_warnings WebFront_options) add_dependencies(webtest webkitgtk_lifecycle) webfront_find_xvfb(display_runner) - foreach(mode no-display worker-thread native-close repeated-show http-error pre-run-failure poll-failure profile-permissions window-title download download-user-dir choose-file cancel-choose close-with-dialog script-dialogs close-with-script-dialog) + foreach(mode sandbox-environment sandbox-recheck no-display worker-thread native-close repeated-show http-error pre-run-failure poll-failure profile-permissions window-title download download-user-dir choose-file cancel-choose close-with-dialog script-dialogs close-with-script-dialog) if(mode MATCHES "^(no-display|worker-thread|pre-run-failure|profile-permissions)$") add_test(NAME WebKitGTKAdapter-${mode} COMMAND webkitgtk_lifecycle ${mode}) elseif(display_runner) diff --git a/docs/ASYNC_EXECUTION.md b/docs/ASYNC_EXECUTION.md index 771fafff..396107a2 100644 --- a/docs/ASYNC_EXECUTION.md +++ b/docs/ASYNC_EXECUTION.md @@ -197,8 +197,9 @@ app.cppFunction("slowSquare", [&app](int value) -> webfront::ResultTask { ## Threads -WebFront runs its HTTP/WebSocket server on one thread: the thread `show()` starts, or the thread -that calls `run()` or `runOne()`. That server thread is the only one that runs: +WebFront runs its HTTP/WebSocket server on one thread: the thread `show()` or `start()` starts, or +the thread that calls `run()` or `runOne()`. An application that keeps its own loop instead of +giving its thread to `show()` follows [host integration](HOST_INTEGRATION.md). That server thread is the only one that runs: - `cppFunction` callbacks, `onUIStarted`, `subscribeUIStarted` and `subscribeUIClosed` handlers; - DOM event callbacks and the bodies of tasks started with `app.spawn` or `ui.spawn`. @@ -210,7 +211,8 @@ From any thread, while the application lives, you can call: - `ui.jsFunction(name)(...)`, `ui.jsFunction(name)(...)` and starting a `jsFunctionSender`; - `ui.addScript`, `ui.pendingWrites`, `ui.writesAtMost` and `ui.spawn`; -- `app.broadcast(name)(...)`, `app.forEachUI`, `app.connectedBrowsers`, `app.spawn` and `app.stop`. +- `app.broadcast(name)(...)`, `app.forEachUI`, `app.connectedBrowsers`, `app.spawn`, `app.stop` + and `app.requestClose`. These calls never wait for the server thread. They take short internal locks, queue the frame, and the server thread writes it. Only `ui.document()` and its nodes are confined to the server diff --git a/docs/AUTOMATION.md b/docs/AUTOMATION.md index 6bab6f04..82f1893d 100644 --- a/docs/AUTOMATION.md +++ b/docs/AUTOMATION.md @@ -11,12 +11,19 @@ bridge as MCP. Applications can explicitly integrate `automation::Binding` with A session ID routes operations and prevents accidental cross-session requests; it is not an authentication secret. The opt-in native attachment channel uses a separate OS-generated capability. +New to WebFront, or an agent about to write an application? Start with [developing with an agent](DEVELOPING_WITH_AGENTS.md): +the model (C++ with a TypeScript/TSX interface in `ui/`), the development loop and the JSON and MCP form of each `wf` command. +This page is the reference. + For testing a consumer's own page through CTest, see [consumer testing](CONSUMER_TESTING.md). That independent API is available in this tree; MCP is unnecessary for CI to run Jasmine. ## Building and provisioning -Enable an embedded frontend and the launcher. For example, on macOS: +Enable an embedded frontend and the launcher. An application build needs only `-DWEBFRONT_BUILD_AUTOMATION=ON`: the native +engine of the platform is detected. Each configuration prints one `WebFront for agents:` line that says whether the launcher +is built, and `webfront_write_agent_guide()` writes the agent guide as `AGENTS.md` in a project that embeds WebFront +(never replacing an existing file). A test build selects its engine explicitly; for example, on macOS: ```sh cmake -S . -B build-agent -DCMAKE_BUILD_TYPE=Release \ @@ -33,7 +40,7 @@ The implementation is native C++23; no Node.js, npm or Python is required to run Provision an environment containing automation API v1 (0.6.3 or later). The setup operations (`init`, `create`, `install`, `restore`, `embed`) need environment **0.6.4 or later**, which must be published (see the [0.6.4 publication gate](validation/developer-0.6.4-release.md)) before anything depending on this pin is merged: the launcher checks this at startup, and granting one of them to an older environment fails with a bootstrap error (status 70) naming the operation, instead of failing each run. -`create` needs the starter archives (`-starter.tgz`, such as `life-starter.tgz` of a distribution build) in the same +`create` needs the starter archives (`-starter.tgz`, such as `app-starter.tgz` and `life-starter.tgz` of a distribution build) in the same directory as the `--environment` archive: the launcher serves only files of that name from there, and the environment's manifest pins their SHA-512, so the directory is not trusted for content. Environment 0.6.2 predates that API; passing an older environment produces a bootstrap error with status 70. @@ -378,20 +385,19 @@ control need their own reviewed authorization/isolation design. ## Validation -Catch2 covers native grants, cross-session rejection, path/option refusal, cancellation races, +The unit tests cover native grants, cross-session rejection, path/option refusal, cancellation races, deadline revocation, MCP lifecycle/IDs and hostile JSON. Browser Jasmine specs cover shared dispatch arbitration and the runner. `AutomationMcpWindow` drives a real embedded window through stdio: structured errors, file correction, check/build/test, preview inspection/actions, cross-frame rejection, cancellation and POSIX SIGTERM cleanup of the shared owner -(endpoint and temporary profile). This reuses the existing window. Separate `AutomationMcpWatchdog` and -`AutomationCliWatchdog` cases block a real renderer inside a test-archive operation body, -without loading/compiling Jasmine just to provoke that hang. They exercise the production signed -callback/runner, native two-second deadline, five-second close grace, stdio EOF and endpoint removal; -the CLI case checks endpoint reuse and Unicode failure reporting in the same restart after forced -exit. The MCP case delays bootstrap by three -seconds to verify that its shorter operation deadline starts only after startup. The cases retain -separate private project/temporary directories and ephemeral ports; the frontend storage limits -listed above still apply. Only the two spinning renderers share a lock. +(endpoint and temporary profile). This reuses the existing window. A separate `AutomationMcpWatchdog` case +blocks a real renderer inside a test-archive operation body, +without loading/compiling Jasmine just to provoke that hang. It exercises the production signed +callback/runner, native two-second deadline, five-second close grace, stdio EOF and endpoint removal +through MCP; a CLI restart after the forced exit then checks endpoint reuse and Unicode failure reporting. +It delays bootstrap by three seconds to verify that its shorter operation deadline starts only after startup. The +cases retain separate private project/temporary directories and ephemeral ports; the frontend storage limits +listed above still apply. That regression uses Python's standard library as a test client; Python is not a runtime dependency of the launcher. It is registered when a Python interpreter and embedded test engine are available; without xvfb-run on Linux only the optional Automation window tests are skipped with diff --git a/docs/BUILD_TIME_STUDY.md b/docs/BUILD_TIME_STUDY.md index bec79c66..1fd9cf5e 100644 --- a/docs/BUILD_TIME_STUDY.md +++ b/docs/BUILD_TIME_STUDY.md @@ -15,7 +15,7 @@ runs; Linux runs are steadier. | Change | Effect | |---|---| | `--parallel 4` on the desktop builds | Linux `tests` 280 -> 170 s cold, `all` 520 -> 255-375 s; Windows `tests` 820 -> 640 s, `all` 1240 -> 1080 s. Peak memory stays under 1 GB. | -| The 13 heavy unit tests compile four to a file (`WEBFRONT_TEST_UNITY_BATCH=4` on the desktop jobs) | Windows cold 640 -> 355 s, `WebFront.hpp` changed 298 -> 111 s; Linux 202 -> 143 s and 88 -> 45 s. Less memory. | +| The 13 heavy unit tests compile four to a file (`WEBFRONT_TEST_UNITY_BATCH=4`, the default) | Windows cold 640 -> 355 s, `WebFront.hpp` changed 298 -> 111 s; Linux 202 -> 143 s and 88 -> 45 s. Less memory. | | MSVC `/analyze` and the examples only in the master and weekly tier | `/analyze` is about 22 % of a Windows build (640 -> 497 s cold); the examples about 190 s of compiler time. | | The reproducibility builds only when a pull request changes their inputs | About 45 s of worker time per job (`SelfBuildRepeat`, `SelfBuildRefresh`). | | `JourneyEmbeddedBuild` and `LifeEmbeddedBuild` do not hold `webfront_port_9002` | They only compile; the lock had serialised 175 s (Linux) and 203 s (Windows) of tests. | diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index fe4ac5fd..bc4d781c 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -1,812 +1,242 @@ # Changelog +All notable changes to WebFront, newest first. The format follows [Keep a Changelog](https://keepachangelog.com/) and +[Common Changelog](https://common-changelog.org/); see [Changelog format](../.github/CONTRIBUTING.md#changelog-format). + +Each version opens with a short summary, then lists `Breaking`, `Added`, `Changed`, `Fixed` and `Security` entries +(empty categories are omitted). An entry is one line that says what changes for you and ends with its references. +Mechanisms, error codes and platform details live in the cited ADR, guide or pull request. The earlier, detailed text of +these entries stays in the GitHub releases and the Git history. + ## Unreleased -## 0.9.0 - 2026-11-10 - -- Diagnose asynchronous media and file-services specs before Jasmine's generic timeout (#504). Each spec shares a 15 s - budget across named operations with a 20 s Jasmine deadline; video failures include the media state and a bounded - `mediaRanges` query. The video waits for initial data and checks the destination of each `seeked` event. Consumer - Jasmine reports retain recorded failure names, normalize isolated Unicode surrogates and explicitly shorten diagnostics - to fit the JSON byte budget. See the [macOS investigation and validation](validation/wkwebview-specs-504.md). -- Build the unit tests with GCC 16.1 and make the native storage tests independent of the umask (#517). `fs::detail::pageOf` - moves its page into the result with a loop instead of `vector::assign` over move iterators, which GCC 16.1 reported with - `-Wnull-dereference` in `basic_string` (an error under the default `-Werror`). The native storage tests created their - directories with the process umask: under the common `0002` each one was group-writable, refused by the POSIX checks as - `unsafeDirectory` instead of reaching the link, root-move and confinement checks they target (5 scenarios). They now use - `makeDirectories()`, and a scenario runs it under `umask(0)`. -- Record the [platform validation of the native integration](validation/native-integration-450.md) (#450): the manual program - `native_integration_manual` (`test/web/NativeIntegrationManual.cpp`, outside CTest/CI) drives the interface-thread executor and the - native window with a real browser, window and native dialog. It passes on Windows (system browser's loop, and WebView2 with a - dialog owned by the window) and on a Linux desktop (system browser's loop; WebKitGTK under X11 and Wayland, with the - portal identifier exported and the parented `GtkFileDialog` completing on the interface thread). -- Typed access to the native window and its link to a connection (#463, ADR-020 step 5, last task). `frontend::NativeWindow` - (`NativeWindow.hpp`) gives the `HWND` (WebView2), `NSWindow*` (WKWebView), `GtkWindow*` (WebKitGTK) or `CefBrowser*` (CEF) through - `get()`, a `std::expected` that answers only on the interface thread (#462) while the window is published: `notOpen`, `closed`, - `wrongThread`, `unsupported` otherwise. `BasicWF::nativeWindow()` returns the frontend's handle and `UI::nativeWindow()` adds the - association of #453: a connection that is not the embedded view gets `notEmbedded`, so the system browser stays without a parent. - WebKitGTK also gives the portal `parent_window` (`x11:`, or `wayland:` exported once the window is ready). Catch2 tests - with a simulated host and the shared lifecycle case `native-window` (before open, from another thread, on the interface thread, - after closure). The manual check of a parented dialog is documented in `docs/FRONTENDS.md` and waits for the native backend. -- Interface-thread executor for every frontend (#462, ADR-020 step 5, ADR-007 1.11). `frontend::UIExecutor` (`UIExecutor.hpp`) - exposes `available()`, `onUIThread()` and `schedule()`, a sender that completes on the interface thread: `set_value()` there, - `set_stopped()` when the stop token fires first or the loop closes with the operation pending (it never runs after closure), - `set_error(UIExecutorUnavailable)` when no loop is attached. `BasicWF::uiExecutor()` forwards the frontend's. WKWebView - (main queue), WebView2 (a window message), WebKitGTK (`g_idle_add_full`) and CEF (`CefPostTask(TID_UI)`) publish one while - `open()` runs their loop. New `BrowserWithUILoopFrontend` is the system browser with an optional minimal loop on the calling - thread (message-only window pump, AppKit run loop with `NSApplication` in the Accessory policy, GLib loop; all loaded at run - time, nothing to link) that ends with `requestStop()`; the plain browser frontend still has no executor. Catch2 tests with a - simulated loop and the shared lifecycle case `ui-executor` (execution on the interface thread, race with closure, call after closure). -- Release workflow of the developer environment (#482, ADR-021 phase 1; repository side). The `release-developer` workflow - (`.github/workflows/ReleaseDeveloper.yml`) builds twice, commits a closed list of paths on `release/developer-` - with a dedicated GitHub application's token, tags in the same run, publishes, verifies the deployed bytes and opens the - pull request into `develop`; its permissions are declared job by job and checked by `ReleaseDeveloperWorkflow`. - `wf run pin` now fails (instead of warning) when the pinned URL is off the origin of `baseUrl`, redirects or lacks CORS, - and reads `previousBase` and `baseSince` for the migration waiver, which covers only versions before `baseSince`. `DeveloperPinConsistency` checks the states (a) to (c) and the - inconsistencies of ADR-021 decision 2. The compatibility table of `docs/DEVELOPER_ENVIRONMENT.md` is maintained by - `cmake/DeveloperCompatibility.cmake` and enforced on `v*` tags by `CheckReleaseVersion.cmake`. Environment 0.9.0 is the first - published by this workflow (tag `developer-v0.9.0`); the application and the tag rule are configured on the repository. -- `@webfront/services` package (#461, ADR-010 1.8, ADR-020 step 4). The browser side of the optional system services is - delivered outside the core, like `@webfront/react`: `js/services/` (a skeleton: an empty frozen `services` object and - `selfTest()`, declarations, license), `wf run services-package` for its deterministic archive and SHA-512, the same - bytes in the test registry, and a Jasmine spec that imports the installed archive. The archive packager is shared with - `react-package` (`js/developer/scripts/package-archive.mjs`) and `CheckPackage.cmake` verifies both. No core resource - is added. Publication to npm remains a separate maintainer action. -- Automation of a consumer's own application and discoverability (#501). `webfront::automation::enableAutomation(app, options)` - (`automation/Enable.hpp`) mounts the controller, the page binding and the private attachment endpoint on an application - that called `bootstrap("developer")`, so `webfront-agent --attach` drives its own window, with its own `cppFunction` - callbacks, under native grants; it registers nothing unless called, announces itself on stderr and offers a window title - marker. A shared session publishes a record without capability in a private per-user directory - (`%LOCALAPPDATA%\WebFront\sessions`, `~/.local/state/webfront/sessions`, `~/Library/Application Support/WebFront/sessions`), - removed on closure and dropped when its process is gone. `webfront-agent --list` prints these records and - `--print-mcp-config --attach [--name n]` prints a `.mcp.json`; `--sessions-dir` overrides the directory. - `webfront_add_agent([INSTALL] [DESTINATION dir])` checks and installs the launcher target for `add_subdirectory` and - `FetchContent` consumers. `wf check` without a `tsconfig.json` now also roots the project's own `.d.ts`, `.d.mts` and `.d.cts` files, so an ambient - `declare module '*.css'` applies. Environment 0.6.6 carries these changes; it is published (`developer-v0.6.6`) and pinned by `DeveloperReleaseData.hpp`, so `bootstrap("developer")` runs `call` and the notices. - The operation `call` (permission `call`, environment 0.6.6) invokes an application callback that the owner allow-listed by exact name - (`AutomationOptions::callbacks`, shown in the session, in `--list` and in the notice), with at most one string argument and a scalar or - short-list result; `webfront.*` names and anything outside the list are refused natively and audited (ADR-019 1.4). Once connected, the - window's terminal prints the grants and the attach path, `wf help` ends with an `Automation:` line, `wf create` writes an `AGENTS.md` - beside the starter's sources, and the errors asking for typescript or jasmine-core name the `install` operation. A browser regression - attaches `webfront-agent` to a real consumer application (`automation_consumer`, `AutomationConsumerWindow`). A new discovery directory is created private to the user; an existing one that others can read is refused, never modified. -- Writable storage confined to declared roots (#460, ADR-002 3.0, ADR-020 step 4). `fs::Storage` is the contract of a - writable storage: stable paginated listing (`list(dir, after, limit)`, at most 1000 entries a page), `status`, - `openRead`, `beginWrite(path, createNew | replace)` whose `commit()` renames a temporary file atomically (an uncommitted - writer removes it), `createDirectory`, `remove` and `rename` (never replacing). Failures are `fs::StorageError`, a - `BridgeError` with a `storage.*` code (`notFound`, `linkRefused`, `unsafeDirectory`, `rootMoved`, - `confinementViolated`…) whose message never names the root's host location. `fs::NativeStorage` resolves every path - from the opened root, one component at a time, without following links (`openat(O_NOFOLLOW)` on POSIX, `NtCreateFile` - relative to the parent handle with reparse points refused on Windows; `LinkPolicy::followInside` follows a relative - link that stays inside, POSIX only), checks on every operation that the declared location still designates the root - (`rootMoved`), refuses on POSIX a root, a directory or an ancestor another user could move, by its mode or, on macOS, - its extended ACL (`unsafeDirectory`; `/tmp` - accepted; `RootOptions::shared` lifts the check as a weakened confinement), holds the root and the traversed - directories without `FILE_SHARE_DELETE` on Windows, and detects a directory or a root moved by the same user before a - commit and after every operation (`confinementViolated`). On POSIX a move by the same user or the superuser after the - last check is not prevented. Names starting with `.wf-tmp-`, in any letter case, are reserved to temporary files. A replacing write creates its temporary file private (0600, in a private 0700 directory, without inherited ACL) and its commit gives the new file the group, permission bits and ACL of the file it then replaces (none if it has none), or refuses the replacement; running out of descriptors is not taken for a moved root. `fs::MemoryStorage` is the simulated storage of the tests. `fs::File` reads a - `fs::ByteSource`, the extension point for native handles. `safeRelativePath` now also refuses, on every platform, the - device names Windows reserves (`CON`, `NUL`, `COM1`…, with any extension) and names ending with a dot or a space. -- The bridge supports long strings, homogeneous lists of strings, tuples, typed arrays and bitsets, and typed errors - with application codes. A `cppFunction` callback can return a `webfront::ResultTask` or another sender and answer - when it completes; disconnecting the browser requests cancellation and drops late answers (#456–#459). -- `Server::drain()` and `shutdown()` no longer throw `std::logic_error` while a route handler or file read is still running on a - server worker; the gzip tests drain with the retrying variant, and a read lifetime the clock cannot represent is refused (#469). -- HTTP reads bound to the browser client (#469, ADR-020 rule 4). `app.addReadRoute(prefix, handler)` registers a route under - `/webfront/services/` whose URLs are grants: `ui.grantRead(route, path, ReadOptions)` returns `prefix + token + "/" + path` - (a 256-bit secret and an identifier, compared in constant time, reusable for byte ranges, revoked with the connection, - `app.revokeRead(url)` or an optional lifetime). After its handshake each connection receives a one-time secret through the - bridge (`wfBind.exchange`) and exchanges it by a same-origin `fetch` for a `wf-client--` cookie (`HttpOnly`, - `SameSite=Strict`, `Path=/webfront/services/`) naming its browser client; `webFront.bound` resolves once the cookie is - held, or rejects with an explicit error when the browser refuses it, and bound reads then answer `403` without a fallback. - The tabs of a profile that present the cookie share one client; concurrent exchanges of a blank profile create two - coexisting cookies; cookies of forgotten clients are erased at a later exchange; a client is forgotten with its last - connection. A token without the cookie of the owning connection's client, or after that connection closed, or after a - restart, is refused without saying whether it exists. A transferable grant (token alone) needs a lifetime of at most - 15 minutes. Every read answer carries `Cache-Control: no-store`, `Referrer-Policy: no-referrer`, - `Content-Security-Policy: sandbox; default-src 'none'`, `X-Content-Type-Options: nosniff` and - `Cross-Origin-Resource-Policy: same-origin`; types outside the closed passive list (raster images, audio, video, - `text/plain`) are attachments; HTML, XML, JavaScript and WebAssembly are announced as `application/octet-stream`; SVG keeps - its type but downloads on navigation. The server logs a route flagged secret without the rest of its path. The transport is - declared, never deduced: only the view of an embedded frontend is local; any other connection (the system browser - included) is refused a grant unless `WebFrontConfig::remoteFileTransport` is `loopbackAttested` (refused at construction - unless the server listens on a literal loopback address: `localhost` is a name the host resolves, so it is not accepted), `encryptedByDeployment` (a tunnel under http://, so the cookie is not `Secure`), `httpsByDeployment` (a TLS proxy: the cookie is `Secure`) or `plaintextAccepted`. - The shared Jasmine suite covers the binding (cookie required, neutralizing headers, hostile HTML and SVG in frames, SVG by - ``, `bound` rejecting on a failed connection); it passes under WKWebView. Qualification under CEF, WebView2, WebKitGTK - and the system browsers remains to be run in the corresponding CI jobs. - -- Embedded frontends: a connection proves it comes from the view (#453, ADR-020 rule 3). Each launch creates a random - 256-bit secret that the adapter gives to its own view at the start of every top-level document of the application's - origin (WKWebView `WKUserScript`, WebView2 `AddScriptToExecuteOnDocumentCreated`, WebKitGTK `WebKitUserScript`, CEF - extra browser information read by the renderer); `WebFront.js` takes it when it loads, removes it from the window and presents it in the handshake - (ADR-003, ADR-008). `UI::isEmbeddedView()` is true only for that connection and `UI::isLocalClient()` is the only - criterion of a local client: it is never deduced from the address. The system browser receives no secret and is never - local, unless the application sets `WebFrontConfig::trustLoopbackClients` (off by default, unsafe on a shared machine - or behind a proxy or tunnel). A frontend receives the proof through an optional - `open(address, port, file, policy, window, ViewLaunch)` overload. The handshake is accepted once per connection and a proof is copied only at the size of a secret; the - script handed to a view is refused (no association) for an origin or a secret that would need escaping; an IPv4 loopback - seen through a dual-stack socket counts as loopback. The injection script normalizes its expected origin with the browser's - URL parser, so expanded IPv6 and IPv6 with embedded IPv4 notation match `location.origin`. The association does not protect - against a script admitted into the view. WebView2, WebKitGTK and CEF code is covered by their own CI jobs; WKWebView is also tested here. - -- HTTP server: dynamic routes (#454, ADR-020 prerequisite). `addRoute(prefix, handler)` on the application answers `GET` and - `HEAD` under an absolute prefix with a reply produced at run time (`http::RouteReply`: status, headers, exact or unknown - length, and a body read chunk by chunk). The handler and the reads run on a worker thread of the server, one chunk of - `emissionBufferSize` bytes at a time with back-pressure, so memory does not depend on the body's size; a closing connection - or a server stop ends the response. The route precedes the file providers and cannot cover `WebFront.js`; overlapping - prefixes are refused at registration; other methods get 405. Headers that could split the response, or that the server - owns (`Content-Length`, `Connection`, `Transfer-Encoding`), turn into a 500. Unencoded files of known size - (`fs::File::knownSize()`) are streamed the same way, so serving a large file no longer loads it into memory; encoded - files are still read whole. The binding to a connection (#469) follows; `Range` is described below (#455). - -- HTTP server: byte ranges (#455, ADR-020 prerequisite). Unencoded files of known size are served by `Range` (`bytes=a-b`, - `a-`, `-n`): `206` with `Content-Range` and only the selected bytes read, `416` with `bytes */size` for a range that - starts past the end, and `Accept-Ranges: bytes`. Several ranges, a unit other than - `bytes` and malformed ranges are ignored (`200`, whole file), as is any `Range` on `HEAD`; encoded or decoded responses say `Accept-Ranges: none`. - `If-Range` compares a strong `ETag` that a provider gives with `fs::File::setEntityTag`; nothing is derived from a path, - a size or a time, so native and embedded files have none and a conditioned range is answered in full. `fs::File` - gains `seek`, `entityTag` and `setEntityTag`. Dynamic routes serve a file by ranges with `http::fileReply`, or `http::range::select`. The binding - to a connection (#469) follows. - -- Embedded frontends: `alert`, `confirm`, `prompt` and `beforeunload` (`beforeunload` is not handled under WKWebView, see `docs/FRONTENDS.md`; #452, ADR-020 rule 6). WKWebView implements the three - `WKUIDelegate` panel methods (an `NSAlert` sheet of the window; without them these calls did nothing); WebKitGTK, CEF and - WebView2 keep their engine's dialogs. A shared test injection (`frontend/ScriptDialogs.hpp`) answers the dialogs in each - frontend, and closing the window with a box open dismisses it. See `docs/FRONTENDS.md` for the engine-by-engine coverage. - -- Embedded frontends: `` and downloads (#451, ADR-020 rule 6). WebKitGTK saves downloads to the user's - download folder (name reduced to its last component, never overwritten); WKWebView gets `runOpenPanelWithParameters` and - `WKDownload`; CEF and WebView2 use the engine's own handling. A `blob:` URL of an admitted origin - now passes the navigation policy, so a generated Blob can be downloaded. Test injection points answer the chooser and the - download without a dialog (`docs/FRONTENDS.md`). On Windows, WebView2 tests exercise chooser selection and cancellation - through DevTools and verify completed downloads on disk; the native dialog UI itself remains unqualified. - WKWebView stages downloads privately and preserves a destination created during transfer; failed downloads remove their - incomplete files. Automatic destination selection cancels instead of reusing - an occupied path when all 10,000 candidate names are taken. - -- Developer environment: the distribution is served from `https://dist.webfront.fr/` (#478, ADR-021). The sources advance to 0.6.5, the - first version published under that address; `site.mjs` writes the `CNAME` file of the Pages branch and `wf run pin` - checks the pinned archive where it is served now. Libraries and environments up to 0.6.4 pin the former - `ambroise-leclerc.github.io/WebFront/` address, which redirects to the new domain without the CORS headers a browser - needs: their developer bootstrap no longer starts and they must be rebuilt with a pin on `dist.webfront.fr`. 0.6.5 is - published and pinned, and the test bootstrap moves to it. - -## 0.8.0 - 2026-11-01 - -- Run authorized native programs from the specs of `webfront_add_jasmine_test` (#445): `PROGRAMS` is the owner's grant and - `webFrontHost.run({program, args, cwd, env, inheritEnv, timeoutMs, maxOutputBytes, signal})` starts a listed program - directly, without a shell, with literal arguments, an explicit environment, bounded time and output, and a structured result - (`exited`, `signaled`, `timeout`, `cancelled`, `launchFailed`, stdout/stderr and truncation flags). The program and its - process group (POSIX) or job object (Windows) are killed at the timeout, on cancellation and when the program ends. - `makeTemp`/`withTemp`, `writeFile` and `readFile` give private temporary spaces that are removed after success, failure and - cancellation. Without `PROGRAMS` every call rejects; `webfront::testing::runProcess` and `HostSession` are the C++ API. The wf - scripts keep no process capability. The browser specs are validated on Linux; Windows and macOS run the unit tests of the runner in CI. See `docs/CONSUMER_TESTING.md` for - the XML-to-JSON recipe. - -- Automation can set a project up end to end (#466): `init`, `create`, `install`, `restore` and `embed` join the contract of - `webfront-agent`, each behind its own `--allow` grant and with plain-name or project-relative arguments (no options, no - traversal). `install` takes one package from the configured registry or installs the locked graph; `embed` takes a manifest - provider, or an entry with an output header. See `docs/AUTOMATION.md`. Developer environment 0.6.4 is published and pinned; - the separate test bootstrap remains on 0.6.3. Granting one of these operations to an older environment now fails at startup with a bootstrap error naming - the operation, and `embed` is documented as replacing its output header. `create` now finds the pinned starters (the connection reads them from the - environment manifest) and the launcher serves `-starter.tgz` from beside the environment archive; an end-to-end case - creates, initializes, installs and embeds a project. -- Declare the embedded engine without consumer-side macros (#467): `webfront::embeddedFrontendAvailable` (`constexpr bool`, true - when a native web view or CEF is compiled in) and `webfront::EmbeddedWebFront` (the application type with the native web view, - or with CEF when only CEF is built) exist in every configuration; constructing `EmbeddedWebFront` throws - `std::runtime_error` when the build has no engine. See `docs/FRONTENDS.md`. -- Capture the web view as PNG images (#468): `webFrontCapture.screenshot(name)` and `webFrontCapture.record(name, {seconds, - framesPerSecond})` (also `startRecording`/`stopRecording`) in the specs of `webfront_add_jasmine_test` write - `webfront-jasmine//captures/.png` and numbered `/0001.png`... for an external encoder such as ffmpeg. - `webfront::frontend::capturePng()` and `webfront::testing::CaptureStore` are the C++ API. WebKitGTK, WKWebView, WebView2 and CEF - implement it. The bridge callbacks start the work on a worker - thread and the page polls, so a capture never blocks the server thread. See `docs/CONSUMER_TESTING.md`. - -## 0.7.0 - 2026-10-31 - -- Cut pull-request CI time (#435): the desktop jobs build with `--parallel 4` and compile the 13 heavy unit-test files four - to a file (`WEBFRONT_TEST_UNITY_BATCH`; the default build keeps one object per file, and `JsFunctionSenderTests.cpp`, - `CommandsTests.cpp`, `FrontendContractTests.cpp` and `BroadcastTests.cpp` name their helpers so that they can share one). - A pull request into `develop` no longer builds the examples or runs the MSVC code analysis (`WEBFRONT_MSVC_ANALYZE`, - default ON), nor the builds that prove the self-built environment reproducible unless it changes their inputs - (`WEBFRONT_TEST_REPRODUCIBILITY`, default ON); the weekly run, pull requests into and pushes to `master` do all three. - `JourneyEmbeddedBuild` and `LifeEmbeddedBuild` no longer hold the `webfront_port_9002` lock while they compile. - `DeveloperBrowserIntegration` is cut into five parts (`DeveloperBrowserIntegration`, `-scripts`, `-typescript`, - `-jasmine`, `-terminal`) that run in parallel from their own projects on ephemeral ports. `RunWithDeadline.sh` returns - when its command does instead of at the deadline, which took 30 s from each of the six `ConsumerJasmine-*` cases under - dash, and gives the command its own process group (`setsid`, or a walk of its descendants) where the shell has no job - control. `docs/BUILD_TIME_STUDY.md` holds the measurements and the decisions. - The developer test parts are serialized for CEF because they share its default profile with other native browser tests. - -- Include `developer_integration` in the documented Linux CEF build commands (#434), preparing the developer journey - and its dependent Life tests. Check the browser targets in both guides and CI with `NewcomerDocsMatchExamples`. - -- **Breaking:** WebFront's test, fuzzing, coverage and sanitizer CMake options now require the `WEBFRONT_` prefix - (#412). For example, use `WEBFRONT_ENABLE_TESTING` instead of `ENABLE_TESTING`. Generic `ENABLE_*` variables and - old cache entries no longer configure WebFront, either at the top level or as a subproject; set the prefixed options - explicitly. This also prevents a parent project's own options from enabling WebFront tests or instrumentation. - -- Remove the Windows agent's native profile after a forced exit (#439): when WebView2 processes still held the profile - at the end of the 2 s in-process retry, the agent exited and left it behind, so `AutomationCliWatchdog` failed - intermittently on loaded runners. A detached agent process now retries removal for about 20 s, including for Unicode - paths and paths containing shell metacharacters. The watchdog test waits for the cleanup window, and its second CLI - invocation has a 45 s limit instead of 15 s. - -## 0.6.0 - 2026-10-31 - -- Build the React store tests in Release with GCC 16 (#429): at -O2 and above, GCC reported the moved-from path of - `react::Store::flush()`, where the check throws first, as a call on a null pointer (`-Werror=nonnull`), and the unit - tests did not compile. The store now reaches its state through a checked reference. As GCC only runs this analysis - when it optimizes, GCC builds also compile `ReactStoreTests.cpp` at -O3 (`react_store_optimized`), so the Debug CI - job sees it too. - -- Reject a stale `UI` after its connection identifier is reused (#428): each connection gets a 64-bit - generation, never reused, kept in the application next to its link. `UI`, `JsFunction` and - `JsFunctionSender` carry it with the 16-bit identifier, so a value kept after its connection closed finds no - link even once a later browser receives the same `id()`: calls are dropped, typed calls fail, - `addScript` throws `ConnectionError`, `pendingWrites()` is 0, and the value equals no later connection's. - `operator==` compares application, identifier and generation. Removing kept values in `subscribeUIClosed` - becomes a recommendation, not a safety requirement. The generation never crosses the wire: no change to the - binary format or `WebFront.js`. The public constructors of `UI`, `JsFunction` and `JsFunctionSender` take the - generation as an extra argument, so code that builds one by hand no longer compiles: use the `UI` that - `onUIStarted`, `subscribeUIStarted` or a callback hands over. - -- Add `app.broadcast(name, options)(...)` and `app.forEachUI(function)` (#401): calls to every browser - whose `onUIStarted` handlers have returned, from any thread, with no table of browsers kept by the - application. A broadcast made while those handlers run follows what they sent. Each call is encoded - once into a frame shared by every browser. `BroadcastOptions::maxPendingWrites` holds a call back - for a browser that has that many calls of the function waiting, and keeps only the latest for it, - in the browser's connection; such a held call may follow other functions' later calls. `forEachUI` - skips a starting browser, so states go through `broadcast`. Document the threads of callbacks and - browser calls ([threads](ASYNC_EXECUTION.md#threads)). No wire format change. - -- Stabilise the desktop-native tier (#416): before removing its temporary WebView2 profile, the automation owner - waits up to 5 s for the browser processes it launched to exit and ends those still running (at once after a forced - exit, which also keeps the status of an exit that completes meanwhile), then retries files pending deletion for 2 s. - The watchdog tests check that a forced exit removes the profile, the automation failure messages report the observed - run state, exit status and owner log, and `NativeAutodetectReconfiguration` has a 180 s timeout. On Linux, the - automation agent gives the CEF helpers descending from it (the processes running its own executable, recognized by - their command name when the sandbox hides it) the same grace, then kills them through pidfds, removes the profile, - and after a forced exit leaves a last removal to a shell in its own session that waits for its exit (a minute at - most), since the CEF browser inside the agent writes into the profile until then, and repeats it for 2 s against a - helper relaunched meanwhile; the tests wait up to 10 s for that removal and keep the - watchdog profile in a short system temporary path. The deadline check of the Jasmine runner waits up to 5 s for a - killed orphan to exit and treats one reaped while it reads its state as gone, reading that state with `ps` where - there is no `/proc` (macOS). - -- Show the `wf` commands of the developer browser test in its window (#415): `DeveloperBrowserIntegration` shows, in - place of its terminal, each command it runs with its outcome and duration, labelling the timeouts and cancellations - the specs cause. The trace comes from the specs only; the published environment is unchanged. `docs/TEST_TIERS.md` - explains how to follow a test live. - -- Make `BasicUI` (`UI`) an assignable value type (#400): it holds a pointer to the application instead of a - reference, so it is copy- and move-assignable and usable in `std::vector` with `std::erase_if` and in - `std::optional`. It has no default constructor, so it does not satisfy `std::regular`. Two values compare equal - when they belong to the same application and have the same `id()`. The lifetime contract is unchanged: a `UI` is - valid while its application exists and must not be used, compared included, after it is destroyed. A value only - identifies its connection until that connection closes: once the identifier is reused, a value kept after the close - reaches the later browser and equals its value, so applications remove kept values in `subscribeUIClosed` (#428 - tracks rejecting such stale values). `BasicWF` now declares itself non-copyable and non-movable, which the pointer - requires. The automation binding and the Jasmine session identify their browser by this equality, and assign it - instead of re-emplacing an optional. `docs/ASYNC_EXECUTION.md` describes the value semantics. - -- Add awaitable DOM events (#384): `co_await node.next(name, options)` completes with the value of - the element's next event, for sequential dialogs and wizards. Starting the sender subscribes with - the flags declared then; the event unsubscribes. It completes stopped through the task's stop token, - `unlisten()`, node removal or revocation, rejection, disconnection and shutdown; every end of a wait - but a rejection, which closes the document until the page reloads, removes its browser subscription - and flags, also after a stop from another thread. One callback or - wait per element and event. No wire format change. - -- Add optional [type descriptors and generated forms](FORMS.md) (#383, ADR-018 criterion 5): - `forms::Description` (name, label, kind, bounds, choices, accessors) written by hand in C++23, - `forms::form()` and `forms::inspector()` built in a DOM document from them, and - `forms::typescriptDeclaration()`, whose output the developer journey type-checks with `wf check`. - The optional `forms::describe()` produces the same descriptors by C++26 reflection from - `Label`/`Range` annotations; its tests build with GCC 16 and are required on the Linux CI job - (`WEBFRONT_REQUIRE_REFLECTION_TESTS`). The library stays C++23. - -- Warn at the end of a consumer's configuration, with GCC 16, about each target linking - `WebFront::WebFront` that CMake scans for C++ modules (`-fmodules-ts`), which makes GCC crash inside - stdexec (#399). Add `webfront_disable_module_scan(target...)`; the global workaround is - `set(CMAKE_CXX_SCAN_FOR_MODULES OFF)`. GCC 16.1 and 16.2 both crash, GCC 13.4 and 15.2 do not - (reported upstream as GCC bug 128318). The reduced case needs no stdexec: - `extern const int t; inline constexpr int t = 0;` compiled with `g++ -std=gnu++23 -fmodules-ts` - crashes in `transfer_defining_module`. stdexec declares `forwarding_query` this way. - -- Add `frontend::nativeWebViewAvailable` and `frontend::NativeOrBrowserFrontend` (#398): a native - window when the platform engine is compiled in and a session exists, the system browser otherwise, - with the reason printed once and available from `fallbackReason()`. An application needs neither a - `WEBFRONT_EMBED_*` macro nor a second application type. A frontend may define an optional - `static bool closeServerAfterOpen()` to override its `action` at run time. - -- Accept ADR-019 for the delivered local automation contract, shared window and native grants, - with consumer Jasmine coverage, the five-model qualification and the final PR #407 CI evidence. - Record the remaining distribution publication gate and deferred remote/browser transports. -- Native-window detection is enabled by default for add_subdirectory/CPM consumers (#397). - On MSVC this downloads the pinned WebView2 SDK at configure time, including when no target - calls the helper; disable detection explicitly for offline or browser-only builds. - A parent's own `ENABLE_TESTING`/`ENABLE_FUZZING` do not disable it. Frontend metadata and detected - options are accessible from parent and sibling directories. - `webfront_use_native_window(target)` applies native setup and defines `WEBFRONT_NATIVE_WINDOW` - when available, with a configuration notice (printed once) for the browser fallback otherwise. - -- Let automation use an idle `wf dev` watcher started through nested `wf run` aliases, while - retaining exclusive compilation/publication and module-script execution. Accept manifest entry - labels such as `app:debug` and `app..debug` in native build/preview requests. - -- Keep automation CLI bootstrap failures at exit 70 regardless of transport completion order, - while preserving native deadline and signal exit statuses. - -- Record the [local-model MCP qualification](validation/automation-models-2026-10-29.md) on five - installed models through LM Studio: 30/30 final sources pass host verification, while 29/30 - model conversations observe successful check/test results. Retain per-task data, measured token - costs, the incomplete Flint case and the distinction from the built-in Ollama benchmark. - -- Keep mandatory browser coverage enabled without silently falling back when xvfb is missing; - restrict optional display gating to automation. Retry transient native socket errors within the - deadline, accept authenticated sequence gaps while refusing replay, recover stalled preview - navigation, drain Windows stdin on pipe closure, preserve Unicode bootstrap failures and keep - the bounded audit focused on start-authorization decisions. Share native platform declarations. - -- Split functional MCP coverage from short native watchdog process regressions, with private ports - and profiles and a lock limited to spinning renderers. Bound attachment startup IO by its remaining - deadline and preserve diagnostic paths through the producer's 256-character limit. - -- Select the automation window with a single-use launcher URL claim instead of connection order, - create profiles with private permissions atomically, keep queued output separate from previous - runs, and complete unexpected busy runner starts as errors. Document strict counter failure and - the Windows endpoint reader's reliance on its directory ACL. - -- Harden developer automation callbacks with per-message HMAC-SHA-256 and replay protection, - revoke the attachment listener and endpoint on shutdown/watchdog exit, preserve final output - summaries and invalidate old preview actions before every navigation. Document the actual - frontend storage limits and add a maintained optional official MCP SDK regression. - -- The embedded native windows take their title and initial size from `WebFrontConfig::window` - (`WindowOptions`, #396). The default title is the executable's name (or "WebFront" if it cannot be determined) instead of - "WebFront Application"/"WebFront". The WebKitGTK lifecycle suite reads the native title back; a unit test - covers the dispatch to the frontend. Following `document.title` and an icon remain future work. - -- Consumer Jasmine/CTest integration (#402): opt-in instrumentation runs classic JavaScript - specs in an application's own page with its existing DOM and callbacks. The public CMake - helper provisions verified Jasmine, passes application arguments and checks a fresh JSON - report. An external process timeout bounds even a synchronously blocked renderer and, on POSIX, - kills its whole process group. `JasmineTest` is inert unless the target defines - `WEBFRONT_JASMINE_TESTING`; a spec file that fails to load fails the run. - -- The initial ADR-019 proposal (#404, now accepted above) compared developer automation paths: one versioned - operation contract (JSON Schema) projected onto the window, a public CLI with agent instructions and an - optional local MCP stdio adapter, with a threat model, local-model requirements and acceptance criteria. - The proposal itself introduced no server, driver or API; #402 remained an independent deliverable. - -- Optional React adapter (#382): an installable `@webfront/react` package with cached - `useSyncExternalStore` snapshots and empty `Island` components that tolerate StrictMode - effect replay. `webfront::react::Store` coalesces the last snapshot per 1 ms server cycle - without changing the wire format or core assets. A Game of Life variant constructs its - simulation panel in C++ inside React. Package assembly, wf installation, declarations, - batching and island lifecycle have regression coverage. Explicit flush failures retain the - pending snapshot; automatic error callbacks are contained and logged. Moved-from - store wrappers reject operations explicitly. Self-capturing error callbacks are released on - close and automatic failure; subscriber and island-release exceptions are logged and isolated. - The Life variant gates - cell edits until startup succeeds and bounds island readiness. Test installation uses the exact - archive bytes, with file-list and SHA-512 checks. Registry publication stays explicit. - -- Optional native developer automation (#403): `webfront-agent` drives its developer window - through stdio MCP or a JSON CLI, with native operation grants, asynchronous run IDs, bounded - structured diagnostics/results, preview inspection/actions, cooperative cancellation and - an external renderer deadline. Human commands share dispatch and arbitrate agent operations. - No MCP network endpoint or arbitrary callback/shell export is added. A compatible rebuilt - environment is required until a release is published and pinned. +## [1.0.0] - 2026-11-17 -- License WebFront under Apache-2.0 OR CECILL-B, at the recipient's option. - Include both full license texts (CeCILL-B in French and English), document - contribution terms and carry the license into newly built developer and - Life starter archives. Third-party components retain their own licenses. - -- Per-browser DOM documents (#381): `ui.document()` shares node identities, name interning, - writes grouped on a 1 ms server cadence, event callbacks with declared browser flags, and - explicit grouped read senders with local cancellation. The fallback page lends `root`; - custom pages opt in through `dom.connect()`. Revocation, disconnection and shutdown - invalidate handles. Reject element-only operations on text nodes/islands locally; enforce - the connection thread before document lookup and refuse document creation during closure. - DOM connection attempts retry unacknowledged revocations after partial success, retaining - the acknowledged handshake; server readiness is idempotent for a lost acknowledgement. - Revocation notification failures are logged, and missing network timers report an explicit error. - Empty event callbacks fail locally; validity predicates are - nonthrowing and return false off the document thread. Document the single-thread context - requirement and the coordinated handoff needed before page-initiated island unmounts. - Missing form values are empty. Event values over 65,535 UTF-8 bytes are not delivered to C++ - or truncated; their rejected delivery is logged in the browser console. - The fallback distinguishes bridge failures from DOM initialization failures. Batch-id exhaustion - notifies `onError`, and insert-before-self follows native no-op semantics. The server-thread - and rejection/reload contracts are in `docs/DOM.md`. - -- DOM batch protocol (#380): bounded command 5, canonical uint32 LEB128 and UTF-8 codec, - interned names and correlated rejection callbacks. The optional embedded `webfront-dom.mjs` - validates the evolving tree before applying mutations, protects page-owned islands, and - rejects executable content and normalized unsafe URLs. Catch2 and the shared Jasmine - suite cover encoding boundaries, hostile batches and real WebSocket dispatch. ADR-003 - specifies the wire contract; ADR-016 adds the module within the existing 150 KiB budget. - Follow-up: validate against per-node and per-child-set deltas, cap retained UTF-8 name bytes at - 1 MiB per interpreter, and document the trusted-content model, event values and recovery after - residual exceptions. Real WebSocket tests cover events and listener cleanup; a C++ regression - covers sending through a lost UI link. The manual DOM benchmark is described in embedded assets. - Reserve batch id zero for uncorrelated rejections and require explicit nonzero C++ ids. Index - subscriptions by node and revoke islands by subtree traversal. Both codecs limit each batch to - 131,072 operations; C++ reserves the counted operation total and rejects unused operands. - Event integration checks count identities/values independently of arrival order. - Reject `PROPERTY value` on `output` before applying a batch, preserving tracked children; - update output text with `SET_TEXT`. Use checked event-count indexing for MSVC analysis. - -- The single-command test driver can set `--command-timeout` after browser/bootstrap startup, - within its unchanged overall `--timeout` deadline (#376). The watchdog regression deliberately - delays bootstrap beyond its command limit and requires the command's start marker before accepting - status 71; slow native browser startup can no longer satisfy the wrong timeout condition. - -- Repository cleanup (#376): consolidate the gzip benchmark and differential-validation commands - into [HTTP assets](HTTP_ASSETS.md#manual-benchmarks-and-differential-validation); remove - `GZIP_CACHE_MEASUREMENTS.md`, `GZIP_DECODER_MEASUREMENTS.md` and the one-off profiles under - `docs/test-performance/`. The last revision containing these reports is - [cce1927](https://github.com/ambroise-leclerc/WebFront/tree/cce1927ec952cb5d80b7bb130e9eaddbd1744885/docs); - new CI reports are workflow artifacts. - `PROJECT_STATUS.md` now describes supported paths, contracts and outstanding limitations; - completed migration/qualification records remain in Git and this changelog. Remove the unreferenced - Hello World and retired Signal Studio screenshots. Active build, test, publication and animation - generation tools, plus the measurement evidence cited by proposed ADRs, are retained. - -- Tests are organized in tiers by CTest label: `fast` (unit tests, about one second), the standard tier and - `portability` (the consumer project). CI runs the fast tier first, excludes `portability` from pull requests into - `develop`, and runs the advanced tier (three suite repetitions, a portability matrix, sanitizers, fuzzers, CEF) weekly - and on pull requests into `master`. `RunTestSuite.cmake` accepts `LABEL_EXCLUDE`. See [TEST_TIERS](TEST_TIERS.md) (#388). - -- Compatible `wf` regression commands share browser sessions, with fresh command realms and individual CTest reports - (#388). The suite runner reuses one Xvfb display on Linux, supports bounded `PARALLEL`, and records detailed phase/spec - timings. Independent driver groups use OS-assigned ports; `WebFrontConfig::port = "0"` and `app.port()` expose this - with TCPStdnet. Native `WebView2Options::visible` / `WKWebViewOptions::visible` default to true and allow quiet tests. - Windows/macOS CI no longer wait for the Linux image, extended jobs use sccache, fuzzers have bounded concurrency, - and lcov verifies its fast JSON backend. See [TEST_PERFORMANCE](TEST_PERFORMANCE.md). Local #388 measurements on Linux/GCC 16 - Release/WebKitGTK (two build workers, four CTest workers) went from 172.43 s at baseline - [da0297f](https://github.com/ambroise-leclerc/WebFront/commit/da0297ff235642ccbe665a78e42873da9cde9c98) - (365 cases/97 specs, one pass) to a 93.41 s median (378 cases/97 specs, three passes), a 45.8% - reduction. These are local observations on a busy shared workstation, not a cross-platform guarantee; - [measurement details](https://github.com/ambroise-leclerc/WebFront/blob/cce1927ec952cb5d80b7bb130e9eaddbd1744885/docs/TEST_PERFORMANCE.md#measurements) and - [raw profiles](https://github.com/ambroise-leclerc/WebFront/tree/cce1927ec952cb5d80b7bb130e9eaddbd1744885/docs/test-performance) - are preserved at cce1927. - -- Accepted stdnet connections enable `TCP_NODELAY`, including after WebSocket upgrade (#379). - This removes the Nagle/delayed-ACK interaction that could delay a callback's return - after it sent a browser message. A real-socket regression checks the option directly; - the shared browser suite checks a callback sending a message before returning a value. - -- The Linux desktop CI job runs in a prebuilt toolchain image (GCC 16, WebKitGTK, lcov, Xvfb; `.github/docker/linux-ci.Dockerfile`) - published to ghcr.io and tagged with the hash of its Dockerfile, instead of installing those packages from an Ubuntu mirror - on every run. Windows, macOS and the extended jobs are unchanged. - -- HTTP status-line buffers belong to each response until its asynchronous send ends (#376). - Ordinary responses announce `Connection: close`, matching the existing one-request-per-socket - server behavior; WebSocket upgrades remain open. Unit and real-browser regressions cover - pending response independence, closure headers and concurrent success/error responses. -- Developer specs report each started spec to the native driver; self-build watchdogs expire - before CTest so a stalled page leaves useful output and a nonzero status (#376). -- CI stability runs repeat the complete CTest fixture graph three times, retaining - a separate JUnit report per pass and stopping on the first failure (#376). - Reruns remove old numbered reports before starting, and optional spec-progress - diagnostics cannot fail specs when the driver callback is absent or disconnected. - Repeating each stateful journey step in isolation tried to initialize an already - initialized project; an offline CMake regression demonstrates the failure and - checks whole-suite repetition and failure propagation. -- Isolate the GET/HEAD gzip failure tests from the one-job admission limit (#376): - receiving a response does not imply that its server-side lease has been released. - Browser integration reports its current phase, and failed macOS CI jobs retain WebKit - system logs and crash reports alongside CTest diagnostics. -- Remove completed migration/audit notes and obsolete timing narratives, update their - references, and retain historical migration links at their original Git revision (#376). - Replace the unused 2,698-line Doxyfile template with CMake's generated configuration; - both documentation targets generate the public headers with the project version, - and Graphviz is optional. Active build, test and publication scripts remain in use. -- ADR-018 (Proposed, #378) studies DOM access from C++: a batched, validated mutation stream into page-lent islands, React and - other UI libraries kept as owners of their DOM (external store, islands), optional C++26 reflection for generated - interfaces. Its measurements come from throwaway prototypes, kept out of the repository (commit `ef2bb25` of PR #385). - They also found a 40 ms delay on callbacks that call `ui.jsFunction` before returning - (`TCP_NODELAY` is not set); the fix is tracked by #379. - -## 0.5.0 - 2026-10-26 - -- Gzip identity fallback reuses a bounded validated-representation cache for GET and HEAD (#281). - Cold decoding uses buffered bit reads and a small Huffman lookup (#282), with unchanged - allocation behavior, strict stream validation and output budgets. Release benchmarks and - test-only zlib differential/sanitizer validation are recorded in [HTTP asset validation](HTTP_ASSETS.md#manual-benchmarks-and-differential-validation). - -- `WebFrontLifeDeveloper` starts without argument on `./life-project` (created when missing, reused untouched otherwise) and the - pinned environment; the explicit ` [ ]` form remains. At configuration, the - native window engine of the platform is enabled automatically when its dependencies are found (top-level builds with examples, - without `ENABLE_TESTING`; `-DWEBFRONT_AUTODETECT_NATIVE=OFF` disables it, an explicit `WEBFRONT_EMBED_*` value always wins). - A missing engine does not fail the configuration: CMake explains how to install it and the Life examples are built for the default browser instead. The README Game of Life walkthrough builds with `mkdir build`, `cd build`, - `cmake ..` and `cmake --build .` (#366). The developer terminal drops its redundant banner line; the sources advance to environment 0.6.3 (published as 0.6.3; the test bootstrap pin moves to it in #403). - Automatic engine values stay outside the cache so an explicit choice equal to the previous detection is still respected; - removing an explicit engine cache entry resumes detection. Platforms without a registered engine configure the browser fallback. - -- Cold gzip identity fallback uses one server-owned worker with bounded jobs, consumers and - buffer capacities (#283). The new compressed-input cap defaults to 4 MiB and returns 500 - before cache lookup when exceeded, including HEAD; configure `maxGzipEncodedAssetSize` - for larger assets. Queue/memory saturation and preparation allocation failures return 503. - Cancelled work skipped before decoding and decoder exceptions cannot poison later consumers. -- Transport benchmarks are manual targets, excluded from CI, CTest and default builds (#283). - Short direct-channel correctness contracts remain in CTest for WebKitGTK, WebView2 and WKWebView. - -- Remove the local SSH CI orchestrator, container definitions, native session workers and matrix drift checks. - The GitHub-hosted workflows remain the CI execution path. - -- The allocation-counting regression is omitted from ThreadSanitizer builds, whose C++ runtime - defines the same global `new`/`delete` operators; ordinary and ASan/UBSan builds retain it. macOS adds - `WKWebViewTransportBenchmark` (HTML bridge, native strings, `callAsyncJavaScript` and base64 bytes) and separate native - API contract tests. ADR-017 records the measurements and the public Cocoa API constraints on a future direct transport. - -- Linux transport performance now has a dedicated Release CI lane without coverage, repeated three times with retained - JSON, environment and CTest reports; the Debug/coverage desktop lane stays in place. ADR-017 distinguishes mandatory HTML - availability from the selected default transport and qualifies mobile network rules by OS version. - -- ADR-017 (Proposed, #363) prepares direct access to embedded frontends (native resource schemes and message channels) for - future Android, iOS and other mobile frontends, while HTTP/WebSocket stays the normative path of every frontend and of future - microcontroller targets. The binary format of ADR-003 is carried unchanged; no API or wire change is made. The new - `WebKitGTKTransportBenchmark` CTest case (labels `web-integration` and `performance`) compares the bridge with WebKitGTK's - message handlers and `evaluate_javascript` in one window; it fails on a wrong echo, never on a timing, and writes a JSON report. - `WebView2TransportBenchmark` does the same on Windows with `WebMessageReceived`, `ExecuteScript` and a shared buffer - (`ICoreWebView2SharedBuffer`): WebView2 string messages are slower than the HTML bridge from 32 KiB and for C++ to JS, the - shared buffer is 2 to 6 times faster. The figures leave out the codec and the thread hop a real transport adds, so they - overstate the gain of a direct path. The benchmark exposed two per-message costs of the bridge, fixed with regression tests: - `Messages.hpp` wrote to the standard output for every encoded parameter, and `Frame::addBuffer` formatted a hex dump of - every buffer before the log level was tested. - -- The README animation draws the C++ application inside the image, beside the WebFront window (#359): it is no longer cropped by the table column on narrow screens and in the GitHub app, and weighs 0.4 MB instead of 1.2 MB. The code stays in the README as text, in a collapsed block; `docs/tools/render-life-bootstrap.py` reads it from there. - -- The manifest and the lock of the repository move to `js/developer/` (#354): the driver and the CI select them with `--manifest-dir js/developer`, and the closed list of the root loses two entries (9 left). - -- The test bootstrap environment is the published 0.6.2 (#354), which installs the archives of `@types` packages and honours a manifest directory; the README walkthrough no longer needs a local archive for `wf check`. - -- The manifest and the lock of a project may live in a directory of the project (#354): `DeveloperBootstrapOptions::manifestDirectory` (validated, passed in the bootstrap configuration only when set) and `webfront-wf --manifest-dir`; the environment derives `manifestPath` and `lockPath` from it, and a script still never writes them. Paths inside the manifest stay relative to the project root. Environment 0.6.2, not yet published; an earlier environment ignores the option. - -- Simpler repository root (#352): `.devcontainer/` is removed (nothing used it, and its Dockerfile duplicated the toolchain of the CI by hand); `.gitattributes` drops its generic Visual Studio and document rules (177 to 69 lines, the attributes of every tracked file are unchanged); `.clang-tidy` becomes `cmake/clang-tidy.yaml`, passed to clang-tidy by `cmake/StaticAnalyzers.cmake`, and `.clang-format` moves next to the C++ it formats, with a copy in `include/webfront/`, `test/` and `examples/` so that their styles may diverge; the layout guard records why every other root entry stays. - -- Documentation of the standalone developer environment (#317, epic #303): the README walkthrough uses `wf create`, `init`, `install`, `dev`, `check`, `test` and `embed` on the pinned environment; `DEVELOPER_ENVIRONMENT.md` opens with the commands, the direct statement of its limits (no sandbox, browser packages only, installation scripts not run) and the maintenance of TypeScript through `wf check`; the 0.4.0 "prepared, not published" text is removed; PROJECT_STATUS starts with the current state; ADR-016 is 1.5. - -- Remove the retired PI starter from source distributions and `wf create`; Life remains the maintained React/C++ starter. - Preserve real-time fallbacks in scoped test clocks, release preparation cancellation before the test frame runs, - and retain independent reproducibility, bootstrap-refresh and packaged permission checks. The attribution audit - ignores user signature/log display settings. +WebFront 1.0 ships with developer environment 1.0.0. This release adds host-loop integration, developer tools and +platform qualification; see the breaking changes below when upgrading. + +### Breaking +- WebKitGTK defaults to development mode with its sandbox disabled; packaged applications must select `WEBFRONT_DISTRIBUTION=ON` or `webfront_use_distribution(target)` to require it, independently of Debug/Release (#596, `docs/WEBKITGTK.md`). +- Reserve more command names for the terminal: an application command named `ls`, `cat`, `tree`, `mounts`, `cd`, `pwd`, `cp`, `mv`, `rm`, `mkdir`, `rmdir`, `touch`, `edit`, `find`, `grep`, `head`, `tail`, `less`, `stat`, `du` or `df` is now refused by `webfront::Commands::add` and must be renamed (#575, ADR-023). + +### Added +- Capture numbered PNG sequences with a fixed simulation clock using `WebFrontHostLoop --capture-frames`; `--capture-demo` hides statistics and switches materials continuously. Illustrate the bilingual README with the CUDA checkered ball followed by illuminated glass (#602, `docs/HOST_LOOP_EXAMPLE.md`). + +- Qualify real X11 Canvas/WebGL presentation on NVIDIA EGL, the GNOME file portal and fullscreen Life React on Orin Nano Super; retain captures, an EGL diagnostic and the limits of nested Wayland testing (#528, `docs/JETSON.md`). +- Add an isolated, low-priority Jetson Orin hardware workflow with persistent caches, complete CEF-off tests, WebKitGTK integration, required CUDA regression and workflow security checks (#529, `docs/JETSON_RUNNER.md`). +- Turn the `WebFrontHostLoop` example into a ray-traced Boing Ball computed by the host's own loop on the CPU or with an optional CUDA unit, shown full-window by an embedded page that receives at most one image at a time; a glass ball with coloured beams is the workload that separates the two engines. Measured on a Jetson Orin Nano (#530, `docs/HOST_LOOP_EXAMPLE.md`). +- Generate a per-executable AppArmor profile for application packaging with `webfront_generate_webkitgtk_profile`; select the distribution policy per target with `webfront_use_distribution`, without adding a runtime (#596, `docs/WEBKITGTK.md`). +- Look at the project from the terminal with `ls`, `cat`, `tree` and `mounts` (read-only), and at the installed packages with `wf list --tree`, `wf why ` and `wf info `; a `wf` command typed without its prefix answers with the line to type. The `wf` prefix stays (#575, ADR-023, `docs/DEVELOPER_ENVIRONMENT.md`). +- Add WebFront to an application that keeps its own loop: `app.start()` opens the system browser and returns at once, `app.requestClose()` ends an embedded window's `show()` from any thread, and `webfront::UIThread` runs an application on a secondary thread where the frontend allows it (WebView2). New `WebFrontHostLoop` example (#567, `docs/HOST_INTEGRATION.md`, ADR-007). +- Tell an agent at first contact how an application is developed (C++ with a TypeScript/TSX interface in `ui/`, `wf dev`) and that it can run `wf` itself in JSON or MCP: a README section before the tutorial, `webfront_write_agent_guide()`, and notices at configuration, in the terminal and at startup (#561, `docs/DEVELOPING_WITH_AGENTS.md`). +- Add the `app` starter (`wf create app`: a minimal TypeScript interface without dependency), `wf help ` and `wf help agents`, and make a missing manifest, a missing entry and an unknown starter answer with the next steps. Environment 0.9.2 (#561, `docs/DEVELOPER_ENVIRONMENT.md`). +- Build and test with GCC 13 on a hosted Linux aarch64 runner in the weekly and `master` checks (`gcc13-arm64`), and let `setup-cmake` install CMake on aarch64 (#548, `docs/TEST_TIERS.md`). + +### Changed + +- Launch the developer environment from its verified cache without rewriting it while its published files match the archive: a `wf` command of the tests starts in 1.6 s instead of 2.5 s (#570, `docs/DEVELOPER_ENVIRONMENT.md`). +- Replace Catch2 with `test/unit/Bdd.hpp`, a single-header BDD framework: scenarios are `Scenario` objects whose `given`/`when`/`then` sections are lambdas, checked with `require`/`check`. The tests no longer download or compile Catch2; `tests` takes `--exact`, `--list`, `--junit` and the former filters, order and shard options (ADR-012, `docs/TEST_TIERS.md`). +- Wait for asynchronous states in unit tests with `requireEventually`, `checkEventually`, `requireReady` and `checkReady` of `Bdd.hpp`, which report the delay and the time waited and replace nine local helpers; `WEBFRONT_TEST_TIMEOUT_FACTOR` lengthens the delays of a slow job (#582, `docs/TEST_TIERS.md`, ADR-012). +- Run each developer integration part and each wf command of the tests in a process of its own again: the shared windows of #544 and #556 made the driver cases about a third slower on Windows and failed more often. Remove the timing analysis tools and their CI steps, and repeat the desktop suite through one path, with `desktop_passes` on a manual dispatch (#570, `docs/TEST_PERFORMANCE.md`). +- Close the test driver's window with `requestClose()` instead of asking the page: a spec that blocks the page now ends with the driver's timeout report instead of a forced exit (#570). +- Keep the configure downloads of the tests (bootstrap environment, test registry, jasmine-core) once per machine, in `WEBFRONT_DOWNLOAD_CACHE`, and try a failed download three times: a new build tree links the verified archives instead of downloading them again (#570, `docs/DEVELOPER_ENVIRONMENT.md`). +- Declare GCC 13 as the best-effort S2 minimum for the library and examples, document the GCC 14 exit clause and qualified Clang scope, and add GCC 13 ASan/UBSan fast tests (#525, ADR-022). + +- Open the developer page on the interface, over the whole window, once the project has a preview; the terminal moves to a floating, movable window behind a tab on the right edge that shows the session's state, and keeps its session when collapsed. Its shortcut is F9, or the manifest's new optional `developer.terminalShortcut`. Introduced in environment 0.9.1 (#539, `docs/DEVELOPER_ENVIRONMENT.md`). +- Make the default test build the quick one: the heavy unit tests compile four to a file, the MSVC code analysis and the reproducibility proofs are off unless `-DWEBFRONT_MSVC_ANALYZE=ON` or `-DWEBFRONT_TEST_REPRODUCIBILITY=ON` asks for them. The CI passes every option explicitly and checks what it checked before (#546). ### Fixed +- Build the host-loop capture example with AppleClang when ignoring the frame number (#602, `docs/HOST_LOOP_EXAMPLE.md`). +- Deduplicate the host-loop example's frame requests through rendering until each delivery starts, and expose its status messages to assistive technologies (#599, `docs/HOST_LOOP_EXAMPLE.md`). +- Make the host-loop example reject `--capture` without a native window or with `--benchmark`, and return a failure when the capture cannot be saved or the window closes before it completes (#599, `docs/HOST_LOOP_EXAMPLE.md`). +- Enforce the WebKitGTK distribution policy across translation units and inherited environments; bound launcher checks and restore the development opt-out before callbacks or system-browser fallback (#596, `docs/WEBKITGTK.md`). +- On Windows, a slow HTTP client no longer blocks the publication of developer resources, and removing a log sink no longer returns while one of its callbacks is still running (#542, `docs/validation/ci-flakes-542.md`). +- The Linux interface loop shuts down without leaving work behind, and the automation deadlines are decided consistently when a window is ready at the moment its startup expires. The ThreadSanitizer job no longer needs its GLib suppression (#542, `docs/validation/ci-flakes-542.md`). +- `WebView2Lifecycle-native-early-close` no longer fails under load: the COM initialization that the WebView2 runtime keeps after a window closed during its startup is a documented limit, and the frontend's own apartment has a unit test (#564, #570, `docs/PROJECT_STATUS.md`). + +- Restore the terminal prompt with exit code 1 when `wf dev` starts without a project or a selectable entry; compilation errors still keep watching for edits. Environment 0.9.2 (#560). +- Read all six developer integration reports in CTest after a part fails, and keep the successful parts' dependent tests runnable, also when the session's native deadline ends it (#556). +- On Windows, `wf install`, `wf build` and `wf test` no longer fail with `rename: Access is denied` while another process, such as an antivirus scan, still reads the files just written: the developer store tries the rename again for up to 635 ms; `wf test` also empties the directory of an interrupted run (#542). + +- Build with `-DWEBFRONT_EMBED_CEF=ON` on Linux aarch64 instead of failing on `-m64`, and cross-compile CEF: WebFront pins CEF 156.0.28, whose package selects the archive and `PROJECT_ARCH` from the target (#523). -- The bridge no longer pays for diagnostics on every message (#363): the encoder of `Messages.hpp` wrote to `std::cout` for - each parameter, and `Frame::addBuffer` formatted a hex dump of each sent buffer before `log::debug()` tested the level (21.7 MB - allocated for a 1 MiB buffer). A 32 KiB echo over the HTML bridge drops from about 2.4 ms to 0.7 ms on WebKitGTK. Regressions: - `Encoding bridge messages writes nothing to the standard output` and `FrameBufferNotFormattedWhenDebugDisabled`. -- The developer store reads and writes project paths beyond MAX_PATH on Windows (#349): `projectPath` takes the extended-length form from 200 characters, as does a project root longer than MAX_PATH (`canonicalDirectory`), containment is checked on the ordinary spelling, and staged files get the same treatment. The MSVC option is now `/analyze:stacksize65536`, one argument: with a space, sccache read `65536` as a second source file and refused to cache 48 compilations of the Windows CI build (about 9 minutes against 25 seconds on Linux). -- The installer of the developer environment reads npm archives rooted at any single directory, as npm does (#316): the archives of - `@types/*` are rooted at the package name and were refused as "Invalid npm tarball root". A mixed or escaping root is still refused. -- The Life starter type-checks under TypeScript `strict` (`useState`), which `wf check` now proves. -- Script injection works before the page body exists, including a driver handshake completed during HTML parsing. - -- `wf test` supports WebKit engines without `AbortSignal.any()` (#335), preserving cancellation/deadline reports and - exit codes. Deadline and cleanup timers and the external cancellation listener are released on every exit. - The driver also remembers a watchdog close requested before the browser handshake; a late connection closes - without launching a command. Environment sources advance to 0.6.2 while the release and test-bootstrap pins remain on published 0.6.1. -- Browser regressions advance deadlines, grace periods and dev polling explicitly instead of sleeping. Native command - cancellation uses a release handshake, repeated type checks reuse immutable fixture bytes, cache/command fixtures - drop the large application-only dependency graph after the Life checks, and the shared bridge - runner avoids full binary debug dumps. Retired PI and Signal Studio application tests are removed; Life retains - React/TSX, preview, reproducible generation and rootless embedded coverage. Reproducibility compares two identical - builds, followed by a separate bootstrap refresh; packaged-script permission checks remain end-to-end. +## [0.9.0] - 2026-11-10 + +Last minor revision before 1.0, with the developer environment at the same number. It lays the groundwork for the +system services of [ADR-020](adr/README.md): confined writable storage, native window access, an interface-thread executor, +ranged and dynamic HTTP routes. **One migration:** libraries and developer environments older than 0.6.5 must be rebuilt, +because they pin a distribution address that no longer bootstraps. Developer environment 0.9.0 is the first one published +by the `release-developer` workflow. + +### Breaking + +- Rebuild libraries and developer environments older than 0.6.5 against current sources: they pin the former distribution address, which redirects to `https://dist.webfront.fr/` without the CORS headers a browser needs, so `bootstrap("developer")` no longer starts (#478, ADR-021). ### Added -- Developer journey qualification (#316, epic #303): `Journey*` CTest cases run `wf create`, `init`, `install`, `check`, `test`, `build` - and `embed` on one project in an empty directory from the local registry, compile the generated header into the Life application - and run it from an empty directory, then check a script under denied permissions and an emptied cache offline and restored. The test - registry gains `@types/react`, `@types/react-dom` and `csstype`. ADR-013, ADR-014 and ADR-015 are accepted. -- `third_party/` is removed (#319, epic #303): `fflate` 0.8.3, the last vendored source, is a locked package of the repository's - `wf` project, imported by name from `js/developer/environment/embed.mjs`; its notice comes from the installed package. - The environment archive stays byte for byte identical. The test registry downloads it at configure time, and - `RepositoryLayout` now rejects `third_party`, `vendor` and `node_modules` paths as well as any unlisted root entry. -- Tests, regeneration and CI without a JavaScript runtime or package manager (#318, epic #303). Configuring with `ENABLE_TESTING=ON` downloads, and - verifies against their SHA-512, the pinned bootstrap environment and the real packages of the tests' npm registry - (`test/web/registry-packages.json`; `-DWEBFRONT_REGISTRY_DIR` for a machine without network access); `wf run test-registry` - builds the registry, the environment is built from the current sources and the fixtures are assembled by CTest itself, so - `WEBFRONT_DEVELOPER_FIXTURES` and `WEBFRONT_REQUIRE_NODE` are gone. The 86 JavaScript tests became 84 Jasmine specs - (`test/developer/specs/`) run by the repository's own `wf test`, plus CMake tests for the bundle checksums and the reserved - command names. The headers of the core are rendered and checked by `js/core/EmbedAsset.cmake` in pure CMake (ADR-016 - v1.3), with a Catch2 scenario that decodes each of them. `NoNodeDependency` audits every file and - `NoNodeDependencyRejectsInjections` proves the guard. The Node.js tools, `vendor/package*.json` and the comparison job - of *Developer packages* are deleted; every CI job removes the JavaScript runtimes from the runner first. The record of - each former tool and test is [migration record](https://github.com/ambroise-leclerc/WebFront/blob/c9f5770273999ead7cff5e61f1d2a22a9ffbce89/docs/NODE_TOOLS_MIGRATION.md). - -- The developer environment builds itself (#315, distribution 0.6.1, published as `developer-v0.6.1` and pinned by `DeveloperReleaseData.hpp`, and by the bootstrap of the tests): the - repository is a `wf` project (`webfront.project.json`, `webfront-packages.lock.json`) and the scripts of - `js/developer/scripts/` run in the pinned bootstrap environment with `webfront-wf`. `build.mjs` bundles the environment - with the locked esbuild-wasm and writes `environment.tgz`, the starters, `provision.json` and the pinned header (with - `--refresh-bootstrap`, the bootstrap bundles, their checksums and the core headers); `site.mjs` stages the Pages site - and refuses to change a published version; `pin.mjs` checks the pinned header against the published archive; `embed-core.mjs` regenerates the core headers. The bytes - are those of the Node.js build, twice in a row (CTest `SelfBuild*`, job `wf-package` of *Developer packages*). The - publication runs without Node.js (`pages.sh`, `archive-release.sh`, a shell tag check); `-DWEBFRONT_REQUIRE_NODE=OFF` - configures a test build without it. The inventory of the Node.js tools and their destination is - [migration record](https://github.com/ambroise-leclerc/WebFront/blob/c9f5770273999ead7cff5e61f1d2a22a9ffbce89/docs/NODE_TOOLS_MIGRATION.md); the maintainer procedure is `js/developer/tools/PUBLISHING.md`. - -- `webfront-wf` test driver and bootstrap provisioning (#321, developer distribution 0.6.0 published as `developer-v0.6.0`, pinned by `DeveloperReleaseData.hpp` and by the bootstrap): runs one `wf` command without interaction on a project - and exits with its status (64 usage, 70 bootstrap failure, 71 time limit, 72 no result), with an optional JSON report. - `cmake/WebFrontBootstrap.cmake` pins the bootstrap environment (0.6.1) and, with `ENABLE_TESTING=ON`, downloads - and verifies it at configure time, or takes it from `WEBFRONT_BOOTSTRAP_DIR`. `environment.json` declares `protocol` and - `api`; `webfront.developer.config` exposes the supported versions and the loader refuses an incompatible archive with an - explicit diagnostic. The Linux CEF job blocks the public network after configure. - -- `wf test [--timeout ] [pattern]` (#310, environment sources; release pin unchanged): builds the manifest's - `test.specs` with esbuild-wasm and runs them under the project's locked `jasmine-core`, obtained by `wf install` from - the registry, in a hidden same-origin frame. Progress and a summary stream to the terminal; the structured report - (counts, failures, pending specs) is bounded, and the exit code is 0, 1 (failure, load error, nothing run), 124 (time - limit) or 130 (Ctrl+C). `runNonInteractive` runs a command without a terminal, sends `{exitCode, output, report}` to an - application's C++ function and ends the session. `DeveloperFS` also serves `.webfront/developer/test/`. - -- `wf build [entry]` / `wf dev [entry]` (#309, environment sources; release pin unchanged): build all manifest - entries to `.webfront/developer/build/` without opening the preview, or continuously rebuild one preview - with a persistent esbuild/WASM context. Sequential 750 ms polling watches read inputs and missing imports - (1,024 paths, 32 MiB per pass). Build/publication errors preserve the last good preview; diagnostics with - file/line/column stream to the terminal and overlay the preview. Corrections resume rebuilding; Ctrl+C - terminates the Worker, stops polling and aborts staged output. - -- Project manifest `webfront.project.json` (format 1: `name`, `version`, `dependencies`, `registry`, `scripts`, - `entries`, `providers`, `test`, `permissions`), strictly validated; `wf init`, `wf install [--update]` and - manifest-driven `wf preview`/`wf embed` in developer distribution 0.5.0, which `DeveloperReleaseData.hpp` pins - (published as `developer-v0.5.0`). The lock records the digest of - the manifest dependencies and reports a desynchronized state. `developer::Store::commitGroup` publishes - manifest and lock through a synced intent journal with crash recovery and a concurrent-install precondition. - New bridge callbacks `webfront.developer.state` and `webfront.developer.commitGroup`. Starters ship a manifest; - `wf install` now needs `wf init` first, which adopts the roots of an existing lock so a project locked before 0.5.0 - keeps its locked graph. A committed publication that cannot be completed does not prevent opening the project: - it is reported (`developer::IncompletePublication`) and completed by the next command. -- `wf restore [--offline]` (developer distribution 0.5.0): rebuilds the package cache from the lock alone, at the - locked versions and integrities, idempotent and interruptible; `--offline` only checks the cache and lists the - missing or corrupted packages. Cached packages carry a record of their files' digests. The registry is the - application's option, else the manifest's `registry`, else registry.npmjs.org; `wf install` and `wf restore` - print it with its origin. A reproducible local npm registry fixture (`js/developer/tools/registry-fixture.mjs`) - serves the tests. - -- `wf run [--timeout ] "; + +/** The page of a published preview. */ +export const previewPage = files => applicationPage(files, previewHook); + let revision = 0; export function showPreview(frame, directory = 'preview') { if (!frame) throw new Error('No preview frame is available'); @@ -195,9 +205,12 @@ export async function dev(args, {bridge, signal, preview: frame, write = () => { let diagnostic = ''; const loaded = () => previewDiagnostics(frame, diagnostic); frame?.addEventListener('load', loaded); + // The page shows where the loop is (workspace.mjs): building, ready, failed, then stopped. + const report = state => frame?.dispatchEvent?.(new CustomEvent('webfront-dev-status', {detail: {state}})); try { for (;;) { active.throwIfAborted(); + report('building'); const configReads = new Map(), budget = {bytes: 0}; try { await withBuild(async () => { @@ -207,11 +220,14 @@ export async function dev(args, {bridge, signal, preview: frame, write = () => { catch (error) { if (configReads.get(path) !== 'missing') throw error; } } const project = await loadProject(bridge); - if (!project.manifest && args[0] === undefined) throw new Error(noManifest); - const entry = resolveEntry(project.manifest, args[0], 'wf dev '); + let entry; + try { + if (!project.manifest && args[0] === undefined) throw new Error(noManifest); + entry = resolveEntry(project.manifest, args[0], 'wf dev '); + } catch (error) { error.invalidStart = true; throw error; } if (!session || session.closed) session = compilerSession(bridge, active); const files = await session.rebuild({entry, lock: project.lock ?? {format: 1, roots: {}, packages: {}}}); - files.set('index.html', applicationPage(files)); + files.set('index.html', previewPage(files)); await publish(bridge, '.webfront/developer/preview', files, {signal: active}); // Once commit succeeds, display its publication even if Ctrl+C arrived while awaiting it. diagnostic = ''; @@ -219,12 +235,17 @@ export async function dev(args, {bridge, signal, preview: frame, write = () => { showPreview(frame); // A successful build can drop dependencies that are no longer imported. observed = new Map(session.observed); + report('ready'); write(syncNotice(project) + 'Preview ready. Watching inputs (Ctrl+C to stop).\n'); }); } catch (error) { if (active.aborted) throw stopped(); if (error?.code === 'busy') { await waitForPoll(active); continue; } + // A missing project or an omitted entry at startup finishes the command; every other failure + // (unreadable or malformed files, compilation errors, later edits) stays recoverable. + if (!session && error?.invalidStart) throw error; diagnostic = diagnosticsText(error); + report('failed'); write(diagnostic + '\n'); previewDiagnostics(frame, diagnostic); if (session?.observed.size) observed = new Map(session.observed); @@ -238,7 +259,7 @@ export async function dev(args, {bridge, signal, preview: frame, write = () => { if (active.aborted) throw stopped(); // A temporarily unreadable file or a bound violation cannot publish or reload anything. const text = diagnosticsText(error); - if (diagnostic !== text) { diagnostic = text; write(text + '\n'); previewDiagnostics(frame, text); } + if (diagnostic !== text) { diagnostic = text; report('failed'); write(text + '\n'); previewDiagnostics(frame, text); } } } } @@ -254,5 +275,6 @@ export async function dev(args, {bridge, signal, preview: frame, write = () => { bridge.socket?.removeEventListener('close', disconnected); frame?.removeEventListener('load', loaded); previewDiagnostics(frame, ''); + report('stopped'); } } diff --git a/js/developer/environment/embed.mjs b/js/developer/environment/embed.mjs index 88ce1f76..f46ffb61 100644 --- a/js/developer/environment/embed.mjs +++ b/js/developer/environment/embed.mjs @@ -62,8 +62,9 @@ ${declarations.join('\n')} `; } -export function applicationPage(files) { +/** The page of an application built into `files`; `head` is markup put before its stylesheet and its scripts. */ +export function applicationPage(files, head = '') { const encode = new TextEncoder(); const stylesheet = files.has('app.css') ? '' : ''; - return encode.encode(`\nWebFront application${stylesheet}
\n`); + return encode.encode(`\nWebFront application${head}${stylesheet}
\n`); } diff --git a/js/developer/environment/files.mjs b/js/developer/environment/files.mjs new file mode 100644 index 00000000..9fd6e1e7 --- /dev/null +++ b/js/developer/environment/files.mjs @@ -0,0 +1,289 @@ +// The terminal's file commands: ls, cat, tree and mounts. They only read the project directory, through the callbacks +// that wf uses; paths are relative to the project and never leave it. They are not a shell: no working directory, no +// glob, no pipe, and nothing is written (ADR-023). +import {call, blockSize} from './io.mjs'; +import {isUnsafe} from './paths.mjs'; +import {manifestPath, lockPath} from './manifest.mjs'; +import {printable, inline} from './terminal.mjs'; + +const decoder = new TextDecoder(); +const usage = { + ls: 'ls [-l] [-a] [--] [path]', cat: 'cat [--] [file...]', tree: 'tree [-a] [-L ] [--] [path]', mounts: 'mounts'}; +/** One line per file command, for the terminal's help. */ +export const fileCommandHelp = { + ls: 'List a project directory; -l adds size, date and what wf knows of each entry, -a the hidden entries', + cat: 'Print text files of the project', + tree: 'Show a project directory as a tree (3 levels; -L , -a for the hidden entries)', + mounts: 'Describe what the application serves to the browser, and from where', +}; + +const usageError = name => new Error(`Usage: ${usage[name]}`); + +/** A project path as the callbacks take it: '' for the project itself, no "./" prefix, no final "/". */ +export function projectPath(argument = '') { + let path = argument; + while (path.startsWith('./')) path = path.slice(2); + path = path.replace(/\/+$/, ''); + if (path === '' && argument.startsWith('/')) throw new Error(`${argument}: paths are relative to the project directory`); + if (path === '' || path === '.') return ''; + if (path.startsWith('/') || isUnsafe(path)) throw new Error(`${argument}: paths are relative to the project directory and stay inside it`); + return path; +} + +// Splits arguments into single-letter flags (-la is -l -a) and the other words. A `valued` flag takes the rest of its +// word (-L3) or the next word (-L 3, -aL 3). After "--" every word is a path, so that a name may start with "-". +function parseArguments(name, args, allowed, valued = '') { + const flags = new Map(), words = []; + for (let index = 0; index < args.length; ++index) { + const word = args[index]; + if (word === '--') { words.push(...args.slice(index + 1)); break; } + if (!word.startsWith('-') || word === '-') { words.push(word); continue; } + for (let position = 1; position < word.length; ++position) { + const flag = word[position]; + if (!allowed.includes(flag)) throw usageError(name); + if (!valued.includes(flag)) { flags.set(flag, true); continue; } + const attached = word.slice(position + 1); + if (!attached && index + 1 === args.length) throw usageError(name); + flags.set(flag, attached || args[++index]); + break; + } + } + return {flags, words}; +} + +const join = (directory, name) => directory ? `${directory}/${name}` : name; +const listNames = async (bridge, directory) => JSON.parse(decoder.decode(await call(bridge, 'list', directory))); +const visible = (names, all) => all ? names : names.filter(name => !name.startsWith('.')); + +// What wf keeps under .webfront/: the longest prefix describes an entry. +const managed = [ + ['.webfront/developer/packages', 'package cache (wf install, wf restore)'], + ['.webfront/developer/environment', 'developer environment, served to the browser'], + ['.webfront/developer/preview', 'interface built by wf dev and wf preview, served to the browser'], + ['.webfront/developer/test', 'files of a wf test run, served to the browser'], + ['.webfront/developer/build', 'output of wf build'], + ['.webfront/developer/staging', 'publications in progress'], + ['.webfront/developer/history.json', 'terminal history'], + ['.webfront', 'managed by wf'], +]; +const firstWord = text => String(text).trim().split(/\s+/)[0]; + +/** + * What wf knows of a project path: the manifest, the lock, what it manages under .webfront/, and the entries, specs, + * scripts and generated providers that the manifest declares. An empty string for the project's other files. + */ +export function nature(path, manifest = null) { + if (path === manifestPath) return 'manifest'; + if (path === lockPath) return 'lock'; + const kept = managed.find(([prefix]) => path === prefix || path.startsWith(prefix + '/')); + if (kept) return kept[1]; + const named = (section, value, label) => Object.entries(Object(manifest?.[section] ?? {})) + .filter(([, declared]) => value(declared) === path).map(([name]) => `${label} ${name}`); + const roles = [ + ...named('entries', entry => entry, 'entry'), + ...named('providers', provider => provider?.output, 'generated provider'), + ...named('scripts', script => firstWord(script) === 'wf' ? null : firstWord(script), 'script'), + ...(Array.isArray(manifest?.test?.specs) && manifest.test.specs.includes(path) ? ['spec'] : []), + ]; + return roles.join(', '); +} + +/** Names laid out in columns read downwards, for a terminal `width` cells wide. */ +export function columns(names, width = 80) { + if (!names.length) return ''; + const cell = Math.max(...names.map(name => name.length)) + 2; + const rows = Math.ceil(names.length / Math.max(1, Math.floor(width / cell))); + return Array.from({length: rows}, (_, row) => + names.filter((_, index) => index % rows === row).map(name => name.padEnd(cell)).join('').trimEnd()).join('\n'); +} + +const two = number => String(number).padStart(2, '0'); +function timestamp(milliseconds) { + if (!milliseconds) return '-'.padEnd(16); + const date = new Date(milliseconds); + return `${date.getFullYear()}-${two(date.getMonth() + 1)}-${two(date.getDate())} ${two(date.getHours())}:${two(date.getMinutes())}`; +} + +/** The lines of ls -l: type, size in bytes, modification time, name, and the entry's nature when wf knows one. */ +export function longListing(entries, directory, manifest) { + const width = Math.max(1, ...entries.map(entry => String(entry.size).length)); + return entries.map(entry => { + const isDirectory = entry.type === 'directory'; + const role = nature(join(directory, entry.name), manifest); + const size = (isDirectory ? '-' : String(entry.size)).padStart(width); + return `${isDirectory ? 'd' : '-'} ${size} ${timestamp(entry.modified)} ${inline(entry.name)}${isDirectory ? '/' : ''}${role ? ` [${inline(role)}]` : ''}`; + }).join('\n'); +} + +/** Whether an error of the bridge says that the application has no such webfront.developer.* callback (an older library). */ +export const isMissingCallback = (error, name) => String(error?.message).includes(`C++ function 'webfront.developer.${name}' was not found`); + +async function describedEntries(bridge, directory) { + try { return JSON.parse(decoder.decode(await call(bridge, 'entries', directory))); } + catch (error) { + if (isMissingCallback(error, 'entries')) + throw new Error('ls -l needs a more recent WebFront library in the application; ls and tree work with this one'); + throw error; + } +} + +// A path that is not a directory is listed as the one entry of its directory, when it is there. +async function listing(bridge, path, read) { + try { return {directory: path, items: await read(path)}; } + catch (error) { + if (!path || !/Cannot list project directory/.test(error?.message)) throw error; + const cut = path.lastIndexOf('/'); + const directory = path.slice(0, Math.max(cut, 0)), name = path.slice(cut + 1); + const items = (await read(directory).catch(() => [])).filter(item => (item.name ?? item) === name); + if (!items.length) throw new Error(`${path}: no such file or directory in the project`); + return {directory, items, single: true}; + } +} + +/** ls [-l] [-a] [path]. context.manifest() resolves with the manifest for the natures, or null. */ +export async function ls(args, {bridge, manifest = async () => null, width = 80}) { + const {flags, words} = parseArguments('ls', args, 'la'); + if (words.length > 1) throw usageError('ls'); + const path = projectPath(words[0]); + const all = flags.has('a'); + if (!flags.has('l')) { + const {items, single} = await listing(bridge, path, directory => listNames(bridge, directory)); + return columns((single ? items : visible(items, all)).map(inline), width); + } + const {directory, items, single} = await listing(bridge, path, target => describedEntries(bridge, target)); + const shown = single || all ? items : items.filter(entry => !entry.name.startsWith('.')); + return longListing(shown, directory, await manifest().catch(() => null)); +} + +export const catLimit = 1024 * 1024; + +async function readText(bridge, path, signal) { + const chunks = []; + let size = 0; + for (;;) { + signal?.throwIfAborted(); + let chunk; + try { chunk = await call(bridge, 'read', path, size); } + catch (error) { + if (/Cannot read project file/.test(error?.message)) throw new Error(`${path}: no such file in the project`); + throw error; + } + chunks.push(chunk); + size += chunk.length; + if (size > catLimit) throw new Error(`${path} is larger than 1 MiB: open it in your editor`); + if (chunk.length < blockSize) break; + } + const bytes = new Uint8Array(await new Blob(chunks).arrayBuffer()); + if (bytes.includes(0)) throw new Error(`${path} is not a text file`); + try { return new TextDecoder('utf-8', {fatal: true}).decode(bytes); } + catch { throw new Error(`${path} is not UTF-8 text`); } +} + +/** cat [file...]: the text of project files, at most 1 MiB each. */ +export async function cat(args, {bridge, signal}) { + const {words} = parseArguments('cat', args, ''); + if (!words.length) throw usageError('cat'); + let output = ''; + for (const word of words) { + const path = projectPath(word); + if (!path) throw new Error(`${word} is a directory`); + const text = printable(await readText(bridge, path, signal)); + output += text && !text.endsWith('\n') ? text + '\n' : text; + } + return output; +} + +export const treeLimit = 2000; +const defaultDepth = 3; + +/** + * tree [-a] [-L ] [path]. Hidden entries need -a, and even then .webfront/ is not opened unless the path names + * it: its package cache would hide the project. The tree stops after treeLimit entries. + */ +export async function tree(args, {bridge, signal}) { + const {flags, words} = parseArguments('tree', args, 'aL', 'L'); + if (words.length > 1) throw usageError('tree'); + const depth = flags.has('L') ? Number(flags.get('L')) : defaultDepth; + if (!Number.isInteger(depth) || depth < 1 || depth > 32) throw new Error('tree -L expects a depth from 1 to 32'); + const root = projectPath(words[0]); + const all = flags.has('a'); + const lines = [root ? inline(root) + '/' : '.']; + let directories = 0, files = 0, cut = false; + let rootNames; + try { rootNames = await listNames(bridge, root); } + catch (error) { + if (!/Cannot list project directory/.test(error?.message)) throw error; + const cutAt = root.lastIndexOf('/'); + const siblings = await listNames(bridge, root.slice(0, Math.max(cutAt, 0))).catch(() => []); + throw new Error(siblings.includes(root.slice(cutAt + 1)) ? `${root} is a file: cat ${root} prints it` : `${root}: no such directory in the project`); + } + // A directory that cannot be listed below the root (removed meanwhile, or unreadable) is shown without content. + const namesOf = directory => directory === root ? rootNames : listNames(bridge, directory).catch(error => { + if (/Cannot list project directory/.test(error?.message)) return []; + throw error; + }); + const walk = async (directory, prefix, level) => { + signal?.throwIfAborted(); + const names = visible(await namesOf(directory), all); + for (const [index, name] of names.entries()) { + if (lines.length > treeLimit) { cut = true; return; } + const last = index === names.length - 1; + const isDirectory = name.endsWith('/'); + const path = join(directory, isDirectory ? name.slice(0, -1) : name); + const closed = isDirectory && (level === depth || (path === '.webfront' && root !== '.webfront')); + lines.push(`${prefix}${last ? '└── ' : '├── '}${inline(name)}${closed && level < depth ? ' [managed by wf: tree .webfront]' : ''}`); + isDirectory ? ++directories : ++files; + if (isDirectory && !closed) await walk(path, prefix + (last ? ' ' : '│ '), level + 1); + if (cut) return; + } + }; + await walk(root, '', 1); + if (cut) lines.push(`... more than ${treeLimit} entries: name a subdirectory or lower -L`); + lines.push('', `${directories} ${directories === 1 ? 'directory' : 'directories'}, ${files} ${files === 1 ? 'file' : 'files'}`); + return lines.join('\n'); +} + +const published = [ + ['environment', 'the developer environment, verified against its SHA-512'], + ['preview', 'the interface built by wf dev and wf preview'], + ['test', 'the files of a wf test run'], +]; + +/** + * mounts: what the developer application answers to the browser, in the order it looks, and what the project + * commands read. The layers are those of fs::DeveloperFS; the application's own providers are not enumerable. + */ +export async function mounts(args, {bridge, config = {}}) { + if (args.length) throw usageError('mounts'); + const present = async name => (await listNames(bridge, `.webfront/developer/${name}`).catch(() => [])).length > 0; + const rows = [ + ['/WebFront.js, /webfront-bootstrap.html, /webfront-bootstrap.mjs', 'embedded in the executable: the bridge and the loader'], + ]; + for (const [name, purpose] of published) + rows.push([`/webfront/developer/${name}/`, `.webfront/developer/${name}/ of the project (${await present(name) ? 'published' : 'empty'}): ${purpose}`]); + rows.push(['/index.html, /favicon.ico, /webfront-dom.mjs, /webfront-fallback.mjs', 'embedded in the executable: the fallback page and its modules'], + ['other paths', "the application's own providers, if it has some; else 404"]); + const width = Math.max(...rows.map(([url]) => url.length)); + return ['Served to the browser, the first that answers:', + ...rows.map(([url, source]) => ` ${url.padEnd(width)} ${source}`), + 'The sources of the project are never served: wf compiles them into a publication, and wf embed into a C++ provider.', + '', + 'Read by the commands of this terminal (ls, cat, tree, wf): the project directory given to the application.', + ` manifest ${manifestPath}`, + ` lock ${lockPath}`, + ' wf cache .webfront/ (packages, publications, history)', + ...(config.environment ? [` environment ${config.environment}`] : []), + ...(config.integrity ? [` integrity ${config.integrity}`] : []), + ...(config.registry ? [` registry ${config.registry}${config.registryExplicit ? ' (chosen by the application)' : ''}`] : []), + ].join('\n'); +} + +/** The file commands the terminal keeps for itself without providing them (commands.mjs: reservedNames). */ +export const withheld = ['cd', 'pwd', 'cp', 'mv', 'rm', 'mkdir', 'rmdir', 'touch', 'edit', 'find', 'grep', 'head', 'tail', 'less', 'stat', 'du', 'df']; +const reading = new Set(['find', 'grep', 'head', 'tail', 'less', 'stat', 'du', 'df']); +/** Why a withheld command does nothing, and what to use instead. */ +export function withheldReason(name) { + if (name === 'cd' || name === 'pwd') return `${name} is not provided: there is no working directory, every path is relative to the project (ls, tree, mounts)`; + if (reading.has(name)) return `${name} is not provided: this terminal has ls, cat and tree; use your own tools for the rest`; + return `${name} is not provided: this terminal does not change files; edit the project in your editor (wf dev rebuilds on every save)`; +} diff --git a/js/developer/environment/manifest.mjs b/js/developer/environment/manifest.mjs index f59662f4..c3a8c570 100644 --- a/js/developer/environment/manifest.mjs +++ b/js/developer/environment/manifest.mjs @@ -33,7 +33,7 @@ const exactVersion = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; const rangeShape = /^[0-9A-Za-z.+\-^~<>=*| ]{1,128}$/; const label = /^[A-Za-z0-9][A-Za-z0-9:_.-]{0,63}$/; const identifier = /^[A-Za-z_][A-Za-z0-9_]*$/; -const keys = ['format', 'name', 'version', 'dependencies', 'registry', 'scripts', 'entries', 'providers', 'test', 'permissions']; +const keys = ['format', 'name', 'version', 'dependencies', 'registry', 'scripts', 'entries', 'providers', 'test', 'permissions', 'developer']; const permissionKeys = ['files', 'publish', 'fetch']; const fail = message => { throw new Error(`${manifestPath}: ${message}`); }; @@ -136,6 +136,35 @@ function checkPermissions(value) { return permissions; } +const shortcutModifiers = {Ctrl: 'ctrlKey', Alt: 'altKey', Shift: 'shiftKey', Meta: 'metaKey'}; + +/** The shortcut of the terminal window when the manifest names none. */ +export const defaultTerminalShortcut = 'F9'; + +/** + * A shortcut written as "F9" or "Ctrl+Shift+F10": a function key, F1 to F12, after any of Ctrl, Alt, Shift and Meta, each + * at most once. Gives the key and the modifiers as a keyboard event has them; null when the text is not a shortcut. + */ +export function parseShortcut(text) { + if (typeof text !== 'string') return null; + const parts = text.split('+'), key = parts.pop(); + if (!/^F(?:[1-9]|1[0-2])$/.test(key) || new Set(parts).size !== parts.length) return null; + const shortcut = {key, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false}; + for (const part of parts) { + if (!Object.hasOwn(shortcutModifiers, part)) return null; + shortcut[shortcutModifiers[part]] = true; + } + return shortcut; +} + +function checkDeveloper(value) { + const developer = requireObject(value, 'developer'); + onlyKeys(developer, ['terminalShortcut'], 'developer'); + if (developer.terminalShortcut !== undefined && !parseShortcut(developer.terminalShortcut)) + fail('developer.terminalShortcut must be a function key, F1 to F12, optionally after Ctrl, Alt, Shift or Meta (for instance "Ctrl+Shift+F9")'); + return developer; +} + function checkIdentity(manifest) { if (typeof manifest.name !== 'string' || !npmName.test(manifest.name)) fail('name must be a lower-case npm package name'); if (typeof manifest.version !== 'string' || !exactVersion.test(manifest.version)) fail('version must be a semantic version'); @@ -164,6 +193,7 @@ export function validateManifest(manifest) { ...(manifest.scripts === undefined ? {} : {scripts: checkScripts(manifest.scripts)}), ...(manifest.test === undefined ? {} : {test: checkTest(manifest.test)}), ...(manifest.permissions === undefined ? {} : {permissions: checkPermissions(manifest.permissions)}), + ...(manifest.developer === undefined ? {} : {developer: checkDeveloper(manifest.developer)}), }; } diff --git a/js/developer/environment/packages.bundle.mjs b/js/developer/environment/packages.bundle.mjs index 772e9b5e..e018908f 100644 --- a/js/developer/environment/packages.bundle.mjs +++ b/js/developer/environment/packages.bundle.mjs @@ -1,16 +1,16 @@ -var _n=Object.create;var gt=Object.defineProperty;var Vn=Object.getOwnPropertyDescriptor;var Xn=Object.getOwnPropertyNames;var Bn=Object.getPrototypeOf,Hn=Object.prototype.hasOwnProperty;var w=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Yn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Xn(t))!Hn.call(e,s)&&s!==r&>(e,s,{get:()=>t[s],enumerable:!(n=Vn(t,s))||n.enumerable});return e};var F=(e,t,r)=>(r=e!=null?_n(Bn(e)):{},Yn(t||!e||!e.__esModule?gt(r,"default",{value:e,enumerable:!0}):r,e));var V=w((ya,Ot)=>{"use strict";var ts="2.0.0",rs=Number.MAX_SAFE_INTEGER||9007199254740991,ns=16,ss=250,os=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Ot.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:ns,MAX_SAFE_BUILD_LENGTH:ss,MAX_SAFE_INTEGER:rs,RELEASE_TYPES:os,SEMVER_SPEC_VERSION:ts,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var X=w((xa,vt)=>{"use strict";var is=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};vt.exports=is});var z=w((j,It)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Te,MAX_SAFE_BUILD_LENGTH:cs,MAX_LENGTH:as}=V(),ls=X();j=It.exports={};var us=j.re=[],fs=j.safeRe=[],p=j.src=[],ps=j.safeSrc=[],h=j.t={},hs=0,je="[a-zA-Z0-9-]",ds=[["\\s",1],["\\d",as],[je,cs]],ms=e=>{for(let[t,r]of ds)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let n=ms(t),s=hs++;ls(e,s,t),h[e]=s,p[s]=t,ps[s]=n,us[s]=new RegExp(t,r?"g":void 0),fs[s]=new RegExp(n,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${je}*`);E("MAINVERSION",`(${p[h.NUMERICIDENTIFIER]})\\.(${p[h.NUMERICIDENTIFIER]})\\.(${p[h.NUMERICIDENTIFIER]})`);E("MAINVERSIONLOOSE",`(${p[h.NUMERICIDENTIFIERLOOSE]})\\.(${p[h.NUMERICIDENTIFIERLOOSE]})\\.(${p[h.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASEIDENTIFIER",`(?:${p[h.NONNUMERICIDENTIFIER]}|${p[h.NUMERICIDENTIFIER]})`);E("PRERELEASEIDENTIFIERLOOSE",`(?:${p[h.NONNUMERICIDENTIFIER]}|${p[h.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASE",`(?:-(${p[h.PRERELEASEIDENTIFIER]}(?:\\.${p[h.PRERELEASEIDENTIFIER]})*))`);E("PRERELEASELOOSE",`(?:-?(${p[h.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${p[h.PRERELEASEIDENTIFIERLOOSE]})*))`);E("BUILDIDENTIFIER",`${je}+`);E("BUILD",`(?:\\+(${p[h.BUILDIDENTIFIER]}(?:\\.${p[h.BUILDIDENTIFIER]})*))`);E("FULLPLAIN",`v?${p[h.MAINVERSION]}${p[h.PRERELEASE]}?${p[h.BUILD]}?`);E("FULL",`^${p[h.FULLPLAIN]}$`);E("LOOSEPLAIN",`[v=\\s]*${p[h.MAINVERSIONLOOSE]}${p[h.PRERELEASELOOSE]}?${p[h.BUILD]}?`);E("LOOSE",`^${p[h.LOOSEPLAIN]}$`);E("GTLT","((?:<|>)?=?)");E("XRANGEIDENTIFIERLOOSE",`${p[h.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);E("XRANGEIDENTIFIER",`${p[h.NUMERICIDENTIFIER]}|x|X|\\*`);E("XRANGEPLAIN",`[v=\\s]*(${p[h.XRANGEIDENTIFIER]})(?:\\.(${p[h.XRANGEIDENTIFIER]})(?:\\.(${p[h.XRANGEIDENTIFIER]})(?:${p[h.PRERELEASE]})?${p[h.BUILD]}?)?)?`);E("XRANGEPLAINLOOSE",`[v=\\s]*(${p[h.XRANGEIDENTIFIERLOOSE]})(?:\\.(${p[h.XRANGEIDENTIFIERLOOSE]})(?:\\.(${p[h.XRANGEIDENTIFIERLOOSE]})(?:${p[h.PRERELEASELOOSE]})?${p[h.BUILD]}?)?)?`);E("XRANGE",`^${p[h.GTLT]}\\s*${p[h.XRANGEPLAIN]}$`);E("XRANGELOOSE",`^${p[h.GTLT]}\\s*${p[h.XRANGEPLAINLOOSE]}$`);E("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Te}})(?:\\.(\\d{1,${Te}}))?(?:\\.(\\d{1,${Te}}))?`);E("COERCE",`${p[h.COERCEPLAIN]}(?:$|[^\\d])`);E("COERCEFULL",p[h.COERCEPLAIN]+`(?:${p[h.PRERELEASE]})?(?:${p[h.BUILD]})?(?:$|[^\\d])`);E("COERCERTL",p[h.COERCE],!0);E("COERCERTLFULL",p[h.COERCEFULL],!0);E("LONETILDE","(?:~>?)");E("TILDETRIM",`(\\s*)${p[h.LONETILDE]}\\s+`,!0);j.tildeTrimReplace="$1~";E("TILDE",`^${p[h.LONETILDE]}${p[h.XRANGEPLAIN]}$`);E("TILDELOOSE",`^${p[h.LONETILDE]}${p[h.XRANGEPLAINLOOSE]}$`);E("LONECARET","(?:\\^)");E("CARETTRIM",`(\\s*)${p[h.LONECARET]}\\s+`,!0);j.caretTrimReplace="$1^";E("CARET",`^${p[h.LONECARET]}${p[h.XRANGEPLAIN]}$`);E("CARETLOOSE",`^${p[h.LONECARET]}${p[h.XRANGEPLAINLOOSE]}$`);E("COMPARATORLOOSE",`^${p[h.GTLT]}\\s*(${p[h.LOOSEPLAIN]})$|^$`);E("COMPARATOR",`^${p[h.GTLT]}\\s*(${p[h.FULLPLAIN]})$|^$`);E("COMPARATORTRIM",`(\\s*)${p[h.GTLT]}\\s*(${p[h.LOOSEPLAIN]}|${p[h.XRANGEPLAIN]})`,!0);j.comparatorTrimReplace="$1$2$3";E("HYPHENRANGE",`^\\s*(${p[h.XRANGEPLAIN]})\\s+-\\s+(${p[h.XRANGEPLAIN]})\\s*$`);E("HYPHENRANGELOOSE",`^\\s*(${p[h.XRANGEPLAINLOOSE]})\\s+-\\s+(${p[h.XRANGEPLAINLOOSE]})\\s*$`);E("STAR","(<|>)?=?\\s*\\*");E("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");E("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var ce=w((Ra,Nt)=>{"use strict";var ws=Object.freeze({loose:!0}),Es=Object.freeze({}),gs=e=>e?typeof e!="object"?ws:e:Es;Nt.exports=gs});var Pe=w((ba,Lt)=>{"use strict";var kt=/^[0-9]+$/,St=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:eSt(t,e);Lt.exports={compareIdentifiers:St,rcompareIdentifiers:$s}});var b=w((Oa,Tt)=>{"use strict";var ae=X(),{MAX_LENGTH:At,MAX_SAFE_INTEGER:le}=V(),{safeRe:ue,t:fe}=z(),ys=ce(),{compareIdentifiers:qe}=Pe(),Ce=class e{constructor(t,r){if(r=ys(r),t instanceof e){if(t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease)return t;t=t.version}else if(typeof t!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>At)throw new TypeError(`version is longer than ${At} characters`);ae("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?ue[fe.LOOSE]:ue[fe.FULL]);if(!n)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>le||this.major<0)throw new TypeError("Invalid major version");if(this.minor>le||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>le||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let o=+s;if(o>=0&&ot.major?1:this.minort.minor?1:this.patcht.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let n=this.prerelease[r],s=t.prerelease[r];if(ae("prerelease compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return qe(n,s)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let n=this.build[r],s=t.build[r];if(ae("build compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return qe(n,s)}while(++r)}inc(t,r,n){if(t.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let s=`-${r}`.match(this.options.loose?ue[fe.PRERELEASELOOSE]:ue[fe.PRERELEASE]);if(!s||s[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let s=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[s];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(r){let o=[r,s];n===!1&&(o=[r]),qe(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=o):this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Tt.exports=Ce});var q=w((va,Pt)=>{"use strict";var jt=b(),xs=(e,t,r=!1)=>{if(e instanceof jt)return e;try{return new jt(e,t)}catch(n){if(!r)return null;throw n}};Pt.exports=xs});var Ct=w((Ia,qt)=>{"use strict";var Rs=q(),bs=(e,t)=>{let r=Rs(e,t);return r?r.version:null};qt.exports=bs});var Ut=w((Na,Dt)=>{"use strict";var Os=q(),vs=(e,t)=>{let r=Os(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};Dt.exports=vs});var Gt=w((ka,zt)=>{"use strict";var Ft=b(),Is=(e,t,r,n,s)=>{typeof r=="string"&&(s=n,n=r,r=void 0);try{return new Ft(e instanceof Ft?e.version:e,r).inc(t,n,s).version}catch{return null}};zt.exports=Is});var _t=w((Sa,Wt)=>{"use strict";var Mt=q(),Ns=(e,t)=>{let r=Mt(e,null,!0),n=Mt(t,null,!0),s=r.compare(n);if(s===0)return null;let o=s>0,i=o?r:n,a=o?n:r,c=!!i.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(i)===0)return a.minor&&!a.patch?"minor":"patch"}let u=c?"pre":"";return r.major!==n.major?u+"major":r.minor!==n.minor?u+"minor":r.patch!==n.patch?u+"patch":"prerelease"};Wt.exports=Ns});var Xt=w((La,Vt)=>{"use strict";var ks=b(),Ss=(e,t)=>new ks(e,t).major;Vt.exports=Ss});var Ht=w((Aa,Bt)=>{"use strict";var Ls=b(),As=(e,t)=>new Ls(e,t).minor;Bt.exports=As});var Jt=w((Ta,Yt)=>{"use strict";var Ts=b(),js=(e,t)=>new Ts(e,t).patch;Yt.exports=js});var Kt=w((ja,Zt)=>{"use strict";var Ps=q(),qs=(e,t)=>{let r=Ps(e,t);return r&&r.prerelease.length?r.prerelease:null};Zt.exports=qs});var S=w((Pa,er)=>{"use strict";var Qt=b(),Cs=(e,t,r)=>new Qt(e,r).compare(new Qt(t,r));er.exports=Cs});var rr=w((qa,tr)=>{"use strict";var Ds=S(),Us=(e,t,r)=>Ds(t,e,r);tr.exports=Us});var sr=w((Ca,nr)=>{"use strict";var Fs=S(),zs=(e,t)=>Fs(e,t,!0);nr.exports=zs});var pe=w((Da,ir)=>{"use strict";var or=b(),Gs=(e,t,r)=>{let n=new or(e,r),s=new or(t,r);return n.compare(s)||n.compareBuild(s)};ir.exports=Gs});var ar=w((Ua,cr)=>{"use strict";var Ms=pe(),Ws=(e,t)=>e.sort((r,n)=>Ms(r,n,t));cr.exports=Ws});var ur=w((Fa,lr)=>{"use strict";var _s=pe(),Vs=(e,t)=>e.sort((r,n)=>_s(n,r,t));lr.exports=Vs});var B=w((za,fr)=>{"use strict";var Xs=S(),Bs=(e,t,r)=>Xs(e,t,r)>0;fr.exports=Bs});var he=w((Ga,pr)=>{"use strict";var Hs=S(),Ys=(e,t,r)=>Hs(e,t,r)<0;pr.exports=Ys});var De=w((Ma,hr)=>{"use strict";var Js=S(),Zs=(e,t,r)=>Js(e,t,r)===0;hr.exports=Zs});var Ue=w((Wa,dr)=>{"use strict";var Ks=S(),Qs=(e,t,r)=>Ks(e,t,r)!==0;dr.exports=Qs});var de=w((_a,mr)=>{"use strict";var eo=S(),to=(e,t,r)=>eo(e,t,r)>=0;mr.exports=to});var me=w((Va,wr)=>{"use strict";var ro=S(),no=(e,t,r)=>ro(e,t,r)<=0;wr.exports=no});var Fe=w((Xa,Er)=>{"use strict";var so=De(),oo=Ue(),io=B(),co=de(),ao=he(),lo=me(),uo=(e,t,r,n)=>{switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return so(e,r,n);case"!=":return oo(e,r,n);case">":return io(e,r,n);case">=":return co(e,r,n);case"<":return ao(e,r,n);case"<=":return lo(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};Er.exports=uo});var $r=w((Ba,gr)=>{"use strict";var fo=b(),po=q(),{safeRe:we,t:Ee}=z(),ho=(e,t)=>{if(e instanceof fo)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};let r=null;if(!t.rtl)r=e.match(t.includePrerelease?we[Ee.COERCEFULL]:we[Ee.COERCE]);else{let c=t.includePrerelease?we[Ee.COERCERTLFULL]:we[Ee.COERCERTL],l;for(;(l=c.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||l.index+l[0].length!==r.index+r[0].length)&&(r=l),c.lastIndex=l.index+l[1].length+l[2].length;c.lastIndex=-1}if(r===null)return null;let n=r[2],s=r[3]||"0",o=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return po(`${n}.${s}.${o}${i}${a}`,t)};gr.exports=ho});var xr=w((Ha,yr)=>{"use strict";var ze=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let s=this.map.keys().next().value;this.delete(s)}this.map.set(t,r)}return this}};yr.exports=ze});var L=w((Ya,vr)=>{"use strict";var mo=/\s+/g,Ge=class e{constructor(t,r){if(r=Eo(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof Me)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(mo," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(s=>!br(s[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&Oo(s[0])){this.set=[s];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t0&&(this.formatted+="||");let r=this.set[t];for(let n=0;n0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){let n=((this.options.includePrerelease&&Ro)|(this.options.loose&&bo))+":"+t,s=Rr.get(n);if(s)return s;let o=this.options.loose,i=o?v[O.HYPHENRANGELOOSE]:v[O.HYPHENRANGE];t=t.replace(i,Po(this.options.includePrerelease)),g("hyphen replace",t),t=t.replace(v[O.COMPARATORTRIM],$o),g("comparator trim",t),t=t.replace(v[O.TILDETRIM],yo),g("tilde trim",t),t=t.replace(v[O.CARETTRIM],xo),g("caret trim",t);let a=t.split(" ").map(f=>vo(f,this.options)).join(" ").split(/\s+/).map(f=>jo(f,this.options));o&&(a=a.filter(f=>(g("loose invalid filter",f,this.options),!!f.match(v[O.COMPARATORLOOSE])))),g("range list",a);let c=new Map,l=a.map(f=>new Me(f,this.options));for(let f of l){if(br(f))return[f];c.set(f.value,f)}c.size>1&&c.has("")&&c.delete("");let u=[...c.values()];return Rr.set(n,u),u}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(n=>Or(n,r)&&t.set.some(s=>Or(s,r)&&n.every(o=>s.every(i=>o.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new go(t,this.options)}catch{return!1}for(let r=0;re.value==="<0.0.0-0",Oo=e=>e.value==="",Or=(e,t)=>{let r=!0,n=e.slice(),s=n.pop();for(;r&&n.length;)r=n.every(o=>s.intersects(o,t)),s=n.pop();return r},vo=(e,t)=>(e=e.replace(v[O.BUILD],""),g("comp",e,t),e=ko(e,t),g("caret",e),e=Io(e,t),g("tildes",e),e=Lo(e,t),g("xrange",e),e=To(e,t),g("stars",e),e),I=e=>!e||e.toLowerCase()==="x"||e==="*",Io=(e,t)=>e.trim().split(/\s+/).map(r=>No(r,t)).join(" "),No=(e,t)=>{let r=t.loose?v[O.TILDELOOSE]:v[O.TILDE];return e.replace(r,(n,s,o,i,a)=>{g("tilde",e,n,s,o,i,a);let c;return I(s)?c="":I(o)?c=`>=${s}.0.0 <${+s+1}.0.0-0`:I(i)?c=`>=${s}.${o}.0 <${s}.${+o+1}.0-0`:a?(g("replaceTilde pr",a),c=`>=${s}.${o}.${i}-${a} <${s}.${+o+1}.0-0`):c=`>=${s}.${o}.${i} <${s}.${+o+1}.0-0`,g("tilde return",c),c})},ko=(e,t)=>e.trim().split(/\s+/).map(r=>So(r,t)).join(" "),So=(e,t)=>{g("caret",e,t);let r=t.loose?v[O.CARETLOOSE]:v[O.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(s,o,i,a,c)=>{g("caret",e,s,o,i,a,c);let l;return I(o)?l="":I(i)?l=`>=${o}.0.0${n} <${+o+1}.0.0-0`:I(a)?o==="0"?l=`>=${o}.${i}.0${n} <${o}.${+i+1}.0-0`:l=`>=${o}.${i}.0${n} <${+o+1}.0.0-0`:c?(g("replaceCaret pr",c),o==="0"?i==="0"?l=`>=${o}.${i}.${a}-${c} <${o}.${i}.${+a+1}-0`:l=`>=${o}.${i}.${a}-${c} <${o}.${+i+1}.0-0`:l=`>=${o}.${i}.${a}-${c} <${+o+1}.0.0-0`):(g("no pr"),o==="0"?i==="0"?l=`>=${o}.${i}.${a}${n} <${o}.${i}.${+a+1}-0`:l=`>=${o}.${i}.${a}${n} <${o}.${+i+1}.0-0`:l=`>=${o}.${i}.${a} <${+o+1}.0.0-0`),g("caret return",l),l})},Lo=(e,t)=>(g("replaceXRanges",e,t),e.split(/\s+/).map(r=>Ao(r,t)).join(" ")),Ao=(e,t)=>{e=e.trim();let r=t.loose?v[O.XRANGELOOSE]:v[O.XRANGE];return e.replace(r,(n,s,o,i,a,c)=>{g("xRange",e,n,s,o,i,a,c);let l=I(o),u=l||I(i),f=u||I(a),m=f;return s==="="&&m&&(s=""),c=t.includePrerelease?"-0":"",l?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&m?(u&&(i=0),a=0,s===">"?(s=">=",u?(o=+o+1,i=0,a=0):(i=+i+1,a=0)):s==="<="&&(s="<",u?o=+o+1:i=+i+1),s==="<"&&(c="-0"),n=`${s+o}.${i}.${a}${c}`):u?n=`>=${o}.0.0${c} <${+o+1}.0.0-0`:f&&(n=`>=${o}.${i}.0${c} <${o}.${+i+1}.0-0`),g("xRange return",n),n})},To=(e,t)=>(g("replaceStars",e,t),e.trim().replace(v[O.STAR],"")),jo=(e,t)=>(g("replaceGTE0",e,t),e.trim().replace(v[t.includePrerelease?O.GTE0PRE:O.GTE0],"")),Po=e=>(t,r,n,s,o,i,a,c,l,u,f,m)=>(I(n)?r="":I(s)?r=`>=${n}.0.0${e?"-0":""}`:I(o)?r=`>=${n}.${s}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,I(l)?c="":I(u)?c=`<${+l+1}.0.0-0`:I(f)?c=`<${l}.${+u+1}.0-0`:m?c=`<=${l}.${u}.${f}-${m}`:e?c=`<${l}.${u}.${+f+1}-0`:c=`<=${c}`,`${r} ${c}`.trim()),qo=(e,t,r)=>{for(let n=0;n0){let s=e[n].semver;if(s.major===t.major&&s.minor===t.minor&&s.patch===t.patch)return!0}return!1}return!0}});var H=w((Ja,Ar)=>{"use strict";var Y=Symbol("SemVer ANY"),Ve=class e{static get ANY(){return Y}constructor(t,r){if(r=Ir(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),_e("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===Y?this.value="":this.value=this.operator+this.semver.version,_e("comp",this)}parse(t){let r=this.options.loose?Nr[kr.COMPARATORLOOSE]:Nr[kr.COMPARATOR],n=t.match(r);if(!n)throw new TypeError(`Invalid comparator: ${t}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Sr(n[2],this.options.loose):this.semver=Y}toString(){return this.value}test(t){if(_e("Comparator.test",t,this.options.loose),this.semver===Y||t===Y)return!0;if(typeof t=="string")try{t=new Sr(t,this.options)}catch{return!1}return We(t,this.operator,this.semver,this.options)}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Lr(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new Lr(this.value,r).test(t.semver):(r=Ir(r),r.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||We(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||We(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};Ar.exports=Ve;var Ir=ce(),{safeRe:Nr,t:kr}=z(),We=Fe(),_e=X(),Sr=b(),Lr=L()});var J=w((Za,Tr)=>{"use strict";var Co=L(),Do=(e,t,r)=>{try{t=new Co(t,r)}catch{return!1}return t.test(e)};Tr.exports=Do});var Pr=w((Ka,jr)=>{"use strict";var Uo=L(),Fo=(e,t)=>new Uo(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));jr.exports=Fo});var Cr=w((Qa,qr)=>{"use strict";var zo=b(),Go=L(),Mo=(e,t,r)=>{let n=null,s=null,o=null;try{o=new Go(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===-1)&&(n=i,s=new zo(n,r))}),n};qr.exports=Mo});var Ur=w((el,Dr)=>{"use strict";var Wo=b(),_o=L(),Vo=(e,t,r)=>{let n=null,s=null,o=null;try{o=new _o(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===1)&&(n=i,s=new Wo(n,r))}),n};Dr.exports=Vo});var Gr=w((tl,zr)=>{"use strict";var Xe=b(),Xo=L(),Fr=B(),Bo=(e,t)=>{e=new Xo(e,t);let r=new Xe("0.0.0");if(e.test(r)||(r=new Xe("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n{let a=new Xe(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!o||Fr(a,o))&&(o=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),o&&(!r||Fr(r,o))&&(r=o)}return r&&e.test(r)?r:null};zr.exports=Bo});var Wr=w((rl,Mr)=>{"use strict";var Ho=L(),Yo=(e,t)=>{try{return new Ho(e,t).range||"*"}catch{return null}};Mr.exports=Yo});var ge=w((nl,Br)=>{"use strict";var Jo=b(),Xr=H(),{ANY:Zo}=Xr,Ko=L(),Qo=J(),_r=B(),Vr=he(),ei=me(),ti=de(),ri=(e,t,r,n)=>{e=new Jo(e,n),t=new Ko(t,n);let s,o,i,a,c;switch(r){case">":s=_r,o=ei,i=Vr,a=">",c=">=";break;case"<":s=Vr,o=ti,i=_r,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Qo(e,t,n))return!1;for(let l=0;l{d.semver===Zo&&(d=new Xr(">=0.0.0")),f=f||d,m=m||d,s(d.semver,f.semver,n)?f=d:i(d.semver,m.semver,n)&&(m=d)}),f.operator===a||f.operator===c||(!m.operator||m.operator===a)&&o(e,m.semver))return!1;if(m.operator===c&&i(e,m.semver))return!1}return!0};Br.exports=ri});var Yr=w((sl,Hr)=>{"use strict";var ni=ge(),si=(e,t,r)=>ni(e,t,">",r);Hr.exports=si});var Zr=w((ol,Jr)=>{"use strict";var oi=ge(),ii=(e,t,r)=>oi(e,t,"<",r);Jr.exports=ii});var en=w((il,Qr)=>{"use strict";var Kr=L(),ci=(e,t,r)=>(e=new Kr(e,r),t=new Kr(t,r),e.intersects(t,r));Qr.exports=ci});var rn=w((cl,tn)=>{"use strict";var ai=J(),li=S();tn.exports=(e,t,r)=>{let n=[],s=null,o=null,i=e.sort((u,f)=>li(u,f,r));for(let u of i)ai(u,t,r)?(o=u,s||(s=u)):(o&&n.push([s,o]),o=null,s=null);s&&n.push([s,null]);let a=[];for(let[u,f]of n)u===f?a.push(u):!f&&u===i[0]?a.push("*"):f?u===i[0]?a.push(`<=${f}`):a.push(`${u} - ${f}`):a.push(`>=${u}`);let c=a.join(" || "),l=typeof t.raw=="string"?t.raw:String(t);return c.length{"use strict";var nn=L(),He=H(),{ANY:Be}=He,Z=J(),Ye=S(),ui=(e,t,r={})=>{if(e===t)return!0;e=new nn(e,r),t=new nn(t,r);let n=!1;e:for(let s of e.set){for(let o of t.set){let i=pi(s,o,r);if(n=n||i!==null,i)continue e}if(n)return!1}return!0},fi=[new He(">=0.0.0-0")],sn=[new He(">=0.0.0")],pi=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Be){if(t.length===1&&t[0].semver===Be)return!0;r.includePrerelease?e=fi:e=sn}if(t.length===1&&t[0].semver===Be){if(r.includePrerelease)return!0;t=sn}let n=new Set,s,o;for(let d of e)d.operator===">"||d.operator===">="?s=on(s,d,r):d.operator==="<"||d.operator==="<="?o=cn(o,d,r):n.add(d.semver);if(n.size>1)return null;let i;if(s&&o){if(i=Ye(s.semver,o.semver,r),i>0)return null;if(i===0&&(s.operator!==">="||o.operator!=="<="))return null}for(let d of n){if(s&&!Z(d,String(s),r)||o&&!Z(d,String(o),r))return null;for(let T of t)if(!Z(d,String(T),r))return!1;return!0}let a,c,l,u,f=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:!1,m=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1;f&&f.prerelease.length===1&&o.operator==="<"&&f.prerelease[0]===0&&(f=!1);for(let d of t){if(u=u||d.operator===">"||d.operator===">=",l=l||d.operator==="<"||d.operator==="<=",s){if(m&&d.semver.prerelease&&d.semver.prerelease.length&&d.semver.major===m.major&&d.semver.minor===m.minor&&d.semver.patch===m.patch&&(m=!1),d.operator===">"||d.operator===">="){if(a=on(s,d,r),a===d&&a!==s)return!1}else if(s.operator===">="&&!Z(s.semver,String(d),r))return!1}if(o){if(f&&d.semver.prerelease&&d.semver.prerelease.length&&d.semver.major===f.major&&d.semver.minor===f.minor&&d.semver.patch===f.patch&&(f=!1),d.operator==="<"||d.operator==="<="){if(c=cn(o,d,r),c===d&&c!==o)return!1}else if(o.operator==="<="&&!Z(o.semver,String(d),r))return!1}if(!d.operator&&(o||s)&&i!==0)return!1}return!(s&&l&&!o&&i!==0||o&&u&&!s&&i!==0||m||f)},on=(e,t,r)=>{if(!e)return t;let n=Ye(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},cn=(e,t,r)=>{if(!e)return t;let n=Ye(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};an.exports=ui});var C=w((ll,pn)=>{"use strict";var Je=z(),un=V(),hi=b(),fn=Pe(),di=q(),mi=Ct(),wi=Ut(),Ei=Gt(),gi=_t(),$i=Xt(),yi=Ht(),xi=Jt(),Ri=Kt(),bi=S(),Oi=rr(),vi=sr(),Ii=pe(),Ni=ar(),ki=ur(),Si=B(),Li=he(),Ai=De(),Ti=Ue(),ji=de(),Pi=me(),qi=Fe(),Ci=$r(),Di=H(),Ui=L(),Fi=J(),zi=Pr(),Gi=Cr(),Mi=Ur(),Wi=Gr(),_i=Wr(),Vi=ge(),Xi=Yr(),Bi=Zr(),Hi=en(),Yi=rn(),Ji=ln();pn.exports={parse:di,valid:mi,clean:wi,inc:Ei,diff:gi,major:$i,minor:yi,patch:xi,prerelease:Ri,compare:bi,rcompare:Oi,compareLoose:vi,compareBuild:Ii,sort:Ni,rsort:ki,gt:Si,lt:Li,eq:Ai,neq:Ti,gte:ji,lte:Pi,cmp:qi,coerce:Ci,Comparator:Di,Range:Ui,satisfies:Fi,toComparators:zi,maxSatisfying:Gi,minSatisfying:Mi,minVersion:Wi,validRange:_i,outside:Vi,gtr:Xi,ltr:Bi,intersects:Hi,simplifyRange:Yi,subset:Ji,SemVer:hi,re:Je.re,src:Je.src,tokens:Je.t,SEMVER_SPEC_VERSION:un.SEMVER_SPEC_VERSION,RELEASE_TYPES:un.RELEASE_TYPES,compareIdentifiers:fn.compareIdentifiers,rcompareIdentifiers:fn.rcompareIdentifiers}});var Ae=new TextDecoder;function ie(e){let t=e.indexOf("@",e.startsWith("@")?1:0);return t<0?{name:e,version:""}:{name:e.slice(0,t),version:e.slice(t+1)}}async function yt(e,t){let r=String(t??"").split(/\s+/).filter(o=>o.startsWith("sha512-")).map(o=>o.split("?")[0]);if(r.length===0)throw new Error("The package has no SHA-512 integrity");if(!globalThis.crypto?.subtle)throw new Error("Integrity checks need a secure context (https or localhost)");let n=new Uint8Array(await crypto.subtle.digest("SHA-512",e)),s="sha512-"+btoa(Array.from(n,o=>String.fromCharCode(o)).join(""));if(!r.includes(s))throw new Error(`Integrity check failed: expected ${r[0]}, got ${s}`);return s}async function xt(e,t=268435456){let r=new Blob([e]).stream().pipeThrough(new DecompressionStream("gzip")).getReader(),n=[],s=0;for(let o=await r.read();!o.done;o=await r.read()){if(s+=o.value.length,s>t)throw await r.cancel(),new Error(`The tarball unpacks to more than ${t} bytes`);n.push(o.value)}return new Uint8Array(await new Blob(n).arrayBuffer())}function _(e,t,r){let n=e.subarray(t,t+r),s=n.indexOf(0);return Ae.decode(s<0?n:n.subarray(0,s))}function Rt(e,t,r){if(e[t]&128)return e.subarray(t+1,t+r).reduce((s,o)=>s*256+o,e[t]&127);let n=_(e,t,r).trim();if(!/^[0-7]*$/.test(n))throw new Error("Corrupt tar header");return n===""?0:parseInt(n,8)}function Jn(e){let t=0;for(let r=0;r<512;++r)t+=r>=148&&r<156?32:e[r];if(Rt(e,148,8)!==t)throw new Error("Corrupt tar header checksum")}function Zn(e){let t={},r=0;for(;r0)||r+s>e.length)throw new Error("Corrupt pax header");let o=Ae.decode(e.subarray(n+1,r+s-1)),i=o.indexOf("=");t[o.slice(0,i)]=o.slice(i+1),r+=s}return t}function Kn(e,t){let r=e.subarray(t,t+512);Jn(r);let n=Rt(r,124,12),s=t+512;if(s+n>e.length)throw new Error("Truncated tar archive");return{header:r,type:r[156]===0?"0":String.fromCharCode(r[156]),data:e.subarray(s,s+n),next:s+Math.ceil(n/512)*512}}function Qn(e,t){return t+512>e.length||e.subarray(t,t+512).every(r=>r===0)}function es(e){let t=_(e,0,100),r=_(e,257,5)==="ustar"?_(e,345,155):"";return r?`${r}/${t}`:t}var $t={x:(e,t)=>({...e,pax:Zn(t).path}),L:(e,t)=>({...e,long:_(t,0,t.length)}),g:e=>e};function bt(e){let t=[],r={};for(let n=0;!Qn(e,n);){let{header:s,type:o,data:i,next:a}=Kn(e,n);if(n=a,Object.hasOwn($t,o)){r=$t[o](r,i);continue}(o==="0"||o==="7")&&t.push({path:r.pax??r.long??es(s),bytes:i}),r={}}return t}var xe=F(C(),1);var R=(e,t,...r)=>e.cppFunction(`webfront.developer.${t}`)(...r);async function G(e,t){let r=[],n=0;for(;;){let s=await R(e,"read",t,n);if(r.push(s),n+=s.length,s.length<262144)break;if(n>256*1024*1024)throw new Error("Project file is too large")}return new Uint8Array(await new Blob(r).arrayBuffer())}async function K(e,{id:t,path:r,bytes:n},s){for(let o=0;o{}),a}}async function Zi(e,t){let r=[],n=0;for(;;){let{done:s,value:o}=await e.read();if(s)return r;if(n+=o.length,n>t)throw new Error("Compressed download exceeds its byte limit");r.push(o)}}async function Ki(e,t){try{return await Zi(e,t)}catch(r){throw await e.cancel().catch(()=>{}),r}finally{e.releaseLock()}}async function hn(e,t=64*1024*1024){if(!e.ok)throw new Error(`Download: HTTP ${e.status}`);if(Number(e.headers.get("content-length"))>t)throw new Error("Compressed download exceeds its byte limit");return new Uint8Array(await new Blob(await Ki(e.body.getReader(),t)).arrayBuffer())}var M=".webfront/developer/packages",Qi=/[\\\0:*?"<>|]/,ec=e=>e.split("/").some(t=>!t||t==="."||t==="..");function Ze(e){return typeof e!="string"||!e||Qi.test(e)?!0:ec(e)}function A(e){if(Ze(e))throw new Error(`Unsafe package path: ${e}`);return e}var tc=new TextDecoder,rc=["preinstall","install","postinstall"];async function dn(e){let t=new Map,r;for(let n of bt(await xt(e))){let s=n.path.indexOf("/"),o=n.path.slice(0,s);if(s<1||o==="."||o===".."||(r??(r=o))!==o)throw new Error("Invalid npm tarball root");let i=A(n.path.slice(s+1));if(t.has(i))throw new Error(`Duplicate package path: ${i}`);t.set(i,n.bytes)}return t}var nc=e=>rc.some(t=>e.scripts?.[t]),sc=e=>e.has("binding.gyp")||[...e.keys()].some(t=>t.endsWith(".node"));function oc(e,t){return nc(e)||e.gypfile?!0:sc(t)}function mn(e,t,r){let n=JSON.parse(tc.decode(e.get("package.json")));if(n.name!==t||n.version!==r)throw new Error("npm archive identity mismatch");if(oc(n,e))throw new Error(`${t} needs an unsupported install script or native module`);return n}function W(e){return!e||typeof e!="object"?!1:!Array.isArray(e)}var Ke="webfront.project.json",Qe="webfront-packages.lock.json",x=Ke,N=Qe;function ic(e){if(e===void 0||e==="")return"";if(typeof e!="string"||e.endsWith("/")||Ze(e)||e===".webfront"||e.startsWith(".webfront/"))throw new Error(`Unsafe manifest directory: ${e}`);return e}function xl(e){let t=ic(e);x=t?`${t}/${Ke}`:Ke,N=t?`${t}/${Qe}`:Qe}var ee=1,et=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,cc=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,ac=/^[0-9A-Za-z.+\-^~<>=*| ]{1,128}$/,wn=/^[A-Za-z0-9][A-Za-z0-9:_.-]{0,63}$/,tt=/^[A-Za-z_][A-Za-z0-9_]*$/,En=["format","name","version","dependencies","registry","scripts","entries","providers","test","permissions"],lc=["files","publish","fetch"],y=e=>{throw new Error(`${x}: ${e}`)};function P(e,t){return W(e)||y(`${t} must be an object`),e}function rt(e,t,r){for(let n of Object.keys(e))t.includes(n)||y(`unknown key "${n}" in ${r}`)}function $e(e,t){typeof e!="string"&&y(`${t} must be a project path`);try{return A(e)}catch{return y(`${t} is not a safe project-relative path: ${e}`)}}function gn(e,t){return(!Array.isArray(e)||e.length>256)&&y(`${t} must be an array of at most 256 paths`),e.map((r,n)=>$e(r,`${t}[${n}]`))}function uc(e){let t=P(e,"dependencies");for(let[r,n]of Object.entries(t))et.test(r)||y(`invalid npm package name "${r}"`),(typeof n!="string"||!ac.test(n)||n!==n.trim())&&y(`invalid version range for "${r}"`);return t}var nt=e=>e.startsWith("/")&&!e.startsWith("//")&&!e.includes("\\");function fc(e){if(typeof e!="string"&&y("registry must be a URL"),nt(e))return e;let t;try{t=new URL(e)}catch{return y("registry must be an https URL or an absolute path")}return t.protocol!=="https:"&&y("registry must use https"),e}function pc(e){let t=P(e,"scripts");for(let[r,n]of Object.entries(t))(!wn.test(r)||typeof n!="string"||!n||n.length>1024)&&y(`invalid script "${r}"`);return t}function hc(e){let t=P(e,"entries");for(let[r,n]of Object.entries(t))wn.test(r)||y(`invalid entry name "${r}"`),$e(n,`entries.${r}`);return t}function dc(e,t){let r=P(e,"providers");for(let[n,s]of Object.entries(r))tt.test(n)||y(`invalid provider name "${n}"`),P(s,`providers.${n}`),rt(s,["entry","output"],`providers.${n}`),typeof s.entry!="string"&&y(`providers.${n}.entry must name an entry or a path`),Object.hasOwn(t,s.entry)||$e(s.entry,`providers.${n}.entry`),$e(s.output,`providers.${n}.output`).endsWith(".hpp")||y(`providers.${n}.output must be a .hpp file`);return r}function mc(e){let t=P(e,"test");return rt(t,["specs"],"test"),t.specs!==void 0&&gn(t.specs,"test.specs"),t}function wc(e,t){let r;try{r=new URL(e)}catch{return y(`${t} must be an https origin`)}return(r.protocol!=="https:"||r.origin!==e)&&y(`${t} must be an https origin without a path`),e}function Ec(e){let t=P(e,"permissions");for(let r of Object.keys(t))lc.includes(r)||y(`unknown permission "${r}"`);for(let r of["files","publish"])t[r]!==void 0&&gn(t[r],`permissions.${r}`);return t.fetch!==void 0&&((!Array.isArray(t.fetch)||t.fetch.length>64)&&y("permissions.fetch must be an array of origins"),t.fetch.forEach((r,n)=>wc(r,`permissions.fetch[${n}]`))),t}function gc(e){(typeof e.name!="string"||!et.test(e.name))&&y("name must be a lower-case npm package name"),(typeof e.version!="string"||!cc.test(e.version))&&y("version must be a semantic version")}function $c(e){e.format!==ee&&(Number.isInteger(e.format)&&e.format>ee&&y(`format ${e.format} is not supported by this environment (it reads format ${ee}); update the environment`),y(`format must be ${ee}`))}function te(e){P(e,"the manifest"),$c(e),rt(e,En,"the manifest"),gc(e);let t=e.entries===void 0?{}:hc(e.entries);return{...e,dependencies:e.dependencies===void 0?{}:uc(e.dependencies),entries:t,providers:e.providers===void 0?{}:dc(e.providers,t),...e.registry===void 0?{}:{registry:fc(e.registry)},...e.scripts===void 0?{}:{scripts:pc(e.scripts)},...e.test===void 0?{}:{test:mc(e.test)},...e.permissions===void 0?{}:{permissions:Ec(e.permissions)}}}function st(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return y("not valid JSON")}return{source:t,manifest:te(t)}}function Rl(e){return st(e).manifest}function ot(e){let t={};for(let r of En)e[r]!==void 0&&(t[r]=e[r]);return JSON.stringify(t,null,2)+` -`}function $n(e){return{format:ee,name:e,version:"0.1.0",dependencies:{}}}function yn(e){let r=(String(e??"").split("/").filter(Boolean).pop()??"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[^a-z0-9]+/,"").replace(/-+$/,"");return et.test(r)?r:"webfront-app"}async function ye(e){let t=JSON.stringify(Object.entries(e).sort(([n],[s])=>ns?1:0)),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return[...new Uint8Array(r)].map(n=>n.toString(16).padStart(2,"0")).join("")}var it=e=>/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(e),Re=(e,t)=>`${e.replace("/","+")}@${t}`,ct=(e,t,r)=>`${Re(e,t)}-${r.slice(7).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}`;async function yc(e,t,{fetchImpl:r,signal:n}){let s=await r(new URL(e.replace("/","%2f"),t),{signal:n});if(!s.ok)throw new Error(`Registry metadata for ${e}: HTTP ${s.status}`);return s.json()}function xc(e,t){let r=e["dist-tags"]?.[t];return r||(xe.default.valid(t)?t:xe.default.maxSatisfying(Object.keys(e.versions??{}),t))}function Rc(e,t,r){let n=r||"latest",s=xc(e,n),o=e.versions?.[s];if(!o||!xe.default.valid(s))throw new Error(`Cannot resolve ${t}@${n}`);return{version:s,manifest:o}}async function bc(e,t,r,{fetchImpl:n,signal:s}){let o=new URL(t.dist?.tarball,r);if(o.protocol!=="https:"&&o.origin!==r.origin)throw new Error("Package tarballs must use HTTPS or the registry origin");let i=await n(o,{signal:s});if(!i.ok)throw new Error(`Package download for ${e}: HTTP ${i.status}`);let a=await hn(i);return{bytes:a,integrity:await yt(a,t.dist.integrity)}}function at(e){let t=new URL(e,globalThis.location?.href),r=t.origin===globalThis.location?.origin;if(e.startsWith("/")?!nt(e)||!r:t.protocol!=="https:"&&!r)throw new Error(`The npm registry must use HTTPS or the application origin: ${e}`);return t.pathname.endsWith("/")||(t.pathname+="/"),t}async function D(e,t,{registry:r,fetchImpl:n=fetch,signal:s}){if(!it(e))throw new Error(`Unsupported npm package name: ${e}`);let o=at(r),i={fetchImpl:n,signal:s},{version:a,manifest:c}=Rc(await yc(e,o,i),e,t),{bytes:l,integrity:u}=await bc(e,c,o,i),f=await dn(l),m=mn(f,e,a);return{id:Re(e,a),key:ct(e,a,u),manifest:m,integrity:u,files:f}}var be=F(C(),1);function Oc(e,t,r){let n=e?.roots?.[t];return n?.requested===r&&e.packages[n.id]?e.packages[n.id]:be.default.validRange(r)?Object.values(e?.packages??{}).filter(o=>o.name===t&&be.default.satisfies(o.version,r)).sort((o,i)=>be.default.rcompare(o.version,i.version))[0]??null:null}function xn({registry:e="https://registry.npmjs.org/",fetchImpl:t=fetch,signal:r,download:n=D,previous:s}){let o=new Map;return async(i,a)=>{let c=`${i}@${a}`;if(o.has(c))return o.get(c);let l=Oc(s,i,a),u=await n(i,l?.version??a,{registry:e,fetchImpl:t,signal:r});if(l&&u.integrity!==l.integrity)throw new Error(`${u.id} no longer matches the integrity recorded in the lock`);return o.set(c,u),u}}var Rn=F(C(),1),bn=(e,t,r)=>new Error(`${e.name}@${e.version} requires peer ${t}@${r}; install a compatible root explicitly`);function vc(e,t,r){if(e.manifest.peerDependenciesMeta?.[t]?.optional)return null;throw bn(e,t,r)}function Ic(e,[t,r],{nodes:n,roots:s}){let o=s[t]?.id??e.dependencies[t];if(!o)return vc(e,t,r);if(!Rn.default.satisfies(n[o].version,r))throw bn(e,t,r);return o}function Nc(e,t){for(let r of Object.entries(e.manifest.peerDependencies??{})){let n=Ic(e,r,t);n&&(e.dependencies[r[0]]=n)}}function On(e,t){for(let r of Object.values(e))Nc(r,{nodes:e,roots:t})}var vn=F(C(),1);function kc(e,t){return!it(t.name)||!vn.default.valid(t.version)?!1:e===Re(t.name,t.version)}function Sc(e){return e.integrity?.startsWith("sha512-")?e.key===ct(e.name,e.version,e.integrity):!1}function Lc(e,t,r){if(!kc(t,r)||!Sc(r))throw new Error("Invalid locked package");for(let n of r.files)A(n);if(Object.values(r.dependencies).some(n=>!e.packages[n]))throw new Error("Dangling locked dependency")}function Ac(e){return e?.format!==1?!1:!!e.roots&&!!e.packages}function lt(e){if(!Ac(e))throw new Error("Unsupported package lock");if(Object.keys(e.packages).length>512)throw new Error("The package lock exceeds 512 packages");for(let[t,r]of Object.entries(e.packages))Lc(e,t,r);if(Object.values(e.roots).some(t=>!e.packages[t.id]))throw new Error("Dangling locked root");return e}function Tc(e,t,r){if(Object.keys(e.nodes).length>=512)throw new Error("Dependency graph exceeds 512 packages");for(let n of r.files.values())e.total+=n.length;if(e.total>256*1024*1024)throw new Error("Dependency graph exceeds 256 MiB");e.nodes[r.id]={name:t,version:r.manifest.version,integrity:r.integrity,key:r.key,manifest:r.manifest,files:[...r.files.keys()].sort(),dependencies:{}},e.downloads.set(r.id,r.files)}async function jc(e,t){let r={};for(let n of e){let{name:s,version:o}=ie(n);r[s]={requested:o||"latest",id:await t(s,o||"latest")}}return r}async function In(e,t={}){let r=xn(t),n={nodes:{},downloads:new Map,total:0},s=async(i,a)=>{t.signal?.throwIfAborted();let c=await r(i,a);if(n.nodes[c.id])return c.id;Tc(n,i,c);for(let[l,u]of Object.entries(c.manifest.dependencies??{}).sort())n.nodes[c.id].dependencies[l]=await s(l,u);return c.id},o=await jc(e,s);return On(n.nodes,o),{lock:{format:1,registry:t.registry??"https://registry.npmjs.org/",roots:o,packages:n.nodes},downloads:n.downloads}}var ut=F(C(),1);var Pc=new TextDecoder,qc=new TextEncoder,Oe="No webfront.project.json: run wf init",ve="The lock does not match the dependencies of webfront.project.json; run wf install --update to resolve them again";async function Nn(e,t){try{return await G(e,t)}catch(r){if(r.message.includes("Cannot read project file:"))return null;throw r}}function Cc(e,t,r){return t?r===t.requested?!0:ut.default.validRange(r)!==null&&ut.default.satisfies(e.packages[t.id].version,r):!1}function Dc(e,t){let r=Object.keys(t);return r.length===Object.keys(e.roots).length&&r.every(n=>Cc(e,e.roots[n],t[n]))}function Uc(e,t,r){return e?t?t.manifestDigest===void 0?Dc(t,e.dependencies)?"legacy":"desynchronized":t.manifestDigest===r?"consistent":"desynchronized":"unlocked":"no-manifest"}async function re(e){let t=await R(e,"state",`${x} -${N}`),r=await Nn(e,x),n=await Nn(e,N),{source:s,manifest:o}=r?st(r):{source:null,manifest:null},i=n?lt(JSON.parse(Pc.decode(n))):null,a=o?await ye(o.dependencies):null;return{manifest:o,source:s,lock:i,token:t,status:Uc(o,i,a),digest:a}}var Sn=e=>e.status==="desynchronized"?`Warning: ${ve}.\r -`:"";async function Ln(e,t,r,{signal:n}={}){let s=[];try{for(let[o,i]of t){n?.throwIfAborted();let a=await R(e,"begin",o,!1);s.push(a),await K(e,{id:a,path:"output",bytes:i},n)}n?.throwIfAborted(),await R(e,"commitGroup",s.join(` +var Xn=Object.create;var gt=Object.defineProperty;var Vn=Object.getOwnPropertyDescriptor;var Bn=Object.getOwnPropertyNames;var Hn=Object.getPrototypeOf,Kn=Object.prototype.hasOwnProperty;var w=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Yn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Bn(t))!Kn.call(e,s)&&s!==r&>(e,s,{get:()=>t[s],enumerable:!(n=Vn(t,s))||n.enumerable});return e};var F=(e,t,r)=>(r=e!=null?Xn(Hn(e)):{},Yn(t||!e||!e.__esModule?gt(r,"default",{value:e,enumerable:!0}):r,e));var X=w((bc,Ot)=>{"use strict";var rs="2.0.0",ns=Number.MAX_SAFE_INTEGER||9007199254740991,ss=16,os=250,is=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Ot.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:ss,MAX_SAFE_BUILD_LENGTH:os,MAX_SAFE_INTEGER:ns,RELEASE_TYPES:is,SEMVER_SPEC_VERSION:rs,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var V=w((Oc,vt)=>{"use strict";var as=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};vt.exports=as});var z=w((j,It)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:je,MAX_SAFE_BUILD_LENGTH:cs,MAX_LENGTH:ls}=X(),us=V();j=It.exports={};var fs=j.re=[],ps=j.safeRe=[],p=j.src=[],hs=j.safeSrc=[],h=j.t={},ds=0,Pe="[a-zA-Z0-9-]",ms=[["\\s",1],["\\d",ls],[Pe,cs]],ws=e=>{for(let[t,r]of ms)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let n=ws(t),s=ds++;us(e,s,t),h[e]=s,p[s]=t,hs[s]=n,fs[s]=new RegExp(t,r?"g":void 0),ps[s]=new RegExp(n,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Pe}*`);E("MAINVERSION",`(${p[h.NUMERICIDENTIFIER]})\\.(${p[h.NUMERICIDENTIFIER]})\\.(${p[h.NUMERICIDENTIFIER]})`);E("MAINVERSIONLOOSE",`(${p[h.NUMERICIDENTIFIERLOOSE]})\\.(${p[h.NUMERICIDENTIFIERLOOSE]})\\.(${p[h.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASEIDENTIFIER",`(?:${p[h.NONNUMERICIDENTIFIER]}|${p[h.NUMERICIDENTIFIER]})`);E("PRERELEASEIDENTIFIERLOOSE",`(?:${p[h.NONNUMERICIDENTIFIER]}|${p[h.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASE",`(?:-(${p[h.PRERELEASEIDENTIFIER]}(?:\\.${p[h.PRERELEASEIDENTIFIER]})*))`);E("PRERELEASELOOSE",`(?:-?(${p[h.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${p[h.PRERELEASEIDENTIFIERLOOSE]})*))`);E("BUILDIDENTIFIER",`${Pe}+`);E("BUILD",`(?:\\+(${p[h.BUILDIDENTIFIER]}(?:\\.${p[h.BUILDIDENTIFIER]})*))`);E("FULLPLAIN",`v?${p[h.MAINVERSION]}${p[h.PRERELEASE]}?${p[h.BUILD]}?`);E("FULL",`^${p[h.FULLPLAIN]}$`);E("LOOSEPLAIN",`[v=\\s]*${p[h.MAINVERSIONLOOSE]}${p[h.PRERELEASELOOSE]}?${p[h.BUILD]}?`);E("LOOSE",`^${p[h.LOOSEPLAIN]}$`);E("GTLT","((?:<|>)?=?)");E("XRANGEIDENTIFIERLOOSE",`${p[h.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);E("XRANGEIDENTIFIER",`${p[h.NUMERICIDENTIFIER]}|x|X|\\*`);E("XRANGEPLAIN",`[v=\\s]*(${p[h.XRANGEIDENTIFIER]})(?:\\.(${p[h.XRANGEIDENTIFIER]})(?:\\.(${p[h.XRANGEIDENTIFIER]})(?:${p[h.PRERELEASE]})?${p[h.BUILD]}?)?)?`);E("XRANGEPLAINLOOSE",`[v=\\s]*(${p[h.XRANGEIDENTIFIERLOOSE]})(?:\\.(${p[h.XRANGEIDENTIFIERLOOSE]})(?:\\.(${p[h.XRANGEIDENTIFIERLOOSE]})(?:${p[h.PRERELEASELOOSE]})?${p[h.BUILD]}?)?)?`);E("XRANGE",`^${p[h.GTLT]}\\s*${p[h.XRANGEPLAIN]}$`);E("XRANGELOOSE",`^${p[h.GTLT]}\\s*${p[h.XRANGEPLAINLOOSE]}$`);E("COERCEPLAIN",`(^|[^\\d])(\\d{1,${je}})(?:\\.(\\d{1,${je}}))?(?:\\.(\\d{1,${je}}))?`);E("COERCE",`${p[h.COERCEPLAIN]}(?:$|[^\\d])`);E("COERCEFULL",p[h.COERCEPLAIN]+`(?:${p[h.PRERELEASE]})?(?:${p[h.BUILD]})?(?:$|[^\\d])`);E("COERCERTL",p[h.COERCE],!0);E("COERCERTLFULL",p[h.COERCEFULL],!0);E("LONETILDE","(?:~>?)");E("TILDETRIM",`(\\s*)${p[h.LONETILDE]}\\s+`,!0);j.tildeTrimReplace="$1~";E("TILDE",`^${p[h.LONETILDE]}${p[h.XRANGEPLAIN]}$`);E("TILDELOOSE",`^${p[h.LONETILDE]}${p[h.XRANGEPLAINLOOSE]}$`);E("LONECARET","(?:\\^)");E("CARETTRIM",`(\\s*)${p[h.LONECARET]}\\s+`,!0);j.caretTrimReplace="$1^";E("CARET",`^${p[h.LONECARET]}${p[h.XRANGEPLAIN]}$`);E("CARETLOOSE",`^${p[h.LONECARET]}${p[h.XRANGEPLAINLOOSE]}$`);E("COMPARATORLOOSE",`^${p[h.GTLT]}\\s*(${p[h.LOOSEPLAIN]})$|^$`);E("COMPARATOR",`^${p[h.GTLT]}\\s*(${p[h.FULLPLAIN]})$|^$`);E("COMPARATORTRIM",`(\\s*)${p[h.GTLT]}\\s*(${p[h.LOOSEPLAIN]}|${p[h.XRANGEPLAIN]})`,!0);j.comparatorTrimReplace="$1$2$3";E("HYPHENRANGE",`^\\s*(${p[h.XRANGEPLAIN]})\\s+-\\s+(${p[h.XRANGEPLAIN]})\\s*$`);E("HYPHENRANGELOOSE",`^\\s*(${p[h.XRANGEPLAINLOOSE]})\\s+-\\s+(${p[h.XRANGEPLAINLOOSE]})\\s*$`);E("STAR","(<|>)?=?\\s*\\*");E("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");E("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var ae=w((vc,St)=>{"use strict";var Es=Object.freeze({loose:!0}),gs=Object.freeze({}),ys=e=>e?typeof e!="object"?Es:e:gs;St.exports=ys});var qe=w((Ic,Lt)=>{"use strict";var kt=/^[0-9]+$/,Nt=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:eNt(t,e);Lt.exports={compareIdentifiers:Nt,rcompareIdentifiers:$s}});var b=w((Sc,Tt)=>{"use strict";var ce=V(),{MAX_LENGTH:At,MAX_SAFE_INTEGER:le}=X(),{safeRe:ue,t:fe}=z(),xs=ae(),{compareIdentifiers:Ce}=qe(),De=class e{constructor(t,r){if(r=xs(r),t instanceof e){if(t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease)return t;t=t.version}else if(typeof t!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>At)throw new TypeError(`version is longer than ${At} characters`);ce("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?ue[fe.LOOSE]:ue[fe.FULL]);if(!n)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>le||this.major<0)throw new TypeError("Invalid major version");if(this.minor>le||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>le||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let o=+s;if(o>=0&&ot.major?1:this.minort.minor?1:this.patcht.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let n=this.prerelease[r],s=t.prerelease[r];if(ce("prerelease compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Ce(n,s)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let n=this.build[r],s=t.build[r];if(ce("build compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Ce(n,s)}while(++r)}inc(t,r,n){if(t.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let s=`-${r}`.match(this.options.loose?ue[fe.PRERELEASELOOSE]:ue[fe.PRERELEASE]);if(!s||s[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let s=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[s];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(r){let o=[r,s];n===!1&&(o=[r]),Ce(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=o):this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Tt.exports=De});var q=w((kc,Pt)=>{"use strict";var jt=b(),Rs=(e,t,r=!1)=>{if(e instanceof jt)return e;try{return new jt(e,t)}catch(n){if(!r)return null;throw n}};Pt.exports=Rs});var Ct=w((Nc,qt)=>{"use strict";var bs=q(),Os=(e,t)=>{let r=bs(e,t);return r?r.version:null};qt.exports=Os});var Ut=w((Lc,Dt)=>{"use strict";var vs=q(),Is=(e,t)=>{let r=vs(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};Dt.exports=Is});var Gt=w((Ac,zt)=>{"use strict";var Ft=b(),Ss=(e,t,r,n,s)=>{typeof r=="string"&&(s=n,n=r,r=void 0);try{return new Ft(e instanceof Ft?e.version:e,r).inc(t,n,s).version}catch{return null}};zt.exports=Ss});var _t=w((Tc,Wt)=>{"use strict";var Mt=q(),ks=(e,t)=>{let r=Mt(e,null,!0),n=Mt(t,null,!0),s=r.compare(n);if(s===0)return null;let o=s>0,i=o?r:n,c=o?n:r,a=!!i.prerelease.length;if(!!c.prerelease.length&&!a){if(!c.patch&&!c.minor)return"major";if(c.compareMain(i)===0)return c.minor&&!c.patch?"minor":"patch"}let u=a?"pre":"";return r.major!==n.major?u+"major":r.minor!==n.minor?u+"minor":r.patch!==n.patch?u+"patch":"prerelease"};Wt.exports=ks});var Vt=w((jc,Xt)=>{"use strict";var Ns=b(),Ls=(e,t)=>new Ns(e,t).major;Xt.exports=Ls});var Ht=w((Pc,Bt)=>{"use strict";var As=b(),Ts=(e,t)=>new As(e,t).minor;Bt.exports=Ts});var Yt=w((qc,Kt)=>{"use strict";var js=b(),Ps=(e,t)=>new js(e,t).patch;Kt.exports=Ps});var Zt=w((Cc,Jt)=>{"use strict";var qs=q(),Cs=(e,t)=>{let r=qs(e,t);return r&&r.prerelease.length?r.prerelease:null};Jt.exports=Cs});var N=w((Dc,er)=>{"use strict";var Qt=b(),Ds=(e,t,r)=>new Qt(e,r).compare(new Qt(t,r));er.exports=Ds});var rr=w((Uc,tr)=>{"use strict";var Us=N(),Fs=(e,t,r)=>Us(t,e,r);tr.exports=Fs});var sr=w((Fc,nr)=>{"use strict";var zs=N(),Gs=(e,t)=>zs(e,t,!0);nr.exports=Gs});var pe=w((zc,ir)=>{"use strict";var or=b(),Ms=(e,t,r)=>{let n=new or(e,r),s=new or(t,r);return n.compare(s)||n.compareBuild(s)};ir.exports=Ms});var cr=w((Gc,ar)=>{"use strict";var Ws=pe(),_s=(e,t)=>e.sort((r,n)=>Ws(r,n,t));ar.exports=_s});var ur=w((Mc,lr)=>{"use strict";var Xs=pe(),Vs=(e,t)=>e.sort((r,n)=>Xs(n,r,t));lr.exports=Vs});var B=w((Wc,fr)=>{"use strict";var Bs=N(),Hs=(e,t,r)=>Bs(e,t,r)>0;fr.exports=Hs});var he=w((_c,pr)=>{"use strict";var Ks=N(),Ys=(e,t,r)=>Ks(e,t,r)<0;pr.exports=Ys});var Ue=w((Xc,hr)=>{"use strict";var Js=N(),Zs=(e,t,r)=>Js(e,t,r)===0;hr.exports=Zs});var Fe=w((Vc,dr)=>{"use strict";var Qs=N(),eo=(e,t,r)=>Qs(e,t,r)!==0;dr.exports=eo});var de=w((Bc,mr)=>{"use strict";var to=N(),ro=(e,t,r)=>to(e,t,r)>=0;mr.exports=ro});var me=w((Hc,wr)=>{"use strict";var no=N(),so=(e,t,r)=>no(e,t,r)<=0;wr.exports=so});var ze=w((Kc,Er)=>{"use strict";var oo=Ue(),io=Fe(),ao=B(),co=de(),lo=he(),uo=me(),fo=(e,t,r,n)=>{switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return oo(e,r,n);case"!=":return io(e,r,n);case">":return ao(e,r,n);case">=":return co(e,r,n);case"<":return lo(e,r,n);case"<=":return uo(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};Er.exports=fo});var yr=w((Yc,gr)=>{"use strict";var po=b(),ho=q(),{safeRe:we,t:Ee}=z(),mo=(e,t)=>{if(e instanceof po)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};let r=null;if(!t.rtl)r=e.match(t.includePrerelease?we[Ee.COERCEFULL]:we[Ee.COERCE]);else{let a=t.includePrerelease?we[Ee.COERCERTLFULL]:we[Ee.COERCERTL],l;for(;(l=a.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||l.index+l[0].length!==r.index+r[0].length)&&(r=l),a.lastIndex=l.index+l[1].length+l[2].length;a.lastIndex=-1}if(r===null)return null;let n=r[2],s=r[3]||"0",o=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",c=t.includePrerelease&&r[6]?`+${r[6]}`:"";return ho(`${n}.${s}.${o}${i}${c}`,t)};gr.exports=mo});var xr=w((Jc,$r)=>{"use strict";var Ge=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let s=this.map.keys().next().value;this.delete(s)}this.map.set(t,r)}return this}};$r.exports=Ge});var L=w((Zc,vr)=>{"use strict";var wo=/\s+/g,Me=class e{constructor(t,r){if(r=go(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof We)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(wo," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(s=>!br(s[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&vo(s[0])){this.set=[s];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t0&&(this.formatted+="||");let r=this.set[t];for(let n=0;n0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){let n=((this.options.includePrerelease&&bo)|(this.options.loose&&Oo))+":"+t,s=Rr.get(n);if(s)return s;let o=this.options.loose,i=o?v[O.HYPHENRANGELOOSE]:v[O.HYPHENRANGE];t=t.replace(i,qo(this.options.includePrerelease)),g("hyphen replace",t),t=t.replace(v[O.COMPARATORTRIM],$o),g("comparator trim",t),t=t.replace(v[O.TILDETRIM],xo),g("tilde trim",t),t=t.replace(v[O.CARETTRIM],Ro),g("caret trim",t);let c=t.split(" ").map(f=>Io(f,this.options)).join(" ").split(/\s+/).map(f=>Po(f,this.options));o&&(c=c.filter(f=>(g("loose invalid filter",f,this.options),!!f.match(v[O.COMPARATORLOOSE])))),g("range list",c);let a=new Map,l=c.map(f=>new We(f,this.options));for(let f of l){if(br(f))return[f];a.set(f.value,f)}a.size>1&&a.has("")&&a.delete("");let u=[...a.values()];return Rr.set(n,u),u}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(n=>Or(n,r)&&t.set.some(s=>Or(s,r)&&n.every(o=>s.every(i=>o.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new yo(t,this.options)}catch{return!1}for(let r=0;re.value==="<0.0.0-0",vo=e=>e.value==="",Or=(e,t)=>{let r=!0,n=e.slice(),s=n.pop();for(;r&&n.length;)r=n.every(o=>s.intersects(o,t)),s=n.pop();return r},Io=(e,t)=>(e=e.replace(v[O.BUILD],""),g("comp",e,t),e=No(e,t),g("caret",e),e=So(e,t),g("tildes",e),e=Ao(e,t),g("xrange",e),e=jo(e,t),g("stars",e),e),I=e=>!e||e.toLowerCase()==="x"||e==="*",So=(e,t)=>e.trim().split(/\s+/).map(r=>ko(r,t)).join(" "),ko=(e,t)=>{let r=t.loose?v[O.TILDELOOSE]:v[O.TILDE];return e.replace(r,(n,s,o,i,c)=>{g("tilde",e,n,s,o,i,c);let a;return I(s)?a="":I(o)?a=`>=${s}.0.0 <${+s+1}.0.0-0`:I(i)?a=`>=${s}.${o}.0 <${s}.${+o+1}.0-0`:c?(g("replaceTilde pr",c),a=`>=${s}.${o}.${i}-${c} <${s}.${+o+1}.0-0`):a=`>=${s}.${o}.${i} <${s}.${+o+1}.0-0`,g("tilde return",a),a})},No=(e,t)=>e.trim().split(/\s+/).map(r=>Lo(r,t)).join(" "),Lo=(e,t)=>{g("caret",e,t);let r=t.loose?v[O.CARETLOOSE]:v[O.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(s,o,i,c,a)=>{g("caret",e,s,o,i,c,a);let l;return I(o)?l="":I(i)?l=`>=${o}.0.0${n} <${+o+1}.0.0-0`:I(c)?o==="0"?l=`>=${o}.${i}.0${n} <${o}.${+i+1}.0-0`:l=`>=${o}.${i}.0${n} <${+o+1}.0.0-0`:a?(g("replaceCaret pr",a),o==="0"?i==="0"?l=`>=${o}.${i}.${c}-${a} <${o}.${i}.${+c+1}-0`:l=`>=${o}.${i}.${c}-${a} <${o}.${+i+1}.0-0`:l=`>=${o}.${i}.${c}-${a} <${+o+1}.0.0-0`):(g("no pr"),o==="0"?i==="0"?l=`>=${o}.${i}.${c}${n} <${o}.${i}.${+c+1}-0`:l=`>=${o}.${i}.${c}${n} <${o}.${+i+1}.0-0`:l=`>=${o}.${i}.${c} <${+o+1}.0.0-0`),g("caret return",l),l})},Ao=(e,t)=>(g("replaceXRanges",e,t),e.split(/\s+/).map(r=>To(r,t)).join(" ")),To=(e,t)=>{e=e.trim();let r=t.loose?v[O.XRANGELOOSE]:v[O.XRANGE];return e.replace(r,(n,s,o,i,c,a)=>{g("xRange",e,n,s,o,i,c,a);let l=I(o),u=l||I(i),f=u||I(c),m=f;return s==="="&&m&&(s=""),a=t.includePrerelease?"-0":"",l?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&m?(u&&(i=0),c=0,s===">"?(s=">=",u?(o=+o+1,i=0,c=0):(i=+i+1,c=0)):s==="<="&&(s="<",u?o=+o+1:i=+i+1),s==="<"&&(a="-0"),n=`${s+o}.${i}.${c}${a}`):u?n=`>=${o}.0.0${a} <${+o+1}.0.0-0`:f&&(n=`>=${o}.${i}.0${a} <${o}.${+i+1}.0-0`),g("xRange return",n),n})},jo=(e,t)=>(g("replaceStars",e,t),e.trim().replace(v[O.STAR],"")),Po=(e,t)=>(g("replaceGTE0",e,t),e.trim().replace(v[t.includePrerelease?O.GTE0PRE:O.GTE0],"")),qo=e=>(t,r,n,s,o,i,c,a,l,u,f,m)=>(I(n)?r="":I(s)?r=`>=${n}.0.0${e?"-0":""}`:I(o)?r=`>=${n}.${s}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,I(l)?a="":I(u)?a=`<${+l+1}.0.0-0`:I(f)?a=`<${l}.${+u+1}.0-0`:m?a=`<=${l}.${u}.${f}-${m}`:e?a=`<${l}.${u}.${+f+1}-0`:a=`<=${a}`,`${r} ${a}`.trim()),Co=(e,t,r)=>{for(let n=0;n0){let s=e[n].semver;if(s.major===t.major&&s.minor===t.minor&&s.patch===t.patch)return!0}return!1}return!0}});var H=w((Qc,Ar)=>{"use strict";var K=Symbol("SemVer ANY"),Ve=class e{static get ANY(){return K}constructor(t,r){if(r=Ir(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Xe("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===K?this.value="":this.value=this.operator+this.semver.version,Xe("comp",this)}parse(t){let r=this.options.loose?Sr[kr.COMPARATORLOOSE]:Sr[kr.COMPARATOR],n=t.match(r);if(!n)throw new TypeError(`Invalid comparator: ${t}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Nr(n[2],this.options.loose):this.semver=K}toString(){return this.value}test(t){if(Xe("Comparator.test",t,this.options.loose),this.semver===K||t===K)return!0;if(typeof t=="string")try{t=new Nr(t,this.options)}catch{return!1}return _e(t,this.operator,this.semver,this.options)}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Lr(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new Lr(this.value,r).test(t.semver):(r=Ir(r),r.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||_e(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||_e(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};Ar.exports=Ve;var Ir=ae(),{safeRe:Sr,t:kr}=z(),_e=ze(),Xe=V(),Nr=b(),Lr=L()});var Y=w((el,Tr)=>{"use strict";var Do=L(),Uo=(e,t,r)=>{try{t=new Do(t,r)}catch{return!1}return t.test(e)};Tr.exports=Uo});var Pr=w((tl,jr)=>{"use strict";var Fo=L(),zo=(e,t)=>new Fo(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));jr.exports=zo});var Cr=w((rl,qr)=>{"use strict";var Go=b(),Mo=L(),Wo=(e,t,r)=>{let n=null,s=null,o=null;try{o=new Mo(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===-1)&&(n=i,s=new Go(n,r))}),n};qr.exports=Wo});var Ur=w((nl,Dr)=>{"use strict";var _o=b(),Xo=L(),Vo=(e,t,r)=>{let n=null,s=null,o=null;try{o=new Xo(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===1)&&(n=i,s=new _o(n,r))}),n};Dr.exports=Vo});var Gr=w((sl,zr)=>{"use strict";var Be=b(),Bo=L(),Fr=B(),Ho=(e,t)=>{e=new Bo(e,t);let r=new Be("0.0.0");if(e.test(r)||(r=new Be("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n{let c=new Be(i.semver.version);switch(i.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!o||Fr(c,o))&&(o=c);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),o&&(!r||Fr(r,o))&&(r=o)}return r&&e.test(r)?r:null};zr.exports=Ho});var Wr=w((ol,Mr)=>{"use strict";var Ko=L(),Yo=(e,t)=>{try{return new Ko(e,t).range||"*"}catch{return null}};Mr.exports=Yo});var ge=w((il,Br)=>{"use strict";var Jo=b(),Vr=H(),{ANY:Zo}=Vr,Qo=L(),ei=Y(),_r=B(),Xr=he(),ti=me(),ri=de(),ni=(e,t,r,n)=>{e=new Jo(e,n),t=new Qo(t,n);let s,o,i,c,a;switch(r){case">":s=_r,o=ti,i=Xr,c=">",a=">=";break;case"<":s=Xr,o=ri,i=_r,c="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(ei(e,t,n))return!1;for(let l=0;l{d.semver===Zo&&(d=new Vr(">=0.0.0")),f=f||d,m=m||d,s(d.semver,f.semver,n)?f=d:i(d.semver,m.semver,n)&&(m=d)}),f.operator===c||f.operator===a||(!m.operator||m.operator===c)&&o(e,m.semver))return!1;if(m.operator===a&&i(e,m.semver))return!1}return!0};Br.exports=ni});var Kr=w((al,Hr)=>{"use strict";var si=ge(),oi=(e,t,r)=>si(e,t,">",r);Hr.exports=oi});var Jr=w((cl,Yr)=>{"use strict";var ii=ge(),ai=(e,t,r)=>ii(e,t,"<",r);Yr.exports=ai});var en=w((ll,Qr)=>{"use strict";var Zr=L(),ci=(e,t,r)=>(e=new Zr(e,r),t=new Zr(t,r),e.intersects(t,r));Qr.exports=ci});var rn=w((ul,tn)=>{"use strict";var li=Y(),ui=N();tn.exports=(e,t,r)=>{let n=[],s=null,o=null,i=e.sort((u,f)=>ui(u,f,r));for(let u of i)li(u,t,r)?(o=u,s||(s=u)):(o&&n.push([s,o]),o=null,s=null);s&&n.push([s,null]);let c=[];for(let[u,f]of n)u===f?c.push(u):!f&&u===i[0]?c.push("*"):f?u===i[0]?c.push(`<=${f}`):c.push(`${u} - ${f}`):c.push(`>=${u}`);let a=c.join(" || "),l=typeof t.raw=="string"?t.raw:String(t);return a.length{"use strict";var nn=L(),Ke=H(),{ANY:He}=Ke,J=Y(),Ye=N(),fi=(e,t,r={})=>{if(e===t)return!0;e=new nn(e,r),t=new nn(t,r);let n=!1;e:for(let s of e.set){for(let o of t.set){let i=hi(s,o,r);if(n=n||i!==null,i)continue e}if(n)return!1}return!0},pi=[new Ke(">=0.0.0-0")],sn=[new Ke(">=0.0.0")],hi=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===He){if(t.length===1&&t[0].semver===He)return!0;r.includePrerelease?e=pi:e=sn}if(t.length===1&&t[0].semver===He){if(r.includePrerelease)return!0;t=sn}let n=new Set,s,o;for(let d of e)d.operator===">"||d.operator===">="?s=on(s,d,r):d.operator==="<"||d.operator==="<="?o=an(o,d,r):n.add(d.semver);if(n.size>1)return null;let i;if(s&&o){if(i=Ye(s.semver,o.semver,r),i>0)return null;if(i===0&&(s.operator!==">="||o.operator!=="<="))return null}for(let d of n){if(s&&!J(d,String(s),r)||o&&!J(d,String(o),r))return null;for(let T of t)if(!J(d,String(T),r))return!1;return!0}let c,a,l,u,f=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:!1,m=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1;f&&f.prerelease.length===1&&o.operator==="<"&&f.prerelease[0]===0&&(f=!1);for(let d of t){if(u=u||d.operator===">"||d.operator===">=",l=l||d.operator==="<"||d.operator==="<=",s){if(m&&d.semver.prerelease&&d.semver.prerelease.length&&d.semver.major===m.major&&d.semver.minor===m.minor&&d.semver.patch===m.patch&&(m=!1),d.operator===">"||d.operator===">="){if(c=on(s,d,r),c===d&&c!==s)return!1}else if(s.operator===">="&&!J(s.semver,String(d),r))return!1}if(o){if(f&&d.semver.prerelease&&d.semver.prerelease.length&&d.semver.major===f.major&&d.semver.minor===f.minor&&d.semver.patch===f.patch&&(f=!1),d.operator==="<"||d.operator==="<="){if(a=an(o,d,r),a===d&&a!==o)return!1}else if(o.operator==="<="&&!J(o.semver,String(d),r))return!1}if(!d.operator&&(o||s)&&i!==0)return!1}return!(s&&l&&!o&&i!==0||o&&u&&!s&&i!==0||m||f)},on=(e,t,r)=>{if(!e)return t;let n=Ye(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},an=(e,t,r)=>{if(!e)return t;let n=Ye(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};cn.exports=fi});var C=w((pl,pn)=>{"use strict";var Je=z(),un=X(),di=b(),fn=qe(),mi=q(),wi=Ct(),Ei=Ut(),gi=Gt(),yi=_t(),$i=Vt(),xi=Ht(),Ri=Yt(),bi=Zt(),Oi=N(),vi=rr(),Ii=sr(),Si=pe(),ki=cr(),Ni=ur(),Li=B(),Ai=he(),Ti=Ue(),ji=Fe(),Pi=de(),qi=me(),Ci=ze(),Di=yr(),Ui=H(),Fi=L(),zi=Y(),Gi=Pr(),Mi=Cr(),Wi=Ur(),_i=Gr(),Xi=Wr(),Vi=ge(),Bi=Kr(),Hi=Jr(),Ki=en(),Yi=rn(),Ji=ln();pn.exports={parse:mi,valid:wi,clean:Ei,inc:gi,diff:yi,major:$i,minor:xi,patch:Ri,prerelease:bi,compare:Oi,rcompare:vi,compareLoose:Ii,compareBuild:Si,sort:ki,rsort:Ni,gt:Li,lt:Ai,eq:Ti,neq:ji,gte:Pi,lte:qi,cmp:Ci,coerce:Di,Comparator:Ui,Range:Fi,satisfies:zi,toComparators:Gi,maxSatisfying:Mi,minSatisfying:Wi,minVersion:_i,validRange:Xi,outside:Vi,gtr:Bi,ltr:Hi,intersects:Ki,simplifyRange:Yi,subset:Ji,SemVer:di,re:Je.re,src:Je.src,tokens:Je.t,SEMVER_SPEC_VERSION:un.SEMVER_SPEC_VERSION,RELEASE_TYPES:un.RELEASE_TYPES,compareIdentifiers:fn.compareIdentifiers,rcompareIdentifiers:fn.rcompareIdentifiers}});var Te=new TextDecoder;function ie(e){let t=e.indexOf("@",e.startsWith("@")?1:0);return t<0?{name:e,version:""}:{name:e.slice(0,t),version:e.slice(t+1)}}async function $t(e,t){let r=String(t??"").split(/\s+/).filter(o=>o.startsWith("sha512-")).map(o=>o.split("?")[0]);if(r.length===0)throw new Error("The package has no SHA-512 integrity");if(!globalThis.crypto?.subtle)throw new Error("Integrity checks need a secure context (https or localhost)");let n=new Uint8Array(await crypto.subtle.digest("SHA-512",e)),s="sha512-"+btoa(Array.from(n,o=>String.fromCharCode(o)).join(""));if(!r.includes(s))throw new Error(`Integrity check failed: expected ${r[0]}, got ${s}`);return s}async function xt(e,t=268435456){let r=new Blob([e]).stream().pipeThrough(new DecompressionStream("gzip")).getReader(),n=[],s=0;for(let o=await r.read();!o.done;o=await r.read()){if(s+=o.value.length,s>t)throw await r.cancel(),new Error(`The tarball unpacks to more than ${t} bytes`);n.push(o.value)}return new Uint8Array(await new Blob(n).arrayBuffer())}function _(e,t,r){let n=e.subarray(t,t+r),s=n.indexOf(0);return Te.decode(s<0?n:n.subarray(0,s))}function Rt(e,t,r){if(e[t]&128)return e.subarray(t+1,t+r).reduce((s,o)=>s*256+o,e[t]&127);let n=_(e,t,r).trim();if(!/^[0-7]*$/.test(n))throw new Error("Corrupt tar header");return n===""?0:parseInt(n,8)}function Jn(e){let t=0;for(let r=0;r<512;++r)t+=r>=148&&r<156?32:e[r];if(Rt(e,148,8)!==t)throw new Error("Corrupt tar header checksum")}function Zn(e){let t={},r=0;for(;r0)||r+s>e.length)throw new Error("Corrupt pax header");let o=Te.decode(e.subarray(n+1,r+s-1)),i=o.indexOf("=");t[o.slice(0,i)]=o.slice(i+1),r+=s}return t}function Qn(e,t){let r=e.subarray(t,t+512);Jn(r);let n=Rt(r,124,12),s=t+512;if(s+n>e.length)throw new Error("Truncated tar archive");return{header:r,type:r[156]===0?"0":String.fromCharCode(r[156]),data:e.subarray(s,s+n),next:s+Math.ceil(n/512)*512}}function es(e,t){return t+512>e.length||e.subarray(t,t+512).every(r=>r===0)}function ts(e){let t=_(e,0,100),r=_(e,257,5)==="ustar"?_(e,345,155):"";return r?`${r}/${t}`:t}var yt={x:(e,t)=>({...e,pax:Zn(t).path}),L:(e,t)=>({...e,long:_(t,0,t.length)}),g:e=>e};function bt(e){let t=[],r={};for(let n=0;!es(e,n);){let{header:s,type:o,data:i,next:c}=Qn(e,n);if(n=c,Object.hasOwn(yt,o)){r=yt[o](r,i);continue}(o==="0"||o==="7")&&t.push({path:r.pax??r.long??ts(s),bytes:i}),r={}}return t}var Re=F(C(),1);var R=(e,t,...r)=>e.cppFunction(`webfront.developer.${t}`)(...r);async function G(e,t){let r=[],n=0;for(;;){let s=await R(e,"read",t,n);if(r.push(s),n+=s.length,s.length<262144)break;if(n>256*1024*1024)throw new Error("Project file is too large")}return new Uint8Array(await new Blob(r).arrayBuffer())}async function Z(e,{id:t,path:r,bytes:n},s){for(let o=0;o{}),c}}async function Zi(e,t){let r=[],n=0;for(;;){let{done:s,value:o}=await e.read();if(s)return r;if(n+=o.length,n>t)throw new Error("Compressed download exceeds its byte limit");r.push(o)}}async function Qi(e,t){try{return await Zi(e,t)}catch(r){throw await e.cancel().catch(()=>{}),r}finally{e.releaseLock()}}async function hn(e,t=64*1024*1024){if(!e.ok)throw new Error(`Download: HTTP ${e.status}`);if(Number(e.headers.get("content-length"))>t)throw new Error("Compressed download exceeds its byte limit");return new Uint8Array(await new Blob(await Qi(e.body.getReader(),t)).arrayBuffer())}var M=".webfront/developer/packages",ea=/[\\\0:*?"<>|]/,ta=e=>e.split("/").some(t=>!t||t==="."||t==="..");function Ze(e){return typeof e!="string"||!e||ea.test(e)?!0:ta(e)}function A(e){if(Ze(e))throw new Error(`Unsafe package path: ${e}`);return e}var ra=new TextDecoder,na=["preinstall","install","postinstall"];async function dn(e){let t=new Map,r;for(let n of bt(await xt(e))){let s=n.path.indexOf("/"),o=n.path.slice(0,s);if(s<1||o==="."||o===".."||(r??(r=o))!==o)throw new Error("Invalid npm tarball root");let i=A(n.path.slice(s+1));if(t.has(i))throw new Error(`Duplicate package path: ${i}`);t.set(i,n.bytes)}return t}var sa=e=>na.some(t=>e.scripts?.[t]),oa=e=>e.has("binding.gyp")||[...e.keys()].some(t=>t.endsWith(".node"));function ia(e,t){return sa(e)||e.gypfile?!0:oa(t)}function mn(e,t,r){let n=JSON.parse(ra.decode(e.get("package.json")));if(n.name!==t||n.version!==r)throw new Error("npm archive identity mismatch");if(ia(n,e))throw new Error(`${t} needs an unsupported install script or native module`);return n}function W(e){return!e||typeof e!="object"?!1:!Array.isArray(e)}var Qe="webfront.project.json",et="webfront-packages.lock.json",x=Qe,S=et;function aa(e){if(e===void 0||e==="")return"";if(typeof e!="string"||e.endsWith("/")||Ze(e)||e===".webfront"||e.startsWith(".webfront/"))throw new Error(`Unsafe manifest directory: ${e}`);return e}function Ol(e){let t=aa(e);x=t?`${t}/${Qe}`:Qe,S=t?`${t}/${et}`:et}var ee=1,tt=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,ca=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,la=/^[0-9A-Za-z.+\-^~<>=*| ]{1,128}$/,En=/^[A-Za-z0-9][A-Za-z0-9:_.-]{0,63}$/,rt=/^[A-Za-z_][A-Za-z0-9_]*$/,gn=["format","name","version","dependencies","registry","scripts","entries","providers","test","permissions","developer"],ua=["files","publish","fetch"],y=e=>{throw new Error(`${x}: ${e}`)};function P(e,t){return W(e)||y(`${t} must be an object`),e}function $e(e,t,r){for(let n of Object.keys(e))t.includes(n)||y(`unknown key "${n}" in ${r}`)}function ye(e,t){typeof e!="string"&&y(`${t} must be a project path`);try{return A(e)}catch{return y(`${t} is not a safe project-relative path: ${e}`)}}function yn(e,t){return(!Array.isArray(e)||e.length>256)&&y(`${t} must be an array of at most 256 paths`),e.map((r,n)=>ye(r,`${t}[${n}]`))}function fa(e){let t=P(e,"dependencies");for(let[r,n]of Object.entries(t))tt.test(r)||y(`invalid npm package name "${r}"`),(typeof n!="string"||!la.test(n)||n!==n.trim())&&y(`invalid version range for "${r}"`);return t}var nt=e=>e.startsWith("/")&&!e.startsWith("//")&&!e.includes("\\");function pa(e){if(typeof e!="string"&&y("registry must be a URL"),nt(e))return e;let t;try{t=new URL(e)}catch{return y("registry must be an https URL or an absolute path")}return t.protocol!=="https:"&&y("registry must use https"),e}function ha(e){let t=P(e,"scripts");for(let[r,n]of Object.entries(t))(!En.test(r)||typeof n!="string"||!n||n.length>1024)&&y(`invalid script "${r}"`);return t}function da(e){let t=P(e,"entries");for(let[r,n]of Object.entries(t))En.test(r)||y(`invalid entry name "${r}"`),ye(n,`entries.${r}`);return t}function ma(e,t){let r=P(e,"providers");for(let[n,s]of Object.entries(r))rt.test(n)||y(`invalid provider name "${n}"`),P(s,`providers.${n}`),$e(s,["entry","output"],`providers.${n}`),typeof s.entry!="string"&&y(`providers.${n}.entry must name an entry or a path`),Object.hasOwn(t,s.entry)||ye(s.entry,`providers.${n}.entry`),ye(s.output,`providers.${n}.output`).endsWith(".hpp")||y(`providers.${n}.output must be a .hpp file`);return r}function wa(e){let t=P(e,"test");return $e(t,["specs"],"test"),t.specs!==void 0&&yn(t.specs,"test.specs"),t}function Ea(e,t){let r;try{r=new URL(e)}catch{return y(`${t} must be an https origin`)}return(r.protocol!=="https:"||r.origin!==e)&&y(`${t} must be an https origin without a path`),e}function ga(e){let t=P(e,"permissions");for(let r of Object.keys(t))ua.includes(r)||y(`unknown permission "${r}"`);for(let r of["files","publish"])t[r]!==void 0&&yn(t[r],`permissions.${r}`);return t.fetch!==void 0&&((!Array.isArray(t.fetch)||t.fetch.length>64)&&y("permissions.fetch must be an array of origins"),t.fetch.forEach((r,n)=>Ea(r,`permissions.fetch[${n}]`))),t}var wn={Ctrl:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"},vl="F9";function ya(e){if(typeof e!="string")return null;let t=e.split("+"),r=t.pop();if(!/^F(?:[1-9]|1[0-2])$/.test(r)||new Set(t).size!==t.length)return null;let n={key:r,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1};for(let s of t){if(!Object.hasOwn(wn,s))return null;n[wn[s]]=!0}return n}function $a(e){let t=P(e,"developer");return $e(t,["terminalShortcut"],"developer"),t.terminalShortcut!==void 0&&!ya(t.terminalShortcut)&&y('developer.terminalShortcut must be a function key, F1 to F12, optionally after Ctrl, Alt, Shift or Meta (for instance "Ctrl+Shift+F9")'),t}function xa(e){(typeof e.name!="string"||!tt.test(e.name))&&y("name must be a lower-case npm package name"),(typeof e.version!="string"||!ca.test(e.version))&&y("version must be a semantic version")}function Ra(e){e.format!==ee&&(Number.isInteger(e.format)&&e.format>ee&&y(`format ${e.format} is not supported by this environment (it reads format ${ee}); update the environment`),y(`format must be ${ee}`))}function te(e){P(e,"the manifest"),Ra(e),$e(e,gn,"the manifest"),xa(e);let t=e.entries===void 0?{}:da(e.entries);return{...e,dependencies:e.dependencies===void 0?{}:fa(e.dependencies),entries:t,providers:e.providers===void 0?{}:ma(e.providers,t),...e.registry===void 0?{}:{registry:pa(e.registry)},...e.scripts===void 0?{}:{scripts:ha(e.scripts)},...e.test===void 0?{}:{test:wa(e.test)},...e.permissions===void 0?{}:{permissions:ga(e.permissions)},...e.developer===void 0?{}:{developer:$a(e.developer)}}}function st(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return y("not valid JSON")}return{source:t,manifest:te(t)}}function Il(e){return st(e).manifest}function ot(e){let t={};for(let r of gn)e[r]!==void 0&&(t[r]=e[r]);return JSON.stringify(t,null,2)+` +`}function $n(e){return{format:ee,name:e,version:"0.1.0",dependencies:{}}}function xn(e){let r=(String(e??"").split("/").filter(Boolean).pop()??"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[^a-z0-9]+/,"").replace(/-+$/,"");return tt.test(r)?r:"webfront-app"}async function xe(e){let t=JSON.stringify(Object.entries(e).sort(([n],[s])=>ns?1:0)),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return[...new Uint8Array(r)].map(n=>n.toString(16).padStart(2,"0")).join("")}var it=e=>/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(e),be=(e,t)=>`${e.replace("/","+")}@${t}`,at=(e,t,r)=>`${be(e,t)}-${r.slice(7).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}`;async function ba(e,t,{fetchImpl:r,signal:n}){let s=await r(new URL(e.replace("/","%2f"),t),{signal:n});if(!s.ok)throw new Error(`Registry metadata for ${e}: HTTP ${s.status}`);return s.json()}function Oa(e,t){let r=e["dist-tags"]?.[t];return r||(Re.default.valid(t)?t:Re.default.maxSatisfying(Object.keys(e.versions??{}),t))}function va(e,t,r){let n=r||"latest",s=Oa(e,n),o=e.versions?.[s];if(!o||!Re.default.valid(s))throw new Error(`Cannot resolve ${t}@${n}`);return{version:s,manifest:o}}async function Ia(e,t,r,{fetchImpl:n,signal:s}){let o=new URL(t.dist?.tarball,r);if(o.protocol!=="https:"&&o.origin!==r.origin)throw new Error("Package tarballs must use HTTPS or the registry origin");let i=await n(o,{signal:s});if(!i.ok)throw new Error(`Package download for ${e}: HTTP ${i.status}`);let c=await hn(i);return{bytes:c,integrity:await $t(c,t.dist.integrity)}}function ct(e){let t=new URL(e,globalThis.location?.href),r=t.origin===globalThis.location?.origin;if(e.startsWith("/")?!nt(e)||!r:t.protocol!=="https:"&&!r)throw new Error(`The npm registry must use HTTPS or the application origin: ${e}`);return t.pathname.endsWith("/")||(t.pathname+="/"),t}async function D(e,t,{registry:r,fetchImpl:n=fetch,signal:s}){if(!it(e))throw new Error(`Unsupported npm package name: ${e}`);let o=ct(r),i={fetchImpl:n,signal:s},{version:c,manifest:a}=va(await ba(e,o,i),e,t),{bytes:l,integrity:u}=await Ia(e,a,o,i),f=await dn(l),m=mn(f,e,c);return{id:be(e,c),key:at(e,c,u),manifest:m,integrity:u,files:f}}var Oe=F(C(),1);function Sa(e,t,r){let n=e?.roots?.[t];return n?.requested===r&&e.packages[n.id]?e.packages[n.id]:Oe.default.validRange(r)?Object.values(e?.packages??{}).filter(o=>o.name===t&&Oe.default.satisfies(o.version,r)).sort((o,i)=>Oe.default.rcompare(o.version,i.version))[0]??null:null}function Rn({registry:e="https://registry.npmjs.org/",fetchImpl:t=fetch,signal:r,download:n=D,previous:s}){let o=new Map;return async(i,c)=>{let a=`${i}@${c}`;if(o.has(a))return o.get(a);let l=Sa(s,i,c),u=await n(i,l?.version??c,{registry:e,fetchImpl:t,signal:r});if(l&&u.integrity!==l.integrity)throw new Error(`${u.id} no longer matches the integrity recorded in the lock`);return o.set(a,u),u}}var bn=F(C(),1),On=(e,t,r)=>new Error(`${e.name}@${e.version} requires peer ${t}@${r}; install a compatible root explicitly`);function ka(e,t,r){if(e.manifest.peerDependenciesMeta?.[t]?.optional)return null;throw On(e,t,r)}function Na(e,[t,r],{nodes:n,roots:s}){let o=s[t]?.id??e.dependencies[t];if(!o)return ka(e,t,r);if(!bn.default.satisfies(n[o].version,r))throw On(e,t,r);return o}function La(e,t){for(let r of Object.entries(e.manifest.peerDependencies??{})){let n=Na(e,r,t);n&&(e.dependencies[r[0]]=n)}}function vn(e,t){for(let r of Object.values(e))La(r,{nodes:e,roots:t})}var In=F(C(),1);function Aa(e,t){return!it(t.name)||!In.default.valid(t.version)?!1:e===be(t.name,t.version)}function Ta(e){return e.integrity?.startsWith("sha512-")?e.key===at(e.name,e.version,e.integrity):!1}function ja(e,t,r){if(!Aa(t,r)||!Ta(r))throw new Error("Invalid locked package");for(let n of r.files)A(n);if(Object.values(r.dependencies).some(n=>!e.packages[n]))throw new Error("Dangling locked dependency")}function Pa(e){return e?.format!==1?!1:!!e.roots&&!!e.packages}function lt(e){if(!Pa(e))throw new Error("Unsupported package lock");if(Object.keys(e.packages).length>512)throw new Error("The package lock exceeds 512 packages");for(let[t,r]of Object.entries(e.packages))ja(e,t,r);if(Object.values(e.roots).some(t=>!e.packages[t.id]))throw new Error("Dangling locked root");return e}function qa(e,t,r){if(Object.keys(e.nodes).length>=512)throw new Error("Dependency graph exceeds 512 packages");for(let n of r.files.values())e.total+=n.length;if(e.total>256*1024*1024)throw new Error("Dependency graph exceeds 256 MiB");e.nodes[r.id]={name:t,version:r.manifest.version,integrity:r.integrity,key:r.key,manifest:r.manifest,files:[...r.files.keys()].sort(),dependencies:{}},e.downloads.set(r.id,r.files)}async function Ca(e,t){let r={};for(let n of e){let{name:s,version:o}=ie(n);r[s]={requested:o||"latest",id:await t(s,o||"latest")}}return r}async function Sn(e,t={}){let r=Rn(t),n={nodes:{},downloads:new Map,total:0},s=async(i,c)=>{t.signal?.throwIfAborted();let a=await r(i,c);if(n.nodes[a.id])return a.id;qa(n,i,a);for(let[l,u]of Object.entries(a.manifest.dependencies??{}).sort())n.nodes[a.id].dependencies[l]=await s(l,u);return a.id},o=await Ca(e,s);return vn(n.nodes,o),{lock:{format:1,registry:t.registry??"https://registry.npmjs.org/",roots:o,packages:n.nodes},downloads:n.downloads}}var ut=F(C(),1);var Da=new TextDecoder,Ua=new TextEncoder,ve="No webfront.project.json: run wf init, then wf dev (the interface is TypeScript/TSX in ui/; wf create app writes a first one; wf help agents gives the sequence)",Ie="The lock does not match the dependencies of webfront.project.json; run wf install --update to resolve them again";async function kn(e,t){try{return await G(e,t)}catch(r){if(r.message.includes("Cannot read project file:"))return null;throw r}}function Fa(e,t,r){return t?r===t.requested?!0:ut.default.validRange(r)!==null&&ut.default.satisfies(e.packages[t.id].version,r):!1}function za(e,t){let r=Object.keys(t);return r.length===Object.keys(e.roots).length&&r.every(n=>Fa(e,e.roots[n],t[n]))}function Ga(e,t,r){return e?t?t.manifestDigest===void 0?za(t,e.dependencies)?"legacy":"desynchronized":t.manifestDigest===r?"consistent":"desynchronized":"unlocked":"no-manifest"}async function re(e){let t=await R(e,"state",`${x} +${S}`),r=await kn(e,x),n=await kn(e,S),{source:s,manifest:o}=r?st(r):{source:null,manifest:null},i=n?lt(JSON.parse(Da.decode(n))):null,c=o?await xe(o.dependencies):null;return{manifest:o,source:s,lock:i,token:t,status:Ga(o,i,c),digest:c}}var Ln=e=>e.status==="desynchronized"?`Warning: ${Ie}.\r +`:"";async function An(e,t,r,{signal:n}={}){let s=[];try{for(let[o,i]of t){n?.throwIfAborted();let c=await R(e,"begin",o,!1);s.push(c),await Z(e,{id:c,path:"output",bytes:i},n)}n?.throwIfAborted(),await R(e,"commitGroup",s.join(` `),`${x} -${N}`,r.token)}catch(o){for(let i of s)await R(e,"abort",i).catch(()=>{});throw o}}function kn(e,t,r){let n=e?.entries??{};if(t!==void 0)return Object.hasOwn(n,t)?n[t]:t;if(Object.hasOwn(n,"main"))return n.main;let s=Object.keys(n);if(s.length===1)return n[s[0]];throw new Error(`Usage: ${r} (declare entries.main in ${x} to omit the entry)`)}function Vl(e,[t,r,n,...s]){if(t&&Object.hasOwn(e?.providers??{},t)&&r===void 0){let i=e.providers[t];return{entry:kn(e,i.entry),output:i.output,className:t}}if(!t||r!=="--output"||s.length||!n?.endsWith(".hpp"))throw new Error("wf embed requires or --output ");let o=n.split("/").pop().slice(0,-4);if(!tt.test(o))throw new Error(`wf embed: ${o} is not a C++ class name; name the output .hpp`);return{entry:kn(e,t),output:n,className:o}}var Ie=e=>qc.encode(e);var mt=F(C(),1);var An=e=>`${M}/${e.key}`,Tn=e=>`${M}/${e.key}.json`,zc=new TextEncoder,Gc=new TextDecoder,jn=e=>e.message.includes("Cannot read project file:");async function Pn(e){return[...new Uint8Array(await crypto.subtle.digest("SHA-256",e))].map(r=>r.toString(16).padStart(2,"0")).join("")}async function Ne(e,t,r,{signal:n}={}){let s={};for(let i of[...r.keys()].sort())s[i]=await Pn(r.get(i));await Q(e,An(t),r,{signal:n});let o=JSON.stringify({format:1,integrity:t.integrity,files:s},null,2)+` -`;await Q(e,Tn(t),new Map([["output",zc.encode(o)]]),{directory:!1,signal:n})}async function Mc(e,t){let r;try{r=await G(e,Tn(t))}catch(n){if(jn(n))return null;throw n}try{return JSON.parse(Gc.decode(r))}catch{return{}}}var Wc=(e,t)=>Object.keys(e.files).sort().join(` +${S}`,r.token)}catch(o){for(let i of s)await R(e,"abort",i).catch(()=>{});throw o}}function Nn(e,t,r){let n=e?.entries??{};if(t!==void 0)return Object.hasOwn(n,t)?n[t]:t;if(Object.hasOwn(n,"main"))return n.main;let s=Object.keys(n);if(s.length===1)return n[s[0]];throw new Error(`Usage: ${r}, for example ui/main.tsx (declare entries.main in ${x} to omit the entry; wf create app writes a first ui/main.ts)`)}function Kl(e,[t,r,n,...s]){if(t&&Object.hasOwn(e?.providers??{},t)&&r===void 0){let i=e.providers[t];return{entry:Nn(e,i.entry),output:i.output,className:t}}if(!t||r!=="--output"||s.length||!n?.endsWith(".hpp"))throw new Error("wf embed requires or --output ");let o=n.split("/").pop().slice(0,-4);if(!rt.test(o))throw new Error(`wf embed: ${o} is not a C++ class name; name the output .hpp`);return{entry:Nn(e,t),output:n,className:o}}var Se=e=>Ua.encode(e);var mt=F(C(),1);var Tn=e=>`${M}/${e.key}`,jn=e=>`${M}/${e.key}.json`,Wa=new TextEncoder,_a=new TextDecoder,Pn=e=>e.message.includes("Cannot read project file:");async function qn(e){return[...new Uint8Array(await crypto.subtle.digest("SHA-256",e))].map(r=>r.toString(16).padStart(2,"0")).join("")}async function ke(e,t,r,{signal:n}={}){let s={};for(let i of[...r.keys()].sort())s[i]=await qn(r.get(i));await Q(e,Tn(t),r,{signal:n});let o=JSON.stringify({format:1,integrity:t.integrity,files:s},null,2)+` +`;await Q(e,jn(t),new Map([["output",Wa.encode(o)]]),{directory:!1,signal:n})}async function Xa(e,t){let r;try{r=await G(e,jn(t))}catch(n){if(Pn(n))return null;throw n}try{return JSON.parse(_a.decode(r))}catch{return{}}}var Va=(e,t)=>Object.keys(e.files).sort().join(` `)===[...t.files].sort().join(` -`);async function _c(e,t,r){let n=[],s=0;for(;;){let o;try{o=await R(e,"read",t,s)}catch(i){if(jn(i))return null;throw i}if(s+=o.length,s>r)return null;if(n.push(o),o.length<262144)return new Uint8Array(await new Blob(n).arrayBuffer())}}async function ft(e,t,{signal:r,limit:n=1/0}={}){let s=await Mc(e,t);if(!s)return{state:"missing",size:0};if(s.integrity!==t.integrity||!W(s.files)||!Wc(s,t))return{state:"corrupted",size:0};let o=0;for(let i of t.files){r?.throwIfAborted();let a=await _c(e,`${An(t)}/${i}`,n-o);if(!a||await Pn(a)!==s.files[i])return{state:"corrupted",size:0};o+=a.length}return{state:"valid",size:o}}var Zl=async(e,t,r)=>(await ft(e,t,r)).state;var Vc="https://registry.npmjs.org/";function Xc({registry:e,registryExplicit:t}={},r){return t&&e?{url:e,source:"application option"}:r?.registry?{url:r.registry,source:x}:{url:e||Vc,source:"default"}}function pt(e,t){let r=Xc(e,t);return at(r.url),r}var ht=({url:e,source:t})=>`Registry: ${e} (${t})`,Bc=256*1024*1024,Hc=e=>[...e.values()].reduce((t,r)=>t+r.length,0),Yc=e=>new Error(`The locked packages exceed ${e/(1024*1024)} MiB unpacked`);async function Jc(e,t,{signal:r,limit:n}){let s=[],o=0;for(let[i,a]of Object.entries(t.packages)){r?.throwIfAborted();let c=await ft(e,a,{signal:r,limit:n-o});o+=c.size,s.push({id:i,node:a,state:c.state})}return{states:s,size:o}}async function dt(e,t,{registry:r,offline:n=!1,signal:s,progress:o=()=>{},fetchImpl:i=fetch,limit:a=Bc}){let{states:c,size:l}=await Jc(e,t,{signal:s,limit:a}),u=l,f={verified:c.filter(({state:m})=>m==="valid").length,restored:0,problems:[]};for(let{id:m,node:d,state:T}of c.filter(({state:k})=>k!=="valid")){if(n){f.problems.push(`${m} (${T})`);continue}o(`Restoring ${m}${T==="corrupted"?" (corrupted in the cache)":""}`);let k=await D(d.name,d.version,{registry:r,fetchImpl:i,signal:s});if(k.integrity!==d.integrity)throw new Error(`${m} no longer matches the integrity recorded in the lock`);if(u+=Hc(k.files),u>a)throw Yc(a);await Ne(e,d,k.files,{signal:s}),f.restored++}if(f.problems.length)throw new Error(`The cache does not match ${N}; missing or corrupted, nothing downloaded:\r +`);async function Ba(e,t,r){let n=[],s=0;for(;;){let o;try{o=await R(e,"read",t,s)}catch(i){if(Pn(i))return null;throw i}if(s+=o.length,s>r)return null;if(n.push(o),o.length<262144)return new Uint8Array(await new Blob(n).arrayBuffer())}}async function ft(e,t,{signal:r,limit:n=1/0}={}){let s=await Xa(e,t);if(!s)return{state:"missing",size:0};if(s.integrity!==t.integrity||!W(s.files)||!Va(s,t))return{state:"corrupted",size:0};let o=0;for(let i of t.files){r?.throwIfAborted();let c=await Ba(e,`${Tn(t)}/${i}`,n-o);if(!c||await qn(c)!==s.files[i])return{state:"corrupted",size:0};o+=c.length}return{state:"valid",size:o}}var tu=async(e,t,r)=>(await ft(e,t,r)).state;var Ha="https://registry.npmjs.org/";function Ka({registry:e,registryExplicit:t}={},r){return t&&e?{url:e,source:"application option"}:r?.registry?{url:r.registry,source:x}:{url:e||Ha,source:"default"}}function pt(e,t){let r=Ka(e,t);return ct(r.url),r}var ht=({url:e,source:t})=>`Registry: ${e} (${t})`,Ya=256*1024*1024,Ja=e=>[...e.values()].reduce((t,r)=>t+r.length,0),Za=e=>new Error(`The locked packages exceed ${e/(1024*1024)} MiB unpacked`);async function Qa(e,t,{signal:r,limit:n}){let s=[],o=0;for(let[i,c]of Object.entries(t.packages)){r?.throwIfAborted();let a=await ft(e,c,{signal:r,limit:n-o});o+=a.size,s.push({id:i,node:c,state:a.state})}return{states:s,size:o}}async function dt(e,t,{registry:r,offline:n=!1,signal:s,progress:o=()=>{},fetchImpl:i=fetch,limit:c=Ya}){let{states:a,size:l}=await Qa(e,t,{signal:s,limit:c}),u=l,f={verified:a.filter(({state:m})=>m==="valid").length,restored:0,problems:[]};for(let{id:m,node:d,state:T}of a.filter(({state:k})=>k!=="valid")){if(n){f.problems.push(`${m} (${T})`);continue}o(`Restoring ${m}${T==="corrupted"?" (corrupted in the cache)":""}`);let k=await D(d.name,d.version,{registry:r,fetchImpl:i,signal:s});if(k.integrity!==d.integrity)throw new Error(`${m} no longer matches the integrity recorded in the lock`);if(u+=Ja(k.files),u>c)throw Za(c);await ke(e,d,k.files,{signal:s}),f.restored++}if(f.problems.length)throw new Error(`The cache does not match ${S}; missing or corrupted, nothing downloaded:\r ${f.problems.join(`\r `)}\r -Run wf restore to download them.`);return f}function Zc(e){let t=e.includes("--offline");if(e.some(r=>r!=="--offline"))throw new Error("Usage: wf restore [--offline]");return{offline:t}}async function nu(e,t,{registry:r,registryExplicit:n,signal:s,progress:o=()=>{},fetchImpl:i=fetch}={}){let{offline:a}=Zc(t),c=await re(e);if(!c.manifest)throw new Error(Oe);if(!c.lock)throw new Error(`No ${N}: run wf install to resolve the dependencies`);let l=a?null:pt({registry:r,registryExplicit:n},c.manifest);o(a?"Offline: no registry is contacted":ht(l));let u=await dt(e,c.lock,{registry:l?.url,offline:a,signal:s,progress:o,fetchImpl:i}),f=Object.keys(c.lock.packages).length,m=a?`Cache verified offline: ${f} packages match ${N}.`:`Restored ${u.restored} of ${f} packages (${u.verified} already in the cache). Lock: ${N}`;return{...u,registry:l,text:Sn(c)+m}}var Dn=e=>{let{name:t,version:r}=ie(e);return[t,r||void 0]};function Kc(e,t){let{version:r}=e.packages[t.id];return!(mt.default.valid(t.requested)!==null)&&t.requested!=="latest"&&mt.default.validRange(t.requested)!==null?t.requested:`^${r}`}async function pu(e,[t,...r],{signal:n}={}){if(r.length)throw new Error("Usage: wf init [name]");let{lock:s}=await re(e),o=$n(t??yn(""));s&&(o.dependencies=Object.fromEntries(Object.entries(s.roots).map(([a,c])=>[a,Kc(s,c)]))),te(o),await Q(e,x,new Map([["output",Ie(ot(o))]]),{directory:!1,replace:!1,signal:n});let i=s?` with the ${Object.keys(o.dependencies).length} dependencies of ${N}`:"";return`Created ${x}${i}. Add libraries with wf install .`}function Qc(e,t){let r={...e.manifest.dependencies},n=new Set;for(let s of t){let[o,i]=Dn(s);r[o]=i??"latest",i&&i!=="latest"&&n.add(o)}return te({...e.source,dependencies:r}),{dependencies:r,explicit:n}}function ea(e,t){let r={...e.source,dependencies:t};return te(r),r}function ta({dependencies:e,explicit:t},r,n){let s={...e};for(let o of n){let i=Dn(o)[0];t.has(i)||(s[i]=`^${r.packages[r.roots[i].id].version}`)}return s}async function ra(e,t,r){let n=Object.entries(e).map(([i,a])=>`${i}@${a}`),{lock:s,downloads:o}=await In(n,{registry:r.registry,signal:r.signal,fetchImpl:r.fetchImpl,previous:t,download:async(...i)=>(r.progress(`Resolving ${i[0]}@${i[1]}`),D(...i))});return{lock:s,downloads:o}}async function na(e,t,r,{signal:n,progress:s}){for(let[o,i]of r)s(`Storing ${o}`),await Ne(e,t.packages[o],i,{signal:n})}function sa(e){let t=e.includes("--update"),r=e.filter(n=>n!=="--update");if(r.some(n=>n.startsWith("-")))throw new Error("Usage: wf install [--update] [[@range] ...]");return{update:t,specs:r}}async function qn(e,t,{manifest:r,lock:n},s){let o=new Map([[N,Ie(JSON.stringify(n,null,2)+` -`)]]);r&&o.set(x,Ie(ot(r))),await Ln(e,o,t,s)}var Cn=async(e,t)=>({format:e.format,manifestDigest:await ye(t),...e});async function hu(e,t,{registry:r,registryExplicit:n,signal:s,progress:o=()=>{},fetchImpl:i=fetch}){let{update:a,specs:c}=sa(t),l=await re(e);if(!l.manifest)throw new Error(Oe);let u=pt({registry:r,registryExplicit:n},l.manifest),f={registry:u.url,signal:s,fetchImpl:i,progress:o};if(c.length&&a)throw new Error("Usage: wf install --update does not take packages");if(c.length&&l.status==="desynchronized")throw new Error(ve);if(!c.length&&!a&&l.status==="desynchronized")throw new Error(ve);o(ht(u));let m=l.status==="consistent"||l.status==="legacy";if(!c.length&&!a&&m){let{restored:U}=await dt(e,l.lock,f);if(l.status==="consistent")return{lock:l.lock,restored:U,registry:u};let oe=await Cn(l.lock,l.manifest.dependencies);return await qn(e,l,{manifest:null,lock:oe},{signal:s}),{lock:oe,restored:U,registry:u}}let d=Qc(l,c),T=m&&!a?l.lock:void 0,k=await ra(d.dependencies,T,f),Le=ta(d,k.lock,c);await na(e,k.lock,k.downloads,{signal:s,progress:o});let se=await Cn(k.lock,Le),$=c.length?ea(l,Le):null;return await qn(e,l,{manifest:$,lock:se},{signal:s}),{lock:se,restored:0,registry:u}}var oa=()=>[x,N,".webfront"],ne=(e,t)=>e===t||e.startsWith(t+"/");function wt(e){try{return A(e)}catch{throw new Error(`Not a project-relative path: ${e}`)}}var ke=(e,t,r)=>new Error(`Permission denied: ${e} ${t} is not granted by permissions.${r} in ${x}`);function Un(e,t){let r=wt(t);if(![...e?.files??[],...e?.publish??[]].some(s=>ne(r,s)))throw ke("reading",t,"files");return r}function Fn(e,t){let r=t===""||t==="."?"":wt(t),n=[...e?.files??[],...e?.publish??[]];if(r&&n.some(o=>ne(r,o)))return{path:r,keep:()=>!0};let s=o=>n.some(i=>ne(o,i)||i.startsWith(o+"/"));if(!n.some(o=>r===""||o.startsWith(r+"/")))throw ke("listing",r||"the project root","files");return{path:r,keep:o=>s(r?`${r}/${o.replace(/\/$/,"")}`:o.replace(/\/$/,""))}}function zn(e,t){let r=wt(t);if(oa().some(n=>ne(r,n)))throw new Error(`Permission denied: ${t} is managed by wf and never written by a script`);if(!(e?.publish??[]).some(n=>ne(r,n)))throw ke("writing",t,"publish");return r}function Eu(e,t,r){let n=new URL(t,r);if(!(e?.fetch??[]).includes(n.origin))throw ke("fetching",n.origin,"fetch");return n}var ia=2e3,Mn=600,Se=[1,3600],Gn=4,Et=class extends Error{constructor(t,r){super(t),this.exitCode=r}},bu=(e,t=1/0,r=Date.now())=>Math.min(r+e*1e3,t),Ou=(e,t=Date.now())=>Math.max(0,(e-t)/1e3);function vu(e,t){let r=Mn,n=e;if(n[0]==="--timeout"){if(r=Number(n[1]),!Number.isInteger(r)||rSe[1])throw new Error(`--timeout expects whole seconds from ${Se[0]} to ${Se[1]}`);n=n.slice(2)}if(!n.length||n[0].startsWith("-"))throw new Error(`Usage: ${t}`);return{timeout:r,target:n[0],args:n.slice(1)}}function Iu(e,t,r,n,s=0){let o=e?.scripts??{};if(!Object.hasOwn(o,t)){let c=Object.keys(o).sort().join(", ")||"none";throw new Error(`No script "${t}" in ${x} (scripts: ${c})`)}let[i,...a]=n(o[t]);if(i==="wf"){if(s>=Gn)throw new Error(`Scripts call wf more than ${Gn} levels deep`);return{kind:"wf",argv:[...a,...r]}}return{kind:"module",entry:{namespace:"project",path:A(i)},args:[...a,...r]}}function Wn(e,t){if(e?.roots&&Object.hasOwn(e.roots,t)){let{id:n}=e.roots[t];return[n,e.packages[n]]}let r=Object.entries(e?.packages??{}).filter(([,n])=>n.name===t);if(r.length>1)throw new Error(`${t} is locked at several versions; install it as a root to choose one`);return r[0]??null}function ca(e,t){let r=t.webfront?.bin;if(typeof r=="string")return{[t.name.split("/").pop()]:r};if(r&&typeof r=="object"&&!Array.isArray(r))return r;throw t.bin?new Error(`${e} only declares an npm "bin" (a Node.js program); wf exec runs only "webfront.bin" entries`):new Error(`${e} has no WebFront executable entry ("webfront.bin" in its package.json)`)}function Nu(e,t){let r=t.indexOf(":",t.startsWith("@")?t.indexOf("/"):0),[n,s]=r<0?[t,void 0]:[t.slice(0,r),t.slice(r+1)],o=Wn(e,n);if(!o)throw new Error(`${n} is not installed: run wf install ${n}`);let[i,a]=o,c=ca(i,a.manifest),l=Object.keys(c),u=s??(l.length===1?l[0]:void 0);if(!u||!Object.hasOwn(c,u))throw new Error(`${i} has the WebFront entries ${l.join(", ")||"none"}: run wf exec ${n}:`);let f=String(c[u]).replace(/^\.\//,"");if(!a.files.includes(A(f)))throw new Error(`${i}: webfront.bin entry ${u} names a missing file ${f}`);return{id:i,name:u,entry:{namespace:"npm",path:`${i}/${f}`}}}var aa=new TextDecoder;function ku({bridge:e,permissions:t,lock:r}){let n=new AbortController,s=[],o=new Set;async function i(c,l){let u=zn(t,c);if(!(l instanceof Uint8Array))throw new TypeError("context.project.write expects a string or a Uint8Array");let f={path:u,state:"staging"};s.push(f);let m=null;try{m=await R(e,"begin",u,!1),await K(e,{id:m,path:"output",bytes:l},n.signal),n.signal.throwIfAborted(),f.state="committing",await R(e,"commit",m),f.state="applied"}catch(d){let T=n.signal.aborted&&f.state!=="committing";throw f.state=T?"abandoned":"failed",m!==null&&await R(e,"abort",m).catch(()=>{}),d}}let a={read:c=>G(e,Un(t,c)),list:async(c="")=>{let{path:l,keep:u}=Fn(t,c);return JSON.parse(aa.decode(await R(e,"list",l))).filter(u)},write:i,resolve:c=>{let l=Wn(r,c)?.[1];return l?{name:l.name,version:l.version,integrity:l.integrity}:null}};return{publications:s,async handle({operation:c,args:l}){if(n.signal.aborted)throw new Error("The script was stopped");if(!Object.hasOwn(a,c))throw new Error(`Unknown context operation: ${c}`);let u=a[c](...l);o.add(u);try{return await u}finally{o.delete(u)}},async finish(){for(let c of s)(c.state==="staging"||c.state==="committing")&&(c.unawaited=!0);for(;o.size;)await Promise.allSettled([...o]);await this.stop()},async stop(){n.abort(new Error("The script was stopped")),await Promise.allSettled([...o])}}}function Su({createWorker:e,host:t,message:r,signal:n,timeout:s=Mn,grace:o=ia,write:i}){return new Promise(a=>{let c=e(),l=[],u=null,f=!1,m=()=>u==="timeout"?124:130,d=$=>{f||(f=!0,c.terminate(),l.forEach(clearTimeout),n?.removeEventListener("abort",k),a({reason:u??"exit",...$}))},T=$=>{u||f||(u=$,c.postMessage({type:"abort"}),l.push(setTimeout(()=>d({code:m(),forced:o}),o)))},k=()=>T("interrupted"),se={console:$=>i(String($.text).replace(/\r?\n/g,`\r +Run wf restore to download them.`);return f}function ec(e){let t=e.includes("--offline");if(e.some(r=>r!=="--offline"))throw new Error("Usage: wf restore [--offline]");return{offline:t}}async function au(e,t,{registry:r,registryExplicit:n,signal:s,progress:o=()=>{},fetchImpl:i=fetch}={}){let{offline:c}=ec(t),a=await re(e);if(!a.manifest)throw new Error(ve);if(!a.lock)throw new Error(`No ${S}: run wf install to resolve the dependencies`);let l=c?null:pt({registry:r,registryExplicit:n},a.manifest);o(c?"Offline: no registry is contacted":ht(l));let u=await dt(e,a.lock,{registry:l?.url,offline:c,signal:s,progress:o,fetchImpl:i}),f=Object.keys(a.lock.packages).length,m=c?`Cache verified offline: ${f} packages match ${S}.`:`Restored ${u.restored} of ${f} packages (${u.verified} already in the cache). Lock: ${S}`;return{...u,registry:l,text:Ln(a)+m}}var Un=e=>{let{name:t,version:r}=ie(e);return[t,r||void 0]};function tc(e,t){let{version:r}=e.packages[t.id];return!(mt.default.valid(t.requested)!==null)&&t.requested!=="latest"&&mt.default.validRange(t.requested)!==null?t.requested:`^${r}`}async function wu(e,[t,...r],{signal:n}={}){if(r.length)throw new Error("Usage: wf init [name]");let{lock:s}=await re(e),o=$n(t??xn(""));s&&(o.dependencies=Object.fromEntries(Object.entries(s.roots).map(([c,a])=>[c,tc(s,a)]))),te(o),await Q(e,x,new Map([["output",Se(ot(o))]]),{directory:!1,replace:!1,signal:n});let i=s?` with the ${Object.keys(o.dependencies).length} dependencies of ${S}`:"";return`Created ${x}${i}. Add libraries with wf install .`}function rc(e,t){let r={...e.manifest.dependencies},n=new Set;for(let s of t){let[o,i]=Un(s);r[o]=i??"latest",i&&i!=="latest"&&n.add(o)}return te({...e.source,dependencies:r}),{dependencies:r,explicit:n}}function nc(e,t){let r={...e.source,dependencies:t};return te(r),r}function sc({dependencies:e,explicit:t},r,n){let s={...e};for(let o of n){let i=Un(o)[0];t.has(i)||(s[i]=`^${r.packages[r.roots[i].id].version}`)}return s}async function oc(e,t,r){let n=Object.entries(e).map(([i,c])=>`${i}@${c}`),{lock:s,downloads:o}=await Sn(n,{registry:r.registry,signal:r.signal,fetchImpl:r.fetchImpl,previous:t,download:async(...i)=>(r.progress(`Resolving ${i[0]}@${i[1]}`),D(...i))});return{lock:s,downloads:o}}async function ic(e,t,r,{signal:n,progress:s}){for(let[o,i]of r)s(`Storing ${o}`),await ke(e,t.packages[o],i,{signal:n})}function ac(e){let t=e.includes("--update"),r=e.filter(n=>n!=="--update");if(r.some(n=>n.startsWith("-")))throw new Error("Usage: wf install [--update] [[@range] ...]");return{update:t,specs:r}}async function Cn(e,t,{manifest:r,lock:n},s){let o=new Map([[S,Se(JSON.stringify(n,null,2)+` +`)]]);r&&o.set(x,Se(ot(r))),await An(e,o,t,s)}var Dn=async(e,t)=>({format:e.format,manifestDigest:await xe(t),...e});async function Eu(e,t,{registry:r,registryExplicit:n,signal:s,progress:o=()=>{},fetchImpl:i=fetch}){let{update:c,specs:a}=ac(t),l=await re(e);if(!l.manifest)throw new Error(ve);let u=pt({registry:r,registryExplicit:n},l.manifest),f={registry:u.url,signal:s,fetchImpl:i,progress:o};if(a.length&&c)throw new Error("Usage: wf install --update does not take packages");if(a.length&&l.status==="desynchronized")throw new Error(Ie);if(!a.length&&!c&&l.status==="desynchronized")throw new Error(Ie);o(ht(u));let m=l.status==="consistent"||l.status==="legacy";if(!a.length&&!c&&m){let{restored:U}=await dt(e,l.lock,f);if(l.status==="consistent")return{lock:l.lock,restored:U,registry:u};let oe=await Dn(l.lock,l.manifest.dependencies);return await Cn(e,l,{manifest:null,lock:oe},{signal:s}),{lock:oe,restored:U,registry:u}}let d=rc(l,a),T=m&&!c?l.lock:void 0,k=await oc(d.dependencies,T,f),Ae=sc(d,k.lock,a);await ic(e,k.lock,k.downloads,{signal:s,progress:o});let se=await Dn(k.lock,Ae),$=a.length?nc(l,Ae):null;return await Cn(e,l,{manifest:$,lock:se},{signal:s}),{lock:se,restored:0,registry:u}}var cc=()=>[x,S,".webfront"],ne=(e,t)=>e===t||e.startsWith(t+"/");function wt(e){try{return A(e)}catch{throw new Error(`Not a project-relative path: ${e}`)}}var Ne=(e,t,r)=>new Error(`Permission denied: ${e} ${t} is not granted by permissions.${r} in ${x}`);function Fn(e,t){let r=wt(t);if(![...e?.files??[],...e?.publish??[]].some(s=>ne(r,s)))throw Ne("reading",t,"files");return r}function zn(e,t){let r=t===""||t==="."?"":wt(t),n=[...e?.files??[],...e?.publish??[]];if(r&&n.some(o=>ne(r,o)))return{path:r,keep:()=>!0};let s=o=>n.some(i=>ne(o,i)||i.startsWith(o+"/"));if(!n.some(o=>r===""||o.startsWith(r+"/")))throw Ne("listing",r||"the project root","files");return{path:r,keep:o=>s(r?`${r}/${o.replace(/\/$/,"")}`:o.replace(/\/$/,""))}}function Gn(e,t){let r=wt(t);if(cc().some(n=>ne(r,n)))throw new Error(`Permission denied: ${t} is managed by wf and never written by a script`);if(!(e?.publish??[]).some(n=>ne(r,n)))throw Ne("writing",t,"publish");return r}function xu(e,t,r){let n=new URL(t,r);if(!(e?.fetch??[]).includes(n.origin))throw Ne("fetching",n.origin,"fetch");return n}var lc=2e3,Wn=600,Le=[1,3600],Mn=4,Et=class extends Error{constructor(t,r){super(t),this.exitCode=r}},Su=(e,t=1/0,r=Date.now())=>Math.min(r+e*1e3,t),ku=(e,t=Date.now())=>Math.max(0,(e-t)/1e3);function Nu(e,t){let r=Wn,n=e;if(n[0]==="--timeout"){if(r=Number(n[1]),!Number.isInteger(r)||rLe[1])throw new Error(`--timeout expects whole seconds from ${Le[0]} to ${Le[1]}`);n=n.slice(2)}if(!n.length||n[0].startsWith("-"))throw new Error(`Usage: ${t}`);return{timeout:r,target:n[0],args:n.slice(1)}}function Lu(e,t,r,n,s=0){let o=e?.scripts??{};if(!Object.hasOwn(o,t)){let a=Object.keys(o).sort().join(", ")||"none";throw new Error(`No script "${t}" in ${x} (scripts: ${a})`)}let[i,...c]=n(o[t]);if(i==="wf"){if(s>=Mn)throw new Error(`Scripts call wf more than ${Mn} levels deep`);return{kind:"wf",argv:[...c,...r]}}return{kind:"module",entry:{namespace:"project",path:A(i)},args:[...c,...r]}}function _n(e,t){if(e?.roots&&Object.hasOwn(e.roots,t)){let{id:n}=e.roots[t];return[n,e.packages[n]]}let r=Object.entries(e?.packages??{}).filter(([,n])=>n.name===t);if(r.length>1)throw new Error(`${t} is locked at several versions; install it as a root to choose one`);return r[0]??null}function uc(e,t){let r=t.webfront?.bin;if(typeof r=="string")return{[t.name.split("/").pop()]:r};if(r&&typeof r=="object"&&!Array.isArray(r))return r;throw t.bin?new Error(`${e} only declares an npm "bin" (a Node.js program); wf exec runs only "webfront.bin" entries`):new Error(`${e} has no WebFront executable entry ("webfront.bin" in its package.json)`)}function Au(e,t){let r=t.indexOf(":",t.startsWith("@")?t.indexOf("/"):0),[n,s]=r<0?[t,void 0]:[t.slice(0,r),t.slice(r+1)],o=_n(e,n);if(!o)throw new Error(`${n} is not installed: run wf install ${n}`);let[i,c]=o,a=uc(i,c.manifest),l=Object.keys(a),u=s??(l.length===1?l[0]:void 0);if(!u||!Object.hasOwn(a,u))throw new Error(`${i} has the WebFront entries ${l.join(", ")||"none"}: run wf exec ${n}:`);let f=String(a[u]).replace(/^\.\//,"");if(!c.files.includes(A(f)))throw new Error(`${i}: webfront.bin entry ${u} names a missing file ${f}`);return{id:i,name:u,entry:{namespace:"npm",path:`${i}/${f}`}}}var fc=new TextDecoder;function Tu({bridge:e,permissions:t,lock:r}){let n=new AbortController,s=[],o=new Set;async function i(a,l){let u=Gn(t,a);if(!(l instanceof Uint8Array))throw new TypeError("context.project.write expects a string or a Uint8Array");let f={path:u,state:"staging"};s.push(f);let m=null;try{m=await R(e,"begin",u,!1),await Z(e,{id:m,path:"output",bytes:l},n.signal),n.signal.throwIfAborted(),f.state="committing",await R(e,"commit",m),f.state="applied"}catch(d){let T=n.signal.aborted&&f.state!=="committing";throw f.state=T?"abandoned":"failed",m!==null&&await R(e,"abort",m).catch(()=>{}),d}}let c={read:a=>G(e,Fn(t,a)),list:async(a="")=>{let{path:l,keep:u}=zn(t,a);return JSON.parse(fc.decode(await R(e,"list",l))).filter(u)},write:i,resolve:a=>{let l=_n(r,a)?.[1];return l?{name:l.name,version:l.version,integrity:l.integrity}:null}};return{publications:s,async handle({operation:a,args:l}){if(n.signal.aborted)throw new Error("The script was stopped");if(!Object.hasOwn(c,a))throw new Error(`Unknown context operation: ${a}`);let u=c[a](...l);o.add(u);try{return await u}finally{o.delete(u)}},async finish(){for(let a of s)(a.state==="staging"||a.state==="committing")&&(a.unawaited=!0);for(;o.size;)await Promise.allSettled([...o]);await this.stop()},async stop(){n.abort(new Error("The script was stopped")),await Promise.allSettled([...o])}}}function ju({createWorker:e,host:t,message:r,signal:n,timeout:s=Wn,grace:o=lc,write:i}){return new Promise(c=>{let a=e(),l=[],u=null,f=!1,m=()=>u==="timeout"?124:130,d=$=>{f||(f=!0,a.terminate(),l.forEach(clearTimeout),n?.removeEventListener("abort",k),c({reason:u??"exit",...$}))},T=$=>{u||f||(u=$,a.postMessage({type:"abort"}),l.push(setTimeout(()=>d({code:m(),forced:o}),o)))},k=()=>T("interrupted"),se={console:$=>i(String($.text).replace(/\r?\n/g,`\r `)+`\r -`,$.stream),exit:$=>d({code:u&&$.code===0?m():$.code,...Array.isArray($.diagnostics)?{diagnostics:$.diagnostics}:{}}),error:$=>d({code:u?m():1,error:$.error}),call:async $=>{let U;try{U={value:await t.handle($)}}catch(oe){U={error:oe.message}}f||c.postMessage({type:"reply",id:$.id,...U})}};c.onmessage=({data:$})=>se[$?.type]?.($),c.onerror=$=>{$.preventDefault?.(),d({code:1,error:$.message||"The script Worker failed"})},n?.addEventListener("abort",k,{once:!0}),l.push(setTimeout(()=>T("timeout"),s*1e3)),c.postMessage({type:"run",...r}),n?.aborted&&k()})}function la(e,t){let r=t?e:e.filter(o=>o.unawaited),n=o=>r.filter(i=>i.state===o).map(({path:i})=>i),s=[];return t&&n("applied").length&&s.push(`Applied before the stop: ${n("applied").join(", ")}`),n("abandoned").length&&s.push(`Abandoned, unchanged: ${n("abandoned").join(", ")}`),n("failed").length&&s.push(`Failed, unchanged: ${n("failed").join(", ")}`),s}function Lu(e,t,r){let n={interrupted:"stopped by Ctrl+C",timeout:"stopped at its time limit"}[t.reason],s=la(r,n!==void 0);if(t.code===0&&!n&&!s.length)return`${e} completed.`;let o=t.forced?` (terminated after the ${t.forced/1e3} s grace period)`:"",i=t.code===0&&!n?1:t.code,a=n?`${n}${o}`:t.code===0?"ended without applying all its writes":`exited with code ${t.code}`;throw new Et([t.error,`${e} ${a}`,...s].filter(Boolean).join(`\r -`),i)}var Uu=new TextDecoder,pa=["",".tsx",".ts",".jsx",".js",".mjs",".cjs",".json",".css","/index.tsx","/index.ts","/index.js"],Fu=new Map(Object.entries({mjs:"js",cjs:"js",js:"js",jsx:"jsx",ts:"ts",tsx:"tsx",css:"css",json:"json"}));async function ha(e,t,r){try{return await e(t,r)}catch(n){if(t!=="project")throw n;return}}function da(e,t,r,n){let s=new Map,o=(c,l)=>{let u=n?.packages?.[c];if(u)return s.has(c)||s.set(c,new Set(u.files)),s.get(c).has(l)?t(`${M}/${u.key}/${l}`):void 0},i=async(c,l)=>{if(c==="project")return t(l);let u=l.indexOf("/"),[f,m]=[l.slice(0,u),l.slice(u+1)];return e?e[f]?.get(m):o(f,m)};return{read:i,find:async(c,l)=>{for(let u of pa){let f=await ha(i,c,l+u);if(f!==void 0)return r.set(`${c}:${l+u}`,f),{path:l+u,namespace:c}}throw new Error(`Cannot resolve ${l}`)}}}var ma=new Set(["assert","async_hooks","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","domain","events","fs","http","http2","https","inspector","module","net","os","path","perf_hooks","process","punycode","querystring","readline","repl","stream","string_decoder","sys","timers","tls","trace_events","tty","url","util","v8","vm","wasi","worker_threads","zlib"]),wa=/^(?:node:|[a-z_][a-z0-9_]*(?:\/|$))/;function Ea(e){if(e.startsWith("node:"))return e.slice(5).split("/")[0];let t=e.split("/")[0];return ma.has(t)?t:null}export{Et as ScriptExit,Zl as cacheState,Eu as checkFetch,ic as checkManifestDirectory,Un as checkRead,zn as checkWrite,da as createFinder,Vc as defaultRegistry,Mn as defaultTimeout,ye as dependenciesDigest,ht as describeRegistry,ve as desynchronized,D as downloadPackage,Xc as effectiveRegistry,Vl as embedTarget,cc as exactVersion,Nu as execTarget,ia as gracePeriod,tt as identifier,pu as initProject,ft as inspectCache,hu as install,Fn as listable,re as loadProject,Qe as lockFileName,N as lockPath,Wn as lockedPackage,Dc as locksDependencies,Ke as manifestFileName,ee as manifestFormat,yn as manifestName,x as manifestPath,$n as newManifest,Oe as noManifest,Ea as nodeBuiltin,wa as nodeImport,et as npmName,An as packageDirectory,M as packageRoot,Rl as parseManifest,vu as parseRunOptions,Ln as publishTogether,st as readManifest,Tn as recordPath,kn as resolveEntry,In as resolvePackages,nu as restore,dt as restorePackages,bu as runDeadline,Lu as runResult,Su as runWorker,A as safePackagePath,nt as sameOriginPath,Iu as scriptCommand,ku as scriptHost,Ou as secondsLeft,ot as serializeManifest,xl as setManifestDirectory,Ne as storePackage,Sn as syncNotice,Ie as textBytes,Se as timeoutBounds,Bc as unpackedLimit,pt as usableRegistry,lt as validateLock,te as validateManifest}; +`,$.stream),exit:$=>d({code:u&&$.code===0?m():$.code,...Array.isArray($.diagnostics)?{diagnostics:$.diagnostics}:{}}),error:$=>d({code:u?m():1,error:$.error}),call:async $=>{let U;try{U={value:await t.handle($)}}catch(oe){U={error:oe.message}}f||a.postMessage({type:"reply",id:$.id,...U})}};a.onmessage=({data:$})=>se[$?.type]?.($),a.onerror=$=>{$.preventDefault?.(),d({code:1,error:$.message||"The script Worker failed"})},n?.addEventListener("abort",k,{once:!0}),l.push(setTimeout(()=>T("timeout"),s*1e3)),a.postMessage({type:"run",...r}),n?.aborted&&k()})}function pc(e,t){let r=t?e:e.filter(o=>o.unawaited),n=o=>r.filter(i=>i.state===o).map(({path:i})=>i),s=[];return t&&n("applied").length&&s.push(`Applied before the stop: ${n("applied").join(", ")}`),n("abandoned").length&&s.push(`Abandoned, unchanged: ${n("abandoned").join(", ")}`),n("failed").length&&s.push(`Failed, unchanged: ${n("failed").join(", ")}`),s}function Pu(e,t,r){let n={interrupted:"stopped by Ctrl+C",timeout:"stopped at its time limit"}[t.reason],s=pc(r,n!==void 0);if(t.code===0&&!n&&!s.length)return`${e} completed.`;let o=t.forced?` (terminated after the ${t.forced/1e3} s grace period)`:"",i=t.code===0&&!n?1:t.code,c=n?`${n}${o}`:t.code===0?"ended without applying all its writes":`exited with code ${t.code}`;throw new Et([t.error,`${e} ${c}`,...s].filter(Boolean).join(`\r +`),i)}var Mu=new TextDecoder,mc=["",".tsx",".ts",".jsx",".js",".mjs",".cjs",".json",".css","/index.tsx","/index.ts","/index.js"],Wu=new Map(Object.entries({mjs:"js",cjs:"js",js:"js",jsx:"jsx",ts:"ts",tsx:"tsx",css:"css",json:"json"}));async function wc(e,t,r){try{return await e(t,r)}catch(n){if(t!=="project")throw n;return}}function Ec(e,t,r,n){let s=new Map,o=(a,l)=>{let u=n?.packages?.[a];if(u)return s.has(a)||s.set(a,new Set(u.files)),s.get(a).has(l)?t(`${M}/${u.key}/${l}`):void 0},i=async(a,l)=>{if(a==="project")return t(l);let u=l.indexOf("/"),[f,m]=[l.slice(0,u),l.slice(u+1)];return e?e[f]?.get(m):o(f,m)};return{read:i,find:async(a,l)=>{for(let u of mc){let f=await wc(i,a,l+u);if(f!==void 0)return r.set(`${a}:${l+u}`,f),{path:l+u,namespace:a}}throw new Error(`Cannot resolve ${l}`)}}}var gc=new Set(["assert","async_hooks","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","domain","events","fs","http","http2","https","inspector","module","net","os","path","perf_hooks","process","punycode","querystring","readline","repl","stream","string_decoder","sys","timers","tls","trace_events","tty","url","util","v8","vm","wasi","worker_threads","zlib"]),yc=/^(?:node:|[a-z_][a-z0-9_]*(?:\/|$))/;function $c(e){if(e.startsWith("node:"))return e.slice(5).split("/")[0];let t=e.split("/")[0];return gc.has(t)?t:null}export{Et as ScriptExit,tu as cacheState,xu as checkFetch,aa as checkManifestDirectory,Fn as checkRead,Gn as checkWrite,Ec as createFinder,Ha as defaultRegistry,vl as defaultTerminalShortcut,Wn as defaultTimeout,xe as dependenciesDigest,ht as describeRegistry,Ie as desynchronized,D as downloadPackage,Ka as effectiveRegistry,Kl as embedTarget,ca as exactVersion,Au as execTarget,lc as gracePeriod,rt as identifier,wu as initProject,ft as inspectCache,Eu as install,zn as listable,re as loadProject,et as lockFileName,S as lockPath,_n as lockedPackage,za as locksDependencies,Qe as manifestFileName,ee as manifestFormat,xn as manifestName,x as manifestPath,$n as newManifest,ve as noManifest,$c as nodeBuiltin,yc as nodeImport,tt as npmName,Tn as packageDirectory,M as packageRoot,Il as parseManifest,Nu as parseRunOptions,ya as parseShortcut,An as publishTogether,st as readManifest,jn as recordPath,Nn as resolveEntry,Sn as resolvePackages,au as restore,dt as restorePackages,Su as runDeadline,Pu as runResult,ju as runWorker,A as safePackagePath,nt as sameOriginPath,Lu as scriptCommand,Tu as scriptHost,ku as secondsLeft,ot as serializeManifest,Ol as setManifestDirectory,ke as storePackage,Ln as syncNotice,Se as textBytes,Le as timeoutBounds,Ya as unpackedLimit,pt as usableRegistry,lt as validateLock,te as validateManifest}; diff --git a/js/developer/environment/project.mjs b/js/developer/environment/project.mjs index 17a1ed8e..c5366a7d 100644 --- a/js/developer/environment/project.mjs +++ b/js/developer/environment/project.mjs @@ -10,7 +10,9 @@ export {packageRoot} from './paths.mjs'; const decoder = new TextDecoder(); const encoder = new TextEncoder(); -export const noManifest = 'No webfront.project.json: run wf init'; +// The whole sequence, not only its first step: the reader may never have seen a WebFront project (wf help agents). +export const noManifest = 'No webfront.project.json: run wf init, then wf dev (the interface is TypeScript/TSX in ui/; ' + + 'wf create app writes a first one; wf help agents gives the sequence)'; export const desynchronized = 'The lock does not match the dependencies of webfront.project.json; run wf install --update to resolve them again'; async function readOptional(bridge, path) { @@ -93,7 +95,7 @@ export function resolveEntry(manifest, argument, command) { if (Object.hasOwn(entries, 'main')) return entries.main; const names = Object.keys(entries); if (names.length === 1) return entries[names[0]]; - throw new Error(`Usage: ${command} (declare entries.main in ${manifestPath} to omit the entry)`); + throw new Error(`Usage: ${command}, for example ui/main.tsx (declare entries.main in ${manifestPath} to omit the entry; wf create app writes a first ui/main.ts)`); } // wf embed : the class is the provider's name. wf embed --output : the class is the file name. diff --git a/js/developer/environment/runtime.mjs b/js/developer/environment/runtime.mjs index bb1d6cf3..218bf2b8 100644 --- a/js/developer/environment/runtime.mjs +++ b/js/developer/environment/runtime.mjs @@ -1,23 +1,26 @@ import {Terminal} from '@xterm/xterm'; import {FitAddon} from '@xterm/addon-fit'; -import {LineEditor, tokenize, wordAtEnd, unicodeProvider, clearScreen, historyLimit} from './terminal.mjs'; +import {LineEditor, tokenize, wordAtEnd, unicodeProvider, clearScreen, historyLimit, inline} from './terminal.mjs'; import {manifestPath, setManifestDirectory} from './manifest.mjs'; import {discoverCommands, runCommand, reservedNames} from './commands.mjs'; export {discoverCommands, reservedNames}; import {validateLock} from './packages.mjs'; import {call, readProject, publish, writeChunks} from './io.mjs'; import {isUnsafe} from './paths.mjs'; -import {createStarter} from './starter.mjs'; +import {createStarter, starterNames} from './starter.mjs'; import {install, initProject} from './installer.mjs'; import {restore, describeRegistry} from './restore.mjs'; import {loadProject, syncNotice, resolveEntry, embedTarget, lockPath, packageRoot, noManifest} from './project.mjs'; import {parseRunOptions, scriptCommand, execTarget, scriptHost, runWorker, runResult, runDeadline, secondsLeft} from './scripts.mjs'; -import {build, dev, showPreview} from './development.mjs'; +import {build, dev, showPreview, previewPage} from './development.mjs'; import {parseTestOptions, specFiles, jasmineCore, runnerFiles, runInFrame, reportResult, fitResult, stoppedRun, abortable, testDirectory} from './testing.mjs'; import {generateProvider, applicationPage} from './embed.mjs'; import {typescriptPackage, parseCheckOptions, checkHost} from './typecheck.mjs'; import {pinnedStarters} from './bootstrap.mjs'; +import {createWorkspace, isManaged} from './workspace.mjs'; import {connectAutomation as connectAgent, clipText, automationHelp, onAutomationNotice} from './automation.mjs'; +import {ls, cat, tree, mounts, fileCommandHelp, withheld, withheldReason} from './files.mjs'; +import {dependencyTree, why as whyInstalled, info as packageInfo} from './dependencies.mjs'; const encoder = new TextEncoder(); const decoder = new TextDecoder(); @@ -91,7 +94,8 @@ function dependencyNotices(lock, packages) { } export async function compile(bridge, entry, signal) { - const lock = await readLock(bridge); + // Without dependency there is no lock: wf init writes the manifest only, and wf dev and wf build already accept that. + const lock = await readLock(bridge, true); const packages = await readPackages(bridge, lock, signal); const files = await buildInWorker(bridge, {type: 'build', entry, lock, packages}, signal); files.set('index.html', applicationPage(files)); @@ -99,7 +103,7 @@ export async function compile(bridge, entry, signal) { } async function create([starter, directory, ...extra], {bridge, config, signal}) { - if (!starter || extra.length) throw new Error('Usage: wf create [directory]'); + if (!starter || extra.length) throw new Error(`Usage: wf create [directory]${availableStarters(config)}`); return createStarter(bridge, config, [starter, directory ?? 'ui'], {signal}); } @@ -125,6 +129,7 @@ async function preview(args, {bridge, signal, preview: frame}) { const project = await loadProject(bridge); const entry = resolveEntry(project.manifest, args[0], 'wf preview '); const result = await compile(bridge, entry, signal); + result.files.set('index.html', previewPage(result.files)); await publish(bridge, '.webfront/developer/preview', result.files, {signal}); showPreview(frame); return syncNotice(project) + 'Preview ready.'; @@ -206,6 +211,9 @@ async function check(args, {bridge, signal, write = () => {}, createWorker = che return syncNotice(project) + runResult('Type check', outcome, host.publications); } +// Milliseconds before each new attempt to empty the directory of a finished run; the last attempt is not followed by a wait. +const cleanupRetryDelays = [20, 40, 80, 160, 320, undefined]; + // wf test [--timeout ] [pattern]: the specs of "test.specs" under the Jasmine of the lock, in a frame of this page. // context.onReport receives the structured report, also when the run fails. --timeout, never later than the deadline // of the wf script that runs this command, covers the whole command: no step waits for the bridge past it, and Ctrl+C @@ -253,23 +261,100 @@ async function test(args, {bridge, signal, write = () => {}, createFrame, onRepo } finally { clearTimeout(timer); signal?.removeEventListener('abort', interrupt); - // The files of the run are not needed any more: an empty directory replaces them, for at most two seconds. - let cleanupTimer; + // The files of the run are not needed any more: an empty directory replaces them, for at most two seconds. The + // server may still be sending a file to a frame removed in the middle of its run, and Windows refuses to replace + // a directory with an open file: the publication is tried again once the server has had time to close it. + let cleanupTimer, retryTimer, expired = false; + const empty = async () => { + for (const delay of cleanupRetryDelays) { + try { return await publish(bridge, directory, new Map()); } catch { /* tried again below */ } + if (expired || delay === undefined) return; + await new Promise(resolve => { retryTimer = setTimeout(resolve, delay); }); + } + }; try { - await Promise.race([publish(bridge, directory, new Map()).catch(() => {}), - new Promise(resolve => { cleanupTimer = setTimeout(resolve, 2000); })]); - } finally { clearTimeout(cleanupTimer); } + await Promise.race([empty(), new Promise(resolve => { cleanupTimer = setTimeout(resolve, 2000); })]); + } finally { + expired = true; + clearTimeout(cleanupTimer); + clearTimeout(retryTimer); + } } } -async function list(_args, {bridge}) { +// wf list [--tree]: the locked packages, or their graph under the roots of the manifest. +async function list(args, {bridge}) { + if (args.length > 1 || (args.length && args[0] !== '--tree')) throw new Error(`Usage: ${usage.list}`); const project = await loadProject(bridge); - const names = Object.keys(project.lock?.packages ?? {}).sort().join('\n'); + if (args.length) return syncNotice(project) + dependencyTree(project.lock); + const names = Object.keys(project.lock?.packages ?? {}).sort().map(inline).join('\n'); return syncNotice(project) + (names || 'No installed packages.'); } -const help = () => 'wf init [name]\nwf create [directory]\nwf install [--update] [[@range] ...]\nwf restore [--offline]\nwf run [--timeout ] )HTML"; - /// Serves the environment archive and the optional local registry under /driver/, from outside the project. class DriverFS { public: @@ -239,15 +197,6 @@ class DriverFS { std::optional open(std::filesystem::path path) const { const auto relative = path.relative_path().generic_string(); - if (relative == "driver/case.html") { - static const auto words = [] { - std::vector packed((suitePage.size() + 7) / 8); - for (std::size_t i = 0; i < suitePage.size(); ++i) - packed[i / 8] |= static_cast(static_cast(suitePage[i])) << ((7 - i % 8) * 8); - return packed; - }(); - return fs::File{std::span{words}, suitePage.size()}; - } if (relative == "driver/environment.tgz") return read(sources().archive); // The starters the environment pins sit next to its archive: plain file names only. @@ -335,11 +284,18 @@ class Outcome { std::string failure; }; -// Waits for the environment, runs the command and reports to C++; the page closes itself when it is done. +// Waits for the environment, runs the command and reports to C++; C++ closes the window when the page says it is done. inline constexpr auto driverScript = R"JS( (async () => { const report = (name, ...args) => webFront.cppFunction(name)(...args); - const stop = () => window.close(); + const stop = () => report('wf.finished').catch(() => window.close()); + // Tests that own a DOM must stay in the viewport, including the nested wf test runner. + const createFrame = () => { + const frame = document.createElement('iframe'); + frame.title = 'WebFront tests'; + frame.style.cssText = 'position:fixed;inset:0;width:100%;height:100%;border:0;z-index:2147483647;background:white'; + return frame; + }; try { await webFront.ready; // Observe the bootstrap status rather than polling the DOM every 50 ms. @@ -360,69 +316,36 @@ inline constexpr auto driverScript = R"JS( throw Object.assign(new Error('Bootstrap failed: this developer environment has no non-interactive mode'), {bootstrap: true}); config.starters = Object.fromEntries(Object.entries(environment.starters ?? {}).map(([name, value]) => [name, {url: new URL(value.archive, new URL(config.environment, location.href)).href, integrity: value.integrity}])); - const suite = JSON.parse(await report('wf.suite')); - if (suite) { - let failed = false; - // One native browser, one fresh realm per command: imports, timers, Workers, listeners and frames - // belong to that realm. Only the explicit project and immutable HTTP resources survive between cases. - for (let index = 0; index < suite.length; ++index) { - const item = suite[index]; - await report('wf.caseStarted', index); - const frame = document.createElement('iframe'); - frame.style.cssText = 'position:fixed;left:-10000px;top:0;width:1024px;height:768px'; - const finished = new Promise((resolve, reject) => { - const receive = event => { - if (event.source !== frame.contentWindow || event.data?.driverCase !== index) return; - removeEventListener('message', receive); - event.data.error ? reject(new Error(event.data.error)) : resolve(event.data.status); - }; - addEventListener('message', receive); - }); - window.webfrontDriverCase = {index, item, config, entry: environment.entry}; - frame.src = '/driver/case.html?case=' + index; - document.body.append(frame); - try { failed = (await finished !== item.expect) || failed; } - finally { frame.remove(); delete window.webfrontDriverCase; } - } - await report('wf.result', failed ? 1 : 0, JSON.stringify({exitCode: failed ? 1 : 0, output: 'Suite completed'})); - } else { - const argv = JSON.parse(await report('wf.arguments')); - await report('wf.commandStarted'); - await runtime.runNonInteractive(argv, {bridge: webFront, config, preview: document.getElementById('preview'), - signal: new AbortController().signal, write: () => {}, onExit: () => {}, - reporter: json => report('wf.result', JSON.parse(json).exitCode, json)}); - } + const argv = JSON.parse(await report('wf.arguments')); + await report('wf.commandStarted'); + await runtime.runNonInteractive(argv, {bridge: webFront, config, createFrame, preview: document.getElementById('preview'), + signal: new AbortController().signal, write: () => {}, onExit: () => {}, + reporter: json => report('wf.result', JSON.parse(json).exitCode, json)}); } catch (error) { await report('wf.bootstrapFailed', String(error?.message ?? error)).catch(() => {}); } finally { stop(); } })(); )JS"; -// Owns the connected UI and remembers a close requested before the handshake. Connection and -// watchdog callbacks share one lock, so neither ordering can lose the close or launch a late command. -template -class DriverBrowser { -public: - void connected(UI ui) { - std::scoped_lock lock{mutex}; - if (browser) - return; // Commands and wf test create their own connected frames; inject only the native page. - browser = std::move(ui); - browser->addScript(closing ? "window.close()" : driverScript); - } - void close() { - std::scoped_lock lock{mutex}; - if (std::exchange(closing, true)) - return; - if (browser) - browser->addScript("window.close()"); - } - -private: - std::mutex mutex; - std::optional browser; - bool closing = false; -}; +// Asks the window to close until show() returns (`shown`). requestClose() reaches nothing before the window exists or +// once it closed, and keeps no request, so it is repeated, as UIThread::stop() does (docs/HOST_INTEGRATION.md). The +// request is native: it does not depend on the page, which a spec may block. False when the window outlives `patience`. +template +bool closeUntilShown(std::stop_token shown, RequestClose requestClose, std::chrono::steady_clock::duration patience) { + std::mutex mutex; + std::condition_variable_any wake; + std::unique_lock lock{mutex}; + const auto limit = std::chrono::steady_clock::now() + patience; + do { + requestClose(); + wake.wait_for(lock, shown, 10ms, [] { + return false; + }); + if (shown.stop_requested()) + return true; + } while (std::chrono::steady_clock::now() < limit); + return false; +} inline std::string jsonArray(const std::vector& items) { std::string json = "["; @@ -473,6 +396,7 @@ struct PlainSetup { template int run(const Options& options, Setup&& setup = {}) { using App = webfront::BasicDeveloperApp, DriverFS, typename std::remove_reference_t::Pages>; + static_assert(frontend::CanRequestClose>, "The driver closes its window with requestClose()"); if (!std::filesystem::is_regular_file(*options.environment)) { std::cerr << "Bootstrap environment archive not found: " << *options.environment << '\n'; return bootstrapStatus; @@ -485,25 +409,7 @@ int run(const Options& options, Setup&& setup = {}) { if (sources().registry) sources().registry = std::filesystem::canonical(*sources().registry); - const auto cases = options.suite ? parseSuite(readSuite(*options.suite), options.filter) : std::vector{}; - if (options.reportDirectory) { - std::filesystem::create_directories(*options.reportDirectory); - for (const auto& item : cases) - std::filesystem::remove(*options.reportDirectory / (item.name + ".json")); - } - std::string suiteJson = "null"; - if (!cases.empty()) { - suiteJson = "["; - for (const auto& item : cases) - suiteJson += (suiteJson.size() > 1 ? "," : "") + std::string("{\"name\":") + json::quote(item.name) + ",\"command\":" + jsonArray(item.command) - + ",\"expect\":" + std::to_string(item.expected) + "}"; - suiteJson += "]"; - if (suiteJson.size() > 60000) - throw UsageError("Suite arguments exceed the bridge string budget (60000 bytes)"); - } - std::size_t completed = 0; - bool caseFailed = false; - const auto started = std::chrono::steady_clock::now(); + const auto started = std::chrono::steady_clock::now(); const auto phase = [&](std::string_view name) { std::cout << "driver " << std::chrono::duration(std::chrono::steady_clock::now() - started).count() << "ms " << name << std::endl; }; @@ -512,36 +418,12 @@ int run(const Options& options, Setup&& setup = {}) { App app{options.project, {.port = "0", .remoteFileTransport = webfront::RemoteFileTransport::loopbackAttested}}; // 127.0.0.1: the test pages are not the embedded view bool commandStarted = false; app.cppFunction("wf.commandStarted", [&] { - if (options.suite || std::exchange(commandStarted, true)) + if (std::exchange(commandStarted, true)) throw std::runtime_error("Unexpected single-command start"); if (options.commandTimeout) deadlines.beginCase(*options.commandTimeout); phase("begin command"); }); - app.cppFunction("wf.suite", [suiteJson] { - return suiteJson; - }); - app.cppFunction("wf.caseStarted", [&](double index) { - if (index != static_cast(completed) || completed >= cases.size()) - throw std::runtime_error("Unexpected suite start index"); - deadlines.beginCase(cases[completed].timeout); - phase("begin " + cases[completed].name); - }); - app.cppFunction("wf.caseResult", [&](double index, double exitCode, std::string json) { - if (index != static_cast(completed) || completed >= cases.size()) - throw std::runtime_error("Unexpected suite result index"); - deadlines.endCase(); - const auto& item = cases[completed]; - printOutput(json); - Options reportOptions; - reportOptions.report = *options.reportDirectory / (item.name + ".json"); - writeReport(reportOptions, json); - if (exitCode != item.expected) - std::cerr << "suite case " << item.name << ": expected status " << item.expected << ", got " << exitCode << std::endl; - caseFailed = (exitCode != item.expected) || caseFailed; - phase("end " + item.name); - ++completed; - }); app.cppFunction("wf.arguments", [arguments = jsonArray(options.command)] { return arguments; }); @@ -554,6 +436,9 @@ int run(const Options& options, Setup&& setup = {}) { app.cppFunction("wf.progress", [](std::string message) { std::cout << "wf spec: " << message << std::endl; }); + app.cppFunction("wf.finished", [&deadlines] { + deadlines.finish(); + }); setup.configure(app); app.bootstrap("developer", {.environment = "/driver/environment.tgz", @@ -561,30 +446,25 @@ int run(const Options& options, Setup&& setup = {}) { .registry = options.registryDirectory ? std::optional{"/driver/registry/"} : std::nullopt, .manifestDirectory = options.manifestDirectory}); - DriverBrowser browser; - auto subscription = app.subscribeUIStarted([&](typename App::UI ui) { - browser.connected(ui); + // Handlers run one at a time on the server thread. Commands and wf test create their own connected frames: the + // driver's script goes to the native page only. + auto subscription = app.subscribeUIStarted([injected = false](typename App::UI ui) mutable { + if (!std::exchange(injected, true)) + ui.addScript(driverScript); }); - // The time limit: ask the page to close, then end the process if the browser does not follow. - std::jthread watchdog([&](std::stop_token stop) { - std::mutex mutex; - std::condition_variable_any wake; - std::unique_lock lock{mutex}; - if (!deadlines.expired(stop)) - return; - outcome.timedOut(); - try { - browser.close(); - } catch (const std::exception&) {} // the bridge is gone: the forced exit below still applies - if (!stop.stop_requested() - && !wake.wait_for(lock, - stop, - 10s, - [] { - return false; - }) - && !stop.stop_requested()) { - std::cerr << "The browser did not close after the driver deadline elapsed\n"; + // Closes the window when the page is done or a time limit elapses; ends the process if the window does not follow. + std::jthread closer([&](std::stop_token shown) { + if (deadlines.expired(shown)) + outcome.timedOut(); + else if (shown.stop_requested()) + return; // the window closed by itself + if (!closeUntilShown( + shown, + [&] { + return app.requestClose(); + }, + 10s)) { + std::cerr << "The browser did not close when the driver asked\n"; std::cerr.flush(); std::_Exit(timeoutStatus); } @@ -592,7 +472,8 @@ int run(const Options& options, Setup&& setup = {}) { phase("begin browser"); app.show(); phase("end browser / begin shutdown"); - watchdog.request_stop(); + closer.request_stop(); + closer.join(); // no requestClose() may still run when shutdown() starts app.shutdown(); phase("end shutdown"); @@ -612,8 +493,6 @@ int run(const Options& options, Setup&& setup = {}) { std::cerr << failure << '\n'; else std::cerr << "The browser closed before the command reported a result\n"; - if (!cases.empty() && status == 0 && (caseFailed || completed != cases.size())) - status = 1; return setup.finish(status); } @@ -623,6 +502,7 @@ int main(int argc, char** argv, std::string_view program, Setup&& setup = {}) { try { // CEF child processes must dispatch before interpreting application arguments or creating files. webfront::detail::ensureFrontendInitialized(); + [[maybe_unused]] const auto requestLog = logRequests(); #if defined(WEBFRONT_EMBED_CEF) && defined(__linux__) std::optional temporaryProfile; if constexpr (std::is_same_v) { @@ -635,8 +515,7 @@ int main(int argc, char** argv, std::string_view program, Setup&& setup = {}) { return run(parse(argc, argv), std::forward(setup)); } catch (const UsageError& error) { std::cerr << program << ": " << error.what() << "\nUsage: " << program << " --project [--environment --integrity ] " - << "[--registry-dir ] [--report ] [--timeout ] [--command-timeout ] [--suite --report-dir " - "[--filter ]] [--] " + << "[--registry-dir ] [--report ] [--timeout ] [--command-timeout ] [--] " "[arguments...]\n"; return usageStatus; } catch (const std::exception& error) { diff --git a/test/fixtures/wf-project/tests/arithmetic.spec.js b/test/fixtures/wf-project/tests/arithmetic.spec.js index f7944f41..79d6d09a 100644 --- a/test/fixtures/wf-project/tests/arithmetic.spec.js +++ b/test/fixtures/wf-project/tests/arithmetic.spec.js @@ -2,17 +2,3 @@ describe('arithmetic', () => { it('adds', () => { expect(1 + 1).toBe(2); }); it('fails on purpose', () => { expect(1 + 1).toBe(3); }); }); - -// Run by name in separate commands (see test/web/CMakeLists.txt): the first leaves values behind and the second must find -// none, which proves that each command starts in a fresh realm. Cleaning up here would make that check vacuous. -describe('session storage', () => { - it('writes its own storage', () => { - localStorage.setItem('wf-session-case', 'previous'); - sessionStorage.setItem('wf-session-case', 'previous'); - expect(localStorage.getItem('wf-session-case')).toBe('previous'); - }); - it('starts with clean storage', () => { - expect(localStorage.getItem('wf-session-case')).toBeNull(); - expect(sessionStorage.getItem('wf-session-case')).toBeNull(); - }); -}); diff --git a/test/fixtures/wf-sleep-environment/runtime.mjs b/test/fixtures/wf-sleep-environment/runtime.mjs index 327782fb..4ca8f688 100644 --- a/test/fixtures/wf-sleep-environment/runtime.mjs +++ b/test/fixtures/wf-sleep-environment/runtime.mjs @@ -5,13 +5,17 @@ export async function mount() { await new Promise(resolve => setTimeout(resolve, 5000)); } +// `run sleep` waits on a timer; `run block` blocks the page, so that nothing in it can close the window. export async function runNonInteractive(argv, {bridge}) { - if (argv.join(' ') !== 'run sleep') throw new Error('Expected the sleeping watchdog command'); - const sleeping = new Promise(resolve => setTimeout(resolve, 120000)); - const call = (name, ...args) => bridge.cppFunction(`webfront.developer.${name}`)(...args); - const id = await call('begin', 'sleep.started', false); + const command = argv.join(' '); + if (command !== 'run sleep' && command !== 'run block') throw new Error('Expected the sleeping or blocking watchdog command'); + const name = command === 'run sleep' ? 'sleep' : 'block'; + const call = (operation, ...args) => bridge.cppFunction(`webfront.developer.${operation}`)(...args); + const id = await call('begin', `${name}.started`, false); await call('write', id, 'output', 0, new TextEncoder().encode('running')); await call('commit', id); - await sleeping; + if (name === 'block') + for (;;) {} + await new Promise(resolve => setTimeout(resolve, 120000)); throw new Error('The watchdog did not stop the sleeping command'); } diff --git a/test/fuzz/README.md b/test/fuzz/README.md index 44411c1e..a7987f83 100644 --- a/test/fuzz/README.md +++ b/test/fuzz/README.md @@ -5,7 +5,7 @@ Clang/libFuzzer, ASan, UBSan, standard library hardening and pattern initializat Linux with Clang/compiler-rt is validated in CI. Apple Clang does not include libFuzzer; on macOS install it externally (for example as part of LLVM/compiler-rt) and use compatible ASan/UBSan runtimes. CMake rejects missing runtimes during configuration. -It works independently of `WEBFRONT_ENABLE_TESTING`; no Catch2 or CEF is needed. +It works independently of `WEBFRONT_ENABLE_TESTING`; neither the unit tests nor CEF are needed. The binary corpus files use the existing wire formats. Seeds derive from `MessagesTests.cpp` (handshake, print call, scalar, tuple, typed arrays and return), diff --git a/test/sanitizers/tsan.supp b/test/sanitizers/tsan.supp index 7a05b04e..257cfecf 100644 --- a/test/sanitizers/tsan.supp +++ b/test/sanitizers/tsan.supp @@ -1,7 +1,9 @@ # ThreadSanitizer suppressions of the sanitizers job (BuildAndTest.yml). # -# GLib is not instrumented, and GMutex and the reference counts of its sources are futexes and atomics that ThreadSanitizer -# cannot see: a GSource that one thread allocates (g_idle_add_full, as the interface-thread executor and UILoopStop do) and -# that the loop thread frees after dispatching it is reported as a race although GLib orders the two itself. A race is -# suppressed only when one of its stacks goes through libglib; the code of WebFront around it stays checked. -race:libglib-2.0.so +# No race suppression: the Linux interface loop creates/removes its single GLib source on the interface thread. +# Other threads signal an eventfd and publish their work through the C++ host/stop mutexes (#542). +# +# This holds because the sanitizers job configures -DWEBFRONT_EMBED_WEBKITGTK=OFF: the WebKitGTK adapter still +# queues work with g_idle_add_full, which GLib orders with futexes ThreadSanitizer cannot see. A job that runs +# WebKitGTK under TSan must restore `race:libglib-2.0.so` (a race is then suppressed only when one of its stacks +# goes through libglib; WebFront's own code stays checked). diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index cc961cb9..131ece6d 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -106,12 +106,15 @@ def run(self, operation, arguments=None, state="succeeded"): def close(self): if self.child.poll() is None: self.child.stdin.close() + # The agent ends on its own within about 9 s when a browser does not close: 5 s of grace, then up to 2 s to + # end its processes and 2 s to remove its profile. Wait longer than that, so a loaded machine is not a failure. try: - self.child.wait(timeout=10) - except subprocess.TimeoutExpired: + self.child.wait(timeout=30) + except subprocess.TimeoutExpired as error: self.child.kill() self.child.wait() - raise + details = self.log_path.read_text()[-2000:] if self.log_path and self.log_path.exists() else "" + raise TimeoutError(f"The agent did not exit after its input closed; native stderr: {details}") from error self.reader.join(timeout=2) @@ -287,12 +290,13 @@ def watchdog(args): Only the test archive replaces the operation body. The real signed callback, runner, native deadline, window close grace, stdio EOF and endpoint cleanup remain on the production path. + The agent is driven through MCP, the way agents drive it; the CLI shares the same native + revocation, and its own exit statuses are checked by the failed relaunch below. """ pathlib.Path(args.work).mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(dir=args.work, prefix="watchdog-") as temporary: root = pathlib.Path(temporary) - if args.scenario == "cli-watchdog": - check_windows_profile_cleaner(args.agent, root) + check_windows_profile_cleaner(args.agent, root) project = root / "project" shutil.copytree(args.fixture, project) environment = root / "watchdog-environment.tgz" @@ -312,17 +316,16 @@ def watchdog(args): exports = re.findall(rb"([A-Za-z_$][A-Za-z0-9_$]*) as runNonInteractive(?=[,}])", data) assert len(exports) == 1, "The watchdog fixture needs the real runNonInteractive export" data += b"\n" + exports[0] + blocked - if args.scenario == "mcp-watchdog": - connect = re.findall(rb"([A-Za-z_$][A-Za-z0-9_$]*) as connectAutomation(?=[,}])", data) - assert len(connect) == 1 - # A bridge RangeError (a message past the bridge's maximum, lowered for this call) consumes a JS - # sequence without reaching native code. - data += (b"\nconst beforeGap=" + connect[0] + b";" + connect[0] + - b"=context=>{const limit=context.bridge.maxMessageBytes;context.bridge.maxMessageBytes=70000;" - b"void context.call('poll','x'.repeat(70000)).then(()=>window.close()," - b"()=>{context.bridge.maxMessageBytes=limit;beforeGap(context);});};") - # Only this startup test needs a delay longer than the operation's two-second deadline. - data = b"await new Promise(resolve => setTimeout(resolve,3000));\n" + data + connect = re.findall(rb"([A-Za-z_$][A-Za-z0-9_$]*) as connectAutomation(?=[,}])", data) + assert len(connect) == 1 + # A bridge RangeError (a message past the bridge's maximum, lowered for this call) consumes a JS + # sequence without reaching native code. + data += (b"\nconst beforeGap=" + connect[0] + b";" + connect[0] + + b"=context=>{const limit=context.bridge.maxMessageBytes;context.bridge.maxMessageBytes=70000;" + b"void context.call('poll','x'.repeat(70000)).then(()=>window.close()," + b"()=>{context.bridge.maxMessageBytes=limit;beforeGap(context);});};") + # Only this startup test needs a delay longer than the operation's two-second deadline. + data = b"await new Promise(resolve => setTimeout(resolve,3000));\n" + data member.size = len(data) replaced = True output.addfile(member, io.BytesIO(data) if data is not None else None) @@ -338,49 +341,44 @@ def watchdog(args): profiles = pathlib.Path(profile_root).resolve() forced_environment = dict(os.environ, TMPDIR=str(profiles), TEMP=str(profiles), TMP=str(profiles)) with (pathlib.Path(args.work) / "watchdog.log").open("w") as log: - if args.scenario == "mcp-watchdog": - client = Client([args.agent, *command, "--mcp", "--listen", str(endpoint)], log, env=forced_environment) + client = Client([args.agent, *command, "--mcp", "--listen", str(endpoint)], log, env=forced_environment) + try: + client.initialize() + client.start("build") try: - client.initialize() - client.start("build") - try: - status = client.child.wait(timeout=30) - except subprocess.TimeoutExpired: - raise AssertionError(f"The forced exit did not happen\n{pathlib.Path(log.name).read_text()}") from None - assert status == 71, f"exit {status}\n{pathlib.Path(log.name).read_text()}" - assert isinstance(client.messages.get(timeout=2), EOFError), "A renderer retained MCP stdout" - finally: - client.close() - else: - cli = subprocess.run([args.agent, *command, "--listen", str(endpoint), "--operation", "build"], - stdout=subprocess.PIPE, stderr=log, text=True, timeout=45, env=forced_environment) - assert cli.returncode == 71, f"exit {cli.returncode}\n{cli.stdout}\n{pathlib.Path(log.name).read_text()}" + status = client.child.wait(timeout=30) + except subprocess.TimeoutExpired: + raise AssertionError(f"The forced exit did not happen\n{pathlib.Path(log.name).read_text()}") from None + assert status == 71, f"exit {status}\n{pathlib.Path(log.name).read_text()}" + assert isinstance(client.messages.get(timeout=2), EOFError), "A renderer retained MCP stdout" + finally: + client.close() assert (project / "renderer.started").is_file(), "The deadline expired before the renderer actually blocked" assert not endpoint.exists(), "The forced exit left its attachment capability behind" left, contents = remaining_profiles(profiles) assert not left, f"The forced exit left its native profile behind: {left} {contents}\n{pathlib.Path(log.name).read_text()}" - if args.scenario == "cli-watchdog": - # This same-path relaunch must reach its authenticated page before the intentional error. - # It checks directory reuse and Unicode failure reporting in one process; normal builds - # are exercised by the functional MCP/shared-window scenario. - failed_environment = root / "failed-bootstrap.tgz" - with tarfile.open(environment, "r:gz") as archive, tarfile.open(failed_environment, "w:gz", compresslevel=1) as output: - for member in archive.getmembers(): - data = archive.extractfile(member).read() if member.isfile() else None - if member.name == "package/runtime.mjs": - connect = re.findall(rb"([A-Za-z_$][A-Za-z0-9_$]*) as connectAutomation(?=[,}])", data) - assert len(connect) == 1 - data += b"\n" + connect[0] + b"=()=>{throw new Error('B'+String.fromCodePoint(0xe9).repeat(1022)+String.fromCodePoint(0x1f600)+'tail');};" - member.size = len(data) - output.addfile(member, io.BytesIO(data) if data is not None else None) - failed_command = list(command) - failed_command[failed_command.index("--environment") + 1] = str(failed_environment) - failed_command[failed_command.index("--integrity") + 1] = "sha512-" + base64.b64encode(hashlib.sha512(failed_environment.read_bytes()).digest()).decode() - failed = subprocess.run([args.agent, *failed_command, "--listen", str(endpoint), "--operation", "build"], - capture_output=True, text=True, encoding="utf-8", timeout=45) - assert failed.returncode == 70, (failed.returncode, failed.stdout, failed.stderr) - assert "Automation startup: B" + "é" * 511 + "\n" in failed.stderr, failed.stderr - assert not endpoint.exists() + # This same-path relaunch, through the CLI, must reach its authenticated page before the intentional error. + # It checks endpoint reuse and Unicode failure reporting in one process; normal builds + # are exercised by the functional MCP scenario. + failed_environment = root / "failed-bootstrap.tgz" + # From the original archive: the blocked one also delays its startup by three seconds. + with tarfile.open(args.environment, "r:gz") as archive, tarfile.open(failed_environment, "w:gz", compresslevel=1) as output: + for member in archive.getmembers(): + data = archive.extractfile(member).read() if member.isfile() else None + if member.name == "package/runtime.mjs": + connect = re.findall(rb"([A-Za-z_$][A-Za-z0-9_$]*) as connectAutomation(?=[,}])", data) + assert len(connect) == 1 + data += b"\n" + connect[0] + b"=()=>{throw new Error('B'+String.fromCodePoint(0xe9).repeat(1022)+String.fromCodePoint(0x1f600)+'tail');};" + member.size = len(data) + output.addfile(member, io.BytesIO(data) if data is not None else None) + failed_command = list(command) + failed_command[failed_command.index("--environment") + 1] = str(failed_environment) + failed_command[failed_command.index("--integrity") + 1] = "sha512-" + base64.b64encode(hashlib.sha512(failed_environment.read_bytes()).digest()).decode() + failed = subprocess.run([args.agent, *failed_command, "--listen", str(endpoint), "--operation", "build"], + capture_output=True, text=True, encoding="utf-8", timeout=45) + assert failed.returncode == 70, (failed.returncode, failed.stdout, failed.stderr) + assert "Automation startup: B" + "é" * 511 + "\n" in failed.stderr, failed.stderr + assert not endpoint.exists() print(f"{args.scenario}: blocked renderer, native deadline, EOF and private endpoint cleanup passed") @@ -486,7 +484,7 @@ def main(): parser = argparse.ArgumentParser() for name in ("agent", "driver", "environment", "provision", "registry", "fixture", "work"): parser.add_argument("--" + name, required=True) - parser.add_argument("--scenario", choices=("session", "mcp-watchdog", "cli-watchdog", "consumer"), default="session") + parser.add_argument("--scenario", choices=("session", "mcp-watchdog", "consumer"), default="session") parser.add_argument("--consumer", help="the automation_consumer executable of the consumer scenario") args = parser.parse_args() if args.scenario == "consumer": diff --git a/test/tools/CompareCoverage.py b/test/tools/CompareCoverage.py deleted file mode 100644 index 3eeff2b6..00000000 --- a/test/tools/CompareCoverage.py +++ /dev/null @@ -1,36 +0,0 @@ -"""Compare per-file line, function and branch hits independently of lcov record ordering.""" -import sys -from pathlib import Path - - -def hits(path): - result = {} - source = None - for line in path.read_text(encoding='utf-8').splitlines(): - kind, _, value = line.partition(':') - if kind == 'SF': - source = value - elif kind == 'DA': - number, count, *_ = value.split(',') - key = source, kind, number - result[key] = result.get(key, 0) + int(count) - elif kind == 'FNDA': - count, name = value.split(',', 1) - key = source, kind, name - result[key] = result.get(key, 0) + int(count) - elif kind == 'BRDA': - number, block, branch, count = value.split(',') - key = source, kind, number, block, branch - previous = result.get(key, '-') - result[key] = '-' if previous == count == '-' else int(0 if previous == '-' else previous) + int(0 if count == '-' else count) - if not result: - raise ValueError('Coverage contains no counters: ' + str(path)) - return result - - -if __name__ == '__main__': - left, right = map(Path, sys.argv[1:]) - first, second = hits(left), hits(right) - if first != second: - raise SystemExit('JSON backends changed coverage counters') - print(f'Identical coverage: {len(first)} line/function/branch counters') diff --git a/test/tools/FlakeReport.py b/test/tools/FlakeReport.py new file mode 100644 index 00000000..85e51319 --- /dev/null +++ b/test/tools/FlakeReport.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Counts the CTest cases that failed in the recent runs of a workflow, per platform job. + +Read-only: it lists runs and reads the logs of their failed jobs through the GitHub CLI (`gh`), which must be +authenticated. A case that fails on one platform of a run whose other platforms pass is the usual sign of an +intermittent failure; one that fails everywhere on a branch is more likely a regression of that branch. Every attempt +of a run is read: a job that failed and passed once run again is exactly an intermittent failure. + + python3 test/tools/FlakeReport.py --limit 60 +""" +import argparse +import collections +import json +import re +import subprocess +import sys +import time + +# "644/687 Test #615: DeveloperBrowserIntegration-jasmine .....***Failed 18.97 sec", after the log's own prefix. +# A repeated case (`--repeat until-fail:5`) has no "644/687" before its first attempts. +FAILED_CASE = re.compile(r"(?:\d+/\d+ )?Test +#\d+: (?P.+?) \.*\*\*\*(?PFailed|Timeout|Exception[^ ]*|Not Run)") + + +def failed_cases(log): + """The (case, kind) pairs of a CTest log; cases that did not run because a dependency failed are left out.""" + found = [] + for line in log.splitlines(): + match = FAILED_CASE.search(line) + if match and match["kind"] != "Not Run": + found.append((match["name"].strip(), match["kind"])) + return found + + +def gh(*arguments): + # GitHub answers a read with a 502 now and then: three tries, ten seconds apart. + for attempt in range(3): + result = subprocess.run(["gh", *arguments], capture_output=True, text=True, encoding="utf-8", errors="replace") + if result.returncode == 0 or "HTTP 50" not in result.stderr: + break + if attempt < 2: + time.sleep(10) + if result.returncode != 0: + raise RuntimeError(f"gh {' '.join(arguments)}: {result.stderr.strip()}") + return result.stdout + + +def attempts_to_read(run): + """The attempts of a run that can hold a failed job: all the earlier ones, and the last one when it failed.""" + last = run.get("attempt") or 1 + return [attempt for attempt in range(1, last + 1) if attempt < last or run["conclusion"] == "failure"] + + +def failed_jobs(run, attempt): + path = f"repos/{{owner}}/{{repo}}/actions/runs/{run['databaseId']}/attempts/{attempt}/jobs?per_page=100" + return [job for job in json.loads(gh("api", path))["jobs"] if job["conclusion"] == "failure"] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--workflow", default="BuildAndTest.yml") + parser.add_argument("--limit", type=int, default=60, help="how many of the latest runs to read") + parser.add_argument("--branch", help="only the runs of this branch") + arguments = parser.parse_args() + + listing = ["run", "list", "--workflow", arguments.workflow, "--limit", str(arguments.limit), + "--json", "databaseId,conclusion,headBranch,event,attempt"] + if arguments.branch: + listing += ["--branch", arguments.branch] + runs = json.loads(gh(*listing)) + completed = [run for run in runs if run["conclusion"] in ("success", "failure")] + cases = collections.defaultdict(list) + other = collections.Counter() + rerun = 0 + for run in completed: + last = run.get("attempt") or 1 + rerun += last > 1 and run["conclusion"] == "success" + for attempt in attempts_to_read(run): + where = f"{run['headBranch']}, run {run['databaseId']}" + (f", attempt {attempt} of {last}" if last > 1 else "") + for job in failed_jobs(run, attempt): + found = failed_cases(gh("run", "view", "--job", str(job["id"]), "--attempt", str(attempt), "--log")) + if not found: + steps = ", ".join(step["name"] for step in job.get("steps", []) if step["conclusion"] == "failure") + other[f"{job['name']}: {steps}"] += 1 + for name, kind in found: + cases[name].append(f"{job['name']} {kind} ({where})") + + failures = sum(1 for run in completed if run["conclusion"] == "failure") + print(f"{len(completed)} completed runs of {arguments.workflow}, {failures} failed, {rerun} passed once run again") + for name, occurrences in sorted(cases.items(), key=lambda item: (-len(item[1]), item[0])): + print(f"\n{len(occurrences):3d} {name}") + for occurrence in occurrences: + print(f" {occurrence}") + if other: + print("\nFailed jobs without a failed CTest case:") + for description, count in other.most_common(): + print(f"{count:3d} {description}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/test/tools/MeasureCommand.py b/test/tools/MeasureCommand.py deleted file mode 100644 index 84e65795..00000000 --- a/test/tools/MeasureCommand.py +++ /dev/null @@ -1,126 +0,0 @@ -"""Sample a command's process family, retaining its exit status and a JSON resource report (stdlib only).""" -import argparse -import json -import os -from pathlib import Path -import subprocess -import sys -import time - - -def ps_seconds(text): - """Parse ps's [[dd-]hh:]mm:ss[.ss] cumulative CPU time.""" - days, _, clock = text.rpartition('-') - seconds = 0.0 - for part in clock.split(':'): - seconds = seconds * 60 + float(part) - return seconds + float(days or 0) * 86400 - - -def snapshot(root=None): - """pid -> (parent, resident bytes, cumulative CPU seconds). Sampling can miss short-lived children.""" - result = {} - if sys.platform.startswith('linux'): - ticks = os.sysconf('SC_CLK_TCK') - page = os.sysconf('SC_PAGE_SIZE') - for directory in Path('/proc').glob('[0-9]*'): - try: - stat = (directory / 'stat').read_text().rsplit(')', 1)[1].split() - result[int(directory.name)] = (int(stat[1]), int(stat[21]) * page, - (int(stat[11]) + int(stat[12])) / ticks) - except (OSError, ValueError, IndexError): - pass - elif sys.platform == 'darwin': - output = subprocess.check_output(['ps', '-axo', 'pid=,ppid=,rss=,time='], text=True) - for line in output.splitlines(): - pid, parent, rss, cpu = line.split() - seconds = ps_seconds(cpu) - result[int(pid)] = (int(parent), int(rss) * 1024, seconds) - elif sys.platform == 'win32': - import ctypes as c - from ctypes import wintypes as w - class Entry(c.Structure): - _fields_ = [('size', w.DWORD), ('usage', w.DWORD), ('pid', w.DWORD), ('heap', c.c_size_t), - ('module', w.DWORD), ('threads', w.DWORD), ('parent', w.DWORD), - ('priority', w.LONG), ('flags', w.DWORD), ('name', w.WCHAR * 260)] - class Memory(c.Structure): - _fields_ = [('size', w.DWORD), ('faults', w.DWORD)] + [(name, c.c_size_t) for name in - ('peakWorking', 'working', 'peakPaged', 'paged', 'peakNonpaged', 'nonpaged', 'pagefile', 'peakPagefile')] - kernel = c.WinDLL('kernel32', use_last_error=True) - kernel.CreateToolhelp32Snapshot.restype = w.HANDLE - kernel.OpenProcess.restype = w.HANDLE - kernel.CloseHandle.argtypes = [w.HANDLE] - kernel.Process32FirstW.argtypes = [w.HANDLE, c.POINTER(Entry)] - kernel.Process32NextW.argtypes = [w.HANDLE, c.POINTER(Entry)] - kernel.GetProcessTimes.argtypes = [w.HANDLE] + [c.POINTER(w.FILETIME)] * 4 - psapi = c.WinDLL('psapi') - psapi.GetProcessMemoryInfo.argtypes = [w.HANDLE, c.POINTER(Memory), w.DWORD] - handle = kernel.CreateToolhelp32Snapshot(2, 0) - entry = Entry(size=c.sizeof(Entry)) - parents = {} - more = kernel.Process32FirstW(handle, c.byref(entry)) - while more: - parents[entry.pid] = entry.parent - more = kernel.Process32NextW(handle, c.byref(entry)) - # Opening every process on a loaded runner can outlast a short command: only query the root's descendants. - wanted = set(parents) - if root is not None: - wanted = {root} - while True: - children = {pid for pid, parent in parents.items() if parent in wanted} - if children <= wanted: - break - wanted |= children - for pid in wanted & set(parents): - process = kernel.OpenProcess(0x1000 | 0x10, False, pid) - if process: - memory = Memory(size=c.sizeof(Memory)) - times = [w.FILETIME() for _ in range(4)] - if psapi.GetProcessMemoryInfo(process, c.byref(memory), memory.size) and kernel.GetProcessTimes(process, *map(c.byref, times)): - cpu = sum((item.dwHighDateTime << 32) + item.dwLowDateTime for item in times[2:]) / 10_000_000 - result[pid] = (parents[pid], memory.working, cpu) - kernel.CloseHandle(process) - kernel.CloseHandle(handle) - else: - raise RuntimeError('Unsupported resource sampler platform: ' + sys.platform) - return result - - -def measure(command, output, interval=0.25): - started = time.monotonic() - process = subprocess.Popen(command) - observed = {} - peak_memory = peak_count = 0 - while process.poll() is None: - processes = snapshot(process.pid) - family = {process.pid} - while True: - children = {pid for pid, (parent, _, _) in processes.items() if parent in family} - if children <= family: - break - family.update(children) - active = {pid: processes[pid] for pid in family if pid in processes} - peak_memory = max(peak_memory, sum(item[1] for item in active.values())) - peak_count = max(peak_count, len(active)) - for pid, (_, _, cpu) in active.items(): - observed[pid] = max(cpu, observed.get(pid, 0)) - time.sleep(interval) - result = {'command': command, 'platform': sys.platform, 'exit_code': process.returncode, - 'wall_seconds': time.monotonic() - started, 'sample_interval_seconds': interval, - 'sampled_peak_family_rss_bytes': peak_memory, 'sampled_peak_processes': peak_count, - 'sampled_processes_seen': len(observed), 'sampled_cpu_seconds': sum(observed.values()), - 'limitation': 'Sampled bounds: short-lived children may be missed; shared pages count in each process RSS.'} - output.parent.mkdir(parents=True, exist_ok=True) - output.write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8') - return process.returncode - - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--output', type=Path, required=True) - parser.add_argument('command', nargs=argparse.REMAINDER) - args = parser.parse_args() - command = args.command[1:] if args.command[:1] == ['--'] else args.command - if not command: - parser.error('a command is required') - raise SystemExit(measure(command, args.output)) diff --git a/test/tools/ProfileTests.py b/test/tools/ProfileTests.py deleted file mode 100644 index 51d25841..00000000 --- a/test/tools/ProfileTests.py +++ /dev/null @@ -1,133 +0,0 @@ -"""Combine CTest's JSON dependency/lock graph and JUnit timings without summing parallel wall times.""" -import argparse -import json -from pathlib import Path -import statistics -import re -import xml.etree.ElementTree as ET - - -def analyze(graph, report, workers): - tests = {test['name']: {p['name']: p['value'] for p in test.get('properties', [])} - for test in graph['tests']} - xml = ET.parse(report).getroot() - times = {case.attrib['name']: float(case.attrib.get('time', 0)) for case in xml.iter('testcase')} - setters = {} - for name, properties in tests.items(): - for fixture in properties.get('FIXTURES_SETUP', []): - setters.setdefault(fixture, []).append(name) - edges = {name: set(properties.get('DEPENDS', [])) for name, properties in tests.items()} - locks = {} - for name, properties in tests.items(): - for fixture in properties.get('FIXTURES_REQUIRED', []): - edges[name].update(setters.get(fixture, [])) - for lock in properties.get('RESOURCE_LOCK', []): - locks.setdefault(lock, []).append(name) - # A fixture cleanup waits for every setup and consumer, even when there are no explicit DEPENDS edges. - for name, properties in tests.items(): - for fixture in properties.get('FIXTURES_CLEANUP', []): - edges[name].update(setters.get(fixture, [])) - edges[name].update(consumer for consumer, props in tests.items() - if fixture in props.get('FIXTURES_REQUIRED', [])) - costs = {} - visiting = set() - def cost(name): - if name in visiting: - raise ValueError('Cyclic CTest dependency: ' + name) - if name not in costs: - visiting.add(name) - costs[name] = times.get(name, 0) + max((cost(parent) for parent in edges.get(name, [])), default=0) - visiting.remove(name) - return costs[name] - critical = max((cost(name) for name in times), default=0) - serial = sum(times.get(name, 0) for name, props in tests.items() if props.get('RUN_SERIAL')) - lock_cost = max((sum(times.get(name, 0) for name in names) for names in locks.values()), default=0) - # Lower bounds only: lock scheduling and fixture order can make the actual critical path longer. - return {'wall_seconds': float(xml.attrib.get('time', 0)), 'sum_seconds': sum(times.values()), - 'dependency_path_seconds': critical, 'serial_seconds': serial, - 'lower_bound_seconds': max(critical, sum(times.values()) / workers, lock_cost, serial), - 'cases': len(times), 'slowest': sorted(times.items(), key=lambda x: x[1], reverse=True)[:25], - 'edges': edges, 'locks': locks} - - -def compile_profile(path): - records = [] - for line in path.read_text(encoding='utf-8', errors='replace').splitlines(): - if line.startswith('#'): - continue - columns = line.split('\t') - if len(columns) != 5: - continue - start, end, _, output, _ = columns - seconds = (int(end) - int(start)) / 1000 - if seconds < 0: - raise ValueError('Negative Ninja job duration: ' + output) - records.append((seconds, output)) - return sorted(records, reverse=True) - - -def write_report(result, output): - output.parent.mkdir(parents=True, exist_ok=True) - lines = ['CTest profile', '', f"Cases: {result['cases']}"] - for key in ('wall_seconds', 'sum_seconds', 'dependency_path_seconds', 'serial_seconds', 'lower_bound_seconds'): - lines.append(f'{key}: {result[key]:.3f}') - lines += ['', 'Slowest cases (seconds):'] + [f'{seconds:9.3f} {name}' for name, seconds in result['slowest']] - output.write_text('\n'.join(lines) + '\n', encoding='utf-8') - dot = ['digraph ctest {'] - for name, dependencies in result['edges'].items(): - dot.append(' ' + json.dumps(name) + ';') - for dependency in dependencies: - dot.append(f' {json.dumps(dependency)} -> {json.dumps(name)};') - for lock, names in result['locks'].items(): - for name in names: - dot.append(f' {json.dumps("lock: " + lock)} -> {json.dumps(name)} [style=dashed];') - output.with_suffix('.dot').write_text('\n'.join(dot + ['}']) + '\n', encoding='utf-8') - - -PHASE = re.compile(r'(?:wf spec: |Developer integration: )?(?:[\d.]+ms )?end (.*?)(?: status=\S+)? durationMs=([\d.]+)') - - -def phase_durations(transcripts): - """(duration ms, 'pass N: name') for every `