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