diff --git a/.codescene/code-health-rules.json b/.codescene/code-health-rules.json index c1547c6e..29e1bf2c 100644 --- a/.codescene/code-health-rules.json +++ b/.codescene/code-health-rules.json @@ -27,6 +27,34 @@ "rules": [ { "name": "String Heavy Function Arguments", "weight": 0.0 } ] + }, + { + "matching_content_path": "src/developer/*.bundle.mjs", + "matching_content_path_doc": "Minified esbuild output of the sources next to it, checked in so that the bootstrap and package resolver need no Node.js at consumption time. It is regenerated by tools/developer/build.mjs --refresh-bootstrap and verified against src/developer/bundles.json, never edited by hand; the readable sources are analysed instead.", + "rules": [ + { "name": "Complex Method", "weight": 0.0 }, + { "name": "Bumpy Road Ahead", "weight": 0.0 }, + { "name": "Complex Conditional", "weight": 0.0 }, + { "name": "Excess Number of Function Arguments", "weight": 0.0 }, + { "name": "Deep, Nested Complexity", "weight": 0.0 }, + { "name": "Large Method", "weight": 0.0 }, + { "name": "Brain Method", "weight": 0.0 }, + { "name": "Overall Code Complexity", "weight": 0.0 }, + { "name": "Lines of Code in a Single File", "weight": 0.0 }, + { "name": "Number of Functions in a Single Module", "weight": 0.0 }, + { "name": "Code Duplication", "weight": 0.0 }, + { "name": "Primitive Obsession", "weight": 0.0 }, + { "name": "String Heavy Function Arguments", "weight": 0.0 }, + { "name": "Low Cohesion", "weight": 0.0 } + ] + }, + { + "matching_content_path": "include/system/DeveloperStore.hpp", + "matching_content_path_doc": "The store implements the webfront.developer.* bridge callbacks, whose identifiers, project paths, offsets and flags arrive as primitives from the browser. Wrapping them in types only to lower the ratio would obscure the bridge contract.", + "rules": [ + { "name": "String Heavy Function Arguments", "weight": 0.0 }, + { "name": "Primitive Obsession", "weight": 0.0 } + ] } ] } diff --git a/.gitattributes b/.gitattributes index f787a122..498d800b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -177,3 +177,12 @@ third_party/jasmine/* text eol=lf third_party/jasmine/*.png binary third_party/fflate/* text eol=lf include/system/*Data.hpp text eol=lf + +# Browser-powered developer bootstrap sources and generated payloads. +src/developer/* text eol=lf +tools/assets/package-lock.json text eol=lf + +# Starter archives and every hashed distribution input must be identical on Windows. +src/pi/* text eol=lf +src/life/* text eol=lf +tools/developer/* text eol=lf diff --git a/.github/workflows/BuildAndTest.yml b/.github/workflows/BuildAndTest.yml index 36d784e4..e98e198d 100644 --- a/.github/workflows/BuildAndTest.yml +++ b/.github/workflows/BuildAndTest.yml @@ -316,12 +316,18 @@ jobs: run: | launchctl print gui/$(id -u) >/dev/null pgrep -x WindowServer + - name: Prepare offline developer environment and starter fixtures + run: | + npm ci --prefix tools/assets --ignore-scripts + node tools/developer/build.mjs build-developer-environment + node tools/developer/fixtures.mjs build-developer-environment - name: Configure system WebKit frontend run: >- cmake -S . -B build-wkwebview -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_EMBED_CEF=OFF -DENABLE_TESTING=ON -DWEBFRONT_EMBED_WKWEBVIEW=ON -DWEBFRONT_WEBTEST_FRONTEND=WKWebView -DWEBFRONT_DEMO_FRONTEND=Native + -DWEBFRONT_DEVELOPER_FIXTURES=${{github.workspace}}/build-developer-environment - name: Build run: cmake --build build-wkwebview --parallel 2 - name: Test @@ -362,11 +368,16 @@ jobs: sudo apt-get update sudo apt-get install -y xvfb + - name: Prepare offline developer environment and starter fixtures + run: | + npm ci --prefix tools/assets --ignore-scripts + node tools/developer/build.mjs build-developer-environment + node tools/developer/fixtures.mjs build-developer-environment - name: Configure CEF integration build - run: cmake . -B ${{github.workspace}}/build-cef -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_EMBED_CEF=ON -DENABLE_TESTING=ON + run: cmake . -B ${{github.workspace}}/build-cef -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_EMBED_CEF=ON -DENABLE_TESTING=ON -DWEBFRONT_DEVELOPER_FIXTURES=${{github.workspace}}/build-developer-environment - name: Build browser test - run: cmake --build ${{github.workspace}}/build-cef --target webtest --parallel 1 + run: cmake --build ${{github.workspace}}/build-cef --target webtest developer_integration --parallel 1 - name: Run Jasmine bridge test run: ctest --test-dir ${{github.workspace}}/build-cef -L web-integration --output-on-failure --no-tests=error diff --git a/.github/workflows/DeveloperDistribution.yml b/.github/workflows/DeveloperDistribution.yml new file mode 100644 index 00000000..585c7444 --- /dev/null +++ b/.github/workflows/DeveloperDistribution.yml @@ -0,0 +1,126 @@ +name: Developer packages + +on: + push: + tags: ['developer-v*'] + branches: ['**'] + paths: + - 'src/developer/**' + - 'src/pi/**' + - 'src/life/**' + - 'tools/developer/**' + - 'tools/assets/package*.json' + - 'include/system/DeveloperReleaseData.hpp' + - '.github/workflows/DeveloperDistribution.yml' + pull_request: + branches: [develop, master] + paths: + - 'src/developer/**' + - 'src/pi/**' + - 'src/life/**' + - 'tools/developer/**' + - 'tools/assets/package*.json' + - 'include/system/DeveloperReleaseData.hpp' + - '.github/workflows/DeveloperDistribution.yml' + workflow_dispatch: + inputs: + publish: + description: Publish the pinned version to GitHub Pages + type: boolean + default: false + +permissions: + contents: read + +jobs: + package: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v6 + with: + node-version: 24 + cache: npm + cache-dependency-path: tools/assets/package-lock.json + - name: Install pinned maintenance dependencies + run: npm ci --prefix tools/assets --ignore-scripts + - name: Build and verify the environment and starter packages + run: | + node tools/developer/build.mjs build-distribution + node tools/developer/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 + cmp include/system/DeveloperReleaseData.hpp build-distribution/DeveloperReleaseData.hpp + node --test tools/developer/check.mjs tools/developer/distribution-check.mjs + - name: Check the dedicated release tag + if: startsWith(github.ref, 'refs/tags/developer-v') + env: + RELEASE_TAG: ${{ github.ref_name }} + run: node tools/developer/release-check.mjs "$RELEASE_TAG" + - uses: actions/upload-artifact@v4 + with: + name: developer-distribution + 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 + + publish: + if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/developer-v') || (github.event_name == 'workflow_dispatch' && inputs.publish)) + needs: package + runs-on: ubuntu-24.04 + permissions: + contents: write + pages: write + concurrency: + group: developer-pages-publication + cancel-in-progress: false + env: + GH_TOKEN: ${{ github.token }} + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v6 + with: + node-version: 24 + - uses: actions/download-artifact@v4 + with: + name: developer-distribution + path: build-distribution + - name: Check the configured Pages source before pushing + run: node tools/developer/pages.mjs --check + - name: Preserve existing versions and publish the static branch + shell: bash + run: | + set -euo pipefail + gh auth setup-git + site="$RUNNER_TEMP/developer-pages" + git init --initial-branch=gh-pages "$site" + git -C "$site" remote add origin "https://github.com/$GITHUB_REPOSITORY.git" + result=0 + git -C "$site" ls-remote --exit-code --heads origin gh-pages > "$RUNNER_TEMP/developer-pages-ref" || result=$? + if [ "$result" = 0 ]; then + git -C "$site" fetch --depth=1 origin gh-pages + git -C "$site" switch --detach FETCH_HEAD + elif [ "$result" != 2 ]; then + exit "$result" + fi + node tools/developer/site.mjs build-distribution "$site" + git -C "$site" config user.name "$GITHUB_ACTOR" + git -C "$site" config user.email "$GITHUB_ACTOR@users.noreply.github.com" + git -C "$site" add .nojekyll index.html developer + if ! git -C "$site" diff --cached --quiet; then + version=$(node -p "require('./tools/developer/distribution.json').version") + git -C "$site" commit -m "Publish developer packages $version [#288]" + git -C "$site" push origin HEAD:refs/heads/gh-pages + fi + - name: Request the configured Pages build + run: node tools/developer/pages.mjs + - name: Archive tagged packages in a dedicated prerelease + if: startsWith(github.ref, 'refs/tags/developer-v') + env: + RELEASE_TAG: ${{ github.ref_name }} + run: node tools/developer/archive-release.mjs "$RELEASE_TAG" build-distribution diff --git a/.github/workflows/ReleaseVersion.yml b/.github/workflows/ReleaseVersion.yml index 68b336b5..851cc110 100644 --- a/.github/workflows/ReleaseVersion.yml +++ b/.github/workflows/ReleaseVersion.yml @@ -11,6 +11,8 @@ permissions: jobs: version: + # Developer package prereleases use their own version and validation workflow. + if: github.event_name != 'release' || !startsWith(github.event.release.tag_name, 'developer-v') runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v7 diff --git a/README.md b/README.md index cae0cac3..38c35a33 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,16 @@ Your system browser opens the interface below. The page is included in the libra ![The embedded Hello, WebFront! page showing the connected indicator](docs/images/hello-world.png) +## Browser-powered development (experimental) + +The optional [developer environment](docs/DEVELOPER_ENVIRONMENT.md) downloads its terminal and +JavaScript/WASM build tools on demand. Install browser libraries with `wf install`, preview local +TSX, then generate compressed C++ resource headers with `wf embed`. The Game of Life example pairs a small C++23 bitset simulation with a spatial React interface, +then demonstrates +recompiling an offline native application without installing Node.js or npm on the developer's machine. +The [version-pinned environment and starters](https://ambroise-leclerc.github.io/WebFront/) +are hosted on GitHub Pages; see the guide for the complete walkthrough. + ## Connect your interface to C++ For a small first example, the Greeter connects a name field and a button to application code. Register an ordinary C++ lambda; WebFront deduces its signature: diff --git a/cmake/WebFrontAssets.cmake b/cmake/WebFrontAssets.cmake index 7a390652..2bf0b85d 100644 --- a/cmake/WebFrontAssets.cmake +++ b/cmake/WebFrontAssets.cmake @@ -43,6 +43,13 @@ function(webfront_add_embedded_assets) "${root}/src/fallback/webfront-fallback.mjs" "${root}/include/system/FallbackModuleData.hpp" FallbackModuleData FallbackModuleAssetFresh) + _webfront_add_embedded_text_asset( + "${root}/src/developer/index.html" "${root}/include/system/DeveloperIndexHtmlData.hpp" + DeveloperIndexHtmlData DeveloperIndexHtmlAssetFresh) + _webfront_add_embedded_text_asset( + "${root}/src/developer/bootstrap.bundle.mjs" "${root}/include/system/DeveloperBootstrapData.hpp" + DeveloperBootstrapData DeveloperBootstrapAssetFresh) + # Terminal component (include/system/TerminalFS.hpp). xterm.js files are vendored verbatim in # third_party/xterm (see its VERSION file); refresh them with cmake/UpdateXterm.cmake. _webfront_add_embedded_text_asset( @@ -93,6 +100,9 @@ function(webfront_add_embedded_assets) endforeach() if(ENABLE_TESTING) find_program(WEBFRONT_NODE_EXECUTABLE NAMES node nodejs REQUIRED) + add_test(NAME DeveloperJavaScript COMMAND "${WEBFRONT_NODE_EXECUTABLE}" + --test "${root}/tools/developer/check.mjs" "${root}/tools/developer/distribution-check.mjs") + set_tests_properties(DeveloperJavaScript PROPERTIES TIMEOUT 30) add_test(NAME EmbeddedGzipContents COMMAND "${WEBFRONT_NODE_EXECUTABLE}" "${root}/tools/assets/check.mjs") endif() diff --git a/codecov.yml b/codecov.yml index 3aeb7659..4b4ae77f 100644 --- a/codecov.yml +++ b/codecov.yml @@ -4,5 +4,9 @@ coverage: default: target: auto threshold: 0.2% + patch: + default: + target: 95% ignore: - "webtest/**" + - "src/**" diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md new file mode 100644 index 00000000..ab5283c0 --- /dev/null +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -0,0 +1,211 @@ +# Browser-powered development + +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 +application developer's machine**. A C++ compiler, CMake and the selected native webview remain +necessary. TypeScript/JSX is transformed in the browser; type checking is not performed. + +This is an experimental, explicit development facility. The downloaded environment runs with +the application's bridge authority and may read/write the selected project. It exposes no shell. +Do not ship developer mode as the distribution configuration. + +## Minimal C++ application + +Enable the platform's native frontend in CMake: `WEBFRONT_EMBED_WKWEBVIEW=ON` on macOS, +`WEBFRONT_EMBED_WEBVIEW2=ON` on Windows, or `WEBFRONT_EMBED_WEBKITGTK=ON` on Linux. +The default `webfront::WebFront` still opens the system browser. + +```cpp +#include +#include + +std::bitset<1024> nextLife(const std::bitset<1024>& cells); // Existing C++ simulation. + +int main() { + webfront::NativeApp app{"."}; // Explicit development project directory. + app.cppFunction("life.step", &nextLife); + app.bootstrap("developer"); // Uses the version and SHA-512 pinned in WebFront. + app.show(); +} +``` + +The [versioned distributions](https://ambroise-leclerc.github.io/WebFront/) are published on GitHub Pages. +Version 0.3.0 provides the packed-bitset Life starter and requires the bridge support from #289. +Version 0.3.1 makes `wf install` keep the versions of the installed lock and reject an archive whose integrity differs from it. +Published versions 0.1.0 to 0.3.0 remain immutable; 0.2.0 used string-based Life grids. +On 2026-10-20, the 0.3.0 public download/WASM/React/PI/Life path passed in WKWebView, including +128-byte grid exchange, painting cells across an octet boundary, playback/reset and deterministic +header generation. Both resulting headers were compiled and the applications passed offline +native tests from empty working directories, with developer callbacks absent. Pages returned +HTTP 200, CORS `*` and the pinned archive bytes. These checks supplement offline CTest fixtures. + +The default configuration is generated in `include/system/DeveloperReleaseData.hpp` and targets +`https://ambroise-leclerc.github.io/WebFront/developer/0.3.1/environment.tgz`. It 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. + +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 +commands. Existing directories are never replaced. The trusted environment hash protects both +its own code and the starter descriptor; `provision.json` on the server is not a new trust anchor. +See [publication instructions](../tools/developer/PUBLISHING.md) for deployment and release checks. + +The bootstrap verifies SHA-512 before unpacking or executing the archive, validates its manifest +and paths, then publishes it under the application's local origin. The cached **archive** is +verified again before reuse, allowing subsequent launches without network access. Failure leaves +a readable status and Retry button. A different pinned hash requires a matching archive; the old +environment is not silently substituted. + +## The Game of Life walkthrough + +`src/Life.hpp` is a small C++23 B3/S23 simulation on a `std::bitset<1024>`. +Each generation reads the old grid and creates a new one; the 32 × 32 world wraps on both axes. +The core needs no React, server, thread, timer or graphics dependency. `nextLife` is registered directly +with its `const LifeGrid&` argument and bitset result. React stores and exchanges a 128-byte `Uint8Array`, +with cell `i` in bit `i % 8` of byte `i / 8`. The bridge validates the exact unsigned-byte type and length. +`src/LifeConsole.cpp` runs it without WebFront; build and run `WebFrontLifeConsole` to start +with a plain console application. + +`src/LifeDeveloper.cpp` adds the native window and downloaded developer bootstrap. Configure +`build-native` with the native frontend option above, then start with an empty project directory: + +```sh +./build-native/src/WebFrontLifeDeveloper /path/to/life-project +``` + +Optional extra arguments ` ` override the pinned default. +In the downloaded terminal: + +```text +wf create life +wf install react@19.3.1 react-dom@19.3.1 +wf preview ui/main.tsx +wf embed ui/main.tsx --output generated/LifeUI.hpp +``` + +The starter contains editable TSX/CSS and an exact-version `webfront.project.json` recipe. +`wf create life another-directory` selects a different new destination; existing directories +are never replaced. React DOM pulls scheduler transitively and checks its React peer. +Edit the local files in your normal editor, then run `wf preview` again. Ctrl+C interrupts +commands, including downloads and builds. + +The interface draws an isometric field with raised living cells, soft lighting and translucent +panels. Play/pause, single step, tempo, glider/blinker/galaxy seeds, clear, cell painting and a plan +view make the simulation interactive. Generation and population counters expose its state. +Every step awaits `webFront.cppFunction('life.step')(cells)`; no Life rules run in JavaScript. +Only one generation request can be outstanding. Replacing a pattern or clearing the field stops +animation and discards stale replies. Errors stop playback and appear in the interface. +Canvas rendering has an accessible description; patterns and simulation controls work with the +keyboard. Individual canvas cells are pointer-editable, without keyboard cell navigation. +No fonts, images, 3D library or additional UI framework are downloaded. + +![The native Game of Life demo at generation 34](images/life-preview.png) + +`wf embed` builds JS/CSS/resources, creates an HTML entry page, preserves dependency notices and +writes a header-only `webfront::fs::LifeUI` provider using deterministic gzip. The filename stem +determines the C++ provider name. The header is replaced only after all chunks arrive successfully. +The distribution form has no project root or developer callbacks: + +```cpp +#include +#include "Life.hpp" +#include "generated/LifeUI.hpp" + +int main() { + webfront::NativeAppWithAssets app; + app.cppFunction("life.step", &webfront::demo::nextLife); + app.show(); +} +``` + +Reconfigure the native build with +`-DWEBFRONT_LIFE_ASSETS=/absolute/path/to/life-project/generated/LifeUI.hpp`, build target +`WebFrontLifeEmbedded` and run it. Recompilation is explicit. The resulting binary needs neither +project sources, downloaded cache nor network. + +The original PI example remains available: `WebFrontPiDeveloper`, `wf create pi`, +`wf embed ui/main.tsx --output generated/PiUI.hpp`, and +`-DWEBFRONT_PI_ASSETS=/absolute/path/to/generated/PiUI.hpp` / `WebFrontPiEmbedded`. +Use a separate project directory for each starter. Existing embedded React/Babel providers +remain supported. + +## Dependencies, storage and limitations + +- `wf install` accepts exact versions, registry tags and semver ranges, resolves ordinary + transitive dependencies, and retains separate nodes for different versions. Required peers must + be satisfied by compatible explicitly installed roots or direct dependencies; conflicts fail. +- Package installation scripts, native add-ons and Node.js APIs are unsupported. Packages must be + usable in a browser. Optional dependencies are not installed in this first version; imports of + missing dependencies fail during the build. This is not a replacement for the complete npm CLI. +- Browser/production exports, ESM, CommonJS, TS/TSX, JSX, CSS and imported resource files are supported. + Private package exports, network imports and unavailable Node built-ins fail. Package-specific + build pipelines and automatic polyfills are not supplied. +- `webfront-packages.lock.json` records exact package versions, dependency edges, source integrities + and requested roots. Commit it and the source TSX/CSS; the generated provider can also be committed. + Preview/embed consume the locked local files without resolving versions again. +- Unpacked packages are cached by name, version and integrity under `.webfront/developer/packages/`. + A failed install can leave unused cached packages, but the lock file remains unchanged. The tools + installed by the existing `ToolManager` keep their separate store and `webfront-tools.lock.json`. +- Published environment/preview resources are served under `/webfront/developer/`. The protected + `/WebFront.js` remains the library's version. Sources, staging and cached archives are not HTTP + routes. Project reads and publications reject traversal and escaping symlinks. This does not + isolate downloaded tools or defend against concurrent modifications by another local process. +- Transfers use sequential 256 KiB chunks. Downloads are bounded to 64 MiB compressed; unpacking, + dependency source graphs and individual publication transactions to 256 MiB, with 512 packages + and eight active publications at most. A publication untouched for ten minutes (a reloaded or disconnected browser) is + abandoned, and staging left by a crashed process is removed after an hour. Browser builds time out after 120 seconds. +- Installing another package keeps every locked version that still satisfies a requested range and fails if its + archive no longer matches the recorded integrity; only new ranges are resolved. Review the resulting lock + changes. Restoring packages from a lockfile on a fresh machine is not yet a separate command. + +## Environment distribution and offline tests (maintainers) + +These commands require Node/npm **only for environment maintainers**. They prepare a tarball that +application developers can download. No command publishes anything to a registry automatically. + +```sh +npm ci --prefix tools/assets --ignore-scripts +node tools/developer/build.mjs build-developer-environment --refresh-bootstrap +node tools/developer/fixtures.mjs build-developer-environment +``` + +`build.mjs` bundles the environment and compiler, includes esbuild.wasm, xterm styles and licenses, +and writes deterministic `environment.tgz`, `life-starter.tgz`, `pi-starter.tgz`, `provision.json` and +`DeveloperReleaseData.hpp`. The version and public base URL are in `tools/developer/distribution.json`. Dependencies are +pinned in `tools/assets/package-lock.json`. `--refresh-bootstrap` additionally refreshes the two +checked-in JS bundles, their input checksums and the embedded bootstrap headers. Without that flag, +it writes only to the output directory. 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. Node/npm is only used by maintainers to build them. + +To try the local archive without an HTTPS server, copy `environment.tgz` to the project's +`.webfront/developer/preview/provision/environment.tgz` and pass +`/webfront/developer/preview/provision/environment.tgz` as its URL. The preview command later replaces +that directory, but the verified archive is already cached independently for subsequent launches. + +Fixture provisioning packs the pinned React, React DOM and scheduler sources from the maintainer's +npm installation into a fake local registry. No CTest case downloads from the public registry. + +```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" +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 +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 +[run 39490581423](https://github.com/ambroise-leclerc/WebFront/actions/runs/39490581423). +For Linux, select CEF and Xvfb instead; the same developer tests use the selected test frontend. +`DeveloperBrowserIntegration` exercises the real WASM compiler, local registry, PI and Life previews, C++ generation/animation and +repeatable header generation. Its CTest fixtures then build that **browser-generated** header and run +`DeveloperEmbeddedIntegration` and `LifeEmbeddedIntegration` from empty working directories +with no developer callbacks. +The standard CEF-off suite also checks project transactions, path rejection, PI, Life rules and boundaries, MIME types, +bootstrap freshness, package resolution, gzip generation, interruption and offline cache reuse. diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index c44f971a..7f6ad241 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -5,10 +5,28 @@ Status snapshot: 2026-07-19. Optional mddlog integration note: 2026-10-02. Newco ## Packed bitsets (#289, 2026-10-20) - The bridge accepts `std::bitset` callback arguments/results and C++ call arguments plus - typed future/sender results through the existing short/regular Uint8Array encodings. - Bit `i` maps to bit `i % 8` of byte `i / 8`; decoding validates the exact unsigned-byte type, - byte count and zero high padding bits. Zero-sized bitsets map to an empty Uint8Array. - JavaScript must know the logical bit count from the application contract. + typed future/sender results, using existing short/regular Uint8Array encodings. Bit `i` is + packed least-significant first into byte `i / 8`; exact lengths and zero padding are validated. + Zero-sized bitsets are supported. JavaScript must know the logical bit count separately. +- Life registers `nextLife` directly and React exchanges 128 packed bytes per generation. + Developer distribution 0.3.0 is published on GitHub Pages and archived as `developer-v0.3.0`; the pinned + 0.3.1 (locked reinstall) awaits its `developer-v0.3.1` publication. Published 0.1.0 to 0.3.0 remain immutable. +- Local verification: all 252 CEF-off CTest cases, 25 WKWebView integration/lifecycle cases + and 14 JavaScript checks pass. Repeated 0.3.0 provisioning produces byte-identical archives + and bootstrap configuration. Browser tests verify packed Life grids, playback/reset, + deterministic providers and offline execution from empty working directories. + CI on [b6bae2e](https://github.com/ambroise-leclerc/WebFront/actions/runs/39490581423) + passes WKWebView, all 14 Linux CEF/Xvfb cases with GCC, and the 252-case Linux + thread-sanitized suite. The codec matches the implementation merged in PR #290. +- After reconciling current `develop`, all 253 CEF-off CTest cases and 26 WKWebView + integration/lifecycle cases pass locally. New developer/embedded test executables use the + same agent bundles as the shared WKWebView suite; user-facing examples stay ordinary apps. +- The public 0.3.0 environment and both starters passed fresh WKWebView download/build tests. + Pages returned HTTP 200, CORS `*` and matching pinned bytes. Both public-path providers then + compiled and ran offline from empty working directories with developer callbacks absent. +- The demo branch uses the codec and browser assertions merged in PR #290, including MSVC's + empty-bitset guards and future tests that tolerate arbitrary response order. JS cell access + uses small packed-byte helpers; painting across an octet boundary is covered by the browser test. - Regression tests cover known bytes, size boundaries, malformed inputs, tuples and both browser call directions, including exceptional future/sender completion. Future calls and their final notification dispatch on the server context; a joined test thread only waits @@ -20,6 +38,40 @@ Status snapshot: 2026-07-19. Optional mddlog integration note: 2026-10-02. Newco on code revision `d9327e7`; the same run also passes both Windows MSVC configurations, the Linux sanitizers, WebKitGTK and macOS/WKWebView checks. + +## Browser-powered development (2026-10-20) + +- `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. +- 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 + local TSX, React/React DOM and scheduler, a same-window preview and an application-owned + generated provider. Offline executables use those providers without developer roots/callbacks. + Existing React/Babel/terminal providers remain supported. +- Historical snapshot at the 0.2.0 milestone (the current validation is listed above): local validation passed 250 CEF-off CTest cases, 25 WKWebView integration/lifecycle cases and + 14 JavaScript checks. Browser coverage includes PI results, C++ Life generations, playback/reset, + deterministic header generation and compiling/running both embedded applications from empty + working directories. Repeated previews replace session history instead of accumulating entries. + Linux CEF/Xvfb passes all 14 integration cases with GCC and Clang in + [run 39421265580](https://github.com/ambroise-leclerc/WebFront/actions/runs/39421265580); + its WKWebView job also passed. The later Windows and sanitizer results are in the validation above. +- 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. + 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 + React dependencies from npm, passed PI/Life previews and deterministic generation, then compiled + those public-path headers and ran both applications offline with developer callbacks absent. + Pages returned HTTP 200, CORS `*` and byte-identical pinned environment data on 2026-10-20. +- Browser packages only: no installation scripts, native modules, Node API shims, optional + dependencies or TypeScript type checking. Peers require explicit compatible roots/direct + dependencies. Lockfile restore on a fresh machine and automatic rebuild/watch are future work. + See [DEVELOPER_ENVIRONMENT](DEVELOPER_ENVIRONMENT.md) for exact commands and limits. + ## Embedded dependency refresh (#284, 2026-10-19) - React and React DOM 19.3.1, Babel standalone 8.0.7 and Jasmine 7.0.2 replace the older embedded diff --git a/docs/UI_COMPONENTS.md b/docs/UI_COMPONENTS.md index 03e8249d..aa65ee56 100644 --- a/docs/UI_COMPONENTS.md +++ b/docs/UI_COMPONENTS.md @@ -264,3 +264,12 @@ production plugin system. - A filesystem provider writing outside the build tree, with tests using temporary directories. - Browser tests that use a local fake registry: tests must not need the public network (done: `webtest/js/tools-specs.mjs`). + +## Browser-powered developer environment + +The opt-in `NativeApp` bootstrap extends this architecture with a downloaded environment rather +than embedding xterm/compiler/framework assets. It installs ordinary npm libraries into a separate +store, builds TSX in a browser Worker and generates application-owned filesystem providers. +The existing terminal/ToolManager APIs and their prebundled tool format remain supported. +See [the developer environment](DEVELOPER_ENVIRONMENT.md) for the API, provisioning, Game of Life walkthrough, +trust boundary and offline tests. The browser installer is intentionally not the complete npm CLI. diff --git a/docs/adr/ADR-003-protocole-binaire-et-bornes.md b/docs/adr/ADR-003-protocole-binaire-et-bornes.md index 86a180cc..7f4948d3 100644 --- a/docs/adr/ADR-003-protocole-binaire-et-bornes.md +++ b/docs/adr/ADR-003-protocole-binaire-et-bornes.md @@ -13,7 +13,7 @@ | 1.6 | 2026-10-16 | Acceptée | Ambroise Leclerc | Réassemblage des messages WebSocket fragmentés. | [3636c85](https://github.com/ambroise-leclerc/WebFront/commit/3636c8519b75bdfbcae8fcc8fca0c3a5f6374c1d) | | 1.7 | 2026-10-16 | Acceptée | Ambroise Leclerc | Limite de message vérifiée dès l’en-tête, avant allocation de la charge utile. | [68f01f5](https://github.com/ambroise-leclerc/WebFront/commit/68f01f53f304ddb56155be0d47fb6fdd293de142) | | 1.8 | 2026-10-16 | Acceptée | Ambroise Leclerc | Plafond indépendant de 125 octets pour les trames de contrôle. | [3ebc181](https://github.com/ambroise-leclerc/WebFront/commit/3ebc181fce48240aa2cecebfe4d3f8cc4966732d) | -| 1.9 | 2026-10-20 | Acceptée | Ambroise Leclerc | `std::bitset` compacté dans le format Uint8Array existant, sans nouvel opcode. | [#290](https://github.com/ambroise-leclerc/WebFront/pull/290) — provisoire, à remplacer par le hash du commit de fusion. | +| 1.9 | 2026-10-20 | Acceptée | Ambroise Leclerc | `std::bitset` compacté dans le format Uint8Array existant, sans nouvel opcode. | [5bc294e](https://github.com/ambroise-leclerc/WebFront/commit/5bc294eb0a9ba81ae7789b425baa6e299e848d97) | ## État et chronologie diff --git a/docs/adr/ADR-013-bootstrap-developpeur-a-la-demande.md b/docs/adr/ADR-013-bootstrap-developpeur-a-la-demande.md new file mode 100644 index 00000000..2b338b4f --- /dev/null +++ b/docs/adr/ADR-013-bootstrap-developpeur-a-la-demande.md @@ -0,0 +1,67 @@ +# ADR-013 : Amorcer un environnement développeur téléchargé à la demande + +## Versions + +| Version | Date | État | Auteur | Évolution | Commit | +| --- | --- | --- | --- | --- | --- | +| 0.1 | 2026-10-20 | Proposée | Ambroise Leclerc | Proposition et première implémentation du bootstrap développeur versionné. | À renseigner après intégration. | + +## Statut et date + +**Proposée le 2026-10-20.** L'implémentation expérimentale est soumise à validation ; la +distribution publique de l'environnement et la qualification des autres moteurs restent ouvertes. +La date est celle de la proposition, pas une origine historique reconstituée. + +## Contexte + +Une petite application C++ doit pouvoir acquérir son environnement de développement web sans +embarquer terminal, React, Babel ou compilateur JavaScript, et sans demander l'installation de npm. +Le navigateur possède déjà HTTPS et les primitives nécessaires au téléchargement. + +## Décision proposée + +`NativeApp` est une façade native explicite accessible depuis `WebFront.hpp`, sans modifier le +navigateur système par défaut. La création et `show()` ouvrent la fenêtre ; l'application enregistre +séparément ses callbacks et appelle `bootstrap("developer", options)` avant `show()`. +Le projet local est désigné explicitement lors de la construction. + +Cette proposition introduit une exception de développement explicite à l'ADR-009 : le bootstrap +peut contacter un dépôt au lancement après activation volontaire. Les applications ordinaires et +le mode distribution conservent leur lancement local sans dépendance npm ou réseau. + +Le petit chargeur embarqué télécharge une archive npm contenant le terminal et les outils. Il +vérifie une empreinte SHA-512 fournie par l'application, puis le manifeste de protocole 1 et les +chemins. Il publie les fichiers sous l'origine locale avant d'importer le module d'entrée. +L'archive mise en cache est revérifiée à chaque bootstrap ; une erreur affiche un diagnostic et +permet de réessayer. Un hash incompatible interdit le repli silencieux vers un autre environnement. + +Le distributeur fournit URL HTTPS/CORS et empreinte par un canal de confiance. Un registre npm +peut héberger cette archive, sans client npm chez l'utilisateur et sans serveur spécifique WebFront. +La première distribution vise GitHub Pages, avec des chemins `developer//` conservés +et une configuration URL/SHA-512 épinglée dans `DeveloperReleaseData.hpp`. Le workflow refuse de +remplacer les octets d'une version publiée et archive les versions taguées dans des prereleases +séparées de la bibliothèque C++. Les archives gardent des identifiants de paquet, sans exiger +publication npm ou propriété d'un scope. Le manifeste vérifié épingle aussi un starter PI distinct ; +`wf create pi` crée son dossier sans remplacer un projet existant. + +## Alternatives et conséquences + +- Embarquer l'environnement complet : écarté pour conserver une application initiale légère. +- Piloter Node/npm installé : écarté pour l'autonomie du développeur utilisateur. +- Exécuter une page distante avec le bridge : écarté ; l'environnement validé est servi localement. +- Le premier lancement nécessite l'accès au dépôt ou un provisioning local explicite. Le cache + vérifié autorise ensuite un lancement hors ligne. +- Le code téléchargé possède l'autorité du bridge et du projet autorisé ; ce n'est pas un sandbox. + Le mode distribution n'active pas ces callbacks. Aucun accès au shell n'est ajouté. + +## Règles et vérification + +Conserver le bridge protégé, les Promises d'erreur et les transferts binaires existants. Ne pas +ajouter terminal/compiler/frameworks à `DefaultFS`. Ne pas activer implicitement une racine projet. +Tester intégrité incorrecte, cache hors ligne, protocole inconnu, chemins invalides et interruption. +Le test natif charge l'archive depuis un dépôt local ; aucun test ne dépend du registre public. + +## Références + +- [Environnement développeur](../DEVELOPER_ENVIRONMENT.md), [ADR-008](ADR-008-contenu-de-confiance-et-origines.md), + [ADR-010](ADR-010-composants-et-outils-optionnels.md). diff --git a/docs/adr/ADR-014-construction-javascript-dans-le-browser.md b/docs/adr/ADR-014-construction-javascript-dans-le-browser.md new file mode 100644 index 00000000..d853972e --- /dev/null +++ b/docs/adr/ADR-014-construction-javascript-dans-le-browser.md @@ -0,0 +1,64 @@ +# ADR-014 : Construire les ressources web dans le moteur du navigateur + +## Versions + +| Version | Date | État | Auteur | Évolution | Commit | +| --- | --- | --- | --- | --- | --- | +| 0.1 | 2026-10-20 | Proposée | Ambroise Leclerc | Proposition et première implémentation du résolveur npm et du compilateur navigateur. | À renseigner après intégration. | + +## Statut et date + +**Proposée le 2026-10-20.** Validation initiale avec React et WKWebView ; couverture multiplateforme +et étendue de compatibilité des paquets à poursuivre avant acceptation générale. + +## Contexte + +Le gestionnaire d'outils de l'ADR-010 installe des outils déjà assemblés, sans dépendances. Le nouveau +parcours doit aussi installer des bibliothèques npm ordinaires et construire un TSX local sans Node. +Il ne s'agit pas de fournir toutes les API Node.js ou toutes les commandes npm dans un navigateur. + +## Décision proposée + +Séparer l'installation des bibliothèques applicatives du store des outils existants. Télécharger +métadonnées et archives avec le navigateur, vérifier SHA-512, refuser scripts d'installation et +extensions natives, résoudre les plages semver et garder les arêtes du graphe ainsi que plusieurs +versions d'un même paquet. Les peers requis doivent être satisfaits par des racines explicites ou +dépendances directes compatibles ; un conflit est une erreur. Les dépendances optionnelles ne sont +pas installées dans cette première version. + +`webfront-packages.lock.json` enregistre racines, versions exactes, intégrités et graphe. Les sources +sont conservées dans un cache par nom/version/intégrité. L'écriture du lock constitue le point de +publication de l'installation ; un échec peut laisser du cache inutilisé, sans changer le lock. + +Un Worker exécute esbuild/WASM pour les entrées JS/TS/JSX/TSX, CSS et ressources. Un filesystem +virtuel résout les imports du projet et des paquets, leurs exports navigateur et modules CommonJS. +Les lectures du projet transitent par les callbacks C++ bornés existants. Les imports réseau, API +Node absentes et exports privés échouent explicitement. Les bibliothèques ne sont pas exécutées +pour découvrir leurs exports ou lancer leurs scripts d'installation. + +`wf preview` publie les résultats puis les affiche dans la même fenêtre. L'aperçu utilise le bridge +ordinaire, y compris les erreurs et les Promises. Ctrl+C termine un build navigateur ; aucun +processus C++ de compilation ou shell n'est lancé. La transformation TS n'effectue pas de typecheck. + +## Alternatives et conséquences + +- Un service distant de bundling introduirait une dépendance de construction externe et un autre + contrat de confiance ; les sources sont ici construites localement. +- Des polyfills Node généraux ou l'émulation de scripts npm étendraient fortement le contrat ; ils + restent hors périmètre. Les paquets doivent être utilisables dans un navigateur. +- Le compilateur WASM est téléchargé à la demande ; son poids n'affecte pas le binaire initial. +- Une nouvelle installation peut recalculer des plages transitives ; le diff du lock doit être + revu. Preview/embed réutilisent exactement le graphe local déjà verrouillé. Une commande de + restauration du cache depuis le lock sur une nouvelle machine reste à concevoir. + +## Règles et vérification + +Ne pas aplatir toutes les versions sous un nom unique. Préserver l'installation existante après +échec ou annulation. Borner téléchargements, décompression, nombre de paquets et temps de build. +Tester transitivité, cycles, versions multiples, peers, intégrité, exports conditionnels et imports +non disponibles. La preuve navigateur doit utiliser le vrai compilateur WASM et un registre local. + +## Références + +- [Environnement développeur](../DEVELOPER_ENVIRONMENT.md), [ADR-013](ADR-013-bootstrap-developpeur-a-la-demande.md), + [ADR-003](ADR-003-protocole-binaire-et-bornes.md), [ADR-010](ADR-010-composants-et-outils-optionnels.md). diff --git a/docs/adr/ADR-015-ressources-generees-par-application.md b/docs/adr/ADR-015-ressources-generees-par-application.md new file mode 100644 index 00000000..8eed2ced --- /dev/null +++ b/docs/adr/ADR-015-ressources-generees-par-application.md @@ -0,0 +1,59 @@ +# ADR-015 : Générer les ressources embarquées dans le projet de l'application + +## Versions + +| Version | Date | État | Auteur | Évolution | Commit | +| --- | --- | --- | --- | --- | --- | +| 0.1 | 2026-10-20 | Proposée | Ambroise Leclerc | Proposition et première implémentation de wf embed et du parcours hors ligne. | À renseigner après intégration. | + +## Statut et date + +**Proposée le 2026-10-20.** Le parcours PI démontre une génération navigateur, sa compilation puis +l'exécution hors projet/cache avec WKWebView. Les autres moteurs nécessitent leur validation. + +## Contexte + +Les providers React/Babel fournis par WebFront imposent une sélection et une maintenance de +bibliothèques au projet. L'application doit pouvoir choisir ses versions et n'embarquer que les +ressources construites pour son interface, sans déplacer une chaîne Node chez son développeur. + +## Décision proposée + +`wf embed --output ` construit les ressources avec le graphe installé, +ajoute la page HTML et produit un provider header-only `webfront::fs::`. Il contient +JS/CSS/ressources compressées avec les paramètres fflate déterministes existants : niveau 9, +mem 8, mtime 0, puis mots 64 bits big-endian, padding exclu de `dataSize`, encodage gzip. +Les routes conservent leurs extensions et donc leurs types MIME, dont `application/wasm`. + +Le provider conserve les notices des dépendances et leurs versions/intégrités. Sa génération ne +contient ni date courante, ni chemin absolu du poste, ni identifiant aléatoire. Le C++ reçoit les +chunks dans un staging, puis remplace le header une fois l'écriture achevée. Les chemins relatifs +et leurs parents existants sont vérifiés pour refuser traversal et symlinks sortant du projet. + +La recompilation reste une action explicite du développeur. La distribution utilise +`NativeAppWithAssets` sans projet local, callbacks de développement ni téléchargement. +Le bridge embarqué reste celui de WebFront, en priorité sur les providers applicatifs. +Conserver les providers historiques pour les consommateurs existants ; leur retrait n'est pas +une conséquence automatique de cette proposition. + +## Alternatives et conséquences + +- Distribuer le cache et des fichiers locaux maintiendrait une dépendance au poste de développement. +- Générer par une chaîne Node obligatoire contredirait l'autonomie du parcours visé. +- Le header et les temps de compilation croissent avec l'interface ; le coût appartient au projet + qui choisit ces dépendances. Le binaire final n'embarque pas l'outillage de construction. +- Ce provider ne garantit pas que l'application finale n'effectue aucun accès réseau : la démo + utilise uniquement des imports assemblés localement, mais le code applicatif reste responsable + de ses éventuels appels réseau. + +## Règles et vérification + +Tester les octets décompressés, le padding, la stabilité à entrées identiques et les erreurs de +publication. Compiler le header réellement produit par le navigateur dans un second exécutable, +puis démarrer celui-ci depuis un répertoire vide, sans racine locale ni callbacks développeur. +Le test vérifie l'interface React et le résultat PI via le bridge. + +## Références + +- [Environnement développeur](../DEVELOPER_ENVIRONMENT.md), [ADR-009](ADR-009-modules-et-assets-reproductibles.md), + [ADR-014](ADR-014-construction-javascript-dans-le-browser.md), [ADR-002](ADR-002-systemes-de-fichiers-composables.md). diff --git a/docs/adr/README.md b/docs/adr/README.md index 9be0db73..8ecdc981 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -1,8 +1,9 @@ # WebFront architecture decision records This directory describes WebFront’s architectural choices and the constraints to preserve -when making changes or generating code. It contains **12 ADRs**, with unique numbers. -The current state corresponds to commit `b031ab5` dated **2026-10-19**. Each ADR is versioned +when making changes or generating code. It contains **15 ADRs**, with unique numbers (12 accepted decisions and 3 proposals). +The accepted baseline corresponds to commit `b031ab5` dated **2026-10-19**; +the browser-powered development proposals are dated **2026-10-20**. Each ADR is versioned according to the decision’s creation and its significant changes in the Git history. The ADRs themselves are written in French. @@ -20,7 +21,7 @@ latest version. A compatible addition or clarification increments the minor vers a backend or contract may introduce a major version. The status “Acceptée” (Accepted) means that the choice recorded in that version has been integrated into the project. -The author of every version is **Ambroise Leclerc**. Dates come from the commits +The author of every version is **Ambroise Leclerc**. Dates of accepted historical versions come from the commits (`git show --format=%as`), searched across all retained branches. The founding intent around 2020 — targeting C++23, anticipating its networking facilities through standalone ASIO and decoupling web resources from storage — remains described in the relevant ADRs’ context. @@ -51,6 +52,9 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | [ADR-010](ADR-010-composants-et-outils-optionnels.md) | Extending WebFront through optional components and development tools | Accepted | 2026-10-14 | 1.5 — 2026-10-16 | | [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.1 — 2026-10-20 | +| [ADR-014](ADR-014-construction-javascript-dans-le-browser.md) | Resolving npm dependencies and building inside the browser | Proposée | 2026-10-20 | 0.1 — 2026-10-20 | +| [ADR-015](ADR-015-ressources-generees-par-application.md) | Generating application-owned embedded resources | Proposée | 2026-10-20 | 0.1 — 2026-10-20 | Numbering follows the reading topics; milestones and individual file histories provide the chronology, which does not follow the numerical order. @@ -74,6 +78,7 @@ the chronology, which does not follow the numerical order. | A new engine or changes to window lifecycle | 006, 007, 008 | | Components, the terminal or installed tools | 004, 006, 008, 010 | | Diagnostics and log transport | 006, 011 | +| Downloaded development environment, npm libraries and generated application assets | 008, 009, 010, 013, 014, 015 | ADRs explain decisions; [AGENTS.md](../../AGENTS.md) sets out working instructions, the [README](../../README.md) provides the user journey, and specialist documents define @@ -82,6 +87,7 @@ with tests; do not implicitly change the contract to make the contradiction disa ## Maintaining the register +Proposals use their actual proposal date and remain proposed until integration/validation. Each ADR starts with a **Versions** table listing version, date, status, author, change and commit. Version **1.0** corresponds to the decision’s initial creation, dated to the historical commit that introduces it. Each significant architectural change adds a row dated to its @@ -90,7 +96,7 @@ Do not replace historical dates with the date of an editorial change to the docu Keep previous rows and update the current version in the index. - Use one `ADR-NNN-description.md` file per decision and one row in this index. The next number - is **ADR-013**. Retain historical numbers and files. + is **ADR-016**. Retain historical numbers and files. - For a new decision that has not been integrated, use **Proposée** (Proposed), its actual proposal date and validation criteria; do not assign an artificial historical commit date. - After integration, record the date and supporting commits, the accepted negative diff --git a/docs/images/life-preview.png b/docs/images/life-preview.png new file mode 100644 index 00000000..a110ebb1 Binary files /dev/null and b/docs/images/life-preview.png differ diff --git a/include/DeveloperApp.hpp b/include/DeveloperApp.hpp new file mode 100644 index 00000000..ff15100f --- /dev/null +++ b/include/DeveloperApp.hpp @@ -0,0 +1,97 @@ +/// @brief Opt-in browser-powered developer environment. Downloaded code has project/bridge authority. +#pragma once + +#include "system/DeveloperFS.hpp" +#include "system/DeveloperReleaseData.hpp" +#include "WebFront.hpp" + +namespace webfront { + +struct DeveloperBootstrapOptions { + /// HTTPS npm tarball URL, or same-origin URL for local provisioning/tests. + std::string environment; + /// Trusted SHA-512 SRI of that exact tarball, supplied independently of its download. + std::string integrity; + std::string registry{"https://registry.npmjs.org/"}; +}; + +namespace developer { +/// The project is the document root of the protected bridge. Its callbacks write the project, so a +/// WebSocket without an Origin header (not a browser page) is refused. +inline WebFrontConfig projectConfig(WebFrontConfig config, const std::filesystem::path& projectDirectory) { + config.documentRoot = projectDirectory; + config.contentPolicy.allowMissingOrigin = false; + return config; +} + +inline void validateBootstrap(std::string_view mode, const std::filesystem::path& project, const DeveloperBootstrapOptions& options) { + if (mode != "developer") + throw std::invalid_argument("Unknown bootstrap mode"); + if (project.empty()) + throw std::invalid_argument("Developer bootstrap requires an explicit project directory"); + if (options.environment.empty() || !options.integrity.starts_with("sha512-")) + throw std::invalid_argument("Developer bootstrap requires an environment URL and trusted SHA-512 integrity"); +} +} // namespace developer + +template +class BasicDeveloperApp : public BasicWF, http::DefaultBuffersPolicy, Frontend> { + using Base = BasicWF, http::DefaultBuffersPolicy, Frontend>; + +public: + /// An explicit project is required before enabling development file operations. + explicit BasicDeveloperApp(std::filesystem::path projectDirectory = {}, WebFrontConfig config = {}) + : Base(developer::projectConfig(std::move(config), projectDirectory)), + project(projectDirectory.empty() ? std::filesystem::path{} : std::filesystem::canonical(projectDirectory)) { } + + void bootstrap(std::string_view mode, + DeveloperBootstrapOptions options = {.environment = std::string(developer::release::environment), + .integrity = std::string(developer::release::integrity)}) { + if (store) + throw std::logic_error("Developer bootstrap is already configured"); + developer::validateBootstrap(mode, project, options); + store = std::make_shared(project); + registerBridge("{\"environment\":" + json::quote(options.environment) + ",\"integrity\":" + json::quote(options.integrity) + + ",\"registry\":" + json::quote(options.registry) + "}"); + } + + void show(std::string_view page = {}) { + Base::show(page.empty() ? (store ? "webfront-bootstrap.html" : "index.html") : page); + } + +private: + void registerBridge(std::string config) { + using Bytes = std::vector; + using developer::Store; + this->cppFunction("webfront.developer.config", [config = std::move(config)] { + return config; + }); + expose<&Store::read, Bytes, std::string, std::uint64_t>("webfront.developer.read"); + expose<&Store::beginReplacing, std::string, std::string, bool>("webfront.developer.begin"); + expose<&Store::beginNew, std::string, std::string, bool>("webfront.developer.beginNew"); + expose<&Store::write, void, std::string, std::string, std::uint64_t, Bytes>("webfront.developer.write"); + expose<&Store::commit, void, std::string>("webfront.developer.commit"); + expose<&Store::abort, void, std::string>("webfront.developer.abort"); + } + + /// Registers a store operation as a bridge callback; the store stays alive as long as the callback. + template + void expose(std::string name) { + this->template cppFunction(std::move(name), [owned = store](Args... arguments) -> Result { + return ((*owned).*Member)(std::move(arguments)...); + }); + } + + std::filesystem::path project; + std::shared_ptr store; +}; + +#if defined(_WIN32) || defined(__APPLE__) || defined(__linux__) +using NativeApp = BasicDeveloperApp; + +/// Distribution form: generated resources, protected bridge and fallback; no developer file API. +template +using NativeAppWithAssets = BasicWF, http::DefaultBuffersPolicy, frontend::NativeWebViewFrontend>; +#endif + +} // namespace webfront diff --git a/include/WebFront.hpp b/include/WebFront.hpp index 4bfab292..548e4c76 100644 --- a/include/WebFront.hpp +++ b/include/WebFront.hpp @@ -531,3 +531,6 @@ using WebFrontWithFrontend = BasicWF{{ + {"js", js}, {"mjs", js}, {"htm", html}, {"html", html}, {"jpg", jpg}, {"jpeg", jpg}, {"css", css}, {"png", png}, + {"gif", gif}, {"json", json}, {"pdf", pdf}, {"ttf", ttf}, {"ico", ico}, {"svg", svg}, {"webp", webp}, {"csv", csv}, {"wasm", wasm}, + }}; if (e.starts_with('.')) e.remove_prefix(1); - if (e == "js" || e == "mjs") return js; - if (e == "htm" || e == "html") return html; - if (e == "jpg" || e == "jpeg") return jpg; - if (e == "css") return css; - if (e == "png") return png; - if (e == "gif") return gif; - if (e == "json") return json; - if (e == "pdf") return pdf; - if (e == "ttf") return ttf; - if (e == "ico") return ico; - if (e == "svg") return svg; - if (e == "webp") return webp; - if (e == "csv") return csv; + for (const auto& mapping : mappings) + if (e == mapping.extension) return mapping.type; return plain; } @@ -47,8 +44,9 @@ struct MimeType { "image/x-icon", "image/svg+xml", "image/webp", - "text/csv"}; - static_assert(names.size() == csv + 1, "MimeType names must match the Type enumerators"); + "text/csv", + "application/wasm"}; + static_assert(names.size() == wasm + 1, "MimeType names must match the Type enumerators"); return names[type]; } }; diff --git a/include/system/DeveloperBootstrapData.hpp b/include/system/DeveloperBootstrapData.hpp new file mode 100644 index 00000000..2f438be5 --- /dev/null +++ b/include/system/DeveloperBootstrapData.hpp @@ -0,0 +1,172 @@ +#pragma once + +#include +#include +#include +#include + +namespace webfront::fs::generated { + +struct DeveloperBootstrapData { + static constexpr std::string_view encoding{}; + static constexpr std::size_t dataSize{6195}; + static constexpr std::array data{ + 0x76617220753d6e65, 0x7720546578744465, 0x636f6465723b6173, 0x796e632066756e63, 0x74696f6e20702874, + 0x2c65297b6c657420, 0x6e3d537472696e67, 0x28653f3f2222292e, 0x73706c6974282f5c, 0x732b2f292e66696c, + 0x74657228613d3e61, 0x2e73746172747357, 0x6974682822736861, 0x3531322d2229292e, 0x6d617028613d3e61, + 0x2e73706c69742822, 0x3f22295b305d293b, 0x6966286e2e6c656e, 0x6774683d3d3d3029, 0x7468726f77206e65, + 0x77204572726f7228, 0x2254686520706163, 0x6b61676520686173, 0x206e6f205348412d, 0x35313220696e7465, + 0x677269747922293b, 0x69662821676c6f62, 0x616c546869732e63, 0x727970746f3f2e73, 0x7562746c65297468, + 0x726f77206e657720, 0x4572726f72282249, 0x6e74656772697479, 0x20636865636b7320, 0x6e65656420612073, + 0x656375726520636f, 0x6e74657874202868, 0x74747073206f7220, 0x6c6f63616c686f73, 0x742922293b6c6574, + 0x20723d6e65772055, 0x696e743841727261, 0x7928617761697420, 0x63727970746f2e73, 0x7562746c652e6469, + 0x6765737428225348, 0x412d353132222c74, 0x29292c6f3d227368, 0x613531322d222b62, 0x746f612841727261, + 0x792e66726f6d2872, 0x2c613d3e53747269, 0x6e672e66726f6d43, 0x686172436f646528, 0x6129292e6a6f696e, + 0x28222229293b6966, 0x28216e2e696e636c, 0x75646573286f2929, 0x7468726f77206e65, 0x77204572726f7228, + 0x60496e7465677269, 0x747920636865636b, 0x206661696c65643a, 0x2065787065637465, 0x6420247b6e5b305d, + 0x7d2c20676f742024, 0x7b6f7d60293b7265, 0x7475726e206f7d61, 0x73796e632066756e, 0x6374696f6e206428, + 0x742c653d32363834, 0x3335343536297b6c, 0x6574206e3d6e6577, 0x20426c6f62285b74, 0x5d292e7374726561, + 0x6d28292e70697065, 0x5468726f75676828, 0x6e6577204465636f, 0x6d7072657373696f, 0x6e53747265616d28, + 0x22677a6970222929, 0x2e67657452656164, 0x657228292c723d5b, 0x5d2c6f3d303b666f, 0x72286c657420613d, + 0x6177616974206e2e, 0x7265616428293b21, 0x612e646f6e653b61, 0x3d6177616974206e, 0x2e72656164282929, + 0x7b6966286f2b3d61, 0x2e76616c75652e6c, 0x656e6774682c6f3e, 0x65297468726f7720, 0x6177616974206e2e, + 0x63616e63656c2829, 0x2c6e657720457272, 0x6f72286054686520, 0x74617262616c6c20, 0x756e7061636b7320, + 0x746f206d6f726520, 0x7468616e20247b65, 0x7d20627974657360, 0x293b722e70757368, 0x28612e76616c7565, + 0x297d72657475726e, 0x206e65772055696e, 0x7438417272617928, 0x6177616974206e65, 0x7720426c6f622872, + 0x292e617272617942, 0x7566666572282929, 0x7d66756e6374696f, 0x6e206c28742c652c, 0x6e297b6c65742072, + 0x3d742e7375626172, 0x72617928652c652b, 0x6e292c6f3d722e69, 0x6e6465784f662830, 0x293b72657475726e, + 0x20752e6465636f64, 0x65286f3c303f723a, 0x722e737562617272, 0x617928302c6f2929, 0x7d66756e6374696f, + 0x6e207928742c652c, 0x6e297b696628745b, 0x655d263132382972, 0x657475726e20742e, 0x7375626172726179, + 0x28652b312c652b6e, 0x292e726564756365, 0x28286f2c61293d3e, 0x6f2a3235362b612c, 0x745b655d26313237, + 0x293b6c657420723d, 0x6c28742c652c6e29, 0x2e7472696d28293b, 0x696628212f5e5b30, 0x2d375d2a242f2e74, + 0x6573742872292974, 0x68726f77206e6577, 0x204572726f722822, 0x436f727275707420, 0x7461722068656164, + 0x657222293b726574, 0x75726e20723d3d3d, 0x22223f303a706172, 0x7365496e7428722c, 0x38297d66756e6374, + 0x696f6e2054287429, 0x7b6c657420653d30, 0x3b666f72286c6574, 0x206e3d303b6e3c35, 0x31323b2b2b6e2965, + 0x2b3d6e3e3d313438, 0x26266e3c3135363f, 0x33323a745b6e5d3b, 0x6966287928742c31, 0x34382c3829213d3d, + 0x65297468726f7720, 0x6e6577204572726f, 0x722822436f727275, 0x7074207461722068, 0x6561646572206368, + 0x65636b73756d2229, 0x7d66756e6374696f, 0x6e20532874297b6c, 0x657420653d7b7d2c, 0x6e3d303b666f7228, + 0x3b6e3c742e6c656e, 0x6774683b297b6c65, 0x7420723d742e696e, 0x6465784f66283332, 0x2c6e292c6f3d723c, + 0x303f4e614e3a4e75, 0x6d62657228752e64, 0x65636f646528742e, 0x7375626172726179, 0x286e2c722929293b, + 0x69662821286f3e30, 0x297c7c6e2b6f3e74, 0x2e6c656e67746829, 0x7468726f77206e65, 0x77204572726f7228, + 0x22436f7272757074, 0x2070617820686561, 0x64657222293b6c65, 0x7420613d752e6465, 0x636f646528742e73, + 0x7562617272617928, 0x722b312c6e2b6f2d, 0x3129292c693d612e, 0x696e6465784f6628, 0x223d22293b655b61, + 0x2e736c6963652830, 0x2c69295d3d612e73, 0x6c69636528692b31, 0x292c6e2b3d6f7d72, 0x657475726e20657d, + 0x66756e6374696f6e, 0x207a28742c65297b, 0x6c6574206e3d742e, 0x7375626172726179, 0x28652c652b353132, + 0x293b54286e293b6c, 0x657420723d79286e, 0x2c3132342c313229, 0x2c6f3d652b353132, 0x3b6966286f2b723e, + 0x742e6c656e677468, 0x297468726f77206e, 0x6577204572726f72, 0x28225472756e6361, 0x7465642074617220, + 0x6172636869766522, 0x293b72657475726e, 0x7b6865616465723a, 0x6e2c747970653a6e, 0x5b3135365d3d3d3d, + 0x303f2230223a5374, 0x72696e672e66726f, 0x6d43686172436f64, 0x65286e5b3135365d, 0x292c646174613a74, + 0x2e73756261727261, 0x79286f2c6f2b7229, 0x2c6e6578743a6f2b, 0x4d6174682e636569, 0x6c28722f35313229, + 0x2a3531327d7d6675, 0x6e6374696f6e2055, 0x28742c65297b7265, 0x7475726e20652b35, 0x31323e742e6c656e, + 0x6774687c7c742e73, 0x7562617272617928, 0x652c652b35313229, 0x2e6576657279286e, 0x3d3e6e3d3d3d3029, + 0x7d66756e6374696f, 0x6e20492874297b6c, 0x657420653d6c2874, 0x2c302c313030292c, 0x6e3d6c28742c3235, + 0x372c35293d3d3d22, 0x7573746172223f6c, 0x28742c3334352c31, 0x3535293a22223b72, 0x657475726e206e3f, + 0x60247b6e7d2f247b, 0x657d603a657d7661, 0x7220683d7b783a28, 0x742c65293d3e287b, 0x2e2e2e742c706178, + 0x3a532865292e7061, 0x74687d292c4c3a28, 0x742c65293d3e287b, 0x2e2e2e742c6c6f6e, 0x673a6c28652c302c, + 0x652e6c656e677468, 0x297d292c673a743d, 0x3e747d3b66756e63, 0x74696f6e206d2874, 0x297b6c657420653d, + 0x5b5d2c6e3d7b7d3b, 0x666f72286c657420, 0x723d303b21552874, 0x2c72293b297b6c65, 0x747b686561646572, + 0x3a6f2c747970653a, 0x612c646174613a69, 0x2c6e6578743a737d, 0x3d7a28742c72293b, 0x696628723d732c4f, + 0x626a6563742e6861, 0x734f776e28682c61, 0x29297b6e3d685b61, 0x5d286e2c69293b63, 0x6f6e74696e75657d, + 0x28613d3d3d223022, 0x7c7c613d3d3d2237, 0x22292626652e7075, 0x7368287b70617468, 0x3a6e2e7061783f3f, + 0x6e2e6c6f6e673f3f, 0x49286f292c627974, 0x65733a697d292c6e, 0x3d7b7d7d72657475, 0x726e20657d766172, + 0x20633d28742c652c, 0x2e2e2e6e293d3e74, 0x2e63707046756e63, 0x74696f6e28607765, 0x6266726f6e742e64, + 0x6576656c6f706572, 0x2e247b657d602928, 0x2e2e2e6e293b6173, 0x796e632066756e63, 0x74696f6e20672874, + 0x2c65297b6c657420, 0x6e3d5b5d2c723d30, 0x3b666f72283b3b29, 0x7b6c6574206f3d61, 0x7761697420632874, + 0x2c2272656164222c, 0x652c72293b696628, 0x6e2e70757368286f, 0x292c722b3d6f2e6c, 0x656e6774682c6f2e, + 0x6c656e6774683c32, 0x3632313434296272, 0x65616b3b69662872, 0x3e3235362a313032, 0x342a313032342974, + 0x68726f77206e6577, 0x204572726f722822, 0x50726f6a65637420, 0x66696c6520697320, 0x746f6f206c617267, + 0x6522297d72657475, 0x726e206e65772055, 0x696e743841727261, 0x7928617761697420, 0x6e657720426c6f62, + 0x286e292e61727261, 0x7942756666657228, 0x29297d6173796e63, 0x2066756e6374696f, 0x6e206a28742c7b69, + 0x643a652c70617468, 0x3a6e2c6279746573, 0x3a727d2c6f297b66, 0x6f72286c65742061, 0x3d303b613c722e6c, + 0x656e6774687c7c61, 0x3d3d3d303b612b3d, 0x323632313434296f, 0x3f2e7468726f7749, 0x6641626f72746564, + 0x28292c6177616974, 0x206328742c227772, 0x697465222c652c6e, 0x2c612c722e737562, 0x617272617928612c, + 0x612b323632313434, 0x29297d6173796e63, 0x2066756e6374696f, 0x6e206628742c652c, 0x6e2c7b6469726563, + 0x746f72793a723d21, 0x302c7369676e616c, 0x3a6f2c7265706c61, 0x63653a613d21307d, 0x3d7b7d297b6c6574, + 0x20693d6177616974, 0x206328742c613f22, 0x626567696e223a22, 0x626567696e4e6577, 0x222c652c72293b74, + 0x72797b666f72286c, 0x65745b732c245d6f, 0x66206e2961776169, 0x74206a28742c7b69, 0x643a692c70617468, + 0x3a732c6279746573, 0x3a247d2c6f293b6f, 0x3f2e7468726f7749, 0x6641626f72746564, 0x28292c6177616974, + 0x206328742c22636f, 0x6d6d6974222c6929, 0x7d63617463682873, 0x297b7468726f7720, 0x6177616974206328, + 0x742c2261626f7274, 0x222c69292e636174, 0x63682828293d3e7b, 0x7d292c737d7d6173, 0x796e632066756e63, + 0x74696f6e20422874, 0x2c65297b6c657420, 0x6e3d5b5d2c723d30, 0x3b666f72283b3b29, 0x7b6c65747b646f6e, + 0x653a6f2c76616c75, 0x653a617d3d617761, 0x697420742e726561, 0x6428293b6966286f, 0x2972657475726e20, + 0x6e3b696628722b3d, 0x612e6c656e677468, 0x2c723e6529746872, 0x6f77206e65772045, 0x72726f722822436f, + 0x6d70726573736564, 0x20646f776e6c6f61, 0x6420657863656564, 0x7320697473206279, 0x7465206c696d6974, + 0x22293b6e2e707573, 0x682861297d7d6173, 0x796e632066756e63, 0x74696f6e20462874, 0x2c65297b7472797b, + 0x72657475726e2061, 0x7761697420422874, 0x2c65297d63617463, 0x68286e297b746872, 0x6f77206177616974, + 0x20742e63616e6365, 0x6c28292e63617463, 0x682828293d3e7b7d, 0x292c6e7d66696e61, 0x6c6c797b742e7265, + 0x6c656173654c6f63, 0x6b28297d7d617379, 0x6e632066756e6374, 0x696f6e206228742c, 0x653d36342a313032, + 0x342a31303234297b, 0x69662821742e6f6b, 0x297468726f77206e, 0x6577204572726f72, 0x2860446f776e6c6f, + 0x61643a2048545450, 0x20247b742e737461, 0x7475737d60293b69, 0x66284e756d626572, 0x28742e6865616465, + 0x72732e6765742822, 0x636f6e74656e742d, 0x6c656e6774682229, 0x293e65297468726f, 0x77206e6577204572, + 0x726f722822436f6d, 0x7072657373656420, 0x646f776e6c6f6164, 0x2065786365656473, 0x2069747320627974, + 0x65206c696d697422, 0x293b72657475726e, 0x206e65772055696e, 0x7438417272617928, 0x6177616974206e65, + 0x7720426c6f622861, 0x7761697420462874, 0x2e626f64792e6765, 0x7452656164657228, 0x292c6529292e6172, + 0x7261794275666665, 0x722829297d766172, 0x204f3d2f5b5c5c5c, 0x303a2a3f223c3e7c, 0x5d2f2c433d743d3e, + 0x742e73706c697428, 0x222f22292e736f6d, 0x6528653d3e21657c, 0x7c653d3d3d222e22, 0x7c7c653d3d3d222e, + 0x2e22293b66756e63, 0x74696f6e20762874, 0x297b72657475726e, 0x20747970656f6620, 0x74213d2273747269, + 0x6e67227c7c21747c, 0x7c4f2e7465737428, 0x74293f21303a4328, 0x74297d7661722077, 0x3d743d3e21762874, + 0x292c503d6e657720, 0x546578744465636f, 0x6465723b66756e63, 0x74696f6e20412874, 0x2c65297b69662821, + 0x652e706174682e73, 0x7461727473576974, 0x6828227061636b61, 0x67652f2229297468, 0x726f77206e657720, + 0x4572726f72282249, 0x6e76616c69642065, 0x6e7669726f6e6d65, 0x6e74206172636869, 0x766520726f6f7422, + 0x293b6c6574206e3d, 0x652e706174682e73, 0x6c6963652838293b, 0x6966282177286e29, 0x7c7c742e68617328, + 0x6e29297468726f77, 0x206e657720457272, 0x6f722822496e7661, 0x6c6964206f722064, 0x75706c6963617465, + 0x20656e7669726f6e, 0x6d656e7420706174, 0x6822293b742e7365, 0x74286e2c652e6279, 0x746573297d66756e, + 0x6374696f6e204c28, 0x74297b6c65742065, 0x3d6e6577204d6170, 0x3b666f72286c6574, 0x206e206f66206d28, + 0x7429294128652c6e, 0x293b72657475726e, 0x20657d66756e6374, 0x696f6e205228742c, 0x65297b7265747572, + 0x6e20742e70726f74, 0x6f636f6c213d3d31, 0x7c7c217728742e65, 0x6e747279293f2131, 0x3a652e6861732874, + 0x2e656e747279297d, 0x6173796e63206675, 0x6e6374696f6e2078, 0x28742c65297b6177, 0x616974207028742c, + 0x65293b6c6574206e, 0x3d4c286177616974, 0x2064287429293b69, 0x6628216e2e686173, 0x2822656e7669726f, + 0x6e6d656e742e6a73, 0x6f6e222929746872, 0x6f77206e65772045, 0x72726f722822456e, 0x7669726f6e6d656e, + 0x7420617263686976, 0x6520686173206e6f, 0x20656e7669726f6e, 0x6d656e742e6a736f, 0x6e22293b6c657420, + 0x723d4a534f4e2e70, 0x6172736528502e64, 0x65636f6465286e2e, 0x6765742822656e76, 0x69726f6e6d656e74, + 0x2e6a736f6e222929, 0x293b696628215228, 0x722c6e2929746872, 0x6f77206e65772045, 0x72726f722822556e, + 0x737570706f727465, 0x642057656246726f, 0x6e7420646576656c, 0x6f70657220656e76, 0x69726f6e6d656e74, + 0x22293b7265747572, 0x6e7b66696c65733a, 0x6e2c6d616e696665, 0x73743a727d7d7661, 0x72206b3d222e7765, + 0x6266726f6e742f64, 0x6576656c6f706572, 0x2f656e7669726f6e, 0x6d656e742e74677a, 0x223b6173796e6320, + 0x66756e6374696f6e, 0x204e28742c65297b, 0x7472797b6c657420, 0x6e3d617761697420, 0x6728742c6b293b72, + 0x657475726e206177, 0x6169742078286e2c, 0x65292c6e7d636174, 0x63687b7265747572, 0x6e206e756c6c7d7d, + 0x6173796e63206675, 0x6e6374696f6e2057, 0x28742c65297b6c65, 0x74206e3d6e657720, 0x55524c28742e656e, + 0x7669726f6e6d656e, 0x742c6c6f63617469, 0x6f6e2e6872656629, 0x3b6966286e2e7072, 0x6f746f636f6c213d, + 0x3d2268747470733a, 0x2226266e2e6f7269, 0x67696e213d3d6c6f, 0x636174696f6e2e6f, 0x726967696e297468, + 0x726f77206e657720, 0x4572726f72282254, 0x686520656e766972, 0x6f6e6d656e74206d, 0x7573742075736520, + 0x4854545053206f72, 0x2074686520617070, 0x6c69636174696f6e, 0x206f726967696e22, 0x293b6c657420723d, + 0x6177616974206528, 0x6e293b6966282172, 0x2e6f6b297468726f, 0x77206e6577204572, 0x726f722860456e76, + 0x69726f6e6d656e74, 0x20646f776e6c6f61, 0x643a204854545020, 0x247b722e73746174, 0x75737d60293b7265, + 0x7475726e20622872, 0x297d66756e637469, 0x6f6e20442874297b, 0x72657475726e2174, 0x7c7c217728742e61, + 0x726368697665293f, 0x21313a537472696e, 0x6728742e696e7465, 0x6772697479292e73, 0x7461727473576974, + 0x6828227368613531, 0x322d22297d66756e, 0x6374696f6e204828, 0x742c65297b726574, 0x75726e204f626a65, + 0x63742e66726f6d45, 0x6e7472696573284f, 0x626a6563742e656e, 0x747269657328742e, 0x7374617274657273, + 0x3f3f7b7d292e6d61, 0x7028285b6e2c725d, 0x293d3e7b69662821, 0x4428722929746872, 0x6f77206e65772045, + 0x72726f722822496e, 0x76616c6964207069, 0x6e6e656420737461, 0x72746572206d6574, 0x616461746122293b, + 0x72657475726e5b6e, 0x2c7b75726c3a6e65, 0x772055524c28722e, 0x617263686976652c, 0x65292e687265662c, + 0x696e746567726974, 0x793a722e696e7465, 0x67726974797d5d7d, 0x29297d6173796e63, 0x2066756e6374696f, + 0x6e204528742c652c, 0x6e3d66657463682c, 0x723d28293d3e7b7d, 0x297b6c6574206f3d, 0x6177616974204e28, + 0x742c652e696e7465, 0x6772697479293b6f, 0x3f7228225573696e, 0x6720766572696669, 0x6564206361636865, + 0x6420646576656c6f, 0x70657220656e7669, 0x726f6e6d656e7422, 0x293a28722822446f, 0x776e6c6f6164696e, + 0x6720646576656c6f, 0x70657220656e7669, 0x726f6e6d656e7422, 0x292c6f3d61776169, 0x74205728652c6e29, + 0x293b6c65747b6669, 0x6c65733a612c6d61, 0x6e69666573743a69, 0x7d3d617761697420, 0x78286f2c652e696e, + 0x7465677269747929, 0x2c733d4828692c6e, 0x65772055524c2865, 0x2e656e7669726f6e, 0x6d656e742c6c6f63, + 0x6174696f6e2e6872, 0x656629293b726574, 0x75726e2061776169, 0x74206628742c222e, 0x77656266726f6e74, + 0x2f646576656c6f70, 0x65722f656e766972, 0x6f6e6d656e74222c, 0x61292c6177616974, 0x206628742c6b2c6e, + 0x6577204d6170285b, 0x5b226f7574707574, 0x222c6f5d5d292c7b, 0x6469726563746f72, 0x793a21317d292c7b, + 0x75726c3a602f7765, 0x6266726f6e742f64, 0x6576656c6f706572, 0x2f656e7669726f6e, 0x6d656e742f247b69, + 0x2e656e7472797d60, 0x2c636f6e6669673a, 0x7b2e2e2e652c7374, 0x6172746572733a73, 0x7d7d7d6966287479, + 0x70656f6620646f63, 0x756d656e743c2275, 0x222626646f63756d, 0x656e742e67657445, 0x6c656d656e744279, + 0x4964282272657472, 0x792229297b6c6574, 0x20743d646f63756d, 0x656e742e67657445, 0x6c656d656e744279, + 0x4964282273746174, 0x757322292c653d64, 0x6f63756d656e742e, 0x676574456c656d65, 0x6e74427949642822, + 0x726574727922292c, 0x6e3d6173796e6328, 0x293d3e7b652e6869, 0x6464656e3d21303b, 0x7472797b61776169, + 0x742077656246726f, 0x6e742e7265616479, 0x3b6c657420723d4a, 0x534f4e2e70617273, 0x6528617761697420, + 0x632877656246726f, 0x6e742c22636f6e66, 0x69672229292c7b75, 0x726c3a6f2c636f6e, 0x6669673a617d3d61, + 0x7761697420452877, 0x656246726f6e742c, 0x722c66657463682c, 0x733d3e7b742e7465, 0x7874436f6e74656e, + 0x743d737d293b6177, 0x6169742861776169, 0x7420696d706f7274, 0x286f29292e6d6f75, 0x6e74287b62726964, + 0x67653a7765624672, 0x6f6e742c636f6e66, 0x69673a612c746572, 0x6d696e616c3a646f, 0x63756d656e742e67, + 0x6574456c656d656e, 0x7442794964282274, 0x65726d696e616c22, 0x292c707265766965, 0x773a646f63756d65, + 0x6e742e676574456c, 0x656d656e74427949, 0x6428227072657669, 0x657722297d292c74, 0x2e74657874436f6e, + 0x74656e743d224465, 0x76656c6f70657220, 0x656e7669726f6e6d, 0x656e742072656164, 0x792e205479706520, + 0x77662068656c702e, 0x227d636174636828, 0x72297b742e746578, 0x74436f6e74656e74, 0x3d60426f6f747374, + 0x726170206661696c, 0x65643a20247b722e, 0x6d6573736167657d, 0x602c652e68696464, 0x656e3d21317d7d3b, + 0x652e616464457665, 0x6e744c697374656e, 0x65722822636c6963, 0x6b222c6e292c6e28, 0x297d0a0000000000 + }; +}; + +} // namespace webfront::fs::generated diff --git a/include/system/DeveloperFS.hpp b/include/system/DeveloperFS.hpp new file mode 100644 index 00000000..f8ac16cf --- /dev/null +++ b/include/system/DeveloperFS.hpp @@ -0,0 +1,58 @@ +/// @brief Bootstrap assets and the explicit developer project's published browser resources. +#pragma once + +#include "DeveloperBootstrapData.hpp" +#include "DeveloperIndexHtmlData.hpp" +#include "DeveloperStore.hpp" +#include "IndexFS.hpp" + +namespace webfront::fs { + +class DeveloperFS { +public: + explicit DeveloperFS(std::filesystem::path project) { + if (!project.empty()) + root = std::filesystem::canonical(project); + } + + std::optional open(std::filesystem::path file) const { + const auto path = file.relative_path().generic_string(); + if (auto embedded = embeddedResource(path)) + return embedded; + constexpr std::string_view prefix = "webfront/developer/"; + if (!root.empty() && path.starts_with(prefix)) { + const auto relative = std::string_view(path).substr(prefix.size()); + // Only published resources, never source files, staging or the cached archive. + if (!relative.starts_with("environment/") && !relative.starts_with("preview/")) + return {}; + if (auto published = openPublished(relative)) + return published; + } + return IndexFS::open(file); + } + +private: + static std::optional embeddedResource(const std::string& path) { + if (path == "WebFront.js") + return File{IndexFS::WebFrontJs{}}; + if (path == "webfront-bootstrap.html") + return File{generated::DeveloperIndexHtmlData{}}; + if (path == "webfront-bootstrap.mjs") + return File{generated::DeveloperBootstrapData{}}; + return std::nullopt; + } + + std::optional openPublished(std::string_view relative) const { + try { + const auto target = developer::projectPath(root, ".webfront/developer/" + std::string(relative)); + std::ifstream stream(target, std::ios::binary); + if (stream) + return File{std::move(stream)}; + } catch (const std::exception&) { } + return std::nullopt; + } + + std::filesystem::path root; +}; + +} // namespace webfront::fs diff --git a/include/system/DeveloperFiles.hpp b/include/system/DeveloperFiles.hpp new file mode 100644 index 00000000..074f8b4f --- /dev/null +++ b/include/system/DeveloperFiles.hpp @@ -0,0 +1,86 @@ +/// @brief Path and file helpers of the developer store: project containment, staging and replacement. +#pragma once + +#include "DeveloperPaths.hpp" + +#include +#include +#include + +namespace webfront::developer { + +inline constexpr std::size_t chunkSize = 256 * 1024; +inline constexpr std::uint64_t maxTransactionBytes = 256 * 1024 * 1024; +inline constexpr std::size_t maxTransactions = 8; +/// A transaction untouched for this long is abandoned: its browser reloaded or disconnected. +inline constexpr std::chrono::minutes defaultAbandonedAfter{10}; +/// Staging left by a crashed process is removed at startup once it is this old. +inline constexpr std::chrono::hours staleStagingAfter{1}; + +// Numbers the staging directories of every store in the process. +inline std::atomic stagingCounter{0}; + +inline void seek(std::ifstream& file, std::uint64_t offset, const std::string& failure) { + if (offset > static_cast(std::numeric_limits::max())) + throw std::invalid_argument("Invalid read offset"); + file.seekg(static_cast(offset)); + if (!file) + throw std::runtime_error(failure); +} + +inline std::ifstream openForReading(const std::filesystem::path& source, const std::string& path, std::uint64_t offset) { + const std::string failure = "Cannot read project file: " + path; + if (!std::filesystem::is_regular_file(source)) + throw std::runtime_error(failure); + std::ifstream file(source, std::ios::binary); + if (!file) + throw std::runtime_error(failure); + seek(file, offset, "Cannot seek project file: " + path); + return file; +} + + +inline std::pair createStaging(const std::filesystem::path& stagingRoot) { + for (;;) { + auto id = std::to_string(++stagingCounter); + auto directory = stagingRoot / id; + if (std::filesystem::create_directory(directory)) + return {std::move(id), std::move(directory)}; + } +} + +// Moves the staged files over the target, restoring the previous content if that fails. +inline void replaceTarget(const std::filesystem::path& target, bool replace, const std::filesystem::path& source, const std::filesystem::path& backup) { + std::filesystem::create_directories(target.parent_path()); + // A backup left by a crashed process must not make the rename below fail. + std::filesystem::remove_all(backup); + const bool exists = std::filesystem::exists(std::filesystem::symlink_status(target)); + if (exists && !replace) + throw std::runtime_error("Starter destination already exists"); + if (exists) + std::filesystem::rename(target, backup); + try { + std::filesystem::rename(source, target); + } catch (...) { + if (exists) + std::filesystem::rename(backup, target); + throw; + } +} + +inline void removeStaleStaging(const std::filesystem::path& root) { + std::error_code error; + // The staging directory may be a symbolic link: never clean up outside the project. + std::filesystem::path stagingRoot; + try { + stagingRoot = projectPath(root, ".webfront/developer/staging"); + } catch (const std::exception&) { + return; + } + const auto now = std::filesystem::file_time_type::clock::now(); + for (const auto& entry : std::filesystem::directory_iterator(stagingRoot, error)) + if (const auto written = entry.last_write_time(error); !error && now - written >= staleStagingAfter) + std::filesystem::remove_all(entry.path(), error); +} + +} // namespace webfront::developer diff --git a/include/system/DeveloperIndexHtmlData.hpp b/include/system/DeveloperIndexHtmlData.hpp new file mode 100644 index 00000000..10a5642c --- /dev/null +++ b/include/system/DeveloperIndexHtmlData.hpp @@ -0,0 +1,36 @@ +#pragma once + +#include +#include +#include +#include + +namespace webfront::fs::generated { + +struct DeveloperIndexHtmlData { + static constexpr std::string_view encoding{}; + static constexpr std::size_t dataSize{758}; + static constexpr std::array data{ + 0x3c21646f63747970, 0x652068746d6c3e0a, 0x3c68746d6c206c61, 0x6e673d22656e223e, 0x0a3c6d6574612063, + 0x6861727365743d22, 0x7574662d38223e0a, 0x3c6d657461206e61, 0x6d653d2276696577, 0x706f72742220636f, + 0x6e74656e743d2277, 0x696474683d646576, 0x6963652d77696474, 0x682c20696e697469, 0x616c2d7363616c65, + 0x3d31223e0a3c7469, 0x746c653e57656246, 0x726f6e7420646576, 0x656c6f7065722062, 0x6f6f747374726170, + 0x3c2f7469746c653e, 0x0a3c7374796c653e, 0x626f64797b6d6172, 0x67696e3a303b6261, 0x636b67726f756e64, + 0x3a23313431383231, 0x3b636f6c6f723a23, 0x6538656466343b66, 0x6f6e743a31357078, 0x2073797374656d2d, + 0x75697d6865616465, 0x727b70616464696e, 0x673a313670787d62, 0x7574746f6e7b6d61, 0x7267696e3a387078, + 0x7d237465726d696e, 0x616c7b6865696768, 0x743a343576683b70, 0x616464696e673a38, 0x70787d2370726576, + 0x6965777b77696474, 0x683a313030253b68, 0x65696768743a3435, 0x76683b626f726465, 0x723a303b6261636b, + 0x67726f756e643a77, 0x686974657d707265, 0x7b77686974652d73, 0x706163653a707265, 0x2d777261707d3c2f, + 0x7374796c653e0a3c, 0x6865616465723e3c, 0x7374726f6e673e57, 0x656246726f6e7420, 0x646576656c6f7065, + 0x723c2f7374726f6e, 0x673e3c7072652069, 0x643d227374617475, 0x73223e5374617274, 0x696e672074686520, + 0x646576656c6f7065, 0x7220656e7669726f, 0x6e6d656e74e280a6, 0x3c2f7072653e3c62, 0x7574746f6e206964, + 0x3d22726574727922, 0x2068696464656e3e, 0x52657472793c2f62, 0x7574746f6e3e3c2f, 0x6865616465723e0a, + 0x3c6469762069643d, 0x227465726d696e61, 0x6c223e3c2f646976, 0x3e3c696672616d65, 0x2069643d22707265, + 0x7669657722207469, 0x746c653d22417070, 0x6c69636174696f6e, 0x2070726576696577, 0x222068696464656e, + 0x3e3c2f696672616d, 0x653e0a3c73637269, 0x7074207372633d22, 0x2f57656246726f6e, 0x742e6a73223e3c2f, + 0x7363726970743e0a, 0x3c73637269707420, 0x747970653d226d6f, 0x64756c6522207372, 0x633d222f77656266, + 0x726f6e742d626f6f, 0x7473747261702e6d, 0x6a73223e3c2f7363, 0x726970743e0a3c2f, 0x68746d6c3e0a0000 + }; +}; + +} // namespace webfront::fs::generated diff --git a/include/system/DeveloperPaths.hpp b/include/system/DeveloperPaths.hpp new file mode 100644 index 00000000..36c87403 --- /dev/null +++ b/include/system/DeveloperPaths.hpp @@ -0,0 +1,34 @@ +/// @brief Path containment helpers of the developer store. +#pragma once + +#include "ToolStore.hpp" + +namespace webfront::developer { + +// Resolve existing parents too: a symlink must never turn a relative project path into an escape. +inline std::filesystem::path projectPath(const std::filesystem::path& root, std::string_view relative) { + const auto path = root / fs::tools::safeRelativePath(relative); + const auto resolved = std::filesystem::weakly_canonical(path); + auto base = root.begin(); + auto part = resolved.begin(); + for (; base != root.end(); ++base, ++part) + if (part == resolved.end() || *part != *base) + throw std::invalid_argument("Path escapes the developer project"); + return path; +} + +inline bool isParent(const std::filesystem::path& parent, const std::filesystem::path& child) { + auto part = child.begin(); + for (const auto& component : parent) { + if (part == child.end() || *part != component) + return false; + ++part; + } + return true; +} + +inline bool related(const std::filesystem::path& first, const std::filesystem::path& second) { + return isParent(first, second) || isParent(second, first); +} + +} // namespace webfront::developer diff --git a/include/system/DeveloperReleaseData.hpp b/include/system/DeveloperReleaseData.hpp new file mode 100644 index 00000000..635675f7 --- /dev/null +++ b/include/system/DeveloperReleaseData.hpp @@ -0,0 +1,10 @@ +#pragma once + +// Pinned developer distribution. Regenerate with tools/developer/build.mjs --refresh-bootstrap. +#include + +namespace webfront::developer::release { +inline constexpr std::string_view version{"0.3.1"}; +inline constexpr std::string_view environment{"https://ambroise-leclerc.github.io/WebFront/developer/0.3.1/environment.tgz"}; +inline constexpr std::string_view integrity{"sha512-dXjGKIxPze87x2c8UiyJ0ij+ekFX5g0Cn2jgtVnQQp6qhE7kw6rkBE2nLvinW12gPqPUBBpKdXvBpp5jpBrA/A=="}; +} // namespace webfront::developer::release diff --git a/include/system/DeveloperStore.hpp b/include/system/DeveloperStore.hpp new file mode 100644 index 00000000..56b8346c --- /dev/null +++ b/include/system/DeveloperStore.hpp @@ -0,0 +1,197 @@ +/// @brief Explicit development project access and staged publication, without shell access. +#pragma once + +#include "DeveloperFiles.hpp" + +#include +#include +#include + +namespace webfront::developer { + +class Store { +public: + explicit Store(std::filesystem::path project, std::chrono::steady_clock::duration abandoned = defaultAbandonedAfter) + : root(std::filesystem::canonical(project)), abandonedAfter(abandoned) { + if (!std::filesystem::is_directory(root)) + throw std::invalid_argument("Developer project must be a directory"); + removeStaleStaging(root); + } + Store(const Store&) = delete; + Store& operator=(const Store&) = delete; + ~Store() { + for (const auto& [id, transaction] : transactions) { + (void)id; + std::error_code ignored; + std::filesystem::remove_all(transaction.staging, ignored); + } + } + + std::vector read(std::string path, std::uint64_t offset) const { + std::scoped_lock lock(mutex); + const auto source = projectPath(root, path); + std::ifstream file = openForReading(source, path, offset); + std::vector bytes(chunkSize); + file.read(reinterpret_cast(bytes.data()), static_cast(bytes.size())); + if (file.bad()) + throw std::runtime_error("Cannot read project file: " + path); + bytes.resize(static_cast(file.gcount())); + return bytes; + } + + std::string begin(std::string destination, bool directory, bool replace = true) { + std::scoped_lock lock(mutex); + expireAbandoned(); + if (transactions.size() >= maxTransactions) + throw std::runtime_error("Too many developer transactions"); + const auto target = projectPath(root, destination); + if (!replace && std::filesystem::exists(std::filesystem::symlink_status(target))) + throw std::runtime_error("Starter destination already exists"); + const auto stagingRoot = projectPath(root, ".webfront/developer/staging"); + std::filesystem::create_directories(stagingRoot); + // Compare resolved paths: a symlink or a differently cased spelling must not reach the staging area. + const auto resolved = std::filesystem::weakly_canonical(target); + requireFreeDestination(resolved, std::filesystem::weakly_canonical(stagingRoot)); + const auto [id, staging] = createStaging(stagingRoot); + transactions.emplace(id, Transaction{staging, target, resolved, std::move(destination), directory, replace, 0, {}, {}, std::chrono::steady_clock::now()}); + return id; + } + + /// The two forms of begin() exposed to the browser: replacing an existing destination or refusing to. + std::string beginReplacing(std::string destination, bool directory) { + return begin(std::move(destination), directory); + } + std::string beginNew(std::string destination, bool directory) { + return begin(std::move(destination), directory, false); + } + + void write(std::string id, std::string path, std::uint64_t offset, std::vector bytes) { + std::scoped_lock lock(mutex); + auto& tx = transaction(id); + const auto relative = checkedChunk(tx, path, bytes.size()); + requireDistinctCase(tx, relative.generic_string()); + auto& size = tx.files[relative.generic_string()]; + if (offset != size) + throw std::invalid_argument("Non-sequential developer write"); + const auto target = tx.staging / relative; + std::filesystem::create_directories(target.parent_path()); + std::ofstream file(target, std::ios::binary | std::ios::app); + file.write(reinterpret_cast(bytes.data()), static_cast(bytes.size())); + file.close(); + if (!file) + throw std::runtime_error("Cannot write staged developer file"); + size += bytes.size(); + tx.size += bytes.size(); + } + + void commit(std::string id) { + std::scoped_lock lock(mutex); + auto& tx = transaction(id); + // Revalidate after the browser has finished writing. + if (projectPath(root, tx.destination) != tx.target) + throw std::runtime_error("Project path changed"); + const auto source = stagedSource(tx); + const auto backup = tx.staging.parent_path() / (id + "-backup"); + replaceTarget(tx.target, tx.replace, source, backup); + std::error_code ignored; + std::filesystem::remove_all(backup, ignored); + std::filesystem::remove_all(tx.staging, ignored); + transactions.erase(id); + } + + void abort(std::string id) { + std::scoped_lock lock(mutex); + const auto found = transactions.find(id); + if (found == transactions.end()) + return; + std::filesystem::remove_all(found->second.staging); + transactions.erase(found); + } + +private: + struct Transaction { + std::filesystem::path staging; + std::filesystem::path target; + std::filesystem::path resolved; + std::string destination; + bool directory; + bool replace; + std::uint64_t size; + std::map files; + std::set folded; + std::chrono::steady_clock::time_point lastUse; + }; + Transaction& transaction(const std::string& id) { + const auto found = transactions.find(id); + if (found == transactions.end()) + throw std::runtime_error("Unknown or abandoned developer transaction"); + found->second.lastUse = std::chrono::steady_clock::now(); + return found->second; + } + + void expireAbandoned() { + const auto now = std::chrono::steady_clock::now(); + for (auto it = transactions.begin(); it != transactions.end();) { + if (now - it->second.lastUse >= abandonedAfter) { + std::error_code ignored; + std::filesystem::remove_all(it->second.staging, ignored); + it = transactions.erase(it); + } else + ++it; + } + } + + // The staging area and the destinations of unfinished transactions are off limits. + void requireFreeDestination(const std::filesystem::path& resolved, const std::filesystem::path& staging) const { + if (resolved == root || related(resolved, staging)) + throw std::invalid_argument("Invalid publication destination"); + requireNoOverlap(resolved); + } + + void requireNoOverlap(const std::filesystem::path& resolved) const { + for (const auto& entry : transactions) + if (related(entry.second.resolved, resolved)) + throw std::runtime_error("Destination is already being written"); + } + + static std::filesystem::path stagedSource(const Transaction& tx) { + if (tx.directory) + return tx.staging; + auto output = tx.staging / "output"; + if (!std::filesystem::is_regular_file(output)) + throw std::runtime_error("No output was staged"); + return output; + } + + // Two paths differing only by case are one file on Windows and macOS: refuse them instead of concatenating. + static void requireDistinctCase(Transaction& tx, const std::string& key) { + std::string lowered = key; + std::ranges::transform(lowered, lowered.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); + if (tx.files.contains(key)) + return; + if (!tx.folded.insert(lowered).second) + throw std::invalid_argument("Developer paths differing only by case: " + key); + } + + static void requireWithinLimits(const Transaction& tx, std::size_t size) { + if (size > chunkSize) + throw std::length_error("Developer transaction exceeds its byte limit"); + if (tx.size + size > maxTransactionBytes) + throw std::length_error("Developer transaction exceeds its byte limit"); + } + + static std::filesystem::path checkedChunk(const Transaction& tx, const std::string& path, std::size_t size) { + if (!tx.directory && path != "output") + throw std::invalid_argument("Expected output file"); + auto relative = fs::tools::safeRelativePath(path); + requireWithinLimits(tx, size); + return relative; + } + + std::filesystem::path root; + std::chrono::steady_clock::duration abandonedAfter; + mutable std::mutex mutex; + std::map transactions; +}; + +} // namespace webfront::developer diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 3aafca85..e8bfd6b9 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -48,3 +48,37 @@ target_compile_definitions(WebFrontApp PRIVATE WEBFRONT_DEMO_FRONTEND=${WEBFRONT foreach(target HelloWorld WebFrontGreeter WebFrontApp WebFrontTerminal WebFrontTools WebFrontAwaitBrowser) webfront_setup_frontends_for_target(${target}) endforeach() + +# Browser-powered development; React, the compiler and terminal are downloaded at runtime. +add_executable(WebFrontPiDeveloper PiDeveloper.cpp) +target_link_libraries(WebFrontPiDeveloper PRIVATE WebFront WebFront_warnings WebFront_options) +webfront_setup_frontends_for_target(WebFrontPiDeveloper) +set(WEBFRONT_PI_ASSETS "" CACHE FILEPATH "PiUI.hpp generated by wf embed (enables the offline PI demo)") +if(WEBFRONT_PI_ASSETS) + if(NOT EXISTS "${WEBFRONT_PI_ASSETS}") + message(FATAL_ERROR "WEBFRONT_PI_ASSETS must name an existing PiUI.hpp generated by wf embed") + endif() + add_executable(WebFrontPiEmbedded PiEmbedded.cpp) + target_link_libraries(WebFrontPiEmbedded PRIVATE WebFront WebFront_warnings WebFront_options) + target_compile_definitions(WebFrontPiEmbedded PRIVATE WEBFRONT_PI_ASSETS_HEADER="${WEBFRONT_PI_ASSETS}") + webfront_setup_frontends_for_target(WebFrontPiEmbedded) +endif() + +# The initial console program has no server or frontend dependency. +add_executable(WebFrontLifeConsole LifeConsole.cpp) +target_link_libraries(WebFrontLifeConsole PRIVATE WebFront_warnings WebFront_options) + +# Game of Life: the same browser-only toolchain with a spatial React interface. +add_executable(WebFrontLifeDeveloper LifeDeveloper.cpp) +target_link_libraries(WebFrontLifeDeveloper PRIVATE WebFront WebFront_warnings WebFront_options) +webfront_setup_frontends_for_target(WebFrontLifeDeveloper) +set(WEBFRONT_LIFE_ASSETS "" CACHE FILEPATH "LifeUI.hpp generated by wf embed (enables the offline Life demo)") +if(WEBFRONT_LIFE_ASSETS) + if(NOT EXISTS "${WEBFRONT_LIFE_ASSETS}") + message(FATAL_ERROR "WEBFRONT_LIFE_ASSETS must name an existing LifeUI.hpp generated by wf embed") + endif() + add_executable(WebFrontLifeEmbedded LifeEmbedded.cpp) + target_link_libraries(WebFrontLifeEmbedded PRIVATE WebFront WebFront_warnings WebFront_options) + target_compile_definitions(WebFrontLifeEmbedded PRIVATE WEBFRONT_LIFE_ASSETS_HEADER="${WEBFRONT_LIFE_ASSETS}") + webfront_setup_frontends_for_target(WebFrontLifeEmbedded) +endif() diff --git a/src/Life.hpp b/src/Life.hpp new file mode 100644 index 00000000..590cfd5e --- /dev/null +++ b/src/Life.hpp @@ -0,0 +1,35 @@ +#pragma once + +#include + +namespace webfront::demo { +using LifeGrid = std::bitset<32 * 32>; + +namespace detail { +inline std::size_t lifeIndex(int x, int y) { + return static_cast(((y + 32) % 32) * 32 + (x + 32) % 32); +} + +inline int liveNeighbors(const LifeGrid& cells, int x, int y) { + int neighbors = 0; + for (int dy = -1; dy <= 1; ++dy) + for (int dx = -1; dx <= 1; ++dx) + if (dx || dy) + neighbors += cells[lifeIndex(x + dx, y + dy)]; + return neighbors; +} +} // namespace detail + +// B3/S23 on a torus: compute a new generation without modifying the old one. +inline LifeGrid nextLife(const LifeGrid& cells) { + LifeGrid next; + for (int y = 0; y < 32; ++y) + for (int x = 0; x < 32; ++x) { + const auto neighbors = detail::liveNeighbors(cells, x, y); + const auto i = detail::lifeIndex(x, y); + next[i] = neighbors == 3 || (cells[i] && neighbors == 2); + } + return next; +} + +} // namespace webfront::demo diff --git a/src/LifeConsole.cpp b/src/LifeConsole.cpp new file mode 100644 index 00000000..b65a5672 --- /dev/null +++ b/src/LifeConsole.cpp @@ -0,0 +1,11 @@ +#include "Life.hpp" + +#include + +int main() { + webfront::demo::LifeGrid cells{0b111}; + for (int generation = 0; generation < 4; ++generation) { + std::cout << "Generation " << generation << ": " << cells.count() << " living cells\n"; + cells = webfront::demo::nextLife(cells); + } +} diff --git a/src/LifeDeveloper.cpp b/src/LifeDeveloper.cpp new file mode 100644 index 00000000..7bc2c8d6 --- /dev/null +++ b/src/LifeDeveloper.cpp @@ -0,0 +1,23 @@ +#include "Life.hpp" +#include + +#include + +int main(int argc, char** argv) { + if (argc != 2 && argc != 4) { + std::cerr << "Usage: WebFrontLifeDeveloper [ ]\n"; + return 2; + } + try { + webfront::NativeApp app{argv[1]}; + app.cppFunction("life.step", &webfront::demo::nextLife); + if (argc == 2) + app.bootstrap("developer"); + else + app.bootstrap("developer", {.environment = argv[2], .integrity = argv[3]}); + app.show(); + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/src/LifeEmbedded.cpp b/src/LifeEmbedded.cpp new file mode 100644 index 00000000..fb5f4b80 --- /dev/null +++ b/src/LifeEmbedded.cpp @@ -0,0 +1,16 @@ +#include +#include WEBFRONT_LIFE_ASSETS_HEADER +#include "Life.hpp" + +#include + +int main() { + try { + webfront::NativeAppWithAssets app; + app.cppFunction("life.step", &webfront::demo::nextLife); + app.show(); + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/src/Pi.hpp b/src/Pi.hpp new file mode 100644 index 00000000..98a4fa44 --- /dev/null +++ b/src/Pi.hpp @@ -0,0 +1,55 @@ +#pragma once + +#include +#include +#include +#include + +namespace webfront::demo { + +namespace detail { +// One spigot step over the remainders: returns the next candidate digit (0..10). +inline int spigotStep(std::vector& remainder) { + int quotient = 0; + for (auto i = static_cast(remainder.size()); i > 0; --i) { + auto& cell = remainder[static_cast(i - 1)]; + const int value = 10 * cell + quotient * i; + cell = value % (2 * i - 1); + quotient = value / (2 * i - 1); + } + remainder[0] = quotient % 10; + return quotient / 10; +} + +// The digits, with a leading placeholder, holding back runs of nines until a carry settles them. +inline std::string spigotDigits(int count) { + std::vector remainder(static_cast(count * 10 / 3 + 1), 2); + std::string digits; + int previous = 0, nines = 0; + for (int digit = 0; digit < count; ++digit) { + const int quotient = spigotStep(remainder); + if (quotient == 9) { + ++nines; + continue; + } + const int carry = quotient == 10; + digits += static_cast('0' + previous + carry); + digits.append(static_cast(nines), "90"[carry]); + previous = quotient % 10; + nines = 0; + } + return digits + static_cast('0' + previous); +} +} // namespace detail + +// Decimal spigot; deliberately small and bounded so it is suitable for the introductory demo. +inline std::string pi(std::uint32_t decimals) { + if (decimals > 1000) + throw std::invalid_argument("Choose at most 1000 decimals"); + auto result = detail::spigotDigits(static_cast(decimals) + 3).substr(1, static_cast(decimals) + 1); + if (decimals != 0) + result.insert(1, "."); + return result; +} + +} // namespace webfront::demo diff --git a/src/PiDeveloper.cpp b/src/PiDeveloper.cpp new file mode 100644 index 00000000..292aa16b --- /dev/null +++ b/src/PiDeveloper.cpp @@ -0,0 +1,23 @@ +#include "Pi.hpp" +#include + +#include + +int main(int argc, char** argv) { + if (argc != 2 && argc != 4) { + std::cerr << "Usage: WebFrontPiDeveloper [ ]\n"; + return 2; + } + try { + webfront::NativeApp app{argv[1]}; + app.cppFunction("pi", &webfront::demo::pi); + if (argc == 2) + app.bootstrap("developer"); + else + app.bootstrap("developer", {.environment = argv[2], .integrity = argv[3]}); + app.show(); + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/src/PiEmbedded.cpp b/src/PiEmbedded.cpp new file mode 100644 index 00000000..bc245c89 --- /dev/null +++ b/src/PiEmbedded.cpp @@ -0,0 +1,16 @@ +#include +#include WEBFRONT_PI_ASSETS_HEADER +#include "Pi.hpp" + +#include + +int main() { + try { + webfront::NativeAppWithAssets app; + app.cppFunction("pi", &webfront::demo::pi); + app.show(); + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/src/developer/PACKAGES-LICENSE.txt b/src/developer/PACKAGES-LICENSE.txt new file mode 100644 index 00000000..19129e31 --- /dev/null +++ b/src/developer/PACKAGES-LICENSE.txt @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/src/developer/archive.mjs b/src/developer/archive.mjs new file mode 100644 index 00000000..ee35d189 --- /dev/null +++ b/src/developer/archive.mjs @@ -0,0 +1,34 @@ +// Reading an npm package archive: its files and the checks on its package.json. +import {gunzip, readTar} from '../components/tools/wf.mjs'; +import {safePackagePath} from './paths.mjs'; + +const text = new TextDecoder(); +const installScripts = ['preinstall', 'install', 'postinstall']; + +export async function readArchive(bytes) { + const files = new Map(); + for (const entry of readTar(await gunzip(bytes))) { + if (!entry.path.startsWith('package/')) throw new Error('Invalid npm tarball root'); + const path = safePackagePath(entry.path.slice(8)); + if (files.has(path)) throw new Error(`Duplicate package path: ${path}`); + files.set(path, entry.bytes); + } + return files; +} + +const hasInstallScript = pkg => installScripts.some(key => pkg.scripts?.[key]); +const hasNativeFile = files => files.has('binding.gyp') || [...files.keys()].some(path => path.endsWith('.node')); + +function needsInstallStep(pkg, files) { + if (hasInstallScript(pkg)) return true; + if (pkg.gypfile) return true; + return hasNativeFile(files); +} + +// The package.json inside the archive must be the requested package and need no install step. +export function checkedManifest(files, name, version) { + const pkg = JSON.parse(text.decode(files.get('package.json'))); + if (pkg.name !== name || pkg.version !== version) throw new Error('npm archive identity mismatch'); + if (needsInstallStep(pkg, files)) throw new Error(`${name} needs an unsupported install script or native module`); + return pkg; +} diff --git a/src/developer/bootstrap-entry.mjs b/src/developer/bootstrap-entry.mjs new file mode 100644 index 00000000..e1a7230a --- /dev/null +++ b/src/developer/bootstrap-entry.mjs @@ -0,0 +1,23 @@ +import {bootstrap} from './bootstrap.mjs'; +import {call} from './io.mjs'; + +if (typeof document !== 'undefined' && document.getElementById('retry')) { + const status = document.getElementById('status'); + const retry = document.getElementById('retry'); + const start = async () => { + retry.hidden = true; + try { + await webFront.ready; + const options = JSON.parse(await call(webFront, 'config')); + const {url, config} = await bootstrap(webFront, options, fetch, text => { status.textContent = text; }); + const environment = await import(url); + await environment.mount({bridge: webFront, config, terminal: document.getElementById('terminal'), preview: document.getElementById('preview')}); + status.textContent = 'Developer environment ready. Type wf help.'; + } catch (error) { + status.textContent = `Bootstrap failed: ${error.message}`; + retry.hidden = false; + } + }; + retry.addEventListener('click', start); + void start(); +} diff --git a/src/developer/bootstrap.bundle.mjs b/src/developer/bootstrap.bundle.mjs new file mode 100644 index 00000000..3b130c47 --- /dev/null +++ b/src/developer/bootstrap.bundle.mjs @@ -0,0 +1 @@ +var u=new TextDecoder;async function p(t,e){let n=String(e??"").split(/\s+/).filter(a=>a.startsWith("sha512-")).map(a=>a.split("?")[0]);if(n.length===0)throw new Error("The package has no SHA-512 integrity");if(!globalThis.crypto?.subtle)throw new Error("Integrity checks need a secure context (https or localhost)");let r=new Uint8Array(await crypto.subtle.digest("SHA-512",t)),o="sha512-"+btoa(Array.from(r,a=>String.fromCharCode(a)).join(""));if(!n.includes(o))throw new Error(`Integrity check failed: expected ${n[0]}, got ${o}`);return o}async function d(t,e=268435456){let n=new Blob([t]).stream().pipeThrough(new DecompressionStream("gzip")).getReader(),r=[],o=0;for(let a=await n.read();!a.done;a=await n.read()){if(o+=a.value.length,o>e)throw await n.cancel(),new Error(`The tarball unpacks to more than ${e} bytes`);r.push(a.value)}return new Uint8Array(await new Blob(r).arrayBuffer())}function l(t,e,n){let r=t.subarray(e,e+n),o=r.indexOf(0);return u.decode(o<0?r:r.subarray(0,o))}function y(t,e,n){if(t[e]&128)return t.subarray(e+1,e+n).reduce((o,a)=>o*256+a,t[e]&127);let r=l(t,e,n).trim();if(!/^[0-7]*$/.test(r))throw new Error("Corrupt tar header");return r===""?0:parseInt(r,8)}function T(t){let e=0;for(let n=0;n<512;++n)e+=n>=148&&n<156?32:t[n];if(y(t,148,8)!==e)throw new Error("Corrupt tar header checksum")}function S(t){let e={},n=0;for(;n0)||n+o>t.length)throw new Error("Corrupt pax header");let a=u.decode(t.subarray(r+1,n+o-1)),i=a.indexOf("=");e[a.slice(0,i)]=a.slice(i+1),n+=o}return e}function z(t,e){let n=t.subarray(e,e+512);T(n);let r=y(n,124,12),o=e+512;if(o+r>t.length)throw new Error("Truncated tar archive");return{header:n,type:n[156]===0?"0":String.fromCharCode(n[156]),data:t.subarray(o,o+r),next:o+Math.ceil(r/512)*512}}function U(t,e){return e+512>t.length||t.subarray(e,e+512).every(n=>n===0)}function I(t){let e=l(t,0,100),n=l(t,257,5)==="ustar"?l(t,345,155):"";return n?`${n}/${e}`:e}var h={x:(t,e)=>({...t,pax:S(e).path}),L:(t,e)=>({...t,long:l(e,0,e.length)}),g:t=>t};function m(t){let e=[],n={};for(let r=0;!U(t,r);){let{header:o,type:a,data:i,next:s}=z(t,r);if(r=s,Object.hasOwn(h,a)){n=h[a](n,i);continue}(a==="0"||a==="7")&&e.push({path:n.pax??n.long??I(o),bytes:i}),n={}}return e}var c=(t,e,...n)=>t.cppFunction(`webfront.developer.${e}`)(...n);async function g(t,e){let n=[],r=0;for(;;){let o=await c(t,"read",e,r);if(n.push(o),r+=o.length,o.length<262144)break;if(r>256*1024*1024)throw new Error("Project file is too large")}return new Uint8Array(await new Blob(n).arrayBuffer())}async function j(t,{id:e,path:n,bytes:r},o){for(let a=0;a{}),s}}async function B(t,e){let n=[],r=0;for(;;){let{done:o,value:a}=await t.read();if(o)return n;if(r+=a.length,r>e)throw new Error("Compressed download exceeds its byte limit");n.push(a)}}async function F(t,e){try{return await B(t,e)}catch(n){throw await t.cancel().catch(()=>{}),n}finally{t.releaseLock()}}async function b(t,e=64*1024*1024){if(!t.ok)throw new Error(`Download: HTTP ${t.status}`);if(Number(t.headers.get("content-length"))>e)throw new Error("Compressed download exceeds its byte limit");return new Uint8Array(await new Blob(await F(t.body.getReader(),e)).arrayBuffer())}var O=/[\\\0:*?"<>|]/,C=t=>t.split("/").some(e=>!e||e==="."||e==="..");function v(t){return typeof t!="string"||!t||O.test(t)?!0:C(t)}var w=t=>!v(t),P=new TextDecoder;function A(t,e){if(!e.path.startsWith("package/"))throw new Error("Invalid environment archive root");let n=e.path.slice(8);if(!w(n)||t.has(n))throw new Error("Invalid or duplicate environment path");t.set(n,e.bytes)}function L(t){let e=new Map;for(let n of m(t))A(e,n);return e}function R(t,e){return t.protocol!==1||!w(t.entry)?!1:e.has(t.entry)}async function x(t,e){await p(t,e);let n=L(await d(t));if(!n.has("environment.json"))throw new Error("Environment archive has no environment.json");let r=JSON.parse(P.decode(n.get("environment.json")));if(!R(r,n))throw new Error("Unsupported WebFront developer environment");return{files:n,manifest:r}}var k=".webfront/developer/environment.tgz";async function N(t,e){try{let n=await g(t,k);return await x(n,e),n}catch{return null}}async function W(t,e){let n=new URL(t.environment,location.href);if(n.protocol!=="https:"&&n.origin!==location.origin)throw new Error("The environment must use HTTPS or the application origin");let r=await e(n);if(!r.ok)throw new Error(`Environment download: HTTP ${r.status}`);return b(r)}function D(t){return!t||!w(t.archive)?!1:String(t.integrity).startsWith("sha512-")}function H(t,e){return Object.fromEntries(Object.entries(t.starters??{}).map(([n,r])=>{if(!D(r))throw new Error("Invalid pinned starter metadata");return[n,{url:new URL(r.archive,e).href,integrity:r.integrity}]}))}async function E(t,e,n=fetch,r=()=>{}){let o=await N(t,e.integrity);o?r("Using verified cached developer environment"):(r("Downloading developer environment"),o=await W(e,n));let{files:a,manifest:i}=await x(o,e.integrity),s=H(i,new URL(e.environment,location.href));return await f(t,".webfront/developer/environment",a),await f(t,k,new Map([["output",o]]),{directory:!1}),{url:`/webfront/developer/environment/${i.entry}`,config:{...e,starters:s}}}if(typeof document<"u"&&document.getElementById("retry")){let t=document.getElementById("status"),e=document.getElementById("retry"),n=async()=>{e.hidden=!0;try{await webFront.ready;let r=JSON.parse(await c(webFront,"config")),{url:o,config:a}=await E(webFront,r,fetch,s=>{t.textContent=s});await(await import(o)).mount({bridge:webFront,config:a,terminal:document.getElementById("terminal"),preview:document.getElementById("preview")}),t.textContent="Developer environment ready. Type wf help."}catch(r){t.textContent=`Bootstrap failed: ${r.message}`,e.hidden=!1}};e.addEventListener("click",n),n()} diff --git a/src/developer/bootstrap.mjs b/src/developer/bootstrap.mjs new file mode 100644 index 00000000..94c9fc08 --- /dev/null +++ b/src/developer/bootstrap.mjs @@ -0,0 +1,82 @@ +import {gunzip, readTar, verifyIntegrity} from '../components/tools/wf.mjs'; +import {readProject, publish, responseBytes} from './io.mjs'; +import {isUnsafe} from './paths.mjs'; + +const safePath = path => !isUnsafe(path); + +const decoder = new TextDecoder(); + +function addEntry(files, entry) { + if (!entry.path.startsWith('package/')) throw new Error('Invalid environment archive root'); + const path = entry.path.slice(8); + if (!safePath(path) || files.has(path)) throw new Error('Invalid or duplicate environment path'); + files.set(path, entry.bytes); +} + +function archiveFiles(tarball) { + const files = new Map(); + for (const entry of readTar(tarball)) addEntry(files, entry); + return files; +} + +function supported(manifest, files) { + if (manifest.protocol !== 1) return false; + if (!safePath(manifest.entry)) return false; + return files.has(manifest.entry); +} + +export async function environmentFiles(bytes, integrity) { + await verifyIntegrity(bytes, integrity); + const files = archiveFiles(await gunzip(bytes)); + if (!files.has('environment.json')) throw new Error('Environment archive has no environment.json'); + const manifest = JSON.parse(decoder.decode(files.get('environment.json'))); + if (!supported(manifest, files)) throw new Error('Unsupported WebFront developer environment'); + return {files, manifest}; +} + +const cachedPath = '.webfront/developer/environment.tgz'; + +async function verifiedCache(bridge, integrity) { + try { + const candidate = await readProject(bridge, cachedPath); + await environmentFiles(candidate, integrity); + return candidate; + } catch { return null; } +} + +async function downloadEnvironment(config, fetchImpl) { + const url = new URL(config.environment, location.href); + if (url.protocol !== 'https:' && url.origin !== location.origin) + throw new Error('The environment must use HTTPS or the application origin'); + const response = await fetchImpl(url); + if (!response.ok) throw new Error(`Environment download: HTTP ${response.status}`); + return responseBytes(response); +} + +function validStarter(starter) { + if (!starter) return false; + if (!safePath(starter.archive)) return false; + return String(starter.integrity).startsWith('sha512-'); +} + +function pinnedStarters(manifest, environmentUrl) { + return Object.fromEntries(Object.entries(manifest.starters ?? {}).map(([name, starter]) => { + if (!validStarter(starter)) throw new Error('Invalid pinned starter metadata'); + return [name, {url: new URL(starter.archive, environmentUrl).href, integrity: starter.integrity}]; + })); +} + +export async function bootstrap(bridge, config, fetchImpl = fetch, progress = () => {}) { + let bytes = await verifiedCache(bridge, config.integrity); + if (bytes) progress('Using verified cached developer environment'); + else { + progress('Downloading developer environment'); + bytes = await downloadEnvironment(config, fetchImpl); + } + const {files, manifest} = await environmentFiles(bytes, config.integrity); + const starters = pinnedStarters(manifest, new URL(config.environment, location.href)); + // All files and the trusted archive are published only after validation succeeds. + await publish(bridge, '.webfront/developer/environment', files); + await publish(bridge, cachedPath, new Map([['output', bytes]]), {directory: false}); + return {url: `/webfront/developer/environment/${manifest.entry}`, config: {...config, starters}}; +} diff --git a/src/developer/bundler.mjs b/src/developer/bundler.mjs new file mode 100644 index 00000000..1e1f3e55 --- /dev/null +++ b/src/developer/bundler.mjs @@ -0,0 +1,60 @@ +// Virtual project/npm filesystem for esbuild's browser API. No Node.js shims or network imports. +import {normalize, packageEntry} from './entry.mjs'; +import {resolveImport} from './resolve.mjs'; +export {normalize, packageEntry}; + +const decoder = new TextDecoder(); + +const extensions = ['', '.tsx', '.ts', '.jsx', '.js', '.mjs', '.cjs', '.json', '.css', '/index.tsx', '/index.ts', '/index.js']; +const loaders = new Map(Object.entries({mjs: 'js', cjs: 'js', js: 'js', jsx: 'jsx', ts: 'ts', tsx: 'tsx', css: 'css', json: 'json'})); + +// A file that does not exist is a miss in the project, but an error inside a locked package. +async function probe(read, namespace, candidate) { + try { return await read(namespace, candidate); } + catch (error) { + if (namespace !== 'project') throw error; + return undefined; + } +} + +function createFinder(packages, readProject, loaded) { + const read = async (namespace, path) => { + if (namespace === 'project') return readProject(path); + const slash = path.indexOf('/'); + return packages[path.slice(0, slash)]?.get(path.slice(slash + 1)); + }; + const find = async (namespace, path) => { + for (const suffix of extensions) { + const content = await probe(read, namespace, path + suffix); + if (content === undefined) continue; + loaded.set(`${namespace}:${path + suffix}`, content); + return {path: path + suffix, namespace}; + } + throw new Error(`Cannot resolve ${path}`); + }; + return {read, find}; +} + +export function virtualPlugin(lock, packages, readProject) { + const loaded = new Map(); + const {read, find} = createFinder(packages, readProject, loaded); + const load = namespace => async args => { + const bytes = loaded.get(`${namespace}:${args.path}`) ?? await read(namespace, args.path); + const loader = loaders.get(args.path.split('.').pop()); + return {contents: loader ? decoder.decode(bytes) : bytes, loader: loader ?? 'file'}; + }; + return {name: 'webfront-project', setup(build) { + build.onResolve({filter: /.*/}, args => resolveImport(args, lock, find)); + build.onLoad({filter: /.*/, namespace: 'empty'}, () => ({contents: '', loader: 'js'})); + for (const namespace of ['project', 'npm']) build.onLoad({filter: /.*/, namespace}, load(namespace)); + }}; +} + +export async function bundle(esbuild, {entry, lock, packages, readProject}) { + const result = await esbuild.build({entryPoints: [entry], bundle: true, write: false, + outdir: '/output', entryNames: 'app', assetNames: 'assets/[name]-[hash]', + format: 'esm', platform: 'browser', target: 'es2020', jsx: 'automatic', minify: true, + define: {'process.env.NODE_ENV': '"production"'}, legalComments: 'inline', + plugins: [virtualPlugin(lock, packages, readProject)]}); + return new Map(result.outputFiles.map(file => [file.path.replace(/^\/output\//, ''), file.contents])); +} diff --git a/src/developer/bundles.json b/src/developer/bundles.json new file mode 100644 index 00000000..ce689006 --- /dev/null +++ b/src/developer/bundles.json @@ -0,0 +1,34 @@ +{ + "src/developer/bootstrap.mjs": "534af4b3d07891338c3390e1d5e06c2fb6dd8df11ca6547735565b17f1b9cd70", + "src/developer/bootstrap-entry.mjs": "ff8084f23f5acc721f97eb1ed0a454e7bfee1894de17d54f0100fa11f7ef8b77", + "src/developer/packages.mjs": "faed29500a34c6ce24756d07bd4b47b9168ccec4bd49d12f00096a869637d74d", + "src/developer/starter.mjs": "f8cdef1218ae14f8bbe49eae495d931cc29e33f74444f0e37d61aea416b9d750", + "src/developer/paths.mjs": "6ebb626610756143c58762c87af18980802809d7f0f53d3b588e4b20e8db0161", + "src/developer/runtime.mjs": "36847f4413928908ebc8a1909e608c783701b13274a289d81e43df0e5125a0e8", + "src/developer/compiler.mjs": "3f7e187ca9a4c2645ef3823127457cad655919cbea3c7c0f22fb7ae2cc87e0e5", + "src/developer/bundler.mjs": "b0ff79a1b0caa012c25ec7b7f121d7d50af1aa1651231d3dcf2f39470c4ea25c", + "src/developer/entry.mjs": "b2b942443e3c74ae2c008392ba244d9b7e91db70ba1b4ebbe1357c455ebf51bb", + "src/developer/conditions.mjs": "7f0ecba239480831e38985ccffd4c82309949924f4eb9d938e4ad1b09f5f36ed", + "src/developer/io.mjs": "a155719c612e065c30272c0dfdc456df28b5efa90ca26f8cfcb55c9cb46de690", + "src/developer/recipe.mjs": "809f2091c50ebd13d23f92de9876b584658dc687324f73d48ee9f1271319f1ed", + "src/developer/registry.mjs": "f566f07ea066155ab7209d925cee2cf12a664ac51b07bc0ca3e3fd8fde49a9c8", + "src/developer/archive.mjs": "1fb8b9c3c27219858597801104639bba1104c7a7d33973609cd556b5e5f81d2d", + "src/developer/lock.mjs": "60d0ea14d24793cd5e85bbd4bb4bfe90d2c7d76c0d20ffc99f462595a6e57291", + "src/developer/pins.mjs": "ddb2214a2e906cb117dc1bac0b5b056decd4f6c6e3d4713615176c1876db3534", + "src/developer/peers.mjs": "e1d999892138682fc0134ef1f4d4b19b9a9ad8d7fb16e37fc9c6c684bd853896", + "src/developer/resolve.mjs": "8b96b850af215be51f5cb85cc9c69e057afa04dfb8a57e572620c07059c17fa3", + "src/developer/embed.mjs": "c8fb80998abecdd5fdeba77aa549ff638d849dc9fd7f34c896fb6c0c0bf15f34", + "src/pi/main.tsx": "d3161b35db204ba54f782f711183e8d96aeff7c92d885c33a6ec168cf461e453", + "src/pi/style.css": "360e2c7ae6d3699b00e18cbf67efbae7a8d8863d88926b31139e102cf38e5abd", + "src/life/main.tsx": "a70e7e6cd282552fb3073e6a63c3c8a2453e63cc7e0466f42251fb3bc78d9015", + "src/life/style.css": "9bb55eb0f0a3287e5b7dc78af9d69608b87ff42c4d9c8a653bc83a52fe293c44", + "src/components/tools/wf.mjs": "6ee86d85ec96bf548ca25ea3ea3554b7dacbed7d047d6a9cfdc1e0f3f42de05e", + "tools/developer/distribution.json": "87d8d9cbe1cd163b04d5df361af7e184eeb2c34657d07c2303e385200fda7919", + "tools/developer/build.mjs": "f63d9b877aaec4f98a85d7e237d416523cb3e8a59c8c2b3a0b5d85975ec4bff3", + "tools/developer/site.mjs": "d4b7112f0aa5f277f291505a3dce84e676fee9d4da386973af7c6df9885d4dd4", + "tools/developer/archive.mjs": "bfe9feeb5e4d4e1b7c44c4dec4dcbeab4ae59c2bf16a1d2b32cd6910a2b84e7b", + "tools/assets/package-lock.json": "eb545112b672f9dbf520125df1f44a878d62cc8e611f0e33baee36470ded4dec", + "src/developer/bootstrap.bundle.mjs": "792fe7cf564bd12ac47fef419d8c71e2070925764a17706552e7d3f5d6ba2181", + "src/developer/packages.bundle.mjs": "994c13a8b30a40ecea98414caa72a17927dcea81a1f62d47744b4f55d87005be", + "include/system/DeveloperReleaseData.hpp": "5a70db963af52ee31bb5ca9dc7413ed24c3567345590a4a9a525d3a283c83d76" +} diff --git a/src/developer/compiler.mjs b/src/developer/compiler.mjs new file mode 100644 index 00000000..c27d3838 --- /dev/null +++ b/src/developer/compiler.mjs @@ -0,0 +1,29 @@ +import * as esbuild from 'esbuild-wasm'; +import {bundle} from './bundler.mjs'; + +const pending = new Map(); +let nextId = 0; +const readProject = path => new Promise((resolve, reject) => { + const id = ++nextId; + pending.set(id, {resolve, reject}); + self.postMessage({type: 'read', id, path}); +}); +const initialized = esbuild.initialize({wasmURL: new URL('./esbuild.wasm', import.meta.url).href, worker: false}); +self.onmessage = async ({data}) => { + if (data.type === 'read-result') { + const request = pending.get(data.id); + if (!request) return; + pending.delete(data.id); + if (data.error) request.reject(new Error(data.error)); + else request.resolve(data.bytes); + return; + } + if (data.type !== 'build') return; + try { + await initialized; + const files = await bundle(esbuild, {...data, readProject}); + self.postMessage({type: 'result', files}); + } catch (error) { + self.postMessage({type: 'error', error: error.message}); + } +}; diff --git a/src/developer/conditions.mjs b/src/developer/conditions.mjs new file mode 100644 index 00000000..c86737b5 --- /dev/null +++ b/src/developer/conditions.mjs @@ -0,0 +1,30 @@ +// Conditional targets of package.json "exports": the first condition that resolves wins, like Node. + +export function isPlainObject(value) { + if (!value || typeof value !== 'object') return false; + return !Array.isArray(value); +} + +function firstMatch(candidates, wildcard, conditions) { + for (const candidate of candidates) { + const result = conditional(candidate, wildcard, conditions); + if (result) return result; + } + return null; +} + +function byCondition(object, wildcard, conditions) { + for (const [key, target] of Object.entries(object)) { + if (!conditions.has(key)) continue; + const result = conditional(target, wildcard, conditions); + if (result) return result; + } + return null; +} + +export function conditional(value, wildcard, conditions) { + if (typeof value === 'string') return value.replaceAll('*', wildcard ?? ''); + if (Array.isArray(value)) return firstMatch(value, wildcard, conditions); + if (isPlainObject(value)) return byCondition(value, wildcard, conditions); + return null; +} diff --git a/src/developer/embed.mjs b/src/developer/embed.mjs new file mode 100644 index 00000000..7de4bc70 --- /dev/null +++ b/src/developer/embed.mjs @@ -0,0 +1,69 @@ +import {gzipSync} from '../../third_party/fflate/browser.mjs'; + +export function compress(bytes) { + return gzipSync(bytes, {level: 9, mem: 8, mtime: 0}); +} + +const byName = ([a], [b]) => a < b ? -1 : a > b ? 1 : 0; +const hasUnsafePart = path => path.split('/').some(part => !part || part === '.' || part === '..'); + +function validRoute(path) { + if (!/^[A-Za-z0-9_./-]+$/.test(path)) return false; + return !hasUnsafePart(path); +} + +// Eight bytes as one big-endian word; the last word is padded with zeros. +const word = (bytes, offset) => '0x' + Array.from({length: 8}, (_, i) => (bytes[offset + i] ?? 0).toString(16).padStart(2, '0')).join('') + 'ULL'; + +function wordsOf(bytes) { + const words = []; + for (let offset = 0; offset < bytes.length; offset += 8) words.push(word(bytes, offset)); + return words; +} + +function declarationOf(name, compressed) { + const words = wordsOf(compressed); + return ` struct ${name} { + static constexpr std::string_view encoding{"gzip"}; + static constexpr std::size_t dataSize{${compressed.length}}; + static constexpr std::array data{\n ${words.join(',\n ')}\n }; + };`; +} + +// The same big-endian word layout, padding and gzip settings as EmbedTextAsset.cmake. +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 = []; + const routes = []; + for (const [path, bytes] of [...files].sort(byName)) { + if (!validRoute(path)) throw new Error(`Invalid embedded route: ${path}`); + const name = `Asset${declarations.length}`; + declarations.push(declarationOf(name, compress(bytes))); + routes.push(` if (name == ${JSON.stringify(path)}) return File{${name}{}};`); + } + return `#pragma once + +#include + +/* Dependency notices and build inputs\n${notices.replaceAll('*/', '* /')}\n*/ +namespace webfront::fs { +class ${className} { +public: + explicit ${className}(std::filesystem::path) {} + static std::optional open(std::filesystem::path path) { + const auto name = path.relative_path().generic_string(); +${routes.join('\n')} + return {}; + } +private: +${declarations.join('\n')} +}; +} // namespace webfront::fs +`; +} + +export function applicationPage(files) { + const encode = new TextEncoder(); + const stylesheet = files.has('app.css') ? '' : ''; + return encode.encode(`\nWebFront application${stylesheet}
\n`); +} diff --git a/src/developer/entry.mjs b/src/developer/entry.mjs new file mode 100644 index 00000000..014d4769 --- /dev/null +++ b/src/developer/entry.mjs @@ -0,0 +1,65 @@ +// Package entry points: normalized paths and the "exports" map of package.json. +import {conditional, isPlainObject} from './conditions.mjs'; +export {isPlainObject}; + +function applySegment(parts, part) { + if (!part || part === '.') return; + if (part !== '..') { + parts.push(part); + return; + } + if (!parts.length) throw new Error('Import escapes its source root'); + parts.pop(); +} + +export function normalize(path) { + const parts = []; + for (const part of path.split('/')) applySegment(parts, part); + return parts.join('/'); +} + +function exportedPath(result, key) { + if (!result?.startsWith('./')) throw new Error(`Unsupported package export: ${key}`); + return normalize(result); +} + +function isSubpathMap(value) { + if (!isPlainObject(value)) return false; + return Object.keys(value).some(key => key.startsWith('.')); +} + +const matches = (pattern, key) => { + const [before, after] = pattern.split('*'); + return key.startsWith(before) && key.endsWith(after); +}; + +// The longest "./prefix/*"-style subpath pattern that matches the requested subpath. +const matchingPattern = (exports, key) => Object.keys(exports).filter(candidate => candidate.includes('*')) + .sort((a, b) => b.length - a.length).find(candidate => matches(candidate, key)); + +function patternEntry(exports, key, conditions) { + const pattern = matchingPattern(exports, key); + if (!pattern) throw new Error(`Package does not export ${key}`); + const [before, after] = pattern.split('*'); + return exportedPath(conditional(exports[pattern], key.slice(before.length, key.length - after.length), conditions), key); +} + +function legacyMain(manifest) { + if (typeof manifest.browser === 'string' && manifest.browser) return manifest.browser; + return manifest.module || manifest.main || 'index.js'; +} + +function mapEntry(exports, key, conditions) { + if (!Object.hasOwn(exports, key)) return patternEntry(exports, key, conditions); + return exportedPath(conditional(exports[key], undefined, conditions), key); +} + +export function packageEntry(manifest, subpath = '', kind = 'import') { + const conditions = new Set(['browser', kind, 'default', 'production']); + const exports = manifest.exports; + if (exports === undefined) return normalize(subpath || legacyMain(manifest)); + const key = subpath ? `./${subpath}` : '.'; + if (isSubpathMap(exports)) return mapEntry(exports, key, conditions); + if (subpath) throw new Error(`Package does not export ${key}`); + return exportedPath(conditional(exports, undefined, conditions), key); +} diff --git a/src/developer/index.html b/src/developer/index.html new file mode 100644 index 00000000..cc4dfb2d --- /dev/null +++ b/src/developer/index.html @@ -0,0 +1,11 @@ + + + + +WebFront developer bootstrap + +
WebFront developer
Starting the developer environment…
+
+ + + diff --git a/src/developer/io.mjs b/src/developer/io.mjs new file mode 100644 index 00000000..d0525b10 --- /dev/null +++ b/src/developer/io.mjs @@ -0,0 +1,62 @@ +// Bridge and network transfers shared by the developer environment: project reads, staged publications, bounded downloads. +export const blockSize = 256 * 1024; +export const call = (bridge, name, ...args) => bridge.cppFunction(`webfront.developer.${name}`)(...args); + +export async function readProject(bridge, path) { + const chunks = []; + let offset = 0; + for (;;) { + const chunk = await call(bridge, 'read', path, offset); + chunks.push(chunk); + offset += chunk.length; + if (chunk.length < blockSize) break; + if (offset > 256 * 1024 * 1024) throw new Error('Project file is too large'); + } + return new Uint8Array(await new Blob(chunks).arrayBuffer()); +} + +async function writeChunks(bridge, {id, path, bytes}, signal) { + for (let offset = 0; offset < bytes.length || offset === 0; offset += blockSize) { + signal?.throwIfAborted(); + await call(bridge, 'write', id, path, offset, bytes.subarray(offset, offset + blockSize)); + } +} + +export async function publish(bridge, destination, files, {directory = true, signal, replace = true} = {}) { + const id = await call(bridge, replace ? 'begin' : 'beginNew', destination, directory); + try { + for (const [path, bytes] of files) await writeChunks(bridge, {id, path, bytes}, signal); + signal?.throwIfAborted(); + await call(bridge, 'commit', id); + } catch (error) { + await call(bridge, 'abort', id).catch(() => {}); + throw error; + } +} + +async function readAll(reader, limit) { + const chunks = []; + let size = 0; + for (;;) { + const {done, value} = await reader.read(); + if (done) return chunks; + size += value.length; + if (size > limit) throw new Error('Compressed download exceeds its byte limit'); + chunks.push(value); + } +} + +async function readLimited(reader, limit) { + try { + return await readAll(reader, limit); + } catch (error) { + await reader.cancel().catch(() => {}); + throw error; + } finally { reader.releaseLock(); } +} + +export async function responseBytes(response, limit = 64 * 1024 * 1024) { + if (!response.ok) throw new Error(`Download: HTTP ${response.status}`); + if (Number(response.headers.get('content-length')) > limit) throw new Error('Compressed download exceeds its byte limit'); + return new Uint8Array(await new Blob(await readLimited(response.body.getReader(), limit)).arrayBuffer()); +} diff --git a/src/developer/lock.mjs b/src/developer/lock.mjs new file mode 100644 index 00000000..6b06f858 --- /dev/null +++ b/src/developer/lock.mjs @@ -0,0 +1,34 @@ +// Validation of webfront-packages.lock.json before any of its files is read. +import semver from 'semver'; +import {safeName, idOf, cacheKey} from './registry.mjs'; +import {safePackagePath} from './paths.mjs'; + +function validIdentity(id, node) { + if (!safeName(node.name)) return false; + if (!semver.valid(node.version)) return false; + return id === idOf(node.name, node.version); +} + +function validSource(node) { + if (!node.integrity?.startsWith('sha512-')) return false; + return node.key === cacheKey(node.name, node.version, node.integrity); +} + +function validateNode(lock, id, node) { + if (!validIdentity(id, node) || !validSource(node)) throw new Error('Invalid locked package'); + for (const path of node.files) safePackagePath(path); + if (Object.values(node.dependencies).some(dependency => !lock.packages[dependency])) + throw new Error('Dangling locked dependency'); +} + +function hasLockShape(lock) { + if (lock?.format !== 1) return false; + return Boolean(lock.roots) && Boolean(lock.packages); +} + +export function validateLock(lock) { + if (!hasLockShape(lock)) throw new Error('Unsupported package lock'); + for (const [id, node] of Object.entries(lock.packages)) validateNode(lock, id, node); + if (Object.values(lock.roots).some(root => !lock.packages[root.id])) throw new Error('Dangling locked root'); + return lock; +} diff --git a/src/developer/packages.bundle.mjs b/src/developer/packages.bundle.mjs new file mode 100644 index 00000000..84e43c3f --- /dev/null +++ b/src/developer/packages.bundle.mjs @@ -0,0 +1 @@ +var Tt=Object.create;var Le=Object.defineProperty;var vt=Object.getOwnPropertyDescriptor;var At=Object.getOwnPropertyNames;var xt=Object.getPrototypeOf,qt=Object.prototype.hasOwnProperty;var m=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var bt=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of At(e))!qt.call(r,n)&&n!==t&&Le(r,n,{get:()=>e[n],enumerable:!(s=vt(e,n))||s.enumerable});return r};var F=(r,e,t)=>(t=r!=null?Tt(xt(r)):{},bt(e||!r||!r.__esModule?Le(t,"default",{value:r,enumerable:!0}):t,r));var A=m((co,xe)=>{"use strict";var Ft="2.0.0",Ut=Number.MAX_SAFE_INTEGER||9007199254740991,Gt=16,Xt=250,Vt=["major","premajor","minor","preminor","patch","prepatch","prerelease"];xe.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Gt,MAX_SAFE_BUILD_LENGTH:Xt,MAX_SAFE_INTEGER:Ut,RELEASE_TYPES:Vt,SEMVER_SPEC_VERSION:Ft,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var x=m((lo,qe)=>{"use strict";var zt=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};qe.exports=zt});var T=m((N,be)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:re,MAX_SAFE_BUILD_LENGTH:_t,MAX_LENGTH:Ht}=A(),Bt=x();N=be.exports={};var Mt=N.re=[],Wt=N.safeRe=[],l=N.src=[],Yt=N.safeSrc=[],u=N.t={},Jt=0,te="[a-zA-Z0-9-]",Kt=[["\\s",1],["\\d",Ht],[te,_t]],Zt=r=>{for(let[e,t]of Kt)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},d=(r,e,t)=>{let s=Zt(e),n=Jt++;Bt(r,n,e),u[r]=n,l[n]=e,Yt[n]=s,Mt[n]=new RegExp(e,t?"g":void 0),Wt[n]=new RegExp(s,t?"g":void 0)};d("NUMERICIDENTIFIER","0|[1-9]\\d*");d("NUMERICIDENTIFIERLOOSE","\\d+");d("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${te}*`);d("MAINVERSION",`(${l[u.NUMERICIDENTIFIER]})\\.(${l[u.NUMERICIDENTIFIER]})\\.(${l[u.NUMERICIDENTIFIER]})`);d("MAINVERSIONLOOSE",`(${l[u.NUMERICIDENTIFIERLOOSE]})\\.(${l[u.NUMERICIDENTIFIERLOOSE]})\\.(${l[u.NUMERICIDENTIFIERLOOSE]})`);d("PRERELEASEIDENTIFIER",`(?:${l[u.NONNUMERICIDENTIFIER]}|${l[u.NUMERICIDENTIFIER]})`);d("PRERELEASEIDENTIFIERLOOSE",`(?:${l[u.NONNUMERICIDENTIFIER]}|${l[u.NUMERICIDENTIFIERLOOSE]})`);d("PRERELEASE",`(?:-(${l[u.PRERELEASEIDENTIFIER]}(?:\\.${l[u.PRERELEASEIDENTIFIER]})*))`);d("PRERELEASELOOSE",`(?:-?(${l[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${l[u.PRERELEASEIDENTIFIERLOOSE]})*))`);d("BUILDIDENTIFIER",`${te}+`);d("BUILD",`(?:\\+(${l[u.BUILDIDENTIFIER]}(?:\\.${l[u.BUILDIDENTIFIER]})*))`);d("FULLPLAIN",`v?${l[u.MAINVERSION]}${l[u.PRERELEASE]}?${l[u.BUILD]}?`);d("FULL",`^${l[u.FULLPLAIN]}$`);d("LOOSEPLAIN",`[v=\\s]*${l[u.MAINVERSIONLOOSE]}${l[u.PRERELEASELOOSE]}?${l[u.BUILD]}?`);d("LOOSE",`^${l[u.LOOSEPLAIN]}$`);d("GTLT","((?:<|>)?=?)");d("XRANGEIDENTIFIERLOOSE",`${l[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);d("XRANGEIDENTIFIER",`${l[u.NUMERICIDENTIFIER]}|x|X|\\*`);d("XRANGEPLAIN",`[v=\\s]*(${l[u.XRANGEIDENTIFIER]})(?:\\.(${l[u.XRANGEIDENTIFIER]})(?:\\.(${l[u.XRANGEIDENTIFIER]})(?:${l[u.PRERELEASE]})?${l[u.BUILD]}?)?)?`);d("XRANGEPLAINLOOSE",`[v=\\s]*(${l[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[u.XRANGEIDENTIFIERLOOSE]})(?:${l[u.PRERELEASELOOSE]})?${l[u.BUILD]}?)?)?`);d("XRANGE",`^${l[u.GTLT]}\\s*${l[u.XRANGEPLAIN]}$`);d("XRANGELOOSE",`^${l[u.GTLT]}\\s*${l[u.XRANGEPLAINLOOSE]}$`);d("COERCEPLAIN",`(^|[^\\d])(\\d{1,${re}})(?:\\.(\\d{1,${re}}))?(?:\\.(\\d{1,${re}}))?`);d("COERCE",`${l[u.COERCEPLAIN]}(?:$|[^\\d])`);d("COERCEFULL",l[u.COERCEPLAIN]+`(?:${l[u.PRERELEASE]})?(?:${l[u.BUILD]})?(?:$|[^\\d])`);d("COERCERTL",l[u.COERCE],!0);d("COERCERTLFULL",l[u.COERCEFULL],!0);d("LONETILDE","(?:~>?)");d("TILDETRIM",`(\\s*)${l[u.LONETILDE]}\\s+`,!0);N.tildeTrimReplace="$1~";d("TILDE",`^${l[u.LONETILDE]}${l[u.XRANGEPLAIN]}$`);d("TILDELOOSE",`^${l[u.LONETILDE]}${l[u.XRANGEPLAINLOOSE]}$`);d("LONECARET","(?:\\^)");d("CARETTRIM",`(\\s*)${l[u.LONECARET]}\\s+`,!0);N.caretTrimReplace="$1^";d("CARET",`^${l[u.LONECARET]}${l[u.XRANGEPLAIN]}$`);d("CARETLOOSE",`^${l[u.LONECARET]}${l[u.XRANGEPLAINLOOSE]}$`);d("COMPARATORLOOSE",`^${l[u.GTLT]}\\s*(${l[u.LOOSEPLAIN]})$|^$`);d("COMPARATOR",`^${l[u.GTLT]}\\s*(${l[u.FULLPLAIN]})$|^$`);d("COMPARATORTRIM",`(\\s*)${l[u.GTLT]}\\s*(${l[u.LOOSEPLAIN]}|${l[u.XRANGEPLAIN]})`,!0);N.comparatorTrimReplace="$1$2$3";d("HYPHENRANGE",`^\\s*(${l[u.XRANGEPLAIN]})\\s+-\\s+(${l[u.XRANGEPLAIN]})\\s*$`);d("HYPHENRANGELOOSE",`^\\s*(${l[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${l[u.XRANGEPLAINLOOSE]})\\s*$`);d("STAR","(<|>)?=?\\s*\\*");d("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");d("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var U=m((uo,Pe)=>{"use strict";var Qt=Object.freeze({loose:!0}),es=Object.freeze({}),rs=r=>r?typeof r!="object"?Qt:r:es;Pe.exports=rs});var se=m((fo,De)=>{"use strict";var ke=/^[0-9]+$/,Ce=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:rCe(e,r);De.exports={compareIdentifiers:Ce,rcompareIdentifiers:ts}});var g=m((ho,Fe)=>{"use strict";var G=x(),{MAX_LENGTH:je,MAX_SAFE_INTEGER:X}=A(),{safeRe:V,t:z}=T(),ss=U(),{compareIdentifiers:ne}=se(),ie=class r{constructor(e,t){if(t=ss(t),e instanceof r){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>je)throw new TypeError(`version is longer than ${je} characters`);G("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let s=e.trim().match(t.loose?V[z.LOOSE]:V[z.FULL]);if(!s)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+s[1],this.minor=+s[2],this.patch=+s[3],this.major>X||this.major<0)throw new TypeError("Invalid major version");if(this.minor>X||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>X||this.patch<0)throw new TypeError("Invalid patch version");s[4]?this.prerelease=s[4].split(".").map(n=>{if(/^[0-9]+$/.test(n)){let i=+n;if(i>=0&&ie.major?1:this.minore.minor?1:this.patche.patch?1:0}comparePre(e){if(e instanceof r||(e=new r(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let s=this.prerelease[t],n=e.prerelease[t];if(G("prerelease compare",t,s,n),s===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(s===void 0)return-1;if(s===n)continue;return ne(s,n)}while(++t)}compareBuild(e){e instanceof r||(e=new r(e,this.options));let t=0;do{let s=this.build[t],n=e.build[t];if(G("build compare",t,s,n),s===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(s===void 0)return-1;if(s===n)continue;return ne(s,n)}while(++t)}inc(e,t,s){if(e.startsWith("pre")){if(!t&&s===!1)throw new Error("invalid increment argument: identifier is empty");if(t){let n=`-${t}`.match(this.options.loose?V[z.PRERELEASELOOSE]:V[z.PRERELEASE]);if(!n||n[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,s);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,s);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,s),this.inc("pre",t,s);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,s),this.inc("pre",t,s);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let n=Number(s)?1:0;if(this.prerelease.length===0)this.prerelease=[n];else{let i=this.prerelease.length;for(;--i>=0;)typeof this.prerelease[i]=="number"&&(this.prerelease[i]++,i=-2);if(i===-1){if(t===this.prerelease.join(".")&&s===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(n)}}if(t){let i=[t,n];s===!1&&(i=[t]),ne(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=i):this.prerelease=i}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Fe.exports=ie});var S=m((po,Ge)=>{"use strict";var Ue=g(),ns=(r,e,t=!1)=>{if(r instanceof Ue)return r;try{return new Ue(r,e)}catch(s){if(!t)return null;throw s}};Ge.exports=ns});var Ve=m((Eo,Xe)=>{"use strict";var is=S(),os=(r,e)=>{let t=is(r,e);return t?t.version:null};Xe.exports=os});var _e=m((mo,ze)=>{"use strict";var as=S(),cs=(r,e)=>{let t=as(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};ze.exports=cs});var Me=m((wo,Be)=>{"use strict";var He=g(),ls=(r,e,t,s,n)=>{typeof t=="string"&&(n=s,s=t,t=void 0);try{return new He(r instanceof He?r.version:r,t).inc(e,s,n).version}catch{return null}};Be.exports=ls});var Je=m(($o,Ye)=>{"use strict";var We=S(),us=(r,e)=>{let t=We(r,null,!0),s=We(e,null,!0),n=t.compare(s);if(n===0)return null;let i=n>0,o=i?t:s,a=i?s:t,c=!!o.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(o)===0)return a.minor&&!a.patch?"minor":"patch"}let p=c?"pre":"";return t.major!==s.major?p+"major":t.minor!==s.minor?p+"minor":t.patch!==s.patch?p+"patch":"prerelease"};Ye.exports=us});var Ze=m((go,Ke)=>{"use strict";var fs=g(),hs=(r,e)=>new fs(r,e).major;Ke.exports=hs});var er=m((Ro,Qe)=>{"use strict";var ps=g(),Es=(r,e)=>new ps(r,e).minor;Qe.exports=Es});var tr=m((Io,rr)=>{"use strict";var ms=g(),ds=(r,e)=>new ms(r,e).patch;rr.exports=ds});var nr=m((yo,sr)=>{"use strict";var ws=S(),$s=(r,e)=>{let t=ws(r,e);return t&&t.prerelease.length?t.prerelease:null};sr.exports=$s});var L=m((Lo,or)=>{"use strict";var ir=g(),gs=(r,e,t)=>new ir(r,t).compare(new ir(e,t));or.exports=gs});var cr=m((Oo,ar)=>{"use strict";var Rs=L(),Is=(r,e,t)=>Rs(e,r,t);ar.exports=Is});var ur=m((No,lr)=>{"use strict";var ys=L(),Ls=(r,e)=>ys(r,e,!0);lr.exports=Ls});var _=m((So,hr)=>{"use strict";var fr=g(),Os=(r,e,t)=>{let s=new fr(r,t),n=new fr(e,t);return s.compare(n)||s.compareBuild(n)};hr.exports=Os});var Er=m((To,pr)=>{"use strict";var Ns=_(),Ss=(r,e)=>r.sort((t,s)=>Ns(t,s,e));pr.exports=Ss});var dr=m((vo,mr)=>{"use strict";var Ts=_(),vs=(r,e)=>r.sort((t,s)=>Ts(s,t,e));mr.exports=vs});var q=m((Ao,wr)=>{"use strict";var As=L(),xs=(r,e,t)=>As(r,e,t)>0;wr.exports=xs});var H=m((xo,$r)=>{"use strict";var qs=L(),bs=(r,e,t)=>qs(r,e,t)<0;$r.exports=bs});var oe=m((qo,gr)=>{"use strict";var Ps=L(),ks=(r,e,t)=>Ps(r,e,t)===0;gr.exports=ks});var ae=m((bo,Rr)=>{"use strict";var Cs=L(),Ds=(r,e,t)=>Cs(r,e,t)!==0;Rr.exports=Ds});var B=m((Po,Ir)=>{"use strict";var js=L(),Fs=(r,e,t)=>js(r,e,t)>=0;Ir.exports=Fs});var M=m((ko,yr)=>{"use strict";var Us=L(),Gs=(r,e,t)=>Us(r,e,t)<=0;yr.exports=Gs});var ce=m((Co,Lr)=>{"use strict";var Xs=oe(),Vs=ae(),zs=q(),_s=B(),Hs=H(),Bs=M(),Ms=(r,e,t,s)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return Xs(r,t,s);case"!=":return Vs(r,t,s);case">":return zs(r,t,s);case">=":return _s(r,t,s);case"<":return Hs(r,t,s);case"<=":return Bs(r,t,s);default:throw new TypeError(`Invalid operator: ${e}`)}};Lr.exports=Ms});var Nr=m((Do,Or)=>{"use strict";var Ws=g(),Ys=S(),{safeRe:W,t:Y}=T(),Js=(r,e)=>{if(r instanceof Ws)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?W[Y.COERCEFULL]:W[Y.COERCE]);else{let c=e.includePrerelease?W[Y.COERCERTLFULL]:W[Y.COERCERTL],f;for(;(f=c.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||f.index+f[0].length!==t.index+t[0].length)&&(t=f),c.lastIndex=f.index+f[1].length+f[2].length;c.lastIndex=-1}if(t===null)return null;let s=t[2],n=t[3]||"0",i=t[4]||"0",o=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return Ys(`${s}.${n}.${i}${o}${a}`,e)};Or.exports=Js});var Tr=m((jo,Sr)=>{"use strict";var le=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let n=this.map.keys().next().value;this.delete(n)}this.map.set(e,t)}return this}};Sr.exports=le});var O=m((Fo,qr)=>{"use strict";var Ks=/\s+/g,ue=class r{constructor(e,t){if(t=Qs(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof fe)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(Ks," "),this.set=this.raw.split("||").map(s=>this.parseRange(s.trim())).filter(s=>s.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let s=this.set[0];if(this.set=this.set.filter(n=>!Ar(n[0])),this.set.length===0)this.set=[s];else if(this.set.length>1){for(let n of this.set)if(n.length===1&&an(n[0])){this.set=[n];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e0&&(this.formatted+="||");let t=this.set[e];for(let s=0;s0&&(this.formatted+=" "),this.formatted+=t[s].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let s=((this.options.includePrerelease&&nn)|(this.options.loose&&on))+":"+e,n=vr.get(s);if(n)return n;let i=this.options.loose,o=i?I[R.HYPHENRANGELOOSE]:I[R.HYPHENRANGE];e=e.replace(o,wn(this.options.includePrerelease)),w("hyphen replace",e),e=e.replace(I[R.COMPARATORTRIM],rn),w("comparator trim",e),e=e.replace(I[R.TILDETRIM],tn),w("tilde trim",e),e=e.replace(I[R.CARETTRIM],sn),w("caret trim",e);let a=e.split(" ").map(h=>cn(h,this.options)).join(" ").split(/\s+/).map(h=>dn(h,this.options));i&&(a=a.filter(h=>(w("loose invalid filter",h,this.options),!!h.match(I[R.COMPARATORLOOSE])))),w("range list",a);let c=new Map,f=a.map(h=>new fe(h,this.options));for(let h of f){if(Ar(h))return[h];c.set(h.value,h)}c.size>1&&c.has("")&&c.delete("");let p=[...c.values()];return vr.set(s,p),p}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(s=>xr(s,t)&&e.set.some(n=>xr(n,t)&&s.every(i=>n.every(o=>i.intersects(o,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new en(e,this.options)}catch{return!1}for(let t=0;tr.value==="<0.0.0-0",an=r=>r.value==="",xr=(r,e)=>{let t=!0,s=r.slice(),n=s.pop();for(;t&&s.length;)t=s.every(i=>n.intersects(i,e)),n=s.pop();return t},cn=(r,e)=>(r=r.replace(I[R.BUILD],""),w("comp",r,e),r=fn(r,e),w("caret",r),r=ln(r,e),w("tildes",r),r=pn(r,e),w("xrange",r),r=mn(r,e),w("stars",r),r),y=r=>!r||r.toLowerCase()==="x"||r==="*",ln=(r,e)=>r.trim().split(/\s+/).map(t=>un(t,e)).join(" "),un=(r,e)=>{let t=e.loose?I[R.TILDELOOSE]:I[R.TILDE];return r.replace(t,(s,n,i,o,a)=>{w("tilde",r,s,n,i,o,a);let c;return y(n)?c="":y(i)?c=`>=${n}.0.0 <${+n+1}.0.0-0`:y(o)?c=`>=${n}.${i}.0 <${n}.${+i+1}.0-0`:a?(w("replaceTilde pr",a),c=`>=${n}.${i}.${o}-${a} <${n}.${+i+1}.0-0`):c=`>=${n}.${i}.${o} <${n}.${+i+1}.0-0`,w("tilde return",c),c})},fn=(r,e)=>r.trim().split(/\s+/).map(t=>hn(t,e)).join(" "),hn=(r,e)=>{w("caret",r,e);let t=e.loose?I[R.CARETLOOSE]:I[R.CARET],s=e.includePrerelease?"-0":"";return r.replace(t,(n,i,o,a,c)=>{w("caret",r,n,i,o,a,c);let f;return y(i)?f="":y(o)?f=`>=${i}.0.0${s} <${+i+1}.0.0-0`:y(a)?i==="0"?f=`>=${i}.${o}.0${s} <${i}.${+o+1}.0-0`:f=`>=${i}.${o}.0${s} <${+i+1}.0.0-0`:c?(w("replaceCaret pr",c),i==="0"?o==="0"?f=`>=${i}.${o}.${a}-${c} <${i}.${o}.${+a+1}-0`:f=`>=${i}.${o}.${a}-${c} <${i}.${+o+1}.0-0`:f=`>=${i}.${o}.${a}-${c} <${+i+1}.0.0-0`):(w("no pr"),i==="0"?o==="0"?f=`>=${i}.${o}.${a}${s} <${i}.${o}.${+a+1}-0`:f=`>=${i}.${o}.${a}${s} <${i}.${+o+1}.0-0`:f=`>=${i}.${o}.${a} <${+i+1}.0.0-0`),w("caret return",f),f})},pn=(r,e)=>(w("replaceXRanges",r,e),r.split(/\s+/).map(t=>En(t,e)).join(" ")),En=(r,e)=>{r=r.trim();let t=e.loose?I[R.XRANGELOOSE]:I[R.XRANGE];return r.replace(t,(s,n,i,o,a,c)=>{w("xRange",r,s,n,i,o,a,c);let f=y(i),p=f||y(o),h=p||y(a),$=h;return n==="="&&$&&(n=""),c=e.includePrerelease?"-0":"",f?n===">"||n==="<"?s="<0.0.0-0":s="*":n&&$?(p&&(o=0),a=0,n===">"?(n=">=",p?(i=+i+1,o=0,a=0):(o=+o+1,a=0)):n==="<="&&(n="<",p?i=+i+1:o=+o+1),n==="<"&&(c="-0"),s=`${n+i}.${o}.${a}${c}`):p?s=`>=${i}.0.0${c} <${+i+1}.0.0-0`:h&&(s=`>=${i}.${o}.0${c} <${i}.${+o+1}.0-0`),w("xRange return",s),s})},mn=(r,e)=>(w("replaceStars",r,e),r.trim().replace(I[R.STAR],"")),dn=(r,e)=>(w("replaceGTE0",r,e),r.trim().replace(I[e.includePrerelease?R.GTE0PRE:R.GTE0],"")),wn=r=>(e,t,s,n,i,o,a,c,f,p,h,$)=>(y(s)?t="":y(n)?t=`>=${s}.0.0${r?"-0":""}`:y(i)?t=`>=${s}.${n}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,y(f)?c="":y(p)?c=`<${+f+1}.0.0-0`:y(h)?c=`<${f}.${+p+1}.0-0`:$?c=`<=${f}.${p}.${h}-${$}`:r?c=`<${f}.${p}.${+h+1}-0`:c=`<=${c}`,`${t} ${c}`.trim()),$n=(r,e,t)=>{for(let s=0;s0){let n=r[s].semver;if(n.major===e.major&&n.minor===e.minor&&n.patch===e.patch)return!0}return!1}return!0}});var b=m((Uo,jr)=>{"use strict";var P=Symbol("SemVer ANY"),Ee=class r{static get ANY(){return P}constructor(e,t){if(t=br(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),pe("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===P?this.value="":this.value=this.operator+this.semver.version,pe("comp",this)}parse(e){let t=this.options.loose?Pr[kr.COMPARATORLOOSE]:Pr[kr.COMPARATOR],s=e.match(t);if(!s)throw new TypeError(`Invalid comparator: ${e}`);this.operator=s[1]!==void 0?s[1]:"",this.operator==="="&&(this.operator=""),s[2]?this.semver=new Cr(s[2],this.options.loose):this.semver=P}toString(){return this.value}test(e){if(pe("Comparator.test",e,this.options.loose),this.semver===P||e===P)return!0;if(typeof e=="string")try{e=new Cr(e,this.options)}catch{return!1}return he(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Dr(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Dr(this.value,t).test(e.semver):(t=br(t),t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||he(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||he(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};jr.exports=Ee;var br=U(),{safeRe:Pr,t:kr}=T(),he=ce(),pe=x(),Cr=g(),Dr=O()});var k=m((Go,Fr)=>{"use strict";var gn=O(),Rn=(r,e,t)=>{try{e=new gn(e,t)}catch{return!1}return e.test(r)};Fr.exports=Rn});var Gr=m((Xo,Ur)=>{"use strict";var In=O(),yn=(r,e)=>new In(r,e).set.map(t=>t.map(s=>s.value).join(" ").trim().split(" "));Ur.exports=yn});var Vr=m((Vo,Xr)=>{"use strict";var Ln=g(),On=O(),Nn=(r,e,t)=>{let s=null,n=null,i=null;try{i=new On(e,t)}catch{return null}return r.forEach(o=>{i.test(o)&&(!s||n.compare(o)===-1)&&(s=o,n=new Ln(s,t))}),s};Xr.exports=Nn});var _r=m((zo,zr)=>{"use strict";var Sn=g(),Tn=O(),vn=(r,e,t)=>{let s=null,n=null,i=null;try{i=new Tn(e,t)}catch{return null}return r.forEach(o=>{i.test(o)&&(!s||n.compare(o)===1)&&(s=o,n=new Sn(s,t))}),s};zr.exports=vn});var Mr=m((_o,Br)=>{"use strict";var me=g(),An=O(),Hr=q(),xn=(r,e)=>{r=new An(r,e);let t=new me("0.0.0");if(r.test(t)||(t=new me("0.0.0-0"),r.test(t)))return t;t=null;for(let s=0;s{let a=new me(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!i||Hr(a,i))&&(i=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),i&&(!t||Hr(t,i))&&(t=i)}return t&&r.test(t)?t:null};Br.exports=xn});var Yr=m((Ho,Wr)=>{"use strict";var qn=O(),bn=(r,e)=>{try{return new qn(r,e).range||"*"}catch{return null}};Wr.exports=bn});var J=m((Bo,Qr)=>{"use strict";var Pn=g(),Zr=b(),{ANY:kn}=Zr,Cn=O(),Dn=k(),Jr=q(),Kr=H(),jn=M(),Fn=B(),Un=(r,e,t,s)=>{r=new Pn(r,s),e=new Cn(e,s);let n,i,o,a,c;switch(t){case">":n=Jr,i=jn,o=Kr,a=">",c=">=";break;case"<":n=Kr,i=Fn,o=Jr,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Dn(r,e,s))return!1;for(let f=0;f{E.semver===kn&&(E=new Zr(">=0.0.0")),h=h||E,$=$||E,n(E.semver,h.semver,s)?h=E:o(E.semver,$.semver,s)&&($=E)}),h.operator===a||h.operator===c||(!$.operator||$.operator===a)&&i(r,$.semver))return!1;if($.operator===c&&o(r,$.semver))return!1}return!0};Qr.exports=Un});var rt=m((Mo,et)=>{"use strict";var Gn=J(),Xn=(r,e,t)=>Gn(r,e,">",t);et.exports=Xn});var st=m((Wo,tt)=>{"use strict";var Vn=J(),zn=(r,e,t)=>Vn(r,e,"<",t);tt.exports=zn});var ot=m((Yo,it)=>{"use strict";var nt=O(),_n=(r,e,t)=>(r=new nt(r,t),e=new nt(e,t),r.intersects(e,t));it.exports=_n});var ct=m((Jo,at)=>{"use strict";var Hn=k(),Bn=L();at.exports=(r,e,t)=>{let s=[],n=null,i=null,o=r.sort((p,h)=>Bn(p,h,t));for(let p of o)Hn(p,e,t)?(i=p,n||(n=p)):(i&&s.push([n,i]),i=null,n=null);n&&s.push([n,null]);let a=[];for(let[p,h]of s)p===h?a.push(p):!h&&p===o[0]?a.push("*"):h?p===o[0]?a.push(`<=${h}`):a.push(`${p} - ${h}`):a.push(`>=${p}`);let c=a.join(" || "),f=typeof e.raw=="string"?e.raw:String(e);return c.length{"use strict";var lt=O(),we=b(),{ANY:de}=we,C=k(),$e=L(),Mn=(r,e,t={})=>{if(r===e)return!0;r=new lt(r,t),e=new lt(e,t);let s=!1;e:for(let n of r.set){for(let i of e.set){let o=Yn(n,i,t);if(s=s||o!==null,o)continue e}if(s)return!1}return!0},Wn=[new we(">=0.0.0-0")],ut=[new we(">=0.0.0")],Yn=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===de){if(e.length===1&&e[0].semver===de)return!0;t.includePrerelease?r=Wn:r=ut}if(e.length===1&&e[0].semver===de){if(t.includePrerelease)return!0;e=ut}let s=new Set,n,i;for(let E of r)E.operator===">"||E.operator===">="?n=ft(n,E,t):E.operator==="<"||E.operator==="<="?i=ht(i,E,t):s.add(E.semver);if(s.size>1)return null;let o;if(n&&i){if(o=$e(n.semver,i.semver,t),o>0)return null;if(o===0&&(n.operator!==">="||i.operator!=="<="))return null}for(let E of s){if(n&&!C(E,String(n),t)||i&&!C(E,String(i),t))return null;for(let St of e)if(!C(E,String(St),t))return!1;return!0}let a,c,f,p,h=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1,$=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1;h&&h.prerelease.length===1&&i.operator==="<"&&h.prerelease[0]===0&&(h=!1);for(let E of e){if(p=p||E.operator===">"||E.operator===">=",f=f||E.operator==="<"||E.operator==="<=",n){if($&&E.semver.prerelease&&E.semver.prerelease.length&&E.semver.major===$.major&&E.semver.minor===$.minor&&E.semver.patch===$.patch&&($=!1),E.operator===">"||E.operator===">="){if(a=ft(n,E,t),a===E&&a!==n)return!1}else if(n.operator===">="&&!C(n.semver,String(E),t))return!1}if(i){if(h&&E.semver.prerelease&&E.semver.prerelease.length&&E.semver.major===h.major&&E.semver.minor===h.minor&&E.semver.patch===h.patch&&(h=!1),E.operator==="<"||E.operator==="<="){if(c=ht(i,E,t),c===E&&c!==i)return!1}else if(i.operator==="<="&&!C(i.semver,String(E),t))return!1}if(!E.operator&&(i||n)&&o!==0)return!1}return!(n&&f&&!i&&o!==0||i&&p&&!n&&o!==0||$||h)},ft=(r,e,t)=>{if(!r)return e;let s=$e(r.semver,e.semver,t);return s>0?r:s<0||e.operator===">"&&r.operator===">="?e:r},ht=(r,e,t)=>{if(!r)return e;let s=$e(r.semver,e.semver,t);return s<0?r:s>0||e.operator==="<"&&r.operator==="<="?e:r};pt.exports=Mn});var D=m((Zo,wt)=>{"use strict";var ge=T(),mt=A(),Jn=g(),dt=se(),Kn=S(),Zn=Ve(),Qn=_e(),ei=Me(),ri=Je(),ti=Ze(),si=er(),ni=tr(),ii=nr(),oi=L(),ai=cr(),ci=ur(),li=_(),ui=Er(),fi=dr(),hi=q(),pi=H(),Ei=oe(),mi=ae(),di=B(),wi=M(),$i=ce(),gi=Nr(),Ri=b(),Ii=O(),yi=k(),Li=Gr(),Oi=Vr(),Ni=_r(),Si=Mr(),Ti=Yr(),vi=J(),Ai=rt(),xi=st(),qi=ot(),bi=ct(),Pi=Et();wt.exports={parse:Kn,valid:Zn,clean:Qn,inc:ei,diff:ri,major:ti,minor:si,patch:ni,prerelease:ii,compare:oi,rcompare:ai,compareLoose:ci,compareBuild:li,sort:ui,rsort:fi,gt:hi,lt:pi,eq:Ei,neq:mi,gte:di,lte:wi,cmp:$i,coerce:gi,Comparator:Ri,Range:Ii,satisfies:yi,toComparators:Li,maxSatisfying:Oi,minSatisfying:Ni,minVersion:Si,validRange:Ti,outside:vi,gtr:Ai,ltr:xi,intersects:qi,simplifyRange:bi,subset:Pi,SemVer:Jn,re:ge.re,src:ge.src,tokens:ge.t,SEMVER_SPEC_VERSION:mt.SEMVER_SPEC_VERSION,RELEASE_TYPES:mt.RELEASE_TYPES,compareIdentifiers:dt.compareIdentifiers,rcompareIdentifiers:dt.rcompareIdentifiers}});var ee=new TextDecoder;function Ne(r){let e=r.indexOf("@",r.startsWith("@")?1:0);return e<0?{name:r,version:""}:{name:r.slice(0,e),version:r.slice(e+1)}}async function Se(r,e){let t=String(e??"").split(/\s+/).filter(i=>i.startsWith("sha512-")).map(i=>i.split("?")[0]);if(t.length===0)throw new Error("The package has no SHA-512 integrity");if(!globalThis.crypto?.subtle)throw new Error("Integrity checks need a secure context (https or localhost)");let s=new Uint8Array(await crypto.subtle.digest("SHA-512",r)),n="sha512-"+btoa(Array.from(s,i=>String.fromCharCode(i)).join(""));if(!t.includes(n))throw new Error(`Integrity check failed: expected ${t[0]}, got ${n}`);return n}async function Te(r,e=268435456){let t=new Blob([r]).stream().pipeThrough(new DecompressionStream("gzip")).getReader(),s=[],n=0;for(let i=await t.read();!i.done;i=await t.read()){if(n+=i.value.length,n>e)throw await t.cancel(),new Error(`The tarball unpacks to more than ${e} bytes`);s.push(i.value)}return new Uint8Array(await new Blob(s).arrayBuffer())}function v(r,e,t){let s=r.subarray(e,e+t),n=s.indexOf(0);return ee.decode(n<0?s:s.subarray(0,n))}function ve(r,e,t){if(r[e]&128)return r.subarray(e+1,e+t).reduce((n,i)=>n*256+i,r[e]&127);let s=v(r,e,t).trim();if(!/^[0-7]*$/.test(s))throw new Error("Corrupt tar header");return s===""?0:parseInt(s,8)}function Pt(r){let e=0;for(let t=0;t<512;++t)e+=t>=148&&t<156?32:r[t];if(ve(r,148,8)!==e)throw new Error("Corrupt tar header checksum")}function kt(r){let e={},t=0;for(;t0)||t+n>r.length)throw new Error("Corrupt pax header");let i=ee.decode(r.subarray(s+1,t+n-1)),o=i.indexOf("=");e[i.slice(0,o)]=i.slice(o+1),t+=n}return e}function Ct(r,e){let t=r.subarray(e,e+512);Pt(t);let s=ve(t,124,12),n=e+512;if(n+s>r.length)throw new Error("Truncated tar archive");return{header:t,type:t[156]===0?"0":String.fromCharCode(t[156]),data:r.subarray(n,n+s),next:n+Math.ceil(s/512)*512}}function Dt(r,e){return e+512>r.length||r.subarray(e,e+512).every(t=>t===0)}function jt(r){let e=v(r,0,100),t=v(r,257,5)==="ustar"?v(r,345,155):"";return t?`${t}/${e}`:e}var Oe={x:(r,e)=>({...r,pax:kt(e).path}),L:(r,e)=>({...r,long:v(e,0,e.length)}),g:r=>r};function Ae(r){let e=[],t={};for(let s=0;!Dt(r,s);){let{header:n,type:i,data:o,next:a}=Ct(r,s);if(s=a,Object.hasOwn(Oe,i)){t=Oe[i](t,o);continue}(i==="0"||i==="7")&&e.push({path:t.pax??t.long??jt(n),bytes:o}),t={}}return e}var K=F(D(),1);async function ki(r,e){let t=[],s=0;for(;;){let{done:n,value:i}=await r.read();if(n)return t;if(s+=i.length,s>e)throw new Error("Compressed download exceeds its byte limit");t.push(i)}}async function Ci(r,e){try{return await ki(r,e)}catch(t){throw await r.cancel().catch(()=>{}),t}finally{r.releaseLock()}}async function $t(r,e=64*1024*1024){if(!r.ok)throw new Error(`Download: HTTP ${r.status}`);if(Number(r.headers.get("content-length"))>e)throw new Error("Compressed download exceeds its byte limit");return new Uint8Array(await new Blob(await Ci(r.body.getReader(),e)).arrayBuffer())}var Di=/[\\\0:*?"<>|]/,ji=r=>r.split("/").some(e=>!e||e==="."||e==="..");function Fi(r){return typeof r!="string"||!r||Di.test(r)?!0:ji(r)}function j(r){if(Fi(r))throw new Error(`Unsafe package path: ${r}`);return r}var Ui=new TextDecoder,Gi=["preinstall","install","postinstall"];async function gt(r){let e=new Map;for(let t of Ae(await Te(r))){if(!t.path.startsWith("package/"))throw new Error("Invalid npm tarball root");let s=j(t.path.slice(8));if(e.has(s))throw new Error(`Duplicate package path: ${s}`);e.set(s,t.bytes)}return e}var Xi=r=>Gi.some(e=>r.scripts?.[e]),Vi=r=>r.has("binding.gyp")||[...r.keys()].some(e=>e.endsWith(".node"));function zi(r,e){return Xi(r)||r.gypfile?!0:Vi(e)}function Rt(r,e,t){let s=JSON.parse(Ui.decode(r.get("package.json")));if(s.name!==e||s.version!==t)throw new Error("npm archive identity mismatch");if(zi(s,r))throw new Error(`${e} needs an unsupported install script or native module`);return s}var Re=r=>/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(r),Z=(r,e)=>`${r.replace("/","+")}@${e}`,Ie=(r,e,t)=>`${Z(r,e)}-${t.slice(7).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}`;async function _i(r,e,{fetchImpl:t,signal:s}){let n=await t(new URL(r.replace("/","%2f"),e),{signal:s});if(!n.ok)throw new Error(`Registry metadata for ${r}: HTTP ${n.status}`);return n.json()}function Hi(r,e){let t=r["dist-tags"]?.[e];return t||(K.default.valid(e)?e:K.default.maxSatisfying(Object.keys(r.versions??{}),e))}function Bi(r,e,t){let s=t||"latest",n=Hi(r,s),i=r.versions?.[n];if(!i||!K.default.valid(n))throw new Error(`Cannot resolve ${e}@${s}`);return{version:n,manifest:i}}async function Mi(r,e,t,{fetchImpl:s,signal:n}){let i=new URL(e.dist?.tarball,t);if(i.protocol!=="https:"&&i.origin!==t.origin)throw new Error("Package tarballs must use HTTPS or the registry origin");let o=await s(i,{signal:n});if(!o.ok)throw new Error(`Package download for ${r}: HTTP ${o.status}`);let a=await $t(o);return{bytes:a,integrity:await Se(a,e.dist.integrity)}}function Wi(r){let e=new URL(r,globalThis.location?.href);return e.pathname.endsWith("/")||(e.pathname+="/"),e}async function ye(r,e,{registry:t,fetchImpl:s=fetch,signal:n}){if(!Re(r))throw new Error(`Unsupported npm package name: ${r}`);let i=Wi(t),o={fetchImpl:s,signal:n},{version:a,manifest:c}=Bi(await _i(r,i,o),r,e),{bytes:f,integrity:p}=await Mi(r,c,i,o),h=await gt(f),$=Rt(h,r,a);return{id:Z(r,a),key:Ie(r,a,p),manifest:$,integrity:p,files:h}}var Q=F(D(),1);function Yi(r,e,t){return Q.default.validRange(t)?Object.values(r?.packages??{}).filter(n=>n.name===e&&Q.default.satisfies(n.version,t)).sort((n,i)=>Q.default.rcompare(n.version,i.version))[0]??null:null}function It({registry:r="https://registry.npmjs.org/",fetchImpl:e=fetch,signal:t,download:s=ye,previous:n}){let i=new Map;return async(o,a)=>{let c=`${o}@${a}`;if(i.has(c))return i.get(c);let f=Yi(n,o,a),p=await s(o,f?.version??a,{registry:r,fetchImpl:e,signal:t});if(f&&p.integrity!==f.integrity)throw new Error(`${p.id} no longer matches the integrity recorded in the lock`);return i.set(c,p),p}}var yt=F(D(),1),Lt=(r,e,t)=>new Error(`${r.name}@${r.version} requires peer ${e}@${t}; install a compatible root explicitly`);function Ji(r,e,t){if(r.manifest.peerDependenciesMeta?.[e]?.optional)return null;throw Lt(r,e,t)}function Ki(r,[e,t],{nodes:s,roots:n}){let i=n[e]?.id??r.dependencies[e];if(!i)return Ji(r,e,t);if(!yt.default.satisfies(s[i].version,t))throw Lt(r,e,t);return i}function Zi(r,e){for(let t of Object.entries(r.manifest.peerDependencies??{})){let s=Ki(r,t,e);s&&(r.dependencies[t[0]]=s)}}function Ot(r,e){for(let t of Object.values(r))Zi(t,{nodes:r,roots:e})}var Nt=F(D(),1);function Qi(r,e){return!Re(e.name)||!Nt.default.valid(e.version)?!1:r===Z(e.name,e.version)}function eo(r){return r.integrity?.startsWith("sha512-")?r.key===Ie(r.name,r.version,r.integrity):!1}function ro(r,e,t){if(!Qi(e,t)||!eo(t))throw new Error("Invalid locked package");for(let s of t.files)j(s);if(Object.values(t.dependencies).some(s=>!r.packages[s]))throw new Error("Dangling locked dependency")}function to(r){return r?.format!==1?!1:!!r.roots&&!!r.packages}function so(r){if(!to(r))throw new Error("Unsupported package lock");for(let[e,t]of Object.entries(r.packages))ro(r,e,t);if(Object.values(r.roots).some(e=>!r.packages[e.id]))throw new Error("Dangling locked root");return r}function no(r,e,t){if(Object.keys(r.nodes).length>=512)throw new Error("Dependency graph exceeds 512 packages");for(let s of t.files.values())r.total+=s.length;if(r.total>256*1024*1024)throw new Error("Dependency graph exceeds 256 MiB");r.nodes[t.id]={name:e,version:t.manifest.version,integrity:t.integrity,key:t.key,manifest:t.manifest,files:[...t.files.keys()].sort(),dependencies:{}},r.downloads.set(t.id,t.files)}async function io(r,e){let t={};for(let s of r){let{name:n,version:i}=Ne(s);t[n]={requested:i||"latest",id:await e(n,i||"latest")}}return t}async function Ra(r,e={}){let t=It(e),s={nodes:{},downloads:new Map,total:0},n=async(o,a)=>{e.signal?.throwIfAborted();let c=await t(o,a);if(s.nodes[c.id])return c.id;no(s,o,c);for(let[f,p]of Object.entries(c.manifest.dependencies??{}).sort())s.nodes[c.id].dependencies[f]=await n(f,p);return c.id},i=await io(r,n);return Ot(s.nodes,i),{lock:{format:1,registry:e.registry??"https://registry.npmjs.org/",roots:i,packages:s.nodes},downloads:s.downloads}}export{ye as downloadPackage,Ra as resolvePackages,j as safePackagePath,so as validateLock}; diff --git a/src/developer/packages.mjs b/src/developer/packages.mjs new file mode 100644 index 00000000..4fd6004d --- /dev/null +++ b/src/developer/packages.mjs @@ -0,0 +1,46 @@ +// npm library resolution for the browser. Tools continue to use the existing wf installer. +import {parseSpec} from '../components/tools/wf.mjs'; +import {downloadPackage} from './registry.mjs'; +import {pinnedDownloader} from './pins.mjs'; +import {connectPeers} from './peers.mjs'; +import {validateLock} from './lock.mjs'; + +import {safePackagePath} from './paths.mjs'; +export {safePackagePath, downloadPackage, validateLock}; + +function addNode(state, name, pkg) { + if (Object.keys(state.nodes).length >= 512) throw new Error('Dependency graph exceeds 512 packages'); + for (const bytes of pkg.files.values()) state.total += bytes.length; + if (state.total > 256 * 1024 * 1024) throw new Error('Dependency graph exceeds 256 MiB'); + state.nodes[pkg.id] = {name, version: pkg.manifest.version, integrity: pkg.integrity, key: pkg.key, + manifest: pkg.manifest, files: [...pkg.files.keys()].sort(), dependencies: {}}; + state.downloads.set(pkg.id, pkg.files); +} + +async function resolveRoots(specifications, visit) { + const roots = {}; + for (const spec of specifications) { + const {name, version} = parseSpec(spec); + roots[name] = {requested: version || 'latest', id: await visit(name, version || 'latest')}; + } + return roots; +} + +// A distinct node per exact version; edges are retained instead of flattening node_modules. +export async function resolvePackages(specifications, options = {}) { + const fetchPackage = pinnedDownloader(options); + const state = {nodes: {}, downloads: new Map(), total: 0}; + const visit = async (name, range) => { + options.signal?.throwIfAborted(); + const pkg = await fetchPackage(name, range); + if (state.nodes[pkg.id]) return pkg.id; // includes cycles currently being resolved + addNode(state, name, pkg); + for (const [dependency, version] of Object.entries(pkg.manifest.dependencies ?? {}).sort()) + state.nodes[pkg.id].dependencies[dependency] = await visit(dependency, version); + // Optional dependencies are intentionally not installed in v1. An import of one fails clearly. + return pkg.id; + }; + const roots = await resolveRoots(specifications, visit); + connectPeers(state.nodes, roots); + return {lock: {format: 1, registry: options.registry ?? 'https://registry.npmjs.org/', roots, packages: state.nodes}, downloads: state.downloads}; +} diff --git a/src/developer/paths.mjs b/src/developer/paths.mjs new file mode 100644 index 00000000..4e5b9831 --- /dev/null +++ b/src/developer/paths.mjs @@ -0,0 +1,13 @@ +const forbidden = /[\\\0:*?"<>|]/; +const hasUnsafePart = path => path.split('/').some(part => !part || part === '.' || part === '..'); + +export function isUnsafe(path) { + if (typeof path !== 'string' || !path) return true; + if (forbidden.test(path)) return true; + return hasUnsafePart(path); +} + +export function safePackagePath(path) { + if (isUnsafe(path)) throw new Error(`Unsafe package path: ${path}`); + return path; +} diff --git a/src/developer/peers.mjs b/src/developer/peers.mjs new file mode 100644 index 00000000..652adc91 --- /dev/null +++ b/src/developer/peers.mjs @@ -0,0 +1,28 @@ +// Peer dependencies: satisfied by an explicit root or a direct dependency, unless optional. +import semver from 'semver'; + +// Optional peers may be absent; others must be satisfied by a root or a direct dependency. +const peerError = (node, name, range) => new Error(`${node.name}@${node.version} requires peer ${name}@${range}; install a compatible root explicitly`); + +function optionalPeer(node, name, range) { + if (node.manifest.peerDependenciesMeta?.[name]?.optional) return null; + throw peerError(node, name, range); +} + +function peerOf(node, [name, range], {nodes, roots}) { + const peer = roots[name]?.id ?? node.dependencies[name]; + if (!peer) return optionalPeer(node, name, range); + if (!semver.satisfies(nodes[peer].version, range)) throw peerError(node, name, range); + return peer; +} + +function connectNode(node, graph) { + for (const requirement of Object.entries(node.manifest.peerDependencies ?? {})) { + const peer = peerOf(node, requirement, graph); + if (peer) node.dependencies[requirement[0]] = peer; + } +} + +export function connectPeers(nodes, roots) { + for (const node of Object.values(nodes)) connectNode(node, {nodes, roots}); +} diff --git a/src/developer/pins.mjs b/src/developer/pins.mjs new file mode 100644 index 00000000..34c73ea0 --- /dev/null +++ b/src/developer/pins.mjs @@ -0,0 +1,26 @@ +// Keeping the versions of an installed lock: a later install never moves or replaces them silently. +import semver from 'semver'; +import {downloadPackage} from './registry.mjs'; + +// The installed version satisfying a range, so that a later install never moves or replaces it silently. +function lockedNode(previous, name, range) { + if (!semver.validRange(range)) return null; + const candidates = Object.values(previous?.packages ?? {}).filter(node => node.name === name && semver.satisfies(node.version, range)); + return candidates.sort((a, b) => semver.rcompare(a.version, b.version))[0] ?? null; +} + +// Downloads each name@range once; versions already in options.previous are kept and their archives must +// still match the recorded integrity. +export function pinnedDownloader({registry = 'https://registry.npmjs.org/', fetchImpl = fetch, signal, download = downloadPackage, previous}) { + const requests = new Map(); + return async (name, range) => { + const request = `${name}@${range}`; + if (requests.has(request)) return requests.get(request); + const pinned = lockedNode(previous, name, range); + const pkg = await download(name, pinned?.version ?? range, {registry, fetchImpl, signal}); + if (pinned && pkg.integrity !== pinned.integrity) + throw new Error(`${pkg.id} no longer matches the integrity recorded in the lock`); + requests.set(request, pkg); + return pkg; + }; +} diff --git a/src/developer/recipe.mjs b/src/developer/recipe.mjs new file mode 100644 index 00000000..2c1c0b6a --- /dev/null +++ b/src/developer/recipe.mjs @@ -0,0 +1,33 @@ +// A starter's webfront.project.json: the entry file, exact dependency versions and the provider name. +import {safePackagePath} from './paths.mjs'; +import {isPlainObject} from './entry.mjs'; + +const decoder = new TextDecoder(); +const npmName = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/; +const exactVersion = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/; + +function requireExactDependencies(dependencies) { + if (!isPlainObject(dependencies)) throw new Error('Invalid starter project recipe'); + for (const [name, version] of Object.entries(dependencies)) + if (!npmName.test(name) || typeof version !== 'string' || !exactVersion.test(version)) + throw new Error('Starter dependencies must name exact npm versions'); +} + +function validProvider(provider) { + if (typeof provider !== 'string') return false; + return /^[A-Za-z_][A-Za-z0-9_]*$/.test(provider); +} + +function hasEntry(recipe, files) { + if (typeof recipe.entry !== 'string') return false; + return files.has(safePackagePath(recipe.entry)); +} + +export function recipeOf(files) { + const recipe = JSON.parse(decoder.decode(files.get('webfront.project.json'))); + if (recipe.format !== 1 || !hasEntry(recipe, files)) throw new Error('Invalid starter project recipe'); + requireExactDependencies(recipe.dependencies); + if (recipe.provider !== undefined && !validProvider(recipe.provider)) + throw new Error('Invalid starter provider name'); + return recipe; +} diff --git a/src/developer/registry.mjs b/src/developer/registry.mjs new file mode 100644 index 00000000..eb49dd26 --- /dev/null +++ b/src/developer/registry.mjs @@ -0,0 +1,57 @@ +// npm registry access: resolving a version, downloading and checking one package archive. +import semver from 'semver'; +import {responseBytes} from './io.mjs'; +import {verifyIntegrity} from '../components/tools/wf.mjs'; +import {readArchive, checkedManifest} from './archive.mjs'; + +export const safeName = name => /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(name); +export const idOf = (name, version) => `${name.replace('/', '+')}@${version}`; +export const cacheKey = (name, version, integrity) => `${idOf(name, version)}-${integrity.slice(7).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '')}`; + +async function fetchPackument(name, base, {fetchImpl, signal}) { + const response = await fetchImpl(new URL(name.replace('/', '%2f'), base), {signal}); + if (!response.ok) throw new Error(`Registry metadata for ${name}: HTTP ${response.status}`); + return response.json(); +} + +function resolveVersion(packument, spec) { + const tagged = packument['dist-tags']?.[spec]; + if (tagged) return tagged; + if (semver.valid(spec)) return spec; + return semver.maxSatisfying(Object.keys(packument.versions ?? {}), spec); +} + +function selectVersion(packument, name, requested) { + const spec = requested || 'latest'; + const version = resolveVersion(packument, spec); + const manifest = packument.versions?.[version]; + if (!manifest || !semver.valid(version)) throw new Error(`Cannot resolve ${name}@${spec}`); + return {version, manifest}; +} + +async function fetchTarball(name, manifest, base, {fetchImpl, signal}) { + const tarball = new URL(manifest.dist?.tarball, base); + if (tarball.protocol !== 'https:' && tarball.origin !== base.origin) + throw new Error('Package tarballs must use HTTPS or the registry origin'); + const archive = await fetchImpl(tarball, {signal}); + if (!archive.ok) throw new Error(`Package download for ${name}: HTTP ${archive.status}`); + const bytes = await responseBytes(archive); + return {bytes, integrity: await verifyIntegrity(bytes, manifest.dist.integrity)}; +} + +function registryBase(registry) { + const base = new URL(registry, globalThis.location?.href); + if (!base.pathname.endsWith('/')) base.pathname += '/'; + return base; +} + +export async function downloadPackage(name, requested, {registry, fetchImpl = fetch, signal}) { + if (!safeName(name)) throw new Error(`Unsupported npm package name: ${name}`); + const base = registryBase(registry); + const context = {fetchImpl, signal}; + const {version, manifest} = selectVersion(await fetchPackument(name, base, context), name, requested); + const {bytes, integrity} = await fetchTarball(name, manifest, base, context); + const files = await readArchive(bytes); + const pkg = checkedManifest(files, name, version); + return {id: idOf(name, version), key: cacheKey(name, version, integrity), manifest: pkg, integrity, files}; +} diff --git a/src/developer/resolve.mjs b/src/developer/resolve.mjs new file mode 100644 index 00000000..e4d91540 --- /dev/null +++ b/src/developer/resolve.mjs @@ -0,0 +1,48 @@ +// Import resolution for the virtual project/npm filesystem: relative, bare and "browser" field specifiers. +import {isPlainObject, normalize, packageEntry} from './entry.mjs'; + +const dirname = path => path.split('/').slice(0, -1).join('/'); +const packageId = importer => importer.split('/')[0]; +const packagePath = importer => importer.slice(importer.indexOf('/') + 1); + +// The package.json "browser" object may redirect, hide or replace a specifier of the importing package. +function applyBrowserField(importerNode, args) { + const browser = importerNode?.manifest.browser; + if (!isPlainObject(browser)) return {specifier: args.path}; + const relative = args.path.startsWith('.') ? './' + normalize(dirname(packagePath(args.importer)) + '/' + args.path) : args.path; + const mapped = browser[relative]; + if (mapped === false) return {empty: true, specifier: args.path}; + if (typeof mapped !== 'string') return {specifier: args.path}; + if (mapped.startsWith('.')) return {local: `${packageId(args.importer)}/${normalize(mapped)}`, specifier: args.path}; + return {specifier: mapped}; +} + +function resolveRelative(args, specifier, find) { + if (args.namespace !== 'npm') return find('project', normalize(dirname(args.importer) + '/' + specifier)); + return find('npm', `${packageId(args.importer)}/${normalize(dirname(packagePath(args.importer)) + '/' + specifier)}`); +} + +function dependencyId(args, name, importerNode, lock) { + if (!importerNode) return lock.roots[name]?.id; + return importerNode.name === name ? packageId(args.importer) : importerNode.dependencies[name]; +} + +function resolveBare(args, specifier, importerNode, {lock, find}) { + const parts = specifier.split('/'); + const name = parts.splice(0, specifier.startsWith('@') ? 2 : 1).join('/'); + const id = dependencyId(args, name, importerNode, lock); + if (!id) throw new Error(`Uninstalled browser dependency: ${specifier}`); + const kind = args.kind.startsWith('require') ? 'require' : 'import'; + return find('npm', `${id}/${packageEntry(lock.packages[id].manifest, parts.join('/'), kind)}`); +} + +export async function resolveImport(args, lock, find) { + if (args.kind === 'entry-point') return find('project', normalize(args.path)); + const importerNode = args.namespace === 'npm' ? lock.packages[packageId(args.importer)] : null; + const browser = applyBrowserField(importerNode, args); + if (browser.empty) return {path: browser.specifier, namespace: 'empty'}; + if (browser.local) return find('npm', browser.local); + if (browser.specifier.startsWith('.')) return resolveRelative(args, browser.specifier, find); + if (/^(?:[a-z]+:|\/|#)/i.test(browser.specifier)) throw new Error(`Unsupported browser import: ${browser.specifier}`); + return resolveBare(args, browser.specifier, importerNode, {lock, find}); +} diff --git a/src/developer/runtime.mjs b/src/developer/runtime.mjs new file mode 100644 index 00000000..5b83914c --- /dev/null +++ b/src/developer/runtime.mjs @@ -0,0 +1,184 @@ +import {Terminal} from '../../third_party/xterm/xterm.mjs'; +import {FitAddon} from '../../third_party/xterm/addon-fit.mjs'; +import {LineEditor, tokenize} from '../components/terminal/terminal.mjs'; +import {resolvePackages, validateLock, downloadPackage} from './packages.mjs'; +import {readProject, publish} from './io.mjs'; +import {createStarter} from './starter.mjs'; +import {generateProvider, applicationPage} from './embed.mjs'; + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); +const lockPath = 'webfront-packages.lock.json'; +const packageRoot = '.webfront/developer/packages'; +export async function readLock(bridge, optional = false) { + try { return validateLock(JSON.parse(decoder.decode(await readProject(bridge, lockPath)))); } + catch (error) { + if (optional && error.message.includes('Cannot read project file:')) + return {format: 1, roots: {}, packages: {}}; + throw error; + } +} + +const splitSpec = spec => { + const at = spec.indexOf('@', spec.startsWith('@') ? 1 : 0); + return at < 0 ? [spec, 'latest'] : [spec.slice(0, at), spec.slice(at + 1)]; +}; + +// The installed roots keep their exact versions unless a requested spec replaces them. +function requestedRoots(previous, specs) { + const requested = new Map(Object.entries(previous.roots).map(([name, root]) => [name, previous.packages[root.id].version])); + for (const spec of specs) requested.set(...splitSpec(spec)); + return [...requested].map(([name, version]) => `${name}@${version}`); +} + +const textFile = text => new Map([['output', encoder.encode(text)]]); + +export async function install(bridge, specs, {registry, signal, progress = () => {}, fetchImpl = fetch}) { + if (!specs.length) throw new Error('Usage: wf install [@version] ...'); + const previous = await readLock(bridge, true); + const {lock, downloads} = await resolvePackages(requestedRoots(previous, specs), { + registry, signal, fetchImpl, previous, + download: async (...args) => { progress(`Resolving ${args[0]}@${args[1]}`); return downloadPackage(...args); }, + }); + for (const [id, files] of downloads) { + progress(`Storing ${id}`); + await publish(bridge, `${packageRoot}/${lock.packages[id].key}`, files, {signal}); + } + // The lock file is the installation commit point. A failed install may leave unused cache files. + await publish(bridge, lockPath, textFile(JSON.stringify(lock, null, 2) + '\n'), {directory: false, signal}); + return lock; +} + +async function readPackages(bridge, lock, signal) { + const packages = {}; + for (const [id, node] of Object.entries(lock.packages)) { + packages[id] = new Map(); + for (const path of node.files) { + signal?.throwIfAborted(); + packages[id].set(path, await readProject(bridge, `${packageRoot}/${node.key}/${path}`)); + } + } + return packages; +} + +// Serves the worker's project reads and settles the build with its result or error. +async function onWorkerMessage(bridge, worker, finish, data) { + if (data.type === 'read') worker.postMessage(await answerRead(bridge, data)); + else if (data.type === 'result') finish(null, data.files); + else if (data.type === 'error') finish(new Error(data.error)); +} + +function buildInWorker(bridge, message, signal) { + return new Promise((resolve, reject) => { + const worker = new Worker(new URL('./compiler.mjs', import.meta.url), {type: 'module'}); + const finish = (error, files) => { + worker.terminate(); + clearTimeout(timeout); + signal?.removeEventListener('abort', abort); + error ? reject(error) : resolve(files); + }; + const abort = () => finish(signal.reason ?? new Error('Interrupted')); + const timeout = setTimeout(() => finish(new Error('Browser build timed out')), 120000); + signal?.addEventListener('abort', abort, {once: true}); + worker.onerror = event => finish(new Error(event.message || 'Compiler worker failed')); + worker.onmessage = ({data}) => onWorkerMessage(bridge, worker, finish, data); + if (signal?.aborted) abort(); + else worker.postMessage(message); + }); +} + +async function answerRead(bridge, {id, path}) { + try { return {type: 'read-result', id, bytes: await readProject(bridge, path)}; } + catch (error) { return {type: 'read-result', id, error: error.message}; } +} + +const licenseFile = /(^|\/)(licen[cs]e|copying|notice)(\.|$)/i; + +function dependencyNotices(lock, packages) { + const notices = [`WebFront browser build; lock format ${lock.format}`]; + for (const [id, node] of Object.entries(lock.packages).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) { + notices.push(`${id} ${node.integrity}`); + for (const [path, bytes] of packages[id]) + if (licenseFile.test(path)) notices.push(`${id}/${path}\n${decoder.decode(bytes)}`); + } + return notices.join('\n\n'); +} + +export async function compile(bridge, entry, signal) { + const lock = await readLock(bridge); + const packages = await readPackages(bridge, lock, signal); + const files = await buildInWorker(bridge, {type: 'build', entry, lock, packages}, signal); + files.set('index.html', applicationPage(files)); + return {files, notices: dependencyNotices(lock, packages)}; +} + +async function create([starter, directory, ...extra], {bridge, config, signal}) { + if (!starter || extra.length) throw new Error('Usage: wf create [directory]'); + return createStarter(bridge, config, [starter, directory ?? 'ui'], {signal}); +} + +async function installCommand(specs, {bridge, config, signal, write = () => {}}) { + const lock = await install(bridge, specs, {registry: config.registry, signal, progress: text => write(text + '\r\n')}); + return `Installed ${Object.keys(lock.packages).length} packages. Lock: ${lockPath}`; +} + +async function preview([entry], {bridge, signal, preview: frame}) { + if (!entry) throw new Error('Usage: wf preview '); + const result = await compile(bridge, entry, signal); + await publish(bridge, '.webfront/developer/preview', result.files, {signal}); + frame.hidden = false; + // Replace transient builds without accumulating browser session history. + frame.contentWindow.location.replace(`/webfront/developer/preview/index.html?build=${Date.now()}`); + return 'Preview ready.'; +} + +async function embed([entry, flag, output, ...extra], {bridge, signal}) { + if (!entry) throw new Error('Usage: wf embed --output '); + if (flag !== '--output' || extra.length || !output?.endsWith('.hpp')) throw new Error('wf embed requires --output '); + const result = await compile(bridge, entry, signal); + const className = output.split('/').pop().slice(0, -4); + await publish(bridge, output, textFile(generateProvider(result.files, className, result.notices)), {directory: false, signal}); + return `Generated ${output}. Use webfront::fs::${className} and recompile the application.`; +} + +async function list(_args, {bridge}) { + const lock = await readLock(bridge, true); + return Object.keys(lock.packages).sort().join('\n') || 'No installed packages.'; +} + +const help = () => 'wf create [directory]\nwf install [@version] ...\nwf list\nwf preview \nwf embed --output \nCtrl+C interrupts a browser command. No system shell is exposed.'; +const commands = {create, install: installCommand, preview, embed, list, help}; + +export async function execute(args, context) { + const [command = 'help', ...rest] = args; + if (!Object.hasOwn(commands, command)) throw new Error(`Unknown wf command: ${command}`); + return commands[command](rest, context); +} + +export async function mount({bridge, config, terminal: element, preview}) { + const link = document.createElement('link'); + link.rel = 'stylesheet'; + link.href = new URL('./xterm.css', import.meta.url).href; + await new Promise((resolve, reject) => { + link.onload = resolve; + link.onerror = () => reject(new Error('Cannot load terminal styles')); + document.head.append(link); + }); + const terminal = new Terminal({cursorBlink: true, theme: {background: '#141821'}}); + const fit = new FitAddon(); + terminal.loadAddon(fit); + terminal.open(element); + fit.fit(); + new ResizeObserver(() => fit.fit()).observe(element); + const write = text => terminal.write(text); + const editor = new LineEditor({write, prompt: 'wf> ', complete: async () => 'wf', run: async (line, signal) => { + const args = tokenize(line); + if (args.shift() !== 'wf') throw new Error('Use wf help to list commands'); + return execute(args, {bridge, config, preview, signal, write}); + }}); + terminal.onData(data => editor.handle(data)); + write('WebFront browser-powered developer environment\r\n'); + editor.showPrompt(); + terminal.focus(); + return {terminal, editor}; +} diff --git a/src/developer/starter.mjs b/src/developer/starter.mjs new file mode 100644 index 00000000..d59ecb03 --- /dev/null +++ b/src/developer/starter.mjs @@ -0,0 +1,42 @@ +import {gunzip, readTar, verifyIntegrity} from '../components/tools/wf.mjs'; +import {safePackagePath} from './paths.mjs'; +import {publish, responseBytes} from './io.mjs'; +import {recipeOf} from './recipe.mjs'; +export {recipeOf}; + +function starterUrl(starter) { + if (!starter?.url || !starter.integrity?.startsWith('sha512-')) throw new Error('Unknown pinned starter'); + const url = new URL(starter.url, location.href); + if (url.protocol !== 'https:' && url.origin !== location.origin) throw new Error('Starter requires HTTPS or the application origin'); + return url; +} + +async function unpackStarter(bytes) { + const files = new Map(); + for (const entry of readTar(await gunzip(bytes))) { + if (!entry.path.startsWith('package/')) throw new Error('Invalid starter archive root'); + const path = safePackagePath(entry.path.slice(8)); + if (files.has(path)) throw new Error('Duplicate starter file'); + files.set(path, entry.bytes); + } + return files; +} + +async function downloadStarter(starter, {signal, fetchImpl}) { + const bytes = await responseBytes(await fetchImpl(starterUrl(starter), {signal})); + await verifyIntegrity(bytes, starter.integrity); + return unpackStarter(bytes); +} + +export async function createStarter(bridge, config, [name, destination = 'ui'], {signal, fetchImpl = fetch} = {}) { + safePackagePath(destination); + const starter = config.starters?.[name]; + if (!starter) throw new Error(`Unknown pinned starter: ${name}`); + const files = await downloadStarter(starter, {signal, fetchImpl}); + const recipe = recipeOf(files); + signal?.throwIfAborted(); + // A starter must never overwrite an existing directory, including a symlink or partial project. + await publish(bridge, destination, files, {signal, replace: false}); + const install = Object.entries(recipe.dependencies).map(([pkg, version]) => `${pkg}@${version}`).join(' '); + return `Created ${destination}.\nwf install ${install}\nwf preview ${destination}/${recipe.entry}\nwf embed ${destination}/${recipe.entry} --output generated/${recipe.provider ?? 'PiUI'}.hpp`; +} diff --git a/src/life/main.tsx b/src/life/main.tsx new file mode 100644 index 00000000..422f14cf --- /dev/null +++ b/src/life/main.tsx @@ -0,0 +1,185 @@ +import React, {useEffect, useRef, useState} from 'react'; +import {createRoot} from 'react-dom/client'; +import './style.css'; + +declare const webFront: {ready: Promise; cppFunction(name: string): (grid: Uint8Array) => Promise}; +const size = 32; +const byteCount = size * size / 8; +const empty = () => new Uint8Array(byteCount); +const isAlive = (cells: Uint8Array, i: number) => (cells[i >> 3] & (1 << (i & 7))) !== 0; +function toggleCell(cells: Uint8Array, i: number) { + const next = cells.slice(); + next[i >> 3] ^= 1 << (i & 7); + return next; +} +const shapes: Record = { + Glider: [[1, 0], [2, 1], [0, 2], [1, 2], [2, 2]], + Blinker: [[0, 1], [1, 1], [2, 1]], + Galaxy: [[1, 0], [2, 0], [0, 1], [1, 1], [1, 2]], +}; +function seed(name: string) { + const cells = empty(); + const offsets = name === 'Galaxy' ? [[7, 7], [21, 9], [13, 22]] : [[14, 14]]; + for (const [ox, oy] of offsets) + for (const [x, y] of shapes[name]) { + const i = (y + oy) * size + x + ox; + cells[i >> 3] |= 1 << (i & 7); + } + return cells; +} + +type Painter = CanvasRenderingContext2D; +type Cell = {x: number; y: number; alive: boolean}; +type Point = {x: number; y: number}; +function fillTile(context: Painter, points: number[][], fill: string, stroke?: string) { + context.beginPath(); points.forEach(([x, y], i) => i ? context.lineTo(x, y) : context.moveTo(x, y)); + context.closePath(); context.fillStyle = fill; context.fill(); + if (stroke) { context.strokeStyle = stroke; context.lineWidth = .7; context.stroke(); } +} +function paintFlat(context: Painter, {x, y, alive}: Cell) { + context.fillStyle = alive ? '#bcf8df' : 'rgba(159,202,194,.07)'; + context.fillRect(209 + x * 17, 65 + y * 17, 15, 15); +} +function paintSpatial(context: Painter, {x, y, alive}: Cell) { + const px = 480 + (x - y) * 13, py = 115 + (x + y) * 7; + const lift = alive ? 20 : 0; + fillTile(context, [[px, py - lift], [px + 12, py + 6 - lift], [px, py + 12 - lift], [px - 12, py + 6 - lift]], + alive ? '#c8ffe4' : 'rgba(145,190,182,.075)', alive ? '#eefff8' : 'rgba(160,207,195,.12)'); + if (!alive) return; + fillTile(context, [[px - 12, py + 6 - lift], [px, py + 12 - lift], [px, py + 12], [px - 12, py + 6]], '#529a83'); + fillTile(context, [[px, py + 12 - lift], [px + 12, py + 6 - lift], [px + 12, py + 6], [px, py + 12]], '#7fc5a6'); +} +function paintBoard(element: HTMLCanvasElement, cells: Uint8Array, flat: boolean) { + const ratio = window.devicePixelRatio || 1; + const {width, height} = element.getBoundingClientRect(); + element.width = Math.round(width * ratio); element.height = Math.round(height * ratio); + const context = element.getContext('2d')!; + context.scale(ratio * width / 960, ratio * height / 680); + const paint = flat ? paintFlat : paintSpatial; + for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) paint(context, {x, y, alive: isAlive(cells, y * size + x)}); +} +// The cell under a point of the 960 x 680 scene, or -1 outside the board. +function cellAt({x: px, y: py}: Point, flat: boolean) { + const x = flat ? Math.floor((px - 209) / 17) : Math.floor(((px - 480) / 13 + (py - 115) / 7) / 2); + const y = flat ? Math.floor((py - 65) / 17) : Math.floor(((py - 115) / 7 - (px - 480) / 13) / 2); + const inside = (value: number) => value >= 0 && value < size; + return inside(x) && inside(y) ? y * size + x : -1; +} + +function Board({cells, flat, toggle}: {cells: Uint8Array; flat: boolean; toggle: (index: number) => void}) { + const canvas = useRef(null); + useEffect(() => { + const element = canvas.current!; + const draw = () => paintBoard(element, cells, flat); + draw(); + const observer = new ResizeObserver(draw); observer.observe(element); + return () => observer.disconnect(); + }, [cells, flat]); + return { + const rect = event.currentTarget.getBoundingClientRect(); + const index = cellAt({x: (event.clientX - rect.left) * 960 / rect.width, y: (event.clientY - rect.top) * 680 / rect.height}, flat); + if (index >= 0) toggle(index); + }}/>; +} + +type Session = {cells: Uint8Array; revision: number; pending: boolean; mounted: boolean}; +const isCurrent = (session: Session, revision: number) => session.mounted && revision === session.revision; +// The next generation from C++, or null when the session moved on while waiting. +async function nextGeneration(session: Session, revision: number) { + await webFront.ready; + if (!isCurrent(session, revision)) return null; + const next = await webFront.cppFunction('life.step')(session.cells); + if (!isCurrent(session, revision)) return null; + if (!(next instanceof Uint8Array) || next.length !== byteCount) throw new Error('Invalid C++ generation'); + return next; +} +const countBits = (cells: Uint8Array) => cells.reduce((count, byte) => { while (byte) { count += byte & 1; byte >>>= 1; } return count; }, 0); + +function Telemetry({generation, population}: {generation: number; population: number}) { + return ; +} + +type ControlProps = {playing: boolean; busy: boolean; speed: number; flat: boolean; pattern: string; + onPlay: () => void; onStep: () => void; onSpeed: (speed: number) => void; onPattern: (name: string) => void; + onClear: () => void; onView: () => void}; +function Controls({playing, busy, speed, flat, pattern, onPlay, onStep, onSpeed, onPattern, onClear, onView}: ControlProps) { + return
+ +
+ +
{Object.keys(shapes).map(name => )} +
+ +
; +} + +type Flag = {current: T}; +// While playing, steps at the chosen rate; a step that is still pending delays the next tick. +function usePlayback(playing: boolean, run: Flag, rate: Flag, step: () => Promise) { + useEffect(() => { + if (!playing) return; + let stopped = false; + let timer: ReturnType; + async function tick() { + if (stopped || !run.current) return; + await step(); + if (!stopped && run.current) timer = setTimeout(tick, 1000 / rate.current); + } + timer = setTimeout(tick, 1000 / rate.current); + return () => { stopped = true; clearTimeout(timer); }; + }, [playing]); +} + +function Life() { + const [cells, setCells] = useState(() => seed('Galaxy')); + const [generation, setGeneration] = useState(0); + const [playing, setPlaying] = useState(false); + const [speed, setSpeed] = useState(8); + const [flat, setFlat] = useState(false); + const [pattern, setPattern] = useState('Galaxy'); + const [error, setError] = useState(''); + const [busy, setBusy] = useState(false); + const state = useRef({cells, revision: 0, pending: false, mounted: true}); + const run = useRef(playing); run.current = playing; + const rate = useRef(speed); rate.current = speed; + useEffect(() => { state.current.mounted = true; return () => { state.current.mounted = false; }; }, []); + function replace(value: Uint8Array, name: string) { + run.current = false; setPlaying(false); state.current.revision++; + state.current.cells = value; setCells(value); setGeneration(0); setPattern(name); setError(''); + } + async function step() { + const current = state.current; + if (current.pending || !current.mounted) return; + current.pending = true; setBusy(true); + const revision = current.revision; + try { + const next = await nextGeneration(current, revision); + if (next) { current.cells = next; setCells(next); setGeneration(value => value + 1); setError(''); } + } catch (error) { + if (isCurrent(current, revision)) { setError(String(error)); run.current = false; setPlaying(false); } + } finally { current.pending = false; if (current.mounted) setBusy(false); } + } + usePlayback(playing, run, rate, step); + const population = countBits(cells); + return
+
✳ FIELD/ 01 + A small universe, computed in C++23 Native engine
+
+
CONWAY’S GAME OF LIFE

Order.
From almost nothing.

+

Three simple rules.
An entire world of possibilities.

+
replace(toggleCell(state.current.cells, index), 'Custom')}/>
+ +
B3 / S23 CLICK THE FIELD TO PLANT A CELL 32²
+
+ {run.current = !playing; setPlaying(!playing);}} onStep={() => {void step();}} onSpeed={setSpeed} + onPattern={name => replace(seed(name), name)} onClear={() => replace(empty(), 'Empty')} onView={() => setFlat(!flat)}/> +

A bitset in C++. A world in your browser. WebFront · React · no Node.js runtime

+

{error}

+
; +} +createRoot(document.getElementById('root')!).render(); diff --git a/src/life/style.css b/src/life/style.css new file mode 100644 index 00000000..cb7905b1 --- /dev/null +++ b/src/life/style.css @@ -0,0 +1 @@ +:root{font-family:Inter,"Avenir Next",system-ui,sans-serif;color:#e8f4ed;background:#101c1d;color-scheme:dark;font-synthesis:none}*{box-sizing:border-box}body{margin:0}button,input{font:inherit}button{cursor:pointer}button:focus-visible,input:focus-visible,a:focus-visible{outline:2px solid #d5ffd7;outline-offset:4px}button:disabled{opacity:.4;cursor:wait}.observatory{min-height:100svh;padding:28px 4vw 12px;overflow:hidden;position:relative;background:radial-gradient(ellipse at 54% 44%,#2c4d46 0%,transparent 58%),radial-gradient(ellipse at 100% 0%,#263332 0%,transparent 55%),#101c1d}header{display:flex;align-items:center;justify-content:space-between;gap:20px;position:relative;z-index:2}.identity{font-size:20px;letter-spacing:.2em;text-decoration:none;color:inherit;display:flex;align-items:center;gap:12px}.mark{font-size:32px;color:#c1e5c2}.edition{font-size:11px;color:#91a7a0;letter-spacing:.03em}.eyebrow{font-size:10px;letter-spacing:.15em;color:#9eb6ac;line-height:1.6}.engine{font-size:11px;color:#c9d9ce;white-space:nowrap}.engine i{display:inline-block;width:6px;height:6px;margin-right:8px;border-radius:50%;background:#b7edba;box-shadow:0 0 12px #a2edaf}.scene{position:relative;min-height:510px;height:calc(100svh - 225px);max-height:850px}.intro{position:absolute;top:13%;left:0;z-index:1;pointer-events:none}h1{font-size:clamp(28px,3.3vw,48px);font-weight:400;line-height:1.1;letter-spacing:-.055em;margin:15px 0 20px}.intro p{color:#91a9a0;font-size:12px;line-height:1.8}.world{position:absolute;inset:-5% 1% -3% 9%;display:flex;align-items:center;justify-content:center}canvas{position:relative;width:100%;height:100%;max-width:1100px;cursor:crosshair}.halo{position:absolute;width:60%;height:38%;left:22%;top:40%;border-radius:50%;background:#93ddae18;filter:blur(65px);transform:rotate(-18deg)}.glass{background:linear-gradient(135deg,#f1fff111,#d7ffe907 70%);border:1px solid #deffe328;border-top-color:#e4ffe34d;box-shadow:0 18px 60px #0003,inset 0 1px 1px #fff1;backdrop-filter:blur(24px) saturate(140%);-webkit-backdrop-filter:blur(24px) saturate(140%)}.telemetry{position:absolute;right:0;top:15%;padding:21px 24px;border-radius:20px;min-width:145px}.telemetry>div{margin-top:20px;display:flex;flex-direction:column;gap:4px}.telemetry output{font-size:30px;font-weight:300;letter-spacing:-.04em;font-variant-numeric:tabular-nums}.telemetry div span,.boundary{font-size:10px;color:#9db5a9}.boundary{display:block;margin-top:24px;font-size:9px}.coordinates{position:absolute;bottom:7%;left:0;right:0;display:flex;justify-content:space-between;font:9px ui-monospace,monospace;letter-spacing:.08em;color:#78968b}.coordinates span{font-size:8px}.controls{position:relative;z-index:2;display:flex;align-items:center;justify-content:space-between;gap:18px;padding:12px 15px;border-radius:23px;max-width:1120px;margin:auto}.controls button{border:1px solid transparent;background:transparent;color:#c2d4c8;padding:10px 13px;border-radius:12px;font-size:11px;white-space:nowrap;transition:background .18s}.controls button:hover{background:#e7ffe414}.controls button[aria-pressed=true]{background:#dfffdf16;color:#efffe9;border-color:#c7e8ca26}.transport{display:flex;gap:4px}.controls .primary{background:#dcf1cb;color:#183227;min-width:89px;box-shadow:inset 0 1px #fff8,0 3px 12px #0002}.controls .primary:hover{background:#edffdc}.speed{display:flex;align-items:center;gap:10px;font-size:10px;color:#9db7a8}.speed input{width:65px;accent-color:#c9e8b7}.speed span{min-width:24px;font-variant-numeric:tabular-nums}.patterns{display:flex;gap:2px}.controls .view{border-left:1px solid #b2c9bc26;border-radius:0 12px 12px 0}.caption{display:flex;justify-content:space-between;color:#819c8e;font-size:9px;letter-spacing:.02em;max-width:1090px;margin:15px auto 0}.error{color:#ffc5ad;font-size:12px;margin:8px 0;min-height:14px}@media(max-width:1000px){header>.eyebrow{display:none}.controls{flex-wrap:wrap;justify-content:center;gap:7px 14px}.speed{margin-left:auto}.scene{min-height:450px}.intro{top:8%}.world{inset:8% -13% -5% -3%}.telemetry{top:8%;padding:15px;min-width:118px}.telemetry output{font-size:24px}.telemetry>div{margin-top:12px}}@media(max-width:560px){.observatory{padding:18px 18px 8px}.scene{height:450px;min-height:450px}.intro{top:7%}h1{font-size:28px}.intro p{font-size:10px}.telemetry{top:7%;padding:12px;min-width:98px}.telemetry .eyebrow{font-size:8px}.boundary{font-size:8px;max-width:80px;line-height:1.5}.world{inset:26% -25% 0 -25%}.coordinates{bottom:2%;font-size:8px}.coordinates span{display:none}.controls{border-radius:19px;padding:10px;gap:6px}.controls button{font-size:10px;padding:9px}.speed{margin-left:6px;gap:6px}.speed input{width:53px}.patterns{order:3;width:100%;justify-content:center}.controls .view{margin-left:auto}.caption{font-size:8px;gap:15px;line-height:1.5}.caption span{text-align:right}}@media(prefers-reduced-motion:reduce){*{transition:none!important}}@supports not (backdrop-filter:blur(1px)){.glass{background:#233730f5}} diff --git a/src/pi/main.tsx b/src/pi/main.tsx new file mode 100644 index 00000000..310df1f9 --- /dev/null +++ b/src/pi/main.tsx @@ -0,0 +1,29 @@ +import React, {useState} from 'react'; +import {createRoot} from 'react-dom/client'; +import './style.css'; + +declare const webFront: { + ready: Promise; + cppFunction(name: string): (digits: number) => Promise; +}; + +function Pi() { + const [digits, setDigits] = useState(50); + const [value, setValue] = useState(''); + const [error, setError] = useState(''); + async function calculate() { + try { + await webFront.ready; + setValue(await webFront.cppFunction('pi')(digits)); + setError(''); + } catch (error) { setError(String(error)); } + } + return

PI, calculated in C++

+ + + {value}

{error}

+
; +} + +createRoot(document.getElementById('root')!).render(); diff --git a/src/pi/style.css b/src/pi/style.css new file mode 100644 index 00000000..24a4da9e --- /dev/null +++ b/src/pi/style.css @@ -0,0 +1,5 @@ +body { font: 18px system-ui; margin: 3rem; color: #193445; background: #f7fafc; } +main { max-width: 52rem; margin: auto; } +input, button { font: inherit; margin: .5rem; padding: .4rem; } +output { display: block; overflow-wrap: anywhere; margin-top: 2rem; font-family: monospace; } +[role=alert] { color: #a02828; } diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 3d1c10ee..7d4917c8 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -17,7 +17,7 @@ list(APPEND TESTS_LIST JSFunctionTests.cpp TypeErasedFunctionTests.cpp MessagesT list(APPEND TESTS_LIST JasmineFSTests.cpp FileSystemTests.cpp NativeFSTests.cpp ReactFSTests.cpp BabelFSTests.cpp) list(APPEND TESTS_LIST DefaultFSTests.cpp StdnetShutdownTests.cpp TerminalTests.cpp TerminalFSTests.cpp UISubscribersTests.cpp) list(APPEND TESTS_LIST WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp ToolStoreTests.cpp ToolManagerTests.cpp) -list(APPEND TESTS_LIST StructuredShutdownTests.cpp JsFunctionSenderTests.cpp ApplicationTaskTests.cpp) +list(APPEND TESTS_LIST DeveloperTests.cpp LifeTests.cpp StructuredShutdownTests.cpp JsFunctionSenderTests.cpp ApplicationTaskTests.cpp) list(APPEND TESTS_LIST SignalDemoTests.cpp FrontendUrlTests.cpp ApplicationUrlTests.cpp FrontendContractTests.cpp) if(WEBFRONT_USE_MDDLOG) list(APPEND TESTS_LIST MddlogLoggerTests.cpp MddlogTransportTests.cpp) diff --git a/test/DeveloperTests.cpp b/test/DeveloperTests.cpp new file mode 100644 index 00000000..60a1b113 --- /dev/null +++ b/test/DeveloperTests.cpp @@ -0,0 +1,340 @@ +#include "../src/Pi.hpp" +#include "TemporaryDirectory.hpp" +#include +#include +#include + +#include +#include +#include + +using namespace webfront; +using webfront::test::TemporaryDirectory; + +namespace { +struct QuietFrontend { + static constexpr frontend::Action action{frontend::Action::keepServerRunning}; + + static void initialize() {} + + static void open(std::string_view, std::string_view) {} +}; + +std::vector bytes(std::string_view text) { + return {text.begin(), text.end()}; +} +std::string read(developer::Store& store, std::string path) { + auto data = store.read(std::move(path), 0); + return {data.begin(), data.end()}; +} +} // namespace + +SCENARIO("Developer publication preserves the installed files until commit") { + TemporaryDirectory project; + developer::Store store{project.path()}; + GIVEN("an installed output") { + auto first = store.begin("generated/PiUI.hpp", false); + store.write(first, "output", 0, bytes("old")); + store.commit(first); + WHEN("the next output is interrupted") { + auto second = store.begin("generated/PiUI.hpp", false); + store.write(second, "output", 0, bytes("partial")); + REQUIRE(read(store, "generated/PiUI.hpp") == "old"); + store.abort(second); + THEN("the installed output remains intact") { + REQUIRE(read(store, "generated/PiUI.hpp") == "old"); + } + } + WHEN("a complete replacement is committed") { + auto second = store.begin("generated/PiUI.hpp", false); + store.write(second, "output", 0, bytes("new")); + store.commit(second); + THEN("the new output replaces it") { + REQUIRE(read(store, "generated/PiUI.hpp") == "new"); + } + } + } +} + +SCENARIO("Developer writes are bounded and paths stay inside the explicit project") { + TemporaryDirectory project; + developer::Store store{project.path()}; + GIVEN("a staged preview") { + const auto id = store.begin(".webfront/developer/preview", true); + WHEN("the browser sends invalid chunks or paths") { + THEN("none are published") { + REQUIRE_THROWS(store.write(id, "../escape", 0, bytes("bad"))); + REQUIRE_THROWS(store.write(id, "index.html", 1, bytes("bad"))); + REQUIRE_THROWS(store.write(id, "big", 0, std::vector(developer::chunkSize + 1))); + REQUIRE_THROWS(store.begin("../escape", false)); + REQUIRE_THROWS(store.read("../escape", 0)); + REQUIRE_THROWS(store.begin(".webfront/developer/staging/x", true)); + REQUIRE_THROWS(store.begin(".webfront", true)); + REQUIRE_THROWS(store.begin(".webfront/developer", true)); + REQUIRE_THROWS(store.begin(".webfront/developer/preview/assets", true)); + } + } + WHEN("a zero-length file and a nested file are sent") { + store.write(id, "empty", 0, {}); + store.write(id, "assets/a.js", 0, bytes("abc")); + store.write(id, "assets/a.js", 3, bytes("def")); + store.commit(id); + THEN("both are readable after commit") { + REQUIRE(read(store, ".webfront/developer/preview/empty").empty()); + REQUIRE_THROWS(store.read(".webfront/developer/preview/assets", 0)); + REQUIRE(read(store, ".webfront/developer/preview/assets/a.js") == "abcdef"); + } + } + } + GIVEN("an escaping directory symlink") { + TemporaryDirectory outside; + std::error_code error; + std::filesystem::create_directory_symlink(outside.path(), project.path() / "escape", error); + if (!error) { + THEN("reads and destinations are rejected") { + REQUIRE_THROWS(store.begin("escape/new.hpp", false)); + REQUIRE_THROWS(store.read("escape/secret", 0)); + } + } + } +} + +SCENARIO("Developer filesystem serves only published resources and protects the bridge") { + TemporaryDirectory project; + developer::Store store{project.path()}; + fs::DeveloperFS filesystem{project.path()}; + GIVEN("published preview assets and private project files") { + const auto id = store.begin(".webfront/developer/preview", true); + store.write(id, "index.html", 0, bytes("preview")); + store.commit(id); + THEN("the preview and bootstrap are served but project sources are not") { + REQUIRE(filesystem.open("/webfront/developer/preview/index.html")); + REQUIRE(filesystem.open("/webfront-bootstrap.html")); + REQUIRE(filesystem.open("/webfront-bootstrap.mjs")); + REQUIRE(filesystem.open("/WebFront.js")); + REQUIRE_FALSE(filesystem.open("/CMakeLists.txt")); + REQUIRE_FALSE(filesystem.open("/webfront/developer/staging/file")); + REQUIRE_FALSE(filesystem.open("/webfront/developer/preview/../../secret")); + REQUIRE(http::MimeType("wasm").toString() == "application/wasm"); + } + } +} + +SCENARIO("The PI demonstration returns exact decimal strings and rejects excessive work") { + REQUIRE(demo::pi(0) == "3"); + REQUIRE(demo::pi(1) == "3.1"); + REQUIRE(demo::pi(50) == "3.14159265358979323846264338327950288419716939937510"); + REQUIRE(demo::pi(1000).size() == 1002); + REQUIRE_THROWS_AS(demo::pi(1001), std::invalid_argument); +} + +SCENARIO("A downloaded starter never replaces a developer's existing project") { + TemporaryDirectory project; + developer::Store store{project.path()}; + GIVEN("an existing project directory") { + std::filesystem::create_directories(project.path() / "ui"); + THEN("new-only publication refuses to stage over it") { + REQUIRE_THROWS(store.begin("ui", true, false)); + REQUIRE(std::filesystem::is_directory(project.path() / "ui")); + } + } + GIVEN("a new starter staged before its destination exists") { + auto id = store.begin("new-ui", true, false); + store.write(id, "main.tsx", 0, bytes("starter")); + WHEN("a local directory appears before commit") { + std::filesystem::create_directory(project.path() / "new-ui"); + THEN("commit refuses to replace that directory") { + REQUIRE_THROWS(store.commit(id)); + REQUIRE_FALSE(std::filesystem::exists(project.path() / "new-ui/main.tsx")); + store.abort(id); + } + } + WHEN("the destination remains new") { + store.commit(id); + THEN("the starter is published") { + REQUIRE(read(store, "new-ui/main.tsx") == "starter"); + } + } + } +} + +SCENARIO("Transactions abandoned by a disconnected browser never lock the project") { + TemporaryDirectory project; + const auto stagingRoot = project.path() / ".webfront/developer/staging"; + GIVEN("the maximum number of unfinished transactions") { + developer::Store store{project.path()}; + std::vector ids; + for (std::size_t index = 0; index < developer::maxTransactions; ++index) + ids.push_back(store.begin("generated/" + std::to_string(index), true)); + THEN("active transactions still bound the number of publications") { + REQUIRE_THROWS(store.begin("generated/extra", true)); + } + } + GIVEN("unfinished transactions left by a browser that reloaded") { + developer::Store store{project.path(), std::chrono::milliseconds{0}}; + std::vector ids; + for (std::size_t index = 0; index < developer::maxTransactions; ++index) + ids.push_back(store.begin("generated/" + std::to_string(index), true)); + WHEN("a new publication begins") { + const auto id = store.begin("generated/new", true); + THEN("the abandoned ones are discarded with their staging") { + REQUIRE_FALSE(std::filesystem::exists(stagingRoot / ids.front())); + REQUIRE_THROWS(store.write(ids.front(), "file", 0, bytes("late"))); + store.write(id, "file", 0, bytes("fresh")); + store.commit(id); + REQUIRE(read(store, "generated/new/file") == "fresh"); + } + } + } + GIVEN("staging left by a crashed process") { + std::filesystem::create_directories(stagingRoot / "1"); + std::filesystem::create_directories(stagingRoot / "2"); + std::filesystem::last_write_time(stagingRoot / "1", std::filesystem::file_time_type::clock::now() - std::chrono::hours{2}); + WHEN("the project is opened again") { + developer::Store store{project.path()}; + THEN("only the stale staging is removed") { + REQUIRE_FALSE(std::filesystem::exists(stagingRoot / "1")); + REQUIRE(std::filesystem::exists(stagingRoot / "2")); + } + } + } + GIVEN("a backup left by a crashed commit") { + developer::Store store{project.path()}; + auto first = store.begin("generated/out.hpp", false); + store.write(first, "output", 0, bytes("old")); + store.commit(first); + const auto second = store.begin("generated/out.hpp", false); + store.write(second, "output", 0, bytes("new")); + std::filesystem::create_directories(stagingRoot / (second + "-backup/inner")); + std::ofstream{stagingRoot / (second + "-backup/inner/file")} << "stale"; + THEN("the replacement still commits") { + store.commit(second); + REQUIRE(read(store, "generated/out.hpp") == "new"); + } + } +} + +SCENARIO("The staging area is protected however its path is spelled") { + TemporaryDirectory project; + developer::Store store{project.path()}; + GIVEN("a symbolic link to the staging area inside the project") { + std::filesystem::create_directories(project.path() / ".webfront/developer/staging"); + const auto victim = store.begin("victim", true); + std::error_code error; + std::filesystem::create_directory_symlink(project.path() / ".webfront/developer/staging", project.path() / "alias", error); + if (!error) { + THEN("it cannot be used as a publication destination") { + REQUIRE_THROWS(store.begin("alias", true)); + REQUIRE_THROWS(store.begin("alias/" + victim, true)); + } + } + store.abort(victim); + } +} + +SCENARIO("The developer bridge refuses WebSocket clients without an Origin") { + GIVEN("the default application configuration") { + REQUIRE(WebFrontConfig{}.contentPolicy.allowMissingOrigin); + WHEN("it is prepared for a developer project") { + const auto config = developer::projectConfig({}, "project"); + THEN("the project is the document root and a missing Origin is refused") { + REQUIRE(config.documentRoot == "project"); + REQUIRE_FALSE(config.contentPolicy.allowMissingOrigin); + } + } + } +} + +SCENARIO("Startup cleanup never leaves the project through a staging link") { + TemporaryDirectory project; + TemporaryDirectory outside; + GIVEN("a staging directory that is a link to an old file outside the project") { + const auto victim = outside.path() / "keep.txt"; + std::ofstream{victim} << "outside"; + std::filesystem::last_write_time(victim, std::filesystem::file_time_type::clock::now() - std::chrono::hours{3}); + std::filesystem::create_directories(project.path() / ".webfront/developer"); + std::error_code error; + std::filesystem::create_directory_symlink(outside.path(), project.path() / ".webfront/developer/staging", error); + if (!error) { + WHEN("the project is opened") { + developer::Store store{project.path()}; + THEN("the outside file is untouched") { + REQUIRE(std::filesystem::exists(victim)); + } + } + } + } +} + +SCENARIO("Paths differing only by case never share a staged file") { + TemporaryDirectory project; + developer::Store store{project.path()}; + GIVEN("a staged directory holding LICENSE") { + const auto id = store.begin("package", true); + store.write(id, "LICENSE", 0, bytes("first")); + WHEN("a second file whose name differs only by case is sent") { + THEN("it is refused and the first file keeps its content") { + REQUIRE_THROWS_AS(store.write(id, "License", 0, bytes("second")), std::invalid_argument); + store.write(id, "LICENSE", 5, bytes("!")); + store.commit(id); + REQUIRE(read(store, "package/LICENSE") == "first!"); + } + } + } +} + +SCENARIO("The developer store refuses malformed requests without changing the project") { + TemporaryDirectory project; + developer::Store store{project.path()}; + GIVEN("a project file and a single-output transaction") { + std::ofstream(project.path() / "notes.txt") << "text"; + const auto id = store.begin("generated/output.hpp", false); + THEN("invalid reads and writes are rejected") { + REQUIRE_THROWS_AS(store.read("notes.txt", std::numeric_limits::max()), std::invalid_argument); + REQUIRE_THROWS_AS(store.write(id, "other", 0, bytes("x")), std::invalid_argument); + REQUIRE_THROWS_AS(store.commit(id), std::runtime_error); + } + THEN("aborting is idempotent and ends the transaction") { + REQUIRE_NOTHROW(store.abort("unknown")); + REQUIRE_NOTHROW(store.abort(id)); + REQUIRE_THROWS_AS(store.commit(id), std::runtime_error); + } + } + GIVEN("an existing destination") { + std::ofstream(project.path() / "taken.txt") << "text"; + THEN("only the replacing form may publish over it") { + REQUIRE_THROWS_AS(store.beginNew("taken.txt", false), std::runtime_error); + REQUIRE_NOTHROW(store.abort(store.beginReplacing("taken.txt", false))); + } + } + GIVEN("a path that is not a directory") { + std::ofstream(project.path() / "file") << "x"; + THEN("it cannot be a project") { + REQUIRE_THROWS_AS(developer::Store{project.path() / "file"}, std::invalid_argument); + } + } +} + +SCENARIO("The developer application needs an explicit project and a trusted environment") { + using App = BasicDeveloperApp; + const DeveloperBootstrapOptions trusted{.environment = "https://example.test/env.tgz", .integrity = "sha512-abc"}; + GIVEN("no project directory") { + App app; + THEN("bootstrap is refused") { + REQUIRE_THROWS_AS(app.bootstrap("developer", trusted), std::invalid_argument); + } + } + GIVEN("a project directory") { + TemporaryDirectory project; + App app(project.path(), WebFrontConfig{.port = "0"}); + THEN("an unknown mode or an unpinned environment is refused") { + REQUIRE_THROWS_AS(app.bootstrap("other", trusted), std::invalid_argument); + REQUIRE_THROWS_AS(app.bootstrap("developer", {.environment = "https://example.test/env.tgz", .integrity = "md5-abc"}), std::invalid_argument); + REQUIRE_THROWS_AS(app.bootstrap("developer", {.environment = "", .integrity = "sha512-abc"}), std::invalid_argument); + } + THEN("a pinned environment is accepted once") { + REQUIRE_NOTHROW(app.bootstrap("developer", trusted)); + REQUIRE_THROWS_AS(app.bootstrap("developer", trusted), std::logic_error); + } + } +} diff --git a/test/LifeTests.cpp b/test/LifeTests.cpp new file mode 100644 index 00000000..f4763e31 --- /dev/null +++ b/test/LifeTests.cpp @@ -0,0 +1,51 @@ +#include "../src/Life.hpp" +#include + +using webfront::demo::LifeGrid; +using webfront::demo::nextLife; + +SCENARIO("Life generations follow B3/S23 synchronously") { + GIVEN("an empty grid and a stable block") { + REQUIRE(nextLife({}).none()); + LifeGrid block; + for (const auto i : {330, 331, 362, 363}) + block.set(static_cast(i)); + REQUIRE(nextLife(block) == block); + } + GIVEN("a horizontal blinker") { + LifeGrid horizontal, vertical; + for (const auto i : {330, 331, 332}) + horizontal.set(static_cast(i)); + for (const auto i : {299, 331, 363}) + vertical.set(static_cast(i)); + WHEN("two generations are computed") { + REQUIRE(nextLife(horizontal) == vertical); + REQUIRE(nextLife(vertical) == horizontal); + REQUIRE(horizontal.count() == 3); + } + } + GIVEN("a glider") { + LifeGrid grid, translated; + for (const auto i : {1, 34, 64, 65, 66}) + grid.set(static_cast(i)); + for (const auto i : {34, 67, 97, 98, 99}) + translated.set(static_cast(i)); + for (int i = 0; i < 4; ++i) + grid = nextLife(grid); + REQUIRE(grid == translated); + } +} + +SCENARIO("Life wraps both axes without treating adjacent rows as neighbors") { + LifeGrid horizontal, vertical; + for (const auto i : {31, 0, 1}) + horizontal.set(static_cast(i)); + for (const auto i : {992, 0, 32}) + vertical.set(static_cast(i)); + REQUIRE(nextLife(horizontal) == vertical); + REQUIRE(nextLife(vertical) == horizontal); + LifeGrid isolated; + for (const auto i : {30, 31, 34}) + isolated.set(static_cast(i)); + REQUIRE(nextLife(isolated).none()); +} diff --git a/test/MimeTypeTests.cpp b/test/MimeTypeTests.cpp index ae64ccd2..7bb2bae8 100644 --- a/test/MimeTypeTests.cpp +++ b/test/MimeTypeTests.cpp @@ -44,6 +44,7 @@ SCENARIO("Every MIME type has its own name") { { "svg", "image/svg+xml"}, {"webp", "image/webp"}, { "csv", "text/csv"}, + {"wasm", "application/wasm"}, })); THEN(extension + " is served as " + contentType) { REQUIRE(std::string(MimeType::fromExtension(extension).toString()) == contentType); diff --git a/tools/assets/package-lock.json b/tools/assets/package-lock.json index 390f60c4..5500ebbc 100644 --- a/tools/assets/package-lock.json +++ b/tools/assets/package-lock.json @@ -9,10 +9,12 @@ "@xterm/addon-fit": "0.11.0", "@xterm/xterm": "6.0.0", "esbuild": "0.28.2", + "esbuild-wasm": "0.28.2", "fflate": "0.8.3", "jasmine-core": "7.0.2", "react": "19.3.1", - "react-dom": "19.3.1" + "react-dom": "19.3.1", + "semver": "7.7.3" }, "engines": { "node": ">=22.18.0" @@ -832,6 +834,18 @@ "@esbuild/win32-x64": "0.28.2" } }, + "node_modules/esbuild-wasm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild-wasm/-/esbuild-wasm-0.28.2.tgz", + "integrity": "sha512-GccVwhv3mmOUVQHCQm2Ox/rby8n/EqUwvZxE6Pjfikrq/lWw9g9WX/u9EykWnpot3Ko6j426DgQdea2xWKIAQA==", + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/escalade": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", @@ -966,6 +980,18 @@ "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", "license": "MIT" }, + "node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/update-browserslist-db": { "version": "1.3.4", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", diff --git a/tools/assets/package.json b/tools/assets/package.json index 912ba214..feacc30e 100644 --- a/tools/assets/package.json +++ b/tools/assets/package.json @@ -7,9 +7,11 @@ "@xterm/addon-fit": "0.11.0", "@xterm/xterm": "6.0.0", "esbuild": "0.28.2", + "esbuild-wasm": "0.28.2", "fflate": "0.8.3", "jasmine-core": "7.0.2", "react": "19.3.1", - "react-dom": "19.3.1" + "react-dom": "19.3.1", + "semver": "7.7.3" } } diff --git a/tools/developer/PUBLISHING.md b/tools/developer/PUBLISHING.md new file mode 100644 index 00000000..4e577d60 --- /dev/null +++ b/tools/developer/PUBLISHING.md @@ -0,0 +1,78 @@ +# Publishing the developer packages + +The version and canonical HTTPS base URL are in `distribution.json`. The environment and Life/PI starters +are published under `developer//`. React, React DOM and scheduler stay on npm; this site +hosts only WebFront's development environment, its pinned Life/PI starters and provisioning metadata. +The package names in their manifests are identifiers, not a requirement to own or publish npm scopes. + +## Build and review + +```sh +npm ci --prefix tools/assets --ignore-scripts +node tools/developer/build.mjs build-distribution --refresh-bootstrap +node tools/developer/fixtures.mjs build-distribution +node --test tools/developer/check.mjs tools/developer/distribution-check.mjs +node tools/developer/site.mjs build-distribution build-developer-site +``` + +Review and commit the updated checked-in bootstrap bundles, checksums and +`include/system/DeveloperReleaseData.hpp`. The header pins the exact environment archive and URL. +The environment pins the starter archive in turn. `provision.json` is informational; applications +do not discover a replacement trust hash from that remote file or follow `latest` at startup. + +The static branch preserves every version. Republishing identical bytes is allowed; replacing a +published version with different bytes fails. Increment `distribution.json` before publishing any +changed environment, starter, public URL or provisioning configuration. + +## One-time Pages configuration + +The repository's Pages source must be the **gh-pages branch, root directory**, with branch-based +builds (`build_type: legacy`). The branch contains only generated distribution files and `.nojekyll`. +An existing unrelated Pages site must not be overwritten. + +For initial setup, a repository maintainer first commits/pushes the generated site to a new +`gh-pages` branch, then enables Settings → Pages → Deploy from a branch → gh-pages → `/`. +The equivalent API call, after that branch exists, is: + +```sh +gh api --method POST repos/ambroise-leclerc/WebFront/pages \ + -f build_type=legacy -f 'source[branch]=gh-pages' -f 'source[path]=/' +``` + +The publication workflow uses repository tokens with `contents: write` and `pages: write` to update +that branch without force-pushing. It explicitly requests a Pages build, because token-driven +branch pushes do not trigger one automatically. It refuses to change an existing Pages source. +Initial Pages enablement is deliberately a maintainer operation, not a side effect of every build. + +## Automated publication + +The **Developer packages** workflow builds packages on relevant pushes/PRs and retains them as an +artifact. It compares a repeat build and the checked-in bootstrap header before permitting publication. +It publishes only on a `developer-v` tag or an explicit workflow dispatch with `publish=true`. +Use the dedicated tag `developer-v` matching `distribution.json`; the C++ library's `v*` releases remain separate. + +```sh +version=$(node -p "require('./tools/developer/distribution.json').version") +git tag "developer-v$version" +git push origin "developer-v$version" +``` + +Alternatively, once the workflow exists on the default branch, run it manually for a reviewed ref. +Tagged publication also archives the same files in a dedicated GitHub prerelease. Existing release +assets are verified on retry; they are never replaced. Downloads used by the bootstrap come from +Pages, whose cross-origin behavior is checked independently of Release asset redirects. + +## Validate the deployed files + +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): + +```sh +./build-native/webtest/developer_integration \ + "$PWD/build-distribution" "$PWD/build-native/webtest/public-generated" --public +``` + +This mode downloads the pinned environment and both starters from Pages, fetches exact React/React DOM +versions and scheduler from npm, executes esbuild/WASM, creates in-window PI and Life previews and generates +both application providers. A mismatch, download failure, browser error or failed assertion returns +nonzero. Keep the issue open until this real-engine check and the normal offline regression suite pass. diff --git a/tools/developer/RELEASE_NOTES.md b/tools/developer/RELEASE_NOTES.md new file mode 100644 index 00000000..f82b15fb --- /dev/null +++ b/tools/developer/RELEASE_NOTES.md @@ -0,0 +1,7 @@ +Browser-powered WebFront developer environment with Game of Life and PI starters, versioned separately from the C++ library. + +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. + +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. diff --git a/tools/developer/archive-release.mjs b/tools/developer/archive-release.mjs new file mode 100644 index 00000000..3eb7c4a0 --- /dev/null +++ b/tools/developer/archive-release.mjs @@ -0,0 +1,35 @@ +// 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('tools/developer/RELEASE_NOTES.md'), ...files.map(name => resolve(distribution, name)))); +} diff --git a/tools/developer/archive.mjs b/tools/developer/archive.mjs new file mode 100644 index 00000000..0c3828c1 --- /dev/null +++ b/tools/developer/archive.mjs @@ -0,0 +1,28 @@ +// Reproducible ustar for the published npm environment and local registry fixtures. +export function tar(files) { + const encoder = new TextEncoder(); + const chunks = []; + const field = (header, offset, length, value) => header.set(encoder.encode(value).subarray(0, length), offset); + for (const [name, bytes] of [...files].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) { + if (encoder.encode(name).length > 100) throw new Error('ustar fixture filename too long'); + const header = new Uint8Array(512); + field(header, 0, 100, name); + field(header, 100, 8, '0000644\0'); + field(header, 108, 8, '0000000\0'); + field(header, 116, 8, '0000000\0'); + field(header, 124, 12, bytes.length.toString(8).padStart(11, '0') + '\0'); + field(header, 136, 12, '00000000000\0'); + header.fill(32, 148, 156); + header[156] = 48; + field(header, 257, 6, 'ustar\0'); + field(header, 263, 2, '00'); + const checksum = header.reduce((sum, byte) => sum + byte, 0); + field(header, 148, 8, checksum.toString(8).padStart(6, '0') + '\0 '); + chunks.push(header, bytes, new Uint8Array((512 - bytes.length % 512) % 512)); + } + chunks.push(new Uint8Array(1024)); + const output = new Uint8Array(chunks.reduce((sum, bytes) => sum + bytes.length, 0)); + let offset = 0; + for (const bytes of chunks) { output.set(bytes, offset); offset += bytes.length; } + return output; +} diff --git a/tools/developer/build.mjs b/tools/developer/build.mjs new file mode 100644 index 00000000..7eb67a5f --- /dev/null +++ b/tools/developer/build.mjs @@ -0,0 +1,87 @@ +// Maintainer provisioning only. Consumers download the resulting tarball, without Node/npm. +import {build} from '../assets/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, 'tools/assets/node_modules')], + plugins: [{name: 'terminal-assets', setup(build) { + build.onResolve({filter: /^\.\/(xterm|addon-fit)\.mjs$/}, args => ({path: resolve(root, 'third_party/xterm', args.path)})); + }}], +}; +await build({...options, entryPoints: ['src/developer/runtime.mjs'], outfile: resolve(output, 'runtime.mjs')}); +await build({...options, entryPoints: ['src/developer/compiler.mjs'], outfile: resolve(output, 'compiler.mjs')}); +await copyFile(resolve(root, 'tools/assets/node_modules/esbuild-wasm/esbuild.wasm'), resolve(output, 'esbuild.wasm')); +await copyFile(resolve(root, 'third_party/xterm/xterm.css'), resolve(output, 'xterm.css')); +const distribution = JSON.parse(await readFile(resolve(root, 'tools/developer/distribution.json'))); +const version = distribution.version; +const publicBase = baseUrl(distribution.baseUrl); +versionPath(version); +const dependencies = JSON.parse(await readFile(resolve(root, 'tools/assets/package.json'))).dependencies; +const licenses = [ + ['esbuild-wasm', 'tools/assets/node_modules/esbuild-wasm/LICENSE.md'], + ['semver', 'tools/assets/node_modules/semver/LICENSE'], + ['xterm', 'third_party/xterm/LICENSE'], + ['xterm Fit addon', 'third_party/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, `src/${name}/${file}`))); + const recipe = {format: 1, name, provider, entry: 'main.tsx', dependencies: { + react: dependencies.react, 'react-dom': dependencies['react-dom']}}; + 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, 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', 'esbuild.wasm', 'xterm.css', 'environment.json', 'LICENSES.txt']}, null, 2) + '\n'); +const files = new Map(); +for (const name of ['runtime.mjs', 'compiler.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, 'src/developer/bootstrap.bundle.mjs'); + await build({...options, entryPoints: ['src/developer/bootstrap-entry.mjs'], outfile: bootstrap}); + await build({...options, entryPoints: ['src/developer/packages.mjs'], outfile: resolve(root, 'src/developer/packages.bundle.mjs')}); + await copyFile(resolve(root, 'tools/assets/node_modules/semver/LICENSE'), resolve(root, 'src/developer/PACKAGES-LICENSE.txt')); + await writeFile(resolve(root, 'include/system/DeveloperReleaseData.hpp'), header); + const inputs = {}; + for (const path of ['src/developer/bootstrap.mjs', 'src/developer/bootstrap-entry.mjs', 'src/developer/packages.mjs', 'src/developer/starter.mjs', 'src/developer/paths.mjs', 'src/developer/runtime.mjs', 'src/developer/compiler.mjs', 'src/developer/bundler.mjs', 'src/developer/entry.mjs', 'src/developer/conditions.mjs', 'src/developer/io.mjs', 'src/developer/recipe.mjs', 'src/developer/registry.mjs', 'src/developer/archive.mjs', 'src/developer/lock.mjs', 'src/developer/pins.mjs', 'src/developer/peers.mjs', 'src/developer/resolve.mjs', 'src/developer/embed.mjs', 'src/pi/main.tsx', 'src/pi/style.css', 'src/life/main.tsx', 'src/life/style.css', 'src/components/tools/wf.mjs', 'tools/developer/distribution.json', 'tools/developer/build.mjs', 'tools/developer/site.mjs', 'tools/developer/archive.mjs', 'tools/assets/package-lock.json', 'src/developer/bootstrap.bundle.mjs', 'src/developer/packages.bundle.mjs', 'include/system/DeveloperReleaseData.hpp']) + inputs[path] = createHash('sha256').update(await readFile(resolve(root, path))).digest('hex'); + await writeFile(resolve(root, 'src/developer/bundles.json'), JSON.stringify(inputs, null, 2) + '\n'); + for (const [source, name] of [['src/developer/index.html', 'DeveloperIndexHtmlData'], ['src/developer/bootstrap.bundle.mjs', 'DeveloperBootstrapData']]) + execFileSync('cmake', [`-DINPUT=${resolve(root, source)}`, `-DOUTPUT=${resolve(root, 'include/system', name + '.hpp')}`, `-DSTRUCT=${name}`, '-P', resolve(root, 'cmake/EmbedTextAsset.cmake')]); +} +console.log(`Environment: ${output}/environment.tgz\nIntegrity: ${integrity}\nStarters: ${Object.keys(starters).join(', ')}`); diff --git a/tools/developer/check.mjs b/tools/developer/check.mjs new file mode 100644 index 00000000..bb36c3ee --- /dev/null +++ b/tools/developer/check.mjs @@ -0,0 +1,201 @@ +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 {resolvePackages, downloadPackage, validateLock} from '../../src/developer/packages.bundle.mjs'; +import {packageEntry, normalize, virtualPlugin} from '../../src/developer/bundler.mjs'; +import {generateProvider, compress} from '../../src/developer/embed.mjs'; +import {environmentFiles, bootstrap} from '../../src/developer/bootstrap.mjs'; +import {publish, responseBytes} from '../../src/developer/io.mjs'; +import {tar} from './archive.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)), /Unsupported WebFront/); + 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('../../src/developer/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 tools/developer/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/); +}); diff --git a/tools/developer/distribution-check.mjs b/tools/developer/distribution-check.mjs new file mode 100644 index 00000000..ecf7d32a --- /dev/null +++ b/tools/developer/distribution-check.mjs @@ -0,0 +1,121 @@ +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 '../../src/developer/embed.mjs'; +import {createStarter} from '../../src/developer/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'); + +function starter(overrides = {}) { + return compress(tar(new Map(Object.entries({ + 'package/main.tsx': encode('export default function Pi() {}'), + 'package/webfront.project.json': encode({format: 1, entry: 'main.tsx', dependencies: {react: '19.3.1'}}), + ...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 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({format: 1, entry: 'main.tsx', 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', ['LifeUI']]) { + const bytes = starter({'package/webfront.project.json': encode({format: 1, provider, entry: 'main.tsx', dependencies: {react: '19.3.1'}})}); + 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/tools/developer/distribution.json b/tools/developer/distribution.json new file mode 100644 index 00000000..929ec6fc --- /dev/null +++ b/tools/developer/distribution.json @@ -0,0 +1,4 @@ +{ + "version": "0.3.1", + "baseUrl": "https://ambroise-leclerc.github.io/WebFront/" +} diff --git a/tools/developer/fixtures.mjs b/tools/developer/fixtures.mjs new file mode 100644 index 00000000..1192bf02 --- /dev/null +++ b/tools/developer/fixtures.mjs @@ -0,0 +1,33 @@ +// Configure offline browser fixtures from the maintainer's pinned npm ci installation. +import {readFile, writeFile, mkdir, readdir, copyFile} from 'node:fs/promises'; +import {resolve} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {createHash} from 'node:crypto'; +import {tar} from './archive.mjs'; +import {compress} from '../../src/developer/embed.mjs'; +const root = fileURLToPath(new URL('../../', import.meta.url)); +const output = resolve(process.argv[2] ?? 'build-developer-environment'); +await mkdir(resolve(output, 'registry'), {recursive: true}); +for (const name of ['react', 'react-dom', 'scheduler']) { + const directory = resolve(root, 'tools/assets/node_modules', name); + const manifest = JSON.parse(await readFile(resolve(directory, 'package.json'))); + const files = new Map(); + async function walk(path = '') { + for (const entry of await readdir(resolve(directory, path), {withFileTypes: true})) { + if (entry.name === 'node_modules') continue; + const relative = path ? `${path}/${entry.name}` : entry.name; + if (entry.isDirectory()) await walk(relative); + else if (entry.isFile()) files.set(`package/${relative}`, await readFile(resolve(directory, relative))); + } + } + await walk(); + const bytes = compress(tar(files)); + await writeFile(resolve(output, 'registry', `${name}.tgz`), bytes); + const integrity = 'sha512-' + createHash('sha512').update(bytes).digest('base64'); + await writeFile(resolve(output, 'registry', name), JSON.stringify({'dist-tags': {latest: manifest.version}, + versions: {[manifest.version]: {...manifest, dist: {tarball: `./${name}.tgz`, integrity}}}})); +} +await copyFile(resolve(root, 'webtest/developer-specs.mjs'), resolve(output, 'run.mjs')); +await copyFile(resolve(root, 'src/pi/main.tsx'), resolve(output, 'main.tsx')); +await copyFile(resolve(root, 'src/pi/style.css'), resolve(output, 'style.css')); +console.log(`Offline developer fixtures: ${output}`); diff --git a/tools/developer/pages.mjs b/tools/developer/pages.mjs new file mode 100644 index 00000000..bbdf2b93 --- /dev/null +++ b/tools/developer/pages.mjs @@ -0,0 +1,10 @@ +// 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/tools/developer/release-check.mjs b/tools/developer/release-check.mjs new file mode 100644 index 00000000..eee5d2c1 --- /dev/null +++ b/tools/developer/release-check.mjs @@ -0,0 +1,4 @@ +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/tools/developer/site.mjs b/tools/developer/site.mjs new file mode 100644 index 00000000..d0404aa5 --- /dev/null +++ b/tools/developer/site.mjs @@ -0,0 +1,107 @@ +// Static, version-preserving GitHub Pages distribution. No dependency on npm at consumption time. +import {readFile, writeFile, mkdir, readdir, stat} from 'node:fs/promises'; +import {resolve, join} from 'node:path'; +import {pathToFileURL} from 'node:url'; +import {createHash} from 'node:crypto'; + +function isHttpsDirectory(url) { + if (url.protocol !== 'https:') return false; + if (url.username || url.password) return false; + return !url.search && !url.hash; +} + +export function baseUrl(value) { + const url = new URL(value); + if (!isHttpsDirectory(url)) throw new Error('Distribution base URL must be an HTTPS directory URL'); + if (!url.pathname.endsWith('/')) url.pathname += '/'; + return url.href; +} +export function versionPath(version) { + if (!versionName.test(version)) throw new Error('Invalid distribution version'); + return `developer/${version}/`; +} +export function bootstrapHeader(version, base, integrity) { + if (!/^sha512-[A-Za-z0-9+/]{86}==$/.test(integrity)) throw new Error('Invalid distribution SHA-512'); + const url = new URL(versionPath(version) + 'environment.tgz', baseUrl(base)); + return `#pragma once + +// Pinned developer distribution. Regenerate with tools/developer/build.mjs --refresh-bootstrap. +#include + +namespace webfront::developer::release { +inline constexpr std::string_view version{${JSON.stringify(version)}}; +inline constexpr std::string_view environment{${JSON.stringify(url.href)}}; +inline constexpr std::string_view integrity{${JSON.stringify(integrity)}}; +} // namespace webfront::developer::release +`; +} + +const validArchive = name => typeof name === 'string' && /^[a-z0-9-]+-starter\.tgz$/.test(name); +const versionName = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/; + +// A manifest may add starters without changing the publication machinery. +export function distributionFiles(manifest) { + const archives = Object.values(manifest.starters ?? {}).map(starter => starter.archive); + if (archives.length === 0 || !archives.every(validArchive)) throw new Error('Invalid distribution starter archives'); + if (new Set(archives).size !== archives.length) throw new Error('Invalid distribution starter archives'); + return ['environment.tgz', ...archives, 'provision.json', 'DeveloperReleaseData.hpp']; +} +const digest = bytes => 'sha512-' + createHash('sha512').update(bytes).digest('base64'); + +async function readDistribution(distribution) { + const manifest = JSON.parse(await readFile(join(distribution, 'provision.json'))); + const input = new Map(); + for (const name of distributionFiles(manifest)) input.set(name, await readFile(join(distribution, name))); + const archives = [[input.get('environment.tgz'), manifest.integrity], + ...Object.values(manifest.starters).map(starter => [input.get(starter.archive), starter.integrity])]; + if (archives.some(([bytes, integrity]) => digest(bytes) !== integrity)) throw new Error('Distribution archive checksum mismatch'); + return {manifest, input}; +} + +async function isDirectory(path) { + try { return (await stat(path)).isDirectory(); } + catch (error) { + if (error.code !== 'ENOENT') throw error; + return false; + } +} + +// A published version is immutable: reruns may only repeat identical bytes. +async function publishVersion(input, destination, version) { + if (!await isDirectory(destination)) { + await mkdir(destination, {recursive: true}); + for (const [name, bytes] of input) await writeFile(join(destination, name), bytes); + return; + } + // Check every byte before modifying anything. + for (const [name, bytes] of input) + if (!bytes.equals(await readFile(join(destination, name)))) + throw new Error(`Published version ${version} differs; increment the distribution version`); +} + +async function versionRow(site, version) { + const manifest = JSON.parse(await readFile(join(site, versionPath(version), 'provision.json'))); + const links = distributionFiles(manifest).map(name => `${name}`).join(' · '); + return `
  • ${version}: ${links}
  • `; +} + +async function writeIndex(site) { + const versions = (await readdir(join(site, 'developer'))).filter(name => versionName.test(name)).sort(); + await writeFile(join(site, '.nojekyll'), ''); + const rows = []; + for (const version of versions) rows.push(await versionRow(site, version)); + await writeFile(join(site, 'index.html'), `\nWebFront developer packages

    WebFront developer packages

    Use a version-pinned bootstrap header and SHA-512. React and its dependencies are downloaded separately from npm.

      ${rows.join('')}
    \n`); +} + +export async function stageSite(distribution, site) { + const {manifest, input} = await readDistribution(distribution); + const relative = versionPath(manifest.version); + await publishVersion(input, join(site, relative), manifest.version); + await writeIndex(site); + return {version: manifest.version, path: relative}; +} +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + const [distribution, site] = process.argv.slice(2); + if (!distribution || !site) throw new Error('Usage: node tools/developer/site.mjs '); + console.log(await stageSite(resolve(distribution), resolve(site))); +} diff --git a/webtest/CMakeLists.txt b/webtest/CMakeLists.txt index 190ce4da..ce224f3a 100644 --- a/webtest/CMakeLists.txt +++ b/webtest/CMakeLists.txt @@ -30,3 +30,72 @@ if(WEBFRONT_EMBED_CEF AND CMAKE_SYSTEM_NAME STREQUAL "Linux") webfront_set_browser_test_properties(CEFContentPolicy "${CMAKE_CURRENT_SOURCE_DIR}" 45) endif() endif() + +# Optional offline fixtures are provisioned by maintainers, never downloaded by CTest. +set(WEBFRONT_DEVELOPER_FIXTURES "" CACHE PATH "Prepared browser developer environment/registry fixtures") +if(WEBFRONT_DEVELOPER_FIXTURES + AND ${WEBFRONT_FRONTEND_${WEBFRONT_WEBTEST_FRONTEND}_OPTION} + AND CMAKE_SYSTEM_NAME IN_LIST WEBFRONT_FRONTEND_${WEBFRONT_WEBTEST_FRONTEND}_TEST_PLATFORMS) + if(NOT EXISTS "${WEBFRONT_DEVELOPER_FIXTURES}/provision.json") + message(FATAL_ERROR "Prepare WEBFRONT_DEVELOPER_FIXTURES with tools/developer/build.mjs and fixtures.mjs") + endif() + add_executable(developer_integration DeveloperTest.cpp) + target_link_libraries(developer_integration PRIVATE WebFront_test_hardening WebFront WebFront_warnings WebFront_options) + target_compile_definitions(developer_integration PRIVATE WEBFRONT_TEST_FRONTEND=${WEBFRONT_WEBTEST_FRONTEND_TYPE}) + webfront_setup_frontends_for_target(developer_integration) + set(_developer_command "$") + if(WEBFRONT_FRONTEND_${WEBFRONT_WEBTEST_FRONTEND}_XVFB_LINUX AND CMAKE_SYSTEM_NAME STREQUAL "Linux") + webfront_find_xvfb(_developer_xvfb) + if(NOT _developer_xvfb) + message(FATAL_ERROR "Developer browser integration requires xvfb-run on this frontend") + endif() + set(_developer_command "${_developer_xvfb}" -a ${_developer_command}) + endif() + add_test(NAME DeveloperBrowserIntegration COMMAND ${_developer_command} + "${WEBFRONT_DEVELOPER_FIXTURES}" "${CMAKE_CURRENT_BINARY_DIR}/developer-generated") + webfront_set_browser_test_properties(DeveloperBrowserIntegration "${CMAKE_CURRENT_SOURCE_DIR}" 180) + set_tests_properties(DeveloperBrowserIntegration PROPERTIES FIXTURES_SETUP DeveloperGenerated) + # Build the actual browser-generated header only after the setup test has produced it. + add_executable(developer_embedded EXCLUDE_FROM_ALL DeveloperEmbeddedTest.cpp) + target_link_libraries(developer_embedded PRIVATE WebFront_test_hardening WebFront WebFront_warnings WebFront_options) + target_compile_definitions(developer_embedded PRIVATE WEBFRONT_TEST_FRONTEND=${WEBFRONT_WEBTEST_FRONTEND_TYPE} + WEBFRONT_PI_ASSETS_HEADER="${CMAKE_CURRENT_BINARY_DIR}/developer-generated/PiUI.hpp") + webfront_setup_frontends_for_target(developer_embedded) + add_test(NAME DeveloperEmbeddedBuild COMMAND ${CMAKE_COMMAND} --build "${CMAKE_BINARY_DIR}" + --config $ --target developer_embedded --parallel 2) + set_tests_properties(DeveloperEmbeddedBuild PROPERTIES FIXTURES_REQUIRED DeveloperGenerated + FIXTURES_SETUP DeveloperEmbedded LABELS "web-integration" TIMEOUT 180 RUN_SERIAL TRUE) + set(_embedded_command "$") + if(_developer_xvfb) + set(_embedded_command "${_developer_xvfb}" -a ${_embedded_command}) + endif() + add_test(NAME DeveloperEmbeddedIntegration COMMAND ${_embedded_command}) + webfront_set_browser_test_properties(DeveloperEmbeddedIntegration "${CMAKE_CURRENT_SOURCE_DIR}" 60) + set_tests_properties(DeveloperEmbeddedIntegration PROPERTIES FIXTURES_REQUIRED DeveloperEmbedded) + add_executable(life_embedded EXCLUDE_FROM_ALL LifeEmbeddedTest.cpp) + target_link_libraries(life_embedded PRIVATE WebFront_test_hardening WebFront WebFront_warnings WebFront_options) + target_compile_definitions(life_embedded PRIVATE WEBFRONT_TEST_FRONTEND=${WEBFRONT_WEBTEST_FRONTEND_TYPE} + WEBFRONT_LIFE_ASSETS_HEADER="${CMAKE_CURRENT_BINARY_DIR}/developer-generated/LifeUI.hpp") + webfront_setup_frontends_for_target(life_embedded) + add_test(NAME LifeEmbeddedBuild COMMAND ${CMAKE_COMMAND} --build "${CMAKE_BINARY_DIR}" + --config $ --target life_embedded --parallel 2) + set_tests_properties(LifeEmbeddedBuild PROPERTIES FIXTURES_REQUIRED DeveloperGenerated + FIXTURES_SETUP LifeEmbedded LABELS "web-integration" TIMEOUT 180 RUN_SERIAL TRUE) + set(_life_command "$") + if(_developer_xvfb) + set(_life_command "${_developer_xvfb}" -a ${_life_command}) + endif() + add_test(NAME LifeEmbeddedIntegration COMMAND ${_life_command}) + webfront_set_browser_test_properties(LifeEmbeddedIntegration "${CMAKE_CURRENT_SOURCE_DIR}" 60) + set_tests_properties(LifeEmbeddedIntegration PROPERTIES FIXTURES_REQUIRED LifeEmbedded) + if(WEBFRONT_WEBTEST_FRONTEND STREQUAL "WKWebView") + get_filename_component(_developer_wk_plist "${CMAKE_CURRENT_SOURCE_DIR}/../cmake/WKWebViewTestInfo.plist.in" ABSOLUTE) + foreach(target developer_integration developer_embedded life_embedded) + string(REPLACE "_" "-" identifier "${target}") + set_target_properties(${target} PROPERTIES + MACOSX_BUNDLE TRUE + MACOSX_BUNDLE_GUI_IDENTIFIER "org.webfront.tests.${identifier}" + MACOSX_BUNDLE_INFO_PLIST "${_developer_wk_plist}") + endforeach() + endif() +endif() diff --git a/webtest/DeveloperEmbeddedTest.cpp b/webtest/DeveloperEmbeddedTest.cpp new file mode 100644 index 00000000..f6d1cf23 --- /dev/null +++ b/webtest/DeveloperEmbeddedTest.cpp @@ -0,0 +1,58 @@ +#include +#include WEBFRONT_PI_ASSETS_HEADER +#include "../src/Pi.hpp" +#include "../test/TemporaryDirectory.hpp" + +#include +#include + +namespace { +constexpr auto uiScript = R"JS( +(async () => { + try { + const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); + for (let attempt = 0; !document.querySelector('button'); ++attempt) { + if (attempt === 100) throw new Error('Embedded React interface did not mount'); + await delay(50); + } + document.querySelector('button').click(); + for (let attempt = 0; !document.querySelector('output').textContent.startsWith('3.14159265358979323846264338327950288419716939937510'); ++attempt) { + if (attempt === 100) throw new Error('Embedded interface did not display PI'); + await delay(50); + } + const developmentDisabled = await webFront.cppFunction('webfront.developer.config')().then(() => false, () => true); + if (!developmentDisabled) throw new Error('Distribution enabled developer callbacks'); + await webFront.cppFunction('test.report')(true, 'Embedded React + PI passed with an empty working directory'); + } catch (error) { + await webFront.cppFunction('test.report')(false, String(error.stack || error)); + } finally { setTimeout(() => globalThis.close(), 0); } +})().catch(error => { console.error(error); globalThis.close(); }); +)JS"; +} // namespace + +int main() { + try { + webfront::detail::ensureFrontendInitialized(); + webfront::test::TemporaryDirectory empty; + const auto original = std::filesystem::current_path(); + std::filesystem::current_path(empty.path()); + using App = webfront:: + BasicWF, webfront::http::DefaultBuffersPolicy, WEBFRONT_TEST_FRONTEND>; + App app; + std::atomic passed{false}; + app.cppFunction("pi", &webfront::demo::pi); + app.cppFunction("test.report", [&](bool success, std::string message) { + std::cout << message << std::endl; + passed.store(success); + }); + auto subscription = app.subscribeUIStarted([](App::UI ui) { + ui.addScript(uiScript); + }); + app.show(); + std::filesystem::current_path(original); + return passed.load() ? 0 : 1; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/webtest/DeveloperTest.cpp b/webtest/DeveloperTest.cpp new file mode 100644 index 00000000..36790915 --- /dev/null +++ b/webtest/DeveloperTest.cpp @@ -0,0 +1,118 @@ +#include "../src/Life.hpp" +#include "../src/Pi.hpp" +#include "../test/TemporaryDirectory.hpp" +#include + +#include +#include +#include + +namespace { +std::string readFixtureText(const std::filesystem::path& path) { + const auto size = std::filesystem::file_size(path); + if (size > 16 * 1024 * 1024) + throw std::length_error("Fixture text exceeds its byte limit"); + std::ifstream file(path, std::ios::binary); + if (!file) + throw std::runtime_error("Cannot read fixture text"); + std::string text(static_cast(size), '\0'); + if (!text.empty() && !file.read(text.data(), static_cast(text.size()))) + throw std::runtime_error("Truncated fixture text"); + return text; +} + +class FixturesFS { +public: + explicit FixturesFS(std::filesystem::path projectRoot) : root(std::filesystem::canonical(projectRoot)) { } + std::optional open(std::filesystem::path path) const { + const auto relative = path.relative_path().generic_string(); + if (!relative.starts_with("fixtures/")) + return {}; + std::ifstream stream(webfront::developer::projectPath(root, relative), std::ios::binary); + if (stream) + return webfront::fs::File{std::move(stream)}; + return {}; + } + +private: + std::filesystem::path root; +}; + +std::string readIntegrity(const std::filesystem::path& config) { + std::string integrity; + const std::string json = readFixtureText(config); + webfront::json::Reader reader{json}; + reader.object([&](const std::string& key) { + if (key == "integrity") + integrity = reader.string(); + else + reader.skipValue(); + }); + return integrity; +} + +template +void registerCallbacks(App& app, const std::filesystem::path& project, std::atomic& passed) { + app.cppFunction("pi", &webfront::demo::pi); + app.cppFunction("life.step", &webfront::demo::nextLife); + app.cppFunction("test.header", [project](std::string name) { + if (name != "PiUI" && name != "LifeUI") + throw std::invalid_argument("Unknown generated fixture"); + const auto header = readFixtureText(project / "generated" / (name + ".hpp")); + // The generated header is larger than a bridge string: return a stable small digest. + return std::to_string(std::hash{}(header)); + }); + app.cppFunction("test.report", [&passed](bool success, std::string message) { + std::cout << message << std::endl; + passed.store(success); + }); +} + +template +void bootstrapApp(App& app, std::string_view mode, const std::string& integrity) { + if (mode.empty()) + app.bootstrap("developer", {.environment = "/fixtures/environment.tgz", .integrity = integrity, .registry = "/fixtures/registry/"}); + else if (mode == "--public") + app.bootstrap("developer"); + else + throw std::invalid_argument("Unknown smoke-test mode"); +} + +void copyHeaders(const std::filesystem::path& project, const std::filesystem::path& output) { + std::filesystem::create_directories(output); + for (const auto* name : {"PiUI.hpp", "LifeUI.hpp"}) + std::filesystem::copy_file(project / "generated" / name, output / name, std::filesystem::copy_options::overwrite_existing); +} + +constexpr auto runScript = + "import('/fixtures/run.mjs').catch(async e => { await webFront.cppFunction('test.report')(false, String(e.stack || e)); window.close(); });"; +} // namespace + +int main(int argc, char** argv) { + try { + // CEF child processes must dispatch before interpreting application arguments or creating files. + webfront::detail::ensureFrontendInitialized(); + if (argc != 3 && argc != 4) + throw std::invalid_argument("Expected fixture directory, header output directory and optional --public"); + webfront::test::TemporaryDirectory project; + std::filesystem::copy(argv[1], project.path() / "fixtures", std::filesystem::copy_options::recursive); + const auto integrity = readIntegrity(project.path() / "fixtures/provision.json"); + using App = webfront::BasicDeveloperApp; + App app{project.path()}; + std::atomic passed{false}; + registerCallbacks(app, project.path(), passed); + bootstrapApp(app, argc == 4 ? std::string_view(argv[3]) : std::string_view{}, integrity); + auto subscription = app.subscribeUIStarted([injected = false](App::UI ui) mutable { + if (!std::exchange(injected, true)) + ui.addScript(runScript); + }); + app.show(); + if (!passed.load()) + return 1; + copyHeaders(project.path(), argv[2]); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/webtest/LifeEmbeddedTest.cpp b/webtest/LifeEmbeddedTest.cpp new file mode 100644 index 00000000..c3c45bfc --- /dev/null +++ b/webtest/LifeEmbeddedTest.cpp @@ -0,0 +1,79 @@ +#include +#include WEBFRONT_LIFE_ASSETS_HEADER +#include "../src/Life.hpp" +#include "../test/TemporaryDirectory.hpp" + +#include +#include + +namespace { +constexpr auto uiScript = R"JS( +(async () => { + try { + const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); + const field = name => document.querySelector(`[data-testid="${name}"]`); + const waitFor = async (predicate, message) => { + for (let attempt = 0; !predicate(); ++attempt) { + if (attempt === 100) throw new Error(message); + await delay(50); + } + }; + await waitFor(() => field('pattern-blinker'), 'Embedded Life interface did not mount'); + const packed = new Uint8Array(128); + for (const i of [330, 331, 332]) packed[i >> 3] |= 1 << (i & 7); + const next = await webFront.cppFunction('life.step')(packed); + if (!(next instanceof Uint8Array) || next.length !== 128) throw new Error('Expected 128 packed Life bytes'); + const expected = new Uint8Array(128); + for (const i of [299, 331, 363]) expected[i >> 3] |= 1 << (i & 7); + if (!next.every((byte, i) => byte === expected[i])) throw new Error('Incorrect packed Life bit order'); + for (const value of [new Uint8Array(127), new Int8Array(128), '0'.repeat(1024)]) { + const rejected = await webFront.cppFunction('life.step')(value).then(() => false, () => true); + if (!rejected) throw new Error('Malformed Life grid accepted'); + } + field('pattern-blinker').click(); + await waitFor(() => field('population').textContent === '3', 'Embedded blinker'); + field('step').click(); + await waitFor(() => field('generation').textContent === '0001', 'Embedded C++ generation'); + if (field('population').textContent !== '3') throw new Error('Embedded blinker population'); + field('play').click(); + await waitFor(() => Number(field('generation').textContent) >= 3, 'Embedded Life playback'); + field('clear').click(); + await delay(400); + if (field('generation').textContent !== '0000' || field('population').textContent !== '0') + throw new Error('Embedded Life reset retained a stale generation'); + const developmentDisabled = await webFront.cppFunction('webfront.developer.config')().then(() => false, () => true); + if (!developmentDisabled) throw new Error('Distribution enabled developer callbacks'); + await webFront.cppFunction('test.report')(true, 'Embedded React + C++ Life passed with an empty working directory'); + } catch (error) { + await webFront.cppFunction('test.report')(false, String(error.stack || error)); + } finally { setTimeout(() => globalThis.close(), 0); } +})().catch(error => { console.error(error); globalThis.close(); }); +)JS"; +} // namespace + +int main() { + try { + webfront::detail::ensureFrontendInitialized(); + webfront::test::TemporaryDirectory empty; + const auto original = std::filesystem::current_path(); + std::filesystem::current_path(empty.path()); + using App = webfront:: + BasicWF, webfront::http::DefaultBuffersPolicy, WEBFRONT_TEST_FRONTEND>; + App app; + std::atomic passed{false}; + app.cppFunction("life.step", &webfront::demo::nextLife); + app.cppFunction("test.report", [&](bool success, std::string message) { + std::cout << message << std::endl; + passed.store(success); + }); + auto subscription = app.subscribeUIStarted([](App::UI ui) { + ui.addScript(uiScript); + }); + app.show(); + std::filesystem::current_path(original); + return passed.load() ? 0 : 1; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/webtest/developer-specs.mjs b/webtest/developer-specs.mjs new file mode 100644 index 00000000..810d8506 --- /dev/null +++ b/webtest/developer-specs.mjs @@ -0,0 +1,128 @@ +// Autonomous real-engine test: compiled WASM, npm graph, PI bridge, preview, cache and embedding. +const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); +const assert = (condition, message) => { if (!condition) throw new Error(message); }; +try { + await webFront.ready; + for (let attempt = 0; attempt < 300; ++attempt) { + const text = document.getElementById('status')?.textContent ?? ''; + if (text.startsWith('Bootstrap failed:')) throw new Error(text); + if (text.startsWith('Developer environment ready.')) break; + if (attempt === 299) throw new Error('Bootstrap readiness timed out'); + await delay(100); + } + const runtime = await import('/webfront/developer/environment/runtime.mjs'); + const config = JSON.parse(await webFront.cppFunction('webfront.developer.config')()); + const environment = await (await fetch('/webfront/developer/environment/environment.json')).json(); + config.starters = Object.fromEntries(Object.entries(environment.starters).map(([name, value]) => [name, {url: new URL(value.archive, new URL(config.environment, location.href)).href, integrity: value.integrity}])); + const context = {bridge: webFront, config, preview: document.getElementById('preview'), signal: new AbortController().signal, + write: text => console.log(text)}; + await runtime.execute(['create', 'pi'], context); + const overwriteRefused = await runtime.execute(['create', 'pi'], context).then(() => false, () => true); + assert(overwriteRefused, 'A starter must not replace an existing project'); + await runtime.execute(['install', 'react@19.3.1', 'react-dom@19.3.1'], context); + const lock = await runtime.readLock(webFront); + assert(Object.keys(lock.packages).length === 3, 'React, React DOM and scheduler must be resolved'); + const listed = await runtime.execute(['list'], context); + assert(listed.split('\n').length === 3 && listed.includes('react@19.3.1'), 'wf list must name the installed packages'); + const historyLength = history.length; + await runtime.execute(['preview', 'ui/main.tsx'], context); + const frame = context.preview; + for (let attempt = 0; attempt < 300; ++attempt) { + if (frame.contentDocument?.querySelector('button')) break; + if (attempt === 299) throw new Error('React preview did not mount'); + await delay(50); + } + frame.contentDocument.querySelector('button').click(); + for (let attempt = 0; attempt < 100; ++attempt) { + if (frame.contentDocument.querySelector('output')?.textContent.startsWith('3.14159265358979323846264338327950288419716939937510')) break; + if (attempt === 99) throw new Error('React preview did not display C++ PI'); + await delay(50); + } + await runtime.execute(['embed', 'ui/main.tsx', '--output', 'generated/PiUI.hpp'], context); + // Repeat the browser build to prove reproducibility, including licenses and packed gzip bytes. + const first = await webFront.cppFunction('test.header')('PiUI'); + await runtime.execute(['embed', 'ui/main.tsx', '--output', 'generated/PiUI.hpp'], context); + assert(await webFront.cppFunction('test.header')('PiUI') === first, 'Header generation must be deterministic'); + // Keep the original PI regression and exercise the new primary starter in the same engine. + await runtime.execute(['create', 'life', 'life-ui'], context); + await runtime.execute(['preview', 'life-ui/main.tsx'], context); + for (let attempt = 0; !frame.contentDocument?.querySelector('[data-testid="pattern-blinker"]'); ++attempt) { + if (attempt === 200) throw new Error('Life preview did not mount'); + await delay(50); + } + assert(history.length === historyLength, 'Preview rebuilds must not accumulate session history'); + const life = frame.contentDocument; + const button = name => life.querySelector(`[data-testid="${name}"]`); + const waitFor = async (predicate, message) => { + for (let attempt = 0; !predicate(); ++attempt) { + if (attempt === 100) throw new Error(message); + await delay(30); + } + }; + const packed = new Uint8Array(128); + for (const i of [330, 331, 332]) packed[i >> 3] |= 1 << (i & 7); + const next = await webFront.cppFunction('life.step')(packed); + if (!(next instanceof Uint8Array) || next.length !== 128) throw new Error('Expected 128 packed Life bytes'); + const expected = new Uint8Array(128); + for (const i of [299, 331, 363]) expected[i >> 3] |= 1 << (i & 7); + if (!next.every((byte, i) => byte === expected[i])) throw new Error('Incorrect packed Life bit order'); + for (const value of [new Uint8Array(127), new Int8Array(128), '0'.repeat(1024)]) { + const rejected = await webFront.cppFunction('life.step')(value).then(() => false, () => true); + if (!rejected) throw new Error('Malformed Life grid accepted'); + } + button('pattern-blinker').click(); + await waitFor(() => button('population').textContent === '3', 'Blinker population'); + button('step').click(); + await waitFor(() => button('generation').textContent === '0001', 'C++ Life step'); + assert(button('population').textContent === '3', 'Blinker must preserve its population'); + button('play').click(); + await waitFor(() => Number(button('generation').textContent) >= 3, 'Life animation'); + button('play').click(); + // Clear invalidates a possible in-flight generation and stops the timer. + button('clear').click(); + await delay(400); + assert(button('generation').textContent === '0000' && button('population').textContent === '0', 'Clear must discard stale replies'); + // Paint across an octet boundary, then let C++ eliminate the two isolated cells. + button('view').click(); + await waitFor(() => button('view').getAttribute('aria-pressed') === 'true', 'Plan view'); + const canvas = life.querySelector('canvas'); + const paint = x => { + const rect = canvas.getBoundingClientRect(); + canvas.dispatchEvent(new frame.contentWindow.MouseEvent('click', {bubbles: true, + clientX: rect.left + (209 + x * 17 + 7) * rect.width / 960, + clientY: rect.top + (65 + 7) * rect.height / 680})); + }; + paint(7); + await waitFor(() => button('population').textContent === '1', 'Plant the last bit of an octet'); + paint(7); + await waitFor(() => button('population').textContent === '0', 'Toggle a packed cell off'); + paint(7); + await waitFor(() => button('population').textContent === '1', 'Plant the first cell'); + paint(8); + await waitFor(() => button('population').textContent === '2', 'Plant across the octet boundary'); + button('step').click(); + await waitFor(() => button('generation').textContent === '0001' && button('population').textContent === '0', 'C++ evolves painted packed cells'); + button('view').click(); + button('pattern-glider').click(); + await waitFor(() => button('population').textContent === '5', 'Glider population'); + for (let i = 1; i <= 4; i++) { + await waitFor(() => !button('step').disabled, 'Single step readiness'); + button('step').click(); + await waitFor(() => Number(button('generation').textContent) === i, 'Glider generation'); + } + assert(button('population').textContent === '5', 'C++ glider survives four steps'); + assert(life.querySelector('canvas').width > 0 && !life.querySelector('[role="alert"]').textContent, 'Life canvas rendered without errors'); + await runtime.execute(['embed', 'life-ui/main.tsx', '--output', 'generated/LifeUI.hpp'], context); + const lifeHeader = await webFront.cppFunction('test.header')('LifeUI'); + await runtime.execute(['embed', 'life-ui/main.tsx', '--output', 'generated/LifeUI.hpp'], context); + assert(await webFront.cppFunction('test.header')('LifeUI') === lifeHeader, 'Life header must be deterministic'); + const failed = await runtime.execute(['install', 'INVALID-NPM-NAME'], context).then(() => false, () => true); + assert(failed, 'Missing packages must reject'); + assert(JSON.stringify(await runtime.readLock(webFront)) === JSON.stringify(lock), 'A failed install must preserve the lock'); + await webFront.cppFunction('test.report')(true, 'WASM + npm + TSX + PI + Life animation + deterministic headers passed'); +} catch (error) { + console.error(error); + await webFront.cppFunction('test.report')(false, String(error.stack ?? error)); +} finally { + setTimeout(() => globalThis.close(), 0); +}