diff --git a/.gitattributes b/.gitattributes index c8a987df..4f90624d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,6 +1,3 @@ -# Normalise line endings to LF in the working tree on every platform. The repo's -# Biome config enforces `lineEnding: lf`, so a Windows checkout (where Git would -# otherwise apply core.autocrlf and produce CRLF) must keep LF — both for the -# Windows CI `biome format` check and to silence the "LF will be replaced by CRLF" -# warnings. Binary files are auto-detected by `text=auto` and left untouched. +# LF everywhere: Biome enforces `lineEnding: lf`, so a CRLF Windows checkout fails +# `biome format` on the Windows CI leg. `text=auto` leaves binaries untouched. * text=auto eol=lf diff --git a/.githooks/pre-commit b/.githooks/pre-commit index 313fa2a9..207f6f02 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -1,9 +1,6 @@ #!/bin/sh -# Auto-format staged files with Biome before they are committed, so no un-run -# formatting ever lands in a commit. Covers the core package and website/src -# (both are in the root biome.json). `--staged` limits Biome to staged files; -# `--write` applies formatting. Linting/type-check/tests stay in `validate` — -# this hook only formats, and never blocks a commit on lint findings. +# Format staged files with Biome before they are committed; lint, type-check and +# tests stay in `validate`, so this hook never blocks a commit. # # Enable once per clone: git config core.hooksPath .githooks # (or run `bun run setup:hooks`). See .admin/CONTRIBUTING.md. @@ -13,14 +10,21 @@ if ! command -v bun >/dev/null 2>&1; then exit 0 fi -# Format the staged, Biome-supported files in place. +# Re-adding a file that also has unstaged edits would commit those edits. +partial=$(git diff --name-only) + bunx biome format --write --staged >/dev/null 2>&1 || true -# Re-stage anything Biome reformatted (only files that were already staged). -git diff --cached --name-only --diff-filter=ACM | while IFS= read -r file; do +git diff --cached --name-only --diff-filter=ACMR | while IFS= read -r file; do case "$file" in - *.ts | *.tsx | *.js | *.jsx | *.mjs | *.json | *.css) git add "$file" ;; + *.ts | *.tsx | *.js | *.jsx | *.mjs | *.json | *.css) ;; + *) continue ;; esac + if printf '%s\n' "$partial" | grep -qxF -- "$file"; then + echo "pre-commit: $file is partly staged; formatted in the working tree only" >&2 + else + git add -- "$file" + fi done exit 0 diff --git a/.github/workflows/build-engine-windows.yml b/.github/workflows/build-engine-windows.yml index 008f749f..69c733cf 100644 --- a/.github/workflows/build-engine-windows.yml +++ b/.github/workflows/build-engine-windows.yml @@ -1,14 +1,14 @@ name: build-engine-windows # Builds OUR OWN WinCairo WebKit engine FROM SOURCE on a Windows runner, relocates -# it into the Bunmaska engine-store layout, and proves it loads from the store — +# it into the Bunmaska engine-store layout, and proves it loads from the store - # the Windows peer of `build-engine.yml` (which relocates apt's WebKitGTK on Linux). # Windows has no system WebKit and we never ship Playwright's build, so the engine # is our own from-source binary. # # This recipe mirrors the one proven locally end-to-end (a real BrowserWindow loaded # the from-source engine from the store: STORE_ENGINE_OK). Notes baked in from that: -# * WinCairo dropped MSVC — it builds with clang-cl, so we install LLVM 20. +# * WinCairo dropped MSVC - it builds with clang-cl, so we install LLVM 20. # * WebKit's code-gen needs gperf on PATH. # * A short WEBKIT_OUTPUTDIR avoids Windows' 250-char object-path limit in vcpkg. # * patch-webkit-wincairo.py routes ~300 serializer inputs through a response file @@ -16,6 +16,10 @@ name: build-engine-windows # * `ninja -k 0` finishes past a broken dev-tooling target (compile_commands.json) # that no product DLL depends on; success = WebKit2.dll exists. # +# The release signing key (D042) never enters `build`: hours of third-party inputs +# (choco, LLVM, vcpkg, WebKit's scripts) run there and could exfiltrate it. `publish` +# signs the uploaded artifact from a fresh checkout, behind the engine-release environment. +# # Heavy (~hours, GBs): runs on demand / on the engine branch only. on: workflow_dispatch: @@ -24,6 +28,10 @@ on: description: 'WebKit git tag to build (STABLE train only - even minor, e.g. wpewebkit-2.52.5)' required: true default: 'wpewebkit-2.52.5' + rev: + description: 'Build revision; bump it to rebuild a tag (a published engine id never changes)' + required: false + default: 'bunmaska1' llvm: description: 'LLVM version for clang-cl (older WebKit trains may need an older clang)' required: false @@ -31,6 +39,9 @@ on: push: branches: [feat/windows-engine] +permissions: + contents: read + jobs: build: name: build WinCairo from source (windows) @@ -39,28 +50,40 @@ jobs: # whole pipeline was proven end-to-end on (2026-07). runs-on: windows-2022 timeout-minutes: 350 + outputs: + engine_id: ${{ steps.id.outputs.engine_id }} env: # Hosted engines track the STABLE WPE train only (even minor; WSAs land # there). Development tags (odd minor) are for local experiments, never # the feed. WEBKIT_TAG: ${{ github.event.inputs.webkit_tag || 'wpewebkit-2.52.5' }} + ENGINE_REV: ${{ github.event.inputs.rev || 'bunmaska1' }} # Short build-output root (WebKit honours WEBKIT_OUTPUTDIR): vcpkg's ICU build # generates pathologically deep try-compile object paths that blow past # Windows' 250-char limit when nested under the workspace. WEBKIT_OUTPUTDIR: C:\wkb LLVM_VER: ${{ github.event.inputs.llvm || '20.1.8' }} LLVM_DIR: C:\llvm\clang+llvm-${{ github.event.inputs.llvm || '20.1.8' }}-x86_64-pc-windows-msvc - # Publish steps are gated on these so forks / unconfigured runs still build - # + prove the engine, skipping pack/sign/upload when the secrets are absent. - HAVE_KEY: ${{ secrets.ENGINE_SIGNING_KEY != '' }} - # R2_PUBLISH_TOKEN is R2-only, separate from the Pages-scoped - # CLOUDFLARE_API_TOKEN deploy-web.yml uses (which has no R2 perms). - HAVE_R2: ${{ secrets.R2_PUBLISH_TOKEN != '' && secrets.CLOUDFLARE_ACCOUNT_ID != '' }} steps: - name: Checkout bunmaska uses: actions/checkout@v4 with: path: bunmaska + persist-credentials: false + + # Fail in seconds, not after the multi-hour build. + - name: Compute and validate the engine id + id: id + run: | + $ver = "$env:WEBKIT_TAG" -replace '^(wpe|webkit)webkit-?|^webkitgtk-', '' + if ($ver -notmatch '^\d+\.(\d+)\.\d+$' -or [int]$Matches[1] % 2 -ne 0) { + Write-Error "$env:WEBKIT_TAG is not a stable (even-minor) x.y.z WebKit release"; exit 1 + } + if ($env:ENGINE_REV -notmatch '^bunmaska\d+$') { + Write-Error "rev must look like bunmaska, got $env:ENGINE_REV"; exit 1 + } + "engine_id=webkit-2-$ver-$env:ENGINE_REV-windows-x64" >> $env:GITHUB_OUTPUT + shell: pwsh # Clone WebKit to a SHORT path (C:\WebKit) at the pinned tag; shallow (history # is enormous, the build only needs the tree at that revision). @@ -134,13 +157,6 @@ jobs: } shell: pwsh - - name: Compute the engine id from the tag - id: id - run: | - $ver = "$env:WEBKIT_TAG" -replace '^(wpe|webkit)webkit-?|^webkitgtk-', '' - "engine_id=webkit-2-$ver-bunmaska1-windows-x64" >> $env:GITHUB_OUTPUT - shell: pwsh - # Relocate the from-source closure (Release/bin) into the store, mark installed. - name: Relocate into the engine store run: | @@ -180,9 +196,42 @@ jobs: path: ${{ runner.temp }}\store\${{ steps.id.outputs.engine_id }} retention-days: 7 - # Pack + sign the engine into the 3-file feed layout, then publish to R2. - # Gated on the signing key being present, so forks / unconfigured runs still - # build + prove the engine without needing the release secret. + publish: + name: pack, sign and publish the engine + needs: build + runs-on: windows-2022 + timeout-minutes: 30 + # Configure required reviewers on this environment: it gates every use of the key. + environment: engine-release + # A publish read-modify-writes index.json; two at once would drop an engine. + concurrency: + group: engine-publish + cancel-in-progress: false + env: + ENGINE_ID: ${{ needs.build.outputs.engine_id }} + # Forks / unconfigured runs skip pack/sign/upload when the secrets are absent. + HAVE_KEY: ${{ secrets.ENGINE_SIGNING_KEY != '' }} + # R2_PUBLISH_TOKEN is R2-only, separate from the Pages-scoped + # CLOUDFLARE_API_TOKEN deploy-web.yml uses (which has no R2 perms). + HAVE_R2: ${{ secrets.R2_PUBLISH_TOKEN != '' && secrets.CLOUDFLARE_ACCOUNT_ID != '' }} + # Pinned by SHA and no `bun install`: nothing mutable runs beside the key. + steps: + - name: Checkout bunmaska + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + path: bunmaska + persist-credentials: false + + - name: Download the engine artifact + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ env.ENGINE_ID }} + path: ${{ runner.temp }}\store\${{ env.ENGINE_ID }} + + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version-file: bunmaska/.bun-version + - name: Pack + sign the engine for the feed if: ${{ env.HAVE_KEY == 'true' }} working-directory: bunmaska @@ -191,9 +240,7 @@ jobs: run: | $key = "$env:RUNNER_TEMP\engine-signing-key.pem" Set-Content -Path $key -Value $env:ENGINE_SIGNING_KEY -NoNewline - bun tools/engine/pack-engine.ts ` - "$env:RUNNER_TEMP\store\${{ steps.id.outputs.engine_id }}" ` - "$env:RUNNER_TEMP\feed" $key + bun tools/engine/pack-engine.ts "$env:RUNNER_TEMP\store\$env:ENGINE_ID" "$env:RUNNER_TEMP\feed" $key Remove-Item $key -Force shell: pwsh @@ -204,6 +251,5 @@ jobs: CLOUDFLARE_API_TOKEN: ${{ secrets.R2_PUBLISH_TOKEN }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} run: | - bun tools/engine/publish-engine-r2.ts ` - "$env:RUNNER_TEMP\feed" "${{ steps.id.outputs.engine_id }}" --bucket bunmaska-engines + bun tools/engine/publish-engine-r2.ts "$env:RUNNER_TEMP\feed" "$env:ENGINE_ID" --bucket bunmaska-engines shell: pwsh diff --git a/.github/workflows/build-engine.yml b/.github/workflows/build-engine.yml index e2bf520c..67b37e43 100644 --- a/.github/workflows/build-engine.yml +++ b/.github/workflows/build-engine.yml @@ -3,11 +3,9 @@ name: build-engine # Builds a relocatable WebKitGTK engine from the runner's apt WebKitGTK and # proves it loads from the store with its dependency closure resolved via the # engine's own $ORIGIN rpaths. This is the start of the hosted-engine pipeline; -# it runs on demand and on the engine branch, not on every push. +# it runs on demand, not on every push. on: workflow_dispatch: - push: - branches: [feat/relocatable-engine] jobs: build: @@ -23,7 +21,7 @@ jobs: - uses: oven-sh/setup-bun@v2 with: - bun-version: latest + bun-version-file: .bun-version - run: bun install --frozen-lockfile @@ -31,7 +29,16 @@ jobs: run: | chmod +x tools/engine/build-webkitgtk-linux.sh WK_VER=$(dpkg-query -W -f='${Version}' libwebkitgtk-6.0-4 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1) - ENGINE_ID="webkitgtk-6.0-${WK_VER:-0.0.0}-built1-linux-x64" + if [ -z "$WK_VER" ]; then + echo "could not read the libwebkitgtk-6.0-4 version" + exit 1 + fi + case "$(uname -m)" in + x86_64) ARCH=x64 ;; + aarch64) ARCH=arm64 ;; + *) echo "unsupported arch $(uname -m)"; exit 1 ;; + esac + ENGINE_ID="webkitgtk-6.0-${WK_VER}-built1-linux-${ARCH}" echo "ENGINE_ID=$ENGINE_ID" >> "$GITHUB_ENV" echo "Building engine id: $ENGINE_ID" mkdir -p "$RUNNER_TEMP/store" diff --git a/.github/workflows/deploy-web.yml b/.github/workflows/deploy-web.yml index 6d180717..3ac4b984 100644 --- a/.github/workflows/deploy-web.yml +++ b/.github/workflows/deploy-web.yml @@ -1,15 +1,22 @@ name: deploy-web -# Builds website/ and deploys it to Cloudflare Pages (project "bunmaska", -# which serves bunmaska.org) on pushes that touch the site. Repo secrets: -# CLOUDFLARE_API_TOKEN — scoped token (Pages Edit + DNS Edit + Zone Read) -# CLOUDFLARE_ACCOUNT_ID — 33b4bb12637807398ca2edac6c77fe8c +# Checks website/ on pull requests; on main also deploys it to Cloudflare Pages +# (project "bunmaska") and pings IndexNow. Secrets: CLOUDFLARE_API_TOKEN, CLOUDFLARE_ACCOUNT_ID. on: push: branches: [main] - paths: ['website/**', '.github/workflows/deploy-web.yml'] + # package.json carries the version the site shows. + paths: ['website/**', 'package.json', '.github/workflows/deploy-web.yml'] + pull_request: + branches: [main] + paths: ['website/**', 'package.json', '.github/workflows/deploy-web.yml'] workflow_dispatch: +# Queue instead of racing, so two quick pushes deploy in push order. +concurrency: + group: deploy-web-${{ github.ref }} + cancel-in-progress: false + permissions: contents: read @@ -20,21 +27,19 @@ jobs: run: working-directory: website steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: # The IndexNow step diffs against the previous push; a shallow clone # would silently see no changes on a multi-commit push. fetch-depth: 0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 with: bun-version-file: .bun-version - name: Install run: bun install --frozen-lockfile - # The site is held to the same bar as the framework: biome (ts/tsx) + - # `astro check` (strict tsconfig over every .astro/.ts) gate the deploy. - name: Install framework dev tools (biome) run: bun install --frozen-lockfile working-directory: . @@ -52,20 +57,19 @@ jobs: GITHUB_TOKEN: ${{ github.token }} run: bun run build - # Run wrangler via bunx (the wrangler-action's npm install is flaky on Bun). - # wrangler reads the token + account id from the env below. + # Run wrangler via bunx (the wrangler-action's npm install is flaky on Bun), + # pinned exactly because the deploy token is in its env. - name: Deploy to Cloudflare Pages + if: github.event_name != 'pull_request' env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - run: bunx wrangler@4 pages deploy dist --project-name=bunmaska --branch=main + run: bunx wrangler@4.143.0 pages deploy dist --project-name=bunmaska --branch=main - # IndexNow: tell Bing (and Yandex, Naver, Seznam, Amazon, and the AI - # surfaces riding Bing's index) which pages changed. Google does not - # participate; the sitemap covers it. Only URLs whose source changed are - # sent; pushing the whole sitemap on every deploy is the protocol's - # documented anti-pattern. Key file lives in public/. + # Only URLs whose source changed: pinging the whole sitemap on every deploy + # is IndexNow's documented anti-pattern. The key file lives in public/. - name: Ping IndexNow with the URLs whose source changed + if: github.event_name != 'pull_request' env: BEFORE: ${{ github.event.before }} run: | diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index b3b622b0..1c843aef 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -3,10 +3,10 @@ name: validate on: push: branches: [main] - paths: ['src/**', 'tests/**', 'tools/**', 'examples/**', 'biome.json', 'bunfig.toml', 'tsconfig.json', 'tsconfig.base.json', 'package.json', 'bun.lock', '.bun-version', '.github/workflows/validate.yml'] + paths: ['src/**', 'tests/**', 'tools/**', 'examples/**', 'scripts/**', '.githooks/**', '.gitattributes', 'biome.json', 'bunfig.toml', 'tsconfig.json', 'tsconfig.base.json', 'package.json', 'bun.lock', '.bun-version', '.github/workflows/validate.yml'] pull_request: branches: [main] - paths: ['src/**', 'tests/**', 'tools/**', 'examples/**', 'biome.json', 'bunfig.toml', 'tsconfig.json', 'tsconfig.base.json', 'package.json', 'bun.lock', '.bun-version', '.github/workflows/validate.yml'] + paths: ['src/**', 'tests/**', 'tools/**', 'examples/**', 'scripts/**', '.githooks/**', '.gitattributes', 'biome.json', 'bunfig.toml', 'tsconfig.json', 'tsconfig.base.json', 'package.json', 'bun.lock', '.bun-version', '.github/workflows/validate.yml'] concurrency: group: validate-${{ github.ref }} @@ -26,11 +26,11 @@ jobs: steps: - uses: actions/checkout@v4 - - name: Install Linux native deps (GTK 4 + WebKitGTK 6.0 + libnotify + libsecret + Xvfb) + - name: Install Linux native deps (GTK 4 + WebKitGTK 6.0 + libnotify + libsecret + XTest + Xvfb) if: runner.os == 'Linux' run: | sudo apt-get update - sudo apt-get install -y libgtk-4-1 libwebkitgtk-6.0-4 libnotify4 libsecret-1-0 xvfb + sudo apt-get install -y libgtk-4-1 libwebkitgtk-6.0-4 libnotify4 libsecret-1-0 libxtst6 xvfb - uses: oven-sh/setup-bun@v2 with: @@ -41,7 +41,7 @@ jobs: # WebKitGTK's bubblewrap sandbox and GPU acceleration are unavailable on # the headless runner; disable them so the GTK/WebKitGTK tests can run. - - name: Validate (Linux — under Xvfb for GTK tests) + - name: Validate (Linux - under Xvfb for GTK tests) if: runner.os == 'Linux' env: WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS: "1" @@ -54,12 +54,8 @@ jobs: if: runner.os == 'macOS' run: bun run validate - # Windows runs a SCOPED validation: format + lint + type-check (all - # platform-agnostic) plus the Windows backend tests, which pass on a real - # windows-latest runner (engine-gated WebKit tests skip without - # BUNMASKA_WEBKIT_PATH). The full cross-platform suite is not yet - # POSIX/Windows path-portable; running it on Windows is a separate - # test-hardening follow-up (see .admin/WINDOWS.md). - - name: Validate (Windows — backend tests + lint + type-check) + # Scoped to the Windows tests under their own budget leg: the full suite is + # not path-portable to Windows. No engine is provisioned, so engine-gated tests skip. + - name: Validate (Windows - backend tests + lint + type-check) if: runner.os == 'Windows' run: bun run validate:windows diff --git a/.github/workflows/watch-webkit.yml b/.github/workflows/watch-webkit.yml index 31cb1fe3..014f53f2 100644 --- a/.github/workflows/watch-webkit.yml +++ b/.github/workflows/watch-webkit.yml @@ -1,13 +1,8 @@ name: watch-webkit -# Weekly upstream watch: compare the newest STABLE WPE WebKit tag against the -# engines the live feed serves, and open an issue when a newer engine should be -# built. Policy: hosted engines track the STABLE train only (even minor — -# 2.52.x; odd minors are development and security advisories land on stable), -# so development tags are filtered out here. The issue is the tracking record; -# building stays a human call (dispatch build-engine-windows.yml with the new -# tag — pack/sign/publish then run unattended off the repo secrets). Skips if -# an engine-update issue is already open, so it never stacks duplicates. +# Weekly: open an engine-update issue when upstream has a newer STABLE WPE WebKit than +# the feed serves. Hosted engines track the stable train only (even minor, e.g. 2.52.x: +# odd minors are development, and security advisories land on stable). on: schedule: - cron: '0 6 * * 1' # Mondays 06:00 UTC @@ -24,13 +19,21 @@ jobs: env: GH_TOKEN: ${{ github.token }} run: | + set -o pipefail latest_tag=$(git ls-remote --tags https://github.com/WebKit/WebKit.git 'wpewebkit-*' \ | awk -F/ '{print $3}' | grep -E '^wpewebkit-[0-9]+\.[0-9]+\.[0-9]+$' \ | awk -F'[-.]' '$3 % 2 == 0' | sort -V | tail -1) latest="${latest_tag#wpewebkit-}" - served=$(curl -sf https://engines.bunmaska.org/index.json \ - | jq -r '.engines[].id' | cut -d- -f3 | sort -V | tail -1) - echo "upstream latest: $latest / feed serves: $served" + # Only stable Windows WebKit ids count: a dev (odd-minor), other-OS or + # other-family id must never mask a stable update. + served=$(curl -sf https://engines.bunmaska.org/index.json | jq -r '.engines[].id' \ + | awk -F- '$1 == "webkit" && $5 == "windows" { split($3, v, "."); if (v[2] % 2 == 0) print $3 }' \ + | sort -V | tail -1) + if [ -z "$latest" ]; then + echo "found no stable upstream WPE WebKit tag" + exit 1 + fi + echo "upstream latest: $latest / feed serves: ${served:-none}" newest=$(printf '%s\n%s\n' "$served" "$latest" | sort -V | tail -1) if [ "$newest" = "$served" ]; then echo "feed is current" @@ -45,7 +48,7 @@ jobs: gh label create engine-update --repo "$GITHUB_REPOSITORY" \ --description "a newer upstream WebKit is available for the engine feed" \ --color D93F0B 2>/dev/null || true - body=$(printf 'The weekly upstream watch found a newer stable WPE WebKit release.\n\n- Upstream: `%s`\n- Live feed serves: `%s` (https://engines.bunmaska.org/index.json)\n\nTo ship it: dispatch `build-engine-windows.yml` with `webkit_tag=%s`. Pack, sign, publish, and the index refresh all run unattended off the repo secrets. Release policy notes live in the engine hosting runbook (.admin).' "$latest_tag" "$served" "$latest_tag") + body=$(printf 'The weekly upstream watch found a newer stable WPE WebKit release.\n\n- Upstream: `%s`\n- Live feed serves: `%s` (https://engines.bunmaska.org/index.json)\n\nTo ship it: dispatch `build-engine-windows.yml` with `webkit_tag=%s`, then approve its `publish` job (pack, sign, upload and the index refresh). Release policy notes live in the engine hosting runbook (.admin).' "$latest_tag" "${served:-none}" "$latest_tag") gh issue create --repo "$GITHUB_REPOSITORY" \ - --title "engine: upstream WebKit $latest available (feed serves $served)" \ + --title "engine: upstream WebKit $latest available (feed serves ${served:-none})" \ --label engine-update --body "$body" diff --git a/.gitignore b/.gitignore index a64ba86e..fb083e5e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -# Internal — never commit +# Internal - never commit .admin/ # Dependencies diff --git a/README.md b/README.md index f695775d..6fa4766c 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ Full reference, every flag → **[bunmaska.org/docs/cli](https://bunmaska.org/do ## What you get -An Electron-shaped API surface - `app`, `BrowserWindow`, `webContents`, `ipcMain`/`ipcRenderer` with context isolation, `Menu`, `dialog`, `clipboard`, `Tray`, `Notification`, `nativeImage`, `safeStorage`, and more - plus an auto-updater and the engine store, all pure `bun:ffi`. +An Electron-shaped API surface - `app`, `BrowserWindow`, `webContents`, `ipcMain`/`ipcRenderer` with a context bridge, `Menu`, `dialog`, `clipboard`, `Tray`, `Notification`, `nativeImage`, `safeStorage`, and more - plus an auto-updater and the engine store, all pure `bun:ffi`. The README won't try to be the API reference, because that list only grows. The **full module list, per-platform status, and the exact Electron parity matrix** live where they can stay honest: @@ -133,7 +133,7 @@ The docs site lives in [`website/`](./website); the framework is this repo's roo ## Status -**Alpha** - `0.1.0-alpha.8`. It genuinely works on macOS, Linux, and Windows (x64), it's on npm, and everything deeper lives at **[bunmaska.org](https://bunmaska.org)**. If it's still 2027 and this file still opens with "alpha," feel free to open an issue titled *"are you OK."* +**Alpha** - `0.1.0-alpha.9`. It genuinely works on macOS, Linux, and Windows (x64), it's on npm, and everything deeper lives at **[bunmaska.org](https://bunmaska.org)**. If it's still 2027 and this file still opens with "alpha," feel free to open an issue titled *"are you OK."* ## License diff --git a/biome.json b/biome.json index 814a0476..f716a7cd 100644 --- a/biome.json +++ b/biome.json @@ -12,14 +12,10 @@ "examples/**", "tools/**", "scripts/**", - "!website/.astro", - "!website/dist", "website/src/**/*.ts", "website/src/**/*.tsx", "*.json", "*.md", - "!**/dist", - "!**/build", "!**/node_modules", "!**/.admin", "!examples/**/*.html" @@ -74,5 +70,124 @@ "formatter": { "indentWidth": 2 } - } + }, + "overrides": [ + { + "includes": ["src/main/api/**"], + "linter": { + "rules": { + "style": { + "noRestrictedImports": { + "level": "error", + "options": { + "patterns": [ + { + "group": [ + "**/platform/macos/**", + "**/platform/linux/**", + "**/platform/windows/**", + "**/platform/cef/**" + ], + "message": "D024: api/ reaches a backend only through platform/index.ts, native.ts and services.ts." + } + ] + } + } + } + } + } + }, + { + "includes": ["src/main/platform/**"], + "linter": { + "rules": { + "style": { + "noRestrictedImports": { + "level": "error", + "options": { + "patterns": [ + { + "group": ["../api/**", "../../api/**", "**/bootstrap", "**/native-app"], + "message": "D024: platform/ never imports api/; contracts live in platform/services.ts and native.ts." + } + ] + } + } + } + } + } + }, + { + "includes": ["src/main/platform/macos/**"], + "linter": { + "rules": { + "style": { + "noRestrictedImports": { + "level": "error", + "options": { + "patterns": [ + { + "group": ["../api/**", "../../api/**", "**/bootstrap", "**/native-app"], + "message": "D024: platform/ never imports api/; contracts live in platform/services.ts and native.ts." + }, + { + "group": ["**/linux/**", "**/windows/**", "**/cef/**"], + "message": "D024: a backend never imports another backend; share through a platform/ root file." + } + ] + } + } + } + } + } + }, + { + "includes": ["src/main/platform/linux/**"], + "linter": { + "rules": { + "style": { + "noRestrictedImports": { + "level": "error", + "options": { + "patterns": [ + { + "group": ["../api/**", "../../api/**", "**/bootstrap", "**/native-app"], + "message": "D024: platform/ never imports api/; contracts live in platform/services.ts and native.ts." + }, + { + "group": ["**/macos/**", "**/windows/**", "**/cef/**"], + "message": "D024: a backend never imports another backend; share through a platform/ root file." + } + ] + } + } + } + } + } + }, + { + "includes": ["src/main/platform/windows/**"], + "linter": { + "rules": { + "style": { + "noRestrictedImports": { + "level": "error", + "options": { + "patterns": [ + { + "group": ["../api/**", "../../api/**", "**/bootstrap", "**/native-app"], + "message": "D024: platform/ never imports api/; contracts live in platform/services.ts and native.ts." + }, + { + "group": ["**/macos/**", "**/linux/**", "**/cef/**"], + "message": "D024: a backend never imports another backend; share through a platform/ root file." + } + ] + } + } + } + } + } + } + ] } diff --git a/bun.lock b/bun.lock index 925ef198..96f0e3f0 100644 --- a/bun.lock +++ b/bun.lock @@ -6,7 +6,7 @@ "name": "bunmaska", "devDependencies": { "@biomejs/biome": "2.4.15", - "@types/bun": "latest", + "@types/bun": "1.4.2", "typescript": "6.0.3", }, }, diff --git a/bunfig.toml b/bunfig.toml index 3dbc4349..15aa2925 100644 --- a/bunfig.toml +++ b/bunfig.toml @@ -2,11 +2,8 @@ exact = true [test] -# Coverage is off for the default `bun test` (dev speed); `bun test --coverage` -# (the `test:coverage` script) turns it on and honors these excludes. The FFI -# signature tables are dense declarations, not logic, so they only dilute the -# number; test files are excluded so coverage measures src, not the tests. +# Coverage (`test:coverage`) measures src logic: tests and FFI declaration tables excluded. coverageSkipTestFiles = true -# `**/` is required — bun's glob `*` does not cross `/`, so a bare `*-ffi.ts` +# `**/` is required: bun's glob `*` does not cross `/`, so a bare `*-ffi.ts` # would match nothing (every FFI file lives under src/main/platform/*/). coveragePathIgnorePatterns = ["**/*-ffi.ts"] diff --git a/examples/README.md b/examples/README.md index cdf9438a..daeca73c 100644 --- a/examples/README.md +++ b/examples/README.md @@ -11,9 +11,9 @@ root with `bun examples//main.ts`. These examples import Bunmaska via a relative path (`../../src/main`) because they live inside the repo. In your own project you would `import { app, BrowserWindow } -from 'bunmaska'` instead — see `bunmaska init` for a scaffold. +from 'bunmaska'` instead; see `bunmaska init` for a scaffold. > Note on preloads: a preload script runs in the page's isolated world. It is -> bundled before injection, so you can `import` modules — just keep it browser code +> bundled before injection, so you can `import` modules; just keep it browser code > (no Node APIs) and use the injected `contextBridge` and `__bunmaska` globals. See > `ipc-demo/preload.js`. diff --git a/examples/hello-webview/main.ts b/examples/hello-webview/main.ts index dc5f11e7..7dd0a26a 100644 --- a/examples/hello-webview/main.ts +++ b/examples/hello-webview/main.ts @@ -1,12 +1,4 @@ -/** - * Bunmaska "hello, webview" — the smallest real app. - * - * Run from the repo root with: bun examples/hello-webview/main.ts - * - * Opens a native window with an embedded system WebKit view and loads a page. - * The cooperative run-loop pump keeps the process alive, so the window stays - * open until you quit (Cmd-Q / Ctrl-C). - */ +/** The smallest real app. Run from the repo root: bun examples/hello-webview/main.ts */ import { app, BrowserWindow } from '../../src/main'; app.whenReady().then(() => { diff --git a/examples/ipc-demo/main.ts b/examples/ipc-demo/main.ts index 33016154..0d80159e 100644 --- a/examples/ipc-demo/main.ts +++ b/examples/ipc-demo/main.ts @@ -1,12 +1,4 @@ -/** - * Bunmaska "IPC demo" — contextBridge + ipcMain.handle end-to-end. - * - * Run from the repo root with: bun examples/ipc-demo/main.ts - * - * The isolated preload exposes a typed `window.api` to the page; clicking the - * button invokes `ipcMain.handle('ping')` in the main process and shows the - * reply. This is the canonical secure IPC pattern (contextIsolation on). - */ +/** Secure IPC end to end. Run from the repo root: bun examples/ipc-demo/main.ts */ import { join } from 'node:path'; import { app, BrowserWindow, ipcMain } from '../../src/main'; diff --git a/examples/ipc-demo/preload.js b/examples/ipc-demo/preload.js index 1b7385a6..c7db5488 100644 --- a/examples/ipc-demo/preload.js +++ b/examples/ipc-demo/preload.js @@ -1,8 +1,6 @@ -// Runs in Bunmaska's isolated preload world (Electron contextIsolation). It is -// bundled before injection, so you can import modules — keep it browser code -// (no Node APIs). Two globals are available here: -// contextBridge.exposeInMainWorld(key, api) — expose a safe surface to the page -// __bunmaska.invoke(channel, ...args) — call an ipcMain.handle handler +// Runs in the isolated preload world, where two globals are injected: +// contextBridge.exposeInMainWorld(key, api): expose a safe surface to the page +// __bunmaska.invoke(channel, ...args): call an ipcMain.handle handler contextBridge.exposeInMainWorld('api', { ping: (message) => __bunmaska.invoke('ping', message), }); diff --git a/examples/window-controls/main.ts b/examples/window-controls/main.ts index 0afd0a42..f43bd293 100644 --- a/examples/window-controls/main.ts +++ b/examples/window-controls/main.ts @@ -1,11 +1,4 @@ -/** - * Bunmaska "window controls" — exercising BrowserWindow's runtime setters. - * - * Run from the repo root with: bun examples/window-controls/main.ts - * - * Opens a window, then drives resizable / opacity / minimum-size / center and - * reads them back. Demonstrates the API a settings or tool window needs. - */ +/** BrowserWindow's runtime setters. Run from the repo root: bun examples/window-controls/main.ts */ import { app, BrowserWindow } from '../../src/main'; app.whenReady().then(() => { diff --git a/package.json b/package.json index f6769143..aca6082d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "bunmaska", - "version": "0.1.0-alpha.8", + "version": "0.1.0-alpha.9", "description": "Electron minus Chromium, powered by Bun and WebKit: a drop-in Electron replacement and lightweight Electron alternative. Same APIs, no bundled Chromium, 23MB downloads, native modules that are just .ts files.", "keywords": [ "electron", @@ -43,23 +43,23 @@ "exports": { ".": { "types": "./src/index.ts", - "import": "./src/index.ts" + "default": "./src/index.ts" }, "./main": { "types": "./src/main/index.ts", - "import": "./src/main/index.ts" + "default": "./src/main/index.ts" }, "./renderer": { "types": "./src/renderer/index.ts", - "import": "./src/renderer/index.ts" + "default": "./src/renderer/index.ts" }, "./config": { "types": "./src/config.ts", - "import": "./src/config.ts" + "default": "./src/config.ts" }, "./electron": { "types": "./src/electron.ts", - "import": "./src/electron.ts" + "default": "./src/electron.ts" } }, "files": [ @@ -90,7 +90,7 @@ "test:coverage": "bun test --timeout 30000 --coverage", "test:coverage:lcov": "bun test --timeout 30000 --coverage --coverage-reporter=lcov --coverage-reporter=text", "validate": "bun run format:check && bun run lint && bun run type-check && bun run test:budget", - "validate:windows": "bun run format:check && bun run lint && bun run type-check && bun test tests/unit/main/platform/windows tests/integration/windows --timeout 60000", + "validate:windows": "bun run format:check && bun run lint && bun run type-check && bun scripts/check-test-budget.ts windows-scoped", "pack:check": "npm pack --dry-run", "prepublishOnly": "bun run validate", "setup:hooks": "git config core.hooksPath .githooks", @@ -98,7 +98,7 @@ }, "devDependencies": { "@biomejs/biome": "2.4.15", - "@types/bun": "latest", + "@types/bun": "1.4.2", "typescript": "6.0.3" } } diff --git a/scripts/check-test-budget.ts b/scripts/check-test-budget.ts index 9852b6e2..d8675e09 100644 --- a/scripts/check-test-budget.ts +++ b/scripts/check-test-budget.ts @@ -1,72 +1,99 @@ /** - * Runs the test suite once and gates on its shape, so a suite that SILENTLY stops - * registering (a broken `hasEngine` probe, a wrong `currentPlatform()` guard, a - * module-level `if` that drops to zero tests) fails CI instead of passing green. - * - * It asserts, per OS: zero failures, at least `minPass` passing tests (a big drop - * means a whole suite vanished), and no more than `maxSkip` skips (a jump means a - * suite that should run got gated off). Bounds are deliberately generous for now — - * they catch a catastrophic regression without false-failing normal per-OS - * variation; ratchet them tighter as each leg's real numbers settle. - * - * Where it runs: `validate` (macOS + Linux CI, and any local `bun run validate`, - * incl. Windows dev boxes where the full suite passes). Windows CI runs the scoped - * `validate:windows` (its own gate) because that leg has no engine, so a budget with - * mac/linux skip bounds wouldn't fit it; tightening Windows into a full-`validate` - * CI leg is the tracked 1d follow-up (needs the engine cached into that leg first). + * Runs `bun test` for one leg and fails on a failing test or on pass/skip counts + * outside the leg's budget, so a suite that silently stops registering fails CI. + * Rules: CONTRIBUTING, "The budget gate". Usage: `bun scripts/check-test-budget.ts [leg]`. */ import { platform } from 'node:os'; -type Budget = { minPass: number; maxSkip: number }; - -const BUDGETS: Record = { - // Ratcheted to the numbers each leg actually reported on a green 3-OS run - // (darwin 1502/74, linux 1400/45), with ~5% headroom. win32 CI runs the scoped - // `validate:windows`, which does not call this gate at all, so its bound only - // fires on a Windows dev box running full validate — left loose deliberately. - win32: { minPass: 1200, maxSkip: 130 }, - darwin: { minPass: 1400, maxSkip: 90 }, - linux: { minPass: 1330, maxSkip: 55 }, +type Leg = { + readonly minPass: number; + readonly maxSkip: number; + readonly paths?: readonly string[]; + readonly timeoutMs?: number; }; -const budget = BUDGETS[platform()] ?? { minPass: 1000, maxSkip: 200 }; - -const proc = Bun.spawnSync(['bun', 'test', '--timeout', '30000'], { - stdout: 'pipe', - stderr: 'pipe', -}); -const out = `${proc.stdout.toString()}\n${proc.stderr.toString()}`; -process.stdout.write(out); +type Counts = { readonly pass: number; readonly skip: number; readonly fail: number }; -const num = (label: string): number => { - // bun prints e.g. " 1524 pass" / " 75 skip" / " 0 fail" - const match = out.match(new RegExp(`(\\d+)\\s+${label}`)); - return match?.[1] ? Number(match[1]) : Number.NaN; +/** + * Full-suite legs by `os.platform()`, within ~5% of measured CI runs at 9e2e312 (darwin 1901/185, + * linux 1730/189), plus `windows-scoped`, the suite `validate:windows` runs (231/15). + * ponytail: counts only; a per-OS file floor would catch a few files vanishing in the headroom. + */ +export const LEGS: Readonly> = { + darwin: { minPass: 1805, maxSkip: 194 }, + linux: { minPass: 1637, maxSkip: 198 }, + // ponytail: unmeasured; the full suite is not path-portable to Windows yet. + win32: { minPass: 1197, maxSkip: 130 }, + 'windows-scoped': { + minPass: 220, + maxSkip: 16, + paths: ['tests/unit/main/platform/windows', 'tests/integration/windows'], + timeoutMs: 60000, + }, }; -const pass = num('pass'); -const skip = num('skip'); -const fail = num('fail'); +/** Read bun's summary from its stderr; the last summary line wins, and bun omits `skip` at zero. */ +export const parseCounts = (stderr: string): Counts => { + const count = (label: string, missing: number): number => { + const last = [...stderr.matchAll(new RegExp(`^\\s*(\\d+) ${label}\\s*$`, 'gm'))].at(-1)?.[1]; + return last === undefined ? missing : Number(last); + }; + return { + pass: count('pass', Number.NaN), + skip: count('skip', 0), + fail: count('fail', Number.NaN), + }; +}; -const problems: string[] = []; -if (proc.exitCode !== 0) problems.push(`the test run exited ${proc.exitCode}`); -if (Number.isNaN(pass) || Number.isNaN(skip) || Number.isNaN(fail)) { - problems.push('could not parse pass/skip/fail counts from the test output'); -} -if (fail > 0) problems.push(`${fail} test(s) failed`); -if (pass < budget.minPass) { - problems.push(`only ${pass} tests passed (< ${budget.minPass}) — did a suite stop registering?`); -} -if (skip > budget.maxSkip) { - problems.push(`${skip} tests skipped (> ${budget.maxSkip}) — did a suite get gated off?`); -} +/** Why a run breaks `leg`'s budget; empty when it holds. */ +export const budgetProblems = (leg: Leg, counts: Counts, exitCode: number | null): string[] => { + const { pass, skip, fail } = counts; + const problems: string[] = []; + if (exitCode !== 0) problems.push(`the test run exited ${exitCode}`); + if (Number.isNaN(pass) || Number.isNaN(fail)) { + problems.push('could not parse the pass/fail counts from the test output'); + } + if (fail > 0) problems.push(`${fail} test(s) failed`); + if (pass < leg.minPass) { + problems.push(`only ${pass} tests passed (< ${leg.minPass}) - did a suite stop registering?`); + } + if (skip > leg.maxSkip) { + problems.push(`${skip} tests skipped (> ${leg.maxSkip}) - did a suite get gated off?`); + } + return problems; +}; -process.stdout.write( - `\ntest budget [${platform()}]: pass=${pass} skip=${skip} fail=${fail} ` + - `(min pass ${budget.minPass}, max skip ${budget.maxSkip})\n`, -); -if (problems.length > 0) { - process.stdout.write(`TEST BUDGET FAILED:\n - ${problems.join('\n - ')}\n`); - process.exit(1); +if (import.meta.main) { + const name = process.argv[2] ?? platform(); + const leg = LEGS[name]; + if (leg === undefined) { + process.stderr.write( + `test budget: no leg "${name}" (known: ${Object.keys(LEGS).join(', ')})\n`, + ); + process.exit(1); + } + const timeout = String(leg.timeoutMs ?? 30000); + const proc = Bun.spawn([process.execPath, 'test', '--timeout', timeout, ...(leg.paths ?? [])], { + stdout: 'inherit', + stderr: 'pipe', + }); + // Streamed, not buffered: a CI timeout on a hung test must still show how far the run got. + let stderr = ''; + const decoder = new TextDecoder(); + for await (const chunk of proc.stderr) { + process.stderr.write(chunk); + stderr += decoder.decode(chunk, { stream: true }); + } + const exitCode = await proc.exited; + const counts = parseCounts(stderr); + const problems = budgetProblems(leg, counts, exitCode); + process.stdout.write( + `\ntest budget [${name}]: pass=${counts.pass} skip=${counts.skip} fail=${counts.fail} ` + + `(min pass ${leg.minPass}, max skip ${leg.maxSkip})\n`, + ); + if (problems.length > 0) { + process.stdout.write(`TEST BUDGET FAILED:\n - ${problems.join('\n - ')}\n`); + process.exit(1); + } + process.stdout.write('test budget OK\n'); } -process.stdout.write('test budget OK\n'); diff --git a/scripts/validate-linux.sh b/scripts/validate-linux.sh index 7daba0d3..a8792fd3 100755 --- a/scripts/validate-linux.sh +++ b/scripts/validate-linux.sh @@ -1,7 +1,6 @@ #!/bin/sh -# Run the exact CI Linux leg locally in a container, so blind-platform FFI code -# (GTK/WebKitGTK) is proven BEFORE a push instead of by a red CI run. Mirrors -# validate.yml's ubuntu job: same deps, same xvfb-run, same validate script. +# Run validate.yml's Linux leg in a container (same deps, Bun version, WebKit env +# and xvfb-run), so GTK/WebKitGTK FFI code is proven before a push, not by red CI. # # The repo mounts READ-ONLY and is copied inside the container: a shared # writable mount let the container's `bun install` write Linux binaries into @@ -10,11 +9,15 @@ set -e exec docker run --rm -t \ -v "$(pwd)":/repo:ro \ -e HOME=/tmp \ + -e WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS=1 \ + -e WEBKIT_DISABLE_COMPOSITING_MODE=1 \ + -e LIBGL_ALWAYS_SOFTWARE=1 \ + -e GDK_BACKEND=x11 \ ubuntu:24.04 bash -c ' set -e apt-get update -q - apt-get install -y -q curl unzip libgtk-4-1 libwebkitgtk-6.0-4 libnotify4 libsecret-1-0 xvfb ca-certificates > /dev/null - curl -fsSL https://bun.sh/install | bash > /dev/null + apt-get install -y -q curl unzip libgtk-4-1 libwebkitgtk-6.0-4 libnotify4 libsecret-1-0 libxtst6 xvfb ca-certificates > /dev/null + curl -fsSL https://bun.sh/install | bash -s "bun-v$(cat /repo/.bun-version)" > /dev/null export PATH="/tmp/.bun/bin:$PATH" mkdir /work tar -C /repo --exclude node_modules --exclude .git --exclude website/node_modules --exclude website/dist -cf - . | tar -C /work -xf - diff --git a/src/cli/app-assets.ts b/src/cli/app-assets.ts index 837297a8..9143a076 100644 --- a/src/cli/app-assets.ts +++ b/src/cli/app-assets.ts @@ -1,28 +1,36 @@ -import { cpSync, existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; -import { dirname, extname, join, resolve, sep } from 'node:path'; +import { cpSync, existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; +import { basename, dirname, extname, join, resolve, sep } from 'node:path'; import { defaultPreloadBundler, type PreloadBundler, usesModuleSyntax, } from '../common/preload-bundle'; +import { findManifest } from '../main/api/app-metadata'; -const COMPILED_SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.mts', '.cts']); +// An allowlist, not a denylist: the entry's directory can hold the update-signing key. +const RUNTIME_ASSET_EXTENSIONS = new Set( + ( + '.html .htm .js .mjs .cjs .css .json .wasm .txt ' + + '.png .jpg .jpeg .gif .svg .webp .avif .ico .icns .bmp .woff .woff2 .ttf .otf ' + + '.mp3 .mp4 .m4a .aac .wav .ogg .webm .flac .dylib .so .dll' + ).split(' '), +); -/** - * Whether a sibling of the entry ships as a runtime asset rather than being - * compiled into the binary. TypeScript sources, dotfiles and `node_modules` are - * excluded; HTML, JS preloads, CSS, images, JSON and the like are kept. - */ +/** Whether a file of this name ships beside the executable. */ export const isRuntimeAsset = (name: string): boolean => - name !== 'node_modules' && - !name.startsWith('.') && - !COMPILED_SOURCE_EXTENSIONS.has(extname(name).toLowerCase()); + RUNTIME_ASSET_EXTENSIONS.has(extname(name).toLowerCase()); + +const shipsAsAsset = (path: string): boolean => { + const name = basename(path); + if (name.startsWith('.') || name === 'node_modules') { + return false; + } + return statSync(path).isDirectory() || isRuntimeAsset(name); +}; /** - * Copy the entry's sibling runtime assets into `destination` — the directory of - * the compiled executable — so the app resolves them next to itself at launch. - * The build output is skipped, so a destination nested under the entry's - * directory is never copied into itself. Returns the names copied. + * Copy the entry's allowlisted sibling assets (recursively) beside the executable. + * The build output is skipped, so a destination under the entry dir never copies into itself. */ export const copyAppAssets = (entry: string, destination: string): string[] => { const source = dirname(entry); @@ -32,30 +40,48 @@ export const copyAppAssets = (entry: string, destination: string): string[] => { const resolvedDestination = resolve(destination); const copied: string[] = []; for (const name of readdirSync(source)) { - if (!isRuntimeAsset(name)) { - continue; - } const from = resolve(source, name); if (resolvedDestination === from || resolvedDestination.startsWith(`${from}${sep}`)) { continue; } - cpSync(from, join(destination, name), { recursive: true }); + if (!shipsAsAsset(from)) { + continue; + } + cpSync(from, join(destination, name), { recursive: true, filter: shipsAsAsset }); copied.push(name); } return copied; }; +const readIfPresent = (path: string): string | undefined => + existsSync(path) ? readFileSync(path, 'utf8') : undefined; + +/** + * The runtime reads a compiled app's name and version only from `package.json` beside it. The + * name is the one dev reads from the entry's project (so `userData` stays put), else `name`. + */ +export const writeAppManifest = ( + destination: string, + entry: string, + name: string, + version: string, +): void => { + const project = findManifest(dirname(resolve(entry)), readIfPresent)?.manifest; + const named = project?.productName !== undefined || project?.name !== undefined; + const manifest = named + ? { name: project?.name, productName: project?.productName, version } + : { productName: name, version }; + writeFileSync(join(destination, 'package.json'), `${JSON.stringify(manifest)}\n`); +}; + const PRELOAD_ASSET = /^preload\.(?:js|mjs|cjs)$/i; /** - * Bundle any shipped `preload.*` asset that uses `import`/`export` into a - * self-contained classic script, in place, so a packaged app's preload runs the - * same as it does under `bunmaska dev` — a preload is injected as a CLASSIC script - * (no module mode), so a raw `import` would throw and silently kill `window.api`. - * Plain preloads are left untouched. `names` is typically the {@link copyAppAssets} - * return value. Returns the names rewritten. + * Bundle each shipped module-syntax `preload.*` into a classic IIFE in place + * (D046: a compiled app cannot bundle at runtime). Returns the names rewritten. */ export const bundlePreloadAssets = ( + entry: string, destination: string, names: readonly string[], bundler: PreloadBundler = defaultPreloadBundler, @@ -69,7 +95,8 @@ export const bundlePreloadAssets = ( if (!usesModuleSyntax(readFileSync(path, 'utf8'))) { continue; } - writeFileSync(path, bundler.bundle(resolve(path))); + // Bundle the source, not the copy: its imports (e.g. `.ts` helpers) resolve only there. + writeFileSync(path, bundler.bundle(resolve(dirname(entry), name))); rewritten.push(name); } return rewritten; diff --git a/src/cli/build-linux.ts b/src/cli/build-linux.ts index 32ceffef..9d1f957e 100644 --- a/src/cli/build-linux.ts +++ b/src/cli/build-linux.ts @@ -1,72 +1,69 @@ -/** - * No GTK/WebKitGTK libraries are bundled: Bunmaska dlopens the SYSTEM - * GTK/WebKitGTK at runtime via bun:ffi. The output is an AppDir-style tree - * packaged as a `.tar.gz` plus a `.deb`. - */ - -import { chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, writeFileSync } from 'node:fs'; +import { + chmodSync, + copyFileSync, + cpSync, + existsSync, + mkdirSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; import { dirname, join, posix } from 'node:path'; import { isSystemEngine, parseEngineId } from '../common/engine-id'; -import { type Arch, currentArch } from '../common/platform'; +import { slugifyName } from '../common/manifest'; +import { type Arch, currentArch, type Platform } from '../common/platform'; import { BUNMASKA_VERSION } from '../common/version'; -import { bundlePreloadAssets, copyAppAssets } from './app-assets'; +import { bundlePreloadAssets, copyAppAssets, writeAppManifest } from './app-assets'; import { runTool } from './run-tool'; -import { bundleIdSlug } from './build-macos'; +import { packageDeb, tarGz } from './deb'; export type LinuxLayout = { readonly appDir: string; readonly slug: string; + /** `usr/lib//`: the binary and its assets share a directory no other package owns. */ readonly binPath: string; + /** `usr/bin/`, a relative link to {@link binPath}; the only file in the shared `usr/bin`. */ + readonly launcherPath: string; readonly desktopPath: string; readonly iconPath: string; - /** The baked engine-id, read at launch (resolves `usr/bin/` -> here). */ readonly engineIdPath: string; }; -/** - * Compute every on-disk path of an `/` AppDir-style tree. POSIX joins - * keep the layout identical when computed on a cross-building host. - */ +/** Paths of the `/` AppDir tree; POSIX joins so any build host lays it out alike. */ export const linuxLayout = (out: string, name: string): LinuxLayout => { const { join } = posix; - const slug = bundleIdSlug(name); + const slug = slugifyName(name); const appDir = join(out, name); return { appDir, slug, - binPath: join(appDir, 'usr', 'bin', slug), + binPath: join(appDir, 'usr', 'lib', slug, slug), + launcherPath: join(appDir, 'usr', 'bin', slug), desktopPath: join(appDir, 'usr', 'share', 'applications', `${slug}.desktop`), iconPath: join(appDir, 'usr', 'share', 'icons', 'hicolor', '512x512', 'apps', `${slug}.png`), - engineIdPath: join(appDir, 'usr', 'share', slug, 'engine.id'), + engineIdPath: join(appDir, 'usr', 'lib', slug, 'engine.id'), }; }; -/** - * A full engine id verbatim, else the `system` sentinel. A bare upstream version - * (e.g. `2.52.4`) downgrades to `system` — this path does not consult the engine - * catalog yet, so the caller should surface the downgrade. - */ -export const resolveBuildEngineId = (webkitPin: string | undefined): string => { +/** A full engine id built for `target` verbatim, else `system`; the caller warns about a downgrade. */ +export const resolveBuildEngineId = ( + webkitPin: string | undefined, + target: { readonly os: Platform; readonly arch: Arch }, +): string => { if (webkitPin === undefined || isSystemEngine(webkitPin)) { return 'system'; } try { - parseEngineId(webkitPin); - return webkitPin; + const ref = parseEngineId(webkitPin); + return ref.os === target.os && ref.arch === target.arch ? webkitPin : 'system'; } catch { - return 'system'; + return 'system'; // ponytail: a bare version (`2.52.4`) lands here; resolve via the catalog } }; -/** Debian's label for the architecture: `amd64` for x64, `arm64` as is. */ -export const debArch = (arch: Arch): 'amd64' | 'arm64' => (arch === 'x64' ? 'amd64' : 'arm64'); - export const tarballName = (name: string, arch: Arch = currentArch()): string => `${name}-linux-${arch}.tar.gz`; -export const debFileName = (name: string, version: string, arch: Arch = currentArch()): string => - `${bundleIdSlug(name)}_${version}_${debArch(arch)}.deb`; - export type DesktopEntryOptions = { readonly name: string; readonly slug: string; @@ -86,69 +83,9 @@ export const buildDesktopEntry = (opts: DesktopEntryOptions): string => '', ].join('\n'); -export type ControlFileOptions = { - readonly slug: string; - readonly version: string; - /** Debian architecture label; defaults to the host's. */ - readonly arch?: 'amd64' | 'arm64'; - readonly maintainer: string; - readonly description: string; - /** Runtime package dependencies (`Depends:`). Omitted from the field when empty. */ - readonly depends?: readonly string[]; -}; - -/** - * Runtime packages a non-embedded Bunmaska `.deb` needs: the system WebKitGTK 6.0 - * web view and its GTK 4 toolkit. Without this, an `apt install` on a minimal box - * leaves the app to crash at the first `dlopen` (the latent bug this fixes). Debian - * package names confirmed on sid: `libwebkitgtk-6.0-4`, `libgtk-4-1`. - */ -export const DEFAULT_LINUX_DEPENDS: readonly string[] = ['libwebkitgtk-6.0-4', 'libgtk-4-1']; - -export const buildControlFile = (opts: ControlFileOptions): string => - [ - `Package: ${opts.slug}`, - `Version: ${opts.version}`, - `Architecture: ${opts.arch ?? debArch(currentArch())}`, - `Maintainer: ${opts.maintainer}`, - ...(opts.depends !== undefined && opts.depends.length > 0 - ? [`Depends: ${opts.depends.join(', ')}`] - : []), - `Description: ${opts.description}`, - '', - ].join('\n'); - -/** Pad a field to a fixed width for a GNU `ar` member header. */ -const arField = (value: string, width: number): string => value.padEnd(width, ' ').slice(0, width); - -/** Encode one GNU `ar` member: header + content, padded to an even byte length. */ -const arMember = (name: string, content: Uint8Array): Uint8Array => { - const header = - arField(name, 16) + - arField('0', 12) + // mtime - arField('0', 6) + // uid - arField('0', 6) + // gid - arField('100644', 8) + // mode - arField(String(content.length), 10) + // size - '`\n'; // two-byte member-header terminator - const headerBytes = new TextEncoder().encode(header); - // ar pads an odd-length member with one '\n' so the next header is even-aligned. - const pad = content.length % 2 === 1 ? [Buffer.from('\n')] : []; - return Buffer.concat([headerBytes, content, ...pad]); -}; - -export const buildArArchive = ( - members: readonly { name: string; content: Uint8Array }[], -): Uint8Array => { - return Buffer.concat([ - new TextEncoder().encode('!\n'), - ...members.map((m) => arMember(m.name, m.content)), - ]); -}; - const compileLinuxBinary = async (entry: string, outfile: string, arch: Arch): Promise => { await runTool('bun build --compile', [ - 'bun', + process.execPath, 'build', entry, '--compile', @@ -168,10 +105,10 @@ export type BuildLinuxAppOptions = { readonly icon?: string; /** Engine-id to bake (the per-app pin); `system` (the default) = OS WebView. */ readonly engineId?: string; - /** Engine shipped inside the bundle — drops the system WebKitGTK `Depends:`. */ - readonly embedEngine?: boolean; /** The app's own version for the .deb; defaults to the framework version. */ readonly version?: string; + /** The .deb `Maintainer`, `Name `; defaults to one derived from the bundle id. */ + readonly maintainer?: string; /** Target architecture; defaults to the host's. */ readonly arch?: Arch; }; @@ -185,19 +122,30 @@ export type BuildLinuxAppResult = { export const buildLinuxApp = async (opts: BuildLinuxAppOptions): Promise => { const out = opts.out ?? process.cwd(); const layout = linuxLayout(out, opts.name); - const maintainer = `${opts.id ?? `com.bunmaska.${layout.slug}`} `; + if (layout.slug.length < 2) { + throw new Error( + `bunmaska build: a .deb package name needs at least 2 characters (got "${layout.slug}"); use a longer app name.`, + ); + } + const maintainer = + opts.maintainer ?? `${opts.id ?? `com.bunmaska.${layout.slug}`} `; const description = `${opts.name} built with Bunmaska`; + const version = opts.version ?? BUNMASKA_VERSION; + // Start clean (everything the build writes is under usr/): cpSync merges into stale trees. + rmSync(join(layout.appDir, 'usr'), { recursive: true, force: true }); mkdirSync(dirname(layout.binPath), { recursive: true }); + mkdirSync(dirname(layout.launcherPath), { recursive: true }); mkdirSync(dirname(layout.desktopPath), { recursive: true }); const arch = opts.arch ?? currentArch(); await compileLinuxBinary(opts.entry, layout.binPath, arch); chmodSync(layout.binPath, 0o755); + symlinkSync(posix.join('..', 'lib', layout.slug, layout.slug), layout.launcherPath); - // Bundle a module-using preload so it runs as a classic script in the packaged app. const assetsDir = dirname(layout.binPath); - bundlePreloadAssets(assetsDir, copyAppAssets(opts.entry, assetsDir)); + bundlePreloadAssets(opts.entry, assetsDir, copyAppAssets(opts.entry, assetsDir)); + writeAppManifest(assetsDir, opts.entry, opts.name, version); if (opts.rendererDir !== undefined) { cpSync(opts.rendererDir, join(assetsDir, 'renderer'), { recursive: true }); } @@ -215,74 +163,20 @@ export const buildLinuxApp = async (opts: BuildLinuxAppOptions): Promise. const tarball = join(out, tarballName(opts.name, arch)); - await runTool('tar', ['tar', '-czf', tarball, '-C', out, opts.name]); + await tarGz(tarball, out, opts.name); - // An embedded engine ships its own WebKitGTK, so it needs no system Depends. - const depends = opts.embedEngine === true ? [] : DEFAULT_LINUX_DEPENDS; const deb = await packageDeb({ layout, out, - version: opts.version ?? BUNMASKA_VERSION, + version, arch, name: opts.name, maintainer, description, - depends, }); return { appDir: layout.appDir, tarball, deb }; }; - -/** - * A `.deb` is an `ar` archive of `debian-binary`, `control.tar.gz`, and - * `data.tar.gz` (the `usr/` tree under the filesystem root), in that order. - */ -const packageDeb = async (args: { - readonly layout: LinuxLayout; - readonly out: string; - readonly version: string; - readonly arch: Arch; - readonly name: string; - readonly maintainer: string; - readonly description: string; - readonly depends: readonly string[]; -}): Promise => { - const { layout, out, version, arch, name, maintainer, description, depends } = args; - const staging = join(out, `.deb-${layout.slug}`); - const controlDir = join(staging, 'control-root'); - mkdirSync(controlDir, { recursive: true }); - - writeFileSync( - join(controlDir, 'control'), - buildControlFile({ - slug: layout.slug, - version, - arch: debArch(arch), - maintainer, - description, - depends, - }), - ); - - const controlTar = join(staging, 'control.tar.gz'); - await runTool('tar', ['tar', '-czf', controlTar, '-C', controlDir, 'control']); - - const dataTar = join(staging, 'data.tar.gz'); - await runTool('tar', ['tar', '-czf', dataTar, '-C', layout.appDir, 'usr']); - - const debPath = join(out, debFileName(name, version, arch)); - const archive = buildArArchive([ - { name: 'debian-binary', content: new TextEncoder().encode('2.0\n') }, - { name: 'control.tar.gz', content: new Uint8Array(await Bun.file(controlTar).arrayBuffer()) }, - { name: 'data.tar.gz', content: new Uint8Array(await Bun.file(dataTar).arrayBuffer()) }, - ]); - await Bun.write(debPath, archive); - - return debPath; -}; diff --git a/src/cli/build-macos.ts b/src/cli/build-macos.ts index 1ae166e1..32c41a83 100644 --- a/src/cli/build-macos.ts +++ b/src/cli/build-macos.ts @@ -1,8 +1,3 @@ -/** - * No WebKit/AppKit framework is bundled: Bunmaska dlopens the SYSTEM - * frameworks at runtime via bun:ffi. - */ - import { cpSync, chmodSync, @@ -15,11 +10,13 @@ import { } from 'node:fs'; import { tmpdir } from 'node:os'; import { join, posix } from 'node:path'; +import { slugifyName } from '../common/manifest'; import { BUNMASKA_VERSION } from '../common/version'; -import { bundlePreloadAssets, copyAppAssets } from './app-assets'; +import { bundlePreloadAssets, copyAppAssets, writeAppManifest } from './app-assets'; import { runTool } from './run-tool'; -const MINIMUM_SYSTEM_VERSION = '11.0'; +// The minos `bun build --compile` stamps into the Mach-O (Bun 1.4.2). +const MINIMUM_SYSTEM_VERSION = '13.0'; const escapeXml = (value: string): string => value @@ -29,16 +26,26 @@ const escapeXml = (value: string): string => .replace(/"/g, '"') .replace(/'/g, '''); -/** Lowercase DNS-label-ish slug; falls back to `app` when nothing survives. */ -export const bundleIdSlug = (name: string): string => { - const slug = name - .toLowerCase() - .replace(/[^a-z0-9]+/g, '-') - .replace(/^-+|-+$/g, ''); - return slug.length > 0 ? slug : 'app'; -}; +export const defaultBundleId = (name: string): string => `com.bunmaska.${slugifyName(name)}`; -export const defaultBundleId = (name: string): string => `com.bunmaska.${bundleIdSlug(name)}`; +/** + * Info.plist and a Windows VERSIONINFO accept only numeric `major.minor.patch`: + * `0.1.0-alpha.2+b5` -> `0.1.0`, `1.2` -> `1.2.0`, a non-numeric segment -> `0`. + */ +export const numericVersion = (version: string): string => { + const core = (version.split('+', 1)[0] ?? '').split('-', 1)[0] ?? ''; + const parts = core + .split('.') + .slice(0, 3) + .map((segment) => { + const value = Number.parseInt(segment, 10); + return Number.isNaN(value) ? '0' : String(value); + }); + while (parts.length < 3) { + parts.push('0'); + } + return parts.join('.'); +}; export type InfoPlistOptions = { readonly name: string; @@ -58,8 +65,8 @@ export const buildInfoPlist = (opts: InfoPlistOptions): string => { plistString('CFBundleExecutable', opts.name), plistString('CFBundlePackageType', 'APPL'), plistString('CFBundleInfoDictionaryVersion', '6.0'), - plistString('CFBundleShortVersionString', opts.version), - plistString('CFBundleVersion', opts.version), + plistString('CFBundleShortVersionString', numericVersion(opts.version)), + plistString('CFBundleVersion', numericVersion(opts.version)), plistString('LSMinimumSystemVersion', MINIMUM_SYSTEM_VERSION), ' NSHighResolutionCapable\n ', ]; @@ -89,10 +96,6 @@ export type AppBundleLayout = { readonly iconPath: string; }; -/** - * Compute every on-disk path of an `/.app` bundle. POSIX joins keep - * the layout identical when computed on a cross-building host. - */ export const appBundleLayout = (out: string, name: string): AppBundleLayout => { const { join } = posix; const appDir = join(out, `${name}.app`); @@ -113,10 +116,10 @@ export const appBundleLayout = (out: string, name: string): AppBundleLayout => { }; /** - * Entitlements a Bun-compiled app needs under the Hardened Runtime: JIT and - * unsigned executable memory for JavaScriptCore and bun:ffi, and library - * validation disabled so the app can dlopen the system WebKit/AppKit at launch. - * Without these a hardened-runtime app traps (SIGTRAP) on its first FFI call. + * `allow-jit` is mandatory: without it a hardened app throws "bun:ffi requires the JIT" + * (Bun 1.4.2); the system WebKit/AppKit load with it alone. `disable-library-validation` + * lets the app dlopen dylibs its team did not sign (user native modules). + * ponytail: the two extra grants ship by default; make them config opt-ins */ export const codesignEntitlements = (): string => ` @@ -133,10 +136,7 @@ export const codesignEntitlements = (): string => `; -/** - * `--options runtime` is required for notarization. `identity` is a real - * `Developer ID Application: …` identity, or `-` for an ad-hoc signature. - */ +/** `--options runtime` (the hardened runtime) is required for notarization; `-` signs ad hoc. */ export const buildCodesignArgs = ( identity: string, appPath: string, @@ -146,6 +146,8 @@ export const buildCodesignArgs = ( '--deep', '--options', 'runtime', + // Notarization rejects a signature without a secure timestamp; ad-hoc cannot have one. + ...(identity === '-' ? [] : ['--timestamp']), '--entitlements', entitlementsPath, '--sign', @@ -166,14 +168,7 @@ export type NotarizeOptions = { readonly password: string; }; -/** - * Build the `xcrun notarytool submit …` argv. Pure. - * - * The default `--notarize` hook submits the ditto ZIP of the bundle (notarytool - * refuses a bare `.app`), so `appPath` is the submit target, not always an app. - * `password` is an app-specific password for the Apple ID. `--wait` blocks - * until Apple finishes processing. - */ +/** `appPath` is the zip notarize.ts submits; `password` is an app-specific password. */ export const buildNotarizeArgs = (opts: NotarizeOptions): string[] => [ 'xcrun', 'notarytool', @@ -188,12 +183,6 @@ export const buildNotarizeArgs = (opts: NotarizeOptions): string[] => [ '--wait', ]; -/** - * Build the `xcrun stapler staple …` argv for an `.app` bundle. Pure. - * - * Stapling attaches the notarization ticket to the bundle and is only - * meaningful after a successful notarytool submission. - */ export const buildStapleArgs = (appPath: string): string[] => [ 'xcrun', 'stapler', @@ -332,24 +321,38 @@ export type BuildMacAppOptions = { readonly signApp?: SignApp; readonly convertIcon?: ConvertIcon; readonly buildDmg?: BuildDmg; + /** Notarize and staple the signed bundle; runs before the `.dmg` is built. */ + readonly notarize?: (appPath: string) => Promise; + /** The app's own version for Info.plist; defaults to the framework version. */ + readonly version?: string; }; const compileBinary = (entry: string, outfile: string): Promise => - runTool('bun build --compile', ['bun', 'build', entry, '--compile', '--outfile', outfile]); + runTool('bun build --compile', [ + process.execPath, + 'build', + entry, + '--compile', + '--outfile', + outfile, + ]); export const buildMacApp = async (opts: BuildMacAppOptions): Promise => { const out = opts.out ?? process.cwd(); const bundleId = opts.id ?? defaultBundleId(opts.name); + const version = opts.version ?? BUNMASKA_VERSION; const layout = appBundleLayout(out, opts.name); + // Start clean: cpSync merges, so files an earlier build shipped would ship again. + rmSync(layout.appDir, { recursive: true, force: true }); mkdirSync(layout.macosDir, { recursive: true }); mkdirSync(layout.resourcesDir, { recursive: true }); await compileBinary(opts.entry, layout.executablePath); chmodSync(layout.executablePath, 0o755); - // Bundle a module-using preload so it runs as a classic script in the packaged app. - bundlePreloadAssets(layout.macosDir, copyAppAssets(opts.entry, layout.macosDir)); + bundlePreloadAssets(opts.entry, layout.macosDir, copyAppAssets(opts.entry, layout.macosDir)); + writeAppManifest(layout.macosDir, opts.entry, opts.name, version); if (opts.rendererDir !== undefined) { cpSync(opts.rendererDir, join(layout.macosDir, 'renderer'), { recursive: true }); } @@ -371,19 +374,21 @@ export const buildMacApp = async (opts: BuildMacAppOptions): Promise => const plist = buildInfoPlist( iconFile === undefined - ? { name: opts.name, bundleId, version: BUNMASKA_VERSION } - : { name: opts.name, bundleId, version: BUNMASKA_VERSION, iconFile }, + ? { name: opts.name, bundleId, version } + : { name: opts.name, bundleId, version, iconFile }, ); writeFileSync(layout.infoPlistPath, plist); - // Sign last, once the bundle (binary + Info.plist + resources) is fully laid - // out, so the signature covers the final contents. + // Sign last so the seal covers the final bundle. if (opts.sign !== undefined) { const signApp = opts.signApp ?? codesignApp; await signApp(opts.sign, layout.appDir); } + if (opts.notarize !== undefined) { + await opts.notarize(layout.appDir); + } - // The .dmg packages the signed bundle, so it is produced after signing. + // The .dmg packages the final bundle, so it comes after signing and stapling. if (opts.dmg === true) { const dmg = opts.buildDmg ?? buildDmg; await dmg({ appDir: layout.appDir, name: opts.name, outDmg: join(out, `${opts.name}.dmg`) }); diff --git a/src/cli/build-windows.ts b/src/cli/build-windows.ts index 6d96d52a..0a300e2e 100644 --- a/src/cli/build-windows.ts +++ b/src/cli/build-windows.ts @@ -1,26 +1,25 @@ -/** - * Windows ships no system WebKit, so at launch Bunmaska `dlopen`s a WinCairo - * `WebKit2.dll`. With `--embed-engine` that engine's whole directory is copied - * into the bundle's `webkit/` folder and the `.exe` runs with NO environment - * variables; without it the launch relies on the engine store (the baked - * `engine.id`) or `BUNMASKA_WEBKIT_PATH`. - */ - -import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +// Windows has no system WebKit: the app loads a WinCairo engine from `webkit/` (--embed-engine), +// the engine store (the baked `engine.id`) or `BUNMASKA_WEBKIT_PATH`. + +import { + cpSync, + existsSync, + mkdirSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; import { join } from 'node:path'; +import { BUNDLED_ENGINE_DIRNAME } from '../common/engine-store'; +import { slugifyName } from '../common/manifest'; +import { currentPlatform, type Platform } from '../common/platform'; import { BUNMASKA_VERSION } from '../common/version'; -import { bundlePreloadAssets, copyAppAssets } from './app-assets'; +import { bundlePreloadAssets, copyAppAssets, writeAppManifest } from './app-assets'; import { runTool } from './run-tool'; -import { bundleIdSlug } from './build-macos'; +import { numericVersion } from './build-macos'; import { buildZipArchive, type ZipEntry } from './zip'; -/** - * The bundle subdirectory an embedded WinCairo engine is copied into. The runtime - * looks for `/webkit/WebKit2.dll` (see `webkit2-ffi.ts`'s `bundledEngineDir`, - * which carries the matching constant) — keep the two in sync. - */ -export const BUNDLED_ENGINE_DIRNAME = 'webkit'; - export type WindowsLayout = { readonly appDir: string; readonly slug: string; @@ -35,7 +34,7 @@ export const windowsLayout = (out: string, name: string): WindowsLayout => { const exeName = `${name}.exe`; return { appDir, - slug: bundleIdSlug(name), + slug: slugifyName(name), exeName, exePath: join(appDir, exeName), engineIdPath: join(appDir, 'engine.id'), @@ -44,33 +43,13 @@ export const windowsLayout = (out: string, name: string): WindowsLayout => { export const zipFileName = (name: string): string => `${name}-windows-x64.zip`; -/** - * A Windows PE VERSIONINFO resource (`--windows-version`) accepts only a numeric - * `major.minor.patch`, so `+build` and `-prerelease` are dropped, short segments - * zero-padded, and a non-numeric segment becomes `0`. `0.1.0-alpha.2` -> `0.1.0`. - */ -export const numericVersion = (version: string): string => { - const core = (version.split('+', 1)[0] ?? '').split('-', 1)[0] ?? ''; - const parts = core - .split('.') - .slice(0, 3) - .map((segment) => { - const value = Number.parseInt(segment, 10); - return Number.isNaN(value) ? '0' : String(value); - }); - while (parts.length < 3) { - parts.push('0'); - } - return parts.join('.'); -}; - export type WindowsMetadata = { readonly title: string; readonly publisher: string; readonly version: string; readonly description: string; readonly hideConsole: boolean; - /** Optional executable icon — must be a `.ico` (Bun does not convert on Windows). */ + /** A `.ico`; Bun does not convert other formats. */ readonly icon?: string; }; @@ -78,6 +57,7 @@ export const buildCompileArgs = ( entry: string, outfile: string, meta: WindowsMetadata, + host: Platform = currentPlatform(), ): string[] => { const args = ['build', entry, '--compile', '--target=bun-windows-x64', '--outfile', outfile]; // Shrink the binary WITHOUT mangling identifiers: mangling would rename the user @@ -87,6 +67,10 @@ export const buildCompileArgs = ( if (meta.hideConsole) { args.push('--windows-hide-console'); } + // Bun rejects every other --windows-* flag unless it runs on Windows (Bun 1.4.2). + if (host !== 'windows') { + return args; + } args.push('--windows-title', meta.title); args.push('--windows-publisher', meta.publisher); args.push('--windows-version', meta.version); @@ -97,10 +81,6 @@ export const buildCompileArgs = ( return args; }; -/** - * Spawns the RUNNING Bun (`process.execPath`) rather than a bare `bun`, so the - * build does not depend on Bun being on `$PATH`. - */ const compileWindowsBinary = async ( entry: string, outfile: string, @@ -112,10 +92,7 @@ const compileWindowsBinary = async ( ]); }; -/** - * Entry names use forward slashes (the ZIP convention) under a single - * `/` folder, so extracting yields one top-level directory. - */ +/** Forward-slash names under one `/` folder, so extraction yields one directory. */ const collectZipEntries = (rootDir: string, topPrefix: string): ZipEntry[] => { const entries: ZipEntry[] = []; const walk = (dir: string, rel: string): void => { @@ -139,12 +116,14 @@ export type BuildWindowsAppOptions = { readonly entry: string; readonly name: string; readonly out?: string; - /** App icon — a `.ico` embedded into the `.exe`. */ + /** A `.ico` embedded into the `.exe` (Windows hosts only). */ readonly icon?: string; /** Engine-id to bake (the per-app pin); `system` is a no-op on Windows (no OS WebKit). */ readonly engineId?: string; /** Directory of a WinCairo WebKit engine to bundle into the app's `webkit/` folder. */ readonly embedEngine?: string; + /** The app's own version for the .exe; defaults to the framework version. */ + readonly version?: string; }; export type BuildWindowsAppResult = { @@ -168,37 +147,43 @@ export const buildWindowsApp = async ( } } - // Validate the engine to embed BEFORE the (slow) compile, so a bad path fails fast. + // Validate before the slow compile so a bad path fails fast. if (opts.embedEngine !== undefined && !existsSync(join(opts.embedEngine, 'WebKit2.dll'))) { throw new Error( `bunmaska build: --embed-engine directory has no WebKit2.dll: ${opts.embedEngine}`, ); } + // cpSync merges, so clear our own earlier output (it holds engine.id) or stale files ship again. + if (existsSync(layout.engineIdPath)) { + rmSync(layout.appDir, { recursive: true, force: true }); + } mkdirSync(layout.appDir, { recursive: true }); + if (currentPlatform() !== 'windows') { + process.stderr.write( + 'bunmaska build: only a Windows host can embed the .exe icon and version info; building without them.\n', + ); + } const meta: WindowsMetadata = { title: opts.name, - publisher: 'Bunmaska', - version: numericVersion(BUNMASKA_VERSION), + publisher: opts.name, + version: numericVersion(opts.version ?? BUNMASKA_VERSION), description: `${opts.name} built with Bunmaska`, hideConsole: true, ...(opts.icon !== undefined ? { icon: opts.icon } : {}), }; await compileWindowsBinary(opts.entry, layout.exePath, meta); - // Bundle a module-using preload so it runs as a classic script in the packaged app. - bundlePreloadAssets(layout.appDir, copyAppAssets(opts.entry, layout.appDir)); + bundlePreloadAssets(opts.entry, layout.appDir, copyAppAssets(opts.entry, layout.appDir)); + writeAppManifest(layout.appDir, opts.entry, opts.name, opts.version ?? BUNMASKA_VERSION); if (opts.rendererDir !== undefined) { cpSync(opts.rendererDir, join(layout.appDir, 'renderer'), { recursive: true }); } - // Bake the engine-id the app pins, read at launch by the engine resolver. writeFileSync(layout.engineIdPath, `${opts.engineId ?? 'system'}\n`); - // Copy the engine's whole directory closure (WebKit2.dll + ICU/libcurl/ANGLE + - // the helper processes) into `/webkit/`, which the runtime finds next to - // the executable, so the .exe runs with no env vars. + // The whole directory: WebKit2.dll needs its ICU/libcurl/ANGLE DLLs and helper processes. if (opts.embedEngine !== undefined) { cpSync(opts.embedEngine, join(layout.appDir, BUNDLED_ENGINE_DIRNAME), { recursive: true }); } diff --git a/src/cli/config.ts b/src/cli/config.ts index 8cb4bfd8..1165693e 100644 --- a/src/cli/config.ts +++ b/src/cli/config.ts @@ -1,26 +1,11 @@ -/** - * Filesystem discovery + dynamic import of a project's `bunmaska.config.ts`. The - * schema and validation live in {@link ../common/config-schema}. - */ +/** Finds and imports a project's bunmaska.config; the schema lives in common/config-schema. */ import { existsSync } from 'node:fs'; -import { dirname, isAbsolute, join, resolve } from 'node:path'; +import { dirname, join, resolve } from 'node:path'; import { CONFIG_FILE_NAMES, type BunmaskaConfig, validateConfig } from '../common/config-schema'; import { InvalidArgumentError } from '../common/errors'; -export { - CONFIG_FILE_NAMES, - configChannel, - defineConfig, - type BunmaskaConfig, - type BunmaskaUpdatesConfig, - validateConfig, -} from '../common/config-schema'; - -/** - * Absolute path of the project's config file, or `undefined`. The first name in - * {@link CONFIG_FILE_NAMES} wins. - */ +/** The project's config file; the first existing name in {@link CONFIG_FILE_NAMES} wins. */ export const findConfigFile = (cwd: string): string | undefined => { for (const fileName of CONFIG_FILE_NAMES) { const candidate = join(cwd, fileName); @@ -31,19 +16,16 @@ export const findConfigFile = (cwd: string): string | undefined => { return undefined; }; -/** - * Accepts a `default` export or a named `config` export; throws - * {@link InvalidArgumentError} if neither is present or the value is malformed. - */ +/** Takes the `default` or a named `config` export; throws {@link InvalidArgumentError} if bad. */ export const loadConfigFile = async (path: string): Promise => { - const absolute = isAbsolute(path) ? path : resolve(path); + const absolute = resolve(path); let module: Record; try { module = (await import(absolute)) as Record; } catch (error) { const message = error instanceof Error ? error.message : String(error); - // A config importing `bunmaska/config` before `bun install` fails in Bun's - // resolver; say what to do instead of dumping the stack. + // With no node_modules Bun auto-installs the import; with one that lacks bunmaska + // the import fails here, so say what to do instead of dumping the stack. if (/Cannot find (module|package)/.test(message)) { throw new InvalidArgumentError( `${path}: could not import the config (${message.split('\n')[0]}). Run bun install in ${dirname(absolute)} first.`, @@ -58,10 +40,7 @@ export const loadConfigFile = async (path: string): Promise => { return validateConfig(value, path); }; -/** - * Returns an empty config with `configPath: undefined` when the project has no - * config file. - */ +/** An empty config and `configPath: undefined` when the project has no config file. */ export const loadConfig = async ( cwd: string = process.cwd(), ): Promise<{ readonly config: BunmaskaConfig; readonly configPath: string | undefined }> => { diff --git a/src/cli/deb.ts b/src/cli/deb.ts new file mode 100644 index 00000000..128ebd6b --- /dev/null +++ b/src/cli/deb.ts @@ -0,0 +1,154 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { slugifyName } from '../common/manifest'; +import { type Arch, currentArch, currentPlatform } from '../common/platform'; +import type { LinuxLayout } from './build-linux'; +import { runTool } from './run-tool'; + +/** Debian's label for the architecture: `amd64` for x64, `arm64` as is. */ +export const debArch = (arch: Arch): 'amd64' | 'arm64' => (arch === 'x64' ? 'amd64' : 'arm64'); + +// dpkg splits a revision at the last `-`, so `1.0.0-beta.1` sorts above `1.0.0`; `~` sorts below. +const debVersion = (version: string): string => version.replace('-', '~'); + +export const debFileName = (name: string, version: string, arch: Arch = currentArch()): string => + `${slugifyName(name)}_${debVersion(version)}_${debArch(arch)}.deb`; + +/** A Debian `Maintainer` from package.json's `author`; `undefined` without the required email. */ +export const debMaintainer = (author: unknown): string | undefined => { + if (typeof author === 'string') { + const match = /^([^<(]*?)\s*<([^>]+)>/.exec(author.trim()); + return match === null ? undefined : `${match[1]} <${match[2]}>`; + } + if (typeof author === 'object' && author !== null) { + const { name, email } = author as Record; + return typeof name === 'string' && typeof email === 'string' ? `${name} <${email}>` : undefined; + } + return undefined; +}; + +export type ControlFileOptions = { + readonly slug: string; + readonly version: string; + /** Debian architecture label; defaults to the host's. */ + readonly arch?: 'amd64' | 'arm64'; + readonly maintainer: string; + readonly description: string; + /** `Depends:` packages; the field is omitted when empty. */ + readonly depends?: readonly string[]; +}; + +/** + * The system WebKitGTK 6.0 and GTK 4 the app dlopens; without them an `apt install` + * on a minimal box crashes at the first `dlopen`. Names confirmed on Debian sid. The + * floors are hard: one symbol missing from an older library fails its whole table. + */ +export const DEFAULT_LINUX_DEPENDS: readonly string[] = [ + 'libwebkitgtk-6.0-4 (>= 2.42)', + 'libgtk-4-1 (>= 4.10)', +]; + +export const buildControlFile = (opts: ControlFileOptions): string => + [ + `Package: ${opts.slug}`, + `Version: ${debVersion(opts.version)}`, + `Architecture: ${opts.arch ?? debArch(currentArch())}`, + `Maintainer: ${opts.maintainer}`, + ...(opts.depends !== undefined && opts.depends.length > 0 + ? [`Depends: ${opts.depends.join(', ')}`] + : []), + // Notifications dlopen libnotify.so.4; the app runs without it. + 'Recommends: libnotify4', + `Description: ${opts.description}`, + '', + ].join('\n'); + +const arField = (value: string, width: number): string => value.padEnd(width, ' ').slice(0, width); + +const arMember = (name: string, content: Uint8Array): Uint8Array => { + const header = + arField(name, 16) + + arField('0', 12) + // mtime + arField('0', 6) + // uid + arField('0', 6) + // gid + arField('100644', 8) + // mode + arField(String(content.length), 10) + // size + '`\n'; // two-byte member-header terminator + const headerBytes = new TextEncoder().encode(header); + // ar pads an odd-length member with one '\n' so the next header is even-aligned. + const pad = content.length % 2 === 1 ? [Buffer.from('\n')] : []; + return Buffer.concat([headerBytes, content, ...pad]); +}; + +export const buildArArchive = ( + members: readonly { name: string; content: Uint8Array }[], +): Uint8Array => { + return Buffer.concat([ + new TextEncoder().encode('!\n'), + ...members.map((m) => arMember(m.name, m.content)), + ]); +}; + +// dpkg installs the archived owner and every path, so members must be root-owned, xattr-free +// and without macOS bsdtar's AppleDouble `._*` twins (they collide across packages). +// The flags work in bsdtar and GNU tar. +export const tarGz = (archive: string, dir: string, member: string): Promise => + runTool('tar', [ + ...(currentPlatform() === 'macos' ? ['env', 'COPYFILE_DISABLE=1'] : []), + 'tar', + '--no-xattrs', + '--owner=0', + '--group=0', + '--numeric-owner', + '-czf', + archive, + '-C', + dir, + member, + ]); + +/** dpkg requires the `ar` members in order: `debian-binary`, `control.tar.gz`, `data.tar.gz`. */ +export const packageDeb = async (args: { + readonly layout: Pick; + readonly out: string; + readonly version: string; + readonly arch: Arch; + readonly name: string; + readonly maintainer: string; + readonly description: string; +}): Promise => { + const { layout, out, version, arch, name, maintainer, description } = args; + const staging = mkdtempSync(join(tmpdir(), 'bunmaska-deb-')); + try { + const controlDir = join(staging, 'control-root'); + mkdirSync(controlDir, { recursive: true }); + writeFileSync( + join(controlDir, 'control'), + buildControlFile({ + slug: layout.slug, + version, + arch: debArch(arch), + maintainer, + description, + depends: DEFAULT_LINUX_DEPENDS, + }), + ); + + const controlTar = join(staging, 'control.tar.gz'); + await tarGz(controlTar, controlDir, 'control'); + const dataTar = join(staging, 'data.tar.gz'); + await tarGz(dataTar, layout.appDir, 'usr'); + + const debPath = join(out, debFileName(name, version, arch)); + const archive = buildArArchive([ + { name: 'debian-binary', content: new TextEncoder().encode('2.0\n') }, + { name: 'control.tar.gz', content: new Uint8Array(await Bun.file(controlTar).arrayBuffer()) }, + { name: 'data.tar.gz', content: new Uint8Array(await Bun.file(dataTar).arrayBuffer()) }, + ]); + await Bun.write(debPath, archive); + return debPath; + } finally { + rmSync(staging, { recursive: true, force: true }); + } +}; diff --git a/src/cli/dev-classify.ts b/src/cli/dev-classify.ts new file mode 100644 index 00000000..75a986f2 --- /dev/null +++ b/src/cli/dev-classify.ts @@ -0,0 +1,119 @@ +/** How `bunmaska dev` reacts to a changed path: restart, rebuild, reload or ignore. */ + +import { readFileSync, realpathSync } from 'node:fs'; +import { dirname, extname, isAbsolute, relative, resolve, sep } from 'node:path'; +import type { BunmaskaRendererConfig } from '../common/config-schema'; +import { isIgnoredPath, pathParts } from './dev-watch'; + +/** TypeScript is compiled into the main process, so a change there restarts it. */ +const MAIN_SOURCE_EXTENSIONS: ReadonlySet = new Set(['.ts', '.tsx', '.mts', '.cts']); + +/** The preload is bundled once, at window construction: a reload re-injects the stale script. */ +const PRELOAD_BASENAME = /^preload\.(?:js|mjs|cjs|ts)$/i; + +export type ChangeAction = 'restart' | 'rebuild' | 'reload' | 'ignore'; + +/** + * Classify a root-relative changed path. Under `rendererRoot` (the renderer + * entry's directory) an edit rebuilds, and the bundle's writes then reload. + */ +export const classifyChange = (relPath: string, rendererRoot?: string): ChangeAction => { + if (isIgnoredPath(relPath)) { + return 'ignore'; + } + const parts = pathParts(relPath); + const base = parts[parts.length - 1] ?? ''; + if (PRELOAD_BASENAME.test(base)) { + return 'restart'; + } + if (rendererRoot !== undefined && isWithin(parts, pathParts(rendererRoot))) { + return 'rebuild'; + } + return MAIN_SOURCE_EXTENSIONS.has(extname(base).toLowerCase()) ? 'restart' : 'reload'; +}; + +/** True when `parts` lies strictly under `root` (or is it, with `orSelf`). */ +const isWithin = (parts: readonly string[], root: readonly string[], orSelf = false): boolean => + root.length > 0 && + root.length <= parts.length - (orSelf ? 0 : 1) && + root.every((part, i) => parts[i] === part); + +/** + * {@link classifyChange} for a project: a `renderer.copy` source rebuilds (its + * dist copy then reloads, or restarts for a preload), and a module the entry + * imports restarts wherever it lives. + */ +export const devClassifier = ( + dir: string, + entry: string, + renderer?: BunmaskaRendererConfig, +): ((relPath: string) => ChangeAction) => { + const rendererRoot = renderer === undefined ? undefined : dirname(renderer.entry); + const copies = (renderer?.copy ?? []).map(pathParts); + let main = mainModules(dir, entry); + return (relPath) => { + const action = classifyChange(relPath, rendererRoot); + if (action === 'ignore') { + return action; + } + const parts = pathParts(relPath); + if (copies.some((source) => isWithin(parts, source, true))) { + return 'rebuild'; + } + if (main.has(parts.join('/'))) { + // The edit may add an import. + main = mainModules(dir, entry); + return 'restart'; + } + return action; + }; +}; + +const SCRIPT_FILE = /\.[cm]?[jt]sx?$/i; + +/** + * Root-relative paths of `entry` and every local module it imports, transitively. + * Only `./`, `../` and absolute specifiers are followed, so resolving never + * reaches the package manager. + */ +const mainModules = (dir: string, entry: string): Set => { + const found = new Set(); + let root: string; + try { + root = realpathSync(dir); + } catch { + return found; + } + const visit = (file: string): void => { + const rel = relative(root, file).split(sep).join('/'); + if (found.has(rel) || rel.startsWith('..') || isAbsolute(rel) || isIgnoredPath(rel)) { + return; + } + found.add(rel); + if (!SCRIPT_FILE.test(file)) { + return; + } + let imports: readonly { readonly path: string }[]; + try { + const loader = /x$/i.test(file) ? 'tsx' : 'ts'; + imports = new Bun.Transpiler({ loader }).scanImports(readFileSync(file, 'utf8')); + } catch { + return; + } + for (const { path } of imports) { + if (/^\.{0,2}\//.test(path)) { + try { + visit(Bun.resolveSync(path, dirname(file))); + } catch { + // A missing local module is not a main module yet. + } + } + } + }; + try { + visit(realpathSync(resolve(dir, entry))); + } catch { + // No entry file: nothing to follow. + } + return found; +}; diff --git a/src/cli/dev-watch.ts b/src/cli/dev-watch.ts new file mode 100644 index 00000000..f944fba5 --- /dev/null +++ b/src/cli/dev-watch.ts @@ -0,0 +1,203 @@ +/** The `bunmaska dev` file watcher: which paths count, and which events are real edits. */ + +import { type Dirent, readdirSync, readFileSync, statSync, watch as fsWatch } from 'node:fs'; +import { resolve } from 'node:path'; + +/** The dev window-state file `bunmaska dev` keeps in the project root. */ +export const DEV_STATE_FILE = '.bunmaska-dev-state.json'; + +/** + * Top-level output dirs of common tools. `dist` is deliberately NOT here: the + * renderer bundle lives there, and ignoring it means a rebuild never reloads. + */ +const IGNORED_ROOT_DIRS: ReadonlySet = new Set(['build', 'out', 'coverage']); + +/** + * Dependencies, dot directories (VCS, editor state), `.app` bundles `bunmaska build` + * writes into the root, and the root output dirs. + * ponytail: a Linux or Windows build writes a bare `/` into the root, which + * stays watched; `--out` outside the root avoids the churn. + */ +const isIgnoredSegment = (name: string, depth: number): boolean => + name === 'node_modules' || + name.startsWith('.') || + name.endsWith('.app') || + (depth === 0 && IGNORED_ROOT_DIRS.has(name)); + +/** Split a watcher or config path on either separator, dropping `.` segments. */ +export const pathParts = (relPath: string): string[] => + relPath.split(/[\\/]/).filter((p) => p.length > 0 && p !== '.'); + +/** True for a path `bunmaska dev` never reacts to: ignored trees and dotfiles. */ +export const isIgnoredPath = (relPath: string): boolean => { + const parts = pathParts(relPath); + return parts.length === 0 || parts.some(isIgnoredSegment); +}; + +/** Two views over one content-hash baseline. */ +export type ContentFilter = { + /** True for a new file, a byte change or a deletion. */ + changed(relPath: string): boolean; + /** + * True only for a seen path whose bytes changed; an unseen path is seeded + * silently. Rescans need this: first-sight-passes would fire every sibling. + */ + changedIfSeen(relPath: string): boolean; +}; + +/** + * Drop events whose bytes did not change: `fs.watch` fires on a metadata-only + * touch and on a formatter rewriting identical bytes, and both would restart the app. + */ +export const makeContentFilter = ( + readFile: (relPath: string) => Uint8Array | undefined, +): ContentFilter => { + const seen = new Map(); + const hashOf = (relPath: string): string | undefined => { + const contents = readFile(relPath); + return contents === undefined ? undefined : String(Bun.hash(contents)); + }; + return { + changed(relPath) { + const hash = hashOf(relPath); + if (hash === undefined) { + seen.delete(relPath); + return true; + } + if (seen.get(relPath) === hash) { + return false; + } + seen.set(relPath, hash); + return true; + }, + changedIfSeen(relPath) { + const hash = hashOf(relPath); + if (hash === undefined) { + seen.delete(relPath); + return false; + } + const previous = seen.get(relPath); + seen.set(relPath, hash); + return previous !== undefined && previous !== hash; + }, + }; +}; + +/** + * The directory of an editor temp-file event, or `undefined` for any other path. + * FSEvents can coalesce an atomic save (write temp, rename) into a SINGLE event + * for the dot-named temp file (`.!1234!main.ts` from BSD sed), so dropping dot + * basenames loses the save; the caller rescans this directory instead. + */ +export const editorTempDir = (relPath: string): string | undefined => { + const parts = pathParts(relPath); + const dirs = parts.slice(0, -1); + const base = parts[parts.length - 1] ?? ''; + return base.startsWith('.') && !dirs.some(isIgnoredSegment) ? dirs.join('/') : undefined; +}; + +/** Files bigger than this are not seeded; their first event passes as first sight. */ +const SEED_MAX_BYTES = 5_000_000; + +/** Hash every watchable file up front, so a rescan has a baseline from the first save. */ +const seedContentFilter = (root: string, filter: ContentFilter, relDir = ''): void => { + let entries: Dirent[]; + try { + entries = readdirSync(resolve(root, relDir), { withFileTypes: true }); + } catch { + return; + } + for (const entry of entries) { + const rel = relDir === '' ? entry.name : `${relDir}/${entry.name}`; + if (isIgnoredPath(rel)) { + continue; + } + if (entry.isDirectory()) { + seedContentFilter(root, filter, rel); + continue; + } + if (!entry.isFile()) { + continue; + } + try { + if (statSync(resolve(root, rel)).size > SEED_MAX_BYTES) { + continue; + } + } catch { + continue; + } + filter.changedIfSeen(rel); + } +}; + +/** + * The `fs.watch` callback for `dir`: forwards each real edit to `onChange` as a + * root-relative path. Seeds the content baseline when created. + */ +export const makeWatchHandler = ( + dir: string, + onChange: (relPath: string) => void, +): ((filename: string | null) => void) => { + const filter = makeContentFilter((relPath) => { + try { + return readFileSync(resolve(dir, relPath)); + } catch { + return undefined; + } + }); + seedContentFilter(dir, filter); + // An atomic save may surface only as its temp-file event; find what really + // changed in that directory instead of dropping the save. + const rescan = (relDir: string): void => { + let entries: Dirent[]; + try { + entries = readdirSync(resolve(dir, relDir), { withFileTypes: true }); + } catch { + return; + } + for (const entry of entries) { + const rel = relDir === '' ? entry.name : `${relDir}/${entry.name}`; + if (entry.isFile() && !isIgnoredPath(rel) && filter.changedIfSeen(rel)) { + onChange(rel); + } + } + }; + return (filename) => { + if (filename === null || filename === DEV_STATE_FILE) { + return; + } + // One key per file: libuv reports Windows paths with backslashes, the seed uses slashes. + const relPath = pathParts(filename).join('/'); + const tempDir = editorTempDir(relPath); + if (tempDir !== undefined) { + rescan(tempDir); + return; + } + // Classify before hashing so node_modules churn never costs a file read. + if (isIgnoredPath(relPath) || !filter.changed(relPath)) { + return; + } + onChange(relPath); + }; +}; + +/** Watch `dir` recursively; see {@link makeWatchHandler}. */ +export const watchTree = ( + dir: string, + onChange: (relPath: string) => void, + log: (message: string) => void, +): { readonly close: () => void } => { + const handle = makeWatchHandler(dir, onChange); + const watcher = fsWatch(dir, { recursive: true }, (_event, filename) => { + handle(filename === null ? null : filename.toString()); + }); + // Unhandled, a watch error (inotify ENOSPC) kills the supervisor and orphans the app. + watcher.on('error', (error) => { + log(`file watching stopped (${error.message}); restart bunmaska dev`); + }); + return { + close: () => { + watcher.close(); + }, + }; +}; diff --git a/src/cli/dev.ts b/src/cli/dev.ts index 08811533..f1edc3c5 100644 --- a/src/cli/dev.ts +++ b/src/cli/dev.ts @@ -1,233 +1,56 @@ -/** - * `bunmaska dev`: a change in the main-process graph restarts the - * `bun run ` child; any other watched file is a renderer asset and - * live-reloads the open windows in place. - */ +/** `bunmaska dev`: runs the app and restarts, rebuilds or reloads it as files change. */ -import { type Dirent, readdirSync, readFileSync, statSync, watch as fsWatch } from 'node:fs'; -import { extname, resolve } from 'node:path'; +import { resolve } from 'node:path'; import type { BunmaskaConfig } from '../common/config-schema'; import { InvalidArgumentError } from '../common/errors'; +import { DEV_RELOAD_COMMAND } from '../main/dev-reload'; +import { type ChangeAction, devClassifier } from './dev-classify'; + +export type { ChangeAction } from './dev-classify'; +import { DEV_STATE_FILE, watchTree } from './dev-watch'; + +export { classifyChange, devClassifier } from './dev-classify'; export const DEV_DEFAULT_ENTRY = 'src/main.ts'; /** Default debounce window (ms) collapsing a burst of file changes into one action. */ export const DEV_DEBOUNCE_MS = 120; -/** - * Precedence: the explicit argument, then the config's `entry`, then - * {@link DEV_DEFAULT_ENTRY}. - */ -export const resolveDevEntry = (config: BunmaskaConfig, explicit?: string): string => - explicit ?? config.entry ?? DEV_DEFAULT_ENTRY; - -/** - * Dependency, VCS and OUR-OWN-BUILD-OUTPUT directories. `dist` is deliberately NOT - * here: an app's renderer bundle lives there, and ignoring it meant a rebuilt - * bundle could never trigger a reload. The app bundles `bunmaska build` writes are - * ignored by suffix instead, because it defaults its output to the project root. - */ -const IGNORED_SEGMENTS: ReadonlySet = new Set([ - 'node_modules', - '.git', - 'build', - 'out', - 'coverage', -]); +const DEV_KILL_GRACE_MS = 3000; -/** - * Directory suffixes `bunmaska build` produces inside the watched root. - * ponytail: the Linux AppDir is a bare `/` with no suffix to match, so a - * Linux build during `dev` still churns; `--out` outside the root avoids it. - */ -const IGNORED_SEGMENT_SUFFIXES: readonly string[] = ['.app', '.AppDir']; - -/** TypeScript is compiled into the main process, so a change there restarts it. */ -const MAIN_SOURCE_EXTENSIONS: ReadonlySet = new Set(['.ts', '.tsx', '.mts', '.cts']); - -/** - * The preload is read and bundled once, when the window is constructed, so a - * reload would re-inject the STALE script. Restarting is the honest action. - * Matches the shipped-asset convention in {@link ../cli/app-assets}. - */ -const PRELOAD_BASENAME = /^preload\.(?:js|mjs|cjs|ts)$/i; - -export type ChangeAction = 'restart' | 'rebuild' | 'reload' | 'ignore'; +/** Resolves true once `promise` settles, or false after `ms`. */ +const settlesWithin = (promise: Promise | undefined, ms: number): Promise => + new Promise((resolvePromise) => { + const timer = setTimeout(() => resolvePromise(false), ms); + void Promise.resolve(promise).then(() => { + clearTimeout(timer); + resolvePromise(true); + }); + }); -/** - * Classify a changed path, relative to the watched root. Dotfiles are ignored - * because they catch editor swap files. With `rendererRoot` set (the directory - * of `config.renderer.entry`), a change under it is `rebuild`: the renderer is - * re-bundled and the resulting output writes live-reload the window, so a - * React component edit no longer restarts the whole app. - */ -export const classifyChange = (relPath: string, rendererRoot?: string): ChangeAction => { - const parts = relPath.split(/[\\/]/).filter((p) => p.length > 0); - const ignored = (p: string): boolean => - IGNORED_SEGMENTS.has(p) || IGNORED_SEGMENT_SUFFIXES.some((suffix) => p.endsWith(suffix)); - if (parts.some(ignored)) { - return 'ignore'; - } - const base = parts[parts.length - 1] ?? ''; - if (base.length === 0 || base.startsWith('.')) { - return 'ignore'; - } - if (PRELOAD_BASENAME.test(base)) { - return 'restart'; - } - if (rendererRoot !== undefined) { - const rootParts = rendererRoot.split(/[\\/]/).filter((p) => p.length > 0); - const underRoot = - rootParts.length > 0 && - rootParts.length < parts.length && - rootParts.every((part, i) => parts[i] === part); - if (underRoot) { - return 'rebuild'; - } - } - return MAIN_SOURCE_EXTENSIONS.has(extname(base).toLowerCase()) ? 'restart' : 'reload'; -}; +/** The explicit entry, then the config's `entry`, then {@link DEV_DEFAULT_ENTRY}. */ +export const resolveDevEntry = (config: BunmaskaConfig, explicit?: string): string => + explicit ?? config.entry ?? DEV_DEFAULT_ENTRY; -/** Debounce-window precedence: a restart beats a rebuild beats a reload. */ +/** Debounce-window precedence: a restart (which rebuilds first) beats a rebuild beats a reload. */ const ACTION_RANK: Record, number> = { restart: 3, rebuild: 2, reload: 1, }; -/** The two content-comparison modes the watcher needs. Same seen-map underneath. */ -export type ContentFilter = { - /** - * First sight passes (a newly created file is a real change); thereafter only - * a byte change passes. A vanished file always passes (a deletion is real). - */ - changed(relPath: string): boolean; - /** - * Strict: passes only for a path already seen whose bytes changed; an unseen - * path is silently seeded. Used when rescanning a directory on an editor - * temp-file event, where first-sight-passes would fire every untouched - * sibling. - */ - changedIfSeen(relPath: string): boolean; -}; - -/** - * Drop events whose file content did not actually change. `fs.watch` fires on a - * metadata-only touch, and a formatter that rewrites identical bytes fires too; - * both would otherwise restart the app. `readFile` is a seam so this tests - * without the filesystem. - */ -export const makeContentFilter = ( - readFile: (relPath: string) => string | undefined, -): ContentFilter => { - const seen = new Map(); - const hashOf = (relPath: string): string | undefined => { - const contents = readFile(relPath); - return contents === undefined ? undefined : String(Bun.hash(contents)); - }; - return { - changed(relPath) { - const hash = hashOf(relPath); - if (hash === undefined) { - seen.delete(relPath); - return true; - } - if (seen.get(relPath) === hash) { - return false; - } - seen.set(relPath, hash); - return true; - }, - changedIfSeen(relPath) { - const hash = hashOf(relPath); - if (hash === undefined) { - seen.delete(relPath); - return false; - } - const previous = seen.get(relPath); - seen.set(relPath, hash); - return previous !== undefined && previous !== hash; - }, - }; -}; - -/** - * The parent directory of an editor temp-file event, or `undefined` when the - * event is not one. An atomic save (write temp + rename) can coalesce under - * FSEvents into a SINGLE event for the dot-named temp file (`.!1234!main.ts` - * from BSD sed, swap files, etc.), so ignoring dot basenames outright loses the - * save; the caller rescans this directory instead. Pure. - */ -export const editorTempDir = (relPath: string): string | undefined => { - const parts = relPath.split(/[\\/]/).filter((p) => p.length > 0); - const ignored = (p: string): boolean => - IGNORED_SEGMENTS.has(p) || IGNORED_SEGMENT_SUFFIXES.some((suffix) => p.endsWith(suffix)); - if (parts.length === 0 || parts.some(ignored)) { - return undefined; - } - const base = parts[parts.length - 1] ?? ''; - if (!base.startsWith('.')) { - return undefined; - } - return parts.slice(0, -1).join('/'); -}; - -/** Files bigger than this are not hashed at seed time (first-sight then applies). */ -const SEED_MAX_BYTES = 5_000_000; - -/** - * Hash every watchable file up front so the strict rescan mode has a baseline - * from the first save of the session, not the second. - */ -const seedContentFilter = (root: string, filter: ContentFilter, relDir = ''): void => { - let entries: Dirent[]; - try { - entries = readdirSync(resolve(root, relDir), { withFileTypes: true }); - } catch { - return; - } - for (const entry of entries) { - const name = entry.name; - if (name.startsWith('.')) { - continue; - } - const rel = relDir === '' ? name : `${relDir}/${name}`; - if (entry.isDirectory()) { - if ( - !IGNORED_SEGMENTS.has(name) && - !IGNORED_SEGMENT_SUFFIXES.some((suffix) => name.endsWith(suffix)) - ) { - seedContentFilter(root, filter, rel); - } - continue; - } - if (!entry.isFile()) { - continue; - } - try { - if (statSync(resolve(root, rel)).size > SEED_MAX_BYTES) { - continue; - } - } catch { - continue; - } - filter.changedIfSeen(rel); - } -}; - export type DevChild = { - readonly kill: () => void; - /** Ask the running child to live-reload its open windows (a renderer-only change). */ + /** SIGTERM, or SIGKILL when `force`. */ + readonly kill: (force?: boolean) => void; + /** Live-reload the child's open windows. */ readonly reload: () => void; /** - * Settles when the process is really gone. Awaited before respawning: `kill()` - * only delivers a signal, so spawning immediately leaves two live apps racing - * for the window and the single-instance lock. + * Settles when the process is gone. Await it before respawning: `kill()` only + * signals, and two live apps race for the window and the single-instance lock. */ readonly exited?: Promise; }; export type DevWatcher = { readonly close: () => void }; -/** Timers; defaults to the global setTimeout/clearTimeout. */ export type DevTimers = { readonly set: (fn: () => void, ms: number) => unknown; readonly clear: (handle: unknown) => void; @@ -240,12 +63,11 @@ export type DevDeps = { readonly timers: DevTimers; readonly log: (message: string) => void; readonly debounceMs?: number; - /** Overrides {@link classifyChange} (e.g. bound to a renderer root). */ + /** How long a killed child gets to exit before it is force-killed. */ + readonly killGraceMs?: number; + /** Defaults to {@link devClassifier} without a renderer. */ readonly classify?: (relPath: string) => ChangeAction; - /** - * Rebuild the configured renderer. Must not throw: a broken renderer edit - * must never take the dev loop down with it. - */ + /** Rebuild the configured renderer; also runs before every restart. A throw is logged. */ readonly rebuild?: () => void | Promise; }; @@ -253,12 +75,15 @@ export class DevSupervisor { readonly #entry: string; readonly #deps: DevDeps; readonly #debounceMs: number; + readonly #classify: (relPath: string) => ChangeAction; #child: DevChild; readonly #watcher: DevWatcher; #pending: unknown; #pendingAction: Exclude | undefined; #stopped = false; #restarting = false; + #rebuilding: Promise | undefined; + #rebuildAgain = false; #alive = true; /** Number of times the child has been (re)started, including the first spawn. */ starts = 1; @@ -268,6 +93,7 @@ export class DevSupervisor { this.#entry = entry; this.#deps = deps; this.#debounceMs = deps.debounceMs ?? DEV_DEBOUNCE_MS; + this.#classify = deps.classify ?? devClassifier(dir, entry); this.#child = this.#track(deps.spawn(entry)); this.#watcher = deps.watch(dir, (relPath) => { this.#onChange(relPath); @@ -278,11 +104,10 @@ export class DevSupervisor { if (this.#stopped) { return; } - const action = (this.#deps.classify ?? classifyChange)(relPath); + const action = this.#classify(relPath); if (action === 'ignore') { return; } - // The strongest action coalesced into the debounce window wins. this.#pendingAction = this.#pendingAction !== undefined && ACTION_RANK[this.#pendingAction] >= ACTION_RANK[action] ? this.#pendingAction @@ -307,15 +132,13 @@ export class DevSupervisor { return; } if (action === 'rebuild') { - // The rebuild's own output writes come back through the watcher as - // 'reload', so the window refreshes only once the new bundle exists. - void this.#deps.rebuild?.(); + // The bundle's writes come back through the watcher as reloads. + this.#rebuild(); return; } - // Reloading a child that already quit silently does nothing, and logging - // 'reloaded' at it is how the loop ends up pretending to drive a corpse. + // A reload sent to a child that already quit is silently lost. if (!this.#alive) { - this.#deps.log('app is not running — edit a main-process file to restart it'); + this.#deps.log('app is not running - edit a main-process file to restart it'); return; } this.#child.reload(); @@ -323,21 +146,59 @@ export class DevSupervisor { this.#deps.log('reloaded'); } + /** Single-flight: a request mid-build reruns once after it, so the last edit gets built. */ + #rebuild(): void { + const rebuild = this.#deps.rebuild; + if (rebuild === undefined) { + return; + } + if (this.#rebuilding !== undefined) { + this.#rebuildAgain = true; + return; + } + this.#rebuilding = (async () => { + do { + this.#rebuildAgain = false; + try { + await rebuild(); + } catch (error) { + this.#deps.log(`renderer rebuild failed: ${String(error)}`); + } + } while (this.#rebuildAgain && !this.#stopped); + this.#rebuilding = undefined; + })(); + } + async #restart(): Promise { + // A renderer edit coalesced into this restart must reach the new child. + this.#rebuild(); if (this.#restarting) { + // The restart in flight has not spawned yet and waits for this rebuild. return; } this.#restarting = true; try { const previous = this.#child; previous.kill(); - await previous.exited; + // A child that traps SIGTERM (a vetoed quit) would otherwise wedge every later restart. + const grace = this.#deps.killGraceMs ?? DEV_KILL_GRACE_MS; + if (!(await settlesWithin(previous.exited, grace))) { + this.#deps.log(`app did not exit ${grace}ms after SIGTERM; force-killed it`); + previous.kill(true); + await previous.exited; + } + // Spawning mid-build would load a stale or half-written bundle. + while (this.#rebuilding !== undefined) { + await this.#rebuilding; + } if (this.#stopped) { return; } this.#child = this.#track(this.#deps.spawn(this.#entry, { restart: true })); this.starts += 1; this.#deps.log(`restarted (${this.#entry})`); + } catch (error) { + this.#deps.log(`restart failed: ${String(error)}`); } finally { this.#restarting = false; } @@ -371,9 +232,7 @@ export class DevSupervisor { const defaultTimers: DevTimers = { set: (fn, ms) => setTimeout(fn, ms), - clear: (handle) => { - clearTimeout(handle as ReturnType); - }, + clear: (handle) => clearTimeout(handle as ReturnType), }; export const defaultDevDeps = ( @@ -382,18 +241,15 @@ export const defaultDevDeps = ( extraEnv: Readonly> = {}, ): DevDeps => ({ spawn: (entry, opts) => { - // `BUNMASKA_DEV` switches on the app's stdin reload listener; a piped stdin is - // how the supervisor delivers reload requests to it. `BUNMASKA_DEV_RESTART` - // tells a respawned app to show its window without taking focus from the - // editor the developer is typing in. - const proc = Bun.spawn(['bun', 'run', entry], { + // BUNMASKA_DEV turns on the app's stdin reload listener; BUNMASKA_DEV_RESTART + // shows a respawned window without stealing focus from the editor. + const proc = Bun.spawn([process.execPath, 'run', entry], { cwd, env: { ...process.env, ...extraEnv, BUNMASKA_DEV: '1', - // Dot-named so the watcher never classifies the state file itself. - BUNMASKA_DEV_STATE: resolve(cwd, '.bunmaska-dev-state.json'), + BUNMASKA_DEV_STATE: resolve(cwd, DEV_STATE_FILE), ...(opts?.restart ? { BUNMASKA_DEV_RESTART: '1' } : {}), }, stdin: 'pipe', @@ -402,12 +258,12 @@ export const defaultDevDeps = ( }); return { exited: proc.exited, - kill: () => { - proc.kill(); + kill: (force) => { + proc.kill(force === true ? 'SIGKILL' : undefined); }, reload: () => { try { - proc.stdin.write('reload\n'); + proc.stdin.write(`${DEV_RELOAD_COMMAND}\n`); proc.stdin.flush(); } catch { // The child may be mid-exit; a dropped reload is harmless. @@ -415,64 +271,12 @@ export const defaultDevDeps = ( }, }; }, - watch: (dir, onChange) => { - const filter = makeContentFilter((relPath) => { - try { - return readFileSync(resolve(dir, relPath), 'utf8'); - } catch { - return undefined; - } - }); - seedContentFilter(dir, filter); - // An atomic save may surface only as its temp-file event; find what really - // changed in that directory instead of dropping the save. - const rescan = (relDir: string): void => { - let entries: Dirent[]; - try { - entries = readdirSync(resolve(dir, relDir), { withFileTypes: true }); - } catch { - return; - } - for (const entry of entries) { - if (!entry.isFile() || entry.name.startsWith('.')) { - continue; - } - const rel = relDir === '' ? entry.name : `${relDir}/${entry.name}`; - if (classifyChange(rel) !== 'ignore' && filter.changedIfSeen(rel)) { - onChange(rel); - } - } - }; - const watcher = fsWatch(dir, { recursive: true }, (_event, filename) => { - if (filename === null) { - return; - } - const relPath = filename.toString(); - const tempDir = editorTempDir(relPath); - if (tempDir !== undefined) { - rescan(tempDir); - return; - } - // Classify before hashing so node_modules churn never costs a file read. - if (classifyChange(relPath) === 'ignore' || !filter.changed(relPath)) { - return; - } - onChange(relPath); - }); - return { - close: () => { - watcher.close(); - }, - }; - }, + watch: (dir, onChange) => watchTree(dir, onChange, log), timers: defaultTimers, log, }); -/** - * Resolves only once `awaitStop` signals stop (e.g. SIGINT); the supervisor is - * torn down either way. - */ +/** Supervise `entry` in `targetDir` until `awaitStop` resolves, then tear the supervisor down. */ export const runDev = async ( targetDir: string, entry: string, diff --git a/src/cli/engine-command.ts b/src/cli/engine-command.ts index bc111e79..ed177209 100644 --- a/src/cli/engine-command.ts +++ b/src/cli/engine-command.ts @@ -1,5 +1,10 @@ import { existsSync, statSync } from 'node:fs'; -import { compareEngineIds, isSystemEngine, parseEngineId } from '../common/engine-id'; +import { + compareEngineIds, + type EngineRef, + isSystemEngine, + parseEngineId, +} from '../common/engine-id'; import type { BunmaskaConfig } from '../common/config-schema'; import { currentArch, currentPlatform } from '../common/platform'; import type { EngineSubcommand } from './parse-args'; @@ -18,14 +23,12 @@ import { isInstalled, listInstalled, readLinks, - type StoreEnv, verifyEngine, -} from './engine-store'; +} from '../common/engine-store'; export type EngineCommandDeps = { /** The engine store root (the `webkit/` dir). */ readonly root: string; - readonly env: StoreEnv; readonly out: (text: string) => void; readonly err: (text: string) => void; /** Read a project's validated config (empty `{}` when none). */ @@ -33,7 +36,12 @@ export type EngineCommandDeps = { /** Defaults to {@link installFromDir}. */ readonly installDir?: (root: string, sourceDir: string) => Promise; /** Defaults to {@link installFromUrl} over the real fetch. */ - readonly installUrl?: (root: string, url: string, publicKeyPem: string) => Promise; + readonly installUrl?: ( + root: string, + url: string, + publicKeyPem: string, + expectedId: string | undefined, + ) => Promise; /** Defaults to {@link fetchEngineIndex} over the real fetch. */ readonly fetchIndex?: (feedBase: string) => Promise; }; @@ -51,10 +59,29 @@ const sortIds = (ids: readonly string[]): string[] => /** The pinned engine declared by a project's config (defaults to the system sentinel). */ const configPin = (config: BunmaskaConfig): string => config.engine?.webkit ?? 'system'; +type PinState = 'system' | 'bare' | 'foreign' | 'installed' | 'missing'; + +/** How this machine treats a pin; `foreign` = built for another os/arch, never loaded here. */ +const pinState = (pin: string, root: string): PinState => { + if (isSystemEngine(pin)) { + return 'system'; + } + let ref: EngineRef; + try { + ref = parseEngineId(pin); + } catch { + return 'bare'; + } + if (ref.os !== currentPlatform() || ref.arch !== currentArch()) { + return 'foreign'; + } + return isInstalled(root, pin) ? 'installed' : 'missing'; +}; + const runList = (deps: EngineCommandDeps): number => { const installed = listInstalled(deps.root); if (installed.length === 0) { - deps.out('No engines installed — apps use the system WebKit by default.'); + deps.out('No engines installed: apps use the system WebKit by default.'); return 0; } const refs = new Map(); @@ -103,18 +130,22 @@ const runAvailable = async (deps: EngineCommandDeps): Promise => { const runWhich = async (target: string | undefined, deps: EngineCommandDeps): Promise => { const config = await deps.readConfig(target ?? '.'); const pin = configPin(config); - if (isSystemEngine(pin)) { - deps.out('system — uses the OS WebView (no pinned engine)'); - return 0; - } - try { - parseEngineId(pin); - const state = isInstalled(deps.root, pin) - ? 'installed' - : 'NOT installed — run `bunmaska engine install`'; - deps.out(`${pin} [${state}]`); - } catch { - deps.out(`${pin} (bare upstream — resolved to a full engine-id at build time)`); + switch (pinState(pin, deps.root)) { + case 'system': + deps.out('system: uses the OS WebView (no pinned engine)'); + break; + case 'bare': + deps.out(`${pin} (bare version, not resolved yet: builds bake \`system\`; pin a full id)`); + break; + case 'foreign': + deps.out(`${pin} [built for another os/arch, not used on this machine]`); + break; + case 'installed': + deps.out(`${pin} [installed]`); + break; + case 'missing': + deps.out(`${pin} [NOT installed: run \`bunmaska engine install\`]`); + break; } return 0; }; @@ -137,9 +168,8 @@ const isBareEngineId = (source: string): boolean => { const runInstall = async (source: string, deps: EngineCommandDeps): Promise => { const isUrl = /^https?:\/\//.test(source); - // A local, already-extracted engine directory wins over feed routing — a dir - // whose name happens to be a valid engine-id must not be shadowed by the feed, - // and a local install never reads (or is broken by) bunmaska.config. + // A local dir wins over feed routing (even one named like an engine-id), and a + // local install never reads, or is broken by, bunmaska.config. if (!isUrl && existsSync(source) && statSync(source).isDirectory()) { const install = deps.installDir ?? installFromDir; deps.out(installedMessage(await install(deps.root, source))); @@ -158,37 +188,23 @@ const runInstall = async (source: string, deps: EngineCommandDeps): Promise installFromUrl(root, u, key, { fetch: defaultRemoteFetch })); - try { - deps.out(installedMessage(await installUrl(deps.root, url, publicKey))); - return 0; - } catch (error) { - deps.err(`bunmaska engine install: ${error instanceof Error ? error.message : String(error)}`); - return 1; - } + ((root, u, key, expectedId) => + installFromUrl(root, u, key, { + fetch: defaultRemoteFetch, + ...(expectedId === undefined ? {} : { expectedId }), + })); + deps.out( + installedMessage(await installUrl(deps.root, url, publicKey, isUrl ? undefined : source)), + ); + return 0; }; const runUse = (id: string, forDir: string | undefined, deps: EngineCommandDeps): number => { if (!isSystemEngine(id)) { - try { - parseEngineId(id); - } catch (error) { - deps.err(`bunmaska engine use: ${error instanceof Error ? error.message : String(error)}`); - return 1; - } + parseEngineId(id); } const where = forDir ?? '.'; deps.out( @@ -210,21 +226,20 @@ const runPrune = async ( force: boolean, deps: EngineCommandDeps, ): Promise => { - // Refcounts are populated by apps at launch. Before any app has registered, - // every engine looks unreferenced — so a plain prune would wipe the whole - // store. Refuse that case unless explicitly forced (or just previewing). + // Apps register links at launch, so before any has, every engine looks + // unreferenced and a plain prune would wipe the whole store. const installed = listInstalled(deps.root); if (!dryRun && !force && installed.length > 0 && readLinks(deps.root).length === 0) { deps.out( `Refusing to prune: no app has registered a dependency yet, so all ${installed.length} ` + - 'installed engine(s) look unreferenced. Apps register on launch — re-run with --force ' + + 'installed engine(s) look unreferenced. Apps register on launch; re-run with --force ' + 'to prune anyway, or --dry-run to preview.', ); return 0; } const result = await gc(deps.root, { dryRun }); if (result.removed.length === 0) { - deps.out('Nothing to prune — every installed engine is still referenced.'); + deps.out('Nothing to prune: every installed engine is still referenced.'); } else { deps.out( `${dryRun ? 'Would remove' : 'Removed'} ${result.removed.length} unreferenced engine(s):`, @@ -238,7 +253,7 @@ const runPrune = async ( } deps.out(`Kept ${result.kept.length} referenced engine(s).`); if (dryRun) { - deps.out('(dry run — nothing was deleted)'); + deps.out('(dry run: nothing was deleted)'); } return 0; }; @@ -256,11 +271,7 @@ const runVerify = (id: string, deps: EngineCommandDeps): number => { return 1; }; -/** Run a `bunmaska engine ` command and resolve to the process exit code. */ -export const runEngine = async ( - sub: EngineSubcommand, - deps: EngineCommandDeps, -): Promise => { +const dispatch = async (sub: EngineSubcommand, deps: EngineCommandDeps): Promise => { switch (sub.action) { case 'list': return runList(deps); @@ -279,46 +290,69 @@ export const runEngine = async ( } }; -/** - * Exits non-zero only when the project pins a full engine-id that is not - * installed. - */ -export const runDoctor = async ( - target: string | undefined, +/** Print a failure as one `bunmaska