@nbtca/prompt 1.5.13 → 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.
@@ -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,
@@ -3,7 +3,7 @@ import { c, type, space, glyph } from '../../core/theme.js';
3
3
  import { pickIcon } from '../../core/icons.js';
4
4
  import { t, fmt } from '../../i18n/index.js';
5
5
  import { renderListFieldWithContext } from '../fields/list-field.js';
6
- import { renderNextClassBanner, renderWeekGrid, renderUnresolvedItems, renderTodayTimeline, weekdayShortLabel, renderTermDensity, renderMeetingDetail, renderDayTimeline, renderDaySwitcher, } from '../../features/schedule-render.js';
6
+ import { renderNextClassBanner, renderWeekGrid, renderUnresolvedItems, renderTodayTimeline, weekdayShortLabel, renderTermDensity, renderMeetingDetail, renderDayTimeline, renderDaySwitcher, renderWeekAgenda, lineBudget, } from '../../features/schedule-render.js';
7
7
  import { sanitizeTerminalLine, visualWidth, wrapAnsiWithIndent } from '../../core/text.js';
8
8
  import { isoDayDifference } from '../../core/calendar-day.js';
9
9
  import { loadingLines } from '../../core/components/spinner.js';
@@ -42,7 +42,7 @@ export function hubShortcuts(tt) {
42
42
  return shortcuts;
43
43
  }
44
44
  function renderShortcutLines(shortcuts, cols, compact = false) {
45
- const available = Math.max(1, cols - visualWidth(space.indent));
45
+ const available = Math.max(1, lineBudget(cols) - visualWidth(space.indent));
46
46
  const parts = shortcuts.map((shortcut) => {
47
47
  const text = compact
48
48
  ? shortcut.showKey === false
@@ -105,37 +105,64 @@ function hubPreGridLines(state, now, cols) {
105
105
  week: String(week),
106
106
  })),
107
107
  ...renderTodayTimeline(today, tt.periods, now, cols).split('\n'),
108
+ '',
108
109
  weekHeading,
109
110
  ];
110
111
  return { inlineLines, fallbackLines: [...lines, weekHeading], week, tt };
111
112
  }
112
113
  const MIN_GRID_COLS = 100;
113
- function gridFitsInline(precedingLineCount, tt, week, now, bodyRows, cols, cursor, reservedRows) {
114
+ function fittingWeekGrid(tt, week, now, rows, cols, cursor) {
114
115
  if (cols < MIN_GRID_COLS)
115
- return false;
116
- const gridLines = renderWeekGrid(tt, week, now, cols, cursor).split('\n');
117
- return precedingLineCount + gridLines.length <= bodyRows - reservedRows;
116
+ return null;
117
+ const grid = renderWeekGrid(tt, week, now, cols, cursor).split('\n');
118
+ return grid.length <= rows ? grid : null;
118
119
  }
119
- function renderAdaptiveWeekGrid(inlineLines, fallbackLines, tt, week, todayWd, now, bodyRows, cols, cursor, reservedRows) {
120
- if (gridFitsInline(inlineLines.length, tt, week, now, bodyRows, cols, cursor, reservedRows)) {
121
- return [...inlineLines, ...renderWeekGrid(tt, week, now, cols, cursor).split('\n')];
122
- }
120
+ function renderDayFallback(tt, week, todayWd, now, cols, cursor) {
123
121
  const selectedWd = cursor?.weekday ?? todayWd;
124
- const dayMeetings = createTimetableSchedule(tt).meetingsOnDay(week, selectedWd);
125
122
  return [
126
- ...fallbackLines,
127
123
  renderDaySwitcher(selectedWd, todayWd, cols),
128
- ...renderDayTimeline(dayMeetings, tt.periods, now, selectedWd === todayWd, cursor?.period, cols).split('\n'),
124
+ ...renderDayTimeline(createTimetableSchedule(tt).meetingsOnDay(week, selectedWd), tt.periods, now, { weekday: selectedWd, isToday: selectedWd === todayWd }, cursor?.period, cols).split('\n'),
129
125
  ];
130
126
  }
127
+ function renderAdaptiveWeekGrid(inlineLines, fallbackLines, tt, week, todayWd, now, bodyRows, cols, cursor, reservedRows) {
128
+ const grid = fittingWeekGrid(tt, week, now, bodyRows - reservedRows - inlineLines.length, cols, cursor);
129
+ if (grid)
130
+ return [...inlineLines, ...grid];
131
+ return [...fallbackLines, ...renderDayFallback(tt, week, todayWd, now, cols, cursor)];
132
+ }
133
+ function renderWeekBody(tt, week, todayWd, now, bodyRows, cols, cursor) {
134
+ const rows = Math.max(0, Math.floor(bodyRows));
135
+ const title = heading(t().timetable.hubWeek);
136
+ const layouts = [
137
+ fittingWeekGrid(tt, week, now, rows - 2, cols, cursor),
138
+ renderWeekAgenda(tt, week, now, cols, cursor),
139
+ renderWeekAgenda(tt, week, now, cols, cursor, true),
140
+ ];
141
+ for (const layout of layouts) {
142
+ if (!layout)
143
+ continue;
144
+ if (layout.length + 2 <= rows)
145
+ return [title, '', ...layout];
146
+ if (layout.length + 1 <= rows)
147
+ return [title, ...layout];
148
+ }
149
+ const dense = layouts.at(-1);
150
+ if (dense && dense.length <= rows)
151
+ return dense;
152
+ return [
153
+ ...hintLines(t().timetable.weekTooSmall, cols),
154
+ ...renderDayFallback(tt, week, todayWd, now, cols, cursor),
155
+ ];
156
+ }
157
+ const MIN_HUB_CONTENT_ROWS = 4;
131
158
  function renderHubBody(state, now, bodyRows, cols) {
132
159
  const tt = state.timetable;
133
160
  const pre = hubPreGridLines(state, now, cols);
134
161
  const shortcuts = tt ? hubShortcuts(tt) : [];
135
162
  const rows = Math.max(0, Math.floor(bodyRows));
136
- const build = (shortcutLines) => {
163
+ const build = (shortcutLines, gap = true) => {
137
164
  const tail = [];
138
- if (pre && (state.statusMessage || shortcutLines.length > 0))
165
+ if (gap && pre && (state.statusMessage || shortcutLines.length > 0))
139
166
  tail.push('');
140
167
  if (state.statusMessage) {
141
168
  tail.push(...hintLines(state.statusMessage, cols));
@@ -148,9 +175,15 @@ function renderHubBody(state, now, bodyRows, cols) {
148
175
  : [];
149
176
  return { content, tail };
150
177
  };
151
- const full = build(renderShortcutLines(shortcuts, cols));
178
+ const labelled = renderShortcutLines(shortcuts, cols);
179
+ const full = build(labelled);
152
180
  if (full.content.length + full.tail.length <= rows)
153
181
  return [...full.content, ...full.tail];
182
+ const tight = build(labelled, false);
183
+ if (rows - tight.tail.length >= MIN_HUB_CONTENT_ROWS) {
184
+ const content = tight.content.filter((line) => line !== '');
185
+ return [...content.slice(0, rows - tight.tail.length), ...tight.tail];
186
+ }
154
187
  const compact = build(renderShortcutLines(shortcuts, cols, true));
155
188
  if (compact.tail.length >= rows)
156
189
  return rows > 0 ? compact.tail.slice(-rows) : [];
@@ -241,16 +274,25 @@ export function renderSchedule(state, now, bodyRows = 100, cols = 80) {
241
274
  const schedule = createTimetableSchedule(state.timetable, {
242
275
  weekOneMonday: state.weekOne,
243
276
  });
244
- const week = Math.max(1, schedule.weekAt(now));
245
- const weekLines = [heading(trans.timetable.hubWeek), ''];
246
- return renderAdaptiveWeekGrid(weekLines, weekLines, state.timetable, week, schedule.weekdayAt(now), now, bodyRows, cols, state.gridCursor, 2);
277
+ return renderWeekBody(state.timetable, Math.max(1, schedule.weekAt(now)), schedule.weekdayAt(now), now, bodyRows, cols, state.gridCursor);
247
278
  }
248
279
  case 'termDensity':
249
280
  if (!state.timetable || !state.weekOne)
250
281
  return [hint(trans.timetable.genericError)];
251
282
  return renderTermDensity(state.timetable.meetings, state.weekOne, createTimetableSchedule(state.timetable, { weekOneMonday: state.weekOne }).weekAt(now), cols).split('\n');
252
- case 'termPicker':
253
- return state.termField?.render(bodyRows, cols) ?? [];
283
+ case 'termPicker': {
284
+ if (!state.termField)
285
+ return [];
286
+ const note = state.termPickerNote
287
+ ? [
288
+ ...headingLines(trans.timetable.hubSwitchTerm, cols),
289
+ '',
290
+ ...hintLines(state.termPickerNote, cols),
291
+ '',
292
+ ]
293
+ : [];
294
+ return renderListFieldWithContext(note, state.termField, bodyRows, cols);
295
+ }
254
296
  case 'unresolved':
255
297
  return [
256
298
  heading(trans.timetable.unresolvedTitle),
@@ -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
- 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
+ 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
  }
@@ -73,7 +90,7 @@ function returnToHub() {
73
90
  ...(state.term ? { term: state.term } : {}),
74
91
  weekOne: backWeekOne,
75
92
  timetable: tt,
76
- gridCursor: state.gridCursor ?? defaultGridCursor(schedule.weekdayAt(new Date()), tt.periods),
93
+ gridCursor: state.gridCursor ?? todayGridCursor(schedule, tt.periods, new Date()),
77
94
  };
78
95
  return true;
79
96
  }
@@ -213,7 +230,7 @@ async function fetchAndShowHub(ctx, term, key, weekOne, generation = lifecycleGe
213
230
  term,
214
231
  weekOne,
215
232
  timetable,
216
- gridCursor: defaultGridCursor(schedule.weekdayAt(new Date()), timetable.periods),
233
+ gridCursor: todayGridCursor(schedule, timetable.periods, new Date()),
217
234
  };
218
235
  }
219
236
  catch (err) {
@@ -277,7 +294,7 @@ export const scheduleView = {
277
294
  key: ptr.termKey,
278
295
  weekOne: ptr.weekOneMonday,
279
296
  timetable: cached,
280
- gridCursor: defaultGridCursor(schedule.weekdayAt(new Date()), cached.periods),
297
+ gridCursor: todayGridCursor(schedule, cached.periods, new Date()),
281
298
  };
282
299
  }
283
300
  else {
@@ -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') {
@@ -453,7 +483,7 @@ export const scheduleView = {
453
483
  {
454
484
  const schedule = createTimetableSchedule(tt, { weekOneMonday: hubWeekOne });
455
485
  const now = new Date();
456
- const cursor = state.gridCursor ?? defaultGridCursor(schedule.weekdayAt(now), tt.periods);
486
+ const cursor = state.gridCursor ?? todayGridCursor(schedule, tt.periods, now);
457
487
  const week = Math.max(1, schedule.weekAt(now));
458
488
  const nav = handleGridKey(key, cursor, tt, week);
459
489
  if (nav.kind === 'moveCursor') {
@@ -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
  }),
@@ -536,7 +575,7 @@ export const scheduleView = {
536
575
  }
537
576
  const schedule = createTimetableSchedule(tt, { weekOneMonday: weekOne });
538
577
  const now = new Date();
539
- const cursor = state.gridCursor ?? defaultGridCursor(schedule.weekdayAt(now), tt.periods);
578
+ const cursor = state.gridCursor ?? todayGridCursor(schedule, tt.periods, now);
540
579
  const week = Math.max(1, schedule.weekAt(now));
541
580
  const nav = handleGridKey(key, cursor, tt, week);
542
581
  if (nav.kind === 'moveCursor') {
@@ -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,11 +5,29 @@ 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) {
11
12
  return current ? { hint } : {};
12
13
  }
14
+ function modeLabel(mode) {
15
+ const theme = t().theme;
16
+ return {
17
+ auto: theme.modeAuto,
18
+ ascii: theme.modeAscii,
19
+ unicode: theme.modeUnicode,
20
+ on: theme.modeOn,
21
+ off: theme.modeOff,
22
+ }[mode];
23
+ }
24
+ function modeOptions(modes, current) {
25
+ return modes.map((mode) => ({
26
+ value: mode,
27
+ label: modeLabel(mode),
28
+ ...currentHint(mode === current, t().common.current),
29
+ }));
30
+ }
13
31
  function buildMenuField(statusMessage) {
14
32
  const trans = t();
15
33
  const prefs = loadPreferences();
@@ -20,15 +38,15 @@ function buildMenuField(statusMessage) {
20
38
  label: trans.language.selectLanguage,
21
39
  hint: currentLang === 'zh' ? trans.language.zh : trans.language.en,
22
40
  },
23
- { value: 'icon', label: trans.theme.iconMode, hint: prefs.iconMode },
24
- { value: 'color', label: trans.theme.colorMode, hint: prefs.colorMode },
41
+ { value: 'icon', label: trans.theme.iconMode, hint: modeLabel(prefs.iconMode) },
42
+ { value: 'color', label: trans.theme.colorMode, hint: modeLabel(prefs.colorMode) },
25
43
  { value: 'reset', label: trans.theme.resetLabel },
26
44
  { value: 'about', label: trans.about.title },
27
45
  ];
28
46
  return {
29
47
  mode: 'menu',
30
48
  ...(statusMessage === undefined ? {} : { statusMessage }),
31
- menuField: new ListField({ title: trans.theme.chooseAction, options }),
49
+ menuField: new ListField({ options }),
32
50
  };
33
51
  }
34
52
  function goToMenu(statusMessage) {
@@ -90,28 +108,12 @@ export const settingsView = {
90
108
  }
91
109
  if (result.selected === 'icon') {
92
110
  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
- ];
111
+ const options = modeOptions(['auto', 'ascii', 'unicode'], prefs.iconMode);
110
112
  const idx = Math.max(0, options.findIndex((o) => o.value === prefs.iconMode));
111
113
  state = {
112
114
  mode: 'icon',
113
115
  subField: new ListField({
114
- title: trans.theme.chooseIconMode,
116
+ title: trans.theme.iconMode,
115
117
  options,
116
118
  initialIndex: idx,
117
119
  }),
@@ -120,28 +122,12 @@ export const settingsView = {
120
122
  }
121
123
  if (result.selected === 'color') {
122
124
  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
- ];
125
+ const options = modeOptions(['auto', 'on', 'off'], prefs.colorMode);
140
126
  const idx = Math.max(0, options.findIndex((o) => o.value === prefs.colorMode));
141
127
  state = {
142
128
  mode: 'color',
143
129
  subField: new ListField({
144
- title: trans.theme.chooseColorMode,
130
+ title: trans.theme.colorMode,
145
131
  options,
146
132
  initialIndex: idx,
147
133
  }),
@@ -162,6 +148,8 @@ export const settingsView = {
162
148
  state = {
163
149
  mode: 'about',
164
150
  aboutLines: [
151
+ type.heading(trans.about.title),
152
+ '',
165
153
  row(trans.about.project, APP_INFO.name),
166
154
  row(trans.about.version, `v${APP_INFO.version}`),
167
155
  row(trans.about.description, trans.about.descriptionText),
@@ -173,7 +161,7 @@ export const settingsView = {
173
161
  row(trans.about.license, `MIT ${pickIcon('·', '-')} ${trans.about.author}: m1ngsama`),
174
162
  ],
175
163
  backField: new ListField({
176
- title: trans.about.title,
164
+ title: '',
177
165
  options: [{ value: '__back__', label: trans.common.back }],
178
166
  }),
179
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
+ }