cursor-switch 1.0.6 → 1.0.8

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 (84) hide show
  1. package/README.md +76 -75
  2. package/SECURITY.md +22 -19
  3. package/bin/cswitch.js +31 -8
  4. package/dist/cli.d.ts +0 -4
  5. package/dist/cli.js +404 -225
  6. package/dist/core/account-store.d.ts +0 -7
  7. package/dist/core/account-store.js +22 -28
  8. package/dist/core/cdp-engine.d.ts +11 -49
  9. package/dist/core/cdp-engine.js +155 -110
  10. package/dist/core/config-store.d.ts +7 -6
  11. package/dist/core/config-store.js +33 -12
  12. package/dist/core/cursor-paths.d.ts +8 -18
  13. package/dist/core/cursor-paths.js +18 -37
  14. package/dist/core/dashboard-launcher.d.ts +2 -22
  15. package/dist/core/dashboard-launcher.js +10 -60
  16. package/dist/core/extract-client.d.ts +57 -0
  17. package/dist/core/extract-client.js +219 -0
  18. package/dist/core/extract-menu.d.ts +3 -0
  19. package/dist/core/extract-menu.js +360 -0
  20. package/dist/core/extract-service.d.ts +64 -0
  21. package/dist/core/extract-service.js +435 -0
  22. package/dist/core/fingerprint.d.ts +0 -4
  23. package/dist/core/fingerprint.js +0 -6
  24. package/dist/core/oauth-receiver.d.ts +1 -11
  25. package/dist/core/oauth-receiver.js +509 -527
  26. package/dist/core/official-api.d.ts +0 -17
  27. package/dist/core/official-api.js +4 -23
  28. package/dist/core/outlook-launcher.d.ts +0 -27
  29. package/dist/core/outlook-launcher.js +235 -261
  30. package/dist/core/process-manager.d.ts +0 -14
  31. package/dist/core/process-manager.js +7 -22
  32. package/dist/core/pure-login-service.d.ts +64 -28
  33. package/dist/core/pure-login-service.js +527 -346
  34. package/dist/core/refund-client.d.ts +0 -22
  35. package/dist/core/refund-client.js +7 -27
  36. package/dist/core/refund-service.d.ts +0 -16
  37. package/dist/core/refund-service.js +8 -34
  38. package/dist/core/safe-storage.d.ts +27 -0
  39. package/dist/core/safe-storage.js +284 -0
  40. package/dist/core/sqlite-bridge.d.ts +10 -11
  41. package/dist/core/sqlite-bridge.js +112 -47
  42. package/dist/core/storage-bridge.d.ts +14 -5
  43. package/dist/core/storage-bridge.js +84 -24
  44. package/dist/core/switch-orchestrator.d.ts +96 -0
  45. package/dist/core/switch-orchestrator.js +341 -0
  46. package/dist/core/token-exchange.d.ts +81 -0
  47. package/dist/core/token-exchange.js +275 -0
  48. package/dist/core/token-parser.d.ts +56 -20
  49. package/dist/core/token-parser.js +354 -43
  50. package/dist/core/update-checker.d.ts +1 -29
  51. package/dist/core/update-checker.js +28 -43
  52. package/dist/index.d.ts +1 -3
  53. package/dist/index.js +1 -3
  54. package/dist/menu.d.ts +0 -7
  55. package/dist/menu.js +445 -538
  56. package/dist/types.d.ts +12 -4
  57. package/dist/types.js +0 -4
  58. package/dist/utils/account-text-importer.d.ts +9 -0
  59. package/dist/utils/account-text-importer.js +96 -0
  60. package/dist/utils/browser-utils.d.ts +0 -24
  61. package/dist/utils/browser-utils.js +0 -57
  62. package/dist/utils/clipboard.d.ts +0 -4
  63. package/dist/utils/clipboard.js +0 -5
  64. package/dist/utils/credential-bundle-ui.d.ts +36 -0
  65. package/dist/utils/credential-bundle-ui.js +246 -0
  66. package/dist/utils/live-menu.d.ts +37 -9
  67. package/dist/utils/live-menu.js +510 -81
  68. package/dist/utils/plan-formatter.d.ts +0 -26
  69. package/dist/utils/plan-formatter.js +10 -44
  70. package/dist/utils/prompt-utils.d.ts +0 -18
  71. package/dist/utils/prompt-utils.js +0 -23
  72. package/dist/utils/proxy-bootstrap.d.ts +12 -0
  73. package/dist/utils/proxy-bootstrap.js +141 -0
  74. package/dist/utils/security.d.ts +2 -4
  75. package/dist/utils/security.js +36 -4
  76. package/dist/utils/table-renderer.d.ts +0 -4
  77. package/dist/utils/table-renderer.js +24 -8
  78. package/dist/utils/time-formatter.d.ts +0 -4
  79. package/dist/utils/time-formatter.js +0 -8
  80. package/dist/utils/token-preflight-ui.d.ts +28 -0
  81. package/dist/utils/token-preflight-ui.js +222 -0
  82. package/dist/utils/window-focus.d.ts +3 -0
  83. package/dist/utils/window-focus.js +106 -0
  84. package/package.json +12 -5
@@ -1,17 +1,364 @@
1
- /**
2
- * 现代终端极速响应式交互菜单引擎 (Live & Quick TUI Engine)
3
- * 支持:
4
- * 1. 单键快捷直达 (按 0, 1, 2, s, q, Esc 键无需按回车直接触发秒选)
5
- * 2. 方向键平滑巡览与动态说明 (↑↓ 移动光标,↵ 回车确认)
6
- * 3. 毫秒级无闪烁响应式时钟 (主界面 HUD 每秒平滑走字)
7
- */
8
- import { createPrompt, useState, useEffect, useKeypress, usePagination, Separator, isUpKey, isDownKey, isEnterKey, } from '@inquirer/core';
1
+ import fs from 'node:fs';
2
+ import { Writable } from 'node:stream';
3
+ import { stripVTControlCharacters } from 'node:util';
4
+ import { createPrompt, useState, useEffect, useRef, useKeypress, usePagination, Separator, isUpKey, isDownKey, isEnterKey, } from '@inquirer/core';
9
5
  import chalk from 'chalk';
10
- export const quickSelect = createPrompt((config, done) => {
11
- const { pageSize = 12, tickIntervalMs = 0 } = config;
6
+ const ENTER_ALT_SCREEN = '\x1b[?1049h\x1b[?25l';
7
+ const LEAVE_ALT_SCREEN = '\x1b[?1049l\x1b[?25h';
8
+ const SYNC_BEGIN = '\x1b[?2026h';
9
+ const SYNC_END = '\x1b[?2026l';
10
+ let activeAltScreenStream = null;
11
+ function isWideCodePoint(cp) {
12
+ return ((cp >= 0x1100 && cp <= 0x115f) ||
13
+ cp === 0x231a ||
14
+ cp === 0x231b ||
15
+ cp === 0x2329 ||
16
+ cp === 0x232a ||
17
+ (cp >= 0x23e9 && cp <= 0x23ec) ||
18
+ cp === 0x23f0 ||
19
+ cp === 0x23f3 ||
20
+ cp === 0x25fd ||
21
+ cp === 0x25fe ||
22
+ cp === 0x2614 ||
23
+ cp === 0x2615 ||
24
+ (cp >= 0x2648 && cp <= 0x2653) ||
25
+ cp === 0x267f ||
26
+ cp === 0x2693 ||
27
+ cp === 0x26a1 ||
28
+ cp === 0x26aa ||
29
+ cp === 0x26ab ||
30
+ cp === 0x26bd ||
31
+ cp === 0x26be ||
32
+ cp === 0x26c4 ||
33
+ cp === 0x26c5 ||
34
+ cp === 0x26ce ||
35
+ cp === 0x26d4 ||
36
+ cp === 0x26ea ||
37
+ cp === 0x26f2 ||
38
+ cp === 0x26f3 ||
39
+ cp === 0x26f5 ||
40
+ cp === 0x26fa ||
41
+ cp === 0x26fd ||
42
+ cp === 0x2705 ||
43
+ cp === 0x270a ||
44
+ cp === 0x270b ||
45
+ cp === 0x2728 ||
46
+ cp === 0x274c ||
47
+ cp === 0x274e ||
48
+ (cp >= 0x2753 && cp <= 0x2755) ||
49
+ cp === 0x2757 ||
50
+ (cp >= 0x2795 && cp <= 0x2797) ||
51
+ cp === 0x27b0 ||
52
+ cp === 0x27bf ||
53
+ cp === 0x2b1b ||
54
+ cp === 0x2b1c ||
55
+ cp === 0x2b50 ||
56
+ cp === 0x2b55 ||
57
+ (cp >= 0x2e80 && cp <= 0x303e) ||
58
+ (cp >= 0x3040 && cp <= 0x3247) ||
59
+ (cp >= 0x3250 && cp <= 0x4dbf) ||
60
+ (cp >= 0x4e00 && cp <= 0xa4cf) ||
61
+ (cp >= 0xa960 && cp <= 0xa97f) ||
62
+ (cp >= 0xac00 && cp <= 0xd7a3) ||
63
+ (cp >= 0xf900 && cp <= 0xfaff) ||
64
+ (cp >= 0xfe10 && cp <= 0xfe19) ||
65
+ (cp >= 0xfe30 && cp <= 0xfe6f) ||
66
+ (cp >= 0xff01 && cp <= 0xff60) ||
67
+ (cp >= 0xffe0 && cp <= 0xffe6) ||
68
+ cp === 0x1f004 ||
69
+ cp === 0x1f0cf ||
70
+ cp === 0x1f18e ||
71
+ (cp >= 0x1f191 && cp <= 0x1f19a) ||
72
+ (cp >= 0x1f200 && cp <= 0x1f2ff) ||
73
+ (cp >= 0x1f300 && cp <= 0x1f64f) ||
74
+ (cp >= 0x1f680 && cp <= 0x1f6ff) ||
75
+ (cp >= 0x1f900 && cp <= 0x1faff) ||
76
+ (cp >= 0x20000 && cp <= 0x3fffd));
77
+ }
78
+ function getCodePointDisplayWidth(cp, nextCp) {
79
+ if (cp <= 0x1f ||
80
+ (cp >= 0x7f && cp <= 0x9f) ||
81
+ (cp >= 0x0300 && cp <= 0x036f) ||
82
+ (cp >= 0x1ab0 && cp <= 0x1aff) ||
83
+ (cp >= 0x1dc0 && cp <= 0x1dff) ||
84
+ (cp >= 0x200b && cp <= 0x200f) ||
85
+ (cp >= 0x202a && cp <= 0x202e) ||
86
+ (cp >= 0x2060 && cp <= 0x206f) ||
87
+ (cp >= 0x20d0 && cp <= 0x20ff) ||
88
+ (cp >= 0xfe00 && cp <= 0xfe0f) ||
89
+ (cp >= 0xfe20 && cp <= 0xfe2f) ||
90
+ cp === 0xfeff ||
91
+ (cp >= 0xe0100 && cp <= 0xe01ef)) {
92
+ return 0;
93
+ }
94
+ if (nextCp === 0xfe0f) {
95
+ return 2;
96
+ }
97
+ return isWideCodePoint(cp) ? 2 : 1;
98
+ }
99
+ export function measureAnsiWidth(text) {
100
+ const plain = stripVTControlCharacters(text || '');
101
+ let width = 0;
102
+ for (let i = 0; i < plain.length;) {
103
+ const cp = plain.codePointAt(i);
104
+ const step = cp > 0xffff ? 2 : 1;
105
+ const nextCp = i + step < plain.length ? plain.codePointAt(i + step) : undefined;
106
+ width += getCodePointDisplayWidth(cp, nextCp);
107
+ i += step;
108
+ }
109
+ return width;
110
+ }
111
+ function matchEscapeSequenceLength(text, start) {
112
+ if (text[start] !== '\x1b')
113
+ return 0;
114
+ const rest = text.slice(start);
115
+ const csi = rest.match(/^\x1b\[[0-?]*[ -/]*[@-~]/);
116
+ if (csi)
117
+ return csi[0].length;
118
+ const osc = rest.match(/^\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/);
119
+ if (osc)
120
+ return osc[0].length;
121
+ return Math.min(2, rest.length);
122
+ }
123
+ export function truncateAnsiLine(text, maxCols) {
124
+ if (maxCols <= 0)
125
+ return '';
126
+ if (measureAnsiWidth(text) <= maxCols)
127
+ return text;
128
+ const limit = maxCols >= 2 ? maxCols - 1 : maxCols;
129
+ let out = '';
130
+ let used = 0;
131
+ let sawAnsi = false;
132
+ for (let i = 0; i < text.length;) {
133
+ if (text[i] === '\x1b') {
134
+ const escLen = matchEscapeSequenceLength(text, i);
135
+ out += text.slice(i, i + escLen);
136
+ sawAnsi = true;
137
+ i += escLen;
138
+ continue;
139
+ }
140
+ const cp = text.codePointAt(i);
141
+ const step = cp > 0xffff ? 2 : 1;
142
+ const nextIdx = i + step;
143
+ const nextCp = nextIdx < text.length && text[nextIdx] !== '\x1b' ? text.codePointAt(nextIdx) : undefined;
144
+ const w = getCodePointDisplayWidth(cp, nextCp);
145
+ if (used + w > limit) {
146
+ break;
147
+ }
148
+ out += text.slice(i, nextIdx);
149
+ used += w;
150
+ i = nextIdx;
151
+ if (nextCp === 0xfe0f) {
152
+ out += text.slice(i, i + 1);
153
+ i += 1;
154
+ }
155
+ }
156
+ if (maxCols >= 2) {
157
+ out += '…';
158
+ }
159
+ if (sawAnsi) {
160
+ out += '\x1b[0m';
161
+ }
162
+ return out;
163
+ }
164
+ export function computeMenuViewport(input) {
165
+ const rows = Math.max(1, input.terminalRows || 24);
166
+ const cols = Math.max(2, input.terminalCols || 80);
167
+ const safeCols = Math.max(1, cols - 1);
168
+ const safetyMargin = input.altScreen ? 0 : 1;
169
+ const maxTotalLines = Math.max(1, rows - safetyMargin);
170
+ let headerLines = input.rawHeader
171
+ ? input.rawHeader
172
+ .split(/\r?\n/)
173
+ .map((line) => truncateAnsiLine(line, safeCols))
174
+ : [];
175
+ let leadingBlank = !input.altScreen && headerLines.length === 0 ? 1 : 0;
176
+ let promptLines = input.message
177
+ ? [truncateAnsiLine(` ${chalk.cyan('●')} ${chalk.bold.white(input.message)}`, safeCols)]
178
+ : [];
179
+ let showDesc = true;
180
+ let showHelp = true;
181
+ const totalItems = Math.max(0, input.totalItems);
182
+ const minDesiredList = Math.min(totalItems, 3);
183
+ const calcFixedLines = () => leadingBlank + headerLines.length + promptLines.length + (showDesc ? 1 : 0) + (showHelp ? 1 : 0);
184
+ if (maxTotalLines - calcFixedLines() < minDesiredList && leadingBlank > 0) {
185
+ leadingBlank = 0;
186
+ }
187
+ if (maxTotalLines - calcFixedLines() < minDesiredList) {
188
+ showDesc = false;
189
+ }
190
+ if (maxTotalLines - calcFixedLines() < minDesiredList) {
191
+ showHelp = false;
192
+ }
193
+ if (maxTotalLines - calcFixedLines() < minDesiredList && headerLines.length > 0) {
194
+ const keepHeader = Math.max(0, maxTotalLines - (leadingBlank + promptLines.length + (showDesc ? 1 : 0) + (showHelp ? 1 : 0) + Math.min(totalItems, 2)));
195
+ headerLines = headerLines.slice(0, keepHeader);
196
+ }
197
+ if (maxTotalLines - calcFixedLines() < 1 && promptLines.length > 0) {
198
+ promptLines = [];
199
+ }
200
+ const finalPromptLines = leadingBlank > 0 ? ['', ...promptLines] : promptLines;
201
+ const fixedWithoutFooter = headerLines.length + finalPromptLines.length;
202
+ const footerCount = (showDesc ? 1 : 0) + (showHelp ? 1 : 0);
203
+ const availableListRows = Math.max(1, maxTotalLines - fixedWithoutFooter - footerCount);
204
+ const effectivePageSize = Math.max(1, Math.min(Math.max(1, input.requestedPageSize), Math.max(1, totalItems), availableListRows));
205
+ const isPaginated = totalItems > effectivePageSize;
206
+ const moveHint = isPaginated ? '[↑↓] 移动(可滚动)' : '[↑↓] 移动';
207
+ const footerLines = [];
208
+ if (showDesc) {
209
+ footerLines.push(input.description
210
+ ? truncateAnsiLine(` ${chalk.dim('›')} ${chalk.cyan(input.description)}`, safeCols)
211
+ : '');
212
+ }
213
+ if (showHelp) {
214
+ footerLines.push(truncateAnsiLine(` ${chalk.dim(`${moveHint} [↵] 确认 [数字/字母] 直达 [Esc/q] 返回 [Ctrl+C] 退出`)}`, safeCols));
215
+ }
216
+ return {
217
+ safeCols,
218
+ headerLines,
219
+ promptLines: finalPromptLines,
220
+ effectivePageSize,
221
+ footerLines,
222
+ maxTotalLines,
223
+ };
224
+ }
225
+ function enterAltScreen(output) {
226
+ if (activeAltScreenStream === output)
227
+ return;
228
+ if (activeAltScreenStream) {
229
+ leaveAltScreenIfActive();
230
+ }
231
+ activeAltScreenStream = output;
232
+ output.write(ENTER_ALT_SCREEN);
233
+ }
234
+ export function leaveAltScreenIfActive() {
235
+ const stream = activeAltScreenStream;
236
+ if (!stream)
237
+ return;
238
+ activeAltScreenStream = null;
239
+ try {
240
+ stream.write(LEAVE_ALT_SCREEN);
241
+ }
242
+ catch { }
243
+ }
244
+ function leaveAltScreenIfActiveSync() {
245
+ const stream = activeAltScreenStream;
246
+ if (!stream)
247
+ return;
248
+ activeAltScreenStream = null;
249
+ const fd = typeof stream.fd === 'number' ? stream.fd : 1;
250
+ try {
251
+ fs.writeSync(fd, LEAVE_ALT_SCREEN);
252
+ }
253
+ catch {
254
+ try {
255
+ stream.write(LEAVE_ALT_SCREEN);
256
+ }
257
+ catch { }
258
+ }
259
+ }
260
+ globalThis.__cswitchLeaveAltScreen = leaveAltScreenIfActive;
261
+ function createSilentTtySink(target) {
262
+ const sink = new Writable({
263
+ write(_chunk, _encoding, callback) {
264
+ callback();
265
+ },
266
+ });
267
+ Object.defineProperties(sink, {
268
+ isTTY: { get: () => Boolean(target.isTTY) },
269
+ columns: { get: () => target.columns || 80 },
270
+ rows: { get: () => target.rows || 24 },
271
+ });
272
+ sink.getWindowSize = () => [target.columns || 80, target.rows || 24];
273
+ return sink;
274
+ }
275
+ const isSelectableChoice = (item) => !Separator.isSeparator(item) && !item?.disabled;
276
+ export function computeMenuPanelGeometry(items, headerLines, safeCols) {
277
+ const headerWidth = headerLines.reduce((max, line) => Math.max(max, measureAnsiWidth(line)), 0);
278
+ const maxMeasuredNameWidth = items.reduce((max, entry) => {
279
+ if (!isSelectableChoice(entry))
280
+ return max;
281
+ const w = measureAnsiWidth(entry.name);
282
+ return w <= 42 ? Math.max(max, w) : max;
283
+ }, 20);
284
+ const nameColWidth = Math.min(36, Math.max(20, maxMeasuredNameWidth));
285
+ const maxDesiredRowWidth = items.reduce((max, entry) => {
286
+ if (!isSelectableChoice(entry))
287
+ return max;
288
+ const plainName = stripVTControlCharacters(entry.name || '');
289
+ const nameW = measureAnsiWidth(plainName);
290
+ const explicitHint = typeof entry.hint === 'string' ? stripVTControlCharacters(entry.hint).trim() : '';
291
+ const explicitShortHint = typeof entry.shortHint === 'string' ? stripVTControlCharacters(entry.shortHint).trim() : '';
292
+ const fallbackDesc = explicitHint
293
+ ? ''
294
+ : stripVTControlCharacters(entry.description || '').trim();
295
+ const rawHint = explicitHint || fallbackDesc;
296
+ if (!rawHint || nameW > nameColWidth + 2) {
297
+ return Math.max(max, 4 + nameW + 2);
298
+ }
299
+ const gap = Math.max(2, nameColWidth - nameW + 3);
300
+ const desired = 4 + nameW + gap + measureAnsiWidth(rawHint) + 2;
301
+ if (explicitHint) {
302
+ if (desired <= safeCols) {
303
+ return Math.max(max, desired);
304
+ }
305
+ if (explicitShortHint) {
306
+ return Math.max(max, 4 + nameW + gap + measureAnsiWidth(explicitShortHint) + 2);
307
+ }
308
+ return Math.max(max, desired);
309
+ }
310
+ if (desired > safeCols) {
311
+ return Math.max(max, 4 + nameW + 2);
312
+ }
313
+ return Math.max(max, desired);
314
+ }, 72);
315
+ const panelWidth = Math.min(safeCols, Math.max(headerWidth, maxDesiredRowWidth, 72));
316
+ return { panelWidth, nameColWidth };
317
+ }
318
+ export function computeHudInnerWidth(items, cols, minLinesWidth = 0) {
319
+ const safeCols = Math.max(40, cols - 1);
320
+ const maxInnerByCols = Math.max(40, cols - 5);
321
+ const menuGeom = computeMenuPanelGeometry(items, [], safeCols);
322
+ const contentFitInner = Math.max(72, menuGeom.panelWidth - 2);
323
+ const desired = Math.max(contentFitInner, minLinesWidth);
324
+ return Math.max(40, Math.min(desired, maxInnerByCols));
325
+ }
326
+ export function resolveQuickShortcut(items, rawChar) {
327
+ const char = (rawChar || '').toLowerCase();
328
+ if (!char)
329
+ return null;
330
+ const matchIdx = items.findIndex((item) => {
331
+ if (!isSelectableChoice(item))
332
+ return false;
333
+ if (item.key && item.key.toLowerCase() === char)
334
+ return true;
335
+ const cleanName = item.name.replace(/\x1b\[[0-9;]*m/g, '').trim();
336
+ return (cleanName.startsWith(`${char}.`) ||
337
+ cleanName.startsWith(`${char} `) ||
338
+ cleanName.startsWith(`${char}·`) ||
339
+ cleanName.startsWith(`${char}、`));
340
+ });
341
+ if (matchIdx !== -1) {
342
+ return { index: matchIdx, value: items[matchIdx].value };
343
+ }
344
+ if (char === 'q') {
345
+ const backIdx = items.findIndex((item) => isSelectableChoice(item) &&
346
+ (item.value === 'back' ||
347
+ item.value === '__back__' ||
348
+ item.value === 'exit' ||
349
+ item.value === '__cancel__'));
350
+ if (backIdx !== -1) {
351
+ return { index: backIdx, value: items[backIdx].value };
352
+ }
353
+ }
354
+ return null;
355
+ }
356
+ const innerQuickSelect = createPrompt((config, done) => {
357
+ const { pageSize = 12, tickIntervalMs = 0, altScreen, outputStream } = config;
12
358
  const [, setTick] = useState(0);
359
+ const [, setResizeTick] = useState(0);
13
360
  const [status, setStatus] = useState('idle');
14
- // 如果配置了定时刷新,每秒触发一次虚拟 Diff 重绘 (零闪烁实时走字)
361
+ const lastFrameRef = useRef('');
15
362
  useEffect(() => {
16
363
  if (!tickIntervalMs || tickIntervalMs <= 0)
17
364
  return;
@@ -22,8 +369,21 @@ export const quickSelect = createPrompt((config, done) => {
22
369
  }, tickIntervalMs);
23
370
  return () => clearInterval(timer);
24
371
  }, []);
372
+ useEffect(() => {
373
+ if (!outputStream || typeof outputStream.on !== 'function')
374
+ return;
375
+ let resizeCount = 0;
376
+ const onResize = () => {
377
+ resizeCount++;
378
+ setResizeTick(resizeCount);
379
+ };
380
+ outputStream.on('resize', onResize);
381
+ return () => {
382
+ outputStream.removeListener('resize', onResize);
383
+ };
384
+ }, []);
25
385
  const items = config.choices;
26
- const isSelectable = (item) => !Separator.isSeparator(item) && !item?.disabled;
386
+ const isSelectable = isSelectableChoice;
27
387
  const selectableIndices = [];
28
388
  items.forEach((item, idx) => {
29
389
  if (isSelectable(item)) {
@@ -32,30 +392,29 @@ export const quickSelect = createPrompt((config, done) => {
32
392
  });
33
393
  const [active, setActive] = useState(selectableIndices[0] ?? 0);
34
394
  const selectedChoice = items[active];
35
- // 核心终端防护:确保无论上一界面以何种形式退出,此处均 100% 激活 rawMode 且流正常,彻底杜绝 Windows 方向键假死
36
- useEffect(() => {
37
- if (process.stdin.isTTY) {
38
- if (!process.stdin.isRaw) {
395
+ useEffect((rl) => {
396
+ const stdinStream = (rl?.input ?? process.stdin);
397
+ if (stdinStream.isTTY && typeof stdinStream.setRawMode === 'function') {
398
+ if (!stdinStream.isRaw) {
39
399
  try {
40
- process.stdin.setRawMode(true);
400
+ stdinStream.setRawMode(true);
41
401
  }
42
402
  catch { }
43
403
  }
44
404
  try {
45
- process.stdin.resume();
405
+ stdinStream.resume();
46
406
  }
47
407
  catch { }
48
408
  }
49
409
  }, []);
50
- useKeypress((key, rl) => {
410
+ useKeypress((key) => {
51
411
  if (status !== 'idle')
52
412
  return;
53
- // 1. Ctrl+C 紧急强退:无论任何时候按 Ctrl+C,100% 恢复光标并瞬间退回终端 Shell
54
413
  if (key.ctrl && key.name === 'c') {
55
- process.stdout.write('\x1b[?25h\n');
414
+ leaveAltScreenIfActive();
415
+ outputStream.write('\x1b[?25h\n');
56
416
  process.exit(0);
57
417
  }
58
- // 2. 回车键确认当前选定项
59
418
  if (isEnterKey(key)) {
60
419
  if (selectedChoice && isSelectable(selectedChoice)) {
61
420
  setStatus('done');
@@ -63,7 +422,6 @@ export const quickSelect = createPrompt((config, done) => {
63
422
  }
64
423
  return;
65
424
  }
66
- // 3. Escape 键取消当前操作,返回上一级或主菜单
67
425
  if (key.name === 'escape') {
68
426
  const backItem = items.find((item) => isSelectable(item) &&
69
427
  (item.value === 'back' ||
@@ -75,12 +433,10 @@ export const quickSelect = createPrompt((config, done) => {
75
433
  done(backItem.value);
76
434
  return;
77
435
  }
78
- // 无明确返回项时默认安全返回 '__back__',绝不抛出 ExitPromptError 误判为 SIGINT
79
436
  setStatus('done');
80
437
  done('__back__');
81
438
  return;
82
439
  }
83
- // 4. 方向键导航 (支持 ↑↓ 和 vim 的 j/k)
84
440
  if (isUpKey(key) || isDownKey(key) || key.name === 'k' || key.name === 'j') {
85
441
  const isUp = isUpKey(key) || key.name === 'k';
86
442
  const offset = isUp ? -1 : 1;
@@ -91,79 +447,152 @@ export const quickSelect = createPrompt((config, done) => {
91
447
  setActive(next);
92
448
  return;
93
449
  }
94
- // 5. 单键快捷直达:支持数字键 0-9、字符键 s (搜索)、q (退出/返回)
450
+ if (key.ctrl || key.meta)
451
+ return;
95
452
  const char = key.name ? key.name.toLowerCase() : '';
96
- if (char) {
97
- // 快捷退出/返回: 按 q 直接触发返回项
98
- if (char === 'q') {
99
- const backItem = items.find((item) => isSelectable(item) &&
100
- (item.value === 'back' ||
101
- item.value === '__back__' ||
102
- item.value === 'exit' ||
103
- item.value === '__cancel__'));
104
- if (backItem && isSelectable(backItem)) {
105
- setStatus('done');
106
- done(backItem.value);
107
- return;
108
- }
109
- }
110
- // 匹配以该按键开头或指定 key 的选项
111
- const matchIdx = items.findIndex((item) => {
112
- if (!isSelectable(item))
113
- return false;
114
- if (item.key && item.key.toLowerCase() === char)
115
- return true;
116
- // 过滤颜色控制字符后比对前缀
117
- const cleanName = item.name.replace(/\x1b\[[0-9;]*m/g, '').trim();
118
- return (cleanName.startsWith(`${char}.`) ||
119
- cleanName.startsWith(`${char} `) ||
120
- cleanName.startsWith(`${char}·`) ||
121
- cleanName.startsWith(`${char}、`));
122
- });
123
- if (matchIdx !== -1) {
124
- const target = items[matchIdx];
125
- setActive(matchIdx);
126
- // 单键快捷执行!无需再按回车
127
- setStatus('done');
128
- done(target.value);
129
- return;
130
- }
453
+ const shortcut = resolveQuickShortcut(items, char);
454
+ if (shortcut) {
455
+ setActive(shortcut.index);
456
+ setStatus('done');
457
+ done(shortcut.value);
458
+ return;
131
459
  }
132
460
  });
461
+ const terminalRows = outputStream.rows || 24;
462
+ const terminalCols = outputStream.columns || 80;
463
+ const rawHeader = config.getHeader
464
+ ? config.getHeader()
465
+ : config.header
466
+ ? config.header
467
+ : '';
468
+ const layout = computeMenuViewport({
469
+ rawHeader,
470
+ message: config.message,
471
+ description: selectedChoice?.description,
472
+ requestedPageSize: pageSize,
473
+ totalItems: items.length,
474
+ terminalRows,
475
+ terminalCols,
476
+ altScreen,
477
+ });
478
+ const { panelWidth, nameColWidth } = computeMenuPanelGeometry(items, layout.headerLines, layout.safeCols);
479
+ const activeBg = chalk.bgRgb(18, 52, 77);
133
480
  const page = usePagination({
134
481
  items,
135
482
  active,
136
483
  renderItem({ item, isActive }) {
137
484
  if (Separator.isSeparator(item)) {
138
- return ` ${chalk.dim('────────────────────────────────')}`;
485
+ const sepWidth = Math.max(8, Math.min(panelWidth - 4, layout.safeCols - 4));
486
+ return truncateAnsiLine(` ${chalk.dim('─'.repeat(sepWidth))}`, layout.safeCols);
139
487
  }
140
488
  const choice = item;
489
+ const plainName = stripVTControlCharacters(choice.name || '');
490
+ const nameW = measureAnsiWidth(plainName);
491
+ const explicitHint = typeof choice.hint === 'string' ? stripVTControlCharacters(choice.hint).trim() : '';
492
+ const explicitShortHint = typeof choice.shortHint === 'string' ? stripVTControlCharacters(choice.shortHint).trim() : '';
493
+ const fallbackDesc = explicitHint
494
+ ? ''
495
+ : stripVTControlCharacters(choice.description || '').trim();
496
+ const rawHint = explicitHint || fallbackDesc;
497
+ const canShowHint = rawHint.length > 0 &&
498
+ panelWidth >= nameColWidth + 18 &&
499
+ nameW <= nameColWidth + 2;
500
+ let hintText = '';
501
+ let gap = 0;
502
+ if (canShowHint) {
503
+ gap = Math.max(2, nameColWidth - nameW + 3);
504
+ const maxHintCols = Math.max(0, panelWidth - (4 + nameW + gap) - 1);
505
+ if (explicitHint) {
506
+ if (measureAnsiWidth(explicitHint) <= maxHintCols) {
507
+ hintText = explicitHint;
508
+ }
509
+ else if (explicitShortHint && measureAnsiWidth(explicitShortHint) <= maxHintCols) {
510
+ hintText = explicitShortHint;
511
+ }
512
+ else if (maxHintCols >= 6) {
513
+ hintText = truncateAnsiLine(explicitShortHint || explicitHint, maxHintCols);
514
+ }
515
+ }
516
+ else if (fallbackDesc && measureAnsiWidth(fallbackDesc) <= maxHintCols) {
517
+ hintText = fallbackDesc;
518
+ }
519
+ }
520
+ const hintW = hintText ? measureAnsiWidth(hintText) : 0;
141
521
  if (isActive) {
142
- return ` ${chalk.cyan.bold('❯')} ${chalk.bold.white(choice.name)}`;
522
+ const barWidth = Math.max(20, panelWidth - 2);
523
+ const contentW = 4 + nameW + (hintW > 0 ? gap + hintW : 0);
524
+ const padRight = ' '.repeat(Math.max(0, barWidth - contentW));
525
+ const leftPart = `${chalk.cyan.bold(' ❯ ')}${chalk.bold.hex('#38bdf8')(plainName)}`;
526
+ const rightPart = hintW > 0 ? `${' '.repeat(gap)}${chalk.hex('#7dd3fc')(hintText)}` : '';
527
+ const line = activeBg(`${leftPart}${rightPart}${padRight}`);
528
+ return truncateAnsiLine(line, layout.safeCols);
143
529
  }
144
- return ` ${chalk.white(choice.name)}`;
530
+ const leftPart = ` ${chalk.white(choice.name)}`;
531
+ const rightPart = hintW > 0 ? `${' '.repeat(gap)}${chalk.grey(hintText)}` : '';
532
+ return truncateAnsiLine(`${leftPart}${rightPart}`, layout.safeCols);
145
533
  },
146
- pageSize,
534
+ pageSize: layout.effectivePageSize,
147
535
  loop: true,
148
536
  });
149
537
  if (status === 'done') {
150
- return '\x1b[?25h';
538
+ return altScreen ? '' : '\x1b[?25h';
151
539
  }
152
- const headerText = config.getHeader
153
- ? config.getHeader()
154
- : config.header
155
- ? config.header
156
- : '';
157
- const promptMessage = config.message
158
- ? `\n ${chalk.cyan('●')} ${chalk.bold.white(config.message)}\n`
159
- : '\n';
160
- const descText = selectedChoice?.description
161
- ? `\n ${chalk.dim('›')} ${chalk.cyan(selectedChoice.description)}`
162
- : '\n';
163
- const helpTip = `\n ${chalk.dim('[↑↓] 移动 [↵] 确认 [数字/按键] 快捷直达 [Esc/q] 返回 [Ctrl+C] 退出')}`;
164
- const content = `${headerText}${promptMessage}${page}${descText}${helpTip}\x1b[?25l`;
165
- return content;
540
+ const pageLines = page ? page.split('\n') : [];
541
+ const frameLines = [
542
+ ...layout.headerLines,
543
+ ...layout.promptLines,
544
+ ...pageLines,
545
+ ...layout.footerLines,
546
+ ].slice(0, layout.maxTotalLines);
547
+ if (altScreen) {
548
+ const body = frameLines.map((line) => `${line}\x1b[K`).join('\r\n');
549
+ const frameKey = `${terminalCols}x${terminalRows}:${body}`;
550
+ if (lastFrameRef.current !== frameKey) {
551
+ lastFrameRef.current = frameKey;
552
+ outputStream.write(`${SYNC_BEGIN}\x1b[H${body}\x1b[J${SYNC_END}`);
553
+ }
554
+ return '';
555
+ }
556
+ return `${frameLines.join('\n')}\x1b[?25l`;
166
557
  });
167
- // 兼容别名导出
558
+ export async function quickSelect(config, context) {
559
+ const targetInput = (context?.input ?? process.stdin);
560
+ const targetOutput = (context?.output ?? process.stdout);
561
+ const isTty = Boolean(targetOutput?.isTTY && targetInput?.isTTY);
562
+ const useAltScreen = Boolean(config.altScreen && isTty);
563
+ if (!useAltScreen) {
564
+ return innerQuickSelect({ ...config, altScreen: false, outputStream: targetOutput }, {
565
+ clearPromptOnDone: true,
566
+ ...context,
567
+ input: targetInput,
568
+ output: targetOutput,
569
+ });
570
+ }
571
+ const silentSink = createSilentTtySink(targetOutput);
572
+ enterAltScreen(targetOutput);
573
+ const onSignal = () => {
574
+ leaveAltScreenIfActive();
575
+ };
576
+ const onExit = () => {
577
+ leaveAltScreenIfActiveSync();
578
+ };
579
+ process.prependOnceListener('SIGINT', onSignal);
580
+ process.prependOnceListener('SIGTERM', onSignal);
581
+ process.once('exit', onExit);
582
+ try {
583
+ return await innerQuickSelect({ ...config, altScreen: true, outputStream: targetOutput }, {
584
+ ...context,
585
+ input: targetInput,
586
+ output: silentSink,
587
+ clearPromptOnDone: true,
588
+ });
589
+ }
590
+ finally {
591
+ process.removeListener('SIGINT', onSignal);
592
+ process.removeListener('SIGTERM', onSignal);
593
+ process.removeListener('exit', onExit);
594
+ leaveAltScreenIfActive();
595
+ }
596
+ }
168
597
  export const liveMenu = quickSelect;
169
598
  export { Separator };