@vue-skuilder/db 0.2.24 → 0.2.25

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