@effected/cli 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/Cancelled.js +44 -0
  2. package/CliAudience.js +178 -0
  3. package/CliColor.js +13 -19
  4. package/CliEnv.js +89 -0
  5. package/CliExit.js +1 -1
  6. package/CliFailure.js +302 -0
  7. package/CliInteractive.js +71 -0
  8. package/CliLinks.js +154 -0
  9. package/CliLog.js +346 -0
  10. package/CliLogger.js +34 -33
  11. package/CliMessage.js +80 -0
  12. package/CliPrompt.js +104 -0
  13. package/CliRuntime.js +110 -54
  14. package/CliTest.js +16 -0
  15. package/CliTheme.js +141 -0
  16. package/ConfigIssueRenderer.js +14 -33
  17. package/Doc.js +536 -0
  18. package/Fmt.js +133 -0
  19. package/GithubAnnotation.js +40 -0
  20. package/Glyphs.js +83 -0
  21. package/NotInteractive.js +42 -0
  22. package/README.md +145 -131
  23. package/Render.js +255 -0
  24. package/SchemaIssueRenderer.js +7 -10
  25. package/Status.js +166 -0
  26. package/TestTerminal.js +80 -0
  27. package/Token.js +69 -0
  28. package/index.d.ts +3089 -169
  29. package/index.js +19 -1
  30. package/internal/ansi.js +230 -0
  31. package/internal/autoFormat.js +34 -0
  32. package/internal/canPrompt.js +15 -0
  33. package/internal/counts.js +84 -0
  34. package/internal/diagnostics.js +32 -0
  35. package/internal/displayWidth.js +35 -0
  36. package/internal/failureTarget.js +195 -0
  37. package/internal/fallbackAnswer.js +18 -0
  38. package/internal/fileSink.js +62 -0
  39. package/internal/format.js +62 -7
  40. package/internal/layout.js +250 -0
  41. package/internal/linkScheme.js +30 -0
  42. package/internal/linkTarget.js +50 -0
  43. package/internal/logSafety.js +46 -0
  44. package/internal/renderAnsi.js +52 -0
  45. package/internal/renderDoc.js +320 -0
  46. package/internal/renderGithubLog.js +46 -0
  47. package/internal/renderMarkdown.js +368 -0
  48. package/internal/renderPlain.js +50 -0
  49. package/internal/scanAudience.js +106 -0
  50. package/internal/splitFrame.js +56 -0
  51. package/internal/wizardGate.js +18 -0
  52. package/package.json +40 -5
  53. package/testing.d.ts +88 -2
  54. package/testing.js +2 -1
  55. package/ui/CliUi.js +432 -0
  56. package/ui/CliUiLive.js +446 -0
  57. package/ui/Confirm.js +245 -0
  58. package/ui/DocView.js +74 -0
  59. package/ui/KeyHelp.js +62 -0
  60. package/ui/KeyTable.js +199 -0
  61. package/ui/MultiSelect.js +260 -0
  62. package/ui/Select.js +230 -0
  63. package/ui/Tabs.js +202 -0
  64. package/ui/TextInput.js +290 -0
  65. package/ui/Toggle.js +32 -0
  66. package/ui/UiKey.js +44 -0
  67. package/ui/UiProvider.js +60 -0
  68. package/ui/UiStreams.js +18 -0
  69. package/ui/UiTheme.js +119 -0
  70. package/ui/Viewport.js +204 -0
  71. package/ui/internal/ErrorBoundary.js +30 -0
  72. package/ui/internal/Holder.js +74 -0
  73. package/ui/internal/ScreenContext.js +52 -0
  74. package/ui/internal/UiProviders.js +21 -0
  75. package/ui/internal/ink.js +122 -0
  76. package/ui/internal/inkChalk.js +58 -0
  77. package/ui/internal/inkConsole.js +146 -0
  78. package/ui/internal/lazyView.js +74 -0
  79. package/ui/internal/lineText.js +19 -0
  80. package/ui/internal/mountPermit.js +16 -0
  81. package/ui/internal/perfDrain.js +33 -0
  82. package/ui/internal/processStreams.js +19 -0
  83. package/ui/internal/renderOptions.js +13 -0
  84. package/ui/testing/CliUiTest.js +760 -0
  85. package/ui/testing/fakeStreams.js +79 -0
  86. package/ui/testing/terminalModel.js +59 -0
  87. package/ui-testing-serializer.d.ts +14 -0
  88. package/ui-testing-serializer.js +33 -0
  89. package/ui-testing.d.ts +527 -0
  90. package/ui-testing.js +3 -0
  91. package/ui.d.ts +1790 -0
  92. package/ui.js +17 -0
package/ui/Viewport.js ADDED
@@ -0,0 +1,204 @@
1
+ import { inkModules } from "./internal/ink.js";
2
+ import { useTerminalSize } from "./UiTheme.js";
3
+ import { KeyTable } from "./KeyTable.js";
4
+
5
+ //#region src/ui/Viewport.ts
6
+ /**
7
+ * Throws on a repeated item key. Checked before React sees the rows: React reports a duplicate key on
8
+ * `console.error`, which under a screen's unpatched console lands on the real stderr, over the frame.
9
+ */
10
+ const assertUniqueItemKeys = (rows) => {
11
+ const seen = /* @__PURE__ */ new Set();
12
+ for (const row of rows) {
13
+ if (row._tag !== "Item") continue;
14
+ if (seen.has(row.key)) throw new Error(`@effected/cli/ui: Viewport item keys must be unique; "${row.key}" repeats`);
15
+ seen.add(row.key);
16
+ }
17
+ };
18
+ const clamp = (value, low, high) => Math.min(Math.max(value, low), high);
19
+ /** The offset that keeps `cursor` in view, moving as little as possible, never past the last full window. */
20
+ const follow = (cursor, offset, height, count) => {
21
+ if (count === 0) return 0;
22
+ let next = offset;
23
+ if (cursor < next) next = cursor;
24
+ if (cursor >= next + height) next = cursor - height + 1;
25
+ return clamp(next, 0, Math.max(0, count - height));
26
+ };
27
+ const init = (count, height, cursor = 0) => {
28
+ const items = Math.max(0, Math.floor(count));
29
+ const window = Math.max(1, Math.floor(height));
30
+ const selected = items === 0 ? 0 : clamp(Math.floor(cursor), 0, items - 1);
31
+ return {
32
+ cursor: selected,
33
+ offset: follow(selected, 0, window, items),
34
+ height: window,
35
+ count: items
36
+ };
37
+ };
38
+ const step = (state, move) => {
39
+ if (state.count === 0) return state;
40
+ const last = state.count - 1;
41
+ const target = move === "up" ? state.cursor - 1 : move === "down" ? state.cursor + 1 : move === "home" ? 0 : move === "end" ? last : move === "pageup" ? state.cursor - state.height : state.cursor + state.height;
42
+ const cursor = clamp(target, 0, last);
43
+ return {
44
+ ...state,
45
+ cursor,
46
+ offset: follow(cursor, state.offset, state.height, state.count)
47
+ };
48
+ };
49
+ const resize = (state, height) => {
50
+ const window = Math.max(1, Math.floor(height));
51
+ return {
52
+ ...state,
53
+ height: window,
54
+ offset: follow(state.cursor, state.offset, window, state.count)
55
+ };
56
+ };
57
+ /**
58
+ * The rows to draw, as indexes into `rows`, for a window of `budget` lines starting at item `start`: the section
59
+ * header of the first item first (re-emitted when it has scrolled off), then rows in order until the budget is spent.
60
+ */
61
+ const linesFrom = (rows, items, start, budget) => {
62
+ const first = items[start] ?? 0;
63
+ const lines = [];
64
+ if (budget > 1) {
65
+ for (let index = first - 1; index >= 0; index--) if (rows[index]?._tag === "Header") {
66
+ lines.push(index);
67
+ break;
68
+ }
69
+ }
70
+ for (let index = first; index < rows.length && lines.length < budget; index++) lines.push(index);
71
+ return lines;
72
+ };
73
+ /**
74
+ * The visible slice, starting where the window last started (`previous`, or the state's offset on first draw) and
75
+ * moving only as far as the selected item needs: back to it when it is above the window, forward until it is drawn
76
+ * when it is below. So moving inside the window moves only the highlight, even when headers take lines the
77
+ * item-counting reducer does not. The cursor is clamped into the items here, for both the slice and the highlight.
78
+ */
79
+ const slice = (rows, state, budget, previous) => {
80
+ const items = rows.flatMap((row, index) => row._tag === "Item" ? [index] : []);
81
+ if (items.length === 0) return {
82
+ lines: rows.slice(0, budget).map((_, index) => index),
83
+ start: 0,
84
+ selected: -1
85
+ };
86
+ const cursor = clamp(state.cursor, 0, items.length - 1);
87
+ const selected = items[cursor] ?? 0;
88
+ let start = clamp(previous ?? state.offset, 0, cursor);
89
+ let lines = linesFrom(rows, items, start, budget);
90
+ while (!lines.includes(selected) && start < cursor) {
91
+ start++;
92
+ lines = linesFrom(rows, items, start, budget);
93
+ }
94
+ while (lines.length < budget && start > 0) {
95
+ const earlier = linesFrom(rows, items, start - 1, budget);
96
+ if (!earlier.includes(selected)) break;
97
+ start--;
98
+ lines = earlier;
99
+ }
100
+ return {
101
+ lines,
102
+ start,
103
+ selected
104
+ };
105
+ };
106
+ /**
107
+ * A scrolling list: a pure reducer over a window of items, its key table, and a view that draws the window.
108
+ *
109
+ * @remarks
110
+ * The view never draws more lines than fit: its height is `min(state.height, terminal rows - 1 - reserved)`, and
111
+ * every row is clipped to one line of `columns - 1` cells, so a frame never fills the terminal and Ink never clears
112
+ * the screen and scrollback to redraw it. A section header stays visible: when the header of the first visible item
113
+ * has scrolled off, it is drawn again atop the slice.
114
+ *
115
+ * @public
116
+ */
117
+ var Viewport = class {
118
+ constructor() {}
119
+ /**
120
+ * A viewport over `count` items, `height` of them in view, with `cursor` selected (clamped; 0 by default).
121
+ *
122
+ * @param count - how many items
123
+ * @param height - how many fit (at least 1)
124
+ * @param cursor - the item to select
125
+ */
126
+ static init = init;
127
+ /**
128
+ * Move the cursor, clamped at both ends with no wrap, keeping it in view. A page is the window height.
129
+ *
130
+ * @param state - where the viewport is
131
+ * @param move - the move
132
+ */
133
+ static step = step;
134
+ /**
135
+ * Change the window height, keeping the cursor where it is and in view.
136
+ *
137
+ * @param state - where the viewport is
138
+ * @param height - the new height (at least 1)
139
+ */
140
+ static resize = resize;
141
+ /** The keys: ↑/↓ move, pgup/pgdn page, home top, end bottom. */
142
+ static keys = KeyTable.make([
143
+ {
144
+ keys: ["up"],
145
+ action: "up",
146
+ help: "move"
147
+ },
148
+ {
149
+ keys: ["down"],
150
+ action: "down",
151
+ help: "move"
152
+ },
153
+ {
154
+ keys: ["pageup"],
155
+ action: "pageup",
156
+ help: "page"
157
+ },
158
+ {
159
+ keys: ["pagedown"],
160
+ action: "pagedown",
161
+ help: "page"
162
+ },
163
+ {
164
+ keys: ["home"],
165
+ action: "home",
166
+ help: "top"
167
+ },
168
+ {
169
+ keys: ["end"],
170
+ action: "end",
171
+ help: "bottom"
172
+ }
173
+ ]);
174
+ /**
175
+ * Draw the window: the visible rows, each clipped to one line. A repeated item key is a defect: the view throws, so
176
+ * the screen dies with the reason.
177
+ *
178
+ * @param props - the rows, the state, how to draw a row, and the lines reserved for the rest of the screen
179
+ */
180
+ static View = (props) => {
181
+ assertUniqueItemKeys(props.rows);
182
+ const { ink, react } = inkModules();
183
+ const size = useTerminalSize();
184
+ const budget = Math.max(1, Math.min(props.state.height, size.rows - (props.reserved ?? 0)));
185
+ const started = react.useRef(void 0);
186
+ const { lines, start, selected } = slice(props.rows, props.state, budget, started.current);
187
+ started.current = start;
188
+ return react.createElement(ink.Box, {
189
+ flexDirection: "column",
190
+ width: size.columns
191
+ }, ...lines.map((index) => {
192
+ const row = props.rows[index];
193
+ return react.createElement(ink.Box, {
194
+ key: row._tag === "Item" ? `item:${row.key}` : `header:${index}`,
195
+ height: 1,
196
+ width: size.columns,
197
+ overflow: "hidden"
198
+ }, props.renderRow(row, index === selected));
199
+ }));
200
+ };
201
+ };
202
+
203
+ //#endregion
204
+ export { Viewport };
@@ -0,0 +1,30 @@
1
+ import { fromReact } from "./ink.js";
2
+
3
+ //#region src/ui/internal/ErrorBoundary.ts
4
+ /**
5
+ * The screen's error boundary: catches a render error anywhere in the screen, renders nothing, and reports it.
6
+ *
7
+ * @remarks
8
+ * It sits inside Ink's own boundary, so Ink's `ErrorOverview` (which Ink writes to stdout) never renders: a probe on
9
+ * fake streams found zero bytes of it with this boundary in place, against an `ERROR` header, a stack and a
10
+ * screen-and-scrollback clear without it. A class over the loaded React, built on first use, because the kit holds
11
+ * no runtime React at module scope.
12
+ *
13
+ * @internal
14
+ */
15
+ const errorBoundary = fromReact((react) => class ScreenErrorBoundary extends react.Component {
16
+ static displayName = "CliUiErrorBoundary";
17
+ static getDerivedStateFromError() {
18
+ return { failed: true };
19
+ }
20
+ state = { failed: false };
21
+ componentDidCatch(error) {
22
+ this.props.onError(error);
23
+ }
24
+ render() {
25
+ return this.state.failed ? this.props.fallback?.() ?? null : this.props.children ?? null;
26
+ }
27
+ });
28
+
29
+ //#endregion
30
+ export { errorBoundary };
@@ -0,0 +1,74 @@
1
+ import { fromReact } from "./ink.js";
2
+
3
+ //#region src/ui/internal/Holder.ts
4
+ /**
5
+ * A component that shows one element and lets its owner swap it in place.
6
+ *
7
+ * @remarks
8
+ * Everything above the holder stays mounted across a swap: the screen's error boundary, its context, the root keys
9
+ * and the colour hold. Only the held subtree changes, so the screen's `ScreenControl` keeps meaning the same screen.
10
+ * The swap function is handed over in a layout effect, before the first frame is written, and taken back in that
11
+ * effect's cleanup. A swap is a state update, which React commits in a microtask rather than at once, so a swap can
12
+ * ask to be told when its element is committed: the live view waits for that before it draws on or unmounts. Built on
13
+ * the loaded React, like every kit component; the screen harness's `rerender` and the live view's pushes use it.
14
+ *
15
+ * @internal
16
+ */
17
+ const holder = fromReact((react) => {
18
+ const Holder = (props) => {
19
+ const [shown, setShown] = react.useState(() => ({
20
+ element: props.initial,
21
+ committed: void 0
22
+ }));
23
+ react.useLayoutEffect(() => {
24
+ props.bind((element, committed) => setShown({
25
+ element,
26
+ committed
27
+ }));
28
+ return () => props.bind(void 0);
29
+ }, [props.bind]);
30
+ react.useLayoutEffect(() => shown.committed?.(), [shown]);
31
+ return shown.element;
32
+ };
33
+ Holder.displayName = "CliUiHolder";
34
+ return Holder;
35
+ });
36
+ /**
37
+ * A fresh {@link HolderSlot}.
38
+ *
39
+ * @internal
40
+ */
41
+ const holderSlot = () => {
42
+ let bound;
43
+ const pending = [];
44
+ const release = (through) => {
45
+ for (const committed of pending.splice(0, through + 1)) committed();
46
+ };
47
+ return {
48
+ bind: (swap) => {
49
+ bound = swap;
50
+ if (swap === void 0) release(pending.length - 1);
51
+ },
52
+ isBound: () => bound !== void 0,
53
+ swap: (next, committed) => {
54
+ if (bound === void 0) {
55
+ committed?.();
56
+ return false;
57
+ }
58
+ if (committed === void 0) {
59
+ bound(next);
60
+ return true;
61
+ }
62
+ const own = () => committed();
63
+ pending.push(own);
64
+ bound(next, () => {
65
+ const at = pending.indexOf(own);
66
+ if (at !== -1) release(at);
67
+ });
68
+ return true;
69
+ }
70
+ };
71
+ };
72
+
73
+ //#endregion
74
+ export { holder, holderSlot };
@@ -0,0 +1,52 @@
1
+ import { fromReact, inkModules } from "./ink.js";
2
+
3
+ //#region src/ui/internal/ScreenContext.ts
4
+ /**
5
+ * The React context carrying {@link ScreenContextValue}, built on the loaded React.
6
+ *
7
+ * @internal
8
+ */
9
+ const screenContext = fromReact((react) => react.createContext(void 0));
10
+ const ignore = () => void 0;
11
+ /**
12
+ * The mounted screen's cancel, for a widget whose own key (such as Select's `q`) ends the screen.
13
+ *
14
+ * @remarks
15
+ * A React hook; throws outside a screen mounted by `CliUi.run` or a `UiProvider`. Under a tree that is not a screen
16
+ * (a `UiProvider`, a live view) there is nothing to cancel, and it does nothing.
17
+ *
18
+ * @internal
19
+ */
20
+ const useScreenCancel = () => {
21
+ const screen = inkModules().react.useContext(screenContext());
22
+ if (screen === void 0) throw new Error("@effected/cli/ui: a widget was used outside a screen mounted by CliUi.run or a UiProvider");
23
+ return screen.cancel ?? ignore;
24
+ };
25
+ /**
26
+ * Wrap an input handler so a throw ends the screen as a defect instead of escaping.
27
+ *
28
+ * @remarks
29
+ * Ink calls `useInput` and `usePaste` handlers from its stdin listener, outside React's render, so an error boundary
30
+ * never sees what they throw: unguarded, it is an uncaught exception (the process dies, Effect finalizers skipped)
31
+ * or, where something keeps the process alive, a screen left waiting. Guarded, the screen dies with the error and
32
+ * `CliUi.run` unmounts it like any other defect. Outside a screen mounted by `CliUi.run`, a `UiProvider` tree
33
+ * included, a handler is called as is.
34
+ *
35
+ * A React hook.
36
+ *
37
+ * @internal
38
+ */
39
+ const useScreenGuard = () => {
40
+ const die = inkModules().react.useContext(screenContext())?.die;
41
+ return (handler) => (...args) => {
42
+ if (die === void 0) return handler(...args);
43
+ try {
44
+ handler(...args);
45
+ } catch (error) {
46
+ die(error);
47
+ }
48
+ };
49
+ };
50
+
51
+ //#endregion
52
+ export { screenContext, useScreenCancel, useScreenGuard };
@@ -0,0 +1,21 @@
1
+ import { inkModules } from "./ink.js";
2
+ import { screenContext } from "./ScreenContext.js";
3
+
4
+ //#region src/ui/internal/UiProviders.ts
5
+ /**
6
+ * Wrap `children` in the kit's providers: the theme, the glyph set, the optional size override, and a screen's cancel
7
+ * and defect route when it has them.
8
+ *
9
+ * @remarks
10
+ * The one place a kit tree's context is built, for `CliUi.run`'s screens, a live view and the public `UiProvider`,
11
+ * so every kit hook reads the same value under each.
12
+ *
13
+ * @internal
14
+ */
15
+ const uiProviders = (value, children) => inkModules().react.createElement(screenContext().Provider, {
16
+ value,
17
+ children
18
+ });
19
+
20
+ //#endregion
21
+ export { uiProviders };
@@ -0,0 +1,122 @@
1
+ import { inkChalk } from "./inkChalk.js";
2
+ import { Effect, Option } from "effect";
3
+
4
+ //#region src/ui/internal/ink.ts
5
+ const MISSING_PEERS = "@effected/cli/ui could not load its optional peers ink and react: install both beside @effected/cli to mount a screen";
6
+ const READ_BEFORE_LOAD = "@effected/cli/ui read Ink before loading it: run CliUi.context (or mount a screen with CliUi.run) before rendering UiProvider or a kit component in a tree of your own";
7
+ const UNRESOLVED_CHALK = "@effected/cli/ui could not resolve the chalk Ink uses (is ink bundled?), so Ink decides its own colour level";
8
+ let modules;
9
+ let loading;
10
+ const importPeers = async () => {
11
+ const [ink, react] = await Promise.all([import("ink"), import("react")]);
12
+ return {
13
+ ink,
14
+ react: react.default
15
+ };
16
+ };
17
+ /**
18
+ * Load `ink` and `react`, once. The only runtime access the kit has to either package: nothing imports a value
19
+ * from them, so importing `./ui` loads neither, and only mounting a screen does.
20
+ *
21
+ * @remarks
22
+ * Concurrent loads share one import, and a failed one is retried by the next call. A missing peer is a defect, not
23
+ * a typed failure, because it is an installation error no handler can recover from; its message names both peers.
24
+ *
25
+ * @internal
26
+ */
27
+ const loadInk = Effect.suspend(() => {
28
+ if (modules !== void 0) return Effect.succeed(modules);
29
+ return Effect.tryPromise({
30
+ try: () => {
31
+ loading ??= importPeers();
32
+ return loading;
33
+ },
34
+ catch: (cause) => new Error(MISSING_PEERS, { cause })
35
+ }).pipe(Effect.tap((loaded) => Effect.sync(() => {
36
+ modules = loaded;
37
+ })), Effect.tapError(() => Effect.sync(() => {
38
+ loading = void 0;
39
+ })), Effect.orDie);
40
+ });
41
+ /**
42
+ * The modules {@link loadInk} loaded, read at render time by kit components.
43
+ *
44
+ * @remarks
45
+ * Throws when nothing has loaded them: a kit component rendered outside a screen. Inside a render that throw is
46
+ * caught by the screen's error boundary and becomes a defect.
47
+ *
48
+ * @internal
49
+ */
50
+ const inkModules = () => {
51
+ if (modules === void 0) throw new Error(READ_BEFORE_LOAD);
52
+ return modules;
53
+ };
54
+ /**
55
+ * A value built once from the loaded React, such as a class component or a context, which cannot be declared at
56
+ * module scope because the kit holds no runtime React until {@link loadInk} runs.
57
+ *
58
+ * @remarks
59
+ * The returned accessor builds on first call and returns the same value thereafter; like {@link inkModules}, it
60
+ * throws if called before the load.
61
+ *
62
+ * @internal
63
+ */
64
+ const fromReact = (build) => {
65
+ let built;
66
+ return () => {
67
+ const { react } = inkModules();
68
+ if (built === void 0 || built.react !== react) built = {
69
+ react,
70
+ value: build(react)
71
+ };
72
+ return built.value;
73
+ };
74
+ };
75
+ const LEVELS = {
76
+ none: 0,
77
+ basic: 1,
78
+ "256": 2,
79
+ truecolor: 3
80
+ };
81
+ /**
82
+ * A stream's colour level as a chalk level: `none` 0, `basic` 1, `256` 2, `truecolor` 3.
83
+ *
84
+ * @internal
85
+ */
86
+ const levelOf = (colour) => LEVELS[colour];
87
+ let chalk;
88
+ const resolveChalk = Effect.promise(() => {
89
+ chalk ??= inkChalk();
90
+ return chalk;
91
+ });
92
+ let warned = false;
93
+ /**
94
+ * Hold `chalk` at `colour`'s level for the enclosing scope, restoring the saved level when the scope closes, by
95
+ * release or by interruption. With no chalk to hold, warn once and leave Ink's own detection in place.
96
+ *
97
+ * @internal
98
+ */
99
+ const holdChalkLevel = (found, colour) => Option.match(found, {
100
+ onNone: () => Effect.suspend(() => {
101
+ if (warned) return Effect.void;
102
+ warned = true;
103
+ return Effect.logWarning(UNRESOLVED_CHALK);
104
+ }),
105
+ onSome: (instance) => Effect.asVoid(Effect.acquireRelease(Effect.sync(() => {
106
+ const saved = instance.level;
107
+ instance.level = levelOf(colour);
108
+ return saved;
109
+ }), (saved) => Effect.sync(() => {
110
+ instance.level = saved;
111
+ })))
112
+ });
113
+ /**
114
+ * Set Ink's colour level from the stream's `ColorLevel` for the enclosing scope, on Ink's own chalk. The level is process-global while held: the last screen
115
+ * mounted wins.
116
+ *
117
+ * @internal
118
+ */
119
+ const withInkColour = (colour) => Effect.flatMap(resolveChalk, (found) => holdChalkLevel(found, colour));
120
+
121
+ //#endregion
122
+ export { fromReact, holdChalkLevel, inkModules, levelOf, loadInk, withInkColour };
@@ -0,0 +1,58 @@
1
+ import { createRequire } from "node:module";
2
+ import { Option } from "effect";
3
+ import { realpathSync } from "node:fs";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
+
6
+ //#region src/ui/internal/inkChalk.ts
7
+ const isInkChalk = (value) => (typeof value === "function" || typeof value === "object" && value !== null) && typeof value.level === "number";
8
+ /** The runtime's `import.meta.resolve`, when it has one. */
9
+ const esmResolve = typeof import.meta.resolve === "function" ? (specifier) => import.meta.resolve(specifier) : void 0;
10
+ /**
11
+ * The path of Ink's entry: through `resolve` (the runtime's `import.meta.resolve` by default), or, where that is
12
+ * missing or throws, through Node's CommonJS resolution from this module.
13
+ *
14
+ * @remarks
15
+ * Vite's module runner, which evaluates a Vitest reporter loaded by path, has an `import.meta.resolve` that throws
16
+ * ("not supported"); the CommonJS resolution finds the same file, since Ink's `exports` has a `default` condition.
17
+ *
18
+ * @param resolve - an ESM resolver, to stand in for the runtime's in a test
19
+ *
20
+ * @internal
21
+ */
22
+ const resolveInkEntry = (resolve = esmResolve) => {
23
+ if (resolve !== void 0) try {
24
+ return fileURLToPath(resolve("ink"));
25
+ } catch {}
26
+ return createRequire(import.meta.url).resolve("ink");
27
+ };
28
+ /**
29
+ * The chalk instance Ink itself imports, resolved from Ink's own location; `None` when it cannot be resolved.
30
+ *
31
+ * @remarks
32
+ * One of the three files licensed to touch Node. Ink's `exports` has
33
+ * only `"."` and chalk is its own dependency, so the kit cannot import Ink's chalk by name: a `chalk` of the kit's
34
+ * own could be a different copy, and setting its level would silently change nothing. Resolving `chalk` from Ink's
35
+ * entry ({@link resolveInkEntry}) and importing its realpath yields the very module Ink imports, because Node keys ES
36
+ * modules by realpath. A consumer that bundles Ink leaves nothing
37
+ * to resolve, and the answer is `None`; it never rejects.
38
+ *
39
+ * @param inkEntryOf - how Ink's entry is found; {@link resolveInkEntry} by default
40
+ *
41
+ * @internal
42
+ */
43
+ const inkChalk = async (inkEntryOf = () => resolveInkEntry()) => {
44
+ try {
45
+ const inkEntry = inkEntryOf();
46
+ const chalkPath = realpathSync(createRequire(inkEntry).resolve("chalk"));
47
+ const chalk = await import(
48
+ /* @vite-ignore */
49
+ pathToFileURL(chalkPath).href
50
+ );
51
+ return isInkChalk(chalk.default) ? Option.some(chalk.default) : Option.none();
52
+ } catch {
53
+ return Option.none();
54
+ }
55
+ };
56
+
57
+ //#endregion
58
+ export { inkChalk, resolveInkEntry };