stitchkit-tui 0.2.13 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +88 -4
  2. package/dist/App.d.ts +2 -2
  3. package/dist/App.d.ts.map +1 -1
  4. package/dist/app-mqzzrp1t.js +618 -0
  5. package/dist/cli.js +11 -2195
  6. package/dist/config.d.ts +8 -16
  7. package/dist/config.d.ts.map +1 -1
  8. package/dist/core/chart.d.ts +82 -0
  9. package/dist/core/chart.d.ts.map +1 -0
  10. package/dist/core/collection.d.ts.map +1 -1
  11. package/dist/core/command-palette.d.ts.map +1 -1
  12. package/dist/core/focus.d.ts +33 -0
  13. package/dist/core/focus.d.ts.map +1 -0
  14. package/dist/core/form.d.ts +88 -0
  15. package/dist/core/form.d.ts.map +1 -0
  16. package/dist/core/index.d.ts +17 -0
  17. package/dist/core/index.d.ts.map +1 -1
  18. package/dist/core/index.js +226 -358
  19. package/dist/core/json.d.ts +24 -0
  20. package/dist/core/json.d.ts.map +1 -0
  21. package/dist/core/key-hints.d.ts +28 -0
  22. package/dist/core/key-hints.d.ts.map +1 -0
  23. package/dist/core/keys.d.ts +32 -0
  24. package/dist/core/keys.d.ts.map +1 -0
  25. package/dist/core/labels.d.ts +44 -0
  26. package/dist/core/labels.d.ts.map +1 -0
  27. package/dist/core/list.d.ts +112 -0
  28. package/dist/core/list.d.ts.map +1 -0
  29. package/dist/core/meter.d.ts +61 -0
  30. package/dist/core/meter.d.ts.map +1 -0
  31. package/dist/core/navigation.d.ts +33 -0
  32. package/dist/core/navigation.d.ts.map +1 -0
  33. package/dist/core/notices.d.ts +39 -0
  34. package/dist/core/notices.d.ts.map +1 -0
  35. package/dist/core/progress.d.ts +53 -0
  36. package/dist/core/progress.d.ts.map +1 -0
  37. package/dist/core/search.d.ts +36 -0
  38. package/dist/core/search.d.ts.map +1 -0
  39. package/dist/core/table.d.ts +126 -0
  40. package/dist/core/table.d.ts.map +1 -0
  41. package/dist/core/tabs.d.ts +37 -0
  42. package/dist/core/tabs.d.ts.map +1 -0
  43. package/dist/core/text.d.ts +36 -0
  44. package/dist/core/text.d.ts.map +1 -0
  45. package/dist/core/theme.d.ts +38 -0
  46. package/dist/core/theme.d.ts.map +1 -0
  47. package/dist/gallery/app.d.ts +12 -0
  48. package/dist/gallery/app.d.ts.map +1 -0
  49. package/dist/gallery/catalogue.d.ts +11 -0
  50. package/dist/gallery/catalogue.d.ts.map +1 -0
  51. package/dist/gallery/main.d.ts +3 -0
  52. package/dist/gallery/main.d.ts.map +1 -0
  53. package/dist/gallery/main.js +16 -0
  54. package/dist/gallery/monitor-page.d.ts +8 -0
  55. package/dist/gallery/monitor-page.d.ts.map +1 -0
  56. package/dist/gallery/widgets-page.d.ts +7 -0
  57. package/dist/gallery/widgets-page.d.ts.map +1 -0
  58. package/dist/index-251fexwh.js +106 -0
  59. package/dist/index-54sqbm3r.js +1354 -0
  60. package/dist/index-ecpc5qkb.js +245 -0
  61. package/dist/index-fxx9ktw7.js +1603 -0
  62. package/dist/index-kz62sdr9.js +336 -0
  63. package/dist/index-z4c2ehg4.js +1705 -0
  64. package/dist/index.js +77 -2219
  65. package/dist/run-e1kdpzna.js +15 -0
  66. package/dist/run.d.ts.map +1 -1
  67. package/dist/status-line.d.ts +2 -2
  68. package/dist/status-line.d.ts.map +1 -1
  69. package/dist/transcript.d.ts +2 -1
  70. package/dist/transcript.d.ts.map +1 -1
  71. package/dist/widgets/chart.d.ts +32 -0
  72. package/dist/widgets/chart.d.ts.map +1 -0
  73. package/dist/widgets/context.d.ts +29 -0
  74. package/dist/widgets/context.d.ts.map +1 -0
  75. package/dist/widgets/feedback.d.ts +65 -0
  76. package/dist/widgets/feedback.d.ts.map +1 -0
  77. package/dist/widgets/form.d.ts +23 -0
  78. package/dist/widgets/form.d.ts.map +1 -0
  79. package/dist/widgets/index.d.ts +13 -0
  80. package/dist/widgets/index.d.ts.map +1 -0
  81. package/dist/widgets/index.js +76 -0
  82. package/dist/widgets/keyboard.d.ts +28 -0
  83. package/dist/widgets/keyboard.d.ts.map +1 -0
  84. package/dist/widgets/layout.d.ts +51 -0
  85. package/dist/widgets/layout.d.ts.map +1 -0
  86. package/dist/widgets/list.d.ts +32 -0
  87. package/dist/widgets/list.d.ts.map +1 -0
  88. package/dist/widgets/meter.d.ts +26 -0
  89. package/dist/widgets/meter.d.ts.map +1 -0
  90. package/dist/widgets/table.d.ts +25 -0
  91. package/dist/widgets/table.d.ts.map +1 -0
  92. package/dist/widgets/tabs.d.ts +13 -0
  93. package/dist/widgets/tabs.d.ts.map +1 -0
  94. package/dist/widgets/text-view.d.ts +24 -0
  95. package/dist/widgets/text-view.d.ts.map +1 -0
  96. package/dist/widgets/theme.d.ts +17 -0
  97. package/dist/widgets/theme.d.ts.map +1 -0
  98. package/package.json +25 -12
@@ -0,0 +1,1705 @@
1
+ // @bun
2
+ // src/core/search.ts
3
+ function fold(text) {
4
+ return Array.from(text, (char) => char.toLocaleLowerCase());
5
+ }
6
+ function indexOfUnits(haystack, needle) {
7
+ outer:
8
+ for (let start = 0;start + needle.length <= haystack.length; start += 1) {
9
+ for (let offset = 0;offset < needle.length; offset += 1) {
10
+ if (haystack[start + offset] !== needle[offset])
11
+ continue outer;
12
+ }
13
+ return start;
14
+ }
15
+ return -1;
16
+ }
17
+ function rangesOf(positions) {
18
+ const ranges = [];
19
+ for (const position of positions) {
20
+ const last = ranges.at(-1);
21
+ if (last && last[1] === position)
22
+ last[1] += 1;
23
+ else
24
+ ranges.push([position, position + 1]);
25
+ }
26
+ return ranges;
27
+ }
28
+ function matchTerminalSearch2(query, text, options = {}) {
29
+ const words = query.trim().split(/\s+/).filter(Boolean);
30
+ if (words.length === 0)
31
+ return { score: 0, ranges: [] };
32
+ const haystack = fold(text);
33
+ const isBoundary = (index) => index === 0 || /[\s\-_./:\u00B7,(]/.test(haystack[index - 1] ?? " ");
34
+ let score = 0;
35
+ const positions = new Set;
36
+ for (const word of words) {
37
+ const needle = fold(word);
38
+ const start = indexOfUnits(haystack, needle);
39
+ if (start >= 0) {
40
+ for (let offset = 0;offset < needle.length; offset += 1)
41
+ positions.add(start + offset);
42
+ score += 100 + (isBoundary(start) ? 50 : 0) - Math.min(start, 40);
43
+ continue;
44
+ }
45
+ if (options.scattered === false)
46
+ return null;
47
+ let cursor = 0;
48
+ let gaps = 0;
49
+ const found = [];
50
+ for (const letter of needle) {
51
+ let index = cursor;
52
+ while (index < haystack.length && haystack[index] !== letter)
53
+ index += 1;
54
+ if (index >= haystack.length)
55
+ return null;
56
+ if (found.length > 0)
57
+ gaps += index - cursor;
58
+ found.push(index);
59
+ cursor = index + 1;
60
+ }
61
+ for (const index of found)
62
+ positions.add(index);
63
+ score += 20 + found.filter(isBoundary).length * 5 - Math.min(gaps, 30);
64
+ }
65
+ return { score, ranges: rangesOf([...positions].sort((a, b) => a - b)) };
66
+ }
67
+ function searchTerminalItems2(items, query, text, options = {}) {
68
+ const results = [];
69
+ items.forEach((item, index) => {
70
+ const match = matchTerminalSearch2(query, text(item), options);
71
+ if (match)
72
+ results.push({ item, match, index });
73
+ });
74
+ if (query.trim() !== "") {
75
+ results.sort((a, b) => b.match.score - a.match.score || a.index - b.index);
76
+ }
77
+ return results.map(({ item, match }) => ({ item, match }));
78
+ }
79
+ function terminalHighlightRuns2(text, ranges) {
80
+ const points = Array.from(text);
81
+ const runs = [];
82
+ let cursor = 0;
83
+ for (const [start, end] of ranges) {
84
+ if (start > cursor)
85
+ runs.push({ text: points.slice(cursor, start).join(""), highlighted: false });
86
+ runs.push({ text: points.slice(start, end).join(""), highlighted: true });
87
+ cursor = end;
88
+ }
89
+ if (cursor < points.length)
90
+ runs.push({ text: points.slice(cursor).join(""), highlighted: false });
91
+ return runs;
92
+ }
93
+
94
+ // src/core/chart.ts
95
+ import { z as z2 } from "zod";
96
+
97
+ // src/core/theme.ts
98
+ import { z } from "zod";
99
+ var TerminalToneSchema2 = z.enum([
100
+ "primary",
101
+ "muted",
102
+ "accent",
103
+ "success",
104
+ "warning",
105
+ "danger"
106
+ ]);
107
+ var TerminalThemeModeSchema2 = z.enum(["dark", "light"]);
108
+ var ColorSchema = z.string().min(1);
109
+ var TerminalPaletteSchema2 = z.object({
110
+ canvas: ColorSchema,
111
+ panel: ColorSchema,
112
+ panelRaised: ColorSchema,
113
+ border: ColorSchema,
114
+ borderActive: ColorSchema,
115
+ primary: ColorSchema,
116
+ muted: ColorSchema,
117
+ accent: ColorSchema,
118
+ success: ColorSchema,
119
+ warning: ColorSchema,
120
+ danger: ColorSchema
121
+ }).strict();
122
+ var terminalPalettes2 = Object.freeze({
123
+ dark: Object.freeze({
124
+ canvas: "#111111",
125
+ panel: "#1e2129",
126
+ panelRaised: "#303441",
127
+ border: "#454a57",
128
+ borderActive: "#d9dde7",
129
+ primary: "#e6ebf5",
130
+ muted: "#828aa0",
131
+ accent: "#e58a66",
132
+ success: "#64df98",
133
+ warning: "#ffd04f",
134
+ danger: "#ff6b78"
135
+ }),
136
+ light: Object.freeze({
137
+ canvas: "#fafafa",
138
+ panel: "#eef0f4",
139
+ panelRaised: "#dfe3ea",
140
+ border: "#b4bac6",
141
+ borderActive: "#2b303b",
142
+ primary: "#1d2129",
143
+ muted: "#646b7a",
144
+ accent: "#b5502b",
145
+ success: "#1a7f45",
146
+ warning: "#946200",
147
+ danger: "#c4283a"
148
+ })
149
+ });
150
+ function resolveTerminalPalette2(mode, overrides = {}) {
151
+ return TerminalPaletteSchema2.parse({
152
+ ...terminalPalettes2[TerminalThemeModeSchema2.parse(mode)],
153
+ ...overrides
154
+ });
155
+ }
156
+
157
+ // src/core/chart.ts
158
+ var SampleSchema = z2.object({
159
+ at: z2.number(),
160
+ value: z2.number().nullable()
161
+ }).strict();
162
+ var TimeSeriesOptionsSchema = z2.object({
163
+ windowMs: z2.int().positive(),
164
+ maxSamples: z2.int().min(2).default(4096)
165
+ }).strict();
166
+ function createTerminalTimeSeries2(options) {
167
+ return { ...TimeSeriesOptionsSchema.parse(options), samples: [] };
168
+ }
169
+ function appendTerminalSample2(series, sample) {
170
+ const next = SampleSchema.parse(sample);
171
+ const last = series.samples.at(-1);
172
+ if (last !== undefined && next.at < last.at) {
173
+ throw new Error(`Terminal samples must arrive in time order: ${next.at} is before ${last.at}`);
174
+ }
175
+ const horizon = next.at - series.windowMs;
176
+ let first = Math.max(0, series.samples.length + 1 - series.maxSamples);
177
+ while (first + 1 < series.samples.length && (series.samples[first + 1]?.at ?? 0) <= horizon) {
178
+ first += 1;
179
+ }
180
+ return { ...series, samples: [...series.samples.slice(first), next] };
181
+ }
182
+ function sampleTerminalTimeSeries2(series, input) {
183
+ const count = z2.int().nonnegative().parse(input.count);
184
+ const values = [];
185
+ let cursor = -1;
186
+ for (let index = 0;index < count; index += 1) {
187
+ const instant = count === 1 ? input.now : input.now - series.windowMs + series.windowMs * index / (count - 1);
188
+ while (cursor + 1 < series.samples.length && (series.samples[cursor + 1]?.at ?? 0) <= instant) {
189
+ cursor += 1;
190
+ }
191
+ values.push(cursor < 0 ? null : series.samples[cursor]?.value ?? null);
192
+ }
193
+ return values;
194
+ }
195
+ function terminalChartScale2(values, fixed = {}) {
196
+ const present = values.filter((value) => value !== null);
197
+ const min = fixed.min ?? Math.min(0, ...present);
198
+ const max = fixed.max ?? Math.max(min, ...present);
199
+ return { min, max: max > min ? max : min + 1 };
200
+ }
201
+ var BARS = ["\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588"];
202
+ function terminalSparkline2(values, scale = {}) {
203
+ const { min, max } = terminalChartScale2(values, scale);
204
+ return values.map((value) => {
205
+ if (value === null)
206
+ return " ";
207
+ const ratio = Math.min(1, Math.max(0, (value - min) / (max - min)));
208
+ return BARS[Math.round(ratio * (BARS.length - 1))] ?? " ";
209
+ }).join("");
210
+ }
211
+ var DOT_BITS = [
212
+ [1, 8],
213
+ [2, 16],
214
+ [4, 32],
215
+ [64, 128]
216
+ ];
217
+ var ChartInputSchema = z2.object({
218
+ series: z2.array(z2.object({
219
+ values: z2.array(z2.number().nullable()),
220
+ tone: TerminalToneSchema2
221
+ }).strict()),
222
+ width: z2.int().positive(),
223
+ height: z2.int().positive(),
224
+ min: z2.number().optional(),
225
+ max: z2.number().optional(),
226
+ fill: z2.boolean().default(false)
227
+ }).strict();
228
+ function terminalBrailleChart2(input) {
229
+ const { series, width, height, fill, ...fixed } = ChartInputSchema.parse(input);
230
+ const dotsHigh = height * 4;
231
+ const dotsWide = width * 2;
232
+ const bits = new Uint8Array(width * height);
233
+ const tones = new Array(width * height).fill(null);
234
+ const scale = terminalChartScale2(series.flatMap(({ values }) => values), fixed);
235
+ const level = (value) => Math.round(Math.min(1, Math.max(0, (value - scale.min) / (scale.max - scale.min))) * (dotsHigh - 1));
236
+ const plot = (x, y, tone) => {
237
+ const row = dotsHigh - 1 - y;
238
+ const cell = Math.floor(row / 4) * width + Math.floor(x / 2);
239
+ bits[cell] = (bits[cell] ?? 0) | (DOT_BITS[row % 4]?.[x % 2] ?? 0);
240
+ tones[cell] = tone;
241
+ };
242
+ for (const { values, tone } of series) {
243
+ let previous = null;
244
+ for (let x = 0;x < Math.min(dotsWide, values.length); x += 1) {
245
+ const value = values[x] ?? null;
246
+ if (value === null) {
247
+ previous = null;
248
+ continue;
249
+ }
250
+ const y = level(value);
251
+ const from = fill ? 0 : previous === null ? y : Math.min(previous, y);
252
+ const to = fill ? y : previous === null ? y : Math.max(previous, y);
253
+ for (let dot = from;dot <= to; dot += 1)
254
+ plot(x, dot, tone);
255
+ previous = y;
256
+ }
257
+ }
258
+ return Array.from({ length: height }, (_, row) => {
259
+ const segments = [];
260
+ for (let column = 0;column < width; column += 1) {
261
+ const cell = row * width + column;
262
+ const value = bits[cell] ?? 0;
263
+ const tone = value === 0 ? null : tones[cell] ?? null;
264
+ const text = value === 0 ? " " : String.fromCharCode(10240 + value);
265
+ const last = segments.at(-1);
266
+ if (last !== undefined && last.tone === tone)
267
+ last.text += text;
268
+ else
269
+ segments.push({ text, tone });
270
+ }
271
+ return segments;
272
+ });
273
+ }
274
+ function durationLabel(ms) {
275
+ const exact = ms / 1000;
276
+ if (!Number.isInteger(exact) && exact < 60)
277
+ return `${Number(exact.toFixed(1))}s`;
278
+ const seconds = Math.round(exact);
279
+ if (seconds % 3600 === 0 && seconds >= 3600)
280
+ return `${seconds / 3600}h`;
281
+ if (seconds % 60 === 0 && seconds >= 60)
282
+ return `${seconds / 60}m`;
283
+ return `${seconds}s`;
284
+ }
285
+ function terminalTimeAxis2(windowMs, width) {
286
+ const cells = z2.int().nonnegative().parse(width);
287
+ const left = `-${durationLabel(z2.int().positive().parse(windowMs))}`;
288
+ const right = "now";
289
+ if (cells < left.length + right.length + 1)
290
+ return right.padStart(cells).slice(0, cells);
291
+ const middle = `-${durationLabel(windowMs / 2)}`;
292
+ const gap = cells - left.length - right.length;
293
+ if (gap < middle.length + 2)
294
+ return left + " ".repeat(gap) + right;
295
+ const before = Math.floor((gap - middle.length) / 2);
296
+ return left + " ".repeat(before) + middle + " ".repeat(gap - middle.length - before) + right;
297
+ }
298
+
299
+ // src/core/collection.ts
300
+ import { z as z3 } from "zod";
301
+ var TerminalCollectionStateSchema2 = z3.object({
302
+ keys: z3.array(z3.string().min(1)),
303
+ selectedKey: z3.string().min(1).nullable(),
304
+ start: z3.int().nonnegative(),
305
+ capacity: z3.int().positive()
306
+ }).strict();
307
+ function maximumStart(total, capacity) {
308
+ return Math.max(0, total - capacity);
309
+ }
310
+ function reveal(start, capacity, index, total) {
311
+ const bounded = Math.min(Math.max(0, start), maximumStart(total, capacity));
312
+ if (index < bounded)
313
+ return index;
314
+ if (index >= bounded + capacity)
315
+ return index - capacity + 1;
316
+ return bounded;
317
+ }
318
+ function uniqueKeys(keys) {
319
+ const result = z3.array(z3.string().min(1)).parse(keys);
320
+ if (new Set(result).size !== result.length) {
321
+ throw new Error("Terminal collection keys must be unique");
322
+ }
323
+ return result;
324
+ }
325
+ function createTerminalCollection2(keys, capacity, selectedKey) {
326
+ const parsedKeys = uniqueKeys(keys);
327
+ const parsedCapacity = z3.int().positive().parse(capacity);
328
+ const selected = selectedKey !== undefined && parsedKeys.includes(selectedKey) ? selectedKey : parsedKeys[0] ?? null;
329
+ const index = selected === null ? -1 : parsedKeys.indexOf(selected);
330
+ return TerminalCollectionStateSchema2.parse({
331
+ keys: parsedKeys,
332
+ selectedKey: selected,
333
+ start: index < 0 ? 0 : reveal(0, parsedCapacity, index, parsedKeys.length),
334
+ capacity: parsedCapacity
335
+ });
336
+ }
337
+ function reduceTerminalCollection2(state, action) {
338
+ const current = state;
339
+ if (action.type === "reconcile") {
340
+ const keys = uniqueKeys(action.keys);
341
+ if (keys.length === 0)
342
+ return { keys, selectedKey: null, start: 0, capacity: current.capacity };
343
+ const previousIndex = current.selectedKey === null ? 0 : Math.max(0, current.keys.indexOf(current.selectedKey));
344
+ const selectedKey = current.selectedKey !== null && keys.includes(current.selectedKey) ? current.selectedKey : keys[Math.min(previousIndex, keys.length - 1)];
345
+ if (!selectedKey)
346
+ throw new Error("Terminal collection survivor is unavailable");
347
+ const index = keys.indexOf(selectedKey);
348
+ return {
349
+ ...current,
350
+ keys,
351
+ selectedKey,
352
+ start: reveal(current.start, current.capacity, index, keys.length)
353
+ };
354
+ }
355
+ if (action.type === "resize") {
356
+ const capacity = z3.int().positive().parse(action.capacity);
357
+ const index = current.selectedKey === null ? -1 : current.keys.indexOf(current.selectedKey);
358
+ return {
359
+ ...current,
360
+ capacity,
361
+ start: index < 0 ? 0 : reveal(current.start, capacity, index, current.keys.length)
362
+ };
363
+ }
364
+ if (action.type === "scroll") {
365
+ return {
366
+ ...current,
367
+ start: Math.min(Math.max(0, current.start + z3.int().parse(action.lines)), maximumStart(current.keys.length, current.capacity))
368
+ };
369
+ }
370
+ if (current.keys.length === 0)
371
+ return current;
372
+ const currentIndex = current.selectedKey === null ? 0 : Math.max(0, current.keys.indexOf(current.selectedKey));
373
+ const nextIndex = action.type === "select" ? current.keys.indexOf(action.key) : action.wrap ? ((currentIndex + action.delta) % current.keys.length + current.keys.length) % current.keys.length : Math.min(Math.max(0, currentIndex + action.delta), current.keys.length - 1);
374
+ if (nextIndex < 0) {
375
+ throw new Error(action.type === "select" ? `Unknown terminal collection key: ${action.key}` : "Terminal collection movement could not resolve a selection");
376
+ }
377
+ const selectedKey = current.keys[nextIndex];
378
+ if (!selectedKey)
379
+ throw new Error("Terminal collection selection is unavailable");
380
+ return {
381
+ ...current,
382
+ selectedKey,
383
+ start: reveal(current.start, current.capacity, nextIndex, current.keys.length)
384
+ };
385
+ }
386
+ function visibleTerminalCollectionRange2(state) {
387
+ return {
388
+ start: state.start,
389
+ end: Math.min(state.keys.length, state.start + state.capacity)
390
+ };
391
+ }
392
+
393
+ // src/core/form.ts
394
+ import { z as z4 } from "zod";
395
+
396
+ // src/core/text.ts
397
+ var STRING_SEQUENCE = /(?:\u001b[\]PX^_]|[\u0090\u0098\u009d\u009e\u009f])[\s\S]*?(?:\u0007|\u001b\\|\u009c|$)/g;
398
+ var CSI = /(?:\u001b\[|\u009b)[0-?]*[ -/]*[@-~]?/g;
399
+ var ESCAPE = /\u001b[ -/]*[0-~]?/g;
400
+ var CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g;
401
+ function sanitizeTerminalText2(text, tabWidth = 2) {
402
+ return text.replace(STRING_SEQUENCE, "").replace(CSI, "").replace(ESCAPE, "").replace(/\r\n?/g, `
403
+ `).replace(/\t/g, " ".repeat(tabWidth)).replace(CONTROL, "");
404
+ }
405
+ var WIDE = [
406
+ [4352, 4447],
407
+ [11904, 12350],
408
+ [12353, 13311],
409
+ [13312, 19903],
410
+ [19968, 40959],
411
+ [40960, 42191],
412
+ [44032, 55203],
413
+ [63744, 64255],
414
+ [65072, 65103],
415
+ [65280, 65376],
416
+ [65504, 65510],
417
+ [127744, 128591],
418
+ [129280, 129535],
419
+ [131072, 262141]
420
+ ];
421
+ var segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
422
+ function terminalGraphemes2(text) {
423
+ return Array.from(segmenter.segment(text), ({ segment }) => segment);
424
+ }
425
+ function terminalGraphemeWidth2(grapheme) {
426
+ if (/^[\p{M}\p{Cf}]+$/u.test(grapheme))
427
+ return 0;
428
+ if (/\p{Emoji_Presentation}/u.test(grapheme) || grapheme.includes("\uFE0F") && /\p{Extended_Pictographic}/u.test(grapheme))
429
+ return 2;
430
+ const code = grapheme.codePointAt(0) ?? 0;
431
+ for (const [start, end] of WIDE)
432
+ if (code >= start && code <= end)
433
+ return 2;
434
+ return 1;
435
+ }
436
+ function terminalTextWidth2(text) {
437
+ let width = 0;
438
+ for (const grapheme of terminalGraphemes2(text))
439
+ width += terminalGraphemeWidth2(grapheme);
440
+ return width;
441
+ }
442
+ function truncateTerminalText2(text, width) {
443
+ if (width <= 0)
444
+ return "";
445
+ if (terminalTextWidth2(text) <= width)
446
+ return text;
447
+ let used = 0;
448
+ let result = "";
449
+ for (const grapheme of terminalGraphemes2(text)) {
450
+ const cells = terminalGraphemeWidth2(grapheme);
451
+ if (used + cells > width - 1)
452
+ break;
453
+ result += grapheme;
454
+ used += cells;
455
+ }
456
+ return `${result}\u2026`;
457
+ }
458
+ function fitTerminalText2(text, width, align = "left") {
459
+ const cut = truncateTerminalText2(text, width);
460
+ const pad = Math.max(0, width - terminalTextWidth2(cut));
461
+ if (align === "right")
462
+ return " ".repeat(pad) + cut;
463
+ if (align === "center") {
464
+ const before = Math.floor(pad / 2);
465
+ return " ".repeat(before) + cut + " ".repeat(pad - before);
466
+ }
467
+ return cut + " ".repeat(pad);
468
+ }
469
+ function wrapTerminalText2(text, width) {
470
+ if (width <= 0)
471
+ return [];
472
+ const lines = [];
473
+ for (const paragraph of text.split(`
474
+ `)) {
475
+ const indent = /^ */.exec(paragraph)?.[0] ?? "";
476
+ const words = paragraph.slice(indent.length).split(/ +/).filter(Boolean);
477
+ if (words.length === 0) {
478
+ lines.push("");
479
+ continue;
480
+ }
481
+ const first = indent.length < width ? indent : "";
482
+ const hang = indent.length < width / 2 ? indent : "";
483
+ let line = first;
484
+ let start = first.length;
485
+ let used = start;
486
+ const flush = () => {
487
+ lines.push(line.trimEnd());
488
+ line = hang;
489
+ start = hang.length;
490
+ used = start;
491
+ };
492
+ for (const word of words) {
493
+ const cells = terminalTextWidth2(word);
494
+ const separator = used > start ? 1 : 0;
495
+ if (used + separator + cells <= width) {
496
+ line += (separator ? " " : "") + word;
497
+ used += separator + cells;
498
+ continue;
499
+ }
500
+ if (used > start)
501
+ flush();
502
+ if (cells <= width - used) {
503
+ line += word;
504
+ used += cells;
505
+ continue;
506
+ }
507
+ for (const grapheme of terminalGraphemes2(word)) {
508
+ const graphemeCells = terminalGraphemeWidth2(grapheme);
509
+ if (used + graphemeCells > width && used > start)
510
+ flush();
511
+ line += grapheme;
512
+ used += graphemeCells;
513
+ }
514
+ }
515
+ lines.push(line.trimEnd());
516
+ }
517
+ return lines;
518
+ }
519
+ function terminalTextEdit2(key) {
520
+ if (key.name === "escape")
521
+ return { kind: "clear" };
522
+ if (key.name === "return" || key.name === "enter")
523
+ return { kind: "commit" };
524
+ if (key.name === "backspace")
525
+ return { kind: "erase" };
526
+ const text = key.sequence ?? "";
527
+ const control = Array.from(text).some((char) => {
528
+ const code = char.codePointAt(0) ?? 0;
529
+ return code < 32 || code === 127;
530
+ });
531
+ if (key.ctrl || key.meta || text.length === 0 || control)
532
+ return null;
533
+ return { kind: "insert", text };
534
+ }
535
+ function applyTerminalTextEdit2(text, edit) {
536
+ if (edit.kind === "insert")
537
+ return text + edit.text;
538
+ if (edit.kind === "erase")
539
+ return terminalGraphemes2(text).slice(0, -1).join("");
540
+ if (edit.kind === "clear")
541
+ return "";
542
+ return text;
543
+ }
544
+
545
+ // src/core/form.ts
546
+ var TerminalFormFieldSchema2 = z4.object({
547
+ name: z4.string().min(1),
548
+ label: z4.string().min(1),
549
+ kind: z4.enum(["text", "secret", "number", "integer", "boolean", "choice", "json"]),
550
+ required: z4.boolean().default(false),
551
+ choices: z4.array(z4.union([z4.string(), z4.number(), z4.boolean()])).optional(),
552
+ defaultValue: z4.unknown().optional(),
553
+ description: z4.string().optional(),
554
+ placeholder: z4.string().optional()
555
+ }).strict().refine((field) => field.kind !== "choice" || (field.choices?.length ?? 0) > 0, {
556
+ message: "A choice field needs at least one choice"
557
+ });
558
+ var terminalFormMessages2 = {
559
+ required: "Required",
560
+ number: "Expected a number",
561
+ integer: "Expected a whole number",
562
+ choice: (choices) => `Choose one of: ${choices.join(", ")}`,
563
+ json: (reason) => `Invalid JSON: ${reason}`
564
+ };
565
+ function draftOf(field) {
566
+ const value = field.defaultValue;
567
+ if (value === undefined || value === null)
568
+ return "";
569
+ if (field.kind === "json")
570
+ return JSON.stringify(value);
571
+ return String(value);
572
+ }
573
+ function readField(field, draft, messages) {
574
+ const text = field.kind === "text" || field.kind === "secret" ? draft : draft.trim();
575
+ if (text === "")
576
+ return field.required ? { error: messages.required } : {};
577
+ switch (field.kind) {
578
+ case "text":
579
+ case "secret":
580
+ return { value: text };
581
+ case "number":
582
+ case "integer": {
583
+ if (!/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(text))
584
+ return { error: messages.number };
585
+ const value = Number(text);
586
+ if (!Number.isFinite(value))
587
+ return { error: messages.number };
588
+ if (field.kind === "integer" && !Number.isInteger(value))
589
+ return { error: messages.integer };
590
+ return { value };
591
+ }
592
+ case "boolean":
593
+ return text === "true" || text === "false" ? { value: text === "true" } : { error: messages.choice(["true", "false"]) };
594
+ case "choice": {
595
+ const choice = field.choices?.find((candidate) => String(candidate) === text);
596
+ return choice === undefined ? { error: messages.choice((field.choices ?? []).map(String)) } : { value: choice };
597
+ }
598
+ case "json":
599
+ try {
600
+ return { value: JSON.parse(text) };
601
+ } catch (error) {
602
+ return {
603
+ error: messages.json(error instanceof Error ? error.message : String(error))
604
+ };
605
+ }
606
+ }
607
+ }
608
+ function createTerminalForm2(fields) {
609
+ const parsed = z4.array(TerminalFormFieldSchema2).parse(fields);
610
+ const names = new Set;
611
+ for (const field of parsed) {
612
+ if (names.has(field.name))
613
+ throw new Error(`Terminal form field ${field.name} is declared twice`);
614
+ names.add(field.name);
615
+ }
616
+ return {
617
+ fields: parsed,
618
+ drafts: Object.fromEntries(parsed.map((field) => [field.name, draftOf(field)])),
619
+ errors: {},
620
+ focus: 0,
621
+ submitted: false,
622
+ accepted: null
623
+ };
624
+ }
625
+ function fieldNamed(state, name) {
626
+ const field = name === undefined ? state.fields[state.focus] : state.fields.find((f) => f.name === name);
627
+ if (!field)
628
+ throw new Error(`Unknown terminal form field: ${name ?? `#${state.focus}`}`);
629
+ return field;
630
+ }
631
+ function readTerminalForm2(state, messages = terminalFormMessages2) {
632
+ const values = {};
633
+ const errors = {};
634
+ for (const field of state.fields) {
635
+ const read = readField(field, state.drafts[field.name] ?? "", messages);
636
+ if (read.error !== undefined)
637
+ errors[field.name] = read.error;
638
+ else if ("value" in read)
639
+ values[field.name] = read.value;
640
+ }
641
+ return Object.keys(errors).length > 0 ? { ok: false, errors } : { ok: true, values };
642
+ }
643
+ function reduceTerminalForm2(state, action, messages = terminalFormMessages2) {
644
+ const validate = (next, name) => {
645
+ const field = fieldNamed(next, name);
646
+ const read = readField(field, next.drafts[name] ?? "", messages);
647
+ const errors = { ...next.errors };
648
+ if (read.error !== undefined)
649
+ errors[name] = read.error;
650
+ else
651
+ delete errors[name];
652
+ return { ...next, errors };
653
+ };
654
+ switch (action.type) {
655
+ case "focus":
656
+ case "move": {
657
+ if (state.fields.length === 0)
658
+ return state;
659
+ const target = action.type === "focus" ? state.fields.findIndex(({ name }) => name === action.name) : Math.min(Math.max(0, state.focus + action.delta), state.fields.length - 1);
660
+ if (target < 0)
661
+ throw new Error(`Unknown terminal form field: ${action.type === "focus" ? action.name : ""}`);
662
+ const left = state.fields[state.focus];
663
+ const checked = left && target !== state.focus ? validate(state, left.name) : state;
664
+ return { ...checked, focus: target };
665
+ }
666
+ case "set":
667
+ case "edit": {
668
+ const field = fieldNamed(state, action.name);
669
+ const text = action.type === "set" ? action.text : applyTerminalTextEdit2(state.drafts[field.name] ?? "", action.edit);
670
+ const next = { ...state, drafts: { ...state.drafts, [field.name]: text } };
671
+ return state.errors[field.name] !== undefined || state.submitted ? validate(next, field.name) : next;
672
+ }
673
+ case "cycle": {
674
+ const field = fieldNamed(state, action.name);
675
+ const options = field.kind === "boolean" ? ["true", "false"] : field.kind === "choice" ? (field.choices ?? []).map(String) : null;
676
+ if (options === null)
677
+ return state;
678
+ const all = field.required ? options : ["", ...options];
679
+ const index = all.indexOf(state.drafts[field.name] ?? "");
680
+ const next = all[((index + action.delta) % all.length + all.length) % all.length] ?? "";
681
+ return validate({ ...state, drafts: { ...state.drafts, [field.name]: next } }, field.name);
682
+ }
683
+ case "clear": {
684
+ const field = fieldNamed(state, action.name);
685
+ const next = { ...state, drafts: { ...state.drafts, [field.name]: "" } };
686
+ return state.errors[field.name] !== undefined || state.submitted ? validate(next, field.name) : next;
687
+ }
688
+ case "submit": {
689
+ const result = readTerminalForm2(state, messages);
690
+ if (result.ok) {
691
+ const serial = (state.accepted?.serial ?? 0) + 1;
692
+ return {
693
+ ...state,
694
+ errors: {},
695
+ submitted: true,
696
+ accepted: { serial, values: result.values }
697
+ };
698
+ }
699
+ const first = state.fields.findIndex(({ name }) => result.errors[name] !== undefined);
700
+ return {
701
+ ...state,
702
+ errors: result.errors,
703
+ submitted: true,
704
+ focus: first < 0 ? state.focus : first
705
+ };
706
+ }
707
+ }
708
+ }
709
+ var JsonSchemaPropertySchema = z4.object({
710
+ type: z4.union([z4.string(), z4.array(z4.string())]).optional(),
711
+ enum: z4.array(z4.unknown()).optional(),
712
+ title: z4.string().optional(),
713
+ description: z4.string().optional(),
714
+ default: z4.unknown().optional(),
715
+ format: z4.string().optional(),
716
+ writeOnly: z4.boolean().optional()
717
+ }).loose();
718
+ var JsonSchemaObjectSchema = z4.object({
719
+ properties: z4.record(z4.string(), z4.unknown()).default({}),
720
+ required: z4.array(z4.string()).default([])
721
+ }).loose();
722
+ function terminalFormFieldsFromJsonSchema2(schema) {
723
+ const object = JsonSchemaObjectSchema.parse(schema);
724
+ return Object.entries(object.properties).map(([name, raw]) => {
725
+ const property = JsonSchemaPropertySchema.parse(typeof raw === "boolean" ? {} : raw ?? {});
726
+ const types = (Array.isArray(property.type) ? property.type : [property.type]).filter((type) => type !== undefined && type !== "null");
727
+ const type = types.length === 1 ? types[0] : undefined;
728
+ const listed = property.enum?.filter((value) => value !== null);
729
+ const scalars = listed?.filter((value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean");
730
+ const choices = scalars !== undefined && scalars.length > 0 && scalars.length === listed?.length ? scalars : undefined;
731
+ const kind = choices ? "choice" : type === "string" ? property.format === "password" || property.writeOnly ? "secret" : "text" : type === "number" ? "number" : type === "integer" ? "integer" : type === "boolean" ? "boolean" : "json";
732
+ return {
733
+ name,
734
+ label: property.title ?? name,
735
+ kind,
736
+ required: object.required.includes(name),
737
+ ...choices && { choices },
738
+ ...property.default !== undefined && { defaultValue: property.default },
739
+ ...property.description !== undefined && { description: property.description }
740
+ };
741
+ });
742
+ }
743
+
744
+ // src/core/json.ts
745
+ function terminalJsonLines2(value, indent = 2) {
746
+ const lines = [];
747
+ const pad = (depth) => ({
748
+ text: " ".repeat(depth * indent),
749
+ tone: "muted"
750
+ });
751
+ const scalar = (input) => {
752
+ if (typeof input === "string")
753
+ return { text: sanitizeTerminalText2(JSON.stringify(input)), tone: "success" };
754
+ if (input === null || typeof input === "boolean")
755
+ return { text: String(input), tone: "accent" };
756
+ if (typeof input === "number" || typeof input === "bigint")
757
+ return { text: String(input), tone: "warning" };
758
+ return { text: JSON.stringify(input) ?? "undefined", tone: "muted" };
759
+ };
760
+ const seen = new WeakSet;
761
+ const visit = (raw, depth, prefix, last) => {
762
+ const comma = last ? [] : [{ text: ",", tone: "muted" }];
763
+ const input = typeof raw === "object" && raw !== null && "toJSON" in raw && typeof raw.toJSON === "function" ? raw.toJSON() : raw;
764
+ if (typeof input === "object" && input !== null) {
765
+ if (seen.has(input)) {
766
+ lines.push([pad(depth), ...prefix, { text: "[Circular]", tone: "muted" }, ...comma]);
767
+ return;
768
+ }
769
+ seen.add(input);
770
+ }
771
+ const entries = Array.isArray(input) ? input.map((item) => [null, item]) : typeof input === "object" && input !== null ? Object.entries(input) : null;
772
+ if (entries === null) {
773
+ lines.push([pad(depth), ...prefix, scalar(input), ...comma]);
774
+ return;
775
+ }
776
+ const [open, close] = Array.isArray(input) ? ["[", "]"] : ["{", "}"];
777
+ if (entries.length === 0) {
778
+ lines.push([
779
+ pad(depth),
780
+ ...prefix,
781
+ { text: `${open}${close}`, tone: "muted" },
782
+ ...comma
783
+ ]);
784
+ return;
785
+ }
786
+ lines.push([pad(depth), ...prefix, { text: open, tone: "muted" }]);
787
+ entries.forEach(([key, item], index) => {
788
+ const keyRuns = key === null ? [] : [
789
+ { text: sanitizeTerminalText2(JSON.stringify(key)), tone: "accent" },
790
+ { text: ": ", tone: "muted" }
791
+ ];
792
+ visit(item, depth + 1, keyRuns, index === entries.length - 1);
793
+ });
794
+ lines.push([pad(depth), { text: close, tone: "muted" }, ...comma]);
795
+ };
796
+ visit(value, 0, [], true);
797
+ return lines.map((line) => line.filter(({ text }) => text !== ""));
798
+ }
799
+ function layoutTerminalDetails2(pairs, width, gap = 2) {
800
+ const keyWidth = Math.min(Math.max(0, ...pairs.map(({ key }) => terminalTextWidth2(key))), Math.max(1, Math.floor(width / 3)));
801
+ return pairs.map(({ key, value, tone }) => ({
802
+ key: fitTerminalText2(sanitizeTerminalText2(key), keyWidth) + " ".repeat(gap),
803
+ value: truncateTerminalText2(sanitizeTerminalText2(value).replace(/\n/g, " \u23CE "), Math.max(1, width - keyWidth - gap)),
804
+ tone: tone ?? "primary"
805
+ }));
806
+ }
807
+
808
+ // src/core/key-hints.ts
809
+ import { z as z5 } from "zod";
810
+ var TerminalKeyBindingSchema2 = z5.object({
811
+ id: z5.string().min(1),
812
+ keys: z5.array(z5.string().min(1)).min(1),
813
+ display: z5.string().min(1),
814
+ label: z5.string().min(1),
815
+ short: z5.string().min(1).optional(),
816
+ priority: z5.int().nonnegative().default(1),
817
+ ctrl: z5.boolean().default(false),
818
+ shift: z5.boolean().optional(),
819
+ hidden: z5.boolean().default(false)
820
+ }).strict();
821
+ function defineTerminalKeymap2(bindings) {
822
+ const parsed = z5.array(TerminalKeyBindingSchema2).parse(bindings);
823
+ const ids = new Set;
824
+ const chords = new Map;
825
+ for (const binding of parsed) {
826
+ if (ids.has(binding.id))
827
+ throw new Error(`Terminal key binding ${binding.id} is declared twice`);
828
+ ids.add(binding.id);
829
+ for (const key of binding.keys) {
830
+ const shifts = binding.shift === undefined ? [false, true] : [binding.shift];
831
+ for (const shift of shifts) {
832
+ const chord = `${binding.ctrl ? "ctrl+" : ""}${shift ? "shift+" : ""}${key}`;
833
+ const owner = chords.get(chord);
834
+ if (owner)
835
+ throw new Error(`Key ${chord} is bound to both ${owner} and ${binding.id}`);
836
+ chords.set(chord, binding.id);
837
+ }
838
+ }
839
+ }
840
+ return parsed;
841
+ }
842
+ function matchTerminalKey2(bindings, key) {
843
+ for (const binding of bindings) {
844
+ if (binding.ctrl !== Boolean(key.ctrl))
845
+ continue;
846
+ if (binding.shift !== undefined && binding.shift !== Boolean(key.shift))
847
+ continue;
848
+ if (binding.keys.some((name) => name === key.name || name === key.sequence))
849
+ return binding;
850
+ }
851
+ return null;
852
+ }
853
+ function fitTerminalKeyHints2(bindings, width, separator = " \xB7 ") {
854
+ const shown = bindings.filter(({ hidden }) => !hidden);
855
+ const render = (items, short) => items.map((binding) => `${binding.display} ${short ? binding.short ?? binding.label : binding.label}`).join(separator);
856
+ let items = [...shown];
857
+ for (;; ) {
858
+ const full = render(items, false);
859
+ if (terminalTextWidth2(full) <= width)
860
+ return full;
861
+ const short = render(items, true);
862
+ if (terminalTextWidth2(short) <= width)
863
+ return short;
864
+ if (items.length <= 1)
865
+ return truncateTerminalText2(short, width);
866
+ let drop = 0;
867
+ items.forEach((binding, index) => {
868
+ if (binding.priority >= (items[drop]?.priority ?? 0))
869
+ drop = index;
870
+ });
871
+ items = items.filter((_, index) => index !== drop);
872
+ }
873
+ }
874
+
875
+ // src/core/labels.ts
876
+ var terminalLabelsEn2 = Object.freeze({
877
+ form: terminalFormMessages2,
878
+ rows: (shown, total) => shown === total ? `${total} ${total === 1 ? "row" : "rows"}` : `${shown} of ${total} rows`,
879
+ filter: "filter",
880
+ nothingFound: "Nothing found",
881
+ moreAbove: (count) => `\u2191 ${count} more`,
882
+ moreBelow: (count) => `\u2193 ${count} more`,
883
+ loading: "Loading",
884
+ empty: "Nothing here yet",
885
+ error: "Failed",
886
+ retry: "retry",
887
+ yes: "Yes",
888
+ no: "No",
889
+ back: "back",
890
+ open: "open",
891
+ move: "move",
892
+ page: "page",
893
+ search: "search",
894
+ typing: "type",
895
+ submit: "submit",
896
+ next: "next field",
897
+ change: "change",
898
+ sort: "sort",
899
+ invert: "invert",
900
+ expand: "expand",
901
+ collapse: "collapse",
902
+ tabs: "views",
903
+ pick: "pick",
904
+ help: "help",
905
+ quit: "quit",
906
+ top: "top",
907
+ bottom: "bottom",
908
+ required: "required",
909
+ scroll: (percent) => `${percent}%`
910
+ });
911
+ var terminalLabelsRu2 = Object.freeze({
912
+ form: {
913
+ required: "\u041E\u0431\u044F\u0437\u0430\u0442\u0435\u043B\u044C\u043D\u043E\u0435 \u043F\u043E\u043B\u0435",
914
+ number: "\u041D\u0443\u0436\u043D\u043E \u0447\u0438\u0441\u043B\u043E",
915
+ integer: "\u041D\u0443\u0436\u043D\u043E \u0446\u0435\u043B\u043E\u0435 \u0447\u0438\u0441\u043B\u043E",
916
+ choice: (choices) => `\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u043E\u0434\u043D\u043E \u0438\u0437: ${choices.join(", ")}`,
917
+ json: (reason) => `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 JSON: ${reason}`
918
+ },
919
+ rows: (shown, total) => shown === total ? `\u0441\u0442\u0440\u043E\u043A: ${total}` : `${shown} \u0438\u0437 ${total}`,
920
+ filter: "\u0444\u0438\u043B\u044C\u0442\u0440",
921
+ nothingFound: "\u041D\u0438\u0447\u0435\u0433\u043E \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u043E",
922
+ moreAbove: (count) => `\u2191 \u0435\u0449\u0451 ${count}`,
923
+ moreBelow: (count) => `\u2193 \u0435\u0449\u0451 ${count}`,
924
+ loading: "\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430",
925
+ empty: "\u041F\u043E\u043A\u0430 \u043F\u0443\u0441\u0442\u043E",
926
+ error: "\u041E\u0448\u0438\u0431\u043A\u0430",
927
+ retry: "\u043F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u044C",
928
+ yes: "\u0414\u0430",
929
+ no: "\u041D\u0435\u0442",
930
+ back: "\u043D\u0430\u0437\u0430\u0434",
931
+ open: "\u043E\u0442\u043A\u0440\u044B\u0442\u044C",
932
+ move: "\u0432\u044B\u0431\u043E\u0440",
933
+ page: "\u0441\u0442\u0440\u0430\u043D\u0438\u0446\u0430",
934
+ search: "\u043F\u043E\u0438\u0441\u043A",
935
+ typing: "\u043F\u0435\u0447\u0430\u0442\u0430\u0439\u0442\u0435",
936
+ submit: "\u0432\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u044C",
937
+ next: "\u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0435\u0435 \u043F\u043E\u043B\u0435",
938
+ change: "\u0438\u0437\u043C\u0435\u043D\u0438\u0442\u044C",
939
+ sort: "\u0441\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u043A\u0430",
940
+ invert: "\u043E\u0431\u0440\u0430\u0442\u043D\u044B\u0439 \u043F\u043E\u0440\u044F\u0434\u043E\u043A",
941
+ expand: "\u0440\u0430\u0441\u043A\u0440\u044B\u0442\u044C",
942
+ collapse: "\u0441\u0432\u0435\u0440\u043D\u0443\u0442\u044C",
943
+ tabs: "\u0432\u043A\u043B\u0430\u0434\u043A\u0438",
944
+ pick: "\u043E\u0442\u043C\u0435\u0442\u0438\u0442\u044C",
945
+ help: "\u0441\u043F\u0440\u0430\u0432\u043A\u0430",
946
+ quit: "\u0432\u044B\u0445\u043E\u0434",
947
+ top: "\u0432 \u043D\u0430\u0447\u0430\u043B\u043E",
948
+ bottom: "\u0432 \u043A\u043E\u043D\u0435\u0446",
949
+ required: "\u043E\u0431\u044F\u0437\u0430\u0442\u0435\u043B\u044C\u043D\u043E",
950
+ scroll: (percent) => `${percent}%`
951
+ });
952
+
953
+ // src/core/keys.ts
954
+ function terminalTableKeymap2(labels = terminalLabelsEn2) {
955
+ return defineTerminalKeymap2([
956
+ {
957
+ id: "up",
958
+ keys: ["up", "k"],
959
+ shift: false,
960
+ display: "\u2191\u2193",
961
+ label: labels.move,
962
+ priority: 0
963
+ },
964
+ {
965
+ id: "down",
966
+ keys: ["down", "j"],
967
+ shift: false,
968
+ display: "\u2193",
969
+ label: labels.move,
970
+ hidden: true
971
+ },
972
+ {
973
+ id: "activate",
974
+ keys: ["return", "enter"],
975
+ display: "Enter",
976
+ label: labels.open,
977
+ priority: 0
978
+ },
979
+ { id: "filter", keys: ["/"], display: "/", label: labels.filter, priority: 1 },
980
+ {
981
+ id: "expand",
982
+ keys: ["right", "+"],
983
+ display: "\u2192\u2190",
984
+ label: `${labels.expand}/${labels.collapse}`,
985
+ short: labels.expand,
986
+ priority: 2
987
+ },
988
+ {
989
+ id: "collapse",
990
+ keys: ["left", "-"],
991
+ display: "\u2190",
992
+ label: labels.collapse,
993
+ hidden: true
994
+ },
995
+ { id: "sort-next", keys: [">", "."], display: "<>", label: labels.sort, priority: 2 },
996
+ { id: "sort-previous", keys: ["<", ","], display: "<", label: labels.sort, hidden: true },
997
+ { id: "sort-invert", keys: ["I"], display: "I", label: labels.invert, priority: 4 },
998
+ { id: "page-up", keys: ["pageup"], display: "PgUp/PgDn", label: labels.page, priority: 3 },
999
+ { id: "page-down", keys: ["pagedown"], display: "PgDn", label: labels.page, hidden: true },
1000
+ { id: "home", keys: ["home"], display: "Home", label: labels.top, hidden: true },
1001
+ { id: "end", keys: ["end"], display: "End", label: labels.bottom, hidden: true }
1002
+ ]);
1003
+ }
1004
+ var defaultTableKeymap = terminalTableKeymap2();
1005
+ function terminalTableKey2(state, key, keymap = defaultTableKeymap) {
1006
+ if (key.meta)
1007
+ return null;
1008
+ const binding = matchTerminalKey2(keymap, key);
1009
+ if (binding === null)
1010
+ return null;
1011
+ const page = state.collection.capacity;
1012
+ const all = Math.max(1, state.collection.keys.length);
1013
+ const act = (action) => ({
1014
+ kind: "action",
1015
+ action
1016
+ });
1017
+ switch (binding.id) {
1018
+ case "up":
1019
+ return act({ type: "move", delta: -1 });
1020
+ case "down":
1021
+ return act({ type: "move", delta: 1 });
1022
+ case "page-up":
1023
+ return act({ type: "move", delta: -page });
1024
+ case "page-down":
1025
+ return act({ type: "move", delta: page });
1026
+ case "home":
1027
+ return act({ type: "move", delta: -all });
1028
+ case "end":
1029
+ return act({ type: "move", delta: all });
1030
+ case "activate":
1031
+ return { kind: "activate" };
1032
+ case "expand":
1033
+ return act({ type: "expand" });
1034
+ case "collapse":
1035
+ return act({ type: "collapse" });
1036
+ case "sort-next":
1037
+ return act({ type: "sort-next", delta: 1 });
1038
+ case "sort-previous":
1039
+ return act({ type: "sort-next", delta: -1 });
1040
+ case "sort-invert":
1041
+ return act({ type: "sort-invert" });
1042
+ case "filter":
1043
+ return { kind: "filter-start" };
1044
+ default:
1045
+ return null;
1046
+ }
1047
+ }
1048
+ function terminalTabsKeymap2(labels = terminalLabelsEn2) {
1049
+ return defineTerminalKeymap2([
1050
+ {
1051
+ id: "next",
1052
+ keys: ["tab"],
1053
+ shift: false,
1054
+ display: "Tab",
1055
+ label: labels.tabs,
1056
+ priority: 1
1057
+ },
1058
+ {
1059
+ id: "previous",
1060
+ keys: ["tab"],
1061
+ shift: true,
1062
+ display: "\u21E7Tab",
1063
+ label: labels.tabs,
1064
+ hidden: true
1065
+ },
1066
+ ...Array.from({ length: 9 }, (_, index) => ({
1067
+ id: `tab-${index + 1}`,
1068
+ keys: [String(index + 1)],
1069
+ display: index === 0 ? "1\u20139" : String(index + 1),
1070
+ label: labels.tabs,
1071
+ hidden: index > 0,
1072
+ priority: 3
1073
+ }))
1074
+ ]);
1075
+ }
1076
+ var defaultTabsKeymap = terminalTabsKeymap2();
1077
+ function terminalTabsKey2(key, keymap = defaultTabsKeymap) {
1078
+ if (key.meta)
1079
+ return null;
1080
+ const binding = matchTerminalKey2(keymap, key);
1081
+ if (binding === null)
1082
+ return null;
1083
+ if (binding.id === "next")
1084
+ return { type: "move", delta: 1 };
1085
+ if (binding.id === "previous")
1086
+ return { type: "move", delta: -1 };
1087
+ const digit = /^tab-([1-9])$/.exec(binding.id)?.[1];
1088
+ return digit ? { type: "select-index", index: Number(digit) - 1 } : null;
1089
+ }
1090
+
1091
+ // src/core/list.ts
1092
+ import { z as z6 } from "zod";
1093
+ var TerminalListItemSchema2 = z6.object({
1094
+ key: z6.string().min(1),
1095
+ title: z6.string().min(1),
1096
+ meta: z6.string().optional(),
1097
+ description: z6.string().optional(),
1098
+ section: z6.string().min(1).optional(),
1099
+ badge: z6.union([z6.string(), z6.int()]).optional(),
1100
+ tone: TerminalToneSchema2.optional(),
1101
+ disabled: z6.boolean().default(false),
1102
+ keywords: z6.array(z6.string()).default([])
1103
+ }).strict();
1104
+ function parseItems(items) {
1105
+ const parsed = z6.array(TerminalListItemSchema2).parse(items);
1106
+ const keys = new Set;
1107
+ for (const item of parsed) {
1108
+ if (keys.has(item.key))
1109
+ throw new Error(`Terminal list keys must be unique: ${item.key}`);
1110
+ keys.add(item.key);
1111
+ }
1112
+ return parsed;
1113
+ }
1114
+ function project(state) {
1115
+ const searching = state.query.trim() !== "";
1116
+ const results = searchTerminalItems2(state.items, state.query, (item) => [item.title, item.meta ?? "", item.description ?? "", ...item.keywords].join(" \xB7 "));
1117
+ const titleMatch = (item, match) => {
1118
+ const width = Array.from(item.title).length;
1119
+ return match.ranges.filter(([start]) => start < width).map(([start, end]) => [start, Math.min(end, width)]);
1120
+ };
1121
+ if (searching) {
1122
+ return results.map(({ item, match }) => ({
1123
+ kind: "item",
1124
+ key: item.key,
1125
+ item,
1126
+ titleRanges: titleMatch(item, match)
1127
+ }));
1128
+ }
1129
+ const order = new Map(state.sections.map(({ id }, index) => [id, index]));
1130
+ const groups = new Map;
1131
+ for (const { item } of results) {
1132
+ const section = item.section ?? null;
1133
+ const group = groups.get(section);
1134
+ if (group)
1135
+ group.push(item);
1136
+ else
1137
+ groups.set(section, [item]);
1138
+ }
1139
+ const ids = [...groups.keys()].sort((a, b) => {
1140
+ if (a === null)
1141
+ return -1;
1142
+ if (b === null)
1143
+ return 1;
1144
+ return (order.get(a) ?? Number.MAX_SAFE_INTEGER) - (order.get(b) ?? Number.MAX_SAFE_INTEGER);
1145
+ });
1146
+ const lines = [];
1147
+ for (const id of ids) {
1148
+ const group = groups.get(id) ?? [];
1149
+ if (id !== null) {
1150
+ const title = state.sections.find((section) => section.id === id)?.title ?? id;
1151
+ lines.push({ kind: "section", key: `\xA7${id}`, title, count: group.length });
1152
+ }
1153
+ for (const item of group)
1154
+ lines.push({ kind: "item", key: item.key, item, titleRanges: [] });
1155
+ }
1156
+ return lines;
1157
+ }
1158
+ function withLines(state, collection, queryChanged = false) {
1159
+ const lines = project(state);
1160
+ const keys = lines.filter((line) => line.kind === "item").map(({ key }) => key);
1161
+ let next = reduceTerminalCollection2(collection, { type: "reconcile", keys });
1162
+ if (queryChanged && state.query.trim() !== "" && keys[0] !== undefined) {
1163
+ next = reduceTerminalCollection2(next, { type: "select", key: keys[0] });
1164
+ }
1165
+ return { ...state, lines, collection: next };
1166
+ }
1167
+ function createTerminalList2(input) {
1168
+ const items = parseItems(input.items);
1169
+ const base = {
1170
+ items,
1171
+ sections: input.sections ?? [],
1172
+ query: "",
1173
+ picked: new Set,
1174
+ multiple: input.multiple ?? false,
1175
+ activation: null
1176
+ };
1177
+ const state = withLines(base, createTerminalCollection2([], 1));
1178
+ return input.selectedKey !== undefined && state.collection.keys.includes(input.selectedKey) ? {
1179
+ ...state,
1180
+ collection: reduceTerminalCollection2(state.collection, {
1181
+ type: "select",
1182
+ key: input.selectedKey
1183
+ })
1184
+ } : state;
1185
+ }
1186
+ function reduceTerminalList2(state, action) {
1187
+ const base = {
1188
+ items: state.items,
1189
+ sections: state.sections,
1190
+ query: state.query,
1191
+ picked: state.picked,
1192
+ multiple: state.multiple,
1193
+ activation: state.activation
1194
+ };
1195
+ switch (action.type) {
1196
+ case "items": {
1197
+ const items = parseItems(action.items);
1198
+ const keys = new Set(items.map(({ key }) => key));
1199
+ return withLines({
1200
+ ...base,
1201
+ items,
1202
+ sections: action.sections ?? state.sections,
1203
+ picked: new Set([...state.picked].filter((key) => keys.has(key)))
1204
+ }, state.collection);
1205
+ }
1206
+ case "query":
1207
+ case "query-edit": {
1208
+ const query = action.type === "query" ? z6.string().parse(action.query) : applyTerminalTextEdit2(state.query, action.edit);
1209
+ return query === state.query ? state : withLines({ ...base, query }, state.collection, true);
1210
+ }
1211
+ case "activate": {
1212
+ const item = selectedTerminalListItem2(state);
1213
+ if (!item || item.disabled)
1214
+ return state;
1215
+ return {
1216
+ ...state,
1217
+ activation: { key: item.key, serial: (state.activation?.serial ?? 0) + 1 }
1218
+ };
1219
+ }
1220
+ case "section": {
1221
+ const items = state.lines.filter((line) => line.kind === "item");
1222
+ const current = items.findIndex(({ key }) => key === state.collection.selectedKey);
1223
+ const sectionOf = (index) => {
1224
+ const line = items[index];
1225
+ return line?.kind === "item" ? line.item.section ?? "" : undefined;
1226
+ };
1227
+ const here = sectionOf(current);
1228
+ let index = current;
1229
+ const step = Math.sign(action.delta);
1230
+ if (step === 0)
1231
+ return state;
1232
+ while (index + step >= 0 && index + step < items.length && sectionOf(index) === here)
1233
+ index += step;
1234
+ if (step < 0) {
1235
+ const target = sectionOf(index);
1236
+ while (index - 1 >= 0 && sectionOf(index - 1) === target)
1237
+ index -= 1;
1238
+ }
1239
+ const key = items[index]?.key;
1240
+ return key === undefined ? state : {
1241
+ ...state,
1242
+ collection: reduceTerminalCollection2(state.collection, { type: "select", key })
1243
+ };
1244
+ }
1245
+ case "toggle": {
1246
+ if (!state.multiple)
1247
+ return state;
1248
+ const key = action.key ?? state.collection.selectedKey;
1249
+ const item = state.items.find((candidate) => candidate.key === key);
1250
+ if (!item || item.disabled)
1251
+ return state;
1252
+ const picked = new Set(state.picked);
1253
+ if (picked.has(item.key))
1254
+ picked.delete(item.key);
1255
+ else
1256
+ picked.add(item.key);
1257
+ return { ...state, picked };
1258
+ }
1259
+ case "pick-all": {
1260
+ if (!state.multiple)
1261
+ return state;
1262
+ const visible = state.lines.flatMap((line) => line.kind === "item" && !line.item.disabled ? [line.key] : []);
1263
+ const picked = new Set(state.picked);
1264
+ for (const key of visible) {
1265
+ if (action.picked)
1266
+ picked.add(key);
1267
+ else
1268
+ picked.delete(key);
1269
+ }
1270
+ return { ...state, picked };
1271
+ }
1272
+ default:
1273
+ return { ...state, collection: reduceTerminalCollection2(state.collection, action) };
1274
+ }
1275
+ }
1276
+ function selectedTerminalListItem2(state) {
1277
+ return state.items.find(({ key }) => key === state.collection.selectedKey) ?? null;
1278
+ }
1279
+ function visibleTerminalListLines2(state, height) {
1280
+ const rows = Math.max(1, height);
1281
+ const index = state.lines.findIndex((line) => line.kind === "item" && line.key === state.collection.selectedKey);
1282
+ const anchor = Math.max(0, index);
1283
+ let start = Math.max(0, Math.min(anchor - Math.floor(rows / 2), state.lines.length - rows));
1284
+ if (start > 0 && state.lines[start - 1]?.kind === "section" && anchor - start < rows - 1)
1285
+ start -= 1;
1286
+ const lines = state.lines.slice(start, start + rows);
1287
+ return {
1288
+ lines,
1289
+ above: start,
1290
+ below: Math.max(0, state.lines.length - start - lines.length)
1291
+ };
1292
+ }
1293
+
1294
+ // src/core/meter.ts
1295
+ import { z as z7 } from "zod";
1296
+ var EIGHTHS = ["", "\u258F", "\u258E", "\u258D", "\u258C", "\u258B", "\u258A", "\u2589"];
1297
+ var FULL = "\u2588";
1298
+ var TerminalMeterThresholdSchema2 = z7.object({
1299
+ ratio: z7.number().min(0).max(1),
1300
+ tone: TerminalToneSchema2
1301
+ }).strict();
1302
+ var defaultTerminalMeterThresholds2 = Object.freeze([
1303
+ { ratio: 0, tone: "success" },
1304
+ { ratio: 0.6, tone: "warning" },
1305
+ { ratio: 0.85, tone: "danger" }
1306
+ ]);
1307
+ var MeterInputSchema = z7.object({
1308
+ value: z7.number().nullable(),
1309
+ max: z7.number().positive(),
1310
+ width: z7.int().nonnegative(),
1311
+ thresholds: z7.array(TerminalMeterThresholdSchema2).min(1).optional()
1312
+ }).strict();
1313
+ function toneFor(ratio, thresholds) {
1314
+ const sorted = [...thresholds].sort((a, b) => a.ratio - b.ratio);
1315
+ let tone = sorted[0]?.tone ?? "success";
1316
+ for (const threshold of sorted) {
1317
+ if (ratio >= threshold.ratio)
1318
+ tone = threshold.tone;
1319
+ }
1320
+ return tone;
1321
+ }
1322
+ function terminalMeter2(input) {
1323
+ const { value, max, width, thresholds } = MeterInputSchema.parse(input);
1324
+ if (value === null) {
1325
+ return { filled: "", empty: " ".repeat(width), ratio: null, tone: "muted" };
1326
+ }
1327
+ const ratio = Math.min(1, Math.max(0, value / max));
1328
+ const eighths = Math.round(ratio * width * 8);
1329
+ const whole = Math.floor(eighths / 8);
1330
+ const partial = EIGHTHS[eighths % 8] ?? "";
1331
+ const filled = FULL.repeat(whole) + partial;
1332
+ const used = whole + (partial ? 1 : 0);
1333
+ return {
1334
+ filled,
1335
+ empty: " ".repeat(width - used),
1336
+ ratio,
1337
+ tone: toneFor(ratio, thresholds ?? defaultTerminalMeterThresholds2)
1338
+ };
1339
+ }
1340
+ var GridInputSchema = z7.object({
1341
+ count: z7.int().nonnegative(),
1342
+ width: z7.int().positive(),
1343
+ minMeterWidth: z7.int().positive(),
1344
+ gap: z7.int().nonnegative().default(1)
1345
+ }).strict();
1346
+ function layoutTerminalMeterGrid2(input) {
1347
+ const { count, width, minMeterWidth, gap } = GridInputSchema.parse(input);
1348
+ if (count === 0)
1349
+ return { columns: 0, rows: 0, meterWidth: width, cells: [] };
1350
+ const fit = Math.max(1, Math.floor((width + gap) / (minMeterWidth + gap)));
1351
+ const rows = Math.ceil(count / Math.min(count, fit));
1352
+ const columns = Math.ceil(count / rows);
1353
+ const meterWidth = Math.max(1, Math.floor((width - gap * (columns - 1)) / columns));
1354
+ const cells = Array.from({ length: rows }, (_, row) => Array.from({ length: columns }, (_, column) => column * rows + row).filter((index) => index < count));
1355
+ return { columns, rows, meterWidth, cells };
1356
+ }
1357
+
1358
+ // src/core/progress.ts
1359
+ import { z as z8 } from "zod";
1360
+ var TerminalSpinnerKindSchema2 = z8.enum(["dots", "line", "pulse", "arc"]);
1361
+ var terminalSpinners2 = Object.freeze({
1362
+ dots: { intervalMs: 80, frames: ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"] },
1363
+ line: { intervalMs: 120, frames: ["-", "\\", "|", "/"] },
1364
+ pulse: { intervalMs: 160, frames: ["\xB7", "\u2022", "\u25CF", "\u2022"] },
1365
+ arc: { intervalMs: 100, frames: ["\u25DC", "\u25E0", "\u25DD", "\u25DE", "\u25E1", "\u25DF"] }
1366
+ });
1367
+ function terminalSpinnerFrame2(kind, elapsedMs) {
1368
+ const spinner = terminalSpinners2[kind];
1369
+ const index = Math.floor(Math.max(0, elapsedMs) / spinner.intervalMs) % spinner.frames.length;
1370
+ return spinner.frames[index] ?? "";
1371
+ }
1372
+ function formatTerminalDuration2(ms) {
1373
+ const value = Math.max(0, ms);
1374
+ if (value < 1e4)
1375
+ return `${(value / 1000).toFixed(1)}s`;
1376
+ const seconds = Math.floor(value / 1000);
1377
+ if (seconds < 60)
1378
+ return `${seconds}s`;
1379
+ const minutes = Math.floor(seconds / 60);
1380
+ if (minutes < 60)
1381
+ return `${minutes}m ${String(seconds % 60).padStart(2, "0")}s`;
1382
+ return `${Math.floor(minutes / 60)}h ${String(minutes % 60).padStart(2, "0")}m`;
1383
+ }
1384
+ var ProgressInputSchema = z8.object({
1385
+ done: z8.number().nonnegative().nullable(),
1386
+ total: z8.number().positive().nullable(),
1387
+ startedAt: z8.number(),
1388
+ now: z8.number()
1389
+ }).strict();
1390
+ function terminalProgress2(input) {
1391
+ const { done, total, startedAt, now } = ProgressInputSchema.parse(input);
1392
+ const elapsedMs = Math.max(0, now - startedAt);
1393
+ const ratio = done === null || total === null ? null : Math.min(1, done / total);
1394
+ const rate = done === null || elapsedMs === 0 ? null : done * 1000 / elapsedMs;
1395
+ const etaMs = done === null || total === null || rate === null || rate === 0 ? null : Math.max(0, (total - done) / rate * 1000);
1396
+ return { ratio, elapsedMs, rate, etaMs };
1397
+ }
1398
+ function terminalIndeterminateBlock2(width, elapsedMs, periodMs = 1600) {
1399
+ const length = Math.max(1, Math.floor(width / 4));
1400
+ const travel = Math.max(0, width - length);
1401
+ const phase = Math.max(0, elapsedMs) % periodMs / periodMs;
1402
+ const position = phase < 0.5 ? phase * 2 : 2 - phase * 2;
1403
+ return [Math.round(position * travel), length];
1404
+ }
1405
+
1406
+ // src/core/table.ts
1407
+ import { z as z9 } from "zod";
1408
+ var TerminalTableColumnSchema2 = z9.object({
1409
+ id: z9.string().min(1),
1410
+ title: z9.string(),
1411
+ kind: z9.enum(["number", "text"]),
1412
+ width: z9.union([z9.int().positive(), z9.object({ flex: z9.int().positive() }).strict()]),
1413
+ align: z9.enum(["left", "right"]).optional(),
1414
+ sortable: z9.boolean().default(true),
1415
+ filterable: z9.boolean().optional()
1416
+ }).strict();
1417
+ var TerminalTableRowSchema2 = z9.object({
1418
+ key: z9.string().min(1),
1419
+ parentKey: z9.string().min(1).nullable().default(null),
1420
+ cells: z9.record(z9.string(), z9.union([z9.string(), z9.number(), z9.null()]))
1421
+ }).strict();
1422
+ var TerminalTableSortSchema2 = z9.object({ columnId: z9.string().min(1), direction: z9.enum(["asc", "desc"]) }).strict();
1423
+ var collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
1424
+ function parseColumns(columns) {
1425
+ if (columns.length === 0)
1426
+ throw new Error("A terminal table needs at least one column");
1427
+ const parsed = columns.map((column) => {
1428
+ const { format, ...shape } = column;
1429
+ const value = TerminalTableColumnSchema2.parse(shape);
1430
+ return format === undefined ? value : { ...value, format };
1431
+ });
1432
+ if (new Set(parsed.map(({ id }) => id)).size !== parsed.length) {
1433
+ throw new Error("Terminal table column ids must be unique");
1434
+ }
1435
+ return parsed;
1436
+ }
1437
+ function parseRows(columns, rows) {
1438
+ const parsed = z9.array(TerminalTableRowSchema2).parse(rows);
1439
+ const byKey = new Map;
1440
+ for (const row of parsed) {
1441
+ if (byKey.has(row.key))
1442
+ throw new Error(`Terminal table row keys must be unique: ${row.key}`);
1443
+ byKey.set(row.key, row);
1444
+ for (const column of columns) {
1445
+ if (!(column.id in row.cells)) {
1446
+ throw new Error(`Terminal table row ${row.key} has no cell for column ${column.id}`);
1447
+ }
1448
+ const value = row.cells[column.id];
1449
+ if (value !== null && typeof value !== (column.kind === "number" ? "number" : "string")) {
1450
+ throw new Error(`Terminal table row ${row.key} holds a ${typeof value} in ${column.kind} column ${column.id}`);
1451
+ }
1452
+ }
1453
+ }
1454
+ for (const row of parsed) {
1455
+ const seen = new Set([row.key]);
1456
+ for (let parent = row.parentKey;parent !== null; ) {
1457
+ if (seen.has(parent))
1458
+ throw new Error(`Terminal table rows form a cycle through ${parent}`);
1459
+ seen.add(parent);
1460
+ parent = byKey.get(parent)?.parentKey ?? null;
1461
+ }
1462
+ }
1463
+ return parsed;
1464
+ }
1465
+ function formatTerminalTableCell2(column, value) {
1466
+ if (value === null)
1467
+ return "\u2014";
1468
+ return sanitizeTerminalText2(column.format ? column.format(value) : String(value)).replace(/\n/g, " ");
1469
+ }
1470
+ function sortColumn(state) {
1471
+ if (state.sort === null)
1472
+ return null;
1473
+ return state.columns.find(({ id }) => id === state.sort?.columnId) ?? null;
1474
+ }
1475
+ function compareRows(column, direction) {
1476
+ return (a, b) => {
1477
+ if (column !== null) {
1478
+ const left = a.cells[column.id] ?? null;
1479
+ const right = b.cells[column.id] ?? null;
1480
+ if (left === null && right !== null)
1481
+ return 1;
1482
+ if (right === null && left !== null)
1483
+ return -1;
1484
+ if (left !== null && right !== null) {
1485
+ const order = typeof left === "number" && typeof right === "number" ? left - right : collator.compare(String(left), String(right));
1486
+ if (order !== 0)
1487
+ return direction === "asc" ? order : -order;
1488
+ }
1489
+ }
1490
+ return a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
1491
+ };
1492
+ }
1493
+ function projectTerminalTable2(state) {
1494
+ const keys = new Set(state.rows.map(({ key }) => key));
1495
+ const children = new Map;
1496
+ for (const row of state.rows) {
1497
+ const parent = row.parentKey !== null && keys.has(row.parentKey) ? row.parentKey : null;
1498
+ const siblings = children.get(parent);
1499
+ if (siblings)
1500
+ siblings.push(row);
1501
+ else
1502
+ children.set(parent, [row]);
1503
+ }
1504
+ const compare = compareRows(sortColumn(state), state.sort?.direction ?? "asc");
1505
+ for (const siblings of children.values())
1506
+ siblings.sort(compare);
1507
+ const query = state.filter.trim().toLocaleLowerCase();
1508
+ const matched = new Set;
1509
+ const shown = new Set;
1510
+ if (query !== "") {
1511
+ const searched = state.columns.filter((column) => column.filterable ?? column.kind === "text");
1512
+ const byKey = new Map(state.rows.map((row) => [row.key, row]));
1513
+ for (const row of state.rows) {
1514
+ const hit = searched.some((column) => formatTerminalTableCell2(column, row.cells[column.id] ?? null).toLocaleLowerCase().includes(query));
1515
+ if (!hit)
1516
+ continue;
1517
+ matched.add(row.key);
1518
+ for (let key = row.key;key !== null && !shown.has(key); ) {
1519
+ shown.add(key);
1520
+ const parent = byKey.get(key)?.parentKey ?? null;
1521
+ key = parent !== null && keys.has(parent) ? parent : null;
1522
+ }
1523
+ }
1524
+ }
1525
+ const view = [];
1526
+ const visit = (parent, depth) => {
1527
+ for (const row of children.get(parent) ?? []) {
1528
+ if (query !== "" && !shown.has(row.key))
1529
+ continue;
1530
+ const hasChildren = (children.get(row.key) ?? []).some((child) => query === "" || shown.has(child.key));
1531
+ const expanded = hasChildren && (query !== "" || state.expanded.has(row.key));
1532
+ view.push({
1533
+ row,
1534
+ depth,
1535
+ hasChildren,
1536
+ expanded,
1537
+ matched: query === "" || matched.has(row.key)
1538
+ });
1539
+ if (expanded)
1540
+ visit(row.key, depth + 1);
1541
+ }
1542
+ };
1543
+ visit(null, 0);
1544
+ return view;
1545
+ }
1546
+ function withView(state, collection, fallback) {
1547
+ const view = projectTerminalTable2(state);
1548
+ const keys = view.map(({ row }) => row.key);
1549
+ const lost = collection.selectedKey !== null && !keys.includes(collection.selectedKey);
1550
+ let next = reduceTerminalCollection2(collection, { type: "reconcile", keys });
1551
+ if (lost && fallback !== undefined && keys.includes(fallback)) {
1552
+ next = reduceTerminalCollection2(next, { type: "select", key: fallback });
1553
+ }
1554
+ return { ...state, activation: state.activation ?? null, view, collection: next };
1555
+ }
1556
+ function createTerminalTable2(input) {
1557
+ const columns = parseColumns(input.columns);
1558
+ const rows = parseRows(columns, input.rows ?? []);
1559
+ const sort = input.sort ? TerminalTableSortSchema2.parse(input.sort) : null;
1560
+ if (sort && !columns.some(({ id, sortable }) => id === sort.columnId && sortable)) {
1561
+ throw new Error(`Terminal table cannot sort by column ${sort.columnId}`);
1562
+ }
1563
+ const keys = new Set(rows.map(({ key }) => key));
1564
+ return withView({
1565
+ columns,
1566
+ rows,
1567
+ sort,
1568
+ expanded: new Set((input.expanded ?? []).filter((key) => keys.has(key))),
1569
+ filter: ""
1570
+ }, createTerminalCollection2([], input.capacity));
1571
+ }
1572
+ function selectedRow(state, key) {
1573
+ const target = key ?? state.collection.selectedKey;
1574
+ return state.view.find(({ row }) => row.key === target) ?? null;
1575
+ }
1576
+ function reduceTerminalTable2(state, action) {
1577
+ const { collection } = state;
1578
+ const base = {
1579
+ columns: state.columns,
1580
+ rows: state.rows,
1581
+ sort: state.sort,
1582
+ expanded: state.expanded,
1583
+ filter: state.filter,
1584
+ activation: state.activation
1585
+ };
1586
+ switch (action.type) {
1587
+ case "rows": {
1588
+ const rows = parseRows(base.columns, action.rows);
1589
+ const keys = new Set(rows.map(({ key }) => key));
1590
+ const expanded = new Set([...base.expanded].filter((key) => keys.has(key)));
1591
+ return withView({ ...base, rows, expanded }, collection);
1592
+ }
1593
+ case "sort": {
1594
+ const column = base.columns.find(({ id }) => id === action.columnId);
1595
+ if (!column?.sortable)
1596
+ throw new Error(`Terminal table cannot sort by column ${action.columnId}`);
1597
+ const direction = action.direction ?? (base.sort?.columnId === column.id ? base.sort.direction === "asc" ? "desc" : "asc" : column.kind === "number" ? "desc" : "asc");
1598
+ return withView({ ...base, sort: { columnId: column.id, direction } }, collection);
1599
+ }
1600
+ case "sort-next": {
1601
+ const sortable = base.columns.filter(({ sortable }) => sortable);
1602
+ if (sortable.length === 0)
1603
+ return state;
1604
+ const index = sortable.findIndex(({ id }) => id === base.sort?.columnId);
1605
+ const step = z9.int().parse(action.delta);
1606
+ const next = sortable[(((index < 0 ? step > 0 ? -1 : 0 : index) + step) % sortable.length + sortable.length) % sortable.length];
1607
+ if (!next)
1608
+ return state;
1609
+ return withView({
1610
+ ...base,
1611
+ sort: { columnId: next.id, direction: next.kind === "number" ? "desc" : "asc" }
1612
+ }, collection);
1613
+ }
1614
+ case "sort-invert": {
1615
+ if (base.sort === null)
1616
+ return state;
1617
+ return withView({
1618
+ ...base,
1619
+ sort: { ...base.sort, direction: base.sort.direction === "asc" ? "desc" : "asc" }
1620
+ }, collection);
1621
+ }
1622
+ case "expand":
1623
+ case "collapse":
1624
+ case "toggle": {
1625
+ const target = selectedRow(state, action.key);
1626
+ if (target === null || state.filter.trim() !== "")
1627
+ return state;
1628
+ const open = action.type === "expand" ? true : action.type === "collapse" ? false : !target.expanded;
1629
+ if (!target.hasChildren || target.expanded === open) {
1630
+ if (action.type === "collapse" && action.key === undefined && target.row.parentKey) {
1631
+ const parent = state.view.find(({ row }) => row.key === target.row.parentKey);
1632
+ if (parent) {
1633
+ return {
1634
+ ...state,
1635
+ collection: reduceTerminalCollection2(collection, {
1636
+ type: "select",
1637
+ key: parent.row.key
1638
+ })
1639
+ };
1640
+ }
1641
+ }
1642
+ return state;
1643
+ }
1644
+ const expanded = new Set(base.expanded);
1645
+ if (open)
1646
+ expanded.add(target.row.key);
1647
+ else
1648
+ expanded.delete(target.row.key);
1649
+ return withView({ ...base, expanded }, collection, open ? undefined : target.row.key);
1650
+ }
1651
+ case "filter":
1652
+ return withView({ ...base, filter: z9.string().parse(action.query) }, collection);
1653
+ case "activate": {
1654
+ const key = state.collection.selectedKey;
1655
+ if (key === null)
1656
+ return state;
1657
+ return { ...state, activation: { key, serial: (state.activation?.serial ?? 0) + 1 } };
1658
+ }
1659
+ case "filter-edit": {
1660
+ const filter = applyTerminalTextEdit2(state.filter, action.edit);
1661
+ return filter === state.filter ? state : withView({ ...base, filter }, collection);
1662
+ }
1663
+ default:
1664
+ return { ...state, collection: reduceTerminalCollection2(collection, action) };
1665
+ }
1666
+ }
1667
+ function visibleTerminalTableRows2(state) {
1668
+ const { start, capacity } = state.collection;
1669
+ return state.view.slice(start, start + capacity);
1670
+ }
1671
+ function selectedTerminalTableRow2(state) {
1672
+ return selectedRow(state)?.row ?? null;
1673
+ }
1674
+ function layoutTerminalTableColumns2(columns, width, gap = 1) {
1675
+ const total = z9.int().nonnegative().parse(width);
1676
+ let remaining = total;
1677
+ const widths = columns.map((column, index) => {
1678
+ if (typeof column.width !== "number")
1679
+ return { id: column.id, width: 0 };
1680
+ const needed = column.width + (index === 0 ? 0 : gap);
1681
+ if (needed > remaining)
1682
+ return { id: column.id, width: 0 };
1683
+ remaining -= needed;
1684
+ return { id: column.id, width: column.width };
1685
+ });
1686
+ const flexible = columns.map((column, index) => ({ column, index })).filter(({ column }) => typeof column.width !== "number");
1687
+ const gaps = flexible.filter(({ index }) => index > 0).length * gap;
1688
+ const share = Math.max(0, remaining - gaps);
1689
+ const weights = flexible.reduce((sum, { column }) => sum + (typeof column.width === "number" ? 0 : column.width.flex), 0);
1690
+ let given = 0;
1691
+ flexible.forEach(({ column, index }, position) => {
1692
+ if (typeof column.width === "number")
1693
+ return;
1694
+ const cells = position === flexible.length - 1 ? share - given : Math.floor(share * column.width.flex / Math.max(1, weights));
1695
+ given += cells;
1696
+ widths[index] = { id: column.id, width: Math.max(0, cells) };
1697
+ });
1698
+ return widths;
1699
+ }
1700
+ function terminalTableTreePrefix2(row) {
1701
+ const mark = row.hasChildren ? row.expanded ? "\u25BE " : "\u25B8 " : " ";
1702
+ return " ".repeat(row.depth) + mark;
1703
+ }
1704
+
1705
+ export { matchTerminalSearch2, searchTerminalItems2, terminalHighlightRuns2, TerminalToneSchema2, TerminalThemeModeSchema2, TerminalPaletteSchema2, terminalPalettes2, resolveTerminalPalette2, createTerminalTimeSeries2, appendTerminalSample2, sampleTerminalTimeSeries2, terminalChartScale2, terminalSparkline2, terminalBrailleChart2, terminalTimeAxis2, TerminalCollectionStateSchema2, createTerminalCollection2, reduceTerminalCollection2, visibleTerminalCollectionRange2, sanitizeTerminalText2, terminalGraphemes2, terminalGraphemeWidth2, terminalTextWidth2, truncateTerminalText2, fitTerminalText2, wrapTerminalText2, terminalTextEdit2, applyTerminalTextEdit2, TerminalFormFieldSchema2, terminalFormMessages2, createTerminalForm2, readTerminalForm2, reduceTerminalForm2, terminalFormFieldsFromJsonSchema2, terminalJsonLines2, layoutTerminalDetails2, TerminalKeyBindingSchema2, defineTerminalKeymap2, matchTerminalKey2, fitTerminalKeyHints2, terminalLabelsEn2, terminalLabelsRu2, terminalTableKeymap2, terminalTableKey2, terminalTabsKeymap2, terminalTabsKey2, TerminalListItemSchema2, createTerminalList2, reduceTerminalList2, selectedTerminalListItem2, visibleTerminalListLines2, TerminalMeterThresholdSchema2, defaultTerminalMeterThresholds2, terminalMeter2, layoutTerminalMeterGrid2, TerminalSpinnerKindSchema2, terminalSpinners2, terminalSpinnerFrame2, formatTerminalDuration2, terminalProgress2, terminalIndeterminateBlock2, TerminalTableColumnSchema2, TerminalTableRowSchema2, TerminalTableSortSchema2, formatTerminalTableCell2, projectTerminalTable2, createTerminalTable2, reduceTerminalTable2, visibleTerminalTableRows2, selectedTerminalTableRow2, layoutTerminalTableColumns2, terminalTableTreePrefix2 };