@nbtca/prompt 1.5.12 → 1.5.14

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.
package/dist/app/tabs.js CHANGED
@@ -2,7 +2,7 @@ import { t } from '../i18n/index.js';
2
2
  export function getAppTabs() {
3
3
  const trans = t();
4
4
  return [
5
- { id: 'home', title: 'Home' },
5
+ { id: 'home', title: trans.menu.home },
6
6
  { id: 'schedule', title: trans.timetable.menuEntry },
7
7
  { id: 'events', title: trans.menu.events },
8
8
  { id: 'docs', title: trans.menu.docs },
@@ -1,14 +1,14 @@
1
1
  import { type, space } from '../../core/theme.js';
2
2
  import { t } from '../../i18n/index.js';
3
3
  import { renderListFieldWithContext } from '../fields/list-field.js';
4
- import { visualWidth, wrapAnsiHanging, wrapAnsiWithIndent } from '../../core/text.js';
4
+ import { visualWidth, wrapAnsiWithIndent } from '../../core/text.js';
5
5
  import { loadingLines } from '../../core/components/spinner.js';
6
6
  function hintLines(label, cols) {
7
7
  return wrapAnsiWithIndent(type.hint(label), cols, space.indent);
8
8
  }
9
- function renderReader(lines, cols) {
9
+ function renderReader(render, cols) {
10
10
  const contentWidth = Math.max(1, Math.min(80, cols - visualWidth(space.indent)));
11
- return lines.flatMap((line) => wrapAnsiHanging(line, contentWidth).map((part) => `${space.indent}${part}`));
11
+ return render(contentWidth).map((line) => (line ? `${space.indent}${line}` : ''));
12
12
  }
13
13
  function listFieldForState(state) {
14
14
  switch (state.mode) {
@@ -40,7 +40,9 @@ export function renderDocs(state, cols = 80, bodyRows = Number.POSITIVE_INFINITY
40
40
  lines = loadingLines(trans.common.loading, cols);
41
41
  break;
42
42
  case 'sections':
43
- lines = state.sectionsField?.render(bodyRows, cols) ?? [];
43
+ lines = state.sectionsField
44
+ ? renderListFieldWithContext(state.stale ? [...hintLines(trans.docs.stale, cols), ''] : [], state.sectionsField, bodyRows, cols)
45
+ : [];
44
46
  break;
45
47
  case 'files':
46
48
  lines = state.filesField?.render(bodyRows, cols) ?? [];
@@ -72,7 +74,7 @@ export function renderDocs(state, cols = 80, bodyRows = Number.POSITIVE_INFINITY
72
74
  case 'reader':
73
75
  lines = state.readerLinksField
74
76
  ? state.readerLinksField.render(bodyRows, cols)
75
- : renderReader(state.readerLines ?? [], cols);
77
+ : renderReader(state.readerRender ?? (() => []), cols);
76
78
  break;
77
79
  case 'error':
78
80
  return hintLines(state.errorMessage ?? trans.docs.loadError, cols);
@@ -12,6 +12,7 @@ let state = { mode: 'loading' };
12
12
  let sections = [];
13
13
  let archivedGroups = new Map();
14
14
  let loaded = false;
15
+ let stale = false;
15
16
  let loadedLanguage = null;
16
17
  let currentSectionKey = null;
17
18
  let currentArchivedGroupKey = null;
@@ -210,7 +211,7 @@ function goToSections() {
210
211
  currentSectionKey = null;
211
212
  currentArchivedGroupKey = null;
212
213
  currentSearchResults = [];
213
- state = { mode: 'sections', sectionsField: buildSectionsField() };
214
+ state = { mode: 'sections', sectionsField: buildSectionsField(), stale };
214
215
  }
215
216
  function replaceSection(section) {
216
217
  sections = sections.map((current) => (current.key === section.key ? section : current));
@@ -338,7 +339,7 @@ async function openInReader(ctx, path, pushCurrent) {
338
339
  state = {
339
340
  mode: 'reader',
340
341
  readerTitle: doc.title,
341
- readerLines: doc.lines,
342
+ readerRender: doc.render,
342
343
  readerLinks: doc.links,
343
344
  };
344
345
  ctx.resetScroll();
@@ -401,13 +402,24 @@ export const docsView = {
401
402
  sections = localized;
402
403
  loaded = true;
403
404
  loadedLanguage = getCurrentLanguage();
404
- if (!cached || changed || state.mode !== 'sections')
405
+ stale = false;
406
+ if (!cached || (changed && state.mode === 'sections'))
405
407
  goToSections();
408
+ else if (state.mode === 'sections')
409
+ state = { ...state, stale };
406
410
  }
407
411
  catch {
408
412
  if (!isLifecycleActive(ctx, generation) || requestId !== sectionsRequestId)
409
413
  return;
410
- state = { mode: 'error', errorMessage: t().docs.loadError };
414
+ if (cached) {
415
+ loaded = true;
416
+ stale = true;
417
+ if (state.mode === 'sections')
418
+ state = { ...state, stale };
419
+ }
420
+ else {
421
+ state = { mode: 'error', errorMessage: t().docs.loadError };
422
+ }
411
423
  }
412
424
  if (isLifecycleActive(ctx, generation))
413
425
  ctx.rerender();
@@ -18,14 +18,14 @@ function backLabel() {
18
18
  function buildHubField() {
19
19
  const trans = t();
20
20
  const options = [
21
- { value: 'upcoming', label: trans.menu.events },
21
+ { value: 'upcoming', label: trans.calendar.next30Days },
22
22
  { value: 'week', label: trans.calendar.thisWeek },
23
23
  { value: 'month', label: trans.calendar.thisMonth },
24
24
  { value: 'search', label: trans.calendar.search },
25
25
  { value: 'past', label: trans.calendar.pastEvents },
26
26
  { value: 'heatmap', label: trans.calendar.heatmap.title },
27
27
  ];
28
- return new ListField({ title: trans.menu.events, options });
28
+ return new ListField({ title: trans.calendar.browse, options });
29
29
  }
30
30
  function buildListField(title, events, maxVisible) {
31
31
  const trans = t();
@@ -151,7 +151,7 @@ export const eventsView = {
151
151
  return;
152
152
  const now = new Date();
153
153
  if (result.selected === 'upcoming') {
154
- showList(t().menu.events, currentEvents(calendar, now), ctx);
154
+ showList(t().calendar.next30Days, currentEvents(calendar, now), ctx);
155
155
  return;
156
156
  }
157
157
  if (result.selected === 'week') {
@@ -50,37 +50,26 @@ function renderWeekAheadGrid(classDays, eventDays, cols) {
50
50
  const blankCell = ' ';
51
51
  const rowLabelW = Math.max(visualWidth(trans.timetable.weekAheadClasses), visualWidth(trans.menu.events)) + 1;
52
52
  const days = [1, 2, 3, 4, 5, 6, 7];
53
+ const classCell = (wd) => classDays[wd - 1] ? hasClassChar : wd >= 6 ? weekendChar : freeChar;
54
+ const eventCell = (wd) => eventDays ? (eventDays[wd - 1] ? hasClassChar : freeChar) : blankCell;
55
+ const legendText = `${hasClassChar} ${trans.timetable.weekAheadBusy} ${freeChar} ${trans.timetable.weekAheadFree} ${weekendChar} ${trans.timetable.weekAheadNone}`;
53
56
  const dayLabels = days.map((wd) => type.hint(weekdayShortLabel(wd))).join(' ');
54
57
  const headerLine = `${space.indent}${padEndV('', rowLabelW)}${dayLabels}`;
55
- const classCells = days
56
- .map((wd) => {
57
- const isWeekend = wd === 6 || wd === 7;
58
- const glyphChar = isWeekend ? weekendChar : classDays[wd - 1] ? hasClassChar : freeChar;
59
- return type.body(glyphChar);
60
- })
61
- .join(' ');
58
+ const classCells = days.map((wd) => type.body(classCell(wd))).join(' ');
62
59
  const classLine = `${space.indent}${type.hint(padEndV(trans.timetable.weekAheadClasses, rowLabelW))}${classCells}`;
63
- const eventCells = days
64
- .map((wd) => {
65
- if (!eventDays)
66
- return blankCell;
67
- return type.body(eventDays[wd - 1] ? hasClassChar : freeChar);
68
- })
69
- .join(' ');
60
+ const eventCells = days.map((wd) => type.body(eventCell(wd))).join(' ');
70
61
  const eventLine = `${space.indent}${type.hint(padEndV(trans.menu.events, rowLabelW))}${eventCells}`;
71
- const legend = `${space.indent}${type.hint(`${hasClassChar} ${trans.timetable.weekAheadBusy} ${freeChar} ${trans.timetable.weekAheadFree} ${weekendChar} ${trans.timetable.weekAheadNone}`)}`;
62
+ const legend = `${space.indent}${type.hint(legendText)}`;
72
63
  const wideLines = [headerLine, classLine, eventLine, legend];
73
64
  const width = Number.isFinite(cols) ? Math.max(1, Math.floor(cols)) : Number.POSITIVE_INFINITY;
74
65
  if (wideLines.every((line) => visualWidth(line) <= width))
75
66
  return wideLines.join('\n');
76
67
  const compactHeading = wrappedIndentedLines(`${trans.timetable.weekAheadClasses} / ${trans.menu.events}`, cols, type.hint);
77
68
  const compactDays = days.flatMap((wd) => {
78
- const classCell = wd === 6 || wd === 7 ? weekendChar : classDays[wd - 1] ? hasClassChar : freeChar;
79
- const eventCell = eventDays ? (eventDays[wd - 1] ? hasClassChar : freeChar) : blankCell;
80
- const row = `${type.hint(weekdayShortLabel(wd))} ${type.body(classCell)} ${type.body(eventCell)}`;
69
+ const row = `${type.hint(weekdayShortLabel(wd))} ${type.body(classCell(wd))} ${type.body(eventCell(wd))}`;
81
70
  return wrappedIndentedLines(row, cols, (value) => value);
82
71
  });
83
- const compactLegend = wrappedIndentedLines(`${hasClassChar} ${trans.timetable.weekAheadBusy} ${freeChar} ${trans.timetable.weekAheadFree} ${weekendChar} ${trans.timetable.weekAheadNone}`, cols, type.hint);
72
+ const compactLegend = wrappedIndentedLines(legendText, cols, type.hint);
84
73
  return [...compactHeading, ...compactDays, ...compactLegend].join('\n');
85
74
  }
86
75
  export function renderHome(data, now, bodyRows = 100, cols = 80) {
@@ -5,12 +5,17 @@ export const KEY_ARROW_UP = '\x1b[A';
5
5
  export const KEY_ARROW_DOWN = '\x1b[B';
6
6
  export const KEY_ENTER_CR = '\r';
7
7
  export const KEY_ENTER_LF = '\n';
8
- export function defaultGridCursor(todayWeekday, periods) {
8
+ export function defaultGridCursor(todayWeekday, periods, todayHasClasses = false) {
9
9
  const sorted = [...periods].sort((a, b) => a.period - b.period);
10
10
  const firstPeriod = sorted[0]?.period ?? 1;
11
- const weekday = (todayWeekday >= 1 && todayWeekday <= 5 ? todayWeekday : 1);
11
+ const weekday = ((todayWeekday >= 1 && todayWeekday <= 5) || todayHasClasses ? todayWeekday : 1);
12
12
  return { weekday, period: firstPeriod };
13
13
  }
14
+ export function todayGridCursor(schedule, periods, now) {
15
+ const weekday = schedule.weekdayAt(now);
16
+ const week = schedule.weekAt(now);
17
+ return defaultGridCursor(weekday, periods, week >= 1 && schedule.meetingsOnDay(week, weekday).length > 0);
18
+ }
14
19
  export function moveCursorWeekday(cursor, delta) {
15
20
  return {
16
21
  ...cursor,
@@ -4,7 +4,7 @@ import { captureFooterHint, 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
- import { defaultGridCursor, handleGridKey } from './schedule-grid-cursor.js';
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
10
  import { AuthError } from '../../auth/errors.js';
@@ -73,7 +73,7 @@ function returnToHub() {
73
73
  ...(state.term ? { term: state.term } : {}),
74
74
  weekOne: backWeekOne,
75
75
  timetable: tt,
76
- gridCursor: state.gridCursor ?? defaultGridCursor(schedule.weekdayAt(new Date()), tt.periods),
76
+ gridCursor: state.gridCursor ?? todayGridCursor(schedule, tt.periods, new Date()),
77
77
  };
78
78
  return true;
79
79
  }
@@ -213,7 +213,7 @@ async function fetchAndShowHub(ctx, term, key, weekOne, generation = lifecycleGe
213
213
  term,
214
214
  weekOne,
215
215
  timetable,
216
- gridCursor: defaultGridCursor(schedule.weekdayAt(new Date()), timetable.periods),
216
+ gridCursor: todayGridCursor(schedule, timetable.periods, new Date()),
217
217
  };
218
218
  }
219
219
  catch (err) {
@@ -277,7 +277,7 @@ export const scheduleView = {
277
277
  key: ptr.termKey,
278
278
  weekOne: ptr.weekOneMonday,
279
279
  timetable: cached,
280
- gridCursor: defaultGridCursor(schedule.weekdayAt(new Date()), cached.periods),
280
+ gridCursor: todayGridCursor(schedule, cached.periods, new Date()),
281
281
  };
282
282
  }
283
283
  else {
@@ -453,7 +453,7 @@ export const scheduleView = {
453
453
  {
454
454
  const schedule = createTimetableSchedule(tt, { weekOneMonday: hubWeekOne });
455
455
  const now = new Date();
456
- const cursor = state.gridCursor ?? defaultGridCursor(schedule.weekdayAt(now), tt.periods);
456
+ const cursor = state.gridCursor ?? todayGridCursor(schedule, tt.periods, now);
457
457
  const week = Math.max(1, schedule.weekAt(now));
458
458
  const nav = handleGridKey(key, cursor, tt, week);
459
459
  if (nav.kind === 'moveCursor') {
@@ -536,7 +536,7 @@ export const scheduleView = {
536
536
  }
537
537
  const schedule = createTimetableSchedule(tt, { weekOneMonday: weekOne });
538
538
  const now = new Date();
539
- const cursor = state.gridCursor ?? defaultGridCursor(schedule.weekdayAt(now), tt.periods);
539
+ const cursor = state.gridCursor ?? todayGridCursor(schedule, tt.periods, now);
540
540
  const week = Math.max(1, schedule.weekAt(now));
541
541
  const nav = handleGridKey(key, cursor, tt, week);
542
542
  if (nav.kind === 'moveCursor') {
@@ -10,6 +10,23 @@ let state = { mode: 'menu' };
10
10
  function currentHint(current, hint) {
11
11
  return current ? { hint } : {};
12
12
  }
13
+ function modeLabel(mode) {
14
+ const theme = t().theme;
15
+ return {
16
+ auto: theme.modeAuto,
17
+ ascii: theme.modeAscii,
18
+ unicode: theme.modeUnicode,
19
+ on: theme.modeOn,
20
+ off: theme.modeOff,
21
+ }[mode];
22
+ }
23
+ function modeOptions(modes, current) {
24
+ return modes.map((mode) => ({
25
+ value: mode,
26
+ label: modeLabel(mode),
27
+ ...currentHint(mode === current, t().common.current),
28
+ }));
29
+ }
13
30
  function buildMenuField(statusMessage) {
14
31
  const trans = t();
15
32
  const prefs = loadPreferences();
@@ -20,8 +37,8 @@ function buildMenuField(statusMessage) {
20
37
  label: trans.language.selectLanguage,
21
38
  hint: currentLang === 'zh' ? trans.language.zh : trans.language.en,
22
39
  },
23
- { value: 'icon', label: trans.theme.iconMode, hint: prefs.iconMode },
24
- { value: 'color', label: trans.theme.colorMode, hint: prefs.colorMode },
40
+ { value: 'icon', label: trans.theme.iconMode, hint: modeLabel(prefs.iconMode) },
41
+ { value: 'color', label: trans.theme.colorMode, hint: modeLabel(prefs.colorMode) },
25
42
  { value: 'reset', label: trans.theme.resetLabel },
26
43
  { value: 'about', label: trans.about.title },
27
44
  ];
@@ -90,23 +107,7 @@ export const settingsView = {
90
107
  }
91
108
  if (result.selected === 'icon') {
92
109
  const prefs = loadPreferences();
93
- const options = [
94
- {
95
- value: 'auto',
96
- label: trans.theme.modeAuto,
97
- ...currentHint(prefs.iconMode === 'auto', trans.common.current),
98
- },
99
- {
100
- value: 'ascii',
101
- label: trans.theme.modeAscii,
102
- ...currentHint(prefs.iconMode === 'ascii', trans.common.current),
103
- },
104
- {
105
- value: 'unicode',
106
- label: trans.theme.modeUnicode,
107
- ...currentHint(prefs.iconMode === 'unicode', trans.common.current),
108
- },
109
- ];
110
+ const options = modeOptions(['auto', 'ascii', 'unicode'], prefs.iconMode);
110
111
  const idx = Math.max(0, options.findIndex((o) => o.value === prefs.iconMode));
111
112
  state = {
112
113
  mode: 'icon',
@@ -120,23 +121,7 @@ export const settingsView = {
120
121
  }
121
122
  if (result.selected === 'color') {
122
123
  const prefs = loadPreferences();
123
- const options = [
124
- {
125
- value: 'auto',
126
- label: trans.theme.modeAuto,
127
- ...currentHint(prefs.colorMode === 'auto', trans.common.current),
128
- },
129
- {
130
- value: 'on',
131
- label: trans.theme.modeOn,
132
- ...currentHint(prefs.colorMode === 'on', trans.common.current),
133
- },
134
- {
135
- value: 'off',
136
- label: trans.theme.modeOff,
137
- ...currentHint(prefs.colorMode === 'off', trans.common.current),
138
- },
139
- ];
124
+ const options = modeOptions(['auto', 'on', 'off'], prefs.colorMode);
140
125
  const idx = Math.max(0, options.findIndex((o) => o.value === prefs.colorMode));
141
126
  state = {
142
127
  mode: 'color',
@@ -172,6 +172,7 @@ export function createCampusCookieSession(options = {}) {
172
172
  if (finalUrl.hostname.toLowerCase() !== JWXT_HOST ||
173
173
  finalUrl.pathname.includes('/authserver/login') ||
174
174
  finalUrl.pathname.includes('/users/sign_in') ||
175
+ finalUrl.pathname === '/jwglxt/xtgl/login_slogin.html' ||
175
176
  finalUrl.pathname === '/vpn_key/update')
176
177
  throw new SessionExpiredError();
177
178
  }
@@ -0,0 +1,141 @@
1
+ const HIDDEN = /<!--[\s\S]*?(?:-->|$)|<(script|style|template|textarea|title|noscript|iframe|xmp|noembed|noframes)\b[\s\S]*?(?:<\/\1\s*>|$)/gi;
2
+ const VOID = new Set(['area', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'wbr']);
3
+ const TAG_NAME = /<(\/?)([a-zA-Z][^\t\n\f\r />]*)/y;
4
+ const ATTRIBUTE_NAME = /[^\t\n\f\r />=]+/y;
5
+ const SPACE = /[\t\n\f\r ]*/y;
6
+ const UNQUOTED = /[^\t\n\f\r >]*/y;
7
+ const ENTITY = /&(?:#[xX]([0-9a-fA-F]+);?|#([0-9]+);?|(amp|lt|gt|quot|apos|nbsp)(?:;|(?![\w=])))/g;
8
+ const NAMED = {
9
+ amp: '&',
10
+ lt: '<',
11
+ gt: '>',
12
+ quot: '"',
13
+ apos: "'",
14
+ nbsp: ' ',
15
+ };
16
+ function decode(text) {
17
+ return text.replace(ENTITY, (match, hex, decimal, name) => {
18
+ if (name)
19
+ return NAMED[name] ?? match;
20
+ const code = hex ? Number.parseInt(hex, 16) : Number(decimal);
21
+ return code > 0 && code <= 0x10ffff && (code < 0xd800 || code > 0xdfff)
22
+ ? String.fromCodePoint(code)
23
+ : '�';
24
+ });
25
+ }
26
+ function sticky(pattern, html, at) {
27
+ pattern.lastIndex = at;
28
+ return pattern.exec(html)?.[0] ?? '';
29
+ }
30
+ function* tags(html) {
31
+ let at = html.indexOf('<');
32
+ while (at >= 0) {
33
+ TAG_NAME.lastIndex = at;
34
+ const head = TAG_NAME.exec(html);
35
+ if (!head) {
36
+ at = html.indexOf('<', at + 1);
37
+ continue;
38
+ }
39
+ const attributes = new Map();
40
+ let cursor = at + head[0].length;
41
+ while (cursor < html.length && html[cursor] !== '>') {
42
+ cursor += sticky(SPACE, html, cursor).length;
43
+ if (html[cursor] === '/' || html[cursor] === '>') {
44
+ if (html[cursor] === '/')
45
+ cursor += 1;
46
+ continue;
47
+ }
48
+ const name = sticky(ATTRIBUTE_NAME, html, cursor);
49
+ cursor += Math.max(name.length, 1);
50
+ cursor += sticky(SPACE, html, cursor).length;
51
+ let value = '';
52
+ if (html[cursor] === '=') {
53
+ cursor += 1 + sticky(SPACE, html, cursor + 1).length;
54
+ const quote = html[cursor];
55
+ if (quote === '"' || quote === "'") {
56
+ const close = html.indexOf(quote, cursor + 1);
57
+ if (close < 0)
58
+ return;
59
+ value = html.slice(cursor + 1, close);
60
+ cursor = close + 1;
61
+ }
62
+ else {
63
+ value = sticky(UNQUOTED, html, cursor);
64
+ cursor += value.length;
65
+ }
66
+ }
67
+ const key = name.toLowerCase();
68
+ if (name && !attributes.has(key))
69
+ attributes.set(key, decode(value));
70
+ }
71
+ if (cursor >= html.length)
72
+ return;
73
+ yield {
74
+ name: (head[2] ?? '').toLowerCase(),
75
+ closing: head[1] === '/',
76
+ attributes,
77
+ start: at,
78
+ end: cursor + 1,
79
+ };
80
+ at = html.indexOf('<', cursor + 1);
81
+ }
82
+ }
83
+ function visible(html) {
84
+ return html.replace(/\r\n?/g, '\n').replace(HIDDEN, '');
85
+ }
86
+ export function readLoginForm(source) {
87
+ let action;
88
+ let execution;
89
+ let salt;
90
+ let inForm = false;
91
+ for (const tag of tags(visible(source))) {
92
+ const id = tag.attributes.get('id');
93
+ if (tag.name === 'form') {
94
+ if (tag.closing)
95
+ inForm = false;
96
+ else if (!inForm && id === 'pwdFromId') {
97
+ inForm = true;
98
+ action ??= tag.attributes.get('action');
99
+ }
100
+ continue;
101
+ }
102
+ if (!inForm || tag.closing)
103
+ continue;
104
+ const name = tag.attributes.get('name');
105
+ const value = tag.name === 'input' ? (tag.attributes.get('value')?.trim() ?? '') : '';
106
+ if (execution === undefined && (name === 'execution' || id === 'execution'))
107
+ execution = value;
108
+ if (salt === undefined && (id === 'pwdEncryptSalt' || name === 'pwdEncryptSalt'))
109
+ salt = value;
110
+ }
111
+ return { action, execution: execution ?? '', salt: salt ?? '' };
112
+ }
113
+ export function errorText(source, matches) {
114
+ const html = visible(source);
115
+ const parts = [];
116
+ let open;
117
+ let last = 0;
118
+ for (const tag of tags(html)) {
119
+ if (open) {
120
+ if (tag.name === open.name)
121
+ open.depth += tag.closing ? -1 : 1;
122
+ parts.push(html.slice(last, tag.start));
123
+ last = tag.end;
124
+ if (open.depth === 0)
125
+ open = undefined;
126
+ }
127
+ else if (!tag.closing && !VOID.has(tag.name) && matches(tag)) {
128
+ open = { name: tag.name, depth: 1 };
129
+ last = tag.end;
130
+ }
131
+ }
132
+ if (open)
133
+ parts.push(html.slice(last));
134
+ return decode(parts.join(''));
135
+ }
136
+ export function hasId(id) {
137
+ return (tag) => tag.attributes.get('id') === id;
138
+ }
139
+ export function hasClass(name) {
140
+ return (tag) => (tag.attributes.get('class') ?? '').split(/[\t\n\f\r ]+/).includes(name);
141
+ }
@@ -1,6 +1,6 @@
1
1
  import { createCipheriv, randomFillSync } from 'node:crypto';
2
- import { load } from 'cheerio';
3
2
  import { AuthError } from './errors.js';
3
+ import { errorText, hasClass, hasId, readLoginForm } from './login-page.js';
4
4
  import { JWXT_HOST, cookieSessionFromSerialized, createCampusCookieSession, } from './cookie-transport.js';
5
5
  const WEBVPN_ENTRY = new URL('https://webvpn.nbt.edu.cn/');
6
6
  const SSO_ENTRY = new URL(`https://${JWXT_HOST}/sso/jziotlogin`);
@@ -49,12 +49,8 @@ export function encryptCampusPassword(password, salt, source = secureRandomBytes
49
49
  }
50
50
  }
51
51
  function parseLoginForm(html, responseUrl) {
52
- const $ = load(html);
53
- const form = $('#pwdFromId');
54
- const execution = String(form.find('input[name="execution"], #execution').first().val() ?? '').trim();
55
- const salt = String(form.find('#pwdEncryptSalt, input[name="pwdEncryptSalt"]').first().val() ?? '').trim();
56
- const actionValue = form.attr('action');
57
- if (form.length === 0 || !execution || !salt || !actionValue) {
52
+ const { action: actionValue, execution, salt } = readLoginForm(html);
53
+ if (!execution || !salt || !actionValue) {
58
54
  throw new AuthError('LOGIN_PAGE_CHANGED', 'login-page', 'The campus login page changed unexpectedly.');
59
55
  }
60
56
  let current;
@@ -75,12 +71,11 @@ function hasLoginFingerprint(html) {
75
71
  return /(?:id=["']pwdFromId["']|id=["']pwdEncryptSalt["']|name=["']execution["'])/i.test(html);
76
72
  }
77
73
  function classifyRejectedLogin(html) {
78
- const $ = load(html);
79
74
  const visibleError = [
80
- $('#showErrorTip').text(),
81
- $('#showWarnTip').text(),
82
- $('#errorMsg').text(),
83
- $('.alert-danger').text(),
75
+ errorText(html, hasId('showErrorTip')),
76
+ errorText(html, hasId('showWarnTip')),
77
+ errorText(html, hasId('errorMsg')),
78
+ errorText(html, hasClass('alert-danger')),
84
79
  ]
85
80
  .join(' ')
86
81
  .replace(/\s+/g, ' ')
package/dist/core/text.js CHANGED
@@ -240,6 +240,9 @@ function applyKinsoku(tokens, start, end) {
240
240
  }
241
241
  return end;
242
242
  }
243
+ function isWideBoundary(tokens, index) {
244
+ return ((visibleAt(tokens, index)?.width ?? 0) > 1 || (visibleAt(tokens, index - 1)?.width ?? 0) > 1);
245
+ }
243
246
  export function wrapAnsiToVisualWidth(str, maxWidth, continuationWidth = maxWidth) {
244
247
  const widthLimit = Math.max(1, Math.floor(maxWidth));
245
248
  const nextLimit = Math.max(1, Math.floor(continuationWidth));
@@ -254,6 +257,8 @@ export function wrapAnsiToVisualWidth(str, maxWidth, continuationWidth = maxWidt
254
257
  let width = 0;
255
258
  let hasVisible = false;
256
259
  let lastWhitespace = -1;
260
+ let lastWideBoundary = -1;
261
+ let previousWide = false;
257
262
  let index = start;
258
263
  while (index < tokens.length) {
259
264
  const token = tokens[index];
@@ -263,11 +268,15 @@ export function wrapAnsiToVisualWidth(str, maxWidth, continuationWidth = maxWidt
263
268
  index += 1;
264
269
  continue;
265
270
  }
271
+ const wide = token.width > 1;
272
+ if (hasVisible && (wide || previousWide) && !token.whitespace)
273
+ lastWideBoundary = index;
266
274
  const limit = lines.length === 0 ? widthLimit : nextLimit;
267
275
  if (width + token.width > limit && hasVisible)
268
276
  break;
269
277
  width += token.width;
270
278
  hasVisible = true;
279
+ previousWide = wide;
271
280
  if (token.whitespace)
272
281
  lastWhitespace = index;
273
282
  index += 1;
@@ -279,9 +288,14 @@ export function wrapAnsiToVisualWidth(str, maxWidth, continuationWidth = maxWidt
279
288
  const overflow = tokens[index];
280
289
  let end = index;
281
290
  let next = index;
291
+ const wideBreak = lastWideBoundary > lastWhitespace + 1 ? applyKinsoku(tokens, start, lastWideBoundary) : -1;
282
292
  if (overflow?.whitespace) {
283
293
  next = index + 1;
284
294
  }
295
+ else if (wideBreak > lastWhitespace + 1 && isWideBoundary(tokens, wideBreak)) {
296
+ end = wideBreak;
297
+ next = wideBreak;
298
+ }
285
299
  else if (lastWhitespace >= start) {
286
300
  end = lastWhitespace;
287
301
  next = lastWhitespace + 1;
@@ -302,18 +316,6 @@ export function wrapAnsiToVisualWidth(str, maxWidth, continuationWidth = maxWidt
302
316
  }
303
317
  return lines.length > 0 ? lines : [''];
304
318
  }
305
- const LEADING_MARKER = /^(\s*)((?:[-*+•]|\d{1,3}[.)])\s+)?/u;
306
- export function wrapAnsiHanging(str, maxWidth) {
307
- const width = Number.isFinite(maxWidth)
308
- ? Math.max(1, Math.floor(maxWidth))
309
- : Number.POSITIVE_INFINITY;
310
- const match = LEADING_MARKER.exec(stripAnsi(str));
311
- const hang = visualWidth((match?.[1] ?? '') + (match?.[2] ?? ''));
312
- if (hang === 0 || hang >= width)
313
- return wrapAnsiToVisualWidth(str, width);
314
- const continuation = ' '.repeat(hang);
315
- return wrapAnsiToVisualWidth(str, width, width - hang).map((line, index) => index === 0 ? line : continuation + line);
316
- }
317
319
  export function wrapAnsiWithIndent(str, maxWidth, preferredIndent = '') {
318
320
  const width = Number.isFinite(maxWidth)
319
321
  ? Math.max(1, Math.floor(maxWidth))
@@ -22,6 +22,7 @@ export const c = {
22
22
  subtle: (s) => chalk.gray(s),
23
23
  label: (s) => chalk.bold.cyan(s),
24
24
  url: (s) => chalk.dim.underline(s),
25
+ code: (s) => chalk.yellow(s),
25
26
  version: (s) => chalk.dim(s),
26
27
  latency: (ms) => {
27
28
  const s = `${ms}ms`;
@@ -35,6 +36,7 @@ export const c = {
35
36
  export const glyph = {
36
37
  cursor: () => pickIcon('→', '>'),
37
38
  rule: () => pickIcon('─', '-'),
39
+ bar: () => pickIcon('│', '|'),
38
40
  bullet: () => pickIcon('·', '.'),
39
41
  dot: () => pickIcon('●', '*'),
40
42
  updown: () => pickIcon('↑↓', 'up/down'),
@@ -1,5 +1,6 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  import { createDocsClient } from '@nbtca/docs';
3
+ import { createDocsStore } from './docs-store.js';
3
4
  const contextKey = Symbol.for('@nbtca/prompt/docs-fetch-context/v2');
4
5
  const globalWithContext = globalThis;
5
6
  function abortError(signal) {
@@ -158,7 +159,8 @@ function beginDocsFetch() {
158
159
  },
159
160
  };
160
161
  }
161
- const defaultClient = createDocsClient();
162
+ const store = createDocsStore();
163
+ const defaultClient = createDocsClient({ store });
162
164
  const clientsBySignal = new WeakMap();
163
165
  const clients = new Set([defaultClient]);
164
166
  function clientFor(signal) {
@@ -167,7 +169,7 @@ function clientFor(signal) {
167
169
  const existing = clientsBySignal.get(signal);
168
170
  if (existing)
169
171
  return existing;
170
- const client = createDocsClient();
172
+ const client = createDocsClient({ store });
171
173
  clientsBySignal.set(signal, client);
172
174
  clients.add(client);
173
175
  signal.addEventListener('abort', () => {
@@ -177,6 +179,9 @@ function clientFor(signal) {
177
179
  }, { once: true });
178
180
  return client;
179
181
  }
182
+ export function peekDocs() {
183
+ return defaultClient.peekAll();
184
+ }
180
185
  export function clearDocsClients() {
181
186
  for (const client of clients)
182
187
  client.clear();