diff --git a/README.fr.md b/README.fr.md index e3e8cf05..53c3aa22 100644 --- a/README.fr.md +++ b/README.fr.md @@ -235,7 +235,7 @@ wf dev ui/main.tsx `wf create life` écrit le [starter TSX et CSS](examples/life/ui) dans `ui/` sans écraser un répertoire existant. `wf init` crée le manifeste `webfront.project.json`. `wf install` résout et vérifie les paquets, puis verrouille leurs versions dans `webfront-packages.lock.json`, sans lancer de scripts d'installation. `wf restore` reconstruit le cache depuis ce verrou ; `wf restore --offline` le vérifie sans réseau. -`wf dev` compile le TSX avec esbuild-wasm, ouvre l'interface et la reconstruit à chaque sauvegarde. Les erreurs apparaissent dans le terminal et l'aperçu, qui conserve sa dernière version valide. Ctrl+C l'arrête ; `wf build` compile une fois. +`wf dev` compile le TSX avec esbuild-wasm, ouvre l'interface et la reconstruit à chaque sauvegarde. Les erreurs apparaissent dans le terminal et l'aperçu, qui conserve sa dernière version valide. Échap ou le bouton Stop du terminal l'arrête ; `wf build` compile une fois. Éditez `life-project/ui/main.tsx` et `style.css` avec votre éditeur habituel. React dessine la grille ; chaque génération attend C++ : diff --git a/README.md b/README.md index 011c7535..7f69e533 100644 --- a/README.md +++ b/README.md @@ -282,7 +282,7 @@ wf dev ui/main.tsx - `wf create life` writes the editable [TSX and CSS starter](examples/life/ui) into `ui/`; it never overwrites an existing directory. The argument names a starter, not your project: `wf create app` writes a minimal TypeScript interface for a new application instead. - `wf init` writes `webfront.project.json`, the manifest every other command reads: dependencies, entries, providers, scripts and permissions. - `wf install` resolves the packages and their dependencies from the registry, verifies their integrity and records exact versions in `webfront-packages.lock.json`. It does not run the installation scripts of packages. `wf restore` rebuilds the cache from the lock on another machine, and `wf restore --offline` verifies it without any network. -- `wf dev` compiles the TSX with esbuild-wasm, opens the interface inside the application and rebuilds it whenever you save a source. A build error appears in the terminal and over the preview, which keeps its last good version. Ctrl+C stops it; `wf build` compiles once without opening anything. +- `wf dev` compiles the TSX with esbuild-wasm, opens the interface inside the application and rebuilds it whenever you save a source. A build error appears in the terminal and over the preview, which keeps its last good version. Escape or the terminal's Stop button stops it; `wf build` compiles once without opening anything. Edit `life-project/ui/main.tsx` and `style.css` with your usual editor. React renders the field and controls; each generation awaits the C++ callback: diff --git a/README.zh-CN.md b/README.zh-CN.md index af9b220b..0292b7f7 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -279,7 +279,7 @@ wf dev ui/main.tsx - `wf create life` 将可编辑的 [TSX 和 CSS 模板](examples/life/ui)写入 `ui/`,已有目录会保留。参数是模板名。`wf create app` 可为新项目生成最小的 TypeScript 界面。 - `wf init` 写入 `webfront.project.json`。其他命令从该清单读取依赖、入口、资源提供器、脚本和权限。 - `wf install` 从包仓库解析依赖,校验完整性,并将确切版本写入 `webfront-packages.lock.json`。安装过程不会执行软件包的安装脚本。`wf restore` 可在其他机器上按锁文件重建缓存,`wf restore --offline` 可离线验证缓存。 -- `wf dev` 用 esbuild-wasm 编译 TSX,在应用中打开界面,并在保存源码后重新构建。构建错误会显示在终端和预览上,预览保留最近一次成功的版本。按 Ctrl+C 停止。若只需编译一次,可运行 `wf build`。 +- `wf dev` 用 esbuild-wasm 编译 TSX,在应用中打开界面,并在保存源码后重新构建。构建错误会显示在终端和预览上,预览保留最近一次成功的版本。按 Esc 键或终端的 Stop 按钮停止。若只需编译一次,可运行 `wf build`。 用常用编辑器修改 `life-project/ui/main.tsx` 和 `style.css`。React 绘制网格和控件,每一代的计算都等待 C++ 回调完成。 diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index ce63fbec..a36653d0 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -11,11 +11,13 @@ these entries stays in the GitHub releases and the Git history. ## Unreleased ### Breaking +- In the developer environment's terminal, Ctrl+C no longer interrupts a command nor clears the line: press Escape (with no text selected) or the terminal's **Stop** button; the interruption is unchanged (exit code 130, `webfront.commands.cancel`, the grace period of scripts, status `interrupted`), its messages say `interrupted` (#721, `docs/DEVELOPER_ENVIRONMENT.md`). - A custom frontend whose `open()` takes `const ViewLaunch&` declares `static bool providesViewProof()`, `true` when it gives the proof to its view and `false` otherwise, or the developer environment no longer compiles with it: undeclared, its proven view would leave project writes and C++ commands unguarded (#680, ADR-027, `docs/FRONTENDS.md`). - `cppFunction` (and `Space::cppFunction`) refuses the names starting with `webfront.inspector.`, reserved to the inspectors, with `std::invalid_argument`: rename such a function, and its `webFront.cppFunction(...)` calls in the page, to a name of your own (#680, ADR-027). - An external tool that writes the project (`webfront.developer.*` writes) or starts terminal commands (`webfront.commands.start`, `cancel`) through the bridge is refused with `webfront.inspector.denied` when the frontend proves its view: run it in that view, use MCP automation, or set `trustLoopbackClients` knowingly (#680, ADR-027, `docs/DEVELOPER_ENVIRONMENT.md`). ### Added +- Copy, paste, cut and select all in the terminal of the developer environment with the system's shortcuts, Ctrl+C/V/X/A (Cmd on macOS), on CEF, WebView2, WebKitGTK, WKWebView and a system browser: they no longer become control characters, and a paste of several lines still runs them one after the other (#721, `docs/DEVELOPER_ENVIRONMENT.md`). - Open the inspectors from the WebFront tab's menu of the developer environment: each panel shows in a floating window of the page and can be detached to a native secondary window (WebKitGTK, WKWebView, WebView2) or, with `trustLoopbackClients`, a tab of the system browser; the choice and the place are kept per project (#680, ADR-027, `docs/DEVELOPER_ENVIRONMENT.md`). - See in the **Functions** panel of the inspectors what the application registered: each `cppFunction` with its signature written in TypeScript, the file and line of its registration, whether it receives the calling `UI`, its calls, failures, last error and durations, then the JavaScript functions that C++ calls; sort, search, and choose the refresh period (#681, ADR-027, `docs/DEVELOPER_ENVIRONMENT.md`). - See in the **Browsers and tasks** panel the connected browsers (embedded view or external browser, local client, pending writes and calls), the running tasks of the server and the application's terminal commands (#681, ADR-027). @@ -43,7 +45,7 @@ these entries stays in the GitHub releases and the Git history. ### Changed - Detach and attach an inspector panel with small icons, a frame with an arrow leaving it or entering it, instead of the **Detach** and **Attach** words; their tooltip and accessible name say the action, and a greyed detach icon still says why (#722, `docs/DEVELOPER_ENVIRONMENT.md`). -- `wf test` stopped at its time limit or by Ctrl+C says how far its runner got, in its message and in the report's new `stage`: the last step reached, the spec in progress, and the runner files that never finished loading (#690, `docs/DEVELOPER_ENVIRONMENT.md`). +- `wf test` stopped at its time limit or by an interruption says how far its runner got, in its message and in the report's new `stage`: the last step reached, the spec in progress, and the runner files that never finished loading (#690, `docs/DEVELOPER_ENVIRONMENT.md`). - Destroying the handle of a watch (`inspect::Watch`) waits for an operation of the inspectors in progress on another thread: destroy it outside every lock its source takes, or declare the watch with the state it owns (#682, ADR-027, `docs/WATCHES.md`). - `cppFunction` and `Space::cppFunction` take a last, defaulted `std::source_location`, which the inspectors show; existing calls compile unchanged, the explicit `cppFunction` form included (#681, ADR-027). - Document the security contract of the application's callbacks: one that writes the project or what the server serves, starts a process or exposes a sensitive state takes the calling `UI` and checks `ui.isLocalClient()`, since WebFront guards only its own functions (#686, ADR-027, `docs/DEVELOPING_WITH_AGENTS.md`). diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index d2c31735..8fd3b65d 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -145,8 +145,8 @@ application: `ui/main.ts` calls one C++ callback, `app.greet`, and each of its e The starter contains editable TSX/CSS and a recipe of exact versions; `wf init` does not copy it, so list the dependencies with `wf install` and declare `test.specs`, `entries` and `providers` in the manifest yourself. `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 and use `wf dev` for automatic rebuilds, or run `wf preview` again. Ctrl+C interrupts -commands, including downloads and builds. +Edit the local files in your normal editor and use `wf dev` for automatic rebuilds, or run `wf preview` again. Escape (while no +text of the terminal is selected) or the terminal's Stop button interrupts commands, including downloads and builds. The interface draws an isometric field with raised living cells, soft lighting and translucent panels. Play/pause, single step, tempo, glider/blinker/galaxy seeds, clear, cell painting and a plan @@ -265,7 +265,7 @@ when it is damaged, `wf restore` rebuilds it from the lock alone: - each locked package is downloaded at its exact locked version (no range is resolved again) and checked against the lock's SHA-512 integrity; packages already valid in the cache are not downloaded again, so the command is idempotent; -- every package is published on its own: Ctrl+C or an error (changed archive, package absent from the +- every package is published on its own: an interruption or an error (changed archive, package absent from the registry) keeps the packages already restored and never writes the manifest or the lock; run the command again; - `wf restore --offline` contacts no registry at all: it checks the cache against the lock and fails with the list of missing or corrupted packages, without downloading anything. @@ -320,7 +320,7 @@ and runs in a dedicated Worker; only the package files it imports are read from | Member | Behavior | | --- | --- | | `args` | The arguments, as an array of strings. | -| `signal` | An `AbortSignal` aborted by Ctrl+C and by the time limit. | +| `signal` | An `AbortSignal` aborted by an interruption (Escape or the Stop button) and by the time limit. | | `console` | `log`/`info`/`debug` and `warn`/`error`, streamed to the terminal; the Worker's global `console` too. | | `project.read(path)`, `readText(path)` | A project file as bytes or text, under `permissions.files` or `publish`. | | `project.list(path = '')` | The names in a project directory (directories end with `/`). A readable directory is listed whole; the root and the directories leading to granted paths list only the entries leading to them. | @@ -338,14 +338,14 @@ provided. A script cannot run a native program, and no manifest permission can g program (a CLI under test, a converter's output checked by the binary that reads it) is a spec of the consumer Jasmine path, where the test's owner authorizes the program ([native programs and temporary files](CONSUMER_TESTING.md#native-programs-and-temporary-files-from-the-specs)). -Ctrl+C first aborts `context.signal`; a script still running two seconds later (the grace period) is terminated with +An interruption first aborts `context.signal`; a script still running two seconds later (the grace period) is terminated with `worker.terminate()`, which also stops a loop that never returns to the event loop. The time limit (`--timeout`, 600 seconds by default, from 1 to 3600) applies the same sequence; it also bounds the scripts that the script runs through `wf` commands, whatever their own limit. The terminal stays usable. Each write is a transaction of its own: at a stop, one still staging is aborted and leaves the file unchanged, and one whose commit was already sent completes atomically; the terminal lists the publications applied and abandoned. When a script ends by itself, the writes it did not await complete first; if one of them fails, the run ends with code 1 and names it. A script that -returns ends with code 0, a thrown error with 1, `exit(code)` with that code, Ctrl+C with 130 and the time limit with +returns ends with code 0, a thrown error with 1, `exit(code)` with that code, an interruption with 130 and the time limit with 124; a non-zero code is an error carrying `exitCode`. ## Type checking (`wf check`) @@ -383,9 +383,9 @@ wf check snapshot that reaches its bounds still compiles but reports the files it left out and fails; a listing past its bound fails at once. TypeScript itself (about 9 MiB) is read from the cache and is not counted. The Worker's memory is the browser's; it is not limited further. -- **Time**: `--timeout` (600 seconds by default, from 1 to 3600) and Ctrl+C stop the check like `wf run`: a check +- **Time**: `--timeout` (600 seconds by default, from 1 to 3600) and an interruption stop the check like `wf run`: a check still loading its snapshot stops at its next read, and one compiling, which never returns to its event loop, is - terminated with `worker.terminate()` after the two-second grace period. The exit code is 130 (Ctrl+C) or 124 (time + terminated with `worker.terminate()` after the two-second grace period. The exit code is 130 (interruption) or 124 (time limit), and the terminal stays usable. ## The page: interface and floating terminal @@ -658,22 +658,33 @@ scheduler@0.28.0 unknown starter lists the starters. The line under the terminal that reports the bootstrap ends with `Agents: docs/DEVELOPING_WITH_AGENTS.md`; it comes from the library's embedded loader, not from the environment. -- **Editing:** left/right, Home/End (Ctrl+A/Ctrl+E), Backspace/Delete, Ctrl+U/Ctrl+K, Ctrl+L, up/down through the +- **Editing:** left/right, Home/End (Ctrl+E for End), Backspace/Delete, Ctrl+U/Ctrl+K, Ctrl+L, up/down through the history. A line wider than the terminal wraps over several rows and is redrawn in place; a line taller than the terminal is drawn a screen of rows at a time around the cursor, since rows that left the screen cannot be rewritten. The editor moves over grapheme clusters: CJK characters and emoji (ZWJ sequences, flags, skin tones, presentation selector) take two cells, combining marks none. The same widths are registered in xterm.js, so both always agree. +- **System shortcuts:** Ctrl+C/⌘C copies the selection, Ctrl+V/⌘V pastes, Ctrl+A/⌘A selects the whole terminal and + Ctrl+X/⌘X copies the selection, since nothing of the terminal can be cut (Shift may be held, as Ctrl+Shift+C in other + terminals). The terminal does not turn them into control characters: the engine copies and pastes, with CEF, WebView2, + WebKitGTK, WKWebView (through its Edit menu) and a system browser alike. Without a selection, Ctrl+C does nothing: it + neither clears the line nor interrupts a command. A paste keeps the multi-line behaviour below. +- **Interruption:** while a command runs, Escape (when no text of the terminal is selected; with a selection, Escape + clears it) or the **Stop** button interrupts it. The button shows while a command runs, in the bar of the floating + terminal window or at the top right of the terminal when it fills the window, and is disabled once the command is + interrupted. The command's `signal` is aborted, a C++ command receives `webfront.commands.cancel`, a script gets + its grace period, and the command ends with exit code 130 (status `interrupted` in the reports of `wf test`). + The `@webfront/pty` adapter ([PTY](PTY.md)) is a separate terminal and is unchanged: Ctrl+C still sends `^C` to its shell. - **History:** kept per project in `.webfront/developer/history.json` (500 lines), restored by the next terminal. Each line is added to the file as it is, with a conditional publication tried again on conflict, so terminals of several pages on the same project keep each other's lines. A history file that cannot be read is never replaced. - **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. + line without a line break waits on the prompt. Interrupting the command drops the keys still waiting. - **Completion (Tab):** command names, `wf` subcommands, the manifest's scripts after `wf run`, the installed packages after `wf why` and `wf info`, its entries and 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. +- **Exit codes:** a failed command prints `Error: `, with `(exit code N)` when N is not 1. An interruption gives 130. - **Output streams** while a command runs, for `wf` and C++ commands alike, without a size limit: C++ output is sent in pieces below the 65,535-byte limit of bridge strings. @@ -700,10 +711,10 @@ of its browser with `webfront.commands.start`. In C++, the command is spawned li - `context.write(text)` streams output with fire-and-forget calls; `co_await context.print(text)` sends it piece by piece and, after each piece, suspends the command while more than 32 frames wait for a browser that reads slower - (`ui.writesAtMost`, woken by the write that drains the queue); each wait is a point where Ctrl+C stops it. + (`ui.writesAtMost`, woken by the write that drains the queue); each wait is a point where an interruption stops it. `context.args()` holds the words after the command name, split like a shell line; `context.exit(code)` sets the exit code. A command that returns once asked to stop reports 130, whatever it returned. -- Ctrl+C sends `webfront.commands.cancel`: the command's stop token is requested, which the senders it awaits +- An interruption sends `webfront.commands.cancel`: the command's stop token is requested, which the senders it awaits observe (`ui.resumeAfter`, `ui.jsFunctionSender`, ...); loops check `context.stopRequested()`. The terminal does not wait for the command to end: the prompt returns at once and the next command runs, while the first one unwinds. Its late output and exit report are ignored. @@ -733,7 +744,7 @@ Publication replaces the directory only after every entry succeeds. Build output 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. +and keeps running until it is interrupted (Escape or the Stop button). It reuses one compiler Worker and esbuild context across rebuilds. At startup only a missing project or an omitted entry that cannot be selected ends the command with exit code 1 and restores the terminal prompt. Any other error (an unreadable or malformed manifest or lock, a compilation error, including a failed first build) keeps the watcher running so that editing the inputs can recover. @@ -752,7 +763,7 @@ the next poll; polling can miss a change that is reverted completely between rea 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 +Fixing the source resumes rebuilding and clears the overlay. An interruption ends it 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. @@ -785,7 +796,7 @@ and integrity. Nothing else is needed, and no public network once the package is spec can call `webFront.cppFunction`). The runner page, Jasmine and everything the specs built (JS, CSS imported by a spec, assets) are published to a directory of the run's own, `.webfront/developer/test//`, and served by the developer HTTP provider; two sessions on a project never run each other's specs. The files are removed when the run ends (an empty directory - remains) and the frame is removed at the end, on a time limit and on Ctrl+C. + remains) and the frame is removed at the end, on a time limit and on an interruption. - `pattern` keeps the specs whose full name (suites and spec names) contains it; the others count as filtered out. The order is fixed: no random shuffling. - The terminal shows `.`, `F` and `*` (passed, failed, pending) as specs end, then a summary line (`PASSED: 3 specs, @@ -794,17 +805,17 @@ and integrity. Nothing else is needed, and no public network once the package is - Exit codes: 0 when every executed spec passed; 1 for a failed spec, a failure outside the specs, an unhandled asynchronous exception or rejection (Jasmine reports both as failures), a spec file that does not build or load, `fit`/`fdescribe`, and a run that executed nothing (no specs, or a pattern matching none); 124 at the time limit - (`--timeout`, default 60 s, 1 to 3600, covering the build and the publication as well as the run, and never later than the `--timeout` of a `wf run` script that runs `wf test`); 130 on Ctrl+C, at any step. Jasmine's own per-spec timeout (5 s by default) still ends a + (`--timeout`, default 60 s, 1 to 3600, covering the build and the publication as well as the run, and never later than the `--timeout` of a `wf run` script that runs `wf test`); 130 on an interruption, at any step. Jasmine's own per-spec timeout (5 s by default) still ends a spec that never completes, which fails. - A synchronous infinite loop in a spec blocks the page that hosts the frame, as it would in any same-origin frame: - the time limit cannot fire. Use asynchronous waits, which the time limit and Ctrl+C do stop. + the time limit cannot fire. Use asynchronous waits, which the time limit and an interruption do stop. The result sent to C++ is cut to 60,000 bytes when it is larger (a bridge string holds 65,535): the output first, then stack frames, messages and the lists, never the counts or the status; `truncated` is then `true`. The report is structured: `{status, exitCode, total, passed, failed, pending, excluded, durationMs, jasmine, failures: [{name, messages: [{message, stack}]}], pendingSpecs, suites, global, incomplete}`, bounded (100 failures, 8 messages of 16 KiB each per spec). `status` is `passed`, `failed`, `incomplete`, `error` (the specs did not load), `timeout` or `interrupted`. -A run stopped at the time limit or by Ctrl+C once its frame was in the page also has `stage: {reached, specs, current, suite, +A run stopped at the time limit or by an interruption once its frame was in the page also has `stage: {reached, specs, current, suite, loaded, missing}`, which its message repeats: the last step the runner reached (`page requested` when it never started, `runner started`, `bridge settled`, `specs loaded`, `specs running`, `between specs` in a suite's hook or after a spec), the specs it finished, the spec in progress or the innermost suite whose hooks run, and @@ -1015,7 +1026,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, Ctrl+C, non-interactive report to C++), build without navigation, incremental dev reload/error/recovery/Ctrl+C, 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) 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/DEVELOPING_WITH_AGENTS.md b/docs/DEVELOPING_WITH_AGENTS.md index 0bd8c509..11a63bde 100644 --- a/docs/DEVELOPING_WITH_AGENTS.md +++ b/docs/DEVELOPING_WITH_AGENTS.md @@ -72,7 +72,7 @@ declare `"entries": {"main": "ui/main.ts"}`; the rest of the loop is the same. wf create app # writes ui/main.ts, ui/style.css and ui/AGENTS.md; never replaces an existing ui/ wf init # writes webfront.project.json, the manifest every other command reads wf install # only when the interface imports npm packages (wf create lists the starter's) -wf dev ui/main.ts # builds, shows the interface in the window and rebuilds on every save; Ctrl+C stops it +wf dev ui/main.ts # builds, shows the interface in the window and rebuilds on every save; Escape or the Stop button stops it wf check # type check: needs tsconfig.json and `wf install typescript` wf test # the Jasmine specs of "test": {"specs": [...]}: needs `wf install jasmine-core` wf build # compiles the manifest's entries once diff --git a/docs/TEST_TIERS.md b/docs/TEST_TIERS.md index 2a28ac25..3927cce8 100644 --- a/docs/TEST_TIERS.md +++ b/docs/TEST_TIERS.md @@ -78,8 +78,8 @@ command. The window of `DeveloperBrowserIntegration` also shows, in place of its run with its outcome and duration, as if it had been typed. Only the `wf` subcommand is shown, never an argument, an option value or a path. A failed command appears as `rejected`, with its exit code when it has one, whether or not the spec expected the refusal. A wait is labelled `timeout (expected)` only for a time limit the spec announces and fires, -and `cancelled (expected)` only when the spec pressed Ctrl+C; any other time limit or cancellation appears as `timeout` -or `cancelled`. This trace comes from the specs (`test/web/developer-specs.mjs`), not from the published environment. +and `cancelled (expected)` only when the spec interrupted the command (aborted its signal); any other time limit or +cancellation appears as `timeout` or `cancelled`. This trace comes from the specs (`test/web/developer-specs.mjs`), not from the published environment. ## A quick local build by default diff --git a/include/webfront/Commands.hpp b/include/webfront/Commands.hpp index 86602192..8032d595 100644 --- a/include/webfront/Commands.hpp +++ b/include/webfront/Commands.hpp @@ -8,7 +8,8 @@ // LLM: public API; read the command contract and reserved names before the registration code // Terminal commands of an application: coroutines that the developer environment's terminal discovers and -// runs, one browser session at a time, streaming their output and cancelled by Ctrl+C, a disconnection or shutdown. +// runs, one browser session at a time, streaming their output and cancelled by an interruption (Escape or the +// terminal's Stop button), a disconnection or shutdown. #pragma once @@ -49,7 +50,8 @@ inline constexpr std::size_t maxChunkBytes = 60000; /// Frames that print() lets wait for the network before it suspends the command. inline constexpr std::size_t maxPendingOutput = 32; -/// Exit code of a command stopped by Ctrl+C, a disconnection or the application's shutdown. +/// Exit code of a command stopped by an interruption (Escape or the terminal's Stop button), a disconnection or the +/// application's shutdown. inline constexpr int interruptedExitCode = 130; /// Names the terminal itself handles, which an application cannot register: wf, the terminal's own commands (help, @@ -157,8 +159,8 @@ class Context { /// Writes like write(), one piece at a time: after each piece, the command is suspended while more than /// maxPendingOutput frames wait for a browser that reads slower than the command writes. Each wait is a point where - /// Ctrl+C stops the command. Prefer it to write() for large or unbounded output. The returned task does not need - /// this Context: it may be awaited after it is gone. + /// an interruption stops the command. Prefer it to write() for large or unbounded output. The returned task does not + /// need this Context: it may be awaited after it is gone. [[nodiscard]] Task print(std::string text) const { return printPieces(run, std::move(text)); } @@ -168,7 +170,7 @@ class Context { run->exitCode = code; } - /// True once Ctrl+C, a disconnection or the application's shutdown asked the command to stop. Awaited senders + /// True once an interruption, a disconnection or the application's shutdown asked the command to stop. Awaited senders /// observe it themselves; loops that do not await check it. [[nodiscard]] bool stopRequested() const noexcept { return run->stop.stop_requested(); @@ -252,7 +254,8 @@ class Registry : public std::enable_shared_from_this> { } } - /// Ctrl+C: asks the command to stop. The browser no longer waits for it; a command that already ended is ignored. + /// An interruption (Escape or the terminal's Stop button): asks the command to stop. The browser no longer waits for + /// it; a command that already ended is ignored. void cancel(const UI& ui, std::uint32_t id) { std::optional handle; { @@ -334,7 +337,7 @@ class Registry : public std::enable_shared_from_this> { static Task execute(std::weak_ptr registry, std::shared_ptr handler, std::shared_ptr> run) { const auto taskStop = co_await ex::read_env(ex::get_stop_token); - // Forwards the task's stop request (Ctrl+C, disconnection, shutdown) to the command's source while it runs. + // Forwards the task's stop request (interruption, disconnection, shutdown) to the command's source while it runs. const ex::stop_callback_for_t, ForwardStop> forward{taskStop, ForwardStop{run.get()}}; bool stopped = false; std::string error; @@ -369,9 +372,10 @@ class Registry : public std::enable_shared_from_this> { /// `webfront::Task(webfront::commands::Context)`, spawned on the server thread like ui.spawn: /// - it streams its output with Context::write, never through one blocking reply; co_await Context::print also waits /// while a slow browser has not read the output; -/// - Ctrl+C in the terminal, the browser's disconnection or the application's shutdown requests its stop, which the -/// senders it awaits observe (ui.resumeAfter, ui.jsFunctionSender, ...). The terminal does not wait for a stopped -/// command: its late output and exit report are ignored, and the next command can start at once; +/// - an interruption in the terminal (Escape or its Stop button), the browser's disconnection or the application's +/// shutdown requests its stop, which the senders it awaits observe (ui.resumeAfter, ui.jsFunctionSender, ...). The +/// terminal does not wait for a stopped command: its late output and exit report are ignored, and the next command +/// can start at once; /// - an exception it throws is shown as an error in the terminal, with exit code 1. /// A command must not block the server thread, which serves every browser: synchronous handlers are refused at /// compile time, and long computations belong on another thread. Create one Commands object per application (a second diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 78dc1622..e470124f 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -5,24 +5,24 @@ "js/developer/environment/installer.mjs": "1159404b151dc8c580d9a155a9ec0dfa3fcb6a8e073d8586d29b329ce91b741b", "js/developer/environment/restore.mjs": "cdd22eebd55d68bd705685cd5ee3059e228a35053eaad116ab99c4c05b908098", "js/developer/environment/cache.mjs": "6fd0e3b760dfc1070a28e2e2eb3c86621c970c775045e7a9ae665da4f6845922", - "js/developer/environment/scripts.mjs": "6b61d7cdbf766d7c54f1888b7e9c75ca0154ff2c7afc0f574e941540b0801ed3", + "js/developer/environment/scripts.mjs": "bf4d3998635ecc197a4f4ff39ce71625c3f52d51dbf8a5294f2d3b8ceeaa677b", "js/developer/environment/script-worker.mjs": "b50ddfddf696720ab0b1958c0bd327ac3a9004f37cc0aa439a9ad536fd11ac92", "js/developer/environment/permissions.mjs": "ed785d6608ff31037579e130d30a3a45049b8b86040eccfa5717ecb493c8809e", "js/developer/environment/typecheck.mjs": "e850f020f798be0eab99cb30457e43ff775ac45e56cfe9ce206f69902e92cde1", "js/developer/environment/typecheck-snapshot.mjs": "ec2336781df84bf8a739d578437a0ff737478d3ca57fecf534f18e699487ec94", - "js/developer/environment/typecheck-worker.mjs": "9f89315a8f7dcb2a19141c321a79aa47eabefdf60d05c60d39016663f1bafecd", + "js/developer/environment/typecheck-worker.mjs": "3e04316e137dea09989b86a6348f35d57b3cd1db8c36c843bf04dea0cf2c9cb8", "js/developer/environment/packages-entry.mjs": "e0b4acd4330b8b51eb0e695384c8df2b103a4be4f598ac83277838022f747e30", "js/developer/environment/bootstrap.mjs": "e0a42c5cdaede1f32b34d6c4df64f2cade3b0ef10d74284461b101f4b5cb6cb8", "js/developer/environment/bootstrap-entry.mjs": "ca066f5ea08a298544feb30b920f3bc8ad41658332728c5395843ffd23f89ec3", "js/developer/environment/packages.mjs": "37fe2a410e211264cfeaedbff3df50f7e62b02f8088130127d94f92081e2a5ad", "js/developer/environment/starter.mjs": "fd43db1861121577c48a0327436ce39cb9076d7cad0e9e273d40955747cc6a48", "js/developer/environment/paths.mjs": "3b6114df78eb193161c5c84499dda084cb7ff91c56a4496371c30295d00880e3", - "js/developer/environment/runtime.mjs": "1b5f0bfc5964b902725a4c765d83db0644cdad91a8f07d8bf6a3bbd0f550c1eb", + "js/developer/environment/runtime.mjs": "65c3025781f37c18d32fb4fce99abee45180df0f2c33cdaac0fa84d0a75e9fba", "js/developer/environment/automation.mjs": "773dcca7b8847c11670995f759c218c86af95a29ea46b44f350f79c4b71a143c", - "js/developer/environment/development.mjs": "1f32f911610c72ad3e935de1c2b138fa275ce9eda04bb63c824d5e09923305a6", - "js/developer/environment/testing.mjs": "48695dc7c368d5f0671a0549a61d06c732e10604c56e98f7254f3c4dd21a792c", - "js/developer/environment/terminal.mjs": "e7c3ca8f9833f10e07939277996eb01fb989c986420c96052271ff469fa59062", - "js/developer/environment/workspace.mjs": "e82ec4df21ffb2b112550e0212504aba05af4f924b5645c0712f40f8466257fc", + "js/developer/environment/development.mjs": "29097775f382354e4a0269827754646d293c5c526db4426a760a01a581db96f2", + "js/developer/environment/testing.mjs": "e3826c275c3ce75decc2ff63a7152c472811c5497e6d348cc5ea0073b2846a4f", + "js/developer/environment/terminal.mjs": "3b4dd07636fde64f12d350cc857573232da089fb9c889bf5d917a52f32185811", + "js/developer/environment/workspace.mjs": "978caa51b393c0cd3f92c97a3ed5925274717c1d7403506703fd2face0ac8fe0", "js/developer/environment/menu.mjs": "a1703bf927058f8641b82c469335fd430a723880a336e16dfbd3a8296287b7fa", "js/developer/environment/inspector-host.mjs": "4b48bd862cc369ba006990303393ca861e2164627013f464f00de9ac893777ea", "js/developer/environment/inspector.mjs": "eaacc50bffa03a955324a9a3634a1d92afd1c7962bae88cb982b15cf047cb2b3", @@ -32,7 +32,7 @@ "js/developer/environment/inspector-bridge.mjs": "b3f269245870d1a7e126cab5f80b2918164a5c24b3d351015cf52d44bf343cb8", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", - "js/developer/environment/commands.mjs": "a759f48584b78aed79e9965fd202d2ec108a6948ef6f1b8d689fed87a458b265", + "js/developer/environment/commands.mjs": "264dd9246d998f21988bffb1f1b096fc8087e29e66b5e9c4f6345529568c5b51", "js/developer/environment/files.mjs": "199336f7f3d23f6370da352993bf4686738b1f394b79aa9883769d19824540e0", "js/developer/environment/dependencies.mjs": "7f536e30584b10822dea6b5642fd584e5935c58f90a271ee70a03d3023e9dd34", "js/developer/environment/compiler.mjs": "0158931132aa9b43b7bbbd01de6fa4fc34fce8c65515d593dd494930f7a1910f", @@ -57,8 +57,8 @@ "js/developer/tools/archive.mjs": "da63bb9d796ddfd24ed945b15c53f66a0400eb177886fd4f1c8fd10cafb5a91b", "js/developer/tools/distribution.mjs": "43dfdccc912693db46fd095fd78ae79325abab672d99f89fd569914ef3499cad", "js/developer/scripts/build.mjs": "a6b64a8a75c9a30118e7f5c843a0feee89ee1372ccd19b7e468c816b23fd1367", - "js/developer/webfront.project.json": "ac750924271fe5f9c9be27007068ba435ba7d31dd25df656c24a581d2298be0e", + "js/developer/webfront.project.json": "a40e935b904f23e289b3f0a8e27c0dcc3b4529de4c2eba317a3b0544ab259e10", "js/core/bootstrap/bootstrap.bundle.mjs": "18a0567efa928fddbaa3f8d16a4d1e8440f21709ff2e3058d10ba406b2e9b66d", - "js/developer/environment/packages.bundle.mjs": "5598a590a9e859a4128075387a6c32963b2246ca120c2d7775851c780ad437f2", + "js/developer/environment/packages.bundle.mjs": "42bae05e30369e1be5c28f28860b1e1d8cfc34ab1239cbb396fbc7ddb259d456", "include/webfront/system/DeveloperReleaseData.hpp": "666e13d0625154a247f44bbf85c6f06259b459480d1b7eaf7486b166ecbcc22c" } diff --git a/js/developer/environment/commands.mjs b/js/developer/environment/commands.mjs index 5509321d..d7387f38 100644 --- a/js/developer/environment/commands.mjs +++ b/js/developer/environment/commands.mjs @@ -1,5 +1,5 @@ // The application's C++ commands (webfront::Commands): discovered through the bridge and run in this browser's session. -// Their output streams in through fire-and-forget calls; Ctrl+C cancels them in C++ without waiting for them to end. +// Their output streams in through fire-and-forget calls; an interruption cancels them in C++ without waiting for them to end. /** * Names the terminal itself handles; webfront::commands::reservedNames refuses them to C++ commands. After wf and the @@ -77,7 +77,7 @@ export function runCommand(bridge, name, args, {signal, write = () => {}} = {}) finish(); reject(error); }; - // The start is sent now, before any cancel that Ctrl+C sends; a bridge that throws instead of rejecting must + // The start is sent now, before any cancel that an interruption sends; a bridge that throws instead of rejecting must // not leave the command registered. try { bridge.cppFunction('webfront.commands.start')(id, name, JSON.stringify(args)).catch(failed); } catch (error) { failed(error); } diff --git a/js/developer/environment/development.mjs b/js/developer/environment/development.mjs index a01cf49f..576773bd 100644 --- a/js/developer/environment/development.mjs +++ b/js/developer/environment/development.mjs @@ -229,14 +229,14 @@ export async function dev(args, {bridge, signal, preview: frame, write = () => { const files = await session.rebuild({entry, lock: project.lock ?? {format: 1, roots: {}, packages: {}}}); files.set('index.html', previewPage(files)); await publish(bridge, '.webfront/developer/preview', files, {signal: active}); - // Once commit succeeds, display its publication even if Ctrl+C arrived while awaiting it. + // Once commit succeeds, display its publication even if an interruption 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); report('ready'); - write(syncNotice(project) + 'Preview ready. Watching inputs (Ctrl+C to stop).\n'); + write(syncNotice(project) + 'Preview ready. Watching inputs (Escape or the Stop button ends wf dev).\n'); }); } catch (error) { if (active.aborted) throw stopped(); diff --git a/js/developer/environment/packages.bundle.mjs b/js/developer/environment/packages.bundle.mjs index e018908f..2235ed65 100644 --- a/js/developer/environment/packages.bundle.mjs +++ b/js/developer/environment/packages.bundle.mjs @@ -1,5 +1,5 @@ -var Xn=Object.create;var gt=Object.defineProperty;var Vn=Object.getOwnPropertyDescriptor;var Bn=Object.getOwnPropertyNames;var Hn=Object.getPrototypeOf,Kn=Object.prototype.hasOwnProperty;var w=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Yn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Bn(t))!Kn.call(e,s)&&s!==r&>(e,s,{get:()=>t[s],enumerable:!(n=Vn(t,s))||n.enumerable});return e};var F=(e,t,r)=>(r=e!=null?Xn(Hn(e)):{},Yn(t||!e||!e.__esModule?gt(r,"default",{value:e,enumerable:!0}):r,e));var X=w((bc,Ot)=>{"use strict";var rs="2.0.0",ns=Number.MAX_SAFE_INTEGER||9007199254740991,ss=16,os=250,is=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Ot.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:ss,MAX_SAFE_BUILD_LENGTH:os,MAX_SAFE_INTEGER:ns,RELEASE_TYPES:is,SEMVER_SPEC_VERSION:rs,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var V=w((Oc,vt)=>{"use strict";var as=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};vt.exports=as});var z=w((j,It)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:je,MAX_SAFE_BUILD_LENGTH:cs,MAX_LENGTH:ls}=X(),us=V();j=It.exports={};var fs=j.re=[],ps=j.safeRe=[],p=j.src=[],hs=j.safeSrc=[],h=j.t={},ds=0,Pe="[a-zA-Z0-9-]",ms=[["\\s",1],["\\d",ls],[Pe,cs]],ws=e=>{for(let[t,r]of ms)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let n=ws(t),s=ds++;us(e,s,t),h[e]=s,p[s]=t,hs[s]=n,fs[s]=new RegExp(t,r?"g":void 0),ps[s]=new RegExp(n,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Pe}*`);E("MAINVERSION",`(${p[h.NUMERICIDENTIFIER]})\\.(${p[h.NUMERICIDENTIFIER]})\\.(${p[h.NUMERICIDENTIFIER]})`);E("MAINVERSIONLOOSE",`(${p[h.NUMERICIDENTIFIERLOOSE]})\\.(${p[h.NUMERICIDENTIFIERLOOSE]})\\.(${p[h.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASEIDENTIFIER",`(?:${p[h.NONNUMERICIDENTIFIER]}|${p[h.NUMERICIDENTIFIER]})`);E("PRERELEASEIDENTIFIERLOOSE",`(?:${p[h.NONNUMERICIDENTIFIER]}|${p[h.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASE",`(?:-(${p[h.PRERELEASEIDENTIFIER]}(?:\\.${p[h.PRERELEASEIDENTIFIER]})*))`);E("PRERELEASELOOSE",`(?:-?(${p[h.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${p[h.PRERELEASEIDENTIFIERLOOSE]})*))`);E("BUILDIDENTIFIER",`${Pe}+`);E("BUILD",`(?:\\+(${p[h.BUILDIDENTIFIER]}(?:\\.${p[h.BUILDIDENTIFIER]})*))`);E("FULLPLAIN",`v?${p[h.MAINVERSION]}${p[h.PRERELEASE]}?${p[h.BUILD]}?`);E("FULL",`^${p[h.FULLPLAIN]}$`);E("LOOSEPLAIN",`[v=\\s]*${p[h.MAINVERSIONLOOSE]}${p[h.PRERELEASELOOSE]}?${p[h.BUILD]}?`);E("LOOSE",`^${p[h.LOOSEPLAIN]}$`);E("GTLT","((?:<|>)?=?)");E("XRANGEIDENTIFIERLOOSE",`${p[h.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);E("XRANGEIDENTIFIER",`${p[h.NUMERICIDENTIFIER]}|x|X|\\*`);E("XRANGEPLAIN",`[v=\\s]*(${p[h.XRANGEIDENTIFIER]})(?:\\.(${p[h.XRANGEIDENTIFIER]})(?:\\.(${p[h.XRANGEIDENTIFIER]})(?:${p[h.PRERELEASE]})?${p[h.BUILD]}?)?)?`);E("XRANGEPLAINLOOSE",`[v=\\s]*(${p[h.XRANGEIDENTIFIERLOOSE]})(?:\\.(${p[h.XRANGEIDENTIFIERLOOSE]})(?:\\.(${p[h.XRANGEIDENTIFIERLOOSE]})(?:${p[h.PRERELEASELOOSE]})?${p[h.BUILD]}?)?)?`);E("XRANGE",`^${p[h.GTLT]}\\s*${p[h.XRANGEPLAIN]}$`);E("XRANGELOOSE",`^${p[h.GTLT]}\\s*${p[h.XRANGEPLAINLOOSE]}$`);E("COERCEPLAIN",`(^|[^\\d])(\\d{1,${je}})(?:\\.(\\d{1,${je}}))?(?:\\.(\\d{1,${je}}))?`);E("COERCE",`${p[h.COERCEPLAIN]}(?:$|[^\\d])`);E("COERCEFULL",p[h.COERCEPLAIN]+`(?:${p[h.PRERELEASE]})?(?:${p[h.BUILD]})?(?:$|[^\\d])`);E("COERCERTL",p[h.COERCE],!0);E("COERCERTLFULL",p[h.COERCEFULL],!0);E("LONETILDE","(?:~>?)");E("TILDETRIM",`(\\s*)${p[h.LONETILDE]}\\s+`,!0);j.tildeTrimReplace="$1~";E("TILDE",`^${p[h.LONETILDE]}${p[h.XRANGEPLAIN]}$`);E("TILDELOOSE",`^${p[h.LONETILDE]}${p[h.XRANGEPLAINLOOSE]}$`);E("LONECARET","(?:\\^)");E("CARETTRIM",`(\\s*)${p[h.LONECARET]}\\s+`,!0);j.caretTrimReplace="$1^";E("CARET",`^${p[h.LONECARET]}${p[h.XRANGEPLAIN]}$`);E("CARETLOOSE",`^${p[h.LONECARET]}${p[h.XRANGEPLAINLOOSE]}$`);E("COMPARATORLOOSE",`^${p[h.GTLT]}\\s*(${p[h.LOOSEPLAIN]})$|^$`);E("COMPARATOR",`^${p[h.GTLT]}\\s*(${p[h.FULLPLAIN]})$|^$`);E("COMPARATORTRIM",`(\\s*)${p[h.GTLT]}\\s*(${p[h.LOOSEPLAIN]}|${p[h.XRANGEPLAIN]})`,!0);j.comparatorTrimReplace="$1$2$3";E("HYPHENRANGE",`^\\s*(${p[h.XRANGEPLAIN]})\\s+-\\s+(${p[h.XRANGEPLAIN]})\\s*$`);E("HYPHENRANGELOOSE",`^\\s*(${p[h.XRANGEPLAINLOOSE]})\\s+-\\s+(${p[h.XRANGEPLAINLOOSE]})\\s*$`);E("STAR","(<|>)?=?\\s*\\*");E("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");E("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var ae=w((vc,St)=>{"use strict";var Es=Object.freeze({loose:!0}),gs=Object.freeze({}),ys=e=>e?typeof e!="object"?Es:e:gs;St.exports=ys});var qe=w((Ic,Lt)=>{"use strict";var kt=/^[0-9]+$/,Nt=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:eNt(t,e);Lt.exports={compareIdentifiers:Nt,rcompareIdentifiers:$s}});var b=w((Sc,Tt)=>{"use strict";var ce=V(),{MAX_LENGTH:At,MAX_SAFE_INTEGER:le}=X(),{safeRe:ue,t:fe}=z(),xs=ae(),{compareIdentifiers:Ce}=qe(),De=class e{constructor(t,r){if(r=xs(r),t instanceof e){if(t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease)return t;t=t.version}else if(typeof t!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>At)throw new TypeError(`version is longer than ${At} characters`);ce("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?ue[fe.LOOSE]:ue[fe.FULL]);if(!n)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>le||this.major<0)throw new TypeError("Invalid major version");if(this.minor>le||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>le||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let o=+s;if(o>=0&&ot.major?1:this.minort.minor?1:this.patcht.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let n=this.prerelease[r],s=t.prerelease[r];if(ce("prerelease compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Ce(n,s)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let n=this.build[r],s=t.build[r];if(ce("build compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Ce(n,s)}while(++r)}inc(t,r,n){if(t.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let s=`-${r}`.match(this.options.loose?ue[fe.PRERELEASELOOSE]:ue[fe.PRERELEASE]);if(!s||s[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let s=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[s];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(r){let o=[r,s];n===!1&&(o=[r]),Ce(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=o):this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Tt.exports=De});var q=w((kc,Pt)=>{"use strict";var jt=b(),Rs=(e,t,r=!1)=>{if(e instanceof jt)return e;try{return new jt(e,t)}catch(n){if(!r)return null;throw n}};Pt.exports=Rs});var Ct=w((Nc,qt)=>{"use strict";var bs=q(),Os=(e,t)=>{let r=bs(e,t);return r?r.version:null};qt.exports=Os});var Ut=w((Lc,Dt)=>{"use strict";var vs=q(),Is=(e,t)=>{let r=vs(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};Dt.exports=Is});var Gt=w((Ac,zt)=>{"use strict";var Ft=b(),Ss=(e,t,r,n,s)=>{typeof r=="string"&&(s=n,n=r,r=void 0);try{return new Ft(e instanceof Ft?e.version:e,r).inc(t,n,s).version}catch{return null}};zt.exports=Ss});var _t=w((Tc,Wt)=>{"use strict";var Mt=q(),ks=(e,t)=>{let r=Mt(e,null,!0),n=Mt(t,null,!0),s=r.compare(n);if(s===0)return null;let o=s>0,i=o?r:n,c=o?n:r,a=!!i.prerelease.length;if(!!c.prerelease.length&&!a){if(!c.patch&&!c.minor)return"major";if(c.compareMain(i)===0)return c.minor&&!c.patch?"minor":"patch"}let u=a?"pre":"";return r.major!==n.major?u+"major":r.minor!==n.minor?u+"minor":r.patch!==n.patch?u+"patch":"prerelease"};Wt.exports=ks});var Vt=w((jc,Xt)=>{"use strict";var Ns=b(),Ls=(e,t)=>new Ns(e,t).major;Xt.exports=Ls});var Ht=w((Pc,Bt)=>{"use strict";var As=b(),Ts=(e,t)=>new As(e,t).minor;Bt.exports=Ts});var Yt=w((qc,Kt)=>{"use strict";var js=b(),Ps=(e,t)=>new js(e,t).patch;Kt.exports=Ps});var Zt=w((Cc,Jt)=>{"use strict";var qs=q(),Cs=(e,t)=>{let r=qs(e,t);return r&&r.prerelease.length?r.prerelease:null};Jt.exports=Cs});var N=w((Dc,er)=>{"use strict";var Qt=b(),Ds=(e,t,r)=>new Qt(e,r).compare(new Qt(t,r));er.exports=Ds});var rr=w((Uc,tr)=>{"use strict";var Us=N(),Fs=(e,t,r)=>Us(t,e,r);tr.exports=Fs});var sr=w((Fc,nr)=>{"use strict";var zs=N(),Gs=(e,t)=>zs(e,t,!0);nr.exports=Gs});var pe=w((zc,ir)=>{"use strict";var or=b(),Ms=(e,t,r)=>{let n=new or(e,r),s=new or(t,r);return n.compare(s)||n.compareBuild(s)};ir.exports=Ms});var cr=w((Gc,ar)=>{"use strict";var Ws=pe(),_s=(e,t)=>e.sort((r,n)=>Ws(r,n,t));ar.exports=_s});var ur=w((Mc,lr)=>{"use strict";var Xs=pe(),Vs=(e,t)=>e.sort((r,n)=>Xs(n,r,t));lr.exports=Vs});var B=w((Wc,fr)=>{"use strict";var Bs=N(),Hs=(e,t,r)=>Bs(e,t,r)>0;fr.exports=Hs});var he=w((_c,pr)=>{"use strict";var Ks=N(),Ys=(e,t,r)=>Ks(e,t,r)<0;pr.exports=Ys});var Ue=w((Xc,hr)=>{"use strict";var Js=N(),Zs=(e,t,r)=>Js(e,t,r)===0;hr.exports=Zs});var Fe=w((Vc,dr)=>{"use strict";var Qs=N(),eo=(e,t,r)=>Qs(e,t,r)!==0;dr.exports=eo});var de=w((Bc,mr)=>{"use strict";var to=N(),ro=(e,t,r)=>to(e,t,r)>=0;mr.exports=ro});var me=w((Hc,wr)=>{"use strict";var no=N(),so=(e,t,r)=>no(e,t,r)<=0;wr.exports=so});var ze=w((Kc,Er)=>{"use strict";var oo=Ue(),io=Fe(),ao=B(),co=de(),lo=he(),uo=me(),fo=(e,t,r,n)=>{switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return oo(e,r,n);case"!=":return io(e,r,n);case">":return ao(e,r,n);case">=":return co(e,r,n);case"<":return lo(e,r,n);case"<=":return uo(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};Er.exports=fo});var yr=w((Yc,gr)=>{"use strict";var po=b(),ho=q(),{safeRe:we,t:Ee}=z(),mo=(e,t)=>{if(e instanceof po)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};let r=null;if(!t.rtl)r=e.match(t.includePrerelease?we[Ee.COERCEFULL]:we[Ee.COERCE]);else{let a=t.includePrerelease?we[Ee.COERCERTLFULL]:we[Ee.COERCERTL],l;for(;(l=a.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||l.index+l[0].length!==r.index+r[0].length)&&(r=l),a.lastIndex=l.index+l[1].length+l[2].length;a.lastIndex=-1}if(r===null)return null;let n=r[2],s=r[3]||"0",o=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",c=t.includePrerelease&&r[6]?`+${r[6]}`:"";return ho(`${n}.${s}.${o}${i}${c}`,t)};gr.exports=mo});var xr=w((Jc,$r)=>{"use strict";var Ge=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let s=this.map.keys().next().value;this.delete(s)}this.map.set(t,r)}return this}};$r.exports=Ge});var L=w((Zc,vr)=>{"use strict";var wo=/\s+/g,Me=class e{constructor(t,r){if(r=go(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof We)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(wo," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(s=>!br(s[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&vo(s[0])){this.set=[s];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t0&&(this.formatted+="||");let r=this.set[t];for(let n=0;n0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){let n=((this.options.includePrerelease&&bo)|(this.options.loose&&Oo))+":"+t,s=Rr.get(n);if(s)return s;let o=this.options.loose,i=o?v[O.HYPHENRANGELOOSE]:v[O.HYPHENRANGE];t=t.replace(i,qo(this.options.includePrerelease)),g("hyphen replace",t),t=t.replace(v[O.COMPARATORTRIM],$o),g("comparator trim",t),t=t.replace(v[O.TILDETRIM],xo),g("tilde trim",t),t=t.replace(v[O.CARETTRIM],Ro),g("caret trim",t);let c=t.split(" ").map(f=>Io(f,this.options)).join(" ").split(/\s+/).map(f=>Po(f,this.options));o&&(c=c.filter(f=>(g("loose invalid filter",f,this.options),!!f.match(v[O.COMPARATORLOOSE])))),g("range list",c);let a=new Map,l=c.map(f=>new We(f,this.options));for(let f of l){if(br(f))return[f];a.set(f.value,f)}a.size>1&&a.has("")&&a.delete("");let u=[...a.values()];return Rr.set(n,u),u}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(n=>Or(n,r)&&t.set.some(s=>Or(s,r)&&n.every(o=>s.every(i=>o.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new yo(t,this.options)}catch{return!1}for(let r=0;re.value==="<0.0.0-0",vo=e=>e.value==="",Or=(e,t)=>{let r=!0,n=e.slice(),s=n.pop();for(;r&&n.length;)r=n.every(o=>s.intersects(o,t)),s=n.pop();return r},Io=(e,t)=>(e=e.replace(v[O.BUILD],""),g("comp",e,t),e=No(e,t),g("caret",e),e=So(e,t),g("tildes",e),e=Ao(e,t),g("xrange",e),e=jo(e,t),g("stars",e),e),I=e=>!e||e.toLowerCase()==="x"||e==="*",So=(e,t)=>e.trim().split(/\s+/).map(r=>ko(r,t)).join(" "),ko=(e,t)=>{let r=t.loose?v[O.TILDELOOSE]:v[O.TILDE];return e.replace(r,(n,s,o,i,c)=>{g("tilde",e,n,s,o,i,c);let a;return I(s)?a="":I(o)?a=`>=${s}.0.0 <${+s+1}.0.0-0`:I(i)?a=`>=${s}.${o}.0 <${s}.${+o+1}.0-0`:c?(g("replaceTilde pr",c),a=`>=${s}.${o}.${i}-${c} <${s}.${+o+1}.0-0`):a=`>=${s}.${o}.${i} <${s}.${+o+1}.0-0`,g("tilde return",a),a})},No=(e,t)=>e.trim().split(/\s+/).map(r=>Lo(r,t)).join(" "),Lo=(e,t)=>{g("caret",e,t);let r=t.loose?v[O.CARETLOOSE]:v[O.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(s,o,i,c,a)=>{g("caret",e,s,o,i,c,a);let l;return I(o)?l="":I(i)?l=`>=${o}.0.0${n} <${+o+1}.0.0-0`:I(c)?o==="0"?l=`>=${o}.${i}.0${n} <${o}.${+i+1}.0-0`:l=`>=${o}.${i}.0${n} <${+o+1}.0.0-0`:a?(g("replaceCaret pr",a),o==="0"?i==="0"?l=`>=${o}.${i}.${c}-${a} <${o}.${i}.${+c+1}-0`:l=`>=${o}.${i}.${c}-${a} <${o}.${+i+1}.0-0`:l=`>=${o}.${i}.${c}-${a} <${+o+1}.0.0-0`):(g("no pr"),o==="0"?i==="0"?l=`>=${o}.${i}.${c}${n} <${o}.${i}.${+c+1}-0`:l=`>=${o}.${i}.${c}${n} <${o}.${+i+1}.0-0`:l=`>=${o}.${i}.${c} <${+o+1}.0.0-0`),g("caret return",l),l})},Ao=(e,t)=>(g("replaceXRanges",e,t),e.split(/\s+/).map(r=>To(r,t)).join(" ")),To=(e,t)=>{e=e.trim();let r=t.loose?v[O.XRANGELOOSE]:v[O.XRANGE];return e.replace(r,(n,s,o,i,c,a)=>{g("xRange",e,n,s,o,i,c,a);let l=I(o),u=l||I(i),f=u||I(c),m=f;return s==="="&&m&&(s=""),a=t.includePrerelease?"-0":"",l?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&m?(u&&(i=0),c=0,s===">"?(s=">=",u?(o=+o+1,i=0,c=0):(i=+i+1,c=0)):s==="<="&&(s="<",u?o=+o+1:i=+i+1),s==="<"&&(a="-0"),n=`${s+o}.${i}.${c}${a}`):u?n=`>=${o}.0.0${a} <${+o+1}.0.0-0`:f&&(n=`>=${o}.${i}.0${a} <${o}.${+i+1}.0-0`),g("xRange return",n),n})},jo=(e,t)=>(g("replaceStars",e,t),e.trim().replace(v[O.STAR],"")),Po=(e,t)=>(g("replaceGTE0",e,t),e.trim().replace(v[t.includePrerelease?O.GTE0PRE:O.GTE0],"")),qo=e=>(t,r,n,s,o,i,c,a,l,u,f,m)=>(I(n)?r="":I(s)?r=`>=${n}.0.0${e?"-0":""}`:I(o)?r=`>=${n}.${s}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,I(l)?a="":I(u)?a=`<${+l+1}.0.0-0`:I(f)?a=`<${l}.${+u+1}.0-0`:m?a=`<=${l}.${u}.${f}-${m}`:e?a=`<${l}.${u}.${+f+1}-0`:a=`<=${a}`,`${r} ${a}`.trim()),Co=(e,t,r)=>{for(let n=0;n0){let s=e[n].semver;if(s.major===t.major&&s.minor===t.minor&&s.patch===t.patch)return!0}return!1}return!0}});var H=w((Qc,Ar)=>{"use strict";var K=Symbol("SemVer ANY"),Ve=class e{static get ANY(){return K}constructor(t,r){if(r=Ir(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Xe("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===K?this.value="":this.value=this.operator+this.semver.version,Xe("comp",this)}parse(t){let r=this.options.loose?Sr[kr.COMPARATORLOOSE]:Sr[kr.COMPARATOR],n=t.match(r);if(!n)throw new TypeError(`Invalid comparator: ${t}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Nr(n[2],this.options.loose):this.semver=K}toString(){return this.value}test(t){if(Xe("Comparator.test",t,this.options.loose),this.semver===K||t===K)return!0;if(typeof t=="string")try{t=new Nr(t,this.options)}catch{return!1}return _e(t,this.operator,this.semver,this.options)}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Lr(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new Lr(this.value,r).test(t.semver):(r=Ir(r),r.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||_e(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||_e(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};Ar.exports=Ve;var Ir=ae(),{safeRe:Sr,t:kr}=z(),_e=ze(),Xe=V(),Nr=b(),Lr=L()});var Y=w((el,Tr)=>{"use strict";var Do=L(),Uo=(e,t,r)=>{try{t=new Do(t,r)}catch{return!1}return t.test(e)};Tr.exports=Uo});var Pr=w((tl,jr)=>{"use strict";var Fo=L(),zo=(e,t)=>new Fo(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));jr.exports=zo});var Cr=w((rl,qr)=>{"use strict";var Go=b(),Mo=L(),Wo=(e,t,r)=>{let n=null,s=null,o=null;try{o=new Mo(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===-1)&&(n=i,s=new Go(n,r))}),n};qr.exports=Wo});var Ur=w((nl,Dr)=>{"use strict";var _o=b(),Xo=L(),Vo=(e,t,r)=>{let n=null,s=null,o=null;try{o=new Xo(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===1)&&(n=i,s=new _o(n,r))}),n};Dr.exports=Vo});var Gr=w((sl,zr)=>{"use strict";var Be=b(),Bo=L(),Fr=B(),Ho=(e,t)=>{e=new Bo(e,t);let r=new Be("0.0.0");if(e.test(r)||(r=new Be("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n{let c=new Be(i.semver.version);switch(i.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!o||Fr(c,o))&&(o=c);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),o&&(!r||Fr(r,o))&&(r=o)}return r&&e.test(r)?r:null};zr.exports=Ho});var Wr=w((ol,Mr)=>{"use strict";var Ko=L(),Yo=(e,t)=>{try{return new Ko(e,t).range||"*"}catch{return null}};Mr.exports=Yo});var ge=w((il,Br)=>{"use strict";var Jo=b(),Vr=H(),{ANY:Zo}=Vr,Qo=L(),ei=Y(),_r=B(),Xr=he(),ti=me(),ri=de(),ni=(e,t,r,n)=>{e=new Jo(e,n),t=new Qo(t,n);let s,o,i,c,a;switch(r){case">":s=_r,o=ti,i=Xr,c=">",a=">=";break;case"<":s=Xr,o=ri,i=_r,c="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(ei(e,t,n))return!1;for(let l=0;l{d.semver===Zo&&(d=new Vr(">=0.0.0")),f=f||d,m=m||d,s(d.semver,f.semver,n)?f=d:i(d.semver,m.semver,n)&&(m=d)}),f.operator===c||f.operator===a||(!m.operator||m.operator===c)&&o(e,m.semver))return!1;if(m.operator===a&&i(e,m.semver))return!1}return!0};Br.exports=ni});var Kr=w((al,Hr)=>{"use strict";var si=ge(),oi=(e,t,r)=>si(e,t,">",r);Hr.exports=oi});var Jr=w((cl,Yr)=>{"use strict";var ii=ge(),ai=(e,t,r)=>ii(e,t,"<",r);Yr.exports=ai});var en=w((ll,Qr)=>{"use strict";var Zr=L(),ci=(e,t,r)=>(e=new Zr(e,r),t=new Zr(t,r),e.intersects(t,r));Qr.exports=ci});var rn=w((ul,tn)=>{"use strict";var li=Y(),ui=N();tn.exports=(e,t,r)=>{let n=[],s=null,o=null,i=e.sort((u,f)=>ui(u,f,r));for(let u of i)li(u,t,r)?(o=u,s||(s=u)):(o&&n.push([s,o]),o=null,s=null);s&&n.push([s,null]);let c=[];for(let[u,f]of n)u===f?c.push(u):!f&&u===i[0]?c.push("*"):f?u===i[0]?c.push(`<=${f}`):c.push(`${u} - ${f}`):c.push(`>=${u}`);let a=c.join(" || "),l=typeof t.raw=="string"?t.raw:String(t);return a.length{"use strict";var nn=L(),Ke=H(),{ANY:He}=Ke,J=Y(),Ye=N(),fi=(e,t,r={})=>{if(e===t)return!0;e=new nn(e,r),t=new nn(t,r);let n=!1;e:for(let s of e.set){for(let o of t.set){let i=hi(s,o,r);if(n=n||i!==null,i)continue e}if(n)return!1}return!0},pi=[new Ke(">=0.0.0-0")],sn=[new Ke(">=0.0.0")],hi=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===He){if(t.length===1&&t[0].semver===He)return!0;r.includePrerelease?e=pi:e=sn}if(t.length===1&&t[0].semver===He){if(r.includePrerelease)return!0;t=sn}let n=new Set,s,o;for(let d of e)d.operator===">"||d.operator===">="?s=on(s,d,r):d.operator==="<"||d.operator==="<="?o=an(o,d,r):n.add(d.semver);if(n.size>1)return null;let i;if(s&&o){if(i=Ye(s.semver,o.semver,r),i>0)return null;if(i===0&&(s.operator!==">="||o.operator!=="<="))return null}for(let d of n){if(s&&!J(d,String(s),r)||o&&!J(d,String(o),r))return null;for(let T of t)if(!J(d,String(T),r))return!1;return!0}let c,a,l,u,f=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:!1,m=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1;f&&f.prerelease.length===1&&o.operator==="<"&&f.prerelease[0]===0&&(f=!1);for(let d of t){if(u=u||d.operator===">"||d.operator===">=",l=l||d.operator==="<"||d.operator==="<=",s){if(m&&d.semver.prerelease&&d.semver.prerelease.length&&d.semver.major===m.major&&d.semver.minor===m.minor&&d.semver.patch===m.patch&&(m=!1),d.operator===">"||d.operator===">="){if(c=on(s,d,r),c===d&&c!==s)return!1}else if(s.operator===">="&&!J(s.semver,String(d),r))return!1}if(o){if(f&&d.semver.prerelease&&d.semver.prerelease.length&&d.semver.major===f.major&&d.semver.minor===f.minor&&d.semver.patch===f.patch&&(f=!1),d.operator==="<"||d.operator==="<="){if(a=an(o,d,r),a===d&&a!==o)return!1}else if(o.operator==="<="&&!J(o.semver,String(d),r))return!1}if(!d.operator&&(o||s)&&i!==0)return!1}return!(s&&l&&!o&&i!==0||o&&u&&!s&&i!==0||m||f)},on=(e,t,r)=>{if(!e)return t;let n=Ye(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},an=(e,t,r)=>{if(!e)return t;let n=Ye(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};cn.exports=fi});var C=w((pl,pn)=>{"use strict";var Je=z(),un=X(),di=b(),fn=qe(),mi=q(),wi=Ct(),Ei=Ut(),gi=Gt(),yi=_t(),$i=Vt(),xi=Ht(),Ri=Yt(),bi=Zt(),Oi=N(),vi=rr(),Ii=sr(),Si=pe(),ki=cr(),Ni=ur(),Li=B(),Ai=he(),Ti=Ue(),ji=Fe(),Pi=de(),qi=me(),Ci=ze(),Di=yr(),Ui=H(),Fi=L(),zi=Y(),Gi=Pr(),Mi=Cr(),Wi=Ur(),_i=Gr(),Xi=Wr(),Vi=ge(),Bi=Kr(),Hi=Jr(),Ki=en(),Yi=rn(),Ji=ln();pn.exports={parse:mi,valid:wi,clean:Ei,inc:gi,diff:yi,major:$i,minor:xi,patch:Ri,prerelease:bi,compare:Oi,rcompare:vi,compareLoose:Ii,compareBuild:Si,sort:ki,rsort:Ni,gt:Li,lt:Ai,eq:Ti,neq:ji,gte:Pi,lte:qi,cmp:Ci,coerce:Di,Comparator:Ui,Range:Fi,satisfies:zi,toComparators:Gi,maxSatisfying:Mi,minSatisfying:Wi,minVersion:_i,validRange:Xi,outside:Vi,gtr:Bi,ltr:Hi,intersects:Ki,simplifyRange:Yi,subset:Ji,SemVer:di,re:Je.re,src:Je.src,tokens:Je.t,SEMVER_SPEC_VERSION:un.SEMVER_SPEC_VERSION,RELEASE_TYPES:un.RELEASE_TYPES,compareIdentifiers:fn.compareIdentifiers,rcompareIdentifiers:fn.rcompareIdentifiers}});var Te=new TextDecoder;function ie(e){let t=e.indexOf("@",e.startsWith("@")?1:0);return t<0?{name:e,version:""}:{name:e.slice(0,t),version:e.slice(t+1)}}async function $t(e,t){let r=String(t??"").split(/\s+/).filter(o=>o.startsWith("sha512-")).map(o=>o.split("?")[0]);if(r.length===0)throw new Error("The package has no SHA-512 integrity");if(!globalThis.crypto?.subtle)throw new Error("Integrity checks need a secure context (https or localhost)");let n=new Uint8Array(await crypto.subtle.digest("SHA-512",e)),s="sha512-"+btoa(Array.from(n,o=>String.fromCharCode(o)).join(""));if(!r.includes(s))throw new Error(`Integrity check failed: expected ${r[0]}, got ${s}`);return s}async function xt(e,t=268435456){let r=new Blob([e]).stream().pipeThrough(new DecompressionStream("gzip")).getReader(),n=[],s=0;for(let o=await r.read();!o.done;o=await r.read()){if(s+=o.value.length,s>t)throw await r.cancel(),new Error(`The tarball unpacks to more than ${t} bytes`);n.push(o.value)}return new Uint8Array(await new Blob(n).arrayBuffer())}function _(e,t,r){let n=e.subarray(t,t+r),s=n.indexOf(0);return Te.decode(s<0?n:n.subarray(0,s))}function Rt(e,t,r){if(e[t]&128)return e.subarray(t+1,t+r).reduce((s,o)=>s*256+o,e[t]&127);let n=_(e,t,r).trim();if(!/^[0-7]*$/.test(n))throw new Error("Corrupt tar header");return n===""?0:parseInt(n,8)}function Jn(e){let t=0;for(let r=0;r<512;++r)t+=r>=148&&r<156?32:e[r];if(Rt(e,148,8)!==t)throw new Error("Corrupt tar header checksum")}function Zn(e){let t={},r=0;for(;r0)||r+s>e.length)throw new Error("Corrupt pax header");let o=Te.decode(e.subarray(n+1,r+s-1)),i=o.indexOf("=");t[o.slice(0,i)]=o.slice(i+1),r+=s}return t}function Qn(e,t){let r=e.subarray(t,t+512);Jn(r);let n=Rt(r,124,12),s=t+512;if(s+n>e.length)throw new Error("Truncated tar archive");return{header:r,type:r[156]===0?"0":String.fromCharCode(r[156]),data:e.subarray(s,s+n),next:s+Math.ceil(n/512)*512}}function es(e,t){return t+512>e.length||e.subarray(t,t+512).every(r=>r===0)}function ts(e){let t=_(e,0,100),r=_(e,257,5)==="ustar"?_(e,345,155):"";return r?`${r}/${t}`:t}var yt={x:(e,t)=>({...e,pax:Zn(t).path}),L:(e,t)=>({...e,long:_(t,0,t.length)}),g:e=>e};function bt(e){let t=[],r={};for(let n=0;!es(e,n);){let{header:s,type:o,data:i,next:c}=Qn(e,n);if(n=c,Object.hasOwn(yt,o)){r=yt[o](r,i);continue}(o==="0"||o==="7")&&t.push({path:r.pax??r.long??ts(s),bytes:i}),r={}}return t}var Re=F(C(),1);var R=(e,t,...r)=>e.cppFunction(`webfront.developer.${t}`)(...r);async function G(e,t){let r=[],n=0;for(;;){let s=await R(e,"read",t,n);if(r.push(s),n+=s.length,s.length<262144)break;if(n>256*1024*1024)throw new Error("Project file is too large")}return new Uint8Array(await new Blob(r).arrayBuffer())}async function Z(e,{id:t,path:r,bytes:n},s){for(let o=0;o{}),c}}async function Zi(e,t){let r=[],n=0;for(;;){let{done:s,value:o}=await e.read();if(s)return r;if(n+=o.length,n>t)throw new Error("Compressed download exceeds its byte limit");r.push(o)}}async function Qi(e,t){try{return await Zi(e,t)}catch(r){throw await e.cancel().catch(()=>{}),r}finally{e.releaseLock()}}async function hn(e,t=64*1024*1024){if(!e.ok)throw new Error(`Download: HTTP ${e.status}`);if(Number(e.headers.get("content-length"))>t)throw new Error("Compressed download exceeds its byte limit");return new Uint8Array(await new Blob(await Qi(e.body.getReader(),t)).arrayBuffer())}var M=".webfront/developer/packages",ea=/[\\\0:*?"<>|]/,ta=e=>e.split("/").some(t=>!t||t==="."||t==="..");function Ze(e){return typeof e!="string"||!e||ea.test(e)?!0:ta(e)}function A(e){if(Ze(e))throw new Error(`Unsafe package path: ${e}`);return e}var ra=new TextDecoder,na=["preinstall","install","postinstall"];async function dn(e){let t=new Map,r;for(let n of bt(await xt(e))){let s=n.path.indexOf("/"),o=n.path.slice(0,s);if(s<1||o==="."||o===".."||(r??(r=o))!==o)throw new Error("Invalid npm tarball root");let i=A(n.path.slice(s+1));if(t.has(i))throw new Error(`Duplicate package path: ${i}`);t.set(i,n.bytes)}return t}var sa=e=>na.some(t=>e.scripts?.[t]),oa=e=>e.has("binding.gyp")||[...e.keys()].some(t=>t.endsWith(".node"));function ia(e,t){return sa(e)||e.gypfile?!0:oa(t)}function mn(e,t,r){let n=JSON.parse(ra.decode(e.get("package.json")));if(n.name!==t||n.version!==r)throw new Error("npm archive identity mismatch");if(ia(n,e))throw new Error(`${t} needs an unsupported install script or native module`);return n}function W(e){return!e||typeof e!="object"?!1:!Array.isArray(e)}var Qe="webfront.project.json",et="webfront-packages.lock.json",x=Qe,S=et;function aa(e){if(e===void 0||e==="")return"";if(typeof e!="string"||e.endsWith("/")||Ze(e)||e===".webfront"||e.startsWith(".webfront/"))throw new Error(`Unsafe manifest directory: ${e}`);return e}function Ol(e){let t=aa(e);x=t?`${t}/${Qe}`:Qe,S=t?`${t}/${et}`:et}var ee=1,tt=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,ca=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,la=/^[0-9A-Za-z.+\-^~<>=*| ]{1,128}$/,En=/^[A-Za-z0-9][A-Za-z0-9:_.-]{0,63}$/,rt=/^[A-Za-z_][A-Za-z0-9_]*$/,gn=["format","name","version","dependencies","registry","scripts","entries","providers","test","permissions","developer"],ua=["files","publish","fetch"],y=e=>{throw new Error(`${x}: ${e}`)};function P(e,t){return W(e)||y(`${t} must be an object`),e}function $e(e,t,r){for(let n of Object.keys(e))t.includes(n)||y(`unknown key "${n}" in ${r}`)}function ye(e,t){typeof e!="string"&&y(`${t} must be a project path`);try{return A(e)}catch{return y(`${t} is not a safe project-relative path: ${e}`)}}function yn(e,t){return(!Array.isArray(e)||e.length>256)&&y(`${t} must be an array of at most 256 paths`),e.map((r,n)=>ye(r,`${t}[${n}]`))}function fa(e){let t=P(e,"dependencies");for(let[r,n]of Object.entries(t))tt.test(r)||y(`invalid npm package name "${r}"`),(typeof n!="string"||!la.test(n)||n!==n.trim())&&y(`invalid version range for "${r}"`);return t}var nt=e=>e.startsWith("/")&&!e.startsWith("//")&&!e.includes("\\");function pa(e){if(typeof e!="string"&&y("registry must be a URL"),nt(e))return e;let t;try{t=new URL(e)}catch{return y("registry must be an https URL or an absolute path")}return t.protocol!=="https:"&&y("registry must use https"),e}function ha(e){let t=P(e,"scripts");for(let[r,n]of Object.entries(t))(!En.test(r)||typeof n!="string"||!n||n.length>1024)&&y(`invalid script "${r}"`);return t}function da(e){let t=P(e,"entries");for(let[r,n]of Object.entries(t))En.test(r)||y(`invalid entry name "${r}"`),ye(n,`entries.${r}`);return t}function ma(e,t){let r=P(e,"providers");for(let[n,s]of Object.entries(r))rt.test(n)||y(`invalid provider name "${n}"`),P(s,`providers.${n}`),$e(s,["entry","output"],`providers.${n}`),typeof s.entry!="string"&&y(`providers.${n}.entry must name an entry or a path`),Object.hasOwn(t,s.entry)||ye(s.entry,`providers.${n}.entry`),ye(s.output,`providers.${n}.output`).endsWith(".hpp")||y(`providers.${n}.output must be a .hpp file`);return r}function wa(e){let t=P(e,"test");return $e(t,["specs"],"test"),t.specs!==void 0&&yn(t.specs,"test.specs"),t}function Ea(e,t){let r;try{r=new URL(e)}catch{return y(`${t} must be an https origin`)}return(r.protocol!=="https:"||r.origin!==e)&&y(`${t} must be an https origin without a path`),e}function ga(e){let t=P(e,"permissions");for(let r of Object.keys(t))ua.includes(r)||y(`unknown permission "${r}"`);for(let r of["files","publish"])t[r]!==void 0&&yn(t[r],`permissions.${r}`);return t.fetch!==void 0&&((!Array.isArray(t.fetch)||t.fetch.length>64)&&y("permissions.fetch must be an array of origins"),t.fetch.forEach((r,n)=>Ea(r,`permissions.fetch[${n}]`))),t}var wn={Ctrl:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"},vl="F9";function ya(e){if(typeof e!="string")return null;let t=e.split("+"),r=t.pop();if(!/^F(?:[1-9]|1[0-2])$/.test(r)||new Set(t).size!==t.length)return null;let n={key:r,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1};for(let s of t){if(!Object.hasOwn(wn,s))return null;n[wn[s]]=!0}return n}function $a(e){let t=P(e,"developer");return $e(t,["terminalShortcut"],"developer"),t.terminalShortcut!==void 0&&!ya(t.terminalShortcut)&&y('developer.terminalShortcut must be a function key, F1 to F12, optionally after Ctrl, Alt, Shift or Meta (for instance "Ctrl+Shift+F9")'),t}function xa(e){(typeof e.name!="string"||!tt.test(e.name))&&y("name must be a lower-case npm package name"),(typeof e.version!="string"||!ca.test(e.version))&&y("version must be a semantic version")}function Ra(e){e.format!==ee&&(Number.isInteger(e.format)&&e.format>ee&&y(`format ${e.format} is not supported by this environment (it reads format ${ee}); update the environment`),y(`format must be ${ee}`))}function te(e){P(e,"the manifest"),Ra(e),$e(e,gn,"the manifest"),xa(e);let t=e.entries===void 0?{}:da(e.entries);return{...e,dependencies:e.dependencies===void 0?{}:fa(e.dependencies),entries:t,providers:e.providers===void 0?{}:ma(e.providers,t),...e.registry===void 0?{}:{registry:pa(e.registry)},...e.scripts===void 0?{}:{scripts:ha(e.scripts)},...e.test===void 0?{}:{test:wa(e.test)},...e.permissions===void 0?{}:{permissions:ga(e.permissions)},...e.developer===void 0?{}:{developer:$a(e.developer)}}}function st(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return y("not valid JSON")}return{source:t,manifest:te(t)}}function Il(e){return st(e).manifest}function ot(e){let t={};for(let r of gn)e[r]!==void 0&&(t[r]=e[r]);return JSON.stringify(t,null,2)+` -`}function $n(e){return{format:ee,name:e,version:"0.1.0",dependencies:{}}}function xn(e){let r=(String(e??"").split("/").filter(Boolean).pop()??"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[^a-z0-9]+/,"").replace(/-+$/,"");return tt.test(r)?r:"webfront-app"}async function xe(e){let t=JSON.stringify(Object.entries(e).sort(([n],[s])=>ns?1:0)),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return[...new Uint8Array(r)].map(n=>n.toString(16).padStart(2,"0")).join("")}var it=e=>/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(e),be=(e,t)=>`${e.replace("/","+")}@${t}`,at=(e,t,r)=>`${be(e,t)}-${r.slice(7).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}`;async function ba(e,t,{fetchImpl:r,signal:n}){let s=await r(new URL(e.replace("/","%2f"),t),{signal:n});if(!s.ok)throw new Error(`Registry metadata for ${e}: HTTP ${s.status}`);return s.json()}function Oa(e,t){let r=e["dist-tags"]?.[t];return r||(Re.default.valid(t)?t:Re.default.maxSatisfying(Object.keys(e.versions??{}),t))}function va(e,t,r){let n=r||"latest",s=Oa(e,n),o=e.versions?.[s];if(!o||!Re.default.valid(s))throw new Error(`Cannot resolve ${t}@${n}`);return{version:s,manifest:o}}async function Ia(e,t,r,{fetchImpl:n,signal:s}){let o=new URL(t.dist?.tarball,r);if(o.protocol!=="https:"&&o.origin!==r.origin)throw new Error("Package tarballs must use HTTPS or the registry origin");let i=await n(o,{signal:s});if(!i.ok)throw new Error(`Package download for ${e}: HTTP ${i.status}`);let c=await hn(i);return{bytes:c,integrity:await $t(c,t.dist.integrity)}}function ct(e){let t=new URL(e,globalThis.location?.href),r=t.origin===globalThis.location?.origin;if(e.startsWith("/")?!nt(e)||!r:t.protocol!=="https:"&&!r)throw new Error(`The npm registry must use HTTPS or the application origin: ${e}`);return t.pathname.endsWith("/")||(t.pathname+="/"),t}async function D(e,t,{registry:r,fetchImpl:n=fetch,signal:s}){if(!it(e))throw new Error(`Unsupported npm package name: ${e}`);let o=ct(r),i={fetchImpl:n,signal:s},{version:c,manifest:a}=va(await ba(e,o,i),e,t),{bytes:l,integrity:u}=await Ia(e,a,o,i),f=await dn(l),m=mn(f,e,c);return{id:be(e,c),key:at(e,c,u),manifest:m,integrity:u,files:f}}var Oe=F(C(),1);function Sa(e,t,r){let n=e?.roots?.[t];return n?.requested===r&&e.packages[n.id]?e.packages[n.id]:Oe.default.validRange(r)?Object.values(e?.packages??{}).filter(o=>o.name===t&&Oe.default.satisfies(o.version,r)).sort((o,i)=>Oe.default.rcompare(o.version,i.version))[0]??null:null}function Rn({registry:e="https://registry.npmjs.org/",fetchImpl:t=fetch,signal:r,download:n=D,previous:s}){let o=new Map;return async(i,c)=>{let a=`${i}@${c}`;if(o.has(a))return o.get(a);let l=Sa(s,i,c),u=await n(i,l?.version??c,{registry:e,fetchImpl:t,signal:r});if(l&&u.integrity!==l.integrity)throw new Error(`${u.id} no longer matches the integrity recorded in the lock`);return o.set(a,u),u}}var bn=F(C(),1),On=(e,t,r)=>new Error(`${e.name}@${e.version} requires peer ${t}@${r}; install a compatible root explicitly`);function ka(e,t,r){if(e.manifest.peerDependenciesMeta?.[t]?.optional)return null;throw On(e,t,r)}function Na(e,[t,r],{nodes:n,roots:s}){let o=s[t]?.id??e.dependencies[t];if(!o)return ka(e,t,r);if(!bn.default.satisfies(n[o].version,r))throw On(e,t,r);return o}function La(e,t){for(let r of Object.entries(e.manifest.peerDependencies??{})){let n=Na(e,r,t);n&&(e.dependencies[r[0]]=n)}}function vn(e,t){for(let r of Object.values(e))La(r,{nodes:e,roots:t})}var In=F(C(),1);function Aa(e,t){return!it(t.name)||!In.default.valid(t.version)?!1:e===be(t.name,t.version)}function Ta(e){return e.integrity?.startsWith("sha512-")?e.key===at(e.name,e.version,e.integrity):!1}function ja(e,t,r){if(!Aa(t,r)||!Ta(r))throw new Error("Invalid locked package");for(let n of r.files)A(n);if(Object.values(r.dependencies).some(n=>!e.packages[n]))throw new Error("Dangling locked dependency")}function Pa(e){return e?.format!==1?!1:!!e.roots&&!!e.packages}function lt(e){if(!Pa(e))throw new Error("Unsupported package lock");if(Object.keys(e.packages).length>512)throw new Error("The package lock exceeds 512 packages");for(let[t,r]of Object.entries(e.packages))ja(e,t,r);if(Object.values(e.roots).some(t=>!e.packages[t.id]))throw new Error("Dangling locked root");return e}function qa(e,t,r){if(Object.keys(e.nodes).length>=512)throw new Error("Dependency graph exceeds 512 packages");for(let n of r.files.values())e.total+=n.length;if(e.total>256*1024*1024)throw new Error("Dependency graph exceeds 256 MiB");e.nodes[r.id]={name:t,version:r.manifest.version,integrity:r.integrity,key:r.key,manifest:r.manifest,files:[...r.files.keys()].sort(),dependencies:{}},e.downloads.set(r.id,r.files)}async function Ca(e,t){let r={};for(let n of e){let{name:s,version:o}=ie(n);r[s]={requested:o||"latest",id:await t(s,o||"latest")}}return r}async function Sn(e,t={}){let r=Rn(t),n={nodes:{},downloads:new Map,total:0},s=async(i,c)=>{t.signal?.throwIfAborted();let a=await r(i,c);if(n.nodes[a.id])return a.id;qa(n,i,a);for(let[l,u]of Object.entries(a.manifest.dependencies??{}).sort())n.nodes[a.id].dependencies[l]=await s(l,u);return a.id},o=await Ca(e,s);return vn(n.nodes,o),{lock:{format:1,registry:t.registry??"https://registry.npmjs.org/",roots:o,packages:n.nodes},downloads:n.downloads}}var ut=F(C(),1);var Da=new TextDecoder,Ua=new TextEncoder,ve="No webfront.project.json: run wf init, then wf dev (the interface is TypeScript/TSX in ui/; wf create app writes a first one; wf help agents gives the sequence)",Ie="The lock does not match the dependencies of webfront.project.json; run wf install --update to resolve them again";async function kn(e,t){try{return await G(e,t)}catch(r){if(r.message.includes("Cannot read project file:"))return null;throw r}}function Fa(e,t,r){return t?r===t.requested?!0:ut.default.validRange(r)!==null&&ut.default.satisfies(e.packages[t.id].version,r):!1}function za(e,t){let r=Object.keys(t);return r.length===Object.keys(e.roots).length&&r.every(n=>Fa(e,e.roots[n],t[n]))}function Ga(e,t,r){return e?t?t.manifestDigest===void 0?za(t,e.dependencies)?"legacy":"desynchronized":t.manifestDigest===r?"consistent":"desynchronized":"unlocked":"no-manifest"}async function re(e){let t=await R(e,"state",`${x} +var Xn=Object.create;var gt=Object.defineProperty;var Vn=Object.getOwnPropertyDescriptor;var Bn=Object.getOwnPropertyNames;var Hn=Object.getPrototypeOf,Kn=Object.prototype.hasOwnProperty;var w=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Yn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Bn(t))!Kn.call(e,s)&&s!==r&>(e,s,{get:()=>t[s],enumerable:!(n=Vn(t,s))||n.enumerable});return e};var F=(e,t,r)=>(r=e!=null?Xn(Hn(e)):{},Yn(t||!e||!e.__esModule?gt(r,"default",{value:e,enumerable:!0}):r,e));var X=w((bc,Ot)=>{"use strict";var rs="2.0.0",ns=Number.MAX_SAFE_INTEGER||9007199254740991,ss=16,os=250,is=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Ot.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:ss,MAX_SAFE_BUILD_LENGTH:os,MAX_SAFE_INTEGER:ns,RELEASE_TYPES:is,SEMVER_SPEC_VERSION:rs,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var V=w((Oc,vt)=>{"use strict";var as=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};vt.exports=as});var z=w((j,It)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:je,MAX_SAFE_BUILD_LENGTH:cs,MAX_LENGTH:ls}=X(),us=V();j=It.exports={};var fs=j.re=[],ps=j.safeRe=[],p=j.src=[],hs=j.safeSrc=[],h=j.t={},ds=0,Pe="[a-zA-Z0-9-]",ms=[["\\s",1],["\\d",ls],[Pe,cs]],ws=e=>{for(let[t,r]of ms)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let n=ws(t),s=ds++;us(e,s,t),h[e]=s,p[s]=t,hs[s]=n,fs[s]=new RegExp(t,r?"g":void 0),ps[s]=new RegExp(n,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Pe}*`);E("MAINVERSION",`(${p[h.NUMERICIDENTIFIER]})\\.(${p[h.NUMERICIDENTIFIER]})\\.(${p[h.NUMERICIDENTIFIER]})`);E("MAINVERSIONLOOSE",`(${p[h.NUMERICIDENTIFIERLOOSE]})\\.(${p[h.NUMERICIDENTIFIERLOOSE]})\\.(${p[h.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASEIDENTIFIER",`(?:${p[h.NONNUMERICIDENTIFIER]}|${p[h.NUMERICIDENTIFIER]})`);E("PRERELEASEIDENTIFIERLOOSE",`(?:${p[h.NONNUMERICIDENTIFIER]}|${p[h.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASE",`(?:-(${p[h.PRERELEASEIDENTIFIER]}(?:\\.${p[h.PRERELEASEIDENTIFIER]})*))`);E("PRERELEASELOOSE",`(?:-?(${p[h.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${p[h.PRERELEASEIDENTIFIERLOOSE]})*))`);E("BUILDIDENTIFIER",`${Pe}+`);E("BUILD",`(?:\\+(${p[h.BUILDIDENTIFIER]}(?:\\.${p[h.BUILDIDENTIFIER]})*))`);E("FULLPLAIN",`v?${p[h.MAINVERSION]}${p[h.PRERELEASE]}?${p[h.BUILD]}?`);E("FULL",`^${p[h.FULLPLAIN]}$`);E("LOOSEPLAIN",`[v=\\s]*${p[h.MAINVERSIONLOOSE]}${p[h.PRERELEASELOOSE]}?${p[h.BUILD]}?`);E("LOOSE",`^${p[h.LOOSEPLAIN]}$`);E("GTLT","((?:<|>)?=?)");E("XRANGEIDENTIFIERLOOSE",`${p[h.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);E("XRANGEIDENTIFIER",`${p[h.NUMERICIDENTIFIER]}|x|X|\\*`);E("XRANGEPLAIN",`[v=\\s]*(${p[h.XRANGEIDENTIFIER]})(?:\\.(${p[h.XRANGEIDENTIFIER]})(?:\\.(${p[h.XRANGEIDENTIFIER]})(?:${p[h.PRERELEASE]})?${p[h.BUILD]}?)?)?`);E("XRANGEPLAINLOOSE",`[v=\\s]*(${p[h.XRANGEIDENTIFIERLOOSE]})(?:\\.(${p[h.XRANGEIDENTIFIERLOOSE]})(?:\\.(${p[h.XRANGEIDENTIFIERLOOSE]})(?:${p[h.PRERELEASELOOSE]})?${p[h.BUILD]}?)?)?`);E("XRANGE",`^${p[h.GTLT]}\\s*${p[h.XRANGEPLAIN]}$`);E("XRANGELOOSE",`^${p[h.GTLT]}\\s*${p[h.XRANGEPLAINLOOSE]}$`);E("COERCEPLAIN",`(^|[^\\d])(\\d{1,${je}})(?:\\.(\\d{1,${je}}))?(?:\\.(\\d{1,${je}}))?`);E("COERCE",`${p[h.COERCEPLAIN]}(?:$|[^\\d])`);E("COERCEFULL",p[h.COERCEPLAIN]+`(?:${p[h.PRERELEASE]})?(?:${p[h.BUILD]})?(?:$|[^\\d])`);E("COERCERTL",p[h.COERCE],!0);E("COERCERTLFULL",p[h.COERCEFULL],!0);E("LONETILDE","(?:~>?)");E("TILDETRIM",`(\\s*)${p[h.LONETILDE]}\\s+`,!0);j.tildeTrimReplace="$1~";E("TILDE",`^${p[h.LONETILDE]}${p[h.XRANGEPLAIN]}$`);E("TILDELOOSE",`^${p[h.LONETILDE]}${p[h.XRANGEPLAINLOOSE]}$`);E("LONECARET","(?:\\^)");E("CARETTRIM",`(\\s*)${p[h.LONECARET]}\\s+`,!0);j.caretTrimReplace="$1^";E("CARET",`^${p[h.LONECARET]}${p[h.XRANGEPLAIN]}$`);E("CARETLOOSE",`^${p[h.LONECARET]}${p[h.XRANGEPLAINLOOSE]}$`);E("COMPARATORLOOSE",`^${p[h.GTLT]}\\s*(${p[h.LOOSEPLAIN]})$|^$`);E("COMPARATOR",`^${p[h.GTLT]}\\s*(${p[h.FULLPLAIN]})$|^$`);E("COMPARATORTRIM",`(\\s*)${p[h.GTLT]}\\s*(${p[h.LOOSEPLAIN]}|${p[h.XRANGEPLAIN]})`,!0);j.comparatorTrimReplace="$1$2$3";E("HYPHENRANGE",`^\\s*(${p[h.XRANGEPLAIN]})\\s+-\\s+(${p[h.XRANGEPLAIN]})\\s*$`);E("HYPHENRANGELOOSE",`^\\s*(${p[h.XRANGEPLAINLOOSE]})\\s+-\\s+(${p[h.XRANGEPLAINLOOSE]})\\s*$`);E("STAR","(<|>)?=?\\s*\\*");E("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");E("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var ae=w((vc,St)=>{"use strict";var Es=Object.freeze({loose:!0}),gs=Object.freeze({}),$s=e=>e?typeof e!="object"?Es:e:gs;St.exports=$s});var qe=w((Ic,Lt)=>{"use strict";var kt=/^[0-9]+$/,Nt=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:eNt(t,e);Lt.exports={compareIdentifiers:Nt,rcompareIdentifiers:ys}});var b=w((Sc,Tt)=>{"use strict";var ce=V(),{MAX_LENGTH:At,MAX_SAFE_INTEGER:le}=X(),{safeRe:ue,t:fe}=z(),xs=ae(),{compareIdentifiers:Ce}=qe(),De=class e{constructor(t,r){if(r=xs(r),t instanceof e){if(t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease)return t;t=t.version}else if(typeof t!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>At)throw new TypeError(`version is longer than ${At} characters`);ce("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?ue[fe.LOOSE]:ue[fe.FULL]);if(!n)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>le||this.major<0)throw new TypeError("Invalid major version");if(this.minor>le||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>le||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let o=+s;if(o>=0&&ot.major?1:this.minort.minor?1:this.patcht.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let n=this.prerelease[r],s=t.prerelease[r];if(ce("prerelease compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Ce(n,s)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let n=this.build[r],s=t.build[r];if(ce("build compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Ce(n,s)}while(++r)}inc(t,r,n){if(t.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let s=`-${r}`.match(this.options.loose?ue[fe.PRERELEASELOOSE]:ue[fe.PRERELEASE]);if(!s||s[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let s=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[s];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(r){let o=[r,s];n===!1&&(o=[r]),Ce(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=o):this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Tt.exports=De});var q=w((kc,Pt)=>{"use strict";var jt=b(),Rs=(e,t,r=!1)=>{if(e instanceof jt)return e;try{return new jt(e,t)}catch(n){if(!r)return null;throw n}};Pt.exports=Rs});var Ct=w((Nc,qt)=>{"use strict";var bs=q(),Os=(e,t)=>{let r=bs(e,t);return r?r.version:null};qt.exports=Os});var Ut=w((Lc,Dt)=>{"use strict";var vs=q(),Is=(e,t)=>{let r=vs(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};Dt.exports=Is});var Gt=w((Ac,zt)=>{"use strict";var Ft=b(),Ss=(e,t,r,n,s)=>{typeof r=="string"&&(s=n,n=r,r=void 0);try{return new Ft(e instanceof Ft?e.version:e,r).inc(t,n,s).version}catch{return null}};zt.exports=Ss});var _t=w((Tc,Wt)=>{"use strict";var Mt=q(),ks=(e,t)=>{let r=Mt(e,null,!0),n=Mt(t,null,!0),s=r.compare(n);if(s===0)return null;let o=s>0,i=o?r:n,c=o?n:r,a=!!i.prerelease.length;if(!!c.prerelease.length&&!a){if(!c.patch&&!c.minor)return"major";if(c.compareMain(i)===0)return c.minor&&!c.patch?"minor":"patch"}let u=a?"pre":"";return r.major!==n.major?u+"major":r.minor!==n.minor?u+"minor":r.patch!==n.patch?u+"patch":"prerelease"};Wt.exports=ks});var Vt=w((jc,Xt)=>{"use strict";var Ns=b(),Ls=(e,t)=>new Ns(e,t).major;Xt.exports=Ls});var Ht=w((Pc,Bt)=>{"use strict";var As=b(),Ts=(e,t)=>new As(e,t).minor;Bt.exports=Ts});var Yt=w((qc,Kt)=>{"use strict";var js=b(),Ps=(e,t)=>new js(e,t).patch;Kt.exports=Ps});var Zt=w((Cc,Jt)=>{"use strict";var qs=q(),Cs=(e,t)=>{let r=qs(e,t);return r&&r.prerelease.length?r.prerelease:null};Jt.exports=Cs});var N=w((Dc,er)=>{"use strict";var Qt=b(),Ds=(e,t,r)=>new Qt(e,r).compare(new Qt(t,r));er.exports=Ds});var rr=w((Uc,tr)=>{"use strict";var Us=N(),Fs=(e,t,r)=>Us(t,e,r);tr.exports=Fs});var sr=w((Fc,nr)=>{"use strict";var zs=N(),Gs=(e,t)=>zs(e,t,!0);nr.exports=Gs});var pe=w((zc,ir)=>{"use strict";var or=b(),Ms=(e,t,r)=>{let n=new or(e,r),s=new or(t,r);return n.compare(s)||n.compareBuild(s)};ir.exports=Ms});var cr=w((Gc,ar)=>{"use strict";var Ws=pe(),_s=(e,t)=>e.sort((r,n)=>Ws(r,n,t));ar.exports=_s});var ur=w((Mc,lr)=>{"use strict";var Xs=pe(),Vs=(e,t)=>e.sort((r,n)=>Xs(n,r,t));lr.exports=Vs});var B=w((Wc,fr)=>{"use strict";var Bs=N(),Hs=(e,t,r)=>Bs(e,t,r)>0;fr.exports=Hs});var he=w((_c,pr)=>{"use strict";var Ks=N(),Ys=(e,t,r)=>Ks(e,t,r)<0;pr.exports=Ys});var Ue=w((Xc,hr)=>{"use strict";var Js=N(),Zs=(e,t,r)=>Js(e,t,r)===0;hr.exports=Zs});var Fe=w((Vc,dr)=>{"use strict";var Qs=N(),eo=(e,t,r)=>Qs(e,t,r)!==0;dr.exports=eo});var de=w((Bc,mr)=>{"use strict";var to=N(),ro=(e,t,r)=>to(e,t,r)>=0;mr.exports=ro});var me=w((Hc,wr)=>{"use strict";var no=N(),so=(e,t,r)=>no(e,t,r)<=0;wr.exports=so});var ze=w((Kc,Er)=>{"use strict";var oo=Ue(),io=Fe(),ao=B(),co=de(),lo=he(),uo=me(),fo=(e,t,r,n)=>{switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return oo(e,r,n);case"!=":return io(e,r,n);case">":return ao(e,r,n);case">=":return co(e,r,n);case"<":return lo(e,r,n);case"<=":return uo(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};Er.exports=fo});var $r=w((Yc,gr)=>{"use strict";var po=b(),ho=q(),{safeRe:we,t:Ee}=z(),mo=(e,t)=>{if(e instanceof po)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};let r=null;if(!t.rtl)r=e.match(t.includePrerelease?we[Ee.COERCEFULL]:we[Ee.COERCE]);else{let a=t.includePrerelease?we[Ee.COERCERTLFULL]:we[Ee.COERCERTL],l;for(;(l=a.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||l.index+l[0].length!==r.index+r[0].length)&&(r=l),a.lastIndex=l.index+l[1].length+l[2].length;a.lastIndex=-1}if(r===null)return null;let n=r[2],s=r[3]||"0",o=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",c=t.includePrerelease&&r[6]?`+${r[6]}`:"";return ho(`${n}.${s}.${o}${i}${c}`,t)};gr.exports=mo});var xr=w((Jc,yr)=>{"use strict";var Ge=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let s=this.map.keys().next().value;this.delete(s)}this.map.set(t,r)}return this}};yr.exports=Ge});var L=w((Zc,vr)=>{"use strict";var wo=/\s+/g,Me=class e{constructor(t,r){if(r=go(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof We)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(wo," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(s=>!br(s[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&vo(s[0])){this.set=[s];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t0&&(this.formatted+="||");let r=this.set[t];for(let n=0;n0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){let n=((this.options.includePrerelease&&bo)|(this.options.loose&&Oo))+":"+t,s=Rr.get(n);if(s)return s;let o=this.options.loose,i=o?v[O.HYPHENRANGELOOSE]:v[O.HYPHENRANGE];t=t.replace(i,qo(this.options.includePrerelease)),g("hyphen replace",t),t=t.replace(v[O.COMPARATORTRIM],yo),g("comparator trim",t),t=t.replace(v[O.TILDETRIM],xo),g("tilde trim",t),t=t.replace(v[O.CARETTRIM],Ro),g("caret trim",t);let c=t.split(" ").map(f=>Io(f,this.options)).join(" ").split(/\s+/).map(f=>Po(f,this.options));o&&(c=c.filter(f=>(g("loose invalid filter",f,this.options),!!f.match(v[O.COMPARATORLOOSE])))),g("range list",c);let a=new Map,l=c.map(f=>new We(f,this.options));for(let f of l){if(br(f))return[f];a.set(f.value,f)}a.size>1&&a.has("")&&a.delete("");let u=[...a.values()];return Rr.set(n,u),u}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(n=>Or(n,r)&&t.set.some(s=>Or(s,r)&&n.every(o=>s.every(i=>o.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new $o(t,this.options)}catch{return!1}for(let r=0;re.value==="<0.0.0-0",vo=e=>e.value==="",Or=(e,t)=>{let r=!0,n=e.slice(),s=n.pop();for(;r&&n.length;)r=n.every(o=>s.intersects(o,t)),s=n.pop();return r},Io=(e,t)=>(e=e.replace(v[O.BUILD],""),g("comp",e,t),e=No(e,t),g("caret",e),e=So(e,t),g("tildes",e),e=Ao(e,t),g("xrange",e),e=jo(e,t),g("stars",e),e),I=e=>!e||e.toLowerCase()==="x"||e==="*",So=(e,t)=>e.trim().split(/\s+/).map(r=>ko(r,t)).join(" "),ko=(e,t)=>{let r=t.loose?v[O.TILDELOOSE]:v[O.TILDE];return e.replace(r,(n,s,o,i,c)=>{g("tilde",e,n,s,o,i,c);let a;return I(s)?a="":I(o)?a=`>=${s}.0.0 <${+s+1}.0.0-0`:I(i)?a=`>=${s}.${o}.0 <${s}.${+o+1}.0-0`:c?(g("replaceTilde pr",c),a=`>=${s}.${o}.${i}-${c} <${s}.${+o+1}.0-0`):a=`>=${s}.${o}.${i} <${s}.${+o+1}.0-0`,g("tilde return",a),a})},No=(e,t)=>e.trim().split(/\s+/).map(r=>Lo(r,t)).join(" "),Lo=(e,t)=>{g("caret",e,t);let r=t.loose?v[O.CARETLOOSE]:v[O.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(s,o,i,c,a)=>{g("caret",e,s,o,i,c,a);let l;return I(o)?l="":I(i)?l=`>=${o}.0.0${n} <${+o+1}.0.0-0`:I(c)?o==="0"?l=`>=${o}.${i}.0${n} <${o}.${+i+1}.0-0`:l=`>=${o}.${i}.0${n} <${+o+1}.0.0-0`:a?(g("replaceCaret pr",a),o==="0"?i==="0"?l=`>=${o}.${i}.${c}-${a} <${o}.${i}.${+c+1}-0`:l=`>=${o}.${i}.${c}-${a} <${o}.${+i+1}.0-0`:l=`>=${o}.${i}.${c}-${a} <${+o+1}.0.0-0`):(g("no pr"),o==="0"?i==="0"?l=`>=${o}.${i}.${c}${n} <${o}.${i}.${+c+1}-0`:l=`>=${o}.${i}.${c}${n} <${o}.${+i+1}.0-0`:l=`>=${o}.${i}.${c} <${+o+1}.0.0-0`),g("caret return",l),l})},Ao=(e,t)=>(g("replaceXRanges",e,t),e.split(/\s+/).map(r=>To(r,t)).join(" ")),To=(e,t)=>{e=e.trim();let r=t.loose?v[O.XRANGELOOSE]:v[O.XRANGE];return e.replace(r,(n,s,o,i,c,a)=>{g("xRange",e,n,s,o,i,c,a);let l=I(o),u=l||I(i),f=u||I(c),m=f;return s==="="&&m&&(s=""),a=t.includePrerelease?"-0":"",l?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&m?(u&&(i=0),c=0,s===">"?(s=">=",u?(o=+o+1,i=0,c=0):(i=+i+1,c=0)):s==="<="&&(s="<",u?o=+o+1:i=+i+1),s==="<"&&(a="-0"),n=`${s+o}.${i}.${c}${a}`):u?n=`>=${o}.0.0${a} <${+o+1}.0.0-0`:f&&(n=`>=${o}.${i}.0${a} <${o}.${+i+1}.0-0`),g("xRange return",n),n})},jo=(e,t)=>(g("replaceStars",e,t),e.trim().replace(v[O.STAR],"")),Po=(e,t)=>(g("replaceGTE0",e,t),e.trim().replace(v[t.includePrerelease?O.GTE0PRE:O.GTE0],"")),qo=e=>(t,r,n,s,o,i,c,a,l,u,f,m)=>(I(n)?r="":I(s)?r=`>=${n}.0.0${e?"-0":""}`:I(o)?r=`>=${n}.${s}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,I(l)?a="":I(u)?a=`<${+l+1}.0.0-0`:I(f)?a=`<${l}.${+u+1}.0-0`:m?a=`<=${l}.${u}.${f}-${m}`:e?a=`<${l}.${u}.${+f+1}-0`:a=`<=${a}`,`${r} ${a}`.trim()),Co=(e,t,r)=>{for(let n=0;n0){let s=e[n].semver;if(s.major===t.major&&s.minor===t.minor&&s.patch===t.patch)return!0}return!1}return!0}});var H=w((Qc,Ar)=>{"use strict";var K=Symbol("SemVer ANY"),Ve=class e{static get ANY(){return K}constructor(t,r){if(r=Ir(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Xe("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===K?this.value="":this.value=this.operator+this.semver.version,Xe("comp",this)}parse(t){let r=this.options.loose?Sr[kr.COMPARATORLOOSE]:Sr[kr.COMPARATOR],n=t.match(r);if(!n)throw new TypeError(`Invalid comparator: ${t}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Nr(n[2],this.options.loose):this.semver=K}toString(){return this.value}test(t){if(Xe("Comparator.test",t,this.options.loose),this.semver===K||t===K)return!0;if(typeof t=="string")try{t=new Nr(t,this.options)}catch{return!1}return _e(t,this.operator,this.semver,this.options)}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Lr(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new Lr(this.value,r).test(t.semver):(r=Ir(r),r.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||_e(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||_e(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};Ar.exports=Ve;var Ir=ae(),{safeRe:Sr,t:kr}=z(),_e=ze(),Xe=V(),Nr=b(),Lr=L()});var Y=w((el,Tr)=>{"use strict";var Do=L(),Uo=(e,t,r)=>{try{t=new Do(t,r)}catch{return!1}return t.test(e)};Tr.exports=Uo});var Pr=w((tl,jr)=>{"use strict";var Fo=L(),zo=(e,t)=>new Fo(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));jr.exports=zo});var Cr=w((rl,qr)=>{"use strict";var Go=b(),Mo=L(),Wo=(e,t,r)=>{let n=null,s=null,o=null;try{o=new Mo(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===-1)&&(n=i,s=new Go(n,r))}),n};qr.exports=Wo});var Ur=w((nl,Dr)=>{"use strict";var _o=b(),Xo=L(),Vo=(e,t,r)=>{let n=null,s=null,o=null;try{o=new Xo(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===1)&&(n=i,s=new _o(n,r))}),n};Dr.exports=Vo});var Gr=w((sl,zr)=>{"use strict";var Be=b(),Bo=L(),Fr=B(),Ho=(e,t)=>{e=new Bo(e,t);let r=new Be("0.0.0");if(e.test(r)||(r=new Be("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n{let c=new Be(i.semver.version);switch(i.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!o||Fr(c,o))&&(o=c);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),o&&(!r||Fr(r,o))&&(r=o)}return r&&e.test(r)?r:null};zr.exports=Ho});var Wr=w((ol,Mr)=>{"use strict";var Ko=L(),Yo=(e,t)=>{try{return new Ko(e,t).range||"*"}catch{return null}};Mr.exports=Yo});var ge=w((il,Br)=>{"use strict";var Jo=b(),Vr=H(),{ANY:Zo}=Vr,Qo=L(),ei=Y(),_r=B(),Xr=he(),ti=me(),ri=de(),ni=(e,t,r,n)=>{e=new Jo(e,n),t=new Qo(t,n);let s,o,i,c,a;switch(r){case">":s=_r,o=ti,i=Xr,c=">",a=">=";break;case"<":s=Xr,o=ri,i=_r,c="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(ei(e,t,n))return!1;for(let l=0;l{d.semver===Zo&&(d=new Vr(">=0.0.0")),f=f||d,m=m||d,s(d.semver,f.semver,n)?f=d:i(d.semver,m.semver,n)&&(m=d)}),f.operator===c||f.operator===a||(!m.operator||m.operator===c)&&o(e,m.semver))return!1;if(m.operator===a&&i(e,m.semver))return!1}return!0};Br.exports=ni});var Kr=w((al,Hr)=>{"use strict";var si=ge(),oi=(e,t,r)=>si(e,t,">",r);Hr.exports=oi});var Jr=w((cl,Yr)=>{"use strict";var ii=ge(),ai=(e,t,r)=>ii(e,t,"<",r);Yr.exports=ai});var en=w((ll,Qr)=>{"use strict";var Zr=L(),ci=(e,t,r)=>(e=new Zr(e,r),t=new Zr(t,r),e.intersects(t,r));Qr.exports=ci});var rn=w((ul,tn)=>{"use strict";var li=Y(),ui=N();tn.exports=(e,t,r)=>{let n=[],s=null,o=null,i=e.sort((u,f)=>ui(u,f,r));for(let u of i)li(u,t,r)?(o=u,s||(s=u)):(o&&n.push([s,o]),o=null,s=null);s&&n.push([s,null]);let c=[];for(let[u,f]of n)u===f?c.push(u):!f&&u===i[0]?c.push("*"):f?u===i[0]?c.push(`<=${f}`):c.push(`${u} - ${f}`):c.push(`>=${u}`);let a=c.join(" || "),l=typeof t.raw=="string"?t.raw:String(t);return a.length{"use strict";var nn=L(),Ke=H(),{ANY:He}=Ke,J=Y(),Ye=N(),fi=(e,t,r={})=>{if(e===t)return!0;e=new nn(e,r),t=new nn(t,r);let n=!1;e:for(let s of e.set){for(let o of t.set){let i=hi(s,o,r);if(n=n||i!==null,i)continue e}if(n)return!1}return!0},pi=[new Ke(">=0.0.0-0")],sn=[new Ke(">=0.0.0")],hi=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===He){if(t.length===1&&t[0].semver===He)return!0;r.includePrerelease?e=pi:e=sn}if(t.length===1&&t[0].semver===He){if(r.includePrerelease)return!0;t=sn}let n=new Set,s,o;for(let d of e)d.operator===">"||d.operator===">="?s=on(s,d,r):d.operator==="<"||d.operator==="<="?o=an(o,d,r):n.add(d.semver);if(n.size>1)return null;let i;if(s&&o){if(i=Ye(s.semver,o.semver,r),i>0)return null;if(i===0&&(s.operator!==">="||o.operator!=="<="))return null}for(let d of n){if(s&&!J(d,String(s),r)||o&&!J(d,String(o),r))return null;for(let T of t)if(!J(d,String(T),r))return!1;return!0}let c,a,l,u,f=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:!1,m=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1;f&&f.prerelease.length===1&&o.operator==="<"&&f.prerelease[0]===0&&(f=!1);for(let d of t){if(u=u||d.operator===">"||d.operator===">=",l=l||d.operator==="<"||d.operator==="<=",s){if(m&&d.semver.prerelease&&d.semver.prerelease.length&&d.semver.major===m.major&&d.semver.minor===m.minor&&d.semver.patch===m.patch&&(m=!1),d.operator===">"||d.operator===">="){if(c=on(s,d,r),c===d&&c!==s)return!1}else if(s.operator===">="&&!J(s.semver,String(d),r))return!1}if(o){if(f&&d.semver.prerelease&&d.semver.prerelease.length&&d.semver.major===f.major&&d.semver.minor===f.minor&&d.semver.patch===f.patch&&(f=!1),d.operator==="<"||d.operator==="<="){if(a=an(o,d,r),a===d&&a!==o)return!1}else if(o.operator==="<="&&!J(o.semver,String(d),r))return!1}if(!d.operator&&(o||s)&&i!==0)return!1}return!(s&&l&&!o&&i!==0||o&&u&&!s&&i!==0||m||f)},on=(e,t,r)=>{if(!e)return t;let n=Ye(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},an=(e,t,r)=>{if(!e)return t;let n=Ye(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};cn.exports=fi});var C=w((pl,pn)=>{"use strict";var Je=z(),un=X(),di=b(),fn=qe(),mi=q(),wi=Ct(),Ei=Ut(),gi=Gt(),$i=_t(),yi=Vt(),xi=Ht(),Ri=Yt(),bi=Zt(),Oi=N(),vi=rr(),Ii=sr(),Si=pe(),ki=cr(),Ni=ur(),Li=B(),Ai=he(),Ti=Ue(),ji=Fe(),Pi=de(),qi=me(),Ci=ze(),Di=$r(),Ui=H(),Fi=L(),zi=Y(),Gi=Pr(),Mi=Cr(),Wi=Ur(),_i=Gr(),Xi=Wr(),Vi=ge(),Bi=Kr(),Hi=Jr(),Ki=en(),Yi=rn(),Ji=ln();pn.exports={parse:mi,valid:wi,clean:Ei,inc:gi,diff:$i,major:yi,minor:xi,patch:Ri,prerelease:bi,compare:Oi,rcompare:vi,compareLoose:Ii,compareBuild:Si,sort:ki,rsort:Ni,gt:Li,lt:Ai,eq:Ti,neq:ji,gte:Pi,lte:qi,cmp:Ci,coerce:Di,Comparator:Ui,Range:Fi,satisfies:zi,toComparators:Gi,maxSatisfying:Mi,minSatisfying:Wi,minVersion:_i,validRange:Xi,outside:Vi,gtr:Bi,ltr:Hi,intersects:Ki,simplifyRange:Yi,subset:Ji,SemVer:di,re:Je.re,src:Je.src,tokens:Je.t,SEMVER_SPEC_VERSION:un.SEMVER_SPEC_VERSION,RELEASE_TYPES:un.RELEASE_TYPES,compareIdentifiers:fn.compareIdentifiers,rcompareIdentifiers:fn.rcompareIdentifiers}});var Te=new TextDecoder;function ie(e){let t=e.indexOf("@",e.startsWith("@")?1:0);return t<0?{name:e,version:""}:{name:e.slice(0,t),version:e.slice(t+1)}}async function yt(e,t){let r=String(t??"").split(/\s+/).filter(o=>o.startsWith("sha512-")).map(o=>o.split("?")[0]);if(r.length===0)throw new Error("The package has no SHA-512 integrity");if(!globalThis.crypto?.subtle)throw new Error("Integrity checks need a secure context (https or localhost)");let n=new Uint8Array(await crypto.subtle.digest("SHA-512",e)),s="sha512-"+btoa(Array.from(n,o=>String.fromCharCode(o)).join(""));if(!r.includes(s))throw new Error(`Integrity check failed: expected ${r[0]}, got ${s}`);return s}async function xt(e,t=268435456){let r=new Blob([e]).stream().pipeThrough(new DecompressionStream("gzip")).getReader(),n=[],s=0;for(let o=await r.read();!o.done;o=await r.read()){if(s+=o.value.length,s>t)throw await r.cancel(),new Error(`The tarball unpacks to more than ${t} bytes`);n.push(o.value)}return new Uint8Array(await new Blob(n).arrayBuffer())}function _(e,t,r){let n=e.subarray(t,t+r),s=n.indexOf(0);return Te.decode(s<0?n:n.subarray(0,s))}function Rt(e,t,r){if(e[t]&128)return e.subarray(t+1,t+r).reduce((s,o)=>s*256+o,e[t]&127);let n=_(e,t,r).trim();if(!/^[0-7]*$/.test(n))throw new Error("Corrupt tar header");return n===""?0:parseInt(n,8)}function Jn(e){let t=0;for(let r=0;r<512;++r)t+=r>=148&&r<156?32:e[r];if(Rt(e,148,8)!==t)throw new Error("Corrupt tar header checksum")}function Zn(e){let t={},r=0;for(;r0)||r+s>e.length)throw new Error("Corrupt pax header");let o=Te.decode(e.subarray(n+1,r+s-1)),i=o.indexOf("=");t[o.slice(0,i)]=o.slice(i+1),r+=s}return t}function Qn(e,t){let r=e.subarray(t,t+512);Jn(r);let n=Rt(r,124,12),s=t+512;if(s+n>e.length)throw new Error("Truncated tar archive");return{header:r,type:r[156]===0?"0":String.fromCharCode(r[156]),data:e.subarray(s,s+n),next:s+Math.ceil(n/512)*512}}function es(e,t){return t+512>e.length||e.subarray(t,t+512).every(r=>r===0)}function ts(e){let t=_(e,0,100),r=_(e,257,5)==="ustar"?_(e,345,155):"";return r?`${r}/${t}`:t}var $t={x:(e,t)=>({...e,pax:Zn(t).path}),L:(e,t)=>({...e,long:_(t,0,t.length)}),g:e=>e};function bt(e){let t=[],r={};for(let n=0;!es(e,n);){let{header:s,type:o,data:i,next:c}=Qn(e,n);if(n=c,Object.hasOwn($t,o)){r=$t[o](r,i);continue}(o==="0"||o==="7")&&t.push({path:r.pax??r.long??ts(s),bytes:i}),r={}}return t}var Re=F(C(),1);var R=(e,t,...r)=>e.cppFunction(`webfront.developer.${t}`)(...r);async function G(e,t){let r=[],n=0;for(;;){let s=await R(e,"read",t,n);if(r.push(s),n+=s.length,s.length<262144)break;if(n>256*1024*1024)throw new Error("Project file is too large")}return new Uint8Array(await new Blob(r).arrayBuffer())}async function Z(e,{id:t,path:r,bytes:n},s){for(let o=0;o{}),c}}async function Zi(e,t){let r=[],n=0;for(;;){let{done:s,value:o}=await e.read();if(s)return r;if(n+=o.length,n>t)throw new Error("Compressed download exceeds its byte limit");r.push(o)}}async function Qi(e,t){try{return await Zi(e,t)}catch(r){throw await e.cancel().catch(()=>{}),r}finally{e.releaseLock()}}async function hn(e,t=64*1024*1024){if(!e.ok)throw new Error(`Download: HTTP ${e.status}`);if(Number(e.headers.get("content-length"))>t)throw new Error("Compressed download exceeds its byte limit");return new Uint8Array(await new Blob(await Qi(e.body.getReader(),t)).arrayBuffer())}var M=".webfront/developer/packages",ea=/[\\\0:*?"<>|]/,ta=e=>e.split("/").some(t=>!t||t==="."||t==="..");function Ze(e){return typeof e!="string"||!e||ea.test(e)?!0:ta(e)}function A(e){if(Ze(e))throw new Error(`Unsafe package path: ${e}`);return e}var ra=new TextDecoder,na=["preinstall","install","postinstall"];async function dn(e){let t=new Map,r;for(let n of bt(await xt(e))){let s=n.path.indexOf("/"),o=n.path.slice(0,s);if(s<1||o==="."||o===".."||(r??(r=o))!==o)throw new Error("Invalid npm tarball root");let i=A(n.path.slice(s+1));if(t.has(i))throw new Error(`Duplicate package path: ${i}`);t.set(i,n.bytes)}return t}var sa=e=>na.some(t=>e.scripts?.[t]),oa=e=>e.has("binding.gyp")||[...e.keys()].some(t=>t.endsWith(".node"));function ia(e,t){return sa(e)||e.gypfile?!0:oa(t)}function mn(e,t,r){let n=JSON.parse(ra.decode(e.get("package.json")));if(n.name!==t||n.version!==r)throw new Error("npm archive identity mismatch");if(ia(n,e))throw new Error(`${t} needs an unsupported install script or native module`);return n}function W(e){return!e||typeof e!="object"?!1:!Array.isArray(e)}var Qe="webfront.project.json",et="webfront-packages.lock.json",x=Qe,S=et;function aa(e){if(e===void 0||e==="")return"";if(typeof e!="string"||e.endsWith("/")||Ze(e)||e===".webfront"||e.startsWith(".webfront/"))throw new Error(`Unsafe manifest directory: ${e}`);return e}function Ol(e){let t=aa(e);x=t?`${t}/${Qe}`:Qe,S=t?`${t}/${et}`:et}var ee=1,tt=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,ca=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,la=/^[0-9A-Za-z.+\-^~<>=*| ]{1,128}$/,En=/^[A-Za-z0-9][A-Za-z0-9:_.-]{0,63}$/,rt=/^[A-Za-z_][A-Za-z0-9_]*$/,gn=["format","name","version","dependencies","registry","scripts","entries","providers","test","permissions","developer"],ua=["files","publish","fetch"],$=e=>{throw new Error(`${x}: ${e}`)};function P(e,t){return W(e)||$(`${t} must be an object`),e}function ye(e,t,r){for(let n of Object.keys(e))t.includes(n)||$(`unknown key "${n}" in ${r}`)}function $e(e,t){typeof e!="string"&&$(`${t} must be a project path`);try{return A(e)}catch{return $(`${t} is not a safe project-relative path: ${e}`)}}function $n(e,t){return(!Array.isArray(e)||e.length>256)&&$(`${t} must be an array of at most 256 paths`),e.map((r,n)=>$e(r,`${t}[${n}]`))}function fa(e){let t=P(e,"dependencies");for(let[r,n]of Object.entries(t))tt.test(r)||$(`invalid npm package name "${r}"`),(typeof n!="string"||!la.test(n)||n!==n.trim())&&$(`invalid version range for "${r}"`);return t}var nt=e=>e.startsWith("/")&&!e.startsWith("//")&&!e.includes("\\");function pa(e){if(typeof e!="string"&&$("registry must be a URL"),nt(e))return e;let t;try{t=new URL(e)}catch{return $("registry must be an https URL or an absolute path")}return t.protocol!=="https:"&&$("registry must use https"),e}function ha(e){let t=P(e,"scripts");for(let[r,n]of Object.entries(t))(!En.test(r)||typeof n!="string"||!n||n.length>1024)&&$(`invalid script "${r}"`);return t}function da(e){let t=P(e,"entries");for(let[r,n]of Object.entries(t))En.test(r)||$(`invalid entry name "${r}"`),$e(n,`entries.${r}`);return t}function ma(e,t){let r=P(e,"providers");for(let[n,s]of Object.entries(r))rt.test(n)||$(`invalid provider name "${n}"`),P(s,`providers.${n}`),ye(s,["entry","output"],`providers.${n}`),typeof s.entry!="string"&&$(`providers.${n}.entry must name an entry or a path`),Object.hasOwn(t,s.entry)||$e(s.entry,`providers.${n}.entry`),$e(s.output,`providers.${n}.output`).endsWith(".hpp")||$(`providers.${n}.output must be a .hpp file`);return r}function wa(e){let t=P(e,"test");return ye(t,["specs"],"test"),t.specs!==void 0&&$n(t.specs,"test.specs"),t}function Ea(e,t){let r;try{r=new URL(e)}catch{return $(`${t} must be an https origin`)}return(r.protocol!=="https:"||r.origin!==e)&&$(`${t} must be an https origin without a path`),e}function ga(e){let t=P(e,"permissions");for(let r of Object.keys(t))ua.includes(r)||$(`unknown permission "${r}"`);for(let r of["files","publish"])t[r]!==void 0&&$n(t[r],`permissions.${r}`);return t.fetch!==void 0&&((!Array.isArray(t.fetch)||t.fetch.length>64)&&$("permissions.fetch must be an array of origins"),t.fetch.forEach((r,n)=>Ea(r,`permissions.fetch[${n}]`))),t}var wn={Ctrl:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"},vl="F9";function $a(e){if(typeof e!="string")return null;let t=e.split("+"),r=t.pop();if(!/^F(?:[1-9]|1[0-2])$/.test(r)||new Set(t).size!==t.length)return null;let n={key:r,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1};for(let s of t){if(!Object.hasOwn(wn,s))return null;n[wn[s]]=!0}return n}function ya(e){let t=P(e,"developer");return ye(t,["terminalShortcut"],"developer"),t.terminalShortcut!==void 0&&!$a(t.terminalShortcut)&&$('developer.terminalShortcut must be a function key, F1 to F12, optionally after Ctrl, Alt, Shift or Meta (for instance "Ctrl+Shift+F9")'),t}function xa(e){(typeof e.name!="string"||!tt.test(e.name))&&$("name must be a lower-case npm package name"),(typeof e.version!="string"||!ca.test(e.version))&&$("version must be a semantic version")}function Ra(e){e.format!==ee&&(Number.isInteger(e.format)&&e.format>ee&&$(`format ${e.format} is not supported by this environment (it reads format ${ee}); update the environment`),$(`format must be ${ee}`))}function te(e){P(e,"the manifest"),Ra(e),ye(e,gn,"the manifest"),xa(e);let t=e.entries===void 0?{}:da(e.entries);return{...e,dependencies:e.dependencies===void 0?{}:fa(e.dependencies),entries:t,providers:e.providers===void 0?{}:ma(e.providers,t),...e.registry===void 0?{}:{registry:pa(e.registry)},...e.scripts===void 0?{}:{scripts:ha(e.scripts)},...e.test===void 0?{}:{test:wa(e.test)},...e.permissions===void 0?{}:{permissions:ga(e.permissions)},...e.developer===void 0?{}:{developer:ya(e.developer)}}}function st(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return $("not valid JSON")}return{source:t,manifest:te(t)}}function Il(e){return st(e).manifest}function ot(e){let t={};for(let r of gn)e[r]!==void 0&&(t[r]=e[r]);return JSON.stringify(t,null,2)+` +`}function yn(e){return{format:ee,name:e,version:"0.1.0",dependencies:{}}}function xn(e){let r=(String(e??"").split("/").filter(Boolean).pop()??"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[^a-z0-9]+/,"").replace(/-+$/,"");return tt.test(r)?r:"webfront-app"}async function xe(e){let t=JSON.stringify(Object.entries(e).sort(([n],[s])=>ns?1:0)),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return[...new Uint8Array(r)].map(n=>n.toString(16).padStart(2,"0")).join("")}var it=e=>/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(e),be=(e,t)=>`${e.replace("/","+")}@${t}`,at=(e,t,r)=>`${be(e,t)}-${r.slice(7).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}`;async function ba(e,t,{fetchImpl:r,signal:n}){let s=await r(new URL(e.replace("/","%2f"),t),{signal:n});if(!s.ok)throw new Error(`Registry metadata for ${e}: HTTP ${s.status}`);return s.json()}function Oa(e,t){let r=e["dist-tags"]?.[t];return r||(Re.default.valid(t)?t:Re.default.maxSatisfying(Object.keys(e.versions??{}),t))}function va(e,t,r){let n=r||"latest",s=Oa(e,n),o=e.versions?.[s];if(!o||!Re.default.valid(s))throw new Error(`Cannot resolve ${t}@${n}`);return{version:s,manifest:o}}async function Ia(e,t,r,{fetchImpl:n,signal:s}){let o=new URL(t.dist?.tarball,r);if(o.protocol!=="https:"&&o.origin!==r.origin)throw new Error("Package tarballs must use HTTPS or the registry origin");let i=await n(o,{signal:s});if(!i.ok)throw new Error(`Package download for ${e}: HTTP ${i.status}`);let c=await hn(i);return{bytes:c,integrity:await yt(c,t.dist.integrity)}}function ct(e){let t=new URL(e,globalThis.location?.href),r=t.origin===globalThis.location?.origin;if(e.startsWith("/")?!nt(e)||!r:t.protocol!=="https:"&&!r)throw new Error(`The npm registry must use HTTPS or the application origin: ${e}`);return t.pathname.endsWith("/")||(t.pathname+="/"),t}async function D(e,t,{registry:r,fetchImpl:n=fetch,signal:s}){if(!it(e))throw new Error(`Unsupported npm package name: ${e}`);let o=ct(r),i={fetchImpl:n,signal:s},{version:c,manifest:a}=va(await ba(e,o,i),e,t),{bytes:l,integrity:u}=await Ia(e,a,o,i),f=await dn(l),m=mn(f,e,c);return{id:be(e,c),key:at(e,c,u),manifest:m,integrity:u,files:f}}var Oe=F(C(),1);function Sa(e,t,r){let n=e?.roots?.[t];return n?.requested===r&&e.packages[n.id]?e.packages[n.id]:Oe.default.validRange(r)?Object.values(e?.packages??{}).filter(o=>o.name===t&&Oe.default.satisfies(o.version,r)).sort((o,i)=>Oe.default.rcompare(o.version,i.version))[0]??null:null}function Rn({registry:e="https://registry.npmjs.org/",fetchImpl:t=fetch,signal:r,download:n=D,previous:s}){let o=new Map;return async(i,c)=>{let a=`${i}@${c}`;if(o.has(a))return o.get(a);let l=Sa(s,i,c),u=await n(i,l?.version??c,{registry:e,fetchImpl:t,signal:r});if(l&&u.integrity!==l.integrity)throw new Error(`${u.id} no longer matches the integrity recorded in the lock`);return o.set(a,u),u}}var bn=F(C(),1),On=(e,t,r)=>new Error(`${e.name}@${e.version} requires peer ${t}@${r}; install a compatible root explicitly`);function ka(e,t,r){if(e.manifest.peerDependenciesMeta?.[t]?.optional)return null;throw On(e,t,r)}function Na(e,[t,r],{nodes:n,roots:s}){let o=s[t]?.id??e.dependencies[t];if(!o)return ka(e,t,r);if(!bn.default.satisfies(n[o].version,r))throw On(e,t,r);return o}function La(e,t){for(let r of Object.entries(e.manifest.peerDependencies??{})){let n=Na(e,r,t);n&&(e.dependencies[r[0]]=n)}}function vn(e,t){for(let r of Object.values(e))La(r,{nodes:e,roots:t})}var In=F(C(),1);function Aa(e,t){return!it(t.name)||!In.default.valid(t.version)?!1:e===be(t.name,t.version)}function Ta(e){return e.integrity?.startsWith("sha512-")?e.key===at(e.name,e.version,e.integrity):!1}function ja(e,t,r){if(!Aa(t,r)||!Ta(r))throw new Error("Invalid locked package");for(let n of r.files)A(n);if(Object.values(r.dependencies).some(n=>!e.packages[n]))throw new Error("Dangling locked dependency")}function Pa(e){return e?.format!==1?!1:!!e.roots&&!!e.packages}function lt(e){if(!Pa(e))throw new Error("Unsupported package lock");if(Object.keys(e.packages).length>512)throw new Error("The package lock exceeds 512 packages");for(let[t,r]of Object.entries(e.packages))ja(e,t,r);if(Object.values(e.roots).some(t=>!e.packages[t.id]))throw new Error("Dangling locked root");return e}function qa(e,t,r){if(Object.keys(e.nodes).length>=512)throw new Error("Dependency graph exceeds 512 packages");for(let n of r.files.values())e.total+=n.length;if(e.total>256*1024*1024)throw new Error("Dependency graph exceeds 256 MiB");e.nodes[r.id]={name:t,version:r.manifest.version,integrity:r.integrity,key:r.key,manifest:r.manifest,files:[...r.files.keys()].sort(),dependencies:{}},e.downloads.set(r.id,r.files)}async function Ca(e,t){let r={};for(let n of e){let{name:s,version:o}=ie(n);r[s]={requested:o||"latest",id:await t(s,o||"latest")}}return r}async function Sn(e,t={}){let r=Rn(t),n={nodes:{},downloads:new Map,total:0},s=async(i,c)=>{t.signal?.throwIfAborted();let a=await r(i,c);if(n.nodes[a.id])return a.id;qa(n,i,a);for(let[l,u]of Object.entries(a.manifest.dependencies??{}).sort())n.nodes[a.id].dependencies[l]=await s(l,u);return a.id},o=await Ca(e,s);return vn(n.nodes,o),{lock:{format:1,registry:t.registry??"https://registry.npmjs.org/",roots:o,packages:n.nodes},downloads:n.downloads}}var ut=F(C(),1);var Da=new TextDecoder,Ua=new TextEncoder,ve="No webfront.project.json: run wf init, then wf dev (the interface is TypeScript/TSX in ui/; wf create app writes a first one; wf help agents gives the sequence)",Ie="The lock does not match the dependencies of webfront.project.json; run wf install --update to resolve them again";async function kn(e,t){try{return await G(e,t)}catch(r){if(r.message.includes("Cannot read project file:"))return null;throw r}}function Fa(e,t,r){return t?r===t.requested?!0:ut.default.validRange(r)!==null&&ut.default.satisfies(e.packages[t.id].version,r):!1}function za(e,t){let r=Object.keys(t);return r.length===Object.keys(e.roots).length&&r.every(n=>Fa(e,e.roots[n],t[n]))}function Ga(e,t,r){return e?t?t.manifestDigest===void 0?za(t,e.dependencies)?"legacy":"desynchronized":t.manifestDigest===r?"consistent":"desynchronized":"unlocked":"no-manifest"}async function re(e){let t=await R(e,"state",`${x} ${S}`),r=await kn(e,x),n=await kn(e,S),{source:s,manifest:o}=r?st(r):{source:null,manifest:null},i=n?lt(JSON.parse(Da.decode(n))):null,c=o?await xe(o.dependencies):null;return{manifest:o,source:s,lock:i,token:t,status:Ga(o,i,c),digest:c}}var Ln=e=>e.status==="desynchronized"?`Warning: ${Ie}.\r `:"";async function An(e,t,r,{signal:n}={}){let s=[];try{for(let[o,i]of t){n?.throwIfAborted();let c=await R(e,"begin",o,!1);s.push(c),await Z(e,{id:c,path:"output",bytes:i},n)}n?.throwIfAborted(),await R(e,"commitGroup",s.join(` `),`${x} @@ -9,8 +9,8 @@ ${S}`,r.token)}catch(o){for(let i of s)await R(e,"abort",i).catch(()=>{});throw `);async function Ba(e,t,r){let n=[],s=0;for(;;){let o;try{o=await R(e,"read",t,s)}catch(i){if(Pn(i))return null;throw i}if(s+=o.length,s>r)return null;if(n.push(o),o.length<262144)return new Uint8Array(await new Blob(n).arrayBuffer())}}async function ft(e,t,{signal:r,limit:n=1/0}={}){let s=await Xa(e,t);if(!s)return{state:"missing",size:0};if(s.integrity!==t.integrity||!W(s.files)||!Va(s,t))return{state:"corrupted",size:0};let o=0;for(let i of t.files){r?.throwIfAborted();let c=await Ba(e,`${Tn(t)}/${i}`,n-o);if(!c||await qn(c)!==s.files[i])return{state:"corrupted",size:0};o+=c.length}return{state:"valid",size:o}}var tu=async(e,t,r)=>(await ft(e,t,r)).state;var Ha="https://registry.npmjs.org/";function Ka({registry:e,registryExplicit:t}={},r){return t&&e?{url:e,source:"application option"}:r?.registry?{url:r.registry,source:x}:{url:e||Ha,source:"default"}}function pt(e,t){let r=Ka(e,t);return ct(r.url),r}var ht=({url:e,source:t})=>`Registry: ${e} (${t})`,Ya=256*1024*1024,Ja=e=>[...e.values()].reduce((t,r)=>t+r.length,0),Za=e=>new Error(`The locked packages exceed ${e/(1024*1024)} MiB unpacked`);async function Qa(e,t,{signal:r,limit:n}){let s=[],o=0;for(let[i,c]of Object.entries(t.packages)){r?.throwIfAborted();let a=await ft(e,c,{signal:r,limit:n-o});o+=a.size,s.push({id:i,node:c,state:a.state})}return{states:s,size:o}}async function dt(e,t,{registry:r,offline:n=!1,signal:s,progress:o=()=>{},fetchImpl:i=fetch,limit:c=Ya}){let{states:a,size:l}=await Qa(e,t,{signal:s,limit:c}),u=l,f={verified:a.filter(({state:m})=>m==="valid").length,restored:0,problems:[]};for(let{id:m,node:d,state:T}of a.filter(({state:k})=>k!=="valid")){if(n){f.problems.push(`${m} (${T})`);continue}o(`Restoring ${m}${T==="corrupted"?" (corrupted in the cache)":""}`);let k=await D(d.name,d.version,{registry:r,fetchImpl:i,signal:s});if(k.integrity!==d.integrity)throw new Error(`${m} no longer matches the integrity recorded in the lock`);if(u+=Ja(k.files),u>c)throw Za(c);await ke(e,d,k.files,{signal:s}),f.restored++}if(f.problems.length)throw new Error(`The cache does not match ${S}; missing or corrupted, nothing downloaded:\r ${f.problems.join(`\r `)}\r -Run wf restore to download them.`);return f}function ec(e){let t=e.includes("--offline");if(e.some(r=>r!=="--offline"))throw new Error("Usage: wf restore [--offline]");return{offline:t}}async function au(e,t,{registry:r,registryExplicit:n,signal:s,progress:o=()=>{},fetchImpl:i=fetch}={}){let{offline:c}=ec(t),a=await re(e);if(!a.manifest)throw new Error(ve);if(!a.lock)throw new Error(`No ${S}: run wf install to resolve the dependencies`);let l=c?null:pt({registry:r,registryExplicit:n},a.manifest);o(c?"Offline: no registry is contacted":ht(l));let u=await dt(e,a.lock,{registry:l?.url,offline:c,signal:s,progress:o,fetchImpl:i}),f=Object.keys(a.lock.packages).length,m=c?`Cache verified offline: ${f} packages match ${S}.`:`Restored ${u.restored} of ${f} packages (${u.verified} already in the cache). Lock: ${S}`;return{...u,registry:l,text:Ln(a)+m}}var Un=e=>{let{name:t,version:r}=ie(e);return[t,r||void 0]};function tc(e,t){let{version:r}=e.packages[t.id];return!(mt.default.valid(t.requested)!==null)&&t.requested!=="latest"&&mt.default.validRange(t.requested)!==null?t.requested:`^${r}`}async function wu(e,[t,...r],{signal:n}={}){if(r.length)throw new Error("Usage: wf init [name]");let{lock:s}=await re(e),o=$n(t??xn(""));s&&(o.dependencies=Object.fromEntries(Object.entries(s.roots).map(([c,a])=>[c,tc(s,a)]))),te(o),await Q(e,x,new Map([["output",Se(ot(o))]]),{directory:!1,replace:!1,signal:n});let i=s?` with the ${Object.keys(o.dependencies).length} dependencies of ${S}`:"";return`Created ${x}${i}. Add libraries with wf install .`}function rc(e,t){let r={...e.manifest.dependencies},n=new Set;for(let s of t){let[o,i]=Un(s);r[o]=i??"latest",i&&i!=="latest"&&n.add(o)}return te({...e.source,dependencies:r}),{dependencies:r,explicit:n}}function nc(e,t){let r={...e.source,dependencies:t};return te(r),r}function sc({dependencies:e,explicit:t},r,n){let s={...e};for(let o of n){let i=Un(o)[0];t.has(i)||(s[i]=`^${r.packages[r.roots[i].id].version}`)}return s}async function oc(e,t,r){let n=Object.entries(e).map(([i,c])=>`${i}@${c}`),{lock:s,downloads:o}=await Sn(n,{registry:r.registry,signal:r.signal,fetchImpl:r.fetchImpl,previous:t,download:async(...i)=>(r.progress(`Resolving ${i[0]}@${i[1]}`),D(...i))});return{lock:s,downloads:o}}async function ic(e,t,r,{signal:n,progress:s}){for(let[o,i]of r)s(`Storing ${o}`),await ke(e,t.packages[o],i,{signal:n})}function ac(e){let t=e.includes("--update"),r=e.filter(n=>n!=="--update");if(r.some(n=>n.startsWith("-")))throw new Error("Usage: wf install [--update] [[@range] ...]");return{update:t,specs:r}}async function Cn(e,t,{manifest:r,lock:n},s){let o=new Map([[S,Se(JSON.stringify(n,null,2)+` -`)]]);r&&o.set(x,Se(ot(r))),await An(e,o,t,s)}var Dn=async(e,t)=>({format:e.format,manifestDigest:await xe(t),...e});async function Eu(e,t,{registry:r,registryExplicit:n,signal:s,progress:o=()=>{},fetchImpl:i=fetch}){let{update:c,specs:a}=ac(t),l=await re(e);if(!l.manifest)throw new Error(ve);let u=pt({registry:r,registryExplicit:n},l.manifest),f={registry:u.url,signal:s,fetchImpl:i,progress:o};if(a.length&&c)throw new Error("Usage: wf install --update does not take packages");if(a.length&&l.status==="desynchronized")throw new Error(Ie);if(!a.length&&!c&&l.status==="desynchronized")throw new Error(Ie);o(ht(u));let m=l.status==="consistent"||l.status==="legacy";if(!a.length&&!c&&m){let{restored:U}=await dt(e,l.lock,f);if(l.status==="consistent")return{lock:l.lock,restored:U,registry:u};let oe=await Dn(l.lock,l.manifest.dependencies);return await Cn(e,l,{manifest:null,lock:oe},{signal:s}),{lock:oe,restored:U,registry:u}}let d=rc(l,a),T=m&&!c?l.lock:void 0,k=await oc(d.dependencies,T,f),Ae=sc(d,k.lock,a);await ic(e,k.lock,k.downloads,{signal:s,progress:o});let se=await Dn(k.lock,Ae),$=a.length?nc(l,Ae):null;return await Cn(e,l,{manifest:$,lock:se},{signal:s}),{lock:se,restored:0,registry:u}}var cc=()=>[x,S,".webfront"],ne=(e,t)=>e===t||e.startsWith(t+"/");function wt(e){try{return A(e)}catch{throw new Error(`Not a project-relative path: ${e}`)}}var Ne=(e,t,r)=>new Error(`Permission denied: ${e} ${t} is not granted by permissions.${r} in ${x}`);function Fn(e,t){let r=wt(t);if(![...e?.files??[],...e?.publish??[]].some(s=>ne(r,s)))throw Ne("reading",t,"files");return r}function zn(e,t){let r=t===""||t==="."?"":wt(t),n=[...e?.files??[],...e?.publish??[]];if(r&&n.some(o=>ne(r,o)))return{path:r,keep:()=>!0};let s=o=>n.some(i=>ne(o,i)||i.startsWith(o+"/"));if(!n.some(o=>r===""||o.startsWith(r+"/")))throw Ne("listing",r||"the project root","files");return{path:r,keep:o=>s(r?`${r}/${o.replace(/\/$/,"")}`:o.replace(/\/$/,""))}}function Gn(e,t){let r=wt(t);if(cc().some(n=>ne(r,n)))throw new Error(`Permission denied: ${t} is managed by wf and never written by a script`);if(!(e?.publish??[]).some(n=>ne(r,n)))throw Ne("writing",t,"publish");return r}function xu(e,t,r){let n=new URL(t,r);if(!(e?.fetch??[]).includes(n.origin))throw Ne("fetching",n.origin,"fetch");return n}var lc=2e3,Wn=600,Le=[1,3600],Mn=4,Et=class extends Error{constructor(t,r){super(t),this.exitCode=r}},Su=(e,t=1/0,r=Date.now())=>Math.min(r+e*1e3,t),ku=(e,t=Date.now())=>Math.max(0,(e-t)/1e3);function Nu(e,t){let r=Wn,n=e;if(n[0]==="--timeout"){if(r=Number(n[1]),!Number.isInteger(r)||rLe[1])throw new Error(`--timeout expects whole seconds from ${Le[0]} to ${Le[1]}`);n=n.slice(2)}if(!n.length||n[0].startsWith("-"))throw new Error(`Usage: ${t}`);return{timeout:r,target:n[0],args:n.slice(1)}}function Lu(e,t,r,n,s=0){let o=e?.scripts??{};if(!Object.hasOwn(o,t)){let a=Object.keys(o).sort().join(", ")||"none";throw new Error(`No script "${t}" in ${x} (scripts: ${a})`)}let[i,...c]=n(o[t]);if(i==="wf"){if(s>=Mn)throw new Error(`Scripts call wf more than ${Mn} levels deep`);return{kind:"wf",argv:[...c,...r]}}return{kind:"module",entry:{namespace:"project",path:A(i)},args:[...c,...r]}}function _n(e,t){if(e?.roots&&Object.hasOwn(e.roots,t)){let{id:n}=e.roots[t];return[n,e.packages[n]]}let r=Object.entries(e?.packages??{}).filter(([,n])=>n.name===t);if(r.length>1)throw new Error(`${t} is locked at several versions; install it as a root to choose one`);return r[0]??null}function uc(e,t){let r=t.webfront?.bin;if(typeof r=="string")return{[t.name.split("/").pop()]:r};if(r&&typeof r=="object"&&!Array.isArray(r))return r;throw t.bin?new Error(`${e} only declares an npm "bin" (a Node.js program); wf exec runs only "webfront.bin" entries`):new Error(`${e} has no WebFront executable entry ("webfront.bin" in its package.json)`)}function Au(e,t){let r=t.indexOf(":",t.startsWith("@")?t.indexOf("/"):0),[n,s]=r<0?[t,void 0]:[t.slice(0,r),t.slice(r+1)],o=_n(e,n);if(!o)throw new Error(`${n} is not installed: run wf install ${n}`);let[i,c]=o,a=uc(i,c.manifest),l=Object.keys(a),u=s??(l.length===1?l[0]:void 0);if(!u||!Object.hasOwn(a,u))throw new Error(`${i} has the WebFront entries ${l.join(", ")||"none"}: run wf exec ${n}:`);let f=String(a[u]).replace(/^\.\//,"");if(!c.files.includes(A(f)))throw new Error(`${i}: webfront.bin entry ${u} names a missing file ${f}`);return{id:i,name:u,entry:{namespace:"npm",path:`${i}/${f}`}}}var fc=new TextDecoder;function Tu({bridge:e,permissions:t,lock:r}){let n=new AbortController,s=[],o=new Set;async function i(a,l){let u=Gn(t,a);if(!(l instanceof Uint8Array))throw new TypeError("context.project.write expects a string or a Uint8Array");let f={path:u,state:"staging"};s.push(f);let m=null;try{m=await R(e,"begin",u,!1),await Z(e,{id:m,path:"output",bytes:l},n.signal),n.signal.throwIfAborted(),f.state="committing",await R(e,"commit",m),f.state="applied"}catch(d){let T=n.signal.aborted&&f.state!=="committing";throw f.state=T?"abandoned":"failed",m!==null&&await R(e,"abort",m).catch(()=>{}),d}}let c={read:a=>G(e,Fn(t,a)),list:async(a="")=>{let{path:l,keep:u}=zn(t,a);return JSON.parse(fc.decode(await R(e,"list",l))).filter(u)},write:i,resolve:a=>{let l=_n(r,a)?.[1];return l?{name:l.name,version:l.version,integrity:l.integrity}:null}};return{publications:s,async handle({operation:a,args:l}){if(n.signal.aborted)throw new Error("The script was stopped");if(!Object.hasOwn(c,a))throw new Error(`Unknown context operation: ${a}`);let u=c[a](...l);o.add(u);try{return await u}finally{o.delete(u)}},async finish(){for(let a of s)(a.state==="staging"||a.state==="committing")&&(a.unawaited=!0);for(;o.size;)await Promise.allSettled([...o]);await this.stop()},async stop(){n.abort(new Error("The script was stopped")),await Promise.allSettled([...o])}}}function ju({createWorker:e,host:t,message:r,signal:n,timeout:s=Wn,grace:o=lc,write:i}){return new Promise(c=>{let a=e(),l=[],u=null,f=!1,m=()=>u==="timeout"?124:130,d=$=>{f||(f=!0,a.terminate(),l.forEach(clearTimeout),n?.removeEventListener("abort",k),c({reason:u??"exit",...$}))},T=$=>{u||f||(u=$,a.postMessage({type:"abort"}),l.push(setTimeout(()=>d({code:m(),forced:o}),o)))},k=()=>T("interrupted"),se={console:$=>i(String($.text).replace(/\r?\n/g,`\r +Run wf restore to download them.`);return f}function ec(e){let t=e.includes("--offline");if(e.some(r=>r!=="--offline"))throw new Error("Usage: wf restore [--offline]");return{offline:t}}async function au(e,t,{registry:r,registryExplicit:n,signal:s,progress:o=()=>{},fetchImpl:i=fetch}={}){let{offline:c}=ec(t),a=await re(e);if(!a.manifest)throw new Error(ve);if(!a.lock)throw new Error(`No ${S}: run wf install to resolve the dependencies`);let l=c?null:pt({registry:r,registryExplicit:n},a.manifest);o(c?"Offline: no registry is contacted":ht(l));let u=await dt(e,a.lock,{registry:l?.url,offline:c,signal:s,progress:o,fetchImpl:i}),f=Object.keys(a.lock.packages).length,m=c?`Cache verified offline: ${f} packages match ${S}.`:`Restored ${u.restored} of ${f} packages (${u.verified} already in the cache). Lock: ${S}`;return{...u,registry:l,text:Ln(a)+m}}var Un=e=>{let{name:t,version:r}=ie(e);return[t,r||void 0]};function tc(e,t){let{version:r}=e.packages[t.id];return!(mt.default.valid(t.requested)!==null)&&t.requested!=="latest"&&mt.default.validRange(t.requested)!==null?t.requested:`^${r}`}async function wu(e,[t,...r],{signal:n}={}){if(r.length)throw new Error("Usage: wf init [name]");let{lock:s}=await re(e),o=yn(t??xn(""));s&&(o.dependencies=Object.fromEntries(Object.entries(s.roots).map(([c,a])=>[c,tc(s,a)]))),te(o),await Q(e,x,new Map([["output",Se(ot(o))]]),{directory:!1,replace:!1,signal:n});let i=s?` with the ${Object.keys(o.dependencies).length} dependencies of ${S}`:"";return`Created ${x}${i}. Add libraries with wf install .`}function rc(e,t){let r={...e.manifest.dependencies},n=new Set;for(let s of t){let[o,i]=Un(s);r[o]=i??"latest",i&&i!=="latest"&&n.add(o)}return te({...e.source,dependencies:r}),{dependencies:r,explicit:n}}function nc(e,t){let r={...e.source,dependencies:t};return te(r),r}function sc({dependencies:e,explicit:t},r,n){let s={...e};for(let o of n){let i=Un(o)[0];t.has(i)||(s[i]=`^${r.packages[r.roots[i].id].version}`)}return s}async function oc(e,t,r){let n=Object.entries(e).map(([i,c])=>`${i}@${c}`),{lock:s,downloads:o}=await Sn(n,{registry:r.registry,signal:r.signal,fetchImpl:r.fetchImpl,previous:t,download:async(...i)=>(r.progress(`Resolving ${i[0]}@${i[1]}`),D(...i))});return{lock:s,downloads:o}}async function ic(e,t,r,{signal:n,progress:s}){for(let[o,i]of r)s(`Storing ${o}`),await ke(e,t.packages[o],i,{signal:n})}function ac(e){let t=e.includes("--update"),r=e.filter(n=>n!=="--update");if(r.some(n=>n.startsWith("-")))throw new Error("Usage: wf install [--update] [[@range] ...]");return{update:t,specs:r}}async function Cn(e,t,{manifest:r,lock:n},s){let o=new Map([[S,Se(JSON.stringify(n,null,2)+` +`)]]);r&&o.set(x,Se(ot(r))),await An(e,o,t,s)}var Dn=async(e,t)=>({format:e.format,manifestDigest:await xe(t),...e});async function Eu(e,t,{registry:r,registryExplicit:n,signal:s,progress:o=()=>{},fetchImpl:i=fetch}){let{update:c,specs:a}=ac(t),l=await re(e);if(!l.manifest)throw new Error(ve);let u=pt({registry:r,registryExplicit:n},l.manifest),f={registry:u.url,signal:s,fetchImpl:i,progress:o};if(a.length&&c)throw new Error("Usage: wf install --update does not take packages");if(a.length&&l.status==="desynchronized")throw new Error(Ie);if(!a.length&&!c&&l.status==="desynchronized")throw new Error(Ie);o(ht(u));let m=l.status==="consistent"||l.status==="legacy";if(!a.length&&!c&&m){let{restored:U}=await dt(e,l.lock,f);if(l.status==="consistent")return{lock:l.lock,restored:U,registry:u};let oe=await Dn(l.lock,l.manifest.dependencies);return await Cn(e,l,{manifest:null,lock:oe},{signal:s}),{lock:oe,restored:U,registry:u}}let d=rc(l,a),T=m&&!c?l.lock:void 0,k=await oc(d.dependencies,T,f),Ae=sc(d,k.lock,a);await ic(e,k.lock,k.downloads,{signal:s,progress:o});let se=await Dn(k.lock,Ae),y=a.length?nc(l,Ae):null;return await Cn(e,l,{manifest:y,lock:se},{signal:s}),{lock:se,restored:0,registry:u}}var cc=()=>[x,S,".webfront"],ne=(e,t)=>e===t||e.startsWith(t+"/");function wt(e){try{return A(e)}catch{throw new Error(`Not a project-relative path: ${e}`)}}var Ne=(e,t,r)=>new Error(`Permission denied: ${e} ${t} is not granted by permissions.${r} in ${x}`);function Fn(e,t){let r=wt(t);if(![...e?.files??[],...e?.publish??[]].some(s=>ne(r,s)))throw Ne("reading",t,"files");return r}function zn(e,t){let r=t===""||t==="."?"":wt(t),n=[...e?.files??[],...e?.publish??[]];if(r&&n.some(o=>ne(r,o)))return{path:r,keep:()=>!0};let s=o=>n.some(i=>ne(o,i)||i.startsWith(o+"/"));if(!n.some(o=>r===""||o.startsWith(r+"/")))throw Ne("listing",r||"the project root","files");return{path:r,keep:o=>s(r?`${r}/${o.replace(/\/$/,"")}`:o.replace(/\/$/,""))}}function Gn(e,t){let r=wt(t);if(cc().some(n=>ne(r,n)))throw new Error(`Permission denied: ${t} is managed by wf and never written by a script`);if(!(e?.publish??[]).some(n=>ne(r,n)))throw Ne("writing",t,"publish");return r}function xu(e,t,r){let n=new URL(t,r);if(!(e?.fetch??[]).includes(n.origin))throw Ne("fetching",n.origin,"fetch");return n}var lc=2e3,Wn=600,Le=[1,3600],Mn=4,Et=class extends Error{constructor(t,r){super(t),this.exitCode=r}},Su=(e,t=1/0,r=Date.now())=>Math.min(r+e*1e3,t),ku=(e,t=Date.now())=>Math.max(0,(e-t)/1e3);function Nu(e,t){let r=Wn,n=e;if(n[0]==="--timeout"){if(r=Number(n[1]),!Number.isInteger(r)||rLe[1])throw new Error(`--timeout expects whole seconds from ${Le[0]} to ${Le[1]}`);n=n.slice(2)}if(!n.length||n[0].startsWith("-"))throw new Error(`Usage: ${t}`);return{timeout:r,target:n[0],args:n.slice(1)}}function Lu(e,t,r,n,s=0){let o=e?.scripts??{};if(!Object.hasOwn(o,t)){let a=Object.keys(o).sort().join(", ")||"none";throw new Error(`No script "${t}" in ${x} (scripts: ${a})`)}let[i,...c]=n(o[t]);if(i==="wf"){if(s>=Mn)throw new Error(`Scripts call wf more than ${Mn} levels deep`);return{kind:"wf",argv:[...c,...r]}}return{kind:"module",entry:{namespace:"project",path:A(i)},args:[...c,...r]}}function _n(e,t){if(e?.roots&&Object.hasOwn(e.roots,t)){let{id:n}=e.roots[t];return[n,e.packages[n]]}let r=Object.entries(e?.packages??{}).filter(([,n])=>n.name===t);if(r.length>1)throw new Error(`${t} is locked at several versions; install it as a root to choose one`);return r[0]??null}function uc(e,t){let r=t.webfront?.bin;if(typeof r=="string")return{[t.name.split("/").pop()]:r};if(r&&typeof r=="object"&&!Array.isArray(r))return r;throw t.bin?new Error(`${e} only declares an npm "bin" (a Node.js program); wf exec runs only "webfront.bin" entries`):new Error(`${e} has no WebFront executable entry ("webfront.bin" in its package.json)`)}function Au(e,t){let r=t.indexOf(":",t.startsWith("@")?t.indexOf("/"):0),[n,s]=r<0?[t,void 0]:[t.slice(0,r),t.slice(r+1)],o=_n(e,n);if(!o)throw new Error(`${n} is not installed: run wf install ${n}`);let[i,c]=o,a=uc(i,c.manifest),l=Object.keys(a),u=s??(l.length===1?l[0]:void 0);if(!u||!Object.hasOwn(a,u))throw new Error(`${i} has the WebFront entries ${l.join(", ")||"none"}: run wf exec ${n}:`);let f=String(a[u]).replace(/^\.\//,"");if(!c.files.includes(A(f)))throw new Error(`${i}: webfront.bin entry ${u} names a missing file ${f}`);return{id:i,name:u,entry:{namespace:"npm",path:`${i}/${f}`}}}var fc=new TextDecoder;function Tu({bridge:e,permissions:t,lock:r}){let n=new AbortController,s=[],o=new Set;async function i(a,l){let u=Gn(t,a);if(!(l instanceof Uint8Array))throw new TypeError("context.project.write expects a string or a Uint8Array");let f={path:u,state:"staging"};s.push(f);let m=null;try{m=await R(e,"begin",u,!1),await Z(e,{id:m,path:"output",bytes:l},n.signal),n.signal.throwIfAborted(),f.state="committing",await R(e,"commit",m),f.state="applied"}catch(d){let T=n.signal.aborted&&f.state!=="committing";throw f.state=T?"abandoned":"failed",m!==null&&await R(e,"abort",m).catch(()=>{}),d}}let c={read:a=>G(e,Fn(t,a)),list:async(a="")=>{let{path:l,keep:u}=zn(t,a);return JSON.parse(fc.decode(await R(e,"list",l))).filter(u)},write:i,resolve:a=>{let l=_n(r,a)?.[1];return l?{name:l.name,version:l.version,integrity:l.integrity}:null}};return{publications:s,async handle({operation:a,args:l}){if(n.signal.aborted)throw new Error("The script was stopped");if(!Object.hasOwn(c,a))throw new Error(`Unknown context operation: ${a}`);let u=c[a](...l);o.add(u);try{return await u}finally{o.delete(u)}},async finish(){for(let a of s)(a.state==="staging"||a.state==="committing")&&(a.unawaited=!0);for(;o.size;)await Promise.allSettled([...o]);await this.stop()},async stop(){n.abort(new Error("The script was stopped")),await Promise.allSettled([...o])}}}function ju({createWorker:e,host:t,message:r,signal:n,timeout:s=Wn,grace:o=lc,write:i}){return new Promise(c=>{let a=e(),l=[],u=null,f=!1,m=()=>u==="timeout"?124:130,d=y=>{f||(f=!0,a.terminate(),l.forEach(clearTimeout),n?.removeEventListener("abort",k),c({reason:u??"exit",...y}))},T=y=>{u||f||(u=y,a.postMessage({type:"abort"}),l.push(setTimeout(()=>d({code:m(),forced:o}),o)))},k=()=>T("interrupted"),se={console:y=>i(String(y.text).replace(/\r?\n/g,`\r `)+`\r -`,$.stream),exit:$=>d({code:u&&$.code===0?m():$.code,...Array.isArray($.diagnostics)?{diagnostics:$.diagnostics}:{}}),error:$=>d({code:u?m():1,error:$.error}),call:async $=>{let U;try{U={value:await t.handle($)}}catch(oe){U={error:oe.message}}f||a.postMessage({type:"reply",id:$.id,...U})}};a.onmessage=({data:$})=>se[$?.type]?.($),a.onerror=$=>{$.preventDefault?.(),d({code:1,error:$.message||"The script Worker failed"})},n?.addEventListener("abort",k,{once:!0}),l.push(setTimeout(()=>T("timeout"),s*1e3)),a.postMessage({type:"run",...r}),n?.aborted&&k()})}function pc(e,t){let r=t?e:e.filter(o=>o.unawaited),n=o=>r.filter(i=>i.state===o).map(({path:i})=>i),s=[];return t&&n("applied").length&&s.push(`Applied before the stop: ${n("applied").join(", ")}`),n("abandoned").length&&s.push(`Abandoned, unchanged: ${n("abandoned").join(", ")}`),n("failed").length&&s.push(`Failed, unchanged: ${n("failed").join(", ")}`),s}function Pu(e,t,r){let n={interrupted:"stopped by Ctrl+C",timeout:"stopped at its time limit"}[t.reason],s=pc(r,n!==void 0);if(t.code===0&&!n&&!s.length)return`${e} completed.`;let o=t.forced?` (terminated after the ${t.forced/1e3} s grace period)`:"",i=t.code===0&&!n?1:t.code,c=n?`${n}${o}`:t.code===0?"ended without applying all its writes":`exited with code ${t.code}`;throw new Et([t.error,`${e} ${c}`,...s].filter(Boolean).join(`\r -`),i)}var Mu=new TextDecoder,mc=["",".tsx",".ts",".jsx",".js",".mjs",".cjs",".json",".css","/index.tsx","/index.ts","/index.js"],Wu=new Map(Object.entries({mjs:"js",cjs:"js",js:"js",jsx:"jsx",ts:"ts",tsx:"tsx",css:"css",json:"json"}));async function wc(e,t,r){try{return await e(t,r)}catch(n){if(t!=="project")throw n;return}}function Ec(e,t,r,n){let s=new Map,o=(a,l)=>{let u=n?.packages?.[a];if(u)return s.has(a)||s.set(a,new Set(u.files)),s.get(a).has(l)?t(`${M}/${u.key}/${l}`):void 0},i=async(a,l)=>{if(a==="project")return t(l);let u=l.indexOf("/"),[f,m]=[l.slice(0,u),l.slice(u+1)];return e?e[f]?.get(m):o(f,m)};return{read:i,find:async(a,l)=>{for(let u of mc){let f=await wc(i,a,l+u);if(f!==void 0)return r.set(`${a}:${l+u}`,f),{path:l+u,namespace:a}}throw new Error(`Cannot resolve ${l}`)}}}var gc=new Set(["assert","async_hooks","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","domain","events","fs","http","http2","https","inspector","module","net","os","path","perf_hooks","process","punycode","querystring","readline","repl","stream","string_decoder","sys","timers","tls","trace_events","tty","url","util","v8","vm","wasi","worker_threads","zlib"]),yc=/^(?:node:|[a-z_][a-z0-9_]*(?:\/|$))/;function $c(e){if(e.startsWith("node:"))return e.slice(5).split("/")[0];let t=e.split("/")[0];return gc.has(t)?t:null}export{Et as ScriptExit,tu as cacheState,xu as checkFetch,aa as checkManifestDirectory,Fn as checkRead,Gn as checkWrite,Ec as createFinder,Ha as defaultRegistry,vl as defaultTerminalShortcut,Wn as defaultTimeout,xe as dependenciesDigest,ht as describeRegistry,Ie as desynchronized,D as downloadPackage,Ka as effectiveRegistry,Kl as embedTarget,ca as exactVersion,Au as execTarget,lc as gracePeriod,rt as identifier,wu as initProject,ft as inspectCache,Eu as install,zn as listable,re as loadProject,et as lockFileName,S as lockPath,_n as lockedPackage,za as locksDependencies,Qe as manifestFileName,ee as manifestFormat,xn as manifestName,x as manifestPath,$n as newManifest,ve as noManifest,$c as nodeBuiltin,yc as nodeImport,tt as npmName,Tn as packageDirectory,M as packageRoot,Il as parseManifest,Nu as parseRunOptions,ya as parseShortcut,An as publishTogether,st as readManifest,jn as recordPath,Nn as resolveEntry,Sn as resolvePackages,au as restore,dt as restorePackages,Su as runDeadline,Pu as runResult,ju as runWorker,A as safePackagePath,nt as sameOriginPath,Lu as scriptCommand,Tu as scriptHost,ku as secondsLeft,ot as serializeManifest,Ol as setManifestDirectory,ke as storePackage,Ln as syncNotice,Se as textBytes,Le as timeoutBounds,Ya as unpackedLimit,pt as usableRegistry,lt as validateLock,te as validateManifest}; +`,y.stream),exit:y=>d({code:u&&y.code===0?m():y.code,...Array.isArray(y.diagnostics)?{diagnostics:y.diagnostics}:{}}),error:y=>d({code:u?m():1,error:y.error}),call:async y=>{let U;try{U={value:await t.handle(y)}}catch(oe){U={error:oe.message}}f||a.postMessage({type:"reply",id:y.id,...U})}};a.onmessage=({data:y})=>se[y?.type]?.(y),a.onerror=y=>{y.preventDefault?.(),d({code:1,error:y.message||"The script Worker failed"})},n?.addEventListener("abort",k,{once:!0}),l.push(setTimeout(()=>T("timeout"),s*1e3)),a.postMessage({type:"run",...r}),n?.aborted&&k()})}function pc(e,t){let r=t?e:e.filter(o=>o.unawaited),n=o=>r.filter(i=>i.state===o).map(({path:i})=>i),s=[];return t&&n("applied").length&&s.push(`Applied before the stop: ${n("applied").join(", ")}`),n("abandoned").length&&s.push(`Abandoned, unchanged: ${n("abandoned").join(", ")}`),n("failed").length&&s.push(`Failed, unchanged: ${n("failed").join(", ")}`),s}function Pu(e,t,r){let n={interrupted:"interrupted",timeout:"stopped at its time limit"}[t.reason],s=pc(r,n!==void 0);if(t.code===0&&!n&&!s.length)return`${e} completed.`;let o=t.forced?` (terminated after the ${t.forced/1e3} s grace period)`:"",i=t.code===0&&!n?1:t.code,c=n?`${n}${o}`:t.code===0?"ended without applying all its writes":`exited with code ${t.code}`;throw new Et([t.error,`${e} ${c}`,...s].filter(Boolean).join(`\r +`),i)}var Mu=new TextDecoder,mc=["",".tsx",".ts",".jsx",".js",".mjs",".cjs",".json",".css","/index.tsx","/index.ts","/index.js"],Wu=new Map(Object.entries({mjs:"js",cjs:"js",js:"js",jsx:"jsx",ts:"ts",tsx:"tsx",css:"css",json:"json"}));async function wc(e,t,r){try{return await e(t,r)}catch(n){if(t!=="project")throw n;return}}function Ec(e,t,r,n){let s=new Map,o=(a,l)=>{let u=n?.packages?.[a];if(u)return s.has(a)||s.set(a,new Set(u.files)),s.get(a).has(l)?t(`${M}/${u.key}/${l}`):void 0},i=async(a,l)=>{if(a==="project")return t(l);let u=l.indexOf("/"),[f,m]=[l.slice(0,u),l.slice(u+1)];return e?e[f]?.get(m):o(f,m)};return{read:i,find:async(a,l)=>{for(let u of mc){let f=await wc(i,a,l+u);if(f!==void 0)return r.set(`${a}:${l+u}`,f),{path:l+u,namespace:a}}throw new Error(`Cannot resolve ${l}`)}}}var gc=new Set(["assert","async_hooks","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","domain","events","fs","http","http2","https","inspector","module","net","os","path","perf_hooks","process","punycode","querystring","readline","repl","stream","string_decoder","sys","timers","tls","trace_events","tty","url","util","v8","vm","wasi","worker_threads","zlib"]),$c=/^(?:node:|[a-z_][a-z0-9_]*(?:\/|$))/;function yc(e){if(e.startsWith("node:"))return e.slice(5).split("/")[0];let t=e.split("/")[0];return gc.has(t)?t:null}export{Et as ScriptExit,tu as cacheState,xu as checkFetch,aa as checkManifestDirectory,Fn as checkRead,Gn as checkWrite,Ec as createFinder,Ha as defaultRegistry,vl as defaultTerminalShortcut,Wn as defaultTimeout,xe as dependenciesDigest,ht as describeRegistry,Ie as desynchronized,D as downloadPackage,Ka as effectiveRegistry,Kl as embedTarget,ca as exactVersion,Au as execTarget,lc as gracePeriod,rt as identifier,wu as initProject,ft as inspectCache,Eu as install,zn as listable,re as loadProject,et as lockFileName,S as lockPath,_n as lockedPackage,za as locksDependencies,Qe as manifestFileName,ee as manifestFormat,xn as manifestName,x as manifestPath,yn as newManifest,ve as noManifest,yc as nodeBuiltin,$c as nodeImport,tt as npmName,Tn as packageDirectory,M as packageRoot,Il as parseManifest,Nu as parseRunOptions,$a as parseShortcut,An as publishTogether,st as readManifest,jn as recordPath,Nn as resolveEntry,Sn as resolvePackages,au as restore,dt as restorePackages,Su as runDeadline,Pu as runResult,ju as runWorker,A as safePackagePath,nt as sameOriginPath,Lu as scriptCommand,Tu as scriptHost,ku as secondsLeft,ot as serializeManifest,Ol as setManifestDirectory,ke as storePackage,Ln as syncNotice,Se as textBytes,Le as timeoutBounds,Ya as unpackedLimit,pt as usableRegistry,lt as validateLock,te as validateManifest}; diff --git a/js/developer/environment/runtime.mjs b/js/developer/environment/runtime.mjs index 20a608f2..19ab10b9 100644 --- a/js/developer/environment/runtime.mjs +++ b/js/developer/environment/runtime.mjs @@ -1,6 +1,8 @@ import {Terminal} from '@xterm/xterm'; import {FitAddon} from '@xterm/addon-fit'; -import {LineEditor, tokenize, wordAtEnd, unicodeProvider, clearScreen, historyLimit, inline} from './terminal.mjs'; +import {LineEditor, tokenize, wordAtEnd, unicodeProvider, clearScreen, historyLimit, inline, attachShortcuts} from './terminal.mjs'; +// The line editor and its interruption key, for a page that drives a command like the terminal (the integration specs). +export {LineEditor, interruptKey} from './terminal.mjs'; import {manifestPath, setManifestDirectory} from './manifest.mjs'; import {discoverCommands, runCommand, reservedNames} from './commands.mjs'; export {discoverCommands, reservedNames}; @@ -218,13 +220,13 @@ const cleanupRetryDelays = [20, 40, 80, 160, 320, undefined]; // wf test [--timeout ] [pattern]: the specs of "test.specs" under the Jasmine of the lock, in a frame of this page. // context.onReport receives the structured report, also when the run fails. --timeout, never later than the deadline -// of the wf script that runs this command, covers the whole command: no step waits for the bridge past it, and Ctrl+C -// ends every step as well. +// of the wf script that runs this command, covers the whole command: no step waits for the bridge past it, and an +// interruption ends every step as well. async function test(args, {bridge, signal, write = () => {}, createFrame, onReport, deadline: inherited}) { const {timeout, pattern} = parseTestOptions(args); const deadline = runDeadline(timeout, inherited); const limit = new AbortController(); - // Forward Ctrl+C into the deadline controller: older supported WebKit lacks AbortSignal.any. + // Forward an interruption into the deadline controller: older supported WebKit lacks AbortSignal.any. const interrupt = () => limit.abort(signal.reason); const preparing = limit.signal; const step = promise => abortable(promise, preparing); @@ -253,7 +255,7 @@ async function test(args, {bridge, signal, write = () => {}, createFrame, onRepo write('\n'); return reportResult(report); } catch (error) { - // An abort of the preparation ends the command like it ends a run: Ctrl+C with 130, the limit with 124, and a report. + // An abort of the preparation ends the command like it ends a run: an interruption with 130, the limit with 124, and a report. if (!error.report) { if (signal?.aborted) error = stoppedRun('interrupted', pattern); else if (limit.signal.aborted) error = stoppedRun('timeout', pattern); @@ -325,7 +327,7 @@ const purposes = { why: 'Shows which dependencies of the manifest bring a package, as chains of requirements.', info: 'Describes an installed package: license, integrity, files, dependencies and dependents.', build: 'Compiles the entries once into .webfront/developer/build/.', - dev: 'Compiles a TypeScript/TSX entry (ui/main.tsx), shows the interface in the window and rebuilds on every save. Ctrl+C stops it.', + dev: 'Compiles a TypeScript/TSX entry (ui/main.tsx), shows the interface in the window and rebuilds on every save. Escape or the Stop button stops it.', preview: 'Compiles an entry once and shows the interface in the window.', embed: 'Compiles an entry and packages it as a C++ header for the distributed application.', help: 'Lists the commands, describes one, or with agents gives the sequence for an agent.'}; @@ -359,7 +361,7 @@ function help([topic, ...extra] = [], {config} = {}) { return `${usage[topic]}\n${typeof purpose === 'function' ? purpose(config) : purpose}`; } return Object.values(usage).join('\n') + '\nAgents: wf help agents (the sequence, and how to run wf through MCP).' + - '\nCtrl+C interrupts a command. No system shell is exposed.' + automationHelp(); + '\nEscape or the Stop button interrupts a command. No system shell is exposed.' + automationHelp(); } const commands = {init, create, install: installCommand, restore: restoreCommand, run, exec, check, test, build, dev, preview, embed, list, why, info, help}; @@ -529,7 +531,7 @@ const builtins = { line('history', 'List the commands typed in this project; history -c clears them'), line('exit', 'End the session [with an exit code]'), line('help', 'List the commands'), ...[...cppCommands].map(([name, text]) => line(name, text)), - 'Paths are relative to the project. Ctrl+C interrupts a command. No system shell is exposed.'].join('\n'); + 'Paths are relative to the project. Escape or the Stop button interrupts a command. No system shell is exposed.'].join('\n'); }, ls: (args, {bridge, editor}) => ls(args, {bridge, width: editor?.columns?.() ?? 80, manifest: () => cachedManifest(bridge)}), cat: (args, {bridge, signal}) => cat(args, {bridge, signal}), @@ -645,6 +647,56 @@ export async function complete(line, {bridge, cppCommands = new Map()}) { return matching(await projectPaths(bridge, word)); } +// The Stop button: in the bar of the floating terminal window, else over the terminal's top right corner. +const stopStyles = ` +.webfront-terminal-stop{box-sizing:border-box;height:24px;margin:0;padding:0 10px;display:inline-flex;align-items:center;gap:6px;border:1px solid #8a3d3d;border-radius:4px;background:#5a1f1f;color:#ffe3e3;font:12px system-ui;cursor:pointer} +.webfront-terminal-stop::before{content:'';width:8px;height:8px;background:currentColor} +.webfront-terminal-stop:hover:not(:disabled){background:#7a2626} +.webfront-terminal-stop:focus-visible{outline:2px solid #d7fa85;outline-offset:1px} +.webfront-terminal-stop:disabled{opacity:.55;cursor:default} +.webfront-terminal-stop[hidden]{display:none} +:not(.webfront-terminal-bar)>.webfront-terminal-stop{position:absolute;top:6px;right:18px;z-index:10} +.webfront-terminal-bar>.webfront-terminal-stop{margin:0 6px 0 auto}`; +const styledPages = new WeakSet(); + +/** + * The Stop button of a terminal: shown while a command runs, it interrupts it like Escape (`interrupt`), then stays + * disabled until the command has ended. Pressing it leaves the focus in the terminal. + */ +function stopButton(page, {interrupt, focus}) { + if (!styledPages.has(page)) { + styledPages.add(page); + const style = page.createElement('style'); + style.textContent = stopStyles; + page.head.append(style); + } + const button = page.createElement('button'); + button.type = 'button'; + button.className = 'webfront-terminal-stop'; + button.textContent = 'Stop'; + button.title = 'Stop the command (Esc)'; + button.setAttribute('aria-label', 'Stop the running command'); + button.setAttribute('aria-keyshortcuts', 'Escape'); + button.hidden = true; + button.addEventListener('mousedown', event => event.preventDefault()); // the terminal keeps the focus + button.addEventListener('click', () => { + interrupt(); + focus(); + }); + return { + button, + /** A command starts: the button stops it until its signal is aborted. */ + running(signal) { + Object.assign(button, {hidden: false, disabled: signal.aborted}); + signal.addEventListener('abort', () => { button.disabled = true; }, {once: true}); + }, + ended() { + if (button.contains(page.activeElement)) focus(); // a hidden button would hold the keys + Object.assign(button, {hidden: true, disabled: false}); + }, + }; +} + /** The terminal of each page that had the focus last: the one a click on the page around the terminals gives it back to. */ const focusedTerminal = new WeakMap(); @@ -685,6 +737,11 @@ export async function mount({bridge, config, terminal: element, preview, onExit, inspectorUrl: new URL('./inspector.html', import.meta.url).href}); terminal.open(element); fit.fit(); + // Ctrl+C and ⌘C copy, Ctrl+V and ⌘V paste, Ctrl+A and ⌘A select all; Escape or the Stop button interrupts a command. + attachShortcuts(terminal); + const stop = stopButton(element.ownerDocument, {interrupt: () => editor?.interrupt(), focus: () => terminal.focus()}); + if (element.ownerDocument.defaultView.getComputedStyle(element).position === 'static') element.style.position = 'relative'; + element.append(stop.button); const write = text => terminal.write(text); // Keys typed while the commands and the history load are applied once the editor is ready. const early = []; @@ -701,8 +758,12 @@ export async function mount({bridge, config, terminal: element, preview, onExit, remember: line => rememberLine(bridge, line), run: async (line, signal) => { workspace?.command(true); // the tab shows that a command runs, also while the terminal is collapsed + stop.running(signal); try { return await runLine(line, {...context, editor, signal, write: text => editor.write(text)}); } - finally { workspace?.command(false); } + finally { + stop.ended(); + workspace?.command(false); + } }, complete: line => complete(line, context)}); terminal.onResize(() => editor.resized()); @@ -759,7 +820,7 @@ export async function mount({bridge, config, terminal: element, preview, onExit, if (workspace) { // The interface the project already has fills the window; the keys go to it while the terminal is collapsed. if (workspace.interfaceExists) showPreview(preview); - workspace.attach({focus: () => terminal.focus(), fit: fitToElement ? fitTerminal : undefined}); + workspace.attach({focus: () => terminal.focus(), fit: fitToElement ? fitTerminal : undefined, stop: stop.button}); } else terminal.focus(); - return {terminal, editor, workspace, inspectors: () => inspectors?.host() ?? null}; + return {terminal, editor, workspace, stop: stop.button, inspectors: () => inspectors?.host() ?? null}; } diff --git a/js/developer/environment/scripts.mjs b/js/developer/environment/scripts.mjs index e5d67d44..a0813e91 100644 --- a/js/developer/environment/scripts.mjs +++ b/js/developer/environment/scripts.mjs @@ -1,5 +1,5 @@ // wf run and wf exec: WebFront scripts run in a dedicated Worker; the page answers their context calls under the -// manifest permissions, publishes with developer::Store and stops the Worker on Ctrl+C or at the time limit. +// manifest permissions, publishes with developer::Store and stops the Worker on an interruption or at the time limit. import {call, readProject, writeChunks} from './io.mjs'; import {checkRead, checkWrite, listable} from './permissions.mjs'; import {manifestPath} from './manifest.mjs'; @@ -94,7 +94,7 @@ const decoder = new TextDecoder(); /** * The page side of a run: answers the Worker's context calls. Each write is a transaction of its own. When the - * script ends by itself, finish() lets the writes it did not await complete; after stop() (Ctrl+C, time limit), a + * script ends by itself, finish() lets the writes it did not await complete; after stop() (an interruption, the time limit), a * transaction still staging is aborted, and one whose commit was sent completes or fails atomically in C++. */ export function scriptHost({bridge, permissions, lock}) { @@ -165,7 +165,7 @@ export function scriptHost({bridge, permissions, lock}) { } /** - * Runs compiled script code in a Worker. Ctrl+C (signal) or the time limit first aborts the script's context.signal; + * Runs compiled script code in a Worker. An interruption (signal) or the time limit first aborts the script's context.signal; * a script still running after the grace period is terminated with worker.terminate(), which also stops one that * never returns to its event loop. Resolves with {code, reason, error}; reason is 'exit', 'interrupted' or 'timeout'. */ @@ -233,7 +233,7 @@ function publicationReport(all, stopped) { * ScriptExit otherwise. A write that was not applied, even one the script did not await, is never silent. */ export function runResult(label, outcome, publications) { - const stopped = {interrupted: 'stopped by Ctrl+C', timeout: 'stopped at its time limit'}[outcome.reason]; + const stopped = {interrupted: 'interrupted', timeout: 'stopped at its time limit'}[outcome.reason]; const report = publicationReport(publications, stopped !== undefined); if (outcome.code === 0 && !stopped && !report.length) return `${label} completed.`; const forced = outcome.forced ? ` (terminated after the ${outcome.forced / 1000} s grace period)` : ''; diff --git a/js/developer/environment/terminal.mjs b/js/developer/environment/terminal.mjs index 371cb4bd..93031443 100644 --- a/js/developer/environment/terminal.mjs +++ b/js/developer/environment/terminal.mjs @@ -1,8 +1,10 @@ // The environment's line editor: multi-row redraw, grapheme clusters and their cell widths, history, multi-line paste, -// completion and Ctrl+C. The cell widths are also given to xterm.js (unicodeProvider), so both agree on every row. +// completion, the interruption of a command and the system's shortcuts (copy, paste, cut, select all). The cell widths are +// also given to xterm.js (unicodeProvider), so both agree on every row. const ansi = { red: text => `\x1b[31m${text}\x1b[0m`, + dim: text => `\x1b[2m${text}\x1b[0m`, up: count => count > 0 ? `\x1b[${count}A` : '', right: count => count > 0 ? `\x1b[${count}C` : '', clearBelow: '\x1b[J', @@ -209,9 +211,87 @@ function commonPrefix(words) { }); } +// --- System shortcuts ------------------------------------------------------------------------------------------ + +/** What Escape sends in onData: the key that interrupts a command while no text of the terminal is selected. */ +export const interruptKey = '\x1b'; + +const shortcutLetters = {c: 'copy', v: 'paste', x: 'cut', a: 'selectAll'}; +const shortcutCodes = {KeyC: 'copy', KeyV: 'paste', KeyX: 'cut', KeyA: 'selectAll'}; + +/** + * The system shortcut that a key event of the terminal is, or null when it is a key for the line editor: + * copy, paste, cut, selectAll: Ctrl or ⌘ (Meta) with C, V, X or A, Shift allowed (Ctrl+Shift+C as in other terminals) + * but not Alt, which AltGr sets with Ctrl on Windows. The letter is the one the layout gives (Ctrl+A on AZERTY is + * the key labelled A), or the key's place for a layout without Latin letters, as the system does; + * clearSelection: Escape alone while text of the terminal is selected; without a selection, Escape goes to the editor + * (interruptKey). + */ +export function shortcutOf(event, hasSelection) { + const bare = !event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey; + if (event.key === 'Escape') return bare && hasSelection ? 'clearSelection' : null; + if (!(event.ctrlKey || event.metaKey) || event.altKey) return null; + const key = String(event.key ?? '').toLowerCase(); + return /^[a-z]$/.test(key) ? shortcutLetters[key] ?? null : shortcutCodes[event.code] ?? null; +} + +/** + * Lets the system's shortcuts work in an xterm.js `terminal`, instead of becoming control characters for the editor + * (Ctrl+C would send \x03, Ctrl+V \x16): the engine runs its own copy, cut and paste, whichever the frontend (CEF, + * WebView2, WebKitGTK, WKWebView through its Edit menu, a system browser), and xterm.js answers them: + * - copy and cut put the selection on the clipboard; nothing of the terminal can be removed, so a cut copies. The + * selection is also put in xterm.js's hidden textarea and selected there, as xterm.js does for its context menu, + * so that an engine that enables Copy only for a selection of the page (a native Edit menu) enables it; + * - paste reaches xterm.js's paste handler, which gives the text to onData: a pasted line break submits the line, and + * the lines after it wait for the command before them (LineEditor.insertText); + * - select all selects the whole terminal, not the page; + * - Escape clears a selection; without one, it reaches the editor and interrupts the command that runs. + * Without a selection, Ctrl+C does nothing. Returns a function that removes the listeners. + */ +export function attachShortcuts(terminal) { + const element = terminal.element, textarea = terminal.textarea; + let staged = false; // the selection waits in the textarea for the engine's copy or cut + const unstage = () => { + if (!staged) return; + staged = false; + textarea.value = ''; + }; + terminal.attachCustomKeyEventHandler(event => { + const action = shortcutOf(event, terminal.hasSelection()); + if (event.type !== 'keydown') return action === null; + unstage(); + if (action === null) return true; + if (action === 'selectAll' || action === 'clearSelection') { + event.preventDefault(); // the page's own selection stays as it is + if (action === 'selectAll') terminal.selectAll(); else terminal.clearSelection(); + } else if ((action === 'copy' || action === 'cut') && terminal.hasSelection()) { + textarea.value = terminal.getSelection(); + textarea.select(); + staged = true; + } + return false; // xterm.js leaves the event to the engine, which copies, cuts or pastes + }); + // The engine enables Copy and Cut for a selection of the page; cancelling beforecopy and beforecut enables them for + // the terminal's own selection too. xterm.js fills the clipboard on copy; a cut does the same, the terminal unchanged. + const enable = event => { if (terminal.hasSelection()) event.preventDefault(); }; + const cut = event => { + if (!terminal.hasSelection()) return; + event.clipboardData?.setData('text/plain', terminal.getSelection()); + event.preventDefault(); + }; + const listeners = [['beforecopy', enable], ['beforecut', enable], ['cut', cut], ['copy', unstage], ['cut', unstage], ['blur', unstage]]; + for (const [type, listener] of listeners) (type === 'blur' ? textarea : element).addEventListener(type, listener); + return () => { + terminal.attachCustomKeyEventHandler(() => true); + unstage(); + for (const [type, listener] of listeners) (type === 'blur' ? textarea : element).removeEventListener(type, listener); + }; +} + // --- Line editor ----------------------------------------------------------------------------------------------- -// Editing keys, as xterm.js reports them in onData, mapped to LineEditor actions. +// Editing keys, as xterm.js reports them in onData, mapped to LineEditor actions. Ctrl+C is not one of them: it copies +// (attachShortcuts), and the interruption of a command is Escape or the Stop button. const keyActions = new Map([ ['\r', editor => editor.submit()], ['\x7f', editor => editor.erase(-1)], @@ -228,7 +308,6 @@ const keyActions = new Map([ ['\x1b[A', editor => editor.recall(-1)], ['\x1b[B', editor => editor.recall(1)], ['\t', editor => editor.track(editor.completeThenReplay())], - ['\x03', editor => editor.cancelLine()], ['\x0c', editor => editor.clearScreen()], ['\x15', editor => editor.killBeforeCursor()], ['\x0b', editor => editor.killAfterCursor()], @@ -240,7 +319,7 @@ export const historyLimit = 500; * Line editor driven by the terminal's input data. * write(text): displays text; columns() and rows(): the terminal's size; * run(line, signal): a Promise of the command's output; it rejects with an Error whose exitCode (1 by default, 130 - * once Ctrl+C aborted `signal`) becomes the status; + * once interrupt() aborted `signal`) becomes the status; * complete(line): a Promise of {candidates}, the full words that can replace the word at the end of the line (its * value as wordAtEnd reads it); * remember(line): persists a line added to the history. @@ -319,10 +398,10 @@ export class LineEditor { if (!data.startsWith('\x1b')) return this.insertText(data); } - // While a command runs, Ctrl+C aborts it and drops the keys typed after it; other keys, typed or pasted, wait for - // the command and are applied after it. + // While a command runs, Escape (a lone ESC, which no other key sends) interrupts it and drops the keys typed after + // it; other keys, typed or pasted, wait for the command and are applied after it. whileBusy(data) { - if (data === '\x03') return this.interrupt(); + if (data === interruptKey) return this.interrupt(); this.typeAhead(data); } @@ -355,10 +434,20 @@ export class LineEditor { return null; } + /** Whether a command runs that interrupt() would stop: it has not been interrupted yet. */ + get interruptible() { + return this.abort?.signal.aborted === false; + } + + /** + * Interrupts the command that runs (Escape, the Stop button): its signal is aborted, it ends with 130, and the keys + * typed after it are dropped. Nothing happens while no command runs. + */ interrupt() { + if (!this.running) return; this.ahead = []; - if (this.abort?.signal.aborted !== false) return; - this.write('^C\r\n'); + if (!this.interruptible) return; + this.write(`${this.atLineStart ? '' : '\r\n'}${ansi.dim('Interrupted')}\r\n`); this.abort.abort(new Error('Interrupted')); } @@ -420,15 +509,6 @@ export class LineEditor { this.setLine(index === this.history.length ? '' : this.history[index]); } - cancelLine() { - this.moveTo(this.cells.length); - this.write('^C\r\n'); - this.cells = []; - this.cursor = 0; - this.historyIndex = this.history.length; - this.showPrompt(); - } - clearScreen() { this.write(ansi.clearScreen); this.showPrompt(); @@ -526,7 +606,7 @@ export class LineEditor { } catch (error) { this.status = error?.exitCode ?? (signal.aborted ? 130 : 1); const message = String(error?.message ?? error); - // Ctrl+C already shows ^C: a bare interruption adds nothing. A code other than 1 is shown, unless the + // interrupt() already said so: a bare interruption adds nothing. A code other than 1 is shown, unless the // message already gives it ("exited with code 3"). const stated = this.status === 1 || new RegExp(`\\bcode ${this.status}\\b`).test(message); if (!(signal.aborted && message === 'Interrupted')) @@ -539,7 +619,7 @@ export class LineEditor { } // Keys typed while the completion is pending are kept and applied once it is inserted, in order: once one of them - // submits the line, the next ones act on its command like keys typed while it runs (Ctrl+C interrupts it). + // submits the line, the next ones act on its command like keys typed while it runs (Escape interrupts it). async completeThenReplay() { this.completing = []; try { await this.completeLine(); } diff --git a/js/developer/environment/testing.mjs b/js/developer/environment/testing.mjs index 3a6ceba9..bdff8ceb 100644 --- a/js/developer/environment/testing.mjs +++ b/js/developer/environment/testing.mjs @@ -179,7 +179,7 @@ export function abortable(promise, signal) { * says how far it got (frameStage) and is added to the message and to the report. */ export const stoppedRun = (reason, pattern, stage) => { - const [stopped, exitCode] = reason === 'timeout' ? ['Tests stopped at their time limit', 124] : ['Tests stopped by Ctrl+C', 130]; + const [stopped, exitCode] = reason === 'timeout' ? ['Tests stopped at their time limit', 124] : ['Tests interrupted', 130]; const message = stage ? `${stopped} (${describeStage(stage)})` : stopped; return Object.assign(new ScriptExit(message, exitCode), {report: emptyReport(reason, exitCode, {pattern, error: message, ...(stage ? {stage} : {})})}); }; diff --git a/js/developer/environment/typecheck-worker.mjs b/js/developer/environment/typecheck-worker.mjs index 65eaf9d7..7767a3aa 100644 --- a/js/developer/environment/typecheck-worker.mjs +++ b/js/developer/environment/typecheck-worker.mjs @@ -38,7 +38,7 @@ async function run({lock, typescript, entries, bounds: given}) { const {snapshot, rootNames} = loaded; print(`Checking ${rootNames.length} root file${rootNames.length === 1 ? '' : 's'} with TypeScript ${ts.version} ` + `(snapshot: ${snapshot.files.size} files, ${(snapshot.bytes / 1048576).toFixed(1)} MiB)`); - // Synchronous from here: Ctrl+C can only terminate the Worker. + // Synchronous from here: an interruption can only terminate the Worker. const {lines, code, diagnostics} = checkReport(ts, snapshot, checkProgram(ts, loaded, typescript), bounds); for (const line of lines) print(line, code ? 'err' : 'out'); self.postMessage({type: 'exit', code, diagnostics}); diff --git a/js/developer/environment/workspace.mjs b/js/developer/environment/workspace.mjs index 7b364ff9..bb5b1f25 100644 --- a/js/developer/environment/workspace.mjs +++ b/js/developer/environment/workspace.mjs @@ -259,7 +259,8 @@ export const layoutState = frame => layouts.get(frame)?.workspace?.state; /** * Lays the page out around the terminal's `element` and the preview `frame`, which starts hidden. Call it before the - * terminal opens in `element`, then attach({focus, fit}) with the functions that focus the terminal and fit it to `element`. + * terminal opens in `element`, then attach({focus, fit, stop}) with the functions that focus the terminal and fit it to `element`, + * and the terminal's Stop button, which the workspace puts in the floating window's bar. * The result gives the `state`, `interfaceExists` (the page opened on an existing interface, to load in the frame), * the `status` shown on the tab and command(running) to say that a command runs, toggle(), open({focus}) and close(), `button` and `panel`, the `shortcut` in use ("F9") and placeSaved(). * The tab's context menu (menu.mjs) is `menu`, and `inspectorAccess` resolves to what webfront.inspector.containers() @@ -275,7 +276,7 @@ export async function createWorkspace({bridge, element, frame, openInspector = n const viewport = () => ({width: root.clientWidth, height: root.clientHeight}); let state = initialState(interfaceExists); let place = remembered; // as chosen; what is displayed is fitted to the viewport - let focusTerminal = () => {}, fitTerminal = () => {}; + let focusTerminal = () => {}, fitTerminal = () => {}, stopButton = null; const session = {command: false, dev: null}; // Asked once: whether this page may reach the inspectors does not change while its connection lives. let access = null; @@ -329,11 +330,19 @@ export async function createWorkspace({bridge, element, frame, openInspector = n button.dataset.status = status; button.setAttribute('aria-label', `${open ? 'Hide' : 'Show'} the WebFront terminal${words && `: ${words}`}`); button.title = `${open ? 'Hide' : 'Show'} the terminal (${keys})${words && `: ${words}`}`; + placeStop(); const rect = state === State.terminal ? null : shown(); Object.assign(panel.style, rect ? {left: `${rect.x}px`, top: `${rect.y}px`, width: `${rect.width}px`, height: `${rect.height}px`} : {left: '', top: '', width: '', height: ''}); fitTerminal(); // its window may have changed size } + // The Stop button of the terminal (runtime.mjs) is in the window's bar, before the close button, while the bar shows; + // over the terminal's corner while the terminal fills the window. + function placeStop() { + if (!stopButton) return; + if (state === State.terminal) { if (stopButton.parentNode !== element) element.append(stopButton); } + else if (stopButton.nextSibling !== closeButton) bar.insertBefore(stopButton, closeButton); + } function choose(rect) { place = clampRect(rect, viewport()); store.remember(place); @@ -440,9 +449,11 @@ export async function createWorkspace({bridge, element, frame, openInspector = n render(); }, interfaceExists, button, panel, bar, shortcut: keys, menu, inspectorAccess, - attach({focus, fit = () => {}}) { + attach({focus, fit = () => {}, stop = null}) { focusTerminal = focus; fitTerminal = fit; + stopButton = stop; + placeStop(); if (state === State.interface) frame.focus(); else focus(); }, toggle: () => apply('toggle'), diff --git a/js/developer/webfront.project.json b/js/developer/webfront.project.json index 189f4038..f1a72746 100644 --- a/js/developer/webfront.project.json +++ b/js/developer/webfront.project.json @@ -32,6 +32,7 @@ "test/developer/specs/testing-specs.mjs", "test/developer/specs/timers-specs.mjs", "test/developer/specs/workspace-specs.mjs", + "test/developer/specs/terminal-specs.mjs", "test/developer/specs/inspector-specs.mjs", "test/developer/specs/inspector-registry-specs.mjs", "test/developer/specs/inspector-watches-specs.mjs", diff --git a/test/developer/specs/development-specs.mjs b/test/developer/specs/development-specs.mjs index a9633984..2f9efd6b 100644 --- a/test/developer/specs/development-specs.mjs +++ b/test/developer/specs/development-specs.mjs @@ -15,7 +15,7 @@ describe('wf dev', () => { for (const [label, manifest, message] of [ ['without a project', null, /No webfront.project.json: run wf init/], ['without an entry', {format: 1, name: 'empty', version: '0.1.0'}, /Usage: wf dev /], - ]) it(`rejects ${label} without waiting for Ctrl+C or starting a compiler`, async () => { + ]) it(`rejects ${label} without waiting for an interruption or starting a compiler`, async () => { const {bridge} = memoryBridge(new Map(manifest ? [['webfront.project.json', encode(JSON.stringify(manifest))]] : [])); const controller = new AbortController(); // Bound the regression: the broken command stays in its polling loop until this aborts it. @@ -98,7 +98,7 @@ describe('wf dev', () => { await rejects(inputsChanged(broken, new Map([['file', 'old']])), /Connection closed/); }); - it('Ctrl+C terminates an active compiler, rejects once, and drops late read answers', async () => { + it('an interruption terminates an active compiler, rejects once, and drops late read answers', async () => { let callback, terminated = 0; const messages = []; const worker = {postMessage: message => messages.push(message), terminate: () => ++terminated, @@ -152,7 +152,7 @@ describe('wf dev', () => { }); - it('Ctrl+C during commit still displays the committed preview before stopping dev', async () => { + it('an interruption during commit still displays the committed preview before stopping dev', async () => { const project = memoryBridge(new Map([['webfront.project.json', encode(JSON.stringify({ format: 1, name: 'commit-race', version: '0.1.0', entries: {main: 'main.ts'}, }))]])); @@ -179,7 +179,7 @@ describe('wf dev', () => { try { await rejects(dev([], {bridge, signal: controller.signal, preview: frame}), error => error.exitCode === 130); expect(project.storage.get('.webfront/developer/preview/app.js')).toEqual(encode('console.log("committed")')); - expect(navigations.length).withContext('a completed publication must be displayed even when Ctrl+C arrived during commit').toBe(1); + expect(navigations.length).withContext('a completed publication must be displayed even when an interruption arrived during commit').toBe(1); expect(navigations[0]).toMatch(/^\/webfront\/developer\/preview\/index.html\?build=/); expect(frame.hidden).toBe(false); expect(project.pending()).toBe(0); diff --git a/test/developer/specs/scripts-specs.mjs b/test/developer/specs/scripts-specs.mjs index 968aefaf..93b30187 100644 --- a/test/developer/specs/scripts-specs.mjs +++ b/test/developer/specs/scripts-specs.mjs @@ -178,7 +178,7 @@ describe('wf run and wf exec', () => { expect(failed).toEqual({reason: 'exit', code: 1, error: 'Error: boom'}); }); - it('Ctrl+C aborts the script cooperatively, then terminates one that does not stop', async () => { + it('an interruption aborts the script cooperatively, then terminates one that does not stop', async () => { const controller = new AbortController(); const cooperative = fastRun((message, w) => { if (message.type === 'abort') w.emit({type: 'error', error: 'Error: Interrupted'}); }, {signal: controller.signal}); controller.abort(); @@ -192,11 +192,11 @@ describe('wf run and wf exec', () => { expect(looping.worker.received.some(message => message.type === 'abort')).withContext('the signal is emitted before the termination').toBeTruthy(); const publications = [{path: 'generated/a', state: 'applied'}, {path: 'generated/b', state: 'abandoned'}]; throws(() => runResult('Script loop', outcome, publications), error => error.exitCode === 130 - && /stopped by Ctrl\+C \(terminated after the 0.02 s grace period\)/.test(error.message) + && /interrupted \(terminated after the 0.02 s grace period\)/.test(error.message) && /Applied before the stop: generated\/a/.test(error.message) && /Abandoned, unchanged: generated\/b/.test(error.message)); }); - it('the time limit stops a script the same way, without Ctrl+C', async () => { + it('the time limit stops a script the same way, without an interruption', async () => { const {worker, outcome} = fastRun(() => {}, {timeout: 0.01}); expect(await outcome).toEqual({reason: 'timeout', code: 124, forced: 20}); expect(worker.terminated && worker.received.some(message => message.type === 'abort')).toBeTruthy(); diff --git a/test/developer/specs/terminal-specs.mjs b/test/developer/specs/terminal-specs.mjs new file mode 100644 index 00000000..4c9affa0 --- /dev/null +++ b/test/developer/specs/terminal-specs.mjs @@ -0,0 +1,225 @@ +// Specs of the terminal's keys (#721): the system's shortcuts reach the engine instead of becoming control characters, +// \x03 neither clears the line nor interrupts, and Escape or the Stop button interrupts a command with code 130. The +// engine's own copy and paste, which a script cannot trigger, are checked with real keys in test/web/developer-specs.mjs. +import {Terminal} from '@xterm/xterm'; +import {LineEditor, shortcutOf, attachShortcuts, interruptKey} from '../../../js/developer/environment/terminal.mjs'; + +const keyCodes = {a: 65, c: 67, e: 69, v: 86, x: 88, Escape: 27}; + +/** A keydown as the keyboard sends it; xterm.js reads keyCode, which KeyboardEvent's constructor does not set. */ +function keydown(target, {key, code = key.length === 1 ? `Key${key.toUpperCase()}` : key, ...modifiers}) { + const event = new KeyboardEvent('keydown', {key, code, bubbles: true, cancelable: true, ...modifiers}); + Object.defineProperty(event, 'keyCode', {get: () => keyCodes[key] ?? 0}); + target.dispatchEvent(event); + return event; +} + +/** A clipboard event carrying its own DataTransfer, as the engine dispatches it for a copy, a cut or a paste. */ +function clipboardEvent(target, type, text) { + const clipboardData = new DataTransfer(); + if (text !== undefined) clipboardData.setData('text/plain', text); + const event = new ClipboardEvent(type, {clipboardData, bubbles: true, cancelable: true}); + target.dispatchEvent(event); + return event; +} + +/** A command that runs until its signal is aborted, then ends like an interrupted command of the environment. */ +const untilInterrupted = (line, signal) => new Promise((resolve, reject) => { + if (line.startsWith('echo ')) return resolve(`${line.slice(5)}\r\n`); + signal.addEventListener('abort', () => reject(Object.assign(new Error('Interrupted'), {exitCode: 130})), {once: true}); +}); + +function editorOf({run = untilInterrupted} = {}) { + const output = []; + const signals = []; + const editor = new LineEditor({write: text => output.push(text), run: (line, signal) => { + signals.push(signal); + return run(line, signal); + }}); + return {editor, output, signals, text: () => output.join('')}; +} + +describe('The terminal', () => { + describe('shortcuts', () => { + it('are the system\'s copy, paste, cut and select all, with Ctrl or ⌘, and Escape on a selection', () => { + const cases = [ + [{key: 'c', ctrlKey: true}, false, 'copy'], + [{key: 'c', metaKey: true}, true, 'copy'], + [{key: 'C', ctrlKey: true, shiftKey: true}, true, 'copy'], + [{key: 'v', ctrlKey: true}, false, 'paste'], + [{key: 'v', metaKey: true}, false, 'paste'], + [{key: 'x', ctrlKey: true}, true, 'cut'], + [{key: 'a', ctrlKey: true}, false, 'selectAll'], + [{key: 'a', metaKey: true}, false, 'selectAll'], + // The letter the layout gives: Ctrl+A on AZERTY is the key in the place of Q. + [{key: 'a', code: 'KeyQ', ctrlKey: true}, false, 'selectAll'], + [{key: 'q', code: 'KeyA', ctrlKey: true}, false, null], + // Without Latin letters, the key's place, as the system does (Cyrillic с on the C key). + [{key: 'с', code: 'KeyC', ctrlKey: true}, true, 'copy'], + // AltGr sets Ctrl and Alt on Windows: a character, not a shortcut. + [{key: 'c', ctrlKey: true, altKey: true}, true, null], + [{key: 'c'}, true, null], + [{key: 'e', ctrlKey: true}, false, null], + [{key: 'Escape'}, true, 'clearSelection'], + [{key: 'Escape'}, false, null], + [{key: 'Escape', shiftKey: true}, true, null], + ]; + for (const [event, selection, expected] of cases) + expect(shortcutOf({code: '', ...event}, selection)).withContext(`${JSON.stringify(event)} selection=${selection}`).toBe(expected); + }); + }); + + describe('in xterm.js', () => { + let host, terminal, data; + const written = text => new Promise(resolve => terminal.write(text, resolve)); + beforeEach(async () => { + host = document.createElement('div'); + host.style.cssText = 'width:640px;height:240px'; + document.body.append(host); + terminal = new Terminal({cols: 80, rows: 10}); + terminal.open(host); + data = []; + terminal.onData(text => data.push(text)); + await written('hello copy\r\nsecond row\r\n'); + }); + afterEach(() => { + terminal.dispose(); + host.remove(); + }); + + it('sends \\x03 for Ctrl+C without the shortcuts: the keys of these specs reach its key handling', () => { + keydown(terminal.textarea, {key: 'c', ctrlKey: true}); + expect(data).toEqual(['\x03']); + }); + + it('leaves Ctrl+C and ⌘C on a selection to the engine\'s copy, which puts the selection on the clipboard', () => { + attachShortcuts(terminal); + for (const modifier of ['ctrlKey', 'metaKey']) { + terminal.select(0, 0, 5); + const event = keydown(terminal.textarea, {key: 'c', [modifier]: true}); + expect(data).withContext(modifier).toEqual([]); + expect(event.defaultPrevented).withContext('the engine copies').toBeFalse(); + // The selection waits in the focused textarea, selected, so that a native Edit menu enables Copy. + const {value, selectionStart, selectionEnd} = terminal.textarea; + expect([value, selectionStart, selectionEnd]).toEqual(['hello', 0, 5]); + const copy = clipboardEvent(terminal.textarea, 'copy'); + expect(copy.clipboardData.getData('text/plain')).toBe('hello'); + expect(copy.defaultPrevented).toBeTrue(); + expect(terminal.textarea.value).withContext('the textarea is emptied after the copy').toBe(''); + } + // The engine enables Copy and Cut for the terminal's selection. + expect(clipboardEvent(terminal.element, 'beforecopy').defaultPrevented).toBeTrue(); + expect(clipboardEvent(terminal.element, 'beforecut').defaultPrevented).toBeTrue(); + terminal.clearSelection(); + expect(clipboardEvent(terminal.element, 'beforecopy').defaultPrevented).withContext('nothing to copy').toBeFalse(); + }); + + it('copies on Ctrl+X, since nothing of the terminal can be cut', () => { + attachShortcuts(terminal); + terminal.select(0, 1, 6); + keydown(terminal.textarea, {key: 'x', ctrlKey: true}); + const cut = clipboardEvent(terminal.textarea, 'cut'); + expect([data, cut.clipboardData.getData('text/plain'), cut.defaultPrevented, terminal.textarea.value]).toEqual([[], 'second', true, '']); + expect(terminal.getSelection()).toBe('second'); + }); + + it('selects the whole terminal on Ctrl+A and ⌘A, not the page', () => { + attachShortcuts(terminal); + for (const modifier of ['ctrlKey', 'metaKey']) { + terminal.clearSelection(); + const event = keydown(terminal.textarea, {key: 'a', [modifier]: true}); + expect([data, event.defaultPrevented, terminal.getSelection().startsWith('hello copy')]).withContext(modifier).toEqual([[], true, true]); + } + }); + + it('leaves Ctrl+V to the engine\'s paste, whose lines reach the editor as before', () => { + attachShortcuts(terminal); + const event = keydown(terminal.textarea, {key: 'v', ctrlKey: true}); + expect([data, event.defaultPrevented]).toEqual([[], false]); + clipboardEvent(terminal.textarea, 'paste', 'echo one\necho two'); + expect(data).toEqual(['echo one\recho two']); + }); + + it('clears a selection on Escape, and sends Escape to the editor without one', () => { + attachShortcuts(terminal); + terminal.select(0, 0, 5); + const event = keydown(terminal.textarea, {key: 'Escape'}); + expect([data, event.defaultPrevented, terminal.hasSelection()]).toEqual([[], true, false]); + keydown(terminal.textarea, {key: 'Escape'}); + expect(data).toEqual([interruptKey]); + }); + + it('passes the other keys with Ctrl to the editor', () => { + attachShortcuts(terminal); + keydown(terminal.textarea, {key: 'e', ctrlKey: true}); + expect(data).toEqual(['\x05']); + }); + + it('lets Ctrl+C without a selection leave the line being typed as it is', async () => { + attachShortcuts(terminal); + const {editor} = editorOf(); + terminal.onData(text => editor.handle(text)); + terminal.input('echo kept'); + keydown(terminal.textarea, {key: 'c', ctrlKey: true}); + expect([editor.line, editor.busy, data]).toEqual(['echo kept', null, ['echo kept']]); + }); + }); + + describe('line editor', () => { + it('neither clears the line nor interrupts a command on \\x03', async () => { + const {editor, signals, text} = editorOf(); + editor.handle('echo kept'); + editor.handle('\x03'); + expect(editor.line).toBe('echo kept'); + editor.handle('\x15'); + editor.handle('sleep\r'); + editor.handle('\x03'); + expect(signals[0].aborted).withContext('\\x03 is not an interruption').toBeFalse(); + expect(text()).not.toContain('^C'); + editor.interrupt(); + await editor.whenIdle(); + expect(editor.status).toBe(130); + }); + + it('interrupts the command that runs on Escape, with code 130, and drops the keys typed after it', async () => { + const {editor, signals, text} = editorOf(); + editor.handle('sleep\r'); + editor.handle('echo dropped\r'); + editor.handle(interruptKey); + await editor.whenIdle(); + expect([editor.status, signals.length, signals[0].aborted, editor.line]).toEqual([130, 1, true, '']); + expect(text().match(/Interrupted/g)).withContext('said once, without an error line').toEqual(['Interrupted']); + expect(text()).not.toContain('dropped'); + }); + + it('interrupts like the Stop button with interrupt(), once, and only while a command runs', async () => { + const {editor, signals} = editorOf(); + editor.interrupt(); + editor.handle(interruptKey); // idle: Escape does nothing + expect([editor.line, editor.interruptible]).toEqual(['', false]); + editor.handle('sleep\r'); + expect(editor.interruptible).toBeTrue(); + editor.interrupt(); + expect(editor.interruptible).withContext('an interrupted command is not interrupted again').toBeFalse(); + editor.interrupt(); + await editor.whenIdle(); + expect([editor.status, signals[0].aborted]).toEqual([130, true]); + editor.handle('echo after\r'); + await editor.whenIdle(); + expect(editor.status).withContext('the next command runs').toBe(0); + }); + + it('interrupts the command that Enter submitted while a completion was pending', async () => { + let answer; + const editor = new LineEditor({write: () => {}, run: untilInterrupted, + complete: () => new Promise(resolve => { answer = resolve; })}); + editor.handle('sle'); + editor.handle('\t'); + editor.handle('\r'); + editor.handle(interruptKey); + answer({candidates: ['sleep']}); + await editor.whenIdle(); + expect(editor.status).toBe(130); + }); + }); +}); diff --git a/test/developer/specs/testing-specs.mjs b/test/developer/specs/testing-specs.mjs index 97af6b82..3e17c8df 100644 --- a/test/developer/specs/testing-specs.mjs +++ b/test/developer/specs/testing-specs.mjs @@ -377,6 +377,6 @@ describe('the stage of a stopped wf test run', () => { .toBe('stage: between specs, in suite slow setup'); // Stopped before the frame existed: no stage, and the message stays the plain one. const early = stoppedRun('interrupted', ''); - expect([early.exitCode, early.message, 'stage' in early.report]).toEqual([130, 'Tests stopped by Ctrl+C', false]); + expect([early.exitCode, early.message, 'stage' in early.report]).toEqual([130, 'Tests interrupted', false]); }); }); diff --git a/test/unit/CommandsTests.cpp b/test/unit/CommandsTests.cpp index 82a16017..9324e36f 100644 --- a/test/unit/CommandsTests.cpp +++ b/test/unit/CommandsTests.cpp @@ -401,7 +401,7 @@ const Scenario printTask{"A print task may be awaited after its context is gone" }); }}; -const Scenario ctrlC{"Ctrl+C stops a running command and the next one runs at once", [] { +const Scenario ctrlC{"An interruption stops a running command and the next one runs at once", [] { given("a command waiting in a browser", [&] { Fixture fixture; auto& app = fixture.app; diff --git a/test/web/DeveloperTest.cpp b/test/web/DeveloperTest.cpp index ec57d316..daa45978 100644 --- a/test/web/DeveloperTest.cpp +++ b/test/web/DeveloperTest.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -28,7 +29,9 @@ #include #include #include +#include #include +#include namespace { std::string readFixtureText(const std::filesystem::path& path) { @@ -109,7 +112,7 @@ void registerCallbacks(App& app, const std::filesystem::path& project, std::atom }); } -// What the test's long commands went through, by tag: running, stopping (a lingering command after Ctrl+C), cancelled. +// What the test's long commands went through, by tag: running, stopping (a lingering command after an interruption), cancelled. class CommandStates { public: void set(const std::string& tag, std::string state) { @@ -163,7 +166,7 @@ webfront::Task waitUntilStopped(Context context, std::shared_ptr co_await context.ui().resumeAfter(20ms); } -// After Ctrl+C, remains deaf to the stop request until the test releases it. +// After an interruption, remains deaf to the stop request until the test releases it. template webfront::Task lingerAfterStop(Context context, std::shared_ptr states) { const auto tag = context.args().at(0); @@ -218,7 +221,7 @@ void registerCommands(webfront::Commands& commands, const std::shared_ptr +class KeyPressTask : public CefTask { +public: + KeyPressTask(App& application, std::vector> pressed, std::shared_ptr> result) + : app(application), keys(std::move(pressed)), done(std::move(result)) { } + + void Execute() override { + const auto window = app.nativeWindow().get(); + if (!window || !window->pointer) { + done->set_value("the view is not open"); + return; + } + const auto host = static_cast(window->pointer)->GetHost(); + for (const auto& [key, code, keyCode, modifiers] : keys) + for (const auto* type : {"rawKeyDown", "keyUp"}) { + auto params = CefDictionaryValue::Create(); + params->SetString("type", type); + params->SetString("key", key); + params->SetString("code", code); + params->SetInt("windowsVirtualKeyCode", keyCode); + params->SetInt("nativeVirtualKeyCode", keyCode); + params->SetInt("modifiers", modifiers); + if (!host->ExecuteDevToolsMethod(0, "Input.dispatchKeyEvent", params)) { + done->set_value("the engine refused a key event"); + return; + } + } + done->set_value("sent"); + } + +private: + App& app; + std::vector> keys; + std::shared_ptr> done; + + #ifdef __clang__ + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wextra-semi" + #endif + IMPLEMENT_REFCOUNTING(KeyPressTask); + #ifdef __clang__ + #pragma clang diagnostic pop + #endif +}; +#endif + +/// Presses keys in the view as the keyboard does: [[key, code, windowsKeyCode, modifiers], ...], modifiers as DevTools +/// counts them (2 for Ctrl). "sent", "unsupported" on a frontend other than CEF, or why the keys could not be sent. +template +std::string pressKeys([[maybe_unused]] App& app, const std::string& json) { + std::vector> keys; + webfront::json::Reader reader{json}; + reader.array([&] { + std::vector fields; + reader.array([&] { + fields.push_back(fields.size() < 2 ? reader.string() : std::string(reader.rawValue())); + }); + if (fields.size() != 4) + throw std::invalid_argument("A key is [key, code, keyCode, modifiers]"); + keys.emplace_back(fields[0], fields[1], std::stoi(fields[2]), std::stoi(fields[3])); + }); +#ifdef WEBFRONT_EMBED_CEF + if constexpr (std::is_same_v) { + auto done = std::make_shared>(); + auto result = done->get_future(); + if (!CefPostTask(TID_UI, new KeyPressTask(app, std::move(keys), done))) + return "the interface thread is gone"; + if (result.wait_for(std::chrono::seconds(10)) != std::future_status::ready) + return "the interface thread did not send the keys"; + return result.get(); + } +#endif + return "unsupported"; +} + constexpr auto runScript = "import('/fixtures/run.mjs').catch(async e => { await webFront.cppFunction('test.report')(false, String(e.stack || e)); window.close(); });"; @@ -291,6 +373,9 @@ class Part { app.cppFunction("test.part", [part = mode.part] { return part; }); + app.cppFunction("test.keys", [this](std::string keys) { + return pressKeys(app, keys); + }); // What the inspectors must offer this page, known from the frontend type and not from webfront.inspector.containers(), // which the spec checks against it: the view of an embedded frontend is admitted, and a frontend that has secondary // windows offers one (ADR-027, sections 2 and 8). diff --git a/test/web/developer-specs.mjs b/test/web/developer-specs.mjs index 387bc7ee..fc3d7c07 100644 --- a/test/web/developer-specs.mjs +++ b/test/web/developer-specs.mjs @@ -57,7 +57,7 @@ const echo = text => { }; // Only the wf subcommand is shown, never an argument, an option value or a path; `execute` runs help for no argument. const subcommand = ([command = 'help']) => /^[a-z][a-z-]*$/.test(command) ? command : '?'; -// A wait is labelled expected only when the spec caused it: it pressed Ctrl+C (aborted its signal), or announced the time +// A wait is labelled expected only when the spec caused it: it interrupted the command (aborted its signal), or announced the time // limit it fires. Many specs also expect a rejection, which the trace cannot tell from a defect. const outcomeOf = (exitCode, {signal, expect}) => exitCode === 0 ? 'done' @@ -126,12 +126,30 @@ try { } } const runtime = await import('/webfront/developer/environment/runtime.mjs'); + // The interruption of the terminal (#721): Escape in its line editor aborts the signal of the command that runs, as + // a key of the terminal or its Stop button does. abort() presses Escape; an older published environment (--public), + // which interrupts on Ctrl+C, has its signal aborted directly. + const interruption = () => { + const {LineEditor, interruptKey} = runtime; + if (!interruptKey) { + const controller = new AbortController(); + return {signal: controller.signal, abort: () => controller.abort(new Error('Interrupted'))}; + } + let signal; + const editor = new LineEditor({write: () => {}, run: (line, given) => { + signal = given; + return new Promise(resolve => given.addEventListener('abort', resolve, {once: true})); + }}); + editor.handle('command\r'); + return {signal, abort: () => editor.handle(interruptKey)}; + }; runtimeExecute = runtime.execute; runtimeNonInteractive = runtime.runNonInteractive; const config = JSON.parse(await webFront.cppFunction('webfront.developer.config')()); showTrace(); const environment = await (await fetch('/webfront/developer/environment/environment.json')).json(); const currentDistribution = !config.environment.startsWith('https:'); + assert(!currentDistribution || runtime.interruptKey === '\x1b', 'The environment must interrupt a command on Escape'); if (currentDistribution) assert(JSON.stringify(Object.keys(environment.starters)) === JSON.stringify(['app', 'life']), 'Only the application and Life starters must be shipped'); config.starters = Object.fromEntries(Object.entries(environment.starters).map(([name, value]) => [name, {url: new URL(value.archive, new URL(config.environment, location.href)).href, integrity: value.integrity}])); const createFrame = () => { @@ -274,7 +292,7 @@ try { await writeFile('watch/main.ts', "import {value} from './value'; document.getElementById('root').textContent = value;\n"); await writeFile('watch/value.ts', "export const value: string = 'watch-one';\n"); let devOutput = ''; - const devStop = new AbortController(); + const devStop = interruption(); await withTimers([750], async clock => { const poll = async () => { await waitDev(() => clock.pending() > 0, 'Dev polling deadline was not armed'); @@ -307,7 +325,7 @@ try { await waitDev(() => frame.contentDocument?.getElementById('root')?.textContent === 'watch-created', 'Creating a missing import must recover'); assert(history.length === historyLength, 'Dev reloads must replace session history'); } finally { devStop.abort(); } - assert((await devResult)?.exitCode === 130, 'Ctrl+C must stop dev with exit code 130'); + assert((await devResult)?.exitCode === 130, 'An interruption must stop dev with exit code 130'); const afterStop = frame.contentDocument; await writeFile('watch/created.ts', "export const value = 'must-not-rebuild';\n"); assert(clock.pending() === 0, 'Stopped dev must remove its polling timer'); @@ -461,20 +479,20 @@ try { assert(/"fs" is a Node\.js API/.test(node?.message), `A Node.js import must be refused while loading: ${node}`); const exited = await failure(execute(['run', 'fail'], runContext())); assert(exited?.exitCode === 3 && /exited with code 3/.test(exited.message), 'A non-zero exit code must be propagated'); - const cooperative = new AbortController(); + const cooperative = interruption(); const waiting = failure(execute(['run', 'coop'], runContext(cooperative.signal))); await printed('waiting'); cooperative.abort(new Error('Interrupted')); const stopped = await waiting; - assert(stopped?.exitCode === 130 && !/grace period/.test(stopped.message), `Ctrl+C must stop a cooperative script: ${stopped}`); - const interrupt = new AbortController(); + assert(stopped?.exitCode === 130 && !/grace period/.test(stopped.message), `An interruption must stop a cooperative script: ${stopped}`); + const interrupt = interruption(); const looping = failure(execute(['run', 'loop'], runContext(interrupt.signal))); await printed('looping'); await withTimers([2000], async clock => { interrupt.abort(new Error('Interrupted')); clock.fire(2000); const killed = await looping; - assert(killed?.exitCode === 130 && /terminated after the 2 s grace period/.test(killed.message), `A busy script must be terminated after Ctrl+C: ${killed}`); + assert(killed?.exitCode === 130 && /terminated after the 2 s grace period/.test(killed.message), `A busy script must be terminated after an interruption: ${killed}`); }); // Real Worker/bridge preparation gets a generous bound; only the deadline under test is advanced. for (const target of ['loop', 'nested']) { @@ -496,7 +514,7 @@ try { await execute(['run', 'jsx'], runContext()); assert(scriptOutput.includes('jsx b\r\n'), 'A TSX script must compile its JSX with the automatic runtime'); // A stop during a large write: the file is either untouched or complete, and no staging is left. - const writing = new AbortController(); + const writing = interruption(); const big = failure(execute(['run', 'big'], runContext(writing.signal))); await printed('writing'); writing.abort(new Error('Interrupted')); @@ -628,13 +646,13 @@ try { assert(modDeclared.text && modDeclared.output.includes('No type errors in 4 project files'), `.d.mts and .d.cts declarations must be checked with the entries: ${modDeclared.error}\n${modDeclared.output}`); await writeFile('webfront.project.json', manifestBeforeDeclarations); - // A long check is synchronous in its Worker: Ctrl+C terminates it after the grace period, and nothing is written. + // A long check is synchronous in its Worker: an interruption terminates it after the grace period, and nothing is written. const slow =['type Build = T["length"] extends N ? T : Build;']; for (let n = 400; n < 1000; ++n) slow.push(`export const v${n}: Build<${n}>['length'] = ${n};`); await writeFile('check/slow.ts', slow.join('\n') + '\n'); const listing = async path => new TextDecoder().decode(await call('list', path)); const before = [await listing(''), await listing('check')]; - const stopCheck = new AbortController(); + const stopCheck = interruption(); scriptOutput.length = 0; const longCheck = failure(execute(['check'], {...runContext(stopCheck.signal), bridge: checkBridge})); await printed('Checking 3 root files'); @@ -642,8 +660,8 @@ try { stopCheck.abort(new Error('Interrupted')); clock.fire(2000); const checkStopped = await longCheck; - assert(checkStopped?.exitCode === 130 && /Type check stopped by Ctrl\+C \(terminated after the 2 s grace period\)/.test(checkStopped.message), - `Ctrl+C must terminate a long check after the grace period: ${checkStopped}`); + assert(checkStopped?.exitCode === 130 && /Type check interrupted \(terminated after the 2 s grace period\)/.test(checkStopped.message), + `An interruption must terminate a long check after the grace period: ${checkStopped}`); }); assert(JSON.stringify([await listing(''), await listing('check')]) === JSON.stringify(before), 'A check must not write any project file'); assert(JSON.parse(await listing('.webfront/developer/staging')).length === 0, 'A check must leave no staged files'); @@ -728,7 +746,7 @@ try { await specsOf(['tests/throws.spec.js']); const unloaded = await tested(); assert(unloaded.error?.exitCode === 1 && unloaded.report?.status !== 'passed' && /loading boom/.test(unloaded.error.message), `A spec that throws while loading must fail: ${unloaded.error}\n${JSON.stringify(unloaded.report)}`); - // A time limit and Ctrl+C end a run that does not return, remove the frame and report it. + // A time limit and an interruption end a run that does not return, remove the frame and report it. const hangingToken = crypto.randomUUID(); await writeFile('tests/hang.spec.js', `describe('hanging', () => {\n it('never ends', () => {\n` + ` parent.postMessage({hangingSpec: ${JSON.stringify(hangingToken)}}, location.origin);\n` + @@ -763,14 +781,14 @@ try { assert(!document.querySelector('iframe[title="WebFront tests"]'), 'A timed out run must remove its frame'); } finally { started.dispose(); } }); - const stopTests = new AbortController(); + const stopTests = interruption(); const started = hangingStarted(); try { const interrupted = tested([], {signal: stopTests.signal}); await untilReady(started.ready, interrupted); stopTests.abort(new Error('Interrupted')); const interruptedRun = await interrupted; - assert(interruptedRun.error?.exitCode === 130 && interruptedRun.report?.status === 'interrupted' && !document.querySelector('iframe[title="WebFront tests"]'), `Ctrl+C must stop a run: ${interruptedRun.error}`); + assert(interruptedRun.error?.exitCode === 130 && interruptedRun.report?.status === 'interrupted' && !document.querySelector('iframe[title="WebFront tests"]'), `An interruption must stop a run: ${interruptedRun.error}`); } finally { started.dispose(); } // The command must stop even when the bridge read never settles. Wait for the read, not wall time. const blockedRead = () => { @@ -790,12 +808,12 @@ try { assert(result.error?.exitCode === 124 && result.report?.status === 'timeout', `A blocked bridge must report the preparation timeout: ${result.error}`); }); const blocked = blockedRead(); - const interruptPreparing = new AbortController(); + const interruptPreparing = interruption(); const preparingRun = tested([], {bridge: blocked.bridge, signal: interruptPreparing.signal}); await untilReady(blocked.ready, preparingRun); interruptPreparing.abort(new Error('Interrupted')); const preparingResult = await preparingRun; - assert(preparingResult.error?.exitCode === 130 && preparingResult.report?.status === 'interrupted', `Ctrl+C during preparation must end with 130 and a report: ${preparingResult.error}`); + assert(preparingResult.error?.exitCode === 130 && preparingResult.report?.status === 'interrupted', `An interruption during preparation must end with 130 and a report: ${preparingResult.error}`); // macOS 13.3 supports WKWebView, but its WebKit need not provide AbortSignal.any (Safari 17.4). const signalAny = Object.getOwnPropertyDescriptor(AbortSignal, 'any'); Object.defineProperty(AbortSignal, 'any', {configurable: true, value: undefined}); @@ -803,7 +821,7 @@ try { const legacyPassing = await tested([], {signal: new AbortController().signal}); assert(legacyPassing.report?.status === 'passed' && legacyPassing.report.exitCode === 0, `A terminal run must work without AbortSignal.any: ${legacyPassing.error}`); - const alreadyStopped = new AbortController(); + const alreadyStopped = interruption(); alreadyStopped.abort(new Error('Interrupted')); const legacyStopped = await tested([], {signal: alreadyStopped.signal}); assert(legacyStopped.error?.exitCode === 130 && legacyStopped.report?.status === 'interrupted', @@ -817,14 +835,14 @@ try { assert(result.error?.exitCode === 124 && result.report?.status === 'timeout', `The preparation deadline must report timeout without AbortSignal.any: ${result.error}`); }); - const legacyStop = new AbortController(); + const legacyStop = interruption(); const blocked = blockedRead(); const legacyPreparing = tested([], {bridge: blocked.bridge, signal: legacyStop.signal}); await untilReady(blocked.ready, legacyPreparing); legacyStop.abort(new Error('Interrupted')); const legacyInterrupted = await legacyPreparing; assert(legacyInterrupted.error?.exitCode === 130 && legacyInterrupted.report?.status === 'interrupted', - `Ctrl+C during preparation must report interruption without AbortSignal.any: ${legacyInterrupted.error}`); + `An interruption during preparation must be reported without AbortSignal.any: ${legacyInterrupted.error}`); } finally { if (signalAny) Object.defineProperty(AbortSignal, 'any', signalAny); else delete AbortSignal.any; @@ -960,7 +978,7 @@ try { // A first build that fails shows its diagnostic in the terminal: no interface was published, so the page keeps // the terminal alone, without the icon or an empty frame, also once wf dev is stopped. await writeFile('layout/value.ts', 'export const value = ;\n'); - const failedStop = new AbortController(); + const failedStop = interruption(); let failedOutput = ''; const failedDev = execute(['dev', 'layout/main.ts'], {...context, signal: failedStop.signal, write: text => { failedOutput += text; }}).then(() => null, error => error); @@ -1401,7 +1419,7 @@ try { inner.remove(); // wf dev with the terminal collapsed: the full-window interface reloads and shows the build diagnostics. - const devStop = new AbortController(); + const devStop = interruption(); let devOutput = ''; await withTimers([750], async clock => { const poll = async () => { @@ -1441,7 +1459,7 @@ try { assert(page.elementFromPoint(icon.left + icon.width / 2, icon.top + icon.height / 2)?.closest('button') === button && overlay.width > 0, 'The icon must stay over the diagnostic'); } finally { devStop.abort(); } - assert((await devResult)?.exitCode === 130, 'Ctrl+C must stop dev with exit code 130'); + assert((await devResult)?.exitCode === 130, 'An interruption must stop dev with exit code 130'); }); assert(button.dataset.status === 'idle', `The tab must show that wf dev stopped: ${button.dataset.status}`); // A failed build keeps the last interface published: the next launch still opens on it. @@ -1528,13 +1546,22 @@ try { `The tab must show a running command while the terminal is collapsed: ${toggleButton.dataset.status}`); workspace.open(); assert((await commandState('layout')) === 'running', 'Opening must not interrupt a running command'); - terminal.input('\x03'); + // The Stop button of the floating window (#721): in its bar, before the close button, while a command runs. + const stop = mounted.stop; + assert(stop.parentNode === workspace.bar && stop.nextSibling === otherPage.querySelector('.webfront-terminal-close') && !stop.hidden && !stop.disabled + && there.box('.webfront-terminal-stop').width > 0, `The Stop button must show in the window's bar while a command runs: ${stop.parentNode?.className}`); + assert(Math.round(there.box('.webfront-terminal-stop').top) >= Math.round(there.box('.webfront-terminal-bar').top) + && Math.round(there.box('.webfront-terminal-stop').bottom) <= Math.round(there.box('.webfront-terminal-bar').bottom), 'The Stop button must be inside the bar'); + terminal.input('ignored'); + stop.click(); + assert(stop.disabled && otherPage.activeElement === terminal.textarea, 'An interrupted command must disable the button and leave the keys in the terminal'); await editor.whenIdle(); await rendered(); - await until(async () => (await commandState('layout')) === 'cancelled', 'Ctrl+C must still reach the command'); + await until(async () => (await commandState('layout')) === 'cancelled', 'The Stop button must reach the command'); + assert(stop.hidden && editor.status === 130 && editor.line === '', `The Stop button must interrupt the command with 130, drop the keys typed after it and hide: ${editor.status} ${editor.line}`); assert(toggleButton.dataset.status === 'idle', `The tab must show that the command ended: ${toggleButton.dataset.status}`); - assert(/waiting layout/.test(screen()) && /^layout kept$/m.test(screen()), - 'Ctrl+C must still reach the command, in the same session'); + assert(/waiting layout/.test(screen()) && /^Interrupted$/m.test(screen()) && /^layout kept$/m.test(screen()), + 'The Stop button must reach the command, in the same session'); await mounted.workspace.placeSaved(); terminal.dispose(); sessionFrame.remove(); @@ -1543,8 +1570,8 @@ try { if (wants('terminal')) { // The completions below name a script and a file that the `scripts` part creates in a single-session run. if (part === 'terminal') { - for (const path of ['tools/gen.ts', 'tools/jsx.tsx']) await writeFile(path, scripts[path]); - await writeFile('webfront.project.json', JSON.stringify({...manifest, scripts: {gen: 'tools/gen.ts', jsx: 'tools/jsx.tsx'}}, null, 2)); + for (const path of ['tools/gen.ts', 'tools/jsx.tsx', 'tools/coop.mjs']) await writeFile(path, scripts[path]); + await writeFile('webfront.project.json', JSON.stringify({...manifest, scripts: {gen: 'tools/gen.ts', jsx: 'tools/jsx.tsx', coop: 'tools/coop.mjs'}}, null, 2)); } await progress('terminal and sessions'); // The terminal: the application's C++ commands, run in this browser's session. @@ -1595,21 +1622,21 @@ try { assert(['ls', 'cat', 'tree', 'mounts', 'wf', 'echo'].every(name => firstWords.includes(name)) && !firstWords.includes('rm'), `Completion must offer the commands that exist: ${firstWords}`); assert((await runtime.complete('wf li', {bridge: webFront})).candidates.join() === 'list' && (await runtime.complete('wf list ', {bridge: webFront})).candidates.join() === '--tree', 'Completion must offer wf list and its option'); - // Ctrl+C: the terminal stops waiting at once, the next command answers while the first is still ending in C++. - const interruptLinger = new AbortController(); + // An interruption: the terminal stops waiting at once, the next command answers while the first is still ending in C++. + const interruptLinger = interruption(); const lingering = failure(runtime.runLine('linger first', lineContext(interruptLinger.signal))); await waitState('first', 'running'); interruptLinger.abort(new Error('Interrupted')); assert((await lingering)?.exitCode === 130, 'An interrupted C++ command must end with exit code 130'); const echoed = []; - await runtime.runLine('echo "after Ctrl+C"', lineContext(undefined, echoed)); - assert(echoed.join('') === 'after Ctrl+C\r\n', `The next command must run normally: ${echoed}`); + await runtime.runLine('echo "after the interruption"', lineContext(undefined, echoed)); + assert(echoed.join('') === 'after the interruption\r\n', `The next command must run normally: ${echoed}`); assert(['running', 'stopping'].includes(await commandState('first')), 'The second command must answer before the first one ends'); await waitState('first', 'stopping'); await webFront.cppFunction('test.release')('first'); await waitState('first', 'cancelled'); - // Sessions: a second browser has its own commands; a long command there does not delay this one, Ctrl+C here does - // not stop it, and its disconnection does. + // Sessions: a second browser has its own commands; a long command there does not delay this one, an interruption + // here does not stop it, and its disconnection does. const sessionFrame = document.createElement('iframe'); sessionFrame.src = '/fixtures/session.html'; document.body.append(sessionFrame); @@ -1618,7 +1645,7 @@ try { const second = await sessionFrame.contentWindow.session; const secondWait = failure(second.runtime.runLine('wait second', {bridge: second.bridge, cppCommands: second.cppCommands, signal: new AbortController().signal})); await waitState('second', 'running'); - const interruptFirst = new AbortController(); + const interruptFirst = interruption(); const firstWait = failure(runtime.runLine('wait here', lineContext(interruptFirst.signal))); await waitState('here', 'running'); const echoStarted = performance.now(); @@ -1627,7 +1654,7 @@ try { interruptFirst.abort(new Error('Interrupted')); await firstWait; await waitState('here', 'cancelled'); - assert(await commandState('second') === 'running', 'Ctrl+C in one browser must not stop the command of another'); + assert(await commandState('second') === 'running', 'An interruption in one browser must not stop the command of another'); const browsers = await webFront.cppFunction('test.browsers')(); // Its connection closes while its acknowledged command runs: the terminal stops waiting for an exit that cannot come. second.bridge.socket.close(); @@ -1652,7 +1679,7 @@ try { }}; // The test sets the terminal's size itself: an observer following the element would race with it. const mounted = async () => runtime.mount({bridge: terminalBridge, config, terminal: host, preview: context.preview, onExit: code => { exitedWith = code; }, fitToElement: false}); - const {terminal, editor} = await mounted(); + const {terminal, editor, stop} = await mounted(); terminal.resize(80, 12); const buffer = () => terminal.buffer.active; const rendered = () => new Promise(resolve => terminal.write('', resolve)); @@ -1664,6 +1691,14 @@ try { } await rendered(); }; + // A key pressed in the terminal, through xterm.js and its key handler (#721); xterm.js reads keyCode, which + // KeyboardEvent's constructor does not set. The engine runs no default action for it: test.keys sends real keys. + const press = init => { + const event = new KeyboardEvent('keydown', {bubbles: true, cancelable: true, ...init}); + Object.defineProperty(event, 'keyCode', {get: () => ({Escape: 27, c: 67})[init.key] ?? 0}); + terminal.textarea.dispatchEvent(event); + return event; + }; const rows = () => { const lines = []; for (let y = 0; y < buffer().length; ++y) lines.push(buffer().getLine(y).translateToString(true)); @@ -1766,14 +1801,14 @@ try { terminal.focus(); } } - // Initial dev errors must finish the session command, without requiring Ctrl+C (#560). + // Initial dev errors must finish the session command, without an interruption (#560). for (const [manifest, message] of [[null, 'No webfront.project.json: run wf init'], [{format: 1, name: 'empty', version: '0.1.0'}, 'Usage: wf dev ']]) { startupFiles = new Map(manifest ? [['webfront.project.json', new TextEncoder().encode(JSON.stringify(manifest))]] : []); try { terminal.input('wf dev\r'); await delay(10); - await eventually(() => !editor.busy, 'An invalid wf dev invocation must finish without Ctrl+C', {every: 10}); + await eventually(() => !editor.busy, 'An invalid wf dev invocation must finish without an interruption', {every: 10}); await editor.whenIdle(); await rendered(); assert(editor.status === 1 && rows().some(row => row.includes(message)) && lastRows(1)[0] === '> ', @@ -1782,7 +1817,7 @@ try { assert(editor.status === 0 && lastRows(2)[0] === 'recovered', 'The next command must run after the startup error'); } finally { startupFiles = undefined; - if (editor.busy) await type('\x03'); + if (editor.busy) await type('\x1b'); } } // Cell widths: CJK, emoji, a flag, a ZWJ sequence and a combining mark. @@ -1797,8 +1832,12 @@ try { assert(buffer().cursorX === 12 && editor.line === '漢字😀🇫🇷👨‍👩‍👧', `Backspace must erase whole clusters: ${buffer().cursorX} ${editor.line}`); await type('\x1b[D', '\x1b[D'); assert(buffer().cursorX === 8, `The cursor must move over whole clusters: ${buffer().cursorX}`); - await type('\x03'); - assert(lastRows(2)[0].endsWith('^C') && lastRows(1)[0] === '> ' && editor.line === '', 'Ctrl+C must drop the line'); + // Ctrl+C is the system's copy (#721): with nothing selected, it neither sends \x03 nor clears the line. + const copyKey = press({key: 'c', code: 'KeyC', ctrlKey: true}); + await rendered(); + assert(!copyKey.defaultPrevented && editor.line === '漢字😀🇫🇷👨‍👩‍👧' && buffer().cursorX === 8, `Ctrl+C must leave the line as it is: ${editor.line}`); + await type('\x05', '\x15'); + assert(lastRows(1)[0] === '> ' && editor.line === '', 'Ctrl+U at the end must erase the line'); // A line over several rows: wrapping, editing in the middle, a row filled exactly and a wide character at a row end. terminal.resize(20, 12); await rendered(); @@ -1826,7 +1865,7 @@ try { assert(editor.status === 1 && lastRows(2)[0] === 'Error: command failed on purpose', `A C++ exception must be shown as an error: ${lastRows(2)}`); await type('partial\r', 'x'); assert(JSON.stringify(lastRows(2)) === JSON.stringify(['partial', '> x']), `Output without a final line break must not hold the prompt: ${lastRows(2)}`); - await type('\x03'); + await type('\x15'); // Keys typed while a completion is pending are applied after it, Enter included. terminal.input('ec'); terminal.input('\t'); @@ -1841,15 +1880,68 @@ try { assert(lastRows(3)[0] === '> echo ho typed-ahead' && editor.ahead.length === 0, `The completed line must run once: ${lastRows(3)}`); await type('echo ok\r'); assert(editor.status === 0, 'A successful command must reset the status'); - // Ctrl+C in the terminal: the prompt comes back at once, and a command typed then runs while the first one ends. + // Escape in the terminal (#721): the prompt comes back at once, and a command typed then runs while the first one + // ends. The Stop button shows over the terminal's corner while the command runs: this terminal has no window bar. + assert(stop.hidden && stop.parentNode === host, 'The Stop button must be hidden while no command runs'); terminal.input('linger terminal\r'); await waitState('terminal', 'running'); - await type('\x03'); + const corner = stop.getBoundingClientRect(), area = host.getBoundingClientRect(); + assert(!stop.hidden && !stop.disabled && corner.width > 0 && corner.top - area.top < 40 && area.right - corner.right < 60, + `The Stop button must show at the terminal's top right while a command runs: ${JSON.stringify(corner)}`); + const escape = press({key: 'Escape', code: 'Escape'}); + await editor.whenIdle(); + await rendered(); + assert(escape.key === 'Escape' && editor.status === 130 && lastRows(2)[0] === 'Interrupted' && stop.hidden, + `Escape must interrupt a C++ command with 130: ${lastRows(3)} ${editor.status}`); await type('echo next\r'); const lingerState = await commandState('terminal'); - assert(editor.status === 0 && lastRows(2)[0] === 'next' && ['running', 'stopping'].includes(lingerState), `Ctrl+C must interrupt a C++ command: ${lastRows(3)} ${editor.status} ${lingerState}`); + assert(editor.status === 0 && lastRows(2)[0] === 'next' && ['running', 'stopping'].includes(lingerState), `The next command must run while the first one ends: ${lastRows(3)} ${editor.status} ${lingerState}`); await waitState('terminal', 'stopping'); await webFront.cppFunction('test.release')('terminal'); + // The Stop button interrupts a wf run script like Escape: its signal is aborted and it ends with 130. + terminal.input('wf run coop\r'); + await eventually(() => rows().some(row => row === 'waiting') && !stop.hidden, () => `The script did not start: ${lastRows(3)}`, {every: 20}); + stop.click(); + assert(stop.disabled && host.ownerDocument.activeElement === terminal.textarea, 'The Stop button must disable itself and leave the keys in the terminal'); + await editor.whenIdle(); + await rendered(); + assert(editor.status === 130 && rows().some(row => /Script coop interrupted/.test(row)) && stop.hidden && lastRows(1)[0] === '> ', + `The Stop button must interrupt wf run with 130: ${lastRows(4)} ${editor.status}`); + // The system's copy and paste with real keys, where the frontend can send them (CEF): the engine copies the + // terminal's selection on Ctrl+C, pastes it on Ctrl+V, Ctrl+A selects the terminal, Escape clears the selection and + // interrupts a command. + const native = async (...keys) => { + const sent = await webFront.cppFunction('test.keys')(JSON.stringify(keys)); + assert(sent === 'sent' || sent === 'unsupported', `The keys could not be sent: ${sent}`); + return sent === 'sent'; + }; + const ctrl = 2; + terminal.focus(); + await type('echo clip-board\r'); + const copied = cursorRow() - 1; + assert(rows()[copied] === 'clip-board', `The text to copy must be on screen: ${rows()[copied]}`); + terminal.select(0, copied, 'clip-board'.length); + if (await native(['c', 'KeyC', 67, ctrl])) { + await progress('copy and paste with real keys'); + await delay(100); + assert(editor.line === '' && terminal.getSelection() === 'clip-board', `Ctrl+C must copy without typing anything: ${JSON.stringify(editor.line)}`); + await native(['Escape', 'Escape', 27, 0]); + await eventually(() => !terminal.hasSelection(), 'Escape must clear the selection', {every: 20}); + await native(['v', 'KeyV', 86, ctrl]); + await eventually(() => editor.line === 'clip-board', () => `Ctrl+V must paste the copied selection: ${JSON.stringify(editor.line)}`, {every: 20}); + await native(['a', 'KeyA', 65, ctrl]); + await eventually(() => terminal.getSelection().includes('> echo clip-board'), 'Ctrl+A must select the terminal', {every: 20}); + assert(host.ownerDocument.getSelection()?.toString() === '', 'Ctrl+A must not select the page'); + await native(['Escape', 'Escape', 27, 0]); + await eventually(() => !terminal.hasSelection(), 'Escape must clear the selection made by Ctrl+A', {every: 20}); + await type('\x15'); + terminal.input('linger keys\r'); + await waitState('keys', 'running'); + await native(['Escape', 'Escape', 27, 0]); + await eventually(() => !editor.busy && editor.status === 130, () => `A real Escape must interrupt the command: ${editor.status}`, {every: 20}); + await waitState('keys', 'stopping'); + await webFront.cppFunction('test.release')('keys'); + } else terminal.clearSelection(); // Pasted lines run one after the other; the last one, without a line break, waits on the prompt. // Keys typed one by one while a command runs are applied after it, Enter included. terminal.input('sleep 300\r'); @@ -1867,7 +1959,7 @@ try { const completed = async (text, expected) => { await type(text, '\t'); assert(editor.line === expected, `${JSON.stringify(text)} must complete to ${JSON.stringify(expected)}: ${JSON.stringify(editor.line)}`); - await type('\x03'); + await type('\x15'); }; await completed('ec', 'echo '); await completed('wf ru', 'wf run '); @@ -1886,7 +1978,7 @@ try { await completed("echo 'my dir/f", "echo 'my dir/f"); await type('h', '\t'); assert(editor.line === 'h' && lastRows(2)[0].includes('help') && lastRows(2)[0].includes('history'), `Several candidates must be listed: ${lastRows(2)}`); - await type('\x03'); + await type('\x15'); await type('clear\r'); assert(buffer().length === terminal.rows && rows()[0] === '> ', `clear must empty the screen and the scrollback: ${rows()[0]}`); // A line taller than the screen is drawn a screen at a time around the cursor, never duplicated on it. @@ -1911,15 +2003,15 @@ try { assert(lastRows(2)[0] === digits.slice(80) && lastRows(1)[0] === '> ', `A tall line must run: ${screen()}`); terminal.resize(80, 12); await type('clear\r'); - // Enter and Ctrl+C typed while a completion is pending: the command starts, then is interrupted at once. + // Enter and Escape typed while a completion is pending: the command starts, then is interrupted at once. terminal.input('lin'); terminal.input('\t'); terminal.input('replay'); terminal.input('\r'); - terminal.input('\x03'); + terminal.input('\x1b'); await waitState('replay', 'stopping'); await webFront.cppFunction('test.release')('replay'); - await eventually(() => !editor.busy, () => `Ctrl+C typed during a completion must interrupt the replayed command: ${lastRows(3)}`, + await eventually(() => !editor.busy, () => `Escape typed during a completion must interrupt the replayed command: ${lastRows(3)}`, {attempts: 100, every: 20}); assert(editor.status === 130 && lastRows(3)[0] === '> linger replay', `The replayed command must be interrupted: ${lastRows(3)} ${editor.status}`); // The history is kept per project: a new terminal recalls it. @@ -1940,7 +2032,7 @@ try { again.terminal.input('\x1b[A'); await new Promise(resolve => again.terminal.write('', resolve)); assert(again.editor.line === 'exit 4', `A new terminal must recall the project's history: ${again.editor.line}`); - again.terminal.input('\x03'); + again.terminal.input('\x15'); // Two terminals on the same project: each one adds its lines to the history, neither erases the other's. const otherHost = document.createElement('div'); otherHost.style.cssText = 'width:640px;height:240px';