diff --git a/.codescene/code-health-rules.json b/.codescene/code-health-rules.json deleted file mode 100644 index 3077539b..00000000 --- a/.codescene/code-health-rules.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "usage": "CodeScene code health rules for this repository. third_party/ holds pinned upstream distributions (see docs/EMBEDDED_ASSETS.md) that are copied verbatim or reproducibly bundled and never edited here, so function and module size heuristics are disabled for them.", - "rule_sets": [ - { - "matching_content_path": "third_party/**", - "matching_content_path_doc": "Vendored third-party code, refreshed only with cmake/UpdateXterm.cmake or tools/assets/update.mjs.", - "rules": [ - { "name": "Complex Method", "weight": 0.0 }, - { "name": "Bumpy Road Ahead", "weight": 0.0 }, - { "name": "Complex Conditional", "weight": 0.0 }, - { "name": "Excess Number of Function Arguments", "weight": 0.0 }, - { "name": "Deep, Nested Complexity", "weight": 0.0 }, - { "name": "Large Method", "weight": 0.0 }, - { "name": "Brain Method", "weight": 0.0 }, - { "name": "Overall Code Complexity", "weight": 0.0 }, - { "name": "Lines of Code in a Single File", "weight": 0.0 }, - { "name": "Number of Functions in a Single Module", "weight": 0.0 }, - { "name": "Code Duplication", "weight": 0.0 }, - { "name": "Primitive Obsession", "weight": 0.0 }, - { "name": "String Heavy Function Arguments", "weight": 0.0 }, - { "name": "Low Cohesion", "weight": 0.0 } - ] - }, - { - "matching_content_path": "include/components/Terminal.hpp", - "matching_content_path_doc": "A text command-line interface: its API and helpers take command names, help texts and command lines, which are strings by nature. Wrapping them in structs only to lower the ratio would make the public API (terminal.command(name, help, handler)) harder to read.", - "rules": [ - { "name": "String Heavy Function Arguments", "weight": 0.0 } - ] - }, - { - "matching_content_path": "assets/developer/*.bundle.mjs", - "matching_content_path_doc": "Minified esbuild output of the sources next to it, checked in so that the bootstrap and package resolver need no Node.js at consumption time. It is regenerated by tools/developer/build.mjs --refresh-bootstrap and verified against assets/developer/bundles.json, never edited by hand; the readable sources are analysed instead.", - "rules": [ - { "name": "Complex Method", "weight": 0.0 }, - { "name": "Bumpy Road Ahead", "weight": 0.0 }, - { "name": "Complex Conditional", "weight": 0.0 }, - { "name": "Excess Number of Function Arguments", "weight": 0.0 }, - { "name": "Deep, Nested Complexity", "weight": 0.0 }, - { "name": "Large Method", "weight": 0.0 }, - { "name": "Brain Method", "weight": 0.0 }, - { "name": "Overall Code Complexity", "weight": 0.0 }, - { "name": "Lines of Code in a Single File", "weight": 0.0 }, - { "name": "Number of Functions in a Single Module", "weight": 0.0 }, - { "name": "Code Duplication", "weight": 0.0 }, - { "name": "Primitive Obsession", "weight": 0.0 }, - { "name": "String Heavy Function Arguments", "weight": 0.0 }, - { "name": "Low Cohesion", "weight": 0.0 } - ] - }, - { - "matching_content_path": "include/system/DeveloperStore.hpp", - "matching_content_path_doc": "The store implements the webfront.developer.* bridge callbacks, whose identifiers, project paths, offsets and flags arrive as primitives from the browser. Wrapping them in types only to lower the ratio would obscure the bridge contract.", - "rules": [ - { "name": "String Heavy Function Arguments", "weight": 0.0 }, - { "name": "Primitive Obsession", "weight": 0.0 } - ] - } - ] -} diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json deleted file mode 100644 index 3ed41f49..00000000 --- a/.devcontainer/devcontainer.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "C++", - "build": { - "dockerfile": "../Dockerfile", - "context": ".." - }, - "runArgs": [ "--cap-add=SYS_PTRACE", "--security-opt", "seccomp=unconfined"], - "customizations": { - "vscode": { - "settings": { - "terminal.integrated.defaultProfile.linux": "bash" - }, - "extensions": [ - "ms-vscode.cpptools" - ] - } - } -} diff --git a/.gitattributes b/.gitattributes index 0e89bd2b..fcdb4466 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,188 +1,69 @@ # Auto detect text files and perform LF normalization * text=auto -# -# The above will handle all files NOT found below -# -# Documents -*.bibtex text diff=bibtex -*.doc diff=astextplain -*.DOC diff=astextplain -*.docx diff=astextplain -*.DOCX diff=astextplain -*.dot diff=astextplain -*.DOT diff=astextplain -*.pdf diff=astextplain -*.PDF diff=astextplain -*.rtf diff=astextplain -*.RTF diff=astextplain +# Documents and data *.md text diff=markdown -*.mdx text diff=markdown -*.tex text diff=tex -*.adoc text -*.textile text -*.mustache text -*.csv text -*.tab text -*.tsv text *.txt text -*.sql text +*.csv text +*.json text +*.yml text +*.yaml text +*.toml text +*.xml text # Graphics *.png binary *.jpg binary *.jpeg binary *.gif binary -*.tif binary -*.tiff binary *.ico binary -*.svg text -*.eps binary - -# Scripts -*.bash text eol=lf -*.fish text eol=lf -*.sh text eol=lf -*.zsh text eol=lf -# These are explicitly windows files and should use crlf -*.bat text eol=crlf -*.cmd text eol=crlf -*.ps1 text eol=crlf - -# Embedded headers hold the exact bytes of their text sources. Freshness tests -# re-read those sources, so Windows checkouts must preserve LF for every asset. -assets/WebFront.js text eol=lf -include/system/WebFrontJsData.hpp text eol=lf -assets/fallback/index.html text eol=lf -assets/fallback/webfront-fallback.mjs text eol=lf -include/system/FallbackIndexHtmlData.hpp text eol=lf -include/system/FallbackModuleData.hpp text eol=lf -assets/components/terminal/* text eol=lf -assets/components/tools/* text eol=lf -include/system/ToolManagerModuleData.hpp text eol=lf -third_party/xterm/* text eol=lf -include/system/TerminalIndexHtmlData.hpp text eol=lf -include/system/TerminalModuleData.hpp text eol=lf -include/system/XtermModuleData.hpp text eol=lf -include/system/XtermCssData.hpp text eol=lf -include/system/XtermFitAddonData.hpp text eol=lf - -# The fake npm registry of the browser integration test: its packuments are served byte for byte. -webtest/registry/* text eol=lf -webtest/registry/tarballs/* binary - -# Serialisation -*.json text -*.toml text -*.xml text -*.yaml text -*.yml text # Archives -*.7z binary *.gz binary -*.tar binary *.tgz binary *.zip binary -# Text files where line endings should be preserved -*.patch -text - # Sources -*.c text diff=cpp -*.cc text diff=cpp -*.cxx text diff=cpp -*.cpp text diff=cpp -*.c++ text diff=cpp -*.hpp text diff=cpp -*.h text diff=cpp -*.h++ text diff=cpp -*.hh text diff=cpp - -# Compiled Object files -*.slo binary -*.lo binary -*.o binary -*.obj binary - -# Precompiled Headers -*.gch binary -*.pch binary - -# Compiled Dynamic libraries -*.so binary -*.dylib binary -*.dll binary - -# Compiled Static libraries -*.lai binary -*.la binary -*.a binary -*.lib binary - -# Executables -*.exe binary -*.out binary -*.app binary - - - +*.cpp text diff=cpp +*.hpp text diff=cpp +*.h text diff=cpp -############################################################################### -# Set the merge driver for project and solution files -# -# Merging from the command prompt will add diff markers to the files if there -# are conflicts (Merging from VS is not affected by the settings below, in VS -# the diff markers are never inserted). Diff markers may cause the following -# file extensions to fail to load in VS. An alternative would be to treat -# these files as binary and thus will always conflict and require user -# intervention with every merge. To do so, just comment the entries below and -# uncomment the group further below -############################################################################### - -*.sln text eol=crlf -*.csproj text eol=crlf -*.vbproj text eol=crlf -*.vcxproj text eol=crlf -*.vcproj text eol=crlf -*.dbproj text eol=crlf -*.fsproj text eol=crlf -*.lsproj text eol=crlf -*.wixproj text eol=crlf -*.modelproj text eol=crlf -*.sqlproj text eol=crlf -*.wwaproj text eol=crlf - -*.xproj text eol=crlf -*.props text eol=crlf -*.filters text eol=crlf -*.vcxitems text eol=crlf +# Scripts. These are explicitly windows files and should use crlf +*.sh text eol=lf +*.bat text eol=crlf +*.cmd text eol=crlf +*.ps1 text eol=crlf -# # Exclude files from exporting -# - .gitattributes export-ignore .gitignore export-ignore .gitkeep export-ignore +# Embedded headers hold the exact bytes of their text sources. Freshness tests +# re-read those sources, so Windows checkouts must preserve LF for every asset. +js/core/WebFront.js text eol=lf +js/core/bootstrap/* text eol=lf +js/core/favicon.ico binary +include/webfront/system/WebFrontJsData.hpp text eol=lf +js/core/fallback/index.html text eol=lf +js/core/fallback/webfront-fallback.mjs text eol=lf +include/webfront/system/FallbackIndexHtmlData.hpp text eol=lf +include/webfront/system/FallbackModuleData.hpp text eol=lf # Fuzzer seeds retain exact protocol bytes, including HTTP CRLF. -fuzz/corpus/** binary +test/fuzz/corpus/** binary -# Pinned third-party sources and generated dependency data keep exact bytes on Windows. -third_party/react/* text eol=lf -third_party/babel/* text eol=lf -third_party/jasmine/* text eol=lf -third_party/jasmine/*.png binary -third_party/fflate/* text eol=lf -include/system/*Data.hpp text eol=lf +# Generated dependency data keeps exact bytes on Windows. +include/webfront/system/*Data.hpp text eol=lf # Browser-powered developer bootstrap sources and generated payloads. -assets/developer/* text eol=lf -tools/assets/package-lock.json text eol=lf +js/developer/environment/* text eol=lf # Starter archives and every hashed distribution input must be identical on Windows. -tools/developer/starters/pi/* text eol=lf examples/life/ui/* text eol=lf -tools/developer/* text eol=lf +js/developer/tools/* text eol=lf + +# The wf project of the repository: its scripts, manifest and lock are hashed inputs of the self-build. +js/developer/scripts/* text eol=lf +js/developer/webfront.project.json text eol=lf +js/developer/webfront-packages.lock.json text eol=lf diff --git a/CONTRIBUTING.md b/.github/CONTRIBUTING.md similarity index 93% rename from CONTRIBUTING.md rename to .github/CONTRIBUTING.md index fb36412a..e933361a 100644 --- a/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -82,7 +82,7 @@ This workflow ensures that `master` always reflects the latest deployable versio ## Tooling -To ensure consistency, we use `.clang-format` and `.clang-tidy` to enforce our coding style. These configuration files are included in the root of the repository. +To ensure consistency, we use `.clang-format` and `clang-tidy` to enforce our coding style. `.clang-format` is next to the C++ it formats (`include/webfront/`, `test/` and `examples/` each have their own copy, so their styles may diverge); the clang-tidy configuration is `cmake/clang-tidy.yaml`, applied by `-DENABLE_CLANG_TIDY=ON` (or `clang-tidy --config-file=cmake/clang-tidy.yaml`). - **Clang-Format:** Automatically formats your code to match our style guidelines. - **Clang-Tidy:** Detects and warns about style violations, bugs, and non-modern C++ practices. diff --git a/.github/actions/remove-node/action.yml b/.github/actions/remove-node/action.yml new file mode 100644 index 00000000..4db5d1c3 --- /dev/null +++ b/.github/actions/remove-node/action.yml @@ -0,0 +1,33 @@ +name: Remove Node.js +description: >- + Deletes node, nodejs, npm, npx and corepack from the runner (an ephemeral machine), then checks that none is reachable: + the steps that follow are the proof that a path needs no Node.js. +runs: + using: composite + steps: + - name: Remove Node.js, npm and npx + shell: bash + run: | + # A hosted Windows runner has no sudo: its user may delete the files itself. + remove() { if [ "$RUNNER_OS" = Windows ]; then rm -f "$1"; else sudo rm -f "$1"; fi; } + for tool in node nodejs npm npx corepack; do + while path=$(command -v "$tool"); do + remove "$path" || exit 1 + hash -r + done + done + # On Windows the command shims (npm.cmd, npx.cmd, corepack.cmd) are separate files next to the executables. + if [ "$RUNNER_OS" = Windows ]; then + for tool in npm npx corepack; do + while path=$(command -v "$tool.cmd"); do + rm -f "$path" || exit 1 + hash -r + done + done + fi + for tool in node nodejs npm npx corepack; do + if command -v "$tool"; then + echo "::error::$tool is still reachable" + exit 1 + fi + done diff --git a/.github/actions/setup-cmake/action.yml b/.github/actions/setup-cmake/action.yml new file mode 100644 index 00000000..60235d23 --- /dev/null +++ b/.github/actions/setup-cmake/action.yml @@ -0,0 +1,51 @@ +name: Set up CMake +description: >- + Installs an exact CMake release from its Kitware archive, checked against a SHA-256 pinned here. No GitHub API call + lists the releases, so the installation cannot fail on an incomplete answer ("Unable to find version matching"). +inputs: + version: + description: Exact CMake version; its archives must have a pinned SHA-256 below. + required: true +runs: + using: composite + steps: + - name: Install CMake ${{ inputs.version }} + shell: bash + env: + VERSION: ${{ inputs.version }} + run: | + set -euo pipefail + case "$RUNNER_OS" in + Linux) platform=linux-x86_64; extension=tar.gz; bin=bin ;; + macOS) platform=macos-universal; extension=tar.gz; bin=CMake.app/Contents/bin ;; + Windows) platform=windows-x86_64; extension=zip; bin=bin ;; + *) echo "::error::No CMake archive for $RUNNER_OS"; exit 1 ;; + esac + name="cmake-$VERSION-$platform" + # From cmake--SHA-256.txt of each Kitware release. + case "$name.$extension" in + cmake-4.4.4-linux-x86_64.tar.gz) expected=e5bb807f7728cb60cd8b27ebc97a2edb469b68655f21e844a600c3575b76f5bb ;; + cmake-4.4.4-macos-universal.tar.gz) expected=4b7b73704b1db9b374e5c9ab8e17ac6148b817b6396ee75cd94a852cbac9d305 ;; + cmake-4.4.4-windows-x86_64.zip) expected=bace36e94b31c68ab6fa295f26dfa11219e0701cf7c94b0284a7d1cb13dac536 ;; + cmake-4.3.1-linux-x86_64.tar.gz) expected=208d76804009cbe8ec9aea0aa052c857c6e59bd289b43b9941c99324dc78b1d8 ;; + cmake-4.3.1-macos-universal.tar.gz) expected=c21fe4ade82a6a236aae0b9fbd8263c7ac6824a3fb32d03594456e30b06f3b7f ;; + cmake-4.3.1-windows-x86_64.zip) expected=03a610be931546474e46a442d171ef10532f4fc847de9cf76b7a8065bbef6a23 ;; + *) echo "::error::No pinned SHA-256 for $name.$extension: add it to .github/actions/setup-cmake/action.yml"; exit 1 ;; + esac + archive="$RUNNER_TEMP/$name.$extension" + curl -fsSL --retry 5 --retry-all-errors --retry-delay 15 -o "$archive" \ + "https://github.com/Kitware/CMake/releases/download/v$VERSION/$name.$extension" + # From standard input: with a file name, sha256sum escapes a Windows path and prefixes the hash with "\". + if command -v sha256sum > /dev/null; then actual=$(sha256sum < "$archive" | cut -d' ' -f1) + else actual=$(shasum -a 256 < "$archive" | cut -d' ' -f1); fi + if [ "$actual" != "$expected" ]; then + echo "::error::$name.$extension has SHA-256 $actual, expected $expected"; exit 1 + fi + if [ "$extension" = zip ]; then + pwsh -NoProfile -Command "Expand-Archive -LiteralPath '$(cygpath -w "$archive")' -DestinationPath '$(cygpath -w "$RUNNER_TEMP")' -Force" + cygpath -w "$RUNNER_TEMP/$name/$bin" >> "$GITHUB_PATH" + else + tar -xzf "$archive" -C "$RUNNER_TEMP" + echo "$RUNNER_TEMP/$name/$bin" >> "$GITHUB_PATH" + fi + "$RUNNER_TEMP/$name/$bin/cmake" --version diff --git a/.github/actions/wf-driver/action.yml b/.github/actions/wf-driver/action.yml new file mode 100644 index 00000000..0911c62f --- /dev/null +++ b/.github/actions/wf-driver/action.yml @@ -0,0 +1,42 @@ +name: Build the wf driver +description: >- + Builds webfront-wf (WebKitGTK frontend), the non-interactive driver of the WebFront developer environment, from the + bootstrap environment pinned by cmake/WebFrontBootstrap.cmake, and installs a `wf` command that runs a wf command on the + project at the root of the workspace. Node.js is neither used nor required. +runs: + using: composite + steps: + - uses: ./.github/actions/setup-cmake + with: + version: '4.4.4' + # Ubuntu 26.04 ships GCC 16 in its main archive. The image already provides Ninja, pkg-config and Xvfb. + - name: Install GCC 16 and WebKitGTK + shell: bash + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends -o Acquire::Retries=3 gcc-16 g++-16 libwebkitgtk-6.0-dev + echo "CC=gcc-16" >> "$GITHUB_ENV" + echo "CXX=g++-16" >> "$GITHUB_ENV" + - name: Build webfront-wf + shell: bash + run: | + cmake -S . -B build-driver -G Ninja -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_EMBED_CEF=OFF -DENABLE_TESTING=ON \ + -DWEBFRONT_EMBED_WEBKITGTK=ON -DWEBFRONT_WEBTEST_FRONTEND=WebKitGTK \ + -DCMAKE_CXX_SCAN_FOR_MODULES=OFF + cmake --build build-driver --target webfront-wf --parallel 2 + - name: Install the wf command + shell: bash + run: | + bin="$RUNNER_TEMP/wf-bin" + mkdir -p "$bin" + # The sandbox opt-out is confined to this driver, which runs trusted sources and a verified environment. + cat > "$bin/wf" < - - - diff --git a/assets/components/terminal/terminal.mjs b/assets/components/terminal/terminal.mjs deleted file mode 100644 index 62acbf67..00000000 --- a/assets/components/terminal/terminal.mjs +++ /dev/null @@ -1,360 +0,0 @@ -/// @brief WebFront terminal component: an xterm.js terminal whose line editor sends each validated -/// line to the C++ commands registered through webfront::Terminal (include/components/Terminal.hpp), -/// unless a browser command of an extension module (Terminal::extension) handles it first. - -import {Terminal} from "./xterm.mjs"; -import {FitAddon} from "./addon-fit.mjs"; - -const ansi = { - red: (text) => `\x1b[31m${text}\x1b[0m`, - clearToEnd: "\x1b[K", - clearScreen: "\x1b[2J\x1b[3J\x1b[H", - left: (count) => (count > 0 ? `\x1b[${count}D` : ""), -}; - -function commonPrefix(words) { - return words.reduce((prefix, word) => { - const limit = Math.min(prefix.length, word.length); - let length = 0; - while (length < limit && prefix[length] === word[length]) - ++length; - return prefix.slice(0, length); - }); -} - -// Reads a line for tokenize(), one word part at a time. -class Scanner { - constructor(line) { - this.line = line; - this.index = 0; - } - - get done() { - return this.index === this.line.length; - } - - next(problem) { - if (this.done) - throw new SyntaxError(problem); - return this.line[this.index++]; - } - - // The content of a quoted string whose opening quote was read. Inside double quotes a backslash - // escapes the next character; one ending the line stays literal, and the missing closing quote - // is reported next. - quoted(quote) { - let content = ""; - for (let char = this.next("Unterminated quote"); char !== quote; char = this.next("Unterminated quote")) - content += quote === '"' && char === "\\" && !this.done ? this.next() : char; - return content; - } - - // What `char`, read outside quotes, adds to the current word. - part(char) { - if (char === "\\") - return this.next("Trailing backslash"); - if (char === "'" || char === '"') - return this.quoted(char); - return char; - } -} - -/// Splits a line into words like terminal::tokenize in C++: whitespace separates words, single quotes -/// keep their content verbatim, double quotes keep it but honor backslash escapes, and an unquoted -/// backslash escapes the next character. Throws a SyntaxError on an unterminated quote or a trailing -/// backslash. -export function tokenize(line) { - const words = []; - const scanner = new Scanner(line); - let word = null; // null between words - while (!scanner.done) { - const char = scanner.next(); - const separator = char === " " || char === "\t"; - if (separator && word !== null) - words.push(word); - word = separator ? null : (word ?? "") + scanner.part(char); - } - if (word !== null) - words.push(word); - return words; -} - -// Browser command output uses "\n" line endings, converted like C++ output. -const toTerminalText = (text) => text.replace(/(? 0 ? commands.get(words[0]) : undefined; - if (!handler) - return runInCpp(line); - const output = await handler(words.slice(1), { - line, - bridge, - signal, - write: (text) => write(toTerminalText(String(text))), - runInCpp: () => runInCpp(line), - }); - return output === undefined ? runInCpp(line) : toTerminalText(String(output)); -} - -/// Imports the extension modules listed by C++ ("\n"-separated URLs) and collects their browser -/// commands. A module that fails to load is reported and skipped. -async function loadExtensions(urls, write) { - const commands = new Map(); - for (const url of urls.split("\n").filter((entry) => entry !== "")) { - try { - const module = await import(url); - for (const [name, handler] of Object.entries(module.commands ?? {})) - commands.set(name, handler); - } catch (error) { - write(ansi.red(`Terminal extension ${url} failed to load: ${error?.message ?? error}`) + "\r\n"); - } - } - return commands; -} - -// Editing keys, as xterm.js reports them in onData, mapped to LineEditor actions. -const keyActions = new Map([ - ["\r", (editor) => editor.submit()], - ["\x7f", (editor) => editor.erase(-1)], - ["\b", (editor) => editor.erase(-1)], - ["\x1b[3~", (editor) => editor.erase(0)], - ["\x1b[D", (editor) => editor.moveTo(editor.cursor - 1)], - ["\x1b[C", (editor) => editor.moveTo(editor.cursor + 1)], - ["\x1b[H", (editor) => editor.moveTo(0)], - ["\x1bOH", (editor) => editor.moveTo(0)], - ["\x01", (editor) => editor.moveTo(0)], - ["\x1b[F", (editor) => editor.moveTo(editor.chars.length)], - ["\x1bOF", (editor) => editor.moveTo(editor.chars.length)], - ["\x05", (editor) => editor.moveTo(editor.chars.length)], - ["\x1b[A", (editor) => editor.recall(-1)], - ["\x1b[B", (editor) => editor.recall(1)], - ["\t", (editor) => editor.track(editor.completeLine())], - ["\x03", (editor) => editor.cancelLine()], - ["\x0c", (editor) => editor.redraw(ansi.clearScreen)], - ["\x15", (editor) => editor.killBeforeCursor()], -]); - -/// Line editor driven by the terminal's input data. `write(text)` displays text; `run(line)` and -/// `complete(line)` return Promises of the C++ output and of "\n"-separated completion candidates. -export class LineEditor { - constructor({write, run, complete, prompt}) { - this.write = write; - this.run = run; - this.complete = complete; - this.abort = null; - this.prompt = prompt; - this.chars = []; - this.cursor = 0; - this.history = []; - this.historyIndex = 0; - this.busy = null; - } - - get line() { - return this.chars.join(""); - } - - /// Resolves once no command or completion is pending. - async whenIdle() { - while (this.busy) - await this.busy; - } - - showPrompt() { - this.write(this.prompt); - } - - handle(data) { - if (this.busy) - return this.interrupt(data); - const action = keyActions.get(data); - if (action) - return action(this); - if (!data.startsWith("\x1b")) - return this.insertText(data); - } - - // While a command runs, Ctrl+C aborts its signal once and the other keys are ignored. - interrupt(data) { - const running = this.abort?.signal.aborted === false; - if (data !== "\x03" || !running) - return; - this.write("^C\r\n"); - this.abort.abort(new Error("Interrupted")); - } - - // Typed or pasted text: printable characters are inserted, a carriage return submits the line - // and the rest of a multi-line paste is dropped, since commands run one at a time. - insertText(data) { - const [text, ...rest] = data.split("\r"); - this.insert(Array.from(text).filter((char) => char >= " " && char !== "\x7f")); - if (rest.length > 0) - return this.submit(); - } - - insert(chars) { - if (chars.length === 0) - return; - this.chars.splice(this.cursor, 0, ...chars); - this.cursor += chars.length; - this.redraw(); - } - - erase(offset) { - const index = this.cursor + offset; - if (index < 0 || index >= this.chars.length) - return; - this.chars.splice(index, 1); - this.cursor = index; - this.redraw(); - } - - killBeforeCursor() { - this.chars.splice(0, this.cursor); - this.cursor = 0; - this.redraw(); - } - - moveTo(position) { - const cursor = Math.max(0, Math.min(this.chars.length, position)); - if (cursor === this.cursor) - return; - this.cursor = cursor; - this.redraw(); - } - - recall(direction) { - const index = this.historyIndex + direction; - if (index < 0 || index > this.history.length) - return; - this.historyIndex = index; - this.chars = Array.from(index === this.history.length ? "" : this.history[index]); - this.cursor = this.chars.length; - this.redraw(); - } - - cancelLine() { - this.write("^C\r\n"); - this.chars = []; - this.cursor = 0; - this.historyIndex = this.history.length; - this.showPrompt(); - } - - // Rewrites the prompt and the line in place, then moves the cursor back to its position. - redraw(prefix = "\r") { - this.write(prefix + this.prompt + this.line + ansi.clearToEnd + ansi.left(this.chars.length - this.cursor)); - } - - track(promise) { - this.busy = promise.finally(() => { - this.busy = null; - }); - return this.busy; - } - - submit() { - const line = this.line; - this.write("\r\n"); - this.chars = []; - this.cursor = 0; - if (line.trim() !== "" && this.history.at(-1) !== line) - this.history.push(line); - this.historyIndex = this.history.length; - return this.track(this.execute(line)); - } - - async execute(line) { - this.abort = new AbortController(); - try { - const output = await this.run(line, this.abort.signal); - // The prompt starts on a new line, unless the output already ends one or leaves the - // cursor at home (such as the 'clear' command). - if (output) - this.write(output.endsWith("\n") || output.endsWith("\x1b[H") ? output : output + "\r\n"); - } catch (error) { - this.write(ansi.red(`Error: ${error?.message ?? error}`) + "\r\n"); - } - this.showPrompt(); - } - - async completeLine() { - // Only the command name is completed, and only with the cursor at the end of the line. - if (this.cursor !== this.chars.length) - return; - const line = this.line; - let candidates; - try { - candidates = (await this.complete(line)).split("\n").filter((word) => word !== ""); - } catch (error) { - return; - } - if (candidates.length === 0) - return; - const completion = candidates.length === 1 ? candidates[0] + " " : commonPrefix(candidates); - if (completion.length > line.length) - return this.insert(Array.from(completion.slice(line.length))); - this.write("\r\n" + candidates.join(" ") + "\r\n"); - this.redraw(); - } -} - -/// Mounts a terminal in `element` once the WebFront bridge is ready. Returns the xterm Terminal, -/// its line editor and a `flush()` resolving when every write has been rendered. -export async function mount(element, {bridge = globalThis.webFront, terminalOptions = {}} = {}) { - const terminal = new Terminal({ - cursorBlink: true, - convertEol: false, - fontFamily: 'ui-monospace, "Cascadia Code", "Source Code Pro", Menlo, Consolas, monospace', - theme: {background: "#0d1117", foreground: "#e6edf3"}, - ...terminalOptions, - }); - const fit = new FitAddon(); - terminal.loadAddon(fit); - terminal.open(element); - fit.fit(); - new ResizeObserver(() => fit.fit()).observe(element); - - let lastWrite = Promise.resolve(); - const write = (text) => { - lastWrite = new Promise((resolve) => terminal.write(text, resolve)); - }; - const flush = () => lastWrite; - - try { - await bridge.ready; - } catch (error) { - write(ansi.red(`Connection to the application failed: ${error?.message ?? error}`) + "\r\n"); - return {terminal, editor: null, flush}; - } - - const call = (name) => bridge.cppFunction(`webfront.terminal.${name}`); - let prompt, banner, extensions; - try { - [prompt, banner, extensions] = await Promise.all([call("prompt")(), call("banner")(), call("extensions")()]); - } catch (error) { - // For example a page served by an application without webfront::Terminal. - write(ansi.red(`Terminal unavailable: ${error?.message ?? error}`) + "\r\n"); - return {terminal, editor: null, flush}; - } - const commands = await loadExtensions(extensions, write); - const runInCpp = call("run"); - const run = (line, signal) => runLine(line, {commands, runInCpp, write, bridge, signal}); - const editor = new LineEditor({write, run, complete: call("complete"), prompt}); - if (banner) - write(banner.replaceAll("\n", "\r\n") + "\r\n"); - editor.showPrompt(); - terminal.onData((data) => editor.handle(data)); - terminal.focus(); - return {terminal, editor, flush}; -} diff --git a/assets/components/tools/wf.mjs b/assets/components/tools/wf.mjs deleted file mode 100644 index 82ffcc63..00000000 --- a/assets/components/tools/wf.mjs +++ /dev/null @@ -1,341 +0,0 @@ -/// @brief Browser side of the wf tool manager (#234), a terminal extension added by -/// webfront::ToolManager (include/components/ToolManager.hpp). 'wf search', 'wf install' and -/// 'wf open' run here, because the download speaks HTTPS; 'wf list', 'wf remove' and 'wf help' run -/// in C++. An installation fetches the packument and the tarball from the npm registry, checks the -/// tarball's SHA-512 integrity, unpacks it and sends its files through webfront.pkg.begin, -/// .writeFile and .commit. - -const blockSize = 512; -/// Files cross the bridge in chunks of this many bytes; the browser sends a large one in several -/// WebSocket frames, which the server reassembles. -export const chunkSize = 256 * 1024; -/// Largest unpacked tarball accepted, against decompression bombs. -export const maxUnpackedBytes = 256 * 1024 * 1024; -const utf8 = new TextDecoder(); - -/// Splits "name[@version]", where the name may be scoped ("@scope/name@1.0.0"). The version is "" -/// when absent. -export function parseSpec(spec) { - const at = spec.indexOf("@", spec.startsWith("@") ? 1 : 0); - return at < 0 ? {name: spec, version: ""} : {name: spec.slice(0, at), version: spec.slice(at + 1)}; -} - -function registryBase(registry) { - const base = new URL(registry, globalThis.location?.href); - if (!base.pathname.endsWith("/")) - base.pathname += "/"; - return base; -} - -// The registry encodes the slash of a scoped name. -const packumentUrl = (base, name) => new URL(name.replace("/", "%2f"), base); - -async function fetchOk(url, fetchImpl, signal) { - const response = await fetchImpl(url, {signal}); - if (!response.ok) - throw new Error(`${url}: HTTP ${response.status}`); - return response; -} - -async function fetchJson(url, fetchImpl, signal) { - return (await fetchOk(url, fetchImpl, signal)).json(); -} - -function resolveManifest(packument, name, requested) { - const tag = requested || "latest"; - const version = packument["dist-tags"]?.[tag] ?? requested; - const manifest = packument.versions?.[version]; - if (!manifest) - throw new Error(`${name} has no version '${tag}'`); - return manifest; -} - -/// Checks bytes against an SRI integrity string ("sha512-", possibly several hashes -/// separated by spaces) and returns the matching "sha512-…" hash. Only SHA-512 is accepted. -export async function verifyIntegrity(bytes, integrity) { - const expected = String(integrity ?? "") - .split(/\s+/) - .filter((hash) => hash.startsWith("sha512-")) - .map((hash) => hash.split("?")[0]); - if (expected.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)"); - const digest = new Uint8Array(await crypto.subtle.digest("SHA-512", bytes)); - const actual = "sha512-" + btoa(Array.from(digest, (byte) => String.fromCharCode(byte)).join("")); - if (!expected.includes(actual)) - throw new Error(`Integrity check failed: expected ${expected[0]}, got ${actual}`); - return actual; -} - -/// Gunzips bytes, failing once more than `limit` bytes come out. -export async function gunzip(bytes, limit = maxUnpackedBytes) { - const reader = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip")).getReader(); - const chunks = []; - let total = 0; - for (let read = await reader.read(); !read.done; read = await reader.read()) { - total += read.value.length; - if (total > limit) { - await reader.cancel(); - throw new Error(`The tarball unpacks to more than ${limit} bytes`); - } - chunks.push(read.value); - } - return new Uint8Array(await new Blob(chunks).arrayBuffer()); -} - -// A NUL-terminated header field. -function text(block, offset, length) { - const field = block.subarray(offset, offset + length); - const end = field.indexOf(0); - return utf8.decode(end < 0 ? field : field.subarray(0, end)); -} - -// An octal number, or a base-256 one when the first byte has its high bit set (GNU and star). -function number(block, offset, length) { - if (block[offset] & 0x80) - return block.subarray(offset + 1, offset + length).reduce((value, byte) => value * 256 + byte, block[offset] & 0x7f); - const digits = text(block, offset, length).trim(); - if (!/^[0-7]*$/.test(digits)) - throw new Error("Corrupt tar header"); - return digits === "" ? 0 : parseInt(digits, 8); -} - -function verifyChecksum(header) { - let sum = 0; - for (let index = 0; index < blockSize; ++index) - sum += index >= 148 && index < 156 ? 0x20 : header[index]; - if (number(header, 148, 8) !== sum) - throw new Error("Corrupt tar header checksum"); -} - -// " =\n" records of a pax extended header; lengths count bytes. -function paxRecords(data) { - const records = {}; - let offset = 0; - while (offset < data.length) { - const space = data.indexOf(0x20, offset); - const length = space < 0 ? NaN : Number(utf8.decode(data.subarray(offset, space))); - if (!(length > 0) || offset + length > data.length) - throw new Error("Corrupt pax header"); - const record = utf8.decode(data.subarray(space + 1, offset + length - 1)); - const equals = record.indexOf("="); - records[record.slice(0, equals)] = record.slice(equals + 1); - offset += length; - } - return records; -} - -// The entry whose header starts at `offset`: its header, type flag, data and the offset of the next -// entry. -function readEntry(archive, offset) { - const header = archive.subarray(offset, offset + blockSize); - verifyChecksum(header); - const size = number(header, 124, 12); - const start = offset + blockSize; - if (start + size > archive.length) - throw new Error("Truncated tar archive"); - return { - header, - type: header[156] === 0 ? "0" : String.fromCharCode(header[156]), - data: archive.subarray(start, start + size), - next: start + Math.ceil(size / blockSize) * blockSize, - }; -} - -// An archive ends at two zero blocks; one is enough to stop. -function isEnd(archive, offset) { - return offset + blockSize > archive.length || archive.subarray(offset, offset + blockSize).every((byte) => byte === 0); -} - -// The name field of a ustar header, after its prefix field. -function headerPath(header) { - const name = text(header, 0, 100); - const prefix = text(header, 257, 5) === "ustar" ? text(header, 345, 155) : ""; - return prefix ? `${prefix}/${name}` : name; -} - -// Entries naming the next one: a pax extended header and a GNU long name. A pax global header names -// nothing WebFront uses. -const nameEntries = { - x: (names, data) => ({...names, pax: paxRecords(data).path}), - L: (names, data) => ({...names, long: text(data, 0, data.length)}), - g: (names) => names, -}; - -/// Reads a tar archive (ustar, with pax and GNU long names) and returns its regular files as -/// {path, bytes}, in archive order. Directories, links and other entries are skipped. -export function readTar(archive) { - const files = []; - let names = {}; - for (let offset = 0; !isEnd(archive, offset);) { - const {header, type, data, next} = readEntry(archive, offset); - offset = next; - if (Object.hasOwn(nameEntries, type)) { - names = nameEntries[type](names, data); - continue; - } - if (type === "0" || type === "7") - files.push({path: names.pax ?? names.long ?? headerPath(header), bytes: data}); - names = {}; - } - return files; -} - -/// The files of an npm tarball by path relative to the package root: the first path component -/// (normally "package/") is removed, as npm does. A later entry replaces an earlier one. -function packageFiles(entries) { - const files = new Map(); - for (const {path, bytes} of entries) { - const relative = path.replace(/^(\.?\/)+/, "").split("/").slice(1).join("/"); - if (relative !== "") - files.set(relative, bytes); - } - return files; -} - -function packageJson(files, name, version) { - const manifest = files.get("package.json"); - if (!manifest) - throw new Error(`${name}@${version} has no package.json`); - const pkg = JSON.parse(utf8.decode(manifest)); - if (pkg.name !== name || pkg.version !== version) - throw new Error(`The archive contains ${pkg.name}@${pkg.version}, not ${name}@${version}`); - return pkg; -} - -const isTool = (field) => field?.kind === "tool" && typeof field.entry === "string"; - -function toolOf(files, name, version) { - const tool = packageJson(files, name, version).webfront; - if (!isTool(tool)) - throw new Error(`${name} is not a WebFront tool: its package.json has no webfront field with kind "tool" and an entry`); - return {entry: tool.entry.replace(/^(\.\/)+/, ""), title: typeof tool.title === "string" ? tool.title : name}; -} - -const pkgFunction = (bridge, name) => bridge.cppFunction(`webfront.pkg.${name}`); - -/// Options shared by search() and install(): -/// bridge the WebFront bridge (globalThis.webFront) -/// registry the npm registry URL (default: webfront.pkg.registry(), set in ToolManagerOptions) -/// fetch the fetch function -/// signal an AbortSignal stopping the downloads and the upload -async function settings({bridge = globalThis.webFront, registry, fetch: fetchImpl = (...args) => globalThis.fetch(...args), signal} = {}) { - return {bridge, fetchImpl, signal, base: registryBase(registry ?? (await pkgFunction(bridge, "registry")()))}; -} - -/// Searches the registry for packages with the webfront-tool keyword. Returns {name, version, -/// description} objects. -export async function search(term, options) { - const {fetchImpl, signal, base} = await settings(options); - const url = new URL("-/v1/search", base); - url.searchParams.set("text", `keywords:webfront-tool ${term}`.trim()); - url.searchParams.set("size", "20"); - const result = await fetchJson(url, fetchImpl, signal); - return (result.objects ?? []).map(({package: found}) => ({ - name: found.name, - version: found.version, - description: found.description ?? "", - })); -} - -// Downloads the tarball of a manifest and returns its files with the verified integrity. -async function download(manifest, packumentLocation, fetchImpl, signal) { - const tarballUrl = new URL(manifest.dist?.tarball ?? "", packumentLocation); - const tarball = new Uint8Array(await (await fetchOk(tarballUrl, fetchImpl, signal)).arrayBuffer()); - const integrity = await verifyIntegrity(tarball, manifest.dist?.integrity); - return {integrity, files: packageFiles(readTar(await gunzip(tarball)))}; -} - -// Sends the files to webfront.pkg.writeFile in chunks; an empty file is sent as one empty chunk. -async function upload(files, {bridge, name, version, signal}) { - const writeFile = pkgFunction(bridge, "writeFile"); - for (const [path, bytes] of files) { - let offset = 0; - do { - signal?.throwIfAborted(); - const chunk = bytes.subarray(offset, offset + chunkSize); - await writeFile(name, version, path, offset, chunk); - offset += chunk.length; - } while (offset < bytes.length); - } -} - -/// Downloads, verifies and stores "name[@version or dist-tag]" (latest by default). `progress(text)` -/// reports the steps. Resolves to {name, version, title, entry, files}; rejects without changing the -/// installed version when anything fails or `signal` is aborted. -export async function install(spec, {progress = () => {}, ...options} = {}) { - const {name, version: requested} = parseSpec(spec); - const {bridge, fetchImpl, signal, base} = await settings(options); - const packumentLocation = packumentUrl(base, name); - const manifest = resolveManifest(await fetchJson(packumentLocation, fetchImpl, signal), name, requested); - const {version} = manifest; - progress(`Downloading ${name}@${version}…`); - const {integrity, files} = await download(manifest, packumentLocation, fetchImpl, signal); - const {entry, title} = toolOf(files, name, version); - if (!files.has(entry)) - throw new Error(`The entry page ${entry} of ${name} is not in the package`); - - progress(`Installing ${files.size} files…`); - await pkgFunction(bridge, "begin")(name, version); - await upload(files, {bridge, name, version, signal}); - signal?.throwIfAborted(); - await pkgFunction(bridge, "commit")(name, version, integrity, entry, title); - return {name, version, title, entry, files: files.size}; -} - -/// The installed tools, from the pages of webfront.pkg.list(): {name, version, url, title} objects. -export async function installed(bridge = globalThis.webFront) { - const list = pkgFunction(bridge, "list"); - const tools = []; - for (;;) { - const lines = (await list(tools.length)).split("\n").filter((line) => line !== ""); - if (lines.length === 0) - return tools; - for (const line of lines) { - const [name, version, url, title] = line.split("\t"); - tools.push({name, version, url, title}); - } - } -} - -/// Opens the entry page of an installed tool in a new tab or window, and resolves to its URL. -export async function open(name, bridge = globalThis.webFront) { - const tool = (await installed(bridge)).find((candidate) => candidate.name === name); - if (!tool) - throw new Error(`${name} is not installed`); - return {...tool, opened: globalThis.open(tool.url, "_blank") !== null}; -} - -function requireOne(args) { - if (args.length !== 1) - throw new Error("Wrong number of arguments. Type 'wf help'."); - return args[0]; -} - -function formatFound(found) { - if (found.length === 0) - return "No tool found."; - const width = Math.max(...found.map(({name, version}) => name.length + version.length + 1)); - return found.map(({name, version, description}) => `${name}@${version}`.padEnd(width + 2) + description).join("\n"); -} - -// The wf subcommands running in the browser; 'wf list', 'wf remove' and 'wf help' run in C++. -const subcommands = { - search: async (args, {bridge, signal}) => formatFound(await search(args.join(" "), {bridge, signal})), - install: async (args, {bridge, signal, write}) => { - const tool = await install(requireOne(args), {bridge, signal, progress: (step) => write(step + "\n")}); - return `Installed ${tool.name}@${tool.version}: ${tool.title}. Type 'wf open ${tool.name}'.`; - }, - open: async (args, {bridge}) => { - const tool = await open(requireOne(args), bridge); - return tool.opened ? `Opened ${tool.title}: ${tool.url}` : `The browser blocked the new window. Open ${tool.url}`; - }, -}; - -async function wf([command, ...args], context) { - return Object.hasOwn(subcommands, command) ? subcommands[command](args, context) : undefined; -} - -/// Terminal browser commands (see Terminal::extension). -export const commands = {wf}; diff --git a/assets/developer/bootstrap.bundle.mjs b/assets/developer/bootstrap.bundle.mjs deleted file mode 100644 index 3b130c47..00000000 --- a/assets/developer/bootstrap.bundle.mjs +++ /dev/null @@ -1 +0,0 @@ -var u=new TextDecoder;async function p(t,e){let n=String(e??"").split(/\s+/).filter(a=>a.startsWith("sha512-")).map(a=>a.split("?")[0]);if(n.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 r=new Uint8Array(await crypto.subtle.digest("SHA-512",t)),o="sha512-"+btoa(Array.from(r,a=>String.fromCharCode(a)).join(""));if(!n.includes(o))throw new Error(`Integrity check failed: expected ${n[0]}, got ${o}`);return o}async function d(t,e=268435456){let n=new Blob([t]).stream().pipeThrough(new DecompressionStream("gzip")).getReader(),r=[],o=0;for(let a=await n.read();!a.done;a=await n.read()){if(o+=a.value.length,o>e)throw await n.cancel(),new Error(`The tarball unpacks to more than ${e} bytes`);r.push(a.value)}return new Uint8Array(await new Blob(r).arrayBuffer())}function l(t,e,n){let r=t.subarray(e,e+n),o=r.indexOf(0);return u.decode(o<0?r:r.subarray(0,o))}function y(t,e,n){if(t[e]&128)return t.subarray(e+1,e+n).reduce((o,a)=>o*256+a,t[e]&127);let r=l(t,e,n).trim();if(!/^[0-7]*$/.test(r))throw new Error("Corrupt tar header");return r===""?0:parseInt(r,8)}function T(t){let e=0;for(let n=0;n<512;++n)e+=n>=148&&n<156?32:t[n];if(y(t,148,8)!==e)throw new Error("Corrupt tar header checksum")}function S(t){let e={},n=0;for(;n0)||n+o>t.length)throw new Error("Corrupt pax header");let a=u.decode(t.subarray(r+1,n+o-1)),i=a.indexOf("=");e[a.slice(0,i)]=a.slice(i+1),n+=o}return e}function z(t,e){let n=t.subarray(e,e+512);T(n);let r=y(n,124,12),o=e+512;if(o+r>t.length)throw new Error("Truncated tar archive");return{header:n,type:n[156]===0?"0":String.fromCharCode(n[156]),data:t.subarray(o,o+r),next:o+Math.ceil(r/512)*512}}function U(t,e){return e+512>t.length||t.subarray(e,e+512).every(n=>n===0)}function I(t){let e=l(t,0,100),n=l(t,257,5)==="ustar"?l(t,345,155):"";return n?`${n}/${e}`:e}var h={x:(t,e)=>({...t,pax:S(e).path}),L:(t,e)=>({...t,long:l(e,0,e.length)}),g:t=>t};function m(t){let e=[],n={};for(let r=0;!U(t,r);){let{header:o,type:a,data:i,next:s}=z(t,r);if(r=s,Object.hasOwn(h,a)){n=h[a](n,i);continue}(a==="0"||a==="7")&&e.push({path:n.pax??n.long??I(o),bytes:i}),n={}}return e}var c=(t,e,...n)=>t.cppFunction(`webfront.developer.${e}`)(...n);async function g(t,e){let n=[],r=0;for(;;){let o=await c(t,"read",e,r);if(n.push(o),r+=o.length,o.length<262144)break;if(r>256*1024*1024)throw new Error("Project file is too large")}return new Uint8Array(await new Blob(n).arrayBuffer())}async function j(t,{id:e,path:n,bytes:r},o){for(let a=0;a{}),s}}async function B(t,e){let n=[],r=0;for(;;){let{done:o,value:a}=await t.read();if(o)return n;if(r+=a.length,r>e)throw new Error("Compressed download exceeds its byte limit");n.push(a)}}async function F(t,e){try{return await B(t,e)}catch(n){throw await t.cancel().catch(()=>{}),n}finally{t.releaseLock()}}async function b(t,e=64*1024*1024){if(!t.ok)throw new Error(`Download: HTTP ${t.status}`);if(Number(t.headers.get("content-length"))>e)throw new Error("Compressed download exceeds its byte limit");return new Uint8Array(await new Blob(await F(t.body.getReader(),e)).arrayBuffer())}var O=/[\\\0:*?"<>|]/,C=t=>t.split("/").some(e=>!e||e==="."||e==="..");function v(t){return typeof t!="string"||!t||O.test(t)?!0:C(t)}var w=t=>!v(t),P=new TextDecoder;function A(t,e){if(!e.path.startsWith("package/"))throw new Error("Invalid environment archive root");let n=e.path.slice(8);if(!w(n)||t.has(n))throw new Error("Invalid or duplicate environment path");t.set(n,e.bytes)}function L(t){let e=new Map;for(let n of m(t))A(e,n);return e}function R(t,e){return t.protocol!==1||!w(t.entry)?!1:e.has(t.entry)}async function x(t,e){await p(t,e);let n=L(await d(t));if(!n.has("environment.json"))throw new Error("Environment archive has no environment.json");let r=JSON.parse(P.decode(n.get("environment.json")));if(!R(r,n))throw new Error("Unsupported WebFront developer environment");return{files:n,manifest:r}}var k=".webfront/developer/environment.tgz";async function N(t,e){try{let n=await g(t,k);return await x(n,e),n}catch{return null}}async function W(t,e){let n=new URL(t.environment,location.href);if(n.protocol!=="https:"&&n.origin!==location.origin)throw new Error("The environment must use HTTPS or the application origin");let r=await e(n);if(!r.ok)throw new Error(`Environment download: HTTP ${r.status}`);return b(r)}function D(t){return!t||!w(t.archive)?!1:String(t.integrity).startsWith("sha512-")}function H(t,e){return Object.fromEntries(Object.entries(t.starters??{}).map(([n,r])=>{if(!D(r))throw new Error("Invalid pinned starter metadata");return[n,{url:new URL(r.archive,e).href,integrity:r.integrity}]}))}async function E(t,e,n=fetch,r=()=>{}){let o=await N(t,e.integrity);o?r("Using verified cached developer environment"):(r("Downloading developer environment"),o=await W(e,n));let{files:a,manifest:i}=await x(o,e.integrity),s=H(i,new URL(e.environment,location.href));return await f(t,".webfront/developer/environment",a),await f(t,k,new Map([["output",o]]),{directory:!1}),{url:`/webfront/developer/environment/${i.entry}`,config:{...e,starters:s}}}if(typeof document<"u"&&document.getElementById("retry")){let t=document.getElementById("status"),e=document.getElementById("retry"),n=async()=>{e.hidden=!0;try{await webFront.ready;let r=JSON.parse(await c(webFront,"config")),{url:o,config:a}=await E(webFront,r,fetch,s=>{t.textContent=s});await(await import(o)).mount({bridge:webFront,config:a,terminal:document.getElementById("terminal"),preview:document.getElementById("preview")}),t.textContent="Developer environment ready. Type wf help."}catch(r){t.textContent=`Bootstrap failed: ${r.message}`,e.hidden=!1}};e.addEventListener("click",n),n()} diff --git a/assets/developer/bundler.mjs b/assets/developer/bundler.mjs deleted file mode 100644 index 1e1f3e55..00000000 --- a/assets/developer/bundler.mjs +++ /dev/null @@ -1,60 +0,0 @@ -// Virtual project/npm filesystem for esbuild's browser API. No Node.js shims or network imports. -import {normalize, packageEntry} from './entry.mjs'; -import {resolveImport} from './resolve.mjs'; -export {normalize, packageEntry}; - -const decoder = new TextDecoder(); - -const extensions = ['', '.tsx', '.ts', '.jsx', '.js', '.mjs', '.cjs', '.json', '.css', '/index.tsx', '/index.ts', '/index.js']; -const loaders = new Map(Object.entries({mjs: 'js', cjs: 'js', js: 'js', jsx: 'jsx', ts: 'ts', tsx: 'tsx', css: 'css', json: 'json'})); - -// A file that does not exist is a miss in the project, but an error inside a locked package. -async function probe(read, namespace, candidate) { - try { return await read(namespace, candidate); } - catch (error) { - if (namespace !== 'project') throw error; - return undefined; - } -} - -function createFinder(packages, readProject, loaded) { - const read = async (namespace, path) => { - if (namespace === 'project') return readProject(path); - const slash = path.indexOf('/'); - return packages[path.slice(0, slash)]?.get(path.slice(slash + 1)); - }; - const find = async (namespace, path) => { - for (const suffix of extensions) { - const content = await probe(read, namespace, path + suffix); - if (content === undefined) continue; - loaded.set(`${namespace}:${path + suffix}`, content); - return {path: path + suffix, namespace}; - } - throw new Error(`Cannot resolve ${path}`); - }; - return {read, find}; -} - -export function virtualPlugin(lock, packages, readProject) { - const loaded = new Map(); - const {read, find} = createFinder(packages, readProject, loaded); - const load = namespace => async args => { - const bytes = loaded.get(`${namespace}:${args.path}`) ?? await read(namespace, args.path); - const loader = loaders.get(args.path.split('.').pop()); - return {contents: loader ? decoder.decode(bytes) : bytes, loader: loader ?? 'file'}; - }; - return {name: 'webfront-project', setup(build) { - build.onResolve({filter: /.*/}, args => resolveImport(args, lock, find)); - build.onLoad({filter: /.*/, namespace: 'empty'}, () => ({contents: '', loader: 'js'})); - for (const namespace of ['project', 'npm']) build.onLoad({filter: /.*/, namespace}, load(namespace)); - }}; -} - -export async function bundle(esbuild, {entry, lock, packages, readProject}) { - const result = await esbuild.build({entryPoints: [entry], bundle: true, write: false, - outdir: '/output', entryNames: 'app', assetNames: 'assets/[name]-[hash]', - format: 'esm', platform: 'browser', target: 'es2020', jsx: 'automatic', minify: true, - define: {'process.env.NODE_ENV': '"production"'}, legalComments: 'inline', - plugins: [virtualPlugin(lock, packages, readProject)]}); - return new Map(result.outputFiles.map(file => [file.path.replace(/^\/output\//, ''), file.contents])); -} diff --git a/assets/developer/bundles.json b/assets/developer/bundles.json deleted file mode 100644 index ca39e451..00000000 --- a/assets/developer/bundles.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "assets/developer/bootstrap.mjs": "534af4b3d07891338c3390e1d5e06c2fb6dd8df11ca6547735565b17f1b9cd70", - "assets/developer/bootstrap-entry.mjs": "ff8084f23f5acc721f97eb1ed0a454e7bfee1894de17d54f0100fa11f7ef8b77", - "assets/developer/packages.mjs": "faed29500a34c6ce24756d07bd4b47b9168ccec4bd49d12f00096a869637d74d", - "assets/developer/starter.mjs": "f8cdef1218ae14f8bbe49eae495d931cc29e33f74444f0e37d61aea416b9d750", - "assets/developer/paths.mjs": "6ebb626610756143c58762c87af18980802809d7f0f53d3b588e4b20e8db0161", - "assets/developer/runtime.mjs": "36847f4413928908ebc8a1909e608c783701b13274a289d81e43df0e5125a0e8", - "assets/developer/compiler.mjs": "3f7e187ca9a4c2645ef3823127457cad655919cbea3c7c0f22fb7ae2cc87e0e5", - "assets/developer/bundler.mjs": "b0ff79a1b0caa012c25ec7b7f121d7d50af1aa1651231d3dcf2f39470c4ea25c", - "assets/developer/entry.mjs": "b2b942443e3c74ae2c008392ba244d9b7e91db70ba1b4ebbe1357c455ebf51bb", - "assets/developer/conditions.mjs": "7f0ecba239480831e38985ccffd4c82309949924f4eb9d938e4ad1b09f5f36ed", - "assets/developer/io.mjs": "a155719c612e065c30272c0dfdc456df28b5efa90ca26f8cfcb55c9cb46de690", - "assets/developer/recipe.mjs": "809f2091c50ebd13d23f92de9876b584658dc687324f73d48ee9f1271319f1ed", - "assets/developer/registry.mjs": "f566f07ea066155ab7209d925cee2cf12a664ac51b07bc0ca3e3fd8fde49a9c8", - "assets/developer/archive.mjs": "1fb8b9c3c27219858597801104639bba1104c7a7d33973609cd556b5e5f81d2d", - "assets/developer/lock.mjs": "60d0ea14d24793cd5e85bbd4bb4bfe90d2c7d76c0d20ffc99f462595a6e57291", - "assets/developer/pins.mjs": "ddb2214a2e906cb117dc1bac0b5b056decd4f6c6e3d4713615176c1876db3534", - "assets/developer/peers.mjs": "e1d999892138682fc0134ef1f4d4b19b9a9ad8d7fb16e37fc9c6c684bd853896", - "assets/developer/resolve.mjs": "8b96b850af215be51f5cb85cc9c69e057afa04dfb8a57e572620c07059c17fa3", - "assets/developer/embed.mjs": "c8fb80998abecdd5fdeba77aa549ff638d849dc9fd7f34c896fb6c0c0bf15f34", - "tools/developer/starters/pi/main.tsx": "d3161b35db204ba54f782f711183e8d96aeff7c92d885c33a6ec168cf461e453", - "tools/developer/starters/pi/style.css": "360e2c7ae6d3699b00e18cbf67efbae7a8d8863d88926b31139e102cf38e5abd", - "examples/life/ui/main.tsx": "ed11a82aad1639eb6997af8b0fca4d5c5ed4c36422c22a74ac49ae73078d0a91", - "examples/life/ui/style.css": "9bb55eb0f0a3287e5b7dc78af9d69608b87ff42c4d9c8a653bc83a52fe293c44", - "assets/components/tools/wf.mjs": "6ee86d85ec96bf548ca25ea3ea3554b7dacbed7d047d6a9cfdc1e0f3f42de05e", - "tools/developer/distribution.json": "f17197a710d994a83dd35fbb983ae672ae00144bc81eb3f22a78bbaf5f26f658", - "tools/developer/build.mjs": "c486ac6816e7c18c51d4b75dd3b032616ee081a4461a4125a5c1753f00d36c8d", - "tools/developer/site.mjs": "d4b7112f0aa5f277f291505a3dce84e676fee9d4da386973af7c6df9885d4dd4", - "tools/developer/archive.mjs": "bfe9feeb5e4d4e1b7c44c4dec4dcbeab4ae59c2bf16a1d2b32cd6910a2b84e7b", - "tools/assets/package-lock.json": "eb545112b672f9dbf520125df1f44a878d62cc8e611f0e33baee36470ded4dec", - "assets/developer/bootstrap.bundle.mjs": "792fe7cf564bd12ac47fef419d8c71e2070925764a17706552e7d3f5d6ba2181", - "assets/developer/packages.bundle.mjs": "994c13a8b30a40ecea98414caa72a17927dcea81a1f62d47744b4f55d87005be", - "include/system/DeveloperReleaseData.hpp": "89dd809cf07eb5f3c11c772f385941b81cf78b94ad3719ab1c40e844c246bc76" -} diff --git a/assets/developer/compiler.mjs b/assets/developer/compiler.mjs deleted file mode 100644 index c27d3838..00000000 --- a/assets/developer/compiler.mjs +++ /dev/null @@ -1,29 +0,0 @@ -import * as esbuild from 'esbuild-wasm'; -import {bundle} from './bundler.mjs'; - -const pending = new Map(); -let nextId = 0; -const readProject = path => new Promise((resolve, reject) => { - const id = ++nextId; - pending.set(id, {resolve, reject}); - self.postMessage({type: 'read', id, path}); -}); -const initialized = esbuild.initialize({wasmURL: new URL('./esbuild.wasm', import.meta.url).href, worker: false}); -self.onmessage = async ({data}) => { - if (data.type === 'read-result') { - const request = pending.get(data.id); - if (!request) return; - pending.delete(data.id); - if (data.error) request.reject(new Error(data.error)); - else request.resolve(data.bytes); - return; - } - if (data.type !== 'build') return; - try { - await initialized; - const files = await bundle(esbuild, {...data, readProject}); - self.postMessage({type: 'result', files}); - } catch (error) { - self.postMessage({type: 'error', error: error.message}); - } -}; diff --git a/assets/developer/packages.bundle.mjs b/assets/developer/packages.bundle.mjs deleted file mode 100644 index 84e43c3f..00000000 --- a/assets/developer/packages.bundle.mjs +++ /dev/null @@ -1 +0,0 @@ -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}; diff --git a/assets/developer/recipe.mjs b/assets/developer/recipe.mjs deleted file mode 100644 index 2c1c0b6a..00000000 --- a/assets/developer/recipe.mjs +++ /dev/null @@ -1,33 +0,0 @@ -// A starter's webfront.project.json: the entry file, exact dependency versions and the provider name. -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.-]+)?$/; - -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)) - 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)); -} - -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; -} diff --git a/assets/developer/runtime.mjs b/assets/developer/runtime.mjs deleted file mode 100644 index 5b83914c..00000000 --- a/assets/developer/runtime.mjs +++ /dev/null @@ -1,184 +0,0 @@ -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 {readProject, publish} from './io.mjs'; -import {createStarter} from './starter.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 async function readLock(bridge, optional = false) { - try { return validateLock(JSON.parse(decoder.decode(await readProject(bridge, lockPath)))); } - catch (error) { - if (optional && error.message.includes('Cannot read project file:')) - return {format: 1, roots: {}, packages: {}}; - throw error; - } -} - -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; -} - -async function readPackages(bridge, lock, signal) { - const packages = {}; - for (const [id, node] of Object.entries(lock.packages)) { - packages[id] = new Map(); - for (const path of node.files) { - signal?.throwIfAborted(); - packages[id].set(path, await readProject(bridge, `${packageRoot}/${node.key}/${path}`)); - } - } - return packages; -} - -// Serves the worker's project reads and settles the build with its result or error. -async function onWorkerMessage(bridge, worker, finish, data) { - if (data.type === 'read') worker.postMessage(await answerRead(bridge, data)); - else if (data.type === 'result') finish(null, data.files); - else if (data.type === 'error') finish(new Error(data.error)); -} - -function buildInWorker(bridge, message, signal) { - return new Promise((resolve, reject) => { - const worker = new Worker(new URL('./compiler.mjs', import.meta.url), {type: 'module'}); - const finish = (error, files) => { - worker.terminate(); - clearTimeout(timeout); - signal?.removeEventListener('abort', abort); - error ? reject(error) : resolve(files); - }; - const abort = () => finish(signal.reason ?? new Error('Interrupted')); - const timeout = setTimeout(() => finish(new Error('Browser build timed out')), 120000); - signal?.addEventListener('abort', abort, {once: true}); - worker.onerror = event => finish(new Error(event.message || 'Compiler worker failed')); - worker.onmessage = ({data}) => onWorkerMessage(bridge, worker, finish, data); - if (signal?.aborted) abort(); - else worker.postMessage(message); - }); -} - -async function answerRead(bridge, {id, path}) { - try { return {type: 'read-result', id, bytes: await readProject(bridge, path)}; } - catch (error) { return {type: 'read-result', id, error: error.message}; } -} - -const licenseFile = /(^|\/)(licen[cs]e|copying|notice)(\.|$)/i; - -function dependencyNotices(lock, packages) { - const notices = [`WebFront browser build; lock format ${lock.format}`]; - for (const [id, node] of Object.entries(lock.packages).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) { - notices.push(`${id} ${node.integrity}`); - for (const [path, bytes] of packages[id]) - if (licenseFile.test(path)) notices.push(`${id}/${path}\n${decoder.decode(bytes)}`); - } - return notices.join('\n\n'); -} - -export async function compile(bridge, entry, signal) { - const lock = await readLock(bridge); - const packages = await readPackages(bridge, lock, signal); - const files = await buildInWorker(bridge, {type: 'build', entry, lock, packages}, signal); - files.set('index.html', applicationPage(files)); - return {files, notices: dependencyNotices(lock, packages)}; -} - -async function create([starter, directory, ...extra], {bridge, config, signal}) { - if (!starter || extra.length) throw new Error('Usage: wf create [directory]'); - 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}`; -} - -async function preview([entry], {bridge, signal, preview: frame}) { - if (!entry) throw new Error('Usage: 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.'; -} - -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 '); - 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.`; -} - -async function list(_args, {bridge}) { - const lock = await readLock(bridge, true); - return Object.keys(lock.packages).sort().join('\n') || '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}; - -export async function execute(args, context) { - const [command = 'help', ...rest] = args; - if (!Object.hasOwn(commands, command)) throw new Error(`Unknown wf command: ${command}`); - return commands[command](rest, context); -} - -export async function mount({bridge, config, terminal: element, preview}) { - const link = document.createElement('link'); - link.rel = 'stylesheet'; - link.href = new URL('./xterm.css', import.meta.url).href; - await new Promise((resolve, reject) => { - link.onload = resolve; - link.onerror = () => reject(new Error('Cannot load terminal styles')); - document.head.append(link); - }); - const terminal = new Terminal({cursorBlink: true, theme: {background: '#141821'}}); - const fit = new FitAddon(); - terminal.loadAddon(fit); - terminal.open(element); - fit.fit(); - new ResizeObserver(() => fit.fit()).observe(element); - const write = text => terminal.write(text); - const editor = new LineEditor({write, prompt: 'wf> ', complete: async () => 'wf', run: async (line, signal) => { - const args = tokenize(line); - if (args.shift() !== 'wf') throw new Error('Use wf help to list commands'); - return execute(args, {bridge, config, preview, signal, write}); - }}); - terminal.onData(data => editor.handle(data)); - write('WebFront browser-powered developer environment\r\n'); - editor.showPrompt(); - terminal.focus(); - return {terminal, editor}; -} diff --git a/cmake/CEFSupport.cmake b/cmake/CEFSupport.cmake index cf930f54..242e6ed9 100644 --- a/cmake/CEFSupport.cmake +++ b/cmake/CEFSupport.cmake @@ -91,6 +91,87 @@ function(_cef_copy_directory_to_target target_name source_dir dest_dir comment_t ) endfunction() +# Linux: CEF targets that build into one directory share it, and every CEF target shares the CEF binary directory +# (ICU fix). Copying from each target's POST_BUILD step made parallel builds copy into one directory twice at the +# same time ("Error copying directory ... locales"). Each destination gets one copy target instead, named after the +# destination, on which its targets depend. Its rules produce the copied files from their sources, so a build with +# nothing to copy copies nothing; a directory is copied with a stamp file standing for its contents. +function(_cef_shared_copy target_name destination) + cmake_parse_arguments(PARSE_ARGV 2 copy "" "NAME;SOURCE_DIR;DIRECTORY" "FILES") + string(MD5 key "${destination}") + set(name webfront_cef_${copy_NAME}_${key}) + if(NOT TARGET ${name}) + set(outputs "") + foreach(file_name IN LISTS copy_FILES) + add_custom_command(OUTPUT "${destination}/${file_name}" + COMMAND ${CMAKE_COMMAND} -E make_directory "${destination}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${copy_SOURCE_DIR}/${file_name}" "${destination}/${file_name}" + DEPENDS "${copy_SOURCE_DIR}/${file_name}" + COMMENT "Copying CEF ${file_name} to ${destination}" + VERBATIM) + list(APPEND outputs "${destination}/${file_name}") + endforeach() + if(copy_DIRECTORY) + file(GLOB_RECURSE contents CONFIGURE_DEPENDS "${copy_SOURCE_DIR}/${copy_DIRECTORY}/*") + set(stamp "${destination}/${copy_DIRECTORY}/.webfront-copied") + add_custom_command(OUTPUT "${stamp}" + COMMAND ${CMAKE_COMMAND} -E copy_directory_if_different "${copy_SOURCE_DIR}/${copy_DIRECTORY}" "${destination}/${copy_DIRECTORY}" + COMMAND ${CMAKE_COMMAND} -E touch "${stamp}" + DEPENDS ${contents} + COMMENT "Copying CEF ${copy_DIRECTORY} to ${destination}" + VERBATIM) + list(APPEND outputs "${stamp}") + endif() + add_custom_target(${name} DEPENDS ${outputs}) + endif() + add_dependencies(${target_name} ${name}) +endfunction() + +# Fails at the end of the directory if the target's output directory changed after the copy was planned for it. +function(_cef_check_output_directory target_name planned) + _cef_output_directory(${target_name} actual) + if(NOT actual STREQUAL planned) + message(FATAL_ERROR "The CEF files of ${target_name} are copied to ${planned}, but it now builds into ${actual}: " + "set its RUNTIME_OUTPUT_DIRECTORY (or CMAKE_RUNTIME_OUTPUT_DIRECTORY) before calling the WebFront frontend setup") + endif() +endfunction() + +# The directory a target's executable is built into, as $ would name it: its RUNTIME_OUTPUT_DIRECTORY +# (initialized from CMAKE_RUNTIME_OUTPUT_DIRECTORY), else the binary directory of the directory that created it, plus +# the configuration with a multi-config generator. A path, not $: a copy target referencing a target +# that depends on it would form a cycle. Per-configuration output directories are refused rather than guessed. +function(_cef_output_directory target_name out_dir) + foreach(config IN LISTS CMAKE_CONFIGURATION_TYPES CMAKE_BUILD_TYPE) + string(TOUPPER "${config}" upper) + get_target_property(per_config ${target_name} RUNTIME_OUTPUT_DIRECTORY_${upper}) + if(per_config) + message(FATAL_ERROR "${target_name} sets RUNTIME_OUTPUT_DIRECTORY_${upper}, which the CEF file copy does not " + "support on Linux: set RUNTIME_OUTPUT_DIRECTORY instead") + endif() + endforeach() + get_target_property(binary_dir ${target_name} BINARY_DIR) + get_target_property(directory ${target_name} RUNTIME_OUTPUT_DIRECTORY) + if(NOT directory) + set(directory "${binary_dir}") + elseif(NOT IS_ABSOLUTE "${directory}" AND NOT directory MATCHES "^\\$<") + set(directory "${binary_dir}/${directory}") + endif() + get_property(multi GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) + # Multi-config generators add the configuration unless the directory is a generator expression. + if(multi AND NOT directory MATCHES "\\$<") + set(directory "${directory}/$") + endif() + set(${out_dir} "${directory}" PARENT_SCOPE) +endfunction() + +# The output directory of a target, checked again once its directory is processed. +function(_cef_planned_output_directory target_name out_dir) + _cef_output_directory(${target_name} directory) + cmake_language(EVAL CODE + "cmake_language(DEFER CALL _cef_check_output_directory [==[${target_name}]==] [==[${directory}]==])") + set(${out_dir} "${directory}" PARENT_SCOPE) +endfunction() + # Internal function to setup CEF paths and variables function(_cef_setup_paths) set(CEF_ROOT "${CMAKE_BINARY_DIR}/_deps/cef_binaries-src" PARENT_SCOPE) @@ -213,12 +294,8 @@ function(copy_cef_runtime_files target_name cef_build_dir) ) endif() elseif(UNIX) - _cef_copy_files_to_target(${target_name} - "${cef_build_dir}" - "${target_dir}" - "${CEF_LINUX_RUNTIME_FILES}" - "Copying CEF runtime files to output directory" - ) + _cef_planned_output_directory(${target_name} output) + _cef_shared_copy(${target_name} "${output}" NAME runtime SOURCE_DIR "${cef_build_dir}" FILES ${CEF_LINUX_RUNTIME_FILES}) endif() message(STATUS "CEF runtime files will be copied for ${target_name}") @@ -269,31 +346,15 @@ function(copy_cef_resource_files target_name) # This dual-copy approach fixes the ICU data loading issue where CEF # searches for icudtl.dat in its installation directory - # Copy to application directory (standard deployment) - _cef_copy_files_to_target(${target_name} - "${CEF_RESOURCE_SOURCE_DIR}" - "${target_dir}" - "${CEF_RESOURCE_FILES}" - "Copying CEF resource files to application directory" - ) - _cef_copy_directory_to_target(${target_name} - "${CEF_RESOURCE_SOURCE_DIR}/locales" - "${target_dir}/locales" - "Copying CEF locales to application directory" - ) - - # Copy to CEF binary directory (ICU loading fix) - _cef_copy_files_to_target(${target_name} - "${CEF_RESOURCE_SOURCE_DIR}" - "${CEF_BINARY_RELEASE_DIR}" - "${CEF_RESOURCE_FILES}" - "Copying CEF resource files to binary directory (ICU fix)" - ) - _cef_copy_directory_to_target(${target_name} - "${CEF_RESOURCE_SOURCE_DIR}/locales" - "${CEF_BINARY_RELEASE_DIR}/locales" - "Copying CEF locales to binary directory (ICU fix)" - ) + # Copy to application directory (standard deployment), once per output directory + _cef_planned_output_directory(${target_name} output) + _cef_shared_copy(${target_name} "${output}" NAME resources SOURCE_DIR "${CEF_RESOURCE_SOURCE_DIR}" + FILES ${CEF_RESOURCE_FILES} DIRECTORY locales) + + # Copy to CEF binary directory (ICU loading fix), once for all targets. As before, this is the Release + # directory in every configuration. + _cef_shared_copy(${target_name} "${CEF_BINARY_RELEASE_DIR}" NAME resources SOURCE_DIR "${CEF_RESOURCE_SOURCE_DIR}" + FILES ${CEF_RESOURCE_FILES} DIRECTORY locales) endif() message(STATUS "CEF resource files will be copied for ${target_name}") diff --git a/cmake/CompilerWarnings.cmake b/cmake/CompilerWarnings.cmake index 6a201896..8fb735a6 100644 --- a/cmake/CompilerWarnings.cmake +++ b/cmake/CompilerWarnings.cmake @@ -31,7 +31,7 @@ function(set_project_warnings project_name) /wd4714 # '__forceinline' function not inlined: stdexec's coroutine helpers, which are not ours to change /analyze # Enable Code Analysis /analyze:external- # Disable Code Analysis for external headers - /analyze:stacksize 65536 # Raise C6262 stack warning threshold to 64KB (policy buffers can reach 32KB) + /analyze:stacksize65536 # Raise C6262 stack warning threshold to 64KB (policy buffers can reach 32KB); one argument, as sccache reads a separate "65536" as a second source file and refuses to cache the compilation /permissive- # standards conformance mode for MSVC compiler. ) @@ -70,6 +70,12 @@ function(set_project_warnings project_name) -Wlogical-op # warn about logical operations being used where bitwise were probably wanted ) + # GCC 16 at -O2/-O3 reports a stringop-overflow inside stdexec's task_scheduler (std::optional of a type-erased + # scheduler) for every coroutine awaiting continues_on. The code is not ours: keep the warning, never fail on it. + if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + list(APPEND GCC_WARNINGS -Wno-error=stringop-overflow) + endif() + # Vérifier si -Wdangling-reference est supporté (GCC 13+ ou certaines versions de GCC 12) include(CheckCXXCompilerFlag) check_cxx_compiler_flag("-Wdangling-reference" COMPILER_SUPPORTS_DANGLING_REF) diff --git a/cmake/EmbedTextAsset.cmake b/cmake/EmbedTextAsset.cmake deleted file mode 100644 index aafecece..00000000 --- a/cmake/EmbedTextAsset.cmake +++ /dev/null @@ -1,98 +0,0 @@ -if(NOT DEFINED INPUT) - message(FATAL_ERROR "INPUT must name the readable text asset source") -endif() - -if(NOT DEFINED OUTPUT AND NOT DEFINED CHECK) - message(FATAL_ERROR "Set OUTPUT to regenerate the header or CHECK to verify it") -endif() - -if(NOT DEFINED STRUCT) - message(FATAL_ERROR "STRUCT must name the generated struct, e.g. WebFrontJsData") -endif() - -# Normal assets retain their identity representation. Third-party payloads use the pinned, -# vendored pure-JavaScript compressor, independent of the host's gzip/zlib implementation. -set(encoding "") -if(GZIP) - find_program(NODE_EXECUTABLE NAMES node nodejs REQUIRED) - set(compressed "${CMAKE_CURRENT_BINARY_DIR}/${STRUCT}.gz") - execute_process(COMMAND "${NODE_EXECUTABLE}" "${CMAKE_CURRENT_LIST_DIR}/../tools/assets/gzip.mjs" - "${INPUT}" "${compressed}" RESULT_VARIABLE result) - if(NOT result EQUAL 0) - message(FATAL_ERROR "gzip generation failed for ${INPUT}") - endif() - file(READ "${compressed}" gzip_hex HEX) - file(REMOVE "${compressed}") - set(encoding "gzip") -else() - file(READ "${INPUT}" gzip_hex HEX) -endif() - -string(LENGTH "${gzip_hex}" hex_length) -math(EXPR data_size "${hex_length} / 2") -math(EXPR word_count "(${data_size} + 7) / 8") - -set(words "") -set(word_index 0) -while(word_index LESS word_count) - math(EXPR offset "${word_index} * 16") - math(EXPR remaining "${hex_length} - ${offset}") - if(remaining GREATER 16) - set(chunk_length 16) - else() - set(chunk_length "${remaining}") - endif() - string(SUBSTRING "${gzip_hex}" "${offset}" "${chunk_length}" word) - string(LENGTH "${word}" word_length) - while(word_length LESS 16) - string(APPEND word "0") - string(LENGTH "${word}" word_length) - endwhile() - math(EXPR line_position "${word_index} % 5") - if(line_position EQUAL 0) - if(word_index GREATER 0) - string(APPEND words ",") - endif() - string(APPEND words "\n ") - elseif(word_index GREATER 0) - string(APPEND words ", ") - endif() - string(APPEND words "0x${word}") - math(EXPR word_index "${word_index} + 1") -endwhile() - -if(encoding) - set(encoding_initializer "{\"${encoding}\"}") -else() - set(encoding_initializer "{}") -endif() - -set(contents "#pragma once\n\n#include \n#include \n#include \n#include \n\nnamespace webfront::fs::generated {\n\nstruct ${STRUCT} {\n static constexpr std::string_view encoding${encoding_initializer};\n static constexpr std::size_t dataSize{${data_size}};\n static constexpr std::array data{${words}\n };\n};\n\n} // namespace webfront::fs::generated\n") - -# A Windows checkout converting either file to CRLF would make it look stale, so both must keep -# LF through .gitattributes. Checked only in a git work tree, on every platform. -if(DEFINED CHECK AND GIT_EXECUTABLE AND NOT INPUT MATCHES "\\.png$") - get_filename_component(source_dir "${INPUT}" DIRECTORY) - execute_process( - COMMAND "${GIT_EXECUTABLE}" check-attr eol -- "${INPUT}" "${CHECK}" - WORKING_DIRECTORY "${source_dir}" - OUTPUT_VARIABLE attributes - RESULT_VARIABLE not_in_work_tree - ERROR_QUIET) - if(NOT not_in_work_tree) - string(REGEX MATCHALL "eol: lf\n" lf_lines "${attributes}") - list(LENGTH lf_lines lf_count) - if(NOT lf_count EQUAL 2) - message(FATAL_ERROR "${INPUT} and ${CHECK} must have 'text eol=lf' in .gitattributes:\n${attributes}") - endif() - endif() -endif() - -if(DEFINED CHECK) - file(READ "${CHECK}" expected) - if(NOT contents STREQUAL expected) - message(FATAL_ERROR "${CHECK} is stale; run the webfront-embedded-assets target") - endif() -else() - file(WRITE "${OUTPUT}" "${contents}") -endif() diff --git a/cmake/Frontends.cmake b/cmake/Frontends.cmake index 1c6bb516..8e77c5d0 100644 --- a/cmake/Frontends.cmake +++ b/cmake/Frontends.cmake @@ -11,7 +11,7 @@ function(webfront_register_frontend name) if(NOT "${name}" MATCHES "^[A-Za-z_][A-Za-z0-9_]*$") message(FATAL_ERROR "Frontend name '${name}' must be a C++ identifier") endif() - cmake_parse_arguments(PARSE_ARGV 1 ARG "XVFB_LINUX;ALWAYS_AVAILABLE" "OPTION;POLICY;DESCRIPTION;SUPPORT;SETUP;TEST_SETUP;TEST_NAME;TEST_TIMEOUT" "PLATFORMS;TEST_PLATFORMS") + cmake_parse_arguments(PARSE_ARGV 1 ARG "XVFB_LINUX;ALWAYS_AVAILABLE;NATIVE" "OPTION;POLICY;DESCRIPTION;SUPPORT;SETUP;TEST_SETUP;TEST_NAME;TEST_TIMEOUT" "PLATFORMS;TEST_PLATFORMS") if(name IN_LIST WEBFRONT_FRONTEND_REGISTRY) message(FATAL_ERROR "Frontend '${name}' is already registered") endif() @@ -70,29 +70,32 @@ function(webfront_register_frontend name) if(ARG_XVFB_LINUX) message(FATAL_ERROR "Frontend '${name}' cannot use XVFB_LINUX without OPTION") endif() + if(ARG_NATIVE) + message(FATAL_ERROR "Frontend '${name}' cannot use NATIVE without OPTION") + endif() endif() list(APPEND WEBFRONT_FRONTEND_REGISTRY "${name}") set(WEBFRONT_FRONTEND_REGISTRY "${WEBFRONT_FRONTEND_REGISTRY}" PARENT_SCOPE) - foreach(field OPTION POLICY DESCRIPTION SUPPORT SUPPORT_FILE SETUP TEST_SETUP TEST_NAME TEST_TIMEOUT PLATFORMS TEST_PLATFORMS XVFB_LINUX) + foreach(field OPTION POLICY DESCRIPTION SUPPORT SUPPORT_FILE SETUP TEST_SETUP TEST_NAME TEST_TIMEOUT PLATFORMS TEST_PLATFORMS XVFB_LINUX NATIVE) set(WEBFRONT_FRONTEND_${name}_${field} "${ARG_${field}}" PARENT_SCOPE) endforeach() endfunction() webfront_register_frontend(DefaultBrowser ALWAYS_AVAILABLE) webfront_register_frontend(WebView2 - OPTION WEBFRONT_EMBED_WEBVIEW2 POLICY strict + NATIVE OPTION WEBFRONT_EMBED_WEBVIEW2 POLICY strict DESCRIPTION "Download the pinned WebView2 SDK and link its static loader (Windows only)" PLATFORMS Windows SUPPORT WebView2Support TEST_PLATFORMS Windows TEST_NAME WebFrontWebView2Integration TEST_TIMEOUT 90 TEST_SETUP webfront_add_webview2_tests) webfront_register_frontend(WKWebView - OPTION WEBFRONT_EMBED_WKWEBVIEW POLICY strict + NATIVE OPTION WEBFRONT_EMBED_WKWEBVIEW POLICY strict DESCRIPTION "Link the system Cocoa and WebKit frameworks for WKWebViewFrontend (macOS 13.3+ only)" PLATFORMS Darwin SUPPORT WKWebViewSupport TEST_PLATFORMS Darwin TEST_NAME WebFrontWKWebViewIntegration TEST_TIMEOUT 90 TEST_SETUP webfront_add_wkwebview_tests) webfront_register_frontend(WebKitGTK - OPTION WEBFRONT_EMBED_WEBKITGTK POLICY strict + NATIVE OPTION WEBFRONT_EMBED_WEBKITGTK POLICY strict DESCRIPTION "Enable the system WebKitGTK 6.0 embedded frontend (Linux only)" PLATFORMS Linux SUPPORT WebKitGTKSupport TEST_PLATFORMS Linux TEST_NAME WebFrontWebKitGTKIntegration TEST_TIMEOUT 90 XVFB_LINUX @@ -127,6 +130,73 @@ function(webfront_declare_frontend_options) endforeach() endfunction() + +# Probes whether the native engine can be built here. Sets to ON or OFF and to a +# diagnostic for the OFF case. Only the registry's native engines are probed, never CEF. Kept +# separate so that configure-only tests can supply a deterministic answer. +function(webfront_probe_native_frontend name out reason) + set(available OFF) + set(why "") + if(name STREQUAL "WebKitGTK") + find_package(PkgConfig QUIET) + if(PkgConfig_FOUND) + pkg_check_modules(WEBFRONT_AUTODETECT_WEBKITGTK QUIET webkitgtk-6.0) + endif() + if(WEBFRONT_AUTODETECT_WEBKITGTK_FOUND) + set(available ON) + else() + set(why "pkg-config webkitgtk-6.0 was not found; install libwebkitgtk-6.0-dev (Ubuntu/Debian) or webkitgtk6.0-devel (Fedora), see docs/WEBKITGTK.md") + endif() + elseif(name STREQUAL "WKWebView") + if(NOT CMAKE_CXX_COMPILER_ID MATCHES "Clang") + set(why "WKWebViewFrontend requires Clang with Apple Blocks support") + elseif(CMAKE_OSX_DEPLOYMENT_TARGET AND CMAKE_OSX_DEPLOYMENT_TARGET VERSION_LESS "13.3") + set(why "CMAKE_OSX_DEPLOYMENT_TARGET ${CMAKE_OSX_DEPLOYMENT_TARGET} is older than 13.3") + elseif(NOT CMAKE_OSX_DEPLOYMENT_TARGET AND CMAKE_HOST_SYSTEM_VERSION VERSION_LESS "22.4") + set(why "macOS 13.3 or later is required (Darwin ${CMAKE_HOST_SYSTEM_VERSION})") + else() + set(available ON) + endif() + elseif(name STREQUAL "WebView2") + if(MSVC) + set(available ON) + else() + set(why "WebView2Frontend requires an MSVC-compatible compiler (MSVC or clang-cl)") + endif() + else() + set(why "no probe is defined for ${name}") + endif() + set(${out} "${available}" PARENT_SCOPE) + set(${reason} "${why}" PARENT_SCOPE) +endfunction() + +# Enables, for this platform's native engine, an option the user has not set. Automatic values stay +# in normal variables: option() honors them (CMP0077), without creating a cache entry. A later +# configure probes again, while an explicit normal or cached value always wins, even when unchanged. +# A missing engine only produces a status message; the application reports it at run time. +function(webfront_autodetect_native_frontends) + foreach(name IN LISTS WEBFRONT_FRONTEND_REGISTRY) + set(option "${WEBFRONT_FRONTEND_${name}_OPTION}") + if(option STREQUAL "" OR NOT WEBFRONT_FRONTEND_${name}_NATIVE) + continue() + endif() + webfront_frontend_supports_platform("${name}" supported) + if(NOT supported) + continue() + endif() + if(DEFINED ${option}) + continue() + endif() + webfront_probe_native_frontend("${name}" available reason) + set(${option} "${available}" PARENT_SCOPE) + if(available) + message(STATUS "Native window: ${name} detected, ${option}=ON") + else() + message(STATUS "Native window: ${name} unavailable (${reason}), so applications using NativeApp will report it when started. Set -D${option}=ON once it is installed") + endif() + endforeach() +endfunction() + # Hook functions are supplied by the support module. Validate them immediately after loading it, # rather than deferring an unknown-command error until target or test setup. function(webfront_validate_frontend_hooks name) @@ -177,7 +247,10 @@ function(webfront_set_browser_test_properties name assets_directory timeout) endfunction() # Shared Jasmine and lifecycle registration; engine-specific cases stay in the support module. +# ARGUMENTS are passed to the Jasmine target (webtest runs `wf test` on a prepared project); SKIP_JASMINE registers the +# lifecycle and engine cases only, when the target cannot run on this configuration. function(webfront_add_browser_tests target frontend assets_directory lifecycle_target) + cmake_parse_arguments(ARG "SKIP_JASMINE" "" "ARGUMENTS" ${ARGN}) if(NOT frontend IN_LIST WEBFRONT_FRONTEND_REGISTRY) message(FATAL_ERROR "Unknown browser-test frontend '${frontend}'") endif() @@ -218,11 +291,13 @@ function(webfront_add_browser_tests target frontend assets_directory lifecycle_t webfront_set_browser_test_properties("${lifecycle_name}" "${assets_directory}" "${WEBFRONT_FRONTEND_${frontend}_TEST_TIMEOUT}") endforeach() - set(name "${WEBFRONT_FRONTEND_${frontend}_TEST_NAME}") - add_test(NAME ${name} COMMAND ${command}) - list(APPEND shared_tests "${name}") - webfront_set_browser_test_properties("${name}" "${assets_directory}" - "${WEBFRONT_FRONTEND_${frontend}_TEST_TIMEOUT}") + if(NOT ARG_SKIP_JASMINE) + set(name "${WEBFRONT_FRONTEND_${frontend}_TEST_NAME}") + add_test(NAME ${name} COMMAND ${command} ${ARG_ARGUMENTS}) + list(APPEND shared_tests "${name}") + webfront_set_browser_test_properties("${name}" "${assets_directory}" + "${WEBFRONT_FRONTEND_${frontend}_TEST_TIMEOUT}") + endif() endif() # Per-engine tests may be independent of a display and must not be skipped with Jasmine. set(setup "${WEBFRONT_FRONTEND_${frontend}_TEST_SETUP}") @@ -318,3 +393,16 @@ function(webfront_select_frontend var default description) endforeach() set(${var}_TYPE "webfront::frontend::${selected}Frontend" PARENT_SCOPE) endfunction() + +# Sets to the option of the native engine registered for this platform, or to "" when there is none. +function(webfront_native_frontend_option out) + set(result "") + foreach(name IN LISTS WEBFRONT_FRONTEND_REGISTRY) + webfront_frontend_supports_platform("${name}" supported) + if(WEBFRONT_FRONTEND_${name}_NATIVE AND supported) + set(result "${WEBFRONT_FRONTEND_${name}_OPTION}") + break() + endif() + endforeach() + set(${out} "${result}" PARENT_SCOPE) +endfunction() diff --git a/cmake/MddlogIntegration.cmake b/cmake/MddlogIntegration.cmake index 84dca7b3..a4bfb708 100644 --- a/cmake/MddlogIntegration.cmake +++ b/cmake/MddlogIntegration.cmake @@ -101,7 +101,7 @@ function(webfront_add_mddlog) find_package(mddlog CONFIG REQUIRED) endif() - add_library(WebFront_mddlog STATIC "${PROJECT_SOURCE_DIR}/logging/Logger.cpp") + add_library(WebFront_mddlog STATIC "${PROJECT_SOURCE_DIR}/cmake/mddlog/Logger.cpp") add_library(WebFront::mddlog ALIAS WebFront_mddlog) target_compile_features(WebFront_mddlog PUBLIC cxx_std_23) set_target_properties(WebFront_mddlog PROPERTIES CXX_SCAN_FOR_MODULES ON) diff --git a/cmake/StaticAnalyzers.cmake b/cmake/StaticAnalyzers.cmake index d1e5b3bf..2af8affc 100644 --- a/cmake/StaticAnalyzers.cmake +++ b/cmake/StaticAnalyzers.cmake @@ -22,7 +22,7 @@ endif() if(ENABLE_CLANG_TIDY) find_program(CLANGTIDY clang-tidy) if(CLANGTIDY) - set(CMAKE_CXX_CLANG_TIDY ${CLANGTIDY} -extra-arg=-std=c++23 -header-filter=.*) + set(CMAKE_CXX_CLANG_TIDY ${CLANGTIDY} --config-file=${CMAKE_CURRENT_LIST_DIR}/clang-tidy.yaml -extra-arg=-std=c++23 -header-filter=.*) if(WARNINGS_AS_ERRORS) list(APPEND CMAKE_CXX_CLANG_TIDY -warnings-as-errors=*) endif() diff --git a/cmake/UpdateXterm.cmake b/cmake/UpdateXterm.cmake deleted file mode 100644 index 5867c7dc..00000000 --- a/cmake/UpdateXterm.cmake +++ /dev/null @@ -1,39 +0,0 @@ -# Maintenance script, not part of the build: refreshes the vendored xterm.js files in -# third_party/xterm from the npm registry (network access required), then regenerate the embedded -# headers with the webfront-embedded-assets target and review the diff. -# -# cmake -DXTERM_VERSION=6.0.0 -DFIT_VERSION=0.11.0 -P cmake/UpdateXterm.cmake - -cmake_minimum_required(VERSION 3.31) - -if(NOT DEFINED XTERM_VERSION OR NOT DEFINED FIT_VERSION) - message(FATAL_ERROR "Set XTERM_VERSION and FIT_VERSION, e.g. -DXTERM_VERSION=6.0.0 -DFIT_VERSION=0.11.0") -endif() - -get_filename_component(root "${CMAKE_CURRENT_LIST_DIR}/.." ABSOLUTE) -set(destination "${root}/third_party/xterm") -string(RANDOM LENGTH 8 suffix) -set(work "${CMAKE_CURRENT_BINARY_DIR}/webfront-xterm-update-${suffix}") - -function(_fetch_package url archive) - file(DOWNLOAD "${url}" "${archive}" STATUS status TLS_VERIFY ON) - list(GET status 0 code) - if(NOT code EQUAL 0) - message(FATAL_ERROR "Download of ${url} failed: ${status}") - endif() -endfunction() - -_fetch_package("https://registry.npmjs.org/@xterm/xterm/-/xterm-${XTERM_VERSION}.tgz" "${work}/xterm.tgz") -_fetch_package("https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-${FIT_VERSION}.tgz" "${work}/fit.tgz") -file(ARCHIVE_EXTRACT INPUT "${work}/xterm.tgz" DESTINATION "${work}/xterm") -file(ARCHIVE_EXTRACT INPUT "${work}/fit.tgz" DESTINATION "${work}/fit") - -file(COPY_FILE "${work}/xterm/package/lib/xterm.mjs" "${destination}/xterm.mjs") -file(COPY_FILE "${work}/xterm/package/css/xterm.css" "${destination}/xterm.css") -file(COPY_FILE "${work}/xterm/package/LICENSE" "${destination}/LICENSE") -file(COPY_FILE "${work}/fit/package/lib/addon-fit.mjs" "${destination}/addon-fit.mjs") -file(COPY_FILE "${work}/fit/package/LICENSE" "${destination}/addon-fit-LICENSE") -file(WRITE "${destination}/VERSION" "@xterm/xterm ${XTERM_VERSION}\n@xterm/addon-fit ${FIT_VERSION}\n") -file(REMOVE_RECURSE "${work}") - -message(STATUS "Updated ${destination}; now run: cmake --build --target webfront-embedded-assets") diff --git a/cmake/WKWebViewSupport.cmake b/cmake/WKWebViewSupport.cmake index 9f847074..a95d70ad 100644 --- a/cmake/WKWebViewSupport.cmake +++ b/cmake/WKWebViewSupport.cmake @@ -14,7 +14,7 @@ target_compile_options(WebFront INTERFACE "$<$:-fblocks>") target_link_libraries(WebFront INTERFACE "${WEBFRONT_COCOA_FRAMEWORK}" "${WEBFRONT_WEBKIT_FRAMEWORK}") function(webfront_add_wkwebview_tests) - get_filename_component(webtest_source_dir "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../webtest" ABSOLUTE) + get_filename_component(webtest_source_dir "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../test/web" ABSOLUTE) add_executable(wkwebview_lifecycle "${webtest_source_dir}/WKWebViewLifecycle.cpp" "${webtest_source_dir}/WKWebViewHeaderConsumer.cpp") target_link_libraries(wkwebview_lifecycle PRIVATE WebFront WebFront_warnings WebFront_options) @@ -22,6 +22,16 @@ function(webfront_add_wkwebview_tests) add_test(NAME WKWebViewLifecycle-${mode} COMMAND wkwebview_lifecycle ${mode}) webfront_set_browser_test_properties("WKWebViewLifecycle-${mode}" "${webtest_source_dir}" 90) endforeach() + # Measurement is manual; the short contract checks remain ordinary browser tests. + add_executable(wkwebview_transport_benchmark EXCLUDE_FROM_ALL "${webtest_source_dir}/WKWebViewTransportBenchmark.cpp") + add_executable(wkwebview_transport_contracts "${webtest_source_dir}/WKWebViewTransportBenchmark.cpp") + target_compile_definitions(wkwebview_transport_contracts PRIVATE WEBFRONT_TRANSPORT_CONTRACTS_ONLY) + foreach(target wkwebview_transport_benchmark wkwebview_transport_contracts) + target_link_libraries(${target} PRIVATE WebFront_test_hardening WebFront WebFront_warnings WebFront_options) + endforeach() + add_dependencies(webtest wkwebview_transport_contracts) + add_test(NAME WKWebViewTransportContracts COMMAND wkwebview_transport_contracts) + webfront_set_browser_test_properties(WKWebViewTransportContracts "${webtest_source_dir}" 60) add_library(wkwebview_class_module SHARED "${webtest_source_dir}/WKWebViewClassModule.cpp") add_executable(wkwebview_class_images "${webtest_source_dir}/WKWebViewClassImages.cpp") @@ -38,11 +48,13 @@ function(webfront_add_wkwebview_tests) webfront_set_browser_test_properties("WKWebViewClassImages-${order}" "${webtest_source_dir}" 90) endforeach() # Stable agent bundles avoid one anonymous executable tile per test process in the Dock. - foreach(target webtest frontend_lifecycle wkwebview_lifecycle wkwebview_class_images) + # The path is normalized: a second spelling of the template would be a duplicate Ninja output. + get_filename_component(_wk_plist "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../test/cmake/WKWebViewTestInfo.plist.in" ABSOLUTE) + foreach(target webtest frontend_lifecycle wkwebview_lifecycle wkwebview_class_images wkwebview_transport_benchmark wkwebview_transport_contracts) string(REPLACE "_" "-" identifier "${target}") set_target_properties(${target} PROPERTIES MACOSX_BUNDLE TRUE MACOSX_BUNDLE_GUI_IDENTIFIER "org.webfront.tests.${identifier}" - MACOSX_BUNDLE_INFO_PLIST "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/WKWebViewTestInfo.plist.in") + MACOSX_BUNDLE_INFO_PLIST "${_wk_plist}") endforeach() endfunction() diff --git a/cmake/WebFrontAssets.cmake b/cmake/WebFrontAssets.cmake deleted file mode 100644 index 53623f0b..00000000 --- a/cmake/WebFrontAssets.cmake +++ /dev/null @@ -1,109 +0,0 @@ -# Maintenance of the embedded browser bridge and fallback-page assets. Normal builds consume the -# checked-in generated headers; the webfront-embedded-assets target regenerates them from their -# readable sources, while CTest verifies (per asset, for clear failure attribution) that each is current. - -set(_WEBFRONT_ASSETS_DIR "${CMAKE_CURRENT_LIST_DIR}") - -function(_webfront_add_embedded_text_asset source header struct test_name) - add_custom_command(TARGET webfront-embedded-assets POST_BUILD - COMMAND ${CMAKE_COMMAND} - -DINPUT=${source} - -DOUTPUT=${header} - -DSTRUCT=${struct} - -DGZIP=${ARGN} - -P ${_WEBFRONT_ASSETS_DIR}/EmbedTextAsset.cmake - COMMENT "Regenerating ${header}" - VERBATIM - ) - if(ENABLE_TESTING) - add_test(NAME ${test_name} - COMMAND ${CMAKE_COMMAND} - -DINPUT=${source} - -DCHECK=${header} - -DSTRUCT=${struct} - -DGZIP=${ARGN} - -DGIT_EXECUTABLE=${GIT_EXECUTABLE} - -P ${_WEBFRONT_ASSETS_DIR}/EmbedTextAsset.cmake - ) - endif() -endfunction() - -function(webfront_add_embedded_assets) - find_package(Git QUIET) - set(root "${_WEBFRONT_ASSETS_DIR}/..") - cmake_path(NORMAL_PATH root) - add_custom_target(webfront-embedded-assets COMMENT "Regenerating embedded browser bridge and fallback-page assets") - _webfront_add_embedded_text_asset( - "${root}/assets/WebFront.js" "${root}/include/system/WebFrontJsData.hpp" - WebFrontJsData WebFrontJsAssetsFresh) - _webfront_add_embedded_text_asset( - "${root}/assets/fallback/index.html" "${root}/include/system/FallbackIndexHtmlData.hpp" - FallbackIndexHtmlData FallbackIndexHtmlAssetFresh) - _webfront_add_embedded_text_asset( - "${root}/assets/fallback/webfront-fallback.mjs" "${root}/include/system/FallbackModuleData.hpp" - FallbackModuleData FallbackModuleAssetFresh) - - _webfront_add_embedded_text_asset( - "${root}/assets/developer/index.html" "${root}/include/system/DeveloperIndexHtmlData.hpp" - DeveloperIndexHtmlData DeveloperIndexHtmlAssetFresh) - _webfront_add_embedded_text_asset( - "${root}/assets/developer/bootstrap.bundle.mjs" "${root}/include/system/DeveloperBootstrapData.hpp" - DeveloperBootstrapData DeveloperBootstrapAssetFresh) - - # Terminal component (include/system/TerminalFS.hpp). xterm.js files are vendored verbatim in - # third_party/xterm (see its VERSION file); refresh them with cmake/UpdateXterm.cmake. - _webfront_add_embedded_text_asset( - "${root}/assets/components/terminal/index.html" "${root}/include/system/TerminalIndexHtmlData.hpp" - TerminalIndexHtmlData TerminalIndexHtmlAssetFresh) - _webfront_add_embedded_text_asset( - "${root}/assets/components/terminal/terminal.mjs" "${root}/include/system/TerminalModuleData.hpp" - TerminalModuleData TerminalModuleAssetFresh) - # Browser side of the wf tool manager (include/system/ToolManagerFS.hpp). - _webfront_add_embedded_text_asset( - "${root}/assets/components/tools/wf.mjs" "${root}/include/system/ToolManagerModuleData.hpp" - ToolManagerModuleData ToolManagerModuleAssetFresh) - _webfront_add_embedded_text_asset( - "${root}/third_party/xterm/xterm.mjs" "${root}/include/system/XtermModuleData.hpp" - XtermModuleData XtermModuleAssetFresh ON) - _webfront_add_embedded_text_asset( - "${root}/third_party/xterm/xterm.css" "${root}/include/system/XtermCssData.hpp" - XtermCssData XtermCssAssetFresh ON) - _webfront_add_embedded_text_asset( - "${root}/third_party/xterm/addon-fit.mjs" "${root}/include/system/XtermFitAddonData.hpp" - XtermFitAddonData XtermFitAddonAssetFresh ON) - _webfront_add_embedded_text_asset( - "${root}/third_party/react/runtime.mjs" "${root}/include/system/ReactRuntimeData.hpp" - ReactRuntimeData ReactRuntimeAssetFresh ON) - _webfront_add_embedded_text_asset( - "${root}/third_party/babel/babel.min.js" "${root}/include/system/BabelData.hpp" - BabelData BabelAssetFresh ON) - foreach(asset IN ITEMS jasmine.js jasmine-html.js jasmine.css boot.js jasmine_favicon.png) - if(asset STREQUAL "jasmine.js") - set(struct JasmineJsData) - elseif(asset STREQUAL "jasmine-html.js") - set(struct JasmineHtmlData) - elseif(asset STREQUAL "jasmine.css") - set(struct JasmineCssData) - elseif(asset STREQUAL "boot.js") - set(struct JasmineBootData) - else() - set(struct JasmineFaviconData) - endif() - if(asset STREQUAL "jasmine_favicon.png") - set(compress OFF) - else() - set(compress ON) - endif() - _webfront_add_embedded_text_asset( - "${root}/third_party/jasmine/${asset}" "${root}/include/system/${struct}.hpp" - ${struct} ${struct}AssetFresh ${compress}) - endforeach() - if(ENABLE_TESTING) - find_program(WEBFRONT_NODE_EXECUTABLE NAMES node nodejs REQUIRED) - add_test(NAME DeveloperJavaScript COMMAND "${WEBFRONT_NODE_EXECUTABLE}" - --test "${root}/tools/developer/check.mjs" "${root}/tools/developer/distribution-check.mjs") - set_tests_properties(DeveloperJavaScript PROPERTIES TIMEOUT 30) - add_test(NAME EmbeddedGzipContents COMMAND "${WEBFRONT_NODE_EXECUTABLE}" - "${root}/tools/assets/check.mjs") - endif() -endfunction() diff --git a/cmake/WebFrontBootstrap.cmake b/cmake/WebFrontBootstrap.cmake new file mode 100644 index 00000000..4bc15891 --- /dev/null +++ b/cmake/WebFrontBootstrap.cmake @@ -0,0 +1,150 @@ +# Bootstrap environment used to test WebFront: the pinned archive wf runs from, provisioned at configure time. +# +# It is distinct from include/webfront/system/DeveloperReleaseData.hpp (the environment applications start from) and is +# updated by an explicit pull request, once a published environment can build and test itself without interaction. +# 0.6.0 is the first published environment that runs a wf command without interaction (runNonInteractive); 0.6.1 also returns the +# output of a script, and 0.6.2 reads the archives of @types packages and a manifest directory chosen by the application. +# The driver tests also +# run the environment built from the current sources (the "environment under test"), which may be ahead of this pin. +set(WEBFRONT_BOOTSTRAP_VERSION "0.6.2") +set(WEBFRONT_BOOTSTRAP_URL "https://ambroise-leclerc.github.io/WebFront/developer/0.6.2/environment.tgz") +set(WEBFRONT_BOOTSTRAP_INTEGRITY "sha512-SYnS6iRdK0VZM1PLECwK9Iwm/I6wxVlpM+1a0IXDs/lZN0y7lSB6hnv4+gSsX+U+aZ600WDXniF4w0LtHJFH/A==") + +# A directory holding environment.tgz (the pinned archive) replaces the download on a machine without network access. +set(WEBFRONT_BOOTSTRAP_DIR "" CACHE PATH "Directory with the pinned bootstrap environment.tgz, instead of downloading it") + +# Converts a base64 value to lowercase hexadecimal bytes. +function(webfront_base64_to_hex value output) + set(alphabet "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") + string(LENGTH "${value}" length) + math(EXPR remainder "${length} % 4") + if(NOT remainder EQUAL 0) + message(FATAL_ERROR "Invalid base64 value (length ${length})") + endif() + set(hex "") + math(EXPR last "${length} - 1") + foreach(start RANGE 0 ${last} 4) + set(group 0) + set(padding 0) + foreach(offset RANGE 0 3) + math(EXPR position "${start} + ${offset}") + string(SUBSTRING "${value}" ${position} 1 character) + if(character STREQUAL "=") + math(EXPR padding "${padding} + 1") + set(sextet 0) + else() + string(FIND "${alphabet}" "${character}" sextet) + if(sextet EQUAL -1) + message(FATAL_ERROR "Invalid base64 character '${character}'") + endif() + endif() + math(EXPR group "(${group} << 6) | ${sextet}") + endforeach() + math(EXPR bytes "3 - ${padding}") + foreach(index RANGE 0 ${bytes}) + if(index EQUAL bytes) + break() + endif() + math(EXPR shift "16 - 8 * ${index}") + math(EXPR byte "(${group} >> ${shift}) & 255" OUTPUT_FORMAT HEXADECIMAL) + string(SUBSTRING "${byte}" 2 -1 digits) + string(LENGTH "${digits}" digitCount) + if(digitCount EQUAL 1) + set(digits "0${digits}") + endif() + string(APPEND hex "${digits}") + endforeach() + endforeach() + set(${output} "${hex}" PARENT_SCOPE) +endfunction() + +# The hexadecimal SHA-512 of an SRI value ("sha512-"). +function(webfront_sri_to_sha512 integrity output) + if(NOT integrity MATCHES "^sha512-([A-Za-z0-9+/]+=*)$") + message(FATAL_ERROR "Bootstrap integrity must be a sha512- SRI value: '${integrity}'") + endif() + webfront_base64_to_hex("${CMAKE_MATCH_1}" hex) + string(LENGTH "${hex}" length) + if(NOT length EQUAL 128) + message(FATAL_ERROR "Bootstrap integrity is not a SHA-512 digest") + endif() + set(${output} "${hex}" PARENT_SCOPE) +endfunction() + +# Makes the verified path of an environment archive: / when LOCAL_DIR is given, else the +# download of URL into DESTINATION (reused when it already matches). A wrong digest or a missing file stops the configure. +function(webfront_provision_bootstrap archive) + cmake_parse_arguments(ARG "" "URL;INTEGRITY;DESTINATION;LOCAL_DIR" "" ${ARGN}) + webfront_sri_to_sha512("${ARG_INTEGRITY}" expected) + get_filename_component(name "${ARG_URL}" NAME) + if(ARG_LOCAL_DIR) + set(path "${ARG_LOCAL_DIR}/${name}") + if(NOT EXISTS "${path}") + message(FATAL_ERROR "Bootstrap environment ${path} is missing: WEBFRONT_BOOTSTRAP_DIR must hold ${name}") + endif() + else() + set(path "${ARG_DESTINATION}/${name}") + set(present FALSE) + if(EXISTS "${path}") + file(SHA512 "${path}" actual) + if(actual STREQUAL expected) + set(present TRUE) + endif() + endif() + if(NOT present) + file(MAKE_DIRECTORY "${ARG_DESTINATION}") + file(DOWNLOAD "${ARG_URL}" "${path}" STATUS result TLS_VERIFY ON INACTIVITY_TIMEOUT 60 TIMEOUT 600) + list(GET result 0 code) + if(NOT code EQUAL 0) + file(REMOVE "${path}") + list(GET result 1 reason) + message(FATAL_ERROR "Cannot download the bootstrap environment ${ARG_URL}: ${reason}. " + "Provision it with -DWEBFRONT_BOOTSTRAP_DIR=.") + endif() + endif() + endif() + file(SHA512 "${path}" actual) + if(NOT actual STREQUAL expected) + if(NOT ARG_LOCAL_DIR) + file(REMOVE "${path}") + endif() + message(FATAL_ERROR "Bootstrap environment integrity check failed for ${path}: expected ${ARG_INTEGRITY}") + endif() + set(${archive} "${path}" PARENT_SCOPE) +endfunction() + +# The SRI value ("sha512-") of a file, for archives a test builds itself. +function(webfront_file_sri file output) + file(SHA512 "${file}" hex) + set(alphabet "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") + string(LENGTH "${hex}" length) + set(encoded "") + foreach(start RANGE 0 ${length} 6) + if(start GREATER_EQUAL length) + break() + endif() + math(EXPR remaining "(${length} - ${start}) / 2") + string(SUBSTRING "${hex}" ${start} 6 digits) + string(LENGTH "${digits}" digitCount) + string(APPEND digits "000000") + string(SUBSTRING "${digits}" 0 6 digits) + math(EXPR group "0x${digits}") + set(characters 4) + if(remaining EQUAL 1) + set(characters 2) + elseif(remaining EQUAL 2) + set(characters 3) + endif() + foreach(index RANGE 0 3) + math(EXPR shift "18 - 6 * ${index}") + math(EXPR sextet "(${group} >> ${shift}) & 63") + if(index LESS characters) + string(SUBSTRING "${alphabet}" ${sextet} 1 character) + else() + set(character "=") + endif() + string(APPEND encoded "${character}") + endforeach() + endforeach() + set(${output} "sha512-${encoded}" PARENT_SCOPE) +endfunction() diff --git a/cmake/WebFrontRegistry.cmake b/cmake/WebFrontRegistry.cmake new file mode 100644 index 00000000..be76d82c --- /dev/null +++ b/cmake/WebFrontRegistry.cmake @@ -0,0 +1,58 @@ +# The real packages of the local npm registry of the tests (test/web/registry-packages.json): downloaded at configure time +# like the other dependencies, verified against their SHA-512 integrity, never committed. A wf script then builds the +# registry's files from them (test/web/registry/), so that no test reaches the public registry and none needs a JavaScript runtime. +include(WebFrontBootstrap) + +# A directory holding the listed archives (-.tgz, @scope/name as scope-name-.tgz) replaces the +# downloads on a machine without network access. +set(WEBFRONT_REGISTRY_DIR "" CACHE PATH "Directory with the pinned archives of the test registry, instead of downloading them") + +# Fills with the archives of , each named and verified; sets to the +# directory. A wrong digest or a missing archive stops the configure. +function(webfront_provision_registry output list directory) + file(READ "${list}" content) + string(JSON count LENGTH "${content}" packages) + math(EXPR last "${count} - 1") + file(MAKE_DIRECTORY "${directory}") + foreach(index RANGE 0 ${last}) + string(JSON url GET "${content}" packages ${index} url) + string(JSON integrity GET "${content}" packages ${index} integrity) + webfront_sri_to_sha512("${integrity}" expected) + get_filename_component(name "${url}" NAME) + # Scoped packages share base names with others of the same version: the file name carries the scope. + string(JSON package GET "${content}" packages ${index} name) + if(package MATCHES "^@([^/]+)/") + set(name "${CMAKE_MATCH_1}-${name}") + endif() + set(path "${directory}/${name}") + set(present FALSE) + if(EXISTS "${path}") + file(SHA512 "${path}" actual) + if(actual STREQUAL expected) + set(present TRUE) + endif() + endif() + if(NOT present) + if(WEBFRONT_REGISTRY_DIR) + if(NOT EXISTS "${WEBFRONT_REGISTRY_DIR}/${name}") + message(FATAL_ERROR "Test registry archive ${WEBFRONT_REGISTRY_DIR}/${name} is missing: WEBFRONT_REGISTRY_DIR must hold it") + endif() + file(COPY_FILE "${WEBFRONT_REGISTRY_DIR}/${name}" "${path}" ONLY_IF_DIFFERENT) + else() + file(DOWNLOAD "${url}" "${path}" STATUS result TLS_VERIFY ON INACTIVITY_TIMEOUT 60 TIMEOUT 600) + list(GET result 0 code) + if(NOT code EQUAL 0) + file(REMOVE "${path}") + list(GET result 1 reason) + message(FATAL_ERROR "Cannot download ${url}: ${reason}. Provision the archives with -DWEBFRONT_REGISTRY_DIR=.") + endif() + endif() + endif() + file(SHA512 "${path}" actual) + if(NOT actual STREQUAL expected) + file(REMOVE "${path}") + message(FATAL_ERROR "Integrity check failed for ${name}: expected ${integrity}") + endif() + endforeach() + set(${output} "${directory}" PARENT_SCOPE) +endfunction() diff --git a/cmake/WebKitGTKSupport.cmake b/cmake/WebKitGTKSupport.cmake index 61bbed7e..55ccaa7f 100644 --- a/cmake/WebKitGTKSupport.cmake +++ b/cmake/WebKitGTKSupport.cmake @@ -14,13 +14,13 @@ endif() target_compile_definitions(WebFront INTERFACE WEBFRONT_EMBED_WEBKITGTK) target_link_libraries(WebFront INTERFACE ${CMAKE_DL_LIBS}) -include("${CMAKE_CURRENT_LIST_DIR}/WebKitGTKTestEnvironment.cmake") +include("${CMAKE_CURRENT_LIST_DIR}/../test/cmake/WebKitGTKTestEnvironment.cmake") function(webfront_add_webkitgtk_tests) foreach(name IN LISTS ARGN) webfront_configure_webkitgtk_test("${name}") endforeach() - set(source "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../webtest") + set(source "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../test/web") add_executable(webkitgtk_lifecycle "${source}/WebKitGTKLifecycle.cpp") target_link_libraries(webkitgtk_lifecycle PRIVATE WebFront_test_hardening WebFront WebFront_warnings WebFront_options) add_dependencies(webtest webkitgtk_lifecycle) @@ -36,4 +36,19 @@ function(webfront_add_webkitgtk_tests) webfront_set_browser_test_properties(WebKitGTKAdapter-${mode} "${source}" 60) webfront_configure_webkitgtk_test(WebKitGTKAdapter-${mode}) endforeach() + # Short direct-channel correctness checks; no measurement batches or reports. + add_executable(webkitgtk_transport_contracts "${source}/WebKitGTKTransportBenchmark.cpp") + target_compile_definitions(webkitgtk_transport_contracts PRIVATE WEBFRONT_TRANSPORT_CONTRACTS_ONLY) + target_link_libraries(webkitgtk_transport_contracts PRIVATE WebFront WebFront_warnings WebFront_options) + add_dependencies(webtest webkitgtk_transport_contracts) + if(display_runner) + add_test(NAME WebKitGTKTransportContracts COMMAND "${display_runner}" -a $) + else() + add_test(NAME WebKitGTKTransportContracts COMMAND webkitgtk_transport_contracts) + endif() + webfront_set_browser_test_properties(WebKitGTKTransportContracts "${source}" 60) + webfront_configure_webkitgtk_test(WebKitGTKTransportContracts) + # Manual measurement only: never built or run by CTest/CI. + add_executable(webkitgtk_transport_benchmark EXCLUDE_FROM_ALL "${source}/WebKitGTKTransportBenchmark.cpp") + target_link_libraries(webkitgtk_transport_benchmark PRIVATE WebFront WebFront_warnings WebFront_options) endfunction() diff --git a/cmake/WebView2Support.cmake b/cmake/WebView2Support.cmake index ace600ab..b969378f 100644 --- a/cmake/WebView2Support.cmake +++ b/cmake/WebView2Support.cmake @@ -59,7 +59,7 @@ target_link_libraries(WebFront INTERFACE # Register lifecycle coverage once, alongside the shared Jasmine runner; paths are module-relative. function(webfront_add_webview2_tests) - get_filename_component(webtest_source_dir "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../webtest" ABSOLUTE) + get_filename_component(webtest_source_dir "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../test/web" ABSOLUTE) add_executable(webview2_lifecycle "${webtest_source_dir}/WebView2Lifecycle.cpp" "${webtest_source_dir}/WebView2HeaderConsumer.cpp") @@ -69,4 +69,14 @@ function(webfront_add_webview2_tests) add_test(NAME WebView2Lifecycle-${mode} COMMAND webview2_lifecycle ${mode}) webfront_set_browser_test_properties("WebView2Lifecycle-${mode}" "${webtest_source_dir}" 45) endforeach() + # Short direct-channel correctness checks; no measurement batches or reports. + add_executable(webview2_transport_contracts "${webtest_source_dir}/WebView2TransportBenchmark.cpp") + target_compile_definitions(webview2_transport_contracts PRIVATE WEBFRONT_TRANSPORT_CONTRACTS_ONLY) + target_link_libraries(webview2_transport_contracts PRIVATE WebFront WebFront_warnings WebFront_options) + add_dependencies(webtest webview2_transport_contracts) + add_test(NAME WebView2TransportContracts COMMAND webview2_transport_contracts) + webfront_set_browser_test_properties(WebView2TransportContracts "${webtest_source_dir}" 60) + # Manual measurement only: never built or run by CTest/CI. + add_executable(webview2_transport_benchmark EXCLUDE_FROM_ALL "${webtest_source_dir}/WebView2TransportBenchmark.cpp") + target_link_libraries(webview2_transport_benchmark PRIVATE WebFront WebFront_warnings WebFront_options) endfunction() diff --git a/.clang-tidy b/cmake/clang-tidy.yaml similarity index 100% rename from .clang-tidy rename to cmake/clang-tidy.yaml diff --git a/logging/Logger.cpp b/cmake/mddlog/Logger.cpp similarity index 99% rename from logging/Logger.cpp rename to cmake/mddlog/Logger.cpp index 068d7847..96123a70 100644 --- a/logging/Logger.cpp +++ b/cmake/mddlog/Logger.cpp @@ -7,7 +7,7 @@ import mddlog.core.ring; import mddlog.adapter.logrecord; import mddlog.adapter.transportconsumer; -#include "tooling/LoggerApi.hpp" +#include namespace webfront::log { struct SinkHandle::Registration { diff --git a/codecov.yml b/codecov.yml deleted file mode 100644 index cb759f37..00000000 --- a/codecov.yml +++ /dev/null @@ -1,12 +0,0 @@ -coverage: - status: - project: - default: - target: auto - threshold: 0.2% - patch: - default: - target: 95% -ignore: - - "webtest/**" - - "examples/**" diff --git a/docs/ASYNC_EXECUTION.md b/docs/ASYNC_EXECUTION.md index 518b685d..fc718e32 100644 --- a/docs/ASYNC_EXECUTION.md +++ b/docs/ASYNC_EXECUTION.md @@ -76,6 +76,27 @@ auto handle = app.spawn(showSquareRoot(ui)); handle.requestStop(); ``` +`ui.writesAtMost(limit)` returns a sender completing once at most `limit` frames +wait for the network on that browser's connection, woken by the write that brings +them down (no polling), or at once when the browser is gone. A closing connection +or a released link also completes it, after the closure was reported; it observes +the task's stop token. It paces output to a browser that reads slower than written. + +`app.resumeAfter(duration)` and `ui.resumeAfter(duration)` return a sender that +completes on the server context once the duration has elapsed. Awaited in a task, +it observes the task's stop token: `TaskHandle::requestStop()` or shutdown +completes it stopped at once, so a waiting coroutine never delays shutdown. +`app.subscribeUIClosed(handler)` calls the handler on the server thread when a +browser closes its connection or the connection fails (a failed write included), +for as long as the returned `UISubscription` lives; shutdown, which stops every +connection itself, notifies no handler. The connection is then released by a task +on the server context; a call made meanwhile on another thread keeps the link alive +until it returns (`findLink` shares it). Afterwards, an untyped `jsFunction` call to that UI is +dropped, a typed call returns a future that throws `Browser connection closed`, +a `jsFunctionSender` completes with an error when started, and `addScript` throws +`ConnectionError`. The 16-bit identifier of a released connection is reused only +after 65,536 later connections. + `app.spawn(task)` and `ui.spawn(task)` may be called from any thread while the application object remains alive, including concurrently with stop/shutdown. Coroutine bodies and their resumptions execute on the server context. Synchronize @@ -120,7 +141,7 @@ context. Neither sender calls nor future calls have a delivery acknowledgement for the write queue or an automatic response deadline. An unsuccessful write that does not report closure can leave a call pending until disconnection; sender waits can also be ended by task cancellation or application shutdown. -Timeout composition remains future work. +Timeout composition with `resumeAfter` remains future work. Cancellation before start sends no frame. Cancellation after dispatch stops waiting locally; JavaScript already running continues, and its late response @@ -142,3 +163,18 @@ already-stopped token also completes safely, without dispatching. cancellation API. The untyped `ui.jsFunction(name)` remains fire-and-forget. JavaScript-to-C++ calls still always return Promises. None of these changes adds richer bridge result types or remote Promise cancellation. + +## HTTP gzip CPU work + +Cold gzip identity fallback is a sender backed by one lazy, owned worker per HTTP server. +The worker reads owned compressed bytes and fills preallocated output; it never calls filesystem +providers or manipulates network objects. Completion resumes on the connection's I/O scheduler, +where validation results enter the cache and HTTP headers/body are finalized. Bounded response +leases survive through the network send, including cache-hit responses and HEAD consumers. + +Stop closes admission; queued work without live consumers is skipped. An active decode runs +to completion before cancellation is delivered locally. Peer disconnects are discovered at the +subsequent write. After external run callers return, server drain joins CPU work before pumping +and joining its existing task scope. No CPU task or encoded/decoded buffer is detached from its +owner. See [HTTP asset encoding](HTTP_ASSETS.md) for 503 backpressure, memory reservations and +remaining synchronous provider-read and non-interruptible-decode limits. diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md new file mode 100644 index 00000000..30615a00 --- /dev/null +++ b/docs/CHANGELOG.md @@ -0,0 +1,304 @@ +# Changelog + +## Unreleased + +## 0.5.0 - 2026-10-26 + +- Gzip identity fallback reuses a bounded validated-representation cache for GET and HEAD (#281). + Cold decoding uses buffered bit reads and a small Huffman lookup (#282), with unchanged + allocation behavior, strict stream validation and output budgets. Release benchmarks and + test-only zlib differential/sanitizer validation are recorded in `docs/GZIP_DECODER_MEASUREMENTS.md`. + +- `WebFrontLifeDeveloper` starts without argument on `./life-project` (created when missing, reused untouched otherwise) and the + pinned environment; the explicit ` [ ]` form remains. At configuration, the + native window engine of the platform is enabled automatically when its dependencies are found (top-level builds with examples, + without `ENABLE_TESTING`; `-DWEBFRONT_AUTODETECT_NATIVE=OFF` disables it, an explicit `WEBFRONT_EMBED_*` value always wins). + A missing engine does not fail the configuration: CMake explains how to install it and the Life examples are built for the default browser instead. The README Game of Life walkthrough builds with `mkdir build`, `cd build`, + `cmake ..` and `cmake --build .` (#366). The developer terminal drops its redundant banner line; the sources advance to environment 0.6.3 (unpublished, the pin stays on 0.6.2). + Automatic engine values stay outside the cache so an explicit choice equal to the previous detection is still respected; + removing an explicit engine cache entry resumes detection. Platforms without a registered engine configure the browser fallback. + +- Cold gzip identity fallback uses one server-owned worker with bounded jobs, consumers and + buffer capacities (#283). The new compressed-input cap defaults to 4 MiB and returns 500 + before cache lookup when exceeded, including HEAD; configure `maxGzipEncodedAssetSize` + for larger assets. Queue/memory saturation and preparation allocation failures return 503. + Cancelled work skipped before decoding and decoder exceptions cannot poison later consumers. +- Transport benchmarks are manual targets, excluded from CI, CTest and default builds (#283). + Short direct-channel correctness contracts remain in CTest for WebKitGTK, WebView2 and WKWebView. + +- Remove the local SSH CI orchestrator, container definitions, native session workers and matrix drift checks. + The GitHub-hosted workflows remain the CI execution path. + +- The allocation-counting regression is omitted from ThreadSanitizer builds, whose C++ runtime + defines the same global `new`/`delete` operators; ordinary and ASan/UBSan builds retain it. macOS adds + `WKWebViewTransportBenchmark` (HTML bridge, native strings, `callAsyncJavaScript` and base64 bytes) and separate native + API contract tests. ADR-017 records the measurements and the public Cocoa API constraints on a future direct transport. + +- Linux transport performance now has a dedicated Release CI lane without coverage, repeated three times with retained + JSON, environment and CTest reports; the Debug/coverage desktop lane stays in place. ADR-017 distinguishes mandatory HTML + availability from the selected default transport and qualifies mobile network rules by OS version. + +- ADR-017 (Proposed, #363) prepares direct access to embedded frontends (native resource schemes and message channels) for + future Android, iOS and other mobile frontends, while HTTP/WebSocket stays the normative path of every frontend and of future + microcontroller targets. The binary format of ADR-003 is carried unchanged; no API or wire change is made. The new + `WebKitGTKTransportBenchmark` CTest case (labels `web-integration` and `performance`) compares the bridge with WebKitGTK's + message handlers and `evaluate_javascript` in one window; it fails on a wrong echo, never on a timing, and writes a JSON report. + `WebView2TransportBenchmark` does the same on Windows with `WebMessageReceived`, `ExecuteScript` and a shared buffer + (`ICoreWebView2SharedBuffer`): WebView2 string messages are slower than the HTML bridge from 32 KiB and for C++ to JS, the + shared buffer is 2 to 6 times faster. The figures leave out the codec and the thread hop a real transport adds, so they + overstate the gain of a direct path. The benchmark exposed two per-message costs of the bridge, fixed with regression tests: + `Messages.hpp` wrote to the standard output for every encoded parameter, and `Frame::addBuffer` formatted a hex dump of + every buffer before the log level was tested. + +- The README animation draws the C++ application inside the image, beside the WebFront window (#359): it is no longer cropped by the table column on narrow screens and in the GitHub app, and weighs 0.4 MB instead of 1.2 MB. The code stays in the README as text, in a collapsed block; `docs/tools/render-life-bootstrap.py` reads it from there. + +- The manifest and the lock of the repository move to `js/developer/` (#354): the driver and the CI select them with `--manifest-dir js/developer`, and the closed list of the root loses two entries (9 left). + +- The test bootstrap environment is the published 0.6.2 (#354), which installs the archives of `@types` packages and honours a manifest directory; the README walkthrough no longer needs a local archive for `wf check`. + +- The manifest and the lock of a project may live in a directory of the project (#354): `DeveloperBootstrapOptions::manifestDirectory` (validated, passed in the bootstrap configuration only when set) and `webfront-wf --manifest-dir`; the environment derives `manifestPath` and `lockPath` from it, and a script still never writes them. Paths inside the manifest stay relative to the project root. Environment 0.6.2, not yet published; an earlier environment ignores the option. + +- Simpler repository root (#352): `.devcontainer/` is removed (nothing used it, and its Dockerfile duplicated the toolchain of the CI by hand); `.gitattributes` drops its generic Visual Studio and document rules (177 to 69 lines, the attributes of every tracked file are unchanged); `.clang-tidy` becomes `cmake/clang-tidy.yaml`, passed to clang-tidy by `cmake/StaticAnalyzers.cmake`, and `.clang-format` moves next to the C++ it formats, with a copy in `include/webfront/`, `test/` and `examples/` so that their styles may diverge; the layout guard records why every other root entry stays. + +- Documentation of the standalone developer environment (#317, epic #303): the README walkthrough uses `wf create`, `init`, `install`, `dev`, `check`, `test` and `embed` on the pinned environment; `DEVELOPER_ENVIRONMENT.md` opens with the commands, the direct statement of its limits (no sandbox, browser packages only, installation scripts not run) and the maintenance of TypeScript through `wf check`; the 0.4.0 "prepared, not published" text is removed; PROJECT_STATUS starts with the current state; ADR-016 is 1.5. + +- Remove the retired PI starter from source distributions and `wf create`; Life remains the maintained React/C++ starter. + Preserve real-time fallbacks in scoped test clocks, release preparation cancellation before the test frame runs, + and retain independent reproducibility, bootstrap-refresh and packaged permission checks. The attribution audit + ignores user signature/log display settings. + +### Fixed + +- The bridge no longer pays for diagnostics on every message (#363): the encoder of `Messages.hpp` wrote to `std::cout` for + each parameter, and `Frame::addBuffer` formatted a hex dump of each sent buffer before `log::debug()` tested the level (21.7 MB + allocated for a 1 MiB buffer). A 32 KiB echo over the HTML bridge drops from about 2.4 ms to 0.7 ms on WebKitGTK. Regressions: + `Encoding bridge messages writes nothing to the standard output` and `FrameBufferNotFormattedWhenDebugDisabled`. +- The developer store reads and writes project paths beyond MAX_PATH on Windows (#349): `projectPath` takes the extended-length form from 200 characters, as does a project root longer than MAX_PATH (`canonicalDirectory`), containment is checked on the ordinary spelling, and staged files get the same treatment. The MSVC option is now `/analyze:stacksize65536`, one argument: with a space, sccache read `65536` as a second source file and refused to cache 48 compilations of the Windows CI build (about 9 minutes against 25 seconds on Linux). +- The installer of the developer environment reads npm archives rooted at any single directory, as npm does (#316): the archives of + `@types/*` are rooted at the package name and were refused as "Invalid npm tarball root". A mixed or escaping root is still refused. +- The Life starter type-checks under TypeScript `strict` (`useState`), which `wf check` now proves. +- Script injection works before the page body exists, including a driver handshake completed during HTML parsing. + +- `wf test` supports WebKit engines without `AbortSignal.any()` (#335), preserving cancellation/deadline reports and + exit codes. Deadline and cleanup timers and the external cancellation listener are released on every exit. + The driver also remembers a watchdog close requested before the browser handshake; a late connection closes + without launching a command. Environment sources advance to 0.6.2 while the release and test-bootstrap pins remain on published 0.6.1. +- Browser regressions advance deadlines, grace periods and dev polling explicitly instead of sleeping. Native command + cancellation uses a release handshake, repeated type checks reuse immutable fixture bytes, cache/command fixtures + drop the large application-only dependency graph after the Life checks, and the shared bridge + runner avoids full binary debug dumps. Retired PI and Signal Studio application tests are removed; Life retains + React/TSX, preview, reproducible generation and rootless embedded coverage. Reproducibility compares two identical + builds, followed by a separate bootstrap refresh; packaged-script permission checks remain end-to-end. + + +### Added + +- Developer journey qualification (#316, epic #303): `Journey*` CTest cases run `wf create`, `init`, `install`, `check`, `test`, `build` + and `embed` on one project in an empty directory from the local registry, compile the generated header into the Life application + and run it from an empty directory, then check a script under denied permissions and an emptied cache offline and restored. The test + registry gains `@types/react`, `@types/react-dom` and `csstype`. ADR-013, ADR-014 and ADR-015 are accepted. +- `third_party/` is removed (#319, epic #303): `fflate` 0.8.3, the last vendored source, is a locked package of the repository's + `wf` project, imported by name from `js/developer/environment/embed.mjs`; its notice comes from the installed package. + The environment archive stays byte for byte identical. The test registry downloads it at configure time, and + `RepositoryLayout` now rejects `third_party`, `vendor` and `node_modules` paths as well as any unlisted root entry. +- Tests, regeneration and CI without a JavaScript runtime or package manager (#318, epic #303). Configuring with `ENABLE_TESTING=ON` downloads, and + verifies against their SHA-512, the pinned bootstrap environment and the real packages of the tests' npm registry + (`test/web/registry-packages.json`; `-DWEBFRONT_REGISTRY_DIR` for a machine without network access); `wf run test-registry` + builds the registry, the environment is built from the current sources and the fixtures are assembled by CTest itself, so + `WEBFRONT_DEVELOPER_FIXTURES` and `WEBFRONT_REQUIRE_NODE` are gone. The 86 JavaScript tests became 84 Jasmine specs + (`test/developer/specs/`) run by the repository's own `wf test`, plus CMake tests for the bundle checksums and the reserved + command names. The headers of the core are rendered and checked by `js/core/EmbedAsset.cmake` in pure CMake (ADR-016 + v1.3), with a Catch2 scenario that decodes each of them. `NoNodeDependency` audits every file and + `NoNodeDependencyRejectsInjections` proves the guard. The Node.js tools, `vendor/package*.json` and the comparison job + of *Developer packages* are deleted; every CI job removes the JavaScript runtimes from the runner first. The record of + each former tool and test is `docs/NODE_TOOLS_MIGRATION.md`. + +- The developer environment builds itself (#315, distribution 0.6.1, published as `developer-v0.6.1` and pinned by `DeveloperReleaseData.hpp`, and by the bootstrap of the tests): the + repository is a `wf` project (`webfront.project.json`, `webfront-packages.lock.json`) and the scripts of + `js/developer/scripts/` run in the pinned bootstrap environment with `webfront-wf`. `build.mjs` bundles the environment + with the locked esbuild-wasm and writes `environment.tgz`, the starters, `provision.json` and the pinned header (with + `--refresh-bootstrap`, the bootstrap bundles, their checksums and the core headers); `site.mjs` stages the Pages site + and refuses to change a published version; `pin.mjs` checks the pinned header against the published archive; `embed-core.mjs` regenerates the core headers. The bytes + are those of the Node.js build, twice in a row (CTest `SelfBuild*`, job `wf-package` of *Developer packages*). The + publication runs without Node.js (`pages.sh`, `archive-release.sh`, a shell tag check); `-DWEBFRONT_REQUIRE_NODE=OFF` + configures a test build without it. The inventory of the Node.js tools and their destination is + `docs/NODE_TOOLS_MIGRATION.md`; the maintainer procedure is `js/developer/tools/PUBLISHING.md`. + +- `webfront-wf` test driver and bootstrap provisioning (#321, developer distribution 0.6.0 published as `developer-v0.6.0`, pinned by `DeveloperReleaseData.hpp` and by the bootstrap): runs one `wf` command without interaction on a project + and exits with its status (64 usage, 70 bootstrap failure, 71 time limit, 72 no result), with an optional JSON report. + `cmake/WebFrontBootstrap.cmake` pins the bootstrap environment (0.6.1) and, with `ENABLE_TESTING=ON`, downloads + and verifies it at configure time, or takes it from `WEBFRONT_BOOTSTRAP_DIR`. `environment.json` declares `protocol` and + `api`; `webfront.developer.config` exposes the supported versions and the loader refuses an incompatible archive with an + explicit diagnostic. The Linux CEF job blocks the public network after configure. + +- `wf test [--timeout ] [pattern]` (#310, environment sources; release pin unchanged): builds the manifest's + `test.specs` with esbuild-wasm and runs them under the project's locked `jasmine-core`, obtained by `wf install` from + the registry, in a hidden same-origin frame. Progress and a summary stream to the terminal; the structured report + (counts, failures, pending specs) is bounded, and the exit code is 0, 1 (failure, load error, nothing run), 124 (time + limit) or 130 (Ctrl+C). `runNonInteractive` runs a command without a terminal, sends `{exitCode, output, report}` to an + application's C++ function and ends the session. `DeveloperFS` also serves `.webfront/developer/test/`. + +- `wf build [entry]` / `wf dev [entry]` (#309, environment sources; release pin unchanged): build all manifest + entries to `.webfront/developer/build/` without opening the preview, or continuously rebuild one preview + with a persistent esbuild/WASM context. Sequential 750 ms polling watches read inputs and missing imports + (1,024 paths, 32 MiB per pass). Build/publication errors preserve the last good preview; diagnostics with + file/line/column stream to the terminal and overlay the preview. Corrections resume rebuilding; Ctrl+C + terminates the Worker, stops polling and aborts staged output. + +- Project manifest `webfront.project.json` (format 1: `name`, `version`, `dependencies`, `registry`, `scripts`, + `entries`, `providers`, `test`, `permissions`), strictly validated; `wf init`, `wf install [--update]` and + manifest-driven `wf preview`/`wf embed` in developer distribution 0.5.0, which `DeveloperReleaseData.hpp` pins + (published as `developer-v0.5.0`). 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. +- `wf restore [--offline]` (developer distribution 0.5.0): rebuilds the package cache from the lock alone, at the + locked versions and integrities, idempotent and interruptible; `--offline` only checks the cache and lists the + missing or corrupted packages. Cached packages carry a record of their files' digests. The registry is the + application's option, else the manifest's `registry`, else registry.npmjs.org; `wf install` and `wf restore` + print it with its origin. A reproducible local npm registry fixture (`js/developer/tools/registry-fixture.mjs`) + serves the tests. + +- `wf run [--timeout ] ' + + '\n'; + return new Map([...compiled, ['index.html', encoder.encode(page)], ['runner.js', encoder.encode(runnerSource)], ['jasmine.js', jasmine]]); +} + +const emptyReport = (status, exitCode, extra = {}) => ({status, exitCode, jasmine: '', pattern: '', incomplete: '', total: 0, passed: 0, + failed: 0, pending: 0, excluded: 0, durationMs: 0, failures: [], pendingSpecs: [], suites: [], global: [], ...extra}); +const finite = value => Number.isFinite(value) && value >= 0 ? Math.round(value) : 0; +const text = (value, limit) => typeof value === 'string' ? value.slice(0, limit) : ''; +const problems = list => Array.isArray(list) ? list.slice(0, reportLimits.messages).map(item => + ({message: text(item?.message, reportLimits.text), stack: text(item?.stack, reportLimits.text)})) : []; + +/** + * The report of a finished run, from what the frame posted. Counts are exact; the lists of failures and of pending + * specs are cut at their limits. + * status: passed | failed | incomplete (no spec, or fit/fdescribe) | error (the specs did not load); + * exitCode: 0 only for passed. + */ +export function buildReport(data, {pattern = ''} = {}) { + if (data.type === 'error') return emptyReport('error', 1, {pattern, error: text(data.message, reportLimits.text)}); + const specs = Array.isArray(data.specs) ? data.specs : []; + const count = status => specs.filter(spec => spec.status === status).length; + const failedSpecs = specs.filter(spec => spec.status === 'failed'); + const executed = specs.filter(spec => spec.status !== 'excluded').length; + const global = problems(data.global); + const suites = Array.isArray(data.suites) ? data.suites.slice(0, reportLimits.failures).map(({name, failures}) => ({name: text(name, 1024), messages: problems(failures)})) : []; + let status = ['passed', 'failed', 'incomplete'].includes(data.overall) ? data.overall : 'failed'; + let incomplete = text(data.incomplete, 1024); + if (status === 'passed' && (failedSpecs.length || global.length || suites.length)) status = 'failed'; + if (status === 'passed' && !executed) { status = 'incomplete'; incomplete = pattern ? `No spec matches "${pattern}"` : 'No specs found'; } + return {status, exitCode: status === 'passed' ? 0 : 1, jasmine: text(data.version, 32), pattern, incomplete, + total: executed, passed: count('passed'), failed: failedSpecs.length, pending: count('pending'), excluded: count('excluded'), + durationMs: finite(data.durationMs), + failures: failedSpecs.slice(0, reportLimits.failures).map(({name, failures}) => ({name: text(name, 1024), messages: problems(failures)})), + pendingSpecs: specs.filter(spec => spec.status === 'pending').slice(0, reportLimits.pending).map(({name, reason}) => ({name: text(name, 1024), reason: text(reason, 1024)})), + suites, global}; +} + +const plural = (count, word) => `${count} ${word}${count === 1 ? '' : 's'}`; +const trace = stack => stack.split('\n').filter(line => /(^|\s|@)\S+:\d+(:\d+)?\)?$/.test(line.trim())).slice(0, 3).map(line => ` ${line.trim()}`); +const problemLines = ({message, stack}) => [` ${message.split('\n').join('\n ')}`, ...trace(stack)]; + +/** The terminal's text for a report: a summary line, then each failure, global failure and pending spec. */ +export function formatReport(report) { + if (report.status === 'error') return `The specs did not load: ${report.error}`; + const summary = [plural(report.total, 'spec'), plural(report.failed, 'failure'), `${report.pending} pending`]; + if (report.excluded) summary.push(`${report.excluded} filtered out`); + const lines = [`${report.status === 'passed' ? 'PASSED' : 'FAILED'}: ${summary.join(', ')} (${report.durationMs} ms, jasmine-core ${report.jasmine})`]; + if (report.incomplete) lines.push(report.incomplete); + for (const {name, messages} of report.failures) lines.push(`FAIL ${name}`, ...messages.flatMap(problemLines)); + for (const {name, messages} of report.suites) lines.push(`FAIL ${name} (suite)`, ...messages.flatMap(problemLines)); + if (report.global.length) lines.push('Failures outside the specs:', ...report.global.flatMap(problemLines)); + for (const {name, reason} of report.pendingSpecs) lines.push(`PENDING ${name}${reason ? `: ${reason}` : ''}`); + return lines.join('\n'); +} + +const progress = {passed: '.', failed: 'F', pending: '*'}; +/** The promise, or a rejection with the signal's reason as soon as the signal aborts, whatever the promise is waiting for. */ +export function abortable(promise, signal) { + return new Promise((resolve, reject) => { + const abort = () => reject(signal.reason); + if (signal.aborted) abort(); + signal.addEventListener('abort', abort, {once: true}); + promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort)); + }); +} + +export const stoppedRun = (reason, pattern) => { + const [message, exitCode] = reason === 'timeout' ? ['Tests stopped at their time limit', 124] : ['Tests stopped by Ctrl+C', 130]; + return Object.assign(new ScriptExit(message, exitCode), {report: emptyReport(reason, exitCode, {pattern, error: message})}); +}; + +// Out of sight but laid out like a page: specs that measure the DOM need a real viewport. +function defaultFrame() { + const frame = document.createElement('iframe'); + frame.title = 'WebFront tests'; + frame.setAttribute('aria-hidden', 'true'); + frame.style.cssText = 'position:fixed;left:-10000px;top:0;width:1024px;height:768px;border:0'; + return frame; +} + +/** + * Runs the published runner in a frame of its own and resolves with its report. It rejects with a ScriptExit when + * `signal` aborts (130) or after `timeout` seconds (124); the frame is removed in every case. `createFrame` makes the + * frame element. + */ +export function runInFrame({pattern, timeout, runId, signal, write = () => {}, createFrame = defaultFrame}) { + return new Promise((resolve, reject) => { + const frame = createFrame(); + let timer; + const finish = (error, report) => { + clearTimeout(timer); + removeEventListener('message', receive); + signal?.removeEventListener('abort', interrupt); + frame.remove(); + error ? reject(error) : resolve(report); + }; + const receive = ({source, origin, data}) => { + if (source !== frame.contentWindow || origin !== location.origin) return; + const message = data?.webfrontTest; + if (message?.type === 'spec') write(progress[message.status] ?? ''); + else if (message?.type === 'done' || message?.type === 'error') finish(null, buildReport(message, {pattern})); + }; + const interrupt = () => finish(stoppedRun('interrupted', pattern)); + addEventListener('message', receive); + signal?.addEventListener('abort', interrupt, {once: true}); + timer = setTimeout(() => finish(stoppedRun('timeout', pattern)), timeout * 1000); + if (signal?.aborted) return interrupt(); + frame.src = `/webfront/developer/test/${runId}/index.html?pattern=${encodeURIComponent(pattern)}&run=${Date.now()}`; + document.body.append(frame); + }); +} + +/** The terminal's result of a report: its text on success, a ScriptExit carrying the report otherwise. */ +export function reportResult(report) { + const output = formatReport(report); + if (report.exitCode === 0) return output; + throw Object.assign(new ScriptExit(output, report.exitCode), {report}); +} + +// A bridge string carries a 16-bit length, in UTF-8 bytes: the result must fit in one, with a margin. +export const resultLimit = 60000; +const byteLength = value => encoder.encode(JSON.stringify(value)).length; +const clipText = (text, length) => text.length > length ? `${text.slice(0, length)}…` : text; + +/** + * The result cut to `limit` bytes of JSON, so that it can cross the bridge: the output first, then the stack frames, + * then the messages, then the lists of failures; the counts and statuses are never changed. A result that was cut says + * so in `truncated`. + */ +export function fitResult(result, limit = resultLimit) { + if (byteLength(result) <= limit) return result; + const fitted = structuredClone(result); + fitted.truncated = true; + const problems = report => [...report.failures, ...report.suites ?? []].flatMap(({messages}) => messages).concat(report.global ?? []); + const steps = [ + ...[4096, 1024, 256].map(length => () => { fitted.output = clipText(fitted.output, length); }), + () => { for (const problem of problems(fitted.report)) problem.stack = ''; }, + ...[2048, 512, 128].map(length => () => { + for (const problem of problems(fitted.report)) problem.message = clipText(problem.message, length); + for (const key of ['error', 'incomplete', 'pattern']) if (typeof fitted.report[key] === 'string') fitted.report[key] = clipText(fitted.report[key], length); + }), + ...[10, 3, 0].map(count => () => { + for (const key of ['failures', 'suites', 'pendingSpecs']) if (fitted.report[key]) fitted.report[key].length = Math.min(fitted.report[key].length, count); + fitted.report.global.length = Math.min(fitted.report.global.length, count); + }), + () => { fitted.output = ''; }, + // Whatever is left: the status and the counts, which are numbers and short words. + () => { + const {status, exitCode, jasmine, total, passed, failed, pending, excluded, durationMs} = fitted.report; + fitted.report = {status, exitCode, jasmine: clipText(String(jasmine ?? ''), 32), total, passed, failed, pending, excluded, durationMs, + failures: [], pendingSpecs: [], suites: [], global: [], pattern: '', incomplete: '', error: ''}; + }, + ]; + for (const step of fitted.report ? steps : steps.slice(0, 3).concat(steps.at(-2))) { + step(); + if (byteLength(fitted) <= limit) break; + } + return fitted; +} diff --git a/js/developer/environment/typecheck-snapshot.mjs b/js/developer/environment/typecheck-snapshot.mjs new file mode 100644 index 00000000..e2584509 --- /dev/null +++ b/js/developer/environment/typecheck-snapshot.mjs @@ -0,0 +1,400 @@ +// wf check inside its Worker: TypeScript compiles synchronously over an in-memory snapshot loaded beforehand. +// Phase 1 (asynchronous) reads the lib files of the locked typescript, the declaration files of the locked graph and +// the project files that tsconfig.json or the manifest entries cover, within bounds. Phase 2 creates the program with +// a CompilerHost over that snapshot: a file absent from it does not exist. +import {packageRoot} from './paths.mjs'; + +export const snapshotBounds = Object.freeze({files: 10000, bytes: 64 * 1024 * 1024, entries: 50000}); +export const projectRoot = '/project'; +const packagesRoot = '/packages'; +export const configPath = `${projectRoot}/tsconfig.json`; +// Never listed: installed packages come from the lock, wf's own files are not sources. +const skippedDirectories = new Set(['node_modules', '.webfront', '.git']); +const maxConfigPasses = 16; + +/** The options without a tsconfig.json; wf check always adds noEmit. */ +export const defaultCompilerOptions = Object.freeze({ + target: 'ES2022', module: 'ESNext', moduleResolution: 'Bundler', jsx: 'react-jsx', + lib: ['ES2022', 'DOM', 'DOM.Iterable'], strict: true, isolatedModules: true, skipLibCheck: true, +}); +// Nothing is emitted; the other options keep their meaning (composite still implies declaration), and the host +// writes nothing, not even build information. emitDeclarationOnly cannot be combined with noEmit. +const noEmit = {noEmit: true, emitDeclarationOnly: false}; + +const decoder = new TextDecoder(); +const declaration = /\.d\.[cm]?ts$/; +const missingFile = error => /Cannot read project file:/.test(error?.message); + +/** A module evaluating the CommonJS lib/typescript.js without require, so that TypeScript sees no Node.js system. */ +export const typescriptModule = source => + `const module = {exports: {}};\n(function (module, exports, require) {\n${source}\n}).call(globalThis, module, module.exports, undefined);\nexport default module.exports;\n`; + +const splitName = parts => parts[0]?.startsWith('@') ? [parts.slice(0, 2).join('/'), parts.slice(2)] : [parts[0], parts.slice(1)]; + +/** + * The locked graph as TypeScript sees it, without flattening: the roots in /project/node_modules, and package at + * /packages//node_modules/, where its dependencies are its siblings. realpath() maps every path to that + * canonical place, so TypeScript resolves a package's imports from its own dependencies. + */ +export function createLayout(lock) { + const packages = lock?.packages ?? {}; + const roots = new Map(Object.entries(lock?.roots ?? {}).map(([name, root]) => [name, root.id])); + const visible = owner => owner === null ? roots + : new Map([[packages[owner].name, owner], ...Object.entries(packages[owner].dependencies ?? {})]); + const packagePath = (id, path = '') => [packagesRoot, id, 'node_modules', packages[id].name, path].filter(Boolean).join('/'); + + // {kind: 'project', path} | {kind: 'package', id, path} | {kind: 'modules', names} | null + function locate(path) { + const parts = path.split('/').filter(Boolean); + let owner = null; + let rest; + if (parts[0] === 'project') { + rest = parts.slice(1); + if (rest[0] !== 'node_modules') return {kind: 'project', path: rest.join('/')}; + } else if (parts[0] === 'packages' && Object.hasOwn(packages, parts[1]) && parts[2] === 'node_modules') { + owner = parts[1]; + rest = parts.slice(2); + } else return null; + const names = visible(owner); + const inside = rest.slice(1); + if (!inside.length) return {kind: 'modules', names: [...new Set([...names.keys()].map(name => name.split('/')[0]))]}; + if (inside.length === 1 && inside[0].startsWith('@')) + return {kind: 'modules', names: [...names.keys()].filter(name => name.startsWith(`${inside[0]}/`)).map(name => name.split('/')[1])}; + const [name, inner] = splitName(inside); + return names.has(name) ? {kind: 'package', id: names.get(name), path: inner.join('/')} : null; + } + + const canonical = location => location.kind === 'project' + ? [projectRoot, location.path].filter(Boolean).join('/') : packagePath(location.id, location.path); + return {locate, canonical, packagePath}; +} + +const parentOf = path => path.slice(0, path.lastIndexOf('/')); +const nameOf = path => path.slice(path.lastIndexOf('/') + 1); + +/** + * The files TypeScript may see, by canonical path, and the reads that missed. Adding a file beyond the bounds skips + * it: the snapshot then records that it is truncated, and the files it skipped do not exist for the compiler. + */ +export function createSnapshot(lock, bounds = snapshotBounds) { + const layout = createLayout(lock); + const files = new Map(); + const directories = new Set([projectRoot]); + const misses = new Set(); + let bytes = 0; + let skipped = 0; + const addDirectories = path => { + for (let directory = parentOf(path); directory && !directories.has(directory); directory = parentOf(directory)) + directories.add(directory); + }; + for (const id of Object.keys(lock?.packages ?? {})) { + directories.add(layout.packagePath(id)); + addDirectories(layout.packagePath(id)); + } + const resolve = path => { + const location = layout.locate(path); + return location && location.kind !== 'modules' ? layout.canonical(location) : null; + }; + + return { + layout, files, misses, + get bytes() { return bytes; }, + get skipped() { return skipped; }, + get truncated() { return skipped > 0; }, + /** Adds a file by its canonical path; false when the bounds leave no room for it. */ + add(path, data) { + if (files.has(path)) return true; + if (files.size >= bounds.files || bytes + data.length > bounds.bytes) { + ++skipped; + return false; + } + files.set(path, decoder.decode(data)); + bytes += data.length; + addDirectories(path); + return true; + }, + /** Counts a file left out once the snapshot is truncated. */ + skip() { + ++skipped; + return false; + }, + addDirectory(path) { + directories.add(path); + addDirectories(path); + }, + realpath: path => resolve(path) ?? path, + fileExists(path) { + const real = resolve(path); + if (real !== null && files.has(real)) return true; + misses.add(path); + return false; + }, + readFile(path) { + const real = resolve(path); + if (real !== null && files.has(real)) return files.get(real); + misses.add(path); + return undefined; + }, + directoryExists(path) { + const location = layout.locate(path); + if (location?.kind === 'modules') return location.names.length > 0; + return location !== null && directories.has(layout.canonical(location)); + }, + // The subdirectories of a directory, by name. + getDirectories(path) { + const location = layout.locate(path); + if (!location) return []; + if (location.kind === 'modules') return location.names; + const real = layout.canonical(location); + const names = [...directories].filter(directory => parentOf(directory) === real).map(nameOf); + if (real === projectRoot && Object.keys(lock?.roots ?? {}).length) names.push('node_modules'); + return names; + }, + // Files and subdirectories of a project directory, for the tsconfig.json include patterns. + entries(path) { + const real = resolve(path) ?? path; + const children = paths => [...paths].filter(item => parentOf(item) === real).map(nameOf); + return {files: children(files.keys()), directories: children(directories)}; + }, + }; +} + +async function readOptional(read, path) { + try { return await read(path); } + catch (error) { + if (missingFile(error)) return null; + throw error; + } +} + +/** + * Lists project directories through `list` (names, with a trailing slash for directories), recursively when asked. + * Returns the project-relative paths of the files found; the directories go into the snapshot. + */ +async function listProject(snapshot, list, directories, bounds, signal) { + const found = []; + let entries = 0; + const visit = async (directory, recursive) => { + signal?.throwIfAborted(); + let names; + try { names = await list(directory); } + catch (error) { + if (/Cannot list project directory/.test(error?.message)) return; + throw error; + } + snapshot.addDirectory([projectRoot, directory].filter(Boolean).join('/')); + for (const name of names) { + if (++entries > bounds.entries) + throw new Error(`wf check: the project directories hold more than ${bounds.entries} entries; narrow the include patterns of tsconfig.json`); + const path = [directory, name.replace(/\/$/, '')].filter(Boolean).join('/'); + if (!name.endsWith('/')) found.push(path); + else if (recursive && !skippedDirectories.has(name.slice(0, -1))) await visit(path, true); + } + }; + for (const [directory, recursive] of directories) await visit(directory, recursive); + return found; +} + +const projectRelative = path => path === projectRoot ? '' : path.startsWith(`${projectRoot}/`) ? path.slice(projectRoot.length + 1) : null; + +function configHost(ts, snapshot) { + return { + useCaseSensitiveFileNames: true, + readDirectory: (root, extensions, excludes, includes, depth) => + ts.matchFiles(root, extensions, excludes, includes, true, projectRoot, depth, snapshot.entries, snapshot.realpath), + fileExists: snapshot.fileExists, + readFile: snapshot.readFile, + directoryExists: snapshot.directoryExists, + getDirectories: snapshot.getDirectories, + realpath: snapshot.realpath, + }; +} + +// The configuration's own text is kept apart from the snapshot, which may have no room left for it. +function parseConfig(ts, snapshot, text) { + const source = ts.parseJsonText(configPath, text); + return ts.parseJsonSourceFileConfigFileContent(source, configHost(ts, snapshot), projectRoot, undefined, configPath); +} + +/** + * Loads into the snapshot the files that the previous reads missed and that exist: a project file read through the + * bridge, or a file of a locked package. Returns whether one was added. + */ +async function loadMisses(snapshot, {read, lock}, attempted) { + let added = false; + for (const path of [...snapshot.misses]) { + snapshot.misses.delete(path); + const location = snapshot.layout.locate(path); + if (!location || location.kind === 'modules') continue; + const real = snapshot.layout.canonical(location); + if (attempted.has(real)) continue; + attempted.add(real); + let bytes = null; + if (location.kind === 'project' && location.path) bytes = await readOptional(read, location.path); + else if (location.kind === 'package' && lock.packages[location.id].files.includes(location.path)) + bytes = await read(`${packageRoot}/${lock.packages[location.id].key}/${location.path}`); + if (bytes !== null && snapshot.add(real, bytes)) added = true; + if (snapshot.truncated) break; + } + return added; +} + +// The extensions of the project files TypeScript may resolve under these options. +function projectExtensions(options) { + const extensions = ['.ts', '.tsx', '.mts', '.cts']; + if (options.allowJs) extensions.push('.js', '.jsx', '.mjs', '.cjs'); + if (options.resolveJsonModule) extensions.push('.json'); + return extensions; +} + +// The project files of the snapshot: the sources TypeScript may resolve, and the package.json files that give the +// module format of the files under them. +const projectSource = options => path => + nameOf(`/${path}`) === 'package.json' || projectExtensions(options).some(extension => path.endsWith(extension)); + +/** + * Phase 1. `read(path)` and `list(directory)` take project-relative paths and return Promises; `typescript` is the id + * of the locked typescript package. Returns the snapshot and what phase 2 compiles: the root files, the options and + * the configuration diagnostics. + */ +export async function loadSnapshot(ts, {read, list, lock, typescript, entries = [], bounds = snapshotBounds, signal}) { + const snapshot = createSnapshot(lock, bounds); + const loadPackageFile = async (id, path) => { + signal?.throwIfAborted(); + const node = lock.packages[id]; + const real = snapshot.layout.packagePath(id, path); + // Past the bounds, the remaining files are only counted. + if (snapshot.truncated) return snapshot.skip(); + return snapshot.add(real, await read(`${packageRoot}/${node.key}/${path}`)); + }; + // The lib files of the compiler first, then the declarations of the whole locked graph. + const ordered = [typescript, ...Object.keys(lock.packages).filter(id => id !== typescript).sort()]; + for (const id of ordered) + for (const path of lock.packages[id].files) + if (path === 'package.json' || (id === typescript ? /^lib\/lib\..*\.d\.ts$/.test(path) : declaration.test(path))) + await loadPackageFile(id, path); + + const attempted = new Set(); + const configText = await readOptional(read, 'tsconfig.json'); + let options; + let rootNames; + let errors = []; + if (configText !== null) { + const configSource = decoder.decode(configText); + snapshot.add(configPath, configText); + attempted.add(configPath); + // The configuration and the files it extends, until no read misses. + let parsed = parseConfig(ts, snapshot, configSource); + for (let pass = 0; pass < maxConfigPasses && await loadMisses(snapshot, {read, lock}, attempted); ++pass) + parsed = parseConfig(ts, snapshot, configSource); + const directories = Object.entries(parsed.wildcardDirectories ?? {}) + .map(([directory, flags]) => [projectRelative(directory), (flags & 1) !== 0]) + .filter(([directory]) => directory !== null); + const listed = await listProject(snapshot, list, directories, bounds, signal); + const wanted = new Set([...listed.filter(projectSource(parsed.options)), + ...parsed.fileNames.map(projectRelative).filter(path => path !== null)]); + for (const path of wanted) await loadProjectFile(path); + await loadPackageScopes(wanted); + parsed = parseConfig(ts, snapshot, configSource); + ({options, fileNames: rootNames, errors} = parsed); + } else { + const converted = ts.convertCompilerOptionsFromJson(defaultCompilerOptions, projectRoot); + options = converted.options; + errors = converted.errors; + const sources = entries.filter(entry => projectExtensions(options).some(extension => entry.endsWith(extension))); + if (!sources.length) + throw new Error('wf check needs a tsconfig.json or TypeScript entries in webfront.project.json'); + // The directories of the entries, recursively: the files they import are found there. + const directories = [...new Set(sources.map(entry => entry.includes('/') ? entry.slice(0, entry.lastIndexOf('/')) : ''))]; + const listed = await listProject(snapshot, list, directories.map(directory => [directory, true]), bounds, signal); + const wanted = new Set([...sources, ...listed.filter(projectSource(options))]); + for (const path of wanted) await loadProjectFile(path); + await loadPackageScopes(wanted); + rootNames = sources.map(entry => `${projectRoot}/${entry}`); + } + snapshot.misses.clear(); + return {snapshot, rootNames, options, errors}; + + // The package.json files of the directories above the loaded files, up to the project root: they give the module + // format of those files, even outside the listed directories. + async function loadPackageScopes(paths) { + const scopes = new Set(); + for (const path of paths) + for (let directory = parentOf(`/${path}`); ; directory = parentOf(directory)) { + scopes.add(`${directory.slice(1)}/package.json`.replace(/^\//, '')); + if (!directory) break; + } + for (const path of scopes) if (!attempted.has(`${projectRoot}/${path}`)) await loadProjectFile(path); + } + + async function loadProjectFile(path) { + signal?.throwIfAborted(); + const real = `${projectRoot}/${path}`; + if (attempted.has(real)) return; + attempted.add(real); + if (snapshot.truncated) return snapshot.skip(); + const bytes = await readOptional(read, path); + if (bytes !== null) snapshot.add(real, bytes); + } +} + +/** The CompilerHost of phase 2: synchronous, over the snapshot only; it writes nothing. */ +export function createCompilerHost(ts, snapshot, typescript) { + const libLocation = snapshot.layout.packagePath(typescript, 'lib'); + return { + getSourceFile: (fileName, languageVersionOrOptions) => { + const text = snapshot.readFile(fileName); + return text === undefined ? undefined : ts.createSourceFile(fileName, text, languageVersionOrOptions); + }, + getDefaultLibLocation: () => libLocation, + getDefaultLibFileName: options => `${libLocation}/${ts.getDefaultLibFileName(options)}`, + writeFile: () => {}, + getCurrentDirectory: () => projectRoot, + getCanonicalFileName: fileName => fileName, + useCaseSensitiveFileNames: () => true, + getNewLine: () => '\n', + fileExists: snapshot.fileExists, + readFile: snapshot.readFile, + directoryExists: snapshot.directoryExists, + getDirectories: snapshot.getDirectories, + realpath: snapshot.realpath, + }; +} + +/** Phase 2: the program over the snapshot and all its diagnostics before emit, configuration ones first. */ +export function checkProgram(ts, {snapshot, rootNames, options, errors}, typescript) { + const host = createCompilerHost(ts, snapshot, typescript); + const program = ts.createProgram({rootNames, options: {...options, ...noEmit}, host}); + return {program, diagnostics: [...errors, ...ts.getPreEmitDiagnostics(program)]}; +} + +/** A path as the terminal shows it: project-relative, or / inside a package. */ +export function displayPath(snapshot, path) { + const relative = projectRelative(path); + if (relative !== null) return relative; + const location = snapshot.layout.locate(path); + return location?.kind === 'package' ? `${location.id}/${location.path}` : path; +} + +/** One line per diagnostic, like tsc without --pretty: file(line,column): error TScode: message. */ +export function formatDiagnostic(ts, snapshot, diagnostic) { + const category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); + if (!diagnostic.file) return `${category} TS${diagnostic.code}: ${message}`; + const {line, character} = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start ?? 0); + return `${displayPath(snapshot, diagnostic.file.fileName)}(${line + 1},${character + 1}): ${category} TS${diagnostic.code}: ${message}`; +} + +/** The terminal lines and exit code of a check: 1 for a type error or a truncated snapshot. */ +export function checkReport(ts, snapshot, {program, diagnostics}, bounds = snapshotBounds) { + const lines = diagnostics.map(diagnostic => formatDiagnostic(ts, snapshot, diagnostic)); + const errors = diagnostics.filter(diagnostic => diagnostic.category === ts.DiagnosticCategory.Error); + if (snapshot.truncated) + lines.push(`error: the snapshot reached its bounds (${bounds.files} files, ${bounds.bytes / 1048576} MiB): ` + + `${snapshot.skipped} files were not loaded and are treated as missing`); + const files = new Set(errors.map(diagnostic => diagnostic.file?.fileName ?? '')); + const projectFiles = program.getSourceFiles().filter(file => projectRelative(file.fileName) !== null).length; + if (errors.length) lines.push(`Found ${errors.length} error${errors.length === 1 ? '' : 's'} in ${files.size} file${files.size === 1 ? '' : 's'}.`); + else if (!snapshot.truncated) lines.push(`No type errors in ${projectFiles} project file${projectFiles === 1 ? '' : 's'} (TypeScript ${ts.version}).`); + return {lines, code: errors.length || snapshot.truncated ? 1 : 0}; +} diff --git a/js/developer/environment/typecheck-worker.mjs b/js/developer/environment/typecheck-worker.mjs new file mode 100644 index 00000000..35d6b7d9 --- /dev/null +++ b/js/developer/environment/typecheck-worker.mjs @@ -0,0 +1,60 @@ +// The Worker of wf check: loads the locked TypeScript, then the snapshot through the page (phase 1, asynchronous), +// then compiles over it (phase 2, synchronous). The page answers only reads and listings: nothing is written. +import {packageRoot} from './paths.mjs'; +import {typescriptModule, loadSnapshot, checkProgram, checkReport, snapshotBounds} from './typecheck-snapshot.mjs'; + +const pending = new Map(); +let nextId = 0; +const controller = new AbortController(); +const decoder = new TextDecoder(); + +function call(operation, ...args) { + return new Promise((resolve, reject) => { + const id = ++nextId; + pending.set(id, {resolve, reject}); + self.postMessage({type: 'call', id, operation, args}); + }); +} + +const print = (text, stream = 'out') => self.postMessage({type: 'console', stream, text}); + +async function loadTypeScript(node) { + const source = decoder.decode(await call('read', `${packageRoot}/${node.key}/lib/typescript.js`)); + const url = URL.createObjectURL(new Blob([typescriptModule(source)], {type: 'text/javascript'})); + let ts; + try { ts = (await import(url)).default; } + finally { URL.revokeObjectURL(url); } + if (ts?.version !== node.version || typeof ts.createProgram !== 'function' || typeof ts.matchFiles !== 'function') + throw new Error(`typescript@${node.version}: lib/typescript.js does not provide the compiler API wf check uses`); + return ts; +} + +async function run({lock, typescript, entries, bounds: given}) { + const bounds = given ?? snapshotBounds; + const ts = await loadTypeScript(lock.packages[typescript]); + const loaded = await loadSnapshot(ts, {read: path => call('read', path), list: directory => call('list', directory), + lock, typescript, entries, bounds, signal: controller.signal}); + controller.signal.throwIfAborted(); + const {snapshot, rootNames} = loaded; + print(`Checking ${rootNames.length} root file${rootNames.length === 1 ? '' : 's'} with TypeScript ${ts.version} ` + + `(snapshot: ${snapshot.files.size} files, ${(snapshot.bytes / 1048576).toFixed(1)} MiB)`); + // Synchronous from here: Ctrl+C can only terminate the Worker. + const {lines, code} = checkReport(ts, snapshot, checkProgram(ts, loaded, typescript), bounds); + for (const line of lines) print(line, code ? 'err' : 'out'); + self.postMessage({type: 'exit', code}); +} + +function answer({id, error, value}) { + const request = pending.get(id); + if (!request) return; + pending.delete(id); + if (error === undefined) request.resolve(value); + else request.reject(new Error(error)); +} + +self.onmessage = ({data}) => { + if (data.type === 'reply') return answer(data); + if (data.type === 'abort') return controller.abort(new Error('Interrupted')); + if (data.type !== 'run') return; + run(data).catch(error => self.postMessage({type: 'error', error: error.message})); +}; diff --git a/js/developer/environment/typecheck.mjs b/js/developer/environment/typecheck.mjs new file mode 100644 index 00000000..a8ebd3ae --- /dev/null +++ b/js/developer/environment/typecheck.mjs @@ -0,0 +1,51 @@ +// wf check, page side: the locked typescript must be a supported version; the Worker reads the project and the +// package cache through a host that answers only reads and listings, under the stop mechanism of wf run. +import semver from 'semver'; +import {call, readProject} from './io.mjs'; +import {lockedPackage, defaultTimeout, timeoutBounds} from './scripts.mjs'; +import {safePackagePath} from './paths.mjs'; + +/** The typescript versions wf check runs: those whose lib/typescript.js provides the compiler API. */ +export const supportedTypeScript = '>=5.0.0 <7.0.0'; +const decoder = new TextDecoder(); + +/** The locked typescript package wf check runs, as [id, node]; a missing or unsupported one is refused. */ +export function typescriptPackage(lock) { + const locked = lockedPackage(lock, 'typescript'); + if (!locked) throw new Error('wf check needs the typescript package: run wf install typescript@6'); + const [id, node] = locked; + if (!semver.satisfies(node.version, supportedTypeScript)) { + const native = semver.major(node.version) >= 7 ? ', whose compiler is a native program without the JavaScript API' : ''; + throw new Error(`wf check supports typescript 5.x and 6.x (${supportedTypeScript}), not ${id}${native}: run wf install typescript@6`); + } + if (!node.files.includes('lib/typescript.js')) throw new Error(`${id} has no lib/typescript.js`); + return locked; +} + +// wf check [--timeout ] +export function parseCheckOptions(args) { + if (!args.length) return {timeout: defaultTimeout}; + const timeout = Number(args[1]); + if (args[0] !== '--timeout' || args.length !== 2) throw new Error('Usage: wf check [--timeout ]'); + if (!Number.isInteger(timeout) || timeout < timeoutBounds[0] || timeout > timeoutBounds[1]) + throw new Error(`--timeout expects whole seconds from ${timeoutBounds[0]} to ${timeoutBounds[1]}`); + return {timeout}; +} + +/** The page side of a check: project reads and listings only, refused once stopped. */ +export function checkHost(bridge) { + let stopped = false; + const operations = { + read: path => readProject(bridge, safePackagePath(path)), + list: async (directory = '') => JSON.parse(decoder.decode(await call(bridge, 'list', directory && safePackagePath(directory)))), + }; + return { + publications: [], + async handle({operation, args}) { + if (stopped) throw new Error('The check was stopped'); + if (!Object.hasOwn(operations, operation)) throw new Error(`Unknown check operation: ${operation}`); + return operations[operation](...args); + }, + async stop() { stopped = true; }, + }; +} diff --git a/js/developer/scripts/build.mjs b/js/developer/scripts/build.mjs new file mode 100644 index 00000000..597959d3 --- /dev/null +++ b/js/developer/scripts/build.mjs @@ -0,0 +1,117 @@ +// Builds the developer environment, its starters and the pinned header from the sources of this repository, with wf: +// +// wf run js/developer/scripts/build.mjs [] [--refresh-bootstrap] +// +// The compiler is the locked esbuild-wasm of webfront.project.json, run in the script's Worker; the files it reads are +// the project's and the locked packages'. With --refresh-bootstrap, the checked-in bootstrap bundles, their checksums and +// the pinned header are regenerated too; the core headers that embed the bundles come from the CMake target +// webfront-embedded-assets (js/core/EmbedAsset.cmake). +import * as esbuild from 'esbuild-wasm'; +import {virtualPlugin} from '../environment/bundler.mjs'; +import {compress} from '../environment/embed.mjs'; +import {packageRoot} from '../environment/paths.mjs'; +import {tar} from '../tools/archive.mjs'; +import {baseUrl, versionPath, bootstrapHeader, sriOf} from '../tools/distribution.mjs'; + +const manifestPath = 'js/developer/webfront.project.json'; +const lockPath = 'js/developer/webfront-packages.lock.json'; +const encoder = new TextEncoder(); +const hexOf = bytes => Array.from(new Uint8Array(bytes), byte => byte.toString(16).padStart(2, '0')).join(''); + +/** The project path of a file of a locked package: the root of that name. */ +export function lockedFile(lock, name, file) { + const node = lock.packages[lock.roots[name]?.id]; + if (!node) throw new Error(`${name} is not installed: run wf install`); + return `${packageRoot}/${node.key}/${file}`; +} + +export default async function (context) { + const {project} = context; + const flags = context.args.filter(argument => argument.startsWith('--')); + const refresh = flags.includes('--refresh-bootstrap'); + const unknown = flags.find(flag => flag !== '--refresh-bootstrap'); + if (unknown) throw new Error(`Unknown option ${unknown}`); + const output = context.args.find(argument => !argument.startsWith('--')) ?? 'build-developer-environment'; + const lock = JSON.parse(await project.readText(lockPath)); + const readProject = path => project.read(path); + + await esbuild.initialize({wasmModule: await WebAssembly.compile(await project.read(lockedFile(lock, 'esbuild-wasm', 'esbuild.wasm'))), worker: false}); + const bundle = async entry => { + const result = await esbuild.build({entryPoints: [entry], bundle: true, format: 'esm', platform: 'browser', target: 'es2020', + minify: true, legalComments: 'inline', write: false, outfile: '/output/bundle.mjs', + plugins: [virtualPlugin(lock, undefined, readProject)]}); + return result.outputFiles[0].contents; + }; + const written = new Map(); + const write = async (path, data) => { + const bytes = typeof data === 'string' ? encoder.encode(data) : data; + await project.write(path, bytes); + written.set(path, bytes); + return bytes; + }; + const read = async path => written.get(path) ?? await project.read(path); + + const files = new Map(); + for (const name of ['runtime', 'compiler', 'script-worker', 'typecheck-worker']) + files.set(`${name}.mjs`, await write(`${output}/${name}.mjs`, await bundle(`js/developer/environment/${name}.mjs`))); + files.set('esbuild.wasm', await write(`${output}/esbuild.wasm`, await project.read(lockedFile(lock, 'esbuild-wasm', 'esbuild.wasm')))); + files.set('xterm.css', await write(`${output}/xterm.css`, await project.read(lockedFile(lock, '@xterm/xterm', 'css/xterm.css')))); + + const distribution = JSON.parse(await project.readText('js/developer/tools/distribution.json')); + const version = distribution.version; + const publicBase = baseUrl(distribution.baseUrl); + versionPath(version); + const dependencies = JSON.parse(await project.readText(manifestPath)).dependencies; + const licenses = [ + ['esbuild-wasm', lockedFile(lock, 'esbuild-wasm', 'LICENSE.md')], + ['semver', lockedFile(lock, 'semver', 'LICENSE')], + ['xterm', lockedFile(lock, '@xterm/xterm', 'LICENSE')], + ['xterm Fit addon', lockedFile(lock, '@xterm/addon-fit', 'LICENSE')], + ['fflate', lockedFile(lock, 'fflate', 'LICENSE')], + ]; + const notices = []; + for (const [name, path] of licenses) notices.push(`${name}\n${await project.readText(path)}`); + files.set('LICENSES.txt', await write(`${output}/LICENSES.txt`, notices.join('\n\n'))); + + // The starter is pinned by the environment's own trusted archive, not by unverified remote metadata. + const starters = {}; + for (const [name, provider] of [['life', 'LifeUI']]) { + const starterFiles = new Map(); + for (const file of ['main.tsx', 'style.css']) + starterFiles.set(`package/${file}`, await project.read(`examples/life/ui/${file}`)); + 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', encoder.encode(JSON.stringify(recipe, null, 2) + '\n')); + starterFiles.set('package/package.json', encoder.encode(JSON.stringify({name: `@webfront/${name}-starter`, version, + private: true, webfront: {kind: 'starter', entry: 'main.tsx'}}, null, 2) + '\n')); + const starterBytes = compress(tar(starterFiles)); + const archive = `${name}-starter.tgz`; + await write(`${output}/${archive}`, starterBytes); + starters[name] = {archive, integrity: await sriOf(starterBytes)}; + } + files.set('environment.json', await write(`${output}/environment.json`, JSON.stringify({protocol: 1, api: 1, version, entry: 'runtime.mjs', + compiler: `esbuild-wasm@${dependencies['esbuild-wasm']}`, semver: dependencies.semver, starters}, null, 2) + '\n')); + files.set('package.json', await write(`${output}/package.json`, JSON.stringify({name: '@webfront/developer-environment', version, + description: 'Browser-powered WebFront developer environment', type: 'module', + files: ['runtime.mjs', 'compiler.mjs', 'script-worker.mjs', 'typecheck-worker.mjs', 'esbuild.wasm', 'xterm.css', 'environment.json', 'LICENSES.txt']}, null, 2) + '\n')); + + const bytes = compress(tar(new Map([...files].map(([name, content]) => [`package/${name}`, content])))); + await write(`${output}/environment.tgz`, bytes); + const integrity = await sriOf(bytes); + await write(`${output}/provision.json`, JSON.stringify({format: 1, version, environment: './environment.tgz', integrity, starters}, null, 2) + '\n'); + const header = bootstrapHeader(version, publicBase, integrity); + await write(`${output}/DeveloperReleaseData.hpp`, header); + + if (refresh) { + await write('js/core/bootstrap/bootstrap.bundle.mjs', await bundle('js/developer/environment/bootstrap-entry.mjs')); + await write('js/developer/environment/packages.bundle.mjs', await bundle('js/developer/environment/packages-entry.mjs')); + await write('js/developer/environment/PACKAGES-LICENSE.txt', await project.read(lockedFile(lock, 'semver', 'LICENSE'))); + await write('include/webfront/system/DeveloperReleaseData.hpp', header); + const inputs = {}; + for (const path of JSON.parse(await project.readText('js/developer/tools/bundle-inputs.json'))) + inputs[path] = hexOf(await crypto.subtle.digest('SHA-256', await read(path))); + await write('js/developer/environment/bundles.json', JSON.stringify(inputs, null, 2) + '\n'); + } + context.console.log(`Environment: ${output}/environment.tgz\nIntegrity: ${integrity}\nStarters: ${Object.keys(starters).join(', ')}`); +} diff --git a/js/developer/scripts/pin.mjs b/js/developer/scripts/pin.mjs new file mode 100644 index 00000000..afdce187 --- /dev/null +++ b/js/developer/scripts/pin.mjs @@ -0,0 +1,25 @@ +// Checks include/webfront/system/DeveloperReleaseData.hpp against the published distribution it pins, for sources that +// build a newer version, with wf: +// +// wf run js/developer/scripts/pin.mjs +// +// The header must be exactly the one generated for its version, and the archive at its URL must have its integrity. +import {bootstrapHeader, sriOf} from '../tools/distribution.mjs'; + +export default async function (context) { + const {project} = context; + const header = await project.readText('include/webfront/system/DeveloperReleaseData.hpp'); + const field = name => header.match(new RegExp(`\\b${name}\\{"([^"]*)"\\}`))?.[1] ?? ''; + const version = field('version'); + const integrity = field('integrity'); + // The base is the one the pinned URL was published under, not distribution.json's: the sources may have moved on. + const url = field('environment'); + const marker = `developer/${version}/environment.tgz`; + if (!url.endsWith('/' + marker) || header !== bootstrapHeader(version, url.slice(0, -marker.length), integrity)) + throw new Error(`DeveloperReleaseData.hpp is not the header generated for the published ${version}`); + const response = await context.fetch(url, {signal: context.signal}); + if (!response.ok) throw new Error(`The pinned environment ${url} is not published (${response.status})`); + if (await sriOf(new Uint8Array(await response.arrayBuffer())) !== integrity) + throw new Error(`The published ${url} does not have the pinned integrity`); + context.console.log(`DeveloperReleaseData.hpp pins the published ${version}.`); +} diff --git a/js/developer/scripts/site.mjs b/js/developer/scripts/site.mjs new file mode 100644 index 00000000..9b026280 --- /dev/null +++ b/js/developer/scripts/site.mjs @@ -0,0 +1,72 @@ +// Stages a built distribution into the static GitHub Pages site, keeping every published version, with wf: +// +// wf run js/developer/scripts/site.mjs +// +// A published version is immutable: staging may only repeat identical bytes. Nothing is modified before every byte of +// an existing version has been compared. +import {versionName, versionPath, distributionFiles, sriOf} from '../tools/distribution.mjs'; + +const same = (a, b) => a.length === b.length && a.every((byte, index) => byte === b[index]); + +async function readDistribution(project, distribution) { + const manifest = JSON.parse(await project.readText(`${distribution}/provision.json`)); + const input = new Map(); + for (const name of distributionFiles(manifest)) input.set(name, await project.read(`${distribution}/${name}`)); + const archives = [[input.get('environment.tgz'), manifest.integrity], + ...Object.values(manifest.starters).map(starter => [input.get(starter.archive), starter.integrity])]; + for (const [bytes, integrity] of archives) + if (await sriOf(bytes) !== integrity) throw new Error('Distribution archive checksum mismatch'); + return {manifest, input}; +} + +const entries = async (project, directory) => (await project.list(directory)).map(name => name.replace(/\/$/, '')); + +// A version is published when its directory is listed under the site's developer directory. A missing directory cannot be +// listed, so each level is looked up in its parent (the site itself, in the project root or in its parent directory). +async function published(project, site, version) { + const slash = site.lastIndexOf('/'); + const [parent, name] = slash < 0 ? ['', site] : [site.slice(0, slash), site.slice(slash + 1)]; + if (!(await entries(project, parent)).includes(name)) return false; + if (!(await entries(project, site)).includes('developer')) return false; + return (await entries(project, `${site}/developer`)).includes(version); +} + +// A published version is immutable: reruns may only repeat identical bytes. +async function publishVersion(project, input, site, version) { + const destination = `${site}/developer/${version}`; + if (!await published(project, site, version)) { + for (const [name, bytes] of input) await project.write(`${destination}/${name}`, bytes); + return; + } + // Check every byte before modifying anything. + for (const [name, bytes] of input) { + const existing = await project.read(`${destination}/${name}`).catch(() => null); + if (!existing || !same(bytes, existing)) + throw new Error(`Published version ${version} differs; increment the distribution version`); + } +} + +async function versionRow(project, site, version) { + const manifest = JSON.parse(await project.readText(`${site}/${versionPath(version)}provision.json`)); + const links = distributionFiles(manifest).map(name => `${name}`).join(' · '); + return `
  • ${version}: ${links}
  • `; +} + +async function writeIndex(project, site) { + const versions = (await entries(project, `${site}/developer`)).filter(name => versionName.test(name)).sort(); + await project.write(`${site}/.nojekyll`, ''); + const rows = []; + for (const version of versions) rows.push(await versionRow(project, site, version)); + await project.write(`${site}/index.html`, `\nWebFront developer packages

    WebFront developer packages

    Use a version-pinned bootstrap header and SHA-512. React and its dependencies are downloaded separately from npm.

      ${rows.join('')}
    \n`); +} + +export default async function (context) { + const [distribution, site] = context.args; + if (!distribution || !site || context.args.length !== 2) throw new Error('Usage: wf run site '); + const {project} = context; + const {manifest, input} = await readDistribution(project, distribution); + const relative = versionPath(manifest.version); + await publishVersion(project, input, site, manifest.version); + await writeIndex(project, site); + context.console.log(`Staged developer packages ${manifest.version} in ${site}/${relative}`); +} diff --git a/js/developer/tools/PUBLISHING.md b/js/developer/tools/PUBLISHING.md new file mode 100644 index 00000000..5025387f --- /dev/null +++ b/js/developer/tools/PUBLISHING.md @@ -0,0 +1,128 @@ +# Publishing the developer packages + +The version and canonical HTTPS base URL are in `distribution.json`. The environment and the Life starter +are published under `developer//`. React, React DOM and scheduler stay on npm; this site +hosts only WebFront's development environment, its pinned Life starter and provisioning metadata. +The package names in their manifests are identifiers, not a requirement to own or publish npm scopes. + +The environment builds itself: the pinned bootstrap environment (`cmake/WebFrontBootstrap.cmake`) runs the scripts of +`js/developer/scripts/` on the sources of this repository, which is a `wf` project (`js/developer/webfront.project.json` and its +lock). Building, reviewing and publishing need a C++23 compiler, CMake, the engine of the driver's frontend and `gh` +and `jq` for the host operations. + +## Build and review + +The driver `webfront-wf` runs one `wf` command without interaction on a project (here, the repository). Any frontend +works; WebKitGTK on Linux is the one CI uses. + +```sh +cmake -S . -B build-driver -DCMAKE_BUILD_TYPE=Release -DENABLE_TESTING=ON \ + -DWEBFRONT_EMBED_WEBKITGTK=ON -DWEBFRONT_WEBTEST_FRONTEND=WebKitGTK +cmake --build build-driver --target webfront-wf +wf() { xvfb-run -a build-driver/test/web/webfront-wf --project "$PWD" --manifest-dir js/developer -- "$@"; } + +wf restore # the locked build dependencies, verified against their SHA-512 +wf run build build-distribution # environment, starters, provision.json, pinned header +wf run build build-distribution-repeat # must be the same bytes +cmp build-distribution/environment.tgz build-distribution-repeat/environment.tgz +``` + +`wf run build --refresh-bootstrap` also rebuilds the checked-in bootstrap bundles +(`js/core/bootstrap/bootstrap.bundle.mjs`, `js/developer/environment/packages.bundle.mjs`), their checksums +(`js/developer/environment/bundles.json`, over the inputs of `js/developer/tools/bundle-inputs.json`) and the pinned +header. The core headers that embed the bootstrap bundle (`DeveloperIndexHtmlData.hpp`, `DeveloperBootstrapData.hpp`) are +rendered from their sources by CMake, like the others: `cmake --build --target webfront-embedded-assets`. A script may only write where `permissions.publish` +of `js/developer/webfront.project.json` allows: the `build-*` directories and these checked-in outputs. + +The output of a script reaches the terminal of an environment 0.6.1 or later; with 0.6.0 the command prints +only its summary. The integrity of an archive is `openssl dgst -sha512 -binary build-distribution/environment.tgz | base64 -w0`, +prefixed by `sha512-`. + +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. + +The static branch preserves every version. Republishing identical bytes is allowed; replacing a +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, `wf run pin` 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 `wf run build build-distribution --refresh-bootstrap` and commit the new header (and the + checksums of `bundles.json`, which cover it). +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. + +Once the new version is published, `cmake/WebFrontBootstrap.cmake` may pin it as the bootstrap environment of the +tests, in a pull request of its own. + +## One-time Pages configuration + +The repository's Pages source must be the **gh-pages branch, root directory**, with branch-based +builds (`build_type: legacy`). The branch contains only generated distribution files and `.nojekyll`. +An existing unrelated Pages site must not be overwritten. + +For initial setup, a repository maintainer first commits/pushes the generated site to a new +`gh-pages` branch, then enables Settings → Pages → Deploy from a branch → gh-pages → `/`. +The equivalent API call, after that branch exists, is: + +```sh +gh api --method POST repos/ambroise-leclerc/WebFront/pages \ + -f build_type=legacy -f 'source[branch]=gh-pages' -f 'source[path]=/' +``` + +The publication workflow uses repository tokens with `contents: write` and `pages: write` to update +that branch without force-pushing. It explicitly requests a Pages build, because token-driven +branch pushes do not trigger one automatically. It refuses to change an existing Pages source. +Initial Pages enablement is deliberately a maintainer operation, not a side effect of every build. + +## Automated publication + +The **Developer packages** workflow builds packages on relevant pushes/PRs and retains them as an +artifact. Its `wf-package` job removes every JavaScript runtime from the runner, builds the driver, restores the locked +dependencies, builds the distribution twice and compares the repeat build and the checked-in bootstrap header before +permitting publication; it also runs the specs of the environment with `wf test`. +It publishes only on a `developer-v` tag or an explicit workflow dispatch with `publish=true`. The `publish` job +runs the same way: `wf run site` stages the new version into a checkout of `gh-pages` and refuses to +change a published one, `pages.sh` checks the configured source and requests the build, and `archive-release.sh` +archives the files in a prerelease. +Use the dedicated tag `developer-v` matching `distribution.json`; the C++ library's `v*` releases remain separate. + +```sh +version=$(jq -r .version js/developer/tools/distribution.json) +git tag "developer-v$version" +git push origin "developer-v$version" +``` + +Alternatively, once the workflow exists on the default branch, run it manually for a reviewed ref. +Tagged publication also archives the same files in a dedicated GitHub prerelease. Existing release +assets are verified on retry; they are never replaced. Downloads used by the bootstrap come from +Pages, whose cross-origin behavior is checked independently of Release asset redirects. + +## Validate the deployed files + +Check the canonical Pages URL, its `Access-Control-Allow-Origin` response and the archive checksum. +Then run the optional live smoke test (the ordinary CTest suite remains entirely offline). Its fixtures (the local +registry and the test pages) are the ones that the CTest case `DeveloperFixtures` assembles in the build directory: + +```sh +ctest --test-dir build-native -R '^DeveloperFixtures$' --output-on-failure +./build-native/test/web/developer_integration \ + "$PWD/build-native/test/web/developer-fixtures" "$PWD/build-native/test/web/public-generated" --public +``` + +This mode downloads the pinned environment and the starter from Pages, fetches exact React/React DOM +versions and scheduler from npm, executes esbuild/WASM, creates the in-window Life preview and generates +the application provider. A mismatch, download failure, browser error or failed assertion returns +nonzero. Keep the issue open until this real-engine check and the normal offline regression suite pass. diff --git a/js/developer/tools/RELEASE_NOTES.md b/js/developer/tools/RELEASE_NOTES.md new file mode 100644 index 00000000..2e526ca8 --- /dev/null +++ b/js/developer/tools/RELEASE_NOTES.md @@ -0,0 +1,13 @@ +Browser-powered WebFront developer environment with Game of Life starter (the PI starter of earlier versions is retired), versioned separately from the C++ library. + +Version 0.3.0 migrates the Life starter to packed Uint8Array grids: 128 bytes per generation with direct C++ bitset registration. It requires the bridge support introduced in #289. The interface retains editable patterns, playback, reset and single stepping. Version 0.3.1 makes `wf install` honor the installed lock: versions it records are kept and their archives must still match the recorded integrity. Published versions 0.1.0 to 0.3.0 remain available without modification. + +Download through the version-pinned GitHub Pages URLs in the bootstrap configuration. SHA-512 is verified before executing the environment or creating a starter. React, React DOM and scheduler remain on npm; application developers install no JavaScript tooling. Applications using the starter can generate their own compressed header-only resources for an offline native executable. + +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 server-side runtime 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. + +Version 0.6.0 (published as `developer-v0.6.0`) adds `wf test` (the project's Jasmine, obtained by `wf install jasmine-core`, runs the specs of `test.specs` in the browser, with a structured report and a non-interactive entry), `wf build` and incremental `wf dev`, with bounded input polling, diagnostics in the preview and Ctrl+C cancellation. A publication whose commit has completed is displayed before cancellation ends the command. `DeveloperReleaseData.hpp` and the bootstrap environment of the tests pin it. `environment.json` now declares `api` (the `webfront.developer.*` version, 1); an environment that predates the field reads as 1. diff --git a/js/developer/tools/archive-release.sh b/js/developer/tools/archive-release.sh new file mode 100755 index 00000000..84614d85 --- /dev/null +++ b/js/developer/tools/archive-release.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# Dedicated prereleases: retries verify existing assets, never replace an existing release. +# archive-release.sh > +# Needs the gh CLI (GH_TOKEN), jq and GITHUB_REPOSITORY; the tag must exist on the remote. +set -euo pipefail + +tag=${1:?Usage: archive-release.sh } +distribution=${2:?Usage: archive-release.sh } +root=$(cd "$(dirname "$0")/../../.." && pwd) +version=$(jq -r .version "$root/js/developer/tools/distribution.json") +if [ "$tag" != "developer-v$version" ] || ! [[ "${GITHUB_REPOSITORY:-}" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]]; then + echo "Expected the dedicated distribution tag and GITHUB_REPOSITORY" >&2 + exit 1 +fi + +# The published files: the environment, each starter, the provisioning data and the pinned header. jq must succeed before +# anything is sent to GitHub: a status inside a process substitution would be lost. +if ! listed=$(jq -er '["environment.tgz"] + [.starters[].archive] + ["provision.json", "DeveloperReleaseData.hpp"] | .[]' \ + "$distribution/provision.json"); then + echo "Cannot read the starters of $distribution/provision.json" >&2 + exit 1 +fi +mapfile -t files <<< "$listed" +[ "${#files[@]}" -ge 4 ] || { echo "The distribution lists too few files" >&2; exit 1; } +for name in "${files[@]}"; do + [ -f "$distribution/$name" ] || { echo "Missing distribution file $name" >&2; exit 1; } +done + +errors=$(mktemp) +directory=$(mktemp -d) +trap 'rm -rf "$errors" "$directory"' EXIT +existing=false +if gh api "repos/$GITHUB_REPOSITORY/releases/tags/$tag" > /dev/null 2> "$errors"; then + existing=true +elif ! grep -q '(HTTP 404)' "$errors"; then + cat "$errors" >&2 + exit 1 +fi + +if [ "$existing" = true ]; then + patterns=() + for name in "${files[@]}"; do patterns+=(--pattern "$name"); done + gh release download "$tag" --repo "$GITHUB_REPOSITORY" --dir "$directory" "${patterns[@]}" + for name in "${files[@]}"; do + cmp -s "$directory/$name" "$distribution/$name" || { echo "Existing release asset $name differs; choose a new version" >&2; exit 1; } + done + echo "Existing release assets match the distribution" +else + paths=() + for name in "${files[@]}"; do paths+=("$distribution/$name"); done + gh release create "$tag" --repo "$GITHUB_REPOSITORY" --verify-tag --prerelease \ + --title "WebFront developer packages $version" --notes-file "$root/js/developer/tools/RELEASE_NOTES.md" "${paths[@]}" +fi diff --git a/tools/developer/archive.mjs b/js/developer/tools/archive.mjs similarity index 100% rename from tools/developer/archive.mjs rename to js/developer/tools/archive.mjs diff --git a/js/developer/tools/bundle-inputs.json b/js/developer/tools/bundle-inputs.json new file mode 100644 index 00000000..d9d4cd2c --- /dev/null +++ b/js/developer/tools/bundle-inputs.json @@ -0,0 +1,48 @@ +[ + "js/developer/environment/manifest.mjs", + "js/developer/environment/project.mjs", + "js/developer/environment/installer.mjs", + "js/developer/environment/restore.mjs", + "js/developer/environment/cache.mjs", + "js/developer/environment/scripts.mjs", + "js/developer/environment/script-worker.mjs", + "js/developer/environment/permissions.mjs", + "js/developer/environment/typecheck.mjs", + "js/developer/environment/typecheck-snapshot.mjs", + "js/developer/environment/typecheck-worker.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/development.mjs", + "js/developer/environment/testing.mjs", + "js/developer/environment/terminal.mjs", + "js/developer/environment/tarball.mjs", + "js/developer/environment/commands.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", + "examples/life/ui/main.tsx", + "examples/life/ui/style.css", + "js/developer/tools/distribution.json", + "js/developer/tools/archive.mjs", + "js/developer/tools/distribution.mjs", + "js/developer/scripts/build.mjs", + "js/developer/webfront.project.json", + "js/core/bootstrap/bootstrap.bundle.mjs", + "js/developer/environment/packages.bundle.mjs", + "include/webfront/system/DeveloperReleaseData.hpp" +] diff --git a/tools/developer/distribution.json b/js/developer/tools/distribution.json similarity index 74% rename from tools/developer/distribution.json rename to js/developer/tools/distribution.json index 82b7f6dd..48ac84ab 100644 --- a/tools/developer/distribution.json +++ b/js/developer/tools/distribution.json @@ -1,4 +1,4 @@ { - "version": "0.4.0", + "version": "0.6.3", "baseUrl": "https://ambroise-leclerc.github.io/WebFront/" } diff --git a/js/developer/tools/distribution.mjs b/js/developer/tools/distribution.mjs new file mode 100644 index 00000000..716bfa81 --- /dev/null +++ b/js/developer/tools/distribution.mjs @@ -0,0 +1,53 @@ +// The pure rules of the developer distribution (versions, URLs, the pinned header, the published files). They use +// no host API: the wf scripts of js/developer/scripts and the Node maintenance tools share them. + +function isHttpsDirectory(url) { + if (url.protocol !== 'https:') return false; + if (url.username || url.password) return false; + return !url.search && !url.hash; +} + +export function baseUrl(value) { + const url = new URL(value); + if (!isHttpsDirectory(url)) throw new Error('Distribution base URL must be an HTTPS directory URL'); + if (!url.pathname.endsWith('/')) url.pathname += '/'; + return url.href; +} + +export const versionName = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/; + +export function versionPath(version) { + if (!versionName.test(version)) throw new Error('Invalid distribution version'); + return `developer/${version}/`; +} + +export function bootstrapHeader(version, base, integrity) { + if (!/^sha512-[A-Za-z0-9+/]{86}==$/.test(integrity)) throw new Error('Invalid distribution SHA-512'); + const url = new URL(versionPath(version) + 'environment.tgz', baseUrl(base)); + return `#pragma once + +// Pinned developer distribution. Regenerate with wf run build --refresh-bootstrap. +#include + +namespace webfront::developer::release { +inline constexpr std::string_view version{${JSON.stringify(version)}}; +inline constexpr std::string_view environment{${JSON.stringify(url.href)}}; +inline constexpr std::string_view integrity{${JSON.stringify(integrity)}}; +} // namespace webfront::developer::release +`; +} + +const validArchive = name => typeof name === 'string' && /^[a-z0-9-]+-starter\.tgz$/.test(name); + +// A manifest may add starters without changing the publication machinery. +export function distributionFiles(manifest) { + const archives = Object.values(manifest.starters ?? {}).map(starter => starter.archive); + if (archives.length === 0 || !archives.every(validArchive)) throw new Error('Invalid distribution starter archives'); + if (new Set(archives).size !== archives.length) throw new Error('Invalid distribution starter archives'); + return ['environment.tgz', ...archives, 'provision.json', 'DeveloperReleaseData.hpp']; +} + +/** The SRI value of the SHA-512 of some bytes, with the Web Crypto API (a Worker, a page or Node). */ +export async function sriOf(bytes) { + return 'sha512-' + btoa(String.fromCharCode(...new Uint8Array(await crypto.subtle.digest('SHA-512', bytes)))); +} diff --git a/js/developer/tools/pages.sh b/js/developer/tools/pages.sh new file mode 100755 index 00000000..3c0b4a2b --- /dev/null +++ b/js/developer/tools/pages.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# A token-driven branch push does not trigger Pages automatically: request the build explicitly. +# With --check, only verify the configured Pages source (before anything is pushed to gh-pages). +# Needs the gh CLI (GH_TOKEN) and GITHUB_REPOSITORY; no other tool. +set -euo pipefail + +[[ "${GITHUB_REPOSITORY:-}" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]] || { echo "GITHUB_REPOSITORY is required" >&2; exit 1; } + +source=$(gh api "repos/$GITHUB_REPOSITORY/pages" --jq '[.build_type, .source.branch, .source.path] | join(" ")') +if [ "$source" != "legacy gh-pages /" ]; then + echo "Configure GitHub Pages to build from gh-pages / before publishing; an existing site is never reconfigured automatically" >&2 + exit 1 +fi +if [ "${1:-}" != "--check" ]; then + gh api --method POST "repos/$GITHUB_REPOSITORY/pages/builds" +fi diff --git a/js/developer/webfront-packages.lock.json b/js/developer/webfront-packages.lock.json new file mode 100644 index 00000000..a05f84bf --- /dev/null +++ b/js/developer/webfront-packages.lock.json @@ -0,0 +1,1104 @@ +{ + "format": 1, + "manifestDigest": "45184fd39426a231356fa5448e94c1bbb15599c384b37bb87ee92b355175b775", + "registry": "https://registry.npmjs.org/", + "roots": { + "@xterm/addon-fit": { + "requested": "0.11.0", + "id": "@xterm+addon-fit@0.11.0" + }, + "@xterm/xterm": { + "requested": "6.0.0", + "id": "@xterm+xterm@6.0.0" + }, + "esbuild-wasm": { + "requested": "0.28.2", + "id": "esbuild-wasm@0.28.2" + }, + "jasmine-core": { + "requested": "7.0.2", + "id": "jasmine-core@7.0.2" + }, + "react": { + "requested": "19.3.1", + "id": "react@19.3.1" + }, + "react-dom": { + "requested": "19.3.1", + "id": "react-dom@19.3.1" + }, + "semver": { + "requested": "7.7.3", + "id": "semver@7.7.3" + }, + "fflate": { + "requested": "0.8.3", + "id": "fflate@0.8.3" + } + }, + "packages": { + "@xterm+addon-fit@0.11.0": { + "name": "@xterm/addon-fit", + "version": "0.11.0", + "integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==", + "key": "@xterm+addon-fit@0.11.0-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo-vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g", + "manifest": { + "name": "@xterm/addon-fit", + "version": "0.11.0", + "author": { + "name": "The xterm.js authors", + "url": "https://xtermjs.org/" + }, + "main": "lib/addon-fit.js", + "module": "lib/addon-fit.mjs", + "types": "typings/addon-fit.d.ts", + "repository": "https://github.com/xtermjs/xterm.js/tree/master/addons/addon-fit", + "license": "MIT", + "keywords": [ + "terminal", + "xterm", + "xterm.js" + ], + "scripts": { + "build": "../../node_modules/.bin/tsc -p .", + "prepackage": "npm run build", + "package": "../../node_modules/.bin/webpack", + "prepublishOnly": "npm run package", + "start": "node ../../demo/start" + }, + "commit": "f447274f430fd22513f6adbf9862d19524471c04" + }, + "files": [ + "LICENSE", + "README.md", + "lib/addon-fit.js", + "lib/addon-fit.js.map", + "lib/addon-fit.mjs", + "lib/addon-fit.mjs.map", + "package.json", + "src/FitAddon.ts", + "typings/addon-fit.d.ts" + ], + "dependencies": {} + }, + "@xterm+xterm@6.0.0": { + "name": "@xterm/xterm", + "version": "6.0.0", + "integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==", + "key": "@xterm+xterm@6.0.0-TQwDdQGtwwDt-2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc_Zgc5kq5omJ-V0a8_kIM2WD3sMOYg", + "manifest": { + "name": "@xterm/xterm", + "description": "Full xterm terminal, in your browser", + "version": "6.0.0", + "main": "lib/xterm.js", + "module": "lib/xterm.mjs", + "style": "css/xterm.css", + "types": "typings/xterm.d.ts", + "repository": "https://github.com/xtermjs/xterm.js", + "license": "MIT", + "workspaces": [ + "addons/*" + ], + "keywords": [ + "cli", + "command-line", + "console", + "pty", + "shell", + "ssh", + "styles", + "terminal-emulator", + "terminal", + "tty", + "vt100", + "webgl", + "xterm" + ], + "scripts": { + "setup": "npm run build", + "start": "node demo/start", + "build": "npm run tsc", + "watch": "npm run tsc-watch", + "tsc": "tsc -b ./tsconfig.all.json", + "tsc-watch": "tsc -b -w ./tsconfig.all.json --preserveWatchOutput", + "esbuild": "node bin/esbuild_all.mjs", + "esbuild-watch": "node bin/esbuild_all.mjs --watch", + "esbuild-package": "node bin/esbuild_all.mjs --prod", + "esbuild-package-watch": "node bin/esbuild_all.mjs --prod --watch", + "esbuild-package-headless-only": "node bin/esbuild.mjs --prod --headless", + "esbuild-demo": "node bin/esbuild.mjs --demo-client", + "esbuild-demo-watch": "node bin/esbuild.mjs --demo-client --watch", + "test": "npm run test-unit", + "posttest": "npm run lint", + "lint": "eslint -c .eslintrc.json --max-warnings 0 --ext .ts src/ addons/", + "lint-fix": "eslint -c .eslintrc.json --fix --ext .ts src/ addons/", + "lint-api": "eslint --no-eslintrc -c .eslintrc.json.typings --max-warnings 0 --no-ignore --ext .d.ts typings/", + "test-unit": "node ./bin/test_unit.js", + "test-unit-coverage": "node ./bin/test_unit.js --coverage", + "test-unit-dev": "cross-env NODE_PATH='./out' mocha", + "test-integration": "node ./bin/test_integration.js --workers=75%", + "test-integration-chromium": "node ./bin/test_integration.js --workers=75% \"--project=ChromeStable\"", + "test-integration-firefox": "node ./bin/test_integration.js --workers=75% \"--project=FirefoxStable\"", + "test-integration-webkit": "node ./bin/test_integration.js --workers=75% \"--project=WebKit\"", + "test-integration-debug": "node ./bin/test_integration.js --workers=1 --headed --timeout=30000", + "benchmark": "NODE_PATH=./out xterm-benchmark -r 5 -c test/benchmark/benchmark.json", + "benchmark-baseline": "NODE_PATH=./out xterm-benchmark -r 5 -c test/benchmark/benchmark.json --baseline out-test/benchmark/*benchmark.js", + "benchmark-eval": "NODE_PATH=./out xterm-benchmark -r 5 -c test/benchmark/benchmark.json --eval out-test/benchmark/*benchmark.js", + "clean": "rm -rf lib out addons/*/lib addons/*/out", + "vtfeatures": "node bin/extract_vtfeatures.js src/**/*.ts src/*.ts", + "prepackage": "npm run build", + "package": "webpack", + "postpackage": "npm run esbuild-package", + "prepackage-headless": "npm run esbuild-package-headless-only", + "package-headless": "webpack --config ./webpack.config.headless.js", + "postpackage-headless": "node ./bin/package_headless.js", + "prepublishOnly": "npm run package" + }, + "devDependencies": { + "@lunapaint/png-codec": "^0.2.0", + "@playwright/test": "^1.37.1", + "@stylistic/eslint-plugin": "^2.3.0", + "@types/chai": "^4.2.22", + "@types/debug": "^4.1.7", + "@types/deep-equal": "^1.0.1", + "@types/express": "4", + "@types/express-ws": "^3.0.1", + "@types/jsdom": "^16.2.13", + "@types/mocha": "^9.0.0", + "@types/node": "^18.16.0", + "@types/trusted-types": "^1.0.6", + "@types/utf8": "^3.0.0", + "@types/webpack": "^5.28.0", + "@types/ws": "^8.2.0", + "@typescript-eslint/eslint-plugin": "^6.2.00", + "@typescript-eslint/parser": "^6.2.00", + "chai": "^4.3.4", + "cross-env": "^7.0.3", + "deep-equal": "^2.0.5", + "esbuild": "~0.25.2", + "eslint": "^8.56.0", + "eslint-plugin-jsdoc": "^46.9.1", + "express": "^4.19.2", + "express-ws": "^5.0.2", + "jsdom": "^18.0.1", + "mocha": "^10.1.0", + "mustache": "^4.2.0", + "node-pty": "1.1.0-beta19", + "nyc": "^15.1.0", + "source-map-loader": "^3.0.0", + "source-map-support": "^0.5.20", + "ts-loader": "^9.3.1", + "typescript": "5.5", + "utf8": "^3.0.0", + "webpack": "^5.61.0", + "webpack-cli": "^4.9.1", + "ws": "^8.2.3", + "xterm-benchmark": "^0.3.1" + }, + "commit": "f447274f430fd22513f6adbf9862d19524471c04" + }, + "files": [ + "LICENSE", + "README.md", + "css/xterm.css", + "lib/xterm.js", + "lib/xterm.js.map", + "lib/xterm.mjs", + "lib/xterm.mjs.map", + "package.json", + "src/browser/AccessibilityManager.ts", + "src/browser/Clipboard.ts", + "src/browser/ColorContrastCache.ts", + "src/browser/CoreBrowserTerminal.ts", + "src/browser/Linkifier.ts", + "src/browser/LocalizableStrings.ts", + "src/browser/OscLinkProvider.ts", + "src/browser/RenderDebouncer.ts", + "src/browser/TimeBasedDebouncer.ts", + "src/browser/Types.ts", + "src/browser/Viewport.ts", + "src/browser/decorations/BufferDecorationRenderer.ts", + "src/browser/decorations/ColorZoneStore.ts", + "src/browser/decorations/OverviewRulerRenderer.ts", + "src/browser/input/CompositionHelper.ts", + "src/browser/input/Mouse.ts", + "src/browser/input/MoveToCell.ts", + "src/browser/public/Terminal.ts", + "src/browser/renderer/dom/DomRenderer.ts", + "src/browser/renderer/dom/DomRendererRowFactory.ts", + "src/browser/renderer/dom/WidthCache.ts", + "src/browser/renderer/shared/Constants.ts", + "src/browser/renderer/shared/RendererUtils.ts", + "src/browser/renderer/shared/SelectionRenderModel.ts", + "src/browser/renderer/shared/Types.ts", + "src/browser/selection/SelectionModel.ts", + "src/browser/selection/Types.ts", + "src/browser/services/CharSizeService.ts", + "src/browser/services/CharacterJoinerService.ts", + "src/browser/services/CoreBrowserService.ts", + "src/browser/services/LinkProviderService.ts", + "src/browser/services/MouseService.ts", + "src/browser/services/RenderService.ts", + "src/browser/services/SelectionService.ts", + "src/browser/services/Services.ts", + "src/browser/services/ThemeService.ts", + "src/browser/shared/Constants.ts", + "src/common/CircularList.ts", + "src/common/Clone.ts", + "src/common/Color.ts", + "src/common/CoreTerminal.ts", + "src/common/InputHandler.ts", + "src/common/MultiKeyMap.ts", + "src/common/Platform.ts", + "src/common/SortedList.ts", + "src/common/TaskQueue.ts", + "src/common/TypedArrayUtils.ts", + "src/common/Types.ts", + "src/common/WindowsMode.ts", + "src/common/buffer/AttributeData.ts", + "src/common/buffer/Buffer.ts", + "src/common/buffer/BufferLine.ts", + "src/common/buffer/BufferRange.ts", + "src/common/buffer/BufferReflow.ts", + "src/common/buffer/BufferSet.ts", + "src/common/buffer/CellData.ts", + "src/common/buffer/Constants.ts", + "src/common/buffer/Marker.ts", + "src/common/buffer/Types.ts", + "src/common/data/Charsets.ts", + "src/common/data/EscapeSequences.ts", + "src/common/input/Keyboard.ts", + "src/common/input/TextDecoder.ts", + "src/common/input/UnicodeV6.ts", + "src/common/input/WriteBuffer.ts", + "src/common/input/XParseColor.ts", + "src/common/parser/Constants.ts", + "src/common/parser/DcsParser.ts", + "src/common/parser/EscapeSequenceParser.ts", + "src/common/parser/OscParser.ts", + "src/common/parser/Params.ts", + "src/common/parser/Types.ts", + "src/common/public/AddonManager.ts", + "src/common/public/BufferApiView.ts", + "src/common/public/BufferLineApiView.ts", + "src/common/public/BufferNamespaceApi.ts", + "src/common/public/ParserApi.ts", + "src/common/public/UnicodeApi.ts", + "src/common/services/BufferService.ts", + "src/common/services/CharsetService.ts", + "src/common/services/CoreMouseService.ts", + "src/common/services/CoreService.ts", + "src/common/services/DecorationService.ts", + "src/common/services/InstantiationService.ts", + "src/common/services/LogService.ts", + "src/common/services/OptionsService.ts", + "src/common/services/OscLinkService.ts", + "src/common/services/ServiceRegistry.ts", + "src/common/services/Services.ts", + "src/common/services/UnicodeService.ts", + "src/vs/base/browser/browser.ts", + "src/vs/base/browser/canIUse.ts", + "src/vs/base/browser/dom.ts", + "src/vs/base/browser/fastDomNode.ts", + "src/vs/base/browser/globalPointerMoveMonitor.ts", + "src/vs/base/browser/iframe.ts", + "src/vs/base/browser/keyboardEvent.ts", + "src/vs/base/browser/mouseEvent.ts", + "src/vs/base/browser/touch.ts", + "src/vs/base/browser/ui/scrollbar/abstractScrollbar.ts", + "src/vs/base/browser/ui/scrollbar/horizontalScrollbar.ts", + "src/vs/base/browser/ui/scrollbar/scrollableElement.ts", + "src/vs/base/browser/ui/scrollbar/scrollableElementOptions.ts", + "src/vs/base/browser/ui/scrollbar/scrollbarArrow.ts", + "src/vs/base/browser/ui/scrollbar/scrollbarState.ts", + "src/vs/base/browser/ui/scrollbar/scrollbarVisibilityController.ts", + "src/vs/base/browser/ui/scrollbar/verticalScrollbar.ts", + "src/vs/base/browser/ui/widget.ts", + "src/vs/base/browser/window.ts", + "src/vs/base/common/arrays.ts", + "src/vs/base/common/arraysFind.ts", + "src/vs/base/common/assert.ts", + "src/vs/base/common/async.ts", + "src/vs/base/common/cancellation.ts", + "src/vs/base/common/charCode.ts", + "src/vs/base/common/collections.ts", + "src/vs/base/common/decorators.ts", + "src/vs/base/common/equals.ts", + "src/vs/base/common/errors.ts", + "src/vs/base/common/event.ts", + "src/vs/base/common/functional.ts", + "src/vs/base/common/hash.ts", + "src/vs/base/common/iterator.ts", + "src/vs/base/common/keyCodes.ts", + "src/vs/base/common/keybindings.ts", + "src/vs/base/common/lazy.ts", + "src/vs/base/common/lifecycle.ts", + "src/vs/base/common/linkedList.ts", + "src/vs/base/common/map.ts", + "src/vs/base/common/numbers.ts", + "src/vs/base/common/observable.ts", + "src/vs/base/common/observableInternal/api.ts", + "src/vs/base/common/observableInternal/autorun.ts", + "src/vs/base/common/observableInternal/base.ts", + "src/vs/base/common/observableInternal/debugName.ts", + "src/vs/base/common/observableInternal/derived.ts", + "src/vs/base/common/observableInternal/lazyObservableValue.ts", + "src/vs/base/common/observableInternal/logging.ts", + "src/vs/base/common/observableInternal/promise.ts", + "src/vs/base/common/observableInternal/utils.ts", + "src/vs/base/common/platform.ts", + "src/vs/base/common/scrollable.ts", + "src/vs/base/common/sequence.ts", + "src/vs/base/common/stopwatch.ts", + "src/vs/base/common/strings.ts", + "src/vs/base/common/symbols.ts", + "src/vs/base/common/uint.ts", + "src/vs/patches/nls.ts", + "src/vs/typings/base-common.d.ts", + "src/vs/typings/require.d.ts", + "src/vs/typings/vscode-globals-nls.d.ts", + "src/vs/typings/vscode-globals-product.d.ts", + "typings/xterm.d.ts" + ], + "dependencies": {} + }, + "esbuild-wasm@0.28.2": { + "name": "esbuild-wasm", + "version": "0.28.2", + "integrity": "sha512-GccVwhv3mmOUVQHCQm2Ox/rby8n/EqUwvZxE6Pjfikrq/lWw9g9WX/u9EykWnpot3Ko6j426DgQdea2xWKIAQA==", + "key": "esbuild-wasm@0.28.2-GccVwhv3mmOUVQHCQm2Ox_rby8n_EqUwvZxE6Pjfikrq_lWw9g9WX_u9EykWnpot3Ko6j426DgQdea2xWKIAQA", + "manifest": { + "name": "esbuild-wasm", + "version": "0.28.2", + "description": "The cross-platform WebAssembly binary for esbuild, a JavaScript bundler.", + "repository": { + "type": "git", + "url": "git+https://github.com/evanw/esbuild.git" + }, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "main": "lib/main.js", + "browser": "lib/browser.js", + "types": "lib/main.d.ts", + "directories": { + "bin": "bin" + } + }, + "files": [ + "LICENSE.md", + "README.md", + "bin/esbuild", + "esbuild.wasm", + "esm/browser.d.ts", + "esm/browser.js", + "esm/browser.min.js", + "lib/browser.d.ts", + "lib/browser.js", + "lib/browser.min.js", + "lib/main.d.ts", + "lib/main.js", + "package.json", + "wasm_exec.js", + "wasm_exec_node.js" + ], + "dependencies": {} + }, + "jasmine-core@7.0.2": { + "name": "jasmine-core", + "version": "7.0.2", + "integrity": "sha512-YMVijt84KPQQFm1db1AQAxTXfq0k3wU06OkepLViljURFqiRQ7EYYX2eUAshhUv9fA9t1E2N65GrdqvupA9VPQ==", + "key": "jasmine-core@7.0.2-YMVijt84KPQQFm1db1AQAxTXfq0k3wU06OkepLViljURFqiRQ7EYYX2eUAshhUv9fA9t1E2N65GrdqvupA9VPQ", + "manifest": { + "name": "jasmine-core", + "license": "MIT", + "version": "7.0.2", + "repository": { + "type": "git", + "url": "https://github.com/jasmine/jasmine.git" + }, + "keywords": [ + "test", + "testing", + "jasmine", + "tdd", + "bdd" + ], + "scripts": { + "lint": "eslint \"src/**/*.js\" \"spec/**/*.js\" && prettier --check \"src/**/*.js\" \"spec/**/*.js\"", + "test": "node scripts/runSpecsInNode.js && npm run lint", + "test:parallel": "node scripts/runSpecsInParallel.js", + "cleanup": "prettier --write \"src/**/*.js\" \"spec/**/*.js\"", + "build": "node scripts/buildDistribution.js", + "buildStandaloneDist": "node scripts/buildStandaloneDist.js", + "serve": "node spec/support/localJasmineBrowser.js", + "serve:performance": "node spec/support/localJasmineBrowser.js jasmine-browser-performance.json", + "ci": "node spec/support/ci.js", + "ci:performance": "node spec/support/ci.js jasmine-browser-performance.json" + }, + "description": "Simple JavaScript testing framework for browsers and node.js", + "homepage": "https://jasmine.github.io", + "main": "./lib/jasmine-core.js", + "exports": { + ".": "./lib/jasmine-core.js" + }, + "files": [ + "LICENSE", + "README.md", + "images/*.{png,svg}", + "lib/**/*.{js,css}", + "package.json" + ], + "devDependencies": { + "@eslint/eslintrc": "^3.3.1", + "@eslint/js": "^9.24.0", + "@jasminejs/reporters": "^1.1.0", + "archiver": "^8.0.0", + "css-url-embed": "^0.1.0", + "ejs": "^3.1.10", + "eslint": "^9.24.0", + "eslint-plugin-compat": "^6.0.2", + "glob": "^13.0.0", + "globals": "^16.0.0", + "jasmine": "^7.0.0", + "jasmine-browser-runner": "^5.0.0", + "jsdom": "^26.0.0", + "prettier": "1.17.1", + "sass": "^1.58.3" + }, + "browserslist": [ + "Safari >= 26", + "Firefox >= 140", + "last 2 Chrome versions", + "last 2 Edge versions" + ] + }, + "files": [ + "LICENSE", + "README.md", + "images/jasmine-horizontal.png", + "images/jasmine-horizontal.svg", + "images/jasmine_favicon.png", + "lib/jasmine-core.js", + "lib/jasmine-core/boot.js", + "lib/jasmine-core/example/node_example/lib/jasmine_examples/Player.js", + "lib/jasmine-core/example/node_example/lib/jasmine_examples/Song.js", + "lib/jasmine-core/example/node_example/spec/helpers/jasmine_examples/SpecHelper.js", + "lib/jasmine-core/example/node_example/spec/jasmine_examples/PlayerSpec.js", + "lib/jasmine-core/example/spec/PlayerSpec.js", + "lib/jasmine-core/example/spec/SpecHelper.js", + "lib/jasmine-core/example/src/Player.js", + "lib/jasmine-core/example/src/Song.js", + "lib/jasmine-core/jasmine-html.js", + "lib/jasmine-core/jasmine.css", + "lib/jasmine-core/jasmine.js", + "package.json" + ], + "dependencies": {} + }, + "react@19.3.1": { + "name": "react", + "version": "19.3.1", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "key": "react@19.3.1-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw", + "manifest": { + "name": "react", + "description": "React is a JavaScript library for building user interfaces.", + "keywords": [ + "react" + ], + "version": "19.3.1", + "homepage": "https://react.dev/", + "bugs": "https://github.com/react/react/issues", + "license": "MIT", + "files": [ + "LICENSE", + "README.md", + "index.js", + "cjs/", + "compiler-runtime.js", + "jsx-runtime.js", + "jsx-runtime.react-server.js", + "jsx-dev-runtime.js", + "jsx-dev-runtime.react-server.js", + "react.react-server.js" + ], + "main": "index.js", + "exports": { + ".": { + "react-server": "./react.react-server.js", + "default": "./index.js" + }, + "./package.json": "./package.json", + "./jsx-runtime": { + "react-server": "./jsx-runtime.react-server.js", + "default": "./jsx-runtime.js" + }, + "./jsx-dev-runtime": { + "react-server": "./jsx-dev-runtime.react-server.js", + "default": "./jsx-dev-runtime.js" + }, + "./compiler-runtime": { + "react-server": "./compiler-runtime.js", + "default": "./compiler-runtime.js" + } + }, + "repository": { + "type": "git", + "url": "https://github.com/react/react.git", + "directory": "packages/react" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "files": [ + "LICENSE", + "README.md", + "cjs/react-compiler-runtime.development.js", + "cjs/react-compiler-runtime.production.js", + "cjs/react-compiler-runtime.profiling.js", + "cjs/react-jsx-dev-runtime.development.js", + "cjs/react-jsx-dev-runtime.production.js", + "cjs/react-jsx-dev-runtime.profiling.js", + "cjs/react-jsx-dev-runtime.react-server.development.js", + "cjs/react-jsx-dev-runtime.react-server.production.js", + "cjs/react-jsx-runtime.development.js", + "cjs/react-jsx-runtime.production.js", + "cjs/react-jsx-runtime.profiling.js", + "cjs/react-jsx-runtime.react-server.development.js", + "cjs/react-jsx-runtime.react-server.production.js", + "cjs/react.development.js", + "cjs/react.production.js", + "cjs/react.react-server.development.js", + "cjs/react.react-server.production.js", + "compiler-runtime.js", + "index.js", + "jsx-dev-runtime.js", + "jsx-dev-runtime.react-server.js", + "jsx-runtime.js", + "jsx-runtime.react-server.js", + "package.json", + "react.react-server.js" + ], + "dependencies": {} + }, + "react-dom@19.3.1": { + "name": "react-dom", + "version": "19.3.1", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "key": "react-dom@19.3.1-Y0bARz53lhEC1NMCASs0_j-faB_zqt3R8hpvg1e8-61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe-ZeBCavQPtKQ", + "manifest": { + "name": "react-dom", + "version": "19.3.1", + "description": "React package for working with the DOM.", + "main": "index.js", + "repository": { + "type": "git", + "url": "https://github.com/react/react.git", + "directory": "packages/react-dom" + }, + "keywords": [ + "react" + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/react/react/issues" + }, + "homepage": "https://react.dev/", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + }, + "files": [ + "LICENSE", + "README.md", + "client.js", + "client.react-server.js", + "index.js", + "profiling.js", + "profiling.react-server.js", + "react-dom.react-server.js", + "server.browser.js", + "server.bun.js", + "server.edge.js", + "server.js", + "server.node.js", + "server.react-server.js", + "static.browser.js", + "static.edge.js", + "static.js", + "static.node.js", + "static.react-server.js", + "test-utils.js", + "cjs/" + ], + "exports": { + ".": { + "react-server": "./react-dom.react-server.js", + "default": "./index.js" + }, + "./client": { + "react-server": "./client.react-server.js", + "default": "./client.js" + }, + "./server": { + "react-server": "./server.react-server.js", + "workerd": "./server.edge.js", + "bun": "./server.bun.js", + "deno": "./server.node.js", + "worker": "./server.browser.js", + "node": "./server.node.js", + "edge-light": "./server.edge.js", + "browser": "./server.browser.js", + "default": "./server.node.js" + }, + "./server.browser": { + "react-server": "./server.react-server.js", + "default": "./server.browser.js" + }, + "./server.bun": { + "react-server": "./server.react-server.js", + "default": "./server.bun.js" + }, + "./server.edge": { + "react-server": "./server.react-server.js", + "default": "./server.edge.js" + }, + "./server.node": { + "react-server": "./server.react-server.js", + "default": "./server.node.js" + }, + "./static": { + "react-server": "./static.react-server.js", + "workerd": "./static.edge.js", + "deno": "./static.browser.js", + "worker": "./static.browser.js", + "node": "./static.node.js", + "edge-light": "./static.edge.js", + "browser": "./static.browser.js", + "default": "./static.node.js" + }, + "./static.browser": { + "react-server": "./static.react-server.js", + "default": "./static.browser.js" + }, + "./static.edge": { + "react-server": "./static.react-server.js", + "default": "./static.edge.js" + }, + "./static.node": { + "react-server": "./static.react-server.js", + "default": "./static.node.js" + }, + "./profiling": { + "react-server": "./profiling.react-server.js", + "default": "./profiling.js" + }, + "./test-utils": "./test-utils.js", + "./package.json": "./package.json" + }, + "browser": { + "./server.js": "./server.browser.js", + "./static.js": "./static.browser.js" + } + }, + "files": [ + "LICENSE", + "README.md", + "cjs/react-dom-client.development.js", + "cjs/react-dom-client.production.js", + "cjs/react-dom-profiling.development.js", + "cjs/react-dom-profiling.profiling.js", + "cjs/react-dom-server-legacy.browser.development.js", + "cjs/react-dom-server-legacy.browser.production.js", + "cjs/react-dom-server-legacy.node.development.js", + "cjs/react-dom-server-legacy.node.production.js", + "cjs/react-dom-server.browser.development.js", + "cjs/react-dom-server.browser.production.js", + "cjs/react-dom-server.bun.development.js", + "cjs/react-dom-server.bun.production.js", + "cjs/react-dom-server.edge.development.js", + "cjs/react-dom-server.edge.production.js", + "cjs/react-dom-server.node.development.js", + "cjs/react-dom-server.node.production.js", + "cjs/react-dom-test-utils.development.js", + "cjs/react-dom-test-utils.production.js", + "cjs/react-dom.development.js", + "cjs/react-dom.production.js", + "cjs/react-dom.react-server.development.js", + "cjs/react-dom.react-server.production.js", + "client.js", + "client.react-server.js", + "index.js", + "package.json", + "profiling.js", + "profiling.react-server.js", + "react-dom.react-server.js", + "server.browser.js", + "server.bun.js", + "server.edge.js", + "server.js", + "server.node.js", + "server.react-server.js", + "static.browser.js", + "static.edge.js", + "static.js", + "static.node.js", + "static.react-server.js", + "test-utils.js" + ], + "dependencies": { + "scheduler": "scheduler@0.28.0", + "react": "react@19.3.1" + } + }, + "scheduler@0.28.0": { + "name": "scheduler", + "version": "0.28.0", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "key": "scheduler@0.28.0-juorfCmIkIw8tT-p5BXSm6PJjQF_ycEYmKyzURCIt_RaZIhL-PulbQ9Yu2z1HdOJDdqDTlxA1-xKBmHXJsczAw", + "manifest": { + "name": "scheduler", + "version": "0.28.0", + "description": "Cooperative scheduler for the browser environment.", + "repository": { + "type": "git", + "url": "https://github.com/react/react.git", + "directory": "packages/scheduler" + }, + "license": "MIT", + "keywords": [ + "react" + ], + "bugs": { + "url": "https://github.com/react/react/issues" + }, + "homepage": "https://react.dev/", + "files": [ + "LICENSE", + "README.md", + "index.js", + "index.native.js", + "unstable_mock.js", + "unstable_post_task.js", + "cjs/" + ] + }, + "files": [ + "LICENSE", + "README.md", + "cjs/scheduler-unstable_mock.development.js", + "cjs/scheduler-unstable_mock.production.js", + "cjs/scheduler-unstable_post_task.development.js", + "cjs/scheduler-unstable_post_task.production.js", + "cjs/scheduler.development.js", + "cjs/scheduler.native.development.js", + "cjs/scheduler.native.production.js", + "cjs/scheduler.production.js", + "index.js", + "index.native.js", + "package.json", + "unstable_mock.js", + "unstable_post_task.js" + ], + "dependencies": {} + }, + "semver@7.7.3": { + "name": "semver", + "version": "7.7.3", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "key": "semver@7.7.3-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl-dPb_rExr0Btby5loQm20Q", + "manifest": { + "name": "semver", + "version": "7.7.3", + "description": "The semantic version parser used by npm.", + "main": "index.js", + "scripts": { + "test": "tap", + "snap": "tap", + "lint": "npm run eslint", + "postlint": "template-oss-check", + "lintfix": "npm run eslint -- --fix", + "posttest": "npm run lint", + "template-oss-apply": "template-oss-apply --force", + "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" + }, + "devDependencies": { + "@npmcli/eslint-config": "^5.0.0", + "@npmcli/template-oss": "4.25.1", + "benchmark": "^2.1.4", + "tap": "^16.0.0" + }, + "license": "ISC", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/node-semver.git" + }, + "bin": { + "semver": "bin/semver.js" + }, + "files": [ + "bin/", + "lib/", + "classes/", + "functions/", + "internal/", + "ranges/", + "index.js", + "preload.js", + "range.bnf" + ], + "tap": { + "timeout": 30, + "coverage-map": "map.js", + "nyc-arg": [ + "--exclude", + "tap-snapshots/**" + ] + }, + "engines": { + "node": ">=10" + }, + "author": "GitHub Inc.", + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "version": "4.25.1", + "engines": ">=10", + "distPaths": [ + "classes/", + "functions/", + "internal/", + "ranges/", + "index.js", + "preload.js", + "range.bnf" + ], + "allowPaths": [ + "/classes/", + "/functions/", + "/internal/", + "/ranges/", + "/index.js", + "/preload.js", + "/range.bnf", + "/benchmarks" + ], + "publish": "true" + } + }, + "files": [ + "LICENSE", + "README.md", + "bin/semver.js", + "classes/comparator.js", + "classes/index.js", + "classes/range.js", + "classes/semver.js", + "functions/clean.js", + "functions/cmp.js", + "functions/coerce.js", + "functions/compare-build.js", + "functions/compare-loose.js", + "functions/compare.js", + "functions/diff.js", + "functions/eq.js", + "functions/gt.js", + "functions/gte.js", + "functions/inc.js", + "functions/lt.js", + "functions/lte.js", + "functions/major.js", + "functions/minor.js", + "functions/neq.js", + "functions/parse.js", + "functions/patch.js", + "functions/prerelease.js", + "functions/rcompare.js", + "functions/rsort.js", + "functions/satisfies.js", + "functions/sort.js", + "functions/valid.js", + "index.js", + "internal/constants.js", + "internal/debug.js", + "internal/identifiers.js", + "internal/lrucache.js", + "internal/parse-options.js", + "internal/re.js", + "package.json", + "preload.js", + "range.bnf", + "ranges/gtr.js", + "ranges/intersects.js", + "ranges/ltr.js", + "ranges/max-satisfying.js", + "ranges/min-satisfying.js", + "ranges/min-version.js", + "ranges/outside.js", + "ranges/simplify.js", + "ranges/subset.js", + "ranges/to-comparators.js", + "ranges/valid.js" + ], + "dependencies": {} + }, + "fflate@0.8.3": { + "name": "fflate", + "version": "0.8.3", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "key": "fflate@0.8.3-tbZNuJrLwGUp3zshBtdy4W-ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA", + "manifest": { + "name": "fflate", + "version": "0.8.3", + "description": "High performance (de)compression in an 8kB package", + "main": "./lib/index.cjs", + "module": "./esm/browser.js", + "types": "./lib/index.d.ts", + "unpkg": "./umd/index.js", + "jsdelivr": "./umd/index.js", + "browser": { + "./lib/node-worker.cjs": "./lib/worker.cjs" + }, + "exports": { + ".": { + "node": { + "import": { + "types": "./esm/index.d.mts", + "default": "./esm/index.mjs" + }, + "require": { + "types": "./lib/node.d.cts", + "default": "./lib/node.cjs" + } + }, + "import": { + "types": "./esm/browser.d.ts", + "default": "./esm/browser.js" + }, + "require": { + "types": "./lib/browser.d.cts", + "default": "./lib/browser.cjs" + } + }, + "./node": { + "import": { + "types": "./esm/index.d.mts", + "default": "./esm/index.mjs" + }, + "require": { + "types": "./lib/node.d.cts", + "default": "./lib/node.cjs" + } + }, + "./browser": { + "import": { + "types": "./esm/browser.d.ts", + "default": "./esm/browser.js" + }, + "require": { + "types": "./lib/browser.d.cts", + "default": "./lib/browser.cjs" + } + }, + "./package.json": "./package.json" + }, + "targets": { + "main": false, + "module": false, + "browser": false, + "types": false + }, + "sideEffects": false, + "homepage": "https://101arrowz.github.io/fflate", + "repository": "https://github.com/101arrowz/fflate", + "bugs": { + "email": "arjunbarrett@gmail.com", + "url": "https://github.com/101arrowz/fflate/issues" + }, + "author": "Arjun Barrett ", + "license": "MIT", + "keywords": [ + "gzip", + "gunzip", + "deflate", + "inflate", + "compression", + "decompression", + "zlib", + "pako", + "jszip", + "browser", + "node.js", + "tiny", + "fast", + "zip", + "unzip", + "non-blocking" + ], + "scripts": { + "build": "npm run build:lib && npm run build:docs && npm run build:demo", + "script": "node -r ts-node/register scripts/$SC.ts", + "build:lib": "tsc && tsc --project tsconfig.esm.json && npm run build:rewrite && npm run build:umd", + "build:umd": "SC=buildUMD npm run script", + "build:rewrite": "SC=rewriteBuilds npm run script", + "build:demo": "tsc --project tsconfig.demo.json && parcel build demo/index.html --no-cache --public-url \"./\" && SC=cpGHPages npm run script", + "build:docs": "typedoc --plugin typedoc-plugin-markdown --hideBreadcrumbs --readme none --disableSources --excludePrivate --excludeProtected --expandParameters --githubPages false --out docs/ src/index.ts", + "test": "TS_NODE_PROJECT=test/tsconfig.json uvu -b -r ts-node/register test", + "prepack": "npm run build && npm run test" + }, + "devDependencies": { + "@parcel/service-worker": "^2.9.3", + "@types/node": "^25.8.0", + "@types/pako": "*", + "@types/react": "^18.2.21", + "@types/react-dom": "^18.2.7", + "jszip": "^3.10.1", + "pako": "*", + "parcel": "^2.9.3", + "preact": "^10.17.1", + "react": "^18.2.0", + "react-dom": "^18.2.0", + "simple-git": "^3.19.1", + "terser": "^5.47.1", + "tiny-inflate": "*", + "ts-node": "^10.9.2", + "typedoc": "^0.28.19", + "typedoc-plugin-markdown": "^4.11.0", + "typescript": "^6.0.3", + "uvu": "^0.5.6", + "uzip": "*" + }, + "alias": { + "react": "preact/compat", + "react-dom": "preact/compat", + "buffer": false, + "process": false + } + }, + "files": [ + "CHANGELOG.md", + "LICENSE", + "README.md", + "esm/browser.d.ts", + "esm/browser.js", + "esm/index.d.mts", + "esm/index.mjs", + "lib/browser.cjs", + "lib/browser.d.cts", + "lib/index.cjs", + "lib/index.d.ts", + "lib/node-worker.cjs", + "lib/node.cjs", + "lib/node.d.cts", + "lib/worker.cjs", + "package.json", + "umd/index.js" + ], + "dependencies": {} + } + } +} diff --git a/js/developer/webfront.project.json b/js/developer/webfront.project.json new file mode 100644 index 00000000..1dc43f9c --- /dev/null +++ b/js/developer/webfront.project.json @@ -0,0 +1,64 @@ +{ + "format": 1, + "name": "webfront-developer-tools", + "version": "0.1.0", + "dependencies": { + "@xterm/addon-fit": "0.11.0", + "@xterm/xterm": "6.0.0", + "esbuild-wasm": "0.28.2", + "fflate": "0.8.3", + "jasmine-core": "7.0.2", + "react": "19.3.1", + "react-dom": "19.3.1", + "semver": "7.7.3" + }, + "scripts": { + "build": "js/developer/scripts/build.mjs", + "site": "js/developer/scripts/site.mjs", + "pin": "js/developer/scripts/pin.mjs", + "test-registry": "test/web/registry/build.mjs" + }, + "test": { + "specs": [ + "test/developer/specs/environment-specs.mjs", + "test/developer/specs/manifest-specs.mjs", + "test/developer/specs/restore-specs.mjs", + "test/developer/specs/scripts-specs.mjs", + "test/developer/specs/development-specs.mjs", + "test/developer/specs/testing-specs.mjs", + "test/developer/specs/timers-specs.mjs", + "test/developer/specs/distribution-specs.mjs" + ] + }, + "permissions": { + "files": [ + "js/developer/webfront.project.json", + "js/developer/webfront-packages.lock.json", + ".webfront/developer/packages", + "js/core", + "js/developer/environment", + "js/developer/tools", + "js/developer/scripts", + "test/developer", + "test/web/registry", + "registry-archives", + "examples/life/ui", + "include/webfront/system/DeveloperReleaseData.hpp" + ], + "publish": [ + "build-distribution", + "build-distribution-repeat", + "build-developer-environment", + "build-site", + "build-registry", + "js/core/bootstrap/bootstrap.bundle.mjs", + "js/developer/environment/packages.bundle.mjs", + "js/developer/environment/PACKAGES-LICENSE.txt", + "js/developer/environment/bundles.json", + "include/webfront/system/DeveloperReleaseData.hpp" + ], + "fetch": [ + "https://ambroise-leclerc.github.io" + ] + } +} diff --git a/test/.clang-format b/test/.clang-format new file mode 100644 index 00000000..45e9ebf1 --- /dev/null +++ b/test/.clang-format @@ -0,0 +1,242 @@ +--- +# Modern C++20+ clang-format configuration for WebFront project +# Compatible with clang-format 22+ +Language: Cpp +BasedOnStyle: WebKit + +# ============================================================================= +# Basic Formatting +# ============================================================================= +Standard: c++20 +ColumnLimit: 160 +TabWidth: 4 +UseTab: Never +IndentWidth: 4 +ContinuationIndentWidth: 4 + +# ============================================================================= +# Alignment and Spacing +# ============================================================================= +AlignAfterOpenBracket: Align +AlignArrayOfStructures: Right +AlignConsecutiveAssignments: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: true + PadOperators: false +AlignConsecutiveBitFields: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false +AlignConsecutiveDeclarations: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false +AlignConsecutiveMacros: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false +AlignConsecutiveShortCaseStatements: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCaseColons: false +AlignEscapedNewlines: Right +AlignOperands: Align +AlignTrailingComments: + Kind: Always + OverEmptyLines: 1 + +# ============================================================================= +# Line Breaking +# ============================================================================= +AllowAllArgumentsOnNextLine: false +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: Empty +AllowShortCaseLabelsOnASingleLine: false +AllowShortEnumsOnASingleLine: true +AllowShortFunctionsOnASingleLine: Empty +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: Empty +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: Yes + +# ============================================================================= +# Braces and Brackets +# ============================================================================= +BreakBeforeBraces: Custom +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false + +BreakBeforeBinaryOperators: NonAssignment +BreakBeforeConceptDeclarations: Always +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeColon +BreakInheritanceList: BeforeColon +BreakStringLiterals: true + +# ============================================================================= +# Includes +# ============================================================================= +SortIncludes: CaseInsensitive +SortUsingDeclarations: Lexicographic +IncludeBlocks: Regroup +IncludeCategories: + # Project headers + - Regex: '^".*\.hpp"$|^<.*\.hpp>$' + Priority: 1 + SortPriority: 1 + # C++ standard library + - Regex: '^<[a-z_]+>$' + Priority: 2 + SortPriority: 2 + # Third-party headers + - Regex: '^<(?!std).*>$' + Priority: 3 + SortPriority: 3 + # System headers + - Regex: '.*' + Priority: 4 + SortPriority: 4 + +# ============================================================================= +# Indentation +# ============================================================================= +AccessModifierOffset: -4 +IndentAccessModifiers: false +IndentCaseBlocks: false +IndentCaseLabels: true +IndentExternBlock: NoIndent +IndentGotoLabels: false +IndentPPDirectives: BeforeHash +IndentRequiresClause: true +IndentWrappedFunctionNames: false + +# ============================================================================= +# Spacing +# ============================================================================= +BitFieldColonSpacing: Both +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatementsExceptControlMacros +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 2 +SpacesInAngles: Never +SpacesInConditionalStatement: false +SpacesInContainerLiterals: false +SpacesInCStyleCastParentheses: false +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParentheses: false +SpacesInSquareBrackets: false + +# ============================================================================= +# Modern C++ Features +# ============================================================================= +Cpp11BracedListStyle: true +FixNamespaceComments: true +NamespaceIndentation: None +CompactNamespaces: false + +# Concepts and requires clauses +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope + +# Lambda formatting +LambdaBodyIndentation: Signature + +# ============================================================================= +# Penalties (for line breaking decisions) +# ============================================================================= +PenaltyBreakAssignment: 100 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 60 + +# ============================================================================= +# Miscellaneous +# ============================================================================= +BinPackArguments: false +BinPackParameters: false +ConstructorInitializerIndentWidth: 4 +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +KeepEmptyLinesAtTheStartOfBlocks: false +MaxEmptyLinesToKeep: 2 +PackConstructorInitializers: NextLine +PointerAlignment: Left +QualifierAlignment: Leave +ReferenceAlignment: Pointer +ReflowComments: true +RemoveBracesLLVM: false +RemoveParentheses: Leave +RemoveSemicolon: false +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 + +# ============================================================================= +# Language-specific overrides +# ============================================================================= +--- +Language: JavaScript +BasedOnStyle: WebKit +ColumnLimit: 160 +IndentWidth: 2 +TabWidth: 2 + +--- +Language: Json +BasedOnStyle: None +IndentWidth: 2 +TabWidth: 2 + +--- +Language: Proto +BasedOnStyle: Google +IndentWidth: 2 +TabWidth: 2 + +--- +Language: TextProto +BasedOnStyle: Google +IndentWidth: 2 +TabWidth: 2 \ No newline at end of file diff --git a/test/BabelFSTests.cpp b/test/BabelFSTests.cpp deleted file mode 100644 index 74f78b04..00000000 --- a/test/BabelFSTests.cpp +++ /dev/null @@ -1,13 +0,0 @@ -#include "EmbeddedAssetChecks.hpp" -#include - -using namespace webfront; - -SCENARIO("BabelFS provides the pinned Babel 8 standalone compiler") { - auto path = std::filesystem::path("babel-standalone@8.0.7") / "babel.min.js"; - path.make_preferred(); - auto file = fs::BabelFS::open(path); - REQUIRE(file.has_value()); - readEmbeddedAsset(*file, fs::generated::BabelData::dataSize); - REQUIRE_FALSE(fs::BabelFS::open("babel-standalone@7.22.5/babel.min.js")); -} diff --git a/test/DeveloperTests.cpp b/test/DeveloperTests.cpp deleted file mode 100644 index 20c0521b..00000000 --- a/test/DeveloperTests.cpp +++ /dev/null @@ -1,340 +0,0 @@ -#include "../test/fixtures/Pi.hpp" -#include "TemporaryDirectory.hpp" -#include -#include -#include - -#include -#include -#include - -using namespace webfront; -using webfront::test::TemporaryDirectory; - -namespace { -struct QuietFrontend { - static constexpr frontend::Action action{frontend::Action::keepServerRunning}; - - static void initialize() {} - - static void open(std::string_view, std::string_view) {} -}; - -std::vector bytes(std::string_view text) { - return {text.begin(), text.end()}; -} -std::string read(developer::Store& store, std::string path) { - auto data = store.read(std::move(path), 0); - return {data.begin(), data.end()}; -} -} // namespace - -SCENARIO("Developer publication preserves the installed files until commit") { - TemporaryDirectory project; - developer::Store store{project.path()}; - GIVEN("an installed output") { - auto first = store.begin("generated/PiUI.hpp", false); - store.write(first, "output", 0, bytes("old")); - store.commit(first); - WHEN("the next output is interrupted") { - auto second = store.begin("generated/PiUI.hpp", false); - store.write(second, "output", 0, bytes("partial")); - REQUIRE(read(store, "generated/PiUI.hpp") == "old"); - store.abort(second); - THEN("the installed output remains intact") { - REQUIRE(read(store, "generated/PiUI.hpp") == "old"); - } - } - WHEN("a complete replacement is committed") { - auto second = store.begin("generated/PiUI.hpp", false); - store.write(second, "output", 0, bytes("new")); - store.commit(second); - THEN("the new output replaces it") { - REQUIRE(read(store, "generated/PiUI.hpp") == "new"); - } - } - } -} - -SCENARIO("Developer writes are bounded and paths stay inside the explicit project") { - TemporaryDirectory project; - developer::Store store{project.path()}; - GIVEN("a staged preview") { - const auto id = store.begin(".webfront/developer/preview", true); - WHEN("the browser sends invalid chunks or paths") { - THEN("none are published") { - REQUIRE_THROWS(store.write(id, "../escape", 0, bytes("bad"))); - REQUIRE_THROWS(store.write(id, "index.html", 1, bytes("bad"))); - REQUIRE_THROWS(store.write(id, "big", 0, std::vector(developer::chunkSize + 1))); - REQUIRE_THROWS(store.begin("../escape", false)); - REQUIRE_THROWS(store.read("../escape", 0)); - REQUIRE_THROWS(store.begin(".webfront/developer/staging/x", true)); - REQUIRE_THROWS(store.begin(".webfront", true)); - REQUIRE_THROWS(store.begin(".webfront/developer", true)); - REQUIRE_THROWS(store.begin(".webfront/developer/preview/assets", true)); - } - } - WHEN("a zero-length file and a nested file are sent") { - store.write(id, "empty", 0, {}); - store.write(id, "assets/a.js", 0, bytes("abc")); - store.write(id, "assets/a.js", 3, bytes("def")); - store.commit(id); - THEN("both are readable after commit") { - REQUIRE(read(store, ".webfront/developer/preview/empty").empty()); - REQUIRE_THROWS(store.read(".webfront/developer/preview/assets", 0)); - REQUIRE(read(store, ".webfront/developer/preview/assets/a.js") == "abcdef"); - } - } - } - GIVEN("an escaping directory symlink") { - TemporaryDirectory outside; - std::error_code error; - std::filesystem::create_directory_symlink(outside.path(), project.path() / "escape", error); - if (!error) { - THEN("reads and destinations are rejected") { - REQUIRE_THROWS(store.begin("escape/new.hpp", false)); - REQUIRE_THROWS(store.read("escape/secret", 0)); - } - } - } -} - -SCENARIO("Developer filesystem serves only published resources and protects the bridge") { - TemporaryDirectory project; - developer::Store store{project.path()}; - fs::DeveloperFS filesystem{project.path()}; - GIVEN("published preview assets and private project files") { - const auto id = store.begin(".webfront/developer/preview", true); - store.write(id, "index.html", 0, bytes("preview")); - store.commit(id); - THEN("the preview and bootstrap are served but project sources are not") { - REQUIRE(filesystem.open("/webfront/developer/preview/index.html")); - REQUIRE(filesystem.open("/webfront-bootstrap.html")); - REQUIRE(filesystem.open("/webfront-bootstrap.mjs")); - REQUIRE(filesystem.open("/WebFront.js")); - REQUIRE_FALSE(filesystem.open("/CMakeLists.txt")); - REQUIRE_FALSE(filesystem.open("/webfront/developer/staging/file")); - REQUIRE_FALSE(filesystem.open("/webfront/developer/preview/../../secret")); - REQUIRE(http::MimeType("wasm").toString() == "application/wasm"); - } - } -} - -SCENARIO("The PI demonstration returns exact decimal strings and rejects excessive work") { - REQUIRE(demo::pi(0) == "3"); - REQUIRE(demo::pi(1) == "3.1"); - REQUIRE(demo::pi(50) == "3.14159265358979323846264338327950288419716939937510"); - REQUIRE(demo::pi(1000).size() == 1002); - REQUIRE_THROWS_AS(demo::pi(1001), std::invalid_argument); -} - -SCENARIO("A downloaded starter never replaces a developer's existing project") { - TemporaryDirectory project; - developer::Store store{project.path()}; - GIVEN("an existing project directory") { - std::filesystem::create_directories(project.path() / "ui"); - THEN("new-only publication refuses to stage over it") { - REQUIRE_THROWS(store.begin("ui", true, false)); - REQUIRE(std::filesystem::is_directory(project.path() / "ui")); - } - } - GIVEN("a new starter staged before its destination exists") { - auto id = store.begin("new-ui", true, false); - store.write(id, "main.tsx", 0, bytes("starter")); - WHEN("a local directory appears before commit") { - std::filesystem::create_directory(project.path() / "new-ui"); - THEN("commit refuses to replace that directory") { - REQUIRE_THROWS(store.commit(id)); - REQUIRE_FALSE(std::filesystem::exists(project.path() / "new-ui/main.tsx")); - store.abort(id); - } - } - WHEN("the destination remains new") { - store.commit(id); - THEN("the starter is published") { - REQUIRE(read(store, "new-ui/main.tsx") == "starter"); - } - } - } -} - -SCENARIO("Transactions abandoned by a disconnected browser never lock the project") { - TemporaryDirectory project; - const auto stagingRoot = project.path() / ".webfront/developer/staging"; - GIVEN("the maximum number of unfinished transactions") { - developer::Store store{project.path()}; - std::vector ids; - for (std::size_t index = 0; index < developer::maxTransactions; ++index) - ids.push_back(store.begin("generated/" + std::to_string(index), true)); - THEN("active transactions still bound the number of publications") { - REQUIRE_THROWS(store.begin("generated/extra", true)); - } - } - GIVEN("unfinished transactions left by a browser that reloaded") { - developer::Store store{project.path(), std::chrono::milliseconds{0}}; - std::vector ids; - for (std::size_t index = 0; index < developer::maxTransactions; ++index) - ids.push_back(store.begin("generated/" + std::to_string(index), true)); - WHEN("a new publication begins") { - const auto id = store.begin("generated/new", true); - THEN("the abandoned ones are discarded with their staging") { - REQUIRE_FALSE(std::filesystem::exists(stagingRoot / ids.front())); - REQUIRE_THROWS(store.write(ids.front(), "file", 0, bytes("late"))); - store.write(id, "file", 0, bytes("fresh")); - store.commit(id); - REQUIRE(read(store, "generated/new/file") == "fresh"); - } - } - } - GIVEN("staging left by a crashed process") { - std::filesystem::create_directories(stagingRoot / "1"); - std::filesystem::create_directories(stagingRoot / "2"); - std::filesystem::last_write_time(stagingRoot / "1", std::filesystem::file_time_type::clock::now() - std::chrono::hours{2}); - WHEN("the project is opened again") { - developer::Store store{project.path()}; - THEN("only the stale staging is removed") { - REQUIRE_FALSE(std::filesystem::exists(stagingRoot / "1")); - REQUIRE(std::filesystem::exists(stagingRoot / "2")); - } - } - } - GIVEN("a backup left by a crashed commit") { - developer::Store store{project.path()}; - auto first = store.begin("generated/out.hpp", false); - store.write(first, "output", 0, bytes("old")); - store.commit(first); - const auto second = store.begin("generated/out.hpp", false); - store.write(second, "output", 0, bytes("new")); - std::filesystem::create_directories(stagingRoot / (second + "-backup/inner")); - std::ofstream{stagingRoot / (second + "-backup/inner/file")} << "stale"; - THEN("the replacement still commits") { - store.commit(second); - REQUIRE(read(store, "generated/out.hpp") == "new"); - } - } -} - -SCENARIO("The staging area is protected however its path is spelled") { - TemporaryDirectory project; - developer::Store store{project.path()}; - GIVEN("a symbolic link to the staging area inside the project") { - std::filesystem::create_directories(project.path() / ".webfront/developer/staging"); - const auto victim = store.begin("victim", true); - std::error_code error; - std::filesystem::create_directory_symlink(project.path() / ".webfront/developer/staging", project.path() / "alias", error); - if (!error) { - THEN("it cannot be used as a publication destination") { - REQUIRE_THROWS(store.begin("alias", true)); - REQUIRE_THROWS(store.begin("alias/" + victim, true)); - } - } - store.abort(victim); - } -} - -SCENARIO("The developer bridge refuses WebSocket clients without an Origin") { - GIVEN("the default application configuration") { - REQUIRE(WebFrontConfig{}.contentPolicy.allowMissingOrigin); - WHEN("it is prepared for a developer project") { - const auto config = developer::projectConfig({}, "project"); - THEN("the project is the document root and a missing Origin is refused") { - REQUIRE(config.documentRoot == "project"); - REQUIRE_FALSE(config.contentPolicy.allowMissingOrigin); - } - } - } -} - -SCENARIO("Startup cleanup never leaves the project through a staging link") { - TemporaryDirectory project; - TemporaryDirectory outside; - GIVEN("a staging directory that is a link to an old file outside the project") { - const auto victim = outside.path() / "keep.txt"; - std::ofstream{victim} << "outside"; - std::filesystem::last_write_time(victim, std::filesystem::file_time_type::clock::now() - std::chrono::hours{3}); - std::filesystem::create_directories(project.path() / ".webfront/developer"); - std::error_code error; - std::filesystem::create_directory_symlink(outside.path(), project.path() / ".webfront/developer/staging", error); - if (!error) { - WHEN("the project is opened") { - developer::Store store{project.path()}; - THEN("the outside file is untouched") { - REQUIRE(std::filesystem::exists(victim)); - } - } - } - } -} - -SCENARIO("Paths differing only by case never share a staged file") { - TemporaryDirectory project; - developer::Store store{project.path()}; - GIVEN("a staged directory holding LICENSE") { - const auto id = store.begin("package", true); - store.write(id, "LICENSE", 0, bytes("first")); - WHEN("a second file whose name differs only by case is sent") { - THEN("it is refused and the first file keeps its content") { - REQUIRE_THROWS_AS(store.write(id, "License", 0, bytes("second")), std::invalid_argument); - store.write(id, "LICENSE", 5, bytes("!")); - store.commit(id); - REQUIRE(read(store, "package/LICENSE") == "first!"); - } - } - } -} - -SCENARIO("The developer store refuses malformed requests without changing the project") { - TemporaryDirectory project; - developer::Store store{project.path()}; - GIVEN("a project file and a single-output transaction") { - std::ofstream(project.path() / "notes.txt") << "text"; - const auto id = store.begin("generated/output.hpp", false); - THEN("invalid reads and writes are rejected") { - REQUIRE_THROWS_AS(store.read("notes.txt", std::numeric_limits::max()), std::invalid_argument); - REQUIRE_THROWS_AS(store.write(id, "other", 0, bytes("x")), std::invalid_argument); - REQUIRE_THROWS_AS(store.commit(id), std::runtime_error); - } - THEN("aborting is idempotent and ends the transaction") { - REQUIRE_NOTHROW(store.abort("unknown")); - REQUIRE_NOTHROW(store.abort(id)); - REQUIRE_THROWS_AS(store.commit(id), std::runtime_error); - } - } - GIVEN("an existing destination") { - std::ofstream(project.path() / "taken.txt") << "text"; - THEN("only the replacing form may publish over it") { - REQUIRE_THROWS_AS(store.beginNew("taken.txt", false), std::runtime_error); - REQUIRE_NOTHROW(store.abort(store.beginReplacing("taken.txt", false))); - } - } - GIVEN("a path that is not a directory") { - std::ofstream(project.path() / "file") << "x"; - THEN("it cannot be a project") { - REQUIRE_THROWS_AS(developer::Store{project.path() / "file"}, std::invalid_argument); - } - } -} - -SCENARIO("The developer application needs an explicit project and a trusted environment") { - using App = BasicDeveloperApp; - const DeveloperBootstrapOptions trusted{.environment = "https://example.test/env.tgz", .integrity = "sha512-abc"}; - GIVEN("no project directory") { - App app; - THEN("bootstrap is refused") { - REQUIRE_THROWS_AS(app.bootstrap("developer", trusted), std::invalid_argument); - } - } - GIVEN("a project directory") { - TemporaryDirectory project; - App app(project.path(), WebFrontConfig{.port = "0"}); - THEN("an unknown mode or an unpinned environment is refused") { - REQUIRE_THROWS_AS(app.bootstrap("other", trusted), std::invalid_argument); - REQUIRE_THROWS_AS(app.bootstrap("developer", {.environment = "https://example.test/env.tgz", .integrity = "md5-abc"}), std::invalid_argument); - REQUIRE_THROWS_AS(app.bootstrap("developer", {.environment = "", .integrity = "sha512-abc"}), std::invalid_argument); - } - THEN("a pinned environment is accepted once") { - REQUIRE_NOTHROW(app.bootstrap("developer", trusted)); - REQUIRE_THROWS_AS(app.bootstrap("developer", trusted), std::logic_error); - } - } -} diff --git a/test/GzipTests.cpp b/test/GzipTests.cpp deleted file mode 100644 index 342010a2..00000000 --- a/test/GzipTests.cpp +++ /dev/null @@ -1,196 +0,0 @@ -#include "GzipFixtures.hpp" -#include -#include - -#include - -using webfront::http::gzip::decodeGzip; - -namespace { -std::string payload() { - std::string result; - for (unsigned index = 0; index < 1000; ++index) - result += "WebFront gzip fallback\n"; - for (unsigned repeat = 0; repeat < 3; ++repeat) - for (unsigned byte = 0; byte < 256; ++byte) - result.push_back(static_cast(byte)); - return result; -} -} // namespace - -SCENARIO("Gzip decoding validates complete bounded members") { - const auto expected = payload(); - GIVEN("fixed and dynamic Huffman blocks, with optional gzip fields") { - for (const auto bytes : {gzipfixtures::fixed, gzipfixtures::dynamic, gzipfixtures::optional}) { - WHEN("decoding a complete member of " << bytes.size() << " bytes") { - THEN("the exact binary content is returned") { - REQUIRE(decodeGzip(bytes) == expected); - REQUIRE(decodeGzip(bytes, expected.size()) == expected); - REQUIRE_FALSE(decodeGzip(bytes, expected.size() - 1)); - } - } - WHEN("truncating a member of " << bytes.size() << " bytes at every byte boundary") { - THEN("every prefix is rejected") { - for (std::size_t length = 0; length < bytes.size(); ++length) { - INFO(length); - REQUIRE_FALSE(decodeGzip(bytes.substr(0, length))); - } - } - } - } - } - GIVEN("a gzip member with a stored DEFLATE block") { - // A final, byte-aligned stored block containing 'abc', CRC32 and ISIZE. - const std::string bytes("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03" - "\x01\x03\x00\xfc\xff" - "abc" - "\xc2\x41\x24\x35\x03\x00\x00\x00", - 26); - THEN("stored bytes and their complement are checked") { - REQUIRE(decodeGzip(bytes) == "abc"); - auto corrupt = bytes; - corrupt[13] ^= 1; - REQUIRE_FALSE(decodeGzip(corrupt)); - REQUIRE_FALSE(decodeGzip(bytes, 2)); - for (std::size_t length = 0; length < bytes.size(); ++length) - REQUIRE_FALSE(decodeGzip(std::string_view(bytes).substr(0, length))); - } - } - GIVEN("empty and concatenated members") { - const auto bytes = std::string(gzipfixtures::dynamic) + std::string(gzipfixtures::empty) + std::string(gzipfixtures::fixed); - THEN("members are decoded independently under one total budget") { - REQUIRE(decodeGzip(gzipfixtures::empty, 0) == ""); - REQUIRE(decodeGzip(bytes) == expected + expected); - REQUIRE_FALSE(decodeGzip(bytes, expected.size())); - REQUIRE_FALSE(decodeGzip(std::string(gzipfixtures::dynamic) + "garbage")); - } - } - GIVEN("corrupt gzip metadata, trailer or block type") { - for (const auto offset : {0u, 1u, 2u, 3u, 10u}) { - auto bytes = std::string(gzipfixtures::dynamic); - bytes[offset] = static_cast(0xff); - REQUIRE_FALSE(decodeGzip(bytes)); - } - for (std::size_t offset = gzipfixtures::dynamic.size() - 8; offset < gzipfixtures::dynamic.size(); ++offset) { - auto bytes = std::string(gzipfixtures::dynamic); - bytes[offset] ^= 1; - REQUIRE_FALSE(decodeGzip(bytes)); - } - auto bytes = std::string(gzipfixtures::optional); - bytes[10] = static_cast(0xff); // Invalid extra-field length. - REQUIRE_FALSE(decodeGzip(bytes)); - bytes = gzipfixtures::optional; - bytes[17] ^= 1; // Header CRC covers the optional name, too. - REQUIRE_FALSE(decodeGzip(bytes)); - } -} - -SCENARIO("Gzip rejects invalid Huffman codes and match distances") { - GIVEN("malformed DEFLATE blocks") { - THEN("decoding rejects the blocks without accessing missing history or table entries") { - for (const auto bytes : {gzipfixtures::invalidDistance, - gzipfixtures::reservedLiteral, - gzipfixtures::reservedDistance, - gzipfixtures::oversubscribed, - gzipfixtures::repeatWithoutPrevious, - gzipfixtures::repeatOverflow, - gzipfixtures::missingEnd}) { - REQUIRE_FALSE(decodeGzip(bytes)); - } - } - } -} - -SCENARIO("Gzip rejects reserved distance declarations and trailing padding") { - GIVEN("dynamic blocks declaring 31 or 32 distance symbols") { - THEN("the declarations are rejected even when no distance is used") { - REQUIRE_FALSE(decodeGzip(gzipfixtures::distanceCount31)); - REQUIRE_FALSE(decodeGzip(gzipfixtures::distanceCount32)); - } - } - GIVEN("zero padding after a complete member") { - const auto bytes = std::string(gzipfixtures::empty) + std::string(8, '\0'); - THEN("strict member parsing rejects the padding") { - REQUIRE_FALSE(decodeGzip(bytes)); - } - } -} - -SCENARIO("Gzip default output budget is four MiB across concatenated members") { - const auto memberSize = payload().size(); - const auto memberCount = (4 * 1024 * 1024) / memberSize + 1; - std::string bytes; - for (std::size_t index = 0; index < memberCount; ++index) - bytes += gzipfixtures::fixed; - THEN("the default rejects a response just above four MiB") { - REQUIRE_FALSE(decodeGzip(bytes)); - } - THEN("an explicitly larger budget can permit the same valid content") { - const auto decoded = decodeGzip(bytes, memberCount * memberSize); - REQUIRE(decoded); - REQUIRE(decoded->size() == memberCount * memberSize); - } -} - -SCENARIO("Gzip match copies preserve overlapping history across string growth") { - using webfront::http::gzip::InflateContext; - GIVEN("a periodic match longer than its distance") { - std::string output = "abc"; - InflateContext context{output, 0, 1000}; - context.copyMatch(258, 3); - THEN("newly written bytes extend the same periodic sequence") { - REQUIRE(output.size() == 261); - for (std::size_t index = 0; index < output.size(); ++index) - REQUIRE(output[index] == "abc"[index % 3]); - } - } - GIVEN("a repeated byte and an exact output budget") { - std::string output = "x"; - InflateContext context{output, 0, 259}; - context.copyMatch(258, 1); - THEN("the copy grows safely and the next copy fails without modifying output") { - REQUIRE(output == std::string(259, 'x')); - REQUIRE_THROWS_AS(context.copyMatch(3, 1), webfront::http::gzip::InvalidGzip); - REQUIRE(output == std::string(259, 'x')); - } - } -} - -SCENARIO("Gzip bulk reads require alignment and complete input") { - webfront::http::gzip::GzipReader reader("abc"); - GIVEN("an unaligned reader") { - reader.bits(1); - REQUIRE_THROWS_AS(reader.readBytes(1), webfront::http::gzip::InvalidGzip); - reader.align(); - THEN("aligned reads consume only available bytes") { - REQUIRE(reader.readBytes(2) == "bc"); - REQUIRE(reader.done()); - REQUIRE(reader.readBytes(0).empty()); - REQUIRE_THROWS_AS(reader.readBytes(1), webfront::http::gzip::InvalidGzip); - } - } - GIVEN("a truncated read") { - REQUIRE_THROWS_AS(reader.readBytes(4), webfront::http::gzip::InvalidGzip); - THEN("failure leaves the reader position unchanged") { - REQUIRE(reader.readBytes(3) == "abc"); - } - } -} - -SCENARIO("Gzip CRC32 matches standard and binary reference vectors") { - using webfront::http::gzip::gzipCrc; - GIVEN("the empty input and the standard check vector") { - THEN("the IEEE CRC32 values match") { - REQUIRE(gzipCrc("") == 0u); - REQUIRE(gzipCrc("123456789") == 0xcbf43926u); - } - } - GIVEN("every byte value, including bytes with the high bit set") { - std::string bytes; - for (unsigned byte = 0; byte < 256; ++byte) - bytes.push_back(static_cast(byte)); - THEN("the result matches the independent zlib reference") { - REQUIRE(gzipCrc(bytes) == 0x29058c73u); - } - } -} diff --git a/test/JasmineFSTests.cpp b/test/JasmineFSTests.cpp deleted file mode 100644 index a4b1a3a7..00000000 --- a/test/JasmineFSTests.cpp +++ /dev/null @@ -1,33 +0,0 @@ -#include "EmbeddedAssetChecks.hpp" -#include - -#include -#include -#include - -using namespace webfront; - -SCENARIO("JasmineFS provides the pinned Jasmine 7 distribution") { - constexpr std::array, 5> assets{ - { - {"jasmine.js", fs::generated::JasmineJsData::dataSize}, - {"jasmine-html.js", fs::generated::JasmineHtmlData::dataSize}, - {"jasmine.css", fs::generated::JasmineCssData::dataSize}, - {"boot.js", fs::generated::JasmineBootData::dataSize}, - {"jasmine_favicon.png", fs::generated::JasmineFaviconData::dataSize}, - } - }; - for (const auto& [name, size] : assets) { - WHEN("requesting " << name) { - auto path = std::filesystem::path("jasmine/7.0.2") / name; - path.make_preferred(); - auto file = fs::JasmineFS::open(path); - REQUIRE(file.has_value()); - const auto content = readEmbeddedAsset(*file, size, name != "jasmine_favicon.png"); - if (name == "jasmine_favicon.png") - REQUIRE(content.substr(0, 8) == "\x89PNG\r\n\x1a\n"); - } - } - REQUIRE_FALSE(fs::JasmineFS::open("jasmine/7.0.2/boot0.js")); - REQUIRE_FALSE(fs::JasmineFS::open("jasmine/4.6.0/jasmine.js")); -} diff --git a/test/LifeTests.cpp b/test/LifeTests.cpp deleted file mode 100644 index aeb130a4..00000000 --- a/test/LifeTests.cpp +++ /dev/null @@ -1,51 +0,0 @@ -#include "../examples/life/Life.hpp" -#include - -using webfront::demo::LifeGrid; -using webfront::demo::nextLife; - -SCENARIO("Life generations follow B3/S23 synchronously") { - GIVEN("an empty grid and a stable block") { - REQUIRE(nextLife({}).none()); - LifeGrid block; - for (const auto i : {330, 331, 362, 363}) - block.set(static_cast(i)); - REQUIRE(nextLife(block) == block); - } - GIVEN("a horizontal blinker") { - LifeGrid horizontal, vertical; - for (const auto i : {330, 331, 332}) - horizontal.set(static_cast(i)); - for (const auto i : {299, 331, 363}) - vertical.set(static_cast(i)); - WHEN("two generations are computed") { - REQUIRE(nextLife(horizontal) == vertical); - REQUIRE(nextLife(vertical) == horizontal); - REQUIRE(horizontal.count() == 3); - } - } - GIVEN("a glider") { - LifeGrid grid, translated; - for (const auto i : {1, 34, 64, 65, 66}) - grid.set(static_cast(i)); - for (const auto i : {34, 67, 97, 98, 99}) - translated.set(static_cast(i)); - for (int i = 0; i < 4; ++i) - grid = nextLife(grid); - REQUIRE(grid == translated); - } -} - -SCENARIO("Life wraps both axes without treating adjacent rows as neighbors") { - LifeGrid horizontal, vertical; - for (const auto i : {31, 0, 1}) - horizontal.set(static_cast(i)); - for (const auto i : {992, 0, 32}) - vertical.set(static_cast(i)); - REQUIRE(nextLife(horizontal) == vertical); - REQUIRE(nextLife(vertical) == horizontal); - LifeGrid isolated; - for (const auto i : {30, 31, 34}) - isolated.set(static_cast(i)); - REQUIRE(nextLife(isolated).none()); -} diff --git a/test/ModuleHTTPServerTests.cpp b/test/ModuleHTTPServerTests.cpp deleted file mode 100644 index a0bbe7a7..00000000 --- a/test/ModuleHTTPServerTests.cpp +++ /dev/null @@ -1,113 +0,0 @@ -#include "Mocks.hpp" -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -using namespace webfront; -using namespace webfront::http; -using Net = networking::NetworkingMock; - -namespace { -struct ModuleFile { - static inline std::list names{"modules/main.mjs"}; -}; -constexpr std::array, 9> dependencies{ - { - {"jasmine/7.0.2/jasmine.js", "jasmine/jasmine.js"}, - {"jasmine/7.0.2/jasmine-html.js", "jasmine/jasmine-html.js"}, - {"jasmine/7.0.2/jasmine.css", "jasmine/jasmine.css"}, - {"jasmine/7.0.2/boot.js", "jasmine/boot.js"}, - {"react@19.3.1/runtime.mjs", "react/runtime.mjs"}, - {"babel-standalone@8.0.7/babel.min.js", "babel/babel.min.js"}, - {"webfront/components/terminal/xterm.mjs", "xterm/xterm.mjs"}, - {"webfront/components/terminal/xterm.css", "xterm/xterm.css"}, - {"webfront/components/terminal/addon-fit.mjs", "xterm/addon-fit.mjs"}, - } -}; -} // namespace - -SCENARIO("RequestHandler serves JavaScript modules") { - std::string input{"GET /modules/main.mjs HTTP/1.1\r\nHost: localhost\r\nAccept-encoding: gzip, br, deflate\r\n\r\n"}; - Request request; - REQUIRE_NOTHROW(request.parseSomeData(input.cbegin(), input.cend())); - - RequestHandler> handler{"."}; - auto response = handler.handleRequest(request); - - REQUIRE(response.statusCode == Response::ok); - REQUIRE(response.getHeaderValue("Content-Encoding") == "br"); - REQUIRE(response.getHeaderValue("Content-Type") == "application/javascript"); - REQUIRE(response.getHeaderValue("Content-Length") == "0"); -} - -// WebKit does not advertise Brotli over loopback HTTP. - -SCENARIO("Embedded browser dependencies support gzip-only HTTP clients") { - using Filesystem = fs::Multi; - RequestHandler handler{"."}; - for (const auto& [path, sourceName] : dependencies) { - WHEN("the client requests " << path << " without Brotli support") { - const auto input = std::string("GET /") + std::string(path) + " HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: gzip, deflate\r\n\r\n"; - Request request; - request.parseSomeData(input.begin(), input.end()); - auto response = handler.handleRequest(request); - THEN("the dependency is served using gzip") { - INFO(path); - REQUIRE(response.statusCode == Response::ok); - REQUIRE(response.getHeaderValue("Content-Encoding") == "gzip"); - REQUIRE(response.getHeaderValue("Vary") == "Accept-Encoding"); - REQUIRE(response.getHeaderValue("Content-Length") == std::to_string(response.content.size())); - auto file = Filesystem{"."}.open(path); - REQUIRE(file.has_value()); - std::string expected; - std::array buffer{}; - while (auto count = file->read(buffer)) - expected.append(buffer.data(), count); - REQUIRE(response.content == expected); - REQUIRE(response.getHeaderValue("Content-Type") == (std::string_view(path).ends_with(".css") ? "text/css" : "application/javascript")); - } - } - } -} - -SCENARIO("Embedded browser dependencies support identity-only HTTP clients") { - using Filesystem = fs::Multi; - RequestHandler handler{"."}; - for (const auto& [path, sourceName] : dependencies) { - GIVEN(path) { - const auto sourcePath = std::filesystem::path{__FILE__}.parent_path().parent_path() / "third_party" / sourceName; - std::ifstream source{sourcePath, std::ios::binary}; - REQUIRE(source.is_open()); - const std::string expected{std::istreambuf_iterator{source}, std::istreambuf_iterator{}}; - REQUIRE_FALSE(expected.empty()); - for (const auto accept : {"", "Accept-Encoding: identity\r\n", "Accept-Encoding: gzip;q=0, identity;q=1\r\n"}) { - WHEN("the client requests identity with " << accept) { - const auto input = std::string("GET /") + std::string(path) + " HTTP/1.1\r\nHost: localhost\r\n" + accept + "\r\n"; - Request request; - request.parseSomeData(input.begin(), input.end()); - auto response = handler.handleRequest(request); - THEN("the server returns the upstream bytes with their decoded length") { - REQUIRE(response.statusCode == Response::ok); - REQUIRE_FALSE(response.getHeaderValue("Content-Encoding")); - REQUIRE(response.getHeaderValue("Content-Length") == std::to_string(expected.size())); - REQUIRE(response.content == expected); - REQUIRE(response.getHeaderValue("Content-Type") == (path.ends_with(".css") ? "text/css" : "application/javascript")); - REQUIRE(response.getHeaderValue("Vary") == "Accept-Encoding"); - } - } - } - } - } -} diff --git a/test/ReactFSTests.cpp b/test/ReactFSTests.cpp deleted file mode 100644 index 8b740e54..00000000 --- a/test/ReactFSTests.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "EmbeddedAssetChecks.hpp" -#include - -using namespace webfront; - -SCENARIO("ReactFS provides the local React 19 DOM and automatic JSX runtime") { - GIVEN("the pinned React runtime route") { - auto file = fs::ReactFS::open("/react@19.3.1/runtime.mjs"); - REQUIRE(file.has_value()); - readEmbeddedAsset(*file, fs::generated::ReactRuntimeData::dataSize); - } - THEN("obsolete UMD and unknown module routes are not served") { - REQUIRE_FALSE(fs::ReactFS::open("react@18/umd/react.production.min.js")); - REQUIRE_FALSE(fs::ReactFS::open("react@19.3.1/missing.mjs")); - } -} diff --git a/test/SignalDemoTests.cpp b/test/SignalDemoTests.cpp deleted file mode 100644 index 29efd497..00000000 --- a/test/SignalDemoTests.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include "../test/fixtures/SignalDemo.hpp" -#include -#include - -#include -#include - -SCENARIO("The React signal demo generates a one-second waveform in C++") { - GIVEN("A four-Hertz sine wave at 0.8 volts") { - const auto samples = demo::generateSignal(4, 0.8, 0); - THEN("The buffer has 256 samples and the expected phase and RMS") { - REQUIRE(samples.size() == 256); - REQUIRE(samples[0] == Catch::Approx(0).margin(1e-12)); - REQUIRE(samples[16] == Catch::Approx(0.8)); - REQUIRE(samples[48] == Catch::Approx(-0.8)); - const auto energy = std::inner_product(samples.begin(), samples.end(), samples.begin(), 0.0); - REQUIRE(std::sqrt(energy / 256) == Catch::Approx(0.8 / std::sqrt(2.0))); - } - WHEN("A third harmonic is mixed in") { - const auto mixed = demo::generateSignal(4, 0.8, 0.6); - THEN("The samples contain that harmonic") { - REQUIRE(mixed[16] == Catch::Approx(0.64)); - REQUIRE(mixed != samples); - } - } - } -} - -SCENARIO("The React signal demo rejects invalid parameters") { - GIVEN("Invalid frequencies, amplitudes or harmonic mixes") { - for (const auto frequency : {0.0, 13.0, std::numeric_limits::quiet_NaN()}) - REQUIRE_THROWS_AS(demo::generateSignal(frequency, 0.8, 0.3), std::invalid_argument); - for (const auto amplitude : {0.0, 1.6, std::numeric_limits::infinity()}) - REQUIRE_THROWS_AS(demo::generateSignal(4, amplitude, 0.3), std::invalid_argument); - for (const auto harmonics : {-0.1, 1.1, std::numeric_limits::quiet_NaN()}) - REQUIRE_THROWS_AS(demo::generateSignal(4, 0.8, harmonics), std::invalid_argument); - THEN("The supported boundary values still produce finite samples") { - for (const auto sample : demo::generateSignal(12, 1.5, 1)) - REQUIRE(std::isfinite(sample)); - REQUIRE(demo::generateSignal(1, 0.1, 0).size() == 256); - } - } -} diff --git a/test/TerminalFSTests.cpp b/test/TerminalFSTests.cpp deleted file mode 100644 index 9103317f..00000000 --- a/test/TerminalFSTests.cpp +++ /dev/null @@ -1,90 +0,0 @@ -#include "EmbeddedAssetChecks.hpp" -#include -#include -#include -#include - -#include -#include -#include - -using namespace std; -using namespace webfront; - -namespace { - -string readAll(fs::File& file) { - string content; - array buffer; - while (auto bytesRead = file.read(buffer)) - content.append(buffer.data(), bytesRead); - return content; -} - -string read(auto& filesystem, const string& path) { - auto file = filesystem.open(path); - REQUIRE(file.has_value()); - REQUIRE_FALSE(file->isEncoded()); - return readAll(*file); -} - -} // namespace - -SCENARIO("TerminalFS serves the terminal component under its reserved prefix") { - GIVEN("a TerminalFS") { - fs::TerminalFS terminalFS{filesystem::path{}}; - const string prefix{fs::TerminalFS::prefix}; - - THEN("the page loads the bridge from the root and the component module next to it") { - REQUIRE(prefix + "index.html" == fs::TerminalFS::page); - const auto page = read(terminalFS, string{fs::TerminalFS::page}); - REQUIRE(page.find(R"()") != string::npos); - REQUIRE(page.find(R"(from "./terminal.mjs")") != string::npos); - REQUIRE(page.find(R"(href="xterm.css")") != string::npos); - } - THEN("the component module imports the vendored xterm.js modules") { - const auto module = read(terminalFS, prefix + "terminal.mjs"); - REQUIRE(module.find(R"(from "./xterm.mjs")") != string::npos); - REQUIRE(module.find(R"(from "./addon-fit.mjs")") != string::npos); - } - THEN("the vendored xterm.js and Fit modules and CSS are gzip encoded") { - for (const auto& [name, size] : array, 3>{ - {{"xterm.mjs", fs::generated::XtermModuleData::dataSize}, - {"xterm.css", fs::generated::XtermCssData::dataSize}, - {"addon-fit.mjs", fs::generated::XtermFitAddonData::dataSize}} - }) { - auto file = terminalFS.open(prefix + string{name}); - REQUIRE(file.has_value()); - readEmbeddedAsset(*file, size); - } - } - THEN("each served file has the MIME type the browser needs for modules and styles") { - auto mime = [](const string& path) { - return http::MimeType::fromExtension(filesystem::path{path}.extension().string()).toString(); - }; - REQUIRE(mime(prefix + "index.html") == "text/html"); - REQUIRE(mime(prefix + "terminal.mjs") == "application/javascript"); - REQUIRE(mime(prefix + "xterm.mjs") == "application/javascript"); - REQUIRE(mime(prefix + "xterm.css") == "text/css"); - } - THEN("other paths, including the bare names outside the prefix, are not served") { - REQUIRE_FALSE(terminalFS.open("xterm.mjs").has_value()); - REQUIRE_FALSE(terminalFS.open("index.html").has_value()); - REQUIRE_FALSE(terminalFS.open(prefix + "missing.mjs").has_value()); - REQUIRE_FALSE(terminalFS.open(prefix + "xterm.mjs.map").has_value()); - } - } -} - -SCENARIO("DefaultFSWith adds component assets to the default WebFront filesystem") { - GIVEN("DefaultFSWith without a document root") { - fs::DefaultFSWith filesystem{std::filesystem::path{}}; - - THEN("the terminal page, the protected bridge and the fallback page are all served") { - REQUIRE(filesystem.open(string{fs::TerminalFS::page}).has_value()); - REQUIRE(read(filesystem, "WebFront.js").find("WebFrontBridge") != string::npos); - REQUIRE(filesystem.open("index.html").has_value()); - REQUIRE_FALSE(filesystem.open("unknown.txt").has_value()); - } - } -} diff --git a/test/TerminalTests.cpp b/test/TerminalTests.cpp deleted file mode 100644 index 23e2260e..00000000 --- a/test/TerminalTests.cpp +++ /dev/null @@ -1,268 +0,0 @@ -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; -using namespace webfront; - -namespace { - -// Records the functions a Terminal registers, like BasicWF::cppFunction, and calls them directly. -struct RecordingApp { - map> nullary; - map> unary; - - template - void cppFunction(string name, auto&& function) { - static_assert(is_same_v); - if constexpr (sizeof...(Args) == 0) - nullary.try_emplace(std::move(name), std::forward(function)); - else - unary.try_emplace(std::move(name), std::forward(function)); - } - - string run(const string& line) { - return unary.at("webfront.terminal.run")(line); - } - string complete(const string& line) { - return unary.at("webfront.terminal.complete")(line); - } -}; - -bool contains(const string& text, const string& part) { - return text.find(part) != string::npos; -} - -// A shell with one command per accepted handler shape, plus a throwing one. -struct SampleShell { - terminal::Shell shell; - vector received; - - SampleShell() { - shell.command("greet", "Greet someone", terminal::adaptHandler([](CommandArgs args) { - return "Hello, " + (args.empty() ? string{"world"} : args[0]) + "!"; - })); - shell.command("record", "Record its arguments", terminal::adaptHandler([this](CommandArgs args) { - received.assign(args.begin(), args.end()); - })); - shell.command("lines", "Write two lines", terminal::adaptHandler([](CommandArgs, ostream& output) { - output << "one\ntwo"; - })); - shell.command("answer", "No argument", terminal::adaptHandler([] { - return 42; - })); - shell.command("fail", "Throw", terminal::adaptHandler([](CommandArgs) -> string { - throw runtime_error("command failed"); - })); - } - SampleShell(const SampleShell&) = delete; - SampleShell& operator=(const SampleShell&) = delete; -}; - -} // namespace - -SCENARIO("Terminal lines are split into words") { - GIVEN("lines with whitespace, quotes and escapes") { - auto [line, words] = GENERATE(table>({ - { " greet \t Ada ", {"greet", "Ada"}}, // whitespace runs separate words - { "", {}}, // an empty line has no word - { " ", {}}, // nor has a blank one - {R"(say "hello world" 'a b')", {"say", "hello world", "a b"}}, - { R"(x "" y)", {"x", "", "y"}}, // empty quotes give an empty word - { R"(pre"fix"post)", {"prefixpost"}}, // quotes join adjacent text - { R"(a\ b)", {"a b"}}, // a backslash escapes outside quotes, - { R"("say \"hi\"")", {R"(say "hi")"}}, // inside double quotes, - { R"('a\b')", {R"(a\b)"}}, // but not inside single quotes - })); - THEN("the line '" + line + "' is split as expected") { - REQUIRE(terminal::tokenize(line) == words); - } - } - GIVEN("malformed lines") { - auto line = GENERATE(string{R"(say "hello)"}, string{"say 'hello"}, string{R"(say \)"}, string{R"("a\)"}); - THEN("an unterminated quote or a trailing backslash is rejected: " + line) { - REQUIRE_THROWS_AS(terminal::tokenize(line), invalid_argument); - } - } -} - -SCENARIO("The terminal shell runs commands of every accepted handler shape") { - GIVEN("a shell with sample commands") { - SampleShell sample; - auto& shell = sample.shell; - - THEN("a returning command's result is its output") { - REQUIRE(shell.run("greet Ada") == "Hello, Ada!"); - REQUIRE(shell.run("greet") == "Hello, world!"); - REQUIRE(shell.run("answer ignored") == "42"); - } - THEN("the command receives its arguments without its name") { - REQUIRE(shell.run("record 'a b' c").empty()); - REQUIRE(sample.received == vector{"a b", "c"}); - } - THEN("written line breaks become terminal line breaks") { - REQUIRE(shell.run("lines") == "one\r\ntwo"); - } - THEN("an empty line produces no output") { - REQUIRE(shell.run("").empty()); - REQUIRE(shell.run(" ").empty()); - } - } -} - -SCENARIO("The terminal shell reports failing lines") { - GIVEN("a shell with sample commands") { - SampleShell sample; - auto& shell = sample.shell; - - THEN("an unknown command or a malformed line produces an error message, not an exception") { - const auto unknown = shell.run("nope"); - REQUIRE(contains(unknown, "Unknown command 'nope'")); - REQUIRE(unknown.starts_with("\x1b[31m")); - REQUIRE(contains(shell.run(R"(greet "Ada)"), "Unterminated quote")); - } - THEN("a command's exception propagates, so the JavaScript Promise rejects") { - REQUIRE_THROWS_AS(shell.run("fail"), runtime_error); - } - } -} - -SCENARIO("The terminal shell completes and documents its commands") { - GIVEN("a shell with sample commands") { - SampleShell sample; - auto& shell = sample.shell; - - THEN("command names complete by prefix, in order") { - REQUIRE(shell.complete("") == "answer\nfail\ngreet\nlines\nrecord"); - REQUIRE(shell.complete("gr") == "greet"); - REQUIRE(shell.complete("zz").empty()); - } - THEN("arguments are not completed") { - REQUIRE(shell.complete("greet A").empty()); - } - THEN("help lists every command with its aligned description") { - REQUIRE(shell.help() - == "answer No argument\n" - "fail Throw\n" - "greet Greet someone\n" - "lines Write two lines\n" - "record Record its arguments"); - } - } -} - -SCENARIO("The terminal shell rejects invalid registrations") { - GIVEN("a shell with sample commands") { - SampleShell sample; - auto& shell = sample.shell; - - THEN("a duplicate or malformed name is rejected") { - auto name = GENERATE(string{"greet"}, string{""}, string{"two words"}, string{"quo'te"}); - REQUIRE_THROWS_AS(shell.command(name, "rejected", terminal::adaptHandler([] {})), invalid_argument); - } - THEN("a command without a handler is rejected") { - REQUIRE_THROWS_AS(shell.command("ok", "no handler", terminal::Shell::Handler{}), invalid_argument); - REQUIRE(shell.complete("ok").empty()); - } - } -} - -SCENARIO("Terminal output is capped below the bridge's string limit") { - GIVEN("a command writing more than the limit, ending in multi-byte characters") { - terminal::Shell shell; - shell.command("flood", "Too much output", terminal::adaptHandler([] { - string text(terminal::maxOutputBytes - 1, 'x'); - for (int index = 0; index < 10; ++index) - text += "\xc3\xa9"; // U+00E9, two bytes - return text; - })); - - WHEN("it runs") { - const auto output = shell.run("flood"); - THEN("the output fits a 16-bit length and ends with a notice") { - REQUIRE(output.size() < 65536); - REQUIRE(output.ends_with("[output truncated]\x1b[0m")); - } - THEN("it is cut before the first character that would not fit whole") { - REQUIRE(output.substr(0, terminal::maxOutputBytes - 1) == string(terminal::maxOutputBytes - 1, 'x')); - REQUIRE(output[terminal::maxOutputBytes - 1] == '\r'); - } - } - } -} - -SCENARIO("Terminal error messages are capped below the bridge's string limit") { - GIVEN("a shell and an unknown command name as long as the largest bridge string") { - terminal::Shell shell; - const string name(65535, 'x'); - - WHEN("it runs") { - const auto output = shell.run(name); - THEN("the diagnostic fits a 16-bit length and is marked as truncated") { - REQUIRE(output.size() < 65536); - REQUIRE(contains(output, "[output truncated]")); - } - THEN("the diagnostic keeps its colors") { - REQUIRE(output.starts_with("\x1b[31mUnknown command 'xxx")); - REQUIRE(output.ends_with("\x1b[0m")); - } - } - } -} - -SCENARIO("Terminal registers its bridge functions and built-in commands on the application") { - GIVEN("a terminal on an application") { - RecordingApp app; - auto terminal = make_unique>(app, TerminalOptions{.prompt = "demo> ", .banner = "Welcome"}); - terminal->command("greet", "Greet someone", [](CommandArgs args) { - return "Hello, " + args[0] + "!"; - }); - - THEN("the page reads the configured prompt and banner") { - REQUIRE(app.nullary.at("webfront.terminal.prompt")() == "demo> "); - REQUIRE(app.nullary.at("webfront.terminal.banner")() == "Welcome"); - } - THEN("lines run registered commands and complete their names") { - REQUIRE(app.run("greet Ada") == "Hello, Ada!"); - REQUIRE(app.complete("g") == "greet"); - } - THEN("help and clear are built in") { - REQUIRE(contains(app.run("help"), "greet Greet someone")); - REQUIRE(contains(app.run("help"), "clear ")); - REQUIRE(app.run("clear") == Terminal::clearScreen); - } - THEN("a duplicate command is rejected") { - REQUIRE_THROWS_AS(terminal->command("help", "again", [] {}), invalid_argument); - } - THEN("the page lists no extension module by default") { - REQUIRE(app.nullary.at("webfront.terminal.extensions")().empty()); - } - WHEN("extension modules are added, one of them twice") { - terminal->extension("/a.mjs").extension("/b/c.mjs").extension("/a.mjs"); - THEN("the page lists each once, in order") { - REQUIRE(app.nullary.at("webfront.terminal.extensions")() == "/a.mjs\n/b/c.mjs"); - } - } - THEN("an empty or multi-line extension URL is rejected") { - auto url = GENERATE(string{}, string{"/a.mjs\n/b.mjs"}, string{"/a.mjs\r"}); - REQUIRE_THROWS_AS(terminal->extension(url), invalid_argument); - REQUIRE(app.nullary.at("webfront.terminal.extensions")().empty()); - } - WHEN("the Terminal object is destroyed") { - terminal.reset(); - THEN("the registered functions still own the commands") { - REQUIRE(app.run("greet Ada") == "Hello, Ada!"); - REQUIRE(contains(app.run("help"), "greet")); - } - } - } -} diff --git a/test/ToolManagerTests.cpp b/test/ToolManagerTests.cpp deleted file mode 100644 index fba5899e..00000000 --- a/test/ToolManagerTests.cpp +++ /dev/null @@ -1,306 +0,0 @@ -#include "TemporaryDirectory.hpp" -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; -using namespace webfront; -using webfront::test::TemporaryDirectory; - -namespace { - -// The project directory of the tools, chosen by each test. -struct TestProject { - static inline filesystem::path directory; - static filesystem::path get() { - return directory; - } -}; - -using TestPackageFS = fs::BasicPackageFS; - -// Records the functions registered on it, like BasicWF::cppFunction, and calls them directly. -struct RecordingApp { - map functions; - - template - void cppFunction(string name, auto&& function) { - functions.try_emplace(std::move(name), std::function(std::forward(function))); - } - - template - R call(const string& name, Args... args) { - return any_cast&>(functions.at(name))(std::move(args)...); - } - - string run(const string& line) { - return call("webfront.terminal.run", line); - } -}; - -vector bytes(string_view text) { - return {text.begin(), text.end()}; -} - -optional served(TestPackageFS& packages, const filesystem::path& path) { - auto file = packages.open(path); - if (!file) - return nullopt; - string content; - array buffer{}; - while (!file->eof()) - content.append(buffer.data(), file->read(buffer)); - return content; -} - -bool contains(const string& text, const string& part) { - return text.find(part) != string::npos; -} - -} // namespace - -SCENARIO("The tool manager installs tools through its bridge functions") { - GIVEN("a terminal with a tool manager on an application") { - TemporaryDirectory project; - TestProject::directory = project.path(); - RecordingApp app; - Terminal terminal{app}; - auto manager = make_unique>(app, terminal); - REQUIRE(manager->store().projectDir() == project.path()); - - WHEN("the page installs a tool in two chunks") { - app.call("webfront.pkg.begin", "@acme/plot", "1.2.0"); - app.call>("webfront.pkg.writeFile", - "@acme/plot", - "1.2.0", - "dist/index.html", - 0, - bytes("

    pl")); - app.call>("webfront.pkg.writeFile", - "@acme/plot", - "1.2.0", - "dist/index.html", - 5, - bytes("ot

    ")); - app.call("webfront.pkg.commit", "@acme/plot", "1.2.0", "sha512-abc", "dist/index.html", "Live plot"); - - THEN("the page lists it with the URL of its entry") { - REQUIRE(app.call("webfront.pkg.list", 0) == "@acme/plot\t1.2.0\t/webfront/tools/@acme/plot/dist/index.html\tLive plot\n"); - } - THEN("wf list shows it") { - REQUIRE(app.run("wf list") == "@acme/plot@1.2.0 Live plot"); - } - THEN("PackageFS serves its files") { - TestPackageFS packages{"ignored"}; - REQUIRE(served(packages, "webfront/tools/@acme/plot/dist/index.html") == "

    plot

    "); - REQUIRE(served(packages, "/webfront/tools/@acme/plot/dist/index.html") == "

    plot

    "); - } - AND_WHEN("wf remove uninstalls it") { - REQUIRE(app.run("wf remove @acme/plot") == "Removed @acme/plot."); - THEN("it is no longer listed nor served") { - REQUIRE(app.run("wf list") == "No tool installed."); - REQUIRE(app.call("webfront.pkg.list", 0).empty()); - TestPackageFS packages{"ignored"}; - REQUIRE_FALSE(served(packages, "webfront/tools/@acme/plot/dist/index.html")); - } - } - AND_WHEN("the ToolManager object is destroyed") { - manager.reset(); - THEN("the registered functions still own the store") { - REQUIRE(contains(app.run("wf list"), "@acme/plot@1.2.0")); - } - } - } - } -} - -SCENARIO("Installed tools are listed with URLs the HTTP server resolves") { - GIVEN("a terminal with a tool manager on an application") { - TemporaryDirectory project; - TestProject::directory = project.path(); - RecordingApp app; - Terminal terminal{app}; - ToolManager manager{app, terminal}; - - WHEN("a tool whose entry needs escaping in a URL is installed") { - const string entry = "dist/a+b c%41\xc3\xa9#[].html"; - app.call("webfront.pkg.begin", "logs", "1.0.0"); - app.call>("webfront.pkg.writeFile", "logs", "1.0.0", entry, 0, bytes("

    logs

    ")); - app.call("webfront.pkg.commit", "logs", "1.0.0", "", entry, "Logs"); - THEN("its listed URL is absolute, encoded, and leads the server to the file") { - const auto list = app.call("webfront.pkg.list", 0); - const auto url = list.substr(list.find("logs\t1.0.0\t") + 11); - REQUIRE(url.starts_with("/webfront/tools/logs/dist/a%2Bb%20c%2541%C3%A9%23%5B%5D.html\t")); - TestPackageFS packages{"ignored"}; - REQUIRE(served(packages, uri::decode(url.substr(0, url.find('\t')))) == "

    logs

    "); - http::RequestHandler handler{"."}; - http::Request request; - request.method = http::Request::Method::Get; - request.uri = url.substr(0, url.find('\t')); - REQUIRE(handler.handleRequest(request).statusCode == http::Response::ok); - } - } - } -} - -SCENARIO("The tool manager rejects malformed calls and commands") { - GIVEN("a terminal with a tool manager on an application") { - TemporaryDirectory project; - TestProject::directory = project.path(); - RecordingApp app; - Terminal terminal{app}; - ToolManager manager{app, terminal}; - - THEN("a negative, fractional or too large offset is rejected") { - app.call("webfront.pkg.begin", "plot", "1.0.0"); - for (const double offset : {-1.0, 0.5, 1e300, numeric_limits::infinity(), numeric_limits::quiet_NaN()}) - REQUIRE_THROWS_AS( - (app.call>("webfront.pkg.writeFile", "plot", "1.0.0", "a.js", offset, bytes("x"))), - invalid_argument); - } - THEN("wf documents itself and rejects malformed commands") { - REQUIRE(contains(app.run("help"), "Manage web tools: wf search | install | list | open | remove")); - for (const auto* command : {"wf search [term]", "wf install [@version]", "wf list", "wf open ", "wf remove "}) - REQUIRE(contains(app.run("wf"), command)); - REQUIRE(app.run("wf help") == app.run("wf")); - REQUIRE_THROWS_AS(app.run("wf frobnicate"), invalid_argument); - REQUIRE_THROWS_AS(app.run("wf remove"), invalid_argument); - REQUIRE_THROWS_AS(app.run("wf remove a b"), invalid_argument); - REQUIRE_THROWS_AS(app.run("wf list all"), invalid_argument); - REQUIRE_THROWS_AS(app.run("wf remove plot"), invalid_argument); - REQUIRE_THROWS_AS(app.run("wf remove ../x"), invalid_argument); - } - THEN("the commands of the page explain that it did not load its module when they reach C++") { - for (const auto* line : {"wf search", "wf install plot", "wf open plot"}) - REQUIRE_THROWS_WITH(app.run(line), Catch::Matchers::ContainsSubstring("webfront/components/tools/wf.mjs")); - } - THEN("the terminal page loads the browser module and reads the default registry") { - REQUIRE(app.call("webfront.terminal.extensions") == "/webfront/components/tools/wf.mjs"); - REQUIRE(app.call("webfront.pkg.registry") == "https://registry.npmjs.org/"); - } - } -} - -SCENARIO("The registry of the tool manager is configurable") { - GIVEN("a tool manager with a local registry") { - TemporaryDirectory project; - TestProject::directory = project.path(); - RecordingApp app; - Terminal terminal{app}; - ToolManager manager{app, terminal, {.registry = "/registry/"}}; - THEN("the page reads it") { - REQUIRE(app.call("webfront.pkg.registry") == "/registry/"); - } - } -} - -SCENARIO("The tool list is paged below the bridge's string limit") { - GIVEN("more tools with long titles than one bridge string can carry") { - TemporaryDirectory project; - TestProject::directory = project.path(); - RecordingApp app; - Terminal terminal{app}; - ToolManager manager{app, terminal}; - constexpr size_t toolCount = 70; - for (size_t index = 0; index < toolCount; ++index) { - const auto name = "tool" + to_string(index); - manager.store().begin(name, "1.0.0"); - manager.store().write(name, "1.0.0", {.path = "index.html", .offset = 0, .bytes = bytes("x")}); - manager.store().commit({.name = name, .version = "1.0.0", .entry = "index.html", .title = string(1024, 't')}); - } - - WHEN("the page reads the list from index 0 until an empty page") { - vector lines; - size_t pages = 0; - for (string page = app.call("webfront.pkg.list", 0); !page.empty(); - page = app.call("webfront.pkg.list", static_cast(lines.size()))) { - REQUIRE(page.size() <= tools::detail::maxListBytes); - REQUIRE(page.ends_with('\n')); - for (size_t start = 0, end = page.find('\n'); end != string::npos; start = end + 1, end = page.find('\n', start)) - lines.push_back(page.substr(0, page.find('\t', start)).substr(start)); - ++pages; - } - THEN("every tool is listed once, over several pages") { - REQUIRE(pages > 1); - REQUIRE(lines.size() == toolCount); - REQUIRE(set(lines.begin(), lines.end()).size() == toolCount); - } - } - THEN("an index past the end gives an empty page and an invalid index is rejected") { - REQUIRE(app.call("webfront.pkg.list", toolCount).empty()); - REQUIRE_THROWS_AS((app.call("webfront.pkg.list", -1)), invalid_argument); - } - } -} - -SCENARIO("PackageFS serves only the files of installed tools") { - GIVEN("a project with one installed tool and a file outside it") { - TemporaryDirectory project; - TestProject::directory = project.path(); - fs::ToolStore store{project.path()}; - store.begin("plot", "1.0.0"); - store.write("plot", "1.0.0", {.path = "index.html", .offset = 0, .bytes = bytes("

    plot

    ")}); - store.write("plot", "1.0.0", {.path = "assets/app.js", .offset = 0, .bytes = bytes("go()")}); - store.commit({.name = "plot", .version = "1.0.0", .entry = "index.html"}); - ofstream(project.path() / "secret.txt") << "secret"; - TestPackageFS packages{"ignored"}; - - THEN("files of the installed version are served, also in subdirectories") { - REQUIRE(served(packages, "webfront/tools/plot/index.html") == "

    plot

    "); - REQUIRE(served(packages, "webfront/tools/plot/assets/app.js") == "go()"); - } - THEN("missing files, directories, unknown tools and other prefixes are not served") { - REQUIRE_FALSE(served(packages, "webfront/tools/plot/missing.js")); - REQUIRE_FALSE(served(packages, "webfront/tools/plot/assets")); - REQUIRE_FALSE(served(packages, "webfront/tools/other/index.html")); - REQUIRE_FALSE(served(packages, "webfront/tools/plot")); - REQUIRE_FALSE(served(packages, "webfront/tools/@scope")); - REQUIRE_FALSE(served(packages, "tools/plot/index.html")); - } - THEN("paths escaping the tool are not served") { - REQUIRE_FALSE(served(packages, "webfront/tools/plot/../../../secret.txt")); - REQUIRE_FALSE(served(packages, "webfront/tools/plot/./index.html")); - REQUIRE_FALSE(served(packages, "webfront/tools/../../secret.txt")); - } - WHEN("the lock file becomes malformed") { - ofstream(project.path() / "webfront-tools.lock.json") << "{"; - THEN("nothing is served") { - REQUIRE_FALSE(served(packages, "webfront/tools/plot/index.html")); - } - } - } -} - -SCENARIO("ToolsApp serves installed tools after the protected bridge script") { - GIVEN("the filesystem of ToolsApp") { - fs::DefaultFSWith files{""}; - THEN("the bridge script, the terminal, the tool manager module and the fallback page are served") { - REQUIRE(files.open("WebFront.js")); - REQUIRE(files.open(fs::TerminalFS::page)); - REQUIRE(files.open(fs::ToolManagerFS::module)); - REQUIRE_FALSE(files.open(string(fs::ToolManagerFS::prefix) + "other.mjs")); - REQUIRE(files.open("index.html")); - } - THEN("an unknown tool falls through to the next providers") { - REQUIRE_FALSE(files.open("webfront/tools/none/index.html")); - } - } -} diff --git a/test/ToolStoreTests.cpp b/test/ToolStoreTests.cpp deleted file mode 100644 index 4d505143..00000000 --- a/test/ToolStoreTests.cpp +++ /dev/null @@ -1,532 +0,0 @@ -#include "TemporaryDirectory.hpp" -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; -using namespace webfront; -using webfront::test::TemporaryDirectory; - -namespace { - -vector bytes(string_view text) { - return {text.begin(), text.end()}; -} - -string contentOf(const filesystem::path& file) { - ifstream stream(file, ios::binary); - ostringstream content; - content << stream.rdbuf(); - return content.str(); -} - -fs::ToolRecord plotRecord(string version = "1.2.0") { - return {.name = "@acme/plot", .version = std::move(version), .integrity = "sha512-abc", .entry = "dist/index.html", .title = "Live plot"}; -} - -void install(fs::ToolStore& store, const fs::ToolRecord& record, string_view page = "

    plot

    ") { - store.begin(record.name, record.version); - store.write(record.name, record.version, {.path = record.entry, .offset = 0, .bytes = bytes(page)}); - store.commit(record); -} - -} // namespace - -SCENARIO("Package names, versions and paths from the browser are validated") { - GIVEN("valid npm names, versions and package paths") { - auto name = GENERATE("plot", "webfront-plot", "@acme/plot", "a.b_c~d"); - THEN("they are accepted") { - REQUIRE_NOTHROW(fs::tools::validatePackageName(name)); - REQUIRE_NOTHROW(fs::tools::validateVersion("1.2.0-beta.1+build.5")); - REQUIRE(fs::tools::safeRelativePath("dist/assets/app.js") == filesystem::path("dist") / "assets" / "app.js"); - } - } - GIVEN("names that could leave the tools directory or are not npm names") { - auto name = GENERATE("", - ".", - "..", - "../x", - "@acme", - "@acme/", - "@/plot", - "@acme/../x", - "@acme/a/b", - "Plot", - "_plot", - "a b", - "a\\b", - "a..b", - "@acme/a..b", - "@a..b/c"); - THEN("they are rejected") { - REQUIRE_THROWS_AS(fs::tools::validatePackageName(name), invalid_argument); - } - } - GIVEN("names and versions longer than npm accepts") { - THEN("they are rejected") { - REQUIRE_THROWS_AS(fs::tools::validatePackageName(string(215, 'a')), invalid_argument); - REQUIRE_THROWS_AS(fs::tools::validateVersion("1" + string(256, '0')), invalid_argument); - } - } - GIVEN("invalid versions") { - auto version = GENERATE("", "..", "v1.0.0", "1.0/0", "1.0 0", "1..0"); - THEN("they are rejected") { - REQUIRE_THROWS_AS(fs::tools::validateVersion(version), invalid_argument); - } - } - GIVEN("unsafe paths") { - auto path = GENERATE(as{}, - "", - "/etc/passwd", - "../x", - "a/../../x", - "a/./b", - "a//b", - "a/", - "..", - "C:/x", - "c:x", - "a\\..\\b", - "a?.js", - "a*.js", - "ab", - "a|b", - "a\"b", - "main..html", - "a/b..c/d", - string("a\0b", 3)); - THEN("they are rejected") { - REQUIRE_THROWS_AS(fs::tools::safeRelativePath(path), invalid_argument); - } - } -} - -SCENARIO("The lock file is read and written as JSON") { - GIVEN("two installed tools") { - fs::tools::LockedTools tools; - tools.emplace("@acme/plot", plotRecord()); - tools.emplace("logs", fs::ToolRecord{.name = "logs", .version = "0.1.0", .integrity = "", .entry = "index.html", .title = "Say \"hi\" \\o/"}); - - WHEN("they are formatted and parsed back") { - const auto json = fs::tools::formatLock(tools); - THEN("the same records are read, sorted by name") { - REQUIRE(json.starts_with("{\n \"lockfileVersion\": 1,\n \"tools\": {\n \"@acme/plot\": {")); - REQUIRE(fs::tools::parseLock(json) == tools); - } - } - } - GIVEN("no tool") { - THEN("an empty lock file round-trips") { - REQUIRE(fs::tools::parseLock(fs::tools::formatLock({})).empty()); - } - } - GIVEN("a lock file edited by hand, with unknown members and escapes") { - const auto json = R"({"other": [1, true, null, {"a": "b"}], "tools": {"plot": {"version": "1.0.0", "extra": 3, - "entry": "index.html", "title": "\u00e9\ud83d\ude00\/"}}})"; - THEN("the unknown members are skipped and the escapes decoded") { - const auto tools = fs::tools::parseLock(json); - REQUIRE(tools.at("plot").version == "1.0.0"); - REQUIRE(tools.at("plot").title == "\xc3\xa9\xf0\x9f\x98\x80/"); - } - } - GIVEN("empty arrays and objects among the unknown members") { - THEN("they are skipped") { - REQUIRE(fs::tools::parseLock(R"({"a": [], "b": {}, "c": [[]], "tools": {}})").empty()); - } - } - GIVEN("every escape of the JSON grammar") { - json::Reader reader{R"("\"\\\/\b\f\n\r\t\u20AC\u0041")"}; - THEN("each one is decoded") { - REQUIRE(reader.string() - == "\"\\/\b\f\n\r\t\xe2\x82\xac" - "A"); - } - } -} - -SCENARIO("The lock file reader is strict") { - GIVEN("malformed JSON") { - auto json = GENERATE("", - "{", - R"({"tools": {"plot": {"version": "1.0.0"}})", - R"({"tools": 1} x)", - R"({"tools": {"p": {"title": "\x"}}})", - R"({"tools": {"p": {"title": "\ud800"}}})", - R"({"tools": {"p": {"title": "\udc00"}}})", - R"({"tools": {"p": {"title": "\ud800\u0041"}}})", - R"({"tools": {"p": {"title": "\u12G4"}}})", - R"({"tools": {"p": {"title": "\u12"}}})", - R"({"other": [1, }})", - R"({"other": 1} x)", - R"({"other": "abc)", - R"({"tools": {"p": {"x": }}})", - R"({"tools": {}, "other": garbage})", - R"({"tools": {}, "lockfileVersion": 1e+})", - R"({"a": 01})", - R"({"a": -})", - R"({"a": 1.})", - R"({"a": .5})", - R"({"a": +1})", - R"({"a": 1e})", - R"({"a": tru})", - R"({"a": nulls})", - "{\"tools\": {\"p\": {\"title\": \"a\nb\"}}}"); - THEN("parsing throws") { - REQUIRE_THROWS(fs::tools::parseLock(json)); - } - } - GIVEN("numbers and literals of the JSON grammar among the unknown members") { - const auto json = R"({"a": -0.5e+10, "b": 1E5, "c": 0, "d": true, "e": false, "f": null, "g": 12.25, "h": -0, "i": 3e-2, "tools": {}})"; - THEN("they are skipped") { - REQUIRE(fs::tools::parseLock(json).empty()); - } - } - GIVEN("strings with control characters") { - THEN("quoting escapes them") { - REQUIRE(json::quote("a\nb\x01") == R"("a\u000ab\u0001")"); - } - } - GIVEN("a record pointing outside the tools directory or breaking the listing") { - auto json = GENERATE(R"({"tools": {"../x": {"version": "1.0.0", "entry": "index.html"}}})", - R"({"tools": {"plot": {"version": "../1", "entry": "index.html"}}})", - R"({"tools": {"plot": {"version": "1.0.0", "entry": "../../secret"}}})", - R"({"tools": {"plot": {"version": "1.0.0", "entry": "index.html", "title": "a\nb"}}})", - R"({"tools": {"plot": {"version": "1.0.0", "entry": "index.html", "integrity": "a\tb"}}})"); - THEN("parsing rejects it") { - REQUIRE_THROWS_AS(fs::tools::parseLock(json), invalid_argument); - } - } -} - -SCENARIO("A tool store installs tools in its project directory") { - GIVEN("an empty project") { - TemporaryDirectory project; - fs::ToolStore store{project.path()}; - REQUIRE(store.installed().empty()); - - WHEN("a tool is installed in several chunks") { - store.begin("@acme/plot", "1.2.0"); - store.write("@acme/plot", "1.2.0", {.path = "dist/index.html", .offset = 0, .bytes = bytes("

    ")}); - store.write("@acme/plot", "1.2.0", {.path = "dist/index.html", .offset = 3, .bytes = bytes("plot

    ")}); - store.write("@acme/plot", "1.2.0", {.path = "package.json", .offset = 0, .bytes = bytes("{}")}); - store.commit(plotRecord()); - - THEN("its files are in its version directory and the lock file records it") { - const auto directory = project.path() / ".webfront" / "tools" / "@acme" / "plot@1.2.0"; - REQUIRE(store.installDir("@acme/plot", "1.2.0") == directory); - REQUIRE(contentOf(directory / "dist" / "index.html") == "

    plot

    "); - REQUIRE(contentOf(directory / "package.json") == "{}"); - REQUIRE(store.find("@acme/plot") == plotRecord()); - REQUIRE(fs::ToolStore::readLock(project.path() / "webfront-tools.lock.json").size() == 1); - REQUIRE_FALSE(filesystem::exists(project.path() / "webfront-tools.lock.json.tmp")); - } - AND_WHEN("another version is installed") { - install(store, plotRecord("2.0.0"), "

    v2

    "); - THEN("it replaces the previous one") { - REQUIRE(store.find("@acme/plot")->version == "2.0.0"); - REQUIRE_FALSE(filesystem::exists(store.installDir("@acme/plot", "1.2.0"))); - REQUIRE(contentOf(store.installDir("@acme/plot", "2.0.0") / "dist" / "index.html") == "

    v2

    "); - } - } - AND_WHEN("the same version is installed again") { - install(store, plotRecord(), "

    again

    "); - THEN("its files are replaced") { - REQUIRE(contentOf(store.installDir("@acme/plot", "1.2.0") / "dist" / "index.html") == "

    again

    "); - } - } - AND_WHEN("it is removed") { - REQUIRE(store.remove("@acme/plot")); - THEN("its files and its lock entry are gone") { - REQUIRE_FALSE(filesystem::exists(store.installDir("@acme/plot", "1.2.0"))); - REQUIRE(store.installed().empty()); - REQUIRE_FALSE(store.remove("@acme/plot")); - } - } - } - } -} - -SCENARIO("A tool store rejects inconsistent installations") { - GIVEN("a project with an installation in progress") { - TemporaryDirectory project; - fs::ToolStore store{project.path()}; - store.begin("plot", "1.0.0"); - store.write("plot", "1.0.0", {.path = "index.html", .offset = 0, .bytes = bytes("abc")}); - - THEN("a chunk that does not follow the written bytes is rejected") { - REQUIRE_THROWS_AS(store.write("plot", "1.0.0", {.path = "index.html", .offset = 2, .bytes = bytes("x")}), invalid_argument); - REQUIRE_THROWS_AS(store.write("plot", "1.0.0", {.path = "missing.js", .offset = 1, .bytes = bytes("x")}), invalid_argument); - } - THEN("a file that cannot be written is reported") { - store.write("plot", "1.0.0", {.path = "dir/file.js", .offset = 0, .bytes = bytes("x")}); - REQUIRE_THROWS_AS(store.write("plot", "1.0.0", {.path = "dir", .offset = 0, .bytes = bytes("x")}), runtime_error); - } - THEN("an unsafe path is rejected") { - REQUIRE_THROWS_AS(store.write("plot", "1.0.0", {.path = "../escape.js", .offset = 0, .bytes = bytes("x")}), invalid_argument); - REQUIRE_FALSE(filesystem::exists(project.path() / ".webfront" / "tools" / ".staging" / "escape.js")); - } - THEN("writing or committing a version that was not begun is rejected") { - REQUIRE_THROWS_AS(store.write("plot", "2.0.0", {.path = "index.html", .offset = 0, .bytes = bytes("x")}), invalid_argument); - REQUIRE_THROWS_AS(store.commit({.name = "plot", .version = "2.0.0", .entry = "index.html"}), invalid_argument); - } - THEN("a lock file that cannot be written fails the commit") { - filesystem::create_directories(project.path() / "webfront-tools.lock.json.tmp"); - REQUIRE_THROWS_AS(store.commit({.name = "plot", .version = "1.0.0", .entry = "index.html"}), runtime_error); - } - THEN("a title or integrity longer than 1024 bytes is rejected") { - REQUIRE_THROWS_AS(store.commit({.name = "plot", .version = "1.0.0", .entry = "index.html", .title = string(1025, 't')}), invalid_argument); - REQUIRE_THROWS_AS(store.commit({.name = "plot", .version = "1.0.0", .integrity = string(1025, 'i'), .entry = "index.html"}), invalid_argument); - REQUIRE_NOTHROW(store.commit({.name = "plot", .version = "1.0.0", .entry = "index.html", .title = string(1024, 't')})); - } - THEN("a title or integrity with control characters is rejected") { - REQUIRE_THROWS_AS(store.commit({.name = "plot", .version = "1.0.0", .entry = "index.html", .title = "two\nlines"}), invalid_argument); - REQUIRE_THROWS_AS(store.commit({.name = "plot", .version = "1.0.0", .integrity = "a\tb", .entry = "index.html"}), invalid_argument); - REQUIRE(store.installed().empty()); - } - THEN("a commit whose entry page was not written is rejected") { - REQUIRE_THROWS_AS(store.commit({.name = "plot", .version = "1.0.0", .entry = "missing.html"}), invalid_argument); - REQUIRE(store.installed().empty()); - } - WHEN("the installation is committed") { - store.commit({.name = "plot", .version = "1.0.0", .entry = "index.html"}); - THEN("it cannot be committed or written again without a new begin") { - REQUIRE_THROWS_AS(store.commit({.name = "plot", .version = "1.0.0", .entry = "index.html"}), invalid_argument); - REQUIRE_THROWS_AS(store.write("plot", "1.0.0", {.path = "index.html", .offset = 0, .bytes = bytes("x")}), invalid_argument); - } - } - } -} - -SCENARIO("A tool store refuses lock files it cannot read") { - GIVEN("a lock file that exists but cannot be read") { - TemporaryDirectory project; - const auto lockFile = project.path() / "webfront-tools.lock.json"; - filesystem::create_directory(lockFile); - fs::ToolStore store{project.path()}; - THEN("reading the installed tools fails instead of reporting none") { - REQUIRE_THROWS_AS(store.installed(), runtime_error); - } - THEN("an installation fails without replacing the lock file") { - store.begin("plot", "1.0.0"); - store.write("plot", "1.0.0", {.path = "index.html", .offset = 0, .bytes = bytes("x")}); - REQUIRE_THROWS_AS(store.commit({.name = "plot", .version = "1.0.0", .entry = "index.html"}), runtime_error); - REQUIRE(filesystem::is_directory(lockFile)); - } - } - -#ifndef _WIN32 - GIVEN("a lock file without read permission") { - TemporaryDirectory project; - const auto lockFile = project.path() / "webfront-tools.lock.json"; - ofstream(lockFile) << R"({"tools": {"logs": {"version": "1.0.0", "entry": "index.html"}}})"; - filesystem::permissions(lockFile, filesystem::perms::none); - const bool readable = ifstream(lockFile).is_open(); // e.g. when the tests run as root - fs::ToolStore store{project.path()}; - THEN("an installation fails instead of dropping the recorded tools") { - store.begin("plot", "1.0.0"); - store.write("plot", "1.0.0", {.path = "index.html", .offset = 0, .bytes = bytes("x")}); - if (!readable) - REQUIRE_THROWS_AS(store.commit({.name = "plot", .version = "1.0.0", .entry = "index.html"}), runtime_error); - filesystem::permissions(lockFile, filesystem::perms::owner_read | filesystem::perms::owner_write); - REQUIRE(store.find("logs")); - } - } -#endif - GIVEN("a malformed lock file") { - TemporaryDirectory project; - ofstream(project.path() / "webfront-tools.lock.json") << "{ not json"; - fs::ToolStore store{project.path()}; - THEN("reading the installed tools reports it") { - REQUIRE_THROWS_AS(store.installed(), runtime_error); - } - } -} - -SCENARIO("A tool store keeps the installed version when a replacement does not complete") { - GIVEN("a project with an installed tool") { - TemporaryDirectory project; - fs::ToolStore store{project.path()}; - install(store, plotRecord()); - - WHEN("a version differing only by case is installed, as on a case-insensitive volume") { - install(store, plotRecord("1.2.0-alpha"), "

    alpha

    "); - install(store, plotRecord("1.2.0-Alpha"), "

    Alpha

    "); - THEN("the cleanup of the replaced version keeps the new files") { - REQUIRE(store.find("@acme/plot")->version == "1.2.0-Alpha"); - REQUIRE(contentOf(store.installDir("@acme/plot", "1.2.0-Alpha") / "dist" / "index.html") == "

    Alpha

    "); - } - } - WHEN("installing a version fails when the lock file is written") { - filesystem::create_directories(project.path() / "webfront-tools.lock.json.tmp"); - const auto failingInstall = [&](string version) { - REQUIRE_THROWS_AS(install(store, plotRecord(std::move(version)), "

    failed

    "), runtime_error); - }; - failingInstall("1.2.0"); - failingInstall("2.0.0"); - THEN("the installed version and its files are intact, and no other version is left") { - REQUIRE(store.find("@acme/plot") == plotRecord()); - REQUIRE(contentOf(store.installDir("@acme/plot", "1.2.0") / "dist" / "index.html") == "

    plot

    "); - REQUIRE_FALSE(filesystem::exists(store.installDir("@acme/plot", "2.0.0"))); - } - } - WHEN("a new installation is abandoned") { - store.begin("@acme/plot", "3.0.0"); - store.write("@acme/plot", "3.0.0", {.path = "dist/index.html", .offset = 0, .bytes = bytes("

    v3

    ")}); - THEN("the installed version is untouched") { - REQUIRE(store.find("@acme/plot")->version == "1.2.0"); - REQUIRE(contentOf(store.installDir("@acme/plot", "1.2.0") / "dist" / "index.html") == "

    plot

    "); - } - } - } -} - -SCENARIO("Installations of versions differing only by case do not share their staged files") { - GIVEN("a project") { - TemporaryDirectory project; - fs::ToolStore store{project.path()}; - const auto stage = [&store](const fs::ToolRecord& record, string_view page) { - store.begin(record.name, record.version); - store.write(record.name, record.version, {.path = record.entry, .offset = 0, .bytes = bytes(page)}); - }; - - WHEN("the installations of 1.2.0-alpha and 1.2.0-Alpha are interleaved") { - stage(plotRecord("1.2.0-alpha"), "

    alpha

    "); - stage(plotRecord("1.2.0-Alpha"), "

    Alpha

    "); - THEN("each commit installs the files written for its own version") { - store.commit(plotRecord("1.2.0-alpha")); - REQUIRE(store.find("@acme/plot")->version == "1.2.0-alpha"); - REQUIRE(contentOf(store.installDir("@acme/plot", "1.2.0-alpha") / "dist" / "index.html") == "

    alpha

    "); - store.commit(plotRecord("1.2.0-Alpha")); - REQUIRE(store.find("@acme/plot")->version == "1.2.0-Alpha"); - REQUIRE(contentOf(store.installDir("@acme/plot", "1.2.0-Alpha") / "dist" / "index.html") == "

    Alpha

    "); - } - } - WHEN("an installation is restarted while another case variant is staged") { - stage(plotRecord("1.2.0-alpha"), "

    alpha

    "); - stage(plotRecord("1.2.0-Alpha"), "

    Alpha

    "); - store.begin("@acme/plot", "1.2.0-Alpha"); - THEN("only the restarted installation loses its staged files") { - REQUIRE_THROWS_AS(store.commit(plotRecord("1.2.0-Alpha")), invalid_argument); - store.commit(plotRecord("1.2.0-alpha")); - REQUIRE(contentOf(store.installDir("@acme/plot", "1.2.0-alpha") / "dist" / "index.html") == "

    alpha

    "); - } - } - } -} - -SCENARIO("Stores of the same project share their transactions") { - GIVEN("two stores of one project") { - TemporaryDirectory project; - fs::ToolStore first{project.path()}; - fs::ToolStore second{project.path() / "."}; - - THEN("an installation begun in one can be completed in the other") { - first.begin("plot", "1.0.0"); - second.write("plot", "1.0.0", {.path = "index.html", .offset = 0, .bytes = bytes("x")}); - second.commit({.name = "plot", .version = "1.0.0", .entry = "index.html"}); - REQUIRE(first.find("plot")); - } - WHEN("both install tools at the same time") { - constexpr int toolsPerStore = 25; - atomic failures{0}; - const auto installMany = [&failures](fs::ToolStore& store, const string& prefix) { - for (int index = 0; index < toolsPerStore; ++index) { - try { - install(store, {.name = prefix + to_string(index), .version = "1.0.0", .entry = "index.html"}); - } catch (const exception&) { - ++failures; - } - } - }; - { - jthread a{installMany, ref(first), "a"}; - jthread b{installMany, ref(second), "b"}; - } - THEN("every installation succeeds and is recorded with its files") { - REQUIRE(failures == 0); - const auto installed = first.installed(); - REQUIRE(installed.size() == 2 * toolsPerStore); - for (const auto& [name, record] : installed) - REQUIRE(filesystem::is_regular_file(first.installDir(name, record.version) / "index.html")); - } - } - } -} - -#ifndef _WIN32 -namespace { - -// Makes a directory read-only (its entries cannot be deleted) until destroyed. -class ReadOnlyDirectory { -public: - explicit ReadOnlyDirectory(filesystem::path path) : directory(std::move(path)) { - filesystem::permissions(directory, filesystem::perms::owner_read | filesystem::perms::owner_exec); - } - ReadOnlyDirectory(const ReadOnlyDirectory&) = delete; - ReadOnlyDirectory& operator=(const ReadOnlyDirectory&) = delete; - ~ReadOnlyDirectory() { - error_code ignored; - filesystem::permissions(directory, filesystem::perms::owner_all, ignored); - } - -private: - filesystem::path directory; -}; - -} // namespace - -SCENARIO("Directories that cannot be deleted do not fail completed operations") { - GIVEN("an installed version whose files cannot be deleted") { - TemporaryDirectory project; - fs::ToolStore store{project.path()}; - install(store, {.name = "plot", .version = "1.0.0", .entry = "index.html"}); - const auto installed = store.installDir("plot", "1.0.0"); - const auto backup = project.path() / ".webfront" / "tools" / "plot@1.0.0~backup"; - - WHEN("another version replaces it") { - const ReadOnlyDirectory readOnly{installed}; - REQUIRE_NOTHROW(install(store, {.name = "plot", .version = "2.0.0", .entry = "index.html"})); - THEN("the new version is installed") { - REQUIRE(store.find("plot")->version == "2.0.0"); - } - } - WHEN("the same version is reinstalled") { - const ReadOnlyDirectory readOnly{installed}; - REQUIRE_NOTHROW(install(store, {.name = "plot", .version = "1.0.0", .entry = "index.html"}, "

    again

    ")); - THEN("the new files are installed") { - REQUIRE(contentOf(installed / "index.html") == "

    again

    "); - } - AND_WHEN("it is reinstalled again while the backup is still left behind") { - REQUIRE_NOTHROW(install(store, {.name = "plot", .version = "1.0.0", .entry = "index.html"}, "

    third

    ")); - THEN("the newest files are installed") { - REQUIRE(contentOf(installed / "index.html") == "

    third

    "); - } - } - // The read-only directory was moved to the backup, which could not be deleted. - error_code ignored; - filesystem::permissions(backup, filesystem::perms::owner_all, ignored); - } - WHEN("it is removed") { - const ReadOnlyDirectory readOnly{installed}; - THEN("the removal succeeds") { - REQUIRE(store.remove("plot")); - REQUIRE(store.installed().empty()); - } - } - } -} -#endif diff --git a/test/cmake/AssembleDeveloperFixtures.cmake b/test/cmake/AssembleDeveloperFixtures.cmake new file mode 100644 index 00000000..9ced710a --- /dev/null +++ b/test/cmake/AssembleDeveloperFixtures.cmake @@ -0,0 +1,16 @@ +# Assembles the directory of the developer browser tests from what wf built: the local npm registry, the environment +# built from the current sources (archive, starters, provision.json) and the pages and specs of the tests. +# Usage: cmake -DSOURCE= -DPROJECT= -DOUTPUT= -P AssembleDeveloperFixtures.cmake +file(REMOVE_RECURSE "${OUTPUT}") +file(MAKE_DIRECTORY "${OUTPUT}") +foreach(directory build-registry build-distribution) + if(NOT EXISTS "${PROJECT}/${directory}") + message(FATAL_ERROR "${PROJECT}/${directory} is missing: wf must build the registry and the environment first") + endif() +endforeach() +file(COPY "${PROJECT}/build-distribution/" DESTINATION "${OUTPUT}") +file(COPY "${PROJECT}/build-registry/" DESTINATION "${OUTPUT}/registry") +file(COPY_FILE "${SOURCE}/test/web/developer-specs.mjs" "${OUTPUT}/run.mjs") +file(COPY_FILE "${SOURCE}/test/web/developer-session.html" "${OUTPUT}/session.html") +file(COPY_FILE "${SOURCE}/test/web/developer-session.mjs" "${OUTPUT}/session.mjs") +file(COPY_FILE "${SOURCE}/test/developer/timers.mjs" "${OUTPUT}/timers.mjs") diff --git a/test/cmake/CheckArchiveRelease.cmake b/test/cmake/CheckArchiveRelease.cmake new file mode 100644 index 00000000..3b587b11 --- /dev/null +++ b/test/cmake/CheckArchiveRelease.cmake @@ -0,0 +1,23 @@ +# archive-release.sh must refuse a missing or invalid manifest before it calls GitHub. +# Usage: cmake -DSCRIPT= -DWORK_DIR= -DBASH= -P CheckArchiveRelease.cmake +file(REMOVE_RECURSE "${WORK_DIR}") +file(MAKE_DIRECTORY "${WORK_DIR}/bin" "${WORK_DIR}/missing" "${WORK_DIR}/invalid") +file(WRITE "${WORK_DIR}/bin/gh" "#!/bin/sh\necho \"$*\" >> \"${WORK_DIR}/gh.log\"\nexit 1\n") +file(CHMOD "${WORK_DIR}/bin/gh" PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE) +file(WRITE "${WORK_DIR}/invalid/provision.json" "{ not json") +get_filename_component(tools "${SCRIPT}" DIRECTORY) +file(READ "${tools}/distribution.json" distribution) +string(JSON version GET "${distribution}" version) +foreach(case missing invalid) + file(REMOVE "${WORK_DIR}/gh.log") + execute_process(COMMAND "${CMAKE_COMMAND}" -E env "PATH=${WORK_DIR}/bin:$ENV{PATH}" GITHUB_REPOSITORY=o/r + "${BASH}" "${SCRIPT}" developer-v${version} "${WORK_DIR}/${case}" + RESULT_VARIABLE status OUTPUT_QUIET ERROR_QUIET) + if(status EQUAL 0) + message(FATAL_ERROR "archive-release.sh accepted a ${case} manifest") + endif() + if(EXISTS "${WORK_DIR}/gh.log") + file(READ "${WORK_DIR}/gh.log" calls) + message(FATAL_ERROR "archive-release.sh called gh with a ${case} manifest: ${calls}") + endif() +endforeach() diff --git a/test/cmake/CheckBootstrapProvisioning.cmake b/test/cmake/CheckBootstrapProvisioning.cmake new file mode 100644 index 00000000..7b107b08 --- /dev/null +++ b/test/cmake/CheckBootstrapProvisioning.cmake @@ -0,0 +1,111 @@ +# Bootstrap provisioning at configure time: SRI conversion, verified download, local directory, integrity failures. +# Usage: cmake -DROOT= -DWORK= -P CheckBootstrapProvisioning.cmake +include("${ROOT}/cmake/WebFrontBootstrap.cmake") + +# No line break: a text-mode write would turn it into CRLF on Windows and change the digest. +set(content "webfront bootstrap test archive") +set(sri "sha512-tp5zEsnN4U2b4SrnPY7GY6cYRK/sFQRO9ZX/xlR7mRyMxqedrks3Oc6EVPRYECyrQE8C4FAg6wH5CVNFoNoT6Q==") +set(hex "b69e7312c9cde14d9be12ae73d8ec663a71844afec15044ef595ffc6547b991c8cc6a79dae4b3739ce8454f458102cab404f02e05020eb01f9095345a0da13e9") + +function(expect_equal actual expected message) + if(NOT actual STREQUAL expected) + message(FATAL_ERROR "${message}: expected '${expected}', got '${actual}'") + endif() +endfunction() + +# The pinned value of the repository is a well-formed SHA-512. +webfront_sri_to_sha512("${WEBFRONT_BOOTSTRAP_INTEGRITY}" pinned) +string(LENGTH "${pinned}" pinnedLength) +expect_equal("${pinnedLength}" 128 "The pinned integrity must decode to 64 bytes") + +webfront_sri_to_sha512("${sri}" decoded) +expect_equal("${decoded}" "${hex}" "SRI conversion") + +file(REMOVE_RECURSE "${WORK}") +# The SRI of a file built by a test round-trips through the conversion above. +file(MAKE_DIRECTORY "${WORK}") +file(WRITE "${WORK}/sri.bin" "${content}") +webfront_file_sri("${WORK}/sri.bin" encoded) +expect_equal("${encoded}" "${sri}" "SRI encoding") + +# Each case runs in its own cmake process: a failed integrity check is a FATAL_ERROR. +file(MAKE_DIRECTORY "${WORK}/source" "${WORK}/local") +file(WRITE "${WORK}/source/environment.tgz" "${content}") +file(WRITE "${WORK}/local/environment.tgz" "${content}") +file(WRITE "${WORK}/tampered.tgz" "tampered\n") +file(WRITE "${WORK}/run.cmake" [[ +include("${ROOT}/cmake/WebFrontBootstrap.cmake") +if(LOCAL) + webfront_provision_bootstrap(archive URL "${URL}" INTEGRITY "${INTEGRITY}" DESTINATION "${WORK}/cache" LOCAL_DIR "${LOCAL}") +else() + webfront_provision_bootstrap(archive URL "${URL}" INTEGRITY "${INTEGRITY}" DESTINATION "${WORK}/cache") +endif() +message(STATUS "provisioned ${archive}") +]]) + +function(provision name result_var output_var) + cmake_parse_arguments(ARG "" "URL;INTEGRITY;LOCAL" "" ${ARGN}) + execute_process(COMMAND "${CMAKE_COMMAND}" -DROOT=${ROOT} -DWORK=${WORK} -DURL=${ARG_URL} -DINTEGRITY=${ARG_INTEGRITY} + -DLOCAL=${ARG_LOCAL} -P "${WORK}/run.cmake" + RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err) + set(${result_var} "${result}" PARENT_SCOPE) + set(${output_var} "${out}${err}" PARENT_SCOPE) +endfunction() + +# A file URL: a Windows drive letter needs a third slash. +if(WORK MATCHES "^[A-Za-z]:") + set(scheme "file:///") +else() + set(scheme "file://") +endif() +set(url "${scheme}${WORK}/source/environment.tgz") + +provision(download result text URL "${url}" INTEGRITY "${sri}") +expect_equal("${result}" 0 "A matching download must be provisioned: ${text}") +if(NOT EXISTS "${WORK}/cache/environment.tgz") + message(FATAL_ERROR "The verified archive must be kept in the destination") +endif() + +# A cached archive is reused without the source. +file(REMOVE "${WORK}/source/environment.tgz") +provision(reuse result text URL "${url}" INTEGRITY "${sri}") +expect_equal("${result}" 0 "A verified cached archive must be reused: ${text}") + +# A wrong digest stops the configure and leaves no unverified archive behind. +file(REMOVE_RECURSE "${WORK}/cache") +file(COPY "${WORK}/tampered.tgz" DESTINATION "${WORK}/source") +file(RENAME "${WORK}/source/tampered.tgz" "${WORK}/source/environment.tgz") +provision(wrong result text URL "${url}" INTEGRITY "${sri}") +if(result EQUAL 0 OR NOT text MATCHES "integrity check failed") + message(FATAL_ERROR "A wrong integrity must fail the configure: ${result} ${text}") +endif() +if(EXISTS "${WORK}/cache/environment.tgz") + message(FATAL_ERROR "A downloaded archive that fails its integrity check must be removed") +endif() + +# A download failure names the offline alternative. +provision(missing result text URL "${scheme}${WORK}/absent/environment.tgz" INTEGRITY "${sri}") +if(result EQUAL 0 OR NOT text MATCHES "WEBFRONT_BOOTSTRAP_DIR") + message(FATAL_ERROR "A failed download must point to WEBFRONT_BOOTSTRAP_DIR: ${result} ${text}") +endif() + +# A local provisioning directory replaces the download and is verified too. +provision(local result text URL "https://offline.invalid/environment.tgz" INTEGRITY "${sri}" LOCAL "${WORK}/local") +expect_equal("${result}" 0 "A local directory must replace the download: ${text}") +file(WRITE "${WORK}/local/environment.tgz" "tampered\n") +provision(localWrong result text URL "https://offline.invalid/environment.tgz" INTEGRITY "${sri}" LOCAL "${WORK}/local") +if(result EQUAL 0 OR NOT text MATCHES "integrity check failed") + message(FATAL_ERROR "A tampered local archive must fail the configure: ${result} ${text}") +endif() +file(REMOVE "${WORK}/local/environment.tgz") +provision(localMissing result text URL "https://offline.invalid/environment.tgz" INTEGRITY "${sri}" LOCAL "${WORK}/local") +if(result EQUAL 0 OR NOT text MATCHES "is missing") + message(FATAL_ERROR "An absent local archive must fail the configure: ${result} ${text}") +endif() + +# A malformed integrity is refused before anything is downloaded. +provision(malformed result text URL "${url}" INTEGRITY "sha256-abc") +if(result EQUAL 0 OR NOT text MATCHES "sha512- SRI") + message(FATAL_ERROR "A non SHA-512 integrity must be refused: ${result} ${text}") +endif() +message(STATUS "Bootstrap provisioning checks passed") diff --git a/test/cmake/CheckBundleInputs.cmake b/test/cmake/CheckBundleInputs.cmake new file mode 100644 index 00000000..f3d5dae5 --- /dev/null +++ b/test/cmake/CheckBundleInputs.cmake @@ -0,0 +1,52 @@ +# The bundles that are checked in (the bootstrap loader, the packages of the environment) are built from the readable sources +# of js/developer/environment and the files listed in js/developer/tools/bundle-inputs.json. bundles.json records the SHA-256 of +# each of those files and of the bundles themselves: a source changed without rebuilding the bundles is detected here, with no +# browser. wf rebuilds the bundles and the checksums (`wf run build build-distribution --refresh-bootstrap`), and the +# SelfBuildRefresh cases prove that the checked-in ones are what wf produces. +# cmake -DROOT= -P test/cmake/CheckBundleInputs.cmake +cmake_minimum_required(VERSION 3.31) + +if(NOT ROOT) + message(FATAL_ERROR "ROOT is required") +endif() +set(manifest_path "${ROOT}/js/developer/environment/bundles.json") +set(list_path "${ROOT}/js/developer/tools/bundle-inputs.json") +file(READ "${manifest_path}" manifest) +file(READ "${list_path}" listed) + +# Every input of the build has a checksum, and only those: the two files agree. +string(JSON count LENGTH "${listed}") +math(EXPR last "${count} - 1") +set(inputs "") +foreach(index RANGE 0 ${last}) + string(JSON path GET "${listed}" ${index}) + list(APPEND inputs "${path}") +endforeach() +string(JSON recorded_count LENGTH "${manifest}") +if(NOT recorded_count EQUAL count) + message(FATAL_ERROR "bundles.json records ${recorded_count} checksums for ${count} inputs: " + "run wf run build build-distribution --refresh-bootstrap") +endif() + +set(changed "") +foreach(path IN LISTS inputs) + string(JSON expected ERROR_VARIABLE missing GET "${manifest}" "${path}") + if(missing) + list(APPEND changed "${path} (no checksum)") + continue() + endif() + if(NOT EXISTS "${ROOT}/${path}") + list(APPEND changed "${path} (missing)") + continue() + endif() + file(SHA256 "${ROOT}/${path}" actual) + if(NOT actual STREQUAL expected) + list(APPEND changed "${path}") + endif() +endforeach() +if(changed) + list(JOIN changed "\n " text) + message(FATAL_ERROR "The inputs of the bundles changed without rebuilding them:\n ${text}\n" + "Run wf run build build-distribution --refresh-bootstrap") +endif() +message(STATUS "${count} bundle inputs match bundles.json") diff --git a/test/cmake/CheckBundleInputsNegative.cmake b/test/cmake/CheckBundleInputsNegative.cmake new file mode 100644 index 00000000..9386be1e --- /dev/null +++ b/test/cmake/CheckBundleInputsNegative.cmake @@ -0,0 +1,46 @@ +# CheckBundleInputs.cmake must fail on an input that changed since the bundles were built, and on a checksum nobody can +# match, while it passes on an untouched copy. +# cmake -DROOT= -DWORK_DIR= -P test/cmake/CheckBundleInputsNegative.cmake +cmake_minimum_required(VERSION 3.31) + +if(NOT ROOT OR NOT WORK_DIR) + message(FATAL_ERROR "ROOT and WORK_DIR are required") +endif() +file(REMOVE_RECURSE "${WORK_DIR}") +file(READ "${ROOT}/js/developer/tools/bundle-inputs.json" listed) +string(JSON count LENGTH "${listed}") +math(EXPR last "${count} - 1") +foreach(index RANGE 0 ${last}) + string(JSON path GET "${listed}" ${index}) + get_filename_component(directory "${path}" DIRECTORY) + file(COPY "${ROOT}/${path}" DESTINATION "${WORK_DIR}/${directory}") +endforeach() +file(COPY "${ROOT}/js/developer/tools/bundle-inputs.json" DESTINATION "${WORK_DIR}/js/developer/tools") +file(COPY "${ROOT}/js/developer/environment/bundles.json" DESTINATION "${WORK_DIR}/js/developer/environment") + +function(run_check expected_status description) + execute_process(COMMAND "${CMAKE_COMMAND}" -DROOT=${WORK_DIR} -P "${CMAKE_CURRENT_LIST_DIR}/CheckBundleInputs.cmake" + RESULT_VARIABLE status OUTPUT_VARIABLE output ERROR_VARIABLE errors) + if(NOT status EQUAL expected_status) + message(FATAL_ERROR "${description}: expected status ${expected_status}, got ${status}\n${output}${errors}") + endif() + set(text "${output}${errors}" PARENT_SCOPE) +endfunction() + +run_check(0 "an untouched copy") + +# A source modified after the bundles were built. +file(APPEND "${WORK_DIR}/js/developer/environment/restore.mjs" "// changed\n") +run_check(1 "a modified source") +if(NOT text MATCHES "environment/restore\\.mjs") + message(FATAL_ERROR "The modified input is not named:\n${text}") +endif() +file(COPY "${ROOT}/js/developer/environment/restore.mjs" DESTINATION "${WORK_DIR}/js/developer/environment") +run_check(0 "a restored source") + +# A bundle modified by hand. +file(APPEND "${WORK_DIR}/js/core/bootstrap/bootstrap.bundle.mjs" "// changed\n") +run_check(1 "a modified bundle") +if(NOT text MATCHES "bootstrap\\.bundle\\.mjs") + message(FATAL_ERROR "The modified bundle is not named:\n${text}") +endif() diff --git a/test/cmake/CheckCEFCopy.cmake b/test/cmake/CheckCEFCopy.cmake new file mode 100644 index 00000000..07901032 --- /dev/null +++ b/test/cmake/CheckCEFCopy.cmake @@ -0,0 +1,97 @@ +# The Linux CEF file copy of cmake/CEFSupport.cmake, with stand-in CEF files: one copy per destination, which is the +# target's own output directory; nothing copied again by a build with nothing to copy; explicit errors for the output +# directories it cannot honour. No compiler, SDK or network. +# cmake -DROOT= [-DTEST_GENERATOR=] -P test/cmake/CheckCEFCopy.cmake +cmake_minimum_required(VERSION 3.31) +if(NOT ROOT) + message(FATAL_ERROR "ROOT must be supplied") +endif() +set(generator_args "") +if(TEST_GENERATOR) + list(APPEND generator_args -G "${TEST_GENERATOR}") +endif() +set(work "${CMAKE_CURRENT_BINARY_DIR}/cef-copy") +set(source "${work}/source") +file(REMOVE_RECURSE "${work}") +file(WRITE "${source}/libcef.so" "library 1") +file(WRITE "${source}/locales/en-US.pak" "locale") + +function(configure state out_result out_log) + execute_process( + COMMAND "${CMAKE_COMMAND}" -S "${ROOT}/test/cmake/cef-copy" -B "${work}/${state}" ${generator_args} + -DROOT=${ROOT} -DSOURCE_DIR=${source} -DSTATE=${state} -DCMAKE_BUILD_TYPE=Release + RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE error) + set(${out_result} ${result} PARENT_SCOPE) + set(${out_log} "${output}${error}" PARENT_SCOPE) +endfunction() + +function(build out_log) + execute_process(COMMAND "${CMAKE_COMMAND}" --build "${work}/plan" --config Release + RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE error) + if(NOT result EQUAL 0) + message(FATAL_ERROR "Build of the copy fixture failed: ${output}${error}") + endif() + set(${out_log} "${output}${error}" PARENT_SCOPE) +endfunction() + +function(expect_file path content) + if(NOT EXISTS "${path}") + message(FATAL_ERROR "Missing copied file ${path}") + endif() + file(READ "${path}" actual) + if(NOT actual STREQUAL content) + message(FATAL_ERROR "${path} holds '${actual}', expected '${content}'") + endif() +endfunction() + +configure(plan result log) +if(NOT result EQUAL 0) + message(FATAL_ERROR "Copy destinations: ${log}") +endif() +build(first) +string(REGEX MATCHALL "Copying CEF libcef.so to [^\n]*" copies "${first}") +list(LENGTH copies count) +if(NOT count EQUAL 2) + message(FATAL_ERROR "Each of the two destinations must be copied once, got ${count}: ${first}") +endif() +set(copied_libraries "") +foreach(destination "${work}/plan" "${work}/plan/bin") + if(NOT EXISTS "${destination}/libcef.so" AND EXISTS "${destination}/Release/libcef.so") + set(destination "${destination}/Release") + endif() + file(RELATIVE_PATH library "${work}" "${destination}/libcef.so") + list(APPEND copied_libraries "${library}") + expect_file("${destination}/libcef.so" "library 1") + expect_file("${destination}/locales/en-US.pak" "locale") +endforeach() +build(second) +if(second MATCHES "Copying CEF") + message(FATAL_ERROR "A build with nothing to copy must copy nothing: ${second}") +endif() +# The fixture must not depend on crossing a filesystem/make timestamp tick. Age the existing +# outputs deterministically, then change the source: no sleep and no missing-output shortcut. +file(ARCHIVE_CREATE OUTPUT "${work}/old-libraries.tar" PATHS ${copied_libraries} + WORKING_DIRECTORY "${work}" FORMAT gnutar MTIME "2000-01-01 00:00:00 UTC") +file(ARCHIVE_EXTRACT INPUT "${work}/old-libraries.tar" DESTINATION "${work}") +file(WRITE "${source}/libcef.so" "library 2") +build(third) +if(NOT third MATCHES "Copying CEF libcef.so" OR third MATCHES "Copying CEF locales") + message(FATAL_ERROR "Only the changed file must be copied again: ${third}") +endif() +foreach(destination "${work}/plan" "${work}/plan/bin") + if(NOT EXISTS "${destination}/libcef.so" AND EXISTS "${destination}/Release/libcef.so") + set(destination "${destination}/Release") + endif() + expect_file("${destination}/libcef.so" "library 2") +endforeach() + +configure(per-config result log) +# CMake wraps long messages: any whitespace may separate the words. +if(result EQUAL 0 OR NOT log MATCHES "sets[ \t\r\n]+RUNTIME_OUTPUT_DIRECTORY_RELEASE") + message(FATAL_ERROR "A per-configuration output directory must be refused: ${log}") +endif() +configure(late result log) +if(result EQUAL 0 OR NOT log MATCHES "now[ \t\r\n]+builds[ \t\r\n]+into") + message(FATAL_ERROR "An output directory set after the copy was planned must be refused: ${log}") +endif() +message(STATUS "CEF copy destinations, incremental copies and refusals checked") diff --git a/cmake/CheckCEFTestingState.cmake b/test/cmake/CheckCEFTestingState.cmake similarity index 80% rename from cmake/CheckCEFTestingState.cmake rename to test/cmake/CheckCEFTestingState.cmake index ec10444d..ef1c9670 100644 --- a/cmake/CheckCEFTestingState.cmake +++ b/test/cmake/CheckCEFTestingState.cmake @@ -3,12 +3,18 @@ cmake_minimum_required(VERSION 3.31) if(NOT ROOT OR NOT EXISTS "${CPM_MODULE}") message(FATAL_ERROR "ROOT and the already-downloaded CPM_MODULE must be supplied") endif() +# This compiler-free fixture needs the generator, but intentionally no -A/-T. +set(generator_args "") +if(TEST_GENERATOR) + list(APPEND generator_args -G "${TEST_GENERATOR}") +endif() foreach(state undefined cache-ON cache-OFF cache-empty normal-ON normal-OFF normal-empty normal-ON-cache-OFF normal-OFF-cache-ON) set(directory "${CMAKE_CURRENT_BINARY_DIR}/cef-testing-state/${state}") file(REMOVE_RECURSE "${directory}") execute_process( - COMMAND "${CMAKE_COMMAND}" -S "${ROOT}/test/cef-testing" -B "${directory}" + COMMAND "${CMAKE_COMMAND}" -S "${ROOT}/test/cmake/cef-testing" -B "${directory}" + ${generator_args} -DROOT=${ROOT} -DCPM_MODULE=${CPM_MODULE} -DSTATE=${state} RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE error) if(NOT result EQUAL 0) @@ -21,7 +27,8 @@ foreach(kind static interface missing) set(directory "${CMAKE_CURRENT_BINARY_DIR}/cef-testing-state/apple-${kind}") file(REMOVE_RECURSE "${directory}") execute_process( - COMMAND "${CMAKE_COMMAND}" -S "${ROOT}/test/cef-testing" -B "${directory}" + COMMAND "${CMAKE_COMMAND}" -S "${ROOT}/test/cmake/cef-testing" -B "${directory}" + ${generator_args} -DROOT=${ROOT} -DCPM_MODULE=${CPM_MODULE} -DSTATE=undefined -DSIMULATE_APPLE=ON -DWRAPPER_KIND=${kind} RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE error) diff --git a/test/cmake/CheckCommandNames.cmake b/test/cmake/CheckCommandNames.cmake new file mode 100644 index 00000000..0c553087 --- /dev/null +++ b/test/cmake/CheckCommandNames.cmake @@ -0,0 +1,33 @@ +# The terminal (js/developer/environment/commands.mjs) and webfront::Commands (include/webfront/Commands.hpp) must refuse the +# same command names to an application: a name one accepts and the other handles would never reach the application. +# cmake -DROOT= -P test/cmake/CheckCommandNames.cmake +cmake_minimum_required(VERSION 3.31) + +if(NOT ROOT) + message(FATAL_ERROR "ROOT is required") +endif() + +function(reserved_names file pattern output) + file(READ "${ROOT}/${file}" text) + if(NOT text MATCHES "${pattern}") + message(FATAL_ERROR "${file} must declare reservedNames") + endif() + string(REGEX MATCHALL "[\"']([^\"']*)[\"']" quoted "${CMAKE_MATCH_1}") + set(names "") + foreach(item IN LISTS quoted) + string(REGEX REPLACE "^[\"']|[\"']$" "" name "${item}") + list(APPEND names "${name}") + endforeach() + list(SORT names) + set(${output} "${names}" PARENT_SCOPE) +endfunction() + +reserved_names(js/developer/environment/commands.mjs "reservedNames = \\[([^]]*)\\]" terminal) +reserved_names(include/webfront/Commands.hpp "reservedNames\\{([^}]*)\\}" cpp) +if(NOT terminal) + message(FATAL_ERROR "commands.mjs declares no reserved name") +endif() +if(NOT terminal STREQUAL cpp) + message(FATAL_ERROR "The terminal reserves '${terminal}' but webfront::Commands reserves '${cpp}'") +endif() +message(STATUS "Both reserve: ${terminal}") diff --git a/test/cmake/CheckEmbedAsset.cmake b/test/cmake/CheckEmbedAsset.cmake new file mode 100644 index 00000000..e8b0b98d --- /dev/null +++ b/test/cmake/CheckEmbedAsset.cmake @@ -0,0 +1,144 @@ +# The renderer of the embedded assets (js/core/EmbedAsset.cmake): the exact format of a header, word order and padding, the +# check of exact bytes, the exit status of a stale or missing header, a path with spaces and a checkout reached through a +# symbolic link. +# cmake -DROOT= -DWORK_DIR= -P test/cmake/CheckEmbedAsset.cmake +cmake_minimum_required(VERSION 3.31) + +if(NOT ROOT OR NOT WORK_DIR) + message(FATAL_ERROR "ROOT and WORK_DIR are required") +endif() +file(REMOVE_RECURSE "${WORK_DIR}") +file(MAKE_DIRECTORY "${WORK_DIR}") +set(script "${ROOT}/js/core/EmbedAsset.cmake") + +# render( ...): runs the script like the build does. +function(render status errors script_path input) + execute_process(COMMAND "${CMAKE_COMMAND}" "-DINPUT=${input}" -DSTRUCT=Fixture ${ARGN} -P "${script_path}" + WORKING_DIRECTORY "${WORK_DIR}" RESULT_VARIABLE result OUTPUT_QUIET ERROR_VARIABLE text) + set(${status} "${result}" PARENT_SCOPE) + set(${errors} "${text}" PARENT_SCOPE) +endfunction() + +function(expect_status expected description) + if(NOT status EQUAL expected) + message(FATAL_ERROR "${description}: expected exit status ${expected}, got ${status}\n${errors}") + endif() +endfunction() +function(expect_stale description) + expect_status(1 "${description}") + # CMake wraps the text of an error at the width of the terminal, wherever the path of the header leaves room. + string(REGEX REPLACE "[ \t\r\n]+" " " flat "${errors}") + if(NOT flat MATCHES "is stale; run the webfront-embedded-assets target") + message(FATAL_ERROR "${description}: no stale message:\n${errors}") + endif() +endfunction() + +# The format, word order, padding and line wrapping, byte for byte (41 bytes: five full words and one padded). +file(WRITE "${WORK_DIR}/input 41.txt" "0123456789abcdefghijklmnopqrstuvwxyzABCDE") +render(status errors "${script}" "${WORK_DIR}/input 41.txt" "-DOUTPUT=${WORK_DIR}/nested/Fixture.hpp") +expect_status(0 "rendering a 41-byte input") +file(READ "${WORK_DIR}/nested/Fixture.hpp" rendered) +set(expected "#pragma once + +#include +#include +#include +#include + +namespace webfront::fs::generated { + +struct Fixture { + static constexpr std::string_view encoding{}; + static constexpr std::size_t dataSize{41}; + static constexpr std::array data{ + 0x3031323334353637, 0x3839616263646566, 0x6768696a6b6c6d6e, 0x6f70717273747576, 0x7778797a41424344, + 0x4500000000000000 + }; +}; + +} // namespace webfront::fs::generated +") +if(NOT rendered STREQUAL expected) + message(FATAL_ERROR "The rendered header differs from the expected format:\n${rendered}") +endif() + +# Padding and the empty array, for the sizes around the word and line boundaries. +string(REPEAT "x" 41 filler) +foreach(size 0 1 7 8 9 39 40 41) + string(SUBSTRING "${filler}" 0 ${size} content) + file(WRITE "${WORK_DIR}/sized.bin" "${content}") + render(status errors "${script}" "${WORK_DIR}/sized.bin" "-DOUTPUT=${WORK_DIR}/sized.hpp") + expect_status(0 "rendering ${size} bytes") + file(READ "${WORK_DIR}/sized.hpp" header) + math(EXPR words "(${size} + 7) / 8") + if(NOT header MATCHES "dataSize\\{${size}\\}" OR NOT header MATCHES "std::array data\\{") + message(FATAL_ERROR "Wrong size or array length for ${size} bytes:\n${header}") + endif() + # The words, read back, are the content followed by zero padding only. + string(REGEX MATCHALL "0x[0-9a-f]+" found "${header}") + string(REPLACE "0x" "" found "${found}") + string(REPLACE ";" "" decoded "${found}") + string(HEX "${content}" hex) + string(LENGTH "${decoded}" decoded_length) + math(EXPR padded "${words} * 16") + if(NOT decoded_length EQUAL padded OR NOT decoded MATCHES "^${hex}0*$") + message(FATAL_ERROR "The words of ${size} bytes do not decode to the input: ${decoded}") + endif() + if(size EQUAL 0 AND NOT header MATCHES "data\\{\n };") + message(FATAL_ERROR "An empty asset must render an empty array:\n${header}") + endif() +endforeach() + +# Exact bytes: a current header passes, a stale or CRLF one, a changed source or a missing header fail. The favicon is binary. +foreach(source "${WORK_DIR}/input 41.txt" "${ROOT}/js/core/favicon.ico") + render(status errors "${script}" "${source}" "-DOUTPUT=${WORK_DIR}/Checked.hpp") + expect_status(0 "rendering ${source}") + render(status errors "${script}" "${source}" "-DCHECK=${WORK_DIR}/Checked.hpp") + expect_status(0 "checking a current header") + file(READ "${WORK_DIR}/Checked.hpp" current) + string(REPLACE "\n" "\r\n" crlf "${current}") + file(WRITE "${WORK_DIR}/Checked.hpp" "${crlf}") + render(status errors "${script}" "${source}" "-DCHECK=${WORK_DIR}/Checked.hpp") + if(status EQUAL 0) + message(FATAL_ERROR "A header with CRLF line ends must be stale") + endif() + file(WRITE "${WORK_DIR}/Checked.hpp" "stale header") + render(status errors "${script}" "${source}" "-DCHECK=${WORK_DIR}/Checked.hpp") + expect_stale("checking a stale header") + file(REMOVE "${WORK_DIR}/Checked.hpp") + render(status errors "${script}" "${source}" "-DCHECK=${WORK_DIR}/Checked.hpp") + if(status EQUAL 0) + message(FATAL_ERROR "A missing header must fail the check") + endif() +endforeach() +file(WRITE "${WORK_DIR}/changing.txt" "before") +render(status errors "${script}" "${WORK_DIR}/changing.txt" "-DOUTPUT=${WORK_DIR}/Changing.hpp") +file(WRITE "${WORK_DIR}/changing.txt" "after") +render(status errors "${script}" "${WORK_DIR}/changing.txt" "-DCHECK=${WORK_DIR}/Changing.hpp") +expect_stale("checking a header after its source changed") + +# Missing arguments and a missing source are errors, never an empty header. +foreach(arguments "-DOUTPUT=${WORK_DIR}/none.hpp" "-DCHECK=${WORK_DIR}/Changing.hpp") + render(status errors "${script}" "${WORK_DIR}/absent.txt" ${arguments}) + if(status EQUAL 0) + message(FATAL_ERROR "A missing source must fail (${arguments})") + endif() +endforeach() +if(EXISTS "${WORK_DIR}/none.hpp") + message(FATAL_ERROR "A missing source must not write a header") +endif() +render(status errors "${script}" "${WORK_DIR}/changing.txt") +if(status EQUAL 0) + message(FATAL_ERROR "Neither OUTPUT nor CHECK must fail") +endif() + +# The checkout reached through a symbolic link (skipped where the platform refuses to create one). +file(CREATE_LINK "${ROOT}" "${WORK_DIR}/linked checkout" SYMBOLIC RESULT linked) +if(linked STREQUAL "0") + foreach(argument "-DOUTPUT=${WORK_DIR}/Linked.hpp" "-DCHECK=${WORK_DIR}/Linked.hpp") + render(status errors "${WORK_DIR}/linked checkout/js/core/EmbedAsset.cmake" "${WORK_DIR}/input 41.txt" "${argument}") + expect_status(0 "through a symbolic link (${argument})") + endforeach() +else() + message(STATUS "Symbolic links are not available: ${linked}") +endif() diff --git a/cmake/CheckFrontendGenerators.cmake b/test/cmake/CheckFrontendGenerators.cmake similarity index 87% rename from cmake/CheckFrontendGenerators.cmake rename to test/cmake/CheckFrontendGenerators.cmake index 347a3500..686f116f 100644 --- a/cmake/CheckFrontendGenerators.cmake +++ b/test/cmake/CheckFrontendGenerators.cmake @@ -3,13 +3,13 @@ cmake_minimum_required(VERSION 3.31) if(NOT ROOT) message(FATAL_ERROR "ROOT must point at the WebFront checkout") endif() -include("${ROOT}/cmake/FrontendTestHelpers.cmake") +include("${ROOT}/test/cmake/FrontendTestHelpers.cmake") set(directory "${CMAKE_CURRENT_BINARY_DIR}/frontend-tests/extension") foreach(generator Ninja "Ninja Multi-Config" Ninja) file(REMOVE_RECURSE "${directory}") execute_process( COMMAND "${CMAKE_COMMAND}" -E env "CMAKE_GENERATOR=${generator}" - "${CMAKE_COMMAND}" -S "${ROOT}/test/frontends" -B "${directory}" -DROOT=${ROOT} -DCASE=extension + "${CMAKE_COMMAND}" -S "${ROOT}/test/cmake/frontends" -B "${directory}" -DROOT=${ROOT} -DCASE=extension RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE error) if(NOT result EQUAL 0) message(FATAL_ERROR "Extension fixture with ${generator} failed: ${output}${error}") diff --git a/cmake/CheckFrontendSelection.cmake b/test/cmake/CheckFrontendSelection.cmake similarity index 86% rename from cmake/CheckFrontendSelection.cmake rename to test/cmake/CheckFrontendSelection.cmake index a8c541e8..8f1bf702 100644 --- a/cmake/CheckFrontendSelection.cmake +++ b/test/cmake/CheckFrontendSelection.cmake @@ -1,7 +1,7 @@ # Exercises cmake/Frontends.cmake: registered names, defaults, rejection of unknown or unavailable # frontends and the generated C++ type name. Each case runs in its own cmake -P process so that a # FATAL_ERROR can be observed. Run with: -# cmake -DROOT= -P cmake/CheckFrontendSelection.cmake +# cmake -DROOT= -P test/cmake/CheckFrontendSelection.cmake cmake_minimum_required(VERSION 3.31) if(NOT ROOT) @@ -21,7 +21,7 @@ if(CASE) endforeach() list(PREPEND CMAKE_MODULE_PATH "${parent_modules}") endif() - list(APPEND CMAKE_MODULE_PATH "${ROOT}/test/frontends") + list(APPEND CMAKE_MODULE_PATH "${ROOT}/test/cmake/frontends") include("${ROOT}/cmake/Frontends.cmake") # Unquoted empty inputs intentionally unset these variables so option() supplies its default. set(WEBFRONT_EMBED_CEF ${CEF}) @@ -78,8 +78,8 @@ if(CASE) elseif(VALUE STREQUAL "strict") webfront_register_frontend(TestBrowser ALWAYS_AVAILABLE POLICY strict) webfront_select_frontend(TEST_BROWSER TestBrowser "Test always-available browser" REQUIRE_AVAILABLE) - elseif(VALUE STREQUAL "XVFB_LINUX") - webfront_register_frontend(TestBrowser ALWAYS_AVAILABLE XVFB_LINUX) + elseif(VALUE STREQUAL "XVFB_LINUX" OR VALUE STREQUAL "NATIVE") + webfront_register_frontend(TestBrowser ALWAYS_AVAILABLE ${VALUE}) else() webfront_register_frontend(TestBrowser ALWAYS_AVAILABLE ${VALUE} ignored) endif() @@ -141,6 +141,20 @@ if(CASE) endif() webfront_register_frontend(TestEngine ${args}) endif() + elseif(CASE STREQUAL "autodetect") + # VALUE is the probe answer (ON/OFF). Empty option variables are undefined. + function(webfront_probe_native_frontend name out reason) + set(${out} "${VALUE}" PARENT_SCOPE) + set(${reason} "probe says ${VALUE}" PARENT_SCOPE) + endfunction() + webfront_autodetect_native_frontends() + foreach(option WEBFRONT_EMBED_WEBVIEW2 WEBFRONT_EMBED_WKWEBVIEW WEBFRONT_EMBED_WEBKITGTK WEBFRONT_EMBED_CEF) + if(DEFINED ${option}) + message("AUTO ${option}=${${option}}") + else() + message("AUTO ${option}=undefined") + endif() + endforeach() elseif(CASE STREQUAL "default") webfront_default_embedded_frontend(chosen FALLBACK CEF) message("CHOSEN=${chosen}") @@ -152,7 +166,16 @@ if(CASE) return() endif() -include("${ROOT}/cmake/FrontendTestHelpers.cmake") +include("${ROOT}/test/cmake/FrontendTestHelpers.cmake") + +# Reuse the outer build's generator instead of repeatedly probing the host default +# (Visual Studio on Windows). The focused multi-config test still switches generators. +# These fixtures enable no language and compile nothing, so -A/-T are intentionally +# omitted: architecture/toolset selection belongs to the real consumer build. +set(generator_args "") +if(TEST_GENERATOR) + list(APPEND generator_args -G "${TEST_GENERATOR}") +endif() set(failures "") function(run_case name expect_success expected_text) @@ -207,6 +230,37 @@ endforeach() set(CASE_NAME cached-selection) run_case("cached selector and explicit override" TRUE "CACHE_SELECTION=OK") + +# Native engines are detected only for this platform, and never override a decision of the user. +set(CASE_NAME autodetect) +set(CASE_CEF "") +set(CASE_WEBVIEW2 "") +set(CASE_WKWEBVIEW "") +set(CASE_WEBKITGTK "") +set(CASE_FLAGS "") +set(CASE_PLATFORM Linux) +set(CASE_VALUE ON) +run_case("Linux enables WebKitGTK when found" TRUE "AUTO WEBFRONT_EMBED_WEBVIEW2=undefined AUTO WEBFRONT_EMBED_WKWEBVIEW=undefined AUTO WEBFRONT_EMBED_WEBKITGTK=ON AUTO WEBFRONT_EMBED_CEF=undefined") +set(CASE_VALUE OFF) +run_case("Linux without WebKitGTK stays OFF and does not fail" TRUE "Native window: WebKitGTK unavailable [(]probe says OFF[)].*AUTO WEBFRONT_EMBED_WEBKITGTK=OFF") +set(CASE_VALUE ON) +set(CASE_PLATFORM Darwin) +run_case("macOS enables WKWebView" TRUE "AUTO WEBFRONT_EMBED_WEBVIEW2=undefined AUTO WEBFRONT_EMBED_WKWEBVIEW=ON AUTO WEBFRONT_EMBED_WEBKITGTK=undefined") +set(CASE_PLATFORM Windows) +run_case("Windows enables WebView2" TRUE "AUTO WEBFRONT_EMBED_WEBVIEW2=ON AUTO WEBFRONT_EMBED_WKWEBVIEW=undefined") +set(CASE_PLATFORM Linux) +set(CASE_WEBKITGTK OFF) +run_case("an explicit OFF is kept" TRUE "AUTO WEBFRONT_EMBED_WEBKITGTK=OFF") +set(CASE_WEBKITGTK ON) +set(CASE_VALUE OFF) +run_case("an explicit ON is kept" TRUE "AUTO WEBFRONT_EMBED_WEBKITGTK=ON") +set(CASE_WEBKITGTK "") +set(CASE_PLATFORM FreeBSD) +set(CASE_FLAGS "") +run_case("an unsupported platform enables nothing" TRUE "AUTO WEBFRONT_EMBED_WEBKITGTK=undefined") +set(CASE_PLATFORM Windows) +set(CASE_VALUE "") +set(CASE_FLAGS "") # Invalid registration metadata fails before add_test() or loading platform dependencies. set(CASE_NAME register) set(CASE_VALUE duplicate) @@ -242,7 +296,7 @@ set(CASE_VALUE valid) run_case("custom always-available browser" TRUE "TYPE=webfront::frontend::TestBrowserFrontend") set(CASE_VALUE strict) run_case("always-available rejects strict policy" FALSE "cannot use POLICY strict with ALWAYS_AVAILABLE") -foreach(CASE_VALUE DESCRIPTION PLATFORMS SUPPORT SETUP TEST_PLATFORMS TEST_SETUP TEST_NAME TEST_TIMEOUT XVFB_LINUX) +foreach(CASE_VALUE DESCRIPTION PLATFORMS SUPPORT SETUP TEST_PLATFORMS TEST_SETUP TEST_NAME TEST_TIMEOUT XVFB_LINUX NATIVE) run_case("browser rejects ${CASE_VALUE}" FALSE "Frontend 'TestBrowser' cannot use ${CASE_VALUE} without OPTION") endforeach() set(CASE_VALUE "") @@ -350,7 +404,8 @@ foreach(case webkitgtk-linux cef-linux cef-macos cef-windows cef-disabled missin # changed generator or previous discovery result cannot influence the next invocation. file(REMOVE_RECURSE "${CMAKE_CURRENT_BINARY_DIR}/frontend-tests/${case}") execute_process( - COMMAND "${CMAKE_COMMAND}" -S "${ROOT}/test/frontends" -B "${CMAKE_CURRENT_BINARY_DIR}/frontend-tests/${case}" + COMMAND "${CMAKE_COMMAND}" -S "${ROOT}/test/cmake/frontends" -B "${CMAKE_CURRENT_BINARY_DIR}/frontend-tests/${case}" + ${generator_args} -DROOT=${ROOT} -DCASE=${case} RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE error) if(NOT result EQUAL 0) @@ -439,8 +494,10 @@ run_case("WebKitGTK selector" TRUE "TYPE=webfront::frontend::WebKitGTKFrontend") set(CASE_WEBKITGTK OFF) run_case("WebKitGTK tests require support" FALSE "requires WEBFRONT_EMBED_WEBKITGTK=ON") -execute_process(COMMAND "${CMAKE_COMMAND}" -S "${ROOT}/test/frontends" - -B "${CMAKE_CURRENT_BINARY_DIR}/frontend-tests/webkitgtk-missing-sdk" -DROOT=${ROOT} -DCASE=webkitgtk-missing-sdk +file(REMOVE_RECURSE "${CMAKE_CURRENT_BINARY_DIR}/frontend-tests/webkitgtk-missing-sdk") +execute_process(COMMAND "${CMAKE_COMMAND}" -S "${ROOT}/test/cmake/frontends" + -B "${CMAKE_CURRENT_BINARY_DIR}/frontend-tests/webkitgtk-missing-sdk" ${generator_args} + -DROOT=${ROOT} -DCASE=webkitgtk-missing-sdk RESULT_VARIABLE missing_sdk OUTPUT_VARIABLE sdk_output ERROR_VARIABLE sdk_error) if(missing_sdk EQUAL 0 OR NOT "${sdk_output}${sdk_error}" MATCHES "WEBFRONT_EMBED_WEBKITGTK=ON requires") list(APPEND failures "Missing WebKitGTK SDK did not report its enabling option: ${sdk_output}${sdk_error}") diff --git a/test/cmake/CheckManualTransportBenchmarks.cmake b/test/cmake/CheckManualTransportBenchmarks.cmake new file mode 100644 index 00000000..e61c4178 --- /dev/null +++ b/test/cmake/CheckManualTransportBenchmarks.cmake @@ -0,0 +1,22 @@ +# Transport timings are manual tools, never CTest cases, default build dependencies or CI jobs. +cmake_minimum_required(VERSION 3.31) +file(GLOB workflows "${ROOT}/.github/workflows/*.yml") +foreach(workflow IN LISTS workflows) + file(READ "${workflow}" text) + if(text MATCHES "transport[_-]benchmark|TransportBenchmark|performance-linux") + message(FATAL_ERROR "Transport measurement has returned to CI: ${workflow}") + endif() +endforeach() +foreach(frontend WebKitGTK WebView2 WKWebView) + file(READ "${ROOT}/cmake/${frontend}Support.cmake" text) + string(TOLOWER "${frontend}" target) + if(NOT text MATCHES "add_executable\\(${target}_transport_benchmark EXCLUDE_FROM_ALL") + message(FATAL_ERROR "${frontend} measurement must be an explicit manual build target") + endif() + if(NOT text MATCHES "add_test\\(NAME ${frontend}TransportContracts" OR NOT text MATCHES "WEBFRONT_TRANSPORT_CONTRACTS_ONLY") + message(FATAL_ERROR "${frontend} must retain its short direct-channel contract test") + endif() + if(text MATCHES "add_test\\(NAME ${frontend}TransportBenchmark" OR text MATCHES "add_dependencies\\(webtest ${target}_transport_benchmark") + message(FATAL_ERROR "${frontend} measurement must not be a CTest case or a webtest dependency") + endif() +endforeach() diff --git a/test/cmake/CheckMinimalCoreAssets.cmake b/test/cmake/CheckMinimalCoreAssets.cmake new file mode 100644 index 00000000..eda898fd --- /dev/null +++ b/test/cmake/CheckMinimalCoreAssets.cmake @@ -0,0 +1,119 @@ +# Guard of the minimal core (ADR-016): the generated resource headers of include/webfront/ are a +# closed, normative list with a size budget. Adding a web resource means changing this list and the +# ADR in the same change. +# cmake -DROOT= -P test/cmake/CheckMinimalCoreAssets.cmake +cmake_minimum_required(VERSION 3.31) + +if(NOT ROOT) + message(FATAL_ERROR "ROOT is required") +endif() + +# Normative list: header file name under include/webfront/system/. +set(allowed + WebFrontJsData.hpp # bridge WebFront.js + FallbackIndexHtmlData.hpp # fallback page + FallbackModuleData.hpp # fallback module + FaviconData.hpp # default favicon + DeveloperIndexHtmlData.hpp # bootstrap page + DeveloperBootstrapData.hpp # bootstrap loader + DeveloperReleaseData.hpp) # pinned release (URL and SHA-512, no payload) +# Budget on the decoded bytes of the embedded payloads, independent of their encoding. +set(budget_bytes 153600) + +file(GLOB_RECURSE headers RELATIVE "${ROOT}/include/webfront" "${ROOT}/include/webfront/*.hpp") +list(SORT headers) + +set(generated "") +foreach(header IN LISTS headers) + get_filename_component(name "${header}" NAME) + file(READ "${ROOT}/include/webfront/${header}" text) + # A resource header is named *Data.hpp or embeds a payload (a dataSize constant). + if(name MATCHES "Data\\.hpp$" OR text MATCHES "dataSize[ \t]*[{=]") + list(APPEND generated "${header}") + endif() +endforeach() + +set(unexpected "") +set(unreadable "") +set(decoded_total 0) +set(encoded_total 0) +set(file_total 0) +foreach(header IN LISTS generated) + get_filename_component(name "${header}" NAME) + if(NOT header STREQUAL "system/${name}" OR NOT name IN_LIST allowed) + list(APPEND unexpected "${header}") + continue() + endif() + file(SIZE "${ROOT}/include/webfront/${header}" file_size) + math(EXPR file_total "${file_total} + ${file_size}") + file(READ "${ROOT}/include/webfront/${header}" text) + # Only DeveloperReleaseData.hpp carries no payload. Any other header must declare one decimal + # dataSize ({n} or = n, spaces allowed) and a known encoding: a size the guard cannot read is refused. + string(REGEX MATCHALL "dataSize" size_mentions "${text}") + list(LENGTH size_mentions mention_count) + if(name STREQUAL "DeveloperReleaseData.hpp") + if(mention_count) + list(APPEND unreadable "${header}: the release data must not carry a payload") + endif() + set(encoded 0) + set(decoded 0) + set(kind "no payload") + elseif(NOT mention_count EQUAL 1 + OR NOT text MATCHES "dataSize[ \t\r\n]*[{=][ \t\r\n]*([0-9]+)[ \t\r\n]*[;}]") + list(APPEND unreadable "${header}: expected exactly one decimal 'dataSize' declaration") + continue() + else() + set(encoded ${CMAKE_MATCH_1}) + set(decoded ${encoded}) + set(kind "identity") + if(NOT text MATCHES "encoding[ \t\r\n]*[{=][ \t\r\n]*(\"[a-z]*\")?[ \t\r\n]*[;}]") + list(APPEND unreadable "${header}: unreadable 'encoding' declaration") + continue() + endif() + if(CMAKE_MATCH_1 STREQUAL "\"gzip\"") + # The decoded size is the ISIZE trailer: the last four bytes, little endian. + string(REGEX MATCHALL "0x[0-9a-f]+" words "${text}") + string(REGEX REPLACE "0x" "" words "${words}") + string(REPLACE ";" "" hex "${words}") + math(EXPR trailer "(${encoded} - 4) * 2") + string(SUBSTRING "${hex}" ${trailer} 8 isize) + string(REGEX REPLACE "^(..)(..)(..)(..)$" "0x\\4\\3\\2\\1" isize "${isize}") + math(EXPR decoded "${isize}") + set(kind "gzip") + elseif(NOT CMAKE_MATCH_1 STREQUAL "" AND NOT CMAKE_MATCH_1 STREQUAL "\"\"") + list(APPEND unreadable "${header}: unsupported encoding ${CMAKE_MATCH_1}") + continue() + endif() + endif() + math(EXPR decoded_total "${decoded_total} + ${decoded}") + math(EXPR encoded_total "${encoded_total} + ${encoded}") + message(STATUS "${header}: ${kind}, ${decoded} decoded, ${encoded} encoded bytes") +endforeach() + +# Every listed resource must exist: a stale list is as wrong as a stale directory. +set(missing "") +foreach(name IN LISTS allowed) + if(NOT EXISTS "${ROOT}/include/webfront/system/${name}") + list(APPEND missing "${name}") + endif() +endforeach() + +message(STATUS "Embedded resources: ${decoded_total} decoded, ${encoded_total} encoded bytes, " + "${file_total} bytes of headers (budget ${budget_bytes} decoded)") + +if(unexpected) + list(JOIN unexpected "\n " list) + message(FATAL_ERROR "Resource headers outside the normative list of ADR-016:\n ${list}\n" + "Remove them, or amend the ADR and test/cmake/CheckMinimalCoreAssets.cmake together.") +endif() +if(unreadable) + list(JOIN unreadable "\n " list) + message(FATAL_ERROR "Resource headers the guard cannot measure:\n ${list}") +endif() +if(missing) + list(JOIN missing "\n " list) + message(FATAL_ERROR "Listed resource headers are missing:\n ${list}") +endif() +if(decoded_total GREATER budget_bytes) + message(FATAL_ERROR "Embedded resources total ${decoded_total} decoded bytes, over the budget of ${budget_bytes}") +endif() diff --git a/test/cmake/CheckMinimalCoreAssetsNegative.cmake b/test/cmake/CheckMinimalCoreAssetsNegative.cmake new file mode 100644 index 00000000..4be32793 --- /dev/null +++ b/test/cmake/CheckMinimalCoreAssetsNegative.cmake @@ -0,0 +1,98 @@ +# The guard of the minimal core must fail on an unlisted resource header and pass once it is removed. +# cmake -DROOT= -DWORK_DIR= -P test/cmake/CheckMinimalCoreAssetsNegative.cmake +cmake_minimum_required(VERSION 3.31) + +if(NOT ROOT OR NOT WORK_DIR) + message(FATAL_ERROR "ROOT and WORK_DIR are required") +endif() +file(REMOVE_RECURSE "${WORK_DIR}") +file(MAKE_DIRECTORY "${WORK_DIR}/include") +file(COPY "${ROOT}/include/webfront" DESTINATION "${WORK_DIR}/include") + +function(run_guard result_variable output_variable) + execute_process( + COMMAND "${CMAKE_COMMAND}" -DROOT=${WORK_DIR} -P "${CMAKE_CURRENT_LIST_DIR}/CheckMinimalCoreAssets.cmake" + RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE error) + set(${result_variable} "${result}" PARENT_SCOPE) + set(${output_variable} "${output}${error}" PARENT_SCOPE) +endfunction() + +run_guard(clean_result clean_output) +if(NOT clean_result EQUAL 0) + message(FATAL_ERROR "The guard rejects a clean copy of the headers:\n${clean_output}") +endif() + +set(rogue "${WORK_DIR}/include/webfront/system/RogueData.hpp") +file(WRITE "${rogue}" "#pragma once\n// not a normative resource\n") +run_guard(rogue_result rogue_output) +if(rogue_result EQUAL 0 OR NOT rogue_output MATCHES "system/RogueData\\.hpp") + message(FATAL_ERROR "The guard accepts an unlisted *Data.hpp:\n${rogue_output}") +endif() + +# A payload hidden behind another name is a resource too. +file(REMOVE "${rogue}") +file(WRITE "${WORK_DIR}/include/webfront/system/Sneaky.hpp" + "#pragma once\nstruct Sneaky { static constexpr unsigned long dataSize{1}; };\n") +run_guard(sneaky_result sneaky_output) +if(sneaky_result EQUAL 0 OR NOT sneaky_output MATCHES "system/Sneaky\\.hpp") + message(FATAL_ERROR "The guard accepts an unlisted payload header:\n${sneaky_output}") +endif() + +file(REMOVE "${WORK_DIR}/include/webfront/system/Sneaky.hpp") +# A size the guard cannot read is refused rather than counted as zero. +foreach(declaration "dataSize = 999999;" "dataSize{ 999999 };" "dataSize{0x10};" "dataSize{1'000};" "dataSize{kSize};") + file(WRITE "${WORK_DIR}/include/webfront/system/FaviconData.hpp" + "#pragma once\nstruct FaviconData { static constexpr std::string_view encoding{}; static constexpr std::size_t ${declaration} };\n") + run_guard(unreadable_result unreadable_output) + if(unreadable_result EQUAL 0 OR NOT unreadable_output MATCHES "FaviconData\\.hpp") + message(FATAL_ERROR "The guard accepts '${declaration}':\n${unreadable_output}") + endif() +endforeach() +# Spaced and '=' forms are read, so their size is counted against the budget. +foreach(declaration "dataSize = 999999;" "dataSize{ 999999 };") + file(WRITE "${WORK_DIR}/include/webfront/system/FaviconData.hpp" + "#pragma once\nstruct FaviconData { static constexpr std::string_view encoding{}; static constexpr std::size_t ${declaration} };\n") + run_guard(spaced_result spaced_output) + if(spaced_result EQUAL 0 OR NOT spaced_output MATCHES "over the budget") + message(FATAL_ERROR "The guard does not count '${declaration}':\n${spaced_output}") + endif() +endforeach() +# An unknown encoding and a missing size are refused, and the release data must stay payload free. +file(WRITE "${WORK_DIR}/include/webfront/system/FaviconData.hpp" + "#pragma once\nstruct FaviconData { static constexpr std::string_view encoding{\"br\"}; static constexpr std::size_t dataSize{8}; };\n") +run_guard(encoding_result encoding_output) +if(encoding_result EQUAL 0 OR NOT encoding_output MATCHES "unsupported encoding") + message(FATAL_ERROR "The guard accepts an unknown encoding:\n${encoding_output}") +endif() +file(WRITE "${WORK_DIR}/include/webfront/system/FaviconData.hpp" "#pragma once\nstruct FaviconData {};\n") +run_guard(nosize_result nosize_output) +if(nosize_result EQUAL 0 OR NOT nosize_output MATCHES "FaviconData\\.hpp") + message(FATAL_ERROR "The guard accepts a resource without a size:\n${nosize_output}") +endif() +file(COPY "${ROOT}/include/webfront/system/FaviconData.hpp" DESTINATION "${WORK_DIR}/include/webfront/system") +file(APPEND "${WORK_DIR}/include/webfront/system/DeveloperReleaseData.hpp" "inline constexpr unsigned dataSize{999999};\n") +run_guard(release_result release_output) +if(release_result EQUAL 0 OR NOT release_output MATCHES "must not carry a payload") + message(FATAL_ERROR "The guard accepts a payload in the release data:\n${release_output}") +endif() +file(COPY "${ROOT}/include/webfront/system/DeveloperReleaseData.hpp" DESTINATION "${WORK_DIR}/include/webfront/system") + +# A resource that outgrows the budget is refused as well. +file(REMOVE "${WORK_DIR}/include/webfront/system/Sneaky.hpp") +file(WRITE "${WORK_DIR}/include/webfront/system/FaviconData.hpp" + "#pragma once\nstruct FaviconData { static constexpr std::string_view encoding{}; static constexpr std::size_t dataSize{999999}; };\n") +run_guard(budget_result budget_output) +if(budget_result EQUAL 0 OR NOT budget_output MATCHES "over the budget") + message(FATAL_ERROR "The guard accepts an oversized resource:\n${budget_output}") +endif() + +# The budget counts decoded bytes: a small gzip stream whose trailer announces 196608 bytes is over it. +file(WRITE "${WORK_DIR}/include/webfront/system/FaviconData.hpp" + "#pragma once\nstruct FaviconData {\n static constexpr std::string_view encoding{\"gzip\"};\n" + " static constexpr std::size_t dataSize{8};\n static constexpr std::array data{ 0x0000000000000300 };\n};\n") +run_guard(gzip_result gzip_output) +if(gzip_result EQUAL 0 OR NOT gzip_output MATCHES "gzip, 196608 decoded" OR NOT gzip_output MATCHES "over the budget") + message(FATAL_ERROR "The guard ignores the decoded size of a gzip resource:\n${gzip_output}") +endif() + +file(REMOVE_RECURSE "${WORK_DIR}") diff --git a/test/cmake/CheckNativeAutodetect.cmake b/test/cmake/CheckNativeAutodetect.cmake new file mode 100644 index 00000000..f8e2aee5 --- /dev/null +++ b/test/cmake/CheckNativeAutodetect.cmake @@ -0,0 +1,29 @@ +cmake_minimum_required(VERSION 3.31) +if(NOT ROOT OR NOT WORK_DIR) + message(FATAL_ERROR "ROOT and WORK_DIR are required") +endif() +file(REMOVE_RECURSE "${WORK_DIR}") +function(configure name directory expected) + execute_process(COMMAND "${CMAKE_COMMAND}" -S "${ROOT}/test/cmake/native-autodetect" + -B "${WORK_DIR}/${directory}" "-DROOT=${ROOT}" ${ARGN} + RESULT_VARIABLE status OUTPUT_VARIABLE output ERROR_VARIABLE error) + if(NOT status EQUAL 0 OR NOT "${output}${error}" MATCHES "${expected}") + message(FATAL_ERROR "${name}: status ${status}\n${output}\n${error}") + endif() +endfunction() + +# All calls reuse real CMake caches, including -D overrides equal to the last detected value. +configure("initial automatic OFF" off "RESULT=OFF" -DPLATFORM=Linux -DPROBE=OFF) +configure("automatic OFF is probed again" off "RESULT=ON" -DPROBE=ON) +configure("explicit ON survives a missing dependency" off "RESULT=ON" + -DPROBE=OFF -DWEBFRONT_EMBED_WEBKITGTK:BOOL=ON) +configure("explicit ON stays explicit" off "RESULT=ON" -DPROBE=OFF) +configure("remove the override to resume detection" off "RESULT=OFF" -UWEBFRONT_EMBED_WEBKITGTK) +configure("explicit OFF survives a newly available dependency" off "RESULT=OFF" + -DPROBE=ON -DWEBFRONT_EMBED_WEBKITGTK:BOOL=OFF) +configure("explicit OFF stays explicit" off "RESULT=OFF" -DPROBE=ON) +configure("initial automatic ON" on "RESULT=ON" -DPLATFORM=Linux -DPROBE=ON) +configure("automatic ON is probed again" on "RESULT=OFF" -DPROBE=OFF) +configure("examples on an unsupported platform" unsupported "no native engine is registered for FreeBSD" + -DPLATFORM=FreeBSD -DTEST_EXAMPLES=ON) +message(STATUS "Native detection preserves explicit options across configurations") diff --git a/cmake/CheckNewcomerDocs.cmake b/test/cmake/CheckNewcomerDocs.cmake similarity index 73% rename from cmake/CheckNewcomerDocs.cmake rename to test/cmake/CheckNewcomerDocs.cmake index 36c987d7..188c51bd 100644 --- a/cmake/CheckNewcomerDocs.cmake +++ b/test/cmake/CheckNewcomerDocs.cmake @@ -26,11 +26,19 @@ _read(ci .github/workflows/BuildAndTest.yml) _read(frontends docs/FRONTENDS.md) _read(developer_guide docs/DEVELOPER_ENVIRONMENT.md) _read(wkwebview_guide docs/WKWEBVIEW.md) -_read(developer_release include/system/DeveloperReleaseData.hpp) -# The local-review instructions must not silently use an unpublished default archive. -foreach(text readme wkwebview_guide) +_read(developer_release include/webfront/system/DeveloperReleaseData.hpp) +# The README starts the example on the environment pinned in the release data; only the guides of the maintainers and of +# WKWebView show the explicit local archive, which must not silently use an unpublished default. +_require("${readme}" "```bash\nexamples/WebFrontLifeDeveloper\n```" "README starts the example without argument") +_require("${readme}" "-DWEBFRONT_AUTODETECT_NATIVE=OFF" "README advanced native selection") +_require("${root}" "webfront_autodetect_native_frontends()" "native engine autodetection") +foreach(option WEBFRONT_EMBED_WEBVIEW2 WEBFRONT_EMBED_WKWEBVIEW WEBFRONT_EMBED_WEBKITGTK) + _require("${readme}" "-D${option}=ON|OFF" "README explicit engine choice") +endforeach() +_require("${life}" "parseLifeDeveloperOptions" "default project and explicit arguments") +foreach(text developer_guide wkwebview_guide) _require("${${text}}" "/webfront/developer/preview/provision/environment.tgz \"$integrity\"" "${text} local bootstrap arguments") - _require("${${text}}" "require('./build-developer-environment/provision.json').integrity" "${text} trusted local integrity") + _require("${${text}}" "sed -n 's/^ \"integrity\": \"\\(.*\\)\",$/\\1/p' build-developer-environment/provision.json" "${text} trusted local integrity") endforeach() string(REGEX MATCH "https://[^\"]+/environment\\.tgz" developer_url "${developer_release}") if(NOT developer_url) @@ -43,7 +51,7 @@ _require("${root}" "add_subdirectory(examples)" "examples directory") _require("${root}" "option(ENABLE_TESTING \"Enable Test Builds\" OFF)" "tests opt-in") _require("${root}" "add_library(WebFront::WebFront ALIAS WebFront)" "consumer alias") _require("${readme}" "target_link_libraries(MyApp PRIVATE WebFront::WebFront)" "consumer instructions") -_require("${readme}" "cmake -S . -B build -DCMAKE_BUILD_TYPE=Release\ncmake --build build --parallel 2" "Life initial build") +_require("${readme}" "mkdir build\ncd build\ncmake ..\ncmake --build .\n" "Life standard build") foreach(line "app.cppFunction(\"life.step\", &webfront::demo::nextLife);" "app.bootstrap(\"developer\");" "app.show();") _require("${readme}" "${line}" "Life bootstrap snippet") _require("${life}" "${line}" "compiled Life bootstrap") @@ -51,8 +59,9 @@ endforeach() foreach(line "#include " "Grid nextLife(const Grid& cells)" "app.cppFunction(\"life.step\", &nextLife);") _require("${readme}" "${line}" "self-contained introductory Life application") endforeach() -_require("${readme}" "webfront::NativeAppWithAssets app;" "offline application snippet") -_require("${embedded}" "webfront::NativeAppWithAssets app;" "compiled offline application") +_require("${readme}" "webfront::demo::LifeApp app{\"life-project\"};" "developer application snippet") +_require("${readme}" "webfront::demo::LifeAppWithAssets app;" "offline application snippet") +_require("${embedded}" "webfront::demo::LifeAppWithAssets app;" "compiled offline application") foreach(target HelloWorld WebFrontLifeConsole WebFrontLifeDeveloper WebFrontLifeEmbedded) _require("${examples}" "add_executable(${target} " "compiled example stage") if(NOT target STREQUAL "HelloWorld") @@ -64,11 +73,11 @@ list(LENGTH targets target_count) if(NOT target_count EQUAL 4) list(APPEND failures "Only Hello World and the three Life stages should be built") endif() -foreach(command "wf create life" "wf install react@19.3.1 react-dom@19.3.1" "wf preview ui/main.tsx" "wf embed ui/main.tsx --output generated/LifeUI.hpp") +foreach(command "wf create life" "wf init" "wf install react@19.3.1 react-dom@19.3.1" "wf dev ui/main.tsx" "wf check" "wf test" "wf embed ui/main.tsx --output generated/LifeUI.hpp") _require("${readme}" "${command}" "developer-terminal walkthrough") endforeach() _require("${readme}" "-DWEBFRONT_LIFE_ASSETS=\"$PWD/life-project/generated/LifeUI.hpp\"" "generated-header build") -_require("${readme}" "src=\"docs/images/life-bootstrap.gif\" width=\"560\"" "early Life animation") +_require("${readme}" "src=\"docs/images/life-bootstrap.gif\" width=\"100%\"" "early Life animation") foreach(path examples/hello-world/HelloWorld.cpp examples/life/Life.hpp examples/life/ui/main.tsx docs/images/life-preview.jpg docs/images/life-bootstrap.gif) if(NOT EXISTS "${ROOT}/${path}") list(APPEND failures "missing walkthrough asset ${path}") @@ -101,7 +110,7 @@ foreach(text readme agents ci) _require("${${text}}" "-DWEBFRONT_EMBED_CEF=OFF -DENABLE_TESTING=ON" "${text} baseline configuration") endforeach() foreach(text readme agents) - _require("${${text}}" "ctest --test-dir build --output-on-failure" "${text} test command") + _require("${${text}}" "ctest --test-dir build --output-on-failure --parallel 4" "${text} test command") endforeach() if(failures) list(JOIN failures "\n " joined) diff --git a/test/cmake/CheckNoNode.cmake b/test/cmake/CheckNoNode.cmake new file mode 100644 index 00000000..c35a552d --- /dev/null +++ b/test/cmake/CheckNoNode.cmake @@ -0,0 +1,128 @@ +# Global guard of #303: no path of WebFront depends on Node.js, npm or npx. Every file of the project is audited, not only the +# CMake find_program calls: sources, scripts, manifests, locks, workflows, development configuration, current documentation and +# the generated files that are allowed. The registries, formats and metadata of npm (package.json, integrities, semver, the +# resolution fields) are not matched: only imports and APIs of Node, commands of node/npm/npx, their configuration, their +# requirement in current documentation and the "like node.js" positioning of #303 are. +# +# The files are the tracked ones (`git ls-files`); outside a work tree (a source archive) the equivalent inventory is every file +# of the tree except the untracked build products (build*/, _deps/, .cache/). The exceptions are a list of files, each with the +# class of match it allows and why (test/cmake/NodeGuardExceptions.cmake); an exception that matches nothing fails too. +# cmake -DROOT= [-DGIT_EXECUTABLE=] [-DEXCEPTIONS=] -P test/cmake/CheckNoNode.cmake +cmake_minimum_required(VERSION 3.31) + +if(NOT ROOT) + message(FATAL_ERROR "ROOT is required") +endif() +if(NOT DEFINED EXCEPTIONS) + set(EXCEPTIONS "${CMAKE_CURRENT_LIST_DIR}/NodeGuardExceptions.cmake") +endif() + +# |: a CMake regular expression has no \b or lookaround, so a word is delimited by a character class. +set(word_start "(^|[^A-Za-z0-9_./@-])") +set(patterns + "node-import|[\"'`]node:[a-z_]" + "commonjs|${word_start}require\\([\"']" + "node-api|process\\.(argv|exit|execPath|platform|exitCode|cwd|stdout|stderr|versions|env)" + "node-command|${word_start}(node|nodejs)[ \t]+(-[-A-Za-z]|[^ \t\n]*\\.(mjs|cjs|js)([^A-Za-z]|$))" + "npm-command|${word_start}npm[ \t]+((ci|install|i|run|test|exec|start|publish|init|audit|update)([^A-Za-z0-9_]|$)|-)" + "tool-word|${word_start}(npx|nodejs|corepack)([^A-Za-z0-9_-]|$)" + "shebang|#![^\n]*node" + "node-config|setup-node|node_modules|NODE_EXECUTABLE|REQUIRE_NODE|find_program\\([^)]*node|\"engines\"" + "requirement|(require|requires|required|need|needs|needed|use|uses) (Node|npm)([^A-Za-z]|$)" + "positioning|à la [Nn]ode|like Node\\.js|[Nn]ode\\.js-like|npm/npx|npx/node|\\| *(npm|npx) *\\|") +set(binary_extensions ico png jpg jpeg gif wasm tgz gz zip woff woff2 ttf otf) + +# --- the inventory +set(files "") +if(GIT_EXECUTABLE) + execute_process(COMMAND "${GIT_EXECUTABLE}" -c core.quotepath=off ls-files WORKING_DIRECTORY "${ROOT}" OUTPUT_VARIABLE listed + RESULT_VARIABLE git_status ERROR_QUIET) +endif() +if(GIT_EXECUTABLE AND git_status EQUAL 0 AND listed) + string(REPLACE "\r" "" listed "${listed}") + string(REPLACE "\n" ";" files "${listed}") +else() + file(GLOB_RECURSE absolute RELATIVE "${ROOT}" "${ROOT}/*" "${ROOT}/.*/*") + foreach(file IN LISTS absolute) + if(NOT file MATCHES "^(build[^/]*|_deps|\\.cache|\\.git)/") + list(APPEND files "${file}") + endif() + endforeach() +endif() +list(SORT files) +list(LENGTH files file_count) +if(file_count LESS 1) + message(FATAL_ERROR "The inventory of ${ROOT} is empty") +endif() + +# --- the exceptions: set(NODE_GUARD_EXCEPTIONS "||" ...) +set(NODE_GUARD_EXCEPTIONS "") +include("${EXCEPTIONS}") +set(allowed "") +foreach(exception IN LISTS NODE_GUARD_EXCEPTIONS) + string(REPLACE "|" ";" parts "${exception}") + list(LENGTH parts parts_count) + if(NOT parts_count EQUAL 3) + message(FATAL_ERROR "An exception is ||: ${exception}") + endif() + list(GET parts 0 file) + list(GET parts 1 class) + list(GET parts 2 reason) + if(NOT reason) + message(FATAL_ERROR "The exception for ${file} (${class}) has no reason") + endif() + list(APPEND allowed "${file}:${class}") +endforeach() + +# --- the audit +set(violations "") +set(used "") +foreach(file IN LISTS files) + get_filename_component(extension "${file}" LAST_EXT) + string(REPLACE "." "" extension "${extension}") + string(TOLOWER "${extension}" extension) + if(file STREQUAL "" OR IS_DIRECTORY "${ROOT}/${file}" OR extension IN_LIST binary_extensions OR NOT EXISTS "${ROOT}/${file}") + continue() + endif() + file(READ "${ROOT}/${file}" content) + # The compile-time constant of the browser bundlers (React reads it) is not an API of Node. + string(REPLACE "process.env.NODE_ENV" "" content "${content}") + foreach(entry IN LISTS patterns) + string(FIND "${entry}" "|" bar) + string(SUBSTRING "${entry}" 0 ${bar} class) + math(EXPR start "${bar} + 1") + string(SUBSTRING "${entry}" ${start} -1 expression) + if(content MATCHES "${expression}") + set(matched "${CMAKE_MATCH_0}") + if("${file}:${class}" IN_LIST allowed) + list(APPEND used "${file}:${class}") + else() + # The line of the first match, for the report. + string(FIND "${content}" "${matched}" offset) + string(SUBSTRING "${content}" 0 ${offset} before) + string(REGEX MATCHALL "\n" breaks "${before}") + list(LENGTH breaks line) + math(EXPR line "${line} + 1") + string(REPLACE "\n" " " matched "${matched}") + list(APPEND violations "${file}:${line}: [${class}] ${matched}") + endif() + endif() + endforeach() +endforeach() + +set(unused "") +foreach(entry IN LISTS allowed) + if(NOT entry IN_LIST used) + list(APPEND unused "${entry}") + endif() +endforeach() + +if(violations) + list(JOIN violations "\n " text) + message(FATAL_ERROR "Node.js, npm or npx appear outside the exceptions of the guard:\n ${text}") +endif() +if(unused) + list(JOIN unused "\n " text) + message(FATAL_ERROR "These exceptions of the guard match nothing any more; remove them:\n ${text}") +endif() +message(STATUS "${file_count} files audited: no dependency on Node.js, npm or npx") diff --git a/test/cmake/CheckNoNodeNegative.cmake b/test/cmake/CheckNoNodeNegative.cmake new file mode 100644 index 00000000..ae162482 --- /dev/null +++ b/test/cmake/CheckNoNodeNegative.cmake @@ -0,0 +1,86 @@ +# The guard of #303 (CheckNoNode.cmake) must fail on what #303 removes and pass on what it keeps. The injections live in a +# scratch tree, never in the checkout: an import of node:fs, `npm ci` in a workflow, `engines.node` in a manifest, a Node +# script that nothing calls, an old command in a guide, a find_program of node, a shebang, a CommonJS require, the "like +# node.js" positioning. An npm registry URL, the formats and metadata of npm packages, the compile-time constant of the +# bundlers and a test that checks the rejection of a Node import pass. +# cmake -DROOT= -DWORK_DIR= -P test/cmake/CheckNoNodeNegative.cmake +cmake_minimum_required(VERSION 3.31) + +if(NOT ROOT OR NOT WORK_DIR) + message(FATAL_ERROR "ROOT and WORK_DIR are required") +endif() +set(guard "${ROOT}/test/cmake/CheckNoNode.cmake") +file(WRITE "${WORK_DIR}/no-exceptions.cmake" "set(NODE_GUARD_EXCEPTIONS \"\")\n") + +# audit( ): audits the tree of WORK_DIR/tree. +function(audit expected description class) + execute_process(COMMAND "${CMAKE_COMMAND}" "-DROOT=${WORK_DIR}/tree" "-DEXCEPTIONS=${WORK_DIR}/no-exceptions.cmake" -P "${guard}" + RESULT_VARIABLE status OUTPUT_VARIABLE output ERROR_VARIABLE errors) + if(NOT status EQUAL expected) + message(FATAL_ERROR "${description}: expected status ${expected}, got ${status}\n${output}${errors}") + endif() + if(class AND NOT errors MATCHES "\\[${class}\\]") + message(FATAL_ERROR "${description}: the class ${class} is not reported\n${errors}") + endif() +endfunction() + +# fresh( ): the scratch tree holds one file. +function(fresh path content) + file(REMOVE_RECURSE "${WORK_DIR}/tree") + file(WRITE "${WORK_DIR}/tree/${path}" "${content}") +endfunction() + +fresh("README.md" "# WebFront\n\nBuild with CMake. Packages come from the npm registry https://registry.npmjs.org/.\n") +audit(0 "a clean tree" "") + +# What must fail. +fresh("tools/check.mjs" "import fs from 'node:fs';\nfs.readFileSync('x');\n") +audit(1 "an import of node:fs" "node-import") +fresh(".github/workflows/Build.yml" "steps:\n - run: npm ci --prefix tools\n") +audit(1 "npm ci in a workflow" "npm-command") +fresh(".github/workflows/Build.yml" "steps:\n - uses: actions/setup-node@v6\n") +audit(1 "setup-node in a workflow" "node-config") +fresh("package.json" "{\n \"name\": \"x\",\n \"engines\": {\"node\": \">=22\"}\n}\n") +audit(1 "engines.node in a manifest of the project" "node-config") +fresh("tools/unused.mjs" "const [, , input] = process.argv;\nconsole.log(input);\n") +audit(1 "a Node script that nothing calls" "node-api") +fresh("docs/GUIDE.md" "Regenerate the assets:\n\n```sh\nnode tools/build.mjs out\n```\n") +audit(1 "an old command in a guide" "node-command") +fresh("docs/GUIDE.md" "Install first with `npx esbuild`.\n") +audit(1 "npx in a guide" "tool-word") +fresh("CMakeLists.txt" "find_program(NODE_EXECUTABLE NAMES node REQUIRED)\n") +audit(1 "a find_program of node" "node-config") +fresh("bin/tool" "#!/usr/bin/env node\nconsole.log(1);\n") +audit(1 "a shebang" "shebang") +fresh("tools/legacy.js" "const fs = require('fs');\n") +audit(1 "a CommonJS require" "commonjs") +fresh("docs/GUIDE.md" "Tests require Node.js 22 or newer.\n") +audit(1 "a requirement in a guide" "requirement") +fresh("docs/GUIDE.md" "wf works à la node.js.\n") +audit(1 "the positioning of #303" "positioning") + +# What must pass. +fresh("src/bundle.mjs" "define: {'process.env.NODE_ENV': '\"production\"'}\n") +audit(0 "the compile-time constant of the bundlers" "") +fresh("lock.json" "{\"packages\": {\"semver@7.7.3\": {\"integrity\": \"sha512-x\", \"resolved\": \"https://registry.npmjs.org/semver/-/semver-7.7.3.tgz\"}}}\n") +audit(0 "an npm registry URL and the metadata of a package" "") +fresh("spec/rejects.mjs" "it('refuses a Node import', () => expect(compile('import fs from \"fs\"')).toThrowError(/Node API/));\n") +audit(0 "a test that checks the rejection of a Node import" "") +fresh("docs/GUIDE.md" "wf install reads package.json files and the dist-tags of the registry.\n") +audit(0 "the formats of npm packages" "") + +# An exception that matches nothing is itself an error, and one that matches is accepted. +fresh("docs/HISTORY.md" "The old build ran `npm ci`.\n") +file(WRITE "${WORK_DIR}/allowing.cmake" "set(NODE_GUARD_EXCEPTIONS \"docs/HISTORY.md|npm-command|history of the migration\")\n") +execute_process(COMMAND "${CMAKE_COMMAND}" "-DROOT=${WORK_DIR}/tree" "-DEXCEPTIONS=${WORK_DIR}/allowing.cmake" -P "${guard}" + RESULT_VARIABLE status ERROR_VARIABLE errors) +if(NOT status EQUAL 0) + message(FATAL_ERROR "A listed exception must be accepted:\n${errors}") +endif() +fresh("docs/HISTORY.md" "The old build was replaced.\n") +execute_process(COMMAND "${CMAKE_COMMAND}" "-DROOT=${WORK_DIR}/tree" "-DEXCEPTIONS=${WORK_DIR}/allowing.cmake" -P "${guard}" + RESULT_VARIABLE status ERROR_VARIABLE errors) +if(status EQUAL 0 OR NOT errors MATCHES "match nothing any more") + message(FATAL_ERROR "An exception that matches nothing must fail:\n${errors}") +endif() +file(REMOVE_RECURSE "${WORK_DIR}") diff --git a/cmake/CheckReleaseVersion.cmake b/test/cmake/CheckReleaseVersion.cmake similarity index 97% rename from cmake/CheckReleaseVersion.cmake rename to test/cmake/CheckReleaseVersion.cmake index 82ee20b0..f2d0d358 100644 --- a/cmake/CheckReleaseVersion.cmake +++ b/test/cmake/CheckReleaseVersion.cmake @@ -7,7 +7,7 @@ if(NOT ROOT OR NOT DEFINED EXPECTED_VERSION) message(FATAL_ERROR "ROOT and EXPECTED_VERSION are required") endif() -file(STRINGS "${ROOT}/include/WebFront.hpp" declarations +file(STRINGS "${ROOT}/include/webfront/WebFront.hpp" declarations REGEX "^inline constexpr std::string_view version = \"[0-9]+\\.[0-9]+\\.[0-9]+\";") list(LENGTH declarations count) if(NOT count EQUAL 1) diff --git a/cmake/CheckReleaseVersionTests.cmake b/test/cmake/CheckReleaseVersionTests.cmake similarity index 92% rename from cmake/CheckReleaseVersionTests.cmake rename to test/cmake/CheckReleaseVersionTests.cmake index f18e01b4..a5f28ad6 100644 --- a/cmake/CheckReleaseVersionTests.cmake +++ b/test/cmake/CheckReleaseVersionTests.cmake @@ -3,13 +3,13 @@ cmake_minimum_required(VERSION 3.31) if(NOT ROOT OR NOT WORK) message(FATAL_ERROR "ROOT and WORK are required") endif() -file(MAKE_DIRECTORY "${WORK}/archive/include") -file(WRITE "${WORK}/archive/include/WebFront.hpp" +file(MAKE_DIRECTORY "${WORK}/archive/include/webfront") +file(WRITE "${WORK}/archive/include/webfront/WebFront.hpp" "inline constexpr std::string_view version = \"0.1.0\";\n") function(check_case description expected_result expected_message) execute_process(COMMAND "${CMAKE_COMMAND}" "-DROOT=${WORK}/archive" ${ARGN} - -P "${ROOT}/cmake/CheckReleaseVersion.cmake" + -P "${ROOT}/test/cmake/CheckReleaseVersion.cmake" RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE error) if(expected_result STREQUAL "success") if(NOT result EQUAL 0) @@ -49,7 +49,7 @@ execute_process(COMMAND "${GIT_EXECUTABLE}" -c user.name=VersionTest -c user.ema execute_process(COMMAND "${GIT_EXECUTABLE}" tag v0.1.1 WORKING_DIRECTORY "${repo}" COMMAND_ERROR_IS_FATAL ANY) execute_process(COMMAND "${CMAKE_COMMAND}" "-DROOT=${repo}" -DEXPECTED_VERSION=0.1.0 - -P "${ROOT}/cmake/CheckReleaseVersion.cmake" + -P "${ROOT}/test/cmake/CheckReleaseVersion.cmake" RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE error) if(result EQUAL 0 OR NOT "${output}${error}" MATCHES "Release tag 'v0.1.1' differs") message(FATAL_ERROR "Tag at HEAD mismatch was not detected: ${output}${error}") diff --git a/test/cmake/CheckRepositoryLayout.cmake b/test/cmake/CheckRepositoryLayout.cmake new file mode 100644 index 00000000..c9b2e748 --- /dev/null +++ b/test/cmake/CheckRepositoryLayout.cmake @@ -0,0 +1,83 @@ +# The tracked root of the repository is a closed list, so that the README stays visible on the +# GitHub page, and no third-party source is vendored: libraries are locked npm packages (#319). The repository is a wf project whose +# manifest and lock are js/developer/webfront.project.json and its lock (#354, #315): the environment builds itself with wf run. +# Each entry has to stay at the root (#352): .clang-format sits next to the C++ it formats (include/webfront/, test/, examples/) and +# .clang-tidy is cmake/clang-tidy.yaml, passed by cmake/StaticAnalyzers.cmake; wf only grants files under the project root, which must contain js/, test/, examples/ and +# include/; Git, GitHub, CMake and the agents require the others. There is no .devcontainer: the CI is the toolchain reference. +# cmake -DROOT= [-DGIT_EXECUTABLE=] -P test/cmake/CheckRepositoryLayout.cmake +cmake_minimum_required(VERSION 3.31) + +if(NOT ROOT) + message(FATAL_ERROR "ROOT is required") +endif() + +set(expected + .gitattributes .github .gitignore + AGENTS.md CMakeLists.txt README.md + cmake docs examples include js test) + +set(actual "") +set(from_git OFF) +if(NOT GIT_EXECUTABLE) + find_program(GIT_EXECUTABLE git) +endif() +if(GIT_EXECUTABLE AND EXISTS "${ROOT}/.git") + execute_process(COMMAND "${GIT_EXECUTABLE}" ls-files + WORKING_DIRECTORY "${ROOT}" OUTPUT_VARIABLE tracked RESULT_VARIABLE git_result ERROR_QUIET) + if(git_result EQUAL 0) + set(from_git ON) + string(REPLACE "\n" ";" tracked "${tracked}") + foreach(path IN LISTS tracked) + string(REGEX REPLACE "/.*$" "" top "${path}") + list(APPEND actual "${top}") + if(path MATCHES "(^|/)(third_party|vendor|node_modules)/") + message(FATAL_ERROR "Third-party sources are not vendored; lock the library as a package instead: ${path}") + endif() + endforeach() + endif() +endif() +if(NOT from_git) + # A source archive holds tracked content only, minus its export-ignore entries; a local + # checkout without Git metadata may also hold build trees, which are not tracked content. + file(GLOB entries LIST_DIRECTORIES true RELATIVE "${ROOT}" "${ROOT}/*" "${ROOT}/.[!.]*") + list(FILTER entries EXCLUDE REGEX "^(build|\\.git$)") + set(actual ${entries}) + file(GLOB_RECURSE nested LIST_DIRECTORIES false RELATIVE "${ROOT}" "${ROOT}/*") + foreach(path IN LISTS nested) + if(path MATCHES "^(build|\\.git/)") + continue() + endif() + if(path MATCHES "(^|/)(third_party|vendor|node_modules)/") + message(FATAL_ERROR "Third-party sources are not vendored; lock the library as a package instead: ${path}") + endif() + endforeach() +endif() +# .gitattributes and .gitignore are export-ignored, so archives legitimately lack them. +set(archive_optional .gitattributes .gitignore) +list(REMOVE_ITEM actual "" ${archive_optional}) +list(REMOVE_ITEM expected ${archive_optional}) +list(REMOVE_DUPLICATES actual) +list(SORT actual) +list(SORT expected) + +if(NOT actual STREQUAL expected) + set(unexpected ${actual}) + list(REMOVE_ITEM unexpected ${expected}) + set(missing ${expected}) + list(REMOVE_ITEM missing ${actual}) + message(FATAL_ERROR "The repository root drifted from the declared layout.\n" + " unexpected: ${unexpected}\n missing: ${missing}") +endif() + +# include/ exposes a single namespace directory, which holds headers only (no JavaScript, so that +# installers need no filter). Its .clang-format is the only other file: the style of the library, kept next to the headers. +file(GLOB include_entries LIST_DIRECTORIES true RELATIVE "${ROOT}/include" "${ROOT}/include/*") +if(NOT include_entries STREQUAL "webfront") + message(FATAL_ERROR "include/ must contain only webfront/, found: ${include_entries}") +endif() +file(GLOB_RECURSE include_files LIST_DIRECTORIES false RELATIVE "${ROOT}/include/webfront" "${ROOT}/include/webfront/*") +foreach(file IN LISTS include_files) + if(NOT file MATCHES "\\.(hpp|h)$" AND NOT file STREQUAL ".clang-format") + message(FATAL_ERROR "include/webfront must hold headers only: ${file}") + endif() +endforeach() diff --git a/test/cmake/CheckRepositoryLayoutNegative.cmake b/test/cmake/CheckRepositoryLayoutNegative.cmake new file mode 100644 index 00000000..37be4dac --- /dev/null +++ b/test/cmake/CheckRepositoryLayoutNegative.cmake @@ -0,0 +1,71 @@ +# The layout guard must accept the declared root and reject a vendored third-party source, wherever it is tracked. +# cmake -DROOT= -DGIT_EXECUTABLE= -DWORK_DIR= -P test/cmake/CheckRepositoryLayoutNegative.cmake +cmake_minimum_required(VERSION 3.31) + +if(NOT ROOT OR NOT GIT_EXECUTABLE OR NOT WORK_DIR) + message(FATAL_ERROR "ROOT, GIT_EXECUTABLE and WORK_DIR are required") +endif() +file(REMOVE_RECURSE "${WORK_DIR}" "${WORK_DIR}-archive") +file(MAKE_DIRECTORY "${WORK_DIR}/include/webfront") +foreach(entry .gitattributes .github .gitignore AGENTS.md CMakeLists.txt README.md + cmake docs examples js test) + file(WRITE "${WORK_DIR}/${entry}/placeholder" "") +endforeach() +file(WRITE "${WORK_DIR}/include/webfront/WebFront.hpp" "") + +function(git) + execute_process(COMMAND "${GIT_EXECUTABLE}" ${ARGN} WORKING_DIRECTORY "${WORK_DIR}" + RESULT_VARIABLE result OUTPUT_QUIET ERROR_VARIABLE error) + if(NOT result EQUAL 0) + message(FATAL_ERROR "git ${ARGN} failed: ${error}") + endif() +endfunction() + +function(run_guard result_variable output_variable) + execute_process( + COMMAND "${CMAKE_COMMAND}" -DROOT=${WORK_DIR} -DGIT_EXECUTABLE=${GIT_EXECUTABLE} + -P "${CMAKE_CURRENT_LIST_DIR}/CheckRepositoryLayout.cmake" + RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE error) + set(${result_variable} "${result}" PARENT_SCOPE) + set(${output_variable} "${output}${error}" PARENT_SCOPE) +endfunction() + +git(init -q) +git(add -A -f) +run_guard(clean_result clean_output) +if(NOT clean_result EQUAL 0) + message(FATAL_ERROR "The guard rejects the declared layout:\n${clean_output}") +endif() + +foreach(rogue js/developer/vendor/lib.mjs js/third_party/lib.mjs js/node_modules/lib/index.js) + file(WRITE "${WORK_DIR}/${rogue}" "export {};\n") + git(add -f "${rogue}") + run_guard(rogue_result rogue_output) + if(rogue_result EQUAL 0 OR NOT rogue_output MATCHES "not vendored") + message(FATAL_ERROR "The guard accepts the vendored source ${rogue}:\n${rogue_output}") + endif() + git(rm -q -f --cached "${rogue}") +endforeach() + +# A root directory outside the declared list is refused too. +file(WRITE "${WORK_DIR}/extras/notes.txt" "notes\n") +git(add -f extras/notes.txt) +run_guard(root_result root_output) +if(root_result EQUAL 0 OR NOT root_output MATCHES "unexpected: extras") + message(FATAL_ERROR "The guard accepts an undeclared root directory:\n${root_output}") +endif() + +# A source archive has no Git metadata: the nested paths are scanned instead. +file(COPY "${WORK_DIR}/" DESTINATION "${WORK_DIR}-archive" PATTERN ".git" EXCLUDE) +file(REMOVE_RECURSE "${WORK_DIR}-archive/extras") +file(REMOVE_RECURSE "${WORK_DIR}-archive/js/developer/vendor" "${WORK_DIR}-archive/js/third_party" "${WORK_DIR}-archive/js/node_modules") +set(WORK_DIR "${WORK_DIR}-archive") +run_guard(archive_result archive_output) +if(NOT archive_result EQUAL 0) + message(FATAL_ERROR "The guard rejects the declared layout of an archive:\n${archive_output}") +endif() +file(WRITE "${WORK_DIR}/js/vendor/lib.mjs" "export {};\n") +run_guard(archive_rogue_result archive_rogue_output) +if(archive_rogue_result EQUAL 0 OR NOT archive_rogue_output MATCHES "not vendored") + message(FATAL_ERROR "The guard accepts a vendored source in an archive:\n${archive_rogue_output}") +endif() diff --git a/test/cmake/CheckSelfBuildRefresh.cmake b/test/cmake/CheckSelfBuildRefresh.cmake new file mode 100644 index 00000000..63dcca56 --- /dev/null +++ b/test/cmake/CheckSelfBuildRefresh.cmake @@ -0,0 +1,36 @@ +# The bootstrap bundles and their checksums that wf regenerates from the sources must be the checked-in ones, and the core +# headers that embed the bundles, rendered from them by js/core/EmbedAsset.cmake, too: the proof that the checked-in bundles +# and headers are rebuilt from the sources by wf and CMake alone. The pinned header and its checksum are the exceptions: +# the sources build a version that is not published yet, so the refresh writes the header of that version. +# Usage: cmake -DSOURCE= -DPROJECT= -DOUTPUT= -P CheckSelfBuildRefresh.cmake +set(pinned "include/webfront/system/DeveloperReleaseData.hpp") +foreach(name js/core/bootstrap/bootstrap.bundle.mjs js/developer/environment/packages.bundle.mjs + js/developer/environment/PACKAGES-LICENSE.txt) + execute_process(COMMAND "${CMAKE_COMMAND}" -E compare_files "${SOURCE}/${name}" "${PROJECT}/${name}" RESULT_VARIABLE different) + if(different) + message(FATAL_ERROR "${name} rebuilt by wf differs from the checked-in file") + endif() +endforeach() +foreach(asset "js/core/bootstrap/index.html;DeveloperIndexHtmlData" "js/core/bootstrap/bootstrap.bundle.mjs;DeveloperBootstrapData") + list(GET asset 0 input) + list(GET asset 1 struct) + execute_process(COMMAND "${CMAKE_COMMAND}" "-DINPUT=${PROJECT}/${input}" -DSTRUCT=${struct} + "-DOUTPUT=${PROJECT}/rendered/${struct}.hpp" -P "${SOURCE}/js/core/EmbedAsset.cmake" RESULT_VARIABLE rendered) + execute_process(COMMAND "${CMAKE_COMMAND}" -E compare_files "${SOURCE}/include/webfront/system/${struct}.hpp" + "${PROJECT}/rendered/${struct}.hpp" RESULT_VARIABLE different) + if(NOT rendered EQUAL 0 OR different) + message(FATAL_ERROR "${struct}.hpp rendered from the bundle rebuilt by wf differs from the checked-in header") + endif() +endforeach() +execute_process(COMMAND "${CMAKE_COMMAND}" -E compare_files "${PROJECT}/${pinned}" "${PROJECT}/${OUTPUT}/DeveloperReleaseData.hpp" RESULT_VARIABLE different) +if(different) + message(FATAL_ERROR "The refresh and the build wrote different pinned headers") +endif() + +file(READ "${SOURCE}/js/developer/environment/bundles.json" expected) +file(READ "${PROJECT}/js/developer/environment/bundles.json" actual) +string(JSON expected REMOVE "${expected}" "${pinned}") +string(JSON actual REMOVE "${actual}" "${pinned}") +if(NOT actual STREQUAL expected) + message(FATAL_ERROR "bundles.json rebuilt by wf differs from the checked-in checksums") +endif() diff --git a/cmake/CheckWKWebViewSupport.cmake b/test/cmake/CheckWKWebViewSupport.cmake similarity index 100% rename from cmake/CheckWKWebViewSupport.cmake rename to test/cmake/CheckWKWebViewSupport.cmake diff --git a/cmake/CheckWebView2Architecture.cmake b/test/cmake/CheckWebView2Architecture.cmake similarity index 92% rename from cmake/CheckWebView2Architecture.cmake rename to test/cmake/CheckWebView2Architecture.cmake index 51047317..0001e578 100644 --- a/cmake/CheckWebView2Architecture.cmake +++ b/test/cmake/CheckWebView2Architecture.cmake @@ -73,15 +73,20 @@ foreach(probe ARM64EC UNKNOWN) endif() endforeach() -# Call the lifecycle hook from this script's directory, outside webtest/, without building or +# Call the lifecycle hook from this script's directory, outside test/web/, without building or # downloading anything. Production source paths and test working directories must be absolute. function(add_executable target) foreach(source IN LISTS ARGN) + if(source STREQUAL "EXCLUDE_FROM_ALL") + continue() + endif() if(NOT IS_ABSOLUTE "${source}" OR NOT EXISTS "${source}") message(FATAL_ERROR "Lifecycle hook source must be an existing absolute path: '${source}'") endif() endforeach() endfunction() +function(add_dependencies) +endfunction() function(add_test) endfunction() function(set_tests_properties) @@ -91,8 +96,8 @@ function(set_tests_properties) endif() math(EXPR index "${index} + 1") list(GET ARGN ${index} directory) - if(NOT directory STREQUAL "${ROOT}/webtest") - message(FATAL_ERROR "Lifecycle hook must use '${ROOT}/webtest', got '${directory}'") + if(NOT directory STREQUAL "${ROOT}/test/web") + message(FATAL_ERROR "Lifecycle hook must use '${ROOT}/test/web', got '${directory}'") endif() endfunction() include("${ROOT}/cmake/Frontends.cmake") diff --git a/cmake/CheckWebView2Toolchain.cmake b/test/cmake/CheckWebView2Toolchain.cmake similarity index 100% rename from cmake/CheckWebView2Toolchain.cmake rename to test/cmake/CheckWebView2Toolchain.cmake diff --git a/test/cmake/CompareFiles.cmake b/test/cmake/CompareFiles.cmake new file mode 100644 index 00000000..ae2da188 --- /dev/null +++ b/test/cmake/CompareFiles.cmake @@ -0,0 +1,14 @@ +# Fails unless every listed file is byte for byte the same in two directories. +# Usage: cmake -DLEFT= -DRIGHT= "-DFILES=;..." -P CompareFiles.cmake +foreach(name IN LISTS FILES) + foreach(side LEFT RIGHT) + if(NOT EXISTS "${${side}}/${name}") + message(FATAL_ERROR "${${side}}/${name} does not exist") + endif() + endforeach() + execute_process(COMMAND "${CMAKE_COMMAND}" -E compare_files "${LEFT}/${name}" "${RIGHT}/${name}" RESULT_VARIABLE different) + if(different) + message(FATAL_ERROR "${name} differs between ${LEFT} and ${RIGHT}") + endif() + message(STATUS "same ${name}") +endforeach() diff --git a/cmake/FrontendTestHelpers.cmake b/test/cmake/FrontendTestHelpers.cmake similarity index 100% rename from cmake/FrontendTestHelpers.cmake rename to test/cmake/FrontendTestHelpers.cmake diff --git a/test/cmake/NodeGuardExceptions.cmake b/test/cmake/NodeGuardExceptions.cmake new file mode 100644 index 00000000..bfd78470 --- /dev/null +++ b/test/cmake/NodeGuardExceptions.cmake @@ -0,0 +1,41 @@ +# The exceptions of the guard of #303 (CheckNoNode.cmake): "||". Each is a file and the one class of match +# it may keep; a new match anywhere else fails the guard, and an exception that matches nothing any more fails it too. +# The contract of #303 allows only: the registries, formats and metadata of npm; the locks and notices of dependencies; +# historical elements (Git history, earlier versions of the ADRs, migration notes); and the fixtures, diagnostics and tests +# that check the rejection of Node APIs, imports and executables. +set(NODE_GUARD_EXCEPTIONS + # The guard itself: the words of its patterns and of its documentation, and the injections that it must reject. + "test/cmake/CheckNoNode.cmake|tool-word|names the tools the guard looks for" + "test/cmake/CheckNoNode.cmake|shebang|a pattern and a comment of the guard" + "test/cmake/CheckNoNode.cmake|node-config|names the configuration the guard looks for" + "test/cmake/CheckNoNode.cmake|positioning|names the positioning the guard looks for" + "test/cmake/CheckNoNodeNegative.cmake|node-import|injection that the guard must reject" + "test/cmake/CheckNoNodeNegative.cmake|commonjs|injection that the guard must reject" + "test/cmake/CheckNoNodeNegative.cmake|node-api|injection that the guard must reject" + "test/cmake/CheckNoNodeNegative.cmake|npm-command|injection that the guard must reject" + "test/cmake/CheckNoNodeNegative.cmake|tool-word|injection that the guard must reject" + "test/cmake/CheckNoNodeNegative.cmake|shebang|injection that the guard must reject" + "test/cmake/CheckNoNodeNegative.cmake|node-config|injection that the guard must reject" + "test/cmake/CheckNoNodeNegative.cmake|requirement|injection that the guard must reject" + "test/cmake/CheckNoNodeNegative.cmake|positioning|injection that the guard must reject" + "test/cmake/NodeGuardExceptions.cmake|node-config|names the directory whose TypeScript layout is an exception" + # Specs that check the rejection of Node imports and of installation scripts. + "test/developer/specs/environment-specs.mjs|node-import|checks that an import of a Node module is refused" + "test/developer/specs/environment-specs.mjs|node-command|a package whose installation script is refused" + "test/developer/specs/scripts-specs.mjs|node-import|checks that Node built-in modules are recognized and refused" + # The proof that no JavaScript runtime is needed: the action that deletes them names them. + ".github/actions/remove-node/action.yml|tool-word|names the tools it removes from the runner" + # Migration note and history. + "docs/NODE_TOOLS_MIGRATION.md|npm-command|migration note: names the former commands" + "docs/NODE_TOOLS_MIGRATION.md|tool-word|migration note: names the former tools" + "docs/CHANGELOG.md|node-config|history of the releases, which names the options that existed" + # Diagnostics and tests of the rejection of Node APIs. + "js/developer/environment/typecheck-snapshot.mjs|node-config|the layout of /project/node_modules that the TypeScript module resolver reads: wf check cannot resolve a package without it" + "test/cmake/CheckRepositoryLayout.cmake|node-config|names the directory whose tracked presence it rejects, as a vendored source" + "test/cmake/CheckRepositoryLayoutNegative.cmake|node-config|tracks such a directory in a scratch repository to prove that the layout guard rejects it" + "docs/DEVELOPER_ENVIRONMENT.md|node-config|states which directories wf check never lists, the TypeScript layout among them" + # Data of dependencies. + "js/developer/webfront-packages.lock.json|node-command|the lock records the package.json scripts of its dependencies verbatim, and nothing runs them" + "js/developer/webfront-packages.lock.json|npm-command|the lock records the package.json scripts of its dependencies verbatim, and nothing runs them" + "js/developer/webfront-packages.lock.json|node-config|the lock records the file lists of its dependencies verbatim" + "js/developer/environment/packages.bundle.mjs|node-api|semver's debug probe, guarded by typeof process, inside the bundle that is a checked-in generated artifact (lock and notices in PACKAGES-LICENSE.txt)") diff --git a/test/cmake/PrepareJourney.cmake b/test/cmake/PrepareJourney.cmake new file mode 100644 index 00000000..34d7e3f8 --- /dev/null +++ b/test/cmake/PrepareJourney.cmake @@ -0,0 +1,16 @@ +# Completes the manifest that wf init and wf install wrote in the project of the developer journey (#316): the entries and +# the provider that wf build and wf embed use, the specs of wf test, a script under permissions; then copies the files +# the starter does not bring (tsconfig.json for wf check, a spec, the script). +# Usage: cmake -DSOURCE= -DPROJECT= -P PrepareJourney.cmake +set(manifest_path "${PROJECT}/webfront.project.json") +if(NOT EXISTS "${manifest_path}") + message(FATAL_ERROR "wf init has not created ${manifest_path}") +endif() +file(READ "${manifest_path}" manifest) +string(JSON manifest SET "${manifest}" entries "{\"main\": \"ui/main.tsx\"}") +string(JSON manifest SET "${manifest}" providers "{\"LifeUI\": {\"entry\": \"main\", \"output\": \"generated/LifeUI.hpp\"}}") +string(JSON manifest SET "${manifest}" test "{\"specs\": [\"tests/life.spec.js\"]}") +string(JSON manifest SET "${manifest}" scripts "{\"denied\": \"tools/denied.mjs\"}") +string(JSON manifest SET "${manifest}" permissions "{\"files\": [\"tools\"], \"publish\": [\"generated\"]}") +file(WRITE "${manifest_path}" "${manifest}\n") +file(COPY "${SOURCE}/" DESTINATION "${PROJECT}") diff --git a/test/cmake/PrepareSelfBuildProject.cmake b/test/cmake/PrepareSelfBuildProject.cmake new file mode 100644 index 00000000..e550ba4d --- /dev/null +++ b/test/cmake/PrepareSelfBuildProject.cmake @@ -0,0 +1,20 @@ +# Gives the self-build tests a fresh copy of the sources that the environment is built from: the wf project of the +# repository, kept in js/developer (without its lock, which the tests resolve from the local registry), the environment, the tools and scripts, +# the starters, the sources of the core's embedded assets, the specs of the developer environment and the pinned header. The build outputs go inside this copy, +# never into the checkout. The site directory is not created: the first staging creates it. The scripts of the test +# registry are copied too, and, with ARCHIVES, the verified archives of its real packages. +# Usage: cmake -DSOURCE= -DPROJECT= [-DARCHIVES=] -P PrepareSelfBuildProject.cmake +file(REMOVE_RECURSE "${PROJECT}") +file(MAKE_DIRECTORY "${PROJECT}" "${PROJECT}/include/webfront/system" "${PROJECT}/js/developer") +file(COPY "${SOURCE}/js/core" DESTINATION "${PROJECT}/js") +file(COPY "${SOURCE}/js/developer/webfront.project.json" DESTINATION "${PROJECT}/js/developer") +foreach(directory environment scripts tools) + file(COPY "${SOURCE}/js/developer/${directory}" DESTINATION "${PROJECT}/js/developer") +endforeach() +file(COPY "${SOURCE}/examples/life/ui" DESTINATION "${PROJECT}/examples/life") +file(COPY "${SOURCE}/test/web/registry" DESTINATION "${PROJECT}/test/web") +file(COPY "${SOURCE}/test/developer" DESTINATION "${PROJECT}/test") +if(ARCHIVES) + file(COPY "${ARCHIVES}/" DESTINATION "${PROJECT}/registry-archives") +endif() +file(COPY "${SOURCE}/include/webfront/system/DeveloperReleaseData.hpp" DESTINATION "${PROJECT}/include/webfront/system") diff --git a/test/cmake/PrepareWfProject.cmake b/test/cmake/PrepareWfProject.cmake new file mode 100644 index 00000000..ff6e10dc --- /dev/null +++ b/test/cmake/PrepareWfProject.cmake @@ -0,0 +1,4 @@ +# Gives the driver tests a fresh copy of the fixture project. +# Usage: cmake -DSOURCE= -DPROJECT= -P PrepareWfProject.cmake +file(REMOVE_RECURSE "${PROJECT}") +file(COPY "${SOURCE}/" DESTINATION "${PROJECT}") diff --git a/test/cmake/RunWfDriver.cmake b/test/cmake/RunWfDriver.cmake new file mode 100644 index 00000000..d5ca1e0e --- /dev/null +++ b/test/cmake/RunWfDriver.cmake @@ -0,0 +1,152 @@ +# Runs webfront-wf and checks its exit status and output. +# Usage: cmake -DDRIVER= -DPROJECT= -DEXPECT_STATUS= [-DENVIRONMENT= -DINTEGRITY=] +# [-DREGISTRY=] [-DTIMEOUT=] [-DEXPECT_OUTPUT=] [-DEXPECT_REPORT=] [-DFORGE=: +# -DWORK=] [-DRENAME_ENTRY=] [-DFRESH_PROJECT=: an empty project instead of PROJECT] -DCOMMAND=|... -P RunWfDriver.cmake +# MANIFEST_DIR is passed as --manifest-dir; EXPECT_PRESENT and EXPECT_ABSENT are project paths (separated by |) that must +# exist, or not, once the command ended. +# SLEEP_ENVIRONMENT uses a tiny compatible archive whose command records its start before sleeping; EXPECT_FILE +# requires that record after the watchdog exits. Real packaged-script execution is covered by the other driver cases. +# PROVISION is the provision.json of ENVIRONMENT, from which an INTEGRITY left empty is read when the test runs. +# PROFILE is a directory for the browser's own persistent state (WebKitGTK/WebView2 profiles), emptied first: a browser reuses the +# modules it loaded by URL, and the first page that loads another environment through the same profile fails with +# "Importing a module script failed". Every case then starts from nothing. +# FORGE replaces ENVIRONMENT with an archive whose environment.json declares the given protocol and API versions. +if(PROFILE) + file(REMOVE_RECURSE "${PROFILE}") + set(ENV{XDG_DATA_HOME} "${PROFILE}/data") + set(ENV{XDG_CACHE_HOME} "${PROFILE}/cache") + # A fresh native profile also isolates WebView2 HTTP/module caches and lingering + # browser processes. Repeated invocations of the same case get distinct profiles. + string(RANDOM LENGTH 16 ALPHABET 0123456789abcdef webview2_session) + set(ENV{WEBFRONT_TEST_WEBVIEW2_PROFILE} "${PROFILE}/webview2-${webview2_session}") +endif() +if(FORGE) + include("${ROOT}/cmake/WebFrontBootstrap.cmake") + string(REPLACE ":" ";" versions "${FORGE}") + list(GET versions 0 protocol) + list(GET versions 1 api) + file(REMOVE_RECURSE "${WORK}/forged") + file(MAKE_DIRECTORY "${WORK}/forged/package") + file(WRITE "${WORK}/forged/package/environment.json" "{\"protocol\": ${protocol}, \"api\": ${api}, \"entry\": \"runtime.mjs\"}\n") + file(WRITE "${WORK}/forged/package/runtime.mjs" "export function mount() {}\n") + execute_process(COMMAND "${CMAKE_COMMAND}" -E tar czf "${WORK}/forged.tgz" --format=gnutar package + WORKING_DIRECTORY "${WORK}/forged" RESULT_VARIABLE tarred) + if(NOT tarred EQUAL 0) + message(FATAL_ERROR "Cannot build the forged environment") + endif() + set(ENVIRONMENT "${WORK}/forged.tgz") + webfront_file_sri("${ENVIRONMENT}" INTEGRITY) +endif() + +if(PROVISION AND ENVIRONMENT AND NOT INTEGRITY AND NOT FORGE) + file(READ "${PROVISION}" provision) + string(JSON INTEGRITY GET "${provision}" integrity) +endif() + +if(SLEEP_ENVIRONMENT) + # The watchdog must interrupt an active command, independently of WASM compiler startup cost. + include("${ROOT}/cmake/WebFrontBootstrap.cmake") + file(REMOVE_RECURSE "${WORK}/sleep-environment") + file(MAKE_DIRECTORY "${WORK}/sleep-environment/package") + file(COPY "${ROOT}/test/fixtures/wf-sleep-environment/" DESTINATION "${WORK}/sleep-environment/package") + set(ENVIRONMENT "${WORK}/sleep-environment.tgz") + execute_process(COMMAND "${CMAKE_COMMAND}" -E tar czf "${ENVIRONMENT}" --format=gnutar package + WORKING_DIRECTORY "${WORK}/sleep-environment" RESULT_VARIABLE packed) + if(NOT packed EQUAL 0) + message(FATAL_ERROR "Cannot pack the watchdog environment") + endif() + webfront_file_sri("${ENVIRONMENT}" INTEGRITY) +endif() + +if(FRESH_PROJECT) + set(PROJECT "${FRESH_PROJECT}") + file(REMOVE_RECURSE "${PROJECT}") + file(MAKE_DIRECTORY "${PROJECT}") +endif() +if(RENAME_ENTRY) + # The real environment, with its entry module renamed: the driver must follow environment.json. + include("${ROOT}/cmake/WebFrontBootstrap.cmake") + file(REMOVE_RECURSE "${WORK}/renamed") + file(MAKE_DIRECTORY "${WORK}/renamed") + execute_process(COMMAND "${CMAKE_COMMAND}" -E tar xzf "${ENVIRONMENT}" WORKING_DIRECTORY "${WORK}/renamed" RESULT_VARIABLE unpacked) + if(NOT unpacked EQUAL 0) + message(FATAL_ERROR "Cannot unpack the environment") + endif() + file(RENAME "${WORK}/renamed/package/runtime.mjs" "${WORK}/renamed/package/${RENAME_ENTRY}") + file(READ "${WORK}/renamed/package/environment.json" manifest) + string(JSON manifest SET "${manifest}" entry "\"${RENAME_ENTRY}\"") + file(WRITE "${WORK}/renamed/package/environment.json" "${manifest}") + file(REMOVE "${WORK}/renamed.tgz") + execute_process(COMMAND "${CMAKE_COMMAND}" -E tar czf "${WORK}/renamed.tgz" --format=gnutar package + WORKING_DIRECTORY "${WORK}/renamed" RESULT_VARIABLE packed) + if(NOT packed EQUAL 0) + message(FATAL_ERROR "Cannot repack the environment") + endif() + set(ENVIRONMENT "${WORK}/renamed.tgz") + webfront_file_sri("${ENVIRONMENT}" INTEGRITY) +endif() + +set(arguments --project "${PROJECT}") +if(ENVIRONMENT) + list(APPEND arguments --environment "${ENVIRONMENT}" --integrity "${INTEGRITY}") +endif() +if(REGISTRY) + list(APPEND arguments --registry-dir "${REGISTRY}") +endif() +if(MANIFEST_DIR) + list(APPEND arguments --manifest-dir "${MANIFEST_DIR}") +endif() +if(TIMEOUT) + list(APPEND arguments --timeout "${TIMEOUT}") +endif() +if(EXPECT_REPORT) + set(report "${PROJECT}/report.json") + file(REMOVE "${report}") + list(APPEND arguments --report "${report}") +endif() +if(EXPECT_FILE) + file(REMOVE "${PROJECT}/${EXPECT_FILE}") +endif() +string(REPLACE "|" ";" command "${COMMAND}") +execute_process(COMMAND "${DRIVER}" ${arguments} -- ${command} + RESULT_VARIABLE status OUTPUT_VARIABLE output ERROR_VARIABLE errors) +set(text "${output}${errors}") +message(STATUS "exit status ${status}\n${text}") +if(NOT status EQUAL EXPECT_STATUS) + message(FATAL_ERROR "Expected exit status ${EXPECT_STATUS}, got ${status}") +endif() +if(EXPECT_OUTPUT AND NOT text MATCHES "${EXPECT_OUTPUT}") + message(FATAL_ERROR "The output does not match '${EXPECT_OUTPUT}'") +endif() +if(EXPECT_REPORT) + if(NOT EXISTS "${report}") + message(FATAL_ERROR "The driver wrote no report") + endif() + file(READ "${report}" content) + if(NOT content MATCHES "${EXPECT_REPORT}") + message(FATAL_ERROR "The report does not match '${EXPECT_REPORT}': ${content}") + endif() +endif() + +if(EXPECT_FILE) + if(NOT EXISTS "${PROJECT}/${EXPECT_FILE}") + message(FATAL_ERROR "The command did not start: ${EXPECT_FILE} is missing") + endif() + file(READ "${PROJECT}/${EXPECT_FILE}" started) + if(NOT started STREQUAL "running") + message(FATAL_ERROR "The command did not record its running state") + endif() +endif() + +string(REPLACE "|" ";" present "${EXPECT_PRESENT}") +foreach(path IN LISTS present) + if(NOT EXISTS "${PROJECT}/${path}") + message(FATAL_ERROR "The command did not write ${path}") + endif() +endforeach() +string(REPLACE "|" ";" absent "${EXPECT_ABSENT}") +foreach(path IN LISTS absent) + if(EXISTS "${PROJECT}/${path}") + message(FATAL_ERROR "The command wrote ${path}, which belongs elsewhere") + endif() +endforeach() diff --git a/test/cmake/TamperFile.cmake b/test/cmake/TamperFile.cmake new file mode 100644 index 00000000..0947f297 --- /dev/null +++ b/test/cmake/TamperFile.cmake @@ -0,0 +1,6 @@ +# Appends a byte to a file, to simulate a published file that changed. +# Usage: cmake -DFILE= -P TamperFile.cmake +if(NOT EXISTS "${FILE}") + message(FATAL_ERROR "${FILE} does not exist") +endif() +file(APPEND "${FILE}" "x") diff --git a/cmake/TestHardening.cmake b/test/cmake/TestHardening.cmake similarity index 100% rename from cmake/TestHardening.cmake rename to test/cmake/TestHardening.cmake diff --git a/cmake/WKWebViewTestInfo.plist.in b/test/cmake/WKWebViewTestInfo.plist.in similarity index 100% rename from cmake/WKWebViewTestInfo.plist.in rename to test/cmake/WKWebViewTestInfo.plist.in diff --git a/cmake/WebKitGTKTestEnvironment.cmake b/test/cmake/WebKitGTKTestEnvironment.cmake similarity index 100% rename from cmake/WebKitGTKTestEnvironment.cmake rename to test/cmake/WebKitGTKTestEnvironment.cmake diff --git a/test/cmake/cef-copy/CMakeLists.txt b/test/cmake/cef-copy/CMakeLists.txt new file mode 100644 index 00000000..846fef74 --- /dev/null +++ b/test/cmake/cef-copy/CMakeLists.txt @@ -0,0 +1,61 @@ +# Fixture of CheckCEFCopy.cmake: the Linux CEF file copy of cmake/CEFSupport.cmake, with stand-in CEF files and +# custom targets, so that no compiler, SDK or network is needed. STATE selects the case. +cmake_minimum_required(VERSION 3.31) +project(CEFCopyFixture LANGUAGES NONE) +include("${ROOT}/cmake/CEFSupport.cmake") + +if(NOT ROOT OR NOT IS_DIRECTORY "${SOURCE_DIR}") + message(FATAL_ERROR "ROOT and SOURCE_DIR (the stand-in CEF files) must be supplied") +endif() +set(source "${SOURCE_DIR}") +get_property(multi GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +set(config "") +if(multi) + set(config "/$") +endif() + +function(expect actual expected what) + if(NOT actual STREQUAL expected) + message(FATAL_ERROR "${what}: ${actual}, expected ${expected}") + endif() +endfunction() + +# Copies the stand-in runtime file and locales for a target, as copy_cef_runtime_files and copy_cef_resource_files do. +function(copy_for target_name) + _cef_planned_output_directory(${target_name} output) + _cef_shared_copy(${target_name} "${output}" NAME runtime SOURCE_DIR "${source}" FILES libcef.so DIRECTORY locales) + set(planned "${output}" PARENT_SCOPE) +endfunction() + +add_custom_target(everything ALL) + +if(STATE STREQUAL "plan") + # Two targets of this directory without an output directory share it, and one copy target. + add_custom_target(first) + add_custom_target(second) + copy_for(first) + expect("${planned}" "${CMAKE_CURRENT_BINARY_DIR}${config}" "default destination") + copy_for(second) + string(MD5 key "${planned}") + get_target_property(dependencies second MANUALLY_ADDED_DEPENDENCIES) + expect("${dependencies}" "webfront_cef_runtime_${key}" "second target's copy target") + # A relative RUNTIME_OUTPUT_DIRECTORY is under the target's binary directory. + add_custom_target(binned) + set_target_properties(binned PROPERTIES RUNTIME_OUTPUT_DIRECTORY bin) + copy_for(binned) + expect("${planned}" "${CMAKE_CURRENT_BINARY_DIR}/bin${config}" "relative output directory") + # A target of another directory building into the same absolute directory shares that copy target. + add_subdirectory(other) + add_dependencies(everything first second binned elsewhere) +elseif(STATE STREQUAL "per-config") + add_custom_target(configured) + set_target_properties(configured PROPERTIES RUNTIME_OUTPUT_DIRECTORY_RELEASE bin) + set(CMAKE_BUILD_TYPE Release) + copy_for(configured) +elseif(STATE STREQUAL "late") + add_custom_target(late) + copy_for(late) + set_target_properties(late PROPERTIES RUNTIME_OUTPUT_DIRECTORY bin) +else() + message(FATAL_ERROR "Unknown STATE ${STATE}") +endif() diff --git a/test/cmake/cef-copy/other/CMakeLists.txt b/test/cmake/cef-copy/other/CMakeLists.txt new file mode 100644 index 00000000..feafe598 --- /dev/null +++ b/test/cmake/cef-copy/other/CMakeLists.txt @@ -0,0 +1,8 @@ +# A target of another directory, building into the directory of the target "binned": it shares its copy target. +add_custom_target(elsewhere) +set_target_properties(elsewhere PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin") +copy_for(elsewhere) +expect("${planned}" "${CMAKE_BINARY_DIR}/bin${config}" "absolute output directory") +string(MD5 key "${planned}") +get_target_property(dependencies elsewhere MANUALLY_ADDED_DEPENDENCIES) +expect("${dependencies}" "webfront_cef_runtime_${key}" "shared copy target across directories") diff --git a/test/cef-testing/CMakeLists.txt b/test/cmake/cef-testing/CMakeLists.txt similarity index 100% rename from test/cef-testing/CMakeLists.txt rename to test/cmake/cef-testing/CMakeLists.txt diff --git a/test/cef-testing/dependency/CMakeLists.txt b/test/cmake/cef-testing/dependency/CMakeLists.txt similarity index 100% rename from test/cef-testing/dependency/CMakeLists.txt rename to test/cmake/cef-testing/dependency/CMakeLists.txt diff --git a/test/consumer/CMakeLists.txt b/test/cmake/consumer/CMakeLists.txt similarity index 100% rename from test/consumer/CMakeLists.txt rename to test/cmake/consumer/CMakeLists.txt diff --git a/test/consumer/CheckOptions.cmake b/test/cmake/consumer/CheckOptions.cmake similarity index 100% rename from test/consumer/CheckOptions.cmake rename to test/cmake/consumer/CheckOptions.cmake diff --git a/test/consumer/main.cpp b/test/cmake/consumer/main.cpp similarity index 96% rename from test/consumer/main.cpp rename to test/cmake/consumer/main.cpp index 588b8f70..ec271820 100644 --- a/test/consumer/main.cpp +++ b/test/cmake/consumer/main.cpp @@ -11,7 +11,7 @@ #endif #endif -#include +#include int main(int argc, char**) { if (argc > 1) { // never taken by the smoke test: it only proves that the library compiles and links diff --git a/test/frontends/CMakeLists.txt b/test/cmake/frontends/CMakeLists.txt similarity index 97% rename from test/frontends/CMakeLists.txt rename to test/cmake/frontends/CMakeLists.txt index f9953781..67b1275c 100644 --- a/test/frontends/CMakeLists.txt +++ b/test/cmake/frontends/CMakeLists.txt @@ -64,7 +64,7 @@ elseif(CASE STREQUAL "webkitgtk-linux") set(name WebFrontWebKitGTKIntegration) set(expected_timeout 90) set(expect_xvfb ON) - include("${ROOT}/cmake/WebKitGTKTestEnvironment.cmake") + include("${ROOT}/test/cmake/WebKitGTKTestEnvironment.cmake") function(webfront_add_webkitgtk_tests) list(LENGTH ARGN shared_count) if(NOT shared_count EQUAL 8 OR NOT "WebFrontWebKitGTKIntegration" IN_LIST ARGN) @@ -125,7 +125,7 @@ if(expect_xvfb) # A deterministic stand-in: this fixture checks generated commands, never runs the browser. set(XVFB_RUN_EXECUTABLE "${CMAKE_COMMAND}" CACHE FILEPATH "Xvfb fixture" FORCE) endif() -webfront_add_browser_tests(browser "${frontend}" "${ROOT}/webtest" lifecycle) +webfront_add_browser_tests(browser "${frontend}" "${ROOT}/test/web" lifecycle) if(CASE STREQUAL "missing-xvfb-hook") if(TEST ${name} OR NOT TEST EngineLifecycle) message(FATAL_ERROR "Missing Xvfb must skip Jasmine while preserving independent engine tests") @@ -141,7 +141,7 @@ endif() set(expected_TIMEOUT "${expected_timeout}") set(expected_LABELS web-integration) set(expected_RESOURCE_LOCK webfront_port_9002) -set(expected_WORKING_DIRECTORY "${ROOT}/webtest") +set(expected_WORKING_DIRECTORY "${ROOT}/test/web") if(NOT EXISTS "${expected_WORKING_DIRECTORY}/JasmineTest.cpp") message(FATAL_ERROR "Expected the actual WebFront browser asset directory") endif() diff --git a/test/frontends/TestSupport.cmake b/test/cmake/frontends/TestSupport.cmake similarity index 100% rename from test/frontends/TestSupport.cmake rename to test/cmake/frontends/TestSupport.cmake diff --git a/test/cmake/native-autodetect/CMakeLists.txt b/test/cmake/native-autodetect/CMakeLists.txt new file mode 100644 index 00000000..96016bf4 --- /dev/null +++ b/test/cmake/native-autodetect/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.31) +project(NativeAutodetect LANGUAGES CXX) + +include("${ROOT}/cmake/Frontends.cmake") +set(CMAKE_SYSTEM_NAME "${PLATFORM}") +function(webfront_probe_native_frontend name out reason) + set(${out} "${PROBE}" PARENT_SCOPE) + set(${reason} "controlled probe" PARENT_SCOPE) +endfunction() +webfront_autodetect_native_frontends() +webfront_declare_frontend_options() +message(STATUS "RESULT=${WEBFRONT_EMBED_WEBKITGTK}") + +if(TEST_EXAMPLES) + list(APPEND CMAKE_MODULE_PATH "${ROOT}/cmake") + foreach(target WebFront WebFront_warnings WebFront_options) + add_library(${target} INTERFACE) + endforeach() + function(webfront_setup_frontends_for_target target) + endfunction() + add_subdirectory("${ROOT}/examples" examples) + get_target_property(definitions WebFrontLifeDeveloper COMPILE_DEFINITIONS) + if("WEBFRONT_LIFE_NATIVE_WINDOW" IN_LIST definitions) + message(FATAL_ERROR "An unsupported platform must use the default browser") + endif() +endif() diff --git a/test/developer/memory-bridge.mjs b/test/developer/memory-bridge.mjs new file mode 100644 index 00000000..fedac5c9 --- /dev/null +++ b/test/developer/memory-bridge.mjs @@ -0,0 +1,53 @@ +// An in-memory project behind the webfront.developer.* callbacks, with the store's directory replacement, group +// publication and precondition. Shared by the Node tests; it uses only browser APIs, so that the tests can move to +// a browser runner. +export function memoryBridge(storage = new Map()) { + const transactions = new Map(); + let next = 0; + // The state of a file is its content: compared synchronously, so that check and publication stay one step. + const stateOf = paths => JSON.stringify(paths.map(path => storage.has(path) ? [...storage.get(path)] : null)); + const inside = destination => [...storage.keys()].filter(key => key.startsWith(destination + '/')); + 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); + }, + // Like Store::list: the sorted names of a directory as a JSON array, directories ending with '/'. + list: directory => { + const prefix = directory ? directory + '/' : ''; + const names = new Set([...storage.keys()].filter(key => key.startsWith(prefix)) + .map(key => key.slice(prefix.length)).map(rest => rest.includes('/') ? rest.split('/')[0] + '/' : rest)); + if (!names.size) throw new Error('Cannot list project directory: ' + directory); + return new TextEncoder().encode(JSON.stringify([...names].sort())); + }, + 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(); + if (previous.length !== offset) throw new Error('Non-sequential developer write'); + files.set(path, new Uint8Array([...previous, ...bytes])); + }, + commit: id => { + const {destination, directory, files, replace} = transactions.get(id); + if (!replace && (storage.has(destination) || inside(destination).length)) + throw new Error('Starter destination already exists'); + // A directory publication replaces the whole directory, as the store does. + if (directory) inside(destination).forEach(key => storage.delete(key)); + 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}; +} diff --git a/test/developer/specs/development-specs.mjs b/test/developer/specs/development-specs.mjs new file mode 100644 index 00000000..a4c8613c --- /dev/null +++ b/test/developer/specs/development-specs.mjs @@ -0,0 +1,139 @@ +// Specs of wf dev's host side, which supplement the real-WASM browser regression in test/web/developer-specs.mjs. +import {bundleContext} from '../../../js/developer/environment/bundler.mjs'; +import {observedRead, inputsChanged, compilerSession, waitForPoll, buildEntries, diagnosticsText, dev} from '../../../js/developer/environment/development.mjs'; +import {memoryBridge} from '../memory-bridge.mjs'; +import {rejects, throws, esbuild} from '../support.mjs'; + +describe('wf dev', () => { + // Compiling the wasm of esbuild takes a while on a machine without a GPU. + beforeAll(esbuild, 120000); + + const encode = text => new TextEncoder().encode(text); + + const lock = {format: 1, roots: {}, packages: {}}; + it('one esbuild context reads changed imports, reports syntax errors and recovers', async () => { + const files = new Map([['main.ts', encode("import {value} from './value'; console.log(value)")], ['value.ts', encode('export const value = 1')]]); + const context = await bundleContext(await esbuild(), {entry: 'main.ts', lock, readProject: async path => { + if (!files.has(path)) throw new Error('missing'); + return files.get(path); + }}); + try { + const text = async () => new TextDecoder().decode((await context.rebuild()).get('app.js')); + expect(await text()).toMatch(/console.log\(1\)/); + files.set('value.ts', encode('export const value = 2')); + expect(await text()).toMatch(/console.log\(2\)/); + files.set('value.ts', encode('export const value = ;')); + await rejects(text(), error => diagnosticsText(error).includes('value.ts:1:')); + files.set('value.ts', encode('export const value = 3')); + expect(await text()).toMatch(/console.log\(3\)/); + } finally { await context.dispose(); } + }, 60000); + + it('polling compares read-time bytes and missing probes and ignores unrelated writes', async () => { + const {bridge, storage: files} = memoryBridge(new Map([['ui/main.ts', encode('one')]])); + const observed = new Map(), budget = {bytes: 0}; + await observedRead(bridge, 'ui/main.ts', observed, budget); + await rejects(observedRead(bridge, 'ui/new.ts', observed, budget), /Cannot read project file/); + expect(await inputsChanged(bridge, observed)).toBe(false); + files.set('unrelated.ts', encode('ignored')); + expect(await inputsChanged(bridge, observed)).toBe(false); + files.set('ui/main.ts', encode('two')); + expect(await inputsChanged(bridge, observed)).toBe(true); + await observedRead(bridge, 'ui/main.ts', observed, {bytes: 0}); + files.set('ui/new.ts', encode('created')); + expect(await inputsChanged(bridge, observed)).toBe(true); + await observedRead(bridge, 'ui/new.ts', observed, {bytes: 0}); + files.delete('ui/main.ts'); + expect(await inputsChanged(bridge, observed)).withContext('deletion is a change').toBe(true); + }); + + it('a polling pass bounds bytes and paths, reports non-missing failures', async () => { + const {bridge} = memoryBridge(new Map([['main.ts', encode('file')]])); + await rejects(observedRead(bridge, 'main.ts', new Map(), {bytes: 32 * 1024 * 1024}), /32 MiB/); + const paths = new Map(Array.from({length: 1024}, (_, n) => [`file-${n}`, 'missing'])); + await rejects(observedRead(bridge, 'extra', paths, {bytes: 0}), /1024 input paths/); + const broken = {cppFunction: () => async () => { throw new Error('Connection closed'); }}; + await rejects(inputsChanged(broken, new Map([['file', 'old']])), /Connection closed/); + }); + + it('Ctrl+C terminates an active compiler, rejects once, and drops late read answers', async () => { + let callback, terminated = 0; + const messages = []; + const worker = {postMessage: message => messages.push(message), terminate: () => ++terminated, + set onmessage(value) { callback = value; }}; + const controller = new AbortController(); + const session = compilerSession({cppFunction: () => () => new Promise(() => {})}, controller.signal, () => worker); + const pending = session.rebuild({entry: 'main.ts', lock}); + callback({data: {type: 'read', id: 1, path: 'main.ts'}}); + controller.abort(); + await rejects(pending, error => error.exitCode === 130); + callback({data: {type: 'result', files: new Map()}}); + session.close(); + expect(terminated).toBe(1); + expect(messages.length).toBe(1); + await rejects(session.rebuild({entry: 'main.ts', lock}), error => error.exitCode === 130); + await rejects(waitForPoll(controller.signal), error => error.exitCode === 130); + }); + + it('a compiler session reuses its Worker and serializes rebuilds', async () => { + let callback; + const worker = {postMessage() {}, terminate() {}, set onmessage(value) { callback = value; }}; + const session = compilerSession({}, undefined, () => worker); + try { + const first = session.rebuild({entry: 'one', lock}); + await rejects(session.rebuild({entry: 'two', lock}), /already running/); + callback({data: {type: 'result', files: new Map([['app.js', encode('one')]])}}); + expect((await first).size).toBe(1); + const second = session.rebuild({entry: 'two', lock}); + callback({data: {type: 'error', error: 'syntax', diagnostics: [{text: 'bad', location: {file: 'project:two.ts', line: 4, column: 2}}]}}); + await rejects(second, error => diagnosticsText(error).startsWith('two.ts:4:3: bad')); + } finally { session.close(); } + }); + + it('build selects one explicit entry or every declared entry', () => { + expect(buildEntries({entries: {main: 'ui/main.ts'}})).toEqual([['', 'ui/main.ts']]); + expect(buildEntries({entries: {one: 'one.ts', two: 'two.ts'}})).toEqual([['one', 'one.ts'], ['two', 'two.ts']]); + expect(buildEntries({entries: {one: 'one.ts', two: 'two.ts'}}, 'two')).toEqual([['', 'two.ts']]); + expect(buildEntries({entries: {'app:one': 'one.ts', 'app..two': 'two.ts', CON: 'three.ts'}})).toEqual([['app%3Aone', 'one.ts'], ['app%2E%2Etwo', 'two.ts'], ['%43ON', 'three.ts']]); + throws(() => buildEntries(null), /Usage: wf build/); + }); + + + it('Ctrl+C during commit still displays the committed preview before stopping dev', async () => { + const project = memoryBridge(new Map([['webfront.project.json', encode(JSON.stringify({ + format: 1, name: 'commit-race', version: '0.1.0', entries: {main: 'main.ts'}, + }))]])); + const controller = new AbortController(); + const bridge = {cppFunction: name => async (...args) => { + const result = await project.bridge.cppFunction(name)(...args); + // The native commit has completed, but its acknowledgement has not reached dev yet. + if (name === 'webfront.developer.commit') controller.abort(); + return result; + }}; + let terminated = 0; + const previousWorker = globalThis.Worker; + globalThis.Worker = class { + postMessage(message) { + if (message.type === 'build') queueMicrotask(() => this.onmessage({data: { + type: 'result', files: new Map([['app.js', encode('console.log("committed")')]]), + }})); + } + terminate() { ++terminated; } + }; + const navigations = []; + const frame = {hidden: true, contentDocument: null, contentWindow: {location: {replace: url => navigations.push(url)}}, + addEventListener() {}, removeEventListener() {}}; + try { + await rejects(dev([], {bridge, signal: controller.signal, preview: frame}), error => error.exitCode === 130); + expect(project.storage.get('.webfront/developer/preview/app.js')).toEqual(encode('console.log("committed")')); + expect(navigations.length).withContext('a completed publication must be displayed even when Ctrl+C arrived during commit').toBe(1); + expect(navigations[0]).toMatch(/^\/webfront\/developer\/preview\/index.html\?build=/); + expect(frame.hidden).toBe(false); + expect(project.pending()).toBe(0); + expect(terminated).toBe(1); + } finally { + if (previousWorker === undefined) delete globalThis.Worker; + else globalThis.Worker = previousWorker; + } + }); +}); diff --git a/test/developer/specs/distribution-specs.mjs b/test/developer/specs/distribution-specs.mjs new file mode 100644 index 00000000..d9805c9e --- /dev/null +++ b/test/developer/specs/distribution-specs.mjs @@ -0,0 +1,135 @@ +// Specs of the developer distribution: the starters, the Pages staging and the pinned bootstrap header. +import {tar} from '../../../js/developer/tools/archive.mjs'; +import {bootstrapHeader, versionPath, distributionFiles} from '../../../js/developer/tools/distribution.mjs'; +import stageSite from '../../../js/developer/scripts/site.mjs'; +import {compress} from '../../../js/developer/environment/embed.mjs'; +import {createStarter} from '../../../js/developer/environment/starter.mjs'; +import {rejects, throws, integrity} from '../support.mjs'; + +describe('The developer distribution', () => { + const encode = value => new TextEncoder().encode(typeof value === 'string' ? value : JSON.stringify(value)); + const decode = bytes => new TextDecoder().decode(bytes); + + const recipe = (fields = {}) => ({format: 1, name: 'life-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 Life() {}'), + 'package/webfront.project.json': encode(recipe()), + ...overrides, + })))); + } + + it('starter integrity, recipes and archive paths are checked before any project writes', async () => { + const bytes = starter(); + const calls = []; + const bridge = {cppFunction: name => async (...args) => { calls.push([name, ...args]); return 'transaction'; }}; + const config = {starters: {life: {url: 'https://pages.test/developer/0.1.0/life-starter.tgz', integrity: await integrity(bytes)}}}; + const fetchImpl = async () => new Response(bytes); + const help = await createStarter(bridge, config, ['life', 'ui'], {fetchImpl}); + expect(help).toMatch(/wf init\nwf install react@19.3.1/); + expect(help).toMatch(/wf preview ui\/main.tsx/); + expect(calls[0][0]).toBe('webfront.developer.beginNew'); + expect(calls.at(-1)[0]).toBe('webfront.developer.commit'); + calls.length = 0; + await rejects(createStarter(bridge, {starters: {life: {...config.starters.life, integrity: await integrity(encode('bad'))}}}, ['life', 'ui'], {fetchImpl}), /Integrity check/); + expect(calls.length).toBe(0); + for (const bytes of [starter({'package/../escape': encode('bad')}), starter({'package/webfront.project.json': encode(recipe({dependencies: {react: 'latest'}}))})]) { + await rejects(createStarter(bridge, {starters: {life: {...config.starters.life, integrity: await integrity(bytes)}}}, ['life', 'ui'], {fetchImpl: async () => new Response(bytes)})); + expect(calls.length).toBe(0); + } + }); + + it('starter replacement refusal aborts the publication rather than overwriting files', async () => { + const bytes = starter(); + const calls = []; + const bridge = {cppFunction: name => async () => { + calls.push(name); + if (name.endsWith('.commit')) throw new Error('Starter destination already exists'); + return 'transaction'; + }}; + await rejects(createStarter(bridge, {starters: {life: {url: '/starter.tgz', integrity: await integrity(bytes)}}}, ['life', 'ui'], {fetchImpl: async () => new Response(bytes)}), /already exists/); + expect(calls.at(-1)).toBe('webfront.developer.abort'); + }); + + // The project a wf script sees, over a map of files: directories are the prefixes of the paths, listed with a trailing + // slash, and a directory that holds no file cannot be listed or read, like with developer::Store. + function memoryProject(storage = new Map()) { + const directory = path => path ? path + '/' : ''; + return {storage, + read: async path => { + if (!storage.has(path)) throw new Error(`Cannot read project file: ${path}`); + return storage.get(path); + }, + readText: async path => decode(await storage.get(path)), + write: async (path, data) => { storage.set(path, typeof data === 'string' ? encode(data) : data); }, + list: async path => { + const prefix = directory(path.replace(/\/$/, '')); + const names = new Set([...storage.keys()].filter(key => key.startsWith(prefix)) + .map(key => key.slice(prefix.length)).map(rest => rest.includes('/') ? rest.split('/')[0] + '/' : rest)); + if (!names.size) throw new Error(`Cannot list project directory: ${path}`); + return [...names].sort(); + }}; + } + + it('Pages staging retains older versions and refuses different bytes under an existing version', async () => { + const project = memoryProject(); + const environment = encode('environment'); + const starterBytes = encode('starter'); + const write = async version => { + const manifest = {version, integrity: await integrity(environment), starters: {sample: {archive: 'sample-starter.tgz', integrity: await integrity(starterBytes)}, + ...(version !== '0.1.0' ? {life: {archive: 'life-starter.tgz', integrity: await integrity(starterBytes)}} : {})}}; + await project.write('distribution/environment.tgz', environment); + await project.write('distribution/sample-starter.tgz', starterBytes); + if (version !== '0.1.0') await project.write('distribution/life-starter.tgz', starterBytes); + await project.write('distribution/provision.json', JSON.stringify(manifest)); + await project.write('distribution/DeveloperReleaseData.hpp', bootstrapHeader(version, 'https://owner.github.io/WebFront/', manifest.integrity)); + }; + const stage = () => stageSite({args: ['distribution', 'site'], project, console: {log() {}}}); + await write('0.1.0'); + await stage(); + await stage(); + await write('0.2.0'); + await stage(); + expect(await project.readText('site/developer/0.1.0/environment.tgz')).toBe('environment'); + expect(await project.readText('site/index.html')).toMatch(/developer\/0.2.0\/life-starter.tgz/); + expect(await project.readText('site/developer/0.2.0/life-starter.tgz')).toBe('starter'); + await write('0.3.0'); + await project.write('distribution/life-starter.tgz', 'packed-starter'); + const manifest = JSON.parse(await project.readText('distribution/provision.json')); + manifest.starters.life.integrity = await integrity(encode('packed-starter')); + await project.write('distribution/provision.json', JSON.stringify(manifest)); + await stage(); + expect(await project.readText('site/developer/0.1.0/environment.tgz')).toBe('environment'); + expect(await project.readText('site/developer/0.2.0/life-starter.tgz')).toBe('starter'); + expect(await project.readText('site/developer/0.3.0/life-starter.tgz')).toBe('packed-starter'); + await project.write('distribution/DeveloperReleaseData.hpp', 'changed'); + await rejects(stage(), /increment the distribution version/); + expect(await project.readText('site/developer/0.2.0/DeveloperReleaseData.hpp')).toMatch(/namespace webfront/); + await project.write('distribution/environment.tgz', 'corrupt'); + await rejects(stage(), /checksum mismatch/); + }); + + it('bootstrap configuration is pinned and rejects unsafe version/base inputs', async () => { + const digest = await integrity(encode('environment')); + const header = bootstrapHeader('0.1.0', 'https://owner.github.io/WebFront/', digest); + expect(header).toMatch(/https:\/\/owner.github.io\/WebFront\/developer\/0.1.0\/environment.tgz/); + expect(header).not.toMatch(/latest/); + throws(() => versionPath('../evil')); + throws(() => bootstrapHeader('0.1.0', 'http://owner.test/', digest)); + }); + + it('Life recipes select their generated provider and reject invalid provider names', async () => { + 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: await integrity(bytes)}}}; + const create = () => createStarter(bridge, config, ['life', 'ui'], {fetchImpl: async () => new Response(bytes)}); + if (provider === 'LifeUI') expect(await create()).toMatch(/generated\/LifeUI.hpp/); + else { await rejects(create(), /provider name/); expect(writes).toBe(0); } + } + throws(() => distributionFiles({starters: {life: {archive: '../life-starter.tgz'}}})); + }); +}); diff --git a/test/developer/specs/environment-specs.mjs b/test/developer/specs/environment-specs.mjs new file mode 100644 index 00000000..ec43552e --- /dev/null +++ b/test/developer/specs/environment-specs.mjs @@ -0,0 +1,318 @@ +// Specs of the environment's packages, bundler, bootstrap and C++ commands, run by `wf test` in the browser. +import {rejects, throws, integrity} from '../support.mjs'; +import {resolvePackages, downloadPackage, validateLock} from '../../../js/developer/environment/packages.bundle.mjs'; +import {packageEntry, normalize, virtualPlugin} from '../../../js/developer/environment/bundler.mjs'; +import {generateProvider, compress} from '../../../js/developer/environment/embed.mjs'; +import {environmentFiles, bootstrap} from '../../../js/developer/environment/bootstrap.mjs'; +import {publish, responseBytes} from '../../../js/developer/environment/io.mjs'; +import {tar} from '../../../js/developer/tools/archive.mjs'; +import {parseSpec, verifyIntegrity, gunzip, readTar} from '../../../js/developer/environment/tarball.mjs'; +import {runCommand} from '../../../js/developer/environment/commands.mjs'; + +describe('The environment', () => { + const encoder = new TextEncoder(); + const encode = value => encoder.encode(typeof value === 'string' ? value : JSON.stringify(value)); + const idOf = (name, version) => `${name.replace('/', '+')}@${version}`; + function fixture(name, version, fields = {}, extra = {}) { + const files = new Map(Object.entries({'package/package.json': encode({name, version, ...fields}), ...extra})); + return compress(tar(files)); + } + function registry(packages) { + return async url => { + const path = new URL(url).pathname.slice(1); + if (path.endsWith('.tgz')) return new Response(packages[path.slice(0, -4)].bytes); + const pkg = packages[path]; + if (!pkg) return new Response('', {status: 404}); + const manifest = {dist: {tarball: `https://registry.test/${path}.tgz`, integrity: await integrity(pkg.bytes)}}; + return Response.json({'dist-tags': {latest: pkg.version}, versions: {[pkg.version]: manifest}}); + }; + } + + it('resolves transitive semver edges, cycles, multiple versions and required peers', async () => { + const source = { + app: {version: '1.0.0', bytes: fixture('app', '1.0.0', {dependencies: {dep: '^2.0.0'}, peerDependencies: {react: '^19.0.0'}})}, + dep: {version: '2.1.0', bytes: fixture('dep', '2.1.0', {dependencies: {app: '1.0.0'}})}, + react: {version: '19.0.0', bytes: fixture('react', '19.0.0')}, + }; + const options = {registry: 'https://registry.test/', fetchImpl: registry(source)}; + const {lock} = await resolvePackages(['app@latest', 'react@19.0.0'], options); + expect(lock.packages['app@1.0.0'].dependencies.dep).toBe('dep@2.1.0'); + expect(lock.packages['dep@2.1.0'].dependencies.app).toBe('app@1.0.0'); + expect(lock.packages['app@1.0.0'].dependencies.react).toBe('react@19.0.0'); + expect(validateLock(lock)).toBe(lock); + await rejects(resolvePackages(['app'], options), /requires peer react/); + const download = async (name, range) => { + const version = name === 'dep' ? (range.startsWith('^1') ? '1.2.0' : '2.0.0') : '1.0.0'; + const manifest = {name, version, dependencies: name === 'a' ? {dep: '^1.0.0'} : name === 'b' ? {dep: '^2.0.0'} : {}}; + return {id: idOf(name, version), key: name, manifest, integrity: 'sha512-test', files: new Map()}; + }; + const multiple = await resolvePackages(['a', 'b'], {download}); + expect(multiple.lock.packages['a@1.0.0'].dependencies.dep).toBe('dep@1.2.0'); + expect(multiple.lock.packages['b@1.0.0'].dependencies.dep).toBe('dep@2.0.0'); + }); + + // Fake registry: dep 2.1.0 is installed, 2.2.0 is the newest; `tampered` changes the archive of 2.1.0. + const depIntegrity = {'2.1.0': 'sha512-first', '2.2.0': 'sha512-second'}; + function lockDownloads(requests, tampered = false) { + return async (name, range) => { + requests.push(`${name}@${range}`); + const version = name === 'dep' ? (depIntegrity[range] ? range : '2.2.0') : '1.0.0'; + const manifest = {name, version, dependencies: name === 'app' ? {dep: '^2.0.0'} : {}}; + let integrity = 'sha512-app'; + if (name === 'dep') integrity = tampered && version === '2.1.0' ? 'sha512-other' : depIntegrity[version]; + return {id: idOf(name, version), key: `${name}-${version}`, manifest, integrity, files: new Map()}; + }; + } + + it('an installed lock pins transitive versions and rejects changed archives', async () => { + const requests = []; + const first = await resolvePackages(['app'], {download: async (name, range) => lockDownloads(requests)(name, range === '^2.0.0' ? '2.1.0' : range)}); + expect(first.lock.packages['app@1.0.0'].dependencies.dep).toBe('dep@2.1.0'); + requests.length = 0; + const again = await resolvePackages(['app@1.0.0'], {download: lockDownloads(requests), previous: first.lock}); + expect(again.lock.packages['app@1.0.0'].dependencies.dep).toBe('dep@2.1.0'); + expect(requests.includes('dep@2.1.0') && !requests.includes('dep@^2.0.0')).withContext(requests.join()).toBeTruthy(); + await rejects(resolvePackages(['app@1.0.0'], {download: lockDownloads(requests, true), previous: first.lock}), + /dep@2\.1\.0 no longer matches the integrity recorded in the lock/); + const fresh = await resolvePackages(['app@1.0.0'], {download: lockDownloads(requests)}); + expect(fresh.lock.packages['app@1.0.0'].dependencies.dep).toBe('dep@2.2.0'); + }); + + it('rejects integrity, archive identity, traversal and installation scripts', async () => { + for (const [bytes, pattern] of [ + [fixture('wrong', '1.0.0'), /identity mismatch/], + [fixture('pkg', '1.0.0', {scripts: {postinstall: 'node setup.js'}}), /unsupported install script/], + [fixture('pkg', '1.0.0', {}, {'package/../escape': encode('bad')}), /Unsafe package path/], + [fixture('pkg', '1.0.0', {}, {'package/addon.node': encode('bad')}), /native module/], + ]) { + await rejects(downloadPackage('pkg', 'latest', {registry: 'https://registry.test/', fetchImpl: registry({pkg: {bytes, version: '1.0.0'}})}), pattern); + } + const bytes = fixture('pkg', '1.0.0'); + const fetchImpl = async url => String(url).endsWith('.tgz') ? new Response(bytes) : Response.json({versions: {'1.0.0': {dist: {tarball: 'https://registry.test/pkg.tgz', integrity: await integrity(encode('other'))}}}}); + await rejects(downloadPackage('pkg', '1.0.0', {registry: 'https://registry.test/', fetchImpl}), /Integrity check failed/); + }); + + it('reads the archives of DefinitelyTyped, rooted at the package name, and refuses any other mixed root (#316)', async () => { + // npm strips the first path component whatever it is: @types/* archives are rooted at "react/", not "package/". + const rooted = root => compress(tar(new Map([[`${root}/package.json`, encode({name: '@types/react', version: '19.3.0'})], [`${root}/index.d.ts`, encode('export {};')]]))); + const download = bytes => downloadPackage('@types/react', '19.3.0', {registry: 'https://registry.test/', fetchImpl: async url => + String(url).endsWith('.tgz') ? new Response(bytes) : Response.json({versions: {'19.3.0': {dist: {tarball: 'https://registry.test/types-react.tgz', integrity: await integrity(bytes)}}}})}); + for (const root of ['react', 'package']) { + const {files} = await download(rooted(root)); + expect([...files.keys()].sort()).toEqual(['index.d.ts', 'package.json']); + } + const mixed = compress(tar(new Map([['react/package.json', encode({name: '@types/react', version: '19.3.0'})], ['other/index.d.ts', encode('')]]))); + await rejects(download(mixed), /Invalid npm tarball root/); + await rejects(download(rooted('..')), /Invalid npm tarball root/); + await rejects(download(compress(tar(new Map([['package.json', encode({name: '@types/react', version: '19.3.0'})]])))), /Invalid npm tarball root/); + }); + + it('resolves browser conditional exports and rejects private and Node imports', async () => { + expect(packageEntry({exports: {'.': {browser: './browser.js', default: './node.js'}, './*': './src/*.mjs'}}, '')).toBe('browser.js'); + expect(packageEntry({exports: {'./*': './src/*.mjs'}}, 'sub')).toBe('src/sub.mjs'); + throws(() => packageEntry({exports: {'.': './index.js'}}, 'private'), /does not export/); + expect(packageEntry({exports: {browser: {import: './b.mjs'}, default: './c.js'}}, '', 'require')).toBe('c.js'); + throws(() => normalize('../outside'), /escapes/); + expect(packageEntry({exports: {'.': {import: './esm.js', require: './cjs.js'}}}, '', 'require')).toBe('cjs.js'); + let resolve; + virtualPlugin({packages: {}, roots: {}}, {}, async () => undefined).setup({onResolve: (_, cb) => { resolve = cb; }, onLoad() {}}); + await rejects(resolve({path: 'node:fs', importer: 'entry.tsx', namespace: 'project', kind: 'import-statement'}), /Unsupported browser import/); + }); + + it('generated gzip words decode to the exact resources and generation is reproducible', async () => { + const files = new Map([['index.html', encode('
    PI
    ')], ['app.js', encode('console.log("π")')]]); + const header = generateProvider(files, 'AppUI', 'MIT */ preserved'); + expect(header).toBe(generateProvider(new Map([...files].reverse()), 'AppUI', 'MIT */ preserved')); + const blocks = [...header.matchAll(/dataSize\{(\d+)\};\s+static constexpr[\s\S]*?data\{([\s\S]*?)\n \};/g)]; + expect(blocks.length).toBe(2); + for (const [index, match] of blocks.entries()) { + const hex = [...match[2].matchAll(/0x([a-f0-9]{16})ULL/g)].map(word => word[1]).join(''); + const compressed = Uint8Array.from(hex.match(/../g), byte => parseInt(byte, 16)).subarray(0, Number(match[1])); + expect(await gunzip(compressed)).toEqual([...files].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)[index][1]); + expect([...compressed.subarray(4, 8)]).toEqual([0, 0, 0, 0]); + } + throws(() => generateProvider(files, '../bad'), /provider name/); + }); + + it('environment integrity and protocol are checked before publication', async () => { + const archive = compress(tar(new Map([['package/environment.json', encode({protocol: 1, entry: 'runtime.mjs'})], ['package/runtime.mjs', encode('export function mount() {}')]]))); + const environment = await environmentFiles(archive, await integrity(archive)); + expect(environment.manifest.entry).toBe('runtime.mjs'); + await rejects(environmentFiles(archive, await integrity(encode('wrong'))), /Integrity check failed/); + const wrong = compress(tar(new Map([['package/environment.json', encode({protocol: 2, entry: 'runtime.mjs'})], ['package/runtime.mjs', encode('')]]))); + await rejects(environmentFiles(wrong, await integrity(wrong)), /Incompatible WebFront developer environment: protocol version 2, this application supports 1/); + // The API an environment expects must be one the C++ declares; an environment from before "api" reads as API 1. + const withApi = api => compress(tar(new Map([['package/environment.json', encode({protocol: 1, api, entry: 'runtime.mjs'})], ['package/runtime.mjs', encode('')]]))); + const newer = withApi(2); + await rejects(environmentFiles(newer, await integrity(newer)), /api version 2, this application supports 1/); + expect((await environmentFiles(newer, await integrity(newer), {protocol: [1], api: [1, 2]})).manifest.api).toBe(2); + await rejects(environmentFiles(archive, await integrity(archive), {protocol: [1], api: [2]}), /api version 1, this application supports 2/); + const current = withApi(1); + expect((await environmentFiles(current, await integrity(current))).manifest.api).toBe(1); + const missing = compress(tar(new Map([['package/runtime.mjs', encode('')]]))); + await rejects(environmentFiles(missing, await integrity(missing)), /no environment\.json/); + }); + + it('aborted publications never commit and clean their staging transaction', async () => { + const calls = []; + const bridge = {cppFunction: name => async (...args) => { calls.push([name, ...args]); return 'transaction'; }}; + const controller = new AbortController(); + controller.abort(new Error('Interrupted')); + await rejects(publish(bridge, 'generated.hpp', new Map([['output', encode('header')]]), {directory: false, signal: controller.signal}), /Interrupted/); + expect(calls.some(([name]) => name.endsWith('.commit'))).toBe(false); + expect(calls.at(-1)[0]).toBe('webfront.developer.abort'); + }); + + // An in-memory project behind the webfront.developer.* bridge callbacks. + function memoryBridge(storage) { + const transactions = new Map(); + let next = 0; + const operations = { + read: ([path, offset]) => { + const bytes = storage.get(path); + if (!bytes) throw new Error('Cannot read project file: ' + path); + return bytes.subarray(offset, offset + 256 * 1024); + }, + begin: ([destination, directory]) => { + const id = String(++next); + transactions.set(id, {destination, directory, files: new Map()}); + return id; + }, + write: ([id, path, offset, bytes]) => { + const files = transactions.get(id).files; + const previous = files.get(path) ?? new Uint8Array(); + expect(previous.length).toBe(offset); + files.set(path, new Uint8Array([...previous, ...bytes])); + }, + commit: ([id]) => { + const {destination, directory, files} = transactions.get(id); + for (const [path, bytes] of files) storage.set(directory ? `${destination}/${path}` : destination, bytes); + transactions.delete(id); + }, + abort: ([id]) => { transactions.delete(id); }, + }; + return {cppFunction: name => async (...args) => operations[name.split('.').pop()](args)}; + } + + it('a pinned cached environment bootstraps offline and failed refreshes preserve publications', async () => { + const archive = compress(tar(new Map([['package/environment.json', encode({protocol: 1, entry: 'runtime.mjs'})], ['package/runtime.mjs', encode('export function mount() {}')]]))); + const storage = new Map([['.webfront/developer/environment.tgz', archive]]); + const bridge = memoryBridge(storage); + const config = {environment: 'https://offline.test/environment.tgz', integrity: await integrity(archive)}; + const offline = async () => { throw new Error('Offline'); }; + const result = await bootstrap(bridge, config, offline); + expect(result.url).toBe('/webfront/developer/environment/runtime.mjs'); + expect(storage.has('.webfront/developer/environment/runtime.mjs')).toBeTruthy(); + const before = storage.get('.webfront/developer/environment/runtime.mjs'); + await rejects(bootstrap(bridge, {...config, integrity: await integrity(encode('different'))}, offline), /Offline/); + expect(storage.get('.webfront/developer/environment/runtime.mjs')).toBe(before); + }); + + it('compressed downloads stop at their byte limit', async () => { + await rejects(responseBytes(new Response(new Uint8Array(9)), 8), /byte limit/); + }); + + it('npm tarballs: package specs, integrity, bounded gunzip and tar entries', async () => { + expect(parseSpec('plot')).toEqual({name: 'plot', version: ''}); + expect(parseSpec('plot@1.2.0')).toEqual({name: 'plot', version: '1.2.0'}); + expect(parseSpec('@acme/plot')).toEqual({name: '@acme/plot', version: ''}); + expect(parseSpec('@acme/plot@next')).toEqual({name: '@acme/plot', version: 'next'}); + const files = new Map([['package/package.json', encode({name: 'plot'})], ['package/dist/index.js', encode('x')]]); + const archive = compress(tar(files)); + expect(await verifyIntegrity(archive, `sha1-ignored ${await integrity(archive)}`)).toBe(await integrity(archive)); + await rejects(verifyIntegrity(archive, await integrity(encode('other'))), /Integrity check failed/); + await rejects(verifyIntegrity(archive, 'sha1-only'), /no SHA-512 integrity/); + const unpacked = await gunzip(archive); + expect(readTar(unpacked).map(entry => entry.path).sort()).toEqual([...files.keys()].sort()); + await rejects(gunzip(archive, unpacked.length - 1), /unpacks to more than/); + expect(readTar(new Uint8Array(1024))).toEqual([]); + const corrupt = unpacked.slice(); + corrupt[148] ^= 1; + throws(() => readTar(corrupt), /Corrupt tar header/); + }); + + // A WebSocket the real bridge (js/core/WebFront.js) talks to: it records the frames sent, fires the on* handlers like a + // browser, and counts the listeners added with addEventListener. + class FakeWebSocket extends EventTarget { + static last = null; + constructor() { + super(); + this.sent = []; + this.listeners = 0; + FakeWebSocket.last = this; + } + send(data) { this.sent.push(new Uint8Array(data.buffer ?? data).slice()); } + addEventListener(...args) { ++this.listeners; super.addEventListener(...args); } + removeEventListener(...args) { --this.listeners; super.removeEventListener(...args); } + fire(type, init = {}) { + const event = Object.assign(new Event(type), init); + this[`on${type}`]?.(event); + this.dispatchEvent(event); + } + } + + // A bridge linked to the fake WebSocket, little-endian, and a helper answering a C++ call with a void return. The real + // bridge (js/core/WebFront.js, as the application serves it) runs in a frame of its own, so that it neither replaces nor + // is replaced by the one of the page that runs the specs. + const frames = []; + afterEach(() => { for (const frame of frames.splice(0)) frame.remove(); }); + async function linkedBridge() { + const source = await (await fetch('/WebFront.js')).text(); // the embedded bridge: the runner page loads the same file + const frame = document.body.appendChild(document.createElement('iframe')); + frames.push(frame); + frame.hidden = true; + frame.contentWindow.WebSocket = FakeWebSocket; + frame.contentWindow.eval(source); + const bridge = frame.contentWindow.webFront, socket = FakeWebSocket.last; + socket.fire('open'); + socket.fire('message', {data: new Uint8Array([1, 0]).buffer}); // acknowledgement: little-endian + await bridge.ready; + const acknowledge = frame => socket.fire('message', {data: new Uint8Array([4, 0, frame[2], frame[3], 0, 0, 0, 0]).buffer}); + return {bridge, socket, acknowledge}; + } + + // The command number of a webfront.commands.start frame: the number after the function name. + const commandNumber = frame => { + const view = new DataView(frame.buffer); + return view.getFloat64(8 + 2 + view.getUint8(9) + 1, true); + }; + + const settled = promise => Promise.race([promise.then(() => 'resolved', () => 'rejected'), new Promise(resolve => setTimeout(() => resolve('pending'), 20))]); + + it('a C++ command whose start was acknowledged rejects when the connection closes, and unsubscribes', async () => { + const {bridge, socket, acknowledge} = await linkedBridge(); + const listenersBefore = socket.listeners; + const command = runCommand(bridge, 'wait', []); + command.catch(() => {}); + const start = socket.sent.at(-1); + acknowledge(start); + expect(await settled(command)).toBe('pending'); + expect(socket.listeners).toBe(listenersBefore + 1); + socket.fire('close', {wasClean: false}); + await rejects(command, error => error.exitCode === 1 && /connection to the application closed/.test(error.message)); + expect(socket.listeners).toBe(listenersBefore); + // The exit report of the stopped command can no longer reach it; a late one is ignored. + globalThis.webfront.commands.exit(commandNumber(start), 130, ''); + await rejects(runCommand(bridge, 'wait', []), /not connected/); + expect(socket.listeners).toBe(listenersBefore); + }); + + it('a C++ command that exits, or is interrupted, removes its close listener', async () => { + const {bridge, socket, acknowledge} = await linkedBridge(); + const listenersBefore = socket.listeners; + const finished = runCommand(bridge, 'echo', ['x']); + const start = socket.sent.at(-1); + acknowledge(start); + globalThis.webfront.commands.exit(commandNumber(start), 0, ''); + expect(await finished).toBe(''); + expect(socket.listeners).toBe(listenersBefore); + const controller = new AbortController(); + const interrupted = runCommand(bridge, 'wait', [], {signal: controller.signal}); + acknowledge(socket.sent.at(-1)); + controller.abort(); + await rejects(interrupted, error => error.exitCode === 130); + expect(socket.listeners).toBe(listenersBefore); + socket.fire('close', {wasClean: true, code: 1000, reason: ''}); + }); + +}); diff --git a/test/developer/specs/manifest-specs.mjs b/test/developer/specs/manifest-specs.mjs new file mode 100644 index 00000000..621b57db --- /dev/null +++ b/test/developer/specs/manifest-specs.mjs @@ -0,0 +1,350 @@ +// Specs of the project manifest, its agreement with the lock and the joint publication of both. +import {validateManifest, parseManifest, serializeManifest, manifestName, dependenciesDigest} from '../../../js/developer/environment/manifest.mjs'; +import {install, initProject, loadProject, syncNotice, resolveEntry, embedTarget, lockPath, manifestPath, setManifestDirectory, checkWrite} from '../../../js/developer/environment/packages.bundle.mjs'; +import {compress} from '../../../js/developer/environment/embed.mjs'; +import {tar} from '../../../js/developer/tools/archive.mjs'; +import {memoryBridge} from '../memory-bridge.mjs'; +import {rejects, throws, integrity} from '../support.mjs'; + +describe('The project manifest', () => { + const encoder = new TextEncoder(); + const decoder = new TextDecoder(); + const encode = value => encoder.encode(typeof value === 'string' ? value : JSON.stringify(value)); + const minimal = {format: 1, name: 'app', version: '0.1.0'}; + + it('a valid manifest receives its defaults and keeps a stable serialization', () => { + const manifest = validateManifest(minimal); + expect(manifest.dependencies).toEqual({}); + expect(manifest.entries).toEqual({}); + 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: {AppUI: {entry: 'main', output: 'generated/AppUI.hpp'}}, test: {specs: ['spec/a.mjs']}, + permissions: {files: ['ui'], publish: ['generated'], fetch: ['https://registry.npmjs.org']}}; + const text = serializeManifest(validateManifest(full)); + expect(JSON.parse(text)).toEqual(full); + expect(serializeManifest(parseManifest(encode(text)))).toBe(text); + expect(manifestName('apps/My App')).toBe('my-app'); + expect(manifestName('')).toBe('webfront-app'); + }); + + it('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, registry: '/\\registry.test/'}, /registry must be an https URL or an absolute path/], + [{...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) throws(() => validateManifest(value), message); + throws(() => parseManifest(encode('{')), /not valid JSON/); + }); + + it('the dependency digest ignores key order and changes with any range', async () => { + const first = await dependenciesDigest({a: '^1.0.0', b: '2.0.0'}); + expect(first).toBe(await dependenciesDigest({b: '2.0.0', a: '^1.0.0'})); + expect(first).not.toBe(await dependenciesDigest({a: '^1.0.0', b: '^2.0.0'})); + expect(first).toMatch(/^[0-9a-f]{64}$/); + }); + + it('entries are named in the manifest or given as paths', () => { + const manifest = validateManifest({...minimal, entries: {main: 'ui/main.tsx', other: 'ui/other.tsx'}}); + expect(resolveEntry(manifest, undefined, 'wf preview')).toBe('ui/main.tsx'); + expect(resolveEntry(manifest, 'other', 'wf preview')).toBe('ui/other.tsx'); + expect(resolveEntry(manifest, 'free/path.tsx', 'wf preview')).toBe('free/path.tsx'); + throws(() => resolveEntry(validateManifest(minimal), undefined, 'wf preview'), /entries.main/); + }); + + it('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: {AppUI: {entry: 'main', output: 'generated/app-ui.hpp'}}}); + expect(embedTarget(manifest, ['AppUI'])).toEqual({entry: 'ui/main.tsx', output: 'generated/app-ui.hpp', className: 'AppUI'}); + expect(embedTarget(manifest, ['ui/main.tsx', '--output', 'generated/LifeUI.hpp']).className).toBe('LifeUI'); + throws(() => embedTarget(manifest, ['ui/main.tsx', '--output', 'generated/life-ui.hpp']), /not a C\+\+ class name/); + throws(() => embedTarget(manifest, ['ui/main.tsx']), /--output/); + }); + + 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(await Promise.all(Object.entries(versions).map(async ([version, bytes]) => + [version, {dist: {tarball: `https://registry.test/${path}@${version}.tgz`, integrity: await 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; + } + + it('wf init creates the root manifest every command reads, and never replaces it', async () => { + const {bridge, storage} = memoryBridge(); + expect(await initProject(bridge, [], {})).toMatch(/Created webfront.project.json/); + expect(json(storage, manifestPath)).toEqual({format: 1, name: 'webfront-app', version: '0.1.0', dependencies: {}}); + expect((await loadProject(bridge)).status).toBe('unlocked'); + await rejects(initProject(bridge, [], {}), /already exists/); + await rejects(initProject(bridge, ['a', 'b'], {}), /Usage/); + const named = memoryBridge(); + await initProject(named.bridge, ['my-app'], {}); + expect(json(named.storage, manifestPath).name).toBe('my-app'); + await rejects(initProject(memoryBridge().bridge, ['Bad Name'], {}), /name must be/); + }); + + it('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); + expect(await initProject(bridge, [], {})).toMatch(/with the 3 dependencies of webfront-packages.lock.json/); + expect(json(storage, manifestPath).dependencies).toEqual({a: '^1.2.0', b: '^2.0.0', c: '^3'}); + expect((await loadProject(bridge)).status).toBe('legacy'); + expect(syncNotice(await loadProject(bridge))).toBe(''); + // 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); + expect(Object.keys(adopted.packages).sort()).toEqual(['a@1.2.0', 'b@2.0.0', 'c@3.1.0']); + expect(adopted.manifestDigest).toBe(await dependenciesDigest({a: '^1.2.0', b: '^2.0.0', c: '^3'})); + expect((await loadProject(bridge)).status).toBe('consistent'); + expect(pending()).toBe(0); + }); + + it('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)); + expect(Object.keys(json(storage, lockPath).packages).sort()).toEqual(['a@1.2.0', 'b@2.0.0']); + expect((await loadProject(bridge)).status).toBe('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'}})); + expect((await loadProject(bridge)).status).toBe('desynchronized'); + }); + + it('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 rejects(install(bridge, [spec], options(fetchImpl)), /invalid version range/); + expect(requests.length).toBe(0); + expect(storage.get(manifestPath)).toBe(before); + await install(bridge, ['a@'], options(fetchImpl)); + expect(json(storage, manifestPath)).toEqual({format: 1, name: 'webfront-app', version: '0.1.0', dependencies: {a: '^1.2.0'}}); + expect((await loadProject(bridge)).manifest.entries).withContext('the defaults are still applied when reading').toEqual({}); + }); + + it('wf install needs a manifest, then publishes manifest and lock together', async () => { + const {bridge, storage} = memoryBridge(); + const {fetchImpl} = registry(source()); + await rejects(install(bridge, ['a'], options(fetchImpl)), /run wf init/); + await initProject(bridge, [], {}); + expect((await loadProject(bridge)).status).toBe('unlocked'); + await install(bridge, ['a'], options(fetchImpl)); + const afterFirst = await loadProject(bridge); + expect(afterFirst.status).toBe('consistent'); + expect(afterFirst.manifest.dependencies).toEqual({a: '^1.2.0'}); + expect(afterFirst.lock.manifestDigest).toBe(await dependenciesDigest({a: '^1.2.0'})); + await install(bridge, ['b@2.0.0', 'c@^3'], options(fetchImpl)); + expect(json(storage, manifestPath).dependencies).toEqual({a: '^1.2.0', b: '2.0.0', c: '^3'}); + expect(Object.keys(json(storage, lockPath).roots)).toEqual(['a', 'b', 'c']); + expect((await loadProject(bridge)).status).toBe('consistent'); + }); + + it('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)); + expect(restored.restored).toBe(1); + expect(cache.every(key => storage.has(key))).toBeTruthy(); + expect(storage.get(manifestPath)).toBe(manifestBefore); + expect(storage.get(lockPath)).toBe(lockBefore); + expect(requests.filter(url => !url.endsWith('.tgz')).length).withContext('only the locked package is fetched, not a new resolution').toBe(1); + // no lock: install resolves the manifest and creates the lock, leaving the manifest alone. + storage.delete(lockPath); + expect((await loadProject(bridge)).status).toBe('unlocked'); + await install(bridge, [], options(fetchImpl)); + expect((await loadProject(bridge)).status).toBe('consistent'); + expect(storage.get(manifestPath)).toEqual(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); + expect(stale.status).toBe('desynchronized'); + expect(syncNotice(stale)).toMatch(/wf install --update/); + const lockStale = storage.get(lockPath); + requests.length = 0; + await rejects(install(bridge, [], options(fetchImpl)), /wf install --update/); + await rejects(install(bridge, ['c'], options(fetchImpl)), /wf install --update/); + expect(requests.length).toBe(0); + expect(storage.get(lockPath)).toBe(lockStale); + await install(bridge, ['--update'], options(fetchImpl)); + expect((await loadProject(bridge)).status).toBe('consistent'); + expect(Object.keys(json(storage, lockPath).roots)).toEqual(['a', 'b']); + expect(pending()).toBe(0); + }); + + it('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 rejects(install(bridge, [], options(registry(tampered).fetchImpl)), /Integrity check|integrity/); + }); + + it('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'); + expect(refused.length).withContext('exactly one publication is refused by the precondition').toBe(1); + expect(refused[0].reason.message).toMatch(/changed since it was read; run the command again/); + expect(pending()).withContext('the refused installation leaves no staged transaction').toBe(0); + expect((await loadProject(bridge)).status).toBe('consistent'); + const winner = Object.keys(json(storage, manifestPath).dependencies); + expect(winner.length).toBe(1); + await install(bridge, [winner[0] === 'a' ? 'b' : 'a'], options(fetchImpl)); + expect(Object.keys(json(storage, manifestPath).dependencies).sort()).toEqual(['a', 'b']); + expect(Object.keys(json(storage, lockPath).roots).sort()).toEqual(['a', 'b']); + expect((await loadProject(bridge)).status).toBe('consistent'); + }); + + it('an invalid manifest is reported before anything is resolved', async () => { + const {bridge, storage} = await project('a'); + storage.set(manifestPath, encode({...minimal, format: 3})); + await rejects(loadProject(bridge), /format 3 is not supported/); + storage.set(manifestPath, encode({...minimal, permissions: {network: true}})); + await rejects(install(bridge, [], options(registry(source()).fetchImpl)), /unknown permission/); + }); + + it('wf install --update takes the newest version within the ranges while installing a package keeps the others', async () => { + const {bridge, storage} = await project('a'); + expect(json(storage, lockPath).packages['a@1.2.0'].version).toBe('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)); + expect(json(storage, lockPath).packages['a@1.2.0']).withContext('installing another package leaves a at its locked version').toBeTruthy(); + expect(json(storage, lockPath).packages['a@1.3.0']).toBe(undefined); + await install(bridge, ['--update'], options(registry(newer).fetchImpl)); + expect(Object.keys(json(storage, lockPath).packages).sort()).toEqual(['a@1.3.0', 'b@2.0.0']); + expect(json(storage, manifestPath).dependencies).toEqual({a: '^1.2.0', b: '^2.0.0'}); + expect((await loadProject(bridge)).status).toBe('consistent'); + }); + + it('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'})); + expect(json(storage, manifestPath).dependencies).toEqual({a: 'beta'}); + await install(bridge, ['b'], beta({beta: '1.3.0'})); + expect(Object.keys(json(storage, lockPath).packages).sort()).withContext('the tag moved but the lock did not').toEqual(['a@1.2.0', 'b@2.0.0']); + await install(bridge, ['--update'], beta({beta: '1.3.0'})); + expect(Object.keys(json(storage, lockPath).packages).sort()).toEqual(['a@1.3.0', 'b@2.0.0']); + }); + + describe('kept in a directory of the project', () => { + const directory = 'config/wf'; + afterEach(() => setManifestDirectory('')); + + it('the manifest and the lock are the files of that directory, and the root is the default', () => { + expect(manifestPath).toBe('webfront.project.json'); + setManifestDirectory(directory); + expect(manifestPath).toBe('config/wf/webfront.project.json'); + expect(lockPath).toBe('config/wf/webfront-packages.lock.json'); + setManifestDirectory(undefined); + expect(manifestPath).toBe('webfront.project.json'); + setManifestDirectory('js'); + setManifestDirectory(''); + expect(lockPath).toBe('webfront-packages.lock.json'); + }); + + it('a directory that is absolute, has an empty or dot component or leaves the project is refused and changes nothing', () => { + for (const unsafe of ['/etc', 'a//b', 'a/', '../outside', 'a/../b', './wf', 'a\\b', 'C:/wf', '.webfront', '.webfront/developer/preview', 7]) + throws(() => setManifestDirectory(unsafe), /Unsafe manifest directory/); + expect(manifestPath).toBe('webfront.project.json'); + }); + + it('wf init and wf install write and read there, and leave the project root alone', async () => { + setManifestDirectory(directory); + const {bridge, storage} = memoryBridge(); + expect(await initProject(bridge, [], {})).toMatch(/Created config\/wf\/webfront.project.json/); + expect(await loadProject(bridge)).toEqual(jasmine.objectContaining({status: 'unlocked'})); + await install(bridge, ['a'], options(registry(source()).fetchImpl)); + expect([...storage.keys()].filter(path => !path.startsWith('.webfront/')).sort()) + .toEqual(['config/wf/webfront-packages.lock.json', 'config/wf/webfront.project.json']); + expect(json(storage, manifestPath).dependencies).toEqual({a: '^1.2.0'}); + const loaded = await loadProject(bridge); + expect(loaded.status).toBe('consistent'); + expect(Object.keys(loaded.lock.packages)).toEqual(['a@1.2.0']); + await rejects(initProject(bridge, [], {}), /already exists/); + }); + + it('a project without manifest in that directory has none, even with one at the root', async () => { + const {bridge, storage} = memoryBridge(); + await initProject(bridge, [], {}); + expect([...storage.keys()]).toEqual(['webfront.project.json']); + setManifestDirectory(directory); + expect((await loadProject(bridge)).status).toBe('no-manifest'); + }); + + it('a script may not write the manifest or the lock there, whatever it is granted', () => { + setManifestDirectory(directory); + const permissions = {publish: ['config']}; + expect(checkWrite(permissions, 'config/other.json')).toBe('config/other.json'); + for (const reserved of ['config/wf/webfront.project.json', 'config/wf/webfront-packages.lock.json']) + throws(() => checkWrite(permissions, reserved), /managed by wf/); + }); + }); +}); diff --git a/test/developer/specs/restore-specs.mjs b/test/developer/specs/restore-specs.mjs new file mode 100644 index 00000000..407ca2c9 --- /dev/null +++ b/test/developer/specs/restore-specs.mjs @@ -0,0 +1,246 @@ +// Specs of wf restore against the local registry fixture, served as plain files. +import {install, initProject, restore, restorePackages, effectiveRegistry, usableRegistry, cacheState, validateLock, lockPath, manifestPath, packageRoot} from '../../../js/developer/environment/packages.bundle.mjs'; +import {syntheticPackages, registryFiles} from '../../web/registry/fixture.mjs'; +import {memoryBridge} from '../memory-bridge.mjs'; +import {rejects, throws} from '../support.mjs'; + +describe('wf restore', () => { + const encoder = new TextEncoder(); + const decoder = new TextDecoder(); + const json = (storage, path) => JSON.parse(decoder.decode(storage.get(path))); + const cacheKeys = storage => [...storage.keys()].filter(key => key.startsWith(packageRoot + '/')).sort(); + const snapshot = storage => new Map(storage); + + const registries = {}; + beforeAll(async () => { + const packages = syntheticPackages(); + const genuine = packages.map(pkg => ({...pkg, tampered: false})); + registries.local = (await registryFiles(packages)).files; + // The same packages, with the tampered archive still matching its integrity: a lock can be created from it. + registries.genuine = (await registryFiles(genuine)).files; + // A mirror missing a package of the lock. + registries.partial = (await registryFiles(genuine.filter(pkg => pkg.manifest.name !== 'webfront-fixture-lib'))).files; + }); + + // Serves the registry's files at an origin, as a static file server would; records every request. + function served(files, origin = 'https://registry.test') { + const requests = []; + const fetchImpl = async (url, {signal} = {}) => { + signal?.throwIfAborted(); + requests.push(String(url)); + const {origin: requested, pathname} = new URL(url); + if (requested !== origin) return new Response('', {status: 503}); + const bytes = files.get(decodeURIComponent(pathname.slice(1))); + return bytes ? new Response(bytes) : new Response('', {status: 404}); + }; + return {fetchImpl, requests, registry: `${origin}/`}; + } + + const explicit = source => ({registry: source.registry, registryExplicit: true, fetchImpl: source.fetchImpl}); + + // A project locked to webfront-fixture-app@1.0.0 and webfront-fixture-lib@1.0.0, although lib 1.1.0 satisfies ^1.0.0. + async function lockedProject(files = registries.local, specs = ['webfront-fixture-lib@1.0.0', 'webfront-fixture-app@1.0.0']) { + const memory = memoryBridge(); + await initProject(memory.bridge, [], {}); + for (const spec of specs) await install(memory.bridge, [spec], explicit(served(files))); + return memory; + } + + it('lock and empty cache: wf restore rebuilds the exact locked graph from the local registry', async () => { + const {bridge, storage, pending} = await lockedProject(); + const lock = json(storage, lockPath); + expect(Object.keys(lock.packages).sort()).toEqual(['webfront-fixture-app@1.0.0', 'webfront-fixture-lib@1.0.0']); + const cached = cacheKeys(storage); + expect(cached.some(key => key.endsWith('.json'))).withContext('each cached package has a record').toBeTruthy(); + cached.forEach(key => storage.delete(key)); + const before = snapshot(storage); + const source = served(registries.local); + const lines = []; + const result = await restore(bridge, [], {...explicit(source), progress: line => lines.push(line)}); + expect(result.restored).toBe(2); + expect(result.text).toMatch(/Restored 2 of 2 packages \(0 already in the cache\)/); + expect(cacheKeys(storage)).withContext('the cache is the one the installation wrote').toEqual(cached); + expect([...before].every(([key, bytes]) => storage.get(key) === bytes)).withContext('manifest and lock are only read').toBeTruthy(); + expect(source.requests.every(url => !url.includes('1.1.0'))).withContext('no range is resolved again').toBeTruthy(); + expect(source.requests.every(url => url.startsWith(source.registry))).toBeTruthy(); + expect(lines[0]).toBe(`Registry: ${source.registry} (application option)`); + expect(pending()).toBe(0); + // Idempotent: a valid cache is verified, not downloaded again. + source.requests.length = 0; + const again = await restore(bridge, [], explicit(source)); + expect(again.restored).toBe(0); + expect(again.verified).toBe(2); + expect(source.requests.length).toBe(0); + }); + + it('wf restore --offline checks the cache without any request and lists what is missing or corrupted', async () => { + const {bridge, storage} = await lockedProject(); + const noNetwork = async () => { throw new Error('network access'); }; + const ok = await restore(bridge, ['--offline'], {fetchImpl: noNetwork}); + expect(ok.text).toMatch(/Cache verified offline: 2 packages match/); + const lock = json(storage, lockPath); + const [app, lib] = ['webfront-fixture-app@1.0.0', 'webfront-fixture-lib@1.0.0'].map(id => lock.packages[id]); + storage.delete(`${packageRoot}/${app.key}.json`); + storage.set(`${packageRoot}/${lib.key}/index.js`, encoder.encode('changed')); + const before = snapshot(storage); + await rejects(restore(bridge, ['--offline'], {fetchImpl: noNetwork}), + error => /webfront-fixture-app@1\.0\.0 \(missing\)/.test(error.message) && /webfront-fixture-lib@1\.0\.0 \(corrupted\)/.test(error.message)); + expect(storage).withContext('an offline check writes nothing').toEqual(before); + expect(await cacheState(bridge, app)).toBe('missing'); + expect(await cacheState(bridge, lib)).toBe('corrupted'); + // Online, the same packages are downloaded again and the cache is valid. + const result = await restore(bridge, [], explicit(served(registries.local))); + expect(result.restored).toBe(2); + expect(await cacheState(bridge, lib)).toBe('valid'); + // Only the files the lock lists are checked; a file added beside them is never read by a build. + storage.set(`${packageRoot}/${lib.key}/extra.js`, encoder.encode('')); + expect(await cacheState(bridge, lib)).toBe('valid'); + }); + + it('the application registry takes precedence over the manifest one, which takes precedence over the default', async () => { + const {bridge, storage} = await lockedProject(); + const manifest = json(storage, manifestPath); + storage.set(manifestPath, encoder.encode(JSON.stringify({...manifest, registry: 'https://manifest.test/'}))); + cacheKeys(storage).forEach(key => storage.delete(key)); + const application = served(registries.local); + const result = await restore(bridge, [], explicit(application)); + expect(result.registry).toEqual({url: 'https://registry.test/', source: 'application option'}); + expect(application.requests.length && application.requests.every(url => url.startsWith('https://registry.test/'))).toBeTruthy(); + cacheKeys(storage).forEach(key => storage.delete(key)); + const mirror = served(registries.local, 'https://manifest.test'); + const fromManifest = await restore(bridge, [], {registry: 'https://registry.test/', fetchImpl: mirror.fetchImpl}); + expect(fromManifest.registry).toEqual({url: 'https://manifest.test/', source: 'webfront.project.json'}); + expect(effectiveRegistry({}, {})).toEqual({url: 'https://registry.npmjs.org/', source: 'default'}); + expect(effectiveRegistry({registry: '/mirror/'}, {})).toEqual({url: '/mirror/', source: 'default'}); + await rejects(restore(bridge, [], {registry: 'http://plain.test/', registryExplicit: true, fetchImpl: mirror.fetchImpl}), /HTTPS or the application origin/); + }); + + it('a registry path never leaves the application origin, however a URL parser reads it', () => { + // On an HTTPS page, "/\\host" resolves to https://host/, which an HTTPS check alone would accept; here the page is the + // application's own, and no such path may leave its origin either. + expect(usableRegistry({registry: '/mirror/', registryExplicit: true}).url).toBe('/mirror/'); + for (const registry of ['//registry.test/', '/\\registry.test/', '/\\\\registry.test/', 'http://registry.test/']) + throws(() => usableRegistry({registry, registryExplicit: true}), /HTTPS or the application origin/); + expect(usableRegistry({registry: 'https://registry.test/', registryExplicit: true}).url).toBe('https://registry.test/'); + }); + + it('a bridge failure while reading a record is reported, not taken for a corrupted cache', async () => { + const {bridge} = await lockedProject(); + const failing = {cppFunction: name => async (...args) => { + if (name.endsWith('.read') && args[0].endsWith('.json') && args[0].includes('.webfront/')) throw new Error('Bridge disconnected'); + return bridge.cppFunction(name)(...args); + }}; + const source = served(registries.local); + await rejects(restore(failing, ['--offline'], {}), /Bridge disconnected/); + await rejects(restore(failing, [], explicit(source)), /Bridge disconnected/); + expect(source.requests.length).withContext('a valid package is not downloaded again').toBe(0); + }); + + it('a changed archive or a package missing from the registry fails and keeps lock and valid cache intact', async () => { + const {bridge, storage} = await lockedProject(registries.genuine, ['webfront-fixture-lib@1.0.0', 'webfront-fixture-tampered@1.0.0']); + const lock = json(storage, lockPath); + const tampered = lock.packages['webfront-fixture-tampered@1.0.0']; + const lib = lock.packages['webfront-fixture-lib@1.0.0']; + cacheKeys(storage).filter(key => key.includes('tampered')).forEach(key => storage.delete(key)); + const lockBytes = storage.get(lockPath); + await rejects(restore(bridge, [], explicit(served(registries.local))), /Integrity check failed/); + expect(storage.get(lockPath)).toBe(lockBytes); + expect(await cacheState(bridge, tampered)).toBe('missing'); + expect(await cacheState(bridge, lib)).toBe('valid'); + cacheKeys(storage).filter(key => key.includes('fixture-lib')).forEach(key => storage.delete(key)); + await rejects(restore(bridge, [], explicit(served(registries.partial))), /webfront-fixture-lib: HTTP 404/); + expect(storage.get(lockPath)).toBe(lockBytes); + }); + + it('an interrupted restore keeps the packages already restored and resumes with the others', async () => { + const {bridge, storage, pending} = await lockedProject(); + cacheKeys(storage).forEach(key => storage.delete(key)); + const controller = new AbortController(); + const source = served(registries.local); + let packuments = 0; + const interrupting = async (url, options) => { + if (!String(url).endsWith('.tgz') && ++packuments === 2) controller.abort(new Error('Interrupted')); + return source.fetchImpl(url, options); + }; + await rejects(restore(bridge, [], {...explicit(source), fetchImpl: interrupting, signal: controller.signal}), /Interrupted/); + expect(pending()).withContext('no staged transaction is left behind').toBe(0); + const states = await Promise.all(Object.values(json(storage, lockPath).packages).map(node => cacheState(bridge, node))); + expect(states.sort()).toEqual(['missing', 'valid']); + const resumed = await restore(bridge, [], explicit(source)); + expect(resumed.restored).toBe(1); + expect(resumed.verified).toBe(1); + }); + + // Unpacked sizes of the cached packages of a project, from the files the lock lists. + const sizeOf = (storage, node) => node.files.reduce((total, path) => total + storage.get(`${packageRoot}/${node.key}/${path}`).length, 0); + + it('the bound of the unpacked graph counts the cached packages and is checked before publishing', async () => { + const {bridge, storage} = await lockedProject(); + const lock = json(storage, lockPath); + const [app, lib] = ['webfront-fixture-app@1.0.0', 'webfront-fixture-lib@1.0.0'].map(id => lock.packages[id]); + const limit = sizeOf(storage, app) + sizeOf(storage, lib) - 1; + cacheKeys(storage).filter(key => key.includes('fixture-lib')).forEach(key => storage.delete(key)); + const before = snapshot(storage); + const source = served(registries.local); + for (let attempt = 0; attempt < 2; attempt++) { + await rejects(restorePackages(bridge, lock, {...explicit(source), limit}), /exceed .* MiB unpacked/); + expect(storage).withContext('nothing is published past the bound, and a second attempt keeps it').toEqual(before); + } + const restored = await restorePackages(bridge, lock, {...explicit(source), limit: limit + 1}); + expect(restored.restored).toBe(1); + }); + + it('a cached file larger than the bound is a corruption, listed offline and repaired online', async () => { + const {bridge, storage} = await lockedProject(); + const lock = json(storage, lockPath); + const lib = lock.packages['webfront-fixture-lib@1.0.0']; + const limit = 64 * 1024; + storage.set(`${packageRoot}/${lib.key}/index.js`, new Uint8Array(3 * 256 * 1024)); + const reads = []; + const counting = {cppFunction: name => async (...args) => { + if (name.endsWith('.read')) reads.push(args[0]); + return bridge.cppFunction(name)(...args); + }}; + await rejects(restorePackages(counting, lock, {offline: true, limit}), /webfront-fixture-lib@1\.0\.0 \(corrupted\)/); + expect(reads.filter(path => path.endsWith(`${lib.key}/index.js`)).length).withContext('reading stops at the bound').toBe(1); + const restored = await restorePackages(bridge, lock, {...explicit(served(registries.local)), limit}); + expect(restored.restored).toBe(1); + expect(await cacheState(bridge, lib)).toBe('valid'); + }); + + it('an invalid or absent lock is refused before any request or write', async () => { + const {bridge, storage} = await lockedProject(); + const source = served(registries.local); + for (const lock of ['{', JSON.stringify({format: 2, roots: {}, packages: {}})]) { + storage.set(lockPath, encoder.encode(lock)); + const before = snapshot(storage); + await rejects(restore(bridge, [], explicit(source))); + expect(storage).toEqual(before); + } + storage.delete(lockPath); + await rejects(restore(bridge, [], explicit(source)), /No webfront-packages.lock.json: run wf install/); + await rejects(restore(bridge, ['--force'], explicit(source)), /Usage: wf restore \[--offline\]/); + expect(source.requests.length).toBe(0); + const packages = Object.fromEntries(Array.from({length: 513}, (_, i) => [`p${i}@1.0.0`, {}])); + throws(() => validateLock({format: 1, roots: {}, packages}), /exceeds 512 packages/); + }); + + it('wf install of a consistent lock repairs a corrupted cache and names its registry', async () => { + const {bridge, storage} = await lockedProject(); + const lib = json(storage, lockPath).packages['webfront-fixture-lib@1.0.0']; + storage.set(`${packageRoot}/${lib.key}/index.js`, encoder.encode('changed')); + const lines = []; + const result = await install(bridge, [], {...explicit(served(registries.local)), progress: line => lines.push(line)}); + expect(result.restored).toBe(1); + expect(result.registry).toEqual({url: 'https://registry.test/', source: 'application option'}); + expect(lines.includes('Registry: https://registry.test/ (application option)')).toBeTruthy(); + expect(await cacheState(bridge, lib)).toBe('valid'); + }); + + it('the registry fixture is reproducible', async () => { + const first = await registryFiles(syntheticPackages()); + const second = await registryFiles(syntheticPackages()); + expect(first).toEqual(second); + expect(JSON.parse(new TextDecoder().decode(first.files.get('webfront-fixture-lib')))['dist-tags'].latest).toBe('1.1.0'); + }); +}); diff --git a/test/developer/specs/scripts-specs.mjs b/test/developer/specs/scripts-specs.mjs new file mode 100644 index 00000000..968aefaf --- /dev/null +++ b/test/developer/specs/scripts-specs.mjs @@ -0,0 +1,377 @@ +// Specs of wf run and wf exec: permissions, command resolution, the page side of the context API and the Worker's +// termination, with a scripted stand-in for the Worker and a fresh evaluation of the real Worker module. +import {checkRead, checkWrite, checkFetch, listable, scriptCommand, parseRunOptions, execTarget, lockedPackage, scriptHost, + runWorker, runResult, runDeadline, secondsLeft, ScriptExit, nodeBuiltin, nodeImport, createFinder, validateManifest} + from '../../../js/developer/environment/packages.bundle.mjs'; +import {memoryBridge} from '../memory-bridge.mjs'; +import {rejects, throws, freshModule} from '../support.mjs'; + +describe('wf run and wf exec', () => { + const encoder = new TextEncoder(); + const decoder = new TextDecoder(); + // The terminal's tokenizer splits on spaces outside quotes; terminal.mjs itself needs xterm. + const tokenize = text => text.match(/"[^"]*"|\S+/g).map(word => word.replace(/^"|"$/g, '')); + const permissions = {files: ['ui', 'data/in.json'], publish: ['generated', '.webfront/x', 'webfront.project.json'], fetch: ['https://api.test']}; + + it('context operations are checked against the manifest permissions', () => { + expect(checkRead(permissions, 'ui/main.tsx')).toBe('ui/main.tsx'); + expect(checkRead(permissions, 'generated/out.txt')).withContext('a writable path is readable').toBe('generated/out.txt'); + expect(checkRead(permissions, 'data/in.json')).toBe('data/in.json'); + for (const path of ['data/other.json', 'uix/a', 'webfront-packages.lock.json']) + throws(() => checkRead(permissions, path), /Permission denied: reading .* permissions\.files/); + throws(() => checkRead(permissions, '../outside'), /Not a project-relative path/); + throws(() => checkRead(permissions, ''), /Not a project-relative path/); + expect(checkWrite(permissions, 'generated/a/b.txt')).toBe('generated/a/b.txt'); + throws(() => checkWrite(permissions, 'ui/main.tsx'), /Permission denied: writing ui\/main.tsx .* permissions\.publish/); + for (const path of ['webfront.project.json', '.webfront/x/y']) + throws(() => checkWrite(permissions, path), /managed by wf and never written by a script/); + expect(checkFetch(permissions, 'https://api.test/v1?q=1').href).toBe('https://api.test/v1?q=1'); + throws(() => checkFetch(permissions, 'https://other.test/'), /Permission denied: fetching https:\/\/other.test/); + throws(() => checkFetch({}, '/local', 'http://localhost:9002/'), /permissions\.fetch/); + }); + + it('wf run resolves a script of the manifest to a module or a wf command, without a shell', () => { + const manifest = validateManifest({format: 1, name: 'app', version: '1.0.0', + scripts: {gen: 'tools/gen.ts --fast', build: 'wf embed main', loop: 'wf run loop'}}); + expect(scriptCommand(manifest, 'gen', ['a b'], tokenize)).toEqual({kind: 'module', entry: {namespace: 'project', path: 'tools/gen.ts'}, args: ['--fast', 'a b']}); + expect(scriptCommand(manifest, 'build', ['--x'], tokenize)).toEqual({kind: 'wf', argv: ['embed', 'main', '--x']}); + throws(() => scriptCommand(manifest, 'missing', [], tokenize), /No script "missing" .* \(scripts: build, gen, loop\)/); + throws(() => scriptCommand(manifest, 'loop', [], tokenize, 4), /more than 4 levels/); + throws(() => scriptCommand({...manifest, scripts: {bad: '../x.ts'}}, 'bad', [], tokenize), /Unsafe package path/); + expect(parseRunOptions(['--timeout', '5', 'gen', '--timeout', '9'], 'u')).toEqual({timeout: 5, target: 'gen', args: ['--timeout', '9']}); + expect(parseRunOptions(['gen'], 'u').timeout).toBe(600); + for (const args of [['--timeout', '0', 'gen'], ['--timeout', '3601', 'gen'], ['--timeout', '1.5', 'gen']]) + throws(() => parseRunOptions(args, 'u'), /--timeout expects whole seconds from 1 to 3600/); + throws(() => parseRunOptions([], 'wf run + + diff --git a/test/web/developer-session.mjs b/test/web/developer-session.mjs new file mode 100644 index 00000000..77c8d0fb --- /dev/null +++ b/test/web/developer-session.mjs @@ -0,0 +1,6 @@ +// A second browser session for developer-specs.mjs: its own WebFront connection, the same environment runtime. +globalThis.session = (async () => { + await webFront.ready; + const runtime = await import('/webfront/developer/environment/runtime.mjs'); + return {runtime, bridge: webFront, cppCommands: await runtime.discoverCommands(webFront)}; +})(); diff --git a/test/web/developer-specs.mjs b/test/web/developer-specs.mjs new file mode 100644 index 00000000..75eb1e47 --- /dev/null +++ b/test/web/developer-specs.mjs @@ -0,0 +1,971 @@ +import {withTimers, untilReady} from './timers.mjs'; +// Autonomous real-engine test: compiled WASM, npm graph, Life 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); +} +// Ends the --public smoke test, which has no local registry for the checks that follow the generated headers. +class PublicSmokeDone extends Error {} +try { + await webFront.ready; + for (let attempt = 0; attempt < 300; ++attempt) { + const text = document.getElementById('status')?.textContent ?? ''; + if (text.startsWith('Bootstrap failed:')) throw new Error(text); + if (text.startsWith('Developer environment ready.')) break; + if (attempt === 299) throw new Error('Bootstrap readiness timed out'); + await delay(100); + } + const runtime = await import('/webfront/developer/environment/runtime.mjs'); + const config = JSON.parse(await webFront.cppFunction('webfront.developer.config')()); + const environment = await (await fetch('/webfront/developer/environment/environment.json')).json(); + const currentDistribution = !config.environment.startsWith('https:'); + if (currentDistribution) assert(JSON.stringify(Object.keys(environment.starters)) === JSON.stringify(['life']), 'Only the Life starter must be shipped'); + config.starters = Object.fromEntries(Object.entries(environment.starters).map(([name, value]) => [name, {url: new URL(value.archive, new URL(config.environment, location.href)).href, integrity: value.integrity}])); + const context = {bridge: webFront, config, preview: document.getElementById('preview'), signal: new AbortController().signal, + write: text => console.log(text)}; + if (currentDistribution) assert(await runtime.execute(['create', 'pi'], context).then(() => false, error => /Unknown pinned starter/.test(error.message)), + 'The retired PI starter must not be offered'); + await runtime.execute(['create', 'life'], context); + const overwriteRefused = await runtime.execute(['create', 'life'], 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); + let 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 = {LifeUI: {entry: 'main', output: 'generated/LifeUI.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; + const frame = context.preview; + // wf build does not navigate; wf dev keeps one WASM context, reloads only committed output and recovers. + assert((await runtime.complete('wf d', context)).candidates.includes('dev'), 'Completion must list wf dev'); + assert((await runtime.complete('wf build m', context)).candidates.includes('main') && + (await runtime.complete('wf dev m', context)).candidates.includes('main'), 'Build/dev completion must list manifest entries'); + const frameBeforeBuild = frame.contentDocument; + const frameURLBeforeBuild = frame.contentWindow.location.href; + await runtime.execute(['build'], context); + assert(frame.contentDocument === frameBeforeBuild && frame.contentWindow.location.href === frameURLBeforeBuild, + 'wf build must leave the preview alone'); + assert((await readFile('.webfront/developer/build/app.js')).length > 0, 'wf build must publish compiled JS'); + assert(new TextDecoder().decode(await readFile('.webfront/developer/build/index.html')).includes('./app.js'), 'wf build must publish HTML and JS'); + const waitDev = async (predicate, message) => { + for (let attempt = 0; !predicate(); ++attempt) { + if (attempt === 300) throw new Error(message); + await delay(30); + } + }; + await writeFile('watch/main.ts', "import {value} from './value'; document.getElementById('root').textContent = value;\n"); + await writeFile('watch/value.ts', "export const value: string = 'watch-one';\n"); + let devOutput = ''; + const devStop = new AbortController(); + await withTimers([750], async clock => { + const poll = async () => { + await waitDev(() => clock.pending() > 0, 'Dev polling deadline was not armed'); + clock.fire(750); + }; + const devResult = runtime.execute(['dev', 'watch/main.ts'], {...context, signal: devStop.signal, + write: text => { devOutput += text; }}).then(() => null, error => error); + try { + await waitDev(() => frame.contentDocument?.getElementById('root')?.textContent === 'watch-one', 'Initial dev preview did not mount'); + await writeFile('watch/value.ts', "export const value: string = 'watch-two';\n"); + await poll(); + await waitDev(() => frame.contentDocument?.getElementById('root')?.textContent === 'watch-two', 'Changed dependency was not rebuilt'); + const lastGoodDocument = frame.contentDocument; + const lastGoodJS = new TextDecoder().decode(await readFile('.webfront/developer/preview/app.js')); + await writeFile('watch/value.ts', 'export const value = ;\n'); + await poll(); + await waitDev(() => frame.contentDocument?.getElementById('webfront-build-diagnostics'), 'Syntax error was not overlaid'); + assert(frame.contentDocument === lastGoodDocument && frame.contentDocument.getElementById('root').textContent === 'watch-two', 'A syntax error must preserve the running preview'); + assert(new TextDecoder().decode(await readFile('.webfront/developer/preview/app.js')) === lastGoodJS, 'A syntax error must preserve published output'); + assert(/watch\/value.ts:1:/.test(devOutput) && /watch\/value.ts:1:/.test(frame.contentDocument.getElementById('webfront-build-diagnostics').textContent), 'Terminal and overlay must locate the syntax error'); + await writeFile('watch/value.ts', "export const value: string = 'watch-three';\n"); + await poll(); + await waitDev(() => frame.contentDocument?.getElementById('root')?.textContent === 'watch-three', 'Corrected source did not recover'); + assert(!frame.contentDocument.getElementById('webfront-build-diagnostics'), 'Successful build must clear the overlay'); + await writeFile('watch/main.ts', "import {value} from './created'; document.getElementById('root').textContent = value;\n"); + await poll(); + await waitDev(() => frame.contentDocument?.getElementById('webfront-build-diagnostics'), 'Missing import was not reported'); + await writeFile('watch/created.ts', "export const value = 'watch-created';\n"); + await poll(); + await waitDev(() => frame.contentDocument?.getElementById('root')?.textContent === 'watch-created', 'Creating a missing import must recover'); + assert(history.length === historyLength, 'Dev reloads must replace session history'); + } finally { devStop.abort(); } + assert((await devResult)?.exitCode === 130, 'Ctrl+C must stop dev with exit code 130'); + const afterStop = frame.contentDocument; + await writeFile('watch/created.ts', "export const value = 'must-not-rebuild';\n"); + assert(clock.pending() === 0, 'Stopped dev must remove its polling timer'); + assert(frame.contentDocument === afterStop && frame.contentDocument.getElementById('root').textContent === 'watch-created', 'Stopped dev must not rebuild or reload'); + assert(JSON.parse(new TextDecoder().decode(await call('list', '.webfront/developer/staging'))).length === 0, 'Stopped dev must leave no staging'); + }); + // Each named entry gets its own relative HTML/assets when building all manifest entries. + await writeFile('webfront.project.json', JSON.stringify({...manifest, entries: {one: 'watch/value.ts', two: 'watch/created.ts'}})); + await runtime.execute(['build'], context); + for (const name of ['one', 'two']) assert((await readFile(`.webfront/developer/build/${name}/index.html`)).length > 0, `Missing build entry ${name}`); + const firstEntryBuild = new TextDecoder().decode(await readFile('.webfront/developer/build/one/app.js')); + const secondEntryBuild = new TextDecoder().decode(await readFile('.webfront/developer/build/two/app.js')); + await writeFile('watch/created.ts', 'export const value = ;\n'); + assert(await runtime.execute(['build'], context).then(() => false, () => true), 'A failed build must reject'); + assert(new TextDecoder().decode(await readFile('.webfront/developer/build/one/app.js')) === firstEntryBuild && + new TextDecoder().decode(await readFile('.webfront/developer/build/two/app.js')) === secondEntryBuild, 'Failure in a later entry must preserve the entire previous build'); + await writeFile('watch/created.ts', "export const value = 'must-not-rebuild';\n"); + await writeFile('webfront.project.json', JSON.stringify(manifest)); + // Exercise the maintained public application rather than the retired PI demo. + await runtime.execute(['preview'], context); + for (let attempt = 0; !frame.contentDocument?.querySelector('[data-testid="pattern-blinker"]'); ++attempt) { + if (attempt === 200) throw new Error('Life preview did not mount'); + await delay(50); + } + assert(history.length === historyLength, 'Preview rebuilds must not accumulate session history'); + const life = frame.contentDocument; + const button = name => life.querySelector(`[data-testid="${name}"]`); + const waitFor = async (predicate, message) => { + for (let attempt = 0; !predicate(); ++attempt) { + if (attempt === 100) throw new Error(message); + await delay(30); + } + }; + const packed = new Uint8Array(128); + for (const i of [330, 331, 332]) packed[i >> 3] |= 1 << (i & 7); + const next = await webFront.cppFunction('life.step')(packed); + if (!(next instanceof Uint8Array) || next.length !== 128) throw new Error('Expected 128 packed Life bytes'); + const expected = new Uint8Array(128); + for (const i of [299, 331, 363]) expected[i >> 3] |= 1 << (i & 7); + if (!next.every((byte, i) => byte === expected[i])) throw new Error('Incorrect packed Life bit order'); + for (const value of [new Uint8Array(127), new Int8Array(128), '0'.repeat(1024)]) { + const rejected = await webFront.cppFunction('life.step')(value).then(() => false, () => true); + if (!rejected) throw new Error('Malformed Life grid accepted'); + } + button('pattern-blinker').click(); + await waitFor(() => button('population').textContent === '3', 'Blinker population'); + button('step').click(); + await waitFor(() => button('generation').textContent === '0001', 'C++ Life step'); + assert(button('population').textContent === '3', 'Blinker must preserve its population'); + button('play').click(); + await waitFor(() => Number(button('generation').textContent) >= 3, 'Life animation'); + button('play').click(); + // Clear invalidates a possible in-flight generation and stops the timer. + button('clear').click(); + await delay(400); + assert(button('generation').textContent === '0000' && button('population').textContent === '0', 'Clear must discard stale replies'); + // Paint across an octet boundary, then let C++ eliminate the two isolated cells. + button('view').click(); + await waitFor(() => button('view').getAttribute('aria-pressed') === 'true', 'Plan view'); + const canvas = life.querySelector('canvas'); + const paint = x => { + const rect = canvas.getBoundingClientRect(); + canvas.dispatchEvent(new frame.contentWindow.MouseEvent('click', {bubbles: true, + clientX: rect.left + (209 + x * 17 + 7) * rect.width / 960, + clientY: rect.top + (65 + 7) * rect.height / 680})); + }; + paint(7); + await waitFor(() => button('population').textContent === '1', 'Plant the last bit of an octet'); + paint(7); + await waitFor(() => button('population').textContent === '0', 'Toggle a packed cell off'); + paint(7); + await waitFor(() => button('population').textContent === '1', 'Plant the first cell'); + paint(8); + await waitFor(() => button('population').textContent === '2', 'Plant across the octet boundary'); + button('step').click(); + await waitFor(() => button('generation').textContent === '0001' && button('population').textContent === '0', 'C++ evolves painted packed cells'); + button('view').click(); + button('pattern-glider').click(); + await waitFor(() => button('population').textContent === '5', 'Glider population'); + for (let i = 1; i <= 4; i++) { + await waitFor(() => !button('step').disabled, 'Single step readiness'); + button('step').click(); + await waitFor(() => Number(button('generation').textContent) === i, 'Glider generation'); + } + assert(button('population').textContent === '5', 'C++ glider survives four steps'); + assert(life.querySelector('canvas').width > 0 && !life.querySelector('[role="alert"]').textContent, 'Life canvas rendered without errors'); + await runtime.execute(['embed', 'LifeUI'], context); + const lifeHeader = await webFront.cppFunction('test.header')('LifeUI'); + await runtime.execute(['embed', 'ui/main.tsx', '--output', 'generated/LifeUI.hpp'], context); + assert(await webFront.cppFunction('test.header')('LifeUI') === lifeHeader, 'Life header must be deterministic'); + if (!config.registryExplicit) throw new PublicSmokeDone(); + // The application path above needs React DOM. Cache/command regressions do not: keep a small + // real graph instead of repeatedly transferring React DOM's server/development files through the bridge. + manifest.dependencies = {react: '19.3.1', 'webfront-fixture-lib': '1.0.0'}; + await writeFile('webfront.project.json', JSON.stringify(manifest, null, 2)); + await runtime.execute(['install', '--update'], context); + lock = await runtime.readLock(webFront); + assert(Object.keys(lock.packages).length === 2 && !lock.roots['react-dom'], 'Command fixtures must not retain the application dependency graph'); + // 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 2 packages/.test(await runtime.execute(['install'], context)), 'A consistent lock must install its exact graph'); + // wf restore rebuilds an emptied cache from the lock alone, from the application's local registry although the + // manifest names another one; --offline only checks the cache, without any request. + const requests = []; + const pageFetch = globalThis.fetch; + globalThis.fetch = (input, init) => { + requests.push(new URL(input instanceof Request ? input.url : input, location.href).href); + return pageFetch(input, init); + }; + try { + const emptied = await call('begin', '.webfront/developer/packages', true); + await call('commit', emptied); + const missing = await runtime.execute(['restore', '--offline'], context).then(() => '', error => error.message); + assert(/react@19\.3\.1 \(missing\)/.test(missing) && requests.length === 0, 'An offline check must list missing packages without any request'); + await writeFile('webfront.project.json', JSON.stringify({...manifest, registry: 'https://registry.invalid/'}, null, 2)); + const restored = await runtime.execute(['restore'], context); + assert(/Restored 2 of 2 packages/.test(restored) && restored.includes('Registry: /fixtures/registry/ (application option)'), `wf restore must use and name the application registry: ${restored}`); + assert(requests.length > 0 && requests.every(url => url.startsWith(`${location.origin}/fixtures/registry/`)), 'wf restore must contact the application registry only'); + requests.length = 0; + assert(/Cache verified offline: 2 packages/.test(await runtime.execute(['restore', '--offline'], context)) && requests.length === 0, 'A complete cache must verify offline'); + } finally { + globalThis.fetch = pageFetch; + } + await writeFile('webfront.project.json', JSON.stringify(manifest, null, 2)); + const previous = frame.contentWindow.location.href; + await writeFile('restore/main.js', "import value from 'webfront-fixture-lib'; document.getElementById('root').textContent = value;\n"); + await runtime.execute(['preview', 'restore/main.js'], context); + const restoredMounted = () => frame.contentDocument?.getElementById('root')?.textContent === 'webfront-fixture-lib@1.0.0'; + for (let attempt = 0; frame.contentWindow.location.href === previous || !restoredMounted(); ++attempt) { + if (attempt === 300) throw new Error('The preview did not build from the restored cache'); + await delay(50); + } + const absent = await runtime.execute(['install', 'webfront-fixture-absent'], context).then(() => '', error => error.message); + assert(/HTTP 404/.test(absent), 'A package absent from the registry must reject'); + 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'); + // wf run and wf exec: WebFront scripts in a dedicated Worker, under the manifest permissions. + const scriptOutput = []; + const runContext = (signal = new AbortController().signal) => ({...context, signal, write: text => { scriptOutput.push(text); console.log(text); }}); + const printed = async text => { + for (let attempt = 0; !scriptOutput.some(line => line.includes(text)); ++attempt) { + if (attempt === 200) throw new Error(`The script did not print ${text}`); + await delay(25); + } + }; + const failure = promise => promise.then(() => null, error => error); + const scripts = { + 'tools/gen.ts': "export default async function (context: {args: string[]; project: any; console: Console}) {\n const text: string = context.args.join('+');\n await context.project.write('generated/script/out.txt', text);\n context.console.log('wrote', text);\n}\n", + 'tools/denied.mjs': "export default async context => { await context.project.write('ui/main.tsx', 'replaced'); };\n", + 'tools/node.mjs': "import {readFileSync} from 'fs';\nexport default async () => readFileSync;\n", + 'tools/fail.mjs': "export default async context => context.exit(3);\n", + 'tools/coop.mjs': "export default context => new Promise((resolve, reject) => {\n context.signal.addEventListener('abort', () => reject(context.signal.reason));\n context.console.log('waiting');\n});\n", + 'tools/loop.mjs': "export default async context => { context.console.log('looping'); for (;;) {} };\n", + 'tools/big.mjs': "export default async context => { context.console.log('writing'); await context.project.write('generated/script/big.bin', new Uint8Array(4 * 1024 * 1024).fill(1)); };\n", + 'tools/unawaited.mjs': "export default async context => { context.project.write('generated/script/unawaited.txt', 'done'); };\n", + 'tools/root.mjs': "export default async context => context.console.log('root', JSON.stringify(await context.project.list()));\n", + 'tools/jsx.tsx': "export default async (context: any) => { const element = x; context.console.log('jsx', element.type); };\n", + }; + for (const [path, text] of Object.entries(scripts)) await writeFile(path, text); + const mainBefore = await readFile('ui/main.tsx'); + const scriptManifest = {...manifest, permissions: {files: ['tools'], publish: ['generated/script']}, + scripts: Object.fromEntries([...Object.keys(scripts).map(path => [path.split('/')[1].split('.')[0], path]), ['listing', 'wf list'], ['nested', 'wf run --timeout 120 loop']])}; + await writeFile('webfront.project.json', JSON.stringify(scriptManifest, null, 2)); + assert(/Script gen completed/.test(await runtime.execute(['run', 'gen', 'a', 'b'], runContext())), 'A TypeScript script must run'); + assert(new TextDecoder().decode(await readFile('generated/script/out.txt')) === 'a+b' && scriptOutput.includes('wrote a+b\r\n'), 'The script must write an allowed file and stream its console'); + assert(/react@19\.3\.1/.test(await runtime.execute(['run', 'listing'], runContext())), 'A script may run a wf command'); + const denied = await failure(runtime.execute(['run', 'denied'], runContext())); + assert(/Permission denied: writing ui\/main\.tsx/.test(denied?.message) && denied.exitCode === 1, `A context operation outside the permissions must be refused: ${denied}`); + assert(new TextDecoder().decode(await readFile('ui/main.tsx')) === new TextDecoder().decode(mainBefore), 'A refused write must not change the file'); + const node = await failure(runtime.execute(['run', 'node'], runContext())); + assert(/"fs" is a Node\.js API/.test(node?.message), `A Node.js import must be refused while loading: ${node}`); + const exited = await failure(runtime.execute(['run', 'fail'], runContext())); + assert(exited?.exitCode === 3 && /exited with code 3/.test(exited.message), 'A non-zero exit code must be propagated'); + const cooperative = new AbortController(); + const waiting = failure(runtime.execute(['run', 'coop'], runContext(cooperative.signal))); + await printed('waiting'); + cooperative.abort(new Error('Interrupted')); + const stopped = await waiting; + assert(stopped?.exitCode === 130 && !/grace period/.test(stopped.message), `Ctrl+C must stop a cooperative script: ${stopped}`); + const interrupt = new AbortController(); + const looping = failure(runtime.execute(['run', 'loop'], runContext(interrupt.signal))); + await printed('looping'); + await withTimers([2000], async clock => { + interrupt.abort(new Error('Interrupted')); + clock.fire(2000); + const killed = await looping; + assert(killed?.exitCode === 130 && /terminated after the 2 s grace period/.test(killed.message), `A busy script must be terminated after Ctrl+C: ${killed}`); + }); + // Real Worker/bridge preparation gets a generous bound; only the deadline under test is advanced. + for (const target of ['loop', 'nested']) { + scriptOutput.length = 0; + await withTimers([60000, 2000], async clock => { + const running = failure(runtime.execute(['run', '--timeout', '60', target], runContext())); + await printed('looping'); + clock.fire(60000); + clock.fire(2000); + const timedOut = await running; + assert(timedOut?.exitCode === 124 && /stopped at its time limit/.test(timedOut.message), `The inherited time limit must stop ${target}: ${timedOut}`); + }); + } + assert(/react@19\.3\.1/.test(await runtime.execute(['list'], context)), 'The terminal must stay usable after a termination'); + assert(/completed/.test(await runtime.execute(['run', 'unawaited'], runContext())), 'A script that does not await its write must complete'); + assert(new TextDecoder().decode(await readFile('generated/script/unawaited.txt')) === 'done', 'A write the script did not await must be applied'); + await runtime.execute(['run', 'root'], runContext()); + assert(scriptOutput.includes('root ["generated/","tools/"]\r\n'), `The root must list the entries leading to granted paths: ${scriptOutput.filter(line => line.startsWith('root'))}`); + await runtime.execute(['run', 'jsx'], runContext()); + assert(scriptOutput.includes('jsx b\r\n'), 'A TSX script must compile its JSX with the automatic runtime'); + // A stop during a large write: the file is either untouched or complete, and no staging is left. + const writing = new AbortController(); + const big = failure(runtime.execute(['run', 'big'], runContext(writing.signal))); + await printed('writing'); + writing.abort(new Error('Interrupted')); + await big; + const written = await readFile('generated/script/big.bin').then(bytes => bytes.length, () => 0); + assert(written === 0 || written === 4 * 1024 * 1024, `A stopped write must leave no partial file: ${written} bytes`); + const staged = JSON.parse(new TextDecoder().decode(await call('list', '.webfront/developer/staging'))); + assert(staged.length === 0, `A stopped write must leave no staged files: ${staged}`); + // wf exec runs the webfront.bin entry of an installed package, never an npm bin. + await runtime.execute(['install', 'webfront-fixture-tool', 'webfront-fixture-nodebin'], context); + assert(/completed/.test(await runtime.execute(['exec', 'webfront-fixture-tool', 'hello'], runContext())), 'wf exec must run a WebFront entry'); + assert(/^webfront-fixture-lib@1\.\d+\.\d+ hello$/.test(new TextDecoder().decode(await readFile('generated/script/tool.txt'))), 'The entry must bundle its locked dependency'); + assert(/only declares an npm "bin"/.test((await failure(runtime.execute(['exec', 'webfront-fixture-nodebin'], runContext())))?.message), 'A package with only an npm bin must be refused'); + assert(/no WebFront executable entry/.test((await failure(runtime.execute(['exec', 'webfront-fixture-lib'], runContext())))?.message), 'A browser package without an entry must be refused'); + // wf check: a real TypeScript type check in a Worker, with the typescript and the declarations of the lock, all + // served by the local registry. + const checkRequests = []; + globalThis.fetch = (input, init) => { + checkRequests.push(new URL(input instanceof Request ? input.url : input, location.href).href); + return pageFetch(input, init); + }; + const checkFiles = { + 'tsconfig.json': JSON.stringify({compilerOptions: {strict: true, target: 'ES2022', module: 'ESNext', moduleResolution: 'Bundler', lib: ['ES2022']}, include: ['check']}), + 'check/main.ts': "import {answer, area} from 'webfront-fixture-typed';\nimport {legacy} from 'webfront-fixture-legacy';\nimport {greet} from 'webfront-fixture-untyped';\nimport {twice} from './util';\n" + + "export const total: number = twice(answer) + area({width: 2, height: 3});\nexport const word: string = greet(legacy);\n", + 'check/util.ts': 'export const twice = (value: number): number => 2 * value;\n', + }; + for (const [path, text] of Object.entries(checkFiles)) await writeFile(path, text); + const packageReads = new Map(); + const checkBridge = {socket: webFront.socket, cppFunction: name => name !== 'webfront.developer.read' ? webFront.cppFunction(name) : + (path, offset) => { + if (!path.startsWith('.webfront/developer/packages/')) return webFront.cppFunction(name)(path, offset); + const key = `${path}:${offset}`; + if (!packageReads.has(key)) { + const reading = webFront.cppFunction(name)(path, offset).catch(error => { + packageReads.delete(key); + throw error; + }); + packageReads.set(key, reading); + } + return packageReads.get(key); + }}; + const retryFile = '.webfront/developer/packages/cache-retry-fixture/probe.txt'; + const retryRead = checkBridge.cppFunction('webfront.developer.read'); + assert(await retryRead(retryFile, 0).then(() => false, () => true), 'The first missing package read must fail'); + await writeFile(retryFile, 'recovered'); + assert(new TextDecoder().decode(await retryRead(retryFile, 0)) === 'recovered', 'A rejected package read must be retried'); + const checked = async (args = [], extra = {}) => { + scriptOutput.length = 0; + const result = await runtime.execute(['check', ...args], {...runContext(), bridge: checkBridge, ...extra}).then(text => ({text}), error => ({error})); + return {...result, output: scriptOutput.join('')}; + }; + try { + assert(/needs the typescript package: run wf install typescript@6/.test((await checked()).error?.message), 'wf check must ask for typescript'); + await runtime.execute(['install', 'typescript@4.9.5'], context); + const old = await checked(); + assert(/supports typescript 5\.x and 6\.x .* not typescript@4\.9\.5/.test(old.error?.message), `An unsupported typescript must be refused: ${old.error}`); + await runtime.execute(['install', 'typescript@5.9.3', 'webfront-fixture-typed', 'webfront-fixture-legacy', 'webfront-fixture-untyped', '@types/webfront-fixture-untyped'], context); + const five = await checked(); + assert(five.text && five.output.includes('No type errors in 2 project files (TypeScript 5.9.3).'), `TypeScript 5.9 must accept the project: ${five.error}\n${five.output}`); + await runtime.execute(['install', 'typescript@6.0.3'], context); + const six = await checked(); + assert(/Type check completed/.test(six.text) && six.output.includes('No type errors in 2 project files (TypeScript 6.0.3).'), `TypeScript 6.0 must accept the project: ${six.error}\n${six.output}`); + assert(checkRequests.length > 0 && checkRequests.every(url => url.startsWith(`${location.origin}/fixtures/registry/`)), `typescript must come from the local registry: ${checkRequests}`); + } finally { + globalThis.fetch = pageFetch; + } + await writeFile('check/util.ts', 'export const twice = (value: number): number => `${value}`;\n'); + const typeError = await checked(); + assert(typeError.error?.exitCode === 1 && typeError.output.includes("check/util.ts(1,49): error TS2322: Type 'string' is not assignable to type 'number'.") && + typeError.output.includes('Found 1 error in 1 file.'), `A type error must be reported with its file, line, column and code: ${typeError.error}\n${typeError.output}`); + await writeFile('check/util.ts', checkFiles['check/util.ts']); + const bounded = await checked([], {snapshotBounds: {files: 20, bytes: 64 * 1024 * 1024, entries: 1000}}); + assert(bounded.error?.exitCode === 1 && /the snapshot reached its bounds \(20 files, 64 MiB\): \d+ files were not loaded and are treated as missing/.test(bounded.output), + `A snapshot past its bounds must be reported: ${bounded.error}\n${bounded.output}`); + // NodeNext takes the module format from a package.json above the included directory, and composite keeps implying + // declaration under noEmit. + await writeFile('esm-check/package.json', JSON.stringify({type: 'module'})); + await writeFile('esm-check/src/main.ts', 'export const value: number = await Promise.resolve(1);\n'); + await writeFile('tsconfig.json', JSON.stringify({compilerOptions: {strict: true, target: 'ES2022', module: 'NodeNext', moduleResolution: 'NodeNext', + lib: ['ES2022'], composite: true, declarationMap: true, incremental: true}, include: ['esm-check/src']})); + const esm = await checked(); + assert(esm.text && esm.output.includes('No type errors in 1 project file (TypeScript 6.0.3).'), `A valid NodeNext composite project must pass: ${esm.error}\n${esm.output}`); + assert(await readFile('tsconfig.tsbuildinfo').then(() => false, () => true), 'An incremental check must not write build information'); + await writeFile('tsconfig.json', checkFiles['tsconfig.json']); + // A long check is synchronous in its Worker: Ctrl+C terminates it after the grace period, and nothing is written. + const slow = ['type Build = T["length"] extends N ? T : Build;']; + for (let n = 400; n < 1000; ++n) slow.push(`export const v${n}: Build<${n}>['length'] = ${n};`); + await writeFile('check/slow.ts', slow.join('\n') + '\n'); + const listing = async path => new TextDecoder().decode(await call('list', path)); + const before = [await listing(''), await listing('check')]; + const stopCheck = new AbortController(); + scriptOutput.length = 0; + const longCheck = failure(runtime.execute(['check'], {...runContext(stopCheck.signal), bridge: checkBridge})); + await printed('Checking 3 root files'); + await withTimers([2000], async clock => { + stopCheck.abort(new Error('Interrupted')); + clock.fire(2000); + const checkStopped = await longCheck; + assert(checkStopped?.exitCode === 130 && /Type check stopped by Ctrl\+C \(terminated after the 2 s grace period\)/.test(checkStopped.message), + `Ctrl+C must terminate a long check after the grace period: ${checkStopped}`); + }); + assert(JSON.stringify([await listing(''), await listing('check')]) === JSON.stringify(before), 'A check must not write any project file'); + assert(JSON.parse(await listing('.webfront/developer/staging')).length === 0, 'A check must leave no staged files'); + assert(/typescript@6\.0\.3/.test(await runtime.execute(['list'], context)), 'The terminal must stay usable after a stopped check'); + // wf test: the specs of the manifest under the locked jasmine-core, in a frame of this page. + const testOutput = []; + let testRun = 0; + const tested = async (args = [], extra = {}) => { + const label = `wf test #${++testRun} ${args.join(' ')}`; + await webFront.cppFunction('test.progress')(`${label}: starting`); + testOutput.length = 0; + let report = null; + const result = await runtime.execute(['test', ...args], {...runContext(), write: text => testOutput.push(text), onReport: value => { report = value; }, ...extra}) + .then(text => ({text}), error => ({error})); + await webFront.cppFunction('test.progress')(`${label}: ${report?.status ?? result.error?.message ?? 'done'}`); + return {...result, report, output: testOutput.join('')}; + }; + const readManifest = async () => JSON.parse(new TextDecoder().decode(await readFile('webfront.project.json'))); + const specsOf = async specs => writeFile('webfront.project.json', JSON.stringify({...await readManifest(), test: {specs}}, null, 2)); + assert(/No specs: declare "test"/.test((await tested()).error?.message), 'wf test must ask for declared specs'); + await writeFile('tests/pass.spec.js', "describe('passing', () => {\n it('adds', () => expect(1 + 1).toBe(2));\n it('is pending', () => pending('not yet'));\n" + + " it('awaits', async () => { await Promise.resolve(); expect(true).toBeTrue(); });\n});\n"); + await specsOf(['tests/pass.spec.js']); + assert(/jasmine-core is not installed: run wf install jasmine-core/.test((await tested()).error?.message), 'wf test must ask for jasmine-core'); + const testRequests = []; + globalThis.fetch = (input, init) => { + testRequests.push(new URL(input instanceof Request ? input.url : input, location.href).href); + return pageFetch(input, init); + }; + try { await runtime.execute(['install', 'jasmine-core'], context); } finally { globalThis.fetch = pageFetch; } + assert(testRequests.length > 0 && testRequests.every(url => url.startsWith(`${location.origin}/fixtures/registry/`)), `jasmine-core must come from the local registry: ${testRequests}`); + const testLock = await runtime.readLock(webFront); + const jasmineVersion = testLock.packages[testLock.roots['jasmine-core'].id].version; + const passing = await tested(); + assert(passing.text && passing.report?.status === 'passed' && passing.report.exitCode === 0 && passing.report.total === 3 && passing.report.passed === 2 && + passing.report.pending === 1 && passing.report.failed === 0 && passing.report.jasmine === jasmineVersion, + `Passing specs must be reported exactly: ${passing.error}\n${JSON.stringify(passing.report)}`); + assert(passing.output.startsWith('.*.') && passing.text.startsWith('PASSED: 3 specs, 0 failures, 1 pending') && /PENDING passing is pending: not yet/.test(passing.text) && + passing.text.includes(`jasmine-core ${jasmineVersion}`), `The terminal must show the progress and the summary: ${passing.output}\n${passing.text}`); + assert(!document.querySelector('iframe[title="WebFront tests"]'), 'The runner frame must be removed after a run'); + // A failing spec and the asynchronous failures: a late exception, an unhandled rejection, a spec reaching the bridge. + await writeFile('tests/fail.spec.ts', "describe('failing', () => {\n it('fails with a message', () => { const expected: number = 1; expect(expected).toBe(2); });\n});\n"); + await writeFile('tests/async.spec.js', "describe('asynchronous', () => {\n it('throws later', done => { setTimeout(() => { throw new Error('late boom'); }, 0); setTimeout(done, 80); });\n" + + " it('rejects unhandled', async () => { Promise.reject(new Error('unhandled boom')); await new Promise(resolve => setTimeout(resolve, 80)); });\n" + + " it('reaches the bridge', async () => expect(await webFront.cppFunction('test.browsers')()).toBeGreaterThan(0));\n});\n"); + await specsOf(['tests/pass.spec.js', 'tests/fail.spec.ts', 'tests/async.spec.js']); + const failing = await tested(); + const failedNames = failing.report?.failures.map(failure => failure.name); + assert(failing.error?.exitCode === 1 && failing.report?.status === 'failed' && failing.report.exitCode === 1 && failing.report.total === 7 && failing.report.passed === 3 && + failing.report.failed === 3 && failing.report.pending === 1, `A failing run must report exact counts and exit 1: ${failing.error}\n${JSON.stringify(failing.report)}`); + assert(JSON.stringify(failedNames) === JSON.stringify(['failing fails with a message', 'asynchronous throws later', 'asynchronous rejects unhandled']), `The failed specs must be named in order: ${failedNames}`); + const messageOf = name => failing.report.failures.find(failure => failure.name.endsWith(name)).messages.map(message => message.message).join('\n'); + assert(/Expected 1 to be 2\./.test(messageOf('fails with a message')) && /late boom/.test(messageOf('throws later')) && /unhandled boom/.test(messageOf('rejects unhandled')), + `Failure messages must be exact: ${JSON.stringify(failing.report.failures)}`); + assert(failing.error.message.startsWith('FAILED: 7 specs, 3 failures, 1 pending') && failing.error.message.includes('FAIL failing fails with a message\n Expected 1 to be 2.') && + failing.output.startsWith('.*.F'), `The terminal must show the failures: ${failing.output}\n${failing.error.message}`); + // A pattern keeps the specs whose full name contains it; one that matches nothing is not a pass. + const filtered = await tested(['passing']); + assert(filtered.report?.status === 'passed' && filtered.report.total === 3 && filtered.report.excluded === 4 && /4 filtered out/.test(filtered.text), `A pattern must filter the specs: ${filtered.error}\n${JSON.stringify(filtered.report)}`); + const unmatched = await tested(['no such spec']); + assert(unmatched.error?.exitCode === 1 && unmatched.report?.status === 'incomplete' && /No spec matches "no such spec"/.test(unmatched.error.message), `A pattern matching nothing must fail: ${unmatched.error}`); + // An afterAll that throws is reported with its suite; a stylesheet a spec imports is applied to its page. + await writeFile('tests/styled.css', '.probe { display: block; width: 37px; }\n'); + await writeFile('tests/suite.spec.js', "import './styled.css';\ndescribe('cleanup', () => {\n it('passes', () => {});\n afterAll(() => { throw new Error('afterAll boom'); });\n});\n" + + "describe('styled', () => {\n it('applies the imported stylesheet', () => {\n const probe = document.createElement('div');\n probe.className = 'probe';\n document.body.append(probe);\n expect(getComputedStyle(probe).width).toBe('37px');\n probe.remove();\n });\n});\n"); + await specsOf(['tests/suite.spec.js']); + const suiteFailure = await tested(); + assert(suiteFailure.error?.exitCode === 1 && suiteFailure.report?.status === 'failed' && suiteFailure.report.total === 2 && suiteFailure.report.passed === 2 && suiteFailure.report.failed === 0 && + suiteFailure.report.suites.length === 1 && suiteFailure.report.suites[0].name === 'cleanup' && /afterAll boom/.test(suiteFailure.report.suites[0].messages[0].message) && + /FAIL cleanup \(suite\)/.test(suiteFailure.error.message), `An afterAll failure must be reported with its suite, and the stylesheet applied: ${suiteFailure.error}\n${JSON.stringify(suiteFailure.report)}`); + // A spec that does not load fails the run: it is a build error for one that does not compile, a report for one that throws. + await writeFile('tests/missing.spec.js', "import './absent';\n"); + await specsOf(['tests/pass.spec.js', 'tests/missing.spec.js']); + const unbuilt = await tested(); + assert((unbuilt.error?.exitCode ?? 1) === 1 && /absent/.test(unbuilt.error.message) && !unbuilt.report, `An unresolved import must fail the build: ${unbuilt.error}`); + await writeFile('tests/throws.spec.js', "throw new Error('loading boom');\n"); + await specsOf(['tests/throws.spec.js']); + const unloaded = await tested(); + assert(unloaded.error?.exitCode === 1 && unloaded.report?.status !== 'passed' && /loading boom/.test(unloaded.error.message), `A spec that throws while loading must fail: ${unloaded.error}\n${JSON.stringify(unloaded.report)}`); + // A time limit and Ctrl+C end a run that does not return, remove the frame and report it. + const hangingToken = crypto.randomUUID(); + await writeFile('tests/hang.spec.js', `describe('hanging', () => {\n it('never ends', () => {\n` + + ` parent.postMessage({hangingSpec: ${JSON.stringify(hangingToken)}}, location.origin);\n` + + " return new Promise(() => {});\n }, 600000);\n});\n"); + await specsOf(['tests/hang.spec.js']); + const hangingStarted = () => { + let receive; + const ready = new Promise(resolve => { + receive = event => { + const frame = document.querySelector('iframe[title="WebFront tests"]'); + if (event.origin === location.origin && event.source === frame?.contentWindow && event.data?.hangingSpec === hangingToken) + resolve(); + }; + window.addEventListener('message', receive); + }); + return {ready, dispose: () => window.removeEventListener('message', receive)}; + }; + // Wait for the spec itself: removing a merely inserted frame can interrupt its navigation instead of its run. + await withTimers([60000], async clock => { + const started = hangingStarted(); + try { + const hanging = tested(['--timeout', '60']); + await untilReady(started.ready, hanging); + assert(clock.pending() === 1, 'Only the frame deadline must remain after preparation'); + clock.fire(60000); + const hung = await hanging; + assert(hung.error?.exitCode === 124 && hung.report?.status === 'timeout' && /time limit/.test(hung.error.message), `A hanging run must stop at its time limit: ${hung.error}`); + assert(!document.querySelector('iframe[title="WebFront tests"]'), 'A timed out run must remove its frame'); + } finally { started.dispose(); } + }); + const stopTests = new AbortController(); + const started = hangingStarted(); + try { + const interrupted = tested([], {signal: stopTests.signal}); + await untilReady(started.ready, interrupted); + stopTests.abort(new Error('Interrupted')); + const interruptedRun = await interrupted; + assert(interruptedRun.error?.exitCode === 130 && interruptedRun.report?.status === 'interrupted' && !document.querySelector('iframe[title="WebFront tests"]'), `Ctrl+C must stop a run: ${interruptedRun.error}`); + } finally { started.dispose(); } + // The command must stop even when the bridge read never settles. Wait for the read, not wall time. + const blockedRead = () => { + let started; + const ready = new Promise(resolve => { started = resolve; }); + const bridge = {socket: webFront.socket, cppFunction: name => name === 'webfront.developer.read' ? + () => { started(); return new Promise(() => {}); } : webFront.cppFunction(name)}; + return {bridge, ready}; + }; + await specsOf(['tests/pass.spec.js']); + await withTimers([60000], async clock => { + const blocked = blockedRead(); + const running = tested(['--timeout', '60'], {bridge: blocked.bridge}); + await untilReady(blocked.ready, running); + clock.fire(60000); + const result = await running; + assert(result.error?.exitCode === 124 && result.report?.status === 'timeout', `A blocked bridge must report the preparation timeout: ${result.error}`); + }); + const blocked = blockedRead(); + const interruptPreparing = new AbortController(); + const preparingRun = tested([], {bridge: blocked.bridge, signal: interruptPreparing.signal}); + await untilReady(blocked.ready, preparingRun); + interruptPreparing.abort(new Error('Interrupted')); + const preparingResult = await preparingRun; + assert(preparingResult.error?.exitCode === 130 && preparingResult.report?.status === 'interrupted', `Ctrl+C during preparation must end with 130 and a report: ${preparingResult.error}`); + // macOS 13.3 supports WKWebView, but its WebKit need not provide AbortSignal.any (Safari 17.4). + const signalAny = Object.getOwnPropertyDescriptor(AbortSignal, 'any'); + Object.defineProperty(AbortSignal, 'any', {configurable: true, value: undefined}); + try { + const legacyPassing = await tested([], {signal: new AbortController().signal}); + assert(legacyPassing.report?.status === 'passed' && legacyPassing.report.exitCode === 0, + `A terminal run must work without AbortSignal.any: ${legacyPassing.error}`); + const alreadyStopped = new AbortController(); + alreadyStopped.abort(new Error('Interrupted')); + const legacyStopped = await tested([], {signal: alreadyStopped.signal}); + assert(legacyStopped.error?.exitCode === 130 && legacyStopped.report?.status === 'interrupted', + `An already aborted signal must report interruption without AbortSignal.any: ${legacyStopped.error}`); + await withTimers([60000], async clock => { + const blocked = blockedRead(); + const running = tested(['--timeout', '60'], {bridge: blocked.bridge, signal: new AbortController().signal}); + await untilReady(blocked.ready, running); + clock.fire(60000); + const result = await running; + assert(result.error?.exitCode === 124 && result.report?.status === 'timeout', + `The preparation deadline must report timeout without AbortSignal.any: ${result.error}`); + }); + const legacyStop = new AbortController(); + const blocked = blockedRead(); + const legacyPreparing = tested([], {bridge: blocked.bridge, signal: legacyStop.signal}); + await untilReady(blocked.ready, legacyPreparing); + legacyStop.abort(new Error('Interrupted')); + const legacyInterrupted = await legacyPreparing; + assert(legacyInterrupted.error?.exitCode === 130 && legacyInterrupted.report?.status === 'interrupted', + `Ctrl+C during preparation must report interruption without AbortSignal.any: ${legacyInterrupted.error}`); + } finally { + if (signalAny) Object.defineProperty(AbortSignal, 'any', signalAny); + else delete AbortSignal.any; + } + const withScript = await readManifest(); + await writeFile('webfront.project.json', JSON.stringify({...withScript, scripts: {...withScript.scripts, specs: 'wf test --timeout 120'}}, null, 2)); + await withTimers([60000], async clock => { + let started; + const ready = new Promise(resolve => { started = resolve; }); + let reads = 0; + const bridge = {socket: webFront.socket, cppFunction: name => name === 'webfront.developer.read' ? + (...args) => { + // The first manifest/lock pair belongs to wf run; block preparation of its nested wf test. + if (++reads > 2) { started(); return new Promise(() => {}); } + return webFront.cppFunction(name)(...args); + } : webFront.cppFunction(name)}; + const running = runtime.execute(['run', '--timeout', '60', 'specs'], {...runContext(), bridge, onReport: () => {}}).then(() => null, error => error); + await untilReady(ready, running); + clock.fire(60000); + const inherited = await running; + assert(inherited?.exitCode === 124, `wf test must keep the deadline of the script that runs it: ${inherited}`); + }); + // Each run publishes its own directory, emptied at the end: runs of two sessions never share files. + const runDirectories = JSON.parse(new TextDecoder().decode(await call('list', '.webfront/developer/test'))); + assert(runDirectories.length > 1 && runDirectories.every(name => /^[0-9a-f-]{36}\/?$/.test(name)), `Each run must have its own directory: ${runDirectories}`); + for (const name of runDirectories) assert(JSON.parse(new TextDecoder().decode(await call('list', `.webfront/developer/test/${name.replace(/\/$/, '')}`))).length === 0, `The files of a finished run must be removed: ${name}`); + assert(/--timeout expects whole seconds/.test((await tested(['--timeout', '0'])).error?.message) && /Usage: wf test/.test((await tested(['a', 'b'])).error?.message), 'wf test must check its options'); + // Without a terminal: the result reaches C++ through the bridge and the session ends with the command's status. + await specsOf(['tests/pass.spec.js', 'tests/fail.spec.ts']); + const exits = []; + const sent = await runtime.runNonInteractive(['test'], {...runContext(), reporter: json => webFront.cppFunction('test.result')(json), onExit: code => exits.push(code)}); + const received = JSON.parse(await webFront.cppFunction('test.lastResult')()); + assert(sent.exitCode === 1 && exits.length === 1 && exits[0] === 1 && received.exitCode === 1 && received.report?.failed === 1 && received.report.total === 4 && + received.report.failures[0].name === 'failing fails with a message' && received.output.includes('FAILED: 4 specs, 1 failure'), `A non-interactive failure must reach C++ and end the session with 1: ${JSON.stringify(received)}`); + await specsOf(['tests/pass.spec.js']); + await runtime.runNonInteractive(['test'], {...runContext(), reporter: json => webFront.cppFunction('test.result')(json), onExit: code => exits.push(code)}); + const success = JSON.parse(await webFront.cppFunction('test.lastResult')()); + assert(exits[1] === 0 && success.exitCode === 0 && success.report.status === 'passed', `A non-interactive success must end the session with 0: ${JSON.stringify(success)}`); + // A report too large for a bridge string is cut, not lost: C++ still receives the counts and the exit status. + await writeFile('tests/big.spec.js', "describe('big', () => {\n for (let index = 0; index < 4; ++index) it('fails with a long message ' + index, () => { throw new Error('x'.repeat(10000)); });\n});\n"); + await specsOf(['tests/big.spec.js']); + await runtime.runNonInteractive(['test'], {...runContext(), reporter: json => webFront.cppFunction('test.result')(json), onExit: code => exits.push(code)}); + const cut = JSON.parse(await webFront.cppFunction('test.lastResult')()); + assert(exits[2] === 1 && cut.exitCode === 1 && cut.truncated === true && cut.report?.failed === 4 && cut.report.total === 4 && cut.report.failures.length === 4, + `An oversized result must be cut to cross the bridge: ${JSON.stringify(cut).slice(0, 300)}`); + exits.splice(2, 1); + await runtime.runNonInteractive(['test', '--timeout', 'x'], {...runContext(), reporter: () => { throw new Error('bridge down'); }, onExit: code => exits.push(code)}); + assert(exits[2] === 1, 'A command that fails and a result that cannot be sent must both end non-zero'); + await runtime.runNonInteractive(['list'], {...runContext(), reporter: () => { throw new Error('bridge down'); }, onExit: code => exits.push(code)}); + assert(exits[3] === 1, 'A result that cannot be sent must not end the session with 0'); + // The terminal: the application's C++ commands, run in this browser's session. + assert(JSON.stringify([...runtime.builtinNames].sort()) === JSON.stringify([...runtime.reservedNames].sort()), + `The terminal's own commands must be the names reserved to it: ${runtime.builtinNames}`); + const cppCommands = await runtime.discoverCommands(webFront); + assert(['echo', 'fail', 'linger', 'status', 'stream', 'wait'].every(name => cppCommands.has(name)) && cppCommands.get('echo') === 'Write its arguments', + `The C++ commands must be discovered with their help: ${[...cppCommands.keys()]}`); + const commandState = tag => webFront.cppFunction('test.command')(tag); + const waitState = async (tag, state) => { + for (let attempt = 0; (await commandState(tag)) !== state; ++attempt) { + if (attempt === 200) throw new Error(`Command ${tag} did not reach ${state}: ${await commandState(tag)}`); + await delay(25); + } + }; + const lineContext = (signal = new AbortController().signal, chunks = []) => ({...context, cppCommands, signal, write: text => chunks.push(text)}); + const streamed = []; + assert(await runtime.runLine('stream', lineContext(undefined, streamed)) === '', 'A C++ command resolves once it returns'); + assert(streamed.length >= 3 && streamed.join('') === 'é'.repeat(75000) + '\r\n', `Long C++ output must stream in pieces under the bridge limit: ${streamed.length}`); + const crlf = []; + await runtime.runLine('crlf', lineContext(undefined, crlf)); + assert(crlf.join('') === 'one\r\ntwo\r\n', `A CRLF split between two writes must stay one line break: ${JSON.stringify(crlf.join(''))}`); + const thrown = await failure(runtime.runLine('fail', lineContext())); + assert(thrown?.message === 'command failed on purpose' && thrown.exitCode === 1, `A C++ exception must reject the command: ${thrown}`); + const exitCode = await failure(runtime.runLine('status 3', lineContext())); + assert(exitCode?.exitCode === 3 && /exited with code 3/.test(exitCode.message), `A C++ exit code must be reported: ${exitCode}`); + assert(/Unknown command: absent/.test((await failure(runtime.runLine('absent', lineContext())))?.message), 'An unknown command must be refused'); + // Ctrl+C: the terminal stops waiting at once, the next command answers while the first is still ending in C++. + const interruptLinger = new AbortController(); + const lingering = failure(runtime.runLine('linger first', lineContext(interruptLinger.signal))); + await waitState('first', 'running'); + interruptLinger.abort(new Error('Interrupted')); + assert((await lingering)?.exitCode === 130, 'An interrupted C++ command must end with exit code 130'); + const echoed = []; + await runtime.runLine('echo "after Ctrl+C"', lineContext(undefined, echoed)); + assert(echoed.join('') === 'after Ctrl+C\r\n', `The next command must run normally: ${echoed}`); + assert(['running', 'stopping'].includes(await commandState('first')), 'The second command must answer before the first one ends'); + await waitState('first', 'stopping'); + await webFront.cppFunction('test.release')('first'); + await waitState('first', 'cancelled'); + // Sessions: a second browser has its own commands; a long command there does not delay this one, Ctrl+C here does + // not stop it, and its disconnection does. + const sessionFrame = document.createElement('iframe'); + sessionFrame.src = '/fixtures/session.html'; + document.body.append(sessionFrame); + for (let attempt = 0; !sessionFrame.contentWindow?.session; ++attempt) { + if (attempt === 200) throw new Error('The second session did not load'); + await delay(25); + } + const second = await sessionFrame.contentWindow.session; + const secondWait = failure(second.runtime.runLine('wait second', {bridge: second.bridge, cppCommands: second.cppCommands, signal: new AbortController().signal})); + await waitState('second', 'running'); + const interruptFirst = new AbortController(); + const firstWait = failure(runtime.runLine('wait here', lineContext(interruptFirst.signal))); + await waitState('here', 'running'); + const echoStarted = performance.now(); + await runtime.runLine('echo isolated', lineContext()); + assert(performance.now() - echoStarted < 2000, 'A command in another session must not delay this one'); + interruptFirst.abort(new Error('Interrupted')); + await firstWait; + await waitState('here', 'cancelled'); + assert(await commandState('second') === 'running', 'Ctrl+C in one browser must not stop the command of another'); + const browsers = await webFront.cppFunction('test.browsers')(); + // Its connection closes while its acknowledged command runs: the terminal stops waiting for an exit that cannot come. + second.bridge.socket.close(); + const lost = await secondWait; + assert(lost?.exitCode === 1 && /connection to the application closed/.test(lost.message), + `A command of a closed connection must reject: ${lost?.message}`); + await waitState('second', 'cancelled'); + for (let attempt = 0; await webFront.cppFunction('test.browsers')() !== browsers - 1; ++attempt) + if (attempt === 200) throw new Error('The connection of a closed browser must be released'); + else await delay(25); + sessionFrame.remove(); + // The terminal itself, mounted in this page with a real xterm.js. + const host = document.createElement('div'); + host.style.cssText = 'width:640px;height:240px'; + document.body.append(host); + let exitedWith = null; + // The test sets the terminal's size itself: an observer following the element would race with it. + const mounted = async () => runtime.mount({bridge: webFront, config, terminal: host, preview: context.preview, onExit: code => { exitedWith = code; }, fitToElement: false}); + const {terminal, editor} = await mounted(); + terminal.resize(80, 12); + const buffer = () => terminal.buffer.active; + const rendered = () => new Promise(resolve => terminal.write('', resolve)); + // Like xterm.js, one input per key; text may come as one input. + const type = async (...inputs) => { + for (const data of inputs) { + terminal.input(data); + await editor.whenIdle(); + } + await rendered(); + }; + const rows = () => { + const lines = []; + for (let y = 0; y < buffer().length; ++y) lines.push(buffer().getLine(y).translateToString(true)); + return lines; + }; + const cursorRow = () => buffer().baseY + buffer().cursorY; + const lastRows = count => rows().slice(cursorRow() - count + 1, cursorRow() + 1); + await type('echo hello\r'); + assert(JSON.stringify(lastRows(3)) === JSON.stringify(['> echo hello', 'hello', '> ']), `A C++ command must run from the terminal: ${lastRows(3)}`); + // Cell widths: CJK, emoji, a flag, a ZWJ sequence and a combining mark. + await type('漢字😀🇫🇷👨‍👩‍👧éx'); + assert(buffer().cursorX === 2 + 2 + 2 + 2 + 2 + 2 + 1 + 1, `Wide characters must take two cells: ${buffer().cursorX}`); + // xterm.js draws each cluster where the editor placed it. + const drawn = buffer().getLine(cursorRow()); + const cellsDrawn = [[2, '漢', 2], [4, '字', 2], [6, '😀', 2], [8, '🇫🇷', 2], [10, '👨‍👩‍👧', 2], [12, 'e\u0301', 1], [13, 'x', 1]] + .map(([column, chars, width]) => [drawn.getCell(column).getChars() === chars, drawn.getCell(column).getWidth() === width]).flat(); + assert(cellsDrawn.every(Boolean), `xterm.js must draw the clusters with the editor's widths: ${cellsDrawn}`); + await type('\x7f', '\x7f'); + assert(buffer().cursorX === 12 && editor.line === '漢字😀🇫🇷👨‍👩‍👧', `Backspace must erase whole clusters: ${buffer().cursorX} ${editor.line}`); + await type('\x1b[D', '\x1b[D'); + assert(buffer().cursorX === 8, `The cursor must move over whole clusters: ${buffer().cursorX}`); + await type('\x03'); + assert(lastRows(2)[0].endsWith('^C') && lastRows(1)[0] === '> ' && editor.line === '', 'Ctrl+C must drop the line'); + // A line over several rows: wrapping, editing in the middle, a row filled exactly and a wide character at a row end. + terminal.resize(20, 12); + await rendered(); + assert(terminal.cols === 20, `The terminal must keep the width the test gives it: ${terminal.cols}`); + await type('echo ' + 'a'.repeat(40)); + let top = cursorRow() - 2; + assert(buffer().cursorX === 7 && JSON.stringify(rows().slice(top, top + 3)) === JSON.stringify(['> echo ' + 'a'.repeat(13), 'a'.repeat(20), 'a'.repeat(7)]), + `A long line must wrap: ${rows().slice(top, top + 3)}`); + await type('\x01', 'X'); + assert(cursorRow() === top && buffer().cursorX === 3 && JSON.stringify(rows().slice(top, top + 3)) === JSON.stringify(['> Xecho ' + 'a'.repeat(12), 'a'.repeat(20), 'a'.repeat(8)]), + `Editing the start of a long line must redraw its rows: ${rows().slice(top, top + 3)}`); + await type('\x05', 'b'.repeat(12)); + assert(cursorRow() === top + 3 && buffer().cursorX === 0, `A line filling its last row exactly must leave the cursor on the next row: ${cursorRow() - top} ${buffer().cursorX}`); + await type('\x7f', '漢'); + assert(cursorRow() === top + 3 && buffer().cursorX === 2 && rows()[top + 2] === 'a'.repeat(8) + 'b'.repeat(11) && rows()[top + 3] === '漢', + `A wide character must not split at a row end: ${buffer().cursorX} ${rows().slice(top + 2, top + 4)}`); + await type('\x15'); + assert(cursorRow() === top && buffer().cursorX === 2 && rows()[top + 1] === '', 'Erasing a long line must clear its rows'); + terminal.resize(80, 12); + await rendered(); + // Exit codes, errors and clear. + await type('status 3\r'); + assert(editor.status === 3 && lastRows(2)[0] === 'Error: Command status exited with code 3', `An exit code must be shown: ${lastRows(2)}`); + await type('fail\r'); + assert(editor.status === 1 && lastRows(2)[0] === 'Error: command failed on purpose', `A C++ exception must be shown as an error: ${lastRows(2)}`); + await type('partial\r', 'x'); + assert(JSON.stringify(lastRows(2)) === JSON.stringify(['partial', '> x']), `Output without a final line break must not hold the prompt: ${lastRows(2)}`); + await type('\x03'); + // Keys typed while a completion is pending are applied after it, Enter included. + terminal.input('ec'); + terminal.input('\t'); + terminal.input('ho'); + terminal.input(' typed-ahead\r'); + for (let attempt = 0; editor.busy || lastRows(2)[0] !== 'ho typed-ahead'; ++attempt) { + if (attempt === 200) throw new Error(`Keys typed during a completion must be kept: ${lastRows(3)}`); + await editor.whenIdle(); + await rendered(); + await delay(10); + } + assert(lastRows(3)[0] === '> echo ho typed-ahead' && editor.ahead.length === 0, `The completed line must run once: ${lastRows(3)}`); + await type('echo ok\r'); + assert(editor.status === 0, 'A successful command must reset the status'); + // Ctrl+C in the terminal: the prompt comes back at once, and a command typed then runs while the first one ends. + terminal.input('linger terminal\r'); + await waitState('terminal', 'running'); + await type('\x03'); + await type('echo next\r'); + const lingerState = await commandState('terminal'); + assert(editor.status === 0 && lastRows(2)[0] === 'next' && ['running', 'stopping'].includes(lingerState), `Ctrl+C must interrupt a C++ command: ${lastRows(3)} ${editor.status} ${lingerState}`); + await waitState('terminal', 'stopping'); + await webFront.cppFunction('test.release')('terminal'); + // Pasted lines run one after the other; the last one, without a line break, waits on the prompt. + // Keys typed one by one while a command runs are applied after it, Enter included. + terminal.input('sleep 300\r'); + for (const key of [...'echo ahead', '\r']) terminal.input(key); + await editor.whenIdle(); + await rendered(); + assert(JSON.stringify(lastRows(4)) === JSON.stringify(['> sleep 300', '> echo ahead', 'ahead', '> ']), `Keys typed during a command must be kept: ${lastRows(4)}`); + terminal.paste('echo one\necho two\necho three'); + await editor.whenIdle(); + await rendered(); + assert(JSON.stringify(lastRows(5)) === JSON.stringify(['> echo one', 'one', '> echo two', 'two', '> echo three']), `A multi-line paste must run line by line: ${lastRows(5)}`); + await type('\r'); + assert(lastRows(2)[0] === 'three', 'The pasted last line must run once submitted'); + // Completion of command names, wf subcommands, manifest scripts and project paths. + const completed = async (text, expected) => { + await type(text, '\t'); + assert(editor.line === expected, `${JSON.stringify(text)} must complete to ${JSON.stringify(expected)}: ${JSON.stringify(editor.line)}`); + await type('\x03'); + }; + await completed('ec', 'echo '); + await completed('wf ru', 'wf run '); + await completed('wf run ge', 'wf run gen '); + await completed('echo too', 'echo tools/'); + await completed('echo tools/js', 'echo tools/jsx.tsx '); + await completed('hi', 'history '); + await completed('echo /to', 'echo /to'); // project paths are relative: an absolute one is not completed + // Paths with spaces and quotes: the completion reads the escaped or quoted word and extends it the same way. + await writeFile("my dir/file one's.txt", 'x'); + await completed('echo my\\ d', 'echo my\\ dir/'); + await completed('echo my\\ dir/f', "echo my\\ dir/file\\ one\\'s.txt "); + await completed('echo "my d', 'echo "my dir/'); + await completed('echo "my dir/f', `echo "my dir/file one's.txt" `); + // A single quote cannot be written between single quotes: nothing is inserted. + await completed("echo 'my dir/f", "echo 'my dir/f"); + await type('h', '\t'); + assert(editor.line === 'h' && lastRows(2)[0].includes('help') && lastRows(2)[0].includes('history'), `Several candidates must be listed: ${lastRows(2)}`); + await type('\x03'); + await type('clear\r'); + assert(buffer().length === terminal.rows && rows()[0] === '> ', `clear must empty the screen and the scrollback: ${rows()[0]}`); + // A line taller than the screen is drawn a screen at a time around the cursor, never duplicated on it. + terminal.resize(20, 4); + await rendered(); + const digits = '0123456789'.repeat(10).slice(0, 95); + const tall = '> echo ' + digits; + const layoutRow = index => tall.slice(20 * index, 20 * index + 20); + const screen = () => rows().slice(buffer().baseY, buffer().baseY + terminal.rows); + const shows = (first, cursorY, cursorX, message) => { + const expected = [0, 1, 2, 3].map(index => layoutRow(first + index)); + assert(JSON.stringify(screen()) === JSON.stringify(expected) && buffer().cursorY === cursorY && buffer().cursorX === cursorX, + `${message}: ${JSON.stringify(screen())} at ${buffer().cursorY},${buffer().cursorX}`); + }; + await type('echo ' + digits); + shows(2, 3, 2, 'The end of a tall line must be on screen'); + await type('\x01'); + shows(0, 0, 2, 'Home must show the start of a tall line, once'); + await type('\x05'); + shows(2, 3, 2, 'End must show the end of a tall line again'); + await type('\r'); + assert(lastRows(2)[0] === digits.slice(80) && lastRows(1)[0] === '> ', `A tall line must run: ${screen()}`); + terminal.resize(80, 12); + await type('clear\r'); + // Enter and Ctrl+C typed while a completion is pending: the command starts, then is interrupted at once. + terminal.input('lin'); + terminal.input('\t'); + terminal.input('replay'); + terminal.input('\r'); + terminal.input('\x03'); + await waitState('replay', 'stopping'); + await webFront.cppFunction('test.release')('replay'); + for (let attempt = 0; editor.busy; ++attempt) { + if (attempt === 100) throw new Error(`Ctrl+C typed during a completion must interrupt the replayed command: ${lastRows(3)}`); + await delay(20); + } + assert(editor.status === 130 && lastRows(3)[0] === '> linger replay', `The replayed command must be interrupted: ${lastRows(3)} ${editor.status}`); + // The history is kept per project: a new terminal recalls it. + await runtime.historySaved(); + const saved = JSON.parse(new TextDecoder().decode(await readFile(runtime.historyPath))); + assert(saved.at(-1) === 'linger replay' && saved.includes('clear') && saved.includes('echo three'), `The history must be saved in the project: ${saved.slice(-3)}`); + await type('exit 4\r'); + assert(exitedWith === 4 && editor.closed && lastRows(2)[0] === 'Session ended. Press Enter to start a new session.', `exit must end the session with its code: ${exitedWith}`); + await type('echo ignored'); + assert(!editor.busy && editor.line === '', 'A closed session must ignore input'); + // The window stays open when the browser refuses to close it: Enter starts a new session. + await type('\r'); + assert(!editor.closed && editor.status === 0 && lastRows(1)[0] === '> ', `Enter must start a new session after exit: ${lastRows(2)}`); + await runtime.historySaved(); + terminal.dispose(); + host.replaceChildren(); + const again = await mounted(); + again.terminal.input('\x1b[A'); + await new Promise(resolve => again.terminal.write('', resolve)); + assert(again.editor.line === 'exit 4', `A new terminal must recall the project's history: ${again.editor.line}`); + again.terminal.input('\x03'); + // Two terminals on the same project: each one adds its lines to the history, neither erases the other's. + const otherHost = document.createElement('div'); + otherHost.style.cssText = 'width:640px;height:240px'; + document.body.append(otherHost); + const other = await runtime.mount({bridge: webFront, config, terminal: otherHost, preview: context.preview, onExit: () => {}}); + for (const [session, line] of [[again, 'echo from-first'], [other, 'echo from-second'], [again, 'echo first-again']]) { + session.terminal.input(line + '\r'); + await session.editor.whenIdle(); + } + await runtime.historySaved(); + const shared = JSON.parse(new TextDecoder().decode(await readFile(runtime.historyPath))); + assert(JSON.stringify(shared.slice(-3)) === JSON.stringify(['echo from-first', 'echo from-second', 'echo first-again']), + `Terminals must not erase each other's history: ${shared.slice(-4)}`); + other.terminal.dispose(); + otherHost.remove(); + // Two pages, each with its own runtime module, write their histories at the same time: no line is lost. + const historyFrame = document.createElement('iframe'); + historyFrame.src = '/fixtures/session.html'; + document.body.append(historyFrame); + for (let attempt = 0; !historyFrame.contentWindow?.session; ++attempt) { + if (attempt === 200) throw new Error('The second page did not load'); + await delay(25); + } + const page = await historyFrame.contentWindow.session; + const pageTerminal = await page.runtime.mount({bridge: page.bridge, config, terminal: historyFrame.contentDocument.getElementById('terminal'), + preview: context.preview, onExit: () => {}, fitToElement: false}); + const lines = page => [1, 2, 3, 4, 5].map(index => `echo ${page}${index}`); + again.terminal.paste(lines('here').join('\n') + '\n'); + pageTerminal.terminal.paste(lines('there').join('\n') + '\n'); + await Promise.all([again.editor.whenIdle(), pageTerminal.editor.whenIdle()]); + await Promise.all([runtime.historySaved(), page.runtime.historySaved()]); + const merged = JSON.parse(new TextDecoder().decode(await readFile(runtime.historyPath))); + const missing = [...lines('here'), ...lines('there')].filter(line => !merged.includes(line)); + assert(missing.length === 0, `Concurrent pages must keep every history line: ${missing}`); + // A history that cannot be read is never replaced by the lines of one terminal. + await writeFile(runtime.historyPath, '{broken'); + again.terminal.input('echo kept\r'); + await again.editor.whenIdle(); + await runtime.historySaved(); + assert(new TextDecoder().decode(await readFile(runtime.historyPath)) === '{broken', 'A malformed history must be left unchanged'); + pageTerminal.terminal.dispose(); + historyFrame.remove(); + again.terminal.dispose(); + host.remove(); + // The application stops while this command runs: its shutdown must drain it (checked in C++). + void failure(runtime.runLine('wait final', lineContext())); + await waitState('final', 'running'); + await webFront.cppFunction('test.report')(true, 'WASM + npm + TSX + Life animation + deterministic headers + scripts + type check + terminal passed'); +} catch (error) { + if (error instanceof PublicSmokeDone) + await webFront.cppFunction('test.report')(true, 'Public distribution: WASM + npm + TSX + Life animation + deterministic headers passed'); + else { + console.error(error); + await webFront.cppFunction('test.report')(false, `${error.message ?? error}\n${error.stack ?? ''}`); + } +} finally { + setTimeout(() => globalThis.close(), 0); +} diff --git a/webtest/encoded path #.html b/test/web/encoded path #.html similarity index 100% rename from webtest/encoded path #.html rename to test/web/encoded path #.html diff --git a/webtest/no-bridge.html b/test/web/no-bridge.html similarity index 100% rename from webtest/no-bridge.html rename to test/web/no-bridge.html diff --git a/webtest/policy-controls.html b/test/web/policy-controls.html similarity index 100% rename from webtest/policy-controls.html rename to test/web/policy-controls.html diff --git a/webtest/policy-escaped.html b/test/web/policy-escaped.html similarity index 100% rename from webtest/policy-escaped.html rename to test/web/policy-escaped.html diff --git a/test/web/registry-packages.json b/test/web/registry-packages.json new file mode 100644 index 00000000..6af7a2e3 --- /dev/null +++ b/test/web/registry-packages.json @@ -0,0 +1,89 @@ +{ + "comment": "The real packages of the local npm registry of the tests: downloaded at configure time, verified against their integrity, never committed.", + "packages": [ + { + "name": "@types/react", + "version": "19.3.0", + "url": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==" + }, + { + "name": "@types/react-dom", + "version": "19.3.0", + "url": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==" + }, + { + "name": "@xterm/addon-fit", + "version": "0.11.0", + "url": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz", + "integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==" + }, + { + "name": "@xterm/xterm", + "version": "6.0.0", + "url": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.0.0.tgz", + "integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==" + }, + { + "name": "csstype", + "version": "3.2.3", + "url": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==" + }, + { + "name": "esbuild-wasm", + "version": "0.28.2", + "url": "https://registry.npmjs.org/esbuild-wasm/-/esbuild-wasm-0.28.2.tgz", + "integrity": "sha512-GccVwhv3mmOUVQHCQm2Ox/rby8n/EqUwvZxE6Pjfikrq/lWw9g9WX/u9EykWnpot3Ko6j426DgQdea2xWKIAQA==" + }, + { + "name": "fflate", + "version": "0.8.3", + "url": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==" + }, + { + "name": "jasmine-core", + "version": "7.0.2", + "url": "https://registry.npmjs.org/jasmine-core/-/jasmine-core-7.0.2.tgz", + "integrity": "sha512-YMVijt84KPQQFm1db1AQAxTXfq0k3wU06OkepLViljURFqiRQ7EYYX2eUAshhUv9fA9t1E2N65GrdqvupA9VPQ==" + }, + { + "name": "react", + "version": "19.3.1", + "url": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==" + }, + { + "name": "react-dom", + "version": "19.3.1", + "url": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==" + }, + { + "name": "scheduler", + "version": "0.28.0", + "url": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==" + }, + { + "name": "semver", + "version": "7.7.3", + "url": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==" + }, + { + "name": "typescript", + "version": "5.9.3", + "url": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==" + }, + { + "name": "typescript", + "version": "6.0.3", + "url": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==" + } + ] +} diff --git a/test/web/registry/build.mjs b/test/web/registry/build.mjs new file mode 100644 index 00000000..90a19349 --- /dev/null +++ b/test/web/registry/build.mjs @@ -0,0 +1,21 @@ +// Builds the local npm registry of the tests with wf: +// +// wf run test-registry +// +// The real packages are the verified archives of registry-archives/ (downloaded at configure time from +// test/web/registry-packages.json), kept byte for byte; the synthetic ones are generated. The registry's files go to +// build-registry/, next to an integrities.json of every package. +import {realPackage, syntheticPackages, registryFiles} from './fixture.mjs'; + +export default async function (context) { + if (context.args.length) throw new Error('Usage: wf run test-registry'); + const {project} = context; + const archives = (await project.list('registry-archives')).filter(name => name.endsWith('.tgz')); + if (!archives.length) throw new Error('registry-archives holds no archive'); + const packages = []; + for (const name of archives) packages.push(await realPackage(await project.read(`registry-archives/${name}`))); + const {files, integrities} = await registryFiles([...packages, ...syntheticPackages()]); + for (const [name, bytes] of files) await project.write(`build-registry/${name}`, bytes); + await project.write('build-registry/integrities.json', JSON.stringify(integrities, null, 2) + '\n'); + context.console.log(`Registry: ${files.size} files, ${Object.keys(integrities).length} packages`); +} diff --git a/test/web/registry/fixture.mjs b/test/web/registry/fixture.mjs new file mode 100644 index 00000000..7d4cbdce --- /dev/null +++ b/test/web/registry/fixture.mjs @@ -0,0 +1,132 @@ +// The local npm registry of the tests: packuments and tarballs as plain files, generated reproducibly from the pinned real +// archives (test/web/registry-packages.json, downloaded and verified at configure time) and from synthetic packages for +// the edge cases. The test application serves the directory from its own origin, so no test reaches the public registry. +// Everything here uses only browser APIs: build.mjs runs it with wf. +import {tar} from '../../../js/developer/tools/archive.mjs'; +import {gunzip, readTar} from '../../../js/developer/environment/tarball.mjs'; + +const encoder = new TextEncoder(); +async function integrity(bytes) { + const digest = new Uint8Array(await crypto.subtle.digest('SHA-512', bytes)); + return 'sha512-' + btoa(String.fromCharCode(...digest)); +} +const decoder = new TextDecoder(); + +// The fixture builds the registry that provides fflate, so it cannot depend on it: a gzip stream of stored blocks is +// deterministic and needs no compressor. +const crcTable = Uint32Array.from({length: 256}, (_, n) => { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + return c >>> 0; +}); +function storedGzip(bytes) { + const blocks = Math.max(1, Math.ceil(bytes.length / 0xffff)); + const out = new Uint8Array(10 + bytes.length + 5 * blocks + 8); + const view = new DataView(out.buffer); + out.set([0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 255]); + let at = 10; + for (let block = 0; block < blocks; block++) { + const chunk = bytes.subarray(block * 0xffff, (block + 1) * 0xffff); + out[at++] = block === blocks - 1 ? 1 : 0; + view.setUint16(at, chunk.length, true); + view.setUint16(at + 2, ~chunk.length & 0xffff, true); + out.set(chunk, at + 4); + at += 4 + chunk.length; + } + let crc = 0xffffffff; + for (const byte of bytes) crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8); + view.setUint32(at, (crc ^ 0xffffffff) >>> 0, true); + view.setUint32(at + 4, bytes.length >>> 0, true); + return out; +} +const archive = files => storedGzip(tar(new Map([...files].map(([path, bytes]) => [`package/${path}`, bytes])))); +// The fixture's versions are plain major.minor.patch numbers. +function compareVersions(a, b) { + const [x, y] = [a, b].map(version => version.split('.').map(Number)); + for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] - y[i]; + return 0; +} +const newest = versions => versions.toSorted(compareVersions).at(-1); + +/** A real archive, kept byte for byte: its manifest is the package.json inside it. */ +export async function realPackage(bytes) { + // The root is "package/" for npm, the package name for the archives of DefinitelyTyped. + const entry = readTar(await gunzip(bytes)).find(file => /^[^/]+\/package\.json$/.test(file.path)); + if (!entry) throw new Error('An archive of the registry has no /package.json'); + return {manifest: JSON.parse(decoder.decode(entry.bytes)), bytes}; +} + +function synthetic(name, version, fields = {}, extra = {}) { + const manifest = {name, version, type: 'module', main: 'index.js', ...fields}; + return {manifest, files: new Map([ + ['package.json', encoder.encode(JSON.stringify(manifest, null, 2) + '\n')], + ['index.js', encoder.encode(`export default ${JSON.stringify(`${name}@${version}`)};\n`)], + ...Object.entries(extra).map(([path, text]) => [path, encoder.encode(text)]), + ])}; +} + +// A WebFront executable entry for wf exec: it writes its arguments and its dependency's identity. +const toolEntry = `import lib from 'webfront-fixture-lib'; +export default async function (context) { + await context.project.write('generated/script/tool.txt', [lib, ...context.args].join(' ')); +} +`; + +// Packages typed for wf check: declarations from the "types" condition of "exports" (where esbuild would take the +// browser build) importing a dependency that is not a root, from "typings", and from @types only; and a typescript +// older than the versions wf check supports. +const typedPackages = () => [ + synthetic('webfront-fixture-typed', '1.0.0', {exports: {'.': {types: './index.d.ts', browser: './browser.js', import: './index.js'}}, + dependencies: {'webfront-fixture-shape': '^1.0.0'}}, { + 'index.d.ts': "import type {Shape} from 'webfront-fixture-shape';\nexport declare const answer: number;\nexport declare function area(shape: Shape): number;\n", + 'browser.js': 'export const answer = 42;\nexport const area = shape => shape.width * shape.height;\n'}), + synthetic('webfront-fixture-shape', '1.0.0', {types: 'shape.d.ts'}, {'shape.d.ts': 'export interface Shape { width: number; height: number }\n'}), + synthetic('webfront-fixture-legacy', '1.0.0', {typings: 'types/legacy.d.ts'}, {'types/legacy.d.ts': "export declare const legacy: 'yes';\n"}), + synthetic('webfront-fixture-untyped', '1.0.0'), + synthetic('@types/webfront-fixture-untyped', '1.0.0', {types: 'index.d.ts'}, {'index.d.ts': 'export declare function greet(name: string): string;\n'}), + synthetic('typescript', '4.9.5', {main: 'lib/typescript.js'}, {'lib/typescript.js': 'module.exports = {version: "4.9.5"};\n'}), +]; + +/** + * Edge cases: a dependency range under which a newer version than the locked one exists (a restore must not move + * to it), a published archive that no longer matches the integrity of its packument, a package with a WebFront + * executable entry and one with only an npm "bin". A package absent from the registry is simply not generated. + */ +export const syntheticPackages = () => [ + synthetic('webfront-fixture-app', '1.0.0', {dependencies: {'webfront-fixture-lib': '^1.0.0'}}), + synthetic('webfront-fixture-lib', '1.0.0'), + synthetic('webfront-fixture-lib', '1.1.0'), + {...synthetic('webfront-fixture-tampered', '1.0.0'), tampered: true}, + synthetic('webfront-fixture-tool', '1.0.0', {dependencies: {'webfront-fixture-lib': '^1.0.0'}, + webfront: {bin: {'webfront-fixture-tool': './bin/tool.mjs'}}}, {'bin/tool.mjs': toolEntry}), + synthetic('webfront-fixture-nodebin', '1.0.0', {bin: {'webfront-fixture-nodebin': 'cli.js'}}, {'cli.js': 'console.log(1);\n'}), + ...typedPackages(), +]; + +function byName(packages) { + const names = new Map(); + for (const pkg of packages) names.set(pkg.manifest.name, [...names.get(pkg.manifest.name) ?? [], pkg]); + return names; +} + +/** + * The registry's files: `` packuments (`@scope/` in a scope directory, which the client requests as + * `@scope%2f`) and `-.tgz` archives (`scope--.tgz`), and each package's integrity. + */ +export async function registryFiles(packages) { + const files = new Map(); + const integrities = {}; + for (const [name, versions] of byName(packages)) { + const described = {}; + for (const {manifest, files: contents, bytes: real, tampered} of versions) { + const file = `${name.replace(/^@/, '').replace('/', '-')}-${manifest.version}.tgz`; + const bytes = real ?? archive(contents); + files.set(file, tampered ? archive(new Map([...contents, ['TAMPERED', encoder.encode('changed')]])) : bytes); + integrities[`${name}@${manifest.version}`] = await integrity(bytes); + described[manifest.version] = {...manifest, dist: {tarball: `./${file}`, integrity: integrities[`${name}@${manifest.version}`]}}; + } + const packument = {name, 'dist-tags': {latest: newest(Object.keys(described))}, versions: described}; + files.set(name, encoder.encode(JSON.stringify(packument, null, 2) + '\n')); + } + return {files, integrities}; +} diff --git a/webtest/rejected-ready.html b/test/web/rejected-ready.html similarity index 100% rename from webtest/rejected-ready.html rename to test/web/rejected-ready.html diff --git a/webtest/slow-page.html b/test/web/slow-page.html similarity index 100% rename from webtest/slow-page.html rename to test/web/slow-page.html diff --git a/webtest/slow-resource.js b/test/web/slow-resource.js similarity index 100% rename from webtest/slow-resource.js rename to test/web/slow-resource.js diff --git a/test/web/suite/pages/a+b.html b/test/web/suite/pages/a+b.html new file mode 100644 index 00000000..5fa56801 --- /dev/null +++ b/test/web/suite/pages/a+b.html @@ -0,0 +1,3 @@ + + +Plus in a path diff --git a/webtest/js/origin-probe.mjs b/test/web/suite/pages/js/origin-probe.mjs similarity index 100% rename from webtest/js/origin-probe.mjs rename to test/web/suite/pages/js/origin-probe.mjs diff --git a/webtest/origin-probe.html b/test/web/suite/pages/origin-probe.html similarity index 100% rename from webtest/origin-probe.html rename to test/web/suite/pages/origin-probe.html diff --git a/webtest/js/content-policy-specs.mjs b/test/web/suite/specs/content-policy-specs.mjs similarity index 98% rename from webtest/js/content-policy-specs.mjs rename to test/web/suite/specs/content-policy-specs.mjs index 0ed71e7a..36b9124c 100644 --- a/webtest/js/content-policy-specs.mjs +++ b/test/web/suite/specs/content-policy-specs.mjs @@ -1,4 +1,4 @@ -import { watchOriginProbe } from './origin-probe.mjs'; +import { watchOriginProbe } from '../pages/js/origin-probe.mjs'; describe('Server bridge origin authorization', () => { const socketUrl = new URL('/', location.href); diff --git a/webtest/js/module-fixture.mjs b/test/web/suite/specs/module-fixture.mjs similarity index 100% rename from webtest/js/module-fixture.mjs rename to test/web/suite/specs/module-fixture.mjs diff --git a/webtest/js/webfront-specs.mjs b/test/web/suite/specs/webfront-specs.mjs similarity index 89% rename from webtest/js/webfront-specs.mjs rename to test/web/suite/specs/webfront-specs.mjs index 7bf355c4..39f7770b 100644 --- a/webtest/js/webfront-specs.mjs +++ b/test/web/suite/specs/webfront-specs.mjs @@ -1,30 +1,43 @@ import './content-policy-specs.mjs'; import { importedValue } from './module-fixture.mjs'; -import './terminal-specs.mjs'; -import './tools-specs.mjs'; -import './react-demo-specs.mjs'; +// The page of the application is covered by the lifecycle cases (path-encoding): these specs run in the frame of wf test. describe('Frontend page URL', () => { - it('opens a filename containing spaces and a literal hash', () => { - expect(decodeURIComponent(location.pathname)).toBe('/encoded path #.html'); - }); it('serves a filename containing a literal plus through the C++ URL builder', async () => { const url = await webFront.cppFunction('plusPageUrl')(); expect(new URL(url).pathname).toBe('/a%2Bb.html'); const response = await fetch(url); expect(response.ok).toBeTrue(); - expect(await response.text()).toContain('WebFront automated browser tests'); + expect(await response.text()).toContain('Plus in a path'); + }); + it('injects a C++ script when the handshake completes before the body exists', () => { + const body = document.body; + const text = new TextEncoder().encode('globalThis.earlyInjectedScript = true;'); + const packet = new DataView(new ArrayBuffer(4 + text.length)); + packet.setUint8(0, 2); // TextCommand + packet.setUint8(1, 1); // injectScript + packet.setUint16(2, text.length); + new Uint8Array(packet.buffer, 4).set(text); + try { + body.remove(); + expect(document.body).toBeNull(); + expect(() => webFront.handleTextCommand(packet)).not.toThrow(); + expect(globalThis.earlyInjectedScript).toBeTrue(); + } finally { + document.documentElement.append(body); + delete globalThis.earlyInjectedScript; + } }); - it('preserves the query and fragment passed by C++', () => { - expect(location.search).toBe('?webfront=1'); - expect(location.hash).toBe('#integration'); + it('runs in the frame of the test runner, served from the origin of the application', () => { expect(location.hostname).toBe('127.0.0.1'); + expect(window.parent).not.toBe(window); }); }); const cppToken = 'cpp-to-js-token'; const jsToken = 'js-to-cpp-token'; -const status = document.getElementById('bridge-status'); +const status = document.body.appendChild(document.createElement('p')); +status.textContent = 'Waiting for the C++/JavaScript bridge…'; const browserReadyTimeoutMs = 10000; @@ -123,11 +136,6 @@ globalThis.webfrontTests = { const result = `js-result:${value}`; resolveCppResult(result); return result; - }, - - close(passed) { - status.textContent = passed ? 'Bridge integration passed' : 'Bridge integration failed'; - setTimeout(() => globalThis.close(), 0); } }; @@ -291,15 +299,7 @@ describe('WebFront browser integration', () => { }); }); -jasmine.getEnv().addReporter({ - failures: [], - specDone(result) { - for (const failure of result.failedExpectations) - this.failures.push(`${result.fullName}: ${failure.message}`); - }, - async jasmineDone(result) { - await webFront.cppFunction('reportJasmine')(result.overallStatus, this.failures.join('\n')); - } -}); +// C++ also checks what it observed: it is told over this connection, after every call the specs sent. +afterAll(async () => { await webFront.cppFunction('specsFinished')(); }); await notifyBrowserReady(); diff --git a/test/web/suite/webfront.project.json b/test/web/suite/webfront.project.json new file mode 100644 index 00000000..9a1a45ac --- /dev/null +++ b/test/web/suite/webfront.project.json @@ -0,0 +1,7 @@ +{ + "format": 1, + "name": "webfront-browser-tests", + "version": "0.1.0", + "dependencies": {"jasmine-core": "7.0.2"}, + "test": {"specs": ["specs/webfront-specs.mjs"]} +} diff --git a/test/web/transport-benchmark.html b/test/web/transport-benchmark.html new file mode 100644 index 00000000..de0998c1 --- /dev/null +++ b/test/web/transport-benchmark.html @@ -0,0 +1,245 @@ + + +WebFront transport benchmark + + + diff --git a/test/web/transport-contracts.html b/test/web/transport-contracts.html new file mode 100644 index 00000000..3e54b1a6 --- /dev/null +++ b/test/web/transport-contracts.html @@ -0,0 +1,69 @@ + + +Direct transport contracts + + diff --git a/test/web/wkwebview-transport-contracts.html b/test/web/wkwebview-transport-contracts.html new file mode 100644 index 00000000..afaa6b5c --- /dev/null +++ b/test/web/wkwebview-transport-contracts.html @@ -0,0 +1,69 @@ + + +WKWebView transport API contracts + + + diff --git a/third_party/babel/LICENSE b/third_party/babel/LICENSE deleted file mode 100644 index f31575ec..00000000 --- a/third_party/babel/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -MIT License - -Copyright (c) 2014-present Sebastian McKenzie and other contributors - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/third_party/babel/VERSION b/third_party/babel/VERSION deleted file mode 100644 index 2b0b4118..00000000 --- a/third_party/babel/VERSION +++ /dev/null @@ -1 +0,0 @@ -@babel/standalone 8.0.7 diff --git a/third_party/babel/babel.min.js b/third_party/babel/babel.min.js deleted file mode 100644 index c2cd8c51..00000000 --- a/third_party/babel/babel.min.js +++ /dev/null @@ -1,3 +0,0 @@ -!function(e,a){"object"==typeof exports&&"undefined"!=typeof module?a(exports):"function"==typeof define&&define.amd?define(["exports"],a):a((e="undefined"!=typeof globalThis?globalThis:e||self).Babel={})}(this,function(e){"use strict";var a=Object.freeze({__proto__:null,get DEFAULT_EXTENSIONS(){return Oq},get File(){return aj},get buildExternalHelpers(){return Pj},get createConfigItem(){return qU},get createConfigItemAsync(){return MU},get createConfigItemSync(){return LU},get getEnv(){return Vj},get loadOptions(){return OU},get loadOptionsAsync(){return NU},get loadOptionsSync(){return jU},get loadPartialConfig(){return kU},get loadPartialConfigAsync(){return _U},get loadPartialConfigSync(){return DU},get parse(){return Dq},get parseAsync(){return Iq},get parseSync(){return kq},get resolvePlugin(){return Nq},get resolvePreset(){return jq},get template(){return gx},get tokTypes(){return Cb},get transform(){return vq},get transformAsync(){return xq},get transformFile(){return Sq},get transformFileAsync(){return Tq},get transformFileSync(){return Eq},get transformFromAst(){return Cq},get transformFromAstAsync(){return Aq},get transformFromAstSync(){return Pq},get transformSync(){return bq},get traverse(){return ZI},get types(){return om},get version(){return Bq}});function n(e,a){(null==a||a>e.length)&&(a=e.length);for(var n=0,t=Array(a);n=e.length?{done:!0}:{done:!1,value:e[t++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function s(e,a,n){return(a=v(a))in e?Object.defineProperty(e,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[a]=n,e}function d(e){return d=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},d(e)}function u(e,a){if("function"!=typeof a&&null!==a)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(a&&a.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),a&&h(e,a)}function c(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(c=function(){return!!e})()}function l(e,a){if(null==e)return{};var n={};for(var t in e)if({}.hasOwnProperty.call(e,t)){if(-1!==a.indexOf(t))continue;n[t]=e[t]}return n}function p(){ -/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ -var e,a,n="function"==typeof Symbol?Symbol:{},t=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,t,r,i){var d=t&&t.prototype instanceof s?t:s,u=Object.create(d.prototype);return g(u,"_invoke",function(n,t,r){var i,s,d,u=0,c=r||[],l=!1,p={p:0,n:0,v:e,a:g,f:g.bind(e,4),d:function(a,n){return i=a,s=0,d=e,p.n=n,o}};function g(n,t){for(s=n,d=t,a=0;!l&&u&&!r&&a3?(r=f===t)&&(d=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=e):i[0]<=g&&((r=n<2&&gt||t>f)&&(i[4]=n,i[5]=t,p.n=f,s=0))}if(r||n>1)return o;throw l=!0,t}return function(r,c,f){if(u>1)throw TypeError("Generator is already running");for(l&&1===c&&g(c,f),s=c,d=f;(a=s<2?e:d)||!l;){i||(s?s<3?(s>1&&(p.n=-1),g(s,d)):p.n=d:p.v=d);try{if(u=2,i){if(s||(r="next"),a=i[r]){if(!(a=a.call(i,d)))throw TypeError("iterator result is not an object");if(!a.done)return a;d=a.value,s<2&&(s=0)}else 1===s&&(a=i.return)&&a.call(i),s<2&&(d=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=e}else if((a=(l=p.n<0)?d:n.call(t,p))!==o)break}catch(a){i=e,s=1,d=a}finally{u=1}}return{value:a,done:l}}}(n,r,i),!0),u}var o={};function s(){}function d(){}function u(){}a=Object.getPrototypeOf;var c=[][t]?a(a([][t]())):(g(a={},t,function(){return this}),a),l=u.prototype=s.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,g(e,r,"GeneratorFunction")),e.prototype=Object.create(l),e}return d.prototype=u,g(l,"constructor",u),g(u,"constructor",d),d.displayName="GeneratorFunction",g(u,r,"GeneratorFunction"),g(l),g(l,r,"Generator"),g(l,t,function(){return this}),g(l,"toString",function(){return"[object Generator]"}),(p=function(){return{w:i,m:f}})()}function g(e,a,n,t){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}g=function(e,a,n,t){function i(a,n){g(e,a,function(e){return this._invoke(a,n,e)})}a?r?r(e,a,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[a]=n:(i("next",0),i("throw",1),i("return",2))},g(e,a,n,t)}function f(e){if(null!=e){var a=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],n=0;if(a)return a.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}throw new TypeError(typeof e+" is not iterable")}function h(e,a){return h=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,a){return e.__proto__=a,e},h(e,a)}function m(e,a){return function(e){if(Array.isArray(e))return e}(e)||function(e,a){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var t,r,i,o,s=[],d=!0,u=!1;try{if(i=(n=n.call(e)).next,0===a){if(Object(n)!==n)return;d=!1}else for(;!(d=(t=i.call(n)).done)&&(s.push(t.value),s.length!==a);d=!0);}catch(e){u=!0,r=e}finally{try{if(!d&&null!=n.return&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw r}}return s}}(e,a)||b(e,a)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function R(e,a){return a||(a=e.slice(0)),e.raw=a,e}function y(e){return function(e){if(Array.isArray(e))return n(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||b(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function v(e){var a=function(e,a){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var t=n.call(e,a);if("object"!=typeof t)return t;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===a?String:Number)(e)}(e,"string");return"symbol"==typeof a?a:a+""}function b(e,a){if(e){if("string"==typeof e)return n(e,a);var t={}.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?n(e,a):void 0}}function x(e){var a="function"==typeof Map?new Map:void 0;return x=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(a){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==a){if(a.has(e))return a.get(e);a.set(e,n)}function n(){return function(e,a,n){if(c())return Reflect.construct.apply(null,arguments);var t=[null];t.push.apply(t,a);var r=new(e.bind.apply(e,t));return n&&h(r,n.prototype),r}(e,arguments,d(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),h(n,e)},x(e)}function S(e,a){for(var n=0,t=Object.keys(a);nr.length)return!1;for(var s=0,d=i.length-1;se)return!1;if((n+=a[t+1])>=e)return!0}return!1}function gn(e){return e<65?36===e:e<=90||(e<97?95===e:e<=122||(e<=65535?e>=170&&dn.test(String.fromCharCode(e)):pn(e,cn)))}function fn(e){return e<48?36===e:e<58||!(e<65)&&(e<=90||(e<97?95===e:e<=122||(e<=65535?e>=170&&un.test(String.fromCharCode(e)):pn(e,cn)||pn(e,ln))))}function hn(e){for(var a=!0,n=0;n=48&&e<=57},An={decBinOct:new Set([46,66,69,79,95,98,101,111]),hex:new Set([46,88,95,120])},_n={bin:function(e){return 48===e||49===e},oct:function(e){return e>=48&&e<=55},dec:function(e){return e>=48&&e<=57},hex:function(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}};function Dn(e,a,n,t,r,i){for(var o=n,s=t,d=r,u="",c=null,l=n,p=a.length;;){if(n>=p){i.unterminated(o,s,d),u+=a.slice(l,n);break}var g=a.charCodeAt(n);if(kn(e,g,a,n)){u+=a.slice(l,n);break}if(92===g){u+=a.slice(l,n);var f=In(a,n,t,r,"template"===e,i);null!==f.ch||c?u+=f.ch:c={pos:n,lineStart:t,curLine:r},n=f.pos,t=f.lineStart,r=f.curLine,l=n}else 8232===g||8233===g?(++r,t=++n):10===g||13===g?"template"===e?(u+=a.slice(l,n)+"\n",++n,13===g&&10===a.charCodeAt(n)&&++n,++r,l=t=n):i.unterminated(o,s,d):++n}return{pos:n,str:u,firstInvalidLoc:c,lineStart:t,curLine:r}}function kn(e,a,n,t){return"template"===e?96===a||36===a&&123===n.charCodeAt(t+1):a===("double"===e?34:39)}function In(e,a,n,t,r,i){var o=!r;a++;var s=function(e){return{pos:a,ch:e,lineStart:n,curLine:t}},d=e.charCodeAt(a++);switch(d){case 110:return s("\n");case 114:return s("\r");case 120:var u,c=Bn(e,a,n,t,2,!1,o,i);return u=c.code,a=c.pos,s(null===u?null:String.fromCharCode(u));case 117:var l,p=jn(e,a,n,t,o,i);return l=p.code,a=p.pos,s(null===l?null:String.fromCodePoint(l));case 116:return s("\t");case 98:return s("\b");case 118:return s("\v");case 102:return s("\f");case 13:10===e.charCodeAt(a)&&++a;case 10:n=a,++t;case 8232:case 8233:return s("");case 56:case 57:if(r)return s(null);i.strictNumericEscape(a-1,n,t);default:if(d>=48&&d<=55){var g=a-1,f=/^[0-7]+/.exec(e.slice(g,a+2))[0],h=parseInt(f,8);h>255&&(f=f.slice(0,-1),h=parseInt(f,8)),a+=f.length-1;var m=e.charCodeAt(a);if("0"!==f||56===m||57===m){if(r)return s(null);i.strictNumericEscape(g,n,t)}return s(String.fromCharCode(h))}return s(String.fromCharCode(d))}}function Bn(e,a,n,t,r,i,o,s){var d,u=a,c=Nn(e,a,n,t,16,r,i,!1,s,!o);return d=c.n,a=c.pos,null===d&&(o?s.invalidEscapeSequence(u,n,t):a=u-1),{code:d,pos:a}}function Nn(e,a,n,t,r,i,o,s,d,u){for(var c=a,l=16===r?An.hex:An.decBinOct,p=16===r?_n.hex:10===r?_n.dec:8===r?_n.oct:_n.bin,g=!1,f=0,h=0,m=null==i?1/0:i;h=97?R-97+10:R>=65?R-65+10:Pn(R)?R-48:1/0)>=r)if(y<=9){if(u)return{n:null,pos:a};d.invalidDigit(a,n,t,r),y=0}else{if(!o)break;y=0,g=!0}++a,f=f*r+y}else{var v=e.charCodeAt(a-1),b=e.charCodeAt(a+1);if(s){if(Number.isNaN(b)||!p(b)||l.has(v)||l.has(b)){if(u)return{n:null,pos:a};d.unexpectedNumericSeparator(a,n,t)}}else{if(u)return{n:null,pos:a};d.numericSeparatorInEscapeSequence(a,n,t)}++a}}return a===c||null!=i&&a-c!==i||g?{n:null,pos:a}:{n:f,pos:a}}function jn(e,a,n,t,r,i){var o;if(123===e.charCodeAt(a)){var s=Bn(e,++a,n,t,e.indexOf("}",a)-a,!0,r,i);if(o=s.code,a=s.pos,++a,null!==o&&o>1114111){if(!r)return{code:null,pos:a};i.invalidCodePoint(a,n,t)}}else{var d=Bn(e,a,n,t,4,!1,r,i);o=d.code,a=d.pos}return{code:o,pos:a}}var On=["consequent","body","alternate"],Fn=["leadingComments","trailingComments","innerComments"],Mn=["||","&&","??"],Ln=["++","--"],Un=[">","<",">=","<="],qn=["==","===","!=","!=="],Wn=[].concat(qn,["in","instanceof"]),Vn=[].concat(y(Wn),Un),Hn=["-","/","%","*","**","&","|",">>",">>>","<<","^"],Gn=["+"].concat(Hn,y(Vn),["|>"]),Kn=["=","+="].concat(y(Hn.map(function(e){return e+"="})),y(Mn.map(function(e){return e+"="}))),Jn=["delete","!"],zn=["+","-","~"],Xn=["typeof"],Yn=["void","throw"].concat(Jn,zn,Xn),$n={optional:["typeAnnotation","typeParameters","returnType"],force:["start","loc","end"]},Qn={},Zn={},et={},at={},nt={},tt={},rt={},it={};function ot(e){return Array.isArray(e)?"array":null===e?"null":typeof e}function st(e){for(var a=arguments.length,n=new Array(a>1?a-1:0),t=1;t=2&&"type"in a[0]&&"array"===a[0].type&&!("each"in a[1]))throw new Error('An assertValueType("array") validator can only be followed by an assertEach(...) validator.');return t}var Tt=new Set(["aliases","builder","deprecatedAlias","fields","inherits","visitor","validate","unionShape"]),wt=new Set(["default","optional","deprecated","validate"]),Ct={};function Pt(){for(var e=arguments.length,a=new Array(e),n=0;n0:p&&"object"==typeof p)throw new Error("field defaults can only be primitives or empty arrays currently");s[c]={default:Array.isArray(p)?[]:p,optional:l.optional,deprecated:l.deprecated,validate:l.validate}}for(var g=0,f=Object.keys(a);g+i+1)throw new TypeError("RestElement must be last element of "+r)}}),kt("ReturnStatement",{visitor:["argument"],aliases:["Statement","Terminatorless","CompletionStatement"],fields:{argument:{validate:vt("Expression"),optional:!0}}}),kt("SequenceExpression",{visitor:["expressions"],fields:{expressions:ht("Expression")},aliases:["Expression"]}),kt("ParenthesizedExpression",{visitor:["expression"],aliases:["Expression","ExpressionWrapper"],fields:{expression:{validate:vt("Expression")}}}),kt("SwitchCase",{visitor:["test","consequent"],fields:{test:{validate:vt("Expression"),optional:!0},consequent:ht("Statement")}}),kt("SwitchStatement",{visitor:["discriminant","cases"],aliases:["Statement","BlockParent","Scopable"],fields:{discriminant:{validate:vt("Expression")},cases:ht("SwitchCase")}}),kt("ThisExpression",{aliases:["Expression","TSEntityName"]}),kt("ThrowStatement",{visitor:["argument"],aliases:["Statement","Terminatorless","CompletionStatement"],fields:{argument:{validate:vt("Expression")}}}),kt("TryStatement",{visitor:["block","handler","finalizer"],aliases:["Statement"],fields:{block:{validate:Et(vt("BlockStatement"),st(function(e){if(!e.handler&&!e.finalizer)throw new TypeError("TryStatement expects either a handler or finalizer, or both")},{oneOfNodeTypes:["BlockStatement"]}))},handler:{optional:!0,validate:vt("CatchClause")},finalizer:{optional:!0,validate:vt("BlockStatement")}}}),kt("UnaryExpression",{builder:["operator","argument","prefix"],fields:{prefix:{default:!0},argument:{validate:vt("Expression")},operator:{validate:Rt.apply(void 0,y(Yn))}},visitor:["argument"],aliases:["UnaryLike","Expression"]}),kt("UpdateExpression",{builder:["operator","argument","prefix"],fields:{prefix:{default:!1},argument:{validate:vt("Identifier","MemberExpression")},operator:{validate:Rt.apply(void 0,y(Ln))}},visitor:["argument"],aliases:["Expression"]}),kt("VariableDeclaration",{builder:["kind","declarations"],visitor:["declarations"],aliases:["Statement","Declaration"],fields:{declare:{validate:xt("boolean"),optional:!0},kind:{validate:Rt("var","let","const","using","await using")},declarations:ht("VariableDeclarator")},validate:(Mt=vt("Identifier","Placeholder"),Lt=vt("Identifier","ArrayPattern","ObjectPattern","Placeholder"),Ut=vt("Identifier","VoidPattern","Placeholder"),function(e,a,n){var t=n.kind,r=n.declarations,i=on("ForXStatement",e,{left:n});if(i&&1!==r.length)throw new TypeError("Exactly one VariableDeclarator is required in the VariableDeclaration of a "+e.type);for(var s,d=o(r);!(s=d()).done;){var u=s.value;"const"===t||"let"===t||"var"===t?i||u.init?Lt(u,"id",u.id):Mt(u,"id",u.id):Ut(u,"id",u.id)}})}),kt("VariableDeclarator",{visitor:["id","init"],fields:{id:{validate:vt("Identifier","ArrayPattern","ObjectPattern","VoidPattern")},definite:{optional:!0,validate:xt("boolean")},init:{optional:!0,validate:vt("Expression")}}}),kt("WhileStatement",{visitor:["test","body"],aliases:["Statement","BlockParent","Loop","While","Scopable"],fields:{test:{validate:vt("Expression")},body:{validate:vt("Statement")}}}),kt("WithStatement",{visitor:["object","body"],aliases:["Statement"],fields:{object:{validate:vt("Expression")},body:{validate:vt("Statement")}}}),kt("AssignmentPattern",{visitor:["left","right","decorators"],builder:["left","right"],aliases:["FunctionParameter","Pattern","PatternLike"],fields:Object.assign({},qt(),{left:{validate:vt("Identifier","ObjectPattern","ArrayPattern","MemberExpression","TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","TSNonNullExpression")},right:{validate:vt("Expression")}})}),kt("ArrayPattern",{visitor:["elements","typeAnnotation"],builder:["elements"],aliases:["FunctionParameter","Pattern","PatternLike","LVal"],fields:Object.assign({},qt(),{elements:{validate:Et(xt("array"),mt(bt("null","PatternLike")))}})}),kt("ArrowFunctionExpression",{builder:["params","body","async"],visitor:["typeParameters","params","predicate","returnType","body"],aliases:["Scopable","Function","BlockParent","FunctionParent","Expression","Pureish"],fields:Object.assign({},It(),{generator:{default:null,optional:!0,validate:st(function(e,a,n){if(n)throw new TypeError("ArrowFunctionExpression cannot be a generator")},{type:"boolean"})}},Bt(),{expression:{optional:!0,validate:xt("boolean")},body:{validate:vt("BlockStatement","Expression")},predicate:{validate:vt("FlowPredicate"),optional:!0}})}),kt("ClassBody",{visitor:["body"],fields:{body:ht("ClassMethod","ClassPrivateMethod","ClassProperty","ClassPrivateProperty","ClassAccessorProperty","TSDeclareMethod","TSIndexSignature","StaticBlock")}}),kt("ClassExpression",{builder:["id","superClass","body","decorators"],visitor:["decorators","id","typeParameters","superClass","superTypeArguments","mixins","implements","body"],aliases:["Scopable","Class","Expression"],fields:{id:{validate:vt("Identifier"),optional:!0},typeParameters:{validate:vt("TypeParameterDeclaration","TSTypeParameterDeclaration"),optional:!0},body:{validate:vt("ClassBody")},superClass:{optional:!0,validate:vt("Expression")},superTypeArguments:{validate:vt("TypeParameterInstantiation","TSTypeParameterInstantiation"),optional:!0},implements:{validate:ft("TSClassImplements","ClassImplements"),optional:!0},decorators:{validate:ft("Decorator"),optional:!0},mixins:{validate:vt("InterfaceExtends"),optional:!0}}}),kt("ClassDeclaration",{inherits:"ClassExpression",aliases:["Scopable","Class","Statement","Declaration"],fields:{id:{validate:vt("Identifier"),optional:!0},typeParameters:{validate:vt("TypeParameterDeclaration","TSTypeParameterDeclaration"),optional:!0},body:{validate:vt("ClassBody")},superClass:{optional:!0,validate:vt("Expression")},superTypeArguments:{validate:vt("TypeParameterInstantiation","TSTypeParameterInstantiation"),optional:!0},implements:{validate:ft("TSClassImplements","ClassImplements"),optional:!0},decorators:{validate:ft("Decorator"),optional:!0},mixins:{validate:vt("InterfaceExtends"),optional:!0},declare:{validate:xt("boolean"),optional:!0},abstract:{validate:xt("boolean"),optional:!0}},validate:function(){var e=vt("Identifier");return function(a,n,t){on("ExportDefaultDeclaration",a)||e(t,"id",t.id)}}()});var Wt,Vt,Ht,Gt,Kt={attributes:{optional:!0,validate:ft("ImportAttribute")}};kt("ExportAllDeclaration",{visitor:["source","attributes"],aliases:["Statement","Declaration","ImportOrExportDeclaration","ExportDeclaration"],fields:Object.assign({source:{validate:vt("StringLiteral")},exportKind:ct(Rt("type","value"))},Kt)}),kt("ExportDefaultDeclaration",{visitor:["declaration"],aliases:["Statement","Declaration","ImportOrExportDeclaration","ExportDeclaration"],fields:{declaration:ut("FunctionDeclaration","ClassDeclaration","Expression","TSDeclareFunction","TSInterfaceDeclaration","EnumDeclaration"),exportKind:ct(Rt("value"))}}),kt("ExportNamedDeclaration",{builder:["declaration","specifiers","source","attributes"],visitor:["declaration","specifiers","source","attributes"],aliases:["Statement","Declaration","ImportOrExportDeclaration","ExportDeclaration"],fields:Object.assign({declaration:{optional:!0,validate:Et(vt("Declaration"),st(function(e,a,n){if(n&&e.specifiers.length)throw new TypeError("Only declaration or specifiers is allowed on ExportNamedDeclaration");if(n&&e.source)throw new TypeError("Cannot export a declaration from a source")},{oneOfNodeTypes:["VariableDeclaration","FunctionDeclaration","ClassDeclaration","TSDeclareFunction","TSEnumDeclaration","TSImportEqualsDeclaration","TSInterfaceDeclaration","TSModuleDeclaration","TSTypeAliasDeclaration","EnumDeclaration","InterfaceDeclaration","OpaqueType","TypeAlias"]}))}},Kt,{specifiers:{default:[],validate:gt((Wt=vt("ExportSpecifier","ExportDefaultSpecifier","ExportNamespaceSpecifier"),Vt=vt("ExportSpecifier"),st(function(e,a,n){(e.source?Wt:Vt)(e,a,n)},{oneOfNodeTypes:["ExportSpecifier","ExportDefaultSpecifier","ExportNamespaceSpecifier"]})))},source:{validate:vt("StringLiteral"),optional:!0},exportKind:ct(Rt("type","value"))})}),kt("ExportSpecifier",{visitor:["local","exported"],aliases:["ModuleSpecifier"],fields:{local:{validate:vt("Identifier","StringLiteral")},exported:{validate:vt("Identifier","StringLiteral")},exportKind:{validate:Rt("type","value"),optional:!0}}}),kt("ForOfStatement",{visitor:["left","right","body"],builder:["left","right","body","await"],aliases:["Scopable","Statement","For","BlockParent","Loop","ForXStatement"],fields:{left:{validate:(Ht=vt("VariableDeclaration"),Gt=vt("Identifier","MemberExpression","ArrayPattern","ObjectPattern","TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","TSNonNullExpression"),st(function(e,a,n){on("VariableDeclaration",n)?Ht(e,a,n):Gt(e,a,n)},{oneOfNodeTypes:["VariableDeclaration","Identifier","MemberExpression","ArrayPattern","ObjectPattern","TSAsExpression","TSSatisfiesExpression","TSTypeAssertion","TSNonNullExpression"]}))},right:{validate:vt("Expression")},body:{validate:vt("Statement")},await:{default:!1}}}),kt("ImportDeclaration",{builder:["specifiers","source","attributes"],visitor:["specifiers","source","attributes"],aliases:["Statement","Declaration","ImportOrExportDeclaration"],fields:Object.assign({},Kt,{module:{optional:!0,validate:xt("boolean")},phase:{default:null,validate:Rt("source","defer")},specifiers:ht("ImportSpecifier","ImportDefaultSpecifier","ImportNamespaceSpecifier"),source:{validate:vt("StringLiteral")},importKind:{validate:Rt("type","typeof","value"),optional:!0}})}),kt("ImportDefaultSpecifier",{visitor:["local"],aliases:["ModuleSpecifier"],fields:{local:{validate:vt("Identifier")}}}),kt("ImportNamespaceSpecifier",{visitor:["local"],aliases:["ModuleSpecifier"],fields:{local:{validate:vt("Identifier")}}}),kt("ImportSpecifier",{visitor:["imported","local"],builder:["local","imported"],aliases:["ModuleSpecifier"],fields:{local:{validate:vt("Identifier")},imported:{validate:vt("Identifier","StringLiteral")},importKind:{validate:Rt("type","typeof","value"),optional:!0}}}),kt("MetaProperty",{visitor:["meta","property"],aliases:["Expression"],fields:{meta:{validate:Et(vt("Identifier"),st(function(e,a,n){var t;switch(n.name){case"function":t="sent";break;case"new":t="target";break;case"import":t="meta"}if(!on("Identifier",e.property,{name:t}))throw new TypeError("Unrecognised MetaProperty")},{oneOfNodeTypes:["Identifier"]}))},property:{validate:vt("Identifier")}}});var Jt=function(){return{abstract:{validate:xt("boolean"),default:!1,optional:!0},accessibility:{validate:Rt("public","private","protected"),optional:!0},static:{default:!1},override:{optional:!0,validate:xt("boolean"),default:!1},computed:{default:!1},optional:{validate:xt("boolean"),optional:!0},key:{validate:Et(function(){var e=vt("Identifier","StringLiteral","NumericLiteral","BigIntLiteral"),a=vt("Expression","PrivateName");return function(n,t,r){(n.computed?a:e)(n,t,r)}}(),vt("Identifier","StringLiteral","NumericLiteral","BigIntLiteral","Expression","PrivateName"))}}},zt=function(e){return void 0===e&&(e=!0),Object.assign({},It(),Jt(),{params:ht("FunctionParameter","TSParameterProperty"),kind:{validate:Rt("get","set","method","constructor"),default:"method"},access:{validate:Et(xt("string"),Rt("public","private","protected")),optional:!0}},e?{decorators:{validate:ft("Decorator"),optional:!0}}:{})};kt("ClassMethod",Object.assign({aliases:["Function","Scopable","BlockParent","FunctionParent","Method"],builder:["kind","key","params","body","computed","static","generator","async"],visitor:["decorators","key","typeParameters","params","returnType","body"]},_t(),{fields:Object.assign({},zt(),Bt(),{body:{validate:vt("BlockStatement")}})})),kt("ObjectPattern",{visitor:["decorators","properties","typeAnnotation"],builder:["properties"],aliases:["FunctionParameter","Pattern","PatternLike","LVal"],fields:Object.assign({},qt(),{properties:ht("RestElement","ObjectProperty")})}),kt("SpreadElement",{visitor:["argument"],aliases:["UnaryLike"],deprecatedAlias:"SpreadProperty",fields:{argument:{validate:vt("Expression")}}}),kt("Super"),kt("TaggedTemplateExpression",{visitor:["tag","typeArguments","quasi"],builder:["tag","quasi"],aliases:["Expression"],fields:{tag:{validate:vt("Expression")},quasi:{validate:vt("TemplateLiteral")},typeArguments:{validate:vt("TypeParameterInstantiation","TSTypeParameterInstantiation"),optional:!0}}}),kt("TemplateElement",{builder:["value","tail"],fields:{value:{validate:Et(function(e){var a=Object.keys(e);function n(n,t,r){for(var i,s=[],d=o(a);!(i=d()).done;){var u=i.value;try{Dr(n,u,r[u],e[u])}catch(e){if(e instanceof TypeError){s.push(e.message);continue}throw e}}if(s.length)throw new TypeError("Property "+t+" of "+n.type+" expected to have the following:\n"+s.join("\n"))}return n.shapeOf=e,n}({raw:{validate:xt("string")},cooked:{validate:xt("string"),optional:!0}}),function(e){var a=e.value.raw,n=!1,t=function(){throw new Error("Internal @babel/types error.")},r=Dn("template",a,0,0,0,{unterminated:function(){n=!0},strictNumericEscape:t,invalidEscapeSequence:t,numericSeparatorInEscapeSequence:t,unexpectedNumericSeparator:t,invalidDigit:t,invalidCodePoint:t}),i=r.str,o=r.firstInvalidLoc;if(!n)throw new Error("Invalid raw");e.value.cooked=o?null:i})},tail:{default:!1}}}),kt("TemplateLiteral",{visitor:["quasis","expressions"],aliases:["Expression","Literal"],fields:{quasis:ht("TemplateElement"),expressions:{validate:Et(xt("array"),mt(vt("Expression","TSType")),function(e,a,n){if(e.quasis.length!==n.length+1)throw new TypeError("Number of "+e.type+" quasis should be exactly one more than the number of expressions.\nExpected "+(n.length+1)+" quasis but got "+e.quasis.length)})}}}),kt("YieldExpression",{builder:["argument","delegate"],visitor:["argument"],aliases:["Expression","Terminatorless"],fields:{delegate:{validate:Et(xt("boolean"),st(function(e,a,n){if(n&&!e.argument)throw new TypeError("Property delegate of YieldExpression cannot be true if there is no argument")},{type:"boolean"})),default:!1},argument:{optional:!0,validate:vt("Expression")}}}),kt("AwaitExpression",{builder:["argument"],visitor:["argument"],aliases:["Expression","Terminatorless"],fields:{argument:{validate:vt("Expression")}}}),kt("ImportExpression",{visitor:["source","options"],aliases:["Expression"],fields:{phase:{default:null,validate:Rt("source","defer")},source:{validate:vt("Expression")},options:{validate:vt("Expression"),optional:!0}}}),kt("Import"),kt("BigIntLiteral",{builder:["value"],fields:{value:{validate:xt("bigint")}},aliases:["Expression","Pureish","Literal","Immutable"]}),kt("ExportNamespaceSpecifier",{visitor:["exported"],aliases:["ModuleSpecifier"],fields:{exported:{validate:vt("Identifier","StringLiteral")}}}),kt("OptionalMemberExpression",Object.assign({builder:["object","property","computed","optional"],visitor:["object","property"],aliases:["Expression"]},Dt,{fields:{object:{validate:vt("Expression")},property:{validate:function(){var e=vt("Identifier","PrivateName"),a=vt("Expression");return st(function(n,t,r){(n.computed?a:e)(n,t,r)},{oneOfNodeTypes:["Expression","PrivateName"]})}()},computed:{default:!1},optional:{validate:Et(xt("boolean"),St())}}})),kt("OptionalCallExpression",{visitor:["callee","typeArguments","arguments"],builder:["callee","arguments","optional"],aliases:["Expression"],fields:{callee:{validate:vt("Expression")},arguments:ht("Expression","SpreadElement","ArgumentPlaceholder"),optional:{validate:Et(xt("boolean"),St())},typeArguments:{validate:vt("TypeParameterInstantiation","TSTypeParameterInstantiation"),optional:!0}}}),kt("ClassProperty",Object.assign({visitor:["decorators","variance","key","typeAnnotation","value"],builder:["key","value","typeAnnotation","decorators","computed","static"],aliases:["Property"]},_t(),{fields:Object.assign({},Jt(),{value:{validate:vt("Expression"),optional:!0},definite:{validate:xt("boolean"),optional:!0},typeAnnotation:{validate:vt("TypeAnnotation","TSTypeAnnotation"),optional:!0},decorators:{validate:ft("Decorator"),optional:!0},readonly:{validate:xt("boolean"),optional:!0},declare:{validate:xt("boolean"),optional:!0},variance:{validate:vt("Variance"),optional:!0}})})),kt("ClassPrivateProperty",{visitor:["decorators","variance","key","typeAnnotation","value"],builder:["key","value","decorators","static"],aliases:["Property","Private"],fields:{key:{validate:vt("PrivateName")},value:{validate:vt("Expression"),optional:!0},typeAnnotation:{validate:vt("TypeAnnotation","TSTypeAnnotation"),optional:!0},decorators:{validate:ft("Decorator"),optional:!0},static:{validate:xt("boolean"),default:!1},readonly:{validate:xt("boolean"),optional:!0},optional:{validate:xt("boolean"),optional:!0},definite:{validate:xt("boolean"),optional:!0},variance:{validate:vt("Variance"),optional:!0}}}),kt("ClassPrivateMethod",{builder:["kind","key","params","body","static"],visitor:["decorators","key","typeParameters","params","returnType","body"],aliases:["Function","Scopable","BlockParent","FunctionParent","Method","Private"],fields:Object.assign({},zt(),Bt(),{kind:{validate:Rt("get","set","method"),default:"method"},key:{validate:vt("PrivateName")},body:{validate:vt("BlockStatement")}})}),kt("PrivateName",{visitor:["id"],aliases:["Private"],fields:{id:{validate:vt("Identifier")}}}),kt("StaticBlock",{visitor:["body"],fields:{body:ht("Statement")},aliases:["Scopable","BlockParent","FunctionParent"]}),kt("ImportAttribute",{visitor:["key","value"],fields:{key:{validate:vt("Identifier","StringLiteral")},value:{validate:vt("StringLiteral")}}});var Xt=Pt("Flow"),Yt=function(e){var a="DeclareClass"===e;Xt(e,{builder:["id","typeParameters","extends","body"],visitor:["id","typeParameters","extends"].concat(y(a?["mixins","implements"]:[]),["body"]),aliases:["FlowDeclaration","Statement","Declaration"],fields:Object.assign({id:ut("Identifier"),typeParameters:pt("TypeParameterDeclaration"),extends:ct(ft("InterfaceExtends"))},a?{mixins:ct(ft("InterfaceExtends")),implements:ct(ft("ClassImplements"))}:{},{body:ut("ObjectTypeAnnotation")})})};Xt("AnyTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),Xt("ArrayTypeAnnotation",{visitor:["elementType"],aliases:["FlowType"],fields:{elementType:ut("FlowType")}}),Xt("BooleanTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),Xt("BooleanLiteralTypeAnnotation",{builder:["value"],aliases:["FlowType"],fields:{value:dt(xt("boolean"))}}),Xt("NullLiteralTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),Xt("ClassImplements",{visitor:["id","typeParameters"],fields:{id:ut("Identifier"),typeParameters:pt("TypeParameterInstantiation")}}),Yt("DeclareClass"),Xt("DeclareFunction",{builder:["id"],visitor:["id","predicate"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:ut("Identifier"),predicate:pt("FlowPredicate")}}),Yt("DeclareInterface"),Xt("DeclareModule",{builder:["id","body","kind"],visitor:["id","body"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:ut("Identifier","StringLiteral"),body:ut("BlockStatement"),kind:ct(Rt("CommonJS","ES"))}}),Xt("DeclareModuleExports",{visitor:["typeAnnotation"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{typeAnnotation:ut("TypeAnnotation")}}),Xt("DeclareTypeAlias",{visitor:["id","typeParameters","right"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:ut("Identifier"),typeParameters:pt("TypeParameterDeclaration"),right:ut("FlowType")}}),Xt("DeclareOpaqueType",{visitor:["id","typeParameters","supertype"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:ut("Identifier"),typeParameters:pt("TypeParameterDeclaration"),supertype:pt("FlowType"),impltype:pt("FlowType")}}),Xt("DeclareVariable",{visitor:["id"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:ut("Identifier")}}),Xt("DeclareExportDeclaration",{visitor:["declaration","specifiers","source","attributes"],aliases:["FlowDeclaration","Statement","Declaration"],fields:Object.assign({declaration:pt("Flow"),specifiers:ct(ft("ExportSpecifier","ExportNamespaceSpecifier")),source:pt("StringLiteral"),default:ct(xt("boolean"))},Kt)}),Xt("DeclareExportAllDeclaration",{visitor:["source","attributes"],aliases:["FlowDeclaration","Statement","Declaration"],fields:Object.assign({source:ut("StringLiteral"),exportKind:ct(Rt("type","value"))},Kt)}),Xt("DeclaredPredicate",{visitor:["value"],aliases:["FlowPredicate"],fields:{value:ut("Expression")}}),Xt("ExistsTypeAnnotation",{aliases:["FlowType"]}),Xt("FunctionTypeAnnotation",{builder:["typeParameters","params","rest","returnType"],visitor:["typeParameters","this","params","rest","returnType"],aliases:["FlowType"],fields:{typeParameters:pt("TypeParameterDeclaration"),params:ht("FunctionTypeParam"),rest:pt("FunctionTypeParam"),this:pt("FunctionTypeParam"),returnType:ut("FlowType")}}),Xt("FunctionTypeParam",{visitor:["name","typeAnnotation"],fields:{name:pt("Identifier"),typeAnnotation:ut("FlowType"),optional:ct(xt("boolean"))}}),Xt("GenericTypeAnnotation",{visitor:["id","typeParameters"],aliases:["FlowType"],fields:{id:ut("Identifier","QualifiedTypeIdentifier"),typeParameters:pt("TypeParameterInstantiation")}}),Xt("InferredPredicate",{aliases:["FlowPredicate"]}),Xt("InterfaceExtends",{visitor:["id","typeParameters"],fields:{id:ut("Identifier","QualifiedTypeIdentifier"),typeParameters:pt("TypeParameterInstantiation")}}),Yt("InterfaceDeclaration"),Xt("InterfaceTypeAnnotation",{visitor:["extends","body"],aliases:["FlowType"],fields:{extends:ct(ft("InterfaceExtends")),body:ut("ObjectTypeAnnotation")}}),Xt("IntersectionTypeAnnotation",{visitor:["types"],aliases:["FlowType"],fields:{types:dt(ft("FlowType"))}}),Xt("MixedTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),Xt("EmptyTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),Xt("NullableTypeAnnotation",{visitor:["typeAnnotation"],aliases:["FlowType"],fields:{typeAnnotation:ut("FlowType")}}),Xt("NumberLiteralTypeAnnotation",{builder:["value"],aliases:["FlowType"],fields:{value:dt(xt("number"))}}),Xt("BigIntLiteralTypeAnnotation",{builder:["value"],aliases:["FlowType"],fields:{value:dt(xt("bigint"))}}),Xt("NumberTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),Xt("ObjectTypeAnnotation",{visitor:["properties","indexers","callProperties","internalSlots"],aliases:["FlowType"],builder:["properties","indexers","callProperties","internalSlots","exact"],fields:{properties:dt(ft("ObjectTypeProperty","ObjectTypeSpreadProperty")),indexers:{validate:ft("ObjectTypeIndexer"),optional:!1,default:[]},callProperties:{validate:ft("ObjectTypeCallProperty"),optional:!1,default:[]},internalSlots:{validate:ft("ObjectTypeInternalSlot"),optional:!1,default:[]},exact:{validate:xt("boolean"),default:!1},inexact:ct(xt("boolean"))}}),Xt("ObjectTypeInternalSlot",{visitor:["id","value"],builder:["id","value","optional","static","method"],aliases:["UserWhitespacable"],fields:{id:ut("Identifier"),value:ut("FlowType"),optional:dt(xt("boolean")),static:dt(xt("boolean")),method:dt(xt("boolean"))}}),Xt("ObjectTypeCallProperty",{visitor:["value"],aliases:["UserWhitespacable"],fields:{value:ut("FlowType"),static:lt(xt("boolean"),!1)}}),Xt("ObjectTypeIndexer",{visitor:["variance","id","key","value"],builder:["id","key","value","variance"],aliases:["UserWhitespacable"],fields:{id:pt("Identifier"),key:ut("FlowType"),value:ut("FlowType"),static:lt(xt("boolean"),!1),variance:pt("Variance")}}),Xt("ObjectTypeProperty",{visitor:["key","value","variance"],aliases:["UserWhitespacable"],fields:{key:ut("Identifier","StringLiteral","NumericLiteral"),value:ut("FlowType"),kind:{validate:Rt("init","get","set"),default:"init",optional:!1},static:lt(xt("boolean"),!1),proto:lt(xt("boolean"),!1),optional:lt(xt("boolean"),!1),variance:pt("Variance"),method:lt(xt("boolean"),!1)}}),Xt("ObjectTypeSpreadProperty",{visitor:["argument"],aliases:["UserWhitespacable"],fields:{argument:ut("FlowType")}}),Xt("OpaqueType",{visitor:["id","typeParameters","supertype","impltype"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:ut("Identifier"),typeParameters:pt("TypeParameterDeclaration"),supertype:pt("FlowType"),impltype:ut("FlowType")}}),Xt("QualifiedTypeIdentifier",{visitor:["qualification","id"],builder:["id","qualification"],fields:{id:ut("Identifier"),qualification:ut("Identifier","QualifiedTypeIdentifier")}}),Xt("StringLiteralTypeAnnotation",{builder:["value"],aliases:["FlowType"],fields:{value:dt(xt("string"))}}),Xt("StringTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),Xt("SymbolTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),Xt("ThisTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),Xt("TupleTypeAnnotation",{visitor:["types"],aliases:["FlowType"],fields:{types:dt(ft("FlowType"))}}),Xt("TypeofTypeAnnotation",{visitor:["argument"],aliases:["FlowType"],fields:{argument:ut("FlowType","Identifier")}}),Xt("TypeAlias",{visitor:["id","typeParameters","right"],aliases:["FlowDeclaration","Statement","Declaration"],fields:{id:ut("Identifier"),typeParameters:pt("TypeParameterDeclaration"),right:ut("FlowType")}}),Xt("TypeAnnotation",{visitor:["typeAnnotation"],fields:{typeAnnotation:ut("FlowType","Identifier")}}),Xt("TypeCastExpression",{visitor:["expression","typeAnnotation"],aliases:["ExpressionWrapper","Expression"],fields:{expression:ut("Expression"),typeAnnotation:ut("TypeAnnotation")}}),Xt("TypeParameter",{builder:["name","bound","default","variance"],visitor:["bound","default","variance"],fields:{name:dt(xt("string")),bound:pt("TypeAnnotation"),default:pt("FlowType"),variance:pt("Variance")}}),Xt("TypeParameterDeclaration",{visitor:["params"],fields:{params:dt(ft("TypeParameter"))}}),Xt("TypeParameterInstantiation",{visitor:["params"],fields:{params:dt(ft("FlowType"))}}),Xt("UnionTypeAnnotation",{visitor:["types"],aliases:["FlowType"],fields:{types:dt(ft("FlowType"))}}),Xt("Variance",{builder:["kind"],fields:{kind:dt(Rt("minus","plus"))}}),Xt("VoidTypeAnnotation",{aliases:["FlowType","FlowBaseAnnotation"]}),Xt("EnumDeclaration",{aliases:["Statement","Declaration"],visitor:["id","body"],fields:{id:ut("Identifier"),body:ut("EnumBooleanBody","EnumNumberBody","EnumStringBody","EnumSymbolBody")}});var $t={explicitType:lt(xt("boolean"),!1),hasUnknownMembers:lt(xt("boolean"),!1)};Xt("EnumBooleanBody",{aliases:["EnumBody"],visitor:["members"],fields:Object.assign({},$t,{members:ht("EnumBooleanMember")})}),Xt("EnumNumberBody",{aliases:["EnumBody"],visitor:["members"],fields:Object.assign({},$t,{members:ht("EnumNumberMember")})}),Xt("EnumStringBody",{aliases:["EnumBody"],visitor:["members"],fields:Object.assign({},$t,{members:ht("EnumStringMember","EnumDefaultedMember")})}),Xt("EnumSymbolBody",{aliases:["EnumBody"],visitor:["members"],fields:{members:ht("EnumDefaultedMember"),hasUnknownMembers:lt(xt("boolean"),!1)}}),Xt("EnumBooleanMember",{aliases:["EnumMember"],visitor:["id","init"],fields:{id:ut("Identifier"),init:ut("BooleanLiteral")}}),Xt("EnumNumberMember",{aliases:["EnumMember"],visitor:["id","init"],fields:{id:ut("Identifier"),init:ut("NumericLiteral")}}),Xt("EnumStringMember",{aliases:["EnumMember"],visitor:["id","init"],fields:{id:ut("Identifier"),init:ut("StringLiteral")}}),Xt("EnumDefaultedMember",{aliases:["EnumMember"],visitor:["id"],fields:{id:ut("Identifier")}}),Xt("IndexedAccessType",{visitor:["objectType","indexType"],aliases:["FlowType"],fields:{objectType:ut("FlowType"),indexType:ut("FlowType")}}),Xt("OptionalIndexedAccessType",{visitor:["objectType","indexType"],aliases:["FlowType"],fields:{objectType:ut("FlowType"),indexType:ut("FlowType"),optional:lt(xt("boolean"),!1)}});var Qt=Pt("JSX");Qt("JSXAttribute",{visitor:["name","value"],aliases:["Immutable"],fields:{name:{validate:vt("JSXIdentifier","JSXNamespacedName")},value:{optional:!0,validate:vt("JSXElement","JSXFragment","StringLiteral","JSXExpressionContainer")}}}),Qt("JSXClosingElement",{visitor:["name"],aliases:["Immutable"],fields:{name:{validate:vt("JSXIdentifier","JSXMemberExpression","JSXNamespacedName")}}}),Qt("JSXElement",{builder:["openingElement","closingElement","children"],visitor:["openingElement","children","closingElement"],aliases:["Immutable","Expression"],fields:{openingElement:{validate:vt("JSXOpeningElement")},closingElement:{optional:!0,validate:vt("JSXClosingElement")},children:ht("JSXText","JSXExpressionContainer","JSXSpreadChild","JSXElement","JSXFragment")}}),Qt("JSXEmptyExpression",{}),Qt("JSXExpressionContainer",{visitor:["expression"],aliases:["Immutable"],fields:{expression:{validate:vt("Expression","JSXEmptyExpression")}}}),Qt("JSXSpreadChild",{visitor:["expression"],aliases:["Immutable"],fields:{expression:{validate:vt("Expression")}}}),Qt("JSXIdentifier",{builder:["name"],fields:{name:{validate:xt("string")}}}),Qt("JSXMemberExpression",{visitor:["object","property"],fields:{object:{validate:vt("JSXMemberExpression","JSXIdentifier")},property:{validate:vt("JSXIdentifier")}}}),Qt("JSXNamespacedName",{visitor:["namespace","name"],fields:{namespace:{validate:vt("JSXIdentifier")},name:{validate:vt("JSXIdentifier")}}}),Qt("JSXOpeningElement",{builder:["name","attributes","selfClosing"],visitor:["name","typeArguments","attributes"],aliases:["Immutable"],fields:{name:{validate:vt("JSXIdentifier","JSXMemberExpression","JSXNamespacedName")},selfClosing:{default:!1},attributes:ht("JSXAttribute","JSXSpreadAttribute"),typeArguments:{validate:vt("TypeParameterInstantiation","TSTypeParameterInstantiation"),optional:!0}}}),Qt("JSXSpreadAttribute",{visitor:["argument"],fields:{argument:{validate:vt("Expression")}}}),Qt("JSXText",{aliases:["Immutable"],builder:["value"],fields:{value:{validate:xt("string")}}}),Qt("JSXFragment",{builder:["openingFragment","closingFragment","children"],visitor:["openingFragment","children","closingFragment"],aliases:["Immutable","Expression"],fields:{openingFragment:{validate:vt("JSXOpeningFragment")},closingFragment:{validate:vt("JSXClosingFragment")},children:ht("JSXText","JSXExpressionContainer","JSXSpreadChild","JSXElement","JSXFragment")}}),Qt("JSXOpeningFragment",{aliases:["Immutable"]}),Qt("JSXClosingFragment",{aliases:["Immutable"]});for(var Zt=["Identifier","StringLiteral","Expression","Statement","Declaration","BlockStatement","ClassBody","Pattern"],er={Declaration:["Statement"],Pattern:["PatternLike","LVal"]},ar=0,nr=Zt;ar=Number.MAX_SAFE_INTEGER?Lh.uid=0:Lh.uid++};var qh=Function.call.bind(Object.prototype.toString);function Wh(e){if(void 0===e)return ai("undefined");if(!0===e||!1===e)return si(e);if(null===e)return{type:"NullLiteral"};if("string"==typeof e)return ri(e);if("number"==typeof e){var a;if(Number.isFinite(e))a=ii(Math.abs(e));else a=Or("/",Number.isNaN(e)?ii(0):ii(1),ii(0));return(e<0||Object.is(e,-0))&&(a=wi("-",a)),a}if("bigint"==typeof e)return e<0?wi("-",ro(-e)):ro(e);if(function(e){return"[object RegExp]"===qh(e)}(e))return di(e.source,/\/([a-z]*)$/.exec(e.toString())[1]);if(Array.isArray(e))return Nr(e.map(Wh));if(function(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;var a=Object.getPrototypeOf(e);return null===a||null===Object.getPrototypeOf(a)}(e)){for(var n=[],t=0,r=Object.keys(e);t1?e:e[0]}),cm=dm(function(e){return e}),lm=dm(function(e){if(0===e.length)throw new Error("Found nothing to return.");if(e.length>1)throw new Error("Found multiple statements but wanted one");return e[0]}),pm={code:function(e){return"(\n"+e+"\n)"},validate:function(e){if(e.program.body.length>1)throw new Error("Found multiple statements but wanted one");if(0===pm.unwrap(e).start)throw new Error("Parse result included parens.")},unwrap:function(e){var a=m(e.program.body,1)[0];return sm(a),a.expression}},gm=["placeholderAllowlist","placeholderPattern","preserveComments","syntacticPlaceholders"];function fm(e,a){var n=a.placeholderAllowlist,t=void 0===n?e.placeholderAllowlist:n,r=a.placeholderPattern,i=void 0===r?e.placeholderPattern:r,o=a.preserveComments,s=void 0===o?e.preserveComments:o,d=a.syntacticPlaceholders,u=void 0===d?e.syntacticPlaceholders:d;return{parser:Object.assign({},e.parser,a.parser),placeholderAllowlist:t,placeholderPattern:i,preserveComments:s,syntacticPlaceholders:u}}function hm(e){if(null!=e&&"object"!=typeof e)throw new Error("Unknown template options.");if(null!=e&&Object.hasOwn(e,"placeholderWhitelist")&&!Object.hasOwn(e,"placeholderAllowlist"))throw new Error("The 'placeholderWhitelist' option has been renamed to 'placeholderAllowlist'. Please update your configuration.");var a=e||{},n=a.placeholderAllowlist,t=a.placeholderPattern,r=a.preserveComments,i=a.syntacticPlaceholders,o=l(a,gm);if(null!=n&&!(n instanceof Set))throw new Error("'.placeholderAllowlist' must be a Set, null, or undefined");if(null!=t&&!(t instanceof RegExp)&&!1!==t)throw new Error("'.placeholderPattern' must be a RegExp, false, null, or undefined");if(null!=r&&"boolean"!=typeof r)throw new Error("'.preserveComments' must be a boolean, null, or undefined");if(null!=i&&"boolean"!=typeof i)throw new Error("'.syntacticPlaceholders' must be a boolean, null, or undefined");if(!0===i&&(null!=n||null!=t))throw new Error("'.placeholderAllowlist' and '.placeholderPattern' aren't compatible with '.syntacticPlaceholders: true'");return{parser:o,placeholderAllowlist:n||void 0,placeholderPattern:null==t?void 0:t,preserveComments:null==r?void 0:r,syntacticPlaceholders:null==i?void 0:i}}function mm(e){if(Array.isArray(e))return e.reduce(function(e,a,n){return e["$"+n]=a,e},{});if("object"==typeof e||null==e)return e||void 0;throw new Error("Template replacements must be an array, object, null, or undefined")}var Rm=i(function(e,a,n){this.line=void 0,this.column=void 0,void 0!==n&&(this.index=void 0),this.line=e,this.column=a,void 0!==n&&(this.index=n)}),ym=i(function(e,a){this.start=void 0,this.end=void 0,this.filename=void 0,this.identifierName=void 0,this.start=e,this.end=a});function vm(e,a){var n=e.line,t=e.column,r=e.index;return new Rm(n,t+a,r+a)}var bm,xm,Sm="BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED",Em={ImportMetaOutsideModule:{message:"import.meta may appear only with 'sourceType: \"module\"'",code:Sm},ImportOutsideModule:{message:"'import' and 'export' may appear only with 'sourceType: \"module\"'",code:Sm}},Tm={ArrayPattern:"array destructuring pattern",AssignmentExpression:"assignment expression",AssignmentPattern:"assignment expression",ArrowFunctionExpression:"arrow function expression",ConditionalExpression:"conditional expression",CatchClause:"catch clause",ForOfStatement:"for-of statement",ForInStatement:"for-in statement",ForStatement:"for-loop",FormalParameters:"function parameter list",Identifier:"identifier",ImportSpecifier:"import specifier",ImportDefaultSpecifier:"import default specifier",ImportNamespaceSpecifier:"import namespace specifier",ObjectPattern:"object destructuring pattern",ParenthesizedExpression:"parenthesized expression",RestElement:"rest element",UpdateExpression:{true:"prefix operation",false:"postfix operation"},VariableDeclarator:"variable declaration",YieldExpression:"yield expression"},wm=function(e){return"UpdateExpression"===e.type?Tm.UpdateExpression[""+e.prefix]:Tm[e.type]},Cm={AccessorIsGenerator:function(e){return"A "+e.kind+"ter cannot be a generator."},ArgumentsInClass:"'arguments' is only allowed in functions and class methods.",AsyncFunctionInSingleStatementContext:"Async functions can only be declared at the top level or inside a block.",AwaitBindingIdentifier:"Can not use 'await' as identifier inside an async function.",AwaitBindingIdentifierInStaticBlock:"Can not use 'await' as identifier inside a static block.",AwaitExpressionFormalParameter:"'await' is not allowed in async function parameters.",AwaitUsingNotInAsyncContext:"'await using' is only allowed within async functions and at the top levels of modules.",AwaitNotInAsyncContext:"'await' is only allowed within async functions and at the top levels of modules.",BadGetterArity:"A 'get' accessor must not have any formal parameters.",BadSetterArity:"A 'set' accessor must have exactly one formal parameter.",BadSetterRestParameter:"A 'set' accessor function argument must not be a rest parameter.",ConstructorClassField:"Classes may not have a field named 'constructor'.",ConstructorClassPrivateField:"Classes may not have a private field named '#constructor'.",ConstructorIsAccessor:"Class constructor may not be an accessor.",ConstructorIsAsync:"Constructor can't be an async function.",ConstructorIsGenerator:"Constructor can't be a generator.",DeclarationMissingInitializer:function(e){return"Missing initializer in "+e.kind+" declaration."},DecoratorArgumentsOutsideParentheses:"Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.",DecoratorsBeforeAfterExport:"Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.",DecoratorConstructor:"Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",DecoratorSemicolon:"Decorators must not be followed by a semicolon.",DecoratorStaticBlock:"Decorators can't be used with a static block.",DeferImportRequiresNamespace:'Only `import defer * as x from "./module"` is valid.',DeletePrivateField:"Deleting a private field is not allowed.",DestructureNamedImport:"ES2015 named imports do not destructure. Use another statement for destructuring after the import.",DuplicateConstructor:"Duplicate constructor in the same class.",DuplicateDefaultExport:"Only one default export allowed per module.",DuplicateExport:function(e){return"`"+e.exportName+"` has already been exported. Exported identifiers must be unique."},DuplicateProto:"Redefinition of __proto__ property.",DuplicateRegExpFlags:"Duplicate regular expression flag.",ElementAfterRest:"Rest element must be last element.",EscapedCharNotAnIdentifier:"Invalid Unicode escape.",ExportBindingIsString:function(e){return"A string literal cannot be used as an exported binding without `from`.\n- Did you mean `export { '"+e.localName+"' as '"+e.exportName+"' } from 'some-module'`?"},ExportDefaultFromAsIdentifier:"'from' is not allowed as an identifier after 'export default'.",ForInOfLoopInitializer:function(e){return"'"+("ForInStatement"===e.type?"for-in":"for-of")+"' loop variable declaration may not have an initializer."},ForInUsing:"For-in loop may not start with 'using' declaration.",ForOfAsync:"The left-hand side of a for-of loop may not be 'async'.",ForOfLet:"The left-hand side of a for-of loop may not start with 'let'.",GeneratorInSingleStatementContext:"Generators can only be declared at the top level or inside a block.",IllegalBreakContinue:function(e){return"Unsyntactic "+("BreakStatement"===e.type?"break":"continue")+"."},IllegalLanguageModeDirective:"Illegal 'use strict' directive in function with non-simple parameter list.",IllegalReturn:"'return' outside of function.",ImportBindingIsString:function(e){return'A string literal cannot be used as an imported binding.\n- Did you mean `import { "'+e.importName+'" as foo }`?'},ImportCallArity:function(e){var a=e.phase;return"`import"+(a?"."+a:"")+"()` requires exactly one or two arguments."},ImportCallNotNewExpression:function(e){var a=e.phase;return"Cannot use new with import"+(a?"."+a:"")+"()."},ImportCallSpreadArgument:function(e){var a=e.phase;return"`...` is not allowed in `import"+(a?"."+a:"")+"()`."},IncompatibleRegExpUVFlags:"The 'u' and 'v' regular expression flags cannot be enabled at the same time.",InvalidBigIntLiteral:"Invalid BigIntLiteral.",InvalidCodePoint:"Code point out of bounds.",InvalidCoverDiscardElement:"'void' must be followed by an expression when not used in a binding position.",InvalidCoverInitializedName:"Invalid shorthand property initializer.",InvalidDigit:function(e){return"Expected number in radix "+e.radix+"."},InvalidEscapeSequence:"Bad character escape sequence.",InvalidEscapeSequenceTemplate:"Invalid escape sequence in template.",InvalidEscapedReservedWord:function(e){return"Escape sequence in keyword "+e.reservedWord+"."},InvalidIdentifier:function(e){return"Invalid identifier "+e.identifierName+"."},InvalidLhs:function(e){var a=e.ancestor;return"Invalid left-hand side in "+wm(a)+"."},InvalidLhsBinding:function(e){var a=e.ancestor;return"Binding invalid left-hand side in "+wm(a)+"."},InvalidLhsOptionalChaining:function(e){var a=e.ancestor;return"Invalid optional chaining in the left-hand side of "+wm(a)+"."},InvalidNumber:"Invalid number.",InvalidOrMissingExponent:"Floating-point numbers require a valid exponent after the 'e'.",InvalidOrUnexpectedToken:function(e){return"Unexpected character '"+e.unexpected+"'."},InvalidParenthesizedAssignment:"Invalid parenthesized assignment pattern.",InvalidPrivateFieldResolution:function(e){return"Private name #"+e.identifierName+" is not defined."},InvalidPropertyBindingPattern:"Binding member expression.",InvalidRestAssignmentPattern:"Invalid rest operator's argument.",LabelRedeclaration:function(e){return"Label '"+e.labelName+"' is already declared."},LetInLexicalBinding:"'let' is disallowed as a lexically bound name.",LineTerminatorBeforeArrow:"No line break is allowed before '=>'.",MalformedRegExpFlags:"Invalid regular expression flag.",MissingClassName:"A class name is required.",MissingEqInAssignment:"Only '=' operator can be used for specifying default value.",MissingSemicolon:"Missing semicolon.",MissingPlugin:function(e){return"This experimental syntax requires enabling the parser plugin: "+e.missingPlugin.map(function(e){return JSON.stringify(e)}).join(", ")+"."},MissingOneOfPlugins:function(e){return"This experimental syntax requires enabling one of the following parser plugin(s): "+e.missingPlugin.map(function(e){return JSON.stringify(e)}).join(", ")+"."},MissingUnicodeEscape:"Expecting Unicode escape sequence \\uXXXX.",MixingCoalesceWithLogical:"Nullish coalescing operator(??) requires parens when mixing with logical operators.",ModuleAttributeInvalidValue:"Only string literals are allowed as module attribute values.",ModuleAttributesWithDuplicateKeys:function(e){return'Duplicate key "'+e.key+'" is not allowed in module attributes.'},ModuleExportNameHasLoneSurrogate:function(e){return"An export name cannot include a lone surrogate, found '\\u"+e.surrogateCharCode.toString(16)+"'."},ModuleExportUndefined:function(e){return"Export '"+e.localName+"' is not defined."},MultipleDefaultsInSwitch:"Multiple default clauses.",NewlineAfterThrow:"Illegal newline after throw.",NoCatchOrFinally:"Missing catch or finally clause.",NumberIdentifier:"Identifier directly after number.",NumericSeparatorInEscapeSequence:"Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",ObsoleteAwaitStar:"'await*' has been removed from the async functions proposal. Use Promise.all() instead.",OptionalChainingNoNew:"Constructors in/after an Optional Chain are not allowed.",OptionalChainingNoTemplate:"Tagged Template Literals are not allowed in optionalChain.",OverrideOnConstructor:"'override' modifier cannot appear on a constructor declaration.",ParamDupe:"Argument name clash.",PatternHasAccessor:"Object pattern can't contain getter or setter.",PatternHasMethod:"Object pattern can't contain methods.",PrivateInExpectedIn:function(e){var a=e.identifierName;return"Private names are only allowed in property accesses (`obj.#"+a+"`) or in `in` expressions (`#"+a+" in obj`)."},PrivateNameRedeclaration:function(e){return"Duplicate private name #"+e.identifierName+"."},RestTrailingComma:"Unexpected trailing comma after rest element.",SloppyFunction:"In non-strict mode code, functions can only be declared at top level or inside a block.",SloppyFunctionAnnexB:"In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.",SourcePhaseImportRequiresDefault:'Only `import source x from "./module"` is valid.',StaticPrototype:"Classes may not have static property named prototype.",SuperCallNotNewExpression:"Cannot use new with super(...).",SuperNotAllowed:"`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?",SuperPrivateField:"Private fields can't be accessed on super.",TrailingDecorator:"Decorators must be attached to a class element.",UnexpectedArgumentPlaceholder:"Unexpected argument placeholder.",UnexpectedDigitAfterHash:"Unexpected digit after hash token.",UnexpectedImportExport:"'import' and 'export' may only appear at the top level.",UnexpectedKeyword:function(e){return"Unexpected keyword '"+e.keyword+"'."},UnexpectedLeadingDecorator:"Leading decorators must be attached to a class declaration.",UnexpectedLexicalDeclaration:"Lexical declaration cannot appear in a single-statement context.",UnexpectedNewTarget:"`new.target` can only be used in functions or class properties.",UnexpectedNumericSeparator:"A numeric separator is only allowed between two digits.",UnexpectedPrivateField:"Unexpected private name.",UnexpectedReservedWord:function(e){return"Unexpected reserved word '"+e.reservedWord+"'."},UnexpectedSuper:"'super' is only allowed in object methods and classes.",UnexpectedToken:function(e){var a=e.expected,n=e.unexpected;return"Unexpected token"+(n?" '"+n+"'.":"")+(a?', expected "'+a+'"':"")},UnexpectedTokenUnaryExponentiation:"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",UnexpectedUsingDeclaration:"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement.",UnexpectedVoidPattern:"Unexpected void binding.",UnsupportedDecoratorExport:"A decorated export must export a class declaration.",UnsupportedDefaultExport:"Only expressions, functions or classes are allowed as the `default` export.",UnsupportedImport:"`import` can only be used in `import()` or `import.meta`.",UnsupportedMetaProperty:function(e){var a=e.target;return"The only valid meta property for "+a+" is "+a+"."+e.onlyValidPropertyName+"."},UnsupportedParameterDecorator:"Decorators cannot be used to decorate parameters.",UnsupportedPropertyDecorator:"Decorators cannot be used to decorate object literal properties.",UnsupportedSuper:"'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).",UnterminatedComment:"Unterminated comment.",UnterminatedRegExp:"Unterminated regular expression.",UnterminatedString:"Unterminated string constant.",UnterminatedTemplate:"Unterminated template.",UsingDeclarationExport:"Using declaration cannot be exported.",UsingDeclarationHasBindingPattern:"Using declaration cannot have destructuring patterns.",VarRedeclaration:function(e){return"Identifier '"+e.identifierName+"' has already been declared."},VoidPatternCatchClauseParam:"A void binding can not be the catch clause parameter. Use `try { ... } catch { ... }` if you want to discard the caught error.",VoidPatternInitializer:"A void binding may not have an initializer.",YieldBindingIdentifier:"Can not use 'yield' as identifier inside a generator.",YieldInParameter:"Yield expression is not allowed in formal parameters.",YieldNotInGeneratorFunction:"'yield' is only allowed within generator functions.",ZeroDigitNumericSeparator:"Numeric separator can not be used after leading 0."},Pm={ParseExpressionEmptyInput:"Unexpected parseExpression() input: The input is empty or contains only comments.",ParseExpressionExpectsEOF:function(e){var a=e.unexpected;return"Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character `"+String.fromCodePoint(a)+"`."}},Am=new Set(["ArrowFunctionExpression","AssignmentExpression","ConditionalExpression","YieldExpression"]),_m={PipeTopicRequiresHackPipes:'Topic references are only supported when using the `"proposal": "hack"` version of the pipeline proposal.',PipeTopicUnbound:"Topic reference is unbound; it must be inside a pipe body.",PipeTopicUnconfiguredToken:function(e){var a=e.token;return"Invalid topic token "+a+". In order to use "+a+' as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "'+a+'" }.'},PipeTopicUnused:"Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",PipeUnparenthesizedBody:function(e){var a=e.type;return"Hack-style pipe body cannot be an unparenthesized "+wm({type:a})+"; please wrap it in parentheses."},PipelineUnparenthesized:"Cannot mix binary operator with solo-await F#-style pipeline. Please wrap the pipeline in parentheses."},Dm=["message"];function km(e,a,n){Object.defineProperty(e,a,{enumerable:!1,configurable:!0,value:n})}function Im(e,a){if(Array.isArray(e))return function(a){return Im(a,e[0])};for(var n={},t=function(){var t=i[r],o=e[t],s="string"==typeof o?{message:function(){return o}}:"function"==typeof o?{message:o}:o,d=s.message,u=l(s,Dm),c="string"==typeof d?function(){return d}:d;n[t]=function(e){var a=e.toMessage,n=e.code,t=e.reasonCode,r=e.syntaxPlugin,i="MissingPlugin"===t||"MissingOneOfPlugins"===t;return function e(o,s,d){var u=new SyntaxError;return u.code=n,u.reasonCode=t,u.loc=o,u.pos=s,u.syntaxPlugin=r,i&&(u.missingPlugin=d.missingPlugin),km(u,"clone",function(a){var n;void 0===a&&(a={});var t=null!=(n=a.loc)?n:o,r=t.line,i=t.column,u=t.index,c=void 0===u?s:u;return e(new Rm(r,i),c,Object.assign({},d,a.details))}),km(u,"details",d),Object.defineProperty(u,"message",{configurable:!0,get:function(){var e=a(d)+" ("+o.line+":"+o.column+")";return this.message=e,e},set:function(e){Object.defineProperty(this,"message",{value:e,writable:!0})}}),u}}(Object.assign({code:"BABEL_PARSER_SYNTAX_ERROR",reasonCode:t,toMessage:c},a?{syntaxPlugin:a}:{},u))},r=0,i=Object.keys(e);r",{beforeExpr:Ym}),template:pR("template"),ellipsis:pR("...",{beforeExpr:Ym}),backQuote:pR("`",{startsExpr:$m}),dollarBraceL:pR("${",{beforeExpr:Ym,startsExpr:$m}),templateTail:pR("...`",{startsExpr:$m}),templateNonTail:pR("...${",{beforeExpr:Ym,startsExpr:$m}),at:pR("@"),hash:pR("#",{startsExpr:$m}),interpreterDirective:pR("#!..."),eq:pR("=",{beforeExpr:Ym,isAssign:Zm}),assign:pR("_=",{beforeExpr:Ym,isAssign:Zm}),slashAssign:pR("_=",{beforeExpr:Ym,isAssign:Zm}),xorAssign:pR("_=",{beforeExpr:Ym,isAssign:Zm}),moduloAssign:pR("_=",{beforeExpr:Ym,isAssign:Zm}),incDec:pR("++/--",{prefix:eR,postfix:!0,startsExpr:$m}),bang:pR("!",{beforeExpr:Ym,prefix:eR,startsExpr:$m}),tilde:pR("~",{beforeExpr:Ym,prefix:eR,startsExpr:$m}),doubleCaret:pR("^^",{startsExpr:$m}),doubleAt:pR("@@",{startsExpr:$m}),pipeline:rR("|>",0),nullishCoalescing:rR("??",1),logicalOR:rR("||",1),logicalAND:rR("&&",2),bitwiseOR:rR("|",3),bitwiseXOR:rR("^",4),bitwiseAND:rR("&",5),equality:rR("==/!=/===/!==",6),lt:rR("/<=/>=",7),gt:rR("/<=/>=",7),relational:rR("/<=/>=",7),bitShift:rR("<>/>>>",8),bitShiftL:rR("<>/>>>",8),bitShiftR:rR("<>/>>>",8),plusMin:pR("+/-",{beforeExpr:Ym,binop:9,prefix:eR,startsExpr:$m}),modulo:pR("%",{binop:10,startsExpr:$m}),star:pR("*",{binop:10}),slash:rR("/",10),exponent:pR("**",{beforeExpr:Ym,binop:11,rightAssociative:!0}),_in:tR("in",{beforeExpr:Ym,binop:7}),_instanceof:tR("instanceof",{beforeExpr:Ym,binop:7}),_break:tR("break"),_case:tR("case",{beforeExpr:Ym}),_catch:tR("catch"),_continue:tR("continue"),_debugger:tR("debugger"),_default:tR("default",{beforeExpr:Ym}),_else:tR("else",{beforeExpr:Ym}),_finally:tR("finally"),_function:tR("function",{startsExpr:$m}),_if:tR("if"),_return:tR("return",{beforeExpr:Ym}),_switch:tR("switch"),_throw:tR("throw",{beforeExpr:Ym,prefix:eR,startsExpr:$m}),_try:tR("try"),_var:tR("var"),_const:tR("const"),_with:tR("with"),_new:tR("new",{beforeExpr:Ym,startsExpr:$m}),_this:tR("this",{startsExpr:$m}),_super:tR("super",{startsExpr:$m}),_class:tR("class",{startsExpr:$m}),_extends:tR("extends",{beforeExpr:Ym}),_export:tR("export"),_import:tR("import",{startsExpr:$m}),_null:tR("null",{startsExpr:$m}),_true:tR("true",{startsExpr:$m}),_false:tR("false",{startsExpr:$m}),_typeof:tR("typeof",{beforeExpr:Ym,prefix:eR,startsExpr:$m}),_void:tR("void",{beforeExpr:Ym,prefix:eR,startsExpr:$m}),_delete:tR("delete",{beforeExpr:Ym,prefix:eR,startsExpr:$m}),_do:tR("do",{isLoop:Qm,beforeExpr:Ym}),_for:tR("for",{isLoop:Qm}),_while:tR("while",{isLoop:Qm}),_as:gR("as",{startsExpr:$m}),_assert:gR("assert",{startsExpr:$m}),_async:gR("async",{startsExpr:$m}),_await:gR("await",{startsExpr:$m}),_defer:gR("defer",{startsExpr:$m}),_from:gR("from",{startsExpr:$m}),_get:gR("get",{startsExpr:$m}),_let:gR("let",{startsExpr:$m}),_meta:gR("meta",{startsExpr:$m}),_of:gR("of",{startsExpr:$m}),_sent:gR("sent",{startsExpr:$m}),_set:gR("set",{startsExpr:$m}),_source:gR("source",{startsExpr:$m}),_static:gR("static",{startsExpr:$m}),_using:gR("using",{startsExpr:$m}),_yield:gR("yield",{startsExpr:$m}),_asserts:gR("asserts",{startsExpr:$m}),_checks:gR("checks",{startsExpr:$m}),_exports:gR("exports",{startsExpr:$m}),_global:gR("global",{startsExpr:$m}),_implements:gR("implements",{startsExpr:$m}),_intrinsic:gR("intrinsic",{startsExpr:$m}),_infer:gR("infer",{startsExpr:$m}),_is:gR("is",{startsExpr:$m}),_mixins:gR("mixins",{startsExpr:$m}),_proto:gR("proto",{startsExpr:$m}),_require:gR("require",{startsExpr:$m}),_satisfies:gR("satisfies",{startsExpr:$m}),_keyof:gR("keyof",{startsExpr:$m}),_readonly:gR("readonly",{startsExpr:$m}),_unique:gR("unique",{startsExpr:$m}),_abstract:gR("abstract",{startsExpr:$m}),_declare:gR("declare",{startsExpr:$m}),_enum:gR("enum",{startsExpr:$m}),_module:gR("module",{startsExpr:$m}),_namespace:gR("namespace",{startsExpr:$m}),_interface:gR("interface",{startsExpr:$m}),_type:gR("type",{startsExpr:$m}),_opaque:gR("opaque",{startsExpr:$m}),name:pR("name",{startsExpr:$m}),placeholder:pR("%%",{startsExpr:$m}),string:pR("string",{startsExpr:$m}),num:pR("num",{startsExpr:$m}),bigint:pR("bigint",{startsExpr:$m}),regexp:pR("regexp",{startsExpr:$m}),privateName:pR("#name",{startsExpr:$m}),eof:pR("eof"),jsxName:pR("jsxName"),jsxText:pR("jsxText",{beforeExpr:Ym}),jsxTagStart:pR("jsxTagStart",{startsExpr:$m}),jsxTagEnd:pR("jsxTagEnd")};function hR(e){return e>=89&&e<=129}function mR(e){return e>=54&&e<=129}function RR(e){return e>=54&&e<=132}function yR(e){return cR[e]}function vR(e){return e>=125&&e<=127}function bR(e){return e>=54&&e<=88}function xR(e){return e>=35&&e<=55}function SR(e){return 30===e}function ER(e){return sR[e]}function TR(e){return dR[e]}function wR(e){return e>=20&&e<=21}function CR(e){return oR[e]}var PR=i(function(e,a){this.token=void 0,this.preserveSpace=void 0,this.token=e,this.preserveSpace=!!a}),AR={brace:new PR("{"),j_oTag:new PR("...",!0)};var _R=new Set(["break","case","catch","continue","debugger","default","do","else","finally","for","function","if","return","switch","throw","try","var","const","while","with","new","this","super","class","extends","export","import","null","true","false","in","instanceof","typeof","void","delete","implements","interface","let","package","private","protected","public","static","yield","eval","arguments","enum","await"]);var DR,kR=0,IR=1,BR=2,NR=4,jR=8,OR=16,FR=32,MR=64,LR=128,UR=256,qR=512,WR=1024,VR=2048,HR=514,GR=576,KR=3715,JR=1,zR=2,XR=4,YR=8,$R=16,QR=128,ZR=256,ey=512,ay=1024,ny=2048,ty=4096,ry=8192,iy=8331,oy=8201,sy=9,dy=5,uy=17,cy=130,ly=2,py=8459,gy=1024,fy=64,hy=65,my=8971,Ry=1024,yy=4098,vy=4096,by=2048,xy=0,Sy=4,Ey=3,Ty=6,wy=5,Cy=2,Py=1,Ay=1,_y=2,Dy=4,ky=i(function(e){this.flags=0,this.names=new Map,this.firstLexicalName="",this.flags=e}),Iy=function(){function e(e,a){this.parser=void 0,this.scopeStack=[],this.inModule=void 0,this.undefinedExports=new Map,this.parser=e,this.inModule=a}var a=e.prototype;return a.createScope=function(e){return new ky(e)},a.enter=function(e){this.scopeStack.push(this.createScope(e))},a.exit=function(){return this.scopeStack.pop().flags},a.treatFunctionsAsVarInScope=function(e){return!!(e.flags&(BR|LR)||!this.parser.inModule&&e.flags&IR)},a.declareName=function(e,a,n){var t=this.currentScope();if(a&YR||a&$R){this.checkRedeclarationInScope(t,e,a,n);var r=t.names.get(e)||0;a&$R?r|=Dy:(t.firstLexicalName||(t.firstLexicalName=e),r|=_y),t.names.set(e,r),a&YR&&this.maybeExportDefined(t,e)}else if(a&XR)for(var i=this.scopeStack.length-1;i>=0&&(t=this.scopeStack[i],this.checkRedeclarationInScope(t,e,a,n),t.names.set(e,(t.names.get(e)||0)|Ay),this.maybeExportDefined(t,e),!(t.flags&KR));--i);this.parser.inModule&&t.flags&IR&&this.undefinedExports.delete(e)},a.maybeExportDefined=function(e,a){this.parser.inModule&&e.flags&IR&&this.undefinedExports.delete(a)},a.checkRedeclarationInScope=function(e,a,n,t){this.isRedeclaredInScope(e,a,n)&&this.parser.raise(Bm.VarRedeclaration,t,{identifierName:a})},a.isRedeclaredInScope=function(e,a,n){if(!(n&JR))return!1;if(n&YR)return e.names.has(a);var t=e.names.get(a)||0;return n&$R?(t&_y)>0||!this.treatFunctionsAsVarInScope(e)&&(t&Ay)>0:(t&_y)>0&&!(e.flags&jR&&e.firstLexicalName===a)||!this.treatFunctionsAsVarInScope(e)&&(t&Dy)>0},a.checkLocalExport=function(e){var a=e.name;this.scopeStack[0].names.has(a)||this.undefinedExports.set(a,e.start)},a.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},a.currentVarScopeFlags=function(){for(var e=this.scopeStack.length-1;;e--){var a=this.scopeStack[e].flags;if(a&KR)return a}},a.currentThisScopeFlags=function(){for(var e=this.scopeStack.length-1;;e--){var a=this.scopeStack[e].flags;if(a&(KR|MR)&&!(a&NR))return a}},i(e,[{key:"inTopLevel",get:function(){return(this.currentScope().flags&IR)>0}},{key:"inFunction",get:function(){return(this.currentVarScopeFlags()&BR)>0}},{key:"allowSuper",get:function(){return(this.currentThisScopeFlags()&OR)>0}},{key:"allowDirectSuper",get:function(){return(this.currentThisScopeFlags()&FR)>0}},{key:"allowNewTarget",get:function(){return(this.currentThisScopeFlags()&qR)>0}},{key:"inClass",get:function(){return(this.currentThisScopeFlags()&MR)>0}},{key:"inClassAndNotInNonArrowFunction",get:function(){var e=this.currentThisScopeFlags();return(e&MR)>0&&0===(e&BR)}},{key:"inStaticBlock",get:function(){for(var e=this.scopeStack.length-1;;e--){var a=this.scopeStack[e].flags;if(a&LR)return!0;if(a&(KR|MR))return!1}}},{key:"inNonArrowFunction",get:function(){return(this.currentThisScopeFlags()&BR)>0}},{key:"inBareCaseStatement",get:function(){return(this.currentScope().flags&UR)>0}},{key:"treatFunctionsAsVar",get:function(){return this.treatFunctionsAsVarInScope(this.currentScope())}}])}(),By=function(e){function a(){for(var a,n=arguments.length,t=new Array(n),r=0;r0||(r&_y)>0}return!1},n.checkLocalExport=function(a){this.scopeStack[0].declareFunctions.has(a.name)||e.prototype.checkLocalExport.call(this,a)},i(a)}(Iy),jy=new Set(["_","any","bool","boolean","empty","extends","false","interface","mixed","null","number","static","string","true","typeof","void"]),Oy=Im(DR||(DR=R(["flow"])))({AmbiguousConditionalArrow:"Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",AmbiguousDeclareModuleKind:"Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.",AssignReservedType:function(e){return"Cannot overwrite reserved type "+e.reservedType+"."},DeclareClassElement:"The `declare` modifier can only appear on class fields.",DeclareClassFieldInitializer:"Initializers are not allowed in fields with the `declare` modifier.",DuplicateDeclareModuleExports:"Duplicate `declare module.exports` statement.",EnumBooleanMemberNotInitialized:function(e){var a=e.memberName;return"Boolean enum members need to be initialized. Use either `"+a+" = true,` or `"+a+" = false,` in enum `"+e.enumName+"`."},EnumDuplicateMemberName:function(e){return"Enum member names need to be unique, but the name `"+e.memberName+"` has already been used before in enum `"+e.enumName+"`."},EnumInconsistentMemberValues:function(e){return"Enum `"+e.enumName+"` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers."},EnumInvalidExplicitType:function(e){return"Enum type `"+e.invalidEnumType+"` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `"+e.enumName+"`."},EnumInvalidExplicitTypeUnknownSupplied:function(e){return"Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `"+e.enumName+"`."},EnumInvalidMemberInitializerPrimaryType:function(e){var a=e.enumName,n=e.memberName,t=e.explicitType;return"Enum `"+a+"` has type `"+t+"`, so the initializer of `"+n+"` needs to be a "+t+" literal."},EnumInvalidMemberInitializerSymbolType:function(e){var a=e.enumName;return"Symbol enum members cannot be initialized. Use `"+e.memberName+",` in enum `"+a+"`."},EnumInvalidMemberInitializerUnknownType:function(e){var a=e.enumName;return"The enum member initializer for `"+e.memberName+"` needs to be a literal (either a boolean, number, or string) in enum `"+a+"`."},EnumInvalidMemberName:function(e){var a=e.enumName;return"Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `"+e.memberName+"`, consider using `"+e.suggestion+"`, in enum `"+a+"`."},EnumNumberMemberNotInitialized:function(e){var a=e.enumName;return"Number enum members need to be initialized, e.g. `"+e.memberName+" = 1` in enum `"+a+"`."},EnumStringMemberInconsistentlyInitialized:function(e){return"String enum members need to consistently either all use initializers, or use no initializers, in enum `"+e.enumName+"`."},GetterMayNotHaveThisParam:"A getter cannot have a `this` parameter.",ImportTypeShorthandOnlyInPureImport:"The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.",InexactInsideExact:"Explicit inexact syntax cannot appear inside an explicit exact object type.",InexactInsideNonObject:"Explicit inexact syntax cannot appear in class or interface definitions.",InexactVariance:"Explicit inexact syntax cannot have variance.",InvalidNonTypeImportInDeclareModule:"Imports within a `declare module` body must always be `import type` or `import typeof`.",MissingTypeParamDefault:"Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",NestedDeclareModule:"`declare module` cannot be used inside another `declare module`.",NestedFlowComment:"Cannot have a flow comment inside another flow comment.",PatternIsOptional:{message:"A binding pattern parameter cannot be optional in an implementation signature."},SetterMayNotHaveThisParam:"A setter cannot have a `this` parameter.",SpreadVariance:"Spread properties cannot have variance.",ThisParamAnnotationRequired:"A type annotation is required for the `this` parameter.",ThisParamBannedInConstructor:"Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",ThisParamMayNotBeOptional:"The `this` parameter cannot be optional.",ThisParamMustBeFirst:"The `this` parameter must be the first function parameter.",ThisParamNoDefault:"The `this` parameter may not have a default value.",TypeBeforeInitializer:"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",TypeCastInPattern:"The type cast expression is expected to be wrapped with parenthesis.",UnexpectedExplicitInexactInObject:"Explicit inexact syntax must appear at the end of an inexact object.",UnexpectedReservedType:function(e){return"Unexpected reserved type "+e.reservedType+"."},UnexpectedReservedUnderscore:"`_` is only allowed as a type argument to call or new.",UnexpectedSpaceBetweenModuloChecks:"Spaces between `%` and `checks` are not allowed here.",UnexpectedSpreadType:"Spread operator cannot appear in class or interface definitions.",UnexpectedSubtractionOperand:'Unexpected token, expected "number" or "bigint".',UnexpectedTokenAfterTypeParameter:"Expected an arrow function after this type parameter declaration.",UnexpectedTypeParameterBeforeAsyncArrowFunction:"Type parameters must come after the async keyword, e.g. instead of ` async () => {}`, use `async () => {}`.",UnsupportedDeclareExportKind:function(e){return"`declare export "+e.unsupportedExportKind+"` is not supported. Use `"+e.suggestion+"` instead."},UnsupportedStatementInDeclareModule:"Only declares and type imports are allowed inside declare module.",UnterminatedFlowComment:"Unterminated flow-comment."});function Fy(e){return"type"===e.importKind||"typeof"===e.importKind}var My={const:"declare export var",let:"declare export var",type:"export type",interface:"export interface"};var Ly=/\*?\s*@((?:no)?flow)\b/,Uy={__proto__:null,quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:"\xa0",iexcl:"\xa1",cent:"\xa2",pound:"\xa3",curren:"\xa4",yen:"\xa5",brvbar:"\xa6",sect:"\xa7",uml:"\xa8",copy:"\xa9",ordf:"\xaa",laquo:"\xab",not:"\xac",shy:"\xad",reg:"\xae",macr:"\xaf",deg:"\xb0",plusmn:"\xb1",sup2:"\xb2",sup3:"\xb3",acute:"\xb4",micro:"\xb5",para:"\xb6",middot:"\xb7",cedil:"\xb8",sup1:"\xb9",ordm:"\xba",raquo:"\xbb",frac14:"\xbc",frac12:"\xbd",frac34:"\xbe",iquest:"\xbf",Agrave:"\xc0",Aacute:"\xc1",Acirc:"\xc2",Atilde:"\xc3",Auml:"\xc4",Aring:"\xc5",AElig:"\xc6",Ccedil:"\xc7",Egrave:"\xc8",Eacute:"\xc9",Ecirc:"\xca",Euml:"\xcb",Igrave:"\xcc",Iacute:"\xcd",Icirc:"\xce",Iuml:"\xcf",ETH:"\xd0",Ntilde:"\xd1",Ograve:"\xd2",Oacute:"\xd3",Ocirc:"\xd4",Otilde:"\xd5",Ouml:"\xd6",times:"\xd7",Oslash:"\xd8",Ugrave:"\xd9",Uacute:"\xda",Ucirc:"\xdb",Uuml:"\xdc",Yacute:"\xdd",THORN:"\xde",szlig:"\xdf",agrave:"\xe0",aacute:"\xe1",acirc:"\xe2",atilde:"\xe3",auml:"\xe4",aring:"\xe5",aelig:"\xe6",ccedil:"\xe7",egrave:"\xe8",eacute:"\xe9",ecirc:"\xea",euml:"\xeb",igrave:"\xec",iacute:"\xed",icirc:"\xee",iuml:"\xef",eth:"\xf0",ntilde:"\xf1",ograve:"\xf2",oacute:"\xf3",ocirc:"\xf4",otilde:"\xf5",ouml:"\xf6",divide:"\xf7",oslash:"\xf8",ugrave:"\xf9",uacute:"\xfa",ucirc:"\xfb",uuml:"\xfc",yacute:"\xfd",thorn:"\xfe",yuml:"\xff",OElig:"\u0152",oelig:"\u0153",Scaron:"\u0160",scaron:"\u0161",Yuml:"\u0178",fnof:"\u0192",circ:"\u02c6",tilde:"\u02dc",Alpha:"\u0391",Beta:"\u0392",Gamma:"\u0393",Delta:"\u0394",Epsilon:"\u0395",Zeta:"\u0396",Eta:"\u0397",Theta:"\u0398",Iota:"\u0399",Kappa:"\u039a",Lambda:"\u039b",Mu:"\u039c",Nu:"\u039d",Xi:"\u039e",Omicron:"\u039f",Pi:"\u03a0",Rho:"\u03a1",Sigma:"\u03a3",Tau:"\u03a4",Upsilon:"\u03a5",Phi:"\u03a6",Chi:"\u03a7",Psi:"\u03a8",Omega:"\u03a9",alpha:"\u03b1",beta:"\u03b2",gamma:"\u03b3",delta:"\u03b4",epsilon:"\u03b5",zeta:"\u03b6",eta:"\u03b7",theta:"\u03b8",iota:"\u03b9",kappa:"\u03ba",lambda:"\u03bb",mu:"\u03bc",nu:"\u03bd",xi:"\u03be",omicron:"\u03bf",pi:"\u03c0",rho:"\u03c1",sigmaf:"\u03c2",sigma:"\u03c3",tau:"\u03c4",upsilon:"\u03c5",phi:"\u03c6",chi:"\u03c7",psi:"\u03c8",omega:"\u03c9",thetasym:"\u03d1",upsih:"\u03d2",piv:"\u03d6",ensp:"\u2002",emsp:"\u2003",thinsp:"\u2009",zwnj:"\u200c",zwj:"\u200d",lrm:"\u200e",rlm:"\u200f",ndash:"\u2013",mdash:"\u2014",lsquo:"\u2018",rsquo:"\u2019",sbquo:"\u201a",ldquo:"\u201c",rdquo:"\u201d",bdquo:"\u201e",dagger:"\u2020",Dagger:"\u2021",bull:"\u2022",hellip:"\u2026",permil:"\u2030",prime:"\u2032",Prime:"\u2033",lsaquo:"\u2039",rsaquo:"\u203a",oline:"\u203e",frasl:"\u2044",euro:"\u20ac",image:"\u2111",weierp:"\u2118",real:"\u211c",trade:"\u2122",alefsym:"\u2135",larr:"\u2190",uarr:"\u2191",rarr:"\u2192",darr:"\u2193",harr:"\u2194",crarr:"\u21b5",lArr:"\u21d0",uArr:"\u21d1",rArr:"\u21d2",dArr:"\u21d3",hArr:"\u21d4",forall:"\u2200",part:"\u2202",exist:"\u2203",empty:"\u2205",nabla:"\u2207",isin:"\u2208",notin:"\u2209",ni:"\u220b",prod:"\u220f",sum:"\u2211",minus:"\u2212",lowast:"\u2217",radic:"\u221a",prop:"\u221d",infin:"\u221e",ang:"\u2220",and:"\u2227",or:"\u2228",cap:"\u2229",cup:"\u222a",int:"\u222b",there4:"\u2234",sim:"\u223c",cong:"\u2245",asymp:"\u2248",ne:"\u2260",equiv:"\u2261",le:"\u2264",ge:"\u2265",sub:"\u2282",sup:"\u2283",nsub:"\u2284",sube:"\u2286",supe:"\u2287",oplus:"\u2295",otimes:"\u2297",perp:"\u22a5",sdot:"\u22c5",lceil:"\u2308",rceil:"\u2309",lfloor:"\u230a",rfloor:"\u230b",lang:"\u2329",rang:"\u232a",loz:"\u25ca",spades:"\u2660",clubs:"\u2663",hearts:"\u2665",diams:"\u2666"},qy=/\r\n|[\r\n\u2028\u2029]/g;function Wy(e){switch(e){case 10:case 13:case 8232:case 8233:return!0;default:return!1}}function Vy(e,a,n){for(var t=a;t."},MissingClosingTagFragment:"Expected corresponding JSX closing tag for <>.",UnexpectedSequenceExpression:"Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",UnexpectedToken:function(e){var a=e.unexpected;return"Unexpected token `"+a+"`. Did you mean `"+e.HTMLEntity+"` or `{'"+a+"'}`?"},UnsupportedJsxValue:"JSX value should be either an expression or a quoted JSX text.",UnterminatedJsxContent:"Unterminated JSX contents.",UnwrappedAdjacentJSXElements:"Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...?"});function Xy(e){return!!e&&("JSXOpeningFragment"===e.type||"JSXClosingFragment"===e.type)}function Yy(e){if("JSXIdentifier"===e.type)return e.name;if("JSXNamespacedName"===e.type)return e.namespace.name+":"+e.name.name;if("JSXMemberExpression"===e.type)return Yy(e.object)+"."+Yy(e.property);throw new Error("Node had unexpected type: "+e.type)}var $y=function(e){function a(){for(var a,n=arguments.length,t=new Array(n),r=0;r1)for(var t=0;t0?!(t&ZR)||(t&ey)>0!==(4&r)>0:t&QR&&(8&r)>0?!!(a.names.get(n)&_y)&&!!(t&JR):!!(t&zR&&(1&r)>0)||e.prototype.isRedeclaredInScope.call(this,a,n,t)},n.checkLocalExport=function(a){var n=a.name;if(!this.hasImport(n)){for(var t=this.scopeStack.length-1;t>=0;t--){var r=this.scopeStack[t].tsNames.get(n);if((1&r)>0||(16&r)>0)return}e.prototype.checkLocalExport.call(this,a)}},i(a,[{key:"inTSNamespace",get:function(){var e=this.scopeStack;return e.length>=2&&e[e.length-1].flags===kR&&(e[e.length-2].flags&VR)>0}}])}(Iy),Zy=function(){function e(){this.sawUnambiguousESM=!1,this.ambiguousScriptDifferentAst=!1}var a=e.prototype;return a.sourceToOffsetPos=function(e){return e+this.startIndex},a.offsetToSourcePos=function(e){return e-this.startIndex},a.hasPlugin=function(e){if("string"==typeof e)return this.plugins.has(e);var a=e[0],n=e[1];if(!this.hasPlugin(a))return!1;for(var t=this.plugins.get(a),r=0,i=Object.keys(n);r0;)t=a[--r];null===t||t.start>n.start?av(e,n.comments):ev(t,n.comments)}var tv=function(e){function a(){return e.apply(this,arguments)||this}u(a,e);var n=a.prototype;return n.addComment=function(e){this.filename&&(e.loc.filename=this.filename);var a=this.state.commentsLen;this.comments.length!==a&&(this.comments.length=a),this.comments.push(e),this.state.commentsLen++},n.processComment=function(e){var a=this.state.commentStack,n=a.length;if(0!==n){var t=n-1,r=a[t];r.start===e.end&&(r.leadingNode=e,t--);for(var i=e.start;t>=0;t--){var o=a[t],s=o.end;if(!(s>i)){s===i&&(o.trailingNode=e);break}o.containingNode=e,this.finalizeComment(o),a.splice(t,1)}}},n.finalizeComment=function(e){var a,n=e.comments;if(null!==e.leadingNode||null!==e.trailingNode)null!==e.leadingNode&&ev(e.leadingNode,n),null!==e.trailingNode&&function(e,a){var n;void 0===e.leadingComments?e.leadingComments=a:(n=e.leadingComments).unshift.apply(n,a)}(e.trailingNode,n);else{var t=e.containingNode,r=e.start;if(44===this.input.charCodeAt(this.offsetToSourcePos(r)-1))switch(t.type){case"ObjectExpression":case"ObjectPattern":nv(t,t.properties,e);break;case"CallExpression":case"NewExpression":case"OptionalCallExpression":nv(t,t.arguments,e);break;case"ImportExpression":nv(t,[t.source,null!=(a=t.options)?a:null],e);break;case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":case"ObjectMethod":case"ClassMethod":case"ClassPrivateMethod":case"TSTypeParameterDeclaration":nv(t,t.params,e);break;case"ArrayExpression":case"ArrayPattern":nv(t,t.elements,e);break;case"ExportNamedDeclaration":case"ImportDeclaration":nv(t,t.specifiers,e);break;case"TSEnumBody":nv(t,t.members,e);break;case"TSInterfaceBody":nv(t,t.body,e);break;default:av(t,n)}else av(t,n)}},n.finalizeRemainingComments=function(){for(var e=this.state.commentStack,a=e.length-1;a>=0;a--)this.finalizeComment(e[a]);this.state.commentStack=[]},n.resetPreviousNodeTrailingComments=function(e){var a=this.state.commentStack,n=a.length;if(0!==n){var t=a[n-1];t.leadingNode===e&&(t.leadingNode=null)}},n.takeSurroundingComments=function(e,a,n){var t=this.state.commentStack,r=t.length;if(0!==r)for(var i=r-1;i>=0;i--){var o=t[i],s=o.end;if(o.start===n)o.leadingNode=e;else if(s===a)o.trailingNode=e;else if(s0},set:function(e){e?this.flags|=1:this.flags&=-2}},{key:"canStartArrow",get:function(){return(2&this.flags)>0},set:function(e){e?this.flags|=2:this.flags&=-3}},{key:"inType",get:function(){return(4&this.flags)>0},set:function(e){e?this.flags|=4:this.flags&=-5}},{key:"noAnonFunctionType",get:function(){return(8&this.flags)>0},set:function(e){e?this.flags|=8:this.flags&=-9}},{key:"hasFlowComment",get:function(){return(16&this.flags)>0},set:function(e){e?this.flags|=16:this.flags&=-17}},{key:"isAmbientContext",get:function(){return(32&this.flags)>0},set:function(e){e?this.flags|=32:this.flags&=-33}},{key:"inAbstractClass",get:function(){return(64&this.flags)>0},set:function(e){e?this.flags|=64:this.flags&=-65}},{key:"inDisallowConditionalTypesContext",get:function(){return(128&this.flags)>0},set:function(e){e?this.flags|=128:this.flags&=-129}},{key:"inConditionalConsequent",get:function(){return(256&this.flags)>0},set:function(e){e?this.flags|=256:this.flags&=-257}},{key:"inHackPipelineBody",get:function(){return(512&this.flags)>0},set:function(e){e?this.flags|=512:this.flags&=-513}},{key:"seenTopicReference",get:function(){return(1024&this.flags)>0},set:function(e){e?this.flags|=1024:this.flags&=-1025}},{key:"canStartJSXElement",get:function(){return(2048&this.flags)>0},set:function(e){e?this.flags|=2048:this.flags&=-2049}},{key:"containsEsc",get:function(){return(4096&this.flags)>0},set:function(e){e?this.flags|=4096:this.flags&=-4097}},{key:"hasTopLevelAwait",get:function(){return(8192&this.flags)>0},set:function(e){e?this.flags|=8192:this.flags&=-8193}}])}();function sv(e,a,n){return new Rm(n,e-a,e)}var dv,uv=new Set([103,109,115,105,121,117,100,118]),cv=i(function(e){var a=e.startIndex||0;this.type=e.type,this.value=e.value,this.start=a+e.start,this.end=a+e.end,this.loc=new ym(e.startLoc,e.endLoc)}),lv=function(e){function a(a,n){var t;return(t=e.call(this)||this).isLookahead=void 0,t.tokens=[],t.errorHandlers_readInt={invalidDigit:function(e,a,n,r){t.raise(Bm.InvalidDigit,sv(e,a,n),{radix:r})},numericSeparatorInEscapeSequence:t.errorBuilder(Bm.NumericSeparatorInEscapeSequence),unexpectedNumericSeparator:t.errorBuilder(Bm.UnexpectedNumericSeparator)},t.errorHandlers_readCodePoint=Object.assign({},t.errorHandlers_readInt,{invalidEscapeSequence:t.errorBuilder(Bm.InvalidEscapeSequence),invalidCodePoint:t.errorBuilder(Bm.InvalidCodePoint)}),t.errorHandlers_readStringContents_string=Object.assign({},t.errorHandlers_readCodePoint,{strictNumericEscape:function(e,a,n){t.recordStrictModeErrors(Bm.StrictNumericEscape,sv(e,a,n))},unterminated:function(e,a,n){throw t.raise(Bm.UnterminatedString,sv(e-1,a,n))}}),t.errorHandlers_readStringContents_template=Object.assign({},t.errorHandlers_readCodePoint,{strictNumericEscape:t.errorBuilder(Bm.StrictNumericEscape),unterminated:function(e,a,n){throw t.raise(Bm.UnterminatedTemplate,sv(e,a,n))}}),t.state=new ov,t.state.init(a),t.input=n,t.length=n.length,t.comments=[],t.isLookahead=!1,(!dv||dv.length<2*(t.length+1))&&(dv=new Uint32Array(2*(t.length+1))),t.locData=dv,t}u(a,e);var n=a.prototype;return n.setLoc=function(e){var a=this.offsetToSourcePos(e.index);this.locData[2*a]=e.line,this.locData[2*a+1]=e.column},n.getLoc=function(e){var a=this.offsetToSourcePos(e);return new Rm(this.locData[2*a],this.locData[2*a+1],e)},n.pushToken=function(e){this.tokens.length=this.state.tokensLength,this.tokens.push(e),++this.state.tokensLength},n.next=function(){this.checkKeywordEscapes(),this.optionFlags&Vm&&this.pushToken(new cv(this.state)),this.state.lastTokEndLoc=this.state.endLoc,this.state.lastTokStartLoc=this.state.startLoc,this.nextToken()},n.eat=function(e){return!!this.match(e)&&(this.next(),!0)},n.match=function(e){return this.state.type===e},n.createLookaheadState=function(e){return{pos:e.pos,value:null,type:e.type,start:e.start,end:e.end,context:[this.curContext()],inType:e.inType,startLoc:e.startLoc,lastTokEndLoc:e.lastTokEndLoc,curLine:e.curLine,lineStart:e.lineStart,curPosition:e.curPosition}},n.lookahead=function(){var e=this.state;this.state=this.createLookaheadState(e),this.isLookahead=!0,this.nextToken(),this.isLookahead=!1;var a=this.state;return this.state=e,a},n.nextTokenStart=function(){return this.nextTokenStartSince(this.state.pos)},n.nextTokenStartSince=function(e){return Gy.lastIndex=e,Gy.test(this.input)?Gy.lastIndex:e},n.lookaheadCharCode=function(){return this.lookaheadCharCodeSince(this.state.pos)},n.lookaheadCharCodeSince=function(e){return this.input.charCodeAt(this.nextTokenStartSince(e))},n.nextTokenInLineStart=function(){return this.nextTokenInLineStartSince(this.state.pos)},n.nextTokenInLineStartSince=function(e){return Ky.lastIndex=e,Ky.test(this.input)?Ky.lastIndex:e},n.lookaheadInLineCharCode=function(){return this.input.charCodeAt(this.nextTokenInLineStart())},n.codePointAtPos=function(e){var a=this.input.charCodeAt(e);if(55296==(64512&a)&&++e=this.length?this.finishToken(135):this.getTokenFromCode(this.codePointAtPos(this.state.pos))},n.skipBlockComment=function(e){var a;this.isLookahead||(a=this.state.curPosition());var n=this.state.pos,t=this.input.indexOf(e,n+2);if(-1===t)throw this.raise(Bm.UnterminatedComment,this.state.curPosition());for(this.state.pos=t+e.length,qy.lastIndex=n+2;qy.test(this.input)&&qy.lastIndex<=t;)++this.state.curLine,this.state.lineStart=qy.lastIndex;if(!this.isLookahead){var r={type:"CommentBlock",value:this.input.slice(n+2,t),start:this.sourceToOffsetPos(n),end:this.sourceToOffsetPos(t+e.length),loc:new ym(a,this.state.curPosition())};return this.optionFlags&Vm&&this.pushToken(r),r}},n.skipLineComment=function(e){var a,n=this.state.pos;this.isLookahead||(a=this.state.curPosition());var t=this.input.charCodeAt(this.state.pos+=e);if(this.state.pos0;e:for(;this.state.posn))break e;var d=this.skipLineComment(3);void 0!==d&&(this.addComment(d),t&&(null!=a?a:a=[]).push(d))}else{if(60!==r||this.inModule||!(this.optionFlags&zm))break e;var u=this.state.pos;if(33!==this.input.charCodeAt(u+1)||45!==this.input.charCodeAt(u+2)||45!==this.input.charCodeAt(u+3))break e;var c=this.skipLineComment(4);void 0!==c&&(this.addComment(c),t&&(null!=a?a:a=[]).push(c))}}}if(null!=(e=a)&&e.length){var l=this.state.pos,p={start:this.sourceToOffsetPos(n),end:this.sourceToOffsetPos(l),comments:a,leadingNode:null,trailingNode:null,containingNode:null};this.state.commentStack.push(p)}},n.finishToken=function(e,a){this.state.end=this.state.pos,this.state.endLoc=this.state.curPosition();var n=this.state.type;this.state.type=e,this.state.value=a,this.isLookahead||this.updateContext(n)},n.replaceToken=function(e){this.state.type=e,this.updateContext()},n.readToken_numberSign=function(){if(0!==this.state.pos||!this.readToken_interpreter()){var e=this.state.pos+1,a=this.codePointAtPos(e);if(a>=48&&a<=57)throw this.raise(Bm.UnexpectedDigitAfterHash,this.state.curPosition());gn(a)?(++this.state.pos,this.finishToken(134,this.readWord1(a))):92===a?(++this.state.pos,this.finishToken(134,this.readWord1())):this.finishOp(23,1)}},n.readToken_dot=function(){var e=this.input.charCodeAt(this.state.pos+1);e>=48&&e<=57?this.readNumber(!0):46===e&&46===this.input.charCodeAt(this.state.pos+2)?(this.state.pos+=3,this.finishToken(17)):(++this.state.pos,this.finishToken(12))},n.readToken_slash=function(){61===this.input.charCodeAt(this.state.pos+1)?this.finishOp(27,2):this.finishOp(52,1)},n.readToken_interpreter=function(){if(0!==this.state.pos||this.length<2)return!1;var e=this.input.charCodeAt(this.state.pos+1);if(33!==e)return!1;var a=this.state.pos;for(this.state.pos+=1;!Wy(e)&&++this.state.pos=48&&a<=57?(++this.state.pos,this.finishToken(13)):(this.state.pos+=2,this.finishToken(14))},n.getTokenFromCode=function(e){switch(e){case 46:return void this.readToken_dot();case 40:return++this.state.pos,void this.finishToken(6);case 41:return++this.state.pos,void this.finishToken(7);case 59:return++this.state.pos,void this.finishToken(9);case 44:return++this.state.pos,void this.finishToken(8);case 91:return++this.state.pos,void this.finishToken(0);case 93:return++this.state.pos,void this.finishToken(1);case 123:return++this.state.pos,void this.finishToken(2);case 125:return++this.state.pos,void this.finishToken(4);case 58:return void(this.hasPlugin("functionBind")&&58===this.input.charCodeAt(this.state.pos+1)?this.finishOp(11,2):(++this.state.pos,this.finishToken(10)));case 63:return void this.readToken_question();case 96:return void this.readTemplateToken();case 48:var a=this.input.charCodeAt(this.state.pos+1);if(120===a||88===a)return void this.readRadixNumber(16);if(111===a||79===a)return void this.readRadixNumber(8);if(98===a||66===a)return void this.readRadixNumber(2);case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return void this.readNumber(!1);case 34:case 39:return void this.readString(e);case 47:return void this.readToken_slash();case 37:case 42:return void this.readToken_mult_modulo(e);case 124:case 38:return void this.readToken_pipe_amp(e);case 94:return void this.readToken_caret();case 43:case 45:return void this.readToken_plus_min(e);case 60:return void this.readToken_lt();case 62:return void this.readToken_gt();case 61:case 33:return void this.readToken_eq_excl(e);case 126:return void this.finishOp(32,1);case 64:return void this.readToken_atSign();case 35:return void this.readToken_numberSign();case 92:return void this.readWord();default:if(gn(e))return void this.readWord(e)}throw this.raise(Bm.InvalidOrUnexpectedToken,this.state.curPosition(),{unexpected:String.fromCodePoint(e)})},n.finishOp=function(e,a){var n=this.input.slice(this.state.pos,this.state.pos+a);this.state.pos+=a,this.finishToken(e,n)},n.readRegexp=function(){for(var e,a,n=this.state.startLoc,t=this.state.start+1,r=this.state.pos;;++r){if(r>=this.length)throw this.raise(Bm.UnterminatedRegExp,vm(n,1));var i=this.input.charCodeAt(r);if(Wy(i))throw this.raise(Bm.UnterminatedRegExp,vm(n,1));if(e)e=!1;else{if(91===i)a=!0;else if(93===i&&a)a=!1;else if(47===i&&!a)break;e=92===i}}var o=this.input.slice(t,r);++r;for(var s="",d=function(){return vm(n,r+2-t)};r=2&&48===this.input.charCodeAt(a);if(o){var s=this.input.slice(a,this.state.pos);if(this.recordStrictModeErrors(Bm.StrictOctalLiteral,n),!this.state.strict){var d=s.indexOf("_");d>0&&this.raise(Bm.ZeroDigitNumericSeparator,vm(n,d))}i=o&&!/[89]/.test(s)}var u=this.input.charCodeAt(this.state.pos);46!==u||i||(++this.state.pos,this.readInt(10),t=!0,u=this.input.charCodeAt(this.state.pos)),69!==u&&101!==u||i||(43!==(u=this.input.charCodeAt(++this.state.pos))&&45!==u||++this.state.pos,null===this.readInt(10)&&this.raise(Bm.InvalidOrMissingExponent,n),t=!0,u=this.input.charCodeAt(this.state.pos));var c=this.input.slice(a,this.state.pos).replaceAll("_","");if(110===u&&((t||o)&&this.raise(Bm.InvalidBigIntLiteral,n),++this.state.pos,r=!0),gn(this.codePointAtPos(this.state.pos)))throw this.raise(Bm.NumberIdentifier,this.state.curPosition());if(r)this.finishToken(132,c);else{var l=i?parseInt(c,8):parseFloat(c);this.finishToken(131,l)}},n.readCodePoint=function(e){var a=jn(this.input,this.state.pos,this.state.lineStart,this.state.curLine,e,this.errorHandlers_readCodePoint),n=a.code,t=a.pos;return this.state.pos=t,n},n.readString=function(e){var a=Dn(34===e?"double":"single",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_string),n=a.str,t=a.pos,r=a.curLine,i=a.lineStart;this.state.pos=t+1,this.state.lineStart=i,this.state.curLine=r,this.finishToken(130,n)},n.readTemplateContinuation=function(){this.match(4)||this.unexpected(null,4),this.state.pos--,this.readTemplateToken()},n.readTemplateToken=function(){var e=this.input[this.state.pos],a=Dn("template",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_template),n=a.str,t=a.firstInvalidLoc,r=a.pos,i=a.curLine,o=a.lineStart;this.state.pos=r+1,this.state.lineStart=o,this.state.curLine=i,t&&(this.state.firstInvalidTemplateEscapePos=new Rm(t.curLine,t.pos-t.lineStart,this.sourceToOffsetPos(t.pos))),96===this.input.codePointAt(r)?this.finishToken(20,t?null:e+n+"`"):(this.state.pos++,this.finishToken(21,t?null:e+n+"${"))},n.recordStrictModeErrors=function(e,a){var n=a.index;this.state.strict&&!this.state.strictErrors.has(n)?this.raise(e,a):this.state.strictErrors.set(n,[e,a])},n.readWord1=function(e){this.state.containsEsc=!1;var a="",n=this.state.pos,t=this.state.pos;for(void 0!==e&&(this.state.pos+=e<=65535?1:2);this.state.pos=0;o--){var s=i[o];if(s.pos===r)return i[o]=e(t,r,n);if(s.pos0}},{key:"hasYield",get:function(){return(this.currentFlags()&vv)>0}},{key:"hasReturn",get:function(){return(this.currentFlags()&xv)>0}},{key:"hasIn",get:function(){return(this.currentFlags()&Sv)>0}},{key:"inFSharpPipelineDirectBody",get:function(){return 0===(this.currentFlags()&Ev)}}])}();function wv(e,a){return(e?bv:0)|(a?vv:0)}var Cv=function(e){function a(){return e.apply(this,arguments)||this}u(a,e);var n=a.prototype;return n.addExtra=function(e,a,n,t){if(void 0===t&&(t=!0),e){var r=e.extra;null==r&&(r={},e.extra=r),t?r[a]=n:Object.defineProperty(r,a,{enumerable:t,value:n})}},n.isContextual=function(e){return this.state.type===e&&!this.state.containsEsc},n.isUnparsedContextual=function(e,a){if(this.input.startsWith(a,e)){var n=this.input.charCodeAt(e+a.length);return!(fn(n)||55296==(64512&n))}return!1},n.isLookaheadContextual=function(e){var a=this.nextTokenStart();return this.isUnparsedContextual(a,e)},n.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},n.expectContextual=function(e,a){if(!this.eatContextual(e)){if(null!=a)throw this.raise(a,this.state.startLoc);this.unexpected(null,e)}},n.canInsertSemicolon=function(){return this.match(135)||this.match(4)||this.hasPrecedingLineBreak()},n.hasPrecedingLineBreak=function(){return Vy(this.input,this.offsetToSourcePos(this.state.lastTokEndLoc.index),this.state.start)},n.hasFollowingLineBreak=function(){return Vy(this.input,this.state.end,this.nextTokenStart())},n.isLineTerminator=function(){return this.eat(9)||this.canInsertSemicolon()},n.semicolon=function(e){void 0===e&&(e=!0),(e?this.isLineTerminator():this.eat(9))||this.raise(Bm.MissingSemicolon,this.state.lastTokEndLoc)},n.expect=function(e,a){this.eat(e)||this.unexpected(a,e)},n.tryParse=function(e,a){void 0===a&&(a=this.state.clone());var n={node:null};try{var t=e(function(e){throw void 0===e&&(e=null),n.node=e,n});if(this.state.errors.length>a.errors.length){var r=this.state;return this.state=a,this.state.tokensLength=r.tokensLength,{node:t,error:r.errors[a.errors.length],thrown:!1,aborted:!1,failState:r}}return{node:t,error:null,thrown:!1,aborted:!1,failState:null}}catch(e){var i=this.state;if(this.state=a,e instanceof SyntaxError)return{node:null,error:e,thrown:!0,aborted:!1,failState:i};if(e===n)return{node:n.node,error:null,thrown:!1,aborted:!0,failState:i};throw e}},n.checkExpressionErrors=function(e,a){if(!e)return!1;var n=e.shorthandAssignLoc,t=e.doubleProtoLoc,r=e.privateKeyLoc,i=e.optionalParametersLoc,o=e.voidPatternLoc;if(!a)return!!(n||t||i||r||o);null!=n&&this.raise(Bm.InvalidCoverInitializedName,n),null!=t&&this.raise(Bm.DuplicateProto,t),null!=r&&this.raise(Bm.UnexpectedPrivateField,r),null!=i&&this.unexpected(i),null!=o&&this.raise(Bm.InvalidCoverDiscardElement,o)},n.isLiteralPropertyName=function(){return RR(this.state.type)},n.isPrivateName=function(e){return"PrivateName"===e.type},n.getPrivateNameSV=function(e){return e.id.name},n.hasPropertyAsPrivateName=function(e){return("MemberExpression"===e.type||"OptionalMemberExpression"===e.type)&&this.isPrivateName(e.property)},n.isObjectProperty=function(e){return"ObjectProperty"===e.type},n.isObjectMethod=function(e){return"ObjectMethod"===e.type},n.initializeScopes=function(e){var a=this;void 0===e&&(e="module"===this.options.sourceType);var n=this.state.labels;this.state.labels=[];var t=this.exportedIdentifiers;this.exportedIdentifiers=new Set;var r=this.inModule;this.inModule=e;var i=this.scope,o=this.getScopeHandler();this.scope=new o(this,e);var s=this.prodParam;this.prodParam=new Tv;var d=this.classScope;this.classScope=new gv(this);var u=this.expressionScope;return this.expressionScope=new mv(this),function(){a.state.labels=n,a.exportedIdentifiers=t,a.inModule=r,a.scope=i,a.prodParam=s,a.classScope=d,a.expressionScope=u}},n.enterInitialScopes=function(){var e=yv;(this.inModule||this.optionFlags&Nm)&&(e|=bv),this.optionFlags&Lm&&(e|=vv);var a=!this.inModule&&"commonjs"===this.options.sourceType;(a||this.optionFlags&jm)&&(e|=xv),this.prodParam.enter(e);var n=a?HR:IR;this.optionFlags&Om&&(n|=qR),this.optionFlags&Mm&&(n|=OR|FR),this.scope.enter(n)},n.checkDestructuringPrivate=function(e){var a=e.privateKeyLoc;null!==a&&this.expectPlugin("destructuringPrivate",a)},i(a)}(lv),Pv=i(function(){this.shorthandAssignLoc=null,this.doubleProtoLoc=null,this.privateKeyLoc=null,this.optionalParametersLoc=null,this.voidPatternLoc=null}),Av=i(function(e,a,n,t){this.type="",this.start=n,this.end=0,void 0!==t&&(this.loc=new ym(t)),e&qm&&(this.range=[n,0]),void 0!==t&&a&&(this.loc.filename=a)}),_v=Av.prototype,Dv=function(e){function a(){return e.apply(this,arguments)||this}u(a,e);var n=a.prototype;return n.createPosition=function(e){return e},n.startNode=function(){var e=this.state.startLoc;return this.setLoc(e),this.startNodeAt(e)},n.startNodeAt=function(e){var a=this.optionFlags,n=this.filename;return a&Wm?new Av(a,n,e.index,this.createPosition(e)):new Av(a,n,e.index)},n.startNodeAtNode=function(e){var a=this.optionFlags,n=this.filename;return a&Wm?new Av(a,n,e.start,e.loc.start):new Av(a,n,e.start)},n.finishNode=function(e,a){return this.finishNodeAt(e,a,this.state.lastTokEndLoc)},n.finishNodeAt=function(e,a,n){e.type=a,e.end=n.index;var t=this.optionFlags;return t&Wm&&(e.loc.end=this.createPosition(n)),t&qm&&(e.range[1]=n.index),t&Jm&&this.processComment(e),e},n.finishNodeAtNode=function(e,a,n){e.type=a,e.end=n.end;var t=this.optionFlags;return t&Wm&&(e.loc.end=n.loc.end),t&qm&&(e.range[1]=e.end),t&Jm&&this.processComment(e),e},n.resetStartLocation=function(e,a){e.start=a.index;var n=this.optionFlags;n&Wm&&(e.loc.start=this.createPosition(a)),n&qm&&(e.range[0]=a.index)},n.resetEndLocation=function(e,a){void 0===a&&(a=this.state.lastTokEndLoc),e.end=a.index;var n=this.optionFlags;n&Wm&&(e.loc.end=this.createPosition(a)),n&qm&&(e.range[1]=a.index)},n.resetStartLocationFromNode=function(e,a){e.start=a.start;var n=this.optionFlags;n&Wm&&(e.loc.start=a.loc.start),n&qm&&(e.range[0]=a.start)},n.resetEndLocationFromNode=function(e,a){e.end=a.end;var n=this.optionFlags;n&Wm&&(e.loc.end=a.loc.end),n&qm&&(e.range[1]=a.end)},n.castNodeTo=function(e,a){return e.type=a,e},n.cloneIdentifier=function(e){var a=e.type,n=e.start,t=e.end,r=e.loc,i=e.range,o=e.name,s=Object.create(_v);return s.type=a,s.start=n,s.end=t,s.loc=r,s.range=i,s.name=o,e.extra&&(s.extra=e.extra),s},n.cloneStringLiteral=function(e){var a=e.type,n=e.start,t=e.end,r=e.loc,i=e.range,o=e.extra,s=Object.create(_v);return s.type=a,s.start=n,s.end=t,s.loc=r,s.range=i,s.extra=o,s.value=e.value,s},i(a)}(Cv),kv=function(e){return"ParenthesizedExpression"===e.type?kv(e.expression):e},Iv=1,Bv=2,Nv=4,jv=function(e){function a(){return e.apply(this,arguments)||this}u(a,e);var n=a.prototype;return n.toAssignable=function(e,a){var n,t;void 0===a&&(a=!1);var r=void 0;switch(("ParenthesizedExpression"===e.type||null!=(n=e.extra)&&n.parenthesized)&&(r=kv(e),a?"Identifier"===r.type?this.expressionScope.recordArrowParameterBindingError(Bm.InvalidParenthesizedAssignment,e):"CallExpression"===r.type||"MemberExpression"===r.type||this.isOptionalMemberExpression(r)||this.raise(Bm.InvalidParenthesizedAssignment,e):this.raise(Bm.InvalidParenthesizedAssignment,e)),e.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":case"VoidPattern":break;case"ObjectExpression":this.castNodeTo(e,"ObjectPattern");for(var i=0,o=e.properties.length,s=o-1;i=25&&o<=29){var d=this.startNodeAt(t),u=this.state.value;if(d.operator=u,this.match(25)){this.toAssignable(s,!0),d.left=s;var c=t.index;null!=e.doubleProtoLoc&&e.doubleProtoLoc.index>=c&&(e.doubleProtoLoc=null),null!=e.shorthandAssignLoc&&e.shorthandAssignLoc.index>=c&&(e.shorthandAssignLoc=null),null!=e.privateKeyLoc&&e.privateKeyLoc.index>=c&&(this.checkDestructuringPrivate(e),e.privateKeyLoc=null),null!=e.voidPatternLoc&&e.voidPatternLoc.index>=c&&(e.voidPatternLoc=null)}else d.left=s;return this.next(),d.right=this.parseMaybeAssign(),this.checkLVal(s,this.finishNode(d,"AssignmentExpression"),void 0,void 0,void 0,void 0,"||="===u||"&&="===u||"??="===u),d}if(n&&this.checkExpressionErrors(e,!0),r){var l=this.state.type;if((this.hasPlugin("v8intrinsic")?yR(l):yR(l)&&!this.match(50))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(Bm.YieldNotInGeneratorFunction,t),this.parseYield(t)}return s},n.parseMaybeConditional=function(e){var a=this.state.startLoc,n=this.parseExprOps(e);return this.shouldExitDescending(n)?n:this.parseConditional(n,a,e)},n.parseConditional=function(e,a,n){if(this.eat(13)){var t=this.startNodeAt(a);return t.test=e,t.consequent=this.parseMaybeAssignAllowIn(),this.expect(10),t.alternate=this.parseMaybeAssign(),this.finishNode(t,"ConditionalExpression")}return e},n.parseMaybeUnaryOrPrivate=function(e){return this.match(134)?this.parsePrivateName():this.parseMaybeUnary(e)},n.parseExprOps=function(e){var a=this.state.startLoc,n=this.parseMaybeUnaryOrPrivate(e);return this.shouldExitDescending(n)?n:(this.state.canStartArrow=!1,this.parseExprOp(n,a,-1))},n.parseExprOp=function(e,a,n){if(this.isPrivateName(e)){var t=this.getPrivateNameSV(e);(n>=TR(54)||!this.prodParam.hasIn||!this.match(54))&&this.raise(Bm.PrivateInExpectedIn,a,{identifierName:t}),this.classScope.usePrivateName(t,a)}var r=this.state.type;if(xR(r)&&(this.prodParam.hasIn||!this.match(54))){var i=TR(r);if(i>n){if(35===r&&(this.expectPlugin("pipelineOperator"),this.prodParam.inFSharpPipelineDirectBody))return e;var o=this.startNodeAt(a);o.left=e,o.operator=this.state.value;var s=37===r||38===r,d=36===r;d&&(i=TR(38)),this.next(),o.right=this.parseExprOpRightExpr(r,i);var u=this.finishNode(o,s||d?"LogicalExpression":"BinaryExpression"),c=this.state.type;if(d&&(37===c||38===c)||s&&36===c)throw this.raise(Bm.MixingCoalesceWithLogical,this.state.startLoc);return this.parseExprOp(u,a,n)}}return e},n.parseExprOpRightExpr=function(e,a){var n=this;if(35===e)switch(this.getPluginOption("pipelineOperator","proposal")){case"hack":return this.withTopicBindingContext(function(){return n.parseHackPipeBody()});case"fsharp":return this.parseFSharpPipelineBody(a)}return this.parseExprOpBaseRightExpr(e,a)},n.parseExprOpBaseRightExpr=function(e,a){var n=this.state.startLoc;return this.parseExprOp(this.parseMaybeUnaryOrPrivate(),n,53===e?a-1:a)},n.parseHackPipeBody=function(){var e,a=this.state.startLoc,n=this.parseMaybeAssign();return!Am.has(n.type)||null!=(e=n.extra)&&e.parenthesized||this.raise(Bm.PipeUnparenthesizedBody,a,{type:n.type}),this.topicReferenceWasUsedInCurrentContext()||this.raise(Bm.PipeTopicUnused,a),n},n.checkExponentialAfterUnary=function(e){this.match(53)&&this.raise(Bm.UnexpectedTokenUnaryExponentiation,e.argument)},n.parseMaybeUnary=function(e,a){var n=this.state.startLoc,t=this.isContextual(92);if(t&&this.recordAwaitIfAllowed()){this.next();var r=this.parseAwait(n);return a||this.checkExponentialAfterUnary(r),r}var i,o=this.match(30),s=this.startNode();if(i=this.state.type,lR[i]){s.operator=this.state.value,s.prefix=!0,this.state.canStartArrow=!1,this.match(68)&&this.expectPlugin("throwExpressions");var d=this.match(85);if(this.next(),s.argument=this.parseMaybeUnary(null,!0),this.checkExpressionErrors(e,!0),this.state.strict&&d){var u=s.argument;"Identifier"===u.type?this.raise(Bm.StrictDelete,s):this.hasPropertyAsPrivateName(u)&&this.raise(Bm.DeletePrivateField,s)}if(!o)return a||this.checkExponentialAfterUnary(s),this.finishNode(s,"UnaryExpression")}var c=this.parseUpdate(s,o,e);if(t){var l=this.state.type;if((this.hasPlugin("v8intrinsic")?yR(l):yR(l)&&!this.match(50))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(Bm.AwaitNotInAsyncContext,n),this.parseAwait(n)}return c},n.parseUpdate=function(e,a,n){if(a){var t=this.finishNode(e,"UpdateExpression");return this.checkLVal(t.argument,t),t}var r=this.state.startLoc,i=this.parseExprSubscripts(n);if(this.checkExpressionErrors(n,!1))return i;for(;SR(this.state.type)&&!this.canInsertSemicolon();){var o=this.startNodeAt(r);o.operator=this.state.value,o.prefix=!1,o.argument=i,this.next(),this.checkLVal(i,i=this.finishNode(o,"UpdateExpression"))}return i},n.parseExprSubscripts=function(e){var a=this.state.startLoc;this.setLoc(a);var n=this.parseExprAtom(e);return this.shouldExitDescending(n)?n:this.parseSubscripts(n,a)},n.parseSubscripts=function(e,a,n){var t={optionalChainMember:!1,maybeAsyncArrow:this.atPossibleAsyncArrow(e),stop:!1};do{e=this.parseSubscript(e,a,n,t),t.maybeAsyncArrow=!1}while(!t.stop);return e},n.parseSubscript=function(e,a,n,t){var r=this.state.type;if(!n&&11===r)return this.parseBind(e,a,t);if(wR(r))return this.parseTaggedTemplateExpression(e,a,t);var i=!1;if(14===r){if(n&&(this.raise(Bm.OptionalChainingNoNew,this.state.startLoc),40===this.lookaheadCharCode()))return this.stopParseSubscript(e,t);t.optionalChainMember=i=!0,this.next()}if(!n&&this.match(6))return this.parseCoverCallAndAsyncArrowHead(e,a,t,i);var o=this.eat(0);return o||i||this.eat(12)?this.parseMember(e,a,t,o,i):this.stopParseSubscript(e,t)},n.stopParseSubscript=function(e,a){return a.stop=!0,e},n.parseMember=function(e,a,n,t,r){var i=this.startNodeAt(a);return i.object=e,i.computed=t,t?(i.property=this.parseExpression(),this.expect(1)):this.match(134)?("Super"===e.type&&this.raise(Bm.SuperPrivateField,a),this.classScope.usePrivateName(this.state.value,this.state.startLoc),i.property=this.parsePrivateName()):i.property=this.parseIdentifier(!0),n.optionalChainMember?(i.optional=r,this.finishNode(i,"OptionalMemberExpression")):this.finishNode(i,"MemberExpression")},n.parseBind=function(e,a,n){var t=this,r=this.startNodeAt(a);r.object=e,this.next();var i=this.parseNoCallExpr(function(e){throw t.raise(Bm.UnsupportedBindRHS,e)});if("Super"===i.type||"Import"===i.type)throw this.raise(Bm.UnsupportedBindRHS,i);return r.callee=i,n.stop=!0,this.parseSubscripts(this.finishNode(r,"BindExpression"),a,!1)},n.parseCoverCallAndAsyncArrowHead=function(e,a,n,t){var r=null;this.next();var i=this.startNodeAt(a);i.callee=e;var o=n.maybeAsyncArrow,s=n.optionalChainMember;o&&(this.expressionScope.enter(new hv(2)),r=new Pv),s&&(i.optional=t),i.arguments=t?this.parseCallExpressionArguments():this.parseCallExpressionArguments("Super"!==e.type,i,r);var d=this.finishCallExpression(i,s);return o&&this.shouldParseAsyncArrow()&&!t?(n.stop=!0,this.checkDestructuringPrivate(r),this.expressionScope.validateAsPattern(),this.expressionScope.exit(),d=this.parseAsyncArrowFromCallExpression(this.startNodeAt(a),d)):(o&&(this.checkExpressionErrors(r,!0),this.expressionScope.exit()),this.toReferencedList(i.arguments)),d},n.parseTaggedTemplateExpression=function(e,a,n){var t=this.startNodeAt(a);return t.tag=e,t.quasi=this.parseTemplate(!0),n.optionalChainMember&&this.raise(Bm.OptionalChainingNoTemplate,a),this.finishNode(t,"TaggedTemplateExpression")},n.atPossibleAsyncArrow=function(e){return"Identifier"===e.type&&"async"===e.name&&this.state.lastTokEndLoc.index===e.end&&!this.canInsertSemicolon()&&e.end-e.start===5&&this.state.canStartArrow},n.finishCallExpression=function(e,a){if("Import"===e.callee.type)if(0===e.arguments.length||e.arguments.length>2)this.raise(Bm.ImportCallArity,e);else for(var n=0,t=e.arguments;n1?((a=this.startNodeAt(i)).expressions=o,this.finishNode(a,"SequenceExpression"),this.resetEndLocation(a,c)):a=o[0],this.wrapParenthesis(n,a))},n.wrapParenthesis=function(e,a){if(!(this.optionFlags&Gm))return this.addExtra(a,"parenthesized",!0),this.addExtra(a,"parenStart",e.index),this.takeSurroundingComments(a,e.index,this.state.lastTokEndLoc.index),a;var n=this.startNodeAt(e);return n.expression=a,this.finishNode(n,"ParenthesizedExpression")},n.shouldParseArrow=function(e){return!this.canInsertSemicolon()},n.parseArrow=function(e){if(this.eat(15))return e},n.parseParenItem=function(e,a){return e},n.parseNewOrNewTarget=function(){var e=this.startNode();if(this.next(),this.match(12)){var a=this.createIdentifier(this.startNodeAtNode(e),"new");this.next();var n=this.parseMetaProperty(e,a,"target");return this.scope.allowNewTarget||this.raise(Bm.UnexpectedNewTarget,n),n}return this.parseNew(e)},n.parseNew=function(e){if(this.parseNewCallee(e),this.eat(6)){var a=this.parseExprList(7);this.toReferencedList(a),e.arguments=a}else e.arguments=[];return this.finishNode(e,"NewExpression")},n.parseNewCallee=function(e){var a=this,n=this.parseNoCallExpr(function(e){a.raise(Bm.ImportCallNotNewExpression,e,e)});e.callee=n,"Import"===n.type&&this.raise(Bm.ImportCallNotNewExpression,n),"Super"===n.type&&this.raise(Bm.SuperCallNotNewExpression,n)},n.parseTemplateElement=function(e){var a=this.state,n=a.start,t=a.startLoc,r=a.end,i=a.value,o=n+1,s=this.startNodeAt(vm(t,1));null===i&&(e||this.raise(Bm.InvalidEscapeSequenceTemplate,vm(this.state.firstInvalidTemplateEscapePos,1)));var d=this.match(20),u=d?-1:-2,c=r+u;s.value={raw:this.input.slice(o,c).replace(/\r\n?/g,"\n"),cooked:null===i?null:i.slice(1,u)},s.tail=d,this.next();var l=this.finishNode(s,"TemplateElement");return this.resetEndLocation(l,vm(this.state.lastTokEndLoc,u)),l},n.parseTemplate=function(e){for(var a=this.startNode(),n=this.parseTemplateElement(e),t=[n],r=[];!n.tail;)r.push(this.parseTemplateSubstitution()),this.readTemplateContinuation(),t.push(n=this.parseTemplateElement(e));return a.expressions=r,a.quasis=t,this.finishNode(a,"TemplateLiteral")},n.parseTemplateSubstitution=function(){return this.parseExpression()},n.parseObjectLike=function(e,a,n){var t=!1,r=!0,i=this.startNode();for(i.properties=[],this.next();!this.match(e);){if(r)r=!1;else if(this.expect(8),this.match(e)){this.addTrailingCommaExtraToNode(i);break}var o=void 0;a?o=this.parseBindingProperty():(o=this.parsePropertyDefinition(n),t=this.checkProto(o,t,n)),i.properties.push(o)}this.next();var s=a?"ObjectPattern":"ObjectExpression";return this.finishNode(i,s)},n.addTrailingCommaExtraToNode=function(e){this.addExtra(e,"trailingComma",this.state.lastTokStartLoc.index),this.addExtra(e,"trailingCommaLoc",this.state.lastTokStartLoc,!1)},n.maybeAsyncOrAccessorProp=function(e){return!e.computed&&"Identifier"===e.key.type&&(this.isLiteralPropertyName()||this.match(0)||this.match(51))},n.parsePropertyDefinition=function(e){var a=[];if(this.match(22))for(this.hasPlugin("decorators")&&this.raise(Bm.UnsupportedPropertyDecorator,this.state.startLoc);this.match(22);)a.push(this.parseDecorator());var n,t=this.startNode(),r=!1,i=!1;if(this.match(17))return a.length&&this.unexpected(),this.parseSpread();a.length&&(t.decorators=a),t.method=!1,e&&(n=this.state.startLoc);var o=this.eat(51);this.parsePropertyNamePrefixOperator(t);var s=this.state.containsEsc;if(this.parsePropertyName(t,e),!o&&!s&&this.maybeAsyncOrAccessorProp(t)){var d=t.key,u=d.name;"async"!==u||this.hasPrecedingLineBreak()||(r=!0,this.resetPreviousNodeTrailingComments(d),o=this.eat(51),this.parsePropertyName(t)),"get"!==u&&"set"!==u||(i=!0,this.resetPreviousNodeTrailingComments(d),t.kind=u,this.match(51)&&(o=!0,this.raise(Bm.AccessorIsGenerator,this.state.curPosition(),{kind:u}),this.next()),this.parsePropertyName(t))}return this.parseObjPropValue(t,n,o,r,!1,i,e)},n.getGetterSetterExpectedParamCount=function(e){return"get"===e.kind?0:1},n.getObjectOrClassMethodParams=function(e){return e.params},n.checkGetterSetterParams=function(e){var a,n=this.getGetterSetterExpectedParamCount(e),t=this.getObjectOrClassMethodParams(e);t.length!==n&&this.raise("get"===e.kind?Bm.BadGetterArity:Bm.BadSetterArity,e),"set"===e.kind&&"RestElement"===(null==(a=t[t.length-1])?void 0:a.type)&&this.raise(Bm.BadSetterRestParameter,e)},n.parseObjectMethod=function(e,a,n,t,r){if(r){var i=this.parseMethod(e,a,!1,!1,!1,"ObjectMethod");return this.checkGetterSetterParams(i),i}if(n||a||this.match(6))return t&&this.unexpected(),e.kind="method",e.method=!0,this.parseMethod(e,a,n,!1,!1,"ObjectMethod")},n.parseObjectProperty=function(e,a,n,t){if(e.shorthand=!1,this.eat(10))return e.value=n?this.parseMaybeDefault(this.state.startLoc):this.parseMaybeAssignAllowInOrVoidPattern(4,t),this.finishObjectProperty(e);if(!e.computed&&"Identifier"===e.key.type){if(this.checkReservedWord(e.key.name,e.key.start,!0,!1),n)e.value=this.parseMaybeDefault(a,this.cloneIdentifier(e.key));else if(this.match(25)){var r=this.state.startLoc;null!=t?null===t.shorthandAssignLoc&&(t.shorthandAssignLoc=r):this.raise(Bm.InvalidCoverInitializedName,r),e.value=this.parseMaybeDefault(a,this.cloneIdentifier(e.key))}else e.value=this.cloneIdentifier(e.key);return e.shorthand=!0,this.finishObjectProperty(e)}},n.finishObjectProperty=function(e){return this.finishNode(e,"ObjectProperty")},n.parseObjPropValue=function(e,a,n,t,r,i,o){var s=this.parseObjectMethod(e,n,t,r,i)||this.parseObjectProperty(e,a,r,o);return s||this.unexpected(),s},n.parsePropertyName=function(e,a){if(this.eat(0))e.computed=!0,e.key=this.parseMaybeAssignAllowIn(),this.expect(1);else{var n,t=this.state,r=t.type,i=t.value;if(mR(r))n=this.parseIdentifier(!0);else switch(r){case 131:n=this.parseNumericLiteral(i);break;case 130:n=this.parseStringLiteral(i);break;case 132:n=this.parseBigIntLiteral(i);break;case 134:var o=this.state.startLoc;null!=a?null===a.privateKeyLoc&&(a.privateKeyLoc=o):this.raise(Bm.UnexpectedPrivateField,o),n=this.parsePrivateName();break;default:throw this.unexpected()}e.key=n,134!==r&&(e.computed=!1)}},n.initFunction=function(e,a){e.id=null,e.generator=!1,e.async=a},n.parseMethod=function(e,a,n,t,r,i,o){void 0===o&&(o=!1),this.initFunction(e,n),e.generator=a,this.scope.enter(HR|OR|(o?GR:0)|(r?FR:0)),this.prodParam.enter(wv(n,e.generator)),this.parseFunctionParams(e,t);var s=this.parseFunctionBodyAndFinish(e,i,!0);return this.prodParam.exit(),this.scope.exit(),s},n.parseArrayLike=function(e,a){var n=this.startNode();return this.next(),n.elements=this.parseExprList(e,!0,a,n),this.finishNode(n,"ArrayExpression")},n.parseArrowExpression=function(e,a,n,t){this.scope.enter(HR|NR);var r=wv(n,!1);return this.match(2)||(r|=this.prodParam.currentFlags()&(Sv|Ev)),this.prodParam.enter(r),this.initFunction(e,n),a&&this.setArrowFunctionParameters(e,a,t),this.parseFunctionBody(e,!0),this.prodParam.exit(),this.scope.exit(),this.finishNode(e,"ArrowFunctionExpression")},n.setArrowFunctionParameters=function(e,a,n){this.toAssignableList(a,n,!1),e.params=a},n.parseFunctionBodyAndFinish=function(e,a,n){return void 0===n&&(n=!1),this.parseFunctionBody(e,!1,n),this.finishNode(e,a)},n.parseFunctionBody=function(e,a,n){var t=this;void 0===n&&(n=!1);var r=a&&!this.match(2);if(this.expressionScope.enter(Rv()),r)e.body=this.parseMaybeAssign(),this.checkParams(e,!1,a,!1);else{var i=this.state.strict,o=this.state.labels;this.state.labels=[],this.prodParam.enter(this.prodParam.currentFlags()|xv),e.body=this.parseBlock(!0,!1,function(r){var o=!t.isSimpleParamList(e.params);r&&o&&t.raise(Bm.IllegalLanguageModeDirective,"method"!==e.kind&&"constructor"!==e.kind||!e.key?e:t.optionFlags&Wm?e.key.loc.end:e.key);var s=!i&&t.state.strict;t.checkParams(e,!(t.state.strict||a||n||o),a,s),t.state.strict&&e.id&&t.checkIdentifier(e.id,hy,s)}),this.prodParam.exit(),this.state.labels=o}this.expressionScope.exit()},n.isSimpleParameter=function(e){return"Identifier"===e.type},n.isSimpleParamList=function(e){for(var a=0,n=e.length;a10)&&function(e){return _R.has(e)}(e))if(n&&wn(e))this.raise(Bm.UnexpectedKeyword,a,{keyword:e});else if((this.state.strict?t?Tn:Sn:xn)(e,this.inModule))this.raise(Bm.UnexpectedReservedWord,a,{reservedWord:e});else if("yield"===e){if(this.prodParam.hasYield)return void this.raise(Bm.YieldBindingIdentifier,a)}else if("await"===e){if(this.prodParam.hasAwait)return void this.raise(Bm.AwaitBindingIdentifier,a);if(this.scope.inStaticBlock)return void this.raise(Bm.AwaitBindingIdentifierInStaticBlock,a);this.expressionScope.recordAsyncArrowParametersError(a)}else if("arguments"===e&&this.scope.inClassAndNotInNonArrowFunction)return void this.raise(Bm.ArgumentsInClass,a)},n.recordAwaitIfAllowed=function(){var e=this.prodParam.hasAwait;return e&&!this.scope.inFunction&&(this.state.hasTopLevelAwait=!0),e},n.parseAwait=function(e,a){var n=e.index;this.setLoc(e);var t=this.startNodeAt(e);return this.expressionScope.recordParameterInitializerError(Bm.AwaitExpressionFormalParameter,n),this.eat(51)&&this.raise(Bm.ObsoleteAwaitStar,e),this.scope.inFunction||this.optionFlags&Nm||(this.isAmbiguousPrefixOrIdentifier()?this.ambiguousScriptDifferentAst=!0:this.sawUnambiguousESM=!0),a||(t.argument=this.parseMaybeUnary(null,!0)),this.finishNode(t,"AwaitExpression")},n.isAmbiguousPrefixOrIdentifier=function(){if(this.hasPrecedingLineBreak())return!0;var e=this.state.type;return 49===e||6===e||0===e||wR(e)||98===e&&!this.state.containsEsc||133===e||52===e||this.hasPlugin("v8intrinsic")&&50===e},n.parseYield=function(e){this.setLoc(e);var a=this.startNodeAt(e);this.expressionScope.recordParameterInitializerError(Bm.YieldInParameter,e.index);var n=!1,t=null;if(!this.hasPrecedingLineBreak())switch(n=this.eat(51),this.state.type){case 9:case 135:case 4:case 7:case 1:case 5:case 10:case 8:if(!n)break;default:t=this.parseMaybeAssign()}return a.delegate=n,a.argument=t,this.finishNode(a,"YieldExpression")},n.parseImportCall=function(e){var a;this.next();var n=this.parseCallExpressionArguments();if(0===n.length||n.length>2)this.raise(Bm.ImportCallArity,e,e);else for(var t=0;t0)for(var t=0,r=Array.from(this.scope.undefinedExports);t=86&&o<=88?rv:this.match(67)?iv:null,d=this.state.labels.length-1;d>=0;d--){var u=this.state.labels[d];if(u.statementStart!==e.start)break;u.statementStart=this.sourceToOffsetPos(this.state.start),u.kind=s}return this.state.labels.push({name:a,kind:s,statementStart:this.sourceToOffsetPos(this.state.start)}),e.body=t&zv?this.parseStatementOrSloppyAnnexBFunctionDeclaration(!0):this.parseStatement(),this.state.labels.pop(),e.label=n,this.finishNode(e,"LabeledStatement")},n.parseExpressionStatement=function(e,a){return e.expression=a,this.semicolon(),this.finishNode(e,"ExpressionStatement")},n.parseBlock=function(e,a,n){void 0===e&&(e=!1),void 0===a&&(a=!0);var t=this.startNode();return e&&this.state.strictErrors.clear(),this.expect(2),a&&this.scope.enter(kR),this.parseBlockBody(t,e,!1,4,n),a&&this.scope.exit(),this.finishNode(t,"BlockStatement")},n.isValidDirective=function(e){return"ExpressionStatement"===e.type&&"StringLiteral"===e.expression.type&&!e.expression.extra.parenthesized},n.parseBlockBody=function(e,a,n,t,r){var i=e.body=[],o=e.directives=[];this.parseBlockOrModuleBlockBody(i,a?o:void 0,n,t,r)},n.parseBlockOrModuleBlockBody=function(e,a,n,t,r){for(var i=this.state.strict,o=!1,s=!1;!this.match(t);){var d=n?this.parseModuleItem():this.parseStatementListItem();if(a&&!s){if(this.isValidDirective(d)){var u=this.stmtToDirective(d);a.push(u),o||"use strict"!==u.value.value||(o=!0,this.setStrict(!0));continue}s=!0,this.state.strictErrors.clear()}e.push(d)}null==r||r.call(this,o),i||this.setStrict(!1),this.next()},n.parseFor=function(e,a){return e.init=a,this.semicolon(!1),e.test=this.match(9)?null:this.parseExpression(),this.semicolon(!1),e.update=this.match(7)?null:this.parseExpression(),this.expect(7),e.body=this.parseStatement(),this.scope.exit(),this.state.labels.pop(),this.finishNode(e,"ForStatement")},n.parseForX=function(e,a,n){var t=this.match(54);return this.next(),t?null!==n&&this.unexpected(n):e.await=null!==n,"VariableDeclaration"!==a.type||null==a.declarations[0].init||t&&this.options.annexB&&!this.state.strict&&"var"===a.kind&&"Identifier"===a.declarations[0].id.type||this.raise(Bm.ForInOfLoopInitializer,a,{type:t?"ForInStatement":"ForOfStatement"}),"AssignmentPattern"===a.type&&this.raise(Bm.InvalidLhs,a,{ancestor:{type:"ForStatement"}}),e.left=a,e.right=t?this.parseExpression():this.parseMaybeAssignAllowIn(),this.expect(7),e.body=this.parseStatement(),this.scope.exit(),this.state.labels.pop(),this.finishNode(e,t?"ForInStatement":"ForOfStatement")},n.parseVar=function(e,a,n,t){void 0===t&&(t=!1);var r=e.declarations=[];for(e.kind=n;;){var i=this.startNode();if(this.parseVarId(i,n),i.init=this.eat(25)?a?this.parseMaybeAssignDisallowIn():this.parseMaybeAssignAllowIn():null,null!==i.init||t||("Identifier"===i.id.type||a&&(this.match(54)||this.isContextual(98))?"const"!==n&&"using"!==n&&"await using"!==n||this.match(54)||this.isContextual(98)||this.raise(Bm.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:n}):this.raise(Bm.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:"destructuring"})),r.push(this.finishNode(i,"VariableDeclarator")),!this.eat(8))break}return e},n.parseVarId=function(e,a){var n=this.parseBindingAtom();"using"===a||"await using"===a?"ArrayPattern"!==n.type&&"ObjectPattern"!==n.type||this.raise(Bm.UsingDeclarationHasBindingPattern,n):"VoidPattern"===n.type&&this.raise(Bm.UnexpectedVoidPattern,n),this.checkLVal(n,{type:"VariableDeclarator"},"var"===a?dy:oy),e.id=n},n.parseAsyncFunctionExpression=function(e){return this.parseFunction(e,Vv)},n.parseFunction=function(e,a){void 0===a&&(a=Lv);var n=a&qv,t=!!(a&Uv),r=t&&!(a&Wv),i=!!(a&Vv);return this.initFunction(e,i),this.match(51)&&(n&&this.raise(Bm.GeneratorInSingleStatementContext,this.state.startLoc),this.next(),e.generator=!0),t&&(e.id=this.parseFunctionId(r)),this.scope.enter(HR),this.prodParam.enter(wv(i,e.generator)),!t&&hR(this.state.type)&&(this.expressionScope.enter(Rv()),e.id=this.parseFunctionId(),this.expressionScope.exit()),this.parseFunctionParams(e,!1),this.parseFunctionBodyAndFinish(e,t?"FunctionDeclaration":"FunctionExpression"),this.prodParam.exit(),this.scope.exit(),t&&!n&&this.registerFunctionStatementId(e),e},n.parseFunctionId=function(e){return e||hR(this.state.type)?this.parseIdentifier():null},n.parseFunctionParams=function(e,a){this.expect(6),this.expressionScope.enter(new fv(3)),e.params=this.parseBindingList(7,41,Bv|(a?Nv:0)),this.expressionScope.exit()},n.registerFunctionStatementId=function(e){e.id&&this.scope.declareName(e.id.name,!this.options.annexB||this.state.strict||e.generator||e.async?this.scope.treatFunctionsAsVar?dy:oy:uy,e.id.start)},n.parseClass=function(e,a,n){this.next();var t=this.state.strict;return this.state.strict=!0,this.parseClassId(e,a,n),this.parseClassSuper(e),e.body=this.parseClassBody(!!e.superClass,t),this.finishNode(e,a?"ClassDeclaration":"ClassExpression")},n.isClassProperty=function(){return this.match(25)||this.match(9)||this.match(4)},n.isClassMethod=function(){return this.match(6)},n.nameIsConstructor=function(e){return"Identifier"===e.type&&"constructor"===e.name||"StringLiteral"===e.type&&"constructor"===e.value},n.isNonstaticConstructor=function(e){return!e.computed&&!e.static&&this.nameIsConstructor(e.key)},n.parseClassBody=function(e,a){this.classScope.enter();var n={hadConstructor:!1,hadSuperClass:e},t=[],r=this.startNode();for(r.body=[],this.expect(2);!this.match(4);)if(this.eat(9)){if(t.length>0)throw this.raise(Bm.DecoratorSemicolon,this.state.lastTokEndLoc)}else if(this.match(22))t.push(this.parseDecorator());else{var i=this.startNode();t.length&&(i.decorators=t,this.resetStartLocationFromNode(i,t[0]),t=[]),this.parseClassMember(r,i,n)}if(this.state.strict=a,this.next(),t.length)throw this.raise(Bm.TrailingDecorator,this.state.startLoc);return this.classScope.exit(),this.finishNode(r,"ClassBody")},n.parseClassMemberFromModifier=function(e,a){var n=this.parseIdentifier(!0);if(this.isClassMethod()){var t=a;return t.kind="method",t.computed=!1,t.key=n,t.static=!1,this.pushClassMethod(e,t,!1,!1,!1,!1),!0}if(this.isClassProperty()){var r=a;return r.computed=!1,r.key=n,r.static=!1,e.body.push(this.parseClassProperty(r)),!0}return this.resetPreviousNodeTrailingComments(n),!1},n.parseClassMember=function(e,a,n){var t=this.isContextual(102);if(t){if(this.parseClassMemberFromModifier(e,a))return;if(this.eat(2))return void this.parseClassStaticBlock(e,a)}this.parseClassMemberWithIsStatic(e,a,n,t)},n.parseClassMemberWithIsStatic=function(e,a,n,t){var r=a,i=a,o=a,s=a,d=a,u=r,c=r;if(a.static=t,this.parsePropertyNamePrefixOperator(a),this.eat(51)){u.kind="method";var l=this.match(134);return this.parseClassElementName(u),this.parsePostMemberNameModifiers(u),l?void this.pushClassPrivateMethod(e,i,!0,!1):(this.isNonstaticConstructor(r)&&this.raise(Bm.ConstructorIsGenerator,r.key),void this.pushClassMethod(e,r,!0,!1,!1,!1))}var p=!this.state.containsEsc&&hR(this.state.type),g=this.parseClassElementName(a),f=p?g.name:null,h=this.isPrivateName(g),m=this.state.startLoc;if(this.parsePostMemberNameModifiers(c),this.isClassMethod()){if(u.kind="method",h)return void this.pushClassPrivateMethod(e,i,!1,!1);var R=this.isNonstaticConstructor(r),y=!1;R&&(r.kind="constructor",r.decorators&&r.decorators.length>0&&this.raise(Bm.DecoratorConstructor,a),n.hadConstructor&&!this.hasPlugin("typescript")&&this.raise(Bm.DuplicateConstructor,g),R&&this.hasPlugin("typescript")&&a.override&&this.raise(Bm.OverrideOnConstructor,g),n.hadConstructor=!0,y=n.hadSuperClass),this.pushClassMethod(e,r,!1,!1,R,y)}else if(this.isClassProperty())h?this.pushClassPrivateProperty(e,s):this.pushClassProperty(e,o);else if("async"!==f||this.isLineTerminator())if("get"!==f&&"set"!==f||this.match(51)&&this.isLineTerminator())if("accessor"!==f||this.isLineTerminator())this.isLineTerminator()?h?this.pushClassPrivateProperty(e,s):this.pushClassProperty(e,o):this.unexpected();else{this.expectPlugin("decoratorAutoAccessors"),this.resetPreviousNodeTrailingComments(g);var v=this.match(134);this.parseClassElementName(o),this.pushClassAccessorProperty(e,d,v)}else{this.resetPreviousNodeTrailingComments(g),u.kind=f;var b=this.match(134);this.parseClassElementName(r),b?this.pushClassPrivateMethod(e,i,!1,!1):(this.isNonstaticConstructor(r)&&this.raise(Bm.ConstructorIsAccessor,r.key),this.pushClassMethod(e,r,!1,!1,!1,!1)),this.checkGetterSetterParams(r)}else{this.resetPreviousNodeTrailingComments(g);var x=this.eat(51);c.optional&&this.unexpected(m),u.kind="method";var S=this.match(134);this.parseClassElementName(u),this.parsePostMemberNameModifiers(c),S?this.pushClassPrivateMethod(e,i,x,!0):(this.isNonstaticConstructor(r)&&this.raise(Bm.ConstructorIsAsync,r.key),this.pushClassMethod(e,r,x,!0,!1,!1))}},n.parseClassElementName=function(e){var a=this.state,n=a.type,t=a.value;if(128!==n&&130!==n||!e.static||"prototype"!==t||this.raise(Bm.StaticPrototype,this.state.startLoc),134===n){"constructor"===t&&this.raise(Bm.ConstructorClassPrivateField,this.state.startLoc);var r=this.parsePrivateName();return e.key=r,r}return this.parsePropertyName(e),e.key},n.parseClassStaticBlock=function(e,a){var n;this.scope.enter(GR|LR|OR);var t=this.state.labels;this.state.labels=[],this.prodParam.enter(yv);var r=a.body=[];this.parseBlockOrModuleBlockBody(r,void 0,!1,4),this.prodParam.exit(),this.scope.exit(),this.state.labels=t,e.body.push(this.finishNode(a,"StaticBlock")),null!=(n=a.decorators)&&n.length&&this.raise(Bm.DecoratorStaticBlock,a)},n.pushClassProperty=function(e,a){!a.computed&&this.nameIsConstructor(a.key)&&this.raise(Bm.ConstructorClassField,a.key),e.body.push(this.parseClassProperty(a))},n.pushClassPrivateProperty=function(e,a){var n=this.parseClassPrivateProperty(a);e.body.push(n),this.classScope.declarePrivateName(this.getPrivateNameSV(n.key),xy,n.key.start)},n.pushClassAccessorProperty=function(e,a,n){n||a.computed||!this.nameIsConstructor(a.key)||this.raise(Bm.ConstructorClassField,a.key);var t=this.parseClassAccessorProperty(a);e.body.push(t),n&&this.classScope.declarePrivateName(this.getPrivateNameSV(t.key),xy,t.key.start)},n.pushClassMethod=function(e,a,n,t,r,i){e.body.push(this.parseMethod(a,n,t,r,i,"ClassMethod",!0))},n.pushClassPrivateMethod=function(e,a,n,t){var r=this.parseMethod(a,n,t,!1,!1,"ClassPrivateMethod",!0);e.body.push(r);var i="get"===r.kind?r.static?Ty:Cy:"set"===r.kind?r.static?wy:Py:xy;this.declareClassPrivateMethodInScope(r,i)},n.declareClassPrivateMethodInScope=function(e,a){this.classScope.declarePrivateName(this.getPrivateNameSV(e.key),a,e.key.start)},n.parsePostMemberNameModifiers=function(e){},n.parseClassPrivateProperty=function(e){return this.parseInitializer(e),this.semicolon(),this.finishNode(e,"ClassPrivateProperty")},n.parseClassProperty=function(e){return this.parseInitializer(e),this.semicolon(),this.finishNode(e,"ClassProperty")},n.parseClassAccessorProperty=function(e){return this.parseInitializer(e),this.semicolon(),this.finishNode(e,"ClassAccessorProperty")},n.parseInitializer=function(e){this.scope.enter(GR|OR),this.expressionScope.enter(Rv()),this.prodParam.enter(yv),e.value=this.eat(25)?this.parseMaybeAssignAllowIn():null,this.expressionScope.exit(),this.prodParam.exit(),this.scope.exit()},n.parseClassId=function(e,a,n,t){if(void 0===t&&(t=iy),hR(this.state.type))e.id=this.parseIdentifier(),a&&this.declareNameFromIdentifier(e.id,t);else{if(!n&&a)throw this.raise(Bm.MissingClassName,this.state.startLoc);e.id=null}},n.parseClassSuper=function(e){this.eat(77)?(this.state.canStartArrow=!1,e.superClass=this.parseExprSubscripts()):e.superClass=null},n.parseExport=function(e,a){var n=this.parseMaybeImportPhase(e,!0),t=this.maybeParseExportDefaultSpecifier(e,n),r=!t||this.eat(8),i=r&&this.eatExportStar(e),o=i&&this.maybeParseExportNamespaceSpecifier(e),s=r&&(!o||this.eat(8)),d=t||i;if(i&&!o){if(t&&this.unexpected(),a)throw this.raise(Bm.UnsupportedDecoratorExport,e);return this.parseExportFrom(e,!0),this.sawUnambiguousESM=!0,this.finishNode(e,"ExportAllDeclaration")}var u,c=this.maybeParseExportNamedSpecifiers(e);if(t&&r&&!i&&!c&&this.unexpected(null,2),o&&s&&this.unexpected(null,94),d||c){if(u=!1,a)throw this.raise(Bm.UnsupportedDecoratorExport,e);this.parseExportFrom(e,d)}else u=this.maybeParseExportDeclaration(e);if(d||c||u){var l,p=e;if(this.checkNamedExport(p,!!p.source),"ClassDeclaration"===(null==(l=p.declaration)?void 0:l.type))this.maybeTakeDecorators(a,p.declaration,p);else if(a)throw this.raise(Bm.UnsupportedDecoratorExport,e);return this.sawUnambiguousESM=!0,this.finishNode(p,"ExportNamedDeclaration")}if(this.eat(61)){var g,f=e,h=this.parseExportDefaultExpression();if(f.declaration=h,"ClassDeclaration"===h.type)this.maybeTakeDecorators(a,h,f);else if(a)throw this.raise(Bm.UnsupportedDecoratorExport,e);if(this.checkDuplicateExports(e,"default"),this.hasPlugin("exportDefaultFrom"))"Identifier"!==h.type||"from"!==h.name||h.end-h.start!==4||null!=(g=h.extra)&&g.parenthesized||this.raise(Bm.ExportDefaultFromAsIdentifier,h);return this.sawUnambiguousESM=!0,this.finishNode(f,"ExportDefaultDeclaration")}throw this.unexpected(null,2)},n.eatExportStar=function(e){return this.eat(51)},n.maybeParseExportDefaultSpecifier=function(e,a){if(a||this.isExportDefaultSpecifier()){this.expectPlugin("exportDefaultFrom",null==a?void 0:a.start);var n=a||this.parseIdentifier(!0),t=this.startNodeAtNode(n);return t.exported=n,e.specifiers=[this.finishNode(t,"ExportDefaultSpecifier")],!0}return!1},n.maybeParseExportNamespaceSpecifier=function(e){if(this.isContextual(89)){var a;null!=(a=e).specifiers||(a.specifiers=[]);var n=this.startNodeAt(this.state.lastTokStartLoc);return this.next(),n.exported=this.parseModuleExportName(),e.specifiers.push(this.finishNode(n,"ExportNamespaceSpecifier")),!0}return!1},n.maybeParseExportNamedSpecifiers=function(e){if(this.match(2)){var a,n=e;n.specifiers||(n.specifiers=[]);var t="type"===n.exportKind;return(a=n.specifiers).push.apply(a,this.parseExportSpecifiers(t)),n.source=null,n.attributes=[],n.declaration=null,!0}return!1},n.maybeParseExportDeclaration=function(e){return!!this.shouldParseExportDeclaration()&&(e.specifiers=[],e.source=null,e.attributes=[],e.declaration=this.parseExportDeclaration(e),!0)},n.isAsyncFunction=function(){if(!this.isContextual(91))return!1;var e=this.nextTokenInLineStart();return this.isUnparsedContextual(e,"function")},n.parseExportDefaultExpression=function(){var e=this.startNode();if(this.match(64))return this.next(),this.parseFunction(e,Uv|Wv);if(this.isAsyncFunction())return this.next(),this.next(),this.parseFunction(e,Uv|Wv|Vv);if(this.match(76))return this.parseClass(e,!0,!0);if(this.match(22))return this.parseClass(this.maybeTakeDecorators(this.parseDecorators(!1),this.startNode()),!0,!0);if(this.match(71)||this.match(70)||this.isLet()||this.isUsing()||this.isAwaitUsing())throw this.raise(Bm.UnsupportedDefaultExport,this.state.startLoc);var a=this.parseMaybeAssignAllowIn();return this.semicolon(),a},n.parseExportDeclaration=function(e){return this.match(76)?this.parseClass(this.startNode(),!0,!1):this.parseStatementListItem()},n.isExportDefaultSpecifier=function(){var e=this.state.type;if(hR(e)){if(91===e&&!this.state.containsEsc||96===e)return!1;if((126===e||125===e)&&!this.state.containsEsc){var a=this.nextTokenStart(),n=this.input.charCodeAt(a);if(123===n||this.chStartsBindingIdentifier(n,a)&&!this.input.startsWith("from",a))return this.expectOnePlugin(["flow","typescript"]),!1}}else if(!this.match(61))return!1;var t=this.nextTokenStart(),r=this.isUnparsedContextual(t,"from");if(44===this.input.charCodeAt(t)||hR(this.state.type)&&r)return!0;if(this.match(61)&&r){var i=this.input.charCodeAt(this.nextTokenStartSince(t+4));return 34===i||39===i}return!1},n.parseExportFrom=function(e,a){this.eatContextual(94)?(e.source=this.parseImportSource(),this.maybeParseImportAttributes(e)):a&&this.unexpected(),this.semicolon()},n.shouldParseExportDeclaration=function(){var e=this.state.type;return!(22!==e||(this.expectOnePlugin(["decorators","decorators-legacy"]),!this.hasPlugin("decorators")))||(this.isUsing()||this.isAwaitUsing()?(this.raise(Bm.UsingDeclarationExport,this.state.startLoc),!0):70===e||71===e||64===e||76===e||this.isLet()||this.isAsyncFunction())},n.checkNamedExport=function(e,a){var n;if(null!=(n=e.specifiers)&&n.length)for(var t=0,r=e.specifiers;t() => ...`.",ReservedTypeAssertion:"This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",SetAccessorCannotHaveOptionalParameter:"A 'set' accessor cannot have an optional parameter.",SetAccessorCannotHaveRestParameter:"A 'set' accessor cannot have rest parameter.",SetAccessorCannotHaveReturnType:"A 'set' accessor cannot have a return type annotation.",SingleTypeParameterWithoutTrailingComma:function(e){var a=e.typeParameterName;return"Single type parameter "+a+" should have a trailing comma. Example usage: <"+a+",>."},StaticBlockCannotHaveModifier:"Static class blocks cannot have any modifier.",TupleOptionalAfterType:"A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).",TypeAnnotationAfterAssign:"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",TypeImportCannotSpecifyDefaultAndNamed:"A type-only import can specify a default import or named bindings, but not both.",TypeModifierIsUsedInTypeExports:"The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",TypeModifierIsUsedInTypeImports:"The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",UnexpectedParameterInitializer:"A parameter initializer is only allowed in a function or constructor implementation.",UnexpectedParameterModifier:"A parameter property is only allowed in a constructor implementation.",UnexpectedReadonly:"'readonly' type modifier is only permitted on array and tuple literal types.",UnexpectedTypeAnnotation:"Did not expect a type annotation here.",UnexpectedTypeCastInParameter:"Unexpected type cast in parameter position.",UnexpectedTypeDeclaration:function(e){return"'"+e+"' declarations can only be declared inside a block."},UnsupportedImportTypeArgument:"Argument in a type import must be a string literal.",UnsupportedParameterPropertyKind:"A parameter property may not be declared using a binding pattern.",UnsupportedSignatureParameterKind:function(e){return"Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got "+e.type+"."},UsingDeclarationInAmbientContext:function(e){return"'"+e+"' declarations are not allowed in ambient contexts."}});function tb(e){return"private"===e||"public"===e||"protected"===e}function rb(e){return"in"===e||"out"===e}function ib(e){var a;if(null!=(a=e.extra)&&a.parenthesized)return!1;switch(e.type){case"Identifier":return!0;case"MemberExpression":return!e.computed&&ib(e.object);case"TSInstantiationExpression":return ib(e.expression);default:return!1}}var ob,sb=0,db=1,ub=2,cb=yb(["declare","private","public","protected","override","abstract","readonly","static"],["in","out"]),lb=yb(["readonly"],["declare","abstract","private","protected","public","static","override"]),pb=yb(["public","private","protected","override","readonly"]),gb=yb(["private","public","protected"]);function fb(e){if("MemberExpression"!==e.type)return!1;var a=e.computed,n=e.property;return(!a||"StringLiteral"===n.type||!("TemplateLiteral"!==n.type||n.expressions.length>0))&&Rb(e.object)}function hb(e,a){var n,t=e.type;if(null!=(n=e.extra)&&n.parenthesized)return!1;if(a){if("Literal"===t){var r=e.value;if("string"==typeof r||"boolean"==typeof r)return!0}}else if("StringLiteral"===t||"BooleanLiteral"===t)return!0;return!(!mb(e,a)&&!function(e,a){if("UnaryExpression"===e.type){var n=e.operator,t=e.argument;if("-"===n&&mb(t,a))return!0}return!1}(e,a))||("TemplateLiteral"===t&&0===e.expressions.length||!!fb(e))}function mb(e,a){return a?"Literal"===e.type&&("number"==typeof e.value||"bigint"in e):"NumericLiteral"===e.type||"BigIntLiteral"===e.type}function Rb(e){return"Identifier"===e.type||"MemberExpression"===e.type&&!e.computed&&Rb(e.object)}function yb(e,a){void 0===a&&(a=[]);for(var n=new Map,t=0;t0&&o.start===r.start&&this.resetStartLocation(r,t)}return r},n.stopParseSubscript=function(a,n){var t=e.prototype.stopParseSubscript.call(this,a,n);return n.optionalChainMember?this.estreeParseChainExpression(t,a):t},n.parseMember=function(a,n,t,r,i){var o=e.prototype.parseMember.call(this,a,n,t,r,i);return"OptionalMemberExpression"===o.type?this.castNodeTo(o,"MemberExpression"):o.optional=!1,o},n.isOptionalMemberExpression=function(a){return"ChainExpression"===a.type?"MemberExpression"===a.expression.type:e.prototype.isOptionalMemberExpression.call(this,a)},n.hasPropertyAsPrivateName=function(a){return"ChainExpression"===a.type&&(a=a.expression),e.prototype.hasPropertyAsPrivateName.call(this,a)},n.isObjectProperty=function(e){return"Property"===e.type&&"init"===e.kind&&!e.method},n.isObjectMethod=function(e){return"Property"===e.type&&(e.method||"get"===e.kind||"set"===e.kind)},n.castNodeTo=function(a,n){var t=e.prototype.castNodeTo.call(this,a,n);return this.fillOptionalPropertiesForTSESLint(t),t},n.cloneIdentifier=function(a){var n=e.prototype.cloneIdentifier.call(this,a);return this.fillOptionalPropertiesForTSESLint(n),n},n.cloneStringLiteral=function(a){return"Literal"===a.type?this.cloneEstreeStringLiteral(a):e.prototype.cloneStringLiteral.call(this,a)},n.finishNodeAt=function(a,n,t){return Xm(e.prototype.finishNodeAt.call(this,a,n,t))},n.finishNodeAtNode=function(a,n,t){return Xm(e.prototype.finishNodeAtNode.call(this,a,n,t))},n.finishNode=function(a,n){var t=e.prototype.finishNode.call(this,a,n);return this.fillOptionalPropertiesForTSESLint(t),t},n.resetStartLocation=function(a,n){e.prototype.resetStartLocation.call(this,a,n),Xm(a)},n.resetEndLocation=function(a,n){void 0===n&&(n=this.state.lastTokEndLoc),e.prototype.resetEndLocation.call(this,a,n),Xm(a)},i(a)}(e)},jsx:function(e){return function(e){function a(){return e.apply(this,arguments)||this}u(a,e);var n=a.prototype;return n.jsxReadToken=function(){for(var a="",n=this.state.pos;;){if(this.state.pos>=this.length)throw this.raise(zy.UnterminatedJsxContent,this.state.startLoc);var t=this.input.charCodeAt(this.state.pos);switch(t){case 60:case 123:return this.state.pos===this.state.start?void(60===t&&this.state.canStartJSXElement?(++this.state.pos,this.finishToken(138)):e.prototype.getTokenFromCode.call(this,t)):(a+=this.input.slice(n,this.state.pos),void this.finishToken(137,a));case 38:a+=this.input.slice(n,this.state.pos),a+=this.jsxReadEntity(),n=this.state.pos;break;case 62:case 125:this.raise(zy.UnexpectedToken,this.state.curPosition(),{unexpected:this.input[this.state.pos],HTMLEntity:125===t?"}":">"});default:Wy(t)?(a+=this.input.slice(n,this.state.pos),a+=this.jsxReadNewLine(!0),n=this.state.pos):++this.state.pos}}},n.jsxReadNewLine=function(e){var a,n=this.input.charCodeAt(this.state.pos);return++this.state.pos,13===n&&10===this.input.charCodeAt(this.state.pos)?(++this.state.pos,a=e?"\n":"\r\n"):a=String.fromCharCode(n),++this.state.curLine,this.state.lineStart=this.state.pos,a},n.jsxReadString=function(e){for(var a="",n=++this.state.pos;;){if(this.state.pos>=this.length)throw this.raise(Bm.UnterminatedString,this.state.startLoc);var t=this.input.charCodeAt(this.state.pos);if(t===e)break;38===t?(a+=this.input.slice(n,this.state.pos),a+=this.jsxReadEntity(),n=this.state.pos):Wy(t)?(a+=this.input.slice(n,this.state.pos),a+=this.jsxReadNewLine(!1),n=this.state.pos):++this.state.pos}a+=this.input.slice(n,this.state.pos++),this.finishToken(130,a)},n.jsxReadEntity=function(){var e=++this.state.pos;if(35===this.codePointAtPos(this.state.pos)){++this.state.pos;var a=10;120===this.codePointAtPos(this.state.pos)&&(a=16,++this.state.pos);var n=this.readInt(a,void 0,!1,"bail");if(null!==n&&n<=1114111&&59===this.codePointAtPos(this.state.pos))return++this.state.pos,String.fromCodePoint(n)}else{for(var t=0,r=!1;t++<10&&this.state.posn.index+1&&this.raise(Oy.UnexpectedSpaceBetweenModuloChecks,n),this.eat(6)?(a.value=e.prototype.parseExpression.call(this),this.expect(7),this.finishNode(a,"DeclaredPredicate")):this.finishNode(a,"InferredPredicate")},n.flowParseTypeAndPredicateInitialiser=function(e){var a=this.state.inType;this.state.inType=!0,this.expect(10);var n=null,t=null;return e&&this.match(50)?(this.state.inType=a,t=this.flowParsePredicate()):(n=this.flowParseType(),this.state.inType=a,this.match(50)&&(t=this.flowParsePredicate())),[n,t]},n.flowParseDeclareClass=function(e){return this.next(),this.flowParseInterfaceish(e,!0),this.finishNode(e,"DeclareClass")},n.flowParseDeclareFunction=function(e){this.next();var a=e.id=this.parseIdentifier(),n=this.startNode(),t=this.startNode();this.match(43)?n.typeParameters=this.flowParseTypeParameterDeclaration():n.typeParameters=null,this.expect(6);var r=this.flowParseFunctionTypeParams();n.params=r.params,n.rest=r.rest,n.this=r._this,this.expect(7);var i=this.flowParseTypeAndPredicateInitialiser(!1);return n.returnType=i[0],e.predicate=i[1],t.typeAnnotation=this.finishNode(n,"FunctionTypeAnnotation"),a.typeAnnotation=this.finishNode(t,"TypeAnnotation"),this.resetEndLocation(a),this.semicolon(),this.scope.declareName(e.id.name,by,e.id.start),this.finishNode(e,"DeclareFunction")},n.flowParseDeclare=function(e,a){if(this.match(76))return this.flowParseDeclareClass(e);if(this.match(64))return this.flowParseDeclareFunction(e);if(this.match(70))return this.flowParseDeclareVariable(e);if(this.eatContextual(123))return this.match(12)?this.flowParseDeclareModuleExports(e):(a&&this.raise(Oy.NestedDeclareModule,this.state.lastTokStartLoc),this.flowParseDeclareModule(e));if(this.isContextual(126))return this.flowParseDeclareTypeAlias(e);if(this.isContextual(127))return this.flowParseDeclareOpaqueType(e);if(this.isContextual(125))return this.flowParseDeclareInterface(e);if(this.match(78))return this.flowParseDeclareExportDeclaration(e,a);throw this.unexpected()},n.flowParseDeclareVariable=function(e){return this.next(),e.id=this.flowParseTypeAnnotatableIdentifier(),this.scope.declareName(e.id.name,dy,e.id.start),this.semicolon(),this.finishNode(e,"DeclareVariable")},n.flowParseDeclareModule=function(a){var n=this;this.scope.enter(kR),this.match(130)?a.id=e.prototype.parseExprAtom.call(this):a.id=this.parseIdentifier();var t=this.startNode(),r=t.body=[];for(this.expect(2);!this.match(4);){var i=this.startNode();this.match(79)?(this.next(),this.isContextual(126)||this.match(83)||this.raise(Oy.InvalidNonTypeImportInDeclareModule,this.state.lastTokStartLoc),r.push(e.prototype.parseImport.call(this,i))):(this.expectContextual(121,Oy.UnsupportedStatementInDeclareModule),r.push(this.flowParseDeclare(i,!0)))}this.scope.exit(),this.expect(4),a.body=this.finishNode(t,"BlockStatement");var o=null,s=!1;return r.forEach(function(e){!function(e){return"DeclareExportAllDeclaration"===e.type||"DeclareExportDeclaration"===e.type&&(!e.declaration||"TypeAlias"!==e.declaration.type&&"InterfaceDeclaration"!==e.declaration.type)}(e)?"DeclareModuleExports"===e.type&&(s&&n.raise(Oy.DuplicateDeclareModuleExports,e),"ES"===o&&n.raise(Oy.AmbiguousDeclareModuleKind,e),o="CommonJS",s=!0):("CommonJS"===o&&n.raise(Oy.AmbiguousDeclareModuleKind,e),o="ES")}),a.kind=o||"CommonJS",this.finishNode(a,"DeclareModule")},n.flowParseDeclareExportDeclaration=function(e,a){if(this.expect(78),this.eat(61))return this.match(64)||this.match(76)?e.declaration=this.flowParseDeclare(this.startNode()):(e.declaration=this.flowParseType(),this.semicolon()),e.default=!0,this.finishNode(e,"DeclareExportDeclaration");if(this.match(71)||this.isLet()||(this.isContextual(126)||this.isContextual(125))&&!a){var n=this.state.value;throw this.raise(Oy.UnsupportedDeclareExportKind,this.state.startLoc,{unsupportedExportKind:n,suggestion:My[n]})}if(this.match(70)||this.match(64)||this.match(76)||this.isContextual(127))return e.declaration=this.flowParseDeclare(this.startNode()),e.default=!1,this.finishNode(e,"DeclareExportDeclaration");if(this.match(51)||this.match(2)||this.isContextual(125)||this.isContextual(126)||this.isContextual(127)){var t=this.parseExport(e,null);return"ExportNamedDeclaration"===t.type?(t.default=!1,delete t.exportKind,this.castNodeTo(t,"DeclareExportDeclaration")):this.castNodeTo(t,"DeclareExportAllDeclaration")}throw this.unexpected()},n.flowParseDeclareModuleExports=function(e){return this.next(),this.expectContextual(107),e.typeAnnotation=this.flowParseTypeAnnotation(),this.semicolon(),this.finishNode(e,"DeclareModuleExports")},n.flowParseDeclareTypeAlias=function(e){this.next();var a=this.flowParseTypeAlias(e);return this.castNodeTo(a,"DeclareTypeAlias"),a},n.flowParseDeclareOpaqueType=function(e){return this.next(),this.flowParseOpaqueType(e,!0)},n.flowParseDeclareInterface=function(e){return this.next(),this.flowParseInterfaceish(e,!1),this.finishNode(e,"DeclareInterface")},n.flowParseInterfaceish=function(e,a){if(e.id=this.flowParseRestrictedIdentifier(!a,!0),this.scope.declareName(e.id.name,a?uy:oy,e.id.start),this.match(43)?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.extends=[],this.eat(77))do{e.extends.push(this.flowParseInterfaceExtends())}while(!a&&this.eat(8));if(a){var n=[],t=[];if(this.eatContextual(113))do{t.push(this.flowParseInterfaceExtends())}while(this.eat(8));if(this.eatContextual(109))do{n.push(this.flowParseClassImplements())}while(this.eat(8));e.implements=n,e.mixins=t}e.body=this.flowParseObjectType({allowStatic:a,allowExact:!1,allowSpread:!1,allowProto:a,allowInexact:!1})},n.flowParseInterfaceExtends=function(){var e=this.startNode();return e.id=this.flowParseQualifiedTypeIdentifier(),this.match(43)?e.typeParameters=this.flowParseTypeParameterInstantiation():e.typeParameters=null,this.finishNode(e,"InterfaceExtends")},n.flowParseInterface=function(e){return this.flowParseInterfaceish(e,!1),this.finishNode(e,"InterfaceDeclaration")},n.checkNotUnderscore=function(e){"_"===e&&this.raise(Oy.UnexpectedReservedUnderscore,this.state.startLoc)},n.checkReservedType=function(e,a,n){jy.has(e)&&this.raise(n?Oy.AssignReservedType:Oy.UnexpectedReservedType,a,{reservedType:e})},n.flowParseRestrictedIdentifierName=function(e,a){return this.checkReservedType(this.state.value,this.state.startLoc,a),this.parseIdentifierName(e)},n.flowParseRestrictedIdentifier=function(e,a){var n=this.startNode(),t=this.flowParseRestrictedIdentifierName(e,a);return this.createIdentifier(n,t)},n.flowParseTypeAlias=function(e){return e.id=this.flowParseRestrictedIdentifier(!1,!0),this.scope.declareName(e.id.name,oy,e.id.start),this.match(43)?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.right=this.flowParseTypeInitialiser(25),this.semicolon(),this.finishNode(e,"TypeAlias")},n.flowParseOpaqueType=function(e,a){return this.expectContextual(126),e.id=this.flowParseRestrictedIdentifier(!0,!0),this.scope.declareName(e.id.name,oy,e.id.start),this.match(43)?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.supertype=null,this.match(10)&&(e.supertype=this.flowParseTypeInitialiser(10)),e.impltype=null,a||(e.impltype=this.flowParseTypeInitialiser(25)),this.semicolon(),this.finishNode(e,a?"DeclareOpaqueType":"OpaqueType")},n.flowParseTypeParameterBound=function(){if(this.match(10)||this.isContextual(77)){var e=this.startNode();return this.next(),e.typeAnnotation=this.flowParseType(),this.finishNode(e,"TypeAnnotation")}},n.flowParseTypeParameter=function(e){void 0===e&&(e=!1);var a=this.state.startLoc,n=this.startNode(),t=this.flowParseVariance();return n.name=this.flowParseRestrictedIdentifierName(),n.variance=t,n.bound=this.flowParseTypeParameterBound(),this.match(25)?(this.eat(25),n.default=this.flowParseType()):e&&this.raise(Oy.MissingTypeParamDefault,a),this.finishNode(n,"TypeParameter")},n.flowParseTypeParameterDeclaration=function(){var e=this.state.inType,a=this.startNode();a.params=[],this.state.inType=!0,this.match(43)||this.match(138)?this.next():this.unexpected();var n=!1;do{var t=this.flowParseTypeParameter(n);a.params.push(t),t.default&&(n=!0),this.match(44)||this.expect(8)}while(!this.match(44));return this.expect(44),this.state.inType=e,this.finishNode(a,"TypeParameterDeclaration")},n.flowInTopLevelContext=function(e){if(this.curContext()===AR.brace)return e();var a=this.state.context;this.state.context=[a[0]];try{return e()}finally{this.state.context=a}},n.flowParseTypeParameterInstantiationInExpression=function(){if(43===this.reScan_lt())return this.flowParseTypeParameterInstantiation()},n.flowParseTypeParameterInstantiation=function(){var e=this,a=this.startNode(),n=this.state.inType;return this.state.inType=!0,a.params=[],this.flowInTopLevelContext(function(){e.expect(43);var n=e.state.noAnonFunctionType;for(e.state.noAnonFunctionType=!1;!e.match(44);)a.params.push(e.flowParseType()),e.match(44)||e.expect(8);e.state.noAnonFunctionType=n}),this.state.inType=n,this.state.inType||this.curContext()!==AR.brace||this.reScan_lt_gt(),this.expect(44),this.finishNode(a,"TypeParameterInstantiation")},n.flowParseTypeParameterInstantiationCallOrNew=function(){if(43!==this.reScan_lt())return null;var e=this.startNode(),a=this.state.inType;for(e.params=[],this.state.inType=!0,this.expect(43);!this.match(44);)e.params.push(this.flowParseTypeOrImplicitInstantiation()),this.match(44)||this.expect(8);return this.expect(44),this.state.inType=a,this.finishNode(e,"TypeParameterInstantiation")},n.flowParseInterfaceType=function(){var e=this.startNode();if(this.expectContextual(125),e.extends=[],this.eat(77))do{e.extends.push(this.flowParseInterfaceExtends())}while(this.eat(8));return e.body=this.flowParseObjectType({allowStatic:!1,allowExact:!1,allowSpread:!1,allowProto:!1,allowInexact:!1}),this.finishNode(e,"InterfaceTypeAnnotation")},n.flowParseObjectPropertyKey=function(){return this.match(131)||this.match(130)?e.prototype.parseExprAtom.call(this):this.parseIdentifier(!0)},n.flowParseObjectTypeIndexer=function(e,a,n){return e.static=a,10===this.lookahead().type?(e.id=this.parseIdentifier(!0),e.key=this.flowParseTypeInitialiser()):(e.id=null,e.key=this.flowParseType()),this.expect(1),e.value=this.flowParseTypeInitialiser(),e.variance=n,this.finishNode(e,"ObjectTypeIndexer")},n.flowParseObjectTypeInternalSlot=function(e,a){return e.static=a,e.id=this.parseIdentifier(!0),this.expect(1),this.expect(1),this.match(43)||this.match(6)?(e.method=!0,e.optional=!1,e.value=this.flowParseObjectTypeMethodish(this.startNodeAtNode(e))):(e.method=!1,this.eat(13)&&(e.optional=!0),e.value=this.flowParseTypeInitialiser()),this.finishNode(e,"ObjectTypeInternalSlot")},n.flowParseObjectTypeMethodish=function(e){for(e.params=[],e.rest=null,e.typeParameters=null,e.this=null,this.match(43)&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),this.expect(6),this.match(74)&&(e.this=this.flowParseFunctionTypeParam(!0),e.this.name=null,this.match(7)||this.expect(8));!this.match(7)&&!this.match(17);)e.params.push(this.flowParseFunctionTypeParam(!1)),this.match(7)||this.expect(8);return this.eat(17)&&(e.rest=this.flowParseFunctionTypeParam(!1)),this.expect(7),e.returnType=this.flowParseTypeInitialiser(),this.finishNode(e,"FunctionTypeAnnotation")},n.flowParseObjectTypeCallProperty=function(e,a){var n=this.startNode();return e.static=a,e.value=this.flowParseObjectTypeMethodish(n),this.finishNode(e,"ObjectTypeCallProperty")},n.flowParseObjectType=function(e){var a=e.allowStatic,n=e.allowExact,t=e.allowSpread,r=e.allowProto,i=e.allowInexact,o=this.state.inType;this.state.inType=!0;var s,d,u=this.startNode();u.callProperties=[],u.properties=[],u.indexers=[],u.internalSlots=[];var c=!1;for(n&&this.match(3)?(this.expect(3),s=5,d=!0):(this.expect(2),s=4,d=!1),u.exact=d;!this.match(s);){var l=!1,p=null,g=null,f=this.startNode();if(r&&this.isContextual(114)){var h=this.lookahead();10!==h.type&&13!==h.type&&(this.next(),p=this.state.startLoc,a=!1)}if(a&&this.isContextual(102)){var m=this.lookahead();10!==m.type&&13!==m.type&&(this.next(),l=!0)}var R=this.flowParseVariance();if(this.eat(0))null!=p&&this.unexpected(p),this.eat(0)?(R&&this.unexpected(R.start),u.internalSlots.push(this.flowParseObjectTypeInternalSlot(f,l))):u.indexers.push(this.flowParseObjectTypeIndexer(f,l,R));else if(this.match(6)||this.match(43))null!=p&&this.unexpected(p),R&&this.unexpected(R.start),u.callProperties.push(this.flowParseObjectTypeCallProperty(f,l));else{var y="init";if(this.isContextual(95)||this.isContextual(100))RR(this.lookahead().type)&&(y=this.state.value,this.next());var v=this.flowParseObjectTypeProperty(f,l,p,R,y,t,null!=i?i:!d);null===v?(c=!0,g=this.state.lastTokStartLoc):u.properties.push(v)}this.flowObjectTypeSemicolon(),!g||this.match(4)||this.match(5)||this.raise(Oy.UnexpectedExplicitInexactInObject,g)}this.expect(s),t&&(u.inexact=c);var b=this.finishNode(u,"ObjectTypeAnnotation");return this.state.inType=o,b},n.flowParseObjectTypeProperty=function(e,a,n,t,r,i,o){if(this.eat(17))return this.match(8)||this.match(9)||this.match(4)||this.match(5)?(i?o||this.raise(Oy.InexactInsideExact,this.state.lastTokStartLoc):this.raise(Oy.InexactInsideNonObject,this.state.lastTokStartLoc),t&&this.raise(Oy.InexactVariance,t),null):(i||this.raise(Oy.UnexpectedSpreadType,this.state.lastTokStartLoc),null!=n&&this.unexpected(n),t&&this.raise(Oy.SpreadVariance,t),e.argument=this.flowParseType(),this.finishNode(e,"ObjectTypeSpreadProperty"));e.key=this.flowParseObjectPropertyKey(),e.static=a,e.proto=null!=n,e.kind=r;var s=!1;return this.match(43)||this.match(6)?(e.method=!0,null!=n&&this.unexpected(n),t&&this.unexpected(t.start),e.value=this.flowParseObjectTypeMethodish(this.startNodeAtNode(e)),"get"===r||"set"===r?this.flowCheckGetterSetterParams(e):a||i||"constructor"!==e.key.name||!e.value.this||this.raise(Oy.ThisParamBannedInConstructor,e.value.this)):("init"!==r&&this.unexpected(),e.method=!1,this.eat(13)&&(s=!0),e.value=this.flowParseTypeInitialiser(),e.variance=t),e.optional=s,this.finishNode(e,"ObjectTypeProperty")},n.flowCheckGetterSetterParams=function(e){var a="get"===e.kind?0:1,n=e.value,t=n.params.length+(n.rest?1:0);n.this&&this.raise("get"===e.kind?Oy.GetterMayNotHaveThisParam:Oy.SetterMayNotHaveThisParam,n.this),t!==a&&this.raise("get"===e.kind?Bm.BadGetterArity:Bm.BadSetterArity,e),"set"===e.kind&&n.rest&&this.raise(Bm.BadSetterRestParameter,e)},n.flowObjectTypeSemicolon=function(){this.eat(9)||this.eat(8)||this.match(4)||this.match(5)||this.unexpected()},n.flowParseQualifiedTypeIdentifier=function(e,a){null!=e||(e=this.state.startLoc);for(var n=a||this.flowParseRestrictedIdentifier(!0);this.eat(12);){var t=this.startNodeAt(e);t.qualification=n,t.id=this.flowParseRestrictedIdentifier(!0),n=this.finishNode(t,"QualifiedTypeIdentifier")}return n},n.flowParseGenericType=function(e,a){var n=this.startNodeAt(e);return n.typeParameters=null,n.id=this.flowParseQualifiedTypeIdentifier(e,a),this.match(43)&&(n.typeParameters=this.flowParseTypeParameterInstantiation()),this.finishNode(n,"GenericTypeAnnotation")},n.flowParseTypeofType=function(){var e=this.startNode();return this.expect(83),e.argument=this.flowParsePrimaryType(),this.finishNode(e,"TypeofTypeAnnotation")},n.flowParseTupleType=function(){var e=this.startNode();for(e.types=[],this.expect(0);this.state.pos0){var f=[].concat(o);if(g.length>0){this.state=i,this.state.noArrowAt=f;for(var h=0;h1&&this.raise(Oy.AmbiguousConditionalArrow,i.startLoc),c&&1===p.length)this.state=i,f.push(p[0].start),this.state.noArrowAt=f,u=this.tryParseConditionalConsequent().consequent}return this.getArrowLikeExpressions(u,!0),this.state.noArrowAt=o,this.expect(10),s.test=e,s.consequent=u,s.alternate=this.forwardNoArrowParamsConversionAt(s,function(){return t.parseMaybeAssign()}),this.finishNode(s,"ConditionalExpression")},n.tryParseConditionalConsequent=function(){this.state.noArrowParamsConversionAt.push(this.state.start);var e=this.parseMaybeAssignAllowIn(),a=!this.match(10);return this.state.noArrowParamsConversionAt.pop(),{consequent:e,failed:a}},n.getArrowLikeExpressions=function(e,a){for(var n=this,t=[e],r=[];0!==t.length;){var i=t.pop();"ArrowFunctionExpression"===i.type?(i.typeParameters||!i.returnType?this.finishArrowValidation(i):r.push(i),"BlockStatement"!==i.body.type&&t.push(i.body)):"ConditionalExpression"===i.type&&(t.push(i.consequent),t.push(i.alternate))}return a?(r.forEach(function(e){return n.finishArrowValidation(e)}),[r,[]]):function(e,a){for(var n=[],t=[],r=0;r1)&&a||this.raise(Oy.TypeCastInPattern,r.typeAnnotation)}return e},n.parseArrayLike=function(a,n){var t=e.prototype.parseArrayLike.call(this,a,n);return"ArrayExpression"===t.type&&this.toReferencedList(t.elements),t},n.isValidLVal=function(a,n,t,r){return"TypeCastExpression"===a||e.prototype.isValidLVal.call(this,a,n,t,r)},n.parseClassProperty=function(a){return this.match(10)&&(a.typeAnnotation=this.flowParseTypeAnnotation()),e.prototype.parseClassProperty.call(this,a)},n.parseClassPrivateProperty=function(a){return this.match(10)&&(a.typeAnnotation=this.flowParseTypeAnnotation()),e.prototype.parseClassPrivateProperty.call(this,a)},n.isClassMethod=function(){return this.match(43)||e.prototype.isClassMethod.call(this)},n.isClassProperty=function(){return this.match(10)||e.prototype.isClassProperty.call(this)},n.isNonstaticConstructor=function(a){return!this.match(10)&&e.prototype.isNonstaticConstructor.call(this,a)},n.pushClassMethod=function(a,n,t,r,i,o){if(n.variance&&this.unexpected(n.variance.start),delete n.variance,this.match(43)&&(n.typeParameters=this.flowParseTypeParameterDeclaration()),e.prototype.pushClassMethod.call(this,a,n,t,r,i,o),n.params&&i){var s=n.params;s.length>0&&this.isThisParam(s[0])&&this.raise(Oy.ThisParamBannedInConstructor,n)}else if("MethodDefinition"===n.type&&i&&n.value.params){var d=n.value.params;d.length>0&&this.isThisParam(d[0])&&this.raise(Oy.ThisParamBannedInConstructor,n)}},n.pushClassPrivateMethod=function(a,n,t,r){n.variance&&this.unexpected(n.variance.start),delete n.variance,this.match(43)&&(n.typeParameters=this.flowParseTypeParameterDeclaration()),e.prototype.pushClassPrivateMethod.call(this,a,n,t,r)},n.flowParseClassImplements=function(){var e=this.startNode();return e.id=this.flowParseRestrictedIdentifier(!0),this.match(43)?e.typeParameters=this.flowParseTypeParameterInstantiation():e.typeParameters=null,this.finishNode(e,"ClassImplements")},n.parseClassSuper=function(a){if(e.prototype.parseClassSuper.call(this,a),a.superClass&&(this.match(43)||this.match(47))&&(a.superTypeArguments=this.flowParseTypeParameterInstantiationInExpression()),this.eatContextual(109)){var n=a.implements=[];do{n.push(this.flowParseClassImplements())}while(this.eat(8))}},n.checkGetterSetterParams=function(a){e.prototype.checkGetterSetterParams.call(this,a);var n=this.getObjectOrClassMethodParams(a);if(n.length>0){var t=n[0];this.isThisParam(t)&&"get"===a.kind?this.raise(Oy.GetterMayNotHaveThisParam,t):this.isThisParam(t)&&this.raise(Oy.SetterMayNotHaveThisParam,t)}},n.parsePropertyNamePrefixOperator=function(e){e.variance=this.flowParseVariance()},n.parseObjPropValue=function(a,n,t,r,i,o,s){var d;a.variance&&this.unexpected(a.variance.start),delete a.variance,this.match(43)&&!o&&(d=this.flowParseTypeParameterDeclaration(),this.match(6)||this.unexpected());var u=e.prototype.parseObjPropValue.call(this,a,n,t,r,i,o,s);return d&&((u.value||u).typeParameters=d),u},n.parseFunctionParamType=function(e){return this.eat(13)&&("Identifier"!==e.type&&this.raise(Oy.PatternIsOptional,e),this.isThisParam(e)&&this.raise(Oy.ThisParamMayNotBeOptional,e),e.optional=!0),this.match(10)?e.typeAnnotation=this.flowParseTypeAnnotation():this.isThisParam(e)&&this.raise(Oy.ThisParamAnnotationRequired,e),this.match(25)&&this.isThisParam(e)&&this.raise(Oy.ThisParamNoDefault,e),this.resetEndLocation(e),e},n.parseMaybeDefault=function(a,n){var t=e.prototype.parseMaybeDefault.call(this,a,n);return"AssignmentPattern"===t.type&&t.typeAnnotation&&t.right.start0&&this.raise(Oy.ThisParamMustBeFirst,a.params[i]);e.prototype.checkParams.call(this,a,n,t,r)}},n.parseParenAndDistinguishExpression=function(a){return e.prototype.parseParenAndDistinguishExpression.call(this,a&&!this.state.noArrowAt.includes(this.sourceToOffsetPos(this.state.start)))},n.parseSubscripts=function(a,n,t){var r=this;if("Identifier"===a.type&&"async"===a.name&&this.state.noArrowAt.includes(n.index)){this.next();var i=this.startNodeAt(n);i.callee=a,i.arguments=e.prototype.parseCallExpressionArguments.call(this),a=this.finishNode(i,"CallExpression")}else if("Identifier"===a.type&&"async"===a.name&&this.match(43)){var o=this.state.clone(),s=this.tryParse(function(e){return r.parseAsyncArrowWithTypeParameters(n)||e()},o);if(!s.error&&!s.aborted)return s.node;var d=this.tryParse(function(){return e.prototype.parseSubscripts.call(r,a,n,t)},o);if(d.node&&!d.error)return d.node;if(s.node)return this.state=s.failState,s.node;if(d.node)return this.state=d.failState,d.node;throw s.error||d.error}return e.prototype.parseSubscripts.call(this,a,n,t)},n.parseSubscript=function(a,n,t,r){var i=this;if(this.match(14)&&this.isLookaheadToken_lt()){if(r.optionalChainMember=!0,t)return r.stop=!0,a;this.next();var o=this.startNodeAt(n);return o.callee=a,o.typeArguments=this.flowParseTypeParameterInstantiationInExpression(),this.expect(6),o.arguments=this.parseCallExpressionArguments(),o.optional=!0,this.finishCallExpression(o,!0)}if(!t&&this.shouldParseTypes()&&(this.match(43)||this.match(47))){var s=this.startNodeAt(n);s.callee=a;var d=this.tryParse(function(){return s.typeArguments=i.flowParseTypeParameterInstantiationCallOrNew(),i.expect(6),s.arguments=e.prototype.parseCallExpressionArguments.call(i),r.optionalChainMember&&(s.optional=!1),i.finishCallExpression(s,r.optionalChainMember)});if(d.node)return d.error&&(this.state=d.failState),d.node}return e.prototype.parseSubscript.call(this,a,n,t,r)},n.parseNewCallee=function(a){var n=this;e.prototype.parseNewCallee.call(this,a);var t=null;this.shouldParseTypes()&&this.match(43)&&(t=this.tryParse(function(){return n.flowParseTypeParameterInstantiationCallOrNew()}).node),a.typeArguments=t},n.parseAsyncArrowWithTypeParameters=function(a){var n=this.startNodeAt(a);if(this.parseFunctionParams(n,!1),this.parseArrow(n))return e.prototype.parseArrowExpression.call(this,n,void 0,!0)},n.readToken_mult_modulo=function(a){var n=this.input.charCodeAt(this.state.pos+1);if(42===a&&47===n&&this.state.hasFlowComment)return this.state.hasFlowComment=!1,this.state.pos+=2,void this.nextToken();e.prototype.readToken_mult_modulo.call(this,a)},n.readToken_pipe_amp=function(a){var n=this.input.charCodeAt(this.state.pos+1);124!==a||125!==n?e.prototype.readToken_pipe_amp.call(this,a):this.finishOp(5,2)},n.parseTopLevel=function(a,n){var t=e.prototype.parseTopLevel.call(this,a,n);return this.state.hasFlowComment&&this.raise(Oy.UnterminatedFlowComment,this.state.curPosition()),t},n.skipBlockComment=function(){if(!this.hasPlugin("flowComments")||!this.skipFlowComment())return e.prototype.skipBlockComment.call(this,this.state.hasFlowComment?"*-/":"*/");if(this.state.hasFlowComment)throw this.raise(Oy.NestedFlowComment,this.state.startLoc);this.hasFlowCommentCompletion();var a=this.skipFlowComment();a&&(this.state.pos+=a,this.state.hasFlowComment=!0)},n.skipFlowComment=function(){for(var e=this.state.pos,a=2;[32,9].includes(this.input.charCodeAt(e+a));)a++;var n=this.input.charCodeAt(a+e),t=this.input.charCodeAt(a+e+1);return 58===n&&58===t?a+2:"flow-include"===this.input.slice(a+e,a+e+12)?a+12:58===n&&58!==t&&a},n.hasFlowCommentCompletion=function(){if(-1===this.input.indexOf("*/",this.state.pos))throw this.raise(Bm.UnterminatedComment,this.state.curPosition())},n.flowEnumErrorBooleanMemberNotInitialized=function(e,a){this.raise(Oy.EnumBooleanMemberNotInitialized,e,a)},n.flowEnumErrorInvalidMemberInitializer=function(e,a){return this.raise(a.explicitType?"symbol"===a.explicitType?Oy.EnumInvalidMemberInitializerSymbolType:Oy.EnumInvalidMemberInitializerPrimaryType:Oy.EnumInvalidMemberInitializerUnknownType,e,a)},n.flowEnumErrorNumberMemberNotInitialized=function(e,a){this.raise(Oy.EnumNumberMemberNotInitialized,e,a)},n.flowEnumErrorStringMemberInconsistentlyInitialized=function(e,a){this.raise(Oy.EnumStringMemberInconsistentlyInitialized,e,a)},n.flowEnumMemberInit=function(){var e=this,a=this.state.startLoc,n=function(){return e.match(8)||e.match(4)};switch(this.state.type){case 131:var t=this.parseNumericLiteral(this.state.value);if(n())return{type:"number",loc:t.start,value:t};break;case 130:var r=this.parseStringLiteral(this.state.value);if(n())return{type:"string",loc:r.start,value:r};break;case 81:case 82:var i=this.parseBooleanLiteral(this.match(81));if(n())return{type:"boolean",loc:i.start,value:i}}return{type:"invalid",loc:a}},n.flowEnumMemberRaw=function(){var e=this.state.startLoc;return{id:this.parseIdentifier(!0),init:this.eat(25)?this.flowEnumMemberInit():{type:"none",loc:e}}},n.flowEnumCheckExplicitTypeMismatch=function(e,a,n){var t=a.explicitType;null!==t&&t!==n&&this.flowEnumErrorInvalidMemberInitializer(e,a)},n.flowEnumMembers=function(e){for(var a=e.enumName,n=e.explicitType,t=new Set,r={booleanMembers:[],numberMembers:[],stringMembers:[],defaultedMembers:[]},i=!1;!this.match(4);){if(this.eat(17)){i=!0;break}var o=this.startNode(),s=this.flowEnumMemberRaw(),d=s.id,u=s.init,c=d.name;if(""!==c){/^[a-z]/.test(c)&&this.raise(Oy.EnumInvalidMemberName,d,{memberName:c,suggestion:c[0].toUpperCase()+c.slice(1),enumName:a}),t.has(c)&&this.raise(Oy.EnumDuplicateMemberName,d,{memberName:c,enumName:a}),t.add(c);var l={enumName:a,explicitType:n,memberName:c};switch(o.id=d,u.type){case"boolean":this.flowEnumCheckExplicitTypeMismatch(u.loc,l,"boolean"),o.init=u.value,r.booleanMembers.push(this.finishNode(o,"EnumBooleanMember"));break;case"number":this.flowEnumCheckExplicitTypeMismatch(u.loc,l,"number"),o.init=u.value,r.numberMembers.push(this.finishNode(o,"EnumNumberMember"));break;case"string":this.flowEnumCheckExplicitTypeMismatch(u.loc,l,"string"),o.init=u.value,r.stringMembers.push(this.finishNode(o,"EnumStringMember"));break;case"invalid":throw this.flowEnumErrorInvalidMemberInitializer(u.loc,l);case"none":switch(n){case"boolean":this.flowEnumErrorBooleanMemberNotInitialized(u.loc,l);break;case"number":this.flowEnumErrorNumberMemberNotInitialized(u.loc,l);break;default:r.defaultedMembers.push(this.finishNode(o,"EnumDefaultedMember"))}}this.match(4)||this.expect(8)}}return{members:r,hasUnknownMembers:i}},n.flowEnumStringMembers=function(e,a,n){var t=n.enumName;if(0===e.length)return a;if(0===a.length)return e;if(a.length>e.length){for(var r=0;r=g){for(var f=0,h=s.defaultedMembers;f=g){for(var R=0,y=s.defaultedMembers;R0&&(this.raise(Bm.BadGetterArity,this.state.curPosition()),this.isThisParam(n.params[0])&&this.raise(nb.AccessorCannotDeclareThisParameter,this.state.curPosition()));else if("set"===n.kind){if(1!==n.params.length)this.raise(Bm.BadSetterArity,this.state.curPosition());else{var t=n.params[0];this.isThisParam(t)&&this.raise(nb.AccessorCannotDeclareThisParameter,this.state.curPosition()),"Identifier"===t.type&&t.optional&&this.raise(nb.SetAccessorCannotHaveOptionalParameter,this.state.curPosition()),"RestElement"===t.type&&this.raise(nb.SetAccessorCannotHaveRestParameter,this.state.curPosition())}n.returnType&&this.raise(nb.SetAccessorCannotHaveReturnType,n.returnType)}else n.kind="method";return this.finishNode(n,"TSMethodSignature")}var r=e;a&&(r.readonly=!0);var i=this.tsTryParseTypeAnnotation();return i&&(r.typeAnnotation=i),this.tsParseTypeMemberSemicolon(),this.finishNode(r,"TSPropertySignature")},n.tsParseTypeMember=function(){var a=this.startNode();if(this.match(6)||this.match(43))return this.tsParseSignatureMember("TSCallSignatureDeclaration",a);if(this.match(73)){var n=this.startNode();return this.next(),this.match(6)||this.match(43)?this.tsParseSignatureMember("TSConstructSignatureDeclaration",a):(a.key=this.createIdentifier(n,"new"),this.tsParsePropertyOrMethodSignature(a,!1))}this.tsParseModifiers(lb,void 0,a);var t=this.tsTryParseIndexSignature(a);return t||(e.prototype.parsePropertyName.call(this,a),a.computed||"Identifier"!==a.key.type||"get"!==a.key.name&&"set"!==a.key.name||!this.tsTokenCanFollowModifier()||(a.kind=a.key.name,e.prototype.parsePropertyName.call(this,a),this.match(6)||this.match(43)||this.unexpected(null,6)),this.tsParsePropertyOrMethodSignature(a,!!a.readonly))},n.tsParseTypeLiteral=function(){var e=this.startNode();return e.members=this.tsParseObjectTypeMembers(),this.finishNode(e,"TSTypeLiteral")},n.tsParseObjectTypeMembers=function(){this.expect(2);var e=this.tsParseList("TypeMembers",this.tsParseTypeMember.bind(this));return this.expect(4),e},n.tsIsStartOfMappedType=function(){return this.next(),this.eat(49)?this.isContextual(118):(this.isContextual(118)&&this.next(),!!this.match(0)&&(this.next(),!!this.tsIsIdentifier()&&(this.next(),this.match(54))))},n.tsParseMappedType=function(){var e=this.startNode();return this.expect(2),this.match(49)?(e.readonly=this.state.value,this.next(),this.expectContextual(118)):this.eatContextual(118)&&(e.readonly=!0),this.expect(0),e.key=this.tsParseTypeParameterName(),e.constraint=this.tsExpectThenParseType(54),e.nameType=this.eatContextual(89)?this.tsParseType():null,this.expect(1),this.match(49)?(e.optional=this.state.value,this.next(),this.expect(13)):this.eat(13)&&(e.optional=!0),e.typeAnnotation=this.tsTryParseType(),this.semicolon(),this.expect(4),this.finishNode(e,"TSMappedType")},n.tsParseTupleType=function(){var e=this,a=this.startNode();a.elementTypes=this.tsParseBracketedList("TupleElementTypes",this.tsParseTupleElementType.bind(this),!0,!1);var n=!1;return a.elementTypes.forEach(function(a){var t=a.type;!n||"TSRestType"===t||"TSOptionalType"===t||"TSNamedTupleMember"===t&&a.optional||e.raise(nb.OptionalTypeBeforeRequired,a),n||(n="TSNamedTupleMember"===t&&a.optional||"TSOptionalType"===t)}),this.finishNode(a,"TSTupleType")},n.tsParseTupleElementType=function(){var e,a,n,t,r,i=this.state.startLoc,o=this.eat(17),s=this.state.startLoc,d=mR(this.state.type)?this.lookaheadCharCode():null;if(58===d)e=!0,n=!1,a=this.parseIdentifier(!0),this.expect(10),t=this.tsParseType();else if(63===d){n=!0;var u=this.state.value,c=this.tsParseNonArrayType();58===this.lookaheadCharCode()?(e=!0,a=this.createIdentifier(this.startNodeAt(s),u),this.expect(13),this.expect(10),t=this.tsParseType()):(e=!1,t=c,this.expect(13))}else t=this.tsParseType(),n=this.eat(13),e=this.eat(10);if(e)a?((r=this.startNodeAt(s)).optional=n,r.label=a,r.elementType=t,this.eat(13)&&(r.optional=!0,this.raise(nb.TupleOptionalAfterType,this.state.lastTokStartLoc))):((r=this.startNodeAt(s)).optional=n,this.raise(nb.InvalidTupleMemberLabel,t),r.label=t,r.elementType=this.tsParseType()),t=this.finishNode(r,"TSNamedTupleMember");else if(n){var l=this.startNodeAt(s);l.typeAnnotation=t,t=this.finishNode(l,"TSOptionalType")}if(o){var p=this.startNodeAt(i);p.typeAnnotation=t,t=this.finishNode(p,"TSRestType")}return t},n.tsParseParenthesizedType=function(){var e=this.startNode();return this.expect(6),e.typeAnnotation=this.tsParseType(),this.expect(7),this.finishNode(e,"TSParenthesizedType")},n.tsParseFunctionOrConstructorType=function(e,a){var n=this,t=this.startNode();return"TSConstructorType"===e&&(t.abstract=!!a,a&&this.next(),this.next()),this.tsInAllowConditionalTypesContext(function(){return n.tsFillSignature(15,t)}),this.finishNode(t,e)},n.tsParseLiteralTypeNode=function(){var a=this.startNode();switch(this.state.type){case 131:case 132:case 130:case 81:case 82:a.literal=e.prototype.parseExprAtom.call(this);break;default:this.unexpected()}return this.finishNode(a,"TSLiteralType")},n.tsParseTemplateLiteralType=function(){var e=this.state.startLoc,a=this.parseTemplateElement(!1),n=[a];if(a.tail){var t=this.startNodeAt(e),r=this.startNodeAt(e);return r.expressions=[],r.quasis=n,t.literal=this.finishNode(r,"TemplateLiteral"),this.finishNode(t,"TSLiteralType")}for(var i=[];!a.tail;)i.push(this.tsParseType()),this.readTemplateContinuation(),n.push(a=this.parseTemplateElement(!1));var o=this.startNodeAt(e);return o.types=i,o.quasis=n,this.finishNode(o,"TSTemplateLiteralType")},n.parseTemplateSubstitution=function(){return this.state.inType?this.tsParseType():e.prototype.parseTemplateSubstitution.call(this)},n.tsParseThisTypeOrThisTypePredicate=function(){var e=this.tsParseThisTypeNode();return this.isContextual(112)&&!this.hasPrecedingLineBreak()?this.tsParseThisTypePredicate(e):e},n.tsParseNonArrayType=function(){switch(this.state.type){case 130:case 131:case 132:case 81:case 82:return this.tsParseLiteralTypeNode();case 49:if("-"===this.state.value){var e=this.startNode(),a=this.lookahead();return 131!==a.type&&132!==a.type&&this.unexpected(),e.literal=this.parseMaybeUnary(),this.finishNode(e,"TSLiteralType")}break;case 74:return this.tsParseThisTypeOrThisTypePredicate();case 83:return this.tsParseTypeQuery();case 79:return this.tsParseImportType();case 2:return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this))?this.tsParseMappedType():this.tsParseTypeLiteral();case 0:return this.tsParseTupleType();case 6:if(!(this.optionFlags&Gm)){var n=this.state.startLoc;this.next();var t=this.tsParseType();return this.expect(7),this.addExtra(t,"parenthesized",!0),this.addExtra(t,"parenStart",n.index),t}return this.tsParseParenthesizedType();case 21:case 20:return this.tsParseTemplateLiteralType();default:var r=this.state.type;if(hR(r)||84===r||80===r){var i=84===r?"TSVoidKeyword":80===r?"TSNullKeyword":function(e){switch(e){case"any":return"TSAnyKeyword";case"boolean":return"TSBooleanKeyword";case"bigint":return"TSBigIntKeyword";case"never":return"TSNeverKeyword";case"number":return"TSNumberKeyword";case"object":return"TSObjectKeyword";case"string":return"TSStringKeyword";case"symbol":return"TSSymbolKeyword";case"undefined":return"TSUndefinedKeyword";case"unknown":return"TSUnknownKeyword";default:return}}(this.state.value);if(void 0!==i&&46!==this.lookaheadCharCode()){var o=this.startNode();return this.next(),this.finishNode(o,i)}return this.tsParseTypeReference()}}throw this.unexpected()},n.tsParseArrayTypeOrHigher=function(){for(var e=this.state.startLoc,a=this.tsParseNonArrayType();!this.hasPrecedingLineBreak()&&this.eat(0);)if(this.match(1)){var n=this.startNodeAt(e);n.elementType=a,this.expect(1),a=this.finishNode(n,"TSArrayType")}else{var t=this.startNodeAt(e);t.objectType=a,t.indexType=this.tsParseType(),this.expect(1),a=this.finishNode(t,"TSIndexedAccessType")}return a},n.tsParseTypeOperator=function(){var e=this.startNode(),a=this.state.value;return this.next(),e.operator=a,e.typeAnnotation=this.tsParseTypeOperatorOrHigher(),"readonly"===a&&this.tsCheckTypeAnnotationForReadOnly(e),this.finishNode(e,"TSTypeOperator")},n.tsCheckTypeAnnotationForReadOnly=function(e){switch(e.typeAnnotation.type){case"TSTupleType":case"TSArrayType":return;default:this.raise(nb.UnexpectedReadonly,e)}},n.tsParseInferType=function(){var e=this,a=this.startNode();this.expectContextual(111);var n=this.startNode();return n.name=this.tsParseTypeParameterName(),n.constraint=this.tsTryParse(function(){return e.tsParseConstraintForInferType()}),a.typeParameter=this.finishNode(n,"TSTypeParameter"),this.finishNode(a,"TSInferType")},n.tsParseConstraintForInferType=function(){var e=this;if(this.eat(77)){var a=this.tsInDisallowConditionalTypesContext(function(){return e.tsParseType()});if(this.state.inDisallowConditionalTypesContext||!this.match(13))return a}},n.tsParseTypeOperatorOrHigher=function(){var e,a=this;return(e=this.state.type)>=117&&e<=119&&!this.state.containsEsc?this.tsParseTypeOperator():this.isContextual(111)?this.tsParseInferType():this.tsInAllowConditionalTypesContext(function(){return a.tsParseArrayTypeOrHigher()})},n.tsParseUnionOrIntersectionType=function(e,a,n){var t=this.startNode(),r=this.eat(n),i=[];do{i.push(a())}while(this.eat(n));return 1!==i.length||r?(t.types=i,this.finishNode(t,e)):i[0]},n.tsParseIntersectionTypeOrHigher=function(){return this.tsParseUnionOrIntersectionType("TSIntersectionType",this.tsParseTypeOperatorOrHigher.bind(this),41)},n.tsParseUnionTypeOrHigher=function(){return this.tsParseUnionOrIntersectionType("TSUnionType",this.tsParseIntersectionTypeOrHigher.bind(this),39)},n.tsIsStartOfFunctionType=function(){return!!this.match(43)||this.match(6)&&this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this))},n.tsSkipParameterStart=function(){if(hR(this.state.type)||this.match(74))return this.next(),!0;if(this.match(2)){var a=this.state.errors,n=a.length;try{return this.parseObjectLike(4,!0),a.length===n}catch(e){return!1}}if(this.match(0)){this.next();var t=this.state.errors,r=t.length;try{return e.prototype.parseBindingList.call(this,1,93,Iv),t.length===r}catch(e){return!1}}return!1},n.tsIsUnambiguouslyStartOfFunctionType=function(){if(this.next(),this.match(7)||this.match(17))return!0;if(this.tsSkipParameterStart()){if(this.match(10)||this.match(8)||this.match(13)||this.match(25))return!0;if(this.match(7)&&(this.next(),this.match(15)))return!0}return!1},n.tsParseTypeOrTypePredicateAnnotation=function(e){var a=this;return this.tsInType(function(){var n=a.startNode();a.expect(e);var t=a.startNode(),r=!!a.tsTryParse(a.tsParseTypePredicateAsserts.bind(a));if(r&&a.match(74)){var i=a.tsParseThisTypeOrThisTypePredicate();return"TSThisType"===i.type?(t.parameterName=i,t.asserts=!0,t.typeAnnotation=null,i=a.finishNode(t,"TSTypePredicate")):(a.resetStartLocationFromNode(i,t),i.asserts=!0),n.typeAnnotation=i,a.finishNode(n,"TSTypeAnnotation")}var o=a.tsIsIdentifier()&&a.tsTryParse(a.tsParseTypePredicatePrefix.bind(a));if(!o)return r?(t.parameterName=a.parseIdentifier(),t.asserts=r,t.typeAnnotation=null,n.typeAnnotation=a.finishNode(t,"TSTypePredicate"),a.finishNode(n,"TSTypeAnnotation")):a.tsParseTypeAnnotation(!1,n);var s=a.tsParseTypeAnnotation(!1);return t.parameterName=o,t.typeAnnotation=s,t.asserts=r,n.typeAnnotation=a.finishNode(t,"TSTypePredicate"),a.finishNode(n,"TSTypeAnnotation")})},n.tsTryParseTypeOrTypePredicateAnnotation=function(){if(this.match(10))return this.tsParseTypeOrTypePredicateAnnotation(10)},n.tsTryParseTypeAnnotation=function(){if(this.match(10))return this.tsParseTypeAnnotation()},n.tsTryParseType=function(){return this.tsEatThenParseType(10)},n.tsParseTypePredicatePrefix=function(){var e=this.parseIdentifier();if(this.isContextual(112)&&!this.hasPrecedingLineBreak())return this.next(),e},n.tsParseTypePredicateAsserts=function(){if(105!==this.state.type)return!1;var e=this.state.containsEsc;return this.next(),!(!hR(this.state.type)&&!this.match(74))&&(e&&this.raise(Bm.InvalidEscapedReservedWord,this.state.lastTokStartLoc,{reservedWord:"asserts"}),!0)},n.tsParseTypeAnnotation=function(e,a){var n=this;return void 0===e&&(e=!0),void 0===a&&(a=this.startNode()),this.tsInType(function(){e&&n.expect(10),a.typeAnnotation=n.tsParseType()}),this.finishNode(a,"TSTypeAnnotation")},n.tsParseType=function(){var e=this;ab(this.state.inType);var a=this.tsParseNonConditionalType();if(this.state.inDisallowConditionalTypesContext||this.hasPrecedingLineBreak()||!this.eat(77))return a;var n=this.startNodeAtNode(a);return n.checkType=a,n.extendsType=this.tsInDisallowConditionalTypesContext(function(){return e.tsParseNonConditionalType()}),this.expect(13),n.trueType=this.tsInAllowConditionalTypesContext(function(){return e.tsParseType()}),this.expect(10),n.falseType=this.tsInAllowConditionalTypesContext(function(){return e.tsParseType()}),this.finishNode(n,"TSConditionalType")},n.isAbstractConstructorSignature=function(){return this.isContextual(120)&&this.isLookaheadContextual("new")},n.tsParseNonConditionalType=function(){return this.tsIsStartOfFunctionType()?this.tsParseFunctionOrConstructorType("TSFunctionType"):this.match(73)?this.tsParseFunctionOrConstructorType("TSConstructorType"):this.isAbstractConstructorSignature()?this.tsParseFunctionOrConstructorType("TSConstructorType",!0):this.tsParseUnionTypeOrHigher()},n.tsParseTypeAssertion=function(){var e=this;this.getPluginOption("typescript","disallowAmbiguousJSXLike")&&this.raise(nb.ReservedTypeAssertion,this.state.startLoc);var a=this.startNode();return a.typeAnnotation=this.tsInType(function(){return e.next(),e.match(71)?e.tsParseTypeReference():e.tsParseType()}),this.expect(44),a.expression=this.parseMaybeUnary(),this.finishNode(a,"TSTypeAssertion")},n.tsParseHeritageClause=function(a){var n=this,t=this.state.startLoc,r=this.tsParseDelimitedList("HeritageClauseElement",function(){var t=(n.state.canStartArrow=!1,e.prototype.parseExprSubscripts.call(n));ib(t)||n.raise(nb.InvalidHeritageClauseType,t.start,{token:a});var r="extends"===a?"TSInterfaceHeritage":"TSClassImplements";if("TSInstantiationExpression"===t.type)return t.type=r,t;var i=n.startNodeAtNode(t);return i.expression=t,(n.match(43)||n.match(47))&&(i.typeArguments=n.tsParseTypeArgumentsInExpression()),n.finishNode(i,r)});return r.length||this.raise(nb.EmptyHeritageClauseType,t,{token:a}),r},n.tsParseInterfaceDeclaration=function(e,a){if(void 0===a&&(a={}),this.hasFollowingLineBreak())return null;this.expectContextual(125),a.declare&&(e.declare=!0),hR(this.state.type)?(e.id=this.parseIdentifier(),this.checkIdentifier(e.id,cy)):(e.id=null,this.raise(nb.MissingInterfaceName,this.state.startLoc)),e.typeParameters=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers),this.eat(77)&&(e.extends=this.tsParseHeritageClause("extends"));var n=this.startNode();return n.body=this.tsInType(this.tsParseObjectTypeMembers.bind(this)),e.body=this.finishNode(n,"TSInterfaceBody"),this.finishNode(e,"TSInterfaceDeclaration")},n.tsParseTypeAliasDeclaration=function(e){var a=this;return e.id=this.parseIdentifier(),this.checkIdentifier(e.id,ly),e.typeAnnotation=this.tsInType(function(){if(e.typeParameters=a.tsTryParseTypeParameters(a.tsParseInOutModifiers),a.expect(25),a.isContextual(110)&&46!==a.lookaheadCharCode()){var n=a.startNode();return a.next(),a.finishNode(n,"TSIntrinsicKeyword")}return a.tsParseType()}),this.semicolon(),this.finishNode(e,"TSTypeAliasDeclaration")},n.tsInTopLevelContext=function(e){if(this.curContext()===AR.brace)return e();var a=this.state.context;this.state.context=[a[0]];try{return e()}finally{this.state.context=a}},n.tsInType=function(e){var a=this.state.inType;this.state.inType=!0;try{return e()}finally{this.state.inType=a}},n.tsInDisallowConditionalTypesContext=function(e){var a=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!0;try{return e()}finally{this.state.inDisallowConditionalTypesContext=a}},n.tsInAllowConditionalTypesContext=function(e){var a=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!1;try{return e()}finally{this.state.inDisallowConditionalTypesContext=a}},n.tsEatThenParseType=function(e){if(this.match(e))return this.tsNextThenParseType()},n.tsExpectThenParseType=function(e){var a=this;return this.tsInType(function(){return a.expect(e),a.tsParseType()})},n.tsNextThenParseType=function(){var e=this;return this.tsInType(function(){return e.next(),e.tsParseType()})},n.tsParseEnumMember=function(){var a=this.startNode();return a.id=this.match(130)?e.prototype.parseStringLiteral.call(this,this.state.value):this.parseIdentifier(!0),this.eat(25)&&(a.initializer=e.prototype.parseMaybeAssignAllowIn.call(this)),this.finishNode(a,"TSEnumMember")},n.tsParseEnumDeclaration=function(e,a){return void 0===a&&(a={}),a.const&&(e.const=!0),a.declare&&(e.declare=!0),this.expectContextual(122),e.id=this.parseIdentifier(),this.checkIdentifier(e.id,e.const?my:py),e.body=this.tsParseEnumBody(),this.finishNode(e,"TSEnumDeclaration")},n.tsParseEnumBody=function(){var e=this.startNode();return this.expect(2),e.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this)),this.expect(4),this.finishNode(e,"TSEnumBody")},n.tsParseModuleBlock=function(a){var n=this.startNode();return a||this.scope.enter(kR),this.expect(2),e.prototype.parseBlockOrModuleBlockBody.call(this,n.body=[],void 0,!0,4),a||this.scope.exit(),this.finishNode(n,"TSModuleBlock")},n.tsParseNamespaceDeclaration=function(e){return e.id=this.tsParseEntityName(sb),"Identifier"===e.id.type&&this.checkIdentifier(e.id,Ry),this.scope.enter(VR),this.prodParam.enter(yv),e.body=this.tsParseModuleBlock(!1),this.prodParam.exit(),this.scope.exit(),this.finishNode(e,"TSModuleDeclaration")},n.tsParseAmbientExternalModuleDeclaration=function(a){var n=this.isContextual(108);if(n)a.kind="global",a.id=this.parseIdentifier();else{a.kind="module";var t=this.state,r=t.type,i=t.value;130===r?a.id=e.prototype.parseStringLiteral.call(this,i):hR(r)?(this.raise(nb.InlineModuleDeclarationMustUseString,this.state.startLoc),a.id=this.tsParseEntityName(sb)):2===r?this.raise(nb.EmptyNamespaceName,this.state.startLoc):(this.raise(nb.InvalidNamespaceName,this.state.startLoc,i),a.id=e.prototype.parseExprAtom.call(this))}return this.match(2)?(n||this.scope.enter(WR),this.prodParam.enter(yv),a.body=this.tsParseModuleBlock(n),this.prodParam.exit(),n||this.scope.exit()):this.semicolon(),this.finishNode(a,"TSModuleDeclaration")},n.tsParseImportEqualsDeclaration=function(e,a){e.id=a||this.parseIdentifier(),this.checkIdentifier(e.id,vy),this.expect(25);var n=this.tsParseModuleReference();return"type"===e.importKind&&"TSExternalModuleReference"!==n.type&&this.raise(nb.ImportAliasHasImportType,n),e.moduleReference=n,this.semicolon(),this.finishNode(e,"TSImportEqualsDeclaration")},n.tsIsExternalModuleReference=function(){return this.isContextual(115)&&40===this.lookaheadCharCode()},n.tsParseModuleReference=function(){return this.tsIsExternalModuleReference()?this.tsParseExternalModuleReference():this.tsParseEntityName(sb)},n.tsParseExternalModuleReference=function(){var a=this.startNode();return this.expectContextual(115),this.expect(6),this.match(130)||this.unexpected(),a.expression=e.prototype.parseExprAtom.call(this),this.expect(7),this.sawUnambiguousESM=!0,this.finishNode(a,"TSExternalModuleReference")},n.tsLookAhead=function(e){var a=this.state.clone(),n=e();return this.state=a,n},n.tsTryParseAndCatch=function(e){var a=this.tryParse(function(a){return e()||a()});if(!a.aborted&&a.node)return a.error&&(this.state=a.failState),a.node},n.tsTryParse=function(e){var a=this.state.clone(),n=e();if(void 0!==n&&!1!==n)return n;this.state=a},n.tsTryParseDeclare=function(a){var n=this;if(!this.isLineTerminator()){var t=this.state.type;return this.tsInAmbientContext(function(){switch(t){case 64:return a.declare=!0,e.prototype.parseFunctionStatement.call(n,a,!1,!1);case 76:return a.declare=!0,n.parseClass(a,!0,!1);case 122:return n.tsParseEnumDeclaration(a,{declare:!0});case 108:return n.tsParseAmbientExternalModuleDeclaration(a);case 96:if(n.state.containsEsc)return;case 71:case 70:return n.match(71)&&n.isLookaheadContextual("enum")?(n.expect(71),n.tsParseEnumDeclaration(a,{const:!0,declare:!0})):(a.declare=!0,n.parseVarStatement(a,n.state.value,!0));case 103:if(n.isUsing())return n.raise(nb.InvalidModifierOnUsingDeclaration,n.state.startLoc,"declare"),a.declare=!0,n.parseVarStatement(a,"using",!0);break;case 92:if(n.isAwaitUsing())return n.raise(nb.InvalidModifierOnAwaitUsingDeclaration,n.state.startLoc,"declare"),a.declare=!0,n.next(),n.parseVarStatement(a,"await using",!0);break;case 125:var r=n.tsParseInterfaceDeclaration(a,{declare:!0});if(r)return r;default:if(hR(t))return n.tsParseDeclaration(a,n.state.type,!0,null)}})}},n.tsTryParseExportDeclaration=function(){return this.tsParseDeclaration(this.startNode(),this.state.type,!0,null)},n.tsParseDeclaration=function(e,a,n,t){switch(a){case 120:if(this.tsCheckLineTerminator(n)&&(this.match(76)||hR(this.state.type)))return this.tsParseAbstractDeclaration(e,t);break;case 123:if(this.tsCheckLineTerminator(n))return this.tsParseAmbientExternalModuleDeclaration(e);break;case 124:if(this.tsCheckLineTerminator(n)&&hR(this.state.type))return e.kind="namespace",this.tsParseNamespaceDeclaration(e);break;case 126:if(this.tsCheckLineTerminator(n)&&hR(this.state.type))return this.tsParseTypeAliasDeclaration(e)}},n.tsCheckLineTerminator=function(e){return e?!this.hasFollowingLineBreak()&&(this.next(),!0):!this.isLineTerminator()},n.tsTryParseGenericAsyncArrowFunction=function(a){var n=this;if(this.match(43)){var t=this.tsTryParseAndCatch(function(){var t=n.startNodeAt(a);return t.typeParameters=n.tsParseTypeParameters(n.tsParseConstModifier),e.prototype.parseFunctionParams.call(n,t),t.returnType=n.tsTryParseTypeOrTypePredicateAnnotation(),n.expect(15),t});if(t)return e.prototype.parseArrowExpression.call(this,t,null,!0)}},n.tsParseTypeArgumentsInExpression=function(){if(43===this.reScan_lt())return this.tsParseTypeArguments()},n.tsParseTypeArguments=function(){var e=this,a=this.startNode();return a.params=this.tsInType(function(){return e.tsInTopLevelContext(function(){return e.expect(43),e.tsParseDelimitedList("TypeParametersOrArguments",e.tsParseType.bind(e))})}),0===a.params.length?this.raise(nb.EmptyTypeArguments,a):this.state.inType||this.curContext()!==AR.brace||this.reScan_lt_gt(),this.expect(44),this.finishNode(a,"TSTypeParameterInstantiation")},n.tsIsDeclarationStart=function(){return(e=this.state.type)>=120&&e<=126;var e},n.isExportDefaultSpecifier=function(){return!this.tsIsDeclarationStart()&&e.prototype.isExportDefaultSpecifier.call(this)},n.parseBindingElement=function(e,a){var n=a.length?null:this.state.startLoc,t={};this.tsParseModifiers(pb,void 0,t);var r=t.accessibility,i=t.override,o=t.readonly;e&Nv||!(r||o||i)||this.raise(nb.UnexpectedParameterModifier,n||a[0]);var s=this.state.startLoc,d=this.parseMaybeDefault(s);e&Bv&&this.parseFunctionParamType(d);var u=this.parseMaybeDefault(s,d);if(r||o||i){var c=n?this.startNodeAt(n):this.startNodeAtNode(a[0]);return a.length?c.decorators=a:this.setLoc(n),r&&(c.accessibility=r),o&&(c.readonly=o),i&&(c.override=i),"Identifier"!==u.type&&"AssignmentPattern"!==u.type&&this.raise(nb.UnsupportedParameterPropertyKind,n||a[0]),c.parameter=u,this.finishNode(c,"TSParameterProperty")}return a.length&&(d.decorators=a),u},n.isSimpleParameter=function(a){return"TSParameterProperty"===a.type&&e.prototype.isSimpleParameter.call(this,a.parameter)||e.prototype.isSimpleParameter.call(this,a)},n.tsDisallowOptionalPattern=function(e){for(var a=0,n=e.params;at&&!this.hasPrecedingLineBreak()&&(this.isContextual(89)||(r=this.isContextual(116)))){var o=this.startNodeAt(n);o.expression=a,o.typeAnnotation=this.tsInType(function(){return i.next(),i.match(71)?(r&&i.raise(Bm.UnexpectedKeyword,i.state.startLoc,{keyword:"const"}),i.tsParseTypeReference()):i.tsParseType()});var s=this.finishNode(o,r?"TSSatisfiesExpression":"TSAsExpression");return this.reScan_lt_gt(),this.parseExprOp(s,n,t)}return e.prototype.parseExprOp.call(this,a,n,t)},n.checkReservedWord=function(a,n,t,r){this.state.isAmbientContext||e.prototype.checkReservedWord.call(this,a,n,t,r)},n.checkDuplicateExports=function(){},n.isPotentialImportPhase=function(a){if(e.prototype.isPotentialImportPhase.call(this,a))return!0;if(this.isContextual(126)){var n=this.lookaheadCharCode();return a?123===n||42===n:61!==n}return!a&&this.isContextual(83)},n.applyImportPhase=function(a,n,t,r){e.prototype.applyImportPhase.call(this,a,n,t,r),n?a.exportKind="type"===t?"type":"value":a.importKind="type"===t||"typeof"===t?t:"value"},n.parseImport=function(a){if(this.match(130))return a.importKind="value",this.scope.inTSNamespace&&this.raise(nb.ImportInTSNamespace,a),e.prototype.parseImport.call(this,a);var n;if(hR(this.state.type)&&61===this.lookaheadCharCode()){a.importKind="value";var t=this.tsParseImportEqualsDeclaration(a);return this.scope.inTSNamespace&&"TSExternalModuleReference"===t.moduleReference.type&&this.raise(nb.ImportInTSNamespace,a),t}if(this.isContextual(126)){var r=this.parseMaybeImportPhase(a,!1);if(61===this.lookaheadCharCode())return this.scope.inTSNamespace&&this.raise(nb.ImportInTSNamespace,a),this.tsParseImportEqualsDeclaration(a,r);n=e.prototype.parseImportSpecifiersAndAfter.call(this,a,r)}else n=e.prototype.parseImport.call(this,a);return"type"===n.importKind&&n.specifiers.length>1&&"ImportDefaultSpecifier"===n.specifiers[0].type?this.raise(nb.TypeImportCannotSpecifyDefaultAndNamed,n):this.scope.inTSNamespace&&this.raise(nb.ImportInTSNamespace,n),n},n.parseExport=function(a,n){if(this.match(79)){var t=this.startNode();this.next();var r=null;this.isContextual(126)&&this.isPotentialImportPhase(!1)?r=this.parseMaybeImportPhase(t,!1):t.importKind="value";var i=this.tsParseImportEqualsDeclaration(t,r);return a.attributes=[],a.declaration=i,a.exportKind="value",a.source=null,a.specifiers=[],this.finishNode(a,"ExportNamedDeclaration")}if(this.eat(25)){var o=a;return o.expression=e.prototype.parseExpression.call(this),this.semicolon(),this.sawUnambiguousESM=!0,this.scope.inTSNamespace&&this.raise(nb.ExportAssignmentInTSNamespace,o),this.finishNode(o,"TSExportAssignment")}if(this.eatContextual(89)){var s=a;return this.expectContextual(124),s.id=this.parseIdentifier(),this.checkIdentifier(s.id,oy),this.semicolon(),this.scope.inTSNamespace&&this.raise(nb.NamespaceExportInTSNamespace,s),this.finishNode(s,"TSNamespaceExportDeclaration")}var d=e.prototype.parseExport.call(this,a,n);return this.scope.inTSNamespace&&("ExportNamedDeclaration"!==d.type||d.source||!d.declaration&&!this.state.isAmbientContext)&&this.raise(nb.ExportInTSNamespace,d),d},n.isAbstractClass=function(){return this.isContextual(120)&&this.isLookaheadContextual("class")},n.parseExportDefaultExpression=function(){if(this.isAbstractClass()){var a=this.startNode();return this.next(),a.abstract=!0,this.parseClass(a,!0,!0)}if(this.match(125)){var n=this.tsParseInterfaceDeclaration(this.startNode());if(n)return n}return e.prototype.parseExportDefaultExpression.call(this)},n.parseVarStatement=function(a,n,t){void 0===t&&(t=!1);var r=this.state.isAmbientContext,i=e.prototype.parseVarStatement.call(this,a,n,t||r);if(r&&!a.declare&&("using"===n||"await using"===n))return this.raiseOverwrite(nb.UsingDeclarationInAmbientContext,a,n),i;for(var o=0,s=i.declarations;o0&&!this.hasPlugin("decorators-legacy")&&("TSAbstractMethodDefinition"===n.type||"TSDeclareMethod"===n.type?this.raise(nb.DecoratorAbstractMethod,n,{kind:"abstract method"}):("ClassProperty"===n.type&&n.abstract||"ClassProperty"===n.type&&n.declare||"TSAbstractPropertyDefinition"===n.type||"PropertyDefinition"===n.type&&n.declare)&&this.raise(nb.DecoratorAbstractMethod,n,{kind:n.declare?"declare field":"abstract field"}))},n.parseClassMemberWithIsStatic=function(a,n,t,r){var i=this.tsTryParseIndexSignature(n);if(i)return a.body.push(i),n.abstract&&this.raise(nb.IndexSignatureHasAbstract,n),n.accessibility&&this.raise(nb.IndexSignatureHasAccessibility,n,{modifier:n.accessibility}),n.declare&&this.raise(nb.IndexSignatureHasDeclare,n),void(n.override&&this.raise(nb.IndexSignatureHasOverride,n));!this.state.inAbstractClass&&n.abstract&&this.raise(nb.NonAbstractClassHasAbstractMethod,n),n.override&&(t.hadSuperClass||this.raise(nb.OverrideNotInSubClass,n)),e.prototype.parseClassMemberWithIsStatic.call(this,a,n,t,r)},n.parsePostMemberNameModifiers=function(e){this.eat(13)&&(e.optional=!0),e.readonly&&this.match(6)&&this.raise(nb.ClassMethodHasReadonly,e),e.declare&&this.match(6)&&this.raise(nb.ClassMethodHasDeclare,e)},n.shouldParseExportDeclaration=function(){return!!this.tsIsDeclarationStart()||e.prototype.shouldParseExportDeclaration.call(this)},n.parseConditional=function(e,a,n){if(!this.match(13))return e;if(null!=n){var t=this.lookaheadCharCode();if(44===t||61===t||58===t||41===t)return this.setOptionalParametersError(n),e}this.next();var r=this.startNodeAt(a);r.test=e;var i=this.state.inConditionalConsequent;return this.state.inConditionalConsequent=!0,r.consequent=this.parseMaybeAssignAllowIn(),this.state.inConditionalConsequent=i,this.expect(10),r.alternate=this.parseMaybeAssign(),this.finishNode(r,"ConditionalExpression")},n.parseParenItem=function(a,n){var t=e.prototype.parseParenItem.call(this,a,n);if(this.eat(13)&&(t.optional=!0,this.resetEndLocation(a)),this.match(10)){var r=this.startNodeAt(n);return r.expression=a,r.typeAnnotation=this.tsParseTypeAnnotation(),this.finishNode(r,"TSTypeCastExpression")}return a},n.parseExportDeclaration=function(a){var n=this;if(!this.state.isAmbientContext&&this.isContextual(121))return this.tsInAmbientContext(function(){return n.parseExportDeclaration(a)});var t=this.state.startLoc,r=this.eatContextual(121);if(r&&(this.isContextual(121)||!this.shouldParseExportDeclaration()))throw this.raise(nb.ExpectedAmbientAfterExportDeclare,this.state.startLoc);var i=hR(this.state.type)&&this.tsTryParseExportDeclaration()||e.prototype.parseExportDeclaration.call(this,a);return i?(("TSInterfaceDeclaration"===i.type||"TSTypeAliasDeclaration"===i.type||r)&&(a.exportKind="type"),r&&"TSImportEqualsDeclaration"!==i.type&&(this.resetStartLocation(i,t),i.declare=!0),i):null},n.parseClassId=function(a,n,t,r){if(n&&!t||!this.isContextual(109)){e.prototype.parseClassId.call(this,a,n,t,a.declare?gy:iy);var i=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);i&&(a.typeParameters=i)}else a.id=null},n.parseClassPropertyAnnotation=function(e){e.optional||(this.eat(31)?e.definite=!0:this.eat(13)&&(e.optional=!0));var a=this.tsTryParseTypeAnnotation();a&&(e.typeAnnotation=a),e.definite&&(this.match(25)?this.raise(nb.DeclaratorDefiniteAssertionWithInitializer,e):a||this.raise(nb.DeclaratorDefiniteAssertionRequiresTypeAnnotation,e))},n.parseClassProperty=function(a){if(this.parseClassPropertyAnnotation(a),this.state.isAmbientContext&&(!a.readonly||a.typeAnnotation)&&this.match(25)&&this.raise(nb.DeclareClassFieldHasInitializer,this.state.startLoc),a.abstract&&this.match(25)){var n=a.key;this.raise(nb.AbstractPropertyHasInitializer,this.state.startLoc,{propertyName:"Identifier"!==n.type||a.computed?"["+this.input.slice(this.offsetToSourcePos(n.start),this.offsetToSourcePos(n.end))+"]":n.name})}return e.prototype.parseClassProperty.call(this,a)},n.parseClassPrivateProperty=function(a){return a.abstract&&this.raise(nb.PrivateElementHasAbstract,a),a.accessibility&&this.raise(nb.PrivateElementHasAccessibility,a,{modifier:a.accessibility}),this.parseClassPropertyAnnotation(a),e.prototype.parseClassPrivateProperty.call(this,a)},n.parseClassAccessorProperty=function(a){return this.parseClassPropertyAnnotation(a),a.optional&&this.raise(nb.AccessorCannotBeOptional,a),e.prototype.parseClassAccessorProperty.call(this,a)},n.pushClassMethod=function(a,n,t,r,i,o){var s=this.tsTryParseTypeParameters(this.tsParseConstModifier);s&&i&&this.raise(nb.ConstructorHasTypeParameters,s);var d=n.declare,u=void 0!==d&&d,c=n.kind;!u||"get"!==c&&"set"!==c||this.raise(nb.DeclareAccessor,n,{kind:c}),s&&(n.typeParameters=s),e.prototype.pushClassMethod.call(this,a,n,t,r,i,o)},n.pushClassPrivateMethod=function(a,n,t,r){var i=this.tsTryParseTypeParameters(this.tsParseConstModifier);i&&(n.typeParameters=i),e.prototype.pushClassPrivateMethod.call(this,a,n,t,r)},n.declareClassPrivateMethodInScope=function(a,n){"TSDeclareMethod"!==a.type&&("MethodDefinition"===a.type&&null==a.value.body||e.prototype.declareClassPrivateMethodInScope.call(this,a,n))},n.parseClassSuper=function(a){if(e.prototype.parseClassSuper.call(this,a),a.superClass)if("TSInstantiationExpression"===a.superClass.type){var n=a.superClass,t=n.expression;this.takeSurroundingComments(t,t.start,t.end);var r=n.typeArguments;this.takeSurroundingComments(r,r.start,r.end),a.superClass=t,a.superTypeArguments=r}else(this.match(43)||this.match(47))&&(a.superTypeArguments=this.tsParseTypeArgumentsInExpression());this.eatContextual(109)&&(a.implements=this.tsParseHeritageClause("implements"))},n.parseObjPropValue=function(a,n,t,r,i,o,s){var d=this.tsTryParseTypeParameters(this.tsParseConstModifier);return d&&(a.typeParameters=d),e.prototype.parseObjPropValue.call(this,a,n,t,r,i,o,s)},n.parseFunctionParams=function(a,n){var t=this.tsTryParseTypeParameters(this.tsParseConstModifier);t&&(a.typeParameters=t),e.prototype.parseFunctionParams.call(this,a,n)},n.parseVarId=function(a,n){e.prototype.parseVarId.call(this,a,n),"Identifier"===a.id.type&&!this.hasPrecedingLineBreak()&&this.eat(31)&&(a.definite=!0);var t=this.tsTryParseTypeAnnotation();t&&(a.id.typeAnnotation=t,this.resetEndLocation(a.id))},n.parseAsyncArrowFromCallExpression=function(a,n){return this.match(10)&&(a.returnType=this.tsParseTypeAnnotation()),e.prototype.parseAsyncArrowFromCallExpression.call(this,a,n)},n.parseMaybeAssign=function(a,n){var t,r,i,o,s,d,u,c,l,p=this;if(this.hasPlugin("jsx")&&(this.match(138)||this.match(43))){if(d=this.state.clone(),!(u=this.tryParse(function(){return e.prototype.parseMaybeAssign.call(p,a,n)},d)).error)return u.node;var g=this.state.context,f=g[g.length-1];f!==AR.j_oTag&&f!==AR.j_expr||g.pop()}if(!(null!=(t=u)&&t.error||this.match(43)))return e.prototype.parseMaybeAssign.call(this,a,n);d&&d!==this.state||(d=this.state.clone());var h=this.tryParse(function(t){var r,i,o;l=p.tsParseTypeParameters(p.tsParseConstModifier);var s=e.prototype.parseMaybeAssign.call(p,a,n);if(("ArrowFunctionExpression"!==s.type||null!=(r=s.extra)&&r.parenthesized)&&t(),0!==(null==(i=l)?void 0:i.params.length)&&p.resetStartLocationFromNode(s,l),s.typeParameters=l,p.hasPlugin("jsx")&&1===s.typeParameters.params.length&&(null==(o=s.typeParameters.extra)||!o.trailingComma)){var d=s.typeParameters.params[0];d.constraint||p.raise(nb.SingleTypeParameterWithoutTrailingComma,p.optionFlags&Wm?vm(d.loc.end,1):d,{typeParameterName:d.name.name})}return s},d);if(!h.error&&!h.aborted)return l&&this.reportReservedArrowTypeParam(l),h.node;if(!u&&(ab(!this.hasPlugin("jsx")),!(c=this.tryParse(function(){return e.prototype.parseMaybeAssign.call(p,a,n)},d)).error))return c.node;if(null!=(r=u)&&r.node)return this.state=u.failState,u.node;if(h.node)return this.state=h.failState,l&&this.reportReservedArrowTypeParam(l),h.node;if(null!=(i=c)&&i.node)return this.state=c.failState,c.node;throw(null==(o=u)?void 0:o.error)||h.error||(null==(s=c)?void 0:s.error)},n.reportReservedArrowTypeParam=function(e){var a;1!==e.params.length||e.params[0].constraint||null!=(a=e.extra)&&a.trailingComma||!this.getPluginOption("typescript","disallowAmbiguousJSXLike")||this.raise(nb.ReservedArrowTypeParam,e)},n.parseMaybeUnary=function(a,n){return!this.hasPlugin("jsx")&&this.match(43)?this.tsParseTypeAssertion():e.prototype.parseMaybeUnary.call(this,a,n)},n.parseArrow=function(a){var n=this;if(this.match(10)){var t=this.tryParse(function(e){var a=n.tsParseTypeOrTypePredicateAnnotation(10);return!n.canInsertSemicolon()&&n.match(15)||e(),a});if(t.aborted)return;t.thrown||(t.error&&(this.state=t.failState),a.returnType=t.node)}return e.prototype.parseArrow.call(this,a)},n.parseFunctionParamType=function(e){this.eat(13)&&(e.optional=!0);var a=this.tsTryParseTypeAnnotation();return a&&(e.typeAnnotation=a),this.resetEndLocation(e),e},n.isAssignable=function(a,n){switch(a.type){case"TSTypeCastExpression":return this.isAssignable(a.expression,n);case"TSParameterProperty":return!0;default:return e.prototype.isAssignable.call(this,a,n)}},n.toAssignable=function(a,n){switch(void 0===n&&(n=!1),a.type){case"ParenthesizedExpression":this.toAssignableParenthesizedExpression(a,n);break;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":n?this.expressionScope.recordArrowParameterBindingError(nb.UnexpectedTypeCastInParameter,a):this.raise(nb.UnexpectedTypeCastInParameter,a),this.toAssignable(a.expression,n);break;case"AssignmentExpression":n||"TSTypeCastExpression"!==a.left.type||(a.left=this.typeCastToParameter(a.left));default:e.prototype.toAssignable.call(this,a,n)}},n.toAssignableParenthesizedExpression=function(a,n){switch(a.expression.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":case"ParenthesizedExpression":this.toAssignable(a.expression,n);break;default:e.prototype.toAssignable.call(this,a,n)}},n.checkToRestConversion=function(a,n){switch(a.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":case"TSNonNullExpression":this.checkToRestConversion(a.expression,!1);break;default:e.prototype.checkToRestConversion.call(this,a,n)}},n.isValidLVal=function(a,n,t,r){switch(a){case"TSTypeCastExpression":return!0;case"TSParameterProperty":return"parameter";case"TSNonNullExpression":return"expression";case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":return(r!==fy||!t)&&["expression",!0];default:return e.prototype.isValidLVal.call(this,a,n,t,r)}},n.parseBindingAtom=function(){return 74===this.state.type?this.parseIdentifier(!0):e.prototype.parseBindingAtom.call(this)},n.parseMaybeDecoratorArguments=function(a,n){if(this.match(43)||this.match(47)){var t=this.tsParseTypeArgumentsInExpression();if(this.match(6)){var r=e.prototype.parseMaybeDecoratorArguments.call(this,a,n);return r.typeArguments=t,r}this.unexpected(null,6)}return e.prototype.parseMaybeDecoratorArguments.call(this,a,n)},n.checkCommaAfterRest=function(a){return this.state.isAmbientContext&&this.match(8)&&this.lookaheadCharCode()===a?(this.next(),!1):e.prototype.checkCommaAfterRest.call(this,a)},n.isClassMethod=function(){return this.match(43)||e.prototype.isClassMethod.call(this)},n.isClassProperty=function(){return this.match(31)||this.match(10)||e.prototype.isClassProperty.call(this)},n.parseMaybeDefault=function(a,n){var t=e.prototype.parseMaybeDefault.call(this,a,n);return"AssignmentPattern"===t.type&&t.typeAnnotation&&t.right.startthis.offsetToSourcePos(this.state.lastTokEndLoc.index)&&this.raise(vb.UnexpectedSpace,this.state.lastTokEndLoc)},i(a)}(e)}},Eb=Object.keys(Sb),Tb=function(e){function a(a,n,t){var r,i=function(e){var a={sourceType:"script",sourceFilename:void 0,startIndex:0,startColumn:0,startLine:1,allowAwaitOutsideFunction:!1,allowReturnOutsideFunction:!1,allowNewTargetOutsideFunction:!1,allowImportExportEverywhere:!1,allowSuperOutsideMethod:!1,allowUndeclaredExports:!1,allowYieldOutsideFunction:!1,plugins:[],strictMode:void 0,ranges:!1,locations:!0,tokens:!1,createImportExpressions:!0,createParenthesizedExpressions:!1,errorRecovery:!1,attachComment:!0,annexB:!0};if(null==e)return a;if(null!=e.annexB&&!1!==e.annexB)throw new Error("The `annexB` option can only be set to `false`.");for(var n=0,t=Object.keys(a);n0?a.startIndex=a.startColumn:null==e.startColumn&&a.startIndex>0&&(a.startColumn=a.startIndex);else if(null==e.startColumn||null==e.startIndex)throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`.");if("commonjs"===a.sourceType){if(null!=e.allowAwaitOutsideFunction)throw new Error("The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`.");if(null!=e.allowReturnOutsideFunction)throw new Error("`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`.");if(null!=e.allowNewTargetOutsideFunction)throw new Error("`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`.")}return a}(a);(r=e.call(this,i,n)||this).options=i,r.initializeScopes(),r.plugins=t,r.filename=i.sourceFilename,r.startIndex=i.startIndex;var o=0;return i.allowAwaitOutsideFunction&&(o|=Nm),i.allowReturnOutsideFunction&&(o|=jm),i.allowImportExportEverywhere&&(o|=Fm),i.allowSuperOutsideMethod&&(o|=Mm),i.allowUndeclaredExports&&(o|=Um),i.allowNewTargetOutsideFunction&&(o|=Om),i.allowYieldOutsideFunction&&(o|=Lm),i.ranges&&(o|=qm),!0===i.locations&&(o|=Wm),i.tokens&&(o|=Vm),i.createImportExpressions&&(o|=Hm),i.createParenthesizedExpressions&&(o|=Gm),i.errorRecovery&&(o|=Km),i.attachComment&&(o|=Jm),i.annexB&&(o|=zm),r.optionFlags=o,r}u(a,e);var n=a.prototype;return n.getScopeHandler=function(){return Iy},n.parse=function(){this.enterInitialScopes();var e=this.startNode(),a=this.startNode();this.nextToken(),e.errors=[];var n=this.parseTopLevel(e,a);return n.errors=this.state.errors,n.comments.length=this.state.commentsLen,n},i(a)}(Zv);function wb(e,a){var n;if("unambiguous"!==(null==(n=a)?void 0:n.sourceType))return Pb(a,e).parse();a=Object.assign({},a);try{a.sourceType="module";var t=Pb(a,e),r=t.parse();if(t.sawUnambiguousESM)return r;if(t.ambiguousScriptDifferentAst)try{return a.sourceType="script",Pb(a,e).parse()}catch(e){}else r.program.sourceType="script";return r}catch(n){try{return a.sourceType="script",Pb(a,e).parse()}catch(e){}throw n}}var Cb=function(e){for(var a={},n=0,t=Object.keys(e);n=e.length)throw new Error("Position "+a+" is out of bounds for location data.");return e[2*a+1]},getLine:function(e,a){if(a<0||2*a>=e.length)throw new Error("Position "+a+" is out of bounds for location data.");return e[2*a]},parse:wb,parseExpression:function(e,a){var n=Pb(a,e);return n.options.strictMode&&(n.state.strict=!0),n.getExpression()},tokTypes:Cb}),Db=/\r\n|[\n\r\u2028\u2029]/;function kb(e,a,n,t){void 0===n&&(n={});var r={defs:{gutter:String,marker:String,message:String,reset:String},highlight:String},i=r.defs,o=r.highlight,s=(n.startLine||1)-1,d=function(e,a,n,t){var r=Object.assign({column:null,line:-1},e.start),i=Object.assign({},r,e.end),o=n||{},s=o.linesAbove,d=void 0===s?2:s,u=o.linesBelow,c=void 0===u?3:u,l=r.line-t,p=r.column,g=i.line-t,f=i.column,h=Math.max(l-(d+1),0),m=Math.min(a.length,g+c);-1===l&&(h=0),-1===g&&(m=a.length);var R=g-l,y={};if(R)for(var v=0;v<=R;v++){var b=v+l;if(null==p)y[b]=!0;else if(0===v){var x=a[b-1].length;y[b]=[p,x-p]}else if(v===R)y[b]=[0,f];else{var S=a[b-1].length;y[b]=[0,S]}}else if(p===f)y[l]=null==p||[p,0];else{var E=null!=p?p:0,T=null!=f?f:E;y[l]=[E,T-E]}return{start:h,end:m,markerLines:y}}(a,e.split(Db),n,s),u=d.start,c=d.end,l=d.markerLines,p=a.start&&"number"==typeof a.start.column,g=String(c+s).length,f=o(e).split(Db,c).slice(u,c).map(function(e,a){var t=u+1+a,r=" "+(" "+(t+s)).slice(-g)+" |",o=l[t],d=!l[t+1];if(o){var c="";if(Array.isArray(o)){var p=e.slice(0,o[0]).replace(/[^\t]/g," "),f=o[1]||1;c=["\n ",i.gutter(r.replace(/\d/g," "))," ",p,i.marker("^").repeat(f)].join(""),d&&n.message&&(c+=" "+i.message(n.message))}return[i.marker(">"),i.gutter(r),e.length>0?" "+e:"",c].join("")}return" "+i.gutter(r)+(e.length>0?" "+e:"")}).join("\n");return n.message&&!p&&(f=""+" ".repeat(g+1)+n.message+"\n"+f),i.reset(f)}function Ib(e,a,n){return void 0===n&&(n={}),kb(e,a,n)}var Bb=_,Nb=I,jb=Na,Ob=F,Fb=ta,Mb=K,Lb=ua,Ub=Da,qb=U,Wb=Mh,Vb=Xh,Hb=/^[_$A-Z0-9]+$/;function Gb(e,a,n){var t=n.placeholderAllowlist,r=n.placeholderPattern,i=n.preserveComments,o=void 0!==i&&i,s=n.syntacticPlaceholders,d=function(e,a,n){var t=(a.plugins||[]).slice();!1!==n&&t.push("placeholders");a=Object.assign({allowAwaitOutsideFunction:!0,allowReturnOutsideFunction:!0,allowNewTargetOutsideFunction:!0,allowSuperOutsideMethod:!0,allowYieldOutsideFunction:!0,sourceType:"module"},a,{plugins:t});try{return wb(e,a)}catch(a){var r=a.loc;throw r&&(a.message+="\n"+Ib(e,{start:r}),a.code="BABEL_TEMPLATE_PARSE_ERROR"),a}}(a,n.parser,s);Wb(d,{preserveComments:o}),e.validate(d);var u={syntactic:{placeholders:[],placeholderNames:new Set},legacy:{placeholders:[],placeholderNames:new Set},placeholderAllowlist:t,placeholderPattern:r,syntacticPlaceholders:s};return Vb(d,Kb,u),Object.assign({ast:d},u.syntactic.placeholders.length?u.syntactic:u.legacy)}function Kb(e,a,n){var t,r,i=n.syntactic.placeholders.length>0;if(Lb(e)){if(!1===n.syntacticPlaceholders)throw new Error("%%foo%%-style placeholders can't be used when '.syntacticPlaceholders' is false.");r=e.name.name,i=!0}else{if(i||n.syntacticPlaceholders)return;if(Ob(e)||Fb(e))r=e.name;else{if(!qb(e))return;r=e.value}}if(i&&(null!=n.placeholderPattern||null!=n.placeholderAllowlist))throw new Error("'.placeholderAllowlist' and '.placeholderPattern' aren't compatible with '.syntacticPlaceholders: true'");if(i||!1!==n.placeholderPattern&&(n.placeholderPattern||Hb).test(r)||null!=(t=n.placeholderAllowlist)&&t.has(r)){var o,s=(a=a.slice())[a.length-1],d=s.node,u=s.key;qb(e)||Lb(e,{expectedNode:"StringLiteral"})?o="string":Mb(d)&&"arguments"===u||Bb(d)&&"arguments"===u||jb(d)&&"params"===u?o="param":Nb(d)&&!Lb(e)?(o="statement",a=a.slice(0,-1)):o=Ub(e)&&Lb(e)?"statement":"other";var c=i?n.syntactic:n.legacy,l=c.placeholders,p=c.placeholderNames;l.push({name:r,type:o,resolve:function(e){return function(e,a){for(var n=e,t=0;t1?t-1:0),o=1;o1)throw new Error("Unexpected extra params.");return sx(tx(e,a,fm(r,hm(i[0]))))}if(Array.isArray(a)){var s=n.get(a);return s||(s=rx(e,a,r),n.set(a,s)),sx(s(i))}if("object"==typeof a&&a){if(i.length>0)throw new Error("Unexpected extra params.");return ox(e,fm(r,hm(a)))}throw new Error("Unexpected template param "+typeof a)},{ast:function(a){for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;o1)throw new Error("Unexpected extra params.");return tx(e,a,fm(fm(r,hm(i[0])),ix))()}if(Array.isArray(a)){var s=t.get(a);return s||(s=rx(e,a,fm(r,ix)),t.set(a,s)),s(i)()}throw new Error("Unexpected template param "+typeof a)}})}function sx(e){var a=new Error;return function(n){try{return e(n)}catch(e){throw e.stack+="\n =============\n"+a.stack.split("\n").slice(3).join("\n"),e}}}var dx=ox(um),ux=ox(lm),cx=ox(cm),lx=ox(pm),px=ox({code:function(e){return e},validate:function(){},unwrap:function(e){return e.program}}),gx=Object.assign(dx.bind(void 0),{smart:dx,statement:ux,statements:cx,expression:lx,program:px,ast:dx.ast}),fx=Object.freeze({__proto__:null,default:gx,expression:lx,program:px,smart:dx,statement:ux,statements:cx});function hx(e,a,n){return Object.freeze({minVersion:e,ast:function(){return gx.program.ast(a,{preserveComments:!0})},metadata:n})}var mx={__proto__:null,OverloadYield:hx("7.18.14","function _OverloadYield(e,d){this.v=e,this.k=d}",{globals:[],locals:{_OverloadYield:["body.0.id"]},exportBindingAssignments:[],exportName:"_OverloadYield",dependencies:{},internal:!1}),applyDecoratedDescriptor:hx("7.0.0-beta.0",'function _applyDecoratedDescriptor(i,e,r,n,l){var a={};return Object.keys(n).forEach(function(i){a[i]=n[i]}),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=r.slice().reverse().reduce(function(r,n){return n(i,e,r)||r},a),l&&void 0!==a.initializer&&(a.value=a.initializer?a.initializer.call(l):void 0,a.initializer=void 0),void 0===a.initializer?(Object.defineProperty(i,e,a),null):a}',{globals:["Object"],locals:{_applyDecoratedDescriptor:["body.0.id"]},exportBindingAssignments:[],exportName:"_applyDecoratedDescriptor",dependencies:{},internal:!1}),applyDecs2311:hx("7.24.0",'function applyDecs2311(e,t,n,r,o,i){var a,c,u,s,f,l,p,d=Symbol.metadata||Symbol.for("Symbol.metadata"),m=Object.defineProperty,h=Object.create,y=[h(null),h(null)],v=t.length;function g(t,n,r){return function(o,i){n&&(i=o,o=e);for(var a=0;a=0;O-=n?2:1){var T=b(h[O],"A decorator","be",!0),z=n?h[O-1]:void 0,A={},H={kind:["field","accessor","method","getter","setter","class"][o],name:r,metadata:a,addInitializer:function(e,t){if(e.v)throw new TypeError("attempted to call addInitializer after decoration was finished");b(t,"An initializer","be",!0),i.push(t)}.bind(null,A)};if(w)c=T.call(z,N,H),A.v=1,b(c,"class decorators","return")&&(N=c);else if(H.static=s,H.private=f,c=H.access={has:f?p.bind():function(e){return r in e}},j||(c.get=f?E?function(e){return d(e),P.value}:I("get",0,d):function(e){return e[r]}),E||S||(c.set=f?I("set",0,d):function(e,t){e[r]=t}),N=T.call(z,D?{get:P.get,set:P.set}:P[F],H),A.v=1,D){if("object"==typeof N&&N)(c=b(N.get,"accessor.get"))&&(P.get=c),(c=b(N.set,"accessor.set"))&&(P.set=c),(c=b(N.init,"accessor.init"))&&k.unshift(c);else if(void 0!==N)throw new TypeError("accessor decorators must return an object with get, set, or init properties or undefined")}else b(N,(l?"field":"method")+" decorators","return")&&(l?k.unshift(N):P[F]=N)}return o<2&&u.push(g(k,s,1),g(i,s,0)),l||w||(f?D?u.splice(-1,0,I("get",s),I("set",s)):u.push(E?P[F]:b.call.bind(P[F])):m(e,r,P)),N}function w(e){return m(e,d,{configurable:!0,enumerable:!0,value:a})}return void 0!==i&&(a=i[d]),a=h(null==a?null:a),f=[],l=function(e){e&&f.push(g(e))},p=function(t,r){for(var i=0;ir.length)&&(a=r.length);for(var e=0,n=Array(a);e=r.length?{done:!0}:{done:!1,value:r[n++]}},e:function(r){throw r},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a,u=!0;return{s:function(){t=t.call(r)},n:function(){u=!0;var r=t.next();return r.done?{done:!0}:{value:r.value,done:u=!1}},e:function(r){o=!0,a=r},f:function(){try{u||null==t.return||t.return()}finally{if(o)throw a}}}}',{globals:["Symbol","Array","TypeError"],locals:{_createForOfIteratorHelper:["body.0.id"]},exportBindingAssignments:[],exportName:"_createForOfIteratorHelper",dependencies:{unsupportedIterableToArray:["body.0.body.body.1.consequent.body.0.test.left.right.right.callee"]},internal:!1}),createForOfIteratorHelperLoose:hx("7.9.0",'function _createForOfIteratorHelperLoose(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(t)return(t=t.call(r)).next.bind(t);if(Array.isArray(r)||(t=unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var o=0;return function(){return o>=r.length?{done:!0}:{done:!1,value:r[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}',{globals:["Symbol","Array","TypeError"],locals:{_createForOfIteratorHelperLoose:["body.0.id"]},exportBindingAssignments:[],exportName:"_createForOfIteratorHelperLoose",dependencies:{unsupportedIterableToArray:["body.0.body.body.2.test.left.right.right.callee"]},internal:!1}),createSuper:hx("7.9.0","function _createSuper(t){var r=isNativeReflectConstruct();return function(){var e,o=getPrototypeOf(t);if(r){var s=getPrototypeOf(this).constructor;e=Reflect.construct(o,arguments,s)}else e=o.apply(this,arguments);return possibleConstructorReturn(this,e)}}",{globals:["Reflect"],locals:{_createSuper:["body.0.id"]},exportBindingAssignments:[],exportName:"_createSuper",dependencies:{getPrototypeOf:["body.0.body.body.1.argument.body.body.0.declarations.1.init.callee","body.0.body.body.1.argument.body.body.1.consequent.body.0.declarations.0.init.object.callee"],isNativeReflectConstruct:["body.0.body.body.0.declarations.0.init.callee"],possibleConstructorReturn:["body.0.body.body.1.argument.body.body.2.argument.callee"]},internal:!1}),defaults:hx("7.0.0-beta.0","function _defaults(e,r){for(var t=Object.getOwnPropertyNames(r),o=0;o1){for(var t=Array(n),f=0;f3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&dn||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a \'"+o+"\' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(define(t={},n,function(){return this}),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,define(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,define(u,"constructor",GeneratorFunctionPrototype),define(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",define(GeneratorFunctionPrototype,o,"GeneratorFunction"),define(u),define(u,o,"Generator"),define(u,n,function(){return this}),define(u,"toString",function(){return"[object Generator]"}),(_regenerator=function(){return{w:i,m:f}})()}',{globals:["Symbol","Object","TypeError"],locals:{_regenerator:["body.0.id","body.0.body.body.9.argument.expressions.9.callee.left"]},exportBindingAssignments:["body.0.body.body.9.argument.expressions.9.callee"],exportName:"_regenerator",dependencies:{regeneratorDefine:["body.0.body.body.1.body.body.1.argument.expressions.0.callee","body.0.body.body.7.declarations.0.init.alternate.expressions.0.callee","body.0.body.body.8.body.body.0.argument.expressions.0.alternate.expressions.1.callee","body.0.body.body.9.argument.expressions.1.callee","body.0.body.body.9.argument.expressions.2.callee","body.0.body.body.9.argument.expressions.4.callee","body.0.body.body.9.argument.expressions.5.callee","body.0.body.body.9.argument.expressions.6.callee","body.0.body.body.9.argument.expressions.7.callee","body.0.body.body.9.argument.expressions.8.callee"]},internal:!1}),regeneratorAsync:hx("7.27.0","function _regeneratorAsync(n,e,r,t,o){var a=asyncGen(n,e,r,t,o);return a.next().then(function(n){return n.done?n.value:a.next()})}",{globals:[],locals:{_regeneratorAsync:["body.0.id"]},exportBindingAssignments:[],exportName:"_regeneratorAsync",dependencies:{regeneratorAsyncGen:["body.0.body.body.0.declarations.0.init.callee"]},internal:!1}),regeneratorAsyncGen:hx("7.27.0","function _regeneratorAsyncGen(r,e,t,o,n){return new regeneratorAsyncIterator(regenerator().w(r,e,t,o),n||Promise)}",{globals:["Promise"],locals:{_regeneratorAsyncGen:["body.0.id"]},exportBindingAssignments:[],exportName:"_regeneratorAsyncGen",dependencies:{regenerator:["body.0.body.body.0.argument.arguments.0.callee.object.callee"],regeneratorAsyncIterator:["body.0.body.body.0.argument.callee"]},internal:!1}),regeneratorAsyncIterator:hx("7.27.0",'function AsyncIterator(t,e){function n(r,o,i,f){try{var c=t[r](o),u=c.value;return u instanceof OverloadYield?e.resolve(u.v).then(function(t){n("next",t,i,f)},function(t){n("throw",t,i,f)}):e.resolve(u).then(function(t){c.value=t,i(c)},function(t){return n("throw",t,i,f)})}catch(t){f(t)}}var r;this.next||(define(AsyncIterator.prototype),define(AsyncIterator.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),define(this,"_invoke",function(t,o,i){function f(){return new e(function(e,r){n(t,i,e,r)})}return r=r?r.then(f,f):f()},!0)}',{globals:["Symbol"],locals:{AsyncIterator:["body.0.id","body.0.body.body.2.expression.expressions.0.right.expressions.0.arguments.0.object","body.0.body.body.2.expression.expressions.0.right.expressions.1.arguments.0.object"]},exportBindingAssignments:[],exportName:"AsyncIterator",dependencies:{OverloadYield:["body.0.body.body.0.body.body.0.block.body.1.argument.test.right"],regeneratorDefine:["body.0.body.body.2.expression.expressions.0.right.expressions.0.callee","body.0.body.body.2.expression.expressions.0.right.expressions.1.callee","body.0.body.body.2.expression.expressions.1.callee"]},internal:!0}),regeneratorDefine:hx("7.27.0",'function regeneratorDefine(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}regeneratorDefine=function(e,r,n,t){function o(r,n){regeneratorDefine(e,r,function(e){return this._invoke(r,n,e)})}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))},regeneratorDefine(e,r,n,t)}',{globals:["Object"],locals:{regeneratorDefine:["body.0.id","body.0.body.body.2.expression.expressions.0.right.body.body.0.body.body.0.expression.callee","body.0.body.body.2.expression.expressions.1.callee","body.0.body.body.2.expression.expressions.0.left"]},exportBindingAssignments:["body.0.body.body.2.expression.expressions.0"],exportName:"regeneratorDefine",dependencies:{},internal:!0}),regeneratorKeys:hx("7.27.0","function _regeneratorKeys(e){var n=Object(e),r=[];for(var t in n)r.unshift(t);return function e(){for(;r.length;)if((t=r.pop())in n)return e.value=t,e.done=!1,e;return e.done=!0,e}}",{globals:["Object"],locals:{_regeneratorKeys:["body.0.id"]},exportBindingAssignments:[],exportName:"_regeneratorKeys",dependencies:{},internal:!1}),regeneratorValues:hx("7.18.0",'function _regeneratorValues(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(typeof e+" is not iterable")}',{globals:["Symbol","isNaN","TypeError"],locals:{_regeneratorValues:["body.0.id"]},exportBindingAssignments:[],exportName:"_regeneratorValues",dependencies:{},internal:!1}),set:hx("7.0.0-beta.0",'function set(e,r,t,o){return set="undefined"!=typeof Reflect&&Reflect.set?Reflect.set:function(e,r,t,o){var f,i=superPropBase(e,r);if(i){if((f=Object.getOwnPropertyDescriptor(i,r)).set)return f.set.call(o,t),!0;if(!f.writable)return!1}if(f=Object.getOwnPropertyDescriptor(o,r)){if(!f.writable)return!1;f.value=t,Object.defineProperty(o,r,f)}else defineProperty(o,r,t);return!0},set(e,r,t,o)}function _set(e,r,t,o,f){if(!set(e,r,t,o||e)&&f)throw new TypeError("failed to set property");return t}',{globals:["Reflect","Object","TypeError"],locals:{set:["body.0.id","body.0.body.body.0.argument.expressions.1.callee","body.1.body.body.0.test.left.argument.callee","body.0.body.body.0.argument.expressions.0.left"],_set:["body.1.id"]},exportBindingAssignments:[],exportName:"_set",dependencies:{superPropBase:["body.0.body.body.0.argument.expressions.0.right.alternate.body.body.0.declarations.1.init.callee"],defineProperty:["body.0.body.body.0.argument.expressions.0.right.alternate.body.body.2.alternate.expression.callee"]},internal:!1}),setFunctionName:hx("7.23.6",'function setFunctionName(e,t,n){"symbol"==typeof t&&(t=(t=t.description)?"["+t+"]":"");try{Object.defineProperty(e,"name",{configurable:!0,value:n?n+" "+t:t})}catch(e){}return e}',{globals:["Object"],locals:{setFunctionName:["body.0.id"]},exportBindingAssignments:[],exportName:"setFunctionName",dependencies:{},internal:!1}),setPrototypeOf:hx("7.0.0-beta.0","function _setPrototypeOf(t,e){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},_setPrototypeOf(t,e)}",{globals:["Object"],locals:{_setPrototypeOf:["body.0.id","body.0.body.body.0.argument.expressions.1.callee","body.0.body.body.0.argument.expressions.0.left"]},exportBindingAssignments:["body.0.body.body.0.argument.expressions.0"],exportName:"_setPrototypeOf",dependencies:{},internal:!1}),skipFirstGeneratorNext:hx("7.0.0-beta.0","function _skipFirstGeneratorNext(t){return function(){var r=t.apply(this,arguments);return r.next(),r}}",{globals:[],locals:{_skipFirstGeneratorNext:["body.0.id"]},exportBindingAssignments:[],exportName:"_skipFirstGeneratorNext",dependencies:{},internal:!1}),slicedToArray:hx("7.0.0-beta.0","function _slicedToArray(r,e){return arrayWithHoles(r)||iterableToArrayLimit(r,e)||unsupportedIterableToArray(r,e)||nonIterableRest()}",{globals:[],locals:{_slicedToArray:["body.0.id"]},exportBindingAssignments:[],exportName:"_slicedToArray",dependencies:{arrayWithHoles:["body.0.body.body.0.argument.left.left.left.callee"],iterableToArrayLimit:["body.0.body.body.0.argument.left.left.right.callee"],unsupportedIterableToArray:["body.0.body.body.0.argument.left.right.callee"],nonIterableRest:["body.0.body.body.0.argument.right.callee"]},internal:!1}),superPropBase:hx("7.0.0-beta.0","function _superPropBase(t,o){for(;!{}.hasOwnProperty.call(t,o)&&null!==(t=getPrototypeOf(t)););return t}",{globals:[],locals:{_superPropBase:["body.0.id"]},exportBindingAssignments:[],exportName:"_superPropBase",dependencies:{getPrototypeOf:["body.0.body.body.0.test.right.right.right.callee"]},internal:!1}),superPropGet:hx("7.25.0",'function _superPropGet(t,o,e,r){var p=get(getPrototypeOf(1&r?t.prototype:t),o,e);return 2&r&&"function"==typeof p?function(t){return p.apply(e,t)}:p}',{globals:[],locals:{_superPropGet:["body.0.id"]},exportBindingAssignments:[],exportName:"_superPropGet",dependencies:{get:["body.0.body.body.0.declarations.0.init.callee"],getPrototypeOf:["body.0.body.body.0.declarations.0.init.arguments.0.callee"]},internal:!1}),superPropSet:hx("7.25.0","function _superPropSet(t,e,o,r,p,f){return set(getPrototypeOf(f?t.prototype:t),e,o,r,p)}",{globals:[],locals:{_superPropSet:["body.0.id"]},exportBindingAssignments:[],exportName:"_superPropSet",dependencies:{set:["body.0.body.body.0.argument.callee"],getPrototypeOf:["body.0.body.body.0.argument.arguments.0.callee"]},internal:!1}),taggedTemplateLiteral:hx("7.0.0-beta.0","function _taggedTemplateLiteral(e,t){return t||(t=e.slice(0)),Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}}))}",{globals:["Object"],locals:{_taggedTemplateLiteral:["body.0.id"]},exportBindingAssignments:[],exportName:"_taggedTemplateLiteral",dependencies:{},internal:!1}),taggedTemplateLiteralLoose:hx("7.0.0-beta.0","function _taggedTemplateLiteralLoose(e,t){return t||(t=e.slice(0)),e.raw=t,e}",{globals:[],locals:{_taggedTemplateLiteralLoose:["body.0.id"]},exportBindingAssignments:[],exportName:"_taggedTemplateLiteralLoose",dependencies:{},internal:!1}),tdz:hx("7.5.5",'function _tdzError(e){throw new ReferenceError(e+" is not defined - temporal dead zone")}',{globals:["ReferenceError"],locals:{_tdzError:["body.0.id"]},exportBindingAssignments:[],exportName:"_tdzError",dependencies:{},internal:!1}),temporalRef:hx("7.0.0-beta.0","function _temporalRef(r,e){return r===undef?err(e):r}",{globals:[],locals:{_temporalRef:["body.0.id"]},exportBindingAssignments:[],exportName:"_temporalRef",dependencies:{temporalUndefined:["body.0.body.body.0.argument.test.right"],tdz:["body.0.body.body.0.argument.consequent.callee"]},internal:!1}),temporalUndefined:hx("7.0.0-beta.0","function _temporalUndefined(){}",{globals:[],locals:{_temporalUndefined:["body.0.id"]},exportBindingAssignments:[],exportName:"_temporalUndefined",dependencies:{},internal:!1}),toArray:hx("7.0.0-beta.0","function _toArray(r){return arrayWithHoles(r)||iterableToArray(r)||unsupportedIterableToArray(r)||nonIterableRest()}",{globals:[],locals:{_toArray:["body.0.id"]},exportBindingAssignments:[],exportName:"_toArray",dependencies:{arrayWithHoles:["body.0.body.body.0.argument.left.left.left.callee"],iterableToArray:["body.0.body.body.0.argument.left.left.right.callee"],unsupportedIterableToArray:["body.0.body.body.0.argument.left.right.callee"],nonIterableRest:["body.0.body.body.0.argument.right.callee"]},internal:!1}),toConsumableArray:hx("7.0.0-beta.0","function _toConsumableArray(r){return arrayWithoutHoles(r)||iterableToArray(r)||unsupportedIterableToArray(r)||nonIterableSpread()}",{globals:[],locals:{_toConsumableArray:["body.0.id"]},exportBindingAssignments:[],exportName:"_toConsumableArray",dependencies:{arrayWithoutHoles:["body.0.body.body.0.argument.left.left.left.callee"],iterableToArray:["body.0.body.body.0.argument.left.left.right.callee"],unsupportedIterableToArray:["body.0.body.body.0.argument.left.right.callee"],nonIterableSpread:["body.0.body.body.0.argument.right.callee"]},internal:!1}),toPrimitive:hx("7.1.5",'function toPrimitive(t,e){if("object"!=typeof t||!t)return t;var r;if("undefined"!=typeof Symbol&&void 0!==(r=t[Symbol.toPrimitive])){var i=r.call(t,e||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}',{globals:["Symbol","TypeError","String","Number"],locals:{toPrimitive:["body.0.id"]},exportBindingAssignments:[],exportName:"toPrimitive",dependencies:{},internal:!1}),toPropertyKey:hx("7.1.5",'function toPropertyKey(t){var i=toPrimitive(t,"string");return"symbol"==typeof i?i:i+""}',{globals:[],locals:{toPropertyKey:["body.0.id"]},exportBindingAssignments:[],exportName:"toPropertyKey",dependencies:{toPrimitive:["body.0.body.body.0.declarations.0.init.callee"]},internal:!1}),toSetter:hx("7.24.0",'function _toSetter(t,e,n){e||(e=[]);var r=e.length++;return Object.defineProperty({},"_",{set:function(o){e[r]=o,t.apply(n,e)}})}',{globals:["Object"],locals:{_toSetter:["body.0.id"]},exportBindingAssignments:[],exportName:"_toSetter",dependencies:{},internal:!1}),tsRewriteRelativeImportExtensions:hx("7.27.0",'function tsRewriteRelativeImportExtensions(t,e){return"string"==typeof t&&/^\\.\\.?\\//.test(t)?t.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+)?)\\.([cm]?)ts$/i,function(t,s,r,n,o){return s?e?".jsx":".js":!r||n&&o?r+n+"."+o.toLowerCase()+"js":t}):t}',{globals:[],locals:{tsRewriteRelativeImportExtensions:["body.0.id"]},exportBindingAssignments:[],exportName:"tsRewriteRelativeImportExtensions",dependencies:{},internal:!1}),typeof:hx("7.0.0-beta.0",'function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}',{globals:["Symbol"],locals:{_typeof:["body.0.id","body.0.body.body.0.argument.expressions.1.callee","body.0.body.body.0.argument.expressions.0.left"]},exportBindingAssignments:["body.0.body.body.0.argument.expressions.0"],exportName:"_typeof",dependencies:{},internal:!1}),unsupportedIterableToArray:hx("7.9.0",'function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?arrayLikeToArray(r,a):void 0}}',{globals:["Array"],locals:{_unsupportedIterableToArray:["body.0.id"]},exportBindingAssignments:[],exportName:"_unsupportedIterableToArray",dependencies:{arrayLikeToArray:["body.0.body.body.0.consequent.body.0.consequent.argument.callee","body.0.body.body.0.consequent.body.2.argument.expressions.1.alternate.consequent.callee"]},internal:!1}),usingCtx:hx("7.23.9",'function _usingCtx(){var r="function"==typeof SuppressedError?SuppressedError:function(r,e){var n=Error();return n.name="SuppressedError",n.error=r,n.suppressed=e,n},e={},n=[];function using(r,e){if(null!=e){if(Object(e)!==e)throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");if(r)var o=e[Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose")];if(void 0===o&&(o=e[Symbol.dispose||Symbol.for("Symbol.dispose")],r))var t=o;if("function"!=typeof o)throw new TypeError("Object is not disposable.");t&&(o=function(){try{t.call(e)}catch(r){return Promise.reject(r)}}),n.push({v:e,d:o,a:r})}else r&&n.push({d:e,a:r});return e}return{e:e,u:using.bind(null,!1),a:using.bind(null,!0),d:function(){var o,t=this.e,s=0;function next(){for(;o=n.pop();)try{if(!o.a&&1===s)return s=0,n.push(o),Promise.resolve().then(next);if(o.d){var r=o.d.call(o.v);if(o.a)return s|=2,Promise.resolve(r).then(next,err)}else s|=1}catch(r){return err(r)}if(1===s)return t!==e?Promise.reject(t):Promise.resolve();if(t!==e)throw t}function err(n){return t=t!==e?new r(n,t):n,next()}return next()}}}',{globals:["SuppressedError","Error","Object","TypeError","Symbol","Promise"],locals:{_usingCtx:["body.0.id"]},exportBindingAssignments:[],exportName:"_usingCtx",dependencies:{},internal:!1}),wrapAsyncGenerator:hx("7.0.0-beta.0",'function _wrapAsyncGenerator(e){return function(){return new AsyncGenerator(e.apply(this,arguments))}}function AsyncGenerator(e){var t,n;function resume(t,n){try{var r=e[t](n),o=r.value,u=o instanceof OverloadYield;Promise.resolve(u?o.v:o).then(function(n){if(u){var i="return"===t&&o.k?t:"next";if(!o.k||n.done)return resume(i,n);n=e[i](n).value}settle(!!r.done,n)},function(e){resume("throw",e)})}catch(e){settle(2,e)}}function settle(e,r){2===e?t.reject(r):t.resolve({value:r,done:e}),(t=t.next)?resume(t.key,t.arg):n=null}this._invoke=function(e,r){return new Promise(function(o,u){var i={key:e,arg:r,resolve:o,reject:u,next:null};n?n=n.next=i:(t=n=i,resume(e,r))})},"function"!=typeof e.return&&(this.return=void 0)}AsyncGenerator.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},AsyncGenerator.prototype.next=function(e){return this._invoke("next",e)},AsyncGenerator.prototype.throw=function(e){return this._invoke("throw",e)},AsyncGenerator.prototype.return=function(e){return this._invoke("return",e)};',{globals:["Promise","Symbol"],locals:{_wrapAsyncGenerator:["body.0.id"],AsyncGenerator:["body.1.id","body.0.body.body.0.argument.body.body.0.argument.callee","body.2.expression.expressions.0.left.object.object","body.2.expression.expressions.1.left.object.object","body.2.expression.expressions.2.left.object.object","body.2.expression.expressions.3.left.object.object"]},exportBindingAssignments:[],exportName:"_wrapAsyncGenerator",dependencies:{OverloadYield:["body.1.body.body.1.body.body.0.block.body.0.declarations.2.init.right"]},internal:!1}),wrapNativeSuper:hx("7.0.0-beta.0",'function _wrapNativeSuper(t){var r="function"==typeof Map?new Map:void 0;return _wrapNativeSuper=function(t){if(null===t||!isNativeFunction(t))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==r){if(r.has(t))return r.get(t);r.set(t,Wrapper)}function Wrapper(){return construct(t,arguments,getPrototypeOf(this).constructor)}return Wrapper.prototype=Object.create(t.prototype,{constructor:{value:Wrapper,enumerable:!1,writable:!0,configurable:!0}}),setPrototypeOf(Wrapper,t)},_wrapNativeSuper(t)}',{globals:["Map","TypeError","Object"],locals:{_wrapNativeSuper:["body.0.id","body.0.body.body.1.argument.expressions.1.callee","body.0.body.body.1.argument.expressions.0.left"]},exportBindingAssignments:["body.0.body.body.1.argument.expressions.0"],exportName:"_wrapNativeSuper",dependencies:{getPrototypeOf:["body.0.body.body.1.argument.expressions.0.right.body.body.3.body.body.0.argument.arguments.2.object.callee"],setPrototypeOf:["body.0.body.body.1.argument.expressions.0.right.body.body.4.argument.expressions.1.callee"],isNativeFunction:["body.0.body.body.1.argument.expressions.0.right.body.body.0.test.right.argument.callee"],construct:["body.0.body.body.1.argument.expressions.0.right.body.body.3.body.body.0.argument.callee"]},internal:!1}),wrapRegExp:hx("7.19.0",'function _wrapRegExp(){_wrapRegExp=function(e,r){return new BabelRegExp(e,void 0,r)};var e=RegExp.prototype,r=new WeakMap;function BabelRegExp(e,t,p){var o=RegExp(e,t);return r.set(o,p||r.get(e)),setPrototypeOf(o,BabelRegExp.prototype)}function buildGroups(e,t){var p=r.get(t);return Object.keys(p).reduce(function(r,t){var o=p[t];if("number"==typeof o)r[t]=e[o];else{for(var i=0;void 0===e[o[i]]&&i+1]+)(>|$)/g,function(e,r,t){if(""===t)return e;var p=o[r];return Array.isArray(p)?"$"+p.join("$"):"number"==typeof p?"$"+p:""}))}if("function"==typeof p){var i=this;return e[Symbol.replace].call(this,t,function(){var e=arguments;return"object"!=typeof e[e.length-1]&&(e=[].slice.call(e)).push(buildGroups(e,i)),p.apply(this,e)})}return e[Symbol.replace].call(this,t,p)},_wrapRegExp.apply(this,arguments)}',{globals:["RegExp","WeakMap","Object","Symbol","Array"],locals:{_wrapRegExp:["body.0.id","body.0.body.body.4.argument.expressions.3.callee.object","body.0.body.body.0.expression.left"]},exportBindingAssignments:["body.0.body.body.0.expression"],exportName:"_wrapRegExp",dependencies:{setPrototypeOf:["body.0.body.body.2.body.body.1.argument.expressions.1.callee"],inherits:["body.0.body.body.4.argument.expressions.0.callee"]},internal:!1}),writeOnlyError:hx("7.12.13","function _writeOnlyError(r){throw new TypeError('\"'+r+'\" is write-only')}",{globals:["TypeError"],locals:{_writeOnlyError:["body.0.id"]},exportBindingAssignments:[],exportName:"_writeOnlyError",dependencies:{},internal:!1})},Rx=vf,yx=ai;function vx(e,a,n){try{for(var t=a.split("."),r=t.shift();t.length>0;)e=e[r],r=t.shift();if(!(arguments.length>2))return e[r];e[r]=n}catch(e){throw e.message+=" (when accessing "+a+")",e}}var bx=Object.create(null);function xx(e){if(!bx[e]){var a=mx[e];if(!a)throw Object.assign(new ReferenceError("Unknown helper "+e),{code:"BABEL_HELPER_UNKNOWN",helper:e});bx[e]={minVersion:a.minVersion,build:function(e,n,t,r){var i=a.ast();return function(e,a,n,t,r,i){var s=a.locals,d=a.dependencies,u=a.exportBindingAssignments,c=a.exportName,l=new Set(t||[]);n&&l.add(n);for(var p=0,g=Object.entries(s);p1)for(var n=1;n=1e3?(e/1e3).toFixed(1)+"s":e+"ms"},log:console.debug||console.log||function(){}};!function(e){Dx=[],kx=[];for(var a,n=o((Ax=e).trim().replace(/\s+/g,",").split(",").filter(Boolean));!(a=n()).done;){var t=a.value;"-"===t[0]?kx.push(t.slice(1)):Dx.push(t)}}(function(){var e;try{e=localStorage.getItem("debug")||localStorage.getItem("DEBUG")}catch(e){}return!e&&void 0!==nS&&"env"in nS&&(e=nS.env.DEBUG),e||""}());var rS=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function iS(e,a){var n=this.useColors;if(a[0]=(n?"%c":"")+this.namespace+(n?" %c":" ")+a[0]+(n?"%c ":" ")+"+"+this.humanize(e),n){var t="color: "+this.color;a.splice(1,0,t,"color: inherit");var r=0,i=0;a[0].replace(/%[a-z%]/gi,function(e){"%%"!==e&&(r++,"%c"===e&&(i=r))}),a.splice(i,0,t)}}function oS(e,a){var n,t=null!==(n=a)&&void 0!==n?n:function(e,a){for(var n=0,t=0;t=11?a+=n-1:n>=9?a+=n-9:n>=1&&(a+=n+1),n++}while(this.hasLabel(a)||this.hasBinding(a)||this.hasGlobal(a)||this.hasReference(a));var t=this.getProgramParent();return t.referencesSet.add(a),t.uidsSet.add(a),a},a.generateUidBasedOnNode=function(e,a){var n=[];eT(e,n);var t=n.join("$");return t=t.replace(/^_/,"")||a||"ref",this.generateUid(t.slice(0,20))},a.generateUidIdentifierBasedOnNode=function(e,a){return hE(this.generateUidBasedOnNode(e,a))},a.isStatic=function(e){if(UE(e)||FE(e)||XE(e))return!0;if(CE(e)){var a=this.getBinding(e.name);return a?a.constant:this.hasBinding(e.name)}return!1},a.maybeGenerateMemoised=function(e,a){if(this.isStatic(e))return null;var n=this.generateUidIdentifierBasedOnNode(e);return a?n:(this.push({id:n}),gE(n))},a.checkBlockScopedCollisions=function(e,a,n,t){if("param"!==a&&("local"!==e.kind&&("let"===a||"let"===e.kind||"const"===e.kind||"module"===e.kind||"param"===e.kind&&"const"===a)))throw this.path.hub.buildError(t,'Duplicate declaration "'+n+'"',TypeError)},a.rename=function(e,a){var n=this.getBinding(e);n&&(a||(a=this.generateUidIdentifier(e).name),new aE(n,e,a).rename())},a.dump=function(){var e="-".repeat(60);console.log(e);var a=this;do{console.log("#",a.block.type);for(var n=0,t=Object.keys(a.bindings);n0)&&this.isPure(e.body,a));if(bE(e)){for(var s,d=o(e.body);!(s=d()).done;){var u=s.value;if(!this.isPure(u,a))return!1}return!0}if(RE(e))return this.isPure(e.left,a)&&this.isPure(e.right,a);if(mE(e)){for(var c,l=o(e.elements);!(c=l()).done;){var p=c.value;if(null!==p&&!this.isPure(p,a))return!1}return!0}if(BE(e)){for(var g,f=o(e.properties);!(g=f()).done;){var h=g.value;if(!this.isPure(h,a))return!1}return!0}if(DE(e))return!(e.computed&&!this.isPure(e.key,a))&&!((null==(r=e.decorators)?void 0:r.length)>0);if(NE(e))return!(e.computed&&!this.isPure(e.key,a))&&(!((null==(i=e.decorators)?void 0:i.length)>0)&&!((zE(e)||e.static)&&null!==e.value&&!this.isPure(e.value,a)));if(qE(e))return this.isPure(e.argument,a);if(LE(e)){for(var m,R=o(e.expressions);!(m=R()).done;){var y=m.value;if(!this.isPure(y,a))return!1}return!0}return ME(e)?HE(e.tag,"String.raw")&&!this.hasBinding("String",{noGlobals:!0})&&this.isPure(e.quasi,a):_E(e)?!e.computed&&CE(e.object)&&"Symbol"===e.object.name&&CE(e.property)&&"for"!==e.property.name&&!this.hasBinding("Symbol",{noGlobals:!0}):yE(e)?HE(e.callee,"Symbol.for")&&!this.hasBinding("Symbol",{noGlobals:!0})&&1===e.arguments.length&&U(e.arguments[0]):jE(e)},a.setData=function(e,a){return this.data[e]=a},a.getData=function(e){var a=this;do{var n=a.data[e];if(null!=n)return n}while(a=a.parent)},a.removeData=function(e){var a=this;do{null!=a.data[e]&&(a.data[e]=null)}while(a=a.parent)},a.init=function(){this.inited||(this.inited=!0,this.crawl())},a.crawl=function(){var e=this.path;aT(this),this.data=Object.create(null);var a=this;do{if(a.crawling)return;if(a.path.isProgram())break}while(a=a.parent);var n=a,t={references:[],constantViolations:[],assignments:[]};if(this.crawling=!0,nT||(nT=ZI.visitors.merge([{Scope:function(e){aT(e.scope)}},tT])),"Program"!==e.type){var r=nT[e.type];if(r)for(var i,s=o(r.enter);!(i=s()).done;){i.value.call(t,e,t)}}!function(e,a,n){var t=qS(a);if(t.enter||t.exit)throw new Error("Should not be used with enter/exit visitors.");!function e(a,r,i,s,d,u,c,l){if(i){var p=l||II.get({hub:c,parentPath:a,parent:r,container:s,listKey:u,key:d});qI.call(p);var g=t[i.type];if(null!=g&&g.enter)for(var f,h=o(g.enter);!(f=h()).done;)f.value.call(n,p,n);if(!p.shouldSkip){var m=nE[i.type];if(null!=m&&m.length){for(var R,y=o(m);!(R=y()).done;){var v=R.value,b=i[v];if(b)if(Array.isArray(b))for(var x=0;x>18&63]+oT[e>>12&63]+oT[e>>6&63]+oT[63&e]}function pT(e,a,n){for(var t,r=[],i=a;id?d:s+o));return 1===t?(a=e[n-1],r+=oT[a>>2],r+=oT[a<<4&63],r+="=="):2===t&&(a=(e[n-2]<<8)+e[n-1],r+=oT[a>>10],r+=oT[a>>4&63],r+=oT[a<<2&63],r+="="),i.push(r),i.join("")}function fT(e,a,n,t,r){var i,o,s=8*r-t-1,d=(1<>1,c=-7,l=n?r-1:0,p=n?-1:1,g=e[a+l];for(l+=p,i=g&(1<<-c)-1,g>>=-c,c+=s;c>0;i=256*i+e[a+l],l+=p,c-=8);for(o=i&(1<<-c)-1,i>>=-c,c+=t;c>0;o=256*o+e[a+l],l+=p,c-=8);if(0===i)i=1-u;else{if(i===d)return o?NaN:1/0*(g?-1:1);o+=Math.pow(2,t),i-=u}return(g?-1:1)*o*Math.pow(2,i-t)}function hT(e,a,n,t,r,i){var o,s,d,u=8*i-r-1,c=(1<>1,p=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,g=t?0:i-1,f=t?1:-1,h=a<0||0===a&&1/a<0?1:0;for(a=Math.abs(a),isNaN(a)||a===1/0?(s=isNaN(a)?1:0,o=c):(o=Math.floor(Math.log(a)/Math.LN2),a*(d=Math.pow(2,-o))<1&&(o--,d*=2),(a+=o+l>=1?p/d:p*Math.pow(2,1-l))*d>=2&&(o++,d/=2),o+l>=c?(s=0,o=c):o+l>=1?(s=(a*d-1)*Math.pow(2,r),o+=l):(s=a*Math.pow(2,l-1)*Math.pow(2,r),o=0));r>=8;e[n+g]=255&s,g+=f,s/=256,r-=8);for(o=o<0;e[n+g]=255&o,g+=f,o/=256,u-=8);e[n+g-f]|=128*h}var mT={}.toString,RT=Array.isArray||function(e){return"[object Array]"==mT.call(e)};function yT(){return bT.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function vT(e,a){if(yT()=yT())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+yT().toString(16)+" bytes");return 0|e}function CT(e){return!(null==e||!e._isBuffer)}function PT(e,a){if(CT(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var t=!1;;)switch(a){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return ew(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return aw(e).length;default:if(t)return ew(e).length;a=(""+a).toLowerCase(),t=!0}}function AT(e,a,n){var t=!1;if((void 0===a||a<0)&&(a=0),a>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(a>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return VT(this,a,n);case"utf8":case"utf-8":return LT(this,a,n);case"ascii":return qT(this,a,n);case"latin1":case"binary":return WT(this,a,n);case"base64":return MT(this,a,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return HT(this,a,n);default:if(t)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),t=!0}}function _T(e,a,n){var t=e[a];e[a]=e[n],e[n]=t}function DT(e,a,n,t,r){if(0===e.length)return-1;if("string"==typeof n?(t=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=r?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(r)return-1;n=e.length-1}else if(n<0){if(!r)return-1;n=0}if("string"==typeof a&&(a=bT.from(a,t)),CT(a))return 0===a.length?-1:kT(e,a,n,t,r);if("number"==typeof a)return a&=255,bT.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,a,n):Uint8Array.prototype.lastIndexOf.call(e,a,n):kT(e,[a],n,t,r);throw new TypeError("val must be string, number or Buffer")}function kT(e,a,n,t,r){var i,o=1,s=e.length,d=a.length;if(void 0!==t&&("ucs2"===(t=String(t).toLowerCase())||"ucs-2"===t||"utf16le"===t||"utf-16le"===t)){if(e.length<2||a.length<2)return-1;o=2,s/=2,d/=2,n/=2}function u(e,a){return 1===o?e[a]:e.readUInt16BE(a*o)}if(r){var c=-1;for(i=n;is&&(n=s-d),i=n;i>=0;i--){for(var l=!0,p=0;pr&&(t=r):t=r;var i=a.length;if(i%2!=0)throw new TypeError("Invalid hex string");t>i/2&&(t=i/2);for(var o=0;o>8,r=n%256,i.push(r),i.push(t);return i}(a,e.length-n),e,n,t)}function MT(e,a,n){return 0===a&&n===e.length?gT(e):gT(e.slice(a,n))}function LT(e,a,n){n=Math.min(e.length,n);for(var t=[],r=a;r239?4:u>223?3:u>191?2:1;if(r+l<=n)switch(l){case 1:u<128&&(c=u);break;case 2:128==(192&(i=e[r+1]))&&(d=(31&u)<<6|63&i)>127&&(c=d);break;case 3:i=e[r+1],o=e[r+2],128==(192&i)&&128==(192&o)&&(d=(15&u)<<12|(63&i)<<6|63&o)>2047&&(d<55296||d>57343)&&(c=d);break;case 4:i=e[r+1],o=e[r+2],s=e[r+3],128==(192&i)&&128==(192&o)&&128==(192&s)&&(d=(15&u)<<18|(63&i)<<12|(63&o)<<6|63&s)>65535&&d<1114112&&(c=d)}null===c?(c=65533,l=1):c>65535&&(c-=65536,t.push(c>>>10&1023|55296),c=56320|1023&c),t.push(c),r+=l}return function(e){var a=e.length;if(a<=UT)return String.fromCharCode.apply(String,e);var n="",t=0;for(;t0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),""},bT.prototype.compare=function(e,a,n,t,r){if(!CT(e))throw new TypeError("Argument must be a Buffer");if(void 0===a&&(a=0),void 0===n&&(n=e?e.length:0),void 0===t&&(t=0),void 0===r&&(r=this.length),a<0||n>e.length||t<0||r>this.length)throw new RangeError("out of range index");if(t>=r&&a>=n)return 0;if(t>=r)return-1;if(a>=n)return 1;if(this===e)return 0;for(var i=(r>>>=0)-(t>>>=0),o=(n>>>=0)-(a>>>=0),s=Math.min(i,o),d=this.slice(t,r),u=e.slice(a,n),c=0;cr)&&(n=r),e.length>0&&(n<0||a<0)||a>this.length)throw new RangeError("Attempt to write outside buffer bounds");t||(t="utf8");for(var i=!1;;)switch(t){case"hex":return IT(this,e,a,n);case"utf8":case"utf-8":return BT(this,e,a,n);case"ascii":return NT(this,e,a,n);case"latin1":case"binary":return jT(this,e,a,n);case"base64":return OT(this,e,a,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return FT(this,e,a,n);default:if(i)throw new TypeError("Unknown encoding: "+t);t=(""+t).toLowerCase(),i=!0}},bT.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var UT=4096;function qT(e,a,n){var t="";n=Math.min(e.length,n);for(var r=a;rt)&&(n=t);for(var r="",i=a;in)throw new RangeError("Trying to access beyond buffer length")}function KT(e,a,n,t,r,i){if(!CT(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(a>r||ae.length)throw new RangeError("Index out of range")}function JT(e,a,n,t){a<0&&(a=65535+a+1);for(var r=0,i=Math.min(e.length-n,2);r>>8*(t?r:1-r)}function zT(e,a,n,t){a<0&&(a=4294967295+a+1);for(var r=0,i=Math.min(e.length-n,4);r>>8*(t?r:3-r)&255}function XT(e,a,n,t,r,i){if(n+t>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function YT(e,a,n,t,r){return r||XT(e,0,n,4),hT(e,a,n,t,23,4),n+4}function $T(e,a,n,t,r){return r||XT(e,0,n,8),hT(e,a,n,t,52,8),n+8}bT.prototype.slice=function(e,a){var n,t=this.length;if((e=~~e)<0?(e+=t)<0&&(e=0):e>t&&(e=t),(a=void 0===a?t:~~a)<0?(a+=t)<0&&(a=0):a>t&&(a=t),a0&&(r*=256);)t+=this[e+--a]*r;return t},bT.prototype.readUInt8=function(e,a){return a||GT(e,1,this.length),this[e]},bT.prototype.readUInt16LE=function(e,a){return a||GT(e,2,this.length),this[e]|this[e+1]<<8},bT.prototype.readUInt16BE=function(e,a){return a||GT(e,2,this.length),this[e]<<8|this[e+1]},bT.prototype.readUInt32LE=function(e,a){return a||GT(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},bT.prototype.readUInt32BE=function(e,a){return a||GT(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},bT.prototype.readIntLE=function(e,a,n){e|=0,a|=0,n||GT(e,a,this.length);for(var t=this[e],r=1,i=0;++i=(r*=128)&&(t-=Math.pow(2,8*a)),t},bT.prototype.readIntBE=function(e,a,n){e|=0,a|=0,n||GT(e,a,this.length);for(var t=a,r=1,i=this[e+--t];t>0&&(r*=256);)i+=this[e+--t]*r;return i>=(r*=128)&&(i-=Math.pow(2,8*a)),i},bT.prototype.readInt8=function(e,a){return a||GT(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},bT.prototype.readInt16LE=function(e,a){a||GT(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},bT.prototype.readInt16BE=function(e,a){a||GT(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},bT.prototype.readInt32LE=function(e,a){return a||GT(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},bT.prototype.readInt32BE=function(e,a){return a||GT(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},bT.prototype.readFloatLE=function(e,a){return a||GT(e,4,this.length),fT(this,e,!0,23,4)},bT.prototype.readFloatBE=function(e,a){return a||GT(e,4,this.length),fT(this,e,!1,23,4)},bT.prototype.readDoubleLE=function(e,a){return a||GT(e,8,this.length),fT(this,e,!0,52,8)},bT.prototype.readDoubleBE=function(e,a){return a||GT(e,8,this.length),fT(this,e,!1,52,8)},bT.prototype.writeUIntLE=function(e,a,n,t){(e=+e,a|=0,n|=0,t)||KT(this,e,a,n,Math.pow(2,8*n)-1,0);var r=1,i=0;for(this[a]=255&e;++i=0&&(i*=256);)this[a+r]=e/i&255;return a+n},bT.prototype.writeUInt8=function(e,a,n){return e=+e,a|=0,n||KT(this,e,a,1,255,0),bT.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[a]=255&e,a+1},bT.prototype.writeUInt16LE=function(e,a,n){return e=+e,a|=0,n||KT(this,e,a,2,65535,0),bT.TYPED_ARRAY_SUPPORT?(this[a]=255&e,this[a+1]=e>>>8):JT(this,e,a,!0),a+2},bT.prototype.writeUInt16BE=function(e,a,n){return e=+e,a|=0,n||KT(this,e,a,2,65535,0),bT.TYPED_ARRAY_SUPPORT?(this[a]=e>>>8,this[a+1]=255&e):JT(this,e,a,!1),a+2},bT.prototype.writeUInt32LE=function(e,a,n){return e=+e,a|=0,n||KT(this,e,a,4,4294967295,0),bT.TYPED_ARRAY_SUPPORT?(this[a+3]=e>>>24,this[a+2]=e>>>16,this[a+1]=e>>>8,this[a]=255&e):zT(this,e,a,!0),a+4},bT.prototype.writeUInt32BE=function(e,a,n){return e=+e,a|=0,n||KT(this,e,a,4,4294967295,0),bT.TYPED_ARRAY_SUPPORT?(this[a]=e>>>24,this[a+1]=e>>>16,this[a+2]=e>>>8,this[a+3]=255&e):zT(this,e,a,!1),a+4},bT.prototype.writeIntLE=function(e,a,n,t){if(e=+e,a|=0,!t){var r=Math.pow(2,8*n-1);KT(this,e,a,n,r-1,-r)}var i=0,o=1,s=0;for(this[a]=255&e;++i=0&&(o*=256);)e<0&&0===s&&0!==this[a+i+1]&&(s=1),this[a+i]=(e/o|0)-s&255;return a+n},bT.prototype.writeInt8=function(e,a,n){return e=+e,a|=0,n||KT(this,e,a,1,127,-128),bT.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[a]=255&e,a+1},bT.prototype.writeInt16LE=function(e,a,n){return e=+e,a|=0,n||KT(this,e,a,2,32767,-32768),bT.TYPED_ARRAY_SUPPORT?(this[a]=255&e,this[a+1]=e>>>8):JT(this,e,a,!0),a+2},bT.prototype.writeInt16BE=function(e,a,n){return e=+e,a|=0,n||KT(this,e,a,2,32767,-32768),bT.TYPED_ARRAY_SUPPORT?(this[a]=e>>>8,this[a+1]=255&e):JT(this,e,a,!1),a+2},bT.prototype.writeInt32LE=function(e,a,n){return e=+e,a|=0,n||KT(this,e,a,4,2147483647,-2147483648),bT.TYPED_ARRAY_SUPPORT?(this[a]=255&e,this[a+1]=e>>>8,this[a+2]=e>>>16,this[a+3]=e>>>24):zT(this,e,a,!0),a+4},bT.prototype.writeInt32BE=function(e,a,n){return e=+e,a|=0,n||KT(this,e,a,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),bT.TYPED_ARRAY_SUPPORT?(this[a]=e>>>24,this[a+1]=e>>>16,this[a+2]=e>>>8,this[a+3]=255&e):zT(this,e,a,!1),a+4},bT.prototype.writeFloatLE=function(e,a,n){return YT(this,e,a,!0,n)},bT.prototype.writeFloatBE=function(e,a,n){return YT(this,e,a,!1,n)},bT.prototype.writeDoubleLE=function(e,a,n){return $T(this,e,a,!0,n)},bT.prototype.writeDoubleBE=function(e,a,n){return $T(this,e,a,!1,n)},bT.prototype.copy=function(e,a,n,t){if(n||(n=0),t||0===t||(t=this.length),a>=e.length&&(a=e.length),a||(a=0),t>0&&t=this.length)throw new RangeError("sourceStart out of bounds");if(t<0)throw new RangeError("sourceEnd out of bounds");t>this.length&&(t=this.length),e.length-a=0;--r)e[r+a]=this[r+n];else if(i<1e3||!bT.TYPED_ARRAY_SUPPORT)for(r=0;r>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=a;i55295&&n<57344){if(!r){if(n>56319){(a-=3)>-1&&i.push(239,191,189);continue}if(o+1===t){(a-=3)>-1&&i.push(239,191,189);continue}r=n;continue}if(n<56320){(a-=3)>-1&&i.push(239,191,189),r=n;continue}n=65536+(r-55296<<10|n-56320)}else r&&(a-=3)>-1&&i.push(239,191,189);if(r=null,n<128){if((a-=1)<0)break;i.push(n)}else if(n<2048){if((a-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((a-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((a-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function aw(e){return function(e){var a,n,t,r,i,o;uT||cT();var s=e.length;if(s%4>0)throw new Error("Invalid string. Length must be a multiple of 4");i="="===e[s-2]?2:"="===e[s-1]?1:0,o=new dT(3*s/4-i),t=i>0?s-4:s;var d=0;for(a=0,n=0;a>16&255,o[d++]=r>>8&255,o[d++]=255&r;return 2===i?(r=sT[e.charCodeAt(a)]<<2|sT[e.charCodeAt(a+1)]>>4,o[d++]=255&r):1===i&&(r=sT[e.charCodeAt(a)]<<10|sT[e.charCodeAt(a+1)]<<4|sT[e.charCodeAt(a+2)]>>2,o[d++]=r>>8&255,o[d++]=255&r),o}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(QT,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function nw(e,a,n,t){for(var r=0;r=a.length||r>=e.length);++r)a[r+n]=e[r];return r}function tw(e){return null!=e&&(!!e._isBuffer||rw(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&rw(e.slice(0,0))}(e))}function rw(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}for(var iw=",".charCodeAt(0),ow=";".charCodeAt(0),sw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",dw=new Uint8Array(64),uw=new Uint8Array(128),cw=0;cw<64;cw++){var lw=sw.charCodeAt(cw);dw[cw]=lw,uw[lw]=cw}function pw(e,a){do{var n=31&a;(a>>>=5)>0&&(n|=32),e.write(dw[n])}while(a>0)}function gw(e){return e<0?-e<<1|1:e<<1}var fw="undefined"!=typeof TextDecoder?new TextDecoder:void 0!==bT?{decode:function(e){return bT.from(e.buffer,e.byteOffset,e.byteLength).toString()}}:{decode:function(e){for(var a="",n=0;n0?a+fw.decode(e.subarray(0,n)):a},i(e)}();!function(){function e(e){this.pos=0,this.buffer=e}var a=e.prototype;a.next=function(){return this.buffer.charCodeAt(this.pos++)},a.peek=function(){return this.buffer.charCodeAt(this.pos)},a.indexOf=function(e){var a=this.buffer,n=this.pos,t=a.indexOf(e,n);return-1===t?a.length:t},i(e)}();for(var mw=",".charCodeAt(0),Rw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",yw=new Uint8Array(64),vw=new Uint8Array(128),bw=0;bw<64;bw++){var xw=Rw.charCodeAt(bw);yw[bw]=xw,vw[xw]=bw}function Sw(e,a){var n=0,t=0,r=0;do{var i=e.next();n|=(31&(r=vw[i]))<>>=1,o&&(n=-2147483648|-n),a+n}function Ew(e,a){return!(e.pos>=a)&&e.peek()!==mw}var Tw="undefined"!=typeof TextDecoder?new TextDecoder:void 0!==bT?{decode:function(e){return bT.from(e.buffer,e.byteOffset,e.byteLength).toString()}}:{decode:function(e){for(var a="",n=0;n0?a+Tw.decode(e.subarray(0,n)):a},i(e)}();var ww=function(){function e(e){this.pos=0,this.buffer=e}var a=e.prototype;return a.next=function(){return this.buffer.charCodeAt(this.pos++)},a.peek=function(){return this.buffer.charCodeAt(this.pos)},a.indexOf=function(e){var a=this.buffer,n=this.pos,t=a.indexOf(e,n);return-1===t?a.length:t},i(e)}();function Cw(e){e.sort(Pw)}function Pw(e,a){return e[0]-a[0]}var Aw=/^[\w+.-]+:\/\//,_w=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,Dw=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function kw(e){return e.startsWith("/")}function Iw(e){return/^[.?#]/.test(e)}function Bw(e){var a=_w.exec(e);return Nw(a[1],a[2]||"",a[3],a[4]||"",a[5]||"/",a[6]||"",a[7]||"")}function Nw(e,a,n,t,r,i,o){return{scheme:e,user:a,host:n,port:t,path:r,query:i,hash:o,type:7}}function jw(e){if(function(e){return e.startsWith("//")}(e)){var a=Bw("http:"+e);return a.scheme="",a.type=6,a}if(kw(e)){var n=Bw("http://foo.com"+e);return n.scheme="",n.host="",n.type=5,n}if(function(e){return e.startsWith("file:")}(e))return function(e){var a=Dw.exec(e),n=a[2];return Nw("file:","",a[1]||"","",kw(n)?n:"/"+n,a[3]||"",a[4]||"")}(e);if(function(e){return Aw.test(e)}(e))return Bw(e);var t=Bw("http://foo.com/"+e);return t.scheme="",t.host="",t.type=e?e.startsWith("?")?3:e.startsWith("#")?2:4:1,t}function Ow(e,a){for(var n=a<=4,t=e.path.split("/"),r=1,i=0,o=!1,s=1;st&&(t=i)}Ow(n,t);var o=n.query+n.hash;switch(t){case 2:case 3:return o;case 4:var s=n.path.slice(1);return s?Iw(a||e)&&!Iw(s)?"./"+s+o:s+o:o||".";case 5:return n.path+o;default:return n.scheme+"//"+n.user+n.host+n.port+n.path+o}}function Mw(e,a){for(var n=a;n=0&&e[t][0]===a;n=t--);return n}function Gw(e,a,n,t){var r=n.lastKey,i=n.lastNeedle,o=n.lastIndex,s=0,d=e.length-1;if(t===r){if(a===i)return Ww=-1!==o&&e[o][0]===a,o;a>=i?s=-1===o?0:o:d=o}return n.lastKey=t,n.lastNeedle=a,n.lastIndex=function(e,a,n,t){for(;n<=t;){var r=n+(t-n>>1),i=e[r][0]-a;if(0===i)return Ww=!0,r;i<0?n=r+1:t=r-1}return Ww=!1,n-1}(e,a,s,d)}var Kw=i(function(e,a){var n="string"==typeof e;if(!n&&e._decodedMemo)return e;var t=function(e){return"string"==typeof e?JSON.parse(e):e}(e),r=t.version,i=t.file,o=t.names,s=t.sourceRoot,d=t.sources,u=t.sourcesContent;this.version=r,this.file=i,this.names=o||[],this.sourceRoot=s,this.sources=d,this.sourcesContent=u,this.ignoreList=t.ignoreList||t.x_google_ignoreList||void 0;var c=function(e,a){var n=function(e){if(!e)return"";var a=e.lastIndexOf("/");return e.slice(0,a+1)}(e),t=a?a+"/":"";return function(e){return Fw(t+(e||""),n)}}(a,s);this.resolvedSources=d.map(c);var l=t.mappings;if("string"==typeof l)this._encoded=l,this._decoded=void 0;else{if(!Array.isArray(l))throw t.sections?new Error("TraceMap passed sectioned source map, please use FlattenMap export instead"):new Error("invalid source map: "+JSON.stringify(t));this._encoded=void 0,this._decoded=function(e,a){var n=Mw(e,0);if(n===e.length)return e;a||(e=e.slice());for(var t=n;t=i.length)return Xw(null,null,null,null);var o=i[n],s=function(e,a,n,t,r){var i=Gw(e,t,a,n);Ww?i=(-1===r?Vw:Hw)(e,t,i):-1===r&&i++;return-1===i||i===e.length?-1:i}(o,e._decodedMemo,n,t,r||1);if(-1===s)return Xw(null,null,null,null);var d=o[s];if(1===d.length)return Xw(null,null,null,null);var u=e.names;return Xw(e.resolvedSources[d[1]],d[2]+1,d[3],5===d.length?u[d[4]]:null)}function Xw(e,a,n,t){return{source:e,line:a,column:n,name:t}}var Yw=i(function(){this._indexes={__proto__:null},this.array=[]});function $w(e,a){var n=function(e,a){return e._indexes[a]}(e,a);if(void 0!==n)return n;var t=e,r=t.array,i=t._indexes,o=r.push(a);return i[a]=o-1}var Qw=i(function(e){var a=void 0===e?{}:e,n=a.file,t=a.sourceRoot;this._names=new Yw,this._sources=new Yw,this._sourcesContent=[],this._mappings=[],this.file=n,this.sourceRoot=t,this._ignoreList=new Yw,this._rangeMappings=[]});var Zw=function(e,a){return function(e,a,n){var t=n.generated,r=n.source,i=n.original,o=n.name,s=n.content,d=n.isRange;r?tC(e,a,t.line-1,t.column,r,i.line-1,i.column,o,s):tC(e,a,t.line-1,t.column,null,null,null,null,null);d&&function(e,a,n,t){void 0===t&&(t=!0);var r=e,i=r._mappings,o=r._rangeMappings,s=rC(i,a),d=iC(s,n)-1,u=rC(o,a),c=uC(u,d);if(t){if(c>=0)return;sC(u,~c,d)}else{if(c<0)return;u.splice(c,1)}}(a,t.line-1,t.column)}(!0,e,a)};function eC(e,a,n){var t=e,r=t._sources;t._sourcesContent[$w(r,a)]=n}function aC(e){var a=e,n=a._mappings,t=a._sources,r=a._sourcesContent,i=a._names,o=a._ignoreList.array,s=a._rangeMappings;return dC(n),dC(s),{version:3,file:e.file||void 0,names:i.array,sourceRoot:e.sourceRoot||void 0,sources:t.array,sourcesContent:r,mappings:n,ignoreList:o.length>0?o:void 0,rangeMappings:s.length>0?s:void 0}}function nC(e){var a=aC(e),n=a;return n.mappings=function(e){for(var a=new hw,n=0,t=0,r=0,i=0,o=0;o0&&a.write(ow),0!==s.length)for(var d=0,u=0;u0&&a.write(iw),pw(a,gw(c[0]-d)),d=c[0],1!==c.length&&(pw(a,gw(c[1]-n)),pw(a,gw(c[2]-t)),pw(a,gw(c[3]-r)),n=c[1],t=c[2],r=c[3],4!==c.length&&(pw(a,gw(c[4]-i)),i=c[4]))}}return a.flush()}(a.mappings),a.rangeMappings&&(n.rangeMappings=function(e){if(0===e.length)return"";for(var a=new hw,n=0;n0&&a.write(ow);for(var r=0,i=0;i0;n--){if(a>=e[n-1][0])return n}return 0}function oC(e,a,n,t){if(0===a.length)return!1;if(t<0)for(;--n>=0;){var r=e[n];if(r.length>0){t=r.length-1;break}}return!(n<0)&&(!(n>=a.length)&&uC(a[n],t)>=0)}function sC(e,a,n){for(var t=e.length;t>a;t--)e[t]=e[t-1];e[a]=n}function dC(e){for(var a=e.length-1;a>=0&&!(e[a].length>0);a--)e.pop()}function uC(e,a){for(var n=e.length;n>0;n--){var t=e[n-1];if(t===a)return n-1;if(t=e.length))for(var t=e[a],r=t.length-1;r>=0&&!(t[r]=64?this._indentChar.repeat(a):pC[a/2];this._str+=t}else this._str+=a>1?String.fromCharCode(e).repeat(a):String.fromCharCode(e);var r=32===e,i=this._position;if(10!==e){if(this._map){var o=this._sourcePosition;n&&o?(this._map.mark(i,null,o.line,o.column,r?void 0:o.identifierName,r?void 0:o.identifierNamePos,o.filename),!r&&this._canMarkIdName&&(o.identifierName=void 0,o.identifierNamePos=void 0)):this._map.mark(i,null)}i.column+=a}else i.line++,i.column=0},a._append=function(e,a,n){var t=e.length,r=this._position,i=this._sourcePosition;this._last=-1,++this._appendCount>4096?(this._str,this._buf+=this._str,this._str=e,this._appendCount=0):this._str+=e;var o=!n&&null!==this._map;if(a||o){var s=i.column,d=i.identifierName,u=i.identifierNamePos,c=i.filename,l=i.line;null==d&&null==u||!this._canMarkIdName||(i.identifierName=void 0,i.identifierNamePos=void 0);var p=e.indexOf("\n"),g=0;for(o&&0!==p&&this._map.mark(r,e,l,s,d,u,c);-1!==p;)r.line++,r.column=0,(g=p+1)",7],["<=",7],[">=",7],["in",7],["instanceof",7],[">>",8],["<<",8],[">>>",8],["+",9],["-",9],["*",10],["/",10],["%",10],["**",11]]);function bC(e){return 154===e||199===e||207===e}var xC=function(e,a,n){return(22===n||23===n)&&a.superClass===e},SC=function(e,a,n){switch(n){case 109:case 133:return a.object===e;case 18:case 131:case 113:return a.callee===e;case 220:return a.tag===e;case 189:return!0}return!1};function EC(e){return(e&(vA.expressionStatement|vA.arrowBody))>0}function TC(e,a,n,t){if(xC(e,a,n))return!0;if(SC(e,a,n)||236===n||143===n||8===n)return!0;var r;switch(n){case 11:case 108:r=vC.get(a.operator);break;case 154:case 199:r=7}if(void 0!==r){var i=2===t?7:vC.get(e.operator);if(r>i)return!0;if(r===i&&11===n&&(11===i?a.left===e:a.right===e))return!0;if(1===t&&108===n&&(1===i&&1!==r||1===r&&1!==i))return!0}return!1}function wC(e,a,n){switch(n){case 4:case 116:case 91:case 237:return!0}return!1}function CC(e,a,n){return(6===n||7===n)&&a.left===e||(11===n&&("|"===a.operator||"&"===a.operator)&&e===a.left||TC(e,a,n,2))}function PC(e,a,n){switch(n){case 179:case 209:case 153:case 193:return!0;case 173:return a.objectType===e}return!1}function AC(e,a,n){switch(n){case 153:case 193:return!0;case 173:if(a.objectType===e)return!0}return!1}function _C(e,a,n){return!!PC(e,a,n)||(217===n||159===n&&(a.checkType===e||a.extendsType===e))}function DC(e,a,n){return 11===n||108===n||236===n||143===n||SC(e,a,n)||8===n&&RC(e)||29===n&&e===a.test||xC(e,a,n)||bC(n)}function kC(e,a,n){return SC(e,a,n)||11===n&&"**"===a.operator&&a.left===e||xC(e,a,n)}function IC(e,a,n){switch(n){case 236:case 143:case 11:case 108:case 8:return!0;case 29:if(a.test===e)return!0}return!!bC(n)||kC(e,a,n)}function BC(e,a,n){switch(n){case 18:return a.callee===e;case 109:return a.object===e}return!1}var NC=Object.freeze({__proto__:null,ArrowFunctionExpression:IC,AssignmentExpression:function(e,a,n,t){return!(!EC(t)||"ObjectPattern"!==e.left.type)||IC(e,a,n)},AwaitExpression:DC,BinaryExpression:function(e,a,n,t){return!!TC(e,a,n,0)||(t&vA.forInOrInitHeadAccumulate)>0&&"in"===e.operator},ClassExpression:function(e,a,n,t){return(t&(vA.expressionStatement|vA.exportDefault))>0},ConditionalExpression:IC,DoExpression:function(e,a,n,t){return(t&vA.expressionStatement)>0&&!e.async},FunctionExpression:function(e,a,n,t){return(t&(vA.expressionStatement|vA.exportDefault))>0},FunctionTypeAnnotation:function(e,a,n,t){return 237===n||91===n||4===n||(t&vA.arrowFlowReturnType)>0},Identifier:function(e,a,n,t,r){var i;if(r&&r(e)!==e.name)return!1;if(6===n&&null!=(i=e.extra)&&i.parenthesized&&a.left===e){var o=a.right.type;if(("FunctionExpression"===o||"ClassExpression"===o)&&null==a.right.id)return!0}return(t&vA.forOfHead||(109===n||133===n)&&t&(vA.expressionStatement|vA.forInitHead|vA.forInHead))&&"let"===e.name?!!((hC(a,{object:e,computed:!0})||mC(a,{object:e,computed:!0,optional:!1}))&&t&(vA.expressionStatement|vA.forInitHead|vA.forInHead))||(t&vA.forOfHead)>0:69===n&&a.left===e&&"async"===e.name&&!a.await},IntersectionTypeAnnotation:wC,LogicalExpression:function(e,a,n){return TC(e,a,n,1)},NullableTypeAnnotation:function(e,a,n){return 4===n},ObjectExpression:function(e,a,n,t){return EC(t)},OptionalCallExpression:BC,OptionalIndexedAccessType:function(e,a,n){return 85===n&&a.objectType===e},OptionalMemberExpression:BC,SequenceExpression:function(e,a,n){return!(142===n||134===n||109===n&&a.property===e||133===n&&a.property===e||222===n)&&(22===n||(69===n?a.right===e:61===n||!yC(a)))},SpreadElement:kC,TSAsExpression:CC,TSConditionalType:function(e,a,n){switch(n){case 153:case 193:case 209:case 210:case 179:case 217:return!0;case 173:return a.objectType===e;case 159:return a.checkType===e||a.extendsType===e}return!1},TSConstructorType:_C,TSFunctionType:_C,TSInferType:function(e,a,n){return!!AC(e,a,n)||(179===n||217===n)&&null!=e.typeParameter.constraint},TSInstantiationExpression:function(e,a,n){switch(n){case 18:case 131:case 113:case 175:return null!=a.typeArguments}return!1},TSIntersectionType:function(e,a,n){return 209===n||AC(e,a,n)},TSSatisfiesExpression:CC,TSTypeAssertion:kC,TSTypeOperator:AC,TSUnionType:PC,UnaryExpression:kC,UnionTypeAnnotation:wC,UpdateExpression:function(e,a,n){return SC(e,a,n)||xC(e,a,n)},YieldExpression:DC});function jC(e,a){for(var n=e.quasis,t="`",r=0;r");return null==(null==r?void 0:r.loc)||r.loc.start.line!==e.loc.start.line}return!!this.format.retainLines}function oP(e){var a;return!(null==(a=e.loc)||!a.identifierName)&&e.loc.identifierName!==e.name}function sP(e,a){var n,t=e;if(!t&&a){var r=a.type;"VariableDeclarator"===r?t=a.id:"AssignmentExpression"===r||"AssignmentPattern"===r?t=a.left:"ObjectProperty"===r||"ClassProperty"===r?a.computed&&"StringLiteral"!==a.key.type||(t=a.key):"ClassPrivateProperty"!==r&&"ClassAccessorProperty"!==r||(t=a.key)}if(null!=(n=t)&&n.loc){var i;if("Identifier"===t.type){if(!oP(t))return;i={pos:t.loc.start,name:t.loc.identifierName}}else if("PrivateName"===t.type){if(!oP(t.id))return;i={pos:t.loc.start,name:"#"+t.id.loc.identifierName}}else"StringLiteral"===t.type&&(i={pos:t.loc.start,name:t.value});return i}}function dP(e,a){var n=this;this.tokenChar(60);var t="ArrowFunctionExpression"===a.type&&1===e.params.length;this.tokenMap&&null!=e.start&&null!=e.end&&(t&&(t=!!this.tokenMap.find(e,function(e){return n.tokenMap.matchesOriginal(e,",")})),t||(t=this.shouldPrintTrailingComma(">"))),this.printList(e.params,t),this.tokenChar(62)}function uP(e,a){e.tokenMap&&a.start&&a.end?e.tokenMap.endMatches(a,",")?e.token(","):e.tokenMap.endMatches(a,";")&&e.semicolon():e.semicolon()}function cP(e){e.computed&&this.tokenChar(91),this.print(e.key),e.computed&&this.tokenChar(93),e.optional&&this.tokenChar(63)}function lP(e){var a=e.typeParameters,n=e.params;this.print(a),this.tokenChar(40),ZC.call(this,n,41),this.space();var t=e.returnType;this.print(t)}function pP(e,a,n){var t,r=0;null!=(t=e.tokenMap)&&t.startMatches(a,n)&&(r=1,e.token(n)),e.printJoin(a.types,void 0,void 0,function(e){this.space(),this.token(n,void 0,e+r),this.space()})}function gP(e,a){!0!==a&&e.token(a)}function fP(e){this.print(e.expression),this.print(e.typeArguments)}function hP(e){var a=e.typeParameters,n=e.params;this.print(a),this.tokenChar(40),ZC.call(this,n,41),this.print(e.returnType)}function mP(e){var a="ClassPrivateProperty"===e.type,n="ClassAccessorProperty"===e.type||"ClassProperty"===e.type;yP(this,e,[n&&e.declare&&"declare",!a&&e.accessibility]),e.static&&(this.word("static"),this.space()),yP(this,e,[!a&&e.abstract&&"abstract",!a&&e.override&&"override",(n||a)&&e.readonly&&"readonly"])}function RP(e,a,n){e.token("{");var t=e.enterDelimited();n(),e._noLineTerminatorAfterNode=t,e.rightBrace(a)}function yP(e,a,n){for(var t,r,i=new Set,s=o(n);!(r=s()).done;){var d=r.value;d&&i.add(d)}null==(t=e.tokenMap)||t.find(a,function(a){return!!i.has(a.value)&&(e.token(a.value),e.space(),i.delete(a.value),0===i.size)});for(var u,c=o(i);!(u=c()).done;){var l=u.value;e.word(l),e.space()}}var vP=le,bP=la,xP=Ie,SP=ye,EP=ve,TP=Da;function wP(e,a){var n=e.attributes;this.word("with"),this.space();var t=a?1:0;this.token("{",void 0,t),this.space(),this.printList(n,this.shouldPrintTrailingComma("}")),this.space(),this.token("}",void 0,t)}function CP(e){var a;this.word("export"),this.space(),"type"===e.exportKind&&(this.word("type"),this.space()),this.tokenChar(42),this.space(),this.word("from"),this.space(),null!=(a=e.attributes)&&a.length?(this.print(e.source,!0),this.space(),wP.call(this,e,!1)):this.print(e.source),this.semicolon()}function PP(e,a){vP(a.declaration)&&WC.call(e,a)&&e.printJoin(a.declaration.decorators)}var AP,_P,DP="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function kP(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var a=e.default;if("function"==typeof a){var n=function e(){var n=!1;try{n=this instanceof e}catch(e){}return n?Reflect.construct(a,arguments,this.constructor):a.apply(this,arguments)};n.prototype=a.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(a){var t=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(n,a,t.get?t:{enumerable:!0,get:function(){return e[a]}})}),n}var IP=function(){if(_P)return AP;_P=1;var e={},a=e.hasOwnProperty,n=function(e,n){for(var t in e)a.call(e,t)&&n(t,e[t])},t=function(e){return"\\u"+("0000"+e).slice(-4)},r=function(e,a){var n=e.toString(16);return a?n:n.toUpperCase()},i=e.toString,o=Array.isArray,s=function(e){return"bigint"==typeof e},d={"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t"},u=/[\\\b\f\n\r\t]/,c=/[0-9]/,l=/[\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/,p=/([\uD800-\uDBFF][\uDC00-\uDFFF])|([\uD800-\uDFFF])|(['"`])|[^]/g,g=/([\uD800-\uDBFF][\uDC00-\uDFFF])|([\uD800-\uDFFF])|(['"`])|[^ !#-&\(-\[\]-_a-~]/g,f=function(e,a){var h,m,R=function(){w=T,++a.indentLevel,T=a.indent.repeat(a.indentLevel)},y={escapeEverything:!1,minimal:!1,isScriptContext:!1,quotes:"single",wrap:!1,es6:!1,json:!1,compact:!0,lowercaseHex:!1,numbers:"decimal",indent:"\t",indentLevel:0,__inline1__:!1,__inline2__:!1},v=a&&a.json;v&&(y.quotes="double",y.wrap=!0),h=y,a=(m=a)?(n(m,function(e,a){h[e]=a}),h):h,"single"!=a.quotes&&"double"!=a.quotes&&"backtick"!=a.quotes&&(a.quotes="single");var b,x="double"==a.quotes?'"':"backtick"==a.quotes?"`":"'",S=a.compact,E=a.lowercaseHex,T=a.indent.repeat(a.indentLevel),w="",C=a.__inline1__,P=a.__inline2__,A=S?"":"\n",_=!0,D="binary"==a.numbers,k="octal"==a.numbers,I="decimal"==a.numbers,B="hexadecimal"==a.numbers;if(v&&e&&function(e){return"function"==typeof e}(e.toJSON)&&(e=e.toJSON()),!function(e){return"string"==typeof e||"[object String]"==i.call(e)}(e)){if(function(e){return"[object Map]"==i.call(e)}(e))return 0==e.size?"new Map()":(S||(a.__inline1__=!0,a.__inline2__=!1),"new Map("+f(Array.from(e),a)+")");if(function(e){return"[object Set]"==i.call(e)}(e))return 0==e.size?"new Set()":"new Set("+f(Array.from(e),a)+")";if(function(e){return bT.isBuffer(e)}(e))return 0==e.length?"Buffer.from([])":"Buffer.from("+f(Array.from(e),a)+")";if(o(e))return b=[],a.wrap=!0,C&&(a.__inline1__=!1,a.__inline2__=!0),P||R(),function(e,a){for(var n=e.length,t=-1;++t2?t(h):"\\x"+("00"+h).slice(-2)}),"`"==x&&(b=b.replace(/\$\{/g,"\\${")),a.isScriptContext&&(b=b.replace(/<\/(script|style)/gi,"<\\/$1").replace(/