@hop-top/kit 0.4.0-alpha.1

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 (174) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/LICENSE +25 -0
  3. package/README.md +189 -0
  4. package/dist/aim.d.ts +116 -0
  5. package/dist/aim.js +417 -0
  6. package/dist/alias.d.ts +73 -0
  7. package/dist/alias.js +207 -0
  8. package/dist/api.d.ts +62 -0
  9. package/dist/api.js +165 -0
  10. package/dist/auth.d.ts +26 -0
  11. package/dist/auth.js +41 -0
  12. package/dist/cli.d.ts +309 -0
  13. package/dist/cli.js +885 -0
  14. package/dist/config.d.ts +97 -0
  15. package/dist/config.js +79 -0
  16. package/dist/errcorrect.d.ts +37 -0
  17. package/dist/errcorrect.js +69 -0
  18. package/dist/llm.d.ts +188 -0
  19. package/dist/llm.js +356 -0
  20. package/dist/output.d.ts +213 -0
  21. package/dist/output.js +447 -0
  22. package/dist/progress.d.ts +30 -0
  23. package/dist/progress.js +56 -0
  24. package/dist/provenance.d.ts +24 -0
  25. package/dist/provenance.js +32 -0
  26. package/dist/routellm.d.ts +64 -0
  27. package/dist/routellm.js +258 -0
  28. package/dist/rpc.d.ts +25 -0
  29. package/dist/rpc.js +101 -0
  30. package/dist/safety.d.ts +24 -0
  31. package/dist/safety.js +44 -0
  32. package/dist/scope.d.ts +121 -0
  33. package/dist/scope.js +380 -0
  34. package/dist/sqlstore.d.ts +84 -0
  35. package/dist/sqlstore.js +85 -0
  36. package/dist/stream.d.ts +35 -0
  37. package/dist/stream.js +52 -0
  38. package/dist/tui/index.d.ts +300 -0
  39. package/dist/tui/index.js +332 -0
  40. package/dist/upgrade.d.ts +95 -0
  41. package/dist/upgrade.js +115 -0
  42. package/dist/xdg.d.ts +169 -0
  43. package/dist/xdg.js +129 -0
  44. package/eslint.config.mjs +17 -0
  45. package/package.json +133 -0
  46. package/src/README.md +3 -0
  47. package/src/aim.test.ts +331 -0
  48. package/src/aim.ts +388 -0
  49. package/src/alias.test.ts +423 -0
  50. package/src/alias.ts +256 -0
  51. package/src/api.test.ts +190 -0
  52. package/src/api.ts +214 -0
  53. package/src/auth.test.ts +24 -0
  54. package/src/auth.ts +37 -0
  55. package/src/bus.test.ts +178 -0
  56. package/src/bus.ts +114 -0
  57. package/src/cli.test.ts +690 -0
  58. package/src/cli.ts +741 -0
  59. package/src/completion-values.test.ts +202 -0
  60. package/src/completion-values.ts +173 -0
  61. package/src/completion.test.ts +212 -0
  62. package/src/completion.ts +158 -0
  63. package/src/compliance.test.ts +134 -0
  64. package/src/compliance.ts +669 -0
  65. package/src/config.test.ts +110 -0
  66. package/src/config.ts +164 -0
  67. package/src/errcorrect.test.ts +134 -0
  68. package/src/errcorrect.ts +84 -0
  69. package/src/flagregister.test.ts +103 -0
  70. package/src/flagregister.ts +78 -0
  71. package/src/gen/crud_connect.ts +76 -0
  72. package/src/gen/crud_pb.ts +269 -0
  73. package/src/hint.test.ts +315 -0
  74. package/src/hint.ts +178 -0
  75. package/src/llm.test.ts +612 -0
  76. package/src/llm.ts +577 -0
  77. package/src/log.test.ts +145 -0
  78. package/src/log.ts +155 -0
  79. package/src/output/builtins.ts +34 -0
  80. package/src/output/dispatch.ts +195 -0
  81. package/src/output/flags.ts +151 -0
  82. package/src/output/format_help.ts +80 -0
  83. package/src/output/formatter.ts +167 -0
  84. package/src/output/formatters/csv.ts +72 -0
  85. package/src/output/formatters/json.ts +44 -0
  86. package/src/output/formatters/table.ts +44 -0
  87. package/src/output/formatters/text.ts +109 -0
  88. package/src/output/formatters/yaml.ts +47 -0
  89. package/src/output/projection.ts +126 -0
  90. package/src/output/registry.ts +88 -0
  91. package/src/output/template.ts +63 -0
  92. package/src/output.test.ts +117 -0
  93. package/src/output.ts +90 -0
  94. package/src/progress.test.ts +93 -0
  95. package/src/progress.ts +58 -0
  96. package/src/provenance.test.ts +59 -0
  97. package/src/provenance.ts +26 -0
  98. package/src/routellm.test.ts +179 -0
  99. package/src/routellm.ts +365 -0
  100. package/src/router/bert.test.ts +180 -0
  101. package/src/router/bert.ts +145 -0
  102. package/src/router/controller.test.ts +183 -0
  103. package/src/router/controller.ts +165 -0
  104. package/src/router/integration.test.ts +309 -0
  105. package/src/router/intent.test.ts +187 -0
  106. package/src/router/intent.ts +208 -0
  107. package/src/router/mf.test.ts +66 -0
  108. package/src/router/mf.ts +52 -0
  109. package/src/router/random.test.ts +23 -0
  110. package/src/router/random.ts +13 -0
  111. package/src/router/router.test.ts +31 -0
  112. package/src/router/router.ts +62 -0
  113. package/src/router/server.test.ts +193 -0
  114. package/src/router/server.ts +134 -0
  115. package/src/router/sw.test.ts +199 -0
  116. package/src/router/sw.ts +232 -0
  117. package/src/rpc.test.ts +47 -0
  118. package/src/rpc.ts +91 -0
  119. package/src/safety.test.ts +53 -0
  120. package/src/safety.ts +42 -0
  121. package/src/scope-defaults.json +72 -0
  122. package/src/scope.test.ts +177 -0
  123. package/src/scope.ts +382 -0
  124. package/src/setflag.test.ts +110 -0
  125. package/src/setflag.ts +102 -0
  126. package/src/sqlstore.test.ts +110 -0
  127. package/src/sqlstore.ts +144 -0
  128. package/src/stream.test.ts +69 -0
  129. package/src/stream.ts +47 -0
  130. package/src/textflag.test.ts +105 -0
  131. package/src/textflag.ts +68 -0
  132. package/src/toolspec.test.ts +187 -0
  133. package/src/toolspec.ts +279 -0
  134. package/src/triton/client.test.ts +205 -0
  135. package/src/triton/client.ts +261 -0
  136. package/src/tui/anim.test.ts +146 -0
  137. package/src/tui/anim.ts +134 -0
  138. package/src/tui/badge.test.ts +41 -0
  139. package/src/tui/badge.ts +55 -0
  140. package/src/tui/confirm.test.ts +68 -0
  141. package/src/tui/confirm.ts +49 -0
  142. package/src/tui/index.ts +29 -0
  143. package/src/tui/list.test.ts +84 -0
  144. package/src/tui/list.ts +72 -0
  145. package/src/tui/parity.ts +41 -0
  146. package/src/tui/pills.test.ts +40 -0
  147. package/src/tui/pills.ts +43 -0
  148. package/src/tui/progress.test.ts +164 -0
  149. package/src/tui/progress.ts +120 -0
  150. package/src/tui/spinner.test.ts +111 -0
  151. package/src/tui/spinner.ts +96 -0
  152. package/src/tui/status.test.ts +68 -0
  153. package/src/tui/status.ts +66 -0
  154. package/src/upgrade.test.ts +298 -0
  155. package/src/upgrade.ts +205 -0
  156. package/src/uri.ts +199 -0
  157. package/src/wizard.test.ts +441 -0
  158. package/src/wizard.ts +662 -0
  159. package/src/xdg.test.ts +202 -0
  160. package/src/xdg.ts +280 -0
  161. package/test/output/cols.test.ts +148 -0
  162. package/test/output/csv.test.ts +129 -0
  163. package/test/output/dispatch.test.ts +194 -0
  164. package/test/output/format_help.test.ts +131 -0
  165. package/test/output/formatter.test.ts +137 -0
  166. package/test/output/output_flag.test.ts +124 -0
  167. package/test/output/registry.test.ts +127 -0
  168. package/test/output/smoke-capture.ts +83 -0
  169. package/test/output/smoke.test.ts +142 -0
  170. package/test/output/template.test.ts +95 -0
  171. package/test/output/text.test.ts +75 -0
  172. package/test/testdata/api-fixture.json +115 -0
  173. package/test/testdata/query-vectors.json +187 -0
  174. package/tsconfig.json +12 -0
@@ -0,0 +1,261 @@
1
+ /**
2
+ * Triton Inference Server HTTP+JSON client.
3
+ *
4
+ * Implements the KServe v2 inference protocol over HTTP for calling
5
+ * Triton-hosted models. Supports triton:// URI scheme parsing.
6
+ *
7
+ * @see https://kserve.github.io/website/modelserving/inference_api/
8
+ */
9
+
10
+ // ─── Types ───────────────────────────────────────────────────────────────────
11
+
12
+ /** KServe v2 tensor data types used in requests/responses. */
13
+ export type TritonDataType =
14
+ | "BOOL"
15
+ | "UINT8"
16
+ | "UINT16"
17
+ | "UINT32"
18
+ | "UINT64"
19
+ | "INT8"
20
+ | "INT16"
21
+ | "INT32"
22
+ | "INT64"
23
+ | "FP16"
24
+ | "FP32"
25
+ | "FP64"
26
+ | "BYTES";
27
+
28
+ /** A single input tensor for an inference request. */
29
+ export interface InferInput {
30
+ name: string;
31
+ shape: number[];
32
+ datatype: TritonDataType;
33
+ data: number[] | string[] | boolean[];
34
+ }
35
+
36
+ /** A requested output tensor. */
37
+ export interface InferRequestedOutput {
38
+ name: string;
39
+ }
40
+
41
+ /** KServe v2 inference request body. */
42
+ export interface InferRequest {
43
+ inputs: InferInput[];
44
+ outputs?: InferRequestedOutput[];
45
+ }
46
+
47
+ /** A single output tensor in an inference response. */
48
+ export interface InferOutputTensor {
49
+ name: string;
50
+ shape: number[];
51
+ datatype: TritonDataType;
52
+ data: number[] | string[] | boolean[];
53
+ }
54
+
55
+ /** KServe v2 inference response body. */
56
+ export interface InferResponse {
57
+ model_name: string;
58
+ model_version?: string;
59
+ id?: string;
60
+ outputs: InferOutputTensor[];
61
+ }
62
+
63
+ /** Health status from Triton server. */
64
+ export interface ServerHealth {
65
+ live: boolean;
66
+ ready: boolean;
67
+ }
68
+
69
+ /** Parsed triton:// URI. */
70
+ export interface TritonURI {
71
+ host: string;
72
+ port: number;
73
+ modelName: string;
74
+ modelVersion?: string;
75
+ }
76
+
77
+ // ─── Errors ──────────────────────────────────────────────────────────────────
78
+
79
+ export class TritonError extends Error {
80
+ readonly statusCode?: number;
81
+
82
+ constructor(message: string, statusCode?: number) {
83
+ super(message);
84
+ this.name = "TritonError";
85
+ this.statusCode = statusCode;
86
+ }
87
+ }
88
+
89
+ // ─── URI parsing ─────────────────────────────────────────────────────────────
90
+
91
+ /**
92
+ * Parse a triton:// URI.
93
+ *
94
+ * Format: triton://host:port/model_name[/version]
95
+ *
96
+ * Examples:
97
+ * triton://localhost:8000/my_model
98
+ * triton://gpu-server:8000/bert/1
99
+ */
100
+ export function parseTritonURI(uri: string): TritonURI {
101
+ if (!uri.startsWith("triton://")) {
102
+ throw new TritonError(
103
+ `Invalid Triton URI "${uri}": must start with triton://`,
104
+ );
105
+ }
106
+
107
+ const rest = uri.slice("triton://".length);
108
+ const slashIdx = rest.indexOf("/");
109
+ if (slashIdx < 0) {
110
+ throw new TritonError(
111
+ `Invalid Triton URI "${uri}": missing model name`,
112
+ );
113
+ }
114
+
115
+ const hostPort = rest.slice(0, slashIdx);
116
+ const path = rest.slice(slashIdx + 1);
117
+
118
+ const colonIdx = hostPort.lastIndexOf(":");
119
+ if (colonIdx < 0) {
120
+ throw new TritonError(
121
+ `Invalid Triton URI "${uri}": missing port`,
122
+ );
123
+ }
124
+
125
+ const host = hostPort.slice(0, colonIdx);
126
+ if (!host) {
127
+ throw new TritonError(`Invalid Triton URI "${uri}": missing host`);
128
+ }
129
+ const port = Number(hostPort.slice(colonIdx + 1));
130
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
131
+ throw new TritonError(
132
+ `Invalid Triton URI "${uri}": invalid port`,
133
+ );
134
+ }
135
+
136
+ const parts = path.split("/").filter(Boolean);
137
+ if (parts.length === 0) {
138
+ throw new TritonError(
139
+ `Invalid Triton URI "${uri}": missing model name`,
140
+ );
141
+ }
142
+
143
+ return {
144
+ host,
145
+ port,
146
+ modelName: parts[0],
147
+ modelVersion: parts.length > 1 ? parts[1] : undefined,
148
+ };
149
+ }
150
+
151
+ // ─── TritonScorer interface ──────────────────────────────────────────────────
152
+
153
+ /** Simplified interface for routers that just need a single score. */
154
+ export interface TritonScorer {
155
+ score(input: Float32Array): Promise<number>;
156
+ }
157
+
158
+ // ─── Client ──────────────────────────────────────────────────────────────────
159
+
160
+ export class TritonClient implements TritonScorer {
161
+ readonly baseUrl: string;
162
+ readonly modelName: string;
163
+ readonly modelVersion?: string;
164
+
165
+ constructor(baseUrl: string, modelName: string, version?: string) {
166
+ this.baseUrl = baseUrl.replace(/\/+$/, "");
167
+ this.modelName = modelName;
168
+ this.modelVersion = version;
169
+ }
170
+
171
+ /**
172
+ * Create a TritonClient from a triton:// URI.
173
+ */
174
+ static fromURI(uri: string): TritonClient {
175
+ const parsed = parseTritonURI(uri);
176
+ const baseUrl = `http://${parsed.host}:${parsed.port}`;
177
+ return new TritonClient(baseUrl, parsed.modelName, parsed.modelVersion);
178
+ }
179
+
180
+ /**
181
+ * Send an inference request to Triton.
182
+ */
183
+ async infer(request: InferRequest): Promise<InferResponse> {
184
+ const versionPath = this.modelVersion
185
+ ? `/versions/${this.modelVersion}`
186
+ : "";
187
+ const url =
188
+ `${this.baseUrl}/v2/models/${this.modelName}` +
189
+ `${versionPath}/infer`;
190
+
191
+ const resp = await fetch(url, {
192
+ method: "POST",
193
+ headers: { "Content-Type": "application/json" },
194
+ body: JSON.stringify(request),
195
+ });
196
+
197
+ if (!resp.ok) {
198
+ const text = await resp.text().catch(() => "");
199
+ throw new TritonError(
200
+ `Triton inference failed: HTTP ${resp.status} — ${text}`,
201
+ resp.status,
202
+ );
203
+ }
204
+
205
+ return (await resp.json()) as InferResponse;
206
+ }
207
+
208
+ /**
209
+ * Simplified score: send a single FP32 input array, return the
210
+ * first value of the first output tensor.
211
+ */
212
+ async score(input: Float32Array): Promise<number> {
213
+ const request: InferRequest = {
214
+ inputs: [
215
+ {
216
+ name: "input",
217
+ shape: [1, input.length],
218
+ datatype: "FP32",
219
+ data: Array.from(input),
220
+ },
221
+ ],
222
+ };
223
+
224
+ const response = await this.infer(request);
225
+ const output = response.outputs[0];
226
+ if (!output || !output.data.length) {
227
+ throw new TritonError("Triton response has no output data");
228
+ }
229
+
230
+ return output.data[0] as number;
231
+ }
232
+
233
+ /**
234
+ * Check server health (liveness + readiness).
235
+ */
236
+ async health(): Promise<ServerHealth> {
237
+ const [liveResp, readyResp] = await Promise.all([
238
+ fetch(`${this.baseUrl}/v2/health/live`).catch(() => null),
239
+ fetch(`${this.baseUrl}/v2/health/ready`).catch(() => null),
240
+ ]);
241
+
242
+ return {
243
+ live: liveResp?.ok ?? false,
244
+ ready: readyResp?.ok ?? false,
245
+ };
246
+ }
247
+
248
+ /**
249
+ * Check if a specific model is ready.
250
+ */
251
+ async modelReady(): Promise<boolean> {
252
+ const url =
253
+ `${this.baseUrl}/v2/models/${this.modelName}/ready`;
254
+ try {
255
+ const resp = await fetch(url);
256
+ return resp.ok;
257
+ } catch {
258
+ return false;
259
+ }
260
+ }
261
+ }
@@ -0,0 +1,146 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+ import { buildTheme } from '../cli.js';
3
+ import { anim, makeGradient } from './anim.js';
4
+
5
+ function captureStderr(): { output: string[]; restore: () => void } {
6
+ const output: string[] = [];
7
+ vi.spyOn(process.stderr, 'write').mockImplementation((chunk: unknown) => {
8
+ output.push(String(chunk));
9
+ return true;
10
+ });
11
+ return { output, restore: () => vi.restoreAllMocks() };
12
+ }
13
+
14
+ describe('makeGradient()', () => {
15
+ it('returns empty array for 0 steps', () => {
16
+ expect(makeGradient('#000000', '#FFFFFF', 0)).toEqual([]);
17
+ });
18
+
19
+ it('returns single color for 1 step (start color)', () => {
20
+ const g = makeGradient('#FF0000', '#0000FF', 1);
21
+ expect(g).toHaveLength(1);
22
+ expect(g[0]).toEqual([255, 0, 0]);
23
+ });
24
+
25
+ it('returns correct start and end colors for 2 steps', () => {
26
+ const g = makeGradient('#FF0000', '#0000FF', 2);
27
+ expect(g).toHaveLength(2);
28
+ expect(g[0]).toEqual([255, 0, 0]);
29
+ expect(g[1]).toEqual([0, 0, 255]);
30
+ });
31
+
32
+ it('returns length matching steps', () => {
33
+ const g = makeGradient('#000000', '#FFFFFF', 10);
34
+ expect(g).toHaveLength(10);
35
+ });
36
+
37
+ it('interpolates midpoint approximately', () => {
38
+ const g = makeGradient('#000000', '#FFFFFF', 3);
39
+ // midpoint should be ~128
40
+ expect(g[1][0]).toBeGreaterThan(120);
41
+ expect(g[1][0]).toBeLessThan(136);
42
+ });
43
+ });
44
+
45
+ describe('anim()', () => {
46
+ const theme = buildTheme();
47
+
48
+ beforeEach(() => vi.useFakeTimers());
49
+ afterEach(() => {
50
+ vi.useRealTimers();
51
+ vi.restoreAllMocks();
52
+ });
53
+
54
+ it('start() writes initial frame to stderr', () => {
55
+ const { output, restore } = captureStderr();
56
+ const a = anim(theme);
57
+ a.start();
58
+ expect(output.length).toBeGreaterThan(0);
59
+ expect(output[0]).toContain('\r');
60
+ a.stop();
61
+ restore();
62
+ });
63
+
64
+ it('start() includes ANSI color codes', () => {
65
+ const { output, restore } = captureStderr();
66
+ const a = anim(theme);
67
+ a.start();
68
+ expect(output[0]).toContain('\x1b[38;2;');
69
+ a.stop();
70
+ restore();
71
+ });
72
+
73
+ it('renders on each interval tick', () => {
74
+ const { output, restore } = captureStderr();
75
+ const a = anim(theme);
76
+ a.start();
77
+ const before = output.length;
78
+ vi.advanceTimersByTime(100 * 3);
79
+ expect(output.length).toBeGreaterThan(before);
80
+ a.stop();
81
+ restore();
82
+ });
83
+
84
+ it('stop() clears line', () => {
85
+ const { output, restore } = captureStderr();
86
+ const a = anim(theme);
87
+ a.start();
88
+ output.length = 0;
89
+ a.stop();
90
+ expect(output.join('')).toContain('\r');
91
+ restore();
92
+ });
93
+
94
+ it('stop() halts interval — no renders after stop', () => {
95
+ const { output, restore } = captureStderr();
96
+ const a = anim(theme);
97
+ a.start();
98
+ a.stop();
99
+ const countAfter = output.length;
100
+ vi.advanceTimersByTime(500);
101
+ expect(output.length).toBe(countAfter);
102
+ restore();
103
+ });
104
+
105
+ it('setLabel() updates label in subsequent renders', () => {
106
+ const { output, restore } = captureStderr();
107
+ const a = anim(theme, { label: 'init' });
108
+ a.start();
109
+ a.setLabel('updated');
110
+ vi.advanceTimersByTime(100);
111
+ const joined = output.join('');
112
+ expect(joined).toContain('updated');
113
+ a.stop();
114
+ restore();
115
+ });
116
+
117
+ it('respects custom width option', () => {
118
+ const { output, restore } = captureStderr();
119
+ const a = anim(theme, { width: 5 });
120
+ a.start();
121
+ // 5 chars → 5 reset sequences in one frame
122
+ const resets = (output[0].match(/\x1b\[0m/g) ?? []).length;
123
+ expect(resets).toBe(5);
124
+ a.stop();
125
+ restore();
126
+ });
127
+
128
+ it('initial label appears in first render', () => {
129
+ const { output, restore } = captureStderr();
130
+ const a = anim(theme, { label: 'hello' });
131
+ a.start();
132
+ expect(output[0]).toContain('hello');
133
+ a.stop();
134
+ restore();
135
+ });
136
+
137
+ it('uses gradient colors from accent to secondary', () => {
138
+ const { output, restore } = captureStderr();
139
+ const a = anim(theme, { width: 1 });
140
+ a.start();
141
+ // accent #7ED957 → 38;2;126;217;87 (first/only gradient step for width=1)
142
+ expect(output[0]).toContain('38;2;126;217;87');
143
+ a.stop();
144
+ restore();
145
+ });
146
+ });
@@ -0,0 +1,134 @@
1
+ /**
2
+ * @module tui/anim
3
+ * @package @hop-top/kit
4
+ *
5
+ * Gradient animation component — cycling character scramble.
6
+ * Mirrors Go's Anim from hop.top/kit/tui — pure ANSI, no bubbletea dep.
7
+ *
8
+ * Cycles random chars through a gradient from theme.accent → theme.secondary
9
+ * at ~100ms per frame. Uses \r to overwrite the current line.
10
+ */
11
+
12
+ import type { Theme } from '../cli.js';
13
+ import { parity } from './parity.js';
14
+
15
+ const ANIM_RUNES = parity.anim.runes;
16
+ const DEFAULT_WIDTH = parity.anim.default_width;
17
+ const INTERVAL_MS = parity.anim.interval_ms;
18
+
19
+ export interface AnimOpts {
20
+ /** Number of animated characters (default: 10). */
21
+ width?: number;
22
+ /** Optional label rendered after the animation. */
23
+ label?: string;
24
+ }
25
+
26
+ export interface Anim {
27
+ /** Start the animation loop. */
28
+ start(): void;
29
+ /** Stop the animation loop and clear the line. */
30
+ stop(): void;
31
+ /** Update the label shown after the animated chars. */
32
+ setLabel(label: string): void;
33
+ }
34
+
35
+ /**
36
+ * Creates a gradient-cycling character scramble animation.
37
+ *
38
+ * Colors cycle from theme.accent to theme.secondary across the width.
39
+ * Renders to stderr; uses \r to overwrite the current line each tick.
40
+ *
41
+ * @param theme - Active CLI theme.
42
+ * @param opts - Optional width and initial label.
43
+ * @returns Anim control object.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * import { buildTheme } from '@hop-top/kit/cli';
48
+ * import { anim } from '@hop-top/kit/tui';
49
+ * const a = anim(buildTheme(), { label: 'processing' });
50
+ * a.start();
51
+ * // await work
52
+ * a.stop();
53
+ * ```
54
+ */
55
+ export function anim(theme: Theme, opts?: AnimOpts): Anim {
56
+ const width = opts?.width ?? DEFAULT_WIDTH;
57
+ let label = opts?.label ?? '';
58
+
59
+ // Pre-compute gradient: accent → secondary across `width` steps.
60
+ const gradient = makeGradient(theme.accent, theme.secondary, width);
61
+ const reset = `\x1b[0m`;
62
+
63
+ let timer: ReturnType<typeof setInterval> | null = null;
64
+
65
+ function randomChar(): string {
66
+ return ANIM_RUNES[Math.floor(Math.random() * ANIM_RUNES.length)];
67
+ }
68
+
69
+ function render(): void {
70
+ let line = '\r';
71
+ for (let i = 0; i < width; i++) {
72
+ const [r, g, b] = gradient[i];
73
+ line += `\x1b[38;2;${r};${g};${b}m${randomChar()}${reset}`;
74
+ }
75
+ if (label) {
76
+ line += ' ' + label;
77
+ }
78
+ process.stderr.write(line);
79
+ }
80
+
81
+ return {
82
+ start(): void {
83
+ if (timer !== null) return;
84
+ render();
85
+ timer = setInterval(render, INTERVAL_MS);
86
+ },
87
+
88
+ stop(): void {
89
+ if (timer !== null) {
90
+ clearInterval(timer);
91
+ timer = null;
92
+ }
93
+ process.stderr.write('\r\x1b[K');
94
+ },
95
+
96
+ setLabel(newLabel: string): void {
97
+ label = newLabel;
98
+ },
99
+ };
100
+ }
101
+
102
+ // ---------------------------------------------------------------------------
103
+ // Helpers
104
+ // ---------------------------------------------------------------------------
105
+
106
+ /** Linear RGB blend from hexA → hexB across `steps` positions. */
107
+ export function makeGradient(
108
+ hexA: string,
109
+ hexB: string,
110
+ steps: number,
111
+ ): Array<[number, number, number]> {
112
+ if (steps <= 0) return [];
113
+ const [ar, ag, ab] = hexToRgb(hexA);
114
+ const [br, bg, bb] = hexToRgb(hexB);
115
+ const result: Array<[number, number, number]> = [];
116
+ for (let i = 0; i < steps; i++) {
117
+ const t = steps === 1 ? 0 : i / (steps - 1);
118
+ result.push([
119
+ Math.round(ar + (br - ar) * t),
120
+ Math.round(ag + (bg - ag) * t),
121
+ Math.round(ab + (bb - ab) * t),
122
+ ]);
123
+ }
124
+ return result;
125
+ }
126
+
127
+ function hexToRgb(hex: string): [number, number, number] {
128
+ const h = hex.replace('#', '');
129
+ return [
130
+ parseInt(h.slice(0, 2), 16),
131
+ parseInt(h.slice(2, 4), 16),
132
+ parseInt(h.slice(4, 6), 16),
133
+ ];
134
+ }
@@ -0,0 +1,41 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { buildTheme } from '../cli.js';
3
+ import { badge } from './badge.js';
4
+
5
+ const stripAnsi = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, '');
6
+
7
+ describe('badge()', () => {
8
+ const theme = buildTheme();
9
+
10
+ it('renders text with surrounding spaces (padding)', () => {
11
+ const out = stripAnsi(badge(theme, '^ UPDATE'));
12
+ expect(out).toBe(' ^ UPDATE ');
13
+ });
14
+
15
+ it('returns non-empty ANSI string', () => {
16
+ const out = badge(theme, 'v1.2.3');
17
+ expect(out).toContain('\x1b[');
18
+ });
19
+
20
+ it('uses theme.accent as default background color', () => {
21
+ const out = badge(theme, 'test');
22
+ // accent is #7ED957 → rgb(126,217,87) → 48;2;126;217;87
23
+ expect(out).toContain('48;2;126;217;87');
24
+ });
25
+
26
+ it('respects opts.color override', () => {
27
+ const out = badge(theme, 'test', { color: '#FF0000' });
28
+ // #FF0000 → rgb(255,0,0) → 48;2;255;0;0
29
+ expect(out).toContain('48;2;255;0;0');
30
+ });
31
+
32
+ it('uses white foreground for contrast', () => {
33
+ const out = badge(theme, 'test');
34
+ expect(out).toContain('38;2;255;255;255');
35
+ });
36
+
37
+ it('ends with reset sequence', () => {
38
+ const out = badge(theme, 'test');
39
+ expect(out).toMatch(/\x1b\[0m$/);
40
+ });
41
+ });
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @module tui/badge
3
+ * @package @hop-top/kit
4
+ *
5
+ * Renders a styled badge/pill string.
6
+ * Mirrors Go's badge concept from hop.top/kit/tui — pure string, no bubbletea dep.
7
+ */
8
+
9
+ import type { Theme } from '../cli.js';
10
+
11
+ export interface BadgeOpts {
12
+ /** Override background color (hex, e.g. "#FF0000"). Defaults to theme.accent. */
13
+ color?: string;
14
+ }
15
+
16
+ /**
17
+ * Renders a styled inline badge.
18
+ *
19
+ * Background defaults to `theme.accent`; text is rendered in white for contrast.
20
+ * Padding of one space is added on each side (mirrors lipgloss Padding(0, 1)).
21
+ *
22
+ * @param theme - Active CLI theme.
23
+ * @param text - Badge label text.
24
+ * @param opts - Optional overrides.
25
+ * @returns ANSI-styled badge string.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * import { buildTheme } from '@hop-top/kit/cli';
30
+ * import { badge } from '@hop-top/kit/tui';
31
+ * console.log(badge(buildTheme(), '^ UPDATE'));
32
+ * ```
33
+ */
34
+ export function badge(theme: Theme, text: string, opts?: BadgeOpts): string {
35
+ const bg = opts?.color ?? theme.accent;
36
+ const [r, g, b] = hexToRgb(bg);
37
+ // White text on colored background for contrast.
38
+ const bgOpen = `\x1b[48;2;${r};${g};${b}m`;
39
+ const fgOpen = `\x1b[38;2;255;255;255m`;
40
+ const reset = `\x1b[0m`;
41
+ return `${bgOpen}${fgOpen} ${text} ${reset}`;
42
+ }
43
+
44
+ // ---------------------------------------------------------------------------
45
+ // Helpers
46
+ // ---------------------------------------------------------------------------
47
+
48
+ function hexToRgb(hex: string): [number, number, number] {
49
+ const h = hex.replace('#', '');
50
+ return [
51
+ parseInt(h.slice(0, 2), 16),
52
+ parseInt(h.slice(2, 4), 16),
53
+ parseInt(h.slice(4, 6), 16),
54
+ ];
55
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * @module tui/confirm.test
3
+ * Tests for the confirm() interactive prompt wrapper.
4
+ */
5
+
6
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
7
+ import { buildTheme } from '../cli.js';
8
+
9
+ // Mock @clack/prompts before importing confirm.
10
+ vi.mock('@clack/prompts', () => ({
11
+ confirm: vi.fn(),
12
+ isCancel: vi.fn(),
13
+ }));
14
+
15
+ import * as clack from '@clack/prompts';
16
+ import { confirm } from './confirm.js';
17
+
18
+ const theme = buildTheme();
19
+
20
+ describe('confirm', () => {
21
+ beforeEach(() => {
22
+ vi.clearAllMocks();
23
+ });
24
+
25
+ it('returns true when clack confirm resolves true', async () => {
26
+ vi.mocked(clack.confirm).mockResolvedValue(true);
27
+ vi.mocked(clack.isCancel).mockReturnValue(false);
28
+
29
+ const result = await confirm(theme, 'Continue?');
30
+ expect(result).toBe(true);
31
+ });
32
+
33
+ it('returns false when clack confirm resolves false', async () => {
34
+ vi.mocked(clack.confirm).mockResolvedValue(false);
35
+ vi.mocked(clack.isCancel).mockReturnValue(false);
36
+
37
+ const result = await confirm(theme, 'Continue?');
38
+ expect(result).toBe(false);
39
+ });
40
+
41
+ it('throws Error("cancelled") when user cancels (Ctrl-C)', async () => {
42
+ const cancelSymbol = Symbol('cancel');
43
+ vi.mocked(clack.confirm).mockResolvedValue(cancelSymbol as unknown as boolean);
44
+ vi.mocked(clack.isCancel).mockReturnValue(true);
45
+
46
+ await expect(confirm(theme, 'Continue?')).rejects.toThrow('cancelled');
47
+ });
48
+
49
+ it('forwards message to clack confirm', async () => {
50
+ vi.mocked(clack.confirm).mockResolvedValue(true);
51
+ vi.mocked(clack.isCancel).mockReturnValue(false);
52
+
53
+ await confirm(theme, 'Deploy to prod?');
54
+ expect(clack.confirm).toHaveBeenCalledWith(
55
+ expect.objectContaining({ message: 'Deploy to prod?' }),
56
+ );
57
+ });
58
+
59
+ it('forwards initial option to clack confirm', async () => {
60
+ vi.mocked(clack.confirm).mockResolvedValue(false);
61
+ vi.mocked(clack.isCancel).mockReturnValue(false);
62
+
63
+ await confirm(theme, 'Overwrite?', { initial: false });
64
+ expect(clack.confirm).toHaveBeenCalledWith(
65
+ expect.objectContaining({ initialValue: false }),
66
+ );
67
+ });
68
+ });