diff --git a/.gitattributes b/.gitattributes index 805521b1..42ea0949 100644 --- a/.gitattributes +++ b/.gitattributes @@ -167,7 +167,6 @@ include/webfront/system/*Data.hpp text eol=lf # Browser-powered developer bootstrap sources and generated payloads. js/developer/environment/* text eol=lf -js/developer/vendor/package-lock.json text eol=lf # Starter archives and every hashed distribution input must be identical on Windows. js/developer/tools/starters/pi/* text eol=lf diff --git a/.github/actions/remove-node/action.yml b/.github/actions/remove-node/action.yml index eae461e7..4db5d1c3 100644 --- a/.github/actions/remove-node/action.yml +++ b/.github/actions/remove-node/action.yml @@ -8,13 +8,24 @@ runs: - name: Remove Node.js, npm and npx shell: bash run: | + # A hosted Windows runner has no sudo: its user may delete the files itself. + remove() { if [ "$RUNNER_OS" = Windows ]; then rm -f "$1"; else sudo rm -f "$1"; fi; } for tool in node nodejs npm npx corepack; do while path=$(command -v "$tool"); do - sudo rm -f "$path" || exit 1 + remove "$path" || exit 1 hash -r done done - for tool in node nodejs npm npx; do + # On Windows the command shims (npm.cmd, npx.cmd, corepack.cmd) are separate files next to the executables. + if [ "$RUNNER_OS" = Windows ]; then + for tool in npm npx corepack; do + while path=$(command -v "$tool.cmd"); do + rm -f "$path" || exit 1 + hash -r + done + done + fi + for tool in node nodejs npm npx corepack; do if command -v "$tool"; then echo "::error::$tool is still reachable" exit 1 diff --git a/.github/actions/wf-driver/action.yml b/.github/actions/wf-driver/action.yml index c3a26d06..8908985f 100644 --- a/.github/actions/wf-driver/action.yml +++ b/.github/actions/wf-driver/action.yml @@ -2,7 +2,7 @@ name: Build the wf driver description: >- Builds webfront-wf (WebKitGTK frontend), the non-interactive driver of the WebFront developer environment, from the bootstrap environment pinned by cmake/WebFrontBootstrap.cmake, and installs a `wf` command that runs a wf command on the - project at the root of the workspace. Node.js is neither used nor required (WEBFRONT_REQUIRE_NODE=OFF). + project at the root of the workspace. Node.js is neither used nor required. runs: using: composite steps: @@ -21,7 +21,7 @@ runs: shell: bash run: | cmake -S . -B build-driver -G Ninja -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_EMBED_CEF=OFF -DENABLE_TESTING=ON \ - -DWEBFRONT_REQUIRE_NODE=OFF -DWEBFRONT_EMBED_WEBKITGTK=ON -DWEBFRONT_WEBTEST_FRONTEND=WebKitGTK \ + -DWEBFRONT_EMBED_WEBKITGTK=ON -DWEBFRONT_WEBTEST_FRONTEND=WebKitGTK \ -DCMAKE_CXX_SCAN_FOR_MODULES=OFF cmake --build build-driver --target webfront-wf --parallel 2 - name: Install the wf command diff --git a/.github/workflows/BuildAndTest.yml b/.github/workflows/BuildAndTest.yml index 8ba21550..a94cb6e4 100644 --- a/.github/workflows/BuildAndTest.yml +++ b/.github/workflows/BuildAndTest.yml @@ -56,11 +56,8 @@ jobs: runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v7 - - uses: actions/setup-node@v6 - with: - node-version: 24 - cache: npm - cache-dependency-path: js/developer/vendor/package-lock.json + # 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 with: version: '4.4.4' @@ -74,7 +71,7 @@ jobs: if: runner.os == 'Windows' uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1 # Ubuntu 26.04 ships GCC 16 in its main archive (no flaky toolchain PPA). The image already - # provides CMake, Ninja, Node.js, pkg-config and Xvfb, so install only the missing pieces. + # provides CMake, Ninja, pkg-config and Xvfb, so install only the missing pieces. - name: Install GCC 16, WebKitGTK and coverage tools if: runner.os == 'Linux' run: | @@ -93,11 +90,6 @@ jobs: run: | command -v sccache sccache --version - - name: Prepare offline developer fixtures - run: | - npm ci --prefix js/developer/vendor --ignore-scripts - node js/developer/tools/build.mjs build-developer-environment - node js/developer/tools/fixtures.mjs build-developer-environment # ENABLE_CACHE controls automatic ccache discovery; the explicit sccache launcher stays enabled. - name: Configure run: >- @@ -106,7 +98,6 @@ jobs: -DENABLE_CACHE=OFF -DCMAKE_CXX_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_SCAN_FOR_MODULES=OFF ${{ matrix.options }} - -DWEBFRONT_DEVELOPER_FIXTURES=${{ github.workspace }}/build-developer-environment - name: Build run: cmake --build build --config ${{ matrix.build_type }} --parallel 2 - name: Ensure WebView2 Evergreen runtime @@ -182,9 +173,7 @@ jobs: path: .cache/CPM key: cpm-extended-${{ runner.os }}-${{ hashFiles('CMakeLists.txt', 'cmake/*.cmake') }} restore-keys: cpm-extended-${{ runner.os }}- - - uses: actions/setup-node@v6 - with: - node-version: 24 + - uses: ./.github/actions/remove-node - uses: ./.github/actions/setup-cmake with: version: '4.4.4' @@ -253,9 +242,7 @@ jobs: path: .cache/CPM key: cpm-extended-${{ runner.os }}-${{ hashFiles('CMakeLists.txt', 'cmake/*.cmake') }} restore-keys: cpm-extended-${{ runner.os }}- - - uses: actions/setup-node@v6 - with: - node-version: 24 + - uses: ./.github/actions/remove-node - uses: ./.github/actions/setup-cmake with: @@ -271,13 +258,9 @@ jobs: echo "CC=clang-23" >> "$GITHUB_ENV" echo "CXX=clang++-23" >> "$GITHUB_ENV" - - name: Prepare offline developer environment and starter fixtures - run: | - npm ci --prefix js/developer/vendor --ignore-scripts - node js/developer/tools/build.mjs build-developer-environment - node js/developer/tools/fixtures.mjs build-developer-environment + # 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 -DENABLE_TESTING=ON -DWEBFRONT_DEVELOPER_FIXTURES=${{github.workspace}}/build-developer-environment + run: cmake . -B ${{github.workspace}}/build-cef -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_EMBED_CEF=ON -DWEBFRONT_BUILD_EXAMPLES=OFF -DENABLE_TESTING=ON - 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 6ccec0f7..8186bcb1 100644 --- a/.github/workflows/DeveloperDistribution.yml +++ b/.github/workflows/DeveloperDistribution.yml @@ -10,7 +10,7 @@ on: - 'js/developer/scripts/**' - 'examples/life/ui/**' - 'js/developer/tools/**' - - 'js/developer/vendor/package*.json' + - 'test/developer/**' - 'webfront.project.json' - 'webfront-packages.lock.json' - 'cmake/WebFrontBootstrap.cmake' @@ -27,7 +27,7 @@ on: - 'js/developer/scripts/**' - 'examples/life/ui/**' - 'js/developer/tools/**' - - 'js/developer/vendor/package*.json' + - 'test/developer/**' - 'webfront.project.json' - 'webfront-packages.lock.json' - 'cmake/WebFrontBootstrap.cmake' @@ -54,58 +54,9 @@ env: PUBLISHING: ${{ startsWith(github.ref, 'refs/tags/developer-v') || (github.event_name == 'workflow_dispatch' && inputs.publish) }} jobs: - # The Node.js build and its tests are kept during the transition (#315 to #318): the wf-package job below compares its - # bytes with these, then publishes its own. #318 removes this job with the Node.js tools. - package: - runs-on: ubuntu-24.04 - timeout-minutes: 10 - steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v6 - with: - node-version: 24 - cache: npm - cache-dependency-path: js/developer/vendor/package-lock.json - - name: Install pinned maintenance dependencies - run: npm ci --prefix js/developer/vendor --ignore-scripts - - name: Build and verify the environment and starter packages - run: | - node js/developer/tools/build.mjs build-distribution - node js/developer/tools/build.mjs build-distribution-repeat - cmp build-distribution/environment.tgz build-distribution-repeat/environment.tgz - cmp build-distribution/pi-starter.tgz build-distribution-repeat/pi-starter.tgz - cmp build-distribution/life-starter.tgz build-distribution-repeat/life-starter.tgz - # The pin names the last published version. Sources at that version must rebuild it; sources ahead of it - # leave the header pinning the published archive, which is checked against the deployed file. - pinned=$(sed -n 's/.*version{"\([^"]*\)"}.*/\1/p' include/webfront/system/DeveloperReleaseData.hpp) - building=$(node -p "require('./js/developer/tools/distribution.json').version") - if [ "$pinned" = "$building" ] || [ "$PUBLISHING" = true ]; then - cmp include/webfront/system/DeveloperReleaseData.hpp build-distribution/DeveloperReleaseData.hpp - else - echo "::notice::Sources build $building; DeveloperReleaseData.hpp still pins the published $pinned." - node js/developer/tools/pin-check.mjs - fi - node --test js/developer/tools/check.mjs js/developer/tools/distribution-check.mjs js/developer/tools/manifest-check.mjs js/developer/tools/restore-check.mjs js/developer/tools/scripts-check.mjs js/developer/tools/development-check.mjs js/developer/tools/testing-check.mjs - - name: Check the dedicated release tag - if: startsWith(github.ref, 'refs/tags/developer-v') - env: - RELEASE_TAG: ${{ github.ref_name }} - run: node js/developer/tools/release-check.mjs "$RELEASE_TAG" - - uses: actions/upload-artifact@v4 - with: - name: developer-distribution-node - if-no-files-found: error - path: | - build-distribution/environment.tgz - build-distribution/pi-starter.tgz - build-distribution/life-starter.tgz - build-distribution/provision.json - build-distribution/DeveloperReleaseData.hpp - # The environment builds itself: the pinned bootstrap environment runs js/developer/scripts on these sources, with the - # locked build dependencies restored from npm. No Node.js, npm or npx is available to any step. + # locked build dependencies restored from npm. No JavaScript runtime or package manager is available to any step. wf-package: - needs: package runs-on: ubuntu-26.04 # The whole job takes about two minutes; a longer one is a stalled step (a package mirror, say): fail early. timeout-minutes: 15 @@ -139,17 +90,9 @@ jobs: echo "::notice::Sources build $building; DeveloperReleaseData.hpp still pins the published $pinned." wf run pin fi - # Transition: the Node.js build and the wf build must be the same bytes. #318 removes this comparison with the - # Node.js build. - - uses: actions/download-artifact@v4 - with: - name: developer-distribution-node - path: build-distribution-node - - name: Compare with the Node.js build - run: | - for name in environment.tgz pi-starter.tgz life-starter.tgz provision.json DeveloperReleaseData.hpp; do - cmp "build-distribution/$name" "build-distribution-node/$name" - done + # The specs of the environment run by the project's own wf test, under the locked jasmine-core. + - name: Run the specs of the environment + run: wf test --timeout 300 - uses: actions/upload-artifact@v4 with: name: developer-distribution diff --git a/.gitignore b/.gitignore index 848e2955..c8d424fb 100644 --- a/.gitignore +++ b/.gitignore @@ -53,4 +53,3 @@ Thumbs.db .webfront/ # Maintenance-only npm tooling -/js/developer/vendor/node_modules/ diff --git a/AGENTS.md b/AGENTS.md index 87a47c3b..4451db53 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,7 +18,7 @@ The README introduces WebFront through the Game of Life walkthrough, demonstrati - `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). -- `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 vendoring tools. The repository is itself a `wf` project (`webfront.project.json` and its lock at the root): the environment builds itself, and `docs/NODE_TOOLS_MIGRATION.md` lists the remaining Node.js tools and their destination. Production C++ remains header-only in `include/webfront/`. +- `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 vendoring tools. The repository is itself a `wf` project (`webfront.project.json` and its lock at the root): the environment builds itself, and its pure JavaScript specs (`test/developer/`) run with `wf test`. `docs/NODE_TOOLS_MIGRATION.md` records where each former Node.js tool went. Production C++ remains header-only in `include/webfront/`. - `js/developer/tools/starters/pi/`, `test/fixtures/`, `test/web/fixtures/`: retained package and 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. - `cmake/`: build modules (frontends, CEF, CPM, compiler options); `.github/`: workflows, `.github/CONTRIBUTING.md`. @@ -51,18 +51,17 @@ ctest --test-dir build --output-on-failure --parallel 4 # Run one Catch2 scenario directly ./build/test/unit/tests "Scenario: JsFunction" -# Linux real-browser integration test (the Jasmine suite needs the offline registry of the fixtures) -node js/developer/tools/build.mjs build-developer-environment -node js/developer/tools/fixtures.mjs build-developer-environment +# Linux real-browser integration test: configure downloads and verifies the pinned bootstrap environment and the packages +# of the local npm registry; the tests build the rest with wf cmake -S . -B build-cef -DCMAKE_BUILD_TYPE=Release \ - -DWEBFRONT_EMBED_CEF=ON -DENABLE_TESTING=ON -DWEBFRONT_DEVELOPER_FIXTURES=$PWD/build-developer-environment + -DWEBFRONT_EMBED_CEF=ON -DENABLE_TESTING=ON cmake --build build-cef --target webtest webfront-wf --parallel ctest --test-dir build-cef -L web-integration --output-on-failure --parallel 4 ``` -Build the developer environment with wf (no Node.js; the driver comes from any build with `ENABLE_TESTING=ON`, here with -`-DWEBFRONT_REQUIRE_NODE=OFF`), as `js/developer/tools/PUBLISHING.md` describes: +Build the developer environment with wf (the driver comes from any build with `ENABLE_TESTING=ON`), as +`js/developer/tools/PUBLISHING.md` describes: ```bash wf() { build/test/web/webfront-wf --project "$PWD" -- "$@"; } @@ -71,16 +70,17 @@ wf restore && wf run build build-distribution Important CMake options: -Tests and the `webfront-embedded-assets` regeneration target require Node.js for all -assets, including uncompressed ones. Normal C++ builds consume versioned headers -and do not require Node.js. +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 +`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. - `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. - `ENABLE_TESTING=ON` (default `OFF`): build Catch2 and Jasmine test targets. CI and contributor commands must pass it explicitly. -- `WEBFRONT_REQUIRE_NODE=ON` (default): `ENABLE_TESTING=ON` requires Node.js for the maintenance tests that still use it (until #318). `OFF` configures without it and does not register those tests; only the job that proves a build without Node.js sets it. - `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. - `ENABLE_COVERAGE=ON`: add GCC/Clang coverage instrumentation to the C++ tests. @@ -108,7 +108,7 @@ Exception: a purely C++ change that reuses an existing encoding, introduces no n - Keep production implementation header-only under `include/`; `examples/` contains the two 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. -- 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. Without `WEBFRONT_DEVELOPER_FIXTURES` the Jasmine case is not registered. +- 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 3c560ba0..7121eb19 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10,7 +10,6 @@ endif() option(BUILD_SHARED_LIBS "Enable compilation of shared libraries" OFF) option(ENABLE_TESTING "Enable Test Builds" OFF) option(WEBFRONT_BUILD_EXAMPLES "Build the example applications" ${WEBFRONT_IS_TOP_LEVEL}) -option(WEBFRONT_REQUIRE_NODE "Require Node.js to register the maintenance tests that still use it (removed by #318)" ON) option(ENABLE_COVERAGE "Enable test coverage instrumentation" OFF) option(ENABLE_FUZZING "Enable Fuzzing Builds" OFF) option(WEBFRONT_USE_MDDLOG "Use the compiled mddlog diagnostic adapter" OFF) diff --git a/README.md b/README.md index 09c4f657..de1d1d62 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ [![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: no Node.js, npm or separate JavaScript development environment to install. +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. ## From C++ to a reactive UI @@ -104,14 +104,14 @@ Enable **one** engine for your platform: | macOS 13.3+ | `-DWEBFRONT_EMBED_WKWEBVIEW=ON` | System Cocoa / WebKit | | Linux | `-DWEBFRONT_EMBED_WEBKITGTK=ON` | WebKitGTK 6.0; [installation](docs/WEBKITGTK.md) | -For local review of this unpublished branch, first [build the local archive](docs/DEVELOPER_ENVIRONMENT.md#environment-distribution-and-offline-tests-maintainers). That preparation requires Node/npm for the maintainer only. Then, on macOS, from the repository root: +For local review of this unpublished branch, first [build the local archive](docs/DEVELOPER_ENVIRONMENT.md#environment-distribution-and-offline-tests-maintainers). That preparation is a maintainer task done with `wf` itself. Then, on macOS, from the repository root: ```bash cmake -S . -B build-native -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_EMBED_WKWEBVIEW=ON cmake --build build-native --target WebFrontLifeDeveloper --parallel 2 mkdir -p life-project/.webfront/developer/preview/provision cp build-developer-environment/*.tgz life-project/.webfront/developer/preview/provision/ -integrity=$(node -p "require('./build-developer-environment/provision.json').integrity") +integrity=$(sed -n 's/^ "integrity": "\(.*\)",$/\1/p' build-developer-environment/provision.json) ./build-native/examples/WebFrontLifeDeveloper "$PWD/life-project" \ /webfront/developer/preview/provision/environment.tgz "$integrity" ``` @@ -138,7 +138,7 @@ wf install react@19.3.1 react-dom@19.3.1 wf preview ui/main.tsx ``` -`wf create life` writes the editable [TSX and CSS starter](examples/life/ui), without overwriting an existing project. `wf install` fetches the browser packages and their dependencies, verifies their integrity and records exact versions in `webfront-packages.lock.json`. It does not run npm installation scripts. `wf preview` compiles TSX with WebAssembly and opens the interface inside the application. +`wf create life` writes the editable [TSX and CSS starter](examples/life/ui), without overwriting an existing project. `wf install` fetches the browser packages and their dependencies, verifies their integrity and records exact versions in `webfront-packages.lock.json`. It does not run the installation scripts of packages. `wf preview` compiles TSX with WebAssembly and opens the interface inside the application. Edit `life-project/ui/main.tsx` and `style.css` with your usual editor, then run `wf preview` again. React renders the field and controls; each generation awaits the C++ callback: @@ -208,7 +208,7 @@ cmake --build build --parallel 2 ctest --test-dir build --output-on-failure --parallel 4 ``` -Tests and the `webfront-embedded-assets` regeneration target require Node.js, including assets without gzip. Normal C++ builds use versioned headers and do not require Node.js. Browser tests require an enabled engine; Linux CEF tests use Xvfb. See [AGENTS.md](AGENTS.md) for contributor commands and [developer environment testing](docs/DEVELOPER_ENVIRONMENT.md#environment-distribution-and-offline-tests-maintainers). +Configuring with tests enabled downloads, and verifies against their SHA-512, the pinned bootstrap environment and the packages of the test registry; the embedded assets are generated and checked by CMake alone (the `webfront-embedded-assets` target regenerates them). Normal C++ builds use versioned headers. Browser tests require an enabled engine; Linux CEF tests use Xvfb. See [AGENTS.md](AGENTS.md) for contributor commands and [developer environment testing](docs/DEVELOPER_ENVIRONMENT.md#environment-distribution-and-offline-tests-maintainers). CTest runs up to four tasks at a time; browser ports remain locked and embedded builds run serially. See [test timings and parallelism](docs/TEST_PERFORMANCE.md) for measurements and constraints. @@ -220,7 +220,7 @@ CI runs one combined C++ / native-browser job per desktop platform on each code - WebFront owns an HTTP/WebSocket server on a background thread. Callbacks run there; avoid blocking it. 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). - 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. -- Development project access is explicit and intended for trusted local code. Downloaded tools run with the application's bridge authority. Package scripts, native Node add-ons and Node APIs are unsupported. Previews transform TypeScript without type checking; `wf check` type-checks with the compiler the project locks. +- Development project access is explicit and intended for trusted local code. Downloaded tools run with the application's bridge authority. Package installation scripts, native add-ons and the APIs of server-side JavaScript runtimes are unsupported. Previews transform TypeScript without type checking; `wf check` type-checks with the compiler the project locks. - Packaging, accessibility and native-engine deployment still need application-specific work. General DOM abstractions remain future work. See [project status](docs/PROJECT_STATUS.md) for known limitations. [Developer environment reference](docs/DEVELOPER_ENVIRONMENT.md) · [UI components](docs/UI_COMPONENTS.md) · [architecture decisions](docs/adr/README.md) · [contributing](.github/CONTRIBUTING.md) diff --git a/cmake/WebFrontBootstrap.cmake b/cmake/WebFrontBootstrap.cmake index 37211659..04498eaa 100644 --- a/cmake/WebFrontBootstrap.cmake +++ b/cmake/WebFrontBootstrap.cmake @@ -2,11 +2,12 @@ # # It is distinct from include/webfront/system/DeveloperReleaseData.hpp (the environment applications start from) and is # updated by an explicit pull request, once a published environment can build and test itself without interaction. -# 0.6.0 is the first published environment that runs a wf command without interaction (runNonInteractive). The driver tests also +# 0.6.0 is the first published environment that runs a wf command without interaction (runNonInteractive); 0.6.1 also returns the +# output of a script. The driver tests also # run the environment built from the current sources (the "environment under test"), which may be ahead of this pin. -set(WEBFRONT_BOOTSTRAP_VERSION "0.6.0") -set(WEBFRONT_BOOTSTRAP_URL "https://ambroise-leclerc.github.io/WebFront/developer/0.6.0/environment.tgz") -set(WEBFRONT_BOOTSTRAP_INTEGRITY "sha512-xidz8ggQFo/UUTttIii+3FRJmGpQPoHhbmk9Fv/wxRA4EKEhD5WeiAcstsuY8H/wXc/jo/bljIYkzyyyrJ1oEg==") +set(WEBFRONT_BOOTSTRAP_VERSION "0.6.1") +set(WEBFRONT_BOOTSTRAP_URL "https://ambroise-leclerc.github.io/WebFront/developer/0.6.1/environment.tgz") +set(WEBFRONT_BOOTSTRAP_INTEGRITY "sha512-wBYPxKJQwj4KqWqbLqxXbfhCUSZgBZh1GCnbAvxgb4oVwsxf0vnfpTGdhW/2tGXagwHT/60SwbL7L21vRCVD8g==") # 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") diff --git a/cmake/WebFrontRegistry.cmake b/cmake/WebFrontRegistry.cmake new file mode 100644 index 00000000..be76d82c --- /dev/null +++ b/cmake/WebFrontRegistry.cmake @@ -0,0 +1,58 @@ +# The real packages of the local npm registry of the tests (test/web/registry-packages.json): downloaded at configure time +# like the other dependencies, verified against their SHA-512 integrity, never committed. A wf script then builds the +# registry's files from them (test/web/registry/), so that no test reaches the public registry and none needs a JavaScript runtime. +include(WebFrontBootstrap) + +# A directory holding the listed archives (-.tgz, @scope/name as scope-name-.tgz) replaces the +# downloads on a machine without network access. +set(WEBFRONT_REGISTRY_DIR "" CACHE PATH "Directory with the pinned archives of the test registry, instead of downloading them") + +# Fills with the archives of , each named and verified; sets to the +# directory. A wrong digest or a missing archive stops the configure. +function(webfront_provision_registry output list directory) + file(READ "${list}" content) + string(JSON count LENGTH "${content}" packages) + math(EXPR last "${count} - 1") + file(MAKE_DIRECTORY "${directory}") + foreach(index RANGE 0 ${last}) + string(JSON url GET "${content}" packages ${index} url) + string(JSON integrity GET "${content}" packages ${index} integrity) + webfront_sri_to_sha512("${integrity}" expected) + get_filename_component(name "${url}" NAME) + # Scoped packages share base names with others of the same version: the file name carries the scope. + string(JSON package GET "${content}" packages ${index} name) + if(package MATCHES "^@([^/]+)/") + set(name "${CMAKE_MATCH_1}-${name}") + endif() + set(path "${directory}/${name}") + set(present FALSE) + if(EXISTS "${path}") + file(SHA512 "${path}" actual) + if(actual STREQUAL expected) + 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() + endif() + endif() + file(SHA512 "${path}" actual) + if(NOT actual STREQUAL expected) + file(REMOVE "${path}") + message(FATAL_ERROR "Integrity check failed for ${name}: expected ${integrity}") + endif() + endforeach() + set(${output} "${directory}" PARENT_SCOPE) +endfunction() diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index cc02dcd0..1c99a460 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -4,7 +4,19 @@ ### Added -- The developer environment builds itself (#315, distribution 0.6.1, published as `developer-v0.6.1` and pinned by `DeveloperReleaseData.hpp`; the bootstrap of the tests stays 0.6.0): the +- 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 `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 @@ -17,7 +29,7 @@ - `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.0) and, with `ENABLE_TESTING=ON`, downloads + `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. diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index 1892e6ff..a62d62dc 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -2,7 +2,7 @@ The developer environment downloads its terminal, npm resolver and WebAssembly compiler at runtime. The application's C++ executable initially contains the bridge and a small bootstrap; -it does not embed React, Babel, xterm or esbuild. Node.js and npm are **not required on the +it does not embed React, Babel, xterm or esbuild. No separate JavaScript runtime is **required on the application developer's machine**. A C++ compiler, CMake and the selected native webview remain necessary. TypeScript/JSX is transformed in the browser without type checking; `wf check` type-checks the project with the TypeScript compiler it locks. @@ -51,7 +51,7 @@ The default configuration is generated in `include/webfront/system/DeveloperRele `https://ambroise-leclerc.github.io/WebFront/developer/0.6.1/environment.tgz`. This version (`wf build`, `wf dev`, `wf test` and the non-interactive entry, on top of the 0.5.0 manifest, `wf restore`, `wf run`, `wf check` and the complete terminal) is published and archived as `developer-v0.6.1`. Published 0.6.0, 0.5.0, 0.4.1 and 0.4.0 stay immutable; 0.4.0 targets the former include layout. The configuration pins one version and its SHA-512 rather than resolving a mutable `latest` channel. An explicit `DeveloperBootstrapOptions{.environment = url, .integrity = trustedHash}` still selects a different -HTTPS/CORS repository or a same-origin test fixture. Users install neither npm nor Node.js. +HTTPS/CORS repository or a same-origin test fixture. Users install no JavaScript tooling. The environment archive contains pinned Life and PI starter descriptors. `wf create life` downloads and verifies that separate archive, creates a new `ui` directory and prints the install/preview/embed @@ -81,7 +81,7 @@ with a plain console application. ```sh mkdir -p life-project/.webfront/developer/preview/provision cp build-developer-environment/*.tgz life-project/.webfront/developer/preview/provision/ -integrity=$(node -p "require('./build-developer-environment/provision.json').integrity") +integrity=$(sed -n 's/^ "integrity": "\(.*\)",$/\1/p' build-developer-environment/provision.json) ./build-native/examples/WebFrontLifeDeveloper "$PWD/life-project" \ /webfront/developer/preview/provision/environment.tgz "$integrity" ``` @@ -171,7 +171,7 @@ the operations of the `context` API of scripts; they are not a sandbox. 0.5.0), the manifest takes its roots as dependencies (`^version`, or the range they were installed with). - `wf install [@range]` resolves, downloads and verifies into the cache, then publishes the manifest (the requested range, or `^version` when none was given) and the lock in a single transaction. -- `wf install` without argument installs exactly the locked graph (like `npm ci`) when the lock agrees +- `wf install` without argument installs exactly the locked graph when the lock agrees with the manifest, resolves the manifest and creates the lock when there is none, and fails when they disagree. `wf install --update` resolves the manifest again. - `wf preview [entry]` and `wf embed ` use `entries` and `providers`; an explicit path still works. @@ -243,7 +243,7 @@ and tarballs from the application (`fs::NativeDebugFS` or an application provide ## Scripts (`wf run`, `wf exec`) -WebFront scripts replace npm scripts and `npx` for producing a project's resources, without Node.js: +WebFront scripts produce a project's resources, in the browser: ```json { @@ -441,7 +441,7 @@ The last successful preview stays available. Browser disconnection also stops th `wf test [--timeout ] [pattern]` runs the project's Jasmine specs in the browser. The project chooses the Jasmine: `wf install jasmine-core` resolves it from the registry like any package, and the lock pins its version -and integrity. Nothing else is needed: no Node.js, no npm and no public network once the package is in the cache. +and integrity. Nothing else is needed, and no public network once the package is in the cache. ```json { @@ -520,7 +520,7 @@ webfront-wf --project [--environment --integrity --target webfront-embedded-assets`. Without +that flag, it writes only to the output directory. `site.mjs` stages a build into the GitHub Pages site and `pin.mjs` +checks the pinned header against the published archive. The headers of the core's embedded assets are rendered by `js/core/EmbedAsset.cmake`, in pure CMake (see below). The archives have the package identifiers `@webfront/developer-environment`, `@webfront/life-starter` and `@webfront/pi-starter`. They are distributed as static GitHub Pages downloads; no npm publication or scope ownership is required. -During the transition from Node.js (#318), the Node.js tools (`js/developer/tools/build.mjs` and the others) build the -same bytes, which the CTest case `SelfBuildMatchesFixtures` and the `wf-package` job require; they also still provision -the offline test fixtures (the local registry and test pages): +The `SelfBuild*` CTest cases run the scripts on a copy of the sources, with the dependencies installed from the local +registry: the build, a repeat build (same bytes), the checked-in bootstrap bundles and checksums rebuilt by wf alone (and the +core headers rendered from them by CMake), the staging of the site (a second staging repeats the same bytes, a changed +published file is refused) and the permissions of the manifest. `DeveloperSpecs` runs the pure JavaScript specs of +`test/developer/` with `wf test` on that copy; the CEF-off CTest cases check the generated headers (`*AssetFresh`, +`EmbeddedAssetGenerator`, and the Catch2 scenario on the embedded assets of the core), the checksums of the bundle inputs (`BundleInputsFresh`) and the names the +terminal and `webfront::Commands` reserve (`CommandNamesAgree`) with CMake and Catch2 alone, and `NoNodeDependency` audits +every file of the project. The maintainer procedure is in `js/developer/tools/PUBLISHING.md`. -```sh -npm ci --prefix js/developer/vendor --ignore-scripts -node js/developer/tools/build.mjs build-developer-environment -node js/developer/tools/fixtures.mjs build-developer-environment -``` - -The `SelfBuild*` CTest cases (with `WEBFRONT_DEVELOPER_FIXTURES`) run the scripts on a copy of the sources, with the -dependencies installed from the local registry: the build, a repeat build (same bytes), the checked-in bootstrap bundles, -checksums and core headers rebuilt by wf alone, the headers of the core regenerated from their sources, the staging of the site (a second staging repeats the same bytes, a changed -published file is refused) and the permissions of the manifest. `WEBFRONT_REQUIRE_NODE=OFF` configures a test build without -Node.js: the checks that still use it (asset freshness, `DeveloperJavaScript`, `EmbeddedAssetGenerator`) are then not registered. -The maintainer procedure is in `js/developer/tools/PUBLISHING.md`. - -To try the local archive without an HTTPS server, after building the packages above: +To try the local archive without an HTTPS server, after building the packages above (with `wf run build build-developer-environment`): ```sh mkdir -p life-project/.webfront/developer/preview/provision cp build-developer-environment/*.tgz life-project/.webfront/developer/preview/provision/ -integrity=$(node -p "require('./build-developer-environment/provision.json').integrity") +integrity=$(sed -n 's/^ "integrity": "\(.*\)",$/\1/p' build-developer-environment/provision.json) ./build-native/examples/WebFrontLifeDeveloper "$PWD/life-project" \ /webfront/developer/preview/provision/environment.tgz "$integrity" ``` The preview command later replaces that directory, but the verified archive is already cached independently for subsequent launches. These are maintainer provisioning commands; the application's -terminal still installs and builds browser dependencies without a local Node/npm installation. +terminal installs and builds browser dependencies without any local JavaScript tooling. -Fixture provisioning writes the tests' local npm registry (`js/developer/tools/registry-fixture.mjs`): -packuments and tarballs packed reproducibly from the pinned `jasmine-core`, React, React DOM and scheduler of the -maintainer's npm installation, plus synthetic packages for the edge cases (a newer version under a locked range, -an archive that no longer matches its integrity). The test application serves it from its own origin and imposes -it through the `registry` option. The CEF-off `DeveloperJavaScript` case generates the synthetic part in memory to -test `wf restore`. No CTest case downloads from the public registry. Generating the fixture and the packages' -logic use only browser APIs; reading `node_modules` and writing files (`registry-fixture-node.mjs`) are the -Node-only part, so that `wf` can take the fixture over (#318). +**The tests' local npm registry** is built by `wf run test-registry` (`test/web/registry/`): the packuments and tarballs as +plain files, from the real packages that CMake downloaded at configure time (`test/web/registry-packages.json` lists each by +name, version and SHA-512 integrity; a wrong digest stops the configure, `-DWEBFRONT_REGISTRY_DIR=` replaces the +downloads on a machine without network access) kept byte for byte, and from synthetic packages for the edge cases (a newer +version under a locked range, an archive that no longer matches its integrity, typed and untyped packages). The test +application serves it from its own origin and imposes it through the `registry` option. The CEF-off `DeveloperSpecs` case +generates the synthetic part in memory to test `wf restore`. No CTest case downloads from the public registry. Nothing is +committed: the archives live in the build directory. ```sh cmake -S . -B build-native -DCMAKE_BUILD_TYPE=Release \ -DWEBFRONT_EMBED_CEF=OFF -DWEBFRONT_EMBED_WKWEBVIEW=ON \ - -DWEBFRONT_WEBTEST_FRONTEND=WKWebView -DENABLE_TESTING=ON \ - -DWEBFRONT_DEVELOPER_FIXTURES="$PWD/build-developer-environment" + -DWEBFRONT_WEBTEST_FRONTEND=WKWebView -DENABLE_TESTING=ON cmake --build build-native --parallel ctest --test-dir build-native -R 'Developer|LifeEmbedded' --output-on-failure ``` -The GitHub CI prepares these fixtures for both WKWebView and CEF jobs. The initial 0.2.0 Life version passed +The CTest fixtures prepare the registry and the environment under test in every browser job (WKWebView, WebKitGTK, WebView2, CEF). The initial 0.2.0 Life version passed WKWebView and all 14 Linux CEF/Xvfb cases with both GCC and Clang in [run 39421265580](https://github.com/ambroise-leclerc/WebFront/actions/runs/39421265580). The packed 0.3.0 version passes WKWebView and all 14 GCC CEF/Xvfb cases in diff --git a/docs/EMBEDDED_ASSETS.md b/docs/EMBEDDED_ASSETS.md index ccbb6b13..9213b771 100644 --- a/docs/EMBEDDED_ASSETS.md +++ b/docs/EMBEDDED_ASSETS.md @@ -6,7 +6,7 @@ pinned release data (`Developer*Data.hpp`). Each is generated from a readable so (including the default favicon, `js/core/favicon.ico`) into a header under `include/webfront/system/`. Libraries such as React, Babel and Jasmine are not embedded: they are npm packages that `wf install` locks and downloads (see [DEVELOPER_ENVIRONMENT.md](DEVELOPER_ENVIRONMENT.md)), and the tests obtain them from a local registry. -Normal C++ consumer builds use the checked-in headers and need neither Node.js nor npm. +Normal C++ consumer builds use the checked-in headers and need nothing but the compiler: the headers are generated, and checked, in pure CMake. ## Migration @@ -28,30 +28,35 @@ and is 188 KB now. ## Maintenance -Use Node.js 22.18 or newer (Node 24 in CI) and CMake 3.31 or newer. These tools are needed for -regeneration and `ENABLE_TESTING=ON` asset checks, not for normal library consumers. From the -repository root: +CMake 3.31 or newer is the only tool: regeneration and the asset checks of `ENABLE_TESTING=ON` are CMake scripts, and +normal library consumers need neither. From the repository root: ```sh # Regenerate the headers from their sources, then verify them offline. cmake --build build --target webfront-embedded-assets -ctest --test-dir build -R 'Asset.*Fresh|EmbeddedAssetGenerator' --output-on-failure --parallel 4 +ctest --test-dir build -R 'Asset.*Fresh|EmbeddedAssetGenerator|BundleInputs|embedded assets of the core' --output-on-failure --parallel 4 ``` -`js/core/EmbedTextAsset.cmake` delegates rendering and exact byte comparison to -`js/developer/vendor/embed.mjs`. It assembles bounded lines of five 64-bit words and joins them -once, avoiding the growing-string CMake loop. Generation and checking use the same renderer, without -intermediate files. `EmbeddedAssetGenerator` covers empty and binary inputs, word boundaries, padding, -line wrapping and a nonzero status for stale or missing files; a per-asset `*AssetFresh` test attributes -each stale header. `.gitattributes` keeps sources and headers at LF. +`js/core/EmbedAsset.cmake` renders a header (identity encoded, five 64-bit words per line, big-endian, the last word padded +with zeros, `dataSize` excluding the padding) and compares its exact bytes with a checked-in one (`-DCHECK`, so that a header +with CRLF line ends is stale). It assembles bounded lines and joins them once, avoiding a growing-string CMake loop: the six +core assets, about 35 KB, take a fraction of a second. Generation and checking share one renderer, without intermediate files. +`EmbeddedAssetGenerator` (`test/cmake/CheckEmbedAsset.cmake`) covers the exact format, empty and binary inputs, word +boundaries, padding, a path with spaces, a checkout reached through a symbolic link and a nonzero status for stale or missing +files; a per-asset `*AssetFresh` test attributes each stale header, and a Catch2 scenario decodes every header with the C++ +data it declares and compares it with the source file. `.gitattributes` keeps sources and headers at LF. The choice of CMake +over a script run by `wf` is recorded in [ADR-016](adr/ADR-016-bootstrap-comme-socle.md): the headers must be checkable by a +build that has no browser. -The favicon is binary and small, so `js/core/EmbedBinaryAsset.cmake` renders it (identity encoded, same header format) -with CMake alone: no Node.js and no compressor. `FaviconAssetFresh` compares the checked-in `FaviconData.hpp` with it. +The bundles of the environment (`js/core/bootstrap/bootstrap.bundle.mjs`, `js/developer/environment/packages.bundle.mjs`) are +built by `wf run build --refresh-bootstrap`. `js/developer/environment/bundles.json` records the SHA-256 of +each of their inputs (`js/developer/tools/bundle-inputs.json`) and of the bundles themselves; `BundleInputsFresh` fails +when a source changed without rebuilding them, and `BundleInputsRejectsChange` proves that it does. After a refresh, run the +`webfront-embedded-assets` target for the headers that embed the bootstrap bundle. -The renderer can pack gzip-compressed bytes (`encoding = "gzip"`, `dataSize` excluding the trailing word -padding) with the vendored fflate `gzipSync` (level 9, mem 8, mtime 0, no filename, fixed OS byte), so -the streams are identical across platforms. The current assets are identity encoded because they are -small. Catch2 covers the serving of gzip assets with a neutral fixture module: clients accepting gzip +Applications that embed gzip-compressed resources use `wf embed`, which compresses in the environment with the locked +`fflate` (level 9, mem 8, mtime 0, no filename, fixed OS byte), so the streams are identical across platforms. Catch2 covers the serving of +gzip assets with a neutral fixture module: clients accepting gzip receive the stored representation, other clients accepting identity receive decoded bytes with their decoded `Content-Length`. See [HTTP asset encoding](HTTP_ASSETS.md) for negotiation, decoding limits and failure responses. diff --git a/docs/NODE_TOOLS_MIGRATION.md b/docs/NODE_TOOLS_MIGRATION.md index 824ad6e4..5bfd4263 100644 --- a/docs/NODE_TOOLS_MIGRATION.md +++ b/docs/NODE_TOOLS_MIGRATION.md @@ -1,53 +1,41 @@ -# Node.js tools: inventory and destination - -Transition note of the epic #303 (issues #315 and #318). At the close of the epic no WebFront path depends on Node.js, -npm or npx; until then the Node.js tools of `js/developer/` remain, and this list gives each one's destination. #318 -deletes a tool only after the destination below is in place and proven; nothing is kept as a fallback. - -The environment builds itself since #315: `webfront.project.json` and `webfront-packages.lock.json` make the repository a -`wf` project, and `js/developer/scripts/` holds the scripts that the pinned bootstrap environment runs with -`webfront-wf` (see `js/developer/tools/PUBLISHING.md`). Their outputs are byte for byte those of the Node.js build, which -the CTest cases `SelfBuild*` and the `wf-package` job of `DeveloperDistribution.yml` require during the transition. - -| Entry | Role | Destination | State | -| --- | --- | --- | --- | -| `tools/build.mjs` | environment, starters, header, bootstrap bundles | `scripts/build.mjs` (`wf run build`) | migrated (#315); the Node.js file is deleted by #318 | -| `tools/archive.mjs` | reproducible ustar | unchanged: no Node.js API, imported by the wf scripts | kept | -| `tools/distribution.mjs` (new) | versions, URLs, pinned header, published files | shared by the wf scripts and the Node.js tools | kept | -| `tools/asset-header.mjs` (new) | header of an embedded asset | shared by `scripts/build.mjs` and `vendor/embed.mjs` | kept | -| `tools/bundle-inputs.json` (new) | inputs of the bundle checksums | read by both builds | kept | -| `tools/site.mjs` | staging of the Pages site | `scripts/site.mjs` (`wf run site`) | migrated (#315); the Node.js file is deleted by #318 | -| `tools/pin-check.mjs` | pinned header against the published archive | `scripts/pin.mjs` (`wf run pin`, `permissions.fetch`) | migrated (#315); deleted by #318 | -| `tools/pages.mjs` | Pages source check and build request | `tools/pages.sh` (`gh`) | migrated (#315); deleted by #318 | -| `tools/archive-release.mjs` | prerelease archive | `tools/archive-release.sh` (`gh`, `jq`) | migrated (#315); deleted by #318 | -| `tools/release-check.mjs` | dedicated tag check | step of `wf-package` (shell) | migrated (#315); deleted by #318 | -| `tools/fixtures.mjs`, `registry-fixture-node.mjs` | offline registry and test pages from `npm ci` | tarballs pinned by name, version and SHA-512, downloaded by CMake at configure, and a wf script for the synthetic packages (#319) | #318, #319 | -| `tools/registry-fixture.mjs` | pure part of the registry fixture | wf script of #319 | #318, #319 | -| `tools/check.mjs`, `manifest-check.mjs`, `restore-check.mjs`, `scripts-check.mjs`, `development-check.mjs`, `testing-check.mjs` | pure JavaScript tests (`node --test`) | Jasmine specs run by `wf test`, in the `web-integration` suite | #318 | -| `tools/distribution-check.mjs` | starters, staging of the site | starters: Jasmine specs (#318); staging: `SelfBuildSite*` (#315) | partly migrated | -| `tools/memory-bridge.mjs` | in-memory bridge of the tests | moves with the specs | #318 | -| `vendor/embed.mjs`, `js/core/EmbedTextAsset.cmake` | core header generator | `scripts/embed-core.mjs` (`wf run embed-core`) produces the same bytes (`SelfBuildCoreHeaders`); #318 chooses between it and a pure CMake generator, in ADR-016 | available (#315); switch and deletion by #318 | -| `vendor/embed.test.mjs` | generator tests | CMake tests for processes and files, the browser for gzip | #318 | -| `vendor/package.json`, `package-lock.json` | `npm ci` of the maintainers | `webfront.project.json` and its lock; the fixture packages by #319 | #318, #319 | -| README and `DEVELOPER_ENVIRONMENT.md`: `node -p` extracting the integrity, `npm ci`; `CheckNewcomerDocs.cmake` pins that text | local review of an unpublished archive | the commands read `provision.json` without Node.js | #317, #318 | -| `BuildAndTest.yml`: `setup-node`, `npm ci`, `node build.mjs`, `node fixtures.mjs` | fixtures of the desktop and CEF jobs | the environment built by wf, the registry of #319 | #318 | -| `DeveloperDistribution.yml`: `package` job | Node.js build and tests | removed with the comparison | #318 | -| `WebFrontAssets.cmake`: `DeveloperJavaScript`, `EmbeddedAssetGenerator`, asset freshness | Node.js tests | as above; `WEBFRONT_REQUIRE_NODE=OFF` does not register them | #318 | - -`starters/`, `distribution.json`, `PUBLISHING.md` and `RELEASE_NOTES.md` are data and documents, kept. - -## What needs no Node.js already - -- Configuring and building `webfront-wf` (`-DWEBFRONT_REQUIRE_NODE=OFF`), as the `wf-package` and `publish` jobs do after - removing `node`, `nodejs`, `npm`, `npx` and `corepack` from the runner. -- Restoring the locked build dependencies (`wf restore`), building the environment, the starters and the pinned header, the - bootstrap bundles and the core headers they embed, twice, with identical bytes. -- Staging a version in the Pages site (immutable versions), checking the pin against the published archive, checking the - Pages source, requesting its build and archiving a prerelease. - -## What still needs it - -Tests of the pure JavaScript, the asset freshness checks and the generator of the core headers, the fixtures of the -browser tests (the registry and the test pages) and the desktop and CEF jobs that prepare them. The closing proof of #315, -from an empty cache and with the pinned SHA-512 of the first environment that builds itself, is the publication of that -environment: the Node.js tools are deleted only after it. +# Node.js tools: where each one went + +Record of the transition of the epic #303 (issues #315 and #318). It is a migration note, not a guide: no WebFront path +depends on Node.js, npm or npx any more, and nothing was kept as a fallback. The `NoNodeDependency` CTest case audits every +tracked file; this note and the files of the guard are among its listed exceptions (`test/cmake/NodeGuardExceptions.cmake`). + +## Tools + +| Former entry | Role | Destination | +| --- | --- | --- | +| `js/developer/tools/build.mjs` | environment, starters, header, bootstrap bundles | `js/developer/scripts/build.mjs` (`wf run build`), since #315; the Node.js file was deleted by #318 | +| `tools/site.mjs` | staging of the Pages site | `scripts/site.mjs` (`wf run site`); its test, once on a temporary directory, now runs on an in-memory project in `distribution-specs.mjs` | +| `tools/pin-check.mjs` | pinned header against the published archive | `scripts/pin.mjs` (`wf run pin`) | +| `tools/pages.mjs`, `tools/archive-release.mjs`, `tools/release-check.mjs` | Pages source check, prerelease archive, tag check | `tools/pages.sh`, `tools/archive-release.sh` (`gh`, `jq`) and a step of `wf-package` | +| `tools/fixtures.mjs`, `tools/registry-fixture-node.mjs` | offline registry and test pages from `npm ci` | `cmake/WebFrontRegistry.cmake` downloads the pinned archives at configure; `wf run test-registry` builds the registry; the CTest fixture `DeveloperFixtures` assembles the rest | +| `tools/registry-fixture.mjs` | pure part of the registry fixture | `test/web/registry/fixture.mjs` (only browser APIs) | +| `tools/memory-bridge.mjs` | in-memory bridge of the tests | `test/developer/memory-bridge.mjs` | +| `tools/asset-header.mjs`, `vendor/embed.mjs`, `js/core/EmbedTextAsset.cmake`, `scripts/embed-core.mjs` | rendering of the core headers | `js/core/EmbedAsset.cmake`, pure CMake (ADR-016, v1.3) | +| `vendor/package.json`, `package-lock.json` | `npm ci` of the maintainers | `webfront.project.json` and its lock; the registry packages are listed in `test/web/registry-packages.json` | +| `tools/archive.mjs`, `tools/distribution.mjs`, `tools/bundle-inputs.json` | ustar writer, rules of the distribution, inputs of the bundle checksums | unchanged: they use no host API and are read by the wf scripts | +| `BuildAndTest.yml`: Node.js setup, package installation, `build.mjs` and `fixtures.mjs` steps | fixtures of the desktop and CEF jobs | none: configure downloads, the tests build; every job removes the JavaScript runtimes from the runner first | +| `DeveloperDistribution.yml`: `package` job and its comparison | Node.js build | deleted; `wf-package` also runs `wf test` | +| README and guides: extraction of the integrity with a Node.js one-liner | review of a local archive | `sed` on `provision.json` (`CheckNewcomerDocs.cmake` pins the text) | + +## Tests + +86 tests of the Node.js runner, none lost: + +| Former file (tests) | Destination | +| --- | --- | +| `check.mjs` (14) | `test/developer/specs/environment-specs.mjs` (12 specs); the checksums of the bundle inputs became `BundleInputsFresh` and `BundleInputsRejectsChange` (CMake), the command names reserved by the terminal and by `webfront::Commands` became `CommandNamesAgree` (CMake) | +| `manifest-check.mjs` (16) | `manifest-specs.mjs` | +| `restore-check.mjs` (12) | `restore-specs.mjs` | +| `scripts-check.mjs` (21) | `scripts-specs.mjs`; the Worker module is evaluated afresh for each spec from the project's own source | +| `development-check.mjs` (7) | `development-specs.mjs`; the module is imported directly instead of bundled by a native compiler | +| `testing-check.mjs` (11) | `testing-specs.mjs`, compiling with the locked esbuild-wasm | +| `distribution-check.mjs` (5) | `distribution-specs.mjs` | +| `embed.test.mjs` (5) | `EmbeddedAssetGenerator` (`CheckEmbedAsset.cmake`: format, padding, exit status, path with spaces, symbolic link), the Catch2 scenario on the embedded assets of the core, the per-asset `*AssetFresh` cases. The gzip cases went with the gzip rendering of the core, which had no user left | + +The specs run with `wf test` on the repository (`webfront.project.json`, `test.specs`); the CTest case `DeveloperSpecs` runs them +on a copy of the sources, and the `wf-package` job on the checkout with its lock. diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index 7bc534bb..d67f75f3 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -19,42 +19,61 @@ fetched React from npm, ran the PI and Life previews and generated both provider The Jasmine bridge suite is `test/web/suite/`, a WebFront project (`webfront.project.json`: `jasmine-core`, `react`, `react-dom`, `test.specs`). `webtest` is the `webfront-wf` driver (`test/driver/WfDriver.hpp`) plus the C++ callbacks the specs call: CTest prepares a copy of the project (`WebSuiteProject`), `wf install` resolves its dependencies from the -local registry of `WEBFRONT_DEVELOPER_FIXTURES` (`WebSuiteInstall`), and the `Web*Integration` case runs `wf test` in the -pinned 0.6.0 bootstrap environment under CEF/Xvfb, WebKitGTK, WebView2 or WKWebView. `SpecRunner.html`, the `TestFS` +local registry built by `wf run test-registry` (`WebSuiteInstall`), and the `Web*Integration` case runs `wf test` in the +pinned 0.6.1 bootstrap environment under CEF/Xvfb, WebKitGTK, WebView2 or WKWebView. `SpecRunner.html`, the `TestFS` composition and the use of the embedded Jasmine, React and Babel providers by the browser test are gone; the Signal Studio page is a JSX module built by esbuild-wasm with the locked React and rendered in the runner frame by the specs. The specs now run in the hidden frame of `wf test`, so the URL assertions of the former top-level page (path, query, fragment) are covered by the `path-encoding` lifecycle case, and `webtest` also checks that C++ observed every call the specs make. The Jasmine -case is registered only with `WEBFRONT_DEVELOPER_FIXTURES`; the registry fixtures are still produced by the Node tools -(#318, #319). The embedded Jasmine, React and Babel providers, their headers (~2.1 MB), `third_party/{babel,react,jasmine}`, `vendor/update.mjs` and `vendor/check.mjs`, their freshness tests and `EmbeddedGzipContents` were removed by #312 (migration: `wf install` and `wf embed`, see `docs/EMBEDDED_ASSETS.md`); the HTTP gzip and identity negotiation tests use a neutral fixture module. +case needs no prepared fixtures: configure downloads the registry's packages (#318). The embedded Jasmine, React and Babel providers, their headers (~2.1 MB), `third_party/{babel,react,jasmine}`, `vendor/update.mjs` and `vendor/check.mjs`, their freshness tests and `EmbeddedGzipContents` were removed by #312 (migration: `wf install` and `wf embed`, see `docs/EMBEDDED_ASSETS.md`); the HTTP gzip and identity negotiation tests use a neutral fixture module. ## Self-hosted developer environment (#315, epic #303) The repository is a `wf` project (`webfront.project.json`, `webfront-packages.lock.json` at the root, the only files added -to the closed root list). The pinned 0.6.0 bootstrap environment runs `js/developer/scripts/build.mjs` with `webfront-wf`: +to the closed root list). The pinned 0.6.1 bootstrap environment runs `js/developer/scripts/build.mjs` with `webfront-wf`: the locked esbuild-wasm bundles the environment in the script's Worker, and `environment.tgz`, the starters, -`provision.json`, the pinned header and (with `--refresh-bootstrap`) the bootstrap bundles, their checksums and the core -headers come out byte for byte as from the Node.js build, twice in a row. `site.mjs` stages the Pages site and refuses to -change a published version; `pin.mjs` checks the pin against the published archive; `embed-core.mjs` regenerates the six core headers (the same bytes as the -CMake target `webfront-embedded-assets`); `pages.sh` and `archive-release.sh` do the host operations with `gh`. Verified locally (WebKitGTK, GCC 15) with `node`, `nodejs`, `npm`, `npx` and `corepack` -absent from `PATH`: configure and build of the driver with `-DWEBFRONT_REQUIRE_NODE=OFF`, `wf restore` of the lock from the -public registry, two builds with the same bytes as the Node.js build, the refresh, the staging of the site and the pin -check; CTest `SelfBuild*` (15 cases) covers the same offline, and the whole suite passes locally (299 cases, WebKitGTK). The sources build 0.6.1, which fixes `runNonInteractive` -dropping what a command wrote; it is not published, and `DeveloperReleaseData.hpp` pins 0.6.0. - -Not done here, by design: publishing 0.6.1 (a maintainer operation with the `developer-v0.6.1` tag), deleting the Node.js -tools and the comparison job (#318, after the proof from an empty cache with the pinned environment), the registry of real -tarballs downloaded by CMake that lets `wf restore` replace `wf install` in the tests (#319), and the `BuildAndTest.yml` -fixtures, which are still provisioned with Node.js. The inventory is `docs/NODE_TOOLS_MIGRATION.md`. The workflow changes -(`DeveloperDistribution.yml`: `wf-package`, `publish`; the actions `wf-driver` and `remove-node`) run only on -GitHub: they were checked by running their shell steps locally, not by a workflow run. +`provision.json`, the pinned header and (with `--refresh-bootstrap`) the bootstrap bundles and their checksums come out +the same twice in a row, and byte for byte as the 0.6.1 that is published (`sha512-wBYPxKJQ...`). `site.mjs` stages the Pages +site and refuses to change a published version; `pin.mjs` checks the pin against the published archive; `pages.sh` and +`archive-release.sh` do the host operations with `gh`. The `DeveloperDistribution.yml` jobs `wf-package` and `publish`, and +the actions `wf-driver` and `remove-node`, run only on GitHub. + +## Tests, regeneration and CI without Node.js (#318, epic #303) + +No path of WebFront depends on a JavaScript runtime or package manager any more: configuring, building, testing, regenerating the embedded assets, +building the environment, publishing it, and the CI. + +- **Provisioning.** With `ENABLE_TESTING=ON`, configure downloads the pinned bootstrap environment and the real packages of the + tests' npm registry (`test/web/registry-packages.json`: ten archives, verified against their SHA-512; a wrong digest stops + the configure; `-DWEBFRONT_BOOTSTRAP_DIR` and `-DWEBFRONT_REGISTRY_DIR` replace the downloads offline). `WEBFRONT_DEVELOPER_FIXTURES` + is gone: the CTest chain builds the registry (`TestRegistry`: `wf run test-registry`), installs the build dependencies + from it, builds the environment from the current sources (`SelfBuild*`) and assembles the fixtures of the browser tests + (`DeveloperFixtures`). The environment it builds is byte for byte the published 0.6.1. +- **Tests.** The pure JavaScript tests of the former runner became Jasmine specs in `test/developer/specs/`, run by the + repository's own `wf test` (`DeveloperSpecs`, and the `wf-package` job on the real checkout and lock); 86 tests became 84 + specs because two moved to CMake: the checksums of the bundle inputs (`BundleInputsFresh`, `BundleInputsRejectsChange`) and + the command names reserved by the terminal and by `webfront::Commands` (`CommandNamesAgree`). The tests of the asset + generator became `EmbeddedAssetGenerator` (CMake, exit status and format), a Catch2 scenario that decodes every core + header and compares it with its source, and the per-asset `*AssetFresh` cases. The mapping is in `docs/NODE_TOOLS_MIGRATION.md`. +- **Regeneration.** The headers of the core are rendered, and checked, by `js/core/EmbedAsset.cmake`, in pure CMake (ADR-016): + they must be checkable by a build that has no browser. `wf run embed-core` is gone. +- **Guard.** `NoNodeDependency` audits every tracked file for imports and APIs of Node, commands of its tools and package + managers, their configuration, their requirement in current documentation and the "like node.js" positioning; the exceptions are listed, + with their reason, in `test/cmake/NodeGuardExceptions.cmake`. `NoNodeDependencyRejectsInjections` proves it fails on an + import of a Node module, a package installation command in a workflow, `engines.node` in a manifest, a Node script nobody calls, an old command in a + guide and the other injections, and passes on a registry URL and on a test that checks the rejection of a Node import. +- **CI.** The Node.js setup steps, the package installation, the npm cache and the `package` job are gone; the desktop, sanitizer and CEF jobs and + `wf-package` run `remove-node` (also on Windows and macOS) before anything else. + +Verified locally (WebKitGTK, GCC 15) with every JavaScript runtime and package manager absent from `PATH`; see the pull +request for the figures. The workflow changes were checked by running their shell steps locally, not by a workflow run before +the pull request. ## CI test duration (#298, 2026-10-21) -The maintenance asset renderer generates and compares headers in Node, preserving -all versioned bytes and pinned gzip parameters. Local Babel freshness drops from -14.75 s to 0.30 s. Tests and asset regeneration require Node; ordinary C++ builds do -not. CI uses up to four CTest workers, retains timing reports, locks browser ports +The maintenance asset renderer assembles bounded lines and joins them once, preserving +all versioned bytes. Local Babel freshness dropped from +14.75 s to 0.30 s (the renderer is CMake since #318; Babel is gone). CI uses up to four CTest workers, retains timing reports, locks browser ports and serializes nested embedded builds against every running test in the same tree. Frontend fixtures reuse the parent generator, and the consumer inherits the actual test target's compiler cache launcher at generation time. @@ -137,7 +156,7 @@ Status snapshot: 2026-07-19. Optional mddlog integration note: 2026-10-02. Newco - `NativeApp` can bootstrap a pinned developer environment with a small embedded loader. The downloadable terminal, npm library resolver, esbuild/WASM Worker and gzip/header generator do - not require Node/npm on application developers' machines. + need no JavaScript tooling on application developers' machines. - The Game of Life demo (`WebFrontLifeDeveloper`, `wf create life`) uses a compact C++23 bitset simulation and a spatial React/canvas interface with translucent panels, interactive patterns, playback, single step and tempo. The original PI demo remains available. Both cover @@ -154,7 +173,7 @@ Status snapshot: 2026-07-19. Optional mddlog integration note: 2026-10-02. Newco - Versioned environment and Life/PI starter archives have a GitHub Pages publication workflow, immutable-version checks, dedicated prerelease archiving and a checked-in pinned bootstrap configuration. `wf create life` and `wf create pi` create fresh editable projects without - overwriting existing files. Maintainer preparation requires Node/npm; consumers do not. + overwriting existing files. Maintainer preparation uses `wf` itself (#318); consumers install nothing. Version 0.2.0 was served at `https://ambroise-leclerc.github.io/WebFront/developer/0.2.0/`, with the same archives retained in the `developer-v0.2.0` prerelease; 0.1.0 and later versions are preserved. The live WKWebView smoke test downloaded both starters and the environment from Pages, fetched @@ -176,10 +195,10 @@ Status snapshot: 2026-07-19. Optional mddlog integration note: 2026-10-02. Newco - React and React DOM 19.3.1, Babel standalone 8.0.7 and Jasmine 7.0.2 replace the older embedded versions; xterm 6.0.0 and Fit 0.11.0 remain current. React now uses a local ESM bundle and the automatic JSX transform; Jasmine uses its new single boot script. Editable examples still need - no npm install, CDN or JavaScript build step. + no package installation, CDN or JavaScript build step. - Dependency JavaScript/CSS uses deterministic gzip generated with vendored fflate 0.8.3; sources, licenses, pinned maintenance tooling and offline freshness/decode checks are checked in. - Node.js is required for tests/asset maintenance only. Identity fallback from #274 also applies to the updated gzip payloads. + Identity fallback from #274 also applies to the updated gzip payloads. - The CEF-off Release build passes all 239 CTest cases after integrating #274. All 20 WKWebView browser/lifecycle cases pass locally, including the actual React page, C++ callback recovery and xterm/Fit resizing. Linux CEF/Xvfb and Windows WebView2 coverage runs through their existing CI jobs. diff --git a/docs/TEST_PERFORMANCE.md b/docs/TEST_PERFORMANCE.md index 92c13a0a..7e4c13e2 100644 --- a/docs/TEST_PERFORMANCE.md +++ b/docs/TEST_PERFORMANCE.md @@ -29,7 +29,7 @@ their totals should not be compared as a compiler benchmark. ## Changes -- The asset renderer assembles bounded lines in Node and joins them once. The +- The asset renderer assembles bounded lines (in CMake since #318) and joins them once. The former CMake loop repeatedly processed a growing string for every 64-bit word. All checked-in headers, compression settings and full byte comparisons remain the same. No intermediate gzip file is needed. The independent zlib decode @@ -86,8 +86,8 @@ the profiles. Sanitizer test processes retain their existing runtime settings. ## Local measurements -Measured on the same Linux workstation with GCC 16.1, CMake 4.2.3, Node 22.22.1 -and Release builds. These are local measurements, not predicted hosted-runner +Measured on the same Linux workstation with GCC 16.1, CMake 4.2.3 and Release builds. (The Node.js +renderer measured here has since been replaced by the CMake one.) These are local measurements, not predicted hosted-runner results. CEF compilation was also active during these measurements. | Scope | Before | After | diff --git a/docs/UI_COMPONENTS.md b/docs/UI_COMPONENTS.md index 31361f11..cd26703a 100644 --- a/docs/UI_COMPONENTS.md +++ b/docs/UI_COMPONENTS.md @@ -13,7 +13,7 @@ They are replaced by the developer environment, downloaded and verified by | `webfront::Terminal` page and its line editor | The environment's terminal: streaming, Ctrl+C for every command, per-browser sessions, multi-row redraw, CJK and emoji widths, history, completion | | `terminal::Shell` and `Terminal::command` | `webfront::Commands` (``): coroutine commands, discovered by the environment | | `Terminal::extension` browser commands | `wf run` scripts and `wf exec` package entries | -| `ToolManager`, `wf install/list/remove/open` of tools | `wf install` and `wf restore` of npm packages, locked by `webfront-packages.lock.json` | +| `ToolManager`, `wf install/list/remove/open` of tools | `wf install` and `wf restore` of browser packages, locked by `webfront-packages.lock.json` | ## Migrating `terminal::Shell` commands diff --git a/docs/WKWEBVIEW.md b/docs/WKWEBVIEW.md index af0efe3e..c51a9de2 100644 --- a/docs/WKWEBVIEW.md +++ b/docs/WKWEBVIEW.md @@ -11,7 +11,7 @@ cmake -S . -B build-wkwebview -DCMAKE_BUILD_TYPE=Release \ cmake --build build-wkwebview --target WebFrontLifeDeveloper --parallel 2 mkdir -p life-project/.webfront/developer/preview/provision cp build-developer-environment/*.tgz life-project/.webfront/developer/preview/provision/ -integrity=$(node -p "require('./build-developer-environment/provision.json').integrity") +integrity=$(sed -n 's/^ "integrity": "\(.*\)",$/\1/p' build-developer-environment/provision.json) ./build-wkwebview/examples/WebFrontLifeDeveloper "$PWD/life-project" \ /webfront/developer/preview/provision/environment.tgz "$integrity" ``` diff --git a/docs/adr/ADR-009-modules-et-assets-reproductibles.md b/docs/adr/ADR-009-modules-et-assets-reproductibles.md index 3eeb16da..aba14546 100644 --- a/docs/adr/ADR-009-modules-et-assets-reproductibles.md +++ b/docs/adr/ADR-009-modules-et-assets-reproductibles.md @@ -13,11 +13,12 @@ | 1.6 | 2026-10-19 | Acceptée | Ambroise Leclerc | Négociation gzip/identity, décodage validé et budget de sortie. | [4be7358](https://github.com/ambroise-leclerc/WebFront/commit/4be73581ee6b9f569cb6e50aced73e27562aa38c) | | 2.0 | 2026-10-19 | Acceptée | Ambroise Leclerc | Génération gzip reproductible avec compresseur intégré ; distributions actualisées et runtime React ESM local. | [b031ab5](https://github.com/ambroise-leclerc/WebFront/commit/b031ab58ea9cc32290d701094c1333bab455e67f) | | 2.1 | 2026-10-22 | Acceptée | Ambroise Leclerc | Assets embarqués limités à la liste normative de l'ADR-016 ; trajectoire de retrait de BabelFS, ReactFS, JasmineFS et des sources vendorisées. | [404fed2](https://github.com/ambroise-leclerc/WebFront/commit/404fed2c2145d4faba8efee035e10522ff87a91f) | +| 2.2 | 2026-10-24 | Acceptée | Ambroise Leclerc | Les retraits annoncés sont réalisés (#312, #313, #318) : les en-têtes du cœur sont rendus et vérifiés par CMake seul (`js/core/EmbedAsset.cmake`), sans compression ni Node.js ; la compression gzip reproductible est celle de `wf embed`. | — | ## État et chronologie **Acceptée.** Décision initiale : **2023-03-16** (version 1.0). -Dernière révision : **2026-10-22** (version 2.1). +Dernière révision : **2026-10-24** (version 2.2). Le présent texte expose la décision en vigueur ; le tableau retrace ses états antérieurs. ## Contexte @@ -62,16 +63,17 @@ un échec de décodage ou dépassement du budget donne 500. Les assets embarqués dans `include/webfront/` se limitent à la liste normative de [ADR-016](ADR-016-bootstrap-comme-socle.md). `BabelFS`, `ReactFS`, `JasmineFS`, leurs en-têtes -générés et `third_party/` sont voués au retrait (#312, #319) ; les bibliothèques deviennent des -paquets npm verrouillés fournis par l'environnement. Jusqu'à ce retrait, les règles de génération -ci-dessous restent en vigueur et ne doivent pas être étendues à de nouvelles bibliothèques. +générés ont été retirés (#312) et `third_party/` l'est par #319 ; les bibliothèques sont des +paquets npm verrouillés fournis par l'environnement. Les en-têtes de la liste normative sont rendus par +`js/core/EmbedAsset.cmake` (#318), sans compression : les règles de génération gzip ci-dessous décrivent l'historique de la +décision et ne s'appliquent plus qu'aux providers produits par `wf embed`. ## Prescriptions d’implémentation et de génération de code - Que les sources soient modifiées avant régénération ; préserver les fins de ligne LF et les licences d’origine. -- Rafraîchir xterm uniquement avec `cmake/UpdateXterm.cmake` ; suivre `EMBEDDED_ASSETS.md` pour - les versions, lockfile et autres distributions. +- Régénérer les en-têtes du cœur avec la cible `webfront-embedded-assets` ; suivre `EMBEDDED_ASSETS.md` + pour les bundles de l'environnement et leurs sommes de contrôle. - Que le lancement du programme C++ n’exige ni npm ni connexion réseau. - Pour un nouvel asset, tester route, MIME, encodage, taille, lectures partielles et fraîcheur. - Pour modifier la négociation, tester gzip, identity, exclusions et flux corrompus ; ne pas diff --git a/docs/adr/ADR-016-bootstrap-comme-socle.md b/docs/adr/ADR-016-bootstrap-comme-socle.md index 84c8ece9..ff273f11 100644 --- a/docs/adr/ADR-016-bootstrap-comme-socle.md +++ b/docs/adr/ADR-016-bootstrap-comme-socle.md @@ -6,7 +6,8 @@ | --- | --- | --- | --- | --- | --- | | 1.0 | 2026-10-22 | Acceptée | Ambroise Leclerc | Décision initiale : environnement bootstrap comme architecture de base, liste normative du cœur, scripts autorisés, indépendance vis-à-vis de Node.js. | [404fed2](https://github.com/ambroise-leclerc/WebFront/commit/404fed2c2145d4faba8efee035e10522ff87a91f) | | 1.1 | 2026-10-23 | Acceptée | Ambroise Leclerc | Garde-fou `MinimalCoreAssets` (#314) : la liste est vérifiée par CTest, budget de 150 Kio d'octets décodés ; le favicon devient `FaviconData`, généré par CMake pur depuis `js/core/favicon.ico`. | [c0ee031](https://github.com/ambroise-leclerc/WebFront/commit/c0ee03131d3104721f8a24224533e753a5f6ad13) | -| 1.2 | 2026-10-23 | Acceptée | Ambroise Leclerc | Auto-hébergement (#315) : le dépôt est un projet `wf` dont les scripts construisent l'environnement, le site et la vérification du pin avec l'environnement d'amorçage épinglé ; octets identiques à la construction Node.js, preuve de reconstruction du bundle bootstrap. | — | +| 1.2 | 2026-10-23 | Acceptée | Ambroise Leclerc | Auto-hébergement (#315) : le dépôt est un projet `wf` dont les scripts construisent l'environnement, le site et la vérification du pin avec l'environnement d'amorçage épinglé ; octets identiques à la construction de l'époque, preuve de reconstruction du bundle bootstrap. | — | +| 1.3 | 2026-10-24 | Acceptée | Ambroise Leclerc | Tests, régénération et CI sans Node.js ni npm (#318) : les en-têtes du cœur sont produits et vérifiés par un générateur CMake pur (`js/core/EmbedAsset.cmake`), qui remplace `wf run embed-core` et le générateur Node.js ; les paquets du registre de test sont téléchargés et vérifiés au configure ; les tests JavaScript deviennent des specs Jasmine exécutées par `wf test` ; garde-fou global `NoNodeDependency`. | — | ## Statut et date @@ -33,7 +34,7 @@ et un second système de terminal et d'outils (`Terminal.hpp`, `ToolManager.hpp` ## Décision L'environnement bootstrap devient l'architecture de base : un outil de développement complet -« à la node.js » (manifeste de projet, install, run, test, build, embed) fourni par une archive +(manifeste de projet, install, run, test, build, embed) fourni par une archive téléchargée et vérifiée, tandis que le code source de WebFront redevient minimaliste. ### Liste normative des ressources du cœur @@ -78,11 +79,21 @@ autorisés ont l'autorité du bridge et du projet désigné. Un durcissement ult Aucun usage (utilisateur, contributeur, CI) ne requiert Node.js ou npm : seuls restent un compilateur C++23, CMake et le moteur du frontend choisi. Les en-têtes du cœur sont régénérés et -vérifiés sans Node (#318) : le pilote C++ non interactif exécute les scripts d'assemblage dans le -navigateur à partir d'une version d'amorçage épinglée (#321), puis compare les octets produits aux -en-têtes versionnés. Les paquets de test viennent d'un registre local alimenté par CMake au -configure ; aucun test ne dépend du réseau public ensuite. Aucune source tierce n'est vendorisée -et `third_party/` disparaît (#319) ; les bibliothèques sont des paquets npm verrouillés, jamais +vérifiés sans Node (#318), **par CMake seul** : `js/core/EmbedAsset.cmake` rend l'en-tête de chaque +ressource (six sources de moins de 30 Kio, quelques dixièmes de seconde) et compare ses octets exacts à ceux du fichier +versionné. Le choix d'un générateur CMake pur plutôt que d'un script exécuté par `wf` tient à ce que la fraîcheur des +en-têtes doit être vérifiable par un build qui n'a pas de navigateur (la CI CEF-off, les sanitizers) ; une seule +implémentation du rendu subsiste, la compression gzip n'ayant plus d'usage dans le cœur (elle reste celle de `wf embed`, +dans l'environnement, avec le `fflate` verrouillé). Un test Catch2 décode chaque en-tête avec les données C++ qu'il +déclare et le compare au fichier source ; un test CMake vérifie les sommes de contrôle des entrées des bundles +(`bundles.json`) : une source modifiée sans reconstruction est détectée sans navigateur. La reconstruction effective +sources → bundle est prouvée dans la suite navigateur par `wf run` (`SelfBuildRefreshMatchesSources`), puis bundle → +en-tête par CMake. Le pilote C++ non interactif exécute les scripts d'assemblage et les specs (`wf test`) dans le navigateur +à partir d'une version d'amorçage épinglée (#321). Les paquets de test sont téléchargés par CMake au configure, listés par nom, +version et intégrité SHA-512 (`test/web/registry-packages.json`), puis servis hors ligne par un registre que `wf run +test-registry` construit ; aucun test ne dépend du réseau public ensuite. Un garde-fou global (`NoNodeDependency`) audite +tous les fichiers suivis, ses exceptions étant listées et motivées dans `test/cmake/NodeGuardExceptions.cmake`. Aucune +source tierce n'est vendorisée et `third_party/` disparaît (#319) ; les bibliothèques sont des paquets npm verrouillés, jamais committés. ### Sources vendorisées et artefacts générés @@ -102,12 +113,11 @@ d'amorçage épinglé (`cmake/WebFrontBootstrap.cmake`) par le pilote `webfront- Worker du script : ils lisent les sources du projet et les paquets verrouillés, n'écrivent que sous `permissions.publish` (répertoires `build-*` et sorties versionnées nommées) et n'ont ni shell ni API Node. Ils produisent `environment.tgz`, `environment.json`, `provision.json`, `bootstrap.bundle.mjs` et `DeveloperReleaseData.hpp` **octet pour octet** comme la -construction Node.js, deux constructions successives étant identiques ; les CTest `SelfBuild*` l'exigent à chaque exécution -avec `WEBFRONT_DEVELOPER_FIXTURES` et, tant que Node.js subsiste (#318), le job `wf-package` de `DeveloperDistribution.yml` -compare aussi les deux constructions. La preuve de reconstruction du bundle bootstrap exigée plus haut est +construction qui a précédé (la 0.6.1 publiée), deux constructions successives étant identiques ; les CTest `SelfBuild*` l'exigent +à chaque exécution et le job `wf-package` de `DeveloperDistribution.yml` compare aussi les deux constructions. La preuve de reconstruction du bundle bootstrap exigée plus haut est `SelfBuildRefreshMatchesSources` : `wf run build --refresh-bootstrap` régénère `bootstrap.bundle.mjs`, `packages.bundle.mjs`, -leurs sommes de contrôle et les deux en-têtes `DeveloperIndexHtmlData.hpp` et `DeveloperBootstrapData.hpp`, identiques aux -fichiers versionnés ; `wf run embed-core` régénère les six en-têtes du cœur (`SelfBuildCoreHeaders`). Les opérations d'hôte de la +leurs sommes de contrôle, identiques aux fichiers versionnés, et `EmbedAsset.cmake` en rend les deux en-têtes +`DeveloperIndexHtmlData.hpp` et `DeveloperBootstrapData.hpp`, identiques eux aussi. Les opérations d'hôte de la publication (Pages, prerelease, dépôt `gh-pages`) restent des scripts shell et des étapes de workflow : elles n'entrent pas dans l'API `context`. L'environnement 0.6.1 construit ainsi par la 0.6.0 corrige aussi `runNonInteractive`, qui perdait la sortie d'une commande avant sa fin ; la 0.6.0 reste immuable. @@ -146,6 +156,8 @@ développeur ni outillage. L'outillage de construction n'est jamais embarqué da - Conserver deux systèmes (composants C++ et environnement) : écarté, double maintenance de deux terminaux, deux `wf` et deux modèles d'installation. - Garder Node.js pour la régénération et les tests : écarté, contraire à l'autonomie visée. +- Régénérer les en-têtes du cœur par un script `wf` (`wf run embed-core`, essayé dans #315) : écarté par #318, car il exige un + navigateur pour vérifier la fraîcheur ; un seul rendu, en CMake, sert la génération et la vérification. - Garder les bibliothèques vendorisées pour les tests : écarté, le poids du dépôt et la provenance floue ne se justifient pas face à des paquets verrouillés par intégrité. - **Coût accepté :** le premier lancement du mode développeur nécessite l'accès à la release ou diff --git a/docs/adr/README.md b/docs/adr/README.md index c5db44d5..7cae8032 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -48,14 +48,14 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | [ADR-006](ADR-006-taches-structurees-et-arret.md) | Owning, cancelling and joining every task | Accepted | 2026-10-13 | 2.0 — 2026-10-18 | | [ADR-007](ADR-007-frontends-explicites.md) | Explicit frontend selection and a shared lifecycle contract | Accepted | 2026-05-31 | 1.10 — 2026-10-20 | | [ADR-008](ADR-008-contenu-de-confiance-et-origines.md) | Restricting bridge origins without promising a sandbox | Accepted | 2026-10-18 | 1.0 — 2026-10-18 | -| [ADR-009](ADR-009-modules-et-assets-reproductibles.md) | Serving modules locally and regenerating assets reproducibly | Accepted | 2023-03-16 | 2.1 — 2026-10-22 | +| [ADR-009](ADR-009-modules-et-assets-reproductibles.md) | Serving modules locally and regenerating assets reproducibly | Accepted | 2023-03-16 | 2.2 — 2026-10-24 | | [ADR-010](ADR-010-composants-et-outils-optionnels.md) | Extending WebFront through optional components and development tools | Accepted | 2026-10-14 | 1.7 — 2026-10-23 | | [ADR-011](ADR-011-diagnostics-optionnels.md) | Confining mddlog behind an optional diagnostics façade | Accepted | 2026-10-01 | 1.2 — 2026-10-02 | | [ADR-012](ADR-012-preuves-et-tests.md) | Demonstrating contracts through deterministic tests and browser integration | Accepted | 2020-04-19 | 1.6 — 2026-10-19 | | [ADR-013](ADR-013-bootstrap-developpeur-a-la-demande.md) | Bootstrapping a downloaded developer environment | Proposée | 2026-10-20 | 0.2 — 2026-10-22 | | [ADR-014](ADR-014-construction-javascript-dans-le-browser.md) | Resolving npm dependencies and building inside the browser | Proposée | 2026-10-20 | 0.2 — 2026-10-22 | | [ADR-015](ADR-015-ressources-generees-par-application.md) | Generating application-owned embedded resources | Proposée | 2026-10-20 | 0.2 — 2026-10-22 | -| [ADR-016](ADR-016-bootstrap-comme-socle.md) | The bootstrap environment as WebFront's foundation | Accepted | 2026-10-22 | 1.2 — 2026-10-23 | +| [ADR-016](ADR-016-bootstrap-comme-socle.md) | The bootstrap environment as WebFront's foundation | Accepted | 2026-10-22 | 1.3 — 2026-10-24 | Numbering follows the reading topics; milestones and individual file histories provide the chronology, which does not follow the numerical order. diff --git a/include/webfront/system/DeveloperReleaseData.hpp b/include/webfront/system/DeveloperReleaseData.hpp index 0e487184..d771d135 100644 --- a/include/webfront/system/DeveloperReleaseData.hpp +++ b/include/webfront/system/DeveloperReleaseData.hpp @@ -1,6 +1,6 @@ #pragma once -// Pinned developer distribution. Regenerate with js/developer/tools/build.mjs --refresh-bootstrap. +// Pinned developer distribution. Regenerate with wf run build --refresh-bootstrap. #include namespace webfront::developer::release { diff --git a/js/core/EmbedBinaryAsset.cmake b/js/core/EmbedAsset.cmake similarity index 50% rename from js/core/EmbedBinaryAsset.cmake rename to js/core/EmbedAsset.cmake index 0178a8ff..8263fc02 100644 --- a/js/core/EmbedBinaryAsset.cmake +++ b/js/core/EmbedAsset.cmake @@ -1,16 +1,39 @@ -# Renders a small binary asset (identity encoded) as a header in the format of the embedded assets, -# in pure CMake: no Node.js, no script. Bounded lines are joined once, so the string never grows -# word by word. Used for the default favicon; larger or compressed assets are out of scope. -# cmake -DINPUT= -DSTRUCT= (-DOUTPUT=
| -DCHECK=
) -P EmbedBinaryAsset.cmake +# Renders an embedded asset of the core (identity encoded: the sources are small) as a header in the format of the embedded +# assets, in pure CMake: no other tool is needed to regenerate or check the headers of include/webfront/system. Bounded lines +# are joined once, so the string never grows word by word. +# cmake -DINPUT= -DSTRUCT= (-DOUTPUT=
| -DCHECK=
) [-DGIT_EXECUTABLE=] -P EmbedAsset.cmake +# CHECK compares the exact bytes of the header with the rendering of INPUT and fails when it is stale or missing. if(NOT DEFINED INPUT) - message(FATAL_ERROR "INPUT must name the binary asset source") + message(FATAL_ERROR "INPUT must name the asset source") endif() if(NOT DEFINED STRUCT) - message(FATAL_ERROR "STRUCT must name the generated struct, e.g. FaviconData") + message(FATAL_ERROR "STRUCT must name the generated struct, e.g. WebFrontJsData") endif() if(NOT DEFINED OUTPUT AND NOT DEFINED CHECK) message(FATAL_ERROR "Set OUTPUT to regenerate the header or CHECK to verify it") endif() +if(NOT EXISTS "${INPUT}") + message(FATAL_ERROR "${INPUT} does not exist") +endif() + +# A Windows checkout converting either file to CRLF would make it look stale, so both must keep LF through +# .gitattributes. Checked only in a git work tree, on every platform; the favicon is binary. +if(DEFINED CHECK AND GIT_EXECUTABLE AND NOT INPUT MATCHES "\\.ico$") + get_filename_component(source_dir "${INPUT}" DIRECTORY) + execute_process( + COMMAND "${GIT_EXECUTABLE}" check-attr eol -- "${INPUT}" "${CHECK}" + WORKING_DIRECTORY "${source_dir}" + OUTPUT_VARIABLE attributes + RESULT_VARIABLE not_in_work_tree + ERROR_QUIET) + if(NOT not_in_work_tree) + string(REGEX MATCHALL "eol: lf\n" lf_lines "${attributes}") + list(LENGTH lf_lines lf_count) + if(NOT lf_count EQUAL 2) + message(FATAL_ERROR "${INPUT} and ${CHECK} must have 'text eol=lf' in .gitattributes:\n${attributes}") + endif() + endif() +endif() file(SIZE "${INPUT}" size) file(READ "${INPUT}" hex HEX) @@ -65,12 +88,16 @@ if(DEFINED CHECK) if(NOT EXISTS "${CHECK}") message(FATAL_ERROR "${CHECK} is missing; run the webfront-embedded-assets target") endif() - file(READ "${CHECK}" current) - if(NOT current STREQUAL contents) + # Compared as bytes: a header with CRLF line ends is stale, which a text comparison would not see. + file(READ "${CHECK}" current HEX) + string(HEX "${contents}" expected) + if(NOT current STREQUAL expected) message(FATAL_ERROR "${CHECK} is stale; run the webfront-embedded-assets target") endif() else() get_filename_component(directory "${OUTPUT}" DIRECTORY) file(MAKE_DIRECTORY "${directory}") - file(WRITE "${OUTPUT}" "${contents}") + # file(WRITE) opens the file in text mode, which writes CRLF on Windows: file(CONFIGURE) writes the line ends it is told to. + # The header holds no @ and no ${...} that it could substitute. + file(CONFIGURE OUTPUT "${OUTPUT}" CONTENT "${contents}" @ONLY NEWLINE_STYLE UNIX) endif() diff --git a/js/core/EmbedTextAsset.cmake b/js/core/EmbedTextAsset.cmake deleted file mode 100644 index efdb3216..00000000 --- a/js/core/EmbedTextAsset.cmake +++ /dev/null @@ -1,48 +0,0 @@ -if(NOT DEFINED INPUT) - message(FATAL_ERROR "INPUT must name the readable text asset source") -endif() - -if(NOT DEFINED OUTPUT AND NOT DEFINED CHECK) - message(FATAL_ERROR "Set OUTPUT to regenerate the header or CHECK to verify it") -endif() - -if(NOT DEFINED STRUCT) - message(FATAL_ERROR "STRUCT must name the generated struct, e.g. WebFrontJsData") -endif() - -# A Windows checkout converting either file to CRLF would make it look stale, so both must keep -# LF through .gitattributes. Checked only in a git work tree, on every platform. -if(DEFINED CHECK AND GIT_EXECUTABLE AND NOT INPUT MATCHES "\\.png$") - get_filename_component(source_dir "${INPUT}" DIRECTORY) - execute_process( - COMMAND "${GIT_EXECUTABLE}" check-attr eol -- "${INPUT}" "${CHECK}" - WORKING_DIRECTORY "${source_dir}" - OUTPUT_VARIABLE attributes - RESULT_VARIABLE not_in_work_tree - ERROR_QUIET) - if(NOT not_in_work_tree) - string(REGEX MATCHALL "eol: lf\n" lf_lines "${attributes}") - list(LENGTH lf_lines lf_count) - if(NOT lf_count EQUAL 2) - message(FATAL_ERROR "${INPUT} and ${CHECK} must have 'text eol=lf' in .gitattributes:\n${attributes}") - endif() - endif() -endif() - -# Render and compare in one process without intermediate gzip/header files. Normal C++ -# builds consume checked-in headers; Node is required only for maintenance and tests. -find_program(NODE_EXECUTABLE NAMES node nodejs REQUIRED) -set(arguments --input "${INPUT}" --struct "${STRUCT}") -if(GZIP) - list(APPEND arguments --gzip) -endif() -if(DEFINED CHECK) - list(APPEND arguments --check "${CHECK}") -else() - list(APPEND arguments --output "${OUTPUT}") -endif() -execute_process(COMMAND "${NODE_EXECUTABLE}" "${CMAKE_CURRENT_LIST_DIR}/../developer/vendor/embed.mjs" - ${arguments} RESULT_VARIABLE result) -if(NOT result EQUAL 0) - message(FATAL_ERROR "Embedded asset generation/check failed for ${INPUT}") -endif() diff --git a/js/core/WebFrontAssets.cmake b/js/core/WebFrontAssets.cmake index a9ac748e..804bd86b 100644 --- a/js/core/WebFrontAssets.cmake +++ b/js/core/WebFrontAssets.cmake @@ -1,46 +1,22 @@ -# Maintenance of the embedded browser bridge and fallback-page assets. Normal builds consume the -# checked-in generated headers; the webfront-embedded-assets target regenerates them from their -# readable sources, while CTest verifies (per asset, for clear failure attribution) that each is current. +# Maintenance of the embedded assets of the core: the browser bridge, the fallback and bootstrap pages and the favicon. Normal +# builds consume the checked-in generated headers; the webfront-embedded-assets target regenerates them from their readable +# sources with js/core/EmbedAsset.cmake, in pure CMake, while CTest verifies (per asset, for clear failure attribution) +# that each is current and that the bundles of the environment match the checksums of their inputs. set(_WEBFRONT_ASSETS_DIR "${CMAKE_CURRENT_LIST_DIR}") -function(_webfront_add_embedded_text_asset source header struct test_name) - add_custom_command(TARGET webfront-embedded-assets POST_BUILD - COMMAND ${CMAKE_COMMAND} - -DINPUT=${source} - -DOUTPUT=${header} - -DSTRUCT=${struct} - -DGZIP=${ARGN} - -P ${_WEBFRONT_ASSETS_DIR}/EmbedTextAsset.cmake - COMMENT "Regenerating ${header}" - VERBATIM - ) - # The text asset generator is still a Node.js tool (#318): its freshness checks need Node.js. - if(ENABLE_TESTING AND WEBFRONT_NODE_EXECUTABLE) - add_test(NAME ${test_name} - COMMAND ${CMAKE_COMMAND} - -DINPUT=${source} - -DCHECK=${header} - -DSTRUCT=${struct} - -DGZIP=${ARGN} - -DGIT_EXECUTABLE=${GIT_EXECUTABLE} - -P ${_WEBFRONT_ASSETS_DIR}/EmbedTextAsset.cmake - ) - endif() -endfunction() - -# The favicon is binary and small: a pure CMake renderer, with no Node.js, produces its header. -function(_webfront_add_embedded_binary_asset source header struct test_name) +function(_webfront_add_embedded_asset source header struct test_name) add_custom_command(TARGET webfront-embedded-assets POST_BUILD COMMAND ${CMAKE_COMMAND} -DINPUT=${source} -DOUTPUT=${header} -DSTRUCT=${struct} - -P ${_WEBFRONT_ASSETS_DIR}/EmbedBinaryAsset.cmake + -P ${_WEBFRONT_ASSETS_DIR}/EmbedAsset.cmake COMMENT "Regenerating ${header}" VERBATIM ) if(ENABLE_TESTING) add_test(NAME ${test_name} COMMAND ${CMAKE_COMMAND} -DINPUT=${source} -DCHECK=${header} -DSTRUCT=${struct} - -P ${_WEBFRONT_ASSETS_DIR}/EmbedBinaryAsset.cmake) + -DGIT_EXECUTABLE=${GIT_EXECUTABLE} -P ${_WEBFRONT_ASSETS_DIR}/EmbedAsset.cmake + ) endif() endfunction() @@ -48,37 +24,23 @@ function(webfront_add_embedded_assets) find_package(Git QUIET) set(root "${_WEBFRONT_ASSETS_DIR}/../..") cmake_path(NORMAL_PATH root) - add_custom_target(webfront-embedded-assets COMMENT "Regenerating embedded browser bridge and fallback-page assets") - # Until #318 removes Node.js from the tests, the checks that still use it are registered when it is found. The default - # requires it, so that a test build never silently drops them; the job that proves a build without Node.js sets - # WEBFRONT_REQUIRE_NODE=OFF. - if(ENABLE_TESTING) - if(WEBFRONT_REQUIRE_NODE) - find_program(WEBFRONT_NODE_EXECUTABLE NAMES node nodejs REQUIRED) - else() - find_program(WEBFRONT_NODE_EXECUTABLE NAMES node nodejs) - if(NOT WEBFRONT_NODE_EXECUTABLE) - message(STATUS "Node.js not found and not required: the asset freshness and JavaScript tests are not registered") - endif() - endif() - endif() - _webfront_add_embedded_text_asset( + add_custom_target(webfront-embedded-assets COMMENT "Regenerating the embedded assets of the core") + _webfront_add_embedded_asset( "${root}/js/core/WebFront.js" "${root}/include/webfront/system/WebFrontJsData.hpp" WebFrontJsData WebFrontJsAssetsFresh) - _webfront_add_embedded_text_asset( + _webfront_add_embedded_asset( "${root}/js/core/fallback/index.html" "${root}/include/webfront/system/FallbackIndexHtmlData.hpp" FallbackIndexHtmlData FallbackIndexHtmlAssetFresh) - _webfront_add_embedded_text_asset( + _webfront_add_embedded_asset( "${root}/js/core/fallback/webfront-fallback.mjs" "${root}/include/webfront/system/FallbackModuleData.hpp" FallbackModuleData FallbackModuleAssetFresh) - _webfront_add_embedded_binary_asset( + _webfront_add_embedded_asset( "${root}/js/core/favicon.ico" "${root}/include/webfront/system/FaviconData.hpp" FaviconData FaviconAssetFresh) - - _webfront_add_embedded_text_asset( + _webfront_add_embedded_asset( "${root}/js/core/bootstrap/index.html" "${root}/include/webfront/system/DeveloperIndexHtmlData.hpp" DeveloperIndexHtmlData DeveloperIndexHtmlAssetFresh) - _webfront_add_embedded_text_asset( + _webfront_add_embedded_asset( "${root}/js/core/bootstrap/bootstrap.bundle.mjs" "${root}/include/webfront/system/DeveloperBootstrapData.hpp" DeveloperBootstrapData DeveloperBootstrapAssetFresh) @@ -89,15 +51,25 @@ function(webfront_add_embedded_assets) add_test(NAME MinimalCoreAssetsRejectsUnlisted COMMAND ${CMAKE_COMMAND} -DROOT=${root} -DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/minimal-core-assets -P ${root}/test/cmake/CheckMinimalCoreAssetsNegative.cmake) - if(WEBFRONT_NODE_EXECUTABLE) - add_test(NAME DeveloperJavaScript COMMAND "${WEBFRONT_NODE_EXECUTABLE}" - --test "${root}/js/developer/tools/check.mjs" "${root}/js/developer/tools/distribution-check.mjs" - "${root}/js/developer/tools/manifest-check.mjs" "${root}/js/developer/tools/restore-check.mjs" "${root}/js/developer/tools/scripts-check.mjs") - set_tests_properties(DeveloperJavaScript PROPERTIES TIMEOUT 30) - add_test(NAME EmbeddedAssetGenerator COMMAND ${CMAKE_COMMAND} -E env - "WEBFRONT_TEST_CMAKE=${CMAKE_COMMAND}" "${WEBFRONT_NODE_EXECUTABLE}" - --test "${root}/js/developer/vendor/embed.test.mjs") - set_tests_properties(EmbeddedAssetGenerator PROPERTIES TIMEOUT 30) - endif() + # The renderer: exact format, exit status of a stale or missing header, a checkout reached through a symbolic link. + add_test(NAME EmbeddedAssetGenerator + COMMAND ${CMAKE_COMMAND} -DROOT=${root} -DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/embedded-asset-generator + -P ${root}/test/cmake/CheckEmbedAsset.cmake) + # A source of the environment's bundles changed without rebuilding them is detected: no browser is needed. + add_test(NAME BundleInputsFresh + COMMAND ${CMAKE_COMMAND} -DROOT=${root} -P ${root}/test/cmake/CheckBundleInputs.cmake) + add_test(NAME BundleInputsRejectsChange + COMMAND ${CMAKE_COMMAND} -DROOT=${root} -DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/bundle-inputs + -P ${root}/test/cmake/CheckBundleInputsNegative.cmake) + # No path of the project depends on a JavaScript runtime or package manager: every file is audited, and the guard is + # proven by injections. + add_test(NAME NoNodeDependency + COMMAND ${CMAKE_COMMAND} -DROOT=${root} -DGIT_EXECUTABLE=${GIT_EXECUTABLE} -P ${root}/test/cmake/CheckNoNode.cmake) + add_test(NAME NoNodeDependencyRejectsInjections + COMMAND ${CMAKE_COMMAND} -DROOT=${root} -DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/no-node-guard + -P ${root}/test/cmake/CheckNoNodeNegative.cmake) + # The terminal and webfront::Commands refuse the same command names. + add_test(NAME CommandNamesAgree + COMMAND ${CMAKE_COMMAND} -DROOT=${root} -P ${root}/test/cmake/CheckCommandNames.cmake) endif() endfunction() diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 7930b20b..2a421257 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -1,7 +1,7 @@ { "js/developer/environment/manifest.mjs": "b534d152e6fb008b23d4cad00d8d72913091a9acd12603356995cbd8ed08f76c", "js/developer/environment/project.mjs": "280cced29e41bc48d5d9d69934186ababfdbbc9dc32ed9517e17af4f19d3bd73", - "js/developer/environment/installer.mjs": "d4e67a246fc907d6123ff9602f09c6c263c7942d86890d4f408cbed3cc63b717", + "js/developer/environment/installer.mjs": "1159404b151dc8c580d9a155a9ec0dfa3fcb6a8e073d8586d29b329ce91b741b", "js/developer/environment/restore.mjs": "cdd22eebd55d68bd705685cd5ee3059e228a35053eaad116ab99c4c05b908098", "js/developer/environment/cache.mjs": "6fd0e3b760dfc1070a28e2e2eb3c86621c970c775045e7a9ae665da4f6845922", "js/developer/environment/scripts.mjs": "83ae28e822db986d9b3ae547f005f1a7c94868c36f232d68ddeb6126fb0a5021", @@ -13,7 +13,7 @@ "js/developer/environment/packages-entry.mjs": "e0b4acd4330b8b51eb0e695384c8df2b103a4be4f598ac83277838022f747e30", "js/developer/environment/bootstrap.mjs": "5fa50cc9264809a6a9eb03564a60fbe3171a3ffcc781d26352ae59e2866a7090", "js/developer/environment/bootstrap-entry.mjs": "ff8084f23f5acc721f97eb1ed0a454e7bfee1894de17d54f0100fa11f7ef8b77", - "js/developer/environment/packages.mjs": "6636219f3fef20ea1d274dc9298d8af451ef257b86fe6c1ed0de9a7c797b11d8", + "js/developer/environment/packages.mjs": "37fe2a410e211264cfeaedbff3df50f7e62b02f8088130127d94f92081e2a5ad", "js/developer/environment/starter.mjs": "f38e290e03aebe146623c2ca9b590d645fb91a51acdf7a98101bb00b5b88096c", "js/developer/environment/paths.mjs": "3b6114df78eb193161c5c84499dda084cb7ff91c56a4496371c30295d00880e3", "js/developer/environment/runtime.mjs": "98ed06660333d2a90f9857b5b21da811f9d4ecda78d011dc88501679af7388da", @@ -34,18 +34,17 @@ "js/developer/environment/pins.mjs": "df07f6f01edaf86a1052d0e76f6c6745cb6e7a3309bbd256ac720ee8adc85297", "js/developer/environment/peers.mjs": "e1d999892138682fc0134ef1f4d4b19b9a9ad8d7fb16e37fc9c6c684bd853896", "js/developer/environment/resolve.mjs": "8b96b850af215be51f5cb85cc9c69e057afa04dfb8a57e572620c07059c17fa3", - "js/developer/environment/embed.mjs": "c370fd05b1629d630a3d504f65f6411df3a73c0f6deabf484654bddae52857a2", + "js/developer/environment/embed.mjs": "7e9c0ae9bde50b1f434c1635b90f1c3c0840cf00f8a12620727bae59096c187c", "js/developer/tools/starters/pi/main.tsx": "d3161b35db204ba54f782f711183e8d96aeff7c92d885c33a6ec168cf461e453", "js/developer/tools/starters/pi/style.css": "360e2c7ae6d3699b00e18cbf67efbae7a8d8863d88926b31139e102cf38e5abd", "examples/life/ui/main.tsx": "ed11a82aad1639eb6997af8b0fca4d5c5ed4c36422c22a74ac49ae73078d0a91", "examples/life/ui/style.css": "9bb55eb0f0a3287e5b7dc78af9d69608b87ff42c4d9c8a653bc83a52fe293c44", "js/developer/tools/distribution.json": "f53e062b5e54f10c3120a89ea03916ed861b000af2df2b6e51657c4dfa9b1884", "js/developer/tools/archive.mjs": "bfe9feeb5e4d4e1b7c44c4dec4dcbeab4ae59c2bf16a1d2b32cd6910a2b84e7b", - "js/developer/tools/distribution.mjs": "8ec13a20d29ddb23c06558807fb01d405dcc00ffa872a023a16f7f56a24ea3ff", - "js/developer/tools/asset-header.mjs": "b31608fd39d9d7477c01e1f14b72494bfd579e9d68029f621d469be529074e85", - "js/developer/scripts/build.mjs": "7bf218847988d17c1bb0da3a7cda060ab0d10bdf17612cdfad4f14486910b1bc", - "webfront.project.json": "fef1af6974c8ebf50afd630d2675b2046a801c597b74278005d7f3a7f9dba22c", + "js/developer/tools/distribution.mjs": "1108b61bc659dd945ba1417aa84337bca03039842d342c95815b5463d87a136e", + "js/developer/scripts/build.mjs": "a25e19e357480e1ddde1a425966150f6f3c6e474843ead90f5d67e0a4c704f54", + "webfront.project.json": "081bcfebac2239e44614e5df227038189ed4ebc6484d31f4ab51af0dd7e4740e", "js/core/bootstrap/bootstrap.bundle.mjs": "536831257f0fc92e31911841750e1e59247f7c64e756b0fcb878efd9860a741f", "js/developer/environment/packages.bundle.mjs": "e36d1052285a313f7db67c1f58f8332da9e97446b1e2085422ebdae379288045", - "include/webfront/system/DeveloperReleaseData.hpp": "e845086c05ae9ac4a32f7ed62f0b812a9cf375524460b2cc6e6a19ecbd64aea7" + "include/webfront/system/DeveloperReleaseData.hpp": "7aa74c8e31501fa8733b47767fd11cc4e316ba70634331d86d35d78bd5a4b91c" } diff --git a/js/developer/environment/embed.mjs b/js/developer/environment/embed.mjs index f9903620..d3fbfd95 100644 --- a/js/developer/environment/embed.mjs +++ b/js/developer/environment/embed.mjs @@ -30,7 +30,7 @@ function declarationOf(name, compressed) { };`; } -// The same big-endian word layout, padding and gzip settings as EmbedTextAsset.cmake. +// The same big-endian word layout and padding as js/core/EmbedAsset.cmake, with the gzip settings of the environment. export function generateProvider(files, className = 'ApplicationAssets', notices = '') { if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(className)) throw new Error('Invalid generated provider name'); const declarations = []; diff --git a/js/developer/environment/installer.mjs b/js/developer/environment/installer.mjs index 75e71865..bb2bc03c 100644 --- a/js/developer/environment/installer.mjs +++ b/js/developer/environment/installer.mjs @@ -114,7 +114,7 @@ export async function install(bridge, args, {registry, registryExplicit, signal, if (specs.length && project.status === 'desynchronized') throw new Error(desynchronized); if (!specs.length && !update && project.status === 'desynchronized') throw new Error(desynchronized); progress(describeRegistry(effective)); - // npm ci: exactly the locked graph, every archive checked against the recorded integrity. + // Exactly the locked graph, every archive checked against the recorded integrity. const locked = project.status === 'consistent' || project.status === 'legacy'; if (!specs.length && !update && locked) { const {restored} = await restorePackages(bridge, project.lock, options); diff --git a/js/developer/environment/packages.mjs b/js/developer/environment/packages.mjs index 57de2be4..87fc2185 100644 --- a/js/developer/environment/packages.mjs +++ b/js/developer/environment/packages.mjs @@ -26,7 +26,7 @@ async function resolveRoots(specifications, visit) { return roots; } -// A distinct node per exact version; edges are retained instead of flattening node_modules. +// A distinct node per exact version; edges are retained instead of flattening the graph into one directory. export async function resolvePackages(specifications, options = {}) { const fetchPackage = pinnedDownloader(options); const state = {nodes: {}, downloads: new Map(), total: 0}; diff --git a/js/developer/scripts/build.mjs b/js/developer/scripts/build.mjs index 2a847158..743d9123 100644 --- a/js/developer/scripts/build.mjs +++ b/js/developer/scripts/build.mjs @@ -3,15 +3,15 @@ // wf run js/developer/scripts/build.mjs [] [--refresh-bootstrap] // // The compiler is the locked esbuild-wasm of webfront.project.json, run in the script's Worker; the files it reads are -// the project's and the locked packages'. With --refresh-bootstrap, the checked-in bootstrap bundles, their checksums -// and the core headers that embed them are regenerated too. +// the project's and the locked packages'. With --refresh-bootstrap, the checked-in bootstrap bundles, their checksums and +// the pinned header are regenerated too; the core headers that embed the bundles come from the CMake target +// webfront-embedded-assets (js/core/EmbedAsset.cmake). import * as esbuild from 'esbuild-wasm'; import {virtualPlugin} from '../environment/bundler.mjs'; import {compress} from '../environment/embed.mjs'; import {packageRoot} from '../environment/paths.mjs'; import {tar} from '../tools/archive.mjs'; import {baseUrl, versionPath, bootstrapHeader, sriOf} from '../tools/distribution.mjs'; -import {renderAsset} from '../tools/asset-header.mjs'; const lockPath = 'webfront-packages.lock.json'; const encoder = new TextEncoder(); @@ -111,8 +111,6 @@ export default async function (context) { for (const path of JSON.parse(await project.readText('js/developer/tools/bundle-inputs.json'))) inputs[path] = hexOf(await crypto.subtle.digest('SHA-256', await read(path))); await write('js/developer/environment/bundles.json', JSON.stringify(inputs, null, 2) + '\n'); - for (const [source, name] of [['js/core/bootstrap/index.html', 'DeveloperIndexHtmlData'], ['js/core/bootstrap/bootstrap.bundle.mjs', 'DeveloperBootstrapData']]) - await write(`include/webfront/system/${name}.hpp`, renderAsset(await read(source), name)); } context.console.log(`Environment: ${output}/environment.tgz\nIntegrity: ${integrity}\nStarters: ${Object.keys(starters).join(', ')}`); } diff --git a/js/developer/scripts/embed-core.mjs b/js/developer/scripts/embed-core.mjs deleted file mode 100644 index 8bbed470..00000000 --- a/js/developer/scripts/embed-core.mjs +++ /dev/null @@ -1,23 +0,0 @@ -// Regenerates the headers of the core's embedded assets from their readable sources, with wf: -// -// wf run js/developer/scripts/embed-core.mjs -// -// The bytes are those of the CMake target webfront-embedded-assets: the same renderer, no compression. -import {renderAsset} from '../tools/asset-header.mjs'; - -// [readable source, generated struct]: the closed list of ADR-016, minus the pinned release data. -export const coreAssets = [ - ['js/core/WebFront.js', 'WebFrontJsData'], - ['js/core/fallback/index.html', 'FallbackIndexHtmlData'], - ['js/core/fallback/webfront-fallback.mjs', 'FallbackModuleData'], - ['js/core/favicon.ico', 'FaviconData'], - ['js/core/bootstrap/index.html', 'DeveloperIndexHtmlData'], - ['js/core/bootstrap/bootstrap.bundle.mjs', 'DeveloperBootstrapData'], -]; - -export default async function (context) { - if (context.args.length) throw new Error('Usage: wf run embed-core'); - for (const [source, name] of coreAssets) - await context.project.write(`include/webfront/system/${name}.hpp`, renderAsset(await context.project.read(source), name)); - context.console.log(`Regenerated ${coreAssets.length} core headers.`); -} diff --git a/js/developer/tools/PUBLISHING.md b/js/developer/tools/PUBLISHING.md index d87f72fc..9c147169 100644 --- a/js/developer/tools/PUBLISHING.md +++ b/js/developer/tools/PUBLISHING.md @@ -8,7 +8,7 @@ The package names in their manifests are identifiers, not a requirement to own o The environment builds itself: the pinned bootstrap environment (`cmake/WebFrontBootstrap.cmake`) runs the scripts of `js/developer/scripts/` on the sources of this repository, which is a `wf` project (`webfront.project.json` and its lock). Building, reviewing and publishing need a C++23 compiler, CMake, the engine of the driver's frontend and `gh` -and `jq` for the host operations; they need no Node.js, npm or npx. +and `jq` for the host operations. ## Build and review @@ -16,7 +16,7 @@ The driver `webfront-wf` runs one `wf` command without interaction on a project works; WebKitGTK on Linux is the one CI uses. ```sh -cmake -S . -B build-driver -DCMAKE_BUILD_TYPE=Release -DENABLE_TESTING=ON -DWEBFRONT_REQUIRE_NODE=OFF \ +cmake -S . -B build-driver -DCMAKE_BUILD_TYPE=Release -DENABLE_TESTING=ON \ -DWEBFRONT_EMBED_WEBKITGTK=ON -DWEBFRONT_WEBTEST_FRONTEND=WebKitGTK cmake --build build-driver --target webfront-wf wf() { xvfb-run -a build-driver/test/web/webfront-wf --project "$PWD" -- "$@"; } @@ -29,9 +29,9 @@ cmp build-distribution/environment.tgz build-distribution-repeat/environment.tgz `wf run build --refresh-bootstrap` also rebuilds the checked-in bootstrap bundles (`js/core/bootstrap/bootstrap.bundle.mjs`, `js/developer/environment/packages.bundle.mjs`), their checksums -(`js/developer/environment/bundles.json`, over the inputs of `js/developer/tools/bundle-inputs.json`) and the embedded -headers `DeveloperIndexHtmlData.hpp` and `DeveloperBootstrapData.hpp`. `wf run embed-core` regenerates the headers of the core's embedded assets from their readable sources (the same bytes as -the CMake target `webfront-embedded-assets`). A script may only write where `permissions.publish` +(`js/developer/environment/bundles.json`, over the inputs of `js/developer/tools/bundle-inputs.json`) and the pinned +header. The core headers that embed the bootstrap bundle (`DeveloperIndexHtmlData.hpp`, `DeveloperBootstrapData.hpp`) are +rendered from their sources by CMake, like the others: `cmake --build --target webfront-embedded-assets`. A script may only write where `permissions.publish` of `webfront.project.json` allows: the `build-*` directories and these checked-in outputs. The output of a script reaches the terminal of an environment 0.6.1 or later; with 0.6.0 the command prints @@ -90,12 +90,11 @@ Initial Pages enablement is deliberately a maintainer operation, not a side effe ## Automated publication The **Developer packages** workflow builds packages on relevant pushes/PRs and retains them as an -artifact. Its `wf-package` job removes Node.js, npm and npx from the runner, builds the driver, restores the locked +artifact. Its `wf-package` job removes every JavaScript runtime from the runner, builds the driver, restores the locked dependencies, builds the distribution twice and compares the repeat build and the checked-in bootstrap header before -permitting publication. During the transition from Node.js (#318), the `package` job also builds it with the Node.js tools -and `wf-package` requires the same bytes. +permitting publication; it also runs the specs of the environment with `wf test`. It publishes only on a `developer-v` tag or an explicit workflow dispatch with `publish=true`. The `publish` job -runs the same way, without Node.js: `wf run site` stages the new version into a checkout of `gh-pages` and refuses to +runs the same way: `wf run site` stages the new version into a checkout of `gh-pages` and refuses to change a published one, `pages.sh` checks the configured source and requests the build, and `archive-release.sh` archives the files in a prerelease. Use the dedicated tag `developer-v` matching `distribution.json`; the C++ library's `v*` releases remain separate. @@ -115,12 +114,12 @@ Pages, whose cross-origin behavior is checked independently of Release asset red Check the canonical Pages URL, its `Access-Control-Allow-Origin` response and the archive checksum. Then run the optional live smoke test (the ordinary CTest suite remains entirely offline). Its fixtures (the local -registry and the test pages) are still provisioned with Node.js until #318 and #319 replace them: +registry and the test pages) are the ones that the CTest case `DeveloperFixtures` assembles in the build directory: ```sh -node js/developer/tools/fixtures.mjs build-distribution +ctest --test-dir build-native -R '^DeveloperFixtures$' --output-on-failure ./build-native/test/web/developer_integration \ - "$PWD/build-distribution" "$PWD/build-native/test/web/public-generated" --public + "$PWD/build-native/test/web/developer-fixtures" "$PWD/build-native/test/web/public-generated" --public ``` This mode downloads the pinned environment and both starters from Pages, fetches exact React/React DOM diff --git a/js/developer/tools/RELEASE_NOTES.md b/js/developer/tools/RELEASE_NOTES.md index 1f0e9e24..6409d08a 100644 --- a/js/developer/tools/RELEASE_NOTES.md +++ b/js/developer/tools/RELEASE_NOTES.md @@ -2,9 +2,9 @@ Browser-powered WebFront developer environment with Game of Life and PI starters Version 0.3.0 migrates the Life starter to packed Uint8Array grids: 128 bytes per generation with direct C++ bitset registration. It requires the bridge support introduced in #289. The interface retains editable patterns, playback, reset and single stepping. Version 0.3.1 makes `wf install` honor the installed lock: versions it records are kept and their archives must still match the recorded integrity. Published versions 0.1.0 to 0.3.0 remain available without modification. -Download through the version-pinned GitHub Pages URLs in the bootstrap configuration. SHA-512 is verified before executing the environment or creating a starter. React, React DOM and scheduler remain on npm; application developers do not install Node.js or npm. Both starters can generate their own compressed header-only resources for an offline native executable. +Download through the version-pinned GitHub Pages URLs in the bootstrap configuration. SHA-512 is verified before executing the environment or creating a starter. React, React DOM and scheduler remain on npm; application developers install no JavaScript tooling. Both starters can generate their own compressed header-only resources for an offline native executable. -The environment includes the terminal, npm resolver, esbuild/WASM compiler, embedding tools and dependency notices. These packages are experimental; browser packages only, without installation scripts, native modules or Node API shims. +The environment includes the terminal, npm resolver, esbuild/WASM compiler, embedding tools and dependency notices. These packages are experimental; browser packages only, without installation scripts, native modules or server-side runtime shims. Version 0.4.0 updates the Life starter text for a developer audience. The simulation and bridge contract are unchanged. diff --git a/js/developer/tools/archive-release.mjs b/js/developer/tools/archive-release.mjs deleted file mode 100644 index 7840416c..00000000 --- a/js/developer/tools/archive-release.mjs +++ /dev/null @@ -1,35 +0,0 @@ -// Dedicated prereleases: retries verify existing assets, never replace an existing release. -import {execFileSync} from 'node:child_process'; -import {readFile, mkdtemp, rm} from 'node:fs/promises'; -import {join, resolve} from 'node:path'; -import {tmpdir} from 'node:os'; -import {distributionFiles} from './site.mjs'; -const [tag, distribution] = process.argv.slice(2); -const metadata = JSON.parse(await readFile(new URL('./distribution.json', import.meta.url))); -const repository = process.env.GITHUB_REPOSITORY; -if (tag !== `developer-v${metadata.version}` || !/^[\w.-]+\/[\w.-]+$/.test(repository ?? '')) - throw new Error('Expected the dedicated distribution tag and GITHUB_REPOSITORY'); -const gh = (...args) => execFileSync('gh', args, {encoding: 'utf8'}); -const files = distributionFiles(JSON.parse(await readFile(join(distribution, 'provision.json')))); -let existing = false; -try { - gh('api', `repos/${repository}/releases/tags/${tag}`); - existing = true; -} catch (error) { - if (!String(error.stderr).includes('(HTTP 404)')) throw error; -} -if (existing) { - const directory = await mkdtemp(join(tmpdir(), 'webfront-release-')); - try { - gh('release', 'download', tag, '--repo', repository, '--dir', directory, - ...files.flatMap(name => ['--pattern', name])); - for (const name of files) - if (!(await readFile(join(directory, name))).equals(await readFile(join(distribution, name)))) - throw new Error(`Existing release asset ${name} differs; choose a new version`); - console.log('Existing release assets match the distribution'); - } finally { await rm(directory, {recursive: true, force: true}); } -} else { - console.log(gh('release', 'create', tag, '--repo', repository, '--verify-tag', '--prerelease', - '--title', `WebFront developer packages ${metadata.version}`, - '--notes-file', resolve('js/developer/tools/RELEASE_NOTES.md'), ...files.map(name => resolve(distribution, name)))); -} diff --git a/js/developer/tools/asset-header.mjs b/js/developer/tools/asset-header.mjs deleted file mode 100644 index 02bd2e05..00000000 --- a/js/developer/tools/asset-header.mjs +++ /dev/null @@ -1,35 +0,0 @@ -// The checked-in header format of an embedded asset, with no host API: wf scripts and the Node tools render the same bytes. -import {compress} from '../environment/embed.mjs'; - -const hexOf = bytes => Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join(''); - -export function renderAsset(source, name, compressed = false) { - const payload = compressed ? compress(source) : source; - const hex = hexOf(payload); - const lines = []; - // Build bounded lines, then join once. Appending every word in CMake repeatedly - // copied a growing string and made large assets particularly expensive on Windows. - for (let offset = 0; offset < hex.length; offset += 80) { - const words = hex.slice(offset, offset + 80).match(/.{1,16}/g); - lines.push(` ${words.map(word => `0x${word.padEnd(16, '0')}`).join(', ')}`); - } - const words = lines.length ? `\n${lines.join(',\n')}` : ''; - return `#pragma once - -#include -#include -#include -#include - -namespace webfront::fs::generated { - -struct ${name} { - static constexpr std::string_view encoding${compressed ? '{"gzip"}' : '{}'}; - static constexpr std::size_t dataSize{${payload.length}}; - static constexpr std::array data{${words} - }; -}; - -} // namespace webfront::fs::generated -`; -} diff --git a/js/developer/tools/build.mjs b/js/developer/tools/build.mjs deleted file mode 100644 index e5b5c88c..00000000 --- a/js/developer/tools/build.mjs +++ /dev/null @@ -1,87 +0,0 @@ -// Maintainer provisioning only. Consumers download the resulting tarball, without Node/npm. -import {build} from '../vendor/node_modules/esbuild/lib/main.js'; -import {readFile, writeFile, mkdir, copyFile} from 'node:fs/promises'; -import {resolve} from 'node:path'; -import {fileURLToPath} from 'node:url'; -import {createHash} from 'node:crypto'; -import {execFileSync} from 'node:child_process'; -import {gzipSync} from '../../../third_party/fflate/browser.mjs'; -import {tar} from './archive.mjs'; -import {baseUrl, versionPath, bootstrapHeader} from './site.mjs'; - -const root = fileURLToPath(new URL('../../../', import.meta.url)); -const args = process.argv.slice(2); -const refresh = args.includes('--refresh-bootstrap'); -const output = resolve(args.find(arg => !arg.startsWith('--')) ?? resolve(root, 'build-developer-environment')); -await mkdir(output, {recursive: true}); -const options = { - absWorkingDir: root, bundle: true, format: 'esm', platform: 'browser', target: 'es2020', - minify: true, legalComments: 'inline', - nodePaths: [resolve(root, 'js/developer/vendor/node_modules')], -}; -await build({...options, entryPoints: ['js/developer/environment/runtime.mjs'], outfile: resolve(output, 'runtime.mjs')}); -await build({...options, entryPoints: ['js/developer/environment/compiler.mjs'], outfile: resolve(output, 'compiler.mjs')}); -await build({...options, entryPoints: ['js/developer/environment/script-worker.mjs'], outfile: resolve(output, 'script-worker.mjs')}); -await build({...options, entryPoints: ['js/developer/environment/typecheck-worker.mjs'], outfile: resolve(output, 'typecheck-worker.mjs')}); -await copyFile(resolve(root, 'js/developer/vendor/node_modules/esbuild-wasm/esbuild.wasm'), resolve(output, 'esbuild.wasm')); -await copyFile(resolve(root, 'js/developer/vendor/node_modules/@xterm/xterm/css/xterm.css'), resolve(output, 'xterm.css')); -const distribution = JSON.parse(await readFile(resolve(root, 'js/developer/tools/distribution.json'))); -const version = distribution.version; -const publicBase = baseUrl(distribution.baseUrl); -versionPath(version); -const dependencies = JSON.parse(await readFile(resolve(root, 'js/developer/vendor/package.json'))).dependencies; -const licenses = [ - ['esbuild-wasm', 'js/developer/vendor/node_modules/esbuild-wasm/LICENSE.md'], - ['semver', 'js/developer/vendor/node_modules/semver/LICENSE'], - ['xterm', 'js/developer/vendor/node_modules/@xterm/xterm/LICENSE'], - ['xterm Fit addon', 'js/developer/vendor/node_modules/@xterm/addon-fit/LICENSE'], - ['fflate', 'third_party/fflate/LICENSE'], -]; -const notices = []; -for (const [name, path] of licenses) notices.push(`${name}\n${await readFile(resolve(root, path), 'utf8')}`); -await writeFile(resolve(output, 'LICENSES.txt'), notices.join('\n\n')); -// The starter is pinned by the environment's own trusted archive, not by unverified remote metadata. -const starters = {}; -for (const [name, provider] of [['pi', 'PiUI'], ['life', 'LifeUI']]) { - const starterFiles = new Map(); - for (const file of ['main.tsx', 'style.css']) - starterFiles.set(`package/${file}`, await readFile(resolve(root, `${name === 'life' ? 'examples/life/ui' : 'js/developer/tools/starters/pi'}/${file}`))); - const recipe = {format: 1, name: `${name}-starter`, version, dependencies: { - react: dependencies.react, 'react-dom': dependencies['react-dom']}, - entries: {main: 'main.tsx'}, providers: {[provider]: {entry: 'main', output: `generated/${provider}.hpp`}}}; - starterFiles.set('package/webfront.project.json', Buffer.from(JSON.stringify(recipe, null, 2) + '\n')); - starterFiles.set('package/package.json', Buffer.from(JSON.stringify({name: `@webfront/${name}-starter`, version, - private: true, webfront: {kind: 'starter', entry: 'main.tsx'}}, null, 2) + '\n')); - const starterBytes = gzipSync(tar(starterFiles), {level: 9, mem: 8, mtime: 0}); - const archive = `${name}-starter.tgz`; - await writeFile(resolve(output, archive), starterBytes); - starters[name] = {archive, integrity: 'sha512-' + createHash('sha512').update(starterBytes).digest('base64')}; -} -await writeFile(resolve(output, 'environment.json'), JSON.stringify({protocol: 1, api: 1, version, entry: 'runtime.mjs', - compiler: `esbuild-wasm@${dependencies['esbuild-wasm']}`, semver: dependencies.semver, starters}, null, 2) + '\n'); -await writeFile(resolve(output, 'package.json'), JSON.stringify({name: '@webfront/developer-environment', version, - description: 'Browser-powered WebFront developer environment', type: 'module', - files: ['runtime.mjs', 'compiler.mjs', 'script-worker.mjs', 'typecheck-worker.mjs', 'esbuild.wasm', 'xterm.css', 'environment.json', 'LICENSES.txt']}, null, 2) + '\n'); -const files = new Map(); -for (const name of ['runtime.mjs', 'compiler.mjs', 'script-worker.mjs', 'typecheck-worker.mjs', 'esbuild.wasm', 'xterm.css', 'environment.json', 'LICENSES.txt', 'package.json']) - files.set(`package/${name}`, await readFile(resolve(output, name))); -const bytes = gzipSync(tar(files), {level: 9, mem: 8, mtime: 0}); -await writeFile(resolve(output, 'environment.tgz'), bytes); -const integrity = 'sha512-' + createHash('sha512').update(bytes).digest('base64'); -await writeFile(resolve(output, 'provision.json'), JSON.stringify({format: 1, version, environment: './environment.tgz', integrity, starters}, null, 2) + '\n'); -const header = bootstrapHeader(version, publicBase, integrity); -await writeFile(resolve(output, 'DeveloperReleaseData.hpp'), header); -if (refresh) { - const bootstrap = resolve(root, 'js/core/bootstrap/bootstrap.bundle.mjs'); - await build({...options, entryPoints: ['js/developer/environment/bootstrap-entry.mjs'], outfile: bootstrap}); - await build({...options, entryPoints: ['js/developer/environment/packages-entry.mjs'], outfile: resolve(root, 'js/developer/environment/packages.bundle.mjs')}); - await copyFile(resolve(root, 'js/developer/vendor/node_modules/semver/LICENSE'), resolve(root, 'js/developer/environment/PACKAGES-LICENSE.txt')); - await writeFile(resolve(root, 'include/webfront/system/DeveloperReleaseData.hpp'), header); - const inputs = {}; - for (const path of JSON.parse(await readFile(resolve(root, 'js/developer/tools/bundle-inputs.json')))) - inputs[path] = createHash('sha256').update(await readFile(resolve(root, path))).digest('hex'); - await writeFile(resolve(root, 'js/developer/environment/bundles.json'), JSON.stringify(inputs, null, 2) + '\n'); - for (const [source, name] of [['js/core/bootstrap/index.html', 'DeveloperIndexHtmlData'], ['js/core/bootstrap/bootstrap.bundle.mjs', 'DeveloperBootstrapData']]) - execFileSync('cmake', [`-DINPUT=${resolve(root, source)}`, `-DOUTPUT=${resolve(root, 'include/webfront/system', name + '.hpp')}`, `-DSTRUCT=${name}`, '-P', resolve(root, 'js/core/EmbedTextAsset.cmake')]); -} -console.log(`Environment: ${output}/environment.tgz\nIntegrity: ${integrity}\nStarters: ${Object.keys(starters).join(', ')}`); diff --git a/js/developer/tools/bundle-inputs.json b/js/developer/tools/bundle-inputs.json index cf5cff79..cb263ca0 100644 --- a/js/developer/tools/bundle-inputs.json +++ b/js/developer/tools/bundle-inputs.json @@ -42,7 +42,6 @@ "js/developer/tools/distribution.json", "js/developer/tools/archive.mjs", "js/developer/tools/distribution.mjs", - "js/developer/tools/asset-header.mjs", "js/developer/scripts/build.mjs", "webfront.project.json", "js/core/bootstrap/bootstrap.bundle.mjs", diff --git a/js/developer/tools/check.mjs b/js/developer/tools/check.mjs deleted file mode 100644 index 6b38c389..00000000 --- a/js/developer/tools/check.mjs +++ /dev/null @@ -1,317 +0,0 @@ -import {test} from 'node:test'; -import assert from 'node:assert/strict'; -import {gunzipSync} from 'node:zlib'; -import {createHash} from 'node:crypto'; -import {readFile} from 'node:fs/promises'; -import vm from 'node:vm'; -import {resolvePackages, downloadPackage, validateLock} from '../environment/packages.bundle.mjs'; -import {packageEntry, normalize, virtualPlugin} from '../environment/bundler.mjs'; -import {generateProvider, compress} from '../environment/embed.mjs'; -import {environmentFiles, bootstrap} from '../environment/bootstrap.mjs'; -import {publish, responseBytes} from '../environment/io.mjs'; -import {tar} from './archive.mjs'; -import {parseSpec, verifyIntegrity, gunzip, readTar} from '../environment/tarball.mjs'; - -const encoder = new TextEncoder(); -const encode = value => encoder.encode(typeof value === 'string' ? value : JSON.stringify(value)); -const integrity = bytes => 'sha512-' + createHash('sha512').update(bytes).digest('base64'); -const idOf = (name, version) => `${name.replace('/', '+')}@${version}`; -function fixture(name, version, fields = {}, extra = {}) { - const files = new Map(Object.entries({'package/package.json': encode({name, version, ...fields}), ...extra})); - return compress(tar(files)); -} -function registry(packages) { - return async url => { - const path = new URL(url).pathname.slice(1); - if (path.endsWith('.tgz')) return new Response(packages[path.slice(0, -4)].bytes); - const pkg = packages[path]; - if (!pkg) return new Response('', {status: 404}); - const manifest = {dist: {tarball: `https://registry.test/${path}.tgz`, integrity: integrity(pkg.bytes)}}; - return Response.json({'dist-tags': {latest: pkg.version}, versions: {[pkg.version]: manifest}}); - }; -} - -test('resolves transitive semver edges, cycles, multiple versions and required peers', async () => { - const source = { - app: {version: '1.0.0', bytes: fixture('app', '1.0.0', {dependencies: {dep: '^2.0.0'}, peerDependencies: {react: '^19.0.0'}})}, - dep: {version: '2.1.0', bytes: fixture('dep', '2.1.0', {dependencies: {app: '1.0.0'}})}, - react: {version: '19.0.0', bytes: fixture('react', '19.0.0')}, - }; - const options = {registry: 'https://registry.test/', fetchImpl: registry(source)}; - const {lock} = await resolvePackages(['app@latest', 'react@19.0.0'], options); - assert.equal(lock.packages['app@1.0.0'].dependencies.dep, 'dep@2.1.0'); - assert.equal(lock.packages['dep@2.1.0'].dependencies.app, 'app@1.0.0'); - assert.equal(lock.packages['app@1.0.0'].dependencies.react, 'react@19.0.0'); - assert.equal(validateLock(lock), lock); - await assert.rejects(resolvePackages(['app'], options), /requires peer react/); - const download = async (name, range) => { - const version = name === 'dep' ? (range.startsWith('^1') ? '1.2.0' : '2.0.0') : '1.0.0'; - const manifest = {name, version, dependencies: name === 'a' ? {dep: '^1.0.0'} : name === 'b' ? {dep: '^2.0.0'} : {}}; - return {id: idOf(name, version), key: name, manifest, integrity: 'sha512-test', files: new Map()}; - }; - const multiple = await resolvePackages(['a', 'b'], {download}); - assert.equal(multiple.lock.packages['a@1.0.0'].dependencies.dep, 'dep@1.2.0'); - assert.equal(multiple.lock.packages['b@1.0.0'].dependencies.dep, 'dep@2.0.0'); -}); - -// Fake registry: dep 2.1.0 is installed, 2.2.0 is the newest; `tampered` changes the archive of 2.1.0. -const depIntegrity = {'2.1.0': 'sha512-first', '2.2.0': 'sha512-second'}; -function lockDownloads(requests, tampered = false) { - return async (name, range) => { - requests.push(`${name}@${range}`); - const version = name === 'dep' ? (depIntegrity[range] ? range : '2.2.0') : '1.0.0'; - const manifest = {name, version, dependencies: name === 'app' ? {dep: '^2.0.0'} : {}}; - let integrity = 'sha512-app'; - if (name === 'dep') integrity = tampered && version === '2.1.0' ? 'sha512-other' : depIntegrity[version]; - return {id: idOf(name, version), key: `${name}-${version}`, manifest, integrity, files: new Map()}; - }; -} - -test('an installed lock pins transitive versions and rejects changed archives', async () => { - const requests = []; - const first = await resolvePackages(['app'], {download: async (name, range) => lockDownloads(requests)(name, range === '^2.0.0' ? '2.1.0' : range)}); - assert.equal(first.lock.packages['app@1.0.0'].dependencies.dep, 'dep@2.1.0'); - requests.length = 0; - const again = await resolvePackages(['app@1.0.0'], {download: lockDownloads(requests), previous: first.lock}); - assert.equal(again.lock.packages['app@1.0.0'].dependencies.dep, 'dep@2.1.0'); - assert.ok(requests.includes('dep@2.1.0') && !requests.includes('dep@^2.0.0'), requests.join()); - await assert.rejects(resolvePackages(['app@1.0.0'], {download: lockDownloads(requests, true), previous: first.lock}), - /dep@2\.1\.0 no longer matches the integrity recorded in the lock/); - const fresh = await resolvePackages(['app@1.0.0'], {download: lockDownloads(requests)}); - assert.equal(fresh.lock.packages['app@1.0.0'].dependencies.dep, 'dep@2.2.0'); -}); - -test('rejects integrity, archive identity, traversal and installation scripts', async () => { - for (const [bytes, pattern] of [ - [fixture('wrong', '1.0.0'), /identity mismatch/], - [fixture('pkg', '1.0.0', {scripts: {postinstall: 'node setup.js'}}), /unsupported install script/], - [fixture('pkg', '1.0.0', {}, {'package/../escape': encode('bad')}), /Unsafe package path/], - [fixture('pkg', '1.0.0', {}, {'package/addon.node': encode('bad')}), /native module/], - ]) { - await assert.rejects(downloadPackage('pkg', 'latest', {registry: 'https://registry.test/', fetchImpl: registry({pkg: {bytes, version: '1.0.0'}})}), pattern); - } - const bytes = fixture('pkg', '1.0.0'); - const fetchImpl = async url => String(url).endsWith('.tgz') ? new Response(bytes) : Response.json({versions: {'1.0.0': {dist: {tarball: 'https://registry.test/pkg.tgz', integrity: integrity(encode('other'))}}}}); - await assert.rejects(downloadPackage('pkg', '1.0.0', {registry: 'https://registry.test/', fetchImpl}), /Integrity check failed/); -}); - -test('resolves browser conditional exports and rejects private and Node imports', async () => { - assert.equal(packageEntry({exports: {'.': {browser: './browser.js', default: './node.js'}, './*': './src/*.mjs'}}, ''), 'browser.js'); - assert.equal(packageEntry({exports: {'./*': './src/*.mjs'}}, 'sub'), 'src/sub.mjs'); - assert.throws(() => packageEntry({exports: {'.': './index.js'}}, 'private'), /does not export/); - assert.equal(packageEntry({exports: {browser: {import: './b.mjs'}, default: './c.js'}}, '', 'require'), 'c.js'); - assert.throws(() => normalize('../outside'), /escapes/); - assert.equal(packageEntry({exports: {'.': {import: './esm.js', require: './cjs.js'}}}, '', 'require'), 'cjs.js'); - let resolve; - virtualPlugin({packages: {}, roots: {}}, {}, async () => undefined).setup({onResolve: (_, cb) => { resolve = cb; }, onLoad() {}}); - await assert.rejects(resolve({path: 'node:fs', importer: 'entry.tsx', namespace: 'project', kind: 'import-statement'}), /Unsupported browser import/); -}); - -test('generated gzip words decode to the exact resources and generation is reproducible', () => { - const files = new Map([['index.html', encode('
PI
')], ['app.js', encode('console.log("π")')]]); - const header = generateProvider(files, 'PiUI', 'MIT */ preserved'); - assert.equal(header, generateProvider(new Map([...files].reverse()), 'PiUI', 'MIT */ preserved')); - const blocks = [...header.matchAll(/dataSize\{(\d+)\};\s+static constexpr[\s\S]*?data\{([\s\S]*?)\n \};/g)]; - assert.equal(blocks.length, 2); - for (const [index, match] of blocks.entries()) { - const hex = [...match[2].matchAll(/0x([a-f0-9]{16})ULL/g)].map(word => word[1]).join(''); - const compressed = Buffer.from(hex, 'hex').subarray(0, Number(match[1])); - assert.deepEqual(gunzipSync(compressed), Buffer.from([...files].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)[index][1])); - assert.deepEqual([...compressed.subarray(4, 8)], [0, 0, 0, 0]); - } - assert.throws(() => generateProvider(files, '../bad'), /provider name/); -}); - -test('environment integrity and protocol are checked before publication', async () => { - const archive = compress(tar(new Map([['package/environment.json', encode({protocol: 1, entry: 'runtime.mjs'})], ['package/runtime.mjs', encode('export function mount() {}')]]))); - const environment = await environmentFiles(archive, integrity(archive)); - assert.equal(environment.manifest.entry, 'runtime.mjs'); - await assert.rejects(environmentFiles(archive, integrity(encode('wrong'))), /Integrity check failed/); - const wrong = compress(tar(new Map([['package/environment.json', encode({protocol: 2, entry: 'runtime.mjs'})], ['package/runtime.mjs', encode('')]]))); - await assert.rejects(environmentFiles(wrong, integrity(wrong)), /Incompatible WebFront developer environment: protocol version 2, this application supports 1/); - // The API an environment expects must be one the C++ declares; an environment from before "api" reads as API 1. - const withApi = api => compress(tar(new Map([['package/environment.json', encode({protocol: 1, api, entry: 'runtime.mjs'})], ['package/runtime.mjs', encode('')]]))); - const newer = withApi(2); - await assert.rejects(environmentFiles(newer, integrity(newer)), /api version 2, this application supports 1/); - assert.equal((await environmentFiles(newer, integrity(newer), {protocol: [1], api: [1, 2]})).manifest.api, 2); - await assert.rejects(environmentFiles(archive, integrity(archive), {protocol: [1], api: [2]}), /api version 1, this application supports 2/); - const current = withApi(1); - assert.equal((await environmentFiles(current, integrity(current))).manifest.api, 1); - const missing = compress(tar(new Map([['package/runtime.mjs', encode('')]]))); - await assert.rejects(environmentFiles(missing, integrity(missing)), /no environment\.json/); -}); - -test('aborted publications never commit and clean their staging transaction', async () => { - const calls = []; - const bridge = {cppFunction: name => async (...args) => { calls.push([name, ...args]); return 'transaction'; }}; - const controller = new AbortController(); - controller.abort(new Error('Interrupted')); - await assert.rejects(publish(bridge, 'generated.hpp', new Map([['output', encode('header')]]), {directory: false, signal: controller.signal}), /Interrupted/); - assert.equal(calls.some(([name]) => name.endsWith('.commit')), false); - assert.equal(calls.at(-1)[0], 'webfront.developer.abort'); -}); - -test('checked-in browser bundles match their source and pinned dependency inputs', async () => { - const manifest = JSON.parse(await readFile(new URL('../environment/bundles.json', import.meta.url))); - for (const [path, hash] of Object.entries(manifest)) { - const actual = createHash('sha256').update(await readFile(new URL('../../../' + path, import.meta.url))).digest('hex'); - assert.equal(actual, hash, `${path} changed: run js/developer/tools/build.mjs --refresh-bootstrap`); - } -}); - -// An in-memory project behind the webfront.developer.* bridge callbacks. -function memoryBridge(storage) { - const transactions = new Map(); - let next = 0; - const operations = { - read: ([path, offset]) => { - const bytes = storage.get(path); - if (!bytes) throw new Error('Cannot read project file: ' + path); - return bytes.subarray(offset, offset + 256 * 1024); - }, - begin: ([destination, directory]) => { - const id = String(++next); - transactions.set(id, {destination, directory, files: new Map()}); - return id; - }, - write: ([id, path, offset, bytes]) => { - const files = transactions.get(id).files; - const previous = files.get(path) ?? new Uint8Array(); - assert.equal(previous.length, offset); - files.set(path, new Uint8Array([...previous, ...bytes])); - }, - commit: ([id]) => { - const {destination, directory, files} = transactions.get(id); - for (const [path, bytes] of files) storage.set(directory ? `${destination}/${path}` : destination, bytes); - transactions.delete(id); - }, - abort: ([id]) => { transactions.delete(id); }, - }; - return {cppFunction: name => async (...args) => operations[name.split('.').pop()](args)}; -} - -test('a pinned cached environment bootstraps offline and failed refreshes preserve publications', async () => { - globalThis.location = new URL('http://localhost:9002/webfront-bootstrap.html'); - const archive = compress(tar(new Map([['package/environment.json', encode({protocol: 1, entry: 'runtime.mjs'})], ['package/runtime.mjs', encode('export function mount() {}')]]))); - const storage = new Map([['.webfront/developer/environment.tgz', archive]]); - const bridge = memoryBridge(storage); - const config = {environment: 'https://offline.test/environment.tgz', integrity: integrity(archive)}; - const offline = async () => { throw new Error('Offline'); }; - const result = await bootstrap(bridge, config, offline); - assert.equal(result.url, '/webfront/developer/environment/runtime.mjs'); - assert.ok(storage.has('.webfront/developer/environment/runtime.mjs')); - const before = storage.get('.webfront/developer/environment/runtime.mjs'); - await assert.rejects(bootstrap(bridge, {...config, integrity: integrity(encode('different'))}, offline), /Offline/); - assert.equal(storage.get('.webfront/developer/environment/runtime.mjs'), before); - delete globalThis.location; -}); - -test('compressed downloads stop at their byte limit', async () => { - await assert.rejects(responseBytes(new Response(new Uint8Array(9)), 8), /byte limit/); -}); - -test('npm tarballs: package specs, integrity, bounded gunzip and tar entries', async () => { - assert.deepEqual(parseSpec('plot'), {name: 'plot', version: ''}); - assert.deepEqual(parseSpec('plot@1.2.0'), {name: 'plot', version: '1.2.0'}); - assert.deepEqual(parseSpec('@acme/plot'), {name: '@acme/plot', version: ''}); - assert.deepEqual(parseSpec('@acme/plot@next'), {name: '@acme/plot', version: 'next'}); - const files = new Map([['package/package.json', encode({name: 'plot'})], ['package/dist/index.js', encode('x')]]); - const archive = compress(tar(files)); - assert.equal(await verifyIntegrity(archive, `sha1-ignored ${integrity(archive)}`), integrity(archive)); - await assert.rejects(verifyIntegrity(archive, integrity(encode('other'))), /Integrity check failed/); - await assert.rejects(verifyIntegrity(archive, 'sha1-only'), /no SHA-512 integrity/); - const unpacked = await gunzip(archive); - assert.deepEqual(readTar(unpacked).map(entry => entry.path).sort(), [...files.keys()].sort()); - await assert.rejects(gunzip(archive, unpacked.length - 1), /unpacks to more than/); - assert.deepEqual(readTar(new Uint8Array(1024)), []); - const corrupt = unpacked.slice(); - corrupt[148] ^= 1; - assert.throws(() => readTar(corrupt), /Corrupt tar header/); -}); - -test('the terminal and webfront::Commands reserve the same command names', async () => { - const {reservedNames} = await import('../environment/commands.mjs'); - const header = await readFile(new URL('../../../include/webfront/Commands.hpp', import.meta.url), 'utf8'); - const declared = header.match(/reservedNames\{([^}]*)\}/); - assert.ok(declared, 'Commands.hpp must declare commands::reservedNames'); - assert.deepEqual([...declared[1].matchAll(/"([^"]*)"/g)].map(match => match[1]).sort(), [...reservedNames].sort()); -}); - -// A WebSocket the real bridge (js/core/WebFront.js) talks to: it records the frames sent, fires the on* handlers like a -// browser, and counts the listeners added with addEventListener. -class FakeWebSocket extends EventTarget { - static last = null; - constructor() { - super(); - this.sent = []; - this.listeners = 0; - FakeWebSocket.last = this; - } - send(data) { this.sent.push(new Uint8Array(data.buffer ?? data).slice()); } - addEventListener(...args) { ++this.listeners; super.addEventListener(...args); } - removeEventListener(...args) { --this.listeners; super.removeEventListener(...args); } - fire(type, init = {}) { - const event = Object.assign(new Event(type), init); - this[`on${type}`]?.(event); - this.dispatchEvent(event); - } -} - -// A bridge linked to the fake WebSocket, little-endian, and a helper answering a C++ call with a void return. -async function linkedBridge() { - const source = await readFile(new URL('../../core/WebFront.js', import.meta.url), 'utf8'); - const sandbox = {WebSocket: FakeWebSocket, location: {host: 'localhost'}, TextEncoder, TextDecoder, console}; - vm.runInNewContext(source, sandbox); - const bridge = sandbox.webFront, socket = FakeWebSocket.last; - socket.fire('open'); - socket.fire('message', {data: new Uint8Array([1, 0]).buffer}); // acknowledgement: little-endian - await bridge.ready; - const acknowledge = frame => socket.fire('message', {data: new Uint8Array([4, 0, frame[2], frame[3], 0, 0, 0, 0]).buffer}); - return {bridge, socket, acknowledge}; -} - -// The command number of a webfront.commands.start frame: the number after the function name. -const commandNumber = frame => { - const view = new DataView(frame.buffer); - return view.getFloat64(8 + 2 + view.getUint8(9) + 1, true); -}; - -const settled = promise => Promise.race([promise.then(() => 'resolved', () => 'rejected'), new Promise(resolve => setTimeout(() => resolve('pending'), 20))]); - -test('a C++ command whose start was acknowledged rejects when the connection closes, and unsubscribes', async () => { - const {runCommand} = await import('../environment/commands.mjs'); - const {bridge, socket, acknowledge} = await linkedBridge(); - const listenersBefore = socket.listeners; - const command = runCommand(bridge, 'wait', []); - command.catch(() => {}); - const start = socket.sent.at(-1); - acknowledge(start); - assert.equal(await settled(command), 'pending'); - assert.equal(socket.listeners, listenersBefore + 1); - socket.fire('close', {wasClean: false}); - await assert.rejects(command, error => error.exitCode === 1 && /connection to the application closed/.test(error.message)); - assert.equal(socket.listeners, listenersBefore); - // The exit report of the stopped command can no longer reach it; a late one is ignored. - globalThis.webfront.commands.exit(commandNumber(start), 130, ''); - await assert.rejects(runCommand(bridge, 'wait', []), /not connected/); - assert.equal(socket.listeners, listenersBefore); -}); - -test('a C++ command that exits, or is interrupted, removes its close listener', async () => { - const {runCommand} = await import('../environment/commands.mjs'); - const {bridge, socket, acknowledge} = await linkedBridge(); - const listenersBefore = socket.listeners; - const finished = runCommand(bridge, 'echo', ['x']); - const start = socket.sent.at(-1); - acknowledge(start); - globalThis.webfront.commands.exit(commandNumber(start), 0, ''); - assert.equal(await finished, ''); - assert.equal(socket.listeners, listenersBefore); - const controller = new AbortController(); - const interrupted = runCommand(bridge, 'wait', [], {signal: controller.signal}); - acknowledge(socket.sent.at(-1)); - controller.abort(); - await assert.rejects(interrupted, error => error.exitCode === 130); - assert.equal(socket.listeners, listenersBefore); - socket.fire('close', {wasClean: true, code: 1000, reason: ''}); -}); diff --git a/js/developer/tools/development-check.mjs b/js/developer/tools/development-check.mjs deleted file mode 100644 index a8a87158..00000000 --- a/js/developer/tools/development-check.mjs +++ /dev/null @@ -1,152 +0,0 @@ -// Host tests supplement the real-WASM browser regression in developer-specs.mjs. -import {test} from 'node:test'; -import assert from 'node:assert/strict'; -import {mkdtemp, writeFile, rm} from 'node:fs/promises'; -import {tmpdir} from 'node:os'; -import {join} from 'node:path'; -import {pathToFileURL} from 'node:url'; -import {build as bundle} from '../vendor/node_modules/esbuild/lib/main.js'; -import * as esbuild from '../vendor/node_modules/esbuild/lib/main.js'; -import {bundleContext} from '../environment/bundler.mjs'; -import {memoryBridge} from './memory-bridge.mjs'; - -// Resolve the browser module using the same locked dependencies as the environment archive. -const compiled = await bundle({entryPoints: ['js/developer/environment/development.mjs'], bundle: true, write: false, - format: 'esm', platform: 'browser', nodePaths: ['js/developer/vendor/node_modules']}); -const temporary = await mkdtemp(join(tmpdir(), 'webfront-development-test-')); -let api; -try { - const path = join(temporary, 'development.mjs'); - await writeFile(path, compiled.outputFiles[0].contents); - api = await import(pathToFileURL(path)); -} finally { await rm(temporary, {recursive: true, force: true}); } -const {observedRead, inputsChanged, compilerSession, waitForPoll, buildEntries, diagnosticsText, dev} = api; -const encode = text => new TextEncoder().encode(text); - -const lock = {format: 1, roots: {}, packages: {}}; -test('one esbuild context reads changed imports, reports syntax errors and recovers', async () => { - const files = new Map([['main.ts', encode("import {value} from './value'; console.log(value)")], ['value.ts', encode('export const value = 1')]]); - const context = await bundleContext(esbuild, {entry: 'main.ts', lock, readProject: async path => { - if (!files.has(path)) throw new Error('missing'); - return files.get(path); - }}); - try { - const text = async () => new TextDecoder().decode((await context.rebuild()).get('app.js')); - assert.match(await text(), /console.log\(1\)/); - files.set('value.ts', encode('export const value = 2')); - assert.match(await text(), /console.log\(2\)/); - files.set('value.ts', encode('export const value = ;')); - await assert.rejects(text(), error => diagnosticsText(error).includes('value.ts:1:')); - files.set('value.ts', encode('export const value = 3')); - assert.match(await text(), /console.log\(3\)/); - } finally { await context.dispose(); } -}); - -test('polling compares read-time bytes and missing probes and ignores unrelated writes', async () => { - const {bridge, storage: files} = memoryBridge(new Map([['ui/main.ts', encode('one')]])); - const observed = new Map(), budget = {bytes: 0}; - await observedRead(bridge, 'ui/main.ts', observed, budget); - await assert.rejects(observedRead(bridge, 'ui/new.ts', observed, budget), /Cannot read project file/); - assert.equal(await inputsChanged(bridge, observed), false); - files.set('unrelated.ts', encode('ignored')); - assert.equal(await inputsChanged(bridge, observed), false); - files.set('ui/main.ts', encode('two')); - assert.equal(await inputsChanged(bridge, observed), true); - await observedRead(bridge, 'ui/main.ts', observed, {bytes: 0}); - files.set('ui/new.ts', encode('created')); - assert.equal(await inputsChanged(bridge, observed), true); - await observedRead(bridge, 'ui/new.ts', observed, {bytes: 0}); - files.delete('ui/main.ts'); - assert.equal(await inputsChanged(bridge, observed), true, 'deletion is a change'); -}); - -test('a polling pass bounds bytes and paths, reports non-missing failures', async () => { - const {bridge} = memoryBridge(new Map([['main.ts', encode('file')]])); - await assert.rejects(observedRead(bridge, 'main.ts', new Map(), {bytes: 32 * 1024 * 1024}), /32 MiB/); - const paths = new Map(Array.from({length: 1024}, (_, n) => [`file-${n}`, 'missing'])); - await assert.rejects(observedRead(bridge, 'extra', paths, {bytes: 0}), /1024 input paths/); - const broken = {cppFunction: () => async () => { throw new Error('Connection closed'); }}; - await assert.rejects(inputsChanged(broken, new Map([['file', 'old']])), /Connection closed/); -}); - -test('Ctrl+C terminates an active compiler, rejects once, and drops late read answers', async () => { - let callback, terminated = 0; - const messages = []; - const worker = {postMessage: message => messages.push(message), terminate: () => ++terminated, - set onmessage(value) { callback = value; }}; - const controller = new AbortController(); - const session = compilerSession({cppFunction: () => () => new Promise(() => {})}, controller.signal, () => worker); - const pending = session.rebuild({entry: 'main.ts', lock}); - callback({data: {type: 'read', id: 1, path: 'main.ts'}}); - controller.abort(); - await assert.rejects(pending, error => error.exitCode === 130); - callback({data: {type: 'result', files: new Map()}}); - session.close(); - assert.equal(terminated, 1); - assert.equal(messages.length, 1); - await assert.rejects(session.rebuild({entry: 'main.ts', lock}), error => error.exitCode === 130); - await assert.rejects(waitForPoll(controller.signal), error => error.exitCode === 130); -}); - -test('a compiler session reuses its Worker and serializes rebuilds', async () => { - let callback; - const worker = {postMessage() {}, terminate() {}, set onmessage(value) { callback = value; }}; - const session = compilerSession({}, undefined, () => worker); - try { - const first = session.rebuild({entry: 'one', lock}); - await assert.rejects(session.rebuild({entry: 'two', lock}), /already running/); - callback({data: {type: 'result', files: new Map([['app.js', encode('one')]])}}); - assert.equal((await first).size, 1); - const second = session.rebuild({entry: 'two', lock}); - callback({data: {type: 'error', error: 'syntax', diagnostics: [{text: 'bad', location: {file: 'project:two.ts', line: 4, column: 2}}]}}); - await assert.rejects(second, error => diagnosticsText(error).startsWith('two.ts:4:3: bad')); - } finally { session.close(); } -}); - -test('build selects one explicit entry or every declared entry', () => { - assert.deepEqual(buildEntries({entries: {main: 'ui/main.ts'}}), [['', 'ui/main.ts']]); - assert.deepEqual(buildEntries({entries: {one: 'one.ts', two: 'two.ts'}}), [['one', 'one.ts'], ['two', 'two.ts']]); - assert.deepEqual(buildEntries({entries: {one: 'one.ts', two: 'two.ts'}}, 'two'), [['', 'two.ts']]); - assert.deepEqual(buildEntries({entries: {'app:one': 'one.ts', 'app..two': 'two.ts', CON: 'three.ts'}}), - [['app%3Aone', 'one.ts'], ['app%2E%2Etwo', 'two.ts'], ['%43ON', 'three.ts']]); - assert.throws(() => buildEntries(null), /Usage: wf build/); -}); - - -test('Ctrl+C during commit still displays the committed preview before stopping dev', async () => { - const project = memoryBridge(new Map([['webfront.project.json', encode(JSON.stringify({ - format: 1, name: 'commit-race', version: '0.1.0', entries: {main: 'main.ts'}, - }))]])); - const controller = new AbortController(); - const bridge = {cppFunction: name => async (...args) => { - const result = await project.bridge.cppFunction(name)(...args); - // The native commit has completed, but its acknowledgement has not reached dev yet. - if (name === 'webfront.developer.commit') controller.abort(); - return result; - }}; - let terminated = 0; - const previousWorker = globalThis.Worker; - globalThis.Worker = class { - postMessage(message) { - if (message.type === 'build') queueMicrotask(() => this.onmessage({data: { - type: 'result', files: new Map([['app.js', encode('console.log("committed")')]]), - }})); - } - terminate() { ++terminated; } - }; - const navigations = []; - const frame = {hidden: true, contentDocument: null, contentWindow: {location: {replace: url => navigations.push(url)}}, - addEventListener() {}, removeEventListener() {}}; - try { - await assert.rejects(dev([], {bridge, signal: controller.signal, preview: frame}), error => error.exitCode === 130); - assert.deepEqual(project.storage.get('.webfront/developer/preview/app.js'), encode('console.log("committed")')); - assert.equal(navigations.length, 1, 'a completed publication must be displayed even when Ctrl+C arrived during commit'); - assert.match(navigations[0], /^\/webfront\/developer\/preview\/index.html\?build=/); - assert.equal(frame.hidden, false); - assert.equal(project.pending(), 0); - assert.equal(terminated, 1); - } finally { - if (previousWorker === undefined) delete globalThis.Worker; - else globalThis.Worker = previousWorker; - } -}); diff --git a/js/developer/tools/distribution-check.mjs b/js/developer/tools/distribution-check.mjs deleted file mode 100644 index 52f24f9b..00000000 --- a/js/developer/tools/distribution-check.mjs +++ /dev/null @@ -1,124 +0,0 @@ -import {test} from 'node:test'; -import assert from 'node:assert/strict'; -import {readFile, writeFile, mkdir, mkdtemp, rm} from 'node:fs/promises'; -import {tmpdir} from 'node:os'; -import {join} from 'node:path'; -import {createHash} from 'node:crypto'; -import {tar} from './archive.mjs'; -import {stageSite, bootstrapHeader, versionPath, distributionFiles} from './site.mjs'; -import {compress} from '../environment/embed.mjs'; -import {createStarter} from '../environment/starter.mjs'; -const encode = value => new TextEncoder().encode(typeof value === 'string' ? value : JSON.stringify(value)); -const integrity = bytes => 'sha512-' + createHash('sha512').update(bytes).digest('base64'); - -const recipe = (fields = {}) => ({format: 1, name: 'pi-starter', version: '0.1.0', dependencies: {react: '19.3.1'}, - entries: {main: 'main.tsx'}, ...fields}); - -function starter(overrides = {}) { - return compress(tar(new Map(Object.entries({ - 'package/main.tsx': encode('export default function Pi() {}'), - 'package/webfront.project.json': encode(recipe()), - ...overrides, - })))); -} - -test('starter integrity, recipes and archive paths are checked before any project writes', async () => { - globalThis.location = new URL('http://localhost:9002/'); - const bytes = starter(); - const calls = []; - const bridge = {cppFunction: name => async (...args) => { calls.push([name, ...args]); return 'transaction'; }}; - const config = {starters: {pi: {url: 'https://pages.test/developer/0.1.0/pi-starter.tgz', integrity: integrity(bytes)}}}; - const fetchImpl = async () => new Response(bytes); - const help = await createStarter(bridge, config, ['pi', 'ui'], {fetchImpl}); - assert.match(help, /wf init\nwf install react@19.3.1/); - assert.match(help, /wf preview ui\/main.tsx/); - assert.equal(calls[0][0], 'webfront.developer.beginNew'); - assert.equal(calls.at(-1)[0], 'webfront.developer.commit'); - calls.length = 0; - await assert.rejects(createStarter(bridge, {starters: {pi: {...config.starters.pi, integrity: integrity(encode('bad'))}}}, ['pi', 'ui'], {fetchImpl}), /Integrity check/); - assert.equal(calls.length, 0); - for (const bytes of [starter({'package/../escape': encode('bad')}), starter({'package/webfront.project.json': encode(recipe({dependencies: {react: 'latest'}}))})]) { - await assert.rejects(createStarter(bridge, {starters: {pi: {...config.starters.pi, integrity: integrity(bytes)}}}, ['pi', 'ui'], {fetchImpl: async () => new Response(bytes)})); - assert.equal(calls.length, 0); - } - delete globalThis.location; -}); - -test('starter replacement refusal aborts the publication rather than overwriting files', async () => { - globalThis.location = new URL('http://localhost:9002/'); - const bytes = starter(); - const calls = []; - const bridge = {cppFunction: name => async () => { - calls.push(name); - if (name.endsWith('.commit')) throw new Error('Starter destination already exists'); - return 'transaction'; - }}; - await assert.rejects(createStarter(bridge, {starters: {pi: {url: '/starter.tgz', integrity: integrity(bytes)}}}, ['pi', 'ui'], {fetchImpl: async () => new Response(bytes)}), /already exists/); - assert.equal(calls.at(-1), 'webfront.developer.abort'); - delete globalThis.location; -}); - -test('Pages staging retains older versions and refuses different bytes under an existing version', async () => { - const root = await mkdtemp(join(tmpdir(), 'webfront-distribution-')); - try { - const distribution = join(root, 'distribution'); - const site = join(root, 'site'); - await mkdir(distribution); - const environment = encode('environment'); - const pi = encode('starter'); - const write = async version => { - const manifest = {version, integrity: integrity(environment), starters: {pi: {archive: 'pi-starter.tgz', integrity: integrity(pi)}, ...(version !== '0.1.0' ? {life: {archive: 'life-starter.tgz', integrity: integrity(pi)}} : {})}}; - await writeFile(join(distribution, 'environment.tgz'), environment); - await writeFile(join(distribution, 'pi-starter.tgz'), pi); - if (version !== '0.1.0') await writeFile(join(distribution, 'life-starter.tgz'), pi); - await writeFile(join(distribution, 'provision.json'), JSON.stringify(manifest)); - await writeFile(join(distribution, 'DeveloperReleaseData.hpp'), bootstrapHeader(version, 'https://owner.github.io/WebFront/', manifest.integrity)); - }; - await write('0.1.0'); - await stageSite(distribution, site); - await stageSite(distribution, site); - await write('0.2.0'); - await stageSite(distribution, site); - assert.equal(await readFile(join(site, 'developer/0.1.0/environment.tgz'), 'utf8'), 'environment'); - assert.match(await readFile(join(site, 'index.html'), 'utf8'), /developer\/0.2.0\/life-starter.tgz/); - assert.equal(await readFile(join(site, 'developer/0.2.0/life-starter.tgz'), 'utf8'), 'starter'); - await write('0.3.0'); - await writeFile(join(distribution, 'life-starter.tgz'), 'packed-starter'); - const manifest = JSON.parse(await readFile(join(distribution, 'provision.json'))); - manifest.starters.life.integrity = integrity(encode('packed-starter')); - await writeFile(join(distribution, 'provision.json'), JSON.stringify(manifest)); - await stageSite(distribution, site); - assert.equal(await readFile(join(site, 'developer/0.1.0/environment.tgz'), 'utf8'), 'environment'); - assert.equal(await readFile(join(site, 'developer/0.2.0/life-starter.tgz'), 'utf8'), 'starter'); - assert.equal(await readFile(join(site, 'developer/0.3.0/life-starter.tgz'), 'utf8'), 'packed-starter'); - await writeFile(join(distribution, 'DeveloperReleaseData.hpp'), 'changed'); - await assert.rejects(stageSite(distribution, site), /increment the distribution version/); - assert.match(await readFile(join(site, 'developer/0.2.0/DeveloperReleaseData.hpp'), 'utf8'), /namespace webfront/); - await writeFile(join(distribution, 'environment.tgz'), 'corrupt'); - await assert.rejects(stageSite(distribution, site), /checksum mismatch/); - } finally { await rm(root, {recursive: true, force: true}); } -}); - -test('bootstrap configuration is pinned and rejects unsafe version/base inputs', () => { - const header = bootstrapHeader('0.1.0', 'https://owner.github.io/WebFront/', integrity(encode('environment'))); - assert.match(header, /https:\/\/owner.github.io\/WebFront\/developer\/0.1.0\/environment.tgz/); - assert.doesNotMatch(header, /latest/); - assert.throws(() => versionPath('../evil')); - assert.throws(() => bootstrapHeader('0.1.0', 'http://owner.test/', integrity(encode('environment')))); -}); - -test('Life recipes select their generated provider and reject invalid provider names', async () => { - globalThis.location = new URL('http://localhost:9002/'); - try { - for (const provider of ['LifeUI', '../escape']) { - const bytes = starter({'package/webfront.project.json': encode(recipe({providers: {[provider]: {entry: 'main', output: `generated/${provider}.hpp`}}}))}); - let writes = 0; - const bridge = {cppFunction: () => async () => { writes++; return 'transaction'; }}; - const config = {starters: {life: {url: '/life-starter.tgz', integrity: integrity(bytes)}}}; - const create = () => createStarter(bridge, config, ['life', 'ui'], {fetchImpl: async () => new Response(bytes)}); - if (provider === 'LifeUI') assert.match(await create(), /generated\/LifeUI.hpp/); - else { await assert.rejects(create(), /provider name/); assert.equal(writes, 0); } - } - assert.throws(() => distributionFiles({starters: {life: {archive: '../life-starter.tgz'}}})); - } finally { delete globalThis.location; } -}); diff --git a/js/developer/tools/distribution.mjs b/js/developer/tools/distribution.mjs index b792bc4d..716bfa81 100644 --- a/js/developer/tools/distribution.mjs +++ b/js/developer/tools/distribution.mjs @@ -26,7 +26,7 @@ export function bootstrapHeader(version, base, integrity) { const url = new URL(versionPath(version) + 'environment.tgz', baseUrl(base)); return `#pragma once -// Pinned developer distribution. Regenerate with js/developer/tools/build.mjs --refresh-bootstrap. +// Pinned developer distribution. Regenerate with wf run build --refresh-bootstrap. #include namespace webfront::developer::release { diff --git a/js/developer/tools/fixtures.mjs b/js/developer/tools/fixtures.mjs deleted file mode 100644 index 16373d00..00000000 --- a/js/developer/tools/fixtures.mjs +++ /dev/null @@ -1,18 +0,0 @@ -// Configure offline browser fixtures from the maintainer's pinned npm ci installation. -import {mkdir, copyFile} from 'node:fs/promises'; -import {resolve} from 'node:path'; -import {fileURLToPath} from 'node:url'; -import {pinnedPackages, syntheticPackages} from './registry-fixture.mjs'; -import {installedPackage, writeRegistry} from './registry-fixture-node.mjs'; -const root = fileURLToPath(new URL('../../../', import.meta.url)); -const output = resolve(process.argv[2] ?? 'build-developer-environment'); -await mkdir(output, {recursive: true}); -const nodeModules = resolve(root, 'js/developer/vendor/node_modules'); -const pinned = await Promise.all(pinnedPackages.map(name => installedPackage(nodeModules, name))); -await writeRegistry(resolve(output, 'registry'), [...pinned, ...syntheticPackages()]); -await copyFile(resolve(root, 'test/web/developer-specs.mjs'), resolve(output, 'run.mjs')); -await copyFile(resolve(root, 'test/web/developer-session.html'), resolve(output, 'session.html')); -await copyFile(resolve(root, 'test/web/developer-session.mjs'), resolve(output, 'session.mjs')); -await copyFile(resolve(root, 'js/developer/tools/starters/pi/main.tsx'), resolve(output, 'main.tsx')); -await copyFile(resolve(root, 'js/developer/tools/starters/pi/style.css'), resolve(output, 'style.css')); -console.log(`Offline developer fixtures: ${output}`); diff --git a/js/developer/tools/manifest-check.mjs b/js/developer/tools/manifest-check.mjs deleted file mode 100644 index a7d59424..00000000 --- a/js/developer/tools/manifest-check.mjs +++ /dev/null @@ -1,297 +0,0 @@ -// Node tests of the project manifest, its agreement with the lock and the joint publication of both. -import {test} from 'node:test'; -import assert from 'node:assert/strict'; -import {createHash} from 'node:crypto'; -import {validateManifest, parseManifest, serializeManifest, manifestName, dependenciesDigest} from '../environment/manifest.mjs'; -import {install, initProject, loadProject, syncNotice, resolveEntry, embedTarget, lockPath, manifestPath} from '../environment/packages.bundle.mjs'; -import {compress} from '../environment/embed.mjs'; -import {tar} from './archive.mjs'; -import {memoryBridge} from './memory-bridge.mjs'; - -const encoder = new TextEncoder(); -const decoder = new TextDecoder(); -const encode = value => encoder.encode(typeof value === 'string' ? value : JSON.stringify(value)); -const integrity = bytes => 'sha512-' + createHash('sha512').update(bytes).digest('base64'); -const minimal = {format: 1, name: 'app', version: '0.1.0'}; - -test('a valid manifest receives its defaults and keeps a stable serialization', () => { - const manifest = validateManifest(minimal); - assert.deepEqual(manifest.dependencies, {}); - assert.deepEqual(manifest.entries, {}); - const full = {...minimal, dependencies: {react: '^19.0.0', '@scope/lib': '>=1.2.0 <2', tool: 'latest'}, registry: 'https://registry.test/', - scripts: {build: 'wf embed main'}, entries: {main: 'ui/main.tsx'}, - providers: {PiUI: {entry: 'main', output: 'generated/PiUI.hpp'}}, test: {specs: ['spec/a.mjs']}, - permissions: {files: ['ui'], publish: ['generated'], fetch: ['https://registry.npmjs.org']}}; - const text = serializeManifest(validateManifest(full)); - assert.deepEqual(JSON.parse(text), full); - assert.equal(serializeManifest(parseManifest(encode(text))), text); - assert.equal(manifestName('apps/My App'), 'my-app'); - assert.equal(manifestName(''), 'webfront-app'); -}); - -test('invalid manifests are explicit errors, never silent fallbacks', () => { - const cases = [ - [{...minimal, extra: 1}, /unknown key "extra"/], - [{name: 'app', version: '1.0.0'}, /format must be 1/], - [{...minimal, format: 2}, /format 2 is not supported/], - [{...minimal, name: 'Bad Name'}, /name must be/], - [{...minimal, version: 'one'}, /version must be/], - [{...minimal, dependencies: {react: 3}}, /invalid version range/], - [{...minimal, dependencies: {'../x': '1.0.0'}}, /invalid npm package name/], - [{...minimal, dependencies: {react: 'file:../react'}}, /invalid version range/], - [{...minimal, registry: 'http://insecure.test/'}, /registry must use https/], - [{...minimal, registry: '/\\registry.test/'}, /registry must be an https URL or an absolute path/], - [{...minimal, entries: {main: '../outside.tsx'}}, /safe project-relative path/], - [{...minimal, entries: {main: '/etc/passwd'}}, /safe project-relative path/], - [{...minimal, providers: {'not valid': {entry: 'a.tsx', output: 'a.hpp'}}}, /invalid provider name/], - [{...minimal, providers: {P: {entry: 'a.tsx', output: 'a.js'}}}, /\.hpp file/], - [{...minimal, providers: {P: {entry: 'a.tsx', output: 'a.hpp', more: 1}}}, /unknown key "more"/], - [{...minimal, test: {specs: ['../spec.mjs']}}, /safe project-relative path/], - [{...minimal, test: {runner: 'x'}}, /unknown key "runner"/], - [{...minimal, permissions: {shell: true}}, /unknown permission "shell"/], - [{...minimal, permissions: {files: ['a/../../b']}}, /safe project-relative path/], - [{...minimal, permissions: {fetch: ['http://plain.test']}}, /https origin/], - [{...minimal, permissions: {fetch: ['https://registry.test/path']}}, /without a path/], - [[], /must be an object/], - ]; - for (const [value, message] of cases) assert.throws(() => validateManifest(value), message); - assert.throws(() => parseManifest(encode('{')), /not valid JSON/); -}); - -test('the dependency digest ignores key order and changes with any range', async () => { - const first = await dependenciesDigest({a: '^1.0.0', b: '2.0.0'}); - assert.equal(first, await dependenciesDigest({b: '2.0.0', a: '^1.0.0'})); - assert.notEqual(first, await dependenciesDigest({a: '^1.0.0', b: '^2.0.0'})); - assert.match(first, /^[0-9a-f]{64}$/); -}); - -test('entries are named in the manifest or given as paths', () => { - const manifest = validateManifest({...minimal, entries: {main: 'ui/main.tsx', other: 'ui/other.tsx'}}); - assert.equal(resolveEntry(manifest, undefined, 'wf preview'), 'ui/main.tsx'); - assert.equal(resolveEntry(manifest, 'other', 'wf preview'), 'ui/other.tsx'); - assert.equal(resolveEntry(manifest, 'free/path.tsx', 'wf preview'), 'free/path.tsx'); - assert.throws(() => resolveEntry(validateManifest(minimal), undefined, 'wf preview'), /entries.main/); -}); - -test('wf embed names the generated class after the provider, and refuses a file name that is not a C++ name', () => { - const manifest = validateManifest({...minimal, entries: {main: 'ui/main.tsx'}, providers: {PiUI: {entry: 'main', output: 'generated/pi-ui.hpp'}}}); - assert.deepEqual(embedTarget(manifest, ['PiUI']), {entry: 'ui/main.tsx', output: 'generated/pi-ui.hpp', className: 'PiUI'}); - assert.equal(embedTarget(manifest, ['ui/main.tsx', '--output', 'generated/LifeUI.hpp']).className, 'LifeUI'); - assert.throws(() => embedTarget(manifest, ['ui/main.tsx', '--output', 'generated/life-ui.hpp']), /not a C\+\+ class name/); - assert.throws(() => embedTarget(manifest, ['ui/main.tsx']), /--output/); -}); - -const tagged = (packages, tags) => async url => { - const response = await packages(url); - const body = response.headers.get('content-type')?.includes('json') ? await response.json() : null; - if (!body) return response; - return Response.json({...body, 'dist-tags': {...body['dist-tags'], ...tags}}); -}; -const pkg = (name, version, fields = {}) => compress(tar(new Map([['package/package.json', encode({name, version, ...fields})]]))); -function registry(packages) { - const requests = []; - const fetchImpl = async url => { - requests.push(String(url)); - const path = new URL(url).pathname.slice(1); - if (path.endsWith('.tgz')) { - const [name, version] = path.slice(0, -4).split('@'); - const entry = packages[name]; - return new Response(entry.older?.[version] ?? entry.bytes); - } - const entry = packages[path]; - if (!entry) return new Response('', {status: 404}); - const versions = {[entry.version]: entry.bytes, ...entry.older}; - const described = Object.fromEntries(Object.entries(versions).map(([version, bytes]) => - [version, {dist: {tarball: `https://registry.test/${path}@${version}.tgz`, integrity: integrity(bytes)}}])); - return Response.json({'dist-tags': {latest: entry.version}, versions: described}); - }; - return {fetchImpl, requests}; -} -const source = () => ({ - a: {version: '1.2.0', bytes: pkg('a', '1.2.0')}, - b: {version: '2.0.0', bytes: pkg('b', '2.0.0')}, - c: {version: '3.1.0', bytes: pkg('c', '3.1.0')}, -}); -const options = fetchImpl => ({registry: 'https://registry.test/', fetchImpl}); -const json = (storage, path) => JSON.parse(decoder.decode(storage.get(path))); - -async function project(...files) { - const memory = memoryBridge(); - await initProject(memory.bridge, [], {}); - for (const spec of files) await install(memory.bridge, [spec], options(registry(source()).fetchImpl)); - return memory; -} - -test('wf init creates the root manifest every command reads, and never replaces it', async () => { - const {bridge, storage} = memoryBridge(); - assert.match(await initProject(bridge, [], {}), /Created webfront.project.json/); - assert.deepEqual(json(storage, manifestPath), {format: 1, name: 'webfront-app', version: '0.1.0', dependencies: {}}); - assert.equal((await loadProject(bridge)).status, 'unlocked'); - await assert.rejects(initProject(bridge, [], {}), /already exists/); - await assert.rejects(initProject(bridge, ['a', 'b'], {}), /Usage/); - const named = memoryBridge(); - await initProject(named.bridge, ['my-app'], {}); - assert.equal(json(named.storage, manifestPath).name, 'my-app'); - await assert.rejects(initProject(memoryBridge().bridge, ['Bad Name'], {}), /name must be/); -}); - -test('a project locked before the manifest keeps its locked graph through wf init and wf install', async () => { - const {bridge, storage, pending} = await project('a', 'b@2.0.0', 'c@^3'); - const lock = json(storage, lockPath); - delete lock.manifestDigest; - storage.set(lockPath, encode(lock)); - storage.delete(manifestPath); - assert.match(await initProject(bridge, [], {}), /with the 3 dependencies of webfront-packages.lock.json/); - assert.deepEqual(json(storage, manifestPath).dependencies, {a: '^1.2.0', b: '^2.0.0', c: '^3'}); - assert.equal((await loadProject(bridge)).status, 'legacy'); - assert.equal(syncNotice(await loadProject(bridge)), ''); - // A newer a is published: wf install keeps the locked version and only records the digest. - const newer = {...source(), a: {version: '1.3.0', bytes: pkg('a', '1.3.0'), older: {'1.2.0': pkg('a', '1.2.0')}}}; - await install(bridge, [], options(registry(newer).fetchImpl)); - const adopted = json(storage, lockPath); - assert.deepEqual(Object.keys(adopted.packages).sort(), ['a@1.2.0', 'b@2.0.0', 'c@3.1.0']); - assert.equal(adopted.manifestDigest, await dependenciesDigest({a: '^1.2.0', b: '^2.0.0', c: '^3'})); - assert.equal((await loadProject(bridge)).status, 'consistent'); - assert.equal(pending(), 0); -}); - -test('a legacy lock also stays usable for wf install , and one that does not match is desynchronized', async () => { - const {bridge, storage} = await project('a'); - const lock = json(storage, lockPath); - delete lock.manifestDigest; - storage.set(lockPath, encode(lock)); - const newer = {...source(), a: {version: '1.3.0', bytes: pkg('a', '1.3.0'), older: {'1.2.0': pkg('a', '1.2.0')}}}; - await install(bridge, ['b'], options(registry(newer).fetchImpl)); - assert.deepEqual(Object.keys(json(storage, lockPath).packages).sort(), ['a@1.2.0', 'b@2.0.0']); - assert.equal((await loadProject(bridge)).status, 'consistent'); - const stale = json(storage, lockPath); - delete stale.manifestDigest; - storage.set(lockPath, encode(stale)); - storage.set(manifestPath, encode({...minimal, dependencies: {a: '^2.0.0', b: '^2.0.0'}})); - assert.equal((await loadProject(bridge)).status, 'desynchronized'); -}); - -test('wf install refuses a range the manifest cannot hold before resolving, and writes only what the user wrote', async () => { - const {bridge, storage} = await project(); - const {fetchImpl, requests} = registry(source()); - const before = storage.get(manifestPath); - for (const spec of ['a@next_v2', `a@${'1'.repeat(129)}`]) await assert.rejects(install(bridge, [spec], options(fetchImpl)), /invalid version range/); - assert.equal(requests.length, 0); - assert.equal(storage.get(manifestPath), before); - await install(bridge, ['a@'], options(fetchImpl)); - assert.deepEqual(json(storage, manifestPath), {format: 1, name: 'webfront-app', version: '0.1.0', dependencies: {a: '^1.2.0'}}); - assert.deepEqual((await loadProject(bridge)).manifest.entries, {}, 'the defaults are still applied when reading'); -}); - -test('wf install needs a manifest, then publishes manifest and lock together', async () => { - const {bridge, storage} = memoryBridge(); - const {fetchImpl} = registry(source()); - await assert.rejects(install(bridge, ['a'], options(fetchImpl)), /run wf init/); - await initProject(bridge, [], {}); - assert.equal((await loadProject(bridge)).status, 'unlocked'); - await install(bridge, ['a'], options(fetchImpl)); - const afterFirst = await loadProject(bridge); - assert.equal(afterFirst.status, 'consistent'); - assert.deepEqual(afterFirst.manifest.dependencies, {a: '^1.2.0'}); - assert.equal(afterFirst.lock.manifestDigest, await dependenciesDigest({a: '^1.2.0'})); - await install(bridge, ['b@2.0.0', 'c@^3'], options(fetchImpl)); - assert.deepEqual(json(storage, manifestPath).dependencies, {a: '^1.2.0', b: '2.0.0', c: '^3'}); - assert.deepEqual(Object.keys(json(storage, lockPath).roots), ['a', 'b', 'c']); - assert.equal((await loadProject(bridge)).status, 'consistent'); -}); - -test('the three states of manifest and lock for install, install and install --update', async () => { - const {bridge, storage, pending} = await project('a'); - const {fetchImpl, requests} = registry(source()); - // consistent: install restores the locked graph, resolving and writing nothing. - const manifestBefore = storage.get(manifestPath); - const lockBefore = storage.get(lockPath); - const cache = [...storage.keys()].filter(key => key.startsWith('.webfront/developer/packages/')); - cache.forEach(key => storage.delete(key)); - const restored = await install(bridge, [], options(fetchImpl)); - assert.equal(restored.restored, 1); - assert.ok(cache.every(key => storage.has(key))); - assert.equal(storage.get(manifestPath), manifestBefore); - assert.equal(storage.get(lockPath), lockBefore); - assert.equal(requests.filter(url => !url.endsWith('.tgz')).length, 1, 'only the locked package is fetched, not a new resolution'); - // no lock: install resolves the manifest and creates the lock, leaving the manifest alone. - storage.delete(lockPath); - assert.equal((await loadProject(bridge)).status, 'unlocked'); - await install(bridge, [], options(fetchImpl)); - assert.equal((await loadProject(bridge)).status, 'consistent'); - assert.deepEqual(storage.get(manifestPath), manifestBefore); - // desynchronized: every command says so and nothing is resolved implicitly. - const edited = json(storage, manifestPath); - edited.dependencies.b = '2.0.0'; - storage.set(manifestPath, encode(serializeManifest(edited))); - const stale = await loadProject(bridge); - assert.equal(stale.status, 'desynchronized'); - assert.match(syncNotice(stale), /wf install --update/); - const lockStale = storage.get(lockPath); - requests.length = 0; - await assert.rejects(install(bridge, [], options(fetchImpl)), /wf install --update/); - await assert.rejects(install(bridge, ['c'], options(fetchImpl)), /wf install --update/); - assert.equal(requests.length, 0); - assert.equal(storage.get(lockPath), lockStale); - await install(bridge, ['--update'], options(fetchImpl)); - assert.equal((await loadProject(bridge)).status, 'consistent'); - assert.deepEqual(Object.keys(json(storage, lockPath).roots), ['a', 'b']); - assert.equal(pending(), 0); -}); - -test('a changed archive is refused when restoring a locked graph', async () => { - const {bridge, storage} = await project('a'); - [...storage.keys()].filter(key => key.startsWith('.webfront/developer/packages/')).forEach(key => storage.delete(key)); - const tampered = {a: {version: '1.2.0', bytes: pkg('a', '1.2.0', {description: 'changed'})}}; - await assert.rejects(install(bridge, [], options(registry(tampered).fetchImpl)), /Integrity check|integrity/); -}); - -test('two installations that read the same state cannot overwrite each other', async () => { - const {bridge, storage, pending} = await project(); - const {fetchImpl} = registry(source()); - const results = await Promise.allSettled([install(bridge, ['a'], options(fetchImpl)), install(bridge, ['b'], options(fetchImpl))]); - const refused = results.filter(result => result.status === 'rejected'); - assert.equal(refused.length, 1, 'exactly one publication is refused by the precondition'); - assert.match(refused[0].reason.message, /changed since it was read; run the command again/); - assert.equal(pending(), 0, 'the refused installation leaves no staged transaction'); - assert.equal((await loadProject(bridge)).status, 'consistent'); - const winner = Object.keys(json(storage, manifestPath).dependencies); - assert.equal(winner.length, 1); - await install(bridge, [winner[0] === 'a' ? 'b' : 'a'], options(fetchImpl)); - assert.deepEqual(Object.keys(json(storage, manifestPath).dependencies).sort(), ['a', 'b']); - assert.deepEqual(Object.keys(json(storage, lockPath).roots).sort(), ['a', 'b']); - assert.equal((await loadProject(bridge)).status, 'consistent'); -}); - -test('an invalid manifest is reported before anything is resolved', async () => { - const {bridge, storage} = await project('a'); - storage.set(manifestPath, encode({...minimal, format: 3})); - await assert.rejects(loadProject(bridge), /format 3 is not supported/); - storage.set(manifestPath, encode({...minimal, permissions: {network: true}})); - await assert.rejects(install(bridge, [], options(registry(source()).fetchImpl)), /unknown permission/); -}); - -test('wf install --update takes the newest version within the ranges while installing a package keeps the others', async () => { - const {bridge, storage} = await project('a'); - assert.equal(json(storage, lockPath).packages['a@1.2.0'].version, '1.2.0'); - const newer = {...source(), a: {version: '1.3.0', bytes: pkg('a', '1.3.0'), older: {'1.2.0': pkg('a', '1.2.0')}}}; - await install(bridge, ['b'], options(registry(newer).fetchImpl)); - assert.ok(json(storage, lockPath).packages['a@1.2.0'], 'installing another package leaves a at its locked version'); - assert.equal(json(storage, lockPath).packages['a@1.3.0'], undefined); - await install(bridge, ['--update'], options(registry(newer).fetchImpl)); - assert.deepEqual(Object.keys(json(storage, lockPath).packages).sort(), ['a@1.3.0', 'b@2.0.0']); - assert.deepEqual(json(storage, manifestPath).dependencies, {a: '^1.2.0', b: '^2.0.0'}); - assert.equal((await loadProject(bridge)).status, 'consistent'); -}); - -test('a package installed by dist-tag keeps its version when another package is installed', async () => { - const {bridge, storage} = await project(); - const old = {...source(), a: {version: '1.2.0', bytes: pkg('a', '1.2.0'), older: {'1.3.0': pkg('a', '1.3.0')}}}; - const beta = tags => options(tagged(registry(old).fetchImpl, tags)); - await install(bridge, ['a@beta'], beta({beta: '1.2.0'})); - assert.deepEqual(json(storage, manifestPath).dependencies, {a: 'beta'}); - await install(bridge, ['b'], beta({beta: '1.3.0'})); - assert.deepEqual(Object.keys(json(storage, lockPath).packages).sort(), ['a@1.2.0', 'b@2.0.0'], 'the tag moved but the lock did not'); - await install(bridge, ['--update'], beta({beta: '1.3.0'})); - assert.deepEqual(Object.keys(json(storage, lockPath).packages).sort(), ['a@1.3.0', 'b@2.0.0']); -}); diff --git a/js/developer/tools/pages.mjs b/js/developer/tools/pages.mjs deleted file mode 100644 index bbdf2b93..00000000 --- a/js/developer/tools/pages.mjs +++ /dev/null @@ -1,10 +0,0 @@ -// A token-driven branch push does not trigger Pages automatically: request the build explicitly. -// With --check, only verify the configured Pages source (before anything is pushed to gh-pages). -import {execFileSync} from 'node:child_process'; -const repository = process.env.GITHUB_REPOSITORY; -if (!/^[\w.-]+\/[\w.-]+$/.test(repository ?? '')) throw new Error('GITHUB_REPOSITORY is required'); -const api = (...args) => execFileSync('gh', ['api', ...args], {encoding: 'utf8'}); -const configuration = JSON.parse(api(`repos/${repository}/pages`)); -if (configuration.build_type !== 'legacy' || configuration.source?.branch !== 'gh-pages' || configuration.source?.path !== '/') - throw new Error('Configure GitHub Pages to build from gh-pages / before publishing; an existing site is never reconfigured automatically'); -if (!process.argv.includes('--check')) console.log(api('--method', 'POST', `repos/${repository}/pages/builds`)); diff --git a/js/developer/tools/pin-check.mjs b/js/developer/tools/pin-check.mjs deleted file mode 100644 index 581d692a..00000000 --- a/js/developer/tools/pin-check.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Checks DeveloperReleaseData.hpp against the published distribution it pins, for sources that build a newer version: -// the header must be exactly the one generated for its version, and the archive at its URL must have its integrity. -import {readFile} from 'node:fs/promises'; -import {createHash} from 'node:crypto'; -import {bootstrapHeader} from './site.mjs'; - -const root = new URL('../../../', import.meta.url); -const header = await readFile(new URL('include/webfront/system/DeveloperReleaseData.hpp', root), 'utf8'); -const distribution = JSON.parse(await readFile(new URL('js/developer/tools/distribution.json', root))); -const field = name => header.match(new RegExp(`\\b${name}\\{"([^"]*)"\\}`))?.[1] ?? ''; -const version = field('version'); -const integrity = field('integrity'); -if (header !== bootstrapHeader(version, distribution.baseUrl, integrity)) - throw new Error(`DeveloperReleaseData.hpp is not the header generated for the published ${version}`); -const url = field('environment'); -const response = await fetch(url); -if (!response.ok) throw new Error(`The pinned environment ${url} is not published (${response.status})`); -const actual = 'sha512-' + createHash('sha512').update(new Uint8Array(await response.arrayBuffer())).digest('base64'); -if (actual !== integrity) throw new Error(`The published ${url} does not have the pinned integrity`); -console.log(`DeveloperReleaseData.hpp pins the published ${version}.`); diff --git a/js/developer/tools/registry-fixture-node.mjs b/js/developer/tools/registry-fixture-node.mjs deleted file mode 100644 index ec58f161..00000000 --- a/js/developer/tools/registry-fixture-node.mjs +++ /dev/null @@ -1,31 +0,0 @@ -// Node-only part of the registry fixture: packages read from an npm ci installation, files written to a directory. -import {readFile, writeFile, mkdir, readdir} from 'node:fs/promises'; -import {resolve, dirname} from 'node:path'; -import {registryFiles} from './registry-fixture.mjs'; - -async function collect(directory, files, path = '') { - const entries = await readdir(resolve(directory, path), {withFileTypes: true}); - for (const entry of entries) { - const relative = path ? `${path}/${entry.name}` : entry.name; - if (entry.isDirectory() && entry.name !== 'node_modules') await collect(directory, files, relative); - else if (entry.isFile()) files.set(relative, await readFile(resolve(directory, relative))); - } - return files; -} - -/** A package installed by npm ci, as the files of its archive. */ -export async function installedPackage(nodeModules, name) { - const directory = resolve(nodeModules, name); - return {manifest: JSON.parse(await readFile(resolve(directory, 'package.json'), 'utf8')), files: await collect(directory, new Map())}; -} - -/** Writes the registry's files into `directory`; returns each package's integrity. */ -export async function writeRegistry(directory, packages) { - const {files, integrities} = await registryFiles(packages); - await mkdir(directory, {recursive: true}); - for (const [name, bytes] of files) { - await mkdir(dirname(resolve(directory, name)), {recursive: true}); - await writeFile(resolve(directory, name), bytes); - } - return integrities; -} diff --git a/js/developer/tools/release-check.mjs b/js/developer/tools/release-check.mjs deleted file mode 100644 index eee5d2c1..00000000 --- a/js/developer/tools/release-check.mjs +++ /dev/null @@ -1,4 +0,0 @@ -import {readFile} from 'node:fs/promises'; -const distribution = JSON.parse(await readFile(new URL('./distribution.json', import.meta.url))); -if (process.argv[2] !== `developer-v${distribution.version}`) - throw new Error(`Expected dedicated tag developer-v${distribution.version}`); diff --git a/js/developer/tools/restore-check.mjs b/js/developer/tools/restore-check.mjs deleted file mode 100644 index 8938c316..00000000 --- a/js/developer/tools/restore-check.mjs +++ /dev/null @@ -1,248 +0,0 @@ -// Tests of wf restore against the local registry fixture, served as plain files. Apart from node:test and -// node:assert, they use only browser APIs, so that they can move to wf test. -import {test, before} from 'node:test'; -import assert from 'node:assert/strict'; -import {install, initProject, restore, restorePackages, effectiveRegistry, usableRegistry, cacheState, validateLock, lockPath, manifestPath, packageRoot} from '../environment/packages.bundle.mjs'; -import {syntheticPackages, registryFiles} from './registry-fixture.mjs'; -import {memoryBridge} from './memory-bridge.mjs'; - -const encoder = new TextEncoder(); -const decoder = new TextDecoder(); -const json = (storage, path) => JSON.parse(decoder.decode(storage.get(path))); -const cacheKeys = storage => [...storage.keys()].filter(key => key.startsWith(packageRoot + '/')).sort(); -const snapshot = storage => new Map(storage); - -const registries = {}; -before(async () => { - const packages = syntheticPackages(); - const genuine = packages.map(pkg => ({...pkg, tampered: false})); - registries.local = (await registryFiles(packages)).files; - // The same packages, with the tampered archive still matching its integrity: a lock can be created from it. - registries.genuine = (await registryFiles(genuine)).files; - // A mirror missing a package of the lock. - registries.partial = (await registryFiles(genuine.filter(pkg => pkg.manifest.name !== 'webfront-fixture-lib'))).files; -}); - -// Serves the registry's files at an origin, as a static file server would; records every request. -function served(files, origin = 'https://registry.test') { - const requests = []; - const fetchImpl = async (url, {signal} = {}) => { - signal?.throwIfAborted(); - requests.push(String(url)); - const {origin: requested, pathname} = new URL(url); - if (requested !== origin) return new Response('', {status: 503}); - const bytes = files.get(decodeURIComponent(pathname.slice(1))); - return bytes ? new Response(bytes) : new Response('', {status: 404}); - }; - return {fetchImpl, requests, registry: `${origin}/`}; -} - -const explicit = source => ({registry: source.registry, registryExplicit: true, fetchImpl: source.fetchImpl}); - -// A project locked to webfront-fixture-app@1.0.0 and webfront-fixture-lib@1.0.0, although lib 1.1.0 satisfies ^1.0.0. -async function lockedProject(files = registries.local, specs = ['webfront-fixture-lib@1.0.0', 'webfront-fixture-app@1.0.0']) { - const memory = memoryBridge(); - await initProject(memory.bridge, [], {}); - for (const spec of specs) await install(memory.bridge, [spec], explicit(served(files))); - return memory; -} - -test('lock and empty cache: wf restore rebuilds the exact locked graph from the local registry', async () => { - const {bridge, storage, pending} = await lockedProject(); - const lock = json(storage, lockPath); - assert.deepEqual(Object.keys(lock.packages).sort(), ['webfront-fixture-app@1.0.0', 'webfront-fixture-lib@1.0.0']); - const cached = cacheKeys(storage); - assert.ok(cached.some(key => key.endsWith('.json')), 'each cached package has a record'); - cached.forEach(key => storage.delete(key)); - const before = snapshot(storage); - const source = served(registries.local); - const lines = []; - const result = await restore(bridge, [], {...explicit(source), progress: line => lines.push(line)}); - assert.equal(result.restored, 2); - assert.match(result.text, /Restored 2 of 2 packages \(0 already in the cache\)/); - assert.deepEqual(cacheKeys(storage), cached, 'the cache is the one the installation wrote'); - assert.ok([...before].every(([key, bytes]) => storage.get(key) === bytes), 'manifest and lock are only read'); - assert.ok(source.requests.every(url => !url.includes('1.1.0')), 'no range is resolved again'); - assert.ok(source.requests.every(url => url.startsWith(source.registry))); - assert.equal(lines[0], `Registry: ${source.registry} (application option)`); - assert.equal(pending(), 0); - // Idempotent: a valid cache is verified, not downloaded again. - source.requests.length = 0; - const again = await restore(bridge, [], explicit(source)); - assert.equal(again.restored, 0); - assert.equal(again.verified, 2); - assert.equal(source.requests.length, 0); -}); - -test('wf restore --offline checks the cache without any request and lists what is missing or corrupted', async () => { - const {bridge, storage} = await lockedProject(); - const noNetwork = async () => { throw new Error('network access'); }; - const ok = await restore(bridge, ['--offline'], {fetchImpl: noNetwork}); - assert.match(ok.text, /Cache verified offline: 2 packages match/); - const lock = json(storage, lockPath); - const [app, lib] = ['webfront-fixture-app@1.0.0', 'webfront-fixture-lib@1.0.0'].map(id => lock.packages[id]); - storage.delete(`${packageRoot}/${app.key}.json`); - storage.set(`${packageRoot}/${lib.key}/index.js`, encoder.encode('changed')); - const before = snapshot(storage); - await assert.rejects(restore(bridge, ['--offline'], {fetchImpl: noNetwork}), - error => /webfront-fixture-app@1\.0\.0 \(missing\)/.test(error.message) && /webfront-fixture-lib@1\.0\.0 \(corrupted\)/.test(error.message)); - assert.deepEqual(storage, before, 'an offline check writes nothing'); - assert.equal(await cacheState(bridge, app), 'missing'); - assert.equal(await cacheState(bridge, lib), 'corrupted'); - // Online, the same packages are downloaded again and the cache is valid. - const result = await restore(bridge, [], explicit(served(registries.local))); - assert.equal(result.restored, 2); - assert.equal(await cacheState(bridge, lib), 'valid'); - // Only the files the lock lists are checked; a file added beside them is never read by a build. - storage.set(`${packageRoot}/${lib.key}/extra.js`, encoder.encode('')); - assert.equal(await cacheState(bridge, lib), 'valid'); -}); - -test('the application registry takes precedence over the manifest one, which takes precedence over the default', async () => { - const {bridge, storage} = await lockedProject(); - const manifest = json(storage, manifestPath); - storage.set(manifestPath, encoder.encode(JSON.stringify({...manifest, registry: 'https://manifest.test/'}))); - cacheKeys(storage).forEach(key => storage.delete(key)); - const application = served(registries.local); - const result = await restore(bridge, [], explicit(application)); - assert.deepEqual(result.registry, {url: 'https://registry.test/', source: 'application option'}); - assert.ok(application.requests.length && application.requests.every(url => url.startsWith('https://registry.test/'))); - cacheKeys(storage).forEach(key => storage.delete(key)); - const mirror = served(registries.local, 'https://manifest.test'); - const fromManifest = await restore(bridge, [], {registry: 'https://registry.test/', fetchImpl: mirror.fetchImpl}); - assert.deepEqual(fromManifest.registry, {url: 'https://manifest.test/', source: 'webfront.project.json'}); - assert.deepEqual(effectiveRegistry({}, {}), {url: 'https://registry.npmjs.org/', source: 'default'}); - assert.deepEqual(effectiveRegistry({registry: '/mirror/'}, {}), {url: '/mirror/', source: 'default'}); - await assert.rejects(restore(bridge, [], {registry: 'http://plain.test/', registryExplicit: true, fetchImpl: mirror.fetchImpl}), /HTTPS or the application origin/); -}); - -test('a registry path never leaves the application origin, however a URL parser reads it', () => { - // On an HTTPS page, "/\\host" resolves to https://host/, which an HTTPS check alone would accept. - globalThis.location = new URL('https://app.test/webfront-bootstrap.html'); - try { - assert.equal(usableRegistry({registry: '/mirror/', registryExplicit: true}).url, '/mirror/'); - for (const registry of ['//registry.test/', '/\\registry.test/', '/\\\\registry.test/', 'http://registry.test/']) - assert.throws(() => usableRegistry({registry, registryExplicit: true}), /HTTPS or the application origin/, registry); - assert.equal(usableRegistry({registry: 'https://registry.test/', registryExplicit: true}).url, 'https://registry.test/'); - } finally { delete globalThis.location; } -}); - -test('a bridge failure while reading a record is reported, not taken for a corrupted cache', async () => { - const {bridge} = await lockedProject(); - const failing = {cppFunction: name => async (...args) => { - if (name.endsWith('.read') && args[0].endsWith('.json') && args[0].includes('.webfront/')) throw new Error('Bridge disconnected'); - return bridge.cppFunction(name)(...args); - }}; - const source = served(registries.local); - await assert.rejects(restore(failing, ['--offline'], {}), /Bridge disconnected/); - await assert.rejects(restore(failing, [], explicit(source)), /Bridge disconnected/); - assert.equal(source.requests.length, 0, 'a valid package is not downloaded again'); -}); - -test('a changed archive or a package missing from the registry fails and keeps lock and valid cache intact', async () => { - const {bridge, storage} = await lockedProject(registries.genuine, ['webfront-fixture-lib@1.0.0', 'webfront-fixture-tampered@1.0.0']); - const lock = json(storage, lockPath); - const tampered = lock.packages['webfront-fixture-tampered@1.0.0']; - const lib = lock.packages['webfront-fixture-lib@1.0.0']; - cacheKeys(storage).filter(key => key.includes('tampered')).forEach(key => storage.delete(key)); - const lockBytes = storage.get(lockPath); - await assert.rejects(restore(bridge, [], explicit(served(registries.local))), /Integrity check failed/); - assert.equal(storage.get(lockPath), lockBytes); - assert.equal(await cacheState(bridge, tampered), 'missing'); - assert.equal(await cacheState(bridge, lib), 'valid'); - cacheKeys(storage).filter(key => key.includes('fixture-lib')).forEach(key => storage.delete(key)); - await assert.rejects(restore(bridge, [], explicit(served(registries.partial))), /webfront-fixture-lib: HTTP 404/); - assert.equal(storage.get(lockPath), lockBytes); -}); - -test('an interrupted restore keeps the packages already restored and resumes with the others', async () => { - const {bridge, storage, pending} = await lockedProject(); - cacheKeys(storage).forEach(key => storage.delete(key)); - const controller = new AbortController(); - const source = served(registries.local); - let packuments = 0; - const interrupting = async (url, options) => { - if (!String(url).endsWith('.tgz') && ++packuments === 2) controller.abort(new Error('Interrupted')); - return source.fetchImpl(url, options); - }; - await assert.rejects(restore(bridge, [], {...explicit(source), fetchImpl: interrupting, signal: controller.signal}), /Interrupted/); - assert.equal(pending(), 0, 'no staged transaction is left behind'); - const states = await Promise.all(Object.values(json(storage, lockPath).packages).map(node => cacheState(bridge, node))); - assert.deepEqual(states.sort(), ['missing', 'valid']); - const resumed = await restore(bridge, [], explicit(source)); - assert.equal(resumed.restored, 1); - assert.equal(resumed.verified, 1); -}); - -// Unpacked sizes of the cached packages of a project, from the files the lock lists. -const sizeOf = (storage, node) => node.files.reduce((total, path) => total + storage.get(`${packageRoot}/${node.key}/${path}`).length, 0); - -test('the bound of the unpacked graph counts the cached packages and is checked before publishing', async () => { - const {bridge, storage} = await lockedProject(); - const lock = json(storage, lockPath); - const [app, lib] = ['webfront-fixture-app@1.0.0', 'webfront-fixture-lib@1.0.0'].map(id => lock.packages[id]); - const limit = sizeOf(storage, app) + sizeOf(storage, lib) - 1; - cacheKeys(storage).filter(key => key.includes('fixture-lib')).forEach(key => storage.delete(key)); - const before = snapshot(storage); - const source = served(registries.local); - for (let attempt = 0; attempt < 2; attempt++) { - await assert.rejects(restorePackages(bridge, lock, {...explicit(source), limit}), /exceed .* MiB unpacked/); - assert.deepEqual(storage, before, 'nothing is published past the bound, and a second attempt keeps it'); - } - const restored = await restorePackages(bridge, lock, {...explicit(source), limit: limit + 1}); - assert.equal(restored.restored, 1); -}); - -test('a cached file larger than the bound is a corruption, listed offline and repaired online', async () => { - const {bridge, storage} = await lockedProject(); - const lock = json(storage, lockPath); - const lib = lock.packages['webfront-fixture-lib@1.0.0']; - const limit = 64 * 1024; - storage.set(`${packageRoot}/${lib.key}/index.js`, new Uint8Array(3 * 256 * 1024)); - const reads = []; - const counting = {cppFunction: name => async (...args) => { - if (name.endsWith('.read')) reads.push(args[0]); - return bridge.cppFunction(name)(...args); - }}; - await assert.rejects(restorePackages(counting, lock, {offline: true, limit}), /webfront-fixture-lib@1\.0\.0 \(corrupted\)/); - assert.equal(reads.filter(path => path.endsWith(`${lib.key}/index.js`)).length, 1, 'reading stops at the bound'); - const restored = await restorePackages(bridge, lock, {...explicit(served(registries.local)), limit}); - assert.equal(restored.restored, 1); - assert.equal(await cacheState(bridge, lib), 'valid'); -}); - -test('an invalid or absent lock is refused before any request or write', async () => { - const {bridge, storage} = await lockedProject(); - const source = served(registries.local); - for (const lock of ['{', JSON.stringify({format: 2, roots: {}, packages: {}})]) { - storage.set(lockPath, encoder.encode(lock)); - const before = snapshot(storage); - await assert.rejects(restore(bridge, [], explicit(source))); - assert.deepEqual(storage, before); - } - storage.delete(lockPath); - await assert.rejects(restore(bridge, [], explicit(source)), /No webfront-packages.lock.json: run wf install/); - await assert.rejects(restore(bridge, ['--force'], explicit(source)), /Usage: wf restore \[--offline\]/); - assert.equal(source.requests.length, 0); - const packages = Object.fromEntries(Array.from({length: 513}, (_, i) => [`p${i}@1.0.0`, {}])); - assert.throws(() => validateLock({format: 1, roots: {}, packages}), /exceeds 512 packages/); -}); - -test('wf install of a consistent lock repairs a corrupted cache and names its registry', async () => { - const {bridge, storage} = await lockedProject(); - const lib = json(storage, lockPath).packages['webfront-fixture-lib@1.0.0']; - storage.set(`${packageRoot}/${lib.key}/index.js`, encoder.encode('changed')); - const lines = []; - const result = await install(bridge, [], {...explicit(served(registries.local)), progress: line => lines.push(line)}); - assert.equal(result.restored, 1); - assert.deepEqual(result.registry, {url: 'https://registry.test/', source: 'application option'}); - assert.ok(lines.includes('Registry: https://registry.test/ (application option)')); - assert.equal(await cacheState(bridge, lib), 'valid'); -}); - -test('the registry fixture is reproducible', async () => { - const first = await registryFiles(syntheticPackages()); - const second = await registryFiles(syntheticPackages()); - assert.deepEqual(first, second); - assert.equal(JSON.parse(new TextDecoder().decode(first.files.get('webfront-fixture-lib')))['dist-tags'].latest, '1.1.0'); -}); diff --git a/js/developer/tools/scripts-check.mjs b/js/developer/tools/scripts-check.mjs deleted file mode 100644 index 7113a70c..00000000 --- a/js/developer/tools/scripts-check.mjs +++ /dev/null @@ -1,377 +0,0 @@ -// Tests of wf run and wf exec: permissions, command resolution, the page side of the context API and the Worker's -// termination, with a scripted stand-in for the Worker. Apart from node:test and node:assert, they use only browser -// APIs, so that they can move to wf test. -import {test} from 'node:test'; -import assert from 'node:assert/strict'; -import {checkRead, checkWrite, checkFetch, listable, scriptCommand, parseRunOptions, execTarget, lockedPackage, scriptHost, - runWorker, runResult, runDeadline, secondsLeft, ScriptExit, nodeBuiltin, nodeImport, createFinder, validateManifest} - from '../environment/packages.bundle.mjs'; -import {memoryBridge} from './memory-bridge.mjs'; - -const encoder = new TextEncoder(); -const decoder = new TextDecoder(); -// The terminal's tokenizer splits on spaces outside quotes; terminal.mjs itself needs xterm. -const tokenize = text => text.match(/"[^"]*"|\S+/g).map(word => word.replace(/^"|"$/g, '')); -const permissions = {files: ['ui', 'data/in.json'], publish: ['generated', '.webfront/x', 'webfront.project.json'], fetch: ['https://api.test']}; - -test('context operations are checked against the manifest permissions', () => { - assert.equal(checkRead(permissions, 'ui/main.tsx'), 'ui/main.tsx'); - assert.equal(checkRead(permissions, 'generated/out.txt'), 'generated/out.txt', 'a writable path is readable'); - assert.equal(checkRead(permissions, 'data/in.json'), 'data/in.json'); - for (const path of ['data/other.json', 'uix/a', 'webfront-packages.lock.json']) - assert.throws(() => checkRead(permissions, path), /Permission denied: reading .* permissions\.files/); - assert.throws(() => checkRead(permissions, '../outside'), /Not a project-relative path/); - assert.throws(() => checkRead(permissions, ''), /Not a project-relative path/); - assert.equal(checkWrite(permissions, 'generated/a/b.txt'), 'generated/a/b.txt'); - assert.throws(() => checkWrite(permissions, 'ui/main.tsx'), /Permission denied: writing ui\/main.tsx .* permissions\.publish/); - for (const path of ['webfront.project.json', '.webfront/x/y']) - assert.throws(() => checkWrite(permissions, path), /managed by wf and never written by a script/); - assert.equal(checkFetch(permissions, 'https://api.test/v1?q=1').href, 'https://api.test/v1?q=1'); - assert.throws(() => checkFetch(permissions, 'https://other.test/'), /Permission denied: fetching https:\/\/other.test/); - assert.throws(() => checkFetch({}, '/local', 'http://localhost:9002/'), /permissions\.fetch/); -}); - -test('wf run resolves a script of the manifest to a module or a wf command, without a shell', () => { - const manifest = validateManifest({format: 1, name: 'app', version: '1.0.0', - scripts: {gen: 'tools/gen.ts --fast', build: 'wf embed main', loop: 'wf run loop'}}); - assert.deepEqual(scriptCommand(manifest, 'gen', ['a b'], tokenize), {kind: 'module', entry: {namespace: 'project', path: 'tools/gen.ts'}, args: ['--fast', 'a b']}); - assert.deepEqual(scriptCommand(manifest, 'build', ['--x'], tokenize), {kind: 'wf', argv: ['embed', 'main', '--x']}); - assert.throws(() => scriptCommand(manifest, 'missing', [], tokenize), /No script "missing" .* \(scripts: build, gen, loop\)/); - assert.throws(() => scriptCommand(manifest, 'loop', [], tokenize, 4), /more than 4 levels/); - assert.throws(() => scriptCommand({...manifest, scripts: {bad: '../x.ts'}}, 'bad', [], tokenize), /Unsafe package path/); - assert.deepEqual(parseRunOptions(['--timeout', '5', 'gen', '--timeout', '9'], 'u'), {timeout: 5, target: 'gen', args: ['--timeout', '9']}); - assert.equal(parseRunOptions(['gen'], 'u').timeout, 600); - for (const args of [['--timeout', '0', 'gen'], ['--timeout', '3601', 'gen'], ['--timeout', '1.5', 'gen']]) - assert.throws(() => parseRunOptions(args, 'u'), /--timeout expects whole seconds from 1 to 3600/); - assert.throws(() => parseRunOptions([], 'wf run