@vue-skuilder/db 0.2.24 → 0.2.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/{contentSource-jBskhS2Y.d.cts → contentSource-CrRnbjBx.d.cts} +13 -2
  2. package/dist/{contentSource-Z9lQOuu5.d.ts → contentSource-kD35o65m.d.ts} +13 -2
  3. package/dist/core/index.d.cts +3 -3
  4. package/dist/core/index.d.ts +3 -3
  5. package/dist/core/index.js +2474 -481
  6. package/dist/core/index.js.map +1 -1
  7. package/dist/core/index.mjs +2464 -466
  8. package/dist/core/index.mjs.map +1 -1
  9. package/dist/{dataLayerProvider-CvSh3KW-.d.ts → dataLayerProvider-CtzddVdy.d.ts} +1 -1
  10. package/dist/{dataLayerProvider-DbA3d_Pd.d.cts → dataLayerProvider-IecbidDO.d.cts} +1 -1
  11. package/dist/impl/couch/index.d.cts +2 -2
  12. package/dist/impl/couch/index.d.ts +2 -2
  13. package/dist/impl/couch/index.js +2237 -238
  14. package/dist/impl/couch/index.js.map +1 -1
  15. package/dist/impl/couch/index.mjs +2231 -227
  16. package/dist/impl/couch/index.mjs.map +1 -1
  17. package/dist/impl/static/index.d.cts +2 -2
  18. package/dist/impl/static/index.d.ts +2 -2
  19. package/dist/impl/static/index.js +2319 -320
  20. package/dist/impl/static/index.js.map +1 -1
  21. package/dist/impl/static/index.mjs +2309 -305
  22. package/dist/impl/static/index.mjs.map +1 -1
  23. package/dist/index.d.cts +3 -3
  24. package/dist/index.d.ts +3 -3
  25. package/dist/index.js +8155 -7955
  26. package/dist/index.js.map +1 -1
  27. package/dist/index.mjs +8050 -7851
  28. package/dist/index.mjs.map +1 -1
  29. package/package.json +3 -3
  30. package/src/impl/common/BaseUserDB.ts +13 -4
  31. package/src/study/SpacedRepetition.ts +11 -2
  32. package/src/study/services/EloService.ts +20 -1
  33. package/src/study/services/tagRecent.test.ts +101 -0
  34. package/src/study/services/tagRecent.ts +70 -0
@@ -184,96 +184,6 @@ var init_pouchdb_setup = __esm({
184
184
  }
185
185
  });
186
186
 
187
- // src/util/dataDirectory.ts
188
- import * as path from "path";
189
- import * as os from "os";
190
- function getAppDataDirectory() {
191
- if (ENV.LOCAL_STORAGE_PREFIX) {
192
- return path.join(os.homedir(), `.tuilder`, ENV.LOCAL_STORAGE_PREFIX);
193
- } else {
194
- return path.join(os.homedir(), ".tuilder");
195
- }
196
- }
197
- function getDbPath(dbName) {
198
- return path.join(getAppDataDirectory(), dbName);
199
- }
200
- var init_dataDirectory = __esm({
201
- "src/util/dataDirectory.ts"() {
202
- "use strict";
203
- init_logger();
204
- init_factory();
205
- }
206
- });
207
-
208
- // src/impl/common/userDBHelpers.ts
209
- import moment from "moment";
210
- function makeScheduledCardId(reviewTime) {
211
- return DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */] + moment.utc(reviewTime).format(REVIEW_TIME_FORMAT);
212
- }
213
- function filterAllDocsByPrefix(db, prefix, opts) {
214
- const options = {
215
- startkey: prefix,
216
- endkey: prefix + "\uFFF0",
217
- include_docs: true
218
- };
219
- if (opts) {
220
- Object.assign(options, opts);
221
- }
222
- return db.allDocs(options);
223
- }
224
- function getStartAndEndKeys(key) {
225
- return {
226
- startkey: key,
227
- endkey: key + "\uFFF0"
228
- };
229
- }
230
- function getLocalUserDB(username) {
231
- const dbName = `userdb-${username}`;
232
- if (typeof window === "undefined") {
233
- return new pouchdb_setup_default(getDbPath(dbName), {});
234
- } else {
235
- return new pouchdb_setup_default(dbName, {});
236
- }
237
- }
238
- function scheduleCardReviewLocal(userDB, review) {
239
- const now = moment.utc();
240
- logger.info(`Scheduling for review in: ${review.time.diff(now, "h") / 24} days`);
241
- void userDB.put({
242
- _id: makeScheduledCardId(review.time),
243
- cardId: review.card_id,
244
- reviewTime: review.time.toISOString(),
245
- courseId: review.course_id,
246
- scheduledAt: now.toISOString(),
247
- scheduledFor: review.scheduledFor,
248
- schedulingAgentId: review.schedulingAgentId
249
- });
250
- }
251
- async function removeScheduledCardReviewLocal(userDB, reviewDocID) {
252
- const reviewDoc = await userDB.get(reviewDocID);
253
- userDB.remove(reviewDoc).then((res) => {
254
- if (res.ok) {
255
- log2(`Removed Review Doc: ${reviewDocID}`);
256
- }
257
- }).catch((err) => {
258
- log2(`Failed to remove Review Doc: ${reviewDocID},
259
- ${JSON.stringify(err)}`);
260
- });
261
- }
262
- var REVIEW_TIME_FORMAT, log2;
263
- var init_userDBHelpers = __esm({
264
- "src/impl/common/userDBHelpers.ts"() {
265
- "use strict";
266
- init_core();
267
- init_logger();
268
- init_pouchdb_setup();
269
- init_dataDirectory();
270
- REVIEW_TIME_FORMAT = "YYYY-MM-DD--kk:mm:ss-SSS";
271
- log2 = (s) => {
272
- logger.info(s);
273
- };
274
- }
275
- });
276
-
277
187
  // src/util/Loggable.ts
278
188
  var Loggable;
279
189
  var init_Loggable = __esm({
@@ -413,69 +323,6 @@ var init_updateQueue = __esm({
413
323
  }
414
324
  });
415
325
 
416
- // src/impl/couch/user-course-relDB.ts
417
- import moment2 from "moment";
418
- var UsrCrsData;
419
- var init_user_course_relDB = __esm({
420
- "src/impl/couch/user-course-relDB.ts"() {
421
- "use strict";
422
- init_logger();
423
- UsrCrsData = class {
424
- user;
425
- _courseId;
426
- constructor(user, courseId) {
427
- this.user = user;
428
- this._courseId = courseId;
429
- }
430
- async getReviewsForcast(daysCount) {
431
- const time = moment2.utc().add(daysCount, "days");
432
- return this.getReviewstoDate(time);
433
- }
434
- async getPendingReviews() {
435
- const now = moment2.utc();
436
- return this.getReviewstoDate(now);
437
- }
438
- async getScheduledReviewCount() {
439
- return (await this.getPendingReviews()).length;
440
- }
441
- async getCourseSettings() {
442
- const regDoc = await this.user.getCourseRegistrationsDoc();
443
- const crsDoc = regDoc.courses.find((c) => c.courseID === this._courseId);
444
- if (crsDoc && crsDoc.settings) {
445
- return crsDoc.settings;
446
- } else {
447
- logger.warn(`no settings found during lookup on course ${this._courseId}`);
448
- return {};
449
- }
450
- }
451
- updateCourseSettings(updates) {
452
- if ("updateCourseSettings" in this.user) {
453
- void this.user.updateCourseSettings(this._courseId, updates);
454
- }
455
- }
456
- async getStrategyState(strategyKey) {
457
- return this.user.getStrategyState(this._courseId, strategyKey);
458
- }
459
- async putStrategyState(strategyKey, data) {
460
- return this.user.putStrategyState(this._courseId, strategyKey, data);
461
- }
462
- async deleteStrategyState(strategyKey) {
463
- return this.user.deleteStrategyState(this._courseId, strategyKey);
464
- }
465
- async getReviewstoDate(targetDate) {
466
- const allReviews = await this.user.getPendingReviews(this._courseId);
467
- logger.debug(
468
- `Fetching ${this.user.getUsername()}'s scheduled reviews for course ${this._courseId}.`
469
- );
470
- return allReviews.filter((review) => {
471
- const reviewTime = moment2.utc(review.reviewTime);
472
- return targetDate.isAfter(reviewTime);
473
- });
474
- }
475
- };
476
- }
477
- });
478
-
479
326
  // src/impl/couch/clientCache.ts
480
327
  async function GET_CACHED(k, f) {
481
328
  if (CLIENT_CACHE[k]) {
@@ -2861,7 +2708,7 @@ var srs_exports = {};
2861
2708
  __export(srs_exports, {
2862
2709
  default: () => SRSNavigator
2863
2710
  });
2864
- import moment3 from "moment";
2711
+ import moment from "moment";
2865
2712
  var DEFAULT_HEALTHY_BACKLOG, BACKLOG_GROWTH_RATE, SRSNavigator;
2866
2713
  var init_srs = __esm({
2867
2714
  "src/core/navigators/generators/srs.ts"() {
@@ -2916,8 +2763,8 @@ var init_srs = __esm({
2916
2763
  }
2917
2764
  const courseId = this.course.getCourseID();
2918
2765
  const reviews = await this.user.getPendingReviews(courseId);
2919
- const now = moment3.utc();
2920
- let dueReviews = reviews.filter((r) => now.isAfter(moment3.utc(r.reviewTime)));
2766
+ const now = moment.utc();
2767
+ let dueReviews = reviews.filter((r) => now.isAfter(moment.utc(r.reviewTime)));
2921
2768
  if (dueReviews.length > 0) {
2922
2769
  const dueCardIds = [...new Set(dueReviews.map((r) => r.cardId))];
2923
2770
  const tagsByCard = await this.course.getAppliedTagsBatch(dueCardIds);
@@ -2938,13 +2785,13 @@ var init_srs = __esm({
2938
2785
  }
2939
2786
  }
2940
2787
  const backlogMultiplier = this.computeBacklogMultiplier(dueReviews.length);
2941
- const notDue = reviews.filter((r) => !now.isAfter(moment3.utc(r.reviewTime)));
2788
+ const notDue = reviews.filter((r) => !now.isAfter(moment.utc(r.reviewTime)));
2942
2789
  let nextDueIn = null;
2943
2790
  if (notDue.length > 0) {
2944
2791
  const next = notDue.reduce(
2945
- (a, b) => moment3.utc(a.reviewTime).isBefore(moment3.utc(b.reviewTime)) ? a : b
2792
+ (a, b) => moment.utc(a.reviewTime).isBefore(moment.utc(b.reviewTime)) ? a : b
2946
2793
  );
2947
- const until = moment3.duration(moment3.utc(next.reviewTime).diff(now));
2794
+ const until = moment.duration(moment.utc(next.reviewTime).diff(now));
2948
2795
  nextDueIn = until.asHours() < 1 ? `${Math.round(until.asMinutes())}m` : until.asHours() < 24 ? `${Math.round(until.asHours())}h` : `${Math.round(until.asDays())}d`;
2949
2796
  }
2950
2797
  if (dueReviews.length > 0) {
@@ -2954,11 +2801,11 @@ var init_srs = __esm({
2954
2801
  );
2955
2802
  } else if (reviews.length > 0) {
2956
2803
  const sortedByDue = [...reviews].sort(
2957
- (a, b) => moment3.utc(a.reviewTime).diff(moment3.utc(b.reviewTime))
2804
+ (a, b) => moment.utc(a.reviewTime).diff(moment.utc(b.reviewTime))
2958
2805
  );
2959
2806
  const nextDue = sortedByDue[0];
2960
- const nextDueTime = moment3.utc(nextDue.reviewTime);
2961
- const untilDue = moment3.duration(nextDueTime.diff(now));
2807
+ const nextDueTime = moment.utc(nextDue.reviewTime);
2808
+ const untilDue = moment.duration(nextDueTime.diff(now));
2962
2809
  const untilDueStr = untilDue.asHours() < 1 ? `${Math.round(untilDue.asMinutes())}m` : untilDue.asHours() < 24 ? `${Math.round(untilDue.asHours())}h` : `${Math.round(untilDue.asDays())}d`;
2963
2810
  logger.info(
2964
2811
  `[SRS] Course ${courseId}: 0 reviews due now (${reviews.length} scheduled, next in ${untilDueStr})`
@@ -3054,8 +2901,8 @@ var init_srs = __esm({
3054
2901
  * @param backlogMultiplier - Pre-computed backlog multiplier (>= 1.0, unbounded)
3055
2902
  */
3056
2903
  computeUrgencyScore(review, now, backlogMultiplier) {
3057
- const scheduledAt = moment3.utc(review.scheduledAt);
3058
- const due = moment3.utc(review.reviewTime);
2904
+ const scheduledAt = moment.utc(review.scheduledAt);
2905
+ const due = moment.utc(review.reviewTime);
3059
2906
  const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
3060
2907
  const hoursOverdue = now.diff(due, "hours");
3061
2908
  const relativeOverdue = hoursOverdue / intervalHours;
@@ -5710,7 +5557,7 @@ function randIntWeightedTowardZero(n) {
5710
5557
  }
5711
5558
  async function getCourseTagStubs(courseID) {
5712
5559
  logger.debug(`Getting tag stubs for course: ${courseID}`);
5713
- const stubs = await filterAllDocsByPrefix2(
5560
+ const stubs = await filterAllDocsByPrefix(
5714
5561
  getCourseDB2(courseID),
5715
5562
  "TAG" /* TAG */.valueOf() + "-"
5716
5563
  );
@@ -6451,7 +6298,7 @@ ${e.stack}` : JSON.stringify(e);
6451
6298
  });
6452
6299
 
6453
6300
  // src/impl/couch/classroomDB.ts
6454
- import moment4 from "moment";
6301
+ import moment2 from "moment";
6455
6302
  var CLASSROOM_CONFIG, ClassroomDBBase, StudentClassroomDB;
6456
6303
  var init_classroomDB2 = __esm({
6457
6304
  "src/impl/couch/classroomDB.ts"() {
@@ -6469,7 +6316,7 @@ var init_classroomDB2 = __esm({
6469
6316
  _initComplete = false;
6470
6317
  _content_prefix = "content";
6471
6318
  get _content_searchkeys() {
6472
- return getStartAndEndKeys2(this._content_prefix);
6319
+ return getStartAndEndKeys(this._content_prefix);
6473
6320
  }
6474
6321
  async getAssignedContent() {
6475
6322
  logger.info(`Getting assigned content...`);
@@ -6569,9 +6416,9 @@ var init_classroomDB2 = __esm({
6569
6416
  }
6570
6417
  const activeCards = await this._user.getActiveCards();
6571
6418
  const activeCardIds = new Set(activeCards.map((ac) => ac.cardID));
6572
- const now = moment4.utc();
6419
+ const now = moment2.utc();
6573
6420
  const assigned = await this.getAssignedContent();
6574
- const due = assigned.filter((c) => now.isAfter(moment4.utc(c.activeOn, REVIEW_TIME_FORMAT2)));
6421
+ const due = assigned.filter((c) => now.isAfter(moment2.utc(c.activeOn, REVIEW_TIME_FORMAT)));
6575
6422
  logger.info(`[StudentClassroomDB] Due content: ${JSON.stringify(due)}`);
6576
6423
  for (const content of due) {
6577
6424
  if (content.type === "course") {
@@ -6669,7 +6516,7 @@ var init_CourseSyncService = __esm({
6669
6516
  });
6670
6517
 
6671
6518
  // src/impl/couch/auth.ts
6672
- import fetch from "cross-fetch";
6519
+ import fetch2 from "cross-fetch";
6673
6520
  var init_auth = __esm({
6674
6521
  "src/impl/couch/auth.ts"() {
6675
6522
  "use strict";
@@ -6694,8 +6541,8 @@ var init_CouchDBSyncStrategy = __esm({
6694
6541
  });
6695
6542
 
6696
6543
  // src/impl/couch/index.ts
6697
- import fetch2 from "cross-fetch";
6698
- import moment5 from "moment";
6544
+ import fetch3 from "cross-fetch";
6545
+ import moment3 from "moment";
6699
6546
  import process2 from "process";
6700
6547
  function createPouchDBConfig() {
6701
6548
  const hasExplicitCredentials = ENV.COUCHDB_USERNAME && ENV.COUCHDB_PASSWORD;
@@ -6722,7 +6569,7 @@ function getCourseDB2(courseID) {
6722
6569
  createPouchDBConfig()
6723
6570
  );
6724
6571
  }
6725
- function filterAllDocsByPrefix2(db, prefix, opts) {
6572
+ function filterAllDocsByPrefix(db, prefix, opts) {
6726
6573
  const options = {
6727
6574
  startkey: prefix,
6728
6575
  endkey: prefix + "\uFFF0",
@@ -6733,13 +6580,13 @@ function filterAllDocsByPrefix2(db, prefix, opts) {
6733
6580
  }
6734
6581
  return db.allDocs(options);
6735
6582
  }
6736
- function getStartAndEndKeys2(key) {
6583
+ function getStartAndEndKeys(key) {
6737
6584
  return {
6738
6585
  startkey: key,
6739
6586
  endkey: key + "\uFFF0"
6740
6587
  };
6741
6588
  }
6742
- var isBrowser, GUEST_LOCAL_DB, localUserDB, pouchDBincludeCredentialsConfig, REVIEW_TIME_FORMAT2;
6589
+ var isBrowser, GUEST_LOCAL_DB, localUserDB, pouchDBincludeCredentialsConfig, REVIEW_TIME_FORMAT;
6743
6590
  var init_couch = __esm({
6744
6591
  "src/impl/couch/index.ts"() {
6745
6592
  "use strict";
@@ -6766,102 +6613,2431 @@ var init_couch = __esm({
6766
6613
  return pouchdb_setup_default.fetch(url, opts);
6767
6614
  }
6768
6615
  };
6769
- REVIEW_TIME_FORMAT2 = "YYYY-MM-DD--kk:mm:ss-SSS";
6616
+ REVIEW_TIME_FORMAT = "YYYY-MM-DD--kk:mm:ss-SSS";
6770
6617
  }
6771
6618
  });
6772
6619
 
6773
- // src/impl/common/BaseUserDB.ts
6774
- import { Status as Status3 } from "@vue-skuilder/common";
6775
- import moment6 from "moment";
6776
- function withTimeout(p, ms, label) {
6777
- let timer;
6778
- return Promise.race([
6779
- p,
6780
- new Promise((_resolve, reject) => {
6781
- timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
6782
- })
6783
- ]).finally(() => {
6784
- if (timer !== void 0) {
6785
- clearTimeout(timer);
6786
- }
6787
- });
6620
+ // src/study/SpacedRepetition.ts
6621
+ import moment4 from "moment";
6622
+ import { isTaggedPerformance } from "@vue-skuilder/common";
6623
+ function getStreak(records) {
6624
+ let streak = 0;
6625
+ let index = records.length - 1;
6626
+ while (index >= 0 && records[index].isCorrect) {
6627
+ index--;
6628
+ streak++;
6629
+ }
6630
+ return streak;
6788
6631
  }
6789
- async function getOrCreateClassroomRegistrationsDoc(user) {
6790
- let ret;
6791
- try {
6792
- ret = await getLocalUserDB(user).get(userClassroomsDoc);
6793
- } catch (e) {
6794
- const err = e;
6795
- if (err.status === 404) {
6796
- await getLocalUserDB(user).put({
6797
- _id: userClassroomsDoc,
6798
- registrations: []
6799
- });
6800
- ret = await getOrCreateClassroomRegistrationsDoc(user);
6801
- } else {
6802
- const errorDetails = {
6803
- name: err.name,
6804
- status: err.status,
6805
- message: err.message,
6806
- reason: err.reason,
6807
- error: err.error
6808
- };
6809
- logger.error(
6810
- "Database error in getOrCreateClassroomRegistrationsDoc (standalone function):",
6811
- errorDetails
6812
- );
6813
- throw new Error(
6814
- `Database error accessing classroom registrations: ${err.message || err.name || "Unknown error"} (status: ${err.status})`
6815
- );
6816
- }
6817
- }
6818
- return ret;
6632
+ function getLapses(records) {
6633
+ return records.filter((r) => r.isCorrect === false).length;
6819
6634
  }
6820
- async function getOrCreateCourseRegistrationsDoc(user) {
6821
- let ret;
6822
- try {
6823
- ret = await getLocalUserDB(user).get(userCoursesDoc);
6824
- } catch (e) {
6825
- const err = e;
6826
- if (err.status === 404) {
6827
- await getLocalUserDB(user).put({
6828
- _id: userCoursesDoc,
6829
- courses: [],
6830
- studyWeight: {}
6831
- });
6832
- ret = await getOrCreateCourseRegistrationsDoc(user);
6833
- } else {
6834
- throw new Error(
6835
- `Unexpected error ${JSON.stringify(e)} in getOrCreateCourseRegistrationDoc...`
6836
- );
6837
- }
6635
+ var duration;
6636
+ var init_SpacedRepetition = __esm({
6637
+ "src/study/SpacedRepetition.ts"() {
6638
+ "use strict";
6639
+ init_util();
6640
+ init_logger();
6641
+ duration = moment4.duration;
6838
6642
  }
6839
- return ret;
6840
- }
6841
- async function updateUserElo(user, course_id, elo) {
6842
- const regDoc = await getOrCreateCourseRegistrationsDoc(user);
6843
- const course = regDoc.courses.find((c) => c.courseID === course_id);
6844
- course.elo = elo;
6845
- return getLocalUserDB(user).put(regDoc);
6846
- }
6847
- async function registerUserForClassroom(user, classID, registerAs) {
6848
- log3(`Registering user: ${user} in course: ${classID}`);
6849
- return getOrCreateClassroomRegistrationsDoc(user).then((doc) => {
6850
- const regItem = {
6851
- classID,
6852
- registeredAs: registerAs
6853
- };
6854
- if (doc.registrations.filter((reg) => {
6855
- return reg.classID === regItem.classID && reg.registeredAs === regItem.registeredAs;
6856
- }).length === 0) {
6857
- doc.registrations.push(regItem);
6858
- } else {
6859
- log3(`User ${user} is already registered for class ${classID}`);
6860
- }
6861
- return getLocalUserDB(user).put(doc);
6862
- });
6863
- }
6864
- async function dropUserFromClassroom(user, classID) {
6643
+ });
6644
+
6645
+ // src/study/services/SrsService.ts
6646
+ import moment5 from "moment";
6647
+ var init_SrsService = __esm({
6648
+ "src/study/services/SrsService.ts"() {
6649
+ "use strict";
6650
+ init_couch();
6651
+ init_SpacedRepetition();
6652
+ init_logger();
6653
+ }
6654
+ });
6655
+
6656
+ // src/study/services/tagRecent.ts
6657
+ import {
6658
+ pushTagPresentation
6659
+ } from "@vue-skuilder/common";
6660
+ var init_tagRecent = __esm({
6661
+ "src/study/services/tagRecent.ts"() {
6662
+ "use strict";
6663
+ }
6664
+ });
6665
+
6666
+ // src/study/services/EloService.ts
6667
+ import {
6668
+ adjustCourseScores,
6669
+ adjustCourseScoresPerTag,
6670
+ toCourseElo as toCourseElo7
6671
+ } from "@vue-skuilder/common";
6672
+ var init_EloService = __esm({
6673
+ "src/study/services/EloService.ts"() {
6674
+ "use strict";
6675
+ init_logger();
6676
+ init_tagRecent();
6677
+ }
6678
+ });
6679
+
6680
+ // src/study/services/ResponseProcessor.ts
6681
+ import { isTaggedPerformance as isTaggedPerformance2 } from "@vue-skuilder/common";
6682
+ var init_ResponseProcessor = __esm({
6683
+ "src/study/services/ResponseProcessor.ts"() {
6684
+ "use strict";
6685
+ init_core();
6686
+ init_logger();
6687
+ }
6688
+ });
6689
+
6690
+ // src/study/services/CardHydrationService.ts
6691
+ import {
6692
+ displayableDataToViewData,
6693
+ isCourseElo,
6694
+ toCourseElo as toCourseElo8
6695
+ } from "@vue-skuilder/common";
6696
+ var init_CardHydrationService = __esm({
6697
+ "src/study/services/CardHydrationService.ts"() {
6698
+ "use strict";
6699
+ init_logger();
6700
+ }
6701
+ });
6702
+
6703
+ // src/study/ItemQueue.ts
6704
+ var init_ItemQueue = __esm({
6705
+ "src/study/ItemQueue.ts"() {
6706
+ "use strict";
6707
+ }
6708
+ });
6709
+
6710
+ // src/core/types/studySession.ts
6711
+ function makeStudySessionId(courseId, userId, sessionId) {
6712
+ return `${DocTypePrefixes["STUDY_SESSION" /* STUDY_SESSION */]}::${courseId}::${userId}::${sessionId}`;
6713
+ }
6714
+ function newSessionId() {
6715
+ return `session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
6716
+ }
6717
+ var init_studySession = __esm({
6718
+ "src/core/types/studySession.ts"() {
6719
+ "use strict";
6720
+ init_types_legacy();
6721
+ }
6722
+ });
6723
+
6724
+ // src/util/packer/types.ts
6725
+ var init_types3 = __esm({
6726
+ "src/util/packer/types.ts"() {
6727
+ "use strict";
6728
+ }
6729
+ });
6730
+
6731
+ // src/util/packer/CouchDBToStaticPacker.ts
6732
+ var init_CouchDBToStaticPacker = __esm({
6733
+ "src/util/packer/CouchDBToStaticPacker.ts"() {
6734
+ "use strict";
6735
+ init_types_legacy();
6736
+ init_logger();
6737
+ }
6738
+ });
6739
+
6740
+ // src/util/packer/index.ts
6741
+ var init_packer = __esm({
6742
+ "src/util/packer/index.ts"() {
6743
+ "use strict";
6744
+ init_types3();
6745
+ init_CouchDBToStaticPacker();
6746
+ }
6747
+ });
6748
+
6749
+ // src/util/migrator/types.ts
6750
+ var DEFAULT_MIGRATION_OPTIONS;
6751
+ var init_types4 = __esm({
6752
+ "src/util/migrator/types.ts"() {
6753
+ "use strict";
6754
+ DEFAULT_MIGRATION_OPTIONS = {
6755
+ chunkBatchSize: 100,
6756
+ validateRoundTrip: false,
6757
+ cleanupOnFailure: true,
6758
+ timeout: 3e5
6759
+ // 5 minutes
6760
+ };
6761
+ }
6762
+ });
6763
+
6764
+ // src/util/migrator/FileSystemAdapter.ts
6765
+ var FileSystemError;
6766
+ var init_FileSystemAdapter = __esm({
6767
+ "src/util/migrator/FileSystemAdapter.ts"() {
6768
+ "use strict";
6769
+ FileSystemError = class extends Error {
6770
+ constructor(message, operation, filePath, cause) {
6771
+ super(message);
6772
+ this.operation = operation;
6773
+ this.filePath = filePath;
6774
+ this.cause = cause;
6775
+ this.name = "FileSystemError";
6776
+ }
6777
+ };
6778
+ }
6779
+ });
6780
+
6781
+ // src/util/migrator/validation.ts
6782
+ async function validateStaticCourse(staticPath, fs) {
6783
+ const validation = {
6784
+ valid: true,
6785
+ manifestExists: false,
6786
+ chunksExist: false,
6787
+ attachmentsExist: false,
6788
+ errors: [],
6789
+ warnings: []
6790
+ };
6791
+ try {
6792
+ if (fs) {
6793
+ const stats = await fs.stat(staticPath);
6794
+ if (!stats.isDirectory()) {
6795
+ validation.errors.push(`Path is not a directory: ${staticPath}`);
6796
+ validation.valid = false;
6797
+ return validation;
6798
+ }
6799
+ } else if (!nodeFS) {
6800
+ validation.errors.push("File system access not available - validation skipped");
6801
+ validation.valid = false;
6802
+ return validation;
6803
+ } else {
6804
+ const stats = await nodeFS.promises.stat(staticPath);
6805
+ if (!stats.isDirectory()) {
6806
+ validation.errors.push(`Path is not a directory: ${staticPath}`);
6807
+ validation.valid = false;
6808
+ return validation;
6809
+ }
6810
+ }
6811
+ let manifestPath = `${staticPath}/manifest.json`;
6812
+ try {
6813
+ if (fs) {
6814
+ manifestPath = fs.joinPath(staticPath, "manifest.json");
6815
+ if (await fs.exists(manifestPath)) {
6816
+ validation.manifestExists = true;
6817
+ const manifestContent = await fs.readFile(manifestPath);
6818
+ const manifest = JSON.parse(manifestContent);
6819
+ validation.courseId = manifest.courseId;
6820
+ validation.courseName = manifest.courseName;
6821
+ if (!manifest.version || !manifest.courseId || !manifest.chunks || !Array.isArray(manifest.chunks)) {
6822
+ validation.errors.push("Invalid manifest structure");
6823
+ validation.valid = false;
6824
+ }
6825
+ } else {
6826
+ validation.errors.push(`Manifest not found: ${manifestPath}`);
6827
+ validation.valid = false;
6828
+ }
6829
+ } else {
6830
+ manifestPath = `${staticPath}/manifest.json`;
6831
+ await nodeFS.promises.access(manifestPath);
6832
+ validation.manifestExists = true;
6833
+ const manifestContent = await nodeFS.promises.readFile(manifestPath, "utf8");
6834
+ const manifest = JSON.parse(manifestContent);
6835
+ validation.courseId = manifest.courseId;
6836
+ validation.courseName = manifest.courseName;
6837
+ if (!manifest.version || !manifest.courseId || !manifest.chunks || !Array.isArray(manifest.chunks)) {
6838
+ validation.errors.push("Invalid manifest structure");
6839
+ validation.valid = false;
6840
+ }
6841
+ }
6842
+ } catch (error) {
6843
+ const errorMessage = error instanceof FileSystemError ? error.message : `Manifest not found or invalid: ${manifestPath}`;
6844
+ validation.errors.push(errorMessage);
6845
+ validation.valid = false;
6846
+ }
6847
+ let chunksPath = `${staticPath}/chunks`;
6848
+ try {
6849
+ if (fs) {
6850
+ chunksPath = fs.joinPath(staticPath, "chunks");
6851
+ if (await fs.exists(chunksPath)) {
6852
+ const chunksStats = await fs.stat(chunksPath);
6853
+ if (chunksStats.isDirectory()) {
6854
+ validation.chunksExist = true;
6855
+ } else {
6856
+ validation.errors.push(`Chunks path is not a directory: ${chunksPath}`);
6857
+ validation.valid = false;
6858
+ }
6859
+ } else {
6860
+ validation.errors.push(`Chunks directory not found: ${chunksPath}`);
6861
+ validation.valid = false;
6862
+ }
6863
+ } else {
6864
+ chunksPath = `${staticPath}/chunks`;
6865
+ const chunksStats = await nodeFS.promises.stat(chunksPath);
6866
+ if (chunksStats.isDirectory()) {
6867
+ validation.chunksExist = true;
6868
+ } else {
6869
+ validation.errors.push(`Chunks path is not a directory: ${chunksPath}`);
6870
+ validation.valid = false;
6871
+ }
6872
+ }
6873
+ } catch (error) {
6874
+ const errorMessage = error instanceof FileSystemError ? error.message : `Chunks directory not found: ${chunksPath}`;
6875
+ validation.errors.push(errorMessage);
6876
+ validation.valid = false;
6877
+ }
6878
+ let attachmentsPath;
6879
+ try {
6880
+ if (fs) {
6881
+ attachmentsPath = fs.joinPath(staticPath, "attachments");
6882
+ if (await fs.exists(attachmentsPath)) {
6883
+ const attachmentsStats = await fs.stat(attachmentsPath);
6884
+ if (attachmentsStats.isDirectory()) {
6885
+ validation.attachmentsExist = true;
6886
+ }
6887
+ } else {
6888
+ validation.warnings.push(
6889
+ `Attachments directory not found: ${attachmentsPath} (this is OK if course has no attachments)`
6890
+ );
6891
+ }
6892
+ } else {
6893
+ attachmentsPath = `${staticPath}/attachments`;
6894
+ const attachmentsStats = await nodeFS.promises.stat(attachmentsPath);
6895
+ if (attachmentsStats.isDirectory()) {
6896
+ validation.attachmentsExist = true;
6897
+ }
6898
+ }
6899
+ } catch (error) {
6900
+ attachmentsPath = attachmentsPath || `${staticPath}/attachments`;
6901
+ const warningMessage = error instanceof FileSystemError ? error.message : `Attachments directory not found: ${attachmentsPath} (this is OK if course has no attachments)`;
6902
+ validation.warnings.push(warningMessage);
6903
+ }
6904
+ } catch (error) {
6905
+ validation.errors.push(
6906
+ `Failed to validate static course: ${error instanceof Error ? error.message : String(error)}`
6907
+ );
6908
+ validation.valid = false;
6909
+ }
6910
+ return validation;
6911
+ }
6912
+ async function validateMigration(targetDB, expectedCounts, manifest) {
6913
+ const validation = {
6914
+ valid: true,
6915
+ documentCountMatch: false,
6916
+ attachmentIntegrity: false,
6917
+ viewFunctionality: false,
6918
+ issues: []
6919
+ };
6920
+ try {
6921
+ logger.info("Starting migration validation...");
6922
+ const actualCounts = await getActualDocumentCounts(targetDB);
6923
+ validation.documentCountMatch = compareDocumentCounts(
6924
+ expectedCounts,
6925
+ actualCounts,
6926
+ validation.issues
6927
+ );
6928
+ await validateCourseConfig(targetDB, manifest, validation.issues);
6929
+ validation.viewFunctionality = await validateViews(targetDB, manifest, validation.issues);
6930
+ validation.attachmentIntegrity = await validateAttachmentIntegrity(targetDB, validation.issues);
6931
+ validation.valid = validation.documentCountMatch && validation.viewFunctionality && validation.attachmentIntegrity;
6932
+ logger.info(`Migration validation completed. Valid: ${validation.valid}`);
6933
+ if (validation.issues.length > 0) {
6934
+ logger.info(`Validation issues: ${validation.issues.length}`);
6935
+ validation.issues.forEach((issue) => {
6936
+ if (issue.type === "error") {
6937
+ logger.error(`${issue.category}: ${issue.message}`);
6938
+ } else {
6939
+ logger.warn(`${issue.category}: ${issue.message}`);
6940
+ }
6941
+ });
6942
+ }
6943
+ } catch (error) {
6944
+ validation.valid = false;
6945
+ validation.issues.push({
6946
+ type: "error",
6947
+ category: "metadata",
6948
+ message: `Validation failed: ${error instanceof Error ? error.message : String(error)}`
6949
+ });
6950
+ }
6951
+ return validation;
6952
+ }
6953
+ async function getActualDocumentCounts(db) {
6954
+ const counts = {};
6955
+ try {
6956
+ const allDocs = await db.allDocs({ include_docs: true });
6957
+ for (const row of allDocs.rows) {
6958
+ if (row.id.startsWith("_design/")) {
6959
+ counts["_design"] = (counts["_design"] || 0) + 1;
6960
+ continue;
6961
+ }
6962
+ const doc = row.doc;
6963
+ if (doc && doc.docType) {
6964
+ counts[doc.docType] = (counts[doc.docType] || 0) + 1;
6965
+ } else {
6966
+ counts["unknown"] = (counts["unknown"] || 0) + 1;
6967
+ }
6968
+ }
6969
+ } catch (error) {
6970
+ logger.error("Failed to get actual document counts:", error);
6971
+ }
6972
+ return counts;
6973
+ }
6974
+ function compareDocumentCounts(expected, actual, issues) {
6975
+ let countsMatch = true;
6976
+ for (const [docType, expectedCount] of Object.entries(expected)) {
6977
+ const actualCount = actual[docType] || 0;
6978
+ if (actualCount !== expectedCount) {
6979
+ countsMatch = false;
6980
+ issues.push({
6981
+ type: "error",
6982
+ category: "documents",
6983
+ message: `Document count mismatch for ${docType}: expected ${expectedCount}, got ${actualCount}`
6984
+ });
6985
+ }
6986
+ }
6987
+ for (const [docType, actualCount] of Object.entries(actual)) {
6988
+ if (!expected[docType] && docType !== "_design") {
6989
+ issues.push({
6990
+ type: "warning",
6991
+ category: "documents",
6992
+ message: `Unexpected document type found: ${docType} (${actualCount} documents)`
6993
+ });
6994
+ }
6995
+ }
6996
+ return countsMatch;
6997
+ }
6998
+ async function validateCourseConfig(db, manifest, issues) {
6999
+ try {
7000
+ const courseConfig = await db.get("CourseConfig");
7001
+ if (!courseConfig) {
7002
+ issues.push({
7003
+ type: "error",
7004
+ category: "course_config",
7005
+ message: "CourseConfig document not found after migration"
7006
+ });
7007
+ return;
7008
+ }
7009
+ if (!courseConfig.courseID) {
7010
+ issues.push({
7011
+ type: "warning",
7012
+ category: "course_config",
7013
+ message: "CourseConfig document missing courseID field"
7014
+ });
7015
+ }
7016
+ if (courseConfig.courseID !== manifest.courseId) {
7017
+ issues.push({
7018
+ type: "warning",
7019
+ category: "course_config",
7020
+ message: `CourseConfig courseID mismatch: expected ${manifest.courseId}, got ${courseConfig.courseID}`
7021
+ });
7022
+ }
7023
+ logger.debug("CourseConfig document validation passed");
7024
+ } catch (error) {
7025
+ if (error.status === 404) {
7026
+ issues.push({
7027
+ type: "error",
7028
+ category: "course_config",
7029
+ message: "CourseConfig document not found in database"
7030
+ });
7031
+ } else {
7032
+ issues.push({
7033
+ type: "error",
7034
+ category: "course_config",
7035
+ message: `Failed to validate CourseConfig document: ${error instanceof Error ? error.message : String(error)}`
7036
+ });
7037
+ }
7038
+ }
7039
+ }
7040
+ async function validateViews(db, manifest, issues) {
7041
+ let viewsValid = true;
7042
+ try {
7043
+ for (const designDoc of manifest.designDocs) {
7044
+ try {
7045
+ const doc = await db.get(designDoc._id);
7046
+ if (!doc) {
7047
+ viewsValid = false;
7048
+ issues.push({
7049
+ type: "error",
7050
+ category: "views",
7051
+ message: `Design document not found: ${designDoc._id}`
7052
+ });
7053
+ continue;
7054
+ }
7055
+ for (const viewName of Object.keys(designDoc.views)) {
7056
+ try {
7057
+ const viewPath = `${designDoc._id}/${viewName}`;
7058
+ await db.query(viewPath, { limit: 1 });
7059
+ } catch (viewError) {
7060
+ viewsValid = false;
7061
+ issues.push({
7062
+ type: "error",
7063
+ category: "views",
7064
+ message: `View not accessible: ${designDoc._id}/${viewName} - ${viewError}`
7065
+ });
7066
+ }
7067
+ }
7068
+ } catch (error) {
7069
+ viewsValid = false;
7070
+ issues.push({
7071
+ type: "error",
7072
+ category: "views",
7073
+ message: `Failed to validate design document ${designDoc._id}: ${error}`
7074
+ });
7075
+ }
7076
+ }
7077
+ } catch (error) {
7078
+ viewsValid = false;
7079
+ issues.push({
7080
+ type: "error",
7081
+ category: "views",
7082
+ message: `View validation failed: ${error instanceof Error ? error.message : String(error)}`
7083
+ });
7084
+ }
7085
+ return viewsValid;
7086
+ }
7087
+ async function validateAttachmentIntegrity(db, issues) {
7088
+ let attachmentsValid = true;
7089
+ try {
7090
+ const allDocs = await db.allDocs({
7091
+ include_docs: true,
7092
+ limit: 10
7093
+ // Sample first 10 documents for performance
7094
+ });
7095
+ let attachmentCount = 0;
7096
+ let validAttachments = 0;
7097
+ for (const row of allDocs.rows) {
7098
+ const doc = row.doc;
7099
+ if (doc && doc._attachments) {
7100
+ for (const [attachmentName, _attachmentMeta] of Object.entries(doc._attachments)) {
7101
+ attachmentCount++;
7102
+ try {
7103
+ const attachment = await db.getAttachment(doc._id, attachmentName);
7104
+ if (attachment) {
7105
+ validAttachments++;
7106
+ }
7107
+ } catch (attachmentError) {
7108
+ attachmentsValid = false;
7109
+ issues.push({
7110
+ type: "error",
7111
+ category: "attachments",
7112
+ message: `Attachment not accessible: ${doc._id}/${attachmentName} - ${attachmentError}`
7113
+ });
7114
+ }
7115
+ }
7116
+ }
7117
+ }
7118
+ if (attachmentCount === 0) {
7119
+ issues.push({
7120
+ type: "warning",
7121
+ category: "attachments",
7122
+ message: "No attachments found in sampled documents"
7123
+ });
7124
+ } else {
7125
+ logger.info(`Validated ${validAttachments}/${attachmentCount} sampled attachments`);
7126
+ }
7127
+ } catch (error) {
7128
+ attachmentsValid = false;
7129
+ issues.push({
7130
+ type: "error",
7131
+ category: "attachments",
7132
+ message: `Attachment validation failed: ${error instanceof Error ? error.message : String(error)}`
7133
+ });
7134
+ }
7135
+ return attachmentsValid;
7136
+ }
7137
+ var nodeFS;
7138
+ var init_validation = __esm({
7139
+ "src/util/migrator/validation.ts"() {
7140
+ "use strict";
7141
+ init_logger();
7142
+ init_FileSystemAdapter();
7143
+ nodeFS = null;
7144
+ try {
7145
+ if (typeof window === "undefined" && typeof process !== "undefined" && process.versions?.node) {
7146
+ nodeFS = eval("require")("fs");
7147
+ nodeFS.promises = nodeFS.promises || eval("require")("fs").promises;
7148
+ }
7149
+ } catch {
7150
+ }
7151
+ }
7152
+ });
7153
+
7154
+ // src/util/migrator/StaticToCouchDBMigrator.ts
7155
+ var nodeFS2, nodePath, StaticToCouchDBMigrator;
7156
+ var init_StaticToCouchDBMigrator = __esm({
7157
+ "src/util/migrator/StaticToCouchDBMigrator.ts"() {
7158
+ "use strict";
7159
+ init_logger();
7160
+ init_types4();
7161
+ init_validation();
7162
+ init_FileSystemAdapter();
7163
+ nodeFS2 = null;
7164
+ nodePath = null;
7165
+ try {
7166
+ if (typeof window === "undefined" && typeof process !== "undefined" && process.versions?.node) {
7167
+ nodeFS2 = eval("require")("fs");
7168
+ nodePath = eval("require")("path");
7169
+ nodeFS2.promises = nodeFS2.promises || eval("require")("fs").promises;
7170
+ }
7171
+ } catch {
7172
+ }
7173
+ StaticToCouchDBMigrator = class {
7174
+ options;
7175
+ progressCallback;
7176
+ fs;
7177
+ constructor(options = {}, fileSystemAdapter) {
7178
+ this.options = {
7179
+ ...DEFAULT_MIGRATION_OPTIONS,
7180
+ ...options
7181
+ };
7182
+ this.fs = fileSystemAdapter;
7183
+ }
7184
+ /**
7185
+ * Set a progress callback to receive updates during migration
7186
+ */
7187
+ setProgressCallback(callback) {
7188
+ this.progressCallback = callback;
7189
+ }
7190
+ /**
7191
+ * Migrate a static course to CouchDB
7192
+ */
7193
+ async migrateCourse(staticPath, targetDB) {
7194
+ const startTime = Date.now();
7195
+ const result = {
7196
+ success: false,
7197
+ documentsRestored: 0,
7198
+ attachmentsRestored: 0,
7199
+ designDocsRestored: 0,
7200
+ courseConfigRestored: 0,
7201
+ errors: [],
7202
+ warnings: [],
7203
+ migrationTime: 0
7204
+ };
7205
+ try {
7206
+ logger.info(`Starting migration from ${staticPath} to CouchDB`);
7207
+ this.reportProgress("manifest", 0, 1, "Validating static course...");
7208
+ const validation = await validateStaticCourse(staticPath, this.fs);
7209
+ if (!validation.valid) {
7210
+ result.errors.push(...validation.errors);
7211
+ throw new Error(`Static course validation failed: ${validation.errors.join(", ")}`);
7212
+ }
7213
+ result.warnings.push(...validation.warnings);
7214
+ this.reportProgress("manifest", 1, 1, "Loading course manifest...");
7215
+ const manifest = await this.loadManifest(staticPath);
7216
+ logger.info(`Loaded manifest for course: ${manifest.courseId} (${manifest.courseName})`);
7217
+ this.reportProgress(
7218
+ "design_docs",
7219
+ 0,
7220
+ manifest.designDocs.length,
7221
+ "Restoring design documents..."
7222
+ );
7223
+ const designDocResults = await this.restoreDesignDocuments(manifest.designDocs, targetDB);
7224
+ result.designDocsRestored = designDocResults.restored;
7225
+ result.errors.push(...designDocResults.errors);
7226
+ result.warnings.push(...designDocResults.warnings);
7227
+ this.reportProgress("course_config", 0, 1, "Restoring CourseConfig document...");
7228
+ const courseConfigResults = await this.restoreCourseConfig(manifest, targetDB);
7229
+ result.courseConfigRestored = courseConfigResults.restored;
7230
+ result.errors.push(...courseConfigResults.errors);
7231
+ result.warnings.push(...courseConfigResults.warnings);
7232
+ this.reportProgress("course_config", 1, 1, "CourseConfig document restored");
7233
+ const expectedCounts = this.calculateExpectedCounts(manifest);
7234
+ this.reportProgress(
7235
+ "documents",
7236
+ 0,
7237
+ manifest.documentCount,
7238
+ "Aggregating documents from chunks..."
7239
+ );
7240
+ const documents = await this.aggregateDocuments(staticPath, manifest);
7241
+ const filteredDocuments = documents.filter((doc) => doc._id !== "CourseConfig");
7242
+ if (documents.length !== filteredDocuments.length) {
7243
+ result.warnings.push(
7244
+ `Filtered out ${documents.length - filteredDocuments.length} CourseConfig document(s) from chunks to prevent conflicts`
7245
+ );
7246
+ }
7247
+ this.reportProgress(
7248
+ "documents",
7249
+ filteredDocuments.length,
7250
+ manifest.documentCount,
7251
+ "Uploading documents to CouchDB..."
7252
+ );
7253
+ const docResults = await this.uploadDocuments(filteredDocuments, targetDB);
7254
+ result.documentsRestored = docResults.restored;
7255
+ result.errors.push(...docResults.errors);
7256
+ result.warnings.push(...docResults.warnings);
7257
+ const docsWithAttachments = documents.filter(
7258
+ (doc) => doc._attachments && Object.keys(doc._attachments).length > 0
7259
+ );
7260
+ this.reportProgress("attachments", 0, docsWithAttachments.length, "Uploading attachments...");
7261
+ const attachmentResults = await this.uploadAttachments(
7262
+ staticPath,
7263
+ docsWithAttachments,
7264
+ targetDB
7265
+ );
7266
+ result.attachmentsRestored = attachmentResults.restored;
7267
+ result.errors.push(...attachmentResults.errors);
7268
+ result.warnings.push(...attachmentResults.warnings);
7269
+ if (this.options.validateRoundTrip) {
7270
+ this.reportProgress("validation", 0, 1, "Validating migration...");
7271
+ const validationResult = await validateMigration(targetDB, expectedCounts, manifest);
7272
+ if (!validationResult.valid) {
7273
+ result.warnings.push("Migration validation found issues");
7274
+ validationResult.issues.forEach((issue) => {
7275
+ if (issue.type === "error") {
7276
+ result.errors.push(`Validation: ${issue.message}`);
7277
+ } else {
7278
+ result.warnings.push(`Validation: ${issue.message}`);
7279
+ }
7280
+ });
7281
+ }
7282
+ this.reportProgress("validation", 1, 1, "Migration validation completed");
7283
+ }
7284
+ result.success = result.errors.length === 0;
7285
+ result.migrationTime = Date.now() - startTime;
7286
+ logger.info(`Migration completed in ${result.migrationTime}ms`);
7287
+ logger.info(`Documents restored: ${result.documentsRestored}`);
7288
+ logger.info(`Attachments restored: ${result.attachmentsRestored}`);
7289
+ logger.info(`Design docs restored: ${result.designDocsRestored}`);
7290
+ logger.info(`CourseConfig restored: ${result.courseConfigRestored}`);
7291
+ if (result.errors.length > 0) {
7292
+ logger.error(`Migration completed with ${result.errors.length} errors`);
7293
+ }
7294
+ if (result.warnings.length > 0) {
7295
+ logger.warn(`Migration completed with ${result.warnings.length} warnings`);
7296
+ }
7297
+ } catch (error) {
7298
+ result.success = false;
7299
+ result.migrationTime = Date.now() - startTime;
7300
+ const errorMessage = error instanceof Error ? error.message : String(error);
7301
+ result.errors.push(`Migration failed: ${errorMessage}`);
7302
+ logger.error("Migration failed:", error);
7303
+ if (this.options.cleanupOnFailure) {
7304
+ try {
7305
+ await this.cleanupFailedMigration(targetDB);
7306
+ } catch (cleanupError) {
7307
+ logger.error("Failed to cleanup after migration failure:", cleanupError);
7308
+ result.warnings.push("Failed to cleanup after migration failure");
7309
+ }
7310
+ }
7311
+ }
7312
+ return result;
7313
+ }
7314
+ /**
7315
+ * Load and parse the manifest file
7316
+ */
7317
+ async loadManifest(staticPath) {
7318
+ try {
7319
+ let manifestContent;
7320
+ let manifestPath;
7321
+ if (this.fs) {
7322
+ manifestPath = this.fs.joinPath(staticPath, "manifest.json");
7323
+ manifestContent = await this.fs.readFile(manifestPath);
7324
+ } else {
7325
+ manifestPath = nodeFS2 && nodePath ? nodePath.join(staticPath, "manifest.json") : `${staticPath}/manifest.json`;
7326
+ if (nodeFS2 && this.isLocalPath(staticPath)) {
7327
+ manifestContent = await nodeFS2.promises.readFile(manifestPath, "utf8");
7328
+ } else {
7329
+ const response = await fetch(manifestPath);
7330
+ if (!response.ok) {
7331
+ throw new Error(`Failed to fetch manifest: ${response.status} ${response.statusText}`);
7332
+ }
7333
+ manifestContent = await response.text();
7334
+ }
7335
+ }
7336
+ const manifest = JSON.parse(manifestContent);
7337
+ if (!manifest.version || !manifest.courseId || !manifest.chunks) {
7338
+ throw new Error("Invalid manifest structure");
7339
+ }
7340
+ return manifest;
7341
+ } catch (error) {
7342
+ const errorMessage = error instanceof FileSystemError ? error.message : `Failed to load manifest: ${error instanceof Error ? error.message : String(error)}`;
7343
+ throw new Error(errorMessage);
7344
+ }
7345
+ }
7346
+ /**
7347
+ * Restore design documents to CouchDB
7348
+ */
7349
+ async restoreDesignDocuments(designDocs, db) {
7350
+ const result = { restored: 0, errors: [], warnings: [] };
7351
+ for (let i = 0; i < designDocs.length; i++) {
7352
+ const designDoc = designDocs[i];
7353
+ this.reportProgress("design_docs", i, designDocs.length, `Restoring ${designDoc._id}...`);
7354
+ try {
7355
+ let existingDoc;
7356
+ try {
7357
+ existingDoc = await db.get(designDoc._id);
7358
+ } catch {
7359
+ }
7360
+ const docToInsert = {
7361
+ _id: designDoc._id,
7362
+ views: designDoc.views
7363
+ };
7364
+ if (existingDoc) {
7365
+ docToInsert._rev = existingDoc._rev;
7366
+ logger.debug(`Updating existing design document: ${designDoc._id}`);
7367
+ } else {
7368
+ logger.debug(`Creating new design document: ${designDoc._id}`);
7369
+ }
7370
+ await db.put(docToInsert);
7371
+ result.restored++;
7372
+ } catch (error) {
7373
+ const errorMessage = `Failed to restore design document ${designDoc._id}: ${error instanceof Error ? error.message : String(error)}`;
7374
+ result.errors.push(errorMessage);
7375
+ logger.error(errorMessage);
7376
+ }
7377
+ }
7378
+ this.reportProgress(
7379
+ "design_docs",
7380
+ designDocs.length,
7381
+ designDocs.length,
7382
+ `Restored ${result.restored} design documents`
7383
+ );
7384
+ return result;
7385
+ }
7386
+ /**
7387
+ * Aggregate documents from all chunks
7388
+ */
7389
+ async aggregateDocuments(staticPath, manifest) {
7390
+ const allDocuments = [];
7391
+ const documentMap = /* @__PURE__ */ new Map();
7392
+ for (let i = 0; i < manifest.chunks.length; i++) {
7393
+ const chunk = manifest.chunks[i];
7394
+ this.reportProgress(
7395
+ "documents",
7396
+ allDocuments.length,
7397
+ manifest.documentCount,
7398
+ `Loading chunk ${chunk.id}...`
7399
+ );
7400
+ try {
7401
+ const documents = await this.loadChunk(staticPath, chunk);
7402
+ for (const doc of documents) {
7403
+ if (!doc._id) {
7404
+ logger.warn(`Document without _id found in chunk ${chunk.id}, skipping`);
7405
+ continue;
7406
+ }
7407
+ if (documentMap.has(doc._id)) {
7408
+ logger.warn(`Duplicate document ID found: ${doc._id}, using latest version`);
7409
+ }
7410
+ documentMap.set(doc._id, doc);
7411
+ }
7412
+ } catch (error) {
7413
+ throw new Error(
7414
+ `Failed to load chunk ${chunk.id}: ${error instanceof Error ? error.message : String(error)}`
7415
+ );
7416
+ }
7417
+ }
7418
+ allDocuments.push(...documentMap.values());
7419
+ logger.info(
7420
+ `Aggregated ${allDocuments.length} unique documents from ${manifest.chunks.length} chunks`
7421
+ );
7422
+ return allDocuments;
7423
+ }
7424
+ /**
7425
+ * Load documents from a single chunk file
7426
+ */
7427
+ async loadChunk(staticPath, chunk) {
7428
+ try {
7429
+ let chunkContent;
7430
+ let chunkPath;
7431
+ if (this.fs) {
7432
+ chunkPath = this.fs.joinPath(staticPath, chunk.path);
7433
+ chunkContent = await this.fs.readFile(chunkPath);
7434
+ } else {
7435
+ chunkPath = nodeFS2 && nodePath ? nodePath.join(staticPath, chunk.path) : `${staticPath}/${chunk.path}`;
7436
+ if (nodeFS2 && this.isLocalPath(staticPath)) {
7437
+ chunkContent = await nodeFS2.promises.readFile(chunkPath, "utf8");
7438
+ } else {
7439
+ const response = await fetch(chunkPath);
7440
+ if (!response.ok) {
7441
+ throw new Error(`Failed to fetch chunk: ${response.status} ${response.statusText}`);
7442
+ }
7443
+ chunkContent = await response.text();
7444
+ }
7445
+ }
7446
+ const documents = JSON.parse(chunkContent);
7447
+ if (!Array.isArray(documents)) {
7448
+ throw new Error("Chunk file does not contain an array of documents");
7449
+ }
7450
+ return documents;
7451
+ } catch (error) {
7452
+ const errorMessage = error instanceof FileSystemError ? error.message : `Failed to load chunk: ${error instanceof Error ? error.message : String(error)}`;
7453
+ throw new Error(errorMessage);
7454
+ }
7455
+ }
7456
+ /**
7457
+ * Upload documents to CouchDB in batches
7458
+ */
7459
+ async uploadDocuments(documents, db) {
7460
+ const result = { restored: 0, errors: [], warnings: [] };
7461
+ const batchSize = this.options.chunkBatchSize;
7462
+ for (let i = 0; i < documents.length; i += batchSize) {
7463
+ const batch = documents.slice(i, i + batchSize);
7464
+ this.reportProgress(
7465
+ "documents",
7466
+ i,
7467
+ documents.length,
7468
+ `Uploading batch ${Math.floor(i / batchSize) + 1}...`
7469
+ );
7470
+ try {
7471
+ const docsToInsert = batch.map((doc) => {
7472
+ const cleanDoc = { ...doc };
7473
+ delete cleanDoc._rev;
7474
+ delete cleanDoc._attachments;
7475
+ return cleanDoc;
7476
+ });
7477
+ const bulkResult = await db.bulkDocs(docsToInsert);
7478
+ for (let j = 0; j < bulkResult.length; j++) {
7479
+ const docResult = bulkResult[j];
7480
+ const originalDoc = batch[j];
7481
+ if ("error" in docResult) {
7482
+ const errorMessage = `Failed to upload document ${originalDoc._id}: ${docResult.error} - ${docResult.reason}`;
7483
+ result.errors.push(errorMessage);
7484
+ logger.error(errorMessage);
7485
+ } else {
7486
+ result.restored++;
7487
+ }
7488
+ }
7489
+ } catch (error) {
7490
+ let errorMessage;
7491
+ if (error instanceof Error) {
7492
+ errorMessage = `Failed to upload document batch starting at index ${i}: ${error.message}`;
7493
+ } else if (error && typeof error === "object" && "message" in error) {
7494
+ errorMessage = `Failed to upload document batch starting at index ${i}: ${error.message}`;
7495
+ } else {
7496
+ errorMessage = `Failed to upload document batch starting at index ${i}: ${JSON.stringify(error)}`;
7497
+ }
7498
+ result.errors.push(errorMessage);
7499
+ logger.error(errorMessage);
7500
+ }
7501
+ }
7502
+ this.reportProgress(
7503
+ "documents",
7504
+ documents.length,
7505
+ documents.length,
7506
+ `Uploaded ${result.restored} documents`
7507
+ );
7508
+ return result;
7509
+ }
7510
+ /**
7511
+ * Upload attachments from filesystem to CouchDB
7512
+ */
7513
+ async uploadAttachments(staticPath, documents, db) {
7514
+ const result = { restored: 0, errors: [], warnings: [] };
7515
+ let processedDocs = 0;
7516
+ for (const doc of documents) {
7517
+ this.reportProgress(
7518
+ "attachments",
7519
+ processedDocs,
7520
+ documents.length,
7521
+ `Processing attachments for ${doc._id}...`
7522
+ );
7523
+ processedDocs++;
7524
+ if (!doc._attachments) {
7525
+ continue;
7526
+ }
7527
+ for (const [attachmentName, attachmentMeta] of Object.entries(doc._attachments)) {
7528
+ try {
7529
+ const uploadResult = await this.uploadSingleAttachment(
7530
+ staticPath,
7531
+ doc._id,
7532
+ attachmentName,
7533
+ attachmentMeta,
7534
+ db
7535
+ );
7536
+ if (uploadResult.success) {
7537
+ result.restored++;
7538
+ } else {
7539
+ result.errors.push(uploadResult.error || "Unknown attachment upload error");
7540
+ }
7541
+ } catch (error) {
7542
+ const errorMessage = `Failed to upload attachment ${doc._id}/${attachmentName}: ${error instanceof Error ? error.message : String(error)}`;
7543
+ result.errors.push(errorMessage);
7544
+ logger.error(errorMessage);
7545
+ }
7546
+ }
7547
+ }
7548
+ this.reportProgress(
7549
+ "attachments",
7550
+ documents.length,
7551
+ documents.length,
7552
+ `Uploaded ${result.restored} attachments`
7553
+ );
7554
+ return result;
7555
+ }
7556
+ /**
7557
+ * Upload a single attachment file
7558
+ */
7559
+ async uploadSingleAttachment(staticPath, docId, attachmentName, attachmentMeta, db) {
7560
+ const result = {
7561
+ success: false,
7562
+ attachmentName,
7563
+ docId
7564
+ };
7565
+ try {
7566
+ if (!attachmentMeta.path) {
7567
+ result.error = "Attachment metadata missing file path";
7568
+ return result;
7569
+ }
7570
+ let attachmentData;
7571
+ let attachmentPath;
7572
+ if (this.fs) {
7573
+ attachmentPath = this.fs.joinPath(staticPath, attachmentMeta.path);
7574
+ attachmentData = await this.fs.readBinary(attachmentPath);
7575
+ } else {
7576
+ attachmentPath = nodeFS2 && nodePath ? nodePath.join(staticPath, attachmentMeta.path) : `${staticPath}/${attachmentMeta.path}`;
7577
+ if (nodeFS2 && this.isLocalPath(staticPath)) {
7578
+ attachmentData = await nodeFS2.promises.readFile(attachmentPath);
7579
+ } else {
7580
+ const response = await fetch(attachmentPath);
7581
+ if (!response.ok) {
7582
+ result.error = `Failed to fetch attachment: ${response.status} ${response.statusText}`;
7583
+ return result;
7584
+ }
7585
+ attachmentData = await response.arrayBuffer();
7586
+ }
7587
+ }
7588
+ const doc = await db.get(docId);
7589
+ await db.putAttachment(
7590
+ docId,
7591
+ attachmentName,
7592
+ doc._rev,
7593
+ attachmentData,
7594
+ // PouchDB accepts both ArrayBuffer and Buffer
7595
+ attachmentMeta.content_type
7596
+ );
7597
+ result.success = true;
7598
+ } catch (error) {
7599
+ result.error = error instanceof Error ? error.message : String(error);
7600
+ }
7601
+ return result;
7602
+ }
7603
+ /**
7604
+ * Restore CourseConfig document from manifest
7605
+ */
7606
+ async restoreCourseConfig(manifest, targetDB) {
7607
+ const results = {
7608
+ restored: 0,
7609
+ errors: [],
7610
+ warnings: []
7611
+ };
7612
+ try {
7613
+ if (!manifest.courseConfig) {
7614
+ results.warnings.push(
7615
+ "No courseConfig found in manifest, skipping CourseConfig document creation"
7616
+ );
7617
+ return results;
7618
+ }
7619
+ const courseConfigDoc = {
7620
+ _id: "CourseConfig",
7621
+ ...manifest.courseConfig,
7622
+ courseID: manifest.courseId
7623
+ };
7624
+ delete courseConfigDoc._rev;
7625
+ await targetDB.put(courseConfigDoc);
7626
+ results.restored = 1;
7627
+ logger.info(`CourseConfig document created for course: ${manifest.courseId}`);
7628
+ } catch (error) {
7629
+ const errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
7630
+ results.errors.push(`Failed to restore CourseConfig: ${errorMessage}`);
7631
+ logger.error("CourseConfig restoration failed:", error);
7632
+ }
7633
+ return results;
7634
+ }
7635
+ /**
7636
+ * Calculate expected document counts from manifest
7637
+ */
7638
+ calculateExpectedCounts(manifest) {
7639
+ const counts = {};
7640
+ for (const chunk of manifest.chunks) {
7641
+ counts[chunk.docType] = (counts[chunk.docType] || 0) + chunk.documentCount;
7642
+ }
7643
+ if (manifest.designDocs.length > 0) {
7644
+ counts["_design"] = manifest.designDocs.length;
7645
+ }
7646
+ return counts;
7647
+ }
7648
+ /**
7649
+ * Clean up database after failed migration
7650
+ */
7651
+ async cleanupFailedMigration(db) {
7652
+ logger.info("Cleaning up failed migration...");
7653
+ try {
7654
+ const allDocs = await db.allDocs();
7655
+ const docsToDelete = allDocs.rows.map((row) => ({
7656
+ _id: row.id,
7657
+ _rev: row.value.rev,
7658
+ _deleted: true
7659
+ }));
7660
+ if (docsToDelete.length > 0) {
7661
+ await db.bulkDocs(docsToDelete);
7662
+ logger.info(`Cleaned up ${docsToDelete.length} documents from failed migration`);
7663
+ }
7664
+ } catch (error) {
7665
+ logger.error("Failed to cleanup documents:", error);
7666
+ throw error;
7667
+ }
7668
+ }
7669
+ /**
7670
+ * Report progress to callback if available
7671
+ */
7672
+ reportProgress(phase, current, total, message) {
7673
+ if (this.progressCallback) {
7674
+ this.progressCallback({
7675
+ phase,
7676
+ current,
7677
+ total,
7678
+ message
7679
+ });
7680
+ }
7681
+ }
7682
+ /**
7683
+ * Check if a path is a local file path (vs URL)
7684
+ */
7685
+ isLocalPath(path2) {
7686
+ return !path2.startsWith("http://") && !path2.startsWith("https://");
7687
+ }
7688
+ };
7689
+ }
7690
+ });
7691
+
7692
+ // src/util/migrator/index.ts
7693
+ var init_migrator = __esm({
7694
+ "src/util/migrator/index.ts"() {
7695
+ "use strict";
7696
+ init_StaticToCouchDBMigrator();
7697
+ init_validation();
7698
+ init_FileSystemAdapter();
7699
+ }
7700
+ });
7701
+
7702
+ // src/util/dataDirectory.ts
7703
+ import * as path from "path";
7704
+ import * as os from "os";
7705
+ function getAppDataDirectory() {
7706
+ if (ENV.LOCAL_STORAGE_PREFIX) {
7707
+ return path.join(os.homedir(), `.tuilder`, ENV.LOCAL_STORAGE_PREFIX);
7708
+ } else {
7709
+ return path.join(os.homedir(), ".tuilder");
7710
+ }
7711
+ }
7712
+ function getDbPath(dbName) {
7713
+ return path.join(getAppDataDirectory(), dbName);
7714
+ }
7715
+ var init_dataDirectory = __esm({
7716
+ "src/util/dataDirectory.ts"() {
7717
+ "use strict";
7718
+ init_logger();
7719
+ init_factory();
7720
+ }
7721
+ });
7722
+
7723
+ // src/util/index.ts
7724
+ var init_util2 = __esm({
7725
+ "src/util/index.ts"() {
7726
+ "use strict";
7727
+ init_Loggable();
7728
+ init_packer();
7729
+ init_migrator();
7730
+ init_dataDirectory();
7731
+ }
7732
+ });
7733
+
7734
+ // src/study/SourceMixer.ts
7735
+ var init_SourceMixer = __esm({
7736
+ "src/study/SourceMixer.ts"() {
7737
+ "use strict";
7738
+ }
7739
+ });
7740
+
7741
+ // src/study/MixerDebugger.ts
7742
+ function printMixerSummary(run) {
7743
+ console.group(`\u{1F3A8} Mixer Run: ${run.mixerType}`);
7744
+ logger.info(`Run ID: ${run.runId}`);
7745
+ logger.info(`Time: ${run.timestamp.toISOString()}`);
7746
+ logger.info(
7747
+ `Config: limit=${run.requestedLimit}${run.quotaPerSource ? `, quota/source=${run.quotaPerSource}` : ""}`
7748
+ );
7749
+ console.group(`\u{1F4E5} Input: ${run.sourceSummaries.length} sources`);
7750
+ for (const src of run.sourceSummaries) {
7751
+ logger.info(
7752
+ ` ${src.sourceName || src.sourceId}: ${src.totalCards} cards (${src.reviewCount} reviews, ${src.newCount} new)`
7753
+ );
7754
+ logger.info(` Score range: [${src.scoreRange[0].toFixed(2)}, ${src.scoreRange[1].toFixed(2)}], avg: ${src.avgScore.toFixed(2)}`);
7755
+ }
7756
+ console.groupEnd();
7757
+ console.group(`\u{1F4E4} Output: ${run.finalCount} cards selected (${run.reviewsSelected} reviews, ${run.newSelected} new)`);
7758
+ for (const breakdown of run.sourceBreakdowns) {
7759
+ const name = breakdown.sourceName || breakdown.sourceId;
7760
+ logger.info(
7761
+ ` ${name}: ${breakdown.totalSelected} selected (${breakdown.reviewsSelected} reviews, ${breakdown.newSelected} new) - ${breakdown.selectionRate.toFixed(1)}% selection rate`
7762
+ );
7763
+ }
7764
+ console.groupEnd();
7765
+ console.groupEnd();
7766
+ }
7767
+ function mountMixerDebugger() {
7768
+ if (typeof window === "undefined") return;
7769
+ const win = window;
7770
+ win.skuilder = win.skuilder || {};
7771
+ win.skuilder.mixer = mixerDebugAPI;
7772
+ }
7773
+ var runHistory2, mixerDebugAPI;
7774
+ var init_MixerDebugger = __esm({
7775
+ "src/study/MixerDebugger.ts"() {
7776
+ "use strict";
7777
+ init_logger();
7778
+ init_navigators();
7779
+ runHistory2 = [];
7780
+ mixerDebugAPI = {
7781
+ /**
7782
+ * Get raw run history for programmatic access.
7783
+ */
7784
+ get runs() {
7785
+ return [...runHistory2];
7786
+ },
7787
+ /**
7788
+ * Show summary of a specific mixer run.
7789
+ */
7790
+ showRun(idOrIndex = 0) {
7791
+ if (runHistory2.length === 0) {
7792
+ logger.info("[Mixer Debug] No runs captured yet.");
7793
+ return;
7794
+ }
7795
+ let run;
7796
+ if (typeof idOrIndex === "number") {
7797
+ run = runHistory2[idOrIndex];
7798
+ if (!run) {
7799
+ logger.info(`[Mixer Debug] No run found at index ${idOrIndex}. History length: ${runHistory2.length}`);
7800
+ return;
7801
+ }
7802
+ } else {
7803
+ run = runHistory2.find((r) => r.runId.endsWith(idOrIndex));
7804
+ if (!run) {
7805
+ logger.info(`[Mixer Debug] No run found matching ID '${idOrIndex}'.`);
7806
+ return;
7807
+ }
7808
+ }
7809
+ printMixerSummary(run);
7810
+ },
7811
+ /**
7812
+ * Show summary of the last mixer run.
7813
+ */
7814
+ showLastMix() {
7815
+ this.showRun(0);
7816
+ },
7817
+ /**
7818
+ * Explain source balance in the last run.
7819
+ */
7820
+ explainSourceBalance() {
7821
+ if (runHistory2.length === 0) {
7822
+ logger.info("[Mixer Debug] No runs captured yet.");
7823
+ return;
7824
+ }
7825
+ const run = runHistory2[0];
7826
+ console.group("\u2696\uFE0F Source Balance Analysis");
7827
+ logger.info(`Mixer: ${run.mixerType}`);
7828
+ logger.info(`Requested limit: ${run.requestedLimit}`);
7829
+ if (run.quotaPerSource) {
7830
+ logger.info(`Quota per source: ${run.quotaPerSource}`);
7831
+ }
7832
+ console.group("Input Distribution:");
7833
+ for (const src of run.sourceSummaries) {
7834
+ const name = src.sourceName || src.sourceId;
7835
+ logger.info(`${name}:`);
7836
+ logger.info(` Provided: ${src.totalCards} cards (${src.reviewCount} reviews, ${src.newCount} new)`);
7837
+ logger.info(` Score range: [${src.scoreRange[0].toFixed(2)}, ${src.scoreRange[1].toFixed(2)}]`);
7838
+ }
7839
+ console.groupEnd();
7840
+ console.group("Selection Results:");
7841
+ for (const breakdown of run.sourceBreakdowns) {
7842
+ const name = breakdown.sourceName || breakdown.sourceId;
7843
+ logger.info(`${name}:`);
7844
+ logger.info(
7845
+ ` Selected: ${breakdown.totalSelected}/${breakdown.reviewsProvided + breakdown.newProvided} (${breakdown.selectionRate.toFixed(1)}%)`
7846
+ );
7847
+ logger.info(` Reviews: ${breakdown.reviewsSelected}/${breakdown.reviewsProvided}`);
7848
+ logger.info(` New: ${breakdown.newSelected}/${breakdown.newProvided}`);
7849
+ if (breakdown.reviewsProvided > 0 && breakdown.reviewsSelected === 0) {
7850
+ logger.info(` \u26A0\uFE0F Had reviews but none selected!`);
7851
+ }
7852
+ if (breakdown.totalSelected === 0 && breakdown.reviewsProvided + breakdown.newProvided > 0) {
7853
+ logger.info(` \u26A0\uFE0F Had cards but none selected!`);
7854
+ }
7855
+ }
7856
+ console.groupEnd();
7857
+ const selectionRates = run.sourceBreakdowns.map((b) => b.selectionRate);
7858
+ const avgRate = selectionRates.reduce((a, b) => a + b, 0) / selectionRates.length;
7859
+ const maxDeviation = Math.max(...selectionRates.map((r) => Math.abs(r - avgRate)));
7860
+ if (maxDeviation > 20) {
7861
+ logger.info(`
7862
+ \u26A0\uFE0F Significant imbalance detected (max deviation: ${maxDeviation.toFixed(1)}%)`);
7863
+ logger.info("Possible causes:");
7864
+ logger.info(" - Score range differences between sources");
7865
+ logger.info(" - One source has much better quality cards");
7866
+ logger.info(" - Different card availability (reviews vs new)");
7867
+ }
7868
+ console.groupEnd();
7869
+ },
7870
+ /**
7871
+ * Compare score distributions across sources.
7872
+ */
7873
+ compareScores() {
7874
+ if (runHistory2.length === 0) {
7875
+ logger.info("[Mixer Debug] No runs captured yet.");
7876
+ return;
7877
+ }
7878
+ const run = runHistory2[0];
7879
+ console.group("\u{1F4CA} Score Distribution Comparison");
7880
+ console.table(
7881
+ run.sourceSummaries.map((src) => ({
7882
+ source: src.sourceName || src.sourceId,
7883
+ cards: src.totalCards,
7884
+ min: src.bottomScore.toFixed(3),
7885
+ max: src.topScore.toFixed(3),
7886
+ avg: src.avgScore.toFixed(3),
7887
+ range: (src.topScore - src.bottomScore).toFixed(3)
7888
+ }))
7889
+ );
7890
+ const ranges = run.sourceSummaries.map((s) => s.topScore - s.bottomScore);
7891
+ const avgScores = run.sourceSummaries.map((s) => s.avgScore);
7892
+ const rangeDiff = Math.max(...ranges) - Math.min(...ranges);
7893
+ const avgDiff = Math.max(...avgScores) - Math.min(...avgScores);
7894
+ if (rangeDiff > 0.3 || avgDiff > 0.2) {
7895
+ logger.info("\n\u26A0\uFE0F Significant score distribution differences detected");
7896
+ logger.info(
7897
+ "This may cause one source to dominate selection if using global sorting (not quota-based)"
7898
+ );
7899
+ }
7900
+ console.groupEnd();
7901
+ },
7902
+ /**
7903
+ * Show detailed information for a specific card.
7904
+ */
7905
+ showCard(cardId) {
7906
+ for (const run of runHistory2) {
7907
+ const card = run.cards.find((c) => c.cardId === cardId);
7908
+ if (card) {
7909
+ const source = run.sourceSummaries.find((s) => s.sourceIndex === card.sourceIndex);
7910
+ console.group(`\u{1F3B4} Card: ${cardId}`);
7911
+ logger.info(`Course: ${card.courseId}`);
7912
+ logger.info(`Source: ${source?.sourceName || source?.sourceId || "unknown"}`);
7913
+ logger.info(`Origin: ${card.origin}`);
7914
+ logger.info(`Score: ${card.score.toFixed(3)}`);
7915
+ if (card.rankInSource) {
7916
+ logger.info(`Rank in source: #${card.rankInSource}`);
7917
+ }
7918
+ if (card.rankInMix) {
7919
+ logger.info(`Rank in mixed results: #${card.rankInMix}`);
7920
+ }
7921
+ logger.info(`Selected: ${card.selected ? "Yes \u2705" : "No \u274C"}`);
7922
+ if (!card.selected && card.rankInSource) {
7923
+ logger.info("\nWhy not selected:");
7924
+ if (run.quotaPerSource && card.rankInSource > run.quotaPerSource) {
7925
+ logger.info(` - Ranked #${card.rankInSource} in source, but quota was ${run.quotaPerSource}`);
7926
+ }
7927
+ logger.info(" - Check score compared to selected cards using .showRun()");
7928
+ }
7929
+ console.groupEnd();
7930
+ return;
7931
+ }
7932
+ }
7933
+ logger.info(`[Mixer Debug] Card '${cardId}' not found in recent runs.`);
7934
+ },
7935
+ /**
7936
+ * Show all runs in compact format.
7937
+ */
7938
+ listRuns() {
7939
+ if (runHistory2.length === 0) {
7940
+ logger.info("[Mixer Debug] No runs captured yet.");
7941
+ return;
7942
+ }
7943
+ console.table(
7944
+ runHistory2.map((r) => ({
7945
+ id: r.runId.slice(-8),
7946
+ time: r.timestamp.toLocaleTimeString(),
7947
+ mixer: r.mixerType,
7948
+ sources: r.sourceSummaries.length,
7949
+ selected: r.finalCount,
7950
+ reviews: r.reviewsSelected,
7951
+ new: r.newSelected
7952
+ }))
7953
+ );
7954
+ },
7955
+ /**
7956
+ * Export run history as JSON for bug reports.
7957
+ */
7958
+ export() {
7959
+ const json = JSON.stringify(runHistory2, null, 2);
7960
+ logger.info("[Mixer Debug] Run history exported. Copy the returned string or use:");
7961
+ logger.info(" copy(window.skuilder.mixer.export())");
7962
+ return json;
7963
+ },
7964
+ /**
7965
+ * Clear run history.
7966
+ */
7967
+ clear() {
7968
+ runHistory2.length = 0;
7969
+ logger.info("[Mixer Debug] Run history cleared.");
7970
+ },
7971
+ /**
7972
+ * Show help.
7973
+ */
7974
+ help() {
7975
+ logger.info(`
7976
+ \u{1F3A8} Mixer Debug API
7977
+
7978
+ Commands:
7979
+ .showLastMix() Show summary of most recent mixer run
7980
+ .showRun(id|index) Show summary of a specific run (by index or ID suffix)
7981
+ .explainSourceBalance() Analyze source balance and selection patterns
7982
+ .compareScores() Compare score distributions across sources
7983
+ .showCard(cardId) Show mixer decisions for a specific card
7984
+ .listRuns() List all captured runs in table format
7985
+ .export() Export run history as JSON for bug reports
7986
+ .clear() Clear run history
7987
+ .runs Access raw run history array
7988
+ .help() Show this help message
7989
+
7990
+ Example:
7991
+ window.skuilder.mixer.showLastMix()
7992
+ window.skuilder.mixer.explainSourceBalance()
7993
+ window.skuilder.mixer.compareScores()
7994
+ `);
7995
+ }
7996
+ };
7997
+ mountMixerDebugger();
7998
+ }
7999
+ });
8000
+
8001
+ // src/study/SessionOverlay.ts
8002
+ function getActiveController() {
8003
+ return activeController;
8004
+ }
8005
+ function toggleSessionOverlay() {
8006
+ if (typeof document === "undefined") {
8007
+ logger.info("[Session Overlay] No DOM available (non-browser host); overlay unavailable.");
8008
+ return;
8009
+ }
8010
+ if (overlayEl) {
8011
+ teardown();
8012
+ logger.info("[Session Overlay] Hidden.");
8013
+ } else {
8014
+ mount();
8015
+ logger.info("[Session Overlay] Shown. Toggle off with window.skuilder.session.dbgOverlay().");
8016
+ }
8017
+ }
8018
+ function mount() {
8019
+ minified = false;
8020
+ overlayEl = document.createElement("div");
8021
+ overlayEl.id = OVERLAY_ID;
8022
+ Object.assign(overlayEl.style, {
8023
+ position: "fixed",
8024
+ top: "8px",
8025
+ left: "8px",
8026
+ zIndex: "2147483647",
8027
+ maxWidth: "320px",
8028
+ maxHeight: "90vh",
8029
+ overflowY: "auto",
8030
+ padding: "8px 10px",
8031
+ background: "rgba(17, 24, 39, 0.92)",
8032
+ color: "#e5e7eb",
8033
+ font: "11px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace",
8034
+ borderRadius: "6px",
8035
+ boxShadow: "0 4px 16px rgba(0,0,0,0.4)",
8036
+ pointerEvents: "auto",
8037
+ userSelect: "none"
8038
+ });
8039
+ document.body.appendChild(overlayEl);
8040
+ render();
8041
+ pollHandle = setInterval(render, POLL_MS);
8042
+ }
8043
+ function teardown() {
8044
+ if (pollHandle !== null) {
8045
+ clearInterval(pollHandle);
8046
+ pollHandle = null;
8047
+ }
8048
+ if (overlayEl?.parentNode) {
8049
+ overlayEl.parentNode.removeChild(overlayEl);
8050
+ }
8051
+ overlayEl = null;
8052
+ }
8053
+ function render() {
8054
+ if (!overlayEl) return;
8055
+ spinnerFrame++;
8056
+ const ctrl = getActiveController();
8057
+ if (!ctrl) {
8058
+ lastSnapshot = null;
8059
+ overlayEl.innerHTML = headerHtml() + (minified ? "" : `<div style="opacity:.65">No active session.</div>`);
8060
+ attachHandlers();
8061
+ return;
8062
+ }
8063
+ const s = ctrl.getDebugSnapshot();
8064
+ lastSnapshot = s;
8065
+ if (minified) {
8066
+ overlayEl.innerHTML = headerHtml();
8067
+ attachHandlers();
8068
+ return;
8069
+ }
8070
+ overlayEl.innerHTML = headerHtml() + replanHtml(s) + metaHtml(s) + hintsHtml(s.sessionHints) + backlogHtml(s.reviewBacklog) + strategyPressureHtml(s.strategyPressure) + queueHtml("supplyQ", "supplyQ", s.supplyQ) + queueHtml("failedQ", "failedQ", s.failedQ) + drawnHtml("drawn", s.drawnCards);
8071
+ attachHandlers();
8072
+ }
8073
+ function attachHandlers() {
8074
+ if (!overlayEl) return;
8075
+ overlayEl.querySelectorAll("[data-q]").forEach((el) => {
8076
+ el.onclick = () => {
8077
+ const key = el.dataset.q;
8078
+ if (!key) return;
8079
+ expanded[key] = !expanded[key];
8080
+ render();
8081
+ };
8082
+ });
8083
+ const copyBtn = overlayEl.querySelector("[data-copy]");
8084
+ if (copyBtn) {
8085
+ copyBtn.onclick = (ev) => {
8086
+ ev.stopPropagation();
8087
+ copySnapshot();
8088
+ };
8089
+ }
8090
+ const minBtn = overlayEl.querySelector("[data-min]");
8091
+ if (minBtn) {
8092
+ minBtn.onclick = (ev) => {
8093
+ ev.stopPropagation();
8094
+ minified = !minified;
8095
+ render();
8096
+ };
8097
+ }
8098
+ }
8099
+ function copySnapshot() {
8100
+ const text = snapshotToText(lastSnapshot);
8101
+ const flash = () => {
8102
+ copyFlashUntil = Date.now() + 1200;
8103
+ render();
8104
+ };
8105
+ const clip = typeof navigator !== "undefined" ? navigator.clipboard : void 0;
8106
+ if (clip?.writeText) {
8107
+ clip.writeText(text).then(flash, (err) => {
8108
+ logger.warn(`[Session Overlay] Clipboard write failed: ${String(err)}`);
8109
+ });
8110
+ } else {
8111
+ logger.info(`[Session Overlay] Clipboard unavailable; snapshot follows:
8112
+ ${text}`);
8113
+ }
8114
+ }
8115
+ function headerHtml() {
8116
+ const flashing = Date.now() < copyFlashUntil;
8117
+ const btnLabel = flashing ? "\u2713 copied" : "\u2398 copy";
8118
+ const btnColor = flashing ? "#86efac" : "#93c5fd";
8119
+ const copyBtn = `<span data-copy style="cursor:pointer;float:right;font-weight:400;color:${btnColor};border:1px solid currentColor;border-radius:4px;padding:0 4px;line-height:1.3">${btnLabel}</span>`;
8120
+ const minBtn = `<span data-min title="${minified ? "Restore" : "Minify"}" style="cursor:pointer;float:right;font-weight:400;color:#93c5fd;border:1px solid currentColor;border-radius:4px;padding:0 5px;margin-right:4px;line-height:1.3">${minified ? "\u25A2" : "\u2014"}</span>`;
8121
+ return `<div style="font-weight:600;color:#93c5fd;margin-bottom:${minified ? 0 : 4}px">${copyBtn}${minBtn}\u2699 SessionController</div>`;
8122
+ }
8123
+ function replanHtml(s) {
8124
+ if (!s.replanActive) {
8125
+ return `<div style="margin-bottom:6px;opacity:.45">\u25CB idle</div>`;
8126
+ }
8127
+ const frame = SPINNER_FRAMES[spinnerFrame % SPINNER_FRAMES.length];
8128
+ const reason = esc(s.replanLabel ?? "(auto)");
8129
+ return `<div style="margin-bottom:6px;color:#fde047">${frame} replanning <span style="opacity:.85">[${reason}]</span></div>`;
8130
+ }
8131
+ function metaHtml(s) {
8132
+ const mmss = formatTime(s.secondsRemaining);
8133
+ const guarantee = s.hasCardGuarantee ? ` \xB7 <span style="color:#fbbf24">guarantee ${s.minCardsGuarantee}</span>` : "";
8134
+ const rows = [
8135
+ `time ${mmss}${guarantee}`,
8136
+ `well-indicated left: ${s.wellIndicatedRemaining}`,
8137
+ `current: ${s.currentCard ? esc(s.currentCard) : '<span style="opacity:.6">\u2014</span>'}`
8138
+ ];
8139
+ return `<div style="margin-bottom:6px">${rows.map((r) => `<div>${r}</div>`).join("")}</div>`;
8140
+ }
8141
+ function hintsHtml(h) {
8142
+ const parts = [];
8143
+ if (h) {
8144
+ if (h.boostTags && Object.keys(h.boostTags).length) {
8145
+ parts.push(
8146
+ `boost: ` + Object.entries(h.boostTags).map(([k, v]) => `${esc(k)}<span style="opacity:.6">\xD7${v}</span>`).join(", ")
8147
+ );
8148
+ }
8149
+ if (h.boostCards && Object.keys(h.boostCards).length) {
8150
+ parts.push(
8151
+ `boostCards: ` + Object.entries(h.boostCards).map(([k, v]) => `${esc(k)}<span style="opacity:.6">\xD7${v}</span>`).join(", ")
8152
+ );
8153
+ }
8154
+ if (h.requireCards?.length) parts.push(`require: ${h.requireCards.map(esc).join(", ")}`);
8155
+ if (h.requireTags?.length) parts.push(`requireTags: ${h.requireTags.map(esc).join(", ")}`);
8156
+ if (h.excludeTags?.length) parts.push(`exclude: ${h.excludeTags.map(esc).join(", ")}`);
8157
+ if (h.excludeCards?.length) parts.push(`excludeCards: ${h.excludeCards.map(esc).join(", ")}`);
8158
+ }
8159
+ const body = parts.length ? parts.map((p) => `<div style="margin-left:6px">${p}</div>`).join("") : `<div style="margin-left:6px;opacity:.6">none</div>`;
8160
+ return `<div style="margin-bottom:6px"><div style="color:#86efac">sessionHints</div>${body}</div>`;
8161
+ }
8162
+ function backlogHtml(backlog) {
8163
+ if (!backlog.length) return "";
8164
+ const rows = backlog.map((b) => {
8165
+ const hot = b.backlogMultiplier >= 3;
8166
+ const multColor = b.backlogMultiplier <= 1 ? "#86efac" : hot ? "#fca5a5" : "#fcd34d";
8167
+ const headroom = b.backlogMultiplier > 1 ? `climbing (\xD7${b.backlogGrowthRate.toFixed(2)} per ${b.healthyBacklog}-review excess, unbounded)` : "healthy \u2014 no pressure";
8168
+ const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
8169
+ const next = b.nextDueIn ? ` <span style="opacity:.6">\xB7 next due ${esc(b.nextDueIn)}</span>` : "";
8170
+ return `<div style="margin-left:6px"><span style="opacity:.7">${esc(b.courseId.slice(0, 8))}</span> due ${b.dueNow}/${b.scheduledTotal} <span style="opacity:.6">(healthy ${b.healthyBacklog})</span>${next}<div style="margin-left:6px">pressure <span style="color:${multColor}">\xD7${b.backlogMultiplier.toFixed(2)}</span> <span style="opacity:.6">${headroom} \xB7 top review ${top}</span></div></div>`;
8171
+ }).join("");
8172
+ return `<div style="margin-bottom:6px"><div style="color:#93c5fd">review backpressure</div>${rows}</div>`;
8173
+ }
8174
+ function pressureColor(multiplier, max) {
8175
+ if (multiplier <= 1.001) return "#86efac";
8176
+ if (max !== void 0 && max > 1) {
8177
+ return (multiplier - 1) / (max - 1) >= 0.75 ? "#fca5a5" : "#fcd34d";
8178
+ }
8179
+ return multiplier >= 3 ? "#fca5a5" : "#fcd34d";
8180
+ }
8181
+ function toggleKey(raw) {
8182
+ return raw.replace(/[^\w:.|-]/g, "_");
8183
+ }
8184
+ function gaugeHtml(sectionKey, g) {
8185
+ const cap = g.max !== void 0 ? `<span style="opacity:.5">/${g.max}</span>` : "";
8186
+ const detail = g.detail ? ` <span style="opacity:.6">${esc(g.detail)}</span>` : "";
8187
+ let html = `<div style="margin-left:6px">${esc(g.label)} <span style="color:${pressureColor(g.multiplier, g.max)}">\xD7${g.multiplier.toFixed(2)}</span>${cap}${detail}`;
8188
+ const items = g.items ?? [];
8189
+ if (items.length > 0) {
8190
+ const key = toggleKey(`sp|${sectionKey}|${g.id}`);
8191
+ const isOpen = !!expanded[key];
8192
+ const shown = isOpen ? items : items.slice(0, INLINE_THRESHOLD);
8193
+ html += `<div style="margin-left:6px">` + shown.map(
8194
+ (it) => `<div style="white-space:nowrap;opacity:.75">${esc(it.label)}${it.value ? ` <span style="opacity:.6">${esc(it.value)}</span>` : ""}</div>`
8195
+ ).join("");
8196
+ if (items.length > INLINE_THRESHOLD) {
8197
+ const footer = isOpen ? "\u25BE show less" : `\u2026 +${items.length - shown.length} more`;
8198
+ html += `<div data-q="${key}" style="cursor:pointer;opacity:.6">${footer}</div>`;
8199
+ }
8200
+ html += `</div>`;
8201
+ }
8202
+ return html + `</div>`;
8203
+ }
8204
+ function strategyPressureHtml(list) {
8205
+ if (!list.length) return "";
8206
+ const sections = list.map((s) => {
8207
+ const sectionKey = `${s.source}:${s.courseId.slice(0, 8)}`;
8208
+ const top = s.topScore !== null && s.topScore !== void 0 ? s.topScore.toFixed(2) : "\u2014";
8209
+ const hints = s.hintsLabel ? `<div style="margin-left:6px;opacity:.6">hints: ${esc(s.hintsLabel)}</div>` : "";
8210
+ return `<div style="margin-left:6px"><span style="opacity:.7">${esc(s.source)} \xB7 ${esc(s.courseId.slice(0, 8))}</span> <span style="opacity:.6">top score ${top}</span>` + s.gauges.map((g) => gaugeHtml(sectionKey, g)).join("") + hints + `</div>`;
8211
+ }).join("");
8212
+ return `<div style="margin-bottom:6px"><div style="color:#fdba74">strategy backpressure</div>${sections}</div>`;
8213
+ }
8214
+ function fmtScore(score) {
8215
+ if (score === void 0) return "";
8216
+ if (!Number.isFinite(score)) return "REQ";
8217
+ return score.toFixed(2);
8218
+ }
8219
+ function queueItemHtml(item) {
8220
+ const tagColor = item.origin === "review" ? "#93c5fd" : "#fcd34d";
8221
+ const score = fmtScore(item.score);
8222
+ const label = `${item.origin === "review" ? "r" : "n"}${score ? " " + score : ""}`;
8223
+ return `${esc(item.cardID)}<span style="color:${tagColor};opacity:.85"> [${label}]</span>`;
8224
+ }
8225
+ function queueHtml(key, label, q) {
8226
+ const collapsible = q.length > INLINE_THRESHOLD;
8227
+ const isOpen = collapsible && expanded[key];
8228
+ const caret = collapsible ? expanded[key] ? "\u25BE " : "\u25B8 " : "";
8229
+ const drawn = q.dequeueCount ? ` <span style="opacity:.5">drawn ${q.dequeueCount}</span>` : "";
8230
+ const titleStyle = collapsible ? "cursor:pointer;color:#f9a8d4" : "color:#f9a8d4";
8231
+ const titleAttr = collapsible ? ` data-q="${key}"` : "";
8232
+ const title = `<div${titleAttr} style="${titleStyle}">${caret}${label}: ${q.length}${drawn}</div>`;
8233
+ if (!q.cards.length) {
8234
+ return title + `<div style="margin:1px 0 6px 6px;opacity:.5">empty</div>`;
8235
+ }
8236
+ const shown = isOpen ? q.cards : q.cards.slice(0, INLINE_THRESHOLD);
8237
+ const hiddenCount = q.length - shown.length;
8238
+ const listMarginBottom = collapsible ? 2 : 6;
8239
+ let body = `<ol style="margin:2px 0 ${listMarginBottom}px 0;padding-left:20px">` + shown.map((c) => `<li style="white-space:nowrap">${queueItemHtml(c)}</li>`).join("") + `</ol>`;
8240
+ if (collapsible) {
8241
+ const footer = isOpen ? "\u25BE show less" : `\u2026 +${hiddenCount} more`;
8242
+ body += `<div data-q="${key}" style="cursor:pointer;margin:0 0 6px 20px;opacity:.6">${footer}</div>`;
8243
+ }
8244
+ return title + body;
8245
+ }
8246
+ function outcomeGlyph(correct) {
8247
+ if (correct === true) return `<span style="color:#86efac">\u2713</span>`;
8248
+ if (correct === false) return `<span style="color:#fca5a5">\u2717</span>`;
8249
+ return `<span style="opacity:.5">\xB7</span>`;
8250
+ }
8251
+ function drawnHtml(key, drawn) {
8252
+ const collapsible = drawn.length > INLINE_THRESHOLD;
8253
+ const isOpen = collapsible && expanded[key];
8254
+ const caret = collapsible ? expanded[key] ? "\u25BE " : "\u25B8 " : "";
8255
+ const titleStyle = collapsible ? "cursor:pointer;color:#c4b5fd" : "color:#c4b5fd";
8256
+ const titleAttr = collapsible ? ` data-q="${key}"` : "";
8257
+ const title = `<div${titleAttr} style="${titleStyle}">${caret}drawn: ${drawn.length}</div>`;
8258
+ if (!drawn.length) {
8259
+ return title + `<div style="margin:1px 0 6px 6px;opacity:.5">none yet</div>`;
8260
+ }
8261
+ const shown = isOpen ? drawn : drawn.slice(0, INLINE_THRESHOLD);
8262
+ const hiddenCount = drawn.length - shown.length;
8263
+ const listMarginBottom = collapsible ? 2 : 6;
8264
+ const rows = shown.map((d) => {
8265
+ const retries = d.attempts > 1 ? `<span style="opacity:.5"> \xD7${d.attempts}</span>` : "";
8266
+ const time = `<span style="opacity:.45"> ${Math.round(d.timeSpentMs / 100) / 10}s</span>`;
8267
+ return `<li style="white-space:nowrap">${outcomeGlyph(d.correct)} ${esc(d.cardID)}<span style="opacity:.5"> [${esc(d.status)}]</span>${retries}${time}</li>`;
8268
+ }).join("");
8269
+ let body = `<ol style="margin:2px 0 ${listMarginBottom}px 0;padding-left:20px">${rows}</ol>`;
8270
+ if (collapsible) {
8271
+ const footer = isOpen ? "\u25BE show less" : `\u2026 +${hiddenCount} more`;
8272
+ body += `<div data-q="${key}" style="cursor:pointer;margin:0 0 6px 20px;opacity:.6">${footer}</div>`;
8273
+ }
8274
+ return title + body;
8275
+ }
8276
+ function snapshotToText(s) {
8277
+ if (!s) return "SessionController \u2014 no active session.";
8278
+ const lines = [];
8279
+ lines.push("=== SessionController ===");
8280
+ lines.push(`time ${formatTime(s.secondsRemaining)}`);
8281
+ if (s.hasCardGuarantee) lines.push(`guarantee: ${s.minCardsGuarantee}`);
8282
+ lines.push(`well-indicated left: ${s.wellIndicatedRemaining}`);
8283
+ lines.push(`current: ${s.currentCard ?? "\u2014"}`);
8284
+ lines.push(
8285
+ s.replanActive ? `replan: ACTIVE [${s.replanLabel ?? "(auto)"}]` : "replan: idle"
8286
+ );
8287
+ lines.push("");
8288
+ lines.push("sessionHints:");
8289
+ const h = s.sessionHints;
8290
+ const hintParts = [];
8291
+ if (h) {
8292
+ if (h.boostTags && Object.keys(h.boostTags).length)
8293
+ hintParts.push(` boost: ${Object.entries(h.boostTags).map(([k, v]) => `${k}\xD7${v}`).join(", ")}`);
8294
+ if (h.boostCards && Object.keys(h.boostCards).length)
8295
+ hintParts.push(` boostCards: ${Object.entries(h.boostCards).map(([k, v]) => `${k}\xD7${v}`).join(", ")}`);
8296
+ if (h.requireCards?.length) hintParts.push(` require: ${h.requireCards.join(", ")}`);
8297
+ if (h.requireTags?.length) hintParts.push(` requireTags: ${h.requireTags.join(", ")}`);
8298
+ if (h.excludeTags?.length) hintParts.push(` exclude: ${h.excludeTags.join(", ")}`);
8299
+ if (h.excludeCards?.length) hintParts.push(` excludeCards: ${h.excludeCards.join(", ")}`);
8300
+ }
8301
+ lines.push(hintParts.length ? hintParts.join("\n") : " none");
8302
+ if (s.reviewBacklog.length) {
8303
+ lines.push("");
8304
+ lines.push("review backpressure:");
8305
+ for (const b of s.reviewBacklog) {
8306
+ const headroom = b.backlogMultiplier > 1 ? "climbing" : "healthy";
8307
+ const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
8308
+ const next = b.nextDueIn ? `, next due ${b.nextDueIn}` : "";
8309
+ lines.push(
8310
+ ` ${b.courseId.slice(0, 8)}: due ${b.dueNow}/${b.scheduledTotal} (healthy ${b.healthyBacklog})${next}; pressure \xD7${b.backlogMultiplier.toFixed(2)} ${headroom}; top review ${top}`
8311
+ );
8312
+ }
8313
+ }
8314
+ if (s.strategyPressure.length) {
8315
+ lines.push("");
8316
+ lines.push("strategy backpressure:");
8317
+ for (const sp of s.strategyPressure) {
8318
+ const top = sp.topScore !== null && sp.topScore !== void 0 ? sp.topScore.toFixed(2) : "\u2014";
8319
+ lines.push(` ${sp.source} (${sp.courseId.slice(0, 8)}): top score ${top}`);
8320
+ for (const g of sp.gauges) {
8321
+ const cap = g.max !== void 0 ? `/${g.max}` : "";
8322
+ lines.push(
8323
+ ` ${g.label} \xD7${g.multiplier.toFixed(2)}${cap}${g.detail ? ` \u2014 ${g.detail}` : ""}`
8324
+ );
8325
+ for (const it of g.items ?? []) {
8326
+ lines.push(` ${it.label}${it.value ? ` (${it.value})` : ""}`);
8327
+ }
8328
+ }
8329
+ if (sp.hintsLabel) lines.push(` hints: ${sp.hintsLabel}`);
8330
+ }
8331
+ }
8332
+ const queueText = (label, q) => {
8333
+ lines.push("");
8334
+ lines.push(`${label}: ${q.length} (drawn ${q.dequeueCount})`);
8335
+ q.cards.forEach((c, i) => {
8336
+ const score = fmtScore(c.score);
8337
+ const tag = `${c.origin === "review" ? "r" : "n"}${score ? " " + score : ""}`;
8338
+ lines.push(` ${i + 1}. ${c.cardID} [${tag}]`);
8339
+ });
8340
+ };
8341
+ queueText("supplyQ", s.supplyQ);
8342
+ queueText("failedQ", s.failedQ);
8343
+ lines.push("");
8344
+ lines.push(`drawn: ${s.drawnCards.length}`);
8345
+ s.drawnCards.forEach((d, i) => {
8346
+ const mark = d.correct === true ? "\u2713" : d.correct === false ? "\u2717" : "\xB7";
8347
+ const time = `${Math.round(d.timeSpentMs / 100) / 10}s`;
8348
+ lines.push(` ${i + 1}. ${mark} ${d.cardID} [${d.status}] \xD7${d.attempts} ${time}`);
8349
+ });
8350
+ return lines.join("\n");
8351
+ }
8352
+ function formatTime(totalSeconds) {
8353
+ const s = Math.max(0, Math.round(totalSeconds));
8354
+ const m = Math.floor(s / 60);
8355
+ const r = s % 60;
8356
+ return `${m}:${r.toString().padStart(2, "0")}`;
8357
+ }
8358
+ function esc(value) {
8359
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
8360
+ }
8361
+ var activeController, OVERLAY_ID, POLL_MS, INLINE_THRESHOLD, SPINNER_FRAMES, spinnerFrame, overlayEl, pollHandle, lastSnapshot, copyFlashUntil, minified, expanded;
8362
+ var init_SessionOverlay = __esm({
8363
+ "src/study/SessionOverlay.ts"() {
8364
+ "use strict";
8365
+ init_logger();
8366
+ activeController = null;
8367
+ OVERLAY_ID = "skuilder-session-overlay";
8368
+ POLL_MS = 300;
8369
+ INLINE_THRESHOLD = 5;
8370
+ SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
8371
+ spinnerFrame = 0;
8372
+ overlayEl = null;
8373
+ pollHandle = null;
8374
+ lastSnapshot = null;
8375
+ copyFlashUntil = 0;
8376
+ minified = false;
8377
+ expanded = {
8378
+ supplyQ: false,
8379
+ failedQ: false,
8380
+ drawn: false
8381
+ };
8382
+ }
8383
+ });
8384
+
8385
+ // src/study/SessionDebugger.ts
8386
+ function showCurrentQueue() {
8387
+ if (!activeSession) {
8388
+ logger.info("[Session Debug] No active session.");
8389
+ return;
8390
+ }
8391
+ const latest = activeSession.queueSnapshots[activeSession.queueSnapshots.length - 1] || activeSession.initialQueues;
8392
+ console.group("\u{1F4CA} Current Queue State");
8393
+ logger.info(`Supply Queue: ${latest.supplyQLength} cards`);
8394
+ if (latest.supplyQNext3 && latest.supplyQNext3.length > 0) {
8395
+ logger.info(` Next: ${latest.supplyQNext3.join(", ")}`);
8396
+ }
8397
+ logger.info(`Failed Queue: ${latest.failedQLength} cards`);
8398
+ console.groupEnd();
8399
+ }
8400
+ function showPresentationHistory(sessionIndex = 0) {
8401
+ const session = sessionIndex === 0 && activeSession ? activeSession : sessionHistory[sessionIndex];
8402
+ if (!session) {
8403
+ logger.info(`[Session Debug] No session found at index ${sessionIndex}`);
8404
+ return;
8405
+ }
8406
+ console.group(`\u{1F4DC} Session History: ${session.sessionId}`);
8407
+ logger.info(`Started: ${session.startTime.toLocaleTimeString()}`);
8408
+ if (session.endTime) {
8409
+ logger.info(`Ended: ${session.endTime.toLocaleTimeString()}`);
8410
+ }
8411
+ logger.info(`Cards presented: ${session.presentations.length}`);
8412
+ if (session.presentations.length > 0) {
8413
+ console.table(
8414
+ session.presentations.map((p) => ({
8415
+ "#": p.sequenceNumber,
8416
+ course: p.courseName || p.courseId.slice(0, 8),
8417
+ origin: p.origin,
8418
+ queue: p.queueSource,
8419
+ score: p.score?.toFixed(3) || "-",
8420
+ time: p.timestamp.toLocaleTimeString()
8421
+ }))
8422
+ );
8423
+ }
8424
+ console.groupEnd();
8425
+ }
8426
+ function showInterleaving(sessionIndex = 0) {
8427
+ const session = sessionIndex === 0 && activeSession ? activeSession : sessionHistory[sessionIndex];
8428
+ if (!session) {
8429
+ logger.info(`[Session Debug] No session found at index ${sessionIndex}`);
8430
+ return;
8431
+ }
8432
+ console.group("\u{1F500} Interleaving Analysis");
8433
+ const courseCounts = /* @__PURE__ */ new Map();
8434
+ const courseOrigins = /* @__PURE__ */ new Map();
8435
+ session.presentations.forEach((p) => {
8436
+ const name = p.courseName || p.courseId;
8437
+ courseCounts.set(name, (courseCounts.get(name) || 0) + 1);
8438
+ if (!courseOrigins.has(name)) {
8439
+ courseOrigins.set(name, { review: 0, new: 0, failed: 0 });
8440
+ }
8441
+ const origins = courseOrigins.get(name);
8442
+ origins[p.origin]++;
8443
+ });
8444
+ logger.info("Course distribution:");
8445
+ console.table(
8446
+ Array.from(courseCounts.entries()).map(([course, count]) => {
8447
+ const origins = courseOrigins.get(course);
8448
+ return {
8449
+ course,
8450
+ total: count,
8451
+ reviews: origins.review,
8452
+ new: origins.new,
8453
+ failed: origins.failed,
8454
+ percentage: (count / session.presentations.length * 100).toFixed(1) + "%"
8455
+ };
8456
+ })
8457
+ );
8458
+ if (session.presentations.length > 0) {
8459
+ logger.info("\nPresentation sequence (first 20):");
8460
+ const sequence = session.presentations.slice(0, 20).map((p, idx) => `${idx + 1}. ${p.courseName || p.courseId.slice(0, 8)} (${p.origin})`).join("\n");
8461
+ logger.info(sequence);
8462
+ }
8463
+ let maxCluster = 0;
8464
+ let currentCluster = 1;
8465
+ let currentCourse = session.presentations[0]?.courseId;
8466
+ for (let i = 1; i < session.presentations.length; i++) {
8467
+ if (session.presentations[i].courseId === currentCourse) {
8468
+ currentCluster++;
8469
+ maxCluster = Math.max(maxCluster, currentCluster);
8470
+ } else {
8471
+ currentCourse = session.presentations[i].courseId;
8472
+ currentCluster = 1;
8473
+ }
8474
+ }
8475
+ if (maxCluster > 3) {
8476
+ logger.info(`
8477
+ \u26A0\uFE0F Detected clustering: max ${maxCluster} cards from same course in a row`);
8478
+ logger.info("This suggests cards are sorted by score rather than round-robin by course.");
8479
+ }
8480
+ console.groupEnd();
8481
+ }
8482
+ function mountSessionDebugger() {
8483
+ if (typeof window === "undefined") return;
8484
+ const win = window;
8485
+ win.skuilder = win.skuilder || {};
8486
+ win.skuilder.session = sessionDebugAPI;
8487
+ }
8488
+ var activeSession, sessionHistory, sessionDebugAPI;
8489
+ var init_SessionDebugger = __esm({
8490
+ "src/study/SessionDebugger.ts"() {
8491
+ "use strict";
8492
+ init_logger();
8493
+ init_PipelineDebugger();
8494
+ init_SrsDebugger();
8495
+ init_StrategyPressureDebugger();
8496
+ init_SessionOverlay();
8497
+ activeSession = null;
8498
+ sessionHistory = [];
8499
+ sessionDebugAPI = {
8500
+ /**
8501
+ * Get raw session history for programmatic access.
8502
+ */
8503
+ get sessions() {
8504
+ return [...sessionHistory];
8505
+ },
8506
+ /**
8507
+ * Get active session if any.
8508
+ */
8509
+ get active() {
8510
+ return activeSession;
8511
+ },
8512
+ /**
8513
+ * Show current queue state.
8514
+ */
8515
+ showQueue() {
8516
+ showCurrentQueue();
8517
+ },
8518
+ /**
8519
+ * Toggle the pinned, live-updating DOM overlay for the active controller
8520
+ * (queues, session hints, timer). No-ops in non-browser hosts.
8521
+ */
8522
+ dbgOverlay() {
8523
+ toggleSessionOverlay();
8524
+ },
8525
+ /**
8526
+ * Show presentation history for current or past session.
8527
+ */
8528
+ showHistory(sessionIndex = 0) {
8529
+ showPresentationHistory(sessionIndex);
8530
+ },
8531
+ /**
8532
+ * Analyze course interleaving pattern.
8533
+ */
8534
+ showInterleaving(sessionIndex = 0) {
8535
+ showInterleaving(sessionIndex);
8536
+ },
8537
+ /**
8538
+ * List all tracked sessions.
8539
+ */
8540
+ listSessions() {
8541
+ if (activeSession) {
8542
+ logger.info(`Active session: ${activeSession.sessionId} (${activeSession.presentations.length} cards presented)`);
8543
+ }
8544
+ if (sessionHistory.length === 0) {
8545
+ logger.info("[Session Debug] No completed sessions in history.");
8546
+ return;
8547
+ }
8548
+ console.table(
8549
+ sessionHistory.map((s, idx) => ({
8550
+ index: idx,
8551
+ id: s.sessionId.slice(-8),
8552
+ started: s.startTime.toLocaleTimeString(),
8553
+ ended: s.endTime?.toLocaleTimeString() || "incomplete",
8554
+ cards: s.presentations.length
8555
+ }))
8556
+ );
8557
+ },
8558
+ /**
8559
+ * Export session history as JSON for bug reports.
8560
+ */
8561
+ export() {
8562
+ const data = {
8563
+ active: activeSession,
8564
+ history: sessionHistory
8565
+ };
8566
+ const json = JSON.stringify(data, null, 2);
8567
+ logger.info("[Session Debug] Session data exported. Copy the returned string or use:");
8568
+ logger.info(" copy(window.skuilder.session.export())");
8569
+ return json;
8570
+ },
8571
+ /**
8572
+ * Clear session history.
8573
+ */
8574
+ clear() {
8575
+ sessionHistory.length = 0;
8576
+ logger.info("[Session Debug] Session history cleared.");
8577
+ },
8578
+ /**
8579
+ * Show help.
8580
+ */
8581
+ help() {
8582
+ logger.info(`
8583
+ \u{1F3AF} Session Debug API
8584
+
8585
+ Commands:
8586
+ .dbgOverlay() Toggle the pinned live overlay (queues, hints, timer)
8587
+ .showQueue() Show current queue state (active session only)
8588
+ .showHistory(index?) Show presentation history (0=current/last, 1=previous, etc)
8589
+ .showInterleaving(index?) Analyze course interleaving pattern
8590
+ .listSessions() List all tracked sessions
8591
+ .export() Export session data as JSON for bug reports
8592
+ .clear() Clear session history
8593
+ .sessions Access raw session history array
8594
+ .active Access active session (if any)
8595
+ .help() Show this help message
8596
+
8597
+ Example:
8598
+ window.skuilder.session.showHistory()
8599
+ window.skuilder.session.showInterleaving()
8600
+ window.skuilder.session.showQueue()
8601
+ `);
8602
+ }
8603
+ };
8604
+ mountSessionDebugger();
8605
+ }
8606
+ });
8607
+
8608
+ // src/study/SessionController.ts
8609
+ var init_SessionController = __esm({
8610
+ "src/study/SessionController.ts"() {
8611
+ "use strict";
8612
+ init_SrsService();
8613
+ init_EloService();
8614
+ init_ResponseProcessor();
8615
+ init_CardHydrationService();
8616
+ init_ItemQueue();
8617
+ init_couch();
8618
+ init_core();
8619
+ init_types_legacy();
8620
+ init_studySession();
8621
+ init_recording();
8622
+ init_util2();
8623
+ init_navigators();
8624
+ init_Pipeline();
8625
+ init_SourceMixer();
8626
+ init_MixerDebugger();
8627
+ init_SessionDebugger();
8628
+ init_SessionOverlay();
8629
+ init_logger();
8630
+ }
8631
+ });
8632
+
8633
+ // src/study/TagFilteredContentSource.ts
8634
+ import { hasActiveFilter } from "@vue-skuilder/common";
8635
+ var TagFilteredContentSource;
8636
+ var init_TagFilteredContentSource = __esm({
8637
+ "src/study/TagFilteredContentSource.ts"() {
8638
+ "use strict";
8639
+ init_courseDB();
8640
+ init_logger();
8641
+ TagFilteredContentSource = class {
8642
+ courseId;
8643
+ filter;
8644
+ user;
8645
+ // Cache resolved card IDs to avoid repeated lookups within a session
8646
+ resolvedCardIds = null;
8647
+ constructor(courseId, filter, user) {
8648
+ this.courseId = courseId;
8649
+ this.filter = filter;
8650
+ this.user = user;
8651
+ logger.info(
8652
+ `[TagFilteredContentSource] Created for course "${courseId}" with filter:`,
8653
+ JSON.stringify(filter)
8654
+ );
8655
+ }
8656
+ /**
8657
+ * Resolves the TagFilter to a set of eligible card IDs.
8658
+ *
8659
+ * - Cards in `include` tags are OR'd together (card needs at least one)
8660
+ * - Cards in `exclude` tags are removed from the result
8661
+ */
8662
+ async resolveFilteredCardIds() {
8663
+ if (this.resolvedCardIds !== null) {
8664
+ return this.resolvedCardIds;
8665
+ }
8666
+ const includedCardIds = /* @__PURE__ */ new Set();
8667
+ if (this.filter.include.length > 0) {
8668
+ for (const tagName of this.filter.include) {
8669
+ try {
8670
+ const tagDoc = await getTag(this.courseId, tagName);
8671
+ tagDoc.taggedCards.forEach((cardId) => includedCardIds.add(cardId));
8672
+ } catch (error) {
8673
+ logger.warn(
8674
+ `[TagFilteredContentSource] Could not resolve tag "${tagName}" for inclusion:`,
8675
+ error
8676
+ );
8677
+ }
8678
+ }
8679
+ }
8680
+ if (includedCardIds.size === 0 && this.filter.include.length > 0) {
8681
+ logger.warn(
8682
+ `[TagFilteredContentSource] No cards found for include tags: ${this.filter.include.join(", ")}`
8683
+ );
8684
+ this.resolvedCardIds = /* @__PURE__ */ new Set();
8685
+ return this.resolvedCardIds;
8686
+ }
8687
+ const excludedCardIds = /* @__PURE__ */ new Set();
8688
+ if (this.filter.exclude.length > 0) {
8689
+ for (const tagName of this.filter.exclude) {
8690
+ try {
8691
+ const tagDoc = await getTag(this.courseId, tagName);
8692
+ tagDoc.taggedCards.forEach((cardId) => excludedCardIds.add(cardId));
8693
+ } catch (error) {
8694
+ logger.warn(
8695
+ `[TagFilteredContentSource] Could not resolve tag "${tagName}" for exclusion:`,
8696
+ error
8697
+ );
8698
+ }
8699
+ }
8700
+ }
8701
+ const finalCardIds = /* @__PURE__ */ new Set();
8702
+ for (const cardId of includedCardIds) {
8703
+ if (!excludedCardIds.has(cardId)) {
8704
+ finalCardIds.add(cardId);
8705
+ }
8706
+ }
8707
+ logger.info(
8708
+ `[TagFilteredContentSource] Resolved ${finalCardIds.size} cards (included: ${includedCardIds.size}, excluded: ${excludedCardIds.size})`
8709
+ );
8710
+ this.resolvedCardIds = finalCardIds;
8711
+ return finalCardIds;
8712
+ }
8713
+ /**
8714
+ * Get cards with suitability scores for presentation.
8715
+ *
8716
+ * Filters cards by tag inclusion/exclusion and assigns score=1.0 to all.
8717
+ * TagFilteredContentSource does not currently support pluggable navigation
8718
+ * strategies - it returns flat-scored candidates.
8719
+ *
8720
+ * @param limit - Maximum number of cards to return
8721
+ * @returns Cards sorted by score descending (all scores = 1.0)
8722
+ */
8723
+ async getWeightedCards(limit) {
8724
+ if (!hasActiveFilter(this.filter)) {
8725
+ logger.warn("[TagFilteredContentSource] getWeightedCards called with no active filter");
8726
+ return { cards: [] };
8727
+ }
8728
+ const eligibleCardIds = await this.resolveFilteredCardIds();
8729
+ const activeCards = await this.user.getActiveCards();
8730
+ const activeCardIds = new Set(activeCards.map((c) => c.cardID));
8731
+ const newCardWeighted = [];
8732
+ for (const cardId of eligibleCardIds) {
8733
+ if (!activeCardIds.has(cardId)) {
8734
+ newCardWeighted.push({
8735
+ cardId,
8736
+ courseId: this.courseId,
8737
+ score: 1,
8738
+ provenance: [
8739
+ {
8740
+ strategy: "tagFilter",
8741
+ strategyName: "Tag Filter",
8742
+ strategyId: "TAG_FILTER",
8743
+ action: "generated",
8744
+ score: 1,
8745
+ reason: `Tag-filtered new card (tags: ${this.filter.include.join(", ")})`
8746
+ }
8747
+ ]
8748
+ });
8749
+ }
8750
+ if (newCardWeighted.length >= limit) {
8751
+ break;
8752
+ }
8753
+ }
8754
+ logger.info(
8755
+ `[TagFilteredContentSource] Found ${newCardWeighted.length} new cards matching filter`
8756
+ );
8757
+ const allReviews = await this.user.getPendingReviews(this.courseId);
8758
+ const filteredReviews = allReviews.filter((review) => eligibleCardIds.has(review.cardId));
8759
+ logger.info(
8760
+ `[TagFilteredContentSource] Found ${filteredReviews.length} pending reviews matching filter (of ${allReviews.length} total)`
8761
+ );
8762
+ const reviewWeighted = filteredReviews.map((r) => ({
8763
+ cardId: r.cardId,
8764
+ courseId: r.courseId,
8765
+ score: 1,
8766
+ reviewID: r._id,
8767
+ provenance: [
8768
+ {
8769
+ strategy: "tagFilter",
8770
+ strategyName: "Tag Filter",
8771
+ strategyId: "TAG_FILTER",
8772
+ action: "generated",
8773
+ score: 1,
8774
+ reason: `Tag-filtered review (tags: ${this.filter.include.join(", ")})`
8775
+ }
8776
+ ]
8777
+ }));
8778
+ return { cards: [...reviewWeighted, ...newCardWeighted].slice(0, limit) };
8779
+ }
8780
+ /**
8781
+ * Clears the cached resolved card IDs.
8782
+ * Call this if the underlying tag data may have changed during a session.
8783
+ */
8784
+ clearCache() {
8785
+ this.resolvedCardIds = null;
8786
+ }
8787
+ /**
8788
+ * Returns the course ID this source is filtering.
8789
+ */
8790
+ getCourseId() {
8791
+ return this.courseId;
8792
+ }
8793
+ /**
8794
+ * Returns the active tag filter.
8795
+ */
8796
+ getFilter() {
8797
+ return this.filter;
8798
+ }
8799
+ };
8800
+ }
8801
+ });
8802
+
8803
+ // src/study/index.ts
8804
+ var init_study = __esm({
8805
+ "src/study/index.ts"() {
8806
+ "use strict";
8807
+ init_SessionController();
8808
+ init_SourceMixer();
8809
+ init_SpacedRepetition();
8810
+ init_TagFilteredContentSource();
8811
+ init_MixerDebugger();
8812
+ init_SessionDebugger();
8813
+ init_SessionOverlay();
8814
+ }
8815
+ });
8816
+
8817
+ // src/impl/common/userDBHelpers.ts
8818
+ import moment6 from "moment";
8819
+ function makeScheduledCardId(reviewTime) {
8820
+ return DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */] + moment6.utc(reviewTime).format(REVIEW_TIME_FORMAT2);
8821
+ }
8822
+ function filterAllDocsByPrefix2(db, prefix, opts) {
8823
+ const options = {
8824
+ startkey: prefix,
8825
+ endkey: prefix + "\uFFF0",
8826
+ include_docs: true
8827
+ };
8828
+ if (opts) {
8829
+ Object.assign(options, opts);
8830
+ }
8831
+ return db.allDocs(options);
8832
+ }
8833
+ function getStartAndEndKeys2(key) {
8834
+ return {
8835
+ startkey: key,
8836
+ endkey: key + "\uFFF0"
8837
+ };
8838
+ }
8839
+ function getLocalUserDB(username) {
8840
+ const dbName = `userdb-${username}`;
8841
+ if (typeof window === "undefined") {
8842
+ return new pouchdb_setup_default(getDbPath(dbName), {});
8843
+ } else {
8844
+ return new pouchdb_setup_default(dbName, {});
8845
+ }
8846
+ }
8847
+ function scheduleCardReviewLocal(userDB, review) {
8848
+ const now = moment6.utc();
8849
+ logger.info(`Scheduling for review in: ${review.time.diff(now, "h") / 24} days`);
8850
+ void userDB.put({
8851
+ _id: makeScheduledCardId(review.time),
8852
+ cardId: review.card_id,
8853
+ reviewTime: review.time.toISOString(),
8854
+ courseId: review.course_id,
8855
+ scheduledAt: now.toISOString(),
8856
+ scheduledFor: review.scheduledFor,
8857
+ schedulingAgentId: review.schedulingAgentId
8858
+ });
8859
+ }
8860
+ async function removeScheduledCardReviewLocal(userDB, reviewDocID) {
8861
+ const reviewDoc = await userDB.get(reviewDocID);
8862
+ userDB.remove(reviewDoc).then((res) => {
8863
+ if (res.ok) {
8864
+ log2(`Removed Review Doc: ${reviewDocID}`);
8865
+ }
8866
+ }).catch((err) => {
8867
+ log2(`Failed to remove Review Doc: ${reviewDocID},
8868
+ ${JSON.stringify(err)}`);
8869
+ });
8870
+ }
8871
+ var REVIEW_TIME_FORMAT2, log2;
8872
+ var init_userDBHelpers = __esm({
8873
+ "src/impl/common/userDBHelpers.ts"() {
8874
+ "use strict";
8875
+ init_core();
8876
+ init_logger();
8877
+ init_pouchdb_setup();
8878
+ init_dataDirectory();
8879
+ REVIEW_TIME_FORMAT2 = "YYYY-MM-DD--kk:mm:ss-SSS";
8880
+ log2 = (s) => {
8881
+ logger.info(s);
8882
+ };
8883
+ }
8884
+ });
8885
+
8886
+ // src/impl/couch/user-course-relDB.ts
8887
+ import moment7 from "moment";
8888
+ var UsrCrsData;
8889
+ var init_user_course_relDB = __esm({
8890
+ "src/impl/couch/user-course-relDB.ts"() {
8891
+ "use strict";
8892
+ init_logger();
8893
+ UsrCrsData = class {
8894
+ user;
8895
+ _courseId;
8896
+ constructor(user, courseId) {
8897
+ this.user = user;
8898
+ this._courseId = courseId;
8899
+ }
8900
+ async getReviewsForcast(daysCount) {
8901
+ const time = moment7.utc().add(daysCount, "days");
8902
+ return this.getReviewstoDate(time);
8903
+ }
8904
+ async getPendingReviews() {
8905
+ const now = moment7.utc();
8906
+ return this.getReviewstoDate(now);
8907
+ }
8908
+ async getScheduledReviewCount() {
8909
+ return (await this.getPendingReviews()).length;
8910
+ }
8911
+ async getCourseSettings() {
8912
+ const regDoc = await this.user.getCourseRegistrationsDoc();
8913
+ const crsDoc = regDoc.courses.find((c) => c.courseID === this._courseId);
8914
+ if (crsDoc && crsDoc.settings) {
8915
+ return crsDoc.settings;
8916
+ } else {
8917
+ logger.warn(`no settings found during lookup on course ${this._courseId}`);
8918
+ return {};
8919
+ }
8920
+ }
8921
+ updateCourseSettings(updates) {
8922
+ if ("updateCourseSettings" in this.user) {
8923
+ void this.user.updateCourseSettings(this._courseId, updates);
8924
+ }
8925
+ }
8926
+ async getStrategyState(strategyKey) {
8927
+ return this.user.getStrategyState(this._courseId, strategyKey);
8928
+ }
8929
+ async putStrategyState(strategyKey, data) {
8930
+ return this.user.putStrategyState(this._courseId, strategyKey, data);
8931
+ }
8932
+ async deleteStrategyState(strategyKey) {
8933
+ return this.user.deleteStrategyState(this._courseId, strategyKey);
8934
+ }
8935
+ async getReviewstoDate(targetDate) {
8936
+ const allReviews = await this.user.getPendingReviews(this._courseId);
8937
+ logger.debug(
8938
+ `Fetching ${this.user.getUsername()}'s scheduled reviews for course ${this._courseId}.`
8939
+ );
8940
+ return allReviews.filter((review) => {
8941
+ const reviewTime = moment7.utc(review.reviewTime);
8942
+ return targetDate.isAfter(reviewTime);
8943
+ });
8944
+ }
8945
+ };
8946
+ }
8947
+ });
8948
+
8949
+ // src/impl/common/BaseUserDB.ts
8950
+ import { Status as Status3 } from "@vue-skuilder/common";
8951
+ import moment8 from "moment";
8952
+ function withTimeout(p, ms, label) {
8953
+ let timer;
8954
+ return Promise.race([
8955
+ p,
8956
+ new Promise((_resolve, reject) => {
8957
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
8958
+ })
8959
+ ]).finally(() => {
8960
+ if (timer !== void 0) {
8961
+ clearTimeout(timer);
8962
+ }
8963
+ });
8964
+ }
8965
+ async function getOrCreateClassroomRegistrationsDoc(user) {
8966
+ let ret;
8967
+ try {
8968
+ ret = await getLocalUserDB(user).get(userClassroomsDoc);
8969
+ } catch (e) {
8970
+ const err = e;
8971
+ if (err.status === 404) {
8972
+ await getLocalUserDB(user).put({
8973
+ _id: userClassroomsDoc,
8974
+ registrations: []
8975
+ });
8976
+ ret = await getOrCreateClassroomRegistrationsDoc(user);
8977
+ } else {
8978
+ const errorDetails = {
8979
+ name: err.name,
8980
+ status: err.status,
8981
+ message: err.message,
8982
+ reason: err.reason,
8983
+ error: err.error
8984
+ };
8985
+ logger.error(
8986
+ "Database error in getOrCreateClassroomRegistrationsDoc (standalone function):",
8987
+ errorDetails
8988
+ );
8989
+ throw new Error(
8990
+ `Database error accessing classroom registrations: ${err.message || err.name || "Unknown error"} (status: ${err.status})`
8991
+ );
8992
+ }
8993
+ }
8994
+ return ret;
8995
+ }
8996
+ async function getOrCreateCourseRegistrationsDoc(user) {
8997
+ let ret;
8998
+ try {
8999
+ ret = await getLocalUserDB(user).get(userCoursesDoc);
9000
+ } catch (e) {
9001
+ const err = e;
9002
+ if (err.status === 404) {
9003
+ await getLocalUserDB(user).put({
9004
+ _id: userCoursesDoc,
9005
+ courses: [],
9006
+ studyWeight: {}
9007
+ });
9008
+ ret = await getOrCreateCourseRegistrationsDoc(user);
9009
+ } else {
9010
+ throw new Error(
9011
+ `Unexpected error ${JSON.stringify(e)} in getOrCreateCourseRegistrationDoc...`
9012
+ );
9013
+ }
9014
+ }
9015
+ return ret;
9016
+ }
9017
+ async function updateUserElo(user, course_id, elo) {
9018
+ const regDoc = await getOrCreateCourseRegistrationsDoc(user);
9019
+ const course = regDoc.courses.find((c) => c.courseID === course_id);
9020
+ course.elo = elo;
9021
+ return getLocalUserDB(user).put(regDoc);
9022
+ }
9023
+ async function registerUserForClassroom(user, classID, registerAs) {
9024
+ log3(`Registering user: ${user} in course: ${classID}`);
9025
+ return getOrCreateClassroomRegistrationsDoc(user).then((doc) => {
9026
+ const regItem = {
9027
+ classID,
9028
+ registeredAs: registerAs
9029
+ };
9030
+ if (doc.registrations.filter((reg) => {
9031
+ return reg.classID === regItem.classID && reg.registeredAs === regItem.registeredAs;
9032
+ }).length === 0) {
9033
+ doc.registrations.push(regItem);
9034
+ } else {
9035
+ log3(`User ${user} is already registered for class ${classID}`);
9036
+ }
9037
+ return getLocalUserDB(user).put(doc);
9038
+ });
9039
+ }
9040
+ async function dropUserFromClassroom(user, classID) {
6865
9041
  return getOrCreateClassroomRegistrationsDoc(user).then((doc) => {
6866
9042
  let index = -1;
6867
9043
  for (let i = 0; i < doc.registrations.length; i++) {
@@ -6886,6 +9062,7 @@ var init_BaseUserDB = __esm({
6886
9062
  init_util();
6887
9063
  init_types_legacy();
6888
9064
  init_logger();
9065
+ init_study();
6889
9066
  init_userDBHelpers();
6890
9067
  init_updateQueue();
6891
9068
  init_user_course_relDB();
@@ -7121,7 +9298,7 @@ Currently logged-in as ${this._username}.`
7121
9298
  *
7122
9299
  */
7123
9300
  async getActiveCards() {
7124
- const keys = getStartAndEndKeys(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */]);
9301
+ const keys = getStartAndEndKeys2(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */]);
7125
9302
  const reviews = await this.remoteDB.allDocs({
7126
9303
  startkey: keys.startkey,
7127
9304
  endkey: keys.endkey,
@@ -7198,7 +9375,7 @@ Currently logged-in as ${this._username}.`
7198
9375
  }
7199
9376
  }
7200
9377
  async getReviewstoDate(targetDate, course_id) {
7201
- const keys = getStartAndEndKeys(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */]);
9378
+ const keys = getStartAndEndKeys2(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */]);
7202
9379
  const reviews = await this.remoteDB.allDocs({
7203
9380
  startkey: keys.startkey,
7204
9381
  endkey: keys.endkey,
@@ -7209,9 +9386,9 @@ Currently logged-in as ${this._username}.`
7209
9386
  );
7210
9387
  return reviews.rows.filter((r) => {
7211
9388
  if (r.id.startsWith(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */])) {
7212
- const date = moment6.utc(
9389
+ const date = moment8.utc(
7213
9390
  r.id.substr(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */].length),
7214
- REVIEW_TIME_FORMAT
9391
+ REVIEW_TIME_FORMAT2
7215
9392
  );
7216
9393
  if (targetDate.isAfter(date)) {
7217
9394
  if (course_id === void 0 || r.doc.courseId === course_id) {
@@ -7222,11 +9399,11 @@ Currently logged-in as ${this._username}.`
7222
9399
  }).map((r) => r.doc);
7223
9400
  }
7224
9401
  async getReviewsForcast(daysCount, course_id) {
7225
- const time = moment6.utc().add(daysCount, "days");
9402
+ const time = moment8.utc().add(daysCount, "days");
7226
9403
  return this.getReviewstoDate(time, course_id);
7227
9404
  }
7228
9405
  async getPendingReviews(course_id) {
7229
- const now = moment6.utc();
9406
+ const now = moment8.utc();
7230
9407
  return this.getReviewstoDate(now, course_id);
7231
9408
  }
7232
9409
  async getScheduledReviewCount(course_id) {
@@ -7602,15 +9779,20 @@ Currently logged-in as ${this._username}.`
7602
9779
  */
7603
9780
  async putCardRecord(record) {
7604
9781
  const cardHistoryID = getCardHistoryID(record.courseID, record.cardID);
7605
- record.timeStamp = moment6.utc(record.timeStamp).toString();
9782
+ record.timeStamp = moment8.utc(record.timeStamp).toString();
7606
9783
  try {
7607
9784
  const cardHistory = await this.update(
7608
9785
  cardHistoryID,
7609
9786
  function(h) {
7610
9787
  h.records.push(record);
7611
9788
  h.bestInterval = h.bestInterval || 0;
7612
- h.lapses = h.lapses || 0;
7613
- h.streak = h.streak || 0;
9789
+ if (areQuestionRecords(h)) {
9790
+ h.lapses = getLapses(h.records);
9791
+ h.streak = getStreak(h.records);
9792
+ } else {
9793
+ h.lapses = h.lapses || 0;
9794
+ h.streak = h.streak || 0;
9795
+ }
7614
9796
  return h;
7615
9797
  }
7616
9798
  );
@@ -7618,7 +9800,7 @@ Currently logged-in as ${this._username}.`
7618
9800
  const ret = {
7619
9801
  ...record2
7620
9802
  };
7621
- ret.timeStamp = moment6.utc(record2.timeStamp);
9803
+ ret.timeStamp = moment8.utc(record2.timeStamp);
7622
9804
  return ret;
7623
9805
  });
7624
9806
  return cardHistory;
@@ -7719,7 +9901,7 @@ Currently logged-in as ${this._username}.`
7719
9901
  if (course_id) {
7720
9902
  filterPrefix += `-${course_id}-`;
7721
9903
  }
7722
- const docs = await filterAllDocsByPrefix(this.localDB, filterPrefix, {
9904
+ const docs = await filterAllDocsByPrefix2(this.localDB, filterPrefix, {
7723
9905
  include_docs: false
7724
9906
  });
7725
9907
  const ret = [];
@@ -7735,7 +9917,7 @@ Currently logged-in as ${this._username}.`
7735
9917
  * @returns A promise of the cards that the user has seen in the past.
7736
9918
  */
7737
9919
  async getHistory() {
7738
- const cards = await filterAllDocsByPrefix(
9920
+ const cards = await filterAllDocsByPrefix2(
7739
9921
  this.remoteDB,
7740
9922
  DocTypePrefixes["CARDRECORD" /* CARDRECORD */],
7741
9923
  {
@@ -7902,7 +10084,7 @@ Currently logged-in as ${this._username}.`
7902
10084
  }
7903
10085
  async getStudySessions(courseId) {
7904
10086
  const prefix = courseId ? `${DocTypePrefixes["STUDY_SESSION" /* STUDY_SESSION */]}::${courseId}::` : `${DocTypePrefixes["STUDY_SESSION" /* STUDY_SESSION */]}::`;
7905
- const keys = getStartAndEndKeys(prefix);
10087
+ const keys = getStartAndEndKeys2(prefix);
7906
10088
  const res = await this.localDB.allDocs({
7907
10089
  startkey: keys.startkey,
7908
10090
  endkey: keys.endkey,
@@ -7976,176 +10158,6 @@ var init_factory = __esm({
7976
10158
  }
7977
10159
  });
7978
10160
 
7979
- // src/study/TagFilteredContentSource.ts
7980
- import { hasActiveFilter } from "@vue-skuilder/common";
7981
- var TagFilteredContentSource;
7982
- var init_TagFilteredContentSource = __esm({
7983
- "src/study/TagFilteredContentSource.ts"() {
7984
- "use strict";
7985
- init_courseDB();
7986
- init_logger();
7987
- TagFilteredContentSource = class {
7988
- courseId;
7989
- filter;
7990
- user;
7991
- // Cache resolved card IDs to avoid repeated lookups within a session
7992
- resolvedCardIds = null;
7993
- constructor(courseId, filter, user) {
7994
- this.courseId = courseId;
7995
- this.filter = filter;
7996
- this.user = user;
7997
- logger.info(
7998
- `[TagFilteredContentSource] Created for course "${courseId}" with filter:`,
7999
- JSON.stringify(filter)
8000
- );
8001
- }
8002
- /**
8003
- * Resolves the TagFilter to a set of eligible card IDs.
8004
- *
8005
- * - Cards in `include` tags are OR'd together (card needs at least one)
8006
- * - Cards in `exclude` tags are removed from the result
8007
- */
8008
- async resolveFilteredCardIds() {
8009
- if (this.resolvedCardIds !== null) {
8010
- return this.resolvedCardIds;
8011
- }
8012
- const includedCardIds = /* @__PURE__ */ new Set();
8013
- if (this.filter.include.length > 0) {
8014
- for (const tagName of this.filter.include) {
8015
- try {
8016
- const tagDoc = await getTag(this.courseId, tagName);
8017
- tagDoc.taggedCards.forEach((cardId) => includedCardIds.add(cardId));
8018
- } catch (error) {
8019
- logger.warn(
8020
- `[TagFilteredContentSource] Could not resolve tag "${tagName}" for inclusion:`,
8021
- error
8022
- );
8023
- }
8024
- }
8025
- }
8026
- if (includedCardIds.size === 0 && this.filter.include.length > 0) {
8027
- logger.warn(
8028
- `[TagFilteredContentSource] No cards found for include tags: ${this.filter.include.join(", ")}`
8029
- );
8030
- this.resolvedCardIds = /* @__PURE__ */ new Set();
8031
- return this.resolvedCardIds;
8032
- }
8033
- const excludedCardIds = /* @__PURE__ */ new Set();
8034
- if (this.filter.exclude.length > 0) {
8035
- for (const tagName of this.filter.exclude) {
8036
- try {
8037
- const tagDoc = await getTag(this.courseId, tagName);
8038
- tagDoc.taggedCards.forEach((cardId) => excludedCardIds.add(cardId));
8039
- } catch (error) {
8040
- logger.warn(
8041
- `[TagFilteredContentSource] Could not resolve tag "${tagName}" for exclusion:`,
8042
- error
8043
- );
8044
- }
8045
- }
8046
- }
8047
- const finalCardIds = /* @__PURE__ */ new Set();
8048
- for (const cardId of includedCardIds) {
8049
- if (!excludedCardIds.has(cardId)) {
8050
- finalCardIds.add(cardId);
8051
- }
8052
- }
8053
- logger.info(
8054
- `[TagFilteredContentSource] Resolved ${finalCardIds.size} cards (included: ${includedCardIds.size}, excluded: ${excludedCardIds.size})`
8055
- );
8056
- this.resolvedCardIds = finalCardIds;
8057
- return finalCardIds;
8058
- }
8059
- /**
8060
- * Get cards with suitability scores for presentation.
8061
- *
8062
- * Filters cards by tag inclusion/exclusion and assigns score=1.0 to all.
8063
- * TagFilteredContentSource does not currently support pluggable navigation
8064
- * strategies - it returns flat-scored candidates.
8065
- *
8066
- * @param limit - Maximum number of cards to return
8067
- * @returns Cards sorted by score descending (all scores = 1.0)
8068
- */
8069
- async getWeightedCards(limit) {
8070
- if (!hasActiveFilter(this.filter)) {
8071
- logger.warn("[TagFilteredContentSource] getWeightedCards called with no active filter");
8072
- return { cards: [] };
8073
- }
8074
- const eligibleCardIds = await this.resolveFilteredCardIds();
8075
- const activeCards = await this.user.getActiveCards();
8076
- const activeCardIds = new Set(activeCards.map((c) => c.cardID));
8077
- const newCardWeighted = [];
8078
- for (const cardId of eligibleCardIds) {
8079
- if (!activeCardIds.has(cardId)) {
8080
- newCardWeighted.push({
8081
- cardId,
8082
- courseId: this.courseId,
8083
- score: 1,
8084
- provenance: [
8085
- {
8086
- strategy: "tagFilter",
8087
- strategyName: "Tag Filter",
8088
- strategyId: "TAG_FILTER",
8089
- action: "generated",
8090
- score: 1,
8091
- reason: `Tag-filtered new card (tags: ${this.filter.include.join(", ")})`
8092
- }
8093
- ]
8094
- });
8095
- }
8096
- if (newCardWeighted.length >= limit) {
8097
- break;
8098
- }
8099
- }
8100
- logger.info(
8101
- `[TagFilteredContentSource] Found ${newCardWeighted.length} new cards matching filter`
8102
- );
8103
- const allReviews = await this.user.getPendingReviews(this.courseId);
8104
- const filteredReviews = allReviews.filter((review) => eligibleCardIds.has(review.cardId));
8105
- logger.info(
8106
- `[TagFilteredContentSource] Found ${filteredReviews.length} pending reviews matching filter (of ${allReviews.length} total)`
8107
- );
8108
- const reviewWeighted = filteredReviews.map((r) => ({
8109
- cardId: r.cardId,
8110
- courseId: r.courseId,
8111
- score: 1,
8112
- reviewID: r._id,
8113
- provenance: [
8114
- {
8115
- strategy: "tagFilter",
8116
- strategyName: "Tag Filter",
8117
- strategyId: "TAG_FILTER",
8118
- action: "generated",
8119
- score: 1,
8120
- reason: `Tag-filtered review (tags: ${this.filter.include.join(", ")})`
8121
- }
8122
- ]
8123
- }));
8124
- return { cards: [...reviewWeighted, ...newCardWeighted].slice(0, limit) };
8125
- }
8126
- /**
8127
- * Clears the cached resolved card IDs.
8128
- * Call this if the underlying tag data may have changed during a session.
8129
- */
8130
- clearCache() {
8131
- this.resolvedCardIds = null;
8132
- }
8133
- /**
8134
- * Returns the course ID this source is filtering.
8135
- */
8136
- getCourseId() {
8137
- return this.courseId;
8138
- }
8139
- /**
8140
- * Returns the active tag filter.
8141
- */
8142
- getFilter() {
8143
- return this.filter;
8144
- }
8145
- };
8146
- }
8147
- });
8148
-
8149
10161
  // src/core/interfaces/contentSource.ts
8150
10162
  import { hasActiveFilter as hasActiveFilter2 } from "@vue-skuilder/common";
8151
10163
  function isReview(item) {
@@ -8229,20 +10241,6 @@ var init_userOutcome = __esm({
8229
10241
  }
8230
10242
  });
8231
10243
 
8232
- // src/core/types/studySession.ts
8233
- function makeStudySessionId(courseId, userId, sessionId) {
8234
- return `${DocTypePrefixes["STUDY_SESSION" /* STUDY_SESSION */]}::${courseId}::${userId}::${sessionId}`;
8235
- }
8236
- function newSessionId() {
8237
- return `session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
8238
- }
8239
- var init_studySession = __esm({
8240
- "src/core/types/studySession.ts"() {
8241
- "use strict";
8242
- init_types_legacy();
8243
- }
8244
- });
8245
-
8246
10244
  // src/core/types/hydration.ts
8247
10245
  var HYDRATION_MARKER_ID;
8248
10246
  var init_hydration = __esm({
@@ -8373,7 +10371,7 @@ var init_cardProcessor = __esm({
8373
10371
  });
8374
10372
 
8375
10373
  // src/core/bulkImport/types.ts
8376
- var init_types3 = __esm({
10374
+ var init_types5 = __esm({
8377
10375
  "src/core/bulkImport/types.ts"() {
8378
10376
  "use strict";
8379
10377
  }
@@ -8384,7 +10382,7 @@ var init_bulkImport = __esm({
8384
10382
  "src/core/bulkImport/index.ts"() {
8385
10383
  "use strict";
8386
10384
  init_cardProcessor();
8387
- init_types3();
10385
+ init_types5();
8388
10386
  }
8389
10387
  });
8390
10388
 
@@ -8523,7 +10521,7 @@ var init_UserDBDebugger = __esm({
8523
10521
  const rawDB = getRawDB();
8524
10522
  if (!rawDB) return;
8525
10523
  try {
8526
- const result = await filterAllDocsByPrefix(rawDB, DocTypePrefixes["CARDRECORD" /* CARDRECORD */]);
10524
+ const result = await filterAllDocsByPrefix2(rawDB, DocTypePrefixes["CARDRECORD" /* CARDRECORD */]);
8527
10525
  const cardHistories = result.rows.filter((row) => row.doc && row.doc.cardID === cardId).map((row) => row.doc);
8528
10526
  console.group(`\u{1F3B4} Card History: ${cardId}`);
8529
10527
  logger.info(`Total interactions: ${cardHistories.length}`);
@@ -8560,7 +10558,7 @@ var init_UserDBDebugger = __esm({
8560
10558
  logger.info(`Unknown document type: ${docType}`);
8561
10559
  return;
8562
10560
  }
8563
- const result = await filterAllDocsByPrefix(rawDB, prefix);
10561
+ const result = await filterAllDocsByPrefix2(rawDB, prefix);
8564
10562
  console.group(`\u{1F4C4} Documents: ${docType}`);
8565
10563
  logger.info(`Total: ${result.rows.length}`);
8566
10564
  logger.info(`Prefix: ${prefix}`);