@nbtca/prompt 1.5.14 → 1.5.15

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.
@@ -1,12 +1,14 @@
1
1
  import path from 'node:path';
2
2
  import { createNbtTimetableClient, createTimetableSchedule, timetableToIcs, } from '@nbtca/nbtcal/timetable';
3
- import { captureFooterHint, passiveFooterHint } from '../chrome.js';
3
+ import { captureFooterHint, digitTabHint, fitFooterHint, passiveFooterHint } from '../chrome.js';
4
4
  import { ListField, computeMaxVisible } from '../fields/list-field.js';
5
5
  import { TextField } from '../fields/text-field.js';
6
6
  import { renderSchedule, hubShortcuts } from './schedule-render.js';
7
7
  import { handleGridKey, todayGridCursor } from './schedule-grid-cursor.js';
8
8
  import { setVimKeysActive } from '../../core/vim-keys.js';
9
9
  import { t } from '../../i18n/index.js';
10
+ import { pickIcon } from '../../core/icons.js';
11
+ import { glyph } from '../../core/theme.js';
10
12
  import { AuthError } from '../../auth/errors.js';
11
13
  import { loginWithStudentPassword, restoreNbtSession, } from '../../auth/nbt-auth.js';
12
14
  import { createSessionStore } from '../../auth/session-store.js';
@@ -23,6 +25,21 @@ let catalog = [];
23
25
  let pendingId = '';
24
26
  let lifecycleGeneration = 0;
25
27
  const closingSessions = new WeakMap();
28
+ function gridKeys() {
29
+ return {
30
+ days: pickIcon('← →', 'left/right'),
31
+ periods: glyph.updown(),
32
+ enter: glyph.enter(),
33
+ };
34
+ }
35
+ function gridFooterHint(tabCount, cols) {
36
+ const trans = t();
37
+ const dot = pickIcon('·', '-');
38
+ const keys = gridKeys();
39
+ const local = `${keys.days} ${trans.timetable.footerDay} ${dot} ${keys.periods} ${trans.timetable.footerClass} ${dot} ${keys.enter} ${trans.timetable.footerDetail}`;
40
+ const quit = `Esc ${dot} q ${trans.menu.hintQuit}`;
41
+ return fitFooterHint(cols, `${digitTabHint(tabCount)}${local} ${dot} ${quit} ${dot} ${trans.help.hint}`, `${digitTabHint(tabCount)}${local} ${dot} ${quit}`, `${local} ${dot} ${quit}`, `${local} ${dot} Esc ${dot} q`, local, `Esc ${dot} q`, 'q');
42
+ }
26
43
  function isLifecycleActive(ctx, generation) {
27
44
  return generation === lifecycleGeneration && ctx.signal?.aborted !== true;
28
45
  }
@@ -299,9 +316,18 @@ export const scheduleView = {
299
316
  return state.mode === 'loading';
300
317
  },
301
318
  shortcuts() {
302
- return state.mode === 'hub' && state.timetable
303
- ? hubShortcuts(state.timetable).map(({ key, label }) => ({ key, label }))
304
- : [];
319
+ if ((state.mode !== 'hub' && state.mode !== 'week') || !state.timetable)
320
+ return [];
321
+ const trans = t();
322
+ const keys = gridKeys();
323
+ const grid = [
324
+ { key: keys.days, label: trans.timetable.helpSwitchDay },
325
+ { key: keys.periods, label: trans.timetable.helpPickClass },
326
+ { key: keys.enter, label: trans.timetable.helpOpenClass },
327
+ ];
328
+ if (state.mode === 'week')
329
+ return grid;
330
+ return [...grid, ...hubShortcuts(state.timetable).map(({ key, label }) => ({ key, label }))];
305
331
  },
306
332
  capturesInput() {
307
333
  return (state.mode === 'needsLoginId' ||
@@ -323,7 +349,11 @@ export const scheduleView = {
323
349
  state.mode === 'meetingDetail' ||
324
350
  state.mode === 'unresolved' ||
325
351
  state.mode === 'termDensity';
326
- return passive ? passiveFooterHint(tabCount, cols) : undefined;
352
+ if (passive)
353
+ return passiveFooterHint(tabCount, cols);
354
+ return state.mode === 'hub' || state.mode === 'week'
355
+ ? gridFooterHint(tabCount, cols)
356
+ : undefined;
327
357
  },
328
358
  handleBack(ctx) {
329
359
  if (state.mode === 'needsLoginId') {
@@ -491,12 +521,21 @@ export const scheduleView = {
491
521
  label: tm.academicYearLabel,
492
522
  ...(tm.current ? { hint: t().common.current } : {}),
493
523
  }));
524
+ const note = options.length > 0
525
+ ? undefined
526
+ : session
527
+ ? t().timetable.noTerms
528
+ : t().timetable.termPickerNeedsLogin;
529
+ if (!session && options.length === 0) {
530
+ options.push({ value: '__login__', label: t().timetable.termPickerLoginAction });
531
+ }
494
532
  options.push({ value: '__back__', label: t().common.back });
495
533
  state = {
496
534
  ...state,
497
535
  mode: 'termPicker',
536
+ ...(note === undefined ? {} : { termPickerNote: note }),
498
537
  termField: new ListField({
499
- title: t().timetable.hubSwitchTerm,
538
+ ...(note === undefined ? { title: t().timetable.hubSwitchTerm } : {}),
500
539
  options,
501
540
  maxVisible: computeMaxVisible(ctx.bodyRows),
502
541
  }),
@@ -576,6 +615,10 @@ export const scheduleView = {
576
615
  returnToHub();
577
616
  return;
578
617
  }
618
+ if (result.selected === '__login__') {
619
+ goToLoginId();
620
+ return;
621
+ }
579
622
  const term = resolveTerm(catalog, result.selected);
580
623
  const newTermKey = termKey(term);
581
624
  const weekOne = loadWeekOne(newTermKey);
@@ -5,6 +5,7 @@ import { resetIconCache, pickIcon } from '../../core/icons.js';
5
5
  import { APP_INFO, URLS } from '../../config/data.js';
6
6
  import { t, getCurrentLanguage, saveLanguagePreference, clearTranslationCache, } from '../../i18n/index.js';
7
7
  import { padEndV } from '../../core/text.js';
8
+ import { type } from '../../core/theme.js';
8
9
  import { resetCapabilities } from '../../core/capabilities.js';
9
10
  let state = { mode: 'menu' };
10
11
  function currentHint(current, hint) {
@@ -45,7 +46,7 @@ function buildMenuField(statusMessage) {
45
46
  return {
46
47
  mode: 'menu',
47
48
  ...(statusMessage === undefined ? {} : { statusMessage }),
48
- menuField: new ListField({ title: trans.theme.chooseAction, options }),
49
+ menuField: new ListField({ options }),
49
50
  };
50
51
  }
51
52
  function goToMenu(statusMessage) {
@@ -112,7 +113,7 @@ export const settingsView = {
112
113
  state = {
113
114
  mode: 'icon',
114
115
  subField: new ListField({
115
- title: trans.theme.chooseIconMode,
116
+ title: trans.theme.iconMode,
116
117
  options,
117
118
  initialIndex: idx,
118
119
  }),
@@ -126,7 +127,7 @@ export const settingsView = {
126
127
  state = {
127
128
  mode: 'color',
128
129
  subField: new ListField({
129
- title: trans.theme.chooseColorMode,
130
+ title: trans.theme.colorMode,
130
131
  options,
131
132
  initialIndex: idx,
132
133
  }),
@@ -147,6 +148,8 @@ export const settingsView = {
147
148
  state = {
148
149
  mode: 'about',
149
150
  aboutLines: [
151
+ type.heading(trans.about.title),
152
+ '',
150
153
  row(trans.about.project, APP_INFO.name),
151
154
  row(trans.about.version, `v${APP_INFO.version}`),
152
155
  row(trans.about.description, trans.about.descriptionText),
@@ -158,7 +161,7 @@ export const settingsView = {
158
161
  row(trans.about.license, `MIT ${pickIcon('·', '-')} ${trans.about.author}: m1ngsama`),
159
162
  ],
160
163
  backField: new ListField({
161
- title: trans.about.title,
164
+ title: '',
162
165
  options: [{ value: '__back__', label: trans.common.back }],
163
166
  }),
164
167
  };
@@ -0,0 +1,206 @@
1
+ const CAMPUS_DOMAIN = 'nbt.edu.cn';
2
+ const MAX_COOKIES = 100;
3
+ const MAX_PAIR_LENGTH = 4096;
4
+ const MAX_ATTRIBUTE_LENGTH = 1024;
5
+ const MAX_LIFETIME_MS = 400 * 24 * 60 * 60 * 1000;
6
+ const CONTROL = /[\u0000-\u001f\u007f]/;
7
+ const DATE_DELIMITER = /[\x09\x20-\x2f\x3b-\x40\x5b-\x60\x7b-\x7e]+/;
8
+ const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
9
+ function isCampusDomain(domain) {
10
+ return domain === CAMPUS_DOMAIN || domain.endsWith(`.${CAMPUS_DOMAIN}`);
11
+ }
12
+ function domainMatches(host, domain) {
13
+ return host === domain || host.endsWith(`.${domain}`);
14
+ }
15
+ function pathMatches(requestPath, cookiePath) {
16
+ return (requestPath === cookiePath ||
17
+ (requestPath.startsWith(cookiePath) &&
18
+ (cookiePath.endsWith('/') || requestPath[cookiePath.length] === '/')));
19
+ }
20
+ function defaultPath(requestPath) {
21
+ const lastSlash = requestPath.lastIndexOf('/');
22
+ return lastSlash <= 0 ? '/' : requestPath.slice(0, lastSlash);
23
+ }
24
+ function parseCookieDate(text) {
25
+ let time;
26
+ let day;
27
+ let month;
28
+ let year;
29
+ for (const token of text.split(DATE_DELIMITER)) {
30
+ let match;
31
+ if (!time && (match = /^(\d{1,2}):(\d{1,2}):(\d{1,2})(?!\d)/.exec(token))) {
32
+ time = match.slice(1).map(Number);
33
+ }
34
+ else if (day === undefined && (match = /^\d{1,2}(?!\d)/.exec(token))) {
35
+ day = Number(match[0]);
36
+ }
37
+ else if (month === undefined && MONTHS.includes(token.slice(0, 3).toLowerCase())) {
38
+ month = MONTHS.indexOf(token.slice(0, 3).toLowerCase());
39
+ }
40
+ else if (year === undefined && (match = /^\d{2,4}(?!\d)/.exec(token))) {
41
+ year = Number(match[0]);
42
+ }
43
+ }
44
+ if (!time || day === undefined || month === undefined || year === undefined)
45
+ return undefined;
46
+ if (year >= 70 && year <= 99)
47
+ year += 1900;
48
+ else if (year <= 69)
49
+ year += 2000;
50
+ const [hours = 0, minutes = 0, seconds = 0] = time;
51
+ if (day < 1 || year < 1601 || hours > 23 || minutes > 59 || seconds > 59)
52
+ return undefined;
53
+ const date = new Date(Date.UTC(year, month, day, hours, minutes, seconds));
54
+ return date.getUTCMonth() === month && date.getUTCDate() === day ? date.getTime() : undefined;
55
+ }
56
+ function isStoredCookie(value) {
57
+ if (typeof value !== 'object' || value === null)
58
+ return false;
59
+ const cookie = value;
60
+ return (typeof cookie['name'] === 'string' &&
61
+ cookie['name'] !== '' &&
62
+ !CONTROL.test(cookie['name']) &&
63
+ typeof cookie['value'] === 'string' &&
64
+ !CONTROL.test(cookie['value']) &&
65
+ typeof cookie['domain'] === 'string' &&
66
+ isCampusDomain(cookie['domain']) &&
67
+ typeof cookie['path'] === 'string' &&
68
+ cookie['path'].startsWith('/') &&
69
+ typeof cookie['hostOnly'] === 'boolean' &&
70
+ typeof cookie['secure'] === 'boolean' &&
71
+ typeof cookie['httpOnly'] === 'boolean' &&
72
+ (cookie['expires'] === undefined || Number.isFinite(cookie['expires'])));
73
+ }
74
+ function isSerializedJar(value) {
75
+ if (typeof value !== 'object' || value === null)
76
+ return false;
77
+ const { version, cookies } = value;
78
+ return (version === 1 &&
79
+ Array.isArray(cookies) &&
80
+ cookies.length <= MAX_COOKIES &&
81
+ cookies.every(isStoredCookie));
82
+ }
83
+ export function createCookieJar(serialized) {
84
+ const cookies = new Map();
85
+ const keyOf = (cookie) => JSON.stringify([cookie.domain, cookie.path, cookie.name]);
86
+ if (serialized !== undefined) {
87
+ if (!isSerializedJar(serialized))
88
+ throw new TypeError('Unsupported cookie jar.');
89
+ for (const { name, value, domain, path, hostOnly, secure, httpOnly, expires, } of serialized.cookies) {
90
+ const cookie = { name, value, domain, path, hostOnly, secure, httpOnly };
91
+ cookies.set(keyOf(cookie), expires === undefined ? cookie : { ...cookie, expires });
92
+ }
93
+ }
94
+ function isExpired(cookie, now) {
95
+ return cookie.expires !== undefined && cookie.expires <= now;
96
+ }
97
+ function storeOne(url, header, now) {
98
+ const [pair = '', ...attributes] = header.trim().split(';');
99
+ const separator = pair.indexOf('=');
100
+ const name = pair.slice(0, separator).trim();
101
+ const value = pair.slice(separator + 1).trim();
102
+ if (separator <= 0 || !name || CONTROL.test(name) || CONTROL.test(value))
103
+ return;
104
+ if (name.length + value.length > MAX_PAIR_LENGTH)
105
+ return;
106
+ let domain;
107
+ let path;
108
+ let expires;
109
+ let maxAge;
110
+ let secure = false;
111
+ let httpOnly = false;
112
+ for (const attribute of attributes) {
113
+ const split = attribute.indexOf('=');
114
+ const key = (split === -1 ? attribute : attribute.slice(0, split)).trim().toLowerCase();
115
+ const argument = split === -1 ? '' : attribute.slice(split + 1).trim();
116
+ if (argument.length > MAX_ATTRIBUTE_LENGTH)
117
+ continue;
118
+ if (key === 'expires')
119
+ expires = parseCookieDate(argument) ?? expires;
120
+ else if (key === 'max-age' && /^-?\d+$/.test(argument))
121
+ maxAge = Number(argument);
122
+ else if (key === 'domain' && argument.replace(/^\./, ''))
123
+ domain = argument.replace(/^\./, '').toLowerCase();
124
+ else if (key === 'path')
125
+ path = argument.startsWith('/') ? argument : undefined;
126
+ else if (key === 'secure')
127
+ secure = true;
128
+ else if (key === 'httponly')
129
+ httpOnly = true;
130
+ }
131
+ const host = url.hostname;
132
+ if (domain !== undefined && !domainMatches(host, domain))
133
+ return;
134
+ const cookie = {
135
+ name,
136
+ value,
137
+ domain: domain ?? host,
138
+ path: path ?? defaultPath(url.pathname),
139
+ hostOnly: domain === undefined,
140
+ secure,
141
+ httpOnly,
142
+ };
143
+ if (!isCampusDomain(cookie.domain))
144
+ return;
145
+ if (secure && url.protocol !== 'https:')
146
+ return;
147
+ if (name.startsWith('__Secure-') && !secure)
148
+ return;
149
+ if (name.startsWith('__Host-') && (!secure || !cookie.hostOnly || cookie.path !== '/'))
150
+ return;
151
+ const expiry = maxAge === undefined ? expires : maxAge <= 0 ? 0 : now + maxAge * 1000;
152
+ if (expiry !== undefined)
153
+ cookie.expires = Math.min(expiry, now + MAX_LIFETIME_MS);
154
+ const key = keyOf(cookie);
155
+ if (isExpired(cookie, now)) {
156
+ cookies.delete(key);
157
+ return;
158
+ }
159
+ cookies.set(key, cookie);
160
+ if (cookies.size <= MAX_COOKIES)
161
+ return;
162
+ for (const [staleKey, stale] of cookies)
163
+ if (isExpired(stale, now))
164
+ cookies.delete(staleKey);
165
+ for (const staleKey of cookies.keys()) {
166
+ if (cookies.size <= MAX_COOKIES)
167
+ break;
168
+ cookies.delete(staleKey);
169
+ }
170
+ }
171
+ return {
172
+ store(url, setCookieHeaders) {
173
+ const now = Date.now();
174
+ for (const header of setCookieHeaders)
175
+ storeOne(url, header, now);
176
+ },
177
+ cookieHeader(url) {
178
+ const now = Date.now();
179
+ const matches = [];
180
+ for (const [key, cookie] of cookies) {
181
+ if (isExpired(cookie, now))
182
+ cookies.delete(key);
183
+ else if ((cookie.hostOnly
184
+ ? url.hostname === cookie.domain
185
+ : domainMatches(url.hostname, cookie.domain)) &&
186
+ pathMatches(url.pathname, cookie.path) &&
187
+ (!cookie.secure || url.protocol === 'https:'))
188
+ matches.push(cookie);
189
+ }
190
+ return matches
191
+ .sort((a, b) => b.path.length - a.path.length)
192
+ .map((cookie) => `${cookie.name}=${cookie.value}`)
193
+ .join('; ');
194
+ },
195
+ serialize() {
196
+ const now = Date.now();
197
+ return {
198
+ version: 1,
199
+ cookies: [...cookies.values()].filter((cookie) => !isExpired(cookie, now)),
200
+ };
201
+ },
202
+ clear() {
203
+ cookies.clear();
204
+ },
205
+ };
206
+ }
@@ -1,6 +1,14 @@
1
- import makeFetchCookie from 'fetch-cookie';
2
- import { CookieJar } from 'tough-cookie';
1
+ import { createCookieJar } from './cookie-jar.js';
3
2
  import { AuthError, SessionExpiredError } from './errors.js';
3
+ const MAX_REDIRECTS = 8;
4
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
5
+ const BODY_HEADERS = [
6
+ 'content-type',
7
+ 'content-length',
8
+ 'content-encoding',
9
+ 'content-language',
10
+ 'content-location',
11
+ ];
4
12
  const WEBVPN_HOST = 'webvpn.nbt.edu.cn';
5
13
  const AUTH_HOST = 'authserver-443.webvpn.nbt.edu.cn';
6
14
  export const JWXT_HOST = 'jwxt-443.webvpn.nbt.edu.cn';
@@ -117,25 +125,8 @@ function safeFetchError(error, stage) {
117
125
  return new AuthError('NETWORK', stage, 'The campus service request failed.', { retryable: true });
118
126
  }
119
127
  export function createCampusCookieSession(options = {}) {
120
- // Tough Cookie's secure defaults reject public suffixes and use strict
121
- // parsing while tolerating legacy prefix mistakes. The campus WebVPN relies
122
- // on its default special-domain handling during the CAS callback.
123
- const jar = options.jar ?? new CookieJar();
128
+ const jar = options.jar ?? createCookieJar();
124
129
  const baseFetch = options.baseFetch ?? globalThis.fetch;
125
- const guardedFetch = async (input, init) => {
126
- const url = new URL(input instanceof Request ? input.url : input.toString());
127
- assertAllowedCampusUrl(url);
128
- // Caller headers were checked before fetch-cookie received them. A Cookie
129
- // header at this layer was added by the private jar and is expected.
130
- const headers = new Headers(input instanceof Request ? input.headers : undefined);
131
- for (const [name, value] of new Headers(init?.headers))
132
- headers.set(name, value);
133
- if (headers.has('authorization') || headers.has('host')) {
134
- throw new AuthError('UNTRUSTED_URL', 'session', 'Authentication headers are not allowed.');
135
- }
136
- return baseFetch(input, init);
137
- };
138
- const cookieFetch = makeFetchCookie(guardedFetch, jar, false);
139
130
  const timeoutMs = options.timeoutMs ?? 15_000;
140
131
  async function request(url, init = {}, stage = 'session') {
141
132
  assertAllowedCampusUrl(url);
@@ -150,13 +141,43 @@ export function createCampusCookieSession(options = {}) {
150
141
  }, timeoutMs).unref();
151
142
  // Keep the timer running after the headers: the caller still has to read the body.
152
143
  const signal = init.signal ? AbortSignal.any([init.signal, timeout.signal]) : timeout.signal;
144
+ const headers = new Headers(safeHeaders(init.headers));
145
+ let method = init.method ?? 'GET';
146
+ let body = init.body ?? null;
153
147
  try {
154
- return await cookieFetch(url, {
155
- ...init,
156
- headers: safeHeaders(init.headers),
157
- signal,
158
- maxRedirect: 8,
159
- });
148
+ for (let redirects = 0;; redirects += 1) {
149
+ const cookie = jar.cookieHeader(url);
150
+ if (cookie)
151
+ headers.set('cookie', cookie);
152
+ else
153
+ headers.delete('cookie');
154
+ const response = await baseFetch(url, {
155
+ ...init,
156
+ method,
157
+ body,
158
+ headers,
159
+ signal,
160
+ redirect: 'manual',
161
+ });
162
+ const responseUrl = new URL(response.url || url);
163
+ jar.store(responseUrl, response.headers.getSetCookie());
164
+ const location = response.headers.get('location');
165
+ if (!REDIRECT_STATUSES.has(response.status) || location === null) {
166
+ Object.defineProperty(response, 'url', { value: responseUrl.href });
167
+ return response;
168
+ }
169
+ await response.body?.cancel();
170
+ if (redirects >= MAX_REDIRECTS)
171
+ throw new Error('Too many campus redirects.');
172
+ if (response.status === 303 || (method === 'POST' && response.status <= 302)) {
173
+ method = 'GET';
174
+ body = null;
175
+ for (const name of BODY_HEADERS)
176
+ headers.delete(name);
177
+ }
178
+ url = new URL(location, responseUrl);
179
+ assertAllowedCampusUrl(url);
180
+ }
160
181
  }
161
182
  catch (error) {
162
183
  throw safeFetchError(error, stage);
@@ -189,13 +210,16 @@ export function createCampusCookieSession(options = {}) {
189
210
  request,
190
211
  timetableTransport,
191
212
  serialize: () => jar.serialize(),
192
- close: () => jar.removeAllCookies(),
213
+ close: () => {
214
+ jar.clear();
215
+ return Promise.resolve();
216
+ },
193
217
  };
194
218
  }
195
- export async function cookieSessionFromSerialized(serialized, options = {}) {
219
+ export function cookieSessionFromSerialized(serialized, options = {}) {
196
220
  let jar;
197
221
  try {
198
- jar = await CookieJar.deserialize(serialized);
222
+ jar = createCookieJar(serialized);
199
223
  }
200
224
  catch {
201
225
  throw new SessionExpiredError();
@@ -150,17 +150,17 @@ function createAuthenticatedSession(cookies, metadata) {
150
150
  return {
151
151
  accountHint: metadata.accountHint,
152
152
  timetableTransport: (url, init) => cookies.timetableTransport(url, init),
153
- async snapshot(validatedAt = new Date()) {
153
+ snapshot(validatedAt = new Date()) {
154
154
  const validatedAtText = validatedAt.toISOString();
155
- return {
155
+ return Promise.resolve({
156
156
  version: 1,
157
157
  provider: 'nbt-webvpn',
158
- jar: await cookies.serialize(),
158
+ jar: cookies.serialize(),
159
159
  ...(metadata.accountHint === undefined ? {} : { accountHint: metadata.accountHint }),
160
160
  authenticatedAt: metadata.authenticatedAt,
161
161
  validatedAt: validatedAtText,
162
162
  expiresAt: new Date(validatedAt.getTime() + SESSION_MAX_AGE_MS).toISOString(),
163
- };
163
+ });
164
164
  },
165
165
  close: () => cookies.close(),
166
166
  };
@@ -250,10 +250,11 @@ export async function loginWithStudentPassword(username, password, options = {})
250
250
  });
251
251
  }
252
252
  }
253
- export async function restoreNbtSession(persisted, options = {}) {
254
- const cookies = await cookieSessionFromSerialized(persisted.jar, options);
255
- return createAuthenticatedSession(cookies, {
256
- ...(persisted.accountHint === undefined ? {} : { accountHint: persisted.accountHint }),
257
- authenticatedAt: persisted.authenticatedAt,
253
+ export function restoreNbtSession(persisted, options = {}) {
254
+ return new Promise((resolve) => {
255
+ resolve(createAuthenticatedSession(cookieSessionFromSerialized(persisted.jar, options), {
256
+ ...(persisted.accountHint === undefined ? {} : { accountHint: persisted.accountHint }),
257
+ authenticatedAt: persisted.authenticatedAt,
258
+ }));
258
259
  });
259
260
  }
@@ -1,5 +1,6 @@
1
1
  import { glyph, type, space } from '../theme.js';
2
- import { visualWidth, padEndV, wrapAnsiToVisualWidth } from '../text.js';
2
+ import { visualWidth, padEndV, wrapAnsiToVisualWidth, clipAnsiToVisualWidth } from '../text.js';
3
+ import { pickIcon } from '../icons.js';
3
4
  import { createPainter } from './painter.js';
4
5
  import { startRawInput } from './input-session.js';
5
6
  import { t } from '../../i18n/index.js';
@@ -60,6 +61,12 @@ export function nextIndex(current, key, len, pageSize = 5) {
60
61
  return current;
61
62
  }
62
63
  }
64
+ export function menuColumns(options) {
65
+ return options.reduce((widths, option) => ({
66
+ label: Math.max(widths.label, visualWidth(option.label)),
67
+ hint: Math.max(widths.hint, option.hint ? visualWidth(option.hint) : 0),
68
+ }), { label: 0, hint: 0 });
69
+ }
63
70
  function normalizedWidth(cols) {
64
71
  return Number.isFinite(cols) ? Math.max(1, Math.floor(cols)) : Number.POSITIVE_INFINITY;
65
72
  }
@@ -69,7 +76,36 @@ function renderIndentedText(label, cols, style) {
69
76
  const contentWidth = Math.max(1, width - visualWidth(indent));
70
77
  return wrapAnsiToVisualWidth(style(label), contentWidth).map((line) => `${indent}${line}`);
71
78
  }
72
- export function renderMenuOption(option, selected, labelWidth = visualWidth(option.label), cols = Number.POSITIVE_INFINITY) {
79
+ const MIN_LABEL_COLUMN = 24;
80
+ function clipWithEllipsis(value, width) {
81
+ if (visualWidth(value) <= width)
82
+ return value;
83
+ const ellipsis = pickIcon('…', '~');
84
+ return clipAnsiToVisualWidth(value, width - visualWidth(ellipsis)) + ellipsis;
85
+ }
86
+ function fitColumns(columns, contentWidth) {
87
+ if (columns.label + 2 + columns.hint <= contentWidth)
88
+ return columns;
89
+ const hint = Math.min(columns.hint, Math.max(contentWidth - 2 - columns.label, Math.ceil(contentWidth / 3)));
90
+ const label = Math.min(columns.label, contentWidth - 2 - hint);
91
+ return label >= MIN_LABEL_COLUMN ? { label, hint } : undefined;
92
+ }
93
+ function optionCells(option, columns, contentWidth) {
94
+ const hint = option.hint ?? '';
95
+ if (option.hintColumn) {
96
+ const fitted = fitColumns(columns, contentWidth);
97
+ return fitted
98
+ ? {
99
+ label: padEndV(clipWithEllipsis(option.label, fitted.label), fitted.label),
100
+ hint: clipWithEllipsis(hint, fitted.hint),
101
+ }
102
+ : { label: option.label, hint: '' };
103
+ }
104
+ const hintWidth = hint ? 2 + visualWidth(hint) : 0;
105
+ const labelWidth = columns.label + hintWidth <= contentWidth ? columns.label : visualWidth(option.label);
106
+ return { label: padEndV(option.label, labelWidth), hint };
107
+ }
108
+ export function renderMenuOption(option, selected, columns = menuColumns([option]), cols = Number.POSITIVE_INFINITY) {
73
109
  const width = normalizedWidth(cols);
74
110
  const cursor = glyph.cursor();
75
111
  const gap = ' '.repeat(visualWidth(cursor));
@@ -78,18 +114,17 @@ export function renderMenuOption(option, selected, labelWidth = visualWidth(opti
78
114
  const prefix = prefixes.find((candidate) => visualWidth(candidate) < width) ?? '';
79
115
  const continuation = ' '.repeat(visualWidth(prefix));
80
116
  const contentWidth = Math.max(1, width - visualWidth(prefix));
81
- const hintWidth = option.hint ? 2 + visualWidth(option.hint) : 0;
82
- const paddedWidth = labelWidth + hintWidth <= contentWidth ? labelWidth : visualWidth(option.label);
83
- const padded = padEndV(option.label, paddedWidth);
84
- const label = selected ? type.active(padded) : type.body(padded);
85
- const hint = option.hint ? ` ${type.hint(option.hint)}` : '';
117
+ const cells = optionCells(option, columns, contentWidth);
118
+ const style = selected ? type.active : option.dim ? type.hint : type.body;
119
+ const hint = cells.hint ? ` ${type.hint(cells.hint)}` : '';
120
+ const label = style(cells.label);
86
121
  return wrapAnsiToVisualWidth(`${label}${hint}`, contentWidth).map((line, index) => `${index === 0 ? prefix : continuation}${line}`);
87
122
  }
88
123
  export function renderMenu(state, cols = Number.POSITIVE_INFINITY) {
89
- const labelWidth = state.options.reduce((width, option) => Math.max(width, visualWidth(option.label)), 0);
124
+ const columns = menuColumns(state.options);
90
125
  const lines = state.title ? [...renderIndentedText(state.title, cols, type.heading), ''] : [];
91
126
  state.options.forEach((option, index) => {
92
- lines.push(...renderMenuOption(option, index === state.selectedIndex, labelWidth, cols));
127
+ lines.push(...renderMenuOption(option, index === state.selectedIndex, columns, cols));
93
128
  });
94
129
  if (state.footer) {
95
130
  lines.push('');