@vue-skuilder/db 0.2.24 → 0.2.26

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