diff --git a/.github/workflows/DeveloperDistribution.yml b/.github/workflows/DeveloperDistribution.yml index 46c039e6..149678e2 100644 --- a/.github/workflows/DeveloperDistribution.yml +++ b/.github/workflows/DeveloperDistribution.yml @@ -67,7 +67,7 @@ jobs: echo "::notice::Sources build $building; DeveloperReleaseData.hpp still pins the published $pinned." node js/developer/tools/pin-check.mjs fi - node --test js/developer/tools/check.mjs js/developer/tools/distribution-check.mjs js/developer/tools/manifest-check.mjs js/developer/tools/restore-check.mjs js/developer/tools/scripts-check.mjs + node --test js/developer/tools/check.mjs js/developer/tools/distribution-check.mjs js/developer/tools/manifest-check.mjs js/developer/tools/restore-check.mjs js/developer/tools/scripts-check.mjs js/developer/tools/development-check.mjs - name: Check the dedicated release tag if: startsWith(github.ref, 'refs/tags/developer-v') env: diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 7e8ed45d..c294cb9a 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -4,6 +4,13 @@ ### Added +- `wf build [entry]` / `wf dev [entry]` (#309, environment sources; release pin unchanged): build all manifest + entries to `.webfront/developer/build/` without opening the preview, or continuously rebuild one preview + with a persistent esbuild/WASM context. Sequential 750 ms polling watches read inputs and missing imports + (1,024 paths, 32 MiB per pass). Build/publication errors preserve the last good preview; diagnostics with + file/line/column stream to the terminal and overlay the preview. Corrections resume rebuilding; Ctrl+C + terminates the Worker, stops polling and aborts staged output. + - Project manifest `webfront.project.json` (format 1: `name`, `version`, `dependencies`, `registry`, `scripts`, `entries`, `providers`, `test`, `permissions`), strictly validated; `wf init`, `wf install [--update]` and manifest-driven `wf preview`/`wf embed` in developer distribution 0.5.0, which `DeveloperReleaseData.hpp` pins diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index cffd9d5c..ad55dee4 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -99,7 +99,7 @@ wf embed ui/main.tsx --output generated/LifeUI.hpp The starter contains editable TSX/CSS and an exact-version `webfront.project.json` recipe. `wf create life another-directory` selects a different new destination; existing directories are never replaced. React DOM pulls scheduler transitively and checks its React peer. -Edit the local files in your normal editor, then run `wf preview` again. Ctrl+C interrupts +Edit the local files in your normal editor and use `wf dev` for automatic rebuilds, or run `wf preview` again. Ctrl+C interrupts commands, including downloads and builds. The interface draws an isometric field with raised living cells, soft lighting and translucent @@ -351,7 +351,7 @@ open, Enter starts a new session. No system shell is exposed. - **Typing ahead and paste:** keys typed or pasted while a command runs are applied after it, line by line; a last line without a line break waits on the prompt. Ctrl+C drops the keys still waiting. - **Completion (Tab):** command names, `wf` subcommands, the manifest's scripts after `wf run`, its entries and - providers after `wf preview` and `wf embed`, and project paths, also when the word is escaped (`my\ dir/`) or + entries/providers after `wf build`, `wf dev`, `wf preview` and `wf embed`, and project paths, also when the word is escaped (`my\ dir/`) or quoted (`"my dir/`); the completion is written the same way and closes the quote. Several candidates are completed to their common prefix, or listed. - **Exit codes:** a failed command prints `Error: `, with `(exit code N)` when N is not 1. Ctrl+C gives 130. @@ -404,6 +404,40 @@ browser is gone. The names `wf`, `clear`, `exit`, writing large output with it, faster than the browser reads, grows the connection's write queue; use `context.print` for such output. +## Build and continuous development + +`wf build [entry.tsx|name]` compiles without opening or navigating the preview and publishes the whole +result to `.webfront/developer/build/`. With no argument it builds every manifest entry: a single entry +uses that directory directly; multiple entries each get a named subdirectory with their own `index.html`, +`app.js`, optional CSS and assets. Directory names percent-escape punctuation and Windows device names. An explicit path or manifest entry name selects one entry at the root. +Publication replaces the directory only after every entry succeeds. Build output is available as local +files; the developer HTTP provider serves only the environment and preview directories. + +`wf dev [entry.tsx|name]` selects `entries.main` or the sole entry when omitted, builds, opens the preview +and keeps running until Ctrl+C. It reuses one compiler Worker and esbuild context across rebuilds. +Changing the selected entry or locked graph recreates the context. It uses the installed lock, without +resolving packages or downloading dependencies; `wf install`/`wf restore` remain explicit actions. + +Detection uses portable, sequential polling rather than a platform-specific C++ filesystem watcher. +After each build it waits 750 ms, then compares SHA-256 digests of the inputs actually read during that +build, including missing resolution candidates, the manifest, the lock and used cached package files. +Creating a missing import, deleting an input, editing CSS, or changing entries/the lock triggers a rebuild. +Unrelated files and generated outputs are not scanned. A pass is limited to 1,024 paths and 32 MiB of +input, read in 256 KiB chunks; each compilation has a 120 s deadline. Polling never overlaps a build or +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. + +Only a successful build and publication reload the preview, replacing 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. Ctrl+C ends with exit code 130, terminates +the Worker, cancels polling and aborts staged publication; a publication already committed finishes and reloads +the preview before stopping. +The last successful preview stays available. Browser disconnection also stops the loop. + +These commands are in the 0.6.0 environment sources (not published); the release pin stays on published 0.5.0. To try +them before the next release, provision an archive rebuilt from these sources as described below. + ## Dependencies, storage and limitations - `wf install` accepts exact versions, registry tags and semver ranges, resolves ordinary @@ -491,7 +525,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` exercises the real WASM compiler, local registry, PI and Life previews, C++ generation/animation and +`DeveloperBrowserIntegration` exercises the real WASM compiler, local registry, build without navigation, incremental dev reload/error/recovery/Ctrl+C, PI and Life previews, C++ generation/animation and repeatable header generation. Its CTest fixtures then build that **browser-generated** header and run `DeveloperEmbeddedIntegration` and `LifeEmbeddedIntegration` from empty working directories with no developer callbacks. diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index 49217549..b7aa1cb3 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -132,7 +132,7 @@ Status snapshot: 2026-07-19. Optional mddlog integration note: 2026-10-02. Newco manifest permissions, which frame the `context` API only and are not a sandbox. Peers require explicit compatible roots/direct dependencies. The environment's terminal (#308) runs `wf`, built-in and C++ commands (`webfront::Commands`: per-browser coroutine sessions, streamed output, Ctrl+C cancellation without waiting, drained at shutdown) with - multi-row editing, CJK/emoji widths, persistent history and completion. Automatic rebuild/watch is future work. `wf restore [--offline]` (0.5.0, #306) rebuilds or checks + multi-row editing, CJK/emoji widths, persistent history and completion. `wf build` / `wf dev` (#309, environment sources) publish manifest entries and rebuild the preview automatically with a reused esbuild context, bounded input polling, error overlays and Ctrl+C cancellation; the release pin is unchanged. `wf restore [--offline]` (0.5.0, #306) rebuilds or checks the cache from the lock, from the application's registry option, else the manifest's, else npmjs. See [DEVELOPER_ENVIRONMENT](DEVELOPER_ENVIRONMENT.md) for exact commands and limits. diff --git a/js/developer/environment/bundler.mjs b/js/developer/environment/bundler.mjs index d2d23189..9416df4b 100644 --- a/js/developer/environment/bundler.mjs +++ b/js/developer/environment/bundler.mjs @@ -57,19 +57,32 @@ function virtualPluginWith(lock, packages, readProject, loaded) { return {contents: loader ? decoder.decode(bytes) : bytes, loader: loader ?? 'file'}; }; return {name: 'webfront-project', setup(build) { + // Resolution caches belong to one rebuild: source bytes must never survive into the next one. + build.onStart?.(() => loaded.clear()); build.onResolve({filter: /.*/}, args => resolveImport(args, lock, find)); build.onLoad({filter: /.*/, namespace: 'empty'}, () => ({contents: '', loader: 'js'})); for (const namespace of ['project', 'npm']) build.onLoad({filter: /.*/, namespace}, load(namespace)); }}; } -export async function bundle(esbuild, {entry, lock, packages, readProject}) { - const result = await esbuild.build({entryPoints: [entry], bundle: true, write: false, +function applicationOptions({entry, lock, packages, readProject}) { + 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)]}); - return new Map(result.outputFiles.map(file => [file.path.replace(/^\/output\//, ''), file.contents])); + plugins: [virtualPlugin(lock, packages, readProject)]}; +} + +const outputFiles = result => new Map(result.outputFiles.map(file => [file.path.replace(/^\/output\//, ''), file.contents])); + +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()}; } // 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 65c40f2b..559a146d 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -16,12 +16,13 @@ "js/developer/environment/packages.mjs": "6636219f3fef20ea1d274dc9298d8af451ef257b86fe6c1ed0de9a7c797b11d8", "js/developer/environment/starter.mjs": "f38e290e03aebe146623c2ca9b590d645fb91a51acdf7a98101bb00b5b88096c", "js/developer/environment/paths.mjs": "3b6114df78eb193161c5c84499dda084cb7ff91c56a4496371c30295d00880e3", - "js/developer/environment/runtime.mjs": "6325ee38cafa803b72932b4b2f2263014cbffae47d2191848940145f85e17d08", + "js/developer/environment/runtime.mjs": "391403965c1661c23359d49fd25e2ddb3f7b026225d32256c578f977dd8a7c8a", + "js/developer/environment/development.mjs": "dd07bc64e12c3392223f0e7aab0ae2f5223e093930bee8abe78a0cd3e2940d85", "js/developer/environment/terminal.mjs": "7ffcf7ac6ef63c35cdf5ef70284b384525b13ba18422af069289e53b6c4f6be1", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", "js/developer/environment/commands.mjs": "8de20c01f02f33c0566f204fcf1ee2382a23344d2103581fe2914469ec570531", - "js/developer/environment/compiler.mjs": "cc6fbe8cabbd94750045cebfdf942234247519099a192ef9cdda6ccbdbfbb6a4", - "js/developer/environment/bundler.mjs": "c2f55056a4702d57207203a29226f98a95a31ae615596bf21338b7dfabe83ed9", + "js/developer/environment/compiler.mjs": "64bf490cd09e1324ff95b88f1b1579c8ca186b953cc96862ab49262fe1a85cca", + "js/developer/environment/bundler.mjs": "8ad11d122478a4c6be2025580c28adfeb801f629ffd8b0ed5f05f8d1520b5a2f", "js/developer/environment/entry.mjs": "b2b942443e3c74ae2c008392ba244d9b7e91db70ba1b4ebbe1357c455ebf51bb", "js/developer/environment/conditions.mjs": "7f0ecba239480831e38985ccffd4c82309949924f4eb9d938e4ad1b09f5f36ed", "js/developer/environment/io.mjs": "21af39f07c7eb863908c1df768e3c31de1c6eb8ff757c2a287c4a47c76855db6", @@ -37,8 +38,8 @@ "js/developer/tools/starters/pi/style.css": "360e2c7ae6d3699b00e18cbf67efbae7a8d8863d88926b31139e102cf38e5abd", "examples/life/ui/main.tsx": "ed11a82aad1639eb6997af8b0fca4d5c5ed4c36422c22a74ac49ae73078d0a91", "examples/life/ui/style.css": "9bb55eb0f0a3287e5b7dc78af9d69608b87ff42c4d9c8a653bc83a52fe293c44", - "js/developer/tools/distribution.json": "12b40657d1bc34c4093cd5f793d772bf3fa6fd8615ab7b766ad1756092438f83", - "js/developer/tools/build.mjs": "1516d8f0be60c0dc3d6f3ae66a92558699d62b4d15714325580eb2c0d35dac7f", + "js/developer/tools/distribution.json": "4c8703b10e0bfca70e47e1c2b9f5afe7bbe4b4b87cd8be99e15082cfd2915373", + "js/developer/tools/build.mjs": "ac26574972e1b0ebfb58c8d39ea52a9cf24d2a686370c893308b24c9350183f5", "js/developer/tools/site.mjs": "1827d3fd7e1e470336aab25ea8686c912c2b674a10f7be496f2f0077fbc45292", "js/developer/tools/archive.mjs": "bfe9feeb5e4d4e1b7c44c4dec4dcbeab4ae59c2bf16a1d2b32cd6910a2b84e7b", "js/developer/vendor/package-lock.json": "f6aefe8b4cb0b15f866f41eae425f6654d2c6c2d96438fd0da878c5651585616", diff --git a/js/developer/environment/compiler.mjs b/js/developer/environment/compiler.mjs index f7e3ed23..23abadf6 100644 --- a/js/developer/environment/compiler.mjs +++ b/js/developer/environment/compiler.mjs @@ -1,5 +1,5 @@ import * as esbuild from 'esbuild-wasm'; -import {bundle, bundleScript} from './bundler.mjs'; +import {bundle, bundleScript, bundleContext} from './bundler.mjs'; const pending = new Map(); let nextId = 0; @@ -9,6 +9,7 @@ const readProject = path => new Promise((resolve, reject) => { self.postMessage({type: 'read', id, path}); }); const initialized = esbuild.initialize({wasmURL: new URL('./esbuild.wasm', import.meta.url).href, worker: false}); +let context, contextKey; self.onmessage = async ({data}) => { if (data.type === 'read-result') { const request = pending.get(data.id); @@ -21,9 +22,19 @@ self.onmessage = async ({data}) => { if (data.type !== 'build' && data.type !== 'script') return; try { await initialized; - const files = await (data.type === 'script' ? bundleScript : bundle)(esbuild, {...data, readProject}); + let files; + if (data.incremental) { + const key = JSON.stringify([data.entry, data.lock]); + if (key !== contextKey) { + await context?.dispose(); + contextKey = undefined; + context = await bundleContext(esbuild, {...data, readProject}); + contextKey = key; + } + files = await context.rebuild(); + } else files = await (data.type === 'script' ? bundleScript : bundle)(esbuild, {...data, readProject}); self.postMessage({type: 'result', files}); } catch (error) { - self.postMessage({type: 'error', error: error.message}); + 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 new file mode 100644 index 00000000..cc33f3a7 --- /dev/null +++ b/js/developer/environment/development.mjs @@ -0,0 +1,248 @@ +// Browser builds and development loop. Only project-relative bridge reads; no platform watcher or shell. +import {call, publish} from './io.mjs'; +import {loadProject, resolveEntry, syncNotice, noManifest} from './project.mjs'; +import {manifestPath, lockPath} from './manifest.mjs'; +import {applicationPage} from './embed.mjs'; + +export const watchBounds = {paths: 1024, bytes: 32 * 1024 * 1024, interval: 750}; +const stopped = () => Object.assign(new Error('Interrupted'), {exitCode: 130}); +const digest = async bytes => Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), b => b.toString(16).padStart(2, '0')).join(''); + +// Bound both each read and the whole pass, including resolution probes for files that do not exist yet. +export async function observedRead(bridge, path, observed, budget, signal) { + signal?.throwIfAborted(); + if (!observed.has(path) && observed.size >= watchBounds.paths) throw new Error('Build/watch exceeds 1024 input paths'); + observed.set(path, null); + const chunks = []; + let offset = 0; + try { + for (;;) { + signal?.throwIfAborted(); + const chunk = await call(bridge, 'read', path, offset); + budget.bytes += chunk.length; + if (budget.bytes > watchBounds.bytes) throw new Error('Build/watch exceeds 32 MiB of input per pass'); + chunks.push(chunk); + offset += chunk.length; + if (chunk.length < 256 * 1024) break; + } + } catch (error) { + // Other read failures must be retried/reported, rather than mistaken for a missing import. + observed.set(path, error.message.includes('Cannot read project file:') ? 'missing' : `error:${error.message}`); + throw error; + } + const bytes = new Uint8Array(await new Blob(chunks).arrayBuffer()); + observed.set(path, await digest(bytes)); + return bytes; +} + +/** A persistent compiler Worker. At most one rebuild at a time; stop/timeout terminate it and reject pending work. */ +export function compilerSession(bridge, signal, createWorker = () => new Worker(new URL('./compiler.mjs', import.meta.url), {type: 'module'})) { + const worker = createWorker(); + let pending, closed = false, observed = new Map(), budget; + const finish = (error, files) => { + if (!pending) return; + const {resolve, reject, timer} = pending; + pending = null; + clearTimeout(timer); + error ? reject(error) : resolve(files); + }; + const close = (error = stopped()) => { + if (closed) return; + closed = true; + worker.terminate(); + signal?.removeEventListener('abort', abort); + finish(error); + }; + const abort = () => close(stopped()); + signal?.addEventListener('abort', abort, {once: true}); + worker.onerror = event => close(new Error(event.message || 'Compiler worker failed')); + worker.onmessage = async ({data}) => { + if (closed || !pending) return; + if (data.type === 'read') { + let response; + try { response = {bytes: await observedRead(bridge, data.path, observed, budget, signal)}; } + catch (error) { + if (/Build\/watch exceeds/.test(error.message)) return close(error); + 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 === 'error') finish(Object.assign(new Error(data.error), {diagnostics: data.diagnostics})); + }; + if (signal?.aborted) abort(); + return { + get closed() { return closed; }, + get observed() { return observed; }, + rebuild(message) { + if (closed) return Promise.reject(stopped()); + if (pending) return Promise.reject(new Error('A browser build is already running')); + observed = new Map(); + budget = {bytes: 0}; + return new Promise((resolve, reject) => { + pending = {resolve, reject, timer: setTimeout(() => close(new Error('Browser build timed out')), 120000)}; + worker.postMessage({type: 'build', incremental: true, ...message}); + }); + }, + close, + }; +} + +export function diagnosticsText(error) { + if (!error.diagnostics?.length) return error.message; + return error.diagnostics.map(({text, location}) => location ? + `${location.file.replace(/^project:/, '')}:${location.line}:${location.column + 1}: ${text}\n${location.lineText ?? ''}` : text).join('\n'); +} + +// textContent keeps a diagnostic containing source text inert in the application's document. +export function previewDiagnostics(frame, text) { + if (text && frame) frame.hidden = false; + const document = frame?.contentDocument; + if (!document?.body) return; + document.getElementById('webfront-build-diagnostics')?.remove(); + if (!text) return; + const overlay = document.createElement('pre'); + overlay.id = 'webfront-build-diagnostics'; + overlay.setAttribute('role', 'alert'); + overlay.style.cssText = 'position:fixed;inset:0;z-index:2147483647;margin:0;padding:24px;overflow:auto;white-space:pre-wrap;background:#211821ed;color:#ffd8d8;font:14px/1.5 monospace'; + overlay.textContent = text; + document.body.append(overlay); +} + +let revision = 0; +export function showPreview(frame, directory = 'preview') { + if (!frame) throw new Error('No preview frame is available'); + frame.hidden = false; + frame.contentWindow.location.replace(`/webfront/developer/${directory}/index.html?build=${Date.now()}-${++revision}`); +} + +// Manifest labels allow punctuation that project paths forbid. Escape it without collisions; also avoid +// Windows device directory names, so the same manifest builds on every supported platform. +function entryDirectory(name) { + const escaped = encodeURIComponent(name).replaceAll('.', '%2E'); + return /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(escaped) ? + `%${escaped.charCodeAt(0).toString(16).toUpperCase()}${escaped.slice(1)}` : escaped; +} + +export function buildEntries(manifest, argument) { + if (argument !== undefined) return [['', resolveEntry(manifest, argument)]]; + const entries = Object.entries(manifest?.entries ?? {}); + if (!entries.length) throw new Error('Usage: wf build (or declare entries in webfront.project.json)'); + return entries.map(([name, entry]) => [entries.length === 1 ? '' : entryDirectory(name), entry]); +} + +export async function build(args, {bridge, signal}) { + if (args.length > 1) throw new Error('Usage: wf build [entry.tsx|name]'); + signal?.throwIfAborted(); + const project = await loadProject(bridge); + const session = compilerSession(bridge, signal); + try { + const files = new Map(); + for (const [name, entry] of buildEntries(project.manifest, args[0])) { + const output = await session.rebuild({entry, lock: project.lock ?? {format: 1, roots: {}, packages: {}}}); + output.set('index.html', applicationPage(output)); + for (const [path, bytes] of output) files.set(name ? `${name}/${path}` : path, bytes); + } + await publish(bridge, '.webfront/developer/build', files, {signal}); + return syncNotice(project) + 'Build ready: .webfront/developer/build/'; + } catch (error) { + if (signal?.aborted) throw stopped(); + throw Object.assign(error, {message: diagnosticsText(error)}); + } finally { session.close(); } +} + +export function waitForPoll(signal, milliseconds = watchBounds.interval) { + return new Promise((resolve, reject) => { + const abort = () => { clearTimeout(timer); signal?.removeEventListener('abort', abort); reject(stopped()); }; + const timer = setTimeout(() => { signal?.removeEventListener('abort', abort); resolve(); }, milliseconds); + signal?.addEventListener('abort', abort, {once: true}); + if (signal?.aborted) abort(); + }); +} + +// Compare to the bytes actually read by the build, not a snapshot taken after it: edits made during compilation +// are still noticed. Missing candidates are watched too, so creating an unresolved import recovers a failed build. +export async function inputsChanged(bridge, observed, signal) { + const current = new Map(), budget = {bytes: 0}; + for (const [path, before] of observed) { + try { await observedRead(bridge, path, current, budget, signal); } + catch (error) { + if (signal?.aborted) throw stopped(); + if (current.get(path) !== 'missing') throw error; + } + if (current.get(path) !== before) return true; + } + return false; +} + +export async function dev(args, {bridge, signal, preview: frame, write = () => {}}) { + if (args.length > 1) throw new Error('Usage: wf dev [entry.tsx|name]'); + const controller = new AbortController(); + const abort = () => controller.abort(); + let connectionClosed = false; + const disconnected = () => { connectionClosed = true; controller.abort(); }; + signal?.addEventListener('abort', abort, {once: true}); + bridge.socket?.addEventListener('close', disconnected, {once: true}); + if (signal?.aborted) abort(); + const active = controller.signal; + let session, observed = new Map(); + let diagnostic = ''; + const loaded = () => previewDiagnostics(frame, diagnostic); + frame?.addEventListener('load', loaded); + try { + for (;;) { + active.throwIfAborted(); + const configReads = new Map(), budget = {bytes: 0}; + try { + // Record the configuration before loading it. A concurrent edit triggers another iteration. + for (const path of [manifestPath, lockPath]) { + try { await observedRead(bridge, path, configReads, budget, active); } + catch (error) { if (configReads.get(path) !== 'missing') throw error; } + } + const project = await loadProject(bridge); + if (!project.manifest && args[0] === undefined) throw new Error(noManifest); + const entry = resolveEntry(project.manifest, args[0], 'wf dev '); + if (!session || session.closed) session = compilerSession(bridge, active); + const files = await session.rebuild({entry, lock: project.lock ?? {format: 1, roots: {}, packages: {}}}); + files.set('index.html', applicationPage(files)); + await publish(bridge, '.webfront/developer/preview', files, {signal: active}); + // Once commit succeeds, display its publication even if Ctrl+C arrived while awaiting it. + diagnostic = ''; + previewDiagnostics(frame, ''); + showPreview(frame); + // A successful build can drop dependencies that are no longer imported. + observed = new Map(session.observed); + write(syncNotice(project) + 'Preview ready. Watching inputs (Ctrl+C to stop).\n'); + } catch (error) { + if (active.aborted) throw stopped(); + diagnostic = diagnosticsText(error); + write(diagnostic + '\n'); + previewDiagnostics(frame, diagnostic); + if (session?.observed.size) observed = new Map(session.observed); + } + observed = new Map([...configReads, ...[...observed].filter(([path]) => !configReads.has(path))]); + if (observed.size > watchBounds.paths) throw new Error('Build/watch exceeds 1024 input paths'); + for (;;) { + await waitForPoll(active); + try { if (await inputsChanged(bridge, observed, active)) break; } + catch (error) { + if (active.aborted) throw stopped(); + // A temporarily unreadable file or a bound violation cannot publish or reload anything. + const text = diagnosticsText(error); + if (diagnostic !== text) { diagnostic = text; write(text + '\n'); previewDiagnostics(frame, text); } + } + } + } + } catch (error) { + if (controller.signal.aborted) { + if (connectionClosed) throw new Error('The connection to the application closed'); + throw stopped(); + } + throw error; + } finally { + session?.close(); + signal?.removeEventListener('abort', abort); + bridge.socket?.removeEventListener('close', disconnected); + frame?.removeEventListener('load', loaded); + previewDiagnostics(frame, ''); + } +} diff --git a/js/developer/environment/runtime.mjs b/js/developer/environment/runtime.mjs index bf95f886..77d4cffc 100644 --- a/js/developer/environment/runtime.mjs +++ b/js/developer/environment/runtime.mjs @@ -12,6 +12,7 @@ import {install, initProject} from './installer.mjs'; import {restore, describeRegistry} from './restore.mjs'; import {loadProject, syncNotice, resolveEntry, embedTarget, lockPath, packageRoot, noManifest} from './project.mjs'; import {parseRunOptions, scriptCommand, execTarget, scriptHost, runWorker, runResult, runDeadline, secondsLeft} from './scripts.mjs'; +import {build, dev} from './development.mjs'; import {generateProvider, applicationPage} from './embed.mjs'; import {typescriptPackage, parseCheckOptions, checkHost} from './typecheck.mjs'; @@ -202,8 +203,8 @@ async function list(_args, {bridge}) { return syncNotice(project) + (names || 'No installed packages.'); } -const help = () => 'wf init [name]\nwf create [directory]\nwf install [--update] [[@range] ...]\nwf restore [--offline]\nwf run [--timeout ]