Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

build(tui): vendor the patched ink 5.2.1 and bundle it (ADR-017)

Salman Qureshi000213e48951
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index db6df28a..5fd58841 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -83,6 +83,9 @@ jobs:
- name: Verify package integrity
run: node scripts/verify-package.cjs
+ - name: Verify vendor/ink is stock ink 5.2.1 + the patch set (ADR-017)
+ run: node scripts/vendor-ink.cjs --check
+
termux:
name: Termux (Android, x86_64)
runs-on: ubuntu-latest
diff --git a/DECISIONS.md b/DECISIONS.md
index a06ee201..10851767 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -136,6 +136,13 @@
- **Decision**: Accept and maintain. Verified empirically on macOS before merge: an xattr-bearing `web/` directory produced `._web` in the archive without `COPYFILE_DISABLE=1` and nothing with it. Full suite green (487 tests), `tsc --noEmit` clean. The allowlist change is a security positive (defense in depth — children can no longer invoke tools outside their allowlist, e.g. `list_agents`/`stop_agent`); the runtime filter subsumes the prompt-text filtering in `sub-agent.ts` line 516, which remains as harmless documentation. Merge commit authored by Mercury, feature commits retain the original author.
- **Consequence**: Release archives stay safe for GNU tar consumers; sub-agent tool scoping is now enforced at the SDK boundary rather than trusted to the model's cooperation. Maintenance owned by Mercury: any new tool surface exposed to sub-agents must respect `resolveTools()` (not `capabilities.getTools()` directly), and release builds on macOS must keep `COPYFILE_DISABLE=1` — re-verify archive contents with GNU tar or the `verify-standalone-release.cjs` path check before publishing.
+## ADR-017: Vendor the patched Ink renderer
+
+- **Context**: Mercury's TUI depends on seven fixes to ink 5.2.1 (Yoga free-node hygiene, `<Static itemKey>`, freeze gate, live-region guard, diff-render, resize invalidate and — new here — hardware cursor positioning for IME, #41/#66). Until now they were applied to `node_modules/ink` by `postinstall` (`patch-package || apply-ink-patch.cjs || echo`). That path failed silently on `--ignore-scripts` installs, npm policies that block lifecycle scripts, hoisted installs, and Termux containers without `patch-package`; the stock renderer then capped the transcript at ~100 messages and re-exposed the Yoga WASM crash (ROADMAP P0.9, P2.4). `ink` was a tsup external, so even the standalone binaries depended on whatever ink was on disk at build time.
+- **Decision**: Commit the patched build to `vendor/ink/` (runtime files only: `build/` without source maps, a trimmed `package.json`, `license`) and bundle it: tsup aliases `ink` → `vendor/ink/build/index.js` with `noExternal: ['ink']`, vitest aliases the same path, and `tsconfig` `paths` point the types there. The files are generated, never hand-edited: `scripts/vendor-ink.cjs` verifies the stock tarball's registry integrity, copies it, runs the hunks in `scripts/apply-ink-patch.cjs` (the single source of truth), stamps `inkPatch.vendored = true`, and rewrites `patches/ink+5.2.1.patch` as the stock-vs-vendored diff for review. `--check` rebuilds into a temp dir and fails on any byte difference (run in CI's pack-verify job). The postinstall step is removed; `post-build.cjs` and `verify-package.cjs` fail if `dist/index.js` imports `ink` at runtime or lacks the patch markers. `ink-patch-check` judges a vendored build by its runtime globals only and reports `source: 'vendored'` (`mercury doctor`: "vendored (patched ink 5.2.1 bundled)").
+- **Alternatives considered**: keep postinstall and harden it (still depends on lifecycle scripts running); publish a fork as `@cosmicstack/ink` (adds a release pipeline for a package whose fixes we want upstream anyway); upgrade to ink 6 (React 19 migration, and the same fixes would still be needed).
+- **Consequence**: Every install path — npm with or without scripts, Termux, Bun binaries — runs the identical patched renderer. `ink` stays in `dependencies` for now, used only for its transitive packages at build time; moving it to `devDependencies` (and dropping `patch-package`) needs a lockfile regeneration and is left as a follow-up. Two bundling details: ink's DEV-only React DevTools module is replaced by an empty stub (esbuild would otherwise inline `react-devtools-core`, which crashes at load), and the bundle banner defines `require` via `createRequire` because ink's CommonJS dependencies require node builtins. Upgrading ink means: bump `INK_VERSION`/`INK_INTEGRITY` in `scripts/vendor-ink.cjs`, re-anchor the hunks, regenerate, and review the patch file. Each hunk's rationale and upstream status is in `docs/ink-patch.md`.
+
## ADR-018: SQLite backend selection: better-sqlite3 → bun:sqlite → node:sqlite → JSON
- **Context**: Four stores depend on SQLite — Second Brain (`src/memory/second-brain-db.ts`), the bots job queue (`src/bots/queue.ts`), boards (`src/core/board-db.ts`) and the cloud pool-search cache (`src/cloud/pool-search.ts`). Each carried its own `require('better-sqlite3')` probe. The standalone binaries (`bun build --compile`) bundle better-sqlite3's JavaScript but not its native addon, so inside a binary every probe failed on every target: Second Brain was silently disabled and bots/boards fell back to JSON (ROADMAP P1.9, §F, #96). Toolchain-less npm installs (Termux, no compiler) hit the same wall. Meanwhile both runtimes ship an embedded engine — `bun:sqlite` in Bun and `node:sqlite` (`DatabaseSync`) in Node ≥ 22.5 (unflagged in 22.13 / 23.4) — with the same synchronous shape better-sqlite3 has.
diff --git a/package.json b/package.json
index 588287f9..b36e437e 100644
--- a/package.json
+++ b/package.json
@@ -20,7 +20,8 @@
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
- "postinstall": "patch-package || node scripts/apply-ink-patch.cjs || echo 'WARNING: ink patch not applied — run: node scripts/apply-ink-patch.cjs'",
+ "vendor:ink": "node scripts/vendor-ink.cjs",
+ "vendor:ink:check": "node scripts/vendor-ink.cjs --check",
"prepublishOnly": "npm run build"
},
"keywords": [
@@ -58,8 +59,6 @@
},
"files": [
"dist",
- "patches",
- "scripts/apply-ink-patch.cjs",
"src/web/static"
],
"dependencies": {
diff --git a/patches/ink+5.2.1.patch b/patches/ink+5.2.1.patch
index 5afd70a9..34b87ab4 100644
--- a/patches/ink+5.2.1.patch
+++ b/patches/ink+5.2.1.patch
@@ -18,7 +18,7 @@ index 9a25884..a4d515b 100644
/**
* `<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 9c54f14..6274f9a 100644
+index 6bb7894..e22c94e 100644
--- a/node_modules/ink/build/components/Static.js
+++ b/node_modules/ink/build/components/Static.js
@@ -1,4 +1,4 @@
@@ -94,9 +94,10 @@ index 9c54f14..6274f9a 100644
const style = useMemo(() => ({
position: 'absolute',
diff --git a/node_modules/ink/build/ink.js b/node_modules/ink/build/ink.js
+index 68d3045..b6adc6d 100644
--- a/node_modules/ink/build/ink.js
+++ b/node_modules/ink/build/ink.js
-@@ -14,6 +14,14 @@
+@@ -14,6 +14,53 @@ import logUpdate from './log-update.js';
import instances from './instances.js';
import App from './components/App.js';
const noop = () => { };
@@ -108,10 +109,49 @@ diff --git a/node_modules/ink/build/ink.js b/node_modules/ink/build/ink.js
+// 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'],
++};
++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;
-@@ -81,6 +89,11 @@
+@@ -81,6 +128,11 @@ export default class Ink {
}
}
resized = () => {
@@ -123,7 +163,23 @@ diff --git a/node_modules/ink/build/ink.js b/node_modules/ink/build/ink.js
this.calculateLayout();
this.onRender();
};
-@@ -98,7 +111,33 @@
+@@ -94,11 +146,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;
}
@@ -149,20 +205,116 @@ diff --git a/node_modules/ink/build/ink.js b/node_modules/ink/build/ink.js
+ // 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) {
+@@ -127,12 +221,13 @@ export default class Ink {
+ if (hasStaticOutput) {
+ this.log.clear();
+ this.options.stdout.write(staticOutput);
+- this.log(output);
++ 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));
+@@ -152,7 +247,7 @@ export default class Ink {
+ }
+ this.log.clear();
+ this.options.stdout.write(data);
+- this.log(this.lastOutput);
++ this.log(this.lastOutput, this.lastCursor);
+ }
+ writeToStderr(data) {
+ if (this.isUnmounted) {
+@@ -169,7 +264,7 @@ export default class Ink {
+ }
+ this.log.clear();
+ this.options.stderr.write(data);
+- this.log(this.lastOutput);
++ 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..501a658 100644
--- a/node_modules/ink/build/log-update.js
+++ b/node_modules/ink/build/log-update.js
-@@ -13,10 +13,34 @@
+@@ -4,25 +4,81 @@ const create = (stream, { showCursor = false } = {}) => {
+ 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) stream.write(unpark() + park(target));
return;
}
+ // Diff-render (Cosmic Stack patch): erase and rewrite only the rows
@@ -185,23 +337,32 @@ diff --git a/node_modules/ink/build/log-update.js b/node_modules/ink/build/log-u
previousOutput = output;
- stream.write(ansiEscapes.eraseLines(previousLineCount) + output);
previousLineCount = output.split('\n').length;
-+ stream.write(ansiEscapes.eraseLines(eraseCount) + nextRows.slice(firstChange).join('\n') + '\n');
- };
++ stream.write(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.clear = () => {
- stream.write(ansiEscapes.eraseLines(previousLineCount));
+- stream.write(ansiEscapes.eraseLines(previousLineCount));
++ stream.write(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 55acec7..f440fa9 100644
+index 81379f2..5930232 100644
--- a/node_modules/ink/build/reconciler.js
+++ b/node_modules/ink/build/reconciler.js
-@@ -58,6 +58,40 @@ const cleanupYogaNode = (node) => {
+@@ -58,6 +58,41 @@ const cleanupYogaNode = (node) => {
node?.unsetMeasureFunc();
node?.freeRecursive();
};
@@ -239,10 +400,11 @@ index 55acec7..f440fa9 100644
+ rootNode.staticNode = undefined;
+ }
+};
++globalThis.__mercuryInkYogaHygiene = true;
export default createReconciler({
getRootHostContext: () => ({
isInsideText: false,
-@@ -173,7 +207,7 @@ export default createReconciler({
+@@ -173,7 +208,7 @@ export default createReconciler({
insertInContainerBefore: insertBeforeNode,
removeChildFromContainer(node, removeNode) {
removeChildNode(node, removeNode);
@@ -251,7 +413,7 @@ index 55acec7..f440fa9 100644
},
prepareUpdate(node, _type, oldProps, newProps, rootNode) {
if (node.internal_static) {
-@@ -213,7 +247,7 @@ export default createReconciler({
+@@ -213,6 +248,6 @@ export default createReconciler({
},
removeChild(node, removeNode) {
removeChildNode(node, removeNode);
@@ -259,5 +421,3 @@ index 55acec7..f440fa9 100644
+ cleanupRemovedNode(node, removeNode);
},
});
- //# sourceMappingURL=reconciler.js.map
-\ No newline at end of file
diff --git a/scripts/apply-ink-patch.cjs b/scripts/apply-ink-patch.cjs
index 243603b9..9b90bc82 100644
--- a/scripts/apply-ink-patch.cjs
+++ b/scripts/apply-ink-patch.cjs
@@ -1,10 +1,14 @@
/**
- * Ensure the bundled ink fixes are applied to the installed ink.
- * Idempotent: checks for the fix markers first, then edits the two files
- * DIRECTLY — no patch-package dependency (patch-package itself failed on
- * Termux/npm-11 containers: `sh: 1: patch-package: not found`).
+ * 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`).
*
- * What it applies (mirrors patches/ink+5.2.1.patch):
+ * 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
@@ -14,6 +18,14 @@
* 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.
*
* Loud on failure: a silent skip is never acceptable for a crash fix.
*/
@@ -22,31 +34,39 @@ const path = require('path');
const root = path.join(__dirname, '..');
-/** File paths for an ink install. `root` is overridable so tests can
- * exercise the applier against a synthetic ink tree without touching the
- * real node_modules. */
-function pathsFor(projectRoot) {
- let inkDir = path.join(projectRoot, 'node_modules', 'ink', 'build');
- // 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);
- } catch {
- // not installed / not resolvable — fall back to the conventional path
+/** File paths for an ink build directory. `root` is overridable so tests
+ * can exercise the applier against a synthetic ink tree, and `inkDir`
+ * (the `build/` directory) can be given explicitly — that is how
+ * scripts/vendor-ink.cjs patches the extracted stock tarball. */
+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);
+ } catch {
+ // not installed / not resolvable — fall back to the conventional path
+ }
}
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'),
};
}
+/** The committed vendored build (ADR-017). */
+const VENDORED_INK_DIR = path.join(root, 'vendor', 'ink', 'build');
+
const paths = pathsFor(root);
function isPatched(p = paths) {
@@ -58,13 +78,16 @@ function isPatched(p = paths) {
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)
- && inkJs.includes(FRAME_GATE_MARKER);
+ && inkJs.includes(FRAME_GATE_MARKER)
+ && inkJs.includes(CURSOR_ANCHOR_MARKER);
} catch {
return false;
}
@@ -72,6 +95,204 @@ function isPatched(p = paths) {
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';
+
+/**
+ * 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));
+ 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);
+ }
+
+ // 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 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.
+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.
+export const inkPatch = {
+ vendored: false,
+ hunks: ['yoga-hygiene', 'static-item-key', 'freeze-gate', 'live-region-guard', 'diff-render', 'resize-invalidate', 'cursor-positioning'],
+};
+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;
+};`);
+ 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"
@@ -230,7 +451,11 @@ function applyLogUpdateDiffRender(p = paths) {
function applyReconcilerFix(p = paths) {
const { reconcilerPath } = p;
let s = fs.readFileSync(reconcilerPath, 'utf8');
- if (s.includes('clearYogaRefs')) return true;
+ 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) => {
@@ -286,10 +511,22 @@ const cleanupRemovedNode = (node, removeNode) => {
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.
@@ -398,11 +635,16 @@ function applyStaticFix(p = paths) {
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);
+ const p = pathsFor(opts.root ?? root, { inkDir: opts.inkDir });
if (isPatched(p)) return { ok: true, applied: false };
if (!fs.existsSync(p.reconcilerPath)) {
- return { ok: false, applied: false, error: 'node_modules/ink not installed' };
+ return { ok: false, applied: false, error: `ink build not found at ${p.inkDir}` };
}
try {
const reconcilerOk = applyReconcilerFix(p);
@@ -411,6 +653,10 @@ function apply(opts = {}) {
const liveRegionOk = applyInkLiveRegionGuard(p);
const diffRenderOk = applyLogUpdateDiffRender(p);
const resizeResetOk = applyResizeBaselineReset(p);
+ const cursorOk = applyCursorPositioning(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 (!reconcilerOk) {
return { ok: false, applied: true, error: 'reconciler.js no longer matches the expected ink 5.2.1 shape — patch anchors not found' };
}
@@ -438,20 +684,29 @@ function apply(opts = {}) {
return { ok: true, applied: true };
}
-module.exports = { isPatched, apply, pathsFor };
+/** True when the committed vendored build carries every hunk. */
+function isVendoredPatched() {
+ return isPatched(pathsFor(root, { inkDir: VENDORED_INK_DIR }));
+}
+
+module.exports = { isPatched, apply, pathsFor, isVendoredPatched, VENDORED_INK_DIR };
if (require.main === module) {
- const result = apply();
+ // 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 WASM crash hygiene + Static identity dedup)');
+ 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 install.');
+ console.error(' ⚠ INK FIXES NOT APPLIED — the Yoga WASM crash class is UNPATCHED in this build.');
console.error(` Reason: ${result.error}`);
- console.error(' Fix: reinstall dependencies (npm install) and re-run the build.');
- // Non-zero so a postinstall chain (`patch-package || node scripts/apply-ink-patch.cjs || echo …`)
- // falls through to the loud warning instead of reporting success.
+ console.error(' Fix: node scripts/vendor-ink.cjs (regenerates vendor/ink from the stock tarball).');
process.exitCode = 1;
}
}
\ No newline at end of file
diff --git a/scripts/apply-ink-patch.test.ts b/scripts/apply-ink-patch.test.ts
index 0e6f42d9..3c02a575 100644
--- a/scripts/apply-ink-patch.test.ts
+++ b/scripts/apply-ink-patch.test.ts
@@ -5,10 +5,12 @@ import { join } from 'node:path';
import { tmpdir } from 'node:os';
const requireCjs = createRequire(import.meta.url);
-const { apply, isPatched, pathsFor } = requireCjs('../scripts/apply-ink-patch.cjs') as {
- apply: (opts?: { root?: string }) => { ok: boolean; applied: boolean; error?: string };
+const { apply, isPatched, pathsFor, isVendoredPatched, VENDORED_INK_DIR } = requireCjs('../scripts/apply-ink-patch.cjs') as {
+ apply: (opts?: { root?: string; inkDir?: string }) => { ok: boolean; applied: boolean; error?: string };
isPatched: (p?: unknown) => boolean;
- pathsFor: (root: string) => Record<string, string>;
+ pathsFor: (root: string, opts?: { inkDir?: string }) => Record<string, string>;
+ isVendoredPatched: () => boolean;
+ VENDORED_INK_DIR: string;
};
/**
@@ -37,6 +39,8 @@ function writeStockInk(root: string): void {
' removeChildNode(node, removeNode);',
' cleanupYogaNode(removeNode.yogaNode);',
'};',
+ '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");
@@ -49,9 +53,23 @@ function writeStockInk(root: string): void {
' this.calculateLayout();',
' this.onRender();',
' };',
- ' 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;',
+ ' };',
+ ' writeToStdout(data) {',
+ ' this.log.clear();',
+ ' this.options.stdout.write(data);',
+ ' this.log(this.lastOutput);',
' }',
'}',
].join('\n'));
@@ -59,6 +77,7 @@ function writeStockInk(root: string): void {
'const create = (stream, { showCursor = false } = {}) => {',
' let previousLineCount = 0;',
' let previousOutput = \'\';',
+ ' let hasHiddenCursor = false;',
' const render = (str) => {',
" const output = str + '\\n';",
' if (output === previousOutput) {',
@@ -71,6 +90,8 @@ function writeStockInk(root: string): void {
' render.clear = () => {',
' stream.write(ansiEscapes.eraseLines(previousLineCount));',
' };',
+ ' render.done = () => {',
+ ' };',
' return render;',
'};',
].join('\n'));
@@ -96,6 +117,16 @@ describe('ink patch applier (patch-package-free)', () => {
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,
+ // and both log() call sites pass the resolved cell through.
+ expect(logUpdate).toContain('const render = (str, cursor) => {');
+ expect(logUpdate).toContain('stream.write(unpark() + ansiEscapes.eraseLines(eraseCount)');
+ expect(logUpdate).toContain('stream.write(unpark() + ansiEscapes.eraseLines(previousLineCount))');
+ 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;');
// Idempotent: a second run must recognize the applied state and no-op.
const again = apply({ root });
expect(again.ok).toBe(true);
@@ -104,4 +135,24 @@ describe('ink patch applier (patch-package-free)', () => {
rmSync(root, { recursive: true, force: true });
}
});
-});
\ No newline at end of file
+});
+
+describe('vendored ink (ADR-017)', () => {
+ it('the committed vendor/ink build carries every hunk', () => {
+ expect(isVendoredPatched()).toBe(true);
+ const inkJs = readFileSync(join(VENDORED_INK_DIR, 'ink.js'), 'utf8');
+ expect(inkJs).toContain('vendored: true');
+ // Runtime-only file set: no source maps, no dangling map trailers.
+ expect(inkJs).not.toContain('sourceMappingURL');
+ });
+
+ it('re-applying the patch set to the vendored build is a no-op', () => {
+ expect(apply({ inkDir: VENDORED_INK_DIR })).toEqual({ ok: true, applied: false });
+ });
+
+ it('reports a missing build directory instead of throwing', () => {
+ const result = apply({ inkDir: join(tmpdir(), 'mercury-no-such-ink', 'build') });
+ expect(result.ok).toBe(false);
+ expect(result.error).toContain('ink build not found');
+ });
+});
diff --git a/scripts/post-build.cjs b/scripts/post-build.cjs
index 26b788d7..9a9f2982 100644
--- a/scripts/post-build.cjs
+++ b/scripts/post-build.cjs
@@ -19,19 +19,21 @@ function copyDirSync(src, dest) {
}
}
-// 0. Ensure the bundled ink patch is applied. Newer npm policies can block
-// lifecycle scripts (postinstall), so the build pipeline — which runs on
-// every build — enforces it here instead. Un-patched ink carries the Yoga
-// WASM crash class; a skip is never silent.
-try {
- const { apply } = require('./apply-ink-patch.cjs');
- const result = apply();
- if (result.ok && result.applied) console.log(' ✓ ink patch applied');
- else if (!result.ok) {
- console.error(' ⚠ INK PATCH NOT APPLIED — Yoga WASM crash class unpatched. Reason:', result.error);
+// 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).
+{
+ 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']) {
+ if (!bundle.includes(marker)) problems.push(`vendored ink marker missing from the bundle: ${marker}`);
}
-} catch (err) {
- console.error(' ⚠ ink patch step failed:', err.message);
+ if (problems.length) {
+ for (const p of problems) console.error(` ✗ ${p}`);
+ process.exit(1);
+ }
+ console.log(' ✓ patched ink is bundled (vendor/ink)');
}
// 1. Copy src/web/static -> dist/web/static
diff --git a/scripts/vendor-ink.cjs b/scripts/vendor-ink.cjs
new file mode 100644
index 00000000..c5b36447
--- /dev/null
+++ b/scripts/vendor-ink.cjs
@@ -0,0 +1,227 @@
+#!/usr/bin/env node
+/**
+ * Regenerate `vendor/ink/` — the patched ink build Mercury bundles (ADR-017).
+ *
+ * node scripts/vendor-ink.cjs [--tarball <ink-5.2.1.tgz>] [--check]
+ *
+ * Pipeline, fully deterministic from a pinned stock tarball:
+ * 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
+ * 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
+ * differs from the committed `vendor/ink` — CI can use it to prove the
+ * committed files are exactly tarball + patch, nothing hand-edited.
+ *
+ * tsup and vitest alias `ink` → `vendor/ink/build/index.js`, so the patched
+ * renderer ships inside dist/index.js and the standalone binaries on every
+ * install path (npm, Bun --compile, Termux) with no postinstall step.
+ */
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const crypto = require('node:crypto');
+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 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. */
+const DROP_PKG_FIELDS = ['scripts', 'devDependencies', 'ava', 'xo', 'prettier', 'files'];
+
+function parseArgs(argv) {
+ const opts = { tarball: null, check: false };
+ for (let i = 0; i < argv.length; i++) {
+ if (argv[i] === '--tarball') opts.tarball = path.resolve(argv[++i] || '');
+ else if (argv[i] === '--check') opts.check = true;
+ else throw new Error(`unknown argument: ${argv[i]}`);
+ }
+ return opts;
+}
+
+function integrityOf(file) {
+ return 'sha512-' + crypto.createHash('sha512').update(fs.readFileSync(file)).digest('base64');
+}
+
+function obtainTarball(explicit, tmp) {
+ if (explicit) {
+ if (!fs.existsSync(explicit)) throw new Error(`tarball not found: ${explicit}`);
+ return explicit;
+ }
+ console.log(` fetching ink@${INK_VERSION} with npm pack …`);
+ execFileSync('npm', ['pack', `ink@${INK_VERSION}`, '--pack-destination', tmp], { stdio: ['ignore', 'ignore', 'inherit'] });
+ const found = fs.readdirSync(tmp).find((f) => f.startsWith('ink-') && f.endsWith('.tgz'));
+ if (!found) throw new Error('npm pack produced no tarball');
+ return path.join(tmp, found);
+}
+
+/** Source maps are not needed at runtime (and tsup emits its own). */
+const isRuntimeFile = (name) => !name.endsWith('.map');
+
+/** Drop `.map` files and the `//# sourceMappingURL=` trailers that point at
+ * them (vitest/vite and esbuild would otherwise warn on every load). */
+function stripSourceMaps(dir) {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const p = path.join(dir, entry.name);
+ if (entry.isDirectory()) stripSourceMaps(p);
+ else if (!isRuntimeFile(entry.name)) fs.rmSync(p);
+ else if (entry.name.endsWith('.js') || entry.name.endsWith('.d.ts')) {
+ const src = fs.readFileSync(p, 'utf8');
+ const out = src.replace(/\n?\/\/# sourceMappingURL=\S+\s*$/, '\n');
+ if (out !== src) fs.writeFileSync(p, out);
+ }
+ }
+}
+
+function copyTree(src, dest) {
+ fs.mkdirSync(dest, { recursive: true });
+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
+ if (!entry.isDirectory() && !isRuntimeFile(entry.name)) continue;
+ const from = path.join(src, entry.name);
+ const to = path.join(dest, entry.name);
+ if (entry.isDirectory()) copyTree(from, to);
+ else fs.copyFileSync(from, to);
+ }
+}
+
+function listFiles(dir, prefix = '') {
+ const out = [];
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) out.push(...listFiles(path.join(dir, entry.name), rel));
+ else out.push(rel);
+ }
+ return out;
+}
+
+/** Build the vendored tree into `outDir` from `tarball`; returns the stock package dir. */
+function buildVendored(tarball, tmp, outDir) {
+ const got = integrityOf(tarball);
+ if (got !== INK_INTEGRITY) {
+ throw new Error(`tarball integrity mismatch for ${tarball}\n expected ${INK_INTEGRITY}\n got ${got}`);
+ }
+ const extractDir = path.join(tmp, 'stock');
+ fs.mkdirSync(extractDir, { recursive: true });
+ execFileSync('tar', ['-xzf', tarball, '-C', extractDir]);
+ const stockPkg = path.join(extractDir, 'package');
+ const stockJson = JSON.parse(fs.readFileSync(path.join(stockPkg, 'package.json'), 'utf8'));
+ if (stockJson.name !== 'ink' || stockJson.version !== INK_VERSION) {
+ throw new Error(`tarball is ${stockJson.name}@${stockJson.version}, expected ink@${INK_VERSION}`);
+ }
+
+ fs.rmSync(outDir, { recursive: true, force: true });
+ copyTree(path.join(stockPkg, 'build'), path.join(outDir, 'build'));
+ fs.copyFileSync(path.join(stockPkg, 'license'), path.join(outDir, 'license'));
+ for (const field of DROP_PKG_FIELDS) delete stockJson[field];
+ stockJson._mercury = {
+ source: `ink@${INK_VERSION}`,
+ integrity: INK_INTEGRITY,
+ 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.',
+ };
+ fs.writeFileSync(path.join(outDir, 'package.json'), JSON.stringify(stockJson, null, '\t') + '\n');
+
+ const inkDir = path.join(outDir, 'build');
+ const result = apply({ inkDir });
+ if (!result.ok || !result.applied) {
+ throw new Error(`patch set did not apply cleanly: ${result.error || 'nothing applied — stock tarball already carries markers?'}`);
+ }
+ const inkJs = path.join(inkDir, 'ink.js');
+ const stamped = fs.readFileSync(inkJs, 'utf8').replace(' vendored: false,', ' vendored: true,');
+ if (!stamped.includes('vendored: true')) throw new Error('could not stamp inkPatch.vendored in ink.js');
+ fs.writeFileSync(inkJs, stamped);
+ stripSourceMaps(inkDir);
+ if (!isPatched(pathsFor(root, { inkDir }))) throw new Error('markers missing after apply');
+ return stockPkg;
+}
+
+/** `patches/ink+<v>.patch`: stock build/ vs vendored build/, patch-package style paths. */
+function writePatchFile(stockPkg, outDir) {
+ // Compare like with like: the vendored tree carries no source maps.
+ stripSourceMaps(path.join(stockPkg, 'build'));
+ const r = spawnSync('git', [
+ '-c', 'core.autocrlf=false', '-c', 'color.diff=never',
+ 'diff', '--no-index', '--src-prefix=a/node_modules/ink/', '--dst-prefix=b/node_modules/ink/',
+ 'build', path.join(outDir, 'build'),
+ ], { cwd: stockPkg, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
+ if (r.error) {
+ console.warn(` ! git not available — patches file not regenerated (${r.error.message})`);
+ return false;
+ }
+ if ((r.status !== 0 && r.status !== 1) || !r.stdout.trim()) throw new Error(`git diff failed (status ${r.status}): ${r.stderr}`);
+ // git prints the vendored side with the relative path we passed; normalise
+ // both sides to `node_modules/ink/build/...` so the file reads like the
+ // patch-package diff it replaces.
+ const vendoredRel = path.join(outDir, 'build').split(path.sep).join('/').replace(/^\//, '');
+ const text = r.stdout
+ .split('\n')
+ .map((line) => {
+ if (line.startsWith('diff --git ') || line.startsWith('+++ ') || line.startsWith('--- ')) {
+ return line.split(`b/node_modules/ink/${vendoredRel}`).join('b/node_modules/ink/build');
+ }
+ return line;
+ })
+ .join('\n');
+ fs.mkdirSync(path.dirname(PATCH_FILE), { recursive: true });
+ fs.writeFileSync(PATCH_FILE, text);
+ return true;
+}
+
+function treesEqual(a, b) {
+ const fa = listFiles(a);
+ const fb = listFiles(b);
+ if (fa.length !== fb.length || fa.some((f, i) => f !== fb[i])) return { equal: false, why: 'file lists differ' };
+ for (const f of fa) {
+ if (!fs.readFileSync(path.join(a, f)).equals(fs.readFileSync(path.join(b, f)))) return { equal: false, why: `${f} differs` };
+ }
+ return { equal: true };
+}
+
+function main() {
+ const opts = parseArgs(process.argv.slice(2));
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-vendor-ink-'));
+ try {
+ const tarball = obtainTarball(opts.tarball, tmp);
+ console.log(` tarball: ${tarball}`);
+ if (opts.check) {
+ const candidate = path.join(tmp, 'vendor-ink');
+ buildVendored(tarball, tmp, candidate);
+ const cmp = treesEqual(candidate, VENDOR_DIR);
+ if (!cmp.equal) {
+ console.error(` ✗ vendor/ink is NOT tarball + patch: ${cmp.why}. Run: node scripts/vendor-ink.cjs`);
+ process.exitCode = 1;
+ return;
+ }
+ console.log(' ✓ vendor/ink matches stock tarball + patch set');
+ return;
+ }
+ const stockPkg = buildVendored(tarball, tmp, VENDOR_DIR);
+ const wrotePatch = writePatchFile(stockPkg, VENDOR_DIR);
+ console.log(` ✓ vendor/ink regenerated from ink@${INK_VERSION} (${listFiles(VENDOR_DIR).length} files)`);
+ if (wrotePatch) console.log(` ✓ ${path.relative(root, PATCH_FILE)} rewritten`);
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+}
+
+if (require.main === module) {
+ try {
+ main();
+ } catch (err) {
+ console.error(` ✗ vendor-ink failed: ${err.message}`);
+ process.exitCode = 1;
+ }
+}
+
+module.exports = { INK_VERSION, INK_INTEGRITY, VENDOR_DIR, buildVendored, treesEqual };
diff --git a/scripts/verify-package.cjs b/scripts/verify-package.cjs
index 9a7f25b4..93d27321 100755
--- a/scripts/verify-package.cjs
+++ b/scripts/verify-package.cjs
@@ -73,17 +73,14 @@ check('no dangling script references', () => {
}
});
-check('scripts/apply-ink-patch.cjs ships in the tarball', () => {
- if (!existsSync(join(modDir, 'scripts', 'apply-ink-patch.cjs'))) throw new Error('missing scripts/apply-ink-patch.cjs');
-});
-
-check('ink is pinned exactly and the installed copy is patched', () => {
+check('patched ink is bundled into dist (ADR-017, no postinstall)', () => {
+ const bundle = readFileSync(join(modDir, 'dist', 'index.js'), 'utf-8');
+ if (/(?:from|import\()\s*["']ink["']/.test(bundle)) throw new Error('dist/index.js imports "ink" at runtime — the vendored build is not bundled');
+ for (const marker of ['__mercuryFrameGate', '__mercuryCursorAnchor', '__mercuryInkYogaHygiene', 'vendored: true']) {
+ if (!bundle.includes(marker)) throw new Error(`vendored ink marker missing from dist/index.js: ${marker}`);
+ }
const pkg = JSON.parse(readFileSync(join(modDir, 'package.json'), 'utf-8'));
- const ink = pkg.dependencies && pkg.dependencies.ink;
- if (!ink || !/^\d+\.\d+\.\d+$/.test(ink)) throw new Error(`ink must be pinned exactly (got ${ink})`);
- const { isPatched, pathsFor } = require(join(modDir, 'scripts', 'apply-ink-patch.cjs'));
- // ink is hoisted to the install root; pathsFor resolves it from modDir.
- if (!isPatched(pathsFor(modDir))) throw new Error('installed ink is NOT patched (Static.itemKey / frame gate markers missing) — postinstall fallback failed');
+ if (pkg.scripts && pkg.scripts.postinstall) throw new Error(`postinstall must not be needed any more (got: ${pkg.scripts.postinstall})`);
});
check('better-sqlite3 is optional', () => {
diff --git a/src/index.ts b/src/index.ts
index 23ffd7d7..97f4711b 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -78,7 +78,7 @@ import { startBackground, stopDaemon, showLogs, getDaemonStatus, registerRuntime
import { runUninstall } from './cli/uninstall.js';
import { runAttach } from './cli/attach.js';
import { installService, uninstallService, showServiceStatus, isServiceInstalled } from './cli/service.js';
-import { detectInkPatch, inkPatchFixCommand } from './ui/ink-patch-check.js';
+import { detectInkPatch, describeInkPatch, inkPatchFixCommand } from './ui/ink-patch-check.js';
import { runWithWatchdog } from './cli/watchdog.js';
import { setGitHubToken } from './utils/github.js';
import { selectWithArrowKeys } from './utils/arrow-select.js';
@@ -2302,7 +2302,7 @@ function runPlatformDoctor(): void {
console.log(` Daemon: ${daemon.running ? chalk.green(`running (PID: ${daemon.pid})`) : chalk.dim('not running')}`);
console.log(` Spotify inline art: ${canInlineArt ? chalk.green('supported (iTerm local)') : chalk.dim('disabled/fallback mode')}`);
const inkPatch = detectInkPatch();
- console.log(` Ink TUI patch: ${inkPatch.patched ? chalk.green('applied') : chalk.red(`MISSING (${inkPatch.missing.join('; ')})`)}`);
+ console.log(` Ink TUI patch: ${inkPatch.patched ? chalk.green(describeInkPatch(inkPatch)) : chalk.red(describeInkPatch(inkPatch))}`);
console.log('');
console.log(chalk.bold.white(' Keybinding Notes'));
console.log(` • View toggle: ${chalk.white('Ctrl+T')} (fallback: ${chalk.white('/view')})`);
@@ -2317,7 +2317,7 @@ function runPlatformDoctor(): void {
}
if (!inkPatch.patched) {
- console.log(chalk.yellow(' Warning: the bundled ink patch is not applied — the TUI stops rendering new messages after ~100 and may crash on long sessions.'));
+ console.log(chalk.yellow(' Warning: the ink patch set is not active — the TUI stops rendering new messages after ~100 and may crash on long sessions.'));
console.log(chalk.dim(` Fix: ${inkPatchFixCommand()} (then restart Mercury)`));
console.log('');
}
diff --git a/src/ui/ink-patch-check.test.ts b/src/ui/ink-patch-check.test.ts
index f32eea74..b23b5151 100644
--- a/src/ui/ink-patch-check.test.ts
+++ b/src/ui/ink-patch-check.test.ts
@@ -8,9 +8,12 @@ import {
inkPatchFixCommand,
inkPatchWarning,
detectInkPatch,
+ describeInkPatch,
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'] };
+
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; }';
const PATCHED_RECONCILER = 'const clearYogaRefs = (node) => {};';
@@ -46,7 +49,42 @@ describe('evaluateInkPatch', () => {
});
});
+describe('evaluateInkPatch (vendored build, ADR-017)', () => {
+ it('judges a vendored build by its runtime globals and ignores files', () => {
+ const s = evaluateInkPatch({
+ frameGate: {}, manifest: VENDORED_MANIFEST, yogaHygiene: true, cursorAnchor: { enabled: true },
+ // A stock node_modules copy must not matter once the build is vendored.
+ 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)');
+ });
+
+ it('names every missing runtime marker of a broken vendored build', () => {
+ const s = evaluateInkPatch({ manifest: { vendored: true, hunks: [] } });
+ expect(s.source).toBe('vendored');
+ 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/);
+ });
+
+ it('treats a malformed manifest as non-vendored', () => {
+ expect(evaluateInkPatch({ manifest: { vendored: 'yes' }, frameGate: {} }).source).toBe('node_modules');
+ });
+});
+
describe('detectInkPatch (this checkout)', () => {
+ it('reports the vendored, fully patched ink that tests and the bundle use', () => {
+ const s = detectInkPatch(true);
+ expect(s.source).toBe('vendored');
+ expect(s.missing).toEqual([]);
+ expect(s.patched).toBe(true);
+ });
+
it('mirrors the result to globalThis.__mercuryInkPatchMissing', () => {
const s = detectInkPatch(true);
expect((globalThis as any).__mercuryInkPatchMissing).toBe(!s.patched);
@@ -63,7 +101,7 @@ describe('fix command', () => {
writeFileSync(join(root, 'scripts', 'apply-ink-patch.cjs'), '// stub');
const found = findInkPatchScript(join(root, 'dist', 'deep'));
expect(found).toBe(join(root, 'scripts', 'apply-ink-patch.cjs'));
- expect(inkPatchFixCommand(found)).toBe(`node "${found}"`);
+ expect(inkPatchFixCommand(found)).toBe(`node "${join(root, 'scripts', 'vendor-ink.cjs')}" && npm run build`);
} finally {
rmSync(root, { recursive: true, force: true });
}
@@ -72,6 +110,7 @@ describe('fix command', () => {
it('falls back to a reinstall hint when the script is not shipped', () => {
expect(findInkPatchScript(tmpdir())).toBeNull();
expect(inkPatchFixCommand(null)).toContain('npm install -g @cosmicstack/mercury-agent');
+ expect(inkPatchFixCommand(null)).toContain('bundles the patched ink');
});
it('builds a single-paragraph warning naming the missing markers and the fix', () => {
diff --git a/src/ui/ink-patch-check.ts b/src/ui/ink-patch-check.ts
index 5e4dfc3a..1ea14610 100644
--- a/src/ui/ink-patch-check.ts
+++ b/src/ui/ink-patch-check.ts
@@ -1,6 +1,15 @@
/**
- * Runtime detection of the bundled ink patch (patches/ink+5.2.1.patch /
- * scripts/apply-ink-patch.cjs).
+ * Runtime detection of the Mercury ink patch set.
+ *
+ * Since ADR-017 ink is VENDORED: `vendor/ink` (stock 5.2.1 + 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
+ * sets a runtime global, so it is judged WITHOUT reading files — the stock
+ * ink that may still sit in node_modules is irrelevant and never inspected.
+ *
+ * The file-based path below remains for a non-vendored ink (a dev running
+ * source against node_modules); it is reported as source `node_modules`.
*
* On stock ink the TUI's `<Static itemKey>` prop is silently ignored: the
* transcript stops rendering new messages once the bounded window starts
@@ -17,14 +26,22 @@
* File-based markers are only consulted when the file could be read, so a
* standalone binary (no node_modules on disk) is judged by the gate alone.
*/
+// Side-effect import: evaluating ink (vendored in every build) installs the
+// runtime markers this module reads.
+import 'ink';
import { readFileSync, existsSync } from 'node:fs';
import { createRequire } from 'node:module';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+export type InkPatchSource = 'vendored' | 'node_modules';
+
export interface InkPatchStatus {
/** True when every observable marker is present. */
patched: boolean;
+ /** Where the running ink came from: the bundled vendor/ink build, or an
+ * ink resolved from node_modules (patched in place or stock). */
+ source: InkPatchSource;
/** Human-readable names of the missing markers (empty when patched). */
missing: string[];
/** Directory of the ink build that was inspected, when resolvable. */
@@ -34,6 +51,12 @@ export interface InkPatchStatus {
export interface InkPatchProbe {
/** `globalThis.__mercuryFrameGate` (object when patched ink.js loaded). */
frameGate?: unknown;
+ /** `globalThis.__mercuryInkPatch` manifest ({ vendored, hunks }). */
+ manifest?: unknown;
+ /** `globalThis.__mercuryInkYogaHygiene` (true when patched reconciler.js loaded). */
+ yogaHygiene?: unknown;
+ /** `globalThis.__mercuryCursorAnchor` (object when the cursor hunk loaded). */
+ cursorAnchor?: unknown;
/** Contents of ink/build/components/Static.js; null/undefined = unreadable. */
staticSource?: string | null;
/** Contents of ink/build/reconciler.js; null/undefined = unreadable. */
@@ -44,11 +67,30 @@ export const INK_PATCH_MARKERS = {
frameGate: 'freeze gate (ink.js)',
staticItemKey: 'Static.itemKey dedup (components/Static.js)',
yogaHygiene: 'Yoga free-node hygiene (reconciler.js)',
+ cursor: 'hardware cursor positioning (ink.js)',
} as const;
+interface InkPatchManifest { vendored: boolean; hunks: string[] }
+
+function asManifest(value: unknown): InkPatchManifest | null {
+ if (!value || typeof value !== 'object') return null;
+ const m = value as Partial<InkPatchManifest>;
+ if (typeof m.vendored !== 'boolean' || !Array.isArray(m.hunks)) return null;
+ return { vendored: m.vendored, hunks: m.hunks };
+}
+
/** Pure evaluation of a probe — unit-testable without touching node_modules. */
export function evaluateInkPatch(probe: InkPatchProbe): InkPatchStatus {
const missing: string[] = [];
+ const manifest = asManifest(probe.manifest);
+ if (manifest?.vendored) {
+ // Vendored build: every hunk is observable through runtime globals.
+ 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' };
+ }
if (!probe.frameGate || typeof probe.frameGate !== 'object') {
missing.push(INK_PATCH_MARKERS.frameGate);
}
@@ -59,7 +101,7 @@ export function evaluateInkPatch(probe: InkPatchProbe): InkPatchStatus {
if (typeof probe.reconcilerSource === 'string' && !probe.reconcilerSource.includes('clearYogaRefs')) {
missing.push(INK_PATCH_MARKERS.yogaHygiene);
}
- return { patched: missing.length === 0, missing };
+ return { patched: missing.length === 0, missing, source: 'node_modules' };
}
/** Best-effort read of the ink build files Node would load from here. */
@@ -89,9 +131,16 @@ let cached: InkPatchStatus | null = null;
*/
export function detectInkPatch(force = false): InkPatchStatus {
if (cached && !force) return cached;
- const sources = readInkSources();
+ const g = globalThis as any;
+ const vendored = asManifest(g.__mercuryInkPatch)?.vendored === true;
+ // A vendored build never consults node_modules: whatever ink is installed
+ // there is not the one rendering.
+ const sources = vendored ? { staticSource: null, reconcilerSource: null, inkBuildDir: undefined } : readInkSources();
const status = evaluateInkPatch({
- frameGate: (globalThis as any).__mercuryFrameGate,
+ frameGate: g.__mercuryFrameGate,
+ manifest: g.__mercuryInkPatch,
+ yogaHygiene: g.__mercuryInkYogaHygiene,
+ cursorAnchor: g.__mercuryCursorAnchor,
staticSource: sources.staticSource,
reconcilerSource: sources.reconcilerSource,
});
@@ -113,10 +162,18 @@ export function findInkPatchScript(startDir: string = dirname(fileURLToPath(impo
return null;
}
-/** The one command a user should run to fix an unpatched install. */
+/** 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)';
+}
+
+/** The one command a user should run to fix an unpatched install. Every
+ * release bundles the patched ink, so outside a source checkout the fix is
+ * a reinstall; in a checkout, regenerate vendor/ink and rebuild. */
export function inkPatchFixCommand(scriptPath: string | null = findInkPatchScript()): string {
- if (scriptPath) return `node "${scriptPath}"`;
- return 'npm install -g @cosmicstack/mercury-agent --force (re-runs the ink patch postinstall)';
+ if (scriptPath) return `node "${scriptPath.replace(/apply-ink-patch\.cjs$/, 'vendor-ink.cjs')}" && npm run build`;
+ return 'npm install -g @cosmicstack/mercury-agent --force (every release bundles the patched ink)';
}
/** One-paragraph warning for the TUI transcript / doctor. */
diff --git a/src/ui/live-region-guard.test.tsx b/src/ui/live-region-guard.test.tsx
index f5938172..c99b5d71 100644
--- a/src/ui/live-region-guard.test.tsx
+++ b/src/ui/live-region-guard.test.tsx
@@ -60,7 +60,9 @@ const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
// skip instead of failing the platform job red.
const inkPatchApplied = (() => {
try {
- return createRequire(import.meta.url)('../../scripts/apply-ink-patch.cjs').isPatched();
+ // ADR-017: tests resolve `ink` to vendor/ink (vitest.config.ts), so the
+ // vendored build is the one whose patch state matters.
+ return createRequire(import.meta.url)('../../scripts/apply-ink-patch.cjs').isVendoredPatched();
} catch {
return false;
}
diff --git a/tsconfig.json b/tsconfig.json
index 2f8deb15..cd757007 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -18,7 +18,8 @@
"jsxImportSource": "react",
"types": ["node"],
"paths": {
- "@/*": ["./src/*"]
+ "@/*": ["./src/*"],
+ "ink": ["./vendor/ink/build/index.d.ts"]
}
},
"include": ["src/**/*"],
diff --git a/tsup.config.ts b/tsup.config.ts
index 2f1a57bb..c98dad12 100644
--- a/tsup.config.ts
+++ b/tsup.config.ts
@@ -1,5 +1,13 @@
import { defineConfig } from "tsup";
import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { sep } from "node:path";
+
+// ADR-017: `ink` resolves to the committed, patched build in vendor/ink
+// (regenerated by scripts/vendor-ink.cjs) and is bundled into dist, so npm
+// installs, `--ignore-scripts` installs, Termux and the Bun standalone
+// binaries all run the same patched renderer — no postinstall step.
+const VENDORED_INK = fileURLToPath(new URL("./vendor/ink/build/index.js", import.meta.url));
const pkg = JSON.parse(readFileSync("./package.json", "utf8"));
@@ -23,13 +31,42 @@ export default defineConfig({
splitting: false,
sourcemap: true,
minify: false,
- banner: { js: "#!/usr/bin/env node" },
+ // createRequire: ink's bundled CommonJS dependencies (signal-exit 3, …)
+ // `require()` node builtins, which an ESM bundle has no global for.
+ banner: {
+ js: [
+ "#!/usr/bin/env node",
+ 'import { createRequire as __mercuryCreateRequire } from "node:module";',
+ "const require = __mercuryCreateRequire(import.meta.url);",
+ ].join("\n"),
+ },
// Inject the version so standalone binaries (Bun --compile) can read it
// without trying to load package.json from disk.
define: {
"globalThis.__MERCURY_VERSION__": JSON.stringify(channelVersion),
"globalThis.__MERCURY_CHANNEL_VERSION__": JSON.stringify(channelStamp),
},
+ noExternal: ["ink"],
+ esbuildOptions(options) {
+ options.alias = { ...(options.alias ?? {}), ink: VENDORED_INK };
+ },
+ esbuildPlugins: [
+ {
+ // ink's reconciler does `await import('./devtools.js')` when DEV=true.
+ // With splitting off, esbuild inlines that module — and its static
+ // `react-devtools-core` import, which crashes at load ("self is not
+ // defined"). Mercury never attaches React DevTools to the TUI, so the
+ // vendored devtools module is replaced with an empty one.
+ name: "mercury-ink-no-devtools",
+ setup(build) {
+ build.onResolve({ filter: /^\.\/devtools\.js$/ }, (args) =>
+ args.importer.includes(`vendor${sep}ink${sep}`)
+ ? { path: "ink-devtools-stub", namespace: "mercury-stub" }
+ : undefined);
+ build.onLoad({ filter: /.*/, namespace: "mercury-stub" }, () => ({ contents: "export {};", loader: "js" }));
+ },
+ },
+ ],
external: [
"ai",
"@ai-sdk/anthropic",
@@ -40,7 +77,9 @@ export default defineConfig({
"commander",
"dotenv",
"grammy",
- "ink",
+ // Only reachable from ink's DEV=true devtools hook (dynamic import in
+ // vendor/ink/build/reconciler.js) — never bundle it.
+ "react-devtools-core",
"js-tiktoken",
"marked",
"node-cron",
diff --git a/vendor/ink/build/apply-styles.js b/vendor/ink/build/apply-styles.js
new file mode 100644
index 00000000..88c9ee23
--- /dev/null
+++ b/vendor/ink/build/apply-styles.js
@@ -0,0 +1,175 @@
+"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 file
diff --git a/vendor/ink/build/build-layout.js b/vendor/ink/build/build-layout.js
new file mode 100644
index 00000000..6975196c
--- /dev/null
+++ b/vendor/ink/build/build-layout.js
@@ -0,0 +1,77 @@
+"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 file
diff --git a/vendor/ink/build/calculate-wrapped-text.js b/vendor/ink/build/calculate-wrapped-text.js
new file mode 100644
index 00000000..dde4742f
--- /dev/null
+++ b/vendor/ink/build/calculate-wrapped-text.js
@@ -0,0 +1,53 @@
+"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 file
diff --git a/vendor/ink/build/colorize.d.ts b/vendor/ink/build/colorize.d.ts
new file mode 100644
index 00000000..627451e8
--- /dev/null
+++ b/vendor/ink/build/colorize.d.ts
@@ -0,0 +1,3 @@
+type ColorType = 'foreground' | 'background';
+declare const colorize: (str: string, color: string | undefined, type: ColorType) => string;
+export default colorize;
diff --git a/vendor/ink/build/colorize.js b/vendor/ink/build/colorize.js
new file mode 100644
index 00000000..d28d3545
--- /dev/null
+++ b/vendor/ink/build/colorize.js
@@ -0,0 +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) => {
+ if (!color) {
+ return str;
+ }
+ if (isNamedColor(color)) {
+ if (type === 'foreground') {
+ return chalk[color](str);
+ }
+ const methodName = `bg${color[0].toUpperCase() + color.slice(1)}`;
+ return chalk[methodName](str);
+ }
+ if (color.startsWith('#')) {
+ return type === 'foreground'
+ ? chalk.hex(color)(str)
+ : chalk.bgHex(color)(str);
+ }
+ if (color.startsWith('ansi256')) {
+ const matches = ansiRegex.exec(color);
+ if (!matches) {
+ return str;
+ }
+ const value = Number(matches[1]);
+ return type === 'foreground'
+ ? chalk.ansi256(value)(str)
+ : chalk.bgAnsi256(value)(str);
+ }
+ if (color.startsWith('rgb')) {
+ const matches = rgbRegex.exec(color);
+ if (!matches) {
+ return str;
+ }
+ const firstValue = Number(matches[1]);
+ const secondValue = Number(matches[2]);
+ const thirdValue = Number(matches[3]);
+ return type === 'foreground'
+ ? chalk.rgb(firstValue, secondValue, thirdValue)(str)
+ : chalk.bgRgb(firstValue, secondValue, thirdValue)(str);
+ }
+ return str;
+};
+export default colorize;
diff --git a/vendor/ink/build/components/App.d.ts b/vendor/ink/build/components/App.d.ts
new file mode 100644
index 00000000..87c9c4c6
--- /dev/null
+++ b/vendor/ink/build/components/App.d.ts
@@ -0,0 +1,59 @@
+import { EventEmitter } from 'node:events';
+import React, { PureComponent, type ReactNode } from 'react';
+type Props = {
+ readonly children: ReactNode;
+ readonly stdin: NodeJS.ReadStream;
+ readonly stdout: NodeJS.WriteStream;
+ readonly stderr: NodeJS.WriteStream;
+ readonly writeToStdout: (data: string) => void;
+ readonly writeToStderr: (data: string) => void;
+ readonly exitOnCtrlC: boolean;
+ readonly onExit: (error?: Error) => void;
+};
+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;
+}
+export {};
diff --git a/vendor/ink/build/components/App.js b/vendor/ink/build/components/App.js
new file mode 100644
index 00000000..5a35b5d6
--- /dev/null
+++ b/vendor/ink/build/components/App.js
@@ -0,0 +1,285 @@
+import { EventEmitter } from 'node:events';
+import process from 'node:process';
+import React, { PureComponent } from 'react';
+import cliCursor from 'cli-cursor';
+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';
+// 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,
+ };
+ // 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');
+ }
+ }
+ 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);
+ }
+ this.rawModeEnabledCount++;
+ 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();
+ }
+ };
+ 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);
+ }
+ };
+ handleInput = (input) => {
+ // Exit on Ctrl+C
+ // eslint-disable-next-line unicorn/no-hex-escape
+ if (input === '\x03' && this.props.exitOnCtrlC) {
+ this.handleExit();
+ }
+ // 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 (input === shiftTab) {
+ this.focusPrevious();
+ }
+ }
+ };
+ handleExit = (error) => {
+ if (this.isRawModeSupported()) {
+ this.handleSetRawMode(false);
+ }
+ 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;
+ }
+ 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;
+ }
+ return {
+ id,
+ isActive: false,
+ };
+ }),
+ }));
+ };
+ findNextFocusable = (state) => {
+ const activeIndex = state.focusables.findIndex(focusable => {
+ return focusable.id === state.activeFocusId;
+ });
+ for (let index = activeIndex + 1; index < state.focusables.length; index++) {
+ const focusable = state.focusables[index];
+ if (focusable?.isActive) {
+ return focusable.id;
+ }
+ }
+ return undefined;
+ };
+ findPreviousFocusable = (state) => {
+ const activeIndex = state.focusables.findIndex(focusable => {
+ return focusable.id === state.activeFocusId;
+ });
+ for (let index = activeIndex - 1; index >= 0; index--) {
+ const focusable = state.focusables[index];
+ if (focusable?.isActive) {
+ return focusable.id;
+ }
+ }
+ return undefined;
+ };
+}
diff --git a/vendor/ink/build/components/AppContext.d.ts b/vendor/ink/build/components/AppContext.d.ts
new file mode 100644
index 00000000..f09d5edc
--- /dev/null
+++ b/vendor/ink/build/components/AppContext.d.ts
@@ -0,0 +1,11 @@
+export type Props = {
+ /**
+ * Exit (unmount) the whole Ink app.
+ */
+ readonly exit: (error?: Error) => void;
+};
+/**
+ * `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.js
new file mode 100644
index 00000000..2cfc3641
--- /dev/null
+++ b/vendor/ink/build/components/AppContext.js
@@ -0,0 +1,10 @@
+import { createContext } from 'react';
+/**
+ * `AppContext` is a React context, which exposes a method to manually exit the app (unmount).
+ */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const AppContext = createContext({
+ exit() { },
+});
+AppContext.displayName = 'InternalAppContext';
+export default AppContext;
diff --git a/vendor/ink/build/components/Box.d.ts b/vendor/ink/build/components/Box.d.ts
new file mode 100644
index 00000000..3320cf50
--- /dev/null
+++ b/vendor/ink/build/components/Box.d.ts
@@ -0,0 +1,62 @@
+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'>;
+/**
+ * `<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 columnGap?: number | undefined;
+ readonly rowGap?: number | undefined;
+ readonly gap?: number | undefined;
+ readonly margin?: number | undefined;
+ readonly marginX?: number | undefined;
+ readonly marginY?: number | undefined;
+ readonly marginTop?: number | undefined;
+ readonly marginBottom?: number | undefined;
+ readonly marginLeft?: number | undefined;
+ readonly marginRight?: number | undefined;
+ readonly padding?: number | undefined;
+ readonly paddingX?: number | undefined;
+ readonly paddingY?: number | undefined;
+ readonly paddingTop?: number | undefined;
+ readonly paddingBottom?: number | undefined;
+ readonly paddingLeft?: number | undefined;
+ readonly paddingRight?: number | undefined;
+ readonly flexGrow?: number | undefined;
+ readonly flexShrink?: number | undefined;
+ 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 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 minHeight?: number | string | undefined;
+ readonly display?: "flex" | "none" | undefined;
+ readonly borderStyle?: (keyof import("cli-boxes").Boxes | import("cli-boxes").BoxStyle) | undefined;
+ readonly borderTop?: boolean | undefined;
+ readonly borderBottom?: boolean | undefined;
+ readonly borderLeft?: boolean | undefined;
+ readonly borderRight?: boolean | undefined;
+ readonly borderColor?: import("type-fest").LiteralUnion<import("ansi-styles").ForegroundColorName, string> | undefined;
+ readonly borderTopColor?: import("type-fest").LiteralUnion<import("ansi-styles").ForegroundColorName, string> | undefined;
+ readonly borderBottomColor?: import("type-fest").LiteralUnion<import("ansi-styles").ForegroundColorName, string> | undefined;
+ readonly borderLeftColor?: import("type-fest").LiteralUnion<import("ansi-styles").ForegroundColorName, string> | undefined;
+ readonly borderRightColor?: import("type-fest").LiteralUnion<import("ansi-styles").ForegroundColorName, string> | undefined;
+ readonly borderDimColor?: boolean | undefined;
+ readonly borderTopDimColor?: boolean | undefined;
+ readonly borderBottomDimColor?: boolean | undefined;
+ readonly borderLeftDimColor?: boolean | undefined;
+ readonly borderRightDimColor?: boolean | undefined;
+ readonly overflow?: "visible" | "hidden" | undefined;
+ readonly overflowX?: "visible" | "hidden" | undefined;
+ readonly overflowY?: "visible" | "hidden" | undefined;
+} & {
+ children?: React.ReactNode | undefined;
+} & React.RefAttributes<DOMElement>>;
+export default Box;
diff --git a/vendor/ink/build/components/Box.js b/vendor/ink/build/components/Box.js
new file mode 100644
index 00000000..2e5b96b8
--- /dev/null
+++ b/vendor/ink/build/components/Box.js
@@ -0,0 +1,19 @@
+import React, { forwardRef } from 'react';
+/**
+ * `<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: {
+ ...style,
+ overflowX: style.overflowX ?? style.overflow ?? 'visible',
+ overflowY: style.overflowY ?? style.overflow ?? 'visible',
+ } }, children));
+});
+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.js
new file mode 100644
index 00000000..42319d18
--- /dev/null
+++ b/vendor/ink/build/components/Color.js
@@ -0,0 +1,62 @@
+"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 file
diff --git a/vendor/ink/build/components/ErrorOverview.d.ts b/vendor/ink/build/components/ErrorOverview.d.ts
new file mode 100644
index 00000000..5f157b96
--- /dev/null
+++ b/vendor/ink/build/components/ErrorOverview.d.ts
@@ -0,0 +1,6 @@
+import React from 'react';
+type Props = {
+ readonly error: Error;
+};
+export default function ErrorOverview({ error }: Props): React.JSX.Element;
+export {};
diff --git a/vendor/ink/build/components/ErrorOverview.js b/vendor/ink/build/components/ErrorOverview.js
new file mode 100644
index 00000000..b2330887
--- /dev/null
+++ b/vendor/ink/build/components/ErrorOverview.js
@@ -0,0 +1,78 @@
+import * as fs from 'node:fs';
+import { cwd } from 'node:process';
+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()}/`, '');
+};
+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 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);
+ if (excerpt) {
+ for (const { line } of excerpt) {
+ lineWidth = Math.max(lineWidth, String(line).length);
+ }
+ }
+ }
+ return (React.createElement(Box, { flexDirection: "column", padding: 1 },
+ React.createElement(Box, null,
+ React.createElement(Text, { backgroundColor: "red", color: "white" },
+ ' ',
+ "ERROR",
+ ' '),
+ React.createElement(Text, null,
+ " ",
+ error.message)),
+ origin && 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 },
+ 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 },
+ 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 => {
+ 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 },
+ React.createElement(Text, { dimColor: true }, "- "),
+ React.createElement(Text, { dimColor: true, bold: true }, line)));
+ }
+ return (React.createElement(Box, { key: line },
+ React.createElement(Text, { dimColor: true }, "- "),
+ React.createElement(Text, { dimColor: true, bold: true }, parsedLine.function),
+ React.createElement(Text, { dimColor: true, color: "gray" },
+ ' ',
+ "(",
+ cleanupPath(parsedLine.file) ?? '',
+ ":",
+ parsedLine.line,
+ ":",
+ parsedLine.column,
+ ")")));
+ })))));
+}
diff --git a/vendor/ink/build/components/FocusContext.d.ts b/vendor/ink/build/components/FocusContext.d.ts
new file mode 100644
index 00000000..cfa3b581
--- /dev/null
+++ b/vendor/ink/build/components/FocusContext.d.ts
@@ -0,0 +1,16 @@
+export type Props = {
+ readonly activeId?: string;
+ readonly add: (id: string, options: {
+ autoFocus: boolean;
+ }) => void;
+ readonly remove: (id: string) => void;
+ readonly activate: (id: string) => void;
+ readonly deactivate: (id: string) => void;
+ readonly enableFocus: () => void;
+ readonly disableFocus: () => void;
+ readonly focusNext: () => void;
+ readonly focusPrevious: () => void;
+ readonly focus: (id: string) => void;
+};
+declare const FocusContext: import("react").Context<Props>;
+export default FocusContext;
diff --git a/vendor/ink/build/components/FocusContext.js b/vendor/ink/build/components/FocusContext.js
new file mode 100644
index 00000000..b6340ae0
--- /dev/null
+++ b/vendor/ink/build/components/FocusContext.js
@@ -0,0 +1,16 @@
+import { createContext } from 'react';
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const FocusContext = createContext({
+ activeId: undefined,
+ add() { },
+ remove() { },
+ activate() { },
+ deactivate() { },
+ enableFocus() { },
+ disableFocus() { },
+ focusNext() { },
+ focusPrevious() { },
+ focus() { },
+});
+FocusContext.displayName = 'InternalFocusContext';
+export default FocusContext;
diff --git a/vendor/ink/build/components/Newline.d.ts b/vendor/ink/build/components/Newline.d.ts
new file mode 100644
index 00000000..c51a05ec
--- /dev/null
+++ b/vendor/ink/build/components/Newline.d.ts
@@ -0,0 +1,13 @@
+import React from 'react';
+export type Props = {
+ /**
+ * Number of newlines to insert.
+ *
+ * @default 1
+ */
+ readonly count?: number;
+};
+/**
+ * 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.js
new file mode 100644
index 00000000..58a106b8
--- /dev/null
+++ b/vendor/ink/build/components/Newline.js
@@ -0,0 +1,7 @@
+import React from 'react';
+/**
+ * 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/Spacer.d.ts b/vendor/ink/build/components/Spacer.d.ts
new file mode 100644
index 00000000..82171f86
--- /dev/null
+++ b/vendor/ink/build/components/Spacer.d.ts
@@ -0,0 +1,6 @@
+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.
+ */
+export default function Spacer(): React.JSX.Element;
diff --git a/vendor/ink/build/components/Spacer.js b/vendor/ink/build/components/Spacer.js
new file mode 100644
index 00000000..bdb26d95
--- /dev/null
+++ b/vendor/ink/build/components/Spacer.js
@@ -0,0 +1,9 @@
+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.
+ */
+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.ts
new file mode 100644
index 00000000..a4d515b3
--- /dev/null
+++ b/vendor/ink/build/components/Static.d.ts
@@ -0,0 +1,39 @@
+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.
+ */
+ readonly items: T[];
+ /**
+ * 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;
+ /**
+ * 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.
+ * 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.
+ */
+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.js
new file mode 100644
index 00000000..e22c94e5
--- /dev/null
+++ b/vendor/ink/build/components/Static.js
@@ -0,0 +1,75 @@
+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);
+ }
+ }
+ 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);
+ }
+ 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));
+}
diff --git a/vendor/ink/build/components/StderrContext.d.ts b/vendor/ink/build/components/StderrContext.d.ts
new file mode 100644
index 00000000..6e65a172
--- /dev/null
+++ b/vendor/ink/build/components/StderrContext.d.ts
@@ -0,0 +1,17 @@
+export type Props = {
+ /**
+ * Stderr stream passed to `render()` in `options.stderr` or `process.stderr` by default.
+ */
+ readonly stderr: NodeJS.WriteStream;
+ /**
+ * 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.
+ */
+ readonly write: (data: string) => void;
+};
+/**
+ * `StderrContext` is a React context, which exposes 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.js
new file mode 100644
index 00000000..41c44554
--- /dev/null
+++ b/vendor/ink/build/components/StderrContext.js
@@ -0,0 +1,12 @@
+import process from 'node:process';
+import { createContext } from 'react';
+/**
+ * `StderrContext` is a React context, which exposes stderr stream.
+ */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const StderrContext = createContext({
+ stderr: process.stderr,
+ write() { },
+});
+StderrContext.displayName = 'InternalStderrContext';
+export default StderrContext;
diff --git a/vendor/ink/build/components/StdinContext.d.ts b/vendor/ink/build/components/StdinContext.d.ts
new file mode 100644
index 00000000..c7259e5e
--- /dev/null
+++ b/vendor/ink/build/components/StdinContext.d.ts
@@ -0,0 +1,23 @@
+import { EventEmitter } from 'node:events';
+export type Props = {
+ /**
+ * 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;
+ /**
+ * 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;
+ /**
+ * 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;
+ readonly internal_exitOnCtrlC: boolean;
+ readonly internal_eventEmitter: EventEmitter;
+};
+/**
+ * `StdinContext` is a React context, which exposes 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.js
new file mode 100644
index 00000000..67047b50
--- /dev/null
+++ b/vendor/ink/build/components/StdinContext.js
@@ -0,0 +1,18 @@
+import { EventEmitter } from 'node:events';
+import process from 'node:process';
+import { createContext } from 'react';
+/**
+ * `StdinContext` is a React context, which exposes input stream.
+ */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const StdinContext = createContext({
+ stdin: process.stdin,
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ internal_eventEmitter: new EventEmitter(),
+ setRawMode() { },
+ isRawModeSupported: false,
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ internal_exitOnCtrlC: true,
+});
+StdinContext.displayName = 'InternalStdinContext';
+export default StdinContext;
diff --git a/vendor/ink/build/components/StdoutContext.d.ts b/vendor/ink/build/components/StdoutContext.d.ts
new file mode 100644
index 00000000..03d17cf2
--- /dev/null
+++ b/vendor/ink/build/components/StdoutContext.d.ts
@@ -0,0 +1,17 @@
+export type Props = {
+ /**
+ * Stdout stream passed to `render()` in `options.stdout` or `process.stdout` by default.
+ */
+ readonly stdout: NodeJS.WriteStream;
+ /**
+ * 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.
+ */
+ readonly write: (data: string) => void;
+};
+/**
+ * `StdoutContext` is a React context, which exposes 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.js
new file mode 100644
index 00000000..f6108293
--- /dev/null
+++ b/vendor/ink/build/components/StdoutContext.js
@@ -0,0 +1,12 @@
+import process from 'node:process';
+import { createContext } from 'react';
+/**
+ * `StdoutContext` is a React context, which exposes stdout stream, where Ink renders your app.
+ */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+const StdoutContext = createContext({
+ stdout: process.stdout,
+ write() { },
+});
+StdoutContext.displayName = 'InternalStdoutContext';
+export default StdoutContext;
diff --git a/vendor/ink/build/components/Text.d.ts b/vendor/ink/build/components/Text.d.ts
new file mode 100644
index 00000000..01b12d8a
--- /dev/null
+++ b/vendor/ink/build/components/Text.d.ts
@@ -0,0 +1,49 @@
+import React, { type ReactNode } from 'react';
+import { type ForegroundColorName } from 'chalk';
+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.
+ */
+ readonly color?: LiteralUnion<ForegroundColorName, string>;
+ /**
+ * Same as `color`, but for background.
+ */
+ readonly backgroundColor?: LiteralUnion<ForegroundColorName, string>;
+ /**
+ * Dim the color (emit a small amount of light).
+ */
+ readonly dimColor?: boolean;
+ /**
+ * Make the text bold.
+ */
+ readonly bold?: boolean;
+ /**
+ * Make the text italic.
+ */
+ readonly italic?: boolean;
+ /**
+ * Make the text underlined.
+ */
+ readonly underline?: boolean;
+ /**
+ * Make the text crossed with a line.
+ */
+ readonly strikethrough?: boolean;
+ /**
+ * 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.
+ */
+ 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;
diff --git a/vendor/ink/build/components/Text.js b/vendor/ink/build/components/Text.js
new file mode 100644
index 00000000..edee34b8
--- /dev/null
+++ b/vendor/ink/build/components/Text.js
@@ -0,0 +1,39 @@
+import React from 'react';
+import chalk from 'chalk';
+import colorize from '../colorize.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) {
+ return null;
+ }
+ const transform = (children) => {
+ if (dimColor) {
+ children = chalk.dim(children);
+ }
+ if (color) {
+ children = colorize(children, color, 'foreground');
+ }
+ if (backgroundColor) {
+ children = colorize(children, backgroundColor, 'background');
+ }
+ if (bold) {
+ children = chalk.bold(children);
+ }
+ if (italic) {
+ children = chalk.italic(children);
+ }
+ if (underline) {
+ children = chalk.underline(children);
+ }
+ if (strikethrough) {
+ children = chalk.strikethrough(children);
+ }
+ if (inverse) {
+ children = chalk.inverse(children);
+ }
+ return children;
+ };
+ return (React.createElement("ink-text", { style: { flexGrow: 0, flexShrink: 1, flexDirection: 'row', textWrap: wrap }, internal_transform: transform }, children));
+}
diff --git a/vendor/ink/build/components/Transform.d.ts b/vendor/ink/build/components/Transform.d.ts
new file mode 100644
index 00000000..98aa7dd7
--- /dev/null
+++ b/vendor/ink/build/components/Transform.d.ts
@@ -0,0 +1,15 @@
+import React, { type ReactNode } from 'react';
+export type Props = {
+ /**
+ * Function which transforms children output. It accepts children and must return transformed children too.
+ */
+ 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;
diff --git a/vendor/ink/build/components/Transform.js b/vendor/ink/build/components/Transform.js
new file mode 100644
index 00000000..4dc3a1a6
--- /dev/null
+++ b/vendor/ink/build/components/Transform.js
@@ -0,0 +1,13 @@
+import React from 'react';
+/**
+ * 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) {
+ return null;
+ }
+ return (React.createElement("ink-text", { style: { flexGrow: 0, flexShrink: 1, flexDirection: 'row' }, internal_transform: transform }, children));
+}
diff --git a/vendor/ink/build/devtools-window-polyfill.d.ts b/vendor/ink/build/devtools-window-polyfill.d.ts
new file mode 100644
index 00000000..cb0ff5c3
--- /dev/null
+++ b/vendor/ink/build/devtools-window-polyfill.d.ts
@@ -0,0 +1 @@
+export {};
diff --git a/vendor/ink/build/devtools-window-polyfill.js b/vendor/ink/build/devtools-window-polyfill.js
new file mode 100644
index 00000000..8f5a3a95
--- /dev/null
+++ b/vendor/ink/build/devtools-window-polyfill.js
@@ -0,0 +1,63 @@
+// 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;
+// These things must exist before importing `react-devtools-core`
+customGlobal.WebSocket ||= ws;
+customGlobal.window ||= global;
+customGlobal.self ||= global;
+// 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.
+// See https://github.com/facebook/react/blob/edf6eac8a181860fd8a2d076a43806f1237495a1/packages/react-devtools-shared/src/types.js#L24
+customGlobal.window.__REACT_DEVTOOLS_COMPONENT_FILTERS__ = [
+ {
+ // ComponentFilterElementType
+ type: 1,
+ // ElementTypeHostComponent
+ value: 7,
+ isEnabled: true,
+ },
+ {
+ // ComponentFilterDisplayName
+ type: 2,
+ value: 'InternalApp',
+ isEnabled: true,
+ isValid: true,
+ },
+ {
+ // ComponentFilterDisplayName
+ type: 2,
+ value: 'InternalAppContext',
+ isEnabled: true,
+ isValid: true,
+ },
+ {
+ // ComponentFilterDisplayName
+ type: 2,
+ value: 'InternalStdoutContext',
+ isEnabled: true,
+ isValid: true,
+ },
+ {
+ // ComponentFilterDisplayName
+ type: 2,
+ value: 'InternalStderrContext',
+ isEnabled: true,
+ isValid: true,
+ },
+ {
+ // ComponentFilterDisplayName
+ type: 2,
+ value: 'InternalStdinContext',
+ isEnabled: true,
+ isValid: true,
+ },
+ {
+ // ComponentFilterDisplayName
+ type: 2,
+ value: 'InternalFocusContext',
+ isEnabled: true,
+ isValid: true,
+ },
+];
diff --git a/vendor/ink/build/devtools.d.ts b/vendor/ink/build/devtools.d.ts
new file mode 100644
index 00000000..5c830167
--- /dev/null
+++ b/vendor/ink/build/devtools.d.ts
@@ -0,0 +1 @@
+import './devtools-window-polyfill.js';
diff --git a/vendor/ink/build/devtools.js b/vendor/ink/build/devtools.js
new file mode 100644
index 00000000..c6f72b94
--- /dev/null
+++ b/vendor/ink/build/devtools.js
@@ -0,0 +1,8 @@
+/* eslint-disable import/order */
+// eslint-disable-next-line import/no-unassigned-import
+import './devtools-window-polyfill.js';
+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
+// @ts-expect-error
+import devtools from 'react-devtools-core';
+// eslint-disable-next-line @typescript-eslint/no-unsafe-call
+devtools.connectToDevTools();
diff --git a/vendor/ink/build/dom.d.ts b/vendor/ink/build/dom.d.ts
new file mode 100644
index 00000000..3e0ce25c
--- /dev/null
+++ b/vendor/ink/build/dom.d.ts
@@ -0,0 +1,42 @@
+import { type Node as YogaNode } from 'yoga-layout';
+import { type Styles } from './styles.js';
+import { type OutputTransformer } from './render-node-to-output.js';
+type InkNode = {
+ parentNode: DOMElement | undefined;
+ yogaNode?: YogaNode;
+ internal_static?: boolean;
+ style: Styles;
+};
+export type TextName = '#text';
+export type ElementNames = 'ink-root' | 'ink-box' | 'ink-text' | 'ink-virtual-text';
+export type NodeNames = ElementNames | TextName;
+export type DOMElement = {
+ nodeName: ElementNames;
+ attributes: Record<string, DOMNodeAttribute>;
+ childNodes: DOMNode[];
+ internal_transform?: OutputTransformer;
+ isStaticDirty?: boolean;
+ staticNode?: DOMElement;
+ onComputeLayout?: () => void;
+ onRender?: () => void;
+ onImmediateRender?: () => void;
+} & InkNode;
+export type TextNode = {
+ nodeName: TextName;
+ nodeValue: string;
+} & InkNode;
+export type DOMNode<T = {
+ nodeName: NodeNames;
+}> = T extends {
+ nodeName: infer U;
+} ? U extends '#text' ? TextNode : DOMElement : never;
+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 setAttribute: (node: DOMElement, key: string, value: DOMNodeAttribute) => void;
+export declare const setStyle: (node: DOMNode, style: Styles) => void;
+export declare const createTextNode: (text: string) => TextNode;
+export declare const setTextNodeValue: (node: TextNode, text: string) => void;
+export {};
diff --git a/vendor/ink/build/dom.js b/vendor/ink/build/dom.js
new file mode 100644
index 00000000..8d0ae6d6
--- /dev/null
+++ b/vendor/ink/build/dom.js
@@ -0,0 +1,116 @@
+import Yoga from 'yoga-layout';
+import measureText from './measure-text.js';
+import wrapText from './wrap-text.js';
+import squashTextNodes from './squash-text-nodes.js';
+export const createNode = (nodeName) => {
+ const node = {
+ nodeName,
+ style: {},
+ attributes: {},
+ childNodes: [],
+ parentNode: undefined,
+ yogaNode: nodeName === 'ink-virtual-text' ? undefined : Yoga.Node.create(),
+ };
+ if (nodeName === 'ink-text') {
+ node.yogaNode?.setMeasureFunc(measureTextNode.bind(null, node));
+ }
+ return node;
+};
+export const appendChildNode = (node, childNode) => {
+ if (childNode.parentNode) {
+ removeChildNode(childNode.parentNode, childNode);
+ }
+ childNode.parentNode = node;
+ node.childNodes.push(childNode);
+ if (childNode.yogaNode) {
+ node.yogaNode?.insertChild(childNode.yogaNode, node.yogaNode.getChildCount());
+ }
+ if (node.nodeName === 'ink-text' || node.nodeName === 'ink-virtual-text') {
+ markNodeAsDirty(node);
+ }
+};
+export 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);
+ 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());
+ }
+ 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);
+ }
+ removeNode.parentNode = undefined;
+ const index = node.childNodes.indexOf(removeNode);
+ if (index >= 0) {
+ node.childNodes.splice(index, 1);
+ }
+ if (node.nodeName === 'ink-text' || node.nodeName === 'ink-virtual-text') {
+ markNodeAsDirty(node);
+ }
+};
+export const setAttribute = (node, key, value) => {
+ node.attributes[key] = value;
+};
+export const setStyle = (node, style) => {
+ node.style = style;
+};
+export const createTextNode = (text) => {
+ const node = {
+ nodeName: '#text',
+ nodeValue: text,
+ yogaNode: undefined,
+ parentNode: undefined,
+ style: {},
+ };
+ setTextNodeValue(node, text);
+ return node;
+};
+const measureTextNode = function (node, width) {
+ const text = node.nodeName === '#text' ? node.nodeValue : squashTextNodes(node);
+ const dimensions = measureText(text);
+ // 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) {
+ 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 markNodeAsDirty = (node) => {
+ // Mark closest Yoga node as dirty to measure text dimensions again
+ const yogaNode = findClosestYogaNode(node);
+ yogaNode?.markDirty();
+};
+export const setTextNodeValue = (node, text) => {
+ if (typeof text !== 'string') {
+ text = String(text);
+ }
+ node.nodeValue = text;
+ markNodeAsDirty(node);
+};
diff --git a/vendor/ink/build/experimental/apply-style.js b/vendor/ink/build/experimental/apply-style.js
new file mode 100644
index 00000000..59507521
--- /dev/null
+++ b/vendor/ink/build/experimental/apply-style.js
@@ -0,0 +1,140 @@
+"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 file
diff --git a/vendor/ink/build/experimental/dom.js b/vendor/ink/build/experimental/dom.js
new file mode 100644
index 00000000..5bfe0bc1
--- /dev/null
+++ b/vendor/ink/build/experimental/dom.js
@@ -0,0 +1,123 @@
+"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 file
diff --git a/vendor/ink/build/experimental/output.js b/vendor/ink/build/experimental/output.js
new file mode 100644
index 00000000..52354b04
--- /dev/null
+++ b/vendor/ink/build/experimental/output.js
@@ -0,0 +1,91 @@
+"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 file
diff --git a/vendor/ink/build/experimental/reconciler.js b/vendor/ink/build/experimental/reconciler.js
new file mode 100644
index 00000000..d6580b69
--- /dev/null
+++ b/vendor/ink/build/experimental/reconciler.js
@@ -0,0 +1,141 @@
+"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 file
diff --git a/vendor/ink/build/experimental/renderer.js b/vendor/ink/build/experimental/renderer.js
new file mode 100644
index 00000000..7b57ec72
--- /dev/null
+++ b/vendor/ink/build/experimental/renderer.js
@@ -0,0 +1,81 @@
+"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 file
diff --git a/vendor/ink/build/get-max-width.d.ts b/vendor/ink/build/get-max-width.d.ts
new file mode 100644
index 00000000..caf50c14
--- /dev/null
+++ b/vendor/ink/build/get-max-width.d.ts
@@ -0,0 +1,3 @@
+import { type Node as YogaNode } from 'yoga-layout';
+declare const getMaxWidth: (yogaNode: YogaNode) => number;
+export default getMaxWidth;
diff --git a/vendor/ink/build/get-max-width.js b/vendor/ink/build/get-max-width.js
new file mode 100644
index 00000000..c10fbdc6
--- /dev/null
+++ b/vendor/ink/build/get-max-width.js
@@ -0,0 +1,9 @@
+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));
+};
+export default getMaxWidth;
diff --git a/vendor/ink/build/hooks/use-app.d.ts b/vendor/ink/build/hooks/use-app.d.ts
new file mode 100644
index 00000000..d06fdfeb
--- /dev/null
+++ b/vendor/ink/build/hooks/use-app.d.ts
@@ -0,0 +1,5 @@
+/**
+ * `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;
diff --git a/vendor/ink/build/hooks/use-app.js b/vendor/ink/build/hooks/use-app.js
new file mode 100644
index 00000000..2fcb94da
--- /dev/null
+++ b/vendor/ink/build/hooks/use-app.js
@@ -0,0 +1,7 @@
+import { useContext } 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;
diff --git a/vendor/ink/build/hooks/use-focus-manager.d.ts b/vendor/ink/build/hooks/use-focus-manager.d.ts
new file mode 100644
index 00000000..17236a5f
--- /dev/null
+++ b/vendor/ink/build/hooks/use-focus-manager.d.ts
@@ -0,0 +1,34 @@
+import { type Props } from '../components/FocusContext.js';
+type Output = {
+ /**
+ * 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.
+ */
+ 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.
+ */
+ 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.
+ */
+ 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.
+ */
+ focus: Props['focus'];
+};
+/**
+ * This hook exposes methods to enable or disable focus management for all
+ * components or manually switch focus to 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.js
new file mode 100644
index 00000000..ac12e8ab
--- /dev/null
+++ b/vendor/ink/build/hooks/use-focus-manager.js
@@ -0,0 +1,17 @@
+import { useContext } 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.
+ */
+const useFocusManager = () => {
+ const focusContext = useContext(FocusContext);
+ return {
+ enableFocus: focusContext.enableFocus,
+ disableFocus: focusContext.disableFocus,
+ focusNext: focusContext.focusNext,
+ focusPrevious: focusContext.focusPrevious,
+ focus: focusContext.focus,
+ };
+};
+export default useFocusManager;
diff --git a/vendor/ink/build/hooks/use-focus.d.ts b/vendor/ink/build/hooks/use-focus.d.ts
new file mode 100644
index 00000000..0e4e2285
--- /dev/null
+++ b/vendor/ink/build/hooks/use-focus.d.ts
@@ -0,0 +1,34 @@
+type Input = {
+ /**
+ * 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.
+ */
+ autoFocus?: boolean;
+ /**
+ * Assign an ID to this component, so it can be programmatically focused with `focus(id)`.
+ */
+ id?: string;
+};
+type Output = {
+ /**
+ * Determines whether this component is focused or not.
+ */
+ isFocused: boolean;
+ /**
+ * 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.
+ */
+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.js
new file mode 100644
index 00000000..0f0e1b5a
--- /dev/null
+++ b/vendor/ink/build/hooks/use-focus.js
@@ -0,0 +1,46 @@
+import { useEffect, useContext, useMemo } 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.
+ */
+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]);
+ useEffect(() => {
+ add(id, { autoFocus });
+ return () => {
+ remove(id);
+ };
+ }, [id, autoFocus]);
+ useEffect(() => {
+ if (isActive) {
+ activate(id);
+ }
+ else {
+ deactivate(id);
+ }
+ }, [isActive, id]);
+ useEffect(() => {
+ if (!isRawModeSupported || !isActive) {
+ return;
+ }
+ setRawMode(true);
+ return () => {
+ setRawMode(false);
+ };
+ }, [isActive]);
+ return {
+ isFocused: Boolean(id) && activeId === id,
+ focus,
+ };
+};
+export default useFocus;
diff --git a/vendor/ink/build/hooks/use-input.d.ts b/vendor/ink/build/hooks/use-input.d.ts
new file mode 100644
index 00000000..47acf9ab
--- /dev/null
+++ b/vendor/ink/build/hooks/use-input.d.ts
@@ -0,0 +1,97 @@
+/**
+ * Handy information about a key that was pressed.
+ */
+export type Key = {
+ /**
+ * Up arrow key was pressed.
+ */
+ upArrow: boolean;
+ /**
+ * Down arrow key was pressed.
+ */
+ downArrow: boolean;
+ /**
+ * Left arrow key was pressed.
+ */
+ leftArrow: boolean;
+ /**
+ * Right arrow key was pressed.
+ */
+ rightArrow: boolean;
+ /**
+ * Page Down key was pressed.
+ */
+ pageDown: boolean;
+ /**
+ * Page Up key was pressed.
+ */
+ pageUp: boolean;
+ /**
+ * Return (Enter) key was pressed.
+ */
+ return: boolean;
+ /**
+ * Escape key was pressed.
+ */
+ escape: boolean;
+ /**
+ * Ctrl key was pressed.
+ */
+ ctrl: boolean;
+ /**
+ * Shift key was pressed.
+ */
+ shift: boolean;
+ /**
+ * Tab key was pressed.
+ */
+ tab: boolean;
+ /**
+ * Backspace key was pressed.
+ */
+ backspace: boolean;
+ /**
+ * Delete key was pressed.
+ */
+ delete: boolean;
+ /**
+ * [Meta key](https://en.wikipedia.org/wiki/Meta_key) was pressed.
+ */
+ meta: boolean;
+};
+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
+ */
+ 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 …
+ * };
+ * ```
+ */
+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.js
new file mode 100644
index 00000000..a92b0f4c
--- /dev/null
+++ b/vendor/ink/build/hooks/use-input.js
@@ -0,0 +1,95 @@
+import { useEffect } from 'react';
+import parseKeypress, { nonAlphanumericKeys } from '../parse-keypress.js';
+import reconciler from '../reconciler.js';
+import useStdin 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 …
+ * };
+ * ```
+ */
+const useInput = (inputHandler, options = {}) => {
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ const { stdin, setRawMode, internal_exitOnCtrlC, internal_eventEmitter } = useStdin();
+ useEffect(() => {
+ if (options.isActive === false) {
+ return;
+ }
+ setRawMode(true);
+ return () => {
+ setRawMode(false);
+ };
+ }, [options.isActive, setRawMode]);
+ 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);
+ return () => {
+ internal_eventEmitter?.removeListener('input', handleData);
+ };
+ }, [options.isActive, stdin, internal_exitOnCtrlC, inputHandler]);
+};
+export default useInput;
diff --git a/vendor/ink/build/hooks/use-stderr.d.ts b/vendor/ink/build/hooks/use-stderr.d.ts
new file mode 100644
index 00000000..c034fb39
--- /dev/null
+++ b/vendor/ink/build/hooks/use-stderr.d.ts
@@ -0,0 +1,5 @@
+/**
+ * `useStderr` is a React hook, which exposes stderr stream.
+ */
+declare const useStderr: () => import("../components/StderrContext.js").Props;
+export default useStderr;
diff --git a/vendor/ink/build/hooks/use-stderr.js b/vendor/ink/build/hooks/use-stderr.js
new file mode 100644
index 00000000..a974153c
--- /dev/null
+++ b/vendor/ink/build/hooks/use-stderr.js
@@ -0,0 +1,7 @@
+import { useContext } from 'react';
+import StderrContext from '../components/StderrContext.js';
+/**
+ * `useStderr` is a React hook, which exposes stderr stream.
+ */
+const useStderr = () => useContext(StderrContext);
+export default useStderr;
diff --git a/vendor/ink/build/hooks/use-stdin.d.ts b/vendor/ink/build/hooks/use-stdin.d.ts
new file mode 100644
index 00000000..39c97f48
--- /dev/null
+++ b/vendor/ink/build/hooks/use-stdin.d.ts
@@ -0,0 +1,5 @@
+/**
+ * `useStdin` is a React hook, which exposes stdin stream.
+ */
+declare const useStdin: () => import("../components/StdinContext.js").Props;
+export default useStdin;
diff --git a/vendor/ink/build/hooks/use-stdin.js b/vendor/ink/build/hooks/use-stdin.js
new file mode 100644
index 00000000..861f6188
--- /dev/null
+++ b/vendor/ink/build/hooks/use-stdin.js
@@ -0,0 +1,7 @@
+import { useContext } from 'react';
+import StdinContext from '../components/StdinContext.js';
+/**
+ * `useStdin` is a React hook, which exposes stdin stream.
+ */
+const useStdin = () => useContext(StdinContext);
+export default useStdin;
diff --git a/vendor/ink/build/hooks/use-stdout.d.ts b/vendor/ink/build/hooks/use-stdout.d.ts
new file mode 100644
index 00000000..40a27ffe
--- /dev/null
+++ b/vendor/ink/build/hooks/use-stdout.d.ts
@@ -0,0 +1,5 @@
+/**
+ * `useStdout` is a React hook, which exposes stdout stream.
+ */
+declare const useStdout: () => import("../components/StdoutContext.js").Props;
+export default useStdout;
diff --git a/vendor/ink/build/hooks/use-stdout.js b/vendor/ink/build/hooks/use-stdout.js
new file mode 100644
index 00000000..a3d677aa
--- /dev/null
+++ b/vendor/ink/build/hooks/use-stdout.js
@@ -0,0 +1,7 @@
+import { useContext } from 'react';
+import StdoutContext from '../components/StdoutContext.js';
+/**
+ * `useStdout` is a React hook, which exposes stdout stream.
+ */
+const useStdout = () => useContext(StdoutContext);
+export default useStdout;
diff --git a/vendor/ink/build/hooks/useInput.js b/vendor/ink/build/hooks/useInput.js
new file mode 100644
index 00000000..3db41a7d
--- /dev/null
+++ b/vendor/ink/build/hooks/useInput.js
@@ -0,0 +1,38 @@
+"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 file
diff --git a/vendor/ink/build/index.d.ts b/vendor/ink/build/index.d.ts
new file mode 100644
index 00000000..198843d8
--- /dev/null
+++ b/vendor/ink/build/index.d.ts
@@ -0,0 +1,27 @@
+export type { RenderOptions, Instance } from './render.js';
+export { default as render } from './render.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 { 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';
+export { default as Static } from './components/Static.js';
+export type { Props as TransformProps } from './components/Transform.js';
+export { default as Transform } from './components/Transform.js';
+export type { Props as NewlineProps } from './components/Newline.js';
+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 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 measureElement } from './measure-element.js';
+export type { DOMElement } from './dom.js';
diff --git a/vendor/ink/build/index.js b/vendor/ink/build/index.js
new file mode 100644
index 00000000..dfc6b821
--- /dev/null
+++ b/vendor/ink/build/index.js
@@ -0,0 +1,15 @@
+export { default as render } from './render.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';
+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 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 measureElement } from './measure-element.js';
diff --git a/vendor/ink/build/ink.d.ts b/vendor/ink/build/ink.d.ts
new file mode 100644
index 00000000..5e7e28bd
--- /dev/null
+++ b/vendor/ink/build/ink.d.ts
@@ -0,0 +1,37 @@
+import { type ReactNode } from 'react';
+export type Options = {
+ stdout: NodeJS.WriteStream;
+ stdin: NodeJS.ReadStream;
+ stderr: NodeJS.WriteStream;
+ debug: boolean;
+ exitOnCtrlC: boolean;
+ patchConsole: boolean;
+ waitUntilExit?: () => Promise<void>;
+};
+export default class Ink {
+ private readonly options;
+ private readonly log;
+ private readonly throttledLog;
+ private isUnmounted;
+ private lastOutput;
+ private readonly container;
+ private readonly rootNode;
+ private fullStaticOutput;
+ private exitPromise?;
+ private restoreConsole?;
+ private readonly unsubscribeResize?;
+ constructor(options: Options);
+ resized: () => void;
+ resolveExitPromise: () => void;
+ rejectExitPromise: (reason?: Error) => void;
+ unsubscribeExit: () => void;
+ calculateLayout: () => void;
+ onRender: () => void;
+ render(node: ReactNode): void;
+ writeToStdout(data: string): void;
+ writeToStderr(data: string): void;
+ unmount(error?: Error | number | null): void;
+ waitUntilExit(): Promise<void>;
+ clear(): void;
+ patchConsole(): void;
+}
diff --git a/vendor/ink/build/ink.js b/vendor/ink/build/ink.js
new file mode 100644
index 00000000..b6adc6d1
--- /dev/null
+++ b/vendor/ink/build/ink.js
@@ -0,0 +1,329 @@
+import process from 'node:process';
+import React from 'react';
+import { throttle } from 'es-toolkit/compat';
+import ansiEscapes from 'ansi-escapes';
+import isInCi from 'is-in-ci';
+import autoBind from 'auto-bind';
+import signalExit from 'signal-exit';
+import patchConsole from 'patch-console';
+import Yoga from 'yoga-layout';
+import reconciler from './reconciler.js';
+import render from './renderer.js';
+import * as dom from './dom.js';
+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'],
+};
+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;
+ throttledLog;
+ // Ignore last render after unmounting a tree to prevent empty output before exit
+ isUnmounted;
+ lastOutput;
+ 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
+ fullStaticOutput;
+ exitPromise;
+ restoreConsole;
+ unsubscribeResize;
+ 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, {
+ leading: true,
+ trailing: true,
+ });
+ this.rootNode.onImmediateRender = this.onRender;
+ this.log = logUpdate.create(options.stdout);
+ this.throttledLog = options.debug
+ ? this.log
+ : throttle(this.log, undefined, {
+ 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 = '';
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+ this.container = reconciler.createContainer(this.rootNode,
+ // Legacy mode
+ 0, null, false, null, 'id', () => { }, null);
+ // Unmount when process exits
+ this.unsubscribeExit = signalExit(this.unmount, { alwaysLast: false });
+ 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',
+ });
+ }
+ if (options.patchConsole) {
+ this.patchConsole();
+ }
+ if (!isInCi) {
+ options.stdout.on('resize', this.resized);
+ this.unsubscribeResize = () => {
+ options.stdout.off('resize', this.resized);
+ };
+ }
+ }
+ 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);
+ // 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 (isInCi) {
+ if (hasStaticOutput) {
+ this.options.stdout.write(staticOutput);
+ }
+ this.lastOutput = output;
+ return;
+ }
+ if (hasStaticOutput) {
+ this.fullStaticOutput += staticOutput;
+ }
+ if (outputHeight >= this.options.stdout.rows) {
+ this.options.stdout.write(ansiEscapes.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);
+ this.log(output, cursor);
+ }
+ 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);
+ }
+ writeToStdout(data) {
+ if (this.isUnmounted) {
+ return;
+ }
+ if (this.options.debug) {
+ this.options.stdout.write(data + this.fullStaticOutput + this.lastOutput);
+ return;
+ }
+ if (isInCi) {
+ this.options.stdout.write(data);
+ return;
+ }
+ this.log.clear();
+ this.options.stdout.write(data);
+ this.log(this.lastOutput, this.lastCursor);
+ }
+ writeToStderr(data) {
+ if (this.isUnmounted) {
+ return;
+ }
+ if (this.options.debug) {
+ this.options.stderr.write(data);
+ this.options.stdout.write(this.fullStaticOutput + this.lastOutput);
+ return;
+ }
+ if (isInCi) {
+ this.options.stderr.write(data);
+ return;
+ }
+ this.log.clear();
+ this.options.stderr.write(data);
+ this.log(this.lastOutput, this.lastCursor);
+ }
+ // eslint-disable-next-line @typescript-eslint/ban-types
+ unmount(error) {
+ if (this.isUnmounted) {
+ return;
+ }
+ this.calculateLayout();
+ this.onRender();
+ this.unsubscribeExit();
+ if (typeof this.restoreConsole === 'function') {
+ 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);
+ }
+ else {
+ this.resolveExitPromise();
+ }
+ }
+ async waitUntilExit() {
+ this.exitPromise ||= new Promise((resolve, reject) => {
+ this.resolveExitPromise = resolve;
+ this.rejectExitPromise = reject;
+ });
+ return this.exitPromise;
+ }
+ clear() {
+ if (!isInCi && !this.options.debug) {
+ this.log.clear();
+ }
+ }
+ patchConsole() {
+ if (this.options.debug) {
+ return;
+ }
+ this.restoreConsole = patchConsole((stream, data) => {
+ if (stream === 'stdout') {
+ this.writeToStdout(data);
+ }
+ if (stream === 'stderr') {
+ const isReactMessage = data.startsWith('The above error occurred');
+ if (!isReactMessage) {
+ this.writeToStderr(data);
+ }
+ }
+ });
+ }
+}
diff --git a/vendor/ink/build/instance.js b/vendor/ink/build/instance.js
new file mode 100644
index 00000000..291c46e8
--- /dev/null
+++ b/vendor/ink/build/instance.js
@@ -0,0 +1,205 @@
+"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 file
diff --git a/vendor/ink/build/instances.d.ts b/vendor/ink/build/instances.d.ts
new file mode 100644
index 00000000..01524258
--- /dev/null
+++ b/vendor/ink/build/instances.d.ts
@@ -0,0 +1,3 @@
+import type Ink from './ink.js';
+declare const instances: WeakMap<NodeJS.WriteStream, Ink>;
+export default instances;
diff --git a/vendor/ink/build/instances.js b/vendor/ink/build/instances.js
new file mode 100644
index 00000000..49544bba
--- /dev/null
+++ b/vendor/ink/build/instances.js
@@ -0,0 +1,7 @@
+// Store all instances of Ink (instance.js) to ensure that consecutive render() calls
+// use the same instance of Ink and don't create a new one
+//
+// This map has to be stored in a separate file, because render.js creates instances,
+// but instance.js should delete itself from the map on unmount
+const instances = new WeakMap();
+export default instances;
diff --git a/vendor/ink/build/log-update.d.ts b/vendor/ink/build/log-update.d.ts
new file mode 100644
index 00000000..ff501a9b
--- /dev/null
+++ b/vendor/ink/build/log-update.d.ts
@@ -0,0 +1,15 @@
+import { type Writable } from 'node:stream';
+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;
+};
+declare const logUpdate: {
+ create: (stream: Writable, { showCursor }?: {
+ showCursor?: boolean | undefined;
+ }) => LogUpdate;
+};
+export default logUpdate;
diff --git a/vendor/ink/build/log-update.js b/vendor/ink/build/log-update.js
new file mode 100644
index 00000000..501a6587
--- /dev/null
+++ b/vendor/ink/build/log-update.js
@@ -0,0 +1,92 @@
+import ansiEscapes from 'ansi-escapes';
+import cliCursor from 'cli-cursor';
+const create = (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)) };
+ };
+ 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) stream.write(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;
+ previousLineCount = output.split('\n').length;
+ stream.write(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.clear = () => {
+ stream.write(unpark() + ansiEscapes.eraseLines(previousLineCount));
+ previousOutput = '';
+ previousLineCount = 0;
+ };
+ render.done = () => {
+ const restore = unpark();
+ if (restore) stream.write(restore);
+ previousOutput = '';
+ previousLineCount = 0;
+ if (!showCursor) {
+ cliCursor.show();
+ hasHiddenCursor = false;
+ }
+ };
+ return render;
+};
+const logUpdate = { create };
+export default logUpdate;
diff --git a/vendor/ink/build/measure-element.d.ts b/vendor/ink/build/measure-element.d.ts
new file mode 100644
index 00000000..f01e0cf6
--- /dev/null
+++ b/vendor/ink/build/measure-element.d.ts
@@ -0,0 +1,16 @@
+import { type DOMElement } from './dom.js';
+type Output = {
+ /**
+ * Element width.
+ */
+ width: number;
+ /**
+ * Element height.
+ */
+ height: number;
+};
+/**
+ * Measure the dimensions of a particular `<Box>` element.
+ */
+declare const measureElement: (node: DOMElement) => Output;
+export default measureElement;
diff --git a/vendor/ink/build/measure-element.js b/vendor/ink/build/measure-element.js
new file mode 100644
index 00000000..429c73ed
--- /dev/null
+++ b/vendor/ink/build/measure-element.js
@@ -0,0 +1,8 @@
+/**
+ * Measure the dimensions of a particular `<Box>` element.
+ */
+const measureElement = (node) => ({
+ width: node.yogaNode?.getComputedWidth() ?? 0,
+ height: node.yogaNode?.getComputedHeight() ?? 0,
+});
+export default measureElement;
diff --git a/vendor/ink/build/measure-text.d.ts b/vendor/ink/build/measure-text.d.ts
new file mode 100644
index 00000000..c0e01433
--- /dev/null
+++ b/vendor/ink/build/measure-text.d.ts
@@ -0,0 +1,6 @@
+type Output = {
+ width: number;
+ height: number;
+};
+declare const measureText: (text: string) => Output;
+export default measureText;
diff --git a/vendor/ink/build/measure-text.js b/vendor/ink/build/measure-text.js
new file mode 100644
index 00000000..2f1fde84
--- /dev/null
+++ b/vendor/ink/build/measure-text.js
@@ -0,0 +1,19 @@
+import widestLine from 'widest-line';
+const cache = {};
+const measureText = (text) => {
+ if (text.length === 0) {
+ return {
+ width: 0,
+ height: 0,
+ };
+ }
+ const cachedDimensions = cache[text];
+ if (cachedDimensions) {
+ return cachedDimensions;
+ }
+ const width = widestLine(text);
+ const height = text.split('\n').length;
+ cache[text] = { width, height };
+ return { width, height };
+};
+export default measureText;
diff --git a/vendor/ink/build/output.d.ts b/vendor/ink/build/output.d.ts
new file mode 100644
index 00000000..30c87bcd
--- /dev/null
+++ b/vendor/ink/build/output.d.ts
@@ -0,0 +1,35 @@
+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)
+ */
+type Options = {
+ width: number;
+ height: number;
+};
+type Clip = {
+ x1: number | undefined;
+ x2: number | undefined;
+ y1: number | undefined;
+ y2: number | undefined;
+};
+export default class Output {
+ width: number;
+ height: number;
+ private readonly operations;
+ constructor(options: Options);
+ write(x: number, y: number, text: string, options: {
+ transformers: OutputTransformer[];
+ }): void;
+ clip(clip: Clip): void;
+ unclip(): void;
+ get(): {
+ output: string;
+ height: number;
+ };
+}
+export {};
diff --git a/vendor/ink/build/output.js b/vendor/ink/build/output.js
new file mode 100644
index 00000000..1e18184f
--- /dev/null
+++ b/vendor/ink/build/output.js
@@ -0,0 +1,147 @@
+import sliceAnsi from 'slice-ansi';
+import stringWidth from 'string-width';
+import widestLine from 'widest-line';
+import { styledCharsFromTokens, styledCharsToString, tokenize, } from '@alcalzone/ansi-tokenize';
+export default class Output {
+ width;
+ height;
+ operations = [];
+ constructor(options) {
+ const { width, height } = options;
+ this.width = width;
+ this.height = height;
+ }
+ write(x, y, text, options) {
+ const { transformers } = options;
+ if (!text) {
+ return;
+ }
+ this.operations.push({
+ type: 'write',
+ x,
+ y,
+ text,
+ transformers,
+ });
+ }
+ clip(clip) {
+ this.operations.push({
+ type: 'clip',
+ clip,
+ });
+ }
+ unclip() {
+ this.operations.push({
+ type: 'unclip',
+ });
+ }
+ get() {
+ // Initialize output array with a specific set of rows, so that margin/padding at the bottom is preserved
+ const output = [];
+ for (let y = 0; y < this.height; y++) {
+ const row = [];
+ for (let x = 0; x < this.width; x++) {
+ row.push({
+ type: 'char',
+ value: ' ',
+ fullWidth: false,
+ styles: [],
+ });
+ }
+ output.push(row);
+ }
+ const clips = [];
+ for (const operation of this.operations) {
+ if (operation.type === 'clip') {
+ clips.push(operation.clip);
+ }
+ 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++;
+ }
+ }
+ }
+ const generatedOutput = output
+ .map(line => {
+ // See https://github.com/vadimdemedes/ink/pull/564#issuecomment-1637022742
+ const lineWithoutEmptyItems = line.filter(item => item !== undefined);
+ return styledCharsToString(lineWithoutEmptyItems).trimEnd();
+ })
+ .join('\n');
+ return {
+ output: generatedOutput,
+ height: output.length,
+ };
+ }
+}
diff --git a/vendor/ink/build/parse-keypress.d.ts b/vendor/ink/build/parse-keypress.d.ts
new file mode 100644
index 00000000..1dc1e48f
--- /dev/null
+++ b/vendor/ink/build/parse-keypress.d.ts
@@ -0,0 +1,14 @@
+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;
+};
+declare const parseKeypress: (s?: Buffer | string) => ParsedKey;
+export default parseKeypress;
diff --git a/vendor/ink/build/parse-keypress.js b/vendor/ink/build/parse-keypress.js
new file mode 100644
index 00000000..247d2842
--- /dev/null
+++ b/vendor/ink/build/parse-keypress.js
@@ -0,0 +1,224 @@
+// Copied from https://github.com/enquirer/enquirer/blob/36785f3399a41cd61e9d28d1eb9c2fcd73d69b4c/lib/keypress.js
+import { Buffer } from 'node:buffer';
+const metaKeyCodeRe = /^(?:\x1b)([a-zA-Z0-9])$/;
+const fnKeyRe = /^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/;
+const keyName = {
+ /* xterm/gnome ESC O letter */
+ OP: 'f1',
+ OQ: 'f2',
+ OR: 'f3',
+ OS: 'f4',
+ /* xterm/rxvt ESC [ number ~ */
+ '[11~': 'f1',
+ '[12~': 'f2',
+ '[13~': 'f3',
+ '[14~': 'f4',
+ /* from Cygwin and used in libuv */
+ '[[A': 'f1',
+ '[[B': 'f2',
+ '[[C': 'f3',
+ '[[D': 'f4',
+ '[[E': 'f5',
+ /* common */
+ '[15~': 'f5',
+ '[17~': 'f6',
+ '[18~': 'f7',
+ '[19~': 'f8',
+ '[20~': 'f9',
+ '[21~': 'f10',
+ '[23~': 'f11',
+ '[24~': 'f12',
+ /* xterm ESC [ letter */
+ '[A': 'up',
+ '[B': 'down',
+ '[C': 'right',
+ '[D': 'left',
+ '[E': 'clear',
+ '[F': 'end',
+ '[H': 'home',
+ /* xterm/gnome ESC O letter */
+ OA: 'up',
+ OB: 'down',
+ OC: 'right',
+ OD: 'left',
+ OE: 'clear',
+ OF: 'end',
+ OH: 'home',
+ /* xterm/rxvt ESC [ number ~ */
+ '[1~': 'home',
+ '[2~': 'insert',
+ '[3~': 'delete',
+ '[4~': 'end',
+ '[5~': 'pageup',
+ '[6~': 'pagedown',
+ /* putty */
+ '[[5~': 'pageup',
+ '[[6~': 'pagedown',
+ /* rxvt */
+ '[7~': 'home',
+ '[8~': 'end',
+ /* rxvt keys with modifiers */
+ '[a': 'up',
+ '[b': 'down',
+ '[c': 'right',
+ '[d': 'left',
+ '[e': 'clear',
+ '[2$': 'insert',
+ '[3$': 'delete',
+ '[5$': 'pageup',
+ '[6$': 'pagedown',
+ '[7$': 'home',
+ '[8$': 'end',
+ Oa: 'up',
+ Ob: 'down',
+ Oc: 'right',
+ Od: 'left',
+ Oe: 'clear',
+ '[2^': 'insert',
+ '[3^': 'delete',
+ '[5^': 'pageup',
+ '[6^': 'pagedown',
+ '[7^': 'home',
+ '[8^': 'end',
+ /* misc. */
+ '[Z': 'tab',
+};
+export const nonAlphanumericKeys = [...Object.values(keyName), 'backspace'];
+const isShiftKey = (code) => {
+ return [
+ '[a',
+ '[b',
+ '[c',
+ '[d',
+ '[e',
+ '[2$',
+ '[3$',
+ '[5$',
+ '[6$',
+ '[7$',
+ '[8$',
+ '[Z',
+ ].includes(code);
+};
+const isCtrlKey = (code) => {
+ return [
+ 'Oa',
+ 'Ob',
+ 'Oc',
+ 'Od',
+ 'Oe',
+ '[2^',
+ '[3^',
+ '[5^',
+ '[6^',
+ '[7^',
+ '[8^',
+ ].includes(code);
+};
+const parseKeypress = (s = '') => {
+ let parts;
+ if (Buffer.isBuffer(s)) {
+ if (s[0] > 127 && s[1] === undefined) {
+ s[0] -= 128;
+ s = '\x1b' + String(s);
+ }
+ else {
+ s = String(s);
+ }
+ }
+ else if (s !== undefined && typeof s !== 'string') {
+ s = String(s);
+ }
+ else if (!s) {
+ s = '';
+ }
+ 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
+ key.raw = undefined;
+ key.name = 'return';
+ }
+ else if (s === '\n') {
+ // enter, should have been called linefeed
+ key.name = 'enter';
+ }
+ else if (s === '\t') {
+ // tab
+ key.name = 'tab';
+ }
+ else if (s === '\b' || s === '\x1b\b') {
+ // backspace or ctrl+h
+ key.name = 'backspace';
+ 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';
+ key.meta = s.charAt(0) === '\x1b';
+ }
+ else if (s === '\x1b' || s === '\x1b\x1b') {
+ // escape key
+ key.name = 'escape';
+ key.meta = s.length === 2;
+ }
+ else if (s === ' ' || s === '\x1b ') {
+ key.name = 'space';
+ 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);
+ key.ctrl = true;
+ }
+ else if (s.length === 1 && s >= '0' && s <= '9') {
+ // number
+ key.name = 'number';
+ }
+ else if (s.length === 1 && s >= 'a' && s <= 'z') {
+ // lowercase letter
+ key.name = s;
+ }
+ else if (s.length === 1 && s >= 'A' && s <= 'Z') {
+ // shift+letter
+ key.name = s.toLowerCase();
+ key.shift = true;
+ }
+ else if ((parts = metaKeyCodeRe.exec(s))) {
+ // meta+character key
+ 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;
+ }
+ // ansi escape sequence
+ // reassemble the key code leaving out leading \x1b's,
+ // the modifier key bitflag and any meaningless "1;" sequence
+ const code = [parts[1], parts[2], parts[4], parts[6]]
+ .filter(Boolean)
+ .join('');
+ const modifier = (parts[3] || parts[5] || 1) - 1;
+ // Parse the key modifier
+ key.ctrl = !!(modifier & 4);
+ key.meta = !!(modifier & 10);
+ key.shift = !!(modifier & 1);
+ key.code = code;
+ key.name = keyName[code];
+ key.shift = isShiftKey(code) || key.shift;
+ key.ctrl = isCtrlKey(code) || key.ctrl;
+ }
+ return key;
+};
+export default parseKeypress;
diff --git a/vendor/ink/build/reconciler.d.ts b/vendor/ink/build/reconciler.d.ts
new file mode 100644
index 00000000..7f1956d0
--- /dev/null
+++ b/vendor/ink/build/reconciler.d.ts
@@ -0,0 +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>;
+export default _default;
diff --git a/vendor/ink/build/reconciler.js b/vendor/ink/build/reconciler.js
new file mode 100644
index 00000000..59302327
--- /dev/null
+++ b/vendor/ink/build/reconciler.js
@@ -0,0 +1,253 @@
+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 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
+if (process.env['DEV'] === 'true') {
+ try {
+ await import('./devtools.js');
+ }
+ 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;
+ }
+ }
+}
+const diff = (before, after) => {
+ if (before === after) {
+ return;
+ }
+ if (!before) {
+ return after;
+ }
+ const changed = {};
+ let isChanged = false;
+ for (const key of Object.keys(before)) {
+ const isDeleted = after ? !Object.hasOwn(after, key) : true;
+ if (isDeleted) {
+ changed[key] = undefined;
+ isChanged = true;
+ }
+ }
+ if (after) {
+ for (const key of Object.keys(after)) {
+ if (after[key] !== before[key]) {
+ changed[key] = after[key];
+ isChanged = true;
+ }
+ }
+ }
+ return isChanged ? changed : undefined;
+};
+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,
+ }),
+ prepareForCommit: () => null,
+ preparePortalMount: () => null,
+ clearContainer: () => false,
+ resetAfterCommit(rootNode) {
+ if (typeof rootNode.onComputeLayout === 'function') {
+ rootNode.onComputeLayout();
+ }
+ // 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;
+ if (typeof rootNode.onImmediateRender === 'function') {
+ rootNode.onImmediateRender();
+ }
+ return;
+ }
+ if (typeof rootNode.onRender === 'function') {
+ rootNode.onRender();
+ }
+ },
+ getChildHostContext(parentHostContext, type) {
+ const previousIsInsideText = parentHostContext.isInsideText;
+ const isInsideText = type === 'ink-text' || type === 'ink-virtual-text';
+ if (previousIsInsideText === isInsideText) {
+ return parentHostContext;
+ }
+ return { 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`);
+ }
+ const type = originalType === 'ink-text' && hostContext.isInsideText
+ ? 'ink-virtual-text'
+ : originalType;
+ const node = createNode(type);
+ for (const [key, value] of Object.entries(newProps)) {
+ if (key === 'children') {
+ continue;
+ }
+ if (key === 'style') {
+ setStyle(node, value);
+ if (node.yogaNode) {
+ applyStyles(node.yogaNode, value);
+ }
+ continue;
+ }
+ if (key === 'internal_transform') {
+ node.internal_transform = value;
+ continue;
+ }
+ if (key === 'internal_static') {
+ node.internal_static = true;
+ continue;
+ }
+ setAttribute(node, key, value);
+ }
+ return node;
+ },
+ createTextInstance(text, _root, hostContext) {
+ if (!hostContext.isInsideText) {
+ throw new Error(`Text string "${text}" must be rendered inside <Text> component`);
+ }
+ return createTextNode(text);
+ },
+ resetTextContent() { },
+ hideTextInstance(node) {
+ setTextNodeValue(node, '');
+ },
+ unhideTextInstance(node, text) {
+ setTextNodeValue(node, text);
+ },
+ getPublicInstance: instance => instance,
+ hideInstance(node) {
+ node.yogaNode?.setDisplay(Yoga.DISPLAY_NONE);
+ },
+ unhideInstance(node) {
+ node.yogaNode?.setDisplay(Yoga.DISPLAY_FLEX);
+ },
+ 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;
+ }
+ return false;
+ },
+ isPrimaryRenderer: true,
+ supportsMutation: true,
+ supportsPersistence: false,
+ supportsHydration: false,
+ scheduleTimeout: setTimeout,
+ cancelTimeout: clearTimeout,
+ noTimeout: -1,
+ getCurrentEventPriority: () => DefaultEventPriority,
+ beforeActiveInstanceBlur() { },
+ afterActiveInstanceBlur() { },
+ detachDeletedInstance() { },
+ getInstanceFromNode: () => null,
+ prepareScopeUpdate() { },
+ getInstanceFromScope: () => null,
+ appendChildToContainer: appendChildNode,
+ insertInContainerBefore: insertBeforeNode,
+ removeChildFromContainer(node, removeNode) {
+ removeChildNode(node, removeNode);
+ cleanupRemovedNode(node, removeNode);
+ },
+ prepareUpdate(node, _type, oldProps, newProps, rootNode) {
+ if (node.internal_static) {
+ rootNode.isStaticDirty = true;
+ }
+ const props = diff(oldProps, newProps);
+ const style = diff(oldProps['style'], newProps['style']);
+ if (!props && !style) {
+ return null;
+ }
+ return { props, style };
+ },
+ commitUpdate(node, { props, style }) {
+ if (props) {
+ for (const [key, value] of Object.entries(props)) {
+ if (key === 'style') {
+ setStyle(node, value);
+ continue;
+ }
+ if (key === 'internal_transform') {
+ node.internal_transform = value;
+ continue;
+ }
+ if (key === 'internal_static') {
+ node.internal_static = true;
+ continue;
+ }
+ setAttribute(node, key, value);
+ }
+ }
+ if (style && node.yogaNode) {
+ applyStyles(node.yogaNode, style);
+ }
+ },
+ commitTextUpdate(node, _oldText, newText) {
+ setTextNodeValue(node, newText);
+ },
+ removeChild(node, removeNode) {
+ removeChildNode(node, removeNode);
+ cleanupRemovedNode(node, removeNode);
+ },
+});
diff --git a/vendor/ink/build/render-border.d.ts b/vendor/ink/build/render-border.d.ts
new file mode 100644
index 00000000..bffd70c3
--- /dev/null
+++ b/vendor/ink/build/render-border.d.ts
@@ -0,0 +1,4 @@
+import { type DOMNode } from './dom.js';
+import type Output from './output.js';
+declare const renderBorder: (x: number, y: number, node: DOMNode, output: Output) => void;
+export default renderBorder;
diff --git a/vendor/ink/build/render-border.js b/vendor/ink/build/render-border.js
new file mode 100644
index 00000000..18970e21
--- /dev/null
+++ b/vendor/ink/build/render-border.js
@@ -0,0 +1,72 @@
+import cliBoxes from 'cli-boxes';
+import chalk from 'chalk';
+import colorize from './colorize.js';
+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: [] });
+ }
+ }
+};
+export default renderBorder;
diff --git a/vendor/ink/build/render-node-to-output.d.ts b/vendor/ink/build/render-node-to-output.d.ts
new file mode 100644
index 00000000..7dd9eaa7
--- /dev/null
+++ b/vendor/ink/build/render-node-to-output.d.ts
@@ -0,0 +1,10 @@
+import { type DOMElement } from './dom.js';
+import type Output from './output.js';
+export type OutputTransformer = (s: string, index: number) => string;
+declare const renderNodeToOutput: (node: DOMElement, output: Output, options: {
+ offsetX?: number;
+ offsetY?: number;
+ transformers?: OutputTransformer[];
+ skipStaticElements: boolean;
+}) => void;
+export default renderNodeToOutput;
diff --git a/vendor/ink/build/render-node-to-output.js b/vendor/ink/build/render-node-to-output.js
new file mode 100644
index 00000000..46dad67f
--- /dev/null
+++ b/vendor/ink/build/render-node-to-output.js
@@ -0,0 +1,98 @@
+import widestLine from 'widest-line';
+import indentString from 'indent-string';
+import Yoga from 'yoga-layout';
+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';
+// 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
+// and use it as offset for the rest of the nodes
+// 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 anyway
+const applyPaddingToText = (node, text) => {
+ const yogaNode = node.childNodes[0]?.yogaNode;
+ if (yogaNode) {
+ const offsetX = yogaNode.getComputedLeft();
+ const offsetY = yogaNode.getComputedTop();
+ text = '\n'.repeat(offsetY) + indentString(text, offsetX);
+ }
+ return text;
+};
+// After nodes are laid out, render each to output object, which later gets rendered to terminal
+const renderNodeToOutput = (node, output, options) => {
+ const { offsetX = 0, offsetY = 0, transformers = [], skipStaticElements, } = options;
+ if (skipStaticElements && node.internal_static) {
+ 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 (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();
+ }
+ }
+ }
+};
+export default renderNodeToOutput;
diff --git a/vendor/ink/build/render.d.ts b/vendor/ink/build/render.d.ts
new file mode 100644
index 00000000..b84a89b8
--- /dev/null
+++ b/vendor/ink/build/render.d.ts
@@ -0,0 +1,63 @@
+import type { ReactNode } from 'react';
+import Ink from './ink.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
+ */
+ 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
+ */
+ exitOnCtrlC?: boolean;
+ /**
+ * Patch console methods to ensure console output doesn't mix with Ink output.
+ *
+ * @default true
+ */
+ patchConsole?: boolean;
+};
+export type Instance = {
+ /**
+ * Replace previous root node with a new one or update props of the current root node.
+ */
+ rerender: Ink['render'];
+ /**
+ * Manually unmount the whole Ink app.
+ */
+ unmount: Ink['unmount'];
+ /**
+ * Returns a promise, which resolves when app is unmounted.
+ */
+ waitUntilExit: Ink['waitUntilExit'];
+ cleanup: () => void;
+ /**
+ * Clear output.
+ */
+ clear: () => void;
+};
+/**
+ * Mount a component and render the output.
+ */
+declare const render: (node: ReactNode, options?: NodeJS.WriteStream | RenderOptions) => Instance;
+export default render;
diff --git a/vendor/ink/build/render.js b/vendor/ink/build/render.js
new file mode 100644
index 00000000..1e7e68ee
--- /dev/null
+++ b/vendor/ink/build/render.js
@@ -0,0 +1,47 @@
+import { Stream } from 'node:stream';
+import process from 'node:process';
+import Ink from './ink.js';
+import instances from './instances.js';
+/**
+ * Mount a component and render the output.
+ */
+const render = (node, options) => {
+ const inkOptions = {
+ stdout: process.stdout,
+ stdin: process.stdin,
+ stderr: process.stderr,
+ debug: false,
+ exitOnCtrlC: true,
+ patchConsole: true,
+ ...getOptions(options),
+ };
+ const instance = getInstance(inkOptions.stdout, () => new Ink(inkOptions));
+ instance.render(node);
+ return {
+ rerender: instance.render,
+ unmount() {
+ instance.unmount();
+ },
+ waitUntilExit: instance.waitUntilExit,
+ cleanup: () => instances.delete(inkOptions.stdout),
+ clear: instance.clear,
+ };
+};
+export default render;
+const getOptions = (stdout = {}) => {
+ if (stdout instanceof Stream) {
+ return {
+ stdout,
+ stdin: process.stdin,
+ };
+ }
+ return stdout;
+};
+const getInstance = (stdout, createInstance) => {
+ let instance = instances.get(stdout);
+ if (!instance) {
+ instance = createInstance();
+ instances.set(stdout, instance);
+ }
+ return instance;
+};
diff --git a/vendor/ink/build/renderer.d.ts b/vendor/ink/build/renderer.d.ts
new file mode 100644
index 00000000..5e149100
--- /dev/null
+++ b/vendor/ink/build/renderer.d.ts
@@ -0,0 +1,8 @@
+import { type DOMElement } from './dom.js';
+type Result = {
+ output: string;
+ outputHeight: number;
+ staticOutput: string;
+};
+declare const renderer: (node: DOMElement) => Result;
+export default renderer;
diff --git a/vendor/ink/build/renderer.js b/vendor/ink/build/renderer.js
new file mode 100644
index 00000000..07032d09
--- /dev/null
+++ b/vendor/ink/build/renderer.js
@@ -0,0 +1,35 @@
+import renderNodeToOutput from './render-node-to-output.js';
+import Output from './output.js';
+const renderer = (node) => {
+ if (node.yogaNode) {
+ const output = new Output({
+ width: node.yogaNode.getComputedWidth(),
+ height: node.yogaNode.getComputedHeight(),
+ });
+ renderNodeToOutput(node, output, { skipStaticElements: true });
+ let staticOutput;
+ if (node.staticNode?.yogaNode) {
+ staticOutput = new Output({
+ width: node.staticNode.yogaNode.getComputedWidth(),
+ height: node.staticNode.yogaNode.getComputedHeight(),
+ });
+ renderNodeToOutput(node.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` : '',
+ };
+ }
+ return {
+ output: '',
+ outputHeight: 0,
+ staticOutput: '',
+ };
+};
+export default renderer;
diff --git a/vendor/ink/build/squash-text-nodes.d.ts b/vendor/ink/build/squash-text-nodes.d.ts
new file mode 100644
index 00000000..4781e720
--- /dev/null
+++ b/vendor/ink/build/squash-text-nodes.d.ts
@@ -0,0 +1,3 @@
+import { type DOMElement } from './dom.js';
+declare const squashTextNodes: (node: DOMElement) => string;
+export default squashTextNodes;
diff --git a/vendor/ink/build/squash-text-nodes.js b/vendor/ink/build/squash-text-nodes.js
new file mode 100644
index 00000000..1bc1a9c2
--- /dev/null
+++ b/vendor/ink/build/squash-text-nodes.js
@@ -0,0 +1,34 @@
+// 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`.
+//
+// Also, this is necessary for libraries like ink-link (https://github.com/sindresorhus/ink-link),
+// 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;
+ }
+ let nodeText = '';
+ if (childNode.nodeName === '#text') {
+ nodeText = childNode.nodeValue;
+ }
+ else {
+ if (childNode.nodeName === 'ink-text' ||
+ childNode.nodeName === 'ink-virtual-text') {
+ nodeText = squashTextNodes(childNode);
+ }
+ // Since these text nodes are being concatenated, `Output` instance won't be able to
+ // apply children transform, so we have to do it manually here for each text node
+ if (nodeText.length > 0 &&
+ typeof childNode.internal_transform === 'function') {
+ nodeText = childNode.internal_transform(nodeText, index);
+ }
+ }
+ text += nodeText;
+ }
+ return text;
+};
+export default squashTextNodes;
diff --git a/vendor/ink/build/styles.d.ts b/vendor/ink/build/styles.d.ts
new file mode 100644
index 00000000..e4e04eac
--- /dev/null
+++ b/vendor/ink/build/styles.d.ts
@@ -0,0 +1,243 @@
+import { type Boxes, type BoxStyle } from 'cli-boxes';
+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';
+ /**
+ * Size of the gap between an element's columns.
+ */
+ readonly columnGap?: number;
+ /**
+ * Size of the gap between element's rows.
+ */
+ readonly rowGap?: number;
+ /**
+ * Size of the gap between an element's columns and rows. Shorthand for `columnGap` and `rowGap`.
+ */
+ readonly gap?: number;
+ /**
+ * Margin on all sides. Equivalent to setting `marginTop`, `marginBottom`, `marginLeft` and `marginRight`.
+ */
+ readonly margin?: number;
+ /**
+ * Horizontal margin. Equivalent to setting `marginLeft` and `marginRight`.
+ */
+ readonly marginX?: number;
+ /**
+ * Vertical margin. Equivalent to setting `marginTop` and `marginBottom`.
+ */
+ readonly marginY?: number;
+ /**
+ * Top margin.
+ */
+ readonly marginTop?: number;
+ /**
+ * Bottom margin.
+ */
+ readonly marginBottom?: number;
+ /**
+ * Left margin.
+ */
+ readonly marginLeft?: number;
+ /**
+ * Right margin.
+ */
+ readonly marginRight?: number;
+ /**
+ * Padding on all sides. Equivalent to setting `paddingTop`, `paddingBottom`, `paddingLeft` and `paddingRight`.
+ */
+ readonly padding?: number;
+ /**
+ * Horizontal padding. Equivalent to setting `paddingLeft` and `paddingRight`.
+ */
+ readonly paddingX?: number;
+ /**
+ * Vertical padding. Equivalent to setting `paddingTop` and `paddingBottom`.
+ */
+ readonly paddingY?: number;
+ /**
+ * Top padding.
+ */
+ readonly paddingTop?: number;
+ /**
+ * Bottom padding.
+ */
+ readonly paddingBottom?: number;
+ /**
+ * Left padding.
+ */
+ readonly paddingLeft?: number;
+ /**
+ * 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/).
+ */
+ 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/).
+ */
+ 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/).
+ */
+ 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/).
+ */
+ 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/).
+ */
+ 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';
+ /**
+ * 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 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.
+ */
+ 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.
+ */
+ readonly height?: number | string;
+ /**
+ * Sets a minimum width of the element.
+ */
+ readonly minWidth?: number | string;
+ /**
+ * Sets a minimum height of the element.
+ */
+ readonly minHeight?: number | string;
+ /**
+ * 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.
+ */
+ readonly borderStyle?: keyof Boxes | BoxStyle;
+ /**
+ * Determines whether top border is visible.
+ *
+ * @default true
+ */
+ readonly borderTop?: boolean;
+ /**
+ * Determines whether bottom border is visible.
+ *
+ * @default true
+ */
+ readonly borderBottom?: boolean;
+ /**
+ * Determines whether left border is visible.
+ *
+ * @default true
+ */
+ readonly borderLeft?: boolean;
+ /**
+ * Determines whether right border is visible.
+ *
+ * @default true
+ */
+ readonly borderRight?: boolean;
+ /**
+ * Change border color.
+ * 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.
+ */
+ readonly borderTopColor?: LiteralUnion<ForegroundColorName, string>;
+ /**
+ * Change 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.
+ */
+ readonly borderLeftColor?: LiteralUnion<ForegroundColorName, string>;
+ /**
+ * Change 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
+ */
+ readonly borderDimColor?: boolean;
+ /**
+ * Dim the top border color.
+ *
+ * @default false
+ */
+ readonly borderTopDimColor?: boolean;
+ /**
+ * Dim the bottom border color.
+ *
+ * @default false
+ */
+ readonly borderBottomDimColor?: boolean;
+ /**
+ * Dim the left border color.
+ *
+ * @default false
+ */
+ readonly borderLeftDimColor?: boolean;
+ /**
+ * Dim the right border color.
+ *
+ * @default false
+ */
+ readonly borderRightDimColor?: boolean;
+ /**
+ * 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'
+ */
+ readonly overflowX?: 'visible' | 'hidden';
+ /**
+ * Behavior for an element's overflow in vertical direction.
+ *
+ * @default 'visible'
+ */
+ readonly overflowY?: 'visible' | 'hidden';
+};
+declare const styles: (node: YogaNode, style?: Styles) => void;
+export default styles;
diff --git a/vendor/ink/build/styles.js b/vendor/ink/build/styles.js
new file mode 100644
index 00000000..af34bdca
--- /dev/null
+++ b/vendor/ink/build/styles.js
@@ -0,0 +1,231 @@
+import Yoga from 'yoga-layout';
+const applyPositionStyles = (node, style) => {
+ if ('position' in style) {
+ node.setPositionType(style.position === 'absolute'
+ ? Yoga.POSITION_TYPE_ABSOLUTE
+ : Yoga.POSITION_TYPE_RELATIVE);
+ }
+};
+const applyMarginStyles = (node, style) => {
+ if ('margin' in style) {
+ node.setMargin(Yoga.EDGE_ALL, style.margin ?? 0);
+ }
+ if ('marginX' in style) {
+ node.setMargin(Yoga.EDGE_HORIZONTAL, style.marginX ?? 0);
+ }
+ if ('marginY' in style) {
+ node.setMargin(Yoga.EDGE_VERTICAL, style.marginY ?? 0);
+ }
+ if ('marginLeft' in style) {
+ node.setMargin(Yoga.EDGE_START, style.marginLeft || 0);
+ }
+ if ('marginRight' in style) {
+ node.setMargin(Yoga.EDGE_END, style.marginRight || 0);
+ }
+ if ('marginTop' in style) {
+ node.setMargin(Yoga.EDGE_TOP, style.marginTop || 0);
+ }
+ if ('marginBottom' in style) {
+ node.setMargin(Yoga.EDGE_BOTTOM, style.marginBottom || 0);
+ }
+};
+const applyPaddingStyles = (node, style) => {
+ if ('padding' in style) {
+ node.setPadding(Yoga.EDGE_ALL, style.padding ?? 0);
+ }
+ if ('paddingX' in style) {
+ node.setPadding(Yoga.EDGE_HORIZONTAL, style.paddingX ?? 0);
+ }
+ if ('paddingY' in style) {
+ node.setPadding(Yoga.EDGE_VERTICAL, style.paddingY ?? 0);
+ }
+ if ('paddingLeft' in style) {
+ node.setPadding(Yoga.EDGE_LEFT, style.paddingLeft || 0);
+ }
+ if ('paddingRight' in style) {
+ node.setPadding(Yoga.EDGE_RIGHT, style.paddingRight || 0);
+ }
+ if ('paddingTop' in style) {
+ node.setPadding(Yoga.EDGE_TOP, style.paddingTop || 0);
+ }
+ if ('paddingBottom' in style) {
+ node.setPadding(Yoga.EDGE_BOTTOM, style.paddingBottom || 0);
+ }
+};
+const applyFlexStyles = (node, style) => {
+ if ('flexGrow' in style) {
+ node.setFlexGrow(style.flexGrow ?? 0);
+ }
+ if ('flexShrink' in 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);
+ }
+ }
+ 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);
+ }
+ }
+ if ('flexBasis' in style) {
+ if (typeof style.flexBasis === 'number') {
+ node.setFlexBasis(style.flexBasis);
+ }
+ else if (typeof style.flexBasis === 'string') {
+ node.setFlexBasisPercent(Number.parseInt(style.flexBasis, 10));
+ }
+ else {
+ // This should be replaced with node.setFlexBasisAuto() when new Yoga release is out
+ node.setFlexBasis(Number.NaN);
+ }
+ }
+ 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);
+ }
+ }
+ 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 applyDimensionStyles = (node, style) => {
+ if ('width' in style) {
+ if (typeof style.width === 'number') {
+ node.setWidth(style.width);
+ }
+ else if (typeof style.width === 'string') {
+ node.setWidthPercent(Number.parseInt(style.width, 10));
+ }
+ else {
+ node.setWidthAuto();
+ }
+ }
+ if ('height' in style) {
+ if (typeof style.height === 'number') {
+ node.setHeight(style.height);
+ }
+ else if (typeof style.height === 'string') {
+ node.setHeightPercent(Number.parseInt(style.height, 10));
+ }
+ 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);
+ }
+ }
+ if ('minHeight' in style) {
+ if (typeof style.minHeight === 'string') {
+ node.setMinHeightPercent(Number.parseInt(style.minHeight, 10));
+ }
+ else {
+ node.setMinHeight(style.minHeight ?? 0);
+ }
+ }
+};
+const applyDisplayStyles = (node, style) => {
+ if ('display' in style) {
+ node.setDisplay(style.display === 'flex' ? Yoga.DISPLAY_FLEX : Yoga.DISPLAY_NONE);
+ }
+};
+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 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);
+ }
+ if ('rowGap' in style) {
+ node.setGap(Yoga.GUTTER_ROW, style.rowGap ?? 0);
+ }
+};
+const styles = (node, style = {}) => {
+ applyPositionStyles(node, style);
+ applyMarginStyles(node, style);
+ applyPaddingStyles(node, style);
+ applyFlexStyles(node, style);
+ applyDimensionStyles(node, style);
+ applyDisplayStyles(node, style);
+ applyBorderStyles(node, style);
+ applyGapStyles(node, style);
+};
+export default styles;
diff --git a/vendor/ink/build/wrap-text.d.ts b/vendor/ink/build/wrap-text.d.ts
new file mode 100644
index 00000000..935cfb8d
--- /dev/null
+++ b/vendor/ink/build/wrap-text.d.ts
@@ -0,0 +1,3 @@
+import { type Styles } from './styles.js';
+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.js
new file mode 100644
index 00000000..1792bb39
--- /dev/null
+++ b/vendor/ink/build/wrap-text.js
@@ -0,0 +1,30 @@
+import wrapAnsi from 'wrap-ansi';
+import cliTruncate from 'cli-truncate';
+const cache = {};
+const wrapText = (text, maxWidth, wrapType) => {
+ const cacheKey = text + String(maxWidth) + String(wrapType);
+ const cachedText = cache[cacheKey];
+ if (cachedText) {
+ return cachedText;
+ }
+ let wrappedText = text;
+ if (wrapType === 'wrap') {
+ wrappedText = wrapAnsi(text, maxWidth, {
+ trim: false,
+ hard: true,
+ });
+ }
+ if (wrapType.startsWith('truncate')) {
+ let position = 'end';
+ if (wrapType === 'truncate-middle') {
+ position = 'middle';
+ }
+ if (wrapType === 'truncate-start') {
+ position = 'start';
+ }
+ wrappedText = cliTruncate(text, maxWidth, { position });
+ }
+ cache[cacheKey] = wrappedText;
+ return wrappedText;
+};
+export default wrapText;
diff --git a/vendor/ink/license b/vendor/ink/license
new file mode 100644
index 00000000..5afed125
--- /dev/null
+++ b/vendor/ink/license
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright (c) Vadym Demedes <[email protected]> (github.com/vadimdemedes)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/vendor/ink/package.json b/vendor/ink/package.json
new file mode 100644
index 00000000..312e6c9a
--- /dev/null
+++ b/vendor/ink/package.json
@@ -0,0 +1,80 @@
+{
+ "name": "ink",
+ "version": "5.2.1",
+ "description": "React for CLI",
+ "license": "MIT",
+ "repository": "vadimdemedes/ink",
+ "author": {
+ "name": "Vadim Demedes",
+ "email": "[email protected]",
+ "url": "https://github.com/vadimdemedes"
+ },
+ "type": "module",
+ "exports": {
+ "types": "./build/index.d.ts",
+ "default": "./build/index.js"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "keywords": [
+ "react",
+ "cli",
+ "jsx",
+ "stdout",
+ "components",
+ "command-line",
+ "preact",
+ "redux",
+ "print",
+ "render",
+ "colors",
+ "text"
+ ],
+ "dependencies": {
+ "@alcalzone/ansi-tokenize": "^0.1.3",
+ "ansi-escapes": "^7.0.0",
+ "ansi-styles": "^6.2.1",
+ "auto-bind": "^5.0.1",
+ "chalk": "^5.3.0",
+ "cli-boxes": "^3.0.0",
+ "cli-cursor": "^4.0.0",
+ "cli-truncate": "^4.0.0",
+ "code-excerpt": "^4.0.0",
+ "es-toolkit": "^1.22.0",
+ "indent-string": "^5.0.0",
+ "is-in-ci": "^1.0.0",
+ "patch-console": "^2.0.0",
+ "react-reconciler": "^0.29.0",
+ "scheduler": "^0.23.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",
+ "yoga-layout": "~3.2.1"
+ },
+ "peerDependencies": {
+ "@types/react": ">=18.0.0",
+ "react": ">=18.0.0",
+ "react-devtools-core": "^4.19.1"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "react-devtools-core": {
+ "optional": true
+ }
+ },
+ "_mercury": {
+ "source": "[email protected]",
+ "integrity": "sha512-BqcUyWrG9zq5HIwW6JcfFHsIYebJkWWb4fczNah1goUO0vv5vneIlfwuS85twyJ5hYR/y18FlAYUxrO9ChIWVg==",
+ "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/vitest.config.ts b/vitest.config.ts
new file mode 100644
index 00000000..aa77fa0b
--- /dev/null
+++ b/vitest.config.ts
@@ -0,0 +1,12 @@
+import { defineConfig } from 'vitest/config';
+import { fileURLToPath } from 'node:url';
+
+// ADR-017: tests run against the same vendored, patched ink the bundle
+// ships (vendor/ink), never the stock copy in node_modules.
+export default defineConfig({
+ resolve: {
+ alias: [
+ { find: /^ink$/, replacement: fileURLToPath(new URL('./vendor/ink/build/index.js', import.meta.url)) },
+ ],
+ },
+});