@vue-skuilder/db 0.2.23 → 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 (37) hide show
  1. package/dist/{contentSource-DT9NaX69.d.cts → contentSource-CrRnbjBx.d.cts} +63 -2
  2. package/dist/{contentSource-BvOpKUeU.d.ts → contentSource-kD35o65m.d.ts} +63 -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-CY2B2lyW.d.ts → dataLayerProvider-CtzddVdy.d.ts} +1 -1
  10. package/dist/{dataLayerProvider-wY6s_4x9.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 +32 -7
  24. package/dist/index.d.ts +32 -7
  25. package/dist/index.js +8194 -7868
  26. package/dist/index.js.map +1 -1
  27. package/dist/index.mjs +8059 -7734
  28. package/dist/index.mjs.map +1 -1
  29. package/package.json +3 -3
  30. package/src/core/types/studySession.ts +42 -0
  31. package/src/impl/common/BaseUserDB.ts +13 -4
  32. package/src/study/SessionController.ts +24 -1
  33. package/src/study/SpacedRepetition.ts +11 -2
  34. package/src/study/services/EloService.ts +97 -5
  35. package/src/study/services/ResponseProcessor.ts +79 -27
  36. package/src/study/services/tagRecent.test.ts +101 -0
  37. package/src/study/services/tagRecent.ts +70 -0
@@ -124,6 +124,12 @@ var init_types_legacy = __esm({
124
124
  });
125
125
 
126
126
  // src/core/util/index.ts
127
+ function areQuestionRecords(h) {
128
+ return isQuestionRecord(h.records[0]);
129
+ }
130
+ function isQuestionRecord(c) {
131
+ return c.userAnswer !== void 0;
132
+ }
127
133
  function getCardHistoryID(courseID, cardID) {
128
134
  return `${DocTypePrefixes["CARDRECORD" /* CARDRECORD */]}-${courseID}-${cardID}`;
129
135
  }
@@ -156,96 +162,6 @@ var init_pouchdb_setup = __esm({
156
162
  }
157
163
  });
158
164
 
159
- // src/util/dataDirectory.ts
160
- import * as path from "path";
161
- import * as os from "os";
162
- function getAppDataDirectory() {
163
- if (ENV.LOCAL_STORAGE_PREFIX) {
164
- return path.join(os.homedir(), `.tuilder`, ENV.LOCAL_STORAGE_PREFIX);
165
- } else {
166
- return path.join(os.homedir(), ".tuilder");
167
- }
168
- }
169
- function getDbPath(dbName) {
170
- return path.join(getAppDataDirectory(), dbName);
171
- }
172
- var init_dataDirectory = __esm({
173
- "src/util/dataDirectory.ts"() {
174
- "use strict";
175
- init_logger();
176
- init_factory();
177
- }
178
- });
179
-
180
- // src/impl/common/userDBHelpers.ts
181
- import moment from "moment";
182
- function makeScheduledCardId(reviewTime) {
183
- return DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */] + moment.utc(reviewTime).format(REVIEW_TIME_FORMAT);
184
- }
185
- function filterAllDocsByPrefix(db, prefix, opts) {
186
- const options = {
187
- startkey: prefix,
188
- endkey: prefix + "\uFFF0",
189
- include_docs: true
190
- };
191
- if (opts) {
192
- Object.assign(options, opts);
193
- }
194
- return db.allDocs(options);
195
- }
196
- function getStartAndEndKeys(key) {
197
- return {
198
- startkey: key,
199
- endkey: key + "\uFFF0"
200
- };
201
- }
202
- function getLocalUserDB(username) {
203
- const dbName = `userdb-${username}`;
204
- if (typeof window === "undefined") {
205
- return new pouchdb_setup_default(getDbPath(dbName), {});
206
- } else {
207
- return new pouchdb_setup_default(dbName, {});
208
- }
209
- }
210
- function scheduleCardReviewLocal(userDB, review) {
211
- const now = moment.utc();
212
- logger.info(`Scheduling for review in: ${review.time.diff(now, "h") / 24} days`);
213
- void userDB.put({
214
- _id: makeScheduledCardId(review.time),
215
- cardId: review.card_id,
216
- reviewTime: review.time.toISOString(),
217
- courseId: review.course_id,
218
- scheduledAt: now.toISOString(),
219
- scheduledFor: review.scheduledFor,
220
- schedulingAgentId: review.schedulingAgentId
221
- });
222
- }
223
- async function removeScheduledCardReviewLocal(userDB, reviewDocID) {
224
- const reviewDoc = await userDB.get(reviewDocID);
225
- userDB.remove(reviewDoc).then((res) => {
226
- if (res.ok) {
227
- log(`Removed Review Doc: ${reviewDocID}`);
228
- }
229
- }).catch((err) => {
230
- log(`Failed to remove Review Doc: ${reviewDocID},
231
- ${JSON.stringify(err)}`);
232
- });
233
- }
234
- var REVIEW_TIME_FORMAT, log;
235
- var init_userDBHelpers = __esm({
236
- "src/impl/common/userDBHelpers.ts"() {
237
- "use strict";
238
- init_core();
239
- init_logger();
240
- init_pouchdb_setup();
241
- init_dataDirectory();
242
- REVIEW_TIME_FORMAT = "YYYY-MM-DD--kk:mm:ss-SSS";
243
- log = (s) => {
244
- logger.info(s);
245
- };
246
- }
247
- });
248
-
249
165
  // src/util/Loggable.ts
250
166
  var Loggable;
251
167
  var init_Loggable = __esm({
@@ -385,69 +301,6 @@ var init_updateQueue = __esm({
385
301
  }
386
302
  });
387
303
 
388
- // src/impl/couch/user-course-relDB.ts
389
- import moment2 from "moment";
390
- var UsrCrsData;
391
- var init_user_course_relDB = __esm({
392
- "src/impl/couch/user-course-relDB.ts"() {
393
- "use strict";
394
- init_logger();
395
- UsrCrsData = class {
396
- user;
397
- _courseId;
398
- constructor(user, courseId) {
399
- this.user = user;
400
- this._courseId = courseId;
401
- }
402
- async getReviewsForcast(daysCount) {
403
- const time = moment2.utc().add(daysCount, "days");
404
- return this.getReviewstoDate(time);
405
- }
406
- async getPendingReviews() {
407
- const now = moment2.utc();
408
- return this.getReviewstoDate(now);
409
- }
410
- async getScheduledReviewCount() {
411
- return (await this.getPendingReviews()).length;
412
- }
413
- async getCourseSettings() {
414
- const regDoc = await this.user.getCourseRegistrationsDoc();
415
- const crsDoc = regDoc.courses.find((c) => c.courseID === this._courseId);
416
- if (crsDoc && crsDoc.settings) {
417
- return crsDoc.settings;
418
- } else {
419
- logger.warn(`no settings found during lookup on course ${this._courseId}`);
420
- return {};
421
- }
422
- }
423
- updateCourseSettings(updates) {
424
- if ("updateCourseSettings" in this.user) {
425
- void this.user.updateCourseSettings(this._courseId, updates);
426
- }
427
- }
428
- async getStrategyState(strategyKey) {
429
- return this.user.getStrategyState(this._courseId, strategyKey);
430
- }
431
- async putStrategyState(strategyKey, data) {
432
- return this.user.putStrategyState(this._courseId, strategyKey, data);
433
- }
434
- async deleteStrategyState(strategyKey) {
435
- return this.user.deleteStrategyState(this._courseId, strategyKey);
436
- }
437
- async getReviewstoDate(targetDate) {
438
- const allReviews = await this.user.getPendingReviews(this._courseId);
439
- logger.debug(
440
- `Fetching ${this.user.getUsername()}'s scheduled reviews for course ${this._courseId}.`
441
- );
442
- return allReviews.filter((review) => {
443
- const reviewTime = moment2.utc(review.reviewTime);
444
- return targetDate.isAfter(reviewTime);
445
- });
446
- }
447
- };
448
- }
449
- });
450
-
451
304
  // src/impl/couch/clientCache.ts
452
305
  var init_clientCache = __esm({
453
306
  "src/impl/couch/clientCache.ts"() {
@@ -2663,7 +2516,7 @@ var srs_exports = {};
2663
2516
  __export(srs_exports, {
2664
2517
  default: () => SRSNavigator
2665
2518
  });
2666
- import moment3 from "moment";
2519
+ import moment from "moment";
2667
2520
  var DEFAULT_HEALTHY_BACKLOG, BACKLOG_GROWTH_RATE, SRSNavigator;
2668
2521
  var init_srs = __esm({
2669
2522
  "src/core/navigators/generators/srs.ts"() {
@@ -2718,8 +2571,8 @@ var init_srs = __esm({
2718
2571
  }
2719
2572
  const courseId = this.course.getCourseID();
2720
2573
  const reviews = await this.user.getPendingReviews(courseId);
2721
- const now = moment3.utc();
2722
- let dueReviews = reviews.filter((r) => now.isAfter(moment3.utc(r.reviewTime)));
2574
+ const now = moment.utc();
2575
+ let dueReviews = reviews.filter((r) => now.isAfter(moment.utc(r.reviewTime)));
2723
2576
  if (dueReviews.length > 0) {
2724
2577
  const dueCardIds = [...new Set(dueReviews.map((r) => r.cardId))];
2725
2578
  const tagsByCard = await this.course.getAppliedTagsBatch(dueCardIds);
@@ -2740,13 +2593,13 @@ var init_srs = __esm({
2740
2593
  }
2741
2594
  }
2742
2595
  const backlogMultiplier = this.computeBacklogMultiplier(dueReviews.length);
2743
- const notDue = reviews.filter((r) => !now.isAfter(moment3.utc(r.reviewTime)));
2596
+ const notDue = reviews.filter((r) => !now.isAfter(moment.utc(r.reviewTime)));
2744
2597
  let nextDueIn = null;
2745
2598
  if (notDue.length > 0) {
2746
2599
  const next = notDue.reduce(
2747
- (a, b) => moment3.utc(a.reviewTime).isBefore(moment3.utc(b.reviewTime)) ? a : b
2600
+ (a, b) => moment.utc(a.reviewTime).isBefore(moment.utc(b.reviewTime)) ? a : b
2748
2601
  );
2749
- const until = moment3.duration(moment3.utc(next.reviewTime).diff(now));
2602
+ const until = moment.duration(moment.utc(next.reviewTime).diff(now));
2750
2603
  nextDueIn = until.asHours() < 1 ? `${Math.round(until.asMinutes())}m` : until.asHours() < 24 ? `${Math.round(until.asHours())}h` : `${Math.round(until.asDays())}d`;
2751
2604
  }
2752
2605
  if (dueReviews.length > 0) {
@@ -2756,11 +2609,11 @@ var init_srs = __esm({
2756
2609
  );
2757
2610
  } else if (reviews.length > 0) {
2758
2611
  const sortedByDue = [...reviews].sort(
2759
- (a, b) => moment3.utc(a.reviewTime).diff(moment3.utc(b.reviewTime))
2612
+ (a, b) => moment.utc(a.reviewTime).diff(moment.utc(b.reviewTime))
2760
2613
  );
2761
2614
  const nextDue = sortedByDue[0];
2762
- const nextDueTime = moment3.utc(nextDue.reviewTime);
2763
- const untilDue = moment3.duration(nextDueTime.diff(now));
2615
+ const nextDueTime = moment.utc(nextDue.reviewTime);
2616
+ const untilDue = moment.duration(nextDueTime.diff(now));
2764
2617
  const untilDueStr = untilDue.asHours() < 1 ? `${Math.round(untilDue.asMinutes())}m` : untilDue.asHours() < 24 ? `${Math.round(untilDue.asHours())}h` : `${Math.round(untilDue.asDays())}d`;
2765
2618
  logger.info(
2766
2619
  `[SRS] Course ${courseId}: 0 reviews due now (${reviews.length} scheduled, next in ${untilDueStr})`
@@ -2856,8 +2709,8 @@ var init_srs = __esm({
2856
2709
  * @param backlogMultiplier - Pre-computed backlog multiplier (>= 1.0, unbounded)
2857
2710
  */
2858
2711
  computeUrgencyScore(review, now, backlogMultiplier) {
2859
- const scheduledAt = moment3.utc(review.scheduledAt);
2860
- const due = moment3.utc(review.reviewTime);
2712
+ const scheduledAt = moment.utc(review.scheduledAt);
2713
+ const due = moment.utc(review.reviewTime);
2861
2714
  const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
2862
2715
  const hoursOverdue = now.diff(due, "hours");
2863
2716
  const relativeOverdue = hoursOverdue / intervalHours;
@@ -5278,7 +5131,7 @@ var init_courseDB = __esm({
5278
5131
  });
5279
5132
 
5280
5133
  // src/impl/couch/classroomDB.ts
5281
- import moment4 from "moment";
5134
+ import moment2 from "moment";
5282
5135
  var init_classroomDB2 = __esm({
5283
5136
  "src/impl/couch/classroomDB.ts"() {
5284
5137
  "use strict";
@@ -5340,7 +5193,7 @@ var init_CouchDBSyncStrategy = __esm({
5340
5193
 
5341
5194
  // src/impl/couch/index.ts
5342
5195
  import fetch3 from "cross-fetch";
5343
- import moment5 from "moment";
5196
+ import moment3 from "moment";
5344
5197
  import process2 from "process";
5345
5198
  function createPouchDBConfig() {
5346
5199
  const hasExplicitCredentials = ENV.COUCHDB_USERNAME && ENV.COUCHDB_PASSWORD;
@@ -5391,104 +5244,2267 @@ var init_couch = __esm({
5391
5244
  }
5392
5245
  });
5393
5246
 
5394
- // src/impl/common/BaseUserDB.ts
5395
- import { Status as Status3 } from "@vue-skuilder/common";
5396
- import moment6 from "moment";
5397
- function withTimeout(p, ms, label) {
5398
- let timer;
5399
- return Promise.race([
5400
- p,
5401
- new Promise((_resolve, reject) => {
5402
- timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
5403
- })
5404
- ]).finally(() => {
5405
- if (timer !== void 0) {
5406
- clearTimeout(timer);
5407
- }
5408
- });
5409
- }
5410
- function accomodateGuest() {
5411
- logger.log("[funnel] accomodateGuest() called");
5412
- if (typeof localStorage === "undefined") {
5413
- logger.log(
5414
- "[funnel] localStorage not available (Node.js environment), returning default guest"
5415
- );
5416
- return {
5417
- username: GuestUsername + "nodejs-test",
5418
- firstVisit: true
5419
- };
5247
+ // src/study/SpacedRepetition.ts
5248
+ import moment4 from "moment";
5249
+ import { isTaggedPerformance } from "@vue-skuilder/common";
5250
+ function getStreak(records) {
5251
+ let streak = 0;
5252
+ let index = records.length - 1;
5253
+ while (index >= 0 && records[index].isCorrect) {
5254
+ index--;
5255
+ streak++;
5420
5256
  }
5421
- const dbUUID = "sk-guest-uuid";
5422
- let firstVisit;
5423
- const existingUUID = localStorage.getItem(dbUUID);
5424
- logger.log("[funnel] Checking localStorage for key:", dbUUID);
5425
- logger.log("[funnel] Existing UUID value:", existingUUID);
5426
- logger.log("[funnel] existingUUID !== null:", existingUUID !== null);
5427
- if (existingUUID !== null) {
5428
- firstVisit = false;
5429
- logger.log(`[funnel] Returning guest ${existingUUID} "logging in".`);
5430
- } else {
5431
- firstVisit = true;
5432
- logger.log("[funnel] No existing UUID, generating new one...");
5433
- const uuid = generateUUID();
5434
- logger.log("[funnel] Generated UUID:", uuid);
5435
- logger.log("[funnel] UUID length:", uuid.length);
5436
- try {
5437
- localStorage.setItem(dbUUID, uuid);
5438
- logger.log("[funnel] Successfully stored UUID in localStorage");
5439
- const verification = localStorage.getItem(dbUUID);
5440
- logger.log("[funnel] Verification read from localStorage:", verification);
5441
- } catch (e) {
5442
- logger.error("[funnel] ERROR storing UUID:", e);
5443
- }
5444
- logger.log(`[funnel] Accommodating a new guest with account: ${uuid}`);
5257
+ return streak;
5258
+ }
5259
+ function getLapses(records) {
5260
+ return records.filter((r) => r.isCorrect === false).length;
5261
+ }
5262
+ var duration;
5263
+ var init_SpacedRepetition = __esm({
5264
+ "src/study/SpacedRepetition.ts"() {
5265
+ "use strict";
5266
+ init_util();
5267
+ init_logger();
5268
+ duration = moment4.duration;
5445
5269
  }
5446
- const finalUUID = localStorage.getItem(dbUUID);
5447
- const finalUsername = GuestUsername + finalUUID;
5448
- logger.log("[funnel] Final UUID from localStorage:", finalUUID);
5449
- logger.log("[funnel] GuestUsername constant:", GuestUsername);
5450
- logger.log("[funnel] Final username to return:", finalUsername);
5451
- return {
5452
- username: finalUsername,
5453
- firstVisit
5454
- };
5455
- function generateUUID() {
5456
- logger.log("[funnel] Inside generateUUID()");
5457
- if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
5458
- const uuid2 = crypto.randomUUID();
5459
- logger.log("[funnel] Generated UUID using crypto.randomUUID():", uuid2);
5460
- return uuid2;
5461
- }
5462
- if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
5463
- const bytes = new Uint8Array(16);
5464
- crypto.getRandomValues(bytes);
5465
- bytes[6] = bytes[6] & 15 | 64;
5466
- bytes[8] = bytes[8] & 63 | 128;
5467
- const uuid2 = [
5468
- Array.from(bytes.slice(0, 4)).map((b) => b.toString(16).padStart(2, "0")).join(""),
5469
- Array.from(bytes.slice(4, 6)).map((b) => b.toString(16).padStart(2, "0")).join(""),
5470
- Array.from(bytes.slice(6, 8)).map((b) => b.toString(16).padStart(2, "0")).join(""),
5471
- Array.from(bytes.slice(8, 10)).map((b) => b.toString(16).padStart(2, "0")).join(""),
5472
- Array.from(bytes.slice(10, 16)).map((b) => b.toString(16).padStart(2, "0")).join("")
5473
- ].join("-");
5474
- logger.log("[funnel] Generated UUID using crypto.getRandomValues():", uuid2);
5475
- return uuid2;
5476
- }
5477
- logger.warn("[funnel] crypto API not available, using timestamp-based UUID (NOT SECURE)");
5478
- let d = (/* @__PURE__ */ new Date()).getTime();
5479
- if (typeof performance !== "undefined" && typeof performance.now === "function") {
5480
- d += performance.now();
5481
- }
5482
- const uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
5483
- const r = (d + Math.random() * 16) % 16 | 0;
5484
- d = Math.floor(d / 16);
5485
- return (c === "x" ? r : r & 3 | 8).toString(16);
5486
- });
5487
- logger.log("[funnel] Generated UUID (fallback):", uuid);
5488
- return uuid;
5270
+ });
5271
+
5272
+ // src/study/services/SrsService.ts
5273
+ import moment5 from "moment";
5274
+ var init_SrsService = __esm({
5275
+ "src/study/services/SrsService.ts"() {
5276
+ "use strict";
5277
+ init_couch();
5278
+ init_SpacedRepetition();
5279
+ init_logger();
5489
5280
  }
5490
- }
5491
- async function getOrCreateClassroomRegistrationsDoc(user) {
5281
+ });
5282
+
5283
+ // src/study/services/tagRecent.ts
5284
+ import {
5285
+ pushTagPresentation
5286
+ } from "@vue-skuilder/common";
5287
+ var init_tagRecent = __esm({
5288
+ "src/study/services/tagRecent.ts"() {
5289
+ "use strict";
5290
+ }
5291
+ });
5292
+
5293
+ // src/study/services/EloService.ts
5294
+ import {
5295
+ adjustCourseScores,
5296
+ adjustCourseScoresPerTag,
5297
+ toCourseElo as toCourseElo7
5298
+ } from "@vue-skuilder/common";
5299
+ var init_EloService = __esm({
5300
+ "src/study/services/EloService.ts"() {
5301
+ "use strict";
5302
+ init_logger();
5303
+ init_tagRecent();
5304
+ }
5305
+ });
5306
+
5307
+ // src/study/services/ResponseProcessor.ts
5308
+ import { isTaggedPerformance as isTaggedPerformance2 } from "@vue-skuilder/common";
5309
+ var init_ResponseProcessor = __esm({
5310
+ "src/study/services/ResponseProcessor.ts"() {
5311
+ "use strict";
5312
+ init_core();
5313
+ init_logger();
5314
+ }
5315
+ });
5316
+
5317
+ // src/study/services/CardHydrationService.ts
5318
+ import {
5319
+ displayableDataToViewData,
5320
+ isCourseElo,
5321
+ toCourseElo as toCourseElo8
5322
+ } from "@vue-skuilder/common";
5323
+ var init_CardHydrationService = __esm({
5324
+ "src/study/services/CardHydrationService.ts"() {
5325
+ "use strict";
5326
+ init_logger();
5327
+ }
5328
+ });
5329
+
5330
+ // src/study/ItemQueue.ts
5331
+ var init_ItemQueue = __esm({
5332
+ "src/study/ItemQueue.ts"() {
5333
+ "use strict";
5334
+ }
5335
+ });
5336
+
5337
+ // src/core/types/studySession.ts
5338
+ var init_studySession = __esm({
5339
+ "src/core/types/studySession.ts"() {
5340
+ "use strict";
5341
+ init_types_legacy();
5342
+ }
5343
+ });
5344
+
5345
+ // src/util/packer/types.ts
5346
+ var init_types3 = __esm({
5347
+ "src/util/packer/types.ts"() {
5348
+ "use strict";
5349
+ }
5350
+ });
5351
+
5352
+ // src/util/packer/CouchDBToStaticPacker.ts
5353
+ var init_CouchDBToStaticPacker = __esm({
5354
+ "src/util/packer/CouchDBToStaticPacker.ts"() {
5355
+ "use strict";
5356
+ init_types_legacy();
5357
+ init_logger();
5358
+ }
5359
+ });
5360
+
5361
+ // src/util/packer/index.ts
5362
+ var init_packer = __esm({
5363
+ "src/util/packer/index.ts"() {
5364
+ "use strict";
5365
+ init_types3();
5366
+ init_CouchDBToStaticPacker();
5367
+ }
5368
+ });
5369
+
5370
+ // src/util/migrator/types.ts
5371
+ var DEFAULT_MIGRATION_OPTIONS;
5372
+ var init_types4 = __esm({
5373
+ "src/util/migrator/types.ts"() {
5374
+ "use strict";
5375
+ DEFAULT_MIGRATION_OPTIONS = {
5376
+ chunkBatchSize: 100,
5377
+ validateRoundTrip: false,
5378
+ cleanupOnFailure: true,
5379
+ timeout: 3e5
5380
+ // 5 minutes
5381
+ };
5382
+ }
5383
+ });
5384
+
5385
+ // src/util/migrator/FileSystemAdapter.ts
5386
+ var FileSystemError;
5387
+ var init_FileSystemAdapter = __esm({
5388
+ "src/util/migrator/FileSystemAdapter.ts"() {
5389
+ "use strict";
5390
+ FileSystemError = class extends Error {
5391
+ constructor(message, operation, filePath, cause) {
5392
+ super(message);
5393
+ this.operation = operation;
5394
+ this.filePath = filePath;
5395
+ this.cause = cause;
5396
+ this.name = "FileSystemError";
5397
+ }
5398
+ };
5399
+ }
5400
+ });
5401
+
5402
+ // src/util/migrator/validation.ts
5403
+ async function validateStaticCourse(staticPath, fs) {
5404
+ const validation = {
5405
+ valid: true,
5406
+ manifestExists: false,
5407
+ chunksExist: false,
5408
+ attachmentsExist: false,
5409
+ errors: [],
5410
+ warnings: []
5411
+ };
5412
+ try {
5413
+ if (fs) {
5414
+ const stats = await fs.stat(staticPath);
5415
+ if (!stats.isDirectory()) {
5416
+ validation.errors.push(`Path is not a directory: ${staticPath}`);
5417
+ validation.valid = false;
5418
+ return validation;
5419
+ }
5420
+ } else if (!nodeFS) {
5421
+ validation.errors.push("File system access not available - validation skipped");
5422
+ validation.valid = false;
5423
+ return validation;
5424
+ } else {
5425
+ const stats = await nodeFS.promises.stat(staticPath);
5426
+ if (!stats.isDirectory()) {
5427
+ validation.errors.push(`Path is not a directory: ${staticPath}`);
5428
+ validation.valid = false;
5429
+ return validation;
5430
+ }
5431
+ }
5432
+ let manifestPath = `${staticPath}/manifest.json`;
5433
+ try {
5434
+ if (fs) {
5435
+ manifestPath = fs.joinPath(staticPath, "manifest.json");
5436
+ if (await fs.exists(manifestPath)) {
5437
+ validation.manifestExists = true;
5438
+ const manifestContent = await fs.readFile(manifestPath);
5439
+ const manifest = JSON.parse(manifestContent);
5440
+ validation.courseId = manifest.courseId;
5441
+ validation.courseName = manifest.courseName;
5442
+ if (!manifest.version || !manifest.courseId || !manifest.chunks || !Array.isArray(manifest.chunks)) {
5443
+ validation.errors.push("Invalid manifest structure");
5444
+ validation.valid = false;
5445
+ }
5446
+ } else {
5447
+ validation.errors.push(`Manifest not found: ${manifestPath}`);
5448
+ validation.valid = false;
5449
+ }
5450
+ } else {
5451
+ manifestPath = `${staticPath}/manifest.json`;
5452
+ await nodeFS.promises.access(manifestPath);
5453
+ validation.manifestExists = true;
5454
+ const manifestContent = await nodeFS.promises.readFile(manifestPath, "utf8");
5455
+ const manifest = JSON.parse(manifestContent);
5456
+ validation.courseId = manifest.courseId;
5457
+ validation.courseName = manifest.courseName;
5458
+ if (!manifest.version || !manifest.courseId || !manifest.chunks || !Array.isArray(manifest.chunks)) {
5459
+ validation.errors.push("Invalid manifest structure");
5460
+ validation.valid = false;
5461
+ }
5462
+ }
5463
+ } catch (error) {
5464
+ const errorMessage = error instanceof FileSystemError ? error.message : `Manifest not found or invalid: ${manifestPath}`;
5465
+ validation.errors.push(errorMessage);
5466
+ validation.valid = false;
5467
+ }
5468
+ let chunksPath = `${staticPath}/chunks`;
5469
+ try {
5470
+ if (fs) {
5471
+ chunksPath = fs.joinPath(staticPath, "chunks");
5472
+ if (await fs.exists(chunksPath)) {
5473
+ const chunksStats = await fs.stat(chunksPath);
5474
+ if (chunksStats.isDirectory()) {
5475
+ validation.chunksExist = true;
5476
+ } else {
5477
+ validation.errors.push(`Chunks path is not a directory: ${chunksPath}`);
5478
+ validation.valid = false;
5479
+ }
5480
+ } else {
5481
+ validation.errors.push(`Chunks directory not found: ${chunksPath}`);
5482
+ validation.valid = false;
5483
+ }
5484
+ } else {
5485
+ chunksPath = `${staticPath}/chunks`;
5486
+ const chunksStats = await nodeFS.promises.stat(chunksPath);
5487
+ if (chunksStats.isDirectory()) {
5488
+ validation.chunksExist = true;
5489
+ } else {
5490
+ validation.errors.push(`Chunks path is not a directory: ${chunksPath}`);
5491
+ validation.valid = false;
5492
+ }
5493
+ }
5494
+ } catch (error) {
5495
+ const errorMessage = error instanceof FileSystemError ? error.message : `Chunks directory not found: ${chunksPath}`;
5496
+ validation.errors.push(errorMessage);
5497
+ validation.valid = false;
5498
+ }
5499
+ let attachmentsPath;
5500
+ try {
5501
+ if (fs) {
5502
+ attachmentsPath = fs.joinPath(staticPath, "attachments");
5503
+ if (await fs.exists(attachmentsPath)) {
5504
+ const attachmentsStats = await fs.stat(attachmentsPath);
5505
+ if (attachmentsStats.isDirectory()) {
5506
+ validation.attachmentsExist = true;
5507
+ }
5508
+ } else {
5509
+ validation.warnings.push(
5510
+ `Attachments directory not found: ${attachmentsPath} (this is OK if course has no attachments)`
5511
+ );
5512
+ }
5513
+ } else {
5514
+ attachmentsPath = `${staticPath}/attachments`;
5515
+ const attachmentsStats = await nodeFS.promises.stat(attachmentsPath);
5516
+ if (attachmentsStats.isDirectory()) {
5517
+ validation.attachmentsExist = true;
5518
+ }
5519
+ }
5520
+ } catch (error) {
5521
+ attachmentsPath = attachmentsPath || `${staticPath}/attachments`;
5522
+ const warningMessage = error instanceof FileSystemError ? error.message : `Attachments directory not found: ${attachmentsPath} (this is OK if course has no attachments)`;
5523
+ validation.warnings.push(warningMessage);
5524
+ }
5525
+ } catch (error) {
5526
+ validation.errors.push(
5527
+ `Failed to validate static course: ${error instanceof Error ? error.message : String(error)}`
5528
+ );
5529
+ validation.valid = false;
5530
+ }
5531
+ return validation;
5532
+ }
5533
+ async function validateMigration(targetDB, expectedCounts, manifest) {
5534
+ const validation = {
5535
+ valid: true,
5536
+ documentCountMatch: false,
5537
+ attachmentIntegrity: false,
5538
+ viewFunctionality: false,
5539
+ issues: []
5540
+ };
5541
+ try {
5542
+ logger.info("Starting migration validation...");
5543
+ const actualCounts = await getActualDocumentCounts(targetDB);
5544
+ validation.documentCountMatch = compareDocumentCounts(
5545
+ expectedCounts,
5546
+ actualCounts,
5547
+ validation.issues
5548
+ );
5549
+ await validateCourseConfig(targetDB, manifest, validation.issues);
5550
+ validation.viewFunctionality = await validateViews(targetDB, manifest, validation.issues);
5551
+ validation.attachmentIntegrity = await validateAttachmentIntegrity(targetDB, validation.issues);
5552
+ validation.valid = validation.documentCountMatch && validation.viewFunctionality && validation.attachmentIntegrity;
5553
+ logger.info(`Migration validation completed. Valid: ${validation.valid}`);
5554
+ if (validation.issues.length > 0) {
5555
+ logger.info(`Validation issues: ${validation.issues.length}`);
5556
+ validation.issues.forEach((issue) => {
5557
+ if (issue.type === "error") {
5558
+ logger.error(`${issue.category}: ${issue.message}`);
5559
+ } else {
5560
+ logger.warn(`${issue.category}: ${issue.message}`);
5561
+ }
5562
+ });
5563
+ }
5564
+ } catch (error) {
5565
+ validation.valid = false;
5566
+ validation.issues.push({
5567
+ type: "error",
5568
+ category: "metadata",
5569
+ message: `Validation failed: ${error instanceof Error ? error.message : String(error)}`
5570
+ });
5571
+ }
5572
+ return validation;
5573
+ }
5574
+ async function getActualDocumentCounts(db) {
5575
+ const counts = {};
5576
+ try {
5577
+ const allDocs = await db.allDocs({ include_docs: true });
5578
+ for (const row of allDocs.rows) {
5579
+ if (row.id.startsWith("_design/")) {
5580
+ counts["_design"] = (counts["_design"] || 0) + 1;
5581
+ continue;
5582
+ }
5583
+ const doc = row.doc;
5584
+ if (doc && doc.docType) {
5585
+ counts[doc.docType] = (counts[doc.docType] || 0) + 1;
5586
+ } else {
5587
+ counts["unknown"] = (counts["unknown"] || 0) + 1;
5588
+ }
5589
+ }
5590
+ } catch (error) {
5591
+ logger.error("Failed to get actual document counts:", error);
5592
+ }
5593
+ return counts;
5594
+ }
5595
+ function compareDocumentCounts(expected, actual, issues) {
5596
+ let countsMatch = true;
5597
+ for (const [docType, expectedCount] of Object.entries(expected)) {
5598
+ const actualCount = actual[docType] || 0;
5599
+ if (actualCount !== expectedCount) {
5600
+ countsMatch = false;
5601
+ issues.push({
5602
+ type: "error",
5603
+ category: "documents",
5604
+ message: `Document count mismatch for ${docType}: expected ${expectedCount}, got ${actualCount}`
5605
+ });
5606
+ }
5607
+ }
5608
+ for (const [docType, actualCount] of Object.entries(actual)) {
5609
+ if (!expected[docType] && docType !== "_design") {
5610
+ issues.push({
5611
+ type: "warning",
5612
+ category: "documents",
5613
+ message: `Unexpected document type found: ${docType} (${actualCount} documents)`
5614
+ });
5615
+ }
5616
+ }
5617
+ return countsMatch;
5618
+ }
5619
+ async function validateCourseConfig(db, manifest, issues) {
5620
+ try {
5621
+ const courseConfig = await db.get("CourseConfig");
5622
+ if (!courseConfig) {
5623
+ issues.push({
5624
+ type: "error",
5625
+ category: "course_config",
5626
+ message: "CourseConfig document not found after migration"
5627
+ });
5628
+ return;
5629
+ }
5630
+ if (!courseConfig.courseID) {
5631
+ issues.push({
5632
+ type: "warning",
5633
+ category: "course_config",
5634
+ message: "CourseConfig document missing courseID field"
5635
+ });
5636
+ }
5637
+ if (courseConfig.courseID !== manifest.courseId) {
5638
+ issues.push({
5639
+ type: "warning",
5640
+ category: "course_config",
5641
+ message: `CourseConfig courseID mismatch: expected ${manifest.courseId}, got ${courseConfig.courseID}`
5642
+ });
5643
+ }
5644
+ logger.debug("CourseConfig document validation passed");
5645
+ } catch (error) {
5646
+ if (error.status === 404) {
5647
+ issues.push({
5648
+ type: "error",
5649
+ category: "course_config",
5650
+ message: "CourseConfig document not found in database"
5651
+ });
5652
+ } else {
5653
+ issues.push({
5654
+ type: "error",
5655
+ category: "course_config",
5656
+ message: `Failed to validate CourseConfig document: ${error instanceof Error ? error.message : String(error)}`
5657
+ });
5658
+ }
5659
+ }
5660
+ }
5661
+ async function validateViews(db, manifest, issues) {
5662
+ let viewsValid = true;
5663
+ try {
5664
+ for (const designDoc of manifest.designDocs) {
5665
+ try {
5666
+ const doc = await db.get(designDoc._id);
5667
+ if (!doc) {
5668
+ viewsValid = false;
5669
+ issues.push({
5670
+ type: "error",
5671
+ category: "views",
5672
+ message: `Design document not found: ${designDoc._id}`
5673
+ });
5674
+ continue;
5675
+ }
5676
+ for (const viewName of Object.keys(designDoc.views)) {
5677
+ try {
5678
+ const viewPath = `${designDoc._id}/${viewName}`;
5679
+ await db.query(viewPath, { limit: 1 });
5680
+ } catch (viewError) {
5681
+ viewsValid = false;
5682
+ issues.push({
5683
+ type: "error",
5684
+ category: "views",
5685
+ message: `View not accessible: ${designDoc._id}/${viewName} - ${viewError}`
5686
+ });
5687
+ }
5688
+ }
5689
+ } catch (error) {
5690
+ viewsValid = false;
5691
+ issues.push({
5692
+ type: "error",
5693
+ category: "views",
5694
+ message: `Failed to validate design document ${designDoc._id}: ${error}`
5695
+ });
5696
+ }
5697
+ }
5698
+ } catch (error) {
5699
+ viewsValid = false;
5700
+ issues.push({
5701
+ type: "error",
5702
+ category: "views",
5703
+ message: `View validation failed: ${error instanceof Error ? error.message : String(error)}`
5704
+ });
5705
+ }
5706
+ return viewsValid;
5707
+ }
5708
+ async function validateAttachmentIntegrity(db, issues) {
5709
+ let attachmentsValid = true;
5710
+ try {
5711
+ const allDocs = await db.allDocs({
5712
+ include_docs: true,
5713
+ limit: 10
5714
+ // Sample first 10 documents for performance
5715
+ });
5716
+ let attachmentCount = 0;
5717
+ let validAttachments = 0;
5718
+ for (const row of allDocs.rows) {
5719
+ const doc = row.doc;
5720
+ if (doc && doc._attachments) {
5721
+ for (const [attachmentName, _attachmentMeta] of Object.entries(doc._attachments)) {
5722
+ attachmentCount++;
5723
+ try {
5724
+ const attachment = await db.getAttachment(doc._id, attachmentName);
5725
+ if (attachment) {
5726
+ validAttachments++;
5727
+ }
5728
+ } catch (attachmentError) {
5729
+ attachmentsValid = false;
5730
+ issues.push({
5731
+ type: "error",
5732
+ category: "attachments",
5733
+ message: `Attachment not accessible: ${doc._id}/${attachmentName} - ${attachmentError}`
5734
+ });
5735
+ }
5736
+ }
5737
+ }
5738
+ }
5739
+ if (attachmentCount === 0) {
5740
+ issues.push({
5741
+ type: "warning",
5742
+ category: "attachments",
5743
+ message: "No attachments found in sampled documents"
5744
+ });
5745
+ } else {
5746
+ logger.info(`Validated ${validAttachments}/${attachmentCount} sampled attachments`);
5747
+ }
5748
+ } catch (error) {
5749
+ attachmentsValid = false;
5750
+ issues.push({
5751
+ type: "error",
5752
+ category: "attachments",
5753
+ message: `Attachment validation failed: ${error instanceof Error ? error.message : String(error)}`
5754
+ });
5755
+ }
5756
+ return attachmentsValid;
5757
+ }
5758
+ var nodeFS;
5759
+ var init_validation = __esm({
5760
+ "src/util/migrator/validation.ts"() {
5761
+ "use strict";
5762
+ init_logger();
5763
+ init_FileSystemAdapter();
5764
+ nodeFS = null;
5765
+ try {
5766
+ if (typeof window === "undefined" && typeof process !== "undefined" && process.versions?.node) {
5767
+ nodeFS = eval("require")("fs");
5768
+ nodeFS.promises = nodeFS.promises || eval("require")("fs").promises;
5769
+ }
5770
+ } catch {
5771
+ }
5772
+ }
5773
+ });
5774
+
5775
+ // src/util/migrator/StaticToCouchDBMigrator.ts
5776
+ var nodeFS2, nodePath, StaticToCouchDBMigrator;
5777
+ var init_StaticToCouchDBMigrator = __esm({
5778
+ "src/util/migrator/StaticToCouchDBMigrator.ts"() {
5779
+ "use strict";
5780
+ init_logger();
5781
+ init_types4();
5782
+ init_validation();
5783
+ init_FileSystemAdapter();
5784
+ nodeFS2 = null;
5785
+ nodePath = null;
5786
+ try {
5787
+ if (typeof window === "undefined" && typeof process !== "undefined" && process.versions?.node) {
5788
+ nodeFS2 = eval("require")("fs");
5789
+ nodePath = eval("require")("path");
5790
+ nodeFS2.promises = nodeFS2.promises || eval("require")("fs").promises;
5791
+ }
5792
+ } catch {
5793
+ }
5794
+ StaticToCouchDBMigrator = class {
5795
+ options;
5796
+ progressCallback;
5797
+ fs;
5798
+ constructor(options = {}, fileSystemAdapter) {
5799
+ this.options = {
5800
+ ...DEFAULT_MIGRATION_OPTIONS,
5801
+ ...options
5802
+ };
5803
+ this.fs = fileSystemAdapter;
5804
+ }
5805
+ /**
5806
+ * Set a progress callback to receive updates during migration
5807
+ */
5808
+ setProgressCallback(callback) {
5809
+ this.progressCallback = callback;
5810
+ }
5811
+ /**
5812
+ * Migrate a static course to CouchDB
5813
+ */
5814
+ async migrateCourse(staticPath, targetDB) {
5815
+ const startTime = Date.now();
5816
+ const result = {
5817
+ success: false,
5818
+ documentsRestored: 0,
5819
+ attachmentsRestored: 0,
5820
+ designDocsRestored: 0,
5821
+ courseConfigRestored: 0,
5822
+ errors: [],
5823
+ warnings: [],
5824
+ migrationTime: 0
5825
+ };
5826
+ try {
5827
+ logger.info(`Starting migration from ${staticPath} to CouchDB`);
5828
+ this.reportProgress("manifest", 0, 1, "Validating static course...");
5829
+ const validation = await validateStaticCourse(staticPath, this.fs);
5830
+ if (!validation.valid) {
5831
+ result.errors.push(...validation.errors);
5832
+ throw new Error(`Static course validation failed: ${validation.errors.join(", ")}`);
5833
+ }
5834
+ result.warnings.push(...validation.warnings);
5835
+ this.reportProgress("manifest", 1, 1, "Loading course manifest...");
5836
+ const manifest = await this.loadManifest(staticPath);
5837
+ logger.info(`Loaded manifest for course: ${manifest.courseId} (${manifest.courseName})`);
5838
+ this.reportProgress(
5839
+ "design_docs",
5840
+ 0,
5841
+ manifest.designDocs.length,
5842
+ "Restoring design documents..."
5843
+ );
5844
+ const designDocResults = await this.restoreDesignDocuments(manifest.designDocs, targetDB);
5845
+ result.designDocsRestored = designDocResults.restored;
5846
+ result.errors.push(...designDocResults.errors);
5847
+ result.warnings.push(...designDocResults.warnings);
5848
+ this.reportProgress("course_config", 0, 1, "Restoring CourseConfig document...");
5849
+ const courseConfigResults = await this.restoreCourseConfig(manifest, targetDB);
5850
+ result.courseConfigRestored = courseConfigResults.restored;
5851
+ result.errors.push(...courseConfigResults.errors);
5852
+ result.warnings.push(...courseConfigResults.warnings);
5853
+ this.reportProgress("course_config", 1, 1, "CourseConfig document restored");
5854
+ const expectedCounts = this.calculateExpectedCounts(manifest);
5855
+ this.reportProgress(
5856
+ "documents",
5857
+ 0,
5858
+ manifest.documentCount,
5859
+ "Aggregating documents from chunks..."
5860
+ );
5861
+ const documents = await this.aggregateDocuments(staticPath, manifest);
5862
+ const filteredDocuments = documents.filter((doc) => doc._id !== "CourseConfig");
5863
+ if (documents.length !== filteredDocuments.length) {
5864
+ result.warnings.push(
5865
+ `Filtered out ${documents.length - filteredDocuments.length} CourseConfig document(s) from chunks to prevent conflicts`
5866
+ );
5867
+ }
5868
+ this.reportProgress(
5869
+ "documents",
5870
+ filteredDocuments.length,
5871
+ manifest.documentCount,
5872
+ "Uploading documents to CouchDB..."
5873
+ );
5874
+ const docResults = await this.uploadDocuments(filteredDocuments, targetDB);
5875
+ result.documentsRestored = docResults.restored;
5876
+ result.errors.push(...docResults.errors);
5877
+ result.warnings.push(...docResults.warnings);
5878
+ const docsWithAttachments = documents.filter(
5879
+ (doc) => doc._attachments && Object.keys(doc._attachments).length > 0
5880
+ );
5881
+ this.reportProgress("attachments", 0, docsWithAttachments.length, "Uploading attachments...");
5882
+ const attachmentResults = await this.uploadAttachments(
5883
+ staticPath,
5884
+ docsWithAttachments,
5885
+ targetDB
5886
+ );
5887
+ result.attachmentsRestored = attachmentResults.restored;
5888
+ result.errors.push(...attachmentResults.errors);
5889
+ result.warnings.push(...attachmentResults.warnings);
5890
+ if (this.options.validateRoundTrip) {
5891
+ this.reportProgress("validation", 0, 1, "Validating migration...");
5892
+ const validationResult = await validateMigration(targetDB, expectedCounts, manifest);
5893
+ if (!validationResult.valid) {
5894
+ result.warnings.push("Migration validation found issues");
5895
+ validationResult.issues.forEach((issue) => {
5896
+ if (issue.type === "error") {
5897
+ result.errors.push(`Validation: ${issue.message}`);
5898
+ } else {
5899
+ result.warnings.push(`Validation: ${issue.message}`);
5900
+ }
5901
+ });
5902
+ }
5903
+ this.reportProgress("validation", 1, 1, "Migration validation completed");
5904
+ }
5905
+ result.success = result.errors.length === 0;
5906
+ result.migrationTime = Date.now() - startTime;
5907
+ logger.info(`Migration completed in ${result.migrationTime}ms`);
5908
+ logger.info(`Documents restored: ${result.documentsRestored}`);
5909
+ logger.info(`Attachments restored: ${result.attachmentsRestored}`);
5910
+ logger.info(`Design docs restored: ${result.designDocsRestored}`);
5911
+ logger.info(`CourseConfig restored: ${result.courseConfigRestored}`);
5912
+ if (result.errors.length > 0) {
5913
+ logger.error(`Migration completed with ${result.errors.length} errors`);
5914
+ }
5915
+ if (result.warnings.length > 0) {
5916
+ logger.warn(`Migration completed with ${result.warnings.length} warnings`);
5917
+ }
5918
+ } catch (error) {
5919
+ result.success = false;
5920
+ result.migrationTime = Date.now() - startTime;
5921
+ const errorMessage = error instanceof Error ? error.message : String(error);
5922
+ result.errors.push(`Migration failed: ${errorMessage}`);
5923
+ logger.error("Migration failed:", error);
5924
+ if (this.options.cleanupOnFailure) {
5925
+ try {
5926
+ await this.cleanupFailedMigration(targetDB);
5927
+ } catch (cleanupError) {
5928
+ logger.error("Failed to cleanup after migration failure:", cleanupError);
5929
+ result.warnings.push("Failed to cleanup after migration failure");
5930
+ }
5931
+ }
5932
+ }
5933
+ return result;
5934
+ }
5935
+ /**
5936
+ * Load and parse the manifest file
5937
+ */
5938
+ async loadManifest(staticPath) {
5939
+ try {
5940
+ let manifestContent;
5941
+ let manifestPath;
5942
+ if (this.fs) {
5943
+ manifestPath = this.fs.joinPath(staticPath, "manifest.json");
5944
+ manifestContent = await this.fs.readFile(manifestPath);
5945
+ } else {
5946
+ manifestPath = nodeFS2 && nodePath ? nodePath.join(staticPath, "manifest.json") : `${staticPath}/manifest.json`;
5947
+ if (nodeFS2 && this.isLocalPath(staticPath)) {
5948
+ manifestContent = await nodeFS2.promises.readFile(manifestPath, "utf8");
5949
+ } else {
5950
+ const response = await fetch(manifestPath);
5951
+ if (!response.ok) {
5952
+ throw new Error(`Failed to fetch manifest: ${response.status} ${response.statusText}`);
5953
+ }
5954
+ manifestContent = await response.text();
5955
+ }
5956
+ }
5957
+ const manifest = JSON.parse(manifestContent);
5958
+ if (!manifest.version || !manifest.courseId || !manifest.chunks) {
5959
+ throw new Error("Invalid manifest structure");
5960
+ }
5961
+ return manifest;
5962
+ } catch (error) {
5963
+ const errorMessage = error instanceof FileSystemError ? error.message : `Failed to load manifest: ${error instanceof Error ? error.message : String(error)}`;
5964
+ throw new Error(errorMessage);
5965
+ }
5966
+ }
5967
+ /**
5968
+ * Restore design documents to CouchDB
5969
+ */
5970
+ async restoreDesignDocuments(designDocs, db) {
5971
+ const result = { restored: 0, errors: [], warnings: [] };
5972
+ for (let i = 0; i < designDocs.length; i++) {
5973
+ const designDoc = designDocs[i];
5974
+ this.reportProgress("design_docs", i, designDocs.length, `Restoring ${designDoc._id}...`);
5975
+ try {
5976
+ let existingDoc;
5977
+ try {
5978
+ existingDoc = await db.get(designDoc._id);
5979
+ } catch {
5980
+ }
5981
+ const docToInsert = {
5982
+ _id: designDoc._id,
5983
+ views: designDoc.views
5984
+ };
5985
+ if (existingDoc) {
5986
+ docToInsert._rev = existingDoc._rev;
5987
+ logger.debug(`Updating existing design document: ${designDoc._id}`);
5988
+ } else {
5989
+ logger.debug(`Creating new design document: ${designDoc._id}`);
5990
+ }
5991
+ await db.put(docToInsert);
5992
+ result.restored++;
5993
+ } catch (error) {
5994
+ const errorMessage = `Failed to restore design document ${designDoc._id}: ${error instanceof Error ? error.message : String(error)}`;
5995
+ result.errors.push(errorMessage);
5996
+ logger.error(errorMessage);
5997
+ }
5998
+ }
5999
+ this.reportProgress(
6000
+ "design_docs",
6001
+ designDocs.length,
6002
+ designDocs.length,
6003
+ `Restored ${result.restored} design documents`
6004
+ );
6005
+ return result;
6006
+ }
6007
+ /**
6008
+ * Aggregate documents from all chunks
6009
+ */
6010
+ async aggregateDocuments(staticPath, manifest) {
6011
+ const allDocuments = [];
6012
+ const documentMap = /* @__PURE__ */ new Map();
6013
+ for (let i = 0; i < manifest.chunks.length; i++) {
6014
+ const chunk = manifest.chunks[i];
6015
+ this.reportProgress(
6016
+ "documents",
6017
+ allDocuments.length,
6018
+ manifest.documentCount,
6019
+ `Loading chunk ${chunk.id}...`
6020
+ );
6021
+ try {
6022
+ const documents = await this.loadChunk(staticPath, chunk);
6023
+ for (const doc of documents) {
6024
+ if (!doc._id) {
6025
+ logger.warn(`Document without _id found in chunk ${chunk.id}, skipping`);
6026
+ continue;
6027
+ }
6028
+ if (documentMap.has(doc._id)) {
6029
+ logger.warn(`Duplicate document ID found: ${doc._id}, using latest version`);
6030
+ }
6031
+ documentMap.set(doc._id, doc);
6032
+ }
6033
+ } catch (error) {
6034
+ throw new Error(
6035
+ `Failed to load chunk ${chunk.id}: ${error instanceof Error ? error.message : String(error)}`
6036
+ );
6037
+ }
6038
+ }
6039
+ allDocuments.push(...documentMap.values());
6040
+ logger.info(
6041
+ `Aggregated ${allDocuments.length} unique documents from ${manifest.chunks.length} chunks`
6042
+ );
6043
+ return allDocuments;
6044
+ }
6045
+ /**
6046
+ * Load documents from a single chunk file
6047
+ */
6048
+ async loadChunk(staticPath, chunk) {
6049
+ try {
6050
+ let chunkContent;
6051
+ let chunkPath;
6052
+ if (this.fs) {
6053
+ chunkPath = this.fs.joinPath(staticPath, chunk.path);
6054
+ chunkContent = await this.fs.readFile(chunkPath);
6055
+ } else {
6056
+ chunkPath = nodeFS2 && nodePath ? nodePath.join(staticPath, chunk.path) : `${staticPath}/${chunk.path}`;
6057
+ if (nodeFS2 && this.isLocalPath(staticPath)) {
6058
+ chunkContent = await nodeFS2.promises.readFile(chunkPath, "utf8");
6059
+ } else {
6060
+ const response = await fetch(chunkPath);
6061
+ if (!response.ok) {
6062
+ throw new Error(`Failed to fetch chunk: ${response.status} ${response.statusText}`);
6063
+ }
6064
+ chunkContent = await response.text();
6065
+ }
6066
+ }
6067
+ const documents = JSON.parse(chunkContent);
6068
+ if (!Array.isArray(documents)) {
6069
+ throw new Error("Chunk file does not contain an array of documents");
6070
+ }
6071
+ return documents;
6072
+ } catch (error) {
6073
+ const errorMessage = error instanceof FileSystemError ? error.message : `Failed to load chunk: ${error instanceof Error ? error.message : String(error)}`;
6074
+ throw new Error(errorMessage);
6075
+ }
6076
+ }
6077
+ /**
6078
+ * Upload documents to CouchDB in batches
6079
+ */
6080
+ async uploadDocuments(documents, db) {
6081
+ const result = { restored: 0, errors: [], warnings: [] };
6082
+ const batchSize = this.options.chunkBatchSize;
6083
+ for (let i = 0; i < documents.length; i += batchSize) {
6084
+ const batch = documents.slice(i, i + batchSize);
6085
+ this.reportProgress(
6086
+ "documents",
6087
+ i,
6088
+ documents.length,
6089
+ `Uploading batch ${Math.floor(i / batchSize) + 1}...`
6090
+ );
6091
+ try {
6092
+ const docsToInsert = batch.map((doc) => {
6093
+ const cleanDoc = { ...doc };
6094
+ delete cleanDoc._rev;
6095
+ delete cleanDoc._attachments;
6096
+ return cleanDoc;
6097
+ });
6098
+ const bulkResult = await db.bulkDocs(docsToInsert);
6099
+ for (let j = 0; j < bulkResult.length; j++) {
6100
+ const docResult = bulkResult[j];
6101
+ const originalDoc = batch[j];
6102
+ if ("error" in docResult) {
6103
+ const errorMessage = `Failed to upload document ${originalDoc._id}: ${docResult.error} - ${docResult.reason}`;
6104
+ result.errors.push(errorMessage);
6105
+ logger.error(errorMessage);
6106
+ } else {
6107
+ result.restored++;
6108
+ }
6109
+ }
6110
+ } catch (error) {
6111
+ let errorMessage;
6112
+ if (error instanceof Error) {
6113
+ errorMessage = `Failed to upload document batch starting at index ${i}: ${error.message}`;
6114
+ } else if (error && typeof error === "object" && "message" in error) {
6115
+ errorMessage = `Failed to upload document batch starting at index ${i}: ${error.message}`;
6116
+ } else {
6117
+ errorMessage = `Failed to upload document batch starting at index ${i}: ${JSON.stringify(error)}`;
6118
+ }
6119
+ result.errors.push(errorMessage);
6120
+ logger.error(errorMessage);
6121
+ }
6122
+ }
6123
+ this.reportProgress(
6124
+ "documents",
6125
+ documents.length,
6126
+ documents.length,
6127
+ `Uploaded ${result.restored} documents`
6128
+ );
6129
+ return result;
6130
+ }
6131
+ /**
6132
+ * Upload attachments from filesystem to CouchDB
6133
+ */
6134
+ async uploadAttachments(staticPath, documents, db) {
6135
+ const result = { restored: 0, errors: [], warnings: [] };
6136
+ let processedDocs = 0;
6137
+ for (const doc of documents) {
6138
+ this.reportProgress(
6139
+ "attachments",
6140
+ processedDocs,
6141
+ documents.length,
6142
+ `Processing attachments for ${doc._id}...`
6143
+ );
6144
+ processedDocs++;
6145
+ if (!doc._attachments) {
6146
+ continue;
6147
+ }
6148
+ for (const [attachmentName, attachmentMeta] of Object.entries(doc._attachments)) {
6149
+ try {
6150
+ const uploadResult = await this.uploadSingleAttachment(
6151
+ staticPath,
6152
+ doc._id,
6153
+ attachmentName,
6154
+ attachmentMeta,
6155
+ db
6156
+ );
6157
+ if (uploadResult.success) {
6158
+ result.restored++;
6159
+ } else {
6160
+ result.errors.push(uploadResult.error || "Unknown attachment upload error");
6161
+ }
6162
+ } catch (error) {
6163
+ const errorMessage = `Failed to upload attachment ${doc._id}/${attachmentName}: ${error instanceof Error ? error.message : String(error)}`;
6164
+ result.errors.push(errorMessage);
6165
+ logger.error(errorMessage);
6166
+ }
6167
+ }
6168
+ }
6169
+ this.reportProgress(
6170
+ "attachments",
6171
+ documents.length,
6172
+ documents.length,
6173
+ `Uploaded ${result.restored} attachments`
6174
+ );
6175
+ return result;
6176
+ }
6177
+ /**
6178
+ * Upload a single attachment file
6179
+ */
6180
+ async uploadSingleAttachment(staticPath, docId, attachmentName, attachmentMeta, db) {
6181
+ const result = {
6182
+ success: false,
6183
+ attachmentName,
6184
+ docId
6185
+ };
6186
+ try {
6187
+ if (!attachmentMeta.path) {
6188
+ result.error = "Attachment metadata missing file path";
6189
+ return result;
6190
+ }
6191
+ let attachmentData;
6192
+ let attachmentPath;
6193
+ if (this.fs) {
6194
+ attachmentPath = this.fs.joinPath(staticPath, attachmentMeta.path);
6195
+ attachmentData = await this.fs.readBinary(attachmentPath);
6196
+ } else {
6197
+ attachmentPath = nodeFS2 && nodePath ? nodePath.join(staticPath, attachmentMeta.path) : `${staticPath}/${attachmentMeta.path}`;
6198
+ if (nodeFS2 && this.isLocalPath(staticPath)) {
6199
+ attachmentData = await nodeFS2.promises.readFile(attachmentPath);
6200
+ } else {
6201
+ const response = await fetch(attachmentPath);
6202
+ if (!response.ok) {
6203
+ result.error = `Failed to fetch attachment: ${response.status} ${response.statusText}`;
6204
+ return result;
6205
+ }
6206
+ attachmentData = await response.arrayBuffer();
6207
+ }
6208
+ }
6209
+ const doc = await db.get(docId);
6210
+ await db.putAttachment(
6211
+ docId,
6212
+ attachmentName,
6213
+ doc._rev,
6214
+ attachmentData,
6215
+ // PouchDB accepts both ArrayBuffer and Buffer
6216
+ attachmentMeta.content_type
6217
+ );
6218
+ result.success = true;
6219
+ } catch (error) {
6220
+ result.error = error instanceof Error ? error.message : String(error);
6221
+ }
6222
+ return result;
6223
+ }
6224
+ /**
6225
+ * Restore CourseConfig document from manifest
6226
+ */
6227
+ async restoreCourseConfig(manifest, targetDB) {
6228
+ const results = {
6229
+ restored: 0,
6230
+ errors: [],
6231
+ warnings: []
6232
+ };
6233
+ try {
6234
+ if (!manifest.courseConfig) {
6235
+ results.warnings.push(
6236
+ "No courseConfig found in manifest, skipping CourseConfig document creation"
6237
+ );
6238
+ return results;
6239
+ }
6240
+ const courseConfigDoc = {
6241
+ _id: "CourseConfig",
6242
+ ...manifest.courseConfig,
6243
+ courseID: manifest.courseId
6244
+ };
6245
+ delete courseConfigDoc._rev;
6246
+ await targetDB.put(courseConfigDoc);
6247
+ results.restored = 1;
6248
+ logger.info(`CourseConfig document created for course: ${manifest.courseId}`);
6249
+ } catch (error) {
6250
+ const errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
6251
+ results.errors.push(`Failed to restore CourseConfig: ${errorMessage}`);
6252
+ logger.error("CourseConfig restoration failed:", error);
6253
+ }
6254
+ return results;
6255
+ }
6256
+ /**
6257
+ * Calculate expected document counts from manifest
6258
+ */
6259
+ calculateExpectedCounts(manifest) {
6260
+ const counts = {};
6261
+ for (const chunk of manifest.chunks) {
6262
+ counts[chunk.docType] = (counts[chunk.docType] || 0) + chunk.documentCount;
6263
+ }
6264
+ if (manifest.designDocs.length > 0) {
6265
+ counts["_design"] = manifest.designDocs.length;
6266
+ }
6267
+ return counts;
6268
+ }
6269
+ /**
6270
+ * Clean up database after failed migration
6271
+ */
6272
+ async cleanupFailedMigration(db) {
6273
+ logger.info("Cleaning up failed migration...");
6274
+ try {
6275
+ const allDocs = await db.allDocs();
6276
+ const docsToDelete = allDocs.rows.map((row) => ({
6277
+ _id: row.id,
6278
+ _rev: row.value.rev,
6279
+ _deleted: true
6280
+ }));
6281
+ if (docsToDelete.length > 0) {
6282
+ await db.bulkDocs(docsToDelete);
6283
+ logger.info(`Cleaned up ${docsToDelete.length} documents from failed migration`);
6284
+ }
6285
+ } catch (error) {
6286
+ logger.error("Failed to cleanup documents:", error);
6287
+ throw error;
6288
+ }
6289
+ }
6290
+ /**
6291
+ * Report progress to callback if available
6292
+ */
6293
+ reportProgress(phase, current, total, message) {
6294
+ if (this.progressCallback) {
6295
+ this.progressCallback({
6296
+ phase,
6297
+ current,
6298
+ total,
6299
+ message
6300
+ });
6301
+ }
6302
+ }
6303
+ /**
6304
+ * Check if a path is a local file path (vs URL)
6305
+ */
6306
+ isLocalPath(path2) {
6307
+ return !path2.startsWith("http://") && !path2.startsWith("https://");
6308
+ }
6309
+ };
6310
+ }
6311
+ });
6312
+
6313
+ // src/util/migrator/index.ts
6314
+ var init_migrator = __esm({
6315
+ "src/util/migrator/index.ts"() {
6316
+ "use strict";
6317
+ init_StaticToCouchDBMigrator();
6318
+ init_validation();
6319
+ init_FileSystemAdapter();
6320
+ }
6321
+ });
6322
+
6323
+ // src/util/dataDirectory.ts
6324
+ import * as path from "path";
6325
+ import * as os from "os";
6326
+ function getAppDataDirectory() {
6327
+ if (ENV.LOCAL_STORAGE_PREFIX) {
6328
+ return path.join(os.homedir(), `.tuilder`, ENV.LOCAL_STORAGE_PREFIX);
6329
+ } else {
6330
+ return path.join(os.homedir(), ".tuilder");
6331
+ }
6332
+ }
6333
+ function getDbPath(dbName) {
6334
+ return path.join(getAppDataDirectory(), dbName);
6335
+ }
6336
+ var init_dataDirectory = __esm({
6337
+ "src/util/dataDirectory.ts"() {
6338
+ "use strict";
6339
+ init_logger();
6340
+ init_factory();
6341
+ }
6342
+ });
6343
+
6344
+ // src/util/index.ts
6345
+ var init_util2 = __esm({
6346
+ "src/util/index.ts"() {
6347
+ "use strict";
6348
+ init_Loggable();
6349
+ init_packer();
6350
+ init_migrator();
6351
+ init_dataDirectory();
6352
+ }
6353
+ });
6354
+
6355
+ // src/study/SourceMixer.ts
6356
+ var init_SourceMixer = __esm({
6357
+ "src/study/SourceMixer.ts"() {
6358
+ "use strict";
6359
+ }
6360
+ });
6361
+
6362
+ // src/study/MixerDebugger.ts
6363
+ function printMixerSummary(run) {
6364
+ console.group(`\u{1F3A8} Mixer Run: ${run.mixerType}`);
6365
+ logger.info(`Run ID: ${run.runId}`);
6366
+ logger.info(`Time: ${run.timestamp.toISOString()}`);
6367
+ logger.info(
6368
+ `Config: limit=${run.requestedLimit}${run.quotaPerSource ? `, quota/source=${run.quotaPerSource}` : ""}`
6369
+ );
6370
+ console.group(`\u{1F4E5} Input: ${run.sourceSummaries.length} sources`);
6371
+ for (const src of run.sourceSummaries) {
6372
+ logger.info(
6373
+ ` ${src.sourceName || src.sourceId}: ${src.totalCards} cards (${src.reviewCount} reviews, ${src.newCount} new)`
6374
+ );
6375
+ logger.info(` Score range: [${src.scoreRange[0].toFixed(2)}, ${src.scoreRange[1].toFixed(2)}], avg: ${src.avgScore.toFixed(2)}`);
6376
+ }
6377
+ console.groupEnd();
6378
+ console.group(`\u{1F4E4} Output: ${run.finalCount} cards selected (${run.reviewsSelected} reviews, ${run.newSelected} new)`);
6379
+ for (const breakdown of run.sourceBreakdowns) {
6380
+ const name = breakdown.sourceName || breakdown.sourceId;
6381
+ logger.info(
6382
+ ` ${name}: ${breakdown.totalSelected} selected (${breakdown.reviewsSelected} reviews, ${breakdown.newSelected} new) - ${breakdown.selectionRate.toFixed(1)}% selection rate`
6383
+ );
6384
+ }
6385
+ console.groupEnd();
6386
+ console.groupEnd();
6387
+ }
6388
+ function mountMixerDebugger() {
6389
+ if (typeof window === "undefined") return;
6390
+ const win = window;
6391
+ win.skuilder = win.skuilder || {};
6392
+ win.skuilder.mixer = mixerDebugAPI;
6393
+ }
6394
+ var runHistory2, mixerDebugAPI;
6395
+ var init_MixerDebugger = __esm({
6396
+ "src/study/MixerDebugger.ts"() {
6397
+ "use strict";
6398
+ init_logger();
6399
+ init_navigators();
6400
+ runHistory2 = [];
6401
+ mixerDebugAPI = {
6402
+ /**
6403
+ * Get raw run history for programmatic access.
6404
+ */
6405
+ get runs() {
6406
+ return [...runHistory2];
6407
+ },
6408
+ /**
6409
+ * Show summary of a specific mixer run.
6410
+ */
6411
+ showRun(idOrIndex = 0) {
6412
+ if (runHistory2.length === 0) {
6413
+ logger.info("[Mixer Debug] No runs captured yet.");
6414
+ return;
6415
+ }
6416
+ let run;
6417
+ if (typeof idOrIndex === "number") {
6418
+ run = runHistory2[idOrIndex];
6419
+ if (!run) {
6420
+ logger.info(`[Mixer Debug] No run found at index ${idOrIndex}. History length: ${runHistory2.length}`);
6421
+ return;
6422
+ }
6423
+ } else {
6424
+ run = runHistory2.find((r) => r.runId.endsWith(idOrIndex));
6425
+ if (!run) {
6426
+ logger.info(`[Mixer Debug] No run found matching ID '${idOrIndex}'.`);
6427
+ return;
6428
+ }
6429
+ }
6430
+ printMixerSummary(run);
6431
+ },
6432
+ /**
6433
+ * Show summary of the last mixer run.
6434
+ */
6435
+ showLastMix() {
6436
+ this.showRun(0);
6437
+ },
6438
+ /**
6439
+ * Explain source balance in the last run.
6440
+ */
6441
+ explainSourceBalance() {
6442
+ if (runHistory2.length === 0) {
6443
+ logger.info("[Mixer Debug] No runs captured yet.");
6444
+ return;
6445
+ }
6446
+ const run = runHistory2[0];
6447
+ console.group("\u2696\uFE0F Source Balance Analysis");
6448
+ logger.info(`Mixer: ${run.mixerType}`);
6449
+ logger.info(`Requested limit: ${run.requestedLimit}`);
6450
+ if (run.quotaPerSource) {
6451
+ logger.info(`Quota per source: ${run.quotaPerSource}`);
6452
+ }
6453
+ console.group("Input Distribution:");
6454
+ for (const src of run.sourceSummaries) {
6455
+ const name = src.sourceName || src.sourceId;
6456
+ logger.info(`${name}:`);
6457
+ logger.info(` Provided: ${src.totalCards} cards (${src.reviewCount} reviews, ${src.newCount} new)`);
6458
+ logger.info(` Score range: [${src.scoreRange[0].toFixed(2)}, ${src.scoreRange[1].toFixed(2)}]`);
6459
+ }
6460
+ console.groupEnd();
6461
+ console.group("Selection Results:");
6462
+ for (const breakdown of run.sourceBreakdowns) {
6463
+ const name = breakdown.sourceName || breakdown.sourceId;
6464
+ logger.info(`${name}:`);
6465
+ logger.info(
6466
+ ` Selected: ${breakdown.totalSelected}/${breakdown.reviewsProvided + breakdown.newProvided} (${breakdown.selectionRate.toFixed(1)}%)`
6467
+ );
6468
+ logger.info(` Reviews: ${breakdown.reviewsSelected}/${breakdown.reviewsProvided}`);
6469
+ logger.info(` New: ${breakdown.newSelected}/${breakdown.newProvided}`);
6470
+ if (breakdown.reviewsProvided > 0 && breakdown.reviewsSelected === 0) {
6471
+ logger.info(` \u26A0\uFE0F Had reviews but none selected!`);
6472
+ }
6473
+ if (breakdown.totalSelected === 0 && breakdown.reviewsProvided + breakdown.newProvided > 0) {
6474
+ logger.info(` \u26A0\uFE0F Had cards but none selected!`);
6475
+ }
6476
+ }
6477
+ console.groupEnd();
6478
+ const selectionRates = run.sourceBreakdowns.map((b) => b.selectionRate);
6479
+ const avgRate = selectionRates.reduce((a, b) => a + b, 0) / selectionRates.length;
6480
+ const maxDeviation = Math.max(...selectionRates.map((r) => Math.abs(r - avgRate)));
6481
+ if (maxDeviation > 20) {
6482
+ logger.info(`
6483
+ \u26A0\uFE0F Significant imbalance detected (max deviation: ${maxDeviation.toFixed(1)}%)`);
6484
+ logger.info("Possible causes:");
6485
+ logger.info(" - Score range differences between sources");
6486
+ logger.info(" - One source has much better quality cards");
6487
+ logger.info(" - Different card availability (reviews vs new)");
6488
+ }
6489
+ console.groupEnd();
6490
+ },
6491
+ /**
6492
+ * Compare score distributions across sources.
6493
+ */
6494
+ compareScores() {
6495
+ if (runHistory2.length === 0) {
6496
+ logger.info("[Mixer Debug] No runs captured yet.");
6497
+ return;
6498
+ }
6499
+ const run = runHistory2[0];
6500
+ console.group("\u{1F4CA} Score Distribution Comparison");
6501
+ console.table(
6502
+ run.sourceSummaries.map((src) => ({
6503
+ source: src.sourceName || src.sourceId,
6504
+ cards: src.totalCards,
6505
+ min: src.bottomScore.toFixed(3),
6506
+ max: src.topScore.toFixed(3),
6507
+ avg: src.avgScore.toFixed(3),
6508
+ range: (src.topScore - src.bottomScore).toFixed(3)
6509
+ }))
6510
+ );
6511
+ const ranges = run.sourceSummaries.map((s) => s.topScore - s.bottomScore);
6512
+ const avgScores = run.sourceSummaries.map((s) => s.avgScore);
6513
+ const rangeDiff = Math.max(...ranges) - Math.min(...ranges);
6514
+ const avgDiff = Math.max(...avgScores) - Math.min(...avgScores);
6515
+ if (rangeDiff > 0.3 || avgDiff > 0.2) {
6516
+ logger.info("\n\u26A0\uFE0F Significant score distribution differences detected");
6517
+ logger.info(
6518
+ "This may cause one source to dominate selection if using global sorting (not quota-based)"
6519
+ );
6520
+ }
6521
+ console.groupEnd();
6522
+ },
6523
+ /**
6524
+ * Show detailed information for a specific card.
6525
+ */
6526
+ showCard(cardId) {
6527
+ for (const run of runHistory2) {
6528
+ const card = run.cards.find((c) => c.cardId === cardId);
6529
+ if (card) {
6530
+ const source = run.sourceSummaries.find((s) => s.sourceIndex === card.sourceIndex);
6531
+ console.group(`\u{1F3B4} Card: ${cardId}`);
6532
+ logger.info(`Course: ${card.courseId}`);
6533
+ logger.info(`Source: ${source?.sourceName || source?.sourceId || "unknown"}`);
6534
+ logger.info(`Origin: ${card.origin}`);
6535
+ logger.info(`Score: ${card.score.toFixed(3)}`);
6536
+ if (card.rankInSource) {
6537
+ logger.info(`Rank in source: #${card.rankInSource}`);
6538
+ }
6539
+ if (card.rankInMix) {
6540
+ logger.info(`Rank in mixed results: #${card.rankInMix}`);
6541
+ }
6542
+ logger.info(`Selected: ${card.selected ? "Yes \u2705" : "No \u274C"}`);
6543
+ if (!card.selected && card.rankInSource) {
6544
+ logger.info("\nWhy not selected:");
6545
+ if (run.quotaPerSource && card.rankInSource > run.quotaPerSource) {
6546
+ logger.info(` - Ranked #${card.rankInSource} in source, but quota was ${run.quotaPerSource}`);
6547
+ }
6548
+ logger.info(" - Check score compared to selected cards using .showRun()");
6549
+ }
6550
+ console.groupEnd();
6551
+ return;
6552
+ }
6553
+ }
6554
+ logger.info(`[Mixer Debug] Card '${cardId}' not found in recent runs.`);
6555
+ },
6556
+ /**
6557
+ * Show all runs in compact format.
6558
+ */
6559
+ listRuns() {
6560
+ if (runHistory2.length === 0) {
6561
+ logger.info("[Mixer Debug] No runs captured yet.");
6562
+ return;
6563
+ }
6564
+ console.table(
6565
+ runHistory2.map((r) => ({
6566
+ id: r.runId.slice(-8),
6567
+ time: r.timestamp.toLocaleTimeString(),
6568
+ mixer: r.mixerType,
6569
+ sources: r.sourceSummaries.length,
6570
+ selected: r.finalCount,
6571
+ reviews: r.reviewsSelected,
6572
+ new: r.newSelected
6573
+ }))
6574
+ );
6575
+ },
6576
+ /**
6577
+ * Export run history as JSON for bug reports.
6578
+ */
6579
+ export() {
6580
+ const json = JSON.stringify(runHistory2, null, 2);
6581
+ logger.info("[Mixer Debug] Run history exported. Copy the returned string or use:");
6582
+ logger.info(" copy(window.skuilder.mixer.export())");
6583
+ return json;
6584
+ },
6585
+ /**
6586
+ * Clear run history.
6587
+ */
6588
+ clear() {
6589
+ runHistory2.length = 0;
6590
+ logger.info("[Mixer Debug] Run history cleared.");
6591
+ },
6592
+ /**
6593
+ * Show help.
6594
+ */
6595
+ help() {
6596
+ logger.info(`
6597
+ \u{1F3A8} Mixer Debug API
6598
+
6599
+ Commands:
6600
+ .showLastMix() Show summary of most recent mixer run
6601
+ .showRun(id|index) Show summary of a specific run (by index or ID suffix)
6602
+ .explainSourceBalance() Analyze source balance and selection patterns
6603
+ .compareScores() Compare score distributions across sources
6604
+ .showCard(cardId) Show mixer decisions for a specific card
6605
+ .listRuns() List all captured runs in table format
6606
+ .export() Export run history as JSON for bug reports
6607
+ .clear() Clear run history
6608
+ .runs Access raw run history array
6609
+ .help() Show this help message
6610
+
6611
+ Example:
6612
+ window.skuilder.mixer.showLastMix()
6613
+ window.skuilder.mixer.explainSourceBalance()
6614
+ window.skuilder.mixer.compareScores()
6615
+ `);
6616
+ }
6617
+ };
6618
+ mountMixerDebugger();
6619
+ }
6620
+ });
6621
+
6622
+ // src/study/SessionOverlay.ts
6623
+ function getActiveController() {
6624
+ return activeController;
6625
+ }
6626
+ function toggleSessionOverlay() {
6627
+ if (typeof document === "undefined") {
6628
+ logger.info("[Session Overlay] No DOM available (non-browser host); overlay unavailable.");
6629
+ return;
6630
+ }
6631
+ if (overlayEl) {
6632
+ teardown();
6633
+ logger.info("[Session Overlay] Hidden.");
6634
+ } else {
6635
+ mount();
6636
+ logger.info("[Session Overlay] Shown. Toggle off with window.skuilder.session.dbgOverlay().");
6637
+ }
6638
+ }
6639
+ function mount() {
6640
+ minified = false;
6641
+ overlayEl = document.createElement("div");
6642
+ overlayEl.id = OVERLAY_ID;
6643
+ Object.assign(overlayEl.style, {
6644
+ position: "fixed",
6645
+ top: "8px",
6646
+ left: "8px",
6647
+ zIndex: "2147483647",
6648
+ maxWidth: "320px",
6649
+ maxHeight: "90vh",
6650
+ overflowY: "auto",
6651
+ padding: "8px 10px",
6652
+ background: "rgba(17, 24, 39, 0.92)",
6653
+ color: "#e5e7eb",
6654
+ font: "11px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace",
6655
+ borderRadius: "6px",
6656
+ boxShadow: "0 4px 16px rgba(0,0,0,0.4)",
6657
+ pointerEvents: "auto",
6658
+ userSelect: "none"
6659
+ });
6660
+ document.body.appendChild(overlayEl);
6661
+ render();
6662
+ pollHandle = setInterval(render, POLL_MS);
6663
+ }
6664
+ function teardown() {
6665
+ if (pollHandle !== null) {
6666
+ clearInterval(pollHandle);
6667
+ pollHandle = null;
6668
+ }
6669
+ if (overlayEl?.parentNode) {
6670
+ overlayEl.parentNode.removeChild(overlayEl);
6671
+ }
6672
+ overlayEl = null;
6673
+ }
6674
+ function render() {
6675
+ if (!overlayEl) return;
6676
+ spinnerFrame++;
6677
+ const ctrl = getActiveController();
6678
+ if (!ctrl) {
6679
+ lastSnapshot = null;
6680
+ overlayEl.innerHTML = headerHtml() + (minified ? "" : `<div style="opacity:.65">No active session.</div>`);
6681
+ attachHandlers();
6682
+ return;
6683
+ }
6684
+ const s = ctrl.getDebugSnapshot();
6685
+ lastSnapshot = s;
6686
+ if (minified) {
6687
+ overlayEl.innerHTML = headerHtml();
6688
+ attachHandlers();
6689
+ return;
6690
+ }
6691
+ 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);
6692
+ attachHandlers();
6693
+ }
6694
+ function attachHandlers() {
6695
+ if (!overlayEl) return;
6696
+ overlayEl.querySelectorAll("[data-q]").forEach((el) => {
6697
+ el.onclick = () => {
6698
+ const key = el.dataset.q;
6699
+ if (!key) return;
6700
+ expanded[key] = !expanded[key];
6701
+ render();
6702
+ };
6703
+ });
6704
+ const copyBtn = overlayEl.querySelector("[data-copy]");
6705
+ if (copyBtn) {
6706
+ copyBtn.onclick = (ev) => {
6707
+ ev.stopPropagation();
6708
+ copySnapshot();
6709
+ };
6710
+ }
6711
+ const minBtn = overlayEl.querySelector("[data-min]");
6712
+ if (minBtn) {
6713
+ minBtn.onclick = (ev) => {
6714
+ ev.stopPropagation();
6715
+ minified = !minified;
6716
+ render();
6717
+ };
6718
+ }
6719
+ }
6720
+ function copySnapshot() {
6721
+ const text = snapshotToText(lastSnapshot);
6722
+ const flash = () => {
6723
+ copyFlashUntil = Date.now() + 1200;
6724
+ render();
6725
+ };
6726
+ const clip = typeof navigator !== "undefined" ? navigator.clipboard : void 0;
6727
+ if (clip?.writeText) {
6728
+ clip.writeText(text).then(flash, (err) => {
6729
+ logger.warn(`[Session Overlay] Clipboard write failed: ${String(err)}`);
6730
+ });
6731
+ } else {
6732
+ logger.info(`[Session Overlay] Clipboard unavailable; snapshot follows:
6733
+ ${text}`);
6734
+ }
6735
+ }
6736
+ function headerHtml() {
6737
+ const flashing = Date.now() < copyFlashUntil;
6738
+ const btnLabel = flashing ? "\u2713 copied" : "\u2398 copy";
6739
+ const btnColor = flashing ? "#86efac" : "#93c5fd";
6740
+ 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>`;
6741
+ 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>`;
6742
+ return `<div style="font-weight:600;color:#93c5fd;margin-bottom:${minified ? 0 : 4}px">${copyBtn}${minBtn}\u2699 SessionController</div>`;
6743
+ }
6744
+ function replanHtml(s) {
6745
+ if (!s.replanActive) {
6746
+ return `<div style="margin-bottom:6px;opacity:.45">\u25CB idle</div>`;
6747
+ }
6748
+ const frame = SPINNER_FRAMES[spinnerFrame % SPINNER_FRAMES.length];
6749
+ const reason = esc(s.replanLabel ?? "(auto)");
6750
+ return `<div style="margin-bottom:6px;color:#fde047">${frame} replanning <span style="opacity:.85">[${reason}]</span></div>`;
6751
+ }
6752
+ function metaHtml(s) {
6753
+ const mmss = formatTime(s.secondsRemaining);
6754
+ const guarantee = s.hasCardGuarantee ? ` \xB7 <span style="color:#fbbf24">guarantee ${s.minCardsGuarantee}</span>` : "";
6755
+ const rows = [
6756
+ `time ${mmss}${guarantee}`,
6757
+ `well-indicated left: ${s.wellIndicatedRemaining}`,
6758
+ `current: ${s.currentCard ? esc(s.currentCard) : '<span style="opacity:.6">\u2014</span>'}`
6759
+ ];
6760
+ return `<div style="margin-bottom:6px">${rows.map((r) => `<div>${r}</div>`).join("")}</div>`;
6761
+ }
6762
+ function hintsHtml(h) {
6763
+ const parts = [];
6764
+ if (h) {
6765
+ if (h.boostTags && Object.keys(h.boostTags).length) {
6766
+ parts.push(
6767
+ `boost: ` + Object.entries(h.boostTags).map(([k, v]) => `${esc(k)}<span style="opacity:.6">\xD7${v}</span>`).join(", ")
6768
+ );
6769
+ }
6770
+ if (h.boostCards && Object.keys(h.boostCards).length) {
6771
+ parts.push(
6772
+ `boostCards: ` + Object.entries(h.boostCards).map(([k, v]) => `${esc(k)}<span style="opacity:.6">\xD7${v}</span>`).join(", ")
6773
+ );
6774
+ }
6775
+ if (h.requireCards?.length) parts.push(`require: ${h.requireCards.map(esc).join(", ")}`);
6776
+ if (h.requireTags?.length) parts.push(`requireTags: ${h.requireTags.map(esc).join(", ")}`);
6777
+ if (h.excludeTags?.length) parts.push(`exclude: ${h.excludeTags.map(esc).join(", ")}`);
6778
+ if (h.excludeCards?.length) parts.push(`excludeCards: ${h.excludeCards.map(esc).join(", ")}`);
6779
+ }
6780
+ const body = parts.length ? parts.map((p) => `<div style="margin-left:6px">${p}</div>`).join("") : `<div style="margin-left:6px;opacity:.6">none</div>`;
6781
+ return `<div style="margin-bottom:6px"><div style="color:#86efac">sessionHints</div>${body}</div>`;
6782
+ }
6783
+ function backlogHtml(backlog) {
6784
+ if (!backlog.length) return "";
6785
+ const rows = backlog.map((b) => {
6786
+ const hot = b.backlogMultiplier >= 3;
6787
+ const multColor = b.backlogMultiplier <= 1 ? "#86efac" : hot ? "#fca5a5" : "#fcd34d";
6788
+ const headroom = b.backlogMultiplier > 1 ? `climbing (\xD7${b.backlogGrowthRate.toFixed(2)} per ${b.healthyBacklog}-review excess, unbounded)` : "healthy \u2014 no pressure";
6789
+ const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
6790
+ const next = b.nextDueIn ? ` <span style="opacity:.6">\xB7 next due ${esc(b.nextDueIn)}</span>` : "";
6791
+ 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>`;
6792
+ }).join("");
6793
+ return `<div style="margin-bottom:6px"><div style="color:#93c5fd">review backpressure</div>${rows}</div>`;
6794
+ }
6795
+ function pressureColor(multiplier, max) {
6796
+ if (multiplier <= 1.001) return "#86efac";
6797
+ if (max !== void 0 && max > 1) {
6798
+ return (multiplier - 1) / (max - 1) >= 0.75 ? "#fca5a5" : "#fcd34d";
6799
+ }
6800
+ return multiplier >= 3 ? "#fca5a5" : "#fcd34d";
6801
+ }
6802
+ function toggleKey(raw) {
6803
+ return raw.replace(/[^\w:.|-]/g, "_");
6804
+ }
6805
+ function gaugeHtml(sectionKey, g) {
6806
+ const cap = g.max !== void 0 ? `<span style="opacity:.5">/${g.max}</span>` : "";
6807
+ const detail = g.detail ? ` <span style="opacity:.6">${esc(g.detail)}</span>` : "";
6808
+ 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}`;
6809
+ const items = g.items ?? [];
6810
+ if (items.length > 0) {
6811
+ const key = toggleKey(`sp|${sectionKey}|${g.id}`);
6812
+ const isOpen = !!expanded[key];
6813
+ const shown = isOpen ? items : items.slice(0, INLINE_THRESHOLD);
6814
+ html += `<div style="margin-left:6px">` + shown.map(
6815
+ (it) => `<div style="white-space:nowrap;opacity:.75">${esc(it.label)}${it.value ? ` <span style="opacity:.6">${esc(it.value)}</span>` : ""}</div>`
6816
+ ).join("");
6817
+ if (items.length > INLINE_THRESHOLD) {
6818
+ const footer = isOpen ? "\u25BE show less" : `\u2026 +${items.length - shown.length} more`;
6819
+ html += `<div data-q="${key}" style="cursor:pointer;opacity:.6">${footer}</div>`;
6820
+ }
6821
+ html += `</div>`;
6822
+ }
6823
+ return html + `</div>`;
6824
+ }
6825
+ function strategyPressureHtml(list) {
6826
+ if (!list.length) return "";
6827
+ const sections = list.map((s) => {
6828
+ const sectionKey = `${s.source}:${s.courseId.slice(0, 8)}`;
6829
+ const top = s.topScore !== null && s.topScore !== void 0 ? s.topScore.toFixed(2) : "\u2014";
6830
+ const hints = s.hintsLabel ? `<div style="margin-left:6px;opacity:.6">hints: ${esc(s.hintsLabel)}</div>` : "";
6831
+ 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>`;
6832
+ }).join("");
6833
+ return `<div style="margin-bottom:6px"><div style="color:#fdba74">strategy backpressure</div>${sections}</div>`;
6834
+ }
6835
+ function fmtScore(score) {
6836
+ if (score === void 0) return "";
6837
+ if (!Number.isFinite(score)) return "REQ";
6838
+ return score.toFixed(2);
6839
+ }
6840
+ function queueItemHtml(item) {
6841
+ const tagColor = item.origin === "review" ? "#93c5fd" : "#fcd34d";
6842
+ const score = fmtScore(item.score);
6843
+ const label = `${item.origin === "review" ? "r" : "n"}${score ? " " + score : ""}`;
6844
+ return `${esc(item.cardID)}<span style="color:${tagColor};opacity:.85"> [${label}]</span>`;
6845
+ }
6846
+ function queueHtml(key, label, q) {
6847
+ const collapsible = q.length > INLINE_THRESHOLD;
6848
+ const isOpen = collapsible && expanded[key];
6849
+ const caret = collapsible ? expanded[key] ? "\u25BE " : "\u25B8 " : "";
6850
+ const drawn = q.dequeueCount ? ` <span style="opacity:.5">drawn ${q.dequeueCount}</span>` : "";
6851
+ const titleStyle = collapsible ? "cursor:pointer;color:#f9a8d4" : "color:#f9a8d4";
6852
+ const titleAttr = collapsible ? ` data-q="${key}"` : "";
6853
+ const title = `<div${titleAttr} style="${titleStyle}">${caret}${label}: ${q.length}${drawn}</div>`;
6854
+ if (!q.cards.length) {
6855
+ return title + `<div style="margin:1px 0 6px 6px;opacity:.5">empty</div>`;
6856
+ }
6857
+ const shown = isOpen ? q.cards : q.cards.slice(0, INLINE_THRESHOLD);
6858
+ const hiddenCount = q.length - shown.length;
6859
+ const listMarginBottom = collapsible ? 2 : 6;
6860
+ 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>`;
6861
+ if (collapsible) {
6862
+ const footer = isOpen ? "\u25BE show less" : `\u2026 +${hiddenCount} more`;
6863
+ body += `<div data-q="${key}" style="cursor:pointer;margin:0 0 6px 20px;opacity:.6">${footer}</div>`;
6864
+ }
6865
+ return title + body;
6866
+ }
6867
+ function outcomeGlyph(correct) {
6868
+ if (correct === true) return `<span style="color:#86efac">\u2713</span>`;
6869
+ if (correct === false) return `<span style="color:#fca5a5">\u2717</span>`;
6870
+ return `<span style="opacity:.5">\xB7</span>`;
6871
+ }
6872
+ function drawnHtml(key, drawn) {
6873
+ const collapsible = drawn.length > INLINE_THRESHOLD;
6874
+ const isOpen = collapsible && expanded[key];
6875
+ const caret = collapsible ? expanded[key] ? "\u25BE " : "\u25B8 " : "";
6876
+ const titleStyle = collapsible ? "cursor:pointer;color:#c4b5fd" : "color:#c4b5fd";
6877
+ const titleAttr = collapsible ? ` data-q="${key}"` : "";
6878
+ const title = `<div${titleAttr} style="${titleStyle}">${caret}drawn: ${drawn.length}</div>`;
6879
+ if (!drawn.length) {
6880
+ return title + `<div style="margin:1px 0 6px 6px;opacity:.5">none yet</div>`;
6881
+ }
6882
+ const shown = isOpen ? drawn : drawn.slice(0, INLINE_THRESHOLD);
6883
+ const hiddenCount = drawn.length - shown.length;
6884
+ const listMarginBottom = collapsible ? 2 : 6;
6885
+ const rows = shown.map((d) => {
6886
+ const retries = d.attempts > 1 ? `<span style="opacity:.5"> \xD7${d.attempts}</span>` : "";
6887
+ const time = `<span style="opacity:.45"> ${Math.round(d.timeSpentMs / 100) / 10}s</span>`;
6888
+ return `<li style="white-space:nowrap">${outcomeGlyph(d.correct)} ${esc(d.cardID)}<span style="opacity:.5"> [${esc(d.status)}]</span>${retries}${time}</li>`;
6889
+ }).join("");
6890
+ let body = `<ol style="margin:2px 0 ${listMarginBottom}px 0;padding-left:20px">${rows}</ol>`;
6891
+ if (collapsible) {
6892
+ const footer = isOpen ? "\u25BE show less" : `\u2026 +${hiddenCount} more`;
6893
+ body += `<div data-q="${key}" style="cursor:pointer;margin:0 0 6px 20px;opacity:.6">${footer}</div>`;
6894
+ }
6895
+ return title + body;
6896
+ }
6897
+ function snapshotToText(s) {
6898
+ if (!s) return "SessionController \u2014 no active session.";
6899
+ const lines = [];
6900
+ lines.push("=== SessionController ===");
6901
+ lines.push(`time ${formatTime(s.secondsRemaining)}`);
6902
+ if (s.hasCardGuarantee) lines.push(`guarantee: ${s.minCardsGuarantee}`);
6903
+ lines.push(`well-indicated left: ${s.wellIndicatedRemaining}`);
6904
+ lines.push(`current: ${s.currentCard ?? "\u2014"}`);
6905
+ lines.push(
6906
+ s.replanActive ? `replan: ACTIVE [${s.replanLabel ?? "(auto)"}]` : "replan: idle"
6907
+ );
6908
+ lines.push("");
6909
+ lines.push("sessionHints:");
6910
+ const h = s.sessionHints;
6911
+ const hintParts = [];
6912
+ if (h) {
6913
+ if (h.boostTags && Object.keys(h.boostTags).length)
6914
+ hintParts.push(` boost: ${Object.entries(h.boostTags).map(([k, v]) => `${k}\xD7${v}`).join(", ")}`);
6915
+ if (h.boostCards && Object.keys(h.boostCards).length)
6916
+ hintParts.push(` boostCards: ${Object.entries(h.boostCards).map(([k, v]) => `${k}\xD7${v}`).join(", ")}`);
6917
+ if (h.requireCards?.length) hintParts.push(` require: ${h.requireCards.join(", ")}`);
6918
+ if (h.requireTags?.length) hintParts.push(` requireTags: ${h.requireTags.join(", ")}`);
6919
+ if (h.excludeTags?.length) hintParts.push(` exclude: ${h.excludeTags.join(", ")}`);
6920
+ if (h.excludeCards?.length) hintParts.push(` excludeCards: ${h.excludeCards.join(", ")}`);
6921
+ }
6922
+ lines.push(hintParts.length ? hintParts.join("\n") : " none");
6923
+ if (s.reviewBacklog.length) {
6924
+ lines.push("");
6925
+ lines.push("review backpressure:");
6926
+ for (const b of s.reviewBacklog) {
6927
+ const headroom = b.backlogMultiplier > 1 ? "climbing" : "healthy";
6928
+ const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
6929
+ const next = b.nextDueIn ? `, next due ${b.nextDueIn}` : "";
6930
+ lines.push(
6931
+ ` ${b.courseId.slice(0, 8)}: due ${b.dueNow}/${b.scheduledTotal} (healthy ${b.healthyBacklog})${next}; pressure \xD7${b.backlogMultiplier.toFixed(2)} ${headroom}; top review ${top}`
6932
+ );
6933
+ }
6934
+ }
6935
+ if (s.strategyPressure.length) {
6936
+ lines.push("");
6937
+ lines.push("strategy backpressure:");
6938
+ for (const sp of s.strategyPressure) {
6939
+ const top = sp.topScore !== null && sp.topScore !== void 0 ? sp.topScore.toFixed(2) : "\u2014";
6940
+ lines.push(` ${sp.source} (${sp.courseId.slice(0, 8)}): top score ${top}`);
6941
+ for (const g of sp.gauges) {
6942
+ const cap = g.max !== void 0 ? `/${g.max}` : "";
6943
+ lines.push(
6944
+ ` ${g.label} \xD7${g.multiplier.toFixed(2)}${cap}${g.detail ? ` \u2014 ${g.detail}` : ""}`
6945
+ );
6946
+ for (const it of g.items ?? []) {
6947
+ lines.push(` ${it.label}${it.value ? ` (${it.value})` : ""}`);
6948
+ }
6949
+ }
6950
+ if (sp.hintsLabel) lines.push(` hints: ${sp.hintsLabel}`);
6951
+ }
6952
+ }
6953
+ const queueText = (label, q) => {
6954
+ lines.push("");
6955
+ lines.push(`${label}: ${q.length} (drawn ${q.dequeueCount})`);
6956
+ q.cards.forEach((c, i) => {
6957
+ const score = fmtScore(c.score);
6958
+ const tag = `${c.origin === "review" ? "r" : "n"}${score ? " " + score : ""}`;
6959
+ lines.push(` ${i + 1}. ${c.cardID} [${tag}]`);
6960
+ });
6961
+ };
6962
+ queueText("supplyQ", s.supplyQ);
6963
+ queueText("failedQ", s.failedQ);
6964
+ lines.push("");
6965
+ lines.push(`drawn: ${s.drawnCards.length}`);
6966
+ s.drawnCards.forEach((d, i) => {
6967
+ const mark = d.correct === true ? "\u2713" : d.correct === false ? "\u2717" : "\xB7";
6968
+ const time = `${Math.round(d.timeSpentMs / 100) / 10}s`;
6969
+ lines.push(` ${i + 1}. ${mark} ${d.cardID} [${d.status}] \xD7${d.attempts} ${time}`);
6970
+ });
6971
+ return lines.join("\n");
6972
+ }
6973
+ function formatTime(totalSeconds) {
6974
+ const s = Math.max(0, Math.round(totalSeconds));
6975
+ const m = Math.floor(s / 60);
6976
+ const r = s % 60;
6977
+ return `${m}:${r.toString().padStart(2, "0")}`;
6978
+ }
6979
+ function esc(value) {
6980
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
6981
+ }
6982
+ var activeController, OVERLAY_ID, POLL_MS, INLINE_THRESHOLD, SPINNER_FRAMES, spinnerFrame, overlayEl, pollHandle, lastSnapshot, copyFlashUntil, minified, expanded;
6983
+ var init_SessionOverlay = __esm({
6984
+ "src/study/SessionOverlay.ts"() {
6985
+ "use strict";
6986
+ init_logger();
6987
+ activeController = null;
6988
+ OVERLAY_ID = "skuilder-session-overlay";
6989
+ POLL_MS = 300;
6990
+ INLINE_THRESHOLD = 5;
6991
+ SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
6992
+ spinnerFrame = 0;
6993
+ overlayEl = null;
6994
+ pollHandle = null;
6995
+ lastSnapshot = null;
6996
+ copyFlashUntil = 0;
6997
+ minified = false;
6998
+ expanded = {
6999
+ supplyQ: false,
7000
+ failedQ: false,
7001
+ drawn: false
7002
+ };
7003
+ }
7004
+ });
7005
+
7006
+ // src/study/SessionDebugger.ts
7007
+ function showCurrentQueue() {
7008
+ if (!activeSession) {
7009
+ logger.info("[Session Debug] No active session.");
7010
+ return;
7011
+ }
7012
+ const latest = activeSession.queueSnapshots[activeSession.queueSnapshots.length - 1] || activeSession.initialQueues;
7013
+ console.group("\u{1F4CA} Current Queue State");
7014
+ logger.info(`Supply Queue: ${latest.supplyQLength} cards`);
7015
+ if (latest.supplyQNext3 && latest.supplyQNext3.length > 0) {
7016
+ logger.info(` Next: ${latest.supplyQNext3.join(", ")}`);
7017
+ }
7018
+ logger.info(`Failed Queue: ${latest.failedQLength} cards`);
7019
+ console.groupEnd();
7020
+ }
7021
+ function showPresentationHistory(sessionIndex = 0) {
7022
+ const session = sessionIndex === 0 && activeSession ? activeSession : sessionHistory[sessionIndex];
7023
+ if (!session) {
7024
+ logger.info(`[Session Debug] No session found at index ${sessionIndex}`);
7025
+ return;
7026
+ }
7027
+ console.group(`\u{1F4DC} Session History: ${session.sessionId}`);
7028
+ logger.info(`Started: ${session.startTime.toLocaleTimeString()}`);
7029
+ if (session.endTime) {
7030
+ logger.info(`Ended: ${session.endTime.toLocaleTimeString()}`);
7031
+ }
7032
+ logger.info(`Cards presented: ${session.presentations.length}`);
7033
+ if (session.presentations.length > 0) {
7034
+ console.table(
7035
+ session.presentations.map((p) => ({
7036
+ "#": p.sequenceNumber,
7037
+ course: p.courseName || p.courseId.slice(0, 8),
7038
+ origin: p.origin,
7039
+ queue: p.queueSource,
7040
+ score: p.score?.toFixed(3) || "-",
7041
+ time: p.timestamp.toLocaleTimeString()
7042
+ }))
7043
+ );
7044
+ }
7045
+ console.groupEnd();
7046
+ }
7047
+ function showInterleaving(sessionIndex = 0) {
7048
+ const session = sessionIndex === 0 && activeSession ? activeSession : sessionHistory[sessionIndex];
7049
+ if (!session) {
7050
+ logger.info(`[Session Debug] No session found at index ${sessionIndex}`);
7051
+ return;
7052
+ }
7053
+ console.group("\u{1F500} Interleaving Analysis");
7054
+ const courseCounts = /* @__PURE__ */ new Map();
7055
+ const courseOrigins = /* @__PURE__ */ new Map();
7056
+ session.presentations.forEach((p) => {
7057
+ const name = p.courseName || p.courseId;
7058
+ courseCounts.set(name, (courseCounts.get(name) || 0) + 1);
7059
+ if (!courseOrigins.has(name)) {
7060
+ courseOrigins.set(name, { review: 0, new: 0, failed: 0 });
7061
+ }
7062
+ const origins = courseOrigins.get(name);
7063
+ origins[p.origin]++;
7064
+ });
7065
+ logger.info("Course distribution:");
7066
+ console.table(
7067
+ Array.from(courseCounts.entries()).map(([course, count]) => {
7068
+ const origins = courseOrigins.get(course);
7069
+ return {
7070
+ course,
7071
+ total: count,
7072
+ reviews: origins.review,
7073
+ new: origins.new,
7074
+ failed: origins.failed,
7075
+ percentage: (count / session.presentations.length * 100).toFixed(1) + "%"
7076
+ };
7077
+ })
7078
+ );
7079
+ if (session.presentations.length > 0) {
7080
+ logger.info("\nPresentation sequence (first 20):");
7081
+ const sequence = session.presentations.slice(0, 20).map((p, idx) => `${idx + 1}. ${p.courseName || p.courseId.slice(0, 8)} (${p.origin})`).join("\n");
7082
+ logger.info(sequence);
7083
+ }
7084
+ let maxCluster = 0;
7085
+ let currentCluster = 1;
7086
+ let currentCourse = session.presentations[0]?.courseId;
7087
+ for (let i = 1; i < session.presentations.length; i++) {
7088
+ if (session.presentations[i].courseId === currentCourse) {
7089
+ currentCluster++;
7090
+ maxCluster = Math.max(maxCluster, currentCluster);
7091
+ } else {
7092
+ currentCourse = session.presentations[i].courseId;
7093
+ currentCluster = 1;
7094
+ }
7095
+ }
7096
+ if (maxCluster > 3) {
7097
+ logger.info(`
7098
+ \u26A0\uFE0F Detected clustering: max ${maxCluster} cards from same course in a row`);
7099
+ logger.info("This suggests cards are sorted by score rather than round-robin by course.");
7100
+ }
7101
+ console.groupEnd();
7102
+ }
7103
+ function mountSessionDebugger() {
7104
+ if (typeof window === "undefined") return;
7105
+ const win = window;
7106
+ win.skuilder = win.skuilder || {};
7107
+ win.skuilder.session = sessionDebugAPI;
7108
+ }
7109
+ var activeSession, sessionHistory, sessionDebugAPI;
7110
+ var init_SessionDebugger = __esm({
7111
+ "src/study/SessionDebugger.ts"() {
7112
+ "use strict";
7113
+ init_logger();
7114
+ init_PipelineDebugger();
7115
+ init_SrsDebugger();
7116
+ init_StrategyPressureDebugger();
7117
+ init_SessionOverlay();
7118
+ activeSession = null;
7119
+ sessionHistory = [];
7120
+ sessionDebugAPI = {
7121
+ /**
7122
+ * Get raw session history for programmatic access.
7123
+ */
7124
+ get sessions() {
7125
+ return [...sessionHistory];
7126
+ },
7127
+ /**
7128
+ * Get active session if any.
7129
+ */
7130
+ get active() {
7131
+ return activeSession;
7132
+ },
7133
+ /**
7134
+ * Show current queue state.
7135
+ */
7136
+ showQueue() {
7137
+ showCurrentQueue();
7138
+ },
7139
+ /**
7140
+ * Toggle the pinned, live-updating DOM overlay for the active controller
7141
+ * (queues, session hints, timer). No-ops in non-browser hosts.
7142
+ */
7143
+ dbgOverlay() {
7144
+ toggleSessionOverlay();
7145
+ },
7146
+ /**
7147
+ * Show presentation history for current or past session.
7148
+ */
7149
+ showHistory(sessionIndex = 0) {
7150
+ showPresentationHistory(sessionIndex);
7151
+ },
7152
+ /**
7153
+ * Analyze course interleaving pattern.
7154
+ */
7155
+ showInterleaving(sessionIndex = 0) {
7156
+ showInterleaving(sessionIndex);
7157
+ },
7158
+ /**
7159
+ * List all tracked sessions.
7160
+ */
7161
+ listSessions() {
7162
+ if (activeSession) {
7163
+ logger.info(`Active session: ${activeSession.sessionId} (${activeSession.presentations.length} cards presented)`);
7164
+ }
7165
+ if (sessionHistory.length === 0) {
7166
+ logger.info("[Session Debug] No completed sessions in history.");
7167
+ return;
7168
+ }
7169
+ console.table(
7170
+ sessionHistory.map((s, idx) => ({
7171
+ index: idx,
7172
+ id: s.sessionId.slice(-8),
7173
+ started: s.startTime.toLocaleTimeString(),
7174
+ ended: s.endTime?.toLocaleTimeString() || "incomplete",
7175
+ cards: s.presentations.length
7176
+ }))
7177
+ );
7178
+ },
7179
+ /**
7180
+ * Export session history as JSON for bug reports.
7181
+ */
7182
+ export() {
7183
+ const data = {
7184
+ active: activeSession,
7185
+ history: sessionHistory
7186
+ };
7187
+ const json = JSON.stringify(data, null, 2);
7188
+ logger.info("[Session Debug] Session data exported. Copy the returned string or use:");
7189
+ logger.info(" copy(window.skuilder.session.export())");
7190
+ return json;
7191
+ },
7192
+ /**
7193
+ * Clear session history.
7194
+ */
7195
+ clear() {
7196
+ sessionHistory.length = 0;
7197
+ logger.info("[Session Debug] Session history cleared.");
7198
+ },
7199
+ /**
7200
+ * Show help.
7201
+ */
7202
+ help() {
7203
+ logger.info(`
7204
+ \u{1F3AF} Session Debug API
7205
+
7206
+ Commands:
7207
+ .dbgOverlay() Toggle the pinned live overlay (queues, hints, timer)
7208
+ .showQueue() Show current queue state (active session only)
7209
+ .showHistory(index?) Show presentation history (0=current/last, 1=previous, etc)
7210
+ .showInterleaving(index?) Analyze course interleaving pattern
7211
+ .listSessions() List all tracked sessions
7212
+ .export() Export session data as JSON for bug reports
7213
+ .clear() Clear session history
7214
+ .sessions Access raw session history array
7215
+ .active Access active session (if any)
7216
+ .help() Show this help message
7217
+
7218
+ Example:
7219
+ window.skuilder.session.showHistory()
7220
+ window.skuilder.session.showInterleaving()
7221
+ window.skuilder.session.showQueue()
7222
+ `);
7223
+ }
7224
+ };
7225
+ mountSessionDebugger();
7226
+ }
7227
+ });
7228
+
7229
+ // src/study/SessionController.ts
7230
+ var init_SessionController = __esm({
7231
+ "src/study/SessionController.ts"() {
7232
+ "use strict";
7233
+ init_SrsService();
7234
+ init_EloService();
7235
+ init_ResponseProcessor();
7236
+ init_CardHydrationService();
7237
+ init_ItemQueue();
7238
+ init_couch();
7239
+ init_core();
7240
+ init_types_legacy();
7241
+ init_studySession();
7242
+ init_recording();
7243
+ init_util2();
7244
+ init_navigators();
7245
+ init_Pipeline();
7246
+ init_SourceMixer();
7247
+ init_MixerDebugger();
7248
+ init_SessionDebugger();
7249
+ init_SessionOverlay();
7250
+ init_logger();
7251
+ }
7252
+ });
7253
+
7254
+ // src/study/TagFilteredContentSource.ts
7255
+ import { hasActiveFilter } from "@vue-skuilder/common";
7256
+ var init_TagFilteredContentSource = __esm({
7257
+ "src/study/TagFilteredContentSource.ts"() {
7258
+ "use strict";
7259
+ init_courseDB();
7260
+ init_logger();
7261
+ }
7262
+ });
7263
+
7264
+ // src/study/index.ts
7265
+ var init_study = __esm({
7266
+ "src/study/index.ts"() {
7267
+ "use strict";
7268
+ init_SessionController();
7269
+ init_SourceMixer();
7270
+ init_SpacedRepetition();
7271
+ init_TagFilteredContentSource();
7272
+ init_MixerDebugger();
7273
+ init_SessionDebugger();
7274
+ init_SessionOverlay();
7275
+ }
7276
+ });
7277
+
7278
+ // src/impl/common/userDBHelpers.ts
7279
+ import moment6 from "moment";
7280
+ function makeScheduledCardId(reviewTime) {
7281
+ return DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */] + moment6.utc(reviewTime).format(REVIEW_TIME_FORMAT2);
7282
+ }
7283
+ function filterAllDocsByPrefix2(db, prefix, opts) {
7284
+ const options = {
7285
+ startkey: prefix,
7286
+ endkey: prefix + "\uFFF0",
7287
+ include_docs: true
7288
+ };
7289
+ if (opts) {
7290
+ Object.assign(options, opts);
7291
+ }
7292
+ return db.allDocs(options);
7293
+ }
7294
+ function getStartAndEndKeys2(key) {
7295
+ return {
7296
+ startkey: key,
7297
+ endkey: key + "\uFFF0"
7298
+ };
7299
+ }
7300
+ function getLocalUserDB(username) {
7301
+ const dbName = `userdb-${username}`;
7302
+ if (typeof window === "undefined") {
7303
+ return new pouchdb_setup_default(getDbPath(dbName), {});
7304
+ } else {
7305
+ return new pouchdb_setup_default(dbName, {});
7306
+ }
7307
+ }
7308
+ function scheduleCardReviewLocal(userDB, review) {
7309
+ const now = moment6.utc();
7310
+ logger.info(`Scheduling for review in: ${review.time.diff(now, "h") / 24} days`);
7311
+ void userDB.put({
7312
+ _id: makeScheduledCardId(review.time),
7313
+ cardId: review.card_id,
7314
+ reviewTime: review.time.toISOString(),
7315
+ courseId: review.course_id,
7316
+ scheduledAt: now.toISOString(),
7317
+ scheduledFor: review.scheduledFor,
7318
+ schedulingAgentId: review.schedulingAgentId
7319
+ });
7320
+ }
7321
+ async function removeScheduledCardReviewLocal(userDB, reviewDocID) {
7322
+ const reviewDoc = await userDB.get(reviewDocID);
7323
+ userDB.remove(reviewDoc).then((res) => {
7324
+ if (res.ok) {
7325
+ log2(`Removed Review Doc: ${reviewDocID}`);
7326
+ }
7327
+ }).catch((err) => {
7328
+ log2(`Failed to remove Review Doc: ${reviewDocID},
7329
+ ${JSON.stringify(err)}`);
7330
+ });
7331
+ }
7332
+ var REVIEW_TIME_FORMAT2, log2;
7333
+ var init_userDBHelpers = __esm({
7334
+ "src/impl/common/userDBHelpers.ts"() {
7335
+ "use strict";
7336
+ init_core();
7337
+ init_logger();
7338
+ init_pouchdb_setup();
7339
+ init_dataDirectory();
7340
+ REVIEW_TIME_FORMAT2 = "YYYY-MM-DD--kk:mm:ss-SSS";
7341
+ log2 = (s) => {
7342
+ logger.info(s);
7343
+ };
7344
+ }
7345
+ });
7346
+
7347
+ // src/impl/couch/user-course-relDB.ts
7348
+ import moment7 from "moment";
7349
+ var UsrCrsData;
7350
+ var init_user_course_relDB = __esm({
7351
+ "src/impl/couch/user-course-relDB.ts"() {
7352
+ "use strict";
7353
+ init_logger();
7354
+ UsrCrsData = class {
7355
+ user;
7356
+ _courseId;
7357
+ constructor(user, courseId) {
7358
+ this.user = user;
7359
+ this._courseId = courseId;
7360
+ }
7361
+ async getReviewsForcast(daysCount) {
7362
+ const time = moment7.utc().add(daysCount, "days");
7363
+ return this.getReviewstoDate(time);
7364
+ }
7365
+ async getPendingReviews() {
7366
+ const now = moment7.utc();
7367
+ return this.getReviewstoDate(now);
7368
+ }
7369
+ async getScheduledReviewCount() {
7370
+ return (await this.getPendingReviews()).length;
7371
+ }
7372
+ async getCourseSettings() {
7373
+ const regDoc = await this.user.getCourseRegistrationsDoc();
7374
+ const crsDoc = regDoc.courses.find((c) => c.courseID === this._courseId);
7375
+ if (crsDoc && crsDoc.settings) {
7376
+ return crsDoc.settings;
7377
+ } else {
7378
+ logger.warn(`no settings found during lookup on course ${this._courseId}`);
7379
+ return {};
7380
+ }
7381
+ }
7382
+ updateCourseSettings(updates) {
7383
+ if ("updateCourseSettings" in this.user) {
7384
+ void this.user.updateCourseSettings(this._courseId, updates);
7385
+ }
7386
+ }
7387
+ async getStrategyState(strategyKey) {
7388
+ return this.user.getStrategyState(this._courseId, strategyKey);
7389
+ }
7390
+ async putStrategyState(strategyKey, data) {
7391
+ return this.user.putStrategyState(this._courseId, strategyKey, data);
7392
+ }
7393
+ async deleteStrategyState(strategyKey) {
7394
+ return this.user.deleteStrategyState(this._courseId, strategyKey);
7395
+ }
7396
+ async getReviewstoDate(targetDate) {
7397
+ const allReviews = await this.user.getPendingReviews(this._courseId);
7398
+ logger.debug(
7399
+ `Fetching ${this.user.getUsername()}'s scheduled reviews for course ${this._courseId}.`
7400
+ );
7401
+ return allReviews.filter((review) => {
7402
+ const reviewTime = moment7.utc(review.reviewTime);
7403
+ return targetDate.isAfter(reviewTime);
7404
+ });
7405
+ }
7406
+ };
7407
+ }
7408
+ });
7409
+
7410
+ // src/impl/common/BaseUserDB.ts
7411
+ import { Status as Status3 } from "@vue-skuilder/common";
7412
+ import moment8 from "moment";
7413
+ function withTimeout(p, ms, label) {
7414
+ let timer;
7415
+ return Promise.race([
7416
+ p,
7417
+ new Promise((_resolve, reject) => {
7418
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
7419
+ })
7420
+ ]).finally(() => {
7421
+ if (timer !== void 0) {
7422
+ clearTimeout(timer);
7423
+ }
7424
+ });
7425
+ }
7426
+ function accomodateGuest() {
7427
+ logger.log("[funnel] accomodateGuest() called");
7428
+ if (typeof localStorage === "undefined") {
7429
+ logger.log(
7430
+ "[funnel] localStorage not available (Node.js environment), returning default guest"
7431
+ );
7432
+ return {
7433
+ username: GuestUsername + "nodejs-test",
7434
+ firstVisit: true
7435
+ };
7436
+ }
7437
+ const dbUUID = "sk-guest-uuid";
7438
+ let firstVisit;
7439
+ const existingUUID = localStorage.getItem(dbUUID);
7440
+ logger.log("[funnel] Checking localStorage for key:", dbUUID);
7441
+ logger.log("[funnel] Existing UUID value:", existingUUID);
7442
+ logger.log("[funnel] existingUUID !== null:", existingUUID !== null);
7443
+ if (existingUUID !== null) {
7444
+ firstVisit = false;
7445
+ logger.log(`[funnel] Returning guest ${existingUUID} "logging in".`);
7446
+ } else {
7447
+ firstVisit = true;
7448
+ logger.log("[funnel] No existing UUID, generating new one...");
7449
+ const uuid = generateUUID();
7450
+ logger.log("[funnel] Generated UUID:", uuid);
7451
+ logger.log("[funnel] UUID length:", uuid.length);
7452
+ try {
7453
+ localStorage.setItem(dbUUID, uuid);
7454
+ logger.log("[funnel] Successfully stored UUID in localStorage");
7455
+ const verification = localStorage.getItem(dbUUID);
7456
+ logger.log("[funnel] Verification read from localStorage:", verification);
7457
+ } catch (e) {
7458
+ logger.error("[funnel] ERROR storing UUID:", e);
7459
+ }
7460
+ logger.log(`[funnel] Accommodating a new guest with account: ${uuid}`);
7461
+ }
7462
+ const finalUUID = localStorage.getItem(dbUUID);
7463
+ const finalUsername = GuestUsername + finalUUID;
7464
+ logger.log("[funnel] Final UUID from localStorage:", finalUUID);
7465
+ logger.log("[funnel] GuestUsername constant:", GuestUsername);
7466
+ logger.log("[funnel] Final username to return:", finalUsername);
7467
+ return {
7468
+ username: finalUsername,
7469
+ firstVisit
7470
+ };
7471
+ function generateUUID() {
7472
+ logger.log("[funnel] Inside generateUUID()");
7473
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
7474
+ const uuid2 = crypto.randomUUID();
7475
+ logger.log("[funnel] Generated UUID using crypto.randomUUID():", uuid2);
7476
+ return uuid2;
7477
+ }
7478
+ if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
7479
+ const bytes = new Uint8Array(16);
7480
+ crypto.getRandomValues(bytes);
7481
+ bytes[6] = bytes[6] & 15 | 64;
7482
+ bytes[8] = bytes[8] & 63 | 128;
7483
+ const uuid2 = [
7484
+ Array.from(bytes.slice(0, 4)).map((b) => b.toString(16).padStart(2, "0")).join(""),
7485
+ Array.from(bytes.slice(4, 6)).map((b) => b.toString(16).padStart(2, "0")).join(""),
7486
+ Array.from(bytes.slice(6, 8)).map((b) => b.toString(16).padStart(2, "0")).join(""),
7487
+ Array.from(bytes.slice(8, 10)).map((b) => b.toString(16).padStart(2, "0")).join(""),
7488
+ Array.from(bytes.slice(10, 16)).map((b) => b.toString(16).padStart(2, "0")).join("")
7489
+ ].join("-");
7490
+ logger.log("[funnel] Generated UUID using crypto.getRandomValues():", uuid2);
7491
+ return uuid2;
7492
+ }
7493
+ logger.warn("[funnel] crypto API not available, using timestamp-based UUID (NOT SECURE)");
7494
+ let d = (/* @__PURE__ */ new Date()).getTime();
7495
+ if (typeof performance !== "undefined" && typeof performance.now === "function") {
7496
+ d += performance.now();
7497
+ }
7498
+ const uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
7499
+ const r = (d + Math.random() * 16) % 16 | 0;
7500
+ d = Math.floor(d / 16);
7501
+ return (c === "x" ? r : r & 3 | 8).toString(16);
7502
+ });
7503
+ logger.log("[funnel] Generated UUID (fallback):", uuid);
7504
+ return uuid;
7505
+ }
7506
+ }
7507
+ async function getOrCreateClassroomRegistrationsDoc(user) {
5492
7508
  let ret;
5493
7509
  try {
5494
7510
  ret = await getLocalUserDB(user).get(userClassroomsDoc);
@@ -5588,6 +7604,7 @@ var init_BaseUserDB = __esm({
5588
7604
  init_util();
5589
7605
  init_types_legacy();
5590
7606
  init_logger();
7607
+ init_study();
5591
7608
  init_userDBHelpers();
5592
7609
  init_updateQueue();
5593
7610
  init_user_course_relDB();
@@ -5823,7 +7840,7 @@ Currently logged-in as ${this._username}.`
5823
7840
  *
5824
7841
  */
5825
7842
  async getActiveCards() {
5826
- const keys = getStartAndEndKeys(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */]);
7843
+ const keys = getStartAndEndKeys2(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */]);
5827
7844
  const reviews = await this.remoteDB.allDocs({
5828
7845
  startkey: keys.startkey,
5829
7846
  endkey: keys.endkey,
@@ -5900,7 +7917,7 @@ Currently logged-in as ${this._username}.`
5900
7917
  }
5901
7918
  }
5902
7919
  async getReviewstoDate(targetDate, course_id) {
5903
- const keys = getStartAndEndKeys(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */]);
7920
+ const keys = getStartAndEndKeys2(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */]);
5904
7921
  const reviews = await this.remoteDB.allDocs({
5905
7922
  startkey: keys.startkey,
5906
7923
  endkey: keys.endkey,
@@ -5911,9 +7928,9 @@ Currently logged-in as ${this._username}.`
5911
7928
  );
5912
7929
  return reviews.rows.filter((r) => {
5913
7930
  if (r.id.startsWith(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */])) {
5914
- const date = moment6.utc(
7931
+ const date = moment8.utc(
5915
7932
  r.id.substr(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */].length),
5916
- REVIEW_TIME_FORMAT
7933
+ REVIEW_TIME_FORMAT2
5917
7934
  );
5918
7935
  if (targetDate.isAfter(date)) {
5919
7936
  if (course_id === void 0 || r.doc.courseId === course_id) {
@@ -5924,11 +7941,11 @@ Currently logged-in as ${this._username}.`
5924
7941
  }).map((r) => r.doc);
5925
7942
  }
5926
7943
  async getReviewsForcast(daysCount, course_id) {
5927
- const time = moment6.utc().add(daysCount, "days");
7944
+ const time = moment8.utc().add(daysCount, "days");
5928
7945
  return this.getReviewstoDate(time, course_id);
5929
7946
  }
5930
7947
  async getPendingReviews(course_id) {
5931
- const now = moment6.utc();
7948
+ const now = moment8.utc();
5932
7949
  return this.getReviewstoDate(now, course_id);
5933
7950
  }
5934
7951
  async getScheduledReviewCount(course_id) {
@@ -6304,15 +8321,20 @@ Currently logged-in as ${this._username}.`
6304
8321
  */
6305
8322
  async putCardRecord(record) {
6306
8323
  const cardHistoryID = getCardHistoryID(record.courseID, record.cardID);
6307
- record.timeStamp = moment6.utc(record.timeStamp).toString();
8324
+ record.timeStamp = moment8.utc(record.timeStamp).toString();
6308
8325
  try {
6309
8326
  const cardHistory = await this.update(
6310
8327
  cardHistoryID,
6311
8328
  function(h) {
6312
8329
  h.records.push(record);
6313
8330
  h.bestInterval = h.bestInterval || 0;
6314
- h.lapses = h.lapses || 0;
6315
- h.streak = h.streak || 0;
8331
+ if (areQuestionRecords(h)) {
8332
+ h.lapses = getLapses(h.records);
8333
+ h.streak = getStreak(h.records);
8334
+ } else {
8335
+ h.lapses = h.lapses || 0;
8336
+ h.streak = h.streak || 0;
8337
+ }
6316
8338
  return h;
6317
8339
  }
6318
8340
  );
@@ -6320,7 +8342,7 @@ Currently logged-in as ${this._username}.`
6320
8342
  const ret = {
6321
8343
  ...record2
6322
8344
  };
6323
- ret.timeStamp = moment6.utc(record2.timeStamp);
8345
+ ret.timeStamp = moment8.utc(record2.timeStamp);
6324
8346
  return ret;
6325
8347
  });
6326
8348
  return cardHistory;
@@ -6421,7 +8443,7 @@ Currently logged-in as ${this._username}.`
6421
8443
  if (course_id) {
6422
8444
  filterPrefix += `-${course_id}-`;
6423
8445
  }
6424
- const docs = await filterAllDocsByPrefix(this.localDB, filterPrefix, {
8446
+ const docs = await filterAllDocsByPrefix2(this.localDB, filterPrefix, {
6425
8447
  include_docs: false
6426
8448
  });
6427
8449
  const ret = [];
@@ -6437,7 +8459,7 @@ Currently logged-in as ${this._username}.`
6437
8459
  * @returns A promise of the cards that the user has seen in the past.
6438
8460
  */
6439
8461
  async getHistory() {
6440
- const cards = await filterAllDocsByPrefix(
8462
+ const cards = await filterAllDocsByPrefix2(
6441
8463
  this.remoteDB,
6442
8464
  DocTypePrefixes["CARDRECORD" /* CARDRECORD */],
6443
8465
  {
@@ -6604,7 +8626,7 @@ Currently logged-in as ${this._username}.`
6604
8626
  }
6605
8627
  async getStudySessions(courseId) {
6606
8628
  const prefix = courseId ? `${DocTypePrefixes["STUDY_SESSION" /* STUDY_SESSION */]}::${courseId}::` : `${DocTypePrefixes["STUDY_SESSION" /* STUDY_SESSION */]}::`;
6607
- const keys = getStartAndEndKeys(prefix);
8629
+ const keys = getStartAndEndKeys2(prefix);
6608
8630
  const res = await this.localDB.allDocs({
6609
8631
  startkey: keys.startkey,
6610
8632
  endkey: keys.endkey,
@@ -6678,16 +8700,6 @@ var init_factory = __esm({
6678
8700
  }
6679
8701
  });
6680
8702
 
6681
- // src/study/TagFilteredContentSource.ts
6682
- import { hasActiveFilter } from "@vue-skuilder/common";
6683
- var init_TagFilteredContentSource = __esm({
6684
- "src/study/TagFilteredContentSource.ts"() {
6685
- "use strict";
6686
- init_courseDB();
6687
- init_logger();
6688
- }
6689
- });
6690
-
6691
8703
  // src/core/interfaces/contentSource.ts
6692
8704
  import { hasActiveFilter as hasActiveFilter2 } from "@vue-skuilder/common";
6693
8705
  var init_contentSource = __esm({
@@ -6757,14 +8769,6 @@ var init_userOutcome = __esm({
6757
8769
  }
6758
8770
  });
6759
8771
 
6760
- // src/core/types/studySession.ts
6761
- var init_studySession = __esm({
6762
- "src/core/types/studySession.ts"() {
6763
- "use strict";
6764
- init_types_legacy();
6765
- }
6766
- });
6767
-
6768
8772
  // src/core/types/hydration.ts
6769
8773
  var HYDRATION_MARKER_ID;
6770
8774
  var init_hydration = __esm({
@@ -6784,7 +8788,7 @@ var init_cardProcessor = __esm({
6784
8788
  });
6785
8789
 
6786
8790
  // src/core/bulkImport/types.ts
6787
- var init_types3 = __esm({
8791
+ var init_types5 = __esm({
6788
8792
  "src/core/bulkImport/types.ts"() {
6789
8793
  "use strict";
6790
8794
  }
@@ -6795,7 +8799,7 @@ var init_bulkImport = __esm({
6795
8799
  "src/core/bulkImport/index.ts"() {
6796
8800
  "use strict";
6797
8801
  init_cardProcessor();
6798
- init_types3();
8802
+ init_types5();
6799
8803
  }
6800
8804
  });
6801
8805
 
@@ -6934,7 +8938,7 @@ var init_UserDBDebugger = __esm({
6934
8938
  const rawDB = getRawDB();
6935
8939
  if (!rawDB) return;
6936
8940
  try {
6937
- const result = await filterAllDocsByPrefix(rawDB, DocTypePrefixes["CARDRECORD" /* CARDRECORD */]);
8941
+ const result = await filterAllDocsByPrefix2(rawDB, DocTypePrefixes["CARDRECORD" /* CARDRECORD */]);
6938
8942
  const cardHistories = result.rows.filter((row) => row.doc && row.doc.cardID === cardId).map((row) => row.doc);
6939
8943
  console.group(`\u{1F3B4} Card History: ${cardId}`);
6940
8944
  logger.info(`Total interactions: ${cardHistories.length}`);
@@ -6971,7 +8975,7 @@ var init_UserDBDebugger = __esm({
6971
8975
  logger.info(`Unknown document type: ${docType}`);
6972
8976
  return;
6973
8977
  }
6974
- const result = await filterAllDocsByPrefix(rawDB, prefix);
8978
+ const result = await filterAllDocsByPrefix2(rawDB, prefix);
6975
8979
  console.group(`\u{1F4C4} Documents: ${docType}`);
6976
8980
  logger.info(`Total: ${result.rows.length}`);
6977
8981
  logger.info(`Prefix: ${prefix}`);
@@ -7154,7 +9158,7 @@ var init_core = __esm({
7154
9158
  });
7155
9159
 
7156
9160
  // src/impl/static/StaticDataUnpacker.ts
7157
- var pathUtils, nodeFS, StaticDataUnpacker;
9161
+ var pathUtils, nodeFS3, StaticDataUnpacker;
7158
9162
  var init_StaticDataUnpacker = __esm({
7159
9163
  "src/impl/static/StaticDataUnpacker.ts"() {
7160
9164
  "use strict";
@@ -7171,10 +9175,10 @@ var init_StaticDataUnpacker = __esm({
7171
9175
  return false;
7172
9176
  }
7173
9177
  };
7174
- nodeFS = null;
9178
+ nodeFS3 = null;
7175
9179
  try {
7176
9180
  if (typeof window === "undefined" && typeof process !== "undefined" && process.versions?.node) {
7177
- nodeFS = eval("require")("fs");
9181
+ nodeFS3 = eval("require")("fs");
7178
9182
  }
7179
9183
  } catch {
7180
9184
  }
@@ -7361,8 +9365,8 @@ var init_StaticDataUnpacker = __esm({
7361
9365
  const chunkPath = `${this.basePath}/${chunk.path}`;
7362
9366
  logger.debug(`Loading chunk from ${chunkPath}`);
7363
9367
  let documents;
7364
- if (this.isLocalPath(chunkPath) && nodeFS) {
7365
- const fileContent = await nodeFS.promises.readFile(chunkPath, "utf8");
9368
+ if (this.isLocalPath(chunkPath) && nodeFS3) {
9369
+ const fileContent = await nodeFS3.promises.readFile(chunkPath, "utf8");
7366
9370
  documents = JSON.parse(fileContent);
7367
9371
  } else {
7368
9372
  const response = await fetch(chunkPath);
@@ -7400,8 +9404,8 @@ var init_StaticDataUnpacker = __esm({
7400
9404
  const indexPath = `${this.basePath}/${indexMeta.path}`;
7401
9405
  logger.debug(`Loading index from ${indexPath}`);
7402
9406
  let indexData;
7403
- if (this.isLocalPath(indexPath) && nodeFS) {
7404
- const fileContent = await nodeFS.promises.readFile(indexPath, "utf8");
9407
+ if (this.isLocalPath(indexPath) && nodeFS3) {
9408
+ const fileContent = await nodeFS3.promises.readFile(indexPath, "utf8");
7405
9409
  indexData = JSON.parse(fileContent);
7406
9410
  } else {
7407
9411
  const response = await fetch(indexPath);
@@ -7476,8 +9480,8 @@ var init_StaticDataUnpacker = __esm({
7476
9480
  return null;
7477
9481
  }
7478
9482
  try {
7479
- if (this.isLocalPath(attachmentPath) && nodeFS) {
7480
- const buffer = await nodeFS.promises.readFile(attachmentPath);
9483
+ if (this.isLocalPath(attachmentPath) && nodeFS3) {
9484
+ const buffer = await nodeFS3.promises.readFile(attachmentPath);
7481
9485
  return buffer;
7482
9486
  } else {
7483
9487
  const response = await fetch(attachmentPath);