@vue-skuilder/platform-ui 0.2.22 → 0.2.24

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 (92) hide show
  1. package/dist/assets/{About-BinSo4od.js → About-BpF64SeZ.js} +2 -2
  2. package/dist/assets/{About-BinSo4od.js.map → About-BpF64SeZ.js.map} +1 -1
  3. package/dist/assets/{AdminDashboard-CEb-vIi7.js → AdminDashboard-BpbXoTgh.js} +2 -2
  4. package/dist/assets/{AdminDashboard-CEb-vIi7.js.map → AdminDashboard-BpbXoTgh.js.map} +1 -1
  5. package/dist/assets/{ClassroomCtrlPanel-DXw-5Njn.js → ClassroomCtrlPanel-B224_mhy.js} +2 -2
  6. package/dist/assets/{ClassroomCtrlPanel-DXw-5Njn.js.map → ClassroomCtrlPanel-B224_mhy.js.map} +1 -1
  7. package/dist/assets/{Classrooms-DCMbsfUL.js → Classrooms-BCfInF-a.js} +2 -2
  8. package/dist/assets/{Classrooms-DCMbsfUL.js.map → Classrooms-BCfInF-a.js.map} +1 -1
  9. package/dist/assets/{CourseRouter-ESl00XJP.js → CourseRouter-Bzg7X5kl.js} +2 -2
  10. package/dist/assets/{CourseRouter-ESl00XJP.js.map → CourseRouter-Bzg7X5kl.js.map} +1 -1
  11. package/dist/assets/{CourseWare-BTFRjgBR-BmnClSwv.js → CourseWare-BTFRjgBR-Dxg0h8E2.js} +3 -3
  12. package/dist/assets/{CourseWare-BTFRjgBR-BmnClSwv.js.map → CourseWare-BTFRjgBR-Dxg0h8E2.js.map} +1 -1
  13. package/dist/assets/{Courses-B7YKtsRZ.js → Courses-BofXy-aW.js} +2 -2
  14. package/dist/assets/{Courses-B7YKtsRZ.js.map → Courses-BofXy-aW.js.map} +1 -1
  15. package/dist/assets/{EloModeration-DCFtgWVo.js → EloModeration-B6Hw_tBP.js} +2 -2
  16. package/dist/assets/{EloModeration-DCFtgWVo.js.map → EloModeration-B6Hw_tBP.js.map} +1 -1
  17. package/dist/assets/{JoinCode-_hcfvpGP.js → JoinCode-CZPavfrz.js} +2 -2
  18. package/dist/assets/{JoinCode-_hcfvpGP.js.map → JoinCode-CZPavfrz.js.map} +1 -1
  19. package/dist/assets/{NewCourseDialog-Br4_PUce.js → NewCourseDialog-DDLWdnzs.js} +2 -2
  20. package/dist/assets/{NewCourseDialog-Br4_PUce.js.map → NewCourseDialog-DDLWdnzs.js.map} +1 -1
  21. package/dist/assets/{ReleaseNotes-zQgb0Cds.js → ReleaseNotes-BZGVYO7V.js} +2 -2
  22. package/dist/assets/{ReleaseNotes-zQgb0Cds.js.map → ReleaseNotes-BZGVYO7V.js.map} +1 -1
  23. package/dist/assets/{RequestPasswordReset-4lAadmzI.js → RequestPasswordReset-Cv2U8l2g.js} +2 -2
  24. package/dist/assets/{RequestPasswordReset-4lAadmzI.js.map → RequestPasswordReset-Cv2U8l2g.js.map} +1 -1
  25. package/dist/assets/{ResetPassword-sVeO4SUM.js → ResetPassword-Cq2ZwWPS.js} +2 -2
  26. package/dist/assets/{ResetPassword-sVeO4SUM.js.map → ResetPassword-Cq2ZwWPS.js.map} +1 -1
  27. package/dist/assets/{Study-l5ZdLcD-.js → Study-CPMb-XdT.js} +2 -2
  28. package/dist/assets/{Study-l5ZdLcD-.js.map → Study-CPMb-XdT.js.map} +1 -1
  29. package/dist/assets/{TagInformation-CZMcMmP1.js → TagInformation-B4zvmBwR.js} +2 -2
  30. package/dist/assets/{TagInformation-CZMcMmP1.js.map → TagInformation-B4zvmBwR.js.map} +1 -1
  31. package/dist/assets/{User-DmDgN7WO.js → User-husKeJRJ.js} +2 -2
  32. package/dist/assets/{User-DmDgN7WO.js.map → User-husKeJRJ.js.map} +1 -1
  33. package/dist/assets/{UserStats-BmxoNxCx.js → UserStats-B_-PVqRz.js} +2 -2
  34. package/dist/assets/{UserStats-BmxoNxCx.js.map → UserStats-B_-PVqRz.js.map} +1 -1
  35. package/dist/assets/{VerifyEmail-C-fwuCII.js → VerifyEmail-9ZWpiPE5.js} +2 -2
  36. package/dist/assets/{VerifyEmail-C-fwuCII.js.map → VerifyEmail-9ZWpiPE5.js.map} +1 -1
  37. package/dist/assets/{chess-E2uOAyQS-DjXjV5rB.js → chess-E2uOAyQS-COCon4Zz.js} +2 -2
  38. package/dist/assets/{chess-E2uOAyQS-DjXjV5rB.js.map → chess-E2uOAyQS-COCon4Zz.js.map} +1 -1
  39. package/dist/assets/chess-Lfm7Fsvs-SecdR1IX.js +1 -0
  40. package/dist/assets/common-ui.es-Bkhr3DWA.js +1 -0
  41. package/dist/assets/{common-ui.es-BWBbEz1h.js → common-ui.es-yyDL5WUq.js} +4 -4
  42. package/dist/assets/{common-ui.es-BWBbEz1h.js.map → common-ui.es-yyDL5WUq.js.map} +1 -1
  43. package/dist/assets/{dist-DcjcehoT.js → dist-BFWCBAj7.js} +3 -3
  44. package/dist/assets/{dist-DcjcehoT.js.map → dist-BFWCBAj7.js.map} +1 -1
  45. package/dist/assets/dist-BRPOqMYr.js +1 -0
  46. package/dist/assets/dist-BYxQfFzk.js +1 -0
  47. package/dist/assets/{dist-ByU4XK4n.js → dist-CG_VzJ5d.js} +13 -13
  48. package/dist/assets/{dist-ByU4XK4n.js.map → dist-CG_VzJ5d.js.map} +1 -1
  49. package/dist/assets/{edit-ui.es-Bw717-xJ.js → edit-ui.es-B_2n06Oi.js} +2 -2
  50. package/dist/assets/{edit-ui.es-Bw717-xJ.js.map → edit-ui.es-B_2n06Oi.js.map} +1 -1
  51. package/dist/assets/edit-ui.es-BiLWpW2o.js +1 -0
  52. package/dist/assets/{french-Dk7YG8Td-I8ls7jxJ.js → french-Dk7YG8Td-C94Hkiug.js} +2 -2
  53. package/dist/assets/{french-Dk7YG8Td-I8ls7jxJ.js.map → french-Dk7YG8Td-C94Hkiug.js.map} +1 -1
  54. package/dist/assets/french-evUMlbbq-DTqj5k5M.js +1 -0
  55. package/dist/assets/{index-i0-XaMZg.js → index-D7SxgwYb.js} +4 -4
  56. package/dist/assets/{index-i0-XaMZg.js.map → index-D7SxgwYb.js.map} +1 -1
  57. package/dist/assets/{math-B4HbgYf6-CPsDCMOB.js → math-B4HbgYf6-DBLreBi2.js} +2 -2
  58. package/dist/assets/{math-B4HbgYf6-CPsDCMOB.js.map → math-B4HbgYf6-DBLreBi2.js.map} +1 -1
  59. package/dist/assets/math-DYni7rRl-C-q3S77b.js +1 -0
  60. package/dist/assets/piano-BN5Btq91-BNaIdA_w.js +1 -0
  61. package/dist/assets/{piano-DF1g6yaX-CZcQ5tI1.js → piano-DF1g6yaX-oYVxyoaj.js} +2 -2
  62. package/dist/assets/{piano-DF1g6yaX-CZcQ5tI1.js.map → piano-DF1g6yaX-oYVxyoaj.js.map} +1 -1
  63. package/dist/assets/{pitch-CgGJFkZ1-DAOLVkSo.js → pitch-CgGJFkZ1-D21Bc5mk.js} +2 -2
  64. package/dist/assets/{pitch-CgGJFkZ1-DAOLVkSo.js.map → pitch-CgGJFkZ1-D21Bc5mk.js.map} +1 -1
  65. package/dist/assets/pitch-Dn0iNqiS-iGo6N2ya.js +1 -0
  66. package/dist/assets/{server-Bx1Fjv_u.js → server-CIZiVq-K.js} +2 -2
  67. package/dist/assets/{server-Bx1Fjv_u.js.map → server-CIZiVq-K.js.map} +1 -1
  68. package/dist/assets/{sightsing-BFQ7HRig-Bnza0c2V.js → sightsing-BFQ7HRig-D14v58C-.js} +2 -2
  69. package/dist/assets/{sightsing-BFQ7HRig-Bnza0c2V.js.map → sightsing-BFQ7HRig-D14v58C-.js.map} +1 -1
  70. package/dist/assets/sightsing-CJX3k0Fd-DwaChJyk.js +1 -0
  71. package/dist/assets/{typing-BevtfWlp-hJvw_7v8.js → typing-BevtfWlp-DpsEfl6-.js} +2 -2
  72. package/dist/assets/{typing-BevtfWlp-hJvw_7v8.js.map → typing-BevtfWlp-DpsEfl6-.js.map} +1 -1
  73. package/dist/assets/typing-k-ojjO7G-DrC0GBAS.js +1 -0
  74. package/dist/assets/{word-work-BOnRlZgd-ni_sRS1f.js → word-work-BOnRlZgd-CagAkKsF.js} +2 -2
  75. package/dist/assets/{word-work-BOnRlZgd-ni_sRS1f.js.map → word-work-BOnRlZgd-CagAkKsF.js.map} +1 -1
  76. package/dist/assets/word-work-Dd6tIKrt-CDvI3FpH.js +1 -0
  77. package/dist/index.html +3 -3
  78. package/dist/sw.js +1 -1
  79. package/dist/sw.js.map +1 -1
  80. package/package.json +7 -7
  81. package/dist/assets/chess-Lfm7Fsvs-DWq5aKTF.js +0 -1
  82. package/dist/assets/common-ui.es-BfQE1HxT.js +0 -1
  83. package/dist/assets/dist-CFrhyyIr.js +0 -1
  84. package/dist/assets/dist-DGZeSkEv.js +0 -1
  85. package/dist/assets/edit-ui.es-DRnztFjo.js +0 -1
  86. package/dist/assets/french-evUMlbbq-CH812tTA.js +0 -1
  87. package/dist/assets/math-DYni7rRl-A9MtWwfu.js +0 -1
  88. package/dist/assets/piano-BN5Btq91-CU1e1CoX.js +0 -1
  89. package/dist/assets/pitch-Dn0iNqiS-V_L5g-6M.js +0 -1
  90. package/dist/assets/sightsing-CJX3k0Fd-CvR9PU-f.js +0 -1
  91. package/dist/assets/typing-k-ojjO7G-DL0IEDBs.js +0 -1
  92. package/dist/assets/word-work-Dd6tIKrt-BqfM1y62.js +0 -1
@@ -306,17 +306,17 @@ Examples:
306
306
  window.skuilder.userdb.queryByType('SCHEDULED_CARD', 10)
307
307
  window.skuilder.userdb.raw(db => db.allDocs({ limit: 5 }))
308
308
  `)}},mountUserDBDebugger()}}),init_core=__esm({"src/core/index.ts"(){init_interfaces(),init_types_legacy(),init_user(),init_strategyState(),init_userOutcome(),init_studySession(),init_hydration(),init_Loggable(),init_util(),init_navigators(),init_bulkImport(),init_orchestration(),init_UserDBDebugger()}});init_core(),init_courseLookupDB(),init_logger();function isDataShapeRegistered(e,t){let n=NameSpacer.getDataShapeString({dataShape:e.name,course:e.course});return t.dataShapes.find(e=>e.name===n)!==void 0}function isDataShapeSchemaAvailable(e,t){let n=NameSpacer.getDataShapeString({dataShape:e.name,course:e.course}),r=t.dataShapes.find(e=>e.name===n);return r!==void 0&&r.serializedZodSchema!==void 0}function isQuestionTypeRegistered(e,t){let n=NameSpacer.getQuestionString({course:e.course,questionType:e.name});return t.questionTypes.some(e=>e.name===n)}function processCustomQuestionsData(e){let t=[],n=[],r=e.courses.map(e=>e.name);return e.questionClasses.forEach(a=>{let o=r.length>0?r[0]:e.meta.packageName;a.dataShapes&&Array.isArray(a.dataShapes)&&a.dataShapes.forEach(e=>{t.push({name:e.name,course:o,dataShape:e})}),n.push({name:a.name,course:o,questionClass:a,dataShapes:a.dataShapes||[],views:a.views||[]})}),{dataShapes:t,questions:n}}function registerDataShape(e,t){let n=NameSpacer.getDataShapeString({dataShape:e.name,course:e.course}),r;try{r=toZodJSON(e.dataShape)}catch(e){logger.warn(`Failed to generate schema for ${n}:`,e),r=void 0}let a=t.dataShapes.findIndex(e=>e.name===n);if(a!==-1){let o=t.dataShapes[a];return o.serializedZodSchema===r?(logger.info(`DataShape '${e.name}' from '${e.course}' already registered with identical schema`),!1):(o.serializedZodSchema?logger.info(`DataShape '${e.name}' from '${e.course}' schema has changed, updating...`):logger.info(`DataShape '${e.name}' from '${e.course}' already registered, but with no schema. Adding schema to existing entry`),t.dataShapes[a]={name:n,questionTypes:o.questionTypes,serializedZodSchema:r},logger.info(`Updated DataShape: ${n}`),!0)}return t.dataShapes.push({name:n,questionTypes:[],serializedZodSchema:r}),logger.info(`Registered DataShape: ${n}`),!0}function registerQuestionType(e,t){if(isQuestionTypeRegistered(e,t))return logger.info(`QuestionType '${e.name}' from '${e.course}' already registered`),!1;let n=NameSpacer.getQuestionString({course:e.course,questionType:e.name}),r=e.views.map(e=>e.name?e.name:`unnamedComponent`),a=e.dataShapes.map(t=>NameSpacer.getDataShapeString({course:e.course,dataShape:t.name}));return t.questionTypes.push({name:n,viewList:r,dataShapeList:a}),e.dataShapes.forEach(r=>{let a=NameSpacer.getDataShapeString({course:e.course,dataShape:r.name});for(let e of t.dataShapes)e.name===a&&e.questionTypes.push(n)}),logger.info(`Registered QuestionType: ${n}`),!0}function removeDataShape(e,t){let n=t.dataShapes.findIndex(t=>t.name===e);return n===-1?(logger.info(`DataShape '${e}' not found in course config`),!1):(t.dataShapes.splice(n,1),t.questionTypes.forEach(t=>{let n=t.dataShapeList.indexOf(e);n!==-1&&t.dataShapeList.splice(n,1)}),logger.info(`Removed DataShape: ${e}`),!0)}function removeQuestionType(e,t){let n=t.questionTypes.findIndex(t=>t.name===e);return n===-1?(logger.info(`QuestionType '${e}' not found in course config`),!1):(t.questionTypes.splice(n,1),t.dataShapes.forEach(t=>{let n=t.questionTypes.indexOf(e);n!==-1&&t.questionTypes.splice(n,1)}),logger.info(`Removed QuestionType: ${e}`),!0)}async function removeCustomQuestionTypes(e,t,n,r){try{logger.info(`Beginning custom question removal`),logger.info(`Removing ${e.length} data shapes and ${t.length} question types`);let a=0;for(let e of t)removeQuestionType(e,n)&&a++;for(let t of e)removeDataShape(t,n)&&a++;logger.info(`Updating course configuration...`);let o=await r.updateCourseConfig(n);if(!o.ok)throw Error(`Failed to update course config: ${JSON.stringify(o)}`);return logger.info(`Custom question removal complete: ${a} items removed`),{success:!0,removedCount:a}}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error(`Custom question removal failed: ${t}`),{success:!1,removedCount:0,errorMessage:t}}}async function registerSeedData(e,t,n){if(e.questionClass.seedData&&Array.isArray(e.questionClass.seedData)){logger.info(`Registering seed data for question: ${e.name}`);try{let r=e.questionClass.seedData.filter(()=>e.dataShapes.length>0).map(r=>t.addNote(e.course,e.dataShapes[0],r,n,[]));await Promise.all(r),logger.info(`Seed data registered for question: ${e.name}`)}catch(t){logger.warn(`Failed to register seed data for question '${e.name}': ${t instanceof Error?t.message:String(t)}`)}}}async function registerBlanksCard(e,t,n,r,a){try{logger.info(`Registering BlanksCard data shapes and question type...`);let o=0,s=`default`;for(let e of t)registerDataShape({name:e.name,course:s,dataShape:e},n)&&o++;let c={name:e.name,course:s,questionClass:{name:e.name,dataShapes:t,views:e.views||[]},dataShapes:t,views:e.views||[]};registerQuestionType(c,n)&&o++,logger.info(`Updating course configuration with BlanksCard...`);let l=await r.updateCourseConfig(n);if(!l.ok)throw Error(`Failed to update course config: ${JSON.stringify(l)}`);return a&&await registerSeedData(c,r,a),logger.info(`BlanksCard registration complete: ${o} items registered`),{success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error(`BlanksCard registration failed: ${t}`),{success:!1,errorMessage:t}}}async function registerCustomQuestionTypes(e,t,n,r){try{logger.info(`Beginning custom question registration`),logger.info(`Processing ${e.questionClasses.length} question classes`);let{dataShapes:a,questions:o}=processCustomQuestionsData(e);logger.info(`Found ${a.length} data shapes and ${o.length} questions`);let s=0;logger.info(`Registering data shapes...`);for(let e of a)registerDataShape(e,t)&&s++;logger.info(`Registering question types...`);for(let e of o)registerQuestionType(e,t)&&s++;logger.info(`Updating course configuration...`);let c=await n.updateCourseConfig(t);if(!c.ok)throw Error(`Failed to update course config: ${JSON.stringify(c)}`);if(r){logger.info(`Registering seed data...`);for(let e of o)await registerSeedData(e,n,r)}return logger.info(`Custom question registration complete: ${s} items registered`),{success:!0,registeredCount:s}}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error(`Custom question registration failed: ${t}`),{success:!1,registeredCount:0,errorMessage:t}}}init_couch(),init_util(),init_logger();var duration=hooks.duration;function newInterval(e,t){return areQuestionRecords(t)?newQuestionInterval(e,t):1e5}function newQuestionInterval(e,t){let n=t.records,r=n[n.length-1],a=lastSuccessfulInterval(n);if(a>t.bestInterval&&(t.bestInterval=a,e.update(t._id,{bestInterval:a}).catch(e=>{logger.warn(`[SpacedRepetition] Failed to update bestInterval for ${t._id}: ${e?.message??e}`)})),r.isCorrect){let e=r.performance,n=isTaggedPerformance(e)?e._global:e,o=Math.min(1,Math.max(0,n));logger.debug(`Demontrated skill: ${o}`);let s=a*(.75+o);if(t.lapses=getLapses(t.records),t.streak=getStreak(t.records),t.lapses&&t.streak&&t.bestInterval&&(t.lapses>=0||t.streak>=0)){let e=(t.lapses*s+t.streak*t.bestInterval)/(t.lapses+t.streak);return logger.debug(`Weighted average interval calculation:
309
- (${t.lapses} * ${s} + ${t.streak} * ${t.bestInterval}) / (${t.lapses} + ${t.streak}) = ${e}`),e}else return s}else return 0}function lastSuccessfulInterval(e){for(let t=e.length-1;t>=1;t--)if(e[t].priorAttemps===0&&e[t].isCorrect){let n=secondsBetween(e[t-1].timeStamp,e[t].timeStamp),r=Math.max(n,1200*60);return logger.debug(`Last interval w/ this card was: ${n}s, returning ${r}s`),r}return getInitialInterval(e)}function getStreak(e){let t=0,n=e.length-1;for(;n>=0&&e[n].isCorrect;)n--,t++;return t}function getLapses(e){return e.filter(e=>e.isCorrect===!1).length}function getInitialInterval(e){return logger.warn(`history of length: ${e.length} ignored!`),3600*24*3}function secondsBetween(e,t){return e=hooks(e),t=hooks(t),duration(t.diff(e)).asSeconds()}init_logger();var SrsService=class{constructor(e){_defineProperty(this,`user`,void 0),this.user=e}removeReview(e){logger.info(`[SrsService] Removing orphaned scheduled review: ${e}`),this.user.removeScheduledCardReview(e)}async scheduleReview(e,t){let n=newInterval(this.user,e),r=hooks.utc().add(n,`seconds`);isReview(t)&&(logger.info(`[SrsService] Removing previously scheduled review for: ${t.cardID}`),this.user.removeScheduledCardReview(t.reviewID)),this.user.scheduleCardReview({user:this.user.getUsername(),course_id:e.courseID,card_id:e.cardID,time:r,scheduledFor:t.contentSourceType,schedulingAgentId:t.contentSourceID})}};init_logger();var EloService=class{constructor(e,t){_defineProperty(this,`dataLayer`,void 0),_defineProperty(this,`user`,void 0),this.dataLayer=e,this.user=t}async updateUserAndCardElo(e,t,n,r,a,o){o&&logger.warn(`k value interpretation not currently implemented`);let s=this.dataLayer.getCourseDB(a.card.course_id),c=r.courses.find(e=>e.courseID===t);if(!c){logger.error(`[EloService] No registration for course ${t} on user's registration doc \u2014 skipping ELO update for card ${n}. (Is the user registered for this course?)`);return}let l=toCourseElo(c.elo),u=(await s.getCardEloData([a.card.card_id]))[0];if(u&&l){let r=adjustCourseScores(l,u,e);c.elo=r.userElo;let a=await Promise.allSettled([this.user.updateUserElo(t,r.userElo),s.updateCardElo(n,r.cardElo)]),o=a[0].status===`fulfilled`,d=a[1].status===`fulfilled`;if(o&&d){let e=a[0].value,t=a[1].value;e.ok&&t&&t.ok&&logger.info(`[EloService] Updated ELOS:
310
- User: ${JSON.stringify(r.userElo)})
311
- Card: ${JSON.stringify(r.cardElo)})
309
+ (${t.lapses} * ${s} + ${t.streak} * ${t.bestInterval}) / (${t.lapses} + ${t.streak}) = ${e}`),e}else return s}else return 0}function lastSuccessfulInterval(e){for(let t=e.length-1;t>=1;t--)if(e[t].priorAttemps===0&&e[t].isCorrect){let n=secondsBetween(e[t-1].timeStamp,e[t].timeStamp),r=Math.max(n,1200*60);return logger.debug(`Last interval w/ this card was: ${n}s, returning ${r}s`),r}return getInitialInterval(e)}function getStreak(e){let t=0,n=e.length-1;for(;n>=0&&e[n].isCorrect;)n--,t++;return t}function getLapses(e){return e.filter(e=>e.isCorrect===!1).length}function getInitialInterval(e){return logger.warn(`history of length: ${e.length} ignored!`),3600*24*3}function secondsBetween(e,t){return e=hooks(e),t=hooks(t),duration(t.diff(e)).asSeconds()}init_logger();var SrsService=class{constructor(e){_defineProperty(this,`user`,void 0),this.user=e}removeReview(e){logger.info(`[SrsService] Removing orphaned scheduled review: ${e}`),this.user.removeScheduledCardReview(e)}async scheduleReview(e,t){let n=newInterval(this.user,e),r=hooks.utc().add(n,`seconds`);isReview(t)&&(logger.info(`[SrsService] Removing previously scheduled review for: ${t.cardID}`),this.user.removeScheduledCardReview(t.reviewID)),this.user.scheduleCardReview({user:this.user.getUsername(),course_id:e.courseID,card_id:e.cardID,time:r,scheduledFor:t.contentSourceType,schedulingAgentId:t.contentSourceID})}};init_logger();var EloService=class{constructor(e,t){_defineProperty(this,`dataLayer`,void 0),_defineProperty(this,`user`,void 0),this.dataLayer=e,this.user=t}async updateUserAndCardElo(e,t,n,r,a,o){o&&logger.warn(`k value interpretation not currently implemented`);let s=this.dataLayer.getCourseDB(a.card.course_id),c=r.courses.find(e=>e.courseID===t);if(!c)return logger.error(`[EloService] No registration for course ${t} on user's registration doc \u2014 skipping ELO update for card ${n}. (Is the user registered for this course?)`),null;let l=toCourseElo(c.elo),u=(await s.getCardEloData([a.card.card_id]))[0];if(u&&l){let r=l.global.score,a=u.global.score,o=Object.keys(u.tags),d={};for(let e of o)d[e]=l.tags[e]?.score??l.global.score;let p=adjustCourseScores(l,u,e);c.elo=p.userElo;let m={};for(let t of o)m[t]={before:d[t],after:p.userElo.tags[t].score,score:e};let g={cardId:n,at:new Date().toISOString(),userScore:e,global:{before:r,after:p.userElo.global.score},card:{before:a,after:p.cardElo.global.score},...o.length?{tags:m}:{}},_=await Promise.allSettled([this.user.updateUserElo(t,p.userElo),s.updateCardElo(n,p.cardElo)]),v=_[0].status===`fulfilled`,y=_[1].status===`fulfilled`;if(v&&y){let e=_[0].value,t=_[1].value;e.ok&&t&&t.ok&&logger.info(`[EloService] Updated ELOS:
310
+ User: ${JSON.stringify(p.userElo)})
311
+ Card: ${JSON.stringify(p.cardElo)})
312
312
  `)}else logger.warn(`[EloService] Partial ELO update:
313
- User ELO update: ${o?`SUCCESS`:`FAILED`}
314
- Card ELO update: ${d?`SUCCESS`:`FAILED`}`),!o&&a[0].status===`rejected`&&logger.error(`[EloService] User ELO update error:`,a[0].reason),!d&&a[1].status===`rejected`&&logger.error(`[EloService] Card ELO update error:`,a[1].reason)}}async updateUserAndCardEloPerTag(e,t,n,r,a){let o=this.dataLayer.getCourseDB(a.card.course_id),s=r.courses.find(e=>e.courseID===t);if(!s){logger.error(`[EloService] No registration for course ${t} on user's registration doc \u2014 skipping per-tag ELO update for card ${n}. (Is the user registered for this course?)`);return}let c=toCourseElo(s.elo),[l,u]=await Promise.all([o.getCardEloData([a.card.card_id]),o.getAppliedTagsBatch([n])]),d=l[0],p=u.get(n)??[],m={...e},g=e._global;for(let e of p)e in m||(m[e]=g);if(d&&c){let e=adjustCourseScoresPerTag(c,d,m);s.elo=e.userElo;let r=await Promise.allSettled([this.user.updateUserElo(t,e.userElo),o.updateCardElo(n,e.cardElo)]),a=r[0].status===`fulfilled`,l=r[1].status===`fulfilled`;if(a&&l){let t=r[0].value,n=r[1].value;if(t.ok&&n&&n.ok){let t=Object.keys(m).length-1;logger.info(`[EloService] Updated ELOS (per-tag, ${t} tags):
315
- User: ${JSON.stringify(e.userElo)})
316
- Card: ${JSON.stringify(e.cardElo)})
313
+ User ELO update: ${v?`SUCCESS`:`FAILED`}
314
+ Card ELO update: ${y?`SUCCESS`:`FAILED`}`),!v&&_[0].status===`rejected`&&logger.error(`[EloService] User ELO update error:`,_[0].reason),!y&&_[1].status===`rejected`&&logger.error(`[EloService] Card ELO update error:`,_[1].reason);return g}return null}async updateUserAndCardEloPerTag(e,t,n,r,a){let o=this.dataLayer.getCourseDB(a.card.course_id),s=r.courses.find(e=>e.courseID===t);if(!s)return logger.error(`[EloService] No registration for course ${t} on user's registration doc \u2014 skipping per-tag ELO update for card ${n}. (Is the user registered for this course?)`),null;let c=toCourseElo(s.elo),[l,u]=await Promise.all([o.getCardEloData([a.card.card_id]),o.getAppliedTagsBatch([n])]),d=l[0],p=u.get(n)??[],m={...e},g=e._global;for(let e of p)e in m||(m[e]=g);if(d&&c){let e=c.global.score,r=d.global.score,a=Object.keys(m).filter(e=>e!==`_global`),l={};for(let e of a)l[e]=c.tags[e]?.score??c.global.score;let u=adjustCourseScoresPerTag(c,d,m);s.elo=u.userElo;let p={};for(let e of a){let t=m[e],n=t===null?l[e]:u.userElo.tags[e]?.score??l[e];p[e]={before:l[e],after:n,score:t}}let _={cardId:n,at:new Date().toISOString(),userScore:g,global:{before:e,after:u.userElo.global.score},card:{before:r,after:u.cardElo.global.score},...a.length?{tags:p}:{}},v=await Promise.allSettled([this.user.updateUserElo(t,u.userElo),o.updateCardElo(n,u.cardElo)]),y=v[0].status===`fulfilled`,b=v[1].status===`fulfilled`;if(y&&b){let e=v[0].value,t=v[1].value;if(e.ok&&t&&t.ok){let e=Object.keys(m).length-1;logger.info(`[EloService] Updated ELOS (per-tag, ${e} tags):
315
+ User: ${JSON.stringify(u.userElo)})
316
+ Card: ${JSON.stringify(u.cardElo)})
317
317
  `)}}else logger.warn(`[EloService] Partial ELO update (per-tag):
318
- User ELO update: ${a?`SUCCESS`:`FAILED`}
319
- Card ELO update: ${l?`SUCCESS`:`FAILED`}`),!a&&r[0].status===`rejected`&&logger.error(`[EloService] User ELO update error:`,r[0].reason),!l&&r[1].status===`rejected`&&logger.error(`[EloService] Card ELO update error:`,r[1].reason)}}};init_core(),init_logger();var ResponseProcessor=class{constructor(e,t){_defineProperty(this,`srsService`,void 0),_defineProperty(this,`eloService`,void 0),this.srsService=e,this.eloService=t}logEloFailure(e,t){return n=>logger.error(`[ResponseProcessor] ELO update failed (${e}) for ${t}:`,n)}parsePerformance(e){return typeof e==`number`?{globalScore:e,taggedPerformance:null}:isTaggedPerformance(e)?{globalScore:e._global,taggedPerformance:e}:(logger.warn(`[ResponseProcessor] Unexpected performance structure, using neutral score`,{performance:e}),{globalScore:.5,taggedPerformance:null})}async processResponse(e,t,n,r,a,o,s,c,l,u){if(!isQuestionRecord(e))return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,shouldClearFeedbackShadow:!0};try{let d=await t,p;return p=e.isCorrect?this.processCorrectResponse(e,d,n,r,a,o,s,l,u):this.processIncorrectResponse(e,d,r,a,o,s,c,l,u),e.deferAdvance&&p.shouldLoadNextCard&&(logger.info(`[ResponseProcessor] deferAdvance requested — suppressing navigation, action stashed:`,{nextCardAction:p.nextCardAction}),p={...p,shouldLoadNextCard:!1,deferred:!0}),p}catch(e){throw logger.error(`[ResponseProcessor] Failed to load card history`,{e,cardId:s}),e}}processCorrectResponse(e,t,n,r,a,o,s,c,l){if(e.priorAttemps===0){a.card.tags.includes(`srs:skip`)||this.srsService.scheduleReview(t,n);let{globalScore:c,taggedPerformance:l}=this.parsePerformance(e.performance);if(l){let n=Object.keys(l).filter(e=>e!==`_global`),c=n.filter(e=>l[e]===null),u=n.filter(e=>l[e]!==null);logger.info(`[FirstContactElo] correct first-attempt per-tag ELO update for ${s} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps}): scored=[${u.join(`, `)}] count-only=[${c.join(`, `)}]`),this.eloService.updateUserAndCardEloPerTag(l,o,s,r,a).catch(this.logEloFailure(`correct per-tag`,s))}else{let n=.5+c/2;if(t.records.length===1)this.eloService.updateUserAndCardElo(n,o,s,r,a).catch(this.logEloFailure(`correct`,s));else{let e=Math.ceil(32/t.records.length);this.eloService.updateUserAndCardElo(n,o,s,r,a,e).catch(this.logEloFailure(`correct repeat-view`,s))}logger.info(`[FirstContactElo] correct first-attempt ELO update (score=${n.toFixed(3)}) for ${s} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps})`)}return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:c,shouldClearFeedbackShadow:!0}}else{let t=l>=c;logger.info(`[ResponseProcessor] Processed correct response (retry attempt - no scheduling/ELO); sessionViews=${l}/${c} -> ${t?`dismiss-success`:`marked-failed`}`);let{globalScore:n}=this.parsePerformance(e.performance);return{nextCardAction:t?`dismiss-success`:`marked-failed`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:n,shouldClearFeedbackShadow:!0}}}processIncorrectResponse(e,t,n,r,a,o,s,c,l){let{taggedPerformance:u}=this.parsePerformance(e.performance),d=!1;return e.priorAttemps===0?(u?(this.eloService.updateUserAndCardEloPerTag(u,a,o,n,r).catch(this.logEloFailure(`incorrect per-tag`,o)),logger.info(`[FirstContactElo] incorrect first-attempt per-tag ELO update for ${o} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps}, tags=${Object.keys(u).length-1})`)):(this.eloService.updateUserAndCardElo(0,a,o,n,r).catch(this.logEloFailure(`incorrect`,o)),logger.info(`[FirstContactElo] incorrect first-attempt ELO update (score=0) for ${o} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps})`)),d=!0):logger.info(`[FirstContactElo] incorrect retry \u2014 no ELO update for ${o} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps})`),r.records.length>=s?l>=c?(d?logger.info(`[FirstContactElo] dismiss-failed \u2014 ELO already updated this response, skipping double penalty for ${o}`):(u?this.eloService.updateUserAndCardEloPerTag(u,a,o,n,r).catch(this.logEloFailure(`dismiss-failed per-tag`,o)):this.eloService.updateUserAndCardElo(0,a,o,n,r).catch(this.logEloFailure(`dismiss-failed`,o)),logger.info(`[FirstContactElo] dismiss-failed final ELO penalty for ${o} (historyLen=${t.records.length}, sessionViews=${l})`)),{nextCardAction:`dismiss-failed`,shouldLoadNextCard:!0,isCorrect:!1,shouldClearFeedbackShadow:!0}):{nextCardAction:`marked-failed`,shouldLoadNextCard:!0,isCorrect:!1,shouldClearFeedbackShadow:!0}:{nextCardAction:`none`,shouldLoadNextCard:!1,isCorrect:!1,shouldClearFeedbackShadow:!0}}};init_logger();function parseAudioURIs(e){return typeof e==`string`?e.match(/https?:\/\/[^\s"'<>]+\.(wav|mp3|ogg|m4a|aac|webm)/gi)??[]:[]}function prefetchAudio(e){return new Promise(t=>{let n=new Audio;n.preload=`auto`;let cleanup=()=>{n.oncanplaythrough=null,n.onerror=null};n.oncanplaythrough=()=>{cleanup(),t()},n.onerror=()=>{cleanup(),logger.warn(`[CardHydrationService] Failed to prefetch audio: ${e}`),t()},n.src=e})}var CardHydrationService=class{constructor(e,t,n){_defineProperty(this,`hydratedCards`,new Map),_defineProperty(this,`hydrationInFlight`,new Set),_defineProperty(this,`hydrationInProgress`,!1),this.getViewComponent=e,this.getCourseDB=t,this.getItemsToHydrate=n}getHydratedCard(e){return this.hydratedCards.get(e)??null}hasHydratedCard(e){return this.hydratedCards.has(e)}removeCard(e){this.hydratedCards.delete(e)}async ensureHydratedCards(){this.fillHydratedCards()}async waitForCard(e){if(this.hydratedCards.has(e))return this.hydratedCards.get(e);this.hydrationInProgress||this.fillHydratedCards();let t=1e4,n=25,r=0;for(;r<1e4;){if(this.hydratedCards.has(e))return this.hydratedCards.get(e);if(!this.hydrationInFlight.has(e)&&!this.hydrationInProgress)break;await new Promise(e=>setTimeout(e,25)),r+=25}return this.hydratedCards.get(e)??null}get hydratedCount(){return this.hydratedCards.size}getHydratedCardIds(){return Array.from(this.hydratedCards.keys())}async fillHydratedCards(){if(!this.hydrationInProgress){this.hydrationInProgress=!0;try{let e=this.getItemsToHydrate();for(let t of e)if(!(this.hydratedCards.has(t.cardID)||this.hydrationInFlight.has(t.cardID)))try{await this.hydrateCard(t)}catch(e){logger.error(`[CardHydrationService] Error hydrating card ${t.cardID}:`,e)}}finally{this.hydrationInProgress=!1}}}async hydrateCard(e){if(!(this.hydratedCards.has(e.cardID)||this.hydrationInFlight.has(e.cardID))){this.hydrationInFlight.add(e.cardID);try{let t=this.getCourseDB(e.courseID),[n,r]=await Promise.all([t.getCourseDoc(e.cardID),t.getAppliedTagsBatch([e.cardID])]);isCourseElo(n.elo)||(n.elo=toCourseElo(n.elo));let a=this.getViewComponent(n.id_view),o=await Promise.all(n.id_displayable_data.map(e=>t.getCourseDoc(e,{attachments:!0,binary:!0}))),s=[];o.forEach(e=>{e.data.forEach(e=>{s.push(...parseAudioURIs(e.data))})});let c=[...new Set(s)];c.length>0&&(logger.debug(`[CardHydrationService] Prefetching ${c.length} audio files for card ${e.cardID}`),await Promise.allSettled(c.map(prefetchAudio)));let l=o.map(displayableDataToViewData).reverse();this.hydratedCards.set(e.cardID,{item:{...e,elo:toCourseElo(n.elo).global.score},view:a,data:l,tags:r.get(e.cardID)??[]}),logger.debug(`[CardHydrationService] Hydrated card ${e.cardID}`)}finally{this.hydrationInFlight.delete(e.cardID)}}}},ItemQueue=class{constructor(){_defineProperty(this,`q`,[]),_defineProperty(this,`seenCardIds`,[]),_defineProperty(this,`_dequeueCount`,0)}get dequeueCount(){return this._dequeueCount}add(e,t){this.seenCardIds.find(e=>e===t)||(this.seenCardIds.push(t),this.q.push(e))}addAll(e,t){e.forEach(e=>this.add(e,t(e)))}get length(){return this.q.length}peek(e){return this.q[e]}dequeue(e){if(this.q.length!==0){this._dequeueCount++;let t=this.q.splice(0,1)[0];if(e){let n=e(t),r=this.seenCardIds.indexOf(n);r>-1&&this.seenCardIds.splice(r,1)}return t}else return null}replaceAll(e,t){this.q=[],this.seenCardIds=[];for(let n of e){let e=t(n);this.seenCardIds.includes(e)||(this.seenCardIds.push(e),this.q.push(n))}}mergeToFront(e,t,n){let r=0,a=[];for(let o of e){let e=t(o);if(!this.seenCardIds.includes(e))this.seenCardIds.push(e),a.push(o),r++;else if(n?.has(e)){let n=this.q.findIndex(n=>t(n)===e);n>=0&&a.push(...this.q.splice(n,1))}}return this.q.unshift(...a),r}get toString(){return`${typeof this.q[0]}:
318
+ User ELO update: ${y?`SUCCESS`:`FAILED`}
319
+ Card ELO update: ${b?`SUCCESS`:`FAILED`}`),!y&&v[0].status===`rejected`&&logger.error(`[EloService] User ELO update error:`,v[0].reason),!b&&v[1].status===`rejected`&&logger.error(`[EloService] Card ELO update error:`,v[1].reason);return _}return null}};init_core(),init_logger();var ResponseProcessor=class{constructor(e,t,n){_defineProperty(this,`srsService`,void 0),_defineProperty(this,`eloService`,void 0),_defineProperty(this,`onEloEvent`,void 0),this.srsService=e,this.eloService=t,this.onEloEvent=n}logEloFailure(e,t){return n=>logger.error(`[ResponseProcessor] ELO update failed (${e}) for ${t}:`,n)}trackElo(e,t,n){e.then(e=>{e&&this.onEloEvent?.(e)}).catch(this.logEloFailure(t,n))}parsePerformance(e){return typeof e==`number`?{globalScore:e,taggedPerformance:null}:isTaggedPerformance(e)?{globalScore:e._global,taggedPerformance:e}:(logger.warn(`[ResponseProcessor] Unexpected performance structure, using neutral score`,{performance:e}),{globalScore:.5,taggedPerformance:null})}async processResponse(e,t,n,r,a,o,s,c,l,u){if(!isQuestionRecord(e))return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,shouldClearFeedbackShadow:!0};try{let d=await t,p;return p=e.isCorrect?this.processCorrectResponse(e,d,n,r,a,o,s,l,u):this.processIncorrectResponse(e,d,r,a,o,s,c,l,u),e.deferAdvance&&p.shouldLoadNextCard&&(logger.info(`[ResponseProcessor] deferAdvance requested — suppressing navigation, action stashed:`,{nextCardAction:p.nextCardAction}),p={...p,shouldLoadNextCard:!1,deferred:!0}),p}catch(e){throw logger.error(`[ResponseProcessor] Failed to load card history`,{e,cardId:s}),e}}processCorrectResponse(e,t,n,r,a,o,s,c,l){if(e.priorAttemps===0){a.card.tags.includes(`srs:skip`)||this.srsService.scheduleReview(t,n);let{globalScore:c,taggedPerformance:l}=this.parsePerformance(e.performance);if(l){let n=Object.keys(l).filter(e=>e!==`_global`),c=n.filter(e=>l[e]===null),u=n.filter(e=>l[e]!==null);logger.info(`[FirstContactElo] correct first-attempt per-tag ELO update for ${s} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps}): scored=[${u.join(`, `)}] count-only=[${c.join(`, `)}]`),this.trackElo(this.eloService.updateUserAndCardEloPerTag(l,o,s,r,a),`correct per-tag`,s)}else{let n=.5+c/2;if(t.records.length===1)this.trackElo(this.eloService.updateUserAndCardElo(n,o,s,r,a),`correct`,s);else{let e=Math.ceil(32/t.records.length);this.trackElo(this.eloService.updateUserAndCardElo(n,o,s,r,a,e),`correct repeat-view`,s)}logger.info(`[FirstContactElo] correct first-attempt ELO update (score=${n.toFixed(3)}) for ${s} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps})`)}return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:c,shouldClearFeedbackShadow:!0}}else{let t=l>=c;logger.info(`[ResponseProcessor] Processed correct response (retry attempt - no scheduling/ELO); sessionViews=${l}/${c} -> ${t?`dismiss-success`:`marked-failed`}`);let{globalScore:n}=this.parsePerformance(e.performance);return{nextCardAction:t?`dismiss-success`:`marked-failed`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:n,shouldClearFeedbackShadow:!0}}}processIncorrectResponse(e,t,n,r,a,o,s,c,l){let{taggedPerformance:u}=this.parsePerformance(e.performance),d=!1;return e.priorAttemps===0?(u?(this.trackElo(this.eloService.updateUserAndCardEloPerTag(u,a,o,n,r),`incorrect per-tag`,o),logger.info(`[FirstContactElo] incorrect first-attempt per-tag ELO update for ${o} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps}, tags=${Object.keys(u).length-1})`)):(this.trackElo(this.eloService.updateUserAndCardElo(0,a,o,n,r),`incorrect`,o),logger.info(`[FirstContactElo] incorrect first-attempt ELO update (score=0) for ${o} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps})`)),d=!0):logger.info(`[FirstContactElo] incorrect retry \u2014 no ELO update for ${o} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps})`),r.records.length>=s?l>=c?(d?logger.info(`[FirstContactElo] dismiss-failed \u2014 ELO already updated this response, skipping double penalty for ${o}`):(u?this.trackElo(this.eloService.updateUserAndCardEloPerTag(u,a,o,n,r),`dismiss-failed per-tag`,o):this.trackElo(this.eloService.updateUserAndCardElo(0,a,o,n,r),`dismiss-failed`,o),logger.info(`[FirstContactElo] dismiss-failed final ELO penalty for ${o} (historyLen=${t.records.length}, sessionViews=${l})`)),{nextCardAction:`dismiss-failed`,shouldLoadNextCard:!0,isCorrect:!1,shouldClearFeedbackShadow:!0}):{nextCardAction:`marked-failed`,shouldLoadNextCard:!0,isCorrect:!1,shouldClearFeedbackShadow:!0}:{nextCardAction:`none`,shouldLoadNextCard:!1,isCorrect:!1,shouldClearFeedbackShadow:!0}}};init_logger();function parseAudioURIs(e){return typeof e==`string`?e.match(/https?:\/\/[^\s"'<>]+\.(wav|mp3|ogg|m4a|aac|webm)/gi)??[]:[]}function prefetchAudio(e){return new Promise(t=>{let n=new Audio;n.preload=`auto`;let cleanup=()=>{n.oncanplaythrough=null,n.onerror=null};n.oncanplaythrough=()=>{cleanup(),t()},n.onerror=()=>{cleanup(),logger.warn(`[CardHydrationService] Failed to prefetch audio: ${e}`),t()},n.src=e})}var CardHydrationService=class{constructor(e,t,n){_defineProperty(this,`hydratedCards`,new Map),_defineProperty(this,`hydrationInFlight`,new Set),_defineProperty(this,`hydrationInProgress`,!1),this.getViewComponent=e,this.getCourseDB=t,this.getItemsToHydrate=n}getHydratedCard(e){return this.hydratedCards.get(e)??null}hasHydratedCard(e){return this.hydratedCards.has(e)}removeCard(e){this.hydratedCards.delete(e)}async ensureHydratedCards(){this.fillHydratedCards()}async waitForCard(e){if(this.hydratedCards.has(e))return this.hydratedCards.get(e);this.hydrationInProgress||this.fillHydratedCards();let t=1e4,n=25,r=0;for(;r<1e4;){if(this.hydratedCards.has(e))return this.hydratedCards.get(e);if(!this.hydrationInFlight.has(e)&&!this.hydrationInProgress)break;await new Promise(e=>setTimeout(e,25)),r+=25}return this.hydratedCards.get(e)??null}get hydratedCount(){return this.hydratedCards.size}getHydratedCardIds(){return Array.from(this.hydratedCards.keys())}async fillHydratedCards(){if(!this.hydrationInProgress){this.hydrationInProgress=!0;try{let e=this.getItemsToHydrate();for(let t of e)if(!(this.hydratedCards.has(t.cardID)||this.hydrationInFlight.has(t.cardID)))try{await this.hydrateCard(t)}catch(e){logger.error(`[CardHydrationService] Error hydrating card ${t.cardID}:`,e)}}finally{this.hydrationInProgress=!1}}}async hydrateCard(e){if(!(this.hydratedCards.has(e.cardID)||this.hydrationInFlight.has(e.cardID))){this.hydrationInFlight.add(e.cardID);try{let t=this.getCourseDB(e.courseID),[n,r]=await Promise.all([t.getCourseDoc(e.cardID),t.getAppliedTagsBatch([e.cardID])]);isCourseElo(n.elo)||(n.elo=toCourseElo(n.elo));let a=this.getViewComponent(n.id_view),o=await Promise.all(n.id_displayable_data.map(e=>t.getCourseDoc(e,{attachments:!0,binary:!0}))),s=[];o.forEach(e=>{e.data.forEach(e=>{s.push(...parseAudioURIs(e.data))})});let c=[...new Set(s)];c.length>0&&(logger.debug(`[CardHydrationService] Prefetching ${c.length} audio files for card ${e.cardID}`),await Promise.allSettled(c.map(prefetchAudio)));let l=o.map(displayableDataToViewData).reverse();this.hydratedCards.set(e.cardID,{item:{...e,elo:toCourseElo(n.elo).global.score},view:a,data:l,tags:r.get(e.cardID)??[]}),logger.debug(`[CardHydrationService] Hydrated card ${e.cardID}`)}finally{this.hydrationInFlight.delete(e.cardID)}}}},ItemQueue=class{constructor(){_defineProperty(this,`q`,[]),_defineProperty(this,`seenCardIds`,[]),_defineProperty(this,`_dequeueCount`,0)}get dequeueCount(){return this._dequeueCount}add(e,t){this.seenCardIds.find(e=>e===t)||(this.seenCardIds.push(t),this.q.push(e))}addAll(e,t){e.forEach(e=>this.add(e,t(e)))}get length(){return this.q.length}peek(e){return this.q[e]}dequeue(e){if(this.q.length!==0){this._dequeueCount++;let t=this.q.splice(0,1)[0];if(e){let n=e(t),r=this.seenCardIds.indexOf(n);r>-1&&this.seenCardIds.splice(r,1)}return t}else return null}replaceAll(e,t){this.q=[],this.seenCardIds=[];for(let n of e){let e=t(n);this.seenCardIds.includes(e)||(this.seenCardIds.push(e),this.q.push(n))}}mergeToFront(e,t,n){let r=0,a=[];for(let o of e){let e=t(o);if(!this.seenCardIds.includes(e))this.seenCardIds.push(e),a.push(o),r++;else if(n?.has(e)){let n=this.q.findIndex(n=>t(n)===e);n>=0&&a.push(...this.q.splice(n,1))}}return this.q.unshift(...a),r}get toString(){return`${typeof this.q[0]}:
320
320
  `+this.q.map(e=>` ${e.courseID}+${e.cardID}: ${e.status}`).join(`
321
321
  `)}};init_couch(),init_core(),init_types_legacy(),init_studySession(),init_recording(),init_Loggable(),init_types_legacy(),init_logger();var CouchDBToStaticPacker=class{constructor(e={}){_defineProperty(this,`config`,void 0),_defineProperty(this,`sourceDB`,null),this.config={chunkSize:1e3,includeAttachments:!0,...e}}async packCourse(e,t){logger.info(`Starting static pack for course: ${t}`),this.sourceDB=e;let n={version:`1.0.0`,courseId:t,courseName:``,courseConfig:null,lastUpdated:new Date().toISOString(),documentCount:0,chunks:[],indices:[],designDocs:[]},r=await this.extractCourseConfig(e);n.courseName=r.name,n.courseConfig=r,n.designDocs=await this.extractDesignDocs(e);let a=await this.extractDocumentsByType(e),o=new Map;this.config.includeAttachments&&await this.extractAllAttachments(a,o);let s=new Map;for(let[e,t]of Object.entries(a)){let r=this.createChunks(t,e);n.chunks.push(...r),n.documentCount+=t.length,this.prepareChunkData(r,t,s)}let c=new Map;return n.indices=await this.buildIndices(a,n.designDocs,c),{manifest:n,chunks:s,indices:c,attachments:o}}async packCourseToFiles(e,t,n,r){logger.info(`Packing course ${t} to files in ${n}`);let a=await this.packCourse(e,t),o=await this.writePackedDataToFiles(a,n,r);return{manifest:a.manifest,filesWritten:o,attachmentsFound:a.attachments?a.attachments.size:0}}async writePackedDataToFiles(e,t,n){let r=0;await n.ensureDir(t);let a=n.joinPath(t,`manifest.json`);await n.writeJson(a,e.manifest,{spaces:2}),r++,logger.info(`Wrote manifest: ${a}`);let o=n.joinPath(t,`chunks`),s=n.joinPath(t,`indices`);await n.ensureDir(o),await n.ensureDir(s);for(let[t,a]of e.chunks){let e=n.joinPath(o,`${t}.json`);await n.writeJson(e,a),r++}logger.info(`Wrote ${e.chunks.size} chunk files`);for(let[t,a]of e.indices){let e=n.joinPath(s,`${t}.json`);await n.writeJson(e,a,{spaces:2}),r++}if(logger.info(`Wrote ${e.indices.size} index files`),e.attachments&&e.attachments.size>0){for(let[a,o]of e.attachments){let e=n.joinPath(t,a),s=n.dirname(e);await n.ensureDir(s),await n.writeFile(e,o.buffer),r++}logger.info(`Wrote ${e.attachments.size} attachment files`)}return r}async extractCourseConfig(e){try{return await e.get(`CourseConfig`)}catch(e){throw logger.error(`Failed to extract course config:`,e),Error(`Course config not found`)}}async extractDesignDocs(e){return(await e.allDocs({startkey:`_design/`,endkey:`_design/￰`,include_docs:!0})).rows.map(e=>({_id:e.id,views:e.doc.views||{}}))}async extractDocumentsByType(e){let t=await e.allDocs({include_docs:!0}),n={};for(let e of t.rows){if(e.id.startsWith(`_`))continue;let t=e.doc;t.docType&&(n[t.docType]||(n[t.docType]=[]),n[t.docType].push(t))}return n}createChunks(e,t){let n=[],r=e.sort((e,t)=>e._id.localeCompare(t._id));for(let e=0;e<r.length;e+=this.config.chunkSize){let a=r.slice(e,e+this.config.chunkSize),o=`${t}-${String(Math.floor(e/this.config.chunkSize)).padStart(4,`0`)}`;n.push({id:o,docType:t,startKey:a[0]._id,endKey:a[a.length-1]._id,documentCount:a.length,path:`chunks/${o}.json`})}return n}prepareChunkData(e,t,n){let r=t.sort((e,t)=>e._id.localeCompare(t._id));for(let t of e){let e=r.filter(e=>e._id>=t.startKey&&e._id<=t.endKey).map(e=>{let t={...e};return delete t._rev,this.config.includeAttachments&&t._attachments?t._attachments=this.transformAttachmentStubs(t._attachments,t._id):this.config.includeAttachments||delete t._attachments,t});n.set(t.id,e)}}async buildIndices(e,t,n){let r=[];if(e.CARD){let t=await this.buildEloIndex(e.CARD,n);r.push(t)}if(e.TAG){let t=await this.buildTagIndex(e.TAG,n);r.push(t)}for(let e of t)for(let[t,a]of Object.entries(e.views))if(a.map){logger.info(`Processing view: ${e._id}/${t}`);let a=await this.buildViewIndex(t,e,n);a?(r.push(a),logger.info(`Successfully built index: ${a.name}`)):logger.warn(`Skipped view index: ${e._id}/${t}`)}return r}async buildEloIndex(e,t){let n=[];for(let t of e)t.elo?.global?.score&&n.push({elo:t.elo.global.score,cardId:t._id});n.sort((e,t)=>e.elo-t.elo);let r={},a=50;for(let e of n){let t=Math.floor(e.elo/50)*50;r[t]||(r[t]=[]),r[t].push(e.cardId)}return t.set(`elo`,{sorted:n,buckets:r,stats:{min:n[0]?.elo||0,max:n[n.length-1]?.elo||0,count:n.length}}),{name:`elo`,type:`btree`,path:`indices/elo.json`}}async buildTagIndex(e,t){let n={};for(let t of e)n[t.name]={cardIds:t.taggedCards,snippet:t.snippet,count:t.taggedCards.length};let r={};for(let t of e)for(let e of t.taggedCards)r[e]||(r[e]=[]),r[e].push(t.name);return t.set(`tags`,{byTag:n,byCard:r}),{name:`tags`,type:`hash`,path:`indices/tags.json`}}async buildViewIndex(e,t,n){if(!this.sourceDB)return logger.error(`Source database not available for view querying`),null;try{let r=`${t._id.replace(`_design/`,``)}/${e}`;logger.info(`Querying CouchDB view: ${r}`);let a=await this.sourceDB.query(r,{include_docs:!1});if(!a.rows||a.rows.length===0)return logger.warn(`View ${r} returned no results`),null;logger.info(`Successfully queried view ${r}: ${a.rows.length} results`);let o=this.formatViewResults(e,a.rows,t),s=`view-${t._id.replace(`_design/`,``)}-${e}`;return n.set(s,o),{name:s,type:`view`,path:`indices/${s}.json`}}catch(n){return logger.error(`Failed to query view ${t._id}/${e}:`,n),null}}formatViewResults(e,t,n){let r={type:`couchdb-view`,viewName:e,designDoc:n._id,results:t,metadata:{resultCount:t.length,generatedAt:new Date().toISOString()}};switch(e){case`elo`:return this.formatEloViewIndex(t,r);case`getTags`:return this.formatTagsViewIndex(t,r);case`cardsByInexperience`:return this.formatInexperienceViewIndex(t,r);default:return this.formatGenericViewIndex(t,r)}}formatEloViewIndex(e,t){let n=e.sort((e,t)=>typeof e.key==`number`&&typeof t.key==`number`?e.key-t.key:0);return{...t,sorted:n,stats:{min:n[0]?.key||0,max:n[n.length-1]?.key||0,count:n.length}}}formatTagsViewIndex(e,t){let n={};for(let t of e){let e=t.key;typeof e==`string`&&(n[e]||(n[e]=[]),n[e].push(t.id))}return{...t,byTag:n,tagCount:Object.keys(n).length}}formatInexperienceViewIndex(e,t){let n=e.sort((e,t)=>typeof e.key==`number`&&typeof t.key==`number`?e.key-t.key:0);return{...t,sorted:n,stats:{minInexperience:n[0]?.key||0,maxInexperience:n[n.length-1]?.key||0,count:n.length}}}formatGenericViewIndex(e,t){return{...t}}async extractAllAttachments(e,t){logger.info(`Extracting attachments...`);let n=[];for(let t of Object.values(e))n.push(...t);let r=n.filter(e=>e._attachments&&Object.keys(e._attachments).length>0);if(r.length===0){logger.info(`No attachments found`);return}logger.info(`Found ${r.length} documents with attachments`);let a=r.map(e=>this.extractDocumentAttachments(e,t));await Promise.all(a),logger.info(`Extracted ${t.size} attachment files`)}async extractDocumentAttachments(e,t){if(!e._attachments||!this.sourceDB)return;let n=e._id;for(let[r,a]of Object.entries(e._attachments))try{let e=await this.sourceDB.getAttachment(n,r),o;if(e instanceof ArrayBuffer)o=Buffer.from(e);else if(Buffer.isBuffer(e))o=e;else{let t=e;o=Buffer.from(await t.arrayBuffer())}let s=`${r}${this.getFileExtension(a.content_type)}`,c=`attachments/${n}/${s}`;t.set(c,{docId:n,attachmentName:r,filename:s,path:c,contentType:a.content_type,length:a.length||o.length,digest:a.digest,buffer:o}),logger.debug(`Extracted attachment: ${c}`)}catch(e){throw logger.error(`Failed to extract attachment ${n}/${r}:`,e),Error(`Failed to extract attachment ${n}/${r}: ${e}`)}}transformAttachmentStubs(e,t){let n={};for(let[r,a]of Object.entries(e))n[r]={path:`attachments/${t}/${`${r}${this.getFileExtension(a.content_type)}`}`,content_type:a.content_type,length:a.length,digest:a.digest,stub:!1};return n}getFileExtension(e){return{"image/jpeg":`.jpg`,"image/jpg":`.jpg`,"image/png":`.png`,"image/gif":`.gif`,"image/webp":`.webp`,"audio/mpeg":`.mp3`,"audio/mp3":`.mp3`,"audio/wav":`.wav`,"audio/ogg":`.ogg`,"video/mp4":`.mp4`,"video/webm":`.webm`,"application/pdf":`.pdf`,"text/plain":`.txt`,"application/json":`.json`}[e]||``}};init_logger();var DEFAULT_MIGRATION_OPTIONS={chunkBatchSize:100,validateRoundTrip:!1,cleanupOnFailure:!0,timeout:3e5};init_logger();var FileSystemError=class extends Error{constructor(e,t,n,r){super(e),this.operation=t,this.filePath=n,this.cause=r,this.name=`FileSystemError`}},nodeFS2=null;try{typeof window>`u`&&typeof process<`u`&&process.versions?.node&&(nodeFS2=eval(`require`)(`fs`),nodeFS2.promises=nodeFS2.promises||eval(`require`)(`fs`).promises)}catch{}async function validateStaticCourse(e,t){let n={valid:!0,manifestExists:!1,chunksExist:!1,attachmentsExist:!1,errors:[],warnings:[]};try{if(t){if(!(await t.stat(e)).isDirectory())return n.errors.push(`Path is not a directory: ${e}`),n.valid=!1,n}else if(!nodeFS2)return n.errors.push(`File system access not available - validation skipped`),n.valid=!1,n;else if(!(await nodeFS2.promises.stat(e)).isDirectory())return n.errors.push(`Path is not a directory: ${e}`),n.valid=!1,n;let r=`${e}/manifest.json`;try{if(t)if(r=t.joinPath(e,`manifest.json`),await t.exists(r)){n.manifestExists=!0;let e=await t.readFile(r),a=JSON.parse(e);n.courseId=a.courseId,n.courseName=a.courseName,(!a.version||!a.courseId||!a.chunks||!Array.isArray(a.chunks))&&(n.errors.push(`Invalid manifest structure`),n.valid=!1)}else n.errors.push(`Manifest not found: ${r}`),n.valid=!1;else{r=`${e}/manifest.json`,await nodeFS2.promises.access(r),n.manifestExists=!0;let t=await nodeFS2.promises.readFile(r,`utf8`),a=JSON.parse(t);n.courseId=a.courseId,n.courseName=a.courseName,(!a.version||!a.courseId||!a.chunks||!Array.isArray(a.chunks))&&(n.errors.push(`Invalid manifest structure`),n.valid=!1)}}catch(e){let t=e instanceof FileSystemError?e.message:`Manifest not found or invalid: ${r}`;n.errors.push(t),n.valid=!1}let a=`${e}/chunks`;try{t?(a=t.joinPath(e,`chunks`),await t.exists(a)?(await t.stat(a)).isDirectory()?n.chunksExist=!0:(n.errors.push(`Chunks path is not a directory: ${a}`),n.valid=!1):(n.errors.push(`Chunks directory not found: ${a}`),n.valid=!1)):(a=`${e}/chunks`,(await nodeFS2.promises.stat(a)).isDirectory()?n.chunksExist=!0:(n.errors.push(`Chunks path is not a directory: ${a}`),n.valid=!1))}catch(e){let t=e instanceof FileSystemError?e.message:`Chunks directory not found: ${a}`;n.errors.push(t),n.valid=!1}let o;try{t?(o=t.joinPath(e,`attachments`),await t.exists(o)?(await t.stat(o)).isDirectory()&&(n.attachmentsExist=!0):n.warnings.push(`Attachments directory not found: ${o} (this is OK if course has no attachments)`)):(o=`${e}/attachments`,(await nodeFS2.promises.stat(o)).isDirectory()&&(n.attachmentsExist=!0))}catch(t){o=o||`${e}/attachments`;let r=t instanceof FileSystemError?t.message:`Attachments directory not found: ${o} (this is OK if course has no attachments)`;n.warnings.push(r)}}catch(e){n.errors.push(`Failed to validate static course: ${e instanceof Error?e.message:String(e)}`),n.valid=!1}return n}async function validateMigration(e,t,n){let r={valid:!0,documentCountMatch:!1,attachmentIntegrity:!1,viewFunctionality:!1,issues:[]};try{logger.info(`Starting migration validation...`),r.documentCountMatch=compareDocumentCounts(t,await getActualDocumentCounts(e),r.issues),await validateCourseConfig(e,n,r.issues),r.viewFunctionality=await validateViews(e,n,r.issues),r.attachmentIntegrity=await validateAttachmentIntegrity(e,r.issues),r.valid=r.documentCountMatch&&r.viewFunctionality&&r.attachmentIntegrity,logger.info(`Migration validation completed. Valid: ${r.valid}`),r.issues.length>0&&(logger.info(`Validation issues: ${r.issues.length}`),r.issues.forEach(e=>{e.type===`error`?logger.error(`${e.category}: ${e.message}`):logger.warn(`${e.category}: ${e.message}`)}))}catch(e){r.valid=!1,r.issues.push({type:`error`,category:`metadata`,message:`Validation failed: ${e instanceof Error?e.message:String(e)}`})}return r}async function getActualDocumentCounts(e){let t={};try{let n=await e.allDocs({include_docs:!0});for(let e of n.rows){if(e.id.startsWith(`_design/`)){t._design=(t._design||0)+1;continue}let n=e.doc;n&&n.docType?t[n.docType]=(t[n.docType]||0)+1:t.unknown=(t.unknown||0)+1}}catch(e){logger.error(`Failed to get actual document counts:`,e)}return t}function compareDocumentCounts(e,t,n){let r=!0;for(let[a,o]of Object.entries(e)){let e=t[a]||0;e!==o&&(r=!1,n.push({type:`error`,category:`documents`,message:`Document count mismatch for ${a}: expected ${o}, got ${e}`}))}for(let[r,a]of Object.entries(t))!e[r]&&r!==`_design`&&n.push({type:`warning`,category:`documents`,message:`Unexpected document type found: ${r} (${a} documents)`});return r}async function validateCourseConfig(e,t,n){try{let r=await e.get(`CourseConfig`);if(!r){n.push({type:`error`,category:`course_config`,message:`CourseConfig document not found after migration`});return}r.courseID||n.push({type:`warning`,category:`course_config`,message:`CourseConfig document missing courseID field`}),r.courseID!==t.courseId&&n.push({type:`warning`,category:`course_config`,message:`CourseConfig courseID mismatch: expected ${t.courseId}, got ${r.courseID}`}),logger.debug(`CourseConfig document validation passed`)}catch(e){e.status===404?n.push({type:`error`,category:`course_config`,message:`CourseConfig document not found in database`}):n.push({type:`error`,category:`course_config`,message:`Failed to validate CourseConfig document: ${e instanceof Error?e.message:String(e)}`})}}async function validateViews(e,t,n){let r=!0;try{for(let a of t.designDocs)try{if(!await e.get(a._id)){r=!1,n.push({type:`error`,category:`views`,message:`Design document not found: ${a._id}`});continue}for(let t of Object.keys(a.views))try{let n=`${a._id}/${t}`;await e.query(n,{limit:1})}catch(e){r=!1,n.push({type:`error`,category:`views`,message:`View not accessible: ${a._id}/${t} - ${e}`})}}catch(e){r=!1,n.push({type:`error`,category:`views`,message:`Failed to validate design document ${a._id}: ${e}`})}}catch(e){r=!1,n.push({type:`error`,category:`views`,message:`View validation failed: ${e instanceof Error?e.message:String(e)}`})}return r}async function validateAttachmentIntegrity(e,t){let n=!0;try{let r=await e.allDocs({include_docs:!0,limit:10}),a=0,o=0;for(let s of r.rows){let r=s.doc;if(r&&r._attachments)for(let[s,c]of Object.entries(r._attachments)){a++;try{await e.getAttachment(r._id,s)&&o++}catch(e){n=!1,t.push({type:`error`,category:`attachments`,message:`Attachment not accessible: ${r._id}/${s} - ${e}`})}}}a===0?t.push({type:`warning`,category:`attachments`,message:`No attachments found in sampled documents`}):logger.info(`Validated ${o}/${a} sampled attachments`)}catch(e){n=!1,t.push({type:`error`,category:`attachments`,message:`Attachment validation failed: ${e instanceof Error?e.message:String(e)}`})}return n}var nodeFS3=null,nodePath=null;try{typeof window>`u`&&typeof process<`u`&&process.versions?.node&&(nodeFS3=eval(`require`)(`fs`),nodePath=eval(`require`)(`path`),nodeFS3.promises=nodeFS3.promises||eval(`require`)(`fs`).promises)}catch{}var StaticToCouchDBMigrator=class{constructor(e={},t){_defineProperty(this,`options`,void 0),_defineProperty(this,`progressCallback`,void 0),_defineProperty(this,`fs`,void 0),this.options={...DEFAULT_MIGRATION_OPTIONS,...e},this.fs=t}setProgressCallback(e){this.progressCallback=e}async migrateCourse(e,t){let n=Date.now(),r={success:!1,documentsRestored:0,attachmentsRestored:0,designDocsRestored:0,courseConfigRestored:0,errors:[],warnings:[],migrationTime:0};try{logger.info(`Starting migration from ${e} to CouchDB`),this.reportProgress(`manifest`,0,1,`Validating static course...`);let a=await validateStaticCourse(e,this.fs);if(!a.valid)throw r.errors.push(...a.errors),Error(`Static course validation failed: ${a.errors.join(`, `)}`);r.warnings.push(...a.warnings),this.reportProgress(`manifest`,1,1,`Loading course manifest...`);let o=await this.loadManifest(e);logger.info(`Loaded manifest for course: ${o.courseId} (${o.courseName})`),this.reportProgress(`design_docs`,0,o.designDocs.length,`Restoring design documents...`);let s=await this.restoreDesignDocuments(o.designDocs,t);r.designDocsRestored=s.restored,r.errors.push(...s.errors),r.warnings.push(...s.warnings),this.reportProgress(`course_config`,0,1,`Restoring CourseConfig document...`);let c=await this.restoreCourseConfig(o,t);r.courseConfigRestored=c.restored,r.errors.push(...c.errors),r.warnings.push(...c.warnings),this.reportProgress(`course_config`,1,1,`CourseConfig document restored`);let l=this.calculateExpectedCounts(o);this.reportProgress(`documents`,0,o.documentCount,`Aggregating documents from chunks...`);let u=await this.aggregateDocuments(e,o),d=u.filter(e=>e._id!==`CourseConfig`);u.length!==d.length&&r.warnings.push(`Filtered out ${u.length-d.length} CourseConfig document(s) from chunks to prevent conflicts`),this.reportProgress(`documents`,d.length,o.documentCount,`Uploading documents to CouchDB...`);let p=await this.uploadDocuments(d,t);r.documentsRestored=p.restored,r.errors.push(...p.errors),r.warnings.push(...p.warnings);let m=u.filter(e=>e._attachments&&Object.keys(e._attachments).length>0);this.reportProgress(`attachments`,0,m.length,`Uploading attachments...`);let g=await this.uploadAttachments(e,m,t);if(r.attachmentsRestored=g.restored,r.errors.push(...g.errors),r.warnings.push(...g.warnings),this.options.validateRoundTrip){this.reportProgress(`validation`,0,1,`Validating migration...`);let e=await validateMigration(t,l,o);e.valid||(r.warnings.push(`Migration validation found issues`),e.issues.forEach(e=>{e.type===`error`?r.errors.push(`Validation: ${e.message}`):r.warnings.push(`Validation: ${e.message}`)})),this.reportProgress(`validation`,1,1,`Migration validation completed`)}r.success=r.errors.length===0,r.migrationTime=Date.now()-n,logger.info(`Migration completed in ${r.migrationTime}ms`),logger.info(`Documents restored: ${r.documentsRestored}`),logger.info(`Attachments restored: ${r.attachmentsRestored}`),logger.info(`Design docs restored: ${r.designDocsRestored}`),logger.info(`CourseConfig restored: ${r.courseConfigRestored}`),r.errors.length>0&&logger.error(`Migration completed with ${r.errors.length} errors`),r.warnings.length>0&&logger.warn(`Migration completed with ${r.warnings.length} warnings`)}catch(e){r.success=!1,r.migrationTime=Date.now()-n;let a=e instanceof Error?e.message:String(e);if(r.errors.push(`Migration failed: ${a}`),logger.error(`Migration failed:`,e),this.options.cleanupOnFailure)try{await this.cleanupFailedMigration(t)}catch(e){logger.error(`Failed to cleanup after migration failure:`,e),r.warnings.push(`Failed to cleanup after migration failure`)}}return r}async loadManifest(e){try{let t,n;if(this.fs)n=this.fs.joinPath(e,`manifest.json`),t=await this.fs.readFile(n);else if(n=nodeFS3&&nodePath?nodePath.join(e,`manifest.json`):`${e}/manifest.json`,nodeFS3&&this.isLocalPath(e))t=await nodeFS3.promises.readFile(n,`utf8`);else{let e=await fetch(n);if(!e.ok)throw Error(`Failed to fetch manifest: ${e.status} ${e.statusText}`);t=await e.text()}let r=JSON.parse(t);if(!r.version||!r.courseId||!r.chunks)throw Error(`Invalid manifest structure`);return r}catch(e){let t=e instanceof FileSystemError?e.message:`Failed to load manifest: ${e instanceof Error?e.message:String(e)}`;throw Error(t)}}async restoreDesignDocuments(e,t){let n={restored:0,errors:[],warnings:[]};for(let r=0;r<e.length;r++){let a=e[r];this.reportProgress(`design_docs`,r,e.length,`Restoring ${a._id}...`);try{let e;try{e=await t.get(a._id)}catch{}let r={_id:a._id,views:a.views};e?(r._rev=e._rev,logger.debug(`Updating existing design document: ${a._id}`)):logger.debug(`Creating new design document: ${a._id}`),await t.put(r),n.restored++}catch(e){let t=`Failed to restore design document ${a._id}: ${e instanceof Error?e.message:String(e)}`;n.errors.push(t),logger.error(t)}}return this.reportProgress(`design_docs`,e.length,e.length,`Restored ${n.restored} design documents`),n}async aggregateDocuments(e,t){let n=[],r=new Map;for(let a=0;a<t.chunks.length;a++){let o=t.chunks[a];this.reportProgress(`documents`,n.length,t.documentCount,`Loading chunk ${o.id}...`);try{let t=await this.loadChunk(e,o);for(let e of t){if(!e._id){logger.warn(`Document without _id found in chunk ${o.id}, skipping`);continue}r.has(e._id)&&logger.warn(`Duplicate document ID found: ${e._id}, using latest version`),r.set(e._id,e)}}catch(e){throw Error(`Failed to load chunk ${o.id}: ${e instanceof Error?e.message:String(e)}`)}}return n.push(...r.values()),logger.info(`Aggregated ${n.length} unique documents from ${t.chunks.length} chunks`),n}async loadChunk(e,t){try{let n,r;if(this.fs)r=this.fs.joinPath(e,t.path),n=await this.fs.readFile(r);else if(r=nodeFS3&&nodePath?nodePath.join(e,t.path):`${e}/${t.path}`,nodeFS3&&this.isLocalPath(e))n=await nodeFS3.promises.readFile(r,`utf8`);else{let e=await fetch(r);if(!e.ok)throw Error(`Failed to fetch chunk: ${e.status} ${e.statusText}`);n=await e.text()}let a=JSON.parse(n);if(!Array.isArray(a))throw Error(`Chunk file does not contain an array of documents`);return a}catch(e){let t=e instanceof FileSystemError?e.message:`Failed to load chunk: ${e instanceof Error?e.message:String(e)}`;throw Error(t)}}async uploadDocuments(e,t){let n={restored:0,errors:[],warnings:[]},r=this.options.chunkBatchSize;for(let a=0;a<e.length;a+=r){let o=e.slice(a,a+r);this.reportProgress(`documents`,a,e.length,`Uploading batch ${Math.floor(a/r)+1}...`);try{let e=o.map(e=>{let t={...e};return delete t._rev,delete t._attachments,t}),r=await t.bulkDocs(e);for(let e=0;e<r.length;e++){let t=r[e],a=o[e];if(`error`in t){let e=`Failed to upload document ${a._id}: ${t.error} - ${t.reason}`;n.errors.push(e),logger.error(e)}else n.restored++}}catch(e){let t;t=e instanceof Error||e&&typeof e==`object`&&`message`in e?`Failed to upload document batch starting at index ${a}: ${e.message}`:`Failed to upload document batch starting at index ${a}: ${JSON.stringify(e)}`,n.errors.push(t),logger.error(t)}}return this.reportProgress(`documents`,e.length,e.length,`Uploaded ${n.restored} documents`),n}async uploadAttachments(e,t,n){let r={restored:0,errors:[],warnings:[]},a=0;for(let o of t)if(this.reportProgress(`attachments`,a,t.length,`Processing attachments for ${o._id}...`),a++,o._attachments)for(let[t,a]of Object.entries(o._attachments))try{let s=await this.uploadSingleAttachment(e,o._id,t,a,n);s.success?r.restored++:r.errors.push(s.error||`Unknown attachment upload error`)}catch(e){let n=`Failed to upload attachment ${o._id}/${t}: ${e instanceof Error?e.message:String(e)}`;r.errors.push(n),logger.error(n)}return this.reportProgress(`attachments`,t.length,t.length,`Uploaded ${r.restored} attachments`),r}async uploadSingleAttachment(e,t,n,r,a){let o={success:!1,attachmentName:n,docId:t};try{if(!r.path)return o.error=`Attachment metadata missing file path`,o;let s,c;if(this.fs)c=this.fs.joinPath(e,r.path),s=await this.fs.readBinary(c);else if(c=nodeFS3&&nodePath?nodePath.join(e,r.path):`${e}/${r.path}`,nodeFS3&&this.isLocalPath(e))s=await nodeFS3.promises.readFile(c);else{let e=await fetch(c);if(!e.ok)return o.error=`Failed to fetch attachment: ${e.status} ${e.statusText}`,o;s=await e.arrayBuffer()}let l=await a.get(t);await a.putAttachment(t,n,l._rev,s,r.content_type),o.success=!0}catch(e){o.error=e instanceof Error?e.message:String(e)}return o}async restoreCourseConfig(e,t){let n={restored:0,errors:[],warnings:[]};try{if(!e.courseConfig)return n.warnings.push(`No courseConfig found in manifest, skipping CourseConfig document creation`),n;let r={_id:`CourseConfig`,...e.courseConfig,courseID:e.courseId};delete r._rev,await t.put(r),n.restored=1,logger.info(`CourseConfig document created for course: ${e.courseId}`)}catch(e){let t=e instanceof Error?e.message:JSON.stringify(e);n.errors.push(`Failed to restore CourseConfig: ${t}`),logger.error(`CourseConfig restoration failed:`,e)}return n}calculateExpectedCounts(e){let t={};for(let n of e.chunks)t[n.docType]=(t[n.docType]||0)+n.documentCount;return e.designDocs.length>0&&(t._design=e.designDocs.length),t}async cleanupFailedMigration(e){logger.info(`Cleaning up failed migration...`);try{let t=(await e.allDocs()).rows.map(e=>({_id:e.id,_rev:e.value.rev,_deleted:!0}));t.length>0&&(await e.bulkDocs(t),logger.info(`Cleaned up ${t.length} documents from failed migration`))}catch(e){throw logger.error(`Failed to cleanup documents:`,e),e}}reportProgress(e,t,n,r){this.progressCallback&&this.progressCallback({phase:e,current:t,total:n,message:r})}isLocalPath(e){return!e.startsWith(`http://`)&&!e.startsWith(`https://`)}};init_dataDirectory(),init_navigators(),init_Pipeline();var QuotaRoundRobinMixer=class{mix(e,t){if(e.length===0)return[];let n=Math.ceil(t/e.length),r=e.map(e=>[...e.weighted].sort((e,t)=>t.score-e.score).slice(0,n));for(let e=r.length-1;e>0;e--){let t=Math.floor(Math.random()*(e+1));[r[e],r[t]]=[r[t],r[e]]}let a=[],o=0,s=Array(r.length).fill(0);for(;a.length<t&&o<r.length;){o=0;for(let e=0;e<r.length&&!(a.length>=t);e++)s[e]<r[e].length?(a.push(r[e][s[e]]),s[e]++):o++}return a}};init_logger(),init_navigators();var MAX_RUNS2=10,runHistory2=[];function buildSourceSummary(e,t,n){let r=e.weighted.map(e=>e.score),a=e.weighted.filter(e=>getCardOrigin(e)===`review`).length,o=e.weighted.filter(e=>getCardOrigin(e)===`new`).length;return{sourceIndex:e.sourceIndex,sourceId:t,sourceName:n,totalCards:e.weighted.length,reviewCount:a,newCount:o,topScore:r.length>0?Math.max(...r):0,bottomScore:r.length>0?Math.min(...r):0,scoreRange:r.length>0?[Math.min(...r),Math.max(...r)]:[0,0],avgScore:r.length>0?r.reduce((e,t)=>e+t,0)/r.length:0}}function buildSourceBreakdown(e,t,n){let r=n.filter(t=>t.courseId===e),a=r.filter(e=>e.selected);return{sourceId:e,sourceName:t,reviewsProvided:r.filter(e=>e.origin===`review`).length,newProvided:r.filter(e=>e.origin===`new`).length,reviewsSelected:a.filter(e=>e.origin===`review`).length,newSelected:a.filter(e=>e.origin===`new`).length,totalSelected:a.length,selectionRate:r.length>0?a.length/r.length*100:0}}function captureMixerRun(e,t,n,r,a,o,s){let c=t.map((e,t)=>buildSourceSummary(e,n[t]||`source-${t}`,r[t])),l=new Set(s.map(e=>e.cardId)),u=new Map;t.forEach(e=>{let t=[...e.weighted].sort((e,t)=>t.score-e.score),r=new Map;t.forEach((e,t)=>{r.set(e.cardId,t+1)}),u.set(n[e.sourceIndex]||`source-${e.sourceIndex}`,r)});let d=new Map;s.forEach((e,t)=>{d.set(e.cardId,t+1)});let p=new Map;t.forEach(e=>{e.weighted.forEach(e=>{p.set(e.cardId,e)})});let m=Array.from(p.values()).map(e=>({cardId:e.cardId,courseId:e.courseId,origin:getCardOrigin(e),score:e.score,sourceIndex:t.findIndex(t=>t.weighted.some(t=>t.cardId===e.cardId)),selected:l.has(e.cardId),rankInSource:u.get(e.courseId)?.get(e.cardId),rankInMix:d.get(e.cardId)})),g=Array.from(new Set(n.filter(e=>e))).map((e,t)=>buildSourceBreakdown(e,r[t],m)),_={runId:`mix-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date,mixerType:e,requestedLimit:a,quotaPerSource:o,sourceSummaries:c,cards:m,finalCount:s.length,reviewsSelected:s.filter(e=>getCardOrigin(e)===`review`).length,newSelected:s.filter(e=>getCardOrigin(e)===`new`).length,sourceBreakdowns:g};runHistory2.unshift(_),runHistory2.length>MAX_RUNS2&&runHistory2.pop()}function printMixerSummary(e){console.group(`\u{1F3A8} Mixer Run: ${e.mixerType}`),logger.info(`Run ID: ${e.runId}`),logger.info(`Time: ${e.timestamp.toISOString()}`),logger.info(`Config: limit=${e.requestedLimit}${e.quotaPerSource?`, quota/source=${e.quotaPerSource}`:``}`),console.group(`\u{1F4E5} Input: ${e.sourceSummaries.length} sources`);for(let t of e.sourceSummaries)logger.info(` ${t.sourceName||t.sourceId}: ${t.totalCards} cards (${t.reviewCount} reviews, ${t.newCount} new)`),logger.info(` Score range: [${t.scoreRange[0].toFixed(2)}, ${t.scoreRange[1].toFixed(2)}], avg: ${t.avgScore.toFixed(2)}`);console.groupEnd(),console.group(`\u{1F4E4} Output: ${e.finalCount} cards selected (${e.reviewsSelected} reviews, ${e.newSelected} new)`);for(let t of e.sourceBreakdowns){let e=t.sourceName||t.sourceId;logger.info(` ${e}: ${t.totalSelected} selected (${t.reviewsSelected} reviews, ${t.newSelected} new) - ${t.selectionRate.toFixed(1)}% selection rate`)}console.groupEnd(),console.groupEnd()}var mixerDebugAPI={get runs(){return[...runHistory2]},showRun(e=0){if(runHistory2.length===0){logger.info(`[Mixer Debug] No runs captured yet.`);return}let t;if(typeof e==`number`){if(t=runHistory2[e],!t){logger.info(`[Mixer Debug] No run found at index ${e}. History length: ${runHistory2.length}`);return}}else if(t=runHistory2.find(t=>t.runId.endsWith(e)),!t){logger.info(`[Mixer Debug] No run found matching ID '${e}'.`);return}printMixerSummary(t)},showLastMix(){this.showRun(0)},explainSourceBalance(){if(runHistory2.length===0){logger.info(`[Mixer Debug] No runs captured yet.`);return}let e=runHistory2[0];console.group(`⚖️ Source Balance Analysis`),logger.info(`Mixer: ${e.mixerType}`),logger.info(`Requested limit: ${e.requestedLimit}`),e.quotaPerSource&&logger.info(`Quota per source: ${e.quotaPerSource}`),console.group(`Input Distribution:`);for(let t of e.sourceSummaries){let e=t.sourceName||t.sourceId;logger.info(`${e}:`),logger.info(` Provided: ${t.totalCards} cards (${t.reviewCount} reviews, ${t.newCount} new)`),logger.info(` Score range: [${t.scoreRange[0].toFixed(2)}, ${t.scoreRange[1].toFixed(2)}]`)}console.groupEnd(),console.group(`Selection Results:`);for(let t of e.sourceBreakdowns){let e=t.sourceName||t.sourceId;logger.info(`${e}:`),logger.info(` Selected: ${t.totalSelected}/${t.reviewsProvided+t.newProvided} (${t.selectionRate.toFixed(1)}%)`),logger.info(` Reviews: ${t.reviewsSelected}/${t.reviewsProvided}`),logger.info(` New: ${t.newSelected}/${t.newProvided}`),t.reviewsProvided>0&&t.reviewsSelected===0&&logger.info(` ⚠️ Had reviews but none selected!`),t.totalSelected===0&&t.reviewsProvided+t.newProvided>0&&logger.info(` ⚠️ Had cards but none selected!`)}console.groupEnd();let t=e.sourceBreakdowns.map(e=>e.selectionRate),n=t.reduce((e,t)=>e+t,0)/t.length,r=Math.max(...t.map(e=>Math.abs(e-n)));r>20&&(logger.info(`
322
322
  \u26A0\uFE0F Significant imbalance detected (max deviation: ${r.toFixed(1)}%)`),logger.info(`Possible causes:`),logger.info(` - Score range differences between sources`),logger.info(` - One source has much better quality cards`),logger.info(` - Different card availability (reviews vs new)`)),console.groupEnd()},compareScores(){if(runHistory2.length===0){logger.info(`[Mixer Debug] No runs captured yet.`);return}let e=runHistory2[0];console.group(`📊 Score Distribution Comparison`),console.table(e.sourceSummaries.map(e=>({source:e.sourceName||e.sourceId,cards:e.totalCards,min:e.bottomScore.toFixed(3),max:e.topScore.toFixed(3),avg:e.avgScore.toFixed(3),range:(e.topScore-e.bottomScore).toFixed(3)})));let t=e.sourceSummaries.map(e=>e.topScore-e.bottomScore),n=e.sourceSummaries.map(e=>e.avgScore),r=Math.max(...t)-Math.min(...t),a=Math.max(...n)-Math.min(...n);(r>.3||a>.2)&&(logger.info(`
@@ -366,13 +366,13 @@ Example:
366
366
  window.skuilder.session.showInterleaving()
367
367
  window.skuilder.session.showQueue()
368
368
  `)}};function mountSessionDebugger(){if(typeof window>`u`)return;let e=window;e.skuilder=e.skuilder||{},e.skuilder.session=sessionDebugAPI}mountSessionDebugger(),init_logger();var SessionController=(_SessionController2=class _SessionController extends Loggable{set sessionRecord(e){this._sessionRecord=e}get secondsRemaining(){return this._secondsRemaining}get hasCardGuarantee(){return this._minCardsGuarantee>0}get report(){let e=this.supplyQ.dequeueCount;return`${e} supply ${e===1?`card`:`cards`} drawn`}get detailedReport(){return this.supplyQ.toString+`
369
- `+this.failedQ.toString}constructor(e,t,n,r,a,o){super(),_defineProperty(this,`_className`,`SessionController`),_defineProperty(this,`services`,void 0),_defineProperty(this,`srsService`,void 0),_defineProperty(this,`eloService`,void 0),_defineProperty(this,`hydrationService`,void 0),_defineProperty(this,`mixer`,void 0),_defineProperty(this,`dataLayer`,void 0),_defineProperty(this,`courseNameCache`,new Map),_defineProperty(this,`_defaultBatchLimit`,20),_defineProperty(this,`sources`,void 0),_defineProperty(this,`_sessionRecord`,[]),_defineProperty(this,`_currentCard`,null),_defineProperty(this,`supplyQ`,new ItemQueue),_defineProperty(this,`failedQ`,new ItemQueue),_defineProperty(this,`_supplyDrawsSinceFailed`,0),_defineProperty(this,`_replanPromise`,null),_defineProperty(this,`_activeReplanLabel`,null),_defineProperty(this,`_wellIndicatedRemaining`,0),_defineProperty(this,`_suppressQualityReplan`,!1),_defineProperty(this,`_minCardsGuarantee`,0),_defineProperty(this,`_sessionHints`,null),_defineProperty(this,`_servedCardIds`,new Set),_defineProperty(this,`_outcomeObservers`,[]),_defineProperty(this,`_sessionControls`,null),_defineProperty(this,`sessionId`,void 0),_defineProperty(this,`_courseId`,void 0),_defineProperty(this,`_stateSnapshotProvider`,void 0),_defineProperty(this,`_sessionDoc`,null),_defineProperty(this,`_openDocPromise`,null),_defineProperty(this,`_runLog`,[]),_defineProperty(this,`_sessionClosed`,!1),_defineProperty(this,`startTime`,void 0),_defineProperty(this,`endTime`,void 0),_defineProperty(this,`_secondsRemaining`,void 0),_defineProperty(this,`_intervalHandle`,void 0),this.sessionId=newSessionId(),setDebugSessionId(this.sessionId),this.dataLayer=n,this.mixer=a||new QuotaRoundRobinMixer,this.srsService=new SrsService(n.getUserDB()),this.eloService=new EloService(n,n.getUserDB()),this.hydrationService=new CardHydrationService(r,e=>n.getCourseDB(e),()=>this._getItemsToHydrate()),this.services={response:new ResponseProcessor(this.srsService,this.eloService)},this.sources=e,this.startTime=new Date,this._secondsRemaining=t,this.endTime=new Date(this.startTime.valueOf()+1e3*this._secondsRemaining),o?.defaultBatchLimit!==void 0&&(this._defaultBatchLimit=o.defaultBatchLimit),o?.outcomeObservers?.length&&(this._outcomeObservers=[...o.outcomeObservers]),this._courseId=o?.courseId,this._stateSnapshotProvider=o?.stateSnapshotProvider,this.log(`Session constructed:
369
+ `+this.failedQ.toString}constructor(e,t,n,r,a,o){super(),_defineProperty(this,`_className`,`SessionController`),_defineProperty(this,`services`,void 0),_defineProperty(this,`srsService`,void 0),_defineProperty(this,`eloService`,void 0),_defineProperty(this,`hydrationService`,void 0),_defineProperty(this,`mixer`,void 0),_defineProperty(this,`dataLayer`,void 0),_defineProperty(this,`courseNameCache`,new Map),_defineProperty(this,`_defaultBatchLimit`,20),_defineProperty(this,`sources`,void 0),_defineProperty(this,`_sessionRecord`,[]),_defineProperty(this,`_currentCard`,null),_defineProperty(this,`supplyQ`,new ItemQueue),_defineProperty(this,`failedQ`,new ItemQueue),_defineProperty(this,`_supplyDrawsSinceFailed`,0),_defineProperty(this,`_replanPromise`,null),_defineProperty(this,`_activeReplanLabel`,null),_defineProperty(this,`_wellIndicatedRemaining`,0),_defineProperty(this,`_suppressQualityReplan`,!1),_defineProperty(this,`_minCardsGuarantee`,0),_defineProperty(this,`_sessionHints`,null),_defineProperty(this,`_servedCardIds`,new Set),_defineProperty(this,`_outcomeObservers`,[]),_defineProperty(this,`_sessionControls`,null),_defineProperty(this,`sessionId`,void 0),_defineProperty(this,`_courseId`,void 0),_defineProperty(this,`_stateSnapshotProvider`,void 0),_defineProperty(this,`_sessionDoc`,null),_defineProperty(this,`_openDocPromise`,null),_defineProperty(this,`_runLog`,[]),_defineProperty(this,`_eloLog`,[]),_defineProperty(this,`_sessionClosed`,!1),_defineProperty(this,`startTime`,void 0),_defineProperty(this,`endTime`,void 0),_defineProperty(this,`_secondsRemaining`,void 0),_defineProperty(this,`_intervalHandle`,void 0),this.sessionId=newSessionId(),setDebugSessionId(this.sessionId),this.dataLayer=n,this.mixer=a||new QuotaRoundRobinMixer,this.srsService=new SrsService(n.getUserDB()),this.eloService=new EloService(n,n.getUserDB()),this.hydrationService=new CardHydrationService(r,e=>n.getCourseDB(e),()=>this._getItemsToHydrate()),this.services={response:new ResponseProcessor(this.srsService,this.eloService,e=>this._recordEloEvent(e))},this.sources=e,this.startTime=new Date,this._secondsRemaining=t,this.endTime=new Date(this.startTime.valueOf()+1e3*this._secondsRemaining),o?.defaultBatchLimit!==void 0&&(this._defaultBatchLimit=o.defaultBatchLimit),o?.outcomeObservers?.length&&(this._outcomeObservers=[...o.outcomeObservers]),this._courseId=o?.courseId,this._stateSnapshotProvider=o?.stateSnapshotProvider,this.log(`Session constructed:
370
370
  sessionId: ${this.sessionId}
371
371
  startTime: ${this.startTime}
372
372
  endTime: ${this.endTime}
373
- defaultBatchLimit: ${this._defaultBatchLimit}`),registerActiveController(this)}tick(){this._secondsRemaining=Math.floor((this.endTime.valueOf()-Date.now())/1e3),this._secondsRemaining<=0&&clearInterval(this._intervalHandle)}estimateCleanupTime(){let e=0;for(let t=0;t<this.failedQ.length;t++){let n=this.failedQ.peek(t),r=this._sessionRecord.find(e=>e.item.cardID===n.cardID),a=0;if(r){for(let e=0;e<r.records.length;e++)a+=r.records[e].timeSpent;a/=r.records.length,e+=a}}let t=e/1e3;return this.log(`Failed card cleanup estimate: ${Math.round(t)}`),t}async prepareSession(){if(this.sources.some(e=>typeof e.getWeightedCards!=`function`))throw Error(`[SessionController] All content sources must implement getWeightedCards().`);clearStaleSessionDebugState();let e=await this.getWeightedContent();this._recordRuns(`bootstrap`),this._wellIndicatedRemaining=e,e>=0&&e<_SessionController.MIN_WELL_INDICATED&&this.log(`[Init] Only ${e}/${_SessionController.MIN_WELL_INDICATED} well-indicated cards in initial load`),await this.hydrationService.ensureHydratedCards(),startSessionTracking(this.sessionId,this.supplyQ.length,this.failedQ.length),this._openDocPromise=this._openSessionDoc(),this._intervalHandle=setInterval(()=>{this.tick()},1e3)}_recordRuns(e,t){for(let n of drainCapturedRuns()){if(this._runLog.length>=_SessionController.MAX_LOGGED_RUNS)break;this._runLog.push({runId:n.runId,at:n.timestamp.toISOString(),label:e,...t?{mode:t}:{},generatedCount:n.generatedCount,finalCount:n.finalCount,reviewsSelected:n.reviewsSelected,newSelected:n.newSelected})}}async _captureState(e){if(!this._stateSnapshotProvider)return;let t=3e3;try{return await Promise.race([Promise.resolve(this._stateSnapshotProvider(e)),new Promise(e=>setTimeout(()=>e(void 0),3e3))])}catch(t){this.log(`[Session] state snapshot (${e}) failed: ${t}`);return}}async _openSessionDoc(){if(this._courseId)try{let e=this.dataLayer.getUserDB(),t={_id:makeStudySessionId(this._courseId,e.getUsername(),this.sessionId),docType:`STUDY_SESSION`,sessionId:this.sessionId,courseId:this._courseId,userId:e.getUsername(),startTime:this.startTime.toISOString(),status:`open`,plannedSeconds:Math.round((this.endTime.valueOf()-this.startTime.valueOf())/1e3),config:{defaultBatchLimit:this._defaultBatchLimit,sourceCount:this.sources.length,initHints:this._sessionHints},initialQueues:{supplyQ:this.supplyQ.length,failedQ:this.failedQ.length},runs:[...this._runLog],stateAtStart:await this._captureState(`start`)};this._sessionDoc=t,await e.putStudySession(t),this.log(`[Session] Opened session record ${t._id}`)}catch(e){logger.warn(`[SessionController] Failed to open session record: ${e}`)}}async requestReplan(e){let t=this.normalizeReplanOptions(e),n=this._replanHasIntent(t);if(this._replanPromise){if(!n)return this.log(`Replan already in progress, coalescing unhinted auto-replan`),this._replanPromise;let e=t.label?` [${t.label}]`:``;this.log(`Replan in progress; queueing hint-bearing replan${e} behind in-flight run`);let r=this._replanPromise.catch(()=>void 0).then(()=>this._runReplan(t)),a=r.finally(()=>{this._replanPromise===a&&(this._replanPromise=null,this._activeReplanLabel=null)});return this._replanPromise=a,r}let r=this._runReplan(t),a=r.finally(()=>{this._replanPromise===a&&(this._replanPromise=null,this._activeReplanLabel=null)});this._replanPromise=a,await r}_replanHasIntent(e){return!!(e.limit!==void 0||e.minFollowUpCards!==void 0||e.mode&&e.mode!==`replace`||e.hints&&Object.keys(e.hints).length>0||e.sessionHints!==void 0||e.mergeSessionHints!==void 0)}async _runReplan(e){this._activeReplanLabel=e.label??`(auto)`,e.hints||(e.hints={});let t=e.hints,n=new Set(t.excludeCards??[]);this._currentCard?.item.cardID&&n.add(this._currentCard.item.cardID);for(let e of this._sessionRecord)n.add(e.card.card_id);this.supplyQ.length>0&&n.add(this.supplyQ.peek(0).cardID),t.excludeCards=[...n],e.sessionHints!==void 0&&(this._sessionHints=e.sessionHints,this.log(`[Replan] Session hints ${e.sessionHints?`set`:`cleared`}: ${JSON.stringify(e.sessionHints)}`)),e.mergeSessionHints!==void 0&&(this._sessionHints=mergeHints2([this._sessionHints,e.mergeSessionHints])??null,this.log(`[Replan] Session hints merged: ${JSON.stringify(this._sessionHints)}`)),this._applyHintsToSources(e.hints,e.label);let r=e.label?` [${e.label}]`:``;this.log(`Mid-session replan requested${r} (limit: ${e.limit??`default`}, mode: ${e.mode??`replace`}${e.hints?`, with hints`:``})`),e.minFollowUpCards!==void 0&&e.minFollowUpCards>0&&(this._minCardsGuarantee=Math.max(this._minCardsGuarantee,e.minFollowUpCards),this.log(`[Replan] Card guarantee set to ${this._minCardsGuarantee}`)),await this._executeReplan(e)}setSessionHints(e){this._sessionHints=e,this.log(`Session hints ${e?`set`:`cleared`}: ${JSON.stringify(e)}`)}getSessionHints(){return this._sessionHints}getDebugSnapshot(){let describe=e=>{let t=[];for(let n=0;n<e.length;n++){let r=e.peek(n);t.push({cardID:r.cardID,status:r.status,origin:isReview(r)?`review`:`new`,score:r.score})}return{length:e.length,dequeueCount:e.dequeueCount,cards:t}},e=this._sessionRecord.map(e=>{let t=e.records[e.records.length-1];return{cardID:e.item.cardID,status:e.item.status,attempts:e.records.length,correct:t&&isQuestionRecord(t)?t.isCorrect:null,timeSpentMs:e.records.reduce((e,t)=>e+t.timeSpent,0)}});return{sessionId:this.sessionId,secondsRemaining:this.secondsRemaining,hasCardGuarantee:this.hasCardGuarantee,minCardsGuarantee:this._minCardsGuarantee,wellIndicatedRemaining:this._wellIndicatedRemaining,currentCard:this._currentCard?.item.cardID??null,sessionHints:this._sessionHints,replanActive:this._replanPromise!==null,replanLabel:this._activeReplanLabel,supplyQ:describe(this.supplyQ),failedQ:describe(this.failedQ),reviewBacklog:getSrsBacklogDebug(),strategyPressure:getStrategyPressureDebug(),drawnCards:e}}mergeSessionHints(e){this._sessionHints=mergeHints2([this._sessionHints,e])??null,this.log(`Session hints merged: ${JSON.stringify(this._sessionHints)}`)}_applyHintsToSources(e,t){let n=e&&t?{...e,_label:t}:e,r=mergeHints2([this._sessionHints,n]);if(r)for(let e of this.sources)e.setEphemeralHints?.(r)}_getSessionControls(){return this._sessionControls||(this._sessionControls={getSessionHints:()=>this.getSessionHints(),setSessionHints:e=>this.setSessionHints(e),mergeSessionHints:e=>this.mergeSessionHints(e),requestReplan:e=>this.requestReplan(e)}),this._sessionControls}async _notifyOutcomeObservers(e,t,n){if(this._outcomeObservers.length===0||!isQuestionRecord(e))return;let r={record:e,card:t.card,result:n},a=this._getSessionControls();for(let e of this._outcomeObservers)try{await e(r,a)}catch(e){this.error(`[OutcomeObserver] observer threw; ignoring`,e)}}async _replanUncoalesced(e){let t=this._runReplan(e),n=t.finally(()=>{this._replanPromise===n&&(this._replanPromise=null,this._activeReplanLabel=null)});this._replanPromise=n,await t}normalizeReplanOptions(e){if(!e)return{};let t=[`hints`,`sessionHints`,`limit`,`mode`,`label`,`minFollowUpCards`];return Object.keys(e).some(e=>t.includes(e))?e:{hints:e}}async _executeReplan(e={}){let t=e.limit,n=e.mode??`replace`,r=await this.getWeightedContent({replan:!0,additive:n===`merge`,limit:t});this._recordRuns(e.label??`(auto)`,n),this._wellIndicatedRemaining=r,t!==void 0&&t<this._defaultBatchLimit?(this._suppressQualityReplan=!0,this.log(`[Replan] Burst mode (limit=${t}): suppressing quality-based auto-replan`)):this._suppressQualityReplan=!1,r>=0&&r<_SessionController.MIN_WELL_INDICATED&&this.log(`[Replan] Only ${r}/${_SessionController.MIN_WELL_INDICATED} well-indicated cards after replan`),await this.hydrationService.ensureHydratedCards();let a=e.label?` [${e.label}]`:``;this.log(`Replan complete${a}: supplyQ now has ${this.supplyQ.length} cards (mode=${n})`),snapshotQueues(this.supplyQ.length,this.failedQ.length)}addTime(e){this.endTime=new Date(this.endTime.valueOf()+1e3*e)}get failedCount(){return this.failedQ.length}toString(){return`Session: ${this.supplyQ.length} supply, ${this.failedQ.length} failed`}reportString(){return`${this.supplyQ.dequeueCount} supply, ${this.failedQ.dequeueCount} failed`}getDebugInfo(){let e=this.sources.some(e=>typeof e.getWeightedCards==`function`),extractQueueItems=(e,t=10)=>{let n=[];for(let r=0;r<Math.min(e.length,t);r++){let t=e.peek(r);n.push({courseID:t.courseID||`unknown`,cardID:t.cardID||`unknown`,status:t.status||`unknown`,score:t.score})}return n};return{api:{mode:e?`weighted`:`legacy`,description:e?`Using getWeightedCards() API with scored candidates`:`ERROR: getWeightedCards() not a function.`},supplyQueue:{length:this.supplyQ.length,dequeueCount:this.supplyQ.dequeueCount,items:extractQueueItems(this.supplyQ)},failedQueue:{length:this.failedQ.length,dequeueCount:this.failedQ.dequeueCount,items:extractQueueItems(this.failedQ)},hydratedCache:{count:this.hydrationService.hydratedCount,cardIds:this.hydrationService.getHydratedCardIds()},replan:{inProgress:this._replanPromise!==null,suppressQualityReplan:this._suppressQualityReplan,defaultBatchLimit:this._defaultBatchLimit,minCardsGuarantee:this._minCardsGuarantee}}}async getWeightedContent(e){let t=e?.replan??!1,n=e?.additive??!1,r=e?.limit??this._defaultBatchLimit,a=r;t||this._applyHintsToSources();let o=[];for(let e=0;e<this.sources.length;e++){let t=this.sources[e];try{let n=(await t.getWeightedCards(a)).cards;o.push({sourceIndex:e,weighted:n})}catch(t){if(this.error(`Failed to get content from source ${e}:`,t),this.sources.length===1)throw Error(`Cannot start session: failed to load content from source ${e}`)}}if(o.length===0){if(t)return this.log(`Replan: no content from any source, keeping existing supplyQ`),-1;throw Error(`Cannot start session: failed to load content from all ${this.sources.length} source(s). Check logs for details.`)}let s=this.mixer.mix(o,a*this.sources.length),c=o.map(e=>e.weighted[0]?.courseId||`source-${e.sourceIndex}`);await Promise.all(c.map(async e=>{if(!this.courseNameCache.has(e))try{let t=await this.dataLayer.getCoursesDB().getCourseConfig(e);this.courseNameCache.set(e,t.name)}catch{}}));let l=c.map(e=>this.courseNameCache.get(e)),u=this.mixer instanceof QuotaRoundRobinMixer?Math.ceil(a*this.sources.length/o.length):void 0;captureMixerRun(this.mixer.constructor.name,o,c,l,a*this.sources.length,u,s);let d=s.filter(e=>!this._servedCardIds.has(e.cardId)),p=d.filter(e=>e.score===1/0),m=d.filter(e=>e.score!==1/0),g=[...p,...m.slice(0,Math.max(0,r-p.length))],_=new Set(p.map(e=>e.cardId)),v=g.filter(e=>e.score>=_SessionController.WELL_INDICATED_SCORE).length,y=t?`Replan content:
373
+ defaultBatchLimit: ${this._defaultBatchLimit}`),registerActiveController(this)}tick(){this._secondsRemaining=Math.floor((this.endTime.valueOf()-Date.now())/1e3),this._secondsRemaining<=0&&clearInterval(this._intervalHandle)}estimateCleanupTime(){let e=0;for(let t=0;t<this.failedQ.length;t++){let n=this.failedQ.peek(t),r=this._sessionRecord.find(e=>e.item.cardID===n.cardID),a=0;if(r){for(let e=0;e<r.records.length;e++)a+=r.records[e].timeSpent;a/=r.records.length,e+=a}}let t=e/1e3;return this.log(`Failed card cleanup estimate: ${Math.round(t)}`),t}async prepareSession(){if(this.sources.some(e=>typeof e.getWeightedCards!=`function`))throw Error(`[SessionController] All content sources must implement getWeightedCards().`);clearStaleSessionDebugState();let e=await this.getWeightedContent();this._recordRuns(`bootstrap`),this._wellIndicatedRemaining=e,e>=0&&e<_SessionController.MIN_WELL_INDICATED&&this.log(`[Init] Only ${e}/${_SessionController.MIN_WELL_INDICATED} well-indicated cards in initial load`),await this.hydrationService.ensureHydratedCards(),startSessionTracking(this.sessionId,this.supplyQ.length,this.failedQ.length),this._openDocPromise=this._openSessionDoc(),this._intervalHandle=setInterval(()=>{this.tick()},1e3)}_recordRuns(e,t){for(let n of drainCapturedRuns()){if(this._runLog.length>=_SessionController.MAX_LOGGED_RUNS)break;this._runLog.push({runId:n.runId,at:n.timestamp.toISOString(),label:e,...t?{mode:t}:{},generatedCount:n.generatedCount,finalCount:n.finalCount,reviewsSelected:n.reviewsSelected,newSelected:n.newSelected,...typeof n.userElo==`number`?{userElo:n.userElo}:{},...n.generators?{generators:n.generators}:{},...n.filters?{filters:n.filters}:{},...n.hints?{hints:n.hints}:{},...n.discardedTail?{discardedTail:n.discardedTail}:{}})}}async _captureState(e){if(!this._stateSnapshotProvider)return;let t=3e3;try{return await Promise.race([Promise.resolve(this._stateSnapshotProvider(e)),new Promise(e=>setTimeout(()=>e(void 0),3e3))])}catch(t){this.log(`[Session] state snapshot (${e}) failed: ${t}`);return}}async _openSessionDoc(){if(this._courseId)try{let e=this.dataLayer.getUserDB(),t={_id:makeStudySessionId(this._courseId,e.getUsername(),this.sessionId),docType:`STUDY_SESSION`,sessionId:this.sessionId,courseId:this._courseId,userId:e.getUsername(),startTime:this.startTime.toISOString(),status:`open`,plannedSeconds:Math.round((this.endTime.valueOf()-this.startTime.valueOf())/1e3),config:{defaultBatchLimit:this._defaultBatchLimit,sourceCount:this.sources.length,initHints:this._sessionHints},initialQueues:{supplyQ:this.supplyQ.length,failedQ:this.failedQ.length},runs:[...this._runLog],stateAtStart:await this._captureState(`start`)};this._sessionDoc=t,await e.putStudySession(t),this.log(`[Session] Opened session record ${t._id}`)}catch(e){logger.warn(`[SessionController] Failed to open session record: ${e}`)}}async requestReplan(e){let t=this.normalizeReplanOptions(e),n=this._replanHasIntent(t);if(this._replanPromise){if(!n)return this.log(`Replan already in progress, coalescing unhinted auto-replan`),this._replanPromise;let e=t.label?` [${t.label}]`:``;this.log(`Replan in progress; queueing hint-bearing replan${e} behind in-flight run`);let r=this._replanPromise.catch(()=>void 0).then(()=>this._runReplan(t)),a=r.finally(()=>{this._replanPromise===a&&(this._replanPromise=null,this._activeReplanLabel=null)});return this._replanPromise=a,r}let r=this._runReplan(t),a=r.finally(()=>{this._replanPromise===a&&(this._replanPromise=null,this._activeReplanLabel=null)});this._replanPromise=a,await r}_replanHasIntent(e){return!!(e.limit!==void 0||e.minFollowUpCards!==void 0||e.mode&&e.mode!==`replace`||e.hints&&Object.keys(e.hints).length>0||e.sessionHints!==void 0||e.mergeSessionHints!==void 0)}async _runReplan(e){this._activeReplanLabel=e.label??`(auto)`,e.hints||(e.hints={});let t=e.hints,n=new Set(t.excludeCards??[]);this._currentCard?.item.cardID&&n.add(this._currentCard.item.cardID);for(let e of this._sessionRecord)n.add(e.card.card_id);this.supplyQ.length>0&&n.add(this.supplyQ.peek(0).cardID),t.excludeCards=[...n],e.sessionHints!==void 0&&(this._sessionHints=e.sessionHints,this.log(`[Replan] Session hints ${e.sessionHints?`set`:`cleared`}: ${JSON.stringify(e.sessionHints)}`)),e.mergeSessionHints!==void 0&&(this._sessionHints=mergeHints2([this._sessionHints,e.mergeSessionHints])??null,this.log(`[Replan] Session hints merged: ${JSON.stringify(this._sessionHints)}`)),this._applyHintsToSources(e.hints,e.label);let r=e.label?` [${e.label}]`:``;this.log(`Mid-session replan requested${r} (limit: ${e.limit??`default`}, mode: ${e.mode??`replace`}${e.hints?`, with hints`:``})`),e.minFollowUpCards!==void 0&&e.minFollowUpCards>0&&(this._minCardsGuarantee=Math.max(this._minCardsGuarantee,e.minFollowUpCards),this.log(`[Replan] Card guarantee set to ${this._minCardsGuarantee}`)),await this._executeReplan(e)}setSessionHints(e){this._sessionHints=e,this.log(`Session hints ${e?`set`:`cleared`}: ${JSON.stringify(e)}`)}getSessionHints(){return this._sessionHints}getDebugSnapshot(){let describe=e=>{let t=[];for(let n=0;n<e.length;n++){let r=e.peek(n);t.push({cardID:r.cardID,status:r.status,origin:isReview(r)?`review`:`new`,score:r.score})}return{length:e.length,dequeueCount:e.dequeueCount,cards:t}},e=this._sessionRecord.map(e=>{let t=e.records[e.records.length-1];return{cardID:e.item.cardID,status:e.item.status,attempts:e.records.length,correct:t&&isQuestionRecord(t)?t.isCorrect:null,timeSpentMs:e.records.reduce((e,t)=>e+t.timeSpent,0)}});return{sessionId:this.sessionId,secondsRemaining:this.secondsRemaining,hasCardGuarantee:this.hasCardGuarantee,minCardsGuarantee:this._minCardsGuarantee,wellIndicatedRemaining:this._wellIndicatedRemaining,currentCard:this._currentCard?.item.cardID??null,sessionHints:this._sessionHints,replanActive:this._replanPromise!==null,replanLabel:this._activeReplanLabel,supplyQ:describe(this.supplyQ),failedQ:describe(this.failedQ),reviewBacklog:getSrsBacklogDebug(),strategyPressure:getStrategyPressureDebug(),drawnCards:e}}mergeSessionHints(e){this._sessionHints=mergeHints2([this._sessionHints,e])??null,this.log(`Session hints merged: ${JSON.stringify(this._sessionHints)}`)}_applyHintsToSources(e,t){let n=e&&t?{...e,_label:t}:e,r=mergeHints2([this._sessionHints,n]);if(r)for(let e of this.sources)e.setEphemeralHints?.(r)}_getSessionControls(){return this._sessionControls||(this._sessionControls={getSessionHints:()=>this.getSessionHints(),setSessionHints:e=>this.setSessionHints(e),mergeSessionHints:e=>this.mergeSessionHints(e),requestReplan:e=>this.requestReplan(e)}),this._sessionControls}_recordEloEvent(e){this._eloLog.length>=_SessionController.MAX_LOGGED_ELO_EVENTS||this._eloLog.push(e)}async _notifyOutcomeObservers(e,t,n){if(this._outcomeObservers.length===0||!isQuestionRecord(e))return;let r={record:e,card:t.card,result:n},a=this._getSessionControls();for(let e of this._outcomeObservers)try{await e(r,a)}catch(e){this.error(`[OutcomeObserver] observer threw; ignoring`,e)}}async _replanUncoalesced(e){let t=this._runReplan(e),n=t.finally(()=>{this._replanPromise===n&&(this._replanPromise=null,this._activeReplanLabel=null)});this._replanPromise=n,await t}normalizeReplanOptions(e){if(!e)return{};let t=[`hints`,`sessionHints`,`limit`,`mode`,`label`,`minFollowUpCards`];return Object.keys(e).some(e=>t.includes(e))?e:{hints:e}}async _executeReplan(e={}){let t=e.limit,n=e.mode??`replace`,r=await this.getWeightedContent({replan:!0,additive:n===`merge`,limit:t});this._recordRuns(e.label??`(auto)`,n),this._wellIndicatedRemaining=r,t!==void 0&&t<this._defaultBatchLimit?(this._suppressQualityReplan=!0,this.log(`[Replan] Burst mode (limit=${t}): suppressing quality-based auto-replan`)):this._suppressQualityReplan=!1,r>=0&&r<_SessionController.MIN_WELL_INDICATED&&this.log(`[Replan] Only ${r}/${_SessionController.MIN_WELL_INDICATED} well-indicated cards after replan`),await this.hydrationService.ensureHydratedCards();let a=e.label?` [${e.label}]`:``;this.log(`Replan complete${a}: supplyQ now has ${this.supplyQ.length} cards (mode=${n})`),snapshotQueues(this.supplyQ.length,this.failedQ.length)}addTime(e){this.endTime=new Date(this.endTime.valueOf()+1e3*e)}get failedCount(){return this.failedQ.length}toString(){return`Session: ${this.supplyQ.length} supply, ${this.failedQ.length} failed`}reportString(){return`${this.supplyQ.dequeueCount} supply, ${this.failedQ.dequeueCount} failed`}getDebugInfo(){let e=this.sources.some(e=>typeof e.getWeightedCards==`function`),extractQueueItems=(e,t=10)=>{let n=[];for(let r=0;r<Math.min(e.length,t);r++){let t=e.peek(r);n.push({courseID:t.courseID||`unknown`,cardID:t.cardID||`unknown`,status:t.status||`unknown`,score:t.score})}return n};return{api:{mode:e?`weighted`:`legacy`,description:e?`Using getWeightedCards() API with scored candidates`:`ERROR: getWeightedCards() not a function.`},supplyQueue:{length:this.supplyQ.length,dequeueCount:this.supplyQ.dequeueCount,items:extractQueueItems(this.supplyQ)},failedQueue:{length:this.failedQ.length,dequeueCount:this.failedQ.dequeueCount,items:extractQueueItems(this.failedQ)},hydratedCache:{count:this.hydrationService.hydratedCount,cardIds:this.hydrationService.getHydratedCardIds()},replan:{inProgress:this._replanPromise!==null,suppressQualityReplan:this._suppressQualityReplan,defaultBatchLimit:this._defaultBatchLimit,minCardsGuarantee:this._minCardsGuarantee}}}async getWeightedContent(e){let t=e?.replan??!1,n=e?.additive??!1,r=e?.limit??this._defaultBatchLimit,a=r;t||this._applyHintsToSources();let o=[];for(let e=0;e<this.sources.length;e++){let t=this.sources[e];try{let n=(await t.getWeightedCards(a)).cards;o.push({sourceIndex:e,weighted:n})}catch(t){if(this.error(`Failed to get content from source ${e}:`,t),this.sources.length===1)throw Error(`Cannot start session: failed to load content from source ${e}`)}}if(o.length===0){if(t)return this.log(`Replan: no content from any source, keeping existing supplyQ`),-1;throw Error(`Cannot start session: failed to load content from all ${this.sources.length} source(s). Check logs for details.`)}let s=this.mixer.mix(o,a*this.sources.length),c=o.map(e=>e.weighted[0]?.courseId||`source-${e.sourceIndex}`);await Promise.all(c.map(async e=>{if(!this.courseNameCache.has(e))try{let t=await this.dataLayer.getCoursesDB().getCourseConfig(e);this.courseNameCache.set(e,t.name)}catch{}}));let l=c.map(e=>this.courseNameCache.get(e)),u=this.mixer instanceof QuotaRoundRobinMixer?Math.ceil(a*this.sources.length/o.length):void 0;captureMixerRun(this.mixer.constructor.name,o,c,l,a*this.sources.length,u,s);let d=s.filter(e=>!this._servedCardIds.has(e.cardId)),p=d.filter(e=>e.score===1/0),m=d.filter(e=>e.score!==1/0),g=[...p,...m.slice(0,Math.max(0,r-p.length))],_=new Set(p.map(e=>e.cardId)),v=g.filter(e=>e.score>=_SessionController.WELL_INDICATED_SCORE).length,y=t?`Replan content:
374
374
  `:`Mixed content session created with:
375
375
  `,b=g.map(e=>{let t=getCardOrigin(e),n=Number.isFinite(e.score)?e.score.toFixed(2):`+INF`;return y+=`${t===`review`?`Review`:`New`}: ${e.courseId}::${e.cardId} (score: ${n})
376
376
  `,this._buildSupplyItem(e,t)});if(n){let e=this.supplyQ.mergeToFront(b,e=>e.cardID,_);y+=`Additive merge: ${e} cards added to front of supplyQ
377
- `}else if(t)this.supplyQ.replaceAll(b,e=>e.cardID);else for(let e of b)this.supplyQ.add(e,e.cardID);return this.log(y),v}_buildSupplyItem(e,t=getCardOrigin(e)){let n={cardID:e.cardId,courseID:e.courseId,contentSourceType:`course`,contentSourceID:e.courseId,score:e.score};return t===`review`?{...n,status:`review`,reviewID:e.reviewID}:{...n,status:`new`}}_getItemsToHydrate(){let e=[],t=3,n=2;for(let t=0;t<Math.min(3,this.supplyQ.length);t++)e.push(this.supplyQ.peek(t));for(let t=0;t<Math.min(2,this.failedQ.length);t++)e.push(this.failedQ.peek(t));return e}_selectNextItemToHydrate(){if(this.supplyQ.length===0&&this.failedQ.length===0||this._secondsRemaining<2&&this.failedQ.length===0&&this._minCardsGuarantee<=0)return null;if(this._secondsRemaining<=0&&this._minCardsGuarantee<=0)return this.failedQ.length>0?this.failedQ.peek(0):null;let e=this.supplyQ.length>0?this.supplyQ.peek(0):null;return this._minCardsGuarantee>0&&e?e:this.failedQ.length>0&&this._shouldInterleaveFailed(e!==null)?this.failedQ.peek(0):e||(this.failedQ.length>0?this.failedQ.peek(0):(this.log(`No more cards available for the session!`),null))}_shouldInterleaveFailed(e){return this.failedQ.length===0?!1:!e||this._secondsRemaining-this.estimateCleanupTime()<=_SessionController.FAILED_ENDGAME_SLACK_SECONDS?!0:this._supplyDrawsSinceFailed>=_SessionController.FAILED_INTERLEAVE_EVERY}async nextCard(e=`dismiss-success`){if(this.dismissCurrentCard(e),this._minCardsGuarantee>0&&(this._minCardsGuarantee--,this.log(`[CardGuarantee] ${this._minCardsGuarantee} guaranteed cards remaining`)),this._replanPromise&&this.supplyQ.length===0&&this.failedQ.length===0&&(this.log(`nextCard: queues empty, awaiting in-flight replan before drawing`),await this._replanPromise),this.supplyQ.length<=_SessionController.DEPLETION_PREFETCH_THRESHOLD&&this._secondsRemaining>0&&!this._replanPromise&&(this._suppressQualityReplan=!1,this.log(`[AutoReplan:depletion] supplyQ has ${this.supplyQ.length} card(s) (${this.failedQ.length} failed pending) with ${this._secondsRemaining}s remaining. Triggering background replan.`),this.requestReplan({label:`auto:depletion`,mode:`merge`})),!this._suppressQualityReplan&&this._wellIndicatedRemaining<=3&&this.supplyQ.length>0&&!this._replanPromise&&(this.log(`[AutoReplan:quality] ${this._wellIndicatedRemaining} well-indicated cards remaining (supplyQ: ${this.supplyQ.length}). Triggering background replan.`),this.requestReplan({label:`auto:quality`})),this._secondsRemaining<=0&&this.failedQ.length===0&&this._minCardsGuarantee<=0)return this._currentCard=null,endSessionTracking(),this._terminate(),null;let t=3,n=250,r=0;for(;this._secondsRemaining>0&&this.supplyQ.length===0&&this.failedQ.length===0;)if(this.log(`[WedgeBreaker] All queues empty with ${this._secondsRemaining}s remaining. Running pipeline (attempt ${r+1}/3).`),await this._replanUncoalesced({label:`wedge-breaker`}),this.supplyQ.length===0&&this.failedQ.length===0){if(r++,r>=3){this.log(`[WedgeBreaker] Pipeline returned no content 3 consecutive times. Giving up; session will end.`);break}await new Promise(e=>setTimeout(e,250))}else r=0;let a=20;for(let e=0;e<20;e++){let e=this._selectNextItemToHydrate();if(!e)return this._currentCard=null,endSessionTracking(),this._terminate(),null;let t=this.hydrationService.getHydratedCard(e.cardID);if(t||(t=await this.hydrationService.waitForCard(e.cardID)),this.removeItemFromQueue(e),t){await this.hydrationService.ensureHydratedCards(),this._currentCard=t;let n=e.status===`review`||e.status===`failed-review`?`review`:e.status===`new`||e.status===`failed-new`?`new`:`failed`,r=e.status.startsWith(`failed`)?`failedQ`:`supplyQ`;return recordCardPresentation(e.cardID,e.courseID,this.courseNameCache.get(e.courseID),n,r,e.score),snapshotQueues(this.supplyQ.length,this.failedQ.length),t}this.log(`Skipping card ${e.cardID}: hydration failed, trying next`),isReview(e)&&this.srsService.removeReview(e.reviewID)}return this.log(`Exhausted 20 skip attempts finding a hydratable card`),this._currentCard=null,endSessionTracking(),this._terminate(),null}_terminate(){this.endSession().catch(e=>{logger.warn(`[SessionController] endSession failed: ${e}`)})}async submitResponse(e,t,n,r,a,o,s,c,l){let u={...r.item},d=await this.services.response.processResponse(e,t,u,n,r,a,o,s,c,l);return await this._notifyOutcomeObservers(e,r,d),d}dismissCurrentCard(e=`dismiss-success`){if(this._currentCard)if(e===`dismiss-success`)this.hydrationService.removeCard(this._currentCard.item.cardID);else if(e===`marked-failed`){let e;e=isReview(this._currentCard.item)?{cardID:this._currentCard.item.cardID,courseID:this._currentCard.item.courseID,contentSourceID:this._currentCard.item.contentSourceID,contentSourceType:this._currentCard.item.contentSourceType,status:`failed-review`,reviewID:this._currentCard.item.reviewID}:{cardID:this._currentCard.item.cardID,courseID:this._currentCard.item.courseID,contentSourceID:this._currentCard.item.contentSourceID,contentSourceType:this._currentCard.item.contentSourceType,status:`failed-new`},this.failedQ.add(e,e.cardID),this._supplyDrawsSinceFailed=0}else (e===`dismiss-error`||e===`dismiss-failed`)&&this.hydrationService.removeCard(this._currentCard.item.cardID)}removeItemFromQueue(e){this._clearDurableRequirement(e.cardID),this._servedCardIds.add(e.cardID),this.failedQ.peek(0)?.cardID===e.cardID?(this.failedQ.dequeue(e=>e.cardID),this._supplyDrawsSinceFailed=0):this.supplyQ.peek(0)?.cardID===e.cardID&&(this.supplyQ.dequeue(e=>e.cardID),this._supplyDrawsSinceFailed++,this._wellIndicatedRemaining>0&&this._wellIndicatedRemaining--)}_clearDurableRequirement(e){let t=this._sessionHints?.requireCards;if(!t||t.length===0)return;let n=t.filter(t=>t!==e);n.length!==t.length&&(this._sessionHints={...this._sessionHints,requireCards:n.length>0?n:void 0},this.log(`[Replan] Durable requirement satisfied & cleared on draw: ${e}`))}async endSession(e=`closed`){if(this._sessionClosed||(this._sessionClosed=!0,clearInterval(this._intervalHandle),setDebugSessionId(void 0),await this._closeSessionDoc(e),!this._sessionRecord||this._sessionRecord.length===0))return;let t=this._sessionRecord.flatMap(e=>e.records).filter(e=>e.userAnswer!==void 0);if(t.length===0)return;let n=null,r=[];for(let e of this.sources)if(e.getOrchestrationContext){try{n=await e.getOrchestrationContext(),e.getStrategyIds&&r.push(...e.getStrategyIds())}catch(e){logger.warn(`[SessionController] Failed to get orchestration context: ${e}`)}if(n)break}if(!n){logger.debug(`[SessionController] No orchestration context available, skipping outcome recording`);return}let a=new Date().toISOString(),o=new Date(this.startTime).toISOString();await recordUserOutcome(n,o,a,t,r)}async _closeSessionDoc(e){this._openDocPromise&&await this._openDocPromise;let t=this._sessionDoc;if(!t)return;let n=this._sessionRecord.flatMap(e=>e.records),r=n.filter(isQuestionRecord);try{let a={...t,status:e,endTime:new Date().toISOString(),tally:{cardsPresented:this._sessionRecord.length,responses:n.length,correct:r.filter(e=>e.isCorrect).length,incorrect:r.filter(e=>!e.isCorrect).length,failedQRemaining:this.failedQ.length,secondsRemaining:Math.max(0,this._secondsRemaining)},runs:[...this._runLog],finalHints:this._sessionHints,stateAtEnd:await this._captureState(`end`)};this._sessionDoc=a,await this.dataLayer.getUserDB().putStudySession(a),this.log(`[Session] Session record ${a._id} -> ${e} (${a.tally.cardsPresented} cards, ${a.tally.responses} responses, ${this._runLog.length} pipeline runs)`)}catch(e){logger.warn(`[SessionController] Failed to close session record: ${e}`)}}},_defineProperty(_SessionController2,`MAX_LOGGED_RUNS`,100),_defineProperty(_SessionController2,`MIN_WELL_INDICATED`,5),_defineProperty(_SessionController2,`WELL_INDICATED_SCORE`,.1),_defineProperty(_SessionController2,`DEPLETION_PREFETCH_THRESHOLD`,3),_defineProperty(_SessionController2,`FAILED_INTERLEAVE_EVERY`,4),_defineProperty(_SessionController2,`FAILED_ENDGAME_SLACK_SECONDS`,20),_SessionController2);init_TagFilteredContentSource(),init_factory(),init_userDBHelpers();export{initializeDataLayer as $,computeSpread as A,snapshotQueues as At,getCardOrigin as B,captureStrategyPressure as C,registerQuestionType as Ct,computeDeviation as D,scoreAccuracyInZone as Dt,clearStrategyPressureDebug as E,removeQuestionType as Et,ensureAppDataDirectory as F,userDBDebugAPI as Ft,getRegisteredNavigatorRole as G,getDbPath as H,getActiveController as I,validateMigration as It,getStrategyPressureDebug as J,getRunsForSession as K,getActivePipeline as L,validateProcessorConfig as Lt,diversityRerank as M,toggleSessionOverlay as Mt,drainCapturedRuns as N,updateLearningState as Nt,computeEffectiveWeight as O,sessionDebugAPI as Ot,endSessionTracking as P,updateStrategyWeight as Pt,initializeDataDirectory as Q,getAppDataDirectory as R,validateStaticCourse as Rt,captureMixerRun as S,registerNavigator as St,clearStaleSessionDebugState as T,removeDataShape as Tt,getRegisteredNavigator as U,getDataLayer as V,getRegisteredNavigatorNames as W,hasRegisteredNavigator as X,getStudySource as Y,importParsedCards as Z,REVIEW_TIME_FORMAT as _,processCustomQuestionsData as _t,DocType as a,isReview as at,areQuestionRecords as b,registerActiveController as bt,FileSystemError as c,makeStudySessionId as ct,Loggable as d,mountPipelineDebugger as dt,initializeNavigatorRegistry as et,NOT_SET as f,mountSessionDebugger as ft,QuotaRoundRobinMixer as g,pipelineDebugAPI as gt,Navigators as h,newSessionId as ht,DIVERSITY_STRENGTH as i,isQuestionTypeRegistered as it,createOrchestrationContext as j,startSessionTracking as jt,computeOutcomeSignal as k,setDebugSessionId as kt,GuestUsername as l,mixerDebugAPI as lt,NavigatorRoles as m,newInterval as mt,CourseLookup as n,isGenerator as nt,DocTypePrefixes as o,log as ot,NavigatorRole as p,mountUserDBDebugger as pt,getSrsBacklogDebug as q,DIVERSITY_FLOOR as r,isQuestionRecord as rt,ENV as s,makeScheduledCardId as st,ContentNavigator as t,isFilter as tt,HYDRATION_MARKER_ID as u,mountMixerDebugger as ut,SessionController as v,recordCardPresentation as vt,clearSrsBacklogDebug as w,registerSeedData as wt,buildStrategyStateId as x,registerDataShape as xt,TagFilteredContentSource as y,recordUserOutcome as yt,getCardHistoryID as z};
378
- //# sourceMappingURL=dist-ByU4XK4n.js.map
377
+ `}else if(t)this.supplyQ.replaceAll(b,e=>e.cardID);else for(let e of b)this.supplyQ.add(e,e.cardID);return this.log(y),v}_buildSupplyItem(e,t=getCardOrigin(e)){let n={cardID:e.cardId,courseID:e.courseId,contentSourceType:`course`,contentSourceID:e.courseId,score:e.score};return t===`review`?{...n,status:`review`,reviewID:e.reviewID}:{...n,status:`new`}}_getItemsToHydrate(){let e=[],t=3,n=2;for(let t=0;t<Math.min(3,this.supplyQ.length);t++)e.push(this.supplyQ.peek(t));for(let t=0;t<Math.min(2,this.failedQ.length);t++)e.push(this.failedQ.peek(t));return e}_selectNextItemToHydrate(){if(this.supplyQ.length===0&&this.failedQ.length===0||this._secondsRemaining<2&&this.failedQ.length===0&&this._minCardsGuarantee<=0)return null;if(this._secondsRemaining<=0&&this._minCardsGuarantee<=0)return this.failedQ.length>0?this.failedQ.peek(0):null;let e=this.supplyQ.length>0?this.supplyQ.peek(0):null;return this._minCardsGuarantee>0&&e?e:this.failedQ.length>0&&this._shouldInterleaveFailed(e!==null)?this.failedQ.peek(0):e||(this.failedQ.length>0?this.failedQ.peek(0):(this.log(`No more cards available for the session!`),null))}_shouldInterleaveFailed(e){return this.failedQ.length===0?!1:!e||this._secondsRemaining-this.estimateCleanupTime()<=_SessionController.FAILED_ENDGAME_SLACK_SECONDS?!0:this._supplyDrawsSinceFailed>=_SessionController.FAILED_INTERLEAVE_EVERY}async nextCard(e=`dismiss-success`){if(this.dismissCurrentCard(e),this._minCardsGuarantee>0&&(this._minCardsGuarantee--,this.log(`[CardGuarantee] ${this._minCardsGuarantee} guaranteed cards remaining`)),this._replanPromise&&this.supplyQ.length===0&&this.failedQ.length===0&&(this.log(`nextCard: queues empty, awaiting in-flight replan before drawing`),await this._replanPromise),this.supplyQ.length<=_SessionController.DEPLETION_PREFETCH_THRESHOLD&&this._secondsRemaining>0&&!this._replanPromise&&(this._suppressQualityReplan=!1,this.log(`[AutoReplan:depletion] supplyQ has ${this.supplyQ.length} card(s) (${this.failedQ.length} failed pending) with ${this._secondsRemaining}s remaining. Triggering background replan.`),this.requestReplan({label:`auto:depletion`,mode:`merge`})),!this._suppressQualityReplan&&this._wellIndicatedRemaining<=3&&this.supplyQ.length>0&&!this._replanPromise&&(this.log(`[AutoReplan:quality] ${this._wellIndicatedRemaining} well-indicated cards remaining (supplyQ: ${this.supplyQ.length}). Triggering background replan.`),this.requestReplan({label:`auto:quality`})),this._secondsRemaining<=0&&this.failedQ.length===0&&this._minCardsGuarantee<=0)return this._currentCard=null,endSessionTracking(),this._terminate(),null;let t=3,n=250,r=0;for(;this._secondsRemaining>0&&this.supplyQ.length===0&&this.failedQ.length===0;)if(this.log(`[WedgeBreaker] All queues empty with ${this._secondsRemaining}s remaining. Running pipeline (attempt ${r+1}/3).`),await this._replanUncoalesced({label:`wedge-breaker`}),this.supplyQ.length===0&&this.failedQ.length===0){if(r++,r>=3){this.log(`[WedgeBreaker] Pipeline returned no content 3 consecutive times. Giving up; session will end.`);break}await new Promise(e=>setTimeout(e,250))}else r=0;let a=20;for(let e=0;e<20;e++){let e=this._selectNextItemToHydrate();if(!e)return this._currentCard=null,endSessionTracking(),this._terminate(),null;let t=this.hydrationService.getHydratedCard(e.cardID);if(t||(t=await this.hydrationService.waitForCard(e.cardID)),this.removeItemFromQueue(e),t){await this.hydrationService.ensureHydratedCards(),this._currentCard=t;let n=e.status===`review`||e.status===`failed-review`?`review`:e.status===`new`||e.status===`failed-new`?`new`:`failed`,r=e.status.startsWith(`failed`)?`failedQ`:`supplyQ`;return recordCardPresentation(e.cardID,e.courseID,this.courseNameCache.get(e.courseID),n,r,e.score),snapshotQueues(this.supplyQ.length,this.failedQ.length),t}this.log(`Skipping card ${e.cardID}: hydration failed, trying next`),isReview(e)&&this.srsService.removeReview(e.reviewID)}return this.log(`Exhausted 20 skip attempts finding a hydratable card`),this._currentCard=null,endSessionTracking(),this._terminate(),null}_terminate(){this.endSession().catch(e=>{logger.warn(`[SessionController] endSession failed: ${e}`)})}async submitResponse(e,t,n,r,a,o,s,c,l){let u={...r.item},d=await this.services.response.processResponse(e,t,u,n,r,a,o,s,c,l);return await this._notifyOutcomeObservers(e,r,d),d}dismissCurrentCard(e=`dismiss-success`){if(this._currentCard)if(e===`dismiss-success`)this.hydrationService.removeCard(this._currentCard.item.cardID);else if(e===`marked-failed`){let e;e=isReview(this._currentCard.item)?{cardID:this._currentCard.item.cardID,courseID:this._currentCard.item.courseID,contentSourceID:this._currentCard.item.contentSourceID,contentSourceType:this._currentCard.item.contentSourceType,status:`failed-review`,reviewID:this._currentCard.item.reviewID}:{cardID:this._currentCard.item.cardID,courseID:this._currentCard.item.courseID,contentSourceID:this._currentCard.item.contentSourceID,contentSourceType:this._currentCard.item.contentSourceType,status:`failed-new`},this.failedQ.add(e,e.cardID),this._supplyDrawsSinceFailed=0}else (e===`dismiss-error`||e===`dismiss-failed`)&&this.hydrationService.removeCard(this._currentCard.item.cardID)}removeItemFromQueue(e){this._clearDurableRequirement(e.cardID),this._servedCardIds.add(e.cardID),this.failedQ.peek(0)?.cardID===e.cardID?(this.failedQ.dequeue(e=>e.cardID),this._supplyDrawsSinceFailed=0):this.supplyQ.peek(0)?.cardID===e.cardID&&(this.supplyQ.dequeue(e=>e.cardID),this._supplyDrawsSinceFailed++,this._wellIndicatedRemaining>0&&this._wellIndicatedRemaining--)}_clearDurableRequirement(e){let t=this._sessionHints?.requireCards;if(!t||t.length===0)return;let n=t.filter(t=>t!==e);n.length!==t.length&&(this._sessionHints={...this._sessionHints,requireCards:n.length>0?n:void 0},this.log(`[Replan] Durable requirement satisfied & cleared on draw: ${e}`))}async endSession(e=`closed`){if(this._sessionClosed||(this._sessionClosed=!0,clearInterval(this._intervalHandle),setDebugSessionId(void 0),await this._closeSessionDoc(e),!this._sessionRecord||this._sessionRecord.length===0))return;let t=this._sessionRecord.flatMap(e=>e.records).filter(e=>e.userAnswer!==void 0);if(t.length===0)return;let n=null,r=[];for(let e of this.sources)if(e.getOrchestrationContext){try{n=await e.getOrchestrationContext(),e.getStrategyIds&&r.push(...e.getStrategyIds())}catch(e){logger.warn(`[SessionController] Failed to get orchestration context: ${e}`)}if(n)break}if(!n){logger.debug(`[SessionController] No orchestration context available, skipping outcome recording`);return}let a=new Date().toISOString(),o=new Date(this.startTime).toISOString();await recordUserOutcome(n,o,a,t,r)}async _closeSessionDoc(e){this._openDocPromise&&await this._openDocPromise;let t=this._sessionDoc;if(!t)return;let n=this._sessionRecord.flatMap(e=>e.records),r=n.filter(isQuestionRecord);try{let a={...t,status:e,endTime:new Date().toISOString(),tally:{cardsPresented:this._sessionRecord.length,responses:n.length,correct:r.filter(e=>e.isCorrect).length,incorrect:r.filter(e=>!e.isCorrect).length,failedQRemaining:this.failedQ.length,secondsRemaining:Math.max(0,this._secondsRemaining)},runs:[...this._runLog],eloEvents:[...this._eloLog],finalHints:this._sessionHints,stateAtEnd:await this._captureState(`end`)};this._sessionDoc=a,await this.dataLayer.getUserDB().putStudySession(a),this.log(`[Session] Session record ${a._id} -> ${e} (${a.tally.cardsPresented} cards, ${a.tally.responses} responses, ${this._runLog.length} pipeline runs)`)}catch(e){logger.warn(`[SessionController] Failed to close session record: ${e}`)}}},_defineProperty(_SessionController2,`MAX_LOGGED_RUNS`,100),_defineProperty(_SessionController2,`MAX_LOGGED_ELO_EVENTS`,2e3),_defineProperty(_SessionController2,`MIN_WELL_INDICATED`,5),_defineProperty(_SessionController2,`WELL_INDICATED_SCORE`,.1),_defineProperty(_SessionController2,`DEPLETION_PREFETCH_THRESHOLD`,3),_defineProperty(_SessionController2,`FAILED_INTERLEAVE_EVERY`,4),_defineProperty(_SessionController2,`FAILED_ENDGAME_SLACK_SECONDS`,20),_SessionController2);init_TagFilteredContentSource(),init_factory(),init_userDBHelpers();export{initializeDataLayer as $,computeSpread as A,snapshotQueues as At,getCardOrigin as B,captureStrategyPressure as C,registerQuestionType as Ct,computeDeviation as D,scoreAccuracyInZone as Dt,clearStrategyPressureDebug as E,removeQuestionType as Et,ensureAppDataDirectory as F,userDBDebugAPI as Ft,getRegisteredNavigatorRole as G,getDbPath as H,getActiveController as I,validateMigration as It,getStrategyPressureDebug as J,getRunsForSession as K,getActivePipeline as L,validateProcessorConfig as Lt,diversityRerank as M,toggleSessionOverlay as Mt,drainCapturedRuns as N,updateLearningState as Nt,computeEffectiveWeight as O,sessionDebugAPI as Ot,endSessionTracking as P,updateStrategyWeight as Pt,initializeDataDirectory as Q,getAppDataDirectory as R,validateStaticCourse as Rt,captureMixerRun as S,registerNavigator as St,clearStaleSessionDebugState as T,removeDataShape as Tt,getRegisteredNavigator as U,getDataLayer as V,getRegisteredNavigatorNames as W,hasRegisteredNavigator as X,getStudySource as Y,importParsedCards as Z,REVIEW_TIME_FORMAT as _,processCustomQuestionsData as _t,DocType as a,isReview as at,areQuestionRecords as b,registerActiveController as bt,FileSystemError as c,makeStudySessionId as ct,Loggable as d,mountPipelineDebugger as dt,initializeNavigatorRegistry as et,NOT_SET as f,mountSessionDebugger as ft,QuotaRoundRobinMixer as g,pipelineDebugAPI as gt,Navigators as h,newSessionId as ht,DIVERSITY_STRENGTH as i,isQuestionTypeRegistered as it,createOrchestrationContext as j,startSessionTracking as jt,computeOutcomeSignal as k,setDebugSessionId as kt,GuestUsername as l,mixerDebugAPI as lt,NavigatorRoles as m,newInterval as mt,CourseLookup as n,isGenerator as nt,DocTypePrefixes as o,log as ot,NavigatorRole as p,mountUserDBDebugger as pt,getSrsBacklogDebug as q,DIVERSITY_FLOOR as r,isQuestionRecord as rt,ENV as s,makeScheduledCardId as st,ContentNavigator as t,isFilter as tt,HYDRATION_MARKER_ID as u,mountMixerDebugger as ut,SessionController as v,recordCardPresentation as vt,clearSrsBacklogDebug as w,registerSeedData as wt,buildStrategyStateId as x,registerDataShape as xt,TagFilteredContentSource as y,recordUserOutcome as yt,getCardHistoryID as z};
378
+ //# sourceMappingURL=dist-CG_VzJ5d.js.map