dsh-ustc-campus 0.2.15 → 0.3.3

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/src/school.mjs CHANGED
@@ -22,13 +22,9 @@ import { join } from 'node:path';
22
22
  * supplied URL is ever fetched, and the public summary returns only a derived
23
23
  * course count and availability, never timetable rows, internal IDs or logs.
24
24
  *
25
- * After a successful login the headed context is retained in memory and all
26
- * reads are serialized through it, because the school may issue session
27
- * cookies that disappear when the browser closes. Persistence across a Host
28
- * restart is therefore NOT promised: it depends on Chromium's persistent
29
- * cookie policy for this dedicated profile, not on this module. `logout()`
30
- * clears cookies only in that dedicated profile and never touches a normal
31
- * Chrome/Edge profile.
25
+ * Background work retains a headless context. Mode changes transfer only
26
+ * school cookies in memory, after closing the old context on the same profile.
27
+ * Logout clears only the dedicated profile, never the user's usual browser.
32
28
  */
33
29
 
34
30
  export const SCHOOL_ORIGIN = 'https://jw.ustc.edu.cn';
@@ -68,6 +64,7 @@ const DEFAULT_LOGIN_TIMEOUT_MS = 10 * 60 * 1000;
68
64
  const DEFAULT_AUTO_LOGIN_TIMEOUT_MS = 2 * 60 * 1000;
69
65
  const DEFAULT_POLL_INTERVAL_MS = 750;
70
66
  const DEFAULT_REQUEST_TIMEOUT_MS = 20_000;
67
+ const DEFAULT_LAUNCH_TIMEOUT_MS = 20_000;
71
68
 
72
69
 
73
70
  const MAX_AGENDA_DAYS = 31;
@@ -276,15 +273,6 @@ async function defaultLauncher(profileDir, options) {
276
273
  throw new LaunchError('browser');
277
274
  }
278
275
 
279
- async function setSchoolWindowState(context, page, windowState) {
280
- const cdp = await context.newCDPSession(page);
281
- try {
282
- const { windowId, bounds } = await cdp.send('Browser.getWindowForTarget');
283
- if (bounds.windowState !== windowState) {
284
- await cdp.send('Browser.setWindowBounds', { windowId, bounds: { windowState } });
285
- }
286
- } finally { await cdp.detach(); }
287
- }
288
276
 
289
277
  async function locatorCount(locator) {
290
278
  try {
@@ -502,7 +490,8 @@ export function createSchool({
502
490
  loginTimeoutMs = DEFAULT_LOGIN_TIMEOUT_MS,
503
491
  pollIntervalMs = DEFAULT_POLL_INTERVAL_MS,
504
492
  requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
505
- vault = null
493
+ vault = null,
494
+ invalidateAccountData = () => {}
506
495
  } = {}) {
507
496
  if (typeof dir !== 'string' || !dir) throw new TypeError('dir must be a non-empty string');
508
497
  if (typeof launcher !== 'function') throw new TypeError('launcher must be a function');
@@ -533,6 +522,8 @@ export function createSchool({
533
522
  let draining = null;
534
523
  let loggingOut = null;
535
524
  let autoStarting = false;
525
+ let savingCredentials = null;
526
+ let changingAccount = false;
536
527
  let autoTask = null;
537
528
  let autoWanted = false;
538
529
 
@@ -744,7 +735,20 @@ export function createSchool({
744
735
  return credentialView({ saved });
745
736
  }
746
737
 
747
- async function saveCredentials(data) {
738
+ function ownsCachedData() {
739
+ return !closed && !loggingOut && !changingAccount && Number.isFinite(record?.connectedAt);
740
+ }
741
+
742
+ function saveCredentials(data) {
743
+ if (savingCredentials) return savingCredentials;
744
+ savingCredentials = storeCredentials(data).finally(() => {
745
+ changingAccount = false;
746
+ savingCredentials = null;
747
+ });
748
+ return savingCredentials;
749
+ }
750
+
751
+ async function storeCredentials(data) {
748
752
  if (!credentialsVault || !vaultAvailable()) {
749
753
  return { saved: false, available: false, enabled: false, requiresLogout: false };
750
754
  }
@@ -771,6 +775,8 @@ export function createSchool({
771
775
  }
772
776
  const sameAccount = Boolean(previous && previous.username === credentials.username);
773
777
  if (!sameAccount) {
778
+ changingAccount = true;
779
+ invalidateAccountData();
774
780
  // Invalidate the old owned session without deleting the user's browser
775
781
  // profile: clear cookies in the dedicated profile and require success.
776
782
  autoWanted = false;
@@ -831,7 +837,7 @@ export function createSchool({
831
837
  * or a successful login clears it.
832
838
  */
833
839
  function maybeAutoReconnect() {
834
- if (closed || loggingOut || activeLogin || loginStarting || verifying || autoStarting) return null;
840
+ if (closed || loggingOut || changingAccount || activeLogin || loginStarting || verifying || autoStarting) return null;
835
841
  if (!credentialsVault || !vaultAvailable()) return null;
836
842
  if (!record || record.state !== 'expired' || record.credentialPause === true) return null;
837
843
  if (!Number.isFinite(record.connectedAt) || record.autoFor === record.connectedAt) return null;
@@ -851,26 +857,22 @@ export function createSchool({
851
857
  return autoTask;
852
858
  }
853
859
 
854
- async function launch(mode) {
860
+ async function launch(headless = true) {
855
861
  mkdirSync(profileDir, { recursive: true, mode: 0o700 });
856
862
  let context;
857
863
  try {
858
864
  context = await launcher(profileDir, {
859
- headless: mode === 'cleanup',
860
- acceptDownloads: false,
865
+ headless,
866
+ timeout: DEFAULT_LAUNCH_TIMEOUT_MS,
861
867
  locale: 'zh-CN',
862
868
  timezoneId: 'Asia/Shanghai',
863
869
  viewport: { width: 1100, height: 780 },
864
- args: ['--no-first-run', '--no-default-browser-check', ...(mode === 'minimized' ? ['--start-minimized'] : [])]
870
+ args: ['--no-first-run', '--no-default-browser-check', '--disable-session-crashed-bubble', '--hide-crash-restore-bubble']
865
871
  });
866
872
  } catch (error) {
867
873
  throw new LaunchError(error?.reason === 'network' ? 'network' : 'browser');
868
874
  }
869
875
  if (!context || typeof context.close !== 'function') throw new LaunchError('browser');
870
- if (mode === 'minimized' && typeof context.newCDPSession === 'function') {
871
- try { await setSchoolWindowState(context, await pickPage(context), 'minimized'); }
872
- catch (error) { await closeQuietly(context); throw new LaunchError('browser'); }
873
- }
874
876
  return context;
875
877
  }
876
878
 
@@ -879,6 +881,26 @@ export function createSchool({
879
881
  try { await context.close(); } catch { /* already closed */ }
880
882
  }
881
883
 
884
+ // Chromium may discard session cookies on close. Carry just the school jar
885
+ // across modes; never export browser storage or persist this transfer.
886
+ async function switchMode(context, headless) {
887
+ const cookies = (await context.cookies?.() ?? []).filter(cookie => officialHost(cookie.domain.replace(/^\./, '')));
888
+ await context.close();
889
+ if (closed || loggingOut) return null;
890
+ const next = await launch(headless);
891
+ try {
892
+ if (closed || loggingOut) {
893
+ await closeQuietly(next);
894
+ return null;
895
+ }
896
+ if (cookies.length) await next.addCookies(cookies);
897
+ return next;
898
+ } catch (error) {
899
+ await closeQuietly(next);
900
+ throw error;
901
+ }
902
+ }
903
+
882
904
  async function pickPage(context) {
883
905
  let pages = [];
884
906
  if (typeof context.pages === 'function') {
@@ -1082,23 +1104,28 @@ export function createSchool({
1082
1104
  return { kind: 'connected', studentId, semesterId: currentSemesterId, data };
1083
1105
  }
1084
1106
 
1085
- async function inspect(context, { priorConnected = Boolean(record?.connectedAt) } = {}) {
1086
- const course = await readCourseData(context, priorConnected);
1087
- if (course.kind !== 'connected') return course;
1088
- const { data, studentId, semesterId } = course;
1107
+ function countLessons(lessons) {
1089
1108
  const selectedIds = new Set();
1090
- for (const lesson of data.lessons) {
1091
- if (!lesson || typeof lesson !== 'object') return { kind: 'unavailable', reason: 'incompatible' };
1109
+ for (const lesson of lessons) {
1110
+ if (!lesson || typeof lesson !== 'object') return null;
1092
1111
  const numericId = typeof lesson.id === 'string' && /^\d+$/.test(lesson.id) ? Number(lesson.id) : lesson.id;
1093
1112
  const key = Number.isInteger(numericId) && numericId > 0
1094
1113
  ? `id:${numericId}`
1095
1114
  : typeof lesson.code === 'string' && lesson.code
1096
1115
  ? `code:${lesson.code}`
1097
1116
  : null;
1098
- if (key === null) return { kind: 'unavailable', reason: 'incompatible' };
1117
+ if (key === null) return null;
1099
1118
  selectedIds.add(key);
1100
1119
  }
1101
- const count = selectedIds.size;
1120
+ return selectedIds.size;
1121
+ }
1122
+
1123
+ async function inspect(context, { priorConnected = Boolean(record?.connectedAt) } = {}) {
1124
+ const course = await readCourseData(context, priorConnected);
1125
+ if (course.kind !== 'connected') return course;
1126
+ const { data, studentId, semesterId } = course;
1127
+ const count = countLessons(data.lessons);
1128
+ if (count === null) return { kind: 'unavailable', reason: 'incompatible' };
1102
1129
 
1103
1130
  let scheduleAvailable = false;
1104
1131
  const printUrl = new URL(`${READ_CONTEXT_PATH}/semester/${semesterId}/print-data/${studentId}`, SCHOOL_ORIGIN);
@@ -1123,14 +1150,9 @@ export function createSchool({
1123
1150
  return { kind: 'connected', count, scheduleAvailable };
1124
1151
  }
1125
1152
 
1126
- /**
1127
- * Local-only agenda for a bounded date range. Dates come solely from the
1128
- * platform's `oddWeekIndex2dayOfWeek2Date` week/weekday map (the contract
1129
- * used by the upstream public parser); calendar weeks are never inferred.
1130
- * Unmapped days are reported, not guessed. Rows never leave the Host: the
1131
- * MCP bridge and status file continue to carry aggregates only.
1132
- */
1133
- async function readAgenda(context, { fromDay, throughDay, priorConnected }) {
1153
+ // Dates come solely from the upstream week/weekday mapping. Keep the whole
1154
+ // semester so changing the requested window never requires another fetch.
1155
+ async function readAgenda(context, priorConnected) {
1134
1156
  const course = await readCourseData(context, priorConnected);
1135
1157
  if (course.kind !== 'connected') return course;
1136
1158
  const { data, studentId, semesterId } = course;
@@ -1165,8 +1187,6 @@ export function createSchool({
1165
1187
  : null;
1166
1188
 
1167
1189
  const allDates = new Map();
1168
- const dates = new Map();
1169
- const mappedWeeks = new Set();
1170
1190
  const mappingWeeks = new Set();
1171
1191
  for (const [weekKey, days] of Object.entries(mapping)) {
1172
1192
  const week = Number(weekKey);
@@ -1175,28 +1195,14 @@ export function createSchool({
1175
1195
  if (!days || typeof days !== 'object' || Array.isArray(days)) continue;
1176
1196
  for (let weekday = 1; weekday <= 7; weekday += 1) {
1177
1197
  const raw = days[String(weekday)];
1178
- if (raw === undefined) continue;
1179
- const stamp = dayStart(raw);
1180
- if (stamp === null) continue;
1198
+ if (dayStart(raw) === null) continue;
1181
1199
  allDates.set(`${week}:${weekday}`, raw);
1182
1200
  mappingWeeks.add(week);
1183
- if (stamp < fromDay || stamp > throughDay) continue;
1184
- dates.set(`${week}:${weekday}`, raw);
1185
- mappedWeeks.add(week);
1186
1201
  }
1187
1202
  }
1188
1203
  if (allDates.size === 0) {
1189
1204
  return { kind: 'unavailable', reason: 'date_mapping' };
1190
1205
  }
1191
- if (mappedWeeks.size === 0) {
1192
- return {
1193
- kind: 'ok',
1194
- complete: false,
1195
- events: [],
1196
- warnings: ['no_mapped_dates_in_range'],
1197
- checkedAt: now()
1198
- };
1199
- }
1200
1206
  const weeks = [...mappingWeeks];
1201
1207
  const firstWeek = Math.min(...weeks);
1202
1208
  const lastWeek = Math.max(...weeks);
@@ -1223,23 +1229,21 @@ export function createSchool({
1223
1229
  continue;
1224
1230
  }
1225
1231
 
1232
+ const title = boundedText(activity.courseName);
1233
+ const room = boundedText(activity.room, 120);
1234
+ const building = boundedText(activity.building, 120);
1235
+ const campus = boundedText(activity.campus, 120);
1236
+ const start = clockTime(activity.startDate);
1237
+ const end = clockTime(activity.endDate);
1238
+ const startUnit = periodNumber(activity.startUnit);
1239
+ const endUnit = periodNumber(activity.endUnit);
1226
1240
  for (const week of weeksArray) {
1227
1241
  if (week < firstWeek || week > lastWeek) continue;
1228
- const fullDate = allDates.get(`${week}:${weekday}`);
1229
- if (fullDate === undefined) {
1242
+ const date = allDates.get(`${week}:${weekday}`);
1243
+ if (date === undefined) {
1230
1244
  missing += 1;
1231
1245
  continue;
1232
1246
  }
1233
- const date = dates.get(`${week}:${weekday}`);
1234
- if (date === undefined) continue;
1235
- const title = boundedText(activity.courseName);
1236
- const room = boundedText(activity.room, 120);
1237
- const building = boundedText(activity.building, 120);
1238
- const campus = boundedText(activity.campus, 120);
1239
- const start = clockTime(activity.startDate);
1240
- const end = clockTime(activity.endDate);
1241
- const startUnit = periodNumber(activity.startUnit);
1242
- const endUnit = periodNumber(activity.endUnit);
1243
1247
  const key = [date, start, end, startUnit, endUnit, title, campus, building, room].join('|');
1244
1248
  if (seen.has(key)) continue;
1245
1249
  seen.add(key);
@@ -1278,7 +1282,9 @@ export function createSchool({
1278
1282
  return {
1279
1283
  kind: 'ok',
1280
1284
  complete: missing === 0 && unmappedWeeks === 0 && custom === 0 && invalid === 0,
1281
- events,
1285
+ count: countLessons(data.lessons),
1286
+ entries: events,
1287
+ mappedDates: [...new Set(allDates.values())].sort(),
1282
1288
  warnings,
1283
1289
  checkedAt: now()
1284
1290
  };
@@ -1385,7 +1391,11 @@ export function createSchool({
1385
1391
  return true;
1386
1392
  }
1387
1393
  const body = await pageBodyText(page);
1388
- if ((submitted && CAS_BAD_CREDENTIALS.test(body)) || CAS_MFA.test(body)) {
1394
+ if ((submitted || !exactLoginUrl(current) || /图形验证码|滑块/.test(body)) && CAS_MFA.test(body)) {
1395
+ beginCasMfa(liveRef, current);
1396
+ return false;
1397
+ }
1398
+ if (submitted && CAS_BAD_CREDENTIALS.test(body)) {
1389
1399
  return false;
1390
1400
  }
1391
1401
  if (!submitted && exactLoginUrl(current)) {
@@ -1417,6 +1427,38 @@ export function createSchool({
1417
1427
  return liveRef.casRefreshing;
1418
1428
  }
1419
1429
 
1430
+ async function showChallenge(session, url) {
1431
+ const next = await switchMode(session.context, false);
1432
+ if (!next) return;
1433
+ session.context = next;
1434
+ if (session.stopped) return;
1435
+ session.page = await pickPage(next);
1436
+ await session.page.goto(url.href, { waitUntil: 'domcontentloaded', timeout: requestMs });
1437
+ session.reason = 'mfa';
1438
+ await runLogin(session);
1439
+ }
1440
+
1441
+ function beginCasMfa(liveRef, url) {
1442
+ if (activeLogin || closed || loggingOut || live !== liveRef) return;
1443
+ const session = { context: liveRef.context, reason: 'auto', stopped: false };
1444
+ activeLogin = session;
1445
+ // Do not wait for readers inside their CAS refresh. Drain them before
1446
+ // reopening the persistent profile, and block new readers meanwhile.
1447
+ session.task = serialized(async () => {
1448
+ await waitForReaders();
1449
+ if (closed || loggingOut || session.stopped || live !== liveRef) return false;
1450
+ live = null;
1451
+ return true;
1452
+ }).then(async detached => {
1453
+ if (!detached) return;
1454
+ try { await showChallenge(session, url); }
1455
+ catch { if (!closed && !loggingOut && !session.stopped) saveUnavailable('browser'); }
1456
+ finally { if (!session.retained) await closeQuietly(session.context); }
1457
+ }).finally(() => {
1458
+ if (activeLogin === session) activeLogin = null;
1459
+ });
1460
+ }
1461
+
1420
1462
  async function runLogin(session) {
1421
1463
  const deadline = now() + loginMs;
1422
1464
  let last = null;
@@ -1440,8 +1482,16 @@ export function createSchool({
1440
1482
  if (current.hostname === JW_HOST) {
1441
1483
  const inspected = await serialized(() => inspect(session.context, { priorConnected: Boolean(record?.connectedAt) }));
1442
1484
  if (inspected.kind === 'connected') {
1443
- const saved = saveConnected(inspected);
1444
- if (!closed && saved.state === 'connected') retainSession(session);
1485
+ if (closed || loggingOut || session.stopped) return;
1486
+ try {
1487
+ session.context = await switchMode(session.context, true);
1488
+ } catch {
1489
+ saveUnavailable('browser');
1490
+ return;
1491
+ }
1492
+ if (closed || loggingOut || session.stopped || !session.context) return;
1493
+ retainSession(session);
1494
+ saveConnected(inspected);
1445
1495
  return;
1446
1496
  }
1447
1497
  if (inspected.kind === 'expired' || inspected.kind === 'signed_out') {
@@ -1458,7 +1508,7 @@ export function createSchool({
1458
1508
  }
1459
1509
  await sleep(pollMs);
1460
1510
  }
1461
- if (closed) return;
1511
+ if (closed || loggingOut || session.stopped) return;
1462
1512
  if (last === 'window_closed') {
1463
1513
  saveNotConnected(Boolean(record?.connectedAt), 'window_closed');
1464
1514
  } else if (last === 'network' && networkFailures > 0) {
@@ -1471,7 +1521,7 @@ export function createSchool({
1471
1521
  saveNotConnected(Boolean(record?.connectedAt), 'timeout');
1472
1522
  }
1473
1523
  } catch {
1474
- if (!closed) saveUnavailable('network');
1524
+ if (!closed && !loggingOut && !session.stopped) saveUnavailable('network');
1475
1525
  } finally {
1476
1526
  if (!session.retained) await closeQuietly(session.context);
1477
1527
  if (activeLogin === session) activeLogin = null;
@@ -1479,7 +1529,7 @@ export function createSchool({
1479
1529
  }
1480
1530
 
1481
1531
  async function runStoredLogin(session, credentials) {
1482
- let deadline = now() + autoMs;
1532
+ const deadline = now() + autoMs;
1483
1533
  let submitted = false;
1484
1534
  let last = null;
1485
1535
  let formMisses = 0;
@@ -1504,17 +1554,16 @@ export function createSchool({
1504
1554
  if (session.reason !== 'mfa' && (current.hostname === CAS_HOST || submitted && current.hostname !== JW_HOST)) {
1505
1555
  const text = await pageBodyText(session.page);
1506
1556
  if (CAS_BAD_CREDENTIALS.test(text) && submitted) {
1557
+ if (closed || loggingOut || session.stopped) return;
1507
1558
  saveNotConnected(Boolean(record?.connectedAt), 'credentials');
1508
1559
  return;
1509
1560
  }
1510
- if (CAS_MFA.test(text) && (submitted || !exactLoginUrl(current))) {
1511
- session.reason = 'mfa';
1512
- deadline = now() + loginMs;
1513
- credentials = null;
1561
+ if (CAS_MFA.test(text) && (submitted || !exactLoginUrl(current) || /(?:图形验证码|拖动.{0,6}滑块)/.test(text))) {
1562
+ return await showChallenge(session, current);
1514
1563
  }
1515
1564
  }
1516
1565
  if (current.hostname === JW_HOST) {
1517
- if (session.reason !== 'mfa' && current.pathname === '/login' && !session.followedUnified) {
1566
+ if (current.pathname === '/login' && !session.followedUnified) {
1518
1567
  const followed = await followUnifiedLogin(session.page, current);
1519
1568
  if (closed || loggingOut || record?.credentialPause === true) return;
1520
1569
  if (followed.kind === 'clicked') {
@@ -1544,9 +1593,6 @@ export function createSchool({
1544
1593
  const inspected = await serialized(() => inspect(session.context, { priorConnected: Boolean(record?.connectedAt) }));
1545
1594
  if (closed || loggingOut || record?.credentialPause === true) return;
1546
1595
  if (inspected.kind === 'connected') {
1547
- if (typeof session.context.newCDPSession === 'function') {
1548
- await setSchoolWindowState(session.context, session.page, 'minimized').catch(() => {});
1549
- }
1550
1596
  if (closed || loggingOut || session.stopped) return;
1551
1597
  const saved = saveConnected(inspected);
1552
1598
  if (saved.state === 'connected') retainSession(session);
@@ -1560,7 +1606,7 @@ export function createSchool({
1560
1606
  await sleep(pollMs);
1561
1607
  continue;
1562
1608
  }
1563
- if (session.reason === 'mfa' || !exactLoginUrl(current)) {
1609
+ if (!exactLoginUrl(current)) {
1564
1610
  last = 'timeout';
1565
1611
  await sleep(pollMs);
1566
1612
  continue;
@@ -1610,20 +1656,32 @@ export function createSchool({
1610
1656
 
1611
1657
  async function startLogin(credentials = null) {
1612
1658
  if (closed) return view('unavailable', { reason: 'closed' });
1613
- if (loggingOut) return view('signed_out', { reason: 'logout' });
1659
+ if (loggingOut || changingAccount) return view('signed_out', { reason: 'logout' });
1614
1660
  if (activeLogin) return view('pending', { reason: activeLogin.reason ?? 'auth' });
1615
- if (live) return summary();
1661
+ if (live && credentials) return summary();
1616
1662
  if (verifying) {
1617
1663
  try { await verifying; } catch { /* verification reports its own state */ }
1618
1664
  if (closed) return view('unavailable', { reason: 'closed' });
1619
1665
  if (loggingOut) return view('signed_out', { reason: 'logout' });
1620
- if (live) return viewRecord();
1666
+ if (live && credentials) return viewRecord();
1667
+ }
1668
+ if (!credentials) {
1669
+ invalidateAccountData();
1670
+ await serialized(async () => {
1671
+ if (!closed && !loggingOut) await dropLive();
1672
+ });
1673
+ if (closed || loggingOut) return status();
1674
+ } else {
1675
+ await serialized(() => undefined);
1676
+ if (closed) return view('unavailable', { reason: 'closed' });
1677
+ if (loggingOut || changingAccount) return view('signed_out', { reason: 'logout' });
1678
+ if (live) return summary();
1621
1679
  }
1622
1680
 
1623
1681
  let context;
1624
1682
  let page;
1625
1683
  try {
1626
- context = await launch(credentials ? 'minimized' : 'interactive');
1684
+ context = await launch(Boolean(credentials));
1627
1685
  startingContext = context;
1628
1686
  if (closed || loggingOut) {
1629
1687
  await closeQuietly(context);
@@ -1674,19 +1732,16 @@ export function createSchool({
1674
1732
 
1675
1733
  async function login({manual = false} = {}) {
1676
1734
  if (closed) return view('unavailable', { reason: 'closed' });
1677
- if (loggingOut) return view('signed_out', { reason: 'logout' });
1735
+ if (loggingOut || changingAccount) return view('signed_out', { reason: 'logout' });
1678
1736
  if (activeLogin) {
1679
1737
  const session = activeLogin;
1680
1738
  if (manual && (session.reason === 'mfa' || session.reason === 'auth')) {
1681
- if (typeof session.context.newCDPSession === 'function') {
1682
- await setSchoolWindowState(session.context, session.page, 'normal');
1683
- }
1684
- await session.page.bringToFront?.();
1739
+ await session.page?.bringToFront?.();
1685
1740
  }
1686
1741
  return status();
1687
1742
  }
1688
1743
  if (autoTask) return view('pending', { reason: 'auto' });
1689
- if (live) return summary();
1744
+ if (live && !manual) return summary();
1690
1745
  if (loginStarting) return loginStarting;
1691
1746
  if (manual) {
1692
1747
  loginStarting = startLogin().finally(() => { loginStarting = null; });
@@ -1708,16 +1763,17 @@ export function createSchool({
1708
1763
 
1709
1764
  async function summary() {
1710
1765
  if (closed) return view('unavailable', { reason: 'closed' });
1711
- if (loggingOut) return view('signed_out', { reason: 'logout' });
1766
+ if (loggingOut || changingAccount) return view('signed_out', { reason: 'logout' });
1712
1767
  if (activeLogin) return view('pending', { reason: activeLogin.reason ?? 'auth' });
1713
1768
  if (loginStarting) return view('pending', { reason: 'auth' });
1714
1769
  if (verifying) return verifying;
1715
1770
 
1716
- verifying = (async () => {
1771
+ verifying = serialized(async () => {
1772
+ if (closed || loggingOut || changingAccount) return status();
1717
1773
  if (live && !contextUsable(live.context)) await dropLive();
1718
1774
  if (live) {
1719
- const result = await serialized(() => inspect(live.context, { priorConnected: true }));
1720
- if (closed) return view('unavailable', { reason: 'closed' });
1775
+ const result = await inspect(live.context, { priorConnected: true });
1776
+ if (closed || loggingOut) return status();
1721
1777
  if (result.kind === 'connected') return saveConnected(result);
1722
1778
  if (result.kind === 'expired' || result.kind === 'signed_out') {
1723
1779
  await dropLive();
@@ -1730,10 +1786,10 @@ export function createSchool({
1730
1786
 
1731
1787
  let context;
1732
1788
  try {
1733
- context = await launch('minimized');
1789
+ context = await launch();
1734
1790
  verifyContext = context;
1735
1791
  if (closed) return view('unavailable', { reason: 'closed' });
1736
- const result = await serialized(() => inspect(context, { priorConnected: Boolean(record?.connectedAt) }));
1792
+ const result = await inspect(context, { priorConnected: Boolean(record?.connectedAt) });
1737
1793
  if (closed) return view('unavailable', { reason: 'closed' });
1738
1794
  if (loggingOut) return view('signed_out', { reason: 'logout' });
1739
1795
  if (result.kind === 'connected') {
@@ -1755,7 +1811,7 @@ export function createSchool({
1755
1811
  if (verifyContext === context) verifyContext = null;
1756
1812
  await closeQuietly(context);
1757
1813
  }
1758
- })().finally(() => {
1814
+ }).finally(() => {
1759
1815
  verifying = null;
1760
1816
  flushAutoReconnect();
1761
1817
  });
@@ -1796,25 +1852,38 @@ export function createSchool({
1796
1852
  async function agenda(options = {}) {
1797
1853
  const from = options?.from;
1798
1854
  const through = options?.through;
1799
- if (closed) return agendaView('unavailable', { from, through, reason: 'closed' });
1800
- if (loggingOut) return agendaView('signed_out', { from, through, reason: 'logout' });
1801
- if (activeLogin) return agendaView('pending', { from, through, reason: activeLogin.reason ?? 'auth' });
1802
- if (loginStarting) return agendaView('pending', { from, through, reason: 'auth' });
1803
- if (autoStarting) return agendaView('pending', { from, through, reason: 'auto' });
1804
- if (verifying) {
1805
- try { await verifying; } catch { /* verification reports its own state */ }
1806
- if (closed) return agendaView('unavailable', { from, through, reason: 'closed' });
1807
- }
1808
-
1809
1855
  const fromDay = dayStart(from);
1810
1856
  const throughDay = dayStart(through);
1811
1857
  if (fromDay === null || throughDay === null
1812
1858
  || throughDay < fromDay || throughDay - fromDay >= MAX_AGENDA_DAYS * DAY_MS) {
1813
1859
  return agendaView('unavailable', { from, through, reason: 'invalid_range' });
1814
1860
  }
1861
+ return sliceAgenda(await semesterAgenda(), { from, through });
1862
+ }
1815
1863
 
1864
+ function sliceAgenda(snapshot, { from, through }) {
1865
+ if (snapshot.state !== 'ok') return agendaView(snapshot.state, { from, through, reason: snapshot.reason });
1866
+ const mapped = snapshot.mappedDates.some(date => date >= from && date <= through);
1867
+ return agendaView('ok', {
1868
+ from, through, checkedAt: snapshot.checkedAt,
1869
+ entries: mapped ? snapshot.entries.filter(row => row.date >= from && row.date <= through) : [],
1870
+ complete: mapped && snapshot.complete,
1871
+ warnings: mapped ? snapshot.warnings : ['no_mapped_dates_in_range']
1872
+ });
1873
+ }
1874
+
1875
+ async function semesterAgenda() {
1876
+ const readyState = () => {
1877
+ if (closed) return { state: 'unavailable', reason: 'closed' };
1878
+ if (loggingOut || changingAccount) return { state: 'signed_out', reason: 'logout' };
1879
+ if (activeLogin || loginStarting || autoStarting) return { state: 'pending', reason: activeLogin?.reason ?? 'auth' };
1880
+ };
1881
+ const blocked = readyState();
1882
+ if (blocked) return blocked;
1816
1883
  let reconnect = false;
1817
1884
  const agendaResult = await serialized(async () => {
1885
+ const blocked = readyState();
1886
+ if (blocked) return blocked;
1818
1887
  let context = null;
1819
1888
  let temporary = false;
1820
1889
  try {
@@ -1822,51 +1891,33 @@ export function createSchool({
1822
1891
  if (live) {
1823
1892
  context = live.context;
1824
1893
  } else {
1825
- context = await launch('minimized');
1894
+ context = await launch();
1826
1895
  verifyContext = context;
1827
1896
  temporary = true;
1828
1897
  }
1829
- if (closed) return agendaView('unavailable', { from, through, reason: 'closed' });
1830
-
1831
- const result = await readAgenda(context, {
1832
- fromDay,
1833
- throughDay,
1834
- priorConnected: Boolean(record?.connectedAt)
1835
- });
1836
- if (closed) return agendaView('unavailable', { from, through, reason: 'closed' });
1837
- if (loggingOut) return agendaView('signed_out', { from, through, reason: 'logout' });
1898
+ if (closed || loggingOut) return readyState();
1899
+ const result = await readAgenda(context, Boolean(record?.connectedAt));
1900
+ if (closed || loggingOut || loginStarting) return readyState();
1838
1901
  if (result.kind === 'ok') {
1839
1902
  if (temporary) {
1840
1903
  retainContext(context);
1841
1904
  verifyContext = null;
1842
1905
  temporary = false;
1843
1906
  }
1844
- return agendaView('ok', {
1845
- from,
1846
- through,
1847
- entries: result.events,
1848
- complete: result.complete,
1849
- warnings: result.warnings,
1850
- checkedAt: result.checkedAt
1851
- });
1907
+ if (record?.state !== 'connected' && result.count !== null) {
1908
+ saveConnected({ count: result.count, scheduleAvailable: true });
1909
+ }
1910
+ return { ...result, state: 'ok' };
1852
1911
  }
1853
1912
  if (result.kind === 'expired' || result.kind === 'signed_out') {
1854
1913
  if (live?.context === context) await dropLive();
1855
1914
  const saved = saveNotConnected(result.kind === 'expired');
1856
1915
  reconnect = result.kind === 'expired';
1857
- return agendaView(result.kind, {
1858
- from,
1859
- through,
1860
- reason: saved.reason
1861
- });
1916
+ return { state: result.kind, reason: saved.reason };
1862
1917
  }
1863
- return agendaView('unavailable', { from, through, reason: result.reason ?? 'incompatible' });
1918
+ return { state: 'unavailable', reason: result.reason ?? 'incompatible' };
1864
1919
  } catch (error) {
1865
- return agendaView('unavailable', {
1866
- from,
1867
- through,
1868
- reason: error?.reason === 'network' ? 'network' : 'browser'
1869
- });
1920
+ return { state: 'unavailable', reason: error?.reason === 'network' ? 'network' : 'browser' };
1870
1921
  } finally {
1871
1922
  if (temporary) {
1872
1923
  if (verifyContext === context) verifyContext = null;
@@ -1874,7 +1925,7 @@ export function createSchool({
1874
1925
  }
1875
1926
  }
1876
1927
  });
1877
- if (reconnect && maybeAutoReconnect()) return agendaView('pending', {from,through,reason:'auto'});
1928
+ if (reconnect && maybeAutoReconnect()) return {state:'pending',reason:'auto'};
1878
1929
  return agendaResult;
1879
1930
  }
1880
1931
 
@@ -1918,7 +1969,7 @@ export function createSchool({
1918
1969
  if (!existsSync(profileDir)) return true;
1919
1970
  let context;
1920
1971
  try {
1921
- context = await launch('cleanup');
1972
+ context = await launch();
1922
1973
  verifyContext = context;
1923
1974
  if (closed) return false;
1924
1975
  if (typeof context.clearCookies !== 'function') return false;
@@ -1935,6 +1986,9 @@ export function createSchool({
1935
1986
  function logout() {
1936
1987
  if (loggingOut) return loggingOut;
1937
1988
  loggingOut = (async () => {
1989
+ let cacheError;
1990
+ try { invalidateAccountData(); } catch (error) { cacheError = error; }
1991
+ if (savingCredentials) await savingCredentials.catch(() => {});
1938
1992
  autoWanted = false;
1939
1993
  await stopLogin();
1940
1994
  const credentialsRemoved = await removeStoredCredentials();
@@ -1955,7 +2009,9 @@ export function createSchool({
1955
2009
  return { ...view('unavailable', { reason: 'closed' }), cookiesCleared: false, credentialsRemoved };
1956
2010
  }
1957
2011
  const cookiesCleared = await clearDedicatedCookies();
1958
- return { ...saveLoggedOut(), cookiesCleared, credentialsRemoved };
2012
+ const signedOut = saveLoggedOut();
2013
+ if (cacheError) throw cacheError;
2014
+ return { ...signedOut, cookiesCleared, credentialsRemoved };
1959
2015
  });
1960
2016
  })().finally(() => { loggingOut = null; });
1961
2017
  return loggingOut;
@@ -1977,7 +2033,7 @@ export function createSchool({
1977
2033
 
1978
2034
  function status() {
1979
2035
  if (closed) return view('unavailable', { reason: 'closed' });
1980
- if (loggingOut) return view('signed_out', { reason: 'logout' });
2036
+ if (loggingOut || changingAccount) return view('signed_out', { reason: 'logout' });
1981
2037
  if (activeLogin) return view('pending', { reason: activeLogin.reason ?? 'auth' });
1982
2038
  if (loginStarting) return view('pending', { reason: 'auth' });
1983
2039
  if (autoStarting) return view('pending', { reason: 'auto' });
@@ -1990,21 +2046,25 @@ export function createSchool({
1990
2046
  return viewRecord();
1991
2047
  }
1992
2048
 
1993
- async function withSchoolContext(operation) {
2049
+ async function withSchoolContext(operation, { refreshCas = true } = {}) {
1994
2050
  if (!live && !closed && !loggingOut && record?.state === 'connected') await summary();
1995
2051
  while (draining && !closed && !loggingOut) await draining;
1996
2052
  const liveRef = live;
1997
- if (closed || loggingOut || !liveRef || !contextUsable(liveRef.context)) {
2053
+ const disconnected = () => {
1998
2054
  const error = new Error('请先登录学校账号');
1999
2055
  error.code = 'SCHOOL_NOT_CONNECTED';
2000
- throw error;
2056
+ return error;
2057
+ };
2058
+ if (closed || loggingOut || activeLogin || loginStarting || !liveRef || !contextUsable(liveRef.context)) {
2059
+ throw disconnected();
2001
2060
  }
2002
- await ensureCasSession(liveRef);
2003
2061
  const context = liveRef.context;
2004
2062
  activeReaders += 1;
2005
2063
  try {
2064
+ if (refreshCas) await ensureCasSession(liveRef);
2065
+ if (closed || loggingOut || activeLogin || loginStarting) throw disconnected();
2006
2066
  let result = await operation(context);
2007
- if (result && typeof result === 'object' && result.state === 'not_connected'
2067
+ if (refreshCas && result && typeof result === 'object' && result.state === 'not_connected'
2008
2068
  && vaultAvailable() && record?.credentialPause !== true
2009
2069
  && now() - (liveRef.casRefreshedAt ?? 0) > 60_000) {
2010
2070
  const refreshed = await ensureCasSession(liveRef, { force: true });
@@ -2013,7 +2073,7 @@ export function createSchool({
2013
2073
  return result;
2014
2074
  } catch (error) {
2015
2075
  const code = String(error?.code ?? '').toLowerCase();
2016
- if (code === 'authentication_required' && vaultAvailable() && record?.credentialPause !== true
2076
+ if (refreshCas && code === 'authentication_required' && vaultAvailable() && record?.credentialPause !== true
2017
2077
  && now() - (liveRef.casRefreshedAt ?? 0) > 60_000) {
2018
2078
  const refreshed = await ensureCasSession(liveRef, { force: true });
2019
2079
  if (refreshed) return await operation(context);
@@ -2031,6 +2091,10 @@ export function createSchool({
2031
2091
  logout,
2032
2092
  summary,
2033
2093
  agenda,
2094
+ semesterAgenda,
2095
+ sliceAgenda,
2096
+ ownsCachedData,
2097
+ isLive: () => Boolean(live && contextUsable(live.context)),
2034
2098
  withSchoolContext,
2035
2099
  saveCredentials,
2036
2100
  forgetCredentials,