From 44475c741e885f5530d995f1e6573a26b14d3b4d Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc Date: Tue, 27 Oct 2026 23:21:10 +0100 Subject: [PATCH] Add optional React stores and DOM islands [#382] --- AGENTS.md | 6 +- README.md | 1 + docs/CHANGELOG.md | 13 + docs/DOM.md | 3 + docs/PROJECT_STATUS.md | 3 + docs/REACT.md | 164 +++ docs/adr/ADR-018-acces-au-dom.md | 5 +- docs/adr/README.md | 2 +- examples/CMakeLists.txt | 5 + examples/life/react/LifeReact.cpp | 22 + examples/life/react/LifeReact.hpp | 81 ++ examples/life/react/main.tsx | 56 + examples/life/react/webfront.project.json | 8 + include/webfront/components/react/Store.hpp | 115 ++ js/developer/environment/bundles.json | 4 +- js/developer/scripts/react-package.mjs | 21 + js/developer/tools/archive.mjs | 27 + js/developer/webfront.project.json | 3 + js/react/LICENSE | 1276 +++++++++++++++++++ js/react/README.md | 17 + js/react/index.d.ts | 18 + js/react/index.mjs | 82 ++ js/react/package.json | 30 + test/cmake/CheckNewcomerDocs.cmake | 6 +- test/cmake/CheckPrepareReactProject.cmake | 54 + test/cmake/CheckReactPackage.cmake | 38 + test/cmake/PrepareReactExample.cmake | 11 + test/cmake/PrepareSelfBuildProject.cmake | 1 + test/cmake/PrepareWfProject.cmake | 28 + test/unit/CMakeLists.txt | 6 +- test/unit/ReactStoreTests.cpp | 208 +++ test/web/CMakeLists.txt | 28 +- test/web/JasmineTest.cpp | 29 + test/web/registry/build.mjs | 3 + test/web/registry/fixture.mjs | 29 +- test/web/suite/pages/react-example.html | 21 + test/web/suite/pages/react.html | 12 + test/web/suite/specs/react-specs.mjs | 260 ++++ test/web/suite/specs/webfront-specs.mjs | 1 + test/web/suite/tsconfig.json | 20 + test/web/suite/types/react.tsx | 15 + test/web/suite/webfront.project.json | 19 +- 42 files changed, 2709 insertions(+), 42 deletions(-) create mode 100644 docs/REACT.md create mode 100644 examples/life/react/LifeReact.cpp create mode 100644 examples/life/react/LifeReact.hpp create mode 100644 examples/life/react/main.tsx create mode 100644 examples/life/react/webfront.project.json create mode 100644 include/webfront/components/react/Store.hpp create mode 100644 js/developer/scripts/react-package.mjs create mode 100644 js/react/LICENSE create mode 100644 js/react/README.md create mode 100644 js/react/index.d.ts create mode 100644 js/react/index.mjs create mode 100644 js/react/package.json create mode 100644 test/cmake/CheckPrepareReactProject.cmake create mode 100644 test/cmake/CheckReactPackage.cmake create mode 100644 test/cmake/PrepareReactExample.cmake create mode 100644 test/unit/ReactStoreTests.cpp create mode 100644 test/web/suite/pages/react-example.html create mode 100644 test/web/suite/pages/react.html create mode 100644 test/web/suite/specs/react-specs.mjs create mode 100644 test/web/suite/tsconfig.json create mode 100644 test/web/suite/types/react.tsx diff --git a/AGENTS.md b/AGENTS.md index 4ab30371..21589358 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,17 +10,19 @@ WebFront is a C++23 header-only library for serving a browser UI from a C++ appl WebFront also ships a standalone developer environment (`NativeApp::bootstrap("developer")`): a terminal whose `wf` commands (`init`, `create`, `install`, `restore`, `run`, `exec`, `check`, `test`, `build`, `dev`, `preview`, `embed`, `list`, `help`) manage a project manifest and lock, compile TS/TSX, type-check, run Jasmine specs and generate the application's embedded provider, with no JavaScript runtime or package manager on the developer's machine. It is not a sandbox. See `docs/DEVELOPER_ENVIRONMENT.md`. -The README introduces WebFront through the Game of Life walkthrough, demonstrating the developer bootstrap, reactive TypeScript UI and embedded distribution. The minimal `HelloWorld` example remains available under `examples/hello-world/`. Native modules and the bridge are covered by the Jasmine browser integration test. The optional `ui.document()` API provides per-connection DOM islands, batched writes, events and grouped sender reads; see `docs/DOM.md`. Application coroutines use `webfront::Task` and `app.spawn(task)`/`ui.spawn(task)`; retain a `TaskHandle` to request individual cancellation. WebFront owns and drains these tasks. Spawn is callable from any thread while the application lives; a call rejected during shutdown returns a stopped handle. Destructors wait for outstanding operations; explicit shutdown reports a stalled join. Typed C++ sender calls support local cancellation; futures and JavaScript Promises do not expose cancellation. +The README introduces WebFront through the Game of Life walkthrough, demonstrating the developer bootstrap, reactive TypeScript UI and embedded distribution. The minimal `HelloWorld` example remains available under `examples/hello-world/`. Native modules and the bridge are covered by the Jasmine browser integration test. The optional `ui.document()` API provides per-connection DOM islands, batched writes, events and grouped sender reads; see `docs/DOM.md`. The optional React store and `Island` adapter, including its support policy and coordinated unmount contract, is described in `docs/REACT.md`; `examples/life/react/` demonstrates it. Application coroutines use `webfront::Task` and `app.spawn(task)`/`ui.spawn(task)`; retain a `TaskHandle` to request individual cancellation. WebFront owns and drains these tasks. Spawn is callable from any thread while the application lives; a call rejected during shutdown returns a stopped handle. Destructors wait for outstanding operations; explicit shutdown reports a stalled join. Typed C++ sender calls support local cancellation; futures and JavaScript Promises do not expose cancellation. ## Repository map - `include/webfront/`: public header-only library, included as ``. `WebFront.hpp` is the main orchestration API; `Commands.hpp` adds an application's C++ commands to the developer environment's terminal. +- `include/webfront/components/react/`: optional C++ snapshot stores coalesced per browser; the React adapter is installed separately with `wf` and documented in `docs/REACT.md`. - `include/webfront/http/`: HTTP and WebSocket protocol implementation. - `include/webfront/weblink/`: bridge message encoding and routing. - `include/webfront/system/`: layered virtual filesystems and the embedded web resources, a closed list guarded by the `MinimalCoreAssets` CTest case (normative list and 150 KiB decoded budget in ADR-016; changing it means amending the ADR and `test/cmake/CheckMinimalCoreAssets.cmake` together). - `include/webfront/frontend/`: system-browser, CEF, optional Windows WebView2 and macOS WKWebView frontend adapters. -- `examples/`: only Hello World (`hello-world/`) and Game of Life (`life/`, with console, developer and embedded stages). +- `examples/`: only Hello World (`hello-world/`) and Game of Life (`life/`, with console, developer and embedded stages, plus the `life/react/` variant with a C++ panel inside React). - `js/core/`: readable browser bridge, fallback and bootstrap loader compiled into `include/webfront/`, plus the embedding CMake modules; `js/developer/`: developer environment (its terminal and `wf`), the wf scripts that build it (`scripts/`), build and publication tools. The repository is itself a `wf` project (`js/developer/webfront.project.json` and its lock, selected with `--manifest-dir js/developer`): the environment builds itself, and its pure JavaScript specs (`test/developer/`) run with `wf test`. Production C++ remains header-only in `include/webfront/`. +- `js/react/`: optional `@webfront/react` package (`createStore`, `useStore`, `Island`), declarations and package-local license. `wf run react-package` assembles it; tests verify the exact archive installed by the registry. It is outside the core's embedded resource list. - `test/fixtures/`, `test/web/fixtures/`: retained regression fixtures, not public example applications. - `test/unit/`: Catch2 unit tests; `test/web/`: real-browser integration (`suite/` is the WebFront project of the Jasmine specs, run by `webtest` through `wf test`); `test/driver/`: `webfront-wf`, the non-interactive `wf` driver for tests; `test/fuzz/`, `test/fixtures/`; `test/cmake/`: CMake test scripts and sub-projects. The `RepositoryLayout` CTest case pins the tracked root. - `cmake/`: build modules (frontends, CEF, CPM, compiler options); `.github/`: workflows, `.github/CONTRIBUTING.md`. diff --git a/README.md b/README.md index 91b87454..477506e3 100644 --- a/README.md +++ b/README.md @@ -279,6 +279,7 @@ CI runs one combined C++ / native-browser job per desktop platform on each code - JavaScript calls to C++ always return Promises. C++ `ui.jsFunction(name)(...)` is fire-and-forget; `ui.jsFunction(name)(...)` returns `std::future`. Missing functions, exceptions, malformed replies and disconnects fail the typed call. - The binary bridge supports scalars, strings, tuples, numeric typed arrays and packed bitsets. Arbitrary objects do not cross it. Strings have a 16-bit encoded length limit. - Development project access is explicit and intended for trusted local code. Downloaded tools run with the application's bridge authority, and script permissions frame only the `context` API: neither is a sandbox. Only packages that run in a browser are supported; installation scripts and native add-ons are not executed. Builds transform TypeScript without type checking; `wf check` type-checks with the compiler the project locks. +- The optional [`@webfront/react` adapter](docs/REACT.md) supplies coalesced C++ stores and empty React islands. `WebFrontLifeReact` demonstrates a C++ panel within the Game of Life React UI; its package archive is prepared locally for registry publication. - Packaging, accessibility and native-engine deployment still need application-specific work. The optional [`ui.document()` API](docs/DOM.md) provides DOM islands, automatically batched writes, event callbacks and grouped sender reads. See [project status](docs/PROJECT_STATUS.md) for known limitations. ## License diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 3c07e6af..b6941703 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,19 @@ ## Unreleased +- Optional React adapter (#382): an installable `@webfront/react` package with cached + `useSyncExternalStore` snapshots and empty `Island` components that tolerate StrictMode + effect replay. `webfront::react::Store` coalesces the last snapshot per 1 ms server cycle + without changing the wire format or core assets. A Game of Life variant constructs its + simulation panel in C++ inside React. Package assembly, wf installation, declarations, + batching and island lifecycle have regression coverage. Explicit flush failures retain the + pending snapshot; automatic error callbacks are contained and logged. Moved-from + store wrappers reject operations explicitly. Self-capturing error callbacks are released on + close and automatic failure; subscriber and island-release exceptions are logged and isolated. + The Life variant gates + cell edits until startup succeeds and bounds island readiness. Test installation uses the exact + archive bytes, with file-list and SHA-512 checks. Registry publication stays explicit. + - License WebFront under Apache-2.0 OR CECILL-B, at the recipient's option. Include both full license texts (CeCILL-B in French and English), document contribution terms and carry the license into newly built developer and diff --git a/docs/DOM.md b/docs/DOM.md index 03180079..3899bc6a 100644 --- a/docs/DOM.md +++ b/docs/DOM.md @@ -21,6 +21,9 @@ app.onUIStarted([](auto ui) { }); ``` +The optional [`@webfront/react` adapter](REACT.md) lends empty React `Island` components +and provides coalesced C++ stores; it is installed separately with `wf`. + A custom page lends only empty, disjoint elements that its UI library does not reconcile. It opts into the document callbacks explicitly: diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index 0ea06a46..c0dfa527 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -81,5 +81,8 @@ are retained for investigation; diagnostics alone do not establish a correction. [the wire contract](adr/ADR-003-protocole-binaire-et-bornes.md#commande-dom-dombatch-code-5-version-1). The per-connection document/node API, events and grouped sender reads are available; see [DOM from C++](DOM.md). A direct engine transport remains future work. + The optional [React adapter](REACT.md) provides a coalesced C++ store and a StrictMode-safe + `Island`, demonstrated in the Life variant. Its npm archive is prepared locally; public + registry publication is a separate action. Solid, Svelte, Vue and Lit adapters remain future work. [ADR-018](adr/ADR-018-acces-au-dom.md) describes DOM islands; [ADR-017](adr/ADR-017-acces-direct-aux-frontends.md) retains transport experiments and acceptance criteria. diff --git a/docs/REACT.md b/docs/REACT.md new file mode 100644 index 00000000..9c2f3628 --- /dev/null +++ b/docs/REACT.md @@ -0,0 +1,164 @@ +# React stores and C++ islands + +`@webfront/react` is an optional package, installed by `wf` from an npm-compatible +registry. Its sources and declarations live in `js/react`; it is not an embedded +core resource. React remains a peer dependency, shared with the application. `@types/react` is an +optional peer for TypeScript projects; install it explicitly alongside TypeScript. +No `react-reconciler` is used. The peer ranges are React `^19.3.1` and optional +`@types/react` `^19.3.0`; CI tests React 19.3.1 and `@types/react` 19.3.0. `useSyncExternalStore` reads cached snapshots; +development React 19.3.1 is exercised under `StrictMode`. This lower bound is a +support/qualification policy based on that CI baseline, not a technical requirement +of the hooks: the hooks used by the adapter exist in React 18, but React 18 and +19.0–19.2 have not been qualified here. + +## Store + +Install the browser receiver before asking C++ to send: + +```tsx +import {createStore, useStore} from '@webfront/react'; +const statistics = createStore<[number, string]>('statistics', [0, 'Waiting']); +function Statistics() { + const [count, label] = useStore(statistics); + return

{count}: {label}

; +} +``` + +In a server-context callback, construct and retain a store for that browser: + +```cpp +#include +using Snapshot = std::tuple; +webfront::react::Store statistics{ui, "statistics"}; +statistics.set({1, "Running"}); +statistics.set({2, "Running"}); // replaces the pending snapshot +``` + +Copies share pending state. Moving a store transfers its wrapper: the source's +`valid()` returns false, and `set`, `flush`, `close` and `onError` throw +`std::runtime_error` on that moved-from wrapper. The first `set` schedules an application-owned task, +which waits 1 ms on the server context. Only the last complete snapshot is sent. +A burst of 1,000 `set` calls in one callback produces one bridge message and one +React commit in the browser regression. This is a server cadence, not a rendering +deadline: writes in later cycles can cause additional commits. Different stores +have independent cycles; fields requiring an atomic update belong in one tuple. +`flush()` queues the latest snapshot early, without awaiting the browser. + +`T` must be a supported bridge value: scalar, string, tuple, numeric typed array +or packed bitset. Tuples arrive as arrays. Ordinary JavaScript objects do not cross +the bridge. Snapshot identity is stable until a message arrives; treat snapshots, +including nested arrays and typed arrays, as immutable. Subscribe functions stay +stable and return an unsubscribe function. An identical snapshot by `Object.is` +does not notify. Store names contain ASCII letters, digits, `_` or `-`. The browser namespace +`webfrontReactStores` is reserved for these receivers. A throwing subscriber is +logged to the browser console and does not interrupt the remaining subscribers; +the adapter contains diagnostic logging failures too. + +The C++ store shares its connection's document lifetime and thread rules, even +when no island is used. It does not require `dom.connect()` to send data. Create +and mutate it on the server context. Disconnect, document rejection and application +shutdown invalidate it; the timer is owned and drained by the application. +`valid()` returns false off that thread. Retained stores are safe to inspect after +the application has been destroyed; they do not extend the lifetime of `UI`. +`close()` discards pending values, releases the installed error callback and +invalidates all copies. Synchronous errors +from `set`/`flush` throw. An explicit `flush()` encoding/send failure retains the +pending snapshot and leaves the store open for retry (including the scheduled +cycle). Only a successful send clears that pending snapshot. An automatic +encoding/send failure closes the store and calls `onError(std::exception_ptr)` if +installed. The automatic failure consumes and clears that callback before invoking +it, so a callback capturing a store copy does not keep a closed store alive. +Self-owning callbacks still require an explicit `close()` on the normal path; +prefer weak captures when that lifecycle cannot be guaranteed. +Exceptions thrown by `onError` are caught and logged; they cannot escape +the automatic-send coroutine. Browser function failures are +not acknowledged by this untyped, fire-and-forget C++ call. + +Create only one C++ store per browser/name and share its copies; two independently +constructed stores do not coalesce together. Browser `createStore` rejects duplicate +names. `dispose()` removes the receiver and subscribers; coordinate it with C++ +`close()` after stopping writers. Store disposal is explicit, independent of a +component's StrictMode cleanup. Unmount all consumers before disposal: subscribing +to a disposed store throws, including a later `useSyncExternalStore` resubscription +while rendering a mounted consumer. Optional `{target: window}` installs a receiver +in another window; the default is `globalThis`. + +## Island + +Load the optional server interpreter and pass it to an empty component: + +```tsx +import {Island} from '@webfront/react'; +async function prepareDom() { + const interpreterUrl = '/webfront-dom.mjs'; + const {installDomInterpreter} = await import(interpreterUrl); + return installDomInterpreter(webFront); +} +// After prepareDom() resolves, render inside your existing React tree: +// +``` + +`Island` renders a `div` without children. Its layout effect lends that element; +after the React commit, `await dom.connect()` and ask a C++ callback to build +`ui.document().island("panel")`. Never send mutations before the corresponding +island is committed. `children` and `dangerouslySetInnerHTML` are rejected at +runtime and excluded from its TypeScript props. Keep `name` and `dom` stable for +the mounted component. Each island name is unique within its interpreter. + +StrictMode's immediate effect cleanup/setup replay keeps the same loan and C++ +children. Release is deferred to a microtask; a real unmount revokes the loan. +Unexpected synchronous release errors are caught and logged, and the adapter drops +its local lease. Such an error still requires application-level recovery/reload; +logging it does not acknowledge a C++ revocation. A bridge already closed rejects +the interpreter's revocation Promise, which the interpreter handles and logs. +Parent renders preserve the C++ subtree. A later real mount gets fresh node IDs. +Delayed effect disconnect/reconnect mechanisms such as React +[`Activity`](https://react.dev/reference/react/Activity) or Offscreen are unsupported +for a live `Island`: hiding revokes its loan, and revealing preserved DOM does not +restore it. Coordinate a full unmount, fresh empty mount and C++ rebuild instead. +Unmount still requires the [document handoff](DOM.md#coordinating-page-unmounts): +pause all document writers, flush, await a browser round trip, then unmount and +await an application-level acknowledgement that C++ observed the revocation +before resuming. The release function itself returns no acknowledgement or Promise. +The component cannot pause application writers itself. An uncoordinated unmount can close the whole document. + +## Game of Life variant + +`examples/life/react/` keeps the simulation in C++, renders the grid and statistics +with React, and builds a heading, status and “Next generation” button in C++ inside `life-panel`. +The C++ event computes a generation, updates the island and sets a tuple snapshot +containing the packed grid, generation and population. Each browser owns a separate +simulation, released on disconnect. The original Life starter remains available. + +Build the `WebFrontLifeReact` CMake target and run it with a writable copy of +`main.tsx` and `webfront.project.json` from that directory as its project argument. +In its terminal, run `wf install`, then `wf preview`. The configured registry must +carry `@webfront/react@0.1.0`; this change prepares the archive but does not publish +to npm. The repository's test registry already carries the package. For a local +evaluation, configure the driver with `--registry-dir /test/web/self-build-project/build-registry`; +the browser suite uses that registry for this adapter and React. To use the same +registry in `WebFrontLifeReact`, copy its contents to `/registry/` and add +`"registry": "/registry/"` to the project manifest before `wf install`. This is a +development mirror served from the project document root. + +To prepare the archive, use the repository wf project after restoring its packages: + +```sh +wf run react-package +``` + +This writes `build-react-package/webfront-react-0.1.0.tgz` and `integrity.txt`. +Publishing that archive to a registry is a separate maintainer action. + +The test registry uses the same deterministic packager as `wf run react-package`. +`ReactAdapterPackageContents` verifies byte-for-byte archive equality, the exact +file list, every maintained source file and the SHA-512 in `integrity.txt`. +The Life canvas ignores clicks until `life.react.start` acknowledges startup. If +the React island does not mount within five seconds, startup fails visibly. +Editing a cell starts a new simulation at generation zero. + +The generated `.tgz` uses valid gzip stored blocks, without size compression, so +bootstrap packaging needs no preinstalled compressor. Registry publication is a +separate step and may retain this format or recompress with a newly recorded digest. +The canvas cell editor is pointer-only; the C++ “Next generation” button supports +normal keyboard activation. A complete keyboard cell editor is not demonstrated. diff --git a/docs/adr/ADR-018-acces-au-dom.md b/docs/adr/ADR-018-acces-au-dom.md index 710d109d..23447528 100644 --- a/docs/adr/ADR-018-acces-au-dom.md +++ b/docs/adr/ADR-018-acces-au-dom.md @@ -7,6 +7,7 @@ | 1.0 | 2026-10-26 | Proposée | Ambroise Leclerc | Décision initiale (#378) : état de l'art TypeScript, Rust et Python vérifié, huit solutions comparées, prototypes mesurés sous WebKitGTK (flux de mutations, proxy, lectures attendues, îlots React, formulaire généré par réflexion C++26, lots hostiles), découverte d'un délai de 40 ms du transport (Nagle). | À renseigner après intégration. | | 1.1 | 2026-10-27 | Proposée, partiellement remplacée | Ambroise Leclerc | Le transport du prototype est remplacé par ADR-003 1.10 et suivantes ; l’API document/nœuds reste proposée (#381). | — | | 1.2 | 2026-10-27 | Proposée, partiellement livrée | Ambroise Leclerc | API document/nœuds, cycle de 1 ms, événements et lectures groupées (#381). | — | +| 1.3 | 2026-10-27 | Proposée, partiellement livrée | Ambroise Leclerc | Adaptateur React hors du cœur, store fusionné et variante Life (#382). | — | ## État et chronologie @@ -14,8 +15,8 @@ Le transport DOM est désormais livré par l'[ADR-003, version 1.10 et suivantes](ADR-003-protocole-binaire-et-bornes.md), avec la commande `domBatch` et `/webfront-dom.mjs` (#380). L'appel `wfDom.apply` par `jsFunction` décrit ci-dessous est uniquement le protocole historique des prototypes ; il ne décrit pas le transport livré. -L’API document/nœuds est livrée par #381 ([DOM.md](../DOM.md)) ; les adaptateurs et la réflexion -restent proposés (#382 à #384). Le point d’envoi retenu est un cycle serveur de 1 ms +L’API document/nœuds est livrée par #381 ([DOM.md](../DOM.md)) ; l’adaptateur React et le store fusionné sont livrés par #382 ([REACT.md](../REACT.md)). +Les autres adaptateurs, la réflexion et les événements attendables restent proposés (#383 et #384). Le point d’envoi retenu est un cycle serveur de 1 ms après la première écriture en attente, au sein d’une tâche possédée et drainée. `flush()` et les lectures explicites peuvent envoyer plus tôt. `SET_TEXT` reste limité aux nœuds texte. Une révocation invalide le sous-arbre ; avec des écritures en attente, diff --git a/docs/adr/README.md b/docs/adr/README.md index 843f9a1a..47c39f4c 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -57,7 +57,7 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | [ADR-015](ADR-015-ressources-generees-par-application.md) | Generating application-owned embedded resources | Accepted | 2026-10-20 | 1.0 — 2026-10-24 | | [ADR-016](ADR-016-bootstrap-comme-socle.md) | The bootstrap environment as WebFront's foundation | Accepted | 2026-10-22 | 1.6 — 2026-10-26 | | [ADR-017](ADR-017-acces-direct-aux-frontends.md) | Direct access to embedded frontends, with HTML kept normative | Proposed | 2026-10-24 | 1.1 — 2026-10-25 | -| [ADR-018](ADR-018-acces-au-dom.md) | DOM access from C++ through a bounded mutation stream, without contesting the DOM of UI libraries | Proposed, partially superseded | 2026-10-26 | 1.2 — 2026-10-27 | +| [ADR-018](ADR-018-acces-au-dom.md) | DOM access from C++ through a bounded mutation stream, without contesting the DOM of UI libraries | Proposed, partially superseded, partially delivered | 2026-10-26 | 1.3 — 2026-10-27 | Numbering follows the reading topics; milestones and individual file histories provide the chronology, which does not follow the numerical order. diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index a0182dad..5e193b62 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -53,6 +53,11 @@ target_link_libraries(WebFrontLifeDeveloper PRIVATE WebFront WebFront_warnings W webfront_setup_frontends_for_target(WebFrontLifeDeveloper) webfront_life_frontend(WebFrontLifeDeveloper) +add_executable(WebFrontLifeReact life/react/LifeReact.cpp) +target_link_libraries(WebFrontLifeReact PRIVATE WebFront WebFront_warnings WebFront_options) +webfront_setup_frontends_for_target(WebFrontLifeReact) +webfront_life_frontend(WebFrontLifeReact) + set(WEBFRONT_LIFE_ASSETS "" CACHE FILEPATH "LifeUI.hpp generated by wf embed (enables the offline Life example)") if(WEBFRONT_LIFE_ASSETS) if(NOT EXISTS "${WEBFRONT_LIFE_ASSETS}") diff --git a/examples/life/react/LifeReact.cpp b/examples/life/react/LifeReact.cpp new file mode 100644 index 00000000..cfc143bb --- /dev/null +++ b/examples/life/react/LifeReact.cpp @@ -0,0 +1,22 @@ +#include "LifeReact.hpp" + +#include "../LifeFrontend.hpp" + +#include +#include + +int main(int argc, char** argv) { + if (argc != 2) { + std::cerr << "Usage: WebFrontLifeReact \n"; + return 2; + } + try { + webfront::demo::LifeApp app{argv[1]}; + auto subscription = webfront::demo::installLifeReact(app); + app.bootstrap("developer"); + app.show(); + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/examples/life/react/LifeReact.hpp b/examples/life/react/LifeReact.hpp new file mode 100644 index 00000000..a4f44fb8 --- /dev/null +++ b/examples/life/react/LifeReact.hpp @@ -0,0 +1,81 @@ +#pragma once +#include "../Life.hpp" +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace webfront::demo { +// Kept by the registered callbacks, one simulation and one coalesced store per browser. +template +[[nodiscard]] UISubscription installLifeReact(App& app) { + using BrowserUI = typename App::UI; + using Snapshot = std::tuple; + struct Session { + react::Store store; + LifeGrid grid; + std::uint32_t generation{}; + dom::Node label; + void publish() { + label.setText("Generation " + std::to_string(generation) + " · " + std::to_string(grid.count()) + " living cells"); + store.set({grid, generation, static_cast(grid.count())}); + } + }; + auto sessions = std::make_shared>>(); + // Closure erasure frees the store and callbacks; old retained handles remain invalid. + app.cppFunction("life.react.start", [sessions](BrowserUI ui) { + if (sessions->contains(ui.id())) + throw std::runtime_error("Life React already started"); + auto doc = ui.document(); + auto panel = doc.island("life-panel"); + auto heading = doc.element("h2"); + heading.append(doc.text("C++ simulation panel")); + panel.append(heading); + auto label = doc.text(""); + auto status = doc.element("p"); + status.append(label); + panel.append(status); + auto session = std::make_shared(Session{ + react::Store{ui, "life"}, + {}, + 0, + label + }); + session->grid[1] = session->grid[34] = session->grid[64] = session->grid[65] = session->grid[66] = true; + auto button = doc.element("button"); + button.attribute("data-testid", "cpp-step"); + button.append(doc.text("Next generation")); + // Weak reference avoids a cycle through the document's owned event handlers. + button.listen("click", [weak = std::weak_ptr(session)](std::string) { + if (auto s = weak.lock()) { + s->grid = nextLife(s->grid); + ++s->generation; + s->publish(); + } + }); + panel.append(button); + sessions->emplace(ui.id(), session); + session->publish(); + }); + app.cppFunction("life.react.toggle", [sessions](BrowserUI ui, std::uint32_t index) { + if (index >= 1024) + throw std::out_of_range("Life cell index"); + const auto found = sessions->find(ui.id()); + if (found == sessions->end()) + throw std::runtime_error("Life React has not started"); + auto session = found->second; + session->grid.flip(index); + // Editing a cell starts a new simulation from generation zero. + session->generation = 0; + session->publish(); + }); + return app.subscribeUIClosed([sessions](BrowserUI ui) { + sessions->erase(ui.id()); + }); +} +} // namespace webfront::demo diff --git a/examples/life/react/main.tsx b/examples/life/react/main.tsx new file mode 100644 index 00000000..4665c5d1 --- /dev/null +++ b/examples/life/react/main.tsx @@ -0,0 +1,56 @@ +import React, {StrictMode, useEffect, useRef} from 'react'; +import {createRoot} from 'react-dom/client'; +import {Island, createStore, useStore} from '@webfront/react'; +// The optional interpreter is served by WebFront, not bundled into the adapter. +const interpreterUrl = '/webfront-dom.mjs'; + +declare const webFront: {ready: Promise; cppFunction(name: string): (...args: unknown[]) => Promise}; +async function main() { + const {installDomInterpreter} = await import(interpreterUrl); + const dom = installDomInterpreter(webFront); + const store = createStore<[Uint8Array, number, number]>('life', [new Uint8Array(128), 0, 0]); + function Life({started}: {started: boolean}) { + const [cells, generation, population] = useStore(store); + const canvas = useRef(null); + useEffect(() => { + const context = canvas.current!.getContext('2d')!; + for (let i = 0; i < 1024; ++i) { + context.fillStyle = cells[i >> 3] & (1 << (i & 7)) ? '#81efbd' : '#16362c'; + context.fillRect((i % 32) * 12, (i >> 5) * 12, 11, 11); + } + }, [cells]); + return
+

Game of Life · React + C++ island

+

Generation {generation} · {population} living cells

+ { + if (!started) return; + const rect = event.currentTarget.getBoundingClientRect(); + const x = Math.floor((event.clientX - rect.left) * 32 / rect.width); + const y = Math.floor((event.clientY - rect.top) * 32 / rect.height); + void webFront.cppFunction('life.react.toggle')(y * 32 + x).catch(showError); + }}/> + +
; + } + function showError(error: unknown) { document.getElementById('error')!.textContent = String(error); } + const root = createRoot(document.getElementById('root')!); + try { + root.render(); + // Wait for the committed Island before lending it to C++; store reception is already installed. + const deadline = performance.now() + 5000; + while (!document.querySelector('[data-testid="cpp-panel"]')) { + if (performance.now() >= deadline) throw new Error('Life panel did not mount within 5 seconds'); + await new Promise(resolve => setTimeout(resolve, 16)); + } + await dom.connect(); + await webFront.cppFunction('life.react.start')(); + root.render(); + } catch (error) { + root.unmount(); + store.dispose(); + throw error; + } +} +void main().catch(error => { document.body.textContent = String(error); }); diff --git a/examples/life/react/webfront.project.json b/examples/life/react/webfront.project.json new file mode 100644 index 00000000..4f0aa1a8 --- /dev/null +++ b/examples/life/react/webfront.project.json @@ -0,0 +1,8 @@ +{ + "format": 1, + "name": "webfront-life-react", + "version": "0.1.0", + "dependencies": {"react": "19.3.1", "react-dom": "19.3.1", "@webfront/react": "0.1.0"}, + "entries": {"main": "main.tsx"}, + "providers": {"LifeReactUI": {"entry": "main", "output": "generated/LifeReactUI.hpp"}} +} diff --git a/include/webfront/components/react/Store.hpp b/include/webfront/components/react/Store.hpp new file mode 100644 index 00000000..3b5cb2f0 --- /dev/null +++ b/include/webfront/components/react/Store.hpp @@ -0,0 +1,115 @@ +/// @brief Optional per-browser React snapshots, coalesced on the server context. +#pragma once +#include "../../dom/Document.hpp" +#include "../../tooling/Logger.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webfront::react { +/** @brief Last snapshot wins within a 1 ms cycle. T must be a bridge value (a tuple for several fields). + * Construct after the page has installed its named store. Copies share pending state. + * All access follows the DOM document's server-thread and connection lifetime rules. + */ +template +class Store { + struct State { + UI ui; + dom::Document document; + std::string function; + std::optional pending; + bool scheduled{}, closed{}; + std::function onError; + + bool valid() const noexcept { + return document.valid() && !closed; + } + void check() const { + if (!valid()) + throw std::runtime_error("React store is closed or used off the server thread"); + } + void flush() { + check(); + if (!pending) + return; + ui.jsFunction(function)(*pending); + pending.reset(); + } + }; + std::shared_ptr state; + + void check() const { + if (!state) + throw std::runtime_error("React store was moved from"); + state->check(); + } + + static Task sendAfter(std::shared_ptr state) { + co_await state->ui.resumeAfter(std::chrono::milliseconds(1)); + state->scheduled = false; + if (!state->valid()) + co_return; + try { + state->flush(); + } catch (...) { + state->closed = true; + state->pending.reset(); + auto callback = std::exchange(state->onError, nullptr); + try { + if (callback) + callback(std::current_exception()); + } catch (...) { + try { + log::error("React store onError callback threw"); + } catch (...) { + // A custom log sink must not let the user's error escape the coroutine either. + } + } + } + } + +public: + Store(UI ui, std::string name) { + if (name.empty() || name.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-") != std::string::npos) + throw std::invalid_argument("Invalid React store name"); + state = std::make_shared(State{ui, ui.document(), "webfrontReactStores." + name, {}, false, false, {}}); + } + bool valid() const noexcept { + return state && state->valid(); + } + void set(T value) const { + check(); + state->pending = std::move(value); + if (!state->scheduled) { + state->scheduled = true; + try { + static_cast(state->ui.spawn(sendAfter(state))); + } catch (...) { + state->scheduled = false; + throw; + } + } + } + /// Queues the last snapshot immediately; it does not acknowledge browser rendering. + void flush() const { + check(); + state->flush(); + } + void onError(std::function callback) const { + check(); + state->onError = std::move(callback); + } + void close() const { + check(); + state->closed = true; + state->pending.reset(); + state->onError = nullptr; + } +}; +} // namespace webfront::react diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 40df0d0d..55eae533 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -39,10 +39,10 @@ "examples/life/ui/main.tsx": "7b1ff285d2a6b8f897ef12df872886e61ef4b24e2358a9423b76b38ab75c85d3", "examples/life/ui/style.css": "9bb55eb0f0a3287e5b7dc78af9d69608b87ff42c4d9c8a653bc83a52fe293c44", "js/developer/tools/distribution.json": "7029cf3e2e64e5ea44b595fddcc0151fca4cc210d2ef1258cee7bb8d75e7cd2f", - "js/developer/tools/archive.mjs": "bfe9feeb5e4d4e1b7c44c4dec4dcbeab4ae59c2bf16a1d2b32cd6910a2b84e7b", + "js/developer/tools/archive.mjs": "da63bb9d796ddfd24ed945b15c53f66a0400eb177886fd4f1c8fd10cafb5a91b", "js/developer/tools/distribution.mjs": "1108b61bc659dd945ba1417aa84337bca03039842d342c95815b5463d87a136e", "js/developer/scripts/build.mjs": "7aa0358dbd8555ab83bf0380f67892e96b7e9806d4968de18e1a8eaf6e91c080", - "js/developer/webfront.project.json": "f5cff35f304e319f23f2bb1666eab1c6521e5da6d61c9531504df46e4001febf", + "js/developer/webfront.project.json": "e0c0bb021b1649afd5f77e8e2a45c707d2d807b1132fb4a7c17bbc2db4d3e527", "js/core/bootstrap/bootstrap.bundle.mjs": "536831257f0fc92e31911841750e1e59247f7c64e756b0fcb878efd9860a741f", "js/developer/environment/packages.bundle.mjs": "413e1dbf24d3993894d6bcbd9c01bd456e446170931f8daacfd06ce537cb2abc", "include/webfront/system/DeveloperReleaseData.hpp": "567a88fed2839a23c2abad2dd9c2b74afe9934b1e1bdf44ec1099d9332b35c90" diff --git a/js/developer/scripts/react-package.mjs b/js/developer/scripts/react-package.mjs new file mode 100644 index 00000000..f03eeb8d --- /dev/null +++ b/js/developer/scripts/react-package.mjs @@ -0,0 +1,21 @@ +// wf run react-package: prepare a publishable npm archive; this never publishes it. +import {tar, storedGzip} from '../tools/archive.mjs'; +import {sriOf} from '../tools/distribution.mjs'; + +export async function reactPackage(project) { + const manifest = JSON.parse(await project.readText('js/react/package.json')); + const files = new Map([['package/package.json', await project.read('js/react/package.json')]]); + for (const file of manifest.files) + files.set(`package/${file}`, await project.read(`js/react/${file}`)); + const bytes = storedGzip(tar(files)); + const archive = `webfront-react-${manifest.version}.tgz`; + return {manifest, bytes, archive, integrity: await sriOf(bytes)}; +} + +export default async function({project, args, console}) { + if (args.length) throw new Error('Usage: wf run react-package'); + const {bytes, archive, integrity} = await reactPackage(project); + await project.write(`build-react-package/${archive}`, bytes); + await project.write('build-react-package/integrity.txt', integrity + '\n'); + console.log(`React adapter: build-react-package/${archive}`); +} diff --git a/js/developer/tools/archive.mjs b/js/developer/tools/archive.mjs index 0c3828c1..3178d3e7 100644 --- a/js/developer/tools/archive.mjs +++ b/js/developer/tools/archive.mjs @@ -26,3 +26,30 @@ export function tar(files) { for (const bytes of chunks) { output.set(bytes, offset); offset += bytes.length; } return output; } + +// Deterministic gzip using stored blocks, usable before a registry has supplied a compressor. +const crcTable = Uint32Array.from({length: 256}, (_, n) => { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + return c >>> 0; +}); +export function storedGzip(bytes) { + const blocks = Math.max(1, Math.ceil(bytes.length / 0xffff)); + const out = new Uint8Array(10 + bytes.length + 5 * blocks + 8); + const view = new DataView(out.buffer); + out.set([0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 255]); + let at = 10; + for (let block = 0; block < blocks; block++) { + const chunk = bytes.subarray(block * 0xffff, (block + 1) * 0xffff); + out[at++] = block === blocks - 1 ? 1 : 0; + view.setUint16(at, chunk.length, true); + view.setUint16(at + 2, ~chunk.length & 0xffff, true); + out.set(chunk, at + 4); + at += 4 + chunk.length; + } + let crc = 0xffffffff; + for (const byte of bytes) crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8); + view.setUint32(at, (crc ^ 0xffffffff) >>> 0, true); + view.setUint32(at + 4, bytes.length >>> 0, true); + return out; +} diff --git a/js/developer/webfront.project.json b/js/developer/webfront.project.json index 2268948c..92ec5250 100644 --- a/js/developer/webfront.project.json +++ b/js/developer/webfront.project.json @@ -16,6 +16,7 @@ "build": "js/developer/scripts/build.mjs", "site": "js/developer/scripts/site.mjs", "pin": "js/developer/scripts/pin.mjs", + "react-package": "js/developer/scripts/react-package.mjs", "test-registry": "test/web/registry/build.mjs" }, "test": { @@ -37,6 +38,7 @@ "js/developer/webfront-packages.lock.json", ".webfront/developer/packages", "js/core", + "js/react", "js/developer/environment", "js/developer/tools", "js/developer/scripts", @@ -52,6 +54,7 @@ "build-developer-environment", "build-site", "build-registry", + "build-react-package", "js/core/bootstrap/bootstrap.bundle.mjs", "js/developer/environment/packages.bundle.mjs", "js/developer/environment/PACKAGES-LICENSE.txt", diff --git a/js/react/LICENSE b/js/react/LICENSE new file mode 100644 index 00000000..782734cb --- /dev/null +++ b/js/react/LICENSE @@ -0,0 +1,1276 @@ +WebFront +Copyright (c) 2013-2026 Ambroise Leclerc and WebFront contributors + +SPDX-License-Identifier: Apache-2.0 OR CECILL-B + +Unless otherwise stated, WebFront's original source code, examples and +accompanying documentation are available under either the Apache License, +Version 2.0, or the CeCILL-B Free Software License Agreement, Version 1, +at your option. You may choose either license; you do not need to comply +with both licenses simultaneously. + +The full license texts follow. The French and English versions of CeCILL-B +are equally authentic. The English text of Apache License 2.0 is authoritative. + +Third-party components retain their own licenses and copyright notices. +This choice of licenses does not relicense dependencies, bundled third-party +code or other material carrying a separate license notice. In particular, +see js/developer/environment/PACKAGES-LICENSE.txt for the bundled package +notice and LICENSES.txt in developer-environment distributions for their +component notices. + +License text sources: +https://www.apache.org/licenses/LICENSE-2.0.txt +https://cecill.info/licences/Licence_CeCILL-B_V1-en.txt +https://cecill.info/licences/Licence_CeCILL-B_V1-fr.txt + +======================================================================== +Apache License, Version 2.0 +======================================================================== + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +======================================================================== +CeCILL-B, Version 1 (English) +======================================================================== + + +CeCILL-B FREE SOFTWARE LICENSE AGREEMENT + + + Notice + +This Agreement is a Free Software license agreement that is the result +of discussions between its authors in order to ensure compliance with +the two main principles guiding its drafting: + + * firstly, compliance with the principles governing the distribution + of Free Software: access to source code, broad rights granted to + users, + * secondly, the election of a governing law, French law, with which + it is conformant, both as regards the law of torts and + intellectual property law, and the protection that it offers to + both authors and holders of the economic rights over software. + +The authors of the CeCILL-B (for Ce[a] C[nrs] I[nria] L[ogiciel] L[ibre]) +license are: + +Commissariat à l'Energie Atomique - CEA, a public scientific, technical +and industrial research establishment, having its principal place of +business at 25 rue Leblanc, immeuble Le Ponant D, 75015 Paris, France. + +Centre National de la Recherche Scientifique - CNRS, a public scientific +and technological establishment, having its principal place of business +at 3 rue Michel-Ange, 75794 Paris cedex 16, France. + +Institut National de Recherche en Informatique et en Automatique - +INRIA, a public scientific and technological establishment, having its +principal place of business at Domaine de Voluceau, Rocquencourt, BP +105, 78153 Le Chesnay cedex, France. + + + Preamble + +This Agreement is an open source software license intended to give users +significant freedom to modify and redistribute the software licensed +hereunder. + +The exercising of this freedom is conditional upon a strong obligation +of giving credits for everybody that distributes a software +incorporating a software ruled by the current license so as all +contributions to be properly identified and acknowledged. + +In consideration of access to the source code and the rights to copy, +modify and redistribute granted by the license, users are provided only +with a limited warranty and the software's author, the holder of the +economic rights, and the successive licensors only have limited liability. + +In this respect, the risks associated with loading, using, modifying +and/or developing or reproducing the software by the user are brought to +the user's attention, given its Free Software status, which may make it +complicated to use, with the result that its use is reserved for +developers and experienced professionals having in-depth computer +knowledge. Users are therefore encouraged to load and test the +suitability of the software as regards their requirements in conditions +enabling the security of their systems and/or data to be ensured and, +more generally, to use and operate it in the same conditions of +security. This Agreement may be freely reproduced and published, +provided it is not altered, and that no provisions are either added or +removed herefrom. + +This Agreement may apply to any or all software for which the holder of +the economic rights decides to submit the use thereof to its provisions. + + + Article 1 - DEFINITIONS + +For the purpose of this Agreement, when the following expressions +commence with a capital letter, they shall have the following meaning: + +Agreement: means this license agreement, and its possible subsequent +versions and annexes. + +Software: means the software in its Object Code and/or Source Code form +and, where applicable, its documentation, "as is" when the Licensee +accepts the Agreement. + +Initial Software: means the Software in its Source Code and possibly its +Object Code form and, where applicable, its documentation, "as is" when +it is first distributed under the terms and conditions of the Agreement. + +Modified Software: means the Software modified by at least one +Contribution. + +Source Code: means all the Software's instructions and program lines to +which access is required so as to modify the Software. + +Object Code: means the binary files originating from the compilation of +the Source Code. + +Holder: means the holder(s) of the economic rights over the Initial +Software. + +Licensee: means the Software user(s) having accepted the Agreement. + +Contributor: means a Licensee having made at least one Contribution. + +Licensor: means the Holder, or any other individual or legal entity, who +distributes the Software under the Agreement. + +Contribution: means any or all modifications, corrections, translations, +adaptations and/or new functions integrated into the Software by any or +all Contributors, as well as any or all Internal Modules. + +Module: means a set of sources files including their documentation that +enables supplementary functions or services in addition to those offered +by the Software. + +External Module: means any or all Modules, not derived from the +Software, so that this Module and the Software run in separate address +spaces, with one calling the other when they are run. + +Internal Module: means any or all Module, connected to the Software so +that they both execute in the same address space. + +Parties: mean both the Licensee and the Licensor. + +These expressions may be used both in singular and plural form. + + + Article 2 - PURPOSE + +The purpose of the Agreement is the grant by the Licensor to the +Licensee of a non-exclusive, transferable and worldwide license for the +Software as set forth in Article 5 hereinafter for the whole term of the +protection granted by the rights over said Software. + + + Article 3 - ACCEPTANCE + +3.1 The Licensee shall be deemed as having accepted the terms and +conditions of this Agreement upon the occurrence of the first of the +following events: + + * (i) loading the Software by any or all means, notably, by + downloading from a remote server, or by loading from a physical + medium; + * (ii) the first time the Licensee exercises any of the rights + granted hereunder. + +3.2 One copy of the Agreement, containing a notice relating to the +characteristics of the Software, to the limited warranty, and to the +fact that its use is restricted to experienced users has been provided +to the Licensee prior to its acceptance as set forth in Article 3.1 +hereinabove, and the Licensee hereby acknowledges that it has read and +understood it. + + + Article 4 - EFFECTIVE DATE AND TERM + + + 4.1 EFFECTIVE DATE + +The Agreement shall become effective on the date when it is accepted by +the Licensee as set forth in Article 3.1. + + + 4.2 TERM + +The Agreement shall remain in force for the entire legal term of +protection of the economic rights over the Software. + + + Article 5 - SCOPE OF RIGHTS GRANTED + +The Licensor hereby grants to the Licensee, who accepts, the following +rights over the Software for any or all use, and for the term of the +Agreement, on the basis of the terms and conditions set forth hereinafter. + +Besides, if the Licensor owns or comes to own one or more patents +protecting all or part of the functions of the Software or of its +components, the Licensor undertakes not to enforce the rights granted by +these patents against successive Licensees using, exploiting or +modifying the Software. If these patents are transferred, the Licensor +undertakes to have the transferees subscribe to the obligations set +forth in this paragraph. + + + 5.1 RIGHT OF USE + +The Licensee is authorized to use the Software, without any limitation +as to its fields of application, with it being hereinafter specified +that this comprises: + + 1. permanent or temporary reproduction of all or part of the Software + by any or all means and in any or all form. + + 2. loading, displaying, running, or storing the Software on any or + all medium. + + 3. entitlement to observe, study or test its operation so as to + determine the ideas and principles behind any or all constituent + elements of said Software. This shall apply when the Licensee + carries out any or all loading, displaying, running, transmission + or storage operation as regards the Software, that it is entitled + to carry out hereunder. + + + 5.2 ENTITLEMENT TO MAKE CONTRIBUTIONS + +The right to make Contributions includes the right to translate, adapt, +arrange, or make any or all modifications to the Software, and the right +to reproduce the resulting software. + +The Licensee is authorized to make any or all Contributions to the +Software provided that it includes an explicit notice that it is the +author of said Contribution and indicates the date of the creation thereof. + + + 5.3 RIGHT OF DISTRIBUTION + +In particular, the right of distribution includes the right to publish, +transmit and communicate the Software to the general public on any or +all medium, and by any or all means, and the right to market, either in +consideration of a fee, or free of charge, one or more copies of the +Software by any means. + +The Licensee is further authorized to distribute copies of the modified +or unmodified Software to third parties according to the terms and +conditions set forth hereinafter. + + + 5.3.1 DISTRIBUTION OF SOFTWARE WITHOUT MODIFICATION + +The Licensee is authorized to distribute true copies of the Software in +Source Code or Object Code form, provided that said distribution +complies with all the provisions of the Agreement and is accompanied by: + + 1. a copy of the Agreement, + + 2. a notice relating to the limitation of both the Licensor's + warranty and liability as set forth in Articles 8 and 9, + +and that, in the event that only the Object Code of the Software is +redistributed, the Licensee allows effective access to the full Source +Code of the Software at a minimum during the entire period of its +distribution of the Software, it being understood that the additional +cost of acquiring the Source Code shall not exceed the cost of +transferring the data. + + + 5.3.2 DISTRIBUTION OF MODIFIED SOFTWARE + +If the Licensee makes any Contribution to the Software, the resulting +Modified Software may be distributed under a license agreement other +than this Agreement subject to compliance with the provisions of Article +5.3.4. + + + 5.3.3 DISTRIBUTION OF EXTERNAL MODULES + +When the Licensee has developed an External Module, the terms and +conditions of this Agreement do not apply to said External Module, that +may be distributed under a separate license agreement. + + + 5.3.4 CREDITS + +Any Licensee who may distribute a Modified Software hereby expressly +agrees to: + + 1. indicate in the related documentation that it is based on the + Software licensed hereunder, and reproduce the intellectual + property notice for the Software, + + 2. ensure that written indications of the Software intended use, + intellectual property notice and license hereunder are included in + easily accessible format from the Modified Software interface, + + 3. mention, on a freely accessible website describing the Modified + Software, at least throughout the distribution term thereof, that + it is based on the Software licensed hereunder, and reproduce the + Software intellectual property notice, + + 4. where it is distributed to a third party that may distribute a + Modified Software without having to make its source code + available, make its best efforts to ensure that said third party + agrees to comply with the obligations set forth in this Article . + +If the Software, whether or not modified, is distributed with an +External Module designed for use in connection with the Software, the +Licensee shall submit said External Module to the foregoing obligations. + + + 5.3.5 COMPATIBILITY WITH THE CeCILL AND CeCILL-C LICENSES + +Where a Modified Software contains a Contribution subject to the CeCILL +license, the provisions set forth in Article 5.3.4 shall be optional. + +A Modified Software may be distributed under the CeCILL-C license. In +such a case the provisions set forth in Article 5.3.4 shall be optional. + + + Article 6 - INTELLECTUAL PROPERTY + + + 6.1 OVER THE INITIAL SOFTWARE + +The Holder owns the economic rights over the Initial Software. Any or +all use of the Initial Software is subject to compliance with the terms +and conditions under which the Holder has elected to distribute its work +and no one shall be entitled to modify the terms and conditions for the +distribution of said Initial Software. + +The Holder undertakes that the Initial Software will remain ruled at +least by this Agreement, for the duration set forth in Article 4.2. + + + 6.2 OVER THE CONTRIBUTIONS + +The Licensee who develops a Contribution is the owner of the +intellectual property rights over this Contribution as defined by +applicable law. + + + 6.3 OVER THE EXTERNAL MODULES + +The Licensee who develops an External Module is the owner of the +intellectual property rights over this External Module as defined by +applicable law and is free to choose the type of agreement that shall +govern its distribution. + + + 6.4 JOINT PROVISIONS + +The Licensee expressly undertakes: + + 1. not to remove, or modify, in any manner, the intellectual property + notices attached to the Software; + + 2. to reproduce said notices, in an identical manner, in the copies + of the Software modified or not. + +The Licensee undertakes not to directly or indirectly infringe the +intellectual property rights of the Holder and/or Contributors on the +Software and to take, where applicable, vis-à-vis its staff, any and all +measures required to ensure respect of said intellectual property rights +of the Holder and/or Contributors. + + + Article 7 - RELATED SERVICES + +7.1 Under no circumstances shall the Agreement oblige the Licensor to +provide technical assistance or maintenance services for the Software. + +However, the Licensor is entitled to offer this type of services. The +terms and conditions of such technical assistance, and/or such +maintenance, shall be set forth in a separate instrument. Only the +Licensor offering said maintenance and/or technical assistance services +shall incur liability therefor. + +7.2 Similarly, any Licensor is entitled to offer to its licensees, under +its sole responsibility, a warranty, that shall only be binding upon +itself, for the redistribution of the Software and/or the Modified +Software, under terms and conditions that it is free to decide. Said +warranty, and the financial terms and conditions of its application, +shall be subject of a separate instrument executed between the Licensor +and the Licensee. + + + Article 8 - LIABILITY + +8.1 Subject to the provisions of Article 8.2, the Licensee shall be +entitled to claim compensation for any direct loss it may have suffered +from the Software as a result of a fault on the part of the relevant +Licensor, subject to providing evidence thereof. + +8.2 The Licensor's liability is limited to the commitments made under +this Agreement and shall not be incurred as a result of in particular: +(i) loss due the Licensee's total or partial failure to fulfill its +obligations, (ii) direct or consequential loss that is suffered by the +Licensee due to the use or performance of the Software, and (iii) more +generally, any consequential loss. In particular the Parties expressly +agree that any or all pecuniary or business loss (i.e. loss of data, +loss of profits, operating loss, loss of customers or orders, +opportunity cost, any disturbance to business activities) or any or all +legal proceedings instituted against the Licensee by a third party, +shall constitute consequential loss and shall not provide entitlement to +any or all compensation from the Licensor. + + + Article 9 - WARRANTY + +9.1 The Licensee acknowledges that the scientific and technical +state-of-the-art when the Software was distributed did not enable all +possible uses to be tested and verified, nor for the presence of +possible defects to be detected. In this respect, the Licensee's +attention has been drawn to the risks associated with loading, using, +modifying and/or developing and reproducing the Software which are +reserved for experienced users. + +The Licensee shall be responsible for verifying, by any or all means, +the suitability of the product for its requirements, its good working +order, and for ensuring that it shall not cause damage to either persons +or properties. + +9.2 The Licensor hereby represents, in good faith, that it is entitled +to grant all the rights over the Software (including in particular the +rights set forth in Article 5). + +9.3 The Licensee acknowledges that the Software is supplied "as is" by +the Licensor without any other express or tacit warranty, other than +that provided for in Article 9.2 and, in particular, without any warranty +as to its commercial value, its secured, safe, innovative or relevant +nature. + +Specifically, the Licensor does not warrant that the Software is free +from any error, that it will operate without interruption, that it will +be compatible with the Licensee's own equipment and software +configuration, nor that it will meet the Licensee's requirements. + +9.4 The Licensor does not either expressly or tacitly warrant that the +Software does not infringe any third party intellectual property right +relating to a patent, software or any other property right. Therefore, +the Licensor disclaims any and all liability towards the Licensee +arising out of any or all proceedings for infringement that may be +instituted in respect of the use, modification and redistribution of the +Software. Nevertheless, should such proceedings be instituted against +the Licensee, the Licensor shall provide it with technical and legal +assistance for its defense. Such technical and legal assistance shall be +decided on a case-by-case basis between the relevant Licensor and the +Licensee pursuant to a memorandum of understanding. The Licensor +disclaims any and all liability as regards the Licensee's use of the +name of the Software. No warranty is given as regards the existence of +prior rights over the name of the Software or as regards the existence +of a trademark. + + + Article 10 - TERMINATION + +10.1 In the event of a breach by the Licensee of its obligations +hereunder, the Licensor may automatically terminate this Agreement +thirty (30) days after notice has been sent to the Licensee and has +remained ineffective. + +10.2 A Licensee whose Agreement is terminated shall no longer be +authorized to use, modify or distribute the Software. However, any +licenses that it may have granted prior to termination of the Agreement +shall remain valid subject to their having been granted in compliance +with the terms and conditions hereof. + + + Article 11 - MISCELLANEOUS + + + 11.1 EXCUSABLE EVENTS + +Neither Party shall be liable for any or all delay, or failure to +perform the Agreement, that may be attributable to an event of force +majeure, an act of God or an outside cause, such as defective +functioning or interruptions of the electricity or telecommunications +networks, network paralysis following a virus attack, intervention by +government authorities, natural disasters, water damage, earthquakes, +fire, explosions, strikes and labor unrest, war, etc. + +11.2 Any failure by either Party, on one or more occasions, to invoke +one or more of the provisions hereof, shall under no circumstances be +interpreted as being a waiver by the interested Party of its right to +invoke said provision(s) subsequently. + +11.3 The Agreement cancels and replaces any or all previous agreements, +whether written or oral, between the Parties and having the same +purpose, and constitutes the entirety of the agreement between said +Parties concerning said purpose. No supplement or modification to the +terms and conditions hereof shall be effective as between the Parties +unless it is made in writing and signed by their duly authorized +representatives. + +11.4 In the event that one or more of the provisions hereof were to +conflict with a current or future applicable act or legislative text, +said act or legislative text shall prevail, and the Parties shall make +the necessary amendments so as to comply with said act or legislative +text. All other provisions shall remain effective. Similarly, invalidity +of a provision of the Agreement, for any reason whatsoever, shall not +cause the Agreement as a whole to be invalid. + + + 11.5 LANGUAGE + +The Agreement is drafted in both French and English and both versions +are deemed authentic. + + + Article 12 - NEW VERSIONS OF THE AGREEMENT + +12.1 Any person is authorized to duplicate and distribute copies of this +Agreement. + +12.2 So as to ensure coherence, the wording of this Agreement is +protected and may only be modified by the authors of the License, who +reserve the right to periodically publish updates or new versions of the +Agreement, each with a separate number. These subsequent versions may +address new issues encountered by Free Software. + +12.3 Any Software distributed under a given version of the Agreement may +only be subsequently distributed under the same version of the Agreement +or a subsequent version. + + + Article 13 - GOVERNING LAW AND JURISDICTION + +13.1 The Agreement is governed by French law. The Parties agree to +endeavor to seek an amicable solution to any disagreements or disputes +that may arise during the performance of the Agreement. + +13.2 Failing an amicable solution within two (2) months as from their +occurrence, and unless emergency proceedings are necessary, the +disagreements or disputes shall be referred to the Paris Courts having +jurisdiction, by the more diligent Party. + + +Version 1.0 dated 2006-09-05. + +======================================================================== +CeCILL-B, version 1 (français) +======================================================================== + + +CONTRAT DE LICENCE DE LOGICIEL LIBRE CeCILL-B + + + Avertissement + +Ce contrat est une licence de logiciel libre issue d'une concertation +entre ses auteurs afin que le respect de deux grands principes préside à +sa rédaction: + + * d'une part, le respect des principes de diffusion des logiciels + libres: accès au code source, droits étendus conférés aux + utilisateurs, + * d'autre part, la désignation d'un droit applicable, le droit + français, auquel elle est conforme, tant au regard du droit de la + responsabilité civile que du droit de la propriété intellectuelle + et de la protection qu'il offre aux auteurs et titulaires des + droits patrimoniaux sur un logiciel. + +Les auteurs de la licence CeCILL-B (pour Ce[a] C[nrs] I[nria] L[ogiciel] +L[ibre]) sont: + +Commissariat à l'Energie Atomique - CEA, établissement public de +recherche à caractère scientifique, technique et industriel, dont le +siège est situé 25 rue Leblanc, immeuble Le Ponant D, 75015 Paris. + +Centre National de la Recherche Scientifique - CNRS, établissement +public à caractère scientifique et technologique, dont le siège est +situé 3 rue Michel-Ange, 75794 Paris cedex 16. + +Institut National de Recherche en Informatique et en Automatique - +INRIA, établissement public à caractère scientifique et technologique, +dont le siège est situé Domaine de Voluceau, Rocquencourt, BP 105, 78153 +Le Chesnay cedex. + + + Préambule + +Ce contrat est une licence de logiciel libre dont l'objectif est de +conférer aux utilisateurs une très large liberté de modification et de +redistribution du logiciel régi par cette licence. + +L'exercice de cette liberté est assorti d'une obligation forte de +citation à la charge de ceux qui distribueraient un logiciel incorporant +un logiciel régi par la présente licence afin d'assurer que les +contributions de tous soient correctement identifiées et reconnues. + +L'accessibilité au code source et les droits de copie, de modification +et de redistribution qui découlent de ce contrat ont pour contrepartie +de n'offrir aux utilisateurs qu'une garantie limitée et de ne faire +peser sur l'auteur du logiciel, le titulaire des droits patrimoniaux et +les concédants successifs qu'une responsabilité restreinte. + +A cet égard l'attention de l'utilisateur est attirée sur les risques +associés au chargement, à l'utilisation, à la modification et/ou au +développement et à la reproduction du logiciel par l'utilisateur étant +donné sa spécificité de logiciel libre, qui peut le rendre complexe à +manipuler et qui le réserve donc à des développeurs ou des +professionnels avertis possédant des connaissances informatiques +approfondies. Les utilisateurs sont donc invités à charger et tester +l'adéquation du logiciel à leurs besoins dans des conditions permettant +d'assurer la sécurité de leurs systèmes et/ou de leurs données et, plus +généralement, à l'utiliser et l'exploiter dans les mêmes conditions de +sécurité. Ce contrat peut être reproduit et diffusé librement, sous +réserve de le conserver en l'état, sans ajout ni suppression de clauses. + +Ce contrat est susceptible de s'appliquer à tout logiciel dont le +titulaire des droits patrimoniaux décide de soumettre l'exploitation aux +dispositions qu'il contient. + + + Article 1 - DEFINITIONS + +Dans ce contrat, les termes suivants, lorsqu'ils seront écrits avec une +lettre capitale, auront la signification suivante: + +Contrat: désigne le présent contrat de licence, ses éventuelles versions +postérieures et annexes. + +Logiciel: désigne le logiciel sous sa forme de Code Objet et/ou de Code +Source et le cas échéant sa documentation, dans leur état au moment de +l'acceptation du Contrat par le Licencié. + +Logiciel Initial: désigne le Logiciel sous sa forme de Code Source et +éventuellement de Code Objet et le cas échéant sa documentation, dans +leur état au moment de leur première diffusion sous les termes du Contrat. + +Logiciel Modifié: désigne le Logiciel modifié par au moins une +Contribution. + +Code Source: désigne l'ensemble des instructions et des lignes de +programme du Logiciel et auquel l'accès est nécessaire en vue de +modifier le Logiciel. + +Code Objet: désigne les fichiers binaires issus de la compilation du +Code Source. + +Titulaire: désigne le ou les détenteurs des droits patrimoniaux d'auteur +sur le Logiciel Initial. + +Licencié: désigne le ou les utilisateurs du Logiciel ayant accepté le +Contrat. + +Contributeur: désigne le Licencié auteur d'au moins une Contribution. + +Concédant: désigne le Titulaire ou toute personne physique ou morale +distribuant le Logiciel sous le Contrat. + +Contribution: désigne l'ensemble des modifications, corrections, +traductions, adaptations et/ou nouvelles fonctionnalités intégrées dans +le Logiciel par tout Contributeur, ainsi que tout Module Interne. + +Module: désigne un ensemble de fichiers sources y compris leur +documentation qui permet de réaliser des fonctionnalités ou services +supplémentaires à ceux fournis par le Logiciel. + +Module Externe: désigne tout Module, non dérivé du Logiciel, tel que ce +Module et le Logiciel s'exécutent dans des espaces d'adressage +différents, l'un appelant l'autre au moment de leur exécution. + +Module Interne: désigne tout Module lié au Logiciel de telle sorte +qu'ils s'exécutent dans le même espace d'adressage. + +Parties: désigne collectivement le Licencié et le Concédant. + +Ces termes s'entendent au singulier comme au pluriel. + + + Article 2 - OBJET + +Le Contrat a pour objet la concession par le Concédant au Licencié d'une +licence non exclusive, cessible et mondiale du Logiciel telle que +définie ci-après à l'article 5 pour toute la durée de protection des droits +portant sur ce Logiciel. + + + Article 3 - ACCEPTATION + +3.1 L'acceptation par le Licencié des termes du Contrat est réputée +acquise du fait du premier des faits suivants: + + * (i) le chargement du Logiciel par tout moyen notamment par + téléchargement à partir d'un serveur distant ou par chargement à + partir d'un support physique; + * (ii) le premier exercice par le Licencié de l'un quelconque des + droits concédés par le Contrat. + +3.2 Un exemplaire du Contrat, contenant notamment un avertissement +relatif aux spécificités du Logiciel, à la restriction de garantie et à +la limitation à un usage par des utilisateurs expérimentés a été mis à +disposition du Licencié préalablement à son acceptation telle que +définie à l'article 3.1 ci dessus et le Licencié reconnaît en avoir pris +connaissance. + + + Article 4 - ENTREE EN VIGUEUR ET DUREE + + + 4.1 ENTREE EN VIGUEUR + +Le Contrat entre en vigueur à la date de son acceptation par le Licencié +telle que définie en 3.1. + + + 4.2 DUREE + +Le Contrat produira ses effets pendant toute la durée légale de +protection des droits patrimoniaux portant sur le Logiciel. + + + Article 5 - ETENDUE DES DROITS CONCEDES + +Le Concédant concède au Licencié, qui accepte, les droits suivants sur +le Logiciel pour toutes destinations et pour la durée du Contrat dans +les conditions ci-après détaillées. + +Par ailleurs, si le Concédant détient ou venait à détenir un ou +plusieurs brevets d'invention protégeant tout ou partie des +fonctionnalités du Logiciel ou de ses composants, il s'engage à ne pas +opposer les éventuels droits conférés par ces brevets aux Licenciés +successifs qui utiliseraient, exploiteraient ou modifieraient le +Logiciel. En cas de cession de ces brevets, le Concédant s'engage à +faire reprendre les obligations du présent alinéa aux cessionnaires. + + + 5.1 DROIT D'UTILISATION + +Le Licencié est autorisé à utiliser le Logiciel, sans restriction quant +aux domaines d'application, étant ci-après précisé que cela comporte: + + 1. la reproduction permanente ou provisoire du Logiciel en tout ou + partie par tout moyen et sous toute forme. + + 2. le chargement, l'affichage, l'exécution, ou le stockage du + Logiciel sur tout support. + + 3. la possibilité d'en observer, d'en étudier, ou d'en tester le + fonctionnement afin de déterminer les idées et principes qui sont + à la base de n'importe quel élément de ce Logiciel; et ceci, + lorsque le Licencié effectue toute opération de chargement, + d'affichage, d'exécution, de transmission ou de stockage du + Logiciel qu'il est en droit d'effectuer en vertu du Contrat. + + + 5.2 DROIT D'APPORTER DES CONTRIBUTIONS + +Le droit d'apporter des Contributions comporte le droit de traduire, +d'adapter, d'arranger ou d'apporter toute autre modification au Logiciel +et le droit de reproduire le logiciel en résultant. + +Le Licencié est autorisé à apporter toute Contribution au Logiciel sous +réserve de mentionner, de façon explicite, son nom en tant qu'auteur de +cette Contribution et la date de création de celle-ci. + + + 5.3 DROIT DE DISTRIBUTION + +Le droit de distribution comporte notamment le droit de diffuser, de +transmettre et de communiquer le Logiciel au public sur tout support et +par tout moyen ainsi que le droit de mettre sur le marché à titre +onéreux ou gratuit, un ou des exemplaires du Logiciel par tout procédé. + +Le Licencié est autorisé à distribuer des copies du Logiciel, modifié ou +non, à des tiers dans les conditions ci-après détaillées. + + + 5.3.1 DISTRIBUTION DU LOGICIEL SANS MODIFICATION + +Le Licencié est autorisé à distribuer des copies conformes du Logiciel, +sous forme de Code Source ou de Code Objet, à condition que cette +distribution respecte les dispositions du Contrat dans leur totalité et +soit accompagnée: + + 1. d'un exemplaire du Contrat, + + 2. d'un avertissement relatif à la restriction de garantie et de + responsabilité du Concédant telle que prévue aux articles 8 + et 9, + +et que, dans le cas où seul le Code Objet du Logiciel est redistribué, +le Licencié permette un accès effectif au Code Source complet du +Logiciel pendant au moins toute la durée de sa distribution du Logiciel, +étant entendu que le coût additionnel d'acquisition du Code Source ne +devra pas excéder le simple coût de transfert des données. + + + 5.3.2 DISTRIBUTION DU LOGICIEL MODIFIE + +Lorsque le Licencié apporte une Contribution au Logiciel, le Logiciel +Modifié peut être distribué sous un contrat de licence autre que le +présent Contrat sous réserve du respect des dispositions de l'article +5.3.4. + + + 5.3.3 DISTRIBUTION DES MODULES EXTERNES + +Lorsque le Licencié a développé un Module Externe les conditions du +Contrat ne s'appliquent pas à ce Module Externe, qui peut être distribué +sous un contrat de licence différent. + + + 5.3.4 CITATIONS + +Le Licencié qui distribue un Logiciel Modifié s'engage expressément: + + 1. à indiquer dans sa documentation qu'il a été réalisé à partir du + Logiciel régi par le Contrat, en reproduisant les mentions de + propriété intellectuelle du Logiciel, + + 2. à faire en sorte que l'utilisation du Logiciel, ses mentions de + propriété intellectuelle et le fait qu'il est régi par le Contrat + soient indiqués dans un texte facilement accessible depuis + l'interface du Logiciel Modifié, + + 3. à mentionner, sur un site Web librement accessible décrivant le + Logiciel Modifié, et pendant au moins toute la durée de sa + distribution, qu'il a été réalisé à partir du Logiciel régi par le + Contrat, en reproduisant les mentions de propriété intellectuelle + du Logiciel, + + 4. lorsqu'il le distribue à un tiers susceptible de distribuer + lui-même un Logiciel Modifié, sans avoir à en distribuer le code + source, à faire ses meilleurs efforts pour que les obligations du + présent article 5.3.4 soient reprises par le dit tiers. + +Lorsque le Logiciel modifié ou non est distribué avec un Module Externe +qui a été conçu pour l'utiliser, le Licencié doit soumettre le dit +Module Externe aux obligations précédentes. + + + 5.3.5 COMPATIBILITE AVEC LES LICENCES CeCILL et CeCILL-C + +Lorsqu'un Logiciel Modifié contient une Contribution soumise au contrat +de licence CeCILL, les stipulations prévues à l'article 5.3.4 sont +facultatives. + +Un Logiciel Modifié peut être distribué sous le contrat de licence +CeCILL-C. Les stipulations prévues à l'article 5.3.4 sont alors +facultatives. + + + Article 6 - PROPRIETE INTELLECTUELLE + + + 6.1 SUR LE LOGICIEL INITIAL + +Le Titulaire est détenteur des droits patrimoniaux sur le Logiciel +Initial. Toute utilisation du Logiciel Initial est soumise au respect +des conditions dans lesquelles le Titulaire a choisi de diffuser son +oeuvre et nul autre n'a la faculté de modifier les conditions de +diffusion de ce Logiciel Initial. + +Le Titulaire s'engage à ce que le Logiciel Initial reste au moins régi +par le Contrat et ce, pour la durée visée à l'article 4.2. + + + 6.2 SUR LES CONTRIBUTIONS + +Le Licencié qui a développé une Contribution est titulaire sur celle-ci +des droits de propriété intellectuelle dans les conditions définies par +la législation applicable. + + + 6.3 SUR LES MODULES EXTERNES + +Le Licencié qui a développé un Module Externe est titulaire sur celui-ci +des droits de propriété intellectuelle dans les conditions définies par +la législation applicable et reste libre du choix du contrat régissant +sa diffusion. + + + 6.4 DISPOSITIONS COMMUNES + +Le Licencié s'engage expressément: + + 1. à ne pas supprimer ou modifier de quelque manière que ce soit les + mentions de propriété intellectuelle apposées sur le Logiciel; + + 2. à reproduire à l'identique lesdites mentions de propriété + intellectuelle sur les copies du Logiciel modifié ou non. + +Le Licencié s'engage à ne pas porter atteinte, directement ou +indirectement, aux droits de propriété intellectuelle du Titulaire et/ou +des Contributeurs sur le Logiciel et à prendre, le cas échéant, à +l'égard de son personnel toutes les mesures nécessaires pour assurer le +respect des dits droits de propriété intellectuelle du Titulaire et/ou +des Contributeurs. + + + Article 7 - SERVICES ASSOCIES + +7.1 Le Contrat n'oblige en aucun cas le Concédant à la réalisation de +prestations d'assistance technique ou de maintenance du Logiciel. + +Cependant le Concédant reste libre de proposer ce type de services. Les +termes et conditions d'une telle assistance technique et/ou d'une telle +maintenance seront alors déterminés dans un acte séparé. Ces actes de +maintenance et/ou assistance technique n'engageront que la seule +responsabilité du Concédant qui les propose. + +7.2 De même, tout Concédant est libre de proposer, sous sa seule +responsabilité, à ses licenciés une garantie, qui n'engagera que lui, +lors de la redistribution du Logiciel et/ou du Logiciel Modifié et ce, +dans les conditions qu'il souhaite. Cette garantie et les modalités +financières de son application feront l'objet d'un acte séparé entre le +Concédant et le Licencié. + + + Article 8 - RESPONSABILITE + +8.1 Sous réserve des dispositions de l'article 8.2, le Licencié a la +faculté, sous réserve de prouver la faute du Concédant concerné, de +solliciter la réparation du préjudice direct qu'il subirait du fait du +Logiciel et dont il apportera la preuve. + +8.2 La responsabilité du Concédant est limitée aux engagements pris en +application du Contrat et ne saurait être engagée en raison notamment: +(i) des dommages dus à l'inexécution, totale ou partielle, de ses +obligations par le Licencié, (ii) des dommages directs ou indirects +découlant de l'utilisation ou des performances du Logiciel subis par le +Licencié et (iii) plus généralement d'un quelconque dommage indirect. En +particulier, les Parties conviennent expressément que tout préjudice +financier ou commercial (par exemple perte de données, perte de +bénéfices, perte d'exploitation, perte de clientèle ou de commandes, +manque à gagner, trouble commercial quelconque) ou toute action dirigée +contre le Licencié par un tiers, constitue un dommage indirect et +n'ouvre pas droit à réparation par le Concédant. + + + Article 9 - GARANTIE + +9.1 Le Licencié reconnaît que l'état actuel des connaissances +scientifiques et techniques au moment de la mise en circulation du +Logiciel ne permet pas d'en tester et d'en vérifier toutes les +utilisations ni de détecter l'existence d'éventuels défauts. L'attention +du Licencié a été attirée sur ce point sur les risques associés au +chargement, à l'utilisation, la modification et/ou au développement et à +la reproduction du Logiciel qui sont réservés à des utilisateurs avertis. + +Il relève de la responsabilité du Licencié de contrôler, par tous +moyens, l'adéquation du produit à ses besoins, son bon fonctionnement et +de s'assurer qu'il ne causera pas de dommages aux personnes et aux biens. + +9.2 Le Concédant déclare de bonne foi être en droit de concéder +l'ensemble des droits attachés au Logiciel (comprenant notamment les +droits visés à l'article 5). + +9.3 Le Licencié reconnaît que le Logiciel est fourni "en l'état" par le +Concédant sans autre garantie, expresse ou tacite, que celle prévue à +l'article 9.2 et notamment sans aucune garantie sur sa valeur commerciale, +son caractère sécurisé, innovant ou pertinent. + +En particulier, le Concédant ne garantit pas que le Logiciel est exempt +d'erreur, qu'il fonctionnera sans interruption, qu'il sera compatible +avec l'équipement du Licencié et sa configuration logicielle ni qu'il +remplira les besoins du Licencié. + +9.4 Le Concédant ne garantit pas, de manière expresse ou tacite, que le +Logiciel ne porte pas atteinte à un quelconque droit de propriété +intellectuelle d'un tiers portant sur un brevet, un logiciel ou sur tout +autre droit de propriété. Ainsi, le Concédant exclut toute garantie au +profit du Licencié contre les actions en contrefaçon qui pourraient être +diligentées au titre de l'utilisation, de la modification, et de la +redistribution du Logiciel. Néanmoins, si de telles actions sont +exercées contre le Licencié, le Concédant lui apportera son aide +technique et juridique pour sa défense. Cette aide technique et +juridique est déterminée au cas par cas entre le Concédant concerné et +le Licencié dans le cadre d'un protocole d'accord. Le Concédant dégage +toute responsabilité quant à l'utilisation de la dénomination du +Logiciel par le Licencié. Aucune garantie n'est apportée quant à +l'existence de droits antérieurs sur le nom du Logiciel et sur +l'existence d'une marque. + + + Article 10 - RESILIATION + +10.1 En cas de manquement par le Licencié aux obligations mises à sa +charge par le Contrat, le Concédant pourra résilier de plein droit le +Contrat trente (30) jours après notification adressée au Licencié et +restée sans effet. + +10.2 Le Licencié dont le Contrat est résilié n'est plus autorisé à +utiliser, modifier ou distribuer le Logiciel. Cependant, toutes les +licences qu'il aura concédées antérieurement à la résiliation du Contrat +resteront valides sous réserve qu'elles aient été effectuées en +conformité avec le Contrat. + + + Article 11 - DISPOSITIONS DIVERSES + + + 11.1 CAUSE EXTERIEURE + +Aucune des Parties ne sera responsable d'un retard ou d'une défaillance +d'exécution du Contrat qui serait dû à un cas de force majeure, un cas +fortuit ou une cause extérieure, telle que, notamment, le mauvais +fonctionnement ou les interruptions du réseau électrique ou de +télécommunication, la paralysie du réseau liée à une attaque +informatique, l'intervention des autorités gouvernementales, les +catastrophes naturelles, les dégâts des eaux, les tremblements de terre, +le feu, les explosions, les grèves et les conflits sociaux, l'état de +guerre... + +11.2 Le fait, par l'une ou l'autre des Parties, d'omettre en une ou +plusieurs occasions de se prévaloir d'une ou plusieurs dispositions du +Contrat, ne pourra en aucun cas impliquer renonciation par la Partie +intéressée à s'en prévaloir ultérieurement. + +11.3 Le Contrat annule et remplace toute convention antérieure, écrite +ou orale, entre les Parties sur le même objet et constitue l'accord +entier entre les Parties sur cet objet. Aucune addition ou modification +aux termes du Contrat n'aura d'effet à l'égard des Parties à moins +d'être faite par écrit et signée par leurs représentants dûment habilités. + +11.4 Dans l'hypothèse où une ou plusieurs des dispositions du Contrat +s'avèrerait contraire à une loi ou à un texte applicable, existants ou +futurs, cette loi ou ce texte prévaudrait, et les Parties feraient les +amendements nécessaires pour se conformer à cette loi ou à ce texte. +Toutes les autres dispositions resteront en vigueur. De même, la +nullité, pour quelque raison que ce soit, d'une des dispositions du +Contrat ne saurait entraîner la nullité de l'ensemble du Contrat. + + + 11.5 LANGUE + +Le Contrat est rédigé en langue française et en langue anglaise, ces +deux versions faisant également foi. + + + Article 12 - NOUVELLES VERSIONS DU CONTRAT + +12.1 Toute personne est autorisée à copier et distribuer des copies de +ce Contrat. + +12.2 Afin d'en préserver la cohérence, le texte du Contrat est protégé +et ne peut être modifié que par les auteurs de la licence, lesquels se +réservent le droit de publier périodiquement des mises à jour ou de +nouvelles versions du Contrat, qui posséderont chacune un numéro +distinct. Ces versions ultérieures seront susceptibles de prendre en +compte de nouvelles problématiques rencontrées par les logiciels libres. + +12.3 Tout Logiciel diffusé sous une version donnée du Contrat ne pourra +faire l'objet d'une diffusion ultérieure que sous la même version du +Contrat ou une version postérieure. + + + Article 13 - LOI APPLICABLE ET COMPETENCE TERRITORIALE + +13.1 Le Contrat est régi par la loi française. Les Parties conviennent +de tenter de régler à l'amiable les différends ou litiges qui +viendraient à se produire par suite ou à l'occasion du Contrat. + +13.2 A défaut d'accord amiable dans un délai de deux (2) mois à compter +de leur survenance et sauf situation relevant d'une procédure d'urgence, +les différends ou litiges seront portés par la Partie la plus diligente +devant les Tribunaux compétents de Paris. + + +Version 1.0 du 2006-09-05. diff --git a/js/react/README.md b/js/react/README.md new file mode 100644 index 00000000..1c148c16 --- /dev/null +++ b/js/react/README.md @@ -0,0 +1,17 @@ +# @webfront/react + +Optional React adapter for WebFront. It is installed with `wf`, uses React's +`useSyncExternalStore`, and renders C++ DOM islands without a custom reconciler. +Neither React nor this package is added to the core's embedded resources. + +The package sources, declared files and license are self-contained in `js/react`. +The packaged license is checked against the repository's root `LICENSE`. +The peer ranges accept React `^19.3.1` and optional `@types/react` `^19.3.0`; +CI currently tests 19.3.1 and 19.3.0 respectively. From the repository's wf project, run +`wf run react-package` after `wf install` to generate +`build-react-package/webfront-react-0.1.0.tgz` and its SHA-512. +This prepares an npm archive; it does **not** publish it. Install from a registry +carrying that archive with `wf install @webfront/react@0.1.0 react@19.3.1 react-dom@19.3.1`. +The repository's test registry packages these same sources and proves installation +without public network access. See [React integration](https://github.com/ambroise-leclerc/WebFront/blob/develop/docs/REACT.md) for +the C++ API, lifecycle contract, and Game of Life variant. diff --git a/js/react/index.d.ts b/js/react/index.d.ts new file mode 100644 index 00000000..1b1a7a31 --- /dev/null +++ b/js/react/index.d.ts @@ -0,0 +1,18 @@ +import type {HTMLAttributes, ReactElement} from 'react'; +export interface Store { + getSnapshot(): T; + subscribe(listener: () => void): () => void; + dispose(): void; +} +export declare function createStore(name: string, initialSnapshot: T, options?: {target?: typeof globalThis | Window}): Store; +export declare function useStore(store: Store): T; +export interface DomInterpreter { + island(name: string, element: HTMLElement): () => void; +} +export type IslandProps = Omit, 'children' | 'dangerouslySetInnerHTML'> & { + dom: DomInterpreter; + name: string; + children?: never; + dangerouslySetInnerHTML?: never; +}; +export declare function Island(props: IslandProps): ReactElement; diff --git a/js/react/index.mjs b/js/react/index.mjs new file mode 100644 index 00000000..b4de1a9a --- /dev/null +++ b/js/react/index.mjs @@ -0,0 +1,82 @@ +import {createElement, useLayoutEffect, useRef, useSyncExternalStore} from 'react'; + +function reportFailure(message, error) { + try { console.error(message, error); } + catch { /* Diagnostics must not interrupt another consumer or escape effect cleanup. */ } +} + +/** A cached snapshot, replaced once per C++ message. Treat bridge arrays as immutable values. */ +export function createStore(name, initialSnapshot, {target = globalThis} = {}) { + if (!/^[A-Za-z0-9_-]+$/.test(name)) throw new TypeError('Invalid React store name'); + const registry = target.webfrontReactStores ??= Object.create(null); + if (Object.hasOwn(registry, name)) throw new Error('React store name already installed'); + let snapshot = initialSnapshot, disposed = false; + const listeners = new Set(); + const receive = value => { + if (Object.is(snapshot, value)) return; + snapshot = value; + for (const listener of [...listeners]) { + try { listener(); } + catch (error) { reportFailure('WebFront React store subscriber failed', error); } + } + }; + registry[name] = receive; + const store = { + getSnapshot: () => snapshot, + subscribe(listener) { + if (disposed) throw new Error('React store disposed'); + listeners.add(listener); + return () => listeners.delete(listener); + }, + dispose() { + disposed = true; + listeners.clear(); + if (registry[name] === receive) delete registry[name]; + }, + }; + return store; +} + +export function useStore(store) { + return useSyncExternalStore(store.subscribe, store.getSnapshot); +} + +// Defer release through StrictMode's synchronous cleanup/setup replay. Real unmounts still revoke. +const leases = new WeakMap(); +function releaseLease(names, name, lease) { + try { lease.release(); } + catch (error) { reportFailure('WebFront React island release failed', error); } + finally { if (names.get(name) === lease) names.delete(name); } +} + +export function Island({dom, name, children, dangerouslySetInnerHTML, ...props}) { + if (children != null || dangerouslySetInnerHTML != null) throw new Error('Island must be rendered without children'); + const element = useRef(null); + const identity = useRef({dom, name}); + if (identity.current.dom !== dom || identity.current.name !== name) + throw new Error('Island dom and name must stay stable; remount with a key'); + useLayoutEffect(() => { + let names = leases.get(dom); + if (!names) leases.set(dom, names = new Map()); + let lease = names.get(name); + if (lease?.pending && lease.element !== element.current) { + releaseLease(names, name, lease); + lease = null; + } + if (lease && (!lease.pending || lease.element !== element.current)) throw new Error('Island name already mounted'); + if (!lease) { + lease = {element: element.current, release: dom.island(name, element.current), pending: false}; + names.set(name, lease); + } + lease.pending = false; + return () => { + lease.pending = true; + queueMicrotask(() => { + if (lease.pending && names.get(name) === lease) { + releaseLease(names, name, lease); + } + }); + }; + }, [dom, name]); + return createElement('div', {...props, ref: element}); +} diff --git a/js/react/package.json b/js/react/package.json new file mode 100644 index 00000000..68b322b9 --- /dev/null +++ b/js/react/package.json @@ -0,0 +1,30 @@ +{ + "name": "@webfront/react", + "version": "0.1.0", + "type": "module", + "main": "index.mjs", + "types": "index.d.ts", + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./index.mjs", + "default": "./index.mjs" + } + }, + "peerDependencies": { + "react": "^19.3.1", + "@types/react": "^19.3.0" + }, + "license": "(Apache-2.0 OR CECILL-B)", + "files": [ + "index.mjs", + "index.d.ts", + "README.md", + "LICENSE" + ], + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } +} diff --git a/test/cmake/CheckNewcomerDocs.cmake b/test/cmake/CheckNewcomerDocs.cmake index 188c51bd..ea4c60ae 100644 --- a/test/cmake/CheckNewcomerDocs.cmake +++ b/test/cmake/CheckNewcomerDocs.cmake @@ -62,7 +62,7 @@ endforeach() _require("${readme}" "webfront::demo::LifeApp app{\"life-project\"};" "developer application snippet") _require("${readme}" "webfront::demo::LifeAppWithAssets app;" "offline application snippet") _require("${embedded}" "webfront::demo::LifeAppWithAssets app;" "compiled offline application") -foreach(target HelloWorld WebFrontLifeConsole WebFrontLifeDeveloper WebFrontLifeEmbedded) +foreach(target HelloWorld WebFrontLifeConsole WebFrontLifeDeveloper WebFrontLifeEmbedded WebFrontLifeReact) _require("${examples}" "add_executable(${target} " "compiled example stage") if(NOT target STREQUAL "HelloWorld") _require("${readme}" "${target}" "documented Life stage") @@ -70,8 +70,8 @@ foreach(target HelloWorld WebFrontLifeConsole WebFrontLifeDeveloper WebFrontLife endforeach() string(REGEX MATCHALL "add_executable\\(" targets "${examples}") list(LENGTH targets target_count) -if(NOT target_count EQUAL 4) - list(APPEND failures "Only Hello World and the three Life stages should be built") +if(NOT target_count EQUAL 5) + list(APPEND failures "Only Hello World, the three Life stages and the React adapter variant should be built") endif() foreach(command "wf create life" "wf init" "wf install react@19.3.1 react-dom@19.3.1" "wf dev ui/main.tsx" "wf check" "wf test" "wf embed ui/main.tsx --output generated/LifeUI.hpp") _require("${readme}" "${command}" "developer-terminal walkthrough") diff --git a/test/cmake/CheckPrepareReactProject.cmake b/test/cmake/CheckPrepareReactProject.cmake new file mode 100644 index 00000000..e49065cf --- /dev/null +++ b/test/cmake/CheckPrepareReactProject.cmake @@ -0,0 +1,54 @@ +cmake_minimum_required(VERSION 3.31) +if(NOT ROOT OR NOT WORK) + message(FATAL_ERROR "ROOT and WORK are required") +endif() +file(REMOVE_RECURSE "${WORK}") +file(MAKE_DIRECTORY "${WORK}/project") +file(WRITE "${WORK}/project/marker" "preserved until validation succeeds") +set(prepare "${ROOT}/test/cmake/PrepareWfProject.cmake") +set(source "${WORK}/suite") +file(MAKE_DIRECTORY "${source}") +file(COPY "${ROOT}/test/web/suite/webfront.project.json" DESTINATION "${source}") + +function(prepare_project expected diagnostic) + execute_process(COMMAND "${CMAKE_COMMAND}" -DSOURCE=${source} -DPROJECT=${WORK}/project ${ARGN} -P "${prepare}" + RESULT_VARIABLE status OUTPUT_VARIABLE output ERROR_VARIABLE error) + string(REGEX REPLACE "[ \t\r\n]+" " " diagnostic_text "${output}${error}") + if(expected STREQUAL "success") + if(NOT status EQUAL 0) + message(FATAL_ERROR "Project preparation failed: ${output}${error}") + endif() + elseif(status EQUAL 0 OR NOT diagnostic_text MATCHES "${diagnostic}") + message(FATAL_ERROR "Project preparation did not reject the missing input: ${output}${error}") + endif() +endfunction() + +prepare_project(failure "Pass -DLIFE_REACT") +prepare_project(failure "LIFE_REACT does not name an existing file" -DLIFE_REACT=${WORK}/missing.tsx) +if(NOT EXISTS "${WORK}/project/marker") + message(FATAL_ERROR "Invalid inputs removed the existing fixture") +endif() +prepare_project(success "" -DLIFE_REACT=${ROOT}/examples/life/react/main.tsx) +file(SHA256 "${ROOT}/examples/life/react/main.tsx" expected) +file(SHA256 "${WORK}/project/pages/life-react.tsx" actual) +if(NOT actual STREQUAL expected) + message(FATAL_ERROR "Prepared Life entry differs from the maintained example") +endif() +# A generic wf fixture has no Life entry and must still work without LIFE_REACT. +set(source "${ROOT}/test/fixtures/wf-project") +prepare_project(success "") + +execute_process(COMMAND "${CMAKE_COMMAND}" -DBUILD=${WORK}/missing-build -DOUTPUT=${WORK}/pages + -P "${ROOT}/test/cmake/PrepareReactExample.cmake" RESULT_VARIABLE status OUTPUT_VARIABLE output ERROR_VARIABLE error) +string(REGEX REPLACE "[ \t\r\n]+" " " diagnostic_text "${output}${error}") +if(status EQUAL 0 OR NOT diagnostic_text MATCHES "run wf build first") + message(FATAL_ERROR "Missing compiled assets did not fail explicitly: ${output}${error}") +endif() +file(MAKE_DIRECTORY "${WORK}/build/assets") +file(WRITE "${WORK}/build/app.js" "export const compiled = true;\n") +file(WRITE "${WORK}/build/assets/test.txt" "asset") +execute_process(COMMAND "${CMAKE_COMMAND}" -DBUILD=${WORK}/build -DOUTPUT=${WORK}/pages + -P "${ROOT}/test/cmake/PrepareReactExample.cmake" RESULT_VARIABLE status) +if(NOT status EQUAL 0 OR NOT EXISTS "${WORK}/pages/app.js" OR NOT EXISTS "${WORK}/pages/assets/test.txt") + message(FATAL_ERROR "Compiled React assets were not staged in the page tree") +endif() diff --git a/test/cmake/CheckReactPackage.cmake b/test/cmake/CheckReactPackage.cmake new file mode 100644 index 00000000..8ab1a5d8 --- /dev/null +++ b/test/cmake/CheckReactPackage.cmake @@ -0,0 +1,38 @@ +# Verify the archive prepared by wf contains the package's actual maintained sources. +cmake_minimum_required(VERSION 3.31) +file(REMOVE_RECURSE "${WORK}") +file(READ "${ROOT}/js/react/package.json" manifest) +string(JSON package_version GET "${manifest}" version) +set(archive "${PROJECT}/build-react-package/webfront-react-${package_version}.tgz") +include("${ROOT}/cmake/WebFrontBootstrap.cmake") +webfront_file_sri("${archive}" actual_integrity) +file(READ "${PROJECT}/build-react-package/integrity.txt" expected_integrity) +string(STRIP "${expected_integrity}" expected_integrity) +if(NOT actual_integrity STREQUAL expected_integrity) + message(FATAL_ERROR "React package integrity.txt differs from the archive SHA-512") +endif() +file(SHA512 "${archive}" archive_hash) +file(SHA512 "${PROJECT}/build-registry/webfront-react-${package_version}.tgz" registry_hash) +if(NOT archive_hash STREQUAL registry_hash) + message(FATAL_ERROR "React registry tarball differs from wf run react-package") +endif() +file(ARCHIVE_EXTRACT INPUT "${archive}" DESTINATION "${WORK}") +file(GLOB_RECURSE actual_files LIST_DIRECTORIES false RELATIVE "${WORK}" "${WORK}/*") +set(expected_files package/package.json package/index.mjs package/index.d.ts package/README.md package/LICENSE) +list(SORT actual_files) +list(SORT expected_files) +if(NOT actual_files STREQUAL expected_files) + message(FATAL_ERROR "React package file list differs: ${actual_files}") +endif() +foreach(name package.json index.mjs index.d.ts README.md LICENSE) + file(SHA256 "${ROOT}/js/react/${name}" expected) + file(SHA256 "${WORK}/package/${name}" actual) + if(NOT actual STREQUAL expected) + message(FATAL_ERROR "React package differs from sources: ${name}") + endif() +endforeach() +file(SHA256 "${ROOT}/LICENSE" expected) +file(SHA256 "${WORK}/package/LICENSE" actual) +if(NOT actual STREQUAL expected) + message(FATAL_ERROR "React package license differs") +endif() diff --git a/test/cmake/PrepareReactExample.cmake b/test/cmake/PrepareReactExample.cmake new file mode 100644 index 00000000..d9b25a9f --- /dev/null +++ b/test/cmake/PrepareReactExample.cmake @@ -0,0 +1,11 @@ +# Stage wf's documented build output into the browser fixture's ordinary page tree. +cmake_minimum_required(VERSION 3.31) +if(NOT BUILD OR NOT OUTPUT) + message(FATAL_ERROR "BUILD and OUTPUT are required") +endif() +if(NOT EXISTS "${BUILD}/app.js") + message(FATAL_ERROR "React example app.js is missing in ${BUILD}; run wf build first") +endif() +file(REMOVE_RECURSE "${OUTPUT}") +file(MAKE_DIRECTORY "${OUTPUT}") +file(COPY "${BUILD}/" DESTINATION "${OUTPUT}") diff --git a/test/cmake/PrepareSelfBuildProject.cmake b/test/cmake/PrepareSelfBuildProject.cmake index 93fe789d..1656b0e2 100644 --- a/test/cmake/PrepareSelfBuildProject.cmake +++ b/test/cmake/PrepareSelfBuildProject.cmake @@ -7,6 +7,7 @@ file(REMOVE_RECURSE "${PROJECT}") file(MAKE_DIRECTORY "${PROJECT}" "${PROJECT}/include/webfront/system" "${PROJECT}/js/developer") file(COPY "${SOURCE}/LICENSE" DESTINATION "${PROJECT}") +file(COPY "${SOURCE}/js/react" DESTINATION "${PROJECT}/js") file(COPY "${SOURCE}/js/core" DESTINATION "${PROJECT}/js") file(COPY "${SOURCE}/js/developer/webfront.project.json" DESTINATION "${PROJECT}/js/developer") foreach(directory environment scripts tools) diff --git a/test/cmake/PrepareWfProject.cmake b/test/cmake/PrepareWfProject.cmake index ff6e10dc..22bd6d3b 100644 --- a/test/cmake/PrepareWfProject.cmake +++ b/test/cmake/PrepareWfProject.cmake @@ -1,4 +1,32 @@ # Gives the driver tests a fresh copy of the fixture project. # Usage: cmake -DSOURCE= -DPROJECT= -P PrepareWfProject.cmake +cmake_minimum_required(VERSION 3.31) +if(NOT SOURCE OR NOT PROJECT) + message(FATAL_ERROR "SOURCE and PROJECT are required") +endif() +if(NOT IS_DIRECTORY "${SOURCE}") + message(FATAL_ERROR "SOURCE is not a fixture directory: ${SOURCE}") +endif() +if(LIFE_REACT AND (NOT EXISTS "${LIFE_REACT}" OR IS_DIRECTORY "${LIFE_REACT}")) + message(FATAL_ERROR "LIFE_REACT does not name an existing file: ${LIFE_REACT}") +endif() +set(life_react_entry "pages/life-react.tsx") +if(EXISTS "${SOURCE}/webfront.project.json") + file(READ "${SOURCE}/webfront.project.json" manifest) + string(JSON entry ERROR_VARIABLE missing GET "${manifest}" entries life-react) + if(NOT missing) + set(life_react_entry "${entry}") + if(NOT EXISTS "${SOURCE}/${entry}" AND NOT LIFE_REACT) + message(FATAL_ERROR "The Life React entry '${entry}' is missing. Pass -DLIFE_REACT=") + endif() + endif() +endif() +# Validate inputs before replacing an existing prepared fixture. file(REMOVE_RECURSE "${PROJECT}") file(COPY "${SOURCE}/" DESTINATION "${PROJECT}") + +if(LIFE_REACT) + get_filename_component(entry_directory "${PROJECT}/${life_react_entry}" DIRECTORY) + file(MAKE_DIRECTORY "${entry_directory}") + file(COPY_FILE "${LIFE_REACT}" "${PROJECT}/${life_react_entry}") +endif() diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index ca9382cc..ab11de1e 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -25,7 +25,7 @@ endif() set(TESTS_LIST) list(APPEND TESTS_LIST WebKitGTKPolicyTests.cpp ContentPolicyTests.cpp HTTPServerTests.cpp HTTPEncodingTests.cpp GzipExecutorTests.cpp AcceptEncodingTests.cpp GzipTests.cpp ModuleHTTPServerTests.cpp EncodingsTests.cpp WebSocketTests.cpp LoggerTests.cpp MimeTypeTests.cpp) -list(APPEND TESTS_LIST DomDocumentTests.cpp DomBatchTests.cpp JSFunctionTests.cpp TypeErasedFunctionTests.cpp MessagesTests.cpp IndexFSTests.cpp) +list(APPEND TESTS_LIST ReactStoreTests.cpp DomDocumentTests.cpp DomBatchTests.cpp JSFunctionTests.cpp TypeErasedFunctionTests.cpp MessagesTests.cpp IndexFSTests.cpp) list(APPEND TESTS_LIST FileSystemTests.cpp NativeFSTests.cpp) list(APPEND TESTS_LIST DefaultFSTests.cpp StdnetShutdownTests.cpp SafePathTests.cpp UISubscribersTests.cpp) list(APPEND TESTS_LIST WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp) @@ -95,6 +95,10 @@ if(WEBFRONT_USE_MDDLOG) add_test(NAME MddlogHeaderConsumer COMMAND mddlog_header_consumer) endif() +add_test(NAME ReactProjectPreparation COMMAND ${CMAKE_COMMAND} -DROOT=${PROJECT_SOURCE_DIR} + -DWORK=${CMAKE_CURRENT_BINARY_DIR}/react-project-preparation -P ${PROJECT_SOURCE_DIR}/test/cmake/CheckPrepareReactProject.cmake) +set_tests_properties(ReactProjectPreparation PROPERTIES TIMEOUT 30) + # The documented newcomer commands and snippets must keep matching the built examples and CI. add_test(NAME RepositoryLayout COMMAND ${CMAKE_COMMAND} -DROOT=${PROJECT_SOURCE_DIR} -DGIT_EXECUTABLE=${GIT_EXECUTABLE} diff --git a/test/unit/ReactStoreTests.cpp b/test/unit/ReactStoreTests.cpp new file mode 100644 index 00000000..53b1ea45 --- /dev/null +++ b/test/unit/ReactStoreTests.cpp @@ -0,0 +1,208 @@ +#include "InjectableNetworking.hpp" +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +struct Harness { + std::shared_ptr document = std::make_shared(); + std::vector sent; + std::vector timers; + bool fail{}; + webfront::BasicWF app{webfront::WebFrontConfig{.port = "0"}}; + void tick() { + auto completion = std::move(timers.back()); + timers.pop_back(); + completion.complete({}, 0); + } +}; +struct UI { + Harness* harness; + auto domState() const { + return harness->document; + } + auto document() const { + return webfront::dom::Document{*this}; + } + auto resumeAfter(std::chrono::milliseconds delay) const { + REQUIRE(delay == std::chrono::milliseconds(1)); + return webfront::testing::ManualSender([h = harness](auto completion) { + h->timers.push_back(std::move(completion)); + }); + } + auto spawn(webfront::Task task) const { + return harness->app.spawn(std::move(task)); + } + auto jsFunction(std::string_view name) const { + REQUIRE(name == "webfrontReactStores.counter"); + return [h = harness](int value) { + if (h->fail) + throw std::runtime_error("send failed"); + h->sent.push_back(value); + }; + } +}; +} // namespace + +SCENARIO("React stores coalesce a thousand writes into one snapshot per server cycle", "[react]") { + Harness harness; + webfront::react::Store store{UI{&harness}, "counter"}; + auto copy = store; + for (int i = 0; i < 1000; ++i) + copy.set(i); + REQUIRE(harness.sent.empty()); + REQUIRE(harness.timers.size() == 1); + harness.tick(); + REQUIRE(harness.sent == std::vector{999}); + WHEN("an explicit flush precedes the timer") { + store.set(1000); + store.flush(); + harness.tick(); + REQUIRE(harness.sent == std::vector{999, 1000}); + store.set(1001); + harness.tick(); + REQUIRE(harness.sent.back() == 1001); + } + WHEN("the connection closes before the next cycle") { + store.set(1000); + harness.document->close(); + harness.tick(); + REQUIRE(harness.sent.size() == 1); + REQUIRE_FALSE(store.valid()); + REQUIRE_THROWS(store.set(1001)); + } + WHEN("the application shuts down with a pending cycle") { + store.set(1000); + harness.app.shutdown(); + REQUIRE(harness.sent.size() == 1); + } + WHEN("the store closes explicitly") { + store.set(1000); + store.close(); + harness.tick(); + REQUIRE_FALSE(copy.valid()); + REQUIRE(harness.sent.size() == 1); + REQUIRE_THROWS(copy.flush()); + } + WHEN("close releases a self-capturing error handler") { + auto lifetime = std::make_shared(7); + std::weak_ptr observed = lifetime; + store.onError([keep = copy, lifetime](std::exception_ptr) { + CHECK_FALSE(keep.valid()); + CHECK(*lifetime == 7); + }); + lifetime.reset(); + REQUIRE_FALSE(observed.expired()); + store.close(); + REQUIRE(observed.expired()); + } + WHEN("automatic failure releases a self-capturing error handler") { + auto lifetime = std::make_shared(7); + std::weak_ptr observed = lifetime; + unsigned calls{}; + store.onError([keep = copy, lifetime, &calls](std::exception_ptr) { + ++calls; + CHECK_FALSE(keep.valid()); + CHECK(*lifetime == 7); + }); + lifetime.reset(); + harness.fail = true; + store.set(1000); + harness.tick(); + REQUIRE(calls == 1); + REQUIRE(observed.expired()); + } + WHEN("sending the automatic snapshot fails") { + unsigned errors{}; + store.onError([&](std::exception_ptr error) { + ++errors; + REQUIRE_THROWS(std::rethrow_exception(error)); + }); + harness.fail = true; + store.set(1000); + harness.tick(); + REQUIRE(errors == 1); + REQUIRE_FALSE(store.valid()); + } + WHEN("an explicit flush fails before the timer fires") { + unsigned errors{}; + store.onError([&](std::exception_ptr) { + ++errors; + }); + store.set(1000); + harness.fail = true; + REQUIRE_THROWS_AS(store.flush(), std::runtime_error); + REQUIRE(store.valid()); + REQUIRE(errors == 0); + harness.fail = false; + store.flush(); + harness.tick(); + REQUIRE(harness.sent == std::vector{999, 1000}); + } + WHEN("the automatic error callback throws") { + std::vector logs; + const auto enabled = webfront::log::is(webfront::log::Error); + webfront::log::set(webfront::log::Error, true); + auto sink = webfront::log::addSinks([&](std::string_view text) { + logs.emplace_back(text); + }); + auto lifetime = std::make_shared(7); + std::weak_ptr observed = lifetime; + store.onError([keep = copy, lifetime](std::exception_ptr) { + CHECK_FALSE(keep.valid()); + CHECK(*lifetime == 7); + throw std::runtime_error("handler failed"); + }); + lifetime.reset(); + harness.fail = true; + store.set(1000); + harness.tick(); + webfront::log::removeSinks(sink); + webfront::log::set(webfront::log::Error, enabled); + REQUIRE_FALSE(store.valid()); + REQUIRE(logs.size() == 1); + REQUIRE(logs.front().find("React store onError callback threw") != std::string::npos); + REQUIRE(observed.expired()); + } + WHEN("a wrapper is moved while a snapshot is pending") { + store.set(1000); + auto moved = std::move(copy); + REQUIRE_FALSE(copy.valid()); + REQUIRE_THROWS_AS(copy.set(1001), std::runtime_error); + REQUIRE_THROWS_AS(copy.flush(), std::runtime_error); + REQUIRE_THROWS_AS(copy.close(), std::runtime_error); + REQUIRE_THROWS_AS(copy.onError({}), std::runtime_error); + REQUIRE(moved.valid()); + REQUIRE(store.valid()); + harness.tick(); + REQUIRE(harness.sent == std::vector{999, 1000}); + moved.set(1002); + moved.flush(); + harness.tick(); + REQUIRE(harness.sent == std::vector{999, 1000, 1002}); + } + WHEN("another thread attempts to update it") { + bool rejected{}; + std::thread other([&] { + try { + store.set(1000); + } catch (const std::runtime_error&) { + rejected = true; + } + }); + other.join(); + REQUIRE(rejected); + REQUIRE(harness.timers.empty()); + } +} diff --git a/test/web/CMakeLists.txt b/test/web/CMakeLists.txt index 685e14a5..a7c6b74a 100644 --- a/test/web/CMakeLists.txt +++ b/test/web/CMakeLists.txt @@ -1,5 +1,9 @@ add_executable(webtest JasmineTest.cpp) target_link_libraries(webtest PRIVATE WebFront_test_hardening WebFront WebFront_warnings WebFront_options) +if(MSVC) + # The shared browser suite instantiates enough bridge callbacks to exceed standard COFF's section limit. + target_compile_options(webtest PRIVATE /bigobj) +endif() include(Frontends) include("${PROJECT_SOURCE_DIR}/test/cmake/DriverSessions.cmake") @@ -330,6 +334,7 @@ if(_browser_tests_available) if(_webtest_runs) add_test(NAME WebSuiteProject COMMAND ${CMAKE_COMMAND} -DSOURCE=${CMAKE_CURRENT_SOURCE_DIR}/suite -DPROJECT=${_suite_project} + -DLIFE_REACT=${PROJECT_SOURCE_DIR}/examples/life/react/main.tsx -P ${PROJECT_SOURCE_DIR}/test/cmake/PrepareWfProject.cmake) set_tests_properties(WebSuiteProject PROPERTIES FIXTURES_SETUP WebSuiteProject LABELS "web-integration" TIMEOUT 30) add_test(NAME WebSuiteInstall @@ -340,7 +345,23 @@ if(_browser_tests_available) webfront_set_browser_test_properties(WebSuiteInstall "${CMAKE_CURRENT_SOURCE_DIR}" 120) set_tests_properties(WebSuiteInstall PROPERTIES FIXTURES_REQUIRED "WebSuiteProject;TestRegistry" FIXTURES_SETUP WebSuiteInstalled RESOURCE_LOCK "${_suite_project}") - set_tests_properties(${WEBFRONT_FRONTEND_${WEBFRONT_WEBTEST_FRONTEND}_TEST_NAME} PROPERTIES FIXTURES_REQUIRED WebSuiteInstalled) + foreach(action Check Build) + string(TOLOWER "${action}" command) + add_test(NAME ReactAdapter${action} + COMMAND ${_developer_xvfb_prefix} ${CMAKE_COMMAND} -DROOT=${PROJECT_SOURCE_DIR} -DDRIVER=$ + -DPROJECT=${_suite_project} -DWORK=${CMAKE_CURRENT_BINARY_DIR}/wf-driver-work -DENVIRONMENT= -DINTEGRITY= + -DREGISTRY=${_registry} -DPROFILE=${CMAKE_CURRENT_BINARY_DIR}/wf-profiles/ReactAdapter${action} + -DEXPECT_STATUS=0 -DCOMMAND=${command} -P ${PROJECT_SOURCE_DIR}/test/cmake/RunWfDriver.cmake) + webfront_set_browser_test_properties(ReactAdapter${action} "${CMAKE_CURRENT_SOURCE_DIR}" 120) + set_tests_properties(ReactAdapter${action} PROPERTIES FIXTURES_REQUIRED WebSuiteInstalled RESOURCE_LOCK "${_suite_project}") + endforeach() + set_tests_properties(ReactAdapterBuild PROPERTIES FIXTURES_SETUP ReactAdapterBuilt) + add_test(NAME ReactAdapterPages COMMAND ${CMAKE_COMMAND} + -DBUILD=${_suite_project}/.webfront/developer/build -DOUTPUT=${_suite_project}/pages/react-example + -P ${PROJECT_SOURCE_DIR}/test/cmake/PrepareReactExample.cmake) + set_tests_properties(ReactAdapterPages PROPERTIES FIXTURES_REQUIRED ReactAdapterBuilt FIXTURES_SETUP ReactAdapterPages + RESOURCE_LOCK "${_suite_project}" LABELS "web-integration" TIMEOUT 30) + set_tests_properties(${WEBFRONT_FRONTEND_${WEBFRONT_WEBTEST_FRONTEND}_TEST_NAME} PROPERTIES FIXTURES_REQUIRED "WebSuiteInstalled;ReactAdapterPages") endif() # The environment builds itself (#315): the pinned bootstrap environment runs js/developer/scripts on a copy of the @@ -400,6 +421,11 @@ if(_browser_tests_available) REQUIRES SelfBuildProject TestRegistry PROVIDES SelfBuildInstalled) webfront_add_self_build_test(SelfBuild 0 "run|build|build-distribution" OUTPUT "Script build completed" REQUIRES SelfBuildInstalled PROVIDES SelfBuilt) + webfront_add_self_build_test(ReactAdapterPackage 0 "run|react-package" OUTPUT "React adapter:" REQUIRES SelfBuildInstalled + PROVIDES ReactAdapterPackaged) + add_test(NAME ReactAdapterPackageContents COMMAND ${CMAKE_COMMAND} -DROOT=${PROJECT_SOURCE_DIR} -DPROJECT=${_self_project} + -DWORK=${CMAKE_CURRENT_BINARY_DIR}/react-package-check -P ${PROJECT_SOURCE_DIR}/test/cmake/CheckReactPackage.cmake) + set_tests_properties(ReactAdapterPackageContents PROPERTIES FIXTURES_REQUIRED ReactAdapterPackaged LABELS "web-integration" TIMEOUT 30) # Developer specs migrated by #344 remain in the browser under the repository's locked Jasmine. webfront_add_self_build_test(DeveloperSpecs 0 "test|--timeout|240" OUTPUT "PASSED: [0-9]+ specs" TIMEOUT 300 REQUIRES SelfBuildInstalled) diff --git a/test/web/JasmineTest.cpp b/test/web/JasmineTest.cpp index 4b7ac217..8f3b96e3 100644 --- a/test/web/JasmineTest.cpp +++ b/test/web/JasmineTest.cpp @@ -7,6 +7,7 @@ #include #include "../driver/WfDriver.hpp" +#include "../../examples/life/react/LifeReact.hpp" #include "RejectedWebSocketServer.hpp" #include @@ -98,6 +99,7 @@ class BrowserIntegrationTest { rejectedWebSocket.emplace(); registerCallbacks(); registerBitsetCallbacks(); + lifeReactSubscription = demo::installLifeReact(app); } /// The status of `wf test` (the specs), unless the specs passed and C++ did not observe every call they make. @@ -111,6 +113,14 @@ class BrowserIntegrationTest { log::error("DOM handles remained valid after application shutdown"); return 1; } + for (auto& [id, store] : reactStores) { + if (store.valid()) + return 1; + try { + store.set({0, "after shutdown"}); + return 1; + } catch (const std::runtime_error&) { } + } try { shutdownDocument->text("after shutdown"); return 1; @@ -133,6 +143,8 @@ class BrowserIntegrationTest { dom::Node shutdownNode; optional connectedUI; UISubscription uiSubscription; + UISubscription lifeReactSubscription; + std::map>> reactStores; UISubscription closedDomSubscription; std::map closedDocumentRejected; future cppResult; @@ -327,6 +339,23 @@ class BrowserIntegrationTest { webFront->cppFunction("domClosedDocumentRejected", [this](uint32_t id) { return closedDocumentRejected[static_cast(id)]; }); + webFront->cppFunction("reactBurst", [this](TestWF::UI ui) { + auto [it, inserted] = reactStores.try_emplace(ui.id(), ui, "counter"); + for (std::uint32_t i = 0; i < 1000; ++i) + it->second.set({i, "été 🌍"}); + return static_cast(ui.id()); + }); + webFront->cppFunction("reactStoreValid", [this](std::uint32_t id) { + return reactStores.at(static_cast(id)).valid(); + }); + webFront->cppFunction("reactPanel", [this](TestWF::UI ui) { + auto doc = ui.document(); + auto label = doc.text("C++ island"); + doc.island("panel").append(label); + doc.flush(); + documentTexts[ui.id()] = label; + return static_cast(ui.id()); + }); webFront->cppFunction("domDocumentOffThread", [](TestWF::UI ui) { bool rejected = false; std::exception_ptr failure; diff --git a/test/web/registry/build.mjs b/test/web/registry/build.mjs index 90a19349..97f08680 100644 --- a/test/web/registry/build.mjs +++ b/test/web/registry/build.mjs @@ -6,6 +6,7 @@ // test/web/registry-packages.json), kept byte for byte; the synthetic ones are generated. The registry's files go to // build-registry/, next to an integrities.json of every package. import {realPackage, syntheticPackages, registryFiles} from './fixture.mjs'; +import {reactPackage} from '../../../js/developer/scripts/react-package.mjs'; export default async function (context) { if (context.args.length) throw new Error('Usage: wf run test-registry'); @@ -14,6 +15,8 @@ export default async function (context) { if (!archives.length) throw new Error('registry-archives holds no archive'); const packages = []; for (const name of archives) packages.push(await realPackage(await project.read(`registry-archives/${name}`))); + // Preserve exactly the same archive bytes that `wf run react-package` writes. + packages.push(await reactPackage(project)); const {files, integrities} = await registryFiles([...packages, ...syntheticPackages()]); for (const [name, bytes] of files) await project.write(`build-registry/${name}`, bytes); await project.write('build-registry/integrities.json', JSON.stringify(integrities, null, 2) + '\n'); diff --git a/test/web/registry/fixture.mjs b/test/web/registry/fixture.mjs index 7d4cbdce..f9baaa1e 100644 --- a/test/web/registry/fixture.mjs +++ b/test/web/registry/fixture.mjs @@ -2,7 +2,7 @@ // archives (test/web/registry-packages.json, downloaded and verified at configure time) and from synthetic packages for // the edge cases. The test application serves the directory from its own origin, so no test reaches the public registry. // Everything here uses only browser APIs: build.mjs runs it with wf. -import {tar} from '../../../js/developer/tools/archive.mjs'; +import {tar, storedGzip} from '../../../js/developer/tools/archive.mjs'; import {gunzip, readTar} from '../../../js/developer/environment/tarball.mjs'; const encoder = new TextEncoder(); @@ -12,33 +12,6 @@ async function integrity(bytes) { } const decoder = new TextDecoder(); -// The fixture builds the registry that provides fflate, so it cannot depend on it: a gzip stream of stored blocks is -// deterministic and needs no compressor. -const crcTable = Uint32Array.from({length: 256}, (_, n) => { - let c = n; - for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; - return c >>> 0; -}); -function storedGzip(bytes) { - const blocks = Math.max(1, Math.ceil(bytes.length / 0xffff)); - const out = new Uint8Array(10 + bytes.length + 5 * blocks + 8); - const view = new DataView(out.buffer); - out.set([0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 255]); - let at = 10; - for (let block = 0; block < blocks; block++) { - const chunk = bytes.subarray(block * 0xffff, (block + 1) * 0xffff); - out[at++] = block === blocks - 1 ? 1 : 0; - view.setUint16(at, chunk.length, true); - view.setUint16(at + 2, ~chunk.length & 0xffff, true); - out.set(chunk, at + 4); - at += 4 + chunk.length; - } - let crc = 0xffffffff; - for (const byte of bytes) crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8); - view.setUint32(at, (crc ^ 0xffffffff) >>> 0, true); - view.setUint32(at + 4, bytes.length >>> 0, true); - return out; -} const archive = files => storedGzip(tar(new Map([...files].map(([path, bytes]) => [`package/${path}`, bytes])))); // The fixture's versions are plain major.minor.patch numbers. function compareVersions(a, b) { diff --git a/test/web/suite/pages/react-example.html b/test/web/suite/pages/react-example.html new file mode 100644 index 00000000..197d96bb --- /dev/null +++ b/test/web/suite/pages/react-example.html @@ -0,0 +1,21 @@ + +
+ + + diff --git a/test/web/suite/pages/react.html b/test/web/suite/pages/react.html new file mode 100644 index 00000000..23d22ab7 --- /dev/null +++ b/test/web/suite/pages/react.html @@ -0,0 +1,12 @@ + +
+ + diff --git a/test/web/suite/specs/react-specs.mjs b/test/web/suite/specs/react-specs.mjs new file mode 100644 index 00000000..28586e1c --- /dev/null +++ b/test/web/suite/specs/react-specs.mjs @@ -0,0 +1,260 @@ +// The adapter is resolved from the package installed by wf, with development React for StrictMode replay. +import React, {StrictMode, createElement, useLayoutEffect} from 'react'; +import {createRoot} from 'react-dom/client'; +import {flushSync} from 'react-dom'; +import {Island, createStore, useStore} from '@webfront/react'; + +const until = async predicate => { + const deadline = performance.now() + 5000; + while (!await predicate()) { + if (performance.now() > deadline) throw new Error('React adapter condition timed out'); + await new Promise(resolve => setTimeout(resolve, 5)); + } +}; +async function page() { + const frame = document.createElement('iframe'); + frame.src = '/react.html'; + document.body.appendChild(frame); + await until(() => frame.contentWindow?.dom); + await frame.contentWindow.webFront.ready; + return frame; +} +const call = (frame, name, ...args) => frame.contentWindow.webFront.cppFunction(name)(...args); + +describe('Optional wf React adapter', () => { + it('caches snapshots, unsubscribes, disposes and rejects duplicate names', () => { + const store = createStore('local', [0]); + try { + expect(store.getSnapshot()).toBe(store.getSnapshot()); + expect(() => createStore('local', 0)).toThrow(); + expect(() => createStore('invalid.name', 0)).toThrow(); + let notifications = 0; + const off = store.subscribe(() => ++notifications); + const next = [1]; + globalThis.webfrontReactStores.local(next); + globalThis.webfrontReactStores.local(next); + expect(store.getSnapshot()).toBe(next); + expect(notifications).toBe(1); + off(); + globalThis.webfrontReactStores.local([2]); + expect(notifications).toBe(1); + } finally { store.dispose(); } + expect(Object.hasOwn(globalThis.webfrontReactStores, 'local')).toBeFalse(); + expect(() => store.subscribe(() => {})).toThrow(); + createStore('local', 0).dispose(); + }); + + it('isolates throwing subscribers, including failures in diagnostic logging', () => { + const store = createStore('isolated', 0); + const failure = new Error('subscriber failed'); + const later = jasmine.createSpy('later subscriber'); + const diagnostic = spyOn(console, 'error'); + store.subscribe(() => { throw failure; }); + store.subscribe(later); + try { + expect(() => globalThis.webfrontReactStores.isolated(1)).not.toThrow(); + expect(later).toHaveBeenCalledTimes(1); + expect(diagnostic).toHaveBeenCalledWith('WebFront React store subscriber failed', failure); + diagnostic.and.throwError('logging failed'); + expect(() => globalThis.webfrontReactStores.isolated(2)).not.toThrow(); + expect(later).toHaveBeenCalledTimes(2); + expect(store.getSnapshot()).toBe(2); + } finally { store.dispose(); } + }); + + it('contains an unexpected synchronous island release error and forgets the local loan', async () => { + const container = document.body.appendChild(document.createElement('div')); + const failure = new Error('release failed'); + const diagnostic = spyOn(console, 'error'); + const dom = {island: () => () => { throw failure; }}; + let root = createRoot(container); + try { + flushSync(() => root.render(createElement(Island, {dom, name: 'throwing-panel'}))); + root.unmount(); root = null; + await Promise.resolve(); + expect(diagnostic).toHaveBeenCalledWith('WebFront React island release failed', failure); + root = createRoot(container); + flushSync(() => root.render(createElement(Island, {dom, name: 'throwing-panel'}))); + root.unmount(); root = null; + await Promise.resolve(); + } finally { + root?.unmount(); + await Promise.resolve(); + container.remove(); + } + }); + + it('unmounts a real island after its bridge disconnects without an unhandled error', async () => { + const frame = await page(), pageWindow = frame.contentWindow; + const dom = pageWindow.dom; + const root = createRoot(frame.contentDocument.getElementById('root')); + const diagnostics = [], errors = []; + const previous = pageWindow.console.error; + pageWindow.console.error = (...args) => diagnostics.push(args); + const unexpected = event => { errors.push(event.type); event.preventDefault(); }; + pageWindow.addEventListener('error', unexpected); + pageWindow.addEventListener('unhandledrejection', unexpected); + let unmounted = false; + try { + flushSync(() => root.render(createElement(Island, {dom, name: 'panel'}))); + await dom.connect(); + await call(frame, 'reactPanel'); + await until(() => frame.contentDocument.getElementById('root').textContent === 'C++ island'); + await pageWindow.disconnectBridge(); + root.unmount(); unmounted = true; + await until(() => diagnostics.some(args => args[0] === 'WebFront DOM island revocation failed')); + await new Promise(resolve => setTimeout(resolve, 0)); + expect(errors).toEqual([]); + } finally { + if (!unmounted) root.unmount(); + await Promise.resolve(); + pageWindow.console.error = previous; + pageWindow.removeEventListener('error', unexpected); + pageWindow.removeEventListener('unhandledrejection', unexpected); + frame.remove(); + } + }); + + it('receives one snapshot and one React commit for 1000 C++ updates, independently per browser', async () => { + const first = await page(), second = await page(); + const store = createStore('counter', [0, 'initial'], {target: first.contentWindow}); + const other = createStore('counter', [0, 'other'], {target: second.contentWindow}); + const root = createRoot(first.contentDocument.getElementById('root')); + let commits = 0, messages = 0; + const off = store.subscribe(() => ++messages); + function View() { + const [count, text] = useStore(store); + useLayoutEffect(() => { ++commits; }); + return createElement('output', null, `${count} ${text}`); + } + try { + flushSync(() => root.render(createElement(View))); + const baseline = commits; + const firstId = await call(first, 'reactBurst'); + await until(() => first.contentDocument.querySelector('output')?.textContent === '999 été 🌍'); + expect(messages).toBe(1); + expect(commits - baseline).toBe(1); + expect(other.getSnapshot()).toEqual([0, 'other']); + await call(second, 'reactBurst'); + await until(() => other.getSnapshot()[0] === 999); + expect(other.getSnapshot()).toEqual([999, 'été 🌍']); + first.remove(); + await until(async () => !await call(second, 'reactStoreValid', firstId)); + } finally { + root.unmount(); off(); store.dispose(); other.dispose(); first.remove(); second.remove(); + } + }); + + it('preserves C++ children through StrictMode effect replay and parent renders; revokes on real unmount', async () => { + const frame = await page(), dom = frame.contentWindow.dom; + const root = createRoot(frame.contentDocument.getElementById('root')); + let mounts = 0, cleanups = 0, unmounted = false; + function View({version}) { + useLayoutEffect(() => { ++mounts; return () => ++cleanups; }, []); + return createElement('section', {'data-version': version}, createElement(Island, {dom, name: 'panel'})); + } + const render = version => flushSync(() => root.render(createElement(StrictMode, null, createElement(View, {version})))); + try { + render(0); + await Promise.resolve(); + // This assertion proves development StrictMode actually replayed the effects. + expect(mounts).toBe(2); + expect(cleanups).toBe(1); + await dom.connect(); + const id = await call(frame, 'reactPanel'); + expect(await call(frame, 'domDocumentNodeValid', id)).toBeTrue(); + await until(() => frame.contentDocument.querySelector('section div')?.textContent === 'C++ island'); + const text = frame.contentDocument.querySelector('section div').firstChild; + render(1); + expect(frame.contentDocument.querySelector('section div').firstChild).toBe(text); + root.unmount(); + unmounted = true; + // Observe the public C++ handle becoming invalid after the page returns its loan. + await until(async () => !await call(frame, 'domDocumentNodeValid', id)); + const freshRoot = createRoot(frame.contentDocument.getElementById('root')); + try { + flushSync(() => freshRoot.render(createElement(Island, {dom, name: 'panel'}))); + await call(frame, 'reactPanel'); + await until(() => frame.contentDocument.getElementById('root').textContent === 'C++ island'); + } finally { freshRoot.unmount(); await Promise.resolve(); } + } finally { + if (!unmounted) root.unmount(); + frame.remove(); + } + }); + + async function exampleFrame(blockMount = false) { + const frame = document.createElement('iframe'); + const loaded = new Promise((resolve, reject) => { frame.onload = resolve; frame.onerror = reject; }); + frame.src = '/react-example.html' + (blockMount ? '?block-mount' : ''); + document.body.appendChild(frame); + await loaded; + return frame; + } + + it('ignores canvas clicks until the maintained example has acknowledged C++ startup', async () => { + const frame = await exampleFrame(); + try { + const doc = frame.contentDocument, page = frame.contentWindow; + await until(() => page.finishStart && doc.querySelector('canvas')); + const canvas = doc.querySelector('canvas'); + expect(canvas.getAttribute('aria-disabled')).toBe('true'); + const click = () => { + const rect = canvas.getBoundingClientRect(); + canvas.dispatchEvent(new page.MouseEvent('click', {bubbles: true, clientX: rect.left + 6, clientY: rect.top + 6})); + }; + click(); + expect(page.toggleCalls).toBe(0); + const earlyError = await call(frame, 'life.react.toggle', 0).then(() => '', error => String(error.message)); + expect(earlyError).toContain('Life React has not started'); + page.finishStart(); + await until(() => canvas.getAttribute('aria-disabled') === 'false'); + click(); + await until(() => doc.querySelector('[data-testid="react-status"]').textContent.includes('6 living cells')); + // One direct pre-start probe above, then exactly one accepted UI click. + expect(page.toggleCalls).toBe(2); + expect(doc.querySelector('[role="alert"]').textContent).toBe(''); + } finally { frame.remove(); } + }); + + it('reports a bounded startup failure when the maintained example cannot observe its island', async () => { + const frame = await exampleFrame(true); + try { + const doc = frame.contentDocument; + await until(() => !!doc.querySelector('canvas')); + // Startup itself has a five-second limit, independently of this test's watchdog. + const deadline = performance.now() + 8000; + while (!doc.body.textContent.includes('Life panel did not mount within 5 seconds')) { + if (performance.now() >= deadline) throw new Error('Life startup did not fail within its bound'); + await new Promise(resolve => setTimeout(resolve, 20)); + } + expect(frame.contentWindow.finishStart).toBeUndefined(); + expect(Object.hasOwn(frame.contentWindow.webfrontReactStores, 'life')).toBeFalse(); + } finally { frame.remove(); } + }, 10000); + + it('runs the maintained Game of Life C++ panel inside React and reads its coalesced store', async () => { + const frame = await page(), dom = frame.contentWindow.dom; + const store = createStore('life', [new Uint8Array(128), 0, 0], {target: frame.contentWindow}); + const root = createRoot(frame.contentDocument.getElementById('root')); + function Life() { + const [cells, generation, population] = useStore(store); + return createElement('main', null, createElement('output', null, `${generation}:${population}:${cells.length}`), + createElement(Island, {dom, name: 'life-panel'})); + } + try { + flushSync(() => root.render(createElement(StrictMode, null, createElement(Life)))); + await dom.connect(); + await call(frame, 'life.react.start'); + const doc = frame.contentDocument; + await until(() => doc.querySelector('output').textContent === '0:5:128' && doc.querySelector('button')); + const button = doc.querySelector('button'); + button.click(); + await until(() => doc.querySelector('output').textContent === '1:5:128'); + expect(doc.querySelector('p').textContent).toBe('Generation 1 · 5 living cells'); + expect(doc.querySelector('button')).toBe(button); + await call(frame, 'life.react.toggle', 1023); + await until(() => doc.querySelector('output').textContent === '0:6:128'); + } finally { root.unmount(); store.dispose(); frame.remove(); } + }, 10000); // Several bounded bridge waits share this scenario's watchdog. +}); diff --git a/test/web/suite/specs/webfront-specs.mjs b/test/web/suite/specs/webfront-specs.mjs index af326afc..0b0ba6fb 100644 --- a/test/web/suite/specs/webfront-specs.mjs +++ b/test/web/suite/specs/webfront-specs.mjs @@ -1,3 +1,4 @@ +import './react-specs.mjs'; import './fallback-specs.mjs'; import './dom-document-specs.mjs'; import './content-policy-specs.mjs'; diff --git a/test/web/suite/tsconfig.json b/test/web/suite/tsconfig.json new file mode 100644 index 00000000..90b4a00f --- /dev/null +++ b/test/web/suite/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "jsx": "react-jsx", + "strict": true, + "noEmit": true, + "lib": [ + "ES2022", + "DOM", + "DOM.Iterable" + ], + "allowSyntheticDefaultImports": true + }, + "files": [ + "types/react.tsx", + "pages/life-react.tsx" + ] +} diff --git a/test/web/suite/types/react.tsx b/test/web/suite/types/react.tsx new file mode 100644 index 00000000..c30e323a --- /dev/null +++ b/test/web/suite/types/react.tsx @@ -0,0 +1,15 @@ +import React from 'react'; +import {Island, createStore, useStore, type DomInterpreter} from '@webfront/react'; +const store = createStore<[number, string]>('typed', [0, 'initial']); +declare const dom: DomInterpreter; +export function Panel() { + const [count, label] = useStore(store); + // @ts-expect-error -- tuple fields retain their types + const wrong: string = count; + return
{label}: {count}
; +} +// @ts-expect-error -- C++ owns the children +const children = forbidden; +// @ts-expect-error -- HTML cannot bypass the DOM ownership boundary +const html = ; +store.dispose(); diff --git a/test/web/suite/webfront.project.json b/test/web/suite/webfront.project.json index 9a1a45ac..bdbc85d2 100644 --- a/test/web/suite/webfront.project.json +++ b/test/web/suite/webfront.project.json @@ -2,6 +2,21 @@ "format": 1, "name": "webfront-browser-tests", "version": "0.1.0", - "dependencies": {"jasmine-core": "7.0.2"}, - "test": {"specs": ["specs/webfront-specs.mjs"]} + "dependencies": { + "jasmine-core": "7.0.2", + "react": "19.3.1", + "react-dom": "19.3.1", + "@webfront/react": "0.1.0", + "typescript": "5.9.3", + "@types/react": "19.3.0", + "@types/react-dom": "19.3.0" + }, + "test": { + "specs": [ + "specs/webfront-specs.mjs" + ] + }, + "entries": { + "life-react": "pages/life-react.tsx" + } }