Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(tui)!: move the vendored renderer to ink 8.0.0; require Node 22
Salman Qureshi5a1459b5956f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 719c560b..d8fad2ba 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -18,8 +18,6 @@ jobs:fail-fast: falsematrix:include:- - os: ubuntu-latest- node: 20- os: ubuntu-latestnode: 22- os: ubuntu-latest@@ -65,8 +63,6 @@ jobs:fail-fast: falsematrix:include:- - os: ubuntu-latest- node: 20- os: ubuntu-latestnode: 22- os: ubuntu-latestdiff --git a/.lint-baseline.json b/.lint-baseline.jsonindex 76cc8c0a..2f5446f8 100644--- a/.lint-baseline.json+++ b/.lint-baseline.json@@ -1,11 +1,11 @@{"$comment": "ESLint ratchet baseline. Per-rule counts (errors + warnings) may only go down. Refresh with `npm run lint:ratchet -- --update` after a clean-up.","provisional": false,- "generatedAt": "2026-10-10T06:55:02.126Z",+ "generatedAt": "2026-10-10T07:52:30.812Z","target": "src","rules": {"(unknown)": 1,- "@typescript-eslint/no-explicit-any": 1159,+ "@typescript-eslint/no-explicit-any": 1145,"@typescript-eslint/no-require-imports": 6,"@typescript-eslint/no-this-alias": 5,"@typescript-eslint/no-unused-expressions": 100,diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1217baac..f60587af 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,15 @@# Changelog+## Unreleased — ink 8++Mercury's terminal renderer moves from a heavily patched ink 5.2.1 to ink 8.0.0, which now does most of that work itself.++- **Requires Node.js 22 or newer.** Ink 7+ needs it, and Node 20 reached end of life in April 2026. On an older Node, Mercury now exits with a clear upgrade message instead of crashing at the first render.+- **Smoother rendering** — incremental rendering rewrites only the changed part of each line, and every frame is painted atomically (synchronized output).+- **Upstream fixes Mercury lacked** — CJK and emoji truncation, control characters stripped from rendered text, dropped keypresses when several keys arrive together, Backspace vs Delete, Windows stale frames, and many `<Static>` fixes.+- **Smaller patch** — four Mercury hunks remain (Static `itemKey`, freeze gate, live-region guard, cursor anchor); the rest are upstream. See `docs/ink-patch.md` and ADR-019.+- React 19.3.+## 1.3.1 — Honest MercuryThe release where Mercury stops pretending. Chat answers instead of forcing tool rounds, "done" means a check actually passed, every channel shows the same evidence, and the terminal UI takes paste, Esc and IME like a real editor. Built from a full audit (`ROADMAP.md`); every change below is covered by tests, including a replay eval harness that drives the real agent loop.diff --git a/DECISIONS.md b/DECISIONS.mdindex 5679862a..20d0b2ce 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -162,3 +162,10 @@- sql.js (WASM) as the universal engine — asynchronous init, whole-file-in-memory, no WAL; already used only as the dashboard's read-only fallback and unsuitable as a durable write path for the queue.- Making JSON the only store — loses FTS5 search for Second Brain and the lease semantics the bots queue relies on.- **Consequence**: Standalone binaries get Second Brain, bots and boards on bun:sqlite with no native addon; Node 22.13+ installs work without a compiler; Node 20 keeps better-sqlite3 (a single process never mixes engines, but the files are plain SQLite so switching runtimes keeps the data). Node 22.5–22.12 only expose node:sqlite behind `--experimental-sqlite`, and Node 22.x prints one `ExperimentalWarning` when it loads. The driver's contract test (`src/utils/sqlite-driver.test.ts`) runs the same assertions against every engine the test process can load — CI should run it under Node 20, Node 22+ and `bun test` (P2.6). FTS5 is required from every engine (Node's and Bun's builds ship it). New SQLite call sites must go through the driver, bind named parameters with bare keys, and never assume `get()` returns `null`.++## ADR-019: Move the vendored renderer to ink 8; require Node 22++- **Context**: ADR-017 vendored ink 5.2.1 with seven Mercury hunks (eight after synchronized output). Upstream reached 8.0.0 with most of that work done properly: incremental rendering, synchronized output, a cursor API, Yoga free-node hygiene, scrollback-preserving fullscreen handling, and dozens of `<Static>`, input, CJK-text and Windows fixes Mercury did not have. Each ink upgrade on the old base meant re-implementing those by hand. Ink 7+ requires Node 22 and ink 8 requires React 19.3.+- **Decision**: Vendor ink 8.0.0 (same pipeline as ADR-017) and keep only what upstream still lacks: `<Static itemKey>`, the freeze gate, the live-region guard (trim instead of writing an over-tall frame, which on ink 8 pushes copies of the live region into scrollback), and a small cursor-anchor hunk that resolves Mercury's `internal_cursor` cell after layout and feeds it to ink's own `setCursorPosition`. Mercury turns on `incrementalRendering`, and after the output wrapper sheds writes it calls `instance.clear()` so the next frame is a full repaint. React moves to 19.3; `engines.node` to `>=22`; the build target to `node22`; CI drops Node 20. The bundle banner exits with a clear message on Node < 22 (Bun is exempt) instead of failing at the first render.+- **Alternatives considered**: backport ink 6–8 fixes into the 5.2.1 fork one by one (rebuilds ink 8 by hand, and every fix touches internals that changed); move to OpenTUI (native renderer, but needs Node ≥ 26.4 with `--experimental-ffi` or Bun, has no Android build for Termux, and is pre-1.0); stay on ink 5 and Node 20 (Node 20 reached end of life in April 2026).+- **Consequence**: The patch shrinks from about a thousand lines to 168 (`patches/ink+8.0.0.patch`). Node 20 users must upgrade before installing; `mercury doctor` and the docs say Node 22. Hardware-cursor and live-region tests now assert the result on an emulated terminal (`src/ui/vt-screen.ts`) instead of exact escape bytes, so they survive ink's encoding choices. The SQLite driver keeps better-sqlite3 first; Node 22.13+ also has `node:sqlite` (ADR-018).diff --git a/README.md b/README.mdindex ce6ed706..62ea711b 100644--- a/README.md+++ b/README.md@@ -44,7 +44,7 @@ curl -fsSL https://mercuryagent.sh/install.sh | shirm https://mercuryagent.sh/install.ps1 | iex```-Or via npm if you already have Node.js 20+:+Or via npm if you already have Node.js 22+:```bashnpx @cosmicstack/mercury-agent@@ -385,7 +385,7 @@ Plus community-driven compat providers (LiteLLM, GitHub Copilot model endpoints)## Architecture-- **TypeScript + Node.js 20+** — ESM, tsup build+- **TypeScript + Node.js 22+** — ESM, tsup build- **Vercel AI SDK v6** — `generateText` + `streamText`, agentic step loop, provider fallback, OpenAI-compat routing- **grammY** — Telegram bot with typing indicators, editable streaming, auto-retry, and file uploads- **discord.js / @slack/bolt / signal-cli** — Discord, Slack (Socket Mode), and E2E-encrypted Signal bridgesdiff --git a/docs/ink-patch.md b/docs/ink-patch.mdindex 1c3f7611..e59a6ae3 100644--- a/docs/ink-patch.md+++ b/docs/ink-patch.md@@ -1,109 +1,72 @@# Mercury's ink patch set-Mercury renders its TUI with [ink](https://github.com/vadimdemedes/ink) 5.2.1 and carries seven fixes to it. Since ADR-017 the patched build is vendored in `vendor/ink/` and bundled into `dist/index.js`, so no install step has to apply them. This page describes each hunk, why it exists, and what an upstream version could look like.+Mercury renders its TUI with [ink](https://github.com/vadimdemedes/ink) 8.0.0 and carries four changes to it. Since ADR-017 the patched build is vendored in `vendor/ink/` and bundled into `dist/index.js`, so no install step has to apply them. This page describes each hunk, why it exists, and what an upstream version could look like.| Item | Where ||---|---|| Single source of truth for the hunks | `scripts/apply-ink-patch.cjs` || Regenerate `vendor/ink` (stock tarball + hunks) | `node scripts/vendor-ink.cjs` || Prove the committed files are exactly tarball + hunks | `node scripts/vendor-ink.cjs --check` (runs in CI) |-| Reviewable stock-vs-vendored diff | `patches/ink+5.2.1.patch` (generated) |+| Reviewable stock-vs-vendored diff | `patches/ink+8.0.0.patch` (generated) || Runtime detection / `mercury doctor` | `src/ui/ink-patch-check.ts` || Bundler and test wiring | `tsup.config.ts` (alias + `noExternal`), `vitest.config.ts`, `tsconfig.json` `paths` |`vendor/ink` holds only what the runtime needs: `build/` without source maps (and without the `sourceMappingURL` trailers that pointed at them), a `package.json` with ink's development-only fields removed, and the MIT `license`. The stock tarball is verified against its registry `sha512` before anything is copied.-Every hunk is idempotent and anchors on exact ink 5.2.1 source text. If an anchor is missing, the applier fails loudly instead of skipping the hunk. Each hunk also leaves a marker, so `isPatched()` and the runtime check can confirm it was applied.+Every hunk anchors on exact ink 8.0.0 source text. If an anchor is missing or ambiguous, the applier fails and names the hunk instead of skipping it. Each hunk leaves a marker, so `isPatched()` and the runtime check can confirm it was applied.----## 1. Yoga free-node hygiene (`reconciler.js`)+## 1. `<Static itemKey>` (`components/Static.js`, `Static.d.ts`)-**Problem.** When React removes a subtree, ink calls `yogaNode.freeRecursive()`, which releases the Yoga WASM memory. The JavaScript DOM nodes still keep their `yogaNode` references to that freed memory. Later layout or render passes can still reach those nodes: through the root's cached `staticNode`, through the parent climb in `measure`, or through an in-flight throttled render. Reading a freed node traps inside WASM with `RuntimeError: memory access out of bounds` in `getComputedWidth`, which crashes the process. Long Mercury sessions hit this regularly.+**Problem.** `<Static>` decides which items are new with a positional index (`items.slice(index)`), which assumes `items` only ever grows. Mercury keeps the transcript bounded by sliding a window (the newest 100 messages). Once the window starts dropping old items, the index points past the end, new messages never render, and every commit unmounts the whole static subtree.-**Fix.** Removals now go through `cleanupRemovedNode`:+**Fix.** An optional `itemKey(item) => string | undefined` prop. When it is set, `<Static>` tracks the keys it has already written and renders only unseen items, so each item is printed exactly once per instance even when the window slides. After writing, it bumps a `commitTick` so the written children unmount; otherwise they stay mounted and are re-emitted as static output on every later frame. The positional path is unchanged when `itemKey` is absent.-- Free the Yoga subtree as before.-- Walk the removed DOM subtree and set every `yogaNode` to `undefined`. The walk skips `#text` nodes, which have no `childNodes`.-- If the removed subtree contains the root's cached `staticNode`, clear that cache too. `removeChild` receives the direct parent, so the hunk climbs to the root before checking.+**Upstream.** Still needed on ink 8, whose `<Static>` is positional. Additive, opt-in API: the prop plus the `commitTick` unmount, with a test that slides a bounded window. The best candidate to propose.-The renderer already reads `yogaNode` through optional chaining, so a cleared reference becomes a no-op instead of a crash. The hunk sets `globalThis.__mercuryInkYogaHygiene = true` so the bundled build can be checked without reading files.+## 2. Freeze gate (`ink.js`)-**Upstream.** This is a pure bug fix with no API change. It matches the analysis in [facebook/yoga#1818](https://github.com/facebook/yoga/issues/1818), and qwen-code#7816 applies the same fix downstream. It is the strongest candidate to propose first.+**Problem.** Mercury's scroll lock (Ctrl+S, `/mc freeze`) lets users scroll and copy from native scrollback while output keeps arriving. Any frame ink writes during that time moves the viewport. Skipping frames is not enough on its own: if `lastOutput` or log-update's baseline advances, the first frame after resume diffs against rows that were never drawn and erases the wrong lines.-## 2. `<Static itemKey>` (`components/Static.js`, `Static.d.ts`)+**Fix.** `export const frameGate = { frozen, armed, marker }`, also exposed as `globalThis.__mercuryFrameGate`. While `frozen` is set, `onRender` returns right after `render()`, before `renderFrame()` writes anything or touches a baseline. `armed` + `marker` let exactly one frame through, the one that contains the "⏸ frozen" hint.-**Problem.** `<Static>` decides which items are new with a positional index (`items.slice(index)`), which assumes `items` only ever grows. Mercury keeps the transcript bounded by sliding a window (the newest 100 messages). Once the window starts dropping old items, the index points past the end, new messages never render, and every commit unmounts the whole static subtree, churning freed Yoga nodes and feeding hunk 1's crash.+**Upstream.** Ink 7.1's `suspendTerminal()` hands the terminal to a child process, which is close but not the same. A public `instance.pause()` / `instance.resume()` with the same no-baseline-advance guarantee would replace this.-**Fix.** Add an optional `itemKey(item) => string | undefined` prop. When it is set, `<Static>` tracks the keys it has already written and renders only unseen items, so each item is printed exactly once per instance even when the window slides. After writing, it bumps a `commitTick` so the written children unmount. Without that bump, ink's renderer re-prints still-mounted static children on every later frame, which duplicates transcript lines. The positional path is unchanged when `itemKey` is absent.+## 3. Live-region guard (`ink.js`)-**Upstream.** Additive, opt-in API. The proposal is the prop plus the `commitTick` unmount, with a test that slides a bounded window.+**Problem.** When the live frame is as tall as the terminal or taller, ink writes the whole frame. On the primary screen every row past the viewport scrolls into scrollback, so each repaint while a reply streams stamps another copy of the top of the live region into the user's history. (Ink 5 was worse: it cleared the scrollback and re-dumped every static byte. Ink 8 fixed that half.)-## 3. Freeze gate (`ink.js`)+**Fix.** On an interactive TTY, outside the alternate screen and screen-reader mode, a frame of `rows` or more is trimmed to its newest `rows - 1` rows before `renderFrame()`, anchored at the bottom so the input and status bar stay visible. The trimmed rows are never written, so they cannot reach scrollback. `src/ui/live-region-guard.test.tsx` fails if this hunk is removed.-**Problem.** Mercury's scroll lock (Ctrl+S, `/mc freeze`) lets users scroll and copy from native scrollback while output keeps arriving. Any frame ink writes during that time moves the viewport. Simply skipping frames is not enough: if `lastOutput` or log-update's baseline advances, the first frame after resume diffs against rows that were never drawn and erases the wrong lines.+**Upstream.** A behaviour option such as `overflow: 'trim-top' | 'write'`, defaulting to today's behaviour.-**Fix.** `export const frameGate = { frozen, armed, marker }`, also exposed as `globalThis.__mercuryFrameGate`. While `frozen` is set, `onRender` returns before writing anything or touching either baseline. `armed` + `marker` let exactly one frame through, the one that contains the "⏸ frozen" hint.+## 4. Cursor anchor (`ink.js`) — #41, #66-**Upstream.** Probably better as a public instance API, `instance.pause()` / `instance.resume()`, with the same no-baseline-advance guarantee than as a global. Medium priority.+**Problem.** Input methods (Chinese, Japanese and Korean IMEs, the macOS accent picker, dictation) open their preedit text and candidate window at the hardware cursor. Ink 8 can place the real cursor (`useCursor()` → `setCursorPosition({ x, y })`), but the caller must supply the coordinates, and React has no cheap way to know where an inline cell lands after layout.-## 4. Live-region guard (`ink.js`)+**Fix.** Mercury's `CursorCell` marks its element with an `internal_cursor` attribute. After `render()` (and after the live-region trim), `onRender` walks the laid-out live tree, sums Yoga offsets to the marked element exactly as the renderer does, and hands `{ x, y }` to ink's own `setCursorPosition`, so ink's log-update shows the cursor there and hides it before the next write. Only a change is pushed, because a dirty cursor forces ink to rewrite an otherwise unchanged frame. No marked element (a prompt or a non-input pane owns the keyboard) means `undefined`: the cursor stays hidden. `cursorAnchor.enabled = false` (`MERCURY_HW_CURSOR=0`) turns it off.-**Problem.** When the live frame is as tall as the terminal or taller, stock ink falls back to `clearTerminal + fullStaticOutput + output`. That wipes the whole scrollback (`ESC[3J`) and re-prints every static byte ever written, on every frame. With a long transcript that is megabytes per frame: the scrollbar jumps to the top, the UI flickers, and native scrolling stops working.+The attribute is read from ink's DOM node rather than a ref because React attaches refs in the layout phase, after the frame has already been rendered, so a ref-based anchor would always be one frame late. Nothing is inserted into the frame text.-**Fix.** Trim the frame to the newest `rows - 1` rows, anchored at the bottom so the input and status bar stay visible, and send it through the normal diff path. Scrollback is never cleared and the transcript is never re-dumped.+**Upstream.** A layout-aware variant of `useCursor()` — for example `useCursor({ anchor: ref })` resolved inside ink after layout — would replace this hunk.-**Upstream.** A behaviour change. It could ship as an option such as `overflow: 'trim-top' | 'clear'`, with the current behaviour as the default. The full-scrollback wipe is arguably always wrong for apps that use `<Static>`.--## 5. Diff-render (`log-update.js`)--**Problem.** Ink 5's log-update erases and rewrites the entire live region on every change. A spinner tick or a selection change in a prompt repaints every row, which shows up as a full-UI flash, especially over SSH and in tmux.--**Fix.** Compare the previous and next frames row by row. Leave the unchanged leading rows in place and erase and rewrite only from the first changed row. The erase count follows the same trailing-newline accounting as `previousLineCount`, so `clear()` and the cursor arithmetic stay consistent.--**Upstream.** Ink 6 moved towards incremental rendering. A backport to 5.x would be this hunk alone; it needs no API change.--## 6. Resize baseline invalidate (`ink.js`, `log-update.js`)--**Problem.** After a resize the terminal re-wraps the rows already on screen, so identical row bytes no longer sit on the same terminal rows. Hunk 5's "unchanged rows stay" assumption no longer holds, and stale fragments survive the next frame.--**Fix.** `log.invalidate()` forgets `previousOutput` but keeps the line count, so the old frame is still fully erased. `resized()` calls it and resets `lastOutput` before re-layout, which makes the next frame a full repaint.--**Upstream.** Belongs with hunk 5; it is only needed once diff-render exists.--## 7. Hardware cursor positioning (`ink.js`, `log-update.js`) — #41, #66--**Problem.** Ink hides the terminal cursor for its whole lifetime and leaves it on the line below the live region. Input methods (Chinese, Japanese and Korean IMEs, the macOS accent picker, dictation) open their preedit text and candidate window at the hardware cursor, so they appear in the wrong place. Some terminals suppress composition entirely while the cursor is hidden; Windows Terminal and some iTerm2 input methods have been reported to. Apps can only draw a fake cursor (an inverse cell), and the IME cannot see it.--**Fix.**--- A host marks its cursor cell with the `internal_cursor` host attribute; in Mercury this is `CursorCell` in `src/ui/cursor-anchor.tsx`. After each frame, and after the live-region trim, `onRender` walks the live tree. It skips `<Static>` and `display: none` subtrees and adds up Yoga offsets exactly as `render-node-to-output` does, which gives the cell's `{row, col}` inside the frame.-- `log(output, cursor)` writes the frame and then parks the cursor on that cell: `CUU n` + `CHA col` + `CSI ?25h`. Before any later write (`render`, `clear`, `done`, console re-logs) it unparks: `CSI ?25l` + `CUD n` + `CHA 1`. The erase arithmetic therefore always starts from the position it assumes: below the last row, column 0.-- The moves are relative on purpose. The live region's absolute row is unknown without a DSR round-trip, so absolute `CUP` would need terminal queries.-- If only the cursor moved and the rows are byte-identical, ink writes just the unpark/park pair. No frame text is written.-- With no marked element, for example while a prompt or a non-input pane owns the keyboard, the cursor stays hidden. `cursorAnchor.enabled = false` turns the feature off globally; Mercury sets it from `MERCURY_HW_CURSOR=0`.--The attribute lives on ink's DOM node instead of a ref for a reason. React attaches refs during the layout phase, *after* `resetAfterCommit` has already rendered the committed frame, so a ref-based anchor would always be one frame late. Nothing is inserted into the frame text, so no sentinel can leak into the terminal.--**Upstream.** Ink has no cursor API in 5.x. A proposal could be a public `useCursor()` hook or a `<Cursor />` marker component that resolves the same way, plus the park/unpark contract in log-update. The tests in `src/ui/hardware-cursor.test.tsx` show the expected byte sequences: wide characters, diff frames, cursor-only moves, trim, `<Static>` output, resize and unmount.---## 8. Synchronized output (`ink.js`, `log-update.js`)--**Problem.** A frame reaches the terminal as an erase followed by a redraw, and a new transcript line takes three writes: erase the live region, print the line, redraw. Terminals paint between those steps, so the user briefly sees the region blank or half-drawn. That is the flicker in iTerm2, kitty, WezTerm, Ghostty and Windows Terminal, and it is worst while a reply streams.+----**Fix.** Bracket each update in BSU/ESU (`ESC[?2026h` … `ESC[?2026l`, DEC private mode 2026), so the terminal swaps the finished frame in at once.-- log-update brackets its own single writes. This also covers the throttled path, which writes after `onRender` returns.-- `Ink.synchronized()` brackets multi-write sequences (clear + static + frame, and the console write-through paths) as one update. log-update skips its own brackets while one is open.-- The gate matches upstream's `shouldSynchronize()`: a TTY, not CI, not debug.-- Terminals without mode 2026 ignore both sequences.+## Retired with the move to ink 8-**Upstream.** Ink 6.7 shipped this (#866). This hunk is a backport, and it goes away with the move to Ink 8.+These hunks existed on ink 5.2.1 and are now upstream behaviour, so the vendored build no longer carries them:----+| Former hunk | Replaced by (ink 8) |+|---|---|+| Yoga free-node hygiene | `freeYogaSubtree` nulls freed Yoga references; `clearStaticNodeIfContained` clears the cached static node |+| Diff-render | `incrementalRendering: true` (set in `CLIChannel.mountTUI`) |+| Resize baseline invalidate | ink 8's `resized()` and viewport handling; after shed writes Mercury calls `instance.clear()` so the next frame is a full repaint |+| Hand-rolled cursor park/unpark | log-update's cursor support, fed by hunk 4 |+| Synchronized output (DEC 2026) | built in since ink 6.7 |## Upgrading ink-1. Bump `INK_VERSION` and `INK_INTEGRITY` in `scripts/vendor-ink.cjs`. The integrity value is `dist.integrity` from `npm view ink@<v> dist.integrity`.-2. Run `node scripts/vendor-ink.cjs`. Any hunk whose anchor moved fails with a named error; re-anchor it in `scripts/apply-ink-patch.cjs`.-3. Review `patches/ink+<v>.patch`, then run `npx vitest run src/ui src/channels scripts/apply-ink-patch.test.ts` and `npx tsup && node dist/index.js --help`.+1. Bump `INK_VERSION` and `INK_INTEGRITY` in `scripts/vendor-ink.cjs`. The integrity value is `dist.integrity` from `npm view ink@<v> dist.integrity`. Bump the `ink` devDependency to the same exact version.+2. Run `node scripts/vendor-ink.cjs`. A hunk whose anchor moved fails with a named error; re-anchor it in `scripts/apply-ink-patch.cjs`, and check the release notes for hunks that upstream now covers.+3. Review `patches/ink+<v>.patch`, then run `npx vitest run src/ui src/channels scripts/apply-ink-patch.test.ts` and `npm run build && node dist/index.js --help`.diff --git a/package-lock.json b/package-lock.jsonindex 8aa81ba7..1ecb4be0 100644--- a/package-lock.json+++ b/package-lock.json@@ -29,7 +29,7 @@"ollama-ai-provider": "^1.2.0","pino": "^10.3.1","qrcode-terminal": "^0.12.0",- "react": "^18.3.1",+ "react": "^19.3.0","sql.js": "^1.14.1","string-width": "^7.2.0","undici": "^6.24.1",@@ -46,9 +46,9 @@"@types/node": "^22.13.0","@types/node-cron": "^3.0.11","@types/qrcode-terminal": "^0.12.2",- "@types/react": "^18.3.28",- "ink": "5.2.1",- "react-devtools-core": "^4.28.5",+ "@types/react": "^19.3.0",+ "ink": "^8.0.0",+ "react-devtools-core": "^7.0.1","tsup": "^8.4.0","typescript": "^5.7.0","vitest": "^3.0.0"@@ -149,16 +149,30 @@}},"node_modules/@alcalzone/ansi-tokenize": {- "version": "0.1.3",- "resolved": "https://registry.npmjs.org/@alcalzone/ansi-tokenize/-/ansi-tokenize-0.1.3.tgz",- "integrity": "sha512-3yWxPTq3UQ/FY9p1ErPxIyfT64elWaMvM9lIHnaqpyft63tkxodF5aUElYHrdisWve5cETkh1+KBw1yJuW0aRw==",+ "version": "0.3.1",+ "resolved": "https://registry.npmjs.org/@alcalzone/ansi-tokenize/-/ansi-tokenize-0.3.1.tgz",+ "integrity": "sha512-cUD0PT0YX+rImRhfn7BfMRduP/tX/Zqt/N0dHlAyn2RlcJssCb5KsCJkhln61eh9vuJDkH8wKn3L8zJzzWXPFg==","dev": true,+ "license": "MIT","dependencies": {"ansi-styles": "^6.2.1",- "is-fullwidth-code-point": "^4.0.0"+ "is-fullwidth-code-point": "^5.0.0"},"engines": {- "node": ">=14.13.1"+ "node": ">=18"+ }+ },+ "node_modules/@alcalzone/ansi-tokenize/node_modules/ansi-styles": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"}},"node_modules/@discordjs/builders": {@@ -1389,12 +1403,6 @@"integrity": "sha512-0ikrnug3/IyneSHqCBeslAhlK2aBfYek1fGo4bP4QnZPmiqSGRK+Oy7ZMisLWkesffJvQ1cqAcBnJC+8+nxIAg==","dev": true},- "node_modules/@types/prop-types": {- "version": "15.7.15",- "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",- "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",- "dev": true- },"node_modules/@types/qrcode-terminal": {"version": "0.12.2","resolved": "https://registry.npmjs.org/@types/qrcode-terminal/-/qrcode-terminal-0.12.2.tgz",@@ -1417,12 +1425,12 @@"peer": true},"node_modules/@types/react": {- "version": "18.3.28",- "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.28.tgz",- "integrity": "sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw==",+ "version": "19.3.0",+ "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",+ "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==","dev": true,+ "license": "MIT","dependencies": {- "@types/prop-types": "*","csstype": "^3.2.2"}},@@ -1680,12 +1688,13 @@}},"node_modules/ansi-styles": {- "version": "6.2.3",- "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",- "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-7.0.0.tgz",+ "integrity": "sha512-kKvt3m4uwzqL0wlkPd09CmljPJGOZZ4D0fP65sqFSvPkMRKhNi+74MgIJ5QxE6SxqB4t4KyUFGg8+n5zjo6hew==","dev": true,+ "license": "MIT","engines": {- "node": ">=12"+ "node": ">=22"},"funding": {"url": "https://github.com/chalk/ansi-styles?sponsor=1"@@ -1993,12 +2002,13 @@"optional": true},"node_modules/cli-boxes": {- "version": "3.0.0",- "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-3.0.0.tgz",- "integrity": "sha512-/lzGpEWL/8PfI0BmBOPRwp0c/wFNX1RdUML3jK/RcSBA9T8mZDdQpqYBKtCFTOfQbwPqWEOpjqW+Fnayc0969g==",+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-4.0.1.tgz",+ "integrity": "sha512-5IOn+jcCEHEraYolBPs/sT4BxYCe2nHg374OPiItB1O96KZFseS2gthU4twyYzeDcFew4DaUM/xwc5BQf08JJw==","dev": true,+ "license": "MIT","engines": {- "node": ">=10"+ "node": ">=18.20 <19 || >=20.10"},"funding": {"url": "https://github.com/sponsors/sindresorhus"@@ -2020,35 +2030,37 @@}},"node_modules/cli-truncate": {- "version": "4.0.0",- "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-4.0.0.tgz",- "integrity": "sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA==",+ "version": "6.1.1",+ "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-6.1.1.tgz",+ "integrity": "sha512-06p9vyLahLa4zkGcgsGxU6iEkSOiuI4fhCH6Emhe2lPAcoUv73n72DnODsnHA+5wwXGnV0n9M9/qOQJSjYhFhw==","dev": true,+ "license": "MIT","dependencies": {- "slice-ansi": "^5.0.0",- "string-width": "^7.0.0"+ "slice-ansi": "^9.0.0",+ "string-width": "^8.2.0"},"engines": {- "node": ">=18"+ "node": ">=22"},"funding": {"url": "https://github.com/sponsors/sindresorhus"}},- "node_modules/cli-truncate/node_modules/slice-ansi": {- "version": "5.0.0",- "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-5.0.0.tgz",- "integrity": "sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==",+ "node_modules/cli-truncate/node_modules/string-width": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz",+ "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==","dev": true,+ "license": "MIT","dependencies": {- "ansi-styles": "^6.0.0",- "is-fullwidth-code-point": "^4.0.0"+ "get-east-asian-width": "^1.5.0",+ "strip-ansi": "^7.1.2"},"engines": {- "node": ">=12"+ "node": ">=20"},"funding": {- "url": "https://github.com/chalk/slice-ansi?sponsor=1"+ "url": "https://github.com/sponsors/sindresorhus"}},"node_modules/code-excerpt": {@@ -2392,10 +2404,17 @@}},"node_modules/es-toolkit": {- "version": "1.46.1",- "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.46.1.tgz",- "integrity": "sha512-5eNtXOs3tbfxXOj04tjjseeWkRWaoCjdEI+96DgwzZoe6c9juL49pXlzAFTI72aWC9Y8p7168g6XIKjh7k6pyQ==",- "dev": true+ "version": "1.52.0",+ "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.52.0.tgz",+ "integrity": "sha512-XTNEJQh1tY1ZJVcf6ayP/2n4ZPyaHlW2FWs7xvw5ddPuhUVjLD3olQVQS7kf58JbAB48iL0uL/jerTrjtV3lDA==",+ "dev": true,+ "license": "MIT",+ "workspaces": [+ "docs",+ "benchmarks",+ "tests/types",+ "tests/browser-compat"+ ]},"node_modules/esbuild": {"version": "0.27.7",@@ -2939,43 +2958,43 @@"optional": true},"node_modules/ink": {- "version": "5.2.1",- "resolved": "https://registry.npmjs.org/ink/-/ink-5.2.1.tgz",- "integrity": "sha512-BqcUyWrG9zq5HIwW6JcfFHsIYebJkWWb4fczNah1goUO0vv5vneIlfwuS85twyJ5hYR/y18FlAYUxrO9ChIWVg==",+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/ink/-/ink-8.0.0.tgz",+ "integrity": "sha512-M2aFwZOqmkFxCwedy6xrP4E+DGoK57iahAFnfTqNyOyJ54O7DZzu027z/NI8EGy44Sw9O9BcbTF4QEUS2GHAtg==","dev": true,+ "license": "MIT","dependencies": {- "@alcalzone/ansi-tokenize": "^0.1.3",- "ansi-escapes": "^7.0.0",- "ansi-styles": "^6.2.1",+ "@alcalzone/ansi-tokenize": "^0.3.1",+ "ansi-escapes": "^7.3.0",+ "ansi-styles": "^7.0.0","auto-bind": "^5.0.1",- "chalk": "^5.3.0",- "cli-boxes": "^3.0.0",+ "chalk": "^6.0.1",+ "cli-boxes": "^4.0.1","cli-cursor": "^4.0.0",- "cli-truncate": "^4.0.0",+ "cli-truncate": "^6.0.0","code-excerpt": "^4.0.0",- "es-toolkit": "^1.22.0",+ "es-toolkit": "^1.52.0","indent-string": "^5.0.0",- "is-in-ci": "^1.0.0",+ "is-in-ci": "^2.0.0","patch-console": "^2.0.0",- "react-reconciler": "^0.29.0",- "scheduler": "^0.23.0",+ "quick-lru": "^7.3.0",+ "react-reconciler": "^0.34.0","signal-exit": "^3.0.7",- "slice-ansi": "^7.1.0","stack-utils": "^2.0.6",- "string-width": "^7.2.0",- "type-fest": "^4.27.0",- "widest-line": "^5.0.0",- "wrap-ansi": "^9.0.0",- "ws": "^8.18.0",+ "string-width": "^8.3.0",+ "terminal-size": "^4.0.1",+ "type-fest": "^5.10.0",+ "widest-line": "^6.0.0",+ "wrap-ansi": "^10.0.2","yoga-layout": "~3.2.1"},"engines": {- "node": ">=18"+ "node": ">=22"},"peerDependencies": {- "@types/react": ">=18.0.0",- "react": ">=18.0.0",- "react-devtools-core": "^4.19.1"+ "@types/react": ">=19.3.0",+ "react": ">=19.3.0",+ "react-devtools-core": ">=6.1.2"},"peerDependenciesMeta": {"@types/react": {@@ -2986,6 +3005,36 @@}}},+ "node_modules/ink/node_modules/chalk": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-6.0.1.tgz",+ "integrity": "sha512-/Ce6KNm3vIbWdMlNna6RVIZ/ICQxnJxCicet5LBKK9ZffBkqzDw0xh9EiKSljdRtiIQ1S1z4YgcscUUGzNCWrA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=22"+ },+ "funding": {+ "url": "https://github.com/chalk/chalk?sponsor=1"+ }+ },+ "node_modules/ink/node_modules/string-width": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz",+ "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "get-east-asian-width": "^1.5.0",+ "strip-ansi": "^7.1.2"+ },+ "engines": {+ "node": ">=20"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/ipaddr.js": {"version": "1.9.1","resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",@@ -3002,27 +3051,32 @@"license": "MIT"},"node_modules/is-fullwidth-code-point": {- "version": "4.0.0",- "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz",- "integrity": "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==",+ "version": "5.1.0",+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz",+ "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==","dev": true,+ "license": "MIT",+ "dependencies": {+ "get-east-asian-width": "^1.3.1"+ },"engines": {- "node": ">=12"+ "node": ">=18"},"funding": {"url": "https://github.com/sponsors/sindresorhus"}},"node_modules/is-in-ci": {- "version": "1.0.0",- "resolved": "https://registry.npmjs.org/is-in-ci/-/is-in-ci-1.0.0.tgz",- "integrity": "sha512-eUuAjybVTHMYWm/U+vBO1sY/JOCgoPCXRxzdju0K+K0BiGW0SChEL1MLC0PoCIR1OlPo5YAp8HuQoUlsWEICwg==",+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/is-in-ci/-/is-in-ci-2.0.0.tgz",+ "integrity": "sha512-cFeerHriAnhrQSbpAxL37W1wcJKUUX07HyLWZCW1URJT/ra3GyUTzBgUnh24TMVfNTV2Hij2HLxkPHFZfOZy5w==","dev": true,+ "license": "MIT","bin": {"is-in-ci": "cli.js"},"engines": {- "node": ">=18"+ "node": ">=20"},"funding": {"url": "https://github.com/sponsors/sindresorhus"@@ -3055,11 +3109,6 @@"node": ">=10"}},- "node_modules/js-tokens": {- "version": "4.0.0",- "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",- "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="- },"node_modules/json-schema": {"version": "0.4.0","resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz",@@ -3189,17 +3238,6 @@"integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==","license": "MIT"},- "node_modules/loose-envify": {- "version": "1.4.0",- "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",- "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",- "dependencies": {- "js-tokens": "^3.0.0 || ^4.0.0"- },- "bin": {- "loose-envify": "cli.js"- }- },"node_modules/loupe": {"version": "3.2.1","resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",@@ -3887,6 +3925,19 @@"resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz","integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg=="},+ "node_modules/quick-lru": {+ "version": "7.3.0",+ "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-7.3.0.tgz",+ "integrity": "sha512-k9lSsjl36EJdK7I06v7APZCbyGT2vMTsYSRX1Q2nbYmnkBqgUhRkAuzH08Ciotteu/PLJmIF2+tti7o3C/ts2g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/range-parser": {"version": "1.2.1","resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",@@ -3927,31 +3978,31 @@}},"node_modules/react": {- "version": "18.3.1",- "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",- "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",- "dependencies": {- "loose-envify": "^1.1.0"- },+ "version": "19.3.0",+ "resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz",+ "integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==",+ "license": "MIT","engines": {"node": ">=0.10.0"}},"node_modules/react-devtools-core": {- "version": "4.28.5",- "resolved": "https://registry.npmjs.org/react-devtools-core/-/react-devtools-core-4.28.5.tgz",- "integrity": "sha512-cq/o30z9W2Wb4rzBefjv5fBalHU0rJGZCHAkf/RHSBWSSYwh8PlQTqqOJmgIIbBtpj27T6FIPXeomIjZtCNVqA==",+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/react-devtools-core/-/react-devtools-core-7.0.1.tgz",+ "integrity": "sha512-C3yNvRHaizlpiASzy7b9vbnBGLrhvdhl1CbdU6EnZgxPNbai60szdLtl+VL76UNOt5bOoVTOz5rNWZxgGt+Gsw==","dev": true,+ "license": "MIT","dependencies": {"shell-quote": "^1.6.1","ws": "^7"}},"node_modules/react-devtools-core/node_modules/ws": {- "version": "7.5.11",- "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.11.tgz",- "integrity": "sha512-zS54Oen9bITtp7kp2XM3AydrCIq1D+HwJOuH+c+e4LfpL/lotP5osijd+UoMnxwAam1GN8R4KtLAyIrIcBNpiA==",+ "version": "7.5.13",+ "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz",+ "integrity": "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA==","dev": true,+ "license": "MIT","engines": {"node": ">=8.3.0"},@@ -3969,19 +4020,19 @@}},"node_modules/react-reconciler": {- "version": "0.29.2",- "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.29.2.tgz",- "integrity": "sha512-zZQqIiYgDCTP/f1N/mAR10nJGrPD2ZR+jDSEsKWJHYC7Cm2wodlwbR3upZRdC3cjIjSlTLNVyO7Iu0Yy7t2AYg==",+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.34.0.tgz",+ "integrity": "sha512-eVibvB1fc9j5Qf1KRkiM3GzRPBdjg2P6G6QV2f3P6Eb3OGMxRBhdg2rrUwjbV5JrQaJj8nOa8uajmmJA5tJWjQ==","dev": true,+ "license": "MIT","dependencies": {- "loose-envify": "^1.1.0",- "scheduler": "^0.23.2"+ "scheduler": "^0.28.0"},"engines": {"node": ">=0.10.0"},"peerDependencies": {- "react": "^18.3.1"+ "react": "^19.3.0"}},"node_modules/readable-stream": {@@ -4148,13 +4199,11 @@"license": "MIT"},"node_modules/scheduler": {- "version": "0.23.2",- "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",- "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",+ "version": "0.28.0",+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz",+ "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==","dev": true,- "dependencies": {- "loose-envify": "^1.1.0"- }+ "license": "MIT"},"node_modules/secure-json-parse": {"version": "2.7.0",@@ -4224,10 +4273,11 @@"license": "ISC"},"node_modules/shell-quote": {- "version": "1.8.4",- "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.4.tgz",- "integrity": "sha512-VsC6n6vz1ihYYyZZwX7YZSF5l5x36ca17OC+a69h94YqB7X6XLwf+5MOgynYir2SLFUbl8gIYvBo8K8RoNQ6bQ==",+ "version": "1.12.0",+ "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.12.0.tgz",+ "integrity": "sha512-PcByqNyT/38F2kDNi006HAMRJaULuBzq/FOsw3qdZvX/GA9W/jamDaRskgHjubHiftXK5sIFxLNkvrXUwcof6Q==","dev": true,+ "license": "MIT","engines": {"node": ">= 0.4"},@@ -4365,35 +4415,33 @@}},"node_modules/slice-ansi": {- "version": "7.1.2",- "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-7.1.2.tgz",- "integrity": "sha512-iOBWFgUX7caIZiuutICxVgX1SdxwAVFFKwt1EvMYYec/NWO5meOJ6K5uQxhrYBdQJne4KxiqZc+KptFOWFSI9w==",+ "version": "9.0.1",+ "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-9.0.1.tgz",+ "integrity": "sha512-aBY19bn/XA+hKOKX0qL7Z0UfdBsbQvc9hn993U8ALUjzxCvDcuZqLoRXjGJrUARWAlwMnsRVD9sw2AFNOYvalA==","dev": true,"license": "MIT","dependencies": {- "ansi-styles": "^6.2.1",- "is-fullwidth-code-point": "^5.0.0"+ "ansi-styles": "^6.2.3",+ "is-fullwidth-code-point": "^5.1.0"},"engines": {- "node": ">=18"+ "node": ">=22"},"funding": {"url": "https://github.com/chalk/slice-ansi?sponsor=1"}},- "node_modules/slice-ansi/node_modules/is-fullwidth-code-point": {- "version": "5.1.0",- "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz",- "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==",+ "node_modules/slice-ansi/node_modules/ansi-styles": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==","dev": true,- "dependencies": {- "get-east-asian-width": "^1.3.1"- },+ "license": "MIT","engines": {- "node": ">=18"+ "node": ">=12"},"funding": {- "url": "https://github.com/sponsors/sindresorhus"+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"}},"node_modules/sonic-boom": {@@ -4567,6 +4615,19 @@"node": ">= 6"}},+ "node_modules/tagged-tag": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/tagged-tag/-/tagged-tag-1.0.0.tgz",+ "integrity": "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=20"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/tar-fs": {"version": "2.1.4","resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz",@@ -4595,6 +4656,19 @@"node": ">=6"}},+ "node_modules/terminal-size": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/terminal-size/-/terminal-size-4.0.1.tgz",+ "integrity": "sha512-avMLDQpUI9I5XFrklECw1ZEUPJhqzcwSWsyyI8blhRLT+8N1jLJWLWWYQpB2q2xthq8xDvjZPISVh53T/+CLYQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/thenify": {"version": "3.3.1","resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz",@@ -4804,12 +4878,16 @@}},"node_modules/type-fest": {- "version": "4.41.0",- "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz",- "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==",+ "version": "5.10.0",+ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.10.0.tgz",+ "integrity": "sha512-NoSdpq/WEiAg5sjmBkmV/hfxv6HJH4NqPNrqjtSO5CwRmpsDfaf4begxW34KdJykH/l1yHtwBWQkCRdoXO8mPA==","dev": true,+ "license": "(MIT OR CC0-1.0)",+ "dependencies": {+ "tagged-tag": "^1.0.0"+ },"engines": {- "node": ">=16"+ "node": ">=20"},"funding": {"url": "https://github.com/sponsors/sindresorhus"@@ -5568,38 +5646,85 @@}},"node_modules/widest-line": {- "version": "5.0.0",- "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-5.0.0.tgz",- "integrity": "sha512-c9bZp7b5YtRj2wOe6dlj32MK+Bx/M/d+9VB2SHM1OtsUHR0aV0tdP6DWh/iMt0kWi1t5g1Iudu6hQRNd1A4PVA==",+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-6.0.0.tgz",+ "integrity": "sha512-U89AsyEeAsyoF0zVJBkG9zBgekjgjK7yk9sje3F4IQpXBJ10TF6ByLlIfjMhcmHMJgHZI4KHt4rdNfktzxIAMA==","dev": true,+ "license": "MIT","dependencies": {- "string-width": "^7.0.0"+ "string-width": "^8.1.0"},"engines": {- "node": ">=18"+ "node": ">=20"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/widest-line/node_modules/string-width": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz",+ "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "get-east-asian-width": "^1.5.0",+ "strip-ansi": "^7.1.2"+ },+ "engines": {+ "node": ">=20"},"funding": {"url": "https://github.com/sponsors/sindresorhus"}},"node_modules/wrap-ansi": {- "version": "9.0.2",- "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",- "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",+ "version": "10.0.2",+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-10.0.2.tgz",+ "integrity": "sha512-6OLRNZqRntVGBm26ghZ5eZhCuWWyOkRCSn8XsOIuq5stpCE/tjLbdozd93naILZig0lmD8ANfRwnhn0DLeXGlg==","dev": true,"license": "MIT","dependencies": {- "ansi-styles": "^6.2.1",- "string-width": "^7.0.0",- "strip-ansi": "^7.1.0"+ "ansi-styles": "^6.2.3",+ "string-width": "^8.2.0"},"engines": {- "node": ">=18"+ "node": ">=20"},"funding": {"url": "https://github.com/chalk/wrap-ansi?sponsor=1"}},+ "node_modules/wrap-ansi/node_modules/ansi-styles": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/wrap-ansi/node_modules/string-width": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz",+ "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "get-east-asian-width": "^1.5.0",+ "strip-ansi": "^7.1.2"+ },+ "engines": {+ "node": ">=20"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/wrappy": {"version": "1.0.2","resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",@@ -5712,13 +5837,21 @@}},"@alcalzone/ansi-tokenize": {- "version": "0.1.3",- "resolved": "https://registry.npmjs.org/@alcalzone/ansi-tokenize/-/ansi-tokenize-0.1.3.tgz",- "integrity": "sha512-3yWxPTq3UQ/FY9p1ErPxIyfT64elWaMvM9lIHnaqpyft63tkxodF5aUElYHrdisWve5cETkh1+KBw1yJuW0aRw==",+ "version": "0.3.1",+ "resolved": "https://registry.npmjs.org/@alcalzone/ansi-tokenize/-/ansi-tokenize-0.3.1.tgz",+ "integrity": "sha512-cUD0PT0YX+rImRhfn7BfMRduP/tX/Zqt/N0dHlAyn2RlcJssCb5KsCJkhln61eh9vuJDkH8wKn3L8zJzzWXPFg==","dev": true,"requires": {"ansi-styles": "^6.2.1",- "is-fullwidth-code-point": "^4.0.0"+ "is-fullwidth-code-point": "^5.0.0"+ },+ "dependencies": {+ "ansi-styles": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",+ "dev": true+ }}},"@discordjs/builders": {@@ -6439,12 +6572,6 @@"integrity": "sha512-0ikrnug3/IyneSHqCBeslAhlK2aBfYek1fGo4bP4QnZPmiqSGRK+Oy7ZMisLWkesffJvQ1cqAcBnJC+8+nxIAg==","dev": true},- "@types/prop-types": {- "version": "15.7.15",- "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",- "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",- "dev": true- },"@types/qrcode-terminal": {"version": "0.12.2","resolved": "https://registry.npmjs.org/@types/qrcode-terminal/-/qrcode-terminal-0.12.2.tgz",@@ -6464,12 +6591,11 @@"peer": true},"@types/react": {- "version": "18.3.28",- "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.28.tgz",- "integrity": "sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw==",+ "version": "19.3.0",+ "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",+ "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==","dev": true,"requires": {- "@types/prop-types": "*","csstype": "^3.2.2"}},@@ -6647,9 +6773,9 @@"integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="},"ansi-styles": {- "version": "6.2.3",- "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",- "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-7.0.0.tgz",+ "integrity": "sha512-kKvt3m4uwzqL0wlkPd09CmljPJGOZZ4D0fP65sqFSvPkMRKhNi+74MgIJ5QxE6SxqB4t4KyUFGg8+n5zjo6hew==","dev": true},"any-promise": {@@ -6848,9 +6974,9 @@"optional": true},"cli-boxes": {- "version": "3.0.0",- "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-3.0.0.tgz",- "integrity": "sha512-/lzGpEWL/8PfI0BmBOPRwp0c/wFNX1RdUML3jK/RcSBA9T8mZDdQpqYBKtCFTOfQbwPqWEOpjqW+Fnayc0969g==",+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-4.0.1.tgz",+ "integrity": "sha512-5IOn+jcCEHEraYolBPs/sT4BxYCe2nHg374OPiItB1O96KZFseS2gthU4twyYzeDcFew4DaUM/xwc5BQf08JJw==","dev": true},"cli-cursor": {@@ -6863,23 +6989,23 @@}},"cli-truncate": {- "version": "4.0.0",- "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-4.0.0.tgz",- "integrity": "sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA==",+ "version": "6.1.1",+ "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-6.1.1.tgz",+ "integrity": "sha512-06p9vyLahLa4zkGcgsGxU6iEkSOiuI4fhCH6Emhe2lPAcoUv73n72DnODsnHA+5wwXGnV0n9M9/qOQJSjYhFhw==","dev": true,"requires": {- "slice-ansi": "^5.0.0",- "string-width": "^7.0.0"+ "slice-ansi": "^9.0.0",+ "string-width": "^8.2.0"},"dependencies": {- "slice-ansi": {- "version": "5.0.0",- "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-5.0.0.tgz",- "integrity": "sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==",+ "string-width": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz",+ "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==","dev": true,"requires": {- "ansi-styles": "^6.0.0",- "is-fullwidth-code-point": "^4.0.0"+ "get-east-asian-width": "^1.5.0",+ "strip-ansi": "^7.1.2"}}}@@ -7109,9 +7235,9 @@}},"es-toolkit": {- "version": "1.46.1",- "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.46.1.tgz",- "integrity": "sha512-5eNtXOs3tbfxXOj04tjjseeWkRWaoCjdEI+96DgwzZoe6c9juL49pXlzAFTI72aWC9Y8p7168g6XIKjh7k6pyQ==",+ "version": "1.52.0",+ "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.52.0.tgz",+ "integrity": "sha512-XTNEJQh1tY1ZJVcf6ayP/2n4ZPyaHlW2FWs7xvw5ddPuhUVjLD3olQVQS7kf58JbAB48iL0uL/jerTrjtV3lDA==","dev": true},"esbuild": {@@ -7469,35 +7595,52 @@"optional": true},"ink": {- "version": "5.2.1",- "resolved": "https://registry.npmjs.org/ink/-/ink-5.2.1.tgz",- "integrity": "sha512-BqcUyWrG9zq5HIwW6JcfFHsIYebJkWWb4fczNah1goUO0vv5vneIlfwuS85twyJ5hYR/y18FlAYUxrO9ChIWVg==",+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/ink/-/ink-8.0.0.tgz",+ "integrity": "sha512-M2aFwZOqmkFxCwedy6xrP4E+DGoK57iahAFnfTqNyOyJ54O7DZzu027z/NI8EGy44Sw9O9BcbTF4QEUS2GHAtg==","dev": true,"requires": {- "@alcalzone/ansi-tokenize": "^0.1.3",- "ansi-escapes": "^7.0.0",- "ansi-styles": "^6.2.1",+ "@alcalzone/ansi-tokenize": "^0.3.1",+ "ansi-escapes": "^7.3.0",+ "ansi-styles": "^7.0.0","auto-bind": "^5.0.1",- "chalk": "^5.3.0",- "cli-boxes": "^3.0.0",+ "chalk": "^6.0.1",+ "cli-boxes": "^4.0.1","cli-cursor": "^4.0.0",- "cli-truncate": "^4.0.0",+ "cli-truncate": "^6.0.0","code-excerpt": "^4.0.0",- "es-toolkit": "^1.22.0",+ "es-toolkit": "^1.52.0","indent-string": "^5.0.0",- "is-in-ci": "^1.0.0",+ "is-in-ci": "^2.0.0","patch-console": "^2.0.0",- "react-reconciler": "^0.29.0",- "scheduler": "^0.23.0",+ "quick-lru": "^7.3.0",+ "react-reconciler": "^0.34.0","signal-exit": "^3.0.7",- "slice-ansi": "^7.1.0","stack-utils": "^2.0.6",- "string-width": "^7.2.0",- "type-fest": "^4.27.0",- "widest-line": "^5.0.0",- "wrap-ansi": "^9.0.0",- "ws": "^8.18.0",+ "string-width": "^8.3.0",+ "terminal-size": "^4.0.1",+ "type-fest": "^5.10.0",+ "widest-line": "^6.0.0",+ "wrap-ansi": "^10.0.2","yoga-layout": "~3.2.1"+ },+ "dependencies": {+ "chalk": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-6.0.1.tgz",+ "integrity": "sha512-/Ce6KNm3vIbWdMlNna6RVIZ/ICQxnJxCicet5LBKK9ZffBkqzDw0xh9EiKSljdRtiIQ1S1z4YgcscUUGzNCWrA==",+ "dev": true+ },+ "string-width": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz",+ "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==",+ "dev": true,+ "requires": {+ "get-east-asian-width": "^1.5.0",+ "strip-ansi": "^7.1.2"+ }+ }}},"ipaddr.js": {@@ -7511,15 +7654,18 @@"integrity": "sha512-FO/Rhvz5tuw4MCWkpMzHFKWD2LsfHzIb7i6MdPYZ/KW7AlxawyLkqdy+jPZP1WubqEADE3O4FUENlJHDfQASRg=="},"is-fullwidth-code-point": {- "version": "4.0.0",- "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz",- "integrity": "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==",- "dev": true+ "version": "5.1.0",+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz",+ "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==",+ "dev": true,+ "requires": {+ "get-east-asian-width": "^1.3.1"+ }},"is-in-ci": {- "version": "1.0.0",- "resolved": "https://registry.npmjs.org/is-in-ci/-/is-in-ci-1.0.0.tgz",- "integrity": "sha512-eUuAjybVTHMYWm/U+vBO1sY/JOCgoPCXRxzdju0K+K0BiGW0SChEL1MLC0PoCIR1OlPo5YAp8HuQoUlsWEICwg==",+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/is-in-ci/-/is-in-ci-2.0.0.tgz",+ "integrity": "sha512-cFeerHriAnhrQSbpAxL37W1wcJKUUX07HyLWZCW1URJT/ra3GyUTzBgUnh24TMVfNTV2Hij2HLxkPHFZfOZy5w==","dev": true},"is-promise": {@@ -7538,11 +7684,6 @@"integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==","dev": true},- "js-tokens": {- "version": "4.0.0",- "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",- "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="- },"json-schema": {"version": "0.4.0","resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz",@@ -7647,14 +7788,6 @@"resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz","integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw=="},- "loose-envify": {- "version": "1.4.0",- "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",- "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",- "requires": {- "js-tokens": "^3.0.0 || ^4.0.0"- }- },"loupe": {"version": "3.2.1","resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",@@ -8090,6 +8223,12 @@"resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz","integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg=="},+ "quick-lru": {+ "version": "7.3.0",+ "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-7.3.0.tgz",+ "integrity": "sha512-k9lSsjl36EJdK7I06v7APZCbyGT2vMTsYSRX1Q2nbYmnkBqgUhRkAuzH08Ciotteu/PLJmIF2+tti7o3C/ts2g==",+ "dev": true+ },"range-parser": {"version": "1.2.1","resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",@@ -8119,17 +8258,14 @@}},"react": {- "version": "18.3.1",- "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",- "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",- "requires": {- "loose-envify": "^1.1.0"- }+ "version": "19.3.0",+ "resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz",+ "integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog=="},"react-devtools-core": {- "version": "4.28.5",- "resolved": "https://registry.npmjs.org/react-devtools-core/-/react-devtools-core-4.28.5.tgz",- "integrity": "sha512-cq/o30z9W2Wb4rzBefjv5fBalHU0rJGZCHAkf/RHSBWSSYwh8PlQTqqOJmgIIbBtpj27T6FIPXeomIjZtCNVqA==",+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/react-devtools-core/-/react-devtools-core-7.0.1.tgz",+ "integrity": "sha512-C3yNvRHaizlpiASzy7b9vbnBGLrhvdhl1CbdU6EnZgxPNbai60szdLtl+VL76UNOt5bOoVTOz5rNWZxgGt+Gsw==","dev": true,"requires": {"shell-quote": "^1.6.1",@@ -8137,22 +8273,21 @@},"dependencies": {"ws": {- "version": "7.5.11",- "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.11.tgz",- "integrity": "sha512-zS54Oen9bITtp7kp2XM3AydrCIq1D+HwJOuH+c+e4LfpL/lotP5osijd+UoMnxwAam1GN8R4KtLAyIrIcBNpiA==",+ "version": "7.5.13",+ "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz",+ "integrity": "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA==","dev": true,"requires": {}}}},"react-reconciler": {- "version": "0.29.2",- "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.29.2.tgz",- "integrity": "sha512-zZQqIiYgDCTP/f1N/mAR10nJGrPD2ZR+jDSEsKWJHYC7Cm2wodlwbR3upZRdC3cjIjSlTLNVyO7Iu0Yy7t2AYg==",+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.34.0.tgz",+ "integrity": "sha512-eVibvB1fc9j5Qf1KRkiM3GzRPBdjg2P6G6QV2f3P6Eb3OGMxRBhdg2rrUwjbV5JrQaJj8nOa8uajmmJA5tJWjQ==","dev": true,"requires": {- "loose-envify": "^1.1.0",- "scheduler": "^0.23.2"+ "scheduler": "^0.28.0"}},"readable-stream": {@@ -8261,13 +8396,10 @@"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="},"scheduler": {- "version": "0.23.2",- "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",- "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",- "dev": true,- "requires": {- "loose-envify": "^1.1.0"- }+ "version": "0.28.0",+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz",+ "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==",+ "dev": true},"secure-json-parse": {"version": "2.7.0",@@ -8314,9 +8446,9 @@"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="},"shell-quote": {- "version": "1.8.4",- "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.4.tgz",- "integrity": "sha512-VsC6n6vz1ihYYyZZwX7YZSF5l5x36ca17OC+a69h94YqB7X6XLwf+5MOgynYir2SLFUbl8gIYvBo8K8RoNQ6bQ==",+ "version": "1.12.0",+ "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.12.0.tgz",+ "integrity": "sha512-PcByqNyT/38F2kDNi006HAMRJaULuBzq/FOsw3qdZvX/GA9W/jamDaRskgHjubHiftXK5sIFxLNkvrXUwcof6Q==","dev": true},"side-channel": {@@ -8393,23 +8525,20 @@}},"slice-ansi": {- "version": "7.1.2",- "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-7.1.2.tgz",- "integrity": "sha512-iOBWFgUX7caIZiuutICxVgX1SdxwAVFFKwt1EvMYYec/NWO5meOJ6K5uQxhrYBdQJne4KxiqZc+KptFOWFSI9w==",+ "version": "9.0.1",+ "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-9.0.1.tgz",+ "integrity": "sha512-aBY19bn/XA+hKOKX0qL7Z0UfdBsbQvc9hn993U8ALUjzxCvDcuZqLoRXjGJrUARWAlwMnsRVD9sw2AFNOYvalA==","dev": true,"requires": {- "ansi-styles": "^6.2.1",- "is-fullwidth-code-point": "^5.0.0"+ "ansi-styles": "^6.2.3",+ "is-fullwidth-code-point": "^5.1.0"},"dependencies": {- "is-fullwidth-code-point": {- "version": "5.1.0",- "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz",- "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==",- "dev": true,- "requires": {- "get-east-asian-width": "^1.3.1"- }+ "ansi-styles": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",+ "dev": true}}},@@ -8542,6 +8671,12 @@}}},+ "tagged-tag": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/tagged-tag/-/tagged-tag-1.0.0.tgz",+ "integrity": "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==",+ "dev": true+ },"tar-fs": {"version": "2.1.4","resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz",@@ -8567,6 +8702,12 @@"readable-stream": "^3.1.1"}},+ "terminal-size": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/terminal-size/-/terminal-size-4.0.1.tgz",+ "integrity": "sha512-avMLDQpUI9I5XFrklECw1ZEUPJhqzcwSWsyyI8blhRLT+8N1jLJWLWWYQpB2q2xthq8xDvjZPISVh53T/+CLYQ==",+ "dev": true+ },"thenify": {"version": "3.3.1","resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz",@@ -8712,10 +8853,13 @@}},"type-fest": {- "version": "4.41.0",- "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz",- "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==",- "dev": true+ "version": "5.10.0",+ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.10.0.tgz",+ "integrity": "sha512-NoSdpq/WEiAg5sjmBkmV/hfxv6HJH4NqPNrqjtSO5CwRmpsDfaf4begxW34KdJykH/l1yHtwBWQkCRdoXO8mPA==",+ "dev": true,+ "requires": {+ "tagged-tag": "^1.0.0"+ }},"type-is": {"version": "2.1.0",@@ -9079,23 +9223,52 @@}},"widest-line": {- "version": "5.0.0",- "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-5.0.0.tgz",- "integrity": "sha512-c9bZp7b5YtRj2wOe6dlj32MK+Bx/M/d+9VB2SHM1OtsUHR0aV0tdP6DWh/iMt0kWi1t5g1Iudu6hQRNd1A4PVA==",+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-6.0.0.tgz",+ "integrity": "sha512-U89AsyEeAsyoF0zVJBkG9zBgekjgjK7yk9sje3F4IQpXBJ10TF6ByLlIfjMhcmHMJgHZI4KHt4rdNfktzxIAMA==","dev": true,"requires": {- "string-width": "^7.0.0"+ "string-width": "^8.1.0"+ },+ "dependencies": {+ "string-width": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz",+ "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==",+ "dev": true,+ "requires": {+ "get-east-asian-width": "^1.5.0",+ "strip-ansi": "^7.1.2"+ }+ }}},"wrap-ansi": {- "version": "9.0.2",- "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",- "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",+ "version": "10.0.2",+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-10.0.2.tgz",+ "integrity": "sha512-6OLRNZqRntVGBm26ghZ5eZhCuWWyOkRCSn8XsOIuq5stpCE/tjLbdozd93naILZig0lmD8ANfRwnhn0DLeXGlg==","dev": true,"requires": {- "ansi-styles": "^6.2.1",- "string-width": "^7.0.0",- "strip-ansi": "^7.1.0"+ "ansi-styles": "^6.2.3",+ "string-width": "^8.2.0"+ },+ "dependencies": {+ "ansi-styles": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",+ "dev": true+ },+ "string-width": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz",+ "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==",+ "dev": true,+ "requires": {+ "get-east-asian-width": "^1.5.0",+ "strip-ansi": "^7.1.2"+ }+ }}},"wrappy": {diff --git a/package.json b/package.jsonindex 7cae4e0c..2f622f0f 100644--- a/package.json+++ b/package.json@@ -85,7 +85,7 @@"ollama-ai-provider": "^1.2.0","pino": "^10.3.1","qrcode-terminal": "^0.12.0",- "react": "^18.3.1",+ "react": "^19.3.0","sql.js": "^1.14.1","string-width": "^7.2.0","undici": "^6.24.1",@@ -102,15 +102,15 @@"@types/node": "^22.13.0","@types/node-cron": "^3.0.11","@types/qrcode-terminal": "^0.12.2",- "@types/react": "^18.3.28",- "ink": "5.2.1",- "react-devtools-core": "^4.28.5",+ "@types/react": "^19.3.0",+ "ink": "8.0.0",+ "react-devtools-core": "^7.0.1","tsup": "^8.4.0","typescript": "^5.7.0","vitest": "^3.0.0"},"engines": {- "node": ">=20.0.0"+ "node": ">=22.0.0"},"allowScripts": {"esbuild": truediff --git a/patches/ink+5.2.1.patch b/patches/ink+5.2.1.patchdeleted file mode 100644index 3a925dd1..00000000--- a/patches/ink+5.2.1.patch+++ /dev/null@@ -1,486 +0,0 @@-diff --git a/node_modules/ink/build/components/Static.d.ts b/node_modules/ink/build/components/Static.d.ts-index 9a25884..a4d515b 100644---- a/node_modules/ink/build/components/Static.d.ts-+++ b/node_modules/ink/build/components/Static.d.ts-@@ -15,6 +15,14 @@ export type Props<T> = {- * Note that `key` must be assigned to the root component.- */- readonly children: (item: T, index: number) => ReactNode;-+ /**-+ * Optional identity function used to track which items have already been-+ * rendered. When provided, each item is rendered exactly once per-+ * `<Static>` instance lifetime even if the `items` array is kept bounded-+ * by shifting the window (which the built-in positional index cannot-+ * handle). Keys returning `undefined` are ignored.-+ */-+ readonly itemKey?: (item: T) => string | undefined;- };- /**- * `<Static>` component permanently renders its output above everything else.-diff --git a/node_modules/ink/build/components/Static.js b/node_modules/ink/build/components/Static.js-index 6bb7894..e22c94e 100644---- a/node_modules/ink/build/components/Static.js-+++ b/node_modules/ink/build/components/Static.js-@@ -1,4 +1,4 @@--import React, { useMemo, useState, useLayoutEffect } from 'react';-+import React, { useMemo, useState, useLayoutEffect, useRef } from 'react';- /**- * `<Static>` component permanently renders its output above everything else.- * It's useful for displaying activity like completed tasks or logs - things that-@@ -10,18 +10,61 @@ import React, { useMemo, useState, useLayoutEffect } from 'react';- * For example, [Tap](https://github.com/tapjs/node-tap) uses `<Static>` to display- * a list of completed tests. [Gatsby](https://github.com/gatsbyjs/gatsby) uses it- * to display a list of generated pages, while still displaying a live progress bar.-+ *-+ * Patched (Cosmic Stack): supports an optional `itemKey` identity function.-+ * The built-in positional index assumes `items` only ever appends — a caller-+ * that keeps the array bounded by dropping the oldest items (a sliding-+ * window) breaks it: `items.slice(index)` returns nothing, new items are-+ * never rendered, and every commit unmounts the whole subtree. With-+ * `itemKey`, each item is tracked by identity and rendered exactly once per-+ * instance lifetime, so bounded sliding windows are safe.- */- export default function Static(props) {-- const { items, children: render, style: customStyle } = props;-+ const { items, children: render, style: customStyle, itemKey } = props;- const [index, setIndex] = useState(0);-+ // Identity of items already written to the terminal in this instance.-+ // Only used when `itemKey` is provided.-+ const committedKeys = useRef(null);-+ // Bumped after committing keys so the memo recomputes and the rendered-+ // children are unmounted — the positional path does this via setIndex.-+ // Without it, committed children stay mounted and the renderer keeps-+ // re-printing them into the terminal on EVERY subsequent render (each-+ // pass re-emits `staticOutput` while the nodes are still attached).-+ const [commitTick, setCommitTick] = useState(0);- const itemsToRender = useMemo(() => {-+ if (typeof itemKey === 'function') {-+ if (!committedKeys.current) {-+ committedKeys.current = new Set();-+ }-+ const committed = committedKeys.current;-+ const out = [];-+ for (const item of items) {-+ const key = itemKey(item);-+ if (key !== undefined && !committed.has(key)) {-+ out.push(item);-+ }-+ }-+ return out;-+ }- return items.slice(index);-- }, [items, index]);-+ }, [items, index, itemKey, commitTick]);- useLayoutEffect(() => {-+ if (typeof itemKey === 'function') {-+ if (committedKeys.current && itemsToRender.length > 0) {-+ for (const item of itemsToRender) {-+ committedKeys.current.add(itemKey(item));-+ }-+ // Unmount what was just written: without this, the nodes stay-+ // attached and every later render re-prints them (duplicate-+ // transcript lines accumulating over time).-+ setCommitTick((v) => v + 1);-+ }-+ return;-+ }- setIndex(items.length);-- }, [items.length]);-+ }, [itemsToRender, itemKey, items.length]);- const children = itemsToRender.map((item, itemIndex) => {-- return render(item, index + itemIndex);-+ return render(item, itemIndex);- });- const style = useMemo(() => ({- position: 'absolute',-diff --git a/node_modules/ink/build/ink.js b/node_modules/ink/build/ink.js-index 68d3045..4fd2a7c 100644---- a/node_modules/ink/build/ink.js-+++ b/node_modules/ink/build/ink.js-@@ -14,6 +14,53 @@ import logUpdate from './log-update.js';- import instances from './instances.js';- import App from './components/App.js';- const noop = () => { };-+// Freeze gate (Cosmic Stack patch): while frozen, onRender writes NOTHING-+// and must not advance lastOutput / log-update's baseline — the resume frame-+// must diff against the last frame actually on screen. `armed` lets exactly-+// one frame through (the "⏸ frozen" hint) if its output contains `marker`.-+// Exposed on globalThis so host code can reach it without a type-level-+// import of this internal module.-+export const frameGate = { frozen: false, armed: false, marker: '' };-+globalThis.__mercuryFrameGate = frameGate;-+// Hardware cursor (Cosmic Stack patch): ink hides the terminal cursor and-+// leaves it below the live region, so IME preedit/candidate windows anchor-+// in the wrong place and some terminals suppress IME entirely. A host marks-+// its fake-cursor cell with the `internal_cursor` attribute (Mercury:-+// src/ui/cursor-anchor.tsx); after every frame onRender finds that element-+// in the live tree and log-update parks the real cursor on it. No marked-+// element (non-input views) → the cursor stays hidden. `enabled: false`-+// turns the feature off globally.-+export const cursorAnchor = { enabled: true };-+globalThis.__mercuryCursorAnchor = cursorAnchor;-+// Patch manifest (Cosmic Stack): which hunks this build carries, and whether-+// it is the vendored copy (stamped by scripts/vendor-ink.cjs) or an-+// in-place node_modules edit.-+export const inkPatch = {-+ vendored: true,-+ hunks: ['yoga-hygiene', 'static-item-key', 'freeze-gate', 'live-region-guard', 'diff-render', 'resize-invalidate', 'cursor-positioning', 'synchronized-output'],-+};-+globalThis.__mercuryInkPatch = inkPatch;-+const sameCursor = (a, b) => (!a && !b) || (!!a && !!b && a.row === b.row && a.col === b.col);-+// Depth-first search for the first element carrying a truthy-+// `internal_cursor` attribute, accumulating Yoga offsets exactly like-+// render-node-to-output does. <Static> subtrees and display:none subtrees-+// are never part of the live frame and are skipped. Reading the DOM-+// attribute (set in createInstance/commitUpdate) instead of a ref matters:-+// refs attach in React's layout phase, AFTER resetAfterCommit has already-+// rendered the frame, so a ref-based anchor would always lag one frame.-+const findCursorCell = (node, x, y) => {-+ const yoga = node.yogaNode;-+ if (!yoga || node.internal_static || node.style?.display === 'none') return null;-+ const nx = x + yoga.getComputedLeft();-+ const ny = y + yoga.getComputedTop();-+ if (node.attributes?.internal_cursor) return { row: ny, col: nx };-+ if (!Array.isArray(node.childNodes)) return null;-+ for (const child of node.childNodes) {-+ const hit = findCursorCell(child, nx, ny);-+ if (hit) return hit;-+ }-+ return null;-+};- export default class Ink {- options;- log;-@@ -41,7 +88,8 @@ export default class Ink {- trailing: true,- });- this.rootNode.onImmediateRender = this.onRender;-- this.log = logUpdate.create(options.stdout);-+ // Synchronized output (Cosmic Stack patch): same gate as upstream shouldSynchronize().-+ this.log = logUpdate.create(options.stdout, { synchronize: Boolean(options.stdout.isTTY) && !isInCi && !options.debug });- this.throttledLog = options.debug- ? this.log- : throttle(this.log, undefined, {-@@ -81,6 +129,11 @@ export default class Ink {- }- }- resized = () => {-+ // Resize baseline reset (Cosmic Stack patch): rows that re-wrapped on-+ // resize must be repainted even when their bytes did not change, so-+ // the diff-render baseline (ours and log-update's) is dropped first.-+ this.lastOutput = '';-+ if (typeof this.log.invalidate === 'function') this.log.invalidate();- this.calculateLayout();- this.onRender();- };-@@ -94,11 +147,53 @@ export default class Ink {- this.rootNode.yogaNode.setWidth(terminalWidth);- this.rootNode.yogaNode.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);- };-+ // Hardware cursor (Cosmic Stack patch): absolute cell of the marked cursor-+ // element inside the live frame, or null when there is none, the feature-+ // is disabled, or the cell was trimmed away by the live-region guard.-+ lastCursor = null;-+ resolveCursor(trimmedRows) {-+ if (!cursorAnchor.enabled) return null;-+ const cell = findCursorCell(this.rootNode, 0, 0);-+ if (!cell) return null;-+ const row = cell.row - trimmedRows;-+ if (row < 0) return null;-+ return { row, col: cell.col };-+ }- onRender = () => {- if (this.isUnmounted) {- return;- }-- const { output, outputHeight, staticOutput } = render(this.rootNode);-+ let { output, outputHeight, staticOutput } = render(this.rootNode);-+ // Freeze gate (Cosmic Stack patch): drop the frame entirely — no-+ // write, and crucially NO advance of `lastOutput` or log-update's-+ // `previousOutput`/`previousLineCount` baseline, so the frame that-+ // ends the freeze diffs against what is actually on screen.-+ if (frameGate.frozen && !(frameGate.armed && frameGate.marker && output.includes(frameGate.marker))) {-+ return;-+ }-+ if (frameGate.armed) frameGate.armed = false;-+ // Live-region guard (Cosmic Stack patch): a live frame as tall as (or-+ // taller than) the terminal cannot go through log-update's cursor-+ // arithmetic, and stock ink's fallback is `clearTerminal +-+ // fullStaticOutput + output` — erasing the ENTIRE scrollback buffer-+ // and re-dumping every static byte ever printed, on EVERY frame. With-+ // a long transcript that is megabytes per frame: the scrollbar jumps-+ // to the top, the UI flickers, and native scrolling becomes-+ // impossible. Instead keep the frame bottom-anchored: trim to what-+ // fits (rows - 1) and let the normal diff path write it. Scrollback-+ // is never cleared, the transcript is never re-dumped, and the newest-+ // rows (live tail, input, status bar) stay visible.-+ const maxLiveRows = Math.max(1, (this.options.stdout.rows || 24) - 1);-+ const liveHeightBeforeTrim = outputHeight;-+ if (outputHeight >= (this.options.stdout.rows || 24)) {-+ // `output` is newline-terminated per row WITHOUT a trailing blank-+ // line (log-update appends its own), so split and re-join verbatim.-+ output = output.split('\n').slice(-maxLiveRows).join('\n');-+ outputHeight = maxLiveRows;-+ }-+ // Hardware cursor (Cosmic Stack patch): resolve AFTER the trim so the row-+ // is relative to the rows actually written.-+ const cursor = this.resolveCursor(liveHeightBeforeTrim - outputHeight);- // If <Static> output isn't empty, it means new children have been added to it- const hasStaticOutput = staticOutput && staticOutput !== '\n';- if (this.options.debug) {-@@ -125,19 +220,41 @@ export default class Ink {- }- // To ensure static output is cleanly rendered before main output, clear main output first- if (hasStaticOutput) {-- this.log.clear();-- this.options.stdout.write(staticOutput);-- this.log(output);-+ this.synchronized(() => {-+ this.log.clear();-+ this.options.stdout.write(staticOutput);-+ this.log(output, cursor);-+ });- }-- if (!hasStaticOutput && output !== this.lastOutput) {-- this.throttledLog(output);-+ if (!hasStaticOutput && (output !== this.lastOutput || !sameCursor(cursor, this.lastCursor))) {-+ this.throttledLog(output, cursor);- }- this.lastOutput = output;-+ this.lastCursor = cursor;- };- render(node) {- const tree = (React.createElement(App, { stdin: this.options.stdin, stdout: this.options.stdout, stderr: this.options.stderr, writeToStdout: this.writeToStdout, writeToStderr: this.writeToStderr, exitOnCtrlC: this.options.exitOnCtrlC, onExit: this.unmount }, node));- reconciler.updateContainer(tree, this.container, null, noop);- }-+ // Synchronized output (Cosmic Stack patch): run several writes as ONE terminal update (DEC-+ // mode 2026), so a new transcript line and the redrawn live region-+ // appear together instead of erase → static → redraw.-+ synchronized(write) {-+ const log = this.log;-+ if (!log.synchronize) {-+ write();-+ return;-+ }-+ this.options.stdout.write('\u001B[?2026h');-+ log.syncDepth++;-+ try {-+ write();-+ }-+ finally {-+ log.syncDepth--;-+ this.options.stdout.write('\u001B[?2026l');-+ }-+ }- writeToStdout(data) {- if (this.isUnmounted) {- return;-@@ -150,9 +267,11 @@ export default class Ink {- this.options.stdout.write(data);- return;- }-- this.log.clear();-- this.options.stdout.write(data);-- this.log(this.lastOutput);-+ this.synchronized(() => {-+ this.log.clear();-+ this.options.stdout.write(data);-+ this.log(this.lastOutput, this.lastCursor);-+ });- }- writeToStderr(data) {- if (this.isUnmounted) {-@@ -167,9 +286,11 @@ export default class Ink {- this.options.stderr.write(data);- return;- }-- this.log.clear();-- this.options.stderr.write(data);-- this.log(this.lastOutput);-+ this.synchronized(() => {-+ this.log.clear();-+ this.options.stderr.write(data);-+ this.log(this.lastOutput, this.lastCursor);-+ });- }- // eslint-disable-next-line @typescript-eslint/ban-types- unmount(error) {-diff --git a/node_modules/ink/build/log-update.d.ts b/node_modules/ink/build/log-update.d.ts-index 8068bd3..ff501a9 100644---- a/node_modules/ink/build/log-update.d.ts-+++ b/node_modules/ink/build/log-update.d.ts-@@ -2,7 +2,10 @@ import { type Writable } from 'node:stream';- export type LogUpdate = {- clear: () => void;- done: () => void;-- (str: string): void;-+ /** Resize baseline reset (Cosmic Stack patch). */-+ invalidate: () => void;-+ /** Hardware cursor (Cosmic Stack patch): `cursor` is the live-frame cell to park the terminal cursor on. */-+ (str: string, cursor?: { row: number; col: number } | null): void;- };- declare const logUpdate: {- create: (stream: Writable, { showCursor }?: {-diff --git a/node_modules/ink/build/log-update.js b/node_modules/ink/build/log-update.js-index 4c72645..22efece 100644---- a/node_modules/ink/build/log-update.js-+++ b/node_modules/ink/build/log-update.js-@@ -1,28 +1,91 @@- import ansiEscapes from 'ansi-escapes';- import cliCursor from 'cli-cursor';--const create = (stream, { showCursor = false } = {}) => {-+// Synchronized output (Cosmic Stack patch): see ink.js synchronized().-+const BSU = '\u001B[?2026h';-+const ESU = '\u001B[?2026l';-+const create = (stream, { showCursor = false, synchronize = false } = {}) => {-+ // One atomic update per write, unless ink.js already opened one.-+ const syncWrite = (data) => stream.write(synchronize && !(render.syncDepth > 0) ? BSU + data + ESU : data);- let previousLineCount = 0;- let previousOutput = '';- let hasHiddenCursor = false;-- const render = (str) => {-+ // Hardware cursor (Cosmic Stack patch): after a frame is written the-+ // cursor sits on the line below the last row (column 0) — that is what-+ // the erase arithmetic assumes. `park` moves it up onto the anchor cell-+ // and shows it; `unpark` hides it and moves it back BEFORE anything else-+ // is written, so the arithmetic never sees a parked cursor. Relative-+ // moves (CUU/CUD/CHA) on purpose: the absolute row of the live region is-+ // unknown without a DSR round-trip.-+ let parked = null;-+ const targetFor = (cursor, lineCount) => {-+ if (!cursor) return null;-+ const rows = lineCount - 1; // lineCount counts the trailing blank line-+ if (!(cursor.row >= 0 && cursor.row < rows)) return null;-+ return { up: rows - cursor.row, col: Math.max(0, Math.floor(cursor.col)) };-+ };-+ const unpark = () => {-+ if (!parked) return '';-+ const { up } = parked;-+ parked = null;-+ return ansiEscapes.cursorHide + ansiEscapes.cursorDown(up) + ansiEscapes.cursorLeft;-+ };-+ const park = (target) => {-+ if (!target) return '';-+ parked = target;-+ return ansiEscapes.cursorUp(target.up) + ansiEscapes.cursorTo(target.col) + ansiEscapes.cursorShow;-+ };-+ const render = (str, cursor) => {- if (!showCursor && !hasHiddenCursor) {- cliCursor.hide();- hasHiddenCursor = true;- }- const output = str + '\n';- if (output === previousOutput) {-+ // Hardware cursor (Cosmic Stack patch): same rows, but the anchor-+ // may have moved or toggled — re-park without touching the frame.-+ const target = targetFor(cursor, previousLineCount);-+ const same = (!parked && !target) || (parked && target && parked.up === target.up && parked.col === target.col);-+ if (!same) syncWrite(unpark() + park(target));- return;- }-+ // Diff-render (Cosmic Stack patch): erase and rewrite only the rows-+ // from the first changed line onward; identical rows above stay on-+ // screen untouched. Ink 5's log-update erased and rewrote the ENTIRE-+ // frame on every render — a prompt-selection change or spinner tick-+ // repainted the whole live region, which read as a full-UI flash.-+ // The row bytes are compared verbatim (layout is deterministic), and-+ // the erase count accounts for the trailing blank line exactly like-+ // `previousLineCount` does, so `clear()` and cursor arithmetic stay-+ // in sync with the original accounting.-+ const previousRows = previousOutput === '' ? [] : previousOutput.slice(0, -1).split('\n');-+ const nextRows = output.slice(0, -1).split('\n');-+ const common = Math.min(previousRows.length, nextRows.length);-+ let firstChange = 0;-+ while (firstChange < common && previousRows[firstChange] === nextRows[firstChange]) {-+ firstChange++;-+ }-+ const eraseCount = previousLineCount - firstChange;- previousOutput = output;-- stream.write(ansiEscapes.eraseLines(previousLineCount) + output);- previousLineCount = output.split('\n').length;-+ syncWrite(unpark() + ansiEscapes.eraseLines(eraseCount) + nextRows.slice(firstChange).join('\n') + '\n' + park(targetFor(cursor, previousLineCount)));-+ };-+ // Resize baseline reset (Cosmic Stack patch): forget what is on screen-+ // without touching the line count — the next render erases the old-+ // frame's rows and rewrites every row instead of diffing against rows-+ // the terminal has already re-wrapped.-+ render.invalidate = () => {-+ previousOutput = '';- };-+ render.synchronize = synchronize;-+ render.syncDepth = 0;- render.clear = () => {-- stream.write(ansiEscapes.eraseLines(previousLineCount));-+ syncWrite(unpark() + ansiEscapes.eraseLines(previousLineCount));- previousOutput = '';- previousLineCount = 0;- };- render.done = () => {-+ const restore = unpark();-+ if (restore) stream.write(restore);- previousOutput = '';- previousLineCount = 0;- if (!showCursor) {-diff --git a/node_modules/ink/build/reconciler.js b/node_modules/ink/build/reconciler.js-index 81379f2..5930232 100644---- a/node_modules/ink/build/reconciler.js-+++ b/node_modules/ink/build/reconciler.js-@@ -58,6 +58,41 @@ const cleanupYogaNode = (node) => {- node?.unsetMeasureFunc();- node?.freeRecursive();- };-+// `freeRecursive` releases Yoga's WASM memory but leaves every JavaScript-+// reference pointing at freed memory. The renderer and layout code read those-+// references through optional chaining, so nulling them here turns what was a-+// fatal WASM trap ("RuntimeError: memory access out of bounds" in-+// getComputedWidth) into a clean no-op. See facebook/yoga#1818 and the-+// equivalent downstream fix in qwen-code#7816. (Cosmic Stack patch.)-+const clearYogaRefs = (node) => {-+ node.yogaNode = undefined;-+ // Host elements carry a childNodes array; ink's `#text` nodes do not.-+ if (Array.isArray(node.childNodes)) {-+ for (const child of node.childNodes) {-+ clearYogaRefs(child);-+ }-+ }-+};-+const containsNode = (ancestor, target) => {-+ let current = target;-+ while (current) {-+ if (current === ancestor) return true;-+ current = current.parentNode;-+ }-+ return false;-+};-+const cleanupRemovedNode = (node, removeNode) => {-+ cleanupYogaNode(removeNode.yogaNode);-+ clearYogaRefs(removeNode);-+ // `staticNode` is cached on the root container, but removeChild receives-+ // the direct parent — climb to the root before checking.-+ let rootNode = node;-+ while (rootNode?.parentNode) rootNode = rootNode.parentNode;-+ if (rootNode?.staticNode && containsNode(removeNode, rootNode.staticNode)) {-+ rootNode.staticNode = undefined;-+ }-+};-+globalThis.__mercuryInkYogaHygiene = true;- export default createReconciler({- getRootHostContext: () => ({- isInsideText: false,-@@ -173,7 +208,7 @@ export default createReconciler({- insertInContainerBefore: insertBeforeNode,- removeChildFromContainer(node, removeNode) {- removeChildNode(node, removeNode);-- cleanupYogaNode(removeNode.yogaNode);-+ cleanupRemovedNode(node, removeNode);- },- prepareUpdate(node, _type, oldProps, newProps, rootNode) {- if (node.internal_static) {-@@ -213,6 +248,6 @@ export default createReconciler({- },- removeChild(node, removeNode) {- removeChildNode(node, removeNode);-- cleanupYogaNode(removeNode.yogaNode);-+ cleanupRemovedNode(node, removeNode);- },- });diff --git a/patches/ink+8.0.0.patch b/patches/ink+8.0.0.patchnew file mode 100644index 00000000..56f45a86--- /dev/null+++ b/patches/ink+8.0.0.patch@@ -0,0 +1,168 @@+diff --git a/node_modules/ink/build/components/Static.d.ts b/node_modules/ink/build/components/Static.d.ts+index ea55350..104e538 100644+--- a/node_modules/ink/build/components/Static.d.ts++++ b/node_modules/ink/build/components/Static.d.ts+@@ -12,6 +12,13 @@ export type Props<T> = {+ /**+ Function that is called to render every item in the `items` array. The first argument is the item itself, and the second argument is the index of that item in the `items` array. Note that a `key` must be assigned to the root component.+ */++ /**++ * Stable identity for an item (Cosmic Stack patch). When set, items are++ * tracked by key instead of position, so `items` may drop its oldest++ * entries (a bounded window) without breaking. Return `undefined` to skip++ * an item.++ */++ readonly itemKey?: (item: T) => string | undefined;+ readonly children: (item: T, index: number) => ReactNode;+ };+ /**+diff --git a/node_modules/ink/build/components/Static.js b/node_modules/ink/build/components/Static.js+index 0c519c3..4c8fb63 100644+--- a/node_modules/ink/build/components/Static.js++++ b/node_modules/ink/build/components/Static.js+@@ -1,4 +1,4 @@+-import React, { useMemo, useState, useLayoutEffect, use, } from 'react';++import React, { useMemo, useState, useLayoutEffect, useRef, use, } from 'react';+ import { BackgroundContext } from './BackgroundContext.js';+ /**+ `<Static>` component permanently renders its output above everything else. It's useful for displaying activity like completed tasks or logs—things that don't change after they're rendered (hence the name "Static").+@@ -8,16 +8,45 @@ It's preferred to use `<Static>` for use cases like these when you can't know or+ For example, [Tap](https://github.com/tapjs/node-tap) uses `<Static>` to display a list of completed tests. [Gatsby](https://github.com/gatsbyjs/gatsby) uses it to display a list of generated pages while still displaying a live progress bar.+ */+ export default function Static(props) {+- const { items, children: render, style: customStyle } = props;++ const { items, children: render, style: customStyle, itemKey } = props;+ const [index, setIndex] = useState(0);++ // Static itemKey (Cosmic Stack patch): with `itemKey`, items are tracked by identity and++ // each is written exactly once per instance, so a caller may keep `items`++ // bounded by dropping the oldest (a sliding window). The positional index++ // below assumes append-only: once old items drop off, `items.slice(index)`++ // returns nothing and new items are never written.++ const committedKeys = useRef(null);++ // Bumped after committing keys so the memo recomputes and the written++ // children unmount (the positional path does this via setIndex). Without++ // it they stay mounted and are re-emitted as static output every render.++ const [commitTick, setCommitTick] = useState(0);+ const inheritedBackgroundColor = use(BackgroundContext);+ const effectiveBackgroundColor =+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, @typescript-eslint/strict-boolean-expressions -- Empty background colors inherit from the parent too.+ customStyle?.backgroundColor || inheritedBackgroundColor;+- const itemsToRender = useMemo(() => items.slice(index), [items, index]);++ const itemsToRender = useMemo(() => {++ if (typeof itemKey === 'function') {++ committedKeys.current ??= new Set();++ const committed = committedKeys.current;++ return items.filter((item) => {++ const key = itemKey(item);++ return key !== undefined && !committed.has(key);++ });++ }++ return items.slice(index);++ }, [items, index, itemKey, commitTick]);+ useLayoutEffect(() => {++ if (typeof itemKey === 'function') {++ if (committedKeys.current && itemsToRender.length > 0) {++ for (const item of itemsToRender) {++ committedKeys.current.add(itemKey(item));++ }++ setCommitTick((v) => v + 1);++ }++ return;++ }+ setIndex(items.length);+- }, [items.length]);++ }, [itemsToRender, itemKey, items.length]);+ const children = itemsToRender.map((item, itemIndex) => render(item, index + itemIndex));+ const style = useMemo(() => ({+ position: 'absolute',+diff --git a/node_modules/ink/build/ink.js b/node_modules/ink/build/ink.js+index 29d1a98..6ee4d5a 100644+--- a/node_modules/ink/build/ink.js++++ b/node_modules/ink/build/ink.js+@@ -23,6 +23,45 @@ import { AccessibilityContext } from './components/AccessibilityContext.js';+ import { resolveFlags, } from './kitty-keyboard.js';+ import { isTty } from './stream.js';+ const noop = () => { };++// Freeze gate (Cosmic Stack patch): while frozen, onRender writes NOTHING and++// must not advance lastOutput or log-update's baseline, so the frame that++// ends the freeze diffs against what is really on screen. `armed` lets++// exactly one frame through (the "⏸ frozen" hint) if it contains `marker`.++export const frameGate = { frozen: false, armed: false, marker: '' };++globalThis.__mercuryFrameGate = frameGate;++// Cursor anchor (Cosmic Stack patch): after every frame, the element marked++// with the `internal_cursor` attribute (Mercury's CursorCell) is located in++// the laid-out live tree and handed to ink's setCursorPosition, so the real++// terminal cursor (and with it IME preedit/candidate windows) sits on the++// input cell. `enabled: false` turns it off (MERCURY_HW_CURSOR=0).++export const cursorAnchor = { enabled: true };++globalThis.__mercuryCursorAnchor = cursorAnchor;++// Patch manifest (Cosmic Stack): which hunks this build carries, and whether++// it is the vendored copy (stamped by scripts/vendor-ink.cjs).++export const inkPatch = {++ vendored: true,++ base: '[email protected]',++ hunks: ['static-item-key', 'freeze-gate', 'live-region-guard', 'cursor-anchor'],++};++globalThis.__mercuryInkPatch = inkPatch;++// Depth-first search for the first element with a truthy `internal_cursor`++// attribute, accumulating Yoga offsets like render-node-to-output does.++// <Static> and display:none subtrees are never part of the live frame. The++// DOM attribute is read instead of a ref because refs attach in React's++// layout phase, after the frame has already been rendered.++const findCursorCell = (node, x, y) => {++ const yoga = node.yogaNode;++ if (!yoga || node.internal_static || node.style?.display === 'none') return undefined;++ const nx = x + yoga.getComputedLeft();++ const ny = y + yoga.getComputedTop();++ if (node.attributes?.internal_cursor) return { x: nx, y: ny };++ if (!Array.isArray(node.childNodes)) return undefined;++ for (const child of node.childNodes) {++ const hit = findCursorCell(child, nx, ny);++ if (hit) return hit;++ }++ return undefined;++};+ const yieldImmediate = async () => new Promise(resolve => {+ setImmediate(resolve);+ });+@@ -233,7 +272,39 @@ export default class Ink {+ this.lastOutputToRender = '';+ }+ const startTime = performance.now();+- const { output, outputHeight, staticOutput } = render(this.rootNode, this.isScreenReaderEnabled);++ let { output, outputHeight, staticOutput } = render(this.rootNode, this.isScreenReaderEnabled);++ // Freeze gate (Cosmic Stack patch): drop the frame entirely.++ if (frameGate.frozen && !(frameGate.armed && frameGate.marker && output.includes(frameGate.marker))) {++ return;++ }++ if (frameGate.armed) frameGate.armed = false;++ // Live-region guard (Cosmic Stack patch): a live frame as tall as the viewport is++ // written whole by stock ink, and on the primary screen every row++ // past the viewport scrolls into scrollback, so each repaint while++ // a reply streams stamps another copy of the live region into the++ // user's history. Keep the newest rows (input, status bar, the live++ // tail) and send the trimmed frame through the normal diff path.++ const liveHeightBeforeTrim = outputHeight;++ if (this.interactive && !this.alternateScreen && !this.isScreenReaderEnabled && !this.options.debug && this.options.stdout.isTTY) {++ const viewportRows = getWindowSize(this.options.stdout).rows;++ if (outputHeight >= viewportRows) {++ const maxLiveRows = Math.max(1, viewportRows - 1);++ output = output.split('\n').slice(-maxLiveRows).join('\n');++ outputHeight = maxLiveRows;++ }++ }++ // Cursor anchor (Cosmic Stack patch): resolved after the trim, so the++ // row is relative to the rows actually written. Only a CHANGE is++ // pushed: setCursorPosition marks the cursor dirty, and a dirty++ // cursor forces a rewrite of an otherwise unchanged frame.++ if (cursorAnchor.enabled && !this.isScreenReaderEnabled) {++ const cell = findCursorCell(this.rootNode, 0, 0);++ const row = cell ? cell.y - (liveHeightBeforeTrim - outputHeight) : -1;++ const next = cell && row >= 0 ? { x: cell.x, y: row } : undefined;++ if (next?.x !== this.cursorPosition?.x || next?.y !== this.cursorPosition?.y) {++ this.setCursorPosition(next);++ }++ }+ const renderTime = performance.now() - startTime;+ this.renderFrame(output, outputHeight, staticOutput);+ this.options.onRender?.({ renderTime });diff --git a/scripts/apply-ink-patch.cjs b/scripts/apply-ink-patch.cjsindex 5a1cdb2b..aaffbcd9 100644--- a/scripts/apply-ink-patch.cjs+++ b/scripts/apply-ink-patch.cjs@@ -1,35 +1,31 @@/*** The Mercury ink patch set, as deterministic source edits on a stock- * ink 5.2.1 build. Idempotent: checks for the fix markers first, then edits- * the files DIRECTLY — no patch-package dependency (patch-package itself- * failed on Termux/npm-11 containers: `sh: 1: patch-package: not found`).+ * ink 8.0.0 build. Idempotent: checks for the fix markers first, then edits+ * the files DIRECTLY (no patch-package).** Since ADR-017 the patched ink is VENDORED: `scripts/vendor-ink.cjs` runs* this applier against a stock tarball and commits the result to- * `vendor/ink/`, which tsup/vitest alias `ink` to. This module is therefore- * the single source of truth for every hunk (see docs/ink-patch.md for the- * rationale behind each one):- * 1. reconciler.js — freed-Yoga-node hygiene: null every JS reference in- * removed subtrees after freeRecursive, and clear the root's cached- * staticNode when the removed subtree contains it. Also guards ink's- * `#text` nodes (no childNodes array) in the traversal.- * 2. Static.js — `itemKey` identity dedup so bounded sliding item windows- * are safe (the positional index assumes append-only), plus the- * commitTick re-render that unmounts written children (ink's renderer- * re-prints still-mounted static children on every render).- * 3. Static.d.ts — the `itemKey` type.- * 4. ink.js — freeze gate (`globalThis.__mercuryFrameGate`).- * 5. ink.js — live-region guard (bottom-anchored trim instead of- * clearTerminal + full static re-dump).- * 6. log-update.js — diff-render (rewrite from the first changed row).- * 7. ink.js + log-update.js — resize baseline invalidate.- * 8. ink.js + log-update.js — hardware cursor positioning- * (`internal_cursor` host attribute), so IME preedit/candidate- * windows anchor on the input cell.- * 9. ink.js + log-update.js — synchronized output (DEC mode 2026): every- * frame is painted atomically; backport of ink 6.7 (#866).+ * `vendor/ink/`, which tsup/vitest alias `ink` to. This module is the single+ * source of truth for every hunk (docs/ink-patch.md has the rationale):+ * 1. Static.js / Static.d.ts — `itemKey` identity dedup, so a bounded+ * sliding window of items is safe (upstream's positional index assumes+ * append-only), plus the commitTick re-render that unmounts written+ * children.+ * 2. ink.js — freeze gate (`globalThis.__mercuryFrameGate`): while frozen,+ * no frame is written and no baseline advances (Ctrl+S scroll lock).+ * 3. ink.js — live-region guard: a live frame as tall as the viewport is+ * trimmed to its newest rows instead of being written whole, so the+ * overflow never scrolls copies of the live region into scrollback.+ * 4. ink.js — cursor anchor: the cell marked `internal_cursor` (Mercury's+ * CursorCell) is resolved from the layout after every frame and fed to+ * ink's own setCursorPosition, so IME preedit/candidate windows anchor+ * on the input cell.*- * Loud on failure: a silent skip is never acceptable for a crash fix.+ * Retired with the move to ink 8 (upstream now covers them): Yoga free-node+ * hygiene (freeYogaSubtree), diff-render (`incrementalRendering`), resize+ * baseline reset, hand-rolled cursor park/unpark, synchronized output.+ *+ * Loud on failure: a silent skip is never acceptable.*/const fs = require('fs');const path = require('path');@@ -43,11 +39,6 @@ const root = path.join(__dirname, '..');function pathsFor(projectRoot, opts = {}) {let inkDir = opts.inkDir || path.join(projectRoot, 'node_modules', 'ink', 'build');if (!opts.inkDir) {- // When Mercury is installed as a dependency (not globally), npm hoists ink- // to the consumer's node_modules — `<root>/node_modules/ink` does not- // exist. Resolve the ink that Node will actually load from this root;- // the plain join above stays as the fallback (synthetic trees in tests- // carry no package.json for the resolver to find).try {const resolved = require.resolve('ink', { paths: [projectRoot] });if (fs.existsSync(resolved)) inkDir = path.dirname(resolved);@@ -57,12 +48,9 @@ function pathsFor(projectRoot, opts = {}) {}return {inkDir,- reconcilerPath: path.join(inkDir, 'reconciler.js'),staticJsPath: path.join(inkDir, 'components', 'Static.js'),staticDtsPath: path.join(inkDir, 'components', 'Static.d.ts'),inkJsPath: path.join(inkDir, 'ink.js'),- logUpdatePath: path.join(inkDir, 'log-update.js'),- logUpdateDtsPath: path.join(inkDir, 'log-update.d.ts'),};}@@ -71,697 +59,193 @@ const VENDORED_INK_DIR = path.join(root, 'vendor', 'ink', 'build');const paths = pathsFor(root);+const FRAME_GATE_MARKER = '__mercuryFrameGate';+const LIVE_REGION_MARKER = 'Live-region guard (Cosmic Stack patch)';+const CURSOR_ANCHOR_MARKER = '__mercuryCursorAnchor';+const STATIC_MARKER = 'Static itemKey (Cosmic Stack patch)';+const HUNKS = ['static-item-key', 'freeze-gate', 'live-region-guard', 'cursor-anchor'];+function isPatched(p = paths) {try {- const reconciler = fs.readFileSync(p.reconcilerPath, 'utf8');- const staticComponent = fs.readFileSync(p.staticJsPath, 'utf8');+ const staticJs = fs.readFileSync(p.staticJsPath, 'utf8');+ const staticDts = fs.readFileSync(p.staticDtsPath, 'utf8');const inkJs = fs.readFileSync(p.inkJsPath, 'utf8');- const logUpdate = fs.readFileSync(p.logUpdatePath, 'utf8');- return reconciler.includes('clearYogaRefs')- && reconciler.includes('Array.isArray(node.childNodes)')- && reconciler.includes('rootNode.staticNode = undefined')- && reconciler.includes(YOGA_HYGIENE_MARKER)- && staticComponent.includes('itemKey')- && staticComponent.includes('setCommitTick')- && logUpdate.includes('Diff-render (Cosmic Stack patch)')- && logUpdate.includes(RESIZE_RESET_MARKER)- && logUpdate.includes(CURSOR_MARKER)- && inkJs.includes('maxLiveRows')- && inkJs.includes(RESIZE_RESET_MARKER)+ return staticJs.includes(STATIC_MARKER)+ && staticJs.includes('setCommitTick')+ && staticDts.includes('itemKey')&& inkJs.includes(FRAME_GATE_MARKER)- && inkJs.includes(CURSOR_ANCHOR_MARKER)- && logUpdate.includes(SYNC_MARKER)- && inkJs.includes(SYNC_MARKER);+ && inkJs.includes(LIVE_REGION_MARKER)+ && inkJs.includes(CURSOR_ANCHOR_MARKER);} catch {return false;}}-const FRAME_GATE_MARKER = '__mercuryFrameGate';-const RESIZE_RESET_MARKER = 'Resize baseline reset (Cosmic Stack patch)';-const CURSOR_MARKER = 'Hardware cursor (Cosmic Stack patch)';-const CURSOR_ANCHOR_MARKER = '__mercuryCursorAnchor';-const YOGA_HYGIENE_MARKER = '__mercuryInkYogaHygiene';-const SYNC_MARKER = 'Synchronized output (Cosmic Stack patch)';+/** Replace exactly one occurrence of `anchor`, or throw naming the hunk. */+function replaceOnce(source, anchor, replacement, hunk) {+ const at = source.indexOf(anchor);+ if (at < 0) throw new Error(`${hunk}: anchor not found — ink changed shape: ${JSON.stringify(anchor.slice(0, 80))}`);+ if (source.indexOf(anchor, at + anchor.length) >= 0) throw new Error(`${hunk}: anchor is ambiguous: ${JSON.stringify(anchor.slice(0, 80))}`);+ return source.slice(0, at) + replacement + source.slice(at + anchor.length);+}-/**- * Hardware cursor positioning (ADR-017, #41, #66). Stock ink hides the- * terminal cursor for its whole lifetime and leaves it on the line below- * the live region, so IME preedit/candidate windows anchor in the wrong- * place and some terminals (Windows Terminal, iTerm2 with certain input- * methods) suppress IME composition entirely while the cursor is hidden.- *- * The host marks its fake-cursor cell with the `internal_cursor` host- * attribute (src/ui/cursor-anchor.tsx). After every frame, ink.js finds- * that element in the live tree, sums Yoga's computed offsets (exactly the- * arithmetic render-node-to-output uses), subtracts any rows the- * live-region guard trimmed, and hands `{row, col}` to log-update. There- * the frame write is followed by CUU + CHA + `CSI ?25h` ("park"), and every- * later write starts with `CSI ?25l` + CUD + `CSI G` ("unpark") so the- * erase arithmetic never sees a parked cursor. Relative moves are used on- * purpose — the absolute row of the live region is unknown without a DSR- * round-trip — and nothing is ever inserted into the frame text, so no- * sentinel can leak into the terminal.- */-function applyCursorPositioning(p = paths) {- const { inkJsPath, logUpdatePath, logUpdateDtsPath } = p;- let lu = fs.readFileSync(logUpdatePath, 'utf8');- if (!lu.includes(CURSOR_MARKER)) {- const stateAnchor = ' let hasHiddenCursor = false;';- if (!lu.includes(stateAnchor)) return false;- lu = lu.replace(stateAnchor, `${stateAnchor}- // ${CURSOR_MARKER}: after a frame is written the- // cursor sits on the line below the last row (column 0) — that is what- // the erase arithmetic assumes. \`park\` moves it up onto the anchor cell- // and shows it; \`unpark\` hides it and moves it back BEFORE anything else- // is written, so the arithmetic never sees a parked cursor. Relative- // moves (CUU/CUD/CHA) on purpose: the absolute row of the live region is- // unknown without a DSR round-trip.- let parked = null;- const targetFor = (cursor, lineCount) => {- if (!cursor) return null;- const rows = lineCount - 1; // lineCount counts the trailing blank line- if (!(cursor.row >= 0 && cursor.row < rows)) return null;- return { up: rows - cursor.row, col: Math.max(0, Math.floor(cursor.col)) };- };- const unpark = () => {- if (!parked) return '';- const { up } = parked;- parked = null;- return ansiEscapes.cursorHide + ansiEscapes.cursorDown(up) + ansiEscapes.cursorLeft;- };- const park = (target) => {- if (!target) return '';- parked = target;- return ansiEscapes.cursorUp(target.up) + ansiEscapes.cursorTo(target.col) + ansiEscapes.cursorShow;- };`);- const sigAnchor = ' const render = (str) => {';- if (!lu.includes(sigAnchor)) return false;- lu = lu.replace(sigAnchor, ' const render = (str, cursor) => {');- const sameAnchor = ` if (output === previousOutput) {- return;- }`;- if (!lu.includes(sameAnchor)) return false;- lu = lu.replace(sameAnchor, ` if (output === previousOutput) {- // ${CURSOR_MARKER}: same rows, but the anchor- // may have moved or toggled — re-park without touching the frame.- const target = targetFor(cursor, previousLineCount);- const same = (!parked && !target) || (parked && target && parked.up === target.up && parked.col === target.col);- if (!same) stream.write(unpark() + park(target));+/** Hunk 1: `<Static itemKey>`. */+function applyStaticItemKey(p = paths) {+ let s = fs.readFileSync(p.staticJsPath, 'utf8');+ if (!s.includes(STATIC_MARKER)) {+ const hunk = 'static-item-key';+ s = replaceOnce(s, "import React, { useMemo, useState, useLayoutEffect, use, } from 'react';",+ "import React, { useMemo, useState, useLayoutEffect, useRef, use, } from 'react';", hunk);+ s = replaceOnce(s, ' const { items, children: render, style: customStyle } = props;',+ ' const { items, children: render, style: customStyle, itemKey } = props;', hunk);+ s = replaceOnce(s, ' const [index, setIndex] = useState(0);\n', ` const [index, setIndex] = useState(0);+ // ${STATIC_MARKER}: with \`itemKey\`, items are tracked by identity and+ // each is written exactly once per instance, so a caller may keep \`items\`+ // bounded by dropping the oldest (a sliding window). The positional index+ // below assumes append-only: once old items drop off, \`items.slice(index)\`+ // returns nothing and new items are never written.+ const committedKeys = useRef(null);+ // Bumped after committing keys so the memo recomputes and the written+ // children unmount (the positional path does this via setIndex). Without+ // it they stay mounted and are re-emitted as static output every render.+ const [commitTick, setCommitTick] = useState(0);+`, hunk);+ s = replaceOnce(s, ' const itemsToRender = useMemo(() => items.slice(index), [items, index]);', ` const itemsToRender = useMemo(() => {+ if (typeof itemKey === 'function') {+ committedKeys.current ??= new Set();+ const committed = committedKeys.current;+ return items.filter((item) => {+ const key = itemKey(item);+ return key !== undefined && !committed.has(key);+ });+ }+ return items.slice(index);+ }, [items, index, itemKey, commitTick]);`, hunk);+ s = replaceOnce(s, ' useLayoutEffect(() => {\n setIndex(items.length);\n }, [items.length]);', ` useLayoutEffect(() => {+ if (typeof itemKey === 'function') {+ if (committedKeys.current && itemsToRender.length > 0) {+ for (const item of itemsToRender) {+ committedKeys.current.add(itemKey(item));+ }+ setCommitTick((v) => v + 1);+ }return;- }`);- const writeAnchor = " stream.write(ansiEscapes.eraseLines(eraseCount) + nextRows.slice(firstChange).join('\\n') + '\\n');";- if (!lu.includes(writeAnchor)) return false;- lu = lu.replace(writeAnchor, " stream.write(unpark() + ansiEscapes.eraseLines(eraseCount) + nextRows.slice(firstChange).join('\\n') + '\\n' + park(targetFor(cursor, previousLineCount)));");- const clearAnchor = ` render.clear = () => {- stream.write(ansiEscapes.eraseLines(previousLineCount));`;- if (!lu.includes(clearAnchor)) return false;- lu = lu.replace(clearAnchor, ` render.clear = () => {- stream.write(unpark() + ansiEscapes.eraseLines(previousLineCount));`);- const doneAnchor = ' render.done = () => {';- if (!lu.includes(doneAnchor)) return false;- lu = lu.replace(doneAnchor, ` render.done = () => {- const restore = unpark();- if (restore) stream.write(restore);`);- fs.writeFileSync(logUpdatePath, lu);+ }+ setIndex(items.length);+ }, [itemsToRender, itemKey, items.length]);`, hunk);+ fs.writeFileSync(p.staticJsPath, s);}-- // Types: keep the .d.ts honest for anyone reading the vendored build.- if (fs.existsSync(logUpdateDtsPath)) {- let dts = fs.readFileSync(logUpdateDtsPath, 'utf8');- if (!dts.includes('invalidate')) {- const anchor = ' done: () => void;\n (str: string): void;';- if (dts.includes(anchor)) {- dts = dts.replace(anchor, ` done: () => void;- /** Resize baseline reset (Cosmic Stack patch). */- invalidate: () => void;- /** Hardware cursor (Cosmic Stack patch): \`cursor\` is the live-frame cell to park the terminal cursor on. */- (str: string, cursor?: { row: number; col: number } | null): void;`);- fs.writeFileSync(logUpdateDtsPath, dts);- }- }+ let d = fs.readFileSync(p.staticDtsPath, 'utf8');+ if (!d.includes('itemKey')) {+ d = replaceOnce(d, ' readonly children: (item: T, index: number) => ReactNode;', ` /**+ * Stable identity for an item (Cosmic Stack patch). When set, items are+ * tracked by key instead of position, so \`items\` may drop its oldest+ * entries (a bounded window) without breaking. Return \`undefined\` to skip+ * an item.+ */+ readonly itemKey?: (item: T) => string | undefined;+ readonly children: (item: T, index: number) => ReactNode;`, 'static-item-key (d.ts)');+ fs.writeFileSync(p.staticDtsPath, d);}+ return true;+}- let ink = fs.readFileSync(inkJsPath, 'utf8');- if (!ink.includes(CURSOR_ANCHOR_MARKER)) {- const gateAnchor = `globalThis.${FRAME_GATE_MARKER} = frameGate;`;- if (!ink.includes(gateAnchor)) return false;- ink = ink.replace(gateAnchor, `${gateAnchor}-// ${CURSOR_MARKER}: ink hides the terminal cursor and-// leaves it below the live region, so IME preedit/candidate windows anchor-// in the wrong place and some terminals suppress IME entirely. A host marks-// its fake-cursor cell with the \`internal_cursor\` attribute (Mercury:-// src/ui/cursor-anchor.tsx); after every frame onRender finds that element-// in the live tree and log-update parks the real cursor on it. No marked-// element (non-input views) → the cursor stays hidden. \`enabled: false\`-// turns the feature off globally.+/** Hunks 2–4 all live in ink.js: module globals after `noop`, and the+ * onRender steps between render() and renderFrame(). */+function applyInkJs(p = paths) {+ let s = fs.readFileSync(p.inkJsPath, 'utf8');+ if (s.includes(FRAME_GATE_MARKER) && s.includes(LIVE_REGION_MARKER) && s.includes(CURSOR_ANCHOR_MARKER)) return true;+ const hunk = 'ink.js';+ s = replaceOnce(s, 'const noop = () => { };\n', `const noop = () => { };+// Freeze gate (Cosmic Stack patch): while frozen, onRender writes NOTHING and+// must not advance lastOutput or log-update's baseline, so the frame that+// ends the freeze diffs against what is really on screen. \`armed\` lets+// exactly one frame through (the "⏸ frozen" hint) if it contains \`marker\`.+export const frameGate = { frozen: false, armed: false, marker: '' };+globalThis.${FRAME_GATE_MARKER} = frameGate;+// Cursor anchor (Cosmic Stack patch): after every frame, the element marked+// with the \`internal_cursor\` attribute (Mercury's CursorCell) is located in+// the laid-out live tree and handed to ink's setCursorPosition, so the real+// terminal cursor (and with it IME preedit/candidate windows) sits on the+// input cell. \`enabled: false\` turns it off (MERCURY_HW_CURSOR=0).export const cursorAnchor = { enabled: true };globalThis.${CURSOR_ANCHOR_MARKER} = cursorAnchor;// Patch manifest (Cosmic Stack): which hunks this build carries, and whether-// it is the vendored copy (stamped by scripts/vendor-ink.cjs) or an-// in-place node_modules edit.+// it is the vendored copy (stamped by scripts/vendor-ink.cjs).export const inkPatch = {vendored: false,- hunks: ['yoga-hygiene', 'static-item-key', 'freeze-gate', 'live-region-guard', 'diff-render', 'resize-invalidate', 'cursor-positioning', 'synchronized-output'],+ base: '[email protected]',+ hunks: [${HUNKS.map((h) => `'${h}'`).join(', ')}],};globalThis.__mercuryInkPatch = inkPatch;-const sameCursor = (a, b) => (!a && !b) || (!!a && !!b && a.row === b.row && a.col === b.col);-// Depth-first search for the first element carrying a truthy-// \`internal_cursor\` attribute, accumulating Yoga offsets exactly like-// render-node-to-output does. <Static> subtrees and display:none subtrees-// are never part of the live frame and are skipped. Reading the DOM-// attribute (set in createInstance/commitUpdate) instead of a ref matters:-// refs attach in React's layout phase, AFTER resetAfterCommit has already-// rendered the frame, so a ref-based anchor would always lag one frame.+// Depth-first search for the first element with a truthy \`internal_cursor\`+// attribute, accumulating Yoga offsets like render-node-to-output does.+// <Static> and display:none subtrees are never part of the live frame. The+// DOM attribute is read instead of a ref because refs attach in React's+// layout phase, after the frame has already been rendered.const findCursorCell = (node, x, y) => {const yoga = node.yogaNode;- if (!yoga || node.internal_static || node.style?.display === 'none') return null;+ if (!yoga || node.internal_static || node.style?.display === 'none') return undefined;const nx = x + yoga.getComputedLeft();const ny = y + yoga.getComputedTop();- if (node.attributes?.internal_cursor) return { row: ny, col: nx };- if (!Array.isArray(node.childNodes)) return null;+ if (node.attributes?.internal_cursor) return { x: nx, y: ny };+ if (!Array.isArray(node.childNodes)) return undefined;for (const child of node.childNodes) {const hit = findCursorCell(child, nx, ny);if (hit) return hit;}- return null;-};`);- const onRenderAnchor = ' onRender = () => {';- if (!ink.includes(onRenderAnchor)) return false;- ink = ink.replace(onRenderAnchor, ` // ${CURSOR_MARKER}: absolute cell of the marked cursor- // element inside the live frame, or null when there is none, the feature- // is disabled, or the cell was trimmed away by the live-region guard.- lastCursor = null;- resolveCursor(trimmedRows) {- if (!cursorAnchor.enabled) return null;- const cell = findCursorCell(this.rootNode, 0, 0);- if (!cell) return null;- const row = cell.row - trimmedRows;- if (row < 0) return null;- return { row, col: cell.col };- }-${onRenderAnchor}`);- const maxRowsAnchor = ' const maxLiveRows = Math.max(1, (this.options.stdout.rows || 24) - 1);';- if (!ink.includes(maxRowsAnchor)) return false;- ink = ink.replace(maxRowsAnchor, `${maxRowsAnchor}- const liveHeightBeforeTrim = outputHeight;`);- const trimEndAnchor = ` outputHeight = maxLiveRows;- }`;- if (!ink.includes(trimEndAnchor)) return false;- ink = ink.replace(trimEndAnchor, `${trimEndAnchor}- // ${CURSOR_MARKER}: resolve AFTER the trim so the row- // is relative to the rows actually written.- const cursor = this.resolveCursor(liveHeightBeforeTrim - outputHeight);`);- const staticLogAnchor = ` this.options.stdout.write(staticOutput);- this.log(output);`;- if (!ink.includes(staticLogAnchor)) return false;- ink = ink.replace(staticLogAnchor, ` this.options.stdout.write(staticOutput);- this.log(output, cursor);`);- const tailAnchor = ` if (!hasStaticOutput && output !== this.lastOutput) {- this.throttledLog(output);- }- this.lastOutput = output;- };`;- if (!ink.includes(tailAnchor)) return false;- ink = ink.replace(tailAnchor, ` if (!hasStaticOutput && (output !== this.lastOutput || !sameCursor(cursor, this.lastCursor))) {- this.throttledLog(output, cursor);- }- this.lastOutput = output;- this.lastCursor = cursor;- };`);- // console patching re-prints the last frame after foreign writes: keep the- // cursor parked where it was.- const relog = ' this.log(this.lastOutput);';- if (!ink.includes(relog)) return false;- ink = ink.split(relog).join(' this.log(this.lastOutput, this.lastCursor);');- fs.writeFileSync(inkJsPath, ink);- }- return lu.includes(CURSOR_MARKER) && ink.includes(CURSOR_ANCHOR_MARKER);-}--/** Resize baseline reset: after a terminal resize the rows already on- * screen have re-wrapped, so the diff-render's "unchanged rows above stay"- * assumption is false — identical row BYTES no longer sit at the same- * terminal rows. Ink's `resized` handler now drops `lastOutput` and- * log-update's `previousOutput` baseline (keeping the line count, so the- * erase still covers the old frame) and the next frame repaints whole.- * Applies to both ink.js and log-update.js (after the diff-render edit). */-/** Synchronized output: bracket every frame write in BSU/ESU (DEC private- * mode 2026) so the terminal swaps it in atomically — no visible gap between- * the erase and the redraw, which is the flicker modern terminals show.- * Terminals without 2026 ignore both sequences. log-update brackets its own- * single writes (that also covers the throttled path, which writes later);- * ink.js brackets multi-write sequences (clear + static + frame) as one- * update, and log-update skips its own brackets while one is open.- * Runs after the cursor hunk: it rewrites the unpark() writes that hunk adds. */-function applySynchronizedOutput(p = paths) {- const { logUpdatePath, inkJsPath } = p;- let lu = fs.readFileSync(logUpdatePath, 'utf8');- let ink = fs.readFileSync(inkJsPath, 'utf8');- if (lu.includes(SYNC_MARKER) && ink.includes(SYNC_MARKER)) return true;- if (!lu.includes(SYNC_MARKER)) {- const createAnchor = 'const create = (stream, { showCursor = false } = {}) => {';- const clearAnchor = ' render.clear = () => {';- if (!lu.includes(createAnchor) || !lu.includes(clearAnchor)) return false;- const writes = lu.split('stream.write(unpark()').length - 1;- if (writes < 2) return false;- lu = lu.replace(createAnchor, `// ${SYNC_MARKER}: see ink.js synchronized().-const BSU = '\\u001B[?2026h';-const ESU = '\\u001B[?2026l';-const create = (stream, { showCursor = false, synchronize = false } = {}) => {- // One atomic update per write, unless ink.js already opened one.- const syncWrite = (data) => stream.write(synchronize && !(render.syncDepth > 0) ? BSU + data + ESU : data);`);- lu = lu.split('stream.write(unpark()').join('syncWrite(unpark()');- lu = lu.replace(clearAnchor, ` render.synchronize = synchronize;- render.syncDepth = 0;-${clearAnchor}`);- }- if (!ink.includes(SYNC_MARKER)) {- const createAnchor = 'this.log = logUpdate.create(options.stdout);';- const staticAnchor = ' this.log.clear();\n this.options.stdout.write(staticOutput);\n this.log(output, cursor);';- const writeToAnchor = ' writeToStdout(data) {';- if (!ink.includes(createAnchor) || !ink.includes(staticAnchor) || !ink.includes(writeToAnchor)) return false;- ink = ink.replace(createAnchor, `// ${SYNC_MARKER}: same gate as upstream shouldSynchronize().- this.log = logUpdate.create(options.stdout, { synchronize: Boolean(options.stdout.isTTY) && !isInCi && !options.debug });`);- ink = ink.replace(staticAnchor, ` this.synchronized(() => {- this.log.clear();- this.options.stdout.write(staticOutput);- this.log(output, cursor);- });`);- for (const stream of ['stdout', 'stderr']) {- const block = ` this.log.clear();\n this.options.${stream}.write(data);\n this.log(this.lastOutput, this.lastCursor);`;- if (ink.includes(block)) {- ink = ink.replace(block, ` this.synchronized(() => {- this.log.clear();- this.options.${stream}.write(data);- this.log(this.lastOutput, this.lastCursor);- });`);- }- }- ink = ink.replace(writeToAnchor, ` // ${SYNC_MARKER}: run several writes as ONE terminal update (DEC- // mode 2026), so a new transcript line and the redrawn live region- // appear together instead of erase → static → redraw.- synchronized(write) {- const log = this.log;- if (!log.synchronize) {- write();- return;- }- this.options.stdout.write('\\u001B[?2026h');- log.syncDepth++;- try {- write();- }- finally {- log.syncDepth--;- this.options.stdout.write('\\u001B[?2026l');- }- }-${writeToAnchor}`);- }- fs.writeFileSync(logUpdatePath, lu);- fs.writeFileSync(inkJsPath, ink);- return true;-}--function applyResizeBaselineReset(p = paths) {- const { inkJsPath, logUpdatePath } = p;- let lu = fs.readFileSync(logUpdatePath, 'utf8');- if (!lu.includes(RESIZE_RESET_MARKER)) {- const anchor = ' render.clear = () => {';- if (!lu.includes(anchor)) return false;- lu = lu.replace(anchor, ` // ${RESIZE_RESET_MARKER}: forget what is on screen- // without touching the line count — the next render erases the old- // frame's rows and rewrites every row instead of diffing against rows- // the terminal has already re-wrapped.- render.invalidate = () => {- previousOutput = '';- };-${anchor}`);- fs.writeFileSync(logUpdatePath, lu);- }- let ink = fs.readFileSync(inkJsPath, 'utf8');- if (!ink.includes(RESIZE_RESET_MARKER)) {- const anchor = ` resized = () => {- this.calculateLayout();- this.onRender();- };`;- if (!ink.includes(anchor)) return false;- ink = ink.replace(anchor, ` resized = () => {- // ${RESIZE_RESET_MARKER}: rows that re-wrapped on- // resize must be repainted even when their bytes did not change, so- // the diff-render baseline (ours and log-update's) is dropped first.- this.lastOutput = '';- if (typeof this.log.invalidate === 'function') this.log.invalidate();- this.calculateLayout();- this.onRender();- };`);- fs.writeFileSync(inkJsPath, ink);- }- return lu.includes(RESIZE_RESET_MARKER) && ink.includes(RESIZE_RESET_MARKER);-}--/** Diff-render log-update + freeze gate. Both live in already-patched- * files, so this is an idempotent string-insert on the applied state. */-function applyInkFrameGate(p = paths) {- const { inkJsPath } = p;- let s = fs.readFileSync(inkJsPath, 'utf8');- if (s.includes(FRAME_GATE_MARKER)) return true;- const noopAnchor = "const noop = () => { };";- if (!s.includes(noopAnchor)) return false;- s = s.replace(noopAnchor, `${noopAnchor}-// Freeze gate (Cosmic Stack patch): while frozen, onRender writes NOTHING-// and must not advance lastOutput / log-update's baseline — the resume frame-// must diff against the last frame actually on screen. \`armed\` lets exactly-// one frame through (the "⏸ frozen" hint) if its output contains \`marker\`.-// Exposed on globalThis so host code can reach it without a type-level-// import of this internal module.-export const frameGate = { frozen: false, armed: false, marker: '' };-globalThis.${FRAME_GATE_MARKER} = frameGate;`);- const renderAnchor = " const { output, outputHeight, staticOutput } = render(this.rootNode);";- if (!s.includes(renderAnchor)) return false;- s = s.replace(renderAnchor, `${renderAnchor}- // Freeze gate (Cosmic Stack patch): drop the frame entirely — no- // write, and crucially NO advance of \`lastOutput\` or log-update's- // \`previousOutput\`/\`previousLineCount\` baseline, so the frame that- // ends the freeze diffs against what is actually on screen.+ return undefined;+};+`, hunk);+ s = replaceOnce(s,+ ' const { output, outputHeight, staticOutput } = render(this.rootNode, this.isScreenReaderEnabled);\n',+ ` let { output, outputHeight, staticOutput } = render(this.rootNode, this.isScreenReaderEnabled);+ // Freeze gate (Cosmic Stack patch): drop the frame entirely.if (frameGate.frozen && !(frameGate.armed && frameGate.marker && output.includes(frameGate.marker))) {return;}- if (frameGate.armed) frameGate.armed = false;`);- fs.writeFileSync(inkJsPath, s);- return true;-}--/** Live-region guard: a live frame as tall as (or taller than) the terminal- * must NEVER go through stock ink's fallback — `clearTerminal + full- * static re-dump` — which erases scrollback and re-prints every static byte- * on every frame. Bottom-anchored trim keeps the newest rows instead.- * Inserts right after the freeze gate (both edits live in ink.js). */-function applyInkLiveRegionGuard(p = paths) {- const { inkJsPath } = p;- let s = fs.readFileSync(inkJsPath, 'utf8');- if (s.includes('maxLiveRows')) return true;- const gateAnchor = ' if (frameGate.armed) frameGate.armed = false;';- if (!s.includes(gateAnchor)) return false;- s = s.replace(gateAnchor, `${gateAnchor}- // Live-region guard (Cosmic Stack patch): a live frame as tall as (or- // taller than) the terminal cannot go through log-update's cursor- // arithmetic, and stock ink's fallback is \`clearTerminal +- // fullStaticOutput + output\` — erasing the ENTIRE scrollback buffer- // and re-dumping every static byte ever printed, on EVERY frame. With- // a long transcript that is megabytes per frame: the scrollbar jumps- // to the top, the UI flickers, and native scrolling becomes- // impossible. Instead keep the frame bottom-anchored: trim to what- // fits (rows - 1) and let the normal diff path write it. Scrollback- // is never cleared, the transcript is never re-dumped, and the newest- // rows (live tail, input, status bar) stay visible.- const maxLiveRows = Math.max(1, (this.options.stdout.rows || 24) - 1);- if (outputHeight >= (this.options.stdout.rows || 24)) {- // \`output\` is newline-terminated per row WITHOUT a trailing blank- // line (log-update appends its own), so split and re-join verbatim.- output = output.split('\\n').slice(-maxLiveRows).join('\\n');- outputHeight = maxLiveRows;- }`);- // The trim reassigns output/outputHeight — the declaration must be `let`.- const constLine = 'const { output, outputHeight, staticOutput } = render(this.rootNode);';- if (s.includes(constLine)) s = s.replace(constLine, 'let { output, outputHeight, staticOutput } = render(this.rootNode);');- fs.writeFileSync(inkJsPath, s);- return s.includes('maxLiveRows');-}--/** Diff-render log-update: erase and rewrite only the rows from the first- * changed line onward. Stock ink 5 erased and rewrote the ENTIRE frame on- * every render — a prompt-selection toggle or spinner tick repainted the- * whole live region (a full-UI flash per keystroke). */-function applyLogUpdateDiffRender(p = paths) {- const { logUpdatePath } = p;- let s = fs.readFileSync(logUpdatePath, 'utf8');- if (s.includes('Diff-render (Cosmic Stack patch)')) return true;- const anchor = [- ' previousOutput = output;',- ' stream.write(ansiEscapes.eraseLines(previousLineCount) + output);',- " previousLineCount = output.split('\\n').length;",- ].join('\n');- if (!s.includes(anchor)) return false;- const replacement = [- ' // Diff-render (Cosmic Stack patch): erase and rewrite only the rows',- ' // from the first changed line onward; identical rows above stay on',- ' // screen untouched. Ink 5\'s log-update erased and rewrote the ENTIRE',- ' // frame on every render — a prompt-selection change or spinner tick',- ' // repainted the whole live region, which read as a full-UI flash.',- ' // The row bytes are compared verbatim (layout is deterministic), and',- ' // the erase count accounts for the trailing blank line exactly like',- ' // `previousLineCount` does, so `clear()` and cursor arithmetic stay',- ' // in sync with the original accounting.',- " const previousRows = previousOutput === '' ? [] : previousOutput.slice(0, -1).split('\\n');",- " const nextRows = output.slice(0, -1).split('\\n');",- ' const common = Math.min(previousRows.length, nextRows.length);',- ' let firstChange = 0;',- ' while (firstChange < common && previousRows[firstChange] === nextRows[firstChange]) {',- ' firstChange++;',- ' }',- ' const eraseCount = previousLineCount - firstChange;',- ' previousOutput = output;',- " previousLineCount = output.split('\\n').length;",- " stream.write(ansiEscapes.eraseLines(eraseCount) + nextRows.slice(firstChange).join('\\n') + '\\n');",- ].join('\n');- s = s.replace(anchor, replacement, 1);- fs.writeFileSync(logUpdatePath, s);- return s.includes('Diff-render (Cosmic Stack patch)');-}--function applyReconcilerFix(p = paths) {- const { reconcilerPath } = p;- let s = fs.readFileSync(reconcilerPath, 'utf8');- if (s.includes('clearYogaRefs')) {- const marked = addYogaHygieneMarker(s);- if (marked !== s) fs.writeFileSync(reconcilerPath, marked);- return true;- }-- // 1a. Insert the freed-subtree hygiene helpers after cleanupYogaNode.- const anchorA = `const cleanupYogaNode = (node) => {- node?.unsetMeasureFunc();- node?.freeRecursive();-};`;- const helpers = `${anchorA}-// \`freeRecursive\` releases Yoga's WASM memory but leaves every JavaScript-// reference pointing at freed memory. The renderer and layout code read those-// references through optional chaining, so nulling them here turns what was a-// fatal WASM trap ("RuntimeError: memory access out of bounds" in-// getComputedWidth) into a clean no-op. See facebook/yoga#1818 and the-// equivalent downstream fix in qwen-code#7816. (Cosmic Stack patch.)-const clearYogaRefs = (node) => {- node.yogaNode = undefined;- // Host elements carry a childNodes array; ink's \`#text\` nodes do not.- if (Array.isArray(node.childNodes)) {- for (const child of node.childNodes) {- clearYogaRefs(child);- }- }-};-const containsNode = (ancestor, target) => {- let current = target;- while (current) {- if (current === ancestor) return true;- current = current.parentNode;- }- return false;-};-const cleanupRemovedNode = (node, removeNode) => {- cleanupYogaNode(removeNode.yogaNode);- clearYogaRefs(removeNode);- // \`staticNode\` is cached on the root container, but removeChild receives- // the direct parent — climb to the root before checking.- let rootNode = node;- while (rootNode?.parentNode) rootNode = rootNode.parentNode;- if (rootNode?.staticNode && containsNode(removeNode, rootNode.staticNode)) {- rootNode.staticNode = undefined;- }-};`;- if (!s.includes(anchorA)) return false;- s = s.replace(anchorA, helpers, 1);-- // 1b. Route both removal paths through cleanupRemovedNode.- const oldRemoval = ` removeChildNode(node, removeNode);- cleanupYogaNode(removeNode.yogaNode);`;- const newRemoval = ` removeChildNode(node, removeNode);- cleanupRemovedNode(node, removeNode);`;- let count = 0;- while (s.includes(oldRemoval)) {- s = s.replace(oldRemoval, newRemoval, 1);- count += 1;- }- if (count === 0) return false;- s = addYogaHygieneMarker(s);- fs.writeFileSync(reconcilerPath, s);- return true;-}--/** Runtime marker for the hygiene hunk: the bundled/vendored build has no- * readable reconciler.js on disk, so src/ui/ink-patch-check.ts reads this- * global instead of the file. Idempotent; also upgrades builds patched- * before the marker existed. */-function addYogaHygieneMarker(source) {- if (source.includes(YOGA_HYGIENE_MARKER)) return source;- const anchor = 'export default createReconciler({';- if (!source.includes(anchor)) return source;- return source.replace(anchor, `globalThis.${YOGA_HYGIENE_MARKER} = true;\n${anchor}`);-}--const PATCHED_STATIC_JS = `import React, { useMemo, useState, useLayoutEffect, useRef } from 'react';-/**- * \`<Static>\` component permanently renders its output above everything else.- * It's useful for displaying activity like completed tasks or logs - things that- * are not changing after they're rendered (hence the name "Static").- *- * It's preferred to use \`<Static>\` for use cases like these, when you can't know- * or control the amount of items that need to be rendered.- *- * For example, [Tap](https://github.com/tapjs/node-tap) uses \`<Static>\` to display- * a list of completed tests. [Gatsby](https://github.com/gatsbyjs/gatsby) uses it- * to display a list of generated pages, while still displaying a live progress bar.- *- * Patched (Cosmic Stack): supports an optional \`itemKey\` identity function.- * The built-in positional index assumes \`items\` only ever appends — a caller- * that keeps the array bounded by dropping the oldest items (a sliding- * window) breaks it: \`items.slice(index)\` returns nothing, new items are- * never rendered, and every commit unmounts the whole subtree. With- * \`itemKey\`, each item is tracked by identity and rendered exactly once per- * instance lifetime, so bounded sliding windows are safe.- */-export default function Static(props) {- const { items, children: render, style: customStyle, itemKey } = props;- const [index, setIndex] = useState(0);- // Identity of items already written to the terminal in this instance.- // Only used when \`itemKey\` is provided.- const committedKeys = useRef(null);- // Bumped after committing keys so the memo recomputes and the rendered- // children are unmounted — the positional path does this via setIndex.- // Without it, committed children stay mounted and the renderer keeps- // re-printing them into the terminal on EVERY subsequent render (each- // pass re-emits \`staticOutput\` while the nodes are still attached).- const [commitTick, setCommitTick] = useState(0);- const itemsToRender = useMemo(() => {- if (typeof itemKey === 'function') {- if (!committedKeys.current) {- committedKeys.current = new Set();- }- const committed = committedKeys.current;- const out = [];- for (const item of items) {- const key = itemKey(item);- if (key !== undefined && !committed.has(key)) {- out.push(item);- }+ if (frameGate.armed) frameGate.armed = false;+ // ${LIVE_REGION_MARKER}: a live frame as tall as the viewport is+ // written whole by stock ink, and on the primary screen every row+ // past the viewport scrolls into scrollback, so each repaint while+ // a reply streams stamps another copy of the live region into the+ // user's history. Keep the newest rows (input, status bar, the live+ // tail) and send the trimmed frame through the normal diff path.+ const liveHeightBeforeTrim = outputHeight;+ if (this.interactive && !this.alternateScreen && !this.isScreenReaderEnabled && !this.options.debug && this.options.stdout.isTTY) {+ const viewportRows = getWindowSize(this.options.stdout).rows;+ if (outputHeight >= viewportRows) {+ const maxLiveRows = Math.max(1, viewportRows - 1);+ output = output.split('\\n').slice(-maxLiveRows).join('\\n');+ outputHeight = maxLiveRows;}- return out;}- return items.slice(index);- }, [items, index, itemKey, commitTick]);- useLayoutEffect(() => {- if (typeof itemKey === 'function') {- if (committedKeys.current && itemsToRender.length > 0) {- for (const item of itemsToRender) {- committedKeys.current.add(itemKey(item));- }- // Unmount what was just written: without this, the nodes stay- // attached and every later render re-prints them (duplicate- // transcript lines accumulating over time).- setCommitTick((v) => v + 1);+ // Cursor anchor (Cosmic Stack patch): resolved after the trim, so the+ // row is relative to the rows actually written. Only a CHANGE is+ // pushed: setCursorPosition marks the cursor dirty, and a dirty+ // cursor forces a rewrite of an otherwise unchanged frame.+ if (cursorAnchor.enabled && !this.isScreenReaderEnabled) {+ const cell = findCursorCell(this.rootNode, 0, 0);+ const row = cell ? cell.y - (liveHeightBeforeTrim - outputHeight) : -1;+ const next = cell && row >= 0 ? { x: cell.x, y: row } : undefined;+ if (next?.x !== this.cursorPosition?.x || next?.y !== this.cursorPosition?.y) {+ this.setCursorPosition(next);}- return;}- setIndex(items.length);- }, [itemsToRender, itemKey, items.length]);- const children = itemsToRender.map((item, itemIndex) => {- return render(item, itemIndex);- });- const style = useMemo(() => ({- position: 'absolute',- flexDirection: 'column',- ...customStyle,- }), [customStyle]);- return (React.createElement("ink-box", { internal_static: true, style: style }, children));-}-//# sourceMappingURL=Static.js.map`;--const ITEMKEY_DTS = ` /**- * Optional identity function used to track which items have already been- * rendered. When provided, each item is rendered exactly once per- * \`<Static>\` instance lifetime even if the \`items\` array is kept bounded- * by shifting the window (which the built-in positional index cannot- * handle). Keys returning \`undefined\` are ignored.- */- readonly itemKey?: (item: T) => string | undefined;-};`;--function applyStaticFix(p = paths) {- const { staticJsPath, staticDtsPath } = p;- const staticJs = fs.readFileSync(staticJsPath, 'utf8');- if (staticJs.includes('itemKey')) {- // Already (partially) applied — ensure the commitTick variant.- if (staticJs.includes('setCommitTick')) return true;- fs.writeFileSync(staticJsPath, PATCHED_STATIC_JS);- return true;- }- fs.writeFileSync(staticJsPath, PATCHED_STATIC_JS);-- const dts = fs.readFileSync(staticDtsPath, 'utf8');- if (!dts.includes('itemKey')) {- const anchor = ' readonly children: (item: T, index: number) => ReactNode;\n};';- if (dts.includes(anchor)) {- fs.writeFileSync(staticDtsPath, dts.replace(anchor, ` readonly children: (item: T, index: number) => ReactNode;\n${ITEMKEY_DTS}`));- }- }+`, hunk);+ fs.writeFileSync(p.inkJsPath, s);return true;}-/**- * Apply every hunk to an ink build. `opts.inkDir` targets a `build/`- * directory directly (vendoring); otherwise the ink resolvable from- * `opts.root` (default: this checkout's node_modules) is patched in place.- */function apply(opts = {}) {const p = pathsFor(opts.root ?? root, { inkDir: opts.inkDir });if (isPatched(p)) return { ok: true, applied: false };- if (!fs.existsSync(p.reconcilerPath)) {+ if (!fs.existsSync(p.inkJsPath)) {return { ok: false, applied: false, error: `ink build not found at ${p.inkDir}` };}try {- const reconcilerOk = applyReconcilerFix(p);- const staticOk = applyStaticFix(p);- const frameGateOk = applyInkFrameGate(p);- const liveRegionOk = applyInkLiveRegionGuard(p);- const diffRenderOk = applyLogUpdateDiffRender(p);- const resizeResetOk = applyResizeBaselineReset(p);- const cursorOk = applyCursorPositioning(p);- const syncOk = cursorOk && applySynchronizedOutput(p);- if (!cursorOk) {- return { ok: false, applied: true, error: 'hardware cursor positioning could not be inserted (ink.js onRender / log-update.js render anchors)' };- }- if (!syncOk) {- return { ok: false, applied: true, error: 'synchronized output could not be inserted (ink.js log/static/writeToStdout or log-update.js create/clear anchors)' };- }- if (!reconcilerOk) {- return { ok: false, applied: true, error: 'reconciler.js no longer matches the expected ink 5.2.1 shape — patch anchors not found' };- }- if (!staticOk) {- return { ok: false, applied: true, error: 'Static.js could not be rewritten' };- }- if (!frameGateOk) {- return { ok: false, applied: true, error: 'ink.js frame gate could not be inserted' };- }- if (!liveRegionOk) {- return { ok: false, applied: true, error: 'ink.js live-region guard could not be inserted' };- }- if (!diffRenderOk) {- return { ok: false, applied: true, error: 'log-update.js diff-render could not be inserted' };- }- if (!resizeResetOk) {- return { ok: false, applied: true, error: 'resize baseline reset could not be inserted (ink.js resized / log-update.js clear anchors)' };- }+ applyStaticItemKey(p);+ applyInkJs(p);} catch (err) {return { ok: false, applied: true, error: err.message };}@@ -776,24 +260,4 @@ function isVendoredPatched() {return isPatched(pathsFor(root, { inkDir: VENDORED_INK_DIR }));}-module.exports = { isPatched, apply, pathsFor, isVendoredPatched, VENDORED_INK_DIR };--if (require.main === module) {- // CLI: `node scripts/apply-ink-patch.cjs [--ink-dir <build dir>]`. Without- // an explicit dir this patches node_modules/ink in place — only useful for- // experiments now that the runtime uses vendor/ink (scripts/vendor-ink.cjs).- const argv = process.argv.slice(2);- const dirFlag = argv.indexOf('--ink-dir');- const inkDir = dirFlag >= 0 ? path.resolve(argv[dirFlag + 1] || '') : undefined;- const result = apply({ inkDir });- if (result.ok && result.applied) {- console.log(' ✓ ink fixes applied (Yoga hygiene, Static.itemKey, freeze gate, live-region guard, diff-render, resize invalidate, hardware cursor)');- } else if (result.ok) {- console.log(' ✓ ink fixes already applied');- } else {- console.error(' ⚠ INK FIXES NOT APPLIED — the Yoga WASM crash class is UNPATCHED in this build.');- console.error(` Reason: ${result.error}`);- console.error(' Fix: node scripts/vendor-ink.cjs (regenerates vendor/ink from the stock tarball).');- process.exitCode = 1;- }-}\ No newline at end of file+module.exports = { isPatched, apply, pathsFor, isVendoredPatched, VENDORED_INK_DIR, HUNKS };diff --git a/scripts/apply-ink-patch.test.ts b/scripts/apply-ink-patch.test.tsindex b40c7e38..ec5c01ea 100644--- a/scripts/apply-ink-patch.test.ts+++ b/scripts/apply-ink-patch.test.ts@@ -14,132 +14,92 @@ const { apply, isPatched, pathsFor, isVendoredPatched, VENDORED_INK_DIR } = requ};/**- * The bundled ink fixes (Yoga WASM hygiene, Static identity dedup, freeze- * gate, live-region guard, log-update diff-render) must be applicable- * WITHOUT patch-package — that is exactly what failed on Termux CI- * (`sh: 1: patch-package: not found`) and left stock ink's clearTerminal- * fallback live, failing the live-region-guard tests. These tests run the- * applier against a synthetic ink tree carrying the real 5.2.1 anchors.+ * The applier must patch a stock ink 8.0.0 build deterministically and fail+ * loudly when ink changes shape. These tests run it against a synthetic ink+ * tree carrying the real 8.0.0 anchors (copied verbatim from the tarball).*/-/** Stock-shaped ink 5.2.1 files containing only the anchors the applier matches. */+/** Stock-shaped ink 8.0.0 files containing only the anchors the applier matches. */function writeStockInk(root: string): void {const build = join(root, 'node_modules', 'ink', 'build');mkdirSync(join(build, 'components'), { recursive: true });- writeFileSync(join(build, 'reconciler.js'), [- 'import { appendChildNode, insertBeforeNode, removeChildNode } from "./dom.js";',- 'const cleanupYogaNode = (node) => {',- ' node?.unsetMeasureFunc();',- ' node?.freeRecursive();',- '};',- 'const somethingElse = (node) => {',- ' removeChildNode(node, removeNode);',- ' cleanupYogaNode(removeNode.yogaNode);',- '};',- ' removeChildNode(node, removeNode);',- ' cleanupYogaNode(removeNode.yogaNode);',+ writeFileSync(join(build, 'components', 'Static.js'), [+ "import React, { useMemo, useState, useLayoutEffect, use, } from 'react';",+ 'export default function Static(props) {',+ ' const { items, children: render, style: customStyle } = props;',+ ' const [index, setIndex] = useState(0);',+ ' const itemsToRender = useMemo(() => items.slice(index), [items, index]);',+ ' useLayoutEffect(() => {',+ ' setIndex(items.length);',+ ' }, [items.length]);',+ ' return null;',+ '}',+ ].join('\n'));+ writeFileSync(join(build, 'components', 'Static.d.ts'), [+ 'export type Props<T> = {',+ ' readonly items: T[];',+ ' readonly children: (item: T, index: number) => ReactNode;','};',- 'export default createReconciler({',- '});',].join('\n'));- // Stock Static.js: no itemKey, no commitTick — the applier rewrites it wholesale.- writeFileSync(join(build, 'components', 'Static.js'), "import React from 'react';\nexport default function Static(props) {\n return null;\n}\n");- writeFileSync(join(build, 'components', 'Static.d.ts'), ' readonly children: (item: T, index: number) => ReactNode;\n};\n');writeFileSync(join(build, 'ink.js'), [- 'import logUpdate from \'./log-update.js\';',+ "import { getWindowSize } from './utils.js';",'const noop = () => { };','export default class Ink {',- ' constructor(options) {',- ' this.log = logUpdate.create(options.stdout);',- ' }',- ' resized = () => {',- ' this.calculateLayout();',- ' this.onRender();',- ' };',' onRender = () => {',- ' const { output, outputHeight, staticOutput } = render(this.rootNode);',- ' const hasStaticOutput = staticOutput && staticOutput !== \'\\n\';',- ' if (hasStaticOutput) {',- ' this.log.clear();',- ' this.options.stdout.write(staticOutput);',- ' this.log(output);',- ' }',- ' if (!hasStaticOutput && output !== this.lastOutput) {',- ' this.throttledLog(output);',- ' }',- ' this.lastOutput = output;',+ ' const startTime = performance.now();',+ ' const { output, outputHeight, staticOutput } = render(this.rootNode, this.isScreenReaderEnabled);',+ ' const renderTime = performance.now() - startTime;',+ ' this.renderFrame(output, outputHeight, staticOutput);',' };',- ' writeToStdout(data) {',- ' this.log.clear();',- ' this.options.stdout.write(data);',- ' this.log(this.lastOutput);',- ' }','}',].join('\n'));- writeFileSync(join(build, 'log-update.js'), [- 'const create = (stream, { showCursor = false } = {}) => {',- ' let previousLineCount = 0;',- ' let previousOutput = \'\';',- ' let hasHiddenCursor = false;',- ' const render = (str) => {',- " const output = str + '\\n';",- ' if (output === previousOutput) {',- ' return;',- ' }',- ' previousOutput = output;',- ' stream.write(ansiEscapes.eraseLines(previousLineCount) + output);',- " previousLineCount = output.split('\\n').length;",- ' };',- ' render.clear = () => {',- ' stream.write(ansiEscapes.eraseLines(previousLineCount));',- ' };',- ' render.done = () => {',- ' };',- ' return render;',- '};',- ].join('\n'));}-describe('ink patch applier (patch-package-free)', () => {- it('fully patches a stock synthetic ink install — no patch-package needed', () => {+describe('ink patch applier (ink 8)', () => {+ it('patches a stock synthetic ink 8 build, idempotently', () => {const root = mkdtempSync(join(tmpdir(), 'mercury-ink-patch-'));try {writeStockInk(root);const result = apply({ root });- expect(result.ok).toBe(true);- expect(result.applied).toBe(true);- expect(result.error).toBeUndefined();- expect(isPatched(pathsFor(root))).toBe(true);+ expect(result).toEqual({ ok: true, applied: true });const paths = pathsFor(root);+ expect(isPatched(paths)).toBe(true);const inkJs = readFileSync(paths.inkJsPath, 'utf8');- const logUpdate = readFileSync(paths.logUpdatePath, 'utf8');- // Resize baseline reset: resized() drops both diff baselines BEFORE- // the re-layout + render, and log-update exposes the invalidate hook.- expect(logUpdate).toContain('render.invalidate = () => {');- const resized = inkJs.slice(inkJs.indexOf('resized = () => {'), inkJs.indexOf('onRender() {'));- expect(resized).toContain("this.lastOutput = '';");- expect(resized).toContain('this.log.invalidate()');- expect(resized.indexOf('this.log.invalidate()')).toBeLessThan(resized.indexOf('this.calculateLayout()'));- // Hardware cursor: every frame write unparks first and parks after- // (through syncWrite, see the synchronized-output checks below),- // and both log() call sites pass the resolved cell through.- expect(logUpdate).toContain('const render = (str, cursor) => {');- expect(inkJs).toContain('this.log(output, cursor);');- expect(inkJs).toContain('this.throttledLog(output, cursor);');- expect(inkJs).toContain('this.log(this.lastOutput, this.lastCursor);');- expect(inkJs).toContain('node.attributes?.internal_cursor');- expect(readFileSync(paths.reconcilerPath, 'utf8')).toContain('globalThis.__mercuryInkYogaHygiene = true;');- // Synchronized output: log-update brackets its own writes, ink.js- // brackets clear + static + frame as one update, gated on a TTY.- expect(logUpdate).toContain('syncWrite(unpark() + ansiEscapes.eraseLines(eraseCount)');- expect(logUpdate).toContain('syncWrite(unpark() + ansiEscapes.eraseLines(previousLineCount))');- expect(logUpdate).not.toContain('stream.write(unpark()');- expect(inkJs).toContain('synchronize: Boolean(options.stdout.isTTY) && !isInCi && !options.debug');- expect(inkJs).toMatch(/this\.synchronized\(\(\) => \{\n\s+this\.log\.clear\(\);\n\s+this\.options\.stdout\.write\(staticOutput\);/);- // Idempotent: a second run must recognize the applied state and no-op.- const again = apply({ root });- expect(again.ok).toBe(true);- expect(again.applied).toBe(false);+ const staticJs = readFileSync(paths.staticJsPath, 'utf8');+ // Static: keyed path next to the positional one, plus the commit tick.+ expect(staticJs).toContain('const { items, children: render, style: customStyle, itemKey } = props;');+ expect(staticJs).toContain('setCommitTick((v) => v + 1);');+ expect(staticJs).toContain('return items.slice(index);');+ expect(readFileSync(paths.staticDtsPath, 'utf8')).toContain('readonly itemKey?: (item: T) => string | undefined;');+ // ink.js: the three steps run between render() and renderFrame(), in order.+ const onRender = inkJs.slice(inkJs.indexOf('onRender = () => {'));+ const gate = onRender.indexOf('frameGate.frozen');+ const trim = onRender.indexOf('Live-region guard (Cosmic Stack patch)');+ const cursor = onRender.indexOf('findCursorCell(this.rootNode, 0, 0)');+ const frame = onRender.indexOf('this.renderFrame(output, outputHeight, staticOutput);');+ expect(gate).toBeGreaterThan(0);+ expect(gate).toBeLessThan(trim);+ expect(trim).toBeLessThan(cursor);+ expect(cursor).toBeLessThan(frame);+ expect(onRender).toContain('let { output, outputHeight, staticOutput } = render(');+ expect(inkJs).toContain("hunks: ['static-item-key', 'freeze-gate', 'live-region-guard', 'cursor-anchor'],");+ expect(inkJs).toContain('vendored: false,');+ // Idempotent: a second run recognises the applied state.+ expect(apply({ root })).toEqual({ ok: true, applied: false });+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ it('fails loudly, naming the hunk, when ink changed shape', () => {+ const root = mkdtempSync(join(tmpdir(), 'mercury-ink-patch-'));+ try {+ writeStockInk(root);+ const inkJs = pathsFor(root).inkJsPath;+ writeFileSync(inkJs, readFileSync(inkJs, 'utf8').replace('render(this.rootNode, this.isScreenReaderEnabled)', 'render(this.rootNode)'));+ const result = apply({ root });+ expect(result.ok).toBe(false);+ expect(result.error).toMatch(/^ink\.js: anchor not found/);} finally {rmSync(root, { recursive: true, force: true });}diff --git a/scripts/post-build.cjs b/scripts/post-build.cjsindex 9a9f2982..b57ba1fb 100644--- a/scripts/post-build.cjs+++ b/scripts/post-build.cjs@@ -21,12 +21,13 @@ function copyDirSync(src, dest) {// 0. ADR-017: the patched ink (vendor/ink) must be INSIDE the bundle — a// bare `import "ink"` would load whatever stock ink npm put in node_modules-// and silently lose every fix (Yoga hygiene, Static.itemKey, hardware cursor).+// and silently lose every fix (Static.itemKey, freeze gate, live-region+// guard, hardware cursor).{const bundle = fs.readFileSync(path.join(__dirname, '..', 'dist', 'index.js'), 'utf8');const problems = [];if (/(?:from|import\()\s*["']ink["']/.test(bundle)) problems.push('dist/index.js imports "ink" at runtime (tsup alias/noExternal missing)');- for (const marker of ['__mercuryFrameGate', '__mercuryCursorAnchor', '__mercuryInkYogaHygiene', 'vendored: true']) {+ for (const marker of ['__mercuryFrameGate', '__mercuryCursorAnchor', 'maxLiveRows', 'setCommitTick', 'vendored: true']) {if (!bundle.includes(marker)) problems.push(`vendored ink marker missing from the bundle: ${marker}`);}if (problems.length) {diff --git a/scripts/vendor-ink.cjs b/scripts/vendor-ink.cjsindex a8e8314e..279d888d 100644--- a/scripts/vendor-ink.cjs+++ b/scripts/vendor-ink.cjs@@ -2,17 +2,17 @@/*** Regenerate `vendor/ink/` — the patched ink build Mercury bundles (ADR-017).*- * node scripts/vendor-ink.cjs [--tarball <ink-5.2.1.tgz>] [--check]+ * node scripts/vendor-ink.cjs [--tarball <ink-8.0.0.tgz>] [--check]** Pipeline, fully deterministic from a pinned stock tarball:- * 1. obtain the stock `[email protected]` tarball (the given path, or `npm pack`+ * 1. obtain the stock `[email protected]` tarball (the given path, or `npm pack`* into a temp dir) and verify its registry integrity (sha512);* 2. extract it and copy only what the runtime needs — `build/` (minus* source maps), `package.json` (trimmed of dev-only fields), `license`;* 3. run the Mercury patch set (`scripts/apply-ink-patch.cjs`, the single* source of truth for every hunk) against the copy and stamp it as* vendored (`inkPatch.vendored = true`);- * 4. rewrite `patches/ink+5.2.1.patch` as `git diff --no-index` of stock+ * 4. rewrite `patches/ink+8.0.0.patch` as `git diff --no-index` of stock* vs patched `build/`, so the whole delta stays reviewable in one file.** `--check` performs steps 1-3 into a temp dir and fails if the result@@ -31,9 +31,9 @@ const { execFileSync, spawnSync } = require('node:child_process');const { apply, isPatched, pathsFor } = require('./apply-ink-patch.cjs');const root = path.join(__dirname, '..');-const INK_VERSION = '5.2.1';-/** `dist.integrity` of [email protected] on registry.npmjs.org. */-const INK_INTEGRITY = 'sha512-BqcUyWrG9zq5HIwW6JcfFHsIYebJkWWb4fczNah1goUO0vv5vneIlfwuS85twyJ5hYR/y18FlAYUxrO9ChIWVg==';+const INK_VERSION = '8.0.0';+/** `dist.integrity` of [email protected] on registry.npmjs.org. */+const INK_INTEGRITY = 'sha512-M2aFwZOqmkFxCwedy6xrP4E+DGoK57iahAFnfTqNyOyJ54O7DZzu027z/NI8EGy44Sw9O9BcbTF4QEUS2GHAtg==';const VENDOR_DIR = path.join(root, 'vendor', 'ink');const PATCH_FILE = path.join(root, 'patches', `ink+${INK_VERSION}.patch`);/** package.json fields that only matter for developing ink itself. */diff --git a/scripts/verify-package.cjs b/scripts/verify-package.cjsindex 294276d5..7912c676 100755--- a/scripts/verify-package.cjs+++ b/scripts/verify-package.cjs@@ -93,10 +93,11 @@ check('better-sqlite3 is optional', () => {}});-check('engines requires >=20', () => {+check('engines requires >=22', () => {const pkg = JSON.parse(readFileSync(join(modDir, 'package.json'), 'utf-8'));- if (!pkg.engines || !pkg.engines.node || !pkg.engines.node.includes('20')) {- throw new Error('engines.node should require >=20.0.0');+ // ink 8 (the vendored TUI renderer) requires Node 22.+ if (!pkg.engines || !pkg.engines.node || !pkg.engines.node.includes('22')) {+ throw new Error('engines.node should require >=22.0.0');}});diff --git a/src/channels/cli.ts b/src/channels/cli.tsindex 7e792a18..90045b1d 100644--- a/src/channels/cli.ts+++ b/src/channels/cli.ts@@ -1283,8 +1283,27 @@ export class CLIChannel extends BaseChannel {onInterrupt: () => { this.interruptTurn(); },spotifyClient: this.spotifyClient,}),- { exitOnCtrlC: false, patchConsole: false, stdin: (this.stdinProxy ?? process.stdin) as unknown as NodeJS.ReadStream, stdout: this.tuiOutput as unknown as NodeJS.WriteStream },+ {+ exitOnCtrlC: false,+ patchConsole: false,+ // Rewrite only the changed part of each line (ink 8). Replaces the+ // diff-render hunk Mercury carried on ink 5.+ incrementalRendering: true,+ stdin: (this.stdinProxy ?? process.stdin) as unknown as NodeJS.ReadStream,+ stdout: this.tuiOutput as unknown as NodeJS.WriteStream,+ },);+ // After the output wrapper had to shed writes, the screen no longer+ // matches the renderer's baseline: clear() makes the next frame a full+ // repaint, and the same-size 'resize' triggers it.+ const output = this.tuiOutput;+ const ink = this.inkInstance;+ if (output) {+ output.onResync = () => {+ ink.clear();+ output.emit('resize');+ };+ }}/**diff --git a/src/index.ts b/src/index.tsindex 8936888e..30e8eae3 100644--- a/src/index.ts+++ b/src/index.ts@@ -2292,7 +2292,7 @@ function runPlatformDoctor(): void {console.log(chalk.dim(' Cross-platform runtime compatibility report'));console.log('');console.log(` OS: ${chalk.white(process.platform)} (${process.arch})`);- console.log(` Node.js: ${chalk.white(process.version)} (required >= 20)`);+ console.log(` Node.js: ${chalk.white(process.version)} (required >= 22)`);console.log(` Terminal program: ${chalk.white(termProgram)}`);console.log(` TERM: ${chalk.white(term)}`);console.log(` Interactive TTY: ${isTTY ? chalk.green('yes') : chalk.yellow('no')}`);diff --git a/src/ui/hardware-cursor.test.tsx b/src/ui/hardware-cursor.test.tsxindex 81fcfc74..09d8b6ce 100644--- a/src/ui/hardware-cursor.test.tsx+++ b/src/ui/hardware-cursor.test.tsx@@ -2,51 +2,50 @@ import { describe, expect, it, vi } from 'vitest';// Ink skips frame writes when it detects CI (`is-in-ci`); '0' is the one// value it treats as false. Must run before ink loads.-// FORCE_COLOR: the fake cell's inverse SGR is how these tests locate it.vi.hoisted(() => {process.env.CI = '0';- process.env.FORCE_COLOR = '1';});import React from 'react';import { render, Box, Text, Static } from 'ink';import { EventEmitter } from 'node:events';-import stringWidth from 'string-width';import { CursorCell, hardwareCursorEnabled, configureHardwareCursor } from './cursor-anchor.js';import { MercuryCodeView, TuiApp } from './App.js';import { CLIChannel } from '../channels/cli.js';import type { TuiState } from '../channels/cli.js';+import { VtScreen } from './vt-screen.js';/*** Hardware cursor positioning (#41, #66) against the REAL vendored ink:- * after every frame the terminal cursor must be parked — shown — exactly on- * the input's fake-cursor cell, so IME preedit/candidate windows anchor- * there; it must be hidden and moved back below the live region before the- * next frame is written (the diff-render erase arithmetic depends on it),- * and stay hidden while no input owns the keyboard.+ * after every frame the terminal cursor must be shown exactly on the input's+ * fake-cursor cell, so IME preedit/candidate windows anchor there, and stay+ * hidden while no input owns the keyboard.+ *+ * Ink 8 owns the cursor plumbing (setCursorPosition); Mercury's patch only+ * resolves the `internal_cursor` cell from the layout. So these tests check+ * the RESULT on an emulated terminal — where the cursor ends up and whether+ * it is visible — not the escape sequences used to get there.*/const SHOW = '\x1b[?25h';-const HIDE = '\x1b[?25l';-const INVERSE = '\x1b[7m';-const ESC = String.fromCharCode(27);-// CUU n, CHA col, DECTCEM show — exactly what log-update's park() writes.-const PARK_RE = new RegExp(`${ESC}\\[(\\d+)A${ESC}\\[(\\d+)G${ESC}\\[\\?25h$`);-const stripAnsi = (s: string) => s.replace(new RegExp(`${ESC}\\[[0-9;?]*[A-Za-z]`, 'g'), '');--// Synchronized output (DEC 2026) brackets every frame; it is framing, not-// content, so the cursor assertions below see chunks without it.+// Synchronized output (DEC 2026) brackets every frame on ink 8.const BSU = '\x1b[?2026h';const ESU = '\x1b[?2026l';+/** Glyph for the fake cursor cell in the fixtures, so it is easy to find. */+const MARK = '▮';class FakeStdout extends EventEmitter {chunks: string[] = [];raw: string[] = [];- columns = 80;- rows = 30;isTTY = true;+ screen: VtScreen;+ constructor(public columns = 80, public rows = 30) {+ super();+ this.screen = new VtScreen(columns, rows);+ }write(chunk: string): boolean {this.raw.push(chunk);+ this.screen.write(chunk);const content = chunk.split(BSU).join('').split(ESU).join('');if (content) this.chunks.push(content);return true;@@ -54,6 +53,13 @@ class FakeStdout extends EventEmitter {get output(): string {return this.chunks.join('');}+ resize(columns: number, rows = this.rows): void {+ this.columns = columns;+ this.rows = rows;+ this.screen.columns = columns;+ this.screen.rows = rows;+ this.emit('resize');+ }}async function waitFor(pred: () => boolean, timeoutMs = 4000): Promise<void> {@@ -62,29 +68,26 @@ async function waitFor(pred: () => boolean, timeoutMs = 4000): Promise<void> {if (!pred()) throw new Error('condition not met in time');}-/** Last chunk ending in a park sequence. */-const lastParkChunk = (stdout: FakeStdout) => [...stdout.chunks].reverse().find((c) => PARK_RE.test(c));+/** Last cell on the emulated screen holding `ch`, as { row, col }. */+function cellOf(screen: VtScreen, ch: string): { row: number; col: number } | null {+ for (let row = screen.lines.length - 1; row >= 0; row--) {+ const col = screen.lines[row].lastIndexOf(ch);+ if (col >= 0) return { row, col };+ }+ return null;+}-/**- * For a FULL-frame write (first frame, or a repaint after resize), derive- * where the inverse cell sits from the frame text itself and compare it with- * the park sequence that followed. Returns both for assertions.- */-function analyse(chunk: string): { parked: { up: number; col: number }; expected: { up: number; col: number }; rows: string[] } {- const m = PARK_RE.exec(chunk)!;- const parked = { up: Number(m[1]), col: Number(m[2]) - 1 };- const frameEnd = chunk.length - m[0].length;- // eraseLines(n) ends with a bare CHA (`ESC[G`); the frame text follows it.- const eraseEnd = chunk.lastIndexOf(`${ESC}[G`, frameEnd);- const frame = chunk.slice(eraseEnd < 0 ? 0 : eraseEnd + 3, frameEnd);- const rows = frame.split('\n').slice(0, -1); // trailing '\n' after the last row- const rowIdx = rows.findIndex((r) => r.includes(INVERSE));- expect(rowIdx).toBeGreaterThanOrEqual(0);- const col = stringWidth(stripAnsi(rows[rowIdx].slice(0, rows[rowIdx].indexOf(INVERSE))));- return { parked, expected: { up: rows.length - rowIdx, col }, rows };+/** Where the real cursor is, when it is shown. */+const cursorAt = (screen: VtScreen) => (screen.cursorVisible ? { row: screen.row, col: screen.col } : null);++/** True once the shown cursor sits on the cell holding `ch`. */+function cursorOn(stdout: FakeStdout, ch = MARK): boolean {+ const target = cellOf(stdout.screen, ch);+ const at = cursorAt(stdout.screen);+ return !!target && !!at && at.row === target.row && at.col === target.col;}-function Prompt({ before, glyph, after = '', active = true, lead = 0 }: { before: string; glyph: string; after?: string; active?: boolean; lead?: number }) {+function Prompt({ before, glyph = MARK, after = '', active = true, lead = 0 }: { before: string; glyph?: string; after?: string; active?: boolean; lead?: number }) {return (<Box flexDirection="column">{Array.from({ length: lead }, (_, i) => <Text key={i}>transcript row {i}</Text>)}@@ -102,58 +105,47 @@ function Prompt({ before, glyph, after = '', active = true, lead = 0 }: { before);}+const opts = (stdout: FakeStdout) => ({ stdout: stdout as never, exitOnCtrlC: false, patchConsole: false });+describe('hardware cursor positioning (vendored ink)', () => {- it('parks the real cursor exactly on the fake cursor cell, including after wide (CJK) text', async () => {+ it('shows the real cursor exactly on the fake cursor cell, including after wide (CJK) text', async () => {const stdout = new FakeStdout();- const { unmount } = render(<Prompt before="日本語 ok" glyph="x" after="yz" />, { stdout: stdout as any, exitOnCtrlC: false, patchConsole: false });- await waitFor(() => !!lastParkChunk(stdout));- const { parked, expected, rows } = analyse(lastParkChunk(stdout)!);- expect(parked).toEqual(expected);- // header, border, input row, border, status → input row is 3rd of 5;+ const { unmount } = render(<Prompt before="日本語 ok" after="yz" />, opts(stdout));+ await waitFor(() => cursorOn(stdout));// col = border(1) + padding(1) + "> "(2) + width("日本語 ok")(9) = 13.- expect(rows).toHaveLength(5);- expect(expected).toEqual({ up: 3, col: 13 });+ expect(cursorAt(stdout.screen)?.col).toBe(13);+ expect(stdout.screen.lines[stdout.screen.row].join('')).toContain('> 日本語 ok▮yz');unmount();});- it('unparks (hide + move back below the frame) before every later write', async () => {+ it('follows the cell as the user types', async () => {const stdout = new FakeStdout();- const { rerender, unmount } = render(<Prompt before="ab" glyph=" " />, { stdout: stdout as any, exitOnCtrlC: false, patchConsole: false });- await waitFor(() => !!lastParkChunk(stdout));- const first = analyse(lastParkChunk(stdout)!);- const mark = stdout.chunks.length;- rerender(<Prompt before="abc" glyph=" " />);- await waitFor(() => stdout.chunks.slice(mark).some((c) => PARK_RE.test(c)));- const next = stdout.chunks.slice(mark).find((c) => PARK_RE.test(c))!;- // Unpark first — the erase arithmetic assumes the cursor sits below the- // last row at column 0 — then the diff-rendered row, then re-park.- expect(next.startsWith(`${HIDE}${ESC}[${first.parked.up}B${ESC}[G`)).toBe(true);- const m = PARK_RE.exec(next)!;- expect(Number(m[1])).toBe(first.parked.up);- expect(Number(m[2]) - 1).toBe(first.parked.col + 1); // one more char typed+ const { rerender, unmount } = render(<Prompt before="ab" />, opts(stdout));+ await waitFor(() => cursorOn(stdout));+ const first = cursorAt(stdout.screen)!;+ rerender(<Prompt before="abc" />);+ await waitFor(() => cursorOn(stdout) && cursorAt(stdout.screen)!.col === first.col + 1);+ expect(cursorAt(stdout.screen)!.row).toBe(first.row);unmount();});- it('re-parks without repainting when only the cursor moves', async () => {+ it('hides the cursor without repainting the frame when only the cursor changes', async () => {const stdout = new FakeStdout();- const { rerender, unmount } = render(<Prompt before="abc" glyph="d" after="" />, { stdout: stdout as any, exitOnCtrlC: false, patchConsole: false });- await waitFor(() => !!lastParkChunk(stdout));+ const { rerender, unmount } = render(<Prompt before="abc" glyph="d" />, opts(stdout));+ await waitFor(() => cursorOn(stdout, 'd'));const mark = stdout.chunks.length;- // Same text, cursor one cell left: identical bytes except the inverse cell- // moved, so rows differ; then a pure cursor toggle with identical rows.- rerender(<Prompt before="abc" glyph="d" after="" active={false} />);- await waitFor(() => stdout.chunks.slice(mark).some((c) => c.includes(HIDE)));- const hideChunk = stdout.chunks.slice(mark).find((c) => c.includes(HIDE))!;- // Rows are byte-identical (the attribute is not rendered): the only write- // is the unpark — no erase, no frame text, and no show.- expect(hideChunk).toMatch(new RegExp(`^${ESC}\\[\\?25l${ESC}\\[\\d+B${ESC}\\[G$`));- expect(stdout.chunks.slice(mark).join('')).not.toContain(SHOW);+ // Same text: only the anchor attribute changes, which is not rendered.+ rerender(<Prompt before="abc" glyph="d" active={false} />);+ await waitFor(() => !stdout.screen.cursorVisible);+ const after = stdout.chunks.slice(mark).join('');+ expect(after).not.toContain('abc'); // no frame text rewritten+ expect(after).not.toContain(SHOW);unmount();});it('keeps the cursor hidden while no input owns the keyboard', async () => {const stdout = new FakeStdout();- const { unmount } = render(<Prompt before="abc" glyph=" " active={false} />, { stdout: stdout as any, exitOnCtrlC: false, patchConsole: false });+ const { unmount } = render(<Prompt before="abc" active={false} />, opts(stdout));await waitFor(() => stdout.output.includes('status bar'));await new Promise((r) => setTimeout(r, 80));expect(stdout.output).not.toContain(SHOW);@@ -161,58 +153,43 @@ describe('hardware cursor positioning (vendored ink)', () => {});it('accounts for rows trimmed by the live-region guard', async () => {- const stdout = new FakeStdout();- stdout.rows = 10; // frame is 5 + 20 rows → trimmed to the newest 9- const { unmount } = render(<Prompt before="hi" glyph=" " lead={20} />, { stdout: stdout as any, exitOnCtrlC: false, patchConsole: false });- await waitFor(() => !!lastParkChunk(stdout));- const { parked, expected, rows } = analyse(lastParkChunk(stdout)!);- expect(rows).toHaveLength(9);- expect(parked).toEqual(expected);+ const stdout = new FakeStdout(80, 10); // frame is 5 + 20 rows → trimmed to the newest 9+ const { unmount } = render(<Prompt before="hi" lead={20} />, opts(stdout));+ await waitFor(() => cursorOn(stdout));+ // The trimmed rows were never written, so the cursor's row is real.+ expect(stdout.screen.text().some((l) => l.includes('transcript row 0'))).toBe(false);unmount();});- it('repaints and re-parks correctly after a resize, and after <Static> output', async () => {+ it('stays on the cell after <Static> output and after a resize', async () => {const stdout = new FakeStdout();- const items = ['first static line'];const tree = (its: string[]) => (<><Static items={its}>{(item) => <Text key={item}>{item}</Text>}</Static>- <Prompt before="résumé" glyph=" " />+ <Prompt before="résumé" /></>);- const { rerender, unmount } = render(tree(items), { stdout: stdout as any, exitOnCtrlC: false, patchConsole: false });- await waitFor(() => !!lastParkChunk(stdout));-- // New static item: ink clears the live region (unpark first), writes the- // static line, then the full live frame + park.- let mark = stdout.chunks.length;- rerender(tree([...items, 'second static line']));- await waitFor(() => stdout.chunks.slice(mark).some((c) => PARK_RE.test(c)));- const afterStatic = stdout.chunks.slice(mark);- expect(afterStatic.join('')).toContain('second static line');- const s = analyse(afterStatic.find((c) => PARK_RE.test(c))!);- expect(s.parked).toEqual(s.expected);-- // Resize: baseline invalidated, whole frame rewritten, cursor re-parked.- mark = stdout.chunks.length;- stdout.columns = 40;- stdout.emit('resize');- await waitFor(() => stdout.chunks.slice(mark).some((c) => PARK_RE.test(c)));- const resized = stdout.chunks.slice(mark).find((c) => PARK_RE.test(c))!;- expect(resized.startsWith(HIDE)).toBe(true);- const r = analyse(resized);- expect(r.parked).toEqual(r.expected);+ const { rerender, unmount } = render(tree(['first static line']), opts(stdout));+ await waitFor(() => cursorOn(stdout));++ rerender(tree(['first static line', 'second static line']));+ await waitFor(() => stdout.output.includes('second static line') && cursorOn(stdout));++ stdout.resize(40);+ await new Promise((r) => setTimeout(r, 120));+ await waitFor(() => cursorOn(stdout));unmount();});- it('restores the cursor below the frame on unmount', async () => {+ it('leaves the cursor below the frame on unmount', async () => {const stdout = new FakeStdout();- const { unmount } = render(<Prompt before="x" glyph=" " />, { stdout: stdout as any, exitOnCtrlC: false, patchConsole: false });- await waitFor(() => !!lastParkChunk(stdout));- const { parked } = analyse(lastParkChunk(stdout)!);- const mark = stdout.chunks.length;+ const { unmount } = render(<Prompt before="x" />, opts(stdout));+ await waitFor(() => cursorOn(stdout));unmount();- expect(stdout.chunks.slice(mark).join('')).toContain(`${HIDE}${ESC}[${parked.up}B${ESC}[G`);+ const status = stdout.screen.lines.findIndex((l) => l.join('').includes('status bar'));+ expect(status).toBeGreaterThanOrEqual(0);+ expect(stdout.screen.row).toBeGreaterThan(status);+ expect(stdout.screen.col).toBe(0);});it('honours MERCURY_HW_CURSOR=0 (global toggle on the vendored ink)', async () => {@@ -221,7 +198,7 @@ describe('hardware cursor positioning (vendored ink)', () => {configureHardwareCursor({ MERCURY_HW_CURSOR: 'off' });try {const stdout = new FakeStdout();- const { unmount } = render(<Prompt before="x" glyph=" " />, { stdout: stdout as any, exitOnCtrlC: false, patchConsole: false });+ const { unmount } = render(<Prompt before="x" />, opts(stdout));await waitFor(() => stdout.output.includes('status bar'));await new Promise((r) => setTimeout(r, 80));expect(stdout.output).not.toContain(SHOW);@@ -234,8 +211,7 @@ describe('hardware cursor positioning (vendored ink)', () => {/*** Frame bytes written outside any BSU…ESU bracket (should be none while- * mounted). Cursor show/hide toggles (ink hides it once at startup) are- * mode switches, not frame content.+ * mounted). Cursor show/hide toggles are mode switches, not frame content.*/function unbracketed(raw: string[]): string {let depth = 0;@@ -250,10 +226,10 @@ function unbracketed(raw: string[]): string {depth += next === open ? 1 : -1;rest = rest.slice(next + BSU.length);}- return outside.split(HIDE).join('').split(SHOW).join('');+ return outside.split('\x1b[?25l').join('').split(SHOW).join('');}-describe('synchronized output (vendored ink, DEC 2026)', () => {+describe('synchronized output (ink 8, DEC 2026)', () => {function Transcript({ lines, live }: { lines: string[]; live: string }) {return (<>@@ -265,7 +241,7 @@ describe('synchronized output (vendored ink, DEC 2026)', () => {it('brackets every frame write on a TTY, so the terminal paints it atomically', async () => {const stdout = new FakeStdout();- const { rerender, unmount } = render(<Transcript lines={[]} live="tick 0" />, { stdout: stdout as never, exitOnCtrlC: false, patchConsole: false });+ const { rerender, unmount } = render(<Transcript lines={[]} live="tick 0" />, opts(stdout));for (let i = 1; i <= 5; i++) {rerender(<Transcript lines={[]} live={`tick ${i}`} />);await new Promise((r) => setTimeout(r, 40));@@ -278,20 +254,17 @@ describe('synchronized output (vendored ink, DEC 2026)', () => {it('writes a new transcript line and the redrawn live region as ONE update', async () => {const stdout = new FakeStdout();- const { rerender, unmount } = render(<Transcript lines={['first line']} live="working" />, { stdout: stdout as never, exitOnCtrlC: false, patchConsole: false });+ const { rerender, unmount } = render(<Transcript lines={['first line']} live="working" />, opts(stdout));await waitFor(() => stdout.output.includes('working'));const mark = stdout.raw.length;rerender(<Transcript lines={['first line', 'second line']} live="done" />);await waitFor(() => stdout.output.includes('done'));const update = stdout.raw.slice(mark).join('');const open = update.indexOf(BSU);- const close = update.indexOf(ESU, open);- // Erase, the static line and the new frame all sit between one BSU/ESU.+ const inside = update.slice(open, update.indexOf(ESU, open));expect(open).toBeGreaterThanOrEqual(0);- const inside = update.slice(open, close);expect(inside).toContain('second line');expect(inside).toContain('done');- expect(inside.indexOf('second line')).toBeLessThan(inside.indexOf('done'));expect(unbracketed(stdout.raw)).toBe('');unmount();});@@ -299,10 +272,11 @@ describe('synchronized output (vendored ink, DEC 2026)', () => {it('never emits mode 2026 when the output is not a TTY', async () => {const stdout = new FakeStdout();stdout.isTTY = false;- const { rerender, unmount } = render(<Transcript lines={['a']} live="x" />, { stdout: stdout as never, exitOnCtrlC: false, patchConsole: false });+ const { rerender, unmount } = render(<Transcript lines={['a']} live="x" />, opts(stdout));rerender(<Transcript lines={['a', 'b']} live="y" />);- await waitFor(() => stdout.output.includes('y'));+ await new Promise((r) => setTimeout(r, 120));unmount();+ expect(stdout.raw.join('')).toContain('b');expect(stdout.raw.join('')).not.toContain('2026');});});@@ -331,22 +305,30 @@ function mercuryState(overrides: Partial<Record<string, unknown>> = {}): TuiStat} as unknown as TuiState;}+/** The shown cursor sits right after `text` on a row that contains `line`. */+function cursorAfter(stdout: FakeStdout, line: string, text: string): boolean {+ const at = cursorAt(stdout.screen);+ if (!at) return false;+ const cells = stdout.screen.lines[at.row] ?? [];+ if (!cells.join('').includes(line)) return false;+ // Column just past `text`: find its last character's cell, then step over it.+ const lastChar = [...text].pop()!;+ const col = cells.lastIndexOf(lastChar, at.col - 1);+ return col >= 0 && at.col === col + (cells[col + 1] === '' ? 2 : 1);+}+describe('hardware cursor in the Mercury Code view', () => {- it('parks on the input cell of a real TUI frame, and the anchor never leaks into the terminal', async () => {+ it('sits on the input cell of a real TUI frame, and the anchor never leaks into the terminal', async () => {const stdout = new FakeStdout();const input = 'fix 漢字 bug';const cursorPos = 'fix 漢字'.length; // on the space before "bug"const { unmount } = render(<MercuryCodeView state={mercuryState()} cols={80} rows={30} input={input} cursorPos={cursorPos} />,- { stdout: stdout as any, exitOnCtrlC: false, patchConsole: false },+ opts(stdout),);- await waitFor(() => !!lastParkChunk(stdout));- const { parked, expected, rows } = analyse(lastParkChunk(stdout)!);- expect(parked).toEqual(expected);- // The cell sits inside the bordered input box: "│ > fix 漢字" → paddingX 2,- // border 1, padding 1, "> " 2, "fix " 4, 漢字 4 = col 14.- expect(expected.col).toBe(14);- expect(stripAnsi(rows[rows.length - expected.up])).toContain('> fix 漢字 bug');+ await waitFor(() => cursorAfter(stdout, '> fix 漢字 bug', 'fix 漢字'));+ // "│ > fix 漢字": paddingX 2, border 1, padding 1, "> " 2, "fix " 4, 漢字 4 = col 14.+ expect(cursorAt(stdout.screen)?.col).toBe(14);expect(stdout.output).not.toContain('internal_cursor');expect(stdout.output).not.toContain('true');unmount();@@ -359,7 +341,7 @@ describe('hardware cursor in the Mercury Code view', () => {});const { unmount } = render(<MercuryCodeView state={state} cols={80} rows={30} input="abc" cursorPos={3} />,- { stdout: stdout as any, exitOnCtrlC: false, patchConsole: false },+ opts(stdout),);await waitFor(() => stdout.output.includes('Proceed?'));await new Promise((r) => setTimeout(r, 80));@@ -397,10 +379,10 @@ function mountTuiApp(state: TuiState) {const stdin = new FakeStdin();const app = render(<TuiApp channel={channel} onInput={() => {}} onPermissionResolve={() => {}} onExit={() => {}} />,- { stdout: stdout as any, stdin: stdin as any, exitOnCtrlC: false, patchConsole: false },+ { stdout: stdout as never, stdin: stdin as never, exitOnCtrlC: false, patchConsole: false },);- const setState = (patch: Partial<TuiState>) => {- snapshot = { ...snapshot, ...patch } as TuiState;+ const setState = (patch: Record<string, unknown>) => {+ snapshot = { ...snapshot, ...patch } as unknown as TuiState;for (const l of listeners) l();};return { stdout, stdin, setState, unmount: app.unmount };@@ -409,36 +391,25 @@ function mountTuiApp(state: TuiState) {const baseState = (patch: Record<string, unknown>): TuiState => ({ ...new CLIChannel().getTuiStateSnapshot(), ...patch } as TuiState);describe('hardware cursor in TuiApp', () => {- it('chat: typed CJK input parks the cursor on the cell after it', async () => {+ it('chat: typed CJK input puts the cursor on the cell after it', async () => {const { stdout, stdin, unmount } = mountTuiApp(baseState({ mode: 'chat' }));await waitFor(() => stdout.output.includes('[CHAT]'));stdin.type('日本');- await waitFor(() => stdout.output.includes('日本') && !!lastParkChunk(stdout));- // Force one full repaint so the frame text can be analysed end to end.- const mark = stdout.chunks.length;- stdout.emit('resize');- await waitFor(() => stdout.chunks.slice(mark).some((c) => PARK_RE.test(c)));- const { parked, expected, rows } = analyse(stdout.chunks.slice(mark).find((c) => PARK_RE.test(c))!);- expect(parked).toEqual(expected);+ await waitFor(() => cursorAfter(stdout, '> 日本', '日本'));// "> 日本" inside paddingX 1: 1 + 2 + 4 = column 7.- expect(expected.col).toBe(7);- expect(stripAnsi(rows[rows.length - expected.up])).toContain('> 日本');+ expect(cursorAt(stdout.screen)?.col).toBe(7);unmount();});it('chat: a permission prompt hides the cursor; dismissing it brings it back', async () => {const { stdout, setState, unmount } = mountTuiApp(baseState({ mode: 'chat' }));- await waitFor(() => !!lastParkChunk(stdout));- const mark = stdout.chunks.length;- setState({ permissionPrompt: { type: 'choice', message: 'Proceed?', options: [{ value: 'y', label: 'Yes' }], resolve: () => {} } } as any);- await waitFor(() => stdout.output.includes('Proceed?'));+ await waitFor(() => stdout.screen.cursorVisible && stdout.output.includes(SHOW));+ setState({ permissionPrompt: { type: 'choice', message: 'Proceed?', options: [{ value: 'y', label: 'Yes' }], resolve: () => {} } });+ await waitFor(() => stdout.output.includes('Proceed?') && !stdout.screen.cursorVisible);await new Promise((r) => setTimeout(r, 80));- const during = stdout.chunks.slice(mark).join('');- expect(during.startsWith(HIDE)).toBe(true);- expect(during).not.toContain(SHOW);- const mark2 = stdout.chunks.length;- setState({ permissionPrompt: null } as any);- await waitFor(() => stdout.chunks.slice(mark2).some((c) => PARK_RE.test(c)));+ expect(stdout.screen.cursorVisible).toBe(false);+ setState({ permissionPrompt: null });+ await waitFor(() => stdout.screen.cursorVisible);unmount();});@@ -454,7 +425,7 @@ describe('hardware cursor in TuiApp', () => {await new Promise((r) => setTimeout(r, 80));expect(stdout.output).not.toContain(SHOW);stdin.type('q');- await waitFor(() => !!lastParkChunk(stdout));+ await waitFor(() => stdout.output.includes(SHOW) && stdout.screen.cursorVisible);unmount();});});diff --git a/src/ui/ink-patch-check.test.ts b/src/ui/ink-patch-check.test.tsindex 51e5d01a..d6dd4993 100644--- a/src/ui/ink-patch-check.test.ts+++ b/src/ui/ink-patch-check.test.ts@@ -12,7 +12,7 @@ import {INK_PATCH_MARKERS,} from './ink-patch-check.js';-const VENDORED_MANIFEST = { vendored: true, hunks: ['yoga-hygiene', 'static-item-key', 'freeze-gate', 'live-region-guard', 'diff-render', 'resize-invalidate', 'cursor-positioning', 'synchronized-output'] };+const VENDORED_MANIFEST = { vendored: true, hunks: ['static-item-key', 'freeze-gate', 'live-region-guard', 'cursor-anchor'] };const PATCHED_STATIC = 'export default function Static(props) { const { itemKey } = props; const [t, setCommitTick] = useState(0); }';const STOCK_STATIC = 'export default function Static(props) { const { items, children: render } = props; }';@@ -57,7 +57,7 @@ describe('evaluateInkPatch (vendored build, ADR-017)', () => {staticSource: STOCK_STATIC, reconcilerSource: STOCK_RECONCILER,});expect(s).toEqual({ patched: true, missing: [], source: 'vendored' });- expect(describeInkPatch(s)).toBe('vendored (patched ink 5.2.1 bundled)');+ expect(describeInkPatch(s)).toBe('vendored (patched ink 8.0.0 bundled)');});it('names every missing runtime marker of a broken vendored build', () => {@@ -66,7 +66,6 @@ describe('evaluateInkPatch (vendored build, ADR-017)', () => {expect(s.missing).toEqual([INK_PATCH_MARKERS.frameGate,INK_PATCH_MARKERS.staticItemKey,- INK_PATCH_MARKERS.yogaHygiene,INK_PATCH_MARKERS.cursor,]);expect(describeInkPatch(s)).toMatch(/^MISSING/);diff --git a/src/ui/ink-patch-check.ts b/src/ui/ink-patch-check.tsindex 1ea14610..aba40fb3 100644--- a/src/ui/ink-patch-check.ts+++ b/src/ui/ink-patch-check.ts@@ -1,7 +1,7 @@/*** Runtime detection of the Mercury ink patch set.*- * Since ADR-017 ink is VENDORED: `vendor/ink` (stock 5.2.1 + the hunks in+ * Since ADR-017 ink is VENDORED: `vendor/ink` (stock 8.0.0 + the hunks in* scripts/apply-ink-patch.cjs, regenerated by scripts/vendor-ink.cjs) is* bundled into dist by tsup and aliased in vitest. The vendored build stamps* `globalThis.__mercuryInkPatch = { vendored: true, hunks }` and every hunk@@ -85,9 +85,10 @@ export function evaluateInkPatch(probe: InkPatchProbe): InkPatchStatus {const manifest = asManifest(probe.manifest);if (manifest?.vendored) {// Vendored build: every hunk is observable through runtime globals.+ // Yoga hygiene is upstream since ink 8 (freeYogaSubtree), so the+ // vendored build no longer carries or reports it.if (!probe.frameGate || typeof probe.frameGate !== 'object') missing.push(INK_PATCH_MARKERS.frameGate);if (!manifest.hunks.includes('static-item-key')) missing.push(INK_PATCH_MARKERS.staticItemKey);- if (probe.yogaHygiene !== true) missing.push(INK_PATCH_MARKERS.yogaHygiene);if (!probe.cursorAnchor || typeof probe.cursorAnchor !== 'object') missing.push(INK_PATCH_MARKERS.cursor);return { patched: missing.length === 0, missing, source: 'vendored' };}@@ -165,7 +166,7 @@ export function findInkPatchScript(startDir: string = dirname(fileURLToPath(impo/** One-line description for `mercury doctor`. */export function describeInkPatch(status: InkPatchStatus): string {if (!status.patched) return `MISSING (${status.missing.join('; ')})`;- return status.source === 'vendored' ? 'vendored (patched ink 5.2.1 bundled)' : 'applied (node_modules)';+ return status.source === 'vendored' ? 'vendored (patched ink 8.0.0 bundled)' : 'applied (node_modules)';}/** The one command a user should run to fix an unpatched install. Everydiff --git a/src/ui/live-region-guard.test.tsx b/src/ui/live-region-guard.test.tsxindex c99b5d71..5284681b 100644--- a/src/ui/live-region-guard.test.tsx+++ b/src/ui/live-region-guard.test.tsx@@ -13,6 +13,7 @@ import { render, Box, Text, Static } from 'ink';import { EventEmitter } from 'node:events';import { MercuryCodeView } from './App.js';import type { TuiState } from '../channels/cli.js';+import { VtScreen } from './vt-screen.js';class FakeStdout extends EventEmitter {chunks: string[] = [];@@ -124,10 +125,22 @@ guard('ink live-region overflow guard', () => {expect(stdout.output.split('static message one').length - 1).toBe(dumpCount);expect(stdout.output).not.toContain('\x1b[3J');- // The bottom of the live region must stay visible (bottom-anchored trim):- // the newest rows — what the user is reading — survive the trim.- const lastChunk = stdout.chunks[stdout.chunks.length - 1];- expect(lastChunk).toContain('live row 39 tick');+ // Replay the bytes on a 12-row screen. The bottom of the live region+ // must be what is visible (bottom-anchored trim), and no repaint may+ // have stamped copies of the live rows into scrollback: each live row+ // the user can find exists at most once.+ const screen = new VtScreen(80, 12);+ screen.write(stdout.output);+ const lines = screen.text();+ expect(lines.slice(-12).join('\n')).toContain('live row 39 tick');+ for (const row of ['live row 30', 'live row 35', 'live row 39 tick']) {+ expect(lines.filter((l) => l.trim() === row).length, row).toBeLessThanOrEqual(1);+ }+ // Rows trimmed off the top of an over-tall frame are never written, so+ // they cannot scroll into the user's history. Stock ink 8 writes the+ // whole frame and pushes them into scrollback on every repaint.+ expect(lines.some((l) => l.trim() === 'live row 0')).toBe(false);+ expect(lines.some((l) => l.trim() === 'live row 0 tick')).toBe(false);unmount();}, 10_000);diff --git a/src/ui/resilient-output.ts b/src/ui/resilient-output.tsindex 26cc6805..ea2802dc 100644--- a/src/ui/resilient-output.ts+++ b/src/ui/resilient-output.ts@@ -17,6 +17,12 @@ export class ResilientTuiOutput extends EventEmitter {private active: TtyWriteStream;private failedOver = false;private outOfSync = false;+ /**+ * How to repaint after shed writes. The TUI sets this to clear the frame+ * (so the next one is written whole) and re-render. Without it, a+ * same-size 'resize' is emitted, which only re-renders.+ */+ onResync: (() => void) | null = null;private readonly onPrimaryError = () => this.failOver();private readonly onFallbackError = () => {// There is nowhere else to render, but an output failure must not kill an@@ -115,8 +121,8 @@ export class ResilientTuiOutput extends EventEmitter {this.outOfSync = true;destination.once('drain', () => {this.outOfSync = false;- // Ink's resize path forgets the on-screen baseline and rewrites every row.- this.emit('resize');+ if (this.onResync) this.onResync();+ else this.emit('resize');});}diff --git a/src/ui/static-transcript.test.ts b/src/ui/static-transcript.test.tsindex 04fd1e61..ab878c3b 100644--- a/src/ui/static-transcript.test.ts+++ b/src/ui/static-transcript.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { readFileSync, existsSync } from 'node:fs';+import { readFileSync } from 'node:fs';import { fileURLToPath } from 'node:url';import { dirname, join } from 'node:path';@@ -23,32 +23,25 @@ const read = (p: string) => readFileSync(join(repo, p), 'utf8');* unmounted the entire static subtree (mass freeRecursive churn).*/describe('ink static-transcript crash fixes', () => {- it('ships an ink patch that nulls freed Yoga references and clears staticNode', () => {- const patchPath = join(repo, 'patches', 'ink+5.2.1.patch');- expect(existsSync(patchPath)).toBe(true);- const patch = readFileSync(patchPath, 'utf8');- // Freed-subtree reference hygiene (reconciler).- expect(patch).toContain('clearYogaRefs');- expect(patch).toContain('cleanupRemovedNode');- // ink's `#text` nodes have no childNodes array — the traversal must- // guard (unguarded iteration crashed: "node.childNodes is not iterable").- expect(patch).toContain('Array.isArray(node.childNodes)');- // Dangling staticNode cache must be cleared when the removed subtree- // contains the static node — not only when the node itself is removed.- expect(patch).toContain('rootNode.staticNode = undefined');- // Key-based <Static> dedup (bounded sliding windows are safe).- expect(patch).toContain('itemKey');+ it('ships ink 8, whose own reconciler nulls freed Yoga references and clears staticNode', () => {+ // Defect 1 is fixed upstream since ink 8 (freeYogaSubtree ++ // clearStaticNodeIfContained), so Mercury no longer patches it. Guard+ // against a downgrade that would bring the crash back.+ expect(JSON.parse(read('vendor/ink/package.json')).version).toBe('8.0.0');+ const dom = read('vendor/ink/build/dom.js');+ expect(dom).toContain('nullifyYogaNodes(removedNode)');+ const reconciler = read('vendor/ink/build/reconciler.js');+ expect(reconciler).toContain('clearStaticNodeIfContained(findRootNode(node), removedNode)');+ expect(reconciler).toContain('freeYogaSubtree(removedNode)');});- it('has the patch applied to the vendored ink that ships in the bundle', () => {- // Ink is vendored and bundled (ADR-017); node_modules/ink is stock and- // unused at runtime. If this fails, regenerate with `npm run vendor:ink`.- const reconciler = read('vendor/ink/build/reconciler.js');- expect(reconciler).toContain('clearYogaRefs');- expect(reconciler).toContain('Array.isArray(node.childNodes)');- expect(reconciler).toContain('rootNode.staticNode = undefined');+ it('has the key-based <Static> patch applied to the vendored ink that ships in the bundle', () => {+ // Defect 2 is still Mercury's patch. If this fails, regenerate with+ // `node scripts/vendor-ink.cjs`.+ expect(read('patches/ink+8.0.0.patch')).toContain('itemKey');const staticComponent = read('vendor/ink/build/components/Static.js');expect(staticComponent).toContain('itemKey');+ expect(staticComponent).toContain('setCommitTick');});it('passes itemKey to every <Static> usage in App.tsx', () => {diff --git a/src/ui/use-terminal-size.ts b/src/ui/use-terminal-size.tsindex 60681505..1ba265be 100644--- a/src/ui/use-terminal-size.ts+++ b/src/ui/use-terminal-size.ts@@ -9,9 +9,12 @@ import { subscribe as subscribeTick } from './tick-store.js';* changes, and a stale size breaks any explicit-width layout. The check* is a property read; the component re-renders only when the size* actually changed (the snapshot object is reused while it is equal).+ * (Ink 8's useWindowSize() only listens for resize, hence the own hook.)*/export function useTerminalSize(): { rows: number; cols: number } {- const { stdout } = useStdout();+ // Ink 8 types stdout as a generic stream; the TTY size fields are read+ // defensively (`|| 24/80`) for the non-TTY case anyway.+ const stdout = useStdout().stdout as NodeJS.WritableStream & { rows?: number; columns?: number };const cacheRef = React.useRef<{ rows: number; cols: number }>({ rows: stdout.rows || 24, cols: stdout.columns || 80 });const getSnapshot = React.useCallback(() => {const rows = stdout.rows || 24;diff --git a/src/ui/vt-screen.ts b/src/ui/vt-screen.tsindex feb8dae7..ec01191f 100644--- a/src/ui/vt-screen.ts+++ b/src/ui/vt-screen.ts@@ -1,10 +1,14 @@+import stringWidth from 'string-width';+/*** A minimal VT100-style screen for tests: replays what the TUI writes and* returns the visible text, including scrollback. It understands exactly* the sequences Ink, log-update and the cursor-parking patch emit — cursor- * moves, line/screen erases, save/restore, show/hide — and ignores colour.+ * moves, line/screen erases, save/restore, cursor show/hide — and ignores+ * colour. Wide (CJK) characters take two cells: the second holds '' so a+ * cell index is always a terminal column.* Used to assert that transient live-region rows (spinners, "Processing")- * never survive into the transcript.+ * never survive into the transcript, and where the real cursor ends up.*/export class VtScreen {/** Every line ever written (scrollback + viewport). */@@ -12,6 +16,8 @@ export class VtScreen {row = 0;col = 0;private saved: { row: number; col: number } | null = null;+ /** DECTCEM: `ESC[?25h` shows the cursor, `ESC[?25l` hides it. */+ cursorVisible = true;constructor(public columns = 100, public rows = 40) {}@@ -25,7 +31,9 @@ export class VtScreen {}private put(ch: string): void {- if (this.col >= this.columns) {+ const width = stringWidth(ch);+ if (width === 0) return;+ if (this.col + width > this.columns) {this.row += 1;this.col = 0;}@@ -33,7 +41,8 @@ export class VtScreen {const line = this.lines[this.row];while (line.length < this.col) line.push(' ');line[this.col] = ch;- this.col += 1;+ if (width === 2) line[this.col + 1] = '';+ this.col += width;}write(data: string): void {@@ -73,7 +82,11 @@ export class VtScreen {}private csi(params: string, final: string): void {- if (params.startsWith('?')) return; // modes: cursor show/hide, bracketed paste, mouse+ if (params === '?25' && (final === 'h' || final === 'l')) {+ this.cursorVisible = final === 'h';+ return;+ }+ if (params.startsWith('?')) return; // other modes: bracketed paste, mouse, sync outputconst nums = params.split(';').map((p) => (p === '' ? NaN : Number(p)));const n = Number.isNaN(nums[0]) ? 1 : nums[0];switch (final) {diff --git a/tsup.config.ts b/tsup.config.tsindex c98dad12..ea73a30c 100644--- a/tsup.config.ts+++ b/tsup.config.ts@@ -24,7 +24,7 @@ const channelStamp = process.env.MERCURY_CHANNEL_VERSION || '';export default defineConfig({entry: ["src/index.ts"],format: ["esm"],- target: "node20",+ target: "node22",outDir: "dist",clean: true,bundle: true,@@ -32,12 +32,17 @@ export default defineConfig({sourcemap: true,minify: false,// createRequire: ink's bundled CommonJS dependencies (signal-exit 3, …)- // `require()` node builtins, which an ESM bundle has no global for.+ // `require()` node builtins, which an ESM bundle has no global for. Then a+ // Node version gate, which runs before any Mercury code.banner: {js: ["#!/usr/bin/env node",'import { createRequire as __mercuryCreateRequire } from "node:module";',"const require = __mercuryCreateRequire(import.meta.url);",+ // ink 8 (the TUI renderer) needs Node 22 (Promise.withResolvers and+ // friends). Say so up front instead of crashing at the first render.+ // Bun reports its own Node-compat version, so it is exempt.+ 'if (!process.versions.bun && Number(process.versions.node.split(".")[0]) < 22) { console.error("Mercury needs Node.js 22 or newer (found " + process.version + "). Upgrade Node, e.g. `nvm install 22`."); process.exit(1); }',].join("\n"),},// Inject the version so standalone binaries (Bun --compile) can read itdiff --git a/vendor/ink/build/ansi-tokenizer.d.ts b/vendor/ink/build/ansi-tokenizer.d.tsnew file mode 100644index 00000000..0f4459f3--- /dev/null+++ b/vendor/ink/build/ansi-tokenizer.d.ts@@ -0,0 +1,38 @@+type ControlStringType = 'osc' | 'dcs' | 'pm' | 'apc' | 'sos';+type CsiToken = {+ readonly type: 'csi';+ readonly value: string;+ readonly parameterString: string;+ readonly intermediateString: string;+ readonly finalCharacter: string;+};+type EscToken = {+ readonly type: 'esc';+ readonly value: string;+ readonly intermediateString: string;+ readonly finalCharacter: string;+};+type ControlStringToken = {+ readonly type: ControlStringType;+ readonly value: string;+};+type TextToken = {+ readonly type: 'text';+ readonly value: string;+};+type StToken = {+ readonly type: 'st';+ readonly value: string;+};+type C1Token = {+ readonly type: 'c1';+ readonly value: string;+};+type InvalidToken = {+ readonly type: 'invalid';+ readonly value: string;+};+export type AnsiToken = TextToken | CsiToken | EscToken | ControlStringToken | StToken | C1Token | InvalidToken;+export declare const hasAnsiControlCharacters: (text: string) => boolean;+export declare const tokenizeAnsi: (text: string) => AnsiToken[];+export {};diff --git a/vendor/ink/build/ansi-tokenizer.js b/vendor/ink/build/ansi-tokenizer.jsnew file mode 100644index 00000000..6ebaac5e--- /dev/null+++ b/vendor/ink/build/ansi-tokenizer.js@@ -0,0 +1,316 @@+const bellCharacter = '\u{7}';+const escapeCharacter = '\u{1B}';+const stringTerminatorCharacter = '\u{9C}';+const csiCharacter = '\u{9B}';+const oscCharacter = '\u{9D}';+const dcsCharacter = '\u{90}';+const pmCharacter = '\u{9E}';+const apcCharacter = '\u{9F}';+const sosCharacter = '\u{98}';+const isCsiParameterCharacter = (character) => {+ const codePoint = character.codePointAt(0);+ return codePoint !== undefined && codePoint >= 0x30 && codePoint <= 0x3f;+};+const isCsiIntermediateCharacter = (character) => {+ const codePoint = character.codePointAt(0);+ return codePoint !== undefined && codePoint >= 0x20 && codePoint <= 0x2f;+};+const isCsiFinalCharacter = (character) => {+ const codePoint = character.codePointAt(0);+ return codePoint !== undefined && codePoint >= 0x40 && codePoint <= 0x7e;+};+const isEscapeIntermediateCharacter = (character) => {+ const codePoint = character.codePointAt(0);+ return codePoint !== undefined && codePoint >= 0x20 && codePoint <= 0x2f;+};+const isEscapeFinalCharacter = (character) => {+ const codePoint = character.codePointAt(0);+ return codePoint !== undefined && codePoint >= 0x30 && codePoint <= 0x7e;+};+const isC1ControlCharacter = (character) => {+ const codePoint = character.codePointAt(0);+ return codePoint !== undefined && codePoint >= 0x80 && codePoint <= 0x9f;+};+// Standards references:+// ECMA-48 control functions and CSI byte classes: https://ecma-international.org/publications-and-standards/standards/ecma-48/+// xterm CSI parameter/intermediate/final format notes: https://invisible-island.net/xterm/ecma-48-parameter-format.html+// xterm/OSC BEL termination behavior: https://davidrg.github.io/ckwin/dev/ctlseqs.html+const readCsiSequence = (text, fromIndex) => {+ let index = fromIndex;+ while (index < text.length) {+ const character = text[index];+ if (!isCsiParameterCharacter(character)) {+ break;+ }+ index++;+ }+ const parameterString = text.slice(fromIndex, index);+ const intermediateStartIndex = index;+ while (index < text.length) {+ const character = text[index];+ if (!isCsiIntermediateCharacter(character)) {+ break;+ }+ index++;+ }+ const intermediateString = text.slice(intermediateStartIndex, index);+ const finalCharacter = text[index];+ if (finalCharacter === undefined || !isCsiFinalCharacter(finalCharacter)) {+ return undefined;+ }+ return {+ endIndex: index + 1,+ parameterString,+ intermediateString,+ finalCharacter,+ };+};+const findControlStringTerminatorIndex = (text, fromIndex, isBellTerminatorAllowed) => {+ for (let index = fromIndex; index < text.length; index++) {+ const character = text[index];+ if (isBellTerminatorAllowed && character === bellCharacter) {+ return index + 1;+ }+ if (character === stringTerminatorCharacter) {+ return index + 1;+ }+ if (character !== escapeCharacter) {+ continue;+ }+ const followingCharacter = text[index + 1];+ // Tmux escapes ESC bytes in payload as ESC ESC.+ if (followingCharacter === escapeCharacter) {+ index++;+ continue;+ }+ if (followingCharacter === '\\') {+ return index + 2;+ }+ }+ return undefined;+};+const readEscapeSequence = (text, fromIndex) => {+ let index = fromIndex;+ while (index < text.length) {+ const character = text[index];+ if (!isEscapeIntermediateCharacter(character)) {+ break;+ }+ index++;+ }+ const intermediateString = text.slice(fromIndex, index);+ const finalCharacter = text[index];+ if (finalCharacter === undefined || !isEscapeFinalCharacter(finalCharacter)) {+ return undefined;+ }+ return {+ endIndex: index + 1,+ intermediateString,+ finalCharacter,+ };+};+// Centralize control-string rules so ESC and C1 paths do not diverge.+const getControlStringFromEscapeIntroducer = (character) => {+ switch (character) {+ case ']': {+ return { type: 'osc', allowBellTerminator: true };+ }+ case 'P': {+ return { type: 'dcs', allowBellTerminator: false };+ }+ case '^': {+ return { type: 'pm', allowBellTerminator: false };+ }+ case '_': {+ return { type: 'apc', allowBellTerminator: false };+ }+ case 'X': {+ return { type: 'sos', allowBellTerminator: false };+ }+ default: {+ return undefined;+ }+ }+};+const getControlStringFromC1Introducer = (character) => {+ switch (character) {+ case oscCharacter: {+ return { type: 'osc', allowBellTerminator: true };+ }+ case dcsCharacter: {+ return { type: 'dcs', allowBellTerminator: false };+ }+ case pmCharacter: {+ return { type: 'pm', allowBellTerminator: false };+ }+ case apcCharacter: {+ return { type: 'apc', allowBellTerminator: false };+ }+ case sosCharacter: {+ return { type: 'sos', allowBellTerminator: false };+ }+ default: {+ return undefined;+ }+ }+};+export const hasAnsiControlCharacters = (text) => {+ if (text.includes(escapeCharacter)) {+ return true;+ }+ for (const character of text) {+ if (isC1ControlCharacter(character)) {+ return true;+ }+ }+ return false;+};+const malformedFromIndex = (tokens, text, textStartIndex, fromIndex) => {+ if (fromIndex > textStartIndex) {+ tokens.push({ type: 'text', value: text.slice(textStartIndex, fromIndex) });+ }+ // Treat the remainder as invalid so callers can drop it as one unsafe unit.+ tokens.push({ type: 'invalid', value: text.slice(fromIndex) });+ return tokens;+};+export const tokenizeAnsi = (text) => {+ if (!hasAnsiControlCharacters(text)) {+ return [{ type: 'text', value: text }];+ }+ const tokens = [];+ let textStartIndex = 0;+ for (let index = 0; index < text.length;) {+ const character = text[index];+ if (character === undefined) {+ break;+ }+ if (character === escapeCharacter) {+ const followingCharacter = text[index + 1];+ if (followingCharacter === undefined) {+ return malformedFromIndex(tokens, text, textStartIndex, index);+ }+ if (followingCharacter === '[') {+ const csiSequence = readCsiSequence(text, index + 2);+ if (csiSequence === undefined) {+ return malformedFromIndex(tokens, text, textStartIndex, index);+ }+ if (index > textStartIndex) {+ tokens.push({ type: 'text', value: text.slice(textStartIndex, index) });+ }+ tokens.push({+ type: 'csi',+ value: text.slice(index, csiSequence.endIndex),+ parameterString: csiSequence.parameterString,+ intermediateString: csiSequence.intermediateString,+ finalCharacter: csiSequence.finalCharacter,+ });+ index = csiSequence.endIndex;+ textStartIndex = index;+ continue;+ }+ const escapeControlString = getControlStringFromEscapeIntroducer(followingCharacter);+ if (escapeControlString !== undefined) {+ const controlStringTerminatorIndex = findControlStringTerminatorIndex(text, index + 2, escapeControlString.allowBellTerminator);+ if (controlStringTerminatorIndex === undefined) {+ return malformedFromIndex(tokens, text, textStartIndex, index);+ }+ if (index > textStartIndex) {+ tokens.push({ type: 'text', value: text.slice(textStartIndex, index) });+ }+ tokens.push({+ type: escapeControlString.type,+ value: text.slice(index, controlStringTerminatorIndex),+ });+ index = controlStringTerminatorIndex;+ textStartIndex = index;+ continue;+ }+ const escapeSequence = readEscapeSequence(text, index + 1);+ if (escapeSequence === undefined) {+ // Incomplete escape sequences with intermediates are malformed control strings.+ if (isEscapeIntermediateCharacter(followingCharacter)) {+ return malformedFromIndex(tokens, text, textStartIndex, index);+ }+ if (index > textStartIndex) {+ tokens.push({ type: 'text', value: text.slice(textStartIndex, index) });+ }+ // Ignore lone ESC and continue tokenizing the rest.+ index++;+ textStartIndex = index;+ continue;+ }+ if (index > textStartIndex) {+ tokens.push({ type: 'text', value: text.slice(textStartIndex, index) });+ }+ tokens.push({+ type: 'esc',+ value: text.slice(index, escapeSequence.endIndex),+ intermediateString: escapeSequence.intermediateString,+ finalCharacter: escapeSequence.finalCharacter,+ });+ index = escapeSequence.endIndex;+ textStartIndex = index;+ continue;+ }+ if (character === csiCharacter) {+ const csiSequence = readCsiSequence(text, index + 1);+ if (csiSequence === undefined) {+ return malformedFromIndex(tokens, text, textStartIndex, index);+ }+ if (index > textStartIndex) {+ tokens.push({ type: 'text', value: text.slice(textStartIndex, index) });+ }+ tokens.push({+ type: 'csi',+ value: text.slice(index, csiSequence.endIndex),+ parameterString: csiSequence.parameterString,+ intermediateString: csiSequence.intermediateString,+ finalCharacter: csiSequence.finalCharacter,+ });+ index = csiSequence.endIndex;+ textStartIndex = index;+ continue;+ }+ const c1ControlString = getControlStringFromC1Introducer(character);+ if (c1ControlString !== undefined) {+ const controlStringTerminatorIndex = findControlStringTerminatorIndex(text, index + 1, c1ControlString.allowBellTerminator);+ if (controlStringTerminatorIndex === undefined) {+ return malformedFromIndex(tokens, text, textStartIndex, index);+ }+ if (index > textStartIndex) {+ tokens.push({ type: 'text', value: text.slice(textStartIndex, index) });+ }+ tokens.push({+ type: c1ControlString.type,+ value: text.slice(index, controlStringTerminatorIndex),+ });+ index = controlStringTerminatorIndex;+ textStartIndex = index;+ continue;+ }+ if (character === stringTerminatorCharacter) {+ if (index > textStartIndex) {+ tokens.push({ type: 'text', value: text.slice(textStartIndex, index) });+ }+ tokens.push({ type: 'st', value: character });+ index++;+ textStartIndex = index;+ continue;+ }+ // Strip remaining C1 controls as standalone functions.+ if (isC1ControlCharacter(character)) {+ if (index > textStartIndex) {+ tokens.push({ type: 'text', value: text.slice(textStartIndex, index) });+ }+ tokens.push({ type: 'c1', value: character });+ index++;+ textStartIndex = index;+ continue;+ }+ index++;+ }+ if (textStartIndex < text.length) {+ tokens.push({ type: 'text', value: text.slice(textStartIndex) });+ }+ return tokens;+};diff --git a/vendor/ink/build/apply-styles.js b/vendor/ink/build/apply-styles.jsdeleted file mode 100644index 88c9ee23..00000000--- a/vendor/ink/build/apply-styles.js+++ /dev/null@@ -1,175 +0,0 @@-"use strict";--Object.defineProperty(exports, "__esModule", {- value: true-});-exports.default = void 0;--var _yogaLayoutPrebuilt = _interopRequireDefault(require("yoga-layout-prebuilt"));--function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }--const applyMarginStyles = (node, style) => {- if (style.margin) {- node.setMargin(_yogaLayoutPrebuilt.default.EDGE_TOP, style.margin);- node.setMargin(_yogaLayoutPrebuilt.default.EDGE_BOTTOM, style.margin);- node.setMargin(_yogaLayoutPrebuilt.default.EDGE_START, style.margin);- node.setMargin(_yogaLayoutPrebuilt.default.EDGE_END, style.margin);- }-- if (style.marginX) {- node.setMargin(_yogaLayoutPrebuilt.default.EDGE_START, style.marginX);- node.setMargin(_yogaLayoutPrebuilt.default.EDGE_END, style.marginX);- }-- if (style.marginY) {- node.setMargin(_yogaLayoutPrebuilt.default.EDGE_TOP, style.marginY);- node.setMargin(_yogaLayoutPrebuilt.default.EDGE_BOTTOM, style.marginY);- }-- if (style.marginTop) {- node.setMargin(_yogaLayoutPrebuilt.default.EDGE_TOP, style.marginTop);- }-- if (style.marginBottom) {- node.setMargin(_yogaLayoutPrebuilt.default.EDGE_BOTTOM, style.marginBottom);- }-- if (style.marginLeft) {- node.setMargin(_yogaLayoutPrebuilt.default.EDGE_START, style.marginLeft);- }-- if (style.marginRight) {- node.setMargin(_yogaLayoutPrebuilt.default.EDGE_END, style.marginRight);- }-};--const applyPaddingStyles = (node, style) => {- if (style.padding) {- node.setPadding(_yogaLayoutPrebuilt.default.EDGE_TOP, style.padding);- node.setPadding(_yogaLayoutPrebuilt.default.EDGE_BOTTOM, style.padding);- node.setPadding(_yogaLayoutPrebuilt.default.EDGE_LEFT, style.padding);- node.setPadding(_yogaLayoutPrebuilt.default.EDGE_RIGHT, style.padding);- }-- if (style.paddingX) {- node.setPadding(_yogaLayoutPrebuilt.default.EDGE_LEFT, style.paddingX);- node.setPadding(_yogaLayoutPrebuilt.default.EDGE_RIGHT, style.paddingX);- }-- if (style.paddingY) {- node.setPadding(_yogaLayoutPrebuilt.default.EDGE_TOP, style.paddingY);- node.setPadding(_yogaLayoutPrebuilt.default.EDGE_BOTTOM, style.paddingY);- }-- if (style.paddingTop) {- node.setPadding(_yogaLayoutPrebuilt.default.EDGE_TOP, style.paddingTop);- }-- if (style.paddingBottom) {- node.setPadding(_yogaLayoutPrebuilt.default.EDGE_BOTTOM, style.paddingBottom);- }-- if (style.paddingLeft) {- node.setPadding(_yogaLayoutPrebuilt.default.EDGE_LEFT, style.paddingLeft);- }-- if (style.paddingRight) {- node.setPadding(_yogaLayoutPrebuilt.default.EDGE_RIGHT, style.paddingRight);- }-};--const applyFlexStyles = (node, style) => {- if (style.flexGrow) {- node.setFlexGrow(style.flexGrow);- }-- if (style.flexShrink) {- node.setFlexShrink(style.flexShrink);- }-- if (style.flexDirection) {- if (style.flexDirection === 'row') {- node.setFlexDirection(_yogaLayoutPrebuilt.default.FLEX_DIRECTION_ROW);- }-- if (style.flexDirection === 'row-reverse') {- node.setFlexDirection(_yogaLayoutPrebuilt.default.FLEX_DIRECTION_ROW_REVERSE);- }-- if (style.flexDirection === 'column') {- node.setFlexDirection(_yogaLayoutPrebuilt.default.FLEX_DIRECTION_COLUMN);- }-- if (style.flexDirection === 'column-reverse') {- node.setFlexDirection(_yogaLayoutPrebuilt.default.FLEX_DIRECTION_COLUMN_REVERSE);- }- }-- if (style.flexBasis !== undefined) {- node.setFlexBasis(style.flexBasis);- }-- if (style.alignItems) {- if (style.alignItems === 'flex-start') {- node.setAlignItems(_yogaLayoutPrebuilt.default.ALIGN_FLEX_START);- }-- if (style.alignItems === 'center') {- node.setAlignItems(_yogaLayoutPrebuilt.default.ALIGN_CENTER);- }-- if (style.alignItems === 'flex-end') {- node.setAlignItems(_yogaLayoutPrebuilt.default.ALIGN_FLEX_END);- }- }-- if (style.justifyContent) {- if (style.justifyContent === 'flex-start') {- node.setJustifyContent(_yogaLayoutPrebuilt.default.JUSTIFY_FLEX_START);- }-- if (style.justifyContent === 'center') {- node.setJustifyContent(_yogaLayoutPrebuilt.default.JUSTIFY_CENTER);- }-- if (style.justifyContent === 'flex-end') {- node.setJustifyContent(_yogaLayoutPrebuilt.default.JUSTIFY_FLEX_END);- }-- if (style.justifyContent === 'space-between') {- node.setJustifyContent(_yogaLayoutPrebuilt.default.JUSTIFY_SPACE_BETWEEN);- }-- if (style.justifyContent === 'space-around') {- node.setJustifyContent(_yogaLayoutPrebuilt.default.JUSTIFY_SPACE_AROUND);- }- }-};--const applyDimensionStyles = (node, style) => {- if (style.width !== undefined) {- node.setWidth(style.width);- }-- if (style.height !== undefined) {- node.setHeight(style.height);- }-- if (style.minWidth !== undefined) {- node.setMinWidth(style.minWidth);- }-- if (style.minHeight !== undefined) {- node.setMinHeight(style.minHeight);- }-};--var _default = (node, style = {}) => {- applyMarginStyles(node, style);- applyPaddingStyles(node, style);- applyFlexStyles(node, style);- applyDimensionStyles(node, style);-};--exports.default = _default;\ No newline at end of filediff --git a/vendor/ink/build/build-layout.js b/vendor/ink/build/build-layout.jsdeleted file mode 100644index 6975196c..00000000--- a/vendor/ink/build/build-layout.js+++ /dev/null@@ -1,77 +0,0 @@-"use strict";--Object.defineProperty(exports, "__esModule", {- value: true-});-exports.default = void 0;--var _yogaLayoutPrebuilt = _interopRequireDefault(require("yoga-layout-prebuilt"));--var _applyStyles = _interopRequireDefault(require("./apply-styles"));--var _measureText = _interopRequireDefault(require("./measure-text"));--function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }--// Traverse the node tree, create Yoga nodes and assign styles to each Yoga node-const buildLayout = (node, options) => {- const {- config,- terminalWidth,- skipStaticElements- } = options;-- const yogaNode = _yogaLayoutPrebuilt.default.Node.create(config);-- node.yogaNode = yogaNode;- const style = node.style || {}; // Root node of the tree-- if (node.nodeName === 'ROOT') {- // `terminalWidth` can be `undefined` if env isn't a TTY- yogaNode.setWidth(terminalWidth || 100);-- if (node.childNodes.length > 0) {- const childNodes = node.childNodes.filter(childNode => {- return skipStaticElements ? !childNode.unstable__static : true;- });-- for (const [index, childNode] of Object.entries(childNodes)) {- const childYogaNode = buildLayout(childNode, options).yogaNode;- yogaNode.insertChild(childYogaNode, index);- }- }-- return node;- } // Apply margin, padding, flex, etc styles--- (0, _applyStyles.default)(yogaNode, style); // Nodes with only text have a child Yoga node dedicated for that text-- if (node.textContent || node.nodeValue) {- const {- width,- height- } = (0, _measureText.default)(node.textContent || node.nodeValue);- yogaNode.setWidth(style.width || width);- yogaNode.setHeight(style.height || height);- return node;- }-- if (Array.isArray(node.childNodes) && node.childNodes.length > 0) {- const childNodes = node.childNodes.filter(childNode => {- return skipStaticElements ? !childNode.unstable__static : true;- });-- for (const [index, childNode] of Object.entries(childNodes)) {- const {- yogaNode: childYogaNode- } = buildLayout(childNode, options);- yogaNode.insertChild(childYogaNode, index);- }- }-- return node;-};--var _default = buildLayout;-exports.default = _default;\ No newline at end of filediff --git a/vendor/ink/build/calculate-wrapped-text.js b/vendor/ink/build/calculate-wrapped-text.jsdeleted file mode 100644index dde4742f..00000000--- a/vendor/ink/build/calculate-wrapped-text.js+++ /dev/null@@ -1,53 +0,0 @@-"use strict";--Object.defineProperty(exports, "__esModule", {- value: true-});-exports.default = void 0;--var _measureText = _interopRequireDefault(require("./measure-text"));--var _wrapText = _interopRequireDefault(require("./wrap-text"));--var _getMaxWidth = _interopRequireDefault(require("./get-max-width"));--function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }--// Since we need to know the width of text container to wrap text, we have to calculate layout twice-// This function is executed after first layout calculation to reassign width and height of text nodes-const calculateWrappedText = node => {- if (node.textContent && typeof node.parentNode.style.textWrap === 'string') {- const {- yogaNode- } = node;- const parentYogaNode = node.parentNode.yogaNode;- const maxWidth = (0, _getMaxWidth.default)(parentYogaNode);- const currentWidth = yogaNode.getComputedWidth();-- if (currentWidth > maxWidth) {- const {- textWrap- } = node.parentNode.style;- const wrappedText = (0, _wrapText.default)(node.textContent, maxWidth, {- textWrap- });- const {- width,- height- } = (0, _measureText.default)(wrappedText);- yogaNode.setWidth(width);- yogaNode.setHeight(height);- }-- return;- }-- if (Array.isArray(node.childNodes) && node.childNodes.length > 0) {- for (const childNode of node.childNodes) {- calculateWrappedText(childNode);- }- }-};--var _default = calculateWrappedText;-exports.default = _default;\ No newline at end of filediff --git a/vendor/ink/build/colorize.d.ts b/vendor/ink/build/colorize.d.tsindex 627451e8..bb4f42cd 100644--- a/vendor/ink/build/colorize.d.ts+++ b/vendor/ink/build/colorize.d.ts@@ -1,3 +1,3 @@type ColorType = 'foreground' | 'background';-declare const colorize: (str: string, color: string | undefined, type: ColorType) => string;+declare const colorize: (text: string, color: string | undefined, type: ColorType) => string;export default colorize;diff --git a/vendor/ink/build/colorize.js b/vendor/ink/build/colorize.jsindex d28d3545..af79727b 100644--- a/vendor/ink/build/colorize.js+++ b/vendor/ink/build/colorize.js@@ -1,47 +1,47 @@-import chalk from 'chalk';-const rgbRegex = /^rgb\(\s?(\d+),\s?(\d+),\s?(\d+)\s?\)$/;-const ansiRegex = /^ansi256\(\s?(\d+)\s?\)$/;-const isNamedColor = (color) => {- return color in chalk;-};-const colorize = (str, color, type) => {+import chalk, { foregroundColorNames, } from 'chalk';+const rgbRegex = /^rgb\(\s*(?<red>\d+)\s*,\s*(?<green>\d+)\s*,\s*(?<blue>\d+)\s*\)$/;+const ansiRegex = /^ansi256\(\s?(?<value>\d+)\s?\)$/;+const isNamedColor = (color) => foregroundColorNames.includes(color);+const colorize = (text, color, type) => {+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions -- JavaScript callers pass `null` or `false` (for example `condition && 'red'`), and any falsy value means unset.if (!color) {- return str;+ return text;}if (isNamedColor(color)) {if (type === 'foreground') {- return chalk[color](str);+ return chalk[color](text);}const methodName = `bg${color[0].toUpperCase() + color.slice(1)}`;- return chalk[methodName](str);+ return chalk[methodName](text);}if (color.startsWith('#')) {return type === 'foreground'- ? chalk.hex(color)(str)- : chalk.bgHex(color)(str);+ ? chalk.hex(color)(text)+ : chalk.bgHex(color)(text);}if (color.startsWith('ansi256')) {const matches = ansiRegex.exec(color);if (!matches) {- return str;+ return text;}- const value = Number(matches[1]);+ const value = Number(matches.groups['value']);return type === 'foreground'- ? chalk.ansi256(value)(str)- : chalk.bgAnsi256(value)(str);+ ? chalk.ansi256(value)(text)+ : chalk.bgAnsi256(value)(text);}if (color.startsWith('rgb')) {const matches = rgbRegex.exec(color);if (!matches) {- return str;+ return text;}- const firstValue = Number(matches[1]);- const secondValue = Number(matches[2]);- const thirdValue = Number(matches[3]);+ const { red, green, blue } = matches.groups;+ const firstValue = Number(red);+ const secondValue = Number(green);+ const thirdValue = Number(blue);return type === 'foreground'- ? chalk.rgb(firstValue, secondValue, thirdValue)(str)- : chalk.bgRgb(firstValue, secondValue, thirdValue)(str);+ ? chalk.rgb(firstValue, secondValue, thirdValue)(text)+ : chalk.bgRgb(firstValue, secondValue, thirdValue)(text);}- return str;+ return text;};export default colorize;diff --git a/vendor/ink/build/components/AccessibilityContext.d.ts b/vendor/ink/build/components/AccessibilityContext.d.tsnew file mode 100644index 00000000..b55cb8fe--- /dev/null+++ b/vendor/ink/build/components/AccessibilityContext.d.ts@@ -0,0 +1,3 @@+export declare const AccessibilityContext: import("react").Context<{+ isScreenReaderEnabled: boolean;+}>;diff --git a/vendor/ink/build/components/AccessibilityContext.js b/vendor/ink/build/components/AccessibilityContext.jsnew file mode 100644index 00000000..8e1b9616--- /dev/null+++ b/vendor/ink/build/components/AccessibilityContext.js@@ -0,0 +1,5 @@+import { createContext } from 'react';+// eslint-disable-next-line @typescript-eslint/naming-convention -- React contexts are named like components.+export const AccessibilityContext = createContext({+ isScreenReaderEnabled: false,+});diff --git a/vendor/ink/build/components/AnimationContext.d.ts b/vendor/ink/build/components/AnimationContext.d.tsnew file mode 100644index 00000000..7f48ffb5--- /dev/null+++ b/vendor/ink/build/components/AnimationContext.d.ts@@ -0,0 +1,9 @@+type AnimationContextValue = {+ readonly renderThrottleMs: number;+ readonly subscribe: (callback: (currentTime: number) => void, interval: number) => {+ readonly startTime: number;+ readonly unsubscribe: () => void;+ };+};+declare const AnimationContext: import("react").Context<AnimationContextValue>;+export default AnimationContext;diff --git a/vendor/ink/build/components/AnimationContext.js b/vendor/ink/build/components/AnimationContext.jsnew file mode 100644index 00000000..f3cd2d19--- /dev/null+++ b/vendor/ink/build/components/AnimationContext.js@@ -0,0 +1,13 @@+import { createContext } from 'react';+// eslint-disable-next-line @typescript-eslint/naming-convention -- React contexts are named like components.+const AnimationContext = createContext({+ renderThrottleMs: 0,+ subscribe() {+ return {+ startTime: 0,+ unsubscribe() { },+ };+ },+});+AnimationContext.displayName = 'InternalAnimationContext';+export default AnimationContext;diff --git a/vendor/ink/build/components/App.d.ts b/vendor/ink/build/components/App.d.tsindex 87c9c4c6..ccc3286c 100644--- a/vendor/ink/build/components/App.d.ts+++ b/vendor/ink/build/components/App.d.ts@@ -1,59 +1,26 @@-import { EventEmitter } from 'node:events';-import React, { PureComponent, type ReactNode } from 'react';+import React, { type ReactNode } from 'react';+import { type CursorPosition } from '../log-update.js';+import { type OutputStream } from '../stream.js';+import { type SuspendTerminal } from './AppContext.js';type Props = {readonly children: ReactNode;- readonly stdin: NodeJS.ReadStream;- readonly stdout: NodeJS.WriteStream;- readonly stderr: NodeJS.WriteStream;+ readonly stdin: NodeJS.ReadableStream;+ readonly stdout: OutputStream;+ readonly stderr: OutputStream;readonly writeToStdout: (data: string) => void;readonly writeToStderr: (data: string) => void;readonly exitOnCtrlC: boolean;- readonly onExit: (error?: Error) => void;+ readonly onExit: (errorOrResult?: unknown) => void;+ readonly onWaitUntilRenderFlush: () => Promise<void>;+ readonly onSuspendTerminal: SuspendTerminal;+ readonly onKittyQueryResponse: () => void;+ readonly onRegisterInputControl: (pauseInput: () => void, resumeInput: () => void) => void;+ readonly setCursorPosition: (position: CursorPosition | undefined) => void;+ readonly interactive: boolean;+ readonly renderThrottleMs: number;};-type State = {- readonly isFocusEnabled: boolean;- readonly activeFocusId?: string;- readonly focusables: Focusable[];- readonly error?: Error;-};-type Focusable = {- readonly id: string;- readonly isActive: boolean;-};-export default class App extends PureComponent<Props, State> {- static displayName: string;- static getDerivedStateFromError(error: Error): {- error: Error;- };- state: {- isFocusEnabled: boolean;- activeFocusId: undefined;- focusables: never[];- error: undefined;- };- rawModeEnabledCount: number;- internal_eventEmitter: EventEmitter<[never]>;- isRawModeSupported(): boolean;- render(): React.JSX.Element;- componentDidMount(): void;- componentWillUnmount(): void;- componentDidCatch(error: Error): void;- handleSetRawMode: (isEnabled: boolean) => void;- handleReadable: () => void;- handleInput: (input: string) => void;- handleExit: (error?: Error) => void;- enableFocus: () => void;- disableFocus: () => void;- focus: (id: string) => void;- focusNext: () => void;- focusPrevious: () => void;- addFocusable: (id: string, { autoFocus }: {- autoFocus: boolean;- }) => void;- removeFocusable: (id: string) => void;- activateFocusable: (id: string) => void;- deactivateFocusable: (id: string) => void;- findNextFocusable: (state: State) => string | undefined;- findPreviousFocusable: (state: State) => string | undefined;+declare function App({ children, stdin, stdout, stderr, writeToStdout, writeToStderr, exitOnCtrlC, onExit, onWaitUntilRenderFlush, onSuspendTerminal, onKittyQueryResponse, onRegisterInputControl, setCursorPosition, interactive, renderThrottleMs, }: Props): React.ReactNode;+declare namespace App {+ var displayName: string;}-export {};+export default App;diff --git a/vendor/ink/build/components/App.js b/vendor/ink/build/components/App.jsindex 5a35b5d6..8193a5bc 100644--- a/vendor/ink/build/components/App.js+++ b/vendor/ink/build/components/App.js@@ -1,285 +1,544 @@import { EventEmitter } from 'node:events';import process from 'node:process';-import React, { PureComponent } from 'react';+import React, { useState, useRef, useCallback, useMemo, useEffect, useInsertionEffect, } from 'react';import cliCursor from 'cli-cursor';+import { createInputParser, isCompleteControlSequence, } from '../input-parser.js';+import parseKeypress from '../parse-keypress.js';+import { getRawModeStream } from '../stream.js';import AppContext from './AppContext.js';import StdinContext from './StdinContext.js';import StdoutContext from './StdoutContext.js';import StderrContext from './StderrContext.js';import FocusContext from './FocusContext.js';-import ErrorOverview from './ErrorOverview.js';-const tab = '\t';-const shiftTab = '\u001B[Z';-const escape = '\u001B';+import AnimationContext from './AnimationContext.js';+import CursorContext from './CursorContext.js';+import ErrorBoundary from './ErrorBoundary.js';+// Components sharing a custom ID are indistinguishable to focus, so navigation treats each ID as one slot at its first registration.+const uniqueFocusables = (focusables) => {+ const seenIds = new Set();+ return focusables.filter(focusable => {+ if (seenIds.has(focusable.id)) {+ return false;+ }+ seenIds.add(focusable.id);+ return true;+ });+};// Root component for all Ink apps// It renders stdin and stdout contexts, so that children can access them if needed// It also handles Ctrl+C exiting and cursor visibility-export default class App extends PureComponent {- static displayName = 'InternalApp';- static getDerivedStateFromError(error) {- return { error };- }- state = {- isFocusEnabled: true,- activeFocusId: undefined,- focusables: [],- error: undefined,- };+function App({ children, stdin, stdout, stderr, writeToStdout, writeToStderr, exitOnCtrlC, onExit, onWaitUntilRenderFlush, onSuspendTerminal, onKittyQueryResponse, onRegisterInputControl, setCursorPosition, interactive, renderThrottleMs, }) {+ const isFocusEnabledRef = useRef(true);+ const [activeFocusId, setActiveFocusId] = useState(undefined);+ // The registry is not rendered. Keep it current without nesting state updates, so focus changes are queued in call order.+ const focusablesRef = useRef([]);+ const animationSubscribersRef = useRef(new Map());+ const animationTimerRef = useRef(undefined);// Count how many components enabled raw mode to avoid disabling// raw mode until all components don't need it anymore- rawModeEnabledCount = 0;- // eslint-disable-next-line @typescript-eslint/naming-convention- internal_eventEmitter = new EventEmitter();- // Determines if TTY is supported on the provided stdin- isRawModeSupported() {- return this.props.stdin.isTTY;- }- render() {- return (React.createElement(AppContext.Provider- // eslint-disable-next-line react/jsx-no-constructed-context-values- , {- // eslint-disable-next-line react/jsx-no-constructed-context-values- value: {- exit: this.handleExit,- } },- React.createElement(StdinContext.Provider- // eslint-disable-next-line react/jsx-no-constructed-context-values- , {- // eslint-disable-next-line react/jsx-no-constructed-context-values- value: {- stdin: this.props.stdin,- setRawMode: this.handleSetRawMode,- isRawModeSupported: this.isRawModeSupported(),- // eslint-disable-next-line @typescript-eslint/naming-convention- internal_exitOnCtrlC: this.props.exitOnCtrlC,- // eslint-disable-next-line @typescript-eslint/naming-convention- internal_eventEmitter: this.internal_eventEmitter,- } },- React.createElement(StdoutContext.Provider- // eslint-disable-next-line react/jsx-no-constructed-context-values- , {- // eslint-disable-next-line react/jsx-no-constructed-context-values- value: {- stdout: this.props.stdout,- write: this.props.writeToStdout,- } },- React.createElement(StderrContext.Provider- // eslint-disable-next-line react/jsx-no-constructed-context-values- , {- // eslint-disable-next-line react/jsx-no-constructed-context-values- value: {- stderr: this.props.stderr,- write: this.props.writeToStderr,- } },- React.createElement(FocusContext.Provider- // eslint-disable-next-line react/jsx-no-constructed-context-values- , {- // eslint-disable-next-line react/jsx-no-constructed-context-values- value: {- activeId: this.state.activeFocusId,- add: this.addFocusable,- remove: this.removeFocusable,- activate: this.activateFocusable,- deactivate: this.deactivateFocusable,- enableFocus: this.enableFocus,- disableFocus: this.disableFocus,- focusNext: this.focusNext,- focusPrevious: this.focusPrevious,- focus: this.focus,- } }, this.state.error ? (React.createElement(ErrorOverview, { error: this.state.error })) : (this.props.children)))))));- }- componentDidMount() {- cliCursor.hide(this.props.stdout);- }- componentWillUnmount() {- cliCursor.show(this.props.stdout);- // ignore calling setRawMode on an handle stdin it cannot be called- if (this.isRawModeSupported()) {- this.handleSetRawMode(false);- }- }- componentDidCatch(error) {- this.handleExit(error);- }- handleSetRawMode = (isEnabled) => {- const { stdin } = this.props;- if (!this.isRawModeSupported()) {- if (stdin === process.stdin) {- throw new Error('Raw mode is not supported on the current process.stdin, which Ink uses as input stream by default.\nRead about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported');- }- else {- throw new Error('Raw mode is not supported on the stdin provided to Ink.\nRead about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported');- }+ const rawModeEnabledCountRef = useRef(0);+ const pendingDisableRawModeRef = useRef(false);+ // Set while suspendTerminal() has handed input to a child process. Input hooks that change while it is set only update the ref counts; resumeInput restores the modes that still have an owner.+ const isInputPausedRef = useRef(false);+ // Count how many components enabled bracketed paste mode+ const bracketedPasteModeEnabledCountRef = useRef(0);+ const eventEmitterRef = useRef(new EventEmitter());+ // Each useInput hook adds a listener, so the count can legitimately exceed the default limit of 10.+ eventEmitterRef.current.setMaxListeners(Infinity);+ // Store the currently attached readable listener to avoid stale closure issues+ const readableListenerRef = useRef(undefined);+ const inputParserRef = useRef(createInputParser());+ const pendingInputFlushRef = useRef(undefined);+ // Small delay to let chunked escape sequences complete before flushing as literal input.+ const pendingInputFlushDelayMilliseconds = 20;+ const clearPendingInputFlush = useCallback(() => {+ if (!pendingInputFlushRef.current) {+ return;}- stdin.setEncoding('utf8');- if (isEnabled) {- // Ensure raw mode is enabled only once- if (this.rawModeEnabledCount === 0) {- stdin.ref();- stdin.setRawMode(true);- stdin.addListener('readable', this.handleReadable);+ clearTimeout(pendingInputFlushRef.current);+ pendingInputFlushRef.current = undefined;+ }, []);+ const clearAnimationTimer = useCallback(() => {+ if (!animationTimerRef.current) {+ return;+ }+ clearTimeout(animationTimerRef.current);+ animationTimerRef.current = undefined;+ }, []);+ const scheduleAnimationTick = useCallback(() => {+ clearAnimationTimer();+ if (animationSubscribersRef.current.size === 0) {+ return;+ }+ let nextDueTime = Infinity;+ for (const subscriber of animationSubscribersRef.current.values()) {+ // One shared timer is enough as long as it wakes at the earliest+ // subscriber deadline and lets slower animations skip that tick.+ nextDueTime = Math.min(nextDueTime, subscriber.nextDueTime);+ }+ const delay = Math.max(0, nextDueTime - performance.now());+ animationTimerRef.current = setTimeout(() => {+ animationTimerRef.current = undefined;+ const currentTime = performance.now();+ for (const subscriber of animationSubscribersRef.current.values()) {+ if (currentTime < subscriber.nextDueTime) {+ continue;+ }+ subscriber.callback(currentTime);+ const elapsedTime = currentTime - subscriber.startTime;+ const elapsedFrames = Math.floor(elapsedTime / subscriber.interval) + 1;+ // Advance from elapsed time rather than callback count so delayed+ // ticks catch up instead of stretching the animation timeline.+ subscriber.nextDueTime =+ subscriber.startTime + elapsedFrames * subscriber.interval;}- this.rawModeEnabledCount++;+ scheduleAnimationTick();+ }, delay);+ // Keep the timer ref'd while animations are active so `useAnimation()`+ // can drive process lifetime in both interactive and non-interactive apps.+ }, [clearAnimationTimer]);+ const animationSubscribe = useCallback((callback, interval) => {+ const startTime = performance.now();+ // The scheduler owns the start timestamp so hooks can derive frames from+ // the exact same origin that determines each subscriber's due time.+ animationSubscribersRef.current.set(callback, {+ callback,+ interval,+ startTime,+ nextDueTime: startTime + interval,+ });+ scheduleAnimationTick();+ return {+ startTime,+ unsubscribe() {+ animationSubscribersRef.current.delete(callback);+ if (animationSubscribersRef.current.size === 0) {+ clearAnimationTimer();+ return;+ }+ scheduleAnimationTick();+ },+ };+ }, [clearAnimationTimer, scheduleAnimationTick]);+ useEffect(() => () => {+ clearAnimationTimer();+ }, [clearAnimationTimer]);+ const rawModeStdin = getRawModeStream(stdin);+ const isRawModeSupported = rawModeStdin !== undefined;+ const detachReadableListener = useCallback(() => {+ if (!readableListenerRef.current) {return;}- // Disable raw mode only when no components left that are using it- if (--this.rawModeEnabledCount === 0) {- stdin.setRawMode(false);- stdin.removeListener('readable', this.handleReadable);- stdin.unref();+ stdin.removeListener('readable', readableListenerRef.current);+ readableListenerRef.current = undefined;+ }, [stdin]);+ const clearInputState = useCallback(() => {+ inputParserRef.current.reset();+ clearPendingInputFlush();+ detachReadableListener();+ }, [clearPendingInputFlush, detachReadableListener]);+ const disableRawMode = useCallback(() => {+ if (!rawModeStdin) {+ return;}- };- handleReadable = () => {- let chunk;- // eslint-disable-next-line @typescript-eslint/ban-types- while ((chunk = this.props.stdin.read()) !== null) {- this.handleInput(chunk);- this.internal_eventEmitter.emit('input', chunk);+ pendingDisableRawModeRef.current = false;+ rawModeStdin.setRawMode(false);+ rawModeStdin.unref?.();+ rawModeEnabledCountRef.current = 0;+ clearInputState();+ }, [rawModeStdin, clearInputState]);+ const handleExit = useCallback((errorOrResult) => {+ if (isRawModeSupported &&+ (rawModeEnabledCountRef.current > 0 || pendingDisableRawModeRef.current)) {+ disableRawMode();}- };- handleInput = (input) => {+ onExit(errorOrResult);+ }, [isRawModeSupported, disableRawMode, onExit]);+ const handleInput = useCallback((input) => {+ const key = parseKeypress(input);// Exit on Ctrl+C- // eslint-disable-next-line unicorn/no-hex-escape- if (input === '\x03' && this.props.exitOnCtrlC) {- this.handleExit();+ if (exitOnCtrlC &&+ key.ctrl &&+ key.name === 'c' &&+ key.eventType !== 'release') {+ handleExit();+ return;}// Reset focus when there's an active focused component on Esc- if (input === escape && this.state.activeFocusId) {- this.setState({- activeFocusId: undefined,- });- }- if (this.state.isFocusEnabled && this.state.focusables.length > 0) {- if (input === tab) {- this.focusNext();+ if (isFocusEnabledRef.current &&+ key.name === 'escape' &&+ key.eventType !== 'release' &&+ !key.shift &&+ !key.ctrl &&+ !key.meta &&+ key.super !== true &&+ key.hyper !== true) {+ setActiveFocusId(undefined);+ }+ }, [exitOnCtrlC, handleExit]);+ const emitInput = useCallback((input) => {+ handleInput(input);+ eventEmitterRef.current.emit('input', input);+ }, [handleInput]);+ const schedulePendingInputFlush = useCallback(() => {+ clearPendingInputFlush();+ pendingInputFlushRef.current = setTimeout(() => {+ pendingInputFlushRef.current = undefined;+ const pendingEscape = inputParserRef.current.flushPendingEscape();+ if (pendingEscape === undefined || pendingEscape === '') {+ return;}- if (input === shiftTab) {- this.focusPrevious();+ emitInput(pendingEscape);+ }, pendingInputFlushDelayMilliseconds);+ }, [clearPendingInputFlush, emitInput]);+ const handleReadable = useCallback(() => {+ const handleInputEvent = (event) => {+ if (typeof event === 'string') {+ // Protocol replies are consumed here; bracketed paste stays literal.+ // eslint-disable-next-line no-control-regex, regexp/no-control-character -- Kitty keyboard query replies start with ESC.+ if (/^\u{1B}\[\?\d+u$/u.test(event)) {+ onKittyQueryResponse();+ return;+ }+ // A complete CSI or SS3 sequence that maps to no key Ink can represent is not printable text. Terminal replies (focus in/out, cursor position, mouse, device attributes) and keys without a `Key` field would otherwise reach `useInput` with the ESC stripped, as if typed.+ if (isCompleteControlSequence(event)) {+ const key = parseKeypress(event);+ if (!key.isKittyProtocol && key.name === '') {+ return;+ }+ }+ emitInput(event);+ }+ else {+ // Keep paste on a separate channel from `useInput` so key handlers+ // don't need to branch on mixed key-vs-paste event shapes.+ if (eventEmitterRef.current.listenerCount('paste') === 0) {+ emitInput(event.paste);+ return;+ }+ eventEmitterRef.current.emit('paste', event.paste);+ }+ };+ clearPendingInputFlush();+ let chunk;+ // eslint-disable-next-line @typescript-eslint/no-restricted-types+ while ((chunk = stdin.read()) !== null) {+ for (const event of inputParserRef.current.push(chunk)) {+ handleInputEvent(event);}}- };- handleExit = (error) => {- if (this.isRawModeSupported()) {- this.handleSetRawMode(false);+ if (inputParserRef.current.hasPendingEscape()) {+ schedulePendingInputFlush();}- this.props.onExit(error);- };- enableFocus = () => {- this.setState({- isFocusEnabled: true,- });- };- disableFocus = () => {- this.setState({- isFocusEnabled: false,- });- };- focus = (id) => {- this.setState(previousState => {- const hasFocusableId = previousState.focusables.some(focusable => focusable?.id === id);- if (!hasFocusableId) {- return previousState;- }- return { activeFocusId: id };- });- };- focusNext = () => {- this.setState(previousState => {- const firstFocusableId = previousState.focusables.find(focusable => focusable.isActive)?.id;- const nextFocusableId = this.findNextFocusable(previousState);- return {- activeFocusId: nextFocusableId ?? firstFocusableId,- };- });- };- focusPrevious = () => {- this.setState(previousState => {- const lastFocusableId = previousState.focusables.findLast(focusable => focusable.isActive)?.id;- const previousFocusableId = this.findPreviousFocusable(previousState);- return {- activeFocusId: previousFocusableId ?? lastFocusableId,- };- });- };- addFocusable = (id, { autoFocus }) => {- this.setState(previousState => {- let nextFocusId = previousState.activeFocusId;- if (!nextFocusId && autoFocus) {- nextFocusId = id;+ }, [+ stdin,+ emitInput,+ clearPendingInputFlush,+ schedulePendingInputFlush,+ onKittyQueryResponse,+ ]);+ const attachReadableListener = useCallback(() => {+ if (readableListenerRef.current) {+ return;+ }+ // Store the listener reference to avoid stale closure when removing+ readableListenerRef.current = handleReadable;+ stdin.addListener('readable', handleReadable);+ }, [stdin, handleReadable]);+ const handleSetRawMode = useCallback((isEnabled) => {+ if (!rawModeStdin) {+ if (stdin === process.stdin) {+ throw new Error('Raw mode is not supported on the current process.stdin, which Ink uses as input stream by default.\nRead about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported');}- return {- activeFocusId: nextFocusId,- focusables: [- ...previousState.focusables,- {- id,- isActive: true,- },- ],- };- });- };- removeFocusable = (id) => {- this.setState(previousState => ({- activeFocusId: previousState.activeFocusId === id- ? undefined- : previousState.activeFocusId,- focusables: previousState.focusables.filter(focusable => {- return focusable.id !== id;- }),- }));- };- activateFocusable = (id) => {- this.setState(previousState => ({- focusables: previousState.focusables.map(focusable => {- if (focusable.id !== id) {- return focusable;- }- return {- id,- isActive: true,- };- }),- }));- };- deactivateFocusable = (id) => {- this.setState(previousState => ({- activeFocusId: previousState.activeFocusId === id- ? undefined- : previousState.activeFocusId,- focusables: previousState.focusables.map(focusable => {- if (focusable.id !== id) {- return focusable;+ throw new Error('Raw mode is not supported on the stdin provided to Ink.\nRead about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported');+ }+ rawModeStdin.setEncoding('utf8');+ if (isEnabled) {+ if (rawModeEnabledCountRef.current === 0) {+ // A same-render component swap may have detached input handling while+ // leaving terminal raw mode enabled until the queued disable runs.+ const isRawModeAlreadyEnabled = pendingDisableRawModeRef.current;+ pendingDisableRawModeRef.current = false;+ if (!isInputPausedRef.current) {+ if (!isRawModeAlreadyEnabled) {+ rawModeStdin.ref?.();+ rawModeStdin.setRawMode(true);+ }+ attachReadableListener();}- return {- id,- isActive: false,- };- }),- }));- };- findNextFocusable = (state) => {- const activeIndex = state.focusables.findIndex(focusable => {- return focusable.id === state.activeFocusId;+ }+ rawModeEnabledCountRef.current++;+ return;+ }+ if (rawModeEnabledCountRef.current === 0 ||+ --rawModeEnabledCountRef.current !== 0 ||+ // Nothing to release while suspended: pauseInput already did.+ isInputPausedRef.current) {+ return;+ }+ // Stop owning input immediately so pending parser state cannot leak into+ // a replacement `useInput` component mounted in the same React update.+ clearInputState();+ // Defer only the terminal raw-mode teardown so a same-render replacement+ // can keep the process ref and raw mode active without a disable/enable cycle.+ pendingDisableRawModeRef.current = true;+ queueMicrotask(() => {+ if (!pendingDisableRawModeRef.current) {+ return;+ }+ disableRawMode();});- for (let index = activeIndex + 1; index < state.focusables.length; index++) {- const focusable = state.focusables[index];+ }, [+ rawModeStdin,+ stdin,+ attachReadableListener,+ clearInputState,+ disableRawMode,+ ]);+ const handleSetBracketedPasteMode = useCallback((isEnabled) => {+ if (!stdout.isTTY) {+ return;+ }+ if (isEnabled) {+ if (bracketedPasteModeEnabledCountRef.current === 0 &&+ !isInputPausedRef.current) {+ stdout.write('\u{1B}[?2004h');+ }+ bracketedPasteModeEnabledCountRef.current++;+ return;+ }+ if (bracketedPasteModeEnabledCountRef.current === 0) {+ return;+ }+ if (--bracketedPasteModeEnabledCountRef.current === 0 &&+ !isInputPausedRef.current) {+ stdout.write('\u{1B}[?2004l');+ }+ }, [stdout]);+ // Pausing and resuming leave the ref counts untouched: the React components+ // still "own" raw mode/bracketed paste across the suspension.+ const pauseInput = useCallback(() => {+ isInputPausedRef.current = true;+ if (bracketedPasteModeEnabledCountRef.current > 0 && stdout.isTTY) {+ try {+ stdout.write('\u{1B}[?2004l');+ }+ catch { }+ }+ // A queued raw-mode disable (last input hook released this commit) has not run yet, so raw mode is still on. Disable it now, before the child owns the terminal, and cancel the microtask.+ if (!(isRawModeSupported &&+ (rawModeEnabledCountRef.current > 0 || pendingDisableRawModeRef.current))) {+ return;+ }+ pendingDisableRawModeRef.current = false;+ rawModeStdin?.setRawMode(false);+ rawModeStdin?.unref?.();+ clearInputState();+ }, [isRawModeSupported, rawModeStdin, stdout, clearInputState]);+ // Hooks may have changed while suspended, so restore only the modes that still have an owner.+ const resumeInput = useCallback(() => {+ isInputPausedRef.current = false;+ if (isRawModeSupported && rawModeEnabledCountRef.current > 0) {+ rawModeStdin?.setEncoding('utf8');+ rawModeStdin?.ref?.();+ rawModeStdin?.setRawMode(true);+ attachReadableListener();+ }+ if (bracketedPasteModeEnabledCountRef.current > 0 && stdout.isTTY) {+ try {+ stdout.write('\u{1B}[?2004h');+ }+ catch { }+ }+ }, [isRawModeSupported, rawModeStdin, stdout, attachReadableListener]);+ // Register input pause/resume in an insertion effect: it runs before every+ // passive effect (parent and child), so a child that calls suspendTerminal()+ // from its own effect always finds the input control already registered. A+ // normal effect would run too late (child effects fire before the parent's).+ useInsertionEffect(() => {+ onRegisterInputControl(pauseInput, resumeInput);+ }, [onRegisterInputControl, pauseInput, resumeInput]);+ // Focus navigation helpers+ const findNextFocusable = useCallback((currentFocusables, currentActiveFocusId) => {+ const activeIndex = currentFocusables.findIndex(focusable => focusable.id === currentActiveFocusId);+ for (let index = activeIndex + 1; index < currentFocusables.length; index++) {+ const focusable = currentFocusables[index];if (focusable?.isActive) {return focusable.id;}}return undefined;- };- findPreviousFocusable = (state) => {- const activeIndex = state.focusables.findIndex(focusable => {- return focusable.id === state.activeFocusId;- });+ }, []);+ const findPreviousFocusable = useCallback((currentFocusables, currentActiveFocusId) => {+ const activeIndex = currentFocusables.findIndex(focusable => focusable.id === currentActiveFocusId);for (let index = activeIndex - 1; index >= 0; index--) {- const focusable = state.focusables[index];+ const focusable = currentFocusables[index];if (focusable?.isActive) {return focusable.id;}}return undefined;- };+ }, []);+ const focusNext = useCallback(() => {+ const currentFocusables = uniqueFocusables(focusablesRef.current);+ setActiveFocusId(currentActiveFocusId => {+ const firstFocusableId = currentFocusables.find(focusable => focusable.isActive)?.id;+ const nextFocusableId = findNextFocusable(currentFocusables, currentActiveFocusId);+ return nextFocusableId ?? firstFocusableId;+ });+ }, [findNextFocusable]);+ const focusPrevious = useCallback(() => {+ const currentFocusables = uniqueFocusables(focusablesRef.current);+ setActiveFocusId(currentActiveFocusId => {+ const lastFocusableId = currentFocusables.findLast(focusable => focusable.isActive)?.id;+ const previousFocusableId = findPreviousFocusable(currentFocusables, currentActiveFocusId);+ return previousFocusableId ?? lastFocusableId;+ });+ }, [findPreviousFocusable]);+ // Handle tab navigation via effect that subscribes to input events+ useEffect(() => {+ const handleTabNavigation = (input) => {+ if (!isFocusEnabledRef.current || focusablesRef.current.length === 0) {+ return;+ }+ const key = parseKeypress(input);+ if (key.name !== 'tab' ||+ key.eventType === 'release' ||+ key.ctrl ||+ key.meta ||+ key.super === true ||+ key.hyper === true) {+ return;+ }+ if (key.shift) {+ focusPrevious();+ }+ else {+ focusNext();+ }+ };+ eventEmitterRef.current.on('input', handleTabNavigation);+ const emitter = eventEmitterRef.current;+ return () => {+ emitter.off('input', handleTabNavigation);+ };+ }, [focusNext, focusPrevious]);+ const enableFocus = useCallback(() => {+ isFocusEnabledRef.current = true;+ }, []);+ const disableFocus = useCallback(() => {+ isFocusEnabledRef.current = false;+ setActiveFocusId(undefined);+ }, []);+ const focus = useCallback((id) => {+ const hasFocusableId = focusablesRef.current.some(focusable => focusable.id === id && focusable.isActive);+ if (hasFocusableId) {+ setActiveFocusId(id);+ }+ }, []);+ const addFocusable = useCallback((id, { autoFocus }) => {+ focusablesRef.current = [...focusablesRef.current, { id, isActive: true }];+ if (autoFocus && isFocusEnabledRef.current) {+ setActiveFocusId(currentActiveFocusId => currentActiveFocusId ?? id);+ }+ }, []);+ const removeFocusable = useCallback((id) => {+ setActiveFocusId(currentActiveFocusId => currentActiveFocusId === id ? undefined : currentActiveFocusId);+ focusablesRef.current = focusablesRef.current.filter(focusable => focusable.id !== id);+ }, []);+ const activateFocusable = useCallback((id) => {+ focusablesRef.current = focusablesRef.current.map(focusable => focusable.id === id ? { id, isActive: true } : focusable);+ }, []);+ const deactivateFocusable = useCallback((id) => {+ setActiveFocusId(currentActiveFocusId => currentActiveFocusId === id ? undefined : currentActiveFocusId);+ focusablesRef.current = focusablesRef.current.map(focusable => focusable.id === id ? { id, isActive: false } : focusable);+ }, []);+ // Handle cursor visibility, raw mode, and bracketed paste mode cleanup on unmount+ useEffect(() => () => {+ const canWriteToStdout = !stdout.destroyed && !stdout.writableEnded;+ if (interactive && canWriteToStdout) {+ cliCursor.show(stdout);+ }+ if (isRawModeSupported &&+ (rawModeEnabledCountRef.current > 0 || pendingDisableRawModeRef.current)) {+ disableRawMode();+ }+ if (!(bracketedPasteModeEnabledCountRef.current > 0)) {+ return;+ }+ if (canWriteToStdout && stdout.isTTY) {+ stdout.write('\u{1B}[?2004l');+ }+ bracketedPasteModeEnabledCountRef.current = 0;+ }, [stdout, isRawModeSupported, disableRawMode, interactive]);+ // Memoize context values to prevent unnecessary re-renders+ const appContextValue = useMemo(() => ({+ exit: handleExit,+ waitUntilRenderFlush: onWaitUntilRenderFlush,+ suspendTerminal: onSuspendTerminal,+ }), [handleExit, onWaitUntilRenderFlush, onSuspendTerminal]);+ const stdinContextValue = useMemo(() => ({+ stdin,+ setRawMode: handleSetRawMode,+ setBracketedPasteMode: handleSetBracketedPasteMode,+ isRawModeSupported,+ // eslint-disable-next-line @typescript-eslint/naming-convention+ internal_exitOnCtrlC: exitOnCtrlC,+ // eslint-disable-next-line @typescript-eslint/naming-convention+ internal_eventEmitter: eventEmitterRef.current,+ }), [+ stdin,+ handleSetRawMode,+ handleSetBracketedPasteMode,+ isRawModeSupported,+ exitOnCtrlC,+ ]);+ const stdoutContextValue = useMemo(() => ({+ stdout,+ write: writeToStdout,+ }), [stdout, writeToStdout]);+ const stderrContextValue = useMemo(() => ({+ stderr,+ write: writeToStderr,+ }), [stderr, writeToStderr]);+ const cursorContextValue = useMemo(() => ({+ setCursorPosition,+ }), [setCursorPosition]);+ const focusContextValue = useMemo(() => ({+ activeId: activeFocusId,+ add: addFocusable,+ remove: removeFocusable,+ activate: activateFocusable,+ deactivate: deactivateFocusable,+ enableFocus,+ disableFocus,+ focusNext,+ focusPrevious,+ focus,+ }), [+ activeFocusId,+ addFocusable,+ removeFocusable,+ activateFocusable,+ deactivateFocusable,+ enableFocus,+ disableFocus,+ focusNext,+ focusPrevious,+ focus,+ ]);+ const animationContextValue = useMemo(() => ({+ renderThrottleMs,+ subscribe: animationSubscribe,+ }), [animationSubscribe, renderThrottleMs]);+ return (React.createElement(AppContext, { value: appContextValue },+ React.createElement(StdinContext, { value: stdinContextValue },+ React.createElement(StdoutContext, { value: stdoutContextValue },+ React.createElement(StderrContext, { value: stderrContextValue },+ React.createElement(FocusContext, { value: focusContextValue },+ React.createElement(AnimationContext, { value: animationContextValue },+ React.createElement(CursorContext, { value: cursorContextValue },+ React.createElement(ErrorBoundary, { onError: handleExit }, children)))))))));}+App.displayName = 'InternalApp';+export default App;diff --git a/vendor/ink/build/components/AppContext.d.ts b/vendor/ink/build/components/AppContext.d.tsindex f09d5edc..1822214d 100644--- a/vendor/ink/build/components/AppContext.d.ts+++ b/vendor/ink/build/components/AppContext.d.ts@@ -1,11 +1,80 @@+/**+A handle returned by `suspendTerminal()` when called without a callback.++Call `resume()` to give terminal ownership back to Ink, or use `await using`+so the suspension is resumed automatically when it leaves scope.+*/+export type TerminalSuspension = {+ readonly resume: () => Promise<void>;+ readonly [Symbol.asyncDispose]: () => Promise<void>;+};+/**+Temporarily hand the terminal over to a child process (e.g. `$EDITOR`, `less`,+`fzf`), then restore Ink's terminal state and force a full redraw.+*/+export type SuspendTerminal = {+ (callback: () => void | Promise<void>): Promise<void>;+ (): Promise<TerminalSuspension>;+};export type Props = {/**- * Exit (unmount) the whole Ink app.- */- readonly exit: (error?: Error) => void;+ Exit (unmount) the whole Ink app.++ - `exit()` — resolves `waitUntilExit()` with `undefined`.+ - `exit(new Error('…'))` — rejects `waitUntilExit()` with the error.+ - `exit(value)` — resolves `waitUntilExit()` with `value`.+ */+ readonly exit: (errorOrResult?: Error | unknown) => void;+ /**+ Returns a promise that settles after pending render output is flushed to stdout.++ @example+ ```jsx+ import {useEffect} from 'react';+ import {useApp} from 'ink';++ const Example = () => {+ const {waitUntilRenderFlush} = useApp();++ useEffect(() => {+ void (async () => {+ await waitUntilRenderFlush();+ runNextCommand();+ })();+ }, [waitUntilRenderFlush]);++ return …;+ };+ ```+ */+ readonly waitUntilRenderFlush: () => Promise<void>;+ /**+ Temporarily release the terminal so a child process can take it over, then+ restore Ink's terminal state and force a full redraw.++ Use the callback form for the common case — Ink restores the terminal even+ if the callback throws:++ @example+ ```jsx+ import {useApp} from 'ink';++ const {suspendTerminal} = useApp();++ await suspendTerminal(async () => {+ await runEditor();+ });+ ```++ Or hold a suspension and resume it yourself:++ @example+ ```jsx+ await using suspension = await suspendTerminal();+ await runEditor();+ ```+ */+ readonly suspendTerminal: SuspendTerminal;};-/**- * `AppContext` is a React context, which exposes a method to manually exit the app (unmount).- */declare const AppContext: import("react").Context<Props>;export default AppContext;diff --git a/vendor/ink/build/components/AppContext.js b/vendor/ink/build/components/AppContext.jsindex 2cfc3641..6d3d1477 100644--- a/vendor/ink/build/components/AppContext.js+++ b/vendor/ink/build/components/AppContext.js@@ -1,10 +1,24 @@import { createContext } from 'react';/**- * `AppContext` is a React context, which exposes a method to manually exit the app (unmount).- */+`AppContext` is a React context that exposes lifecycle methods for the app.+*/+// Keep the default value typed so `useApp()` preserves the public `exit(errorOrResult?)` signature.+const noopSuspension = {+ async resume() { },+ async [Symbol.asyncDispose]() { },+};+const defaultValue = {+ exit(_errorOrResult) { },+ async waitUntilRenderFlush() { },+ suspendTerminal: (async (callback) => {+ if (callback) {+ await callback();+ return undefined;+ }+ return noopSuspension;+ }),+};// eslint-disable-next-line @typescript-eslint/naming-convention-const AppContext = createContext({- exit() { },-});+const AppContext = createContext(defaultValue);AppContext.displayName = 'InternalAppContext';export default AppContext;diff --git a/vendor/ink/build/components/BackgroundContext.d.ts b/vendor/ink/build/components/BackgroundContext.d.tsnew file mode 100644index 00000000..804d2581--- /dev/null+++ b/vendor/ink/build/components/BackgroundContext.d.ts@@ -0,0 +1,4 @@+import { type LiteralUnion } from 'type-fest';+import { type ForegroundColorName } from 'ansi-styles';+export type BackgroundColor = LiteralUnion<ForegroundColorName, string>;+export declare const BackgroundContext: import("react").Context<BackgroundColor | undefined>;diff --git a/vendor/ink/build/components/BackgroundContext.js b/vendor/ink/build/components/BackgroundContext.jsnew file mode 100644index 00000000..d9010510--- /dev/null+++ b/vendor/ink/build/components/BackgroundContext.js@@ -0,0 +1,3 @@+import { createContext } from 'react';+// eslint-disable-next-line @typescript-eslint/naming-convention -- React contexts are named like components.+export const BackgroundContext = createContext(undefined);diff --git a/vendor/ink/build/components/Box.d.ts b/vendor/ink/build/components/Box.d.tsindex 3320cf50..b26f1fbe 100644--- a/vendor/ink/build/components/Box.d.ts+++ b/vendor/ink/build/components/Box.d.ts@@ -2,12 +2,43 @@ import React from 'react';import { type Except } from 'type-fest';import { type Styles } from '../styles.js';import { type DOMElement } from '../dom.js';-export type Props = Except<Styles, 'textWrap'>;+export type Props = Except<Styles, 'textWrap'> & {+ /**+ A label for the element for screen readers.+ */+ readonly 'aria-label'?: string;+ /**+ Hide the element from screen readers.+ */+ readonly 'aria-hidden'?: boolean;+ /**+ The role of the element.+ */+ readonly 'aria-role'?: 'button' | 'checkbox' | 'combobox' | 'list' | 'listbox' | 'listitem' | 'menu' | 'menuitem' | 'option' | 'progressbar' | 'radio' | 'radiogroup' | 'tab' | 'tablist' | 'table' | 'textbox' | 'timer' | 'toolbar';+ /**+ The state of the element.+ */+ readonly 'aria-state'?: {+ readonly busy?: boolean;+ readonly checked?: boolean;+ readonly disabled?: boolean;+ readonly expanded?: boolean;+ readonly multiline?: boolean;+ readonly multiselectable?: boolean;+ readonly readonly?: boolean;+ readonly required?: boolean;+ readonly selected?: boolean;+ };+};/**- * `<Box>` is an essential Ink component to build your layout. It's like `<div style="display: flex">` in the browser.- */+`<Box>` is an essential Ink component to build your layout. It's like `<div style="display: flex">` in the browser.+*/declare const Box: React.ForwardRefExoticComponent<{- readonly position?: "absolute" | "relative" | undefined;+ readonly position?: "absolute" | "relative" | "static" | undefined;+ readonly top?: number | string | undefined;+ readonly right?: number | string | undefined;+ readonly bottom?: number | string | undefined;+ readonly left?: number | string | undefined;readonly columnGap?: number | undefined;readonly rowGap?: number | undefined;readonly gap?: number | undefined;@@ -30,13 +61,17 @@ declare const Box: React.ForwardRefExoticComponent<{readonly flexDirection?: "row" | "column" | "row-reverse" | "column-reverse" | undefined;readonly flexBasis?: number | string | undefined;readonly flexWrap?: "nowrap" | "wrap" | "wrap-reverse" | undefined;- readonly alignItems?: "flex-start" | "center" | "flex-end" | "stretch" | undefined;- readonly alignSelf?: "flex-start" | "center" | "flex-end" | "auto" | undefined;+ readonly alignItems?: "flex-start" | "center" | "flex-end" | "stretch" | "baseline" | undefined;+ readonly alignSelf?: "flex-start" | "center" | "flex-end" | "auto" | "stretch" | "baseline" | undefined;+ readonly alignContent?: "flex-start" | "flex-end" | "center" | "stretch" | "space-between" | "space-around" | "space-evenly" | undefined;readonly justifyContent?: "flex-start" | "flex-end" | "space-between" | "space-around" | "space-evenly" | "center" | undefined;readonly width?: number | string | undefined;readonly height?: number | string | undefined;- readonly minWidth?: number | string | undefined;+ readonly minWidth?: number | undefined;readonly minHeight?: number | string | undefined;+ readonly maxWidth?: number | undefined;+ readonly maxHeight?: number | string | undefined;+ readonly aspectRatio?: number | undefined;readonly display?: "flex" | "none" | undefined;readonly borderStyle?: (keyof import("cli-boxes").Boxes | import("cli-boxes").BoxStyle) | undefined;readonly borderTop?: boolean | undefined;@@ -53,9 +88,44 @@ declare const Box: React.ForwardRefExoticComponent<{readonly borderBottomDimColor?: boolean | undefined;readonly borderLeftDimColor?: boolean | undefined;readonly borderRightDimColor?: boolean | undefined;+ readonly borderBackgroundColor?: import("type-fest").LiteralUnion<import("ansi-styles").ForegroundColorName, string> | undefined;+ readonly borderTopBackgroundColor?: import("type-fest").LiteralUnion<import("ansi-styles").ForegroundColorName, string> | undefined;+ readonly borderBottomBackgroundColor?: import("type-fest").LiteralUnion<import("ansi-styles").ForegroundColorName, string> | undefined;+ readonly borderLeftBackgroundColor?: import("type-fest").LiteralUnion<import("ansi-styles").ForegroundColorName, string> | undefined;+ readonly borderRightBackgroundColor?: import("type-fest").LiteralUnion<import("ansi-styles").ForegroundColorName, string> | undefined;readonly overflow?: "visible" | "hidden" | undefined;readonly overflowX?: "visible" | "hidden" | undefined;readonly overflowY?: "visible" | "hidden" | undefined;+ readonly contentOffsetX?: number | undefined;+ readonly contentOffsetY?: number | undefined;+ readonly backgroundColor?: import("type-fest").LiteralUnion<import("ansi-styles").ForegroundColorName, string> | undefined;+} & {+ /**+ A label for the element for screen readers.+ */+ readonly 'aria-label'?: string;+ /**+ Hide the element from screen readers.+ */+ readonly 'aria-hidden'?: boolean;+ /**+ The role of the element.+ */+ readonly 'aria-role'?: "button" | "checkbox" | "combobox" | "list" | "listbox" | "listitem" | "menu" | "menuitem" | "option" | "progressbar" | "radio" | "radiogroup" | "tab" | "tablist" | "table" | "textbox" | "timer" | "toolbar";+ /**+ The state of the element.+ */+ readonly 'aria-state'?: {+ readonly busy?: boolean;+ readonly checked?: boolean;+ readonly disabled?: boolean;+ readonly expanded?: boolean;+ readonly multiline?: boolean;+ readonly multiselectable?: boolean;+ readonly readonly?: boolean;+ readonly required?: boolean;+ readonly selected?: boolean;+ };} & {children?: React.ReactNode | undefined;} & React.RefAttributes<DOMElement>>;diff --git a/vendor/ink/build/components/Box.js b/vendor/ink/build/components/Box.jsindex 2e5b96b8..b8548051 100644--- a/vendor/ink/build/components/Box.js+++ b/vendor/ink/build/components/Box.js@@ -1,19 +1,34 @@-import React, { forwardRef } from 'react';+import React, { forwardRef, use } from 'react';+import { AccessibilityContext } from './AccessibilityContext.js';+import { BackgroundContext } from './BackgroundContext.js';/**- * `<Box>` is an essential Ink component to build your layout. It's like `<div style="display: flex">` in the browser.- */-const Box = forwardRef(({ children, ...style }, ref) => {- return (React.createElement("ink-box", { ref: ref, style: {+`<Box>` is an essential Ink component to build your layout. It's like `<div style="display: flex">` in the browser.+*/+// eslint-disable-next-line @eslint-react/no-forward-ref -- Removing `forwardRef` changes the public component type of `Box`.+const Box = forwardRef(({ children, backgroundColor, flexWrap = 'nowrap', flexDirection = 'row', 'aria-label': ariaLabel, 'aria-hidden': ariaHidden, 'aria-role': role, 'aria-state': ariaState, ...style }, ref) => {+ const { isScreenReaderEnabled } = use(AccessibilityContext);+ const inheritedBackgroundColor = use(BackgroundContext);+ if (isScreenReaderEnabled && ariaHidden) {+ return null;+ }+ const effectiveBackgroundColor =+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, @typescript-eslint/strict-boolean-expressions -- Empty background colors inherit from the parent too.+ backgroundColor || inheritedBackgroundColor;+ const boxElement = (React.createElement("ink-box", { ref: ref, style: {+ flexWrap,+ flexDirection,+ flexGrow: 0,+ flexShrink: 1,...style,+ backgroundColor,overflowX: style.overflowX ?? style.overflow ?? 'visible',overflowY: style.overflowY ?? style.overflow ?? 'visible',- } }, children));+ }, internal_accessibility: {+ role,+ state: ariaState,+ } }, isScreenReaderEnabled && Boolean(ariaLabel) ? (React.createElement("ink-text", null, ariaLabel)) : (children)));+ // Provide this Box's background color or its inherited color to children via context+ return (React.createElement(BackgroundContext, { value: effectiveBackgroundColor }, boxElement));});Box.displayName = 'Box';-Box.defaultProps = {- flexWrap: 'nowrap',- flexDirection: 'row',- flexGrow: 0,- flexShrink: 1,-};export default Box;diff --git a/vendor/ink/build/components/Color.js b/vendor/ink/build/components/Color.jsdeleted file mode 100644index 42319d18..00000000--- a/vendor/ink/build/components/Color.js+++ /dev/null@@ -1,62 +0,0 @@-"use strict";--Object.defineProperty(exports, "__esModule", {- value: true-});-exports.default = void 0;--var _react = _interopRequireDefault(require("react"));--var _propTypes = _interopRequireDefault(require("prop-types"));--var _arrify = _interopRequireDefault(require("arrify"));--var _chalk = _interopRequireDefault(require("chalk"));--function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }--function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }--function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }--const methods = ['hex', 'hsl', 'hsv', 'hwb', 'rgb', 'keyword', 'bgHex', 'bgHsl', 'bgHsv', 'bgHwb', 'bgRgb', 'bgKeyword'];--const Color = (_ref) => {- let {- children- } = _ref,- colorProps = _objectWithoutProperties(_ref, ["children"]);-- if (children === '') {- return null;- }-- const transformChildren = children => {- Object.keys(colorProps).forEach(method => {- if (colorProps[method]) {- if (methods.includes(method)) {- children = _chalk.default[method](...(0, _arrify.default)(colorProps[method]))(children);- } else if (typeof _chalk.default[method] === 'function') {- children = _chalk.default[method](children);- }- }- });- return children;- };-- return _react.default.createElement("span", {- style: {- flexDirection: 'row'- },- unstable__transformChildren: transformChildren- }, children);-};--Color.propTypes = {- children: _propTypes.default.node-};-Color.defaultProps = {- children: ''-};-var _default = Color;-exports.default = _default;\ No newline at end of filediff --git a/vendor/ink/build/components/CursorContext.d.ts b/vendor/ink/build/components/CursorContext.d.tsnew file mode 100644index 00000000..80d4ab98--- /dev/null+++ b/vendor/ink/build/components/CursorContext.d.ts@@ -0,0 +1,11 @@+import { type CursorPosition } from '../log-update.js';+export type Props = {+ /**+ Set the cursor position relative to the Ink output.++ Pass `undefined` to hide the cursor.+ */+ readonly setCursorPosition: (position: CursorPosition | undefined) => void;+};+declare const CursorContext: import("react").Context<Props>;+export default CursorContext;diff --git a/vendor/ink/build/components/CursorContext.js b/vendor/ink/build/components/CursorContext.jsnew file mode 100644index 00000000..0f570b84--- /dev/null+++ b/vendor/ink/build/components/CursorContext.js@@ -0,0 +1,7 @@+import { createContext } from 'react';+// eslint-disable-next-line @typescript-eslint/naming-convention+const CursorContext = createContext({+ setCursorPosition() { },+});+CursorContext.displayName = 'InternalCursorContext';+export default CursorContext;diff --git a/vendor/ink/build/components/ErrorBoundary.d.ts b/vendor/ink/build/components/ErrorBoundary.d.tsnew file mode 100644index 00000000..2ad44b85--- /dev/null+++ b/vendor/ink/build/components/ErrorBoundary.d.ts@@ -0,0 +1,18 @@+import { PureComponent, type ReactNode } from 'react';+type Props = {+ readonly children: ReactNode;+ readonly onError: (error: Error) => void;+};+type State = {+ readonly error?: Error;+};+export default class ErrorBoundary extends PureComponent<Props, State> {+ static displayName: string;+ static getDerivedStateFromError(error: unknown): {+ error: Error;+ };+ state: State;+ componentDidCatch(): void;+ render(): ReactNode;+}+export {};diff --git a/vendor/ink/build/components/ErrorBoundary.js b/vendor/ink/build/components/ErrorBoundary.jsnew file mode 100644index 00000000..814faf79--- /dev/null+++ b/vendor/ink/build/components/ErrorBoundary.js@@ -0,0 +1,23 @@+import { types } from 'node:util';+import React, { PureComponent } from 'react';+import ErrorOverview from './ErrorOverview.js';+// Error boundary must be a class component since getDerivedStateFromError+// and componentDidCatch are not available as hooks+export default class ErrorBoundary extends PureComponent {+ static displayName = 'InternalErrorBoundary';+ static getDerivedStateFromError(error) {+ return {+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- Error.isError is not available in Node.js 22.+ error: types.isNativeError(error) ? error : new Error(String(error)),+ };+ }+ state = {+ error: undefined,+ };+ componentDidCatch() {+ this.props.onError(this.state.error);+ }+ render() {+ return this.state.error ? (React.createElement(ErrorOverview, { error: this.state.error })) : (this.props.children);+ }+}diff --git a/vendor/ink/build/components/ErrorOverview.js b/vendor/ink/build/components/ErrorOverview.jsindex b2330887..5e0eb4f6 100644--- a/vendor/ink/build/components/ErrorOverview.js+++ b/vendor/ink/build/components/ErrorOverview.js@@ -1,28 +1,39 @@import * as fs from 'node:fs';+import { relative } from 'node:path';import { cwd } from 'node:process';+import { fileURLToPath } from 'node:url';import React from 'react';import StackUtils from 'stack-utils';import codeExcerpt from 'code-excerpt';import Box from './Box.js';import Text from './Text.js';// Error's source file is reported as file:///home/user/file.js-// This function removes the file://[cwd] part-const cleanupPath = (path) => {- return path?.replace(`file://${cwd()}/`, '');-};+// This function converts file URLs to paths relative to the current directory+const cleanupPath = (path) => path?.startsWith('file://') ? relative(cwd(), fileURLToPath(path)) : path;const stackUtils = new StackUtils({cwd: cwd(),internals: StackUtils.nodeInternals(),});export default function ErrorOverview({ error }) {- const stack = error.stack ? error.stack.split('\n').slice(1) : undefined;+ const stack = error.stack+ ?.split('\n')+ .slice(error.message.split('\n').length);const origin = stack ? stackUtils.parseLine(stack[0]) : undefined;const filePath = cleanupPath(origin?.file);let excerpt;let lineWidth = 0;- if (filePath && origin?.line && fs.existsSync(filePath)) {- const sourceCode = fs.readFileSync(filePath, 'utf8');- excerpt = codeExcerpt(sourceCode, origin.line);+ const stackLineCounts = new Map();+ if (filePath !== undefined &&+ filePath !== '' &&+ origin?.line !== undefined &&+ origin.line !== 0) {+ try {+ const sourceCode = fs.readFileSync(filePath, 'utf8');+ excerpt = codeExcerpt(sourceCode, origin.line);+ }+ catch {+ // Source excerpts are best-effort and must not hide the original error.+ }if (excerpt) {for (const { line } of excerpt) {lineWidth = Math.max(lineWidth, String(line).length);@@ -38,34 +49,46 @@ export default function ErrorOverview({ error }) {React.createElement(Text, null," ",error.message)),- origin && filePath && (React.createElement(Box, { marginTop: 1 },+ origin && filePath !== undefined && filePath !== '' ? (React.createElement(Box, { marginTop: 1 },React.createElement(Text, { dimColor: true },filePath,":",origin.line,":",- origin.column))),- origin && excerpt && (React.createElement(Box, { marginTop: 1, flexDirection: "column" }, excerpt.map(({ line, value }) => (React.createElement(Box, { key: line },+ origin.column))) : null,+ origin && excerpt ? (React.createElement(Box, { marginTop: 1, flexDirection: "column" }, excerpt.map(({ line, value }) => (React.createElement(Box, { key: line },React.createElement(Box, { width: lineWidth + 1 },- React.createElement(Text, { dimColor: line !== origin.line, backgroundColor: line === origin.line ? 'red' : undefined, color: line === origin.line ? 'white' : undefined },+ React.createElement(Text, { dimColor: line !== origin.line, backgroundColor: line === origin.line ? 'red' : undefined, color: line === origin.line ? 'white' : undefined, "aria-label": line === origin.line+ ? `Line ${line}, error`+ : `Line ${line}` },String(line).padStart(lineWidth, ' '),":")),- React.createElement(Text, { key: line, backgroundColor: line === origin.line ? 'red' : undefined, color: line === origin.line ? 'white' : undefined }, ' ' + value)))))),- error.stack && (React.createElement(Box, { marginTop: 1, flexDirection: "column" }, error.stack- .split('\n')- .slice(1)- .map(line => {+ React.createElement(Text, { key: line, backgroundColor: line === origin.line ? 'red' : undefined, color: line === origin.line ? 'white' : undefined }, ' ' + value)))))) : null,+ stack ? (React.createElement(Box, { marginTop: 1, flexDirection: "column" }, stack.map(line => {const parsedLine = stackUtils.parseLine(line);- // If the line from the stack cannot be parsed, we print out the unparsed line.- if (!parsedLine) {- return (React.createElement(Box, { key: line },+ const lineCount = stackLineCounts.get(line) ?? 0;+ stackLineCounts.set(line, lineCount + 1);+ const key = `${line}-${lineCount}`;+ // If the line from the stack cannot be parsed, or parsed into an incomplete+ // frame without source location data (for example, "at native"), we print+ // out the unparsed line.+ if (parsedLine?.file === undefined ||+ parsedLine.file === '' ||+ parsedLine.line === undefined ||+ parsedLine.line === 0 ||+ parsedLine.column === undefined ||+ parsedLine.column === 0) {+ return (React.createElement(Box, { key: key },React.createElement(Text, { dimColor: true }, "- "),- React.createElement(Text, { dimColor: true, bold: true }, line)));+ React.createElement(Text, { dimColor: true, bold: true },+ line,+ "\\t",+ ' ')));}- return (React.createElement(Box, { key: line },+ return (React.createElement(Box, { key: key },React.createElement(Text, { dimColor: true }, "- "),React.createElement(Text, { dimColor: true, bold: true }, parsedLine.function),- React.createElement(Text, { dimColor: true, color: "gray" },+ React.createElement(Text, { dimColor: true, color: "gray", "aria-label": `at ${cleanupPath(parsedLine.file) ?? ''} line ${parsedLine.line} column ${parsedLine.column}` },' ',"(",cleanupPath(parsedLine.file) ?? '',@@ -74,5 +97,5 @@ export default function ErrorOverview({ error }) {":",parsedLine.column,")")));- })))));+ }))) : null));}diff --git a/vendor/ink/build/components/Newline.d.ts b/vendor/ink/build/components/Newline.d.tsindex c51a05ec..869173c1 100644--- a/vendor/ink/build/components/Newline.d.ts+++ b/vendor/ink/build/components/Newline.d.ts@@ -1,13 +1,13 @@import React from 'react';export type Props = {/**- * Number of newlines to insert.- *- * @default 1- */+ Number of newlines to insert.++ @default 1+ */readonly count?: number;};/**- * Adds one or more newline (\n) characters. Must be used within <Text> components.- */+Adds one or more newline (`\n`) characters. Must be used within `<Text>` components.+*/export default function Newline({ count }: Props): React.JSX.Element;diff --git a/vendor/ink/build/components/Newline.js b/vendor/ink/build/components/Newline.jsindex 58a106b8..bc9b380e 100644--- a/vendor/ink/build/components/Newline.js+++ b/vendor/ink/build/components/Newline.js@@ -1,7 +1,7 @@import React from 'react';/**- * Adds one or more newline (\n) characters. Must be used within <Text> components.- */+Adds one or more newline (`\n`) characters. Must be used within `<Text>` components.+*/export default function Newline({ count = 1 }) {return React.createElement("ink-text", null, '\n'.repeat(count));}diff --git a/vendor/ink/build/components/RootNodeContext.d.ts b/vendor/ink/build/components/RootNodeContext.d.tsnew file mode 100644index 00000000..84146507--- /dev/null+++ b/vendor/ink/build/components/RootNodeContext.d.ts@@ -0,0 +1,3 @@+import { type DOMElement } from '../dom.js';+declare const RootNodeContext: import("react").Context<DOMElement | undefined>;+export default RootNodeContext;diff --git a/vendor/ink/build/components/RootNodeContext.js b/vendor/ink/build/components/RootNodeContext.jsnew file mode 100644index 00000000..46588351--- /dev/null+++ b/vendor/ink/build/components/RootNodeContext.js@@ -0,0 +1,4 @@+import { createContext } from 'react';+// eslint-disable-next-line @typescript-eslint/naming-convention -- React contexts are named like components.+const RootNodeContext = createContext(undefined);+export default RootNodeContext;diff --git a/vendor/ink/build/components/Spacer.d.ts b/vendor/ink/build/components/Spacer.d.tsindex 82171f86..272d6a53 100644--- a/vendor/ink/build/components/Spacer.d.ts+++ b/vendor/ink/build/components/Spacer.d.ts@@ -1,6 +1,7 @@import React from 'react';/**- * A flexible space that expands along the major axis of its containing layout.- * It's useful as a shortcut for filling all the available spaces between elements.- */+A flexible space that expands along the major axis of its containing layout.++It's useful as a shortcut for filling all the available space between elements.+*/export default function Spacer(): React.JSX.Element;diff --git a/vendor/ink/build/components/Spacer.js b/vendor/ink/build/components/Spacer.jsindex bdb26d95..e33e775d 100644--- a/vendor/ink/build/components/Spacer.js+++ b/vendor/ink/build/components/Spacer.js@@ -1,9 +1,10 @@import React from 'react';import Box from './Box.js';/**- * A flexible space that expands along the major axis of its containing layout.- * It's useful as a shortcut for filling all the available spaces between elements.- */+A flexible space that expands along the major axis of its containing layout.++It's useful as a shortcut for filling all the available space between elements.+*/export default function Spacer() {return React.createElement(Box, { flexGrow: 1 });}diff --git a/vendor/ink/build/components/Static.d.ts b/vendor/ink/build/components/Static.d.tsindex a4d515b3..104e538d 100644--- a/vendor/ink/build/components/Static.d.ts+++ b/vendor/ink/build/components/Static.d.ts@@ -2,38 +2,30 @@ import React, { type ReactNode } from 'react';import { type Styles } from '../styles.js';export type Props<T> = {/**- * Array of items of any type to render using a function you pass as a component child.- */+ Array of items of any type to render using the function you pass as a component child.+ */readonly items: T[];/**- * Styles to apply to a container of child elements. See <Box> for supported properties.- */+ Styles to apply to a container of child elements. See <Box> for supported properties.+ */readonly style?: Styles;/**- * Function that is called to render every item in `items` array.- * First argument is an item itself and second argument is index of that item in `items` array.- * Note that `key` must be assigned to the root component.- */- readonly children: (item: T, index: number) => ReactNode;+ Function that is called to render every item in the `items` array. The first argument is the item itself, and the second argument is the index of that item in the `items` array. Note that a `key` must be assigned to the root component.+ *//**- * Optional identity function used to track which items have already been- * rendered. When provided, each item is rendered exactly once per- * `<Static>` instance lifetime even if the `items` array is kept bounded- * by shifting the window (which the built-in positional index cannot- * handle). Keys returning `undefined` are ignored.+ * Stable identity for an item (Cosmic Stack patch). When set, items are+ * tracked by key instead of position, so `items` may drop its oldest+ * entries (a bounded window) without breaking. Return `undefined` to skip+ * an item.*/readonly itemKey?: (item: T) => string | undefined;+ readonly children: (item: T, index: number) => ReactNode;};/**- * `<Static>` component permanently renders its output above everything else.- * It's useful for displaying activity like completed tasks or logs - things that- * are not changing after they're rendered (hence the name "Static").- *- * It's preferred to use `<Static>` for use cases like these, when you can't know- * or control the amount of items that need to be rendered.- *- * For example, [Tap](https://github.com/tapjs/node-tap) uses `<Static>` to display- * a list of completed tests. [Gatsby](https://github.com/gatsbyjs/gatsby) uses it- * to display a list of generated pages, while still displaying a live progress bar.- */+`<Static>` component permanently renders its output above everything else. It's useful for displaying activity like completed tasks or logs—things that don't change after they're rendered (hence the name "Static").++It's preferred to use `<Static>` for use cases like these when you can't know or control the number of items that need to be rendered.++For example, [Tap](https://github.com/tapjs/node-tap) uses `<Static>` to display a list of completed tests. [Gatsby](https://github.com/gatsbyjs/gatsby) uses it to display a list of generated pages while still displaying a live progress bar.+*/export default function Static<T>(props: Props<T>): React.JSX.Element;diff --git a/vendor/ink/build/components/Static.js b/vendor/ink/build/components/Static.jsindex e22c94e5..4c8fb63d 100644--- a/vendor/ink/build/components/Static.js+++ b/vendor/ink/build/components/Static.js@@ -1,50 +1,37 @@-import React, { useMemo, useState, useLayoutEffect, useRef } from 'react';+import React, { useMemo, useState, useLayoutEffect, useRef, use, } from 'react';+import { BackgroundContext } from './BackgroundContext.js';/**- * `<Static>` component permanently renders its output above everything else.- * It's useful for displaying activity like completed tasks or logs - things that- * are not changing after they're rendered (hence the name "Static").- *- * It's preferred to use `<Static>` for use cases like these, when you can't know- * or control the amount of items that need to be rendered.- *- * For example, [Tap](https://github.com/tapjs/node-tap) uses `<Static>` to display- * a list of completed tests. [Gatsby](https://github.com/gatsbyjs/gatsby) uses it- * to display a list of generated pages, while still displaying a live progress bar.- *- * Patched (Cosmic Stack): supports an optional `itemKey` identity function.- * The built-in positional index assumes `items` only ever appends — a caller- * that keeps the array bounded by dropping the oldest items (a sliding- * window) breaks it: `items.slice(index)` returns nothing, new items are- * never rendered, and every commit unmounts the whole subtree. With- * `itemKey`, each item is tracked by identity and rendered exactly once per- * instance lifetime, so bounded sliding windows are safe.- */+`<Static>` component permanently renders its output above everything else. It's useful for displaying activity like completed tasks or logs—things that don't change after they're rendered (hence the name "Static").++It's preferred to use `<Static>` for use cases like these when you can't know or control the number of items that need to be rendered.++For example, [Tap](https://github.com/tapjs/node-tap) uses `<Static>` to display a list of completed tests. [Gatsby](https://github.com/gatsbyjs/gatsby) uses it to display a list of generated pages while still displaying a live progress bar.+*/export default function Static(props) {const { items, children: render, style: customStyle, itemKey } = props;const [index, setIndex] = useState(0);- // Identity of items already written to the terminal in this instance.- // Only used when `itemKey` is provided.+ // Static itemKey (Cosmic Stack patch): with `itemKey`, items are tracked by identity and+ // each is written exactly once per instance, so a caller may keep `items`+ // bounded by dropping the oldest (a sliding window). The positional index+ // below assumes append-only: once old items drop off, `items.slice(index)`+ // returns nothing and new items are never written.const committedKeys = useRef(null);- // Bumped after committing keys so the memo recomputes and the rendered- // children are unmounted — the positional path does this via setIndex.- // Without it, committed children stay mounted and the renderer keeps- // re-printing them into the terminal on EVERY subsequent render (each- // pass re-emits `staticOutput` while the nodes are still attached).+ // Bumped after committing keys so the memo recomputes and the written+ // children unmount (the positional path does this via setIndex). Without+ // it they stay mounted and are re-emitted as static output every render.const [commitTick, setCommitTick] = useState(0);+ const inheritedBackgroundColor = use(BackgroundContext);+ const effectiveBackgroundColor =+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, @typescript-eslint/strict-boolean-expressions -- Empty background colors inherit from the parent too.+ customStyle?.backgroundColor || inheritedBackgroundColor;const itemsToRender = useMemo(() => {if (typeof itemKey === 'function') {- if (!committedKeys.current) {- committedKeys.current = new Set();- }+ committedKeys.current ??= new Set();const committed = committedKeys.current;- const out = [];- for (const item of items) {+ return items.filter((item) => {const key = itemKey(item);- if (key !== undefined && !committed.has(key)) {- out.push(item);- }- }- return out;+ return key !== undefined && !committed.has(key);+ });}return items.slice(index);}, [items, index, itemKey, commitTick]);@@ -54,22 +41,19 @@ export default function Static(props) {for (const item of itemsToRender) {committedKeys.current.add(itemKey(item));}- // Unmount what was just written: without this, the nodes stay- // attached and every later render re-prints them (duplicate- // transcript lines accumulating over time).setCommitTick((v) => v + 1);}return;}setIndex(items.length);}, [itemsToRender, itemKey, items.length]);- const children = itemsToRender.map((item, itemIndex) => {- return render(item, itemIndex);- });+ const children = itemsToRender.map((item, itemIndex) => render(item, index + itemIndex));const style = useMemo(() => ({position: 'absolute',flexDirection: 'column',...customStyle,- }), [customStyle]);- return (React.createElement("ink-box", { internal_static: true, style: style }, children));+ display: itemsToRender.length > 0 ? customStyle?.display : 'none',+ }), [customStyle, itemsToRender.length]);+ return (React.createElement(BackgroundContext, { value: effectiveBackgroundColor },+ React.createElement("ink-box", { internal_static: true, style: style }, children)));}diff --git a/vendor/ink/build/components/StderrContext.d.ts b/vendor/ink/build/components/StderrContext.d.tsindex 6e65a172..2babced3 100644--- a/vendor/ink/build/components/StderrContext.d.ts+++ b/vendor/ink/build/components/StderrContext.d.ts@@ -1,17 +1,15 @@export type Props = {/**- * Stderr stream passed to `render()` in `options.stderr` or `process.stderr` by default.- */- readonly stderr: NodeJS.WriteStream;+ Stderr stream passed to `render()` in `options.stderr` or `process.stderr` by default.+ */+ readonly stderr: NodeJS.WritableStream;/**- * Write any string to stderr, while preserving Ink's output.- * It's useful when you want to display some external information outside of Ink's rendering and ensure there's no conflict between the two.- * It's similar to `<Static>`, except it can't accept components, it only works with strings.- */+ Write any string to stderr while preserving Ink's output. It's useful when you want to display external information outside of Ink's rendering and ensure there's no conflict between the two. It's similar to `<Static>`, except it can't accept components; it only works with strings.+ */readonly write: (data: string) => void;};/**- * `StderrContext` is a React context, which exposes stderr stream.- */+`StderrContext` is a React context that exposes the stderr stream.+*/declare const StderrContext: import("react").Context<Props>;export default StderrContext;diff --git a/vendor/ink/build/components/StderrContext.js b/vendor/ink/build/components/StderrContext.jsindex 41c44554..a566e3e3 100644--- a/vendor/ink/build/components/StderrContext.js+++ b/vendor/ink/build/components/StderrContext.js@@ -1,8 +1,8 @@import process from 'node:process';import { createContext } from 'react';/**- * `StderrContext` is a React context, which exposes stderr stream.- */+`StderrContext` is a React context that exposes the stderr stream.+*/// eslint-disable-next-line @typescript-eslint/naming-conventionconst StderrContext = createContext({stderr: process.stderr,diff --git a/vendor/ink/build/components/StdinContext.d.ts b/vendor/ink/build/components/StdinContext.d.tsindex c7259e5e..9350b028 100644--- a/vendor/ink/build/components/StdinContext.d.ts+++ b/vendor/ink/build/components/StdinContext.d.ts@@ -1,23 +1,28 @@import { EventEmitter } from 'node:events';-export type Props = {+export type PublicProps = {/**- * Stdin stream passed to `render()` in `options.stdin` or `process.stdin` by default. Useful if your app needs to handle user input.- */- readonly stdin: NodeJS.ReadStream;+ The stdin stream passed to `render()` in `options.stdin`, or `process.stdin` by default. Useful if your app needs to handle user input.+ */+ readonly stdin: NodeJS.ReadableStream;/**- * Ink exposes this function via own `<StdinContext>` to be able to handle Ctrl+C, that's why you should use Ink's `setRawMode` instead of `process.stdin.setRawMode`.- * If the `stdin` stream passed to Ink does not support setRawMode, this function does nothing.- */- readonly setRawMode: (value: boolean) => void;+ Ink exposes this function via own `<StdinContext>` to be able to handle Ctrl+C, that's why you should use Ink's `setRawMode` instead of `process.stdin.setRawMode`. If the `stdin` stream passed to Ink does not support setRawMode, this function does nothing.+ */+ readonly setRawMode: (isEnabled: boolean) => void;/**- * A boolean flag determining if the current `stdin` supports `setRawMode`. A component using `setRawMode` might want to use `isRawModeSupported` to nicely fall back in environments where raw mode is not supported.- */+ A boolean flag determining if the current `stdin` supports `setRawMode`. A component using `setRawMode` might want to use `isRawModeSupported` to nicely fall back in environments where raw mode is not supported.+ */readonly isRawModeSupported: boolean;+};+export type Props = PublicProps & {+ /**+ Enable or disable bracketed paste mode on the terminal. When enabled, pasted text is wrapped in escape sequences that allow it to be distinguished from typed input.+ */+ readonly setBracketedPasteMode: (isEnabled: boolean) => void;readonly internal_exitOnCtrlC: boolean;readonly internal_eventEmitter: EventEmitter;};/**- * `StdinContext` is a React context, which exposes input stream.- */+`StdinContext` is a React context that exposes the input stream.+*/declare const StdinContext: import("react").Context<Props>;export default StdinContext;diff --git a/vendor/ink/build/components/StdinContext.js b/vendor/ink/build/components/StdinContext.jsindex 67047b50..d35d9044 100644--- a/vendor/ink/build/components/StdinContext.js+++ b/vendor/ink/build/components/StdinContext.js@@ -2,14 +2,15 @@ import { EventEmitter } from 'node:events';import process from 'node:process';import { createContext } from 'react';/**- * `StdinContext` is a React context, which exposes input stream.- */+`StdinContext` is a React context that exposes the input stream.+*/// eslint-disable-next-line @typescript-eslint/naming-conventionconst StdinContext = createContext({stdin: process.stdin,// eslint-disable-next-line @typescript-eslint/naming-conventioninternal_eventEmitter: new EventEmitter(),setRawMode() { },+ setBracketedPasteMode() { },isRawModeSupported: false,// eslint-disable-next-line @typescript-eslint/naming-conventioninternal_exitOnCtrlC: true,diff --git a/vendor/ink/build/components/StdoutContext.d.ts b/vendor/ink/build/components/StdoutContext.d.tsindex 03d17cf2..50a899b6 100644--- a/vendor/ink/build/components/StdoutContext.d.ts+++ b/vendor/ink/build/components/StdoutContext.d.ts@@ -1,17 +1,15 @@export type Props = {/**- * Stdout stream passed to `render()` in `options.stdout` or `process.stdout` by default.- */- readonly stdout: NodeJS.WriteStream;+ Stdout stream passed to `render()` in `options.stdout` or `process.stdout` by default.+ */+ readonly stdout: NodeJS.WritableStream;/**- * Write any string to stdout, while preserving Ink's output.- * It's useful when you want to display some external information outside of Ink's rendering and ensure there's no conflict between the two.- * It's similar to `<Static>`, except it can't accept components, it only works with strings.- */+ Write any string to stdout while preserving Ink's output. It's useful when you want to display external information outside of Ink's rendering and ensure there's no conflict between the two. It's similar to `<Static>`, except it can't accept components; it only works with strings.+ */readonly write: (data: string) => void;};/**- * `StdoutContext` is a React context, which exposes stdout stream, where Ink renders your app.- */+`StdoutContext` is a React context that exposes the stdout stream where Ink renders your app.+*/declare const StdoutContext: import("react").Context<Props>;export default StdoutContext;diff --git a/vendor/ink/build/components/StdoutContext.js b/vendor/ink/build/components/StdoutContext.jsindex f6108293..57528fd0 100644--- a/vendor/ink/build/components/StdoutContext.js+++ b/vendor/ink/build/components/StdoutContext.js@@ -1,8 +1,8 @@import process from 'node:process';import { createContext } from 'react';/**- * `StdoutContext` is a React context, which exposes stdout stream, where Ink renders your app.- */+`StdoutContext` is a React context that exposes the stdout stream where Ink renders your app.+*/// eslint-disable-next-line @typescript-eslint/naming-conventionconst StdoutContext = createContext({stdout: process.stdout,diff --git a/vendor/ink/build/components/Text.d.ts b/vendor/ink/build/components/Text.d.tsindex 01b12d8a..1d7bf6bf 100644--- a/vendor/ink/build/components/Text.d.ts+++ b/vendor/ink/build/components/Text.d.ts@@ -4,46 +4,52 @@ import { type LiteralUnion } from 'type-fest';import { type Styles } from '../styles.js';export type Props = {/**- * Change text color. Ink uses chalk under the hood, so all its functionality is supported.- */+ A label for the element for screen readers.+ */+ readonly 'aria-label'?: string;+ /**+ Hide the element from screen readers.+ */+ readonly 'aria-hidden'?: boolean;+ /**+ Change text color. Ink uses Chalk under the hood, so all its functionality is supported.+ */readonly color?: LiteralUnion<ForegroundColorName, string>;/**- * Same as `color`, but for background.- */+ Same as `color`, but for the background.+ */readonly backgroundColor?: LiteralUnion<ForegroundColorName, string>;/**- * Dim the color (emit a small amount of light).- */+ Dim the color (make it less bright).+ */readonly dimColor?: boolean;/**- * Make the text bold.- */+ Make the text bold.+ */readonly bold?: boolean;/**- * Make the text italic.- */+ Make the text italic.+ */readonly italic?: boolean;/**- * Make the text underlined.- */+ Make the text underlined.+ */readonly underline?: boolean;/**- * Make the text crossed with a line.- */+ Make the text crossed out with a line.+ */readonly strikethrough?: boolean;/**- * Inverse background and foreground colors.- */+ Inverse background and foreground colors.+ */readonly inverse?: boolean;/**- * This property tells Ink to wrap or truncate text if its width is larger than container.- * If `wrap` is passed (by default), Ink will wrap text and split it into multiple lines.- * If `truncate-*` is passed, Ink will truncate text instead, which will result in one line of text with the rest cut off.- */+ This property tells Ink to wrap or truncate text if its width is larger than the container. If `wrap` is passed (the default), Ink will wrap text and split it into multiple lines. If `hard` is passed, Ink will fill each line to the full column width, breaking words as necessary. If `truncate-*` is passed, Ink will truncate text instead, resulting in one line of text with the rest cut off.+ */readonly wrap?: Styles['textWrap'];readonly children?: ReactNode;};/**- * This component can display text, and change its style to make it colorful, bold, underline, italic or strikethrough.- */-export default function Text({ color, backgroundColor, dimColor, bold, italic, underline, strikethrough, inverse, wrap, children, }: Props): React.JSX.Element | null;+This component can display text and change its style to make it bold, underlined, italic, or strikethrough.+*/+export default function Text({ color, backgroundColor, dimColor, bold, italic, underline, strikethrough, inverse, wrap, children, 'aria-label': ariaLabel, 'aria-hidden': ariaHidden, }: Props): React.JSX.Element | null;diff --git a/vendor/ink/build/components/Text.js b/vendor/ink/build/components/Text.jsindex edee34b8..a4d86eb3 100644--- a/vendor/ink/build/components/Text.js+++ b/vendor/ink/build/components/Text.js@@ -1,39 +1,51 @@-import React from 'react';+import React, { use } from 'react';import chalk from 'chalk';import colorize from '../colorize.js';+import { AccessibilityContext } from './AccessibilityContext.js';+import { BackgroundContext } from './BackgroundContext.js';/**- * This component can display text, and change its style to make it colorful, bold, underline, italic or strikethrough.- */-export default function Text({ color, backgroundColor, dimColor = false, bold = false, italic = false, underline = false, strikethrough = false, inverse = false, wrap = 'wrap', children, }) {- if (children === undefined || children === null) {+This component can display text and change its style to make it bold, underlined, italic, or strikethrough.+*/+export default function Text({ color, backgroundColor, dimColor = false, bold = false, italic = false, underline = false, strikethrough = false, inverse = false, wrap = 'wrap', children, 'aria-label': ariaLabel, 'aria-hidden': ariaHidden = false, }) {+ const { isScreenReaderEnabled } = use(AccessibilityContext);+ const inheritedBackgroundColor = use(BackgroundContext);+ // Use explicit backgroundColor if provided, otherwise inherit from the nearest parent Text or Box.+ const effectiveBackgroundColor = backgroundColor ?? inheritedBackgroundColor;+ const childrenOrAriaLabel = isScreenReaderEnabled && Boolean(ariaLabel) ? ariaLabel : children;+ if (childrenOrAriaLabel === undefined ||+ childrenOrAriaLabel === null ||+ (isScreenReaderEnabled && ariaHidden)) {return null;}- const transform = (children) => {+ const transform = (text) => {if (dimColor) {- children = chalk.dim(children);- }- if (color) {- children = colorize(children, color, 'foreground');- }- if (backgroundColor) {- children = colorize(children, backgroundColor, 'background');+ text = chalk.dim(text);}+ // `colorize` returns the text unchanged when the color is unset.+ text = colorize(text, color, 'foreground');+ text = colorize(text, effectiveBackgroundColor, 'background');if (bold) {- children = chalk.bold(children);+ text = chalk.bold(text);}if (italic) {- children = chalk.italic(children);+ text = chalk.italic(text);}if (underline) {- children = chalk.underline(children);+ text = chalk.underline(text);}if (strikethrough) {- children = chalk.strikethrough(children);+ text = chalk.strikethrough(text);}if (inverse) {- children = chalk.inverse(children);+ text = chalk.inverse(text);}- return children;+ return text;};- return (React.createElement("ink-text", { style: { flexGrow: 0, flexShrink: 1, flexDirection: 'row', textWrap: wrap }, internal_transform: transform }, children));+ return (React.createElement(BackgroundContext, { value: effectiveBackgroundColor },+ React.createElement("ink-text", { style: {+ flexGrow: 0,+ flexShrink: 1,+ flexDirection: 'row',+ textWrap: wrap,+ }, internal_transform: isScreenReaderEnabled ? undefined : transform }, childrenOrAriaLabel)));}diff --git a/vendor/ink/build/components/Transform.d.ts b/vendor/ink/build/components/Transform.d.tsindex 98aa7dd7..8163e992 100644--- a/vendor/ink/build/components/Transform.d.ts+++ b/vendor/ink/build/components/Transform.d.ts@@ -1,15 +1,16 @@import React, { type ReactNode } from 'react';export type Props = {/**- * Function which transforms children output. It accepts children and must return transformed children too.- */+ Screen-reader-specific text to output. If this is set, all children will be ignored.+ */+ readonly accessibilityLabel?: string;+ /**+ Function that transforms children output. It accepts children and must return transformed children as well. Note that when children use `<Text>` styling props (e.g. `color`, `bold`), the string will contain ANSI escape codes.+ */readonly transform: (children: string, index: number) => string;readonly children?: ReactNode;};/**- * Transform a string representation of React components before they are written to output.- * For example, you might want to apply a gradient to text, add a clickable link or create some text effects.- * These use cases can't accept React nodes as input, they are expecting a string.- * That's what <Transform> component does, it gives you an output string of its child components and lets you transform it in any way.- */-export default function Transform({ children, transform }: Props): React.JSX.Element | null;+Transform a string representation of React components before they're written to output. For example, you might want to apply a gradient to text, add a clickable link, or create some text effects. These use cases can't accept React nodes as input; they expect a string. That's what the <Transform> component does: it gives you an output string of its child components and lets you transform it in any way.+*/+export default function Transform({ children, transform, accessibilityLabel, }: Props): React.JSX.Element | null;diff --git a/vendor/ink/build/components/Transform.js b/vendor/ink/build/components/Transform.jsindex 4dc3a1a6..3298d30f 100644--- a/vendor/ink/build/components/Transform.js+++ b/vendor/ink/build/components/Transform.js@@ -1,13 +1,16 @@-import React from 'react';+import React, { use } from 'react';+import { AccessibilityContext } from './AccessibilityContext.js';/**- * Transform a string representation of React components before they are written to output.- * For example, you might want to apply a gradient to text, add a clickable link or create some text effects.- * These use cases can't accept React nodes as input, they are expecting a string.- * That's what <Transform> component does, it gives you an output string of its child components and lets you transform it in any way.- */-export default function Transform({ children, transform }) {- if (children === undefined || children === null) {+Transform a string representation of React components before they're written to output. For example, you might want to apply a gradient to text, add a clickable link, or create some text effects. These use cases can't accept React nodes as input; they expect a string. That's what the <Transform> component does: it gives you an output string of its child components and lets you transform it in any way.+*/+export default function Transform({ children, transform, accessibilityLabel, }) {+ const { isScreenReaderEnabled } = use(AccessibilityContext);+ const childrenOrAccessibilityLabel = isScreenReaderEnabled+ ? (accessibilityLabel ?? children)+ : children;+ if (childrenOrAccessibilityLabel === undefined ||+ childrenOrAccessibilityLabel === null) {return null;}- return (React.createElement("ink-text", { style: { flexGrow: 0, flexShrink: 1, flexDirection: 'row' }, internal_transform: transform }, children));+ return (React.createElement("ink-text", { style: { flexGrow: 0, flexShrink: 1, flexDirection: 'row' }, internal_transform: isScreenReaderEnabled ? undefined : transform }, childrenOrAccessibilityLabel));}diff --git a/vendor/ink/build/cursor-helpers.d.ts b/vendor/ink/build/cursor-helpers.d.tsnew file mode 100644index 00000000..9ede7365--- /dev/null+++ b/vendor/ink/build/cursor-helpers.d.ts@@ -0,0 +1,56 @@+export type CursorPosition = {+ x: number;+ y: number;+};+declare const showCursorEscape = "\u001B[?25h";+declare const hideCursorEscape = "\u001B[?25l";+export { showCursorEscape, hideCursorEscape };+/**+Compare two cursor positions. Returns true if they differ.+*/+export declare const cursorPositionChanged: (a: CursorPosition | undefined, b: CursorPosition | undefined) => boolean;+/**+Build escape sequence to move cursor from the bottom of the output to the target position and show it.++`bottomLine` is the row the renderer left the cursor on, counted from the top of the output.+That is always `lines.length - 1` for `lines = str.split('\n')`, whether or not the output ends+with a newline:++- With a trailing newline, `split` yields one extra empty element and the renderer stops just+ past the last visible line — which is `lines.length - 1`.+- Without one, there is no extra element and the renderer deliberately stops on the last visible+ line instead of moving past it — which is also `lines.length - 1`.++This is the same row basis `buildReturnToBottom` measures from, so the two stay in step.+*/+export declare const buildCursorSuffix: (bottomLine: number, cursorPosition: CursorPosition | undefined) => string;+/**+Build escape sequence to move cursor from previousCursorPosition back to the bottom of output.+This must be done before eraseLines or any operation that assumes cursor is at the bottom.+*/+export declare const buildReturnToBottom: (previousLineCount: number, previousCursorPosition: CursorPosition | undefined) => string;+export type CursorOnlyInput = {+ cursorWasShown: boolean;+ previousLineCount: number;+ previousCursorPosition: CursorPosition | undefined;+ cursorPosition: CursorPosition | undefined;+};+/**+Build the escape sequence for cursor-only updates (output unchanged, cursor moved).+Hides cursor if it was previously shown, returns to bottom, then repositions.++`buildReturnToBottom` has just placed the cursor on row `previousLineCount - 1`, so the+suffix measures from there rather than recomputing the row from the output.+*/+export declare const buildCursorOnlySequence: (input: CursorOnlyInput) => string;+/**+Build the prefix that hides cursor and returns to bottom before erasing or rewriting.+Returns empty string if cursor was not shown.+*/+export declare const buildReturnToBottomPrefix: (wasCursorShown: boolean, previousLineCount: number, previousCursorPosition: CursorPosition | undefined) => string;+/**+Build the sequence that erases the previous frame, as `clear` does before other output is written.++With a cursor shown, the frame's top row is found relative to the cursor instead of returning to the bottom first. A terminal shrinking its rows drops the rows below the cursor before scrolling anything, so the frame's bottom rows may be gone: moving down clamps at the last row and erasing upward from there reaches into the content above the frame.+*/+export declare const buildEraseFrame: (previousLineCount: number, previousCursorPosition: CursorPosition | undefined) => string;diff --git a/vendor/ink/build/cursor-helpers.js b/vendor/ink/build/cursor-helpers.jsnew file mode 100644index 00000000..64be8e1a--- /dev/null+++ b/vendor/ink/build/cursor-helpers.js@@ -0,0 +1,86 @@+import ansiEscapes from 'ansi-escapes';+const showCursorEscape = '\u{1B}[?25h';+const hideCursorEscape = '\u{1B}[?25l';+export { showCursorEscape, hideCursorEscape };+/**+Compare two cursor positions. Returns true if they differ.+*/+// eslint-disable-next-line unicorn/consistent-boolean-name -- Exported helper that tests import by this name.+export const cursorPositionChanged = (a, b) => a?.x !== b?.x || a?.y !== b?.y;+/**+Build escape sequence to move cursor from the bottom of the output to the target position and show it.++`bottomLine` is the row the renderer left the cursor on, counted from the top of the output.+That is always `lines.length - 1` for `lines = str.split('\n')`, whether or not the output ends+with a newline:++- With a trailing newline, `split` yields one extra empty element and the renderer stops just+ past the last visible line — which is `lines.length - 1`.+- Without one, there is no extra element and the renderer deliberately stops on the last visible+ line instead of moving past it — which is also `lines.length - 1`.++This is the same row basis `buildReturnToBottom` measures from, so the two stay in step.+*/+export const buildCursorSuffix = (bottomLine, cursorPosition) => {+ if (!cursorPosition) {+ return '';+ }+ const moveUp = bottomLine - cursorPosition.y;+ return ((moveUp > 0 ? ansiEscapes.cursorUp(moveUp) : '') ++ ansiEscapes.cursorTo(cursorPosition.x) ++ showCursorEscape);+};+/**+Build escape sequence to move cursor from previousCursorPosition back to the bottom of output.+This must be done before eraseLines or any operation that assumes cursor is at the bottom.+*/+export const buildReturnToBottom = (previousLineCount, previousCursorPosition) => {+ if (!previousCursorPosition) {+ return '';+ }+ // PreviousLineCount is the raw `split('\n')` length, so `previousLineCount - 1`+ // is the row the cursor was left on regardless of a trailing newline — the same+ // basis `buildCursorSuffix` takes as its `bottomLine`.+ const down = previousLineCount - 1 - previousCursorPosition.y;+ return ((down > 0 ? ansiEscapes.cursorDown(down) : '') + ansiEscapes.cursorTo(0));+};+/**+Build the escape sequence for cursor-only updates (output unchanged, cursor moved).+Hides cursor if it was previously shown, returns to bottom, then repositions.++`buildReturnToBottom` has just placed the cursor on row `previousLineCount - 1`, so the+suffix measures from there rather than recomputing the row from the output.+*/+export const buildCursorOnlySequence = (input) => {+ const hidePrefix = input.cursorWasShown ? hideCursorEscape : '';+ const returnToBottom = buildReturnToBottom(input.previousLineCount, input.previousCursorPosition);+ const cursorSuffix = buildCursorSuffix(input.previousLineCount - 1, input.cursorPosition);+ return hidePrefix + returnToBottom + cursorSuffix;+};+/**+Build the prefix that hides cursor and returns to bottom before erasing or rewriting.+Returns empty string if cursor was not shown.+*/+export const buildReturnToBottomPrefix = (wasCursorShown, previousLineCount, previousCursorPosition) => {+ if (!wasCursorShown) {+ return '';+ }+ return (hideCursorEscape ++ buildReturnToBottom(previousLineCount, previousCursorPosition));+};+/**+Build the sequence that erases the previous frame, as `clear` does before other output is written.++With a cursor shown, the frame's top row is found relative to the cursor instead of returning to the bottom first. A terminal shrinking its rows drops the rows below the cursor before scrolling anything, so the frame's bottom rows may be gone: moving down clamps at the last row and erasing upward from there reaches into the content above the frame.+*/+export const buildEraseFrame = (previousLineCount, previousCursorPosition) => {+ if (!previousCursorPosition) {+ return ansiEscapes.eraseLines(previousLineCount);+ }+ // `buildCursorSuffix` never moves below the bottom row, so a cursor set past the output sits on that row.+ const rowsBelowTop = Math.min(previousCursorPosition.y, previousLineCount - 1);+ return (hideCursorEscape ++ ansiEscapes.cursorMove(0, -rowsBelowTop) ++ ansiEscapes.cursorTo(0) ++ ansiEscapes.eraseDown);+};diff --git a/vendor/ink/build/devtools-window-polyfill.js b/vendor/ink/build/devtools-window-polyfill.jsindex 8f5a3a95..2dd46877 100644--- a/vendor/ink/build/devtools-window-polyfill.js+++ b/vendor/ink/build/devtools-window-polyfill.js@@ -1,11 +1,11 @@-// Ignoring missing types error to avoid adding another dependency for this hack to work-import ws from 'ws';// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment-const customGlobal = global;+const customGlobal = globalThis;// These things must exist before importing `react-devtools-core`-customGlobal.WebSocket ||= ws;-customGlobal.window ||= global;-customGlobal.self ||= global;+// Using ||= intentionally to set falsy values, not just null/undefined+// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing+customGlobal.window ||= globalThis;+// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing+customGlobal.self ||= globalThis;// Filter out Ink's internal components from devtools for a cleaner view.// Also, ince `react-devtools-shared` package isn't published on npm, we can't// use its types, that's why there are hard-coded values in `type` fields below.@@ -61,3 +61,4 @@ customGlobal.window.__REACT_DEVTOOLS_COMPONENT_FILTERS__ = [isValid: true,},];+export {};diff --git a/vendor/ink/build/devtools.js b/vendor/ink/build/devtools.jsindex c6f72b94..50c7613b 100644--- a/vendor/ink/build/devtools.js+++ b/vendor/ink/build/devtools.js@@ -1,8 +1,16 @@-/* eslint-disable import/order */-// eslint-disable-next-line import/no-unassigned-import+/* eslint-disable import-x/order -- The window polyfill must be imported before `react-devtools-core`. */+// eslint-disable-next-line import-x/no-unassigned-importimport './devtools-window-polyfill.js';// eslint-disable-next-line @typescript-eslint/ban-ts-comment// @ts-expect-errorimport devtools from 'react-devtools-core';-// eslint-disable-next-line @typescript-eslint/no-unsafe-call-devtools.connectToDevTools();+import isDevToolsReachable from './is-devtools-reachable.js';+if (await isDevToolsReachable()) {+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call+ devtools.initialize();+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call+ devtools.connectToDevTools();+}+else {+ console.warn('DEV is set to true, but the React DevTools server is not running. Start it with:\n\n$ npx react-devtools\n');+}diff --git a/vendor/ink/build/dom.d.ts b/vendor/ink/build/dom.d.tsindex 3e0ce25c..3dee06b8 100644--- a/vendor/ink/build/dom.d.ts+++ b/vendor/ink/build/dom.d.ts@@ -7,6 +7,7 @@ type InkNode = {internal_static?: boolean;style: Styles;};+type LayoutListener = () => void;export type TextName = '#text';export type ElementNames = 'ink-root' | 'ink-box' | 'ink-text' | 'ink-virtual-text';export type NodeNames = ElementNames | TextName;@@ -15,11 +16,29 @@ export type DOMElement = {attributes: Record<string, DOMNodeAttribute>;childNodes: DOMNode[];internal_transform?: OutputTransformer;+ internal_accessibility?: {+ role?: 'button' | 'checkbox' | 'combobox' | 'list' | 'listbox' | 'listitem' | 'menu' | 'menuitem' | 'option' | 'progressbar' | 'radio' | 'radiogroup' | 'tab' | 'tablist' | 'table' | 'textbox' | 'timer' | 'toolbar';+ state?: {+ busy?: boolean;+ checked?: boolean;+ disabled?: boolean;+ expanded?: boolean;+ multiline?: boolean;+ multiselectable?: boolean;+ readonly?: boolean;+ required?: boolean;+ selected?: boolean;+ };+ };+ isHidden?: boolean;isStaticDirty?: boolean;staticNode?: DOMElement;+ previousStaticNode?: DOMElement;onComputeLayout?: () => void;onRender?: () => void;onImmediateRender?: () => void;+ onStaticChange?: () => void;+ internal_layoutListeners?: Set<LayoutListener>;} & InkNode;export type TextNode = {nodeName: TextName;@@ -34,9 +53,27 @@ export type DOMNodeAttribute = boolean | string | number;export declare const createNode: (nodeName: ElementNames) => DOMElement;export declare const appendChildNode: (node: DOMElement, childNode: DOMElement) => void;export declare const insertBeforeNode: (node: DOMElement, newChildNode: DOMNode, beforeChildNode: DOMNode) => void;-export declare const removeChildNode: (node: DOMElement, removeNode: DOMNode) => void;+export declare const removeChildNode: (node: DOMElement, removedNode: DOMNode) => void;+/**+Free the Yoga (WASM) memory of a removed subtree, then drop the `yogaNode`+reference on every DOM node within it.++`freeRecursive()` releases the WASM memory but leaves each JS wrapper object+truthy, so every `?.yogaNode` guard in the codebase would still pass and then+trap on a use-after-free when the wrapper is dereferenced (see+QwenLM/qwen-code#6820). Nulling the references makes those guards effective and+turns any lingering access into a safe no-op.+*/+export declare const freeYogaSubtree: (removedNode: DOMNode) => void;export declare const setAttribute: (node: DOMElement, key: string, value: DOMNodeAttribute) => void;-export declare const setStyle: (node: DOMNode, style: Styles) => void;+/**+Update a text transform and invalidate measurements that include its output.+*/+export declare const setTransform: (node: DOMElement, transform: OutputTransformer | undefined) => void;+export declare const setStyle: (node: DOMNode, style?: Styles) => void;export declare const createTextNode: (text: string) => TextNode;+export declare const setNodeHidden: (node: DOMElement, isHidden: boolean) => void;export declare const setTextNodeValue: (node: TextNode, text: string) => void;+export declare const addLayoutListener: (rootNode: DOMElement, listener: LayoutListener) => (() => void);+export declare const emitLayoutListeners: (rootNode: DOMElement) => void;export {};diff --git a/vendor/ink/build/dom.js b/vendor/ink/build/dom.jsindex 8d0ae6d6..84c8c3b0 100644--- a/vendor/ink/build/dom.js+++ b/vendor/ink/build/dom.js@@ -10,6 +10,8 @@ export const createNode = (nodeName) => {childNodes: [],parentNode: undefined,yogaNode: nodeName === 'ink-virtual-text' ? undefined : Yoga.Node.create(),+ // eslint-disable-next-line @typescript-eslint/naming-convention+ internal_accessibility: {},};if (nodeName === 'ink-text') {node.yogaNode?.setMeasureFunc(measureTextNode.bind(null, node));@@ -40,22 +42,23 @@ export const insertBeforeNode = (node, newChildNode, beforeChildNode) => {if (newChildNode.yogaNode) {node.yogaNode?.insertChild(newChildNode.yogaNode, index);}- return;}- node.childNodes.push(newChildNode);- if (newChildNode.yogaNode) {- node.yogaNode?.insertChild(newChildNode.yogaNode, node.yogaNode.getChildCount());+ else {+ node.childNodes.push(newChildNode);+ if (newChildNode.yogaNode) {+ node.yogaNode?.insertChild(newChildNode.yogaNode, node.yogaNode.getChildCount());+ }}if (node.nodeName === 'ink-text' || node.nodeName === 'ink-virtual-text') {markNodeAsDirty(node);}};-export const removeChildNode = (node, removeNode) => {- if (removeNode.yogaNode) {- removeNode.parentNode?.yogaNode?.removeChild(removeNode.yogaNode);+export const removeChildNode = (node, removedNode) => {+ if (removedNode.yogaNode) {+ removedNode.parentNode?.yogaNode?.removeChild(removedNode.yogaNode);}- removeNode.parentNode = undefined;- const index = node.childNodes.indexOf(removeNode);+ removedNode.parentNode = undefined;+ const index = node.childNodes.indexOf(removedNode);if (index >= 0) {node.childNodes.splice(index, 1);}@@ -63,11 +66,53 @@ export const removeChildNode = (node, removeNode) => {markNodeAsDirty(node);}};+const nullifyYogaNodes = (node) => {+ node.yogaNode = undefined;+ if (node.nodeName !== '#text') {+ for (const childNode of node.childNodes) {+ nullifyYogaNodes(childNode);+ }+ }+};+/**+Free the Yoga (WASM) memory of a removed subtree, then drop the `yogaNode`+reference on every DOM node within it.++`freeRecursive()` releases the WASM memory but leaves each JS wrapper object+truthy, so every `?.yogaNode` guard in the codebase would still pass and then+trap on a use-after-free when the wrapper is dereferenced (see+QwenLM/qwen-code#6820). Nulling the references makes those guards effective and+turns any lingering access into a safe no-op.+*/+export const freeYogaSubtree = (removedNode) => {+ removedNode.yogaNode?.unsetMeasureFunc();+ removedNode.yogaNode?.freeRecursive();+ nullifyYogaNodes(removedNode);+};export const setAttribute = (node, key, value) => {+ if (key === 'internal_accessibility') {+ node.internal_accessibility = value;+ return;+ }node.attributes[key] = value;};+/**+Update a text transform and invalidate measurements that include its output.+*/+export const setTransform = (node, transform) => {+ node.internal_transform = transform;+ // Nested transforms contribute to the enclosing text node's measured content.+ if (node.nodeName === 'ink-virtual-text') {+ markNodeAsDirty(node);+ }+};export const setStyle = (node, style) => {- node.style = style;+ if (node.nodeName === 'ink-text' && node.style.textWrap !== style?.textWrap) {+ // Wrapping changes text measurements without changing any Yoga style.+ node.yogaNode?.markDirty();+ }+ // Rendering code assumes style is always an object.+ node.style = style ?? {};};export const createTextNode = (text) => {const node = {@@ -80,37 +125,62 @@ export const createTextNode = (text) => {setTextNodeValue(node, text);return node;};-const measureTextNode = function (node, width) {+const measureTextNode = function (node, width, widthMode) {const text = node.nodeName === '#text' ? node.nodeValue : squashTextNodes(node);const dimensions = measureText(text);+ // An unconstrained Yoga measurement requests the natural size, not wrapping or truncation at its NaN width.// Text fits into container, no need to wrap- if (dimensions.width <= width) {- return dimensions;- }- // This is happening when <Box> is shrinking child nodes and Yoga asks- // if we can fit this text node in a <1px space, so we just tell Yoga "no"- if (dimensions.width >= 1 && width > 0 && width < 1) {+ if (widthMode === Yoga.MEASURE_MODE_UNDEFINED || dimensions.width <= width) {return dimensions;}const textWrap = node.style?.textWrap ?? 'wrap';const wrappedText = wrapText(text, width, textWrap);- return measureText(wrappedText);-};-const findClosestYogaNode = (node) => {- if (!node?.parentNode) {- return undefined;- }- return node.yogaNode ?? findClosestYogaNode(node.parentNode);+ const wrappedDimensions = measureText(wrappedText);+ // Reserve the truncation width so rendering does not truncate again at a narrower width when a wide character leaves an unused column.+ return textWrap.startsWith('truncate')+ ? { width, height: wrappedDimensions.height }+ : wrappedDimensions;};+const findClosestYogaNode = (node) => node?.parentNode+ ? (node.yogaNode ?? findClosestYogaNode(node.parentNode))+ : undefined;const markNodeAsDirty = (node) => {// Mark closest Yoga node as dirty to measure text dimensions againconst yogaNode = findClosestYogaNode(node);yogaNode?.markDirty();};+export const setNodeHidden = (node, isHidden) => {+ node.isHidden = isHidden;+ node.yogaNode?.setDisplay(isHidden || node.style.display === 'none'+ ? Yoga.DISPLAY_NONE+ : Yoga.DISPLAY_FLEX);+ if (node.nodeName === 'ink-virtual-text') {+ markNodeAsDirty(node);+ }+};export const setTextNodeValue = (node, text) => {if (typeof text !== 'string') {+ // eslint-disable-next-line unicorn/no-useless-coercion -- Runtime guard for callers that pass non-string values despite the type.text = String(text);}node.nodeValue = text;markNodeAsDirty(node);};+export const addLayoutListener = (rootNode, listener) => {+ if (rootNode.nodeName !== 'ink-root') {+ return () => { };+ }+ rootNode.internal_layoutListeners ??= new Set();+ rootNode.internal_layoutListeners.add(listener);+ return () => {+ rootNode.internal_layoutListeners?.delete(listener);+ };+};+export const emitLayoutListeners = (rootNode) => {+ if (rootNode.nodeName !== 'ink-root' || !rootNode.internal_layoutListeners) {+ return;+ }+ for (const listener of rootNode.internal_layoutListeners) {+ listener();+ }+};diff --git a/vendor/ink/build/experimental/apply-style.js b/vendor/ink/build/experimental/apply-style.jsdeleted file mode 100644index 59507521..00000000--- a/vendor/ink/build/experimental/apply-style.js+++ /dev/null@@ -1,140 +0,0 @@-"use strict";--Object.defineProperty(exports, "__esModule", {- value: true-});-exports.default = void 0;--var _yogaLayoutPrebuilt = _interopRequireDefault(require("yoga-layout-prebuilt"));--function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }--const applyPositionStyles = (node, style) => {- if (!style.position) {- node.setPositionType(NaN);- }-- if (style.position === 'absolute') {- node.setPositionType(_yogaLayoutPrebuilt.default.POSITION_TYPE_ABSOLUTE);- }-};--const applyMarginStyles = (node, style) => {- node.setMargin(_yogaLayoutPrebuilt.default.EDGE_START, style.marginLeft || style.marginX || style.margin || 0);- node.setMargin(_yogaLayoutPrebuilt.default.EDGE_END, style.marginRight || style.marginX || style.margin || 0);- node.setMargin(_yogaLayoutPrebuilt.default.EDGE_TOP, style.marginTop || style.marginY || style.margin || 0);- node.setMargin(_yogaLayoutPrebuilt.default.EDGE_BOTTOM, style.marginBottom || style.marginY || style.margin || 0);-};--const applyPaddingStyles = (node, style) => {- node.setPadding(_yogaLayoutPrebuilt.default.EDGE_LEFT, style.paddingLeft || style.paddingX || style.padding || 0);- node.setPadding(_yogaLayoutPrebuilt.default.EDGE_RIGHT, style.paddingRight || style.paddingX || style.padding || 0);- node.setPadding(_yogaLayoutPrebuilt.default.EDGE_TOP, style.paddingTop || style.paddingY || style.padding || 0);- node.setPadding(_yogaLayoutPrebuilt.default.EDGE_BOTTOM, style.paddingBottom || style.paddingY || style.padding || 0);-};--const applyFlexStyles = (node, style) => {- node.setFlexGrow(style.flexGrow || 0);- node.setFlexShrink(typeof style.flexShrink === 'number' ? style.flexShrink : 1);-- if (style.flexDirection === 'row') {- node.setFlexDirection(_yogaLayoutPrebuilt.default.FLEX_DIRECTION_ROW);- }-- if (style.flexDirection === 'row-reverse') {- node.setFlexDirection(_yogaLayoutPrebuilt.default.FLEX_DIRECTION_ROW_REVERSE);- }-- if (style.flexDirection === 'column') {- node.setFlexDirection(_yogaLayoutPrebuilt.default.FLEX_DIRECTION_COLUMN);- }-- if (style.flexDirection === 'column-reverse') {- node.setFlexDirection(_yogaLayoutPrebuilt.default.FLEX_DIRECTION_COLUMN_REVERSE);- }-- if (typeof style.flexBasis === 'number') {- node.setFlexBasis(style.flexBasis);- } else if (typeof style.flexBasis === 'string') {- node.setFlexBasisPercent(parseInt(style.flexBasis, 10));- } else {- // This should be replaced with node.setFlexBasisAuto() when new Yoga release is out- node.setFlexBasis(NaN);- }-- if (style.alignItems === 'stretch' || !style.alignItems) {- node.setAlignItems(_yogaLayoutPrebuilt.default.ALIGN_STRETCH);- }-- if (style.alignItems === 'flex-start') {- node.setAlignItems(_yogaLayoutPrebuilt.default.ALIGN_FLEX_START);- }-- if (style.alignItems === 'center') {- node.setAlignItems(_yogaLayoutPrebuilt.default.ALIGN_CENTER);- }-- if (style.alignItems === 'flex-end') {- node.setAlignItems(_yogaLayoutPrebuilt.default.ALIGN_FLEX_END);- }-- if (style.justifyContent === 'flex-start' || !style.justifyContent) {- node.setJustifyContent(_yogaLayoutPrebuilt.default.JUSTIFY_FLEX_START);- }-- if (style.justifyContent === 'center') {- node.setJustifyContent(_yogaLayoutPrebuilt.default.JUSTIFY_CENTER);- }-- if (style.justifyContent === 'flex-end') {- node.setJustifyContent(_yogaLayoutPrebuilt.default.JUSTIFY_FLEX_END);- }-- if (style.justifyContent === 'space-between') {- node.setJustifyContent(_yogaLayoutPrebuilt.default.JUSTIFY_SPACE_BETWEEN);- }-- if (style.justifyContent === 'space-around') {- node.setJustifyContent(_yogaLayoutPrebuilt.default.JUSTIFY_SPACE_AROUND);- }-};--const applyDimensionStyles = (node, style) => {- if (typeof style.width === 'number') {- node.setWidth(style.width);- } else if (typeof style.width === 'string') {- node.setWidthPercent(parseInt(style.width, 10));- } else {- node.setWidthAuto();- }-- if (typeof style.height === 'number') {- node.setHeight(style.height);- } else if (typeof style.height === 'string') {- node.setHeightPercent(parseInt(style.height, 10));- } else {- node.setHeightAuto();- }-- if (typeof style.minWidth === 'string') {- node.setMinWidthPercent(parseInt(style.minWidth, 10));- } else {- node.setMinWidth(style.minWidth || 0);- }-- if (typeof style.minHeight === 'string') {- node.setMinHeightPercent(parseInt(style.minHeight, 10));- } else {- node.setMinHeight(style.minHeight || 0);- }-};--var _default = (node, style = {}) => {- applyPositionStyles(node, style);- applyMarginStyles(node, style);- applyPaddingStyles(node, style);- applyFlexStyles(node, style);- applyDimensionStyles(node, style);-};--exports.default = _default;\ No newline at end of filediff --git a/vendor/ink/build/experimental/dom.js b/vendor/ink/build/experimental/dom.jsdeleted file mode 100644index 5bfe0bc1..00000000--- a/vendor/ink/build/experimental/dom.js+++ /dev/null@@ -1,123 +0,0 @@-"use strict";--Object.defineProperty(exports, "__esModule", {- value: true-});-exports.setTextContent = exports.createTextNode = exports.setAttribute = exports.setStyle = exports.removeChildNode = exports.insertBeforeNode = exports.appendChildNode = exports.createNode = void 0;--var _yogaLayoutPrebuilt = _interopRequireDefault(require("yoga-layout-prebuilt"));--var _measureText = _interopRequireDefault(require("../measure-text"));--var _applyStyle = _interopRequireDefault(require("./apply-style"));--function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }--// Helper utilities implementing some common DOM methods to simplify reconciliation code-const createNode = tagName => ({- nodeName: tagName.toUpperCase(),- style: {},- attributes: {},- childNodes: [],- parentNode: null,- textContent: null,- yogaNode: _yogaLayoutPrebuilt.default.Node.create()-});--exports.createNode = createNode;--const appendChildNode = (node, childNode) => {- if (childNode.parentNode) {- removeChildNode(childNode.parentNode, childNode);- }-- childNode.parentNode = node;- node.childNodes.push(childNode);- node.yogaNode.insertChild(childNode.yogaNode, node.yogaNode.getChildCount());-};--exports.appendChildNode = appendChildNode;--const insertBeforeNode = (node, newChildNode, beforeChildNode) => {- if (newChildNode.parentNode) {- removeChildNode(newChildNode.parentNode, newChildNode);- }-- newChildNode.parentNode = node;- const index = node.childNodes.indexOf(beforeChildNode);-- if (index >= 0) {- node.childNodes.splice(index, 0, newChildNode);- node.yogaNode.insertChild(newChildNode.yogaNode, index);- return;- }-- node.childNodes.push(newChildNode);- node.yogaNode.insertChild(newChildNode.yogaNode, node.yogaNode.getChildCount());-};--exports.insertBeforeNode = insertBeforeNode;--const removeChildNode = (node, removeNode) => {- removeNode.parentNode.yogaNode.removeChild(removeNode.yogaNode);- removeNode.parentNode = null;- const index = node.childNodes.indexOf(removeNode);-- if (index >= 0) {- node.childNodes.splice(index, 1);- }-};--exports.removeChildNode = removeChildNode;--const setStyle = (node, style) => {- node.style = style;- (0, _applyStyle.default)(node.yogaNode, style);-};--exports.setStyle = setStyle;--const setAttribute = (node, key, value) => {- node.attributes[key] = value;-};--exports.setAttribute = setAttribute;--const createTextNode = text => {- const node = {- nodeName: '#text',- nodeValue: text,- yogaNode: _yogaLayoutPrebuilt.default.Node.create()- };- setTextContent(node, text);- return node;-};--exports.createTextNode = createTextNode;--const setTextContent = (node, text) => {- if (typeof text !== 'string') {- text = String(text);- }-- let width = 0;- let height = 0;-- if (text.length > 0) {- const dimensions = (0, _measureText.default)(text);- width = dimensions.width;- height = dimensions.height;- }-- if (node.nodeName === '#text') {- node.nodeValue = text;- node.yogaNode.setWidth(width);- node.yogaNode.setHeight(height);- } else {- node.textContent = text;- node.yogaNode.setWidth(node.style.width || width);- node.yogaNode.setHeight(node.style.height || height);- }-};--exports.setTextContent = setTextContent;\ No newline at end of filediff --git a/vendor/ink/build/experimental/output.js b/vendor/ink/build/experimental/output.jsdeleted file mode 100644index 52354b04..00000000--- a/vendor/ink/build/experimental/output.js+++ /dev/null@@ -1,91 +0,0 @@-"use strict";--Object.defineProperty(exports, "__esModule", {- value: true-});-exports.default = void 0;--var _stringLength = _interopRequireDefault(require("string-length"));--var _sliceAnsi = _interopRequireDefault(require("slice-ansi"));--function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }--/**- * "Virtual" output class- *- * Handles the positioning and saving of the output of each node in the tree.- * Also responsible for applying transformations to each character of the output.- *- * Used to generate the final output of all nodes before writing it to actual output stream (e.g. stdout)- */-class Output {- constructor({- width,- height- }) {- this.width = width;- this.height = height;- this.writes = []; // Initialize output array with a specific set of rows, so that margin/padding at the bottom is preserved- }-- write(x, y, text, {- transformers- }) {- if (!text) {- return;- }-- this.writes.push({- x,- y,- text,- transformers- });- }-- get() {- const output = [];-- for (let y = 0; y < this.height; y++) {- output.push(' '.repeat(this.width));- }-- for (const write of this.writes) {- const {- x,- y,- text,- transformers- } = write;- const lines = text.split('\n');- let offsetY = 0;-- for (let line of lines) {- const currentLine = output[y + offsetY]; // Line can be missing if `text` is taller than height of pre-initialized `this.output`-- if (!currentLine) {- continue;- }-- const length = (0, _stringLength.default)(line);-- for (const transformer of transformers) {- line = transformer(line);- }-- output[y + offsetY] = (0, _sliceAnsi.default)(currentLine, 0, x) + line + (0, _sliceAnsi.default)(currentLine, x + length);- offsetY++;- }- }-- const generatedOutput = output.map(line => line.trimRight()).join('\n');- return {- output: generatedOutput,- height: output.length- };- }--}--exports.default = Output;\ No newline at end of filediff --git a/vendor/ink/build/experimental/reconciler.js b/vendor/ink/build/experimental/reconciler.jsdeleted file mode 100644index d6580b69..00000000--- a/vendor/ink/build/experimental/reconciler.js+++ /dev/null@@ -1,141 +0,0 @@-"use strict";--Object.defineProperty(exports, "__esModule", {- value: true-});-exports.default = void 0;--var _scheduler = require("scheduler");--var _reactReconciler = _interopRequireDefault(require("react-reconciler"));--var _dom = require("./dom");--function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }--const NO_CONTEXT = true;-const hostConfig = {- schedulePassiveEffects: _scheduler.unstable_scheduleCallback,- cancelPassiveEffects: _scheduler.unstable_cancelCallback,- now: Date.now,- getRootHostContext: () => NO_CONTEXT,- prepareForCommit: () => {},- resetAfterCommit: rootNode => {- // Since renders are throttled at the instance level and <Static> component children- // are rendered only once and then get deleted, we need an escape hatch to- // trigger an immediate render to ensure <Static> children are written to output before they get erased- if (rootNode.isStaticDirty) {- rootNode.isStaticDirty = false;- rootNode.onImmediateRender();- return;- }-- rootNode.onRender();- },- getChildHostContext: () => NO_CONTEXT,- shouldSetTextContent: (type, props) => {- return typeof props.children === 'string' || typeof props.children === 'number';- },- createInstance: (type, newProps) => {- const node = (0, _dom.createNode)(type);-- for (const [key, value] of Object.entries(newProps)) {- if (key === 'children') {- if (typeof value === 'string' || typeof value === 'number') {- if (type === 'div') {- // Text node must be wrapped in another node, so that text can be aligned within container- const textNode = (0, _dom.createNode)('div');- (0, _dom.setTextContent)(textNode, value);- (0, _dom.appendChildNode)(node, textNode);- }-- if (type === 'span') {- (0, _dom.setTextContent)(node, value);- }- }- } else if (key === 'style') {- (0, _dom.setStyle)(node, value);- } else if (key === 'unstable__transformChildren') {- node.unstable__transformChildren = value; // eslint-disable-line camelcase- } else if (key === 'unstable__static') {- node.unstable__static = true; // eslint-disable-line camelcase- } else {- (0, _dom.setAttribute)(node, key, value);- }- }-- return node;- },- createTextInstance: _dom.createTextNode,- resetTextContent: node => {- if (node.textContent) {- node.textContent = '';- }-- if (node.childNodes.length > 0) {- for (const childNode of node.childNodes) {- (0, _dom.removeChildNode)(node, childNode);- }- }- },- getPublicInstance: instance => instance,- appendInitialChild: _dom.appendChildNode,- appendChild: _dom.appendChildNode,- insertBefore: _dom.insertBeforeNode,- finalizeInitialChildren: (node, type, props, rootNode) => {- if (node.unstable__static) {- rootNode.isStaticDirty = true;- }- },- supportsMutation: true,- appendChildToContainer: _dom.appendChildNode,- insertInContainerBefore: _dom.insertBeforeNode,- removeChildFromContainer: _dom.removeChildNode,- prepareUpdate: (node, type, oldProps, newProps, rootNode) => {- if (node.unstable__static) {- rootNode.isStaticDirty = true;- }-- return true;- },- commitUpdate: (node, updatePayload, type, oldProps, newProps) => {- for (const [key, value] of Object.entries(newProps)) {- if (key === 'children') {- if (typeof value === 'string' || typeof value === 'number') {- if (type === 'div') {- // Text node must be wrapped in another node, so that text can be aligned within container- // If there's no such node, a new one must be created- if (node.childNodes.length === 0) {- const textNode = (0, _dom.createNode)('div');- (0, _dom.setTextContent)(textNode, value);- (0, _dom.appendChildNode)(node, textNode);- } else {- (0, _dom.setTextContent)(node.childNodes[0], value);- }- }-- if (type === 'span') {- (0, _dom.setTextContent)(node, value);- }- }- } else if (key === 'style') {- (0, _dom.setStyle)(node, value);- } else if (key === 'unstable__transformChildren') {- node.unstable__transformChildren = value; // eslint-disable-line camelcase- } else if (key === 'unstable__static') {- node.unstable__static = true; // eslint-disable-line camelcase- } else {- (0, _dom.setAttribute)(node, key, value);- }- }- },- commitTextUpdate: (node, oldText, newText) => {- (0, _dom.setTextContent)(node, newText);- },- removeChild: _dom.removeChildNode-};--var _default = (0, _reactReconciler.default)(hostConfig); // eslint-disable-line new-cap---exports.default = _default;\ No newline at end of filediff --git a/vendor/ink/build/experimental/renderer.js b/vendor/ink/build/experimental/renderer.jsdeleted file mode 100644index 7b57ec72..00000000--- a/vendor/ink/build/experimental/renderer.js+++ /dev/null@@ -1,81 +0,0 @@-"use strict";--Object.defineProperty(exports, "__esModule", {- value: true-});-exports.default = void 0;--var _yogaLayoutPrebuilt = _interopRequireDefault(require("yoga-layout-prebuilt"));--var _renderNodeToOutput = _interopRequireDefault(require("../render-node-to-output"));--var _calculateWrappedText = _interopRequireDefault(require("../calculate-wrapped-text"));--var _output = _interopRequireDefault(require("./output"));--var _dom = require("./dom");--function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }--// Since <Static> components can be placed anywhere in the tree, this helper finds and returns them-const findStaticNode = node => {- if (node.unstable__static) {- return node;- }-- for (const childNode of node.childNodes) {- if (childNode.unstable__static) {- return childNode;- }-- if (Array.isArray(childNode.childNodes) && childNode.childNodes.length > 0) {- return findStaticNode(childNode);- }- }-};--var _default = ({- terminalWidth = 100-}) => {- return node => {- (0, _dom.setStyle)(node, {- width: terminalWidth- });- node.yogaNode.calculateLayout(_yogaLayoutPrebuilt.default.UNDEFINED, _yogaLayoutPrebuilt.default.UNDEFINED, _yogaLayoutPrebuilt.default.DIRECTION_LTR);- (0, _calculateWrappedText.default)(node);- node.yogaNode.calculateLayout(_yogaLayoutPrebuilt.default.UNDEFINED, _yogaLayoutPrebuilt.default.UNDEFINED, _yogaLayoutPrebuilt.default.DIRECTION_LTR);- const output = new _output.default({- width: node.yogaNode.getComputedWidth(),- height: node.yogaNode.getComputedHeight()- });- (0, _renderNodeToOutput.default)(node, output, {- skipStaticElements: true- });- const staticNode = findStaticNode(node);- let staticOutput;-- if (staticNode) {- staticOutput = new _output.default({- width: staticNode.yogaNode.getComputedWidth(),- height: staticNode.yogaNode.getComputedHeight()- });- (0, _renderNodeToOutput.default)(staticNode, staticOutput, {- skipStaticElements: false- });- }-- const {- output: generatedOutput,- height: outputHeight- } = output.get();- return {- output: generatedOutput,- outputHeight,- // Newline at the end is needed, because static output doesn't have one, so- // interactive output will override last line of static output- staticOutput: staticOutput ? `${staticOutput.get().output}\n` : undefined- };- };-};--exports.default = _default;\ No newline at end of filediff --git a/vendor/ink/build/get-max-width.js b/vendor/ink/build/get-max-width.jsindex c10fbdc6..26cd0bb1 100644--- a/vendor/ink/build/get-max-width.js+++ b/vendor/ink/build/get-max-width.js@@ -1,9 +1,7 @@import Yoga from 'yoga-layout';-const getMaxWidth = (yogaNode) => {- return (yogaNode.getComputedWidth() -- yogaNode.getComputedPadding(Yoga.EDGE_LEFT) -- yogaNode.getComputedPadding(Yoga.EDGE_RIGHT) -- yogaNode.getComputedBorder(Yoga.EDGE_LEFT) -- yogaNode.getComputedBorder(Yoga.EDGE_RIGHT));-};+const getMaxWidth = (yogaNode) => yogaNode.getComputedWidth() -+ yogaNode.getComputedPadding(Yoga.EDGE_LEFT) -+ yogaNode.getComputedPadding(Yoga.EDGE_RIGHT) -+ yogaNode.getComputedBorder(Yoga.EDGE_LEFT) -+ yogaNode.getComputedBorder(Yoga.EDGE_RIGHT);export default getMaxWidth;diff --git a/vendor/ink/build/hooks/use-animation.d.ts b/vendor/ink/build/hooks/use-animation.d.tsnew file mode 100644index 00000000..36be9d12--- /dev/null+++ b/vendor/ink/build/hooks/use-animation.d.ts@@ -0,0 +1,49 @@+type Options = {+ /**+ Time between ticks in milliseconds.++ @default 100+ */+ readonly interval?: number;+ /**+ Whether the animation is running. When set to `false`, the animation stops. When toggled back to `true`, all values reset to `0`.++ @default true+ */+ readonly isActive?: boolean;+};+export type AnimationResult = {+ /**+ Discrete counter that increments by 1 each interval. Useful for indexed sequences like spinner frames.+ */+ readonly frame: number;+ /**+ Total elapsed time in milliseconds since the animation started or was last reset. Useful for continuous math-based animations like sine waves: `Math.sin(time / 1000 * Math.PI * 2)`.+ */+ readonly time: number;+ /**+ Time in milliseconds since the previous rendered tick. Accounts for throttled renders. Useful for physics-based or velocity-driven motion: `position += speed * delta`.+ */+ readonly delta: number;+ /**+ Resets `frame`, `time`, and `delta` to `0` and restarts timing from the current moment. Useful for one-shot animations triggered by events.+ */+ readonly reset: () => void;+};+/**+A React hook that drives animations. Returns a frame counter, elapsed time, frame delta, and a reset function. All animations share a single timer internally, so multiple animated components consolidate into one render cycle.++@example+```+import {Text, useAnimation} from 'ink';++const Spinner = () => {+ const {frame} = useAnimation({interval: 80});+ const characters = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];++ return <Text>{characters[frame % characters.length]}</Text>;+};+```+*/+export default function useAnimation(options?: Options): AnimationResult;+export {};diff --git a/vendor/ink/build/hooks/use-animation.js b/vendor/ink/build/hooks/use-animation.jsnew file mode 100644index 00000000..3c6ccbac--- /dev/null+++ b/vendor/ink/build/hooks/use-animation.js@@ -0,0 +1,83 @@+import { useState, useLayoutEffect, useRef, useCallback, use } from 'react';+import AnimationContext from '../components/AnimationContext.js';+const defaultAnimationInterval = 100;+const maximumTimerInterval = 2_147_483_647;+const zeroAnimState = { frame: 0, time: 0, delta: 0 };+/**+A React hook that drives animations. Returns a frame counter, elapsed time, frame delta, and a reset function. All animations share a single timer internally, so multiple animated components consolidate into one render cycle.++@example+```+import {Text, useAnimation} from 'ink';++const Spinner = () => {+ const {frame} = useAnimation({interval: 80});+ const characters = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];++ return <Text>{characters[frame % characters.length]}</Text>;+};+```+*/+export default function useAnimation(options) {+ const { interval = defaultAnimationInterval, isActive = true } = options ?? {};+ const safeInterval = normalizeAnimationInterval(interval);+ const { subscribe, renderThrottleMs } = use(AnimationContext);+ const [resetKey, setResetKey] = useState(0);+ const [animState, setAnimState] = useState(zeroAnimState);+ const nextRenderTimeRef = useRef(0);+ const lastRenderTimeRef = useRef(0);+ const previousOptionsRef = useRef({ isActive, safeInterval, resetKey });+ const previousOptions = previousOptionsRef.current;+ const shouldReset = isActive &&+ (safeInterval !== previousOptions.safeInterval ||+ !previousOptions.isActive ||+ resetKey !== previousOptions.resetKey);+ const reset = useCallback(() => {+ setAnimState(zeroAnimState);+ setResetKey(k => k + 1);+ }, []);+ useLayoutEffect(() => {+ if (!isActive) {+ return;+ }+ // Reset to zero immediately so any render that occurs between this+ // effect commit and the first tick shows zeros, not stale values.+ // On initial mount this is a no-op: Object.is bails out because the+ // state was initialized with the same zeroAnimState reference.+ setAnimState(zeroAnimState);+ let startTime = 0;+ const { startTime: subscriberStartTime, unsubscribe } = subscribe(currentTime => {+ const isThrottled = renderThrottleMs > 0 && currentTime < nextRenderTimeRef.current;+ if (isThrottled) {+ // Coalesce intermediate ticks while Ink is inside the current+ // render-throttle window; the next allowed render will jump+ // straight to the latest elapsed values.+ return;+ }+ const elapsed = currentTime - startTime;+ const nextDelta = currentTime - lastRenderTimeRef.current;+ lastRenderTimeRef.current = currentTime;+ nextRenderTimeRef.current = currentTime + renderThrottleMs;+ setAnimState({+ frame: Math.floor(elapsed / safeInterval),+ time: elapsed,+ delta: nextDelta,+ });+ }, safeInterval);+ // Use the scheduler's start time instead of sampling our own clock so the+ // first delivered tick cannot start one frame late.+ startTime = subscriberStartTime;+ lastRenderTimeRef.current = subscriberStartTime;+ nextRenderTimeRef.current = startTime + renderThrottleMs;+ return unsubscribe;+ }, [safeInterval, isActive, subscribe, renderThrottleMs, resetKey]);+ useLayoutEffect(() => {+ previousOptionsRef.current = { isActive, safeInterval, resetKey };+ }, [isActive, safeInterval, resetKey]);+ return shouldReset ? { ...zeroAnimState, reset } : { ...animState, reset };+}+function normalizeAnimationInterval(interval) {+ return Number.isFinite(interval)+ ? Math.min(maximumTimerInterval, Math.max(1, interval))+ : defaultAnimationInterval;+}diff --git a/vendor/ink/build/hooks/use-app.d.ts b/vendor/ink/build/hooks/use-app.d.tsindex d06fdfeb..bfcc1b24 100644--- a/vendor/ink/build/hooks/use-app.d.ts+++ b/vendor/ink/build/hooks/use-app.d.ts@@ -1,5 +1,4 @@/**- * `useApp` is a React hook, which exposes a method to manually exit the app (unmount).- */-declare const useApp: () => import("../components/AppContext.js").Props;-export default useApp;+A React hook that returns app lifecycle methods like `exit()` and `waitUntilRenderFlush()`.+*/+export default function useApp(): import("../components/AppContext.js").Props;diff --git a/vendor/ink/build/hooks/use-app.js b/vendor/ink/build/hooks/use-app.jsindex 2fcb94da..378fd788 100644--- a/vendor/ink/build/hooks/use-app.js+++ b/vendor/ink/build/hooks/use-app.js@@ -1,7 +1,8 @@-import { useContext } from 'react';+import { use } from 'react';import AppContext from '../components/AppContext.js';/**- * `useApp` is a React hook, which exposes a method to manually exit the app (unmount).- */-const useApp = () => useContext(AppContext);-export default useApp;+A React hook that returns app lifecycle methods like `exit()` and `waitUntilRenderFlush()`.+*/+export default function useApp() {+ return use(AppContext);+}diff --git a/vendor/ink/build/hooks/use-box-metrics.d.ts b/vendor/ink/build/hooks/use-box-metrics.d.tsnew file mode 100644index 00000000..984fa189--- /dev/null+++ b/vendor/ink/build/hooks/use-box-metrics.d.ts@@ -0,0 +1,67 @@+import { type RefObject } from 'react';+import { type DOMElement } from '../dom.js';+/**+Metrics of a box element.++All positions are relative to the element's parent.+*/+export type BoxMetrics = {+ /**+ Element width.+ */+ readonly width: number;+ /**+ Element height.+ */+ readonly height: number;+ /**+ Distance from the left edge of the parent. These are layout coordinates and do not include any `contentOffsetX`/`contentOffsetY` applied by an ancestor, so hit-testing inside a scrolled container has to subtract those offsets too.+ */+ readonly left: number;+ /**+ Distance from the top edge of the parent. These are layout coordinates and do not include any `contentOffsetX`/`contentOffsetY` applied by an ancestor, so hit-testing inside a scrolled container has to subtract those offsets too.+ */+ readonly top: number;+ /**+ Element width excluding borders.+ */+ readonly clientWidth: number;+ /**+ Element height excluding borders.+ */+ readonly clientHeight: number;+};+export type UseBoxMetricsResult = BoxMetrics & {+ /**+ Whether the currently tracked element has been measured in the latest layout pass.+ */+ readonly hasMeasured: boolean;+};+/**+A React hook that returns the current layout metrics for a tracked box element.+It updates when layout changes (for example terminal resize, sibling/content changes, or position changes).++The hook returns zeros for all metrics until the first layout pass completes. It also returns zeros when the tracked ref is detached.++Use `hasMeasured` to detect when the currently tracked element has been measured.++@example+```tsx+import {useRef} from 'react';+import {Box, Text, useBoxMetrics} from 'ink';++const Example = () => {+ const ref = useRef(null);+ const {width, height, left, top, hasMeasured} = useBoxMetrics(ref);+ return (+ <Box ref={ref}>+ <Text>+ {hasMeasured ? `${width}x${height} at ${left},${top}` : 'Measuring...'}+ </Text>+ </Box>+ );+};+```+*/+declare const useBoxMetrics: (ref: RefObject<DOMElement | null>) => UseBoxMetricsResult;+export default useBoxMetrics;diff --git a/vendor/ink/build/hooks/use-box-metrics.js b/vendor/ink/build/hooks/use-box-metrics.jsnew file mode 100644index 00000000..a29fb3cd--- /dev/null+++ b/vendor/ink/build/hooks/use-box-metrics.js@@ -0,0 +1,88 @@+import { useState, useEffect, useCallback, useMemo, use, } from 'react';+import { addLayoutListener } from '../dom.js';+import measureElement from '../measure-element.js';+import RootNodeContext from '../components/RootNodeContext.js';+const emptyMetrics = {+ width: 0,+ height: 0,+ left: 0,+ top: 0,+ clientWidth: 0,+ clientHeight: 0,+};+/**+A React hook that returns the current layout metrics for a tracked box element.+It updates when layout changes (for example terminal resize, sibling/content changes, or position changes).++The hook returns zeros for all metrics until the first layout pass completes. It also returns zeros when the tracked ref is detached.++Use `hasMeasured` to detect when the currently tracked element has been measured.++@example+```tsx+import {useRef} from 'react';+import {Box, Text, useBoxMetrics} from 'ink';++const Example = () => {+ const ref = useRef(null);+ const {width, height, left, top, hasMeasured} = useBoxMetrics(ref);+ return (+ <Box ref={ref}>+ <Text>+ {hasMeasured ? `${width}x${height} at ${left},${top}` : 'Measuring...'}+ </Text>+ </Box>+ );+};+```+*/+const useBoxMetrics = (+/* eslint-disable-next-line @typescript-eslint/no-restricted-types --+ Creating a ref object with an initial null, especially when the ref object+ will be passed to a DOM node's ref attribute, is common in React. */+ref) => {+ const rootNode = use(RootNodeContext);+ const [metrics, setMetrics] = useState(emptyMetrics);+ const [hasMeasured, setHasMeasured] = useState(false);+ const updateMetrics = useCallback(() => {+ const node = ref.current;+ const layout = node?.yogaNode?.getComputedLayout();+ // `measureElement()` also returns `x`/`y`, which aren't part of `BoxMetrics` and must not enter the change detection below.+ let nextMetrics = emptyMetrics;+ if (node && layout) {+ const { width, height, clientWidth, clientHeight } = measureElement(node);+ nextMetrics = {+ width,+ height,+ left: layout.left,+ top: layout.top,+ clientWidth,+ clientHeight,+ };+ }+ setMetrics(previousMetrics => {+ const hasChanged = Object.keys(nextMetrics).some(key => previousMetrics[key] !== nextMetrics[key]);+ return hasChanged ? nextMetrics : previousMetrics;+ });+ setHasMeasured(Boolean(node));+ }, [ref]);+ // Runs after every render of this component.+ // This keeps metrics fresh when local state/props in this subtree change.+ useEffect(updateMetrics);+ // Subscribe to root layout commits so memoized components still receive+ // sibling-driven position/size updates, even when they skip re-rendering.+ useEffect(() => {+ if (!rootNode) {+ return;+ }+ return addLayoutListener(rootNode, () => {+ // React attaches refs after the layout notification, during the same commit.+ queueMicrotask(updateMetrics);+ });+ }, [rootNode, updateMetrics]);+ return useMemo(() => ({+ ...metrics,+ hasMeasured,+ }), [metrics, hasMeasured]);+};+export default useBoxMetrics;diff --git a/vendor/ink/build/hooks/use-cursor.d.ts b/vendor/ink/build/hooks/use-cursor.d.tsnew file mode 100644index 00000000..c97f99e1--- /dev/null+++ b/vendor/ink/build/hooks/use-cursor.d.ts@@ -0,0 +1,12 @@+import { type CursorPosition } from '../log-update.js';+/**+A React hook that returns methods to control the terminal cursor position.++Setting a cursor position makes the cursor visible at the specified coordinates (relative to the Ink output origin). This is useful for IME (Input Method Editor) support, where the composing character is displayed at the cursor location.++Pass `undefined` to hide the cursor.+*/+declare const useCursor: () => {+ setCursorPosition: (position: CursorPosition | undefined) => void;+};+export default useCursor;diff --git a/vendor/ink/build/hooks/use-cursor.js b/vendor/ink/build/hooks/use-cursor.jsnew file mode 100644index 00000000..bd83a377--- /dev/null+++ b/vendor/ink/build/hooks/use-cursor.js@@ -0,0 +1,28 @@+import { use, useRef, useCallback, useInsertionEffect } from 'react';+import CursorContext from '../components/CursorContext.js';+/**+A React hook that returns methods to control the terminal cursor position.++Setting a cursor position makes the cursor visible at the specified coordinates (relative to the Ink output origin). This is useful for IME (Input Method Editor) support, where the composing character is displayed at the cursor location.++Pass `undefined` to hide the cursor.+*/+const useCursor = () => {+ const context = use(CursorContext);+ const positionRef = useRef(undefined);+ const setCursorPosition = useCallback((position) => {+ positionRef.current = position;+ }, []);+ // Propagate cursor position to log-update only during commit phase.+ // useInsertionEffect runs before resetAfterCommit (which triggers onRender),+ // and does NOT run for abandoned concurrent renders (e.g. suspended components).+ // This prevents cursor state from leaking across render boundaries.+ useInsertionEffect(() => {+ context.setCursorPosition(positionRef.current);+ return () => {+ context.setCursorPosition(undefined);+ };+ });+ return { setCursorPosition };+};+export default useCursor;diff --git a/vendor/ink/build/hooks/use-focus-manager.d.ts b/vendor/ink/build/hooks/use-focus-manager.d.tsindex 17236a5f..0bd81fd7 100644--- a/vendor/ink/build/hooks/use-focus-manager.d.ts+++ b/vendor/ink/build/hooks/use-focus-manager.d.ts@@ -1,34 +1,43 @@import { type Props } from '../components/FocusContext.js';type Output = {/**- * Enable focus management for all components.- */+ Enable focus management for all components.+ */enableFocus: Props['enableFocus'];/**- * Disable focus management for all components. Currently active component (if there's one) will lose its focus.- */+ Disable focus management for all components. The currently active component (if there's one) will lose its focus.+ */disableFocus: Props['disableFocus'];/**- * Switch focus to the next focusable component.- * If there's no active component right now, focus will be given to the first focusable component.- * If active component is the last in the list of focusable components, focus will be switched to the first component.- */+ Switch focus to the next focusable component. If there's no active component right now, focus will be given to the first focusable component. If the active component is the last in the list of focusable components, focus will be switched to the first focusable component.+ */focusNext: Props['focusNext'];/**- * Switch focus to the previous focusable component.- * If there's no active component right now, focus will be given to the first focusable component.- * If active component is the first in the list of focusable components, focus will be switched to the last component.- */+ Switch focus to the previous focusable component. If there's no active component right now, focus will be given to the first focusable component. If the active component is the first in the list of focusable components, focus will be switched to the last focusable component.+ */focusPrevious: Props['focusPrevious'];/**- * Switch focus to the element with provided `id`.- * If there's no element with that `id`, focus will be given to the first focusable component.- */+ Switch focus to the element with provided `id`. If there's no element with that `id`, focus is not changed.+ */focus: Props['focus'];+ /**+ The ID of the currently focused component, or `undefined` if no component is focused.++ @example+ ```tsx+ import {Text, useFocusManager} from 'ink';++ const Example = () => {+ const {activeId} = useFocusManager();++ return <Text>Focused: {activeId ?? 'none'}</Text>;+ };+ ```+ */+ activeId: Props['activeId'];};/**- * This hook exposes methods to enable or disable focus management for all- * components or manually switch focus to next or previous components.- */+A React hook that returns methods to enable or disable focus management for all components or manually switch focus to the next or previous components.+*/declare const useFocusManager: () => Output;export default useFocusManager;diff --git a/vendor/ink/build/hooks/use-focus-manager.js b/vendor/ink/build/hooks/use-focus-manager.jsindex ac12e8ab..571b5555 100644--- a/vendor/ink/build/hooks/use-focus-manager.js+++ b/vendor/ink/build/hooks/use-focus-manager.js@@ -1,17 +1,17 @@-import { useContext } from 'react';+import { use } from 'react';import FocusContext from '../components/FocusContext.js';/**- * This hook exposes methods to enable or disable focus management for all- * components or manually switch focus to next or previous components.- */+A React hook that returns methods to enable or disable focus management for all components or manually switch focus to the next or previous components.+*/const useFocusManager = () => {- const focusContext = useContext(FocusContext);+ const focusContext = use(FocusContext);return {enableFocus: focusContext.enableFocus,disableFocus: focusContext.disableFocus,focusNext: focusContext.focusNext,focusPrevious: focusContext.focusPrevious,focus: focusContext.focus,+ activeId: focusContext.activeId,};};export default useFocusManager;diff --git a/vendor/ink/build/hooks/use-focus.d.ts b/vendor/ink/build/hooks/use-focus.d.tsindex 0e4e2285..3765ee0c 100644--- a/vendor/ink/build/hooks/use-focus.d.ts+++ b/vendor/ink/build/hooks/use-focus.d.ts@@ -1,34 +1,30 @@type Input = {/**- * Enable or disable this component's focus, while still maintaining its position in the list of focusable components.- */+ Enable or disable this component's focus, while still maintaining its position in the list of focusable components.+ */isActive?: boolean;/**- * Auto focus this component, if there's no active (focused) component right now.- */+ Auto-focus this component if there's no active (focused) component right now.+ */autoFocus?: boolean;/**- * Assign an ID to this component, so it can be programmatically focused with `focus(id)`.- */+ Assign an ID to this component, so it can be programmatically focused with `focus(id)`. The ID must be unique among focusable components.+ */id?: string;};type Output = {/**- * Determines whether this component is focused or not.- */+ Determines whether this component is focused.+ */isFocused: boolean;/**- * Allows focusing a specific element with the provided `id`.- */+ Allows focusing a specific element with the provided `id`.+ */focus: (id: string) => void;};/**- * Component that uses `useFocus` hook becomes "focusable" to Ink,- * so when user presses <kbd>Tab</kbd>, Ink will switch focus to this component.- * If there are multiple components that execute `useFocus` hook, focus will be- * given to them in the order that these components are rendered in.- * This hook returns an object with `isFocused` boolean property, which- * determines if this component is focused or not.- */+A React hook that returns focus state and focus controls for the current component.+A component that uses the `useFocus` hook becomes "focusable" to Ink, so when the user presses <kbd>Tab</kbd>, Ink will switch focus to this component. If there are multiple components that execute the `useFocus` hook, focus will be given to them in registration order. Reordering keyed components does not change their registration order.+*/declare const useFocus: ({ isActive, autoFocus, id: customId, }?: Input) => Output;export default useFocus;diff --git a/vendor/ink/build/hooks/use-focus.js b/vendor/ink/build/hooks/use-focus.jsindex 0f0e1b5a..238c8cd0 100644--- a/vendor/ink/build/hooks/use-focus.js+++ b/vendor/ink/build/hooks/use-focus.js@@ -1,34 +1,30 @@-import { useEffect, useContext, useMemo } from 'react';+import { useEffect, use, useId } from 'react';import FocusContext from '../components/FocusContext.js';import useStdin from './use-stdin.js';/**- * Component that uses `useFocus` hook becomes "focusable" to Ink,- * so when user presses <kbd>Tab</kbd>, Ink will switch focus to this component.- * If there are multiple components that execute `useFocus` hook, focus will be- * given to them in the order that these components are rendered in.- * This hook returns an object with `isFocused` boolean property, which- * determines if this component is focused or not.- */+A React hook that returns focus state and focus controls for the current component.+A component that uses the `useFocus` hook becomes "focusable" to Ink, so when the user presses <kbd>Tab</kbd>, Ink will switch focus to this component. If there are multiple components that execute the `useFocus` hook, focus will be given to them in registration order. Reordering keyed components does not change their registration order.+*/const useFocus = ({ isActive = true, autoFocus = false, id: customId, } = {}) => {const { isRawModeSupported, setRawMode } = useStdin();- const { activeId, add, remove, activate, deactivate, focus } = useContext(FocusContext);- const id = useMemo(() => {- return customId ?? Math.random().toString().slice(2, 7);- }, [customId]);+ const { activeId, add, remove, activate, deactivate, focus } = use(FocusContext);+ const generatedId = useId();+ const id = customId ?? generatedId;useEffect(() => {add(id, { autoFocus });return () => {remove(id);};- }, [id, autoFocus]);+ }, [id, autoFocus, add, remove]);useEffect(() => {+ // Reapply active state when autoFocus changes and re-registers this component.if (isActive) {activate(id);}else {deactivate(id);}- }, [isActive, id]);+ }, [isActive, id, autoFocus, activate, deactivate]);useEffect(() => {if (!isRawModeSupported || !isActive) {return;@@ -37,9 +33,9 @@ const useFocus = ({ isActive = true, autoFocus = false, id: customId, } = {}) =>return () => {setRawMode(false);};- }, [isActive]);+ }, [isActive, isRawModeSupported, setRawMode]);return {- isFocused: Boolean(id) && activeId === id,+ isFocused: activeId === id,focus,};};diff --git a/vendor/ink/build/hooks/use-input.d.ts b/vendor/ink/build/hooks/use-input.d.tsindex 47acf9ab..d8b949aa 100644--- a/vendor/ink/build/hooks/use-input.d.ts+++ b/vendor/ink/build/hooks/use-input.d.ts@@ -1,97 +1,132 @@/**- * Handy information about a key that was pressed.- */+Handy information about a key that was pressed.+*/export type Key = {/**- * Up arrow key was pressed.- */+ Up arrow key was pressed.+ */upArrow: boolean;/**- * Down arrow key was pressed.- */+ Down arrow key was pressed.+ */downArrow: boolean;/**- * Left arrow key was pressed.- */+ Left arrow key was pressed.+ */leftArrow: boolean;/**- * Right arrow key was pressed.- */+ Right arrow key was pressed.+ */rightArrow: boolean;/**- * Page Down key was pressed.- */+ Page Down key was pressed.+ */pageDown: boolean;/**- * Page Up key was pressed.- */+ Page Up key was pressed.+ */pageUp: boolean;/**- * Return (Enter) key was pressed.- */+ Home key was pressed.+ */+ home: boolean;+ /**+ End key was pressed.+ */+ end: boolean;+ /**+ Return (Enter) key was pressed.+ */return: boolean;/**- * Escape key was pressed.- */+ Escape key was pressed.+ */escape: boolean;/**- * Ctrl key was pressed.- */+ Ctrl key was pressed.+ */ctrl: boolean;/**- * Shift key was pressed.- */+ Shift key was pressed.+ */shift: boolean;/**- * Tab key was pressed.- */+ Tab key was pressed.+ */tab: boolean;/**- * Backspace key was pressed.- */+ Backspace key was pressed.+ */backspace: boolean;/**- * Delete key was pressed.- */+ Delete key was pressed.+ */delete: boolean;/**- * [Meta key](https://en.wikipedia.org/wiki/Meta_key) was pressed.- */+ [Meta key](https://en.wikipedia.org/wiki/Meta_key) was pressed.+ */meta: boolean;+ /**+ Super key (Cmd on Mac, Win on Windows) was pressed.++ Only available with kitty keyboard protocol.+ */+ super: boolean;+ /**+ Hyper key was pressed.++ Only available with kitty keyboard protocol.+ */+ hyper: boolean;+ /**+ Caps Lock is active.++ Only available with kitty keyboard protocol.+ */+ capsLock: boolean;+ /**+ Num Lock is active.++ Only available with kitty keyboard protocol.+ */+ numLock: boolean;+ /**+ Event type for key events.++ Only available with kitty keyboard protocol.+ */+ eventType?: 'press' | 'repeat' | 'release';};type Handler = (input: string, key: Key) => void;type Options = {/**- * Enable or disable capturing of user input.- * Useful when there are multiple useInput hooks used at once to avoid handling the same input several times.- *- * @default true- */+ Enable or disable capturing of user input. Useful when there are multiple `useInput` hooks used at once to avoid handling the same input several times.++ @default true+ */isActive?: boolean;};/**- * This hook is used for handling user input.- * It's a more convenient alternative to using `StdinContext` and listening to `data` events.- * The callback you pass to `useInput` is called for each character when user enters any input.- * However, if user pastes text and it's more than one character, the callback will be called only once and the whole string will be passed as `input`.- *- * ```- * import {useInput} from 'ink';- *- * const UserInput = () => {- * useInput((input, key) => {- * if (input === 'q') {- * // Exit program- * }- *- * if (key.leftArrow) {- * // Left arrow key pressed- * }- * });- *- * return …- * };- * ```- */+A React hook that returns `void` and handles user input.+It's a more convenient alternative to using `StdinContext` and listening for `data` events. The callback you pass to `useInput` is called for each character when the user enters any input. However, if the user pastes text and it's more than one character, the callback will be called only once, and the whole string will be passed as `input`.++```+import {useInput} from 'ink';++const UserInput = () => {+ useInput((input, key) => {+ if (input === 'q') {+ // Exit program+ }++ if (key.leftArrow) {+ // Left arrow key pressed+ }+ });++ return …+};+```+*/declare const useInput: (inputHandler: Handler, options?: Options) => void;export default useInput;diff --git a/vendor/ink/build/hooks/use-input.js b/vendor/ink/build/hooks/use-input.jsindex a92b0f4c..ec927794 100644--- a/vendor/ink/build/hooks/use-input.js+++ b/vendor/ink/build/hooks/use-input.js@@ -1,34 +1,32 @@-import { useEffect } from 'react';+import { useEffect, useEffectEvent } from 'react';import parseKeypress, { nonAlphanumericKeys } from '../parse-keypress.js';import reconciler from '../reconciler.js';-import useStdin from './use-stdin.js';+import { useStdinContext } from './use-stdin.js';/**- * This hook is used for handling user input.- * It's a more convenient alternative to using `StdinContext` and listening to `data` events.- * The callback you pass to `useInput` is called for each character when user enters any input.- * However, if user pastes text and it's more than one character, the callback will be called only once and the whole string will be passed as `input`.- *- * ```- * import {useInput} from 'ink';- *- * const UserInput = () => {- * useInput((input, key) => {- * if (input === 'q') {- * // Exit program- * }- *- * if (key.leftArrow) {- * // Left arrow key pressed- * }- * });- *- * return …- * };- * ```- */+A React hook that returns `void` and handles user input.+It's a more convenient alternative to using `StdinContext` and listening for `data` events. The callback you pass to `useInput` is called for each character when the user enters any input. However, if the user pastes text and it's more than one character, the callback will be called only once, and the whole string will be passed as `input`.++```+import {useInput} from 'ink';++const UserInput = () => {+ useInput((input, key) => {+ if (input === 'q') {+ // Exit program+ }++ if (key.leftArrow) {+ // Left arrow key pressed+ }+ });++ return …+};+```+*/const useInput = (inputHandler, options = {}) => {// eslint-disable-next-line @typescript-eslint/naming-convention- const { stdin, setRawMode, internal_exitOnCtrlC, internal_eventEmitter } = useStdin();+ const { setRawMode, internal_exitOnCtrlC, internal_eventEmitter } = useStdinContext();useEffect(() => {if (options.isActive === false) {return;@@ -38,58 +36,85 @@ const useInput = (inputHandler, options = {}) => {setRawMode(false);};}, [options.isActive, setRawMode]);+ const handleData = useEffectEvent((data) => {+ const keypress = parseKeypress(data);+ const key = {+ upArrow: keypress.name === 'up',+ downArrow: keypress.name === 'down',+ leftArrow: keypress.name === 'left',+ rightArrow: keypress.name === 'right',+ pageDown: keypress.name === 'pagedown',+ pageUp: keypress.name === 'pageup',+ home: keypress.name === 'home',+ end: keypress.name === 'end',+ return: keypress.name === 'return',+ escape: keypress.name === 'escape',+ ctrl: keypress.ctrl,+ shift: keypress.shift,+ tab: keypress.name === 'tab',+ backspace: keypress.name === 'backspace',+ delete: keypress.name === 'delete',+ meta: keypress.meta,+ // Kitty keyboard protocol modifiers+ super: keypress.super ?? false,+ hyper: keypress.hyper ?? false,+ capsLock: keypress.capsLock ?? false,+ numLock: keypress.numLock ?? false,+ eventType: keypress.eventType,+ };+ let input;+ if (keypress.isKittyProtocol) {+ // Use text-as-codepoints field for printable keys (needed when+ // reportAllKeysAsEscapeCodes flag is enabled), suppress non-printable+ // Functional and modifier keys do not produce text input.+ input = keypress.isPrintable ? (keypress.text ?? keypress.name) : '';+ }+ else if (keypress.ctrl) {+ // Keypress.name is guaranteed non-undefined by parseKeypress,+ // but guard defensively since a TypeError here would crash the+ // entire Ink app (see https://github.com/vadimdemedes/ink/issues/901).+ input = keypress.name === 'space' ? ' ' : (keypress.name ?? '');+ }+ else {+ input = keypress.sequence;+ }+ if (!keypress.isKittyProtocol &&+ nonAlphanumericKeys.includes(keypress.name)) {+ input = '';+ }+ // Strip escape prefix from broken/incomplete sequences that+ // parseKeypress did not fully resolve (e.g. a flushed "\u001B[").+ if (input.startsWith('\u{1B}')) {+ input = input.slice(1);+ }+ if (!keypress.isKittyProtocol &&+ input.length === 1 &&+ /[A-Z]/.test(input)) {+ key.shift = true;+ }+ // If app is supposed to exit on Ctrl+C, skip input listeners.+ if (internal_exitOnCtrlC &&+ keypress.name === 'c' &&+ key.ctrl &&+ keypress.eventType !== 'release') {+ return;+ }+ // Use discreteUpdates to assign DiscreteEventPriority to state+ // updates from keyboard input, ensuring they are processed at the+ // highest priority in concurrent mode.+ // @ts-expect-error Types require 5 arguments (fn, a, b, c, d) but only fn is needed at runtime.+ reconciler.discreteUpdates(() => {+ inputHandler(input, key);+ });+ });useEffect(() => {if (options.isActive === false) {return;}- const handleData = (data) => {- const keypress = parseKeypress(data);- const key = {- upArrow: keypress.name === 'up',- downArrow: keypress.name === 'down',- leftArrow: keypress.name === 'left',- rightArrow: keypress.name === 'right',- pageDown: keypress.name === 'pagedown',- pageUp: keypress.name === 'pageup',- return: keypress.name === 'return',- escape: keypress.name === 'escape',- ctrl: keypress.ctrl,- shift: keypress.shift,- tab: keypress.name === 'tab',- backspace: keypress.name === 'backspace',- delete: keypress.name === 'delete',- // `parseKeypress` parses \u001B\u001B[A (meta + up arrow) as meta = false- // but with option = true, so we need to take this into account here- // to avoid breaking changes in Ink.- // TODO(vadimdemedes): consider removing this in the next major version.- meta: keypress.meta || keypress.name === 'escape' || keypress.option,- };- let input = keypress.ctrl ? keypress.name : keypress.sequence;- if (nonAlphanumericKeys.includes(keypress.name)) {- input = '';- }- // Strip meta if it's still remaining after `parseKeypress`- // TODO(vadimdemedes): remove this in the next major version.- if (input.startsWith('\u001B')) {- input = input.slice(1);- }- if (input.length === 1 &&- typeof input[0] === 'string' &&- /[A-Z]/.test(input[0])) {- key.shift = true;- }- // If app is not supposed to exit on Ctrl+C, then let input listener handle it- if (!(input === 'c' && key.ctrl) || !internal_exitOnCtrlC) {- // @ts-expect-error TypeScript types for `batchedUpdates` require an argument, but React's codebase doesn't provide it and it works without it as exepected.- reconciler.batchedUpdates(() => {- inputHandler(input, key);- });- }- };- internal_eventEmitter?.on('input', handleData);+ internal_eventEmitter.on('input', handleData);return () => {- internal_eventEmitter?.removeListener('input', handleData);+ internal_eventEmitter.removeListener('input', handleData);};- }, [options.isActive, stdin, internal_exitOnCtrlC, inputHandler]);+ }, [options.isActive, internal_eventEmitter]);};export default useInput;diff --git a/vendor/ink/build/hooks/use-is-screen-reader-enabled.d.ts b/vendor/ink/build/hooks/use-is-screen-reader-enabled.d.tsnew file mode 100644index 00000000..ed931019--- /dev/null+++ b/vendor/ink/build/hooks/use-is-screen-reader-enabled.d.ts@@ -0,0 +1,6 @@+/**+A React hook that returns whether a screen reader is enabled.+This is useful when you want to render different output for screen readers.+*/+declare const useIsScreenReaderEnabled: () => boolean;+export default useIsScreenReaderEnabled;diff --git a/vendor/ink/build/hooks/use-is-screen-reader-enabled.js b/vendor/ink/build/hooks/use-is-screen-reader-enabled.jsnew file mode 100644index 00000000..fe5f8248--- /dev/null+++ b/vendor/ink/build/hooks/use-is-screen-reader-enabled.js@@ -0,0 +1,11 @@+import { use } from 'react';+import { AccessibilityContext } from '../components/AccessibilityContext.js';+/**+A React hook that returns whether a screen reader is enabled.+This is useful when you want to render different output for screen readers.+*/+const useIsScreenReaderEnabled = () => {+ const { isScreenReaderEnabled } = use(AccessibilityContext);+ return isScreenReaderEnabled;+};+export default useIsScreenReaderEnabled;diff --git a/vendor/ink/build/hooks/use-paste.d.ts b/vendor/ink/build/hooks/use-paste.d.tsnew file mode 100644index 00000000..294f95bf--- /dev/null+++ b/vendor/ink/build/hooks/use-paste.d.ts@@ -0,0 +1,35 @@+type Options = {+ /**+ Enable or disable the paste handler. Useful when multiple components use `usePaste` and only one should be active at a time.++ @default true+ */+ isActive?: boolean;+};+/**+A React hook that calls `handler` whenever the user pastes text in the terminal. Bracketed paste mode (`\x1b[?2004h`) is automatically enabled while the hook is active, so pasted text arrives as a single string rather than being misinterpreted as individual key presses.++`usePaste` and `useInput` can be used together in the same component. They operate on separate event channels, so paste content is never forwarded to `useInput` handlers when `usePaste` is active.++```+import {useInput, usePaste} from 'ink';++const MyInput = () => {+ useInput((input, key) => {+ // Only receives typed characters and key events, not pasted text.+ if (key.return) {+ // Submit+ }+ });++ usePaste((text) => {+ // Receives the full pasted string, including newlines.+ console.log('Pasted:', text);+ });++ return …+};+```+*/+declare const usePaste: (handler: (text: string) => void, options?: Options) => void;+export default usePaste;diff --git a/vendor/ink/build/hooks/use-paste.js b/vendor/ink/build/hooks/use-paste.jsnew file mode 100644index 00000000..feec8ec9--- /dev/null+++ b/vendor/ink/build/hooks/use-paste.js@@ -0,0 +1,61 @@+import { useEffect, useEffectEvent } from 'react';+import reconciler from '../reconciler.js';+import { useStdinContext } from './use-stdin.js';+/**+A React hook that calls `handler` whenever the user pastes text in the terminal. Bracketed paste mode (`\x1b[?2004h`) is automatically enabled while the hook is active, so pasted text arrives as a single string rather than being misinterpreted as individual key presses.++`usePaste` and `useInput` can be used together in the same component. They operate on separate event channels, so paste content is never forwarded to `useInput` handlers when `usePaste` is active.++```+import {useInput, usePaste} from 'ink';++const MyInput = () => {+ useInput((input, key) => {+ // Only receives typed characters and key events, not pasted text.+ if (key.return) {+ // Submit+ }+ });++ usePaste((text) => {+ // Receives the full pasted string, including newlines.+ console.log('Pasted:', text);+ });++ return …+};+```+*/+const usePaste = (handler, options = {}) => {+ // eslint-disable-next-line @typescript-eslint/naming-convention+ const { setRawMode, setBracketedPasteMode, internal_eventEmitter } = useStdinContext();+ useEffect(() => {+ if (options.isActive === false) {+ return;+ }+ setRawMode(true);+ setBracketedPasteMode(true);+ return () => {+ setRawMode(false);+ setBracketedPasteMode(false);+ };+ }, [options.isActive, setRawMode, setBracketedPasteMode]);+ const handlePaste = useEffectEvent((text) => {+ // Use discreteUpdates to assign DiscreteEventPriority to state+ // updates triggered by paste, matching the priority of useInput.+ // @ts-expect-error Types require 5 arguments (fn, a, b, c, d) but only fn is needed at runtime.+ reconciler.discreteUpdates(() => {+ handler(text);+ });+ });+ useEffect(() => {+ if (options.isActive === false) {+ return;+ }+ internal_eventEmitter.on('paste', handlePaste);+ return () => {+ internal_eventEmitter.removeListener('paste', handlePaste);+ };+ }, [options.isActive, internal_eventEmitter]);+};+export default usePaste;diff --git a/vendor/ink/build/hooks/use-stderr.d.ts b/vendor/ink/build/hooks/use-stderr.d.tsindex c034fb39..e5d6e5c2 100644--- a/vendor/ink/build/hooks/use-stderr.d.ts+++ b/vendor/ink/build/hooks/use-stderr.d.ts@@ -1,5 +1,4 @@/**- * `useStderr` is a React hook, which exposes stderr stream.- */-declare const useStderr: () => import("../components/StderrContext.js").Props;-export default useStderr;+A React hook that returns the stderr stream.+*/+export default function useStderr(): import("../components/StderrContext.js").Props;diff --git a/vendor/ink/build/hooks/use-stderr.js b/vendor/ink/build/hooks/use-stderr.jsindex a974153c..03c81a54 100644--- a/vendor/ink/build/hooks/use-stderr.js+++ b/vendor/ink/build/hooks/use-stderr.js@@ -1,7 +1,8 @@-import { useContext } from 'react';+import { use } from 'react';import StderrContext from '../components/StderrContext.js';/**- * `useStderr` is a React hook, which exposes stderr stream.- */-const useStderr = () => useContext(StderrContext);-export default useStderr;+A React hook that returns the stderr stream.+*/+export default function useStderr() {+ return use(StderrContext);+}diff --git a/vendor/ink/build/hooks/use-stdin.d.ts b/vendor/ink/build/hooks/use-stdin.d.tsindex 39c97f48..cace3122 100644--- a/vendor/ink/build/hooks/use-stdin.d.ts+++ b/vendor/ink/build/hooks/use-stdin.d.ts@@ -1,5 +1,7 @@+import { type PublicProps, type Props } from '../components/StdinContext.js';/**- * `useStdin` is a React hook, which exposes stdin stream.- */-declare const useStdin: () => import("../components/StdinContext.js").Props;+A React hook that returns the stdin stream and stdin-related utilities.+*/+declare const useStdin: () => PublicProps;+export declare const useStdinContext: () => Props;export default useStdin;diff --git a/vendor/ink/build/hooks/use-stdin.js b/vendor/ink/build/hooks/use-stdin.jsindex 861f6188..836b593c 100644--- a/vendor/ink/build/hooks/use-stdin.js+++ b/vendor/ink/build/hooks/use-stdin.js@@ -1,7 +1,8 @@-import { useContext } from 'react';+import { use } from 'react';import StdinContext from '../components/StdinContext.js';/**- * `useStdin` is a React hook, which exposes stdin stream.- */-const useStdin = () => useContext(StdinContext);+A React hook that returns the stdin stream and stdin-related utilities.+*/+const useStdin = () => use(StdinContext);+export const useStdinContext = () => use(StdinContext);export default useStdin;diff --git a/vendor/ink/build/hooks/use-stdout.d.ts b/vendor/ink/build/hooks/use-stdout.d.tsindex 40a27ffe..8263d437 100644--- a/vendor/ink/build/hooks/use-stdout.d.ts+++ b/vendor/ink/build/hooks/use-stdout.d.ts@@ -1,5 +1,4 @@/**- * `useStdout` is a React hook, which exposes stdout stream.- */-declare const useStdout: () => import("../components/StdoutContext.js").Props;-export default useStdout;+A React hook that returns the stdout stream where Ink renders your app.+*/+export default function useStdout(): import("../components/StdoutContext.js").Props;diff --git a/vendor/ink/build/hooks/use-stdout.js b/vendor/ink/build/hooks/use-stdout.jsindex a3d677aa..e7f79ba6 100644--- a/vendor/ink/build/hooks/use-stdout.js+++ b/vendor/ink/build/hooks/use-stdout.js@@ -1,7 +1,8 @@-import { useContext } from 'react';+import { use } from 'react';import StdoutContext from '../components/StdoutContext.js';/**- * `useStdout` is a React hook, which exposes stdout stream.- */-const useStdout = () => useContext(StdoutContext);-export default useStdout;+A React hook that returns the stdout stream where Ink renders your app.+*/+export default function useStdout() {+ return use(StdoutContext);+}diff --git a/vendor/ink/build/hooks/use-window-size.d.ts b/vendor/ink/build/hooks/use-window-size.d.tsnew file mode 100644index 00000000..41981e03--- /dev/null+++ b/vendor/ink/build/hooks/use-window-size.d.ts@@ -0,0 +1,18 @@+/**+Dimensions of the terminal window.+*/+export type WindowSize = {+ /**+ Number of columns (horizontal character cells).+ */+ readonly columns: number;+ /**+ Number of rows (vertical character cells).+ */+ readonly rows: number;+};+/**+A React hook that returns the current terminal window dimensions and re-renders the component whenever the terminal is resized.+*/+declare const useWindowSize: () => WindowSize;+export default useWindowSize;diff --git a/vendor/ink/build/hooks/use-window-size.js b/vendor/ink/build/hooks/use-window-size.jsnew file mode 100644index 00000000..1077eddb--- /dev/null+++ b/vendor/ink/build/hooks/use-window-size.js@@ -0,0 +1,22 @@+import { useState, useEffect } from 'react';+import { getWindowSize } from '../utils.js';+import useStdout from './use-stdout.js';+/**+A React hook that returns the current terminal window dimensions and re-renders the component whenever the terminal is resized.+*/+const useWindowSize = () => {+ const { stdout } = useStdout();+ const [size, setSize] = useState(() => getWindowSize(stdout));+ useEffect(() => {+ const onResize = () => {+ setSize(getWindowSize(stdout));+ };+ stdout.on('resize', onResize);+ onResize();+ return () => {+ stdout.off('resize', onResize);+ };+ }, [stdout]);+ return size;+};+export default useWindowSize;diff --git a/vendor/ink/build/hooks/useInput.js b/vendor/ink/build/hooks/useInput.jsdeleted file mode 100644index 3db41a7d..00000000--- a/vendor/ink/build/hooks/useInput.js+++ /dev/null@@ -1,38 +0,0 @@-"use strict";--Object.defineProperty(exports, "__esModule", {- value: true-});-exports.default = void 0;--var _react = require("react");--var _ = require("..");--var _default = inputHandler => {- const {- stdin,- setRawMode- } = (0, _react.useContext)(_.StdinContext);- (0, _react.useLayoutEffect)(() => {- setRawMode(true);- return () => setRawMode(false);- }, [setRawMode]);- (0, _react.useLayoutEffect)(() => {- const handleData = data => {- const input = String(data);- const meta = {- up: input === '\u001B[A',- down: input === '\u001B[B',- left: input === '\u001B[D',- right: input === '\u001B[C'- };- inputHandler(input, meta);- };-- stdin.on('data', handleData);- return () => stdin.off('data', handleData);- }, [stdin, inputHandler]);-};--exports.default = _default;\ No newline at end of filediff --git a/vendor/ink/build/index.d.ts b/vendor/ink/build/index.d.tsindex 198843d8..4319a0c1 100644--- a/vendor/ink/build/index.d.ts+++ b/vendor/ink/build/index.d.ts@@ -1,11 +1,13 @@export type { RenderOptions, Instance } from './render.js';export { default as render } from './render.js';+export type { RenderToStringOptions } from './render-to-string.js';+export { default as renderToString } from './render-to-string.js';export type { Props as BoxProps } from './components/Box.js';export { default as Box } from './components/Box.js';export type { Props as TextProps } from './components/Text.js';export { default as Text } from './components/Text.js';export type { Props as AppProps } from './components/AppContext.js';-export type { Props as StdinProps } from './components/StdinContext.js';+export type { PublicProps as StdinProps } from './components/StdinContext.js';export type { Props as StdoutProps } from './components/StdoutContext.js';export type { Props as StderrProps } from './components/StderrContext.js';export type { Props as StaticProps } from './components/Static.js';@@ -17,11 +19,25 @@ export { default as Newline } from './components/Newline.js';export { default as Spacer } from './components/Spacer.js';export type { Key } from './hooks/use-input.js';export { default as useInput } from './hooks/use-input.js';+export { default as usePaste } from './hooks/use-paste.js';+export type { SuspendTerminal, TerminalSuspension, } from './components/AppContext.js';export { default as useApp } from './hooks/use-app.js';export { default as useStdin } from './hooks/use-stdin.js';export { default as useStdout } from './hooks/use-stdout.js';export { default as useStderr } from './hooks/use-stderr.js';export { default as useFocus } from './hooks/use-focus.js';export { default as useFocusManager } from './hooks/use-focus-manager.js';+export { default as useIsScreenReaderEnabled } from './hooks/use-is-screen-reader-enabled.js';+export { default as useCursor } from './hooks/use-cursor.js';+export type { AnimationResult } from './hooks/use-animation.js';+export { default as useAnimation } from './hooks/use-animation.js';+export type { WindowSize } from './hooks/use-window-size.js';+export { default as useWindowSize } from './hooks/use-window-size.js';+export type { BoxMetrics, UseBoxMetricsResult } from './hooks/use-box-metrics.js';+export { default as useBoxMetrics } from './hooks/use-box-metrics.js';+export type { CursorPosition } from './log-update.js';export { default as measureElement } from './measure-element.js';+export type { ElementMetrics } from './measure-element.js';export type { DOMElement } from './dom.js';+export { kittyFlags, kittyModifiers } from './kitty-keyboard.js';+export type { KittyKeyboardOptions, KittyFlagName } from './kitty-keyboard.js';diff --git a/vendor/ink/build/index.js b/vendor/ink/build/index.jsindex dfc6b821..7ac0a47a 100644--- a/vendor/ink/build/index.js+++ b/vendor/ink/build/index.js@@ -1,4 +1,5 @@export { default as render } from './render.js';+export { default as renderToString } from './render-to-string.js';export { default as Box } from './components/Box.js';export { default as Text } from './components/Text.js';export { default as Static } from './components/Static.js';@@ -6,10 +7,17 @@ export { default as Transform } from './components/Transform.js';export { default as Newline } from './components/Newline.js';export { default as Spacer } from './components/Spacer.js';export { default as useInput } from './hooks/use-input.js';+export { default as usePaste } from './hooks/use-paste.js';export { default as useApp } from './hooks/use-app.js';export { default as useStdin } from './hooks/use-stdin.js';export { default as useStdout } from './hooks/use-stdout.js';export { default as useStderr } from './hooks/use-stderr.js';export { default as useFocus } from './hooks/use-focus.js';export { default as useFocusManager } from './hooks/use-focus-manager.js';+export { default as useIsScreenReaderEnabled } from './hooks/use-is-screen-reader-enabled.js';+export { default as useCursor } from './hooks/use-cursor.js';+export { default as useAnimation } from './hooks/use-animation.js';+export { default as useWindowSize } from './hooks/use-window-size.js';+export { default as useBoxMetrics } from './hooks/use-box-metrics.js';export { default as measureElement } from './measure-element.js';+export { kittyFlags, kittyModifiers } from './kitty-keyboard.js';diff --git a/vendor/ink/build/ink.d.ts b/vendor/ink/build/ink.d.tsindex 5e7e28bd..3aca51bd 100644--- a/vendor/ink/build/ink.d.ts+++ b/vendor/ink/build/ink.d.ts@@ -1,37 +1,152 @@import { type ReactNode } from 'react';+import { type CursorPosition } from './log-update.js';+import { type TerminalSuspension } from './components/AppContext.js';+import { type KittyKeyboardOptions } from './kitty-keyboard.js';+import { type OutputStream } from './stream.js';+export declare const homeAndEraseDown: string;+/**+Performance metrics for a render operation.+*/+export type RenderMetrics = {+ /**+ Time spent rendering in milliseconds.+ */+ renderTime: number;+};export type Options = {- stdout: NodeJS.WriteStream;- stdin: NodeJS.ReadStream;- stderr: NodeJS.WriteStream;+ stdout: OutputStream;+ stdin: NodeJS.ReadableStream;+ stderr: OutputStream;debug: boolean;exitOnCtrlC: boolean;patchConsole: boolean;- waitUntilExit?: () => Promise<void>;+ onRender?: (metrics: RenderMetrics) => void;+ isScreenReaderEnabled?: boolean;+ waitUntilExit?: () => Promise<unknown>;+ maxFps?: number;+ incrementalRendering?: boolean;+ /**+ Enable React Concurrent Rendering mode.++ When enabled:+ - Suspense boundaries work correctly with async data+ - `useTransition` and `useDeferredValue` are fully functional+ - Updates can be interrupted for higher priority work++ Note: Concurrent mode changes the timing of renders. Some tests may need to use `act()` to properly await updates. Reusing the same stdout across multiple `render()` calls without unmounting is unsupported. Call `unmount()` first if you need to change the rendering mode or create a fresh instance.++ @default false+ @experimental+ */+ concurrent?: boolean;+ kittyKeyboard?: KittyKeyboardOptions;+ /**+ Override automatic interactive mode detection.++ By default, Ink detects whether the environment is interactive based on CI detection (via [`is-in-ci`](https://github.com/sindresorhus/is-in-ci)) and `stdout.isTTY`. Most users should not need to set this.++ When non-interactive, Ink disables ANSI erase sequences, cursor manipulation, synchronized output, resize handling, and kitty keyboard auto-detection, writing only the final frame at unmount.++ Set to `false` to force non-interactive mode or `true` to force interactive mode when the automatic detection doesn't suit your use case.++ Note: Reusing the same stdout across multiple `render()` calls without unmounting is unsupported. Call `unmount()` first if you need to change this option or create a fresh instance.++ @default true (false if in CI or `stdout.isTTY` is falsy)++ @see {@link RenderOptions.interactive}+ */+ interactive?: boolean;+ /**+ Render the app in the terminal's alternate screen buffer. When enabled, the app renders on a separate screen, and the original terminal content is restored when the app exits. This is the same mechanism used by programs like vim, htop, and less.++ Note: The terminal's scrollback buffer is not available while in the alternate screen. This is standard terminal behavior; programs like vim use the alternate screen specifically to avoid polluting the user's scrollback history.++ Note: Ink intentionally treats alternate-screen teardown output as disposable. It does not preserve or replay teardown-time frames, hook writes, or `console.*` output after restoring the primary screen.++ Only works in interactive mode. Ignored when `interactive` is `false` or in a non-interactive environment (CI, piped stdout).++ Note: Reusing the same stdout across multiple `render()` calls without unmounting is unsupported. Call `unmount()` first if you need to change this option or create a fresh instance.++ @default false++ @see {@link RenderOptions.alternateScreen}+ */+ alternateScreen?: boolean;};export default class Ink {private readonly options;private readonly log;+ private cursorPosition;private readonly throttledLog;+ private readonly isScreenReaderEnabled;+ private readonly interactive;+ private readonly renderThrottleMs;+ private alternateScreen;private isUnmounted;+ private isUnmounting;private lastOutput;+ private lastOutputToRender;+ private lastOutputHeight;+ private lastTerminalWidth;+ private lastTerminalHeight;private readonly container;private readonly rootNode;private fullStaticOutput;- private exitPromise?;+ private hasRenderedStaticOutput;+ private readonly exitPromise;+ private exitResult;+ private beforeExitHandler?;private restoreConsole?;private readonly unsubscribeResize?;- constructor(options: Options);+ private readonly throttledOnRender?;+ private hasPendingThrottledRender;+ private kittyProtocolEnabled;+ private kittyFlags;+ private finishKittyDetection?;+ private nextRenderCommit?;+ private isSuspended;+ private pauseInput?;+ private resumeInput?;+ /**+ Whether this instance is using concurrent rendering mode.+ */+ readonly isConcurrent: boolean;resized: () => void;- resolveExitPromise: () => void;+ resolveExitPromise: (result?: unknown) => void;rejectExitPromise: (reason?: Error) => void;unsubscribeExit: () => void;+ handleAppExit: (errorOrResult?: unknown) => void;+ setCursorPosition: (position: CursorPosition | undefined) => void;+ handleKittyQueryResponse: () => void;+ restoreLastOutput: () => void;calculateLayout: () => void;+ handleStaticChange: () => void;onRender: () => void;+ constructor(options: Options);+ private renderFrame;+ private setAlternateScreen;+ private resolveInteractiveOption;+ private resolveAlternateScreenOption;+ private shouldSync;+ private writeBestEffort;+ private awaitExit;+ private hasPendingConcurrentWork;+ private awaitNextRender;+ private renderInteractiveFrame;+ private initKittyKeyboard;+ private confirmKittySupport;+ private enableKittyProtocol;+ private beginSuspend;+ private endSuspend;render(node: ReactNode): void;writeToStdout(data: string): void;writeToStderr(data: string): void;unmount(error?: Error | number | null): void;- waitUntilExit(): Promise<void>;+ waitUntilExit(): Promise<unknown>;+ waitUntilRenderFlush(): Promise<void>;clear(): void;patchConsole(): void;+ registerInputControl(pauseInput: () => void, resumeInput: () => void): void;+ suspendTerminal(callback: () => void | Promise<void>): Promise<void>;+ suspendTerminal(): Promise<TerminalSuspension>;}diff --git a/vendor/ink/build/ink.js b/vendor/ink/build/ink.jsindex 4fd2a7c1..6ee4d5ae 100644--- a/vendor/ink/build/ink.js+++ b/vendor/ink/build/ink.js@@ -6,275 +6,797 @@ import isInCi from 'is-in-ci';import autoBind from 'auto-bind';import signalExit from 'signal-exit';import patchConsole from 'patch-console';+import { LegacyRoot, ConcurrentRoot } from 'react-reconciler/constants.js';import Yoga from 'yoga-layout';+import wrapAnsi from 'wrap-ansi';+import { getWindowSize } from './utils.js';import reconciler from './reconciler.js';import render from './renderer.js';import * as dom from './dom.js';+import { hideCursorEscape, showCursorEscape } from './cursor-helpers.js';import logUpdate from './log-update.js';+import { bsu, esu, shouldSynchronize } from './write-synchronized.js';import instances from './instances.js';import App from './components/App.js';+import RootNodeContext from './components/RootNodeContext.js';+import { AccessibilityContext } from './components/AccessibilityContext.js';+import { resolveFlags, } from './kitty-keyboard.js';+import { isTty } from './stream.js';const noop = () => { };-// Freeze gate (Cosmic Stack patch): while frozen, onRender writes NOTHING-// and must not advance lastOutput / log-update's baseline — the resume frame-// must diff against the last frame actually on screen. `armed` lets exactly-// one frame through (the "⏸ frozen" hint) if its output contains `marker`.-// Exposed on globalThis so host code can reach it without a type-level-// import of this internal module.+// Freeze gate (Cosmic Stack patch): while frozen, onRender writes NOTHING and+// must not advance lastOutput or log-update's baseline, so the frame that+// ends the freeze diffs against what is really on screen. `armed` lets+// exactly one frame through (the "⏸ frozen" hint) if it contains `marker`.export const frameGate = { frozen: false, armed: false, marker: '' };globalThis.__mercuryFrameGate = frameGate;-// Hardware cursor (Cosmic Stack patch): ink hides the terminal cursor and-// leaves it below the live region, so IME preedit/candidate windows anchor-// in the wrong place and some terminals suppress IME entirely. A host marks-// its fake-cursor cell with the `internal_cursor` attribute (Mercury:-// src/ui/cursor-anchor.tsx); after every frame onRender finds that element-// in the live tree and log-update parks the real cursor on it. No marked-// element (non-input views) → the cursor stays hidden. `enabled: false`-// turns the feature off globally.+// Cursor anchor (Cosmic Stack patch): after every frame, the element marked+// with the `internal_cursor` attribute (Mercury's CursorCell) is located in+// the laid-out live tree and handed to ink's setCursorPosition, so the real+// terminal cursor (and with it IME preedit/candidate windows) sits on the+// input cell. `enabled: false` turns it off (MERCURY_HW_CURSOR=0).export const cursorAnchor = { enabled: true };globalThis.__mercuryCursorAnchor = cursorAnchor;// Patch manifest (Cosmic Stack): which hunks this build carries, and whether-// it is the vendored copy (stamped by scripts/vendor-ink.cjs) or an-// in-place node_modules edit.+// it is the vendored copy (stamped by scripts/vendor-ink.cjs).export const inkPatch = {vendored: true,- hunks: ['yoga-hygiene', 'static-item-key', 'freeze-gate', 'live-region-guard', 'diff-render', 'resize-invalidate', 'cursor-positioning', 'synchronized-output'],+ base: '[email protected]',+ hunks: ['static-item-key', 'freeze-gate', 'live-region-guard', 'cursor-anchor'],};globalThis.__mercuryInkPatch = inkPatch;-const sameCursor = (a, b) => (!a && !b) || (!!a && !!b && a.row === b.row && a.col === b.col);-// Depth-first search for the first element carrying a truthy-// `internal_cursor` attribute, accumulating Yoga offsets exactly like-// render-node-to-output does. <Static> subtrees and display:none subtrees-// are never part of the live frame and are skipped. Reading the DOM-// attribute (set in createInstance/commitUpdate) instead of a ref matters:-// refs attach in React's layout phase, AFTER resetAfterCommit has already-// rendered the frame, so a ref-based anchor would always lag one frame.+// Depth-first search for the first element with a truthy `internal_cursor`+// attribute, accumulating Yoga offsets like render-node-to-output does.+// <Static> and display:none subtrees are never part of the live frame. The+// DOM attribute is read instead of a ref because refs attach in React's+// layout phase, after the frame has already been rendered.const findCursorCell = (node, x, y) => {const yoga = node.yogaNode;- if (!yoga || node.internal_static || node.style?.display === 'none') return null;+ if (!yoga || node.internal_static || node.style?.display === 'none') return undefined;const nx = x + yoga.getComputedLeft();const ny = y + yoga.getComputedTop();- if (node.attributes?.internal_cursor) return { row: ny, col: nx };- if (!Array.isArray(node.childNodes)) return null;+ if (node.attributes?.internal_cursor) return { x: nx, y: ny };+ if (!Array.isArray(node.childNodes)) return undefined;for (const child of node.childNodes) {const hit = findCursorCell(child, nx, ny);if (hit) return hit;}- return null;+ return undefined;+};+const yieldImmediate = async () => new Promise(resolve => {+ setImmediate(resolve);+});+// Windows consoles scroll the buffer when the bottom-right cell is written,+// unlike xterm-like terminals which defer the wrap. That extra scroll+// desynchronizes the incremental erase used for frames that exactly fill the+// viewport, leaving stale copies of previous frames behind (#969). Keep the+// pre-7.0 behavior of fully clearing between fullscreen frames there.+const isWindowsConsole = process.platform === 'win32';+// Full-clear path (see `shouldClearTerminalForFrame`). It must clear only+// what is visible: `ansiEscapes.clearTerminal` emits CSI 3J, which erases the+// terminal's scrollback, and both it and `ansiEscapes.clearViewport` emit+// CSI 2J, which VS Code and Windows Terminal handle by pushing the viewport+// into scrollback first (#935). Exported so tests assert against the real+// sequence rather than a copy.+export const homeAndEraseDown = ansiEscapes.cursorTo(0, 0) + ansiEscapes.eraseDown;+const shouldClearTerminalForFrame = ({ isStdoutTty, viewportRows, previousViewportRows, previousOutputHeight, nextOutputHeight, isUnmounting, }) => {+ if (!isStdoutTty) {+ return false;+ }+ const wasFullscreen = previousOutputHeight >= viewportRows;+ const isFullscreen = nextOutputHeight >= viewportRows;+ if (isWindowsConsole && (wasFullscreen || isFullscreen)) {+ return true;+ }+ const hadPreviousFrame = previousOutputHeight > 0;+ const wasOverflowing = previousOutputHeight > viewportRows;+ const isOverflowing = nextOutputHeight > viewportRows;+ const isLeavingFullscreen = wasFullscreen && nextOutputHeight < viewportRows;+ const isViewportShrinking = viewportRows < previousViewportRows;+ const shouldClearOnUnmount = isUnmounting && wasFullscreen;+ return (+ // Overflowing frames still need full clear fallback.+ wasOverflowing ||+ (isOverflowing && hadPreviousFrame) ||+ // Clear when shrinking from fullscreen to non-fullscreen output.+ isLeavingFullscreen ||+ // A terminal that loses rows scrolls only as far as it must to keep the cursor on screen, so the frame is cut only when it fills the new viewport. Then the cursor-relative diff no longer lines up with what is on screen.+ (isViewportShrinking && wasFullscreen) ||+ // Preserve legacy unmount behavior for fullscreen frames: final teardown+ // render should clear once to avoid leaving a scrolled viewport state.+ shouldClearOnUnmount);+};+const isErrorInput = (value) => value instanceof Error ||+ Object.prototype.toString.call(value) === '[object Error]';+const getWritableStreamState = (stdout) => {+ const canWriteToStdout = !stdout.destroyed && !stdout.writableEnded && (stdout.writable ?? true);+ return {+ canWriteToStdout,+ };+};+const settleThrottle = (throttled, canWriteToStdout) => {+ if (throttled === undefined ||+ throttled === null ||+ typeof throttled.flush !== 'function') {+ return;+ }+ const throttledValue = throttled;+ if (canWriteToStdout) {+ throttledValue.flush();+ }+ else if (typeof throttledValue.cancel === 'function') {+ throttledValue.cancel();+ }};export default class Ink {options;log;+ cursorPosition;throttledLog;+ isScreenReaderEnabled;+ interactive;+ renderThrottleMs;+ alternateScreen;// Ignore last render after unmounting a tree to prevent empty output before exitisUnmounted;+ isUnmounting;lastOutput;+ lastOutputToRender;+ lastOutputHeight;+ lastTerminalWidth;+ lastTerminalHeight;container;rootNode;- // This variable is used only in debug mode to store full static output- // so that it's rerendered every time, not just new static parts, like in non-debug mode+ // Accumulated <Static> output. Only kept in debug mode, where every frame rewrites it, and on the alternate screen, where it has to be replayed on full clears because there is no scrollback to keep it in.fullStaticOutput;+ // Whether any <Static> output has been written. The final unmount render is skipped once it has, since rendering again would duplicate <Static> children on exit (#397).+ hasRenderedStaticOutput;exitPromise;+ exitResult;+ beforeExitHandler;restoreConsole;unsubscribeResize;+ throttledOnRender;+ hasPendingThrottledRender = false;+ kittyProtocolEnabled = false;+ kittyFlags;+ finishKittyDetection;+ nextRenderCommit;+ // Set while suspendTerminal() has handed the terminal to a child process.+ isSuspended = false;+ // Input pause/resume hooks registered by the App component, which owns raw+ // mode and bracketed paste state.+ pauseInput;+ resumeInput;+ /**+ Whether this instance is using concurrent rendering mode.+ */+ isConcurrent;+ resized = () => {+ const { columns: currentWidth, rows: currentHeight } = getWindowSize(this.options.stdout);+ // We clear the screen when decreasing terminal width to prevent duplicate overlapping re-renders. Decreasing the height with a cursor shown also drops the frame rows below the cursor, so erase what is left and render the frame again.+ if (currentWidth < this.lastTerminalWidth ||+ (currentHeight < this.lastTerminalHeight &&+ this.log.getCursorPosition() !== undefined)) {+ this.log.clear();+ this.lastOutput = '';+ this.lastOutputToRender = '';+ this.lastOutputHeight = 0;+ }+ this.calculateLayout();+ dom.emitLayoutListeners(this.rootNode);+ this.onRender();+ this.lastTerminalWidth = currentWidth;+ this.lastTerminalHeight = currentHeight;+ };+ resolveExitPromise = () => { };+ rejectExitPromise = () => { };+ unsubscribeExit = () => { };+ handleAppExit = (errorOrResult) => {+ if (this.isUnmounted || this.isUnmounting) {+ return;+ }+ if (isErrorInput(errorOrResult)) {+ this.unmount(errorOrResult);+ return;+ }+ this.exitResult = errorOrResult;+ this.unmount();+ };+ setCursorPosition = (position) => {+ this.cursorPosition = position;+ this.log.setCursorPosition(position);+ };+ // Must stay referentially stable across `render()` calls: it feeds into App's+ // `setRawMode` identity, so a new function per `rerender()` would make every+ // `useInput`/`usePaste` re-run its raw-mode effect and reset the input parser,+ // dropping keys and pastes that were still in flight.+ handleKittyQueryResponse = () => {+ this.finishKittyDetection?.(true);+ };+ restoreLastOutput = () => {+ if (!this.interactive) {+ return;+ }+ // Screen-reader frames bypass `log()`, so restore them the same way: write, then sync log-update, with no cursor hide or placement.+ if (this.isScreenReaderEnabled) {+ this.options.stdout.write(this.lastOutputToRender);+ this.log.setCursorPosition(undefined);+ this.log.sync(this.lastOutputToRender);+ return;+ }+ // Clear() resets log-update's cursor state, so replay the latest cursor intent+ // before restoring output after external stdout/stderr writes.+ this.log.setCursorPosition(this.cursorPosition);+ this.log(this.lastOutputToRender === ''+ ? this.lastOutput + '\n'+ : this.lastOutputToRender);+ };+ calculateLayout = () => {+ const { yogaNode } = this.rootNode;+ // Calling exit() from an effect unmounts synchronously, so React's teardown commit can land after the root Yoga node is freed. There is nothing left to lay out.+ if (!yogaNode) {+ return;+ }+ const terminalWidth = getWindowSize(this.options.stdout).columns;+ yogaNode.setWidth(terminalWidth);+ yogaNode.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);+ };+ // Resets the accumulated static output when the <Static> identity changes so stale items from a previous instance are not replayed on future rewrites.+ handleStaticChange = () => {+ this.fullStaticOutput = '';+ this.hasRenderedStaticOutput = false;+ };+ onRender = () => {+ this.hasPendingThrottledRender = false;+ if (this.isUnmounted) {+ return;+ }+ // While suspended, the terminal belongs to a child process. Discard queued+ // renders; resume() forces a full redraw once Ink reclaims the terminal.+ // Resolve any awaited render commit so callers don't hang during suspension.+ if (this.isSuspended) {+ if (this.nextRenderCommit) {+ this.nextRenderCommit.resolve();+ this.nextRenderCommit = undefined;+ }+ return;+ }+ if (this.nextRenderCommit) {+ this.nextRenderCommit.resolve();+ this.nextRenderCommit = undefined;+ }+ // After clear(), the recorded frame is no longer on screen, so forget it and draw the next frame even when unchanged. Keep it while unmounting, so clear() followed by unmount() leaves the terminal clean.+ if (this.lastOutputHeight === 0 &&+ this.lastOutput !== '' &&+ !this.isUnmounting) {+ this.lastOutputToRender = '';+ }+ const startTime = performance.now();+ let { output, outputHeight, staticOutput } = render(this.rootNode, this.isScreenReaderEnabled);+ // Freeze gate (Cosmic Stack patch): drop the frame entirely.+ if (frameGate.frozen && !(frameGate.armed && frameGate.marker && output.includes(frameGate.marker))) {+ return;+ }+ if (frameGate.armed) frameGate.armed = false;+ // Live-region guard (Cosmic Stack patch): a live frame as tall as the viewport is+ // written whole by stock ink, and on the primary screen every row+ // past the viewport scrolls into scrollback, so each repaint while+ // a reply streams stamps another copy of the live region into the+ // user's history. Keep the newest rows (input, status bar, the live+ // tail) and send the trimmed frame through the normal diff path.+ const liveHeightBeforeTrim = outputHeight;+ if (this.interactive && !this.alternateScreen && !this.isScreenReaderEnabled && !this.options.debug && this.options.stdout.isTTY) {+ const viewportRows = getWindowSize(this.options.stdout).rows;+ if (outputHeight >= viewportRows) {+ const maxLiveRows = Math.max(1, viewportRows - 1);+ output = output.split('\n').slice(-maxLiveRows).join('\n');+ outputHeight = maxLiveRows;+ }+ }+ // Cursor anchor (Cosmic Stack patch): resolved after the trim, so the+ // row is relative to the rows actually written. Only a CHANGE is+ // pushed: setCursorPosition marks the cursor dirty, and a dirty+ // cursor forces a rewrite of an otherwise unchanged frame.+ if (cursorAnchor.enabled && !this.isScreenReaderEnabled) {+ const cell = findCursorCell(this.rootNode, 0, 0);+ const row = cell ? cell.y - (liveHeightBeforeTrim - outputHeight) : -1;+ const next = cell && row >= 0 ? { x: cell.x, y: row } : undefined;+ if (next?.x !== this.cursorPosition?.x || next?.y !== this.cursorPosition?.y) {+ this.setCursorPosition(next);+ }+ }+ const renderTime = performance.now() - startTime;+ this.renderFrame(output, outputHeight, staticOutput);+ this.options.onRender?.({ renderTime });+ };constructor(options) {autoBind(this);this.options = options;this.rootNode = dom.createNode('ink-root');this.rootNode.onComputeLayout = this.calculateLayout;- this.rootNode.onRender = options.debug- ? this.onRender- : throttle(this.onRender, 32, {+ this.isScreenReaderEnabled =+ options.isScreenReaderEnabled ??+ process.env['INK_SCREEN_READER'] === 'true';+ // CI detection takes precedence: even a TTY stdout in CI defaults to non-interactive.+ // Using Boolean(isTTY) (rather than an 'in' guard) correctly handles piped streams+ // where the property is absent (e.g. `node app.js | cat`).+ this.interactive = this.resolveInteractiveOption(options.interactive);+ this.alternateScreen = false;+ const isUnthrottled = options.debug || this.isScreenReaderEnabled;+ const maxFps = options.maxFps ?? 30;+ // Treat non-positive maxFps as an internal fallback case, not a supported+ // "disable throttling" mode. Keep animation scheduling on a normal cadence+ // so future changes don't accidentally reintroduce zero-delay loops.+ const renderThrottleMs = maxFps > 0 ? Math.max(1, Math.ceil(1000 / maxFps)) : 0;+ this.renderThrottleMs = isUnthrottled ? 0 : renderThrottleMs;+ if (isUnthrottled) {+ this.rootNode.onRender = this.onRender;+ this.throttledOnRender = undefined;+ }+ else {+ const throttled = throttle(this.onRender, renderThrottleMs, {leading: true,trailing: true,});+ this.rootNode.onRender = () => {+ this.hasPendingThrottledRender = true;+ throttled();+ };+ this.throttledOnRender = throttled;+ }this.rootNode.onImmediateRender = this.onRender;- // Synchronized output (Cosmic Stack patch): same gate as upstream shouldSynchronize().- this.log = logUpdate.create(options.stdout, { synchronize: Boolean(options.stdout.isTTY) && !isInCi && !options.debug });- this.throttledLog = options.debug+ this.rootNode.onStaticChange = this.handleStaticChange;+ this.log = logUpdate.create(options.stdout, {+ incremental: options.incrementalRendering,+ });+ this.cursorPosition = undefined;+ this.throttledLog = isUnthrottled? this.log- : throttle(this.log, undefined, {+ : throttle((output) => {+ const shouldWrite = this.log.willRender(output);+ const shouldSync = this.shouldSync();+ if (shouldSync && shouldWrite) {+ this.options.stdout.write(bsu);+ }+ this.log(output);+ if (shouldSync && shouldWrite) {+ this.options.stdout.write(esu);+ }+ }, undefined, {leading: true,trailing: true,});// Ignore last render after unmounting a tree to prevent empty output before exitthis.isUnmounted = false;+ this.isUnmounting = false;+ // Store concurrent mode setting+ this.isConcurrent = options.concurrent ?? false;// Store last output to only rerender when neededthis.lastOutput = '';- // This variable is used only in debug mode to store full static output- // so that it's rerendered every time, not just new static parts, like in non-debug mode+ this.lastOutputToRender = '';+ this.lastOutputHeight = 0;+ const { columns, rows } = getWindowSize(this.options.stdout);+ this.lastTerminalWidth = columns;+ this.lastTerminalHeight = rows;this.fullStaticOutput = '';+ this.hasRenderedStaticOutput = false;+ // Use ConcurrentRoot for concurrent mode, LegacyRoot for legacy mode+ const rootTag = options.concurrent ? ConcurrentRoot : LegacyRoot;// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment- this.container = reconciler.createContainer(this.rootNode,- // Legacy mode- 0, null, false, null, 'id', () => { }, null);+ this.container = reconciler.createContainer(this.rootNode, rootTag, null, false, null, 'id', () => { }, () => { }, () => { }, () => { }, null);// Unmount when process exitsthis.unsubscribeExit = signalExit(this.unmount, { alwaysLast: false });+ this.setAlternateScreen(Boolean(options.alternateScreen));if (process.env['DEV'] === 'true') {- reconciler.injectIntoDevTools({- bundleType: 0,- // Reporting React DOM's version, not Ink's- // See https://github.com/facebook/react/issues/16666#issuecomment-532639905- version: '16.13.1',- rendererPackageName: 'ink',- });+ reconciler.injectIntoDevTools();}if (options.patchConsole) {this.patchConsole();}- if (!isInCi) {+ if (this.interactive) {options.stdout.on('resize', this.resized);this.unsubscribeResize = () => {options.stdout.off('resize', this.resized);};}+ this.initKittyKeyboard();+ this.exitPromise = new Promise((resolve, reject) => {+ this.resolveExitPromise = resolve;+ this.rejectExitPromise = reject;+ });+ // Prevent global unhandled-rejection crashes when app code exits with an+ // error but consumers never call waitUntilExit().+ void this.exitPromise.catch(noop);}- resized = () => {- // Resize baseline reset (Cosmic Stack patch): rows that re-wrapped on- // resize must be repainted even when their bytes did not change, so- // the diff-render baseline (ours and log-update's) is dropped first.- this.lastOutput = '';- if (typeof this.log.invalidate === 'function') this.log.invalidate();- this.calculateLayout();- this.onRender();- };- resolveExitPromise = () => { };- rejectExitPromise = () => { };- unsubscribeExit = () => { };- calculateLayout = () => {- // The 'columns' property can be undefined or 0 when not using a TTY.- // In that case we fall back to 80.- const terminalWidth = this.options.stdout.columns || 80;- this.rootNode.yogaNode.setWidth(terminalWidth);- this.rootNode.yogaNode.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);- };- // Hardware cursor (Cosmic Stack patch): absolute cell of the marked cursor- // element inside the live frame, or null when there is none, the feature- // is disabled, or the cell was trimmed away by the live-region guard.- lastCursor = null;- resolveCursor(trimmedRows) {- if (!cursorAnchor.enabled) return null;- const cell = findCursorCell(this.rootNode, 0, 0);- if (!cell) return null;- const row = cell.row - trimmedRows;- if (row < 0) return null;- return { row, col: cell.col };- }- onRender = () => {- if (this.isUnmounted) {- return;- }- let { output, outputHeight, staticOutput } = render(this.rootNode);- // Freeze gate (Cosmic Stack patch): drop the frame entirely — no- // write, and crucially NO advance of `lastOutput` or log-update's- // `previousOutput`/`previousLineCount` baseline, so the frame that- // ends the freeze diffs against what is actually on screen.- if (frameGate.frozen && !(frameGate.armed && frameGate.marker && output.includes(frameGate.marker))) {- return;- }- if (frameGate.armed) frameGate.armed = false;- // Live-region guard (Cosmic Stack patch): a live frame as tall as (or- // taller than) the terminal cannot go through log-update's cursor- // arithmetic, and stock ink's fallback is `clearTerminal +- // fullStaticOutput + output` — erasing the ENTIRE scrollback buffer- // and re-dumping every static byte ever printed, on EVERY frame. With- // a long transcript that is megabytes per frame: the scrollbar jumps- // to the top, the UI flickers, and native scrolling becomes- // impossible. Instead keep the frame bottom-anchored: trim to what- // fits (rows - 1) and let the normal diff path write it. Scrollback- // is never cleared, the transcript is never re-dumped, and the newest- // rows (live tail, input, status bar) stay visible.- const maxLiveRows = Math.max(1, (this.options.stdout.rows || 24) - 1);- const liveHeightBeforeTrim = outputHeight;- if (outputHeight >= (this.options.stdout.rows || 24)) {- // `output` is newline-terminated per row WITHOUT a trailing blank- // line (log-update appends its own), so split and re-join verbatim.- output = output.split('\n').slice(-maxLiveRows).join('\n');- outputHeight = maxLiveRows;- }- // Hardware cursor (Cosmic Stack patch): resolve AFTER the trim so the row- // is relative to the rows actually written.- const cursor = this.resolveCursor(liveHeightBeforeTrim - outputHeight);+ renderFrame(output, outputHeight, staticOutput) {// If <Static> output isn't empty, it means new children have been added to it- const hasStaticOutput = staticOutput && staticOutput !== '\n';+ const hasStaticOutput = staticOutput !== '';if (this.options.debug) {if (hasStaticOutput) {this.fullStaticOutput += staticOutput;+ this.hasRenderedStaticOutput = true;}+ this.lastOutput = output;+ this.lastOutputToRender = output;+ this.lastOutputHeight = outputHeight;this.options.stdout.write(this.fullStaticOutput + output);return;}- if (isInCi) {+ if (!this.interactive) {if (hasStaticOutput) {this.options.stdout.write(staticOutput);}this.lastOutput = output;+ this.lastOutputToRender = output + '\n';+ this.lastOutputHeight = outputHeight;+ return;+ }+ if (this.isScreenReaderEnabled) {+ const shouldSync = this.shouldSync();+ if (shouldSync) {+ this.options.stdout.write(bsu);+ }+ const terminalWidth = getWindowSize(this.options.stdout).columns;+ const wrappedOutput = wrapAnsi(output, terminalWidth, {+ trim: false,+ hard: true,+ });+ if (!hasStaticOutput && wrappedOutput === this.lastOutputToRender) {+ if (shouldSync) {+ this.options.stdout.write(esu);+ }+ return;+ }+ // Erase the main output before writing new static output or replacing the frame.+ // Log-update tracks the actual rows, including frames restored after external writes.+ this.log.clear();+ // After erasing, the last output is gone, so reset its height until the new frame is written.+ this.lastOutputHeight = 0;+ if (hasStaticOutput) {+ this.options.stdout.write(staticOutput);+ if (this.alternateScreen) {+ this.fullStaticOutput += staticOutput;+ }+ }+ this.options.stdout.write(wrappedOutput);+ this.lastOutput = output;+ this.lastOutputToRender = wrappedOutput;+ this.lastOutputHeight =+ wrappedOutput === '' ? 0 : wrappedOutput.split('\n').length;+ // Screen-reader output uses its own cursor placement.+ this.log.setCursorPosition(undefined);+ this.log.sync(wrappedOutput);+ if (shouldSync) {+ this.options.stdout.write(esu);+ }return;}if (hasStaticOutput) {- this.fullStaticOutput += staticOutput;+ this.hasRenderedStaticOutput = true;+ if (this.alternateScreen) {+ this.fullStaticOutput += staticOutput;+ }}- if (outputHeight >= this.options.stdout.rows) {- this.options.stdout.write(ansiEscapes.clearTerminal + this.fullStaticOutput + output);+ this.renderInteractiveFrame(output, outputHeight, hasStaticOutput ? staticOutput : '');+ }+ setAlternateScreen(isEnabled) {+ this.alternateScreen = this.resolveAlternateScreenOption(isEnabled, this.interactive);+ if (!this.alternateScreen) {+ return;+ }+ this.writeBestEffort(this.options.stdout, ansiEscapes.enterAlternativeScreen);+ this.writeBestEffort(this.options.stdout, hideCursorEscape);+ }+ resolveInteractiveOption(interactive) {+ return interactive ?? (!isInCi && Boolean(this.options.stdout.isTTY));+ }+ resolveAlternateScreenOption(alternateScreen, isInteractive) {+ return (Boolean(alternateScreen) &&+ isInteractive &&+ Boolean(this.options.stdout.isTTY));+ }+ shouldSync() {+ return shouldSynchronize(this.options.stdout, this.interactive);+ }+ // Best-effort write: streams may already be destroyed during shutdown.+ writeBestEffort(stream, data) {+ try {+ stream.write(data);+ }+ catch { }+ }+ // Waits for the exit promise to settle, suppressing any rejection.+ // Errors are surfaced via waitUntilExit() instead.+ async awaitExit() {+ try {+ await this.exitPromise;+ }+ catch { }+ }+ hasPendingConcurrentWork() {+ const concurrentContainer = this.container;+ return ((concurrentContainer.pendingLanes ?? 0) !== 0 &&+ concurrentContainer.callbackNode !== undefined &&+ concurrentContainer.callbackNode !== null);+ }+ async awaitNextRender() {+ this.nextRenderCommit ??= Promise.withResolvers();+ return this.nextRenderCommit.promise;+ }+ renderInteractiveFrame(output, outputHeight, staticOutput) {+ const hasStaticOutput = staticOutput !== '';+ const isStdoutTty = Boolean(this.options.stdout.isTTY);+ // Detect fullscreen: output fills or exceeds terminal height.+ // Only apply when writing to a real TTY — piped output always gets trailing newlines.+ const viewportRows = isStdoutTty+ ? getWindowSize(this.options.stdout).rows+ : 24;+ const isFullscreen = isStdoutTty && outputHeight >= viewportRows;+ const outputToRender = isFullscreen ? output : output + '\n';+ const previousViewportRows = this.lastTerminalHeight;+ const shouldClearTerminal = shouldClearTerminalForFrame({+ isStdoutTty,+ viewportRows,+ previousViewportRows,+ previousOutputHeight: this.lastOutputHeight,+ nextOutputHeight: outputHeight,+ isUnmounting: this.isUnmounting,+ });+ this.lastTerminalHeight = viewportRows;+ if (!shouldClearTerminal &&+ !hasStaticOutput &&+ outputToRender === this.lastOutputToRender &&+ !this.log.isCursorDirty()) {+ return;+ }+ // Keep the committed cursor position when its component skips rendering.+ this.log.setCursorPosition(this.cursorPosition);+ if (shouldClearTerminal) {+ const shouldSync = this.shouldSync();+ if (shouldSync) {+ this.options.stdout.write(bsu);+ }+ // On the primary screen, erase only the previous frame. Everything above it, whether <Static> output, console writes or the shell's own history, is left where the terminal put it, so nothing needs to be replayed there. Replaying `fullStaticOutput` used to restore what `clearTerminal` wiped; with scrollback preserved it only stamps another copy of every <Static> line into history on each full clear. New <Static> output from this frame is still written once, ahead of the frame.+ if (this.alternateScreen) {+ // The alternate screen has no scrollback, so whatever the full clear erases or an overflowing frame pushed off the top is gone for good. Replay the accumulated static output, which already includes this frame's new items, ahead of the frame.+ this.options.stdout.write(homeAndEraseDown + this.fullStaticOutput + outputToRender);+ }+ else if (this.lastOutputHeight >= viewportRows) {+ // The previous frame filled the viewport, so erasing the viewport erases exactly that frame. The absolute sequence also sidesteps the cursor-relative erase that Windows consoles desynchronize (#969).+ //+ // When the terminal just lost rows while a useCursor() position was active, the real cursor sat above the bottom of the output, so the terminal dropped the rows below it instead of scrolling and the absolute origin can land on rows above the frame that Ink does not own. Walk up from the committed cursor position to the frame's top row instead.+ let erasePrefix = homeAndEraseDown;+ const previousCursor = this.log.getCursorPosition();+ if (!isWindowsConsole &&+ previousCursor &&+ viewportRows < previousViewportRows) {+ erasePrefix =+ (previousCursor.y > 0+ ? ansiEscapes.cursorUp(previousCursor.y)+ : '') ++ ansiEscapes.cursorTo(0) ++ ansiEscapes.eraseDown;+ }+ this.options.stdout.write(erasePrefix + staticOutput + outputToRender);+ }+ else {+ // The previous frame only covers the bottom of the viewport. Erase those rows relative to the cursor and let the new frame scroll whatever sits above them into scrollback naturally.+ this.log.clear();+ this.options.stdout.write(staticOutput + outputToRender);+ }this.lastOutput = output;+ this.lastOutputToRender = outputToRender;+ this.lastOutputHeight = outputHeight;+ this.log.sync(outputToRender);+ if (shouldSync) {+ this.options.stdout.write(esu);+ }return;}// To ensure static output is cleanly rendered before main output, clear main output firstif (hasStaticOutput) {- this.synchronized(() => {- this.log.clear();- this.options.stdout.write(staticOutput);- this.log(output, cursor);- });+ const shouldSync = this.shouldSync();+ if (shouldSync) {+ this.options.stdout.write(bsu);+ }+ this.log.clear();+ this.options.stdout.write(staticOutput);+ this.log(outputToRender);+ if (shouldSync) {+ this.options.stdout.write(esu);+ }}- if (!hasStaticOutput && (output !== this.lastOutput || !sameCursor(cursor, this.lastCursor))) {- this.throttledLog(output, cursor);+ else {+ // ThrottledLog manages its own bsu/esu at actual write time+ this.throttledLog(outputToRender);}this.lastOutput = output;- this.lastCursor = cursor;- };- render(node) {- const tree = (React.createElement(App, { stdin: this.options.stdin, stdout: this.options.stdout, stderr: this.options.stderr, writeToStdout: this.writeToStdout, writeToStderr: this.writeToStderr, exitOnCtrlC: this.options.exitOnCtrlC, onExit: this.unmount }, node));- reconciler.updateContainer(tree, this.container, null, noop);+ this.lastOutputToRender = outputToRender;+ this.lastOutputHeight = outputHeight;+ }+ initKittyKeyboard() {+ // Protocol is opt-in: if kittyKeyboard is not specified, do nothing+ if (!this.options.kittyKeyboard) {+ return;+ }+ const options = this.options.kittyKeyboard;+ const mode = options.mode ?? 'auto';+ if (mode === 'disabled') {+ return;+ }+ const flags = options.flags ?? ['disambiguateEscapeCodes'];+ // 'enabled' force-enables the protocol as long as both streams are TTYs,+ // regardless of the interactive setting (e.g. even in CI).+ if (mode === 'enabled') {+ if (isTty(this.options.stdin) && this.options.stdout.isTTY) {+ this.enableKittyProtocol(flags);+ }+ return;+ }+ // Auto mode: require interactive + TTY+ if (!this.interactive ||+ !isTty(this.options.stdin) ||+ !this.options.stdout.isTTY) {+ return;+ }+ // Auto mode: query the terminal for kitty keyboard protocol support.+ // The CSI ? u query is safe to send to any terminal — unsupporting+ // terminals simply won't respond, and the 200ms timeout handles that.+ // This avoids maintaining a hardcoded whitelist of terminal names.+ this.confirmKittySupport(flags);+ }+ confirmKittySupport(flags) {+ // Consume responses through App's normal input pipeline so user input is never read twice.+ const finish = (isSupported) => {+ this.finishKittyDetection = undefined;+ clearTimeout(timer);+ if (isSupported && !this.isUnmounted) {+ this.enableKittyProtocol(flags);+ }+ };+ // Register before writing the query so immediate responses are not missed.+ const timer = setTimeout(() => {+ finish(false);+ }, 200);+ this.finishKittyDetection = finish;+ this.options.stdout.write('\u{1B}[?u');+ }+ enableKittyProtocol(flags) {+ this.options.stdout.write(`\u{1B}[>${resolveFlags(flags)}u`);+ this.kittyProtocolEnabled = true;+ // Remember the flags so suspendTerminal() can re-enable the same protocol+ // after a child process has had the terminal.+ this.kittyFlags = flags;}- // Synchronized output (Cosmic Stack patch): run several writes as ONE terminal update (DEC- // mode 2026), so a new transcript line and the redrawn live region- // appear together instead of erase → static → redraw.- synchronized(write) {- const log = this.log;- if (!log.synchronize) {- write();+ beginSuspend() {+ if (!this.interactive) {+ return;+ }+ if (this.isSuspended) {+ throw new Error('The terminal is already suspended. Resume the current suspension before suspending again.');+ }+ this.finishKittyDetection?.(false);+ this.isSuspended = true;+ if (!this.interactive || this.isUnmounted || this.isUnmounting) {return;}- this.options.stdout.write('\u001B[?2026h');- log.syncDepth++;try {- write();+ const { stdout } = this.options;+ const { canWriteToStdout } = getWritableStreamState(stdout);+ // Flush any pending render/log so the child starts from a settled screen.+ settleThrottle(this.throttledOnRender, canWriteToStdout);+ settleThrottle(this.throttledLog, canWriteToStdout);+ if (canWriteToStdout) {+ // Erase Ink's current frame, then show the cursor and re-arm the hide.+ // The forced redraw on resume hides the cursor again.+ this.log.clear();+ this.log.done();+ if (this.kittyProtocolEnabled) {+ this.writeBestEffort(this.options.stdout, '\u{1B}[<u');+ this.kittyProtocolEnabled = false;+ }+ if (this.alternateScreen) {+ this.writeBestEffort(this.options.stdout, ansiEscapes.exitAlternativeScreen);+ }+ }+ // Hand input back to the terminal (raw mode off, bracketed paste off).+ this.pauseInput?.();}- finally {- log.syncDepth--;- this.options.stdout.write('\u001B[?2026l');+ catch (error) {+ // If handing over the terminal fails partway, don't strand the app in a+ // suspended state with no way back. Best-effort reclaim input, clear the+ // flag, and rethrow so the caller sees the failure.+ this.isSuspended = false;+ try {+ this.resumeInput?.();+ }+ catch { }+ throw error;+ }+ }+ async endSuspend() {+ if (!this.isSuspended) {+ return;+ }+ this.isSuspended = false;+ if (!this.interactive || this.isUnmounted || this.isUnmounting) {+ return;+ }+ // Reclaim input only while the app still owns the terminal. After unmount, App cleanup has already restored raw mode, so resuming must not re-enable it.+ this.resumeInput?.();+ const { stdout } = this.options;+ const { canWriteToStdout } = getWritableStreamState(stdout);+ if (canWriteToStdout) {+ if (this.alternateScreen) {+ // Re-entering the alternate screen gives an empty buffer with no scrollback behind it, and the forced redraw below only carries new <Static> items. Replay the accumulated static output ahead of it, as the full-clear path does, so the rows the child process's turn erased come back. The debug redraw writes fullStaticOutput itself, so skip the replay there.+ this.writeBestEffort(this.options.stdout, ansiEscapes.enterAlternativeScreen ++ (this.options.debug ? '' : this.fullStaticOutput));+ }+ if (this.kittyFlags) {+ this.writeBestEffort(this.options.stdout, `\u{1B}[>${resolveFlags(this.kittyFlags)}u`);+ this.kittyProtocolEnabled = true;+ }+ }+ // Force a full redraw instead of diffing against the stale pre-suspension+ // frame, which the child process may have overwritten. A redraw failure here+ // is best-effort: it must not mask a callback error propagating through the+ // caller's finally block.+ this.lastOutput = '';+ this.lastOutputToRender = '';+ this.lastOutputHeight = 0;+ this.log.reset();+ try {+ this.calculateLayout();+ this.onRender();+ await this.waitUntilRenderFlush();+ }+ catch { }+ }+ render(node) {+ const tree = (React.createElement(AccessibilityContext, { value: { isScreenReaderEnabled: this.isScreenReaderEnabled } },+ React.createElement(App, { stdin: this.options.stdin, stdout: this.options.stdout, stderr: this.options.stderr, exitOnCtrlC: this.options.exitOnCtrlC, interactive: this.interactive, renderThrottleMs: this.renderThrottleMs, writeToStdout: this.writeToStdout, writeToStderr: this.writeToStderr, setCursorPosition: this.setCursorPosition, onExit: this.handleAppExit, onWaitUntilRenderFlush: this.waitUntilRenderFlush, onSuspendTerminal: this.suspendTerminal, onRegisterInputControl: this.registerInputControl, onKittyQueryResponse: this.handleKittyQueryResponse },+ React.createElement(RootNodeContext, { value: this.rootNode }, node))));+ if (this.options.concurrent) {+ // Concurrent mode: use updateContainer (async scheduling)+ reconciler.updateContainer(tree, this.container, null, noop);+ }+ else {+ // Legacy mode: use updateContainerSync + flushSyncWork (sync)+ reconciler.updateContainerSync(tree, this.container, null, noop);+ reconciler.flushSyncWork();}}writeToStdout(data) {- if (this.isUnmounted) {+ if (this.isUnmounted ||+ // While suspended, the terminal belongs to a child process. Don't erase or+ // repaint Ink's frame around console output; the forced redraw on resume+ // restores the screen.+ this.isSuspended) {return;}if (this.options.debug) {this.options.stdout.write(data + this.fullStaticOutput + this.lastOutput);return;}- if (isInCi) {+ if (!this.interactive) {this.options.stdout.write(data);return;}- this.synchronized(() => {- this.log.clear();- this.options.stdout.write(data);- this.log(this.lastOutput, this.lastCursor);- });+ const shouldSync = this.shouldSync();+ if (shouldSync) {+ this.options.stdout.write(bsu);+ }+ this.log.clear();+ this.options.stdout.write(data);+ this.restoreLastOutput();+ if (shouldSync) {+ this.options.stdout.write(esu);+ }}writeToStderr(data) {- if (this.isUnmounted) {+ if (this.isUnmounted ||+ // See writeToStdout: stay off the terminal while suspended.+ this.isSuspended) {return;}if (this.options.debug) {@@ -282,59 +804,194 @@ export default class Ink {this.options.stdout.write(this.fullStaticOutput + this.lastOutput);return;}- if (isInCi) {+ if (!this.interactive) {this.options.stderr.write(data);return;}- this.synchronized(() => {- this.log.clear();- this.options.stderr.write(data);- this.log(this.lastOutput, this.lastCursor);- });+ const shouldSync = this.shouldSync();+ if (shouldSync) {+ this.options.stdout.write(bsu);+ }+ this.log.clear();+ this.options.stderr.write(data);+ this.restoreLastOutput();+ if (shouldSync) {+ this.options.stdout.write(esu);+ }}- // eslint-disable-next-line @typescript-eslint/ban-types+ // eslint-disable-next-line @typescript-eslint/no-restricted-typesunmount(error) {- if (this.isUnmounted) {+ if (this.isUnmounted || this.isUnmounting) {return;}- this.calculateLayout();- this.onRender();+ this.isUnmounting = true;+ if (this.beforeExitHandler) {+ process.off('beforeExit', this.beforeExitHandler);+ this.beforeExitHandler = undefined;+ }+ const { stdout } = this.options;+ const { canWriteToStdout } = getWritableStreamState(stdout);+ // Clear any pending throttled render timer on unmount. When stdout is writable,+ // flush so the final frame is emitted; otherwise cancel to avoid delayed callbacks.+ settleThrottle(this.throttledOnRender, canWriteToStdout);+ if (canWriteToStdout) {+ // If throttling is enabled and there is already a pending render, flushing above+ // is sufficient. Also avoid calling onRender() again when static output already+ // exists, as that can duplicate <Static> children output on exit (see issue #397).+ const shouldRenderFinalFrame = !this.throttledOnRender ||+ (!this.hasPendingThrottledRender && !this.hasRenderedStaticOutput);+ if (shouldRenderFinalFrame) {+ this.calculateLayout();+ this.onRender();+ }+ }+ // Mark as unmounted after the final render but before stdout writes+ // that could re-enter exit() via synchronous write callbacks.+ this.isUnmounted = true;this.unsubscribeExit();+ // Flush any pending throttled log writes if possible, otherwise cancel to+ // prevent delayed callbacks from writing to a closed stream.+ settleThrottle(this.throttledLog, canWriteToStdout);if (typeof this.restoreConsole === 'function') {+ // Once unmount starts, Ink stops trying to manage teardown-time+ // console output. Restoring the native console before React cleanup keeps+ // unmount behavior simple and avoids special-case handling for custom+ // streams, fullscreen frames, and alternate-screen teardown.this.restoreConsole();}- if (typeof this.unsubscribeResize === 'function') {- this.unsubscribeResize();- }- // CIs don't handle erasing ansi escapes well, so it's better to- // only render last frame of non-static output- if (isInCi) {- this.options.stdout.write(this.lastOutput + '\n');- }- else if (!this.options.debug) {- this.log.done();- }- this.isUnmounted = true;- reconciler.updateContainer(null, this.container, null, noop);- instances.delete(this.options.stdout);- if (error instanceof Error) {- this.rejectExitPromise(error);+ const finishUnmount = () => {+ if (typeof this.unsubscribeResize === 'function') {+ this.unsubscribeResize();+ }+ // Cancel any in-progress auto-detection before checking protocol state+ this.finishKittyDetection?.(false);+ if (canWriteToStdout) {+ if (this.kittyProtocolEnabled) {+ this.writeBestEffort(this.options.stdout, '\u{1B}[<u');+ this.kittyProtocolEnabled = false;+ }+ if (this.interactive && !this.options.debug) {+ this.log.done();+ }+ // Alternate-screen content is disposable by design. We intentionally+ // leave it active until React cleanup finishes, then restore the+ // primary buffer without replaying prior frames, hook writes, or+ // diagnostics onto it. Trying to preserve teardown output across the+ // buffer switch adds fragile lifecycle-specific behavior, so Ink keeps+ // alternate-screen teardown intentionally simple and best-effort.+ if (this.alternateScreen) {+ this.writeBestEffort(this.options.stdout, ansiEscapes.exitAlternativeScreen);+ this.writeBestEffort(this.options.stdout, showCursorEscape);+ this.alternateScreen = false;+ }+ if (!this.interactive) {+ // Non-interactive environments don't handle erasing ansi escapes well.+ // In debug mode, each render already writes to stdout, so only a trailing+ // newline is needed. In non-debug mode, write the last frame now (it was+ // deferred during rendering).+ this.options.stdout.write(this.options.debug ? '\n' : this.lastOutput + '\n');+ }+ }+ this.kittyProtocolEnabled = false;+ instances.delete(this.options.stdout);+ // By the time this runs, React has torn down the tree and freed the child Yoga nodes, but the root node is Ink's own. Free it and drop the reference so any late access is a no-op rather than a use-after-free, as `freeYogaSubtree` does.+ this.rootNode.yogaNode?.free();+ this.rootNode.yogaNode = undefined;+ // Ensure all queued writes have been processed before resolving the+ // exit promise. Queue an empty write as a barrier — its callback fires+ // only after all prior writes complete.+ //+ // When called from signal-exit during process shutdown (error is a+ // number or null rather than undefined/Error), resolve synchronously+ // because the event loop is draining and async callbacks won't fire.+ const { exitResult } = this;+ const resolveOrReject = () => {+ if (isErrorInput(error)) {+ this.rejectExitPromise(error);+ }+ else {+ this.resolveExitPromise(exitResult);+ }+ };+ const isProcessExiting = error !== undefined && !isErrorInput(error);+ if (isProcessExiting) {+ resolveOrReject();+ }+ else if (canWriteToStdout) {+ this.options.stdout.write('', resolveOrReject);+ }+ else {+ setImmediate(resolveOrReject);+ }+ };+ const concurrentReconciler = reconciler;+ if (this.options.concurrent) {+ reconciler.updateContainerSync(null, this.container, null, noop);+ reconciler.flushSyncWork();+ concurrentReconciler.flushPassiveEffects?.();+ finishUnmount();}else {- this.resolveExitPromise();+ // Legacy mode: use updateContainerSync + flushSyncWork (sync)+ reconciler.updateContainerSync(null, this.container, null, noop);+ reconciler.flushSyncWork();+ finishUnmount();}}async waitUntilExit() {- this.exitPromise ||= new Promise((resolve, reject) => {- this.resolveExitPromise = resolve;- this.rejectExitPromise = reject;- });+ if (!this.isUnmounting && !this.beforeExitHandler) {+ this.beforeExitHandler = () => {+ this.unmount();+ };+ process.once('beforeExit', this.beforeExitHandler);+ }return this.exitPromise;}+ async waitUntilRenderFlush() {+ if (this.isUnmounted || this.isUnmounting) {+ await this.awaitExit();+ return;+ }+ // Yield to the macrotask queue so that React's scheduler has a chance to+ // fire passive effects and process any work they enqueued.+ await yieldImmediate();+ if (this.isUnmounted || this.isUnmounting) {+ await this.awaitExit();+ return;+ }+ // In concurrent mode, React's scheduler may still be mid-render after+ // the yield. Wait for the next render commit instead of polling.+ if (this.isConcurrent && this.hasPendingConcurrentWork()) {+ await Promise.race([this.awaitNextRender(), this.awaitExit()]);+ if (this.isUnmounted || this.isUnmounting) {+ this.nextRenderCommit = undefined;+ await this.awaitExit();+ return;+ }+ }+ reconciler.flushSyncWork();+ const { stdout } = this.options;+ const { canWriteToStdout } = getWritableStreamState(stdout);+ // Flush pending throttled render/log timers so their output is included in this wait.+ settleThrottle(this.throttledOnRender, canWriteToStdout);+ settleThrottle(this.throttledLog, canWriteToStdout);+ if (canWriteToStdout) {+ await new Promise(resolve => {+ this.options.stdout.write('', () => {+ resolve();+ });+ });+ return;+ }+ await yieldImmediate();+ }clear() {- if (!isInCi && !this.options.debug) {- this.log.clear();+ if (!this.interactive || this.options.debug) {+ return;}+ this.log.clear();+ // Keep lastOutput so that unmount's final onRender sees it as unchanged, but no rows remain on screen.+ this.lastOutputHeight = 0;}patchConsole() {if (this.options.debug) {@@ -344,7 +1001,7 @@ export default class Ink {if (stream === 'stdout') {this.writeToStdout(data);}- if (stream === 'stderr') {+ else if (stream === 'stderr') {const isReactMessage = data.startsWith('The above error occurred');if (!isReactMessage) {this.writeToStderr(data);@@ -352,4 +1009,29 @@ export default class Ink {}});}+ registerInputControl(pauseInput, resumeInput) {+ this.pauseInput = pauseInput;+ this.resumeInput = resumeInput;+ }+ async suspendTerminal(callback) {+ this.beginSuspend();+ if (callback) {+ try {+ await callback();+ }+ finally {+ await this.endSuspend();+ }+ return undefined;+ }+ let isResumed = false;+ const resume = async () => {+ if (isResumed) {+ return;+ }+ isResumed = true;+ await this.endSuspend();+ };+ return { resume, [Symbol.asyncDispose]: resume };+ }}diff --git a/vendor/ink/build/input-parser.d.ts b/vendor/ink/build/input-parser.d.tsnew file mode 100644index 00000000..b69ba49f--- /dev/null+++ b/vendor/ink/build/input-parser.d.ts@@ -0,0 +1,14 @@+export type InputEvent = string | {+ readonly paste: string;+};+/**+Whether `input` is exactly one complete CSI or SS3 sequence as the parser defines it, including legacy `ESC[[A`, rxvt `ESC[2$` and parameterized SS3 forms. Partial sequences (timeout-flushed) and plain escaped code points are not.+*/+export declare const isCompleteControlSequence: (input: string) => boolean;+export type InputParser = {+ push: (chunk: string) => InputEvent[];+ hasPendingEscape: () => boolean;+ flushPendingEscape: () => string | undefined;+ reset: () => void;+};+export declare const createInputParser: () => InputParser;diff --git a/vendor/ink/build/input-parser.js b/vendor/ink/build/input-parser.jsnew file mode 100644index 00000000..191dfac7--- /dev/null+++ b/vendor/ink/build/input-parser.js@@ -0,0 +1,201 @@+const escape = '\u{1B}';+const pasteStart = '\u{1B}[200~';+const pasteEnd = '\u{1B}[201~';+const isCsiParameterByte = (byte) => byte >= 0x30 && byte <= 0x3f;+const isCsiIntermediateByte = (byte) => byte >= 0x20 && byte <= 0x2f;+const isCsiFinalByte = (byte) => byte >= 0x40 && byte <= 0x7e;+const parseCsiSequence = (input, startIndex, prefixLength) => {+ const csiPayloadStart = startIndex + prefixLength + 1;+ let index = csiPayloadStart;+ for (; index < input.length; index++) {+ const byte = input.codePointAt(index);+ if (byte === undefined) {+ return 'pending';+ }+ // Preserve legacy terminal function-key sequences like ESC[[A and ESC[[5~.+ if (byte === 0x5b && index === csiPayloadStart) {+ continue;+ }+ // Shifted editing keys in rxvt end in $, which is normally a CSI intermediate byte.+ const isRxvtShiftKey = byte === 0x24 &&+ index === csiPayloadStart + 1 &&+ '235678'.includes(input[csiPayloadStart]);+ if (isRxvtShiftKey || isCsiFinalByte(byte)) {+ return {+ sequence: input.slice(startIndex, index + 1),+ nextIndex: index + 1,+ };+ }+ if (isCsiParameterByte(byte) || isCsiIntermediateByte(byte)) {+ continue;+ }+ return undefined;+ }+ return 'pending';+};+const parseSs3Sequence = (input, startIndex, prefixLength) => {+ let index = startIndex + prefixLength + 1;+ for (; index < input.length; index++) {+ const byte = input.codePointAt(index);+ if (isCsiFinalByte(byte)) {+ return {+ sequence: input.slice(startIndex, index + 1),+ nextIndex: index + 1,+ };+ }+ // Modified SS3 keys can include numeric parameters separated by semicolons.+ if (byte !== 0x3b && (byte < 0x30 || byte > 0x39)) {+ return undefined;+ }+ }+ return 'pending';+};+const parseControlSequence = (input, startIndex, prefixLength) => {+ const sequenceType = input[startIndex + prefixLength];+ if (sequenceType === undefined) {+ return 'pending';+ }+ if (sequenceType === '[') {+ return parseCsiSequence(input, startIndex, prefixLength);+ }+ return sequenceType === 'O'+ ? parseSs3Sequence(input, startIndex, prefixLength)+ : undefined;+};+/**+Whether `input` is exactly one complete CSI or SS3 sequence as the parser defines it, including legacy `ESC[[A`, rxvt `ESC[2$` and parameterized SS3 forms. Partial sequences (timeout-flushed) and plain escaped code points are not.+*/+export const isCompleteControlSequence = (input) => {+ if (!input.startsWith(escape)) {+ return false;+ }+ const prefixLength = input[1] === escape ? 2 : 1;+ const parsed = parseControlSequence(input, 0, prefixLength);+ return typeof parsed === 'object' && parsed.nextIndex === input.length;+};+const parseEscapedCodePoint = (input, escapeIndex) => {+ const nextCodePoint = input.codePointAt(escapeIndex + 1);+ const nextCodePointLength = nextCodePoint !== undefined && nextCodePoint > 0xff_ff ? 2 : 1;+ const nextIndex = escapeIndex + 1 + nextCodePointLength;+ return {+ sequence: input.slice(escapeIndex, nextIndex),+ nextIndex,+ };+};+const parseEscapeSequence = (input, escapeIndex) => {+ if (escapeIndex === input.length - 1) {+ return 'pending';+ }+ const next = input[escapeIndex + 1];+ if (next === escape) {+ if (escapeIndex + 2 >= input.length) {+ return 'pending';+ }+ const doubleEscapeSequence = parseControlSequence(input, escapeIndex, 2);+ if (doubleEscapeSequence === 'pending') {+ return 'pending';+ }+ if (doubleEscapeSequence) {+ return doubleEscapeSequence;+ }+ return {+ sequence: input.slice(escapeIndex, escapeIndex + 2),+ nextIndex: escapeIndex + 2,+ };+ }+ const controlSequence = parseControlSequence(input, escapeIndex, 1);+ return controlSequence === 'pending'+ ? 'pending'+ : (controlSequence ?? parseEscapedCodePoint(input, escapeIndex));+};+/**+Split a chunk of non-escape text so that backspace bytes (`0x7F` and `0x08`) and Ctrl+C (`0x03`) become individual events. Ctrl+C must be recognized even when buffered with ordinary text. When a user holds the backspace key, the terminal sends repeated bytes in a single stdin chunk. Without splitting, `parseKeypress` receives the multi-byte string and fails to recognize it as a key event, corrupting the input state.++Other control characters like `\r` and `\t` are NOT split because they can legitimately appear inside pasted text.+*/+const splitControlBytes = (text, events) => {+ let textSegmentStart = 0;+ for (let index = 0; index < text.length; index++) {+ const character = text[index];+ if (!['\u{7F}', '\u{8}', '\u{3}'].includes(character)) {+ continue;+ }+ if (index > textSegmentStart) {+ events.push(text.slice(textSegmentStart, index));+ }+ events.push(character);+ textSegmentStart = index + 1;+ }+ if (textSegmentStart < text.length) {+ events.push(text.slice(textSegmentStart));+ }+};+const parseKeypresses = (input) => {+ const events = [];+ let index = 0;+ const pendingFrom = (pendingStartIndex) => ({+ events,+ pending: input.slice(pendingStartIndex),+ });+ while (index < input.length) {+ const escapeIndex = input.indexOf(escape, index);+ if (escapeIndex === -1) {+ splitControlBytes(input.slice(index), events);+ return {+ events,+ pending: '',+ };+ }+ if (escapeIndex > index) {+ splitControlBytes(input.slice(index, escapeIndex), events);+ }+ const parsedEscapeSequence = parseEscapeSequence(input, escapeIndex);+ if (parsedEscapeSequence === 'pending') {+ return pendingFrom(escapeIndex);+ }+ if (parsedEscapeSequence.sequence === pasteStart) {+ const afterStart = parsedEscapeSequence.nextIndex;+ const endIndex = input.indexOf(pasteEnd, afterStart);+ if (endIndex === -1) {+ return pendingFrom(escapeIndex);+ }+ events.push({ paste: input.slice(afterStart, endIndex) });+ index = endIndex + pasteEnd.length;+ continue;+ }+ events.push(parsedEscapeSequence.sequence);+ index = parsedEscapeSequence.nextIndex;+ }+ return {+ events,+ pending: '',+ };+};+export const createInputParser = () => {+ let pending = '';+ return {+ push(chunk) {+ const parsedInput = parseKeypresses(pending + chunk);+ pending = parsedInput.pending;+ return parsedInput.events;+ },+ hasPendingEscape() {+ // Don't trigger the escape flush timer while assembling a paste start+ // marker (`\u001B[200` and then `~`) or while waiting for paste end.+ return (pending.startsWith(escape) &&+ !pending.startsWith(pasteStart) &&+ pending !== '\u{1B}[200');+ },+ flushPendingEscape() {+ if (!pending.startsWith(escape)) {+ return undefined;+ }+ const pendingEscape = pending;+ pending = '';+ return pendingEscape;+ },+ reset() {+ pending = '';+ },+ };+};diff --git a/vendor/ink/build/instance.js b/vendor/ink/build/instance.jsdeleted file mode 100644index 291c46e8..00000000--- a/vendor/ink/build/instance.js+++ /dev/null@@ -1,205 +0,0 @@-"use strict";--Object.defineProperty(exports, "__esModule", {- value: true-});-exports.default = void 0;--var _react = _interopRequireDefault(require("react"));--var _lodash = _interopRequireDefault(require("lodash.throttle"));--var _autoBind = _interopRequireDefault(require("auto-bind"));--var _logUpdate = _interopRequireDefault(require("log-update"));--var _isCi = _interopRequireDefault(require("is-ci"));--var _signalExit = _interopRequireDefault(require("signal-exit"));--var _ansiEscapes = _interopRequireDefault(require("ansi-escapes"));--var _reconciler = _interopRequireDefault(require("./reconciler"));--var _reconciler2 = _interopRequireDefault(require("./experimental/reconciler"));--var _renderer = _interopRequireDefault(require("./renderer"));--var _renderer2 = _interopRequireDefault(require("./experimental/renderer"));--var dom = _interopRequireWildcard(require("./dom"));--var experimentalDom = _interopRequireWildcard(require("./experimental/dom"));--var _instances = _interopRequireDefault(require("./instances"));--var _App = _interopRequireDefault(require("./components/App"));--function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }--function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }--function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }--class Instance {- constructor(options) {- (0, _autoBind.default)(this);- this.options = options;-- if (options.experimental) {- this.rootNode = experimentalDom.createNode('root');- this.rootNode.onRender = options.debug ? this.onRender : (0, _lodash.default)(this.onRender, 16, {- leading: true,- trailing: true- });- this.rootNode.onImmediateRender = this.onRender;- this.renderer = (0, _renderer2.default)({- terminalWidth: options.stdout.columns- });- } else {- this.rootNode = dom.createNode('root');- this.rootNode.onRender = this.onRender;- this.renderer = (0, _renderer.default)({- terminalWidth: options.stdout.columns- });- }-- this.log = _logUpdate.default.create(options.stdout);- this.throttledLog = options.debug ? this.log : (0, _lodash.default)(this.log, {- leading: true,- trailing: true- }); // Ignore last render after unmounting a tree to prevent empty output before exit-- this.isUnmounted = false; // Store last output to only rerender when needed-- this.lastOutput = ''; // This variable is used only in debug mode to store full static output- // so that it's rerendered every time, not just new static parts, like in non-debug mode-- this.fullStaticOutput = '';-- if (options.experimental) {- this.container = _reconciler2.default.createContainer(this.rootNode, false, false);- } else {- this.container = _reconciler.default.createContainer(this.rootNode, false, false);- }-- this.exitPromise = new Promise((resolve, reject) => {- this.resolveExitPromise = resolve;- this.rejectExitPromise = reject;- }); // Unmount when process exits-- this.unsubscribeExit = (0, _signalExit.default)(this.unmount, {- alwaysLast: false- });- }-- onRender() {- if (this.isUnmounted) {- return;- }-- const {- output,- outputHeight,- staticOutput- } = this.renderer(this.rootNode); // If <Static> output isn't empty, it means new children have been added to it-- const hasStaticOutput = staticOutput && staticOutput !== '\n';-- if (this.options.debug) {- if (hasStaticOutput) {- this.fullStaticOutput += staticOutput;- }-- this.options.stdout.write(this.fullStaticOutput + output);- return;- }-- if (_isCi.default) {- if (hasStaticOutput) {- this.options.stdout.write(staticOutput);- }-- this.lastOutput = output;- return;- }-- if (hasStaticOutput) {- this.fullStaticOutput += staticOutput;- }-- if (this.options.experimental && outputHeight >= this.options.stdout.rows) {- this.options.stdout.write(_ansiEscapes.default.clearTerminal + this.fullStaticOutput + output);- this.lastOutput = output;- return;- } // To ensure static output is cleanly rendered before main output, clear main output first--- if (hasStaticOutput) {- this.log.clear();- this.options.stdout.write(staticOutput);- }-- if (output !== this.lastOutput) {- if (this.options.experimental) {- this.throttledLog(output);- } else {- this.log(output);- }- }- }-- render(node) {- const tree = _react.default.createElement(_App.default, {- stdin: this.options.stdin,- stdout: this.options.stdout,- exitOnCtrlC: this.options.exitOnCtrlC,- onExit: this.unmount- }, node);-- if (this.options.experimental) {- _reconciler2.default.updateContainer(tree, this.container);- } else {- _reconciler.default.updateContainer(tree, this.container);- }- }-- unmount(error) {- if (this.isUnmounted) {- return;- }-- this.onRender();- this.unsubscribeExit(); // CIs don't handle erasing ansi escapes well, so it's better to- // only render last frame of non-static output-- if (_isCi.default) {- this.options.stdout.write(this.lastOutput + '\n');- } else if (!this.options.debug) {- this.log.done();- }-- this.isUnmounted = true;-- if (this.options.experimental) {- _reconciler2.default.updateContainer(null, this.container);- } else {- _reconciler.default.updateContainer(null, this.container);- }-- _instances.default.delete(this.options.stdout);-- if (error instanceof Error) {- this.rejectExitPromise(error);- } else {- this.resolveExitPromise();- }- }-- waitUntilExit() {- return this.exitPromise;- }--}--exports.default = Instance;\ No newline at end of filediff --git a/vendor/ink/build/instances.d.ts b/vendor/ink/build/instances.d.tsindex 01524258..8ff36f67 100644--- a/vendor/ink/build/instances.d.ts+++ b/vendor/ink/build/instances.d.ts@@ -1,3 +1,3 @@import type Ink from './ink.js';-declare const instances: WeakMap<NodeJS.WriteStream, Ink>;+declare const instances: WeakMap<NodeJS.WritableStream, Ink>;export default instances;diff --git a/vendor/ink/build/is-devtools-reachable.d.ts b/vendor/ink/build/is-devtools-reachable.d.tsnew file mode 100644index 00000000..d3615897--- /dev/null+++ b/vendor/ink/build/is-devtools-reachable.d.ts@@ -0,0 +1,2 @@+declare const isDevToolsReachable: (url?: string, timeoutMs?: number) => Promise<boolean>;+export default isDevToolsReachable;diff --git a/vendor/ink/build/is-devtools-reachable.js b/vendor/ink/build/is-devtools-reachable.jsnew file mode 100644index 00000000..8e2fb70d--- /dev/null+++ b/vendor/ink/build/is-devtools-reachable.js@@ -0,0 +1,20 @@+const isDevToolsReachable = async (url = 'ws://localhost:8097', timeoutMs = 2000) => new Promise(resolve => {+ const socket = new WebSocket(url);+ const timeout = setTimeout(() => {+ resolve(false);+ socket.close();+ }, timeoutMs);+ // Don't let the timeout keep the process alive on its own+ timeout.unref();+ socket.addEventListener('open', () => {+ clearTimeout(timeout);+ socket.close();+ resolve(true);+ });+ // The socket is already closing after `error`+ socket.addEventListener('error', () => {+ clearTimeout(timeout);+ resolve(false);+ });+});+export default isDevToolsReachable;diff --git a/vendor/ink/build/kitty-keyboard.d.ts b/vendor/ink/build/kitty-keyboard.d.tsnew file mode 100644index 00000000..102043fb--- /dev/null+++ b/vendor/ink/build/kitty-keyboard.d.ts@@ -0,0 +1,23 @@+export declare const kittyFlags: {+ readonly disambiguateEscapeCodes: 1;+ readonly reportEventTypes: 2;+ readonly reportAlternateKeys: 4;+ readonly reportAllKeysAsEscapeCodes: 8;+ readonly reportAssociatedText: 16;+};+export type KittyFlagName = keyof typeof kittyFlags;+export declare function resolveFlags(flags: KittyFlagName[]): number;+export declare const kittyModifiers: {+ readonly shift: 1;+ readonly alt: 2;+ readonly ctrl: 4;+ readonly super: 8;+ readonly hyper: 16;+ readonly meta: 32;+ readonly capsLock: 64;+ readonly numLock: 128;+};+export type KittyKeyboardOptions = {+ mode?: 'auto' | 'enabled' | 'disabled';+ flags?: KittyFlagName[];+};diff --git a/vendor/ink/build/kitty-keyboard.js b/vendor/ink/build/kitty-keyboard.jsnew file mode 100644index 00000000..735ab0a2--- /dev/null+++ b/vendor/ink/build/kitty-keyboard.js@@ -0,0 +1,36 @@+// Kitty keyboard protocol flags.+// @see https://sw.kovidgoyal.net/kitty/keyboard-protocol/+export const kittyFlags = {+ disambiguateEscapeCodes: 1,+ reportEventTypes: 2,+ reportAlternateKeys: 4,+ reportAllKeysAsEscapeCodes: 8,+ reportAssociatedText: 16,+};+// Converts an array of flag names to the corresponding bitmask value.+export function resolveFlags(flags) {+ let result = 0;+ for (const flag of flags) {+ // eslint-disable-next-line no-bitwise+ result |= kittyFlags[flag];+ }+ if (flags.includes('reportAssociatedText')) {+ // Associated text is defined only when all-key reporting is enabled.+ // eslint-disable-next-line no-bitwise+ result |= kittyFlags.reportAllKeysAsEscapeCodes;+ }+ return result;+}+// Kitty keyboard modifier bits.+// These are used in the modifier parameter of CSI u sequences.+// Note: The actual modifier value is (modifiers - 1) as per the protocol.+export const kittyModifiers = {+ shift: 1,+ alt: 2,+ ctrl: 4,+ super: 8,+ hyper: 16,+ meta: 32,+ capsLock: 64,+ numLock: 128,+};diff --git a/vendor/ink/build/line-update.d.ts b/vendor/ink/build/line-update.d.tsnew file mode 100644index 00000000..5abf4a73--- /dev/null+++ b/vendor/ink/build/line-update.d.ts@@ -0,0 +1 @@+export default function lineUpdate(previous: string, next: string, columns: number | undefined): string;diff --git a/vendor/ink/build/line-update.js b/vendor/ink/build/line-update.jsnew file mode 100644index 00000000..e877fca0--- /dev/null+++ b/vendor/ink/build/line-update.js@@ -0,0 +1,85 @@+import ansiEscapes from 'ansi-escapes';+import stringWidth from 'string-width';+const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });+// eslint-disable-next-line no-control-regex, regexp/no-control-character -- SGR starts with ESC.+const sgr = /\u{1B}\[[\d;]*m/gu;+// Only SGR is safe to replay without moving the cursor or changing terminal modes.+// OSC links, tabs, and other controls retain the existing whole-line path.+const control = /\p{Control}/u;+// eslint-disable-next-line regexp/no-obscure-range -- The range covers every printable ASCII character.+const printableAscii = /^[ -~]*$/u;+// Build a changed line, leaving its identical styled prefix on screen when safe.+export default function lineUpdate(previous, next, columns) {+ // Erase from the first changed column before painting. This clears sparse+ // gaps without touching an unchanged prefix or erasing after the last glyph.+ const full = ansiEscapes.cursorTo(0) + ansiEscapes.eraseEndLine + next;+ if (columns === undefined || Number.isNaN(columns) || columns < 1) {+ return full;+ }+ let commonLength = 0;+ while (commonLength < previous.length &&+ commonLength < next.length &&+ previous[commonLength] === next[commonLength]) {+ commonLength++;+ }+ if (commonLength === 0) {+ return full;+ }+ const previousText = previous.replaceAll(sgr, '');+ const nextText = next.replaceAll(sgr, '');+ if (control.test(previousText) || control.test(nextText)) {+ return full;+ }+ // eslint-disable-next-line unicorn/prefer-iterator-to-array -- Iterator helpers are not in the project's ES2024 library.+ const codes = [...next.matchAll(sgr)];+ let textLimit = commonLength;+ for (const match of codes) {+ if (match.index >= commonLength) {+ break;+ }+ // A difference inside an SGR sequence must repaint from before that sequence.+ textLimit -= Math.min(match[0].length, commonLength - match.index);+ }+ let textLength = 0;+ let column = 0;+ // ASCII is common in counters and tables; avoid per-cell segmentation there.+ if (printableAscii.test(previousText) && printableAscii.test(nextText)) {+ textLength = textLimit;+ column = textLimit;+ }+ else {+ const previousSegments = segmenter.segment(previousText)[Symbol.iterator]();+ for (const { segment, index } of segmenter.segment(nextText)) {+ if (index + segment.length > textLimit ||+ previousSegments.next().value?.segment !== segment) {+ break;+ }+ textLength = index + segment.length;+ }+ column = stringWidth(nextText.slice(0, textLength));+ }+ // CHA clamps at the last cell. It cannot reproduce a wrap-pending cursor+ // after a full-width prefix, particularly when the suffix only closes styles.+ if (column === 0 ||+ column >= columns ||+ column + stringWidth(previousText.slice(textLength)) > columns ||+ column + stringWidth(nextText.slice(textLength)) > columns) {+ return full;+ }+ let offset = textLength;+ let styles = '';+ for (const match of codes) {+ if (match.index > offset || match.index + match[0].length > commonLength) {+ break;+ }+ offset += match[0].length;+ // Replay the exact SGR history so nested resets and extended colors have+ // the same state as a full write.+ styles += match[0];+ }+ const partial = ansiEscapes.cursorTo(column) ++ ansiEscapes.eraseEndLine ++ styles ++ next.slice(offset);+ return partial.length < full.length ? partial : full;+}diff --git a/vendor/ink/build/log-update.d.ts b/vendor/ink/build/log-update.d.tsindex ff501a9b..d1f1208a 100644--- a/vendor/ink/build/log-update.d.ts+++ b/vendor/ink/build/log-update.d.ts@@ -1,15 +1,21 @@-import { type Writable } from 'node:stream';+import type { OutputStream } from './stream.js';+import { type CursorPosition } from './cursor-helpers.js';+export type { CursorPosition } from './cursor-helpers.js';export type LogUpdate = {clear: () => void;done: () => void;- /** Resize baseline reset (Cosmic Stack patch). */- invalidate: () => void;- /** Hardware cursor (Cosmic Stack patch): `cursor` is the live-frame cell to park the terminal cursor on. */- (str: string, cursor?: { row: number; col: number } | null): void;+ reset: () => void;+ sync: (text: string) => void;+ setCursorPosition: (position: CursorPosition | undefined) => void;+ isCursorDirty: () => boolean;+ willRender: (text: string) => boolean;+ getCursorPosition: () => CursorPosition | undefined;+ (text: string): boolean;};declare const logUpdate: {- create: (stream: Writable, { showCursor }?: {+ create: (stream: OutputStream, { showCursor, incremental }?: {showCursor?: boolean | undefined;+ incremental?: boolean | undefined;}) => LogUpdate;};export default logUpdate;diff --git a/vendor/ink/build/log-update.js b/vendor/ink/build/log-update.jsindex 22efeceb..85458f44 100644--- a/vendor/ink/build/log-update.js+++ b/vendor/ink/build/log-update.js@@ -1,99 +1,265 @@import ansiEscapes from 'ansi-escapes';import cliCursor from 'cli-cursor';-// Synchronized output (Cosmic Stack patch): see ink.js synchronized().-const BSU = '\u001B[?2026h';-const ESU = '\u001B[?2026l';-const create = (stream, { showCursor = false, synchronize = false } = {}) => {- // One atomic update per write, unless ink.js already opened one.- const syncWrite = (data) => stream.write(synchronize && !(render.syncDepth > 0) ? BSU + data + ESU : data);+import lineUpdate from './line-update.js';+import { cursorPositionChanged, buildCursorSuffix, buildCursorOnlySequence, buildReturnToBottomPrefix, buildReturnToBottom, buildEraseFrame, hideCursorEscape, } from './cursor-helpers.js';+// Count visible lines in a string, ignoring the trailing empty element+// that `split('\n')` produces when the string ends with '\n'.+const visibleLineCount = (lines, text) => text.endsWith('\n') ? lines.length - 1 : lines.length;+const createStandard = (stream, { showCursor = false } = {}) => {let previousLineCount = 0;let previousOutput = '';let hasHiddenCursor = false;- // Hardware cursor (Cosmic Stack patch): after a frame is written the- // cursor sits on the line below the last row (column 0) — that is what- // the erase arithmetic assumes. `park` moves it up onto the anchor cell- // and shows it; `unpark` hides it and moves it back BEFORE anything else- // is written, so the arithmetic never sees a parked cursor. Relative- // moves (CUU/CUD/CHA) on purpose: the absolute row of the live region is- // unknown without a DSR round-trip.- let parked = null;- const targetFor = (cursor, lineCount) => {- if (!cursor) return null;- const rows = lineCount - 1; // lineCount counts the trailing blank line- if (!(cursor.row >= 0 && cursor.row < rows)) return null;- return { up: rows - cursor.row, col: Math.max(0, Math.floor(cursor.col)) };+ let cursorPosition;+ let isCursorDirty = false;+ let previousCursorPosition;+ let wasCursorShown = false;+ const getActiveCursor = () => (isCursorDirty ? cursorPosition : undefined);+ const hasChanges = (text, activeCursor) => {+ const hasCursorChanged = cursorPositionChanged(activeCursor, previousCursorPosition);+ return text !== previousOutput || hasCursorChanged;};- const unpark = () => {- if (!parked) return '';- const { up } = parked;- parked = null;- return ansiEscapes.cursorHide + ansiEscapes.cursorDown(up) + ansiEscapes.cursorLeft;- };- const park = (target) => {- if (!target) return '';- parked = target;- return ansiEscapes.cursorUp(target.up) + ansiEscapes.cursorTo(target.col) + ansiEscapes.cursorShow;- };- const render = (str, cursor) => {+ const render = (text) => {if (!showCursor && !hasHiddenCursor) {- cliCursor.hide();+ cliCursor.hide(stream);hasHiddenCursor = true;}- const output = str + '\n';- if (output === previousOutput) {- // Hardware cursor (Cosmic Stack patch): same rows, but the anchor- // may have moved or toggled — re-park without touching the frame.- const target = targetFor(cursor, previousLineCount);- const same = (!parked && !target) || (parked && target && parked.up === target.up && parked.col === target.col);- if (!same) syncWrite(unpark() + park(target));+ // Only use cursor if setCursorPosition was called since last render.+ // This ensures stale positions don't persist after component unmount.+ const activeCursor = getActiveCursor();+ isCursorDirty = false;+ const hasCursorChanged = cursorPositionChanged(activeCursor, previousCursorPosition);+ if (!hasChanges(text, activeCursor)) {+ return false;+ }+ const lines = text.split('\n');+ const cursorSuffix = buildCursorSuffix(lines.length - 1, activeCursor);+ if (text === previousOutput && hasCursorChanged) {+ stream.write(buildCursorOnlySequence({+ cursorWasShown: wasCursorShown,+ previousLineCount,+ previousCursorPosition,+ cursorPosition: activeCursor,+ }));+ }+ else {+ previousOutput = text;+ const returnPrefix = buildReturnToBottomPrefix(wasCursorShown, previousLineCount, previousCursorPosition);+ stream.write(returnPrefix ++ ansiEscapes.eraseLines(previousLineCount) ++ text ++ cursorSuffix);+ previousLineCount = lines.length;+ }+ previousCursorPosition = activeCursor ? { ...activeCursor } : undefined;+ wasCursorShown = activeCursor !== undefined;+ return true;+ };+ render.clear = () => {+ stream.write(buildEraseFrame(previousLineCount, previousCursorPosition));+ previousOutput = '';+ previousLineCount = 0;+ previousCursorPosition = undefined;+ wasCursorShown = false;+ };+ render.done = () => {+ if (previousCursorPosition) {+ // Leave the terminal at the output bottom before discarding the cursor position.+ stream.write(buildReturnToBottom(previousLineCount, previousCursorPosition));+ }+ previousOutput = '';+ previousLineCount = 0;+ previousCursorPosition = undefined;+ wasCursorShown = false;+ if (showCursor) {return;}- // Diff-render (Cosmic Stack patch): erase and rewrite only the rows- // from the first changed line onward; identical rows above stay on- // screen untouched. Ink 5's log-update erased and rewrote the ENTIRE- // frame on every render — a prompt-selection change or spinner tick- // repainted the whole live region, which read as a full-UI flash.- // The row bytes are compared verbatim (layout is deterministic), and- // the erase count accounts for the trailing blank line exactly like- // `previousLineCount` does, so `clear()` and cursor arithmetic stay- // in sync with the original accounting.- const previousRows = previousOutput === '' ? [] : previousOutput.slice(0, -1).split('\n');- const nextRows = output.slice(0, -1).split('\n');- const common = Math.min(previousRows.length, nextRows.length);- let firstChange = 0;- while (firstChange < common && previousRows[firstChange] === nextRows[firstChange]) {- firstChange++;- }- const eraseCount = previousLineCount - firstChange;- previousOutput = output;- previousLineCount = output.split('\n').length;- syncWrite(unpark() + ansiEscapes.eraseLines(eraseCount) + nextRows.slice(firstChange).join('\n') + '\n' + park(targetFor(cursor, previousLineCount)));+ cliCursor.show(stream);+ hasHiddenCursor = false;};- // Resize baseline reset (Cosmic Stack patch): forget what is on screen- // without touching the line count — the next render erases the old- // frame's rows and rewrites every row instead of diffing against rows- // the terminal has already re-wrapped.- render.invalidate = () => {+ render.reset = () => {previousOutput = '';+ previousLineCount = 0;+ previousCursorPosition = undefined;+ wasCursorShown = false;+ };+ render.sync = (text) => {+ const activeCursor = isCursorDirty ? cursorPosition : undefined;+ isCursorDirty = false;+ const lines = text.split('\n');+ previousOutput = text;+ previousLineCount = lines.length;+ if (!activeCursor && wasCursorShown) {+ stream.write(hideCursorEscape);+ }+ if (activeCursor) {+ stream.write(buildCursorSuffix(lines.length - 1, activeCursor));+ }+ previousCursorPosition = activeCursor ? { ...activeCursor } : undefined;+ wasCursorShown = activeCursor !== undefined;+ };+ render.setCursorPosition = (position) => {+ cursorPosition = position;+ isCursorDirty = true;+ };+ render.isCursorDirty = () => isCursorDirty;+ render.willRender = (text) => hasChanges(text, getActiveCursor());+ render.getCursorPosition = () => previousCursorPosition;+ return render;+};+const createIncremental = (stream, { showCursor = false } = {}) => {+ let previousLines = [];+ let previousOutput = '';+ let previousColumns = stream.columns;+ let hasHiddenCursor = false;+ let cursorPosition;+ let isCursorDirty = false;+ let previousCursorPosition;+ let wasCursorShown = false;+ const getActiveCursor = () => (isCursorDirty ? cursorPosition : undefined);+ const hasChanges = (text, activeCursor) => {+ const hasCursorChanged = cursorPositionChanged(activeCursor, previousCursorPosition);+ return text !== previousOutput || hasCursorChanged;+ };+ const render = (text) => {+ if (!showCursor && !hasHiddenCursor) {+ cliCursor.hide(stream);+ hasHiddenCursor = true;+ }+ // Only use cursor if setCursorPosition was called since last render.+ // This ensures stale positions don't persist after component unmount.+ const activeCursor = getActiveCursor();+ isCursorDirty = false;+ const hasCursorChanged = cursorPositionChanged(activeCursor, previousCursorPosition);+ if (!hasChanges(text, activeCursor)) {+ return false;+ }+ const areColumnsUnchanged = previousColumns === stream.columns;+ previousColumns = stream.columns;+ const nextLines = text.split('\n');+ const visibleCount = visibleLineCount(nextLines, text);+ const previousVisible = visibleLineCount(previousLines, previousOutput);+ if (text === previousOutput && hasCursorChanged) {+ stream.write(buildCursorOnlySequence({+ cursorWasShown: wasCursorShown,+ previousLineCount: previousLines.length,+ previousCursorPosition,+ cursorPosition: activeCursor,+ }));+ previousCursorPosition = activeCursor ? { ...activeCursor } : undefined;+ wasCursorShown = activeCursor !== undefined;+ return true;+ }+ const returnPrefix = buildReturnToBottomPrefix(wasCursorShown, previousLines.length, previousCursorPosition);+ if (text === '\n' || previousOutput.length === 0) {+ const cursorSuffix = buildCursorSuffix(nextLines.length - 1, activeCursor);+ stream.write(returnPrefix ++ ansiEscapes.eraseLines(previousLines.length) ++ text ++ cursorSuffix);+ wasCursorShown = activeCursor !== undefined;+ previousCursorPosition = activeCursor ? { ...activeCursor } : undefined;+ previousOutput = text;+ previousLines = nextLines;+ return true;+ }+ const hasTrailingNewline = text.endsWith('\n');+ // We aggregate all chunks for incremental rendering into a buffer, and then write them to stdout at the end.+ const buffer = [];+ buffer.push(returnPrefix);+ // Clear extra lines if the current content's line count is lower than the previous.+ if (visibleCount < previousVisible) {+ const didPreviousHaveTrailingNewline = previousOutput.endsWith('\n');+ const extraSlot = didPreviousHaveTrailingNewline ? 1 : 0;+ buffer.push(ansiEscapes.eraseLines(previousVisible - visibleCount + extraSlot), ansiEscapes.cursorUp(visibleCount));+ }+ else if (previousLines.length > 1) {+ buffer.push(ansiEscapes.cursorUp(previousLines.length - 1));+ }+ for (let i = 0; i < visibleCount; i++) {+ const isLastLine = i === visibleCount - 1;+ // We do not write lines if the contents are the same. This prevents flickering during renders.+ // New blank rows need a line feed to scroll at the terminal bottom; the trailing split entry is not a visible row.+ if (i < previousVisible && nextLines[i] === previousLines[i]) {+ // Don't move past the last line when there's no trailing newline,+ // otherwise the cursor overshoots the rendered block.+ if (!isLastLine || hasTrailingNewline) {+ buffer.push(ansiEscapes.cursorNextLine);+ }+ continue;+ }+ const nextLine = nextLines[i];+ const changedLine = areColumnsUnchanged && nextLines.length === previousLines.length+ ? lineUpdate(previousLines[i], nextLine, stream.columns)+ : ansiEscapes.cursorTo(0) + ansiEscapes.eraseEndLine + nextLine;+ buffer.push(changedLine ++ // Don't append newline after the last line when the input+ // has no trailing newline (fullscreen mode).+ (isLastLine && !hasTrailingNewline ? '' : '\n'));+ }+ const cursorSuffix = buildCursorSuffix(nextLines.length - 1, activeCursor);+ buffer.push(cursorSuffix);+ stream.write(buffer.join(''));+ wasCursorShown = activeCursor !== undefined;+ previousCursorPosition = activeCursor ? { ...activeCursor } : undefined;+ previousOutput = text;+ previousLines = nextLines;+ return true;};- render.synchronize = synchronize;- render.syncDepth = 0;render.clear = () => {- syncWrite(unpark() + ansiEscapes.eraseLines(previousLineCount));+ stream.write(buildEraseFrame(previousLines.length, previousCursorPosition));previousOutput = '';- previousLineCount = 0;+ previousLines = [];+ previousCursorPosition = undefined;+ wasCursorShown = false;};render.done = () => {- const restore = unpark();- if (restore) stream.write(restore);+ if (previousCursorPosition) {+ // Leave the terminal at the output bottom before discarding the cursor position.+ stream.write(buildReturnToBottom(previousLines.length, previousCursorPosition));+ }previousOutput = '';- previousLineCount = 0;- if (!showCursor) {- cliCursor.show();- hasHiddenCursor = false;+ previousLines = [];+ previousCursorPosition = undefined;+ wasCursorShown = false;+ if (showCursor) {+ return;}+ cliCursor.show(stream);+ hasHiddenCursor = false;+ };+ render.reset = () => {+ previousOutput = '';+ previousLines = [];+ previousCursorPosition = undefined;+ wasCursorShown = false;+ };+ render.sync = (text) => {+ const activeCursor = isCursorDirty ? cursorPosition : undefined;+ isCursorDirty = false;+ previousColumns = stream.columns;+ const lines = text.split('\n');+ previousOutput = text;+ previousLines = lines;+ if (!activeCursor && wasCursorShown) {+ stream.write(hideCursorEscape);+ }+ if (activeCursor) {+ stream.write(buildCursorSuffix(lines.length - 1, activeCursor));+ }+ previousCursorPosition = activeCursor ? { ...activeCursor } : undefined;+ wasCursorShown = activeCursor !== undefined;+ };+ render.setCursorPosition = (position) => {+ cursorPosition = position;+ isCursorDirty = true;};+ render.isCursorDirty = () => isCursorDirty;+ render.willRender = (text) => hasChanges(text, getActiveCursor());+ render.getCursorPosition = () => previousCursorPosition;return render;};+const create = (stream, { showCursor = false, incremental = false } = {}) => incremental+ ? createIncremental(stream, { showCursor })+ : createStandard(stream, { showCursor });const logUpdate = { create };export default logUpdate;diff --git a/vendor/ink/build/measure-element.d.ts b/vendor/ink/build/measure-element.d.tsindex f01e0cf6..75004232 100644--- a/vendor/ink/build/measure-element.d.ts+++ b/vendor/ink/build/measure-element.d.ts@@ -1,16 +1,40 @@import { type DOMElement } from './dom.js';type Output = {/**- * Element width.- */+ Horizontal position (0-based column) within the live layout region.+ */+ x: number;+ /**+ Vertical position (0-based row) within the live layout region.+ */+ y: number;+ /**+ Element width.+ */width: number;/**- * Element height.- */+ Element height.+ */height: number;+ /**+ Element width excluding borders.+ */+ clientWidth: number;+ /**+ Element height excluding borders.+ */+ clientHeight: number;};/**- * Measure the dimensions of a particular `<Box>` element.- */+Measure the layout metrics of a particular `<Box>` element.+Returns an object with `x`, `y`, `width`, `height`, `clientWidth` and `clientHeight` properties.++`x` and `y` are the element's position within the live layout region, computed by walking up the layout tree and accumulating each ancestor's offset. These are layout-tree coordinates, not terminal viewport coordinates. To compare them with mouse events, convert the event coordinates using the live region's viewport position. This is necessary even in alternate-screen mode when output, such as `<Static>` content, appears above the live region. These are layout coordinates and do not include any `contentOffsetX`/`contentOffsetY` applied by an ancestor, so hit-testing inside a scrolled container has to subtract those offsets too.++`clientWidth` and `clientHeight` are the element's dimensions excluding borders, which is the amount of space its content can occupy. To build a scrollable view, measure the content wrapper separately and clamp the offset with `content.height - viewport.clientHeight`, together with the `contentOffsetX`/`contentOffsetY` props. That bound assumes an unpadded viewport, since `clientWidth`/`clientHeight` exclude borders but not padding; put padding on the content wrapper instead.++Note: `measureElement()` returns zeros for all properties when called during render (before layout is calculated). Call it from post-render code, such as `useEffect`, `useLayoutEffect`, input handlers, or timer callbacks. When content changes, pass the relevant dependency to your effect so it re-measures after each update.+*/declare const measureElement: (node: DOMElement) => Output;export default measureElement;+export type { Output as ElementMetrics };diff --git a/vendor/ink/build/measure-element.js b/vendor/ink/build/measure-element.jsindex 429c73ed..943a6801 100644--- a/vendor/ink/build/measure-element.js+++ b/vendor/ink/build/measure-element.js@@ -1,8 +1,50 @@+import Yoga from 'yoga-layout';+const emptyOutput = {+ x: 0,+ y: 0,+ width: 0,+ height: 0,+ clientWidth: 0,+ clientHeight: 0,+};/**- * Measure the dimensions of a particular `<Box>` element.- */-const measureElement = (node) => ({- width: node.yogaNode?.getComputedWidth() ?? 0,- height: node.yogaNode?.getComputedHeight() ?? 0,-});+Measure the layout metrics of a particular `<Box>` element.+Returns an object with `x`, `y`, `width`, `height`, `clientWidth` and `clientHeight` properties.++`x` and `y` are the element's position within the live layout region, computed by walking up the layout tree and accumulating each ancestor's offset. These are layout-tree coordinates, not terminal viewport coordinates. To compare them with mouse events, convert the event coordinates using the live region's viewport position. This is necessary even in alternate-screen mode when output, such as `<Static>` content, appears above the live region. These are layout coordinates and do not include any `contentOffsetX`/`contentOffsetY` applied by an ancestor, so hit-testing inside a scrolled container has to subtract those offsets too.++`clientWidth` and `clientHeight` are the element's dimensions excluding borders, which is the amount of space its content can occupy. To build a scrollable view, measure the content wrapper separately and clamp the offset with `content.height - viewport.clientHeight`, together with the `contentOffsetX`/`contentOffsetY` props. That bound assumes an unpadded viewport, since `clientWidth`/`clientHeight` exclude borders but not padding; put padding on the content wrapper instead.++Note: `measureElement()` returns zeros for all properties when called during render (before layout is calculated). Call it from post-render code, such as `useEffect`, `useLayoutEffect`, input handlers, or timer callbacks. When content changes, pass the relevant dependency to your effect so it re-measures after each update.+*/+const measureElement = (node) => {+ const { yogaNode } = node;+ if (!yogaNode) {+ return emptyOutput;+ }+ let x = yogaNode.getComputedLeft();+ let y = yogaNode.getComputedTop();+ let current = node.parentNode;+ while (current) {+ if (current.yogaNode) {+ x += current.yogaNode.getComputedLeft();+ y += current.yogaNode.getComputedTop();+ }+ current = current.parentNode;+ }+ const width = yogaNode.getComputedWidth();+ const height = yogaNode.getComputedHeight();+ const borderLeft = yogaNode.getComputedBorder(Yoga.EDGE_LEFT);+ const borderTop = yogaNode.getComputedBorder(Yoga.EDGE_TOP);+ const clientWidth = width - borderLeft - yogaNode.getComputedBorder(Yoga.EDGE_RIGHT);+ const clientHeight = height - borderTop - yogaNode.getComputedBorder(Yoga.EDGE_BOTTOM);+ return {+ x,+ y,+ width,+ height,+ clientWidth,+ clientHeight,+ };+};export default measureElement;diff --git a/vendor/ink/build/measure-text.js b/vendor/ink/build/measure-text.jsindex 2f1fde84..95d43df6 100644--- a/vendor/ink/build/measure-text.js+++ b/vendor/ink/build/measure-text.js@@ -1,5 +1,6 @@import widestLine from 'widest-line';-const cache = {};+import QuickLRU from 'quick-lru';+const cache = new QuickLRU({ maxSize: 4096 });const measureText = (text) => {if (text.length === 0) {return {@@ -7,13 +8,14 @@ const measureText = (text) => {height: 0,};}- const cachedDimensions = cache[text];+ const cachedDimensions = cache.get(text);if (cachedDimensions) {return cachedDimensions;}const width = widestLine(text);const height = text.split('\n').length;- cache[text] = { width, height };- return { width, height };+ const dimensions = { width, height };+ cache.set(text, dimensions);+ return dimensions;};export default measureText;diff --git a/vendor/ink/build/output.d.ts b/vendor/ink/build/output.d.tsindex 30c87bcd..181a3a3f 100644--- a/vendor/ink/build/output.d.ts+++ b/vendor/ink/build/output.d.ts@@ -1,12 +1,11 @@import { type OutputTransformer } from './render-node-to-output.js';/**- * "Virtual" output class- *- * Handles the positioning and saving of the output of each node in the tree.- * Also responsible for applying transformations to each character of the output.- *- * Used to generate the final output of all nodes before writing it to actual output stream (e.g. stdout)- */+"Virtual" output class++Handles the positioning and saving of the output of each node in the tree. Also responsible for applying transformations to each character of the output.++Used to generate the final output of all nodes before writing it to actual output stream (e.g. stdout)+*/type Options = {width: number;height: number;@@ -18,15 +17,18 @@ type Clip = {y2: number | undefined;};export default class Output {+ private readonly operations;+ private readonly caches;width: number;height: number;- private readonly operations;constructor(options: Options);+ private applyWriteOperation;write(x: number, y: number, text: string, options: {transformers: OutputTransformer[];}): void;clip(clip: Clip): void;unclip(): void;+ sliceLineToColumns(line: string, from: number, to: number): string;get(): {output: string;height: number;diff --git a/vendor/ink/build/output.js b/vendor/ink/build/output.jsindex 1e18184f..79debd1c 100644--- a/vendor/ink/build/output.js+++ b/vendor/ink/build/output.js@@ -1,19 +1,184 @@-import sliceAnsi from 'slice-ansi';import stringWidth from 'string-width';-import widestLine from 'widest-line';import { styledCharsFromTokens, styledCharsToString, tokenize, } from '@alcalzone/ansi-tokenize';+// Replaces a partially visible wide character with a space that keeps its styles.+const blankCell = (cell) => ({+ ...cell,+ value: ' ',+ fullWidth: false,+});+// An undefined bound means "unbounded on this edge", so intersecting keeps whichever bound is defined and takes the tighter one when both are.+const intersectBound = (a, b, tighter) => {+ if (a === undefined) {+ return b;+ }+ return b === undefined ? a : tighter(a, b);+};+// Bounds are half-open: `x2`/`y2` are exclusive, so an axis is empty as soon as its lower bound reaches its upper one.+const isClipEmpty = (clip) => (clip.x1 !== undefined && clip.x2 !== undefined && clip.x1 >= clip.x2) ||+ (clip.y1 !== undefined && clip.y2 !== undefined && clip.y1 >= clip.y2);+const intersectClips = (outer, inner) => {+ if (!outer) {+ return inner;+ }+ return {+ x1: intersectBound(outer.x1, inner.x1, Math.max),+ x2: intersectBound(outer.x2, inner.x2, Math.min),+ y1: intersectBound(outer.y1, inner.y1, Math.max),+ y2: intersectBound(outer.y2, inner.y2, Math.min),+ };+};+class OutputCaches {+ widths = new Map();+ blockWidths = new Map();+ styledChars = new Map();+ getStyledChars(line) {+ let cached = this.styledChars.get(line);+ if (cached === undefined) {+ // Standalone invisible Unicode characters must not occupy terminal cells.+ cached = styledCharsFromTokens(tokenize(line)).filter(character => !/^\p{Default_Ignorable_Code_Point}+$/u.test(character.value));+ this.styledChars.set(line, cached);+ }+ return cached;+ }+ getStringWidth(text) {+ let cached = this.widths.get(text);+ if (cached === undefined) {+ cached = stringWidth(text);+ this.widths.set(text, cached);+ }+ return cached;+ }+ getWidestLine(text) {+ let cached = this.blockWidths.get(text);+ if (cached === undefined) {+ let lineWidth = 0;+ for (const line of text.split('\n')) {+ lineWidth = Math.max(lineWidth, this.getStringWidth(line));+ }+ cached = lineWidth;+ this.blockWidths.set(text, cached);+ }+ return cached;+ }+}export default class Output {+ operations = [];+ caches = new OutputCaches();width;height;- operations = [];constructor(options) {const { width, height } = options;this.width = width;this.height = height;}+ applyWriteOperation(output, operation, clip) {+ const { text, transformers } = operation;+ let { x, y } = operation;+ // Preserve styles across explicit newlines before clipping individual rows.+ const characterLines = [[]];+ for (const character of this.caches.getStyledChars(text)) {+ if (character.value === '\n') {+ characterLines.push([]);+ }+ else {+ characterLines.at(-1).push(character);+ }+ }+ let lines = characterLines.map(line => styledCharsToString(line));+ if (clip) {+ // Two nested clips can intersect to nothing. Nothing is visible, so bail out before slicing.+ if (isClipEmpty(clip)) {+ return;+ }+ const shouldClipHorizontally = typeof clip?.x1 === 'number' && typeof clip?.x2 === 'number';+ const shouldClipVertically = typeof clip?.y1 === 'number' && typeof clip?.y2 === 'number';+ // If text is positioned outside of clipping area altogether,+ // skip to the next operation to avoid unnecessary calculations+ if (shouldClipHorizontally) {+ const width = this.caches.getWidestLine(text);+ if (x + width < clip.x1 || x > clip.x2) {+ return;+ }+ }+ if (shouldClipVertically) {+ const height = lines.length;+ if (y + height < clip.y1 || y > clip.y2) {+ return;+ }+ }+ if (shouldClipHorizontally) {+ lines = lines.map(line => {+ const from = x < clip.x1 ? clip.x1 - x : 0;+ const width = this.caches.getStringWidth(line);+ const to = x + width > clip.x2 ? clip.x2 - x : width;+ return this.sliceLineToColumns(line, from, to);+ });+ if (x < clip.x1) {+ x = clip.x1;+ }+ }+ if (shouldClipVertically) {+ const from = y < clip.y1 ? clip.y1 - y : 0;+ const height = lines.length;+ const to = y + height > clip.y2 ? clip.y2 - y : height;+ lines = lines.slice(from, to);+ if (y < clip.y1) {+ y = clip.y1;+ }+ }+ }+ for (let [index, line] of lines.entries()) {+ const currentLine = output[y + index];+ // Lines above or below the output area have no corresponding pre-initialized row.+ if (!currentLine) {+ continue;+ }+ for (const transformer of transformers) {+ line = transformer(line, index + y - operation.y);+ }+ const characters = this.caches.getStyledChars(line);+ // Nothing to write (e.g. line was clipped away).+ if (characters.length === 0) {+ continue;+ }+ let offsetX = x;+ // Wide characters (e.g. CJK) occupy two cells: a leading+ // cell with the character and a trailing placeholder with+ // value ''. When an overlapping write lands in the middle+ // of a wide character, the boundary cells need cleanup so+ // the terminal never renders a half-visible wide character.+ // Preserve the styles of cells outside the overlapping write.+ if (currentLine[offsetX]?.value === '' &&+ offsetX > 0 &&+ this.caches.getStringWidth(currentLine[offsetX - 1]?.value ?? '') > 1) {+ currentLine[offsetX - 1] = blankCell(currentLine[offsetX - 1]);+ }+ for (const character of characters) {+ currentLine[offsetX] = character;+ // Determine printed width using string-width to align with measurement+ const characterWidth = Math.max(1, this.caches.getStringWidth(character.value));+ // For multi-column characters, clear following cells to avoid stray spaces/artifacts+ if (characterWidth > 1) {+ for (let offset = 1; offset < characterWidth; offset++) {+ currentLine[offsetX + offset] = {+ type: 'char',+ // Preserve visible cells when the leading cell is outside the output.+ value: offsetX < 0 ? ' ' : '',+ fullWidth: false,+ styles: character.styles,+ };+ }+ }+ offsetX += characterWidth;+ }+ if (currentLine[offsetX]?.value === '') {+ currentLine[offsetX] = blankCell(currentLine[offsetX]);+ }+ }+ }write(x, y, text, options) {const { transformers } = options;- if (!text) {+ if (text === '') {return;}this.operations.push({@@ -35,6 +200,33 @@ export default class Output {type: 'unclip',});}+ // Clipping works in terminal columns. A wide character (e.g. CJK) occupies two cells, so when a clip edge falls between its halves, the character must be replaced by a space that keeps its styles, otherwise its background disappears and the rest of the line shifts by a column.+ sliceLineToColumns(line, from, to) {+ if (from >= to) {+ return '';+ }+ const result = [];+ let column = 0;+ for (const character of this.caches.getStyledChars(line)) {+ const width = this.caches.getStringWidth(character.value);+ const start = column;+ column += width;+ if (column <= from) {+ continue;+ }+ if (start >= to) {+ break;+ }+ if (width > 1 && (start < from || column > to)) {+ // Only part of this wide character is visible, so keep the cell count and styles, but drop the glyph itself.+ result.push(blankCell(character));+ }+ else {+ result.push(character);+ }+ }+ return styledCharsToString(result);+ }get() {// Initialize output array with a specific set of rows, so that margin/padding at the bottom is preservedconst output = [];@@ -53,83 +245,14 @@ export default class Output {const clips = [];for (const operation of this.operations) {if (operation.type === 'clip') {- clips.push(operation.clip);+ // Nested clips must intersect, not replace, otherwise an inner `overflow="hidden"` box lets content escape the outer clip and overwrite surrounding UI.+ clips.push(intersectClips(clips.at(-1), operation.clip));}- if (operation.type === 'unclip') {+ else if (operation.type === 'unclip') {clips.pop();}- if (operation.type === 'write') {- const { text, transformers } = operation;- let { x, y } = operation;- let lines = text.split('\n');- const clip = clips.at(-1);- if (clip) {- const clipHorizontally = typeof clip?.x1 === 'number' && typeof clip?.x2 === 'number';- const clipVertically = typeof clip?.y1 === 'number' && typeof clip?.y2 === 'number';- // If text is positioned outside of clipping area altogether,- // skip to the next operation to avoid unnecessary calculations- if (clipHorizontally) {- const width = widestLine(text);- if (x + width < clip.x1 || x > clip.x2) {- continue;- }- }- if (clipVertically) {- const height = lines.length;- if (y + height < clip.y1 || y > clip.y2) {- continue;- }- }- if (clipHorizontally) {- lines = lines.map(line => {- const from = x < clip.x1 ? clip.x1 - x : 0;- const width = stringWidth(line);- const to = x + width > clip.x2 ? clip.x2 - x : width;- return sliceAnsi(line, from, to);- });- if (x < clip.x1) {- x = clip.x1;- }- }- if (clipVertically) {- const from = y < clip.y1 ? clip.y1 - y : 0;- const height = lines.length;- const to = y + height > clip.y2 ? clip.y2 - y : height;- lines = lines.slice(from, to);- if (y < clip.y1) {- y = clip.y1;- }- }- }- let offsetY = 0;- for (let [index, line] of lines.entries()) {- const currentLine = output[y + offsetY];- // Line can be missing if `text` is taller than height of pre-initialized `this.output`- if (!currentLine) {- continue;- }- for (const transformer of transformers) {- line = transformer(line, index);- }- const characters = styledCharsFromTokens(tokenize(line));- let offsetX = x;- for (const character of characters) {- currentLine[offsetX] = character;- // Some characters take up more than one column. In that case, the following- // pixels need to be cleared to avoid printing extra characters- const isWideCharacter = character.fullWidth || character.value.length > 1;- if (isWideCharacter) {- currentLine[offsetX + 1] = {- type: 'char',- value: '',- fullWidth: false,- styles: character.styles,- };- }- offsetX += isWideCharacter ? 2 : 1;- }- offsetY++;- }+ else {+ this.applyWriteOperation(output, operation, clips.at(-1));}}const generatedOutput = outputdiff --git a/vendor/ink/build/parse-keypress.d.ts b/vendor/ink/build/parse-keypress.d.tsindex 1dc1e48f..42c213d6 100644--- a/vendor/ink/build/parse-keypress.d.ts+++ b/vendor/ink/build/parse-keypress.d.ts@@ -1,14 +1,20 @@-import { Buffer } from 'node:buffer';export declare const nonAlphanumericKeys: string[];type ParsedKey = {name: string;ctrl: boolean;meta: boolean;shift: boolean;- option: boolean;sequence: string;raw: string | undefined;code?: string;+ super?: boolean;+ hyper?: boolean;+ capsLock?: boolean;+ numLock?: boolean;+ eventType?: 'press' | 'repeat' | 'release';+ isKittyProtocol?: boolean;+ text?: string;+ isPrintable?: boolean;};-declare const parseKeypress: (s?: Buffer | string) => ParsedKey;+declare const parseKeypress: (s?: Uint8Array | string) => ParsedKey;export default parseKeypress;diff --git a/vendor/ink/build/parse-keypress.js b/vendor/ink/build/parse-keypress.jsindex 247d2842..a6005c49 100644--- a/vendor/ink/build/parse-keypress.js+++ b/vendor/ink/build/parse-keypress.js@@ -1,6 +1,7 @@// Copied from https://github.com/enquirer/enquirer/blob/36785f3399a41cd61e9d28d1eb9c2fcd73d69b4c/lib/keypress.js-import { Buffer } from 'node:buffer';-const metaKeyCodeRe = /^(?:\x1b)([a-zA-Z0-9])$/;+import { kittyModifiers } from './kitty-keyboard.js';+const textDecoder = new TextDecoder();+const metaKeyCodeRe = /^(?:\x1b)([^\p{C}\[])$/u;const fnKeyRe = /^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/;const keyName = {/* xterm/gnome ESC O letter */@@ -8,6 +9,11 @@ const keyName = {OQ: 'f2',OR: 'f3',OS: 'f4',+ /* vt220-style ESC [ letter (e.g. Ctrl+F1 sends ESC [ 1 ; 5 P) */+ '[P': 'f1',+ '[Q': 'f2',+ '[R': 'f3',+ '[S': 'f4',/* xterm/rxvt ESC [ number ~ */'[11~': 'f1','[12~': 'f2',@@ -115,15 +121,265 @@ const isCtrlKey = (code) => {'[8^',].includes(code);};+// Kitty keyboard protocol: CSI codepoint [: shifted-key [: base-layout-key]] ; modifiers [: eventType] [; text-as-codepoints] u+const kittyKeyRe = /^\x1b\[(\d+)(?::\d*(?::\d+)?)?(?:;(\d*)(?::(\d+))?(?:;([\d:]+))?)?u$/;+// Kitty-enhanced special keys: CSI number [; modifiers [: eventType]] {letter|~}+// These legacy CSI sequences use Kitty modifiers even without the :eventType field.+// Examples: \x1b[1;1:1A (up arrow press), \x1b[3;1:3~ (delete release)+const kittySpecialKeyRe = /^\x1b\[(\d+)(?:;(\d+)(?::(\d+))?)?([A-Za-z~])$/;+// Letter-terminated special key names (CSI 1 ; mods letter)+const kittySpecialLetterKeys = {+ A: 'up',+ B: 'down',+ C: 'right',+ D: 'left',+ E: 'clear',+ F: 'end',+ H: 'home',+ P: 'f1',+ Q: 'f2',+ S: 'f4',+};+// Number-terminated special key names (CSI number ; mods ~)+const kittySpecialNumberKeys = {+ 2: 'insert',+ 3: 'delete',+ 5: 'pageup',+ 6: 'pagedown',+ 7: 'home',+ 8: 'end',+ 11: 'f1',+ 12: 'f2',+ 13: 'f3',+ 14: 'f4',+ 15: 'f5',+ 17: 'f6',+ 18: 'f7',+ 19: 'f8',+ 20: 'f9',+ 21: 'f10',+ 23: 'f11',+ 24: 'f12',+ 57427: 'clear',+};+// Map of special codepoints to key names in kitty protocol+const kittyCodepointNames = {+ 27: 'escape',+ // 13 (return) and 32 (space) are handled before this lookup+ // in parseKittyKeypress so they can be marked as printable.+ 9: 'tab',+ 127: 'backspace',+ 57358: 'capslock',+ 57359: 'scrolllock',+ 57360: 'numlock',+ 57361: 'printscreen',+ 57362: 'pause',+ 57363: 'menu',+ 57376: 'f13',+ 57377: 'f14',+ 57378: 'f15',+ 57379: 'f16',+ 57380: 'f17',+ 57381: 'f18',+ 57382: 'f19',+ 57383: 'f20',+ 57384: 'f21',+ 57385: 'f22',+ 57386: 'f23',+ 57387: 'f24',+ 57388: 'f25',+ 57389: 'f26',+ 57390: 'f27',+ 57391: 'f28',+ 57392: 'f29',+ 57393: 'f30',+ 57394: 'f31',+ 57395: 'f32',+ 57396: 'f33',+ 57397: 'f34',+ 57398: 'f35',+ 57399: 'kp0',+ 57400: 'kp1',+ 57401: 'kp2',+ 57402: 'kp3',+ 57403: 'kp4',+ 57404: 'kp5',+ 57405: 'kp6',+ 57406: 'kp7',+ 57407: 'kp8',+ 57408: 'kp9',+ 57409: 'kpdecimal',+ 57410: 'kpdivide',+ 57411: 'kpmultiply',+ 57412: 'kpsubtract',+ 57413: 'kpadd',+ 57415: 'kpequal',+ 57416: 'kpseparator',+ 57417: 'left',+ 57418: 'right',+ 57419: 'up',+ 57420: 'down',+ 57421: 'pageup',+ 57422: 'pagedown',+ 57423: 'home',+ 57424: 'end',+ 57425: 'insert',+ 57426: 'delete',+ 57428: 'mediaplay',+ 57429: 'mediapause',+ 57430: 'mediaplaypause',+ 57431: 'mediareverse',+ 57432: 'mediastop',+ 57433: 'mediafastforward',+ 57434: 'mediarewind',+ 57435: 'mediatracknext',+ 57436: 'mediatrackprevious',+ 57437: 'mediarecord',+ 57438: 'lowervolume',+ 57439: 'raisevolume',+ 57440: 'mutevolume',+ 57441: 'leftshift',+ 57442: 'leftcontrol',+ 57443: 'leftalt',+ 57444: 'leftsuper',+ 57445: 'lefthyper',+ 57446: 'leftmeta',+ 57447: 'rightshift',+ 57448: 'rightcontrol',+ 57449: 'rightalt',+ 57450: 'rightsuper',+ 57451: 'righthyper',+ 57452: 'rightmeta',+ 57453: 'isoLevel3Shift',+ 57454: 'isoLevel5Shift',+};+// Valid Unicode codepoint range, excluding surrogates+const isValidCodepoint = (cp) => cp >= 0 && cp <= 0x10_ffff && !(cp >= 0xd8_00 && cp <= 0xdf_ff);+const safeFromCodePoint = (cp) => isValidCodepoint(cp) ? String.fromCodePoint(cp) : '?';+function resolveEventType(value) {+ if (value === 3)+ return 'release';+ if (value === 2)+ return 'repeat';+ return 'press';+}+function parseKittyModifiers(modifiers) {+ return {+ ctrl: !!(modifiers & kittyModifiers.ctrl),+ shift: !!(modifiers & kittyModifiers.shift),+ meta: !!(modifiers & (kittyModifiers.meta | kittyModifiers.alt)),+ super: !!(modifiers & kittyModifiers.super),+ hyper: !!(modifiers & kittyModifiers.hyper),+ capsLock: !!(modifiers & kittyModifiers.capsLock),+ numLock: !!(modifiers & kittyModifiers.numLock),+ };+}+const parseKittyKeypress = (s) => {+ const match = kittyKeyRe.exec(s);+ if (!match)+ return null;+ let codepoint = parseInt(match[1], 10);+ // Normalize keypad Enter to the same key and text as Return.+ if (codepoint === 57414) {+ codepoint = 13;+ }+ const modifiers = match[2] ? Math.max(0, parseInt(match[2], 10) - 1) : 0;+ const eventType = match[3] ? parseInt(match[3], 10) : 1;+ const textField = match[4];+ // Bail on invalid primary codepoint+ if (!isValidCodepoint(codepoint)) {+ return null;+ }+ // Parse text-as-codepoints field (colon-separated Unicode codepoints)+ let text;+ if (textField) {+ text = textField+ .split(':')+ .map(cp => safeFromCodePoint(parseInt(cp, 10)))+ .join('');+ }+ // Determine key name from codepoint+ let name;+ let isPrintable;+ if (codepoint === 32) {+ name = 'space';+ isPrintable = true;+ }+ else if (codepoint === 13) {+ name = 'return';+ isPrintable = true;+ }+ else if (kittyCodepointNames[codepoint]) {+ name = kittyCodepointNames[codepoint];+ isPrintable = false;+ }+ else if (codepoint < 32 ||+ (codepoint >= 127 && codepoint <= 159) ||+ (codepoint >= 57344 && codepoint <= 63743)) {+ // Control codes and reserved functional keys do not identify printable characters. Ctrl+letters use their Unicode codepoints, such as 97 for 'a'.+ name = '';+ isPrintable = false;+ }+ else {+ name = safeFromCodePoint(codepoint).toLowerCase();+ isPrintable = true;+ }+ // Default text to the character from the codepoint when not explicitly+ // provided by the protocol, so keys like space and return produce their+ // expected text input (' ' and '\r' respectively).+ if (isPrintable && !text) {+ text = safeFromCodePoint(codepoint);+ }+ return {+ name,+ ...parseKittyModifiers(modifiers),+ eventType: resolveEventType(eventType),+ sequence: s,+ raw: s,+ isKittyProtocol: true,+ isPrintable: isPrintable || text !== undefined,+ text,+ };+};+// Parse kitty-enhanced special key sequences (arrow keys, function keys, etc.)+// These use the legacy CSI format with optional modifiers and :eventType fields.+const parseKittySpecialKey = (s) => {+ const match = kittySpecialKeyRe.exec(s);+ if (!match) {+ return null;+ }+ const number = parseInt(match[1], 10);+ const modifiers = match[2] ? Math.max(0, parseInt(match[2], 10) - 1) : 0;+ const eventType = match[3] ? parseInt(match[3], 10) : 1;+ const terminator = match[4];+ if (terminator !== '~' && number !== 1) {+ return null;+ }+ const name = terminator === '~'+ ? kittySpecialNumberKeys[number]+ : kittySpecialLetterKeys[terminator];+ if (!name) {+ return null;+ }+ return {+ name,+ ...parseKittyModifiers(modifiers),+ eventType: resolveEventType(eventType),+ sequence: s,+ raw: s,+ isKittyProtocol: true,+ isPrintable: false,+ };+};const parseKeypress = (s = '') => {let parts;- if (Buffer.isBuffer(s)) {+ if (s instanceof Uint8Array) {if (s[0] > 127 && s[1] === undefined) {- s[0] -= 128;- s = '\x1b' + String(s);+ // Convert the Meta byte to ASCII without modifying the caller's buffer.+ s = '\x1b' + String.fromCharCode(s[0] - 128);}else {- s = String(s);+ s = textDecoder.decode(s);}}else if (s !== undefined && typeof s !== 'string') {@@ -132,28 +388,58 @@ const parseKeypress = (s = '') => {else if (!s) {s = '';}+ // Try kitty keyboard protocol parsers first+ const kittyResult = parseKittyKeypress(s);+ if (kittyResult)+ return kittyResult;+ const kittySpecialResult = parseKittySpecialKey(s);+ if (kittySpecialResult)+ return kittySpecialResult;+ // If the input matched the kitty CSI-u pattern but was rejected (e.g.,+ // invalid codepoint), return a safe empty keypress instead of falling+ // through to legacy parsing which can produce unsafe states (undefined name)+ if (kittyKeyRe.test(s)) {+ return {+ name: '',+ ctrl: false,+ meta: false,+ shift: false,+ sequence: s,+ raw: s,+ isKittyProtocol: true,+ isPrintable: false,+ };+ }const key = {name: '',ctrl: false,meta: false,shift: false,- option: false,sequence: s,raw: s,};key.sequence = key.sequence || s || key.name;- if (s === '\r') {- // carriage return+ if (s === '\r' || s === '\x1b\r') {+ // carriage return (or meta+return on macOS)+ key.raw = undefined;+ key.name = 'return';+ key.meta = s.length === 2;+ }+ else if (s === '\x1bOM' || s === '\x1b\x1bOM') {+ // Application keypad Enter has the same input value as Return.key.raw = undefined;key.name = 'return';+ key.sequence = '\r';+ key.meta = s.length === 4;}else if (s === '\n') {// enter, should have been called linefeedkey.name = 'enter';}- else if (s === '\t') {+ else if (s === '\t' || s === '\x1b\t') {// tabkey.name = 'tab';+ key.meta = s.length === 2;}else if (s === '\b' || s === '\x1b\b') {// backspace or ctrl+h@@ -161,9 +447,8 @@ const parseKeypress = (s = '') => {key.meta = s.charAt(0) === '\x1b';}else if (s === '\x7f' || s === '\x1b\x7f') {- // TODO(vadimdemedes): `enquirer` detects delete key as backspace, but I had to split them up to avoid breaking changes in Ink. Merge them back together in the next major version.- // delete- key.name = 'delete';+ // backspace+ key.name = 'backspace';key.meta = s.charAt(0) === '\x1b';}else if (s === '\x1b' || s === '\x1b\x1b') {@@ -171,14 +456,17 @@ const parseKeypress = (s = '') => {key.name = 'escape';key.meta = s.length === 2;}- else if (s === ' ' || s === '\x1b ') {+ else if (/^\x1b?[ \x00]$/.test(s)) {key.name = 'space';+ key.ctrl = s.endsWith('\x00');key.meta = s.length === 2;}- else if (s.length === 1 && s <= '\x1a') {- // ctrl+letter- key.name = String.fromCharCode(s.charCodeAt(0) + 'a'.charCodeAt(0) - 1);+ else if (/^\x1b?[\x00-\x1f]$/.test(s)) {+ // ctrl+letter or ctrl+punctuation+ const codepoint = s.charCodeAt(s.length - 1);+ key.name = String.fromCharCode(codepoint + (codepoint <= 26 ? 96 : 64));key.ctrl = true;+ key.meta = s.length === 2;}else if (s.length === 1 && s >= '0' && s <= '9') {// number@@ -195,13 +483,14 @@ const parseKeypress = (s = '') => {}else if ((parts = metaKeyCodeRe.exec(s))) {// meta+character key+ key.name = parts[1].toLowerCase();key.meta = true;key.shift = /^[A-Z]$/.test(parts[1]);}else if ((parts = fnKeyRe.exec(s))) {const segs = [...s];if (segs[0] === '\u001b' && segs[1] === '\u001b') {- key.option = true;+ key.meta = true;}// ansi escape sequence// reassemble the key code leaving out leading \x1b's,@@ -212,10 +501,10 @@ const parseKeypress = (s = '') => {const modifier = (parts[3] || parts[5] || 1) - 1;// Parse the key modifierkey.ctrl = !!(modifier & 4);- key.meta = !!(modifier & 10);+ key.meta = key.meta || !!(modifier & 10);key.shift = !!(modifier & 1);key.code = code;- key.name = keyName[code];+ key.name = keyName[code] ?? '';key.shift = isShiftKey(code) || key.shift;key.ctrl = isCtrlKey(code) || key.ctrl;}diff --git a/vendor/ink/build/reconciler.d.ts b/vendor/ink/build/reconciler.d.tsindex 7f1956d0..7618ba52 100644--- a/vendor/ink/build/reconciler.d.ts+++ b/vendor/ink/build/reconciler.d.ts@@ -1,4 +1,4 @@import createReconciler from 'react-reconciler';import { type TextNode, type DOMElement } from './dom.js';-declare const _default: createReconciler.Reconciler<DOMElement, DOMElement, TextNode, DOMElement, unknown>;+declare const _default: createReconciler.Reconciler<DOMElement, DOMElement, TextNode, DOMElement, unknown, unknown>;export default _default;diff --git a/vendor/ink/build/reconciler.js b/vendor/ink/build/reconciler.jsindex 59302327..551dfef7 100644--- a/vendor/ink/build/reconciler.js+++ b/vendor/ink/build/reconciler.js@@ -1,31 +1,24 @@import process from 'node:process';import createReconciler from 'react-reconciler';-import { DefaultEventPriority } from 'react-reconciler/constants.js';-import Yoga from 'yoga-layout';-import { createTextNode, appendChildNode, insertBeforeNode, removeChildNode, setStyle, setTextNodeValue, createNode, setAttribute, } from './dom.js';+import { DefaultEventPriority, NoEventPriority, } from 'react-reconciler/constants.js';+import { createContext, version as reactVersion } from 'react';+import { createTextNode, appendChildNode, insertBeforeNode, removeChildNode, freeYogaSubtree, emitLayoutListeners, setTransform, setStyle, setTextNodeValue, setNodeHidden, createNode, setAttribute, } from './dom.js';import applyStyles from './styles.js';// We need to conditionally perform devtools connection to avoid// accidentally breaking other third-party code.// See https://github.com/vadimdemedes/ink/issues/384+// See https://github.com/vadimdemedes/ink/issues/648if (process.env['DEV'] === 'true') {+ // Intentionally no warning when the package is missing.+ // DEV may be set for other reasons; devtools is opt-in via installing the package.+ let isDevtoolsInstalled = false;try {- await import('./devtools.js');+ import.meta.resolve('react-devtools-core');+ isDevtoolsInstalled = true;}- catch (error) {- if (error.code === 'ERR_MODULE_NOT_FOUND') {- console.warn(`-The environment variable DEV is set to true, so Ink tried to import \`react-devtools-core\`,-but this failed as it was not installed. Debugging with React Devtools requires it.--To install use this command:--$ npm install --save-dev react-devtools-core- `.trim() + '\n');- }- else {- // eslint-disable-next-line @typescript-eslint/only-throw-error- throw error;- }+ catch { }+ if (isDevtoolsInstalled) {+ await import('./devtools.js');}}const diff = (before, after) => {@@ -36,64 +29,107 @@ const diff = (before, after) => {return after;}const changed = {};- let isChanged = false;+ let hasChanges = false;for (const key of Object.keys(before)) {const isDeleted = after ? !Object.hasOwn(after, key) : true;- if (isDeleted) {- changed[key] = undefined;- isChanged = true;+ if (!isDeleted) {+ continue;}+ changed[key] = undefined;+ hasChanges = true;}if (after) {- for (const key of Object.keys(after)) {- if (after[key] !== before[key]) {- changed[key] = after[key];- isChanged = true;+ for (const [key, value] of Object.entries(after)) {+ if (value === before[key]) {+ continue;}+ changed[key] = value;+ hasChanges = true;}}- return isChanged ? changed : undefined;-};-const cleanupYogaNode = (node) => {- node?.unsetMeasureFunc();- node?.freeRecursive();+ return hasChanges ? changed : undefined;};-// `freeRecursive` releases Yoga's WASM memory but leaves every JavaScript-// reference pointing at freed memory. The renderer and layout code read those-// references through optional chaining, so nulling them here turns what was a-// fatal WASM trap ("RuntimeError: memory access out of bounds" in-// getComputedWidth) into a clean no-op. See facebook/yoga#1818 and the-// equivalent downstream fix in qwen-code#7816. (Cosmic Stack patch.)-const clearYogaRefs = (node) => {- node.yogaNode = undefined;- // Host elements carry a childNodes array; ink's `#text` nodes do not.- if (Array.isArray(node.childNodes)) {- for (const child of node.childNodes) {- clearYogaRefs(child);+const findRootNode = (node) => {+ let current = node;+ while (current) {+ if (current.nodeName === 'ink-root') {+ return current;}+ current = current.parentNode;}+ return undefined;};-const containsNode = (ancestor, target) => {- let current = target;+/**+Clear the root's cached `staticNode` when the node it points at is being removed as part of a larger subtree.++The previous identity check (`staticNode === removeNode`) only caught direct removal of the `<Static>` element. When an *ancestor* of `<Static>` is removed, the stale `staticNode` reference survives and the next render would replay stale static output (and, before `freeYogaSubtree`, trap on freed WASM memory, see QwenLM/qwen-code#6820).++The owning root is derived from the host parent passed to the removal hook, not a module-level global, so instances with separate stdout streams don't clobber each other's pointers.+*/+const clearStaticNodeIfContained = (rootNode, removedNode) => {+ if (!rootNode?.staticNode) {+ return;+ }+ // Walk up from staticNode to see if removedNode is an ancestor.+ let current = rootNode.staticNode;while (current) {- if (current === ancestor) return true;+ if (current === removedNode) {+ // Only clear staticNode, not previousStaticNode. The inequality+ // (undefined !== previousStaticNode) triggers onStaticChange in+ // resetAfterCommit, which resets the accumulated static output.+ rootNode.staticNode = undefined;+ return;+ }current = current.parentNode;}- return false;};-const cleanupRemovedNode = (node, removeNode) => {- cleanupYogaNode(removeNode.yogaNode);- clearYogaRefs(removeNode);- // `staticNode` is cached on the root container, but removeChild receives- // the direct parent — climb to the root before checking.- let rootNode = node;- while (rootNode?.parentNode) rootNode = rootNode.parentNode;- if (rootNode?.staticNode && containsNode(removeNode, rootNode.staticNode)) {- rootNode.staticNode = undefined;+const findStaticNode = (node) => {+ if (node.internal_static) {+ return node;+ }+ for (const child of node.childNodes) {+ if (child.nodeName === '#text') {+ continue;+ }+ const staticNode = findStaticNode(child);+ if (staticNode) {+ return staticNode;+ }}+ return undefined;};-globalThis.__mercuryInkYogaHygiene = true;-export default createReconciler({+let currentUpdatePriority = NoEventPriority;+async function loadPackageJson() {+ const fs = await import('node:fs');+ const content = fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8');+ const parsedContent = JSON.parse(content);+ return {+ name: parsedContent?.name,+ version: parsedContent?.version,+ };+}+let packageInfo = {+ name: 'ink',+ version: reactVersion,+};+if (process.env['DEV'] === 'true') {+ try {+ const loaded = await loadPackageJson();+ packageInfo = {+ name: loaded.name === undefined || loaded.name === ''+ ? packageInfo.name+ : loaded.name,+ version: loaded.version === undefined || loaded.version === ''+ ? packageInfo.version+ : loaded.version,+ };+ }+ catch (error) {+ console.warn('Failed to load package.json in development mode. Falling back to default renderer metadata.', error);+ }+}+// eslint-disable-next-line @eslint-react/naming-convention-context-name -- This is the React reconciler host config, not a React context.+const hostConfig = {getRootHostContext: () => ({isInsideText: false,}),@@ -101,9 +137,25 @@ export default createReconciler({preparePortalMount: () => null,clearContainer: () => false,resetAfterCommit(rootNode) {+ // Save the <Static> reference from the committed tree so rendering can access it directly. createInstance also runs for abandoned transitions and must not replace the committed reference.+ const staticNode = findStaticNode(rootNode);+ rootNode.staticNode = staticNode;+ if (staticNode !== rootNode.previousStaticNode) {+ rootNode.isStaticDirty = true;+ }if (typeof rootNode.onComputeLayout === 'function') {rootNode.onComputeLayout();}+ emitLayoutListeners(rootNode);+ /*+ Fire `onStaticChange` BEFORE `onImmediateRender` so ink resets accumulated static output before the new instance emits. Without this, items from a replaced/removed <Static> stay in `fullStaticOutput` (debug mode) and `hasRenderedStaticOutput` stays set, skipping the final unmount render for the new instance.+ */+ if (rootNode.staticNode !== rootNode.previousStaticNode) {+ rootNode.previousStaticNode = rootNode.staticNode;+ if (typeof rootNode.onStaticChange === 'function') {+ rootNode.onStaticChange();+ }+ }// Since renders are throttled at the instance level and <Static> component children// are rendered only once and then get deleted, we need an escape hatch to// trigger an immediate render to ensure <Static> children are written to output before they get erased@@ -119,17 +171,14 @@ export default createReconciler({}},getChildHostContext(parentHostContext, type) {- const previousIsInsideText = parentHostContext.isInsideText;+ const wasInsideText = parentHostContext.isInsideText;const isInsideText = type === 'ink-text' || type === 'ink-virtual-text';- if (previousIsInsideText === isInsideText) {- return parentHostContext;- }- return { isInsideText };+ return wasInsideText === isInsideText ? parentHostContext : { isInsideText };},shouldSetTextContent: () => false,- createInstance(originalType, newProps, _root, hostContext) {- if (hostContext.isInsideText && originalType === 'ink-box') {- throw new Error(`<Box> can’t be nested inside <Text> component`);+ createInstance(originalType, newProps, _rootNode, hostContext) {+ if (originalType === 'ink-box' && hostContext.isInsideText) {+ throw new Error('<Box> can’t be nested inside <Text> component');}const type = originalType === 'ink-text' && hostContext.isInsideText? 'ink-virtual-text'@@ -173,55 +222,56 @@ export default createReconciler({},getPublicInstance: instance => instance,hideInstance(node) {- node.yogaNode?.setDisplay(Yoga.DISPLAY_NONE);+ setNodeHidden(node, true);},unhideInstance(node) {- node.yogaNode?.setDisplay(Yoga.DISPLAY_FLEX);+ setNodeHidden(node, false);},appendInitialChild: appendChildNode,appendChild: appendChildNode,insertBefore: insertBeforeNode,- finalizeInitialChildren(node, _type, _props, rootNode) {- if (node.internal_static) {- rootNode.isStaticDirty = true;- // Save reference to <Static> node to skip traversal of entire- // node tree to find it- rootNode.staticNode = node;- }+ finalizeInitialChildren() {return false;},isPrimaryRenderer: true,supportsMutation: true,supportsPersistence: false,supportsHydration: false,+ // Scheduler integration for concurrent mode+ supportsMicrotasks: true,+ scheduleMicrotask: queueMicrotask,scheduleTimeout: setTimeout,cancelTimeout: clearTimeout,noTimeout: -1,- getCurrentEventPriority: () => DefaultEventPriority,beforeActiveInstanceBlur() { },afterActiveInstanceBlur() { },detachDeletedInstance() { },getInstanceFromNode: () => null,+ // Fragment refs (React 19.3) have no meaning in a terminal. Returning null makes a `<Fragment ref>` resolve to null instead of crashing inside React, and keeps React from calling the other fragment-instance hooks.+ createFragmentInstance: () => null,prepareScopeUpdate() { },getInstanceFromScope: () => null,appendChildToContainer: appendChildNode,insertInContainerBefore: insertBeforeNode,- removeChildFromContainer(node, removeNode) {- removeChildNode(node, removeNode);- cleanupRemovedNode(node, removeNode);+ removeChildFromContainer(node, removedNode) {+ // `node` is the container, i.e. the root itself. Clear before+ // removeChildNode breaks the parent chain.+ clearStaticNodeIfContained(findRootNode(node), removedNode);+ removeChildNode(node, removedNode);+ freeYogaSubtree(removedNode);},- prepareUpdate(node, _type, oldProps, newProps, rootNode) {+ commitUpdate(node, _type, oldProps, newProps) {if (node.internal_static) {- rootNode.isStaticDirty = true;+ const rootNode = findRootNode(node);+ if (rootNode) {+ rootNode.isStaticDirty = true;+ }}const props = diff(oldProps, newProps);const style = diff(oldProps['style'], newProps['style']);if (!props && !style) {- return null;+ return;}- return { props, style };- },- commitUpdate(node, { props, style }) {if (props) {for (const [key, value] of Object.entries(props)) {if (key === 'style') {@@ -229,7 +279,7 @@ export default createReconciler({continue;}if (key === 'internal_transform') {- node.internal_transform = value;+ setTransform(node, value);continue;}if (key === 'internal_static') {@@ -240,14 +290,73 @@ export default createReconciler({}}if (style && node.yogaNode) {- applyStyles(node.yogaNode, style);+ applyStyles(node.yogaNode, style, newProps['style'] ?? {});}},commitTextUpdate(node, _oldText, newText) {setTextNodeValue(node, newText);},- removeChild(node, removeNode) {- removeChildNode(node, removeNode);- cleanupRemovedNode(node, removeNode);+ removeChild(node, removedNode) {+ // `node` is the host parent; its chain up to the root is still intact+ // here, so derive the owning root from it rather than a global.+ clearStaticNodeIfContained(findRootNode(node), removedNode);+ removeChildNode(node, removedNode);+ freeYogaSubtree(removedNode);+ },+ setCurrentUpdatePriority(newPriority) {+ currentUpdatePriority = newPriority;+ },+ getCurrentUpdatePriority: () => currentUpdatePriority,+ resolveUpdatePriority() {+ return currentUpdatePriority === NoEventPriority+ ? DefaultEventPriority+ : currentUpdatePriority;+ },+ maySuspendCommit() {+ // Return true to enable Suspense resource preloading+ return true;+ },+ // Terminal host instances have no asynchronous resources to wait for on updates.+ maySuspendCommitOnUpdate: () => false,+ maySuspendCommitInSyncRender: () => false,+ // eslint-disable-next-line @typescript-eslint/naming-convention+ NotPendingTransition: undefined,+ // eslint-disable-next-line @typescript-eslint/naming-convention+ HostTransitionContext: createContext(null),+ resetFormInstance() { },+ requestPostPaintCallback() { },+ shouldAttemptEagerTransition() {+ return false;+ },+ trackSchedulerEvent() { },+ resolveEventType() {+ return null;},-});+ resolveEventTimeStamp() {+ return -1.1;+ },+ preloadInstance() {+ return true;+ },+ startSuspendingCommit() { },+ suspendInstance() { },+ // Called for every transition-lane render since React 19.3. Ink has no view transitions, so there is never anything to wait for.+ suspendOnActiveViewTransition() { },+ waitForCommitToBeReady() {+ return null;+ },+ getSuspendedCommitReason: () => null,+ extraDevToolsConfig: null,+ bindToConsole(methodName, args) {+ // Replay React's captured console calls without browser-specific badge styling.+ const method = Reflect.get(console, methodName);+ return () => {+ if (typeof method === 'function') {+ Reflect.apply(method, console, args);+ }+ };+ },+ rendererPackageName: packageInfo.name,+ rendererVersion: packageInfo.version,+};+export default createReconciler(hostConfig);diff --git a/vendor/ink/build/render-background.d.ts b/vendor/ink/build/render-background.d.tsnew file mode 100644index 00000000..baf8b84f--- /dev/null+++ b/vendor/ink/build/render-background.d.ts@@ -0,0 +1,4 @@+import { type DOMNode } from './dom.js';+import type Output from './output.js';+declare const renderBackground: (x: number, y: number, node: DOMNode, output: Output) => void;+export default renderBackground;diff --git a/vendor/ink/build/render-background.js b/vendor/ink/build/render-background.jsnew file mode 100644index 00000000..a7238bba--- /dev/null+++ b/vendor/ink/build/render-background.js@@ -0,0 +1,26 @@+import colorize from './colorize.js';+const renderBackground = (x, y, node, output) => {+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions -- JavaScript callers pass `null` or `false` (for example `condition && 'red'`), and any falsy value means unset.+ if (!node.style.backgroundColor) {+ return;+ }+ const width = node.yogaNode.getComputedWidth();+ const height = node.yogaNode.getComputedHeight();+ // Calculate the actual content area considering borders+ const hasBorder = Boolean(node.style.borderStyle);+ const leftBorderWidth = hasBorder && node.style.borderLeft !== false ? 1 : 0;+ const rightBorderWidth = hasBorder && node.style.borderRight !== false ? 1 : 0;+ const topBorderHeight = hasBorder && node.style.borderTop !== false ? 1 : 0;+ const bottomBorderHeight = hasBorder && node.style.borderBottom !== false ? 1 : 0;+ const contentWidth = width - leftBorderWidth - rightBorderWidth;+ const contentHeight = height - topBorderHeight - bottomBorderHeight;+ if (!(contentWidth > 0 && contentHeight > 0)) {+ return;+ }+ // Create background fill for each row+ const backgroundLine = colorize(' '.repeat(contentWidth), node.style.backgroundColor, 'background');+ for (let row = 0; row < contentHeight; row++) {+ output.write(x + leftBorderWidth, y + topBorderHeight + row, backgroundLine, { transformers: [] });+ }+};+export default renderBackground;diff --git a/vendor/ink/build/render-border.js b/vendor/ink/build/render-border.jsindex 18970e21..e6ff2f52 100644--- a/vendor/ink/build/render-border.js+++ b/vendor/ink/build/render-border.js@@ -1,72 +1,84 @@import cliBoxes from 'cli-boxes';import chalk from 'chalk';import colorize from './colorize.js';+const stylePiece = (segment, fg, bg, isDim) => {+ let styled = colorize(segment, fg, 'foreground');+ styled = colorize(styled, bg, 'background');+ if (isDim) {+ styled = chalk.dim(styled);+ }+ return styled;+};const renderBorder = (x, y, node, output) => {- if (node.style.borderStyle) {- const width = node.yogaNode.getComputedWidth();- const height = node.yogaNode.getComputedHeight();- const box = typeof node.style.borderStyle === 'string'- ? cliBoxes[node.style.borderStyle]- : node.style.borderStyle;- const topBorderColor = node.style.borderTopColor ?? node.style.borderColor;- const bottomBorderColor = node.style.borderBottomColor ?? node.style.borderColor;- const leftBorderColor = node.style.borderLeftColor ?? node.style.borderColor;- const rightBorderColor = node.style.borderRightColor ?? node.style.borderColor;- const dimTopBorderColor = node.style.borderTopDimColor ?? node.style.borderDimColor;- const dimBottomBorderColor = node.style.borderBottomDimColor ?? node.style.borderDimColor;- const dimLeftBorderColor = node.style.borderLeftDimColor ?? node.style.borderDimColor;- const dimRightBorderColor = node.style.borderRightDimColor ?? node.style.borderDimColor;- const showTopBorder = node.style.borderTop !== false;- const showBottomBorder = node.style.borderBottom !== false;- const showLeftBorder = node.style.borderLeft !== false;- const showRightBorder = node.style.borderRight !== false;- const contentWidth = width - (showLeftBorder ? 1 : 0) - (showRightBorder ? 1 : 0);- let topBorder = showTopBorder- ? colorize((showLeftBorder ? box.topLeft : '') +- box.top.repeat(contentWidth) +- (showRightBorder ? box.topRight : ''), topBorderColor, 'foreground')- : undefined;- if (showTopBorder && dimTopBorderColor) {- topBorder = chalk.dim(topBorder);- }- let verticalBorderHeight = height;- if (showTopBorder) {- verticalBorderHeight -= 1;- }- if (showBottomBorder) {- verticalBorderHeight -= 1;- }- let leftBorder = (colorize(box.left, leftBorderColor, 'foreground') + '\n').repeat(verticalBorderHeight);- if (dimLeftBorderColor) {- leftBorder = chalk.dim(leftBorder);- }- let rightBorder = (colorize(box.right, rightBorderColor, 'foreground') + '\n').repeat(verticalBorderHeight);- if (dimRightBorderColor) {- rightBorder = chalk.dim(rightBorder);- }- let bottomBorder = showBottomBorder- ? colorize((showLeftBorder ? box.bottomLeft : '') +- box.bottom.repeat(contentWidth) +- (showRightBorder ? box.bottomRight : ''), bottomBorderColor, 'foreground')- : undefined;- if (showBottomBorder && dimBottomBorderColor) {- bottomBorder = chalk.dim(bottomBorder);- }- const offsetY = showTopBorder ? 1 : 0;- if (topBorder) {- output.write(x, y, topBorder, { transformers: [] });- }- if (showLeftBorder) {- output.write(x, y + offsetY, leftBorder, { transformers: [] });- }- if (showRightBorder) {- output.write(x + width - 1, y + offsetY, rightBorder, {- transformers: [],- });- }- if (bottomBorder) {- output.write(x, y + height - 1, bottomBorder, { transformers: [] });- }+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions -- JavaScript callers pass `null` or `false` (for example `condition && 'round'`), and any falsy value means unset.+ if (!node.style.borderStyle) {+ return;+ }+ const width = node.yogaNode.getComputedWidth();+ const height = node.yogaNode.getComputedHeight();+ const box = typeof node.style.borderStyle === 'string'+ ? cliBoxes[node.style.borderStyle]+ : node.style.borderStyle;+ const topBorderColor = node.style.borderTopColor ?? node.style.borderColor;+ const bottomBorderColor = node.style.borderBottomColor ?? node.style.borderColor;+ const leftBorderColor = node.style.borderLeftColor ?? node.style.borderColor;+ const rightBorderColor = node.style.borderRightColor ?? node.style.borderColor;+ const topBorderBackgroundColor = node.style.borderTopBackgroundColor ?? node.style.borderBackgroundColor;+ const bottomBorderBackgroundColor = node.style.borderBottomBackgroundColor ?? node.style.borderBackgroundColor;+ const leftBorderBackgroundColor = node.style.borderLeftBackgroundColor ?? node.style.borderBackgroundColor;+ const rightBorderBackgroundColor = node.style.borderRightBackgroundColor ?? node.style.borderBackgroundColor;+ const dimTopBorderColor = node.style.borderTopDimColor ?? node.style.borderDimColor;+ const dimBottomBorderColor = node.style.borderBottomDimColor ?? node.style.borderDimColor;+ const dimLeftBorderColor = node.style.borderLeftDimColor ?? node.style.borderDimColor;+ const dimRightBorderColor = node.style.borderRightDimColor ?? node.style.borderDimColor;+ const shouldShowTopBorder = node.style.borderTop !== false;+ const shouldShowBottomBorder = node.style.borderBottom !== false;+ const shouldShowLeftBorder = node.style.borderLeft !== false;+ const shouldShowRightBorder = node.style.borderRight !== false;+ const contentWidth = width - (shouldShowLeftBorder ? 1 : 0) - (shouldShowRightBorder ? 1 : 0);+ let topBorder = shouldShowTopBorder+ ? (shouldShowLeftBorder ? box.topLeft : '') ++ box.top.repeat(contentWidth) ++ (shouldShowRightBorder ? box.topRight : '')+ : undefined;+ topBorder &&= stylePiece(topBorder, topBorderColor, topBorderBackgroundColor, dimTopBorderColor);+ let verticalBorderHeight = height;+ if (shouldShowTopBorder) {+ verticalBorderHeight -= 1;+ }+ if (shouldShowBottomBorder) {+ verticalBorderHeight -= 1;+ }+ let leftBorder = '';+ if (shouldShowLeftBorder) {+ const one = stylePiece(box.left, leftBorderColor, leftBorderBackgroundColor, dimLeftBorderColor);+ leftBorder = (one + '\n').repeat(verticalBorderHeight);+ }+ let rightBorder = '';+ if (shouldShowRightBorder) {+ const one = stylePiece(box.right, rightBorderColor, rightBorderBackgroundColor, dimRightBorderColor);+ rightBorder = (one + '\n').repeat(verticalBorderHeight);+ }+ let bottomBorder = shouldShowBottomBorder+ ? (shouldShowLeftBorder ? box.bottomLeft : '') ++ box.bottom.repeat(contentWidth) ++ (shouldShowRightBorder ? box.bottomRight : '')+ : undefined;+ bottomBorder &&= stylePiece(bottomBorder, bottomBorderColor, bottomBorderBackgroundColor, dimBottomBorderColor);+ const offsetY = shouldShowTopBorder ? 1 : 0;+ if (topBorder !== undefined && topBorder !== '') {+ output.write(x, y, topBorder, { transformers: [] });+ }+ if (leftBorder !== '') {+ output.write(x, y + offsetY, leftBorder, { transformers: [] });+ }+ if (rightBorder !== '') {+ output.write(x + width - 1, y + offsetY, rightBorder, {+ transformers: [],+ });+ }+ if (bottomBorder !== undefined && bottomBorder !== '') {+ output.write(x, y + height - 1, bottomBorder, { transformers: [] });}};export default renderBorder;diff --git a/vendor/ink/build/render-node-to-output.d.ts b/vendor/ink/build/render-node-to-output.d.tsindex 7dd9eaa7..127c6205 100644--- a/vendor/ink/build/render-node-to-output.d.ts+++ b/vendor/ink/build/render-node-to-output.d.ts@@ -1,6 +1,10 @@import { type DOMElement } from './dom.js';import type Output from './output.js';export type OutputTransformer = (s: string, index: number) => string;+export declare const renderNodeToScreenReaderOutput: (node: DOMElement, options?: {+ parentRole?: string;+ skipStaticElements?: boolean;+}) => string;declare const renderNodeToOutput: (node: DOMElement, output: Output, options: {offsetX?: number;offsetY?: number;diff --git a/vendor/ink/build/render-node-to-output.js b/vendor/ink/build/render-node-to-output.jsindex 46dad67f..b7b6a87c 100644--- a/vendor/ink/build/render-node-to-output.js+++ b/vendor/ink/build/render-node-to-output.js@@ -5,6 +5,7 @@ import wrapText from './wrap-text.js';import getMaxWidth from './get-max-width.js';import squashTextNodes from './squash-text-nodes.js';import renderBorder from './render-border.js';+import renderBackground from './render-background.js';// If parent container is `<Box>`, text nodes will be treated as separate nodes in// the tree and will have their own coordinates in the layout.// To ensure text nodes are aligned correctly, take X and Y of the first text node@@ -12,7 +13,7 @@ import renderBorder from './render-border.js';// Only first node is taken into account, because other text nodes can't have margin or padding,// so their coordinates will be relative to the first node anywayconst applyPaddingToText = (node, text) => {- const yogaNode = node.childNodes[0]?.yogaNode;+ const yogaNode = node.childNodes.at(0)?.yogaNode;if (yogaNode) {const offsetX = yogaNode.getComputedLeft();const offsetY = yogaNode.getComputedTop();@@ -20,6 +21,52 @@ const applyPaddingToText = (node, text) => {}return text;};+// Content offsets end up as terminal cell coordinates, so they have to be whole numbers. Fractions would drop or duplicate cells and non-finite values would erase content entirely.+const normalizeContentOffset = (value) => typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : 0;+export const renderNodeToScreenReaderOutput = (node, options = {}) => {+ if (Boolean(options.skipStaticElements && node.internal_static) ||+ node.yogaNode?.getDisplay() === Yoga.DISPLAY_NONE) {+ return '';+ }+ let output = '';+ if (node.nodeName === 'ink-text') {+ output = squashTextNodes(node);+ }+ else if (node.nodeName === 'ink-box' || node.nodeName === 'ink-root') {+ const separator = node.style.flexDirection === 'row' ||+ node.style.flexDirection === 'row-reverse'+ ? ' '+ : '\n';+ const childNodes = node.style.flexDirection === 'row-reverse' ||+ node.style.flexDirection === 'column-reverse'+ ? [...node.childNodes].reverse()+ : [...node.childNodes];+ output = childNodes+ .map(childNode => {+ const screenReaderOutput = renderNodeToScreenReaderOutput(childNode, {+ parentRole: node.internal_accessibility?.role,+ skipStaticElements: options.skipStaticElements,+ });+ return screenReaderOutput;+ })+ .filter(Boolean)+ .join(separator);+ }+ if (node.internal_accessibility) {+ const { role, state } = node.internal_accessibility;+ if (state) {+ const stateKeys = Object.keys(state);+ const stateDescription = stateKeys.filter(key => state[key]).join(', ');+ if (stateDescription !== '') {+ output = `(${stateDescription}) ${output}`;+ }+ }+ if (Boolean(role) && role !== options.parentRole) {+ output = `${role}: ${output}`;+ }+ }+ return output;+};// After nodes are laid out, render each to output object, which later gets rendered to terminalconst renderNodeToOutput = (node, output, options) => {const { offsetX = 0, offsetY = 0, transformers = [], skipStaticElements, } = options;@@ -27,72 +74,71 @@ const renderNodeToOutput = (node, output, options) => {return;}const { yogaNode } = node;- if (yogaNode) {- if (yogaNode.getDisplay() === Yoga.DISPLAY_NONE) {- return;- }- // Left and top positions in Yoga are relative to their parent node- const x = offsetX + yogaNode.getComputedLeft();- const y = offsetY + yogaNode.getComputedTop();- // Transformers are functions that transform final text output of each component- // See Output class for logic that applies transformers- let newTransformers = transformers;- if (typeof node.internal_transform === 'function') {- newTransformers = [node.internal_transform, ...transformers];- }- if (node.nodeName === 'ink-text') {- let text = squashTextNodes(node);- if (text.length > 0) {- const currentWidth = widestLine(text);- const maxWidth = getMaxWidth(yogaNode);- if (currentWidth > maxWidth) {- const textWrap = node.style.textWrap ?? 'wrap';- text = wrapText(text, maxWidth, textWrap);- }- text = applyPaddingToText(node, text);- output.write(x, y, text, { transformers: newTransformers });- }- return;- }- let clipped = false;- if (node.nodeName === 'ink-box') {- renderBorder(x, y, node, output);- const clipHorizontally = node.style.overflowX === 'hidden' || node.style.overflow === 'hidden';- const clipVertically = node.style.overflowY === 'hidden' || node.style.overflow === 'hidden';- if (clipHorizontally || clipVertically) {- const x1 = clipHorizontally- ? x + yogaNode.getComputedBorder(Yoga.EDGE_LEFT)- : undefined;- const x2 = clipHorizontally- ? x +- yogaNode.getComputedWidth() -- yogaNode.getComputedBorder(Yoga.EDGE_RIGHT)- : undefined;- const y1 = clipVertically- ? y + yogaNode.getComputedBorder(Yoga.EDGE_TOP)- : undefined;- const y2 = clipVertically- ? y +- yogaNode.getComputedHeight() -- yogaNode.getComputedBorder(Yoga.EDGE_BOTTOM)- : undefined;- output.clip({ x1, x2, y1, y2 });- clipped = true;+ if (!yogaNode || yogaNode.getDisplay() === Yoga.DISPLAY_NONE) {+ return;+ }+ // Left and top positions in Yoga are relative to their parent node+ const x = offsetX + yogaNode.getComputedLeft();+ const y = offsetY + yogaNode.getComputedTop();+ // Transformers are functions that transform final text output of each component+ // See Output class for logic that applies transformers+ const newTransformers = typeof node.internal_transform === 'function'+ ? [node.internal_transform, ...transformers]+ : transformers;+ if (node.nodeName === 'ink-text') {+ let text = squashTextNodes(node);+ if (text.length > 0) {+ const currentWidth = widestLine(text);+ const maxWidth = getMaxWidth(yogaNode);+ if (currentWidth > maxWidth) {+ const textWrap = node.style.textWrap ?? 'wrap';+ text = wrapText(text, maxWidth, textWrap);}+ text = applyPaddingToText(node, text);+ output.write(x, y, text, { transformers: newTransformers });}- if (node.nodeName === 'ink-root' || node.nodeName === 'ink-box') {- for (const childNode of node.childNodes) {- renderNodeToOutput(childNode, output, {- offsetX: x,- offsetY: y,- transformers: newTransformers,- skipStaticElements,- });- }- if (clipped) {- output.unclip();- }+ return;+ }+ let isClipped = false;+ if (node.nodeName === 'ink-box') {+ renderBackground(x, y, node, output);+ renderBorder(x, y, node, output);+ const shouldClipHorizontally = (node.style.overflowX ?? node.style.overflow) === 'hidden';+ const shouldClipVertically = (node.style.overflowY ?? node.style.overflow) === 'hidden';+ if (shouldClipHorizontally || shouldClipVertically) {+ const x1 = shouldClipHorizontally+ ? x + yogaNode.getComputedBorder(Yoga.EDGE_LEFT)+ : undefined;+ const x2 = shouldClipHorizontally+ ? x ++ yogaNode.getComputedWidth() -+ yogaNode.getComputedBorder(Yoga.EDGE_RIGHT)+ : undefined;+ const y1 = shouldClipVertically+ ? y + yogaNode.getComputedBorder(Yoga.EDGE_TOP)+ : undefined;+ const y2 = shouldClipVertically+ ? y ++ yogaNode.getComputedHeight() -+ yogaNode.getComputedBorder(Yoga.EDGE_BOTTOM)+ : undefined;+ output.clip({ x1, x2, y1, y2 });+ isClipped = true;}}+ if (!(node.nodeName === 'ink-root' || node.nodeName === 'ink-box')) {+ return;+ }+ for (const childNode of node.childNodes) {+ renderNodeToOutput(childNode, output, {+ offsetX: x - normalizeContentOffset(node.style.contentOffsetX),+ offsetY: y - normalizeContentOffset(node.style.contentOffsetY),+ transformers: newTransformers,+ skipStaticElements,+ });+ }+ if (isClipped) {+ output.unclip();+ }};export default renderNodeToOutput;diff --git a/vendor/ink/build/render-to-string.d.ts b/vendor/ink/build/render-to-string.d.tsnew file mode 100644index 00000000..afbb08c7--- /dev/null+++ b/vendor/ink/build/render-to-string.d.ts@@ -0,0 +1,38 @@+import { type ReactNode } from 'react';+export type RenderToStringOptions = {+ /**+ Width of the virtual terminal in columns.++ @default 80+ */+ columns?: number;+};+/**+Render a React element to a string synchronously. Unlike `render()`, this function does not write to stdout, does not set up any terminal event listeners, and returns the rendered output as a string.++Useful for generating documentation, writing output to files, testing, or any scenario where you need the rendered output as a string without starting a persistent terminal application.++**Notes:**++- Terminal-specific hooks (`useInput`, `useStdin`, `useStdout`, `useStderr`, `useApp`, `useFocus`, `useFocusManager`) return default no-op values since there is no terminal session. They will not throw, but they will not function as in a live terminal.+- `useEffect` callbacks will execute during rendering (due to synchronous rendering mode), but state updates they trigger will not affect the returned output, which reflects the initial render.+- `useLayoutEffect` callbacks fire synchronously during commit, so state updates they trigger **will** be reflected in the output.+- The `<Static>` component is supported — its output is prepended to the dynamic output.+- If a component throws during rendering, the error is propagated to the caller after cleanup.++@example+```+import {renderToString, Text, Box} from 'ink';++const output = renderToString(+ <Box padding={1}>+ <Text color="green">Hello World</Text>+ </Box>,+ {columns: 40}+);++console.log(output);+```+*/+declare const renderToString: (node: ReactNode, options?: RenderToStringOptions) => string;+export default renderToString;diff --git a/vendor/ink/build/render-to-string.js b/vendor/ink/build/render-to-string.jsnew file mode 100644index 00000000..813a8e28--- /dev/null+++ b/vendor/ink/build/render-to-string.js@@ -0,0 +1,131 @@+import { types } from 'node:util';+import { createElement } from 'react';+import Yoga from 'yoga-layout';+import { LegacyRoot } from 'react-reconciler/constants.js';+import reconciler from './reconciler.js';+import renderer from './renderer.js';+import { createNode } from './dom.js';+import RootNodeContext from './components/RootNodeContext.js';+/* eslint-disable jsdoc/require-asterisk-prefix -- `**Notes:**` is Markdown bold text, not a line prefix. */+/**+Render a React element to a string synchronously. Unlike `render()`, this function does not write to stdout, does not set up any terminal event listeners, and returns the rendered output as a string.++Useful for generating documentation, writing output to files, testing, or any scenario where you need the rendered output as a string without starting a persistent terminal application.++**Notes:**++- Terminal-specific hooks (`useInput`, `useStdin`, `useStdout`, `useStderr`, `useApp`, `useFocus`, `useFocusManager`) return default no-op values since there is no terminal session. They will not throw, but they will not function as in a live terminal.+- `useEffect` callbacks will execute during rendering (due to synchronous rendering mode), but state updates they trigger will not affect the returned output, which reflects the initial render.+- `useLayoutEffect` callbacks fire synchronously during commit, so state updates they trigger **will** be reflected in the output.+- The `<Static>` component is supported — its output is prepended to the dynamic output.+- If a component throws during rendering, the error is propagated to the caller after cleanup.++@example+```+import {renderToString, Text, Box} from 'ink';++const output = renderToString(+ <Box padding={1}>+ <Text color="green">Hello World</Text>+ </Box>,+ {columns: 40}+);++console.log(output);+```+*/+/* eslint-enable jsdoc/require-asterisk-prefix */+const renderToString = (node, options) => {+ const columns = options?.columns ?? 80;+ // Create a standalone root node — no stdout, stdin, or terminal bindings+ const rootNode = createNode('ink-root');+ // Capture static output from intermediate renders.+ // The <Static> component uses useLayoutEffect to clear its children after+ // the first commit. The reconciler's resetAfterCommit calls onImmediateRender+ // when static content is dirty (and returns early, skipping the normal+ // onRender callback), giving us a chance to capture it before it's cleared+ // by the subsequent re-render.+ let capturedStaticOutput = '';+ rootNode.onStaticChange = () => {+ capturedStaticOutput = '';+ };+ rootNode.onComputeLayout = () => {+ rootNode.yogaNode.setWidth(columns);+ rootNode.yogaNode.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);+ };+ rootNode.onImmediateRender = () => {+ const { staticOutput } = renderer(rootNode, false);+ if (staticOutput !== '') {+ capturedStaticOutput += staticOutput;+ }+ };+ // Capture the first uncaught error so we can re-throw it after cleanup.+ // React's reconciler catches component errors internally and reports them+ // via onUncaughtError rather than letting them propagate. For a synchronous+ // utility like renderToString, callers expect errors to throw.+ let uncaughtError;+ // Create a reconciler container in legacy (synchronous) mode.+ // The four trailing callbacks are: onUncaughtError, onCaughtError,+ // onRecoverableError, and onDefaultTransitionIndicator. Transition tracing is disabled.+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ const container = reconciler.createContainer(rootNode, LegacyRoot, null, false, null, 'render-to-string', (error) => {+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- Error.isError is not available in Node.js 22.+ uncaughtError ??= types.isNativeError(error)+ ? error+ : new Error(String(error));+ }, () => { }, () => { }, () => { }, null);+ let didTeardownSucceed = false;+ try {+ let output;+ let outputHeight;+ let staticOutput;+ try {+ // Synchronously render the React tree into the container+ reconciler.updateContainerSync(createElement(RootNodeContext.Provider, { value: rootNode }, node), container, null, () => { });+ reconciler.flushSyncWork();+ // Yoga layout has already been calculated by onComputeLayout during commit.+ // Render the DOM tree to a string — this captures the dynamic (non-static) output.+ ({ output, outputHeight } = renderer(rootNode, false));+ // Cleanup removes Static too; preserve the completed render before teardown.+ staticOutput = capturedStaticOutput;+ }+ finally {+ // Tear down: unmount the tree so the reconciler cleans up child nodes+ // and runs effect cleanup functions. Child Yoga nodes are freed by the+ // reconciler's removeChildFromContainer → freeYogaSubtree → freeRecursive.+ reconciler.updateContainerSync(null, container, null, () => { });+ reconciler.flushSyncWork();+ didTeardownSucceed = true;+ // Free the root yoga node itself (children already freed by reconciler)+ rootNode.yogaNode.free();+ }+ // Re-throw after full cleanup so callers see the original error.+ if (uncaughtError !== undefined) {+ throw uncaughtError;+ }+ // The renderer appends a trailing newline to static output so dynamic output starts on a fresh line.+ // A single blank dynamic row has empty text but still needs that separator.+ if (outputHeight > 0) {+ return staticOutput + output;+ }+ // Without dynamic output, strip the separator so renderToString returns clean output.+ return staticOutput.endsWith('\n')+ ? staticOutput.slice(0, -1)+ : staticOutput;+ }+ finally {+ // Ensure native Yoga memory is freed even if rendering or teardown threw.+ // Yoga nodes are WASM-backed and not garbage collected.+ if (!didTeardownSucceed && rootNode.yogaNode) {+ try {+ // If reconciler teardown failed, some child nodes may not have been+ // freed. Use freeRecursive to clean up the entire tree as best-effort.+ rootNode.yogaNode.freeRecursive();+ }+ catch {+ // Best-effort: node may already be partially freed+ }+ }+ }+};+export default renderToString;diff --git a/vendor/ink/build/render.d.ts b/vendor/ink/build/render.d.tsindex b84a89b8..63c59ec1 100644--- a/vendor/ink/build/render.d.ts+++ b/vendor/ink/build/render.d.ts@@ -1,63 +1,179 @@+import { type Writable } from 'node:stream';import type { ReactNode } from 'react';-import Ink from './ink.js';+import Ink, { type RenderMetrics } from './ink.js';+import { type KittyKeyboardOptions } from './kitty-keyboard.js';export type RenderOptions = {/**- * Output stream where app will be rendered.- *- * @default process.stdout- */- stdout?: NodeJS.WriteStream;- /**- * Input stream where app will listen for input.- *- * @default process.stdin- */- stdin?: NodeJS.ReadStream;- /**- * Error stream.- * @default process.stderr- */- stderr?: NodeJS.WriteStream;- /**- * If true, each update will be rendered as a separate output, without replacing the previous one.- *- * @default false- */+ Output stream where the app will be rendered.++ @default process.stdout+ */+ stdout?: NodeJS.WritableStream;+ /**+ Input stream where app will listen for input.++ @default process.stdin+ */+ stdin?: NodeJS.ReadableStream;+ /**+ Error stream.+ @default process.stderr+ */+ stderr?: NodeJS.WritableStream;+ /**+ If true, each update will be rendered as separate output, without replacing the previous one.++ @default false+ */debug?: boolean;/**- * Configure whether Ink should listen to Ctrl+C keyboard input and exit the app. This is needed in case `process.stdin` is in raw mode, because then Ctrl+C is ignored by default and process is expected to handle it manually.- *- * @default true- */+ Configure whether Ink should listen for Ctrl+C keyboard input and exit the app. This is needed in case `process.stdin` is in raw mode, because then Ctrl+C is ignored by default and the process is expected to handle it manually.++ @default true+ */exitOnCtrlC?: boolean;/**- * Patch console methods to ensure console output doesn't mix with Ink output.- *- * @default true- */+ Patch console methods to ensure console output doesn't mix with Ink's output.++ Note: Once unmount starts, Ink restores the native console before React cleanup runs. Teardown-time `console.*` output then follows the normal console behavior instead of being rerouted through Ink.++ @default true+ */patchConsole?: boolean;+ /**+ Runs the given callback after each render and re-render with render metrics.++ Note: this callback runs after Ink commits a frame, but it does not wait for `stdout`/`stderr` stream callbacks.+ To run code after output is flushed, use `waitUntilRenderFlush()`.+ */+ onRender?: (metrics: RenderMetrics) => void;+ /**+ Enable screen reader support. See https://github.com/vadimdemedes/ink/blob/master/readme.md#screen-reader-support++ @default process.env['INK_SCREEN_READER'] === 'true'+ */+ isScreenReaderEnabled?: boolean;+ /**+ Maximum frames per second for render updates.+ This controls how frequently the UI can update to prevent excessive re-rendering.+ Higher values allow more frequent updates but may impact performance.++ @default 30+ */+ maxFps?: number;+ /**+ Enable incremental rendering mode which only updates changed lines instead of redrawing the entire output.+ This can reduce flickering and improve performance for frequently updating UIs.+ On changed lines, unchanged prefixes are also skipped when safe, preserving styles and grapheme boundaries.+ Lines containing unsupported terminal controls fall back to whole-line updates.++ @default false+ */+ incrementalRendering?: boolean;+ /**+ Enable React Concurrent Rendering mode.++ When enabled:+ - Suspense boundaries work correctly with async data+ - `useTransition` and `useDeferredValue` are fully functional+ - Updates can be interrupted for higher priority work++ Note: Concurrent mode changes the timing of renders. Some tests may need to use `act()` to properly await updates. Reusing the same stdout across multiple `render()` calls without unmounting is unsupported. Call `unmount()` first if you need to change the rendering mode or create a fresh instance.++ @default false+ */+ concurrent?: boolean;+ /**+ Configure kitty keyboard protocol support for enhanced keyboard input.+ Enables additional modifiers (super, hyper, capsLock, numLock) and+ disambiguated key events in terminals that support the protocol.++ @see https://sw.kovidgoyal.net/kitty/keyboard-protocol/+ */+ kittyKeyboard?: KittyKeyboardOptions;+ /**+ Override automatic interactive mode detection.++ By default, Ink detects whether the environment is interactive based on CI detection (via [`is-in-ci`](https://github.com/sindresorhus/is-in-ci)) and `stdout.isTTY`. Most users should not need to set this.++ When non-interactive, Ink disables ANSI erase sequences, cursor manipulation, synchronized output, resize handling, and kitty keyboard auto-detection, writing only the final frame at unmount.++ Set to `false` to force non-interactive mode or `true` to force interactive mode when the automatic detection doesn't suit your use case.++ Note: Reusing the same stdout across multiple `render()` calls without unmounting is unsupported. Call `unmount()` first if you need to change this option or create a fresh instance.++ @default true (false if in CI or `stdout.isTTY` is falsy)+ */+ interactive?: boolean;+ /**+ Render the app in the terminal's alternate screen buffer. When enabled, the app renders on a separate screen, and the original terminal content is restored when the app exits. This is the same mechanism used by programs like vim, htop, and less.++ Note: The terminal's scrollback buffer is not available while in the alternate screen. This is standard terminal behavior; programs like vim use the alternate screen specifically to avoid polluting the user's scrollback history.++ Note: Ink intentionally treats alternate-screen teardown output as disposable. It does not preserve or replay teardown-time frames, hook writes, or `console.*` output after restoring the primary screen.++ Only works in interactive mode. Ignored when `interactive` is `false` or in a non-interactive environment (CI, piped stdout).++ Note: Reusing the same stdout across multiple `render()` calls without unmounting is unsupported. Call `unmount()` first if you need to change this option or create a fresh instance.++ @default false+ */+ alternateScreen?: boolean;};export type Instance = {/**- * Replace previous root node with a new one or update props of the current root node.- */+ Replace the previous root node with a new one or update props of the current root node.+ */rerender: Ink['render'];/**- * Manually unmount the whole Ink app.- */+ Manually unmount the whole Ink app.+ */unmount: Ink['unmount'];/**- * Returns a promise, which resolves when app is unmounted.- */+ Returns a promise that settles when the app is unmounted.++ It resolves with the value passed to `exit(value)` and rejects with the error passed to `exit(error)`.+ When `unmount()` is called manually, it settles after unmount-related stdout writes complete.++ @example+ ```jsx+ const {unmount, waitUntilExit} = render(<MyApp />);++ setTimeout(unmount, 1000);++ await waitUntilExit(); // resolves after `unmount()` is called+ ```+ */waitUntilExit: Ink['waitUntilExit'];+ /**+ Returns a promise that settles after pending render output is flushed to stdout.++ This can be used after `rerender()` when you need to run code only after the frame is written.++ @example+ ```jsx+ const {rerender, waitUntilRenderFlush} = render(<MyApp step="loading" />);++ rerender(<MyApp step="ready" />);+ await waitUntilRenderFlush(); // output for "ready" is flushed++ runNextCommand();+ ```+ */+ waitUntilRenderFlush: Ink['waitUntilRenderFlush'];+ /**+ Unmount the current app and remove the internal Ink instance for this stdout.++ This is mostly useful for advanced cases where you need `render()` to create a fresh instance for the same stream without leaving terminal state such as the alternate screen behind.+ */cleanup: () => void;/**- * Clear output.- */+ Clear output.+ */clear: () => void;};/**- * Mount a component and render the output.- */-declare const render: (node: ReactNode, options?: NodeJS.WriteStream | RenderOptions) => Instance;+Mount a component and render the output.+*/+declare const render: (node: ReactNode, options?: Writable | RenderOptions) => Instance;export default render;diff --git a/vendor/ink/build/render.js b/vendor/ink/build/render.jsindex 1e7e68ee..fd8e0bc6 100644--- a/vendor/ink/build/render.js+++ b/vendor/ink/build/render.js@@ -3,17 +3,22 @@ import process from 'node:process';import Ink from './ink.js';import instances from './instances.js';/**- * Mount a component and render the output.- */+Mount a component and render the output.+*/const render = (node, options) => {+ const { stdout = process.stdout, stdin = process.stdin, stderr = process.stderr, exitOnCtrlC = true, patchConsole = true, ...renderOptions } = getOptions(options);const inkOptions = {- stdout: process.stdout,- stdin: process.stdin,- stderr: process.stderr,+ stdout,+ stdin,+ stderr,debug: false,- exitOnCtrlC: true,- patchConsole: true,- ...getOptions(options),+ exitOnCtrlC,+ patchConsole,+ maxFps: 30,+ incrementalRendering: false,+ concurrent: false,+ alternateScreen: false,+ ...renderOptions,};const instance = getInstance(inkOptions.stdout, () => new Ink(inkOptions));instance.render(node);@@ -23,7 +28,10 @@ const render = (node, options) => {instance.unmount();},waitUntilExit: instance.waitUntilExit,- cleanup: () => instances.delete(inkOptions.stdout),+ waitUntilRenderFlush: instance.waitUntilRenderFlush,+ cleanup() {+ instance.unmount();+ },clear: instance.clear,};};@@ -38,10 +46,17 @@ const getOptions = (stdout = {}) => {return stdout;};const getInstance = (stdout, createInstance) => {- let instance = instances.get(stdout);- if (!instance) {- instance = createInstance();- instances.set(stdout, instance);+ const instance = instances.get(stdout);+ if (instance === undefined) {+ const newInstance = createInstance();+ instances.set(stdout, newInstance);+ return newInstance;}+ // Ink keeps one live renderer per stdout. Reusing the same stream without+ // unmounting is unsupported, but return the existing instance so we don't+ // create two renderers that compete for the same output. Write the warning+ // directly to native stderr so an existing alternate-screen renderer cannot+ // swallow it via patchConsole.+ process.stderr.write('Warning: render() was called again for the same stdout before the previous Ink instance was unmounted. Reusing stdout across multiple render() calls is unsupported. Call unmount() first.\n');return instance;};diff --git a/vendor/ink/build/renderer.d.ts b/vendor/ink/build/renderer.d.tsindex 5e149100..8c35aea2 100644--- a/vendor/ink/build/renderer.d.ts+++ b/vendor/ink/build/renderer.d.ts@@ -4,5 +4,5 @@ type Result = {outputHeight: number;staticOutput: string;};-declare const renderer: (node: DOMElement) => Result;+declare const renderer: (node: DOMElement, isScreenReaderEnabled: boolean) => Result;export default renderer;diff --git a/vendor/ink/build/renderer.js b/vendor/ink/build/renderer.jsindex 07032d09..4e6028fb 100644--- a/vendor/ink/build/renderer.js+++ b/vendor/ink/build/renderer.js@@ -1,19 +1,54 @@-import renderNodeToOutput from './render-node-to-output.js';+import Yoga from 'yoga-layout';+import renderNodeToOutput, { renderNodeToScreenReaderOutput, } from './render-node-to-output.js';import Output from './output.js';-const renderer = (node) => {+const getVisibleStaticNode = (node) => {+ // Static output is rendered separately, so ancestor visibility must be checked explicitly.+ for (let ancestor = node; ancestor; ancestor = ancestor.parentNode) {+ if (ancestor.yogaNode?.getDisplay() === Yoga.DISPLAY_NONE) {+ return undefined;+ }+ }+ return node;+};+const renderer = (node, isScreenReaderEnabled) => {if (node.yogaNode) {+ const staticNode = getVisibleStaticNode(node.staticNode);+ if (isScreenReaderEnabled) {+ const output = renderNodeToScreenReaderOutput(node, {+ skipStaticElements: true,+ });+ const outputHeight = output === '' ? 0 : output.split('\n').length;+ let staticOutput = '';+ if (staticNode) {+ staticOutput = renderNodeToScreenReaderOutput(staticNode, {+ skipStaticElements: false,+ });+ }+ return {+ output,+ outputHeight,+ staticOutput: staticOutput === '' ? '' : `${staticOutput}\n`,+ };+ }const output = new Output({width: node.yogaNode.getComputedWidth(),height: node.yogaNode.getComputedHeight(),});- renderNodeToOutput(node, output, { skipStaticElements: true });+ renderNodeToOutput(node, output, {+ skipStaticElements: true,+ });let staticOutput;- if (node.staticNode?.yogaNode) {+ if (staticNode?.yogaNode) {+ const { yogaNode } = staticNode;staticOutput = new Output({- width: node.staticNode.yogaNode.getComputedWidth(),- height: node.staticNode.yogaNode.getComputedHeight(),+ width: yogaNode.getComputedLeft() ++ yogaNode.getComputedWidth() ++ yogaNode.getComputedMargin(Yoga.EDGE_RIGHT),+ height: yogaNode.getComputedTop() ++ yogaNode.getComputedHeight() ++ yogaNode.getComputedMargin(Yoga.EDGE_BOTTOM),});- renderNodeToOutput(node.staticNode, staticOutput, {+ renderNodeToOutput(staticNode, staticOutput, {skipStaticElements: false,});}@@ -23,7 +58,9 @@ const renderer = (node) => {outputHeight,// Newline at the end is needed, because static output doesn't have one, so// interactive output will override last line of static output- staticOutput: staticOutput ? `${staticOutput.get().output}\n` : '',+ staticOutput: staticOutput && staticOutput.height > 0+ ? `${staticOutput.get().output}\n`+ : '',};}return {diff --git a/vendor/ink/build/sanitize-ansi.d.ts b/vendor/ink/build/sanitize-ansi.d.tsnew file mode 100644index 00000000..1e5abecd--- /dev/null+++ b/vendor/ink/build/sanitize-ansi.d.ts@@ -0,0 +1,2 @@+declare const sanitizeAnsi: (text: string) => string;+export default sanitizeAnsi;diff --git a/vendor/ink/build/sanitize-ansi.js b/vendor/ink/build/sanitize-ansi.jsnew file mode 100644index 00000000..8bed3e60--- /dev/null+++ b/vendor/ink/build/sanitize-ansi.js@@ -0,0 +1,76 @@+import { hasAnsiControlCharacters, tokenizeAnsi } from './ansi-tokenizer.js';+const sgrParametersRegex = /^[\d:;]*$/;+// Terminals print nothing for C0 controls and DEL, so strip them; tabs and newlines carry layout. ESC and C1 never reach text tokens, the tokenizer owns them.+const controlCharactersRegex = /(?![\t\n])\p{Control}/gu;+const leadingMarksRegex = /^\p{Mark}+/u;+// @alcalzone/ansi-tokenize only accepts `[0-9;]` SGR parameters and renders anything else as visible cells, so colon sub-parameters are rewritten before layout.+// 256-color and truecolor forms map losslessly to the semicolon form, underline styles (`4:n`) degrade to plain underline, everything else (underline color `58:...`, malformed color forms) is dropped.+const normalizeParameter = (parameter) => {+ const parts = parameter.split(':');+ if (parts.length === 1) {+ return parameter;+ }+ if (parts[0] === '4') {+ return parts[1] === '0' || parts[1] === '' ? '24' : '4';+ }+ if (parts[0] !== '38' && parts[0] !== '48') {+ return undefined;+ }+ if (parts[1] === '5' && parts.length === 3) {+ return parts.join(';');+ }+ if (parts[1] === '2') {+ // Drop an empty or default color space id.+ if (parts.length === 6 && (parts[2] === '' || parts[2] === '0')) {+ parts.splice(2, 1);+ }+ if (parts.length === 5) {+ return parts.join(';');+ }+ }+ return undefined;+};+// Strip ANSI escape sequences that would conflict with Ink's layout.+// Preserved: SGR sequences (colors, bold, etc. - end with 'm') and+// OSC sequences (hyperlinks, etc. - ESC ] or C1 OSC).+// Stripped: cursor movement, screen clearing, and other control sequences.+// Combining marks share their base character's cell, so SGR sequences are deferred until after the marks. Otherwise ANSI tokenization consumes the marks as part of the escape sequence.+const sanitizeAnsi = (text) => {+ if (!hasAnsiControlCharacters(text)) {+ return text.replaceAll(controlCharactersRegex, '');+ }+ let output = '';+ let pendingStyles = '';+ for (const token of tokenizeAnsi(text)) {+ if (token.type === 'text') {+ const value = token.value.replaceAll(controlCharactersRegex, '');+ const marks = leadingMarksRegex.exec(value)?.[0] ?? '';+ output += marks;+ if (value.length > marks.length) {+ output += pendingStyles + value.slice(marks.length);+ pendingStyles = '';+ }+ continue;+ }+ if (token.type === 'osc') {+ output += pendingStyles + token.value;+ pendingStyles = '';+ continue;+ }+ if (token.type !== 'csi' ||+ token.finalCharacter !== 'm' ||+ token.intermediateString !== '' ||+ !sgrParametersRegex.test(token.parameterString)) {+ continue;+ }+ const parameters = token.parameterString+ .split(';')+ .map(parameter => normalizeParameter(parameter))+ .filter(parameter => parameter !== undefined);+ if (parameters.length > 0) {+ pendingStyles += `\u{1B}[${parameters.join(';')}m`;+ }+ }+ return output + pendingStyles;+};+export default sanitizeAnsi;diff --git a/vendor/ink/build/squash-text-nodes.js b/vendor/ink/build/squash-text-nodes.jsindex 1bc1a9c2..5839a497 100644--- a/vendor/ink/build/squash-text-nodes.js+++ b/vendor/ink/build/squash-text-nodes.js@@ -1,3 +1,5 @@+import wrapAnsi from 'wrap-ansi';+import sanitizeAnsi from './sanitize-ansi.js';// Squashing text nodes allows to combine multiple text nodes into one and write// to `Output` instance only once. For example, <Text>hello{' '}world</Text>// is actually 3 text nodes, which would result 3 writes to `Output`.@@ -6,16 +8,15 @@// which need to wrap all children at once, instead of wrapping 3 text nodes separately.const squashTextNodes = (node) => {let text = '';- for (let index = 0; index < node.childNodes.length; index++) {- const childNode = node.childNodes[index];- if (childNode === undefined) {- continue;- }+ for (const childNode of node.childNodes) {let nodeText = '';if (childNode.nodeName === '#text') {nodeText = childNode.nodeValue;}else {+ if (childNode.isHidden) {+ continue;+ }if (childNode.nodeName === 'ink-text' ||childNode.nodeName === 'ink-virtual-text') {nodeText = squashTextNodes(childNode);@@ -24,11 +25,22 @@ const squashTextNodes = (node) => {// apply children transform, so we have to do it manually here for each text nodeif (nodeText.length > 0 &&typeof childNode.internal_transform === 'function') {- nodeText = childNode.internal_transform(nodeText, index);+ const transform = childNode.internal_transform;+ nodeText = nodeText+ .split('\n')+ .map((line, lineIndex) => transform(line, lineIndex))+ .join('\n');}}text += nodeText;}+ text = sanitizeAnsi(text.replaceAll('\r\n', '\n'));+ // Measurement and styling dependencies understand the ESC forms of these C1 controls.+ text = text.replaceAll('', '[').replaceAll('', ']').replaceAll('', '\\');+ // Expand tabs after combining nested text so measurement and rendering use the same columns.+ if (node.nodeName === 'ink-text' && text.includes('\t')) {+ text = wrapAnsi(text, Infinity, { trim: false });+ }return text;};export default squashTextNodes;diff --git a/vendor/ink/build/stream.d.ts b/vendor/ink/build/stream.d.tsnew file mode 100644index 00000000..2618042d--- /dev/null+++ b/vendor/ink/build/stream.d.ts@@ -0,0 +1,16 @@+export type OutputStream = NodeJS.WritableStream & {+ isTTY?: boolean;+ columns?: number;+ rows?: number;+ destroyed?: boolean;+ writableEnded?: boolean;+};+type RawModeStream = NodeJS.ReadableStream & {+ isTTY: true;+ setRawMode: (isEnabled: boolean) => void;+ ref?: () => void;+ unref?: () => void;+};+export declare const isTty: (stream: NodeJS.ReadableStream) => boolean;+export declare const getRawModeStream: (stdin: NodeJS.ReadableStream) => RawModeStream | undefined;+export {};diff --git a/vendor/ink/build/stream.js b/vendor/ink/build/stream.jsnew file mode 100644index 00000000..92549aca--- /dev/null+++ b/vendor/ink/build/stream.js@@ -0,0 +1,5 @@+export const isTty = (stream) => 'isTTY' in stream && stream.isTTY === true;+const isRawModeStream = (stdin) => isTty(stdin) &&+ 'setRawMode' in stdin &&+ typeof stdin.setRawMode === 'function';+export const getRawModeStream = (stdin) => (isRawModeStream(stdin) ? stdin : undefined);diff --git a/vendor/ink/build/styles.d.ts b/vendor/ink/build/styles.d.tsindex e4e04eac..d3a8e7e5 100644--- a/vendor/ink/build/styles.d.ts+++ b/vendor/ink/build/styles.d.ts@@ -3,241 +3,316 @@ import { type LiteralUnion } from 'type-fest';import { type ForegroundColorName } from 'ansi-styles';import { type Node as YogaNode } from 'yoga-layout';export type Styles = {- readonly textWrap?: 'wrap' | 'end' | 'middle' | 'truncate-end' | 'truncate' | 'truncate-middle' | 'truncate-start';- readonly position?: 'absolute' | 'relative';+ readonly textWrap?: 'wrap' | 'hard' | 'truncate-end' | 'truncate' | 'truncate-middle' | 'truncate-start';/**- * Size of the gap between an element's columns.- */+ Controls how the element is positioned.++ When `position` is `static`, `top`, `right`, `bottom`, and `left` are ignored.+ */+ readonly position?: 'absolute' | 'relative' | 'static';+ /**+ Top offset for positioned elements.+ */+ readonly top?: number | string;+ /**+ Right offset for positioned elements.+ */+ readonly right?: number | string;+ /**+ Bottom offset for positioned elements.+ */+ readonly bottom?: number | string;+ /**+ Left offset for positioned elements.+ */+ readonly left?: number | string;+ /**+ Size of the gap between an element's columns.+ */readonly columnGap?: number;/**- * Size of the gap between element's rows.- */+ Size of the gap between an element's rows.+ */readonly rowGap?: number;/**- * Size of the gap between an element's columns and rows. Shorthand for `columnGap` and `rowGap`.- */+ Size of the gap between an element's columns and rows. A shorthand for `columnGap` and `rowGap`.+ */readonly gap?: number;/**- * Margin on all sides. Equivalent to setting `marginTop`, `marginBottom`, `marginLeft` and `marginRight`.- */+ Margin on all sides. Equivalent to setting `marginTop`, `marginBottom`, `marginLeft`, and `marginRight`.+ */readonly margin?: number;/**- * Horizontal margin. Equivalent to setting `marginLeft` and `marginRight`.- */+ Horizontal margin. Equivalent to setting `marginLeft` and `marginRight`.+ */readonly marginX?: number;/**- * Vertical margin. Equivalent to setting `marginTop` and `marginBottom`.- */+ Vertical margin. Equivalent to setting `marginTop` and `marginBottom`.+ */readonly marginY?: number;/**- * Top margin.- */+ Top margin.+ */readonly marginTop?: number;/**- * Bottom margin.- */+ Bottom margin.+ */readonly marginBottom?: number;/**- * Left margin.- */+ Left margin.+ */readonly marginLeft?: number;/**- * Right margin.- */+ Right margin.+ */readonly marginRight?: number;/**- * Padding on all sides. Equivalent to setting `paddingTop`, `paddingBottom`, `paddingLeft` and `paddingRight`.- */+ Padding on all sides. Equivalent to setting `paddingTop`, `paddingBottom`, `paddingLeft`, and `paddingRight`.+ */readonly padding?: number;/**- * Horizontal padding. Equivalent to setting `paddingLeft` and `paddingRight`.- */+ Horizontal padding. Equivalent to setting `paddingLeft` and `paddingRight`.+ */readonly paddingX?: number;/**- * Vertical padding. Equivalent to setting `paddingTop` and `paddingBottom`.- */+ Vertical padding. Equivalent to setting `paddingTop` and `paddingBottom`.+ */readonly paddingY?: number;/**- * Top padding.- */+ Top padding.+ */readonly paddingTop?: number;/**- * Bottom padding.- */+ Bottom padding.+ */readonly paddingBottom?: number;/**- * Left padding.- */+ Left padding.+ */readonly paddingLeft?: number;/**- * Right padding.- */+ Right padding.+ */readonly paddingRight?: number;/**- * This property defines the ability for a flex item to grow if necessary.- * See [flex-grow](https://css-tricks.com/almanac/properties/f/flex-grow/).- */+ This property defines the ability for a flex item to grow if necessary.+ See [flex-grow](https://css-tricks.com/almanac/properties/f/flex-grow/).+ */readonly flexGrow?: number;/**- * It specifies the “flex shrink factor”, which determines how much the flex item will shrink relative to the rest of the flex items in the flex container when there isn’t enough space on the row.- * See [flex-shrink](https://css-tricks.com/almanac/properties/f/flex-shrink/).- */+ It specifies the “flex shrink factor”, which determines how much the flex item will shrink relative to the rest of the flex items in the flex container when there isn’t enough space on the row.+ See [flex-shrink](https://css-tricks.com/almanac/properties/f/flex-shrink/).+ */readonly flexShrink?: number;/**- * It establishes the main-axis, thus defining the direction flex items are placed in the flex container.- * See [flex-direction](https://css-tricks.com/almanac/properties/f/flex-direction/).- */+ It establishes the main-axis, thus defining the direction flex items are placed in the flex container.+ See [flex-direction](https://css-tricks.com/almanac/properties/f/flex-direction/).+ */readonly flexDirection?: 'row' | 'column' | 'row-reverse' | 'column-reverse';/**- * It specifies the initial size of the flex item, before any available space is distributed according to the flex factors.- * See [flex-basis](https://css-tricks.com/almanac/properties/f/flex-basis/).- */+ It specifies the initial size of the flex item, before any available space is distributed according to the flex factors.+ See [flex-basis](https://css-tricks.com/almanac/properties/f/flex-basis/).+ */readonly flexBasis?: number | string;/**- * It defines whether the flex items are forced in a single line or can be flowed into multiple lines. If set to multiple lines, it also defines the cross-axis which determines the direction new lines are stacked in.- * See [flex-wrap](https://css-tricks.com/almanac/properties/f/flex-wrap/).- */+ It defines whether the flex items are forced in a single line or can be flowed into multiple lines. If set to multiple lines, it also defines the cross-axis which determines the direction new lines are stacked in.+ See [flex-wrap](https://css-tricks.com/almanac/properties/f/flex-wrap/).+ */readonly flexWrap?: 'nowrap' | 'wrap' | 'wrap-reverse';/**- * The align-items property defines the default behavior for how items are laid out along the cross axis (perpendicular to the main axis).- * See [align-items](https://css-tricks.com/almanac/properties/a/align-items/).- */- readonly alignItems?: 'flex-start' | 'center' | 'flex-end' | 'stretch';+ The align-items property defines the default behavior for how items are laid out along the cross axis (perpendicular to the main axis).+ See [align-items](https://css-tricks.com/almanac/properties/a/align-items/).+ */+ readonly alignItems?: 'flex-start' | 'center' | 'flex-end' | 'stretch' | 'baseline';+ /**+ It makes possible to override the align-items value for specific flex items.+ See [align-self](https://css-tricks.com/almanac/properties/a/align-self/).+ */+ readonly alignSelf?: 'flex-start' | 'center' | 'flex-end' | 'auto' | 'stretch' | 'baseline';/**- * It makes possible to override the align-items value for specific flex items.- * See [align-self](https://css-tricks.com/almanac/properties/a/align-self/).- */- readonly alignSelf?: 'flex-start' | 'center' | 'flex-end' | 'auto';+ It defines the alignment along the cross axis when there are multiple lines of flex items (when using flex-wrap).+ See [align-content](https://css-tricks.com/almanac/properties/a/align-content/).+ */+ readonly alignContent?: 'flex-start' | 'flex-end' | 'center' | 'stretch' | 'space-between' | 'space-around' | 'space-evenly';/**- * It defines the alignment along the main axis.- * See [justify-content](https://css-tricks.com/almanac/properties/j/justify-content/).- */+ It defines the alignment along the main axis.+ See [justify-content](https://css-tricks.com/almanac/properties/j/justify-content/).+ */readonly justifyContent?: 'flex-start' | 'flex-end' | 'space-between' | 'space-around' | 'space-evenly' | 'center';/**- * Width of the element in spaces.- * You can also set it in percent, which will calculate the width based on the width of parent element.- */+ Width of the element in spaces. You can also set it as a percentage, which will calculate the width based on the width of the parent element.+ */readonly width?: number | string;/**- * Height of the element in lines (rows).- * You can also set it in percent, which will calculate the height based on the height of parent element.- */+ Height of the element in lines (rows). You can also set it as a percentage, which will calculate the height based on the height of the parent element.+ */readonly height?: number | string;/**- * Sets a minimum width of the element.- */- readonly minWidth?: number | string;+ Sets a minimum width of the element.+ Percentages aren't supported yet; see https://github.com/facebook/yoga/issues/872.+ */+ readonly minWidth?: number;/**- * Sets a minimum height of the element.- */+ Sets a minimum height of the element in lines (rows). You can also set it as a percentage, which will calculate the minimum height based on the height of the parent element.+ */readonly minHeight?: number | string;/**- * Set this property to `none` to hide the element.- */+ Sets a maximum width of the element.+ Percentages aren't supported yet; see https://github.com/facebook/yoga/issues/872.+ */+ readonly maxWidth?: number;+ /**+ Sets a maximum height of the element in lines (rows). You can also set it as a percentage, which will calculate the maximum height based on the height of the parent element.+ */+ readonly maxHeight?: number | string;+ /**+ Defines the aspect ratio (width/height) for the element.++ Use it with at least one size constraint (`width`, `height`, `minHeight`, or `maxHeight`) so Ink can derive the missing dimension.+ */+ readonly aspectRatio?: number;+ /**+ Set this property to `none` to hide the element.+ */readonly display?: 'flex' | 'none';/**- * Add a border with a specified style.- * If `borderStyle` is `undefined` (which it is by default), no border will be added.- */+ Add a border with a specified style. If `borderStyle` is `undefined` (the default), no border will be added.+ */readonly borderStyle?: keyof Boxes | BoxStyle;/**- * Determines whether top border is visible.- *- * @default true- */+ Determines whether the top border is visible.++ @default true+ */readonly borderTop?: boolean;/**- * Determines whether bottom border is visible.- *- * @default true- */+ Determines whether the bottom border is visible.++ @default true+ */readonly borderBottom?: boolean;/**- * Determines whether left border is visible.- *- * @default true- */+ Determines whether the left border is visible.++ @default true+ */readonly borderLeft?: boolean;/**- * Determines whether right border is visible.- *- * @default true- */+ Determines whether the right border is visible.++ @default true+ */readonly borderRight?: boolean;/**- * Change border color.- * Shorthand for setting `borderTopColor`, `borderRightColor`, `borderBottomColor` and `borderLeftColor`.- */+ Change border color. A shorthand for setting `borderTopColor`, `borderRightColor`, `borderBottomColor`, and `borderLeftColor`.+ */readonly borderColor?: LiteralUnion<ForegroundColorName, string>;/**- * Change top border color.- * Accepts the same values as `color` in `Text` component.- */+ Change the top border color. Accepts the same values as `color` in `Text` component.+ */readonly borderTopColor?: LiteralUnion<ForegroundColorName, string>;/**- * Change bottom border color.- * Accepts the same values as `color` in `Text` component.- */+ Change the bottom border color. Accepts the same values as `color` in `Text` component.+ */readonly borderBottomColor?: LiteralUnion<ForegroundColorName, string>;/**- * Change left border color.- * Accepts the same values as `color` in `Text` component.- */+ Change the left border color. Accepts the same values as `color` in `Text` component.+ */readonly borderLeftColor?: LiteralUnion<ForegroundColorName, string>;/**- * Change right border color.- * Accepts the same values as `color` in `Text` component.- */+ Change the right border color. Accepts the same values as `color` in `Text` component.+ */readonly borderRightColor?: LiteralUnion<ForegroundColorName, string>;/**- * Dim the border color.- * Shorthand for setting `borderTopDimColor`, `borderBottomDimColor`, `borderLeftDimColor` and `borderRightDimColor`.- *- * @default false- */+ Dim the border color. A shorthand for setting `borderTopDimColor`, `borderBottomDimColor`, `borderLeftDimColor`, and `borderRightDimColor`.++ @default false+ */readonly borderDimColor?: boolean;/**- * Dim the top border color.- *- * @default false- */+ Dim the top border color.++ @default false+ */readonly borderTopDimColor?: boolean;/**- * Dim the bottom border color.- *- * @default false- */+ Dim the bottom border color.++ @default false+ */readonly borderBottomDimColor?: boolean;/**- * Dim the left border color.- *- * @default false- */+ Dim the left border color.++ @default false+ */readonly borderLeftDimColor?: boolean;/**- * Dim the right border color.- *- * @default false- */+ Dim the right border color.++ @default false+ */readonly borderRightDimColor?: boolean;/**- * Behavior for an element's overflow in both directions.- *- * @default 'visible'- */+ Change border background color. A shorthand for setting `borderTopBackgroundColor`, `borderRightBackgroundColor`, `borderBottomBackgroundColor`, and `borderLeftBackgroundColor`.+ */+ readonly borderBackgroundColor?: LiteralUnion<ForegroundColorName, string>;+ /**+ Change top border background color. Accepts the same values as `backgroundColor` in `Text` component.+ */+ readonly borderTopBackgroundColor?: LiteralUnion<ForegroundColorName, string>;+ /**+ Change bottom border background color. Accepts the same values as `backgroundColor` in `Text` component.+ */+ readonly borderBottomBackgroundColor?: LiteralUnion<ForegroundColorName, string>;+ /**+ Change left border background color. Accepts the same values as `backgroundColor` in `Text` component.+ */+ readonly borderLeftBackgroundColor?: LiteralUnion<ForegroundColorName, string>;+ /**+ Change right border background color. Accepts the same values as `backgroundColor` in `Text` component.+ */+ readonly borderRightBackgroundColor?: LiteralUnion<ForegroundColorName, string>;+ /**+ Behavior for an element's overflow in both directions.++ @default 'visible'+ */readonly overflow?: 'visible' | 'hidden';/**- * Behavior for an element's overflow in horizontal direction.- *- * @default 'visible'- */+ Behavior for an element's overflow in the horizontal direction.++ @default 'visible'+ */readonly overflowX?: 'visible' | 'hidden';/**- * Behavior for an element's overflow in vertical direction.- *- * @default 'visible'- */+ Behavior for an element's overflow in the vertical direction.++ @default 'visible'+ */readonly overflowY?: 'visible' | 'hidden';+ /**+ Horizontal offset applied to the element's children, in columns. Children are shifted left by this amount. Combine with `overflow="hidden"` to build scrollable views.++ Offsets are terminal cell coordinates, so fractional values are truncated toward zero and non-finite values are treated as `0`.++ @default 0+ */+ readonly contentOffsetX?: number;+ /**+ Vertical offset applied to the element's children, in rows. Children are shifted up by this amount. Combine with `overflow="hidden"` to build scrollable views.++ Offsets are terminal cell coordinates, so fractional values are truncated toward zero and non-finite values are treated as `0`.++ @default 0+ */+ readonly contentOffsetY?: number;+ /**+ Background color for the element.++ Accepts the same values as `color` in the `<Text>` component.+ */+ readonly backgroundColor?: LiteralUnion<ForegroundColorName, string>;};-declare const styles: (node: YogaNode, style?: Styles) => void;+declare const styles: (node: YogaNode, style?: Styles, currentStyle?: Styles) => void;export default styles;diff --git a/vendor/ink/build/styles.js b/vendor/ink/build/styles.jsindex af34bdca..7ca87b0d 100644--- a/vendor/ink/build/styles.js+++ b/vendor/ink/build/styles.js@@ -1,9 +1,32 @@import Yoga from 'yoga-layout';+const positionEdges = [+ ['top', Yoga.EDGE_TOP],+ ['right', Yoga.EDGE_RIGHT],+ ['bottom', Yoga.EDGE_BOTTOM],+ ['left', Yoga.EDGE_LEFT],+];const applyPositionStyles = (node, style) => {if ('position' in style) {- node.setPositionType(style.position === 'absolute'- ? Yoga.POSITION_TYPE_ABSOLUTE- : Yoga.POSITION_TYPE_RELATIVE);+ let positionType = Yoga.POSITION_TYPE_RELATIVE;+ if (style.position === 'absolute') {+ positionType = Yoga.POSITION_TYPE_ABSOLUTE;+ }+ else if (style.position === 'static') {+ positionType = Yoga.POSITION_TYPE_STATIC;+ }+ node.setPositionType(positionType);+ }+ for (const [property, edge] of positionEdges) {+ if (!Object.hasOwn(style, property)) {+ continue;+ }+ const value = style[property];+ if (typeof value === 'string') {+ // eslint-disable-next-line unicorn/prefer-number-coercion -- Percentage strings like `'50%'` need `Number.parseFloat()`, because `Number('50%')` is `NaN`.+ node.setPositionPercent(edge, Number.parseFloat(value));+ continue;+ }+ node.setPosition(edge, value);}};const applyMarginStyles = (node, style) => {@@ -11,22 +34,22 @@ const applyMarginStyles = (node, style) => {node.setMargin(Yoga.EDGE_ALL, style.margin ?? 0);}if ('marginX' in style) {- node.setMargin(Yoga.EDGE_HORIZONTAL, style.marginX ?? 0);+ node.setMargin(Yoga.EDGE_HORIZONTAL, style.marginX);}if ('marginY' in style) {- node.setMargin(Yoga.EDGE_VERTICAL, style.marginY ?? 0);+ node.setMargin(Yoga.EDGE_VERTICAL, style.marginY);}if ('marginLeft' in style) {- node.setMargin(Yoga.EDGE_START, style.marginLeft || 0);+ node.setMargin(Yoga.EDGE_START, style.marginLeft);}if ('marginRight' in style) {- node.setMargin(Yoga.EDGE_END, style.marginRight || 0);+ node.setMargin(Yoga.EDGE_END, style.marginRight);}if ('marginTop' in style) {- node.setMargin(Yoga.EDGE_TOP, style.marginTop || 0);+ node.setMargin(Yoga.EDGE_TOP, style.marginTop);}if ('marginBottom' in style) {- node.setMargin(Yoga.EDGE_BOTTOM, style.marginBottom || 0);+ node.setMargin(Yoga.EDGE_BOTTOM, style.marginBottom);}};const applyPaddingStyles = (node, style) => {@@ -34,24 +57,67 @@ const applyPaddingStyles = (node, style) => {node.setPadding(Yoga.EDGE_ALL, style.padding ?? 0);}if ('paddingX' in style) {- node.setPadding(Yoga.EDGE_HORIZONTAL, style.paddingX ?? 0);+ node.setPadding(Yoga.EDGE_HORIZONTAL, style.paddingX);}if ('paddingY' in style) {- node.setPadding(Yoga.EDGE_VERTICAL, style.paddingY ?? 0);+ node.setPadding(Yoga.EDGE_VERTICAL, style.paddingY);}if ('paddingLeft' in style) {- node.setPadding(Yoga.EDGE_LEFT, style.paddingLeft || 0);+ node.setPadding(Yoga.EDGE_LEFT, style.paddingLeft);}if ('paddingRight' in style) {- node.setPadding(Yoga.EDGE_RIGHT, style.paddingRight || 0);+ node.setPadding(Yoga.EDGE_RIGHT, style.paddingRight);}if ('paddingTop' in style) {- node.setPadding(Yoga.EDGE_TOP, style.paddingTop || 0);+ node.setPadding(Yoga.EDGE_TOP, style.paddingTop);}if ('paddingBottom' in style) {- node.setPadding(Yoga.EDGE_BOTTOM, style.paddingBottom || 0);+ node.setPadding(Yoga.EDGE_BOTTOM, style.paddingBottom);}};+const flexWrapValues = new Map([+ ['nowrap', Yoga.WRAP_NO_WRAP],+ ['wrap', Yoga.WRAP_WRAP],+ ['wrap-reverse', Yoga.WRAP_WRAP_REVERSE],+]);+const flexDirectionValues = new Map([+ ['row', Yoga.FLEX_DIRECTION_ROW],+ ['row-reverse', Yoga.FLEX_DIRECTION_ROW_REVERSE],+ ['column', Yoga.FLEX_DIRECTION_COLUMN],+ ['column-reverse', Yoga.FLEX_DIRECTION_COLUMN_REVERSE],+]);+const alignItemsValues = new Map([+ ['stretch', Yoga.ALIGN_STRETCH],+ ['flex-start', Yoga.ALIGN_FLEX_START],+ ['center', Yoga.ALIGN_CENTER],+ ['flex-end', Yoga.ALIGN_FLEX_END],+ ['baseline', Yoga.ALIGN_BASELINE],+]);+const alignSelfValues = new Map([+ ['auto', Yoga.ALIGN_AUTO],+ ['flex-start', Yoga.ALIGN_FLEX_START],+ ['center', Yoga.ALIGN_CENTER],+ ['flex-end', Yoga.ALIGN_FLEX_END],+ ['stretch', Yoga.ALIGN_STRETCH],+ ['baseline', Yoga.ALIGN_BASELINE],+]);+const alignContentValues = new Map([+ ['flex-start', Yoga.ALIGN_FLEX_START],+ ['center', Yoga.ALIGN_CENTER],+ ['flex-end', Yoga.ALIGN_FLEX_END],+ ['space-between', Yoga.ALIGN_SPACE_BETWEEN],+ ['space-around', Yoga.ALIGN_SPACE_AROUND],+ ['space-evenly', Yoga.ALIGN_SPACE_EVENLY],+ ['stretch', Yoga.ALIGN_STRETCH],+]);+const justifyContentValues = new Map([+ ['flex-start', Yoga.JUSTIFY_FLEX_START],+ ['center', Yoga.JUSTIFY_CENTER],+ ['flex-end', Yoga.JUSTIFY_FLEX_END],+ ['space-between', Yoga.JUSTIFY_SPACE_BETWEEN],+ ['space-around', Yoga.JUSTIFY_SPACE_AROUND],+ ['space-evenly', Yoga.JUSTIFY_SPACE_EVENLY],+]);const applyFlexStyles = (node, style) => {if ('flexGrow' in style) {node.setFlexGrow(style.flexGrow ?? 0);@@ -60,28 +126,15 @@ const applyFlexStyles = (node, style) => {node.setFlexShrink(typeof style.flexShrink === 'number' ? style.flexShrink : 1);}if ('flexWrap' in style) {- if (style.flexWrap === 'nowrap') {- node.setFlexWrap(Yoga.WRAP_NO_WRAP);- }- if (style.flexWrap === 'wrap') {- node.setFlexWrap(Yoga.WRAP_WRAP);- }- if (style.flexWrap === 'wrap-reverse') {- node.setFlexWrap(Yoga.WRAP_WRAP_REVERSE);+ const flexWrap = flexWrapValues.get(style.flexWrap);+ if (flexWrap !== undefined) {+ node.setFlexWrap(flexWrap);}}if ('flexDirection' in style) {- if (style.flexDirection === 'row') {- node.setFlexDirection(Yoga.FLEX_DIRECTION_ROW);- }- if (style.flexDirection === 'row-reverse') {- node.setFlexDirection(Yoga.FLEX_DIRECTION_ROW_REVERSE);- }- if (style.flexDirection === 'column') {- node.setFlexDirection(Yoga.FLEX_DIRECTION_COLUMN);- }- if (style.flexDirection === 'column-reverse') {- node.setFlexDirection(Yoga.FLEX_DIRECTION_COLUMN_REVERSE);+ const flexDirection = flexDirectionValues.get(style.flexDirection);+ if (flexDirection !== undefined) {+ node.setFlexDirection(flexDirection);}}if ('flexBasis' in style) {@@ -89,60 +142,52 @@ const applyFlexStyles = (node, style) => {node.setFlexBasis(style.flexBasis);}else if (typeof style.flexBasis === 'string') {- node.setFlexBasisPercent(Number.parseInt(style.flexBasis, 10));+ // eslint-disable-next-line unicorn/prefer-number-coercion -- Percentage strings like `'50%'` need `Number.parseFloat()`, because `Number('50%')` is `NaN`.+ node.setFlexBasisPercent(Number.parseFloat(style.flexBasis));}else {- // This should be replaced with node.setFlexBasisAuto() when new Yoga release is out- node.setFlexBasis(Number.NaN);+ node.setFlexBasisAuto();}}if ('alignItems' in style) {- if (style.alignItems === 'stretch' || !style.alignItems) {- node.setAlignItems(Yoga.ALIGN_STRETCH);- }- if (style.alignItems === 'flex-start') {- node.setAlignItems(Yoga.ALIGN_FLEX_START);- }- if (style.alignItems === 'center') {- node.setAlignItems(Yoga.ALIGN_CENTER);- }- if (style.alignItems === 'flex-end') {- node.setAlignItems(Yoga.ALIGN_FLEX_END);+ const alignItems =+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions -- JavaScript callers pass `null` or `false` (for example `condition && 'center'`), and any falsy value means the default.+ style.alignItems+ ? alignItemsValues.get(style.alignItems)+ : Yoga.ALIGN_STRETCH;+ if (alignItems !== undefined) {+ node.setAlignItems(alignItems);}}if ('alignSelf' in style) {- if (style.alignSelf === 'auto' || !style.alignSelf) {- node.setAlignSelf(Yoga.ALIGN_AUTO);- }- if (style.alignSelf === 'flex-start') {- node.setAlignSelf(Yoga.ALIGN_FLEX_START);- }- if (style.alignSelf === 'center') {- node.setAlignSelf(Yoga.ALIGN_CENTER);- }- if (style.alignSelf === 'flex-end') {- node.setAlignSelf(Yoga.ALIGN_FLEX_END);- }- }- if ('justifyContent' in style) {- if (style.justifyContent === 'flex-start' || !style.justifyContent) {- node.setJustifyContent(Yoga.JUSTIFY_FLEX_START);- }- if (style.justifyContent === 'center') {- node.setJustifyContent(Yoga.JUSTIFY_CENTER);- }- if (style.justifyContent === 'flex-end') {- node.setJustifyContent(Yoga.JUSTIFY_FLEX_END);- }- if (style.justifyContent === 'space-between') {- node.setJustifyContent(Yoga.JUSTIFY_SPACE_BETWEEN);- }- if (style.justifyContent === 'space-around') {- node.setJustifyContent(Yoga.JUSTIFY_SPACE_AROUND);- }- if (style.justifyContent === 'space-evenly') {- node.setJustifyContent(Yoga.JUSTIFY_SPACE_EVENLY);- }+ const alignSelf =+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions -- JavaScript callers pass `null` or `false` (for example `condition && 'center'`), and any falsy value means the default.+ style.alignSelf ? alignSelfValues.get(style.alignSelf) : Yoga.ALIGN_AUTO;+ if (alignSelf !== undefined) {+ node.setAlignSelf(alignSelf);+ }+ }+ if ('alignContent' in style) {+ // Keep wrapped lines top-packed by default; stretch can add surprising empty rows in fixed-height boxes.+ const alignContent =+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions -- JavaScript callers pass `null` or `false` (for example `condition && 'center'`), and any falsy value means the default.+ style.alignContent+ ? alignContentValues.get(style.alignContent)+ : Yoga.ALIGN_FLEX_START;+ if (alignContent !== undefined) {+ node.setAlignContent(alignContent);+ }+ }+ if (!('justifyContent' in style)) {+ return;+ }+ const justifyContent =+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions -- JavaScript callers pass `null` or `false` (for example `condition && 'center'`), and any falsy value means the default.+ style.justifyContent+ ? justifyContentValues.get(style.justifyContent)+ : Yoga.JUSTIFY_FLEX_START;+ if (justifyContent !== undefined) {+ node.setJustifyContent(justifyContent);}};const applyDimensionStyles = (node, style) => {@@ -151,7 +196,8 @@ const applyDimensionStyles = (node, style) => {node.setWidth(style.width);}else if (typeof style.width === 'string') {- node.setWidthPercent(Number.parseInt(style.width, 10));+ // eslint-disable-next-line unicorn/prefer-number-coercion -- Percentage strings like `'50%'` need `Number.parseFloat()`, because `Number('50%')` is `NaN`.+ node.setWidthPercent(Number.parseFloat(style.width));}else {node.setWidthAuto();@@ -162,70 +208,81 @@ const applyDimensionStyles = (node, style) => {node.setHeight(style.height);}else if (typeof style.height === 'string') {- node.setHeightPercent(Number.parseInt(style.height, 10));+ // eslint-disable-next-line unicorn/prefer-number-coercion -- Percentage strings like `'50%'` need `Number.parseFloat()`, because `Number('50%')` is `NaN`.+ node.setHeightPercent(Number.parseFloat(style.height));}else {node.setHeightAuto();}}if ('minWidth' in style) {- if (typeof style.minWidth === 'string') {- node.setMinWidthPercent(Number.parseInt(style.minWidth, 10));- }- else {- node.setMinWidth(style.minWidth ?? 0);- }+ node.setMinWidth(style.minWidth ?? 0);}if ('minHeight' in style) {if (typeof style.minHeight === 'string') {- node.setMinHeightPercent(Number.parseInt(style.minHeight, 10));+ // eslint-disable-next-line unicorn/prefer-number-coercion -- Percentage strings like `'50%'` need `Number.parseFloat()`, because `Number('50%')` is `NaN`.+ node.setMinHeightPercent(Number.parseFloat(style.minHeight));}else {node.setMinHeight(style.minHeight ?? 0);}}+ if ('maxWidth' in style) {+ node.setMaxWidth(style.maxWidth);+ }+ if ('maxHeight' in style) {+ if (typeof style.maxHeight === 'string') {+ // eslint-disable-next-line unicorn/prefer-number-coercion -- Percentage strings like `'50%'` need `Number.parseFloat()`, because `Number('50%')` is `NaN`.+ node.setMaxHeightPercent(Number.parseFloat(style.maxHeight));+ }+ else {+ node.setMaxHeight(style.maxHeight);+ }+ }+ if ('aspectRatio' in style) {+ node.setAspectRatio(style.aspectRatio);+ }};const applyDisplayStyles = (node, style) => {if ('display' in style) {- node.setDisplay(style.display === 'flex' ? Yoga.DISPLAY_FLEX : Yoga.DISPLAY_NONE);+ node.setDisplay(style.display === 'none' ? Yoga.DISPLAY_NONE : Yoga.DISPLAY_FLEX);}};-const applyBorderStyles = (node, style) => {- if ('borderStyle' in style) {- const borderWidth = style.borderStyle ? 1 : 0;- if (style.borderTop !== false) {- node.setBorder(Yoga.EDGE_TOP, borderWidth);- }- if (style.borderBottom !== false) {- node.setBorder(Yoga.EDGE_BOTTOM, borderWidth);- }- if (style.borderLeft !== false) {- node.setBorder(Yoga.EDGE_LEFT, borderWidth);- }- if (style.borderRight !== false) {- node.setBorder(Yoga.EDGE_RIGHT, borderWidth);- }- }+const applyBorderStyles = (node, style, currentStyle) => {+ const hasBorderChanges = 'borderStyle' in style ||+ 'borderTop' in style ||+ 'borderBottom' in style ||+ 'borderLeft' in style ||+ 'borderRight' in style;+ if (!hasBorderChanges) {+ return;+ }+ const hasBorder = Boolean(currentStyle.borderStyle);+ const borderWidth = hasBorder ? 1 : 0;+ node.setBorder(Yoga.EDGE_TOP, currentStyle.borderTop === false ? 0 : borderWidth);+ node.setBorder(Yoga.EDGE_BOTTOM, currentStyle.borderBottom === false ? 0 : borderWidth);+ node.setBorder(Yoga.EDGE_LEFT, currentStyle.borderLeft === false ? 0 : borderWidth);+ node.setBorder(Yoga.EDGE_RIGHT, currentStyle.borderRight === false ? 0 : borderWidth);};const applyGapStyles = (node, style) => {if ('gap' in style) {node.setGap(Yoga.GUTTER_ALL, style.gap ?? 0);}if ('columnGap' in style) {- node.setGap(Yoga.GUTTER_COLUMN, style.columnGap ?? 0);+ node.setGap(Yoga.GUTTER_COLUMN, style.columnGap);}if ('rowGap' in style) {- node.setGap(Yoga.GUTTER_ROW, style.rowGap ?? 0);+ node.setGap(Yoga.GUTTER_ROW, style.rowGap);}};-const styles = (node, style = {}) => {+const styles = (node, style = {}, currentStyle = style) => {applyPositionStyles(node, style);applyMarginStyles(node, style);applyPaddingStyles(node, style);applyFlexStyles(node, style);applyDimensionStyles(node, style);applyDisplayStyles(node, style);- applyBorderStyles(node, style);+ applyBorderStyles(node, style, currentStyle);applyGapStyles(node, style);};export default styles;diff --git a/vendor/ink/build/utils.d.ts b/vendor/ink/build/utils.d.tsnew file mode 100644index 00000000..5422d026--- /dev/null+++ b/vendor/ink/build/utils.d.ts@@ -0,0 +1,10 @@+import type { OutputStream } from './stream.js';+/**+Get the effective terminal dimensions from the given stdout stream.++Falls back to `terminal-size` for columns in piped processes where `stdout.columns` is 0, and uses standard defaults (80×24) when dimensions cannot be determined.+*/+export declare const getWindowSize: (stdout: OutputStream) => {+ columns: number;+ rows: number;+};diff --git a/vendor/ink/build/utils.js b/vendor/ink/build/utils.jsnew file mode 100644index 00000000..8352692e--- /dev/null+++ b/vendor/ink/build/utils.js@@ -0,0 +1,25 @@+import terminalSize from 'terminal-size';+const resolveDimension = (value, fallback, defaultValue) => {+ if (value !== undefined && value > 0) {+ return value;+ }+ return fallback !== undefined && fallback > 0 ? fallback : defaultValue;+};+/**+Get the effective terminal dimensions from the given stdout stream.++Falls back to `terminal-size` for columns in piped processes where `stdout.columns` is 0, and uses standard defaults (80×24) when dimensions cannot be determined.+*/+export const getWindowSize = (stdout) => {+ // `stdout.columns`/`rows` can be 0 or undefined in non-TTY environments.+ const columns = stdout.columns ?? 0;+ const rows = stdout.rows ?? 0;+ if (Boolean(columns) && Boolean(rows)) {+ return { columns, rows };+ }+ const fallbackSize = terminalSize();+ return {+ columns: resolveDimension(columns, fallbackSize.columns, 80),+ rows: resolveDimension(rows, fallbackSize.rows, 24),+ };+};diff --git a/vendor/ink/build/wrap-text.d.ts b/vendor/ink/build/wrap-text.d.tsindex 935cfb8d..da797c31 100644--- a/vendor/ink/build/wrap-text.d.ts+++ b/vendor/ink/build/wrap-text.d.ts@@ -1,3 +1,5 @@+import QuickLRU from 'quick-lru';import { type Styles } from './styles.js';+export declare const wrapTextCache: QuickLRU<string, string>;declare const wrapText: (text: string, maxWidth: number, wrapType: Styles["textWrap"]) => string;export default wrapText;diff --git a/vendor/ink/build/wrap-text.js b/vendor/ink/build/wrap-text.jsindex 1792bb39..19e7c34b 100644--- a/vendor/ink/build/wrap-text.js+++ b/vendor/ink/build/wrap-text.js@@ -1,10 +1,23 @@import wrapAnsi from 'wrap-ansi';import cliTruncate from 'cli-truncate';-const cache = {};+import { styledCharsFromTokens, styledCharsToString, tokenize, } from '@alcalzone/ansi-tokenize';+import QuickLRU from 'quick-lru';+export const wrapTextCache = new QuickLRU({ maxSize: 4096 });const wrapText = (text, maxWidth, wrapType) => {- const cacheKey = text + String(maxWidth) + String(wrapType);- const cachedText = cache[cacheKey];- if (cachedText) {+ // `wrapAnsi` only breaks a row once something is on it, so wrapping into zero columns puts every character on its own row and the layout height grows to the character count. Text with no room keeps its natural width instead, like any other content that does not fit. Truncation is left alone: it cuts to nothing at zero columns.+ if (maxWidth <= 0 && (wrapType === 'wrap' || wrapType === 'hard')) {+ return text;+ }+ // Yoga rounds a text node's width up to a whole column, so a positive fraction of a column is measured as the one column it renders into.+ if (maxWidth > 0 && maxWidth < 1) {+ maxWidth = 1;+ }+ // `text` goes last because it's the only part of the key that can contain+ // arbitrary characters. With it first, ('ab', 12, 'wrap') and+ // ('ab1', 2, 'wrap') both produce the key `ab12wrap` and share a result.+ const cacheKey = `${maxWidth}\u{0}${String(wrapType)}\u{0}${text}`;+ const cachedText = wrapTextCache.get(cacheKey);+ if (cachedText !== undefined) {return cachedText;}let wrappedText = text;@@ -14,17 +27,40 @@ const wrapText = (text, maxWidth, wrapType) => {hard: true,});}- if (wrapType.startsWith('truncate')) {+ else if (wrapType === 'hard') {+ wrappedText = wrapAnsi(text, maxWidth, {+ trim: false,+ hard: true,+ wordWrap: false,+ });+ }+ else if (wrapType.startsWith('truncate')) {let position = 'end';if (wrapType === 'truncate-middle') {position = 'middle';}- if (wrapType === 'truncate-start') {+ else if (wrapType === 'truncate-start') {position = 'start';}- wrappedText = cliTruncate(text, maxWidth, { position });+ // `cliTruncate` treats its input as a single line: newlines are zero-width, so the widths of every line would add up and the text would be cut as one run. Truncate each line on its own instead, the same way `wrapAnsi` wraps each line. Split on styled characters rather than the raw string so styles and links that span a newline are reopened on every line they cover. Single-line text skips the tokenization, which is the expensive part on long strings.+ let lines = [text];+ if (text.includes('\n')) {+ const styledLines = [[]];+ for (const character of styledCharsFromTokens(tokenize(text))) {+ if (character.value === '\n') {+ styledLines.push([]);+ }+ else {+ styledLines.at(-1).push(character);+ }+ }+ lines = styledLines.map(line => styledCharsToString(line));+ }+ wrappedText = lines+ .map(line => cliTruncate(line, maxWidth, { position }))+ .join('\n');}- cache[cacheKey] = wrappedText;+ wrapTextCache.set(cacheKey, wrappedText);return wrappedText;};export default wrapText;diff --git a/vendor/ink/build/write-synchronized.d.ts b/vendor/ink/build/write-synchronized.d.tsnew file mode 100644index 00000000..5677036f--- /dev/null+++ b/vendor/ink/build/write-synchronized.d.ts@@ -0,0 +1,3 @@+export declare const bsu = "\u001B[?2026h";+export declare const esu = "\u001B[?2026l";+export declare function shouldSynchronize(stream: NodeJS.WritableStream, isInteractive?: boolean): boolean;diff --git a/vendor/ink/build/write-synchronized.js b/vendor/ink/build/write-synchronized.jsnew file mode 100644index 00000000..29d91ad2--- /dev/null+++ b/vendor/ink/build/write-synchronized.js@@ -0,0 +1,8 @@+import isInCi from 'is-in-ci';+export const bsu = '\u{1B}[?2026h';+export const esu = '\u{1B}[?2026l';+export function shouldSynchronize(stream, isInteractive) {+ return ('isTTY' in stream &&+ stream.isTTY &&+ (isInteractive ?? !isInCi));+}diff --git a/vendor/ink/license b/vendor/ink/licenseindex 5afed125..fcb8fa9e 100644--- a/vendor/ink/license+++ b/vendor/ink/license@@ -1,6 +1,7 @@MIT License-Copyright (c) Vadym Demedes <[email protected]> (github.com/vadimdemedes)+Copyright (c) Vadym Demedes <[email protected]> (https://github.com/vadimdemedes)+Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:diff --git a/vendor/ink/package.json b/vendor/ink/package.jsonindex 312e6c9a..d4a77295 100644--- a/vendor/ink/package.json+++ b/vendor/ink/package.json@@ -1,21 +1,18 @@{"name": "ink",- "version": "5.2.1",+ "version": "8.0.0","description": "React for CLI","license": "MIT","repository": "vadimdemedes/ink",- "author": {- "name": "Vadim Demedes",- "email": "[email protected]",- "url": "https://github.com/vadimdemedes"- },+ "author": "Vadim Demedes <[email protected]> (https://github.com/vadimdemedes)","type": "module","exports": {"types": "./build/index.d.ts","default": "./build/index.js"},+ "sideEffects": true,"engines": {- "node": ">=18"+ "node": ">=22"},"keywords": ["react",@@ -32,35 +29,34 @@"text"],"dependencies": {- "@alcalzone/ansi-tokenize": "^0.1.3",- "ansi-escapes": "^7.0.0",- "ansi-styles": "^6.2.1",+ "@alcalzone/ansi-tokenize": "^0.3.1",+ "ansi-escapes": "^7.3.0",+ "ansi-styles": "^7.0.0","auto-bind": "^5.0.1",- "chalk": "^5.3.0",- "cli-boxes": "^3.0.0",+ "chalk": "^6.0.1",+ "cli-boxes": "^4.0.1","cli-cursor": "^4.0.0",- "cli-truncate": "^4.0.0",+ "cli-truncate": "^6.0.0","code-excerpt": "^4.0.0",- "es-toolkit": "^1.22.0",+ "es-toolkit": "^1.52.0","indent-string": "^5.0.0",- "is-in-ci": "^1.0.0",+ "is-in-ci": "^2.0.0","patch-console": "^2.0.0",- "react-reconciler": "^0.29.0",- "scheduler": "^0.23.0",+ "quick-lru": "^7.3.0",+ "react-reconciler": "^0.34.0","signal-exit": "^3.0.7",- "slice-ansi": "^7.1.0","stack-utils": "^2.0.6",- "string-width": "^7.2.0",- "type-fest": "^4.27.0",- "widest-line": "^5.0.0",- "wrap-ansi": "^9.0.0",- "ws": "^8.18.0",+ "string-width": "^8.3.0",+ "terminal-size": "^4.0.1",+ "type-fest": "^5.10.0",+ "widest-line": "^6.0.0",+ "wrap-ansi": "^10.0.2","yoga-layout": "~3.2.1"},"peerDependencies": {- "@types/react": ">=18.0.0",- "react": ">=18.0.0",- "react-devtools-core": "^4.19.1"+ "@types/react": ">=19.3.0",+ "react": ">=19.3.0",+ "react-devtools-core": ">=6.1.2"},"peerDependenciesMeta": {"@types/react": {@@ -71,8 +67,8 @@}},"_mercury": {- "source": "[email protected]",- "integrity": "sha512-BqcUyWrG9zq5HIwW6JcfFHsIYebJkWWb4fczNah1goUO0vv5vneIlfwuS85twyJ5hYR/y18FlAYUxrO9ChIWVg==",+ "source": "[email protected]",+ "integrity": "sha512-M2aFwZOqmkFxCwedy6xrP4E+DGoK57iahAFnfTqNyOyJ54O7DZzu027z/NI8EGy44Sw9O9BcbTF4QEUS2GHAtg==","patched": true,"generator": "scripts/vendor-ink.cjs","note": "Generated file set: stock tarball + scripts/apply-ink-patch.cjs. Do not hand-edit; see docs/ink-patch.md."diff --git a/website/docs/getting-started/installation.mdx b/website/docs/getting-started/installation.mdxindex b1635259..664f2eab 100644--- a/website/docs/getting-started/installation.mdx+++ b/website/docs/getting-started/installation.mdx@@ -4,7 +4,7 @@ title: Installationslug: /----Mercury runs anywhere Node.js 20+ runs, plus everywhere a single binary can live — including phones via Termux.+Mercury runs anywhere Node.js 22+ runs, plus everywhere a single binary can live — including phones via Termux.## Pick your platform@@ -47,7 +47,7 @@ The installer:| `MERCURY_INSTALL` | `$HOME/.mercury` | Install prefix (binary lands at `$MERCURY_INSTALL/bin/mercury`) || `MERCURY_NO_PATH` | _(unset)_ | Set to `1` to skip modifying your shell rc / user PATH |-### 2. npm package (requires Node.js 20+)+### 2. npm package (requires Node.js 22+)If you already have Node.js, the npm route is the simplest:diff --git a/website/docs/getting-started/platforms/linux.mdx b/website/docs/getting-started/platforms/linux.mdxindex 1e0cedb3..6631ade6 100644--- a/website/docs/getting-started/platforms/linux.mdx+++ b/website/docs/getting-started/platforms/linux.mdx@@ -27,7 +27,7 @@ mercury --versionnpm i -g @cosmicstack/mercury-agent```-Requires **Node.js 20+**. Recommended via [nvm](https://github.com/nvm-sh/nvm) so you avoid `sudo` for global packages.+Requires **Node.js 22+**. Recommended via [nvm](https://github.com/nvm-sh/nvm) so you avoid `sudo` for global packages.## Architecture matrixdiff --git a/website/docs/getting-started/platforms/macos.mdx b/website/docs/getting-started/platforms/macos.mdxindex e6eed1d0..97eaa13a 100644--- a/website/docs/getting-started/platforms/macos.mdx+++ b/website/docs/getting-started/platforms/macos.mdx@@ -28,7 +28,7 @@ npm i -g @cosmicstack/mercury-agentmercury```-Requires **Node.js 20+**. Install Node via [nvm](https://github.com/nvm-sh/nvm), Homebrew (`brew install node@20`), or the official installer.+Requires **Node.js 22+**. Install Node via [nvm](https://github.com/nvm-sh/nvm), Homebrew (`brew install node@22`), or the official installer.## Apple Silicon vs Intel