diff --git a/.github/workflows/DeveloperDistribution.yml b/.github/workflows/DeveloperDistribution.yml index 8789fdcf..97adb980 100644 --- a/.github/workflows/DeveloperDistribution.yml +++ b/.github/workflows/DeveloperDistribution.yml @@ -51,14 +51,25 @@ jobs: - name: Install pinned maintenance dependencies run: npm ci --prefix js/developer/vendor --ignore-scripts - name: Build and verify the environment and starter packages + env: + PUBLISHING: ${{ startsWith(github.ref, 'refs/tags/developer-v') || (github.event_name == 'workflow_dispatch' && inputs.publish) }} run: | node js/developer/tools/build.mjs build-distribution node js/developer/tools/build.mjs build-distribution-repeat cmp build-distribution/environment.tgz build-distribution-repeat/environment.tgz cmp build-distribution/pi-starter.tgz build-distribution-repeat/pi-starter.tgz cmp build-distribution/life-starter.tgz build-distribution-repeat/life-starter.tgz - cmp include/webfront/system/DeveloperReleaseData.hpp build-distribution/DeveloperReleaseData.hpp - node --test js/developer/tools/check.mjs js/developer/tools/distribution-check.mjs + # The pin names the last published version. Sources at that version must rebuild it; sources ahead of it + # leave the header pinning the published archive, which is checked against the deployed file. + pinned=$(sed -n 's/.*version{"\([^"]*\)"}.*/\1/p' include/webfront/system/DeveloperReleaseData.hpp) + building=$(node -p "require('./js/developer/tools/distribution.json').version") + if [ "$pinned" = "$building" ] || [ "$PUBLISHING" = true ]; then + cmp include/webfront/system/DeveloperReleaseData.hpp build-distribution/DeveloperReleaseData.hpp + else + echo "::notice::Sources build $building; DeveloperReleaseData.hpp still pins the published $pinned." + node js/developer/tools/pin-check.mjs + fi + node --test js/developer/tools/check.mjs js/developer/tools/distribution-check.mjs js/developer/tools/manifest-check.mjs - name: Check the dedicated release tag if: startsWith(github.ref, 'refs/tags/developer-v') env: diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 56a58e78..48efaf07 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,19 @@ ## Unreleased +### Added + +- Project manifest `webfront.project.json` (format 1: `name`, `version`, `dependencies`, `registry`, `scripts`, + `entries`, `providers`, `test`, `permissions`), strictly validated; `wf init`, `wf install [--update]` and + manifest-driven `wf preview`/`wf embed` in developer distribution 0.5.0 (not published yet; the pin in + `DeveloperReleaseData.hpp` stays on 0.4.1 until 0.5.0 is published and verified). The lock records the digest of + the manifest dependencies and reports a desynchronized state. `developer::Store::commitGroup` publishes + manifest and lock through a synced intent journal with crash recovery and a concurrent-install precondition. + New bridge callbacks `webfront.developer.state` and `webfront.developer.commitGroup`. Starters ship a manifest; + `wf install` now needs `wf init` first, which adopts the roots of an existing lock so a project locked before 0.5.0 + keeps its locked graph. A committed publication that cannot be completed does not prevent opening the project: + it is reported (`developer::IncompletePublication`) and completed by the next command. + ### Changed - **Breaking:** library headers moved to `include/webfront/`; include them as ``, diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index 44ca9540..13ffedda 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -47,7 +47,7 @@ native tests from empty working directories, with developer callbacks absent. Pa HTTP 200, CORS `*` and the pinned archive bytes. These checks supplement offline CTest fixtures. The default configuration is generated in `include/webfront/system/DeveloperReleaseData.hpp` and targets -`https://ambroise-leclerc.github.io/WebFront/developer/0.4.1/environment.tgz`. This version, published and archived as `developer-v0.4.1`, generates providers that include ``. Published 0.4.0 stays immutable but targets the former include layout. The configuration pins one version and +`https://ambroise-leclerc.github.io/WebFront/developer/0.4.1/environment.tgz`. This version, published and archived as `developer-v0.4.1`, generates providers that include ``. Published 0.4.0 stays immutable but targets the former include layout. The sources are ahead of that pin: `distribution.json` names 0.5.0 (the project manifest), which is not pinned until it has been published and verified (see `js/developer/tools/PUBLISHING.md`). The configuration pins one version and its SHA-512 rather than resolving a mutable `latest` channel. An explicit `DeveloperBootstrapOptions{.environment = url, .integrity = trustedHash}` still selects a different HTTPS/CORS repository or a same-origin test fixture. Users install neither npm nor Node.js. @@ -139,6 +139,69 @@ The PI starter remains available through `wf create pi` for existing projects an coverage. Its sources are maintained under `js/developer/tools/starters/pi/`; the public C++ examples are limited to Hello World and Life. Existing embedded React/Babel providers remain supported. +## Project manifest (`webfront.project.json`) + +Available from developer distribution 0.5.0, which is not published yet: the default configuration still pins 0.4.1, whose environment predates the manifest. +A project has one manifest, the equivalent of `package.json`, which every `wf` command reads: + +```json +{ + "format": 1, + "name": "life", + "version": "0.1.0", + "dependencies": {"react": "^19.3.1", "react-dom": "^19.3.1"}, + "registry": "https://registry.npmjs.org/", + "scripts": {}, + "entries": {"main": "ui/main.tsx"}, + "providers": {"LifeUI": {"entry": "main", "output": "generated/LifeUI.hpp"}}, + "test": {"specs": []}, + "permissions": {} +} +``` + +Only `format`, `name` and `version` are required. Validation is strict: an unknown key, a format +newer than the environment reads, a path leaving the project, a non-HTTPS registry or origin and an +unknown permission are errors printed in the terminal, never silently ignored. `scripts`, `test` and +`permissions` are validated here and used by the later commands (#307, #310); permissions will only +frame the operations of the `context` API of authorized scripts, they are not a sandbox. + +- `wf init [name]` writes `webfront.project.json` at the project root, the manifest every `wf` command + reads; it never replaces an existing one. When a lock already exists (a project installed before + 0.5.0), the manifest takes its roots as dependencies (`^version`, or the range they were installed with). +- `wf install [@range]` resolves, downloads and verifies into the cache, then publishes the + manifest (the requested range, or `^version` when none was given) and the lock in a single transaction. +- `wf install` without argument installs exactly the locked graph (like `npm ci`) when the lock agrees + with the manifest, resolves the manifest and creates the lock when there is none, and fails when they + disagree. `wf install --update` resolves the manifest again. +- `wf preview [entry]` and `wf embed ` use `entries` and `providers`; an explicit path still works. + `wf embed ` generates the C++ class `webfront::fs::`; with `--output `, + the file name must be a C++ class name. +- A requested range is checked like the manifest that records it, before anything is resolved: a range or + tag the manifest cannot hold is refused instead of written. The manifest is rewritten with the keys it had, + plus the new dependencies. + +The manifest holds the intent (roots and ranges), the lock the exact resolution. The lock records a +digest of the manifest's `dependencies` (`manifestDigest`). The project is **consistent** when they +match, **unlocked** without a lock (no installed graph) and **desynchronized** when the dependencies +changed since the lock was written; every command reports that state and none resolves implicitly. +A lock written before 0.5.0 has no digest: it is used as consistent when its roots satisfy the +dependencies (after `wf init`, they do), and `wf install` records the digest without resolving anything. + +Both files are published by one all-or-nothing transaction (`developer::Store::commitGroup`): the +staged files are moved under `.webfront/developer/journal/`, a journal naming them is written and +synchronized to disk (the commit point), then each file replaces its target. Opening the project +completes a journal that reached its commit point and abandons the others, so a crash never leaves +a manifest and a lock that belong to different installations. A failure before the commit point returns +the staged files to their transactions. A committed publication whose replacement fails (a target turned +into a directory, a file locked by another program) is reported as committed but not applied yet; its +journal is kept, the project still opens, and every later command first completes it, failing with the +cause until it can. The publication carries a precondition, +the fingerprint of both files as read when the command began: if another browser or command changed +them meanwhile, it is refused with "The project changed since it was read; run the command again" and +nothing is lost. Recovery and group publications also hold an advisory lock on `.webfront/developer/journal/.lock`, so +several processes sharing a project (or several stores of one process) are serialized rather than abandoning one +another's publication; other project files stay unprotected against concurrent local modification. `wf restore` (#306) will fill the cache from a consistent lock without ever writing them. + ## Dependencies, storage and limitations - `wf install` accepts exact versions, registry tags and semver ranges, resolves ordinary @@ -150,8 +213,8 @@ examples are limited to Hello World and Life. Existing embedded React/Babel prov - Browser/production exports, ESM, CommonJS, TS/TSX, JSX, CSS and imported resource files are supported. Private package exports, network imports and unavailable Node built-ins fail. Package-specific build pipelines and automatic polyfills are not supplied. -- `webfront-packages.lock.json` records exact package versions, dependency edges, source integrities - and requested roots. Commit it and the source TSX/CSS; the generated provider can also be committed. +- `webfront-packages.lock.json` records exact package versions, dependency edges, source integrities, + requested roots and the digest of the manifest dependencies it resolved. Commit it and the source TSX/CSS; the generated provider can also be committed. Preview/embed consume the locked local files without resolving versions again. - Unpacked packages are cached by name, version and integrity under `.webfront/developer/packages/`. A failed install can leave unused cached packages, but the lock file remains unchanged. The tools diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index b1f89b7b..e0b230ee 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -9,7 +9,8 @@ removed without redirect headers (see `docs/CHANGELOG.md`). Browser sources live (bridge, fallback, bootstrap loader and embedding modules) and `js/developer/` (environment, terminal components, build tools, vendoring tools); tests live in `test/{unit,web,fuzz,fixtures,cmake}`. The CTest case `RepositoryLayout` enforces the root. The generated-provider include changed, so the developer -distribution is bumped to 0.4.1, published and archived as `developer-v0.4.1`. +distribution is bumped to 0.4.1, published and archived as `developer-v0.4.1`. Version 0.5.0 (project manifest, #305) is +built from the sources but not pinned: `DeveloperReleaseData.hpp` moves to it only after `developer-v0.5.0` is published and verified. ## CI test duration (#298, 2026-10-21) diff --git a/docs/adr/ADR-009-modules-et-assets-reproductibles.md b/docs/adr/ADR-009-modules-et-assets-reproductibles.md index fe4c033a..816c263b 100644 --- a/docs/adr/ADR-009-modules-et-assets-reproductibles.md +++ b/docs/adr/ADR-009-modules-et-assets-reproductibles.md @@ -12,7 +12,7 @@ | 1.5 | 2026-10-16 | Acceptée | Ambroise Leclerc | Contrôle des fins de ligne LF des sources et en-têtes embarqués. | [520ca23](https://github.com/ambroise-leclerc/WebFront/commit/520ca23fa694519d9f428ed3661e64dcfdf906a2) | | 1.6 | 2026-10-19 | Acceptée | Ambroise Leclerc | Négociation gzip/identity, décodage validé et budget de sortie. | [4be7358](https://github.com/ambroise-leclerc/WebFront/commit/4be73581ee6b9f569cb6e50aced73e27562aa38c) | | 2.0 | 2026-10-19 | Acceptée | Ambroise Leclerc | Génération gzip reproductible avec compresseur intégré ; distributions actualisées et runtime React ESM local. | [b031ab5](https://github.com/ambroise-leclerc/WebFront/commit/b031ab58ea9cc32290d701094c1333bab455e67f) | -| 2.1 | 2026-10-22 | Acceptée | Ambroise Leclerc | Assets embarqués limités à la liste normative de l'ADR-016 ; trajectoire de retrait de BabelFS, ReactFS, JasmineFS et des sources vendorisées. | À renseigner après fusion de l'issue #304. | +| 2.1 | 2026-10-22 | Acceptée | Ambroise Leclerc | Assets embarqués limités à la liste normative de l'ADR-016 ; trajectoire de retrait de BabelFS, ReactFS, JasmineFS et des sources vendorisées. | [404fed2](https://github.com/ambroise-leclerc/WebFront/commit/404fed2c2145d4faba8efee035e10522ff87a91f) | ## État et chronologie diff --git a/docs/adr/ADR-010-composants-et-outils-optionnels.md b/docs/adr/ADR-010-composants-et-outils-optionnels.md index 1f2b7f3b..80941db4 100644 --- a/docs/adr/ADR-010-composants-et-outils-optionnels.md +++ b/docs/adr/ADR-010-composants-et-outils-optionnels.md @@ -10,7 +10,7 @@ | 1.3 | 2026-10-15 | Acceptée | Ambroise Leclerc | Recherche, installation et ouverture des outils via une extension navigateur. | [18d5bb4](https://github.com/ambroise-leclerc/WebFront/commit/18d5bb4c5db6e4dc5ecf4867378d451887b2c133) | | 1.4 | 2026-10-15 | Acceptée | Ambroise Leclerc | Validation des outils avec un registre local factice. | [d53ffcc](https://github.com/ambroise-leclerc/WebFront/commit/d53ffcc40102c7405eb7060d7021aad366d6d7e9) | | 1.5 | 2026-10-16 | Acceptée | Ambroise Leclerc | Interruption des commandes navigateur et transferts séquentiels par blocs de 256 KiB. | [c81f7f7](https://github.com/ambroise-leclerc/WebFront/commit/c81f7f74728ad24a53c16f907e016eb0fe1b8bce) | -| 1.6 | 2026-10-22 | Acceptée | Ambroise Leclerc | Trajectoire de retrait de Terminal.hpp, ToolManager.hpp, ToolStore et PackageFS au profit de l'environnement bootstrap (ADR-016). | À renseigner après fusion de l'issue #304. | +| 1.6 | 2026-10-22 | Acceptée | Ambroise Leclerc | Trajectoire de retrait de Terminal.hpp, ToolManager.hpp, ToolStore et PackageFS au profit de l'environnement bootstrap (ADR-016). | [404fed2](https://github.com/ambroise-leclerc/WebFront/commit/404fed2c2145d4faba8efee035e10522ff87a91f) | ## État et chronologie diff --git a/docs/adr/ADR-013-bootstrap-developpeur-a-la-demande.md b/docs/adr/ADR-013-bootstrap-developpeur-a-la-demande.md index 13335a62..89828e89 100644 --- a/docs/adr/ADR-013-bootstrap-developpeur-a-la-demande.md +++ b/docs/adr/ADR-013-bootstrap-developpeur-a-la-demande.md @@ -5,7 +5,7 @@ | Version | Date | État | Auteur | Évolution | Commit | | --- | --- | --- | --- | --- | --- | | 0.1 | 2026-10-20 | Proposée | Ambroise Leclerc | Proposition et première implémentation du bootstrap développeur versionné. | À renseigner après intégration. | -| 0.2 | 2026-10-22 | Proposée | Ambroise Leclerc | Alignement sur ADR-016 : la proposition devient la base de l'architecture ; preuves multiplateformes manquantes listées. | À renseigner après fusion de l'issue #304. | +| 0.2 | 2026-10-22 | Proposée | Ambroise Leclerc | Alignement sur ADR-016 : la proposition devient la base de l'architecture ; preuves multiplateformes manquantes listées. | [404fed2](https://github.com/ambroise-leclerc/WebFront/commit/404fed2c2145d4faba8efee035e10522ff87a91f) | ## Statut et date diff --git a/docs/adr/ADR-014-construction-javascript-dans-le-browser.md b/docs/adr/ADR-014-construction-javascript-dans-le-browser.md index df48a045..d6459a08 100644 --- a/docs/adr/ADR-014-construction-javascript-dans-le-browser.md +++ b/docs/adr/ADR-014-construction-javascript-dans-le-browser.md @@ -5,7 +5,7 @@ | Version | Date | État | Auteur | Évolution | Commit | | --- | --- | --- | --- | --- | --- | | 0.1 | 2026-10-20 | Proposée | Ambroise Leclerc | Proposition et première implémentation du résolveur npm et du compilateur navigateur. | À renseigner après intégration. | -| 0.2 | 2026-10-22 | Proposée | Ambroise Leclerc | Alignement sur ADR-016 : la proposition devient la base de l'architecture ; preuves multiplateformes manquantes listées. | À renseigner après fusion de l'issue #304. | +| 0.2 | 2026-10-22 | Proposée | Ambroise Leclerc | Alignement sur ADR-016 : la proposition devient la base de l'architecture ; preuves multiplateformes manquantes listées. | [404fed2](https://github.com/ambroise-leclerc/WebFront/commit/404fed2c2145d4faba8efee035e10522ff87a91f) | ## Statut et date diff --git a/docs/adr/ADR-015-ressources-generees-par-application.md b/docs/adr/ADR-015-ressources-generees-par-application.md index c4ba88cf..2c949875 100644 --- a/docs/adr/ADR-015-ressources-generees-par-application.md +++ b/docs/adr/ADR-015-ressources-generees-par-application.md @@ -5,7 +5,7 @@ | Version | Date | État | Auteur | Évolution | Commit | | --- | --- | --- | --- | --- | --- | | 0.1 | 2026-10-20 | Proposée | Ambroise Leclerc | Proposition et première implémentation de wf embed et du parcours hors ligne. | À renseigner après intégration. | -| 0.2 | 2026-10-22 | Proposée | Ambroise Leclerc | Alignement sur ADR-016 : la proposition devient la base de l'architecture ; preuves multiplateformes manquantes listées. | À renseigner après fusion de l'issue #304. | +| 0.2 | 2026-10-22 | Proposée | Ambroise Leclerc | Alignement sur ADR-016 : la proposition devient la base de l'architecture ; preuves multiplateformes manquantes listées. | [404fed2](https://github.com/ambroise-leclerc/WebFront/commit/404fed2c2145d4faba8efee035e10522ff87a91f) | ## Statut et date diff --git a/docs/adr/ADR-016-bootstrap-comme-socle.md b/docs/adr/ADR-016-bootstrap-comme-socle.md index c863ec1f..03e75890 100644 --- a/docs/adr/ADR-016-bootstrap-comme-socle.md +++ b/docs/adr/ADR-016-bootstrap-comme-socle.md @@ -4,7 +4,7 @@ | Version | Date | État | Auteur | Évolution | Commit | | --- | --- | --- | --- | --- | --- | -| 1.0 | 2026-10-22 | Acceptée | Ambroise Leclerc | Décision initiale : environnement bootstrap comme architecture de base, liste normative du cœur, scripts autorisés, indépendance vis-à-vis de Node.js. | À renseigner après fusion de l'issue #304. | +| 1.0 | 2026-10-22 | Acceptée | Ambroise Leclerc | Décision initiale : environnement bootstrap comme architecture de base, liste normative du cœur, scripts autorisés, indépendance vis-à-vis de Node.js. | [404fed2](https://github.com/ambroise-leclerc/WebFront/commit/404fed2c2145d4faba8efee035e10522ff87a91f) | ## Statut et date diff --git a/include/webfront/DeveloperApp.hpp b/include/webfront/DeveloperApp.hpp index ff15100f..996d812a 100644 --- a/include/webfront/DeveloperApp.hpp +++ b/include/webfront/DeveloperApp.hpp @@ -72,6 +72,8 @@ class BasicDeveloperApp : public BasicWF("webfront.developer.write"); expose<&Store::commit, void, std::string>("webfront.developer.commit"); expose<&Store::abort, void, std::string>("webfront.developer.abort"); + expose<&Store::stateOfLines, std::string, std::string>("webfront.developer.state"); + expose<&Store::commitGroupLines, void, std::string, std::string, std::string>("webfront.developer.commitGroup"); } /// Registers a store operation as a bridge callback; the store stays alive as long as the callback. diff --git a/include/webfront/system/DeveloperJournal.hpp b/include/webfront/system/DeveloperJournal.hpp new file mode 100644 index 00000000..72ce233e --- /dev/null +++ b/include/webfront/system/DeveloperJournal.hpp @@ -0,0 +1,314 @@ +/// @brief Intent journal of the developer store: publishing several files as one all-or-nothing change. +#pragma once + +#include "WindowsCompat.hpp" +#include "DeveloperPaths.hpp" + +#include +#include +#include +#include +#include +#include + +#if !defined(_WIN32) +#include +#include +#include +#endif + +namespace webfront::developer { + +/// Project-relative directory holding the journals of group publications. +inline constexpr std::string_view journalDirectory = ".webfront/developer/journal"; +inline constexpr std::size_t maxGroupFiles = 4; + +/// Called with the name of each step of a group publication and of its recovery. Tests throw +/// InjectedFault from it to stop the process at that step without any cleanup, as a crash would. +using StepHook = std::function; + +/// A simulated crash: the store leaves the disk exactly as it is. +struct InjectedFault : std::runtime_error { + using std::runtime_error::runtime_error; +}; + +/// Flushes a file's content to stable storage. +inline void syncFile(const std::filesystem::path& file) { +#if defined(_WIN32) + HANDLE handle = CreateFileW(file.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (handle == INVALID_HANDLE_VALUE) + throw std::runtime_error("Cannot open " + file.string() + " for synchronization"); + const bool flushed = FlushFileBuffers(handle) != 0; + CloseHandle(handle); + if (!flushed) + throw std::runtime_error("Cannot synchronize " + file.string()); +#else + const int descriptor = ::open(file.c_str(), O_RDONLY); + if (descriptor < 0) + throw std::runtime_error("Cannot open " + file.string() + " for synchronization"); +#if defined(__APPLE__) && defined(F_FULLFSYNC) + const bool flushed = ::fcntl(descriptor, F_FULLFSYNC) == 0 || ::fsync(descriptor) == 0; +#else + const bool flushed = ::fsync(descriptor) == 0; +#endif + ::close(descriptor); + if (!flushed) + throw std::runtime_error("Cannot synchronize " + file.string()); +#endif +} + +/// Makes the renames and creations in a directory durable. Windows offers no equivalent. +inline void syncDirectory(const std::filesystem::path& directory) { +#if !defined(_WIN32) + syncFile(directory); +#else + (void)directory; +#endif +} + +/// Creates the missing directories between the project root and `directory`, synchronizing the parent +/// of each one it creates: the entry of a new directory is only durable once its parent is. +inline void createDirectoriesDurably(const std::filesystem::path& root, const std::filesystem::path& directory, + const std::function& sync = syncDirectory) { + auto current = root; + for (const auto& part : directory.lexically_relative(root)) { + if (part == ".") + continue; + current /= part; + if (!std::filesystem::exists(current)) { + std::filesystem::create_directory(current); + sync(current.parent_path()); + } + } +} + +/// Serializes the publications and the recoveries of every process sharing a project: an advisory lock on a +/// file of the journal directory, released when the object dies, whatever the way out. The mutex of a Store +/// only protects that store; without this a second process could take a publication still being prepared +/// for the remains of an interrupted one. +class ProjectLock { +public: + explicit ProjectLock(const std::filesystem::path& file) { +#if defined(_WIN32) + handle = CreateFileW(file.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + OVERLAPPED region{}; + if (handle == INVALID_HANDLE_VALUE || !LockFileEx(handle, LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, ®ion)) { + release(); + throw std::runtime_error("Cannot lock the project journal"); + } +#else + descriptor = ::open(file.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600); + if (descriptor < 0 || ::flock(descriptor, LOCK_EX) != 0) { + release(); + throw std::runtime_error("Cannot lock the project journal"); + } +#endif + } + ProjectLock(const ProjectLock&) = delete; + ProjectLock& operator=(const ProjectLock&) = delete; + ~ProjectLock() { + release(); + } + +private: + void release() noexcept { +#if defined(_WIN32) + if (handle != INVALID_HANDLE_VALUE) + CloseHandle(handle); + handle = INVALID_HANDLE_VALUE; +#else + if (descriptor >= 0) + ::close(descriptor); + descriptor = -1; +#endif + } +#if defined(_WIN32) + HANDLE handle = INVALID_HANDLE_VALUE; +#else + int descriptor = -1; +#endif +}; + +inline constexpr std::string_view lockName = ".lock"; + +/// What a group publication changes: the project file it replaces and the journal-owned file replacing it. +struct JournalEntry { + std::string target; + std::string source; +}; + +inline constexpr std::string_view journalHeader = "webfront-journal 1"; +inline constexpr std::string_view journalEnd = "end"; + +inline std::string serializeJournal(const std::vector& entries) { + std::string text{journalHeader}; + text += '\n'; + for (const auto& [target, source] : entries) + text += target + '\n' + source + '\n'; + text += journalEnd; + text += '\n'; + return text; +} + +/// Returns the entries of a complete journal, nothing for an incomplete or malformed one. +inline std::optional> parseJournal(const std::string& text) { + std::vector lines; + std::istringstream stream{text}; + for (std::string line; std::getline(stream, line);) + lines.push_back(std::move(line)); + if (lines.size() < 4 || lines.size() % 2 != 0 || lines.front() != journalHeader || lines.back() != journalEnd) + return std::nullopt; + std::vector entries; + for (std::size_t i = 1; i + 1 < lines.size(); i += 2) { + const auto& source = lines[i + 1]; + if (source.empty() || !std::ranges::all_of(source, [](unsigned char c) { return std::isdigit(c) != 0; })) + return std::nullopt; + entries.push_back({lines[i], source}); + } + return entries; +} + +/// Identifies the content of project files: a precondition for publications that were prepared +/// from an earlier reading of the project. Not a security measure. +inline std::string fingerprint(const std::filesystem::path& root, const std::vector& paths) { + std::uint64_t hash = 14695981039346656037ULL; + const auto feed = [&hash](const char* data, std::size_t size) { + for (std::size_t i = 0; i < size; ++i) + hash = (hash ^ static_cast(data[i])) * 1099511628211ULL; + }; + for (const auto& path : paths) { + const auto file = projectPath(root, path); + std::ifstream stream(file, std::ios::binary); + const char present = std::filesystem::is_regular_file(file) && stream ? 1 : 0; + feed(&present, 1); + if (!present) + continue; + const auto size = static_cast(std::filesystem::file_size(file)); + feed(reinterpret_cast(&size), sizeof size); + std::vector block(64 * 1024); + while (stream.read(block.data(), static_cast(block.size())) || stream.gcount() > 0) + feed(block.data(), static_cast(stream.gcount())); + } + char text[17]; + std::snprintf(text, sizeof text, "%016llx", static_cast(hash)); + return text; +} + +/// Completes a committed journal: every source still present replaces its target. Safe to repeat +/// after an interruption, including one of this very function. A source that is gone was already +/// renamed: sources are only removed after the journal, and a publication that never reached its +/// journal is never rolled forward. +inline void rollForward(const std::filesystem::path& root, const std::filesystem::path& directory, const std::string& number, + const std::vector& entries, const StepHook& hook) { + const auto owned = directory / (number + ".d"); + int done = 0; + std::set directories{owned}; + for (const auto& [target, source] : entries) { + const auto staged = owned / source; + const auto destination = projectPath(root, target); + if (std::filesystem::is_regular_file(staged)) { + createDirectoriesDurably(root, destination.parent_path()); + std::filesystem::rename(staged, destination); + } + directories.insert(destination.parent_path()); + if (hook) + hook("replacement-" + std::to_string(++done)); + } + // The journal is the only record of what remains to be done: it must outlive every replacement, so + // make the renames durable (the directories holding the targets and the emptied source) first. + for (const auto& changed : directories) + syncDirectory(changed); + if (hook) + hook("replacements-synced"); + std::filesystem::remove(directory / (number + ".journal")); + syncDirectory(directory); + std::error_code ignored; + std::filesystem::remove_all(owned, ignored); +} + +/// A publication past its commit point that could not be completed yet: its journal is kept, and the next +/// recovery (the next state() or group publication, or the next opening of the project) completes it. +struct IncompletePublication : std::runtime_error { + explicit IncompletePublication(const std::string& reason) + : std::runtime_error("A committed publication of the project is not applied yet (" + reason + + "); fix the cause and run the command again to complete it") {} +}; + +/// Completes the journals that reached their commit point and abandons the others. A journal is +/// committed once it is renamed to ".journal"; everything else is the remains of a publication +/// interrupted before that point, where no project file was touched. A committed journal that cannot be +/// completed is kept, the others are still processed, and IncompletePublication reports the first failure. +inline void recoverLocked(const std::filesystem::path& root, const StepHook& hook) { + std::filesystem::path directory; + try { + directory = projectPath(root, journalDirectory); + } catch (const std::exception&) { + return; + } + std::error_code error; + if (!std::filesystem::is_directory(directory, error)) + return; + std::vector found; + for (const auto& entry : std::filesystem::directory_iterator(directory, error)) + if (entry.path().filename() != lockName) + found.push_back(entry.path()); + if (error) + return; + std::ranges::sort(found); + std::set committed; + std::optional failure; + for (const auto& path : found) { + if (path.extension() != ".journal") + continue; + std::ostringstream content; + { + // Closed before rollForward() removes the journal: Windows cannot remove an open file. + std::ifstream stream(path, std::ios::binary); + content << stream.rdbuf(); + } + const auto entries = parseJournal(content.str()); + if (!entries) + continue; + try { + for (const auto& entry : *entries) + projectPath(root, entry.target); + } catch (const std::exception&) { + continue; + } + committed.insert(path.stem().string()); + try { + rollForward(root, directory, path.stem().string(), *entries, hook); + } catch (const InjectedFault&) { + throw; + } catch (const std::exception& exception) { + if (!failure) + failure = exception.what(); + } + } + for (const auto& path : found) { + const auto name = path.stem().string(); + if (!committed.contains(name)) + std::filesystem::remove_all(path, error); + } + if (failure) + throw IncompletePublication{*failure}; +} + +/// recoverLocked() for a caller that does not hold the project lock. +inline void recoverJournals(const std::filesystem::path& root, const StepHook& hook = {}) { + std::filesystem::path directory; + try { + directory = projectPath(root, journalDirectory); + } catch (const std::exception&) { + return; + } + std::error_code error; + if (!std::filesystem::is_directory(directory, error)) + return; + ProjectLock lock{directory / lockName}; + recoverLocked(root, hook); +} + +} // namespace webfront::developer diff --git a/include/webfront/system/DeveloperStore.hpp b/include/webfront/system/DeveloperStore.hpp index 56b8346c..380613c6 100644 --- a/include/webfront/system/DeveloperStore.hpp +++ b/include/webfront/system/DeveloperStore.hpp @@ -2,6 +2,7 @@ #pragma once #include "DeveloperFiles.hpp" +#include "DeveloperJournal.hpp" #include #include @@ -11,11 +12,21 @@ namespace webfront::developer { class Store { public: - explicit Store(std::filesystem::path project, std::chrono::steady_clock::duration abandoned = defaultAbandonedAfter) - : root(std::filesystem::canonical(project)), abandonedAfter(abandoned) { + /// Opening a project completes the group publications that reached their commit point before + /// the previous process stopped and abandons the others. A publication that cannot be completed + /// does not prevent opening the project: state() and commitGroup() retry it and report why it fails, + /// and recoveryFailure() describes it meanwhile. The hook is for tests only. + explicit Store(std::filesystem::path project, std::chrono::steady_clock::duration abandoned = defaultAbandonedAfter, + StepHook stepHook = {}) + : root(std::filesystem::canonical(project)), abandonedAfter(abandoned), hook(std::move(stepHook)) { if (!std::filesystem::is_directory(root)) throw std::invalid_argument("Developer project must be a directory"); removeStaleStaging(root); + try { + recoverJournals(root, hook); + } catch (const IncompletePublication& incomplete) { + pendingRecovery = incomplete.what(); + } } Store(const Store&) = delete; Store& operator=(const Store&) = delete; @@ -99,6 +110,79 @@ class Store { transactions.erase(id); } + /// Identifies the current content of project files; see commitGroup(). A committed publication that is + /// not applied yet is completed first; while it cannot be, this throws IncompletePublication. + std::string state(const std::vector& paths) { + std::scoped_lock lock(mutex); + recover(); + return fingerprint(root, paths); + } + + /// Why a committed publication could not be completed, if it still cannot. + std::optional recoveryFailure() const { + std::scoped_lock lock(mutex); + return pendingRecovery; + } + + /// Publishes several staged files as one change. The change is applied only if the files named by + /// `paths` (which include every destination) still have the content identified by `expected`, as + /// read by state() when the operation began; otherwise nothing changes and the caller runs again. + /// + /// The commit point is the journal, completely written and synchronized after the files are + /// staged and before the first replacement. A failure before it returns the files to their + /// transactions, which the caller may commit again or abort; a crash before it leaves the previous + /// files. After it, the publication happens: if a replacement fails, this throws + /// IncompletePublication and the next state(), commitGroup() or opening of the project completes it. + void commitGroup(const std::vector& ids, const std::vector& paths, const std::string& expected) { + std::scoped_lock lock(mutex); + const auto directory = projectPath(root, journalDirectory); + // Before the commit point: the journal directory must itself survive a power cut. + createDirectoriesDurably(root, directory); + // From here to the end, no other process recovers, checks the precondition or publishes. + ProjectLock processLock{directory / lockName}; + recoverHoldingLock(); + auto group = checkedGroup(ids, paths); + if (fingerprint(root, paths) != expected) + throw std::runtime_error("The project changed since it was read; run the command again"); + const auto number = prepareJournal(directory, group); + try { + writeJournal(directory, number, group); + } catch (const InjectedFault&) { + throw; + } catch (...) { + std::error_code ignored; + std::filesystem::remove(directory / (number + ".tmp"), ignored); + std::filesystem::remove(directory / (number + ".journal"), ignored); + returnStaged(directory / (number + ".d"), group); + throw; + } + std::vector entries; + for (std::size_t i = 0; i < group.size(); ++i) + entries.push_back({group[i]->destination, std::to_string(i)}); + for (const auto& id : ids) { + std::error_code ignored; + std::filesystem::remove_all(transactions.at(id).staging, ignored); + transactions.erase(id); + } + try { + rollForward(root, directory, number, entries, hook); + } catch (const InjectedFault&) { + throw; + } catch (const std::exception& exception) { + IncompletePublication incomplete{exception.what()}; + pendingRecovery = incomplete.what(); + throw incomplete; + } + } + + /// Bridge forms of state() and commitGroup(): one path or identifier per line. + std::string stateOfLines(std::string paths) { + return state(lines(paths)); + } + void commitGroupLines(std::string ids, std::string paths, std::string expected) { + commitGroup(lines(ids), lines(paths), expected); + } + void abort(std::string id) { std::scoped_lock lock(mutex); const auto found = transactions.find(id); @@ -109,6 +193,115 @@ class Store { } private: + static std::vector lines(const std::string& text) { + std::vector result; + std::istringstream stream{text}; + for (std::string line; std::getline(stream, line);) + if (!line.empty()) + result.push_back(std::move(line)); + return result; + } + + struct Transaction; + // The transactions of a group: single files, distinct, each destination covered by the precondition. + std::vector checkedGroup(const std::vector& ids, const std::vector& paths) { + if (ids.empty() || ids.size() > maxGroupFiles || paths.empty() || paths.size() > maxGroupFiles * 2) + throw std::invalid_argument("Invalid group publication"); + std::vector group; + for (const auto& id : ids) { + auto& tx = transaction(id); + if (std::ranges::find(group, &tx) != group.end() || tx.directory) + throw std::invalid_argument("A group publishes distinct single files"); + if (std::ranges::find(paths, tx.destination) == paths.end()) + throw std::invalid_argument("A group precondition must cover every destination"); + if (projectPath(root, tx.destination) != tx.target) + throw std::runtime_error("Project path changed"); + if (!tx.replace && std::filesystem::exists(std::filesystem::symlink_status(tx.target))) + throw std::runtime_error("Starter destination already exists"); + stagedSource(tx); + group.push_back(&tx); + } + return group; + } + + // Moves the staged files into a directory owned by the journal and makes them durable. + std::string prepareJournal(const std::filesystem::path& directory, const std::vector& group) { + for (;;) { + const auto number = std::to_string(++stagingCounter); + if (std::filesystem::exists(directory / (number + ".journal")) || std::filesystem::exists(directory / (number + ".tmp"))) + continue; + if (!std::filesystem::create_directory(directory / (number + ".d"))) + continue; + try { + for (std::size_t i = 0; i < group.size(); ++i) { + const auto owned = directory / (number + ".d") / std::to_string(i); + std::filesystem::rename(stagedSource(*group[i]), owned); + syncFile(owned); + } + syncDirectory(directory / (number + ".d")); + } catch (const InjectedFault&) { + throw; + } catch (...) { + returnStaged(directory / (number + ".d"), group); + throw; + } + return number; + } + } + + void writeJournal(const std::filesystem::path& directory, const std::string& number, const std::vector& group) { + std::vector entries; + for (std::size_t i = 0; i < group.size(); ++i) + entries.push_back({group[i]->destination, std::to_string(i)}); + step("before-journal"); + const auto temporary = directory / (number + ".tmp"); + { + std::ofstream file(temporary, std::ios::binary | std::ios::trunc); + const auto text = serializeJournal(entries); + file.write(text.data(), static_cast(text.size())); + file.close(); + if (!file) + throw std::runtime_error("Cannot write the publication journal"); + } + syncFile(temporary); + std::filesystem::rename(temporary, directory / (number + ".journal")); + syncDirectory(directory); + step("after-journal"); + } + + // Before the commit point: puts the files moved into a journal directory back in their transactions. + static void returnStaged(const std::filesystem::path& owned, const std::vector& group) { + std::error_code ignored; + for (std::size_t i = 0; i < group.size(); ++i) { + const auto moved = owned / std::to_string(i); + if (std::filesystem::is_regular_file(moved, ignored)) + std::filesystem::rename(moved, group[i]->staging / "output", ignored); + } + std::filesystem::remove_all(owned, ignored); + } + + // Completes the committed publications, recording why one cannot be completed. + template void recordRecovery(Recovery recovery) { + try { + recovery(root, hook); + pendingRecovery.reset(); + } catch (const IncompletePublication& incomplete) { + pendingRecovery = incomplete.what(); + throw; + } + } + void recover() { + recordRecovery(recoverJournals); + } + void recoverHoldingLock() { + recordRecovery(recoverLocked); + } + + void step(std::string_view name) const { + if (hook) + hook(name); + } + struct Transaction { std::filesystem::path staging; std::filesystem::path target; @@ -190,6 +383,8 @@ class Store { std::filesystem::path root; std::chrono::steady_clock::duration abandonedAfter; + StepHook hook; + std::optional pendingRecovery; mutable std::mutex mutex; std::map transactions; }; diff --git a/js/core/WebFrontAssets.cmake b/js/core/WebFrontAssets.cmake index 9441bc92..03dd8377 100644 --- a/js/core/WebFrontAssets.cmake +++ b/js/core/WebFrontAssets.cmake @@ -101,7 +101,8 @@ function(webfront_add_embedded_assets) if(ENABLE_TESTING) find_program(WEBFRONT_NODE_EXECUTABLE NAMES node nodejs REQUIRED) add_test(NAME DeveloperJavaScript COMMAND "${WEBFRONT_NODE_EXECUTABLE}" - --test "${root}/js/developer/tools/check.mjs" "${root}/js/developer/tools/distribution-check.mjs") + --test "${root}/js/developer/tools/check.mjs" "${root}/js/developer/tools/distribution-check.mjs" + "${root}/js/developer/tools/manifest-check.mjs") set_tests_properties(DeveloperJavaScript PROPERTIES TIMEOUT 30) add_test(NAME EmbeddedAssetGenerator COMMAND ${CMAKE_COMMAND} -E env "WEBFRONT_TEST_CMAKE=${CMAKE_COMMAND}" "${WEBFRONT_NODE_EXECUTABLE}" diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index d20d873d..71456a07 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -1,20 +1,24 @@ { + "js/developer/environment/manifest.mjs": "1cb0c70c87ca31ec81ad0591c0c1d1cb2637ecc491caef9c3d3ec8f1670ea900", + "js/developer/environment/project.mjs": "525bc1545f6ff9a70c744c536e46c2404bdc20daa83b25b29419222161003c3b", + "js/developer/environment/installer.mjs": "e02e047f591a539b04c519570902aa6166614958ac96b61e2aff4dc167d8c816", + "js/developer/environment/packages-entry.mjs": "7b5dc8aac408b741ccd3f9098165fca7645c4e88fd7ca7b8822fe37b7ad21fce", "js/developer/environment/bootstrap.mjs": "534af4b3d07891338c3390e1d5e06c2fb6dd8df11ca6547735565b17f1b9cd70", "js/developer/environment/bootstrap-entry.mjs": "ff8084f23f5acc721f97eb1ed0a454e7bfee1894de17d54f0100fa11f7ef8b77", "js/developer/environment/packages.mjs": "faed29500a34c6ce24756d07bd4b47b9168ccec4bd49d12f00096a869637d74d", - "js/developer/environment/starter.mjs": "f8cdef1218ae14f8bbe49eae495d931cc29e33f74444f0e37d61aea416b9d750", + "js/developer/environment/starter.mjs": "048cf2af36b407bc075323f78a1195b4be91ad7da51f6ce941d9fb230f314ff9", "js/developer/environment/paths.mjs": "6ebb626610756143c58762c87af18980802809d7f0f53d3b588e4b20e8db0161", - "js/developer/environment/runtime.mjs": "640896773c533ecc091a44384f0cac5115de346073c5393994073d7ff9d64c1b", + "js/developer/environment/runtime.mjs": "8c1eec7e111ac33ad40a33baa7722bcb2f0e5e3301981cc4c14e1d07771946aa", "js/developer/environment/compiler.mjs": "3f7e187ca9a4c2645ef3823127457cad655919cbea3c7c0f22fb7ae2cc87e0e5", "js/developer/environment/bundler.mjs": "b0ff79a1b0caa012c25ec7b7f121d7d50af1aa1651231d3dcf2f39470c4ea25c", "js/developer/environment/entry.mjs": "b2b942443e3c74ae2c008392ba244d9b7e91db70ba1b4ebbe1357c455ebf51bb", "js/developer/environment/conditions.mjs": "7f0ecba239480831e38985ccffd4c82309949924f4eb9d938e4ad1b09f5f36ed", - "js/developer/environment/io.mjs": "a155719c612e065c30272c0dfdc456df28b5efa90ca26f8cfcb55c9cb46de690", - "js/developer/environment/recipe.mjs": "809f2091c50ebd13d23f92de9876b584658dc687324f73d48ee9f1271319f1ed", + "js/developer/environment/io.mjs": "21af39f07c7eb863908c1df768e3c31de1c6eb8ff757c2a287c4a47c76855db6", + "js/developer/environment/recipe.mjs": "5e7b80cb9090dce63fafafbb852879fce9f6ed2399ac364bbe5af1cf6f4c1758", "js/developer/environment/registry.mjs": "f566f07ea066155ab7209d925cee2cf12a664ac51b07bc0ca3e3fd8fde49a9c8", "js/developer/environment/archive.mjs": "1fb8b9c3c27219858597801104639bba1104c7a7d33973609cd556b5e5f81d2d", "js/developer/environment/lock.mjs": "60d0ea14d24793cd5e85bbd4bb4bfe90d2c7d76c0d20ffc99f462595a6e57291", - "js/developer/environment/pins.mjs": "ddb2214a2e906cb117dc1bac0b5b056decd4f6c6e3d4713615176c1876db3534", + "js/developer/environment/pins.mjs": "df07f6f01edaf86a1052d0e76f6c6745cb6e7a3309bbd256ac720ee8adc85297", "js/developer/environment/peers.mjs": "e1d999892138682fc0134ef1f4d4b19b9a9ad8d7fb16e37fc9c6c684bd853896", "js/developer/environment/resolve.mjs": "8b96b850af215be51f5cb85cc9c69e057afa04dfb8a57e572620c07059c17fa3", "js/developer/environment/embed.mjs": "c370fd05b1629d630a3d504f65f6411df3a73c0f6deabf484654bddae52857a2", @@ -23,12 +27,12 @@ "examples/life/ui/main.tsx": "ed11a82aad1639eb6997af8b0fca4d5c5ed4c36422c22a74ac49ae73078d0a91", "examples/life/ui/style.css": "9bb55eb0f0a3287e5b7dc78af9d69608b87ff42c4d9c8a653bc83a52fe293c44", "js/developer/components/tools/wf.mjs": "2a8b463b2da223deb8d54d9fdd6037fdd079afeb24e39337693df03cdbcbd0ec", - "js/developer/tools/distribution.json": "26bb7dba24546565e38071087ab088727ad2b51fbbdb37afe801a574aff53fb6", - "js/developer/tools/build.mjs": "30999e2a9209966deb2cd486c786ce27d464a93882cca5b272b530837d46b3dd", + "js/developer/tools/distribution.json": "12b40657d1bc34c4093cd5f793d772bf3fa6fd8615ab7b766ad1756092438f83", + "js/developer/tools/build.mjs": "70ae5acdcd08dcde777c042d1b27f384746530ba97f89a81a91d04c5bd4c8e66", "js/developer/tools/site.mjs": "1827d3fd7e1e470336aab25ea8686c912c2b674a10f7be496f2f0077fbc45292", "js/developer/tools/archive.mjs": "bfe9feeb5e4d4e1b7c44c4dec4dcbeab4ae59c2bf16a1d2b32cd6910a2b84e7b", "js/developer/vendor/package-lock.json": "eb545112b672f9dbf520125df1f44a878d62cc8e611f0e33baee36470ded4dec", "js/core/bootstrap/bootstrap.bundle.mjs": "792fe7cf564bd12ac47fef419d8c71e2070925764a17706552e7d3f5d6ba2181", - "js/developer/environment/packages.bundle.mjs": "994c13a8b30a40ecea98414caa72a17927dcea81a1f62d47744b4f55d87005be", + "js/developer/environment/packages.bundle.mjs": "1bd773a901b747e2a38607171b49e7976af4792214c1e50fc7ed3710fed3bf22", "include/webfront/system/DeveloperReleaseData.hpp": "c97a8c3b21df3306c179f7b46d945159b5854f9d2810f135a4ab224c768c75d7" } diff --git a/js/developer/environment/installer.mjs b/js/developer/environment/installer.mjs new file mode 100644 index 00000000..78370ebb --- /dev/null +++ b/js/developer/environment/installer.mjs @@ -0,0 +1,154 @@ +// wf init and wf install: the manifest states the intent, the lock the exact resolution; both are published together. +import semver from 'semver'; +import {resolvePackages, downloadPackage} from './packages.mjs'; +import {parseSpec} from '../components/tools/wf.mjs'; +import {publish, readProject} from './io.mjs'; +import {manifestPath, newManifest, manifestName, serializeManifest, validateManifest, dependenciesDigest} from './manifest.mjs'; +import {loadProject, publishTogether, lockPath, packageRoot, noManifest, desynchronized, textBytes} from './project.mjs'; + +// The spec syntax resolvePackages() reads: a missing version is undefined, resolved as latest. +const splitSpec = spec => { + const {name, version} = parseSpec(spec); + return [name, version || undefined]; +}; + +// The range a manifest records for a root of a lock written before the manifest: the range it was installed with, +// or ^version for an exact version or a dist-tag, like npm. +function legacyRange(lock, root) { + const {version} = lock.packages[root.id]; + const exact = semver.valid(root.requested) !== null; + return !exact && root.requested !== 'latest' && semver.validRange(root.requested) !== null ? root.requested : `^${version}`; +} + +/** + * Creates webfront.project.json at the project root, without replacing an existing one. Every wf command reads that + * manifest. An existing lock gives the dependencies, so a project installed before the manifest keeps its locked graph. + */ +export async function initProject(bridge, [name, ...extra], {signal} = {}) { + if (extra.length) throw new Error('Usage: wf init [name]'); + const {lock} = await loadProject(bridge); + const manifest = newManifest(name ?? manifestName('')); + if (lock) manifest.dependencies = Object.fromEntries(Object.entries(lock.roots).map(([root, entry]) => [root, legacyRange(lock, entry)])); + validateManifest(manifest); + await publish(bridge, manifestPath, new Map([['output', textBytes(serializeManifest(manifest))]]), {directory: false, replace: false, signal}); + const adopted = lock ? ` with the ${Object.keys(manifest.dependencies).length} dependencies of ${lockPath}` : ''; + return `Created ${manifestPath}${adopted}. Add libraries with wf install .`; +} + +// The ranges to resolve: the manifest's, with the requested packages added or replaced. They are checked like the manifest +// that will record them before anything is resolved, so a range the manifest cannot hold is refused instead of written. +function requestedDependencies(project, specs) { + const dependencies = {...project.manifest.dependencies}; + const explicit = new Set(); + for (const spec of specs) { + const [name, range] = splitSpec(spec); + dependencies[name] = range ?? 'latest'; + if (range && range !== 'latest') explicit.add(name); + } + validateManifest({...project.source, dependencies}); + return {dependencies, explicit}; +} + +// The manifest as written with new dependencies: the defaults added by validation are not written back. +function updatedManifest(project, dependencies) { + const manifest = {...project.source, dependencies}; + validateManifest(manifest); + return manifest; +} + +// A package installed without a range is recorded as ^version, like npm; an explicit range is kept as typed. +function recordedDependencies({dependencies, explicit}, lock, specs) { + const recorded = {...dependencies}; + for (const spec of specs) { + const name = splitSpec(spec)[0]; + if (!explicit.has(name)) recorded[name] = `^${lock.packages[lock.roots[name].id].version}`; + } + return recorded; +} + +async function resolveLock(dependencies, previous, options) { + const roots = Object.entries(dependencies).map(([name, range]) => `${name}@${range}`); + const {lock, downloads} = await resolvePackages(roots, { + registry: options.registry, signal: options.signal, fetchImpl: options.fetchImpl, previous, + download: async (...args) => { options.progress(`Resolving ${args[0]}@${args[1]}`); return downloadPackage(...args); }, + }); + return {lock, downloads}; +} + +async function storePackages(bridge, lock, downloads, {signal, progress}) { + for (const [id, files] of downloads) { + progress(`Storing ${id}`); + await publish(bridge, `${packageRoot}/${lock.packages[id].key}`, files, {signal}); + } +} + +async function isCached(bridge, node) { + try { await readProject(bridge, `${packageRoot}/${node.key}/package.json`); return true; } + catch { return false; } +} + +// npm ci: exactly the locked graph, every archive checked against the recorded integrity. Nothing is resolved or written +// besides the cache. +async function restoreLocked(bridge, lock, {signal, progress, fetchImpl}) { + let restored = 0; + for (const [id, node] of Object.entries(lock.packages)) { + signal?.throwIfAborted(); + if (await isCached(bridge, node)) continue; + progress(`Restoring ${id}`); + const pkg = await downloadPackage(node.name, node.version, {registry: lock.registry, fetchImpl, signal}); + if (pkg.integrity !== node.integrity) throw new Error(`${id} no longer matches the integrity recorded in the lock`); + await publish(bridge, `${packageRoot}/${node.key}`, pkg.files, {signal}); + restored++; + } + return restored; +} + +function parseOptions(args) { + const update = args.includes('--update'); + const specs = args.filter(arg => arg !== '--update'); + if (specs.some(spec => spec.startsWith('-'))) throw new Error('Usage: wf install [--update] [[@range] ...]'); + return {update, specs}; +} + +async function publishResolution(bridge, project, {manifest, lock}, options) { + const files = new Map([[lockPath, textBytes(JSON.stringify(lock, null, 2) + '\n')]]); + if (manifest) files.set(manifestPath, textBytes(serializeManifest(manifest))); + await publishTogether(bridge, files, project, options); +} + +const withDigest = async (lock, dependencies) => ({format: lock.format, manifestDigest: await dependenciesDigest(dependencies), ...lock}); + +/** + * wf install [@range]: resolve, download and verify, then publish manifest and lock in one change. + * wf install: the locked graph exactly when the lock agrees with the manifest; resolves it when there is no lock. + * wf install --update: resolves the manifest again, keeping nothing from the lock. + */ +export async function install(bridge, args, {registry, signal, progress = () => {}, fetchImpl = fetch}) { + const {update, specs} = parseOptions(args); + const project = await loadProject(bridge); + if (!project.manifest) throw new Error(noManifest); + const options = {registry: project.manifest.registry ?? registry, signal, fetchImpl, progress}; + if (specs.length && update) throw new Error('Usage: wf install --update does not take packages'); + if (specs.length && project.status === 'desynchronized') throw new Error(desynchronized); + if (!specs.length && !update && project.status === 'desynchronized') throw new Error(desynchronized); + const locked = project.status === 'consistent' || project.status === 'legacy'; + if (!specs.length && !update && locked) { + const restored = await restoreLocked(bridge, project.lock, {signal, progress, fetchImpl: options.fetchImpl}); + if (project.status === 'consistent') return {lock: project.lock, restored}; + // A lock written before the manifest: the same graph, now recording the dependencies it was resolved from. + const lock = await withDigest(project.lock, project.manifest.dependencies); + await publishResolution(bridge, project, {manifest: null, lock}, {signal}); + return {lock, restored}; + } + const request = requestedDependencies(project, specs); + // --update ignores the locked versions; installing a package keeps the others where they are. + const previous = locked && !update ? project.lock : undefined; + const resolved = await resolveLock(request.dependencies, previous, options); + const dependencies = recordedDependencies(request, resolved.lock, specs); + await storePackages(bridge, resolved.lock, resolved.downloads, {signal, progress}); + // The journal of the joint publication is the installation commit point. A failed install may leave unused cache files. + const lock = await withDigest(resolved.lock, dependencies); + const manifest = specs.length ? updatedManifest(project, dependencies) : null; + await publishResolution(bridge, project, {manifest, lock}, {signal}); + return {lock, restored: 0}; +} diff --git a/js/developer/environment/io.mjs b/js/developer/environment/io.mjs index d0525b10..1240c684 100644 --- a/js/developer/environment/io.mjs +++ b/js/developer/environment/io.mjs @@ -15,7 +15,7 @@ export async function readProject(bridge, path) { return new Uint8Array(await new Blob(chunks).arrayBuffer()); } -async function writeChunks(bridge, {id, path, bytes}, signal) { +export async function writeChunks(bridge, {id, path, bytes}, signal) { for (let offset = 0; offset < bytes.length || offset === 0; offset += blockSize) { signal?.throwIfAborted(); await call(bridge, 'write', id, path, offset, bytes.subarray(offset, offset + blockSize)); diff --git a/js/developer/environment/manifest.mjs b/js/developer/environment/manifest.mjs new file mode 100644 index 00000000..6fb4eae7 --- /dev/null +++ b/js/developer/environment/manifest.mjs @@ -0,0 +1,182 @@ +// webfront.project.json, the project manifest every wf command reads: intent (roots and ranges), entries, +// providers and permissions. The lock records the exact resolution. +import {safePackagePath} from './paths.mjs'; +import {isPlainObject} from './entry.mjs'; + +export const manifestPath = 'webfront.project.json'; +export const manifestFormat = 1; + +const npmName = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/; +const exactVersion = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; +// The shape of an npm range or dist-tag; the registry resolution applies the semver semantics. +const rangeShape = /^[0-9A-Za-z.+\-^~<>=*| ]{1,128}$/; +const label = /^[A-Za-z0-9][A-Za-z0-9:_.-]{0,63}$/; +const identifier = /^[A-Za-z_][A-Za-z0-9_]*$/; +const keys = ['format', 'name', 'version', 'dependencies', 'registry', 'scripts', 'entries', 'providers', 'test', 'permissions']; +const permissionKeys = ['files', 'publish', 'fetch']; + +const fail = message => { throw new Error(`${manifestPath}: ${message}`); }; + +function requireObject(value, where) { + if (!isPlainObject(value)) fail(`${where} must be an object`); + return value; +} + +function onlyKeys(object, allowed, where) { + for (const key of Object.keys(object)) + if (!allowed.includes(key)) fail(`unknown key "${key}" in ${where}`); +} + +function projectPath(value, where) { + if (typeof value !== 'string') fail(`${where} must be a project path`); + try { return safePackagePath(value); } catch { return fail(`${where} is not a safe project-relative path: ${value}`); } +} + +function pathList(value, where) { + if (!Array.isArray(value) || value.length > 256) fail(`${where} must be an array of at most 256 paths`); + return value.map((path, index) => projectPath(path, `${where}[${index}]`)); +} + +function checkDependencies(value) { + const dependencies = requireObject(value, 'dependencies'); + for (const [name, range] of Object.entries(dependencies)) { + if (!npmName.test(name)) fail(`invalid npm package name "${name}"`); + if (typeof range !== 'string' || !rangeShape.test(range) || range !== range.trim()) + fail(`invalid version range for "${name}"`); + } + return dependencies; +} + +function checkRegistry(value) { + if (typeof value !== 'string') fail('registry must be a URL'); + if (value.startsWith('/') && !value.startsWith('//')) return value; + let url; + try { url = new URL(value); } catch { return fail('registry must be an https URL or an absolute path'); } + if (url.protocol !== 'https:') fail('registry must use https'); + return value; +} + +function checkScripts(value) { + const scripts = requireObject(value, 'scripts'); + for (const [name, command] of Object.entries(scripts)) + if (!label.test(name) || typeof command !== 'string' || !command || command.length > 1024) fail(`invalid script "${name}"`); + return scripts; +} + +function checkEntries(value) { + const entries = requireObject(value, 'entries'); + for (const [name, path] of Object.entries(entries)) { + if (!label.test(name)) fail(`invalid entry name "${name}"`); + projectPath(path, `entries.${name}`); + } + return entries; +} + +function checkProviders(value, entries) { + const providers = requireObject(value, 'providers'); + for (const [name, provider] of Object.entries(providers)) { + if (!identifier.test(name)) fail(`invalid provider name "${name}"`); + requireObject(provider, `providers.${name}`); + onlyKeys(provider, ['entry', 'output'], `providers.${name}`); + if (typeof provider.entry !== 'string') fail(`providers.${name}.entry must name an entry or a path`); + if (!Object.hasOwn(entries, provider.entry)) projectPath(provider.entry, `providers.${name}.entry`); + if (!projectPath(provider.output, `providers.${name}.output`).endsWith('.hpp')) fail(`providers.${name}.output must be a .hpp file`); + } + return providers; +} + +function checkTest(value) { + const test = requireObject(value, 'test'); + onlyKeys(test, ['specs'], 'test'); + if (test.specs !== undefined) pathList(test.specs, 'test.specs'); + return test; +} + +function checkOrigin(origin, where) { + let url; + try { url = new URL(origin); } catch { return fail(`${where} must be an https origin`); } + if (url.protocol !== 'https:' || url.origin !== origin) fail(`${where} must be an https origin without a path`); + return origin; +} + +function checkPermissions(value) { + const permissions = requireObject(value, 'permissions'); + for (const key of Object.keys(permissions)) + if (!permissionKeys.includes(key)) fail(`unknown permission "${key}"`); + for (const key of ['files', 'publish']) + if (permissions[key] !== undefined) pathList(permissions[key], `permissions.${key}`); + if (permissions.fetch !== undefined) { + if (!Array.isArray(permissions.fetch) || permissions.fetch.length > 64) fail('permissions.fetch must be an array of origins'); + permissions.fetch.forEach((origin, index) => checkOrigin(origin, `permissions.fetch[${index}]`)); + } + return permissions; +} + +function checkIdentity(manifest) { + if (typeof manifest.name !== 'string' || !npmName.test(manifest.name)) fail('name must be a lower-case npm package name'); + if (typeof manifest.version !== 'string' || !exactVersion.test(manifest.version)) fail('version must be a semantic version'); +} + +function checkFormat(manifest) { + if (manifest.format === manifestFormat) return; + if (Number.isInteger(manifest.format) && manifest.format > manifestFormat) + fail(`format ${manifest.format} is not supported by this environment (it reads format ${manifestFormat}); update the environment`); + fail(`format must be ${manifestFormat}`); +} + +/** Validates a parsed manifest; every problem is an explicit error, never a silent fallback. */ +export function validateManifest(manifest) { + requireObject(manifest, 'the manifest'); + checkFormat(manifest); + onlyKeys(manifest, keys, 'the manifest'); + checkIdentity(manifest); + const entries = manifest.entries === undefined ? {} : checkEntries(manifest.entries); + return { + ...manifest, + dependencies: manifest.dependencies === undefined ? {} : checkDependencies(manifest.dependencies), + entries, + providers: manifest.providers === undefined ? {} : checkProviders(manifest.providers, entries), + ...(manifest.registry === undefined ? {} : {registry: checkRegistry(manifest.registry)}), + ...(manifest.scripts === undefined ? {} : {scripts: checkScripts(manifest.scripts)}), + ...(manifest.test === undefined ? {} : {test: checkTest(manifest.test)}), + ...(manifest.permissions === undefined ? {} : {permissions: checkPermissions(manifest.permissions)}), + }; +} + +/** The manifest as written (`source`, to update without adding the defaults) and validated (`manifest`). */ +export function readManifest(bytes) { + let source; + try { source = JSON.parse(new TextDecoder().decode(bytes)); } catch { return fail('not valid JSON'); } + return {source, manifest: validateManifest(source)}; +} + +export function parseManifest(bytes) { + return readManifest(bytes).manifest; +} + +/** The text written to disk: the schema's keys in a stable order. */ +export function serializeManifest(manifest) { + const ordered = {}; + for (const key of keys) if (manifest[key] !== undefined) ordered[key] = manifest[key]; + return JSON.stringify(ordered, null, 2) + '\n'; +} + +export function newManifest(name) { + return {format: manifestFormat, name, version: '0.1.0', dependencies: {}}; +} + +/** A package name derived from a directory name, for wf init. */ +export function manifestName(directory) { + const base = String(directory ?? '').split('/').filter(Boolean).pop() ?? ''; + const name = base.toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[^a-z0-9]+/, '').replace(/-+$/, ''); + return npmName.test(name) ? name : 'webfront-app'; +} + +/** Fingerprint of the manifest's dependency intent, recorded by the lock it produced. */ +export async function dependenciesDigest(dependencies) { + const canonical = JSON.stringify(Object.entries(dependencies).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)); + const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(canonical)); + return [...new Uint8Array(digest)].map(byte => byte.toString(16).padStart(2, '0')).join(''); +} + +export {exactVersion, npmName, identifier}; diff --git a/js/developer/environment/packages-entry.mjs b/js/developer/environment/packages-entry.mjs new file mode 100644 index 00000000..933bbd76 --- /dev/null +++ b/js/developer/environment/packages-entry.mjs @@ -0,0 +1,5 @@ +// Entry of packages.bundle.mjs: the dependency, manifest and installation logic the Node tests run against. +export * from './packages.mjs'; +export * from './manifest.mjs'; +export * from './project.mjs'; +export * from './installer.mjs'; diff --git a/js/developer/environment/packages.bundle.mjs b/js/developer/environment/packages.bundle.mjs index 84e43c3f..e3243dfe 100644 --- a/js/developer/environment/packages.bundle.mjs +++ b/js/developer/environment/packages.bundle.mjs @@ -1 +1,7 @@ -var Tt=Object.create;var Le=Object.defineProperty;var vt=Object.getOwnPropertyDescriptor;var At=Object.getOwnPropertyNames;var xt=Object.getPrototypeOf,qt=Object.prototype.hasOwnProperty;var m=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var bt=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of At(e))!qt.call(r,n)&&n!==t&&Le(r,n,{get:()=>e[n],enumerable:!(s=vt(e,n))||s.enumerable});return r};var F=(r,e,t)=>(t=r!=null?Tt(xt(r)):{},bt(e||!r||!r.__esModule?Le(t,"default",{value:r,enumerable:!0}):t,r));var A=m((co,xe)=>{"use strict";var Ft="2.0.0",Ut=Number.MAX_SAFE_INTEGER||9007199254740991,Gt=16,Xt=250,Vt=["major","premajor","minor","preminor","patch","prepatch","prerelease"];xe.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Gt,MAX_SAFE_BUILD_LENGTH:Xt,MAX_SAFE_INTEGER:Ut,RELEASE_TYPES:Vt,SEMVER_SPEC_VERSION:Ft,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var x=m((lo,qe)=>{"use strict";var zt=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};qe.exports=zt});var T=m((N,be)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:re,MAX_SAFE_BUILD_LENGTH:_t,MAX_LENGTH:Ht}=A(),Bt=x();N=be.exports={};var Mt=N.re=[],Wt=N.safeRe=[],l=N.src=[],Yt=N.safeSrc=[],u=N.t={},Jt=0,te="[a-zA-Z0-9-]",Kt=[["\\s",1],["\\d",Ht],[te,_t]],Zt=r=>{for(let[e,t]of Kt)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},d=(r,e,t)=>{let s=Zt(e),n=Jt++;Bt(r,n,e),u[r]=n,l[n]=e,Yt[n]=s,Mt[n]=new RegExp(e,t?"g":void 0),Wt[n]=new RegExp(s,t?"g":void 0)};d("NUMERICIDENTIFIER","0|[1-9]\\d*");d("NUMERICIDENTIFIERLOOSE","\\d+");d("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${te}*`);d("MAINVERSION",`(${l[u.NUMERICIDENTIFIER]})\\.(${l[u.NUMERICIDENTIFIER]})\\.(${l[u.NUMERICIDENTIFIER]})`);d("MAINVERSIONLOOSE",`(${l[u.NUMERICIDENTIFIERLOOSE]})\\.(${l[u.NUMERICIDENTIFIERLOOSE]})\\.(${l[u.NUMERICIDENTIFIERLOOSE]})`);d("PRERELEASEIDENTIFIER",`(?:${l[u.NONNUMERICIDENTIFIER]}|${l[u.NUMERICIDENTIFIER]})`);d("PRERELEASEIDENTIFIERLOOSE",`(?:${l[u.NONNUMERICIDENTIFIER]}|${l[u.NUMERICIDENTIFIERLOOSE]})`);d("PRERELEASE",`(?:-(${l[u.PRERELEASEIDENTIFIER]}(?:\\.${l[u.PRERELEASEIDENTIFIER]})*))`);d("PRERELEASELOOSE",`(?:-?(${l[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${l[u.PRERELEASEIDENTIFIERLOOSE]})*))`);d("BUILDIDENTIFIER",`${te}+`);d("BUILD",`(?:\\+(${l[u.BUILDIDENTIFIER]}(?:\\.${l[u.BUILDIDENTIFIER]})*))`);d("FULLPLAIN",`v?${l[u.MAINVERSION]}${l[u.PRERELEASE]}?${l[u.BUILD]}?`);d("FULL",`^${l[u.FULLPLAIN]}$`);d("LOOSEPLAIN",`[v=\\s]*${l[u.MAINVERSIONLOOSE]}${l[u.PRERELEASELOOSE]}?${l[u.BUILD]}?`);d("LOOSE",`^${l[u.LOOSEPLAIN]}$`);d("GTLT","((?:<|>)?=?)");d("XRANGEIDENTIFIERLOOSE",`${l[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);d("XRANGEIDENTIFIER",`${l[u.NUMERICIDENTIFIER]}|x|X|\\*`);d("XRANGEPLAIN",`[v=\\s]*(${l[u.XRANGEIDENTIFIER]})(?:\\.(${l[u.XRANGEIDENTIFIER]})(?:\\.(${l[u.XRANGEIDENTIFIER]})(?:${l[u.PRERELEASE]})?${l[u.BUILD]}?)?)?`);d("XRANGEPLAINLOOSE",`[v=\\s]*(${l[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[u.XRANGEIDENTIFIERLOOSE]})(?:${l[u.PRERELEASELOOSE]})?${l[u.BUILD]}?)?)?`);d("XRANGE",`^${l[u.GTLT]}\\s*${l[u.XRANGEPLAIN]}$`);d("XRANGELOOSE",`^${l[u.GTLT]}\\s*${l[u.XRANGEPLAINLOOSE]}$`);d("COERCEPLAIN",`(^|[^\\d])(\\d{1,${re}})(?:\\.(\\d{1,${re}}))?(?:\\.(\\d{1,${re}}))?`);d("COERCE",`${l[u.COERCEPLAIN]}(?:$|[^\\d])`);d("COERCEFULL",l[u.COERCEPLAIN]+`(?:${l[u.PRERELEASE]})?(?:${l[u.BUILD]})?(?:$|[^\\d])`);d("COERCERTL",l[u.COERCE],!0);d("COERCERTLFULL",l[u.COERCEFULL],!0);d("LONETILDE","(?:~>?)");d("TILDETRIM",`(\\s*)${l[u.LONETILDE]}\\s+`,!0);N.tildeTrimReplace="$1~";d("TILDE",`^${l[u.LONETILDE]}${l[u.XRANGEPLAIN]}$`);d("TILDELOOSE",`^${l[u.LONETILDE]}${l[u.XRANGEPLAINLOOSE]}$`);d("LONECARET","(?:\\^)");d("CARETTRIM",`(\\s*)${l[u.LONECARET]}\\s+`,!0);N.caretTrimReplace="$1^";d("CARET",`^${l[u.LONECARET]}${l[u.XRANGEPLAIN]}$`);d("CARETLOOSE",`^${l[u.LONECARET]}${l[u.XRANGEPLAINLOOSE]}$`);d("COMPARATORLOOSE",`^${l[u.GTLT]}\\s*(${l[u.LOOSEPLAIN]})$|^$`);d("COMPARATOR",`^${l[u.GTLT]}\\s*(${l[u.FULLPLAIN]})$|^$`);d("COMPARATORTRIM",`(\\s*)${l[u.GTLT]}\\s*(${l[u.LOOSEPLAIN]}|${l[u.XRANGEPLAIN]})`,!0);N.comparatorTrimReplace="$1$2$3";d("HYPHENRANGE",`^\\s*(${l[u.XRANGEPLAIN]})\\s+-\\s+(${l[u.XRANGEPLAIN]})\\s*$`);d("HYPHENRANGELOOSE",`^\\s*(${l[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${l[u.XRANGEPLAINLOOSE]})\\s*$`);d("STAR","(<|>)?=?\\s*\\*");d("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");d("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var U=m((uo,Pe)=>{"use strict";var Qt=Object.freeze({loose:!0}),es=Object.freeze({}),rs=r=>r?typeof r!="object"?Qt:r:es;Pe.exports=rs});var se=m((fo,De)=>{"use strict";var ke=/^[0-9]+$/,Ce=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:rCe(e,r);De.exports={compareIdentifiers:Ce,rcompareIdentifiers:ts}});var g=m((ho,Fe)=>{"use strict";var G=x(),{MAX_LENGTH:je,MAX_SAFE_INTEGER:X}=A(),{safeRe:V,t:z}=T(),ss=U(),{compareIdentifiers:ne}=se(),ie=class r{constructor(e,t){if(t=ss(t),e instanceof r){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>je)throw new TypeError(`version is longer than ${je} characters`);G("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let s=e.trim().match(t.loose?V[z.LOOSE]:V[z.FULL]);if(!s)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+s[1],this.minor=+s[2],this.patch=+s[3],this.major>X||this.major<0)throw new TypeError("Invalid major version");if(this.minor>X||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>X||this.patch<0)throw new TypeError("Invalid patch version");s[4]?this.prerelease=s[4].split(".").map(n=>{if(/^[0-9]+$/.test(n)){let i=+n;if(i>=0&&ie.major?1:this.minore.minor?1:this.patche.patch?1:0}comparePre(e){if(e instanceof r||(e=new r(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let s=this.prerelease[t],n=e.prerelease[t];if(G("prerelease compare",t,s,n),s===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(s===void 0)return-1;if(s===n)continue;return ne(s,n)}while(++t)}compareBuild(e){e instanceof r||(e=new r(e,this.options));let t=0;do{let s=this.build[t],n=e.build[t];if(G("build compare",t,s,n),s===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(s===void 0)return-1;if(s===n)continue;return ne(s,n)}while(++t)}inc(e,t,s){if(e.startsWith("pre")){if(!t&&s===!1)throw new Error("invalid increment argument: identifier is empty");if(t){let n=`-${t}`.match(this.options.loose?V[z.PRERELEASELOOSE]:V[z.PRERELEASE]);if(!n||n[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,s);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,s);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,s),this.inc("pre",t,s);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,s),this.inc("pre",t,s);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let n=Number(s)?1:0;if(this.prerelease.length===0)this.prerelease=[n];else{let i=this.prerelease.length;for(;--i>=0;)typeof this.prerelease[i]=="number"&&(this.prerelease[i]++,i=-2);if(i===-1){if(t===this.prerelease.join(".")&&s===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(n)}}if(t){let i=[t,n];s===!1&&(i=[t]),ne(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=i):this.prerelease=i}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Fe.exports=ie});var S=m((po,Ge)=>{"use strict";var Ue=g(),ns=(r,e,t=!1)=>{if(r instanceof Ue)return r;try{return new Ue(r,e)}catch(s){if(!t)return null;throw s}};Ge.exports=ns});var Ve=m((Eo,Xe)=>{"use strict";var is=S(),os=(r,e)=>{let t=is(r,e);return t?t.version:null};Xe.exports=os});var _e=m((mo,ze)=>{"use strict";var as=S(),cs=(r,e)=>{let t=as(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};ze.exports=cs});var Me=m((wo,Be)=>{"use strict";var He=g(),ls=(r,e,t,s,n)=>{typeof t=="string"&&(n=s,s=t,t=void 0);try{return new He(r instanceof He?r.version:r,t).inc(e,s,n).version}catch{return null}};Be.exports=ls});var Je=m(($o,Ye)=>{"use strict";var We=S(),us=(r,e)=>{let t=We(r,null,!0),s=We(e,null,!0),n=t.compare(s);if(n===0)return null;let i=n>0,o=i?t:s,a=i?s:t,c=!!o.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(o)===0)return a.minor&&!a.patch?"minor":"patch"}let p=c?"pre":"";return t.major!==s.major?p+"major":t.minor!==s.minor?p+"minor":t.patch!==s.patch?p+"patch":"prerelease"};Ye.exports=us});var Ze=m((go,Ke)=>{"use strict";var fs=g(),hs=(r,e)=>new fs(r,e).major;Ke.exports=hs});var er=m((Ro,Qe)=>{"use strict";var ps=g(),Es=(r,e)=>new ps(r,e).minor;Qe.exports=Es});var tr=m((Io,rr)=>{"use strict";var ms=g(),ds=(r,e)=>new ms(r,e).patch;rr.exports=ds});var nr=m((yo,sr)=>{"use strict";var ws=S(),$s=(r,e)=>{let t=ws(r,e);return t&&t.prerelease.length?t.prerelease:null};sr.exports=$s});var L=m((Lo,or)=>{"use strict";var ir=g(),gs=(r,e,t)=>new ir(r,t).compare(new ir(e,t));or.exports=gs});var cr=m((Oo,ar)=>{"use strict";var Rs=L(),Is=(r,e,t)=>Rs(e,r,t);ar.exports=Is});var ur=m((No,lr)=>{"use strict";var ys=L(),Ls=(r,e)=>ys(r,e,!0);lr.exports=Ls});var _=m((So,hr)=>{"use strict";var fr=g(),Os=(r,e,t)=>{let s=new fr(r,t),n=new fr(e,t);return s.compare(n)||s.compareBuild(n)};hr.exports=Os});var Er=m((To,pr)=>{"use strict";var Ns=_(),Ss=(r,e)=>r.sort((t,s)=>Ns(t,s,e));pr.exports=Ss});var dr=m((vo,mr)=>{"use strict";var Ts=_(),vs=(r,e)=>r.sort((t,s)=>Ts(s,t,e));mr.exports=vs});var q=m((Ao,wr)=>{"use strict";var As=L(),xs=(r,e,t)=>As(r,e,t)>0;wr.exports=xs});var H=m((xo,$r)=>{"use strict";var qs=L(),bs=(r,e,t)=>qs(r,e,t)<0;$r.exports=bs});var oe=m((qo,gr)=>{"use strict";var Ps=L(),ks=(r,e,t)=>Ps(r,e,t)===0;gr.exports=ks});var ae=m((bo,Rr)=>{"use strict";var Cs=L(),Ds=(r,e,t)=>Cs(r,e,t)!==0;Rr.exports=Ds});var B=m((Po,Ir)=>{"use strict";var js=L(),Fs=(r,e,t)=>js(r,e,t)>=0;Ir.exports=Fs});var M=m((ko,yr)=>{"use strict";var Us=L(),Gs=(r,e,t)=>Us(r,e,t)<=0;yr.exports=Gs});var ce=m((Co,Lr)=>{"use strict";var Xs=oe(),Vs=ae(),zs=q(),_s=B(),Hs=H(),Bs=M(),Ms=(r,e,t,s)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return Xs(r,t,s);case"!=":return Vs(r,t,s);case">":return zs(r,t,s);case">=":return _s(r,t,s);case"<":return Hs(r,t,s);case"<=":return Bs(r,t,s);default:throw new TypeError(`Invalid operator: ${e}`)}};Lr.exports=Ms});var Nr=m((Do,Or)=>{"use strict";var Ws=g(),Ys=S(),{safeRe:W,t:Y}=T(),Js=(r,e)=>{if(r instanceof Ws)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?W[Y.COERCEFULL]:W[Y.COERCE]);else{let c=e.includePrerelease?W[Y.COERCERTLFULL]:W[Y.COERCERTL],f;for(;(f=c.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||f.index+f[0].length!==t.index+t[0].length)&&(t=f),c.lastIndex=f.index+f[1].length+f[2].length;c.lastIndex=-1}if(t===null)return null;let s=t[2],n=t[3]||"0",i=t[4]||"0",o=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return Ys(`${s}.${n}.${i}${o}${a}`,e)};Or.exports=Js});var Tr=m((jo,Sr)=>{"use strict";var le=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let n=this.map.keys().next().value;this.delete(n)}this.map.set(e,t)}return this}};Sr.exports=le});var O=m((Fo,qr)=>{"use strict";var Ks=/\s+/g,ue=class r{constructor(e,t){if(t=Qs(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof fe)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(Ks," "),this.set=this.raw.split("||").map(s=>this.parseRange(s.trim())).filter(s=>s.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let s=this.set[0];if(this.set=this.set.filter(n=>!Ar(n[0])),this.set.length===0)this.set=[s];else if(this.set.length>1){for(let n of this.set)if(n.length===1&&an(n[0])){this.set=[n];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e0&&(this.formatted+="||");let t=this.set[e];for(let s=0;s0&&(this.formatted+=" "),this.formatted+=t[s].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let s=((this.options.includePrerelease&&nn)|(this.options.loose&&on))+":"+e,n=vr.get(s);if(n)return n;let i=this.options.loose,o=i?I[R.HYPHENRANGELOOSE]:I[R.HYPHENRANGE];e=e.replace(o,wn(this.options.includePrerelease)),w("hyphen replace",e),e=e.replace(I[R.COMPARATORTRIM],rn),w("comparator trim",e),e=e.replace(I[R.TILDETRIM],tn),w("tilde trim",e),e=e.replace(I[R.CARETTRIM],sn),w("caret trim",e);let a=e.split(" ").map(h=>cn(h,this.options)).join(" ").split(/\s+/).map(h=>dn(h,this.options));i&&(a=a.filter(h=>(w("loose invalid filter",h,this.options),!!h.match(I[R.COMPARATORLOOSE])))),w("range list",a);let c=new Map,f=a.map(h=>new fe(h,this.options));for(let h of f){if(Ar(h))return[h];c.set(h.value,h)}c.size>1&&c.has("")&&c.delete("");let p=[...c.values()];return vr.set(s,p),p}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(s=>xr(s,t)&&e.set.some(n=>xr(n,t)&&s.every(i=>n.every(o=>i.intersects(o,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new en(e,this.options)}catch{return!1}for(let t=0;tr.value==="<0.0.0-0",an=r=>r.value==="",xr=(r,e)=>{let t=!0,s=r.slice(),n=s.pop();for(;t&&s.length;)t=s.every(i=>n.intersects(i,e)),n=s.pop();return t},cn=(r,e)=>(r=r.replace(I[R.BUILD],""),w("comp",r,e),r=fn(r,e),w("caret",r),r=ln(r,e),w("tildes",r),r=pn(r,e),w("xrange",r),r=mn(r,e),w("stars",r),r),y=r=>!r||r.toLowerCase()==="x"||r==="*",ln=(r,e)=>r.trim().split(/\s+/).map(t=>un(t,e)).join(" "),un=(r,e)=>{let t=e.loose?I[R.TILDELOOSE]:I[R.TILDE];return r.replace(t,(s,n,i,o,a)=>{w("tilde",r,s,n,i,o,a);let c;return y(n)?c="":y(i)?c=`>=${n}.0.0 <${+n+1}.0.0-0`:y(o)?c=`>=${n}.${i}.0 <${n}.${+i+1}.0-0`:a?(w("replaceTilde pr",a),c=`>=${n}.${i}.${o}-${a} <${n}.${+i+1}.0-0`):c=`>=${n}.${i}.${o} <${n}.${+i+1}.0-0`,w("tilde return",c),c})},fn=(r,e)=>r.trim().split(/\s+/).map(t=>hn(t,e)).join(" "),hn=(r,e)=>{w("caret",r,e);let t=e.loose?I[R.CARETLOOSE]:I[R.CARET],s=e.includePrerelease?"-0":"";return r.replace(t,(n,i,o,a,c)=>{w("caret",r,n,i,o,a,c);let f;return y(i)?f="":y(o)?f=`>=${i}.0.0${s} <${+i+1}.0.0-0`:y(a)?i==="0"?f=`>=${i}.${o}.0${s} <${i}.${+o+1}.0-0`:f=`>=${i}.${o}.0${s} <${+i+1}.0.0-0`:c?(w("replaceCaret pr",c),i==="0"?o==="0"?f=`>=${i}.${o}.${a}-${c} <${i}.${o}.${+a+1}-0`:f=`>=${i}.${o}.${a}-${c} <${i}.${+o+1}.0-0`:f=`>=${i}.${o}.${a}-${c} <${+i+1}.0.0-0`):(w("no pr"),i==="0"?o==="0"?f=`>=${i}.${o}.${a}${s} <${i}.${o}.${+a+1}-0`:f=`>=${i}.${o}.${a}${s} <${i}.${+o+1}.0-0`:f=`>=${i}.${o}.${a} <${+i+1}.0.0-0`),w("caret return",f),f})},pn=(r,e)=>(w("replaceXRanges",r,e),r.split(/\s+/).map(t=>En(t,e)).join(" ")),En=(r,e)=>{r=r.trim();let t=e.loose?I[R.XRANGELOOSE]:I[R.XRANGE];return r.replace(t,(s,n,i,o,a,c)=>{w("xRange",r,s,n,i,o,a,c);let f=y(i),p=f||y(o),h=p||y(a),$=h;return n==="="&&$&&(n=""),c=e.includePrerelease?"-0":"",f?n===">"||n==="<"?s="<0.0.0-0":s="*":n&&$?(p&&(o=0),a=0,n===">"?(n=">=",p?(i=+i+1,o=0,a=0):(o=+o+1,a=0)):n==="<="&&(n="<",p?i=+i+1:o=+o+1),n==="<"&&(c="-0"),s=`${n+i}.${o}.${a}${c}`):p?s=`>=${i}.0.0${c} <${+i+1}.0.0-0`:h&&(s=`>=${i}.${o}.0${c} <${i}.${+o+1}.0-0`),w("xRange return",s),s})},mn=(r,e)=>(w("replaceStars",r,e),r.trim().replace(I[R.STAR],"")),dn=(r,e)=>(w("replaceGTE0",r,e),r.trim().replace(I[e.includePrerelease?R.GTE0PRE:R.GTE0],"")),wn=r=>(e,t,s,n,i,o,a,c,f,p,h,$)=>(y(s)?t="":y(n)?t=`>=${s}.0.0${r?"-0":""}`:y(i)?t=`>=${s}.${n}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,y(f)?c="":y(p)?c=`<${+f+1}.0.0-0`:y(h)?c=`<${f}.${+p+1}.0-0`:$?c=`<=${f}.${p}.${h}-${$}`:r?c=`<${f}.${p}.${+h+1}-0`:c=`<=${c}`,`${t} ${c}`.trim()),$n=(r,e,t)=>{for(let s=0;s0){let n=r[s].semver;if(n.major===e.major&&n.minor===e.minor&&n.patch===e.patch)return!0}return!1}return!0}});var b=m((Uo,jr)=>{"use strict";var P=Symbol("SemVer ANY"),Ee=class r{static get ANY(){return P}constructor(e,t){if(t=br(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),pe("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===P?this.value="":this.value=this.operator+this.semver.version,pe("comp",this)}parse(e){let t=this.options.loose?Pr[kr.COMPARATORLOOSE]:Pr[kr.COMPARATOR],s=e.match(t);if(!s)throw new TypeError(`Invalid comparator: ${e}`);this.operator=s[1]!==void 0?s[1]:"",this.operator==="="&&(this.operator=""),s[2]?this.semver=new Cr(s[2],this.options.loose):this.semver=P}toString(){return this.value}test(e){if(pe("Comparator.test",e,this.options.loose),this.semver===P||e===P)return!0;if(typeof e=="string")try{e=new Cr(e,this.options)}catch{return!1}return he(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Dr(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Dr(this.value,t).test(e.semver):(t=br(t),t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||he(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||he(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};jr.exports=Ee;var br=U(),{safeRe:Pr,t:kr}=T(),he=ce(),pe=x(),Cr=g(),Dr=O()});var k=m((Go,Fr)=>{"use strict";var gn=O(),Rn=(r,e,t)=>{try{e=new gn(e,t)}catch{return!1}return e.test(r)};Fr.exports=Rn});var Gr=m((Xo,Ur)=>{"use strict";var In=O(),yn=(r,e)=>new In(r,e).set.map(t=>t.map(s=>s.value).join(" ").trim().split(" "));Ur.exports=yn});var Vr=m((Vo,Xr)=>{"use strict";var Ln=g(),On=O(),Nn=(r,e,t)=>{let s=null,n=null,i=null;try{i=new On(e,t)}catch{return null}return r.forEach(o=>{i.test(o)&&(!s||n.compare(o)===-1)&&(s=o,n=new Ln(s,t))}),s};Xr.exports=Nn});var _r=m((zo,zr)=>{"use strict";var Sn=g(),Tn=O(),vn=(r,e,t)=>{let s=null,n=null,i=null;try{i=new Tn(e,t)}catch{return null}return r.forEach(o=>{i.test(o)&&(!s||n.compare(o)===1)&&(s=o,n=new Sn(s,t))}),s};zr.exports=vn});var Mr=m((_o,Br)=>{"use strict";var me=g(),An=O(),Hr=q(),xn=(r,e)=>{r=new An(r,e);let t=new me("0.0.0");if(r.test(t)||(t=new me("0.0.0-0"),r.test(t)))return t;t=null;for(let s=0;s{let a=new me(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!i||Hr(a,i))&&(i=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),i&&(!t||Hr(t,i))&&(t=i)}return t&&r.test(t)?t:null};Br.exports=xn});var Yr=m((Ho,Wr)=>{"use strict";var qn=O(),bn=(r,e)=>{try{return new qn(r,e).range||"*"}catch{return null}};Wr.exports=bn});var J=m((Bo,Qr)=>{"use strict";var Pn=g(),Zr=b(),{ANY:kn}=Zr,Cn=O(),Dn=k(),Jr=q(),Kr=H(),jn=M(),Fn=B(),Un=(r,e,t,s)=>{r=new Pn(r,s),e=new Cn(e,s);let n,i,o,a,c;switch(t){case">":n=Jr,i=jn,o=Kr,a=">",c=">=";break;case"<":n=Kr,i=Fn,o=Jr,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Dn(r,e,s))return!1;for(let f=0;f{E.semver===kn&&(E=new Zr(">=0.0.0")),h=h||E,$=$||E,n(E.semver,h.semver,s)?h=E:o(E.semver,$.semver,s)&&($=E)}),h.operator===a||h.operator===c||(!$.operator||$.operator===a)&&i(r,$.semver))return!1;if($.operator===c&&o(r,$.semver))return!1}return!0};Qr.exports=Un});var rt=m((Mo,et)=>{"use strict";var Gn=J(),Xn=(r,e,t)=>Gn(r,e,">",t);et.exports=Xn});var st=m((Wo,tt)=>{"use strict";var Vn=J(),zn=(r,e,t)=>Vn(r,e,"<",t);tt.exports=zn});var ot=m((Yo,it)=>{"use strict";var nt=O(),_n=(r,e,t)=>(r=new nt(r,t),e=new nt(e,t),r.intersects(e,t));it.exports=_n});var ct=m((Jo,at)=>{"use strict";var Hn=k(),Bn=L();at.exports=(r,e,t)=>{let s=[],n=null,i=null,o=r.sort((p,h)=>Bn(p,h,t));for(let p of o)Hn(p,e,t)?(i=p,n||(n=p)):(i&&s.push([n,i]),i=null,n=null);n&&s.push([n,null]);let a=[];for(let[p,h]of s)p===h?a.push(p):!h&&p===o[0]?a.push("*"):h?p===o[0]?a.push(`<=${h}`):a.push(`${p} - ${h}`):a.push(`>=${p}`);let c=a.join(" || "),f=typeof e.raw=="string"?e.raw:String(e);return c.length{"use strict";var lt=O(),we=b(),{ANY:de}=we,C=k(),$e=L(),Mn=(r,e,t={})=>{if(r===e)return!0;r=new lt(r,t),e=new lt(e,t);let s=!1;e:for(let n of r.set){for(let i of e.set){let o=Yn(n,i,t);if(s=s||o!==null,o)continue e}if(s)return!1}return!0},Wn=[new we(">=0.0.0-0")],ut=[new we(">=0.0.0")],Yn=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===de){if(e.length===1&&e[0].semver===de)return!0;t.includePrerelease?r=Wn:r=ut}if(e.length===1&&e[0].semver===de){if(t.includePrerelease)return!0;e=ut}let s=new Set,n,i;for(let E of r)E.operator===">"||E.operator===">="?n=ft(n,E,t):E.operator==="<"||E.operator==="<="?i=ht(i,E,t):s.add(E.semver);if(s.size>1)return null;let o;if(n&&i){if(o=$e(n.semver,i.semver,t),o>0)return null;if(o===0&&(n.operator!==">="||i.operator!=="<="))return null}for(let E of s){if(n&&!C(E,String(n),t)||i&&!C(E,String(i),t))return null;for(let St of e)if(!C(E,String(St),t))return!1;return!0}let a,c,f,p,h=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1,$=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1;h&&h.prerelease.length===1&&i.operator==="<"&&h.prerelease[0]===0&&(h=!1);for(let E of e){if(p=p||E.operator===">"||E.operator===">=",f=f||E.operator==="<"||E.operator==="<=",n){if($&&E.semver.prerelease&&E.semver.prerelease.length&&E.semver.major===$.major&&E.semver.minor===$.minor&&E.semver.patch===$.patch&&($=!1),E.operator===">"||E.operator===">="){if(a=ft(n,E,t),a===E&&a!==n)return!1}else if(n.operator===">="&&!C(n.semver,String(E),t))return!1}if(i){if(h&&E.semver.prerelease&&E.semver.prerelease.length&&E.semver.major===h.major&&E.semver.minor===h.minor&&E.semver.patch===h.patch&&(h=!1),E.operator==="<"||E.operator==="<="){if(c=ht(i,E,t),c===E&&c!==i)return!1}else if(i.operator==="<="&&!C(i.semver,String(E),t))return!1}if(!E.operator&&(i||n)&&o!==0)return!1}return!(n&&f&&!i&&o!==0||i&&p&&!n&&o!==0||$||h)},ft=(r,e,t)=>{if(!r)return e;let s=$e(r.semver,e.semver,t);return s>0?r:s<0||e.operator===">"&&r.operator===">="?e:r},ht=(r,e,t)=>{if(!r)return e;let s=$e(r.semver,e.semver,t);return s<0?r:s>0||e.operator==="<"&&r.operator==="<="?e:r};pt.exports=Mn});var D=m((Zo,wt)=>{"use strict";var ge=T(),mt=A(),Jn=g(),dt=se(),Kn=S(),Zn=Ve(),Qn=_e(),ei=Me(),ri=Je(),ti=Ze(),si=er(),ni=tr(),ii=nr(),oi=L(),ai=cr(),ci=ur(),li=_(),ui=Er(),fi=dr(),hi=q(),pi=H(),Ei=oe(),mi=ae(),di=B(),wi=M(),$i=ce(),gi=Nr(),Ri=b(),Ii=O(),yi=k(),Li=Gr(),Oi=Vr(),Ni=_r(),Si=Mr(),Ti=Yr(),vi=J(),Ai=rt(),xi=st(),qi=ot(),bi=ct(),Pi=Et();wt.exports={parse:Kn,valid:Zn,clean:Qn,inc:ei,diff:ri,major:ti,minor:si,patch:ni,prerelease:ii,compare:oi,rcompare:ai,compareLoose:ci,compareBuild:li,sort:ui,rsort:fi,gt:hi,lt:pi,eq:Ei,neq:mi,gte:di,lte:wi,cmp:$i,coerce:gi,Comparator:Ri,Range:Ii,satisfies:yi,toComparators:Li,maxSatisfying:Oi,minSatisfying:Ni,minVersion:Si,validRange:Ti,outside:vi,gtr:Ai,ltr:xi,intersects:qi,simplifyRange:bi,subset:Pi,SemVer:Jn,re:ge.re,src:ge.src,tokens:ge.t,SEMVER_SPEC_VERSION:mt.SEMVER_SPEC_VERSION,RELEASE_TYPES:mt.RELEASE_TYPES,compareIdentifiers:dt.compareIdentifiers,rcompareIdentifiers:dt.rcompareIdentifiers}});var ee=new TextDecoder;function Ne(r){let e=r.indexOf("@",r.startsWith("@")?1:0);return e<0?{name:r,version:""}:{name:r.slice(0,e),version:r.slice(e+1)}}async function Se(r,e){let t=String(e??"").split(/\s+/).filter(i=>i.startsWith("sha512-")).map(i=>i.split("?")[0]);if(t.length===0)throw new Error("The package has no SHA-512 integrity");if(!globalThis.crypto?.subtle)throw new Error("Integrity checks need a secure context (https or localhost)");let s=new Uint8Array(await crypto.subtle.digest("SHA-512",r)),n="sha512-"+btoa(Array.from(s,i=>String.fromCharCode(i)).join(""));if(!t.includes(n))throw new Error(`Integrity check failed: expected ${t[0]}, got ${n}`);return n}async function Te(r,e=268435456){let t=new Blob([r]).stream().pipeThrough(new DecompressionStream("gzip")).getReader(),s=[],n=0;for(let i=await t.read();!i.done;i=await t.read()){if(n+=i.value.length,n>e)throw await t.cancel(),new Error(`The tarball unpacks to more than ${e} bytes`);s.push(i.value)}return new Uint8Array(await new Blob(s).arrayBuffer())}function v(r,e,t){let s=r.subarray(e,e+t),n=s.indexOf(0);return ee.decode(n<0?s:s.subarray(0,n))}function ve(r,e,t){if(r[e]&128)return r.subarray(e+1,e+t).reduce((n,i)=>n*256+i,r[e]&127);let s=v(r,e,t).trim();if(!/^[0-7]*$/.test(s))throw new Error("Corrupt tar header");return s===""?0:parseInt(s,8)}function Pt(r){let e=0;for(let t=0;t<512;++t)e+=t>=148&&t<156?32:r[t];if(ve(r,148,8)!==e)throw new Error("Corrupt tar header checksum")}function kt(r){let e={},t=0;for(;t0)||t+n>r.length)throw new Error("Corrupt pax header");let i=ee.decode(r.subarray(s+1,t+n-1)),o=i.indexOf("=");e[i.slice(0,o)]=i.slice(o+1),t+=n}return e}function Ct(r,e){let t=r.subarray(e,e+512);Pt(t);let s=ve(t,124,12),n=e+512;if(n+s>r.length)throw new Error("Truncated tar archive");return{header:t,type:t[156]===0?"0":String.fromCharCode(t[156]),data:r.subarray(n,n+s),next:n+Math.ceil(s/512)*512}}function Dt(r,e){return e+512>r.length||r.subarray(e,e+512).every(t=>t===0)}function jt(r){let e=v(r,0,100),t=v(r,257,5)==="ustar"?v(r,345,155):"";return t?`${t}/${e}`:e}var Oe={x:(r,e)=>({...r,pax:kt(e).path}),L:(r,e)=>({...r,long:v(e,0,e.length)}),g:r=>r};function Ae(r){let e=[],t={};for(let s=0;!Dt(r,s);){let{header:n,type:i,data:o,next:a}=Ct(r,s);if(s=a,Object.hasOwn(Oe,i)){t=Oe[i](t,o);continue}(i==="0"||i==="7")&&e.push({path:t.pax??t.long??jt(n),bytes:o}),t={}}return e}var K=F(D(),1);async function ki(r,e){let t=[],s=0;for(;;){let{done:n,value:i}=await r.read();if(n)return t;if(s+=i.length,s>e)throw new Error("Compressed download exceeds its byte limit");t.push(i)}}async function Ci(r,e){try{return await ki(r,e)}catch(t){throw await r.cancel().catch(()=>{}),t}finally{r.releaseLock()}}async function $t(r,e=64*1024*1024){if(!r.ok)throw new Error(`Download: HTTP ${r.status}`);if(Number(r.headers.get("content-length"))>e)throw new Error("Compressed download exceeds its byte limit");return new Uint8Array(await new Blob(await Ci(r.body.getReader(),e)).arrayBuffer())}var Di=/[\\\0:*?"<>|]/,ji=r=>r.split("/").some(e=>!e||e==="."||e==="..");function Fi(r){return typeof r!="string"||!r||Di.test(r)?!0:ji(r)}function j(r){if(Fi(r))throw new Error(`Unsafe package path: ${r}`);return r}var Ui=new TextDecoder,Gi=["preinstall","install","postinstall"];async function gt(r){let e=new Map;for(let t of Ae(await Te(r))){if(!t.path.startsWith("package/"))throw new Error("Invalid npm tarball root");let s=j(t.path.slice(8));if(e.has(s))throw new Error(`Duplicate package path: ${s}`);e.set(s,t.bytes)}return e}var Xi=r=>Gi.some(e=>r.scripts?.[e]),Vi=r=>r.has("binding.gyp")||[...r.keys()].some(e=>e.endsWith(".node"));function zi(r,e){return Xi(r)||r.gypfile?!0:Vi(e)}function Rt(r,e,t){let s=JSON.parse(Ui.decode(r.get("package.json")));if(s.name!==e||s.version!==t)throw new Error("npm archive identity mismatch");if(zi(s,r))throw new Error(`${e} needs an unsupported install script or native module`);return s}var Re=r=>/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(r),Z=(r,e)=>`${r.replace("/","+")}@${e}`,Ie=(r,e,t)=>`${Z(r,e)}-${t.slice(7).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}`;async function _i(r,e,{fetchImpl:t,signal:s}){let n=await t(new URL(r.replace("/","%2f"),e),{signal:s});if(!n.ok)throw new Error(`Registry metadata for ${r}: HTTP ${n.status}`);return n.json()}function Hi(r,e){let t=r["dist-tags"]?.[e];return t||(K.default.valid(e)?e:K.default.maxSatisfying(Object.keys(r.versions??{}),e))}function Bi(r,e,t){let s=t||"latest",n=Hi(r,s),i=r.versions?.[n];if(!i||!K.default.valid(n))throw new Error(`Cannot resolve ${e}@${s}`);return{version:n,manifest:i}}async function Mi(r,e,t,{fetchImpl:s,signal:n}){let i=new URL(e.dist?.tarball,t);if(i.protocol!=="https:"&&i.origin!==t.origin)throw new Error("Package tarballs must use HTTPS or the registry origin");let o=await s(i,{signal:n});if(!o.ok)throw new Error(`Package download for ${r}: HTTP ${o.status}`);let a=await $t(o);return{bytes:a,integrity:await Se(a,e.dist.integrity)}}function Wi(r){let e=new URL(r,globalThis.location?.href);return e.pathname.endsWith("/")||(e.pathname+="/"),e}async function ye(r,e,{registry:t,fetchImpl:s=fetch,signal:n}){if(!Re(r))throw new Error(`Unsupported npm package name: ${r}`);let i=Wi(t),o={fetchImpl:s,signal:n},{version:a,manifest:c}=Bi(await _i(r,i,o),r,e),{bytes:f,integrity:p}=await Mi(r,c,i,o),h=await gt(f),$=Rt(h,r,a);return{id:Z(r,a),key:Ie(r,a,p),manifest:$,integrity:p,files:h}}var Q=F(D(),1);function Yi(r,e,t){return Q.default.validRange(t)?Object.values(r?.packages??{}).filter(n=>n.name===e&&Q.default.satisfies(n.version,t)).sort((n,i)=>Q.default.rcompare(n.version,i.version))[0]??null:null}function It({registry:r="https://registry.npmjs.org/",fetchImpl:e=fetch,signal:t,download:s=ye,previous:n}){let i=new Map;return async(o,a)=>{let c=`${o}@${a}`;if(i.has(c))return i.get(c);let f=Yi(n,o,a),p=await s(o,f?.version??a,{registry:r,fetchImpl:e,signal:t});if(f&&p.integrity!==f.integrity)throw new Error(`${p.id} no longer matches the integrity recorded in the lock`);return i.set(c,p),p}}var yt=F(D(),1),Lt=(r,e,t)=>new Error(`${r.name}@${r.version} requires peer ${e}@${t}; install a compatible root explicitly`);function Ji(r,e,t){if(r.manifest.peerDependenciesMeta?.[e]?.optional)return null;throw Lt(r,e,t)}function Ki(r,[e,t],{nodes:s,roots:n}){let i=n[e]?.id??r.dependencies[e];if(!i)return Ji(r,e,t);if(!yt.default.satisfies(s[i].version,t))throw Lt(r,e,t);return i}function Zi(r,e){for(let t of Object.entries(r.manifest.peerDependencies??{})){let s=Ki(r,t,e);s&&(r.dependencies[t[0]]=s)}}function Ot(r,e){for(let t of Object.values(r))Zi(t,{nodes:r,roots:e})}var Nt=F(D(),1);function Qi(r,e){return!Re(e.name)||!Nt.default.valid(e.version)?!1:r===Z(e.name,e.version)}function eo(r){return r.integrity?.startsWith("sha512-")?r.key===Ie(r.name,r.version,r.integrity):!1}function ro(r,e,t){if(!Qi(e,t)||!eo(t))throw new Error("Invalid locked package");for(let s of t.files)j(s);if(Object.values(t.dependencies).some(s=>!r.packages[s]))throw new Error("Dangling locked dependency")}function to(r){return r?.format!==1?!1:!!r.roots&&!!r.packages}function so(r){if(!to(r))throw new Error("Unsupported package lock");for(let[e,t]of Object.entries(r.packages))ro(r,e,t);if(Object.values(r.roots).some(e=>!r.packages[e.id]))throw new Error("Dangling locked root");return r}function no(r,e,t){if(Object.keys(r.nodes).length>=512)throw new Error("Dependency graph exceeds 512 packages");for(let s of t.files.values())r.total+=s.length;if(r.total>256*1024*1024)throw new Error("Dependency graph exceeds 256 MiB");r.nodes[t.id]={name:e,version:t.manifest.version,integrity:t.integrity,key:t.key,manifest:t.manifest,files:[...t.files.keys()].sort(),dependencies:{}},r.downloads.set(t.id,t.files)}async function io(r,e){let t={};for(let s of r){let{name:n,version:i}=Ne(s);t[n]={requested:i||"latest",id:await e(n,i||"latest")}}return t}async function Ra(r,e={}){let t=It(e),s={nodes:{},downloads:new Map,total:0},n=async(o,a)=>{e.signal?.throwIfAborted();let c=await t(o,a);if(s.nodes[c.id])return c.id;no(s,o,c);for(let[f,p]of Object.entries(c.manifest.dependencies??{}).sort())s.nodes[c.id].dependencies[f]=await n(f,p);return c.id},i=await io(r,n);return Ot(s.nodes,i),{lock:{format:1,registry:e.registry??"https://registry.npmjs.org/",roots:i,packages:s.nodes},downloads:s.downloads}}export{ye as downloadPackage,Ra as resolvePackages,j as safePackagePath,so as validateLock}; +var En=Object.create;var Qe=Object.defineProperty;var wn=Object.getOwnPropertyDescriptor;var $n=Object.getOwnPropertyNames;var gn=Object.getPrototypeOf,yn=Object.prototype.hasOwnProperty;var m=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Rn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of $n(t))!yn.call(e,s)&&s!==r&&Qe(e,s,{get:()=>t[s],enumerable:!(n=wn(t,s))||n.enumerable});return e};var P=(e,t,r)=>(r=e!=null?En(gn(e)):{},Rn(t||!e||!e.__esModule?Qe(r,"default",{value:e,enumerable:!0}):r,e));var U=m((Oa,it)=>{"use strict";var Sn="2.0.0",Nn=Number.MAX_SAFE_INTEGER||9007199254740991,bn=16,An=250,Tn=["major","premajor","minor","preminor","patch","prepatch","prerelease"];it.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:bn,MAX_SAFE_BUILD_LENGTH:An,MAX_SAFE_INTEGER:Nn,RELEASE_TYPES:Tn,SEMVER_SPEC_VERSION:Sn,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var F=m((va,ot)=>{"use strict";var kn=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};ot.exports=kn});var q=m((x,at)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:$e,MAX_SAFE_BUILD_LENGTH:Pn,MAX_LENGTH:qn}=U(),jn=F();x=at.exports={};var Cn=x.re=[],Dn=x.safeRe=[],l=x.src=[],Un=x.safeSrc=[],u=x.t={},Fn=0,ge="[a-zA-Z0-9-]",Gn=[["\\s",1],["\\d",qn],[ge,Pn]],zn=e=>{for(let[t,r]of Gn)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let n=zn(t),s=Fn++;jn(e,s,t),u[e]=s,l[s]=t,Un[s]=n,Cn[s]=new RegExp(t,r?"g":void 0),Dn[s]=new RegExp(n,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${ge}*`);E("MAINVERSION",`(${l[u.NUMERICIDENTIFIER]})\\.(${l[u.NUMERICIDENTIFIER]})\\.(${l[u.NUMERICIDENTIFIER]})`);E("MAINVERSIONLOOSE",`(${l[u.NUMERICIDENTIFIERLOOSE]})\\.(${l[u.NUMERICIDENTIFIERLOOSE]})\\.(${l[u.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASEIDENTIFIER",`(?:${l[u.NONNUMERICIDENTIFIER]}|${l[u.NUMERICIDENTIFIER]})`);E("PRERELEASEIDENTIFIERLOOSE",`(?:${l[u.NONNUMERICIDENTIFIER]}|${l[u.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASE",`(?:-(${l[u.PRERELEASEIDENTIFIER]}(?:\\.${l[u.PRERELEASEIDENTIFIER]})*))`);E("PRERELEASELOOSE",`(?:-?(${l[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${l[u.PRERELEASEIDENTIFIERLOOSE]})*))`);E("BUILDIDENTIFIER",`${ge}+`);E("BUILD",`(?:\\+(${l[u.BUILDIDENTIFIER]}(?:\\.${l[u.BUILDIDENTIFIER]})*))`);E("FULLPLAIN",`v?${l[u.MAINVERSION]}${l[u.PRERELEASE]}?${l[u.BUILD]}?`);E("FULL",`^${l[u.FULLPLAIN]}$`);E("LOOSEPLAIN",`[v=\\s]*${l[u.MAINVERSIONLOOSE]}${l[u.PRERELEASELOOSE]}?${l[u.BUILD]}?`);E("LOOSE",`^${l[u.LOOSEPLAIN]}$`);E("GTLT","((?:<|>)?=?)");E("XRANGEIDENTIFIERLOOSE",`${l[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);E("XRANGEIDENTIFIER",`${l[u.NUMERICIDENTIFIER]}|x|X|\\*`);E("XRANGEPLAIN",`[v=\\s]*(${l[u.XRANGEIDENTIFIER]})(?:\\.(${l[u.XRANGEIDENTIFIER]})(?:\\.(${l[u.XRANGEIDENTIFIER]})(?:${l[u.PRERELEASE]})?${l[u.BUILD]}?)?)?`);E("XRANGEPLAINLOOSE",`[v=\\s]*(${l[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[u.XRANGEIDENTIFIERLOOSE]})(?:${l[u.PRERELEASELOOSE]})?${l[u.BUILD]}?)?)?`);E("XRANGE",`^${l[u.GTLT]}\\s*${l[u.XRANGEPLAIN]}$`);E("XRANGELOOSE",`^${l[u.GTLT]}\\s*${l[u.XRANGEPLAINLOOSE]}$`);E("COERCEPLAIN",`(^|[^\\d])(\\d{1,${$e}})(?:\\.(\\d{1,${$e}}))?(?:\\.(\\d{1,${$e}}))?`);E("COERCE",`${l[u.COERCEPLAIN]}(?:$|[^\\d])`);E("COERCEFULL",l[u.COERCEPLAIN]+`(?:${l[u.PRERELEASE]})?(?:${l[u.BUILD]})?(?:$|[^\\d])`);E("COERCERTL",l[u.COERCE],!0);E("COERCERTLFULL",l[u.COERCEFULL],!0);E("LONETILDE","(?:~>?)");E("TILDETRIM",`(\\s*)${l[u.LONETILDE]}\\s+`,!0);x.tildeTrimReplace="$1~";E("TILDE",`^${l[u.LONETILDE]}${l[u.XRANGEPLAIN]}$`);E("TILDELOOSE",`^${l[u.LONETILDE]}${l[u.XRANGEPLAINLOOSE]}$`);E("LONECARET","(?:\\^)");E("CARETTRIM",`(\\s*)${l[u.LONECARET]}\\s+`,!0);x.caretTrimReplace="$1^";E("CARET",`^${l[u.LONECARET]}${l[u.XRANGEPLAIN]}$`);E("CARETLOOSE",`^${l[u.LONECARET]}${l[u.XRANGEPLAINLOOSE]}$`);E("COMPARATORLOOSE",`^${l[u.GTLT]}\\s*(${l[u.LOOSEPLAIN]})$|^$`);E("COMPARATOR",`^${l[u.GTLT]}\\s*(${l[u.FULLPLAIN]})$|^$`);E("COMPARATORTRIM",`(\\s*)${l[u.GTLT]}\\s*(${l[u.LOOSEPLAIN]}|${l[u.XRANGEPLAIN]})`,!0);x.comparatorTrimReplace="$1$2$3";E("HYPHENRANGE",`^\\s*(${l[u.XRANGEPLAIN]})\\s+-\\s+(${l[u.XRANGEPLAIN]})\\s*$`);E("HYPHENRANGELOOSE",`^\\s*(${l[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${l[u.XRANGEPLAINLOOSE]})\\s*$`);E("STAR","(<|>)?=?\\s*\\*");E("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");E("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Y=m((La,ct)=>{"use strict";var Xn=Object.freeze({loose:!0}),Mn=Object.freeze({}),Vn=e=>e?typeof e!="object"?Xn:e:Mn;ct.exports=Vn});var ye=m((xa,ft)=>{"use strict";var lt=/^[0-9]+$/,ut=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:eut(t,e);ft.exports={compareIdentifiers:ut,rcompareIdentifiers:_n}});var y=m((Sa,ht)=>{"use strict";var J=F(),{MAX_LENGTH:pt,MAX_SAFE_INTEGER:Z}=U(),{safeRe:K,t:Q}=q(),Bn=Y(),{compareIdentifiers:Re}=ye(),Ie=class e{constructor(t,r){if(r=Bn(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>pt)throw new TypeError(`version is longer than ${pt} characters`);J("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?K[Q.LOOSE]:K[Q.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>Z||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Z||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Z||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let i=+s;if(i>=0&&it.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(J("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 Re(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(J("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 Re(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?K[Q.PRERELEASELOOSE]:K[Q.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 i=this.prerelease.length;for(;--i>=0;)typeof this.prerelease[i]=="number"&&(this.prerelease[i]++,i=-2);if(i===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(r){let i=[r,s];n===!1&&(i=[r]),Re(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=i):this.prerelease=i}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};ht.exports=Ie});var A=m((Na,mt)=>{"use strict";var dt=y(),Hn=(e,t,r=!1)=>{if(e instanceof dt)return e;try{return new dt(e,t)}catch(n){if(!r)return null;throw n}};mt.exports=Hn});var wt=m((ba,Et)=>{"use strict";var Wn=A(),Yn=(e,t)=>{let r=Wn(e,t);return r?r.version:null};Et.exports=Yn});var gt=m((Aa,$t)=>{"use strict";var Jn=A(),Zn=(e,t)=>{let r=Jn(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};$t.exports=Zn});var It=m((Ta,Rt)=>{"use strict";var yt=y(),Kn=(e,t,r,n,s)=>{typeof r=="string"&&(s=n,n=r,r=void 0);try{return new yt(e instanceof yt?e.version:e,r).inc(t,n,s).version}catch{return null}};Rt.exports=Kn});var Lt=m((ka,vt)=>{"use strict";var Ot=A(),Qn=(e,t)=>{let r=Ot(e,null,!0),n=Ot(t,null,!0),s=r.compare(n);if(s===0)return null;let i=s>0,o=i?r:n,a=i?n:r,c=!!o.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(o)===0)return a.minor&&!a.patch?"minor":"patch"}let d=c?"pre":"";return r.major!==n.major?d+"major":r.minor!==n.minor?d+"minor":r.patch!==n.patch?d+"patch":"prerelease"};vt.exports=Qn});var St=m((Pa,xt)=>{"use strict";var es=y(),ts=(e,t)=>new es(e,t).major;xt.exports=ts});var bt=m((qa,Nt)=>{"use strict";var rs=y(),ns=(e,t)=>new rs(e,t).minor;Nt.exports=ns});var Tt=m((ja,At)=>{"use strict";var ss=y(),is=(e,t)=>new ss(e,t).patch;At.exports=is});var Pt=m((Ca,kt)=>{"use strict";var os=A(),as=(e,t)=>{let r=os(e,t);return r&&r.prerelease.length?r.prerelease:null};kt.exports=as});var v=m((Da,jt)=>{"use strict";var qt=y(),cs=(e,t,r)=>new qt(e,r).compare(new qt(t,r));jt.exports=cs});var Dt=m((Ua,Ct)=>{"use strict";var ls=v(),us=(e,t,r)=>ls(t,e,r);Ct.exports=us});var Ft=m((Fa,Ut)=>{"use strict";var fs=v(),ps=(e,t)=>fs(e,t,!0);Ut.exports=ps});var ee=m((Ga,zt)=>{"use strict";var Gt=y(),hs=(e,t,r)=>{let n=new Gt(e,r),s=new Gt(t,r);return n.compare(s)||n.compareBuild(s)};zt.exports=hs});var Mt=m((za,Xt)=>{"use strict";var ds=ee(),ms=(e,t)=>e.sort((r,n)=>ds(r,n,t));Xt.exports=ms});var _t=m((Xa,Vt)=>{"use strict";var Es=ee(),ws=(e,t)=>e.sort((r,n)=>Es(n,r,t));Vt.exports=ws});var G=m((Ma,Bt)=>{"use strict";var $s=v(),gs=(e,t,r)=>$s(e,t,r)>0;Bt.exports=gs});var te=m((Va,Ht)=>{"use strict";var ys=v(),Rs=(e,t,r)=>ys(e,t,r)<0;Ht.exports=Rs});var Oe=m((_a,Wt)=>{"use strict";var Is=v(),Os=(e,t,r)=>Is(e,t,r)===0;Wt.exports=Os});var ve=m((Ba,Yt)=>{"use strict";var vs=v(),Ls=(e,t,r)=>vs(e,t,r)!==0;Yt.exports=Ls});var re=m((Ha,Jt)=>{"use strict";var xs=v(),Ss=(e,t,r)=>xs(e,t,r)>=0;Jt.exports=Ss});var ne=m((Wa,Zt)=>{"use strict";var Ns=v(),bs=(e,t,r)=>Ns(e,t,r)<=0;Zt.exports=bs});var Le=m((Ya,Kt)=>{"use strict";var As=Oe(),Ts=ve(),ks=G(),Ps=re(),qs=te(),js=ne(),Cs=(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 As(e,r,n);case"!=":return Ts(e,r,n);case">":return ks(e,r,n);case">=":return Ps(e,r,n);case"<":return qs(e,r,n);case"<=":return js(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};Kt.exports=Cs});var er=m((Ja,Qt)=>{"use strict";var Ds=y(),Us=A(),{safeRe:se,t:ie}=q(),Fs=(e,t)=>{if(e instanceof Ds)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?se[ie.COERCEFULL]:se[ie.COERCE]);else{let c=t.includePrerelease?se[ie.COERCERTLFULL]:se[ie.COERCERTL],f;for(;(f=c.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||f.index+f[0].length!==r.index+r[0].length)&&(r=f),c.lastIndex=f.index+f[1].length+f[2].length;c.lastIndex=-1}if(r===null)return null;let n=r[2],s=r[3]||"0",i=r[4]||"0",o=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return Us(`${n}.${s}.${i}${o}${a}`,t)};Qt.exports=Fs});var rr=m((Za,tr)=>{"use strict";var xe=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}};tr.exports=xe});var L=m((Ka,or)=>{"use strict";var Gs=/\s+/g,Se=class e{constructor(t,r){if(r=Xs(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof Ne)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(Gs," "),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=>!sr(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&&Ys(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&&Hs)|(this.options.loose&&Ws))+":"+t,s=nr.get(n);if(s)return s;let i=this.options.loose,o=i?I[R.HYPHENRANGELOOSE]:I[R.HYPHENRANGE];t=t.replace(o,ii(this.options.includePrerelease)),$("hyphen replace",t),t=t.replace(I[R.COMPARATORTRIM],Vs),$("comparator trim",t),t=t.replace(I[R.TILDETRIM],_s),$("tilde trim",t),t=t.replace(I[R.CARETTRIM],Bs),$("caret trim",t);let a=t.split(" ").map(p=>Js(p,this.options)).join(" ").split(/\s+/).map(p=>si(p,this.options));i&&(a=a.filter(p=>($("loose invalid filter",p,this.options),!!p.match(I[R.COMPARATORLOOSE])))),$("range list",a);let c=new Map,f=a.map(p=>new Ne(p,this.options));for(let p of f){if(sr(p))return[p];c.set(p.value,p)}c.size>1&&c.has("")&&c.delete("");let d=[...c.values()];return nr.set(n,d),d}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(n=>ir(n,r)&&t.set.some(s=>ir(s,r)&&n.every(i=>s.every(o=>i.intersects(o,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new Ms(t,this.options)}catch{return!1}for(let r=0;re.value==="<0.0.0-0",Ys=e=>e.value==="",ir=(e,t)=>{let r=!0,n=e.slice(),s=n.pop();for(;r&&n.length;)r=n.every(i=>s.intersects(i,t)),s=n.pop();return r},Js=(e,t)=>(e=e.replace(I[R.BUILD],""),$("comp",e,t),e=Qs(e,t),$("caret",e),e=Zs(e,t),$("tildes",e),e=ti(e,t),$("xrange",e),e=ni(e,t),$("stars",e),e),O=e=>!e||e.toLowerCase()==="x"||e==="*",Zs=(e,t)=>e.trim().split(/\s+/).map(r=>Ks(r,t)).join(" "),Ks=(e,t)=>{let r=t.loose?I[R.TILDELOOSE]:I[R.TILDE];return e.replace(r,(n,s,i,o,a)=>{$("tilde",e,n,s,i,o,a);let c;return O(s)?c="":O(i)?c=`>=${s}.0.0 <${+s+1}.0.0-0`:O(o)?c=`>=${s}.${i}.0 <${s}.${+i+1}.0-0`:a?($("replaceTilde pr",a),c=`>=${s}.${i}.${o}-${a} <${s}.${+i+1}.0-0`):c=`>=${s}.${i}.${o} <${s}.${+i+1}.0-0`,$("tilde return",c),c})},Qs=(e,t)=>e.trim().split(/\s+/).map(r=>ei(r,t)).join(" "),ei=(e,t)=>{$("caret",e,t);let r=t.loose?I[R.CARETLOOSE]:I[R.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(s,i,o,a,c)=>{$("caret",e,s,i,o,a,c);let f;return O(i)?f="":O(o)?f=`>=${i}.0.0${n} <${+i+1}.0.0-0`:O(a)?i==="0"?f=`>=${i}.${o}.0${n} <${i}.${+o+1}.0-0`:f=`>=${i}.${o}.0${n} <${+i+1}.0.0-0`:c?($("replaceCaret pr",c),i==="0"?o==="0"?f=`>=${i}.${o}.${a}-${c} <${i}.${o}.${+a+1}-0`:f=`>=${i}.${o}.${a}-${c} <${i}.${+o+1}.0-0`:f=`>=${i}.${o}.${a}-${c} <${+i+1}.0.0-0`):($("no pr"),i==="0"?o==="0"?f=`>=${i}.${o}.${a}${n} <${i}.${o}.${+a+1}-0`:f=`>=${i}.${o}.${a}${n} <${i}.${+o+1}.0-0`:f=`>=${i}.${o}.${a} <${+i+1}.0.0-0`),$("caret return",f),f})},ti=(e,t)=>($("replaceXRanges",e,t),e.split(/\s+/).map(r=>ri(r,t)).join(" ")),ri=(e,t)=>{e=e.trim();let r=t.loose?I[R.XRANGELOOSE]:I[R.XRANGE];return e.replace(r,(n,s,i,o,a,c)=>{$("xRange",e,n,s,i,o,a,c);let f=O(i),d=f||O(o),p=d||O(a),w=p;return s==="="&&w&&(s=""),c=t.includePrerelease?"-0":"",f?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&w?(d&&(o=0),a=0,s===">"?(s=">=",d?(i=+i+1,o=0,a=0):(o=+o+1,a=0)):s==="<="&&(s="<",d?i=+i+1:o=+o+1),s==="<"&&(c="-0"),n=`${s+i}.${o}.${a}${c}`):d?n=`>=${i}.0.0${c} <${+i+1}.0.0-0`:p&&(n=`>=${i}.${o}.0${c} <${i}.${+o+1}.0-0`),$("xRange return",n),n})},ni=(e,t)=>($("replaceStars",e,t),e.trim().replace(I[R.STAR],"")),si=(e,t)=>($("replaceGTE0",e,t),e.trim().replace(I[t.includePrerelease?R.GTE0PRE:R.GTE0],"")),ii=e=>(t,r,n,s,i,o,a,c,f,d,p,w)=>(O(n)?r="":O(s)?r=`>=${n}.0.0${e?"-0":""}`:O(i)?r=`>=${n}.${s}.0${e?"-0":""}`:o?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,O(f)?c="":O(d)?c=`<${+f+1}.0.0-0`:O(p)?c=`<${f}.${+d+1}.0-0`:w?c=`<=${f}.${d}.${p}-${w}`:e?c=`<${f}.${d}.${+p+1}-0`:c=`<=${c}`,`${r} ${c}`.trim()),oi=(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 z=m((Qa,pr)=>{"use strict";var X=Symbol("SemVer ANY"),Te=class e{static get ANY(){return X}constructor(t,r){if(r=ar(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Ae("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===X?this.value="":this.value=this.operator+this.semver.version,Ae("comp",this)}parse(t){let r=this.options.loose?cr[lr.COMPARATORLOOSE]:cr[lr.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 ur(n[2],this.options.loose):this.semver=X}toString(){return this.value}test(t){if(Ae("Comparator.test",t,this.options.loose),this.semver===X||t===X)return!0;if(typeof t=="string")try{t=new ur(t,this.options)}catch{return!1}return be(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 fr(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new fr(this.value,r).test(t.semver):(r=ar(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("=")||be(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||be(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};pr.exports=Te;var ar=Y(),{safeRe:cr,t:lr}=q(),be=Le(),Ae=F(),ur=y(),fr=L()});var M=m((ec,hr)=>{"use strict";var ai=L(),ci=(e,t,r)=>{try{t=new ai(t,r)}catch{return!1}return t.test(e)};hr.exports=ci});var mr=m((tc,dr)=>{"use strict";var li=L(),ui=(e,t)=>new li(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));dr.exports=ui});var wr=m((rc,Er)=>{"use strict";var fi=y(),pi=L(),hi=(e,t,r)=>{let n=null,s=null,i=null;try{i=new pi(t,r)}catch{return null}return e.forEach(o=>{i.test(o)&&(!n||s.compare(o)===-1)&&(n=o,s=new fi(n,r))}),n};Er.exports=hi});var gr=m((nc,$r)=>{"use strict";var di=y(),mi=L(),Ei=(e,t,r)=>{let n=null,s=null,i=null;try{i=new mi(t,r)}catch{return null}return e.forEach(o=>{i.test(o)&&(!n||s.compare(o)===1)&&(n=o,s=new di(n,r))}),n};$r.exports=Ei});var Ir=m((sc,Rr)=>{"use strict";var ke=y(),wi=L(),yr=G(),$i=(e,t)=>{e=new wi(e,t);let r=new ke("0.0.0");if(e.test(r)||(r=new ke("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n{let a=new ke(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!i||yr(a,i))&&(i=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),i&&(!r||yr(r,i))&&(r=i)}return r&&e.test(r)?r:null};Rr.exports=$i});var vr=m((ic,Or)=>{"use strict";var gi=L(),yi=(e,t)=>{try{return new gi(e,t).range||"*"}catch{return null}};Or.exports=yi});var oe=m((oc,Nr)=>{"use strict";var Ri=y(),Sr=z(),{ANY:Ii}=Sr,Oi=L(),vi=M(),Lr=G(),xr=te(),Li=ne(),xi=re(),Si=(e,t,r,n)=>{e=new Ri(e,n),t=new Oi(t,n);let s,i,o,a,c;switch(r){case">":s=Lr,i=Li,o=xr,a=">",c=">=";break;case"<":s=xr,i=xi,o=Lr,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(vi(e,t,n))return!1;for(let f=0;f{h.semver===Ii&&(h=new Sr(">=0.0.0")),p=p||h,w=w||h,s(h.semver,p.semver,n)?p=h:o(h.semver,w.semver,n)&&(w=h)}),p.operator===a||p.operator===c||(!w.operator||w.operator===a)&&i(e,w.semver))return!1;if(w.operator===c&&o(e,w.semver))return!1}return!0};Nr.exports=Si});var Ar=m((ac,br)=>{"use strict";var Ni=oe(),bi=(e,t,r)=>Ni(e,t,">",r);br.exports=bi});var kr=m((cc,Tr)=>{"use strict";var Ai=oe(),Ti=(e,t,r)=>Ai(e,t,"<",r);Tr.exports=Ti});var jr=m((lc,qr)=>{"use strict";var Pr=L(),ki=(e,t,r)=>(e=new Pr(e,r),t=new Pr(t,r),e.intersects(t,r));qr.exports=ki});var Dr=m((uc,Cr)=>{"use strict";var Pi=M(),qi=v();Cr.exports=(e,t,r)=>{let n=[],s=null,i=null,o=e.sort((d,p)=>qi(d,p,r));for(let d of o)Pi(d,t,r)?(i=d,s||(s=d)):(i&&n.push([s,i]),i=null,s=null);s&&n.push([s,null]);let a=[];for(let[d,p]of n)d===p?a.push(d):!p&&d===o[0]?a.push("*"):p?d===o[0]?a.push(`<=${p}`):a.push(`${d} - ${p}`):a.push(`>=${d}`);let c=a.join(" || "),f=typeof t.raw=="string"?t.raw:String(t);return c.length{"use strict";var Ur=L(),qe=z(),{ANY:Pe}=qe,V=M(),je=v(),ji=(e,t,r={})=>{if(e===t)return!0;e=new Ur(e,r),t=new Ur(t,r);let n=!1;e:for(let s of e.set){for(let i of t.set){let o=Di(s,i,r);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},Ci=[new qe(">=0.0.0-0")],Fr=[new qe(">=0.0.0")],Di=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Pe){if(t.length===1&&t[0].semver===Pe)return!0;r.includePrerelease?e=Ci:e=Fr}if(t.length===1&&t[0].semver===Pe){if(r.includePrerelease)return!0;t=Fr}let n=new Set,s,i;for(let h of e)h.operator===">"||h.operator===">="?s=Gr(s,h,r):h.operator==="<"||h.operator==="<="?i=zr(i,h,r):n.add(h.semver);if(n.size>1)return null;let o;if(s&&i){if(o=je(s.semver,i.semver,r),o>0)return null;if(o===0&&(s.operator!==">="||i.operator!=="<="))return null}for(let h of n){if(s&&!V(h,String(s),r)||i&&!V(h,String(i),r))return null;for(let H of t)if(!V(h,String(H),r))return!1;return!0}let a,c,f,d,p=i&&!r.includePrerelease&&i.semver.prerelease.length?i.semver:!1,w=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1;p&&p.prerelease.length===1&&i.operator==="<"&&p.prerelease[0]===0&&(p=!1);for(let h of t){if(d=d||h.operator===">"||h.operator===">=",f=f||h.operator==="<"||h.operator==="<=",s){if(w&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===w.major&&h.semver.minor===w.minor&&h.semver.patch===w.patch&&(w=!1),h.operator===">"||h.operator===">="){if(a=Gr(s,h,r),a===h&&a!==s)return!1}else if(s.operator===">="&&!V(s.semver,String(h),r))return!1}if(i){if(p&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===p.major&&h.semver.minor===p.minor&&h.semver.patch===p.patch&&(p=!1),h.operator==="<"||h.operator==="<="){if(c=zr(i,h,r),c===h&&c!==i)return!1}else if(i.operator==="<="&&!V(i.semver,String(h),r))return!1}if(!h.operator&&(i||s)&&o!==0)return!1}return!(s&&f&&!i&&o!==0||i&&d&&!s&&o!==0||w||p)},Gr=(e,t,r)=>{if(!e)return t;let n=je(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},zr=(e,t,r)=>{if(!e)return t;let n=je(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};Xr.exports=ji});var T=m((pc,Br)=>{"use strict";var Ce=q(),Vr=U(),Ui=y(),_r=ye(),Fi=A(),Gi=wt(),zi=gt(),Xi=It(),Mi=Lt(),Vi=St(),_i=bt(),Bi=Tt(),Hi=Pt(),Wi=v(),Yi=Dt(),Ji=Ft(),Zi=ee(),Ki=Mt(),Qi=_t(),eo=G(),to=te(),ro=Oe(),no=ve(),so=re(),io=ne(),oo=Le(),ao=er(),co=z(),lo=L(),uo=M(),fo=mr(),po=wr(),ho=gr(),mo=Ir(),Eo=vr(),wo=oe(),$o=Ar(),go=kr(),yo=jr(),Ro=Dr(),Io=Mr();Br.exports={parse:Fi,valid:Gi,clean:zi,inc:Xi,diff:Mi,major:Vi,minor:_i,patch:Bi,prerelease:Hi,compare:Wi,rcompare:Yi,compareLoose:Ji,compareBuild:Zi,sort:Ki,rsort:Qi,gt:eo,lt:to,eq:ro,neq:no,gte:so,lte:io,cmp:oo,coerce:ao,Comparator:co,Range:lo,satisfies:uo,toComparators:fo,maxSatisfying:po,minSatisfying:ho,minVersion:mo,validRange:Eo,outside:wo,gtr:$o,ltr:go,intersects:yo,simplifyRange:Ro,subset:Io,SemVer:Ui,re:Ce.re,src:Ce.src,tokens:Ce.t,SEMVER_SPEC_VERSION:Vr.SEMVER_SPEC_VERSION,RELEASE_TYPES:Vr.RELEASE_TYPES,compareIdentifiers:_r.compareIdentifiers,rcompareIdentifiers:_r.rcompareIdentifiers}});var we=new TextDecoder;function W(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 tt(e,t){let r=String(t??"").split(/\s+/).filter(i=>i.startsWith("sha512-")).map(i=>i.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,i=>String.fromCharCode(i)).join(""));if(!r.includes(s))throw new Error(`Integrity check failed: expected ${r[0]}, got ${s}`);return s}async function rt(e,t=268435456){let r=new Blob([e]).stream().pipeThrough(new DecompressionStream("gzip")).getReader(),n=[],s=0;for(let i=await r.read();!i.done;i=await r.read()){if(s+=i.value.length,s>t)throw await r.cancel(),new Error(`The tarball unpacks to more than ${t} bytes`);n.push(i.value)}return new Uint8Array(await new Blob(n).arrayBuffer())}function D(e,t,r){let n=e.subarray(t,t+r),s=n.indexOf(0);return we.decode(s<0?n:n.subarray(0,s))}function nt(e,t,r){if(e[t]&128)return e.subarray(t+1,t+r).reduce((s,i)=>s*256+i,e[t]&127);let n=D(e,t,r).trim();if(!/^[0-7]*$/.test(n))throw new Error("Corrupt tar header");return n===""?0:parseInt(n,8)}function In(e){let t=0;for(let r=0;r<512;++r)t+=r>=148&&r<156?32:e[r];if(nt(e,148,8)!==t)throw new Error("Corrupt tar header checksum")}function On(e){let t={},r=0;for(;r0)||r+s>e.length)throw new Error("Corrupt pax header");let i=we.decode(e.subarray(n+1,r+s-1)),o=i.indexOf("=");t[i.slice(0,o)]=i.slice(o+1),r+=s}return t}function vn(e,t){let r=e.subarray(t,t+512);In(r);let n=nt(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 Ln(e,t){return t+512>e.length||e.subarray(t,t+512).every(r=>r===0)}function xn(e){let t=D(e,0,100),r=D(e,257,5)==="ustar"?D(e,345,155):"";return r?`${r}/${t}`:t}var et={x:(e,t)=>({...e,pax:On(t).path}),L:(e,t)=>({...e,long:D(t,0,t.length)}),g:e=>e};function st(e){let t=[],r={};for(let n=0;!Ln(e,n);){let{header:s,type:i,data:o,next:a}=vn(e,n);if(n=a,Object.hasOwn(et,i)){r=et[i](r,o);continue}(i==="0"||i==="7")&&t.push({path:r.pax??r.long??xn(s),bytes:o}),r={}}return t}var le=P(T(),1);var S=(e,t,...r)=>e.cppFunction(`webfront.developer.${t}`)(...r);async function ae(e,t){let r=[],n=0;for(;;){let s=await S(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 De(e,{id:t,path:r,bytes:n},s){for(let i=0;i{}),a}}async function Oo(e,t){let r=[],n=0;for(;;){let{done:s,value:i}=await e.read();if(s)return r;if(n+=i.length,n>t)throw new Error("Compressed download exceeds its byte limit");r.push(i)}}async function vo(e,t){try{return await Oo(e,t)}catch(r){throw await e.cancel().catch(()=>{}),r}finally{e.releaseLock()}}async function Hr(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 vo(e.body.getReader(),t)).arrayBuffer())}var Lo=/[\\\0:*?"<>|]/,xo=e=>e.split("/").some(t=>!t||t==="."||t==="..");function So(e){return typeof e!="string"||!e||Lo.test(e)?!0:xo(e)}function k(e){if(So(e))throw new Error(`Unsafe package path: ${e}`);return e}var No=new TextDecoder,bo=["preinstall","install","postinstall"];async function Wr(e){let t=new Map;for(let r of st(await rt(e))){if(!r.path.startsWith("package/"))throw new Error("Invalid npm tarball root");let n=k(r.path.slice(8));if(t.has(n))throw new Error(`Duplicate package path: ${n}`);t.set(n,r.bytes)}return t}var Ao=e=>bo.some(t=>e.scripts?.[t]),To=e=>e.has("binding.gyp")||[...e.keys()].some(t=>t.endsWith(".node"));function ko(e,t){return Ao(e)||e.gypfile?!0:To(t)}function Yr(e,t,r){let n=JSON.parse(No.decode(e.get("package.json")));if(n.name!==t||n.version!==r)throw new Error("npm archive identity mismatch");if(ko(n,e))throw new Error(`${t} needs an unsupported install script or native module`);return n}var Ue=e=>/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(e),ue=(e,t)=>`${e.replace("/","+")}@${t}`,Fe=(e,t,r)=>`${ue(e,t)}-${r.slice(7).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}`;async function Po(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 qo(e,t){let r=e["dist-tags"]?.[t];return r||(le.default.valid(t)?t:le.default.maxSatisfying(Object.keys(e.versions??{}),t))}function jo(e,t,r){let n=r||"latest",s=qo(e,n),i=e.versions?.[s];if(!i||!le.default.valid(s))throw new Error(`Cannot resolve ${t}@${n}`);return{version:s,manifest:i}}async function Co(e,t,r,{fetchImpl:n,signal:s}){let i=new URL(t.dist?.tarball,r);if(i.protocol!=="https:"&&i.origin!==r.origin)throw new Error("Package tarballs must use HTTPS or the registry origin");let o=await n(i,{signal:s});if(!o.ok)throw new Error(`Package download for ${e}: HTTP ${o.status}`);let a=await Hr(o);return{bytes:a,integrity:await tt(a,t.dist.integrity)}}function Do(e){let t=new URL(e,globalThis.location?.href);return t.pathname.endsWith("/")||(t.pathname+="/"),t}async function j(e,t,{registry:r,fetchImpl:n=fetch,signal:s}){if(!Ue(e))throw new Error(`Unsupported npm package name: ${e}`);let i=Do(r),o={fetchImpl:n,signal:s},{version:a,manifest:c}=jo(await Po(e,i,o),e,t),{bytes:f,integrity:d}=await Co(e,c,i,o),p=await Wr(f),w=Yr(p,e,a);return{id:ue(e,a),key:Fe(e,a,d),manifest:w,integrity:d,files:p}}var fe=P(T(),1);function Uo(e,t,r){let n=e?.roots?.[t];return n?.requested===r&&e.packages[n.id]?e.packages[n.id]:fe.default.validRange(r)?Object.values(e?.packages??{}).filter(i=>i.name===t&&fe.default.satisfies(i.version,r)).sort((i,o)=>fe.default.rcompare(i.version,o.version))[0]??null:null}function Jr({registry:e="https://registry.npmjs.org/",fetchImpl:t=fetch,signal:r,download:n=j,previous:s}){let i=new Map;return async(o,a)=>{let c=`${o}@${a}`;if(i.has(c))return i.get(c);let f=Uo(s,o,a),d=await n(o,f?.version??a,{registry:e,fetchImpl:t,signal:r});if(f&&d.integrity!==f.integrity)throw new Error(`${d.id} no longer matches the integrity recorded in the lock`);return i.set(c,d),d}}var Zr=P(T(),1),Kr=(e,t,r)=>new Error(`${e.name}@${e.version} requires peer ${t}@${r}; install a compatible root explicitly`);function Fo(e,t,r){if(e.manifest.peerDependenciesMeta?.[t]?.optional)return null;throw Kr(e,t,r)}function Go(e,[t,r],{nodes:n,roots:s}){let i=s[t]?.id??e.dependencies[t];if(!i)return Fo(e,t,r);if(!Zr.default.satisfies(n[i].version,r))throw Kr(e,t,r);return i}function zo(e,t){for(let r of Object.entries(e.manifest.peerDependencies??{})){let n=Go(e,r,t);n&&(e.dependencies[r[0]]=n)}}function Qr(e,t){for(let r of Object.values(e))zo(r,{nodes:e,roots:t})}var en=P(T(),1);function Xo(e,t){return!Ue(t.name)||!en.default.valid(t.version)?!1:e===ue(t.name,t.version)}function Mo(e){return e.integrity?.startsWith("sha512-")?e.key===Fe(e.name,e.version,e.integrity):!1}function Vo(e,t,r){if(!Xo(t,r)||!Mo(r))throw new Error("Invalid locked package");for(let n of r.files)k(n);if(Object.values(r.dependencies).some(n=>!e.packages[n]))throw new Error("Dangling locked dependency")}function _o(e){return e?.format!==1?!1:!!e.roots&&!!e.packages}function Ge(e){if(!_o(e))throw new Error("Unsupported package lock");for(let[t,r]of Object.entries(e.packages))Vo(e,t,r);if(Object.values(e.roots).some(t=>!e.packages[t.id]))throw new Error("Dangling locked root");return e}function Bo(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 Ho(e,t){let r={};for(let n of e){let{name:s,version:i}=W(n);r[s]={requested:i||"latest",id:await t(s,i||"latest")}}return r}async function tn(e,t={}){let r=Jr(t),n={nodes:{},downloads:new Map,total:0},s=async(o,a)=>{t.signal?.throwIfAborted();let c=await r(o,a);if(n.nodes[c.id])return c.id;Bo(n,o,c);for(let[f,d]of Object.entries(c.manifest.dependencies??{}).sort())n.nodes[c.id].dependencies[f]=await s(f,d);return c.id},i=await Ho(e,s);return Qr(n.nodes,i),{lock:{format:1,registry:t.registry??"https://registry.npmjs.org/",roots:i,packages:n.nodes},downloads:n.downloads}}function ze(e){return!e||typeof e!="object"?!1:!Array.isArray(e)}var N="webfront.project.json",_=1,Xe=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,Wo=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,Yo=/^[0-9A-Za-z.+\-^~<>=*| ]{1,128}$/,rn=/^[A-Za-z0-9][A-Za-z0-9:_.-]{0,63}$/,Me=/^[A-Za-z_][A-Za-z0-9_]*$/,nn=["format","name","version","dependencies","registry","scripts","entries","providers","test","permissions"],Jo=["files","publish","fetch"],g=e=>{throw new Error(`${N}: ${e}`)};function b(e,t){return ze(e)||g(`${t} must be an object`),e}function Ve(e,t,r){for(let n of Object.keys(e))t.includes(n)||g(`unknown key "${n}" in ${r}`)}function pe(e,t){typeof e!="string"&&g(`${t} must be a project path`);try{return k(e)}catch{return g(`${t} is not a safe project-relative path: ${e}`)}}function sn(e,t){return(!Array.isArray(e)||e.length>256)&&g(`${t} must be an array of at most 256 paths`),e.map((r,n)=>pe(r,`${t}[${n}]`))}function Zo(e){let t=b(e,"dependencies");for(let[r,n]of Object.entries(t))Xe.test(r)||g(`invalid npm package name "${r}"`),(typeof n!="string"||!Yo.test(n)||n!==n.trim())&&g(`invalid version range for "${r}"`);return t}function Ko(e){if(typeof e!="string"&&g("registry must be a URL"),e.startsWith("/")&&!e.startsWith("//"))return e;let t;try{t=new URL(e)}catch{return g("registry must be an https URL or an absolute path")}return t.protocol!=="https:"&&g("registry must use https"),e}function Qo(e){let t=b(e,"scripts");for(let[r,n]of Object.entries(t))(!rn.test(r)||typeof n!="string"||!n||n.length>1024)&&g(`invalid script "${r}"`);return t}function ea(e){let t=b(e,"entries");for(let[r,n]of Object.entries(t))rn.test(r)||g(`invalid entry name "${r}"`),pe(n,`entries.${r}`);return t}function ta(e,t){let r=b(e,"providers");for(let[n,s]of Object.entries(r))Me.test(n)||g(`invalid provider name "${n}"`),b(s,`providers.${n}`),Ve(s,["entry","output"],`providers.${n}`),typeof s.entry!="string"&&g(`providers.${n}.entry must name an entry or a path`),Object.hasOwn(t,s.entry)||pe(s.entry,`providers.${n}.entry`),pe(s.output,`providers.${n}.output`).endsWith(".hpp")||g(`providers.${n}.output must be a .hpp file`);return r}function ra(e){let t=b(e,"test");return Ve(t,["specs"],"test"),t.specs!==void 0&&sn(t.specs,"test.specs"),t}function na(e,t){let r;try{r=new URL(e)}catch{return g(`${t} must be an https origin`)}return(r.protocol!=="https:"||r.origin!==e)&&g(`${t} must be an https origin without a path`),e}function sa(e){let t=b(e,"permissions");for(let r of Object.keys(t))Jo.includes(r)||g(`unknown permission "${r}"`);for(let r of["files","publish"])t[r]!==void 0&&sn(t[r],`permissions.${r}`);return t.fetch!==void 0&&((!Array.isArray(t.fetch)||t.fetch.length>64)&&g("permissions.fetch must be an array of origins"),t.fetch.forEach((r,n)=>na(r,`permissions.fetch[${n}]`))),t}function ia(e){(typeof e.name!="string"||!Xe.test(e.name))&&g("name must be a lower-case npm package name"),(typeof e.version!="string"||!Wo.test(e.version))&&g("version must be a semantic version")}function oa(e){e.format!==_&&(Number.isInteger(e.format)&&e.format>_&&g(`format ${e.format} is not supported by this environment (it reads format ${_}); update the environment`),g(`format must be ${_}`))}function B(e){b(e,"the manifest"),oa(e),Ve(e,nn,"the manifest"),ia(e);let t=e.entries===void 0?{}:ea(e.entries);return{...e,dependencies:e.dependencies===void 0?{}:Zo(e.dependencies),entries:t,providers:e.providers===void 0?{}:ta(e.providers,t),...e.registry===void 0?{}:{registry:Ko(e.registry)},...e.scripts===void 0?{}:{scripts:Qo(e.scripts)},...e.test===void 0?{}:{test:ra(e.test)},...e.permissions===void 0?{}:{permissions:sa(e.permissions)}}}function _e(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return g("not valid JSON")}return{source:t,manifest:B(t)}}function zc(e){return _e(e).manifest}function Be(e){let t={};for(let r of nn)e[r]!==void 0&&(t[r]=e[r]);return JSON.stringify(t,null,2)+` +`}function on(e){return{format:_,name:e,version:"0.1.0",dependencies:{}}}function an(e){let r=(String(e??"").split("/").filter(Boolean).pop()??"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[^a-z0-9]+/,"").replace(/-+$/,"");return Xe.test(r)?r:"webfront-app"}async function he(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 He=P(T(),1);var C="webfront-packages.lock.json",de=".webfront/developer/packages",aa=new TextDecoder,ca=new TextEncoder,un="No webfront.project.json: run wf init",me="The lock does not match the dependencies of webfront.project.json; run wf install --update to resolve them again";async function cn(e,t){try{return await ae(e,t)}catch(r){if(r.message.includes("Cannot read project file:"))return null;throw r}}function la(e,t,r){return t?r===t.requested?!0:He.default.validRange(r)!==null&&He.default.satisfies(e.packages[t.id].version,r):!1}function ua(e,t){let r=Object.keys(t);return r.length===Object.keys(e.roots).length&&r.every(n=>la(e,e.roots[n],t[n]))}function fa(e,t,r){return e?t?t.manifestDigest===void 0?ua(t,e.dependencies)?"legacy":"desynchronized":t.manifestDigest===r?"consistent":"desynchronized":"unlocked":"no-manifest"}async function We(e){let t=await S(e,"state",`${N} +${C}`),r=await cn(e,N),n=await cn(e,C),{source:s,manifest:i}=r?_e(r):{source:null,manifest:null},o=n?Ge(JSON.parse(aa.decode(n))):null,a=i?await he(i.dependencies):null;return{manifest:i,source:s,lock:o,token:t,status:fa(i,o,a),digest:a}}var Bc=e=>e.status==="desynchronized"?`Warning: ${me}.\r +`:"";async function fn(e,t,r,{signal:n}={}){let s=[];try{for(let[i,o]of t){n?.throwIfAborted();let a=await S(e,"begin",i,!1);s.push(a),await De(e,{id:a,path:"output",bytes:o},n)}n?.throwIfAborted(),await S(e,"commitGroup",s.join(` +`),`${N} +${C}`,r.token)}catch(i){for(let o of s)await S(e,"abort",o).catch(()=>{});throw i}}function ln(e,t,r){let n=e?.entries??{};if(t!==void 0)return Object.hasOwn(n,t)?n[t]:t;if(Object.hasOwn(n,"main"))return n.main;let s=Object.keys(n);if(s.length===1)return n[s[0]];throw new Error(`Usage: ${r} (declare entries.main in ${N} to omit the entry)`)}function Hc(e,[t,r,n,...s]){if(t&&Object.hasOwn(e?.providers??{},t)&&r===void 0){let o=e.providers[t];return{entry:ln(e,o.entry),output:o.output,className:t}}if(!t||r!=="--output"||s.length||!n?.endsWith(".hpp"))throw new Error("wf embed requires or --output ");let i=n.split("/").pop().slice(0,-4);if(!Me.test(i))throw new Error(`wf embed: ${i} is not a C++ class name; name the output .hpp`);return{entry:ln(e,t),output:n,className:i}}var Ee=e=>ca.encode(e);var Ye=P(T(),1);var dn=e=>{let{name:t,version:r}=W(e);return[t,r||void 0]};function pa(e,t){let{version:r}=e.packages[t.id];return!(Ye.default.valid(t.requested)!==null)&&t.requested!=="latest"&&Ye.default.validRange(t.requested)!==null?t.requested:`^${r}`}async function el(e,[t,...r],{signal:n}={}){if(r.length)throw new Error("Usage: wf init [name]");let{lock:s}=await We(e),i=on(t??an(""));s&&(i.dependencies=Object.fromEntries(Object.entries(s.roots).map(([a,c])=>[a,pa(s,c)]))),B(i),await ce(e,N,new Map([["output",Ee(Be(i))]]),{directory:!1,replace:!1,signal:n});let o=s?` with the ${Object.keys(i.dependencies).length} dependencies of ${C}`:"";return`Created ${N}${o}. Add libraries with wf install .`}function ha(e,t){let r={...e.manifest.dependencies},n=new Set;for(let s of t){let[i,o]=dn(s);r[i]=o??"latest",o&&o!=="latest"&&n.add(i)}return B({...e.source,dependencies:r}),{dependencies:r,explicit:n}}function da(e,t){let r={...e.source,dependencies:t};return B(r),r}function ma({dependencies:e,explicit:t},r,n){let s={...e};for(let i of n){let o=dn(i)[0];t.has(o)||(s[o]=`^${r.packages[r.roots[o].id].version}`)}return s}async function Ea(e,t,r){let n=Object.entries(e).map(([o,a])=>`${o}@${a}`),{lock:s,downloads:i}=await tn(n,{registry:r.registry,signal:r.signal,fetchImpl:r.fetchImpl,previous:t,download:async(...o)=>(r.progress(`Resolving ${o[0]}@${o[1]}`),j(...o))});return{lock:s,downloads:i}}async function wa(e,t,r,{signal:n,progress:s}){for(let[i,o]of r)s(`Storing ${i}`),await ce(e,`${de}/${t.packages[i].key}`,o,{signal:n})}async function $a(e,t){try{return await ae(e,`${de}/${t.key}/package.json`),!0}catch{return!1}}async function ga(e,t,{signal:r,progress:n,fetchImpl:s}){let i=0;for(let[o,a]of Object.entries(t.packages)){if(r?.throwIfAborted(),await $a(e,a))continue;n(`Restoring ${o}`);let c=await j(a.name,a.version,{registry:t.registry,fetchImpl:s,signal:r});if(c.integrity!==a.integrity)throw new Error(`${o} no longer matches the integrity recorded in the lock`);await ce(e,`${de}/${a.key}`,c.files,{signal:r}),i++}return i}function ya(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 pn(e,t,{manifest:r,lock:n},s){let i=new Map([[C,Ee(JSON.stringify(n,null,2)+` +`)]]);r&&i.set(N,Ee(Be(r))),await fn(e,i,t,s)}var hn=async(e,t)=>({format:e.format,manifestDigest:await he(t),...e});async function tl(e,t,{registry:r,signal:n,progress:s=()=>{},fetchImpl:i=fetch}){let{update:o,specs:a}=ya(t),c=await We(e);if(!c.manifest)throw new Error(un);let f={registry:c.manifest.registry??r,signal:n,fetchImpl:i,progress:s};if(a.length&&o)throw new Error("Usage: wf install --update does not take packages");if(a.length&&c.status==="desynchronized")throw new Error(me);if(!a.length&&!o&&c.status==="desynchronized")throw new Error(me);let d=c.status==="consistent"||c.status==="legacy";if(!a.length&&!o&&d){let Ze=await ga(e,c.lock,{signal:n,progress:s,fetchImpl:f.fetchImpl});if(c.status==="consistent")return{lock:c.lock,restored:Ze};let Ke=await hn(c.lock,c.manifest.dependencies);return await pn(e,c,{manifest:null,lock:Ke},{signal:n}),{lock:Ke,restored:Ze}}let p=ha(c,a),w=d&&!o?c.lock:void 0,h=await Ea(p.dependencies,w,f),H=ma(p,h.lock,a);await wa(e,h.lock,h.downloads,{signal:n,progress:s});let Je=await hn(h.lock,H),mn=a.length?da(c,H):null;return await pn(e,c,{manifest:mn,lock:Je},{signal:n}),{lock:Je,restored:0}}export{he as dependenciesDigest,me as desynchronized,j as downloadPackage,Hc as embedTarget,Wo as exactVersion,Me as identifier,el as initProject,tl as install,We as loadProject,C as lockPath,ua as locksDependencies,_ as manifestFormat,an as manifestName,N as manifestPath,on as newManifest,un as noManifest,Xe as npmName,de as packageRoot,zc as parseManifest,fn as publishTogether,_e as readManifest,ln as resolveEntry,tn as resolvePackages,k as safePackagePath,Be as serializeManifest,Bc as syncNotice,Ee as textBytes,Ge as validateLock,B as validateManifest}; diff --git a/js/developer/environment/pins.mjs b/js/developer/environment/pins.mjs index 34c73ea0..b2941935 100644 --- a/js/developer/environment/pins.mjs +++ b/js/developer/environment/pins.mjs @@ -3,7 +3,10 @@ import semver from 'semver'; import {downloadPackage} from './registry.mjs'; // The installed version satisfying a range, so that a later install never moves or replaces it silently. +// A root requested by a dist-tag (a@beta) keeps the version the tag had when it was resolved. function lockedNode(previous, name, range) { + const root = previous?.roots?.[name]; + if (root?.requested === range && previous.packages[root.id]) return previous.packages[root.id]; if (!semver.validRange(range)) return null; const candidates = Object.values(previous?.packages ?? {}).filter(node => node.name === name && semver.satisfies(node.version, range)); return candidates.sort((a, b) => semver.rcompare(a.version, b.version))[0] ?? null; diff --git a/js/developer/environment/project.mjs b/js/developer/environment/project.mjs new file mode 100644 index 00000000..70b9d446 --- /dev/null +++ b/js/developer/environment/project.mjs @@ -0,0 +1,112 @@ +// The project as the wf commands see it: manifest, lock, whether they agree, and their joint publication. +import {call, readProject, writeChunks} from './io.mjs'; +import semver from 'semver'; +import {manifestPath, readManifest, dependenciesDigest, identifier} from './manifest.mjs'; +import {validateLock} from './lock.mjs'; + +export const lockPath = 'webfront-packages.lock.json'; +export const packageRoot = '.webfront/developer/packages'; + +const decoder = new TextDecoder(); +const encoder = new TextEncoder(); + +export const noManifest = 'No webfront.project.json: run wf init'; +export const desynchronized = 'The lock does not match the dependencies of webfront.project.json; run wf install --update to resolve them again'; + +async function readOptional(bridge, path) { + try { return await readProject(bridge, path); } + catch (error) { + if (error.message.includes('Cannot read project file:')) return null; + throw error; + } +} + +// Whether a locked root satisfies a manifest range: a range or exact version by semver, a dist-tag by the name it was resolved with. +function satisfiesRoot(lock, root, range) { + if (!root) return false; + if (range === root.requested) return true; + return semver.validRange(range) !== null && semver.satisfies(lock.packages[root.id].version, range); +} + +/** Whether a lock without a manifest digest (written before the manifest existed) resolves exactly these dependencies. */ +export function locksDependencies(lock, dependencies) { + const names = Object.keys(dependencies); + return names.length === Object.keys(lock.roots).length && + names.every(name => satisfiesRoot(lock, lock.roots[name], dependencies[name])); +} + +function statusOf(manifest, lock, digest) { + if (!manifest) return 'no-manifest'; + if (!lock) return 'unlocked'; + if (lock.manifestDigest === undefined) return locksDependencies(lock, manifest.dependencies) ? 'legacy' : 'desynchronized'; + return lock.manifestDigest === digest ? 'consistent' : 'desynchronized'; +} + +/** + * Reads the manifest and the lock and compares them. `token` identifies the exact state that was read: + * a publication prepared from it is refused if either file changed in the meantime. `source` is the + * manifest as written, `manifest` the validated one with its defaults. + * no-manifest: no webfront.project.json; unlocked: no lock, so no installed graph; + * consistent: the lock was resolved from the manifest's current dependencies; + * legacy: a lock written before the manifest, without its digest, whose roots satisfy the dependencies: + * it is used as a consistent one, and wf install records the digest; + * desynchronized: the dependencies changed since; nothing is resolved implicitly. + */ +export async function loadProject(bridge) { + const token = await call(bridge, 'state', `${manifestPath}\n${lockPath}`); + const manifestBytes = await readOptional(bridge, manifestPath); + const lockBytes = await readOptional(bridge, lockPath); + const {source, manifest} = manifestBytes ? readManifest(manifestBytes) : {source: null, manifest: null}; + const lock = lockBytes ? validateLock(JSON.parse(decoder.decode(lockBytes))) : null; + const digest = manifest ? await dependenciesDigest(manifest.dependencies) : null; + return {manifest, source, lock, token, status: statusOf(manifest, lock, digest), digest}; +} + +/** A line to put before the output of a command that reads a lock which no longer matches its manifest. */ +export const syncNotice = project => project.status === 'desynchronized' ? `Warning: ${desynchronized}.\r\n` : ''; + +/** + * Publishes the given files (path -> bytes) as one change, on condition that the project is still in the + * state `project` was read in. A refusal means another installation finished first: run the command again. + */ +export async function publishTogether(bridge, files, project, {signal} = {}) { + const ids = []; + try { + for (const [path, bytes] of files) { + signal?.throwIfAborted(); + const id = await call(bridge, 'begin', path, false); + ids.push(id); + await writeChunks(bridge, {id, path: 'output', bytes}, signal); + } + signal?.throwIfAborted(); + await call(bridge, 'commitGroup', ids.join('\n'), `${manifestPath}\n${lockPath}`, project.token); + } catch (error) { + for (const id of ids) await call(bridge, 'abort', id).catch(() => {}); + throw error; + } +} + +/** An entry given by its name in the manifest's "entries", or as a project path. */ +export function resolveEntry(manifest, argument, command) { + const entries = manifest?.entries ?? {}; + if (argument !== undefined) return Object.hasOwn(entries, argument) ? entries[argument] : argument; + if (Object.hasOwn(entries, 'main')) return entries.main; + const names = Object.keys(entries); + if (names.length === 1) return entries[names[0]]; + throw new Error(`Usage: ${command} (declare entries.main in ${manifestPath} to omit the entry)`); +} + +// wf embed : the class is the provider's name. wf embed --output : the class is the file name. +export function embedTarget(manifest, [first, flag, output, ...extra]) { + if (first && Object.hasOwn(manifest?.providers ?? {}, first) && flag === undefined) { + const provider = manifest.providers[first]; + return {entry: resolveEntry(manifest, provider.entry), output: provider.output, className: first}; + } + if (!first || flag !== '--output' || extra.length || !output?.endsWith('.hpp')) + throw new Error('wf embed requires or --output '); + const className = output.split('/').pop().slice(0, -4); + if (!identifier.test(className)) throw new Error(`wf embed: ${className} is not a C++ class name; name the output .hpp`); + return {entry: resolveEntry(manifest, first), output, className}; +} + +export const textBytes = text => encoder.encode(text); diff --git a/js/developer/environment/recipe.mjs b/js/developer/environment/recipe.mjs index 2c1c0b6a..f0570e75 100644 --- a/js/developer/environment/recipe.mjs +++ b/js/developer/environment/recipe.mjs @@ -1,33 +1,20 @@ -// A starter's webfront.project.json: the entry file, exact dependency versions and the provider name. +// A starter's webfront.project.json: the project manifest it ships, with exact dependency versions. import {safePackagePath} from './paths.mjs'; -import {isPlainObject} from './entry.mjs'; - -const decoder = new TextDecoder(); -const npmName = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/; -const exactVersion = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/; +import {parseManifest, manifestPath, exactVersion, npmName} from './manifest.mjs'; function requireExactDependencies(dependencies) { - if (!isPlainObject(dependencies)) throw new Error('Invalid starter project recipe'); for (const [name, version] of Object.entries(dependencies)) - if (!npmName.test(name) || typeof version !== 'string' || !exactVersion.test(version)) + if (!npmName.test(name) || !exactVersion.test(version)) throw new Error('Starter dependencies must name exact npm versions'); } -function validProvider(provider) { - if (typeof provider !== 'string') return false; - return /^[A-Za-z_][A-Za-z0-9_]*$/.test(provider); -} - -function hasEntry(recipe, files) { - if (typeof recipe.entry !== 'string') return false; - return files.has(safePackagePath(recipe.entry)); -} - +// A starter has a main entry present in its files and, optionally, one provider. export function recipeOf(files) { - const recipe = JSON.parse(decoder.decode(files.get('webfront.project.json'))); - if (recipe.format !== 1 || !hasEntry(recipe, files)) throw new Error('Invalid starter project recipe'); - requireExactDependencies(recipe.dependencies); - if (recipe.provider !== undefined && !validProvider(recipe.provider)) - throw new Error('Invalid starter provider name'); - return recipe; + if (!files.has(manifestPath)) throw new Error('Invalid starter project recipe'); + const manifest = parseManifest(files.get(manifestPath)); + if (!Object.hasOwn(manifest.entries, 'main') || !files.has(safePackagePath(manifest.entries.main))) + throw new Error('Invalid starter project recipe'); + requireExactDependencies(manifest.dependencies); + const [provider] = Object.keys(manifest.providers); + return {...manifest, entry: manifest.entries.main, provider, output: manifest.providers[provider]?.output}; } diff --git a/js/developer/environment/runtime.mjs b/js/developer/environment/runtime.mjs index 69228ad8..e049b588 100644 --- a/js/developer/environment/runtime.mjs +++ b/js/developer/environment/runtime.mjs @@ -1,15 +1,16 @@ import {Terminal} from '../../../third_party/xterm/xterm.mjs'; import {FitAddon} from '../../../third_party/xterm/addon-fit.mjs'; import {LineEditor, tokenize} from '../components/terminal/terminal.mjs'; -import {resolvePackages, validateLock, downloadPackage} from './packages.mjs'; +import {validateLock} from './packages.mjs'; import {readProject, publish} from './io.mjs'; import {createStarter} from './starter.mjs'; +import {install, initProject} from './installer.mjs'; +import {loadProject, syncNotice, resolveEntry, embedTarget, lockPath, packageRoot} from './project.mjs'; import {generateProvider, applicationPage} from './embed.mjs'; const encoder = new TextEncoder(); const decoder = new TextDecoder(); -const lockPath = 'webfront-packages.lock.json'; -const packageRoot = '.webfront/developer/packages'; +export {lockPath, packageRoot}; export async function readLock(bridge, optional = false) { try { return validateLock(JSON.parse(decoder.decode(await readProject(bridge, lockPath)))); } catch (error) { @@ -19,35 +20,8 @@ export async function readLock(bridge, optional = false) { } } -const splitSpec = spec => { - const at = spec.indexOf('@', spec.startsWith('@') ? 1 : 0); - return at < 0 ? [spec, 'latest'] : [spec.slice(0, at), spec.slice(at + 1)]; -}; - -// The installed roots keep their exact versions unless a requested spec replaces them. -function requestedRoots(previous, specs) { - const requested = new Map(Object.entries(previous.roots).map(([name, root]) => [name, previous.packages[root.id].version])); - for (const spec of specs) requested.set(...splitSpec(spec)); - return [...requested].map(([name, version]) => `${name}@${version}`); -} - const textFile = text => new Map([['output', encoder.encode(text)]]); - -export async function install(bridge, specs, {registry, signal, progress = () => {}, fetchImpl = fetch}) { - if (!specs.length) throw new Error('Usage: wf install [@version] ...'); - const previous = await readLock(bridge, true); - const {lock, downloads} = await resolvePackages(requestedRoots(previous, specs), { - registry, signal, fetchImpl, previous, - download: async (...args) => { progress(`Resolving ${args[0]}@${args[1]}`); return downloadPackage(...args); }, - }); - for (const [id, files] of downloads) { - progress(`Storing ${id}`); - await publish(bridge, `${packageRoot}/${lock.packages[id].key}`, files, {signal}); - } - // The lock file is the installation commit point. A failed install may leave unused cache files. - await publish(bridge, lockPath, textFile(JSON.stringify(lock, null, 2) + '\n'), {directory: false, signal}); - return lock; -} +export {install}; async function readPackages(bridge, lock, signal) { const packages = {}; @@ -117,37 +91,42 @@ async function create([starter, directory, ...extra], {bridge, config, signal}) return createStarter(bridge, config, [starter, directory ?? 'ui'], {signal}); } -async function installCommand(specs, {bridge, config, signal, write = () => {}}) { - const lock = await install(bridge, specs, {registry: config.registry, signal, progress: text => write(text + '\r\n')}); - return `Installed ${Object.keys(lock.packages).length} packages. Lock: ${lockPath}`; +const init = (args, {bridge, signal}) => initProject(bridge, args, {signal}); + +async function installCommand(args, {bridge, config, signal, write = () => {}}) { + const {lock, restored} = await install(bridge, args, {registry: config.registry, signal, progress: text => write(text + '\r\n')}); + const count = Object.keys(lock.packages).length; + return restored || !args.length ? `Installed ${count} packages (${restored} restored). Lock: ${lockPath}` : `Installed ${count} packages. Lock: ${lockPath}`; } -async function preview([entry], {bridge, signal, preview: frame}) { - if (!entry) throw new Error('Usage: wf preview '); +async function preview(args, {bridge, signal, preview: frame}) { + if (args.length > 1) throw new Error('Usage: wf preview [entry.tsx|name]'); + const project = await loadProject(bridge); + const entry = resolveEntry(project.manifest, args[0], 'wf preview '); const result = await compile(bridge, entry, signal); await publish(bridge, '.webfront/developer/preview', result.files, {signal}); frame.hidden = false; // Replace transient builds without accumulating browser session history. frame.contentWindow.location.replace(`/webfront/developer/preview/index.html?build=${Date.now()}`); - return 'Preview ready.'; + return syncNotice(project) + 'Preview ready.'; } -async function embed([entry, flag, output, ...extra], {bridge, signal}) { - if (!entry) throw new Error('Usage: wf embed --output '); - if (flag !== '--output' || extra.length || !output?.endsWith('.hpp')) throw new Error('wf embed requires --output '); +async function embed(args, {bridge, signal}) { + const project = await loadProject(bridge); + const {entry, output, className} = embedTarget(project.manifest, args); const result = await compile(bridge, entry, signal); - const className = output.split('/').pop().slice(0, -4); await publish(bridge, output, textFile(generateProvider(result.files, className, result.notices)), {directory: false, signal}); - return `Generated ${output}. Use webfront::fs::${className} and recompile the application.`; + return `${syncNotice(project)}Generated ${output}. Use webfront::fs::${className} and recompile the application.`; } async function list(_args, {bridge}) { - const lock = await readLock(bridge, true); - return Object.keys(lock.packages).sort().join('\n') || 'No installed packages.'; + const project = await loadProject(bridge); + const names = Object.keys(project.lock?.packages ?? {}).sort().join('\n'); + return syncNotice(project) + (names || 'No installed packages.'); } -const help = () => 'wf create [directory]\nwf install [@version] ...\nwf list\nwf preview \nwf embed --output \nCtrl+C interrupts a browser command. No system shell is exposed.'; -const commands = {create, install: installCommand, preview, embed, list, help}; +const help = () => 'wf init [name]\nwf create [directory]\nwf install [--update] [[@range] ...]\nwf list\nwf preview [entry.tsx|name]\nwf embed | --output \nCtrl+C interrupts a browser command. No system shell is exposed.'; +const commands = {init, create, install: installCommand, preview, embed, list, help}; export async function execute(args, context) { const [command = 'help', ...rest] = args; diff --git a/js/developer/environment/starter.mjs b/js/developer/environment/starter.mjs index d59ecb03..056b3da6 100644 --- a/js/developer/environment/starter.mjs +++ b/js/developer/environment/starter.mjs @@ -38,5 +38,6 @@ export async function createStarter(bridge, config, [name, destination = 'ui'], // A starter must never overwrite an existing directory, including a symlink or partial project. await publish(bridge, destination, files, {signal, replace: false}); const install = Object.entries(recipe.dependencies).map(([pkg, version]) => `${pkg}@${version}`).join(' '); - return `Created ${destination}.\nwf install ${install}\nwf preview ${destination}/${recipe.entry}\nwf embed ${destination}/${recipe.entry} --output generated/${recipe.provider ?? 'PiUI'}.hpp`; + const output = recipe.output ?? `generated/${recipe.provider ?? 'PiUI'}.hpp`; + return `Created ${destination}.\nwf init\nwf install ${install}\nwf preview ${destination}/${recipe.entry}\nwf embed ${destination}/${recipe.entry} --output ${output}`; } diff --git a/js/developer/tools/PUBLISHING.md b/js/developer/tools/PUBLISHING.md index a45a3f68..20b372e7 100644 --- a/js/developer/tools/PUBLISHING.md +++ b/js/developer/tools/PUBLISHING.md @@ -11,12 +11,15 @@ The package names in their manifests are identifiers, not a requirement to own o npm ci --prefix js/developer/vendor --ignore-scripts node js/developer/tools/build.mjs build-distribution --refresh-bootstrap node js/developer/tools/fixtures.mjs build-distribution -node --test js/developer/tools/check.mjs js/developer/tools/distribution-check.mjs +node --test js/developer/tools/check.mjs js/developer/tools/distribution-check.mjs js/developer/tools/manifest-check.mjs node js/developer/tools/site.mjs build-distribution build-developer-site ``` -Review and commit the updated checked-in bootstrap bundles, checksums and -`include/webfront/system/DeveloperReleaseData.hpp`. The header pins the exact environment archive and URL. +Review and commit the updated checked-in bootstrap bundles and checksums. Regenerating +`include/webfront/system/DeveloperReleaseData.hpp` is part of the release procedure ("Pinning a new version"): the header +is committed on a release branch before the tag, because the publication workflow requires it to match the build, and it +reaches the default branch only after the deployed files are verified, so that the default bootstrap never names an +archive that is unavailable. The header pins the exact environment archive and URL. The environment pins the starter archive in turn. `provision.json` is informational; applications do not discover a replacement trust hash from that remote file or follow `latest` at startup. @@ -24,6 +27,19 @@ The static branch preserves every version. Republishing identical bytes is allow published version with different bytes fails. Increment `distribution.json` before publishing any changed environment, starter, public URL or provisioning configuration. +## Pinning a new version + +`distribution.json` names the version under development; `DeveloperReleaseData.hpp` pins the last version that is +published. Pull requests and branch pushes therefore require the header to match a fresh build only when both name +the same version; a publication (a `developer-v*` tag or a dispatch with `publish=true`) always requires it. When the +sources are ahead, `pin-check.mjs` requires the header to be exactly the one generated for its version and the deployed +archive at its URL to have its integrity. + +1. Merge the changes with the header still on the previous version. +2. On a release branch, run `build.mjs build-distribution --refresh-bootstrap` and commit the new header. +3. Tag `developer-v` on that commit; the workflow publishes the site. +4. Verify the deployed files (below), then merge the release branch so the default bootstrap points to the new version. + ## One-time Pages configuration The repository's Pages source must be the **gh-pages branch, root directory**, with branch-based diff --git a/js/developer/tools/RELEASE_NOTES.md b/js/developer/tools/RELEASE_NOTES.md index 9186e3b1..2fbad3be 100644 --- a/js/developer/tools/RELEASE_NOTES.md +++ b/js/developer/tools/RELEASE_NOTES.md @@ -7,3 +7,5 @@ Download through the version-pinned GitHub Pages URLs in the bootstrap configura The environment includes the terminal, npm resolver, esbuild/WASM compiler, embedding tools and dependency notices. These packages are experimental; browser packages only, without installation scripts, native modules or Node API shims. Version 0.4.0 updates the Life starter text for a developer audience. The simulation and bridge contract are unchanged. + +Version 0.5.0 introduces the project manifest `webfront.project.json`: `wf init`, manifest-driven `wf install` (with `--update`), `wf preview` and `wf embed`, and a lock that records the digest of the manifest dependencies. `wf install` now requires a manifest. The starters ship their own manifest. diff --git a/js/developer/tools/build.mjs b/js/developer/tools/build.mjs index c79d884a..55643a31 100644 --- a/js/developer/tools/build.mjs +++ b/js/developer/tools/build.mjs @@ -47,8 +47,9 @@ for (const [name, provider] of [['pi', 'PiUI'], ['life', 'LifeUI']]) { const starterFiles = new Map(); for (const file of ['main.tsx', 'style.css']) starterFiles.set(`package/${file}`, await readFile(resolve(root, `${name === 'life' ? 'examples/life/ui' : 'js/developer/tools/starters/pi'}/${file}`))); - const recipe = {format: 1, name, provider, entry: 'main.tsx', dependencies: { - react: dependencies.react, 'react-dom': dependencies['react-dom']}}; + const recipe = {format: 1, name: `${name}-starter`, version, dependencies: { + react: dependencies.react, 'react-dom': dependencies['react-dom']}, + entries: {main: 'main.tsx'}, providers: {[provider]: {entry: 'main', output: `generated/${provider}.hpp`}}}; starterFiles.set('package/webfront.project.json', Buffer.from(JSON.stringify(recipe, null, 2) + '\n')); starterFiles.set('package/package.json', Buffer.from(JSON.stringify({name: `@webfront/${name}-starter`, version, private: true, webfront: {kind: 'starter', entry: 'main.tsx'}}, null, 2) + '\n')); @@ -74,11 +75,11 @@ await writeFile(resolve(output, 'DeveloperReleaseData.hpp'), header); if (refresh) { const bootstrap = resolve(root, 'js/core/bootstrap/bootstrap.bundle.mjs'); await build({...options, entryPoints: ['js/developer/environment/bootstrap-entry.mjs'], outfile: bootstrap}); - await build({...options, entryPoints: ['js/developer/environment/packages.mjs'], outfile: resolve(root, 'js/developer/environment/packages.bundle.mjs')}); + await build({...options, entryPoints: ['js/developer/environment/packages-entry.mjs'], outfile: resolve(root, 'js/developer/environment/packages.bundle.mjs')}); await copyFile(resolve(root, 'js/developer/vendor/node_modules/semver/LICENSE'), resolve(root, 'js/developer/environment/PACKAGES-LICENSE.txt')); await writeFile(resolve(root, 'include/webfront/system/DeveloperReleaseData.hpp'), header); const inputs = {}; - for (const path of ['js/developer/environment/bootstrap.mjs', 'js/developer/environment/bootstrap-entry.mjs', 'js/developer/environment/packages.mjs', 'js/developer/environment/starter.mjs', 'js/developer/environment/paths.mjs', 'js/developer/environment/runtime.mjs', 'js/developer/environment/compiler.mjs', 'js/developer/environment/bundler.mjs', 'js/developer/environment/entry.mjs', 'js/developer/environment/conditions.mjs', 'js/developer/environment/io.mjs', 'js/developer/environment/recipe.mjs', 'js/developer/environment/registry.mjs', 'js/developer/environment/archive.mjs', 'js/developer/environment/lock.mjs', 'js/developer/environment/pins.mjs', 'js/developer/environment/peers.mjs', 'js/developer/environment/resolve.mjs', 'js/developer/environment/embed.mjs', 'js/developer/tools/starters/pi/main.tsx', 'js/developer/tools/starters/pi/style.css', 'examples/life/ui/main.tsx', 'examples/life/ui/style.css', 'js/developer/components/tools/wf.mjs', 'js/developer/tools/distribution.json', 'js/developer/tools/build.mjs', 'js/developer/tools/site.mjs', 'js/developer/tools/archive.mjs', 'js/developer/vendor/package-lock.json', 'js/core/bootstrap/bootstrap.bundle.mjs', 'js/developer/environment/packages.bundle.mjs', 'include/webfront/system/DeveloperReleaseData.hpp']) + for (const path of ['js/developer/environment/manifest.mjs', 'js/developer/environment/project.mjs', 'js/developer/environment/installer.mjs', 'js/developer/environment/packages-entry.mjs', 'js/developer/environment/bootstrap.mjs', 'js/developer/environment/bootstrap-entry.mjs', 'js/developer/environment/packages.mjs', 'js/developer/environment/starter.mjs', 'js/developer/environment/paths.mjs', 'js/developer/environment/runtime.mjs', 'js/developer/environment/compiler.mjs', 'js/developer/environment/bundler.mjs', 'js/developer/environment/entry.mjs', 'js/developer/environment/conditions.mjs', 'js/developer/environment/io.mjs', 'js/developer/environment/recipe.mjs', 'js/developer/environment/registry.mjs', 'js/developer/environment/archive.mjs', 'js/developer/environment/lock.mjs', 'js/developer/environment/pins.mjs', 'js/developer/environment/peers.mjs', 'js/developer/environment/resolve.mjs', 'js/developer/environment/embed.mjs', 'js/developer/tools/starters/pi/main.tsx', 'js/developer/tools/starters/pi/style.css', 'examples/life/ui/main.tsx', 'examples/life/ui/style.css', 'js/developer/components/tools/wf.mjs', 'js/developer/tools/distribution.json', 'js/developer/tools/build.mjs', 'js/developer/tools/site.mjs', 'js/developer/tools/archive.mjs', 'js/developer/vendor/package-lock.json', 'js/core/bootstrap/bootstrap.bundle.mjs', 'js/developer/environment/packages.bundle.mjs', 'include/webfront/system/DeveloperReleaseData.hpp']) inputs[path] = createHash('sha256').update(await readFile(resolve(root, path))).digest('hex'); await writeFile(resolve(root, 'js/developer/environment/bundles.json'), JSON.stringify(inputs, null, 2) + '\n'); for (const [source, name] of [['js/core/bootstrap/index.html', 'DeveloperIndexHtmlData'], ['js/core/bootstrap/bootstrap.bundle.mjs', 'DeveloperBootstrapData']]) diff --git a/js/developer/tools/distribution-check.mjs b/js/developer/tools/distribution-check.mjs index 35d90b8a..52f24f9b 100644 --- a/js/developer/tools/distribution-check.mjs +++ b/js/developer/tools/distribution-check.mjs @@ -11,10 +11,13 @@ import {createStarter} from '../environment/starter.mjs'; const encode = value => new TextEncoder().encode(typeof value === 'string' ? value : JSON.stringify(value)); const integrity = bytes => 'sha512-' + createHash('sha512').update(bytes).digest('base64'); +const recipe = (fields = {}) => ({format: 1, name: 'pi-starter', version: '0.1.0', dependencies: {react: '19.3.1'}, + entries: {main: 'main.tsx'}, ...fields}); + function starter(overrides = {}) { return compress(tar(new Map(Object.entries({ 'package/main.tsx': encode('export default function Pi() {}'), - 'package/webfront.project.json': encode({format: 1, entry: 'main.tsx', dependencies: {react: '19.3.1'}}), + 'package/webfront.project.json': encode(recipe()), ...overrides, })))); } @@ -27,14 +30,14 @@ test('starter integrity, recipes and archive paths are checked before any projec const config = {starters: {pi: {url: 'https://pages.test/developer/0.1.0/pi-starter.tgz', integrity: integrity(bytes)}}}; const fetchImpl = async () => new Response(bytes); const help = await createStarter(bridge, config, ['pi', 'ui'], {fetchImpl}); - assert.match(help, /wf install react@19.3.1/); + assert.match(help, /wf init\nwf install react@19.3.1/); assert.match(help, /wf preview ui\/main.tsx/); assert.equal(calls[0][0], 'webfront.developer.beginNew'); assert.equal(calls.at(-1)[0], 'webfront.developer.commit'); calls.length = 0; await assert.rejects(createStarter(bridge, {starters: {pi: {...config.starters.pi, integrity: integrity(encode('bad'))}}}, ['pi', 'ui'], {fetchImpl}), /Integrity check/); assert.equal(calls.length, 0); - for (const bytes of [starter({'package/../escape': encode('bad')}), starter({'package/webfront.project.json': encode({format: 1, entry: 'main.tsx', dependencies: {react: 'latest'}})})]) { + for (const bytes of [starter({'package/../escape': encode('bad')}), starter({'package/webfront.project.json': encode(recipe({dependencies: {react: 'latest'}}))})]) { await assert.rejects(createStarter(bridge, {starters: {pi: {...config.starters.pi, integrity: integrity(bytes)}}}, ['pi', 'ui'], {fetchImpl: async () => new Response(bytes)})); assert.equal(calls.length, 0); } @@ -107,8 +110,8 @@ test('bootstrap configuration is pinned and rejects unsafe version/base inputs', test('Life recipes select their generated provider and reject invalid provider names', async () => { globalThis.location = new URL('http://localhost:9002/'); try { - for (const provider of ['LifeUI', '../escape', ['LifeUI']]) { - const bytes = starter({'package/webfront.project.json': encode({format: 1, provider, entry: 'main.tsx', dependencies: {react: '19.3.1'}})}); + for (const provider of ['LifeUI', '../escape']) { + const bytes = starter({'package/webfront.project.json': encode(recipe({providers: {[provider]: {entry: 'main', output: `generated/${provider}.hpp`}}}))}); let writes = 0; const bridge = {cppFunction: () => async () => { writes++; return 'transaction'; }}; const config = {starters: {life: {url: '/life-starter.tgz', integrity: integrity(bytes)}}}; diff --git a/js/developer/tools/distribution.json b/js/developer/tools/distribution.json index 05e7397d..090ea9b8 100644 --- a/js/developer/tools/distribution.json +++ b/js/developer/tools/distribution.json @@ -1,4 +1,4 @@ { - "version": "0.4.1", + "version": "0.5.0", "baseUrl": "https://ambroise-leclerc.github.io/WebFront/" } diff --git a/js/developer/tools/manifest-check.mjs b/js/developer/tools/manifest-check.mjs new file mode 100644 index 00000000..5b284921 --- /dev/null +++ b/js/developer/tools/manifest-check.mjs @@ -0,0 +1,335 @@ +// Node tests of the project manifest, its agreement with the lock and the joint publication of both. +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import {createHash} from 'node:crypto'; +import {validateManifest, parseManifest, serializeManifest, manifestName, dependenciesDigest} from '../environment/manifest.mjs'; +import {install, initProject, loadProject, syncNotice, resolveEntry, embedTarget, lockPath, manifestPath} from '../environment/packages.bundle.mjs'; +import {compress} from '../environment/embed.mjs'; +import {tar} from './archive.mjs'; + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); +const encode = value => encoder.encode(typeof value === 'string' ? value : JSON.stringify(value)); +const integrity = bytes => 'sha512-' + createHash('sha512').update(bytes).digest('base64'); +const minimal = {format: 1, name: 'app', version: '0.1.0'}; + +test('a valid manifest receives its defaults and keeps a stable serialization', () => { + const manifest = validateManifest(minimal); + assert.deepEqual(manifest.dependencies, {}); + assert.deepEqual(manifest.entries, {}); + const full = {...minimal, dependencies: {react: '^19.0.0', '@scope/lib': '>=1.2.0 <2', tool: 'latest'}, registry: 'https://registry.test/', + scripts: {build: 'wf embed main'}, entries: {main: 'ui/main.tsx'}, + providers: {PiUI: {entry: 'main', output: 'generated/PiUI.hpp'}}, test: {specs: ['spec/a.mjs']}, + permissions: {files: ['ui'], publish: ['generated'], fetch: ['https://registry.npmjs.org']}}; + const text = serializeManifest(validateManifest(full)); + assert.deepEqual(JSON.parse(text), full); + assert.equal(serializeManifest(parseManifest(encode(text))), text); + assert.equal(manifestName('apps/My App'), 'my-app'); + assert.equal(manifestName(''), 'webfront-app'); +}); + +test('invalid manifests are explicit errors, never silent fallbacks', () => { + const cases = [ + [{...minimal, extra: 1}, /unknown key "extra"/], + [{name: 'app', version: '1.0.0'}, /format must be 1/], + [{...minimal, format: 2}, /format 2 is not supported/], + [{...minimal, name: 'Bad Name'}, /name must be/], + [{...minimal, version: 'one'}, /version must be/], + [{...minimal, dependencies: {react: 3}}, /invalid version range/], + [{...minimal, dependencies: {'../x': '1.0.0'}}, /invalid npm package name/], + [{...minimal, dependencies: {react: 'file:../react'}}, /invalid version range/], + [{...minimal, registry: 'http://insecure.test/'}, /registry must use https/], + [{...minimal, entries: {main: '../outside.tsx'}}, /safe project-relative path/], + [{...minimal, entries: {main: '/etc/passwd'}}, /safe project-relative path/], + [{...minimal, providers: {'not valid': {entry: 'a.tsx', output: 'a.hpp'}}}, /invalid provider name/], + [{...minimal, providers: {P: {entry: 'a.tsx', output: 'a.js'}}}, /\.hpp file/], + [{...minimal, providers: {P: {entry: 'a.tsx', output: 'a.hpp', more: 1}}}, /unknown key "more"/], + [{...minimal, test: {specs: ['../spec.mjs']}}, /safe project-relative path/], + [{...minimal, test: {runner: 'x'}}, /unknown key "runner"/], + [{...minimal, permissions: {shell: true}}, /unknown permission "shell"/], + [{...minimal, permissions: {files: ['a/../../b']}}, /safe project-relative path/], + [{...minimal, permissions: {fetch: ['http://plain.test']}}, /https origin/], + [{...minimal, permissions: {fetch: ['https://registry.test/path']}}, /without a path/], + [[], /must be an object/], + ]; + for (const [value, message] of cases) assert.throws(() => validateManifest(value), message); + assert.throws(() => parseManifest(encode('{')), /not valid JSON/); +}); + +test('the dependency digest ignores key order and changes with any range', async () => { + const first = await dependenciesDigest({a: '^1.0.0', b: '2.0.0'}); + assert.equal(first, await dependenciesDigest({b: '2.0.0', a: '^1.0.0'})); + assert.notEqual(first, await dependenciesDigest({a: '^1.0.0', b: '^2.0.0'})); + assert.match(first, /^[0-9a-f]{64}$/); +}); + +test('entries are named in the manifest or given as paths', () => { + const manifest = validateManifest({...minimal, entries: {main: 'ui/main.tsx', other: 'ui/other.tsx'}}); + assert.equal(resolveEntry(manifest, undefined, 'wf preview'), 'ui/main.tsx'); + assert.equal(resolveEntry(manifest, 'other', 'wf preview'), 'ui/other.tsx'); + assert.equal(resolveEntry(manifest, 'free/path.tsx', 'wf preview'), 'free/path.tsx'); + assert.throws(() => resolveEntry(validateManifest(minimal), undefined, 'wf preview'), /entries.main/); +}); + +test('wf embed names the generated class after the provider, and refuses a file name that is not a C++ name', () => { + const manifest = validateManifest({...minimal, entries: {main: 'ui/main.tsx'}, providers: {PiUI: {entry: 'main', output: 'generated/pi-ui.hpp'}}}); + assert.deepEqual(embedTarget(manifest, ['PiUI']), {entry: 'ui/main.tsx', output: 'generated/pi-ui.hpp', className: 'PiUI'}); + assert.equal(embedTarget(manifest, ['ui/main.tsx', '--output', 'generated/LifeUI.hpp']).className, 'LifeUI'); + assert.throws(() => embedTarget(manifest, ['ui/main.tsx', '--output', 'generated/life-ui.hpp']), /not a C\+\+ class name/); + assert.throws(() => embedTarget(manifest, ['ui/main.tsx']), /--output/); +}); + +// An in-memory project behind the webfront.developer.* callbacks, with the store's group publication and precondition. +function memoryBridge(storage = new Map()) { + const transactions = new Map(); + let next = 0; + const stateOf = paths => paths.map(path => storage.has(path) ? createHash('sha256').update(storage.get(path)).digest('hex') : '-').join(','); + const operations = { + read: (path, offset) => { + if (!storage.has(path)) throw new Error('Cannot read project file: ' + path); + return storage.get(path).subarray(offset, offset + 256 * 1024); + }, + begin: (destination, directory) => { transactions.set(String(++next), {destination, directory, files: new Map(), replace: true}); return String(next); }, + beginNew: (destination, directory) => { transactions.set(String(++next), {destination, directory, files: new Map(), replace: false}); return String(next); }, + write: (id, path, offset, bytes) => { + const files = transactions.get(id).files; + const previous = files.get(path) ?? new Uint8Array(); + assert.equal(previous.length, offset); + files.set(path, new Uint8Array([...previous, ...bytes])); + }, + commit: id => { + const {destination, directory, files, replace} = transactions.get(id); + if (!replace && (storage.has(destination) || [...storage.keys()].some(key => key.startsWith(destination + '/')))) + throw new Error('Starter destination already exists'); + for (const [path, bytes] of files) storage.set(directory ? `${destination}/${path}` : destination, bytes); + transactions.delete(id); + }, + abort: id => { transactions.delete(id); }, + state: paths => stateOf(paths.split('\n')), + commitGroup: (ids, paths, expected) => { + if (stateOf(paths.split('\n')) !== expected) throw new Error('The project changed since it was read; run the command again'); + for (const id of ids.split('\n')) { + const {destination, files} = transactions.get(id); + storage.set(destination, files.get('output')); + transactions.delete(id); + } + }, + }; + const bridge = {cppFunction: name => async (...args) => operations[name.replace('webfront.developer.', '')](...args)}; + return {bridge, storage, pending: () => transactions.size}; +} + +const tagged = (packages, tags) => async url => { + const response = await packages(url); + const body = response.headers.get('content-type')?.includes('json') ? await response.json() : null; + if (!body) return response; + return Response.json({...body, 'dist-tags': {...body['dist-tags'], ...tags}}); +}; +const pkg = (name, version, fields = {}) => compress(tar(new Map([['package/package.json', encode({name, version, ...fields})]]))); +function registry(packages) { + const requests = []; + const fetchImpl = async url => { + requests.push(String(url)); + const path = new URL(url).pathname.slice(1); + if (path.endsWith('.tgz')) { + const [name, version] = path.slice(0, -4).split('@'); + const entry = packages[name]; + return new Response(entry.older?.[version] ?? entry.bytes); + } + const entry = packages[path]; + if (!entry) return new Response('', {status: 404}); + const versions = {[entry.version]: entry.bytes, ...entry.older}; + const described = Object.fromEntries(Object.entries(versions).map(([version, bytes]) => + [version, {dist: {tarball: `https://registry.test/${path}@${version}.tgz`, integrity: integrity(bytes)}}])); + return Response.json({'dist-tags': {latest: entry.version}, versions: described}); + }; + return {fetchImpl, requests}; +} +const source = () => ({ + a: {version: '1.2.0', bytes: pkg('a', '1.2.0')}, + b: {version: '2.0.0', bytes: pkg('b', '2.0.0')}, + c: {version: '3.1.0', bytes: pkg('c', '3.1.0')}, +}); +const options = fetchImpl => ({registry: 'https://registry.test/', fetchImpl}); +const json = (storage, path) => JSON.parse(decoder.decode(storage.get(path))); + +async function project(...files) { + const memory = memoryBridge(); + await initProject(memory.bridge, [], {}); + for (const spec of files) await install(memory.bridge, [spec], options(registry(source()).fetchImpl)); + return memory; +} + +test('wf init creates the root manifest every command reads, and never replaces it', async () => { + const {bridge, storage} = memoryBridge(); + assert.match(await initProject(bridge, [], {}), /Created webfront.project.json/); + assert.deepEqual(json(storage, manifestPath), {format: 1, name: 'webfront-app', version: '0.1.0', dependencies: {}}); + assert.equal((await loadProject(bridge)).status, 'unlocked'); + await assert.rejects(initProject(bridge, [], {}), /already exists/); + await assert.rejects(initProject(bridge, ['a', 'b'], {}), /Usage/); + const named = memoryBridge(); + await initProject(named.bridge, ['my-app'], {}); + assert.equal(json(named.storage, manifestPath).name, 'my-app'); + await assert.rejects(initProject(memoryBridge().bridge, ['Bad Name'], {}), /name must be/); +}); + +test('a project locked before the manifest keeps its locked graph through wf init and wf install', async () => { + const {bridge, storage, pending} = await project('a', 'b@2.0.0', 'c@^3'); + const lock = json(storage, lockPath); + delete lock.manifestDigest; + storage.set(lockPath, encode(lock)); + storage.delete(manifestPath); + assert.match(await initProject(bridge, [], {}), /with the 3 dependencies of webfront-packages.lock.json/); + assert.deepEqual(json(storage, manifestPath).dependencies, {a: '^1.2.0', b: '^2.0.0', c: '^3'}); + assert.equal((await loadProject(bridge)).status, 'legacy'); + assert.equal(syncNotice(await loadProject(bridge)), ''); + // A newer a is published: wf install keeps the locked version and only records the digest. + const newer = {...source(), a: {version: '1.3.0', bytes: pkg('a', '1.3.0'), older: {'1.2.0': pkg('a', '1.2.0')}}}; + await install(bridge, [], options(registry(newer).fetchImpl)); + const adopted = json(storage, lockPath); + assert.deepEqual(Object.keys(adopted.packages).sort(), ['a@1.2.0', 'b@2.0.0', 'c@3.1.0']); + assert.equal(adopted.manifestDigest, await dependenciesDigest({a: '^1.2.0', b: '^2.0.0', c: '^3'})); + assert.equal((await loadProject(bridge)).status, 'consistent'); + assert.equal(pending(), 0); +}); + +test('a legacy lock also stays usable for wf install , and one that does not match is desynchronized', async () => { + const {bridge, storage} = await project('a'); + const lock = json(storage, lockPath); + delete lock.manifestDigest; + storage.set(lockPath, encode(lock)); + const newer = {...source(), a: {version: '1.3.0', bytes: pkg('a', '1.3.0'), older: {'1.2.0': pkg('a', '1.2.0')}}}; + await install(bridge, ['b'], options(registry(newer).fetchImpl)); + assert.deepEqual(Object.keys(json(storage, lockPath).packages).sort(), ['a@1.2.0', 'b@2.0.0']); + assert.equal((await loadProject(bridge)).status, 'consistent'); + const stale = json(storage, lockPath); + delete stale.manifestDigest; + storage.set(lockPath, encode(stale)); + storage.set(manifestPath, encode({...minimal, dependencies: {a: '^2.0.0', b: '^2.0.0'}})); + assert.equal((await loadProject(bridge)).status, 'desynchronized'); +}); + +test('wf install refuses a range the manifest cannot hold before resolving, and writes only what the user wrote', async () => { + const {bridge, storage} = await project(); + const {fetchImpl, requests} = registry(source()); + const before = storage.get(manifestPath); + for (const spec of ['a@next_v2', `a@${'1'.repeat(129)}`]) await assert.rejects(install(bridge, [spec], options(fetchImpl)), /invalid version range/); + assert.equal(requests.length, 0); + assert.equal(storage.get(manifestPath), before); + await install(bridge, ['a@'], options(fetchImpl)); + assert.deepEqual(json(storage, manifestPath), {format: 1, name: 'webfront-app', version: '0.1.0', dependencies: {a: '^1.2.0'}}); + assert.deepEqual((await loadProject(bridge)).manifest.entries, {}, 'the defaults are still applied when reading'); +}); + +test('wf install needs a manifest, then publishes manifest and lock together', async () => { + const {bridge, storage} = memoryBridge(); + const {fetchImpl} = registry(source()); + await assert.rejects(install(bridge, ['a'], options(fetchImpl)), /run wf init/); + await initProject(bridge, [], {}); + assert.equal((await loadProject(bridge)).status, 'unlocked'); + await install(bridge, ['a'], options(fetchImpl)); + const afterFirst = await loadProject(bridge); + assert.equal(afterFirst.status, 'consistent'); + assert.deepEqual(afterFirst.manifest.dependencies, {a: '^1.2.0'}); + assert.equal(afterFirst.lock.manifestDigest, await dependenciesDigest({a: '^1.2.0'})); + await install(bridge, ['b@2.0.0', 'c@^3'], options(fetchImpl)); + assert.deepEqual(json(storage, manifestPath).dependencies, {a: '^1.2.0', b: '2.0.0', c: '^3'}); + assert.deepEqual(Object.keys(json(storage, lockPath).roots), ['a', 'b', 'c']); + assert.equal((await loadProject(bridge)).status, 'consistent'); +}); + +test('the three states of manifest and lock for install, install and install --update', async () => { + const {bridge, storage, pending} = await project('a'); + const {fetchImpl, requests} = registry(source()); + // consistent: install restores the locked graph, resolving and writing nothing. + const manifestBefore = storage.get(manifestPath); + const lockBefore = storage.get(lockPath); + const cache = [...storage.keys()].filter(key => key.startsWith('.webfront/developer/packages/')); + cache.forEach(key => storage.delete(key)); + const restored = await install(bridge, [], options(fetchImpl)); + assert.equal(restored.restored, 1); + assert.ok(cache.every(key => storage.has(key))); + assert.equal(storage.get(manifestPath), manifestBefore); + assert.equal(storage.get(lockPath), lockBefore); + assert.equal(requests.filter(url => !url.endsWith('.tgz')).length, 1, 'only the locked package is fetched, not a new resolution'); + // no lock: install resolves the manifest and creates the lock, leaving the manifest alone. + storage.delete(lockPath); + assert.equal((await loadProject(bridge)).status, 'unlocked'); + await install(bridge, [], options(fetchImpl)); + assert.equal((await loadProject(bridge)).status, 'consistent'); + assert.deepEqual(storage.get(manifestPath), manifestBefore); + // desynchronized: every command says so and nothing is resolved implicitly. + const edited = json(storage, manifestPath); + edited.dependencies.b = '2.0.0'; + storage.set(manifestPath, encode(serializeManifest(edited))); + const stale = await loadProject(bridge); + assert.equal(stale.status, 'desynchronized'); + assert.match(syncNotice(stale), /wf install --update/); + const lockStale = storage.get(lockPath); + requests.length = 0; + await assert.rejects(install(bridge, [], options(fetchImpl)), /wf install --update/); + await assert.rejects(install(bridge, ['c'], options(fetchImpl)), /wf install --update/); + assert.equal(requests.length, 0); + assert.equal(storage.get(lockPath), lockStale); + await install(bridge, ['--update'], options(fetchImpl)); + assert.equal((await loadProject(bridge)).status, 'consistent'); + assert.deepEqual(Object.keys(json(storage, lockPath).roots), ['a', 'b']); + assert.equal(pending(), 0); +}); + +test('a changed archive is refused when restoring a locked graph', async () => { + const {bridge, storage} = await project('a'); + [...storage.keys()].filter(key => key.startsWith('.webfront/developer/packages/')).forEach(key => storage.delete(key)); + const tampered = {a: {version: '1.2.0', bytes: pkg('a', '1.2.0', {description: 'changed'})}}; + await assert.rejects(install(bridge, [], options(registry(tampered).fetchImpl)), /Integrity check|integrity/); +}); + +test('two installations that read the same state cannot overwrite each other', async () => { + const {bridge, storage, pending} = await project(); + const {fetchImpl} = registry(source()); + const results = await Promise.allSettled([install(bridge, ['a'], options(fetchImpl)), install(bridge, ['b'], options(fetchImpl))]); + const refused = results.filter(result => result.status === 'rejected'); + assert.equal(refused.length, 1, 'exactly one publication is refused by the precondition'); + assert.match(refused[0].reason.message, /changed since it was read; run the command again/); + assert.equal(pending(), 0, 'the refused installation leaves no staged transaction'); + assert.equal((await loadProject(bridge)).status, 'consistent'); + const winner = Object.keys(json(storage, manifestPath).dependencies); + assert.equal(winner.length, 1); + await install(bridge, [winner[0] === 'a' ? 'b' : 'a'], options(fetchImpl)); + assert.deepEqual(Object.keys(json(storage, manifestPath).dependencies).sort(), ['a', 'b']); + assert.deepEqual(Object.keys(json(storage, lockPath).roots).sort(), ['a', 'b']); + assert.equal((await loadProject(bridge)).status, 'consistent'); +}); + +test('an invalid manifest is reported before anything is resolved', async () => { + const {bridge, storage} = await project('a'); + storage.set(manifestPath, encode({...minimal, format: 3})); + await assert.rejects(loadProject(bridge), /format 3 is not supported/); + storage.set(manifestPath, encode({...minimal, permissions: {network: true}})); + await assert.rejects(install(bridge, [], options(registry(source()).fetchImpl)), /unknown permission/); +}); + +test('wf install --update takes the newest version within the ranges while installing a package keeps the others', async () => { + const {bridge, storage} = await project('a'); + assert.equal(json(storage, lockPath).packages['a@1.2.0'].version, '1.2.0'); + const newer = {...source(), a: {version: '1.3.0', bytes: pkg('a', '1.3.0'), older: {'1.2.0': pkg('a', '1.2.0')}}}; + await install(bridge, ['b'], options(registry(newer).fetchImpl)); + assert.ok(json(storage, lockPath).packages['a@1.2.0'], 'installing another package leaves a at its locked version'); + assert.equal(json(storage, lockPath).packages['a@1.3.0'], undefined); + await install(bridge, ['--update'], options(registry(newer).fetchImpl)); + assert.deepEqual(Object.keys(json(storage, lockPath).packages).sort(), ['a@1.3.0', 'b@2.0.0']); + assert.deepEqual(json(storage, manifestPath).dependencies, {a: '^1.2.0', b: '^2.0.0'}); + assert.equal((await loadProject(bridge)).status, 'consistent'); +}); + +test('a package installed by dist-tag keeps its version when another package is installed', async () => { + const {bridge, storage} = await project(); + const old = {...source(), a: {version: '1.2.0', bytes: pkg('a', '1.2.0'), older: {'1.3.0': pkg('a', '1.3.0')}}}; + const beta = tags => options(tagged(registry(old).fetchImpl, tags)); + await install(bridge, ['a@beta'], beta({beta: '1.2.0'})); + assert.deepEqual(json(storage, manifestPath).dependencies, {a: 'beta'}); + await install(bridge, ['b'], beta({beta: '1.3.0'})); + assert.deepEqual(Object.keys(json(storage, lockPath).packages).sort(), ['a@1.2.0', 'b@2.0.0'], 'the tag moved but the lock did not'); + await install(bridge, ['--update'], beta({beta: '1.3.0'})); + assert.deepEqual(Object.keys(json(storage, lockPath).packages).sort(), ['a@1.3.0', 'b@2.0.0']); +}); diff --git a/js/developer/tools/pin-check.mjs b/js/developer/tools/pin-check.mjs new file mode 100644 index 00000000..581d692a --- /dev/null +++ b/js/developer/tools/pin-check.mjs @@ -0,0 +1,20 @@ +// Checks DeveloperReleaseData.hpp against the published distribution it pins, for sources that build a newer version: +// the header must be exactly the one generated for its version, and the archive at its URL must have its integrity. +import {readFile} from 'node:fs/promises'; +import {createHash} from 'node:crypto'; +import {bootstrapHeader} from './site.mjs'; + +const root = new URL('../../../', import.meta.url); +const header = await readFile(new URL('include/webfront/system/DeveloperReleaseData.hpp', root), 'utf8'); +const distribution = JSON.parse(await readFile(new URL('js/developer/tools/distribution.json', root))); +const field = name => header.match(new RegExp(`\\b${name}\\{"([^"]*)"\\}`))?.[1] ?? ''; +const version = field('version'); +const integrity = field('integrity'); +if (header !== bootstrapHeader(version, distribution.baseUrl, integrity)) + throw new Error(`DeveloperReleaseData.hpp is not the header generated for the published ${version}`); +const url = field('environment'); +const response = await fetch(url); +if (!response.ok) throw new Error(`The pinned environment ${url} is not published (${response.status})`); +const actual = 'sha512-' + createHash('sha512').update(new Uint8Array(await response.arrayBuffer())).digest('base64'); +if (actual !== integrity) throw new Error(`The published ${url} does not have the pinned integrity`); +console.log(`DeveloperReleaseData.hpp pins the published ${version}.`); diff --git a/test/unit/DeveloperTests.cpp b/test/unit/DeveloperTests.cpp index 38450888..4a9b3c5c 100644 --- a/test/unit/DeveloperTests.cpp +++ b/test/unit/DeveloperTests.cpp @@ -1,12 +1,15 @@ #include "../fixtures/Pi.hpp" #include "TemporaryDirectory.hpp" #include +#include #include #include #include +#include #include #include +#include using namespace webfront; using webfront::test::TemporaryDirectory; @@ -338,3 +341,376 @@ SCENARIO("The developer application needs an explicit project and a trusted envi } } } + +namespace { +constexpr auto manifestPath = "webfront.project.json"; +constexpr auto lockPath = "webfront-packages.lock.json"; +const std::vector pair{manifestPath, lockPath}; + +void publishFile(developer::Store& store, const std::string& path, std::string_view text) { + const auto id = store.begin(path, false); + store.write(id, "output", 0, bytes(text)); + store.commit(id); +} + +// Stages new contents for the manifest and the lock, then publishes them together. +void publishPair(developer::Store& store, std::string_view manifest, std::string_view lock, const std::string& expected) { + const auto first = store.begin(manifestPath, false); + const auto second = store.begin(lockPath, false); + store.write(first, "output", 0, bytes(manifest)); + store.write(second, "output", 0, bytes(lock)); + store.commitGroup({first, second}, pair, expected); +} + +// The lock file stays in the journal directory; anything else is a journal or its remains. +[[nodiscard]] bool journalsRemain(const std::filesystem::path& directory) { + return std::ranges::any_of(std::filesystem::directory_iterator(directory), + [](const auto& entry) { return entry.path().filename() != developer::lockName; }); +} + +[[nodiscard]] std::string projectState(developer::Store& store) { + return read(store, manifestPath) + "|" + read(store, lockPath); +} + +// Stops the process at one step of a group publication, then reopens the project. +[[nodiscard]] std::string crashAt(const std::string& step, const std::filesystem::path& project) { + { + developer::Store store{project, developer::defaultAbandonedAfter, [&step](std::string_view name) { + if (name == step) + throw developer::InjectedFault{"crash at " + step}; + }}; + const auto expected = store.state(pair); + REQUIRE_THROWS_AS(publishPair(store, "manifest-2", "lock-2", expected), developer::InjectedFault); + } + developer::Store reopened{project}; + return projectState(reopened); +} +} // namespace + +SCENARIO("A manifest and its lock are published together or not at all") { + TemporaryDirectory project; + { + developer::Store store{project.path()}; + publishFile(store, manifestPath, "manifest-1"); + publishFile(store, lockPath, "lock-1"); + } + GIVEN("an installed manifest and lock") { + developer::Store store{project.path()}; + WHEN("both files are published after an uninterrupted install") { + publishPair(store, "manifest-2", "lock-2", store.state(pair)); + THEN("both are replaced and no journal remains") { + REQUIRE(projectState(store) == "manifest-2|lock-2"); + REQUIRE_FALSE(journalsRemain(project.path() / ".webfront/developer/journal")); + } + } + WHEN("the process stops before the journal is committed") { + store.state(pair); + THEN("the previous state is intact after restart") { + REQUIRE(crashAt("before-journal", project.path()) == "manifest-1|lock-1"); + } + } + WHEN("the process stops right after the journal is committed") { + THEN("restart completes the publication") { + REQUIRE(crashAt("after-journal", project.path()) == "manifest-2|lock-2"); + } + } + WHEN("the process stops between the two replacements") { + THEN("restart completes the publication") { + REQUIRE(crashAt("replacement-1", project.path()) == "manifest-2|lock-2"); + } + } + WHEN("the process stops once the replacements are durable but the journal is still there") { + THEN("restart completes the publication") { + REQUIRE(crashAt("replacements-synced", project.path()) == "manifest-2|lock-2"); + } + } + WHEN("the journal is removed") { + std::vector steps; + std::vector journalPresent; + { + developer::Store observed{project.path(), developer::defaultAbandonedAfter, [&](std::string_view name) { + steps.emplace_back(name); + if (name == "replacements-synced") + journalPresent.push_back(journalsRemain(project.path() / ".webfront/developer/journal")); + }}; + publishPair(observed, "manifest-2", "lock-2", observed.state(pair)); + } + THEN("it is only after both replacements, and the journal was still present until then") { + REQUIRE(steps == std::vector{"before-journal", "after-journal", "replacement-1", "replacement-2", "replacements-synced"}); + REQUIRE(journalPresent == std::vector{true}); + } + } + WHEN("the process stops after the second replacement") { + THEN("restart completes the publication") { + REQUIRE(crashAt("replacement-2", project.path()) == "manifest-2|lock-2"); + } + } + } + GIVEN("a publication committed but interrupted between its replacements") { + { + developer::Store store{project.path(), developer::defaultAbandonedAfter, [](std::string_view name) { + if (name == "replacement-1") + throw developer::InjectedFault{"crash"}; + }}; + REQUIRE_THROWS_AS(publishPair(store, "manifest-2", "lock-2", store.state(pair)), developer::InjectedFault); + } + WHEN("the recovery itself is interrupted, once at each of its steps") { + for (const char* step : {"replacement-1", "replacement-2"}) { + REQUIRE_THROWS_AS(developer::Store(project.path(), developer::defaultAbandonedAfter, + [step](std::string_view name) { + if (name == step) + throw developer::InjectedFault{"crash"}; + }), + developer::InjectedFault); + } + THEN("a later restart still reaches the new state") { + developer::Store store{project.path()}; + REQUIRE(projectState(store) == "manifest-2|lock-2"); + REQUIRE_FALSE(journalsRemain(project.path() / ".webfront/developer/journal")); + } + } + } + GIVEN("leftovers of a publication that never reached its commit point") { + const auto journal = project.path() / ".webfront/developer/journal"; + std::filesystem::create_directories(journal / "7.d"); + std::ofstream{journal / "7.d" / "0"} << "orphan"; + std::ofstream{journal / "7.tmp"} << "webfront-journal 1\nwebfront.project.json\n0\n"; + std::ofstream{journal / "8.journal"} << "webfront-journal 1\nwebfront.project.json\n0\n"; + WHEN("the project is opened") { + developer::Store store{project.path()}; + THEN("they are abandoned and the project keeps its files") { + REQUIRE_FALSE(journalsRemain(journal)); + REQUIRE(projectState(store) == "manifest-1|lock-1"); + } + } + } +} + +SCENARIO("A committed publication that cannot be completed does not prevent opening the project") { + TemporaryDirectory project; + const auto journal = project.path() / ".webfront/developer/journal"; + { + developer::Store store{project.path()}; + publishFile(store, manifestPath, "manifest-1"); + publishFile(store, lockPath, "lock-1"); + } + GIVEN("a publication committed before a crash whose manifest replacement is now blocked") { + REQUIRE(crashAt("after-journal", project.path()) == "manifest-2|lock-2"); + { + // Commit a second publication, then obstruct its first target. + developer::Store store{project.path(), developer::defaultAbandonedAfter, [](std::string_view name) { + if (name == "after-journal") + throw developer::InjectedFault{"crash"}; + }}; + REQUIRE_THROWS_AS(publishPair(store, "manifest-3", "lock-3", store.state(pair)), developer::InjectedFault); + } + std::filesystem::remove(project.path() / manifestPath); + std::filesystem::create_directories(project.path() / manifestPath / "obstacle"); + WHEN("the project is opened") { + developer::Store store{project.path()}; + THEN("it opens, reports the failure, refuses to read a state and keeps the journal") { + REQUIRE(store.recoveryFailure().has_value()); + REQUIRE_THROWS_AS(store.state(pair), developer::IncompletePublication); + REQUIRE(journalsRemain(journal)); + REQUIRE(read(store, lockPath) == "lock-2"); + } + AND_WHEN("the obstacle is removed") { + std::filesystem::remove_all(project.path() / manifestPath); + THEN("the next state completes the publication") { + store.state(pair); + REQUIRE_FALSE(store.recoveryFailure().has_value()); + REQUIRE(projectState(store) == "manifest-3|lock-3"); + REQUIRE_FALSE(journalsRemain(journal)); + } + } + } + } + GIVEN("a replacement failing during the publication") { + bool failOnce = true; + developer::Store store{project.path(), developer::defaultAbandonedAfter, [&failOnce](std::string_view name) { + if (name == "replacement-1" && std::exchange(failOnce, false)) + throw std::runtime_error("target locked"); + }}; + WHEN("the group is published") { + THEN("the caller learns that the change is committed but not applied, and the next state applies it") { + REQUIRE_THROWS_AS(publishPair(store, "manifest-2", "lock-2", store.state(pair)), developer::IncompletePublication); + REQUIRE(store.recoveryFailure().has_value()); + store.state(pair); + REQUIRE(projectState(store) == "manifest-2|lock-2"); + REQUIRE_FALSE(journalsRemain(journal)); + } + } + } + GIVEN("a failure before the commit point") { + developer::Store store{project.path(), developer::defaultAbandonedAfter, [](std::string_view name) { + if (name == "before-journal") + throw std::runtime_error("disk full"); + }}; + const auto first = store.begin(manifestPath, false); + const auto second = store.begin(lockPath, false); + store.write(first, "output", 0, bytes("manifest-2")); + store.write(second, "output", 0, bytes("lock-2")); + REQUIRE_THROWS_WITH(store.commitGroup({first, second}, pair, store.state(pair)), "disk full"); + THEN("the staged files are returned to their transactions, which still publish") { + REQUIRE(projectState(store) == "manifest-1|lock-1"); + REQUIRE_FALSE(journalsRemain(journal)); + store.commit(first); + store.commit(second); + REQUIRE(projectState(store) == "manifest-2|lock-2"); + } + } +} + +SCENARIO("A publication prepared from stale state is refused") { + TemporaryDirectory project; + developer::Store store{project.path()}; + publishFile(store, manifestPath, "manifest-1"); + publishFile(store, lockPath, "lock-1"); + GIVEN("two browsers reading the same state") { + const auto firstBrowser = store.state(pair); + const auto secondBrowser = store.state(pair); + REQUIRE(firstBrowser == secondBrowser); + WHEN("the first publishes, then the second does with what it read") { + publishPair(store, "manifest-a", "lock-a", firstBrowser); + THEN("the second is refused and nothing is lost") { + REQUIRE_THROWS_WITH(publishPair(store, "manifest-b", "lock-b", secondBrowser), Catch::Matchers::ContainsSubstring("changed since it was read")); + REQUIRE(projectState(store) == "manifest-a|lock-a"); + } + AND_THEN("it succeeds after reading the new state again") { + publishPair(store, "manifest-ab", "lock-ab", store.state(pair)); + REQUIRE(projectState(store) == "manifest-ab|lock-ab"); + } + } + WHEN("a file changes outside the store") { + publishFile(store, lockPath, "lock-c"); + THEN("the state differs and the group is refused") { + REQUIRE(store.state(pair) != firstBrowser); + REQUIRE_THROWS(publishPair(store, "manifest-b", "lock-b", firstBrowser)); + } + } + } + GIVEN("a missing lock") { + std::filesystem::remove(project.path() / lockPath); + THEN("its absence is part of the state") { + const auto absent = store.state(pair); + publishFile(store, lockPath, ""); + REQUIRE(store.state(pair) != absent); + } + } + GIVEN("malformed groups") { + const auto first = store.begin(manifestPath, false); + store.write(first, "output", 0, bytes("x")); + THEN("they are refused without changing the project") { + REQUIRE_THROWS(store.commitGroup({}, pair, store.state(pair))); + REQUIRE_THROWS(store.commitGroup({first, first}, pair, store.state(pair))); + REQUIRE_THROWS(store.commitGroup({first}, {lockPath}, store.state({lockPath}))); + REQUIRE(projectState(store) == "manifest-1|lock-1"); + store.abort(first); + } + } +} + +SCENARIO("New directories are durable once their parents are synchronized") { + TemporaryDirectory project; + const auto root = std::filesystem::canonical(project.path()); + GIVEN("a project without the journal directory") { + std::vector synced; + WHEN("the directories are created") { + developer::createDirectoriesDurably(root, root / ".webfront/developer/journal", + [&](const std::filesystem::path& directory) { + // The directory just created must exist when its parent is synchronized. + REQUIRE(std::filesystem::exists(directory / (synced.empty() ? ".webfront" : synced.size() == 1 ? "developer" : "journal"))); + synced.push_back(directory); + }); + THEN("each created directory has its parent synchronized, outermost first") { + REQUIRE(synced == std::vector{root, root / ".webfront", root / ".webfront/developer"}); + } + } + WHEN("some of them already exist") { + std::filesystem::create_directories(root / ".webfront/developer"); + developer::createDirectoriesDurably(root, root / ".webfront/developer/journal", + [&](const std::filesystem::path& directory) { synced.push_back(directory); }); + THEN("only the missing one is created and synchronized") { + REQUIRE(synced == std::vector{root / ".webfront/developer"}); + } + } + } +} + +namespace { +// Holds a thread at a step until opened. Opening is idempotent and also happens on destruction, so a failed +// assertion never leaves a thread blocked behind a future that waits for it. +class Gate { +public: + void open() { + std::call_once(once, [this] { opened.set_value(); }); + } + void wait() const { + future.wait(); + } + +private: + std::once_flag once; + std::promise opened; + std::shared_future future{opened.get_future().share()}; +}; +struct OpenOnExit { + Gate& gate; + ~OpenOnExit() { + gate.open(); + } +}; +} // namespace + +SCENARIO("A second opener of the project waits for a publication in progress instead of abandoning it") { + TemporaryDirectory project; + { + developer::Store store{project.path()}; + publishFile(store, manifestPath, "manifest-1"); + publishFile(store, lockPath, "lock-1"); + } + GIVEN("a publication stopped between staging its files and writing its journal") { + Gate reached; + Gate release; + developer::Store publisher{project.path(), developer::defaultAbandonedAfter, [&](std::string_view name) { + if (name == "before-journal") { + reached.open(); + release.wait(); + } + }}; + const auto before = publisher.state(pair); + auto publication = std::async(std::launch::async, [&] { + try { + publishPair(publisher, "manifest-2", "lock-2", before); + } catch (...) { + reached.open(); // do not leave the test waiting for a step that is never reached + throw; + } + }); + const OpenOnExit unblock{release}; + reached.wait(); + WHEN("another store, as another process would, opens the project meanwhile") { + auto opening = std::async(std::launch::async, [&] { developer::Store other{project.path()}; return projectState(other); }); + const auto waiting = opening.wait_for(std::chrono::milliseconds(300)); + release.open(); + publication.get(); + THEN("it waited, then sees the completed publication") { + CHECK(waiting == std::future_status::timeout); + REQUIRE(opening.get() == "manifest-2|lock-2"); + } + } + WHEN("another store tries to publish from the state read before the first publication") { + auto competing = std::async(std::launch::async, [&] { + developer::Store other{project.path()}; + publishPair(other, "manifest-3", "lock-3", before); + }); + const auto waiting = competing.wait_for(std::chrono::milliseconds(300)); + release.open(); + publication.get(); + THEN("its precondition is checked after the first publication, which wins") { + CHECK(waiting == std::future_status::timeout); + REQUIRE_THROWS_WITH(competing.get(), Catch::Matchers::ContainsSubstring("changed since it was read")); + } + } + } +} diff --git a/test/web/developer-specs.mjs b/test/web/developer-specs.mjs index 810d8506..84b6d947 100644 --- a/test/web/developer-specs.mjs +++ b/test/web/developer-specs.mjs @@ -1,6 +1,21 @@ // Autonomous real-engine test: compiled WASM, npm graph, PI bridge, preview, cache and embedding. const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); const assert = (condition, message) => { if (!condition) throw new Error(message); }; +const call = (name, ...args) => webFront.cppFunction(`webfront.developer.${name}`)(...args); +async function readFile(path) { + const chunks = []; + for (let offset = 0;;) { + const chunk = await call('read', path, offset); + chunks.push(chunk); + offset += chunk.length; + if (chunk.length < 256 * 1024) return new Uint8Array(await new Blob(chunks).arrayBuffer()); + } +} +async function writeFile(path, text) { + const id = await call('begin', path, false); + await call('write', id, 'output', 0, new TextEncoder().encode(text)); + await call('commit', id); +} try { await webFront.ready; for (let attempt = 0; attempt < 300; ++attempt) { @@ -19,13 +34,26 @@ try { await runtime.execute(['create', 'pi'], context); const overwriteRefused = await runtime.execute(['create', 'pi'], context).then(() => false, () => true); assert(overwriteRefused, 'A starter must not replace an existing project'); + const noManifest = await runtime.execute(['install', 'react@19.3.1'], context).then(() => false, error => /run wf init/.test(error.message)); + assert(noManifest, 'wf install must ask for a manifest first'); + await runtime.execute(['init'], context); + const initRefused = await runtime.execute(['init'], context).then(() => false, () => true); + assert(initRefused, 'wf init must not replace an existing manifest'); await runtime.execute(['install', 'react@19.3.1', 'react-dom@19.3.1'], context); const lock = await runtime.readLock(webFront); + assert(lock.manifestDigest?.length === 64, 'The lock must record the digest of the manifest dependencies'); + const manifest = JSON.parse(new TextDecoder().decode(await readFile('webfront.project.json'))); + assert(manifest.dependencies.react === '19.3.1' && manifest.dependencies['react-dom'] === '19.3.1', 'The manifest must record the requested ranges'); + // Entries and providers declared in the manifest drive wf preview and wf embed. + manifest.entries = {main: 'ui/main.tsx'}; + manifest.providers = {PiUI: {entry: 'main', output: 'generated/PiUI.hpp'}}; + await writeFile('webfront.project.json', JSON.stringify(manifest, null, 2)); + assert(!(await runtime.execute(['list'], context)).includes('Warning'), 'Editing entries must not desynchronize the lock'); assert(Object.keys(lock.packages).length === 3, 'React, React DOM and scheduler must be resolved'); const listed = await runtime.execute(['list'], context); assert(listed.split('\n').length === 3 && listed.includes('react@19.3.1'), 'wf list must name the installed packages'); const historyLength = history.length; - await runtime.execute(['preview', 'ui/main.tsx'], context); + await runtime.execute(['preview'], context); const frame = context.preview; for (let attempt = 0; attempt < 300; ++attempt) { if (frame.contentDocument?.querySelector('button')) break; @@ -38,7 +66,7 @@ try { if (attempt === 99) throw new Error('React preview did not display C++ PI'); await delay(50); } - await runtime.execute(['embed', 'ui/main.tsx', '--output', 'generated/PiUI.hpp'], context); + await runtime.execute(['embed', 'PiUI'], context); // Repeat the browser build to prove reproducibility, including licenses and packed gzip bytes. const first = await webFront.cppFunction('test.header')('PiUI'); await runtime.execute(['embed', 'ui/main.tsx', '--output', 'generated/PiUI.hpp'], context); @@ -116,6 +144,15 @@ try { const lifeHeader = await webFront.cppFunction('test.header')('LifeUI'); await runtime.execute(['embed', 'life-ui/main.tsx', '--output', 'generated/LifeUI.hpp'], context); assert(await webFront.cppFunction('test.header')('LifeUI') === lifeHeader, 'Life header must be deterministic'); + // A dependency added by hand desynchronizes the lock: commands say so and nothing is resolved implicitly. + manifest.dependencies.scheduler = '*'; + await writeFile('webfront.project.json', JSON.stringify(manifest, null, 2)); + assert((await runtime.execute(['list'], context)).startsWith('Warning'), 'A desynchronized lock must be reported'); + const refused = await runtime.execute(['install'], context).then(() => false, error => /wf install --update/.test(error.message)); + assert(refused, 'wf install must not resolve a desynchronized manifest'); + delete manifest.dependencies.scheduler; + await writeFile('webfront.project.json', JSON.stringify(manifest, null, 2)); + assert(/Installed 3 packages/.test(await runtime.execute(['install'], context)), 'A consistent lock must install its exact graph'); const failed = await runtime.execute(['install', 'INVALID-NPM-NAME'], context).then(() => false, () => true); assert(failed, 'Missing packages must reject'); assert(JSON.stringify(await runtime.readLock(webFront)) === JSON.stringify(lock), 'A failed install must preserve the lock');