@vue-skuilder/db 0.2.24 → 0.2.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/{contentSource-jBskhS2Y.d.cts → contentSource-CrRnbjBx.d.cts} +13 -2
  2. package/dist/{contentSource-Z9lQOuu5.d.ts → contentSource-kD35o65m.d.ts} +13 -2
  3. package/dist/core/index.d.cts +3 -3
  4. package/dist/core/index.d.ts +3 -3
  5. package/dist/core/index.js +2474 -481
  6. package/dist/core/index.js.map +1 -1
  7. package/dist/core/index.mjs +2464 -466
  8. package/dist/core/index.mjs.map +1 -1
  9. package/dist/{dataLayerProvider-CvSh3KW-.d.ts → dataLayerProvider-CtzddVdy.d.ts} +1 -1
  10. package/dist/{dataLayerProvider-DbA3d_Pd.d.cts → dataLayerProvider-IecbidDO.d.cts} +1 -1
  11. package/dist/impl/couch/index.d.cts +2 -2
  12. package/dist/impl/couch/index.d.ts +2 -2
  13. package/dist/impl/couch/index.js +2237 -238
  14. package/dist/impl/couch/index.js.map +1 -1
  15. package/dist/impl/couch/index.mjs +2231 -227
  16. package/dist/impl/couch/index.mjs.map +1 -1
  17. package/dist/impl/static/index.d.cts +2 -2
  18. package/dist/impl/static/index.d.ts +2 -2
  19. package/dist/impl/static/index.js +2319 -320
  20. package/dist/impl/static/index.js.map +1 -1
  21. package/dist/impl/static/index.mjs +2309 -305
  22. package/dist/impl/static/index.mjs.map +1 -1
  23. package/dist/index.d.cts +3 -3
  24. package/dist/index.d.ts +3 -3
  25. package/dist/index.js +8155 -7955
  26. package/dist/index.js.map +1 -1
  27. package/dist/index.mjs +8050 -7851
  28. package/dist/index.mjs.map +1 -1
  29. package/package.json +3 -3
  30. package/src/impl/common/BaseUserDB.ts +13 -4
  31. package/src/study/SpacedRepetition.ts +11 -2
  32. package/src/study/services/EloService.ts +20 -1
  33. package/src/study/services/tagRecent.test.ts +101 -0
  34. package/src/study/services/tagRecent.ts +70 -0
@@ -6772,6 +6772,12 @@ var init_hydration = __esm({
6772
6772
  });
6773
6773
 
6774
6774
  // src/core/util/index.ts
6775
+ function areQuestionRecords(h) {
6776
+ return isQuestionRecord(h.records[0]);
6777
+ }
6778
+ function isQuestionRecord(c) {
6779
+ return c.userAnswer !== void 0;
6780
+ }
6775
6781
  function getCardHistoryID(courseID, cardID) {
6776
6782
  return `${DocTypePrefixes["CARDRECORD" /* CARDRECORD */]}-${courseID}-${cardID}`;
6777
6783
  }
@@ -7028,257 +7034,2249 @@ var init_UserDBDebugger = __esm({
7028
7034
  }
7029
7035
  },
7030
7036
  /**
7031
- * Show course registrations
7037
+ * Show course registrations
7038
+ */
7039
+ async showCourseRegistrations() {
7040
+ const userDB = getUserDB();
7041
+ if (!userDB) return;
7042
+ try {
7043
+ const registrations = await userDB.getActiveCourses();
7044
+ console.group("\u{1F4DA} Course Registrations");
7045
+ logger.info(`Total: ${registrations.length}`);
7046
+ if (registrations.length > 0) {
7047
+ console.table(
7048
+ registrations.map((reg) => ({
7049
+ courseId: reg.courseID,
7050
+ status: reg.status || "active",
7051
+ elo: typeof reg.elo === "number" ? reg.elo.toFixed(0) : reg.elo?.global?.score?.toFixed(0) || "N/A"
7052
+ }))
7053
+ );
7054
+ }
7055
+ console.groupEnd();
7056
+ } catch (err) {
7057
+ logger.info(`Error loading course registrations: ${err.message}`);
7058
+ }
7059
+ },
7060
+ /**
7061
+ * Show card history for a specific card
7062
+ */
7063
+ async showCardHistory(cardId) {
7064
+ const rawDB = getRawDB();
7065
+ if (!rawDB) return;
7066
+ try {
7067
+ const result = await filterAllDocsByPrefix2(rawDB, DocTypePrefixes["CARDRECORD" /* CARDRECORD */]);
7068
+ const cardHistories = result.rows.filter((row) => row.doc && row.doc.cardID === cardId).map((row) => row.doc);
7069
+ console.group(`\u{1F3B4} Card History: ${cardId}`);
7070
+ logger.info(`Total interactions: ${cardHistories.length}`);
7071
+ if (cardHistories.length > 0) {
7072
+ const sorted = cardHistories.sort(
7073
+ (a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
7074
+ );
7075
+ console.table(
7076
+ sorted.slice(0, 20).map((doc) => ({
7077
+ time: formatTimestamp(doc.timestamp),
7078
+ outcome: doc.outcome || "N/A",
7079
+ duration: doc.duration ? `${(doc.duration / 1e3).toFixed(1)}s` : "N/A",
7080
+ courseId: doc.courseId
7081
+ }))
7082
+ );
7083
+ if (sorted.length > 20) {
7084
+ logger.info(`... and ${sorted.length - 20} more interactions`);
7085
+ }
7086
+ }
7087
+ console.groupEnd();
7088
+ } catch (err) {
7089
+ logger.info(`Error loading card history: ${err.message}`);
7090
+ }
7091
+ },
7092
+ /**
7093
+ * Query documents by type
7094
+ */
7095
+ async queryByType(docType, limit = 50) {
7096
+ const rawDB = getRawDB();
7097
+ if (!rawDB) return;
7098
+ try {
7099
+ const prefix = DocTypePrefixes[DocType[docType]];
7100
+ if (!prefix) {
7101
+ logger.info(`Unknown document type: ${docType}`);
7102
+ return;
7103
+ }
7104
+ const result = await filterAllDocsByPrefix2(rawDB, prefix);
7105
+ console.group(`\u{1F4C4} Documents: ${docType}`);
7106
+ logger.info(`Total: ${result.rows.length}`);
7107
+ logger.info(`Prefix: ${prefix}`);
7108
+ if (result.rows.length > 0) {
7109
+ logger.info("Sample documents:");
7110
+ const samples = result.rows.slice(0, Math.min(limit, result.rows.length));
7111
+ for (const row of samples) {
7112
+ logger.info(`
7113
+ ${row.id}:`);
7114
+ logger.info(JSON.stringify(row.doc, null, 2));
7115
+ }
7116
+ if (result.rows.length > limit) {
7117
+ logger.info(`
7118
+ ... and ${result.rows.length - limit} more documents`);
7119
+ }
7120
+ }
7121
+ console.groupEnd();
7122
+ } catch (err) {
7123
+ logger.info(`Error querying documents: ${err.message}`);
7124
+ }
7125
+ },
7126
+ /**
7127
+ * Show database info and statistics
7128
+ */
7129
+ async dbInfo() {
7130
+ const rawDB = getRawDB();
7131
+ if (!rawDB) return;
7132
+ try {
7133
+ const info = await rawDB.info();
7134
+ console.group("\u2139\uFE0F Database Information");
7135
+ logger.info(`Database name: ${info.db_name}`);
7136
+ logger.info(`Total documents: ${info.doc_count}`);
7137
+ logger.info(`Update sequence: ${info.update_seq}`);
7138
+ if ("disk_size" in info) {
7139
+ logger.info(`Disk size: ${(info.disk_size || 0) / 1024 / 1024} MB`);
7140
+ }
7141
+ logger.info("\nDocument counts by type:");
7142
+ const allDocs = await rawDB.allDocs({ include_docs: false });
7143
+ const typeCounts = /* @__PURE__ */ new Map();
7144
+ for (const row of allDocs.rows) {
7145
+ let prefix = "other";
7146
+ for (const [type, typePrefix] of Object.entries(DocTypePrefixes)) {
7147
+ if (row.id.startsWith(typePrefix)) {
7148
+ prefix = type;
7149
+ break;
7150
+ }
7151
+ }
7152
+ typeCounts.set(prefix, (typeCounts.get(prefix) || 0) + 1);
7153
+ }
7154
+ console.table(
7155
+ Array.from(typeCounts.entries()).sort((a, b) => b[1] - a[1]).map(([type, count]) => ({ type, count }))
7156
+ );
7157
+ console.groupEnd();
7158
+ } catch (err) {
7159
+ logger.info(`Error getting database info: ${err.message}`);
7160
+ }
7161
+ },
7162
+ /**
7163
+ * List all document types
7164
+ */
7165
+ listDocTypes() {
7166
+ console.group("\u{1F4CB} Available Document Types");
7167
+ logger.info("Use with queryByType(type):");
7168
+ for (const [type, prefix] of Object.entries(DocTypePrefixes)) {
7169
+ logger.info(` ${type.padEnd(30)} \u2192 prefix: "${prefix}"`);
7170
+ }
7171
+ console.groupEnd();
7172
+ },
7173
+ /**
7174
+ * Export database contents (limited, for debugging)
7175
+ */
7176
+ async export(includeContent = false) {
7177
+ const rawDB = getRawDB();
7178
+ const userDB = getUserDB();
7179
+ if (!rawDB || !userDB) return "{}";
7180
+ try {
7181
+ const data = {
7182
+ username: userDB.getUsername(),
7183
+ loggedIn: userDB.isLoggedIn(),
7184
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
7185
+ };
7186
+ if (includeContent) {
7187
+ const allDocs = await rawDB.allDocs({ include_docs: true });
7188
+ data.documents = allDocs.rows.map((row) => ({
7189
+ id: row.id,
7190
+ doc: row.doc
7191
+ }));
7192
+ data.totalDocs = allDocs.rows.length;
7193
+ } else {
7194
+ const allDocs = await rawDB.allDocs({ include_docs: false });
7195
+ data.totalDocs = allDocs.rows.length;
7196
+ const typeCounts = /* @__PURE__ */ new Map();
7197
+ for (const row of allDocs.rows) {
7198
+ let prefix = "other";
7199
+ for (const [type, typePrefix] of Object.entries(DocTypePrefixes)) {
7200
+ if (row.id.startsWith(typePrefix)) {
7201
+ prefix = type;
7202
+ break;
7203
+ }
7204
+ }
7205
+ typeCounts.set(prefix, (typeCounts.get(prefix) || 0) + 1);
7206
+ }
7207
+ data.docCounts = Object.fromEntries(typeCounts);
7208
+ }
7209
+ const json = JSON.stringify(data, null, 2);
7210
+ logger.info("[UserDB Debug] Database info exported. Copy the returned string or use:");
7211
+ logger.info(" copy(window.skuilder.userdb.export())");
7212
+ if (!includeContent) {
7213
+ logger.info(" For full content export: window.skuilder.userdb.export(true)");
7214
+ }
7215
+ return json;
7216
+ } catch (err) {
7217
+ logger.info(`Error exporting database: ${err.message}`);
7218
+ return "{}";
7219
+ }
7220
+ },
7221
+ /**
7222
+ * Execute raw PouchDB query
7223
+ */
7224
+ async raw(queryFn) {
7225
+ const rawDB = getRawDB();
7226
+ if (!rawDB) return;
7227
+ try {
7228
+ const result = await queryFn(rawDB);
7229
+ logger.info("[UserDB Debug] Query result:");
7230
+ logger.info(result);
7231
+ } catch (err) {
7232
+ logger.info(`[UserDB Debug] Query error: ${err.message}`);
7233
+ }
7234
+ },
7235
+ /**
7236
+ * Show help
7237
+ */
7238
+ help() {
7239
+ logger.info(`
7240
+ \u{1F527} UserDB Debug API
7241
+
7242
+ Commands:
7243
+ .showUser() Show current user info and config
7244
+ .showScheduledReviews(courseId?) Show scheduled reviews (optionally filter by course)
7245
+ .showCourseRegistrations() Show all course registrations
7246
+ .showCardHistory(cardId) Show interaction history for a card
7247
+ .queryByType(docType, limit?) Query documents by type (e.g., 'SCHEDULED_CARD')
7248
+ .listDocTypes() List all available document types
7249
+ .dbInfo() Show database info and statistics
7250
+ .export(includeContent?) Export database info (true = include all docs)
7251
+ .raw(queryFn) Execute raw PouchDB query
7252
+ .help() Show this help message
7253
+
7254
+ Examples:
7255
+ window.skuilder.userdb.showUser()
7256
+ window.skuilder.userdb.showScheduledReviews('course123')
7257
+ window.skuilder.userdb.queryByType('SCHEDULED_CARD', 10)
7258
+ window.skuilder.userdb.raw(db => db.allDocs({ limit: 5 }))
7259
+ `);
7260
+ }
7261
+ };
7262
+ mountUserDBDebugger();
7263
+ }
7264
+ });
7265
+
7266
+ // src/core/index.ts
7267
+ var init_core = __esm({
7268
+ "src/core/index.ts"() {
7269
+ "use strict";
7270
+ init_interfaces();
7271
+ init_types_legacy();
7272
+ init_user();
7273
+ init_strategyState();
7274
+ init_userOutcome();
7275
+ init_studySession();
7276
+ init_hydration();
7277
+ init_Loggable();
7278
+ init_util();
7279
+ init_navigators();
7280
+ init_bulkImport();
7281
+ init_orchestration();
7282
+ init_UserDBDebugger();
7283
+ }
7284
+ });
7285
+
7286
+ // src/study/SpacedRepetition.ts
7287
+ import moment4 from "moment";
7288
+ import { isTaggedPerformance } from "@vue-skuilder/common";
7289
+ function getStreak(records) {
7290
+ let streak = 0;
7291
+ let index = records.length - 1;
7292
+ while (index >= 0 && records[index].isCorrect) {
7293
+ index--;
7294
+ streak++;
7295
+ }
7296
+ return streak;
7297
+ }
7298
+ function getLapses(records) {
7299
+ return records.filter((r) => r.isCorrect === false).length;
7300
+ }
7301
+ var duration;
7302
+ var init_SpacedRepetition = __esm({
7303
+ "src/study/SpacedRepetition.ts"() {
7304
+ "use strict";
7305
+ init_util();
7306
+ init_logger();
7307
+ duration = moment4.duration;
7308
+ }
7309
+ });
7310
+
7311
+ // src/study/services/SrsService.ts
7312
+ import moment5 from "moment";
7313
+ var init_SrsService = __esm({
7314
+ "src/study/services/SrsService.ts"() {
7315
+ "use strict";
7316
+ init_couch();
7317
+ init_SpacedRepetition();
7318
+ init_logger();
7319
+ }
7320
+ });
7321
+
7322
+ // src/study/services/tagRecent.ts
7323
+ import {
7324
+ pushTagPresentation
7325
+ } from "@vue-skuilder/common";
7326
+ var init_tagRecent = __esm({
7327
+ "src/study/services/tagRecent.ts"() {
7328
+ "use strict";
7329
+ }
7330
+ });
7331
+
7332
+ // src/study/services/EloService.ts
7333
+ import {
7334
+ adjustCourseScores,
7335
+ adjustCourseScoresPerTag,
7336
+ toCourseElo as toCourseElo7
7337
+ } from "@vue-skuilder/common";
7338
+ var init_EloService = __esm({
7339
+ "src/study/services/EloService.ts"() {
7340
+ "use strict";
7341
+ init_logger();
7342
+ init_tagRecent();
7343
+ }
7344
+ });
7345
+
7346
+ // src/study/services/ResponseProcessor.ts
7347
+ import { isTaggedPerformance as isTaggedPerformance2 } from "@vue-skuilder/common";
7348
+ var init_ResponseProcessor = __esm({
7349
+ "src/study/services/ResponseProcessor.ts"() {
7350
+ "use strict";
7351
+ init_core();
7352
+ init_logger();
7353
+ }
7354
+ });
7355
+
7356
+ // src/study/services/CardHydrationService.ts
7357
+ import {
7358
+ displayableDataToViewData,
7359
+ isCourseElo,
7360
+ toCourseElo as toCourseElo8
7361
+ } from "@vue-skuilder/common";
7362
+ var init_CardHydrationService = __esm({
7363
+ "src/study/services/CardHydrationService.ts"() {
7364
+ "use strict";
7365
+ init_logger();
7366
+ }
7367
+ });
7368
+
7369
+ // src/study/ItemQueue.ts
7370
+ var init_ItemQueue = __esm({
7371
+ "src/study/ItemQueue.ts"() {
7372
+ "use strict";
7373
+ }
7374
+ });
7375
+
7376
+ // src/util/packer/types.ts
7377
+ var init_types4 = __esm({
7378
+ "src/util/packer/types.ts"() {
7379
+ "use strict";
7380
+ }
7381
+ });
7382
+
7383
+ // src/util/packer/CouchDBToStaticPacker.ts
7384
+ var init_CouchDBToStaticPacker = __esm({
7385
+ "src/util/packer/CouchDBToStaticPacker.ts"() {
7386
+ "use strict";
7387
+ init_types_legacy();
7388
+ init_logger();
7389
+ }
7390
+ });
7391
+
7392
+ // src/util/packer/index.ts
7393
+ var init_packer = __esm({
7394
+ "src/util/packer/index.ts"() {
7395
+ "use strict";
7396
+ init_types4();
7397
+ init_CouchDBToStaticPacker();
7398
+ }
7399
+ });
7400
+
7401
+ // src/util/migrator/types.ts
7402
+ var DEFAULT_MIGRATION_OPTIONS;
7403
+ var init_types5 = __esm({
7404
+ "src/util/migrator/types.ts"() {
7405
+ "use strict";
7406
+ DEFAULT_MIGRATION_OPTIONS = {
7407
+ chunkBatchSize: 100,
7408
+ validateRoundTrip: false,
7409
+ cleanupOnFailure: true,
7410
+ timeout: 3e5
7411
+ // 5 minutes
7412
+ };
7413
+ }
7414
+ });
7415
+
7416
+ // src/util/migrator/FileSystemAdapter.ts
7417
+ var FileSystemError;
7418
+ var init_FileSystemAdapter = __esm({
7419
+ "src/util/migrator/FileSystemAdapter.ts"() {
7420
+ "use strict";
7421
+ FileSystemError = class extends Error {
7422
+ constructor(message, operation, filePath, cause) {
7423
+ super(message);
7424
+ this.operation = operation;
7425
+ this.filePath = filePath;
7426
+ this.cause = cause;
7427
+ this.name = "FileSystemError";
7428
+ }
7429
+ };
7430
+ }
7431
+ });
7432
+
7433
+ // src/util/migrator/validation.ts
7434
+ async function validateStaticCourse(staticPath, fs) {
7435
+ const validation = {
7436
+ valid: true,
7437
+ manifestExists: false,
7438
+ chunksExist: false,
7439
+ attachmentsExist: false,
7440
+ errors: [],
7441
+ warnings: []
7442
+ };
7443
+ try {
7444
+ if (fs) {
7445
+ const stats = await fs.stat(staticPath);
7446
+ if (!stats.isDirectory()) {
7447
+ validation.errors.push(`Path is not a directory: ${staticPath}`);
7448
+ validation.valid = false;
7449
+ return validation;
7450
+ }
7451
+ } else if (!nodeFS) {
7452
+ validation.errors.push("File system access not available - validation skipped");
7453
+ validation.valid = false;
7454
+ return validation;
7455
+ } else {
7456
+ const stats = await nodeFS.promises.stat(staticPath);
7457
+ if (!stats.isDirectory()) {
7458
+ validation.errors.push(`Path is not a directory: ${staticPath}`);
7459
+ validation.valid = false;
7460
+ return validation;
7461
+ }
7462
+ }
7463
+ let manifestPath = `${staticPath}/manifest.json`;
7464
+ try {
7465
+ if (fs) {
7466
+ manifestPath = fs.joinPath(staticPath, "manifest.json");
7467
+ if (await fs.exists(manifestPath)) {
7468
+ validation.manifestExists = true;
7469
+ const manifestContent = await fs.readFile(manifestPath);
7470
+ const manifest = JSON.parse(manifestContent);
7471
+ validation.courseId = manifest.courseId;
7472
+ validation.courseName = manifest.courseName;
7473
+ if (!manifest.version || !manifest.courseId || !manifest.chunks || !Array.isArray(manifest.chunks)) {
7474
+ validation.errors.push("Invalid manifest structure");
7475
+ validation.valid = false;
7476
+ }
7477
+ } else {
7478
+ validation.errors.push(`Manifest not found: ${manifestPath}`);
7479
+ validation.valid = false;
7480
+ }
7481
+ } else {
7482
+ manifestPath = `${staticPath}/manifest.json`;
7483
+ await nodeFS.promises.access(manifestPath);
7484
+ validation.manifestExists = true;
7485
+ const manifestContent = await nodeFS.promises.readFile(manifestPath, "utf8");
7486
+ const manifest = JSON.parse(manifestContent);
7487
+ validation.courseId = manifest.courseId;
7488
+ validation.courseName = manifest.courseName;
7489
+ if (!manifest.version || !manifest.courseId || !manifest.chunks || !Array.isArray(manifest.chunks)) {
7490
+ validation.errors.push("Invalid manifest structure");
7491
+ validation.valid = false;
7492
+ }
7493
+ }
7494
+ } catch (error) {
7495
+ const errorMessage = error instanceof FileSystemError ? error.message : `Manifest not found or invalid: ${manifestPath}`;
7496
+ validation.errors.push(errorMessage);
7497
+ validation.valid = false;
7498
+ }
7499
+ let chunksPath = `${staticPath}/chunks`;
7500
+ try {
7501
+ if (fs) {
7502
+ chunksPath = fs.joinPath(staticPath, "chunks");
7503
+ if (await fs.exists(chunksPath)) {
7504
+ const chunksStats = await fs.stat(chunksPath);
7505
+ if (chunksStats.isDirectory()) {
7506
+ validation.chunksExist = true;
7507
+ } else {
7508
+ validation.errors.push(`Chunks path is not a directory: ${chunksPath}`);
7509
+ validation.valid = false;
7510
+ }
7511
+ } else {
7512
+ validation.errors.push(`Chunks directory not found: ${chunksPath}`);
7513
+ validation.valid = false;
7514
+ }
7515
+ } else {
7516
+ chunksPath = `${staticPath}/chunks`;
7517
+ const chunksStats = await nodeFS.promises.stat(chunksPath);
7518
+ if (chunksStats.isDirectory()) {
7519
+ validation.chunksExist = true;
7520
+ } else {
7521
+ validation.errors.push(`Chunks path is not a directory: ${chunksPath}`);
7522
+ validation.valid = false;
7523
+ }
7524
+ }
7525
+ } catch (error) {
7526
+ const errorMessage = error instanceof FileSystemError ? error.message : `Chunks directory not found: ${chunksPath}`;
7527
+ validation.errors.push(errorMessage);
7528
+ validation.valid = false;
7529
+ }
7530
+ let attachmentsPath;
7531
+ try {
7532
+ if (fs) {
7533
+ attachmentsPath = fs.joinPath(staticPath, "attachments");
7534
+ if (await fs.exists(attachmentsPath)) {
7535
+ const attachmentsStats = await fs.stat(attachmentsPath);
7536
+ if (attachmentsStats.isDirectory()) {
7537
+ validation.attachmentsExist = true;
7538
+ }
7539
+ } else {
7540
+ validation.warnings.push(
7541
+ `Attachments directory not found: ${attachmentsPath} (this is OK if course has no attachments)`
7542
+ );
7543
+ }
7544
+ } else {
7545
+ attachmentsPath = `${staticPath}/attachments`;
7546
+ const attachmentsStats = await nodeFS.promises.stat(attachmentsPath);
7547
+ if (attachmentsStats.isDirectory()) {
7548
+ validation.attachmentsExist = true;
7549
+ }
7550
+ }
7551
+ } catch (error) {
7552
+ attachmentsPath = attachmentsPath || `${staticPath}/attachments`;
7553
+ const warningMessage = error instanceof FileSystemError ? error.message : `Attachments directory not found: ${attachmentsPath} (this is OK if course has no attachments)`;
7554
+ validation.warnings.push(warningMessage);
7555
+ }
7556
+ } catch (error) {
7557
+ validation.errors.push(
7558
+ `Failed to validate static course: ${error instanceof Error ? error.message : String(error)}`
7559
+ );
7560
+ validation.valid = false;
7561
+ }
7562
+ return validation;
7563
+ }
7564
+ async function validateMigration(targetDB, expectedCounts, manifest) {
7565
+ const validation = {
7566
+ valid: true,
7567
+ documentCountMatch: false,
7568
+ attachmentIntegrity: false,
7569
+ viewFunctionality: false,
7570
+ issues: []
7571
+ };
7572
+ try {
7573
+ logger.info("Starting migration validation...");
7574
+ const actualCounts = await getActualDocumentCounts(targetDB);
7575
+ validation.documentCountMatch = compareDocumentCounts(
7576
+ expectedCounts,
7577
+ actualCounts,
7578
+ validation.issues
7579
+ );
7580
+ await validateCourseConfig(targetDB, manifest, validation.issues);
7581
+ validation.viewFunctionality = await validateViews(targetDB, manifest, validation.issues);
7582
+ validation.attachmentIntegrity = await validateAttachmentIntegrity(targetDB, validation.issues);
7583
+ validation.valid = validation.documentCountMatch && validation.viewFunctionality && validation.attachmentIntegrity;
7584
+ logger.info(`Migration validation completed. Valid: ${validation.valid}`);
7585
+ if (validation.issues.length > 0) {
7586
+ logger.info(`Validation issues: ${validation.issues.length}`);
7587
+ validation.issues.forEach((issue) => {
7588
+ if (issue.type === "error") {
7589
+ logger.error(`${issue.category}: ${issue.message}`);
7590
+ } else {
7591
+ logger.warn(`${issue.category}: ${issue.message}`);
7592
+ }
7593
+ });
7594
+ }
7595
+ } catch (error) {
7596
+ validation.valid = false;
7597
+ validation.issues.push({
7598
+ type: "error",
7599
+ category: "metadata",
7600
+ message: `Validation failed: ${error instanceof Error ? error.message : String(error)}`
7601
+ });
7602
+ }
7603
+ return validation;
7604
+ }
7605
+ async function getActualDocumentCounts(db) {
7606
+ const counts = {};
7607
+ try {
7608
+ const allDocs = await db.allDocs({ include_docs: true });
7609
+ for (const row of allDocs.rows) {
7610
+ if (row.id.startsWith("_design/")) {
7611
+ counts["_design"] = (counts["_design"] || 0) + 1;
7612
+ continue;
7613
+ }
7614
+ const doc = row.doc;
7615
+ if (doc && doc.docType) {
7616
+ counts[doc.docType] = (counts[doc.docType] || 0) + 1;
7617
+ } else {
7618
+ counts["unknown"] = (counts["unknown"] || 0) + 1;
7619
+ }
7620
+ }
7621
+ } catch (error) {
7622
+ logger.error("Failed to get actual document counts:", error);
7623
+ }
7624
+ return counts;
7625
+ }
7626
+ function compareDocumentCounts(expected, actual, issues) {
7627
+ let countsMatch = true;
7628
+ for (const [docType, expectedCount] of Object.entries(expected)) {
7629
+ const actualCount = actual[docType] || 0;
7630
+ if (actualCount !== expectedCount) {
7631
+ countsMatch = false;
7632
+ issues.push({
7633
+ type: "error",
7634
+ category: "documents",
7635
+ message: `Document count mismatch for ${docType}: expected ${expectedCount}, got ${actualCount}`
7636
+ });
7637
+ }
7638
+ }
7639
+ for (const [docType, actualCount] of Object.entries(actual)) {
7640
+ if (!expected[docType] && docType !== "_design") {
7641
+ issues.push({
7642
+ type: "warning",
7643
+ category: "documents",
7644
+ message: `Unexpected document type found: ${docType} (${actualCount} documents)`
7645
+ });
7646
+ }
7647
+ }
7648
+ return countsMatch;
7649
+ }
7650
+ async function validateCourseConfig(db, manifest, issues) {
7651
+ try {
7652
+ const courseConfig = await db.get("CourseConfig");
7653
+ if (!courseConfig) {
7654
+ issues.push({
7655
+ type: "error",
7656
+ category: "course_config",
7657
+ message: "CourseConfig document not found after migration"
7658
+ });
7659
+ return;
7660
+ }
7661
+ if (!courseConfig.courseID) {
7662
+ issues.push({
7663
+ type: "warning",
7664
+ category: "course_config",
7665
+ message: "CourseConfig document missing courseID field"
7666
+ });
7667
+ }
7668
+ if (courseConfig.courseID !== manifest.courseId) {
7669
+ issues.push({
7670
+ type: "warning",
7671
+ category: "course_config",
7672
+ message: `CourseConfig courseID mismatch: expected ${manifest.courseId}, got ${courseConfig.courseID}`
7673
+ });
7674
+ }
7675
+ logger.debug("CourseConfig document validation passed");
7676
+ } catch (error) {
7677
+ if (error.status === 404) {
7678
+ issues.push({
7679
+ type: "error",
7680
+ category: "course_config",
7681
+ message: "CourseConfig document not found in database"
7682
+ });
7683
+ } else {
7684
+ issues.push({
7685
+ type: "error",
7686
+ category: "course_config",
7687
+ message: `Failed to validate CourseConfig document: ${error instanceof Error ? error.message : String(error)}`
7688
+ });
7689
+ }
7690
+ }
7691
+ }
7692
+ async function validateViews(db, manifest, issues) {
7693
+ let viewsValid = true;
7694
+ try {
7695
+ for (const designDoc of manifest.designDocs) {
7696
+ try {
7697
+ const doc = await db.get(designDoc._id);
7698
+ if (!doc) {
7699
+ viewsValid = false;
7700
+ issues.push({
7701
+ type: "error",
7702
+ category: "views",
7703
+ message: `Design document not found: ${designDoc._id}`
7704
+ });
7705
+ continue;
7706
+ }
7707
+ for (const viewName of Object.keys(designDoc.views)) {
7708
+ try {
7709
+ const viewPath = `${designDoc._id}/${viewName}`;
7710
+ await db.query(viewPath, { limit: 1 });
7711
+ } catch (viewError) {
7712
+ viewsValid = false;
7713
+ issues.push({
7714
+ type: "error",
7715
+ category: "views",
7716
+ message: `View not accessible: ${designDoc._id}/${viewName} - ${viewError}`
7717
+ });
7718
+ }
7719
+ }
7720
+ } catch (error) {
7721
+ viewsValid = false;
7722
+ issues.push({
7723
+ type: "error",
7724
+ category: "views",
7725
+ message: `Failed to validate design document ${designDoc._id}: ${error}`
7726
+ });
7727
+ }
7728
+ }
7729
+ } catch (error) {
7730
+ viewsValid = false;
7731
+ issues.push({
7732
+ type: "error",
7733
+ category: "views",
7734
+ message: `View validation failed: ${error instanceof Error ? error.message : String(error)}`
7735
+ });
7736
+ }
7737
+ return viewsValid;
7738
+ }
7739
+ async function validateAttachmentIntegrity(db, issues) {
7740
+ let attachmentsValid = true;
7741
+ try {
7742
+ const allDocs = await db.allDocs({
7743
+ include_docs: true,
7744
+ limit: 10
7745
+ // Sample first 10 documents for performance
7746
+ });
7747
+ let attachmentCount = 0;
7748
+ let validAttachments = 0;
7749
+ for (const row of allDocs.rows) {
7750
+ const doc = row.doc;
7751
+ if (doc && doc._attachments) {
7752
+ for (const [attachmentName, _attachmentMeta] of Object.entries(doc._attachments)) {
7753
+ attachmentCount++;
7754
+ try {
7755
+ const attachment = await db.getAttachment(doc._id, attachmentName);
7756
+ if (attachment) {
7757
+ validAttachments++;
7758
+ }
7759
+ } catch (attachmentError) {
7760
+ attachmentsValid = false;
7761
+ issues.push({
7762
+ type: "error",
7763
+ category: "attachments",
7764
+ message: `Attachment not accessible: ${doc._id}/${attachmentName} - ${attachmentError}`
7765
+ });
7766
+ }
7767
+ }
7768
+ }
7769
+ }
7770
+ if (attachmentCount === 0) {
7771
+ issues.push({
7772
+ type: "warning",
7773
+ category: "attachments",
7774
+ message: "No attachments found in sampled documents"
7775
+ });
7776
+ } else {
7777
+ logger.info(`Validated ${validAttachments}/${attachmentCount} sampled attachments`);
7778
+ }
7779
+ } catch (error) {
7780
+ attachmentsValid = false;
7781
+ issues.push({
7782
+ type: "error",
7783
+ category: "attachments",
7784
+ message: `Attachment validation failed: ${error instanceof Error ? error.message : String(error)}`
7785
+ });
7786
+ }
7787
+ return attachmentsValid;
7788
+ }
7789
+ var nodeFS;
7790
+ var init_validation = __esm({
7791
+ "src/util/migrator/validation.ts"() {
7792
+ "use strict";
7793
+ init_logger();
7794
+ init_FileSystemAdapter();
7795
+ nodeFS = null;
7796
+ try {
7797
+ if (typeof window === "undefined" && typeof process !== "undefined" && process.versions?.node) {
7798
+ nodeFS = eval("require")("fs");
7799
+ nodeFS.promises = nodeFS.promises || eval("require")("fs").promises;
7800
+ }
7801
+ } catch {
7802
+ }
7803
+ }
7804
+ });
7805
+
7806
+ // src/util/migrator/StaticToCouchDBMigrator.ts
7807
+ var nodeFS2, nodePath, StaticToCouchDBMigrator;
7808
+ var init_StaticToCouchDBMigrator = __esm({
7809
+ "src/util/migrator/StaticToCouchDBMigrator.ts"() {
7810
+ "use strict";
7811
+ init_logger();
7812
+ init_types5();
7813
+ init_validation();
7814
+ init_FileSystemAdapter();
7815
+ nodeFS2 = null;
7816
+ nodePath = null;
7817
+ try {
7818
+ if (typeof window === "undefined" && typeof process !== "undefined" && process.versions?.node) {
7819
+ nodeFS2 = eval("require")("fs");
7820
+ nodePath = eval("require")("path");
7821
+ nodeFS2.promises = nodeFS2.promises || eval("require")("fs").promises;
7822
+ }
7823
+ } catch {
7824
+ }
7825
+ StaticToCouchDBMigrator = class {
7826
+ options;
7827
+ progressCallback;
7828
+ fs;
7829
+ constructor(options = {}, fileSystemAdapter) {
7830
+ this.options = {
7831
+ ...DEFAULT_MIGRATION_OPTIONS,
7832
+ ...options
7833
+ };
7834
+ this.fs = fileSystemAdapter;
7835
+ }
7836
+ /**
7837
+ * Set a progress callback to receive updates during migration
7838
+ */
7839
+ setProgressCallback(callback) {
7840
+ this.progressCallback = callback;
7841
+ }
7842
+ /**
7843
+ * Migrate a static course to CouchDB
7844
+ */
7845
+ async migrateCourse(staticPath, targetDB) {
7846
+ const startTime = Date.now();
7847
+ const result = {
7848
+ success: false,
7849
+ documentsRestored: 0,
7850
+ attachmentsRestored: 0,
7851
+ designDocsRestored: 0,
7852
+ courseConfigRestored: 0,
7853
+ errors: [],
7854
+ warnings: [],
7855
+ migrationTime: 0
7856
+ };
7857
+ try {
7858
+ logger.info(`Starting migration from ${staticPath} to CouchDB`);
7859
+ this.reportProgress("manifest", 0, 1, "Validating static course...");
7860
+ const validation = await validateStaticCourse(staticPath, this.fs);
7861
+ if (!validation.valid) {
7862
+ result.errors.push(...validation.errors);
7863
+ throw new Error(`Static course validation failed: ${validation.errors.join(", ")}`);
7864
+ }
7865
+ result.warnings.push(...validation.warnings);
7866
+ this.reportProgress("manifest", 1, 1, "Loading course manifest...");
7867
+ const manifest = await this.loadManifest(staticPath);
7868
+ logger.info(`Loaded manifest for course: ${manifest.courseId} (${manifest.courseName})`);
7869
+ this.reportProgress(
7870
+ "design_docs",
7871
+ 0,
7872
+ manifest.designDocs.length,
7873
+ "Restoring design documents..."
7874
+ );
7875
+ const designDocResults = await this.restoreDesignDocuments(manifest.designDocs, targetDB);
7876
+ result.designDocsRestored = designDocResults.restored;
7877
+ result.errors.push(...designDocResults.errors);
7878
+ result.warnings.push(...designDocResults.warnings);
7879
+ this.reportProgress("course_config", 0, 1, "Restoring CourseConfig document...");
7880
+ const courseConfigResults = await this.restoreCourseConfig(manifest, targetDB);
7881
+ result.courseConfigRestored = courseConfigResults.restored;
7882
+ result.errors.push(...courseConfigResults.errors);
7883
+ result.warnings.push(...courseConfigResults.warnings);
7884
+ this.reportProgress("course_config", 1, 1, "CourseConfig document restored");
7885
+ const expectedCounts = this.calculateExpectedCounts(manifest);
7886
+ this.reportProgress(
7887
+ "documents",
7888
+ 0,
7889
+ manifest.documentCount,
7890
+ "Aggregating documents from chunks..."
7891
+ );
7892
+ const documents = await this.aggregateDocuments(staticPath, manifest);
7893
+ const filteredDocuments = documents.filter((doc) => doc._id !== "CourseConfig");
7894
+ if (documents.length !== filteredDocuments.length) {
7895
+ result.warnings.push(
7896
+ `Filtered out ${documents.length - filteredDocuments.length} CourseConfig document(s) from chunks to prevent conflicts`
7897
+ );
7898
+ }
7899
+ this.reportProgress(
7900
+ "documents",
7901
+ filteredDocuments.length,
7902
+ manifest.documentCount,
7903
+ "Uploading documents to CouchDB..."
7904
+ );
7905
+ const docResults = await this.uploadDocuments(filteredDocuments, targetDB);
7906
+ result.documentsRestored = docResults.restored;
7907
+ result.errors.push(...docResults.errors);
7908
+ result.warnings.push(...docResults.warnings);
7909
+ const docsWithAttachments = documents.filter(
7910
+ (doc) => doc._attachments && Object.keys(doc._attachments).length > 0
7911
+ );
7912
+ this.reportProgress("attachments", 0, docsWithAttachments.length, "Uploading attachments...");
7913
+ const attachmentResults = await this.uploadAttachments(
7914
+ staticPath,
7915
+ docsWithAttachments,
7916
+ targetDB
7917
+ );
7918
+ result.attachmentsRestored = attachmentResults.restored;
7919
+ result.errors.push(...attachmentResults.errors);
7920
+ result.warnings.push(...attachmentResults.warnings);
7921
+ if (this.options.validateRoundTrip) {
7922
+ this.reportProgress("validation", 0, 1, "Validating migration...");
7923
+ const validationResult = await validateMigration(targetDB, expectedCounts, manifest);
7924
+ if (!validationResult.valid) {
7925
+ result.warnings.push("Migration validation found issues");
7926
+ validationResult.issues.forEach((issue) => {
7927
+ if (issue.type === "error") {
7928
+ result.errors.push(`Validation: ${issue.message}`);
7929
+ } else {
7930
+ result.warnings.push(`Validation: ${issue.message}`);
7931
+ }
7932
+ });
7933
+ }
7934
+ this.reportProgress("validation", 1, 1, "Migration validation completed");
7935
+ }
7936
+ result.success = result.errors.length === 0;
7937
+ result.migrationTime = Date.now() - startTime;
7938
+ logger.info(`Migration completed in ${result.migrationTime}ms`);
7939
+ logger.info(`Documents restored: ${result.documentsRestored}`);
7940
+ logger.info(`Attachments restored: ${result.attachmentsRestored}`);
7941
+ logger.info(`Design docs restored: ${result.designDocsRestored}`);
7942
+ logger.info(`CourseConfig restored: ${result.courseConfigRestored}`);
7943
+ if (result.errors.length > 0) {
7944
+ logger.error(`Migration completed with ${result.errors.length} errors`);
7945
+ }
7946
+ if (result.warnings.length > 0) {
7947
+ logger.warn(`Migration completed with ${result.warnings.length} warnings`);
7948
+ }
7949
+ } catch (error) {
7950
+ result.success = false;
7951
+ result.migrationTime = Date.now() - startTime;
7952
+ const errorMessage = error instanceof Error ? error.message : String(error);
7953
+ result.errors.push(`Migration failed: ${errorMessage}`);
7954
+ logger.error("Migration failed:", error);
7955
+ if (this.options.cleanupOnFailure) {
7956
+ try {
7957
+ await this.cleanupFailedMigration(targetDB);
7958
+ } catch (cleanupError) {
7959
+ logger.error("Failed to cleanup after migration failure:", cleanupError);
7960
+ result.warnings.push("Failed to cleanup after migration failure");
7961
+ }
7962
+ }
7963
+ }
7964
+ return result;
7965
+ }
7966
+ /**
7967
+ * Load and parse the manifest file
7968
+ */
7969
+ async loadManifest(staticPath) {
7970
+ try {
7971
+ let manifestContent;
7972
+ let manifestPath;
7973
+ if (this.fs) {
7974
+ manifestPath = this.fs.joinPath(staticPath, "manifest.json");
7975
+ manifestContent = await this.fs.readFile(manifestPath);
7976
+ } else {
7977
+ manifestPath = nodeFS2 && nodePath ? nodePath.join(staticPath, "manifest.json") : `${staticPath}/manifest.json`;
7978
+ if (nodeFS2 && this.isLocalPath(staticPath)) {
7979
+ manifestContent = await nodeFS2.promises.readFile(manifestPath, "utf8");
7980
+ } else {
7981
+ const response = await fetch(manifestPath);
7982
+ if (!response.ok) {
7983
+ throw new Error(`Failed to fetch manifest: ${response.status} ${response.statusText}`);
7984
+ }
7985
+ manifestContent = await response.text();
7986
+ }
7987
+ }
7988
+ const manifest = JSON.parse(manifestContent);
7989
+ if (!manifest.version || !manifest.courseId || !manifest.chunks) {
7990
+ throw new Error("Invalid manifest structure");
7991
+ }
7992
+ return manifest;
7993
+ } catch (error) {
7994
+ const errorMessage = error instanceof FileSystemError ? error.message : `Failed to load manifest: ${error instanceof Error ? error.message : String(error)}`;
7995
+ throw new Error(errorMessage);
7996
+ }
7997
+ }
7998
+ /**
7999
+ * Restore design documents to CouchDB
8000
+ */
8001
+ async restoreDesignDocuments(designDocs, db) {
8002
+ const result = { restored: 0, errors: [], warnings: [] };
8003
+ for (let i = 0; i < designDocs.length; i++) {
8004
+ const designDoc = designDocs[i];
8005
+ this.reportProgress("design_docs", i, designDocs.length, `Restoring ${designDoc._id}...`);
8006
+ try {
8007
+ let existingDoc;
8008
+ try {
8009
+ existingDoc = await db.get(designDoc._id);
8010
+ } catch {
8011
+ }
8012
+ const docToInsert = {
8013
+ _id: designDoc._id,
8014
+ views: designDoc.views
8015
+ };
8016
+ if (existingDoc) {
8017
+ docToInsert._rev = existingDoc._rev;
8018
+ logger.debug(`Updating existing design document: ${designDoc._id}`);
8019
+ } else {
8020
+ logger.debug(`Creating new design document: ${designDoc._id}`);
8021
+ }
8022
+ await db.put(docToInsert);
8023
+ result.restored++;
8024
+ } catch (error) {
8025
+ const errorMessage = `Failed to restore design document ${designDoc._id}: ${error instanceof Error ? error.message : String(error)}`;
8026
+ result.errors.push(errorMessage);
8027
+ logger.error(errorMessage);
8028
+ }
8029
+ }
8030
+ this.reportProgress(
8031
+ "design_docs",
8032
+ designDocs.length,
8033
+ designDocs.length,
8034
+ `Restored ${result.restored} design documents`
8035
+ );
8036
+ return result;
8037
+ }
8038
+ /**
8039
+ * Aggregate documents from all chunks
8040
+ */
8041
+ async aggregateDocuments(staticPath, manifest) {
8042
+ const allDocuments = [];
8043
+ const documentMap = /* @__PURE__ */ new Map();
8044
+ for (let i = 0; i < manifest.chunks.length; i++) {
8045
+ const chunk = manifest.chunks[i];
8046
+ this.reportProgress(
8047
+ "documents",
8048
+ allDocuments.length,
8049
+ manifest.documentCount,
8050
+ `Loading chunk ${chunk.id}...`
8051
+ );
8052
+ try {
8053
+ const documents = await this.loadChunk(staticPath, chunk);
8054
+ for (const doc of documents) {
8055
+ if (!doc._id) {
8056
+ logger.warn(`Document without _id found in chunk ${chunk.id}, skipping`);
8057
+ continue;
8058
+ }
8059
+ if (documentMap.has(doc._id)) {
8060
+ logger.warn(`Duplicate document ID found: ${doc._id}, using latest version`);
8061
+ }
8062
+ documentMap.set(doc._id, doc);
8063
+ }
8064
+ } catch (error) {
8065
+ throw new Error(
8066
+ `Failed to load chunk ${chunk.id}: ${error instanceof Error ? error.message : String(error)}`
8067
+ );
8068
+ }
8069
+ }
8070
+ allDocuments.push(...documentMap.values());
8071
+ logger.info(
8072
+ `Aggregated ${allDocuments.length} unique documents from ${manifest.chunks.length} chunks`
8073
+ );
8074
+ return allDocuments;
8075
+ }
8076
+ /**
8077
+ * Load documents from a single chunk file
8078
+ */
8079
+ async loadChunk(staticPath, chunk) {
8080
+ try {
8081
+ let chunkContent;
8082
+ let chunkPath;
8083
+ if (this.fs) {
8084
+ chunkPath = this.fs.joinPath(staticPath, chunk.path);
8085
+ chunkContent = await this.fs.readFile(chunkPath);
8086
+ } else {
8087
+ chunkPath = nodeFS2 && nodePath ? nodePath.join(staticPath, chunk.path) : `${staticPath}/${chunk.path}`;
8088
+ if (nodeFS2 && this.isLocalPath(staticPath)) {
8089
+ chunkContent = await nodeFS2.promises.readFile(chunkPath, "utf8");
8090
+ } else {
8091
+ const response = await fetch(chunkPath);
8092
+ if (!response.ok) {
8093
+ throw new Error(`Failed to fetch chunk: ${response.status} ${response.statusText}`);
8094
+ }
8095
+ chunkContent = await response.text();
8096
+ }
8097
+ }
8098
+ const documents = JSON.parse(chunkContent);
8099
+ if (!Array.isArray(documents)) {
8100
+ throw new Error("Chunk file does not contain an array of documents");
8101
+ }
8102
+ return documents;
8103
+ } catch (error) {
8104
+ const errorMessage = error instanceof FileSystemError ? error.message : `Failed to load chunk: ${error instanceof Error ? error.message : String(error)}`;
8105
+ throw new Error(errorMessage);
8106
+ }
8107
+ }
8108
+ /**
8109
+ * Upload documents to CouchDB in batches
8110
+ */
8111
+ async uploadDocuments(documents, db) {
8112
+ const result = { restored: 0, errors: [], warnings: [] };
8113
+ const batchSize = this.options.chunkBatchSize;
8114
+ for (let i = 0; i < documents.length; i += batchSize) {
8115
+ const batch = documents.slice(i, i + batchSize);
8116
+ this.reportProgress(
8117
+ "documents",
8118
+ i,
8119
+ documents.length,
8120
+ `Uploading batch ${Math.floor(i / batchSize) + 1}...`
8121
+ );
8122
+ try {
8123
+ const docsToInsert = batch.map((doc) => {
8124
+ const cleanDoc = { ...doc };
8125
+ delete cleanDoc._rev;
8126
+ delete cleanDoc._attachments;
8127
+ return cleanDoc;
8128
+ });
8129
+ const bulkResult = await db.bulkDocs(docsToInsert);
8130
+ for (let j = 0; j < bulkResult.length; j++) {
8131
+ const docResult = bulkResult[j];
8132
+ const originalDoc = batch[j];
8133
+ if ("error" in docResult) {
8134
+ const errorMessage = `Failed to upload document ${originalDoc._id}: ${docResult.error} - ${docResult.reason}`;
8135
+ result.errors.push(errorMessage);
8136
+ logger.error(errorMessage);
8137
+ } else {
8138
+ result.restored++;
8139
+ }
8140
+ }
8141
+ } catch (error) {
8142
+ let errorMessage;
8143
+ if (error instanceof Error) {
8144
+ errorMessage = `Failed to upload document batch starting at index ${i}: ${error.message}`;
8145
+ } else if (error && typeof error === "object" && "message" in error) {
8146
+ errorMessage = `Failed to upload document batch starting at index ${i}: ${error.message}`;
8147
+ } else {
8148
+ errorMessage = `Failed to upload document batch starting at index ${i}: ${JSON.stringify(error)}`;
8149
+ }
8150
+ result.errors.push(errorMessage);
8151
+ logger.error(errorMessage);
8152
+ }
8153
+ }
8154
+ this.reportProgress(
8155
+ "documents",
8156
+ documents.length,
8157
+ documents.length,
8158
+ `Uploaded ${result.restored} documents`
8159
+ );
8160
+ return result;
8161
+ }
8162
+ /**
8163
+ * Upload attachments from filesystem to CouchDB
8164
+ */
8165
+ async uploadAttachments(staticPath, documents, db) {
8166
+ const result = { restored: 0, errors: [], warnings: [] };
8167
+ let processedDocs = 0;
8168
+ for (const doc of documents) {
8169
+ this.reportProgress(
8170
+ "attachments",
8171
+ processedDocs,
8172
+ documents.length,
8173
+ `Processing attachments for ${doc._id}...`
8174
+ );
8175
+ processedDocs++;
8176
+ if (!doc._attachments) {
8177
+ continue;
8178
+ }
8179
+ for (const [attachmentName, attachmentMeta] of Object.entries(doc._attachments)) {
8180
+ try {
8181
+ const uploadResult = await this.uploadSingleAttachment(
8182
+ staticPath,
8183
+ doc._id,
8184
+ attachmentName,
8185
+ attachmentMeta,
8186
+ db
8187
+ );
8188
+ if (uploadResult.success) {
8189
+ result.restored++;
8190
+ } else {
8191
+ result.errors.push(uploadResult.error || "Unknown attachment upload error");
8192
+ }
8193
+ } catch (error) {
8194
+ const errorMessage = `Failed to upload attachment ${doc._id}/${attachmentName}: ${error instanceof Error ? error.message : String(error)}`;
8195
+ result.errors.push(errorMessage);
8196
+ logger.error(errorMessage);
8197
+ }
8198
+ }
8199
+ }
8200
+ this.reportProgress(
8201
+ "attachments",
8202
+ documents.length,
8203
+ documents.length,
8204
+ `Uploaded ${result.restored} attachments`
8205
+ );
8206
+ return result;
8207
+ }
8208
+ /**
8209
+ * Upload a single attachment file
8210
+ */
8211
+ async uploadSingleAttachment(staticPath, docId, attachmentName, attachmentMeta, db) {
8212
+ const result = {
8213
+ success: false,
8214
+ attachmentName,
8215
+ docId
8216
+ };
8217
+ try {
8218
+ if (!attachmentMeta.path) {
8219
+ result.error = "Attachment metadata missing file path";
8220
+ return result;
8221
+ }
8222
+ let attachmentData;
8223
+ let attachmentPath;
8224
+ if (this.fs) {
8225
+ attachmentPath = this.fs.joinPath(staticPath, attachmentMeta.path);
8226
+ attachmentData = await this.fs.readBinary(attachmentPath);
8227
+ } else {
8228
+ attachmentPath = nodeFS2 && nodePath ? nodePath.join(staticPath, attachmentMeta.path) : `${staticPath}/${attachmentMeta.path}`;
8229
+ if (nodeFS2 && this.isLocalPath(staticPath)) {
8230
+ attachmentData = await nodeFS2.promises.readFile(attachmentPath);
8231
+ } else {
8232
+ const response = await fetch(attachmentPath);
8233
+ if (!response.ok) {
8234
+ result.error = `Failed to fetch attachment: ${response.status} ${response.statusText}`;
8235
+ return result;
8236
+ }
8237
+ attachmentData = await response.arrayBuffer();
8238
+ }
8239
+ }
8240
+ const doc = await db.get(docId);
8241
+ await db.putAttachment(
8242
+ docId,
8243
+ attachmentName,
8244
+ doc._rev,
8245
+ attachmentData,
8246
+ // PouchDB accepts both ArrayBuffer and Buffer
8247
+ attachmentMeta.content_type
8248
+ );
8249
+ result.success = true;
8250
+ } catch (error) {
8251
+ result.error = error instanceof Error ? error.message : String(error);
8252
+ }
8253
+ return result;
8254
+ }
8255
+ /**
8256
+ * Restore CourseConfig document from manifest
8257
+ */
8258
+ async restoreCourseConfig(manifest, targetDB) {
8259
+ const results = {
8260
+ restored: 0,
8261
+ errors: [],
8262
+ warnings: []
8263
+ };
8264
+ try {
8265
+ if (!manifest.courseConfig) {
8266
+ results.warnings.push(
8267
+ "No courseConfig found in manifest, skipping CourseConfig document creation"
8268
+ );
8269
+ return results;
8270
+ }
8271
+ const courseConfigDoc = {
8272
+ _id: "CourseConfig",
8273
+ ...manifest.courseConfig,
8274
+ courseID: manifest.courseId
8275
+ };
8276
+ delete courseConfigDoc._rev;
8277
+ await targetDB.put(courseConfigDoc);
8278
+ results.restored = 1;
8279
+ logger.info(`CourseConfig document created for course: ${manifest.courseId}`);
8280
+ } catch (error) {
8281
+ const errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
8282
+ results.errors.push(`Failed to restore CourseConfig: ${errorMessage}`);
8283
+ logger.error("CourseConfig restoration failed:", error);
8284
+ }
8285
+ return results;
8286
+ }
8287
+ /**
8288
+ * Calculate expected document counts from manifest
8289
+ */
8290
+ calculateExpectedCounts(manifest) {
8291
+ const counts = {};
8292
+ for (const chunk of manifest.chunks) {
8293
+ counts[chunk.docType] = (counts[chunk.docType] || 0) + chunk.documentCount;
8294
+ }
8295
+ if (manifest.designDocs.length > 0) {
8296
+ counts["_design"] = manifest.designDocs.length;
8297
+ }
8298
+ return counts;
8299
+ }
8300
+ /**
8301
+ * Clean up database after failed migration
8302
+ */
8303
+ async cleanupFailedMigration(db) {
8304
+ logger.info("Cleaning up failed migration...");
8305
+ try {
8306
+ const allDocs = await db.allDocs();
8307
+ const docsToDelete = allDocs.rows.map((row) => ({
8308
+ _id: row.id,
8309
+ _rev: row.value.rev,
8310
+ _deleted: true
8311
+ }));
8312
+ if (docsToDelete.length > 0) {
8313
+ await db.bulkDocs(docsToDelete);
8314
+ logger.info(`Cleaned up ${docsToDelete.length} documents from failed migration`);
8315
+ }
8316
+ } catch (error) {
8317
+ logger.error("Failed to cleanup documents:", error);
8318
+ throw error;
8319
+ }
8320
+ }
8321
+ /**
8322
+ * Report progress to callback if available
8323
+ */
8324
+ reportProgress(phase, current, total, message) {
8325
+ if (this.progressCallback) {
8326
+ this.progressCallback({
8327
+ phase,
8328
+ current,
8329
+ total,
8330
+ message
8331
+ });
8332
+ }
8333
+ }
8334
+ /**
8335
+ * Check if a path is a local file path (vs URL)
8336
+ */
8337
+ isLocalPath(path2) {
8338
+ return !path2.startsWith("http://") && !path2.startsWith("https://");
8339
+ }
8340
+ };
8341
+ }
8342
+ });
8343
+
8344
+ // src/util/migrator/index.ts
8345
+ var init_migrator = __esm({
8346
+ "src/util/migrator/index.ts"() {
8347
+ "use strict";
8348
+ init_StaticToCouchDBMigrator();
8349
+ init_validation();
8350
+ init_FileSystemAdapter();
8351
+ }
8352
+ });
8353
+
8354
+ // src/util/index.ts
8355
+ var init_util2 = __esm({
8356
+ "src/util/index.ts"() {
8357
+ "use strict";
8358
+ init_Loggable();
8359
+ init_packer();
8360
+ init_migrator();
8361
+ init_dataDirectory();
8362
+ }
8363
+ });
8364
+
8365
+ // src/study/SourceMixer.ts
8366
+ var init_SourceMixer = __esm({
8367
+ "src/study/SourceMixer.ts"() {
8368
+ "use strict";
8369
+ }
8370
+ });
8371
+
8372
+ // src/study/MixerDebugger.ts
8373
+ function printMixerSummary(run) {
8374
+ console.group(`\u{1F3A8} Mixer Run: ${run.mixerType}`);
8375
+ logger.info(`Run ID: ${run.runId}`);
8376
+ logger.info(`Time: ${run.timestamp.toISOString()}`);
8377
+ logger.info(
8378
+ `Config: limit=${run.requestedLimit}${run.quotaPerSource ? `, quota/source=${run.quotaPerSource}` : ""}`
8379
+ );
8380
+ console.group(`\u{1F4E5} Input: ${run.sourceSummaries.length} sources`);
8381
+ for (const src of run.sourceSummaries) {
8382
+ logger.info(
8383
+ ` ${src.sourceName || src.sourceId}: ${src.totalCards} cards (${src.reviewCount} reviews, ${src.newCount} new)`
8384
+ );
8385
+ logger.info(` Score range: [${src.scoreRange[0].toFixed(2)}, ${src.scoreRange[1].toFixed(2)}], avg: ${src.avgScore.toFixed(2)}`);
8386
+ }
8387
+ console.groupEnd();
8388
+ console.group(`\u{1F4E4} Output: ${run.finalCount} cards selected (${run.reviewsSelected} reviews, ${run.newSelected} new)`);
8389
+ for (const breakdown of run.sourceBreakdowns) {
8390
+ const name = breakdown.sourceName || breakdown.sourceId;
8391
+ logger.info(
8392
+ ` ${name}: ${breakdown.totalSelected} selected (${breakdown.reviewsSelected} reviews, ${breakdown.newSelected} new) - ${breakdown.selectionRate.toFixed(1)}% selection rate`
8393
+ );
8394
+ }
8395
+ console.groupEnd();
8396
+ console.groupEnd();
8397
+ }
8398
+ function mountMixerDebugger() {
8399
+ if (typeof window === "undefined") return;
8400
+ const win = window;
8401
+ win.skuilder = win.skuilder || {};
8402
+ win.skuilder.mixer = mixerDebugAPI;
8403
+ }
8404
+ var runHistory2, mixerDebugAPI;
8405
+ var init_MixerDebugger = __esm({
8406
+ "src/study/MixerDebugger.ts"() {
8407
+ "use strict";
8408
+ init_logger();
8409
+ init_navigators();
8410
+ runHistory2 = [];
8411
+ mixerDebugAPI = {
8412
+ /**
8413
+ * Get raw run history for programmatic access.
8414
+ */
8415
+ get runs() {
8416
+ return [...runHistory2];
8417
+ },
8418
+ /**
8419
+ * Show summary of a specific mixer run.
8420
+ */
8421
+ showRun(idOrIndex = 0) {
8422
+ if (runHistory2.length === 0) {
8423
+ logger.info("[Mixer Debug] No runs captured yet.");
8424
+ return;
8425
+ }
8426
+ let run;
8427
+ if (typeof idOrIndex === "number") {
8428
+ run = runHistory2[idOrIndex];
8429
+ if (!run) {
8430
+ logger.info(`[Mixer Debug] No run found at index ${idOrIndex}. History length: ${runHistory2.length}`);
8431
+ return;
8432
+ }
8433
+ } else {
8434
+ run = runHistory2.find((r) => r.runId.endsWith(idOrIndex));
8435
+ if (!run) {
8436
+ logger.info(`[Mixer Debug] No run found matching ID '${idOrIndex}'.`);
8437
+ return;
8438
+ }
8439
+ }
8440
+ printMixerSummary(run);
8441
+ },
8442
+ /**
8443
+ * Show summary of the last mixer run.
8444
+ */
8445
+ showLastMix() {
8446
+ this.showRun(0);
8447
+ },
8448
+ /**
8449
+ * Explain source balance in the last run.
8450
+ */
8451
+ explainSourceBalance() {
8452
+ if (runHistory2.length === 0) {
8453
+ logger.info("[Mixer Debug] No runs captured yet.");
8454
+ return;
8455
+ }
8456
+ const run = runHistory2[0];
8457
+ console.group("\u2696\uFE0F Source Balance Analysis");
8458
+ logger.info(`Mixer: ${run.mixerType}`);
8459
+ logger.info(`Requested limit: ${run.requestedLimit}`);
8460
+ if (run.quotaPerSource) {
8461
+ logger.info(`Quota per source: ${run.quotaPerSource}`);
8462
+ }
8463
+ console.group("Input Distribution:");
8464
+ for (const src of run.sourceSummaries) {
8465
+ const name = src.sourceName || src.sourceId;
8466
+ logger.info(`${name}:`);
8467
+ logger.info(` Provided: ${src.totalCards} cards (${src.reviewCount} reviews, ${src.newCount} new)`);
8468
+ logger.info(` Score range: [${src.scoreRange[0].toFixed(2)}, ${src.scoreRange[1].toFixed(2)}]`);
8469
+ }
8470
+ console.groupEnd();
8471
+ console.group("Selection Results:");
8472
+ for (const breakdown of run.sourceBreakdowns) {
8473
+ const name = breakdown.sourceName || breakdown.sourceId;
8474
+ logger.info(`${name}:`);
8475
+ logger.info(
8476
+ ` Selected: ${breakdown.totalSelected}/${breakdown.reviewsProvided + breakdown.newProvided} (${breakdown.selectionRate.toFixed(1)}%)`
8477
+ );
8478
+ logger.info(` Reviews: ${breakdown.reviewsSelected}/${breakdown.reviewsProvided}`);
8479
+ logger.info(` New: ${breakdown.newSelected}/${breakdown.newProvided}`);
8480
+ if (breakdown.reviewsProvided > 0 && breakdown.reviewsSelected === 0) {
8481
+ logger.info(` \u26A0\uFE0F Had reviews but none selected!`);
8482
+ }
8483
+ if (breakdown.totalSelected === 0 && breakdown.reviewsProvided + breakdown.newProvided > 0) {
8484
+ logger.info(` \u26A0\uFE0F Had cards but none selected!`);
8485
+ }
8486
+ }
8487
+ console.groupEnd();
8488
+ const selectionRates = run.sourceBreakdowns.map((b) => b.selectionRate);
8489
+ const avgRate = selectionRates.reduce((a, b) => a + b, 0) / selectionRates.length;
8490
+ const maxDeviation = Math.max(...selectionRates.map((r) => Math.abs(r - avgRate)));
8491
+ if (maxDeviation > 20) {
8492
+ logger.info(`
8493
+ \u26A0\uFE0F Significant imbalance detected (max deviation: ${maxDeviation.toFixed(1)}%)`);
8494
+ logger.info("Possible causes:");
8495
+ logger.info(" - Score range differences between sources");
8496
+ logger.info(" - One source has much better quality cards");
8497
+ logger.info(" - Different card availability (reviews vs new)");
8498
+ }
8499
+ console.groupEnd();
8500
+ },
8501
+ /**
8502
+ * Compare score distributions across sources.
8503
+ */
8504
+ compareScores() {
8505
+ if (runHistory2.length === 0) {
8506
+ logger.info("[Mixer Debug] No runs captured yet.");
8507
+ return;
8508
+ }
8509
+ const run = runHistory2[0];
8510
+ console.group("\u{1F4CA} Score Distribution Comparison");
8511
+ console.table(
8512
+ run.sourceSummaries.map((src) => ({
8513
+ source: src.sourceName || src.sourceId,
8514
+ cards: src.totalCards,
8515
+ min: src.bottomScore.toFixed(3),
8516
+ max: src.topScore.toFixed(3),
8517
+ avg: src.avgScore.toFixed(3),
8518
+ range: (src.topScore - src.bottomScore).toFixed(3)
8519
+ }))
8520
+ );
8521
+ const ranges = run.sourceSummaries.map((s) => s.topScore - s.bottomScore);
8522
+ const avgScores = run.sourceSummaries.map((s) => s.avgScore);
8523
+ const rangeDiff = Math.max(...ranges) - Math.min(...ranges);
8524
+ const avgDiff = Math.max(...avgScores) - Math.min(...avgScores);
8525
+ if (rangeDiff > 0.3 || avgDiff > 0.2) {
8526
+ logger.info("\n\u26A0\uFE0F Significant score distribution differences detected");
8527
+ logger.info(
8528
+ "This may cause one source to dominate selection if using global sorting (not quota-based)"
8529
+ );
8530
+ }
8531
+ console.groupEnd();
8532
+ },
8533
+ /**
8534
+ * Show detailed information for a specific card.
8535
+ */
8536
+ showCard(cardId) {
8537
+ for (const run of runHistory2) {
8538
+ const card = run.cards.find((c) => c.cardId === cardId);
8539
+ if (card) {
8540
+ const source = run.sourceSummaries.find((s) => s.sourceIndex === card.sourceIndex);
8541
+ console.group(`\u{1F3B4} Card: ${cardId}`);
8542
+ logger.info(`Course: ${card.courseId}`);
8543
+ logger.info(`Source: ${source?.sourceName || source?.sourceId || "unknown"}`);
8544
+ logger.info(`Origin: ${card.origin}`);
8545
+ logger.info(`Score: ${card.score.toFixed(3)}`);
8546
+ if (card.rankInSource) {
8547
+ logger.info(`Rank in source: #${card.rankInSource}`);
8548
+ }
8549
+ if (card.rankInMix) {
8550
+ logger.info(`Rank in mixed results: #${card.rankInMix}`);
8551
+ }
8552
+ logger.info(`Selected: ${card.selected ? "Yes \u2705" : "No \u274C"}`);
8553
+ if (!card.selected && card.rankInSource) {
8554
+ logger.info("\nWhy not selected:");
8555
+ if (run.quotaPerSource && card.rankInSource > run.quotaPerSource) {
8556
+ logger.info(` - Ranked #${card.rankInSource} in source, but quota was ${run.quotaPerSource}`);
8557
+ }
8558
+ logger.info(" - Check score compared to selected cards using .showRun()");
8559
+ }
8560
+ console.groupEnd();
8561
+ return;
8562
+ }
8563
+ }
8564
+ logger.info(`[Mixer Debug] Card '${cardId}' not found in recent runs.`);
8565
+ },
8566
+ /**
8567
+ * Show all runs in compact format.
8568
+ */
8569
+ listRuns() {
8570
+ if (runHistory2.length === 0) {
8571
+ logger.info("[Mixer Debug] No runs captured yet.");
8572
+ return;
8573
+ }
8574
+ console.table(
8575
+ runHistory2.map((r) => ({
8576
+ id: r.runId.slice(-8),
8577
+ time: r.timestamp.toLocaleTimeString(),
8578
+ mixer: r.mixerType,
8579
+ sources: r.sourceSummaries.length,
8580
+ selected: r.finalCount,
8581
+ reviews: r.reviewsSelected,
8582
+ new: r.newSelected
8583
+ }))
8584
+ );
8585
+ },
8586
+ /**
8587
+ * Export run history as JSON for bug reports.
8588
+ */
8589
+ export() {
8590
+ const json = JSON.stringify(runHistory2, null, 2);
8591
+ logger.info("[Mixer Debug] Run history exported. Copy the returned string or use:");
8592
+ logger.info(" copy(window.skuilder.mixer.export())");
8593
+ return json;
8594
+ },
8595
+ /**
8596
+ * Clear run history.
8597
+ */
8598
+ clear() {
8599
+ runHistory2.length = 0;
8600
+ logger.info("[Mixer Debug] Run history cleared.");
8601
+ },
8602
+ /**
8603
+ * Show help.
8604
+ */
8605
+ help() {
8606
+ logger.info(`
8607
+ \u{1F3A8} Mixer Debug API
8608
+
8609
+ Commands:
8610
+ .showLastMix() Show summary of most recent mixer run
8611
+ .showRun(id|index) Show summary of a specific run (by index or ID suffix)
8612
+ .explainSourceBalance() Analyze source balance and selection patterns
8613
+ .compareScores() Compare score distributions across sources
8614
+ .showCard(cardId) Show mixer decisions for a specific card
8615
+ .listRuns() List all captured runs in table format
8616
+ .export() Export run history as JSON for bug reports
8617
+ .clear() Clear run history
8618
+ .runs Access raw run history array
8619
+ .help() Show this help message
8620
+
8621
+ Example:
8622
+ window.skuilder.mixer.showLastMix()
8623
+ window.skuilder.mixer.explainSourceBalance()
8624
+ window.skuilder.mixer.compareScores()
8625
+ `);
8626
+ }
8627
+ };
8628
+ mountMixerDebugger();
8629
+ }
8630
+ });
8631
+
8632
+ // src/study/SessionOverlay.ts
8633
+ function getActiveController() {
8634
+ return activeController;
8635
+ }
8636
+ function toggleSessionOverlay() {
8637
+ if (typeof document === "undefined") {
8638
+ logger.info("[Session Overlay] No DOM available (non-browser host); overlay unavailable.");
8639
+ return;
8640
+ }
8641
+ if (overlayEl) {
8642
+ teardown();
8643
+ logger.info("[Session Overlay] Hidden.");
8644
+ } else {
8645
+ mount();
8646
+ logger.info("[Session Overlay] Shown. Toggle off with window.skuilder.session.dbgOverlay().");
8647
+ }
8648
+ }
8649
+ function mount() {
8650
+ minified = false;
8651
+ overlayEl = document.createElement("div");
8652
+ overlayEl.id = OVERLAY_ID;
8653
+ Object.assign(overlayEl.style, {
8654
+ position: "fixed",
8655
+ top: "8px",
8656
+ left: "8px",
8657
+ zIndex: "2147483647",
8658
+ maxWidth: "320px",
8659
+ maxHeight: "90vh",
8660
+ overflowY: "auto",
8661
+ padding: "8px 10px",
8662
+ background: "rgba(17, 24, 39, 0.92)",
8663
+ color: "#e5e7eb",
8664
+ font: "11px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace",
8665
+ borderRadius: "6px",
8666
+ boxShadow: "0 4px 16px rgba(0,0,0,0.4)",
8667
+ pointerEvents: "auto",
8668
+ userSelect: "none"
8669
+ });
8670
+ document.body.appendChild(overlayEl);
8671
+ render();
8672
+ pollHandle = setInterval(render, POLL_MS);
8673
+ }
8674
+ function teardown() {
8675
+ if (pollHandle !== null) {
8676
+ clearInterval(pollHandle);
8677
+ pollHandle = null;
8678
+ }
8679
+ if (overlayEl?.parentNode) {
8680
+ overlayEl.parentNode.removeChild(overlayEl);
8681
+ }
8682
+ overlayEl = null;
8683
+ }
8684
+ function render() {
8685
+ if (!overlayEl) return;
8686
+ spinnerFrame++;
8687
+ const ctrl = getActiveController();
8688
+ if (!ctrl) {
8689
+ lastSnapshot = null;
8690
+ overlayEl.innerHTML = headerHtml() + (minified ? "" : `<div style="opacity:.65">No active session.</div>`);
8691
+ attachHandlers();
8692
+ return;
8693
+ }
8694
+ const s = ctrl.getDebugSnapshot();
8695
+ lastSnapshot = s;
8696
+ if (minified) {
8697
+ overlayEl.innerHTML = headerHtml();
8698
+ attachHandlers();
8699
+ return;
8700
+ }
8701
+ 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);
8702
+ attachHandlers();
8703
+ }
8704
+ function attachHandlers() {
8705
+ if (!overlayEl) return;
8706
+ overlayEl.querySelectorAll("[data-q]").forEach((el) => {
8707
+ el.onclick = () => {
8708
+ const key = el.dataset.q;
8709
+ if (!key) return;
8710
+ expanded[key] = !expanded[key];
8711
+ render();
8712
+ };
8713
+ });
8714
+ const copyBtn = overlayEl.querySelector("[data-copy]");
8715
+ if (copyBtn) {
8716
+ copyBtn.onclick = (ev) => {
8717
+ ev.stopPropagation();
8718
+ copySnapshot();
8719
+ };
8720
+ }
8721
+ const minBtn = overlayEl.querySelector("[data-min]");
8722
+ if (minBtn) {
8723
+ minBtn.onclick = (ev) => {
8724
+ ev.stopPropagation();
8725
+ minified = !minified;
8726
+ render();
8727
+ };
8728
+ }
8729
+ }
8730
+ function copySnapshot() {
8731
+ const text = snapshotToText(lastSnapshot);
8732
+ const flash = () => {
8733
+ copyFlashUntil = Date.now() + 1200;
8734
+ render();
8735
+ };
8736
+ const clip = typeof navigator !== "undefined" ? navigator.clipboard : void 0;
8737
+ if (clip?.writeText) {
8738
+ clip.writeText(text).then(flash, (err) => {
8739
+ logger.warn(`[Session Overlay] Clipboard write failed: ${String(err)}`);
8740
+ });
8741
+ } else {
8742
+ logger.info(`[Session Overlay] Clipboard unavailable; snapshot follows:
8743
+ ${text}`);
8744
+ }
8745
+ }
8746
+ function headerHtml() {
8747
+ const flashing = Date.now() < copyFlashUntil;
8748
+ const btnLabel = flashing ? "\u2713 copied" : "\u2398 copy";
8749
+ const btnColor = flashing ? "#86efac" : "#93c5fd";
8750
+ 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>`;
8751
+ 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>`;
8752
+ return `<div style="font-weight:600;color:#93c5fd;margin-bottom:${minified ? 0 : 4}px">${copyBtn}${minBtn}\u2699 SessionController</div>`;
8753
+ }
8754
+ function replanHtml(s) {
8755
+ if (!s.replanActive) {
8756
+ return `<div style="margin-bottom:6px;opacity:.45">\u25CB idle</div>`;
8757
+ }
8758
+ const frame = SPINNER_FRAMES[spinnerFrame % SPINNER_FRAMES.length];
8759
+ const reason = esc(s.replanLabel ?? "(auto)");
8760
+ return `<div style="margin-bottom:6px;color:#fde047">${frame} replanning <span style="opacity:.85">[${reason}]</span></div>`;
8761
+ }
8762
+ function metaHtml(s) {
8763
+ const mmss = formatTime(s.secondsRemaining);
8764
+ const guarantee = s.hasCardGuarantee ? ` \xB7 <span style="color:#fbbf24">guarantee ${s.minCardsGuarantee}</span>` : "";
8765
+ const rows = [
8766
+ `time ${mmss}${guarantee}`,
8767
+ `well-indicated left: ${s.wellIndicatedRemaining}`,
8768
+ `current: ${s.currentCard ? esc(s.currentCard) : '<span style="opacity:.6">\u2014</span>'}`
8769
+ ];
8770
+ return `<div style="margin-bottom:6px">${rows.map((r) => `<div>${r}</div>`).join("")}</div>`;
8771
+ }
8772
+ function hintsHtml(h) {
8773
+ const parts = [];
8774
+ if (h) {
8775
+ if (h.boostTags && Object.keys(h.boostTags).length) {
8776
+ parts.push(
8777
+ `boost: ` + Object.entries(h.boostTags).map(([k, v]) => `${esc(k)}<span style="opacity:.6">\xD7${v}</span>`).join(", ")
8778
+ );
8779
+ }
8780
+ if (h.boostCards && Object.keys(h.boostCards).length) {
8781
+ parts.push(
8782
+ `boostCards: ` + Object.entries(h.boostCards).map(([k, v]) => `${esc(k)}<span style="opacity:.6">\xD7${v}</span>`).join(", ")
8783
+ );
8784
+ }
8785
+ if (h.requireCards?.length) parts.push(`require: ${h.requireCards.map(esc).join(", ")}`);
8786
+ if (h.requireTags?.length) parts.push(`requireTags: ${h.requireTags.map(esc).join(", ")}`);
8787
+ if (h.excludeTags?.length) parts.push(`exclude: ${h.excludeTags.map(esc).join(", ")}`);
8788
+ if (h.excludeCards?.length) parts.push(`excludeCards: ${h.excludeCards.map(esc).join(", ")}`);
8789
+ }
8790
+ const body = parts.length ? parts.map((p) => `<div style="margin-left:6px">${p}</div>`).join("") : `<div style="margin-left:6px;opacity:.6">none</div>`;
8791
+ return `<div style="margin-bottom:6px"><div style="color:#86efac">sessionHints</div>${body}</div>`;
8792
+ }
8793
+ function backlogHtml(backlog) {
8794
+ if (!backlog.length) return "";
8795
+ const rows = backlog.map((b) => {
8796
+ const hot = b.backlogMultiplier >= 3;
8797
+ const multColor = b.backlogMultiplier <= 1 ? "#86efac" : hot ? "#fca5a5" : "#fcd34d";
8798
+ const headroom = b.backlogMultiplier > 1 ? `climbing (\xD7${b.backlogGrowthRate.toFixed(2)} per ${b.healthyBacklog}-review excess, unbounded)` : "healthy \u2014 no pressure";
8799
+ const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
8800
+ const next = b.nextDueIn ? ` <span style="opacity:.6">\xB7 next due ${esc(b.nextDueIn)}</span>` : "";
8801
+ 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>`;
8802
+ }).join("");
8803
+ return `<div style="margin-bottom:6px"><div style="color:#93c5fd">review backpressure</div>${rows}</div>`;
8804
+ }
8805
+ function pressureColor(multiplier, max) {
8806
+ if (multiplier <= 1.001) return "#86efac";
8807
+ if (max !== void 0 && max > 1) {
8808
+ return (multiplier - 1) / (max - 1) >= 0.75 ? "#fca5a5" : "#fcd34d";
8809
+ }
8810
+ return multiplier >= 3 ? "#fca5a5" : "#fcd34d";
8811
+ }
8812
+ function toggleKey(raw) {
8813
+ return raw.replace(/[^\w:.|-]/g, "_");
8814
+ }
8815
+ function gaugeHtml(sectionKey, g) {
8816
+ const cap = g.max !== void 0 ? `<span style="opacity:.5">/${g.max}</span>` : "";
8817
+ const detail = g.detail ? ` <span style="opacity:.6">${esc(g.detail)}</span>` : "";
8818
+ 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}`;
8819
+ const items = g.items ?? [];
8820
+ if (items.length > 0) {
8821
+ const key = toggleKey(`sp|${sectionKey}|${g.id}`);
8822
+ const isOpen = !!expanded[key];
8823
+ const shown = isOpen ? items : items.slice(0, INLINE_THRESHOLD);
8824
+ html += `<div style="margin-left:6px">` + shown.map(
8825
+ (it) => `<div style="white-space:nowrap;opacity:.75">${esc(it.label)}${it.value ? ` <span style="opacity:.6">${esc(it.value)}</span>` : ""}</div>`
8826
+ ).join("");
8827
+ if (items.length > INLINE_THRESHOLD) {
8828
+ const footer = isOpen ? "\u25BE show less" : `\u2026 +${items.length - shown.length} more`;
8829
+ html += `<div data-q="${key}" style="cursor:pointer;opacity:.6">${footer}</div>`;
8830
+ }
8831
+ html += `</div>`;
8832
+ }
8833
+ return html + `</div>`;
8834
+ }
8835
+ function strategyPressureHtml(list) {
8836
+ if (!list.length) return "";
8837
+ const sections = list.map((s) => {
8838
+ const sectionKey = `${s.source}:${s.courseId.slice(0, 8)}`;
8839
+ const top = s.topScore !== null && s.topScore !== void 0 ? s.topScore.toFixed(2) : "\u2014";
8840
+ const hints = s.hintsLabel ? `<div style="margin-left:6px;opacity:.6">hints: ${esc(s.hintsLabel)}</div>` : "";
8841
+ 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>`;
8842
+ }).join("");
8843
+ return `<div style="margin-bottom:6px"><div style="color:#fdba74">strategy backpressure</div>${sections}</div>`;
8844
+ }
8845
+ function fmtScore(score) {
8846
+ if (score === void 0) return "";
8847
+ if (!Number.isFinite(score)) return "REQ";
8848
+ return score.toFixed(2);
8849
+ }
8850
+ function queueItemHtml(item) {
8851
+ const tagColor = item.origin === "review" ? "#93c5fd" : "#fcd34d";
8852
+ const score = fmtScore(item.score);
8853
+ const label = `${item.origin === "review" ? "r" : "n"}${score ? " " + score : ""}`;
8854
+ return `${esc(item.cardID)}<span style="color:${tagColor};opacity:.85"> [${label}]</span>`;
8855
+ }
8856
+ function queueHtml(key, label, q) {
8857
+ const collapsible = q.length > INLINE_THRESHOLD;
8858
+ const isOpen = collapsible && expanded[key];
8859
+ const caret = collapsible ? expanded[key] ? "\u25BE " : "\u25B8 " : "";
8860
+ const drawn = q.dequeueCount ? ` <span style="opacity:.5">drawn ${q.dequeueCount}</span>` : "";
8861
+ const titleStyle = collapsible ? "cursor:pointer;color:#f9a8d4" : "color:#f9a8d4";
8862
+ const titleAttr = collapsible ? ` data-q="${key}"` : "";
8863
+ const title = `<div${titleAttr} style="${titleStyle}">${caret}${label}: ${q.length}${drawn}</div>`;
8864
+ if (!q.cards.length) {
8865
+ return title + `<div style="margin:1px 0 6px 6px;opacity:.5">empty</div>`;
8866
+ }
8867
+ const shown = isOpen ? q.cards : q.cards.slice(0, INLINE_THRESHOLD);
8868
+ const hiddenCount = q.length - shown.length;
8869
+ const listMarginBottom = collapsible ? 2 : 6;
8870
+ 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>`;
8871
+ if (collapsible) {
8872
+ const footer = isOpen ? "\u25BE show less" : `\u2026 +${hiddenCount} more`;
8873
+ body += `<div data-q="${key}" style="cursor:pointer;margin:0 0 6px 20px;opacity:.6">${footer}</div>`;
8874
+ }
8875
+ return title + body;
8876
+ }
8877
+ function outcomeGlyph(correct) {
8878
+ if (correct === true) return `<span style="color:#86efac">\u2713</span>`;
8879
+ if (correct === false) return `<span style="color:#fca5a5">\u2717</span>`;
8880
+ return `<span style="opacity:.5">\xB7</span>`;
8881
+ }
8882
+ function drawnHtml(key, drawn) {
8883
+ const collapsible = drawn.length > INLINE_THRESHOLD;
8884
+ const isOpen = collapsible && expanded[key];
8885
+ const caret = collapsible ? expanded[key] ? "\u25BE " : "\u25B8 " : "";
8886
+ const titleStyle = collapsible ? "cursor:pointer;color:#c4b5fd" : "color:#c4b5fd";
8887
+ const titleAttr = collapsible ? ` data-q="${key}"` : "";
8888
+ const title = `<div${titleAttr} style="${titleStyle}">${caret}drawn: ${drawn.length}</div>`;
8889
+ if (!drawn.length) {
8890
+ return title + `<div style="margin:1px 0 6px 6px;opacity:.5">none yet</div>`;
8891
+ }
8892
+ const shown = isOpen ? drawn : drawn.slice(0, INLINE_THRESHOLD);
8893
+ const hiddenCount = drawn.length - shown.length;
8894
+ const listMarginBottom = collapsible ? 2 : 6;
8895
+ const rows = shown.map((d) => {
8896
+ const retries = d.attempts > 1 ? `<span style="opacity:.5"> \xD7${d.attempts}</span>` : "";
8897
+ const time = `<span style="opacity:.45"> ${Math.round(d.timeSpentMs / 100) / 10}s</span>`;
8898
+ return `<li style="white-space:nowrap">${outcomeGlyph(d.correct)} ${esc(d.cardID)}<span style="opacity:.5"> [${esc(d.status)}]</span>${retries}${time}</li>`;
8899
+ }).join("");
8900
+ let body = `<ol style="margin:2px 0 ${listMarginBottom}px 0;padding-left:20px">${rows}</ol>`;
8901
+ if (collapsible) {
8902
+ const footer = isOpen ? "\u25BE show less" : `\u2026 +${hiddenCount} more`;
8903
+ body += `<div data-q="${key}" style="cursor:pointer;margin:0 0 6px 20px;opacity:.6">${footer}</div>`;
8904
+ }
8905
+ return title + body;
8906
+ }
8907
+ function snapshotToText(s) {
8908
+ if (!s) return "SessionController \u2014 no active session.";
8909
+ const lines = [];
8910
+ lines.push("=== SessionController ===");
8911
+ lines.push(`time ${formatTime(s.secondsRemaining)}`);
8912
+ if (s.hasCardGuarantee) lines.push(`guarantee: ${s.minCardsGuarantee}`);
8913
+ lines.push(`well-indicated left: ${s.wellIndicatedRemaining}`);
8914
+ lines.push(`current: ${s.currentCard ?? "\u2014"}`);
8915
+ lines.push(
8916
+ s.replanActive ? `replan: ACTIVE [${s.replanLabel ?? "(auto)"}]` : "replan: idle"
8917
+ );
8918
+ lines.push("");
8919
+ lines.push("sessionHints:");
8920
+ const h = s.sessionHints;
8921
+ const hintParts = [];
8922
+ if (h) {
8923
+ if (h.boostTags && Object.keys(h.boostTags).length)
8924
+ hintParts.push(` boost: ${Object.entries(h.boostTags).map(([k, v]) => `${k}\xD7${v}`).join(", ")}`);
8925
+ if (h.boostCards && Object.keys(h.boostCards).length)
8926
+ hintParts.push(` boostCards: ${Object.entries(h.boostCards).map(([k, v]) => `${k}\xD7${v}`).join(", ")}`);
8927
+ if (h.requireCards?.length) hintParts.push(` require: ${h.requireCards.join(", ")}`);
8928
+ if (h.requireTags?.length) hintParts.push(` requireTags: ${h.requireTags.join(", ")}`);
8929
+ if (h.excludeTags?.length) hintParts.push(` exclude: ${h.excludeTags.join(", ")}`);
8930
+ if (h.excludeCards?.length) hintParts.push(` excludeCards: ${h.excludeCards.join(", ")}`);
8931
+ }
8932
+ lines.push(hintParts.length ? hintParts.join("\n") : " none");
8933
+ if (s.reviewBacklog.length) {
8934
+ lines.push("");
8935
+ lines.push("review backpressure:");
8936
+ for (const b of s.reviewBacklog) {
8937
+ const headroom = b.backlogMultiplier > 1 ? "climbing" : "healthy";
8938
+ const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
8939
+ const next = b.nextDueIn ? `, next due ${b.nextDueIn}` : "";
8940
+ lines.push(
8941
+ ` ${b.courseId.slice(0, 8)}: due ${b.dueNow}/${b.scheduledTotal} (healthy ${b.healthyBacklog})${next}; pressure \xD7${b.backlogMultiplier.toFixed(2)} ${headroom}; top review ${top}`
8942
+ );
8943
+ }
8944
+ }
8945
+ if (s.strategyPressure.length) {
8946
+ lines.push("");
8947
+ lines.push("strategy backpressure:");
8948
+ for (const sp of s.strategyPressure) {
8949
+ const top = sp.topScore !== null && sp.topScore !== void 0 ? sp.topScore.toFixed(2) : "\u2014";
8950
+ lines.push(` ${sp.source} (${sp.courseId.slice(0, 8)}): top score ${top}`);
8951
+ for (const g of sp.gauges) {
8952
+ const cap = g.max !== void 0 ? `/${g.max}` : "";
8953
+ lines.push(
8954
+ ` ${g.label} \xD7${g.multiplier.toFixed(2)}${cap}${g.detail ? ` \u2014 ${g.detail}` : ""}`
8955
+ );
8956
+ for (const it of g.items ?? []) {
8957
+ lines.push(` ${it.label}${it.value ? ` (${it.value})` : ""}`);
8958
+ }
8959
+ }
8960
+ if (sp.hintsLabel) lines.push(` hints: ${sp.hintsLabel}`);
8961
+ }
8962
+ }
8963
+ const queueText = (label, q) => {
8964
+ lines.push("");
8965
+ lines.push(`${label}: ${q.length} (drawn ${q.dequeueCount})`);
8966
+ q.cards.forEach((c, i) => {
8967
+ const score = fmtScore(c.score);
8968
+ const tag = `${c.origin === "review" ? "r" : "n"}${score ? " " + score : ""}`;
8969
+ lines.push(` ${i + 1}. ${c.cardID} [${tag}]`);
8970
+ });
8971
+ };
8972
+ queueText("supplyQ", s.supplyQ);
8973
+ queueText("failedQ", s.failedQ);
8974
+ lines.push("");
8975
+ lines.push(`drawn: ${s.drawnCards.length}`);
8976
+ s.drawnCards.forEach((d, i) => {
8977
+ const mark = d.correct === true ? "\u2713" : d.correct === false ? "\u2717" : "\xB7";
8978
+ const time = `${Math.round(d.timeSpentMs / 100) / 10}s`;
8979
+ lines.push(` ${i + 1}. ${mark} ${d.cardID} [${d.status}] \xD7${d.attempts} ${time}`);
8980
+ });
8981
+ return lines.join("\n");
8982
+ }
8983
+ function formatTime(totalSeconds) {
8984
+ const s = Math.max(0, Math.round(totalSeconds));
8985
+ const m = Math.floor(s / 60);
8986
+ const r = s % 60;
8987
+ return `${m}:${r.toString().padStart(2, "0")}`;
8988
+ }
8989
+ function esc(value) {
8990
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
8991
+ }
8992
+ var activeController, OVERLAY_ID, POLL_MS, INLINE_THRESHOLD, SPINNER_FRAMES, spinnerFrame, overlayEl, pollHandle, lastSnapshot, copyFlashUntil, minified, expanded;
8993
+ var init_SessionOverlay = __esm({
8994
+ "src/study/SessionOverlay.ts"() {
8995
+ "use strict";
8996
+ init_logger();
8997
+ activeController = null;
8998
+ OVERLAY_ID = "skuilder-session-overlay";
8999
+ POLL_MS = 300;
9000
+ INLINE_THRESHOLD = 5;
9001
+ SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
9002
+ spinnerFrame = 0;
9003
+ overlayEl = null;
9004
+ pollHandle = null;
9005
+ lastSnapshot = null;
9006
+ copyFlashUntil = 0;
9007
+ minified = false;
9008
+ expanded = {
9009
+ supplyQ: false,
9010
+ failedQ: false,
9011
+ drawn: false
9012
+ };
9013
+ }
9014
+ });
9015
+
9016
+ // src/study/SessionDebugger.ts
9017
+ function showCurrentQueue() {
9018
+ if (!activeSession) {
9019
+ logger.info("[Session Debug] No active session.");
9020
+ return;
9021
+ }
9022
+ const latest = activeSession.queueSnapshots[activeSession.queueSnapshots.length - 1] || activeSession.initialQueues;
9023
+ console.group("\u{1F4CA} Current Queue State");
9024
+ logger.info(`Supply Queue: ${latest.supplyQLength} cards`);
9025
+ if (latest.supplyQNext3 && latest.supplyQNext3.length > 0) {
9026
+ logger.info(` Next: ${latest.supplyQNext3.join(", ")}`);
9027
+ }
9028
+ logger.info(`Failed Queue: ${latest.failedQLength} cards`);
9029
+ console.groupEnd();
9030
+ }
9031
+ function showPresentationHistory(sessionIndex = 0) {
9032
+ const session = sessionIndex === 0 && activeSession ? activeSession : sessionHistory[sessionIndex];
9033
+ if (!session) {
9034
+ logger.info(`[Session Debug] No session found at index ${sessionIndex}`);
9035
+ return;
9036
+ }
9037
+ console.group(`\u{1F4DC} Session History: ${session.sessionId}`);
9038
+ logger.info(`Started: ${session.startTime.toLocaleTimeString()}`);
9039
+ if (session.endTime) {
9040
+ logger.info(`Ended: ${session.endTime.toLocaleTimeString()}`);
9041
+ }
9042
+ logger.info(`Cards presented: ${session.presentations.length}`);
9043
+ if (session.presentations.length > 0) {
9044
+ console.table(
9045
+ session.presentations.map((p) => ({
9046
+ "#": p.sequenceNumber,
9047
+ course: p.courseName || p.courseId.slice(0, 8),
9048
+ origin: p.origin,
9049
+ queue: p.queueSource,
9050
+ score: p.score?.toFixed(3) || "-",
9051
+ time: p.timestamp.toLocaleTimeString()
9052
+ }))
9053
+ );
9054
+ }
9055
+ console.groupEnd();
9056
+ }
9057
+ function showInterleaving(sessionIndex = 0) {
9058
+ const session = sessionIndex === 0 && activeSession ? activeSession : sessionHistory[sessionIndex];
9059
+ if (!session) {
9060
+ logger.info(`[Session Debug] No session found at index ${sessionIndex}`);
9061
+ return;
9062
+ }
9063
+ console.group("\u{1F500} Interleaving Analysis");
9064
+ const courseCounts = /* @__PURE__ */ new Map();
9065
+ const courseOrigins = /* @__PURE__ */ new Map();
9066
+ session.presentations.forEach((p) => {
9067
+ const name = p.courseName || p.courseId;
9068
+ courseCounts.set(name, (courseCounts.get(name) || 0) + 1);
9069
+ if (!courseOrigins.has(name)) {
9070
+ courseOrigins.set(name, { review: 0, new: 0, failed: 0 });
9071
+ }
9072
+ const origins = courseOrigins.get(name);
9073
+ origins[p.origin]++;
9074
+ });
9075
+ logger.info("Course distribution:");
9076
+ console.table(
9077
+ Array.from(courseCounts.entries()).map(([course, count]) => {
9078
+ const origins = courseOrigins.get(course);
9079
+ return {
9080
+ course,
9081
+ total: count,
9082
+ reviews: origins.review,
9083
+ new: origins.new,
9084
+ failed: origins.failed,
9085
+ percentage: (count / session.presentations.length * 100).toFixed(1) + "%"
9086
+ };
9087
+ })
9088
+ );
9089
+ if (session.presentations.length > 0) {
9090
+ logger.info("\nPresentation sequence (first 20):");
9091
+ const sequence = session.presentations.slice(0, 20).map((p, idx) => `${idx + 1}. ${p.courseName || p.courseId.slice(0, 8)} (${p.origin})`).join("\n");
9092
+ logger.info(sequence);
9093
+ }
9094
+ let maxCluster = 0;
9095
+ let currentCluster = 1;
9096
+ let currentCourse = session.presentations[0]?.courseId;
9097
+ for (let i = 1; i < session.presentations.length; i++) {
9098
+ if (session.presentations[i].courseId === currentCourse) {
9099
+ currentCluster++;
9100
+ maxCluster = Math.max(maxCluster, currentCluster);
9101
+ } else {
9102
+ currentCourse = session.presentations[i].courseId;
9103
+ currentCluster = 1;
9104
+ }
9105
+ }
9106
+ if (maxCluster > 3) {
9107
+ logger.info(`
9108
+ \u26A0\uFE0F Detected clustering: max ${maxCluster} cards from same course in a row`);
9109
+ logger.info("This suggests cards are sorted by score rather than round-robin by course.");
9110
+ }
9111
+ console.groupEnd();
9112
+ }
9113
+ function mountSessionDebugger() {
9114
+ if (typeof window === "undefined") return;
9115
+ const win = window;
9116
+ win.skuilder = win.skuilder || {};
9117
+ win.skuilder.session = sessionDebugAPI;
9118
+ }
9119
+ var activeSession, sessionHistory, sessionDebugAPI;
9120
+ var init_SessionDebugger = __esm({
9121
+ "src/study/SessionDebugger.ts"() {
9122
+ "use strict";
9123
+ init_logger();
9124
+ init_PipelineDebugger();
9125
+ init_SrsDebugger();
9126
+ init_StrategyPressureDebugger();
9127
+ init_SessionOverlay();
9128
+ activeSession = null;
9129
+ sessionHistory = [];
9130
+ sessionDebugAPI = {
9131
+ /**
9132
+ * Get raw session history for programmatic access.
9133
+ */
9134
+ get sessions() {
9135
+ return [...sessionHistory];
9136
+ },
9137
+ /**
9138
+ * Get active session if any.
7032
9139
  */
7033
- async showCourseRegistrations() {
7034
- const userDB = getUserDB();
7035
- if (!userDB) return;
7036
- try {
7037
- const registrations = await userDB.getActiveCourses();
7038
- console.group("\u{1F4DA} Course Registrations");
7039
- logger.info(`Total: ${registrations.length}`);
7040
- if (registrations.length > 0) {
7041
- console.table(
7042
- registrations.map((reg) => ({
7043
- courseId: reg.courseID,
7044
- status: reg.status || "active",
7045
- elo: typeof reg.elo === "number" ? reg.elo.toFixed(0) : reg.elo?.global?.score?.toFixed(0) || "N/A"
7046
- }))
7047
- );
7048
- }
7049
- console.groupEnd();
7050
- } catch (err) {
7051
- logger.info(`Error loading course registrations: ${err.message}`);
7052
- }
9140
+ get active() {
9141
+ return activeSession;
7053
9142
  },
7054
9143
  /**
7055
- * Show card history for a specific card
9144
+ * Show current queue state.
7056
9145
  */
7057
- async showCardHistory(cardId) {
7058
- const rawDB = getRawDB();
7059
- if (!rawDB) return;
7060
- try {
7061
- const result = await filterAllDocsByPrefix2(rawDB, DocTypePrefixes["CARDRECORD" /* CARDRECORD */]);
7062
- const cardHistories = result.rows.filter((row) => row.doc && row.doc.cardID === cardId).map((row) => row.doc);
7063
- console.group(`\u{1F3B4} Card History: ${cardId}`);
7064
- logger.info(`Total interactions: ${cardHistories.length}`);
7065
- if (cardHistories.length > 0) {
7066
- const sorted = cardHistories.sort(
7067
- (a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
7068
- );
7069
- console.table(
7070
- sorted.slice(0, 20).map((doc) => ({
7071
- time: formatTimestamp(doc.timestamp),
7072
- outcome: doc.outcome || "N/A",
7073
- duration: doc.duration ? `${(doc.duration / 1e3).toFixed(1)}s` : "N/A",
7074
- courseId: doc.courseId
7075
- }))
7076
- );
7077
- if (sorted.length > 20) {
7078
- logger.info(`... and ${sorted.length - 20} more interactions`);
7079
- }
7080
- }
7081
- console.groupEnd();
7082
- } catch (err) {
7083
- logger.info(`Error loading card history: ${err.message}`);
7084
- }
9146
+ showQueue() {
9147
+ showCurrentQueue();
7085
9148
  },
7086
9149
  /**
7087
- * Query documents by type
9150
+ * Toggle the pinned, live-updating DOM overlay for the active controller
9151
+ * (queues, session hints, timer). No-ops in non-browser hosts.
7088
9152
  */
7089
- async queryByType(docType, limit = 50) {
7090
- const rawDB = getRawDB();
7091
- if (!rawDB) return;
7092
- try {
7093
- const prefix = DocTypePrefixes[DocType[docType]];
7094
- if (!prefix) {
7095
- logger.info(`Unknown document type: ${docType}`);
7096
- return;
7097
- }
7098
- const result = await filterAllDocsByPrefix2(rawDB, prefix);
7099
- console.group(`\u{1F4C4} Documents: ${docType}`);
7100
- logger.info(`Total: ${result.rows.length}`);
7101
- logger.info(`Prefix: ${prefix}`);
7102
- if (result.rows.length > 0) {
7103
- logger.info("Sample documents:");
7104
- const samples = result.rows.slice(0, Math.min(limit, result.rows.length));
7105
- for (const row of samples) {
7106
- logger.info(`
7107
- ${row.id}:`);
7108
- logger.info(JSON.stringify(row.doc, null, 2));
7109
- }
7110
- if (result.rows.length > limit) {
7111
- logger.info(`
7112
- ... and ${result.rows.length - limit} more documents`);
7113
- }
7114
- }
7115
- console.groupEnd();
7116
- } catch (err) {
7117
- logger.info(`Error querying documents: ${err.message}`);
7118
- }
9153
+ dbgOverlay() {
9154
+ toggleSessionOverlay();
7119
9155
  },
7120
9156
  /**
7121
- * Show database info and statistics
9157
+ * Show presentation history for current or past session.
7122
9158
  */
7123
- async dbInfo() {
7124
- const rawDB = getRawDB();
7125
- if (!rawDB) return;
7126
- try {
7127
- const info = await rawDB.info();
7128
- console.group("\u2139\uFE0F Database Information");
7129
- logger.info(`Database name: ${info.db_name}`);
7130
- logger.info(`Total documents: ${info.doc_count}`);
7131
- logger.info(`Update sequence: ${info.update_seq}`);
7132
- if ("disk_size" in info) {
7133
- logger.info(`Disk size: ${(info.disk_size || 0) / 1024 / 1024} MB`);
7134
- }
7135
- logger.info("\nDocument counts by type:");
7136
- const allDocs = await rawDB.allDocs({ include_docs: false });
7137
- const typeCounts = /* @__PURE__ */ new Map();
7138
- for (const row of allDocs.rows) {
7139
- let prefix = "other";
7140
- for (const [type, typePrefix] of Object.entries(DocTypePrefixes)) {
7141
- if (row.id.startsWith(typePrefix)) {
7142
- prefix = type;
7143
- break;
7144
- }
7145
- }
7146
- typeCounts.set(prefix, (typeCounts.get(prefix) || 0) + 1);
7147
- }
7148
- console.table(
7149
- Array.from(typeCounts.entries()).sort((a, b) => b[1] - a[1]).map(([type, count]) => ({ type, count }))
7150
- );
7151
- console.groupEnd();
7152
- } catch (err) {
7153
- logger.info(`Error getting database info: ${err.message}`);
7154
- }
9159
+ showHistory(sessionIndex = 0) {
9160
+ showPresentationHistory(sessionIndex);
7155
9161
  },
7156
9162
  /**
7157
- * List all document types
9163
+ * Analyze course interleaving pattern.
7158
9164
  */
7159
- listDocTypes() {
7160
- console.group("\u{1F4CB} Available Document Types");
7161
- logger.info("Use with queryByType(type):");
7162
- for (const [type, prefix] of Object.entries(DocTypePrefixes)) {
7163
- logger.info(` ${type.padEnd(30)} \u2192 prefix: "${prefix}"`);
7164
- }
7165
- console.groupEnd();
9165
+ showInterleaving(sessionIndex = 0) {
9166
+ showInterleaving(sessionIndex);
7166
9167
  },
7167
9168
  /**
7168
- * Export database contents (limited, for debugging)
9169
+ * List all tracked sessions.
7169
9170
  */
7170
- async export(includeContent = false) {
7171
- const rawDB = getRawDB();
7172
- const userDB = getUserDB();
7173
- if (!rawDB || !userDB) return "{}";
7174
- try {
7175
- const data = {
7176
- username: userDB.getUsername(),
7177
- loggedIn: userDB.isLoggedIn(),
7178
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
7179
- };
7180
- if (includeContent) {
7181
- const allDocs = await rawDB.allDocs({ include_docs: true });
7182
- data.documents = allDocs.rows.map((row) => ({
7183
- id: row.id,
7184
- doc: row.doc
7185
- }));
7186
- data.totalDocs = allDocs.rows.length;
7187
- } else {
7188
- const allDocs = await rawDB.allDocs({ include_docs: false });
7189
- data.totalDocs = allDocs.rows.length;
7190
- const typeCounts = /* @__PURE__ */ new Map();
7191
- for (const row of allDocs.rows) {
7192
- let prefix = "other";
7193
- for (const [type, typePrefix] of Object.entries(DocTypePrefixes)) {
7194
- if (row.id.startsWith(typePrefix)) {
7195
- prefix = type;
7196
- break;
7197
- }
7198
- }
7199
- typeCounts.set(prefix, (typeCounts.get(prefix) || 0) + 1);
7200
- }
7201
- data.docCounts = Object.fromEntries(typeCounts);
7202
- }
7203
- const json = JSON.stringify(data, null, 2);
7204
- logger.info("[UserDB Debug] Database info exported. Copy the returned string or use:");
7205
- logger.info(" copy(window.skuilder.userdb.export())");
7206
- if (!includeContent) {
7207
- logger.info(" For full content export: window.skuilder.userdb.export(true)");
7208
- }
7209
- return json;
7210
- } catch (err) {
7211
- logger.info(`Error exporting database: ${err.message}`);
7212
- return "{}";
9171
+ listSessions() {
9172
+ if (activeSession) {
9173
+ logger.info(`Active session: ${activeSession.sessionId} (${activeSession.presentations.length} cards presented)`);
9174
+ }
9175
+ if (sessionHistory.length === 0) {
9176
+ logger.info("[Session Debug] No completed sessions in history.");
9177
+ return;
7213
9178
  }
9179
+ console.table(
9180
+ sessionHistory.map((s, idx) => ({
9181
+ index: idx,
9182
+ id: s.sessionId.slice(-8),
9183
+ started: s.startTime.toLocaleTimeString(),
9184
+ ended: s.endTime?.toLocaleTimeString() || "incomplete",
9185
+ cards: s.presentations.length
9186
+ }))
9187
+ );
7214
9188
  },
7215
9189
  /**
7216
- * Execute raw PouchDB query
9190
+ * Export session history as JSON for bug reports.
7217
9191
  */
7218
- async raw(queryFn) {
7219
- const rawDB = getRawDB();
7220
- if (!rawDB) return;
7221
- try {
7222
- const result = await queryFn(rawDB);
7223
- logger.info("[UserDB Debug] Query result:");
7224
- logger.info(result);
7225
- } catch (err) {
7226
- logger.info(`[UserDB Debug] Query error: ${err.message}`);
7227
- }
9192
+ export() {
9193
+ const data = {
9194
+ active: activeSession,
9195
+ history: sessionHistory
9196
+ };
9197
+ const json = JSON.stringify(data, null, 2);
9198
+ logger.info("[Session Debug] Session data exported. Copy the returned string or use:");
9199
+ logger.info(" copy(window.skuilder.session.export())");
9200
+ return json;
7228
9201
  },
7229
9202
  /**
7230
- * Show help
9203
+ * Clear session history.
9204
+ */
9205
+ clear() {
9206
+ sessionHistory.length = 0;
9207
+ logger.info("[Session Debug] Session history cleared.");
9208
+ },
9209
+ /**
9210
+ * Show help.
7231
9211
  */
7232
9212
  help() {
7233
9213
  logger.info(`
7234
- \u{1F527} UserDB Debug API
9214
+ \u{1F3AF} Session Debug API
7235
9215
 
7236
9216
  Commands:
7237
- .showUser() Show current user info and config
7238
- .showScheduledReviews(courseId?) Show scheduled reviews (optionally filter by course)
7239
- .showCourseRegistrations() Show all course registrations
7240
- .showCardHistory(cardId) Show interaction history for a card
7241
- .queryByType(docType, limit?) Query documents by type (e.g., 'SCHEDULED_CARD')
7242
- .listDocTypes() List all available document types
7243
- .dbInfo() Show database info and statistics
7244
- .export(includeContent?) Export database info (true = include all docs)
7245
- .raw(queryFn) Execute raw PouchDB query
7246
- .help() Show this help message
9217
+ .dbgOverlay() Toggle the pinned live overlay (queues, hints, timer)
9218
+ .showQueue() Show current queue state (active session only)
9219
+ .showHistory(index?) Show presentation history (0=current/last, 1=previous, etc)
9220
+ .showInterleaving(index?) Analyze course interleaving pattern
9221
+ .listSessions() List all tracked sessions
9222
+ .export() Export session data as JSON for bug reports
9223
+ .clear() Clear session history
9224
+ .sessions Access raw session history array
9225
+ .active Access active session (if any)
9226
+ .help() Show this help message
7247
9227
 
7248
- Examples:
7249
- window.skuilder.userdb.showUser()
7250
- window.skuilder.userdb.showScheduledReviews('course123')
7251
- window.skuilder.userdb.queryByType('SCHEDULED_CARD', 10)
7252
- window.skuilder.userdb.raw(db => db.allDocs({ limit: 5 }))
9228
+ Example:
9229
+ window.skuilder.session.showHistory()
9230
+ window.skuilder.session.showInterleaving()
9231
+ window.skuilder.session.showQueue()
7253
9232
  `);
7254
9233
  }
7255
9234
  };
7256
- mountUserDBDebugger();
9235
+ mountSessionDebugger();
7257
9236
  }
7258
9237
  });
7259
9238
 
7260
- // src/core/index.ts
7261
- var init_core = __esm({
7262
- "src/core/index.ts"() {
9239
+ // src/study/SessionController.ts
9240
+ var init_SessionController = __esm({
9241
+ "src/study/SessionController.ts"() {
7263
9242
  "use strict";
7264
- init_interfaces();
9243
+ init_SrsService();
9244
+ init_EloService();
9245
+ init_ResponseProcessor();
9246
+ init_CardHydrationService();
9247
+ init_ItemQueue();
9248
+ init_couch();
9249
+ init_core();
7265
9250
  init_types_legacy();
7266
- init_user();
7267
- init_strategyState();
7268
- init_userOutcome();
7269
9251
  init_studySession();
7270
- init_hydration();
7271
- init_Loggable();
7272
- init_util();
9252
+ init_recording();
9253
+ init_util2();
7273
9254
  init_navigators();
7274
- init_bulkImport();
7275
- init_orchestration();
7276
- init_UserDBDebugger();
9255
+ init_Pipeline();
9256
+ init_SourceMixer();
9257
+ init_MixerDebugger();
9258
+ init_SessionDebugger();
9259
+ init_SessionOverlay();
9260
+ init_logger();
9261
+ }
9262
+ });
9263
+
9264
+ // src/study/index.ts
9265
+ var init_study = __esm({
9266
+ "src/study/index.ts"() {
9267
+ "use strict";
9268
+ init_SessionController();
9269
+ init_SourceMixer();
9270
+ init_SpacedRepetition();
9271
+ init_TagFilteredContentSource();
9272
+ init_MixerDebugger();
9273
+ init_SessionDebugger();
9274
+ init_SessionOverlay();
7277
9275
  }
7278
9276
  });
7279
9277
 
7280
9278
  // src/impl/couch/user-course-relDB.ts
7281
- import moment4 from "moment";
9279
+ import moment6 from "moment";
7282
9280
  var UsrCrsData;
7283
9281
  var init_user_course_relDB = __esm({
7284
9282
  "src/impl/couch/user-course-relDB.ts"() {
@@ -7292,11 +9290,11 @@ var init_user_course_relDB = __esm({
7292
9290
  this._courseId = courseId;
7293
9291
  }
7294
9292
  async getReviewsForcast(daysCount) {
7295
- const time = moment4.utc().add(daysCount, "days");
9293
+ const time = moment6.utc().add(daysCount, "days");
7296
9294
  return this.getReviewstoDate(time);
7297
9295
  }
7298
9296
  async getPendingReviews() {
7299
- const now = moment4.utc();
9297
+ const now = moment6.utc();
7300
9298
  return this.getReviewstoDate(now);
7301
9299
  }
7302
9300
  async getScheduledReviewCount() {
@@ -7332,7 +9330,7 @@ var init_user_course_relDB = __esm({
7332
9330
  `Fetching ${this.user.getUsername()}'s scheduled reviews for course ${this._courseId}.`
7333
9331
  );
7334
9332
  return allReviews.filter((review) => {
7335
- const reviewTime = moment4.utc(review.reviewTime);
9333
+ const reviewTime = moment6.utc(review.reviewTime);
7336
9334
  return targetDate.isAfter(reviewTime);
7337
9335
  });
7338
9336
  }
@@ -7342,7 +9340,7 @@ var init_user_course_relDB = __esm({
7342
9340
 
7343
9341
  // src/impl/common/BaseUserDB.ts
7344
9342
  import { Status as Status3 } from "@vue-skuilder/common";
7345
- import moment5 from "moment";
9343
+ import moment7 from "moment";
7346
9344
  function withTimeout(p, ms, label) {
7347
9345
  let timer;
7348
9346
  return Promise.race([
@@ -7537,6 +9535,7 @@ var init_BaseUserDB = __esm({
7537
9535
  init_util();
7538
9536
  init_types_legacy();
7539
9537
  init_logger();
9538
+ init_study();
7540
9539
  init_userDBHelpers();
7541
9540
  init_updateQueue();
7542
9541
  init_user_course_relDB();
@@ -7860,7 +9859,7 @@ Currently logged-in as ${this._username}.`
7860
9859
  );
7861
9860
  return reviews.rows.filter((r) => {
7862
9861
  if (r.id.startsWith(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */])) {
7863
- const date = moment5.utc(
9862
+ const date = moment7.utc(
7864
9863
  r.id.substr(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */].length),
7865
9864
  REVIEW_TIME_FORMAT2
7866
9865
  );
@@ -7873,11 +9872,11 @@ Currently logged-in as ${this._username}.`
7873
9872
  }).map((r) => r.doc);
7874
9873
  }
7875
9874
  async getReviewsForcast(daysCount, course_id) {
7876
- const time = moment5.utc().add(daysCount, "days");
9875
+ const time = moment7.utc().add(daysCount, "days");
7877
9876
  return this.getReviewstoDate(time, course_id);
7878
9877
  }
7879
9878
  async getPendingReviews(course_id) {
7880
- const now = moment5.utc();
9879
+ const now = moment7.utc();
7881
9880
  return this.getReviewstoDate(now, course_id);
7882
9881
  }
7883
9882
  async getScheduledReviewCount(course_id) {
@@ -8253,15 +10252,20 @@ Currently logged-in as ${this._username}.`
8253
10252
  */
8254
10253
  async putCardRecord(record) {
8255
10254
  const cardHistoryID = getCardHistoryID(record.courseID, record.cardID);
8256
- record.timeStamp = moment5.utc(record.timeStamp).toString();
10255
+ record.timeStamp = moment7.utc(record.timeStamp).toString();
8257
10256
  try {
8258
10257
  const cardHistory = await this.update(
8259
10258
  cardHistoryID,
8260
10259
  function(h) {
8261
10260
  h.records.push(record);
8262
10261
  h.bestInterval = h.bestInterval || 0;
8263
- h.lapses = h.lapses || 0;
8264
- h.streak = h.streak || 0;
10262
+ if (areQuestionRecords(h)) {
10263
+ h.lapses = getLapses(h.records);
10264
+ h.streak = getStreak(h.records);
10265
+ } else {
10266
+ h.lapses = h.lapses || 0;
10267
+ h.streak = h.streak || 0;
10268
+ }
8265
10269
  return h;
8266
10270
  }
8267
10271
  );
@@ -8269,7 +10273,7 @@ Currently logged-in as ${this._username}.`
8269
10273
  const ret = {
8270
10274
  ...record2
8271
10275
  };
8272
- ret.timeStamp = moment5.utc(record2.timeStamp);
10276
+ ret.timeStamp = moment7.utc(record2.timeStamp);
8273
10277
  return ret;
8274
10278
  });
8275
10279
  return cardHistory;
@@ -8997,7 +11001,7 @@ var init_CourseSyncService = __esm({
8997
11001
  });
8998
11002
 
8999
11003
  // src/impl/couch/auth.ts
9000
- import fetch from "cross-fetch";
11004
+ import fetch2 from "cross-fetch";
9001
11005
  async function getCurrentSession() {
9002
11006
  try {
9003
11007
  if (ENV.COUCHDB_SERVER_URL === NOT_SET || ENV.COUCHDB_SERVER_PROTOCOL === NOT_SET) {
@@ -9006,7 +11010,7 @@ async function getCurrentSession() {
9006
11010
  const baseUrl = ENV.COUCHDB_SERVER_URL.endsWith("/") ? ENV.COUCHDB_SERVER_URL.slice(0, -1) : ENV.COUCHDB_SERVER_URL;
9007
11011
  const url = `${ENV.COUCHDB_SERVER_PROTOCOL}://${baseUrl}/_session`;
9008
11012
  logger.debug(`Attempting session check at: ${url}`);
9009
- const response = await fetch(url, {
11013
+ const response = await fetch2(url, {
9010
11014
  method: "GET",
9011
11015
  credentials: "include"
9012
11016
  });
@@ -9342,8 +11346,8 @@ var init_CouchDBSyncStrategy = __esm({
9342
11346
  });
9343
11347
 
9344
11348
  // src/impl/couch/index.ts
9345
- import fetch2 from "cross-fetch";
9346
- import moment6 from "moment";
11349
+ import fetch3 from "cross-fetch";
11350
+ import moment8 from "moment";
9347
11351
  import process2 from "process";
9348
11352
  function hexEncode2(str) {
9349
11353
  let hex;
@@ -9404,7 +11408,7 @@ async function usernameIsAvailable(username) {
9404
11408
  log(`Checking availability of ${username}`);
9405
11409
  try {
9406
11410
  const url = ENV.COUCHDB_SERVER_URL + "userdb-" + hexEncode2(username);
9407
- const response = await fetch2(url, { method: "HEAD" });
11411
+ const response = await fetch3(url, { method: "HEAD" });
9408
11412
  return response.status === 404;
9409
11413
  } catch (error) {
9410
11414
  log(`Error checking username availability: ${error}`);
@@ -9412,7 +11416,7 @@ async function usernameIsAvailable(username) {
9412
11416
  }
9413
11417
  }
9414
11418
  function updateGuestAccountExpirationDate2(guestDB) {
9415
- const currentTime = moment6.utc();
11419
+ const currentTime = moment8.utc();
9416
11420
  const expirationDate = currentTime.add(2, "months").toISOString();
9417
11421
  void guestDB.get(expiryDocID).then((doc) => {
9418
11422
  return guestDB.put({
@@ -9475,7 +11479,7 @@ function getCouchUserDB(username) {
9475
11479
  return ret;
9476
11480
  }
9477
11481
  function scheduleCardReview(review) {
9478
- const now = moment6.utc();
11482
+ const now = moment8.utc();
9479
11483
  logger.info(`Scheduling for review in: ${review.time.diff(now, "h") / 24} days`);
9480
11484
  void getCouchUserDB(review.user).put({
9481
11485
  _id: DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */] + review.time.format(REVIEW_TIME_FORMAT),