@vue-skuilder/platform-ui 0.1.33 → 0.1.35

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 (104) hide show
  1. package/dist/assets/{About-C1rcp0Ex.js → About-CYoEhp5l.js} +2 -2
  2. package/dist/assets/{About-C1rcp0Ex.js.map → About-CYoEhp5l.js.map} +1 -1
  3. package/dist/assets/{AdminDashboard-BOHgXD45.js → AdminDashboard-DO3Mo6_x.js} +2 -2
  4. package/dist/assets/{AdminDashboard-BOHgXD45.js.map → AdminDashboard-DO3Mo6_x.js.map} +1 -1
  5. package/dist/assets/{ClassroomCtrlPanel-ezMgP7A3.js → ClassroomCtrlPanel-DkBMgZJU.js} +2 -2
  6. package/dist/assets/{ClassroomCtrlPanel-ezMgP7A3.js.map → ClassroomCtrlPanel-DkBMgZJU.js.map} +1 -1
  7. package/dist/assets/{Classrooms-CdN-ogiI.js → Classrooms-BRwjFo6r.js} +2 -2
  8. package/dist/assets/{Classrooms-CdN-ogiI.js.map → Classrooms-BRwjFo6r.js.map} +1 -1
  9. package/dist/assets/{CourseRouter-BKHj3HHh.js → CourseRouter-BrofD0lZ.js} +3 -3
  10. package/dist/assets/{CourseRouter-BKHj3HHh.js.map → CourseRouter-BrofD0lZ.js.map} +1 -1
  11. package/dist/assets/CourseWare-BTFRjgBR-ca7as3tn.js +3 -0
  12. package/dist/assets/CourseWare-BTFRjgBR-ca7as3tn.js.map +1 -0
  13. package/dist/assets/{Courses-DTsQz202.js → Courses-DyZS7Cle.js} +2 -2
  14. package/dist/assets/{Courses-DTsQz202.js.map → Courses-DyZS7Cle.js.map} +1 -1
  15. package/dist/assets/{EloModeration-DqViuzI8.js → EloModeration-B8hFSqwy.js} +2 -2
  16. package/dist/assets/{EloModeration-DqViuzI8.js.map → EloModeration-B8hFSqwy.js.map} +1 -1
  17. package/dist/assets/{JoinCode-BjbhKTgK.js → JoinCode-DOLzN-p-.js} +2 -2
  18. package/dist/assets/{JoinCode-BjbhKTgK.js.map → JoinCode-DOLzN-p-.js.map} +1 -1
  19. package/dist/assets/{MarkdownRenderer-DoVbFpA6-BIbDxYC4.js → MarkdownRenderer-DoVbFpA6-CvaBjTS8.js} +2 -2
  20. package/dist/assets/{MarkdownRenderer-DoVbFpA6-BIbDxYC4.js.map → MarkdownRenderer-DoVbFpA6-CvaBjTS8.js.map} +1 -1
  21. package/dist/assets/MarkdownRenderer-DoVbFpA6-DZdbKtns.js +1 -0
  22. package/dist/assets/{NewCourseDialog-4YsIKoUU.js → NewCourseDialog-CjeJyyc3.js} +2 -2
  23. package/dist/assets/{NewCourseDialog-4YsIKoUU.js.map → NewCourseDialog-CjeJyyc3.js.map} +1 -1
  24. package/dist/assets/{ReleaseNotes-BYXN8IZ4.js → ReleaseNotes-D9KhPUiR.js} +2 -2
  25. package/dist/assets/{ReleaseNotes-BYXN8IZ4.js.map → ReleaseNotes-D9KhPUiR.js.map} +1 -1
  26. package/dist/assets/{RequestPasswordReset-Zxt4oKHx.js → RequestPasswordReset-CdzOhOXs.js} +2 -2
  27. package/dist/assets/{RequestPasswordReset-Zxt4oKHx.js.map → RequestPasswordReset-CdzOhOXs.js.map} +1 -1
  28. package/dist/assets/{ResetPassword-rAc69I0Q.js → ResetPassword-Cu62zkXq.js} +2 -2
  29. package/dist/assets/{ResetPassword-rAc69I0Q.js.map → ResetPassword-Cu62zkXq.js.map} +1 -1
  30. package/dist/assets/{Study-DJlTc-ZH.js → Study-DYkoX3oR.js} +2 -2
  31. package/dist/assets/{Study-DJlTc-ZH.js.map → Study-DYkoX3oR.js.map} +1 -1
  32. package/dist/assets/{TagInformation-CSUtrZy7.js → TagInformation-PbQDPmpb.js} +2 -2
  33. package/dist/assets/{TagInformation-CSUtrZy7.js.map → TagInformation-PbQDPmpb.js.map} +1 -1
  34. package/dist/assets/{User-D2R6CphB.js → User-CIFHdgrZ.js} +2 -2
  35. package/dist/assets/{User-D2R6CphB.js.map → User-CIFHdgrZ.js.map} +1 -1
  36. package/dist/assets/{UserStats-BgnHXg6C.js → UserStats-DSyaFn7j.js} +2 -2
  37. package/dist/assets/{UserStats-BgnHXg6C.js.map → UserStats-DSyaFn7j.js.map} +1 -1
  38. package/dist/assets/{VerifyEmail-BLfciV-4.js → VerifyEmail-DWS9S3tV.js} +2 -2
  39. package/dist/assets/{VerifyEmail-BLfciV-4.js.map → VerifyEmail-DWS9S3tV.js.map} +1 -1
  40. package/dist/assets/chess-BbHATAzk-DOhLaMTg.js +7 -0
  41. package/dist/assets/chess-BbHATAzk-DOhLaMTg.js.map +1 -0
  42. package/dist/assets/chess-X1bmWmh3-C3HyTLIE.js +1 -0
  43. package/dist/assets/common-ui.es-BmXCkW19.js +1 -0
  44. package/dist/assets/{common-ui.es-I814CYyx.js → common-ui.es-ConLKYrk.js} +6 -6
  45. package/dist/assets/common-ui.es-ConLKYrk.js.map +1 -0
  46. package/dist/assets/{dist-DkeESCP4.js → dist-DKtzwGWn.js} +12 -11
  47. package/dist/assets/dist-DKtzwGWn.js.map +1 -0
  48. package/dist/assets/dist-Daq3OiEc.js +18 -0
  49. package/dist/assets/dist-Daq3OiEc.js.map +1 -0
  50. package/dist/assets/dist-EH1RSdAN.js +1 -0
  51. package/dist/assets/dist-huY4PEit.js +1 -0
  52. package/dist/assets/{dist-CrcJCHFk.js → dist-leWgtXBf.js} +2 -2
  53. package/dist/assets/dist-leWgtXBf.js.map +1 -0
  54. package/dist/assets/edit-ui.es-C6Itr3tP.js +1 -0
  55. package/dist/assets/edit-ui.es-DNDxRLE6.js +36 -0
  56. package/dist/assets/{edit-ui.es-Cs9EI-Ey.js.map → edit-ui.es-DNDxRLE6.js.map} +1 -1
  57. package/dist/assets/french-Dk7YG8Td-Bzxo0iir.js +2 -0
  58. package/dist/assets/french-Dk7YG8Td-Bzxo0iir.js.map +1 -0
  59. package/dist/assets/french-evUMlbbq-D88z2AaV.js +1 -0
  60. package/dist/assets/index-B4di3I6o.js +4 -0
  61. package/dist/assets/index-B4di3I6o.js.map +1 -0
  62. package/dist/assets/{index-DotoyByQ.css → index-CmEEzdUX.css} +1 -1
  63. package/dist/assets/math-B4HbgYf6-DW4In8a5.js +34 -0
  64. package/dist/assets/math-B4HbgYf6-DW4In8a5.js.map +1 -0
  65. package/dist/assets/math-DYni7rRl-BLRdDTmX.js +1 -0
  66. package/dist/assets/piano-BN5Btq91-D1ljSgCc.js +1 -0
  67. package/dist/assets/piano-DF1g6yaX-C9jL6jej.js +2 -0
  68. package/dist/assets/piano-DF1g6yaX-C9jL6jej.js.map +1 -0
  69. package/dist/assets/pitch-CgGJFkZ1-B4qiD-od.js +2 -0
  70. package/dist/assets/pitch-CgGJFkZ1-B4qiD-od.js.map +1 -0
  71. package/dist/assets/pitch-Dn0iNqiS-Vbm_Ue9p.js +1 -0
  72. package/dist/assets/{server-Cl1ZnRx7.js → server-RYtUROqF.js} +2 -2
  73. package/dist/assets/{server-Cl1ZnRx7.js.map → server-RYtUROqF.js.map} +1 -1
  74. package/dist/assets/sightsing-BFQ7HRig-gi-f6Gjx.js +133 -0
  75. package/dist/assets/sightsing-BFQ7HRig-gi-f6Gjx.js.map +1 -0
  76. package/dist/assets/sightsing-CJX3k0Fd-CLDxoSv_.js +1 -0
  77. package/dist/assets/typing-BevtfWlp-a9gMsGkx.js +2 -0
  78. package/dist/assets/typing-BevtfWlp-a9gMsGkx.js.map +1 -0
  79. package/dist/assets/typing-k-ojjO7G-CHVzRXi1.js +1 -0
  80. package/dist/assets/word-work-BOnRlZgd-DhZkqecP.js +2 -0
  81. package/dist/assets/word-work-BOnRlZgd-DhZkqecP.js.map +1 -0
  82. package/dist/assets/word-work-Dd6tIKrt-CVY1zayr.js +1 -0
  83. package/dist/index.html +6 -6
  84. package/dist/sw.js +1 -1
  85. package/dist/sw.js.map +1 -1
  86. package/package.json +8 -8
  87. package/src/main.ts +13 -2
  88. package/src/router.ts +17 -17
  89. package/dist/assets/DataInputFormTester-BC2ZDakI.js +0 -2
  90. package/dist/assets/DataInputFormTester-BC2ZDakI.js.map +0 -1
  91. package/dist/assets/MarkdownRenderer-DoVbFpA6-CQGwEJFh.js +0 -1
  92. package/dist/assets/common-ui.es-B6tKmOxI.js +0 -1
  93. package/dist/assets/common-ui.es-I814CYyx.js.map +0 -1
  94. package/dist/assets/dist-BjDnRspm.js +0 -1
  95. package/dist/assets/dist-BwVFN4Xe.js +0 -186
  96. package/dist/assets/dist-BwVFN4Xe.js.map +0 -1
  97. package/dist/assets/dist-CFgc27Ho.js +0 -1
  98. package/dist/assets/dist-CrcJCHFk.js.map +0 -1
  99. package/dist/assets/dist-DkeESCP4.js.map +0 -1
  100. package/dist/assets/edit-ui.es-C_I54ckd.js +0 -1
  101. package/dist/assets/edit-ui.es-Cs9EI-Ey.js +0 -36
  102. package/dist/assets/index-CF-NaZ2k.js +0 -4
  103. package/dist/assets/index-CF-NaZ2k.js.map +0 -1
  104. package/src/dev/DataInputFormTester.vue +0 -117
@@ -1,4 +1,4 @@
1
- import{i as __name,s as __toESM,t as __commonJSMin}from"./chunk-D6hFPZc3.js";import{C as NameSpacer,E as hooks,T as Status,_ as isCourseElo,b as isTaggedPerformance,g as blankCourseElo,h as adjustCourseScoresPerTag,l as require___vite_browser_external,m as adjustCourseScores,o as hasActiveFilter,p as EloToNumber,r as displayableDataToViewData,t as toZodJSON,v as toCourseElo,x as prepareNote55,y as _defineProperty}from"./dist-CrcJCHFk.js";var require_spark_md5=__commonJSMin(((e,t)=>{(function(n){if(typeof e==`object`)t.exports=n();else if(typeof define==`function`&&define.amd)define(n);else{var r;try{r=window}catch{r=self}r.SparkMD5=n()}})(function(e){var t=[`0`,`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`a`,`b`,`c`,`d`,`e`,`f`];function md5cycle(e,t){var n=e[0],r=e[1],a=e[2],o=e[3];n+=(r&a|~r&o)+t[0]-680876936|0,n=(n<<7|n>>>25)+r|0,o+=(n&r|~n&a)+t[1]-389564586|0,o=(o<<12|o>>>20)+n|0,a+=(o&n|~o&r)+t[2]+606105819|0,a=(a<<17|a>>>15)+o|0,r+=(a&o|~a&n)+t[3]-1044525330|0,r=(r<<22|r>>>10)+a|0,n+=(r&a|~r&o)+t[4]-176418897|0,n=(n<<7|n>>>25)+r|0,o+=(n&r|~n&a)+t[5]+1200080426|0,o=(o<<12|o>>>20)+n|0,a+=(o&n|~o&r)+t[6]-1473231341|0,a=(a<<17|a>>>15)+o|0,r+=(a&o|~a&n)+t[7]-45705983|0,r=(r<<22|r>>>10)+a|0,n+=(r&a|~r&o)+t[8]+1770035416|0,n=(n<<7|n>>>25)+r|0,o+=(n&r|~n&a)+t[9]-1958414417|0,o=(o<<12|o>>>20)+n|0,a+=(o&n|~o&r)+t[10]-42063|0,a=(a<<17|a>>>15)+o|0,r+=(a&o|~a&n)+t[11]-1990404162|0,r=(r<<22|r>>>10)+a|0,n+=(r&a|~r&o)+t[12]+1804603682|0,n=(n<<7|n>>>25)+r|0,o+=(n&r|~n&a)+t[13]-40341101|0,o=(o<<12|o>>>20)+n|0,a+=(o&n|~o&r)+t[14]-1502002290|0,a=(a<<17|a>>>15)+o|0,r+=(a&o|~a&n)+t[15]+1236535329|0,r=(r<<22|r>>>10)+a|0,n+=(r&o|a&~o)+t[1]-165796510|0,n=(n<<5|n>>>27)+r|0,o+=(n&a|r&~a)+t[6]-1069501632|0,o=(o<<9|o>>>23)+n|0,a+=(o&r|n&~r)+t[11]+643717713|0,a=(a<<14|a>>>18)+o|0,r+=(a&n|o&~n)+t[0]-373897302|0,r=(r<<20|r>>>12)+a|0,n+=(r&o|a&~o)+t[5]-701558691|0,n=(n<<5|n>>>27)+r|0,o+=(n&a|r&~a)+t[10]+38016083|0,o=(o<<9|o>>>23)+n|0,a+=(o&r|n&~r)+t[15]-660478335|0,a=(a<<14|a>>>18)+o|0,r+=(a&n|o&~n)+t[4]-405537848|0,r=(r<<20|r>>>12)+a|0,n+=(r&o|a&~o)+t[9]+568446438|0,n=(n<<5|n>>>27)+r|0,o+=(n&a|r&~a)+t[14]-1019803690|0,o=(o<<9|o>>>23)+n|0,a+=(o&r|n&~r)+t[3]-187363961|0,a=(a<<14|a>>>18)+o|0,r+=(a&n|o&~n)+t[8]+1163531501|0,r=(r<<20|r>>>12)+a|0,n+=(r&o|a&~o)+t[13]-1444681467|0,n=(n<<5|n>>>27)+r|0,o+=(n&a|r&~a)+t[2]-51403784|0,o=(o<<9|o>>>23)+n|0,a+=(o&r|n&~r)+t[7]+1735328473|0,a=(a<<14|a>>>18)+o|0,r+=(a&n|o&~n)+t[12]-1926607734|0,r=(r<<20|r>>>12)+a|0,n+=(r^a^o)+t[5]-378558|0,n=(n<<4|n>>>28)+r|0,o+=(n^r^a)+t[8]-2022574463|0,o=(o<<11|o>>>21)+n|0,a+=(o^n^r)+t[11]+1839030562|0,a=(a<<16|a>>>16)+o|0,r+=(a^o^n)+t[14]-35309556|0,r=(r<<23|r>>>9)+a|0,n+=(r^a^o)+t[1]-1530992060|0,n=(n<<4|n>>>28)+r|0,o+=(n^r^a)+t[4]+1272893353|0,o=(o<<11|o>>>21)+n|0,a+=(o^n^r)+t[7]-155497632|0,a=(a<<16|a>>>16)+o|0,r+=(a^o^n)+t[10]-1094730640|0,r=(r<<23|r>>>9)+a|0,n+=(r^a^o)+t[13]+681279174|0,n=(n<<4|n>>>28)+r|0,o+=(n^r^a)+t[0]-358537222|0,o=(o<<11|o>>>21)+n|0,a+=(o^n^r)+t[3]-722521979|0,a=(a<<16|a>>>16)+o|0,r+=(a^o^n)+t[6]+76029189|0,r=(r<<23|r>>>9)+a|0,n+=(r^a^o)+t[9]-640364487|0,n=(n<<4|n>>>28)+r|0,o+=(n^r^a)+t[12]-421815835|0,o=(o<<11|o>>>21)+n|0,a+=(o^n^r)+t[15]+530742520|0,a=(a<<16|a>>>16)+o|0,r+=(a^o^n)+t[2]-995338651|0,r=(r<<23|r>>>9)+a|0,n+=(a^(r|~o))+t[0]-198630844|0,n=(n<<6|n>>>26)+r|0,o+=(r^(n|~a))+t[7]+1126891415|0,o=(o<<10|o>>>22)+n|0,a+=(n^(o|~r))+t[14]-1416354905|0,a=(a<<15|a>>>17)+o|0,r+=(o^(a|~n))+t[5]-57434055|0,r=(r<<21|r>>>11)+a|0,n+=(a^(r|~o))+t[12]+1700485571|0,n=(n<<6|n>>>26)+r|0,o+=(r^(n|~a))+t[3]-1894986606|0,o=(o<<10|o>>>22)+n|0,a+=(n^(o|~r))+t[10]-1051523|0,a=(a<<15|a>>>17)+o|0,r+=(o^(a|~n))+t[1]-2054922799|0,r=(r<<21|r>>>11)+a|0,n+=(a^(r|~o))+t[8]+1873313359|0,n=(n<<6|n>>>26)+r|0,o+=(r^(n|~a))+t[15]-30611744|0,o=(o<<10|o>>>22)+n|0,a+=(n^(o|~r))+t[6]-1560198380|0,a=(a<<15|a>>>17)+o|0,r+=(o^(a|~n))+t[13]+1309151649|0,r=(r<<21|r>>>11)+a|0,n+=(a^(r|~o))+t[4]-145523070|0,n=(n<<6|n>>>26)+r|0,o+=(r^(n|~a))+t[11]-1120210379|0,o=(o<<10|o>>>22)+n|0,a+=(n^(o|~r))+t[2]+718787259|0,a=(a<<15|a>>>17)+o|0,r+=(o^(a|~n))+t[9]-343485551|0,r=(r<<21|r>>>11)+a|0,e[0]=n+e[0]|0,e[1]=r+e[1]|0,e[2]=a+e[2]|0,e[3]=o+e[3]|0}function md5blk(e){var t=[],n;for(n=0;n<64;n+=4)t[n>>2]=e.charCodeAt(n)+(e.charCodeAt(n+1)<<8)+(e.charCodeAt(n+2)<<16)+(e.charCodeAt(n+3)<<24);return t}function md5blk_array(e){var t=[],n;for(n=0;n<64;n+=4)t[n>>2]=e[n]+(e[n+1]<<8)+(e[n+2]<<16)+(e[n+3]<<24);return t}function md51(e){var t=e.length,n=[1732584193,-271733879,-1732584194,271733878],r,a,o,s,c,l;for(r=64;r<=t;r+=64)md5cycle(n,md5blk(e.substring(r-64,r)));for(e=e.substring(r-64),a=e.length,o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],r=0;r<a;r+=1)o[r>>2]|=e.charCodeAt(r)<<(r%4<<3);if(o[r>>2]|=128<<(r%4<<3),r>55)for(md5cycle(n,o),r=0;r<16;r+=1)o[r]=0;return s=t*8,s=s.toString(16).match(/(.*?)(.{0,8})$/),c=parseInt(s[2],16),l=parseInt(s[1],16)||0,o[14]=c,o[15]=l,md5cycle(n,o),n}function md51_array(e){var t=e.length,n=[1732584193,-271733879,-1732584194,271733878],r,a,o,s,c,l;for(r=64;r<=t;r+=64)md5cycle(n,md5blk_array(e.subarray(r-64,r)));for(e=r-64<t?e.subarray(r-64):new Uint8Array,a=e.length,o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],r=0;r<a;r+=1)o[r>>2]|=e[r]<<(r%4<<3);if(o[r>>2]|=128<<(r%4<<3),r>55)for(md5cycle(n,o),r=0;r<16;r+=1)o[r]=0;return s=t*8,s=s.toString(16).match(/(.*?)(.{0,8})$/),c=parseInt(s[2],16),l=parseInt(s[1],16)||0,o[14]=c,o[15]=l,md5cycle(n,o),n}function rhex(e){var n=``,r;for(r=0;r<4;r+=1)n+=t[e>>r*8+4&15]+t[e>>r*8&15];return n}function hex(e){var t;for(t=0;t<e.length;t+=1)e[t]=rhex(e[t]);return e.join(``)}hex(md51(`hello`)),typeof ArrayBuffer<`u`&&!ArrayBuffer.prototype.slice&&(function(){function clamp(e,t){return e=e|0||0,e<0?Math.max(e+t,0):Math.min(e,t)}ArrayBuffer.prototype.slice=function(t,n){var r=this.byteLength,a=clamp(t,r),o=r,s,c,l,u;return n!==e&&(o=clamp(n,r)),a>o?new ArrayBuffer(0):(s=o-a,c=new ArrayBuffer(s),l=new Uint8Array(c),u=new Uint8Array(this,a,s),l.set(u),c)}})();function toUtf8(e){return/[\u0080-\uFFFF]/.test(e)&&(e=unescape(encodeURIComponent(e))),e}function utf8Str2ArrayBuffer(e,t){var n=e.length,r=new ArrayBuffer(n),a=new Uint8Array(r),o;for(o=0;o<n;o+=1)a[o]=e.charCodeAt(o);return t?a:r}function arrayBuffer2Utf8Str(e){return String.fromCharCode.apply(null,new Uint8Array(e))}function concatenateArrayBuffers(e,t,n){var r=new Uint8Array(e.byteLength+t.byteLength);return r.set(new Uint8Array(e)),r.set(new Uint8Array(t),e.byteLength),n?r:r.buffer}function hexToBinaryString(e){var t=[],n=e.length,r;for(r=0;r<n-1;r+=2)t.push(parseInt(e.substr(r,2),16));return String.fromCharCode.apply(String,t)}function SparkMD5(){this.reset()}return SparkMD5.prototype.append=function(e){return this.appendBinary(toUtf8(e)),this},SparkMD5.prototype.appendBinary=function(e){this._buff+=e,this._length+=e.length;var t=this._buff.length,n;for(n=64;n<=t;n+=64)md5cycle(this._hash,md5blk(this._buff.substring(n-64,n)));return this._buff=this._buff.substring(n-64),this},SparkMD5.prototype.end=function(e){var t=this._buff,n=t.length,r,a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],o;for(r=0;r<n;r+=1)a[r>>2]|=t.charCodeAt(r)<<(r%4<<3);return this._finish(a,n),o=hex(this._hash),e&&(o=hexToBinaryString(o)),this.reset(),o},SparkMD5.prototype.reset=function(){return this._buff=``,this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},SparkMD5.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},SparkMD5.prototype.setState=function(e){return this._buff=e.buff,this._length=e.length,this._hash=e.hash,this},SparkMD5.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},SparkMD5.prototype._finish=function(e,t){var n=t,r,a,o;if(e[n>>2]|=128<<(n%4<<3),n>55)for(md5cycle(this._hash,e),n=0;n<16;n+=1)e[n]=0;r=this._length*8,r=r.toString(16).match(/(.*?)(.{0,8})$/),a=parseInt(r[2],16),o=parseInt(r[1],16)||0,e[14]=a,e[15]=o,md5cycle(this._hash,e)},SparkMD5.hash=function(e,t){return SparkMD5.hashBinary(toUtf8(e),t)},SparkMD5.hashBinary=function(e,t){var n=hex(md51(e));return t?hexToBinaryString(n):n},SparkMD5.ArrayBuffer=function(){this.reset()},SparkMD5.ArrayBuffer.prototype.append=function(e){var t=concatenateArrayBuffers(this._buff.buffer,e,!0),n=t.length,r;for(this._length+=e.byteLength,r=64;r<=n;r+=64)md5cycle(this._hash,md5blk_array(t.subarray(r-64,r)));return this._buff=r-64<n?new Uint8Array(t.buffer.slice(r-64)):new Uint8Array,this},SparkMD5.ArrayBuffer.prototype.end=function(e){var t=this._buff,n=t.length,r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],a,o;for(a=0;a<n;a+=1)r[a>>2]|=t[a]<<(a%4<<3);return this._finish(r,n),o=hex(this._hash),e&&(o=hexToBinaryString(o)),this.reset(),o},SparkMD5.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array,this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},SparkMD5.ArrayBuffer.prototype.getState=function(){var e=SparkMD5.prototype.getState.call(this);return e.buff=arrayBuffer2Utf8Str(e.buff),e},SparkMD5.ArrayBuffer.prototype.setState=function(e){return e.buff=utf8Str2ArrayBuffer(e.buff,!0),SparkMD5.prototype.setState.call(this,e)},SparkMD5.ArrayBuffer.prototype.destroy=SparkMD5.prototype.destroy,SparkMD5.ArrayBuffer.prototype._finish=SparkMD5.prototype._finish,SparkMD5.ArrayBuffer.hash=function(e,t){var n=hex(md51_array(new Uint8Array(e)));return t?hexToBinaryString(n):n},SparkMD5})})),getRandomValues$1,rnds8$1=new Uint8Array(16);function rng$1(){if(!getRandomValues$1&&(getRandomValues$1=typeof crypto<`u`&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<`u`&&typeof msCrypto.getRandomValues==`function`&&msCrypto.getRandomValues.bind(msCrypto),!getRandomValues$1))throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);return getRandomValues$1(rnds8$1)}__name(rng$1,`rng`);var regex_default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function validate$1(e){return typeof e==`string`&&regex_default.test(e)}__name(validate$1,`validate`);for(var byteToHex$1=[],i=0;i<256;++i)byteToHex$1.push((i+256).toString(16).substr(1));function stringify$2(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=(byteToHex$1[e[t+0]]+byteToHex$1[e[t+1]]+byteToHex$1[e[t+2]]+byteToHex$1[e[t+3]]+`-`+byteToHex$1[e[t+4]]+byteToHex$1[e[t+5]]+`-`+byteToHex$1[e[t+6]]+byteToHex$1[e[t+7]]+`-`+byteToHex$1[e[t+8]]+byteToHex$1[e[t+9]]+`-`+byteToHex$1[e[t+10]]+byteToHex$1[e[t+11]]+byteToHex$1[e[t+12]]+byteToHex$1[e[t+13]]+byteToHex$1[e[t+14]]+byteToHex$1[e[t+15]]).toLowerCase();if(!validate$1(n))throw TypeError(`Stringified UUID is invalid`);return n}__name(stringify$2,`stringify`);function v4$1(e,t,n){e=e||{};var r=e.random||(e.rng||rng$1)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){n=n||0;for(var a=0;a<16;++a)t[n+a]=r[a];return t}return stringify$2(r)}__name(v4$1,`v4`);var require_vuvuzela=__commonJSMin((e=>{e.stringify=function stringify(e){var t=[];t.push({obj:e});for(var n=``,r,a,o,s,c,l,u,d,p,m,g;r=t.pop();)if(a=r.obj,o=r.prefix||``,s=r.val||``,n+=o,s)n+=s;else if(typeof a!=`object`)n+=a===void 0?null:JSON.stringify(a);else if(a===null)n+=`null`;else if(Array.isArray(a)){for(t.push({val:`]`}),c=a.length-1;c>=0;c--)l=c===0?``:`,`,t.push({obj:a[c],prefix:l});t.push({val:`[`})}else{for(d in u=[],a)a.hasOwnProperty(d)&&u.push(d);for(t.push({val:`}`}),c=u.length-1;c>=0;c--)p=u[c],m=a[p],g=c>0?`,`:``,g+=JSON.stringify(p)+`:`,t.push({obj:m,prefix:g});t.push({val:`{`})}return n};function pop(e,t,n){var r=n[n.length-1];e===r.element&&(n.pop(),r=n[n.length-1]);var a=r.element,o=r.index;if(Array.isArray(a))a.push(e);else if(o===t.length-2){var s=t.pop();a[s]=e}else t.push(e)}e.parse=function(e){for(var t=[],n=[],r=0,a,o,s,c,l,u,d,p,m;;){if(a=e[r++],a===`}`||a===`]`||a===void 0){if(t.length===1)return t.pop();pop(t.pop(),t,n);continue}switch(a){case` `:case` `:case`
1
+ import{i as __name,s as __toESM,t as __commonJSMin}from"./chunk-D6hFPZc3.js";import{C as NameSpacer,E as hooks,T as Status,_ as isCourseElo,b as isTaggedPerformance,g as blankCourseElo,h as adjustCourseScoresPerTag,l as require___vite_browser_external,m as adjustCourseScores,o as hasActiveFilter,p as EloToNumber,r as displayableDataToViewData,t as toZodJSON,v as toCourseElo,x as prepareNote55,y as _defineProperty}from"./dist-leWgtXBf.js";var require_spark_md5=__commonJSMin(((e,t)=>{(function(n){if(typeof e==`object`)t.exports=n();else if(typeof define==`function`&&define.amd)define(n);else{var r;try{r=window}catch{r=self}r.SparkMD5=n()}})(function(e){var t=[`0`,`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`a`,`b`,`c`,`d`,`e`,`f`];function md5cycle(e,t){var n=e[0],r=e[1],a=e[2],o=e[3];n+=(r&a|~r&o)+t[0]-680876936|0,n=(n<<7|n>>>25)+r|0,o+=(n&r|~n&a)+t[1]-389564586|0,o=(o<<12|o>>>20)+n|0,a+=(o&n|~o&r)+t[2]+606105819|0,a=(a<<17|a>>>15)+o|0,r+=(a&o|~a&n)+t[3]-1044525330|0,r=(r<<22|r>>>10)+a|0,n+=(r&a|~r&o)+t[4]-176418897|0,n=(n<<7|n>>>25)+r|0,o+=(n&r|~n&a)+t[5]+1200080426|0,o=(o<<12|o>>>20)+n|0,a+=(o&n|~o&r)+t[6]-1473231341|0,a=(a<<17|a>>>15)+o|0,r+=(a&o|~a&n)+t[7]-45705983|0,r=(r<<22|r>>>10)+a|0,n+=(r&a|~r&o)+t[8]+1770035416|0,n=(n<<7|n>>>25)+r|0,o+=(n&r|~n&a)+t[9]-1958414417|0,o=(o<<12|o>>>20)+n|0,a+=(o&n|~o&r)+t[10]-42063|0,a=(a<<17|a>>>15)+o|0,r+=(a&o|~a&n)+t[11]-1990404162|0,r=(r<<22|r>>>10)+a|0,n+=(r&a|~r&o)+t[12]+1804603682|0,n=(n<<7|n>>>25)+r|0,o+=(n&r|~n&a)+t[13]-40341101|0,o=(o<<12|o>>>20)+n|0,a+=(o&n|~o&r)+t[14]-1502002290|0,a=(a<<17|a>>>15)+o|0,r+=(a&o|~a&n)+t[15]+1236535329|0,r=(r<<22|r>>>10)+a|0,n+=(r&o|a&~o)+t[1]-165796510|0,n=(n<<5|n>>>27)+r|0,o+=(n&a|r&~a)+t[6]-1069501632|0,o=(o<<9|o>>>23)+n|0,a+=(o&r|n&~r)+t[11]+643717713|0,a=(a<<14|a>>>18)+o|0,r+=(a&n|o&~n)+t[0]-373897302|0,r=(r<<20|r>>>12)+a|0,n+=(r&o|a&~o)+t[5]-701558691|0,n=(n<<5|n>>>27)+r|0,o+=(n&a|r&~a)+t[10]+38016083|0,o=(o<<9|o>>>23)+n|0,a+=(o&r|n&~r)+t[15]-660478335|0,a=(a<<14|a>>>18)+o|0,r+=(a&n|o&~n)+t[4]-405537848|0,r=(r<<20|r>>>12)+a|0,n+=(r&o|a&~o)+t[9]+568446438|0,n=(n<<5|n>>>27)+r|0,o+=(n&a|r&~a)+t[14]-1019803690|0,o=(o<<9|o>>>23)+n|0,a+=(o&r|n&~r)+t[3]-187363961|0,a=(a<<14|a>>>18)+o|0,r+=(a&n|o&~n)+t[8]+1163531501|0,r=(r<<20|r>>>12)+a|0,n+=(r&o|a&~o)+t[13]-1444681467|0,n=(n<<5|n>>>27)+r|0,o+=(n&a|r&~a)+t[2]-51403784|0,o=(o<<9|o>>>23)+n|0,a+=(o&r|n&~r)+t[7]+1735328473|0,a=(a<<14|a>>>18)+o|0,r+=(a&n|o&~n)+t[12]-1926607734|0,r=(r<<20|r>>>12)+a|0,n+=(r^a^o)+t[5]-378558|0,n=(n<<4|n>>>28)+r|0,o+=(n^r^a)+t[8]-2022574463|0,o=(o<<11|o>>>21)+n|0,a+=(o^n^r)+t[11]+1839030562|0,a=(a<<16|a>>>16)+o|0,r+=(a^o^n)+t[14]-35309556|0,r=(r<<23|r>>>9)+a|0,n+=(r^a^o)+t[1]-1530992060|0,n=(n<<4|n>>>28)+r|0,o+=(n^r^a)+t[4]+1272893353|0,o=(o<<11|o>>>21)+n|0,a+=(o^n^r)+t[7]-155497632|0,a=(a<<16|a>>>16)+o|0,r+=(a^o^n)+t[10]-1094730640|0,r=(r<<23|r>>>9)+a|0,n+=(r^a^o)+t[13]+681279174|0,n=(n<<4|n>>>28)+r|0,o+=(n^r^a)+t[0]-358537222|0,o=(o<<11|o>>>21)+n|0,a+=(o^n^r)+t[3]-722521979|0,a=(a<<16|a>>>16)+o|0,r+=(a^o^n)+t[6]+76029189|0,r=(r<<23|r>>>9)+a|0,n+=(r^a^o)+t[9]-640364487|0,n=(n<<4|n>>>28)+r|0,o+=(n^r^a)+t[12]-421815835|0,o=(o<<11|o>>>21)+n|0,a+=(o^n^r)+t[15]+530742520|0,a=(a<<16|a>>>16)+o|0,r+=(a^o^n)+t[2]-995338651|0,r=(r<<23|r>>>9)+a|0,n+=(a^(r|~o))+t[0]-198630844|0,n=(n<<6|n>>>26)+r|0,o+=(r^(n|~a))+t[7]+1126891415|0,o=(o<<10|o>>>22)+n|0,a+=(n^(o|~r))+t[14]-1416354905|0,a=(a<<15|a>>>17)+o|0,r+=(o^(a|~n))+t[5]-57434055|0,r=(r<<21|r>>>11)+a|0,n+=(a^(r|~o))+t[12]+1700485571|0,n=(n<<6|n>>>26)+r|0,o+=(r^(n|~a))+t[3]-1894986606|0,o=(o<<10|o>>>22)+n|0,a+=(n^(o|~r))+t[10]-1051523|0,a=(a<<15|a>>>17)+o|0,r+=(o^(a|~n))+t[1]-2054922799|0,r=(r<<21|r>>>11)+a|0,n+=(a^(r|~o))+t[8]+1873313359|0,n=(n<<6|n>>>26)+r|0,o+=(r^(n|~a))+t[15]-30611744|0,o=(o<<10|o>>>22)+n|0,a+=(n^(o|~r))+t[6]-1560198380|0,a=(a<<15|a>>>17)+o|0,r+=(o^(a|~n))+t[13]+1309151649|0,r=(r<<21|r>>>11)+a|0,n+=(a^(r|~o))+t[4]-145523070|0,n=(n<<6|n>>>26)+r|0,o+=(r^(n|~a))+t[11]-1120210379|0,o=(o<<10|o>>>22)+n|0,a+=(n^(o|~r))+t[2]+718787259|0,a=(a<<15|a>>>17)+o|0,r+=(o^(a|~n))+t[9]-343485551|0,r=(r<<21|r>>>11)+a|0,e[0]=n+e[0]|0,e[1]=r+e[1]|0,e[2]=a+e[2]|0,e[3]=o+e[3]|0}function md5blk(e){var t=[],n;for(n=0;n<64;n+=4)t[n>>2]=e.charCodeAt(n)+(e.charCodeAt(n+1)<<8)+(e.charCodeAt(n+2)<<16)+(e.charCodeAt(n+3)<<24);return t}function md5blk_array(e){var t=[],n;for(n=0;n<64;n+=4)t[n>>2]=e[n]+(e[n+1]<<8)+(e[n+2]<<16)+(e[n+3]<<24);return t}function md51(e){var t=e.length,n=[1732584193,-271733879,-1732584194,271733878],r,a,o,s,c,l;for(r=64;r<=t;r+=64)md5cycle(n,md5blk(e.substring(r-64,r)));for(e=e.substring(r-64),a=e.length,o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],r=0;r<a;r+=1)o[r>>2]|=e.charCodeAt(r)<<(r%4<<3);if(o[r>>2]|=128<<(r%4<<3),r>55)for(md5cycle(n,o),r=0;r<16;r+=1)o[r]=0;return s=t*8,s=s.toString(16).match(/(.*?)(.{0,8})$/),c=parseInt(s[2],16),l=parseInt(s[1],16)||0,o[14]=c,o[15]=l,md5cycle(n,o),n}function md51_array(e){var t=e.length,n=[1732584193,-271733879,-1732584194,271733878],r,a,o,s,c,l;for(r=64;r<=t;r+=64)md5cycle(n,md5blk_array(e.subarray(r-64,r)));for(e=r-64<t?e.subarray(r-64):new Uint8Array,a=e.length,o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],r=0;r<a;r+=1)o[r>>2]|=e[r]<<(r%4<<3);if(o[r>>2]|=128<<(r%4<<3),r>55)for(md5cycle(n,o),r=0;r<16;r+=1)o[r]=0;return s=t*8,s=s.toString(16).match(/(.*?)(.{0,8})$/),c=parseInt(s[2],16),l=parseInt(s[1],16)||0,o[14]=c,o[15]=l,md5cycle(n,o),n}function rhex(e){var n=``,r;for(r=0;r<4;r+=1)n+=t[e>>r*8+4&15]+t[e>>r*8&15];return n}function hex(e){var t;for(t=0;t<e.length;t+=1)e[t]=rhex(e[t]);return e.join(``)}hex(md51(`hello`)),typeof ArrayBuffer<`u`&&!ArrayBuffer.prototype.slice&&(function(){function clamp(e,t){return e=e|0||0,e<0?Math.max(e+t,0):Math.min(e,t)}ArrayBuffer.prototype.slice=function(t,n){var r=this.byteLength,a=clamp(t,r),o=r,s,c,l,u;return n!==e&&(o=clamp(n,r)),a>o?new ArrayBuffer(0):(s=o-a,c=new ArrayBuffer(s),l=new Uint8Array(c),u=new Uint8Array(this,a,s),l.set(u),c)}})();function toUtf8(e){return/[\u0080-\uFFFF]/.test(e)&&(e=unescape(encodeURIComponent(e))),e}function utf8Str2ArrayBuffer(e,t){var n=e.length,r=new ArrayBuffer(n),a=new Uint8Array(r),o;for(o=0;o<n;o+=1)a[o]=e.charCodeAt(o);return t?a:r}function arrayBuffer2Utf8Str(e){return String.fromCharCode.apply(null,new Uint8Array(e))}function concatenateArrayBuffers(e,t,n){var r=new Uint8Array(e.byteLength+t.byteLength);return r.set(new Uint8Array(e)),r.set(new Uint8Array(t),e.byteLength),n?r:r.buffer}function hexToBinaryString(e){var t=[],n=e.length,r;for(r=0;r<n-1;r+=2)t.push(parseInt(e.substr(r,2),16));return String.fromCharCode.apply(String,t)}function SparkMD5(){this.reset()}return SparkMD5.prototype.append=function(e){return this.appendBinary(toUtf8(e)),this},SparkMD5.prototype.appendBinary=function(e){this._buff+=e,this._length+=e.length;var t=this._buff.length,n;for(n=64;n<=t;n+=64)md5cycle(this._hash,md5blk(this._buff.substring(n-64,n)));return this._buff=this._buff.substring(n-64),this},SparkMD5.prototype.end=function(e){var t=this._buff,n=t.length,r,a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],o;for(r=0;r<n;r+=1)a[r>>2]|=t.charCodeAt(r)<<(r%4<<3);return this._finish(a,n),o=hex(this._hash),e&&(o=hexToBinaryString(o)),this.reset(),o},SparkMD5.prototype.reset=function(){return this._buff=``,this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},SparkMD5.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},SparkMD5.prototype.setState=function(e){return this._buff=e.buff,this._length=e.length,this._hash=e.hash,this},SparkMD5.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},SparkMD5.prototype._finish=function(e,t){var n=t,r,a,o;if(e[n>>2]|=128<<(n%4<<3),n>55)for(md5cycle(this._hash,e),n=0;n<16;n+=1)e[n]=0;r=this._length*8,r=r.toString(16).match(/(.*?)(.{0,8})$/),a=parseInt(r[2],16),o=parseInt(r[1],16)||0,e[14]=a,e[15]=o,md5cycle(this._hash,e)},SparkMD5.hash=function(e,t){return SparkMD5.hashBinary(toUtf8(e),t)},SparkMD5.hashBinary=function(e,t){var n=hex(md51(e));return t?hexToBinaryString(n):n},SparkMD5.ArrayBuffer=function(){this.reset()},SparkMD5.ArrayBuffer.prototype.append=function(e){var t=concatenateArrayBuffers(this._buff.buffer,e,!0),n=t.length,r;for(this._length+=e.byteLength,r=64;r<=n;r+=64)md5cycle(this._hash,md5blk_array(t.subarray(r-64,r)));return this._buff=r-64<n?new Uint8Array(t.buffer.slice(r-64)):new Uint8Array,this},SparkMD5.ArrayBuffer.prototype.end=function(e){var t=this._buff,n=t.length,r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],a,o;for(a=0;a<n;a+=1)r[a>>2]|=t[a]<<(a%4<<3);return this._finish(r,n),o=hex(this._hash),e&&(o=hexToBinaryString(o)),this.reset(),o},SparkMD5.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array,this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},SparkMD5.ArrayBuffer.prototype.getState=function(){var e=SparkMD5.prototype.getState.call(this);return e.buff=arrayBuffer2Utf8Str(e.buff),e},SparkMD5.ArrayBuffer.prototype.setState=function(e){return e.buff=utf8Str2ArrayBuffer(e.buff,!0),SparkMD5.prototype.setState.call(this,e)},SparkMD5.ArrayBuffer.prototype.destroy=SparkMD5.prototype.destroy,SparkMD5.ArrayBuffer.prototype._finish=SparkMD5.prototype._finish,SparkMD5.ArrayBuffer.hash=function(e,t){var n=hex(md51_array(new Uint8Array(e)));return t?hexToBinaryString(n):n},SparkMD5})})),getRandomValues$1,rnds8$1=new Uint8Array(16);function rng$1(){if(!getRandomValues$1&&(getRandomValues$1=typeof crypto<`u`&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<`u`&&typeof msCrypto.getRandomValues==`function`&&msCrypto.getRandomValues.bind(msCrypto),!getRandomValues$1))throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);return getRandomValues$1(rnds8$1)}__name(rng$1,`rng`);var regex_default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function validate$1(e){return typeof e==`string`&&regex_default.test(e)}__name(validate$1,`validate`);for(var byteToHex$1=[],i=0;i<256;++i)byteToHex$1.push((i+256).toString(16).substr(1));function stringify$2(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=(byteToHex$1[e[t+0]]+byteToHex$1[e[t+1]]+byteToHex$1[e[t+2]]+byteToHex$1[e[t+3]]+`-`+byteToHex$1[e[t+4]]+byteToHex$1[e[t+5]]+`-`+byteToHex$1[e[t+6]]+byteToHex$1[e[t+7]]+`-`+byteToHex$1[e[t+8]]+byteToHex$1[e[t+9]]+`-`+byteToHex$1[e[t+10]]+byteToHex$1[e[t+11]]+byteToHex$1[e[t+12]]+byteToHex$1[e[t+13]]+byteToHex$1[e[t+14]]+byteToHex$1[e[t+15]]).toLowerCase();if(!validate$1(n))throw TypeError(`Stringified UUID is invalid`);return n}__name(stringify$2,`stringify`);function v4$1(e,t,n){e=e||{};var r=e.random||(e.rng||rng$1)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){n=n||0;for(var a=0;a<16;++a)t[n+a]=r[a];return t}return stringify$2(r)}__name(v4$1,`v4`);var require_vuvuzela=__commonJSMin((e=>{e.stringify=function stringify(e){var t=[];t.push({obj:e});for(var n=``,r,a,o,s,c,l,u,d,p,m,g;r=t.pop();)if(a=r.obj,o=r.prefix||``,s=r.val||``,n+=o,s)n+=s;else if(typeof a!=`object`)n+=a===void 0?null:JSON.stringify(a);else if(a===null)n+=`null`;else if(Array.isArray(a)){for(t.push({val:`]`}),c=a.length-1;c>=0;c--)l=c===0?``:`,`,t.push({obj:a[c],prefix:l});t.push({val:`[`})}else{for(d in u=[],a)a.hasOwnProperty(d)&&u.push(d);for(t.push({val:`}`}),c=u.length-1;c>=0;c--)p=u[c],m=a[p],g=c>0?`,`:``,g+=JSON.stringify(p)+`:`,t.push({obj:m,prefix:g});t.push({val:`{`})}return n};function pop(e,t,n){var r=n[n.length-1];e===r.element&&(n.pop(),r=n[n.length-1]);var a=r.element,o=r.index;if(Array.isArray(a))a.push(e);else if(o===t.length-2){var s=t.pop();a[s]=e}else t.push(e)}e.parse=function(e){for(var t=[],n=[],r=0,a,o,s,c,l,u,d,p,m;;){if(a=e[r++],a===`}`||a===`]`||a===void 0){if(t.length===1)return t.pop();pop(t.pop(),t,n);continue}switch(a){case` `:case` `:case`
2
2
  `:case`:`:case`,`:break;case`n`:r+=3,pop(null,t,n);break;case`t`:r+=3,pop(!0,t,n);break;case`f`:r+=4,pop(!1,t,n);break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:case`-`:for(o=``,r--;;)if(s=e[r++],/[\d\.\-e\+]/.test(s))o+=s;else{r--;break}pop(parseFloat(o),t,n);break;case`"`:for(c=``,l=void 0,u=0;d=e[r++],d!==`"`||l===`\\`&&u%2==1;)c+=d,l=d,l===`\\`?u++:u=0;pop(JSON.parse(`"`+c+`"`),t,n);break;case`[`:p={element:[],index:t.length},t.push(p.element),n.push(p);break;case`{`:m={element:{},index:t.length},t.push(m.element),n.push(m);break;default:throw Error(`unexpectedly reached end of input: `+a)}}}})),require_events=__commonJSMin(((e,t)=>{var n=typeof Reflect==`object`?Reflect:null,r=n&&typeof n.apply==`function`?n.apply:function ReflectApply(e,t,n){return Function.prototype.apply.call(e,t,n)},a=n&&typeof n.ownKeys==`function`?n.ownKeys:Object.getOwnPropertySymbols?function ReflectOwnKeys(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function ReflectOwnKeys(e){return Object.getOwnPropertyNames(e)};function ProcessEmitWarning(e){console&&console.warn&&console.warn(e)}var o=Number.isNaN||function NumberIsNaN(e){return e!==e};function EventEmitter(){EventEmitter.init.call(this)}t.exports=EventEmitter,t.exports.once=once,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._eventsCount=0,EventEmitter.prototype._maxListeners=void 0;var s=10;function checkListener(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(EventEmitter,`defaultMaxListeners`,{enumerable:!0,get:function(){return s},set:function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);s=e}}),EventEmitter.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},EventEmitter.prototype.setMaxListeners=function setMaxListeners(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+e+`.`);return this._maxListeners=e,this};function _getMaxListeners(e){return e._maxListeners===void 0?EventEmitter.defaultMaxListeners:e._maxListeners}EventEmitter.prototype.getMaxListeners=function getMaxListeners(){return _getMaxListeners(this)},EventEmitter.prototype.emit=function emit(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var a=e===`error`,o=this._events;if(o!==void 0)a=a&&o.error===void 0;else if(!a)return!1;if(a){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var c=Error(`Unhandled error.`+(s?` (`+s.message+`)`:``));throw c.context=s,c}var l=o[e];if(l===void 0)return!1;if(typeof l==`function`)r(l,this,t);else for(var u=l.length,d=arrayClone(l,u),n=0;n<u;++n)r(d[n],this,t);return!0};function _addListener(e,t,n,r){var a,o,s;if(checkListener(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),s=o[t]),s===void 0)s=o[t]=n,++e._eventsCount;else if(typeof s==`function`?s=o[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),a=_getMaxListeners(e),a>0&&s.length>a&&!s.warned){s.warned=!0;var c=Error(`Possible EventEmitter memory leak detected. `+s.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);c.name=`MaxListenersExceededWarning`,c.emitter=e,c.type=t,c.count=s.length,ProcessEmitWarning(c)}return e}EventEmitter.prototype.addListener=function addListener(e,t){return _addListener(this,e,t,!1)},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.prependListener=function prependListener(e,t){return _addListener(this,e,t,!0)};function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},a=onceWrapper.bind(r);return a.listener=n,r.wrapFn=a,a}EventEmitter.prototype.once=function once(e,t){return checkListener(t),this.on(e,_onceWrap(this,e,t)),this},EventEmitter.prototype.prependOnceListener=function prependOnceListener(e,t){return checkListener(t),this.prependListener(e,_onceWrap(this,e,t)),this},EventEmitter.prototype.removeListener=function removeListener(e,t){var n,r,a,o,s;if(checkListener(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(a=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){s=n[o].listener,a=o;break}if(a<0)return this;a===0?n.shift():spliceOne(n,a),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,s||t)}return this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.removeAllListeners=function removeAllListeners(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var a=Object.keys(n),o;for(r=0;r<a.length;++r)o=a[r],o!==`removeListener`&&this.removeAllListeners(o);return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function _listeners(e,t,n){var r=e._events;if(r===void 0)return[];var a=r[t];return a===void 0?[]:typeof a==`function`?n?[a.listener||a]:[a]:n?unwrapListeners(a):arrayClone(a,a.length)}EventEmitter.prototype.listeners=function listeners(e){return _listeners(this,e,!0)},EventEmitter.prototype.rawListeners=function rawListeners(e){return _listeners(this,e,!1)},EventEmitter.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):listenerCount.call(e,t)},EventEmitter.prototype.listenerCount=listenerCount;function listenerCount(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?a(this._events):[]};function arrayClone(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function spliceOne(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function unwrapListeners(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function once(e,t){return new Promise(function(n,r){function errorListener(n){e.removeListener(t,resolver),r(n)}function resolver(){typeof e.removeListener==`function`&&e.removeListener(`error`,errorListener),n([].slice.call(arguments))}eventTargetAgnosticAddListener(e,t,resolver,{once:!0}),t!==`error`&&addErrorHandlerIfEventEmitter(e,errorListener,{once:!0})})}function addErrorHandlerIfEventEmitter(e,t,n){typeof e.on==`function`&&eventTargetAgnosticAddListener(e,`error`,t,n)}function eventTargetAgnosticAddListener(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function wrapListener(a){r.once&&e.removeEventListener(t,wrapListener),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}})),import_spark_md5=__toESM(require_spark_md5()),import_vuvuzela=__toESM(require_vuvuzela()),import_events=__toESM(require_events());function isBinaryObject$1(e){return typeof ArrayBuffer<`u`&&e instanceof ArrayBuffer||typeof Blob<`u`&&e instanceof Blob}__name(isBinaryObject$1,`isBinaryObject`);function cloneBinaryObject$1(e){return e instanceof ArrayBuffer?e.slice(0):e.slice(0,e.size,e.type)}__name(cloneBinaryObject$1,`cloneBinaryObject`);var funcToString$1=Function.prototype.toString,objectCtorString$1=funcToString$1.call(Object);function isPlainObject$1(e){var t=Object.getPrototypeOf(e);if(t===null)return!0;var n=t.constructor;return typeof n==`function`&&n instanceof n&&funcToString$1.call(n)==objectCtorString$1}__name(isPlainObject$1,`isPlainObject`);function clone$1(e){var t,n,r;if(!e||typeof e!=`object`)return e;if(Array.isArray(e)){for(t=[],n=0,r=e.length;n<r;n++)t[n]=clone$1(e[n]);return t}if(e instanceof Date&&isFinite(e))return e.toISOString();if(isBinaryObject$1(e))return cloneBinaryObject$1(e);if(!isPlainObject$1(e))return e;for(n in t={},e)if(Object.prototype.hasOwnProperty.call(e,n)){var a=clone$1(e[n]);a!==void 0&&(t[n]=a)}return t}__name(clone$1,`clone`);function once(e){var t=!1;return function(...n){if(t)throw Error(`once called more than once`);t=!0,e.apply(this,n)}}function toPromise(e){return function(...t){t=clone$1(t);var n=this,r=typeof t[t.length-1]==`function`?t.pop():!1,a=new Promise(function(r,a){var o;try{var s=once(function(e,t){e?a(e):r(t)});t.push(s),o=e.apply(n,t),o&&typeof o.then==`function`&&r(o)}catch(e){a(e)}});return r&&a.then(function(e){r(null,e)},r),a}}function logApiCall(e,t,n){if(e.constructor.listeners(`debug`).length){for(var r=[`api`,e.name,t],a=0;a<n.length-1;a++)r.push(n[a]);e.constructor.emit(`debug`,r);var o=n[n.length-1];n[n.length-1]=function(n,r){var a=[`api`,e.name,t];a=a.concat(n?[`error`,n]:[`success`,r]),e.constructor.emit(`debug`,a),o(n,r)}}}function adapterFun(e,t){return toPromise(function(...n){if(this._closed)return Promise.reject(Error(`database is closed`));if(this._destroyed)return Promise.reject(Error(`database is destroyed`));var r=this;return logApiCall(r,e,n),this.taskqueue.isReady?t.apply(this,n):new Promise(function(t,a){r.taskqueue.addTask(function(o){o?a(o):t(r[e].apply(r,n))})})})}function pick$1(e,t){for(var n={},r=0,a=t.length;r<a;r++){var o=t[r];o in e&&(n[o]=e[o])}return n}__name(pick$1,`pick`);var MAX_NUM_CONCURRENT_REQUESTS=6;function identityFunction(e){return e}function formatResultForOpenRevsGet(e){return[{ok:e}]}function bulkGet(e,t,n){var r=t.docs,a=new Map;r.forEach(function(e){a.has(e.id)?a.get(e.id).push(e):a.set(e.id,[e])});var o=a.size,s=0,c=Array(o);function collapseResultsAndFinish(){var e=[];c.forEach(function(t){t.docs.forEach(function(n){e.push({id:t.id,docs:[n]})})}),n(null,{results:e})}function checkDone(){++s===o&&collapseResultsAndFinish()}function gotResult(e,t,n){c[e]={id:t,docs:n},checkDone()}var l=[];a.forEach(function(e,t){l.push(t)});var u=0;function nextBatch(){if(!(u>=l.length)){var e=Math.min(u+MAX_NUM_CONCURRENT_REQUESTS,l.length),t=l.slice(u,e);processBatch(t,u),u+=t.length}}function processBatch(n,r){n.forEach(function(n,o){var s=r+o,c=a.get(n),l=pick$1(c[0],[`atts_since`,`attachments`]);l.open_revs=c.map(function(e){return e.rev}),l.open_revs=l.open_revs.filter(identityFunction);var u=identityFunction;l.open_revs.length===0&&(delete l.open_revs,u=formatResultForOpenRevsGet),[`revs`,`attachments`,`binary`,`ajax`,`latest`].forEach(function(e){e in t&&(l[e]=t[e])}),e.get(n,l,function(e,t){gotResult(s,n,e?[{error:e}]:u(t)),nextBatch()})})}nextBatch()}var hasLocal$1;try{localStorage.setItem(`_pouch_check_localstorage`,1),hasLocal$1=!!localStorage.getItem(`_pouch_check_localstorage`)}catch{hasLocal$1=!1}function hasLocalStorage(){return hasLocal$1}var nextTick$1=typeof queueMicrotask==`function`?queueMicrotask:function nextTick(e){Promise.resolve().then(e)},Changes=class extends import_events.default{constructor(){super(),this._listeners={},hasLocalStorage()&&addEventListener(`storage`,e=>{this.emit(e.key)})}addListener(e,t,n,r){if(this._listeners[t])return;var a=!1,o=this;function eventFunction(){if(!o._listeners[t])return;if(a){a=`waiting`;return}a=!0;var e=pick$1(r,[`style`,`include_docs`,`attachments`,`conflicts`,`filter`,`doc_ids`,`view`,`since`,`query_params`,`binary`,`return_docs`]);function onError(){a=!1}n.changes(e).on(`change`,function(e){e.seq>r.since&&!r.cancelled&&(r.since=e.seq,r.onChange(e))}).on(`complete`,function(){a===`waiting`&&nextTick$1(eventFunction),a=!1}).on(`error`,onError)}this._listeners[t]=eventFunction,this.on(e,eventFunction)}removeListener(e,t){t in this._listeners&&(super.removeListener(e,this._listeners[t]),delete this._listeners[t])}notifyLocalWindows(e){hasLocalStorage()&&(localStorage[e]=localStorage[e]===`a`?`b`:`a`)}notify(e){this.emit(e),this.notifyLocalWindows(e)}};function guardedConsole$1(e){if(typeof console<`u`&&typeof console[e]==`function`){var t=Array.prototype.slice.call(arguments,1);console[e].apply(console,t)}}__name(guardedConsole$1,`guardedConsole`);function randomNumber(e,t){var n=6e5;e=parseInt(e,10)||0,t=parseInt(t,10),t!==t||t<=e?t=(e||1)<<1:t+=1,t>n&&(e=n>>1,t=n);var r=Math.random();return~~((t-e)*r+e)}function defaultBackOff(e){var t=0;return e||(t=2e3),randomNumber(e,t)}function explainError(e,t){guardedConsole$1(`info`,`The above `+e+` is totally normal. `+t)}var PouchError$1=class extends Error{static{__name(this,`PouchError`)}constructor(e,t,n){super(),this.status=e,this.name=t,this.message=n,this.error=!0}toString(){return JSON.stringify({status:this.status,name:this.name,message:this.message,reason:this.reason})}};new PouchError$1(401,`unauthorized`,`Name or password is incorrect.`);var MISSING_BULK_DOCS$1=new PouchError$1(400,`bad_request`,`Missing JSON list of 'docs'`),MISSING_DOC$1=new PouchError$1(404,`not_found`,`missing`),REV_CONFLICT$1=new PouchError$1(409,`conflict`,`Document update conflict`),INVALID_ID$1=new PouchError$1(400,`bad_request`,`_id field must contain a string`),MISSING_ID$1=new PouchError$1(412,`missing_id`,`_id is required for puts`),RESERVED_ID$1=new PouchError$1(400,`bad_request`,`Only reserved document ids may start with underscore.`);new PouchError$1(412,`precondition_failed`,`Database not open`);var UNKNOWN_ERROR$1=new PouchError$1(500,`unknown_error`,`Database encountered an unknown error`),BAD_ARG$1=new PouchError$1(500,`badarg`,`Some query argument is invalid`);new PouchError$1(400,`invalid_request`,`Request was invalid`);var QUERY_PARSE_ERROR$1=new PouchError$1(400,`query_parse_error`,`Some query parameter is invalid`),DOC_VALIDATION$1=new PouchError$1(500,`doc_validation`,`Bad special document member`),BAD_REQUEST$1=new PouchError$1(400,`bad_request`,`Something wrong with the request`),NOT_AN_OBJECT$1=new PouchError$1(400,`bad_request`,`Document must be a JSON object`);new PouchError$1(404,`not_found`,`Database not found`);var IDB_ERROR$1=new PouchError$1(500,`indexed_db_went_bad`,`unknown`);new PouchError$1(500,`web_sql_went_bad`,`unknown`),new PouchError$1(500,`levelDB_went_went_bad`,`unknown`),new PouchError$1(403,`forbidden`,`Forbidden by design doc validate_doc_update function`);var INVALID_REV$1=new PouchError$1(400,`bad_request`,`Invalid rev format`);new PouchError$1(412,`file_exists`,`The database could not be created, the file already exists.`);var MISSING_STUB$1=new PouchError$1(412,`missing_stub`,`A pre-existing attachment stub wasn't found`);new PouchError$1(413,`invalid_url`,`Provided URL is invalid`);function createError$1(e,t){function CustomPouchError(t){for(var n=Object.getOwnPropertyNames(e),r=0,a=n.length;r<a;r++)typeof e[n[r]]!=`function`&&(this[n[r]]=e[n[r]]);this.stack===void 0&&(this.stack=Error().stack),t!==void 0&&(this.reason=t)}return CustomPouchError.prototype=PouchError$1.prototype,new CustomPouchError(t)}__name(createError$1,`createError`);function generateErrorFromResponse$1(e){if(typeof e!=`object`){var t=e;e=UNKNOWN_ERROR$1,e.data=t}return`error`in e&&e.error===`conflict`&&(e.name=`conflict`,e.status=409),`name`in e||(e.name=e.error||`unknown`),`status`in e||(e.status=500),`message`in e||(e.message=e.message||e.reason),`stack`in e||(e.stack=Error().stack),e}__name(generateErrorFromResponse$1,`generateErrorFromResponse`);function tryFilter(e,t,n){try{return!e(t,n)}catch(e){return createError$1(BAD_REQUEST$1,`Filter function threw: `+e.toString())}}function filterChange(e){var t={},n=e.filter&&typeof e.filter==`function`;return t.query=e.query_params,function filter(r){r.doc||(r.doc={});var a=n&&tryFilter(e.filter,r.doc,t);if(typeof a==`object`)return a;if(a)return!1;if(!e.include_docs)delete r.doc;else if(!e.attachments)for(var o in r.doc._attachments)Object.prototype.hasOwnProperty.call(r.doc._attachments,o)&&(r.doc._attachments[o].stub=!0);return!0}}function invalidIdError(e){var t;if(e?typeof e==`string`?/^_/.test(e)&&!/^_(design|local)/.test(e)&&(t=createError$1(RESERVED_ID$1)):t=createError$1(INVALID_ID$1):t=createError$1(MISSING_ID$1),t)throw t}function isRemote$1(e){return typeof e._remote==`boolean`?e._remote:typeof e.type==`function`?(guardedConsole$1(`warn`,`db.type() is deprecated and will be removed in a future version of PouchDB`),e.type()===`http`):!1}__name(isRemote$1,`isRemote`);function listenerCount(e,t){return`listenerCount`in e?e.listenerCount(t):import_events.default.listenerCount(e,t)}function parseDesignDocFunctionName(e){if(!e)return null;var t=e.split(`/`);return t.length===2?t:t.length===1?[e,e]:null}function normalizeDesignDocFunctionName(e){var t=parseDesignDocFunctionName(e);return t?t.join(`/`):null}var keys=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`],qName=`queryKey`,qParser=/(?:^|&)([^&=]*)=?([^&]*)/g,parser=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;function parseUri(e){for(var t=parser.exec(e),n={},r=14;r--;){var a=keys[r],o=t[r]||``;n[a]=[`user`,`password`].indexOf(a)===-1?o:decodeURIComponent(o)}return n[qName]={},n[keys[12]].replace(qParser,function(e,t,r){t&&(n[qName][t]=r)}),n}function scopeEval(e,t){var n=[],r=[];for(var a in t)Object.prototype.hasOwnProperty.call(t,a)&&(n.push(a),r.push(t[a]));return n.push(e),Function.apply(null,n).apply(null,r)}function upsert$1(e,t,n){return e.get(t).catch(function(e){if(e.status!==404)throw e;return{}}).then(function(r){var a=r._rev,o=n(r);return o?(o._id=t,o._rev=a,tryAndPut$1(e,o,n)):{updated:!1,rev:a}})}__name(upsert$1,`upsert`);function tryAndPut$1(e,t,n){return e.put(t).then(function(e){return{updated:!0,rev:e.rev}},function(r){if(r.status!==409)throw r;return upsert$1(e,t._id,n)})}__name(tryAndPut$1,`tryAndPut`);var thisAtob$1=__name(function(e){return atob(e)},`thisAtob`),thisBtoa=function(e){return btoa(e)};function createBlob$1(e,t){e=e||[],t=t||{};try{return new Blob(e,t)}catch(a){if(a.name!==`TypeError`)throw a;for(var n=new(typeof BlobBuilder<`u`?BlobBuilder:typeof MSBlobBuilder<`u`?MSBlobBuilder:typeof MozBlobBuilder<`u`?MozBlobBuilder:WebKitBlobBuilder),r=0;r<e.length;r+=1)n.append(e[r]);return n.getBlob(t.type)}}__name(createBlob$1,`createBlob`);function binaryStringToArrayBuffer$1(e){for(var t=e.length,n=new ArrayBuffer(t),r=new Uint8Array(n),a=0;a<t;a++)r[a]=e.charCodeAt(a);return n}__name(binaryStringToArrayBuffer$1,`binaryStringToArrayBuffer`);function binStringToBluffer$1(e,t){return createBlob$1([binaryStringToArrayBuffer$1(e)],{type:t})}__name(binStringToBluffer$1,`binStringToBluffer`);function b64ToBluffer$1(e,t){return binStringToBluffer$1(thisAtob$1(e),t)}__name(b64ToBluffer$1,`b64ToBluffer`);function arrayBufferToBinaryString(e){for(var t=``,n=new Uint8Array(e),r=n.byteLength,a=0;a<r;a++)t+=String.fromCharCode(n[a]);return t}function readAsBinaryString(e,t){var n=new FileReader,r=typeof n.readAsBinaryString==`function`;n.onloadend=function(e){var n=e.target.result||``;if(r)return t(n);t(arrayBufferToBinaryString(n))},r?n.readAsBinaryString(e):n.readAsArrayBuffer(e)}function blobToBinaryString(e,t){readAsBinaryString(e,function(e){t(e)})}function blobToBase64(e,t){blobToBinaryString(e,function(e){t(thisBtoa(e))})}function readAsArrayBuffer(e,t){var n=new FileReader;n.onloadend=function(e){t(e.target.result||new ArrayBuffer(0))},n.readAsArrayBuffer(e)}var setImmediateShim$1=self.setImmediate||self.setTimeout,MD5_CHUNK_SIZE=32768;function rawToBase64(e){return thisBtoa(e)}function appendBlob(e,t,n,r,a){(n>0||r<t.size)&&(t=t.slice(n,r)),readAsArrayBuffer(t,function(t){e.append(t),a()})}function appendString(e,t,n,r,a){(n>0||r<t.length)&&(t=t.substring(n,r)),e.appendBinary(t),a()}function binaryMd5(e,t){var n=typeof e==`string`,r=n?e.length:e.size,a=Math.min(MD5_CHUNK_SIZE,r),o=Math.ceil(r/a),s=0,c=n?new import_spark_md5.default:new import_spark_md5.default.ArrayBuffer,l=n?appendString:appendBlob;function next(){setImmediateShim$1(loadNextChunk)}function done(){t(rawToBase64(c.end(!0))),c.destroy()}function loadNextChunk(){var t=s*a,n=t+a;s++,s<o?l(c,e,t,n,next):l(c,e,t,n,done)}loadNextChunk()}function stringMd5$1(e){return import_spark_md5.default.hash(e)}__name(stringMd5$1,`stringMd5`);function rev(e,t){if(!t)return v4$1().replace(/-/g,``).toLowerCase();var n=Object.assign({},e);return delete n._rev_tree,stringMd5$1(JSON.stringify(n))}var uuid=v4$1;function winningRev(e){for(var t,n,r,a=e.rev_tree.slice(),o;o=a.pop();){var s=o.ids,c=s[2],l=o.pos;if(c.length){for(var u=0,d=c.length;u<d;u++)a.push({pos:l+1,ids:c[u]});continue}var p=!!s[1].deleted,m=s[0];(!t||(r===p?n===l?t<m:n<l:r))&&(t=m,n=l,r=p)}return n+`-`+t}function traverseRevTree(e,t){for(var n=e.slice(),r;r=n.pop();)for(var a=r.pos,o=r.ids,s=o[2],c=t(s.length===0,a,o[0],r.ctx,o[1]),l=0,u=s.length;l<u;l++)n.push({pos:a+1,ids:s[l],ctx:c})}function sortByPos(e,t){return e.pos-t.pos}function collectLeaves(e){var t=[];traverseRevTree(e,function(e,n,r,a,o){e&&t.push({rev:n+`-`+r,pos:n,opts:o})}),t.sort(sortByPos).reverse();for(var n=0,r=t.length;n<r;n++)delete t[n].pos;return t}function collectConflicts(e){for(var t=winningRev(e),n=collectLeaves(e.rev_tree),r=[],a=0,o=n.length;a<o;a++){var s=n[a];s.rev!==t&&!s.opts.deleted&&r.push(s.rev)}return r}function compactTree(e){var t=[];return traverseRevTree(e.rev_tree,function(e,n,r,a,o){o.status===`available`&&!e&&(t.push(n+`-`+r),o.status=`missing`)}),t}function findPathToLeaf(e,t){let n=[],r=e.slice(),a;for(;a=r.pop();){let{pos:e,ids:o}=a,s=`${e}-${o[0]}`,c=o[2];if(n.push(s),s===t){if(c.length!==0)throw Error(`The requested revision is not a leaf`);return n.reverse()}(c.length===0||c.length>1)&&(n=[]);for(let t=0,n=c.length;t<n;t++)r.push({pos:e+1,ids:c[t]})}if(n.length===0)throw Error(`The requested revision does not exist`);return n.reverse()}function rootToLeaf(e){for(var t=[],n=e.slice(),r;r=n.pop();){var a=r.pos,o=r.ids,s=o[0],c=o[1],l=o[2],u=l.length===0,d=r.history?r.history.slice():[];d.push({id:s,opts:c}),u&&t.push({pos:a+1-d.length,ids:d});for(var p=0,m=l.length;p<m;p++)n.push({pos:a+1,ids:l[p],history:d})}return t.reverse()}function sortByPos$1(e,t){return e.pos-t.pos}function binarySearch(e,t,n){for(var r=0,a=e.length,o;r<a;)o=r+a>>>1,n(e[o],t)<0?r=o+1:a=o;return r}function insertSorted(e,t,n){var r=binarySearch(e,t,n);e.splice(r,0,t)}function pathToTree(e,t){for(var n,r,a=t,o=e.length;a<o;a++){var s=e[a],c=[s.id,s.opts,[]];r?(r[2].push(c),r=c):n=r=c}return n}function compareTree(e,t){return e[0]<t[0]?-1:1}function mergeTree(e,t){for(var n=[{tree1:e,tree2:t}],r=!1;n.length>0;){var a=n.pop(),o=a.tree1,s=a.tree2;(o[1].status||s[1].status)&&(o[1].status=o[1].status===`available`||s[1].status===`available`?`available`:`missing`);for(var c=0;c<s[2].length;c++){if(!o[2][0]){r=`new_leaf`,o[2][0]=s[2][c];continue}for(var l=!1,u=0;u<o[2].length;u++)o[2][u][0]===s[2][c][0]&&(n.push({tree1:o[2][u],tree2:s[2][c]}),l=!0);l||(r=`new_branch`,insertSorted(o[2],s[2][c],compareTree))}}return{conflicts:r,tree:e}}function doMerge(e,t,n){var r=[],a=!1,o=!1,s;if(!e.length)return{tree:[t],conflicts:`new_leaf`};for(var c=0,l=e.length;c<l;c++){var u=e[c];if(u.pos===t.pos&&u.ids[0]===t.ids[0])s=mergeTree(u.ids,t.ids),r.push({pos:u.pos,ids:s.tree}),a=a||s.conflicts,o=!0;else if(n!==!0){var d=u.pos<t.pos?u:t,p=u.pos<t.pos?t:u,m=p.pos-d.pos,g=[],_=[];for(_.push({ids:d.ids,diff:m,parent:null,parentIdx:null});_.length>0;){var v=_.pop();if(v.diff===0){v.ids[0]===p.ids[0]&&g.push(v);continue}for(var y=v.ids[2],b=0,x=y.length;b<x;b++)_.push({ids:y[b],diff:v.diff-1,parent:v.ids,parentIdx:b})}var S=g[0];S?(s=mergeTree(S.ids,p.ids),S.parent[2][S.parentIdx]=s.tree,r.push({pos:d.pos,ids:d.ids}),a=a||s.conflicts,o=!0):r.push(u)}else r.push(u)}return o||r.push(t),r.sort(sortByPos$1),{tree:r,conflicts:a||`internal_node`}}function stem(e,t){for(var n=rootToLeaf(e),r,a,o=0,s=n.length;o<s;o++){var c=n[o],l=c.ids,u;if(l.length>t){r||(r={});var d=l.length-t;u={pos:c.pos+d,ids:pathToTree(l,d)};for(var p=0;p<d;p++){var m=c.pos+p+`-`+l[p].id;r[m]=!0}}else u={pos:c.pos,ids:pathToTree(l,0)};a=a?doMerge(a,u,!0).tree:[u]}return r&&traverseRevTree(a,function(e,t,n){delete r[t+`-`+n]}),{tree:a,revs:r?Object.keys(r):[]}}function merge(e,t,n){var r=doMerge(e,t),a=stem(r.tree,n);return{tree:a.tree,stemmedRevs:a.revs,conflicts:r.conflicts}}function revExists(e,t){for(var n=e.slice(),r=t.split(`-`),a=parseInt(r[0],10),o=r[1],s;s=n.pop();){if(s.pos===a&&s.ids[0]===o)return!0;for(var c=s.ids[2],l=0,u=c.length;l<u;l++)n.push({pos:s.pos+1,ids:c[l]})}return!1}function getTrees(e){return e.ids}function isDeleted(e,t){t||(t=winningRev(e));for(var n=t.substring(t.indexOf(`-`)+1),r=e.rev_tree.map(getTrees),a;a=r.pop();){if(a[0]===n)return!!a[1].deleted;r=r.concat(a[2])}}function isLocalId(e){return typeof e==`string`&&e.startsWith(`_local/`)}function latest(e,t){for(var n=t.rev_tree.slice(),r;r=n.pop();){var a=r.pos,o=r.ids,s=o[0],c=o[1],l=o[2],u=l.length===0,d=r.history?r.history.slice():[];if(d.push({id:s,pos:a,opts:c}),u)for(var p=0,m=d.length;p<m;p++){var g=d[p];if(g.pos+`-`+g.id===e)return a+`-`+s}for(var _=0,v=l.length;_<v;_++)n.push({pos:a+1,ids:l[_],history:d})}throw Error(`Unable to resolve latest revision for id `+t.id+`, rev `+e)}function tryCatchInChangeListener(e,t,n,r){try{e.emit(`change`,t,n,r)}catch(e){guardedConsole$1(`error`,`Error in .on("change", function):`,e)}}function processChange(e,t,n){var r=[{rev:e._rev}];n.style===`all_docs`&&(r=collectLeaves(t.rev_tree).map(function(e){return{rev:e.rev}}));var a={id:t.id,changes:r,doc:e};return isDeleted(t,e._rev)&&(a.deleted=!0),n.conflicts&&(a.doc._conflicts=collectConflicts(t),a.doc._conflicts.length||delete a.doc._conflicts),a}var Changes$1=class extends import_events.default{constructor(e,t,n){super(),this.db=e,t=t?clone$1(t):{};var r=t.complete=once((t,n)=>{t?listenerCount(this,`error`)>0&&this.emit(`error`,t):this.emit(`complete`,n),this.removeAllListeners(),e.removeListener(`destroyed`,onDestroy)});n&&(this.on(`complete`,function(e){n(null,e)}),this.on(`error`,n));let onDestroy=()=>{this.cancel()};e.once(`destroyed`,onDestroy),t.onChange=(e,t,n)=>{this.isCancelled||tryCatchInChangeListener(this,e,t,n)};var a=new Promise(function(e,n){t.complete=function(t,r){t?n(t):e(r)}});this.once(`cancel`,function(){e.removeListener(`destroyed`,onDestroy),t.complete(null,{status:`cancelled`})}),this.then=a.then.bind(a),this.catch=a.catch.bind(a),this.then(function(e){r(null,e)},r),e.taskqueue.isReady?this.validateChanges(t):e.taskqueue.addTask(e=>{e?t.complete(e):this.isCancelled?this.emit(`cancel`):this.validateChanges(t)})}cancel(){this.isCancelled=!0,this.db.taskqueue.isReady&&this.emit(`cancel`)}validateChanges(e){var t=e.complete;PouchDB._changesFilterPlugin?PouchDB._changesFilterPlugin.validate(e,n=>{if(n)return t(n);this.doChanges(e)}):this.doChanges(e)}doChanges(e){var t=e.complete;if(e=clone$1(e),`live`in e&&!(`continuous`in e)&&(e.continuous=e.live),e.processChange=processChange,e.since===`latest`&&(e.since=`now`),e.since||(e.since=0),e.since===`now`){this.db.info().then(n=>{if(this.isCancelled){t(null,{status:`cancelled`});return}e.since=n.update_seq,this.doChanges(e)},t);return}if(PouchDB._changesFilterPlugin){if(PouchDB._changesFilterPlugin.normalize(e),PouchDB._changesFilterPlugin.shouldFilter(this,e))return PouchDB._changesFilterPlugin.filter(this,e)}else [`doc_ids`,`filter`,`selector`,`view`].forEach(function(t){t in e&&guardedConsole$1(`warn`,`The "`+t+`" option was passed in to changes/replicate, but pouchdb-changes-filter plugin is not installed, so it was ignored. Please install the plugin to enable filtering.`)});`descending`in e||(e.descending=!1),e.limit=e.limit===0?1:e.limit,e.complete=t;var n=this.db._changes(e);if(n&&typeof n.cancel==`function`){let e=this.cancel;this.cancel=(...t)=>{n.cancel(),e.apply(this,t)}}}};function yankError(e,t){return function(n,r){n||r[0]&&r[0].error?(n=n||r[0],n.docId=t,e(n)):e(null,r.length?r[0]:r)}}function cleanDocs(e){for(var t=0;t<e.length;t++){var n=e[t];if(n._deleted)delete n._attachments;else if(n._attachments)for(var r=Object.keys(n._attachments),a=0;a<r.length;a++){var o=r[a];n._attachments[o]=pick$1(n._attachments[o],[`data`,`digest`,`content_type`,`length`,`revpos`,`stub`])}}}function compareByIdThenRev(e,t){return e._id===t._id?(e._revisions?e._revisions.start:0)-(t._revisions?t._revisions.start:0):e._id<t._id?-1:1}function computeHeight(e){var t={},n=[];return traverseRevTree(e,function(e,r,a,o){var s=r+`-`+a;return e&&(t[s]=0),o!==void 0&&n.push({from:o,to:s}),s}),n.reverse(),n.forEach(function(e){t[e.from]===void 0?t[e.from]=1+t[e.to]:t[e.from]=Math.min(t[e.from],1+t[e.to])}),t}function allDocsKeysParse(e){var t=`limit`in e?e.keys.slice(e.skip,e.limit+e.skip):e.skip>0?e.keys.slice(e.skip):e.keys;e.keys=t,e.skip=0,delete e.limit,e.descending&&(t.reverse(),e.descending=!1)}function doNextCompaction(e){var t=e._compactionQueue[0],n=t.opts,r=t.callback;e.get(`_local/compaction`).catch(function(){return!1}).then(function(t){t&&t.last_seq&&(n.last_seq=t.last_seq),e._compact(n,function(t,n){t?r(t):r(null,n),nextTick$1(function(){e._compactionQueue.shift(),e._compactionQueue.length&&doNextCompaction(e)})})})}function appendPurgeSeq(e,t,n){return e.get(`_local/purges`).then(function(e){let r=e.purgeSeq+1;return e.purges.push({docId:t,rev:n,purgeSeq:r}),e.purges.length>self.purged_infos_limit&&e.purges.splice(0,e.purges.length-self.purged_infos_limit),e.purgeSeq=r,e}).catch(function(e){if(e.status!==404)throw e;return{_id:`_local/purges`,purges:[{docId:t,rev:n,purgeSeq:0}],purgeSeq:0}}).then(function(t){return e.put(t)})}function attachmentNameError(e){return e.charAt(0)===`_`?e+` is not a valid attachment name, attachment names cannot start with '_'`:!1}function isNotSingleDoc(e){return typeof e!=`object`||!e||Array.isArray(e)}var validRevRegex=/^\d+-[^-]*$/;function isValidRev(e){return typeof e==`string`&&validRevRegex.test(e)}var AbstractPouchDB=class extends import_events.default{_setup(){this.post=adapterFun(`post`,function(e,t,n){if(typeof t==`function`&&(n=t,t={}),isNotSingleDoc(e))return n(createError$1(NOT_AN_OBJECT$1));this.bulkDocs({docs:[e]},t,yankError(n,e._id))}).bind(this),this.put=adapterFun(`put`,function(e,t,n){if(typeof t==`function`&&(n=t,t={}),isNotSingleDoc(e))return n(createError$1(NOT_AN_OBJECT$1));if(invalidIdError(e._id),`_rev`in e&&!isValidRev(e._rev))return n(createError$1(INVALID_REV$1));if(isLocalId(e._id)&&typeof this._putLocal==`function`)return e._deleted?this._removeLocal(e,n):this._putLocal(e,n);let putDoc=n=>{typeof this._put==`function`&&t.new_edits!==!1?this._put(e,t,n):this.bulkDocs({docs:[e]},t,yankError(n,e._id))};t.force&&e._rev?(transformForceOptionToNewEditsOption(),putDoc(function(t){var r=t?null:{ok:!0,id:e._id,rev:e._rev};n(t,r)})):putDoc(n);function transformForceOptionToNewEditsOption(){var n=e._rev.split(`-`),r=n[1],a=parseInt(n[0],10)+1,o=rev();e._revisions={start:a,ids:[o,r]},e._rev=a+`-`+o,t.new_edits=!1}}).bind(this),this.putAttachment=adapterFun(`putAttachment`,function(e,t,n,r,a){var o=this;typeof a==`function`&&(a=r,r=n,n=null),a===void 0&&(a=r,r=n,n=null),a||guardedConsole$1(`warn`,`Attachment`,t,`on document`,e,`is missing content_type`);function createAttachment(e){var n=`_rev`in e?parseInt(e._rev,10):0;return e._attachments=e._attachments||{},e._attachments[t]={content_type:a,data:r,revpos:++n},o.put(e)}return o.get(e).then(function(e){if(e._rev!==n)throw createError$1(REV_CONFLICT$1);return createAttachment(e)},function(t){if(t.reason===MISSING_DOC$1.message)return createAttachment({_id:e});throw t})}).bind(this),this.removeAttachment=adapterFun(`removeAttachment`,function(e,t,n,r){this.get(e,(e,a)=>{if(e){r(e);return}if(a._rev!==n){r(createError$1(REV_CONFLICT$1));return}if(!a._attachments)return r();delete a._attachments[t],Object.keys(a._attachments).length===0&&delete a._attachments,this.put(a,r)})}).bind(this),this.remove=adapterFun(`remove`,function(e,t,n,r){var a;typeof t==`string`?(a={_id:e,_rev:t},typeof n==`function`&&(r=n,n={})):(a=e,typeof t==`function`?(r=t,n={}):(r=n,n=t)),n=n||{},n.was_delete=!0;var o={_id:a._id,_rev:a._rev||n.rev};if(o._deleted=!0,isLocalId(o._id)&&typeof this._removeLocal==`function`)return this._removeLocal(a,r);this.bulkDocs({docs:[o]},n,yankError(r,o._id))}).bind(this),this.revsDiff=adapterFun(`revsDiff`,function(e,t,n){typeof t==`function`&&(n=t,t={});var r=Object.keys(e);if(!r.length)return n(null,{});var a=0,o=new Map;function addToMissing(e,t){o.has(e)||o.set(e,{missing:[]}),o.get(e).missing.push(t)}function processDoc(t,n){var r=e[t].slice(0);traverseRevTree(n,function(e,n,a,o,s){var c=n+`-`+a,l=r.indexOf(c);l!==-1&&(r.splice(l,1),s.status!==`available`&&addToMissing(t,c))}),r.forEach(function(e){addToMissing(t,e)})}r.forEach(function(t){this._getRevisionTree(t,function(s,c){if(s&&s.status===404&&s.message===`missing`)o.set(t,{missing:e[t]});else if(s)return n(s);else processDoc(t,c);if(++a===r.length){var l={};return o.forEach(function(e,t){l[t]=e}),n(null,l)}})},this)}).bind(this),this.bulkGet=adapterFun(`bulkGet`,function(e,t){bulkGet(this,e,t)}).bind(this),this.compactDocument=adapterFun(`compactDocument`,function(e,t,n){this._getRevisionTree(e,(r,a)=>{if(r)return n(r);var o=computeHeight(a),s=[],c=[];Object.keys(o).forEach(function(e){o[e]>t&&s.push(e)}),traverseRevTree(a,function(e,t,n,r,a){var o=t+`-`+n;a.status===`available`&&s.indexOf(o)!==-1&&c.push(o)}),this._doCompaction(e,c,n)})}).bind(this),this.compact=adapterFun(`compact`,function(e,t){typeof e==`function`&&(t=e,e={}),e=e||{},this._compactionQueue=this._compactionQueue||[],this._compactionQueue.push({opts:e,callback:t}),this._compactionQueue.length===1&&doNextCompaction(this)}).bind(this),this.get=adapterFun(`get`,function(e,t,n){if(typeof t==`function`&&(n=t,t={}),t=t||{},typeof e!=`string`)return n(createError$1(INVALID_ID$1));if(isLocalId(e)&&typeof this._getLocal==`function`)return this._getLocal(e,n);var r=[];let finishOpenRevs=()=>{var a=[],o=r.length;if(!o)return n(null,a);r.forEach(r=>{this.get(e,{rev:r,revs:t.revs,latest:t.latest,attachments:t.attachments,binary:t.binary},function(e,t){if(e)a.push({missing:r});else{for(var s,c=0,l=a.length;c<l;c++)if(a[c].ok&&a[c].ok._rev===t._rev){s=!0;break}s||a.push({ok:t})}o--,o||n(null,a)})})};if(t.open_revs){if(t.open_revs===`all`)this._getRevisionTree(e,function(e,t){if(e)return n(e);r=collectLeaves(t).map(function(e){return e.rev}),finishOpenRevs()});else if(Array.isArray(t.open_revs)){r=t.open_revs;for(var a=0;a<r.length;a++){var o=r[a];if(!isValidRev(o))return n(createError$1(INVALID_REV$1))}finishOpenRevs()}else return n(createError$1(UNKNOWN_ERROR$1,`function_clause`));return}return this._get(e,t,(r,a)=>{if(r)return r.docId=e,n(r);var o=a.doc,s=a.metadata,c=a.ctx;if(t.conflicts){var l=collectConflicts(s);l.length&&(o._conflicts=l)}if(isDeleted(s,o._rev)&&(o._deleted=!0),t.revs||t.revs_info){for(var u=o._rev.split(`-`),d=parseInt(u[0],10),p=u[1],m=rootToLeaf(s.rev_tree),g=null,_=0;_<m.length;_++){var v=m[_];let e=v.ids.findIndex(e=>e.id===p);(e===d-1||!g&&e!==-1)&&(g=v)}if(!g)return r=Error(`invalid rev tree`),r.docId=e,n(r);let a=o._rev.split(`-`)[1],c=g.ids.findIndex(e=>e.id===a)+1;var y=g.ids.length-c;if(g.ids.splice(c,y),g.ids.reverse(),t.revs&&(o._revisions={start:g.pos+g.ids.length-1,ids:g.ids.map(function(e){return e.id})}),t.revs_info){var b=g.pos+g.ids.length;o._revs_info=g.ids.map(function(e){return b--,{rev:b+`-`+e.id,status:e.opts.status}})}}if(t.attachments&&o._attachments){var x=o._attachments,S=Object.keys(x).length;if(S===0)return n(null,o);Object.keys(x).forEach(e=>{this._getAttachment(o._id,e,x[e],{binary:t.binary,metadata:s,ctx:c},function(t,r){var a=o._attachments[e];a.data=r,delete a.stub,delete a.length,--S||n(null,o)})})}else{if(o._attachments)for(var C in o._attachments)Object.prototype.hasOwnProperty.call(o._attachments,C)&&(o._attachments[C].stub=!0);n(null,o)}})}).bind(this),this.getAttachment=adapterFun(`getAttachment`,function(e,t,n,r){n instanceof Function&&(r=n,n={}),this._get(e,n,(a,o)=>{if(a)return r(a);if(o.doc._attachments&&o.doc._attachments[t])n.ctx=o.ctx,n.binary=!0,n.metadata=o.metadata,this._getAttachment(e,t,o.doc._attachments[t],n,r);else return r(createError$1(MISSING_DOC$1))})}).bind(this),this.allDocs=adapterFun(`allDocs`,function(e,t){if(typeof e==`function`&&(t=e,e={}),e.skip=e.skip===void 0?0:e.skip,e.start_key&&(e.startkey=e.start_key),e.end_key&&(e.endkey=e.end_key),`keys`in e){if(!Array.isArray(e.keys))return t(TypeError(`options.keys must be an array`));var n=[`startkey`,`endkey`,`key`].filter(function(t){return t in e})[0];if(n){t(createError$1(QUERY_PARSE_ERROR$1,"Query parameter `"+n+"` is not compatible with multi-get"));return}if(!isRemote$1(this)&&(allDocsKeysParse(e),e.keys.length===0))return this._allDocs({limit:0},t)}return this._allDocs(e,t)}).bind(this),this.close=adapterFun(`close`,function(e){return this._closed=!0,this.emit(`closed`),this._close(e)}).bind(this),this.info=adapterFun(`info`,function(e){this._info((t,n)=>{if(t)return e(t);n.db_name=n.db_name||this.name,n.auto_compaction=!!(this.auto_compaction&&!isRemote$1(this)),n.adapter=this.adapter,e(null,n)})}).bind(this),this.id=adapterFun(`id`,function(e){return this._id(e)}).bind(this),this.bulkDocs=adapterFun(`bulkDocs`,function(e,t,n){if(typeof t==`function`&&(n=t,t={}),t=t||{},Array.isArray(e)&&(e={docs:e}),!e||!e.docs||!Array.isArray(e.docs))return n(createError$1(MISSING_BULK_DOCS$1));for(var r=0;r<e.docs.length;++r){let t=e.docs[r];if(isNotSingleDoc(t))return n(createError$1(NOT_AN_OBJECT$1));if(`_rev`in t&&!isValidRev(t._rev))return n(createError$1(INVALID_REV$1))}var a;if(e.docs.forEach(function(e){e._attachments&&Object.keys(e._attachments).forEach(function(t){a=a||attachmentNameError(t),e._attachments[t].content_type||guardedConsole$1(`warn`,`Attachment`,t,`on document`,e._id,`is missing content_type`)})}),a)return n(createError$1(BAD_REQUEST$1,a));`new_edits`in t||(`new_edits`in e?t.new_edits=e.new_edits:t.new_edits=!0);var o=this;!t.new_edits&&!isRemote$1(o)&&e.docs.sort(compareByIdThenRev),cleanDocs(e.docs);var s=e.docs.map(function(e){return e._id});this._bulkDocs(e,t,function(e,r){if(e)return n(e);if(t.new_edits||(r=r.filter(function(e){return e.error})),!isRemote$1(o))for(var a=0,c=r.length;a<c;a++)r[a].id=r[a].id||s[a];n(null,r)})}).bind(this),this.registerDependentDatabase=adapterFun(`registerDependentDatabase`,function(e,t){var n=clone$1(this.__opts);this.__opts.view_adapter&&(n.adapter=this.__opts.view_adapter);var r=new this.constructor(e,n);function diffFun(t){return t.dependentDbs=t.dependentDbs||{},t.dependentDbs[e]?!1:(t.dependentDbs[e]=!0,t)}upsert$1(this,`_local/_pouch_dependentDbs`,diffFun).then(function(){t(null,{db:r})}).catch(t)}).bind(this),this.destroy=adapterFun(`destroy`,function(e,t){typeof e==`function`&&(t=e,e={});var n=`use_prefix`in this?this.use_prefix:!0;let destroyDb=()=>{this._destroy(e,(e,n)=>{if(e)return t(e);this._destroyed=!0,this.emit(`destroyed`),t(null,n||{ok:!0})})};if(isRemote$1(this))return destroyDb();this.get(`_local/_pouch_dependentDbs`,(e,r)=>{if(e)return e.status===404?destroyDb():t(e);var a=r.dependentDbs,o=this.constructor,s=Object.keys(a).map(e=>new o(n?e.replace(RegExp(`^`+o.prefix),``):e,this.__opts).destroy());Promise.all(s).then(destroyDb,t)})}).bind(this)}_compact(e,t){var n={return_docs:!1,last_seq:e.last_seq||0,since:e.last_seq||0},r=[],a,o=0;let onChange=e=>{this.activeTasks.update(a,{completed_items:++o}),r.push(this.compactDocument(e.id,0))},onError=e=>{this.activeTasks.remove(a,e),t(e)},onComplete=e=>{var n=e.last_seq;Promise.all(r).then(()=>upsert$1(this,`_local/compaction`,e=>!e.last_seq||e.last_seq<n?(e.last_seq=n,e):!1)).then(()=>{this.activeTasks.remove(a),t(null,{ok:!0})}).catch(onError)};this.info().then(e=>{a=this.activeTasks.add({name:`database_compaction`,total_items:e.update_seq-n.last_seq}),this.changes(n).on(`change`,onChange).on(`complete`,onComplete).on(`error`,onError)})}changes(e,t){return typeof e==`function`&&(t=e,e={}),e=e||{},e.return_docs=`return_docs`in e?e.return_docs:!e.live,new Changes$1(this,e,t)}type(){return typeof this._type==`function`?this._type():this.adapter}};AbstractPouchDB.prototype.purge=adapterFun(`_purge`,function(e,t,n){if(this._purge===void 0)return n(createError$1(UNKNOWN_ERROR$1,`Purge is not implemented in the `+this.adapter+` adapter.`));var r=this;r._getRevisionTree(e,(a,o)=>{if(a)return n(a);if(!o)return n(createError$1(MISSING_DOC$1));let s;try{s=findPathToLeaf(o,t)}catch(e){return n(e.message||e)}r._purge(e,s,(a,o)=>{if(a)return n(a);appendPurgeSeq(r,e,t).then(function(){return n(null,o)})})})});var TaskQueue$1=class{static{__name(this,`TaskQueue`)}constructor(){this.isReady=!1,this.failed=!1,this.queue=[]}execute(){var e;if(this.failed)for(;e=this.queue.shift();)e(this.failed);else for(;e=this.queue.shift();)e()}fail(e){this.failed=e,this.execute()}ready(e){this.isReady=!0,this.db=e,this.execute()}addTask(e){this.queue.push(e),this.failed&&this.execute()}};function parseAdapter(e,t){var n=e.match(/([a-z-]*):\/\/(.*)/);if(n)return{name:/https?/.test(n[1])?n[1]+`://`+n[2]:n[2],adapter:n[1]};var r=PouchDB.adapters,a=PouchDB.preferredAdapters,o=PouchDB.prefix,s=t.adapter;if(!s)for(var c=0;c<a.length;++c){if(s=a[c],s===`idb`&&`websql`in r&&hasLocalStorage()&&localStorage[`_pouch__websqldb_`+o+e]){guardedConsole$1(`log`,`PouchDB is downgrading "`+e+`" to WebSQL to avoid data loss, because it was already opened with WebSQL.`);continue}break}var l=r[s];return{name:!(l&&`use_prefix`in l)||l.use_prefix?o+e:e,adapter:s}}function inherits(e,t){e.prototype=Object.create(t.prototype,{constructor:{value:e}})}function createClass(e,t){let klass=function(...e){if(!(this instanceof klass))return new klass(...e);t.apply(this,e)};return inherits(klass,e),klass}function prepareForDestruction(e){function onDestroyed(t){e.removeListener(`closed`,onClosed),t||e.constructor.emit(`destroyed`,e.name)}function onClosed(){e.removeListener(`destroyed`,onDestroyed),e.constructor.emit(`unref`,e)}e.once(`destroyed`,onDestroyed),e.once(`closed`,onClosed),e.constructor.emit(`ref`,e)}var PouchInternal=class extends AbstractPouchDB{constructor(e,t){super(),this._setup(e,t)}_setup(e,t){if(super._setup(),t=t||{},e&&typeof e==`object`&&(t=e,e=t.name,delete t.name),t.deterministic_revs===void 0&&(t.deterministic_revs=!0),this.__opts=t=clone$1(t),this.auto_compaction=t.auto_compaction,this.purged_infos_limit=t.purged_infos_limit||1e3,this.prefix=PouchDB.prefix,typeof e!=`string`)throw Error(`Missing/invalid DB name`);var n=parseAdapter((t.prefix||``)+e,t);if(t.name=n.name,t.adapter=t.adapter||n.adapter,this.name=e,this._adapter=t.adapter,PouchDB.emit(`debug`,[`adapter`,`Picked adapter: `,t.adapter]),!PouchDB.adapters[t.adapter]||!PouchDB.adapters[t.adapter].valid())throw Error(`Invalid Adapter: `+t.adapter);if(t.view_adapter&&(!PouchDB.adapters[t.view_adapter]||!PouchDB.adapters[t.view_adapter].valid()))throw Error(`Invalid View Adapter: `+t.view_adapter);this.taskqueue=new TaskQueue$1,this.adapter=t.adapter,PouchDB.adapters[t.adapter].call(this,t,e=>{if(e)return this.taskqueue.fail(e);prepareForDestruction(this),this.emit(`created`,this),PouchDB.emit(`created`,this.name),this.taskqueue.ready(this)})}},PouchDB=createClass(PouchInternal,function(e,t){PouchInternal.prototype._setup.call(this,e,t)}),f$1=fetch,h$1=Headers,ActiveTasks=class{constructor(){this.tasks={}}list(){return Object.values(this.tasks)}add(e){let t=v4$1();return this.tasks[t]={id:t,name:e.name,total_items:e.total_items,created_at:new Date().toJSON()},t}get(e){return this.tasks[e]}remove(e,t){return delete this.tasks[e],this.tasks}update(e,t){let n=this.tasks[e];if(n!==void 0){let r={id:n.id,name:n.name,created_at:n.created_at,total_items:t.total_items||n.total_items,completed_items:t.completed_items||n.completed_items,updated_at:new Date().toJSON()};this.tasks[e]=r}return this.tasks}};PouchDB.adapters={},PouchDB.preferredAdapters=[],PouchDB.prefix=`_pouch_`;var eventEmitter=new import_events.default;function setUpEventEmitter(e){Object.keys(import_events.default.prototype).forEach(function(t){typeof import_events.default.prototype[t]==`function`&&(e[t]=eventEmitter[t].bind(eventEmitter))});var t=e._destructionListeners=new Map;e.on(`ref`,function onConstructorRef(e){t.has(e.name)||t.set(e.name,[]),t.get(e.name).push(e)}),e.on(`unref`,function onConstructorUnref(e){if(t.has(e.name)){var n=t.get(e.name),r=n.indexOf(e);r<0||(n.splice(r,1),n.length>1?t.set(e.name,n):t.delete(e.name))}}),e.on(`destroyed`,function onConstructorDestroyed(e){if(t.has(e)){var n=t.get(e);t.delete(e),n.forEach(function(e){e.emit(`destroyed`,!0)})}})}setUpEventEmitter(PouchDB),PouchDB.adapter=function(e,t,n){t.valid()&&(PouchDB.adapters[e]=t,n&&PouchDB.preferredAdapters.push(e))},PouchDB.plugin=function(e){if(typeof e==`function`)e(PouchDB);else if(typeof e!=`object`||Object.keys(e).length===0)throw Error(`Invalid plugin: got "`+e+`", expected an object or a function`);else Object.keys(e).forEach(function(t){PouchDB.prototype[t]=e[t]});return this.__defaults&&(PouchDB.__defaults=Object.assign({},this.__defaults)),PouchDB},PouchDB.defaults=function(e){let t=createClass(PouchDB,function(e,n){n=n||{},e&&typeof e==`object`&&(n=e,e=n.name,delete n.name),n=Object.assign({},t.__defaults,n),PouchDB.call(this,e,n)});return t.preferredAdapters=PouchDB.preferredAdapters.slice(),Object.keys(PouchDB).forEach(function(e){e in t||(t[e]=PouchDB[e])}),t.__defaults=Object.assign({},this.__defaults,e),t},PouchDB.fetch=function(e,t){return f$1(e,t)},PouchDB.prototype.activeTasks=PouchDB.activeTasks=new ActiveTasks;var version=`9.0.0`;function getFieldFromDoc$1(e,t){for(var n=e,r=0,a=t.length;r<a;r++){var o=t[r];if(n=n[o],!n)break}return n}__name(getFieldFromDoc$1,`getFieldFromDoc`);function compare$1(e,t){return e<t?-1:e>t?1:0}__name(compare$1,`compare`);function parseField$1(e){for(var t=[],n=``,r=0,a=e.length;r<a;r++){var o=e[r];r>0&&e[r-1]===`\\`&&(o===`$`||o===`.`)?n=n.substring(0,n.length-1)+o:o===`.`?(t.push(n),n=``):n+=o}return t.push(n),t}__name(parseField$1,`parseField`);var combinationFields$1=[`$or`,`$nor`,`$not`];function isCombinationalField$1(e){return combinationFields$1.indexOf(e)>-1}__name(isCombinationalField$1,`isCombinationalField`);function getKey$1(e){return Object.keys(e)[0]}__name(getKey$1,`getKey`);function getValue$1(e){return e[getKey$1(e)]}__name(getValue$1,`getValue`);function mergeAndedSelectors$1(e){var t={},n={$or:!0,$nor:!0};return e.forEach(function(e){Object.keys(e).forEach(function(r){var a=e[r];if(typeof a!=`object`&&(a={$eq:a}),isCombinationalField$1(r))if(a instanceof Array){if(n[r]){n[r]=!1,t[r]=a;return}var o=[];t[r].forEach(function(e){Object.keys(a).forEach(function(t){var n=a[t],r=Math.max(Object.keys(e).length,Object.keys(n).length),s=mergeAndedSelectors$1([e,n]);Object.keys(s).length<=r||o.push(s)})}),t[r]=o}else t[r]=mergeAndedSelectors$1([a]);else{var s=t[r]=t[r]||{};Object.keys(a).forEach(function(e){var t=a[e];if(e===`$gt`||e===`$gte`)return mergeGtGte$1(e,t,s);if(e===`$lt`||e===`$lte`)return mergeLtLte$1(e,t,s);if(e===`$ne`)return mergeNe$1(t,s);if(e===`$eq`)return mergeEq$1(t,s);if(e===`$regex`)return mergeRegex$1(t,s);s[e]=t})}})}),t}__name(mergeAndedSelectors$1,`mergeAndedSelectors`);function mergeGtGte$1(e,t,n){n.$eq===void 0&&(n.$gte===void 0?n.$gt===void 0?n[e]=t:e===`$gte`?t>n.$gt&&(delete n.$gt,n.$gte=t):t>n.$gt&&(n.$gt=t):e===`$gte`?t>n.$gte&&(n.$gte=t):t>=n.$gte&&(delete n.$gte,n.$gt=t))}__name(mergeGtGte$1,`mergeGtGte`);function mergeLtLte$1(e,t,n){n.$eq===void 0&&(n.$lte===void 0?n.$lt===void 0?n[e]=t:e===`$lte`?t<n.$lt&&(delete n.$lt,n.$lte=t):t<n.$lt&&(n.$lt=t):e===`$lte`?t<n.$lte&&(n.$lte=t):t<=n.$lte&&(delete n.$lte,n.$lt=t))}__name(mergeLtLte$1,`mergeLtLte`);function mergeNe$1(e,t){`$ne`in t?t.$ne.push(e):t.$ne=[e]}__name(mergeNe$1,`mergeNe`);function mergeEq$1(e,t){delete t.$gt,delete t.$gte,delete t.$lt,delete t.$lte,delete t.$ne,t.$eq=e}__name(mergeEq$1,`mergeEq`);function mergeRegex$1(e,t){`$regex`in t?t.$regex.push(e):t.$regex=[e]}__name(mergeRegex$1,`mergeRegex`);function mergeAndedSelectorsNested$1(e){for(var t in e){if(Array.isArray(e))for(var n in e)e[n].$and&&(e[n]=mergeAndedSelectors$1(e[n].$and));var r=e[t];typeof r==`object`&&mergeAndedSelectorsNested$1(r)}return e}__name(mergeAndedSelectorsNested$1,`mergeAndedSelectorsNested`);function isAndInSelector$1(e,t){for(var n in e){n===`$and`&&(t=!0);var r=e[n];typeof r==`object`&&(t=isAndInSelector$1(r,t))}return t}__name(isAndInSelector$1,`isAndInSelector`);function massageSelector$1(e){var t=clone$1(e);isAndInSelector$1(t,!1)&&(t=mergeAndedSelectorsNested$1(t),`$and`in t&&(t=mergeAndedSelectors$1(t.$and))),[`$or`,`$nor`].forEach(function(e){e in t&&t[e].forEach(function(e){for(var t=Object.keys(e),n=0;n<t.length;n++){var r=t[n],a=e[r];(typeof a!=`object`||!a)&&(e[r]={$eq:a})}})}),`$not`in t&&(t.$not=mergeAndedSelectors$1([t.$not]));for(var n=Object.keys(t),r=0;r<n.length;r++){var a=n[r],o=t[a];(typeof o!=`object`||!o)&&(o={$eq:o}),t[a]=o}return normalizeArrayOperators$1(t),t}__name(massageSelector$1,`massageSelector`);function normalizeArrayOperators$1(e){Object.keys(e).forEach(function(t){var n=e[t];Array.isArray(n)?n.forEach(function(e){e&&typeof e==`object`&&normalizeArrayOperators$1(e)}):t===`$ne`?e.$ne=[n]:t===`$regex`?e.$regex=[n]:n&&typeof n==`object`&&normalizeArrayOperators$1(n)})}__name(normalizeArrayOperators$1,`normalizeArrayOperators`);function pad$1(e,t,n){for(var r=``,a=n-e.length;r.length<a;)r+=t;return r}__name(pad$1,`pad`);function padLeft$1(e,t,n){return pad$1(e,t,n)+e}__name(padLeft$1,`padLeft`);var MIN_MAGNITUDE$1=-324,MAGNITUDE_DIGITS$1=3,SEP$1=``;function collate$1(e,t){if(e===t)return 0;e=normalizeKey$1(e),t=normalizeKey$1(t);var n=collationIndex$1(e),r=collationIndex$1(t);if(n-r!==0)return n-r;switch(typeof e){case`number`:return e-t;case`boolean`:return e<t?-1:1;case`string`:return stringCollate$1(e,t)}return Array.isArray(e)?arrayCollate$1(e,t):objectCollate$1(e,t)}__name(collate$1,`collate`);function normalizeKey$1(e){switch(typeof e){case`undefined`:return null;case`number`:return e===1/0||e===-1/0||isNaN(e)?null:e;case`object`:var t=e;if(Array.isArray(e)){var n=e.length;e=Array(n);for(var r=0;r<n;r++)e[r]=normalizeKey$1(t[r])}else if(e instanceof Date)return e.toJSON();else if(e!==null){for(var a in e={},t)if(Object.prototype.hasOwnProperty.call(t,a)){var o=t[a];o!==void 0&&(e[a]=normalizeKey$1(o))}}}return e}__name(normalizeKey$1,`normalizeKey`);function indexify$1(e){if(e!==null)switch(typeof e){case`boolean`:return e?1:0;case`number`:return numToIndexableString$1(e);case`string`:return e.replace(/\u0002/g,``).replace(/\u0001/g,``).replace(/\u0000/g,``);case`object`:var t=Array.isArray(e),n=t?e:Object.keys(e),r=-1,a=n.length,o=``;if(t)for(;++r<a;)o+=toIndexableString$1(n[r]);else for(;++r<a;){var s=n[r];o+=toIndexableString$1(s)+toIndexableString$1(e[s])}return o}return``}__name(indexify$1,`indexify`);function toIndexableString$1(e){return e=normalizeKey$1(e),collationIndex$1(e)+SEP$1+indexify$1(e)+`\0`}__name(toIndexableString$1,`toIndexableString`);function parseNumber$1(e,t){var n=t,r;if(e[t]===`1`)r=0,t++;else{var a=e[t]===`0`;t++;var o=``,s=e.substring(t,t+MAGNITUDE_DIGITS$1),c=parseInt(s,10)+MIN_MAGNITUDE$1;for(a&&(c=-c),t+=MAGNITUDE_DIGITS$1;;){var l=e[t];if(l===`\0`)break;o+=l,t++}o=o.split(`.`),r=o.length===1?parseInt(o,10):parseFloat(o[0]+`.`+o[1]),a&&(r-=10),c!==0&&(r=parseFloat(r+`e`+c))}return{num:r,length:t-n}}__name(parseNumber$1,`parseNumber`);function pop$1(e,t){var n=e.pop();if(t.length){var r=t[t.length-1];n===r.element&&(t.pop(),r=t[t.length-1]);var a=r.element,o=r.index;if(Array.isArray(a))a.push(n);else if(o===e.length-2){var s=e.pop();a[s]=n}else e.push(n)}}__name(pop$1,`pop`);function parseIndexableString$1(e){for(var t=[],n=[],r=0;;){var a=e[r++];if(a===`\0`){if(t.length===1)return t.pop();pop$1(t,n);continue}switch(a){case`1`:t.push(null);break;case`2`:t.push(e[r]===`1`),r++;break;case`3`:var o=parseNumber$1(e,r);t.push(o.num),r+=o.length;break;case`4`:for(var s=``;;){var c=e[r];if(c===`\0`)break;s+=c,r++}s=s.replace(/\u0001\u0001/g,`\0`).replace(/\u0001\u0002/g,``).replace(/\u0002\u0002/g,``),t.push(s);break;case`5`:var l={element:[],index:t.length};t.push(l.element),n.push(l);break;case`6`:var u={element:{},index:t.length};t.push(u.element),n.push(u);break;default:throw Error(`bad collationIndex or unexpectedly reached end of input: `+a)}}}__name(parseIndexableString$1,`parseIndexableString`);function arrayCollate$1(e,t){for(var n=Math.min(e.length,t.length),r=0;r<n;r++){var a=collate$1(e[r],t[r]);if(a!==0)return a}return e.length===t.length?0:e.length>t.length?1:-1}__name(arrayCollate$1,`arrayCollate`);function stringCollate$1(e,t){return e===t?0:e>t?1:-1}__name(stringCollate$1,`stringCollate`);function objectCollate$1(e,t){for(var n=Object.keys(e),r=Object.keys(t),a=Math.min(n.length,r.length),o=0;o<a;o++){var s=collate$1(n[o],r[o]);if(s!==0||(s=collate$1(e[n[o]],t[r[o]]),s!==0))return s}return n.length===r.length?0:n.length>r.length?1:-1}__name(objectCollate$1,`objectCollate`);function collationIndex$1(e){var t=[`boolean`,`number`,`string`,`object`].indexOf(typeof e);if(~t)return e===null?1:Array.isArray(e)?5:t<3?t+2:t+3;if(Array.isArray(e))return 5}__name(collationIndex$1,`collationIndex`);function numToIndexableString$1(e){if(e===0)return`1`;var t=e.toExponential().split(/e\+?/),n=parseInt(t[1],10),r=e<0,a=r?`0`:`2`,o=padLeft$1(((r?-n:n)-MIN_MAGNITUDE$1).toString(),`0`,MAGNITUDE_DIGITS$1);a+=SEP$1+o;var s=Math.abs(parseFloat(t[0]));r&&(s=10-s);var c=s.toFixed(20);return c=c.replace(/\.?0+$/,``),a+=SEP$1+c,a}__name(numToIndexableString$1,`numToIndexableString`);function createFieldSorter$1(e){function getFieldValuesAsArray(t){return e.map(function(e){return getFieldFromDoc$1(t,parseField$1(getKey$1(e)))})}return function(e,t){var n=collate$1(getFieldValuesAsArray(e.doc),getFieldValuesAsArray(t.doc));return n===0?compare$1(e.doc._id,t.doc._id):n}}__name(createFieldSorter$1,`createFieldSorter`);function filterInMemoryFields$1(e,t,n){if(e=e.filter(function(e){return rowFilter$1(e.doc,t.selector,n)}),t.sort){var r=createFieldSorter$1(t.sort);e=e.sort(r),typeof t.sort[0]!=`string`&&getValue$1(t.sort[0])===`desc`&&(e=e.reverse())}if(`limit`in t||`skip`in t){var a=t.skip||0,o=(`limit`in t?t.limit:e.length)+a;e=e.slice(a,o)}return e}__name(filterInMemoryFields$1,`filterInMemoryFields`);function rowFilter$1(e,t,n){return n.every(function(n){var r=t[n],a=parseField$1(n),o=getFieldFromDoc$1(e,a);return isCombinationalField$1(n)?matchCominationalSelector$1(n,r,e):matchSelector$1(r,e,a,o)})}__name(rowFilter$1,`rowFilter`);function matchSelector$1(e,t,n,r){return e?typeof e==`object`?Object.keys(e).every(function(a){var o=e[a];if(a.indexOf(`$`)===0)return match$1(a,t,o,n,r);var s=parseField$1(a);if(r===void 0&&typeof o!=`object`&&s.length>0)return!1;var c=getFieldFromDoc$1(r,s);return typeof o==`object`?matchSelector$1(o,t,n,c):match$1(`$eq`,t,o,s,c)}):e===r:!0}__name(matchSelector$1,`matchSelector`);function matchCominationalSelector$1(e,t,n){return e===`$or`?t.some(function(e){return rowFilter$1(n,e,Object.keys(e))}):e===`$not`?!rowFilter$1(n,t,Object.keys(t)):!t.find(function(e){return rowFilter$1(n,e,Object.keys(e))})}__name(matchCominationalSelector$1,`matchCominationalSelector`);function match$1(e,t,n,r,a){if(!matchers$1[e])throw Error(`unknown operator "`+e+`" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, $nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all`);return matchers$1[e](t,n,r,a)}__name(match$1,`match`);function fieldExists$1(e){return e!=null}__name(fieldExists$1,`fieldExists`);function fieldIsNotUndefined$1(e){return e!==void 0}__name(fieldIsNotUndefined$1,`fieldIsNotUndefined`);function modField$1(e,t){if(typeof e!=`number`||parseInt(e,10)!==e)return!1;var n=t[0],r=t[1];return e%n===r}__name(modField$1,`modField`);function arrayContainsValue$1(e,t){return t.some(function(t){return e instanceof Array?e.some(function(e){return collate$1(t,e)===0}):collate$1(t,e)===0})}__name(arrayContainsValue$1,`arrayContainsValue`);function arrayContainsAllValues$1(e,t){return t.every(function(t){return e.some(function(e){return collate$1(t,e)===0})})}__name(arrayContainsAllValues$1,`arrayContainsAllValues`);function arraySize$1(e,t){return e.length===t}__name(arraySize$1,`arraySize`);function regexMatch$1(e,t){return new RegExp(t).test(e)}__name(regexMatch$1,`regexMatch`);function typeMatch$1(e,t){switch(t){case`null`:return e===null;case`boolean`:return typeof e==`boolean`;case`number`:return typeof e==`number`;case`string`:return typeof e==`string`;case`array`:return e instanceof Array;case`object`:return{}.toString.call(e)===`[object Object]`}}__name(typeMatch$1,`typeMatch`);var matchers$1={$elemMatch:function(e,t,n,r){return!Array.isArray(r)||r.length===0?!1:typeof r[0]==`object`&&r[0]!==null?r.some(function(e){return rowFilter$1(e,t,Object.keys(t))}):r.some(function(r){return matchSelector$1(t,e,n,r)})},$allMatch:function(e,t,n,r){return!Array.isArray(r)||r.length===0?!1:typeof r[0]==`object`&&r[0]!==null?r.every(function(e){return rowFilter$1(e,t,Object.keys(t))}):r.every(function(r){return matchSelector$1(t,e,n,r)})},$eq:function(e,t,n,r){return fieldIsNotUndefined$1(r)&&collate$1(r,t)===0},$gte:function(e,t,n,r){return fieldIsNotUndefined$1(r)&&collate$1(r,t)>=0},$gt:function(e,t,n,r){return fieldIsNotUndefined$1(r)&&collate$1(r,t)>0},$lte:function(e,t,n,r){return fieldIsNotUndefined$1(r)&&collate$1(r,t)<=0},$lt:function(e,t,n,r){return fieldIsNotUndefined$1(r)&&collate$1(r,t)<0},$exists:function(e,t,n,r){return t?fieldIsNotUndefined$1(r):!fieldIsNotUndefined$1(r)},$mod:function(e,t,n,r){return fieldExists$1(r)&&modField$1(r,t)},$ne:function(e,t,n,r){return t.every(function(e){return collate$1(r,e)!==0})},$in:function(e,t,n,r){return fieldExists$1(r)&&arrayContainsValue$1(r,t)},$nin:function(e,t,n,r){return fieldExists$1(r)&&!arrayContainsValue$1(r,t)},$size:function(e,t,n,r){return fieldExists$1(r)&&Array.isArray(r)&&arraySize$1(r,t)},$all:function(e,t,n,r){return Array.isArray(r)&&arrayContainsAllValues$1(r,t)},$regex:function(e,t,n,r){return fieldExists$1(r)&&typeof r==`string`&&t.every(function(e){return regexMatch$1(r,e)})},$type:function(e,t,n,r){return typeMatch$1(r,t)}};function matchesSelector$1(e,t){if(typeof t!=`object`)throw Error(`Selector error: expected a JSON object`);t=massageSelector$1(t);var n=filterInMemoryFields$1([{doc:e}],{selector:t},Object.keys(t));return n&&n.length===1}__name(matchesSelector$1,`matchesSelector`);function evalFilter(e){return scopeEval(`"use strict";
3
3
  return `+e+`;`,{})}function evalView(e){return scopeEval([`return function(doc) {`,` "use strict";`,` var emitted = false;`,` var emit = function (a, b) {`,` emitted = true;`,` };`,` var view = `+e+`;`,` view(doc);`,` if (emitted) {`,` return true;`,` }`,`};`].join(`
4
4
  `),{})}function validate(e,t){if(e.selector&&e.filter&&e.filter!==`_selector`){var n=typeof e.filter==`string`?e.filter:`function`;return t(Error(`selector invalid for filter "`+n+`"`))}t()}function normalize(e){e.view&&!e.filter&&(e.filter=`_view`),e.selector&&!e.filter&&(e.filter=`_selector`),e.filter&&typeof e.filter==`string`&&(e.filter===`_view`?e.view=normalizeDesignDocFunctionName(e.view):e.filter=normalizeDesignDocFunctionName(e.filter))}function shouldFilter(e,t){return t.filter&&typeof t.filter==`string`&&!t.doc_ids&&!isRemote$1(e.db)}function filter(e,t){var n=t.complete;if(t.filter===`_view`){if(!t.view||typeof t.view!=`string`)return n(createError$1(BAD_REQUEST$1,"`view` filter parameter not found or invalid."));var r=parseDesignDocFunctionName(t.view);e.db.get(`_design/`+r[0],function(a,o){if(e.isCancelled)return n(null,{status:`cancelled`});if(a)return n(generateErrorFromResponse$1(a));var s=o&&o.views&&o.views[r[1]]&&o.views[r[1]].map;if(!s)return n(createError$1(MISSING_DOC$1,o.views?`missing json key: `+r[1]:`missing json key: views`));t.filter=evalView(s),e.doChanges(t)})}else if(t.selector)t.filter=function(e){return matchesSelector$1(e,t.selector)},e.doChanges(t);else{var a=parseDesignDocFunctionName(t.filter);e.db.get(`_design/`+a[0],function(r,o){if(e.isCancelled)return n(null,{status:`cancelled`});if(r)return n(generateErrorFromResponse$1(r));var s=o&&o.filters&&o.filters[a[1]];if(!s)return n(createError$1(MISSING_DOC$1,o&&o.filters?`missing json key: `+a[1]:`missing json key: filters`));t.filter=evalFilter(s),e.doChanges(t)})}}function applyChangesFilterPlugin(e){e._changesFilterPlugin={validate,normalize,shouldFilter,filter}}PouchDB.plugin(applyChangesFilterPlugin),PouchDB.version=version;function checkBlobSupport(e,t,n){return new Promise(function(r){var a=createBlob$1([``]);let o;if(typeof n==`function`){let r=n(a);o=e.objectStore(t).put(r)}else{let r=n;o=e.objectStore(t).put(a,r)}o.onsuccess=function(){var e=navigator.userAgent.match(/Chrome\/(\d+)/);r(navigator.userAgent.match(/Edge\//)||!e||parseInt(e[1],10)>=43)},o.onerror=e.onabort=function(e){e.preventDefault(),e.stopPropagation(),r(!1)}}).catch(function(){return!1})}function toObject(e){return e.reduce(function(e,t){return e[t]=!0,e},{})}var reservedWords=toObject([`_id`,`_rev`,`_access`,`_attachments`,`_deleted`,`_revisions`,`_revs_info`,`_conflicts`,`_deleted_conflicts`,`_local_seq`,`_rev_tree`,`_replication_id`,`_replication_state`,`_replication_state_time`,`_replication_state_reason`,`_replication_stats`,`_removed`]),dataWords=toObject([`_access`,`_attachments`,`_replication_id`,`_replication_state`,`_replication_state_time`,`_replication_state_reason`,`_replication_stats`]);function parseRevisionInfo(e){if(!/^\d+-/.test(e))return createError$1(INVALID_REV$1);var t=e.indexOf(`-`),n=e.substring(0,t),r=e.substring(t+1);return{prefix:parseInt(n,10),id:r}}function makeRevTreeFromRevisions(e,t){for(var n=e.start-e.ids.length+1,r=e.ids,a=[r[0],t,[]],o=1,s=r.length;o<s;o++)a=[r[o],{status:`missing`},[a]];return[{pos:n,ids:a}]}function parseDoc(e,t,n){n||(n={deterministic_revs:!0});var r,a,o,s={status:`available`};if(e._deleted&&(s.deleted=!0),t)if(e._id||(e._id=uuid()),a=rev(e,n.deterministic_revs),e._rev){if(o=parseRevisionInfo(e._rev),o.error)return o;e._rev_tree=[{pos:o.prefix,ids:[o.id,{status:`missing`},[[a,s,[]]]]}],r=o.prefix+1}else e._rev_tree=[{pos:1,ids:[a,s,[]]}],r=1;else if(e._revisions&&(e._rev_tree=makeRevTreeFromRevisions(e._revisions,s),r=e._revisions.start,a=e._revisions.ids[0]),!e._rev_tree){if(o=parseRevisionInfo(e._rev),o.error)return o;r=o.prefix,a=o.id,e._rev_tree=[{pos:r,ids:[a,s,[]]}]}invalidIdError(e._id),e._rev=r+`-`+a;var c={metadata:{},data:{}};for(var l in e)if(Object.prototype.hasOwnProperty.call(e,l)){var u=l[0]===`_`;if(u&&!reservedWords[l]){var d=createError$1(DOC_VALIDATION$1,l);throw d.message=DOC_VALIDATION$1.message+`: `+l,d}else u&&!dataWords[l]?c.metadata[l.slice(1)]=e[l]:c.data[l]=e[l]}return c}function parseBase64(e){try{return thisAtob$1(e)}catch{return{error:createError$1(BAD_ARG$1,`Attachment is not a valid base64 string`)}}}function preprocessString(e,t,n){var r=parseBase64(e.data);if(r.error)return n(r.error);e.length=r.length,t===`blob`?e.data=binStringToBluffer$1(r,e.content_type):t===`base64`?e.data=thisBtoa(r):e.data=r,binaryMd5(r,function(t){e.digest=`md5-`+t,n()})}function preprocessBlob(e,t,n){binaryMd5(e.data,function(r){e.digest=`md5-`+r,e.length=e.data.size||e.data.length||0,t===`binary`?blobToBinaryString(e.data,function(t){e.data=t,n()}):t===`base64`?blobToBase64(e.data,function(t){e.data=t,n()}):n()})}function preprocessAttachment(e,t,n){if(e.stub)return n();typeof e.data==`string`?preprocessString(e,t,n):preprocessBlob(e,t,n)}function preprocessAttachments(e,t,n){if(!e.length)return n();var r=0,a;e.forEach(function(e){var n=e.data&&e.data._attachments?Object.keys(e.data._attachments):[],r=0;if(!n.length)return done();function processedAttachment(e){a=e,r++,r===n.length&&done()}for(var o in e.data._attachments)Object.prototype.hasOwnProperty.call(e.data._attachments,o)&&preprocessAttachment(e.data._attachments[o],t,processedAttachment)});function done(){r++,e.length===r&&(a?n(a):n())}}function updateDoc(e,t,n,r,a,o,s,c){if(revExists(t.rev_tree,n.metadata.rev)&&!c)return r[a]=n,o();var l=t.winningRev||winningRev(t),u=`deleted`in t?t.deleted:isDeleted(t,l),d=`deleted`in n.metadata?n.metadata.deleted:isDeleted(n.metadata),p=/^1-/.test(n.metadata.rev);if(u&&!d&&c&&p){var m=n.data;m._rev=l,m._id=n.metadata.id,n=parseDoc(m,c)}var g=merge(t.rev_tree,n.metadata.rev_tree[0],e);if(c&&(u&&d&&g.conflicts!==`new_leaf`||!u&&g.conflicts!==`new_leaf`||u&&!d&&g.conflicts===`new_branch`))return r[a]=createError$1(REV_CONFLICT$1),o();var _=n.metadata.rev;n.metadata.rev_tree=g.tree,n.stemmedRevs=g.stemmedRevs||[],t.rev_map&&(n.metadata.rev_map=t.rev_map);var v=winningRev(n.metadata),y=isDeleted(n.metadata,v),b=u===y?0:u<y?-1:1,x=_===v?y:isDeleted(n.metadata,_);s(n,v,y,x,!0,b,a,o)}function rootIsMissing(e){return e.metadata.rev_tree[0].ids[1].status===`missing`}function processDocs(e,t,n,r,a,o,s,c,l){e=e||1e3;function insertDoc(e,t,n){var r=winningRev(e.metadata),a=isDeleted(e.metadata,r);if(`was_delete`in c&&a)return o[t]=createError$1(MISSING_DOC$1,`deleted`),n();if(u&&rootIsMissing(e))return o[t]=createError$1(REV_CONFLICT$1),n();s(e,r,a,a,!1,a?0:1,t,n)}var u=c.new_edits,d=new Map,p=0,m=t.length;function checkAllDocsDone(){++p===m&&l&&l()}t.forEach(function(e,t){if(e._id&&isLocalId(e._id)){n[e._deleted?`_removeLocal`:`_putLocal`](e,{ctx:a},function(e,n){o[t]=e||n,checkAllDocsDone()});return}var r=e.metadata.id;d.has(r)?(m--,d.get(r).push([e,t])):d.set(r,[[e,t]])}),d.forEach(function(t,n){var a=0;function docWritten(){++a<t.length?nextDoc():checkAllDocsDone()}function nextDoc(){var c=t[a],l=c[0],d=c[1];if(r.has(n))updateDoc(e,r.get(n),l,o,d,docWritten,s,u);else{var p=merge([],l.metadata.rev_tree[0],e);l.metadata.rev_tree=p.tree,l.stemmedRevs=p.stemmedRevs||[],insertDoc(l,d,docWritten)}}nextDoc()})}var ADAPTER_VERSION=5,DOC_STORE=`document-store`,BY_SEQ_STORE=`by-sequence`,ATTACH_STORE=`attach-store`,ATTACH_AND_SEQ_STORE=`attach-seq-store`,META_STORE=`meta-store`,LOCAL_STORE=`local-store`,DETECT_BLOB_SUPPORT_STORE=`detect-blob-support`;function safeJsonParse(e){try{return JSON.parse(e)}catch{return import_vuvuzela.parse(e)}}function safeJsonStringify(e){try{return JSON.stringify(e)}catch{return import_vuvuzela.stringify(e)}}function idbError(e){return function(t){var n=`unknown_error`;t.target&&t.target.error&&(n=t.target.error.name||t.target.error.message),e(createError$1(IDB_ERROR$1,n,t.type))}}function encodeMetadata(e,t,n){return{data:safeJsonStringify(e),winningRev:t,deletedOrLocal:n?`1`:`0`,seq:e.seq,id:e.id}}function decodeMetadata(e){if(!e)return null;var t=safeJsonParse(e.data);return t.winningRev=e.winningRev,t.deleted=e.deletedOrLocal===`1`,t.seq=e.seq,t}function decodeDoc(e){if(!e)return e;var t=e._doc_id_rev.lastIndexOf(`:`);return e._id=e._doc_id_rev.substring(0,t-1),e._rev=e._doc_id_rev.substring(t+1),delete e._doc_id_rev,e}function readBlobData(e,t,n,r){n?r(e?typeof e==`string`?b64ToBluffer$1(e,t):e:createBlob$1([``],{type:t})):e?typeof e==`string`?r(e):readAsBinaryString(e,function(e){r(thisBtoa(e))}):r(``)}function fetchAttachmentsIfNecessary(e,t,n,r){var a=Object.keys(e._attachments||{});if(!a.length)return r&&r();var o=0;function checkDone(){++o===a.length&&r&&r()}function fetchAttachment(e,t){var r=e._attachments[t],a=r.digest,o=n.objectStore(ATTACH_STORE).get(a);o.onsuccess=function(e){r.body=e.target.result.body,checkDone()}}a.forEach(function(n){t.attachments&&t.include_docs?fetchAttachment(e,n):(e._attachments[n].stub=!0,checkDone())})}function postProcessAttachments(e,t){return Promise.all(e.map(function(e){if(e.doc&&e.doc._attachments){var n=Object.keys(e.doc._attachments);return Promise.all(n.map(function(n){var r=e.doc._attachments[n];if(`body`in r){var a=r.body,o=r.content_type;return new Promise(function(s){readBlobData(a,o,t,function(t){e.doc._attachments[n]=Object.assign(pick$1(r,[`digest`,`content_type`]),{data:t}),s()})})}}))}}))}function compactRevs(e,t,n){var r=[],a=n.objectStore(BY_SEQ_STORE),o=n.objectStore(ATTACH_STORE),s=n.objectStore(ATTACH_AND_SEQ_STORE),c=e.length;function checkDone(){c--,c||deleteOrphanedAttachments()}function deleteOrphanedAttachments(){r.length&&r.forEach(function(e){var t=s.index(`digestSeq`).count(IDBKeyRange.bound(e+`::`,e+`::￿`,!1,!1));t.onsuccess=function(t){t.target.result||o.delete(e)}})}e.forEach(function(e){var n=a.index(`_doc_id_rev`),o=t+`::`+e;n.getKey(o).onsuccess=function(e){var t=e.target.result;if(typeof t!=`number`)return checkDone();a.delete(t);var n=s.index(`seq`).openCursor(IDBKeyRange.only(t));n.onsuccess=function(e){var t=e.target.result;if(t){var n=t.value.digestSeq.split(`::`)[0];r.push(n),s.delete(t.primaryKey),t.continue()}else checkDone()}}})}function openTransactionSafely(e,t,n){try{return{txn:e.transaction(t,n)}}catch(e){return{error:e}}}var changesHandler=new Changes;function idbBulkDocs(e,t,n,r,a,o){for(var s=t.docs,c,l,u,d,p,m,g,_,v=0,y=s.length;v<y;v++){var b=s[v];b._id&&isLocalId(b._id)||(b=s[v]=parseDoc(b,n.new_edits,e),b.error&&!g&&(g=b))}if(g)return o(g);var x=!1,S=0,C=Array(s.length),w=new Map,T=!1;preprocessAttachments(s,r._meta.blobSupport?`blob`:`base64`,function(e){if(e)return o(e);startTransaction()});function startTransaction(){var e=openTransactionSafely(a,[DOC_STORE,BY_SEQ_STORE,ATTACH_STORE,LOCAL_STORE,ATTACH_AND_SEQ_STORE,META_STORE],`readwrite`);if(e.error)return o(e.error);c=e.txn,c.onabort=idbError(o),c.ontimeout=idbError(o),c.oncomplete=complete,l=c.objectStore(DOC_STORE),u=c.objectStore(BY_SEQ_STORE),d=c.objectStore(ATTACH_STORE),p=c.objectStore(ATTACH_AND_SEQ_STORE),m=c.objectStore(META_STORE),m.get(META_STORE).onsuccess=function(e){_=e.target.result,updateDocCountIfReady()},verifyAttachments(function(e){if(e)return T=!0,o(e);fetchExistingDocs()})}function onAllDocsProcessed(){x=!0,updateDocCountIfReady()}function idbProcessDocs(){processDocs(e.revs_limit,s,r,w,c,C,writeDoc,n,onAllDocsProcessed)}function updateDocCountIfReady(){!_||!x||(_.docCount+=S,m.put(_))}function fetchExistingDocs(){if(!s.length)return;var e=0;function checkDone(){++e===s.length&&idbProcessDocs()}function readMetadata(e){var t=decodeMetadata(e.target.result);t&&w.set(t.id,t),checkDone()}for(var t=0,n=s.length;t<n;t++){var r=s[t];if(r._id&&isLocalId(r._id)){checkDone();continue}var a=l.get(r.metadata.id);a.onsuccess=readMetadata}}function complete(){T||(changesHandler.notify(r._meta.name),o(null,C))}function verifyAttachment(e,t){var n=d.get(e);n.onsuccess=function(n){if(n.target.result)t();else{var r=createError$1(MISSING_STUB$1,`unknown stub attachment with digest `+e);r.status=412,t(r)}}}function verifyAttachments(e){var t=[];if(s.forEach(function(e){e.data&&e.data._attachments&&Object.keys(e.data._attachments).forEach(function(n){var r=e.data._attachments[n];r.stub&&t.push(r.digest)})}),!t.length)return e();var n=0,r;function checkDone(){++n===t.length&&e(r)}t.forEach(function(e){verifyAttachment(e,function(e){e&&!r&&(r=e),checkDone()})})}function writeDoc(e,t,n,r,a,o,s,c){e.metadata.winningRev=t,e.metadata.deleted=n;var l=e.data;if(l._id=e.metadata.id,l._rev=e.metadata.rev,r&&(l._deleted=!0),l._attachments&&Object.keys(l._attachments).length)return writeAttachments(e,t,n,a,s,c);S+=o,updateDocCountIfReady(),finishDoc(e,t,n,a,s,c)}function finishDoc(e,t,n,a,o,s){var d=e.data,p=e.metadata;d._doc_id_rev=p.id+`::`+p.rev,delete d._id,delete d._rev;function afterPutDoc(o){var s=e.stemmedRevs||[];a&&r.auto_compaction&&(s=s.concat(compactTree(e.metadata))),s&&s.length&&compactRevs(s,e.metadata.id,c),p.seq=o.target.result;var u=encodeMetadata(p,t,n),d=l.put(u);d.onsuccess=afterPutMetadata}function afterPutDocError(e){e.preventDefault(),e.stopPropagation();var t=u.index(`_doc_id_rev`).getKey(d._doc_id_rev);t.onsuccess=function(e){var t=u.put(d,e.target.result);t.onsuccess=afterPutDoc}}function afterPutMetadata(){C[o]={ok:!0,id:p.id,rev:p.rev},w.set(e.metadata.id,e.metadata),insertAttachmentMappings(e,p.seq,s)}var m=u.put(d);m.onsuccess=afterPutDoc,m.onerror=afterPutDocError}function writeAttachments(e,t,n,r,a,o){var s=e.data,c=0,l=Object.keys(s._attachments);function collectResults(){c===l.length&&finishDoc(e,t,n,r,a,o)}function attachmentSaved(){c++,collectResults()}l.forEach(function(n){var r=e.data._attachments[n];if(r.stub)c++,collectResults();else{var a=r.data;delete r.data,r.revpos=parseInt(t,10);var o=r.digest;saveAttachment(o,a,attachmentSaved)}})}function insertAttachmentMappings(e,t,n){var r=0,a=Object.keys(e.data._attachments||{});if(!a.length)return n();function checkDone(){++r===a.length&&n()}function add(n){var r=e.data._attachments[n].digest,a=p.put({seq:t,digestSeq:r+`::`+t});a.onsuccess=checkDone,a.onerror=function(e){e.preventDefault(),e.stopPropagation(),checkDone()}}for(var o=0;o<a.length;o++)add(a[o])}function saveAttachment(e,t,n){var r=d.count(e);r.onsuccess=function(r){if(r.target.result)return n();var a={digest:e,body:t},o=d.put(a);o.onsuccess=n}}}function runBatchedCursor(e,t,n,r,a){r===-1&&(r=1e3);var o=typeof e.getAll==`function`&&typeof e.getAllKeys==`function`&&r>1&&!n,s,c,l;function onGetAll(e){c=e.target.result,s&&a(s,c,l)}function onGetAllKeys(e){s=e.target.result,c&&a(s,c,l)}function continuePseudoCursor(){if(!s.length)return a();var n=s[s.length-1],o;if(t&&t.upper)try{o=IDBKeyRange.bound(n,t.upper,!0,t.upperOpen)}catch(e){if(e.name===`DataError`&&e.code===0)return a()}else o=IDBKeyRange.lowerBound(n,!0);t=o,s=null,c=null,e.getAll(t,r).onsuccess=onGetAll,e.getAllKeys(t,r).onsuccess=onGetAllKeys}function onCursor(e){var t=e.target.result;if(!t)return a();a([t.key],[t.value],t)}o?(l={continue:continuePseudoCursor},e.getAll(t,r).onsuccess=onGetAll,e.getAllKeys(t,r).onsuccess=onGetAllKeys):n?e.openCursor(t,`prev`).onsuccess=onCursor:e.openCursor(t).onsuccess=onCursor}function getAll(e,t,n){if(typeof e.getAll==`function`){e.getAll(t).onsuccess=n;return}var r=[];function onCursor(e){var t=e.target.result;t?(r.push(t.value),t.continue()):n({target:{result:r}})}e.openCursor(t).onsuccess=onCursor}function allDocsKeys(e,t,n){var r=Array(e.length),a=0;e.forEach(function(o,s){t.get(o).onsuccess=function(t){t.target.result?r[s]=t.target.result:r[s]={key:o,error:`not_found`},a++,a===e.length&&n(e,r,{})}})}function createKeyRange(e,t,n,r,a){try{if(e&&t)return a?IDBKeyRange.bound(t,e,!n,!1):IDBKeyRange.bound(e,t,!1,!n);if(e)return a?IDBKeyRange.upperBound(e):IDBKeyRange.lowerBound(e);if(t)return a?IDBKeyRange.lowerBound(t,!n):IDBKeyRange.upperBound(t,!n);if(r)return IDBKeyRange.only(r)}catch(e){return{error:e}}return null}function idbAllDocs(e,t,n){var r=`startkey`in e?e.startkey:!1,a=`endkey`in e?e.endkey:!1,o=`key`in e?e.key:!1,s=`keys`in e?e.keys:!1,c=e.skip||0,l=typeof e.limit==`number`?e.limit:-1,u=e.inclusive_end!==!1,d,p;if(!s&&(d=createKeyRange(r,a,u,o,e.descending),p=d&&d.error,p&&!(p.name===`DataError`&&p.code===0)))return n(createError$1(IDB_ERROR$1,p.name,p.message));var m=[DOC_STORE,BY_SEQ_STORE,META_STORE];e.attachments&&m.push(ATTACH_STORE);var g=openTransactionSafely(t,m,`readonly`);if(g.error)return n(g.error);var _=g.txn;_.oncomplete=onTxnComplete,_.onabort=idbError(n);var v=_.objectStore(DOC_STORE),y=_.objectStore(BY_SEQ_STORE),b=_.objectStore(META_STORE),x=y.index(`_doc_id_rev`),S=[],C,w;b.get(META_STORE).onsuccess=function(e){C=e.target.result.docCount},e.update_seq&&(y.openKeyCursor(null,`prev`).onsuccess=e=>{var t=e.target.result;t&&t.key&&(w=t.key)});function fetchDocAsynchronously(t,n,r){var a=t.id+`::`+r;x.get(a).onsuccess=function onGetDoc(r){if(n.doc=decodeDoc(r.target.result)||{},e.conflicts){var a=collectConflicts(t);a.length&&(n.doc._conflicts=a)}fetchAttachmentsIfNecessary(n.doc,e,_)}}function allDocsInner(t,n){var r={id:n.id,key:n.id,value:{rev:t}};n.deleted?s&&(S.push(r),r.value.deleted=!0,r.doc=null):c--<=0&&(S.push(r),e.include_docs&&fetchDocAsynchronously(n,r,t))}function processBatch(e){for(var t=0,n=e.length;t<n&&S.length!==l;t++){var r=e[t];if(r.error&&s){S.push(r);continue}var a=decodeMetadata(r),o=a.winningRev;allDocsInner(o,a)}}function onBatch(e,t,n){n&&(processBatch(t),S.length<l&&n.continue())}function onGetAll(t){var n=t.target.result;e.descending&&(n=n.reverse()),processBatch(n)}function onResultsReady(){var t={total_rows:C,offset:e.skip,rows:S};e.update_seq&&w!==void 0&&(t.update_seq=w),n(null,t)}function onTxnComplete(){e.attachments?postProcessAttachments(S,e.binary).then(onResultsReady):onResultsReady()}if(!(p||l===0)){if(s)return allDocsKeys(s,v,onBatch);if(l===-1)return getAll(v,d,onGetAll);runBatchedCursor(v,d,e.descending,l+c,onBatch)}}function countDocs(e,t){var n=e.objectStore(DOC_STORE).index(`deletedOrLocal`);n.count(IDBKeyRange.only(`0`)).onsuccess=function(e){t(e.target.result)}}var running=!1,queue=[];function tryCode(e,t,n,r){try{e(t,n)}catch(e){r.emit(`error`,e)}}function applyNext(){running||!queue.length||(running=!0,queue.shift()())}function enqueueTask(e,t,n){queue.push(function runAction(){e(function runCallback(e,r){tryCode(t,e,r,n),running=!1,nextTick$1(function runNext(){applyNext(n)})})}),applyNext()}function changes(e,t,n,r){if(e=clone$1(e),e.continuous){var a=n+`:`+uuid();return changesHandler.addListener(n,a,t,e),changesHandler.notify(n),{cancel:function(){changesHandler.removeListener(n,a)}}}var o=e.doc_ids&&new Set(e.doc_ids);e.since=e.since||0;var s=e.since,c=`limit`in e?e.limit:-1;c===0&&(c=1);var l=[],u=0,d=filterChange(e),p=new Map,m,g,_,v;function onBatch(t,n,r){if(!r||!t.length)return;var a=Array(t.length),o=Array(t.length);function processMetadataAndWinningDoc(t,n){var r=e.processChange(n,t,e);s=r.seq=t.seq;var a=d(r);return typeof a==`object`?Promise.reject(a):a?(u++,e.return_docs&&l.push(r),e.attachments&&e.include_docs?new Promise(function(t){fetchAttachmentsIfNecessary(n,e,m,function(){postProcessAttachments([r],e.binary).then(function(){t(r)})})}):Promise.resolve(r)):Promise.resolve()}function onBatchDone(){for(var t=[],n=0,s=a.length;n<s&&u!==c;n++){var l=a[n];if(l){var d=o[n];t.push(processMetadataAndWinningDoc(d,l))}}Promise.all(t).then(function(t){for(var n=0,r=t.length;n<r;n++)t[n]&&e.onChange(t[n])}).catch(e.complete),u!==c&&r.continue()}var p=0;n.forEach(function(e,n){var r=decodeDoc(e),s=t[n];fetchWinningDocAndMetadata(r,s,function(e,r){o[n]=e,a[n]=r,++p===t.length&&onBatchDone()})})}function onGetMetadata(e,t,n,r){if(n.seq!==t)return r();if(n.winningRev===e._rev)return r(n,e);var a=e._id+`::`+n.winningRev,o=v.get(a);o.onsuccess=function(e){r(n,decodeDoc(e.target.result))}}function fetchWinningDocAndMetadata(e,t,n){if(o&&!o.has(e._id))return n();var r=p.get(e._id);if(r)return onGetMetadata(e,t,r,n);_.get(e._id).onsuccess=function(a){r=decodeMetadata(a.target.result),p.set(e._id,r),onGetMetadata(e,t,r,n)}}function finish(){e.complete(null,{results:l,last_seq:s})}function onTxnComplete(){!e.continuous&&e.attachments?postProcessAttachments(l).then(finish):finish()}var y=[DOC_STORE,BY_SEQ_STORE];e.attachments&&y.push(ATTACH_STORE);var b=openTransactionSafely(r,y,`readonly`);if(b.error)return e.complete(b.error);m=b.txn,m.onabort=idbError(e.complete),m.oncomplete=onTxnComplete,g=m.objectStore(BY_SEQ_STORE),_=m.objectStore(DOC_STORE),v=g.index(`_doc_id_rev`);var x=e.since&&!e.descending?IDBKeyRange.lowerBound(e.since,!0):null;runBatchedCursor(g,x,e.descending,c,onBatch)}var cachedDBs=new Map,blobSupportPromise,openReqList=new Map;function IdbPouch(e,t){var n=this;enqueueTask(function(t){init(n,e,t)},t,n.constructor)}function init(e,t,n){var r=t.name,a=null,o=null;e._meta=null;function enrichCallbackError(e){return function(t,n){t&&t instanceof Error&&!t.reason&&o&&(t.reason=o),e(t,n)}}function createSchema(e){var t=e.createObjectStore(DOC_STORE,{keyPath:`id`});e.createObjectStore(BY_SEQ_STORE,{autoIncrement:!0}).createIndex(`_doc_id_rev`,`_doc_id_rev`,{unique:!0}),e.createObjectStore(ATTACH_STORE,{keyPath:`digest`}),e.createObjectStore(META_STORE,{keyPath:`id`,autoIncrement:!1}),e.createObjectStore(DETECT_BLOB_SUPPORT_STORE),t.createIndex(`deletedOrLocal`,`deletedOrLocal`,{unique:!1}),e.createObjectStore(LOCAL_STORE,{keyPath:`_id`});var n=e.createObjectStore(ATTACH_AND_SEQ_STORE,{autoIncrement:!0});n.createIndex(`seq`,`seq`),n.createIndex(`digestSeq`,`digestSeq`,{unique:!0})}function addDeletedOrLocalIndex(e,t){var n=e.objectStore(DOC_STORE);n.createIndex(`deletedOrLocal`,`deletedOrLocal`,{unique:!1}),n.openCursor().onsuccess=function(e){var r=e.target.result;if(r){var a=r.value;a.deletedOrLocal=isDeleted(a)?`1`:`0`,n.put(a),r.continue()}else t()}}function createLocalStoreSchema(e){e.createObjectStore(LOCAL_STORE,{keyPath:`_id`}).createIndex(`_doc_id_rev`,`_doc_id_rev`,{unique:!0})}function migrateLocalStore(e,t){var n=e.objectStore(LOCAL_STORE),r=e.objectStore(DOC_STORE),a=e.objectStore(BY_SEQ_STORE),o=r.openCursor();o.onsuccess=function(e){var o=e.target.result;if(o){var s=o.value,c=s.id,l=isLocalId(c),u=winningRev(s);if(l){var d=c+`::`+u,p=c+`::`,m=c+`::~`,g=a.index(`_doc_id_rev`),_=IDBKeyRange.bound(p,m,!1,!1),v=g.openCursor(_);v.onsuccess=function(e){if(v=e.target.result,!v)r.delete(o.primaryKey),o.continue();else{var t=v.value;t._doc_id_rev===d&&n.put(t),a.delete(v.primaryKey),v.continue()}}}else o.continue()}else t&&t()}}function addAttachAndSeqStore(e){var t=e.createObjectStore(ATTACH_AND_SEQ_STORE,{autoIncrement:!0});t.createIndex(`seq`,`seq`),t.createIndex(`digestSeq`,`digestSeq`,{unique:!0})}function migrateAttsAndSeqs(e,t){var n=e.objectStore(BY_SEQ_STORE),r=e.objectStore(ATTACH_STORE),a=e.objectStore(ATTACH_AND_SEQ_STORE),o=r.count();o.onsuccess=function(e){if(!e.target.result)return t();n.openCursor().onsuccess=function(e){var n=e.target.result;if(!n)return t();for(var r=n.value,o=n.primaryKey,s=Object.keys(r._attachments||{}),c={},l=0;l<s.length;l++){var u=r._attachments[s[l]];c[u.digest]=!0}var d=Object.keys(c);for(l=0;l<d.length;l++){var p=d[l];a.put({seq:o,digestSeq:p+`::`+o})}n.continue()}}}function migrateMetadata(e){function decodeMetadataCompat(e){return e.data?decodeMetadata(e):(e.deleted=e.deletedOrLocal===`1`,e)}var t=e.objectStore(BY_SEQ_STORE),n=e.objectStore(DOC_STORE),r=n.openCursor();r.onsuccess=function(e){var r=e.target.result;if(!r)return;var a=decodeMetadataCompat(r.value);a.winningRev=a.winningRev||winningRev(a);function fetchMetadataSeq(){var e=a.id+`::`,n=a.id+`::￿`,r=t.index(`_doc_id_rev`).openCursor(IDBKeyRange.bound(e,n)),o=0;r.onsuccess=function(e){var t=e.target.result;if(!t)return a.seq=o,onGetMetadataSeq();var n=t.primaryKey;n>o&&(o=n),t.continue()}}function onGetMetadataSeq(){var e=encodeMetadata(a,a.winningRev,a.deleted),t=n.put(e);t.onsuccess=function(){r.continue()}}if(a.seq)return onGetMetadataSeq();fetchMetadataSeq()}}e._remote=!1,e.type=function(){return`idb`},e._id=toPromise(function(t){t(null,e._meta.instanceId)}),e._bulkDocs=function idb_bulkDocs(n,r,o){idbBulkDocs(t,n,r,e,a,enrichCallbackError(o))},e._get=function idb_get(e,t,n){var r,o,s,c=t.ctx;if(!c){var l=openTransactionSafely(a,[DOC_STORE,BY_SEQ_STORE,ATTACH_STORE],`readonly`);if(l.error)return n(l.error);c=l.txn}function finish(){n(s,{doc:r,metadata:o,ctx:c})}c.objectStore(DOC_STORE).get(e).onsuccess=function(e){if(o=decodeMetadata(e.target.result),!o)return s=createError$1(MISSING_DOC$1,`missing`),finish();var n;if(t.rev)n=t.latest?latest(t.rev,o):t.rev;else if(n=o.winningRev,isDeleted(o))return s=createError$1(MISSING_DOC$1,`deleted`),finish();var a=c.objectStore(BY_SEQ_STORE),l=o.id+`::`+n;a.index(`_doc_id_rev`).get(l).onsuccess=function(e){if(r=e.target.result,r&&(r=decodeDoc(r)),!r)return s=createError$1(MISSING_DOC$1,`missing`),finish();finish()}}},e._getAttachment=function(e,t,n,r,o){var s;if(r.ctx)s=r.ctx;else{var c=openTransactionSafely(a,[DOC_STORE,BY_SEQ_STORE,ATTACH_STORE],`readonly`);if(c.error)return o(c.error);s=c.txn}var l=n.digest,u=n.content_type;s.objectStore(ATTACH_STORE).get(l).onsuccess=function(e){var t=e.target.result.body;readBlobData(t,u,r.binary,function(e){o(null,e)})}},e._info=function idb_info(t){var n,r,o=openTransactionSafely(a,[META_STORE,BY_SEQ_STORE],`readonly`);if(o.error)return t(o.error);var s=o.txn;s.objectStore(META_STORE).get(META_STORE).onsuccess=function(e){r=e.target.result.docCount},s.objectStore(BY_SEQ_STORE).openKeyCursor(null,`prev`).onsuccess=function(e){var t=e.target.result;n=t?t.key:0},s.oncomplete=function(){t(null,{doc_count:r,update_seq:n,idb_attachment_format:e._meta.blobSupport?`binary`:`base64`})}},e._allDocs=function idb_allDocs(e,t){idbAllDocs(e,a,enrichCallbackError(t))},e._changes=function idbChanges(t){return changes(t,e,r,a)},e._close=function(e){a.close(),cachedDBs.delete(r),e()},e._getRevisionTree=function(e,t){var n=openTransactionSafely(a,[DOC_STORE],`readonly`);if(n.error)return t(n.error);var r=n.txn.objectStore(DOC_STORE).get(e);r.onsuccess=function(e){var n=decodeMetadata(e.target.result);n?t(null,n.rev_tree):t(createError$1(MISSING_DOC$1))}},e._doCompaction=function(e,t,n){var r=openTransactionSafely(a,[DOC_STORE,BY_SEQ_STORE,ATTACH_STORE,ATTACH_AND_SEQ_STORE],`readwrite`);if(r.error)return n(r.error);var o=r.txn,s=o.objectStore(DOC_STORE);s.get(e).onsuccess=function(n){var r=decodeMetadata(n.target.result);traverseRevTree(r.rev_tree,function(e,n,r,a,o){var s=n+`-`+r;t.indexOf(s)!==-1&&(o.status=`missing`)}),compactRevs(t,e,o);var a=r.winningRev,s=r.deleted;o.objectStore(DOC_STORE).put(encodeMetadata(r,a,s))},o.onabort=idbError(n),o.oncomplete=function(){n()}},e._getLocal=function(e,t){var n=openTransactionSafely(a,[LOCAL_STORE],`readonly`);if(n.error)return t(n.error);var r=n.txn.objectStore(LOCAL_STORE).get(e);r.onerror=idbError(t),r.onsuccess=function(e){var n=e.target.result;n?(delete n._doc_id_rev,t(null,n)):t(createError$1(MISSING_DOC$1))}},e._putLocal=function(e,t,n){typeof t==`function`&&(n=t,t={}),delete e._revisions;var r=e._rev,o=e._id;r?e._rev=`0-`+(parseInt(r.split(`-`)[1],10)+1):e._rev=`0-1`;var s=t.ctx,c;if(!s){var l=openTransactionSafely(a,[LOCAL_STORE],`readwrite`);if(l.error)return n(l.error);s=l.txn,s.onerror=idbError(n),s.oncomplete=function(){c&&n(null,c)}}var u=s.objectStore(LOCAL_STORE),d;r?(d=u.get(o),d.onsuccess=function(a){var o=a.target.result;if(!o||o._rev!==r)n(createError$1(REV_CONFLICT$1));else{var s=u.put(e);s.onsuccess=function(){c={ok:!0,id:e._id,rev:e._rev},t.ctx&&n(null,c)}}}):(d=u.add(e),d.onerror=function(e){n(createError$1(REV_CONFLICT$1)),e.preventDefault(),e.stopPropagation()},d.onsuccess=function(){c={ok:!0,id:e._id,rev:e._rev},t.ctx&&n(null,c)})},e._removeLocal=function(e,t,n){typeof t==`function`&&(n=t,t={});var r=t.ctx;if(!r){var o=openTransactionSafely(a,[LOCAL_STORE],`readwrite`);if(o.error)return n(o.error);r=o.txn,r.oncomplete=function(){s&&n(null,s)}}var s,c=e._id,l=r.objectStore(LOCAL_STORE),u=l.get(c);u.onerror=idbError(n),u.onsuccess=function(r){var a=r.target.result;!a||a._rev!==e._rev?n(createError$1(MISSING_DOC$1)):(l.delete(c),s={ok:!0,id:c,rev:`0-0`},t.ctx&&n(null,s))}},e._destroy=function(e,t){changesHandler.removeAllListeners(r);var n=openReqList.get(r);n&&n.result&&(n.result.close(),cachedDBs.delete(r));var a=indexedDB.deleteDatabase(r);a.onsuccess=function(){openReqList.delete(r),hasLocalStorage()&&r in localStorage&&delete localStorage[r],t(null,{ok:!0})},a.onerror=idbError(t)};var s=cachedDBs.get(r);if(s)return a=s.idb,e._meta=s.global,nextTick$1(function(){n(null,e)});var c=indexedDB.open(r,ADAPTER_VERSION);openReqList.set(r,c),c.onupgradeneeded=function(e){var t=e.target.result;if(e.oldVersion<1)return createSchema(t);var n=e.currentTarget.transaction;e.oldVersion<3&&createLocalStoreSchema(t),e.oldVersion<4&&addAttachAndSeqStore(t);var r=[addDeletedOrLocalIndex,migrateLocalStore,migrateAttsAndSeqs,migrateMetadata],a=e.oldVersion;function next(){var e=r[a-1];a++,e&&e(n,next)}next()},c.onsuccess=function(t){a=t.target.result,a.onversionchange=function(){a.close(),cachedDBs.delete(r)},a.onabort=function(e){guardedConsole$1(`error`,`Database has a global failure`,e.target.error),o=e.target.error,a.close(),cachedDBs.delete(r)};var s=a.transaction([META_STORE,DETECT_BLOB_SUPPORT_STORE,DOC_STORE],`readwrite`),c=!1,l,u,d,p;function completeSetup(){d===void 0||!c||(e._meta={name:r,instanceId:p,blobSupport:d},cachedDBs.set(r,{idb:a,global:e._meta}),n(null,e))}function storeMetaDocIfReady(){if(!(u===void 0||l===void 0)){var e=r+`_id`;e in l?p=l[e]:l[e]=p=uuid(),l.docCount=u,s.objectStore(META_STORE).put(l)}}s.objectStore(META_STORE).get(META_STORE).onsuccess=function(e){l=e.target.result||{id:META_STORE},storeMetaDocIfReady()},countDocs(s,function(e){u=e,storeMetaDocIfReady()}),blobSupportPromise||(blobSupportPromise=checkBlobSupport(s,DETECT_BLOB_SUPPORT_STORE,`key`)),blobSupportPromise.then(function(e){d=e,completeSetup()}),s.oncomplete=function(){c=!0,completeSetup()},s.onabort=idbError(n)},c.onerror=function(e){var t=e.target.error&&e.target.error.message;t?t.indexOf(`stored database is a higher version`)!==-1&&(t=Error(`This DB was created with the newer "indexeddb" adapter, but you are trying to open it with the older "idb" adapter`)):t=`Failed to open indexedDB, are you in private browsing mode?`,guardedConsole$1(`error`,t),n(createError$1(IDB_ERROR$1,t))}}IdbPouch.valid=function(){try{return typeof indexedDB<`u`&&typeof IDBKeyRange<`u`}catch{return!1}};function IDBPouch(e){e.adapter(`idb`,IdbPouch,!0)}function pool(e,t){return new Promise(function(n,r){var a=0,o=0,s=0,c=e.length,l;function runNext(){a++,e[o++]().then(onSuccess,onError)}function doNext(){++s===c?l?r(l):n():runNextBatch()}function onSuccess(){a--,doNext()}function onError(e){a--,l=l||e,doNext()}function runNextBatch(){for(;a<t&&o<c;)runNext()}runNextBatch()})}var CHANGES_BATCH_SIZE$1=25,MAX_SIMULTANEOUS_REVS=50,CHANGES_TIMEOUT_BUFFER=5e3,DEFAULT_HEARTBEAT=1e4,supportsBulkGetMap={};function readAttachmentsAsBlobOrBuffer(e){let t=e.doc||e.ok,n=t&&t._attachments;n&&Object.keys(n).forEach(function(e){let t=n[e];t.data=b64ToBluffer$1(t.data,t.content_type)})}function encodeDocId(e){return/^_design/.test(e)?`_design/`+encodeURIComponent(e.slice(8)):e.startsWith(`_local/`)?`_local/`+encodeURIComponent(e.slice(7)):encodeURIComponent(e)}function preprocessAttachments$1(e){return!e._attachments||!Object.keys(e._attachments)?Promise.resolve():Promise.all(Object.keys(e._attachments).map(function(t){let n=e._attachments[t];if(n.data&&typeof n.data!=`string`)return new Promise(function(e){blobToBase64(n.data,e)}).then(function(e){n.data=e})}))}function hasUrlPrefix(e){if(!e.prefix)return!1;let t=parseUri(e.prefix).protocol;return t===`http`||t===`https`}function getHost(e,t){if(hasUrlPrefix(t)){let n=t.name.substr(t.prefix.length);e=t.prefix.replace(/\/?$/,`/`)+encodeURIComponent(n)}let n=parseUri(e);(n.user||n.password)&&(n.auth={username:n.user,password:n.password});let r=n.path.replace(/(^\/|\/$)/g,``).split(`/`);return n.db=r.pop(),n.db.indexOf(`%`)===-1&&(n.db=encodeURIComponent(n.db)),n.path=r.join(`/`),n}function genDBUrl(e,t){return genUrl(e,e.db+`/`+t)}function genUrl(e,t){let n=e.path?`/`:``;return e.protocol+`://`+e.host+(e.port?`:`+e.port:``)+`/`+e.path+n+t}function paramsToStr(e){let t=Object.keys(e);return t.length===0?``:`?`+t.map(t=>t+`=`+encodeURIComponent(e[t])).join(`&`)}function shouldCacheBust(e){let t=typeof navigator<`u`&&navigator.userAgent?navigator.userAgent.toLowerCase():``,n=t.indexOf(`msie`)!==-1,r=t.indexOf(`trident`)!==-1,a=t.indexOf(`edge`)!==-1,o=!(`method`in e)||e.method===`GET`;return(n||r||a)&&o}function HttpPouch(e,t){let n=this,r=getHost(e.name,e),a=genDBUrl(r,``);e=clone$1(e);let ourFetch=async function(t,n){if(n=n||{},n.headers=n.headers||new h$1,n.credentials=`include`,e.auth||r.auth){let t=e.auth||r.auth,a=t.username+`:`+t.password,o=thisBtoa(unescape(encodeURIComponent(a)));n.headers.set(`Authorization`,`Basic `+o)}let a=e.headers||{};return Object.keys(a).forEach(function(e){n.headers.append(e,a[e])}),shouldCacheBust(n)&&(t+=(t.indexOf(`?`)===-1?`?`:`&`)+`_nonce=`+Date.now()),await(e.fetch||f$1)(t,n)};function adapterFun$$1(e,t){return adapterFun(e,function(...e){setup().then(function(){return t.apply(this,e)}).catch(function(t){e.pop()(t)})}).bind(n)}async function fetchJSON(e,t){let n={};t=t||{},t.headers=t.headers||new h$1,t.headers.get(`Content-Type`)||t.headers.set(`Content-Type`,`application/json`),t.headers.get(`Accept`)||t.headers.set(`Accept`,`application/json`);let r=await ourFetch(e,t);if(n.ok=r.ok,n.status=r.status,n.data=await r.json(),!n.ok)throw n.data.status=n.status,generateErrorFromResponse$1(n.data);return Array.isArray(n.data)&&(n.data=n.data.map(function(e){return e.error||e.missing?generateErrorFromResponse$1(e):e})),n}let o;async function setup(){return e.skip_setup?Promise.resolve():o||(o=fetchJSON(a).catch(function(e){return e&&e.status&&e.status===404?(explainError(404,`PouchDB is just detecting if the remote exists.`),fetchJSON(a,{method:`PUT`})):Promise.reject(e)}).catch(function(e){return e&&e.status&&e.status===412?!0:Promise.reject(e)}),o.catch(function(){o=null}),o)}nextTick$1(function(){t(null,n)}),n._remote=!0,n.type=function(){return`http`},n.id=adapterFun$$1(`id`,async function(e){let t;try{t=await(await ourFetch(genUrl(r,``))).json()}catch{t={}}e(null,t&&t.uuid?t.uuid+r.db:genDBUrl(r,``))}),n.compact=adapterFun$$1(`compact`,async function(e,t){typeof e==`function`&&(t=e,e={}),e=clone$1(e),await fetchJSON(genDBUrl(r,`_compact`),{method:`POST`});function ping(){n.info(function(n,r){r&&!r.compact_running?t(null,{ok:!0}):setTimeout(ping,e.interval||200)})}ping()}),n.bulkGet=adapterFun(`bulkGet`,function(e,t){let n=this;async function doBulkGet(t){let n={};e.revs&&(n.revs=!0),e.attachments&&(n.attachments=!0),e.latest&&(n.latest=!0);try{let a=await fetchJSON(genDBUrl(r,`_bulk_get`+paramsToStr(n)),{method:`POST`,body:JSON.stringify({docs:e.docs})});e.attachments&&e.binary&&a.data.results.forEach(function(e){e.docs.forEach(readAttachmentsAsBlobOrBuffer)}),t(null,a.data)}catch(e){t(e)}}function doBulkGetShim(){let r=MAX_SIMULTANEOUS_REVS,a=Math.ceil(e.docs.length/r),o=0,s=Array(a);function onResult(e){return function(n,r){s[e]=r.results,++o===a&&t(null,{results:s.flat()})}}for(let t=0;t<a;t++){let a=pick$1(e,[`revs`,`attachments`,`binary`,`latest`]);a.docs=e.docs.slice(t*r,Math.min(e.docs.length,(t+1)*r)),bulkGet(n,a,onResult(t))}}let a=genUrl(r,``),o=supportsBulkGetMap[a];typeof o==`boolean`?o?doBulkGet(t):doBulkGetShim():doBulkGet(function(e,n){e?(supportsBulkGetMap[a]=!1,explainError(e.status,`PouchDB is just detecting if the remote supports the _bulk_get API.`),doBulkGetShim()):(supportsBulkGetMap[a]=!0,t(null,n))})}),n._info=async function(e){try{await setup();let t=await(await ourFetch(genDBUrl(r,``))).json();t.host=genDBUrl(r,``),e(null,t)}catch(t){e(t)}},n.fetch=async function(e,t){return await setup(),ourFetch(e.substring(0,1)===`/`?genUrl(r,e.substring(1)):genDBUrl(r,e),t)},n.get=adapterFun$$1(`get`,async function(e,t,n){typeof t==`function`&&(n=t,t={}),t=clone$1(t);let a={};t.revs&&(a.revs=!0),t.revs_info&&(a.revs_info=!0),t.latest&&(a.latest=!0),t.open_revs&&(t.open_revs!==`all`&&(t.open_revs=JSON.stringify(t.open_revs)),a.open_revs=t.open_revs),t.rev&&(a.rev=t.rev),t.conflicts&&(a.conflicts=t.conflicts),t.update_seq&&(a.update_seq=t.update_seq),e=encodeDocId(e);function fetchAttachments(e){let n=e._attachments,a=n&&Object.keys(n);if(!n||!a.length)return;async function fetchData(a){let o=n[a],s=await ourFetch(genDBUrl(r,encodeDocId(e._id)+`/`+encodeAttachmentId(a)+`?rev=`+e._rev)),c;c=`buffer`in s?await s.buffer():await s.blob();let l;if(t.binary){let e=Object.getOwnPropertyDescriptor(c.__proto__,`type`);(!e||e.set)&&(c.type=o.content_type),l=c}else l=await new Promise(function(e){blobToBase64(c,e)});delete o.stub,delete o.length,o.data=l}return pool(a.map(function(e){return function(){return fetchData(e)}}),5)}function fetchAllAttachments(e){return Array.isArray(e)?Promise.all(e.map(function(e){if(e.ok)return fetchAttachments(e.ok)})):fetchAttachments(e)}let o=genDBUrl(r,e+paramsToStr(a));try{let e=await fetchJSON(o);t.attachments&&await fetchAllAttachments(e.data),n(null,e.data)}catch(t){t.docId=e,n(t)}}),n.remove=adapterFun$$1(`remove`,async function(e,t,n,a){let o;typeof t==`string`?(o={_id:e,_rev:t},typeof n==`function`&&(a=n,n={})):(o=e,typeof t==`function`?(a=t,n={}):(a=n,n=t));let s=o._rev||n.rev,c=genDBUrl(r,encodeDocId(o._id))+`?rev=`+s;try{let e=await fetchJSON(c,{method:`DELETE`});a(null,e.data)}catch(e){a(e)}});function encodeAttachmentId(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}n.getAttachment=adapterFun$$1(`getAttachment`,async function(e,t,n,a){typeof n==`function`&&(a=n,n={});let o=n.rev?`?rev=`+n.rev:``,s=genDBUrl(r,encodeDocId(e))+`/`+encodeAttachmentId(t)+o;try{let e=await ourFetch(s,{method:`GET`});if(!e.ok)throw e;e.headers.get(`content-type`);let t;t=await e.blob(),a(null,t)}catch(e){a(e)}}),n.removeAttachment=adapterFun$$1(`removeAttachment`,async function(e,t,n,a){let o=genDBUrl(r,encodeDocId(e)+`/`+encodeAttachmentId(t))+`?rev=`+n;try{a(null,(await fetchJSON(o,{method:`DELETE`})).data)}catch(e){a(e)}}),n.putAttachment=adapterFun$$1(`putAttachment`,async function(e,t,n,a,o,s){typeof o==`function`&&(s=o,o=a,a=n,n=null);let c=genDBUrl(r,encodeDocId(e)+`/`+encodeAttachmentId(t));if(n&&(c+=`?rev=`+n),typeof a==`string`){let e;try{e=thisAtob$1(a)}catch{return s(createError$1(BAD_ARG$1,`Attachment is not a valid base64 string`))}a=e?binStringToBluffer$1(e,o):``}try{let e=await fetchJSON(c,{headers:new h$1({"Content-Type":o}),method:`PUT`,body:a});s(null,e.data)}catch(e){s(e)}}),n._bulkDocs=async function(e,t,n){e.new_edits=t.new_edits;try{await setup(),await Promise.all(e.docs.map(preprocessAttachments$1)),n(null,(await fetchJSON(genDBUrl(r,`_bulk_docs`),{method:`POST`,body:JSON.stringify(e)})).data)}catch(e){n(e)}},n._put=async function(e,t,n){try{await setup(),await preprocessAttachments$1(e),n(null,(await fetchJSON(genDBUrl(r,encodeDocId(e._id)),{method:`PUT`,body:JSON.stringify(e)})).data)}catch(t){t.docId=e&&e._id,n(t)}},n.allDocs=adapterFun$$1(`allDocs`,async function(e,t){typeof e==`function`&&(t=e,e={}),e=clone$1(e);let n={},a,o=`GET`;e.conflicts&&(n.conflicts=!0),e.update_seq&&(n.update_seq=!0),e.descending&&(n.descending=!0),e.include_docs&&(n.include_docs=!0),e.attachments&&(n.attachments=!0),e.key&&(n.key=JSON.stringify(e.key)),e.start_key&&(e.startkey=e.start_key),e.startkey&&(n.startkey=JSON.stringify(e.startkey)),e.end_key&&(e.endkey=e.end_key),e.endkey&&(n.endkey=JSON.stringify(e.endkey)),e.inclusive_end!==void 0&&(n.inclusive_end=!!e.inclusive_end),e.limit!==void 0&&(n.limit=e.limit),e.skip!==void 0&&(n.skip=e.skip);let s=paramsToStr(n);e.keys!==void 0&&(o=`POST`,a={keys:e.keys});try{let n=await fetchJSON(genDBUrl(r,`_all_docs`+s),{method:o,body:JSON.stringify(a)});e.include_docs&&e.attachments&&e.binary&&n.data.rows.forEach(readAttachmentsAsBlobOrBuffer),t(null,n.data)}catch(e){t(e)}}),n._changes=function(e){let t=`batch_size`in e?e.batch_size:CHANGES_BATCH_SIZE$1;e=clone$1(e),e.continuous&&!(`heartbeat`in e)&&(e.heartbeat=DEFAULT_HEARTBEAT);let n=`timeout`in e?e.timeout:30*1e3;`timeout`in e&&e.timeout&&n-e.timeout<CHANGES_TIMEOUT_BUFFER&&(n=e.timeout+CHANGES_TIMEOUT_BUFFER),`heartbeat`in e&&e.heartbeat&&n-e.heartbeat<CHANGES_TIMEOUT_BUFFER&&(n=e.heartbeat+CHANGES_TIMEOUT_BUFFER);let a={};`timeout`in e&&e.timeout&&(a.timeout=e.timeout);let o=e.limit===void 0?!1:e.limit,s=o;if(e.style&&(a.style=e.style),(e.include_docs||e.filter&&typeof e.filter==`function`)&&(a.include_docs=!0),e.attachments&&(a.attachments=!0),e.continuous&&(a.feed=`longpoll`),e.seq_interval&&(a.seq_interval=e.seq_interval),e.conflicts&&(a.conflicts=!0),e.descending&&(a.descending=!0),e.update_seq&&(a.update_seq=!0),`heartbeat`in e&&e.heartbeat&&(a.heartbeat=e.heartbeat),e.filter&&typeof e.filter==`string`&&(a.filter=e.filter),e.view&&typeof e.view==`string`&&(a.filter=`_view`,a.view=e.view),e.query_params&&typeof e.query_params==`object`)for(let t in e.query_params)Object.prototype.hasOwnProperty.call(e.query_params,t)&&(a[t]=e.query_params[t]);let c=`GET`,l;e.doc_ids?(a.filter=`_doc_ids`,c=`POST`,l={doc_ids:e.doc_ids}):e.selector&&(a.filter=`_selector`,c=`POST`,l={selector:e.selector});let u=new AbortController,d,fetchData=async function(n,p){if(e.aborted)return;a.since=n,typeof a.since==`object`&&(a.since=JSON.stringify(a.since)),e.descending?o&&(a.limit=s):a.limit=!o||s>t?t:s;let m=genDBUrl(r,`_changes`+paramsToStr(a)),g={signal:u.signal,method:c,body:JSON.stringify(l)};if(d=n,!e.aborted)try{await setup(),p(null,(await fetchJSON(m,g)).data)}catch(e){p(e)}},p={results:[]},fetched=function(n,r){if(e.aborted)return;let a=0;if(r&&r.results){a=r.results.length,p.last_seq=r.last_seq;let t=null,n=null;typeof r.pending==`number`&&(t=r.pending),(typeof p.last_seq==`string`||typeof p.last_seq==`number`)&&(n=p.last_seq);let o={};o.query=e.query_params,r.results=r.results.filter(function(r){s--;let a=filterChange(e)(r);return a&&(e.include_docs&&e.attachments&&e.binary&&readAttachmentsAsBlobOrBuffer(r),e.return_docs&&p.results.push(r),e.onChange(r,t,n)),a})}else if(n){e.aborted=!0,e.complete(n);return}r&&r.last_seq&&(d=r.last_seq);let c=o&&s<=0||r&&a<t||e.descending;e.continuous&&!(o&&s<=0)||!c?nextTick$1(function(){fetchData(d,fetched)}):e.complete(null,p)};return fetchData(e.since||0,fetched),{cancel:function(){e.aborted=!0,u.abort()}}},n.revsDiff=adapterFun$$1(`revsDiff`,async function(e,t,n){typeof t==`function`&&(n=t,t={});try{let t=await fetchJSON(genDBUrl(r,`_revs_diff`),{method:`POST`,body:JSON.stringify(e)});n(null,t.data)}catch(e){n(e)}}),n._close=function(e){e()},n._destroy=async function(e,t){try{t(null,await fetchJSON(genDBUrl(r,``),{method:`DELETE`}))}catch(e){e.status===404?t(null,{ok:!0}):t(e)}}}HttpPouch.valid=function(){return!0};function HttpPouch$1(e){e.adapter(`http`,HttpPouch,!1),e.adapter(`https`,HttpPouch,!1)}var QueryParseError$1=class QueryParseError$1 extends Error{static{__name(this,`QueryParseError`)}constructor(e){super(),this.status=400,this.name=`query_parse_error`,this.message=e,this.error=!0;try{Error.captureStackTrace(this,QueryParseError$1)}catch{}}},NotFoundError$1=class NotFoundError$1 extends Error{static{__name(this,`NotFoundError`)}constructor(e){super(),this.status=404,this.name=`not_found`,this.message=e,this.error=!0;try{Error.captureStackTrace(this,NotFoundError$1)}catch{}}},BuiltInError$1=class BuiltInError$1 extends Error{static{__name(this,`BuiltInError`)}constructor(e){super(),this.status=500,this.name=`invalid_value`,this.message=e,this.error=!0;try{Error.captureStackTrace(this,BuiltInError$1)}catch{}}};function promisedCallback$1(e,t){return t&&e.then(function(e){nextTick$1(function(){t(null,e)})},function(e){nextTick$1(function(){t(e)})}),e}__name(promisedCallback$1,`promisedCallback`);function callbackify$1(e){return function(...t){var n=t.pop(),r=e.apply(this,t);return typeof n==`function`&&promisedCallback$1(r,n),r}}__name(callbackify$1,`callbackify`);function fin$1(e,t){return e.then(function(e){return t().then(function(){return e})},function(e){return t().then(function(){throw e})})}__name(fin$1,`fin`);function sequentialize$1(e,t){return function(){var n=arguments,r=this;return e.add(function(){return t.apply(r,n)})}}__name(sequentialize$1,`sequentialize`);function uniq$2(e){var t=new Set(e),n=Array(t.size),r=-1;return t.forEach(function(e){n[++r]=e}),n}__name(uniq$2,`uniq`);function mapToKeysArray$1(e){var t=Array(e.size),n=-1;return e.forEach(function(e,r){t[++n]=r}),t}__name(mapToKeysArray$1,`mapToKeysArray`);function createBuiltInError(e){return new BuiltInError$1(`builtin `+e+` function requires map values to be numbers or number arrays`)}function sum(e){for(var t=0,n=0,r=e.length;n<r;n++){var a=e[n];if(typeof a!=`number`)if(Array.isArray(a)){t=typeof t==`number`?[t]:t;for(var o=0,s=a.length;o<s;o++){var c=a[o];if(typeof c!=`number`)throw createBuiltInError(`_sum`);t[o]===void 0?t.push(c):t[o]+=c}}else throw createBuiltInError(`_sum`);else typeof t==`number`?t+=a:t[0]+=a}return t}var log$1=guardedConsole$1.bind(null,`log`),isArray=Array.isArray,toJSON=JSON.parse;function evalFunctionWithEval(e,t){return scopeEval(`return (`+e.replace(/;\s*$/,``)+`);`,{emit:t,sum,log:log$1,isArray,toJSON})}var TaskQueue$1$1=class{static{__name(this,`TaskQueue$1`)}constructor(){this.promise=Promise.resolve()}add(e){return this.promise=this.promise.catch(()=>{}).then(()=>e()),this.promise}finish(){return this.promise}};function stringify$1(e){if(!e)return`undefined`;switch(typeof e){case`function`:return e.toString();case`string`:return e.toString();default:return JSON.stringify(e)}}__name(stringify$1,`stringify`);function createViewSignature$1(e,t){return stringify$1(e)+stringify$1(t)+`undefined`}__name(createViewSignature$1,`createViewSignature`);async function createView$1(e,t,n,r,a,o){let s=createViewSignature$1(n,r),c;if(!a&&(c=e._cachedViews=e._cachedViews||{},c[s]))return c[s];let l=e.info().then(async function(l){let u=l.db_name+`-mrview-`+(a?`temp`:stringMd5$1(s));function diffFunction(e){e.views=e.views||{};let n=t;n.indexOf(`/`)===-1&&(n=t+`/`+t);let r=e.views[n]=e.views[n]||{};if(!r[u])return r[u]=!0,e}await upsert$1(e,`_local/`+o,diffFunction);let d=(await e.registerDependentDatabase(u)).db;d.auto_compaction=!0;let p={name:u,db:d,sourceDB:e,adapter:e.adapter,mapFun:n,reduceFun:r},m;try{m=await p.db.get(`_local/lastSeq`)}catch(e){if(e.status!==404)throw e}return p.seq=m?m.seq:0,c&&p.db.once(`destroyed`,function(){delete c[s]}),p});return c&&(c[s]=l),l}__name(createView$1,`createView`);var persistentQueues$1={},tempViewQueue$1=new TaskQueue$1$1,CHANGES_BATCH_SIZE$1$1=50;function parseViewName$1(e){return e.indexOf(`/`)===-1?[e,e]:e.split(`/`)}__name(parseViewName$1,`parseViewName`);function isGenOne$1(e){return e.length===1&&/^1-/.test(e[0].rev)}__name(isGenOne$1,`isGenOne`);function emitError$1(e,t,n){try{e.emit(`error`,t)}catch{guardedConsole$1(`error`,`The user's map/reduce function threw an uncaught error.
@@ -224,7 +224,7 @@ Example:
224
224
  window.skuilder.pipeline.showLastRun()
225
225
  window.skuilder.pipeline.showRun(1)
226
226
  await window.skuilder.pipeline.diagnoseCardSpace()
227
- `)}},mountPipelineDebugger()}}),CompositeGenerator_exports={};__export(CompositeGenerator_exports,{AggregationMode:()=>AggregationMode,default:()=>CompositeGenerator});function mergeHints(e){let t=e.filter(e=>e!==void 0);if(t.length===0)return;let n={},r={};for(let e of t)for(let[t,n]of Object.entries(e.boostTags??{}))r[t]=(r[t]??1)*n;Object.keys(r).length>0&&(n.boostTags=r);let a={};for(let e of t)for(let[t,n]of Object.entries(e.boostCards??{}))a[t]=(a[t]??1)*n;Object.keys(a).length>0&&(n.boostCards=a);let concatUnique=e=>{let r=t.flatMap(t=>t[e]??[]);r.length>0&&(n[e]=[...new Set(r)])};concatUnique(`requireTags`),concatUnique(`requireCards`),concatUnique(`excludeTags`),concatUnique(`excludeCards`);let o=t.map(e=>e._label).filter(Boolean);return o.length>0&&(n._label=o.join(`; `)),Object.keys(n).length>0?n:void 0}var AggregationMode,DEFAULT_AGGREGATION_MODE,FREQUENCY_BOOST_FACTOR,CompositeGenerator,init_CompositeGenerator=__esm({"src/core/navigators/generators/CompositeGenerator.ts"(){init_navigators(),init_logger(),AggregationMode=(e=>(e.MAX=`max`,e.AVERAGE=`average`,e.FREQUENCY_BOOST=`frequencyBoost`,e))(AggregationMode||{}),DEFAULT_AGGREGATION_MODE=`frequencyBoost`,FREQUENCY_BOOST_FACTOR=.1,CompositeGenerator=class _CompositeGenerator extends ContentNavigator{constructor(e,t=DEFAULT_AGGREGATION_MODE){if(super(),_defineProperty(this,`name`,`Composite Generator`),_defineProperty(this,`generators`,void 0),_defineProperty(this,`aggregationMode`,void 0),this.generators=e,this.aggregationMode=t,e.length===0)throw Error(`CompositeGenerator requires at least one generator`);logger.debug(`[CompositeGenerator] Created with ${e.length} generators, mode: ${t}`)}static async fromStrategies(e,t,n,r=DEFAULT_AGGREGATION_MODE){return new _CompositeGenerator(await Promise.all(n.map(n=>ContentNavigator.create(e,t,n))),r)}async getWeightedCards(e,t){if(!t)throw Error(`CompositeGenerator.getWeightedCards requires a GeneratorContext. It should be called via Pipeline, not directly.`);let n=await Promise.all(this.generators.map(n=>n.getWeightedCards(e,t))),r=[];n.forEach((e,t)=>{let n=e.cards,a=this.generators[t].name||`Generator ${t}`,o=n.filter(e=>e.provenance[0]?.reason?.includes(`new card`)),s=n.filter(e=>e.provenance[0]?.reason?.includes(`review`));if(n.length>0){let e=Math.max(...n.map(e=>e.score)).toFixed(2),t=[];o.length>0&&t.push(`${o.length} new`),s.length>0&&t.push(`${s.length} reviews`);let c=t.length>0?t.join(`, `):`${n.length} cards`;r.push(`${a}: ${c} (top: ${e})`)}else r.push(`${a}: 0 cards`)}),logger.info(`[Composite] Generator breakdown: ${r.join(` | `)}`);let a=new Map;n.forEach((e,n)=>{let r=e.cards,o=this.generators[n],s=o.learnable?.weight??1,c;if(o.learnable&&!o.staticWeight&&t.orchestration){let e=o.strategyId;e&&(s=t.orchestration.getEffectiveWeight(e,o.learnable),c=t.orchestration.getDeviation(e))}for(let e of r){e.provenance.length>0&&(e.provenance[0].effectiveWeight=s,e.provenance[0].deviation=c);let t=a.get(e.cardId)||[];t.push({card:e,weight:s}),a.set(e.cardId,t)}});let o=[];for(let[,e]of a){let t=e.map(e=>e.card),n=this.aggregateScores(e),r=Math.max(0,n),a=t.flatMap(e=>e.provenance),s=t[0].score,c=r>s?`boosted`:r<s?`penalized`:`passed`,l=this.buildAggregationReason(e,r);o.push({...t[0],score:r,provenance:[...a,{strategy:`composite`,strategyName:`Composite Generator`,strategyId:`COMPOSITE_GENERATOR`,action:c,score:r,reason:l}]})}return{cards:o.sort((e,t)=>t.score-e.score).slice(0,e),hints:mergeHints(n.map(e=>e.hints))}}buildAggregationReason(e,t){let n=e.map(e=>e.card),r=n.length,a=n.map(e=>e.score.toFixed(2)).join(`, `);if(r===1){let n=Math.abs(e[0].weight-1)>.001?` (w=${e[0].weight.toFixed(2)})`:``;return`Single generator, score ${t.toFixed(2)}${n}`}let o=n.map(e=>e.provenance[0]?.strategy||`unknown`).join(`, `);switch(this.aggregationMode){case`max`:return`Max of ${r} generators (${o}): scores [${a}] \u2192 ${t.toFixed(2)}`;case`average`:return`Weighted Avg of ${r} generators (${o}): scores [${a}] \u2192 ${t.toFixed(2)}`;case`frequencyBoost`:{let n=e.reduce((e,t)=>e+t.weight,0),a=e.reduce((e,t)=>e+t.card.score*t.weight,0),s=n>0?a/n:0,c=1+FREQUENCY_BOOST_FACTOR*(r-1);return`Frequency boost from ${r} generators (${o}): w-avg ${s.toFixed(2)} \xD7 ${c.toFixed(2)} \u2192 ${t.toFixed(2)}`}default:return`Aggregated from ${r} generators: ${t.toFixed(2)}`}}aggregateScores(e){let t=e.map(e=>e.card.score);switch(this.aggregationMode){case`max`:return Math.max(...t);case`average`:{let t=e.reduce((e,t)=>e+t.weight,0);return t===0?0:e.reduce((e,t)=>e+t.card.score*t.weight,0)/t}case`frequencyBoost`:{let t=e.reduce((e,t)=>e+t.weight,0),n=e.reduce((e,t)=>e+t.card.score*t.weight,0);return(t>0?n/t:0)*(1+FREQUENCY_BOOST_FACTOR*(e.length-1))}default:return t[0]}}}}}),elo_exports={};__export(elo_exports,{default:()=>ELONavigator});var ELONavigator,init_elo=__esm({"src/core/navigators/generators/elo.ts"(){init_navigators(),init_logger(),ELONavigator=class extends ContentNavigator{constructor(e,t,n){super(e,t,n),_defineProperty(this,`name`,void 0),this.name=n?.name||`ELO`}async getWeightedCards(e,t){let n;n=t?.userElo===void 0?toCourseElo((await this.user.getCourseRegDoc(this.course.getCourseID())).elo).global.score:t.userElo;let r=await this.user.getActiveCards(),a=(await this.course.getCardsCenteredAtELO({limit:e,elo:`user`},e=>!r.some(t=>e.cardID===t.cardID))).map(e=>({...e,status:`new`})),o=a.map(e=>e.cardID),s=await this.course.getCardEloData(o),c=a.map((e,t)=>{let r=s[t]?.global?.score??1e3,a=Math.abs(r-n),o=Math.max(0,1-a/500),c=o>0?Math.random()**(1/o):0;return{cardId:e.cardID,courseId:e.courseID,score:c,provenance:[{strategy:`elo`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-ELO-default`,action:`generated`,score:c,reason:`ELO distance ${Math.round(a)} (card: ${Math.round(r)}, user: ${Math.round(n)}), raw ${o.toFixed(3)}, key ${c.toFixed(3)}`}]}});c.sort((e,t)=>t.score-e.score);let l=c.slice(0,e);if(l.length>0){let e=l.slice(0,3).map(e=>e.score.toFixed(2)).join(`, `);logger.info(`[ELO] Course ${this.course.getCourseID()}: ${l.length} new cards (top scores: ${e})`)}else logger.info(`[ELO] Course ${this.course.getCourseID()}: No new cards available`);return{cards:l}}}}}),generators_exports={},init_generators=__esm({"src/core/navigators/generators/index.ts"(){}}),prescribed_exports={};__export(prescribed_exports,{default:()=>PrescribedCardsGenerator});function dedupe(e){return[...new Set(e)]}function isoNow(){return new Date().toISOString()}function clamp(e,t,n){return Math.max(t,Math.min(n,e))}function matchesTagPattern(e,t){if(t===`*`)return!0;let n=t.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${n}$`).test(e)}function extractWordStem(e){for(let t of[`c-ml-`,`c-ws-`,`c-spelling-`])if(e.startsWith(t)){let n=e.slice(t.length),r=n.lastIndexOf(`-`);return r>0?n.slice(0,r):n}return e}function shuffleInPlace(e){for(let t=e.length-1;t>0;t--){let n=Math.floor(Math.random()*(t+1));[e[t],e[n]]=[e[n],e[t]]}}function pickTopByScore(e,t){return[...e].sort((e,t)=>t.score-e.score||e.cardId.localeCompare(t.cardId)).slice(0,t)}var DEFAULT_FRESHNESS_WINDOW,DEFAULT_MAX_DIRECT_PER_RUN,DEFAULT_MAX_SUPPORT_PER_RUN,DEFAULT_HIERARCHY_DEPTH,DEFAULT_MIN_COUNT,BASE_TARGET_SCORE,BASE_SUPPORT_SCORE,DISCOVERED_SUPPORT_SCORE,MAX_TARGET_MULTIPLIER,MAX_SUPPORT_MULTIPLIER,PRESCRIBED_DEBUG_VERSION,PrescribedCardsGenerator,init_prescribed=__esm({"src/core/navigators/generators/prescribed.ts"(){init_navigators(),init_logger(),DEFAULT_FRESHNESS_WINDOW=3,DEFAULT_MAX_DIRECT_PER_RUN=3,DEFAULT_MAX_SUPPORT_PER_RUN=3,DEFAULT_HIERARCHY_DEPTH=2,DEFAULT_MIN_COUNT=3,BASE_TARGET_SCORE=1,BASE_SUPPORT_SCORE=.8,DISCOVERED_SUPPORT_SCORE=12,MAX_TARGET_MULTIPLIER=8,MAX_SUPPORT_MULTIPLIER=4,PRESCRIBED_DEBUG_VERSION=`testversion-prescribed-v3`,PrescribedCardsGenerator=class extends ContentNavigator{constructor(e,t,n){super(e,t,n),_defineProperty(this,`name`,void 0),_defineProperty(this,`config`,void 0),this.name=n.name||`Prescribed Cards`,this.config=this.parseConfig(n.serializedData),logger.debug(`[Prescribed] Initialized with ${this.config.groups.length} groups and ${this.config.groups.reduce((e,t)=>e+t.targetCardIds.length,0)} targets`)}get strategyKey(){return`PrescribedProgress`}async getWeightedCards(e,t){if(this.config.groups.length===0||e<=0)return{cards:[]};let n=this.course.getCourseID(),r=await this.user.getActiveCards(),a=new Set(r.map(e=>e.cardID)),o=await this.user.getSeenCards(n).catch(()=>[]),s=new Set(o),c=await this.getStrategyState()??{updatedAt:isoNow(),groups:{}},l=await this.loadHierarchyConfigs(),u=await this.user.getCourseRegDoc(n).catch(()=>null),d=typeof u?.elo==`number`?u.elo:u?.elo?.global?.score??t?.userElo??1e3,p=typeof u?.elo==`number`?{}:u?.elo?.tags??{},m=dedupe(this.config.groups.flatMap(e=>e.targetCardIds)),g=dedupe(this.config.groups.flatMap(e=>e.supportCardIds??[])),_=dedupe([...m,...g]),v=_.length>0?await this.course.getAppliedTagsBatch(_):new Map,y=await this.course.getCourseTagStubs().catch(()=>({rows:[],offset:0,total_rows:0})),b=new Map;for(let e of y.rows??[]){let t=e.doc;t?.name&&Array.isArray(t.taggedCards)&&b.set(t.name,[...t.taggedCards])}let x={updatedAt:isoNow(),groups:{}},S=[],C=new Set,w=[];for(let e of this.config.groups){let t=this.buildGroupRuntimeState({group:e,priorState:c.groups[e.id],activeIds:a,seenIds:s,tagsByCard:v,cardsByTag:b,hierarchyConfigs:l,userTagElo:p,userGlobalElo:d});w.push(t),logger.info(`[Prescribed] Group '${e.id}': ${e.targetCardIds.length} targets total, ${t.encounteredTargets.size} encountered, ${t.pendingTargets.length} pending (${t.surfaceableTargets.length} surfaceable, ${t.blockedTargets.length} blocked), ${t.supportCandidates.length} authored support candidates, ${t.discoveredSupportCandidates.length} discovered support candidates, pressure=${t.pressureMultiplier.toFixed(2)}`),t.blockedTargets.length>0&&(logger.info(`[Prescribed] Group '${e.id}' blocked targets: ${t.blockedTargets.join(`, `)}`),logger.info(`[Prescribed] Group '${e.id}' support tags needed: ${t.supportTags.join(`, `)||`(none)`}`),logger.info(`[Prescribed] Group '${e.id}' escalation mode: `+(t.supportCandidates.length>0?`direct-support`:t.discoveredSupportCandidates.length>0?`inserted-support-candidates`:`boost-only`)),t.discoveredSupportCandidates.length>0&&logger.info(`[Prescribed] Group '${e.id}' discovered support candidates: ${t.discoveredSupportCandidates.join(`, `)}`)),x.groups[e.id]=this.buildNextGroupState(t,c.groups[e.id]);let r=this.buildDirectTargetCards(t,n,C),o=this.buildSupportCards(t,n,C),u=this.buildDiscoveredSupportCards(t,n,C);S.push(...r,...o,...u)}let T=this.buildSupportHintSummary(w),E=Object.keys(T.boostTags).length>0?{boostTags:T.boostTags,_label:`prescribed-support (${T.supportTags.length} tags; blocked=${T.blockedTargetIds.length}; testversion=${PRESCRIBED_DEBUG_VERSION})`}:void 0;if(E){let e=Object.entries(E.boostTags??{});logger.info(`[Prescribed] Emitting ${e.length} boost hint(s): `+e.map(([e,t])=>`${e}\xD7${t.toFixed(1)}`).join(`, `))}else logger.info(`[Prescribed] No hints to emit (no blocked targets or no support tags)`);if(S.length===0)return logger.info(`[Prescribed] 0 cards emitted (all targets blocked, authored/discovered support candidates exhausted)`+(E?` — boost hints emitted but may not survive filters`:``)),await this.putStrategyState(x).catch(e=>{logger.debug(`[Prescribed] Failed to persist empty-state update: ${e}`)}),E?{cards:[],hints:E}:{cards:[]};let D=pickTopByScore(S,e),O=new Map;for(let e of D){let t=e.provenance[0],n=t?.reason.match(/group=([^;]+)/)?.[1],r=t?.reason.includes(`mode=support`)?`supportIds`:`targetIds`;n&&(O.has(n)||O.set(n,{targetIds:[],supportIds:[]}),O.get(n)[r].push(e.cardId))}for(let e of this.config.groups){let t=x.groups[e.id],n=O.get(e.id);n&&(n.targetIds.length>0||n.supportIds.length>0)&&(t.lastSurfacedAt=isoNow(),t.sessionsSinceSurfaced=0,n.supportIds.length>0&&(t.lastSupportAt=isoNow()))}return await this.putStrategyState(x).catch(e=>{logger.debug(`[Prescribed] Failed to persist prescribed progress: ${e}`)}),logger.info(`[Prescribed] Emitting ${D.length} cards (${D.filter(e=>e.provenance[0]?.reason.includes(`mode=target`)).length} target, ${D.filter(e=>e.provenance[0]?.reason.includes(`mode=support`)).length} support, ${D.filter(e=>e.provenance[0]?.reason.includes(`mode=discovered-support`)).length} discovered support)`),E?{cards:D,hints:E}:{cards:D}}buildSupportHintSummary(e){let t={},n=new Set,r=new Set;for(let a of e)if(!(a.blockedTargets.length===0||a.supportTags.length===0)){a.blockedTargets.forEach(e=>n.add(e));for(let e of a.supportTags)r.add(e),t[e]=(t[e]??1)*a.supportMultiplier}return{boostTags:t,blockedTargetIds:[...n].sort(),supportTags:[...r].sort()}}parseConfig(e){try{let t=JSON.parse(e);return{groups:(Array.isArray(t.groups)?t.groups:[]).map((e,t)=>({id:typeof e.id==`string`&&e.id.trim().length>0?e.id:`group-${t+1}`,targetCardIds:dedupe(Array.isArray(e.targetCardIds)?e.targetCardIds.filter(e=>typeof e==`string`):[]),supportCardIds:dedupe(Array.isArray(e.supportCardIds)?e.supportCardIds.filter(e=>typeof e==`string`):[]),supportTagPatterns:dedupe(Array.isArray(e.supportTagPatterns)?e.supportTagPatterns.filter(e=>typeof e==`string`):[]),freshnessWindowSessions:typeof e.freshnessWindowSessions==`number`?e.freshnessWindowSessions:DEFAULT_FRESHNESS_WINDOW,maxDirectTargetsPerRun:typeof e.maxDirectTargetsPerRun==`number`?e.maxDirectTargetsPerRun:DEFAULT_MAX_DIRECT_PER_RUN,maxSupportCardsPerRun:typeof e.maxSupportCardsPerRun==`number`?e.maxSupportCardsPerRun:DEFAULT_MAX_SUPPORT_PER_RUN,hierarchyWalk:{enabled:e.hierarchyWalk?.enabled!==!1,maxDepth:typeof e.hierarchyWalk?.maxDepth==`number`?e.hierarchyWalk.maxDepth:DEFAULT_HIERARCHY_DEPTH},retireOnEncounter:e.retireOnEncounter!==!1})).filter(e=>e.targetCardIds.length>0)}}catch{return{groups:[]}}}async loadHierarchyConfigs(){try{return(await this.course.getAllNavigationStrategies()).filter(e=>e.implementingClass===`hierarchyDefinition`).map(e=>{try{return{prerequisites:JSON.parse(e.serializedData).prerequisites||{}}}catch{return{prerequisites:{}}}})}catch(e){return logger.debug(`[Prescribed] Failed to load hierarchy configs: ${e}`),[]}}buildGroupRuntimeState(e){let{group:t,priorState:n,activeIds:r,seenIds:a,tagsByCard:o,cardsByTag:s,hierarchyConfigs:c,userTagElo:l,userGlobalElo:u}=e,d=new Set;for(let e of t.targetCardIds)(r.has(e)||a.has(e))&&d.add(e);if(n?.encounteredCardIds?.length)for(let e of n.encounteredCardIds)d.add(e);let p=t.targetCardIds.filter(e=>!d.has(e)),m=new Map;for(let e of p)m.set(e,o.get(e)??[]);let g=[],_=[],v=new Set;for(let e of p){let n=m.get(e)??[],r=this.resolveBlockedSupportTags(n,c,l,u,t.hierarchyWalk?.enabled!==!1,t.hierarchyWalk?.maxDepth??DEFAULT_HIERARCHY_DEPTH),a=n.filter(e=>e.startsWith(`gpc:intro:`)),o=new Set(n.filter(e=>e.startsWith(`gpc:expose:`)));for(let e of a){let t=e.slice(10);t&&o.add(`gpc:expose:${t}`)}let s=[...o].filter(e=>{let t=l[e];return!t||t.count<DEFAULT_MIN_COUNT});s.length>0&&s.forEach(e=>v.add(e)),r.blocked||s.length>0?(g.push(e),r.supportTags.forEach(e=>v.add(e))):_.push(e)}let y=dedupe([...t.supportCardIds??[],...this.findSupportCardsByTags(t,o,[...v])]).filter(e=>!r.has(e)&&!a.has(e)),b=g.length>0&&v.size>0&&y.length===0?this.findDiscoveredSupportCards({supportTags:[...v],cardsByTag:s,activeIds:r,seenIds:a,excludedIds:new Set([...t.targetCardIds,...t.supportCardIds??[]]),limit:t.maxSupportCardsPerRun??DEFAULT_MAX_SUPPORT_PER_RUN}):[];g.length>0&&v.size>0&&b.length===0&&logger.info(`[Prescribed] Group '${t.id}' discovered 0 broader support candidates (blocked=${g.length}; authoredSupport=${y.length})`);let x=n?.sessionsSinceSurfaced??0,S=t.freshnessWindowSessions??DEFAULT_FRESHNESS_WINDOW,C=Math.max(0,x-S),w=p.length===0?1:clamp(1+C*.75+Math.min(2,p.length*.1),1,MAX_TARGET_MULTIPLIER),T=g.length===0?1:clamp(1+C*.5+Math.min(1.5,g.length*.15),1,MAX_SUPPORT_MULTIPLIER);return{group:t,encounteredTargets:d,pendingTargets:p,blockedTargets:g,surfaceableTargets:_,targetTags:m,supportCandidates:y,discoveredSupportCandidates:b,supportTags:[...v],pressureMultiplier:w,supportMultiplier:T,debugVersion:PRESCRIBED_DEBUG_VERSION}}buildNextGroupState(e,t){let n=t?.sessionsSinceSurfaced??0,r=!1;return{encounteredCardIds:[...e.encounteredTargets].sort(),pendingTargetIds:[...e.pendingTargets].sort(),lastSurfacedAt:t?.lastSurfacedAt??null,sessionsSinceSurfaced:n+1,lastSupportAt:t?.lastSupportAt??null,blockedTargetIds:[...e.blockedTargets].sort(),lastResolvedSupportTags:[...e.supportTags].sort()}}buildDirectTargetCards(e,t,n){let r=e.group.maxDirectTargetsPerRun??DEFAULT_MAX_DIRECT_PER_RUN,a=e.surfaceableTargets.filter(e=>!n.has(e)).slice(0,r),o=[];for(let r of a)n.add(r),o.push({cardId:r,courseId:t,score:BASE_TARGET_SCORE*e.pressureMultiplier,provenance:[{strategy:`prescribed`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-prescribed`,action:`generated`,score:BASE_TARGET_SCORE*e.pressureMultiplier,reason:`mode=target;group=${e.group.id};pending=${e.pendingTargets.length};surfaceable=${e.surfaceableTargets.length};blocked=${e.blockedTargets.length};blockedTargets=${e.blockedTargets.join(`|`)||`none`};supportTags=${e.supportTags.join(`|`)||`none`};multiplier=${e.pressureMultiplier.toFixed(2)};testversion=${e.debugVersion}`}]});return o}buildSupportCards(e,t,n){if(e.blockedTargets.length===0||e.supportCandidates.length===0)return[];let r=e.group.maxSupportCardsPerRun??DEFAULT_MAX_SUPPORT_PER_RUN,a=e.supportCandidates.filter(e=>!n.has(e)).slice(0,r),o=[];for(let r of a)n.add(r),o.push({cardId:r,courseId:t,score:BASE_SUPPORT_SCORE*e.supportMultiplier,provenance:[{strategy:`prescribed`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-prescribed`,action:`generated`,score:BASE_SUPPORT_SCORE*e.supportMultiplier,reason:`mode=support;group=${e.group.id};pending=${e.pendingTargets.length};blocked=${e.blockedTargets.length};blockedTargets=${e.blockedTargets.join(`|`)||`none`};supportCard=${r};supportTags=${e.supportTags.join(`|`)||`none`};multiplier=${e.supportMultiplier.toFixed(2)};testversion=${e.debugVersion}`}]});return o}buildDiscoveredSupportCards(e,t,n){if(e.blockedTargets.length===0||e.discoveredSupportCandidates.length===0)return[];let r=e.group.maxSupportCardsPerRun??DEFAULT_MAX_SUPPORT_PER_RUN,a=e.discoveredSupportCandidates.filter(e=>!n.has(e)).slice(0,r),o=[];for(let r of a)n.add(r),o.push({cardId:r,courseId:t,score:DISCOVERED_SUPPORT_SCORE*e.supportMultiplier,provenance:[{strategy:`prescribed`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-prescribed`,action:`generated`,score:DISCOVERED_SUPPORT_SCORE*e.supportMultiplier,reason:`mode=discovered-support;group=${e.group.id};pending=${e.pendingTargets.length};blocked=${e.blockedTargets.length};blockedTargets=${e.blockedTargets.join(`|`)||`none`};supportCard=${r};supportTags=${e.supportTags.join(`|`)||`none`};multiplier=${e.supportMultiplier.toFixed(2)};testversion=${e.debugVersion}`}]});return o}findSupportCardsByTags(e,t,n){if(n.length===0)return[];let r=e.supportCardIds??[],a=e.supportTagPatterns??[];if(r.length===0&&a.length===0)return[];let o=new Set;for(let e of r){let r=t.get(e)??[],s=n.some(e=>r.includes(e)),c=a.some(e=>r.some(t=>matchesTagPattern(t,e)));(s||c)&&o.add(e)}return[...o]}findDiscoveredSupportCards(e){let{supportTags:t,cardsByTag:n,activeIds:r,seenIds:a,excludedIds:o,limit:s}=e,c=new Map;for(let e of t){let t=n.get(e)??[];for(let e of t){if(r.has(e)||a.has(e)||o.has(e))continue;let t=c.get(e);t?t.matches+=1:c.set(e,{cardId:e,matches:1})}}let l=[...c.values()].sort((e,t)=>t.matches-e.matches||e.cardId.localeCompare(t.cardId)),u=new Set,d=[],p=[];for(let e of l){let t=extractWordStem(e.cardId);u.has(t)?p.push(e):(u.add(t),d.push(e))}return shuffleInPlace(d),shuffleInPlace(p),[...d,...p].slice(0,s).map(e=>e.cardId)}resolveBlockedSupportTags(e,t,n,r,a,o){let s=new Set,c=!1;for(let l of e){let e=t.map(e=>e.prerequisites[l]).filter(e=>Array.isArray(e)&&e.length>0);if(e.length!==0&&e.some(e=>e.some(e=>!this.isPrerequisiteMet(e,n[e.tag],r)))){if(c=!0,!a){for(let t of e)for(let e of t)this.isPrerequisiteMet(e,n[e.tag],r)||s.add(e.tag);continue}for(let a of e)for(let e of a)this.isPrerequisiteMet(e,n[e.tag],r)||this.collectSupportTagsRecursive(e.tag,t,n,r,o,new Set,s)}}return{blocked:c,supportTags:[...s]}}collectSupportTagsRecursive(e,t,n,r,a,o,s){if(a<0||o.has(e))return;o.add(e);let c=!1;for(let l of t){let u=l.prerequisites[e];if(!u||u.length===0)continue;let d=u.filter(e=>!this.isPrerequisiteMet(e,n[e.tag],r));if(d.length>0&&a>0){c=!0;for(let e of d)this.collectSupportTagsRecursive(e.tag,t,n,r,a-1,o,s)}}c||s.add(e)}isPrerequisiteMet(e,t,n){if(!t)return!1;let r=e.masteryThreshold?.minCount??DEFAULT_MIN_COUNT;return t.count<r?!1:e.masteryThreshold?.minElo===void 0?e.masteryThreshold?.minCount===void 0?t.score>=n:!0:t.score>=e.masteryThreshold.minElo}}}}),srs_exports={};__export(srs_exports,{default:()=>SRSNavigator});var DEFAULT_HEALTHY_BACKLOG,MAX_BACKLOG_PRESSURE,SRSNavigator,init_srs=__esm({"src/core/navigators/generators/srs.ts"(){init_navigators(),init_logger(),DEFAULT_HEALTHY_BACKLOG=20,MAX_BACKLOG_PRESSURE=.5,SRSNavigator=class extends ContentNavigator{constructor(e,t,n){super(e,t,n),_defineProperty(this,`name`,void 0),_defineProperty(this,`healthyBacklog`,void 0),this.name=n?.name||`SRS`,this.healthyBacklog=this.parseConfig(n?.serializedData).healthyBacklog??DEFAULT_HEALTHY_BACKLOG}parseConfig(e){if(!e)return{};try{return JSON.parse(e)}catch{return logger.warn(`[SRS] Failed to parse strategy config, using defaults`),{}}}async getWeightedCards(e,t){if(!this.user||!this.course)throw Error(`SRSNavigator requires user and course to be set`);let n=this.course.getCourseID(),r=await this.user.getPendingReviews(n),a=hooks.utc(),o=r.filter(e=>a.isAfter(hooks.utc(e.reviewTime))),s=this.computeBacklogPressure(o.length);if(o.length>0){let e=s>0?` [backlog pressure: +${s.toFixed(2)}]`:` [healthy backlog]`;logger.info(`[SRS] Course ${n}: ${o.length} reviews due now (of ${r.length} scheduled)${e}`)}else if(r.length>0){let e=[...r].sort((e,t)=>hooks.utc(e.reviewTime).diff(hooks.utc(t.reviewTime)))[0],t=hooks.utc(e.reviewTime),o=hooks.duration(t.diff(a)),s=o.asHours()<1?`${Math.round(o.asMinutes())}m`:o.asHours()<24?`${Math.round(o.asHours())}h`:`${Math.round(o.asDays())}d`;logger.info(`[SRS] Course ${n}: 0 reviews due now (${r.length} scheduled, next in ${s})`)}else logger.info(`[SRS] Course ${n}: No reviews scheduled`);return{cards:o.map(e=>{let{score:t,reason:n}=this.computeUrgencyScore(e,a,s);return{cardId:e.cardId,courseId:e.courseId,score:t,reviewID:e._id,provenance:[{strategy:`srs`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-SRS-default`,action:`generated`,score:t,reason:n}]}}).sort((e,t)=>t.score-e.score).slice(0,e)}}computeBacklogPressure(e){if(e<=this.healthyBacklog)return 0;let t=(e-this.healthyBacklog)/this.healthyBacklog*(MAX_BACKLOG_PRESSURE/2);return Math.min(MAX_BACKLOG_PRESSURE,t)}computeUrgencyScore(e,t,n){let r=hooks.utc(e.scheduledAt),a=hooks.utc(e.reviewTime),o=Math.max(1,a.diff(r,`hours`)),s=t.diff(a,`hours`),c=s/o,l=.3+.7*Math.exp(-o/720),u=.5+(Math.min(1,Math.max(0,c))*.5+l*.5)*.45,d=Math.min(1,u+n),p=[`${Math.round(s)}h overdue`,`interval: ${Math.round(o)}h`,`relative: ${c.toFixed(2)}`,`recency: ${l.toFixed(2)}`];return n>0&&p.push(`backlog: +${n.toFixed(2)}`),p.push(`review`),{score:d,reason:p.join(`, `)}}}}}),types_exports={},init_types=__esm({"src/core/navigators/generators/types.ts"(){}}),globImport_generators,init_=__esm({'import("./generators/**/*") in src/core/navigators/index.ts'(){globImport_generators=__glob({"./generators/CompositeGenerator.ts":()=>Promise.resolve().then(()=>(init_CompositeGenerator(),CompositeGenerator_exports)),"./generators/elo.ts":()=>Promise.resolve().then(()=>(init_elo(),elo_exports)),"./generators/index.ts":()=>Promise.resolve().then(()=>(init_generators(),generators_exports)),"./generators/prescribed.ts":()=>Promise.resolve().then(()=>(init_prescribed(),prescribed_exports)),"./generators/srs.ts":()=>Promise.resolve().then(()=>(init_srs(),srs_exports)),"./generators/types.ts":()=>Promise.resolve().then(()=>(init_types(),types_exports))})}}),DEFAULT_LEARNABLE_WEIGHT,init_contentNavigationStrategy=__esm({"src/core/types/contentNavigationStrategy.ts"(){DEFAULT_LEARNABLE_WEIGHT={weight:1,confidence:.1,sampleSize:0}}}),WeightedFilter_exports={};__export(WeightedFilter_exports,{WeightedFilter:()=>WeightedFilter});var WeightedFilter,init_WeightedFilter=__esm({"src/core/navigators/filters/WeightedFilter.ts"(){init_contentNavigationStrategy(),WeightedFilter=class{constructor(e,t=DEFAULT_LEARNABLE_WEIGHT,n=!1,r){_defineProperty(this,`name`,void 0),_defineProperty(this,`inner`,void 0),_defineProperty(this,`learnable`,void 0),_defineProperty(this,`staticWeight`,void 0),_defineProperty(this,`strategyId`,void 0),this.inner=e,this.name=e.name,this.learnable=t,this.staticWeight=n,this.strategyId=r}async transform(e,t){let n=this.learnable.weight,r;if(!this.staticWeight&&t.orchestration){let e=this.strategyId||this.inner.strategyId||this.name;n=t.orchestration.getEffectiveWeight(e,this.learnable),r=t.orchestration.getDeviation(e)}if(Math.abs(n-1)<.001)return this.inner.transform(e,t);let a=new Map;for(let t of e)a.set(t.cardId,t.score);return(await this.inner.transform(e,t)).map(e=>{let t=a.get(e.cardId);if(t===void 0||t===0||e.score===0)return e;let o=e.score/t;if(Math.abs(o-1)<1e-4)return e;let s=t*o**+n,c=e.provenance.length-1,l=e.provenance[c];if(l){let t=[...e.provenance];return t[c]={...l,score:s,effectiveWeight:n,deviation:r},{...e,score:s,provenance:t}}return{...e,score:s}})}}}}),eloDistance_exports={};__export(eloDistance_exports,{DEFAULT_HALF_LIFE:()=>DEFAULT_HALF_LIFE,DEFAULT_MAX_MULTIPLIER:()=>DEFAULT_MAX_MULTIPLIER,DEFAULT_MIN_MULTIPLIER:()=>DEFAULT_MIN_MULTIPLIER,createEloDistanceFilter:()=>createEloDistanceFilter});function computeMultiplier(e,t,n,r){let a=e/t,o=Math.exp(-(a*a));return n+(r-n)*o}function createEloDistanceFilter(e){let t=e?.halfLife??DEFAULT_HALF_LIFE,n=e?.minMultiplier??DEFAULT_MIN_MULTIPLIER,r=e?.maxMultiplier??DEFAULT_MAX_MULTIPLIER;return{name:`ELO Distance Filter`,async transform(e,a){let{course:o,userElo:s}=a,c=e.map(e=>e.cardId),l=await o.getCardEloData(c);return e.map((e,a)=>{let o=l[a]?.global?.score??1e3,c=Math.abs(o-s),u=computeMultiplier(c,t,n,r),d=e.score*u,p=u<r-.01?`penalized`:`passed`;return{...e,score:d,provenance:[...e.provenance,{strategy:`eloDistance`,strategyName:`ELO Distance Filter`,strategyId:`ELO_DISTANCE_FILTER`,action:p,score:d,reason:`ELO distance ${Math.round(c)} (card: ${Math.round(o)}, user: ${Math.round(s)}) \u2192 ${u.toFixed(2)}x`}]}})}}}var DEFAULT_HALF_LIFE,DEFAULT_MIN_MULTIPLIER,DEFAULT_MAX_MULTIPLIER,init_eloDistance=__esm({"src/core/navigators/filters/eloDistance.ts"(){DEFAULT_HALF_LIFE=200,DEFAULT_MIN_MULTIPLIER=.3,DEFAULT_MAX_MULTIPLIER=1}}),hierarchyDefinition_exports={};__export(hierarchyDefinition_exports,{default:()=>HierarchyDefinitionNavigator});var DEFAULT_MIN_COUNT2,HierarchyDefinitionNavigator,init_hierarchyDefinition=__esm({"src/core/navigators/filters/hierarchyDefinition.ts"(){init_navigators(),init_logger(),DEFAULT_MIN_COUNT2=3,HierarchyDefinitionNavigator=class extends ContentNavigator{constructor(e,t,n){super(e,t,n),_defineProperty(this,`config`,void 0),_defineProperty(this,`name`,void 0),this.config=this.parseConfig(n.serializedData),this.name=n.name||`Hierarchy Definition`}parseConfig(e){try{return{prerequisites:JSON.parse(e).prerequisites||{}}}catch{return{prerequisites:{}}}}isPrerequisiteMet(e,t,n){if(!t)return!1;let r=e.masteryThreshold?.minCount??DEFAULT_MIN_COUNT2;return t.count<r?!1:e.masteryThreshold?.minElo===void 0?e.masteryThreshold?.minCount===void 0?t.score>=n:!0:t.score>=e.masteryThreshold.minElo}async getMasteredTags(e){let t=new Set;try{let n=toCourseElo((await e.user.getCourseRegDoc(e.course.getCourseID())).elo);for(let e of Object.values(this.config.prerequisites))for(let r of e){let e=n.tags[r.tag];this.isPrerequisiteMet(r,e,n.global.score)&&t.add(r.tag)}}catch{}return t}getUnlockedTags(e){let t=new Set;for(let[n,r]of Object.entries(this.config.prerequisites))r.every(t=>e.has(t.tag))&&t.add(n);return t}hasPrerequisites(e){return e in this.config.prerequisites}async checkCardUnlock(e,t,n,r){try{let t=e.tags??[],a=t.filter(e=>this.hasPrerequisites(e)&&!n.has(e));return a.length===0?{isUnlocked:!0,reason:`Prerequisites met, tags: ${t.length>0?t.join(`, `):`none`}`}:{isUnlocked:!1,reason:`Blocked: missing prerequisites ${a.flatMap(e=>(this.config.prerequisites[e]||[]).filter(e=>!r.has(e.tag)).map(e=>e.tag)).join(`, `)} for tags ${a.join(`, `)}`}}catch{return{isUnlocked:!0,reason:`Prerequisites check skipped (tag lookup failed)`}}}getPreReqBoosts(e,t){let n=new Map;for(let[r,a]of Object.entries(this.config.prerequisites))if(!e.has(r))for(let e of a){if(!e.preReqBoost||e.preReqBoost<=1||t.has(e.tag))continue;let r=n.get(e.tag)??1;n.set(e.tag,Math.max(r,e.preReqBoost))}return n}getTargetBoosts(e){let t=new Map,n=Object.keys(this.config.prerequisites),r=[...e];logger.info(`[HierarchyDefinition:targetBoost:trace] ${this.name} | configKeys=${n.length}, unlocked=${r.length} (${r.slice(0,5).join(`, `)}${r.length>5?`...`:``})`);for(let[n,r]of Object.entries(this.config.prerequisites))if(e.has(n)){logger.info(`[HierarchyDefinition:targetBoost:trace] UNLOCKED ${n}: ${r.length} prereqs, raw=${JSON.stringify(r.map(e=>({tag:e.tag,tb:e.targetBoost})))}`);for(let e of r){if(!e.targetBoost||e.targetBoost<=1)continue;let r=t.get(n)??1;t.set(n,Math.max(r,e.targetBoost))}}return t.size>0?logger.info(`[HierarchyDefinition] targetBoosts active: ${[...t.entries()].map(([e,t])=>`${e}=\xD7${t}`).join(`, `)}`):logger.info(`[HierarchyDefinition:targetBoost:trace] no targetBoosts found despite ${r.length} unlocked tags`),t}async transform(e,t){let n=await this.getMasteredTags(t),r=this.getUnlockedTags(n),a=this.getPreReqBoosts(r,n),o=this.getTargetBoosts(r),s=[];for(let c of e){let{isUnlocked:e,reason:l}=await this.checkCardUnlock(c,t.course,r,n),u=e?c.score:c.score*.02,d=e?`passed`:`penalized`,p=l;if(e&&a.size>0){let e=c.tags??[],t=1,n=[];for(let r of e){let e=a.get(r);e&&e>t&&(t=e,n.push(r))}t>1&&(u*=t,d=`boosted`,p=`${l} | preReqBoost \xD7${t.toFixed(2)} for ${n.join(`, `)}`,logger.info(`[HierarchyDefinition] preReqBoost \xD7${t.toFixed(2)} applied to card ${c.cardId} via tags [${n.join(`, `)}] (score: ${c.score.toFixed(3)} \u2192 ${u.toFixed(3)})`))}if(e&&o.size>0){let e=c.tags??[],t=1,n=[];for(let r of e){let e=o.get(r);e&&e>t&&(t=e,n.push(r))}t>1&&(u*=t,d=`boosted`,p=`${p} | targetBoost \xD7${t.toFixed(2)} for ${n.join(`, `)}`,logger.info(`[HierarchyDefinition] targetBoost \xD7${t.toFixed(2)} applied to card ${c.cardId} via tags [${n.join(`, `)}] (score: ${c.score.toFixed(3)} \u2192 ${u.toFixed(3)})`))}s.push({...c,score:u,provenance:[...c.provenance,{strategy:`hierarchyDefinition`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-hierarchy`,action:d,score:u,reason:p}]})}return s}async getWeightedCards(e){throw Error(`HierarchyDefinitionNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().`)}}}}),userTagPreference_exports={};__export(userTagPreference_exports,{default:()=>UserTagPreferenceFilter});var UserTagPreferenceFilter,init_userTagPreference=__esm({"src/core/navigators/filters/userTagPreference.ts"(){init_navigators(),UserTagPreferenceFilter=class extends ContentNavigator{constructor(e,t,n){super(e,t,n),_defineProperty(this,`_strategyData`,void 0),_defineProperty(this,`name`,void 0),this._strategyData=n,this.name=n.name||`User Tag Preferences`}computeMultiplier(e,t){let n=e.map(e=>t[e]).filter(e=>e!==void 0);return n.length===0?1:Math.max(...n)}buildReason(e,t,n){let r=e.filter(e=>t[e]===n);return n===0?`Excluded by user preference: ${r.join(`, `)} (${n}x)`:n<1?`Penalized by user preference: ${r.join(`, `)} (${n.toFixed(2)}x)`:n>1?`Boosted by user preference: ${r.join(`, `)} (${n.toFixed(2)}x)`:`No matching user preferences`}async transform(e,t){let n=await this.getStrategyState();return!n||Object.keys(n.boost).length===0?e.map(e=>({...e,provenance:[...e.provenance,{strategy:`userTagPreference`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||this._strategyData._id,action:`passed`,score:e.score,reason:`No user tag preferences configured`}]})):await Promise.all(e.map(async e=>{let t=e.tags??[],r=this.computeMultiplier(t,n.boost),a=Math.min(1,e.score*r),o;return o=r===0||r<1?`penalized`:r>1?`boosted`:`passed`,{...e,score:a,provenance:[...e.provenance,{strategy:`userTagPreference`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||this._strategyData._id,action:o,score:a,reason:this.buildReason(t,n.boost,r)}]}}))}async getWeightedCards(e){throw Error(`UserTagPreferenceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().`)}}}}),filters_exports={};__export(filters_exports,{UserTagPreferenceFilter:()=>UserTagPreferenceFilter,createEloDistanceFilter:()=>createEloDistanceFilter});var init_filters=__esm({"src/core/navigators/filters/index.ts"(){init_eloDistance(),init_userTagPreference()}}),inferredPreferenceStub_exports={};__export(inferredPreferenceStub_exports,{INFERRED_PREFERENCE_NAVIGATOR_STUB:()=>INFERRED_PREFERENCE_NAVIGATOR_STUB});var INFERRED_PREFERENCE_NAVIGATOR_STUB,init_inferredPreferenceStub=__esm({"src/core/navigators/filters/inferredPreferenceStub.ts"(){INFERRED_PREFERENCE_NAVIGATOR_STUB=!0}}),interferenceMitigator_exports={};__export(interferenceMitigator_exports,{default:()=>InterferenceMitigatorNavigator});var DEFAULT_MIN_COUNT3,DEFAULT_MIN_ELAPSED_DAYS,DEFAULT_INTERFERENCE_DECAY,InterferenceMitigatorNavigator,init_interferenceMitigator=__esm({"src/core/navigators/filters/interferenceMitigator.ts"(){init_navigators(),DEFAULT_MIN_COUNT3=10,DEFAULT_MIN_ELAPSED_DAYS=3,DEFAULT_INTERFERENCE_DECAY=.8,InterferenceMitigatorNavigator=class extends ContentNavigator{constructor(e,t,n){super(e,t,n),_defineProperty(this,`config`,void 0),_defineProperty(this,`name`,void 0),_defineProperty(this,`interferenceMap`,void 0),this.config=this.parseConfig(n.serializedData),this.interferenceMap=this.buildInterferenceMap(),this.name=n.name||`Interference Mitigator`}parseConfig(e){try{let t=JSON.parse(e),n=t.interferenceSets||[];return n.length>0&&Array.isArray(n[0])&&(n=n.map(e=>({tags:e}))),{interferenceSets:n,maturityThreshold:{minCount:t.maturityThreshold?.minCount??DEFAULT_MIN_COUNT3,minElo:t.maturityThreshold?.minElo,minElapsedDays:t.maturityThreshold?.minElapsedDays??DEFAULT_MIN_ELAPSED_DAYS},defaultDecay:t.defaultDecay??DEFAULT_INTERFERENCE_DECAY}}catch{return{interferenceSets:[],maturityThreshold:{minCount:DEFAULT_MIN_COUNT3,minElapsedDays:DEFAULT_MIN_ELAPSED_DAYS},defaultDecay:DEFAULT_INTERFERENCE_DECAY}}}buildInterferenceMap(){let e=new Map;for(let t of this.config.interferenceSets){let n=t.decay??this.config.defaultDecay??DEFAULT_INTERFERENCE_DECAY;for(let r of t.tags){e.has(r)||e.set(r,[]);let a=e.get(r);for(let e of t.tags)if(e!==r){let t=a.find(t=>t.partner===e);t?t.decay=Math.max(t.decay,n):a.push({partner:e,decay:n})}}}return e}async getImmatureTags(e){let t=new Set;try{let n=toCourseElo((await e.user.getCourseRegDoc(e.course.getCourseID())).elo),r=this.config.maturityThreshold?.minCount??DEFAULT_MIN_COUNT3,a=this.config.maturityThreshold?.minElo,o=(this.config.maturityThreshold?.minElapsedDays??DEFAULT_MIN_ELAPSED_DAYS)*2;for(let[e,s]of Object.entries(n.tags)){if(s.count===0)continue;let n=s.count<r,c=a!==void 0&&s.score<a,l=s.count<o;(n||c||l)&&t.add(e)}}catch{}return t}getTagsToAvoid(e){let t=new Map;for(let n of e){let r=this.interferenceMap.get(n);if(r){for(let{partner:n,decay:a}of r)if(!e.has(n)){let e=t.get(n)??0;t.set(n,Math.max(e,a))}}}return t}computeInterferenceEffect(e,t,n){if(t.size===0)return{multiplier:1,interferingTags:[],reason:`No interference detected`};let r=1,a=[];for(let n of e){let e=t.get(n);e!==void 0&&(a.push(n),r*=1-e)}if(a.length===0)return{multiplier:1,interferingTags:[],reason:`No interference detected`};let o=new Set;for(let e of a)for(let t of n)this.interferenceMap.get(t)?.some(t=>t.partner===e)&&o.add(t);let s=`Interferes with immature tags ${Array.from(o).join(`, `)} (tags: ${a.join(`, `)}, multiplier: ${r.toFixed(2)})`;return{multiplier:r,interferingTags:a,reason:s}}async transform(e,t){let n=await this.getImmatureTags(t),r=this.getTagsToAvoid(n),a=[];for(let t of e){let e=t.tags??[],{multiplier:o,reason:s}=this.computeInterferenceEffect(e,r,n),c=t.score*o,l=o<1?`penalized`:o>1?`boosted`:`passed`;a.push({...t,score:c,provenance:[...t.provenance,{strategy:`interferenceMitigator`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-interference`,action:l,score:c,reason:s}]})}return a}async getWeightedCards(e){throw Error(`InterferenceMitigatorNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().`)}}}}),relativePriority_exports={};__export(relativePriority_exports,{default:()=>RelativePriorityNavigator});var DEFAULT_PRIORITY,DEFAULT_PRIORITY_INFLUENCE,DEFAULT_COMBINE_MODE,RelativePriorityNavigator,init_relativePriority=__esm({"src/core/navigators/filters/relativePriority.ts"(){init_navigators(),DEFAULT_PRIORITY=.5,DEFAULT_PRIORITY_INFLUENCE=.5,DEFAULT_COMBINE_MODE=`max`,RelativePriorityNavigator=class extends ContentNavigator{constructor(e,t,n){super(e,t,n),_defineProperty(this,`config`,void 0),_defineProperty(this,`name`,void 0),this.config=this.parseConfig(n.serializedData),this.name=n.name||`Relative Priority`}parseConfig(e){try{let t=JSON.parse(e);return{tagPriorities:t.tagPriorities||{},defaultPriority:t.defaultPriority??DEFAULT_PRIORITY,combineMode:t.combineMode??DEFAULT_COMBINE_MODE,priorityInfluence:t.priorityInfluence??DEFAULT_PRIORITY_INFLUENCE}}catch{return{tagPriorities:{},defaultPriority:DEFAULT_PRIORITY,combineMode:DEFAULT_COMBINE_MODE,priorityInfluence:DEFAULT_PRIORITY_INFLUENCE}}}getTagPriority(e){return this.config.tagPriorities[e]??this.config.defaultPriority??DEFAULT_PRIORITY}computeCardPriority(e){if(e.length===0)return this.config.defaultPriority??DEFAULT_PRIORITY;let t=e.map(e=>this.getTagPriority(e));switch(this.config.combineMode){case`max`:return Math.max(...t);case`min`:return Math.min(...t);case`average`:return t.reduce((e,t)=>e+t,0)/t.length;default:return Math.max(...t)}}computeBoostFactor(e){let t=this.config.priorityInfluence??DEFAULT_PRIORITY_INFLUENCE;return 1+(e-.5)*t}buildPriorityReason(e,t,n,r){if(e.length===0)return`No tags, neutral priority (${t.toFixed(2)})`;let a=e.slice(0,3).join(`, `),o=e.length>3?` (+${e.length-3} more)`:``;return n===1?`Neutral priority (${t.toFixed(2)}) for tags: ${a}${o}`:n>1?`High-priority tags: ${a}${o} (priority ${t.toFixed(2)} \u2192 boost ${n.toFixed(2)}x \u2192 ${r.toFixed(2)})`:`Low-priority tags: ${a}${o} (priority ${t.toFixed(2)} \u2192 reduce ${n.toFixed(2)}x \u2192 ${r.toFixed(2)})`}async transform(e,t){return await Promise.all(e.map(async e=>{let t=e.tags??[],n=this.computeCardPriority(t),r=this.computeBoostFactor(n),a=Math.max(0,e.score*r),o=r>1?`boosted`:r<1?`penalized`:`passed`,s=this.buildPriorityReason(t,n,r,a);return{...e,score:a,provenance:[...e.provenance,{strategy:`relativePriority`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-priority`,action:o,score:a,reason:s}]}}))}async getWeightedCards(e){throw Error(`RelativePriorityNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().`)}}}}),types_exports2={},init_types2=__esm({"src/core/navigators/filters/types.ts"(){}}),userGoalStub_exports={};__export(userGoalStub_exports,{USER_GOAL_NAVIGATOR_STUB:()=>USER_GOAL_NAVIGATOR_STUB});var USER_GOAL_NAVIGATOR_STUB,init_userGoalStub=__esm({"src/core/navigators/filters/userGoalStub.ts"(){USER_GOAL_NAVIGATOR_STUB=!0}}),globImport_filters,init_2=__esm({'import("./filters/**/*") in src/core/navigators/index.ts'(){globImport_filters=__glob({"./filters/WeightedFilter.ts":()=>Promise.resolve().then(()=>(init_WeightedFilter(),WeightedFilter_exports)),"./filters/eloDistance.ts":()=>Promise.resolve().then(()=>(init_eloDistance(),eloDistance_exports)),"./filters/hierarchyDefinition.ts":()=>Promise.resolve().then(()=>(init_hierarchyDefinition(),hierarchyDefinition_exports)),"./filters/index.ts":()=>Promise.resolve().then(()=>(init_filters(),filters_exports)),"./filters/inferredPreferenceStub.ts":()=>Promise.resolve().then(()=>(init_inferredPreferenceStub(),inferredPreferenceStub_exports)),"./filters/interferenceMitigator.ts":()=>Promise.resolve().then(()=>(init_interferenceMitigator(),interferenceMitigator_exports)),"./filters/relativePriority.ts":()=>Promise.resolve().then(()=>(init_relativePriority(),relativePriority_exports)),"./filters/types.ts":()=>Promise.resolve().then(()=>(init_types2(),types_exports2)),"./filters/userGoalStub.ts":()=>Promise.resolve().then(()=>(init_userGoalStub(),userGoalStub_exports)),"./filters/userTagPreference.ts":()=>Promise.resolve().then(()=>(init_userTagPreference(),userTagPreference_exports))})}});function aggregateOutcomesForGradient(e,t){let n=[];for(let r of e){let e=r.deviations[t];e!==void 0&&n.push({deviation:e,outcomeValue:r.outcomeValue,weight:1})}return logger.debug(`[Orchestration] Aggregated ${n.length} observations for strategy ${t}`),n}function computeStrategyGradient(e){let t=e.length;if(t<3)return logger.debug(`[Orchestration] Insufficient observations for gradient (${t} < 3)`),null;let n=0,r=0,a=0;for(let t of e){let e=t.weight??1;n+=t.deviation*e,r+=t.outcomeValue*e,a+=e}let o=n/a,s=r/a,c=0,l=0,u=0;for(let t of e){let e=t.weight??1,n=t.deviation-o,r=t.outcomeValue-s;c+=e*n*r,l+=e*n*n,u+=e*r*r}if(l<1e-10)return logger.debug(`[Orchestration] No variance in deviations, cannot compute gradient`),{gradient:0,intercept:s,rSquared:0,sampleSize:t};let d=c/l,p=s-d*o,m=0;for(let t of e){let e=t.weight??1,n=d*t.deviation+p,r=t.outcomeValue-n;m+=e*r*r}let g=u>1e-10?1-m/u:0;return logger.debug(`[Orchestration] Computed gradient: ${d.toFixed(4)}, intercept: ${p.toFixed(4)}, R\xB2: ${g.toFixed(4)}, n=${t}`),{gradient:d,intercept:p,rSquared:Math.max(0,Math.min(1,g)),sampleSize:t}}var init_gradient=__esm({"src/core/orchestration/gradient.ts"(){init_logger()}});function updateStrategyWeight(e,t){if(t.sampleSize<MIN_OBSERVATIONS_FOR_UPDATE)return logger.debug(`[Orchestration] Insufficient samples (${t.sampleSize} < ${MIN_OBSERVATIONS_FOR_UPDATE}), keeping current weight`),{...e,sampleSize:e.sampleSize+t.sampleSize};let n=t.rSquared>=MIN_R_SQUARED_FOR_GRADIENT,r=Math.abs(t.gradient)<FLAT_GRADIENT_THRESHOLD,a=e.weight,o=e.confidence;if(!n||r){let n=.05*(1-e.confidence);o=Math.min(1,e.confidence+n),logger.debug(`[Orchestration] Flat/unreliable gradient (|g|=${Math.abs(t.gradient).toFixed(4)}, R\xB2=${t.rSquared.toFixed(4)}). Increasing confidence: ${e.confidence.toFixed(3)} \u2192 ${o.toFixed(3)}`)}else{let n=t.gradient*LEARNING_RATE;n=Math.max(-MAX_WEIGHT_DELTA,Math.min(MAX_WEIGHT_DELTA,n)),a=e.weight+n,a=Math.max(.1,Math.min(3,a));let r=.02*(1-e.confidence);o=Math.min(1,e.confidence+r),logger.debug(`[Orchestration] Adjusting weight: ${e.weight.toFixed(3)} \u2192 ${a.toFixed(3)} (gradient=${t.gradient.toFixed(4)}, delta=${n.toFixed(4)})`)}return{weight:a,confidence:o,sampleSize:e.sampleSize+t.sampleSize}}function updateLearningState(e,t,n,r,a){let o=new Date().toISOString(),s=`STRATEGY_LEARNING_STATE::${e}::${t}`,c={timestamp:o,weight:n.weight,confidence:n.confidence,gradient:r.gradient},l=a?.history??[];return l=[...l,c],l.length>MAX_HISTORY_LENGTH&&(l=l.slice(l.length-MAX_HISTORY_LENGTH)),{_id:s,_rev:a?._rev,docType:`STRATEGY_LEARNING_STATE`,courseId:e,strategyId:t,currentWeight:n,regression:{gradient:r.gradient,intercept:r.intercept,rSquared:r.rSquared,sampleSize:r.sampleSize,computedAt:o},history:l,updatedAt:o}}function runPeriodUpdate(e){let{courseId:t,strategyId:n,currentWeight:r,gradient:a,existingState:o}=e;logger.info(`[Orchestration] Running period update for strategy ${n} (${a.sampleSize} observations)`);let s=updateStrategyWeight(r,a),c=s.weight!==r.weight,l=updateLearningState(t,n,s,a,o);return logger.info(`[Orchestration] Period update complete for ${n}: weight ${r.weight.toFixed(3)} \u2192 ${s.weight.toFixed(3)}, confidence ${r.confidence.toFixed(3)} \u2192 ${s.confidence.toFixed(3)}`),{strategyId:n,previousWeight:r,newWeight:s,gradient:a,learningState:l,updated:c}}function getDefaultLearnableWeight(){return{...DEFAULT_LEARNABLE_WEIGHT}}var MIN_OBSERVATIONS_FOR_UPDATE,LEARNING_RATE,MAX_WEIGHT_DELTA,MIN_R_SQUARED_FOR_GRADIENT,FLAT_GRADIENT_THRESHOLD,MAX_HISTORY_LENGTH,init_learning=__esm({"src/core/orchestration/learning.ts"(){init_contentNavigationStrategy(),init_types_legacy(),init_logger(),MIN_OBSERVATIONS_FOR_UPDATE=10,LEARNING_RATE=.1,MAX_WEIGHT_DELTA=.3,MIN_R_SQUARED_FOR_GRADIENT=.05,FLAT_GRADIENT_THRESHOLD=.02,MAX_HISTORY_LENGTH=100}});function computeOutcomeSignal(e,t={}){if(!e||e.length===0)return null;let n=t.targetAccuracy??.85,r=t.tolerance??.05,a=0;for(let t of e)t.isCorrect&&a++;return scoreAccuracyInZone(a/e.length,n,r)}function scoreAccuracyInZone(e,t,n){let r=Math.abs(e-t);if(r<=n)return 1;let a=r-n;return Math.max(0,1-a*2.5)}var init_signal=__esm({"src/core/orchestration/signal.ts"(){}});async function recordUserOutcome(e,t,n,r,a,o=0,s=0,c){let{user:l,course:u,userId:d}=e,p=u.getCourseID(),m=computeOutcomeSignal(r,c);if(m===null){logger.debug(`[Orchestration] No outcome signal computed for ${d} (insufficient data). Skipping record.`);return}let g={};for(let t of a)g[t]=e.getDeviation(t);let _=`USER_OUTCOME::${p}::${d}::${n}`,v={_id:_,docType:`USER_OUTCOME`,courseId:p,userId:d,periodStart:t,periodEnd:n,outcomeValue:m,deviations:g,metadata:{sessionsCount:1,cardsSeen:r.length,eloStart:o,eloEnd:s,signalType:`accuracy_in_zone`}};try{await l.putUserOutcome(v),logger.debug(`[Orchestration] Recorded outcome ${m.toFixed(3)} for ${d} (doc: ${_})`)}catch(e){logger.error(`[Orchestration] Failed to record outcome: ${e}`)}}var init_recording=__esm({"src/core/orchestration/recording.ts"(){init_signal(),init_types_legacy(),init_logger()}});function fnv1a(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}function computeDeviation(e,t,n){return fnv1a(`${e}:${t}:${n}`)/4294967296*2-1}function computeSpread(e){return MAX_SPREAD-Math.max(0,Math.min(1,e))*(MAX_SPREAD-MIN_SPREAD)}function computeEffectiveWeight(e,t,n,r){let a=computeDeviation(t,n,r)*computeSpread(e.confidence)*e.weight,o=e.weight+a;return Math.max(MIN_WEIGHT,Math.min(MAX_WEIGHT,o))}async function createOrchestrationContext(e,t){let n;try{n=await t.getCourseConfig()}catch(e){logger.error(`[Orchestration] Failed to load course config: ${e}`),n={name:`Unknown`,description:``,public:!1,deleted:!1,creator:``,admins:[],moderators:[],dataShapes:[],questionTypes:[],orchestration:{salt:`default`}}}let r=e.getUsername(),a=n.orchestration?.salt||`default_salt`;return{user:e,course:t,userId:r,courseConfig:n,getEffectiveWeight(e,t){return computeEffectiveWeight(t,r,e,a)},getDeviation(e){return computeDeviation(r,e,a)}}}var MIN_SPREAD,MAX_SPREAD,MIN_WEIGHT,MAX_WEIGHT,init_orchestration=__esm({"src/core/orchestration/index.ts"(){init_logger(),init_gradient(),init_learning(),init_signal(),init_recording(),MIN_SPREAD=.1,MAX_SPREAD=.5,MIN_WEIGHT=.1,MAX_WEIGHT=3}}),Pipeline_exports={};__export(Pipeline_exports,{Pipeline:()=>Pipeline});function globToRegex(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function globMatch(e,t){return t.includes(`*`)?globToRegex(t).test(e):e===t}function cardMatchesTagPattern(e,t){return(e.tags??[]).some(e=>globMatch(e,t))}function mergeHints2(e){let t=e.filter(e=>e!=null);if(t.length===0)return;let n={},r={};for(let e of t)for(let[t,n]of Object.entries(e.boostTags??{}))r[t]=(r[t]??1)*n;Object.keys(r).length>0&&(n.boostTags=r);let a={};for(let e of t)for(let[t,n]of Object.entries(e.boostCards??{}))a[t]=(a[t]??1)*n;Object.keys(a).length>0&&(n.boostCards=a);let concatUnique=e=>{let r=t.flatMap(t=>t[e]??[]);r.length>0&&(n[e]=[...new Set(r)])};concatUnique(`requireTags`),concatUnique(`requireCards`),concatUnique(`excludeTags`),concatUnique(`excludeCards`);let o=t.map(e=>e._label).filter(Boolean);return o.length>0&&(n._label=o.join(`; `)),Object.keys(n).length>0?n:void 0}function logPipelineConfig(e,t){let n=t.length>0?`
227
+ `)}},mountPipelineDebugger()}}),CompositeGenerator_exports={};__export(CompositeGenerator_exports,{AggregationMode:()=>AggregationMode,default:()=>CompositeGenerator});function mergeHints(e){let t=e.filter(e=>e!==void 0);if(t.length===0)return;let n={},r={};for(let e of t)for(let[t,n]of Object.entries(e.boostTags??{}))r[t]=(r[t]??1)*n;Object.keys(r).length>0&&(n.boostTags=r);let a={};for(let e of t)for(let[t,n]of Object.entries(e.boostCards??{}))a[t]=(a[t]??1)*n;Object.keys(a).length>0&&(n.boostCards=a);let concatUnique=e=>{let r=t.flatMap(t=>t[e]??[]);r.length>0&&(n[e]=[...new Set(r)])};concatUnique(`requireTags`),concatUnique(`requireCards`),concatUnique(`excludeTags`),concatUnique(`excludeCards`);let o=t.map(e=>e._label).filter(Boolean);return o.length>0&&(n._label=o.join(`; `)),Object.keys(n).length>0?n:void 0}var AggregationMode,DEFAULT_AGGREGATION_MODE,FREQUENCY_BOOST_FACTOR,CompositeGenerator,init_CompositeGenerator=__esm({"src/core/navigators/generators/CompositeGenerator.ts"(){init_navigators(),init_logger(),AggregationMode=(e=>(e.MAX=`max`,e.AVERAGE=`average`,e.FREQUENCY_BOOST=`frequencyBoost`,e))(AggregationMode||{}),DEFAULT_AGGREGATION_MODE=`frequencyBoost`,FREQUENCY_BOOST_FACTOR=.1,CompositeGenerator=class _CompositeGenerator extends ContentNavigator{constructor(e,t=DEFAULT_AGGREGATION_MODE){if(super(),_defineProperty(this,`name`,`Composite Generator`),_defineProperty(this,`generators`,void 0),_defineProperty(this,`aggregationMode`,void 0),this.generators=e,this.aggregationMode=t,e.length===0)throw Error(`CompositeGenerator requires at least one generator`);logger.debug(`[CompositeGenerator] Created with ${e.length} generators, mode: ${t}`)}static async fromStrategies(e,t,n,r=DEFAULT_AGGREGATION_MODE){return new _CompositeGenerator(await Promise.all(n.map(n=>ContentNavigator.create(e,t,n))),r)}async getWeightedCards(e,t){if(!t)throw Error(`CompositeGenerator.getWeightedCards requires a GeneratorContext. It should be called via Pipeline, not directly.`);let n=await Promise.all(this.generators.map(n=>n.getWeightedCards(e,t))),r=[];n.forEach((e,t)=>{let n=e.cards,a=this.generators[t].name||`Generator ${t}`,o=n.filter(e=>e.provenance[0]?.reason?.includes(`new card`)),s=n.filter(e=>e.provenance[0]?.reason?.includes(`review`));if(n.length>0){let e=Math.max(...n.map(e=>e.score)).toFixed(2),t=[];o.length>0&&t.push(`${o.length} new`),s.length>0&&t.push(`${s.length} reviews`);let c=t.length>0?t.join(`, `):`${n.length} cards`;r.push(`${a}: ${c} (top: ${e})`)}else r.push(`${a}: 0 cards`)}),logger.info(`[Composite] Generator breakdown: ${r.join(` | `)}`);let a=new Map;n.forEach((e,n)=>{let r=e.cards,o=this.generators[n],s=o.learnable?.weight??1,c;if(o.learnable&&!o.staticWeight&&t.orchestration){let e=o.strategyId;e&&(s=t.orchestration.getEffectiveWeight(e,o.learnable),c=t.orchestration.getDeviation(e))}for(let e of r){e.provenance.length>0&&(e.provenance[0].effectiveWeight=s,e.provenance[0].deviation=c);let t=a.get(e.cardId)||[];t.push({card:e,weight:s}),a.set(e.cardId,t)}});let o=[];for(let[,e]of a){let t=e.map(e=>e.card),n=this.aggregateScores(e),r=Math.max(0,n),a=t.flatMap(e=>e.provenance),s=t[0].score,c=r>s?`boosted`:r<s?`penalized`:`passed`,l=this.buildAggregationReason(e,r);o.push({...t[0],score:r,provenance:[...a,{strategy:`composite`,strategyName:`Composite Generator`,strategyId:`COMPOSITE_GENERATOR`,action:c,score:r,reason:l}]})}return{cards:o.sort((e,t)=>t.score-e.score).slice(0,e),hints:mergeHints(n.map(e=>e.hints))}}buildAggregationReason(e,t){let n=e.map(e=>e.card),r=n.length,a=n.map(e=>e.score.toFixed(2)).join(`, `);if(r===1){let n=Math.abs(e[0].weight-1)>.001?` (w=${e[0].weight.toFixed(2)})`:``;return`Single generator, score ${t.toFixed(2)}${n}`}let o=n.map(e=>e.provenance[0]?.strategy||`unknown`).join(`, `);switch(this.aggregationMode){case`max`:return`Max of ${r} generators (${o}): scores [${a}] \u2192 ${t.toFixed(2)}`;case`average`:return`Weighted Avg of ${r} generators (${o}): scores [${a}] \u2192 ${t.toFixed(2)}`;case`frequencyBoost`:{let n=e.reduce((e,t)=>e+t.weight,0),a=e.reduce((e,t)=>e+t.card.score*t.weight,0),s=n>0?a/n:0,c=1+FREQUENCY_BOOST_FACTOR*(r-1);return`Frequency boost from ${r} generators (${o}): w-avg ${s.toFixed(2)} \xD7 ${c.toFixed(2)} \u2192 ${t.toFixed(2)}`}default:return`Aggregated from ${r} generators: ${t.toFixed(2)}`}}aggregateScores(e){let t=e.map(e=>e.card.score);switch(this.aggregationMode){case`max`:return Math.max(...t);case`average`:{let t=e.reduce((e,t)=>e+t.weight,0);return t===0?0:e.reduce((e,t)=>e+t.card.score*t.weight,0)/t}case`frequencyBoost`:{let t=e.reduce((e,t)=>e+t.weight,0),n=e.reduce((e,t)=>e+t.card.score*t.weight,0);return(t>0?n/t:0)*(1+FREQUENCY_BOOST_FACTOR*(e.length-1))}default:return t[0]}}}}}),elo_exports={};__export(elo_exports,{default:()=>ELONavigator});var ELONavigator,init_elo=__esm({"src/core/navigators/generators/elo.ts"(){init_navigators(),init_logger(),ELONavigator=class extends ContentNavigator{constructor(e,t,n){super(e,t,n),_defineProperty(this,`name`,void 0),this.name=n?.name||`ELO`}async getWeightedCards(e,t){let n;n=t?.userElo===void 0?toCourseElo((await this.user.getCourseRegDoc(this.course.getCourseID())).elo).global.score:t.userElo;let r=await this.user.getActiveCards(),a=(await this.course.getCardsCenteredAtELO({limit:e,elo:`user`},e=>!r.some(t=>e.cardID===t.cardID))).map(e=>({...e,status:`new`})),o=a.map(e=>e.cardID),s=await this.course.getCardEloData(o),c=a.map((e,t)=>{let r=s[t]?.global?.score??1e3,a=Math.abs(r-n),o=Math.max(0,1-a/500),c=o>0?Math.random()**(1/o):0;return{cardId:e.cardID,courseId:e.courseID,score:c,provenance:[{strategy:`elo`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-ELO-default`,action:`generated`,score:c,reason:`ELO distance ${Math.round(a)} (card: ${Math.round(r)}, user: ${Math.round(n)}), raw ${o.toFixed(3)}, key ${c.toFixed(3)}`}]}});c.sort((e,t)=>t.score-e.score);let l=c.slice(0,e);if(l.length>0){let e=l.slice(0,3).map(e=>e.score.toFixed(2)).join(`, `);logger.info(`[ELO] Course ${this.course.getCourseID()}: ${l.length} new cards (top scores: ${e})`)}else logger.info(`[ELO] Course ${this.course.getCourseID()}: No new cards available`);return{cards:l}}}}}),generators_exports={},init_generators=__esm({"src/core/navigators/generators/index.ts"(){}}),prescribed_exports={};__export(prescribed_exports,{default:()=>PrescribedCardsGenerator});function dedupe(e){return[...new Set(e)]}function isoNow(){return new Date().toISOString()}function clamp(e,t,n){return Math.max(t,Math.min(n,e))}function matchesTagPattern(e,t){if(t===`*`)return!0;let n=t.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${n}$`).test(e)}function extractWordStem(e){for(let t of[`c-ml-`,`c-ws-`,`c-spelling-`])if(e.startsWith(t)){let n=e.slice(t.length),r=n.lastIndexOf(`-`);return r>0?n.slice(0,r):n}return e}function shuffleInPlace(e){for(let t=e.length-1;t>0;t--){let n=Math.floor(Math.random()*(t+1));[e[t],e[n]]=[e[n],e[t]]}}function pickTopByScore(e,t){return[...e].sort((e,t)=>t.score-e.score||e.cardId.localeCompare(t.cardId)).slice(0,t)}var DEFAULT_FRESHNESS_WINDOW,DEFAULT_MAX_DIRECT_PER_RUN,DEFAULT_MAX_SUPPORT_PER_RUN,DEFAULT_HIERARCHY_DEPTH,DEFAULT_MIN_COUNT,BASE_TARGET_SCORE,BASE_SUPPORT_SCORE,DISCOVERED_SUPPORT_SCORE,MAX_TARGET_MULTIPLIER,MAX_SUPPORT_MULTIPLIER,PRESCRIBED_DEBUG_VERSION,PrescribedCardsGenerator,init_prescribed=__esm({"src/core/navigators/generators/prescribed.ts"(){init_navigators(),init_logger(),DEFAULT_FRESHNESS_WINDOW=3,DEFAULT_MAX_DIRECT_PER_RUN=3,DEFAULT_MAX_SUPPORT_PER_RUN=3,DEFAULT_HIERARCHY_DEPTH=2,DEFAULT_MIN_COUNT=3,BASE_TARGET_SCORE=1,BASE_SUPPORT_SCORE=.8,DISCOVERED_SUPPORT_SCORE=12,MAX_TARGET_MULTIPLIER=8,MAX_SUPPORT_MULTIPLIER=4,PRESCRIBED_DEBUG_VERSION=`testversion-prescribed-v3`,PrescribedCardsGenerator=class extends ContentNavigator{constructor(e,t,n){super(e,t,n),_defineProperty(this,`name`,void 0),_defineProperty(this,`config`,void 0),this.name=n.name||`Prescribed Cards`,this.config=this.parseConfig(n.serializedData),logger.debug(`[Prescribed] Initialized with ${this.config.groups.length} groups and ${this.config.groups.reduce((e,t)=>e+t.targetCardIds.length,0)} targets`)}get strategyKey(){return`PrescribedProgress`}async getWeightedCards(e,t){if(this.config.groups.length===0||e<=0)return{cards:[]};let n=this.course.getCourseID(),r=await this.user.getActiveCards(),a=new Set(r.map(e=>e.cardID)),o=await this.user.getSeenCards(n).catch(()=>[]),s=new Set(o),c=await this.getStrategyState()??{updatedAt:isoNow(),groups:{}},l=await this.loadHierarchyConfigs(),u=await this.user.getCourseRegDoc(n).catch(()=>null),d=typeof u?.elo==`number`?u.elo:u?.elo?.global?.score??t?.userElo??1e3,p=typeof u?.elo==`number`?{}:u?.elo?.tags??{},m=dedupe(this.config.groups.flatMap(e=>e.targetCardIds)),g=dedupe(this.config.groups.flatMap(e=>e.supportCardIds??[])),_=dedupe([...m,...g]),v=_.length>0?await this.course.getAppliedTagsBatch(_):new Map,y=await this.course.getCourseTagStubs().catch(()=>({rows:[],offset:0,total_rows:0})),b=new Map;for(let e of y.rows??[]){let t=e.doc;t?.name&&Array.isArray(t.taggedCards)&&b.set(t.name,[...t.taggedCards])}let x={updatedAt:isoNow(),groups:{}},S=[],C=new Set,w=[];for(let e of this.config.groups){let t=this.buildGroupRuntimeState({group:e,priorState:c.groups[e.id],activeIds:a,seenIds:s,tagsByCard:v,cardsByTag:b,hierarchyConfigs:l,userTagElo:p,userGlobalElo:d});w.push(t),logger.info(`[Prescribed] Group '${e.id}': ${e.targetCardIds.length} targets total, ${t.encounteredTargets.size} encountered, ${t.pendingTargets.length} pending (${t.surfaceableTargets.length} surfaceable, ${t.blockedTargets.length} blocked), ${t.supportCandidates.length} authored support candidates, ${t.discoveredSupportCandidates.length} discovered support candidates, pressure=${t.pressureMultiplier.toFixed(2)}`),t.blockedTargets.length>0&&(logger.info(`[Prescribed] Group '${e.id}' blocked targets: ${t.blockedTargets.join(`, `)}`),logger.info(`[Prescribed] Group '${e.id}' support tags needed: ${t.supportTags.join(`, `)||`(none)`}`),logger.info(`[Prescribed] Group '${e.id}' escalation mode: `+(t.supportCandidates.length>0?`direct-support`:t.discoveredSupportCandidates.length>0?`inserted-support-candidates`:`boost-only`)),t.discoveredSupportCandidates.length>0&&logger.info(`[Prescribed] Group '${e.id}' discovered support candidates: ${t.discoveredSupportCandidates.join(`, `)}`)),x.groups[e.id]=this.buildNextGroupState(t,c.groups[e.id]);let r=this.buildDirectTargetCards(t,n,C),o=this.buildSupportCards(t,n,C),u=this.buildDiscoveredSupportCards(t,n,C);S.push(...r,...o,...u)}let T=this.buildSupportHintSummary(w),E=Object.keys(T.boostTags).length>0?{boostTags:T.boostTags,_label:`prescribed-support (${T.supportTags.length} tags; blocked=${T.blockedTargetIds.length}; testversion=${PRESCRIBED_DEBUG_VERSION})`}:void 0;if(E){let e=Object.entries(E.boostTags??{});logger.info(`[Prescribed] Emitting ${e.length} boost hint(s): `+e.map(([e,t])=>`${e}\xD7${t.toFixed(1)}`).join(`, `))}else logger.info(`[Prescribed] No hints to emit (no blocked targets or no support tags)`);if(S.length===0)return logger.info(`[Prescribed] 0 cards emitted (all targets blocked, authored/discovered support candidates exhausted)`+(E?` — boost hints emitted but may not survive filters`:``)),await this.putStrategyState(x).catch(e=>{logger.debug(`[Prescribed] Failed to persist empty-state update: ${e}`)}),E?{cards:[],hints:E}:{cards:[]};let D=pickTopByScore(S,e),O=new Map;for(let e of D){let t=e.provenance[0],n=t?.reason.match(/group=([^;]+)/)?.[1],r=t?.reason.includes(`mode=support`)?`supportIds`:`targetIds`;n&&(O.has(n)||O.set(n,{targetIds:[],supportIds:[]}),O.get(n)[r].push(e.cardId))}for(let e of this.config.groups){let t=x.groups[e.id],n=O.get(e.id);n&&(n.targetIds.length>0||n.supportIds.length>0)&&(t.lastSurfacedAt=isoNow(),t.sessionsSinceSurfaced=0,n.supportIds.length>0&&(t.lastSupportAt=isoNow()))}return await this.putStrategyState(x).catch(e=>{logger.debug(`[Prescribed] Failed to persist prescribed progress: ${e}`)}),logger.info(`[Prescribed] Emitting ${D.length} cards (${D.filter(e=>e.provenance[0]?.reason.includes(`mode=target`)).length} target, ${D.filter(e=>e.provenance[0]?.reason.includes(`mode=support`)).length} support, ${D.filter(e=>e.provenance[0]?.reason.includes(`mode=discovered-support`)).length} discovered support)`),E?{cards:D,hints:E}:{cards:D}}buildSupportHintSummary(e){let t={},n=new Set,r=new Set;for(let a of e)if(!(a.blockedTargets.length===0||a.supportTags.length===0)){a.blockedTargets.forEach(e=>n.add(e));for(let e of a.supportTags)r.add(e),t[e]=(t[e]??1)*a.supportMultiplier}return{boostTags:t,blockedTargetIds:[...n].sort(),supportTags:[...r].sort()}}parseConfig(e){try{let t=JSON.parse(e);return{groups:(Array.isArray(t.groups)?t.groups:[]).map((e,t)=>({id:typeof e.id==`string`&&e.id.trim().length>0?e.id:`group-${t+1}`,targetCardIds:dedupe(Array.isArray(e.targetCardIds)?e.targetCardIds.filter(e=>typeof e==`string`):[]),supportCardIds:dedupe(Array.isArray(e.supportCardIds)?e.supportCardIds.filter(e=>typeof e==`string`):[]),supportTagPatterns:dedupe(Array.isArray(e.supportTagPatterns)?e.supportTagPatterns.filter(e=>typeof e==`string`):[]),freshnessWindowSessions:typeof e.freshnessWindowSessions==`number`?e.freshnessWindowSessions:DEFAULT_FRESHNESS_WINDOW,maxDirectTargetsPerRun:typeof e.maxDirectTargetsPerRun==`number`?e.maxDirectTargetsPerRun:DEFAULT_MAX_DIRECT_PER_RUN,maxSupportCardsPerRun:typeof e.maxSupportCardsPerRun==`number`?e.maxSupportCardsPerRun:DEFAULT_MAX_SUPPORT_PER_RUN,hierarchyWalk:{enabled:e.hierarchyWalk?.enabled!==!1,maxDepth:typeof e.hierarchyWalk?.maxDepth==`number`?e.hierarchyWalk.maxDepth:DEFAULT_HIERARCHY_DEPTH},retireOnEncounter:e.retireOnEncounter!==!1})).filter(e=>e.targetCardIds.length>0)}}catch{return{groups:[]}}}async loadHierarchyConfigs(){try{return(await this.course.getAllNavigationStrategies()).filter(e=>e.implementingClass===`hierarchyDefinition`).map(e=>{try{return{prerequisites:JSON.parse(e.serializedData).prerequisites||{}}}catch{return{prerequisites:{}}}})}catch(e){return logger.debug(`[Prescribed] Failed to load hierarchy configs: ${e}`),[]}}buildGroupRuntimeState(e){let{group:t,priorState:n,activeIds:r,seenIds:a,tagsByCard:o,cardsByTag:s,hierarchyConfigs:c,userTagElo:l,userGlobalElo:u}=e,d=new Set;for(let e of t.targetCardIds)(r.has(e)||a.has(e))&&d.add(e);if(n?.encounteredCardIds?.length)for(let e of n.encounteredCardIds)d.add(e);let p=t.targetCardIds.filter(e=>!d.has(e)),m=new Map;for(let e of p)m.set(e,o.get(e)??[]);let g=[],_=[],v=new Set;for(let e of p){let n=m.get(e)??[],r=this.resolveBlockedSupportTags(n,c,l,u,t.hierarchyWalk?.enabled!==!1,t.hierarchyWalk?.maxDepth??DEFAULT_HIERARCHY_DEPTH),a=n.filter(e=>e.startsWith(`gpc:intro:`)),o=new Set(n.filter(e=>e.startsWith(`gpc:expose:`)));for(let e of a){let t=e.slice(10);t&&o.add(`gpc:expose:${t}`)}let s=[...o].filter(e=>{let t=l[e];return!t||t.count<DEFAULT_MIN_COUNT});s.length>0&&s.forEach(e=>v.add(e)),r.blocked||s.length>0?(g.push(e),r.supportTags.forEach(e=>v.add(e))):_.push(e)}let y=dedupe([...t.supportCardIds??[],...this.findSupportCardsByTags(t,o,[...v])]).filter(e=>!r.has(e)&&!a.has(e)),b=g.length>0&&v.size>0&&y.length===0?this.findDiscoveredSupportCards({supportTags:[...v],cardsByTag:s,activeIds:r,seenIds:a,excludedIds:new Set([...t.targetCardIds,...t.supportCardIds??[]]),limit:t.maxSupportCardsPerRun??DEFAULT_MAX_SUPPORT_PER_RUN}):[];g.length>0&&v.size>0&&b.length===0&&logger.info(`[Prescribed] Group '${t.id}' discovered 0 broader support candidates (blocked=${g.length}; authoredSupport=${y.length})`);let x=n?.sessionsSinceSurfaced??0,S=t.freshnessWindowSessions??DEFAULT_FRESHNESS_WINDOW,C=Math.max(0,x-S),w=p.length===0?1:clamp(1+C*.75+Math.min(2,p.length*.1),1,MAX_TARGET_MULTIPLIER),T=g.length===0?1:clamp(1+C*.5+Math.min(1.5,g.length*.15),1,MAX_SUPPORT_MULTIPLIER);return{group:t,encounteredTargets:d,pendingTargets:p,blockedTargets:g,surfaceableTargets:_,targetTags:m,supportCandidates:y,discoveredSupportCandidates:b,supportTags:[...v],pressureMultiplier:w,supportMultiplier:T,debugVersion:PRESCRIBED_DEBUG_VERSION}}buildNextGroupState(e,t){let n=t?.sessionsSinceSurfaced??0,r=!1;return{encounteredCardIds:[...e.encounteredTargets].sort(),pendingTargetIds:[...e.pendingTargets].sort(),lastSurfacedAt:t?.lastSurfacedAt??null,sessionsSinceSurfaced:n+1,lastSupportAt:t?.lastSupportAt??null,blockedTargetIds:[...e.blockedTargets].sort(),lastResolvedSupportTags:[...e.supportTags].sort()}}buildDirectTargetCards(e,t,n){let r=e.group.maxDirectTargetsPerRun??DEFAULT_MAX_DIRECT_PER_RUN,a=e.surfaceableTargets.filter(e=>!n.has(e)).slice(0,r),o=[];for(let r of a)n.add(r),o.push({cardId:r,courseId:t,score:BASE_TARGET_SCORE*e.pressureMultiplier,provenance:[{strategy:`prescribed`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-prescribed`,action:`generated`,score:BASE_TARGET_SCORE*e.pressureMultiplier,reason:`mode=target;group=${e.group.id};pending=${e.pendingTargets.length};surfaceable=${e.surfaceableTargets.length};blocked=${e.blockedTargets.length};blockedTargets=${e.blockedTargets.join(`|`)||`none`};supportTags=${e.supportTags.join(`|`)||`none`};multiplier=${e.pressureMultiplier.toFixed(2)};testversion=${e.debugVersion}`}]});return o}buildSupportCards(e,t,n){if(e.blockedTargets.length===0||e.supportCandidates.length===0)return[];let r=e.group.maxSupportCardsPerRun??DEFAULT_MAX_SUPPORT_PER_RUN,a=e.supportCandidates.filter(e=>!n.has(e)).slice(0,r),o=[];for(let r of a)n.add(r),o.push({cardId:r,courseId:t,score:BASE_SUPPORT_SCORE*e.supportMultiplier,provenance:[{strategy:`prescribed`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-prescribed`,action:`generated`,score:BASE_SUPPORT_SCORE*e.supportMultiplier,reason:`mode=support;group=${e.group.id};pending=${e.pendingTargets.length};blocked=${e.blockedTargets.length};blockedTargets=${e.blockedTargets.join(`|`)||`none`};supportCard=${r};supportTags=${e.supportTags.join(`|`)||`none`};multiplier=${e.supportMultiplier.toFixed(2)};testversion=${e.debugVersion}`}]});return o}buildDiscoveredSupportCards(e,t,n){if(e.blockedTargets.length===0||e.discoveredSupportCandidates.length===0)return[];let r=e.group.maxSupportCardsPerRun??DEFAULT_MAX_SUPPORT_PER_RUN,a=e.discoveredSupportCandidates.filter(e=>!n.has(e)).slice(0,r),o=[];for(let r of a)n.add(r),o.push({cardId:r,courseId:t,score:DISCOVERED_SUPPORT_SCORE*e.supportMultiplier,provenance:[{strategy:`prescribed`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-prescribed`,action:`generated`,score:DISCOVERED_SUPPORT_SCORE*e.supportMultiplier,reason:`mode=discovered-support;group=${e.group.id};pending=${e.pendingTargets.length};blocked=${e.blockedTargets.length};blockedTargets=${e.blockedTargets.join(`|`)||`none`};supportCard=${r};supportTags=${e.supportTags.join(`|`)||`none`};multiplier=${e.supportMultiplier.toFixed(2)};testversion=${e.debugVersion}`}]});return o}findSupportCardsByTags(e,t,n){if(n.length===0)return[];let r=e.supportCardIds??[],a=e.supportTagPatterns??[];if(r.length===0&&a.length===0)return[];let o=new Set;for(let e of r){let r=t.get(e)??[],s=n.some(e=>r.includes(e)),c=a.some(e=>r.some(t=>matchesTagPattern(t,e)));(s||c)&&o.add(e)}return[...o]}findDiscoveredSupportCards(e){let{supportTags:t,cardsByTag:n,activeIds:r,seenIds:a,excludedIds:o,limit:s}=e,c=new Map;for(let e of t){let t=n.get(e)??[];for(let e of t){if(r.has(e)||a.has(e)||o.has(e))continue;let t=c.get(e);t?t.matches+=1:c.set(e,{cardId:e,matches:1})}}let l=[...c.values()].sort((e,t)=>t.matches-e.matches||e.cardId.localeCompare(t.cardId)),u=new Set,d=[],p=[];for(let e of l){let t=extractWordStem(e.cardId);u.has(t)?p.push(e):(u.add(t),d.push(e))}return shuffleInPlace(d),shuffleInPlace(p),[...d,...p].slice(0,s).map(e=>e.cardId)}resolveBlockedSupportTags(e,t,n,r,a,o){let s=new Set,c=!1;for(let l of e){let e=t.map(e=>e.prerequisites[l]).filter(e=>Array.isArray(e)&&e.length>0);if(e.length!==0&&e.some(e=>e.some(e=>!this.isPrerequisiteMet(e,n[e.tag],r)))){if(c=!0,!a){for(let t of e)for(let e of t)this.isPrerequisiteMet(e,n[e.tag],r)||s.add(e.tag);continue}for(let a of e)for(let e of a)this.isPrerequisiteMet(e,n[e.tag],r)||this.collectSupportTagsRecursive(e.tag,t,n,r,o,new Set,s)}}return{blocked:c,supportTags:[...s]}}collectSupportTagsRecursive(e,t,n,r,a,o,s){if(a<0||o.has(e))return;o.add(e);let c=!1;for(let l of t){let u=l.prerequisites[e];if(!u||u.length===0)continue;let d=u.filter(e=>!this.isPrerequisiteMet(e,n[e.tag],r));if(d.length>0&&a>0){c=!0;for(let e of d)this.collectSupportTagsRecursive(e.tag,t,n,r,a-1,o,s)}}c||s.add(e)}isPrerequisiteMet(e,t,n){if(!t)return!1;let r=e.masteryThreshold?.minCount??DEFAULT_MIN_COUNT;return t.count<r?!1:e.masteryThreshold?.minElo===void 0?e.masteryThreshold?.minCount===void 0?t.score>=n:!0:t.score>=e.masteryThreshold.minElo}}}}),srs_exports={};__export(srs_exports,{default:()=>SRSNavigator});var DEFAULT_HEALTHY_BACKLOG,MAX_BACKLOG_PRESSURE,SRSNavigator,init_srs=__esm({"src/core/navigators/generators/srs.ts"(){init_navigators(),init_logger(),DEFAULT_HEALTHY_BACKLOG=20,MAX_BACKLOG_PRESSURE=.5,SRSNavigator=class extends ContentNavigator{constructor(e,t,n){super(e,t,n),_defineProperty(this,`name`,void 0),_defineProperty(this,`healthyBacklog`,void 0),this.name=n?.name||`SRS`,this.healthyBacklog=this.parseConfig(n?.serializedData).healthyBacklog??DEFAULT_HEALTHY_BACKLOG}parseConfig(e){if(!e)return{};try{return JSON.parse(e)}catch{return logger.warn(`[SRS] Failed to parse strategy config, using defaults`),{}}}async getWeightedCards(e,t){if(!this.user||!this.course)throw Error(`SRSNavigator requires user and course to be set`);let n=this.course.getCourseID(),r=await this.user.getPendingReviews(n),a=hooks.utc(),o=r.filter(e=>a.isAfter(hooks.utc(e.reviewTime)));if(o.length>0){let e=[...new Set(o.map(e=>e.cardId))],t=await this.course.getAppliedTagsBatch(e),n=[];if(o=o.filter(e=>(t.get(e.cardId)??[]).includes(`srs:skip`)?(n.push(e._id),!1):!0),n.length>0){logger.info(`[SRS] Removing ${n.length} scheduled reviews for srs:skip cards`);for(let e of n)this.user.removeScheduledCardReview(e)}}let s=this.computeBacklogPressure(o.length);if(o.length>0){let e=s>0?` [backlog pressure: +${s.toFixed(2)}]`:` [healthy backlog]`;logger.info(`[SRS] Course ${n}: ${o.length} reviews due now (of ${r.length} scheduled)${e}`)}else if(r.length>0){let e=[...r].sort((e,t)=>hooks.utc(e.reviewTime).diff(hooks.utc(t.reviewTime)))[0],t=hooks.utc(e.reviewTime),o=hooks.duration(t.diff(a)),s=o.asHours()<1?`${Math.round(o.asMinutes())}m`:o.asHours()<24?`${Math.round(o.asHours())}h`:`${Math.round(o.asDays())}d`;logger.info(`[SRS] Course ${n}: 0 reviews due now (${r.length} scheduled, next in ${s})`)}else logger.info(`[SRS] Course ${n}: No reviews scheduled`);return{cards:o.map(e=>{let{score:t,reason:n}=this.computeUrgencyScore(e,a,s);return{cardId:e.cardId,courseId:e.courseId,score:t,reviewID:e._id,provenance:[{strategy:`srs`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-SRS-default`,action:`generated`,score:t,reason:n}]}}).sort((e,t)=>t.score-e.score).slice(0,e)}}computeBacklogPressure(e){if(e<=this.healthyBacklog)return 0;let t=(e-this.healthyBacklog)/this.healthyBacklog*(MAX_BACKLOG_PRESSURE/2);return Math.min(MAX_BACKLOG_PRESSURE,t)}computeUrgencyScore(e,t,n){let r=hooks.utc(e.scheduledAt),a=hooks.utc(e.reviewTime),o=Math.max(1,a.diff(r,`hours`)),s=t.diff(a,`hours`),c=s/o,l=.3+.7*Math.exp(-o/720),u=.5+(Math.min(1,Math.max(0,c))*.5+l*.5)*.45,d=Math.min(1,u+n),p=[`${Math.round(s)}h overdue`,`interval: ${Math.round(o)}h`,`relative: ${c.toFixed(2)}`,`recency: ${l.toFixed(2)}`];return n>0&&p.push(`backlog: +${n.toFixed(2)}`),p.push(`review`),{score:d,reason:p.join(`, `)}}}}}),types_exports={},init_types=__esm({"src/core/navigators/generators/types.ts"(){}}),globImport_generators,init_=__esm({'import("./generators/**/*") in src/core/navigators/index.ts'(){globImport_generators=__glob({"./generators/CompositeGenerator.ts":()=>Promise.resolve().then(()=>(init_CompositeGenerator(),CompositeGenerator_exports)),"./generators/elo.ts":()=>Promise.resolve().then(()=>(init_elo(),elo_exports)),"./generators/index.ts":()=>Promise.resolve().then(()=>(init_generators(),generators_exports)),"./generators/prescribed.ts":()=>Promise.resolve().then(()=>(init_prescribed(),prescribed_exports)),"./generators/srs.ts":()=>Promise.resolve().then(()=>(init_srs(),srs_exports)),"./generators/types.ts":()=>Promise.resolve().then(()=>(init_types(),types_exports))})}}),DEFAULT_LEARNABLE_WEIGHT,init_contentNavigationStrategy=__esm({"src/core/types/contentNavigationStrategy.ts"(){DEFAULT_LEARNABLE_WEIGHT={weight:1,confidence:.1,sampleSize:0}}}),WeightedFilter_exports={};__export(WeightedFilter_exports,{WeightedFilter:()=>WeightedFilter});var WeightedFilter,init_WeightedFilter=__esm({"src/core/navigators/filters/WeightedFilter.ts"(){init_contentNavigationStrategy(),WeightedFilter=class{constructor(e,t=DEFAULT_LEARNABLE_WEIGHT,n=!1,r){_defineProperty(this,`name`,void 0),_defineProperty(this,`inner`,void 0),_defineProperty(this,`learnable`,void 0),_defineProperty(this,`staticWeight`,void 0),_defineProperty(this,`strategyId`,void 0),this.inner=e,this.name=e.name,this.learnable=t,this.staticWeight=n,this.strategyId=r}async transform(e,t){let n=this.learnable.weight,r;if(!this.staticWeight&&t.orchestration){let e=this.strategyId||this.inner.strategyId||this.name;n=t.orchestration.getEffectiveWeight(e,this.learnable),r=t.orchestration.getDeviation(e)}if(Math.abs(n-1)<.001)return this.inner.transform(e,t);let a=new Map;for(let t of e)a.set(t.cardId,t.score);return(await this.inner.transform(e,t)).map(e=>{let t=a.get(e.cardId);if(t===void 0||t===0||e.score===0)return e;let o=e.score/t;if(Math.abs(o-1)<1e-4)return e;let s=t*o**+n,c=e.provenance.length-1,l=e.provenance[c];if(l){let t=[...e.provenance];return t[c]={...l,score:s,effectiveWeight:n,deviation:r},{...e,score:s,provenance:t}}return{...e,score:s}})}}}}),eloDistance_exports={};__export(eloDistance_exports,{DEFAULT_HALF_LIFE:()=>DEFAULT_HALF_LIFE,DEFAULT_MAX_MULTIPLIER:()=>DEFAULT_MAX_MULTIPLIER,DEFAULT_MIN_MULTIPLIER:()=>DEFAULT_MIN_MULTIPLIER,createEloDistanceFilter:()=>createEloDistanceFilter});function computeMultiplier(e,t,n,r){let a=e/t,o=Math.exp(-(a*a));return n+(r-n)*o}function createEloDistanceFilter(e){let t=e?.halfLife??DEFAULT_HALF_LIFE,n=e?.minMultiplier??DEFAULT_MIN_MULTIPLIER,r=e?.maxMultiplier??DEFAULT_MAX_MULTIPLIER;return{name:`ELO Distance Filter`,async transform(e,a){let{course:o,userElo:s}=a,c=e.map(e=>e.cardId),l=await o.getCardEloData(c);return e.map((e,a)=>{let o=l[a]?.global?.score??1e3,c=Math.abs(o-s),u=computeMultiplier(c,t,n,r),d=e.score*u,p=u<r-.01?`penalized`:`passed`;return{...e,score:d,provenance:[...e.provenance,{strategy:`eloDistance`,strategyName:`ELO Distance Filter`,strategyId:`ELO_DISTANCE_FILTER`,action:p,score:d,reason:`ELO distance ${Math.round(c)} (card: ${Math.round(o)}, user: ${Math.round(s)}) \u2192 ${u.toFixed(2)}x`}]}})}}}var DEFAULT_HALF_LIFE,DEFAULT_MIN_MULTIPLIER,DEFAULT_MAX_MULTIPLIER,init_eloDistance=__esm({"src/core/navigators/filters/eloDistance.ts"(){DEFAULT_HALF_LIFE=200,DEFAULT_MIN_MULTIPLIER=.3,DEFAULT_MAX_MULTIPLIER=1}}),hierarchyDefinition_exports={};__export(hierarchyDefinition_exports,{default:()=>HierarchyDefinitionNavigator});var DEFAULT_MIN_COUNT2,HierarchyDefinitionNavigator,init_hierarchyDefinition=__esm({"src/core/navigators/filters/hierarchyDefinition.ts"(){init_navigators(),init_logger(),DEFAULT_MIN_COUNT2=3,HierarchyDefinitionNavigator=class extends ContentNavigator{constructor(e,t,n){super(e,t,n),_defineProperty(this,`config`,void 0),_defineProperty(this,`name`,void 0),this.config=this.parseConfig(n.serializedData),this.name=n.name||`Hierarchy Definition`}parseConfig(e){try{return{prerequisites:JSON.parse(e).prerequisites||{}}}catch{return{prerequisites:{}}}}isPrerequisiteMet(e,t,n){if(!t)return!1;let r=e.masteryThreshold?.minCount??DEFAULT_MIN_COUNT2;return t.count<r?!1:e.masteryThreshold?.minElo===void 0?e.masteryThreshold?.minCount===void 0?t.score>=n:!0:t.score>=e.masteryThreshold.minElo}async getMasteredTags(e){let t=new Set;try{let n=toCourseElo((await e.user.getCourseRegDoc(e.course.getCourseID())).elo);for(let e of Object.values(this.config.prerequisites))for(let r of e){let e=n.tags[r.tag];this.isPrerequisiteMet(r,e,n.global.score)&&t.add(r.tag)}}catch{}return t}getUnlockedTags(e){let t=new Set;for(let[n,r]of Object.entries(this.config.prerequisites))r.every(t=>e.has(t.tag))&&t.add(n);return t}hasPrerequisites(e){return e in this.config.prerequisites}async checkCardUnlock(e,t,n,r){try{let t=e.tags??[],a=t.filter(e=>this.hasPrerequisites(e)&&!n.has(e));return a.length===0?{isUnlocked:!0,reason:`Prerequisites met, tags: ${t.length>0?t.join(`, `):`none`}`}:{isUnlocked:!1,reason:`Blocked: missing prerequisites ${a.flatMap(e=>(this.config.prerequisites[e]||[]).filter(e=>!r.has(e.tag)).map(e=>e.tag)).join(`, `)} for tags ${a.join(`, `)}`}}catch{return{isUnlocked:!0,reason:`Prerequisites check skipped (tag lookup failed)`}}}getPreReqBoosts(e,t){let n=new Map;for(let[r,a]of Object.entries(this.config.prerequisites))if(!e.has(r))for(let e of a){if(!e.preReqBoost||e.preReqBoost<=1||t.has(e.tag))continue;let r=n.get(e.tag)??1;n.set(e.tag,Math.max(r,e.preReqBoost))}return n}getTargetBoosts(e){let t=new Map,n=Object.keys(this.config.prerequisites),r=[...e];logger.info(`[HierarchyDefinition:targetBoost:trace] ${this.name} | configKeys=${n.length}, unlocked=${r.length} (${r.slice(0,5).join(`, `)}${r.length>5?`...`:``})`);for(let[n,r]of Object.entries(this.config.prerequisites))if(e.has(n)){logger.info(`[HierarchyDefinition:targetBoost:trace] UNLOCKED ${n}: ${r.length} prereqs, raw=${JSON.stringify(r.map(e=>({tag:e.tag,tb:e.targetBoost})))}`);for(let e of r){if(!e.targetBoost||e.targetBoost<=1)continue;let r=t.get(n)??1;t.set(n,Math.max(r,e.targetBoost))}}return t.size>0?logger.info(`[HierarchyDefinition] targetBoosts active: ${[...t.entries()].map(([e,t])=>`${e}=\xD7${t}`).join(`, `)}`):logger.info(`[HierarchyDefinition:targetBoost:trace] no targetBoosts found despite ${r.length} unlocked tags`),t}async transform(e,t){let n=await this.getMasteredTags(t),r=this.getUnlockedTags(n),a=this.getPreReqBoosts(r,n),o=this.getTargetBoosts(r),s=[];for(let c of e){let{isUnlocked:e,reason:l}=await this.checkCardUnlock(c,t.course,r,n),u=e?c.score:c.score*.02,d=e?`passed`:`penalized`,p=l;if(e&&a.size>0){let e=c.tags??[],t=1,n=[];for(let r of e){let e=a.get(r);e&&e>t&&(t=e,n.push(r))}t>1&&(u*=t,d=`boosted`,p=`${l} | preReqBoost \xD7${t.toFixed(2)} for ${n.join(`, `)}`,logger.info(`[HierarchyDefinition] preReqBoost \xD7${t.toFixed(2)} applied to card ${c.cardId} via tags [${n.join(`, `)}] (score: ${c.score.toFixed(3)} \u2192 ${u.toFixed(3)})`))}if(e&&o.size>0){let e=c.tags??[],t=1,n=[];for(let r of e){let e=o.get(r);e&&e>t&&(t=e,n.push(r))}t>1&&(u*=t,d=`boosted`,p=`${p} | targetBoost \xD7${t.toFixed(2)} for ${n.join(`, `)}`,logger.info(`[HierarchyDefinition] targetBoost \xD7${t.toFixed(2)} applied to card ${c.cardId} via tags [${n.join(`, `)}] (score: ${c.score.toFixed(3)} \u2192 ${u.toFixed(3)})`))}s.push({...c,score:u,provenance:[...c.provenance,{strategy:`hierarchyDefinition`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-hierarchy`,action:d,score:u,reason:p}]})}return s}async getWeightedCards(e){throw Error(`HierarchyDefinitionNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().`)}}}}),userTagPreference_exports={};__export(userTagPreference_exports,{default:()=>UserTagPreferenceFilter});var UserTagPreferenceFilter,init_userTagPreference=__esm({"src/core/navigators/filters/userTagPreference.ts"(){init_navigators(),UserTagPreferenceFilter=class extends ContentNavigator{constructor(e,t,n){super(e,t,n),_defineProperty(this,`_strategyData`,void 0),_defineProperty(this,`name`,void 0),this._strategyData=n,this.name=n.name||`User Tag Preferences`}computeMultiplier(e,t){let n=e.map(e=>t[e]).filter(e=>e!==void 0);return n.length===0?1:Math.max(...n)}buildReason(e,t,n){let r=e.filter(e=>t[e]===n);return n===0?`Excluded by user preference: ${r.join(`, `)} (${n}x)`:n<1?`Penalized by user preference: ${r.join(`, `)} (${n.toFixed(2)}x)`:n>1?`Boosted by user preference: ${r.join(`, `)} (${n.toFixed(2)}x)`:`No matching user preferences`}async transform(e,t){let n=await this.getStrategyState();return!n||Object.keys(n.boost).length===0?e.map(e=>({...e,provenance:[...e.provenance,{strategy:`userTagPreference`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||this._strategyData._id,action:`passed`,score:e.score,reason:`No user tag preferences configured`}]})):await Promise.all(e.map(async e=>{let t=e.tags??[],r=this.computeMultiplier(t,n.boost),a=Math.min(1,e.score*r),o;return o=r===0||r<1?`penalized`:r>1?`boosted`:`passed`,{...e,score:a,provenance:[...e.provenance,{strategy:`userTagPreference`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||this._strategyData._id,action:o,score:a,reason:this.buildReason(t,n.boost,r)}]}}))}async getWeightedCards(e){throw Error(`UserTagPreferenceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().`)}}}}),filters_exports={};__export(filters_exports,{UserTagPreferenceFilter:()=>UserTagPreferenceFilter,createEloDistanceFilter:()=>createEloDistanceFilter});var init_filters=__esm({"src/core/navigators/filters/index.ts"(){init_eloDistance(),init_userTagPreference()}}),inferredPreferenceStub_exports={};__export(inferredPreferenceStub_exports,{INFERRED_PREFERENCE_NAVIGATOR_STUB:()=>INFERRED_PREFERENCE_NAVIGATOR_STUB});var INFERRED_PREFERENCE_NAVIGATOR_STUB,init_inferredPreferenceStub=__esm({"src/core/navigators/filters/inferredPreferenceStub.ts"(){INFERRED_PREFERENCE_NAVIGATOR_STUB=!0}}),interferenceMitigator_exports={};__export(interferenceMitigator_exports,{default:()=>InterferenceMitigatorNavigator});var DEFAULT_MIN_COUNT3,DEFAULT_MIN_ELAPSED_DAYS,DEFAULT_INTERFERENCE_DECAY,InterferenceMitigatorNavigator,init_interferenceMitigator=__esm({"src/core/navigators/filters/interferenceMitigator.ts"(){init_navigators(),DEFAULT_MIN_COUNT3=10,DEFAULT_MIN_ELAPSED_DAYS=3,DEFAULT_INTERFERENCE_DECAY=.8,InterferenceMitigatorNavigator=class extends ContentNavigator{constructor(e,t,n){super(e,t,n),_defineProperty(this,`config`,void 0),_defineProperty(this,`name`,void 0),_defineProperty(this,`interferenceMap`,void 0),this.config=this.parseConfig(n.serializedData),this.interferenceMap=this.buildInterferenceMap(),this.name=n.name||`Interference Mitigator`}parseConfig(e){try{let t=JSON.parse(e),n=t.interferenceSets||[];return n.length>0&&Array.isArray(n[0])&&(n=n.map(e=>({tags:e}))),{interferenceSets:n,maturityThreshold:{minCount:t.maturityThreshold?.minCount??DEFAULT_MIN_COUNT3,minElo:t.maturityThreshold?.minElo,minElapsedDays:t.maturityThreshold?.minElapsedDays??DEFAULT_MIN_ELAPSED_DAYS},defaultDecay:t.defaultDecay??DEFAULT_INTERFERENCE_DECAY}}catch{return{interferenceSets:[],maturityThreshold:{minCount:DEFAULT_MIN_COUNT3,minElapsedDays:DEFAULT_MIN_ELAPSED_DAYS},defaultDecay:DEFAULT_INTERFERENCE_DECAY}}}buildInterferenceMap(){let e=new Map;for(let t of this.config.interferenceSets){let n=t.decay??this.config.defaultDecay??DEFAULT_INTERFERENCE_DECAY;for(let r of t.tags){e.has(r)||e.set(r,[]);let a=e.get(r);for(let e of t.tags)if(e!==r){let t=a.find(t=>t.partner===e);t?t.decay=Math.max(t.decay,n):a.push({partner:e,decay:n})}}}return e}async getImmatureTags(e){let t=new Set;try{let n=toCourseElo((await e.user.getCourseRegDoc(e.course.getCourseID())).elo),r=this.config.maturityThreshold?.minCount??DEFAULT_MIN_COUNT3,a=this.config.maturityThreshold?.minElo,o=(this.config.maturityThreshold?.minElapsedDays??DEFAULT_MIN_ELAPSED_DAYS)*2;for(let[e,s]of Object.entries(n.tags)){if(s.count===0)continue;let n=s.count<r,c=a!==void 0&&s.score<a,l=s.count<o;(n||c||l)&&t.add(e)}}catch{}return t}getTagsToAvoid(e){let t=new Map;for(let n of e){let r=this.interferenceMap.get(n);if(r){for(let{partner:n,decay:a}of r)if(!e.has(n)){let e=t.get(n)??0;t.set(n,Math.max(e,a))}}}return t}computeInterferenceEffect(e,t,n){if(t.size===0)return{multiplier:1,interferingTags:[],reason:`No interference detected`};let r=1,a=[];for(let n of e){let e=t.get(n);e!==void 0&&(a.push(n),r*=1-e)}if(a.length===0)return{multiplier:1,interferingTags:[],reason:`No interference detected`};let o=new Set;for(let e of a)for(let t of n)this.interferenceMap.get(t)?.some(t=>t.partner===e)&&o.add(t);let s=`Interferes with immature tags ${Array.from(o).join(`, `)} (tags: ${a.join(`, `)}, multiplier: ${r.toFixed(2)})`;return{multiplier:r,interferingTags:a,reason:s}}async transform(e,t){let n=await this.getImmatureTags(t),r=this.getTagsToAvoid(n),a=[];for(let t of e){let e=t.tags??[],{multiplier:o,reason:s}=this.computeInterferenceEffect(e,r,n),c=t.score*o,l=o<1?`penalized`:o>1?`boosted`:`passed`;a.push({...t,score:c,provenance:[...t.provenance,{strategy:`interferenceMitigator`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-interference`,action:l,score:c,reason:s}]})}return a}async getWeightedCards(e){throw Error(`InterferenceMitigatorNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().`)}}}}),relativePriority_exports={};__export(relativePriority_exports,{default:()=>RelativePriorityNavigator});var DEFAULT_PRIORITY,DEFAULT_PRIORITY_INFLUENCE,DEFAULT_COMBINE_MODE,RelativePriorityNavigator,init_relativePriority=__esm({"src/core/navigators/filters/relativePriority.ts"(){init_navigators(),DEFAULT_PRIORITY=.5,DEFAULT_PRIORITY_INFLUENCE=.5,DEFAULT_COMBINE_MODE=`max`,RelativePriorityNavigator=class extends ContentNavigator{constructor(e,t,n){super(e,t,n),_defineProperty(this,`config`,void 0),_defineProperty(this,`name`,void 0),this.config=this.parseConfig(n.serializedData),this.name=n.name||`Relative Priority`}parseConfig(e){try{let t=JSON.parse(e);return{tagPriorities:t.tagPriorities||{},defaultPriority:t.defaultPriority??DEFAULT_PRIORITY,combineMode:t.combineMode??DEFAULT_COMBINE_MODE,priorityInfluence:t.priorityInfluence??DEFAULT_PRIORITY_INFLUENCE}}catch{return{tagPriorities:{},defaultPriority:DEFAULT_PRIORITY,combineMode:DEFAULT_COMBINE_MODE,priorityInfluence:DEFAULT_PRIORITY_INFLUENCE}}}getTagPriority(e){return this.config.tagPriorities[e]??this.config.defaultPriority??DEFAULT_PRIORITY}computeCardPriority(e){if(e.length===0)return this.config.defaultPriority??DEFAULT_PRIORITY;let t=e.map(e=>this.getTagPriority(e));switch(this.config.combineMode){case`max`:return Math.max(...t);case`min`:return Math.min(...t);case`average`:return t.reduce((e,t)=>e+t,0)/t.length;default:return Math.max(...t)}}computeBoostFactor(e){let t=this.config.priorityInfluence??DEFAULT_PRIORITY_INFLUENCE;return 1+(e-.5)*t}buildPriorityReason(e,t,n,r){if(e.length===0)return`No tags, neutral priority (${t.toFixed(2)})`;let a=e.slice(0,3).join(`, `),o=e.length>3?` (+${e.length-3} more)`:``;return n===1?`Neutral priority (${t.toFixed(2)}) for tags: ${a}${o}`:n>1?`High-priority tags: ${a}${o} (priority ${t.toFixed(2)} \u2192 boost ${n.toFixed(2)}x \u2192 ${r.toFixed(2)})`:`Low-priority tags: ${a}${o} (priority ${t.toFixed(2)} \u2192 reduce ${n.toFixed(2)}x \u2192 ${r.toFixed(2)})`}async transform(e,t){return await Promise.all(e.map(async e=>{let t=e.tags??[],n=this.computeCardPriority(t),r=this.computeBoostFactor(n),a=Math.max(0,e.score*r),o=r>1?`boosted`:r<1?`penalized`:`passed`,s=this.buildPriorityReason(t,n,r,a);return{...e,score:a,provenance:[...e.provenance,{strategy:`relativePriority`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-priority`,action:o,score:a,reason:s}]}}))}async getWeightedCards(e){throw Error(`RelativePriorityNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().`)}}}}),types_exports2={},init_types2=__esm({"src/core/navigators/filters/types.ts"(){}}),userGoalStub_exports={};__export(userGoalStub_exports,{USER_GOAL_NAVIGATOR_STUB:()=>USER_GOAL_NAVIGATOR_STUB});var USER_GOAL_NAVIGATOR_STUB,init_userGoalStub=__esm({"src/core/navigators/filters/userGoalStub.ts"(){USER_GOAL_NAVIGATOR_STUB=!0}}),globImport_filters,init_2=__esm({'import("./filters/**/*") in src/core/navigators/index.ts'(){globImport_filters=__glob({"./filters/WeightedFilter.ts":()=>Promise.resolve().then(()=>(init_WeightedFilter(),WeightedFilter_exports)),"./filters/eloDistance.ts":()=>Promise.resolve().then(()=>(init_eloDistance(),eloDistance_exports)),"./filters/hierarchyDefinition.ts":()=>Promise.resolve().then(()=>(init_hierarchyDefinition(),hierarchyDefinition_exports)),"./filters/index.ts":()=>Promise.resolve().then(()=>(init_filters(),filters_exports)),"./filters/inferredPreferenceStub.ts":()=>Promise.resolve().then(()=>(init_inferredPreferenceStub(),inferredPreferenceStub_exports)),"./filters/interferenceMitigator.ts":()=>Promise.resolve().then(()=>(init_interferenceMitigator(),interferenceMitigator_exports)),"./filters/relativePriority.ts":()=>Promise.resolve().then(()=>(init_relativePriority(),relativePriority_exports)),"./filters/types.ts":()=>Promise.resolve().then(()=>(init_types2(),types_exports2)),"./filters/userGoalStub.ts":()=>Promise.resolve().then(()=>(init_userGoalStub(),userGoalStub_exports)),"./filters/userTagPreference.ts":()=>Promise.resolve().then(()=>(init_userTagPreference(),userTagPreference_exports))})}});function aggregateOutcomesForGradient(e,t){let n=[];for(let r of e){let e=r.deviations[t];e!==void 0&&n.push({deviation:e,outcomeValue:r.outcomeValue,weight:1})}return logger.debug(`[Orchestration] Aggregated ${n.length} observations for strategy ${t}`),n}function computeStrategyGradient(e){let t=e.length;if(t<3)return logger.debug(`[Orchestration] Insufficient observations for gradient (${t} < 3)`),null;let n=0,r=0,a=0;for(let t of e){let e=t.weight??1;n+=t.deviation*e,r+=t.outcomeValue*e,a+=e}let o=n/a,s=r/a,c=0,l=0,u=0;for(let t of e){let e=t.weight??1,n=t.deviation-o,r=t.outcomeValue-s;c+=e*n*r,l+=e*n*n,u+=e*r*r}if(l<1e-10)return logger.debug(`[Orchestration] No variance in deviations, cannot compute gradient`),{gradient:0,intercept:s,rSquared:0,sampleSize:t};let d=c/l,p=s-d*o,m=0;for(let t of e){let e=t.weight??1,n=d*t.deviation+p,r=t.outcomeValue-n;m+=e*r*r}let g=u>1e-10?1-m/u:0;return logger.debug(`[Orchestration] Computed gradient: ${d.toFixed(4)}, intercept: ${p.toFixed(4)}, R\xB2: ${g.toFixed(4)}, n=${t}`),{gradient:d,intercept:p,rSquared:Math.max(0,Math.min(1,g)),sampleSize:t}}var init_gradient=__esm({"src/core/orchestration/gradient.ts"(){init_logger()}});function updateStrategyWeight(e,t){if(t.sampleSize<MIN_OBSERVATIONS_FOR_UPDATE)return logger.debug(`[Orchestration] Insufficient samples (${t.sampleSize} < ${MIN_OBSERVATIONS_FOR_UPDATE}), keeping current weight`),{...e,sampleSize:e.sampleSize+t.sampleSize};let n=t.rSquared>=MIN_R_SQUARED_FOR_GRADIENT,r=Math.abs(t.gradient)<FLAT_GRADIENT_THRESHOLD,a=e.weight,o=e.confidence;if(!n||r){let n=.05*(1-e.confidence);o=Math.min(1,e.confidence+n),logger.debug(`[Orchestration] Flat/unreliable gradient (|g|=${Math.abs(t.gradient).toFixed(4)}, R\xB2=${t.rSquared.toFixed(4)}). Increasing confidence: ${e.confidence.toFixed(3)} \u2192 ${o.toFixed(3)}`)}else{let n=t.gradient*LEARNING_RATE;n=Math.max(-MAX_WEIGHT_DELTA,Math.min(MAX_WEIGHT_DELTA,n)),a=e.weight+n,a=Math.max(.1,Math.min(3,a));let r=.02*(1-e.confidence);o=Math.min(1,e.confidence+r),logger.debug(`[Orchestration] Adjusting weight: ${e.weight.toFixed(3)} \u2192 ${a.toFixed(3)} (gradient=${t.gradient.toFixed(4)}, delta=${n.toFixed(4)})`)}return{weight:a,confidence:o,sampleSize:e.sampleSize+t.sampleSize}}function updateLearningState(e,t,n,r,a){let o=new Date().toISOString(),s=`STRATEGY_LEARNING_STATE::${e}::${t}`,c={timestamp:o,weight:n.weight,confidence:n.confidence,gradient:r.gradient},l=a?.history??[];return l=[...l,c],l.length>MAX_HISTORY_LENGTH&&(l=l.slice(l.length-MAX_HISTORY_LENGTH)),{_id:s,_rev:a?._rev,docType:`STRATEGY_LEARNING_STATE`,courseId:e,strategyId:t,currentWeight:n,regression:{gradient:r.gradient,intercept:r.intercept,rSquared:r.rSquared,sampleSize:r.sampleSize,computedAt:o},history:l,updatedAt:o}}function runPeriodUpdate(e){let{courseId:t,strategyId:n,currentWeight:r,gradient:a,existingState:o}=e;logger.info(`[Orchestration] Running period update for strategy ${n} (${a.sampleSize} observations)`);let s=updateStrategyWeight(r,a),c=s.weight!==r.weight,l=updateLearningState(t,n,s,a,o);return logger.info(`[Orchestration] Period update complete for ${n}: weight ${r.weight.toFixed(3)} \u2192 ${s.weight.toFixed(3)}, confidence ${r.confidence.toFixed(3)} \u2192 ${s.confidence.toFixed(3)}`),{strategyId:n,previousWeight:r,newWeight:s,gradient:a,learningState:l,updated:c}}function getDefaultLearnableWeight(){return{...DEFAULT_LEARNABLE_WEIGHT}}var MIN_OBSERVATIONS_FOR_UPDATE,LEARNING_RATE,MAX_WEIGHT_DELTA,MIN_R_SQUARED_FOR_GRADIENT,FLAT_GRADIENT_THRESHOLD,MAX_HISTORY_LENGTH,init_learning=__esm({"src/core/orchestration/learning.ts"(){init_contentNavigationStrategy(),init_types_legacy(),init_logger(),MIN_OBSERVATIONS_FOR_UPDATE=10,LEARNING_RATE=.1,MAX_WEIGHT_DELTA=.3,MIN_R_SQUARED_FOR_GRADIENT=.05,FLAT_GRADIENT_THRESHOLD=.02,MAX_HISTORY_LENGTH=100}});function computeOutcomeSignal(e,t={}){if(!e||e.length===0)return null;let n=t.targetAccuracy??.85,r=t.tolerance??.05,a=0;for(let t of e)t.isCorrect&&a++;return scoreAccuracyInZone(a/e.length,n,r)}function scoreAccuracyInZone(e,t,n){let r=Math.abs(e-t);if(r<=n)return 1;let a=r-n;return Math.max(0,1-a*2.5)}var init_signal=__esm({"src/core/orchestration/signal.ts"(){}});async function recordUserOutcome(e,t,n,r,a,o=0,s=0,c){let{user:l,course:u,userId:d}=e,p=u.getCourseID(),m=computeOutcomeSignal(r,c);if(m===null){logger.debug(`[Orchestration] No outcome signal computed for ${d} (insufficient data). Skipping record.`);return}let g={};for(let t of a)g[t]=e.getDeviation(t);let _=`USER_OUTCOME::${p}::${d}::${n}`,v={_id:_,docType:`USER_OUTCOME`,courseId:p,userId:d,periodStart:t,periodEnd:n,outcomeValue:m,deviations:g,metadata:{sessionsCount:1,cardsSeen:r.length,eloStart:o,eloEnd:s,signalType:`accuracy_in_zone`}};try{await l.putUserOutcome(v),logger.debug(`[Orchestration] Recorded outcome ${m.toFixed(3)} for ${d} (doc: ${_})`)}catch(e){logger.error(`[Orchestration] Failed to record outcome: ${e}`)}}var init_recording=__esm({"src/core/orchestration/recording.ts"(){init_signal(),init_types_legacy(),init_logger()}});function fnv1a(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}function computeDeviation(e,t,n){return fnv1a(`${e}:${t}:${n}`)/4294967296*2-1}function computeSpread(e){return MAX_SPREAD-Math.max(0,Math.min(1,e))*(MAX_SPREAD-MIN_SPREAD)}function computeEffectiveWeight(e,t,n,r){let a=computeDeviation(t,n,r)*computeSpread(e.confidence)*e.weight,o=e.weight+a;return Math.max(MIN_WEIGHT,Math.min(MAX_WEIGHT,o))}async function createOrchestrationContext(e,t){let n;try{n=await t.getCourseConfig()}catch(e){logger.error(`[Orchestration] Failed to load course config: ${e}`),n={name:`Unknown`,description:``,public:!1,deleted:!1,creator:``,admins:[],moderators:[],dataShapes:[],questionTypes:[],orchestration:{salt:`default`}}}let r=e.getUsername(),a=n.orchestration?.salt||`default_salt`;return{user:e,course:t,userId:r,courseConfig:n,getEffectiveWeight(e,t){return computeEffectiveWeight(t,r,e,a)},getDeviation(e){return computeDeviation(r,e,a)}}}var MIN_SPREAD,MAX_SPREAD,MIN_WEIGHT,MAX_WEIGHT,init_orchestration=__esm({"src/core/orchestration/index.ts"(){init_logger(),init_gradient(),init_learning(),init_signal(),init_recording(),MIN_SPREAD=.1,MAX_SPREAD=.5,MIN_WEIGHT=.1,MAX_WEIGHT=3}}),Pipeline_exports={};__export(Pipeline_exports,{Pipeline:()=>Pipeline});function globToRegex(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function globMatch(e,t){return t.includes(`*`)?globToRegex(t).test(e):e===t}function cardMatchesTagPattern(e,t){return(e.tags??[]).some(e=>globMatch(e,t))}function mergeHints2(e){let t=e.filter(e=>e!=null);if(t.length===0)return;let n={},r={};for(let e of t)for(let[t,n]of Object.entries(e.boostTags??{}))r[t]=(r[t]??1)*n;Object.keys(r).length>0&&(n.boostTags=r);let a={};for(let e of t)for(let[t,n]of Object.entries(e.boostCards??{}))a[t]=(a[t]??1)*n;Object.keys(a).length>0&&(n.boostCards=a);let concatUnique=e=>{let r=t.flatMap(t=>t[e]??[]);r.length>0&&(n[e]=[...new Set(r)])};concatUnique(`requireTags`),concatUnique(`requireCards`),concatUnique(`excludeTags`),concatUnique(`excludeCards`);let o=t.map(e=>e._label).filter(Boolean);return o.length>0&&(n._label=o.join(`; `)),Object.keys(n).length>0?n:void 0}function logPipelineConfig(e,t){let n=t.length>0?`
228
228
  - `+t.map(e=>e.name).join(`
229
229
  - `):` none`;logger.info(`[Pipeline] Configuration:
230
230
  Generator: ${e.name}
@@ -251,7 +251,7 @@ Currently logged-in as ${this._username}.`);let n=await this.syncStrategy.create
251
251
  Log out of account ${this.getUsername()} before logging in as ${e}.`);logger.warn(`User ${this._username} is already logged in, but executing login again.`)}let n=await this.syncStrategy.authenticate(e,t);if(n.ok){log4(`Logged in as ${e}`),this._username=e;try{localStorage.removeItem(`sk-guest-uuid`)}catch(e){logger.warn(`localStorage not available (Node.js environment):`,e)}await this.init()}return n}async resetUserData(){if(this.syncStrategy.canAuthenticate())return{status:Status.error,error:`Reset user data is only available for local-only mode. Use logout instead for remote sync.`};try{let e=getLocalUserDB(this._username),t=(await e.allDocs({include_docs:!1})).rows.filter(e=>{let t=e.id;return t.startsWith(DocTypePrefixes.CARDRECORD)||t.startsWith(DocTypePrefixes.SCHEDULED_CARD)||t.startsWith(DocTypePrefixes.STRATEGY_STATE)||t.startsWith(DocTypePrefixes.USER_OUTCOME)||t.startsWith(DocTypePrefixes.STRATEGY_LEARNING_STATE)||t===_BaseUser.DOC_IDS.COURSE_REGISTRATIONS||t===_BaseUser.DOC_IDS.CLASSROOM_REGISTRATIONS||t===_BaseUser.DOC_IDS.CONFIG}).map(e=>({_id:e.id,_rev:e.value.rev,_deleted:!0}));return t.length>0&&await e.bulkDocs(t),await this.init(),{status:Status.ok}}catch(e){return logger.error(`Failed to reset user data:`,e),{status:Status.error,error:e instanceof Error?e.message:`Unknown error during reset`}}}async logout(){if(!this.syncStrategy.canAuthenticate())return this._username=await this.syncStrategy.getCurrentUsername(),await this.init(),{ok:!0};let e=await this.syncStrategy.logout();return this._username=await this.syncStrategy.getCurrentUsername(),await this.init(),e}async get(e){return this.localDB.get(e)}update(e,t){return this.updateQueue.update(e,t)}async getCourseRegistrationsDoc(){logger.debug(`Fetching courseRegistrations for ${this.getUsername()}`);let e;try{return await this.localDB.get(_BaseUser.DOC_IDS.COURSE_REGISTRATIONS)}catch(t){if(t.status===404)await this.localDB.put({_id:_BaseUser.DOC_IDS.COURSE_REGISTRATIONS,courses:[],studyWeight:{}}),e=await this.getCourseRegistrationsDoc();else throw Error(`Unexpected error ${JSON.stringify(t)} in getOrCreateCourseRegistrationDoc...`)}return e}async getActiveCourses(){return(await this.getCourseRegistrationsDoc()).courses.filter(e=>e.status===void 0||e.status===`active`)}async getActiveCards(){let e=getStartAndEndKeys(DocTypePrefixes.SCHEDULED_CARD);return(await this.remoteDB.allDocs({startkey:e.startkey,endkey:e.endkey,include_docs:!0})).rows.map(e=>({courseID:e.doc.courseId,cardID:e.doc.cardId}))}async getActivityRecords(){try{let e=await this.getHistory(),t=[];if(!Array.isArray(e))return logger.error(`getHistory did not return an array:`,e),t;let n=0;for(let r=0;r<e.length;r++)try{e[r]&&Array.isArray(e[r].records)&&e[r].records.forEach(e=>{try{if(!e.timeStamp)return;let r;if(typeof e.timeStamp==`object`)if(typeof e.timeStamp.toDate==`function`)r=e.timeStamp.toISOString();else if(e.timeStamp instanceof Date)r=e.timeStamp.toISOString();else{n<3&&(logger.warn(`Unknown timestamp object type:`,e.timeStamp),n++);return}else if(typeof e.timeStamp==`string`){let t=new Date(e.timeStamp);if(isNaN(t.getTime()))return;r=e.timeStamp}else if(typeof e.timeStamp==`number`)r=new Date(e.timeStamp).toISOString();else return;t.push({timeStamp:r,courseID:e.courseID||`unknown`,cardID:e.cardID||`unknown`,timeSpent:e.timeSpent||0,type:`card_view`})}catch{}})}catch(e){logger.error(`Error processing history item:`,e)}return logger.debug(`Found ${t.length} activity records`),t}catch(e){return logger.error(`Error in getActivityRecords:`,e),[]}}async getReviewstoDate(e,t){let n=getStartAndEndKeys(DocTypePrefixes.SCHEDULED_CARD),r=await this.remoteDB.allDocs({startkey:n.startkey,endkey:n.endkey,include_docs:!0});return log4(`Fetching ${this._username}'s scheduled reviews${t?` for course ${t}`:``}.`),r.rows.filter(n=>{if(n.id.startsWith(DocTypePrefixes.SCHEDULED_CARD)){let r=hooks.utc(n.id.substr(DocTypePrefixes.SCHEDULED_CARD.length),REVIEW_TIME_FORMAT);if(e.isAfter(r)&&(t===void 0||n.doc.courseId===t))return!0}}).map(e=>e.doc)}async getReviewsForcast(e){let t=hooks.utc().add(e,`days`);return this.getReviewstoDate(t)}async getPendingReviews(e){let t=hooks.utc();return this.getReviewstoDate(t,e)}async getScheduledReviewCount(e){return(await this.getPendingReviews(e)).length}async getRegisteredCourses(){return(await this.getCourseRegistrationsDoc()).courses.filter(e=>!e.status||e.status===`active`||e.status===`maintenance-mode`)}async getCourseRegDoc(e){let t=(await this.getCourseRegistrationsDoc()).courses.find(t=>t.courseID===e);if(t)return t;throw Error(`Course registration not found for course ID: ${e}`)}async registerForCourse(e,t=!1){return this.getCourseRegistrationsDoc().then(n=>{let r=t?`preview`:`active`;logger.debug(`Registering for ${e} with status: ${r}`);let a={status:r,courseID:e,user:!0,admin:!1,moderator:!1,elo:{global:{score:1e3,count:0},tags:{},misc:{}}};return n.courses.filter(e=>e.courseID===a.courseID).length===0?(log4(`It's a new course registration!`),n.courses.push(a),n.studyWeight[e]=1):n.courses.forEach(t=>{log4(`Found the previously registered course!`),t.courseID===e&&(t.status=r)}),this.localDB.put(n)}).catch(e=>{throw log4(`Registration failed because of: ${JSON.stringify(e)}`),e})}async dropCourse(e,t=`dropped`){return this.getCourseRegistrationsDoc().then(n=>{let r=-1;for(let t=0;t<n.courses.length;t++)n.courses[t].courseID===e&&(r=t);if(r!==-1)delete n.studyWeight[e],n.courses[r].status=t;else throw Error(`User ${this.getUsername()} is not currently registered for course ${e}`);return this.localDB.put(n)})}async getCourseInterface(e){return new UsrCrsData(this,e)}async getUserEditableCourses(){let e=[],t=await this.getCourseRegistrationsDoc();return e=e.concat(t.courses.map(e=>e.courseID)),await Promise.all(e.map(async e=>await getCredentialledCourseConfig(e)))}async getConfig(){let e={_id:_BaseUser.DOC_IDS.CONFIG,darkMode:!1,likesConfetti:!1,sessionTimeLimit:5};try{let e=await this.localDB.get(_BaseUser.DOC_IDS.CONFIG);return logger.debug(`Raw config from DB:`,e),e}catch(t){let n=t;if(n.name&&n.name===`not_found`)return await this.localDB.put(e),this.getConfig();throw logger.error(`Error setting user default config:`,t),Error(`Error returning the user's configuration: ${JSON.stringify(t)}`)}}async setConfig(e){logger.debug(`Setting Config items ${JSON.stringify(e)}`);let t=await this.getConfig(),n=await this.localDB.put({...t,...e});n.ok?logger.debug(`Config items set: ${JSON.stringify(e)}`):logger.error(`Error setting config items: ${JSON.stringify(n)}`)}static async instance(e,t){return t?(_BaseUser._instance=new _BaseUser(t,e),await _BaseUser._instance.init(),_BaseUser._instance):_BaseUser._instance&&_BaseUser._initialized?_BaseUser._instance:_BaseUser._instance?new Promise(e=>{(function waitForUser(){if(_BaseUser._initialized)return e(_BaseUser._instance);setTimeout(waitForUser,50)})()}):(_BaseUser._instance=new _BaseUser(await e.getCurrentUsername(),e),await _BaseUser._instance.init(),_BaseUser._instance)}constructor(e,t){_defineProperty(this,`_username`,void 0),_defineProperty(this,`syncStrategy`,void 0),_defineProperty(this,`localDB`,void 0),_defineProperty(this,`remoteDB`,void 0),_defineProperty(this,`writeDB`,void 0),_defineProperty(this,`updateQueue`,void 0),_BaseUser._initialized=!1,this._username=e,this.syncStrategy=t,this.setDBandQ()}setDBandQ(){this.localDB=getLocalUserDB(this._username),this.remoteDB=this.syncStrategy.setupRemoteDB(this._username),this.writeDB=this.syncStrategy.getWriteDB?this.syncStrategy.getWriteDB(this._username):this.localDB,this.updateQueue=new UpdateQueue(this.localDB,this.writeDB)}async init(){if(_BaseUser._initialized=!1,this._username===`admin`){_BaseUser._initialized=!0;return}this.setDBandQ(),this.syncStrategy.startSync(this.localDB,this.remoteDB),this.applyDesignDocs().catch(e=>{log4(`Error in applyDesignDocs background task: ${e}`),e&&typeof e==`object`&&log4(`Full error details in applyDesignDocs: ${JSON.stringify(e)}`)}),this.deduplicateReviews().catch(e=>{log4(`Error in deduplicateReviews background task: ${e}`),e&&typeof e==`object`&&log4(`Full error details in background task: ${JSON.stringify(e)}`)}),_BaseUser._initialized=!0}async applyDesignDocs(){if(log4(`Starting applyDesignDocs for user: ${this._username}`),log4(`Remote DB name: ${this.remoteDB.name||`unknown`}`),this._username===`admin`){log4(`Skipping design docs for admin user`);return}log4(`Applying ${_BaseUser.designDocs.length} design docs`);for(let e of _BaseUser.designDocs){log4(`Applying design doc: ${e._id}`);try{try{let t=await this.remoteDB.get(e._id);await this.remoteDB.put({...e,_rev:t._rev})}catch(t){if(t instanceof Error&&t.name===`not_found`)await this.remoteDB.put(e);else throw t}}catch(t){if(t.name&&t.name===`conflict`)logger.warn(`Design doc ${e._id} update conflict - will retry`),await new Promise(e=>setTimeout(e,1e3)),await this.applyDesignDoc(e);else throw logger.error(`Failed to apply design doc ${e._id}:`,t),t}}}async applyDesignDoc(e,t=3){try{let t=await this.remoteDB.get(e._id);await this.remoteDB.put({...e,_rev:t._rev})}catch(n){if(n instanceof Error&&n.name===`conflict`&&t>0)return await new Promise(e=>setTimeout(e,1e3)),this.applyDesignDoc(e,t-1);throw n}}async putCardRecord(e){let t=getCardHistoryID(e.courseID,e.cardID);e.timeStamp=hooks.utc(e.timeStamp).toString();try{let n=await this.update(t,function(t){return t.records.push(e),t.bestInterval=t.bestInterval||0,t.lapses=t.lapses||0,t.streak=t.streak||0,t});return n.records=n.records.map(e=>{let t={...e};return t.timeStamp=hooks.utc(e.timeStamp),t}),n}catch(n){let r=n;if(r.status===404)try{let n={_id:t,cardID:e.cardID,courseID:e.courseID,records:[e],lapses:0,streak:0,bestInterval:0},r=await this.writeDB.put(n);return{...n,_rev:r.rev}}catch(e){throw Error(`Failed to create CardHistory for ${t}. Reason: ${e}`)}else throw Error(`putCardRecord failed because of:
252
252
  name:${r.name}
253
253
  error: ${r.error}
254
- message: ${r.message}`)}}async deduplicateReviews(){try{log4(`Starting deduplication of scheduled reviews...`),log4(`Remote DB name: ${this.remoteDB.name||`unknown`}`),log4(`Write DB name: ${this.writeDB.name||`unknown`}`);let e={},t=[];log4(`Attempting to query remoteDB for reviewCards/reviewCards. Database: ${this.remoteDB.name||`unknown`}`);let n=await this.remoteDB.query(`reviewCards/reviewCards`);if(log4(`Found ${n.rows.length} scheduled reviews to process`),n.rows.forEach(n=>{let r=n.value,a=n.key;e[r]?(log4(`Found duplicate scheduled review for card: ${r}`),log4(`Marking earlier review ${e[r]} for deletion, keeping ${a}`),t.push(e[r]),e[r]=a):e[r]=a}),t.length>0){log4(`Removing ${t.length} duplicate reviews...`);let e=t.map(async e=>{try{let t=await this.remoteDB.get(e);await this.writeDB.remove(t),log4(`Successfully removed duplicate review: ${e}`)}catch(t){log4(`Failed to remove duplicate review ${e}: ${t}`)}});await Promise.all(e),log4(`Deduplication complete. Processed ${t.length} duplicates`)}else log4(`No duplicate reviews found`)}catch(e){log4(`Error during review deduplication: ${e}`),e&&typeof e==`object`&&`status`in e&&e.status===404&&(log4(`Database not found (404) during review deduplication. Database: ${this.remoteDB.name||`unknown`}`),log4(`This might indicate the user database doesn't exist or the reviewCards view isn't available`)),e&&typeof e==`object`&&log4(`Full error details: ${JSON.stringify(e)}`)}}async getSeenCards(e){let t=DocTypePrefixes.CARDRECORD;e&&(t+=e);let n=await filterAllDocsByPrefix(this.localDB,t,{include_docs:!1}),r=[];return n.rows.forEach(e=>{e.id.startsWith(DocTypePrefixes.CARDRECORD)&&r.push(e.id.substr(DocTypePrefixes.CARDRECORD.length))}),r}async getHistory(){return(await filterAllDocsByPrefix(this.remoteDB,DocTypePrefixes.CARDRECORD,{include_docs:!0,attachments:!1})).rows.map(e=>e.doc)}async updateCourseSettings(e,t){this.getCourseRegistrationsDoc().then(n=>{let r=n.courses.find(t=>t.courseID===e);return r&&((r.settings===null||r.settings===void 0)&&(r.settings={}),t.forEach(e=>{r.settings[e.key]=e.value})),this.localDB.put(n)})}async getCourseSettings(e){let t=(await this.getCourseRegistrationsDoc()).courses.find(t=>t.courseID===e);if(t)return t.settings;throw Error(`getCourseSettings Failed:
254
+ message: ${r.message}`)}}async deduplicateReviews(){try{log4(`Starting deduplication of scheduled reviews...`),log4(`Remote DB name: ${this.remoteDB.name||`unknown`}`),log4(`Write DB name: ${this.writeDB.name||`unknown`}`);let e={},t=[];log4(`Attempting to query remoteDB for reviewCards/reviewCards. Database: ${this.remoteDB.name||`unknown`}`);let n=await this.remoteDB.query(`reviewCards/reviewCards`);if(log4(`Found ${n.rows.length} scheduled reviews to process`),n.rows.forEach(n=>{let r=n.value,a=n.key;e[r]?(log4(`Found duplicate scheduled review for card: ${r}`),log4(`Marking earlier review ${e[r]} for deletion, keeping ${a}`),t.push(e[r]),e[r]=a):e[r]=a}),t.length>0){log4(`Removing ${t.length} duplicate reviews...`);let e=t.map(async e=>{try{let t=await this.remoteDB.get(e);await this.writeDB.remove(t),log4(`Successfully removed duplicate review: ${e}`)}catch(t){log4(`Failed to remove duplicate review ${e}: ${t}`)}});await Promise.all(e),log4(`Deduplication complete. Processed ${t.length} duplicates`)}else log4(`No duplicate reviews found`)}catch(e){log4(`Error during review deduplication: ${e}`),e&&typeof e==`object`&&`status`in e&&e.status===404&&(log4(`Database not found (404) during review deduplication. Database: ${this.remoteDB.name||`unknown`}`),log4(`This might indicate the user database doesn't exist or the reviewCards view isn't available`)),e&&typeof e==`object`&&log4(`Full error details: ${JSON.stringify(e)}`)}}async getSeenCards(e){let t=DocTypePrefixes.CARDRECORD;e&&(t+=`-${e}-`);let n=await filterAllDocsByPrefix(this.localDB,t,{include_docs:!1}),r=[];return n.rows.forEach(e=>{e.id.startsWith(t)&&r.push(e.id.substr(t.length))}),r}async getHistory(){return(await filterAllDocsByPrefix(this.remoteDB,DocTypePrefixes.CARDRECORD,{include_docs:!0,attachments:!1})).rows.map(e=>e.doc)}async updateCourseSettings(e,t){this.getCourseRegistrationsDoc().then(n=>{let r=n.courses.find(t=>t.courseID===e);return r&&((r.settings===null||r.settings===void 0)&&(r.settings={}),t.forEach(e=>{r.settings[e.key]=e.value})),this.localDB.put(n)})}async getCourseSettings(e){let t=(await this.getCourseRegistrationsDoc()).courses.find(t=>t.courseID===e);if(t)return t.settings;throw Error(`getCourseSettings Failed:
255
255
  User is not registered for course ${e}`)}async getOrCreateClassroomRegistrationsDoc(){let e;try{e=await this.remoteDB.get(_BaseUser.DOC_IDS.CLASSROOM_REGISTRATIONS)}catch(t){let n=t;if(n.status===404)await this.writeDB.put({_id:_BaseUser.DOC_IDS.CLASSROOM_REGISTRATIONS,registrations:[]}),e=await this.getOrCreateClassroomRegistrationsDoc();else{let e={name:n.name,status:n.status,message:n.message,reason:n.reason,error:n.error};throw logger.error(`Database error in getOrCreateClassroomRegistrationsDoc (private method):`,e),Error(`Database error accessing classroom registrations: ${n.message||n.name||`Unknown error`} (status: ${n.status})`)}}return logger.debug(`Returning classroom registrations doc: ${JSON.stringify(e)}`),e}async getActiveClasses(){try{return(await this.getOrCreateClassroomRegistrationsDoc()).registrations.filter(e=>e.registeredAs===`student`).map(e=>e.classID)}catch(e){return logger.warn(`Failed to load classroom registrations, continuing without classroom data:`,e),[]}}async scheduleCardReview(e){return scheduleCardReviewLocal(this.writeDB,e)}async removeScheduledCardReview(e){return removeScheduledCardReviewLocal(this.writeDB,e)}async registerForClassroom(e,t){return registerUserForClassroom(this._username,e,t)}async dropFromClassroom(e){return dropUserFromClassroom(this._username,e)}async getUserClassrooms(){return getUserClassrooms(this._username)}async updateUserElo(e,t){return updateUserElo(this._username,e,t)}async getStrategyState(e,t){let n=buildStrategyStateId(e,t);try{return(await this.localDB.get(n)).data}catch(e){if(e.status===404)return null;throw e}}async putStrategyState(e,t,n){let r=buildStrategyStateId(e,t),a;try{a=(await this.localDB.get(r))._rev}catch(e){if(e.status!==404)throw e}let o={_id:r,_rev:a,docType:`STRATEGY_STATE`,courseId:e,strategyKey:t,data:n,updatedAt:new Date().toISOString()};await this.localDB.put(o)}async putUserOutcome(e){try{await this.localDB.put(e)}catch(t){if(t.status===409)e._rev=(await this.localDB.get(e._id))._rev,await this.localDB.put(e);else throw t}}async deleteStrategyState(e,t){let n=buildStrategyStateId(e,t);try{let e=await this.localDB.get(n);await this.localDB.remove(e)}catch(e){if(e.status===404)return;throw e}}},_defineProperty(e,`_instance`,void 0),_defineProperty(e,`_initialized`,!1),_defineProperty(e,`DOC_IDS`,{CONFIG:`CONFIG`,COURSE_REGISTRATIONS:`CourseRegistrations`,CLASSROOM_REGISTRATIONS:`ClassroomRegistrations`}),_defineProperty(e,`designDocs`,[{_id:`_design/reviewCards`,views:{reviewCards:{map:`function (doc) {
256
256
  if (doc._id && doc._id.indexOf('card_review') === 0 && doc.courseId && doc.cardId) {
257
257
  emit(doc._id, doc.courseId + '-' + doc.cardId);
@@ -294,7 +294,7 @@ Examples:
294
294
  Card: ${JSON.stringify(e.cardElo)})
295
295
  `)}}else logger.warn(`[EloService] Partial ELO update (per-tag):
296
296
  User ELO update: ${c?`SUCCESS`:`FAILED`}
297
- Card ELO update: ${l?`SUCCESS`:`FAILED`}`),!c&&a[0].status===`rejected`&&logger.error(`[EloService] User ELO update error:`,a[0].reason),!l&&a[1].status===`rejected`&&logger.error(`[EloService] Card ELO update error:`,a[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}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):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){if(e.priorAttemps===0){this.srsService.scheduleReview(t,n);let{globalScore:c,taggedPerformance:l}=this.parsePerformance(e.performance);if(l){let e=Object.keys(l).filter(e=>e!==`_global`),t=e.filter(e=>l[e]===null),n=e.filter(e=>l[e]!==null);logger.info(`[ResponseProcessor] per-tag ELO update for ${s}: scored=[${n.join(`, `)}] count-only=[${t.join(`, `)}]`),this.eloService.updateUserAndCardEloPerTag(l,o,s,r,a)}else{let e=.5+c/2;if(t.records.length===1)this.eloService.updateUserAndCardElo(e,o,s,r,a);else{let n=Math.ceil(32/t.records.length);this.eloService.updateUserAndCardElo(e,o,s,r,a,n)}logger.info(`[ResponseProcessor] Processed correct response with SRS scheduling and ELO update`)}return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:c,shouldClearFeedbackShadow:!0}}else{logger.info(`[ResponseProcessor] Processed correct response (retry attempt - no scheduling/ELO)`);let{globalScore:t}=this.parsePerformance(e.performance);return{nextCardAction:`marked-failed`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:t,shouldClearFeedbackShadow:!0}}}processIncorrectResponse(e,t,n,r,a,o,s,c,l){let{taggedPerformance:u}=this.parsePerformance(e.performance);return t.records.length!==1&&e.priorAttemps===0?u?(this.eloService.updateUserAndCardEloPerTag(u,a,o,n,r),logger.info(`[ResponseProcessor] Processed incorrect response with per-tag ELO update (${Object.keys(u).length-1} tags)`)):(this.eloService.updateUserAndCardElo(0,a,o,n,r),logger.info(`[ResponseProcessor] Processed incorrect response with ELO update`)):logger.info(`[ResponseProcessor] Processed incorrect response (no ELO update needed)`),r.records.length>=s?l>=c?(u?this.eloService.updateUserAndCardEloPerTag(u,a,o,n,r):this.eloService.updateUserAndCardElo(0,a,o,n,r),{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,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){let n=0,r=[];for(let a of e){let e=t(a);this.seenCardIds.includes(e)||(this.seenCardIds.push(e),r.push(a),n++)}return this.q.unshift(...r),n}get toString(){return`${typeof this.q[0]}:
297
+ Card ELO update: ${l?`SUCCESS`:`FAILED`}`),!c&&a[0].status===`rejected`&&logger.error(`[EloService] User ELO update error:`,a[0].reason),!l&&a[1].status===`rejected`&&logger.error(`[EloService] Card ELO update error:`,a[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}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):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){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 e=Object.keys(l).filter(e=>e!==`_global`),t=e.filter(e=>l[e]===null),n=e.filter(e=>l[e]!==null);logger.info(`[ResponseProcessor] per-tag ELO update for ${s}: scored=[${n.join(`, `)}] count-only=[${t.join(`, `)}]`),this.eloService.updateUserAndCardEloPerTag(l,o,s,r,a)}else{let e=.5+c/2;if(t.records.length===1)this.eloService.updateUserAndCardElo(e,o,s,r,a);else{let n=Math.ceil(32/t.records.length);this.eloService.updateUserAndCardElo(e,o,s,r,a,n)}logger.info(`[ResponseProcessor] Processed correct response with SRS scheduling and ELO update`)}return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:c,shouldClearFeedbackShadow:!0}}else{logger.info(`[ResponseProcessor] Processed correct response (retry attempt - no scheduling/ELO)`);let{globalScore:t}=this.parsePerformance(e.performance);return{nextCardAction:`marked-failed`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:t,shouldClearFeedbackShadow:!0}}}processIncorrectResponse(e,t,n,r,a,o,s,c,l){let{taggedPerformance:u}=this.parsePerformance(e.performance);return t.records.length!==1&&e.priorAttemps===0?u?(this.eloService.updateUserAndCardEloPerTag(u,a,o,n,r),logger.info(`[ResponseProcessor] Processed incorrect response with per-tag ELO update (${Object.keys(u).length-1} tags)`)):(this.eloService.updateUserAndCardElo(0,a,o,n,r),logger.info(`[ResponseProcessor] Processed incorrect response with ELO update`)):logger.info(`[ResponseProcessor] Processed incorrect response (no ELO update needed)`),r.records.length>=s?l>=c?(u?this.eloService.updateUserAndCardEloPerTag(u,a,o,n,r):this.eloService.updateUserAndCardElo(0,a,o,n,r),{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,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){let n=0,r=[];for(let a of e){let e=t(a);this.seenCardIds.includes(e)||(this.seenCardIds.push(e),r.push(a),n++)}return this.q.unshift(...r),n}get toString(){return`${typeof this.q[0]}:
298
298
  `+this.q.map(e=>` ${e.courseID}+${e.cardID}: ${e.status}`).join(`
299
299
  `)}};init_couch(),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();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(`
300
300
  \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(`
@@ -341,13 +341,14 @@ Example:
341
341
  window.skuilder.session.showQueue()
342
342
  `)}};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.reviewQ.dequeueCount,t=this.newQ.dequeueCount;return`${e} ${e===1?`review`:`reviews`}, ${t} ${t===1?`new card`:`new cards`}`}get detailedReport(){return this.newQ.toString+`
343
343
  `+this.reviewQ.toString+`
344
- `+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,`reviewQ`,new ItemQueue),_defineProperty(this,`newQ`,new ItemQueue),_defineProperty(this,`failedQ`,new ItemQueue),_defineProperty(this,`_replanPromise`,null),_defineProperty(this,`_wellIndicatedRemaining`,0),_defineProperty(this,`_suppressQualityReplan`,!1),_defineProperty(this,`_depletionReplanAttempted`,!1),_defineProperty(this,`_minCardsGuarantee`,0),_defineProperty(this,`startTime`,void 0),_defineProperty(this,`endTime`,void 0),_defineProperty(this,`_secondsRemaining`,void 0),_defineProperty(this,`_intervalHandle`,void 0),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),this.log(`Session constructed:
344
+ `+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,`_initialReviewCap`,200),_defineProperty(this,`sources`,void 0),_defineProperty(this,`_sessionRecord`,[]),_defineProperty(this,`_currentCard`,null),_defineProperty(this,`reviewQ`,new ItemQueue),_defineProperty(this,`newQ`,new ItemQueue),_defineProperty(this,`failedQ`,new ItemQueue),_defineProperty(this,`_replanPromise`,null),_defineProperty(this,`_wellIndicatedRemaining`,0),_defineProperty(this,`_suppressQualityReplan`,!1),_defineProperty(this,`_depletionReplanAttempted`,!1),_defineProperty(this,`_minCardsGuarantee`,0),_defineProperty(this,`startTime`,void 0),_defineProperty(this,`endTime`,void 0),_defineProperty(this,`_secondsRemaining`,void 0),_defineProperty(this,`_intervalHandle`,void 0),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?.initialReviewCap!==void 0&&(this._initialReviewCap=o.initialReviewCap),this.log(`Session constructed:
345
345
  startTime: ${this.startTime}
346
346
  endTime: ${this.endTime}
347
- defaultBatchLimit: ${this._defaultBatchLimit}`)}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}estimateReviewTime(){let e=5*this.reviewQ.length;return this.log(`Review card time estimate: ${e}`),e}async prepareSession(){if(this.sources.some(e=>typeof e.getWeightedCards!=`function`))throw Error(`[SessionController] All content sources must implement getWeightedCards().`);let e=await this.getWeightedContent();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.reviewQ.length,this.newQ.length,this.failedQ.length),this._intervalHandle=setInterval(()=>{this.tick()},1e3)}async requestReplan(e){let t=this.normalizeReplanOptions(e);if((t.hints||t.label||t.limit)&&(this._depletionReplanAttempted=!1),this._replanPromise)return this.log(`Replan already in progress, awaiting existing replan`),this._replanPromise;if(this._currentCard?.item.cardID){let e=this._currentCard.item.cardID;t.hints||(t.hints={});let n=t.hints,r=n.excludeCards??[];r.includes(e)||r.push(e),n.excludeCards=r}if(t.hints){let e=t.label?{...t.hints,_label:t.label}:t.hints;for(let t of this.sources)t.setEphemeralHints?.(e)}let n=t.label?` [${t.label}]`:``;this.log(`Mid-session replan requested${n} (limit: ${t.limit??`default`}, mode: ${t.mode??`replace`}${t.hints?`, with hints`:``})`),t.minFollowUpCards!==void 0&&t.minFollowUpCards>0&&(this._minCardsGuarantee=Math.max(this._minCardsGuarantee,t.minFollowUpCards),this.log(`[Replan] Card guarantee set to ${this._minCardsGuarantee}`)),this._replanPromise=this._executeReplan(t);try{await this._replanPromise}finally{this._replanPromise=null}}normalizeReplanOptions(e){if(!e)return{};let t=[`hints`,`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._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`),this.newQ.length>0&&(this._depletionReplanAttempted=!1),await this.hydrationService.ensureHydratedCards();let a=e.label?` [${e.label}]`:``;this.log(`Replan complete${a}: newQ now has ${this.newQ.length} cards (mode=${n})`),snapshotQueues(this.reviewQ.length,this.newQ.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.reviewQ.length} Reviews, ${this.newQ.length} New, ${this.failedQ.length} failed`}reportString(){return`${this.reviewQ.dequeueCount} Reviews, ${this.newQ.dequeueCount} New, ${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`})}return n};return{api:{mode:e?`weighted`:`legacy`,description:e?`Using getWeightedCards() API with scored candidates`:`ERROR: getWeightedCards() not a function.`},reviewQueue:{length:this.reviewQ.length,dequeueCount:this.reviewQ.dequeueCount,items:extractQueueItems(this.reviewQ)},newQueue:{length:this.newQ.length,dequeueCount:this.newQ.dequeueCount,items:extractQueueItems(this.newQ)},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=[];for(let e=0;e<this.sources.length;e++){let t=this.sources[e];try{let n=(await t.getWeightedCards(r)).cards;a.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(a.length===0){if(t)return this.log(`Replan: no content from any source, keeping existing newQ`),-1;throw Error(`Cannot start session: failed to load content from all ${this.sources.length} source(s). Check logs for details.`)}let o=this.mixer.mix(a,r*this.sources.length),s=a.map(e=>e.weighted[0]?.courseId||`source-${e.sourceIndex}`);await Promise.all(s.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 c=s.map(e=>this.courseNameCache.get(e)),l=this.mixer instanceof QuotaRoundRobinMixer?Math.ceil(r*this.sources.length/a.length):void 0;captureMixerRun(this.mixer.constructor.name,a,s,c,r*this.sources.length,l,o);let u=o.filter(e=>getCardOrigin(e)===`review`),d=o.filter(e=>getCardOrigin(e)===`new`);logger.debug(`[reviews] got ${u.length} reviews from mixer`);let p=t?`Replan content:
347
+ defaultBatchLimit: ${this._defaultBatchLimit}
348
+ initialReviewCap: ${this._initialReviewCap}`)}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}estimateReviewTime(){let e=5*this.reviewQ.length;return this.log(`Review card time estimate: ${e}`),e}async prepareSession(){if(this.sources.some(e=>typeof e.getWeightedCards!=`function`))throw Error(`[SessionController] All content sources must implement getWeightedCards().`);let e=await this.getWeightedContent();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.reviewQ.length,this.newQ.length,this.failedQ.length),this._intervalHandle=setInterval(()=>{this.tick()},1e3)}async requestReplan(e){let t=this.normalizeReplanOptions(e);if((t.hints||t.label||t.limit)&&(this._depletionReplanAttempted=!1),this._replanPromise)return this.log(`Replan already in progress, awaiting existing replan`),this._replanPromise;t.hints||(t.hints={});let n=t.hints,r=new Set(n.excludeCards??[]);this._currentCard?.item.cardID&&r.add(this._currentCard.item.cardID);for(let e of this._sessionRecord)r.add(e.card.card_id);if(this.newQ.length>0&&r.add(this.newQ.peek(0).cardID),n.excludeCards=[...r],t.hints){let e=t.label?{...t.hints,_label:t.label}:t.hints;for(let t of this.sources)t.setEphemeralHints?.(e)}let a=t.label?` [${t.label}]`:``;this.log(`Mid-session replan requested${a} (limit: ${t.limit??`default`}, mode: ${t.mode??`replace`}${t.hints?`, with hints`:``})`),t.minFollowUpCards!==void 0&&t.minFollowUpCards>0&&(this._minCardsGuarantee=Math.max(this._minCardsGuarantee,t.minFollowUpCards),this.log(`[Replan] Card guarantee set to ${this._minCardsGuarantee}`)),this._replanPromise=this._executeReplan(t);try{await this._replanPromise}finally{this._replanPromise=null}}normalizeReplanOptions(e){if(!e)return{};let t=[`hints`,`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._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`),this.newQ.length>0&&(this._depletionReplanAttempted=!1),await this.hydrationService.ensureHydratedCards();let a=e.label?` [${e.label}]`:``;this.log(`Replan complete${a}: newQ now has ${this.newQ.length} cards (mode=${n})`),snapshotQueues(this.reviewQ.length,this.newQ.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.reviewQ.length} Reviews, ${this.newQ.length} New, ${this.failedQ.length} failed`}reportString(){return`${this.reviewQ.dequeueCount} Reviews, ${this.newQ.dequeueCount} New, ${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`})}return n};return{api:{mode:e?`weighted`:`legacy`,description:e?`Using getWeightedCards() API with scored candidates`:`ERROR: getWeightedCards() not a function.`},reviewQueue:{length:this.reviewQ.length,dequeueCount:this.reviewQ.dequeueCount,items:extractQueueItems(this.reviewQ)},newQueue:{length:this.newQ.length,dequeueCount:this.newQ.dequeueCount,items:extractQueueItems(this.newQ)},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=t?r:r+this._initialReviewCap,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 newQ`),-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=>getCardOrigin(e)===`review`).slice(0,this._initialReviewCap),p=s.filter(e=>getCardOrigin(e)===`new`).slice(0,r);logger.debug(`[reviews] got ${d.length} reviews from mixer`);let m=t?`Replan content:
348
349
  `:`Mixed content session created with:
349
- `;if(!t)for(let e of u){let t={cardID:e.cardId,courseID:e.courseId,contentSourceType:`course`,contentSourceID:e.courseId,reviewID:e.reviewID,status:`review`};this.reviewQ.add(t,t.cardID),p+=`Review: ${e.courseId}::${e.cardId} (score: ${e.score.toFixed(2)})
350
- `}let m=d.filter(e=>e.score>=_SessionController.WELL_INDICATED_SCORE).length,g=[];for(let e of d){let t={cardID:e.cardId,courseID:e.courseId,contentSourceType:`course`,contentSourceID:e.courseId,status:`new`};g.push(t),p+=`New: ${e.courseId}::${e.cardId} (score: ${e.score.toFixed(2)})
351
- `}if(n){let e=this.newQ.mergeToFront(g,e=>e.cardID);p+=`Additive merge: ${e} new cards added to front of newQ
352
- `}else if(t)this.newQ.replaceAll(g,e=>e.cardID);else for(let e of g)this.newQ.add(e,e.cardID);return this.log(p),m}_getItemsToHydrate(){let e=[],t=2;for(let t=0;t<Math.min(2,this.reviewQ.length);t++)e.push(this.reviewQ.peek(t));for(let t=0;t<Math.min(2,this.newQ.length);t++)e.push(this.newQ.peek(t));for(let t=0;t<Math.min(2,this.failedQ.length);t++)e.push(this.failedQ.peek(t));return e}_selectNextItemToHydrate(){let e=Math.random(),t=.1,n=.75;if(this.reviewQ.length===0&&this.failedQ.length===0&&this.newQ.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;if(this.newQ.dequeueCount<this.sources.length&&this.newQ.length)return this.newQ.peek(0);let r=this.estimateCleanupTime(),a=this.estimateReviewTime();return this._secondsRemaining-(r+a)>20?(t=.5,n=.9):this._secondsRemaining-r>20?(t=.05,n=.9):(t=.01,n=.1),this.failedQ.length===0&&(n=1),this.reviewQ.length===0&&(t=n),e<t&&this.newQ.length?this.newQ.peek(0):e<n&&this.reviewQ.length?this.reviewQ.peek(0):this.failedQ.length?this.failedQ.peek(0):(this.log(`No more cards available for the session!`),null)}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.log(`nextCard: awaiting in-flight replan before drawing`),await this._replanPromise),this.newQ.length<=1&&this._secondsRemaining>0&&!this._replanPromise&&!this._depletionReplanAttempted){this._suppressQualityReplan=!1,this._depletionReplanAttempted=!0;let e=this.reviewQ.length+this.failedQ.length;this.newQ.length===0&&e===0?(this.log(`[AutoReplan:depletion] All queues empty with ${this._secondsRemaining}s remaining. Awaiting replan.`),await this.requestReplan()):(this.log(`[AutoReplan:depletion] newQ has ${this.newQ.length} card(s) (${e} in other queues) with ${this._secondsRemaining}s remaining. Triggering background replan.`),this.requestReplan())}if(!this._suppressQualityReplan&&this._wellIndicatedRemaining<=3&&this.newQ.length>0&&!this._replanPromise&&(this.log(`[AutoReplan:quality] ${this._wellIndicatedRemaining} well-indicated cards remaining (newQ: ${this.newQ.length}). Triggering background replan.`),this.requestReplan()),this._secondsRemaining<=0&&this.failedQ.length===0&&this._minCardsGuarantee<=0)return this._currentCard=null,endSessionTracking(),null;let t=20;for(let e=0;e<20;e++){let e=this._selectNextItemToHydrate();if(!e)return this._currentCard=null,endSessionTracking(),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`:e.status===`review`?`reviewQ`:`newQ`;return recordCardPresentation(e.cardID,e.courseID,this.courseNameCache.get(e.courseID),n,r),snapshotQueues(this.reviewQ.length,this.newQ.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(),null}async submitResponse(e,t,n,r,a,o,s,c,l){let u={...r.item};return await this.services.response.processResponse(e,t,u,n,r,a,o,s,c,l)}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)}else (e===`dismiss-error`||e===`dismiss-failed`)&&this.hydrationService.removeCard(this._currentCard.item.cardID)}removeItemFromQueue(e){this.reviewQ.peek(0)?.cardID===e.cardID?this.reviewQ.dequeue(e=>e.cardID):this.newQ.peek(0)?.cardID===e.cardID?(this.newQ.dequeue(e=>e.cardID),this._wellIndicatedRemaining>0&&this._wellIndicatedRemaining--):this.failedQ.peek(0)?.cardID===e.cardID&&this.failedQ.dequeue(e=>e.cardID)}async endSession(){if(!this._sessionRecord||this._sessionRecord.length===0)return;let e=this._sessionRecord.flatMap(e=>e.records).filter(e=>e.userAnswer!==void 0);if(e.length===0)return;let t=null,n=[];for(let e of this.sources)if(e.getOrchestrationContext){try{t=await e.getOrchestrationContext(),e.getStrategyIds&&n.push(...e.getStrategyIds())}catch(e){logger.warn(`[SessionController] Failed to get orchestration context: ${e}`)}if(t)break}if(!t){logger.debug(`[SessionController] No orchestration context available, skipping outcome recording`);return}let r=new Date().toISOString(),a=new Date(this.startTime).toISOString();await recordUserOutcome(t,a,r,e,n)}},_defineProperty(_SessionController2,`MIN_WELL_INDICATED`,5),_defineProperty(_SessionController2,`WELL_INDICATED_SCORE`,.1),_SessionController2);init_TagFilteredContentSource(),init_factory();export{processCustomQuestionsData as $,getDbPath as A,isFilter as B,createOrchestrationContext as C,getCardHistoryID as D,getAppDataDirectory as E,hasRegisteredNavigator as F,log as G,isQuestionRecord as H,importParsedCards as I,mountPipelineDebugger as J,mixerDebugAPI as K,initializeDataDirectory as L,getRegisteredNavigatorNames as M,getRegisteredNavigatorRole as N,getCardOrigin as O,getStudySource as P,pipelineDebugAPI as Q,initializeDataLayer as R,computeSpread as S,ensureAppDataDirectory as T,isQuestionTypeRegistered as U,isGenerator as V,isReview as W,mountUserDBDebugger as X,mountSessionDebugger as Y,newInterval as Z,buildStrategyStateId as _,validateStaticCourse as _t,ENV as a,registerSeedData as at,computeEffectiveWeight as b,Loggable as c,scoreAccuracyInZone as ct,NavigatorRoles as d,startSessionTracking as dt,recordCardPresentation as et,Navigators as f,updateLearningState as ft,areQuestionRecords as g,validateProcessorConfig as gt,TagFilteredContentSource as h,validateMigration as ht,DocTypePrefixes as i,registerQuestionType as it,getRegisteredNavigator as j,getDataLayer as k,NOT_SET as l,sessionDebugAPI as lt,SessionController as m,userDBDebugAPI as mt,CourseLookup as n,registerDataShape as nt,FileSystemError as o,removeDataShape as ot,QuotaRoundRobinMixer as p,updateStrategyWeight as pt,mountMixerDebugger as q,DocType as r,registerNavigator as rt,GuestUsername as s,removeQuestionType as st,ContentNavigator as t,recordUserOutcome as tt,NavigatorRole as u,snapshotQueues as ut,captureMixerRun as v,endSessionTracking as w,computeOutcomeSignal as x,computeDeviation as y,initializeNavigatorRegistry as z};
353
- //# sourceMappingURL=dist-DkeESCP4.js.map
350
+ `;if(!t)for(let e of d){let t={cardID:e.cardId,courseID:e.courseId,contentSourceType:`course`,contentSourceID:e.courseId,reviewID:e.reviewID,status:`review`};this.reviewQ.add(t,t.cardID),m+=`Review: ${e.courseId}::${e.cardId} (score: ${e.score.toFixed(2)})
351
+ `}let g=p.filter(e=>e.score>=_SessionController.WELL_INDICATED_SCORE).length,_=[];for(let e of p){let t={cardID:e.cardId,courseID:e.courseId,contentSourceType:`course`,contentSourceID:e.courseId,status:`new`};_.push(t),m+=`New: ${e.courseId}::${e.cardId} (score: ${e.score.toFixed(2)})
352
+ `}if(n){let e=this.newQ.mergeToFront(_,e=>e.cardID);m+=`Additive merge: ${e} new cards added to front of newQ
353
+ `}else if(t)this.newQ.replaceAll(_,e=>e.cardID);else for(let e of _)this.newQ.add(e,e.cardID);return this.log(m),g}_getItemsToHydrate(){let e=[],t=2;for(let t=0;t<Math.min(2,this.reviewQ.length);t++)e.push(this.reviewQ.peek(t));for(let t=0;t<Math.min(2,this.newQ.length);t++)e.push(this.newQ.peek(t));for(let t=0;t<Math.min(2,this.failedQ.length);t++)e.push(this.failedQ.peek(t));return e}_selectNextItemToHydrate(){let e=Math.random(),t=.1,n=.75;if(this.reviewQ.length===0&&this.failedQ.length===0&&this.newQ.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;if(this.newQ.dequeueCount<this.sources.length&&this.newQ.length)return this.newQ.peek(0);let r=this.estimateCleanupTime(),a=this.estimateReviewTime();return this._secondsRemaining-(r+a)>20?(t=.5,n=.9):this._secondsRemaining-r>20?(t=.05,n=.9):(t=.01,n=.1),this.failedQ.length===0&&(n=1),this.reviewQ.length===0&&(t=n),e<t&&this.newQ.length?this.newQ.peek(0):e<n&&this.reviewQ.length?this.reviewQ.peek(0):this.failedQ.length?this.failedQ.peek(0):(this.log(`No more cards available for the session!`),null)}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.log(`nextCard: awaiting in-flight replan before drawing`),await this._replanPromise),this.newQ.length<=1&&this._secondsRemaining>0&&!this._replanPromise&&!this._depletionReplanAttempted){this._suppressQualityReplan=!1,this._depletionReplanAttempted=!0;let e=this.reviewQ.length+this.failedQ.length;this.newQ.length===0&&e===0?(this.log(`[AutoReplan:depletion] All queues empty with ${this._secondsRemaining}s remaining. Awaiting replan.`),await this.requestReplan()):(this.log(`[AutoReplan:depletion] newQ has ${this.newQ.length} card(s) (${e} in other queues) with ${this._secondsRemaining}s remaining. Triggering background replan.`),this.requestReplan())}if(!this._suppressQualityReplan&&this._wellIndicatedRemaining<=3&&this.newQ.length>0&&!this._replanPromise&&(this.log(`[AutoReplan:quality] ${this._wellIndicatedRemaining} well-indicated cards remaining (newQ: ${this.newQ.length}). Triggering background replan.`),this.requestReplan()),this._secondsRemaining<=0&&this.failedQ.length===0&&this._minCardsGuarantee<=0)return this._currentCard=null,endSessionTracking(),null;let t=20;for(let e=0;e<20;e++){let e=this._selectNextItemToHydrate();if(!e)return this._currentCard=null,endSessionTracking(),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`:e.status===`review`?`reviewQ`:`newQ`;return recordCardPresentation(e.cardID,e.courseID,this.courseNameCache.get(e.courseID),n,r),snapshotQueues(this.reviewQ.length,this.newQ.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(),null}async submitResponse(e,t,n,r,a,o,s,c,l){let u={...r.item};return await this.services.response.processResponse(e,t,u,n,r,a,o,s,c,l)}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)}else (e===`dismiss-error`||e===`dismiss-failed`)&&this.hydrationService.removeCard(this._currentCard.item.cardID)}removeItemFromQueue(e){this.reviewQ.peek(0)?.cardID===e.cardID?this.reviewQ.dequeue(e=>e.cardID):this.newQ.peek(0)?.cardID===e.cardID?(this.newQ.dequeue(e=>e.cardID),this._wellIndicatedRemaining>0&&this._wellIndicatedRemaining--):this.failedQ.peek(0)?.cardID===e.cardID&&this.failedQ.dequeue(e=>e.cardID)}async endSession(){if(!this._sessionRecord||this._sessionRecord.length===0)return;let e=this._sessionRecord.flatMap(e=>e.records).filter(e=>e.userAnswer!==void 0);if(e.length===0)return;let t=null,n=[];for(let e of this.sources)if(e.getOrchestrationContext){try{t=await e.getOrchestrationContext(),e.getStrategyIds&&n.push(...e.getStrategyIds())}catch(e){logger.warn(`[SessionController] Failed to get orchestration context: ${e}`)}if(t)break}if(!t){logger.debug(`[SessionController] No orchestration context available, skipping outcome recording`);return}let r=new Date().toISOString(),a=new Date(this.startTime).toISOString();await recordUserOutcome(t,a,r,e,n)}},_defineProperty(_SessionController2,`MIN_WELL_INDICATED`,5),_defineProperty(_SessionController2,`WELL_INDICATED_SCORE`,.1),_SessionController2);init_TagFilteredContentSource(),init_factory();export{processCustomQuestionsData as $,getDbPath as A,isFilter as B,createOrchestrationContext as C,getCardHistoryID as D,getAppDataDirectory as E,hasRegisteredNavigator as F,log as G,isQuestionRecord as H,importParsedCards as I,mountPipelineDebugger as J,mixerDebugAPI as K,initializeDataDirectory as L,getRegisteredNavigatorNames as M,getRegisteredNavigatorRole as N,getCardOrigin as O,getStudySource as P,pipelineDebugAPI as Q,initializeDataLayer as R,computeSpread as S,ensureAppDataDirectory as T,isQuestionTypeRegistered as U,isGenerator as V,isReview as W,mountUserDBDebugger as X,mountSessionDebugger as Y,newInterval as Z,buildStrategyStateId as _,validateStaticCourse as _t,ENV as a,registerSeedData as at,computeEffectiveWeight as b,Loggable as c,scoreAccuracyInZone as ct,NavigatorRoles as d,startSessionTracking as dt,recordCardPresentation as et,Navigators as f,updateLearningState as ft,areQuestionRecords as g,validateProcessorConfig as gt,TagFilteredContentSource as h,validateMigration as ht,DocTypePrefixes as i,registerQuestionType as it,getRegisteredNavigator as j,getDataLayer as k,NOT_SET as l,sessionDebugAPI as lt,SessionController as m,userDBDebugAPI as mt,CourseLookup as n,registerDataShape as nt,FileSystemError as o,removeDataShape as ot,QuotaRoundRobinMixer as p,updateStrategyWeight as pt,mountMixerDebugger as q,DocType as r,registerNavigator as rt,GuestUsername as s,removeQuestionType as st,ContentNavigator as t,recordUserOutcome as tt,NavigatorRole as u,snapshotQueues as ut,captureMixerRun as v,endSessionTracking as w,computeOutcomeSignal as x,computeDeviation as y,initializeNavigatorRegistry as z};
354
+ //# sourceMappingURL=dist-DKtzwGWn.js.map