diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 62a3c049..51868d51 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -30,6 +30,7 @@ these entries stays in the GitHub releases and the Git history. - First measurements of image streams to the page: raw frames, JPEG and WebCodecs availability under CEF and WebKitGTK (#769, `docs/IMAGE_STREAMS.md`). - Open an embedded window maximized, full screen, without a frame or with a minimum size (`WindowOptions`), on WebKitGTK and CEF (#764, `docs/FRONTENDS.md`). - `wf dev` applies a change of the stylesheet alone without reloading the page, once an environment with it is published (#763, ADR-014). +- `wf dev` replaces modules in place, keeping the page's state and its connection: React Fast Refresh and `import.meta.hot`, with a full reload when neither applies; the Life React component moved to `Life.tsx`. In the sources of environment 1.3.2, not yet published (#763, ADR-014, `docs/DEVELOPER_ENVIRONMENT.md`). - Check your pages for accessibility in `wf test` with axe-core: a guide says how, and the forms generated from C++ and the fallback page are checked in CI (#768, `docs/ACCESSIBILITY.md`). - Fail a spec on an accessibility violation with `await expectAsync(document).toBeAccessible()` once `axe-core` is locked; the `app` and `life` starters carry such a spec (environment 1.3.2, not yet published, #768, `docs/ACCESSIBILITY.md`). - Use the developer terminal and the inspectors with the keyboard alone: Shift+Tab leaves the terminal, Escape closes an inspector window and gives the focus back; the terminal supports screen readers (environment 1.3.2, #768). diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index c3d1c80e..28a8ef4d 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -16,7 +16,7 @@ commands of the terminal operate on it: | `wf init`, `wf create ` | write the manifest; copy a starter (`app` or `life`, not your project's name) into a new directory | | `wf help [command\|agents]` | list the commands, describe one, or print the sequence for an agent | | `wf install`, `wf restore` | resolve, download and lock packages; rebuild or verify the cache from the lock | -| `wf dev`, `wf build`, `wf preview` | rebuild and reload the preview on every change; build once; preview once | +| `wf dev`, `wf build`, `wf preview` | rebuild and update the preview on every change; build once; preview once | | `wf check` | type-check with the locked TypeScript compiler | | `wf test` | run Jasmine specs in the application's window | | `wf run`, `wf exec` | run a manifest script or a package's executable entry | @@ -783,11 +783,50 @@ input, read in 256 KiB chunks; each compilation has a 120 s deadline. Polling ne another poll. Large projects can hit these explicit limits. An edit made during a build is detected by the next poll; polling can miss a change that is reverted completely between reads. -When a build differs from the one shown by its stylesheet only (`app.css`), the preview does not reload: the new -stylesheet is loaded into the document, which keeps its state, its bridge and its `UI`. JavaScript modules have no hot -replacement: any other change reloads the page. +### Hot replacement + +`wf dev` changes a running preview without reloading it when it can. The page keeps its state, its bridge and its +`UI` (same `ui.id()`), so C++ stores, watches and per-browser sessions are not reset. + +- **Stylesheet.** When a build differs by `app.css` only, the new stylesheet is loaded into the document. +- **React components.** A project that bundles `react-dom` is previewed with React's development build and + [Fast Refresh](https://react.dev/learn/fast-refresh): editing a module whose exports are all components renders them + again, keeping their local state (a change of the hooks resets that component). Declare components at the top level + of a module that exports nothing else (types aside), as `examples/life/react/Life.tsx` does; the entry that calls + `createRoot` accepts no update. A component Fast Refresh does not register (anonymous, re-exported from another + module, in a `.cjs` file or a source its transform refuses) does not count: such a module accepts nothing. +- **`import.meta.hot`.** Any other module can accept its own updates: + + ```ts + if (import.meta.hot) { + import.meta.hot.dispose(data => { data.count = count; }); // data is the next version's import.meta.hot.data + import.meta.hot.accept(next => { /* the new exports of this module */ }); + } + ``` + + `data`, `accept([callback])`, `dispose(callback)` and `invalidate()` are all there is: a module cannot accept + updates of its dependencies. As elsewhere, the modules that imported it keep the former exports. Declare the type for + `wf check`, since the environment provides none: `interface ImportMeta { readonly hot?: any }` in a `.d.ts` file. + +An update runs the changed modules again, then their importers up to the first that accepts or is a module of +components. The page is reloaded instead, with `Full reload: ` in the terminal, when a path reaches the entry or a module +nothing imports without being accepted, when an import cycle reaches no module that accepts, when a module of components starts exporting anything else, when a new version throws while it +runs or calls `invalidate()`, and when the imported packages, the lock, the entry or a copied asset changed. An error +thrown later, while React renders, is React's: correct the source and the next update renders again. + +A project with neither `react-dom` nor `import.meta.hot` is previewed as `wf build` bundles it and reloads on every +change other than the stylesheet. So is a project that the module registry cannot link (an `import()` of one of its own +modules, or of a package, by a literal name; a top-level `await`): the terminal says `No hot update: `. + +A hot preview differs from a build: project modules are not minified or tree-shaken, packages and +`process.env.NODE_ENV` are those of development, and modules run through a registry, not as one ES module. Check +behaviour that depends on it with `wf preview`. Nothing of this reaches `wf build`, `wf preview`, `wf test` or +`wf embed`, where `import.meta.hot` is `undefined`. + +Hot replacement is in the sources of environment 1.3.2, which is not published: the released environment reloads the +page on every change. -Only a successful build and publication reload the preview, replacing its session history entry. A build +Only a successful build and publication update the preview; a reload replaces its session history entry. A build error leaves its last successful files and running document intact. Diagnostics (`file:line:column`, with one-based line and column numbers) stream to the terminal and appear as a text overlay in the preview. Fixing the source resumes rebuilding and clears the overlay. An interruption ends it with exit code 130, terminates @@ -1116,7 +1155,7 @@ WKWebView and all 14 Linux CEF/Xvfb cases with both GCC and Clang in The packed 0.3.0 version passes WKWebView and all 14 GCC CEF/Xvfb cases in [run 39490581423](https://github.com/ambroise-leclerc/WebFront/actions/runs/39490581423). For Linux, select CEF and Xvfb instead; the same developer tests use the selected test frontend. -`DeveloperBrowserIntegration` (the application part: starter, build, `wf dev`, Life preview, embedding) and `DeveloperBrowserIntegration-scripts`, `-typescript`, `-jasmine`, `-terminal` and `-workspace` (the page layout: first launch, launch on an existing interface, floating terminal and its session) exercise, in parallel and each from its own project, the real WASM compiler, local registry, `wf test` under the locked jasmine-core (pass, fail, pending, asynchronous failures, pattern, time limit, interruption, non-interactive report to C++), build without navigation, incremental dev reload/error/recovery/interruption, keyboard copy and paste in the terminal (CEF), the Life preview, C++ generation/animation and repeatable header generation. The developer journey (`Journey*`) then +`DeveloperBrowserIntegration` (the application part: starter, build, `wf dev`, Life preview, embedding) and `DeveloperBrowserIntegration-scripts`, `-typescript`, `-jasmine`, `-terminal` and `-workspace` (the page layout: first launch, launch on an existing interface, floating terminal and its session) and `-hot` (hot replacement with Life React) exercise, in parallel and each from its own project, the real WASM compiler, local registry, `wf test` under the locked jasmine-core (pass, fail, pending, asynchronous failures, pattern, time limit, interruption, non-interactive report to C++), build without navigation, incremental dev reload/error/recovery/interruption, keyboard copy and paste in the terminal (CEF), the Life preview, C++ generation/animation and repeatable header generation. The developer journey (`Journey*`) then builds the header that its own `wf embed` generated and runs `JourneyEmbeddedRun` from an empty working directory with no developer callbacks. Deadline and grace-period regressions advance a scoped clock instead of sleeping for seconds; Worker startup, diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index 9e68f166..a3bab902 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -184,6 +184,7 @@ are retained for investigation; diagnostics alone do not establish a correction. encoding; the first request of a connection has no read timeout. WebSocket connections remain open. Accepted stdnet sockets enable `TCP_NODELAY`. Gzip fallback has bounded decoding, cache retention and worker admission; reads from filesystem providers remain synchronous on the I/O context. See [HTTP assets](HTTP_ASSETS.md). +- Hot replacement in `wf dev` (React Fast Refresh, `import.meta.hot`) is exercised under CEF by the browser suite with React 19.3.1; it is in the sources of environment 1.3.2, not yet published. A hot preview is a development build run through a module registry, not the bundle `wf build` makes; literal dynamic imports of bundled modules and top-level `await` are previewed with a full reload. - The developer environment and `NativeDebugFS` are trusted development facilities, not sandboxes. Manifest permissions bound only the scripts' `context` API. Only browser packages install; installation scripts and native add-ons do not run. The [content policy](CONTENT_POLICY.md) diff --git a/docs/REACT.md b/docs/REACT.md index 0d104201..62964467 100644 --- a/docs/REACT.md +++ b/docs/REACT.md @@ -78,17 +78,19 @@ simulation, released on disconnect. The original Life starter remains available. Build the `WebFrontLifeReact` CMake target. The application only creates an empty project directory when it is missing (without argument `./life-project`); -it does not copy the example's sources. Use a new directory, so that no existing project is touched: `mkdir` fails if it exists and `cp -n` never overwrites a file. Copy `main.tsx` and +it does not copy the example's sources. Use a new directory, so that no existing project is touched: `mkdir` fails if it exists and `cp -n` never overwrites a file. Copy `main.tsx`, `Life.tsx` and `webfront.project.json` from `examples/life/react/` into that directory first, then start the application: ```sh mkdir life-react-project -cp -n examples/life/react/main.tsx examples/life/react/webfront.project.json life-react-project/ +cp -n examples/life/react/main.tsx examples/life/react/Life.tsx examples/life/react/webfront.project.json life-react-project/ ./build/examples/WebFrontLifeReact life-react-project ``` -In its terminal, run `wf install`, then `wf preview`. The configured registry must +In its terminal, run `wf install`, then `wf preview` (or `wf dev`: editing the rendering in +`Life.tsx` then keeps the grid, the generation and the connection, see +[hot replacement](DEVELOPER_ENVIRONMENT.md#hot-replacement); `main.tsx` only starts the page, so a change of it reloads). The configured registry must carry `@webfront/react@0.2.0` and its dependency `@webfront/store@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`; diff --git a/docs/adr/ADR-014-construction-javascript-dans-le-browser.md b/docs/adr/ADR-014-construction-javascript-dans-le-browser.md index 77e29191..5cbf6c92 100644 --- a/docs/adr/ADR-014-construction-javascript-dans-le-browser.md +++ b/docs/adr/ADR-014-construction-javascript-dans-le-browser.md @@ -7,6 +7,8 @@ | 0.1 | 2026-10-20 | Proposée | Ambroise Leclerc | Proposition et première implémentation du résolveur npm et du compilateur navigateur. | À renseigner après intégration. | | 0.2 | 2026-10-22 | Proposée | Ambroise Leclerc | Alignement sur ADR-016 : la proposition devient la base de l'architecture ; preuves multiplateformes manquantes listées. | [404fed2](https://github.com/ambroise-leclerc/WebFront/commit/404fed2c2145d4faba8efee035e10522ff87a91f) | | 1.0 | 2026-10-24 | Acceptée | Ambroise Leclerc | Qualification multiplateforme du parcours développeur (#316) : la proposition est acceptée. | [#348](https://github.com/ambroise-leclerc/WebFront/pull/348) | +| 1.1 | 2026-12-05 | Proposée | Ambroise Leclerc | `wf dev` remplace la feuille de style seule sans recharger la page (#763). | [e1bc438](https://github.com/ambroise-leclerc/WebFront/commit/e1bc4381) | +| 1.2 | 2026-12-06 | Proposée | Ambroise Leclerc | Remplacement à chaud des modules en développement : graphe de modules, canal de mise à jour, React Fast Refresh, `import.meta.hot` et limites (#763). | Branche `763-hmr` | ## Statut et date @@ -47,6 +49,33 @@ processus C++ de compilation ou shell n'est lancé. La transformation TS n'effec Elle est **Acceptée** depuis les preuves de #316 (voir le statut). Les providers et composants historiques évoqués ici suivent la trajectoire de retrait de l'ADR-016. +## Remplacement à chaud des modules (1.1 et 1.2, développement seulement) + +`wf dev`, et lui seul, met à jour l'aperçu sans le recharger, pour que le document, le pont et son `UI` demeurent. + +- **Feuille de style.** Si seul `app.css` change, la nouvelle feuille est chargée dans le document. +- **Aperçus concernés.** Ceux qui incluent `react-dom` ou utilisent `import.meta.hot`. Les autres restent le bundle + ordinaire, rechargé à chaque changement. +- **Graphe.** Le build esbuild ordinaire reste exécuté d'abord : il donne les diagnostics, le CSS, les ressources et, + par son `metafile`, le graphe résolu. Chaque module du projet est ensuite transformé seul en une fabrique CommonJS + d'un registre, retransformé uniquement quand sa source change ; les paquets importés forment un seul script, reconstruit + quand leurs entrées ou le lock changent. Aucune seconde résolution d'imports n'est écrite. +- **Canal.** Le même `app.js` publié contient le registre et tous les modules ; une publication y joint `update.js` + avec les seuls modules modifiés, que la boucle charge comme script dans le document affiché (même origine, sans + `eval`). Aucune connexion ni fonction C++ nouvelle. +- **Frontières.** Un module accepte par `import.meta.hot.accept()` (lui-même seulement ; `dispose`, `data`, + `invalidate`) ou parce que tous ses exports sont des composants React. Sinon la mise à jour remonte vers ses + importateurs ; sans frontière, ou en cas d'échec, la page est rechargée et la raison écrite. +- **React Fast Refresh.** `react-refresh` et la transformation Babel (`@babel/standalone`) sont verrouillés dans le + lock de l'environnement, servis par lui, la transformation n'étant téléchargée que pour un projet React. + `build`, `preview`, `test` et `embed` ne les incluent pas et définissent `import.meta.hot` comme `undefined`. +- **Limites.** Aperçu en mode développement, modules du projet non minifiés ; pas d'`import()` littéral d'un module + groupé ni d'`await` de premier niveau (bundle ordinaire dans ce cas) ; pas d'`accept` des dépendances ni de liaisons + ES vivantes vers les anciens importateurs. Ce n'est pas la sémantique d'un build : `wf preview` reste la référence. +- **Alternatives écartées.** Une transformation Refresh écrite à la main ou par expressions régulières (signatures des + hooks incertaines) ; un serveur de modules ES natifs (une requête par module et une seconde résolution des paquets) ; + Babel pour tous les projets (poids sans utilité). + ## Alternatives et conséquences - Un service distant de bundling introduirait une dépendance de construction externe et un autre diff --git a/docs/adr/README.md b/docs/adr/README.md index 9db79d01..2da82ce3 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -56,7 +56,7 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | [ADR-011](ADR-011-diagnostics-optionnels.md) | Confining mddlog behind an optional diagnostics façade | Accepted | 2026-10-01 | 1.2 — 2026-10-02 | | [ADR-012](ADR-012-preuves-et-tests.md) | Demonstrating contracts through deterministic tests and browser integration | Accepted | 2020-04-19 | 1.9 — 2026-11-25 | | [ADR-013](ADR-013-bootstrap-developpeur-a-la-demande.md) | Bootstrapping a downloaded developer environment | Accepted | 2026-10-20 | 1.0 — 2026-10-24 | -| [ADR-014](ADR-014-construction-javascript-dans-le-browser.md) | Resolving npm dependencies and building inside the browser | Accepted through 1.0; 1.1 proposed | 2026-10-20 | 1.1 — 2026-12-05 | +| [ADR-014](ADR-014-construction-javascript-dans-le-browser.md) | Resolving npm dependencies and building inside the browser | Accepted through 1.0; 1.1 and 1.2 proposed | 2026-10-20 | 1.2 — 2026-12-06 | | [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.8 — 2026-11-28 | | [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 | diff --git a/examples/life/react/Life.tsx b/examples/life/react/Life.tsx new file mode 100644 index 00000000..4daa5697 --- /dev/null +++ b/examples/life/react/Life.tsx @@ -0,0 +1,56 @@ +import React, {useEffect, useRef, useState} from 'react'; +import {Island, useStore, type DomInterpreter, type Store} from '@webfront/react'; + +// The live cells as bits, the generation and the population, published by C++. +export type Board = [Uint8Array, number, number]; + +export function Life({started, store, toggle, dom}: { + started: boolean; + store: Store; + toggle: (index: number) => void; + dom: DomInterpreter; +}) { + const [cells, generation, population] = useStore(store); + const [cursor, setCursor] = useState(0); + // The live region speaks once the keyboard is used: the chosen cell and its state, again when C++ changes it. + const [keyboard, setKeyboard] = useState(false); + const alive = (cells[cursor >> 3] & (1 << (cursor & 7))) !== 0; + const said = keyboard ? `Row ${(cursor >> 5) + 1}, column ${cursor % 32 + 1}: ${alive ? 'alive' : 'dead'}` : ''; + 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); + } + context.strokeStyle = '#ffd27d'; + context.strokeRect((cursor % 32) * 12 + .5, (cursor >> 5) * 12 + .5, 10, 10); + }, [cells, cursor]); + return
+

Game of Life · React + C++ island

+

Generation {generation} · {population} living cells

+ { + if (event.ctrlKey || event.altKey || event.metaKey) return; + const steps: Record = {ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1]}; + if (Object.hasOwn(steps, event.key)) { + const [dx, dy] = steps[event.key]; + setCursor(((cursor >> 5) + dy + 32) % 32 * 32 + (cursor % 32 + dx + 32) % 32); + } else if (started && (event.key === ' ' || event.key === 'Enter')) toggle(cursor); + else return; + event.preventDefault(); + setKeyboard(true); + }} + onClick={event => { + 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); + toggle(y * 32 + x); + }}/> + +

{said}

+
; +} diff --git a/examples/life/react/LifeReact.cpp b/examples/life/react/LifeReact.cpp index 8e11417a..f7afe830 100644 --- a/examples/life/react/LifeReact.cpp +++ b/examples/life/react/LifeReact.cpp @@ -24,7 +24,7 @@ int main(int argc, char** argv) { std::cerr << "Usage: WebFrontLifeReact [--port ] []\n" "Without argument the project is ./" << webfront::demo::LifeDeveloperOptions::defaultProject - << ", created empty when missing: copy main.tsx and webfront.project.json from examples/life/react/ into it first.\n"; + << ", created empty when missing: copy main.tsx, Life.tsx and webfront.project.json from examples/life/react/ into it first.\n"; return 2; } try { diff --git a/examples/life/react/main.tsx b/examples/life/react/main.tsx index ea791c6d..dd024420 100644 --- a/examples/life/react/main.tsx +++ b/examples/life/react/main.tsx @@ -1,6 +1,8 @@ -import React, {StrictMode, useEffect, useRef, useState} from 'react'; +import React, {StrictMode} from 'react'; import {createRoot} from 'react-dom/client'; -import {Island, createStore, useStore} from '@webfront/react'; +import {createStore} from '@webfront/react'; +// The component has its own module: `wf dev` replaces it in place (Fast Refresh), keeping the store and the connection. +import {Life, type Board} from './Life'; // The optional interpreter is served by WebFront, not bundled into the adapter. const interpreterUrl = '/webfront-dom.mjs'; @@ -14,57 +16,13 @@ declare const webFront: { async function main() { const {installDomInterpreter} = await import(interpreterUrl); const dom = installDomInterpreter(webFront); - const store = createStore<[Uint8Array, number, number]>('life', [new Uint8Array(128), 0, 0]); + const store = createStore('life', [new Uint8Array(128), 0, 0]); const toggle = (index: number) => void webFront.cppFunction('life.react.toggle')(index).catch(showError); - function Life({started}: {started: boolean}) { - const [cells, generation, population] = useStore(store); - const [cursor, setCursor] = useState(0); - // The live region speaks once the keyboard is used: the chosen cell and its state, again when C++ changes it. - const [keyboard, setKeyboard] = useState(false); - const alive = (cells[cursor >> 3] & (1 << (cursor & 7))) !== 0; - const said = keyboard ? `Row ${(cursor >> 5) + 1}, column ${cursor % 32 + 1}: ${alive ? 'alive' : 'dead'}` : ''; - 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); - } - context.strokeStyle = '#ffd27d'; - context.strokeRect((cursor % 32) * 12 + .5, (cursor >> 5) * 12 + .5, 10, 10); - }, [cells, cursor]); - return
-

Game of Life · React + C++ island

-

Generation {generation} · {population} living cells

- { - if (event.ctrlKey || event.altKey || event.metaKey) return; - const steps: Record = {ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1]}; - if (Object.hasOwn(steps, event.key)) { - const [dx, dy] = steps[event.key]; - setCursor(((cursor >> 5) + dy + 32) % 32 * 32 + (cursor % 32 + dx + 32) % 32); - } else if (started && (event.key === ' ' || event.key === 'Enter')) toggle(cursor); - else return; - event.preventDefault(); - setKeyboard(true); - }} - onClick={event => { - 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); - toggle(y * 32 + x); - }}/> - -

{said}

-
; - } function showError(error: unknown) { document.getElementById('error')!.textContent = String(error); } + const board = {dom, store, toggle}; const root = createRoot(document.getElementById('root')!); try { - root.render(); + 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"]')) { @@ -74,7 +32,7 @@ async function main() { await dom.connect(); await webFront.cppFunction('life.react.start')(); // Survive a lost connection: keep what the page showed then, and hand it to the new C++ session. - let kept: [Uint8Array, number, number] | null = null; + let kept: Board | null = null; webFront.reconnect = true; webFront.onDisconnect(() => { kept ??= store.getSnapshot(); }); webFront.onReconnect(() => void (async () => { @@ -84,7 +42,7 @@ async function main() { await webFront.cppFunction('life.react.restore')(cells, generation); kept = null; })().catch(showError)); - root.render(); + root.render(); } catch (error) { root.unmount(); store.dispose(); diff --git a/js/developer/environment/bundler.mjs b/js/developer/environment/bundler.mjs index a5ff5c5f..32d25811 100644 --- a/js/developer/environment/bundler.mjs +++ b/js/developer/environment/bundler.mjs @@ -49,7 +49,7 @@ export function virtualPlugin(lock, packages, readProject) { return virtualPluginWith(lock, packages, readProject, new Map()); } -function virtualPluginWith(lock, packages, readProject, loaded) { +export function virtualPluginWith(lock, packages, readProject, loaded) { const {read, find} = createFinder(packages, readProject, loaded, lock); const load = namespace => async args => { const bytes = loaded.get(`${namespace}:${args.path}`) ?? await read(namespace, args.path); @@ -65,12 +65,13 @@ function virtualPluginWith(lock, packages, readProject, loaded) { }}; } -function applicationOptions({entry, lock, packages, readProject}) { +function applicationOptions({entry, lock, packages, readProject, loaded = new Map()}) { return {entryPoints: [entry], bundle: true, write: false, outdir: '/output', entryNames: 'app', assetNames: 'assets/[name]-[hash]', format: 'esm', platform: 'browser', target: 'es2020', jsx: 'automatic', minify: true, - define: {'process.env.NODE_ENV': '"production"'}, legalComments: 'inline', - plugins: [virtualPlugin(lock, packages, readProject)]}; + // No hot replacement outside `wf dev`: the branches that use import.meta.hot are dropped. + define: {'process.env.NODE_ENV': '"production"', 'import.meta.hot': 'undefined'}, legalComments: 'inline', + plugins: [virtualPluginWith(lock, packages, readProject, loaded)]}; } const outputFiles = result => new Map(result.outputFiles.map(file => [file.path.replace(/^\/output\//, ''), file.contents])); @@ -79,10 +80,45 @@ export async function bundle(esbuild, options) { return outputFiles(await esbuild.build(applicationOptions(options))); } -/** One esbuild context for repeated builds; the virtual filesystem is read again on every rebuild. */ -export async function bundleContext(esbuild, options) { - const context = await esbuild.context(applicationOptions(options)); - return {rebuild: async () => outputFiles(await context.rebuild()), dispose: () => context.dispose()}; +/** + * One esbuild context for repeated builds; the virtual filesystem is read again on every rebuild. With `hot`, the result + * is {files, hot, reason} as hot.mjs gives it. + */ +export async function bundleContext(esbuild, {hot, ...options}) { + // Both builds of a hot preview see the same bytes, and each file counts once against the bounds of a pass. + const reads = new Map(); + const readProject = !hot ? options.readProject : path => { + if (!reads.has(path)) reads.set(path, options.readProject(path)); + return reads.get(path); + }; + const open = async define => { + const loaded = new Map(); + const base = applicationOptions({...options, readProject, loaded}); + const context = await esbuild.context({...base, define: {...base.define, ...define}, metafile: Boolean(hot)}); + return {context, async run() { + const result = await context.rebuild(); + return {files: outputFiles(result), metafile: result.metafile, sources: loaded}; + }}; + }; + const ordinary = await open(); + let development; + // The graph of a hot preview is that of the code it runs: an import used only under import.meta.hot, or only in + // development, is dead in the ordinary build. + const graph = async () => { + development ??= await open({'process.env.NODE_ENV': '"development"', 'import.meta.hot': '__wfHot'}); + return development.run(); + }; + return { + async rebuild() { + reads.clear(); + const built = await ordinary.run(); + return hot ? hot.build({...options, readProject, ...built, graph}) : {files: built.files}; + }, + async dispose() { + await development?.context.dispose(); + await ordinary.context.dispose(); + }, + }; } // Node.js built-in modules: a script importing one fails while it is loaded, unless a locked package of that name diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 5fa0ab49..b66eb318 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -21,7 +21,7 @@ "js/developer/environment/automation.mjs": "708a6a72925c8f667160e3b76e9da9e96139b281e37844a3467b064ccee2586a", "js/developer/environment/accessibility-tree.mjs": "d3d36f5651ac8c920a77d3d0ae9e989a11a8d3e0fd4a86306be0b9a46854ba3c", "js/developer/environment/bindings.mjs": "10e6f3958b84f0efbad23a7da5a751d8654e8c46922da3eb5dc44081ef392677", - "js/developer/environment/development.mjs": "2bbf0970097f412fd08e5c2124c736a2260f8180ad41ae037689f5d3729e1370", + "js/developer/environment/development.mjs": "1118d9c91ae9c0b942458df4e6e21102eb596b1c3cd6b833e6fdf51f06e5a678", "js/developer/environment/testing.mjs": "f70975a1c8a4c8cd9828fc5f8664d91aa2784d315a2487184b724359680db0c2", "js/developer/environment/terminal.mjs": "26bcc86f2e34a181f3d9e57b8a94a972aeb06cb636e14c7d5a935231c3c64f48", "js/developer/environment/workspace.mjs": "3d11d99228593b2b3af95e3537a3e62b9569e5bfac2387403bd51ed621be8f38", @@ -37,8 +37,12 @@ "js/developer/environment/commands.mjs": "264dd9246d998f21988bffb1f1b096fc8087e29e66b5e9c4f6345529568c5b51", "js/developer/environment/files.mjs": "199336f7f3d23f6370da352993bf4686738b1f394b79aa9883769d19824540e0", "js/developer/environment/dependencies.mjs": "7f536e30584b10822dea6b5642fd584e5935c58f90a271ee70a03d3023e9dd34", - "js/developer/environment/compiler.mjs": "0158931132aa9b43b7bbbd01de6fa4fc34fce8c65515d593dd494930f7a1910f", - "js/developer/environment/bundler.mjs": "48658151aae4fa5ad54c9fa3386ef4095b793de0f3ad242f95e8e5de0cd0ce4d", + "js/developer/environment/compiler.mjs": "697e1c9fbb97e27ea8eb1321918e55771abe807588ab5a24bbdc55d7fb645a26", + "js/developer/environment/bundler.mjs": "694a0fd71f4457f9b9fe408f6a9cc02ad5a1f2f3273835beea95a568359dd7f7", + "js/developer/environment/hot.mjs": "a51f687f4e9470c9156a28f0e3018e67a2156419d751ce76912998f22efbf13c", + "js/developer/environment/hot-runtime.mjs": "ad36aaea742d2a667067571e03f81489fd2f70182ca29f78abd8ce3b5371fd62", + "js/developer/environment/hot-preamble.mjs": "29f7415fdfe3a6227f87738defec4d8d89a613043d47685d30874e1e90436aa3", + "js/developer/environment/refresh.mjs": "7e4a25c0dd702ef23159e462d048805ac56daaba94a1a5abcf3828e1e1dbddaf", "js/developer/environment/entry.mjs": "afc3c0555a6383d75af678fef31d5c6cb8a355c3b62208a72ef2ce9453115c9c", "js/developer/environment/conditions.mjs": "7f0ecba239480831e38985ccffd4c82309949924f4eb9d938e4ad1b09f5f36ed", "js/developer/environment/io.mjs": "21af39f07c7eb863908c1df768e3c31de1c6eb8ff757c2a287c4a47c76855db6", @@ -64,9 +68,9 @@ "js/developer/tools/distribution.json": "133bfe97f126d35ad1e40250290b88b72f49b995409723105fce59df101ad50d", "js/developer/tools/archive.mjs": "da63bb9d796ddfd24ed945b15c53f66a0400eb177886fd4f1c8fd10cafb5a91b", "js/developer/tools/distribution.mjs": "43dfdccc912693db46fd095fd78ae79325abab672d99f89fd569914ef3499cad", - "js/developer/scripts/build.mjs": "82a9b92942d904a6a98bf0ba1dcdb6a9ef44867f5568475b46097508d1e6e931", - "js/developer/webfront.project.json": "7870620b217258e9843bedf474cbba188939f84208c3387bcd4c7f23c79d4f11", + "js/developer/scripts/build.mjs": "27d759235705433fc942b6bca2f2833273125a265e89884f953c85320cbe68ae", + "js/developer/webfront.project.json": "1e6058e1c905f39ab4e1f794e71e208847543c804fa30d85cf20e71d306329d1", "js/core/bootstrap/bootstrap.bundle.mjs": "18a0567efa928fddbaa3f8d16a4d1e8440f21709ff2e3058d10ba406b2e9b66d", - "js/developer/environment/packages.bundle.mjs": "f148187eab89acb6b959fc273d985a45850c9c42cccb200091173895655a8826", + "js/developer/environment/packages.bundle.mjs": "6ec8804aaf287f2f5951cf0dd5880ddbfc816515b28ea1084377685b183783a0", "include/webfront/system/DeveloperReleaseData.hpp": "527927cc77e8874dd12553faa76149405e772e97197b611b3b89e9f1136a2c5b" } diff --git a/js/developer/environment/compiler.mjs b/js/developer/environment/compiler.mjs index e9bb6769..deb2bda3 100644 --- a/js/developer/environment/compiler.mjs +++ b/js/developer/environment/compiler.mjs @@ -1,5 +1,6 @@ import * as esbuild from 'esbuild-wasm'; import {bundle, bundleScript, bundleTests, bundleContext} from './bundler.mjs'; +import {hotBuilder} from './hot.mjs'; const pending = new Map(); let nextId = 0; @@ -10,6 +11,16 @@ const readProject = path => new Promise((resolve, reject) => { }); const initialized = esbuild.initialize({wasmURL: new URL('./esbuild.wasm', import.meta.url).href, worker: false}); let context, contextKey; +// Both are files of the environment beside this Worker, read for hot previews only. +let preambleText, refreshModule; +async function hotOptions() { + preambleText ??= await fetch(new URL('./hot-preamble.js', import.meta.url).href).then(response => { + if (!response.ok) throw new Error('Cannot read hot-preamble.js of the environment'); + return response.text(); + }); + return hotBuilder(esbuild, {preamble: preambleText, + refresh: () => refreshModule ??= import(new URL('./refresh.mjs', import.meta.url).href)}); +} const bundlers = {build: bundle, script: bundleScript, tests: bundleTests}; self.onmessage = async ({data}) => { if (data.type === 'read-result') { @@ -23,18 +34,18 @@ self.onmessage = async ({data}) => { if (!Object.hasOwn(bundlers, data.type)) return; try { await initialized; - let files; + let files, hot, reason; if (data.incremental) { - const key = JSON.stringify([data.entry, data.lock]); + const key = JSON.stringify([data.entry, data.lock, Boolean(data.hot)]); if (key !== contextKey) { await context?.dispose(); contextKey = undefined; - context = await bundleContext(esbuild, {...data, readProject}); + context = await bundleContext(esbuild, {entry: data.entry, lock: data.lock, readProject, hot: data.hot && await hotOptions()}); contextKey = key; } - files = await context.rebuild(); + ({files, hot, reason} = await context.rebuild()); } else files = await bundlers[data.type](esbuild, {...data, readProject}); - self.postMessage({type: 'result', files}); + self.postMessage({type: 'result', files, hot, reason}); } catch (error) { self.postMessage({type: 'error', error: error.message, diagnostics: error.errors?.map(({text, location}) => ({text, location}))}); } diff --git a/js/developer/environment/development.mjs b/js/developer/environment/development.mjs index 4438024e..4379e376 100644 --- a/js/developer/environment/development.mjs +++ b/js/developer/environment/development.mjs @@ -66,7 +66,7 @@ export function compilerSession(bridge, signal, createWorker = () => new Worker( response = {error: error.message}; } if (!closed && pending) worker.postMessage({type: 'read-result', id: data.id, ...response}); - } else if (data.type === 'result') finish(null, data.files); + } else if (data.type === 'result') finish(null, Object.assign(data.files, {hot: data.hot, hotReason: data.reason})); else if (data.type === 'error') finish(Object.assign(new Error(data.error), {diagnostics: data.diagnostics})); }; if (signal?.aborted) abort(); @@ -120,12 +120,54 @@ export const previewHook = "