@histoire/cli 0.0.0-stage → 1.0.0-beta.2

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 (175) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +8 -2
  3. package/dist/cli.d.ts +9 -0
  4. package/dist/cli.js +88 -0
  5. package/dist/commands/dev.d.ts +44 -0
  6. package/dist/commands/dev.js +115 -0
  7. package/dist/commands/host.d.ts +66 -0
  8. package/dist/commands/host.js +1 -0
  9. package/dist/commands/screenshot-setup-args.d.ts +4 -0
  10. package/dist/commands/screenshot-setup-args.js +35 -0
  11. package/dist/commands/signal-guard.d.ts +29 -0
  12. package/dist/commands/signal-guard.js +52 -0
  13. package/dist/index.d.ts +2 -0
  14. package/dist/index.js +1 -0
  15. package/dist/terminal/actions.d.ts +51 -0
  16. package/dist/terminal/actions.js +60 -0
  17. package/dist/terminal/banner.d.ts +19 -0
  18. package/dist/terminal/banner.js +48 -0
  19. package/dist/terminal/bridge.d.ts +58 -0
  20. package/dist/terminal/bridge.js +103 -0
  21. package/dist/terminal/clipboard.d.ts +46 -0
  22. package/dist/terminal/clipboard.js +85 -0
  23. package/dist/terminal/diagnostics/attach.d.ts +9 -0
  24. package/dist/terminal/diagnostics/attach.js +46 -0
  25. package/dist/terminal/diagnostics/client.d.ts +12 -0
  26. package/dist/terminal/diagnostics/client.js +19 -0
  27. package/dist/terminal/diagnostics/lines.d.ts +17 -0
  28. package/dist/terminal/diagnostics/lines.js +61 -0
  29. package/dist/terminal/dispatch.d.ts +28 -0
  30. package/dist/terminal/dispatch.js +52 -0
  31. package/dist/terminal/feedback.d.ts +14 -0
  32. package/dist/terminal/feedback.js +27 -0
  33. package/dist/terminal/history/bounded.d.ts +37 -0
  34. package/dist/terminal/history/bounded.js +54 -0
  35. package/dist/terminal/host-extras.d.ts +14 -0
  36. package/dist/terminal/host-extras.js +26 -0
  37. package/dist/terminal/info/client.d.ts +20 -0
  38. package/dist/terminal/info/client.js +25 -0
  39. package/dist/terminal/info/generation-client.d.ts +33 -0
  40. package/dist/terminal/info/generation-client.js +32 -0
  41. package/dist/terminal/info/lines.d.ts +19 -0
  42. package/dist/terminal/info/lines.js +33 -0
  43. package/dist/terminal/info/network.d.ts +17 -0
  44. package/dist/terminal/info/network.js +48 -0
  45. package/dist/terminal/info/qr.d.ts +7 -0
  46. package/dist/terminal/info/qr.js +14 -0
  47. package/dist/terminal/keys.d.ts +44 -0
  48. package/dist/terminal/keys.js +60 -0
  49. package/dist/terminal/logs/browser-options.d.ts +9 -0
  50. package/dist/terminal/logs/browser-options.js +19 -0
  51. package/dist/terminal/navigation/browser.d.ts +69 -0
  52. package/dist/terminal/navigation/browser.js +193 -0
  53. package/dist/terminal/navigation/list.d.ts +53 -0
  54. package/dist/terminal/navigation/list.js +104 -0
  55. package/dist/terminal/navigation/search.d.ts +22 -0
  56. package/dist/terminal/navigation/search.js +44 -0
  57. package/dist/terminal/output/decoder.d.ts +24 -0
  58. package/dist/terminal/output/decoder.js +63 -0
  59. package/dist/terminal/output/history.d.ts +43 -0
  60. package/dist/terminal/output/history.js +21 -0
  61. package/dist/terminal/output/pipeline.d.ts +33 -0
  62. package/dist/terminal/output/pipeline.js +59 -0
  63. package/dist/terminal/output/sanitize.d.ts +32 -0
  64. package/dist/terminal/output/sanitize.js +142 -0
  65. package/dist/terminal/panel-model.d.ts +20 -0
  66. package/dist/terminal/panel-model.js +38 -0
  67. package/dist/terminal/panel.d.ts +30 -0
  68. package/dist/terminal/panel.js +53 -0
  69. package/dist/terminal/plain.d.ts +29 -0
  70. package/dist/terminal/plain.js +68 -0
  71. package/dist/terminal/progress/format.d.ts +28 -0
  72. package/dist/terminal/progress/format.js +77 -0
  73. package/dist/terminal/progress/state.d.ts +71 -0
  74. package/dist/terminal/progress/state.js +150 -0
  75. package/dist/terminal/protocol/catalog.d.ts +143 -0
  76. package/dist/terminal/protocol/catalog.js +61 -0
  77. package/dist/terminal/protocol/core.d.ts +117 -0
  78. package/dist/terminal/protocol/core.js +98 -0
  79. package/dist/terminal/protocol/diagnostics.d.ts +79 -0
  80. package/dist/terminal/protocol/diagnostics.js +31 -0
  81. package/dist/terminal/protocol/index.d.ts +22 -0
  82. package/dist/terminal/protocol/index.js +1 -0
  83. package/dist/terminal/protocol/progress.d.ts +67 -0
  84. package/dist/terminal/protocol/progress.js +52 -0
  85. package/dist/terminal/protocol/requests.d.ts +30 -0
  86. package/dist/terminal/protocol/requests.js +13 -0
  87. package/dist/terminal/protocol/session.d.ts +55 -0
  88. package/dist/terminal/protocol/session.js +28 -0
  89. package/dist/terminal/protocol/tests.d.ts +212 -0
  90. package/dist/terminal/protocol/tests.js +87 -0
  91. package/dist/terminal/protocol/watch.d.ts +60 -0
  92. package/dist/terminal/protocol/watch.js +40 -0
  93. package/dist/terminal/requests/browser-options.d.ts +8 -0
  94. package/dist/terminal/requests/browser-options.js +24 -0
  95. package/dist/terminal/requests/history.d.ts +30 -0
  96. package/dist/terminal/requests/history.js +53 -0
  97. package/dist/terminal/retained.d.ts +27 -0
  98. package/dist/terminal/retained.js +21 -0
  99. package/dist/terminal/session-types.d.ts +76 -0
  100. package/dist/terminal/session-types.js +1 -0
  101. package/dist/terminal/session.d.ts +8 -0
  102. package/dist/terminal/session.js +282 -0
  103. package/dist/terminal/shutdown.d.ts +12 -0
  104. package/dist/terminal/shutdown.js +30 -0
  105. package/dist/terminal/stories/client.d.ts +26 -0
  106. package/dist/terminal/stories/client.js +28 -0
  107. package/dist/terminal/stories/handoff.d.ts +39 -0
  108. package/dist/terminal/stories/handoff.js +40 -0
  109. package/dist/terminal/stories/paged.d.ts +70 -0
  110. package/dist/terminal/stories/paged.js +137 -0
  111. package/dist/terminal/stories/render.d.ts +39 -0
  112. package/dist/terminal/stories/render.js +94 -0
  113. package/dist/terminal/stories/state.d.ts +93 -0
  114. package/dist/terminal/stories/state.js +191 -0
  115. package/dist/terminal/stories/target.d.ts +24 -0
  116. package/dist/terminal/stories/target.js +29 -0
  117. package/dist/terminal/style.d.ts +45 -0
  118. package/dist/terminal/style.js +82 -0
  119. package/dist/terminal/support.d.ts +53 -0
  120. package/dist/terminal/support.js +66 -0
  121. package/dist/terminal/surface.d.ts +41 -0
  122. package/dist/terminal/surface.js +200 -0
  123. package/dist/terminal/tests/client.d.ts +21 -0
  124. package/dist/terminal/tests/client.js +12 -0
  125. package/dist/terminal/tests/console.d.ts +95 -0
  126. package/dist/terminal/tests/console.js +202 -0
  127. package/dist/terminal/tests/format.d.ts +18 -0
  128. package/dist/terminal/tests/format.js +55 -0
  129. package/dist/terminal/tests/header.d.ts +16 -0
  130. package/dist/terminal/tests/header.js +90 -0
  131. package/dist/terminal/tests/reporter.d.ts +17 -0
  132. package/dist/terminal/tests/reporter.js +99 -0
  133. package/dist/terminal/tests/results.d.ts +44 -0
  134. package/dist/terminal/tests/results.js +104 -0
  135. package/dist/terminal/tests/scope.d.ts +25 -0
  136. package/dist/terminal/tests/scope.js +25 -0
  137. package/dist/terminal/tests/session.d.ts +11 -0
  138. package/dist/terminal/tests/session.js +24 -0
  139. package/dist/terminal/tests/state.d.ts +57 -0
  140. package/dist/terminal/tests/state.js +134 -0
  141. package/dist/terminal/views/clear-history.d.ts +6 -0
  142. package/dist/terminal/views/clear-history.js +10 -0
  143. package/dist/terminal/views/error.d.ts +8 -0
  144. package/dist/terminal/views/error.js +24 -0
  145. package/dist/terminal/views/frame.d.ts +20 -0
  146. package/dist/terminal/views/frame.js +23 -0
  147. package/dist/terminal/views/help.d.ts +3 -0
  148. package/dist/terminal/views/help.js +32 -0
  149. package/dist/terminal/views/index.d.ts +6 -0
  150. package/dist/terminal/views/index.js +13 -0
  151. package/dist/terminal/views/logs.d.ts +3 -0
  152. package/dist/terminal/views/logs.js +7 -0
  153. package/dist/terminal/views/registry.d.ts +114 -0
  154. package/dist/terminal/views/registry.js +40 -0
  155. package/dist/terminal/views/requests.d.ts +8 -0
  156. package/dist/terminal/views/requests.js +15 -0
  157. package/dist/terminal/views/session.d.ts +9 -0
  158. package/dist/terminal/views/session.js +133 -0
  159. package/dist/terminal/views/stories.d.ts +9 -0
  160. package/dist/terminal/views/stories.js +172 -0
  161. package/dist/terminal/views/tests.d.ts +9 -0
  162. package/dist/terminal/views/tests.js +105 -0
  163. package/dist/terminal/watch/client.d.ts +12 -0
  164. package/dist/terminal/watch/client.js +7 -0
  165. package/dist/terminal/watch/controller.d.ts +30 -0
  166. package/dist/terminal/watch/controller.js +157 -0
  167. package/dist/terminal/watch/format.d.ts +15 -0
  168. package/dist/terminal/watch/format.js +37 -0
  169. package/dist/terminal/watch/session.d.ts +17 -0
  170. package/dist/terminal/watch/session.js +12 -0
  171. package/dist/terminal/width.d.ts +24 -0
  172. package/dist/terminal/width.js +171 -0
  173. package/dist/workbench-url.d.ts +30 -0
  174. package/dist/workbench-url.js +55 -0
  175. package/package.json +54 -3
@@ -0,0 +1,193 @@
1
+ import { sanitizeText } from '../output/sanitize.js';
2
+ import { TERMINAL_BOUNDS } from '../protocol/core.js';
3
+ import { defaultStyle } from '../style.js';
4
+ import { renderViewFrame } from '../views/frame.js';
5
+ import { fitWidth, wrapWidth } from '../width.js';
6
+ import { createListNavigation } from './list.js';
7
+ import { createSearchInput } from './search.js';
8
+ /** Copy-all is bounded to this many characters of the newest entries (same bound as retained log text). */
9
+ const COPY_ALL_MAX_CHARS = TERMINAL_BOUNDS.logBytes;
10
+ /** Tab characters would break width accounting; the copied text keeps them. */
11
+ const showable = (text) => text.replaceAll('\t', ' ');
12
+ /**
13
+ * Builds list + detail + search + copy behavior over any bounded history. Logs, the
14
+ * latest-error screen and (slice 06) requests share it instead of cloning navigation.
15
+ * Selection is kept by stable ID: appends never move it, eviction moves it to the nearest
16
+ * retained entry, scrolling pauses following and End resumes.
17
+ * @param options History access and presentation.
18
+ */
19
+ export function createHistoryBrowser(options) {
20
+ const { host } = options;
21
+ const navigation = createListNavigation({ id: options.id, rank: options.rank, follow: options.follow !== false });
22
+ const search = createSearchInput();
23
+ let unsubscribe;
24
+ /** Entry shown in detail; held directly, so eviction while reading does not blank the screen. */
25
+ let detail;
26
+ let detailTop = 0;
27
+ /** Lowercased text per entry object, so filtering does not lowercase every entry on every render. */
28
+ const lowered = new WeakMap();
29
+ /** Lowercased searchable text of an entry (cached for object entries, which retained records are). */
30
+ function searchable(item) {
31
+ if (typeof item !== 'object' || item === null)
32
+ return options.text(item).toLowerCase();
33
+ let text = lowered.get(item);
34
+ if (text === undefined) {
35
+ text = options.text(item).toLowerCase();
36
+ lowered.set(item, text);
37
+ }
38
+ return text;
39
+ }
40
+ /** Entries matching the applied filter. */
41
+ function visible() {
42
+ const needle = search.applied().toLowerCase();
43
+ const all = options.items();
44
+ return needle ? all.filter(item => searchable(item).includes(needle)) : all;
45
+ }
46
+ /**
47
+ * Joins entries for copy-all, newest first until the bound, so a huge history cannot
48
+ * build an unbounded string. Returns the text and how many entries it holds.
49
+ */
50
+ function joinBounded(items) {
51
+ const parts = [];
52
+ let size = 0;
53
+ for (let index = items.length - 1; index >= 0; index--) {
54
+ const part = options.text(items[index]);
55
+ if (parts.length && size + part.length + 1 > COPY_ALL_MAX_CHARS)
56
+ break;
57
+ parts.push(part);
58
+ size += part.length + 1;
59
+ }
60
+ return { text: parts.reverse().join('\n'), count: parts.length };
61
+ }
62
+ /** Copies and reports; the text stays on screen whatever happens. Retained text is clean already, sanitizing again keeps the guarantee local. */
63
+ async function copy(text, what) {
64
+ const result = await host.copy(sanitizeText(text));
65
+ host.notify(result.ok ? `Copied ${what}${result.note ? ` (${result.note})` : ''}` : `Copy unavailable: ${result.reason}. Text is still shown`);
66
+ }
67
+ /** Wrapped lines of the open entry. */
68
+ const detailLines = (columns) => wrapWidth(showable(options.text(detail)), Math.max(1, columns - 2));
69
+ /** Scrolls the detail text, clamped. */
70
+ function scrollDetail(delta, rows) {
71
+ const total = detailLines(host.size().columns).length;
72
+ detailTop = Math.max(0, Math.min(detailTop + delta, Math.max(0, total - rows)));
73
+ }
74
+ /** Keys while an entry is open in detail. */
75
+ function detailKey(key) {
76
+ const page = Math.max(1, host.size().rows - 2);
77
+ if (key.name === 'escape' || key.name === 'return')
78
+ detail = undefined;
79
+ else if (key.char === 'y')
80
+ void copy(options.text(detail), 'entry');
81
+ else if (key.name === 'up')
82
+ scrollDetail(-1, page);
83
+ else if (key.name === 'down')
84
+ scrollDetail(1, page);
85
+ else if (key.name === 'pageup')
86
+ scrollDetail(-page, page);
87
+ else if (key.name === 'pagedown')
88
+ scrollDetail(page, page);
89
+ else if (key.name === 'home')
90
+ detailTop = 0;
91
+ else if (key.name === 'end')
92
+ scrollDetail(Number.MAX_SAFE_INTEGER, page);
93
+ else
94
+ return false;
95
+ return true;
96
+ }
97
+ /** Opens the selected entry. */
98
+ function openDetail() {
99
+ const item = navigation.selectedItem();
100
+ if (!item)
101
+ return;
102
+ detail = item;
103
+ detailTop = 0;
104
+ }
105
+ /** Status line above the list. */
106
+ function status(shown) {
107
+ const parts = [navigation.following() ? 'Following' : 'Paused, End follows', `${shown} of ${options.items().length} ${options.noun}`];
108
+ if (search.applied())
109
+ parts.push(`filter "${search.applied()}"`);
110
+ if (options.omitted())
111
+ parts.push(`${options.omitted()} older omitted`);
112
+ return defaultStyle().dim(parts.join(' · '));
113
+ }
114
+ /** One list row; the selected row is inverse, other rows tint only their label. */
115
+ function row(item, selected, columns) {
116
+ const [first, ...rest] = showable(options.text(item)).split('\n');
117
+ const tone = options.tone?.(item);
118
+ const label = tone && !selected ? defaultStyle()[tone](options.label(item)) : options.label(item);
119
+ const line = fitWidth(`${selected ? '›' : ' '} ${label} ${first}${rest.length ? ` (+${rest.length} lines)` : ''}`, columns);
120
+ return selected ? `\u001B[7m${line}\u001B[27m` : line;
121
+ }
122
+ /** Detail screen. */
123
+ function renderDetail(size) {
124
+ const lines = detailLines(size.columns).map(line => ` ${line}`);
125
+ return renderViewFrame({ title: `${options.title} · ${options.label(detail)}`, body: lines.slice(detailTop, detailTop + size.rows - 2), footer: 'Up/Down scroll · y copy · Enter or Esc list · q back', ...size });
126
+ }
127
+ return {
128
+ navigation,
129
+ search,
130
+ openDetail,
131
+ detailOpen: () => detail !== undefined,
132
+ enter() {
133
+ detail = undefined;
134
+ navigation.setItems(visible());
135
+ if (options.startInDetail) {
136
+ navigation.end();
137
+ openDetail();
138
+ }
139
+ unsubscribe = options.subscribe(() => {
140
+ navigation.setItems(visible());
141
+ host.requestRender();
142
+ });
143
+ },
144
+ leave() {
145
+ unsubscribe?.();
146
+ unsubscribe = undefined;
147
+ detail = undefined;
148
+ },
149
+ capturesInput: () => search.active(),
150
+ handleKey(key) {
151
+ if (detail)
152
+ return detailKey(key);
153
+ if (search.handleKey(key)) {
154
+ navigation.setItems(visible());
155
+ return true;
156
+ }
157
+ if (navigation.handleKey(key, Math.max(1, host.size().rows - 4)))
158
+ return true;
159
+ if (key.name === 'return') {
160
+ openDetail();
161
+ }
162
+ else if (key.char === 'y') {
163
+ const item = navigation.selectedItem();
164
+ if (item)
165
+ void copy(options.text(item), 'entry');
166
+ }
167
+ else if (key.char === 'Y') {
168
+ const items = visible();
169
+ if (items.length) {
170
+ const { text, count } = joinBounded(items);
171
+ void copy(text, count < items.length ? `newest ${count} of ${items.length} ${options.noun} (size limit)` : `${count} ${options.noun}`);
172
+ }
173
+ }
174
+ else {
175
+ return false;
176
+ }
177
+ return true;
178
+ },
179
+ render(size) {
180
+ if (detail)
181
+ return renderDetail(size);
182
+ const items = visible();
183
+ navigation.setItems(items);
184
+ const extra = options.header?.() ?? [];
185
+ const window = navigation.window(Math.max(1, size.rows - 3 - extra.length));
186
+ const selectedId = navigation.selectedId();
187
+ const body = [...extra, options.status ? options.status(items.length) : status(items.length), ...window.items.map(item => row(item, options.id(item) === selectedId, size.columns))];
188
+ if (!window.items.length)
189
+ body.push(` ${typeof options.empty === 'function' ? options.empty() : options.empty}`);
190
+ return renderViewFrame({ title: options.title, body, footer: search.active() ? `/${search.text()}▏` : options.footer ?? 'Up/Down Home/End · Enter detail · / search · y copy · Y copy all · Esc back', ...size });
191
+ },
192
+ };
193
+ }
@@ -0,0 +1,53 @@
1
+ import type { TerminalKey } from '../keys.js';
2
+ /** Visible slice of a navigable list. */
3
+ export interface ListWindow<T> {
4
+ /** Items to draw, in order. */
5
+ items: readonly T[];
6
+ /** Index of the first drawn item in the whole list. */
7
+ start: number;
8
+ /** Index of the selected item inside `items`, or -1 when it is outside or unresolved. */
9
+ selected: number;
10
+ }
11
+ /**
12
+ * Cursor over an ordered list with selection kept by stable ID, never by array offset.
13
+ * Append-only histories use follow mode: the cursor tracks the newest item until the
14
+ * user scrolls away; `end()` resumes following.
15
+ */
16
+ export interface ListNavigation<T> {
17
+ /** Replaces the items; the selection follows its ID, or stays unresolved when the ID is gone. */
18
+ setItems: (items: readonly T[]) => void;
19
+ /** Selected ID; survives the item disappearing (unresolved selection). */
20
+ selectedId: () => string | undefined;
21
+ /** Selected item, undefined when nothing is selected or the ID is unresolved. */
22
+ selectedItem: () => T | undefined;
23
+ /** Selects an ID explicitly (does not require it to exist yet). */
24
+ select: (id: string | undefined) => void;
25
+ /** Moves the cursor by items; leaves follow mode when moving up. */
26
+ move: (delta: number) => void;
27
+ /** Moves by `pageSize` items. */
28
+ page: (direction: 1 | -1, pageSize: number) => void;
29
+ /** Jumps to the first item and pauses following. */
30
+ home: () => void;
31
+ /** Jumps to the last item and resumes following. */
32
+ end: () => void;
33
+ /** Whether the cursor tracks the newest item. */
34
+ following: () => boolean;
35
+ /** Items to draw in `height` rows, keeping the cursor visible. */
36
+ window: (height: number) => ListWindow<T>;
37
+ /** Applies arrow/page/home/end keys; returns whether the key was consumed. */
38
+ handleKey: (key: TerminalKey, pageSize: number) => boolean;
39
+ }
40
+ /**
41
+ * Creates list navigation.
42
+ * @param options Stable ID reader and whether to start in follow mode.
43
+ * @param options.id Stable ID of an item.
44
+ * @param options.follow Start in follow mode.
45
+ * @param options.rank Monotonic ordering key of an item (e.g. a history's increasing ID). When given,
46
+ * a selection whose item disappeared (evicted, cleared, filtered out) moves to the nearest remaining
47
+ * item instead of staying unresolved. Omit for lists that keep an unresolved selection on purpose.
48
+ */
49
+ export declare function createListNavigation<T>(options: {
50
+ id: (item: T) => string;
51
+ follow?: boolean;
52
+ rank?: (item: T) => number;
53
+ }): ListNavigation<T>;
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Creates list navigation.
3
+ * @param options Stable ID reader and whether to start in follow mode.
4
+ * @param options.id Stable ID of an item.
5
+ * @param options.follow Start in follow mode.
6
+ * @param options.rank Monotonic ordering key of an item (e.g. a history's increasing ID). When given,
7
+ * a selection whose item disappeared (evicted, cleared, filtered out) moves to the nearest remaining
8
+ * item instead of staying unresolved. Omit for lists that keep an unresolved selection on purpose.
9
+ */
10
+ export function createListNavigation(options) {
11
+ let items = [];
12
+ let selected;
13
+ /** Last resolved offset, used to keep a window position while the selection is unresolved. */
14
+ let anchor = 0;
15
+ let follow = options.follow === true;
16
+ let firstVisible = 0;
17
+ /** Rank of the last resolved selection; the reference point when its item disappears. */
18
+ let selectedRank;
19
+ const indexOf = () => selected === undefined ? -1 : items.findIndex(item => options.id(item) === selected);
20
+ /** Selects by offset, clamped; offsets are transient, the ID is the identity. */
21
+ function selectIndex(index) {
22
+ if (!items.length)
23
+ return;
24
+ anchor = Math.min(Math.max(index, 0), items.length - 1);
25
+ selected = options.id(items[anchor]);
26
+ selectedRank = options.rank?.(items[anchor]);
27
+ }
28
+ /** Moves a vanished selection to the retained item closest in rank (the later one on a tie). */
29
+ function selectNearest() {
30
+ const rank = options.rank;
31
+ const after = items.findIndex(item => rank(item) >= selectedRank);
32
+ if (after < 0)
33
+ return selectIndex(items.length - 1);
34
+ if (after > 0 && selectedRank - rank(items[after - 1]) < rank(items[after]) - selectedRank)
35
+ return selectIndex(after - 1);
36
+ selectIndex(after);
37
+ }
38
+ const self = {
39
+ setItems(next) {
40
+ items = next;
41
+ if (follow && items.length)
42
+ selectIndex(items.length - 1);
43
+ else if (selected === undefined && items.length)
44
+ selectIndex(0);
45
+ else if (indexOf() >= 0)
46
+ anchor = indexOf();
47
+ else if (options.rank && selectedRank !== undefined && items.length)
48
+ selectNearest();
49
+ },
50
+ selectedId: () => selected,
51
+ selectedItem: () => items[indexOf()],
52
+ select(id) {
53
+ selected = id;
54
+ follow = false;
55
+ if (indexOf() >= 0) {
56
+ anchor = indexOf();
57
+ selectedRank = options.rank?.(items[anchor]);
58
+ }
59
+ },
60
+ move(delta) {
61
+ const current = indexOf();
62
+ selectIndex((current >= 0 ? current : anchor) + delta);
63
+ follow = false;
64
+ },
65
+ page(direction, pageSize) {
66
+ self.move(direction * Math.max(1, pageSize));
67
+ },
68
+ home() {
69
+ follow = false;
70
+ selectIndex(0);
71
+ },
72
+ end() {
73
+ follow = true;
74
+ selectIndex(items.length - 1);
75
+ },
76
+ following: () => follow,
77
+ window(height) {
78
+ const size = Math.max(1, height);
79
+ const current = indexOf() >= 0 ? indexOf() : anchor;
80
+ // Scroll only as far as needed to keep the cursor inside the window.
81
+ if (current < firstVisible)
82
+ firstVisible = current;
83
+ else if (current >= firstVisible + size)
84
+ firstVisible = current - size + 1;
85
+ firstVisible = Math.max(0, Math.min(firstVisible, Math.max(0, items.length - size)));
86
+ const shown = items.slice(firstVisible, firstVisible + size);
87
+ return { items: shown, start: firstVisible, selected: indexOf() >= firstVisible && indexOf() < firstVisible + size ? indexOf() - firstVisible : -1 };
88
+ },
89
+ handleKey(key, pageSize) {
90
+ const move = {
91
+ up: () => self.move(-1),
92
+ down: () => self.move(1),
93
+ pageup: () => self.page(-1, pageSize),
94
+ pagedown: () => self.page(1, pageSize),
95
+ home: () => self.home(),
96
+ end: () => self.end(),
97
+ };
98
+ const run = Object.hasOwn(move, key.name) ? move[key.name] : undefined;
99
+ run?.();
100
+ return run !== undefined;
101
+ },
102
+ };
103
+ return self;
104
+ }
@@ -0,0 +1,22 @@
1
+ import type { TerminalKey } from '../keys.js';
2
+ /** `/` search prompt state shared by detail views. */
3
+ export interface SearchInput {
4
+ /** Whether the prompt is being edited; the view must then route every key here. */
5
+ active: () => boolean;
6
+ /** Text shown in the prompt: the draft while editing, otherwise the applied filter. */
7
+ text: () => string;
8
+ /** Applied filter (empty when none). */
9
+ applied: () => string;
10
+ /**
11
+ * Handles a key. While editing it consumes everything printable (so action keys
12
+ * cannot fire), Enter applies, Escape cancels. Returns whether the key was consumed.
13
+ */
14
+ handleKey: (key: TerminalKey) => boolean;
15
+ /** Drops the applied filter and any draft. */
16
+ clear: () => void;
17
+ }
18
+ /**
19
+ * Creates a search prompt. Opened with `/`; Ctrl+C is never seen here because the
20
+ * session handles it before views.
21
+ */
22
+ export declare function createSearchInput(): SearchInput;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Creates a search prompt. Opened with `/`; Ctrl+C is never seen here because the
3
+ * session handles it before views.
4
+ */
5
+ export function createSearchInput() {
6
+ let editing = false;
7
+ let draft = '';
8
+ let applied = '';
9
+ return {
10
+ active: () => editing,
11
+ text: () => editing ? draft : applied,
12
+ applied: () => applied,
13
+ clear() {
14
+ editing = false;
15
+ draft = '';
16
+ applied = '';
17
+ },
18
+ handleKey(key) {
19
+ if (!editing) {
20
+ if (key.char !== '/')
21
+ return false;
22
+ editing = true;
23
+ draft = applied;
24
+ return true;
25
+ }
26
+ if (key.name === 'return') {
27
+ applied = draft;
28
+ editing = false;
29
+ }
30
+ else if (key.name === 'escape') {
31
+ editing = false;
32
+ draft = '';
33
+ }
34
+ else if (key.name === 'backspace') {
35
+ draft = Array.from(draft).slice(0, -1).join('');
36
+ }
37
+ else if (key.char) {
38
+ draft += key.char;
39
+ }
40
+ // Unknown control keys are swallowed too: nothing may leak to main actions.
41
+ return true;
42
+ },
43
+ };
44
+ }
@@ -0,0 +1,24 @@
1
+ /** One completed, sanitized output line. */
2
+ export interface DecodedLine {
3
+ /** Text without terminators, controls or configured credentials. */
4
+ text: string;
5
+ /** Characters dropped from an oversized line, 0 otherwise. */
6
+ truncated: number;
7
+ }
8
+ /** Streaming decoder for one stdout or stderr stream. */
9
+ export interface LineDecoder {
10
+ /** Consumes a raw chunk; may emit zero or more lines. */
11
+ write: (chunk: Uint8Array) => void;
12
+ /** Flushes the final unterminated line at stream end (or generation change). */
13
+ end: () => void;
14
+ }
15
+ /**
16
+ * Creates a decoder that turns raw bytes into sanitized lines.
17
+ * Split multibyte characters and escape sequences survive chunk boundaries,
18
+ * `\r` rewrites the unfinished line, and oversized lines keep their head with an
19
+ * explicit `truncated` count while the rest keeps draining.
20
+ * @param onLine Receives each completed line.
21
+ * @param secrets Credentials redacted before a line is emitted.
22
+ * @param maxLength Longest retained line in UTF-16 units.
23
+ */
24
+ export declare function createLineDecoder(onLine: (line: DecodedLine) => void, secrets?: readonly string[], maxLength?: number): LineDecoder;
@@ -0,0 +1,63 @@
1
+ import { StringDecoder } from 'node:string_decoder';
2
+ import { TERMINAL_BOUNDS, truncateText } from '../protocol/core.js';
3
+ import { createControlStripper, redactSecrets } from './sanitize.js';
4
+ /**
5
+ * Creates a decoder that turns raw bytes into sanitized lines.
6
+ * Split multibyte characters and escape sequences survive chunk boundaries,
7
+ * `\r` rewrites the unfinished line, and oversized lines keep their head with an
8
+ * explicit `truncated` count while the rest keeps draining.
9
+ * @param onLine Receives each completed line.
10
+ * @param secrets Credentials redacted before a line is emitted.
11
+ * @param maxLength Longest retained line in UTF-16 units.
12
+ */
13
+ export function createLineDecoder(onLine, secrets = [], maxLength = TERMINAL_BOUNDS.logTextLength) {
14
+ const utf8 = new StringDecoder('utf8');
15
+ const strip = createControlStripper();
16
+ let line = '';
17
+ let dropped = 0;
18
+ let carriage = false;
19
+ /** Emits the current line, redacted after the bound so no credential prefix survives the cut. */
20
+ function emit() {
21
+ const cut = truncateText(line, maxLength);
22
+ const truncated = dropped + cut.truncated;
23
+ onLine({ text: redactSecrets(cut.text, secrets, truncated > 0), truncated });
24
+ line = '';
25
+ dropped = 0;
26
+ }
27
+ /** Feeds sanitized text through the line assembler. */
28
+ function feed(text) {
29
+ for (let index = 0; index < text.length; index++) {
30
+ const char = text[index];
31
+ if (char === '\n') {
32
+ carriage = false;
33
+ emit();
34
+ }
35
+ else if (char === '\r') {
36
+ carriage = true;
37
+ }
38
+ else {
39
+ // A bare carriage return rewrites the unfinished line.
40
+ if (carriage) {
41
+ line = '';
42
+ dropped = 0;
43
+ carriage = false;
44
+ }
45
+ if (line.length < maxLength)
46
+ line += char;
47
+ else
48
+ dropped++;
49
+ }
50
+ }
51
+ }
52
+ return {
53
+ write(chunk) {
54
+ feed(strip(utf8.write(Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength))));
55
+ },
56
+ end() {
57
+ feed(strip(utf8.end()));
58
+ if (line || dropped)
59
+ emit();
60
+ carriage = false;
61
+ },
62
+ };
63
+ }
@@ -0,0 +1,43 @@
1
+ import type { TerminalLogLevel } from '../protocol/core.js';
2
+ /** Where a retained record came from. */
3
+ export type LogSource = 'stdout' | 'stderr' | 'console' | 'diagnostic';
4
+ /** Sanitized, retained log entry. */
5
+ export interface LogRecord {
6
+ /** Stable, strictly increasing session identifier (survives eviction, clearing and restarts). */
7
+ id: number;
8
+ /** Origin of the text. */
9
+ source: LogSource;
10
+ /** Severity; raw stderr lines are `error`. */
11
+ level: TerminalLogLevel;
12
+ /** Sanitized text, possibly multiline for console records. */
13
+ text: string;
14
+ /** Characters dropped by a line bound, 0 otherwise. */
15
+ truncated: number;
16
+ /** Runtime generation that produced it, when known. */
17
+ generation?: string;
18
+ }
19
+ /** Fields supplied when appending; `id` is assigned. */
20
+ export type LogInput = Omit<LogRecord, 'id'>;
21
+ /** Bounded session log retention. */
22
+ export interface LogHistory {
23
+ /** Retains a record, evicting oldest ones beyond the bounds. */
24
+ append: (input: LogInput) => LogRecord;
25
+ /** Currently retained records, oldest first. */
26
+ entries: () => readonly LogRecord[];
27
+ /** Number of records evicted by bounds since the session began (not by `clear`). */
28
+ readonly omitted: number;
29
+ /** Retained text size in UTF-8 bytes. */
30
+ readonly bytes: number;
31
+ /** Deletes retained records; identifiers keep increasing. */
32
+ clear: () => void;
33
+ /** Notifies after each append or clear; returns an unsubscribe function. */
34
+ subscribe: (listener: () => void) => () => void;
35
+ }
36
+ /**
37
+ * Creates a session history bounded by entry count and sanitized UTF-8 bytes.
38
+ * @param limits Overrides for tests; defaults are the frozen contract bounds.
39
+ */
40
+ export declare function createLogHistory(limits?: {
41
+ entries?: number;
42
+ bytes?: number;
43
+ }): LogHistory;
@@ -0,0 +1,21 @@
1
+ import { createBoundedHistory } from '../history/bounded.js';
2
+ import { TERMINAL_BOUNDS } from '../protocol/core.js';
3
+ /**
4
+ * Creates a session history bounded by entry count and sanitized UTF-8 bytes.
5
+ * @param limits Overrides for tests; defaults are the frozen contract bounds.
6
+ */
7
+ export function createLogHistory(limits = {}) {
8
+ const history = createBoundedHistory({ entries: limits.entries ?? TERMINAL_BOUNDS.logEntries, maxWeight: limits.bytes ?? TERMINAL_BOUNDS.logBytes, weigh: record => Buffer.byteLength(record.text) });
9
+ return {
10
+ get omitted() {
11
+ return history.omitted;
12
+ },
13
+ get bytes() {
14
+ return history.weight;
15
+ },
16
+ append: input => history.append(id => ({ ...input, id })),
17
+ entries: history.entries,
18
+ clear: history.clear,
19
+ subscribe: history.subscribe,
20
+ };
21
+ }
@@ -0,0 +1,33 @@
1
+ import type { RuntimeOutput } from '@histoire/dev-proxy/protocol';
2
+ import type { LogHistory } from './history.js';
3
+ /** Minimal writable used for visible output. */
4
+ export interface OutputSink {
5
+ write: (data: string | Uint8Array) => unknown;
6
+ }
7
+ /** Where untouched output goes while no renderer owns the screen. */
8
+ export interface OutputPassthrough {
9
+ stdout: OutputSink;
10
+ stderr: OutputSink;
11
+ }
12
+ /** Single entry for every output source: child streams, child console events, proxy diagnostics. */
13
+ export interface OutputPipeline {
14
+ /** Proxy `onOutput`: decodes into history and forwards the raw bytes unchanged. */
15
+ onOutput: (output: RuntimeOutput) => void;
16
+ /** Child console `log` event payload (validated here): records it and forwards `text\n` on the matching stream. */
17
+ onLog: (event: unknown, generation?: string) => void;
18
+ /** Proxy `onDiagnostic`: records it and forwards `text\n` on stderr. */
19
+ onDiagnostic: (text: string) => void;
20
+ /** Flushes unfinished lines of every stream (shutdown). */
21
+ flush: () => void;
22
+ }
23
+ /**
24
+ * Routes all runtime output through one decoder/sanitizer into the history.
25
+ * Passthrough keeps the pre-existing visible output byte for byte; only the
26
+ * retained copy is sanitized and redacted. No process-wide stream patching.
27
+ * @param options History, credentials to redact, and the optional visible sinks.
28
+ */
29
+ export declare function createOutputPipeline(options: {
30
+ history: LogHistory;
31
+ secrets?: readonly string[];
32
+ passthrough?: OutputPassthrough;
33
+ }): OutputPipeline;
@@ -0,0 +1,59 @@
1
+ import { isTerminalLogEvent, TERMINAL_BOUNDS, truncateText } from '../protocol/core.js';
2
+ import { createLineDecoder } from './decoder.js';
3
+ import { sanitizeText } from './sanitize.js';
4
+ /**
5
+ * Routes all runtime output through one decoder/sanitizer into the history.
6
+ * Passthrough keeps the pre-existing visible output byte for byte; only the
7
+ * retained copy is sanitized and redacted. No process-wide stream patching.
8
+ * @param options History, credentials to redact, and the optional visible sinks.
9
+ */
10
+ export function createOutputPipeline(options) {
11
+ const secrets = options.secrets ?? [];
12
+ const decoders = new Map();
13
+ /** Returns the decoder for a stream, flushing the previous generation's tail first. */
14
+ function decoderFor(stream, generation) {
15
+ const current = decoders.get(stream);
16
+ if (current?.generation === generation)
17
+ return current.decoder;
18
+ current?.decoder.end();
19
+ const decoder = createLineDecoder(line => options.history.append({ source: stream, level: stream === 'stderr' ? 'error' : 'log', text: line.text, truncated: line.truncated, generation }), secrets);
20
+ decoders.set(stream, { generation, decoder });
21
+ return decoder;
22
+ }
23
+ /** Visible output must never fail because of a broken sink. */
24
+ function forward(stream, data) {
25
+ try {
26
+ options.passthrough?.[stream].write(data);
27
+ }
28
+ catch { }
29
+ }
30
+ return {
31
+ onOutput({ stream, generation, chunk }) {
32
+ if (!chunk) {
33
+ decoders.get(stream)?.decoder.end();
34
+ decoders.delete(stream);
35
+ return;
36
+ }
37
+ forward(stream, chunk);
38
+ decoderFor(stream, generation).write(chunk);
39
+ },
40
+ onLog(event, generation) {
41
+ if (!isTerminalLogEvent(event))
42
+ return;
43
+ const cut = truncateText(event.text, TERMINAL_BOUNDS.logTextLength);
44
+ const truncated = (event.truncated ?? 0) + cut.truncated;
45
+ options.history.append({ source: 'console', level: event.level, text: sanitizeText(cut.text, secrets, truncated > 0), truncated, generation });
46
+ forward(event.level === 'warn' || event.level === 'error' ? 'stderr' : 'stdout', `${event.text}\n`);
47
+ },
48
+ onDiagnostic(text) {
49
+ const cut = truncateText(text, TERMINAL_BOUNDS.logTextLength);
50
+ options.history.append({ source: 'diagnostic', level: 'error', text: sanitizeText(cut.text, secrets, cut.truncated > 0), truncated: cut.truncated });
51
+ forward('stderr', `${text}\n`);
52
+ },
53
+ flush() {
54
+ for (const { decoder } of decoders.values())
55
+ decoder.end();
56
+ decoders.clear();
57
+ },
58
+ };
59
+ }