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

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 +117 -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,40 @@
1
+ import { invalidArgument, rejectUnknownKeys, requireRecord, TERMINAL_BOUNDS, truncateText } from './core.js';
2
+ import { parseTestRunArgs } from './tests.js';
3
+ /** Longest reason text carried by a state snapshot. */
4
+ export const WATCH_REASON_MAX = 240;
5
+ /**
6
+ * Validates untrusted `watch.set` arguments. The scope is validated exactly like a
7
+ * `tests.run` target, so the watch can never hold a scope a manual run could not name.
8
+ * @param value Detached JSON from the parent.
9
+ */
10
+ export function parseWatchSetArgs(value) {
11
+ const args = requireRecord(value);
12
+ rejectUnknownKeys(args, ['enabled', 'scope']);
13
+ if (typeof args.enabled !== 'boolean')
14
+ invalidArgument('enabled must be a boolean');
15
+ if (!args.enabled)
16
+ return { enabled: false };
17
+ if (args.scope === undefined)
18
+ invalidArgument('scope is required when enabling');
19
+ return { enabled: true, scope: parseTestRunArgs({ target: args.scope }).target };
20
+ }
21
+ /**
22
+ * Bounds free text of a reason so a state snapshot always fits one frame.
23
+ * @param text Reason text.
24
+ */
25
+ export function boundReason(text) {
26
+ return truncateText(text.split('\n')[0], Math.min(WATCH_REASON_MAX, TERMINAL_BOUNDS.logTextLength)).text;
27
+ }
28
+ /**
29
+ * Shape check for a state arriving from the child.
30
+ * @param value Candidate payload.
31
+ */
32
+ export function isWatchState(value) {
33
+ if (!value || typeof value !== 'object')
34
+ return false;
35
+ const state = value;
36
+ return typeof state.enabled === 'boolean' && ['off', 'idle', 'waiting', 'running', 'paused'].includes(state.phase)
37
+ && Number.isFinite(state.pending) && Number.isFinite(state.runs)
38
+ && (state.reason === undefined || typeof state.reason === 'string')
39
+ && (state.operationId === undefined || typeof state.operationId === 'string');
40
+ }
@@ -0,0 +1,8 @@
1
+ import type { HistoryBrowserOptions } from '../navigation/browser.js';
2
+ import type { RequestRecord } from '../protocol/requests.js';
3
+ import type { TerminalViewHost } from '../views/registry.js';
4
+ /**
5
+ * Adapts the request history to the shared history browser.
6
+ * @param host View host; `requests` is the session history.
7
+ */
8
+ export declare function requestBrowserOptions(host: Pick<TerminalViewHost, 'size' | 'notify' | 'copy' | 'requestRender' | 'requests'>): Pick<HistoryBrowserOptions<RequestRecord>, 'host' | 'items' | 'id' | 'rank' | 'text' | 'label' | 'tone' | 'omitted' | 'subscribe' | 'header'>;
@@ -0,0 +1,24 @@
1
+ import { formatDuration } from '../progress/format.js';
2
+ /** One-line description of a request, used for rows, search, detail and copy. */
3
+ function describeRequest(record) {
4
+ return `${record.method} ${record.pathname} ${record.status ?? 'no response'} ${record.outcome} ${formatDuration(record.durationMs)}`;
5
+ }
6
+ /**
7
+ * Adapts the request history to the shared history browser.
8
+ * @param host View host; `requests` is the session history.
9
+ */
10
+ export function requestBrowserOptions(host) {
11
+ const history = host.requests;
12
+ return {
13
+ host,
14
+ items: () => history.entries(),
15
+ id: record => String(record.id),
16
+ rank: record => record.id,
17
+ text: describeRequest,
18
+ label: record => `#${record.id}`,
19
+ tone: record => record.outcome === 'failed' ? 'error' : record.outcome === 'aborted' ? 'warn' : undefined,
20
+ omitted: () => history.omitted,
21
+ subscribe: listener => history.subscribe(listener),
22
+ header: () => history.inFlight() ? [`\u001B[2m${history.inFlight()} in flight\u001B[22m`] : [],
23
+ };
24
+ }
@@ -0,0 +1,30 @@
1
+ import type { ProxyRequestEvent } from '@histoire/dev-proxy';
2
+ import type { RequestRecord } from '../protocol/requests.js';
3
+ /** Bounded session history of public HTTP exchanges. */
4
+ export interface RequestHistory {
5
+ /** Proxy `onRequest`: tracks starts and retains finished exchanges. Never throws. */
6
+ onEvent: (event: ProxyRequestEvent) => void;
7
+ /** Retained finished exchanges, oldest first. */
8
+ entries: () => readonly RequestRecord[];
9
+ /** Exchanges evicted by retention since the session began (not by `clear`). */
10
+ readonly omitted: number;
11
+ /** Exchanges started and not yet ended, among the tracked ones. */
12
+ inFlight: () => number;
13
+ /** Deletes retained records; identifiers keep increasing and in-flight tracking continues. */
14
+ clear: () => void;
15
+ /** Notifies after each change; returns an unsubscribe function. */
16
+ subscribe: (listener: () => void) => () => void;
17
+ }
18
+ /**
19
+ * Creates the request history. Retains 500 finished exchanges; live tracking holds only
20
+ * numeric keys, capped, so stalled connections cannot accumulate metadata.
21
+ * @param options Options.
22
+ * @param options.secrets Credentials to redact from paths.
23
+ * @param options.entries Retained entries override (tests).
24
+ * @param options.inFlight Tracked in-flight override (tests).
25
+ */
26
+ export declare function createRequestHistory(options?: {
27
+ secrets?: readonly string[];
28
+ entries?: number;
29
+ inFlight?: number;
30
+ }): RequestHistory;
@@ -0,0 +1,53 @@
1
+ import { createBoundedHistory } from '../history/bounded.js';
2
+ import { sanitizeText } from '../output/sanitize.js';
3
+ import { TERMINAL_BOUNDS, truncateText } from '../protocol/core.js';
4
+ import { REQUEST_BOUNDS } from '../protocol/requests.js';
5
+ /**
6
+ * Creates the request history. Retains 500 finished exchanges; live tracking holds only
7
+ * numeric keys, capped, so stalled connections cannot accumulate metadata.
8
+ * @param options Options.
9
+ * @param options.secrets Credentials to redact from paths.
10
+ * @param options.entries Retained entries override (tests).
11
+ * @param options.inFlight Tracked in-flight override (tests).
12
+ */
13
+ export function createRequestHistory(options = {}) {
14
+ const history = createBoundedHistory({ entries: options.entries ?? TERMINAL_BOUNDS.requestEntries });
15
+ const maxLive = options.inFlight ?? REQUEST_BOUNDS.inFlight;
16
+ /** Keys of started exchanges, oldest first (a `Set` keeps insertion order). */
17
+ const live = new Set();
18
+ /** Pathname made safe for display and copy: controls removed, credential redacted, bounded. */
19
+ function clean(text, max) {
20
+ return truncateText(sanitizeText(text, options.secrets ?? []), max).text;
21
+ }
22
+ return {
23
+ get omitted() {
24
+ return history.omitted;
25
+ },
26
+ entries: history.entries,
27
+ clear: history.clear,
28
+ subscribe: history.subscribe,
29
+ inFlight: () => live.size,
30
+ onEvent(event) {
31
+ try {
32
+ if (event.phase === 'start') {
33
+ live.add(event.key);
34
+ // Stalled connections must not grow tracking: forget the oldest one (its record is still produced when it ends).
35
+ if (live.size > maxLive)
36
+ live.delete(live.values().next().value);
37
+ history.touch();
38
+ return;
39
+ }
40
+ live.delete(event.key);
41
+ history.append(id => ({
42
+ id,
43
+ method: clean(event.method, REQUEST_BOUNDS.methodLength),
44
+ pathname: clean(event.pathname, REQUEST_BOUNDS.pathLength),
45
+ ...(event.status === undefined ? {} : { status: event.status }),
46
+ outcome: event.outcome,
47
+ durationMs: event.durationMs,
48
+ }));
49
+ }
50
+ catch { }
51
+ },
52
+ };
53
+ }
@@ -0,0 +1,27 @@
1
+ /** One session history that `x` can delete (logs, and requests once slice 06 registers them). */
2
+ export interface RetainedHistory {
3
+ /** Stable key; registering the same key again replaces the earlier entry. */
4
+ id: string;
5
+ /** Plural noun for feedback, e.g. `log entries`. */
6
+ label: string;
7
+ /** Number of retained entries. */
8
+ count: () => number;
9
+ /** Deletes the retained entries. Must not touch test history or running work. */
10
+ clear: () => void;
11
+ }
12
+ /** Result of deleting retained histories. */
13
+ export interface RetainedClearResult {
14
+ /** Feedback sentence, e.g. `Deleted 12 log entries, 3 requests`. */
15
+ summary: string;
16
+ /** Total entries deleted. */
17
+ deleted: number;
18
+ }
19
+ /** Registry of deletable histories shared by the session and views (`x` key). */
20
+ export interface RetainedHistories {
21
+ /** Adds (or replaces) a history; returns a remover. */
22
+ register: (history: RetainedHistory) => () => void;
23
+ /** Deletes every registered history and describes what was deleted. */
24
+ clear: () => RetainedClearResult;
25
+ }
26
+ /** Creates an empty registry. */
27
+ export declare function createRetainedHistories(): RetainedHistories;
@@ -0,0 +1,21 @@
1
+ /** Creates an empty registry. */
2
+ export function createRetainedHistories() {
3
+ const histories = new Map();
4
+ return {
5
+ register(history) {
6
+ histories.set(history.id, history);
7
+ return () => void (histories.get(history.id) === history && histories.delete(history.id));
8
+ },
9
+ clear() {
10
+ const parts = [];
11
+ let deleted = 0;
12
+ for (const history of histories.values()) {
13
+ const count = history.count();
14
+ history.clear();
15
+ deleted += count;
16
+ parts.push(`${count} ${history.label}`);
17
+ }
18
+ return { deleted, summary: deleted ? `Deleted ${parts.join(', ')}` : 'No retained history to delete' };
19
+ },
20
+ };
21
+ }
@@ -0,0 +1,76 @@
1
+ import type { Readable, Writable } from 'node:stream';
2
+ import type { TerminalBridge } from './bridge.js';
3
+ import type { ClipboardWriter } from './clipboard.js';
4
+ import type { LogHistory } from './output/history.js';
5
+ import type { OutputPassthrough } from './output/pipeline.js';
6
+ import type { ProgressState } from './progress/state.js';
7
+ import type { RestartRequest } from './protocol/index.js';
8
+ import type { RequestHistory } from './requests/history.js';
9
+ import type { RetainedHistories } from './retained.js';
10
+ import type { TerminalMode } from './support.js';
11
+ import type { TestsState } from './tests/state.js';
12
+ import type { TerminalViewFactory, ViewRegistry } from './views/registry.js';
13
+ /** Capabilities of the dev command the session drives; bound once the proxy exists. */
14
+ export interface SessionHost {
15
+ /** Requests a runtime replacement. */
16
+ restart: (request: RestartRequest) => Promise<void>;
17
+ /** Opens an absolute URL in the default browser. */
18
+ openBrowser: (url: string) => Promise<void>;
19
+ /** Closes proxy and runtime; the single existing shutdown. */
20
+ close: () => Promise<void>;
21
+ }
22
+ /** Option subset the host extras read. */
23
+ export type SessionHostExtras = Pick<TerminalSessionOptions, 'logs' | 'retained' | 'host' | 'interfaces'>;
24
+ /** Inputs of one dev command's terminal session. Stream/environment fields are injectable for tests. */
25
+ export interface TerminalSessionOptions {
26
+ /** Explicit `--tui` (true) or `--no-tui` (false). */
27
+ flag?: boolean;
28
+ /** `--test-watch`: watch the whole book from the first ready generation, without any input. */
29
+ testWatch?: boolean;
30
+ /** Shown in the panel title. */
31
+ version: string;
32
+ logs: LogHistory;
33
+ /** Public HTTP exchange history fed by the proxy observer; a private empty one is used when absent. */
34
+ requests?: RequestHistory;
35
+ progress: ProgressState;
36
+ bridge: TerminalBridge;
37
+ /** Observed test operations fed by the bridge; the dev command creates it so runtime retirement reaches it. A private one is created when absent. */
38
+ tests?: TestsState;
39
+ /** Deletable histories shared with the dev command (slice 06 registers requests here); logs are always registered. */
40
+ retained?: RetainedHistories;
41
+ /** The `--host` value, to derive network URLs from the configured binding. */
42
+ host?: string | boolean;
43
+ /** Network interfaces for network URLs; defaults to `os.networkInterfaces()`. */
44
+ interfaces?: () => import('./info/network.js').InterfaceTable;
45
+ /** Clipboard writer; defaults to an honest "unavailable". */
46
+ clipboard?: ClipboardWriter;
47
+ /** View list; defaults to `views/index.ts`. */
48
+ viewFactories?: readonly TerminalViewFactory[];
49
+ stdin?: Readable & NodeJS.ReadStream;
50
+ stdout?: Writable & NodeJS.WriteStream;
51
+ environment?: NodeJS.ProcessEnv;
52
+ execArgv?: readonly string[];
53
+ /** Unix suspend; defaults to sending SIGTSTP to this process. */
54
+ suspendProcess?: () => void;
55
+ }
56
+ /** Terminal session of the dev command: owns raw input, screen and the plain fallback. */
57
+ export interface TerminalSession {
58
+ /** Sinks for the output pipeline: child output goes above the panel, or straight to the stream in plain mode. */
59
+ passthrough: OutputPassthrough;
60
+ /** Lifecycle notice: one line above the panel, or a plain line. */
61
+ line: (text: string) => void;
62
+ /** Public listener address, known before project evaluation. */
63
+ onListening: (url: string) => void;
64
+ /** Records the workbench base once ready. */
65
+ onReady: (base: string) => void;
66
+ /** Connects the session to the started proxy. */
67
+ bind: (host: SessionHost) => void;
68
+ /** Restores input, screen and cursor now; idempotent. Also used when startup fails. */
69
+ release: () => void;
70
+ /** Blocks new actions, restores the terminal, then joins the host shutdown. Idempotent; rejects with cleanup failures. */
71
+ shutdown: () => Promise<void>;
72
+ /** Current rendering mode (`plain` while released). */
73
+ readonly mode: TerminalMode;
74
+ /** Registered views (inspection and later slices). */
75
+ readonly registry: ViewRegistry;
76
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,8 @@
1
+ import type { TerminalSession, TerminalSessionOptions } from './session-types.js';
2
+ export type { SessionHost, TerminalSession, TerminalSessionOptions } from './session-types.js';
3
+ /**
4
+ * Creates the session before the proxy binds, without importing the project graph.
5
+ * Throws for an invalid `HISTOIRE_TUI` so the command fails before any evaluation.
6
+ * @param options Session inputs.
7
+ */
8
+ export declare function createTerminalSession(options: TerminalSessionOptions): TerminalSession;
@@ -0,0 +1,282 @@
1
+ import { url as inspectorUrl } from 'node:inspector';
2
+ import { unavailableClipboard } from './clipboard.js';
3
+ import { dispatchKey } from './dispatch.js';
4
+ import { createFeedback } from './feedback.js';
5
+ import { createHostExtras } from './host-extras.js';
6
+ import { createKeyInput } from './keys.js';
7
+ import { buildPanelModel } from './panel-model.js';
8
+ import { renderPanel } from './panel.js';
9
+ import { createPlainInput, runPlainCommand } from './plain.js';
10
+ import { describeProgress } from './progress/format.js';
11
+ import { createRequestHistory } from './requests/history.js';
12
+ import { createShutdown } from './shutdown.js';
13
+ import { decideTerminalMode } from './support.js';
14
+ import { createSurface } from './surface.js';
15
+ import { createSessionTests } from './tests/session.js';
16
+ import { viewFactories } from './views/index.js';
17
+ import { createViewRegistry } from './views/registry.js';
18
+ /** A stop signal that did not actually stop this process (orphaned group) resumes after this delay. */
19
+ const SUSPEND_GRACE_MS = 300;
20
+ /**
21
+ * Creates the session before the proxy binds, without importing the project graph.
22
+ * Throws for an invalid `HISTOIRE_TUI` so the command fails before any evaluation.
23
+ * @param options Session inputs.
24
+ */
25
+ export function createTerminalSession(options) {
26
+ const stdin = options.stdin ?? process.stdin;
27
+ const stdout = options.stdout ?? process.stdout;
28
+ const environment = options.environment ?? process.env;
29
+ const decide = () => decideTerminalMode({ flag: options.flag, env: environment.HISTOIRE_TUI, stdin, stdout, environment, execArgv: options.execArgv ?? process.execArgv, inspectorUrl: inspectorUrl() });
30
+ const initial = decide();
31
+ const explicit = options.flag === true || environment.HISTOIRE_TUI === '1';
32
+ // Without any chance of an interactive panel there is nothing to watch or reclaim.
33
+ const interactive = stdin.isTTY === true && stdout.isTTY === true && options.flag !== false && environment.HISTOIRE_TUI !== 'plain';
34
+ /** `released` is the short window where a stopped process leaves the terminal to the shell. */
35
+ let active;
36
+ let host;
37
+ /** Settles with the host once bound, so a shutdown requested during startup still closes it. */
38
+ let hostBound;
39
+ const hostReady = new Promise(resolve => (hostBound = resolve));
40
+ let publicUrl;
41
+ let workbenchUrl;
42
+ let rendererFailed = false;
43
+ let suspended = false;
44
+ let closed = false;
45
+ let openView;
46
+ let tick;
47
+ let announced;
48
+ const segments = new Set();
49
+ const url = () => workbenchUrl ?? publicUrl;
50
+ const plainLine = (text) => void stdout.write(`${text}\n`);
51
+ const feedback = createFeedback(() => surface.repaint());
52
+ /** Single feedback channel: transient panel line in the TUI, a printed line otherwise. */
53
+ function report(text) {
54
+ if (active === 'tui')
55
+ feedback.show(text);
56
+ else
57
+ plainLine(text);
58
+ }
59
+ /** The proxy exists once a user can act; an earlier key is reported, not thrown. */
60
+ function requireHost() {
61
+ if (!host)
62
+ throw new Error('Histoire is still starting');
63
+ return host;
64
+ }
65
+ const tests = createSessionTests(options, { report, plain: () => session.mode !== 'tui' });
66
+ const actions = {
67
+ tests,
68
+ restart: request => requireHost().restart({ cause: 'manual', fresh: request.fresh }),
69
+ openBrowser: async () => requireHost().openBrowser(url()),
70
+ url,
71
+ copy: options.clipboard ?? unavailableClipboard,
72
+ clearScreen: () => surface.clear(),
73
+ quit: () => void session.shutdown().catch((error) => {
74
+ console.error(error);
75
+ process.exitCode = 1;
76
+ }),
77
+ report,
78
+ };
79
+ const viewHost = {
80
+ bridge: options.bridge,
81
+ logs: options.logs,
82
+ requests: options.requests ?? createRequestHistory(),
83
+ progress: options.progress,
84
+ url,
85
+ size: () => ({ columns: stdout.columns ?? 80, rows: stdout.rows ?? 24 }),
86
+ notify: report,
87
+ requestRender: () => surface.repaint(),
88
+ close: () => closeView(),
89
+ openView(shortcut) {
90
+ const view = registry.byShortcut(shortcut);
91
+ if (view)
92
+ openScreen(view);
93
+ },
94
+ tests,
95
+ copy: actions.copy,
96
+ ...createHostExtras(options, () => publicUrl),
97
+ openBrowser: async (path = '/') => requireHost().openBrowser(new URL(path, workbenchUrl ?? publicUrl).href),
98
+ shortcuts: () => registry.summary(),
99
+ addPanelSegment(provider) {
100
+ segments.add(provider);
101
+ surface.repaint();
102
+ return () => void segments.delete(provider);
103
+ },
104
+ };
105
+ /** Open view lines; feedback replaces the footer row. */
106
+ function screenLines() {
107
+ if (!openView?.render)
108
+ return undefined;
109
+ const lines = openView.render(viewHost.size());
110
+ const message = feedback.text();
111
+ if (message && lines.length)
112
+ lines[lines.length - 1] = message;
113
+ return lines;
114
+ }
115
+ const surface = createSurface({
116
+ stdout,
117
+ content: {
118
+ screen: screenLines,
119
+ panel: () => renderPanel(buildPanelModel({ version: options.version, columns: stdout.columns ?? 80, snapshot: options.progress.snapshot(), url: url(), segments, feedback: feedback.text(), views: registry.list() })),
120
+ },
121
+ onFailure(error) {
122
+ rendererFailed = true;
123
+ plainLine(`Terminal rendering failed (${error instanceof Error ? error.message : String(error)}). Using plain output`);
124
+ applyMode();
125
+ },
126
+ });
127
+ // Created after the surface: view factories may contribute panel segments, which repaint it.
128
+ const registry = createViewRegistry(viewHost, options.viewFactories ?? viewFactories);
129
+ /** Gives a view the screen; an open view (stories handing over to tests) leaves first. */
130
+ function openScreen(view) {
131
+ openView?.leave?.();
132
+ openView = view;
133
+ view.enter?.();
134
+ surface.repaint();
135
+ }
136
+ /** Returns to the main screen. */
137
+ function closeView() {
138
+ const view = openView;
139
+ openView = undefined;
140
+ view?.leave?.();
141
+ surface.repaint();
142
+ }
143
+ const keys = createKeyInput({
144
+ stdin,
145
+ onKey: (key) => {
146
+ if (closed)
147
+ return;
148
+ try {
149
+ dispatchKey({ actions, registry, activeView: () => openView, openView: openScreen, closeView, suspend }, key);
150
+ // A handled key may have moved selection or scroll; screens do not repaint themselves.
151
+ if (openView)
152
+ surface.repaint();
153
+ }
154
+ catch (error) {
155
+ report(`Failed: ${error instanceof Error ? error.message : String(error)}`);
156
+ }
157
+ },
158
+ });
159
+ const plainInput = createPlainInput({ stdin, onLine: line => void (closed || runPlainCommand(actions, line)) });
160
+ /** Releases view, raw input and panel; every step runs even if an earlier one failed. */
161
+ function leaveTui() {
162
+ clearInterval(tick);
163
+ tick = undefined;
164
+ feedback.dispose();
165
+ const view = openView;
166
+ openView = undefined;
167
+ for (const step of [() => view?.leave?.(), () => keys.detach(), () => surface.detach()]) {
168
+ try {
169
+ step();
170
+ }
171
+ catch { }
172
+ }
173
+ }
174
+ /** Brings the screen in line with policy; the only place that switches modes. */
175
+ function applyMode() {
176
+ if (closed)
177
+ return;
178
+ const wanted = suspended ? 'released' : rendererFailed ? 'plain' : decide().mode;
179
+ if (wanted === active)
180
+ return;
181
+ const was = active;
182
+ if (was === 'tui')
183
+ leaveTui();
184
+ if (was === 'plain')
185
+ plainInput.detach();
186
+ active = wanted;
187
+ if (wanted === 'tui') {
188
+ keys.attach();
189
+ surface.attach();
190
+ // A render failure during attach already switched to plain.
191
+ if (active !== 'tui')
192
+ return;
193
+ tick = setInterval(() => surface.repaint(), 1000);
194
+ tick.unref();
195
+ }
196
+ else if (wanted === 'plain') {
197
+ if (stdin.isTTY)
198
+ plainInput.attach();
199
+ if (was === 'tui' && !rendererFailed)
200
+ plainLine('Terminal too small for the interactive panel, using plain output');
201
+ }
202
+ }
203
+ /** Leaves the terminal in shell state and stops the process group like a terminal driver would, so `pnpm`/`npx` wrappers stop too (Unix job control). */
204
+ function suspend() {
205
+ if (process.platform === 'win32' || suspended)
206
+ return;
207
+ suspended = true;
208
+ applyMode();
209
+ // In an orphaned process group the stop signal is ignored; resume ourselves then.
210
+ setTimeout(resume, SUSPEND_GRACE_MS).unref();
211
+ (options.suspendProcess ?? (() => process.kill(0, 'SIGTSTP')))();
212
+ }
213
+ /** Re-detects the terminal after a stop; idempotent. */
214
+ function resume() {
215
+ if (!suspended)
216
+ return;
217
+ suspended = false;
218
+ applyMode();
219
+ }
220
+ const onResize = () => {
221
+ applyMode();
222
+ if (active === 'tui')
223
+ surface.repaint();
224
+ };
225
+ if (interactive) {
226
+ stdout.on('resize', onResize);
227
+ process.on('SIGCONT', resume);
228
+ }
229
+ const stopProgress = options.progress.subscribe((snapshot) => {
230
+ if (active === 'tui')
231
+ return surface.repaint();
232
+ // Plain mode: one real line per readiness or failure, never per tick.
233
+ const marker = snapshot.failed ? `failed:${snapshot.generation}:${snapshot.failed.phase}` : snapshot.status === 'ready' && snapshot.readyAfterMs !== undefined ? `ready:${snapshot.generation}` : undefined;
234
+ if (marker && marker !== announced) {
235
+ announced = marker;
236
+ plainLine(` ${describeProgress(snapshot)}`);
237
+ }
238
+ });
239
+ /** Idempotent restoration of everything the session owns. */
240
+ function release() {
241
+ closed = true;
242
+ stopProgress();
243
+ stdout.off('resize', onResize);
244
+ process.off('SIGCONT', resume);
245
+ if (active === 'tui')
246
+ leaveTui();
247
+ plainInput.detach();
248
+ active = undefined;
249
+ }
250
+ const shutdown = createShutdown({ release, close: () => host ? host.close() : hostReady.then(bound => bound.close()) });
251
+ const session = {
252
+ passthrough: {
253
+ stdout: { write: data => active === 'tui' ? surface.write('stdout', data) : stdout.write(data) },
254
+ stderr: { write: data => active === 'tui' ? surface.write('stderr', data) : process.stderr.write(data) },
255
+ },
256
+ line: text => active === 'tui' ? surface.write('stdout', `${text}\n`) : plainLine(text),
257
+ onListening(address) {
258
+ publicUrl = address;
259
+ surface.repaint();
260
+ },
261
+ onReady(base) {
262
+ if (publicUrl)
263
+ workbenchUrl = new URL(base, publicUrl).href;
264
+ surface.repaint();
265
+ },
266
+ bind(bound) {
267
+ host = bound;
268
+ hostBound(bound);
269
+ },
270
+ release,
271
+ shutdown,
272
+ get mode() {
273
+ return active === 'tui' ? 'tui' : 'plain';
274
+ },
275
+ registry,
276
+ };
277
+ // Initial activation. An explicit request that cannot be honored is said once.
278
+ applyMode();
279
+ if (explicit && initial.mode === 'plain' && initial.reason)
280
+ plainLine(`Interactive terminal unavailable (${initial.reason}), using plain output`);
281
+ return session;
282
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Builds the idempotent shutdown sequence of a terminal session.
3
+ * Terminal state is released before the runtime is awaited, so restoring the shell never waits on a child.
4
+ * Every step runs even when an earlier one failed; failures are rethrown once all steps finished.
5
+ * @param steps Release of terminal-owned state, and close of the bound runtime if any.
6
+ * @param steps.release Restores raw input, panel and listeners synchronously.
7
+ * @param steps.close Closes the runtime host; waits for the host when none is bound yet (shutdown requested during startup).
8
+ */
9
+ export declare function createShutdown(steps: {
10
+ release: () => void;
11
+ close: () => Promise<void> | undefined;
12
+ }): () => Promise<void>;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Builds the idempotent shutdown sequence of a terminal session.
3
+ * Terminal state is released before the runtime is awaited, so restoring the shell never waits on a child.
4
+ * Every step runs even when an earlier one failed; failures are rethrown once all steps finished.
5
+ * @param steps Release of terminal-owned state, and close of the bound runtime if any.
6
+ * @param steps.release Restores raw input, panel and listeners synchronously.
7
+ * @param steps.close Closes the runtime host; waits for the host when none is bound yet (shutdown requested during startup).
8
+ */
9
+ export function createShutdown(steps) {
10
+ let closing;
11
+ return () => closing ??= (async () => {
12
+ const failures = [];
13
+ try {
14
+ steps.release();
15
+ }
16
+ catch (error) {
17
+ failures.push(error);
18
+ }
19
+ try {
20
+ await steps.close();
21
+ }
22
+ catch (error) {
23
+ failures.push(error);
24
+ }
25
+ if (failures.length === 1)
26
+ throw failures[0];
27
+ if (failures.length)
28
+ throw new AggregateError(failures, 'Shutdown failed');
29
+ })();
30
+ }
@@ -0,0 +1,26 @@
1
+ import type { TerminalBridge } from '../bridge.js';
2
+ import type { CatalogListArgs, CatalogListPage, CatalogVariantsArgs, CatalogVariantsPage } from '../protocol/catalog.js';
3
+ /** Typed wrappers of the `catalog.*` operations over the generic bridge. */
4
+ export interface CatalogClient {
5
+ /** Reads one page of matching stories. */
6
+ list: (args: CatalogListArgs) => Promise<CatalogListPage>;
7
+ /** Reads one page of a story's variants. */
8
+ variants: (args: CatalogVariantsArgs) => Promise<CatalogVariantsPage>;
9
+ }
10
+ /**
11
+ * Creates the typed client. Pure sugar over `bridge.send`; holds no state.
12
+ * @param bridge Parent bridge (or any object with a compatible `send`).
13
+ */
14
+ export declare function createCatalogClient(bridge: Pick<TerminalBridge, 'send'>): CatalogClient;
15
+ /**
16
+ * Whether a failed read says its expected revision is no longer current. The read must then
17
+ * restart from the first page; pages of two revisions are never combined.
18
+ * @param error Rejection of a catalog read.
19
+ */
20
+ export declare function isStaleCatalogRead(error: unknown): boolean;
21
+ /**
22
+ * Whether a failed read belongs to a generation that no longer exists. Nothing is shown for
23
+ * it: the progress mirror already moved on and the successor generation is read afresh.
24
+ * @param error Rejection of a catalog read.
25
+ */
26
+ export declare function isRetiredCatalogRead(error: unknown): boolean;