@vue-skuilder/platform-ui 0.2.34 → 0.2.36

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 (190) hide show
  1. package/dist/assets/{About-sUaZ0Srj.js → About-74htcNLT.js} +2 -2
  2. package/dist/assets/{About-sUaZ0Srj.js.map → About-74htcNLT.js.map} +1 -1
  3. package/dist/assets/AdminDashboard-B00qno2M.js +2 -0
  4. package/dist/assets/{AdminDashboard-cKNlDTB2.js.map → AdminDashboard-B00qno2M.js.map} +1 -1
  5. package/dist/assets/AdminLearner-SJNtSyJ_.js +2 -0
  6. package/dist/assets/{AdminLearner-DXeevw2h.js.map → AdminLearner-SJNtSyJ_.js.map} +1 -1
  7. package/dist/assets/BaseUserDB-CV2ZPZOR.js +1 -0
  8. package/dist/assets/ClassroomCtrlPanel-BSAG3h8B.js +2 -0
  9. package/dist/assets/{ClassroomCtrlPanel-BeSz_WX4.js.map → ClassroomCtrlPanel-BSAG3h8B.js.map} +1 -1
  10. package/dist/assets/{Classrooms-DTBqomQE.js → Classrooms-DXNEbtsM.js} +3 -3
  11. package/dist/assets/{Classrooms-DTBqomQE.js.map → Classrooms-DXNEbtsM.js.map} +1 -1
  12. package/dist/assets/CouchDBSyncStrategy-BjM7ROXC.js +1 -0
  13. package/dist/assets/CourseRouter-CsVa_92r.js +7 -0
  14. package/dist/assets/{CourseRouter-CL8v2Zdk.js.map → CourseRouter-CsVa_92r.js.map} +1 -1
  15. package/dist/assets/CourseSyncService-CPU_Ll1h.js +1 -0
  16. package/dist/assets/CourseWare-BTFRjgBR-DBp_fIwH.js +3 -0
  17. package/dist/assets/{CourseWare-BTFRjgBR-C3GJRVef.js.map → CourseWare-BTFRjgBR-DBp_fIwH.js.map} +1 -1
  18. package/dist/assets/{Courses-CUff-WLk.js → Courses-CB6GGtdm.js} +3 -3
  19. package/dist/assets/{Courses-CUff-WLk.js.map → Courses-CB6GGtdm.js.map} +1 -1
  20. package/dist/assets/EloModeration-DUBgs-Vh.js +2 -0
  21. package/dist/assets/{EloModeration-6MUDz-Mu.js.map → EloModeration-DUBgs-Vh.js.map} +1 -1
  22. package/dist/assets/{JoinCode-CW9Lk23D.js → JoinCode-BBvYapCA.js} +2 -2
  23. package/dist/assets/{JoinCode-CW9Lk23D.js.map → JoinCode-BBvYapCA.js.map} +1 -1
  24. package/dist/assets/MarkdownRenderer-WG9YrHpe.js +1 -0
  25. package/dist/assets/MarkdownRenderer-borh39Lq.js +53 -0
  26. package/dist/assets/MarkdownRenderer-borh39Lq.js.map +1 -0
  27. package/dist/assets/NewCourseDialog-DBgFVnt3.js +2 -0
  28. package/dist/assets/{NewCourseDialog-CLm1rQyB.js.map → NewCourseDialog-DBgFVnt3.js.map} +1 -1
  29. package/dist/assets/PipelineDebugger-BHaqzqZw.js +177 -0
  30. package/dist/assets/PipelineDebugger-BHaqzqZw.js.map +1 -0
  31. package/dist/assets/PouchDataLayerProvider-DxsnSIKd.js +2 -0
  32. package/dist/assets/PouchDataLayerProvider-DxsnSIKd.js.map +1 -0
  33. package/dist/assets/{ReleaseNotes-CmITE6hd.js → ReleaseNotes-Dg6mLL1C.js} +2 -2
  34. package/dist/assets/{ReleaseNotes-CmITE6hd.js.map → ReleaseNotes-Dg6mLL1C.js.map} +1 -1
  35. package/dist/assets/RequestPasswordReset-CcFMTnTc.js +2 -0
  36. package/dist/assets/{RequestPasswordReset-DPE6S2dU.js.map → RequestPasswordReset-CcFMTnTc.js.map} +1 -1
  37. package/dist/assets/ResetPassword-Dw_cBJU2.js +2 -0
  38. package/dist/assets/{ResetPassword-Dl6nj4jF.js.map → ResetPassword-Dw_cBJU2.js.map} +1 -1
  39. package/dist/assets/StaticDataLayerProvider-CtgU3VBh.js +2 -0
  40. package/dist/assets/StaticDataLayerProvider-CtgU3VBh.js.map +1 -0
  41. package/dist/assets/Study-DDsGQCTJ.js +2 -0
  42. package/dist/assets/{Study-Cf5yVLaY.js.map → Study-DDsGQCTJ.js.map} +1 -1
  43. package/dist/assets/TagInformation-DBLoXA2a.js +2 -0
  44. package/dist/assets/{TagInformation-tqHJGkyw.js.map → TagInformation-DBLoXA2a.js.map} +1 -1
  45. package/dist/assets/User-DfXUXjFb.js +2 -0
  46. package/dist/assets/User-DfXUXjFb.js.map +1 -0
  47. package/dist/assets/UserDBDebugger-DPqlc4O_.js +23 -0
  48. package/dist/assets/UserDBDebugger-DPqlc4O_.js.map +1 -0
  49. package/dist/assets/UserDBDebugger-xmycWjck.js +1 -0
  50. package/dist/assets/UserStats-C04YVYv7.js +2 -0
  51. package/dist/assets/{UserStats-B25DZy-D.js.map → UserStats-C04YVYv7.js.map} +1 -1
  52. package/dist/assets/VerifyEmail-Y05BSR57.js +2 -0
  53. package/dist/assets/{VerifyEmail-DyWRQweA.js.map → VerifyEmail-Y05BSR57.js.map} +1 -1
  54. package/dist/assets/{admin-Cfzt4Vei.css → admin-CMwKoROX.css} +1 -1
  55. package/dist/assets/admin-DcFjvYJw.js +21 -0
  56. package/dist/assets/admin-DcFjvYJw.js.map +1 -0
  57. package/dist/assets/chess-E2uOAyQS-BZi0vihz.js +7 -0
  58. package/dist/assets/{chess-E2uOAyQS-CP3XwSpG.js.map → chess-E2uOAyQS-BZi0vihz.js.map} +1 -1
  59. package/dist/assets/chess-Lfm7Fsvs-DgN08Qx9.js +1 -0
  60. package/dist/assets/contentSource-DwznMSMs.js +34 -0
  61. package/dist/assets/contentSource-DwznMSMs.js.map +1 -0
  62. package/dist/assets/defineProperty-y9rbOPYz.js +1 -0
  63. package/dist/assets/dist-BcwaOf54.js +1 -0
  64. package/dist/assets/dist-BsRvt0gH.js +38 -0
  65. package/dist/assets/dist-BsRvt0gH.js.map +1 -0
  66. package/dist/assets/dist-CAHkbl3M.js +18 -0
  67. package/dist/assets/dist-CAHkbl3M.js.map +1 -0
  68. package/dist/assets/dist-CgW7D_Gh.js +1 -0
  69. package/dist/assets/dist-Dnehy0sn.js +1 -0
  70. package/dist/assets/dist-Dp6eBE2S.js +64 -0
  71. package/dist/assets/dist-Dp6eBE2S.js.map +1 -0
  72. package/dist/assets/edit-ui.es-BWqvElsJ.js +1 -0
  73. package/dist/assets/edit-ui.es-UaQFL_My.js +41 -0
  74. package/dist/assets/edit-ui.es-UaQFL_My.js.map +1 -0
  75. package/dist/assets/elo-B5qCwvSC.js +2 -0
  76. package/dist/assets/elo-B5qCwvSC.js.map +1 -0
  77. package/dist/assets/elo-COgu6Hu5.js +2 -0
  78. package/dist/assets/elo-COgu6Hu5.js.map +1 -0
  79. package/dist/assets/elo-Cwa8a3Yo.js +1 -0
  80. package/dist/assets/eloDistance-BV7vfiK5.js +2 -0
  81. package/dist/assets/eloDistance-BV7vfiK5.js.map +1 -0
  82. package/dist/assets/eloDistance-MReQeAuj.js +1 -0
  83. package/dist/assets/french-Dk7YG8Td-CD7Hms2j.js +2 -0
  84. package/dist/assets/{french-Dk7YG8Td-Bfl4cirn.js.map → french-Dk7YG8Td-CD7Hms2j.js.map} +1 -1
  85. package/dist/assets/french-evUMlbbq-nGCjilG6.js +1 -0
  86. package/dist/assets/hierarchyDefinition-DLC5DjaA.js +2 -0
  87. package/dist/assets/hierarchyDefinition-DLC5DjaA.js.map +1 -0
  88. package/dist/assets/{index-NFrxkZjT.css → index-B7mmpKZd.css} +1 -1
  89. package/dist/assets/index-CK-rfSIx.js +4 -0
  90. package/dist/assets/{index-JRi1udkz.js.map → index-CK-rfSIx.js.map} +1 -1
  91. package/dist/assets/interferenceMitigator-D78KgOxz.js +2 -0
  92. package/dist/assets/interferenceMitigator-D78KgOxz.js.map +1 -0
  93. package/dist/assets/logshim-YQI0WloD.js +2 -0
  94. package/dist/assets/logshim-YQI0WloD.js.map +1 -0
  95. package/dist/assets/math-DR3fXDcX-C9KfHLHP.js +1 -0
  96. package/dist/assets/math-D_8HiEQR-E4QDLrWp.js +34 -0
  97. package/dist/assets/{math-D_8HiEQR-B9oNpF-3.js.map → math-D_8HiEQR-E4QDLrWp.js.map} +1 -1
  98. package/dist/assets/moment-DbT30ZpG.js +5 -0
  99. package/dist/assets/moment-DbT30ZpG.js.map +1 -0
  100. package/dist/assets/piano-BN5Btq91-CnKhyLGE.js +1 -0
  101. package/dist/assets/piano-DF1g6yaX-Ck3BH5EK.js +2 -0
  102. package/dist/assets/{piano-DF1g6yaX-CjD06Qz8.js.map → piano-DF1g6yaX-Ck3BH5EK.js.map} +1 -1
  103. package/dist/assets/pitch-CgGJFkZ1-Dd0LzmEe.js +2 -0
  104. package/dist/assets/{pitch-CgGJFkZ1-C-2hdk99.js.map → pitch-CgGJFkZ1-Dd0LzmEe.js.map} +1 -1
  105. package/dist/assets/pitch-Dn0iNqiS-BxAdpDDb.js +1 -0
  106. package/dist/assets/prescribed-BWO17Gan.js +2 -0
  107. package/dist/assets/prescribed-BWO17Gan.js.map +1 -0
  108. package/dist/assets/relativePriority-DwPMECAp.js +2 -0
  109. package/dist/assets/relativePriority-DwPMECAp.js.map +1 -0
  110. package/dist/assets/server-CqR7xtQy.js +2 -0
  111. package/dist/assets/server-CqR7xtQy.js.map +1 -0
  112. package/dist/assets/{sightsing-BFQ7HRig-8K5qd7-K.js → sightsing-BFQ7HRig-DV69ELZf.js} +23 -23
  113. package/dist/assets/{sightsing-BFQ7HRig-8K5qd7-K.js.map → sightsing-BFQ7HRig-DV69ELZf.js.map} +1 -1
  114. package/dist/assets/sightsing-CJX3k0Fd-CG94OiDr.js +1 -0
  115. package/dist/assets/srs-DGscV6W4.js +1 -0
  116. package/dist/assets/srs-DOsG9Y-i.js +2 -0
  117. package/dist/assets/srs-DOsG9Y-i.js.map +1 -0
  118. package/dist/assets/tagRoles-jR-PJAgj.js +2 -0
  119. package/dist/assets/tagRoles-jR-PJAgj.js.map +1 -0
  120. package/dist/assets/typing-BevtfWlp-CvStu5BY.js +2 -0
  121. package/dist/assets/{typing-BevtfWlp-BT263ZFw.js.map → typing-BevtfWlp-CvStu5BY.js.map} +1 -1
  122. package/dist/assets/typing-k-ojjO7G-AF8vU_q7.js +1 -0
  123. package/dist/assets/userDBKeys-DYLGKnVC.js +4 -0
  124. package/dist/assets/userDBKeys-DYLGKnVC.js.map +1 -0
  125. package/dist/assets/userTagPreference-cZCPqadC.js +2 -0
  126. package/dist/assets/userTagPreference-cZCPqadC.js.map +1 -0
  127. package/dist/assets/validators-lpYAHmRR.js +2 -0
  128. package/dist/assets/validators-lpYAHmRR.js.map +1 -0
  129. package/dist/assets/word-work-BOnRlZgd-CCGZdwyf.js +2 -0
  130. package/dist/assets/{word-work-BOnRlZgd-BFwc1KBd.js.map → word-work-BOnRlZgd-CCGZdwyf.js.map} +1 -1
  131. package/dist/assets/word-work-Dd6tIKrt-BNTSCq5F.js +1 -0
  132. package/dist/assets/{workbox-window.prod.es5-r2bRTooK.js → workbox-window.prod.es5-YsLcd14J.js} +1 -1
  133. package/dist/assets/{workbox-window.prod.es5-r2bRTooK.js.map → workbox-window.prod.es5-YsLcd14J.js.map} +1 -1
  134. package/dist/index.html +17 -7
  135. package/dist/sw.js +1 -1
  136. package/dist/sw.js.map +1 -1
  137. package/package.json +7 -7
  138. package/dist/assets/AdminDashboard-cKNlDTB2.js +0 -2
  139. package/dist/assets/AdminLearner-DXeevw2h.js +0 -2
  140. package/dist/assets/ClassroomCtrlPanel-BeSz_WX4.js +0 -2
  141. package/dist/assets/CourseRouter-CL8v2Zdk.js +0 -7
  142. package/dist/assets/CourseWare-BTFRjgBR-C3GJRVef.js +0 -3
  143. package/dist/assets/EloModeration-6MUDz-Mu.js +0 -2
  144. package/dist/assets/MarkdownRenderer-U_iPiA2x-DDruDu7E.js +0 -53
  145. package/dist/assets/MarkdownRenderer-U_iPiA2x-DDruDu7E.js.map +0 -1
  146. package/dist/assets/MarkdownRenderer-U_iPiA2x-VCa5mXh1.js +0 -1
  147. package/dist/assets/NewCourseDialog-CLm1rQyB.js +0 -2
  148. package/dist/assets/RequestPasswordReset-DPE6S2dU.js +0 -2
  149. package/dist/assets/ResetPassword-Dl6nj4jF.js +0 -2
  150. package/dist/assets/Study-Cf5yVLaY.js +0 -2
  151. package/dist/assets/TagInformation-tqHJGkyw.js +0 -2
  152. package/dist/assets/User-DCoA5JMB.js +0 -3
  153. package/dist/assets/User-DCoA5JMB.js.map +0 -1
  154. package/dist/assets/UserStats-B25DZy-D.js +0 -2
  155. package/dist/assets/VerifyEmail-DyWRQweA.js +0 -2
  156. package/dist/assets/admin-DCvFP6sY.js +0 -4
  157. package/dist/assets/admin-DCvFP6sY.js.map +0 -1
  158. package/dist/assets/chess-E2uOAyQS-CP3XwSpG.js +0 -7
  159. package/dist/assets/chess-Lfm7Fsvs-RoJ69a0B.js +0 -1
  160. package/dist/assets/common-ui.es-DHzI_ZVr.js +0 -1
  161. package/dist/assets/common-ui.es-te1li8kU.js +0 -38
  162. package/dist/assets/common-ui.es-te1li8kU.js.map +0 -1
  163. package/dist/assets/dist-BnMJdH50.js +0 -380
  164. package/dist/assets/dist-BnMJdH50.js.map +0 -1
  165. package/dist/assets/dist-CtnPlm6M.js +0 -18
  166. package/dist/assets/dist-CtnPlm6M.js.map +0 -1
  167. package/dist/assets/dist-D4MdLcof.js +0 -1
  168. package/dist/assets/dist-Db-U8O3Z.js +0 -1
  169. package/dist/assets/dist-V9Xbab2f.js +0 -12
  170. package/dist/assets/dist-V9Xbab2f.js.map +0 -1
  171. package/dist/assets/edit-ui.es-C7TI7NmB.js +0 -36
  172. package/dist/assets/edit-ui.es-C7TI7NmB.js.map +0 -1
  173. package/dist/assets/edit-ui.es-CiY2oEH8.js +0 -1
  174. package/dist/assets/french-Dk7YG8Td-Bfl4cirn.js +0 -2
  175. package/dist/assets/french-evUMlbbq-DuW1vCaS.js +0 -1
  176. package/dist/assets/index-JRi1udkz.js +0 -4
  177. package/dist/assets/math-DR3fXDcX-BFIht0j2.js +0 -1
  178. package/dist/assets/math-D_8HiEQR-B9oNpF-3.js +0 -34
  179. package/dist/assets/piano-BN5Btq91-Jqe2eqme.js +0 -1
  180. package/dist/assets/piano-DF1g6yaX-CjD06Qz8.js +0 -2
  181. package/dist/assets/pitch-CgGJFkZ1-C-2hdk99.js +0 -2
  182. package/dist/assets/pitch-Dn0iNqiS-DpEcsscT.js +0 -1
  183. package/dist/assets/server-D4lhkoe2.js +0 -2
  184. package/dist/assets/server-D4lhkoe2.js.map +0 -1
  185. package/dist/assets/sightsing-CJX3k0Fd-CA3ntnlE.js +0 -1
  186. package/dist/assets/typing-BevtfWlp-BT263ZFw.js +0 -2
  187. package/dist/assets/typing-k-ojjO7G-Bq4IfdFx.js +0 -1
  188. package/dist/assets/word-work-BOnRlZgd-BFwc1KBd.js +0 -2
  189. package/dist/assets/word-work-Dd6tIKrt-tFtMeyu1.js +0 -1
  190. /package/dist/assets/{common-ui-BY2Ut5jf.css → dist-BY2Ut5jf.css} +0 -0
@@ -0,0 +1,34 @@
1
+ import{i as e,s as t,t as n}from"./chunk-D6hFPZc3.js";import{t as r}from"./moment-DbT30ZpG.js";import{t as i}from"./defineProperty-y9rbOPYz.js";import{i as a,s as o,t as s}from"./elo-B5qCwvSC.js";import{A as c,O as l,b as u,f as d,k as p,l as m,m as h,n as g,s as _,t as v,u as y,y as b}from"./PipelineDebugger-BHaqzqZw.js";import{a as x,c as S,d as C,h as w,i as T,l as E,n as ee,o as D,p as te,r as ne,s as O,t as re}from"./userDBKeys-DYLGKnVC.js";import{c as ie,d as ae,i as oe,l as se,n as ce,r as le,s as ue,t as de}from"./srs-DOsG9Y-i.js";import{t as fe}from"./elo-COgu6Hu5.js";import{n as pe,t as me}from"./eloDistance-BV7vfiK5.js";var k;(function(e){e.awaitingResponse=`awaiting`,e.ok=`ok`,e.warning=`warning`,e.error=`error`})(k||(k={}));var he;(function(e){e.CREATE_CLASSROOM=`CREATE_CLASSROOM`,e.DELETE_CLASSROOM=`DELETE_CLASSROOM`,e.JOIN_CLASSROOM=`JOIN_CLASSROOM`,e.LEAVE_CLASSROOM=`LEAVE_CLASSROOM`,e.CREATE_COURSE=`CREATE_COURSE`,e.DELETE_COURSE=`DELETE_COURSE`,e.ADD_COURSE_DATA=`ADD_COURSE_DATA`,e.PACK_COURSE=`PACK_COURSE`})(he||(he={}));var ge;(function(e){e.DISPLAYABLE_DATA=`DISPLAYABLE_DATA`,e.CARD=`CARD`,e.DATASHAPE=`DATASHAPE`,e.QUESTIONTYPE=`QUESTION`,e.VIEW=`VIEW`,e.PEDAGOGY=`PEDAGOGY`,e.CARDRECORD=`CARDRECORD`,e.SCHEDULED_CARD=`SCHEDULED_CARD`,e.TAG=`TAG`})(ge||(ge={}));var NameSpacer=class{static getDataShapeDescriptor(e){let t=e.split(`.`);if(t.length!==3)throw Error(`shapeStr [${e}] not valid`);return{course:t[0],dataShape:t[2]}}static getDataShapeString(e){return`${e.course}.datashape.${e.dataShape}`}static getViewDescriptor(e){let t=e.split(`.`);if(t.length!==4)throw Error(`viewStr not valid`);return{course:t[0],questionType:t[2],view:t[3]}}static getViewString(e){return`${e.course}.question.${e.questionType}.${e.view}`}static getQuestionDescriptor(e){let t=e.split(`.`);if(t.length!==3)throw Error(`questionStr not valid`);return{course:t[0],questionType:t[2]}}static getQuestionString(e){return`${e.course}.question.${e.questionType}`}},A;(function(e){e.STRING=`string`,e.NUMBER=`number`,e.INT=`int`,e.IMAGE=`image`,e.MARKDOWN=`markdown`,e.AUDIO=`audio`,e.MIDI=`midi`,e.MEDIA_UPLOADS=`uploads`,e.CHESS_PUZZLE=`chess_puzzle`})(A||(A={}));function prepareNote55(e,t,n,r,i,a,o){let s=NameSpacer.getDataShapeString({course:t,dataShape:n.name}),c=n.fields.map(e=>({name:e.name,type:e.type})).filter(e=>e.type===A.IMAGE||e.type===A.AUDIO).concat([{name:`autoplayAudio`,type:A.AUDIO}]);for(let e=1;e<11;e++)r[`audio-${e}`]&&c.push({name:`audio-${e}`,type:A.AUDIO}),r[`image-${e}`]&&c.push({name:`image-${e}`,type:A.IMAGE});if(r[`audio-11`])throw Error(`Too many audio attachments`);if(r[`image-11`])throw Error(`Too many image attachments`);let l={},u={course:e,data:[],docType:ge.DISPLAYABLE_DATA,id_datashape:s};return i&&(u.author=i),c.forEach(e=>{l[e.name]=r[e.name]}),o&&Object.keys(o).forEach(e=>{l[e]=o[e]}),(c.length!==0||o&&Object.keys(o).length)&&(u._attachments=l),n.fields.filter(e=>e.type!==A.IMAGE&&e.type!==A.AUDIO).forEach(e=>{u.data.push({name:e.name,data:r[e.name]})}),u}function isTaggedPerformance(e){return typeof e==`object`&&!!e&&`_global`in e}var _e=n(((e,t)=>{t.exports={}}));function emptyTagFilter(){return{include:[],exclude:[]}}function hasActiveFilter(e){return e?e.include.length>0||e.exclude.length>0:!1}var ve=n(((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],i=e[2],a=e[3];n+=(r&i|~r&a)+t[0]-680876936|0,n=(n<<7|n>>>25)+r|0,a+=(n&r|~n&i)+t[1]-389564586|0,a=(a<<12|a>>>20)+n|0,i+=(a&n|~a&r)+t[2]+606105819|0,i=(i<<17|i>>>15)+a|0,r+=(i&a|~i&n)+t[3]-1044525330|0,r=(r<<22|r>>>10)+i|0,n+=(r&i|~r&a)+t[4]-176418897|0,n=(n<<7|n>>>25)+r|0,a+=(n&r|~n&i)+t[5]+1200080426|0,a=(a<<12|a>>>20)+n|0,i+=(a&n|~a&r)+t[6]-1473231341|0,i=(i<<17|i>>>15)+a|0,r+=(i&a|~i&n)+t[7]-45705983|0,r=(r<<22|r>>>10)+i|0,n+=(r&i|~r&a)+t[8]+1770035416|0,n=(n<<7|n>>>25)+r|0,a+=(n&r|~n&i)+t[9]-1958414417|0,a=(a<<12|a>>>20)+n|0,i+=(a&n|~a&r)+t[10]-42063|0,i=(i<<17|i>>>15)+a|0,r+=(i&a|~i&n)+t[11]-1990404162|0,r=(r<<22|r>>>10)+i|0,n+=(r&i|~r&a)+t[12]+1804603682|0,n=(n<<7|n>>>25)+r|0,a+=(n&r|~n&i)+t[13]-40341101|0,a=(a<<12|a>>>20)+n|0,i+=(a&n|~a&r)+t[14]-1502002290|0,i=(i<<17|i>>>15)+a|0,r+=(i&a|~i&n)+t[15]+1236535329|0,r=(r<<22|r>>>10)+i|0,n+=(r&a|i&~a)+t[1]-165796510|0,n=(n<<5|n>>>27)+r|0,a+=(n&i|r&~i)+t[6]-1069501632|0,a=(a<<9|a>>>23)+n|0,i+=(a&r|n&~r)+t[11]+643717713|0,i=(i<<14|i>>>18)+a|0,r+=(i&n|a&~n)+t[0]-373897302|0,r=(r<<20|r>>>12)+i|0,n+=(r&a|i&~a)+t[5]-701558691|0,n=(n<<5|n>>>27)+r|0,a+=(n&i|r&~i)+t[10]+38016083|0,a=(a<<9|a>>>23)+n|0,i+=(a&r|n&~r)+t[15]-660478335|0,i=(i<<14|i>>>18)+a|0,r+=(i&n|a&~n)+t[4]-405537848|0,r=(r<<20|r>>>12)+i|0,n+=(r&a|i&~a)+t[9]+568446438|0,n=(n<<5|n>>>27)+r|0,a+=(n&i|r&~i)+t[14]-1019803690|0,a=(a<<9|a>>>23)+n|0,i+=(a&r|n&~r)+t[3]-187363961|0,i=(i<<14|i>>>18)+a|0,r+=(i&n|a&~n)+t[8]+1163531501|0,r=(r<<20|r>>>12)+i|0,n+=(r&a|i&~a)+t[13]-1444681467|0,n=(n<<5|n>>>27)+r|0,a+=(n&i|r&~i)+t[2]-51403784|0,a=(a<<9|a>>>23)+n|0,i+=(a&r|n&~r)+t[7]+1735328473|0,i=(i<<14|i>>>18)+a|0,r+=(i&n|a&~n)+t[12]-1926607734|0,r=(r<<20|r>>>12)+i|0,n+=(r^i^a)+t[5]-378558|0,n=(n<<4|n>>>28)+r|0,a+=(n^r^i)+t[8]-2022574463|0,a=(a<<11|a>>>21)+n|0,i+=(a^n^r)+t[11]+1839030562|0,i=(i<<16|i>>>16)+a|0,r+=(i^a^n)+t[14]-35309556|0,r=(r<<23|r>>>9)+i|0,n+=(r^i^a)+t[1]-1530992060|0,n=(n<<4|n>>>28)+r|0,a+=(n^r^i)+t[4]+1272893353|0,a=(a<<11|a>>>21)+n|0,i+=(a^n^r)+t[7]-155497632|0,i=(i<<16|i>>>16)+a|0,r+=(i^a^n)+t[10]-1094730640|0,r=(r<<23|r>>>9)+i|0,n+=(r^i^a)+t[13]+681279174|0,n=(n<<4|n>>>28)+r|0,a+=(n^r^i)+t[0]-358537222|0,a=(a<<11|a>>>21)+n|0,i+=(a^n^r)+t[3]-722521979|0,i=(i<<16|i>>>16)+a|0,r+=(i^a^n)+t[6]+76029189|0,r=(r<<23|r>>>9)+i|0,n+=(r^i^a)+t[9]-640364487|0,n=(n<<4|n>>>28)+r|0,a+=(n^r^i)+t[12]-421815835|0,a=(a<<11|a>>>21)+n|0,i+=(a^n^r)+t[15]+530742520|0,i=(i<<16|i>>>16)+a|0,r+=(i^a^n)+t[2]-995338651|0,r=(r<<23|r>>>9)+i|0,n+=(i^(r|~a))+t[0]-198630844|0,n=(n<<6|n>>>26)+r|0,a+=(r^(n|~i))+t[7]+1126891415|0,a=(a<<10|a>>>22)+n|0,i+=(n^(a|~r))+t[14]-1416354905|0,i=(i<<15|i>>>17)+a|0,r+=(a^(i|~n))+t[5]-57434055|0,r=(r<<21|r>>>11)+i|0,n+=(i^(r|~a))+t[12]+1700485571|0,n=(n<<6|n>>>26)+r|0,a+=(r^(n|~i))+t[3]-1894986606|0,a=(a<<10|a>>>22)+n|0,i+=(n^(a|~r))+t[10]-1051523|0,i=(i<<15|i>>>17)+a|0,r+=(a^(i|~n))+t[1]-2054922799|0,r=(r<<21|r>>>11)+i|0,n+=(i^(r|~a))+t[8]+1873313359|0,n=(n<<6|n>>>26)+r|0,a+=(r^(n|~i))+t[15]-30611744|0,a=(a<<10|a>>>22)+n|0,i+=(n^(a|~r))+t[6]-1560198380|0,i=(i<<15|i>>>17)+a|0,r+=(a^(i|~n))+t[13]+1309151649|0,r=(r<<21|r>>>11)+i|0,n+=(i^(r|~a))+t[4]-145523070|0,n=(n<<6|n>>>26)+r|0,a+=(r^(n|~i))+t[11]-1120210379|0,a=(a<<10|a>>>22)+n|0,i+=(n^(a|~r))+t[2]+718787259|0,i=(i<<15|i>>>17)+a|0,r+=(a^(i|~n))+t[9]-343485551|0,r=(r<<21|r>>>11)+i|0,e[0]=n+e[0]|0,e[1]=r+e[1]|0,e[2]=i+e[2]|0,e[3]=a+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,i,a,o,s,c;for(r=64;r<=t;r+=64)md5cycle(n,md5blk(e.substring(r-64,r)));for(e=e.substring(r-64),i=e.length,a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],r=0;r<i;r+=1)a[r>>2]|=e.charCodeAt(r)<<(r%4<<3);if(a[r>>2]|=128<<(r%4<<3),r>55)for(md5cycle(n,a),r=0;r<16;r+=1)a[r]=0;return o=t*8,o=o.toString(16).match(/(.*?)(.{0,8})$/),s=parseInt(o[2],16),c=parseInt(o[1],16)||0,a[14]=s,a[15]=c,md5cycle(n,a),n}function md51_array(e){var t=e.length,n=[1732584193,-271733879,-1732584194,271733878],r,i,a,o,s,c;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,i=e.length,a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],r=0;r<i;r+=1)a[r>>2]|=e[r]<<(r%4<<3);if(a[r>>2]|=128<<(r%4<<3),r>55)for(md5cycle(n,a),r=0;r<16;r+=1)a[r]=0;return o=t*8,o=o.toString(16).match(/(.*?)(.{0,8})$/),s=parseInt(o[2],16),c=parseInt(o[1],16)||0,a[14]=s,a[15]=c,md5cycle(n,a),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,i=clamp(t,r),a=r,o,s,c,l;return n!==e&&(a=clamp(n,r)),i>a?new ArrayBuffer(0):(o=a-i,s=new ArrayBuffer(o),c=new Uint8Array(s),l=new Uint8Array(this,i,o),c.set(l),s)}})();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),i=new Uint8Array(r),a;for(a=0;a<n;a+=1)i[a]=e.charCodeAt(a);return t?i: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,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],a;for(r=0;r<n;r+=1)i[r>>2]|=t.charCodeAt(r)<<(r%4<<3);return this._finish(i,n),a=hex(this._hash),e&&(a=hexToBinaryString(a)),this.reset(),a},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,i,a;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})$/),i=parseInt(r[2],16),a=parseInt(r[1],16)||0,e[14]=i,e[15]=a,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],i,a;for(i=0;i<n;i+=1)r[i>>2]|=t[i]<<(i%4<<3);return this._finish(r,n),a=hex(this._hash),e&&(a=hexToBinaryString(a)),this.reset(),a},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})})),ye,be=new Uint8Array(16);function rng$1(){if(!ye&&(ye=typeof crypto<`u`&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<`u`&&typeof msCrypto.getRandomValues==`function`&&msCrypto.getRandomValues.bind(msCrypto),!ye))throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);return ye(be)}e(rng$1,`rng`);var xe=/^(?:[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`&&xe.test(e)}e(validate$1,`validate`);for(var j=[],Se=0;Se<256;++Se)j.push((Se+256).toString(16).substr(1));function stringify$2(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=(j[e[t+0]]+j[e[t+1]]+j[e[t+2]]+j[e[t+3]]+`-`+j[e[t+4]]+j[e[t+5]]+`-`+j[e[t+6]]+j[e[t+7]]+`-`+j[e[t+8]]+j[e[t+9]]+`-`+j[e[t+10]]+j[e[t+11]]+j[e[t+12]]+j[e[t+13]]+j[e[t+14]]+j[e[t+15]]).toLowerCase();if(!validate$1(n))throw TypeError(`Stringified UUID is invalid`);return n}e(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 i=0;i<16;++i)t[n+i]=r[i];return t}return stringify$2(r)}e(v4$1,`v4`);var Ce=n((e=>{e.stringify=function stringify(e){var t=[];t.push({obj:e});for(var n=``,r,i,a,o,s,c,l,u,d,p,m;r=t.pop();)if(i=r.obj,a=r.prefix||``,o=r.val||``,n+=a,o)n+=o;else if(typeof i!=`object`)n+=i===void 0?null:JSON.stringify(i);else if(i===null)n+=`null`;else if(Array.isArray(i)){for(t.push({val:`]`}),s=i.length-1;s>=0;s--)c=s===0?``:`,`,t.push({obj:i[s],prefix:c});t.push({val:`[`})}else{for(u in l=[],i)i.hasOwnProperty(u)&&l.push(u);for(t.push({val:`}`}),s=l.length-1;s>=0;s--)d=l[s],p=i[d],m=s>0?`,`:``,m+=JSON.stringify(d)+`:`,t.push({obj:p,prefix:m});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 i=r.element,a=r.index;if(Array.isArray(i))i.push(e);else if(a===t.length-2){var o=t.pop();i[o]=e}else t.push(e)}e.parse=function(e){for(var t=[],n=[],r=0,i,a,o,s,c,l,u,d,p;;){if(i=e[r++],i===`}`||i===`]`||i===void 0){if(t.length===1)return t.pop();pop(t.pop(),t,n);continue}switch(i){case` `:case` `:case`
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(a=``,r--;;)if(o=e[r++],/[\d\.\-e\+]/.test(o))a+=o;else{r--;break}pop(parseFloat(a),t,n);break;case`"`:for(s=``,c=void 0,l=0;u=e[r++],u!==`"`||c===`\\`&&l%2==1;)s+=u,c=u,c===`\\`?l++:l=0;pop(JSON.parse(`"`+s+`"`),t,n);break;case`[`:d={element:[],index:t.length},t.push(d.element),n.push(d);break;case`{`:p={element:{},index:t.length},t.push(p.element),n.push(p);break;default:throw Error(`unexpectedly reached end of input: `+i)}}}})),we=n(((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)},i=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 a=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 o=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 o},set:function(e){if(typeof e!=`number`||e<0||a(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);o=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||a(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 i=e===`error`,a=this._events;if(a!==void 0)i=i&&a.error===void 0;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)r(c,this,t);else for(var l=c.length,u=arrayClone(c,l),n=0;n<l;++n)r(u[n],this,t);return!0};function _addListener(e,t,n,r){var i,a,o;if(checkListener(n),a=e._events,a===void 0?(a=e._events=Object.create(null),e._eventsCount=0):(a.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),a=e._events),o=a[t]),o===void 0)o=a[t]=n,++e._eventsCount;else if(typeof o==`function`?o=a[t]=r?[n,o]:[o,n]:r?o.unshift(n):o.push(n),i=_getMaxListeners(e),i>0&&o.length>i&&!o.warned){o.warned=!0;var s=Error(`Possible EventEmitter memory leak detected. `+o.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);s.name=`MaxListenersExceededWarning`,s.emitter=e,s.type=t,s.count=o.length,ProcessEmitWarning(s)}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},i=onceWrapper.bind(r);return i.listener=n,r.wrapFn=i,i}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,i,a,o;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(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():spliceOne(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||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 i=Object.keys(n),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);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 i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?unwrapListeners(i):arrayClone(i,i.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?i(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(i){r.once&&e.removeEventListener(t,wrapListener),n(i)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}})),Te=t(ve()),Ee=t(Ce()),M=t(we());function isBinaryObject$1(e){return typeof ArrayBuffer<`u`&&e instanceof ArrayBuffer||typeof Blob<`u`&&e instanceof Blob}e(isBinaryObject$1,`isBinaryObject`);function cloneBinaryObject$1(e){return e instanceof ArrayBuffer?e.slice(0):e.slice(0,e.size,e.type)}e(cloneBinaryObject$1,`cloneBinaryObject`);var De=Function.prototype.toString,Oe=De.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&&De.call(n)==Oe}e(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 i=clone$1(e[n]);i!==void 0&&(t[n]=i)}return t}e(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,i=new Promise(function(r,i){var a;try{var o=once(function(e,t){e?i(e):r(t)});t.push(o),a=e.apply(n,t),a&&typeof a.then==`function`&&r(a)}catch(e){i(e)}});return r&&i.then(function(e){r(null,e)},r),i}}function logApiCall(e,t,n){if(e.constructor.listeners(`debug`).length){for(var r=[`api`,e.name,t],i=0;i<n.length-1;i++)r.push(n[i]);e.constructor.emit(`debug`,r);var a=n[n.length-1];n[n.length-1]=function(n,r){var i=[`api`,e.name,t];i=i.concat(n?[`error`,n]:[`success`,r]),e.constructor.emit(`debug`,i),a(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,i){r.taskqueue.addTask(function(a){a?i(a):t(r[e].apply(r,n))})})})}function pick$1(e,t){for(var n={},r=0,i=t.length;r<i;r++){var a=t[r];a in e&&(n[a]=e[a])}return n}e(pick$1,`pick`);var ke=6;function identityFunction(e){return e}function formatResultForOpenRevsGet(e){return[{ok:e}]}function bulkGet(e,t,n){var r=t.docs,i=new Map;r.forEach(function(e){i.has(e.id)?i.get(e.id).push(e):i.set(e.id,[e])});var a=i.size,o=0,s=Array(a);function collapseResultsAndFinish(){var e=[];s.forEach(function(t){t.docs.forEach(function(n){e.push({id:t.id,docs:[n]})})}),n(null,{results:e})}function checkDone(){++o===a&&collapseResultsAndFinish()}function gotResult(e,t,n){s[e]={id:t,docs:n},checkDone()}var c=[];i.forEach(function(e,t){c.push(t)});var l=0;function nextBatch(){if(!(l>=c.length)){var e=Math.min(l+ke,c.length),t=c.slice(l,e);processBatch(t,l),l+=t.length}}function processBatch(n,r){n.forEach(function(n,a){var o=r+a,s=i.get(n),c=pick$1(s[0],[`atts_since`,`attachments`]);c.open_revs=s.map(function(e){return e.rev}),c.open_revs=c.open_revs.filter(identityFunction);var l=identityFunction;c.open_revs.length===0&&(delete c.open_revs,l=formatResultForOpenRevsGet),[`revs`,`attachments`,`binary`,`ajax`,`latest`].forEach(function(e){e in t&&(c[e]=t[e])}),e.get(n,c,function(e,t){gotResult(o,n,e?[{error:e}]:l(t)),nextBatch()})})}nextBatch()}var Ae;try{localStorage.setItem(`_pouch_check_localstorage`,1),Ae=!!localStorage.getItem(`_pouch_check_localstorage`)}catch{Ae=!1}function hasLocalStorage(){return Ae}var N=typeof queueMicrotask==`function`?queueMicrotask:function nextTick(e){Promise.resolve().then(e)},Changes=class extends M.default{constructor(){super(),this._listeners={},hasLocalStorage()&&addEventListener(`storage`,e=>{this.emit(e.key)})}addListener(e,t,n,r){if(this._listeners[t])return;var i=!1,a=this;function eventFunction(){if(!a._listeners[t])return;if(i){i=`waiting`;return}i=!0;var e=pick$1(r,[`style`,`include_docs`,`attachments`,`conflicts`,`filter`,`doc_ids`,`view`,`since`,`query_params`,`binary`,`return_docs`]);function onError(){i=!1}n.changes(e).on(`change`,function(e){e.seq>r.since&&!r.cancelled&&(r.since=e.seq,r.onChange(e))}).on(`complete`,function(){i===`waiting`&&N(eventFunction),i=!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)}}e(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{e(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 je=new PouchError$1(400,`bad_request`,`Missing JSON list of 'docs'`),P=new PouchError$1(404,`not_found`,`missing`),Me=new PouchError$1(409,`conflict`,`Document update conflict`),Ne=new PouchError$1(400,`bad_request`,`_id field must contain a string`),Pe=new PouchError$1(412,`missing_id`,`_id is required for puts`),Fe=new PouchError$1(400,`bad_request`,`Only reserved document ids may start with underscore.`);new PouchError$1(412,`precondition_failed`,`Database not open`);var Ie=new PouchError$1(500,`unknown_error`,`Database encountered an unknown error`),Le=new PouchError$1(500,`badarg`,`Some query argument is invalid`);new PouchError$1(400,`invalid_request`,`Request was invalid`);var Re=new PouchError$1(400,`query_parse_error`,`Some query parameter is invalid`),ze=new PouchError$1(500,`doc_validation`,`Bad special document member`),Be=new PouchError$1(400,`bad_request`,`Something wrong with the request`),Ve=new PouchError$1(400,`bad_request`,`Document must be a JSON object`);new PouchError$1(404,`not_found`,`Database not found`);var He=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 Ue=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 We=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,i=n.length;r<i;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)}e(createError$1,`createError`);function generateErrorFromResponse$1(e){if(typeof e!=`object`){var t=e;e=Ie,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}e(generateErrorFromResponse$1,`generateErrorFromResponse`);function tryFilter(e,t,n){try{return!e(t,n)}catch(e){return createError$1(Be,`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 i=n&&tryFilter(e.filter,r.doc,t);if(typeof i==`object`)return i;if(i)return!1;if(!e.include_docs)delete r.doc;else if(!e.attachments)for(var a in r.doc._attachments)Object.prototype.hasOwnProperty.call(r.doc._attachments,a)&&(r.doc._attachments[a].stub=!0);return!0}}function invalidIdError(e){var t;if(e?typeof e==`string`?/^_/.test(e)&&!/^_(design|local)/.test(e)&&(t=createError$1(Fe)):t=createError$1(Ne):t=createError$1(Pe),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}e(isRemote$1,`isRemote`);function listenerCount(e,t){return`listenerCount`in e?e.listenerCount(t):M.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 Ge=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`],Ke=`queryKey`,qe=/(?:^|&)([^&=]*)=?([^&]*)/g,Je=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;function parseUri(e){for(var t=Je.exec(e),n={},r=14;r--;){var i=Ge[r],a=t[r]||``;n[i]=[`user`,`password`].indexOf(i)===-1?a:decodeURIComponent(a)}return n[Ke]={},n[Ge[12]].replace(qe,function(e,t,r){t&&(n[Ke][t]=r)}),n}function scopeEval(e,t){var n=[],r=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n.push(i),r.push(t[i]));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 i=r._rev,a=n(r);return a?(a._id=t,a._rev=i,tryAndPut$1(e,a,n)):{updated:!1,rev:i}})}e(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)})}e(tryAndPut$1,`tryAndPut`);var Ye=e(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(i){if(i.name!==`TypeError`)throw i;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)}}e(createBlob$1,`createBlob`);function binaryStringToArrayBuffer$1(e){for(var t=e.length,n=new ArrayBuffer(t),r=new Uint8Array(n),i=0;i<t;i++)r[i]=e.charCodeAt(i);return n}e(binaryStringToArrayBuffer$1,`binaryStringToArrayBuffer`);function binStringToBluffer$1(e,t){return createBlob$1([binaryStringToArrayBuffer$1(e)],{type:t})}e(binStringToBluffer$1,`binStringToBluffer`);function b64ToBluffer$1(e,t){return binStringToBluffer$1(Ye(e),t)}e(b64ToBluffer$1,`b64ToBluffer`);function arrayBufferToBinaryString(e){for(var t=``,n=new Uint8Array(e),r=n.byteLength,i=0;i<r;i++)t+=String.fromCharCode(n[i]);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 Xe=self.setImmediate||self.setTimeout,Ze=32768;function rawToBase64(e){return thisBtoa(e)}function appendBlob(e,t,n,r,i){(n>0||r<t.size)&&(t=t.slice(n,r)),readAsArrayBuffer(t,function(t){e.append(t),i()})}function appendString(e,t,n,r,i){(n>0||r<t.length)&&(t=t.substring(n,r)),e.appendBinary(t),i()}function binaryMd5(e,t){var n=typeof e==`string`,r=n?e.length:e.size,i=Math.min(Ze,r),a=Math.ceil(r/i),o=0,s=n?new Te.default:new Te.default.ArrayBuffer,c=n?appendString:appendBlob;function next(){Xe(loadNextChunk)}function done(){t(rawToBase64(s.end(!0))),s.destroy()}function loadNextChunk(){var t=o*i,n=t+i;o++,o<a?c(s,e,t,n,next):c(s,e,t,n,done)}loadNextChunk()}function stringMd5$1(e){return Te.default.hash(e)}e(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 Qe=v4$1;function winningRev(e){for(var t,n,r,i=e.rev_tree.slice(),a;a=i.pop();){var o=a.ids,s=o[2],c=a.pos;if(s.length){for(var l=0,u=s.length;l<u;l++)i.push({pos:c+1,ids:s[l]});continue}var d=!!o[1].deleted,p=o[0];(!t||(r===d?n===c?t<p:n<c:r))&&(t=p,n=c,r=d)}return n+`-`+t}function traverseRevTree(e,t){for(var n=e.slice(),r;r=n.pop();)for(var i=r.pos,a=r.ids,o=a[2],s=t(o.length===0,i,a[0],r.ctx,a[1]),c=0,l=o.length;c<l;c++)n.push({pos:i+1,ids:o[c],ctx:s})}function sortByPos(e,t){return e.pos-t.pos}function collectLeaves(e){var t=[];traverseRevTree(e,function(e,n,r,i,a){e&&t.push({rev:n+`-`+r,pos:n,opts:a})}),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=[],i=0,a=n.length;i<a;i++){var o=n[i];o.rev!==t&&!o.opts.deleted&&r.push(o.rev)}return r}function compactTree(e){var t=[];return traverseRevTree(e.rev_tree,function(e,n,r,i,a){a.status===`available`&&!e&&(t.push(n+`-`+r),a.status=`missing`)}),t}function findPathToLeaf(e,t){let n=[],r=e.slice(),i;for(;i=r.pop();){let{pos:e,ids:a}=i,o=`${e}-${a[0]}`,s=a[2];if(n.push(o),o===t){if(s.length!==0)throw Error(`The requested revision is not a leaf`);return n.reverse()}(s.length===0||s.length>1)&&(n=[]);for(let t=0,n=s.length;t<n;t++)r.push({pos:e+1,ids:s[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 i=r.pos,a=r.ids,o=a[0],s=a[1],c=a[2],l=c.length===0,u=r.history?r.history.slice():[];u.push({id:o,opts:s}),l&&t.push({pos:i+1-u.length,ids:u});for(var d=0,p=c.length;d<p;d++)n.push({pos:i+1,ids:c[d],history:u})}return t.reverse()}function sortByPos$1(e,t){return e.pos-t.pos}function binarySearch(e,t,n){for(var r=0,i=e.length,a;r<i;)a=r+i>>>1,n(e[a],t)<0?r=a+1:i=a;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,i=t,a=e.length;i<a;i++){var o=e[i],s=[o.id,o.opts,[]];r?(r[2].push(s),r=s):n=r=s}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 i=n.pop(),a=i.tree1,o=i.tree2;(a[1].status||o[1].status)&&(a[1].status=a[1].status===`available`||o[1].status===`available`?`available`:`missing`);for(var s=0;s<o[2].length;s++){if(!a[2][0]){r=`new_leaf`,a[2][0]=o[2][s];continue}for(var c=!1,l=0;l<a[2].length;l++)a[2][l][0]===o[2][s][0]&&(n.push({tree1:a[2][l],tree2:o[2][s]}),c=!0);c||(r=`new_branch`,insertSorted(a[2],o[2][s],compareTree))}}return{conflicts:r,tree:e}}function doMerge(e,t,n){var r=[],i=!1,a=!1,o;if(!e.length)return{tree:[t],conflicts:`new_leaf`};for(var s=0,c=e.length;s<c;s++){var l=e[s];if(l.pos===t.pos&&l.ids[0]===t.ids[0])o=mergeTree(l.ids,t.ids),r.push({pos:l.pos,ids:o.tree}),i=i||o.conflicts,a=!0;else if(n!==!0){var u=l.pos<t.pos?l:t,d=l.pos<t.pos?t:l,p=d.pos-u.pos,m=[],h=[];for(h.push({ids:u.ids,diff:p,parent:null,parentIdx:null});h.length>0;){var g=h.pop();if(g.diff===0){g.ids[0]===d.ids[0]&&m.push(g);continue}for(var _=g.ids[2],v=0,y=_.length;v<y;v++)h.push({ids:_[v],diff:g.diff-1,parent:g.ids,parentIdx:v})}var b=m[0];b?(o=mergeTree(b.ids,d.ids),b.parent[2][b.parentIdx]=o.tree,r.push({pos:u.pos,ids:u.ids}),i=i||o.conflicts,a=!0):r.push(l)}else r.push(l)}return a||r.push(t),r.sort(sortByPos$1),{tree:r,conflicts:i||`internal_node`}}function stem(e,t){for(var n=rootToLeaf(e),r,i,a=0,o=n.length;a<o;a++){var s=n[a],c=s.ids,l;if(c.length>t){r||(r={});var u=c.length-t;l={pos:s.pos+u,ids:pathToTree(c,u)};for(var d=0;d<u;d++){var p=s.pos+d+`-`+c[d].id;r[p]=!0}}else l={pos:s.pos,ids:pathToTree(c,0)};i=i?doMerge(i,l,!0).tree:[l]}return r&&traverseRevTree(i,function(e,t,n){delete r[t+`-`+n]}),{tree:i,revs:r?Object.keys(r):[]}}function merge(e,t,n){var r=doMerge(e,t),i=stem(r.tree,n);return{tree:i.tree,stemmedRevs:i.revs,conflicts:r.conflicts}}function revExists(e,t){for(var n=e.slice(),r=t.split(`-`),i=parseInt(r[0],10),a=r[1],o;o=n.pop();){if(o.pos===i&&o.ids[0]===a)return!0;for(var s=o.ids[2],c=0,l=s.length;c<l;c++)n.push({pos:o.pos+1,ids:s[c]})}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),i;i=r.pop();){if(i[0]===n)return!!i[1].deleted;r=r.concat(i[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 i=r.pos,a=r.ids,o=a[0],s=a[1],c=a[2],l=c.length===0,u=r.history?r.history.slice():[];if(u.push({id:o,pos:i,opts:s}),l)for(var d=0,p=u.length;d<p;d++){var m=u[d];if(m.pos+`-`+m.id===e)return i+`-`+o}for(var h=0,g=c.length;h<g;h++)n.push({pos:i+1,ids:c[h],history:u})}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 i={id:t.id,changes:r,doc:e};return isDeleted(t,e._rev)&&(i.deleted=!0),n.conflicts&&(i.doc._conflicts=collectConflicts(t),i.doc._conflicts.length||delete i.doc._conflicts),i}var Changes$1=class extends M.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 i=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=i.then.bind(i),this.catch=i.catch.bind(i),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;I._changesFilterPlugin?I._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(I._changesFilterPlugin){if(I._changesFilterPlugin.normalize(e),I._changesFilterPlugin.shouldFilter(this,e))return I._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),i=0;i<r.length;i++){var a=r[i];n._attachments[a]=pick$1(n._attachments[a],[`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,i,a){var o=r+`-`+i;return e&&(t[o]=0),a!==void 0&&n.push({from:a,to:o}),o}),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),N(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 $e=/^\d+-[^-]*$/;function isValidRev(e){return typeof e==`string`&&$e.test(e)}var AbstractPouchDB=class extends M.default{_setup(){this.post=adapterFun(`post`,function(e,t,n){if(typeof t==`function`&&(n=t,t={}),isNotSingleDoc(e))return n(createError$1(Ve));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(Ve));if(invalidIdError(e._id),`_rev`in e&&!isValidRev(e._rev))return n(createError$1(Ue));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],i=parseInt(n[0],10)+1,a=rev();e._revisions={start:i,ids:[a,r]},e._rev=i+`-`+a,t.new_edits=!1}}).bind(this),this.putAttachment=adapterFun(`putAttachment`,function(e,t,n,r,i){var a=this;typeof i==`function`&&(i=r,r=n,n=null),i===void 0&&(i=r,r=n,n=null),i||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:i,data:r,revpos:++n},a.put(e)}return a.get(e).then(function(e){if(e._rev!==n)throw createError$1(Me);return createAttachment(e)},function(t){if(t.reason===P.message)return createAttachment({_id:e});throw t})}).bind(this),this.removeAttachment=adapterFun(`removeAttachment`,function(e,t,n,r){this.get(e,(e,i)=>{if(e){r(e);return}if(i._rev!==n){r(createError$1(Me));return}if(!i._attachments)return r();delete i._attachments[t],Object.keys(i._attachments).length===0&&delete i._attachments,this.put(i,r)})}).bind(this),this.remove=adapterFun(`remove`,function(e,t,n,r){var i;typeof t==`string`?(i={_id:e,_rev:t},typeof n==`function`&&(r=n,n={})):(i=e,typeof t==`function`?(r=t,n={}):(r=n,n=t)),n=n||{},n.was_delete=!0;var a={_id:i._id,_rev:i._rev||n.rev};if(a._deleted=!0,isLocalId(a._id)&&typeof this._removeLocal==`function`)return this._removeLocal(i,r);this.bulkDocs({docs:[a]},n,yankError(r,a._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 i=0,a=new Map;function addToMissing(e,t){a.has(e)||a.set(e,{missing:[]}),a.get(e).missing.push(t)}function processDoc(t,n){var r=e[t].slice(0);traverseRevTree(n,function(e,n,i,a,o){var s=n+`-`+i,c=r.indexOf(s);c!==-1&&(r.splice(c,1),o.status!==`available`&&addToMissing(t,s))}),r.forEach(function(e){addToMissing(t,e)})}r.forEach(function(t){this._getRevisionTree(t,function(o,s){if(o&&o.status===404&&o.message===`missing`)a.set(t,{missing:e[t]});else if(o)return n(o);else processDoc(t,s);if(++i===r.length){var c={};return a.forEach(function(e,t){c[t]=e}),n(null,c)}})},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,i)=>{if(r)return n(r);var a=computeHeight(i),o=[],s=[];Object.keys(a).forEach(function(e){a[e]>t&&o.push(e)}),traverseRevTree(i,function(e,t,n,r,i){var a=t+`-`+n;i.status===`available`&&o.indexOf(a)!==-1&&s.push(a)}),this._doCompaction(e,s,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(Ne));if(isLocalId(e)&&typeof this._getLocal==`function`)return this._getLocal(e,n);var r=[];let finishOpenRevs=()=>{var i=[],a=r.length;if(!a)return n(null,i);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)i.push({missing:r});else{for(var o,s=0,c=i.length;s<c;s++)if(i[s].ok&&i[s].ok._rev===t._rev){o=!0;break}o||i.push({ok:t})}a--,a||n(null,i)})})};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 i=0;i<r.length;i++){var a=r[i];if(!isValidRev(a))return n(createError$1(Ue))}finishOpenRevs()}else return n(createError$1(Ie,`function_clause`));return}return this._get(e,t,(r,i)=>{if(r)return r.docId=e,n(r);var a=i.doc,o=i.metadata,s=i.ctx;if(t.conflicts){var c=collectConflicts(o);c.length&&(a._conflicts=c)}if(isDeleted(o,a._rev)&&(a._deleted=!0),t.revs||t.revs_info){for(var l=a._rev.split(`-`),u=parseInt(l[0],10),d=l[1],p=rootToLeaf(o.rev_tree),m=null,h=0;h<p.length;h++){var g=p[h];let e=g.ids.findIndex(e=>e.id===d);(e===u-1||!m&&e!==-1)&&(m=g)}if(!m)return r=Error(`invalid rev tree`),r.docId=e,n(r);let i=a._rev.split(`-`)[1],s=m.ids.findIndex(e=>e.id===i)+1;var _=m.ids.length-s;if(m.ids.splice(s,_),m.ids.reverse(),t.revs&&(a._revisions={start:m.pos+m.ids.length-1,ids:m.ids.map(function(e){return e.id})}),t.revs_info){var v=m.pos+m.ids.length;a._revs_info=m.ids.map(function(e){return v--,{rev:v+`-`+e.id,status:e.opts.status}})}}if(t.attachments&&a._attachments){var y=a._attachments,b=Object.keys(y).length;if(b===0)return n(null,a);Object.keys(y).forEach(e=>{this._getAttachment(a._id,e,y[e],{binary:t.binary,metadata:o,ctx:s},function(t,r){var i=a._attachments[e];i.data=r,delete i.stub,delete i.length,--b||n(null,a)})})}else{if(a._attachments)for(var x in a._attachments)Object.prototype.hasOwnProperty.call(a._attachments,x)&&(a._attachments[x].stub=!0);n(null,a)}})}).bind(this),this.getAttachment=adapterFun(`getAttachment`,function(e,t,n,r){n instanceof Function&&(r=n,n={}),this._get(e,n,(i,a)=>{if(i)return r(i);if(a.doc._attachments&&a.doc._attachments[t])n.ctx=a.ctx,n.binary=!0,n.metadata=a.metadata,this._getAttachment(e,t,a.doc._attachments[t],n,r);else return r(createError$1(P))})}).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(Re,"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(je));for(var r=0;r<e.docs.length;++r){let t=e.docs[r];if(isNotSingleDoc(t))return n(createError$1(Ve));if(`_rev`in t&&!isValidRev(t._rev))return n(createError$1(Ue))}var i;if(e.docs.forEach(function(e){e._attachments&&Object.keys(e._attachments).forEach(function(t){i=i||attachmentNameError(t),e._attachments[t].content_type||guardedConsole$1(`warn`,`Attachment`,t,`on document`,e._id,`is missing content_type`)})}),i)return n(createError$1(Be,i));`new_edits`in t||(`new_edits`in e?t.new_edits=e.new_edits:t.new_edits=!0);var a=this;!t.new_edits&&!isRemote$1(a)&&e.docs.sort(compareByIdThenRev),cleanDocs(e.docs);var o=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(a))for(var i=0,s=r.length;i<s;i++)r[i].id=r[i].id||o[i];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 i=r.dependentDbs,a=this.constructor,o=Object.keys(i).map(e=>new a(n?e.replace(RegExp(`^`+a.prefix),``):e,this.__opts).destroy());Promise.all(o).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=[],i,a=0;let onChange=e=>{this.activeTasks.update(i,{completed_items:++a}),r.push(this.compactDocument(e.id,0))},onError=e=>{this.activeTasks.remove(i,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(i),t(null,{ok:!0})}).catch(onError)};this.info().then(e=>{i=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(Ie,`Purge is not implemented in the `+this.adapter+` adapter.`));var r=this;r._getRevisionTree(e,(i,a)=>{if(i)return n(i);if(!a)return n(createError$1(P));let o;try{o=findPathToLeaf(a,t)}catch(e){return n(e.message||e)}r._purge(e,o,(i,a)=>{if(i)return n(i);appendPurgeSeq(r,e,t).then(function(){return n(null,a)})})})});var TaskQueue$1=class{static{e(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=I.adapters,i=I.preferredAdapters,a=I.prefix,o=t.adapter;if(!o)for(var s=0;s<i.length;++s){if(o=i[s],o===`idb`&&`websql`in r&&hasLocalStorage()&&localStorage[`_pouch__websqldb_`+a+e]){guardedConsole$1(`log`,`PouchDB is downgrading "`+e+`" to WebSQL to avoid data loss, because it was already opened with WebSQL.`);continue}break}var c=r[o];return{name:!(c&&`use_prefix`in c)||c.use_prefix?a+e:e,adapter:o}}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=I.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,I.emit(`debug`,[`adapter`,`Picked adapter: `,t.adapter]),!I.adapters[t.adapter]||!I.adapters[t.adapter].valid())throw Error(`Invalid Adapter: `+t.adapter);if(t.view_adapter&&(!I.adapters[t.view_adapter]||!I.adapters[t.view_adapter].valid()))throw Error(`Invalid View Adapter: `+t.view_adapter);this.taskqueue=new TaskQueue$1,this.adapter=t.adapter,I.adapters[t.adapter].call(this,t,e=>{if(e)return this.taskqueue.fail(e);prepareForDestruction(this),this.emit(`created`,this),I.emit(`created`,this.name),this.taskqueue.ready(this)})}},I=createClass(PouchInternal,function(e,t){PouchInternal.prototype._setup.call(this,e,t)}),et=fetch,L=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}};I.adapters={},I.preferredAdapters=[],I.prefix=`_pouch_`;var tt=new M.default;function setUpEventEmitter(e){Object.keys(M.default.prototype).forEach(function(t){typeof M.default.prototype[t]==`function`&&(e[t]=tt[t].bind(tt))});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(I),I.adapter=function(e,t,n){t.valid()&&(I.adapters[e]=t,n&&I.preferredAdapters.push(e))},I.plugin=function(e){if(typeof e==`function`)e(I);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){I.prototype[t]=e[t]});return this.__defaults&&(I.__defaults=Object.assign({},this.__defaults)),I},I.defaults=function(e){let t=createClass(I,function(e,n){n=n||{},e&&typeof e==`object`&&(n=e,e=n.name,delete n.name),n=Object.assign({},t.__defaults,n),I.call(this,e,n)});return t.preferredAdapters=I.preferredAdapters.slice(),Object.keys(I).forEach(function(e){e in t||(t[e]=I[e])}),t.__defaults=Object.assign({},this.__defaults,e),t},I.fetch=function(e,t){return et(e,t)},I.prototype.activeTasks=I.activeTasks=new ActiveTasks;var nt=`9.0.0`;function getFieldFromDoc$1(e,t){for(var n=e,r=0,i=t.length;r<i;r++){var a=t[r];if(n=n[a],!n)break}return n}e(getFieldFromDoc$1,`getFieldFromDoc`);function compare$1(e,t){return e<t?-1:e>t?1:0}e(compare$1,`compare`);function parseField$1(e){for(var t=[],n=``,r=0,i=e.length;r<i;r++){var a=e[r];r>0&&e[r-1]===`\\`&&(a===`$`||a===`.`)?n=n.substring(0,n.length-1)+a:a===`.`?(t.push(n),n=``):n+=a}return t.push(n),t}e(parseField$1,`parseField`);var rt=[`$or`,`$nor`,`$not`];function isCombinationalField$1(e){return rt.indexOf(e)>-1}e(isCombinationalField$1,`isCombinationalField`);function getKey$1(e){return Object.keys(e)[0]}e(getKey$1,`getKey`);function getValue$1(e){return e[getKey$1(e)]}e(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 i=e[r];if(typeof i!=`object`&&(i={$eq:i}),isCombinationalField$1(r))if(i instanceof Array){if(n[r]){n[r]=!1,t[r]=i;return}var a=[];t[r].forEach(function(e){Object.keys(i).forEach(function(t){var n=i[t],r=Math.max(Object.keys(e).length,Object.keys(n).length),o=mergeAndedSelectors$1([e,n]);Object.keys(o).length<=r||a.push(o)})}),t[r]=a}else t[r]=mergeAndedSelectors$1([i]);else{var o=t[r]=t[r]||{};Object.keys(i).forEach(function(e){var t=i[e];if(e===`$gt`||e===`$gte`)return mergeGtGte$1(e,t,o);if(e===`$lt`||e===`$lte`)return mergeLtLte$1(e,t,o);if(e===`$ne`)return mergeNe$1(t,o);if(e===`$eq`)return mergeEq$1(t,o);if(e===`$regex`)return mergeRegex$1(t,o);o[e]=t})}})}),t}e(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))}e(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))}e(mergeLtLte$1,`mergeLtLte`);function mergeNe$1(e,t){`$ne`in t?t.$ne.push(e):t.$ne=[e]}e(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}e(mergeEq$1,`mergeEq`);function mergeRegex$1(e,t){`$regex`in t?t.$regex.push(e):t.$regex=[e]}e(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}e(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}e(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],i=e[r];(typeof i!=`object`||!i)&&(e[r]={$eq:i})}})}),`$not`in t&&(t.$not=mergeAndedSelectors$1([t.$not]));for(var n=Object.keys(t),r=0;r<n.length;r++){var i=n[r],a=t[i];(typeof a!=`object`||!a)&&(a={$eq:a}),t[i]=a}return normalizeArrayOperators$1(t),t}e(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)})}e(normalizeArrayOperators$1,`normalizeArrayOperators`);function pad$1(e,t,n){for(var r=``,i=n-e.length;r.length<i;)r+=t;return r}e(pad$1,`pad`);function padLeft$1(e,t,n){return pad$1(e,t,n)+e}e(padLeft$1,`padLeft`);var it=-324,at=3,ot=``;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)}e(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 i in e={},t)if(Object.prototype.hasOwnProperty.call(t,i)){var a=t[i];a!==void 0&&(e[i]=normalizeKey$1(a))}}}return e}e(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,i=n.length,a=``;if(t)for(;++r<i;)a+=toIndexableString$1(n[r]);else for(;++r<i;){var o=n[r];a+=toIndexableString$1(o)+toIndexableString$1(e[o])}return a}return``}e(indexify$1,`indexify`);function toIndexableString$1(e){return e=normalizeKey$1(e),collationIndex$1(e)+ot+indexify$1(e)+`\0`}e(toIndexableString$1,`toIndexableString`);function parseNumber$1(e,t){var n=t,r;if(e[t]===`1`)r=0,t++;else{var i=e[t]===`0`;t++;var a=``,o=e.substring(t,t+at),s=parseInt(o,10)+it;for(i&&(s=-s),t+=at;;){var c=e[t];if(c===`\0`)break;a+=c,t++}a=a.split(`.`),r=a.length===1?parseInt(a,10):parseFloat(a[0]+`.`+a[1]),i&&(r-=10),s!==0&&(r=parseFloat(r+`e`+s))}return{num:r,length:t-n}}e(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 i=r.element,a=r.index;if(Array.isArray(i))i.push(n);else if(a===e.length-2){var o=e.pop();i[o]=n}else e.push(n)}}e(pop$1,`pop`);function parseIndexableString$1(e){for(var t=[],n=[],r=0;;){var i=e[r++];if(i===`\0`){if(t.length===1)return t.pop();pop$1(t,n);continue}switch(i){case`1`:t.push(null);break;case`2`:t.push(e[r]===`1`),r++;break;case`3`:var a=parseNumber$1(e,r);t.push(a.num),r+=a.length;break;case`4`:for(var o=``;;){var s=e[r];if(s===`\0`)break;o+=s,r++}o=o.replace(/\u0001\u0001/g,`\0`).replace(/\u0001\u0002/g,``).replace(/\u0002\u0002/g,``),t.push(o);break;case`5`:var c={element:[],index:t.length};t.push(c.element),n.push(c);break;case`6`:var l={element:{},index:t.length};t.push(l.element),n.push(l);break;default:throw Error(`bad collationIndex or unexpectedly reached end of input: `+i)}}}e(parseIndexableString$1,`parseIndexableString`);function arrayCollate$1(e,t){for(var n=Math.min(e.length,t.length),r=0;r<n;r++){var i=collate$1(e[r],t[r]);if(i!==0)return i}return e.length===t.length?0:e.length>t.length?1:-1}e(arrayCollate$1,`arrayCollate`);function stringCollate$1(e,t){return e===t?0:e>t?1:-1}e(stringCollate$1,`stringCollate`);function objectCollate$1(e,t){for(var n=Object.keys(e),r=Object.keys(t),i=Math.min(n.length,r.length),a=0;a<i;a++){var o=collate$1(n[a],r[a]);if(o!==0||(o=collate$1(e[n[a]],t[r[a]]),o!==0))return o}return n.length===r.length?0:n.length>r.length?1:-1}e(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}e(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,i=r?`0`:`2`,a=padLeft$1(((r?-n:n)-it).toString(),`0`,at);i+=ot+a;var o=Math.abs(parseFloat(t[0]));r&&(o=10-o);var s=o.toFixed(20);return s=s.replace(/\.?0+$/,``),i+=ot+s,i}e(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}}e(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 i=t.skip||0,a=(`limit`in t?t.limit:e.length)+i;e=e.slice(i,a)}return e}e(filterInMemoryFields$1,`filterInMemoryFields`);function rowFilter$1(e,t,n){return n.every(function(n){var r=t[n],i=parseField$1(n),a=getFieldFromDoc$1(e,i);return isCombinationalField$1(n)?matchCominationalSelector$1(n,r,e):matchSelector$1(r,e,i,a)})}e(rowFilter$1,`rowFilter`);function matchSelector$1(e,t,n,r){return e?typeof e==`object`?Object.keys(e).every(function(i){var a=e[i];if(i.indexOf(`$`)===0)return match$1(i,t,a,n,r);var o=parseField$1(i);if(r===void 0&&typeof a!=`object`&&o.length>0)return!1;var s=getFieldFromDoc$1(r,o);return typeof a==`object`?matchSelector$1(a,t,n,s):match$1(`$eq`,t,a,o,s)}):e===r:!0}e(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))})}e(matchCominationalSelector$1,`matchCominationalSelector`);function match$1(e,t,n,r,i){if(!st[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 st[e](t,n,r,i)}e(match$1,`match`);function fieldExists$1(e){return e!=null}e(fieldExists$1,`fieldExists`);function fieldIsNotUndefined$1(e){return e!==void 0}e(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}e(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})}e(arrayContainsValue$1,`arrayContainsValue`);function arrayContainsAllValues$1(e,t){return t.every(function(t){return e.some(function(e){return collate$1(t,e)===0})})}e(arrayContainsAllValues$1,`arrayContainsAllValues`);function arraySize$1(e,t){return e.length===t}e(arraySize$1,`arraySize`);function regexMatch$1(e,t){return new RegExp(t).test(e)}e(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]`}}e(typeMatch$1,`typeMatch`);var st={$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}e(matchesSelector$1,`matchesSelector`);function evalFilter(e){return scopeEval(`"use strict";
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
+ `),{})}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(Be,"`view` filter parameter not found or invalid."));var r=parseDesignDocFunctionName(t.view);e.db.get(`_design/`+r[0],function(i,a){if(e.isCancelled)return n(null,{status:`cancelled`});if(i)return n(generateErrorFromResponse$1(i));var o=a&&a.views&&a.views[r[1]]&&a.views[r[1]].map;if(!o)return n(createError$1(P,a.views?`missing json key: `+r[1]:`missing json key: views`));t.filter=evalView(o),e.doChanges(t)})}else if(t.selector)t.filter=function(e){return matchesSelector$1(e,t.selector)},e.doChanges(t);else{var i=parseDesignDocFunctionName(t.filter);e.db.get(`_design/`+i[0],function(r,a){if(e.isCancelled)return n(null,{status:`cancelled`});if(r)return n(generateErrorFromResponse$1(r));var o=a&&a.filters&&a.filters[i[1]];if(!o)return n(createError$1(P,a&&a.filters?`missing json key: `+i[1]:`missing json key: filters`));t.filter=evalFilter(o),e.doChanges(t)})}}function applyChangesFilterPlugin(e){e._changesFilterPlugin={validate,normalize,shouldFilter,filter}}I.plugin(applyChangesFilterPlugin),I.version=nt;function checkBlobSupport(e,t,n){return new Promise(function(r){var i=createBlob$1([``]);let a;if(typeof n==`function`){let r=n(i);a=e.objectStore(t).put(r)}else{let r=n;a=e.objectStore(t).put(i,r)}a.onsuccess=function(){var e=navigator.userAgent.match(/Chrome\/(\d+)/);r(navigator.userAgent.match(/Edge\//)||!e||parseInt(e[1],10)>=43)},a.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 ct=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`]),lt=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(Ue);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,i=[r[0],t,[]],a=1,o=r.length;a<o;a++)i=[r[a],{status:`missing`},[i]];return[{pos:n,ids:i}]}function parseDoc(e,t,n){n||(n={deterministic_revs:!0});var r,i,a,o={status:`available`};if(e._deleted&&(o.deleted=!0),t)if(e._id||(e._id=Qe()),i=rev(e,n.deterministic_revs),e._rev){if(a=parseRevisionInfo(e._rev),a.error)return a;e._rev_tree=[{pos:a.prefix,ids:[a.id,{status:`missing`},[[i,o,[]]]]}],r=a.prefix+1}else e._rev_tree=[{pos:1,ids:[i,o,[]]}],r=1;else if(e._revisions&&(e._rev_tree=makeRevTreeFromRevisions(e._revisions,o),r=e._revisions.start,i=e._revisions.ids[0]),!e._rev_tree){if(a=parseRevisionInfo(e._rev),a.error)return a;r=a.prefix,i=a.id,e._rev_tree=[{pos:r,ids:[i,o,[]]}]}invalidIdError(e._id),e._rev=r+`-`+i;var s={metadata:{},data:{}};for(var c in e)if(Object.prototype.hasOwnProperty.call(e,c)){var l=c[0]===`_`;if(l&&!ct[c]){var u=createError$1(ze,c);throw u.message=ze.message+`: `+c,u}else l&&!lt[c]?s.metadata[c.slice(1)]=e[c]:s.data[c]=e[c]}return s}function parseBase64(e){try{return Ye(e)}catch{return{error:createError$1(Le,`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,i;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){i=e,r++,r===n.length&&done()}for(var a in e.data._attachments)Object.prototype.hasOwnProperty.call(e.data._attachments,a)&&preprocessAttachment(e.data._attachments[a],t,processedAttachment)});function done(){r++,e.length===r&&(i?n(i):n())}}function updateDoc(e,t,n,r,i,a,o,s){if(revExists(t.rev_tree,n.metadata.rev)&&!s)return r[i]=n,a();var c=t.winningRev||winningRev(t),l=`deleted`in t?t.deleted:isDeleted(t,c),u=`deleted`in n.metadata?n.metadata.deleted:isDeleted(n.metadata),d=/^1-/.test(n.metadata.rev);if(l&&!u&&s&&d){var p=n.data;p._rev=c,p._id=n.metadata.id,n=parseDoc(p,s)}var m=merge(t.rev_tree,n.metadata.rev_tree[0],e);if(s&&(l&&u&&m.conflicts!==`new_leaf`||!l&&m.conflicts!==`new_leaf`||l&&!u&&m.conflicts===`new_branch`))return r[i]=createError$1(Me),a();var h=n.metadata.rev;n.metadata.rev_tree=m.tree,n.stemmedRevs=m.stemmedRevs||[],t.rev_map&&(n.metadata.rev_map=t.rev_map);var g=winningRev(n.metadata),_=isDeleted(n.metadata,g),v=l===_?0:l<_?-1:1,y=h===g?_:isDeleted(n.metadata,h);o(n,g,_,y,!0,v,i,a)}function rootIsMissing(e){return e.metadata.rev_tree[0].ids[1].status===`missing`}function processDocs(e,t,n,r,i,a,o,s,c){e=e||1e3;function insertDoc(e,t,n){var r=winningRev(e.metadata),i=isDeleted(e.metadata,r);if(`was_delete`in s&&i)return a[t]=createError$1(P,`deleted`),n();if(l&&rootIsMissing(e))return a[t]=createError$1(Me),n();o(e,r,i,i,!1,i?0:1,t,n)}var l=s.new_edits,u=new Map,d=0,p=t.length;function checkAllDocsDone(){++d===p&&c&&c()}t.forEach(function(e,t){if(e._id&&isLocalId(e._id)){n[e._deleted?`_removeLocal`:`_putLocal`](e,{ctx:i},function(e,n){a[t]=e||n,checkAllDocsDone()});return}var r=e.metadata.id;u.has(r)?(p--,u.get(r).push([e,t])):u.set(r,[[e,t]])}),u.forEach(function(t,n){var i=0;function docWritten(){++i<t.length?nextDoc():checkAllDocsDone()}function nextDoc(){var s=t[i],c=s[0],u=s[1];if(r.has(n))updateDoc(e,r.get(n),c,a,u,docWritten,o,l);else{var d=merge([],c.metadata.rev_tree[0],e);c.metadata.rev_tree=d.tree,c.stemmedRevs=d.stemmedRevs||[],insertDoc(c,u,docWritten)}}nextDoc()})}var ut=5,R=`document-store`,z=`by-sequence`,B=`attach-store`,V=`attach-seq-store`,H=`meta-store`,U=`local-store`,dt=`detect-blob-support`;function safeJsonParse(e){try{return JSON.parse(e)}catch{return Ee.parse(e)}}function safeJsonStringify(e){try{return JSON.stringify(e)}catch{return Ee.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(He,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 i=Object.keys(e._attachments||{});if(!i.length)return r&&r();var a=0;function checkDone(){++a===i.length&&r&&r()}function fetchAttachment(e,t){var r=e._attachments[t],i=r.digest,a=n.objectStore(B).get(i);a.onsuccess=function(e){r.body=e.target.result.body,checkDone()}}i.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 i=r.body,a=r.content_type;return new Promise(function(o){readBlobData(i,a,t,function(t){e.doc._attachments[n]=Object.assign(pick$1(r,[`digest`,`content_type`]),{data:t}),o()})})}}))}}))}function compactRevs(e,t,n){var r=[],i=n.objectStore(z),a=n.objectStore(B),o=n.objectStore(V),s=e.length;function checkDone(){s--,s||deleteOrphanedAttachments()}function deleteOrphanedAttachments(){r.length&&r.forEach(function(e){var t=o.index(`digestSeq`).count(IDBKeyRange.bound(e+`::`,e+`::￿`,!1,!1));t.onsuccess=function(t){t.target.result||a.delete(e)}})}e.forEach(function(e){var n=i.index(`_doc_id_rev`),a=t+`::`+e;n.getKey(a).onsuccess=function(e){var t=e.target.result;if(typeof t!=`number`)return checkDone();i.delete(t);var n=o.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),o.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 ft=new Changes;function idbBulkDocs(e,t,n,r,i,a){for(var o=t.docs,s,c,l,u,d,p,m,h,g=0,_=o.length;g<_;g++){var v=o[g];v._id&&isLocalId(v._id)||(v=o[g]=parseDoc(v,n.new_edits,e),v.error&&!m&&(m=v))}if(m)return a(m);var y=!1,b=0,x=Array(o.length),S=new Map,C=!1;preprocessAttachments(o,r._meta.blobSupport?`blob`:`base64`,function(e){if(e)return a(e);startTransaction()});function startTransaction(){var e=openTransactionSafely(i,[R,z,B,U,V,H],`readwrite`);if(e.error)return a(e.error);s=e.txn,s.onabort=idbError(a),s.ontimeout=idbError(a),s.oncomplete=complete,c=s.objectStore(R),l=s.objectStore(z),u=s.objectStore(B),d=s.objectStore(V),p=s.objectStore(H),p.get(H).onsuccess=function(e){h=e.target.result,updateDocCountIfReady()},verifyAttachments(function(e){if(e)return C=!0,a(e);fetchExistingDocs()})}function onAllDocsProcessed(){y=!0,updateDocCountIfReady()}function idbProcessDocs(){processDocs(e.revs_limit,o,r,S,s,x,writeDoc,n,onAllDocsProcessed)}function updateDocCountIfReady(){!h||!y||(h.docCount+=b,p.put(h))}function fetchExistingDocs(){if(!o.length)return;var e=0;function checkDone(){++e===o.length&&idbProcessDocs()}function readMetadata(e){var t=decodeMetadata(e.target.result);t&&S.set(t.id,t),checkDone()}for(var t=0,n=o.length;t<n;t++){var r=o[t];if(r._id&&isLocalId(r._id)){checkDone();continue}var i=c.get(r.metadata.id);i.onsuccess=readMetadata}}function complete(){C||(ft.notify(r._meta.name),a(null,x))}function verifyAttachment(e,t){var n=u.get(e);n.onsuccess=function(n){if(n.target.result)t();else{var r=createError$1(We,`unknown stub attachment with digest `+e);r.status=412,t(r)}}}function verifyAttachments(e){var t=[];if(o.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,i,a,o,s){e.metadata.winningRev=t,e.metadata.deleted=n;var c=e.data;if(c._id=e.metadata.id,c._rev=e.metadata.rev,r&&(c._deleted=!0),c._attachments&&Object.keys(c._attachments).length)return writeAttachments(e,t,n,i,o,s);b+=a,updateDocCountIfReady(),finishDoc(e,t,n,i,o,s)}function finishDoc(e,t,n,i,a,o){var u=e.data,d=e.metadata;u._doc_id_rev=d.id+`::`+d.rev,delete u._id,delete u._rev;function afterPutDoc(a){var o=e.stemmedRevs||[];i&&r.auto_compaction&&(o=o.concat(compactTree(e.metadata))),o&&o.length&&compactRevs(o,e.metadata.id,s),d.seq=a.target.result;var l=encodeMetadata(d,t,n),u=c.put(l);u.onsuccess=afterPutMetadata}function afterPutDocError(e){e.preventDefault(),e.stopPropagation();var t=l.index(`_doc_id_rev`).getKey(u._doc_id_rev);t.onsuccess=function(e){var t=l.put(u,e.target.result);t.onsuccess=afterPutDoc}}function afterPutMetadata(){x[a]={ok:!0,id:d.id,rev:d.rev},S.set(e.metadata.id,e.metadata),insertAttachmentMappings(e,d.seq,o)}var p=l.put(u);p.onsuccess=afterPutDoc,p.onerror=afterPutDocError}function writeAttachments(e,t,n,r,i,a){var o=e.data,s=0,c=Object.keys(o._attachments);function collectResults(){s===c.length&&finishDoc(e,t,n,r,i,a)}function attachmentSaved(){s++,collectResults()}c.forEach(function(n){var r=e.data._attachments[n];if(r.stub)s++,collectResults();else{var i=r.data;delete r.data,r.revpos=parseInt(t,10);var a=r.digest;saveAttachment(a,i,attachmentSaved)}})}function insertAttachmentMappings(e,t,n){var r=0,i=Object.keys(e.data._attachments||{});if(!i.length)return n();function checkDone(){++r===i.length&&n()}function add(n){var r=e.data._attachments[n].digest,i=d.put({seq:t,digestSeq:r+`::`+t});i.onsuccess=checkDone,i.onerror=function(e){e.preventDefault(),e.stopPropagation(),checkDone()}}for(var a=0;a<i.length;a++)add(i[a])}function saveAttachment(e,t,n){var r=u.count(e);r.onsuccess=function(r){if(r.target.result)return n();var i={digest:e,body:t},a=u.put(i);a.onsuccess=n}}}function runBatchedCursor(e,t,n,r,i){r===-1&&(r=1e3);var a=typeof e.getAll==`function`&&typeof e.getAllKeys==`function`&&r>1&&!n,o,s,c;function onGetAll(e){s=e.target.result,o&&i(o,s,c)}function onGetAllKeys(e){o=e.target.result,s&&i(o,s,c)}function continuePseudoCursor(){if(!o.length)return i();var n=o[o.length-1],a;if(t&&t.upper)try{a=IDBKeyRange.bound(n,t.upper,!0,t.upperOpen)}catch(e){if(e.name===`DataError`&&e.code===0)return i()}else a=IDBKeyRange.lowerBound(n,!0);t=a,o=null,s=null,e.getAll(t,r).onsuccess=onGetAll,e.getAllKeys(t,r).onsuccess=onGetAllKeys}function onCursor(e){var t=e.target.result;if(!t)return i();i([t.key],[t.value],t)}a?(c={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),i=0;e.forEach(function(a,o){t.get(a).onsuccess=function(t){t.target.result?r[o]=t.target.result:r[o]={key:a,error:`not_found`},i++,i===e.length&&n(e,r,{})}})}function createKeyRange(e,t,n,r,i){try{if(e&&t)return i?IDBKeyRange.bound(t,e,!n,!1):IDBKeyRange.bound(e,t,!1,!n);if(e)return i?IDBKeyRange.upperBound(e):IDBKeyRange.lowerBound(e);if(t)return i?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,i=`endkey`in e?e.endkey:!1,a=`key`in e?e.key:!1,o=`keys`in e?e.keys:!1,s=e.skip||0,c=typeof e.limit==`number`?e.limit:-1,l=e.inclusive_end!==!1,u,d;if(!o&&(u=createKeyRange(r,i,l,a,e.descending),d=u&&u.error,d&&!(d.name===`DataError`&&d.code===0)))return n(createError$1(He,d.name,d.message));var p=[R,z,H];e.attachments&&p.push(B);var m=openTransactionSafely(t,p,`readonly`);if(m.error)return n(m.error);var h=m.txn;h.oncomplete=onTxnComplete,h.onabort=idbError(n);var g=h.objectStore(R),_=h.objectStore(z),v=h.objectStore(H),y=_.index(`_doc_id_rev`),b=[],x,S;v.get(H).onsuccess=function(e){x=e.target.result.docCount},e.update_seq&&(_.openKeyCursor(null,`prev`).onsuccess=e=>{var t=e.target.result;t&&t.key&&(S=t.key)});function fetchDocAsynchronously(t,n,r){var i=t.id+`::`+r;y.get(i).onsuccess=function onGetDoc(r){if(n.doc=decodeDoc(r.target.result)||{},e.conflicts){var i=collectConflicts(t);i.length&&(n.doc._conflicts=i)}fetchAttachmentsIfNecessary(n.doc,e,h)}}function allDocsInner(t,n){var r={id:n.id,key:n.id,value:{rev:t}};n.deleted?o&&(b.push(r),r.value.deleted=!0,r.doc=null):s--<=0&&(b.push(r),e.include_docs&&fetchDocAsynchronously(n,r,t))}function processBatch(e){for(var t=0,n=e.length;t<n&&b.length!==c;t++){var r=e[t];if(r.error&&o){b.push(r);continue}var i=decodeMetadata(r),a=i.winningRev;allDocsInner(a,i)}}function onBatch(e,t,n){n&&(processBatch(t),b.length<c&&n.continue())}function onGetAll(t){var n=t.target.result;e.descending&&(n=n.reverse()),processBatch(n)}function onResultsReady(){var t={total_rows:x,offset:e.skip,rows:b};e.update_seq&&S!==void 0&&(t.update_seq=S),n(null,t)}function onTxnComplete(){e.attachments?postProcessAttachments(b,e.binary).then(onResultsReady):onResultsReady()}if(!(d||c===0)){if(o)return allDocsKeys(o,g,onBatch);if(c===-1)return getAll(g,u,onGetAll);runBatchedCursor(g,u,e.descending,c+s,onBatch)}}function countDocs(e,t){var n=e.objectStore(R).index(`deletedOrLocal`);n.count(IDBKeyRange.only(`0`)).onsuccess=function(e){t(e.target.result)}}var pt=!1,mt=[];function tryCode(e,t,n,r){try{e(t,n)}catch(e){r.emit(`error`,e)}}function applyNext(){pt||!mt.length||(pt=!0,mt.shift()())}function enqueueTask(e,t,n){mt.push(function runAction(){e(function runCallback(e,r){tryCode(t,e,r,n),pt=!1,N(function runNext(){applyNext(n)})})}),applyNext()}function changes(e,t,n,r){if(e=clone$1(e),e.continuous){var i=n+`:`+Qe();return ft.addListener(n,i,t,e),ft.notify(n),{cancel:function(){ft.removeListener(n,i)}}}var a=e.doc_ids&&new Set(e.doc_ids);e.since=e.since||0;var o=e.since,s=`limit`in e?e.limit:-1;s===0&&(s=1);var c=[],l=0,u=filterChange(e),d=new Map,p,m,h,g;function onBatch(t,n,r){if(!r||!t.length)return;var i=Array(t.length),a=Array(t.length);function processMetadataAndWinningDoc(t,n){var r=e.processChange(n,t,e);o=r.seq=t.seq;var i=u(r);return typeof i==`object`?Promise.reject(i):i?(l++,e.return_docs&&c.push(r),e.attachments&&e.include_docs?new Promise(function(t){fetchAttachmentsIfNecessary(n,e,p,function(){postProcessAttachments([r],e.binary).then(function(){t(r)})})}):Promise.resolve(r)):Promise.resolve()}function onBatchDone(){for(var t=[],n=0,o=i.length;n<o&&l!==s;n++){var c=i[n];if(c){var u=a[n];t.push(processMetadataAndWinningDoc(u,c))}}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),l!==s&&r.continue()}var d=0;n.forEach(function(e,n){var r=decodeDoc(e),o=t[n];fetchWinningDocAndMetadata(r,o,function(e,r){a[n]=e,i[n]=r,++d===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 i=e._id+`::`+n.winningRev,a=g.get(i);a.onsuccess=function(e){r(n,decodeDoc(e.target.result))}}function fetchWinningDocAndMetadata(e,t,n){if(a&&!a.has(e._id))return n();var r=d.get(e._id);if(r)return onGetMetadata(e,t,r,n);h.get(e._id).onsuccess=function(i){r=decodeMetadata(i.target.result),d.set(e._id,r),onGetMetadata(e,t,r,n)}}function finish(){e.complete(null,{results:c,last_seq:o})}function onTxnComplete(){!e.continuous&&e.attachments?postProcessAttachments(c).then(finish):finish()}var _=[R,z];e.attachments&&_.push(B);var v=openTransactionSafely(r,_,`readonly`);if(v.error)return e.complete(v.error);p=v.txn,p.onabort=idbError(e.complete),p.oncomplete=onTxnComplete,m=p.objectStore(z),h=p.objectStore(R),g=m.index(`_doc_id_rev`);var y=e.since&&!e.descending?IDBKeyRange.lowerBound(e.since,!0):null;runBatchedCursor(m,y,e.descending,s,onBatch)}var W=new Map,ht,gt=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,i=null,a=null;e._meta=null;function enrichCallbackError(e){return function(t,n){t&&t instanceof Error&&!t.reason&&a&&(t.reason=a),e(t,n)}}function createSchema(e){var t=e.createObjectStore(R,{keyPath:`id`});e.createObjectStore(z,{autoIncrement:!0}).createIndex(`_doc_id_rev`,`_doc_id_rev`,{unique:!0}),e.createObjectStore(B,{keyPath:`digest`}),e.createObjectStore(H,{keyPath:`id`,autoIncrement:!1}),e.createObjectStore(dt),t.createIndex(`deletedOrLocal`,`deletedOrLocal`,{unique:!1}),e.createObjectStore(U,{keyPath:`_id`});var n=e.createObjectStore(V,{autoIncrement:!0});n.createIndex(`seq`,`seq`),n.createIndex(`digestSeq`,`digestSeq`,{unique:!0})}function addDeletedOrLocalIndex(e,t){var n=e.objectStore(R);n.createIndex(`deletedOrLocal`,`deletedOrLocal`,{unique:!1}),n.openCursor().onsuccess=function(e){var r=e.target.result;if(r){var i=r.value;i.deletedOrLocal=isDeleted(i)?`1`:`0`,n.put(i),r.continue()}else t()}}function createLocalStoreSchema(e){e.createObjectStore(U,{keyPath:`_id`}).createIndex(`_doc_id_rev`,`_doc_id_rev`,{unique:!0})}function migrateLocalStore(e,t){var n=e.objectStore(U),r=e.objectStore(R),i=e.objectStore(z),a=r.openCursor();a.onsuccess=function(e){var a=e.target.result;if(a){var o=a.value,s=o.id,c=isLocalId(s),l=winningRev(o);if(c){var u=s+`::`+l,d=s+`::`,p=s+`::~`,m=i.index(`_doc_id_rev`),h=IDBKeyRange.bound(d,p,!1,!1),g=m.openCursor(h);g.onsuccess=function(e){if(g=e.target.result,!g)r.delete(a.primaryKey),a.continue();else{var t=g.value;t._doc_id_rev===u&&n.put(t),i.delete(g.primaryKey),g.continue()}}}else a.continue()}else t&&t()}}function addAttachAndSeqStore(e){var t=e.createObjectStore(V,{autoIncrement:!0});t.createIndex(`seq`,`seq`),t.createIndex(`digestSeq`,`digestSeq`,{unique:!0})}function migrateAttsAndSeqs(e,t){var n=e.objectStore(z),r=e.objectStore(B),i=e.objectStore(V),a=r.count();a.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,a=n.primaryKey,o=Object.keys(r._attachments||{}),s={},c=0;c<o.length;c++){var l=r._attachments[o[c]];s[l.digest]=!0}var u=Object.keys(s);for(c=0;c<u.length;c++){var d=u[c];i.put({seq:a,digestSeq:d+`::`+a})}n.continue()}}}function migrateMetadata(e){function decodeMetadataCompat(e){return e.data?decodeMetadata(e):(e.deleted=e.deletedOrLocal===`1`,e)}var t=e.objectStore(z),n=e.objectStore(R),r=n.openCursor();r.onsuccess=function(e){var r=e.target.result;if(!r)return;var i=decodeMetadataCompat(r.value);i.winningRev=i.winningRev||winningRev(i);function fetchMetadataSeq(){var e=i.id+`::`,n=i.id+`::￿`,r=t.index(`_doc_id_rev`).openCursor(IDBKeyRange.bound(e,n)),a=0;r.onsuccess=function(e){var t=e.target.result;if(!t)return i.seq=a,onGetMetadataSeq();var n=t.primaryKey;n>a&&(a=n),t.continue()}}function onGetMetadataSeq(){var e=encodeMetadata(i,i.winningRev,i.deleted),t=n.put(e);t.onsuccess=function(){r.continue()}}if(i.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,a){idbBulkDocs(t,n,r,e,i,enrichCallbackError(a))},e._get=function idb_get(e,t,n){var r,a,o,s=t.ctx;if(!s){var c=openTransactionSafely(i,[R,z,B],`readonly`);if(c.error)return n(c.error);s=c.txn}function finish(){n(o,{doc:r,metadata:a,ctx:s})}s.objectStore(R).get(e).onsuccess=function(e){if(a=decodeMetadata(e.target.result),!a)return o=createError$1(P,`missing`),finish();var n;if(t.rev)n=t.latest?latest(t.rev,a):t.rev;else if(n=a.winningRev,isDeleted(a))return o=createError$1(P,`deleted`),finish();var i=s.objectStore(z),c=a.id+`::`+n;i.index(`_doc_id_rev`).get(c).onsuccess=function(e){if(r=e.target.result,r&&(r=decodeDoc(r)),!r)return o=createError$1(P,`missing`),finish();finish()}}},e._getAttachment=function(e,t,n,r,a){var o;if(r.ctx)o=r.ctx;else{var s=openTransactionSafely(i,[R,z,B],`readonly`);if(s.error)return a(s.error);o=s.txn}var c=n.digest,l=n.content_type;o.objectStore(B).get(c).onsuccess=function(e){var t=e.target.result.body;readBlobData(t,l,r.binary,function(e){a(null,e)})}},e._info=function idb_info(t){var n,r,a=openTransactionSafely(i,[H,z],`readonly`);if(a.error)return t(a.error);var o=a.txn;o.objectStore(H).get(H).onsuccess=function(e){r=e.target.result.docCount},o.objectStore(z).openKeyCursor(null,`prev`).onsuccess=function(e){var t=e.target.result;n=t?t.key:0},o.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,i,enrichCallbackError(t))},e._changes=function idbChanges(t){return changes(t,e,r,i)},e._close=function(e){i.close(),W.delete(r),e()},e._getRevisionTree=function(e,t){var n=openTransactionSafely(i,[R],`readonly`);if(n.error)return t(n.error);var r=n.txn.objectStore(R).get(e);r.onsuccess=function(e){var n=decodeMetadata(e.target.result);n?t(null,n.rev_tree):t(createError$1(P))}},e._doCompaction=function(e,t,n){var r=openTransactionSafely(i,[R,z,B,V],`readwrite`);if(r.error)return n(r.error);var a=r.txn,o=a.objectStore(R);o.get(e).onsuccess=function(n){var r=decodeMetadata(n.target.result);traverseRevTree(r.rev_tree,function(e,n,r,i,a){var o=n+`-`+r;t.indexOf(o)!==-1&&(a.status=`missing`)}),compactRevs(t,e,a);var i=r.winningRev,o=r.deleted;a.objectStore(R).put(encodeMetadata(r,i,o))},a.onabort=idbError(n),a.oncomplete=function(){n()}},e._getLocal=function(e,t){var n=openTransactionSafely(i,[U],`readonly`);if(n.error)return t(n.error);var r=n.txn.objectStore(U).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(P))}},e._putLocal=function(e,t,n){typeof t==`function`&&(n=t,t={}),delete e._revisions;var r=e._rev,a=e._id;r?e._rev=`0-`+(parseInt(r.split(`-`)[1],10)+1):e._rev=`0-1`;var o=t.ctx,s;if(!o){var c=openTransactionSafely(i,[U],`readwrite`);if(c.error)return n(c.error);o=c.txn,o.onerror=idbError(n),o.oncomplete=function(){s&&n(null,s)}}var l=o.objectStore(U),u;r?(u=l.get(a),u.onsuccess=function(i){var a=i.target.result;if(!a||a._rev!==r)n(createError$1(Me));else{var o=l.put(e);o.onsuccess=function(){s={ok:!0,id:e._id,rev:e._rev},t.ctx&&n(null,s)}}}):(u=l.add(e),u.onerror=function(e){n(createError$1(Me)),e.preventDefault(),e.stopPropagation()},u.onsuccess=function(){s={ok:!0,id:e._id,rev:e._rev},t.ctx&&n(null,s)})},e._removeLocal=function(e,t,n){typeof t==`function`&&(n=t,t={});var r=t.ctx;if(!r){var a=openTransactionSafely(i,[U],`readwrite`);if(a.error)return n(a.error);r=a.txn,r.oncomplete=function(){o&&n(null,o)}}var o,s=e._id,c=r.objectStore(U),l=c.get(s);l.onerror=idbError(n),l.onsuccess=function(r){var i=r.target.result;!i||i._rev!==e._rev?n(createError$1(P)):(c.delete(s),o={ok:!0,id:s,rev:`0-0`},t.ctx&&n(null,o))}},e._destroy=function(e,t){ft.removeAllListeners(r);var n=gt.get(r);n&&n.result&&(n.result.close(),W.delete(r));var i=indexedDB.deleteDatabase(r);i.onsuccess=function(){gt.delete(r),hasLocalStorage()&&r in localStorage&&delete localStorage[r],t(null,{ok:!0})},i.onerror=idbError(t)};var o=W.get(r);if(o)return i=o.idb,e._meta=o.global,N(function(){n(null,e)});var s=indexedDB.open(r,ut);gt.set(r,s),s.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],i=e.oldVersion;function next(){var e=r[i-1];i++,e&&e(n,next)}next()},s.onsuccess=function(t){i=t.target.result,i.onversionchange=function(){i.close(),W.delete(r)},i.onabort=function(e){guardedConsole$1(`error`,`Database has a global failure`,e.target.error),a=e.target.error,i.close(),W.delete(r)};var o=i.transaction([H,dt,R],`readwrite`),s=!1,c,l,u,d;function completeSetup(){u===void 0||!s||(e._meta={name:r,instanceId:d,blobSupport:u},W.set(r,{idb:i,global:e._meta}),n(null,e))}function storeMetaDocIfReady(){if(!(l===void 0||c===void 0)){var e=r+`_id`;e in c?d=c[e]:c[e]=d=Qe(),c.docCount=l,o.objectStore(H).put(c)}}o.objectStore(H).get(H).onsuccess=function(e){c=e.target.result||{id:H},storeMetaDocIfReady()},countDocs(o,function(e){l=e,storeMetaDocIfReady()}),ht||(ht=checkBlobSupport(o,dt,`key`)),ht.then(function(e){u=e,completeSetup()}),o.oncomplete=function(){s=!0,completeSetup()},o.onabort=idbError(n)},s.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(He,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 i=0,a=0,o=0,s=e.length,c;function runNext(){i++,e[a++]().then(onSuccess,onError)}function doNext(){++o===s?c?r(c):n():runNextBatch()}function onSuccess(){i--,doNext()}function onError(e){i--,c=c||e,doNext()}function runNextBatch(){for(;i<t&&a<s;)runNext()}runNextBatch()})}var _t=25,vt=50,yt=5e3,bt=1e4,xt={};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,i=t.indexOf(`edge`)!==-1,a=!(`method`in e)||e.method===`GET`;return(n||r||i)&&a}function HttpPouch(e,t){let n=this,r=getHost(e.name,e),i=genDBUrl(r,``);e=clone$1(e);let ourFetch=async function(t,n){if(n=n||{},n.headers=n.headers||new L,n.credentials=`include`,e.auth||r.auth){let t=e.auth||r.auth,i=t.username+`:`+t.password,a=thisBtoa(unescape(encodeURIComponent(i)));n.headers.set(`Authorization`,`Basic `+a)}let i=e.headers||{};return Object.keys(i).forEach(function(e){n.headers.append(e,i[e])}),shouldCacheBust(n)&&(t+=(t.indexOf(`?`)===-1?`?`:`&`)+`_nonce=`+Date.now()),await(e.fetch||et)(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 L,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 a;async function setup(){return e.skip_setup?Promise.resolve():a||(a=fetchJSON(i).catch(function(e){return e&&e.status&&e.status===404?(explainError(404,`PouchDB is just detecting if the remote exists.`),fetchJSON(i,{method:`PUT`})):Promise.reject(e)}).catch(function(e){return e&&e.status&&e.status===412?!0:Promise.reject(e)}),a.catch(function(){a=null}),a)}N(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 i=await fetchJSON(genDBUrl(r,`_bulk_get`+paramsToStr(n)),{method:`POST`,body:JSON.stringify({docs:e.docs})});e.attachments&&e.binary&&i.data.results.forEach(function(e){e.docs.forEach(readAttachmentsAsBlobOrBuffer)}),t(null,i.data)}catch(e){t(e)}}function doBulkGetShim(){let r=vt,i=Math.ceil(e.docs.length/r),a=0,o=Array(i);function onResult(e){return function(n,r){o[e]=r.results,++a===i&&t(null,{results:o.flat()})}}for(let t=0;t<i;t++){let i=pick$1(e,[`revs`,`attachments`,`binary`,`latest`]);i.docs=e.docs.slice(t*r,Math.min(e.docs.length,(t+1)*r)),bulkGet(n,i,onResult(t))}}let i=genUrl(r,``),a=xt[i];typeof a==`boolean`?a?doBulkGet(t):doBulkGetShim():doBulkGet(function(e,n){e?(xt[i]=!1,explainError(e.status,`PouchDB is just detecting if the remote supports the _bulk_get API.`),doBulkGetShim()):(xt[i]=!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 i={};t.revs&&(i.revs=!0),t.revs_info&&(i.revs_info=!0),t.latest&&(i.latest=!0),t.open_revs&&(t.open_revs!==`all`&&(t.open_revs=JSON.stringify(t.open_revs)),i.open_revs=t.open_revs),t.rev&&(i.rev=t.rev),t.conflicts&&(i.conflicts=t.conflicts),t.update_seq&&(i.update_seq=t.update_seq),e=encodeDocId(e);function fetchAttachments(e){let n=e._attachments,i=n&&Object.keys(n);if(!n||!i.length)return;async function fetchData(i){let a=n[i],o=await ourFetch(genDBUrl(r,encodeDocId(e._id)+`/`+encodeAttachmentId(i)+`?rev=`+e._rev)),s;s=`buffer`in o?await o.buffer():await o.blob();let c;if(t.binary){let e=Object.getOwnPropertyDescriptor(s.__proto__,`type`);(!e||e.set)&&(s.type=a.content_type),c=s}else c=await new Promise(function(e){blobToBase64(s,e)});delete a.stub,delete a.length,a.data=c}return pool(i.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 a=genDBUrl(r,e+paramsToStr(i));try{let e=await fetchJSON(a);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,i){let a;typeof t==`string`?(a={_id:e,_rev:t},typeof n==`function`&&(i=n,n={})):(a=e,typeof t==`function`?(i=t,n={}):(i=n,n=t));let o=a._rev||n.rev,s=genDBUrl(r,encodeDocId(a._id))+`?rev=`+o;try{let e=await fetchJSON(s,{method:`DELETE`});i(null,e.data)}catch(e){i(e)}});function encodeAttachmentId(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}n.getAttachment=adapterFun$$1(`getAttachment`,async function(e,t,n,i){typeof n==`function`&&(i=n,n={});let a=n.rev?`?rev=`+n.rev:``,o=genDBUrl(r,encodeDocId(e))+`/`+encodeAttachmentId(t)+a;try{let e=await ourFetch(o,{method:`GET`});if(!e.ok)throw e;e.headers.get(`content-type`);let t;t=await e.blob(),i(null,t)}catch(e){i(e)}}),n.removeAttachment=adapterFun$$1(`removeAttachment`,async function(e,t,n,i){let a=genDBUrl(r,encodeDocId(e)+`/`+encodeAttachmentId(t))+`?rev=`+n;try{i(null,(await fetchJSON(a,{method:`DELETE`})).data)}catch(e){i(e)}}),n.putAttachment=adapterFun$$1(`putAttachment`,async function(e,t,n,i,a,o){typeof a==`function`&&(o=a,a=i,i=n,n=null);let s=genDBUrl(r,encodeDocId(e)+`/`+encodeAttachmentId(t));if(n&&(s+=`?rev=`+n),typeof i==`string`){let e;try{e=Ye(i)}catch{return o(createError$1(Le,`Attachment is not a valid base64 string`))}i=e?binStringToBluffer$1(e,a):``}try{let e=await fetchJSON(s,{headers:new L({"Content-Type":a}),method:`PUT`,body:i});o(null,e.data)}catch(e){o(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={},i,a=`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 o=paramsToStr(n);e.keys!==void 0&&(a=`POST`,i={keys:e.keys});try{let n=await fetchJSON(genDBUrl(r,`_all_docs`+o),{method:a,body:JSON.stringify(i)});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:_t;e=clone$1(e),e.continuous&&!(`heartbeat`in e)&&(e.heartbeat=bt);let n=`timeout`in e?e.timeout:30*1e3;`timeout`in e&&e.timeout&&n-e.timeout<yt&&(n=e.timeout+yt),`heartbeat`in e&&e.heartbeat&&n-e.heartbeat<yt&&(n=e.heartbeat+yt);let i={};`timeout`in e&&e.timeout&&(i.timeout=e.timeout);let a=e.limit===void 0?!1:e.limit,o=a;if(e.style&&(i.style=e.style),(e.include_docs||e.filter&&typeof e.filter==`function`)&&(i.include_docs=!0),e.attachments&&(i.attachments=!0),e.continuous&&(i.feed=`longpoll`),e.seq_interval&&(i.seq_interval=e.seq_interval),e.conflicts&&(i.conflicts=!0),e.descending&&(i.descending=!0),e.update_seq&&(i.update_seq=!0),`heartbeat`in e&&e.heartbeat&&(i.heartbeat=e.heartbeat),e.filter&&typeof e.filter==`string`&&(i.filter=e.filter),e.view&&typeof e.view==`string`&&(i.filter=`_view`,i.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)&&(i[t]=e.query_params[t]);let s=`GET`,c;e.doc_ids?(i.filter=`_doc_ids`,s=`POST`,c={doc_ids:e.doc_ids}):e.selector&&(i.filter=`_selector`,s=`POST`,c={selector:e.selector});let l=new AbortController,u,fetchData=async function(n,d){if(e.aborted)return;i.since=n,typeof i.since==`object`&&(i.since=JSON.stringify(i.since)),e.descending?a&&(i.limit=o):i.limit=!a||o>t?t:o;let p=genDBUrl(r,`_changes`+paramsToStr(i)),m={signal:l.signal,method:s,body:JSON.stringify(c)};if(u=n,!e.aborted)try{await setup(),d(null,(await fetchJSON(p,m)).data)}catch(e){d(e)}},d={results:[]},fetched=function(n,r){if(e.aborted)return;let i=0;if(r&&r.results){i=r.results.length,d.last_seq=r.last_seq;let t=null,n=null;typeof r.pending==`number`&&(t=r.pending),(typeof d.last_seq==`string`||typeof d.last_seq==`number`)&&(n=d.last_seq);let a={};a.query=e.query_params,r.results=r.results.filter(function(r){o--;let i=filterChange(e)(r);return i&&(e.include_docs&&e.attachments&&e.binary&&readAttachmentsAsBlobOrBuffer(r),e.return_docs&&d.results.push(r),e.onChange(r,t,n)),i})}else if(n){e.aborted=!0,e.complete(n);return}r&&r.last_seq&&(u=r.last_seq);let s=a&&o<=0||r&&i<t||e.descending;e.continuous&&!(a&&o<=0)||!s?N(function(){fetchData(u,fetched)}):e.complete(null,d)};return fetchData(e.since||0,fetched),{cancel:function(){e.aborted=!0,l.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 St=class QueryParseError$1 extends Error{static{e(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{}}},Ct=class NotFoundError$1 extends Error{static{e(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{}}},wt=class BuiltInError$1 extends Error{static{e(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){N(function(){t(null,e)})},function(e){N(function(){t(e)})}),e}e(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}}e(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})})}e(fin$1,`fin`);function sequentialize$1(e,t){return function(){var n=arguments,r=this;return e.add(function(){return t.apply(r,n)})}}e(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}e(uniq$2,`uniq`);function mapToKeysArray$1(e){var t=Array(e.size),n=-1;return e.forEach(function(e,r){t[++n]=r}),t}e(mapToKeysArray$1,`mapToKeysArray`);function createBuiltInError(e){return new wt(`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 i=e[n];if(typeof i!=`number`)if(Array.isArray(i)){t=typeof t==`number`?[t]:t;for(var a=0,o=i.length;a<o;a++){var s=i[a];if(typeof s!=`number`)throw createBuiltInError(`_sum`);t[a]===void 0?t.push(s):t[a]+=s}}else throw createBuiltInError(`_sum`);else typeof t==`number`?t+=i:t[0]+=i}return t}var Tt=guardedConsole$1.bind(null,`log`),Et=Array.isArray,Dt=JSON.parse;function evalFunctionWithEval(e,t){return scopeEval(`return (`+e.replace(/;\s*$/,``)+`);`,{emit:t,sum,log:Tt,isArray:Et,toJSON:Dt})}var TaskQueue$1$1=class{static{e(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)}}e(stringify$1,`stringify`);function createViewSignature$1(e,t){return stringify$1(e)+stringify$1(t)+`undefined`}e(createViewSignature$1,`createViewSignature`);async function createView$1(e,t,n,r,i,a){let o=createViewSignature$1(n,r),s;if(!i&&(s=e._cachedViews=e._cachedViews||{},s[o]))return s[o];let c=e.info().then(async function(c){let l=c.db_name+`-mrview-`+(i?`temp`:stringMd5$1(o));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[l])return r[l]=!0,e}await upsert$1(e,`_local/`+a,diffFunction);let u=(await e.registerDependentDatabase(l)).db;u.auto_compaction=!0;let d={name:l,db:u,sourceDB:e,adapter:e.adapter,mapFun:n,reduceFun:r},p;try{p=await d.db.get(`_local/lastSeq`)}catch(e){if(e.status!==404)throw e}return d.seq=p?p.seq:0,s&&d.db.once(`destroyed`,function(){delete s[o]}),d});return s&&(s[o]=c),c}e(createView$1,`createView`);var Ot={},kt=new TaskQueue$1$1,At=50;function parseViewName$1(e){return e.indexOf(`/`)===-1?[e,e]:e.split(`/`)}e(parseViewName$1,`parseViewName`);function isGenOne$1(e){return e.length===1&&/^1-/.test(e[0].rev)}e(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.
5
+ You can debug this error by doing:
6
+ myDatabase.on('error', function (err) { debugger; });
7
+ Please double-check your map/reduce function.`),guardedConsole$1(`error`,t,n)}}e(emitError$1,`emitError`);function createAbstractMapReduce$1(e,t,n,r){function tryMap(e,t,n){try{t(n)}catch(r){emitError$1(e,r,{fun:t,doc:n})}}function tryReduce(e,t,n,r,i){try{return{output:t(n,r,i)}}catch(a){return emitError$1(e,a,{fun:t,keys:n,values:r,rereduce:i}),{error:a}}}function sortByKeyThenValue(e,t){let n=collate$1(e.key,t.key);return n===0?collate$1(e.value,t.value):n}function sliceResults(e,t,n){return n=n||0,typeof t==`number`?e.slice(n,t+n):n>0?e.slice(n):e}function rowToDocId(e){let t=e.value;return t&&typeof t==`object`&&t._id||e.id}function readAttachmentsAsBlobOrBuffer(e){for(let t of e.rows){let e=t.doc&&t.doc._attachments;if(e)for(let t of Object.keys(e)){let n=e[t];e[t].data=b64ToBluffer$1(n.data,n.content_type)}}}function postprocessAttachments(e){return function(t){return e.include_docs&&e.attachments&&e.binary&&readAttachmentsAsBlobOrBuffer(t),t}}function addHttpParam(e,t,n,r){let i=t[e];i!==void 0&&(r&&(i=encodeURIComponent(JSON.stringify(i))),n.push(e+`=`+i))}function coerceInteger(e){if(e!==void 0){let t=Number(e);return!isNaN(t)&&t===parseInt(e,10)?t:e}}function coerceOptions(e){return e.group_level=coerceInteger(e.group_level),e.limit=coerceInteger(e.limit),e.skip=coerceInteger(e.skip),e}function checkPositiveInteger(e){if(e){if(typeof e!=`number`)return new St(`Invalid value for integer: "${e}"`);if(e<0)return new St(`Invalid value for positive integer: "${e}"`)}}function checkQueryParseError(e,t){let n=e.descending?`endkey`:`startkey`,r=e.descending?`startkey`:`endkey`;if(e[n]!==void 0&&e[r]!==void 0&&collate$1(e[n],e[r])>0)throw new St(`No rows can match your key range, reverse your start_key and end_key or set {descending : true}`);if(t.reduce&&e.reduce!==!1){if(e.include_docs)throw new St(`{include_docs:true} is invalid for reduce`);if(e.keys&&e.keys.length>1&&!e.group&&!e.group_level)throw new St(`Multi-key fetches for reduce views must use {group: true}`)}for(let t of[`group_level`,`limit`,`skip`]){let n=checkPositiveInteger(e[t]);if(n)throw n}}async function httpQuery(e,t,n){let r=[],i,a=`GET`,o;if(addHttpParam(`reduce`,n,r),addHttpParam(`include_docs`,n,r),addHttpParam(`attachments`,n,r),addHttpParam(`limit`,n,r),addHttpParam(`descending`,n,r),addHttpParam(`group`,n,r),addHttpParam(`group_level`,n,r),addHttpParam(`skip`,n,r),addHttpParam(`stale`,n,r),addHttpParam(`conflicts`,n,r),addHttpParam(`startkey`,n,r,!0),addHttpParam(`start_key`,n,r,!0),addHttpParam(`endkey`,n,r,!0),addHttpParam(`end_key`,n,r,!0),addHttpParam(`inclusive_end`,n,r),addHttpParam(`key`,n,r,!0),addHttpParam(`update_seq`,n,r),r=r.join(`&`),r=r===``?``:`?`+r,n.keys!==void 0){let e=`keys=${encodeURIComponent(JSON.stringify(n.keys))}`;e.length+r.length+1<=2e3?r+=(r[0]===`?`?`&`:`?`)+e:(a=`POST`,typeof t==`string`?i={keys:n.keys}:t.keys=n.keys)}if(typeof t==`string`){let s=parseViewName$1(t),c=await e.fetch(`_design/`+s[0]+`/_view/`+s[1]+r,{headers:new L({"Content-Type":`application/json`}),method:a,body:JSON.stringify(i)});o=c.ok;let l=await c.json();if(!o)throw l.status=c.status,generateErrorFromResponse$1(l);for(let e of l.rows)if(e.value&&e.value.error&&e.value.error===`builtin_reduce_error`)throw Error(e.reason);return new Promise(function(e){e(l)}).then(postprocessAttachments(n))}i=i||{};for(let e of Object.keys(t))Array.isArray(t[e])?i[e]=t[e]:i[e]=t[e].toString();let s=await e.fetch(`_temp_view`+r,{headers:new L({"Content-Type":`application/json`}),method:`POST`,body:JSON.stringify(i)});o=s.ok;let c=await s.json();if(!o)throw c.status=s.status,generateErrorFromResponse$1(c);return new Promise(function(e){e(c)}).then(postprocessAttachments(n))}function customQuery(e,t,n){return new Promise(function(r,i){e._query(t,n,function(e,t){if(e)return i(e);r(t)})})}function customViewCleanup(e){return new Promise(function(t,n){e._viewCleanup(function(e,r){if(e)return n(e);t(r)})})}function defaultsTo(e){return function(t){if(t.status===404)return e;throw t}}async function getDocsToPersist(e,t,n){let r=`_local/doc_`+e,i={_id:r,keys:[]},a=n.get(e),o=a[0],s=a[1];function getMetaDoc(){return isGenOne$1(s)?Promise.resolve(i):t.db.get(r).catch(defaultsTo(i))}function getKeyValueDocs(e){return e.keys.length?t.db.allDocs({keys:e.keys,include_docs:!0}):Promise.resolve({rows:[]})}function processKeyValueDocs(e,t){let n=[],r=new Set;for(let e of t.rows){let t=e.doc;if(t&&(n.push(t),r.add(t._id),t._deleted=!o.has(t._id),!t._deleted)){let e=o.get(t._id);`value`in e&&(t.value=e.value)}}let i=mapToKeysArray$1(o);for(let e of i)if(!r.has(e)){let t={_id:e},r=o.get(e);`value`in r&&(t.value=r.value),n.push(t)}return e.keys=uniq$2(i.concat(e.keys)),n.push(e),n}let c=await getMetaDoc();return processKeyValueDocs(c,await getKeyValueDocs(c))}function updatePurgeSeq(e){return e.sourceDB.get(`_local/purges`).then(function(t){let n=t.purgeSeq;return e.db.get(`_local/purgeSeq`).then(function(e){return e._rev}).catch(defaultsTo(void 0)).then(function(t){return e.db.put({_id:`_local/purgeSeq`,_rev:t,purgeSeq:n})})}).catch(function(e){if(e.status!==404)throw e})}function saveKeyValues(e,t,n){var r=`_local/lastSeq`;return e.db.get(r).catch(defaultsTo({_id:r,seq:0})).then(function(r){var i=mapToKeysArray$1(t);return Promise.all(i.map(function(n){return getDocsToPersist(n,e,t)})).then(function(t){var i=t.flat();return r.seq=n,i.push(r),e.db.bulkDocs({docs:i})}).then(()=>updatePurgeSeq(e))})}function getQueue(e){let t=typeof e==`string`?e:e.name,n=Ot[t];return n||(n=Ot[t]=new TaskQueue$1$1),n}async function updateView(e,t){return sequentialize$1(getQueue(e),function(){return updateViewInQueue(e,t)})()}async function updateViewInQueue(e,n){let r,i,a;function emit(e,t){let n={id:i._id,key:normalizeKey$1(e)};t!=null&&(n.value=normalizeKey$1(t)),r.push(n)}let o=t(e.mapFun,emit),s=e.seq||0;function createTask(){return e.sourceDB.info().then(function(t){a=e.sourceDB.activeTasks.add({name:`view_indexing`,total_items:t.update_seq-s})})}function processChange(t,n){return function(){return saveKeyValues(e,t,n)}}let c=0,l={view:e.name,indexed_docs:c};e.sourceDB.emit(`indexing`,l);let u=new TaskQueue$1$1;async function processNextBatch(){return processBatch(await e.sourceDB.changes({return_docs:!0,conflicts:!0,include_docs:!0,style:`all_docs`,since:s,limit:n.changes_batch_size}),await getRecentPurges())}function getRecentPurges(){return e.db.get(`_local/purgeSeq`).then(function(e){return e.purgeSeq}).catch(defaultsTo(-1)).then(function(t){return e.sourceDB.get(`_local/purges`).then(function(n){let r=n.purges.filter(function(e,n){return n>t}).map(e=>e.docId),i=r.filter(function(e,t){return r.indexOf(e)===t});return Promise.all(i.map(function(t){return e.sourceDB.get(t).then(function(e){return{docId:t,doc:e}}).catch(defaultsTo({docId:t}))}))}).catch(defaultsTo([]))})}function processBatch(t,r){let i=t.results;if(!i.length&&!r.length)return;for(let e of r)if(i.findIndex(function(t){return t.id===e.docId})<0){let t={_id:e.docId,doc:{_id:e.docId,_deleted:1},changes:[]};e.doc&&(t.doc=e.doc,t.changes.push({rev:e.doc._rev})),i.push(t)}let o=createDocIdsToChangesAndEmits(i);u.add(processChange(o,s)),c+=i.length;let l={view:e.name,last_seq:t.last_seq,results_count:i.length,indexed_docs:c};if(e.sourceDB.emit(`indexing`,l),e.sourceDB.activeTasks.update(a,{completed_items:c}),!(i.length<n.changes_batch_size))return processNextBatch()}function createDocIdsToChangesAndEmits(t){let n=new Map;for(let a of t){if(a.doc._id[0]!==`_`){r=[],i=a.doc,i._deleted||tryMap(e.sourceDB,o,i),r.sort(sortByKeyThenValue);let t=createIndexableKeysToKeyValues(r);n.set(a.doc._id,[t,a.changes])}s=a.seq}return n}function createIndexableKeysToKeyValues(e){let t=new Map,n;for(let r=0,i=e.length;r<i;r++){let i=e[r],a=[i.key,i.id];r>0&&collate$1(i.key,n)===0&&a.push(r),t.set(toIndexableString$1(a),i),n=i.key}return t}try{await createTask(),await processNextBatch(),await u.finish(),e.seq=s,e.sourceDB.activeTasks.remove(a)}catch(t){e.sourceDB.activeTasks.remove(a,t)}}function reduceView(e,t,r){r.group_level===0&&delete r.group_level;let i=r.group||r.group_level,a=n(e.reduceFun),o=[],s=isNaN(r.group_level)?1/0:r.group_level;for(let e of t){let t=o[o.length-1],n=i?e.key:null;if(i&&Array.isArray(n)&&(n=n.slice(0,s)),t&&collate$1(t.groupKey,n)===0){t.keys.push([e.key,e.id]),t.values.push(e.value);continue}o.push({keys:[[e.key,e.id]],values:[e.value],groupKey:n})}t=[];for(let n of o){let r=tryReduce(e.sourceDB,a,n.keys,n.values,!1);if(r.error&&r.error instanceof wt)throw r.error;t.push({value:r.error?null:r.output,key:n.groupKey})}return{rows:sliceResults(t,r.limit,r.skip)}}function queryView(e,t){return sequentialize$1(getQueue(e),function(){return queryViewInQueue(e,t)})()}async function queryViewInQueue(e,t){let n,r=e.reduceFun&&t.reduce!==!1,i=t.skip||0;t.keys!==void 0&&!t.keys.length&&(t.limit=0,delete t.keys);async function fetchFromView(t){t.include_docs=!0;let r=await e.db.allDocs(t);return n=r.total_rows,r.rows.map(function(e){if(`value`in e.doc&&typeof e.doc.value==`object`&&e.doc.value!==null){let t=Object.keys(e.doc.value).sort(),n=[`id`,`key`,`value`];if(!(t<n||t>n))return e.doc.value}let t=parseIndexableString$1(e.doc._id);return{key:t[0],id:t[1],value:`value`in e.doc?e.doc.value:null}})}async function onMapResultsReady(a){let o;if(o=r?reduceView(e,a,t):t.keys===void 0?{total_rows:n,offset:i,rows:a}:{total_rows:n,offset:i,rows:sliceResults(a,t.limit,t.skip)},t.update_seq&&(o.update_seq=e.seq),t.include_docs){let n=uniq$2(a.map(rowToDocId)),r=await e.sourceDB.allDocs({keys:n,include_docs:!0,conflicts:t.conflicts,attachments:t.attachments,binary:t.binary}),i=new Map;for(let e of r.rows)i.set(e.id,e.doc);for(let e of a){let t=rowToDocId(e),n=i.get(t);n&&(e.doc=n)}}return o}if(t.keys!==void 0){let e=t.keys.map(function(e){let n={startkey:toIndexableString$1([e]),endkey:toIndexableString$1([e,{}])};return t.update_seq&&(n.update_seq=!0),fetchFromView(n)});return onMapResultsReady((await Promise.all(e)).flat())}else{let e={descending:t.descending};t.update_seq&&(e.update_seq=!0);let n,a;if(`start_key`in t&&(n=t.start_key),`startkey`in t&&(n=t.startkey),`end_key`in t&&(a=t.end_key),`endkey`in t&&(a=t.endkey),n!==void 0&&(e.startkey=t.descending?toIndexableString$1([n,{}]):toIndexableString$1([n])),a!==void 0){let n=t.inclusive_end!==!1;t.descending&&(n=!n),e.endkey=toIndexableString$1(n?[a,{}]:[a])}if(t.key!==void 0){let n=toIndexableString$1([t.key]),r=toIndexableString$1([t.key,{}]);e.descending?(e.endkey=n,e.startkey=r):(e.startkey=n,e.endkey=r)}return r||(typeof t.limit==`number`&&(e.limit=t.limit),e.skip=i),onMapResultsReady(await fetchFromView(e))}}async function httpViewCleanup(e){return(await e.fetch(`_view_cleanup`,{headers:new L({"Content-Type":`application/json`}),method:`POST`})).json()}async function localViewCleanup(t){try{let n=await t.get(`_local/`+e),r=new Map;for(let e of Object.keys(n.views)){let t=parseViewName$1(e),n=`_design/`+t[0],i=t[1],a=r.get(n);a||(a=new Set,r.set(n,a)),a.add(i)}let i={keys:mapToKeysArray$1(r),include_docs:!0},a=await t.allDocs(i),o={};for(let e of a.rows){let t=e.key.substring(8);for(let i of r.get(e.key)){let r=t+`/`+i;n.views[r]||(r=i);let a=Object.keys(n.views[r]),s=e.doc&&e.doc.views&&e.doc.views[i];for(let e of a)o[e]=o[e]||s}}let s=Object.keys(o).filter(function(e){return!o[e]}).map(function(e){return sequentialize$1(getQueue(e),function(){return new t.constructor(e,t.__opts).destroy()})()});return Promise.all(s).then(function(){return{ok:!0}})}catch(e){if(e.status===404)return{ok:!0};throw e}}async function queryPromised(t,n,i){if(typeof t._query==`function`)return customQuery(t,n,i);if(isRemote$1(t))return httpQuery(t,n,i);let a={changes_batch_size:t.__opts.view_update_changes_batch_size||At};if(typeof n!=`string`)return checkQueryParseError(i,n),kt.add(async function(){let r=await createView$1(t,`temp_view/temp_view`,n.map,n.reduce,!0,e);return fin$1(updateView(r,a).then(function(){return queryView(r,i)}),function(){return r.db.destroy()})}),kt.finish();{let o=n,s=parseViewName$1(o),c=s[0],l=s[1],u=await t.get(`_design/`+c);if(n=u.views&&u.views[l],!n)throw new Ct(`ddoc ${u._id} has no view named ${l}`);r(u,l),checkQueryParseError(i,n);let d=await createView$1(t,o,n.map,n.reduce,!1,e);return i.stale===`ok`||i.stale===`update_after`?(i.stale===`update_after`&&N(function(){updateView(d,a)}),queryView(d,i)):(await updateView(d,a),queryView(d,i))}}function abstractQuery(e,t,n){let r=this;typeof t==`function`&&(n=t,t={}),t=t?coerceOptions(t):{},typeof e==`function`&&(e={map:e});let i=Promise.resolve().then(function(){return queryPromised(r,e,t)});return promisedCallback$1(i,n),i}return{query:abstractQuery,viewCleanup:callbackify$1(function(){let e=this;return typeof e._viewCleanup==`function`?customViewCleanup(e):isRemote$1(e)?httpViewCleanup(e):localViewCleanup(e)})}}e(createAbstractMapReduce$1,`createAbstractMapReduce`);var jt={_sum:function(e,t){return sum(t)},_count:function(e,t){return t.length},_stats:function(e,t){function sumsqr(e){for(var t=0,n=0,r=e.length;n<r;n++){var i=e[n];t+=i*i}return t}return{sum:sum(t),min:Math.min.apply(null,t),max:Math.max.apply(null,t),count:t.length,sumsqr:sumsqr(t)}}};function getBuiltIn(e){if(/^_sum/.test(e))return jt._sum;if(/^_count/.test(e))return jt._count;if(/^_stats/.test(e))return jt._stats;if(/^_/.test(e))throw Error(e+` is not a supported reduce function.`)}function mapper$1(e,t){if(typeof e==`function`&&e.length===2){var n=e;return function(e){return n(e,t)}}else return evalFunctionWithEval(e.toString(),t)}e(mapper$1,`mapper`);function reducer$1(e){var t=e.toString();return getBuiltIn(t)||evalFunctionWithEval(t)}e(reducer$1,`reducer`);function ddocValidator$1(e,t){var n=e.views&&e.views[t];if(typeof n.map!=`string`)throw new Ct(`ddoc `+e._id+` has no string view named `+t+`, instead found object of type: `+typeof n.map)}e(ddocValidator$1,`ddocValidator`);var Mt=createAbstractMapReduce$1(`mrviews`,mapper$1,reducer$1,ddocValidator$1);function query(e,t,n){return Mt.query.call(this,e,t,n)}function viewCleanup(e){return Mt.viewCleanup.call(this,e)}var Nt={query,viewCleanup};function fileHasChanged(e,t,n){return!e._attachments||!e._attachments[n]||e._attachments[n].digest!==t._attachments[n].digest}function getDocAttachments(e,t){var n=Object.keys(t._attachments);return Promise.all(n.map(function(n){return e.getAttachment(t._id,n,{rev:t._rev})}))}function getDocAttachmentsFromTargetOrSource(e,t,n){var r=isRemote$1(t)&&!isRemote$1(e),i=Object.keys(n._attachments);return r?e.get(n._id).then(function(r){return Promise.all(i.map(function(i){return fileHasChanged(r,n,i)?t.getAttachment(n._id,i):e.getAttachment(r._id,i)}))}).catch(function(e){if(e.status!==404)throw e;return getDocAttachments(t,n)}):getDocAttachments(t,n)}function createBulkGetOpts(e){var t=[];return Object.keys(e).forEach(function(n){e[n].missing.forEach(function(e){t.push({id:n,rev:e})})}),{docs:t,revs:!0,latest:!0}}function getDocs(e,t,n,r){n=clone$1(n);var i=[],a=!0;function getAllDocs(){var o=createBulkGetOpts(n);if(o.docs.length)return e.bulkGet(o).then(function(n){if(r.cancelled)throw Error(`cancelled`);return Promise.all(n.results.map(function(n){return Promise.all(n.docs.map(function(n){var r=n.ok;return n.error&&(a=!1),!r||!r._attachments?r:getDocAttachmentsFromTargetOrSource(t,e,r).then(e=>{var t=Object.keys(r._attachments);return e.forEach(function(e,n){var i=r._attachments[t[n]];delete i.stub,delete i.length,i.data=e}),r})}))})).then(function(e){i=i.concat(e.flat().filter(Boolean))})})}function returnResult(){return{ok:a,docs:i}}return Promise.resolve().then(getAllDocs).then(returnResult)}var Pt=1,Ft=`pouchdb`,It=5,G=0;function updateCheckpoint(e,t,n,r,i){return e.get(t).catch(function(n){if(n.status===404)return(e.adapter===`http`||e.adapter===`https`)&&explainError(404,`PouchDB is just checking if a remote checkpoint exists.`),{session_id:r,_id:t,history:[],replicator:Ft,version:Pt};throw n}).then(function(a){if(!i.cancelled&&a.last_seq!==n)return a.history=(a.history||[]).filter(function(e){return e.session_id!==r}),a.history.unshift({last_seq:n,session_id:r}),a.history=a.history.slice(0,It),a.version=Pt,a.replicator=Ft,a.session_id=r,a.last_seq=n,e.put(a).catch(function(a){if(a.status===409)return updateCheckpoint(e,t,n,r,i);throw a})})}var CheckpointerInternal=class{constructor(e,t,n,r,i={writeSourceCheckpoint:!0,writeTargetCheckpoint:!0}){this.src=e,this.target=t,this.id=n,this.returnValue=r,this.opts=i,i.writeSourceCheckpoint===void 0&&(i.writeSourceCheckpoint=!0),i.writeTargetCheckpoint===void 0&&(i.writeTargetCheckpoint=!0)}writeCheckpoint(e,t){var n=this;return this.updateTarget(e,t).then(function(){return n.updateSource(e,t)})}updateTarget(e,t){return this.opts.writeTargetCheckpoint?updateCheckpoint(this.target,this.id,e,t,this.returnValue):Promise.resolve(!0)}updateSource(e,t){if(this.opts.writeSourceCheckpoint){var n=this;return updateCheckpoint(this.src,this.id,e,t,this.returnValue).catch(function(e){if(isForbiddenError(e))return n.opts.writeSourceCheckpoint=!1,!0;throw e})}else return Promise.resolve(!0)}getCheckpoint(){var e=this;return!e.opts.writeSourceCheckpoint&&!e.opts.writeTargetCheckpoint?Promise.resolve(G):e.opts&&e.opts.writeSourceCheckpoint&&!e.opts.writeTargetCheckpoint?e.src.get(e.id).then(function(e){return e.last_seq||G}).catch(function(e){if(e.status!==404)throw e;return G}):e.target.get(e.id).then(function(t){return e.opts&&e.opts.writeTargetCheckpoint&&!e.opts.writeSourceCheckpoint?t.last_seq||G:e.src.get(e.id).then(function(e){if(t.version!==e.version)return G;var n=t.version?t.version.toString():`undefined`;return n in Lt?Lt[n](t,e):G},function(n){if(n.status===404&&t.last_seq)return e.src.put({_id:e.id,last_seq:G}).then(function(){return G},function(n){return isForbiddenError(n)?(e.opts.writeSourceCheckpoint=!1,t.last_seq):G});throw n})}).catch(function(e){if(e.status!==404)throw e;return G})}},Lt={undefined:function(e,t){return collate$1(e.last_seq,t.last_seq)===0?t.last_seq:0},1:function(e,t){return compareReplicationLogs(t,e).last_seq}};function compareReplicationLogs(e,t){return e.session_id===t.session_id?{last_seq:e.last_seq,history:e.history}:compareReplicationHistory(e.history,t.history)}function compareReplicationHistory(e,t){var n=e[0],r=e.slice(1),i=t[0],a=t.slice(1);if(!n||t.length===0)return{last_seq:G,history:[]};var o=n.session_id;if(hasSessionId(o,t))return{last_seq:n.last_seq,history:e};var s=i.session_id;return hasSessionId(s,r)?{last_seq:i.last_seq,history:a}:compareReplicationHistory(r,a)}function hasSessionId(e,t){var n=t[0],r=t.slice(1);return!e||t.length===0?!1:e===n.session_id?!0:hasSessionId(e,r)}function isForbiddenError(e){return typeof e.status==`number`&&Math.floor(e.status/100)===4}function Checkpointer(e,t,n,r,i){return this instanceof CheckpointerInternal?Checkpointer:new CheckpointerInternal(e,t,n,r,i)}var Rt=0;function backOff(e,t,n,r){if(e.retry===!1){t.emit(`error`,n),t.removeAllListeners();return}if(typeof e.back_off_function!=`function`&&(e.back_off_function=defaultBackOff),t.emit(`requestError`,n),t.state===`active`||t.state===`pending`){t.emit(`paused`,n),t.state=`stopped`;var i=function backoffTimeSet(){e.current_back_off=Rt};t.once(`paused`,function removeBackOffTimeSet(){t.removeListener(`active`,i)}),t.once(`active`,i)}e.current_back_off=e.current_back_off||Rt,e.current_back_off=e.back_off_function(e.current_back_off),setTimeout(r,e.current_back_off)}function sortObjectPropertiesByKey(e){return Object.keys(e).sort(collate$1).reduce(function(t,n){return t[n]=e[n],t},{})}function generateReplicationId(e,t,n){var r=n.doc_ids?n.doc_ids.sort(collate$1):``,i=n.filter?n.filter.toString():``,a=``,o=``,s=``;return n.selector&&(s=JSON.stringify(n.selector)),n.filter&&n.query_params&&(a=JSON.stringify(sortObjectPropertiesByKey(n.query_params))),n.filter&&n.filter===`_view`&&(o=n.view.toString()),Promise.all([e.id(),t.id()]).then(function(e){var t=e[0]+e[1]+i+o+a+r+s;return new Promise(function(e){binaryMd5(t,e)})}).then(function(e){return e=e.replace(/\//g,`.`).replace(/\+/g,`_`),`_local/`+e})}function replicate(e,t,n,r,i){var a=[],o,s={seq:0,changes:[],docs:[]},c=!1,l=!1,u=!1,d=0,p=0,m=n.continuous||n.live||!1,h=n.batch_size||100,g=n.batches_limit||10,_=n.style||`all_docs`,v=!1,y=n.doc_ids,b=n.selector,x,S,C=[],w=Qe(),T;i=i||{ok:!0,start_time:new Date().toISOString(),docs_read:0,docs_written:0,doc_write_failures:0,errors:[]};var E={};r.ready(e,t);function initCheckpointer(){return S?Promise.resolve():generateReplicationId(e,t,n).then(function(i){x=i;var a={};a=n.checkpoint===!1?{writeSourceCheckpoint:!1,writeTargetCheckpoint:!1}:n.checkpoint===`source`?{writeSourceCheckpoint:!0,writeTargetCheckpoint:!1}:n.checkpoint===`target`?{writeSourceCheckpoint:!1,writeTargetCheckpoint:!0}:{writeSourceCheckpoint:!0,writeTargetCheckpoint:!0},S=new Checkpointer(e,t,x,r,a)})}function writeDocs(){if(C=[],o.docs.length!==0){var e=o.docs,a={timeout:n.timeout};return t.bulkDocs({docs:e,new_edits:!1},a).then(function(t){if(r.cancelled)throw completeReplication(),Error(`cancelled`);var n=Object.create(null);t.forEach(function(e){e.error&&(n[e.id]=e)});var a=Object.keys(n).length;i.doc_write_failures+=a,i.docs_written+=e.length-a,e.forEach(function(e){var t=n[e._id];if(t){i.errors.push(t);var a=(t.name||``).toLowerCase();if(a===`unauthorized`||a===`forbidden`)r.emit(`denied`,clone$1(t));else throw t}else C.push(e)})},function(t){throw i.doc_write_failures+=e.length,t})}}function finishBatch(){if(o.error)throw Error(`There was a problem getting docs.`);i.last_seq=p=o.seq;var t=clone$1(i);return C.length&&(t.docs=C,typeof o.pending==`number`&&(t.pending=o.pending,delete o.pending),r.emit(`change`,t)),c=!0,e.info().then(function(t){var n=e.activeTasks.get(T);if(!(!o||!n)){var r=n.completed_items||0,i=parseInt(t.update_seq,10)-parseInt(d,10);e.activeTasks.update(T,{completed_items:r+o.changes.length,total_items:i})}}),S.writeCheckpoint(o.seq,w).then(function(){if(r.emit(`checkpoint`,{checkpoint:o.seq}),c=!1,r.cancelled)throw completeReplication(),Error(`cancelled`);o=void 0,getChanges()}).catch(function(e){throw onCheckpointError(e),e})}function getDiffs(){var e={};return o.changes.forEach(function(t){r.emit(`checkpoint`,{revs_diff:t}),t.id!==`_user/`&&(e[t.id]=t.changes.map(function(e){return e.rev}))}),t.revsDiff(e).then(function(e){if(r.cancelled)throw completeReplication(),Error(`cancelled`);o.diffs=e})}function getBatchDocs(){return getDocs(e,t,o.diffs,r).then(function(e){o.error=!e.ok,e.docs.forEach(function(e){delete o.diffs[e._id],i.docs_read++,o.docs.push(e)})})}function startNextBatch(){if(!(r.cancelled||o)){if(a.length===0){processPendingBatch(!0);return}o=a.shift(),r.emit(`checkpoint`,{start_next_batch:o.seq}),getDiffs().then(getBatchDocs).then(writeDocs).then(finishBatch).then(startNextBatch).catch(function(e){abortReplication(`batch processing terminated with error`,e)})}}function processPendingBatch(e){if(s.changes.length===0){a.length===0&&!o&&((m&&E.live||l)&&(r.state=`pending`,r.emit(`paused`)),l&&completeReplication());return}(e||l||s.changes.length>=h)&&(a.push(s),s={seq:0,changes:[],docs:[]},(r.state===`pending`||r.state===`stopped`)&&(r.state=`active`,r.emit(`active`)),startNextBatch())}function abortReplication(e,t){u||(t.message||(t.message=e),i.ok=!1,i.status=`aborting`,a=[],s={seq:0,changes:[],docs:[]},completeReplication(t))}function completeReplication(a){if(!u&&!(r.cancelled&&(i.status=`cancelled`,c)))if(i.status=i.status||`complete`,i.end_time=new Date().toISOString(),i.last_seq=p,u=!0,e.activeTasks.remove(T,a),a){a=createError$1(a),a.result=i;var o=(a.name||``).toLowerCase();o===`unauthorized`||o===`forbidden`?(r.emit(`error`,a),r.removeAllListeners()):backOff(n,r,a,function(){replicate(e,t,n,r)})}else r.emit(`complete`,i),r.removeAllListeners()}function onChange(t,i,o){if(r.cancelled)return completeReplication();if(typeof i==`number`&&(s.pending=i),!filterChange(n)(t)){var c=e.activeTasks.get(T);if(c){var l=c.completed_items||0;e.activeTasks.update(T,{completed_items:++l})}return}s.seq=t.seq||o,s.changes.push(t),r.emit(`checkpoint`,{pending_batch:s.seq}),N(function(){processPendingBatch(a.length===0&&E.live)})}function onChangesComplete(e){if(v=!1,r.cancelled)return completeReplication();if(e.results.length>0)E.since=e.results[e.results.length-1].seq,getChanges(),processPendingBatch(!0);else{var complete=function(){m?(E.live=!0,getChanges()):l=!0,processPendingBatch(!0)};!o&&e.results.length===0?(c=!0,S.writeCheckpoint(e.last_seq,w).then(function(){if(c=!1,i.last_seq=p=e.last_seq,r.cancelled)throw completeReplication(),Error(`cancelled`);complete()}).catch(onCheckpointError)):complete()}}function onChangesError(e){if(v=!1,r.cancelled)return completeReplication();abortReplication(`changes rejected`,e)}function getChanges(){if(!(!v&&!l&&a.length<g))return;v=!0;function abortChanges(){t.cancel()}function removeListener(){r.removeListener(`cancel`,abortChanges)}r._changes&&(r.removeListener(`cancel`,r._abortChanges),r._changes.cancel()),r.once(`cancel`,abortChanges);var t=e.changes(E).on(`change`,onChange);t.then(removeListener,removeListener),t.then(onChangesComplete).catch(onChangesError),n.retry&&(r._changes=t,r._abortChanges=abortChanges)}function createTask(t){return e.info().then(function(r){var i=n.since===void 0?parseInt(r.update_seq,10)-parseInt(t,10):parseInt(r.update_seq,10);return T=e.activeTasks.add({name:`${m?`continuous `:``}replication from ${r.db_name}`,total_items:i}),t})}function startChanges(){initCheckpointer().then(function(){if(r.cancelled){completeReplication();return}return S.getCheckpoint().then(createTask).then(function(e){p=e,d=e,E={since:p,limit:h,batch_size:h,style:_,doc_ids:y,selector:b,return_docs:!0},n.filter&&(typeof n.filter==`string`?E.filter=n.filter:E.include_docs=!0),`heartbeat`in n&&(E.heartbeat=n.heartbeat),`timeout`in n&&(E.timeout=n.timeout),n.query_params&&(E.query_params=n.query_params),n.view&&(E.view=n.view),getChanges()})}).catch(function(e){abortReplication(`getCheckpoint rejected with `,e)})}function onCheckpointError(e){c=!1,abortReplication(`writeCheckpoint completed with error`,e)}if(r.cancelled){completeReplication();return}r._addedListeners||(r.once(`cancel`,completeReplication),typeof n.complete==`function`&&(r.once(`error`,n.complete),r.once(`complete`,function(e){n.complete(null,e)})),r._addedListeners=!0),n.since===void 0?startChanges():initCheckpointer().then(function(){return c=!0,S.writeCheckpoint(n.since,w)}).then(function(){if(c=!1,r.cancelled){completeReplication();return}p=n.since,startChanges()}).catch(onCheckpointError)}var Replication=class extends M.default{constructor(){super(),this.cancelled=!1,this.state=`pending`;let e=new Promise((e,t)=>{this.once(`complete`,e),this.once(`error`,t)});this.then=function(t,n){return e.then(t,n)},this.catch=function(t){return e.catch(t)},this.catch(function(){})}cancel(){this.cancelled=!0,this.state=`cancelled`,this.emit(`cancel`)}ready(e,t){if(this._readyCalled)return;this._readyCalled=!0;let onDestroy=()=>{this.cancel()};e.once(`destroyed`,onDestroy),t.once(`destroyed`,onDestroy);function cleanup(){e.removeListener(`destroyed`,onDestroy),t.removeListener(`destroyed`,onDestroy)}this.once(`complete`,cleanup),this.once(`error`,cleanup)}};function toPouch(e,t){var n=t.PouchConstructor;return typeof e==`string`?new n(e,t):e}function replicateWrapper(e,t,n,r){if(typeof n==`function`&&(r=n,n={}),n===void 0&&(n={}),n.doc_ids&&!Array.isArray(n.doc_ids))throw createError$1(Be,"`doc_ids` filter parameter is not a list.");n.complete=r,n=clone$1(n),n.continuous=n.continuous||n.live,n.retry=`retry`in n?n.retry:!1,n.PouchConstructor=n.PouchConstructor||this;var i=new Replication(n);return replicate(toPouch(e,n),toPouch(t,n),n,i),i}function sync(e,t,n,r){return typeof n==`function`&&(r=n,n={}),n===void 0&&(n={}),n=clone$1(n),n.PouchConstructor=n.PouchConstructor||this,e=toPouch(e,n),t=toPouch(t,n),new Sync(e,t,n,r)}var Sync=class extends M.default{constructor(e,t,n,r){super(),this.canceled=!1;let i=n.push?Object.assign({},n,n.push):n,a=n.pull?Object.assign({},n,n.pull):n;this.push=replicateWrapper(e,t,i),this.pull=replicateWrapper(t,e,a),this.pushPaused=!0,this.pullPaused=!0;let pullChange=e=>{this.emit(`change`,{direction:`pull`,change:e})},pushChange=e=>{this.emit(`change`,{direction:`push`,change:e})},pushDenied=e=>{this.emit(`denied`,{direction:`push`,doc:e})},pullDenied=e=>{this.emit(`denied`,{direction:`pull`,doc:e})},pushPaused=()=>{this.pushPaused=!0,this.pullPaused&&this.emit(`paused`)},pullPaused=()=>{this.pullPaused=!0,this.pushPaused&&this.emit(`paused`)},pushActive=()=>{this.pushPaused=!1,this.pullPaused&&this.emit(`active`,{direction:`push`})},pullActive=()=>{this.pullPaused=!1,this.pushPaused&&this.emit(`active`,{direction:`pull`})},o={},removeAll=e=>(t,n)=>{(t===`change`&&(n===pullChange||n===pushChange)||t===`denied`&&(n===pullDenied||n===pushDenied)||t===`paused`&&(n===pullPaused||n===pushPaused)||t===`active`&&(n===pullActive||n===pushActive))&&(t in o||(o[t]={}),o[t][e]=!0,Object.keys(o[t]).length===2&&this.removeAllListeners(t))};n.live&&(this.push.on(`complete`,this.pull.cancel.bind(this.pull)),this.pull.on(`complete`,this.push.cancel.bind(this.push)));function addOneListener(e,t,n){e.listeners(t).indexOf(n)==-1&&e.on(t,n)}this.on(`newListener`,function(e){e===`change`?(addOneListener(this.pull,`change`,pullChange),addOneListener(this.push,`change`,pushChange)):e===`denied`?(addOneListener(this.pull,`denied`,pullDenied),addOneListener(this.push,`denied`,pushDenied)):e===`active`?(addOneListener(this.pull,`active`,pullActive),addOneListener(this.push,`active`,pushActive)):e===`paused`&&(addOneListener(this.pull,`paused`,pullPaused),addOneListener(this.push,`paused`,pushPaused))}),this.on(`removeListener`,function(e){e===`change`?(this.pull.removeListener(`change`,pullChange),this.push.removeListener(`change`,pushChange)):e===`denied`?(this.pull.removeListener(`denied`,pullDenied),this.push.removeListener(`denied`,pushDenied)):e===`active`?(this.pull.removeListener(`active`,pullActive),this.push.removeListener(`active`,pushActive)):e===`paused`&&(this.pull.removeListener(`paused`,pullPaused),this.push.removeListener(`paused`,pushPaused))}),this.pull.on(`removeListener`,removeAll(`pull`)),this.push.on(`removeListener`,removeAll(`push`));let s=Promise.all([this.push,this.pull]).then(e=>{let t={push:e[0],pull:e[1]};return this.emit(`complete`,t),r&&r(null,t),this.removeAllListeners(),t},e=>{if(this.cancel(),r?r(e):this.emit(`error`,e),this.removeAllListeners(),r)throw e});this.then=function(e,t){return s.then(e,t)},this.catch=function(e){return s.catch(e)}}cancel(){this.canceled||(this.canceled=!0,this.push.cancel(),this.pull.cancel())}};function replication(e){e.replicate=replicateWrapper,e.sync=sync,Object.defineProperty(e.prototype,`replicate`,{get:function(){var e=this;return this.replicateMethods===void 0&&(this.replicateMethods={from:function(t,n,r){return e.constructor.replicate(t,e,n,r)},to:function(t,n,r){return e.constructor.replicate(e,t,n,r)}}),this.replicateMethods}}),e.prototype.sync=function(e,t,n){return this.constructor.sync(this,e,t,n)}}I.plugin(IDBPouch).plugin(HttpPouch$1).plugin(Nt).plugin(replication);var PouchError=class extends Error{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(401,`unauthorized`,`Name or password is incorrect.`),new PouchError(400,`bad_request`,`Missing JSON list of 'docs'`),new PouchError(404,`not_found`,`missing`),new PouchError(409,`conflict`,`Document update conflict`),new PouchError(400,`bad_request`,`_id field must contain a string`),new PouchError(412,`missing_id`,`_id is required for puts`),new PouchError(400,`bad_request`,`Only reserved document ids may start with underscore.`),new PouchError(412,`precondition_failed`,`Database not open`);var zt=new PouchError(500,`unknown_error`,`Database encountered an unknown error`);new PouchError(500,`badarg`,`Some query argument is invalid`),new PouchError(400,`invalid_request`,`Request was invalid`),new PouchError(400,`query_parse_error`,`Some query parameter is invalid`),new PouchError(500,`doc_validation`,`Bad special document member`),new PouchError(400,`bad_request`,`Something wrong with the request`),new PouchError(400,`bad_request`,`Document must be a JSON object`),new PouchError(404,`not_found`,`Database not found`),new PouchError(500,`indexed_db_went_bad`,`unknown`),new PouchError(500,`web_sql_went_bad`,`unknown`),new PouchError(500,`levelDB_went_went_bad`,`unknown`),new PouchError(403,`forbidden`,`Forbidden by design doc validate_doc_update function`),new PouchError(400,`bad_request`,`Invalid rev format`),new PouchError(412,`file_exists`,`The database could not be created, the file already exists.`),new PouchError(412,`missing_stub`,`A pre-existing attachment stub wasn't found`),new PouchError(413,`invalid_url`,`Provided URL is invalid`);function createError(e,t){function CustomPouchError(t){for(var n=Object.getOwnPropertyNames(e),r=0,i=n.length;r<i;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.prototype,new CustomPouchError(t)}function generateErrorFromResponse(e){if(typeof e!=`object`){var t=e;e=zt,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}var Bt=Headers,thisAtob=function(e){return atob(e)};function createBlob(e,t){e=e||[],t=t||{};try{return new Blob(e,t)}catch(i){if(i.name!==`TypeError`)throw i;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)}}function binaryStringToArrayBuffer(e){for(var t=e.length,n=new ArrayBuffer(t),r=new Uint8Array(n),i=0;i<t;i++)r[i]=e.charCodeAt(i);return n}function binStringToBluffer(e,t){return createBlob([binaryStringToArrayBuffer(e)],{type:t})}function b64ToBluffer(e,t){return binStringToBluffer(thisAtob(e),t)}function pad(e,t,n){for(var r=``,i=n-e.length;r.length<i;)r+=t;return r}function padLeft(e,t,n){return pad(e,t,n)+e}var Vt=-324,Ht=3,Ut=``;function collate(e,t){if(e===t)return 0;e=normalizeKey(e),t=normalizeKey(t);var n=collationIndex(e),r=collationIndex(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(e,t)}return Array.isArray(e)?arrayCollate(e,t):objectCollate(e,t)}function normalizeKey(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(t[r])}else if(e instanceof Date)return e.toJSON();else if(e!==null){for(var i in e={},t)if(Object.prototype.hasOwnProperty.call(t,i)){var a=t[i];a!==void 0&&(e[i]=normalizeKey(a))}}}return e}function indexify(e){if(e!==null)switch(typeof e){case`boolean`:return e?1:0;case`number`:return numToIndexableString(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,i=n.length,a=``;if(t)for(;++r<i;)a+=toIndexableString(n[r]);else for(;++r<i;){var o=n[r];a+=toIndexableString(o)+toIndexableString(e[o])}return a}return``}function toIndexableString(e){return e=normalizeKey(e),collationIndex(e)+Ut+indexify(e)+`\0`}function parseNumber(e,t){var n=t,r;if(e[t]===`1`)r=0,t++;else{var i=e[t]===`0`;t++;var a=``,o=e.substring(t,t+Ht),s=parseInt(o,10)+Vt;for(i&&(s=-s),t+=Ht;;){var c=e[t];if(c===`\0`)break;a+=c,t++}a=a.split(`.`),r=a.length===1?parseInt(a,10):parseFloat(a[0]+`.`+a[1]),i&&(r-=10),s!==0&&(r=parseFloat(r+`e`+s))}return{num:r,length:t-n}}function pop(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 i=r.element,a=r.index;if(Array.isArray(i))i.push(n);else if(a===e.length-2){var o=e.pop();i[o]=n}else e.push(n)}}function parseIndexableString(e){for(var t=[],n=[],r=0;;){var i=e[r++];if(i===`\0`){if(t.length===1)return t.pop();pop(t,n);continue}switch(i){case`1`:t.push(null);break;case`2`:t.push(e[r]===`1`),r++;break;case`3`:var a=parseNumber(e,r);t.push(a.num),r+=a.length;break;case`4`:for(var o=``;;){var s=e[r];if(s===`\0`)break;o+=s,r++}o=o.replace(/\u0001\u0001/g,`\0`).replace(/\u0001\u0002/g,``).replace(/\u0002\u0002/g,``),t.push(o);break;case`5`:var c={element:[],index:t.length};t.push(c.element),n.push(c);break;case`6`:var l={element:{},index:t.length};t.push(l.element),n.push(l);break;default:throw Error(`bad collationIndex or unexpectedly reached end of input: `+i)}}}function arrayCollate(e,t){for(var n=Math.min(e.length,t.length),r=0;r<n;r++){var i=collate(e[r],t[r]);if(i!==0)return i}return e.length===t.length?0:e.length>t.length?1:-1}function stringCollate(e,t){return e===t?0:e>t?1:-1}function objectCollate(e,t){for(var n=Object.keys(e),r=Object.keys(t),i=Math.min(n.length,r.length),a=0;a<i;a++){var o=collate(n[a],r[a]);if(o!==0||(o=collate(e[n[a]],t[r[a]]),o!==0))return o}return n.length===r.length?0:n.length>r.length?1:-1}function collationIndex(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}function numToIndexableString(e){if(e===0)return`1`;var t=e.toExponential().split(/e\+?/),n=parseInt(t[1],10),r=e<0,i=r?`0`:`2`,a=padLeft(((r?-n:n)-Vt).toString(),`0`,Ht);i+=Ut+a;var o=Math.abs(parseFloat(t[0]));r&&(o=10-o);var s=o.toFixed(20);return s=s.replace(/\.?0+$/,``),i+=Ut+s,i}self.setImmediate||self.setTimeout;function stringMd5(e){return Te.default.hash(e)}function isBinaryObject(e){return typeof ArrayBuffer<`u`&&e instanceof ArrayBuffer||typeof Blob<`u`&&e instanceof Blob}function cloneBinaryObject(e){return e instanceof ArrayBuffer?e.slice(0):e.slice(0,e.size,e.type)}var Wt=Function.prototype.toString,Gt=Wt.call(Object);function isPlainObject(e){var t=Object.getPrototypeOf(e);if(t===null)return!0;var n=t.constructor;return typeof n==`function`&&n instanceof n&&Wt.call(n)==Gt}function clone(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(e[n]);return t}if(e instanceof Date&&isFinite(e))return e.toISOString();if(isBinaryObject(e))return cloneBinaryObject(e);if(!isPlainObject(e))return e;for(n in t={},e)if(Object.prototype.hasOwnProperty.call(e,n)){var i=clone(e[n]);i!==void 0&&(t[n]=i)}return t}try{localStorage.setItem(`_pouch_check_localstorage`,1),localStorage.getItem(`_pouch_check_localstorage`)}catch{}var Kt=typeof queueMicrotask==`function`?queueMicrotask:function nextTick(e){Promise.resolve().then(e)};function guardedConsole(e){if(typeof console<`u`&&typeof console[e]==`function`){var t=Array.prototype.slice.call(arguments,1);console[e].apply(console,t)}}function f(){}f.name;function isRemote(e){return typeof e._remote==`boolean`?e._remote:typeof e.type==`function`?(guardedConsole(`warn`,`db.type() is deprecated and will be removed in a future version of PouchDB`),e.type()===`http`):!1}function upsert(e,t,n){return e.get(t).catch(function(e){if(e.status!==404)throw e;return{}}).then(function(r){var i=r._rev,a=n(r);return a?(a._id=t,a._rev=i,tryAndPut(e,a,n)):{updated:!1,rev:i}})}function tryAndPut(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(e,t._id,n)})}var qt=class QueryParseError extends Error{constructor(e){super(),this.status=400,this.name=`query_parse_error`,this.message=e,this.error=!0;try{Error.captureStackTrace(this,QueryParseError)}catch{}}},Jt=class NotFoundError extends Error{constructor(e){super(),this.status=404,this.name=`not_found`,this.message=e,this.error=!0;try{Error.captureStackTrace(this,NotFoundError)}catch{}}},Yt=class BuiltInError extends Error{constructor(e){super(),this.status=500,this.name=`invalid_value`,this.message=e,this.error=!0;try{Error.captureStackTrace(this,BuiltInError)}catch{}}};function promisedCallback(e,t){return t&&e.then(function(e){Kt(function(){t(null,e)})},function(e){Kt(function(){t(e)})}),e}function callbackify(e){return function(...t){var n=t.pop(),r=e.apply(this,t);return typeof n==`function`&&promisedCallback(r,n),r}}function fin(e,t){return e.then(function(e){return t().then(function(){return e})},function(e){return t().then(function(){throw e})})}function sequentialize(e,t){return function(){var n=arguments,r=this;return e.add(function(){return t.apply(r,n)})}}function uniq$1(e){var t=new Set(e),n=Array(t.size),r=-1;return t.forEach(function(e){n[++r]=e}),n}e(uniq$1,`uniq`);function mapToKeysArray(e){var t=Array(e.size),n=-1;return e.forEach(function(e,r){t[++n]=r}),t}var TaskQueue=class{constructor(){this.promise=Promise.resolve()}add(e){return this.promise=this.promise.catch(()=>{}).then(()=>e()),this.promise}finish(){return this.promise}};function stringify(e){if(!e)return`undefined`;switch(typeof e){case`function`:return e.toString();case`string`:return e.toString();default:return JSON.stringify(e)}}function createViewSignature(e,t){return stringify(e)+stringify(t)+`undefined`}async function createView(e,t,n,r,i,a){let o=createViewSignature(n,r),s;if(!i&&(s=e._cachedViews=e._cachedViews||{},s[o]))return s[o];let c=e.info().then(async function(c){let l=c.db_name+`-mrview-`+(i?`temp`:stringMd5(o));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[l])return r[l]=!0,e}await upsert(e,`_local/`+a,diffFunction);let u=(await e.registerDependentDatabase(l)).db;u.auto_compaction=!0;let d={name:l,db:u,sourceDB:e,adapter:e.adapter,mapFun:n,reduceFun:r},p;try{p=await d.db.get(`_local/lastSeq`)}catch(e){if(e.status!==404)throw e}return d.seq=p?p.seq:0,s&&d.db.once(`destroyed`,function(){delete s[o]}),d});return s&&(s[o]=c),c}var Xt={},Zt=new TaskQueue,Qt=50;function parseViewName(e){return e.indexOf(`/`)===-1?[e,e]:e.split(`/`)}function isGenOne(e){return e.length===1&&/^1-/.test(e[0].rev)}function emitError(e,t,n){try{e.emit(`error`,t)}catch{guardedConsole(`error`,`The user's map/reduce function threw an uncaught error.
8
+ You can debug this error by doing:
9
+ myDatabase.on('error', function (err) { debugger; });
10
+ Please double-check your map/reduce function.`),guardedConsole(`error`,t,n)}}function createAbstractMapReduce(e,t,n,r){function tryMap(e,t,n){try{t(n)}catch(r){emitError(e,r,{fun:t,doc:n})}}function tryReduce(e,t,n,r,i){try{return{output:t(n,r,i)}}catch(a){return emitError(e,a,{fun:t,keys:n,values:r,rereduce:i}),{error:a}}}function sortByKeyThenValue(e,t){let n=collate(e.key,t.key);return n===0?collate(e.value,t.value):n}function sliceResults(e,t,n){return n=n||0,typeof t==`number`?e.slice(n,t+n):n>0?e.slice(n):e}function rowToDocId(e){let t=e.value;return t&&typeof t==`object`&&t._id||e.id}function readAttachmentsAsBlobOrBuffer(e){for(let t of e.rows){let e=t.doc&&t.doc._attachments;if(e)for(let t of Object.keys(e)){let n=e[t];e[t].data=b64ToBluffer(n.data,n.content_type)}}}function postprocessAttachments(e){return function(t){return e.include_docs&&e.attachments&&e.binary&&readAttachmentsAsBlobOrBuffer(t),t}}function addHttpParam(e,t,n,r){let i=t[e];i!==void 0&&(r&&(i=encodeURIComponent(JSON.stringify(i))),n.push(e+`=`+i))}function coerceInteger(e){if(e!==void 0){let t=Number(e);return!isNaN(t)&&t===parseInt(e,10)?t:e}}function coerceOptions(e){return e.group_level=coerceInteger(e.group_level),e.limit=coerceInteger(e.limit),e.skip=coerceInteger(e.skip),e}function checkPositiveInteger(e){if(e){if(typeof e!=`number`)return new qt(`Invalid value for integer: "${e}"`);if(e<0)return new qt(`Invalid value for positive integer: "${e}"`)}}function checkQueryParseError(e,t){let n=e.descending?`endkey`:`startkey`,r=e.descending?`startkey`:`endkey`;if(e[n]!==void 0&&e[r]!==void 0&&collate(e[n],e[r])>0)throw new qt(`No rows can match your key range, reverse your start_key and end_key or set {descending : true}`);if(t.reduce&&e.reduce!==!1){if(e.include_docs)throw new qt(`{include_docs:true} is invalid for reduce`);if(e.keys&&e.keys.length>1&&!e.group&&!e.group_level)throw new qt(`Multi-key fetches for reduce views must use {group: true}`)}for(let t of[`group_level`,`limit`,`skip`]){let n=checkPositiveInteger(e[t]);if(n)throw n}}async function httpQuery(e,t,n){let r=[],i,a=`GET`,o;if(addHttpParam(`reduce`,n,r),addHttpParam(`include_docs`,n,r),addHttpParam(`attachments`,n,r),addHttpParam(`limit`,n,r),addHttpParam(`descending`,n,r),addHttpParam(`group`,n,r),addHttpParam(`group_level`,n,r),addHttpParam(`skip`,n,r),addHttpParam(`stale`,n,r),addHttpParam(`conflicts`,n,r),addHttpParam(`startkey`,n,r,!0),addHttpParam(`start_key`,n,r,!0),addHttpParam(`endkey`,n,r,!0),addHttpParam(`end_key`,n,r,!0),addHttpParam(`inclusive_end`,n,r),addHttpParam(`key`,n,r,!0),addHttpParam(`update_seq`,n,r),r=r.join(`&`),r=r===``?``:`?`+r,n.keys!==void 0){let e=`keys=${encodeURIComponent(JSON.stringify(n.keys))}`;e.length+r.length+1<=2e3?r+=(r[0]===`?`?`&`:`?`)+e:(a=`POST`,typeof t==`string`?i={keys:n.keys}:t.keys=n.keys)}if(typeof t==`string`){let s=parseViewName(t),c=await e.fetch(`_design/`+s[0]+`/_view/`+s[1]+r,{headers:new Bt({"Content-Type":`application/json`}),method:a,body:JSON.stringify(i)});o=c.ok;let l=await c.json();if(!o)throw l.status=c.status,generateErrorFromResponse(l);for(let e of l.rows)if(e.value&&e.value.error&&e.value.error===`builtin_reduce_error`)throw Error(e.reason);return new Promise(function(e){e(l)}).then(postprocessAttachments(n))}i=i||{};for(let e of Object.keys(t))Array.isArray(t[e])?i[e]=t[e]:i[e]=t[e].toString();let s=await e.fetch(`_temp_view`+r,{headers:new Bt({"Content-Type":`application/json`}),method:`POST`,body:JSON.stringify(i)});o=s.ok;let c=await s.json();if(!o)throw c.status=s.status,generateErrorFromResponse(c);return new Promise(function(e){e(c)}).then(postprocessAttachments(n))}function customQuery(e,t,n){return new Promise(function(r,i){e._query(t,n,function(e,t){if(e)return i(e);r(t)})})}function customViewCleanup(e){return new Promise(function(t,n){e._viewCleanup(function(e,r){if(e)return n(e);t(r)})})}function defaultsTo(e){return function(t){if(t.status===404)return e;throw t}}async function getDocsToPersist(e,t,n){let r=`_local/doc_`+e,i={_id:r,keys:[]},a=n.get(e),o=a[0],s=a[1];function getMetaDoc(){return isGenOne(s)?Promise.resolve(i):t.db.get(r).catch(defaultsTo(i))}function getKeyValueDocs(e){return e.keys.length?t.db.allDocs({keys:e.keys,include_docs:!0}):Promise.resolve({rows:[]})}function processKeyValueDocs(e,t){let n=[],r=new Set;for(let e of t.rows){let t=e.doc;if(t&&(n.push(t),r.add(t._id),t._deleted=!o.has(t._id),!t._deleted)){let e=o.get(t._id);`value`in e&&(t.value=e.value)}}let i=mapToKeysArray(o);for(let e of i)if(!r.has(e)){let t={_id:e},r=o.get(e);`value`in r&&(t.value=r.value),n.push(t)}return e.keys=uniq$1(i.concat(e.keys)),n.push(e),n}let c=await getMetaDoc();return processKeyValueDocs(c,await getKeyValueDocs(c))}function updatePurgeSeq(e){return e.sourceDB.get(`_local/purges`).then(function(t){let n=t.purgeSeq;return e.db.get(`_local/purgeSeq`).then(function(e){return e._rev}).catch(defaultsTo(void 0)).then(function(t){return e.db.put({_id:`_local/purgeSeq`,_rev:t,purgeSeq:n})})}).catch(function(e){if(e.status!==404)throw e})}function saveKeyValues(e,t,n){var r=`_local/lastSeq`;return e.db.get(r).catch(defaultsTo({_id:r,seq:0})).then(function(r){var i=mapToKeysArray(t);return Promise.all(i.map(function(n){return getDocsToPersist(n,e,t)})).then(function(t){var i=t.flat();return r.seq=n,i.push(r),e.db.bulkDocs({docs:i})}).then(()=>updatePurgeSeq(e))})}function getQueue(e){let t=typeof e==`string`?e:e.name,n=Xt[t];return n||(n=Xt[t]=new TaskQueue),n}async function updateView(e,t){return sequentialize(getQueue(e),function(){return updateViewInQueue(e,t)})()}async function updateViewInQueue(e,n){let r,i,a;function emit(e,t){let n={id:i._id,key:normalizeKey(e)};t!=null&&(n.value=normalizeKey(t)),r.push(n)}let o=t(e.mapFun,emit),s=e.seq||0;function createTask(){return e.sourceDB.info().then(function(t){a=e.sourceDB.activeTasks.add({name:`view_indexing`,total_items:t.update_seq-s})})}function processChange(t,n){return function(){return saveKeyValues(e,t,n)}}let c=0,l={view:e.name,indexed_docs:c};e.sourceDB.emit(`indexing`,l);let u=new TaskQueue;async function processNextBatch(){return processBatch(await e.sourceDB.changes({return_docs:!0,conflicts:!0,include_docs:!0,style:`all_docs`,since:s,limit:n.changes_batch_size}),await getRecentPurges())}function getRecentPurges(){return e.db.get(`_local/purgeSeq`).then(function(e){return e.purgeSeq}).catch(defaultsTo(-1)).then(function(t){return e.sourceDB.get(`_local/purges`).then(function(n){let r=n.purges.filter(function(e,n){return n>t}).map(e=>e.docId),i=r.filter(function(e,t){return r.indexOf(e)===t});return Promise.all(i.map(function(t){return e.sourceDB.get(t).then(function(e){return{docId:t,doc:e}}).catch(defaultsTo({docId:t}))}))}).catch(defaultsTo([]))})}function processBatch(t,r){let i=t.results;if(!i.length&&!r.length)return;for(let e of r)if(i.findIndex(function(t){return t.id===e.docId})<0){let t={_id:e.docId,doc:{_id:e.docId,_deleted:1},changes:[]};e.doc&&(t.doc=e.doc,t.changes.push({rev:e.doc._rev})),i.push(t)}let o=createDocIdsToChangesAndEmits(i);u.add(processChange(o,s)),c+=i.length;let l={view:e.name,last_seq:t.last_seq,results_count:i.length,indexed_docs:c};if(e.sourceDB.emit(`indexing`,l),e.sourceDB.activeTasks.update(a,{completed_items:c}),!(i.length<n.changes_batch_size))return processNextBatch()}function createDocIdsToChangesAndEmits(t){let n=new Map;for(let a of t){if(a.doc._id[0]!==`_`){r=[],i=a.doc,i._deleted||tryMap(e.sourceDB,o,i),r.sort(sortByKeyThenValue);let t=createIndexableKeysToKeyValues(r);n.set(a.doc._id,[t,a.changes])}s=a.seq}return n}function createIndexableKeysToKeyValues(e){let t=new Map,n;for(let r=0,i=e.length;r<i;r++){let i=e[r],a=[i.key,i.id];r>0&&collate(i.key,n)===0&&a.push(r),t.set(toIndexableString(a),i),n=i.key}return t}try{await createTask(),await processNextBatch(),await u.finish(),e.seq=s,e.sourceDB.activeTasks.remove(a)}catch(t){e.sourceDB.activeTasks.remove(a,t)}}function reduceView(e,t,r){r.group_level===0&&delete r.group_level;let i=r.group||r.group_level,a=n(e.reduceFun),o=[],s=isNaN(r.group_level)?1/0:r.group_level;for(let e of t){let t=o[o.length-1],n=i?e.key:null;if(i&&Array.isArray(n)&&(n=n.slice(0,s)),t&&collate(t.groupKey,n)===0){t.keys.push([e.key,e.id]),t.values.push(e.value);continue}o.push({keys:[[e.key,e.id]],values:[e.value],groupKey:n})}t=[];for(let n of o){let r=tryReduce(e.sourceDB,a,n.keys,n.values,!1);if(r.error&&r.error instanceof Yt)throw r.error;t.push({value:r.error?null:r.output,key:n.groupKey})}return{rows:sliceResults(t,r.limit,r.skip)}}function queryView(e,t){return sequentialize(getQueue(e),function(){return queryViewInQueue(e,t)})()}async function queryViewInQueue(e,t){let n,r=e.reduceFun&&t.reduce!==!1,i=t.skip||0;t.keys!==void 0&&!t.keys.length&&(t.limit=0,delete t.keys);async function fetchFromView(t){t.include_docs=!0;let r=await e.db.allDocs(t);return n=r.total_rows,r.rows.map(function(e){if(`value`in e.doc&&typeof e.doc.value==`object`&&e.doc.value!==null){let t=Object.keys(e.doc.value).sort(),n=[`id`,`key`,`value`];if(!(t<n||t>n))return e.doc.value}let t=parseIndexableString(e.doc._id);return{key:t[0],id:t[1],value:`value`in e.doc?e.doc.value:null}})}async function onMapResultsReady(a){let o;if(o=r?reduceView(e,a,t):t.keys===void 0?{total_rows:n,offset:i,rows:a}:{total_rows:n,offset:i,rows:sliceResults(a,t.limit,t.skip)},t.update_seq&&(o.update_seq=e.seq),t.include_docs){let n=uniq$1(a.map(rowToDocId)),r=await e.sourceDB.allDocs({keys:n,include_docs:!0,conflicts:t.conflicts,attachments:t.attachments,binary:t.binary}),i=new Map;for(let e of r.rows)i.set(e.id,e.doc);for(let e of a){let t=rowToDocId(e),n=i.get(t);n&&(e.doc=n)}}return o}if(t.keys!==void 0){let e=t.keys.map(function(e){let n={startkey:toIndexableString([e]),endkey:toIndexableString([e,{}])};return t.update_seq&&(n.update_seq=!0),fetchFromView(n)});return onMapResultsReady((await Promise.all(e)).flat())}else{let e={descending:t.descending};t.update_seq&&(e.update_seq=!0);let n,a;if(`start_key`in t&&(n=t.start_key),`startkey`in t&&(n=t.startkey),`end_key`in t&&(a=t.end_key),`endkey`in t&&(a=t.endkey),n!==void 0&&(e.startkey=t.descending?toIndexableString([n,{}]):toIndexableString([n])),a!==void 0){let n=t.inclusive_end!==!1;t.descending&&(n=!n),e.endkey=toIndexableString(n?[a,{}]:[a])}if(t.key!==void 0){let n=toIndexableString([t.key]),r=toIndexableString([t.key,{}]);e.descending?(e.endkey=n,e.startkey=r):(e.startkey=n,e.endkey=r)}return r||(typeof t.limit==`number`&&(e.limit=t.limit),e.skip=i),onMapResultsReady(await fetchFromView(e))}}async function httpViewCleanup(e){return(await e.fetch(`_view_cleanup`,{headers:new Bt({"Content-Type":`application/json`}),method:`POST`})).json()}async function localViewCleanup(t){try{let n=await t.get(`_local/`+e),r=new Map;for(let e of Object.keys(n.views)){let t=parseViewName(e),n=`_design/`+t[0],i=t[1],a=r.get(n);a||(a=new Set,r.set(n,a)),a.add(i)}let i={keys:mapToKeysArray(r),include_docs:!0},a=await t.allDocs(i),o={};for(let e of a.rows){let t=e.key.substring(8);for(let i of r.get(e.key)){let r=t+`/`+i;n.views[r]||(r=i);let a=Object.keys(n.views[r]),s=e.doc&&e.doc.views&&e.doc.views[i];for(let e of a)o[e]=o[e]||s}}let s=Object.keys(o).filter(function(e){return!o[e]}).map(function(e){return sequentialize(getQueue(e),function(){return new t.constructor(e,t.__opts).destroy()})()});return Promise.all(s).then(function(){return{ok:!0}})}catch(e){if(e.status===404)return{ok:!0};throw e}}async function queryPromised(t,n,i){if(typeof t._query==`function`)return customQuery(t,n,i);if(isRemote(t))return httpQuery(t,n,i);let a={changes_batch_size:t.__opts.view_update_changes_batch_size||Qt};if(typeof n!=`string`)return checkQueryParseError(i,n),Zt.add(async function(){let r=await createView(t,`temp_view/temp_view`,n.map,n.reduce,!0,e);return fin(updateView(r,a).then(function(){return queryView(r,i)}),function(){return r.db.destroy()})}),Zt.finish();{let o=n,s=parseViewName(o),c=s[0],l=s[1],u=await t.get(`_design/`+c);if(n=u.views&&u.views[l],!n)throw new Jt(`ddoc ${u._id} has no view named ${l}`);r(u,l),checkQueryParseError(i,n);let d=await createView(t,o,n.map,n.reduce,!1,e);return i.stale===`ok`||i.stale===`update_after`?(i.stale===`update_after`&&Kt(function(){updateView(d,a)}),queryView(d,i)):(await updateView(d,a),queryView(d,i))}}function abstractQuery(e,t,n){let r=this;typeof t==`function`&&(n=t,t={}),t=t?coerceOptions(t):{},typeof e==`function`&&(e={map:e});let i=Promise.resolve().then(function(){return queryPromised(r,e,t)});return promisedCallback(i,n),i}return{query:abstractQuery,viewCleanup:callbackify(function(){let e=this;return typeof e._viewCleanup==`function`?customViewCleanup(e):isRemote(e)?httpViewCleanup(e):localViewCleanup(e)})}}function getFieldFromDoc(e,t){for(var n=e,r=0,i=t.length;r<i;r++){var a=t[r];if(n=n[a],!n)break}return n}function setFieldInDoc(e,t,n){for(var r=0,i=t.length;r<i-1;r++){var a=t[r];e=e[a]=e[a]||{}}e[t[i-1]]=n}function compare(e,t){return e<t?-1:e>t?1:0}function parseField(e){for(var t=[],n=``,r=0,i=e.length;r<i;r++){var a=e[r];r>0&&e[r-1]===`\\`&&(a===`$`||a===`.`)?n=n.substring(0,n.length-1)+a:a===`.`?(t.push(n),n=``):n+=a}return t.push(n),t}var $t=[`$or`,`$nor`,`$not`];function isCombinationalField(e){return $t.indexOf(e)>-1}function getKey(e){return Object.keys(e)[0]}function getValue(e){return e[getKey(e)]}function mergeAndedSelectors(e){var t={},n={$or:!0,$nor:!0};return e.forEach(function(e){Object.keys(e).forEach(function(r){var i=e[r];if(typeof i!=`object`&&(i={$eq:i}),isCombinationalField(r))if(i instanceof Array){if(n[r]){n[r]=!1,t[r]=i;return}var a=[];t[r].forEach(function(e){Object.keys(i).forEach(function(t){var n=i[t],r=Math.max(Object.keys(e).length,Object.keys(n).length),o=mergeAndedSelectors([e,n]);Object.keys(o).length<=r||a.push(o)})}),t[r]=a}else t[r]=mergeAndedSelectors([i]);else{var o=t[r]=t[r]||{};Object.keys(i).forEach(function(e){var t=i[e];if(e===`$gt`||e===`$gte`)return mergeGtGte(e,t,o);if(e===`$lt`||e===`$lte`)return mergeLtLte(e,t,o);if(e===`$ne`)return mergeNe(t,o);if(e===`$eq`)return mergeEq(t,o);if(e===`$regex`)return mergeRegex(t,o);o[e]=t})}})}),t}function mergeGtGte(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))}function mergeLtLte(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))}function mergeNe(e,t){`$ne`in t?t.$ne.push(e):t.$ne=[e]}function mergeEq(e,t){delete t.$gt,delete t.$gte,delete t.$lt,delete t.$lte,delete t.$ne,t.$eq=e}function mergeRegex(e,t){`$regex`in t?t.$regex.push(e):t.$regex=[e]}function mergeAndedSelectorsNested(e){for(var t in e){if(Array.isArray(e))for(var n in e)e[n].$and&&(e[n]=mergeAndedSelectors(e[n].$and));var r=e[t];typeof r==`object`&&mergeAndedSelectorsNested(r)}return e}function isAndInSelector(e,t){for(var n in e){n===`$and`&&(t=!0);var r=e[n];typeof r==`object`&&(t=isAndInSelector(r,t))}return t}function massageSelector(e){var t=clone(e);isAndInSelector(t,!1)&&(t=mergeAndedSelectorsNested(t),`$and`in t&&(t=mergeAndedSelectors(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],i=e[r];(typeof i!=`object`||!i)&&(e[r]={$eq:i})}})}),`$not`in t&&(t.$not=mergeAndedSelectors([t.$not]));for(var n=Object.keys(t),r=0;r<n.length;r++){var i=n[r],a=t[i];(typeof a!=`object`||!a)&&(a={$eq:a}),t[i]=a}return normalizeArrayOperators(t),t}function normalizeArrayOperators(e){Object.keys(e).forEach(function(t){var n=e[t];Array.isArray(n)?n.forEach(function(e){e&&typeof e==`object`&&normalizeArrayOperators(e)}):t===`$ne`?e.$ne=[n]:t===`$regex`?e.$regex=[n]:n&&typeof n==`object`&&normalizeArrayOperators(n)})}function createFieldSorter(e){function getFieldValuesAsArray(t){return e.map(function(e){return getFieldFromDoc(t,parseField(getKey(e)))})}return function(e,t){var n=collate(getFieldValuesAsArray(e.doc),getFieldValuesAsArray(t.doc));return n===0?compare(e.doc._id,t.doc._id):n}}function filterInMemoryFields(e,t,n){if(e=e.filter(function(e){return rowFilter(e.doc,t.selector,n)}),t.sort){var r=createFieldSorter(t.sort);e=e.sort(r),typeof t.sort[0]!=`string`&&getValue(t.sort[0])===`desc`&&(e=e.reverse())}if(`limit`in t||`skip`in t){var i=t.skip||0,a=(`limit`in t?t.limit:e.length)+i;e=e.slice(i,a)}return e}function rowFilter(e,t,n){return n.every(function(n){var r=t[n],i=parseField(n),a=getFieldFromDoc(e,i);return isCombinationalField(n)?matchCominationalSelector(n,r,e):matchSelector(r,e,i,a)})}function matchSelector(e,t,n,r){return e?typeof e==`object`?Object.keys(e).every(function(i){var a=e[i];if(i.indexOf(`$`)===0)return match(i,t,a,n,r);var o=parseField(i);if(r===void 0&&typeof a!=`object`&&o.length>0)return!1;var s=getFieldFromDoc(r,o);return typeof a==`object`?matchSelector(a,t,n,s):match(`$eq`,t,a,o,s)}):e===r:!0}function matchCominationalSelector(e,t,n){return e===`$or`?t.some(function(e){return rowFilter(n,e,Object.keys(e))}):e===`$not`?!rowFilter(n,t,Object.keys(t)):!t.find(function(e){return rowFilter(n,e,Object.keys(e))})}function match(e,t,n,r,i){if(!en[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 en[e](t,n,r,i)}function fieldExists(e){return e!=null}function fieldIsNotUndefined(e){return e!==void 0}function modField(e,t){if(typeof e!=`number`||parseInt(e,10)!==e)return!1;var n=t[0],r=t[1];return e%n===r}function arrayContainsValue(e,t){return t.some(function(t){return e instanceof Array?e.some(function(e){return collate(t,e)===0}):collate(t,e)===0})}function arrayContainsAllValues(e,t){return t.every(function(t){return e.some(function(e){return collate(t,e)===0})})}function arraySize(e,t){return e.length===t}function regexMatch(e,t){return new RegExp(t).test(e)}function typeMatch(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]`}}var en={$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(e,t,Object.keys(t))}):r.some(function(r){return matchSelector(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(e,t,Object.keys(t))}):r.every(function(r){return matchSelector(t,e,n,r)})},$eq:function(e,t,n,r){return fieldIsNotUndefined(r)&&collate(r,t)===0},$gte:function(e,t,n,r){return fieldIsNotUndefined(r)&&collate(r,t)>=0},$gt:function(e,t,n,r){return fieldIsNotUndefined(r)&&collate(r,t)>0},$lte:function(e,t,n,r){return fieldIsNotUndefined(r)&&collate(r,t)<=0},$lt:function(e,t,n,r){return fieldIsNotUndefined(r)&&collate(r,t)<0},$exists:function(e,t,n,r){return t?fieldIsNotUndefined(r):!fieldIsNotUndefined(r)},$mod:function(e,t,n,r){return fieldExists(r)&&modField(r,t)},$ne:function(e,t,n,r){return t.every(function(e){return collate(r,e)!==0})},$in:function(e,t,n,r){return fieldExists(r)&&arrayContainsValue(r,t)},$nin:function(e,t,n,r){return fieldExists(r)&&!arrayContainsValue(r,t)},$size:function(e,t,n,r){return fieldExists(r)&&Array.isArray(r)&&arraySize(r,t)},$all:function(e,t,n,r){return Array.isArray(r)&&arrayContainsAllValues(r,t)},$regex:function(e,t,n,r){return fieldExists(r)&&typeof r==`string`&&t.every(function(e){return regexMatch(r,e)})},$type:function(e,t,n,r){return typeMatch(r,t)}};function matchesSelector(e,t){if(typeof t!=`object`)throw Error(`Selector error: expected a JSON object`);t=massageSelector(t);var n=filterInMemoryFields([{doc:e}],{selector:t},Object.keys(t));return n&&n.length===1}var nativeFlat=(...e)=>e.flat(1/0),polyFlat=(...e)=>{let t=[];for(let n of e)Array.isArray(n)?t=t.concat(polyFlat(...n)):t.push(n);return t},tn=typeof Array.prototype.flat==`function`?nativeFlat:polyFlat;function mergeObjects(e){let t={};for(let n of e)Object.assign(t,n);return t}function pick(e,t){let n={};for(let r of t){let t=parseField(r),i=getFieldFromDoc(e,t);i!==void 0&&setFieldInDoc(n,t,i)}return n}function oneArrayIsSubArrayOfOther(e,t){for(let n=0,r=Math.min(e.length,t.length);n<r;n++)if(e[n]!==t[n])return!1;return!0}function oneArrayIsStrictSubArrayOfOther(e,t){return e.length>t.length?!1:oneArrayIsSubArrayOfOther(e,t)}function oneSetIsSubArrayOfOther(e,t){e=e.slice();for(let n of t){if(!e.length)break;let t=e.indexOf(n);if(t===-1)return!1;e.splice(t,1)}return!0}function arrayToObject(e){let t={};for(let n of e)t[n]=!0;return t}function max(e,t){let n=null,r=-1;for(let i of e){let e=t(i);e>r&&(r=e,n=i)}return n}function arrayEquals(e,t){if(e.length!==t.length)return!1;for(let n=0,r=e.length;n<r;n++)if(e[n]!==t[n])return!1;return!0}function uniq(e){return Array.from(new Set(e))}function resolveToCallback(e){return function(...t){let n=t[t.length-1];if(typeof n==`function`){let r=n.bind(null,null),i=n.bind(null);e.apply(this,t.slice(0,-1)).then(r,i)}else return e.apply(this,t)}}function massageCreateIndexRequest(e){e=clone(e),e.index||(e.index={});for(let t of[`type`,`name`,`ddoc`])e.index[t]&&(e[t]=e.index[t],delete e.index[t]);return e.fields&&(e.index.fields=e.fields,delete e.fields),e.type||(e.type=`json`),e}function isNonNullObject(e){return typeof e==`object`&&!!e}function checkFieldValueType(e,t,n){let r=``,i=t,a=!0;if([`$in`,`$nin`,`$or`,`$and`,`$mod`,`$nor`,`$all`].indexOf(e)!==-1&&(Array.isArray(t)||(r=`Query operator `+e+` must be an array.`)),[`$not`,`$elemMatch`,`$allMatch`].indexOf(e)!==-1&&(!Array.isArray(t)&&isNonNullObject(t)||(r=`Query operator `+e+` must be an object.`)),e===`$mod`&&Array.isArray(t))if(t.length!==2)r=`Query operator $mod must be in the format [divisor, remainder], where divisor and remainder are both integers.`;else{let e=t[0],n=t[1];e===0&&(r=`Query operator $mod's divisor cannot be 0, cannot divide by zero.`,a=!1),(typeof e!=`number`||parseInt(e,10)!==e)&&(r=`Query operator $mod's divisor is not an integer.`,i=e),parseInt(n,10)!==n&&(r=`Query operator $mod's remainder is not an integer.`,i=n)}if(e===`$exists`&&typeof t!=`boolean`&&(r=`Query operator $exists must be a boolean.`),e===`$type`){let e=[`null`,`boolean`,`number`,`string`,`array`,`object`],n=`"`+e.slice(0,e.length-1).join(`", "`)+`", or "`+e[e.length-1]+`"`;typeof t==`string`?e.indexOf(t)==-1&&(r=`Query operator $type must be a string. Supported values: `+n+`.`):r=`Query operator $type must be a string. Supported values: `+n+`.`}if(e===`$size`&&parseInt(t,10)!==t&&(r=`Query operator $size must be a integer.`),e===`$regex`&&typeof t!=`string`&&(n?r=`Query operator $regex must be a string.`:t instanceof RegExp||(r=`Query operator $regex must be a string or an instance of a javascript regular expression.`)),r){if(a){let e=i===null?` `:Array.isArray(i)?` array`:` `+typeof i,t=isNonNullObject(i)?JSON.stringify(i,null,` `):i;r+=` Received`+e+`: `+t}throw Error(r)}}var nn=[`$all`,`$allMatch`,`$and`,`$elemMatch`,`$exists`,`$in`,`$mod`,`$nin`,`$nor`,`$not`,`$or`,`$regex`,`$size`,`$type`],rn=[`$in`,`$nin`,`$mod`,`$all`],an=[`$eq`,`$gt`,`$gte`,`$lt`,`$lte`];function validateSelector(e,t){if(Array.isArray(e))for(let n of e)isNonNullObject(n)&&validateSelector(n,t);else for(let[n,r]of Object.entries(e))nn.indexOf(n)!==-1&&checkFieldValueType(n,r,t),an.indexOf(n)===-1&&rn.indexOf(n)===-1&&isNonNullObject(r)&&validateSelector(r,t)}async function dbFetch(e,t,n){n.body&&(n.body=JSON.stringify(n.body),n.headers=new Bt({"Content-type":`application/json`}));let r=await e.fetch(t,n),i=await r.json();if(!r.ok)throw i.status=r.status,generateErrorFromResponse(createError(i));return i}async function createIndex(e,t){return await dbFetch(e,`_index`,{method:`POST`,body:massageCreateIndexRequest(t)})}async function find(e,t){return validateSelector(t.selector,!0),await dbFetch(e,`_find`,{method:`POST`,body:t})}async function explain(e,t){return await dbFetch(e,`_explain`,{method:`POST`,body:t})}async function getIndexes(e){return await dbFetch(e,`_index`,{method:`GET`})}async function deleteIndex(e,t){let n=t.ddoc,r=t.type||`json`,i=t.name;if(!n)throw Error(`you must provide an index's ddoc`);if(!i)throw Error(`you must provide an index's name`);return await dbFetch(e,`_index/`+[n,r,i].map(encodeURIComponent).join(`/`),{method:`DELETE`})}function getDeepValue(e,t){for(let n of t)if(e=e[n],e===void 0)return;return e}function createDeepMultiMapper(e,t,n){return function(r){if(n&&!matchesSelector(r,n))return;let i=[];for(let t of e){let e=getDeepValue(r,parseField(t));if(e===void 0)return;i.push(e)}t(i)}}function createDeepSingleMapper(e,t,n){let r=parseField(e);return function(e){if(n&&!matchesSelector(e,n))return;let i=getDeepValue(e,r);i!==void 0&&t(i)}}function createShallowSingleMapper(e,t,n){return function(r){n&&!matchesSelector(r,n)||t(r[e])}}function createShallowMultiMapper(e,t,n){return function(r){n&&!matchesSelector(r,n)||t(e.map(e=>r[e]))}}function checkShallow(e){return e.every(e=>e.indexOf(`.`)===-1)}function createMapper(e,t,n){let r=checkShallow(e),i=e.length===1;return r?i?createShallowSingleMapper(e[0],t,n):createShallowMultiMapper(e,t,n):i?createDeepSingleMapper(e[0],t,n):createDeepMultiMapper(e,t,n)}function mapper(e,t){let n=Object.keys(e.fields),r=e.partial_filter_selector;return createMapper(n,t,r)}function reducer(){throw Error(`reduce not supported`)}function ddocValidator(e,t){let n=e.views[t];if(!n.map||!n.map.fields)throw Error(`ddoc `+e._id+` with view `+t+` doesn't have map.fields defined. maybe it wasn't created by this plugin?`)}var on=createAbstractMapReduce(`indexes`,mapper,reducer,ddocValidator);function abstractMapper$1(e){return e._customFindAbstractMapper?{query:function addQueryFallback(t,n){let r=on.query.bind(this);return e._customFindAbstractMapper.query.call(this,t,n,r)},viewCleanup:function addViewCleanupFallback(){let t=on.viewCleanup.bind(this);return e._customFindAbstractMapper.viewCleanup.call(this,t)}}:on}function massageSort(e){if(!Array.isArray(e))throw Error(`invalid sort json - should be an array`);return e.map(function(e){if(typeof e==`string`){let t={};return t[e]=`asc`,t}else return e})}var sn=/^_design\//;function massageUseIndex(e){let t=[];return typeof e==`string`?t.push(e):t=e,t.map(function(e){return e.replace(sn,``)})}function massageIndexDef(e){return e.fields=e.fields.map(function(e){if(typeof e==`string`){let t={};return t[e]=`asc`,t}return e}),e.partial_filter_selector&&(e.partial_filter_selector=massageSelector(e.partial_filter_selector)),e}function getKeyFromDoc(e,t){return t.def.fields.map(t=>getFieldFromDoc(e,parseField(getKey(t))))}function filterInclusiveStart(e,t,n){let r=n.def.fields,i=0;for(let a of e){let e=getKeyFromDoc(a.doc,n);if(r.length===1)e=e[0];else for(;e.length>t.length;)e.pop();if(Math.abs(collate(e,t))>0)break;++i}return i>0?e.slice(i):e}function reverseOptions(e){let t=clone(e);return delete t.startkey,delete t.endkey,delete t.inclusive_start,delete t.inclusive_end,`endkey`in e&&(t.startkey=e.endkey),`startkey`in e&&(t.endkey=e.startkey),`inclusive_start`in e&&(t.inclusive_end=e.inclusive_start),`inclusive_end`in e&&(t.inclusive_start=e.inclusive_end),t}function validateIndex(e){let t=e.fields.filter(function(e){return getValue(e)===`asc`});if(t.length!==0&&t.length!==e.fields.length)throw Error(`unsupported mixed sorting`)}function validateSort(e,t){if(t.defaultUsed&&e.sort){let t=e.sort.filter(function(e){return Object.keys(e)[0]!==`_id`}).map(function(e){return Object.keys(e)[0]});if(t.length>0)throw Error(`Cannot sort on field(s) "`+t.join(`,`)+`" when using the default index`)}t.defaultUsed}function validateFindRequest(e){if(typeof e.selector!=`object`)throw Error(`you must provide a selector when you find()`)}function getUserFields(e,t){let n=Object.keys(e),r=t?t.map(getKey):[],i;return i=n.length>=r.length?n:r,r.length===0?{fields:i}:(i=i.sort(function(e,t){let n=r.indexOf(e);n===-1&&(n=Number.MAX_VALUE);let i=r.indexOf(t);return i===-1&&(i=Number.MAX_VALUE),n<i?-1:n>i?1:0}),{fields:i,sortOrder:t.map(getKey)})}async function createIndex$1(e,t){t=massageCreateIndexRequest(t);let n=clone(t.index);t.index=massageIndexDef(t.index),validateIndex(t.index);let r;function getMd5(){return r||(r=stringMd5(JSON.stringify(t)))}let i=t.name||`idx-`+getMd5(),a=t.ddoc||`idx-`+getMd5(),o=`_design/`+a,s=!1,c=!1;function updateDdoc(e){return e._rev&&e.language!==`query`&&(s=!0),e.language=`query`,e.views=e.views||{},c=!!e.views[i],c?!1:(e.views[i]={map:{fields:mergeObjects(t.index.fields),partial_filter_selector:t.index.partial_filter_selector},reduce:`_count`,options:{def:n}},e)}if(e.constructor.emit(`debug`,[`find`,`creating index`,o]),await upsert(e,o,updateDdoc),s)throw Error(`invalid language for ddoc with id "`+o+`" (should be "query")`);let l=a+`/`+i;return await abstractMapper$1(e).query.call(e,l,{limit:0,reduce:!1}),{id:o,name:i,result:c?`exists`:`created`}}async function getIndexes$1(e){let t=await e.allDocs({startkey:`_design/`,endkey:`_design/￿`,include_docs:!0}),n={indexes:[{ddoc:null,name:`_all_docs`,type:`special`,def:{fields:[{_id:`asc`}]}}]};return n.indexes=tn(n.indexes,t.rows.filter(function(e){return e.doc.language===`query`}).map(function(e){return(e.doc.views===void 0?[]:Object.keys(e.doc.views)).map(function(t){let n=e.doc.views[t];return{ddoc:e.id,name:t,type:`json`,def:massageIndexDef(n.options.def)}})})),n.indexes.sort(function(e,t){return compare(e.name,t.name)}),n.total_rows=n.indexes.length,n}var cn=null,ln={"￿":{}},un={queryOpts:{limit:0,startkey:ln,endkey:cn},inMemoryFields:[]};function checkFieldInIndex(e,t){return e.def.fields.some(e=>getKey(e)===t)}function userOperatorLosesPrecision(e,t){let n=e[t];return getKey(n)!==`$eq`}function sortFieldsByIndex(e,t){let n=t.def.fields.map(getKey);return e.slice().sort(function(e,t){let r=n.indexOf(e),i=n.indexOf(t);return r===-1&&(r=Number.MAX_VALUE),i===-1&&(i=Number.MAX_VALUE),compare(r,i)})}function getBasicInMemoryFields(e,t,n){n=sortFieldsByIndex(n,e);let r=!1;for(let i=0,a=n.length;i<a;i++){let o=n[i];if(r||!checkFieldInIndex(e,o))return n.slice(i);i<a-1&&userOperatorLosesPrecision(t,o)&&(r=!0)}return[]}function getInMemoryFieldsFromNe(e){let t=[];for(let[n,r]of Object.entries(e))for(let e of Object.keys(r))e===`$ne`&&t.push(n);return t}function getInMemoryFields(e,t,n,r){return sortFieldsByIndex(uniq(tn(e,getBasicInMemoryFields(t,n,r),getInMemoryFieldsFromNe(n))),t)}function checkIndexFieldsMatch(e,t,n){if(t){let r=oneArrayIsStrictSubArrayOfOther(t,e),i=oneArrayIsSubArrayOfOther(n,e);return r&&i}return oneSetIsSubArrayOfOther(n,e)}var dn=[`$eq`,`$gt`,`$gte`,`$lt`,`$lte`];function isNonLogicalMatcher(e){return dn.indexOf(e)===-1}function checkFieldsLogicallySound(e,t){let n=t[e[0]];return n===void 0?!0:!(Object.keys(n).length===1&&getKey(n)===`$ne`)}function checkIndexMatches(e,t,n,r){let i=e.def.fields.map(getKey);return checkIndexFieldsMatch(i,t,n)?checkFieldsLogicallySound(i,r):!1}function findMatchingIndexes(e,t,n,r){return r.filter(function(r){return checkIndexMatches(r,n,t,e)})}function findBestMatchingIndex(e,t,n,r,i){let a=findMatchingIndexes(e,t,n,r);if(a.length===0){if(i)throw{error:`no_usable_index`,message:`There is no index available for this selector.`};let e=r[0];return e.defaultUsed=!0,e}if(a.length===1&&!i)return a[0];let o=arrayToObject(t);function scoreIndex(e){let t=e.def.fields.map(getKey),n=0;for(let e of t)o[e]&&n++;return n}if(i){let e=`_design/`+i[0],t=i.length===2?i[1]:!1,n=a.find(function(n){return!!(t&&n.ddoc===e&&t===n.name||n.ddoc===e)});if(!n)throw{error:`unknown_error`,message:`Could not find that index or could not use that index for the query`};return n}return max(a,scoreIndex)}function getSingleFieldQueryOptsFor(e,t){switch(e){case`$eq`:return{key:t};case`$lte`:return{endkey:t};case`$gte`:return{startkey:t};case`$lt`:return{endkey:t,inclusive_end:!1};case`$gt`:return{startkey:t,inclusive_start:!1}}return{startkey:cn}}function getSingleFieldCoreQueryPlan(e,t){let n=getKey(t.def.fields[0]),r=e[n]||{},i=[],a=Object.keys(r),o;for(let e of a){isNonLogicalMatcher(e)&&i.push(n);let t=r[e],a=getSingleFieldQueryOptsFor(e,t);o=o?mergeObjects([o,a]):a}return{queryOpts:o,inMemoryFields:i}}function getMultiFieldCoreQueryPlan(e,t){switch(e){case`$eq`:return{startkey:t,endkey:t};case`$lte`:return{endkey:t};case`$gte`:return{startkey:t};case`$lt`:return{endkey:t,inclusive_end:!1};case`$gt`:return{startkey:t,inclusive_start:!1}}}function getMultiFieldQueryOpts(e,t){let n=t.def.fields.map(getKey),r=[],i=[],a=[],o,s;function finish(e){o!==!1&&i.push(cn),s!==!1&&a.push(ln),r=n.slice(e)}for(let t=0,r=n.length;t<r;t++){let r=e[n[t]];if(!r||!Object.keys(r).length){finish(t);break}else if(Object.keys(r).some(isNonLogicalMatcher)){finish(t);break}else if(t>0){let i=`$gt`in r||`$gte`in r||`$lt`in r||`$lte`in r,a=Object.keys(e[n[t-1]]),o=arrayEquals(a,[`$eq`]),s=arrayEquals(a,Object.keys(r));if(i&&!o&&!s){finish(t);break}}let c=Object.keys(r),l=null;for(let e of c){let t=r[e],n=getMultiFieldCoreQueryPlan(e,t);l=l?mergeObjects([l,n]):n}i.push(`startkey`in l?l.startkey:cn),a.push(`endkey`in l?l.endkey:ln),`inclusive_start`in l&&(o=l.inclusive_start),`inclusive_end`in l&&(s=l.inclusive_end)}let c={startkey:i,endkey:a};return o!==void 0&&(c.inclusive_start=o),s!==void 0&&(c.inclusive_end=s),{queryOpts:c,inMemoryFields:r}}function shouldShortCircuit(e){return Object.keys(e).map(function(t){return e[t]}).some(function(e){return typeof e==`object`&&Object.keys(e).length===0})}function getDefaultQueryPlan(e){return{queryOpts:{startkey:null},inMemoryFields:[Object.keys(e)]}}function getCoreQueryPlan(e,t){return t.defaultUsed?getDefaultQueryPlan(e,t):t.def.fields.length===1?getSingleFieldCoreQueryPlan(e,t):getMultiFieldQueryOpts(e,t)}function planQuery(e,t){let n=e.selector,r=e.sort;if(shouldShortCircuit(n))return Object.assign({},un,{index:t[0]});let i=getUserFields(n,r),a=i.fields,o=i.sortOrder,s=findBestMatchingIndex(n,a,o,t,e.use_index),c=getCoreQueryPlan(n,s),l=c.queryOpts,u=c.inMemoryFields;return{queryOpts:l,index:s,inMemoryFields:getInMemoryFields(u,s,n,a)}}function indexToSignature(e){return e.ddoc.substring(8)+`/`+e.name}async function doAllDocs(e,t){let n=clone(t);n.descending?(`endkey`in n&&typeof n.endkey!=`string`&&(n.endkey=``),`startkey`in n&&typeof n.startkey!=`string`&&(n.limit=0)):(`startkey`in n&&typeof n.startkey!=`string`&&(n.startkey=``),`endkey`in n&&typeof n.endkey!=`string`&&(n.limit=0)),`key`in n&&typeof n.key!=`string`&&(n.limit=0),n.limit>0&&n.indexes_count&&(n.original_limit=n.limit,n.limit+=n.indexes_count);let r=await e.allDocs(n);return r.rows=r.rows.filter(function(e){return!/^_design\//.test(e.id)}),n.original_limit&&(n.limit=n.original_limit),r.rows=r.rows.slice(0,n.limit),r}async function queryAllOrIndex(e,t,n){return n.name===`_all_docs`?doAllDocs(e,t):abstractMapper$1(e).query.call(e,indexToSignature(n),t)}async function find$1(e,t,n){t.selector&&(validateSelector(t.selector,!1),t.selector=massageSelector(t.selector)),t.sort&&(t.sort=massageSort(t.sort)),t.use_index&&(t.use_index=massageUseIndex(t.use_index)),`limit`in t||(t.limit=25),validateFindRequest(t);let r=await getIndexes$1(e);e.constructor.emit(`debug`,[`find`,`planning query`,t]);let i=planQuery(t,r.indexes);e.constructor.emit(`debug`,[`find`,`query plan`,i]);let a=i.index;validateSort(t,a);let o=Object.assign({include_docs:!0,reduce:!1,indexes_count:r.total_rows},i.queryOpts);if(`startkey`in o&&`endkey`in o&&collate(o.startkey,o.endkey)>0)return{docs:[]};if(t.sort&&typeof t.sort[0]!=`string`&&getValue(t.sort[0])===`desc`&&(o.descending=!0,o=reverseOptions(o)),i.inMemoryFields.length||(o.limit=t.limit,`skip`in t&&(o.skip=t.skip)),n)return Promise.resolve(i,o);let s=await queryAllOrIndex(e,o,a);o.inclusive_start===!1&&(s.rows=filterInclusiveStart(s.rows,o.startkey,a)),i.inMemoryFields.length&&(s.rows=filterInMemoryFields(s.rows,t,i.inMemoryFields));let c={docs:s.rows.map(function(e){let n=e.doc;return t.fields?pick(n,t.fields):n})};return a.defaultUsed&&(c.warning=`No matching index found, create an index to optimize query time.`),c}async function explain$1(e,t){let n=await find$1(e,t,!0);return{dbname:e.name,index:n.index,selector:t.selector,range:{start_key:n.queryOpts.startkey,end_key:n.queryOpts.endkey},opts:{use_index:t.use_index||[],bookmark:`nil`,limit:t.limit,skip:t.skip,sort:t.sort||{},fields:t.fields,conflicts:!1,r:[49]},limit:t.limit,skip:t.skip||0,fields:t.fields}}async function deleteIndex$1(e,t){if(!t.ddoc)throw Error(`you must supply an index.ddoc when deleting`);if(!t.name)throw Error(`you must supply an index.name when deleting`);let n=t.ddoc,r=t.name;function deltaFun(e){return Object.keys(e.views).length===1&&e.views[r]?{_id:n,_deleted:!0}:(delete e.views[r],e)}return await upsert(e,n,deltaFun),await abstractMapper$1(e).viewCleanup.apply(e),{ok:!0}}var K={};K.createIndex=resolveToCallback(async function(e){if(typeof e!=`object`)throw Error(`you must provide an index to create`);return(isRemote(this)?createIndex:createIndex$1)(this,e)}),K.find=resolveToCallback(async function(e){if(typeof e!=`object`)throw Error(`you must provide search parameters to find()`);return(isRemote(this)?find:find$1)(this,e)}),K.explain=resolveToCallback(async function(e){if(typeof e!=`object`)throw Error(`you must provide search parameters to explain()`);return(isRemote(this)?explain:explain$1)(this,e)}),K.getIndexes=resolveToCallback(async function(){return(isRemote(this)?getIndexes:getIndexes$1)(this)}),K.deleteIndex=resolveToCallback(async function(e){if(typeof e!=`object`)throw Error(`you must provide an index to delete`);return(isRemote(this)?deleteIndex:deleteIndex$1)(this,e)});function getConfigUrl(e){return(e?`/_node/`+e:``)+`/_config`}function wrapError(e){throw e.name===`unknown_error`&&(e.message=(e.message||``)+` Unknown error! Did you remember to enable CORS?`),e}function fetchJSON(e,t,n){return n=n||{},n.body&&(n.body=JSON.stringify(n.body)),n.headers=n.headers||new Bt,n.headers.set(`Content-Type`,`application/json`),n.headers.set(`Accept`,`application/json`),e(t,n).then(function(e){return e.ok?e.json():e.json().then(function(e){throw e})}).catch(wrapError)}function toCallback(e){return function(){for(var t=[],n=arguments.length;n--;)t[n]=arguments[n];if(typeof t[-1]==`function`){var r=t[-1];return e.apply(this,t.slice(0,-2)).then(function(e){return r(null,e)},function(e){return r(e)})}else return e.apply(this,t)}}var q=function(e){function AuthError(t){e.call(this,t),this.name=`authentication_error`,this.status=400,this.error=!0,Object.setPrototypeOf(this,AuthError.prototype)}return e&&(AuthError.__proto__=e),AuthError.prototype=Object.create(e&&e.prototype),AuthError.prototype.constructor=AuthError,AuthError}(Error),fn=toCallback(function(e){var t=this;e===void 0&&(e={});var n=`/_membership`,r=Object.assign({method:`GET`},e.ajax||{});return fetchJSON(t.fetch,n,r)}),getNodeName=function(e,t){return e.getMembership(t).then(function(e){return e.all_nodes[0]},function(e){if(e.error!==`illegal_database_name`)throw e})},pn=toCallback(function(e,t,n){var r=this;return n===void 0&&(n={}),[`http`,`https`].indexOf(r.type())===-1?Promise.reject(new q(`This plugin only works for the http/https adapter. So you should use new PouchDB("http://mysite.com:5984/mydb") instead.`)):e?t?getNodeName(r,n).then(function(i){var a=getConfigUrl(i),o=(n.configUrl||a)+`/admins/`+encodeURIComponent(e),s=Object.assign({method:`PUT`,body:t},n.ajax||{});return fetchJSON(r.fetch,o,s)}):Promise.reject(new q(`You must provide a password`)):Promise.reject(new q(`You must provide a username`))}),mn=toCallback(function(e,t){var n=this;return t===void 0&&(t={}),[`http`,`https`].indexOf(n.type())===-1?Promise.reject(new q(`This plugin only works for the http/https adapter. So you should use new PouchDB("http://mysite.com:5984/mydb") instead.`)):e?getNodeName(n,t).then(function(r){var i=getConfigUrl(r),a=(t.configUrl||i)+`/admins/`+encodeURIComponent(e),o=Object.assign({method:`DELETE`,processData:!1},t.ajax||{});return fetchJSON(n.fetch,a,o)}):Promise.reject(new q(`You must provide a username`))}),hn=`/_session`,gn=toCallback(function(e,t,n){var r=this;if(n===void 0&&(n={}),[`http`,`https`].indexOf(r.type())===-1)return Promise.reject(new q(`this plugin only works for the http/https adapter`));if(!e)return Promise.reject(new q(`you must provide a username`));if(!t)return Promise.reject(new q(`you must provide a password`));var i=hn,a=Object.assign({method:`POST`,body:{name:e,password:t}},n.ajax||{});return fetchJSON(r.fetch,i,a)}),_n=toCallback(function(e){var t=this;e===void 0&&(e={});var n=hn,r=Object.assign({method:`DELETE`},e.ajax||{});return fetchJSON(t.fetch,n,r)}),vn=toCallback(function(e){var t=this;e===void 0&&(e={});var n=hn,r=Object.assign({method:`GET`},e.ajax||{});return fetchJSON(t.fetch,n,r)}),yn=`/_users`;function updateUser(e,t,n){var r=[`_id`,`_rev`,`name`,`type`,`roles`,`password`,`password_scheme`,`iterations`,`derived_key`,`salt`];if(n.metadata){for(var i in n.metadata)if(n.metadata.hasOwnProperty(i)&&r.indexOf(i)!==-1)return Promise.reject(new q(`cannot use reserved word in metadata: "`+i+`"`));t=Object.assign(t,n.metadata)}n.roles&&(t=Object.assign(t,{roles:n.roles}));var a=yn+`/`+encodeURIComponent(t._id),o=Object.assign({method:`PUT`,body:t},n.ajax||{});return fetchJSON(e.fetch,a,o)}var bn=toCallback(function(e,t,n){var r=this;return n===void 0&&(n={}),[`http`,`https`].indexOf(r.type())===-1?Promise.reject(new q(`This plugin only works for the http/https adapter. So you should use new PouchDB("http://mysite.com:5984/mydb") instead.`)):e?t?updateUser(r,{name:e,password:t,roles:[],type:`user`,_id:`org.couchdb.user:`+e},n):Promise.reject(new q(`You must provide a password`)):Promise.reject(new q(`You must provide a username`))}),xn=toCallback(function(e,t){var n=this;if(t===void 0&&(t={}),!e)return Promise.reject(new q(`you must provide a username`));var r=yn+`/`+encodeURIComponent(`org.couchdb.user:`+e),i=Object.assign({method:`GET`},t.ajax||{});return fetchJSON(n.fetch,r,i).then(function(e){return console.log(e),e})}),Sn=toCallback(function(e,t){var n=this;return t===void 0&&(t={}),[`http`,`https`].indexOf(n.type())===-1?Promise.reject(new q(`This plugin only works for the http/https adapter. So you should use new PouchDB("http://mysite.com:5984/mydb") instead.`)):e?n.getUser(e,t).then(function(e){return updateUser(n,e,t)}):Promise.reject(new q(`You must provide a username`))}),Cn=toCallback(function(e,t){var n=this;return t===void 0&&(t={}),[`http`,`https`].indexOf(n.type())===-1?Promise.reject(new q(`This plugin only works for the http/https adapter. So you should use new PouchDB("http://mysite.com:5984/mydb") instead.`)):e?n.getUser(e,t).then(function(e){var r=yn+`/`+encodeURIComponent(e._id)+`?rev=`+e._rev,i=Object.assign({method:`DELETE`},t.ajax||{});return fetchJSON(n.fetch,r,i)}):Promise.reject(new q(`You must provide a username`))}),wn=toCallback(function(e,t,n){var r=this;return n===void 0&&(n={}),[`http`,`https`].indexOf(r.type())===-1?Promise.reject(new q(`This plugin only works for the http/https adapter. So you should use new PouchDB("http://mysite.com:5984/mydb") instead.`)):e?t?r.getUser(e,n).then(function(e){e.password=t;var i=yn+`/`+encodeURIComponent(e._id),a=Object.assign({method:`PUT`,body:e},n.ajax||{});return fetchJSON(r.fetch,i,a)}):Promise.reject(new q(`You must provide a password`)):Promise.reject(new q(`You must provide a username`))}),Tn=toCallback(function(e,t,n){var r=this,i=`org.couchdb.user:`,updateUser=function(e,t){var n=yn+`/`+encodeURIComponent(e._id),i=Object.assign({method:`PUT`,body:e},t.ajax);return fetchJSON(r.fetch,n,i)};return n===void 0&&(n={}),n.ajax=n.ajax||{},[`http`,`https`].indexOf(r.type())===-1?Promise.reject(new q(`This plugin only works for the http/https adapter. So you should use new PouchDB("http://mysite.com:5984/mydb") instead.`)):t?e?r.getUser(t,n).then(function(){var e=new q(`user already exists`);throw e.taken=!0,e},function(){return r.getUser(e,n)}).then(function(e){var r=clone(e);return delete r._rev,r._id=i+t,r.name=t,r.roles=n.roles||e.roles||{},updateUser(r,n).then(function(){return e._deleted=!0,updateUser(e,n)})}):Promise.reject(new q(`You must provide a username to rename`)):Promise.reject(new q(`You must provide a new username`))}),J={};J.login=gn,J.logIn=gn,J.logout=_n,J.logOut=_n,J.getSession=vn,J.getMembership=fn,J.signUpAdmin=pn,J.deleteAdmin=mn,J.signup=bn,J.signUp=bn,J.getUser=xn,J.putUser=Sn,J.deleteUser=Cn,J.changePassword=wn,J.changeUsername=Tn,typeof window<`u`&&window.PouchDB&&window.PouchDB.plugin(J);var En=t(n(((e,t)=>{var n=t.exports={},r,i;function defaultSetTimout(){throw Error(`setTimeout has not been defined`)}function defaultClearTimeout(){throw Error(`clearTimeout has not been defined`)}(function(){try{r=typeof setTimeout==`function`?setTimeout:defaultSetTimout}catch{r=defaultSetTimout}try{i=typeof clearTimeout==`function`?clearTimeout:defaultClearTimeout}catch{i=defaultClearTimeout}})();function runTimeout(e){if(r===setTimeout)return setTimeout(e,0);if((r===defaultSetTimout||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch{try{return r.call(null,e,0)}catch{return r.call(this,e,0)}}}function runClearTimeout(e){if(i===clearTimeout)return clearTimeout(e);if((i===defaultClearTimeout||!i)&&clearTimeout)return i=clearTimeout,clearTimeout(e);try{return i(e)}catch{try{return i.call(null,e)}catch{return i.call(this,e)}}}var a=[],o=!1,s,c=-1;function cleanUpNextTick(){!o||!s||(o=!1,s.length?a=s.concat(a):c=-1,a.length&&drainQueue())}function drainQueue(){if(!o){var e=runTimeout(cleanUpNextTick);o=!0;for(var t=a.length;t;){for(s=a,a=[];++c<t;)s&&s[c].run();c=-1,t=a.length}s=null,o=!1,runClearTimeout(e)}}n.nextTick=function(e){var t=Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];a.push(new Item(e,t)),a.length===1&&!o&&runTimeout(drainQueue)};function Item(e,t){this.fun=e,this.array=t}Item.prototype.run=function(){this.fun.apply(null,this.array)},n.title=`browser`,n.browser=!0,n.env={},n.argv=[],n.version=``,n.versions={};function noop(){}n.on=noop,n.addListener=noop,n.once=noop,n.off=noop,n.removeListener=noop,n.removeAllListeners=noop,n.emit=noop,n.prependListener=noop,n.prependOnceListener=noop,n.listeners=function(e){return[]},n.binding=function(e){throw Error(`process.binding is not supported`)},n.cwd=function(){return`/`},n.chdir=function(e){throw Error(`process.chdir is not supported`)},n.umask=function(){return 0}}))(),1);typeof window<`u`&&(window.process=En.default),I.plugin(K),I.plugin(J),I.debug!==void 0&&I.debug.disable(),I.defaults({});var Y=I,Dn,On=`coursedb-lookup`;p.debug(`COURSELOOKUP FILE RUNNING`);var kn=(Dn=class CourseLookup{static get _db(){if(this._dbInstance)return this._dbInstance;if(E.COUCHDB_SERVER_URL===`NOT_SET`||!E.COUCHDB_SERVER_URL)throw Error(`CourseLookup.db: COUCHDB_SERVER_URL is not set. Ensure initializeDataLayer has been called with valid configuration.`);if(E.COUCHDB_SERVER_PROTOCOL===`NOT_SET`||!E.COUCHDB_SERVER_PROTOCOL)throw Error(`CourseLookup.db: COUCHDB_SERVER_PROTOCOL is not set. Ensure initializeDataLayer has been called with valid configuration.`);let e=`${E.COUCHDB_SERVER_PROTOCOL}://${E.COUCHDB_SERVER_URL}/${On}`,t={};E.COUCHDB_USERNAME&&E.COUCHDB_PASSWORD?(t.auth={username:E.COUCHDB_USERNAME,password:E.COUCHDB_PASSWORD},p.info(`CourseLookup: Connecting to ${e} with authentication.`)):p.info(`CourseLookup: Connecting to ${e} without authentication.`);try{return this._dbInstance=new Y(e,t),p.info(`CourseLookup: Database instance created for ${On}.`),this._dbInstance}catch(t){throw p.error(`CourseLookup: Failed to create PouchDB instance for ${e}`,t),this._dbInstance=null,Error(`CourseLookup: Failed to initialize database connection: ${t instanceof Error?t.message:String(t)}`)}}static async add(e){return(await CourseLookup._db.post({name:e})).id}static async addWithId(e,t,n){let r={_id:e,name:t};n&&(r.disambiguator=n),await CourseLookup._db.put(r)}static async delete(e){let t=await CourseLookup._db.get(e);return await CourseLookup._db.remove(t)}static async allCourseWare(){return(await CourseLookup._db.allDocs({include_docs:!0})).rows.map(e=>e.doc)}static async updateDisambiguator(e,t){let n=await CourseLookup._db.get(e);return n.disambiguator=t,await CourseLookup._db.put(n)}static async isCourse(e){try{return await CourseLookup._db.get(e),!0}catch(e){return p.info(`Courselookup failed:`,e),!1}}},i(Dn,`_dbInstance`,null),Dn),Loggable=class{log(...e){console.log(`LOG-${this._className}@${new Date}:`,...e)}error(...e){console.error(`ERROR-${this._className}@${new Date}:`,...e)}},An={weight:1,confidence:.1,sampleSize:0};function computeOutcomeSignal(e,t={}){if(!e||e.length===0)return null;let n=t.targetAccuracy??.85,r=t.tolerance??.05,i=0;for(let t of e)t.isCorrect&&i++;return scoreAccuracyInZone(i/e.length,n,r)}function scoreAccuracyInZone(e,t,n){let r=Math.abs(e-t);if(r<=n)return 1;let i=r-n;return Math.max(0,1-i*2.5)}async function recordUserOutcome(e,t,n,r,i,a=0,o=0,s){let{user:c,course:l,userId:u}=e,d=l.getCourseID(),m=computeOutcomeSignal(r,s);if(m===null){p.debug(`[Orchestration] No outcome signal computed for ${u} (insufficient data). Skipping record.`);return}let h={};for(let t of i)h[t]=e.getDeviation(t);let g=`USER_OUTCOME::${d}::${u}::${n}`,_={_id:g,docType:D.USER_OUTCOME,courseId:d,userId:u,periodStart:t,periodEnd:n,outcomeValue:m,deviations:h,metadata:{sessionsCount:1,cardsSeen:r.length,eloStart:a,eloEnd:o,signalType:`accuracy_in_zone`}};try{await c.putUserOutcome(_),p.debug(`[Orchestration] Recorded outcome ${m.toFixed(3)} for ${u} (doc: ${g})`)}catch(e){p.error(`[Orchestration] Failed to record outcome: ${e}`)}}var jn=.1,Mn=.5,Nn=.1,Pn=3;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 Mn-Math.max(0,Math.min(1,e))*(Mn-jn)}function computeEffectiveWeight(e,t,n,r){let i=computeDeviation(t,n,r)*computeSpread(e.confidence)*e.weight,a=e.weight+i;return Math.max(Nn,Math.min(Pn,a))}async function createOrchestrationContext(e,t){let n;try{n=await t.getCourseConfig()}catch(e){p.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(),i=n.orchestration?.salt||`default_salt`;return{user:e,course:t,userId:r,courseConfig:n,getEffectiveWeight(e,t){return computeEffectiveWeight(t,r,e,i)},getDeviation(e){return computeDeviation(r,e,i)}}}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 mergeHints$1(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 i={};for(let e of t)for(let[t,n]of Object.entries(e.boostCards??{}))i[t]=(i[t]??1)*n;Object.keys(i).length>0&&(n.boostCards=i);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 a=t.map(e=>e._label).filter(Boolean);return a.length>0&&(n._label=a.join(`; `)),Object.keys(n).length>0?n:void 0}e(mergeHints$1,`mergeHints`);function logPipelineConfig(e,t){let n=t.length>0?`
11
+ - `+t.map(e=>e.name).join(`
12
+ - `):` none`;p.info(`[Pipeline] Configuration:\n Generator: ${e.name}\n Filters:${n}`)}function logTagHydration(e,t){let n=Array.from(t.values()).reduce((e,t)=>e+t.length,0),r=Array.from(t.values()).filter(e=>e.length>0).length;p.debug(`[Pipeline] Tag hydration: ${e.length} cards, ${r} have tags (${n} total tags) - single batch query`)}function logExecutionSummary(e,t,n,r,i,a){let o=i.length>0?i.map(e=>e.toFixed(2)).join(`, `):`none`,s=``;a.length>0&&(s=`\n Filter impact: ${a.map(e=>{let t=[];return e.boosted>0&&t.push(`+${e.boosted}`),e.penalized>0&&t.push(`-${e.penalized}`),e.passed>0&&t.push(`=${e.passed}`),`${e.name}: ${t.join(`/`)}`}).join(`, `)}`),p.info(`[Pipeline] Execution: ${e} produced ${t} → ${n} filters → ${r} results (top scores: ${o})`+s+`
13
+ 💡 Inspect: window.skuilder.pipeline`)}function logCardProvenance(e,t=3){let n=e.slice(0,t);p.debug(`[Pipeline] Provenance for top ${n.length} cards:`);for(let e of n){p.debug(`[Pipeline] ${e.cardId} (final score: ${e.score.toFixed(3)}):`);for(let t of e.provenance){let e=t.score.toFixed(3),n=t.action.padEnd(9);p.debug(`[Pipeline] ${n} ${e} - ${t.strategyName}: ${t.reason}`)}}}var Pipeline=class extends m{constructor(e,t,n,r){super(),i(this,`generator`,void 0),i(this,`filters`,void 0),i(this,`_cachedOrchestration`,null),i(this,`strategyHash`,void 0),i(this,`_tagCache`,new Map),i(this,`_ephemeralHints`,null),i(this,`_intakeClock`,null),i(this,`_intakeClockWrite`,Promise.resolve()),this.generator=e,this.filters=t,this.user=n,this.course=r,r.getCourseConfig().then(e=>{p.debug(`[pipeline] Crated pipeline for ${e.name}`)}).catch(e=>{p.error(`[pipeline] Failed to lookup courseCfg: ${e}`)}),logPipelineConfig(e,t),_(this)}setEphemeralHints(e){this._ephemeralHints=e,p.info(`[Pipeline] Ephemeral hints set: ${JSON.stringify(e)}`)}async getWeightedCards(e){let t=performance.now(),n=await this.buildContext(),r=performance.now();p.debug(`[Pipeline] Fetching 500 candidates from generator '${this.generator.name}'`);let i=await this.generator.getWeightedCards(500,n),a=i.cards,o=performance.now(),s=a.length;this._ephemeralHints=mergeHints$1([this._ephemeralHints,i.hints])??null;let l;if(this.generator.generators){let e=new Map;for(let t of a){let n=t.provenance[0];if(n){let r=n.strategyName;e.has(r)||e.set(r,{cards:[]}),e.get(r).cards.push(t)}}l=Array.from(e.entries()).map(([e,t])=>{let n=t.cards.filter(e=>e.reviewID).length;return{name:e,cardCount:t.cards.length,newCount:t.cards.length-n,reviewCount:n,topScore:Math.max(...t.cards.map(e=>e.score),0)}})}p.debug(`[Pipeline] Generator returned ${s} candidates`),a=await this.hydrateTags(a);let u=performance.now(),d=[...a],m=this._ephemeralHints;if(m?.requireCards?.length){let e=new Set(d.map(e=>e.cardId)),t=m.requireCards.filter(t=>!t.includes(`*`)&&!e.has(t));if(t.length>0){let e=await this.course.getAppliedTagsBatch(t),n=this.course.getCourseID();for(let r of t)d.push({cardId:r,courseId:n,score:1,tags:e.get(r)??[],provenance:[]});p.info(`[Pipeline] Pre-fetched ${t.length} required card(s) into pool: ${t.join(`, `)}`)}}let h=new Set(a.filter(e=>e.provenance.some(e=>e.strategy===`prescribed`)).map(e=>e.cardId)),_=[],y=new Map(a.map(e=>[e.cardId,e.score])),b=new Set;for(let e of this.filters){let t=a.length,r=new Map(a.map(e=>[e.cardId,e.score]));a=await e.transform(a,n);let i=0,o=0,s=0,c=t-a.length,l=e.kind??`gate`;for(let e of a){let t=r.get(e.cardId)??0;e.score>t?i++:e.score<t?(o++,l===`gate`&&b.add(e.cardId)):s++}if(_.push({name:e.name,kind:l,boosted:i,penalized:o,passed:s,removed:c}),h.size>0){let t=new Set(a.map(e=>e.cardId)),n=[...h].filter(e=>!t.has(e)),r=a.filter(e=>h.has(e.cardId)&&e.score===0).map(e=>e.cardId);(n.length>0||r.length>0)&&(p.info(`[Pipeline] Filter '${e.name}' impact on prescribed cards: `+(n.length>0?`removed=[${n.join(`, `)}] `:``)+(r.length>0?`zeroed=[${r.join(`, `)}]`:``)),n.forEach(e=>h.delete(e)))}p.debug(`[Pipeline] Filter '${e.name}': ${r.size} → ${a.length} cards (↑${i} ↓${o} =${s})`)}let x=a;a=a.filter(e=>e.score>0);let S=await this.regulate(a,y,b),C=this._ephemeralHints;C&&(this._ephemeralHints=null,a=this.applyHints(a,C,d)),a=c(a),a.sort((e,t)=>t.score-e.score);let w=performance.now(),T=a.slice(0,e);p.info(`[Pipeline:timing] total=${(w-t).toFixed(0)}ms (context=${(r-t).toFixed(0)} generate=${(o-r).toFixed(0)} hydrate=${(u-o).toFixed(0)} filter=${(w-u).toFixed(0)})`);let E=T.slice(0,3).map(e=>e.score);logExecutionSummary(this.generator.name,s,this.filters.length,T.length,E,_),logCardProvenance(T,3);try{let e=await this.course?.getCourseConfig().catch(()=>void 0),t=e?.name,r=v(this.course?.getCourseID()||`unknown`,t,this.generator.name,l,s,_,a,T,n.userElo,C??void 0,x,S),i={...this.strategyHash?{strategies:this.strategyHash}:{},...e?.contentVersion?{content:e.contentVersion}:{}};g({...r,...Object.keys(i).length?{versions:i}:{}})}catch(e){p.debug(`[Pipeline] Failed to capture debug run: ${e}`)}return{cards:T}}async hydrateTags(e){if(e.length===0)return e;let t=[];for(let n of e)this._tagCache.has(n.cardId)||t.push(n.cardId);if(t.length>0){let e=await this.course.getAppliedTagsBatch(t);for(let[t,n]of e)this._tagCache.set(t,n)}let n=new Map;for(let t of e)n.set(t.cardId,this._tagCache.get(t.cardId)??[]);return logTagHydration(e,n),e.map(e=>({...e,tags:this._tagCache.get(e.cardId)??[]}))}applyHints(e,t,n){let r=e.length;if(t.excludeCards?.length&&(e=e.filter(e=>!t.excludeCards.some(t=>globMatch(e.cardId,t)))),t.excludeTags?.length&&(e=e.filter(e=>!t.excludeTags.some(t=>cardMatchesTagPattern(e,t)))),t.boostTags)for(let[n,r]of Object.entries(t.boostTags))for(let i of e)cardMatchesTagPattern(i,n)&&(i.score*=r,i.provenance.push({strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:t._label?`Replan Hint (${t._label})`:`Replan Hint`,action:`boosted`,score:i.score,reason:`boostTag ${n} ×${r}`}));if(t.boostCards)for(let[n,r]of Object.entries(t.boostCards))for(let i of e)globMatch(i.cardId,n)&&(i.score*=r,i.provenance.push({strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:t._label?`Replan Hint (${t._label})`:`Replan Hint`,action:`boosted`,score:i.score,reason:`boostCard ${n} ×${r}`}));let i=new Set(e.map(e=>e.cardId)),a=new Map(e.map(e=>[e.cardId,e])),o=t._label?`Replan Hint (${t._label})`:`Replan Hint`,applyRequirement=(t,n)=>{let r=1/0,s=a.get(t.cardId);s?s.score<r&&(s.score=r,s.provenance.push({strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:o,action:`boosted`,score:r,reason:`${n} (upgrade to mandatory score)`})):(e.push({...t,score:r,provenance:[...t.provenance,{strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:o,action:`boosted`,score:r,reason:n}]}),i.add(t.cardId),a.set(t.cardId,e[e.length-1]))};if(t.requireCards?.length)for(let e of t.requireCards){for(let t of i)globMatch(t,e)&&applyRequirement(a.get(t),`requireCard ${e}`);for(let t of n)globMatch(t.cardId,e)&&applyRequirement(t,`requireCard ${e}`)}if(t.requireTags?.length)for(let e of t.requireTags){for(let t of i){let n=a.get(t);cardMatchesTagPattern(n,e)&&applyRequirement(n,`requireTag ${e}`)}for(let t of n)cardMatchesTagPattern(t,e)&&applyRequirement(t,`requireTag ${e}`)}return p.info(`[Pipeline] Hints applied: ${r} → ${e.length} cards`),e}async regulate(e,t,n){let r=ce,i=e.filter(e=>e.reviewID),a=e.filter(e=>!e.reviewID),o=a.filter(e=>!n.has(e.cardId)),s=se(i,t,r.reviewMass);oe(i,s),l(this.course.getCourseID(),{mass:s.urgency,healthyMass:r.reviewMass.healthyMass,rate:r.reviewMass.rate,multiplier:s.multiplier});let c=Date.now(),u=await this.loadIntakeClock(c),d=ae(u,c,o.length);d!==u&&this.saveIntakeClock(d);let m=ue(d,c,{eligibleNew:o.length,newCandidates:a.length},r.intake);return oe(o,m),p.info(`[Pipeline:regulators] review mass ${s.urgency.toFixed(1)} over ${i.length} due → ×${s.multiplier.toFixed(2)}; intake ${m.urgency.toFixed(1)}h, ${o.length}/${a.length} new eligible → ×${m.multiplier.toFixed(2)}`),[s,m]}notePresented(e){e.status!==`new`||e.courseId!==this.course?.getCourseID()||this.saveIntakeClock(ie(Date.now()))}async loadIntakeClock(e){if(this._intakeClock)return this._intakeClock;let t=null;try{t=await this.user.getStrategyState(this.course.getCourseID(),le)}catch(e){p.warn(`[Pipeline:regulators] Could not read the intake clock: ${e}`)}return t?this._intakeClock=t:this.saveIntakeClock(ie(e)),this._intakeClock}saveIntakeClock(e){this._intakeClock=e;let t=this.course.getCourseID();this._intakeClockWrite=this._intakeClockWrite.then(()=>this.user.putStrategyState(t,le,e)).catch(e=>p.warn(`[Pipeline:regulators] Could not save the intake clock: ${e}`))}async buildContext(){let e=1e3,t;try{t=o((await this.user.getCourseRegDoc(this.course.getCourseID())).elo),e=t.global.score}catch(e){p.debug(`[Pipeline] Could not get user ELO, using default: ${e}`)}this._cachedOrchestration||(this._cachedOrchestration=await createOrchestrationContext(this.user,this.course));let n=this._cachedOrchestration;return{user:this.user,course:this.course,userElo:e,...t?{userCourseElo:t}:{},orchestration:n}}getCourseID(){return this.course.getCourseID()}async getOrchestrationContext(){return createOrchestrationContext(this.user,this.course)}getStrategyIds(){let e=[],extractId=e=>e.strategyId?e.strategyId:null,t=extractId(this.generator);t&&e.push(t),this.generator.generators&&Array.isArray(this.generator.generators)&&this.generator.generators.forEach(t=>{let n=extractId(t);n&&e.push(n)});for(let t of this.filters){let n=extractId(t);n&&e.push(n)}return[...new Set(e)]}async getTagEloStatus(e){let t=o((await this.user.getCourseRegDoc(this.course.getCourseID())).elo),n={};if(e){let r=Array.isArray(e)?e:[e];for(let e of r){let r=globToRegex(e);for(let[e,i]of Object.entries(t.tags))r.test(e)&&(n[e]={score:i.score,count:i.count})}}else for(let[e,r]of Object.entries(t.tags))n[e]={score:r.score,count:r.count};return n}async forecast(e){let t=e?.threshold??.1,n=e?.unseenOnly??!0,r=this.course.getCourseID(),i=(await this.course.getAllCardIds()).map(e=>({cardId:e,courseId:r,score:1,provenance:[]}));i=await this.hydrateTags(i);let a=i.slice(),o=await this.buildContext();for(let e of this.forecastFilters())i=await e.transform(i,o);if(e?.hints&&(i=this.applyHints(i,e.hints,a)),i=i.filter(e=>e.score>=t),n){let e;try{e=new Set(await this.user.getSeenCards(r))}catch{e=new Set}i=i.filter(t=>!e.has(t.cardId))}return i.sort((e,t)=>t.score-e.score),e?.limit?i.slice(0,e.limit):i}forecastFilters(){return this.filters.filter(e=>!e.liveOnly)}async diagnoseCardSpace(e){let t=e?.threshold??.1,n=performance.now(),r=await this.course.getAllCardIds(),i=r.map(e=>({cardId:e,courseId:this.course.getCourseID(),score:1,provenance:[]}));i=await this.hydrateTags(i);let a=await this.buildContext(),o=[];for(let e of this.forecastFilters()){i=await e.transform(i,a);let n=i.filter(e=>e.score>=t).length;o.push({name:e.name,wellIndicated:n})}let s=i.filter(e=>e.score>=t),c=new Set(s.map(e=>e.cardId)),l;try{let e=this.course.getCourseID(),t=await this.user.getSeenCards(e);l=new Set(t)}catch{l=new Set}let u=s.filter(e=>!l.has(e.cardId)),d=new Map;for(let e of i){let n=e.cardId.split(`-`)[1]||`unknown`;d.has(n)||d.set(n,{total:0,wellIndicated:0,new:0});let r=d.get(n);r.total++,e.score>=t&&(r.wellIndicated++,l.has(e.cardId)||r.new++)}let m=performance.now()-n,h={totalCards:r.length,threshold:t,wellIndicated:c.size,encountered:l.size,wellIndicatedNew:u.length,byType:Object.fromEntries(d),filterBreakdown:o,elapsedMs:Math.round(m)};p.print(`[Pipeline:diagnose] Card space scan (${h.elapsedMs}ms):`),p.print(`[Pipeline:diagnose] Total cards: ${h.totalCards}`),p.print(`[Pipeline:diagnose] Well-indicated (score >= ${t}): ${h.wellIndicated}`),p.print(`[Pipeline:diagnose] Encountered: ${h.encountered}`),p.print(`[Pipeline:diagnose] Well-indicated & new: ${h.wellIndicatedNew}`),p.print(`[Pipeline:diagnose] By type:`);for(let[e,t]of d)p.print(`[Pipeline:diagnose] ${e}: ${t.wellIndicated}/${t.total} well-indicated, ${t.new} new`);p.print(`[Pipeline:diagnose] After each filter:`);for(let e of o)p.print(`[Pipeline:diagnose] ${e.name}: ${e.wellIndicated} well-indicated`);return h}},X=function(e){return e.MAX=`max`,e.AVERAGE=`average`,e.FREQUENCY_BOOST=`frequencyBoost`,e}({}),Fn=X.FREQUENCY_BOOST,In=.1;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 i={};for(let e of t)for(let[t,n]of Object.entries(e.boostCards??{}))i[t]=(i[t]??1)*n;Object.keys(i).length>0&&(n.boostCards=i);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 a=t.map(e=>e._label).filter(Boolean);return a.length>0&&(n._label=a.join(`; `)),Object.keys(n).length>0?n:void 0}var Ln=class CompositeGenerator extends m{constructor(e,t=Fn){if(super(),i(this,`name`,`Composite Generator`),i(this,`generators`,void 0),i(this,`aggregationMode`,void 0),this.generators=e,this.aggregationMode=t,e.length===0)throw Error(`CompositeGenerator requires at least one generator`);p.debug(`[CompositeGenerator] Created with ${e.length} generators, mode: ${t}`)}static async fromStrategies(e,t,n,r=Fn){return new CompositeGenerator(await Promise.all(n.map(n=>m.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,i=this.generators[t].name||`Generator ${t}`,a=n.filter(e=>e.provenance[0]?.reason?.includes(`new card`)),o=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=[];a.length>0&&t.push(`${a.length} new`),o.length>0&&t.push(`${o.length} reviews`);let s=t.length>0?t.join(`, `):`${n.length} cards`;r.push(`${i}: ${s} (top: ${e})`)}else r.push(`${i}: 0 cards`)}),p.info(`[Composite] Generator breakdown: ${r.join(` | `)}`);let i=new Map;n.forEach((e,n)=>{let r=e.cards,a=this.generators[n],o=a.learnable?.weight??1,s;if(a.learnable&&!a.staticWeight&&t.orchestration){let e=a.strategyId;e&&(o=t.orchestration.getEffectiveWeight(e,a.learnable),s=t.orchestration.getDeviation(e))}for(let e of r){e.provenance.length>0&&(e.provenance[0].effectiveWeight=o,e.provenance[0].deviation=s);let t=i.get(e.cardId)||[];t.push({card:e,weight:o}),i.set(e.cardId,t)}});let a=[];for(let[,e]of i){let t=e.map(e=>e.card),n=this.aggregateScores(e),r=Math.max(0,n),i=t.flatMap(e=>e.provenance),o=t[0].score,s=r>o?`boosted`:r<o?`penalized`:`passed`,c=this.buildAggregationReason(e,r);a.push({...t[0],score:r,provenance:[...i,{strategy:`composite`,strategyName:`Composite Generator`,strategyId:`COMPOSITE_GENERATOR`,action:s,score:r,reason:c}]})}return{cards:a.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,i=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 a=n.map(e=>e.provenance[0]?.strategy||`unknown`).join(`, `);switch(this.aggregationMode){case X.MAX:return`Max of ${r} generators (${a}): scores [${i}] → ${t.toFixed(2)}`;case X.AVERAGE:return`Weighted Avg of ${r} generators (${a}): scores [${i}] → ${t.toFixed(2)}`;case X.FREQUENCY_BOOST:{let n=e.reduce((e,t)=>e+t.weight,0),i=e.reduce((e,t)=>e+t.card.score*t.weight,0),o=n>0?i/n:0,s=1+In*(r-1);return`Frequency boost from ${r} generators (${a}): w-avg ${o.toFixed(2)} × ${s.toFixed(2)} → ${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 X.MAX:return Math.max(...t);case X.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 X.FREQUENCY_BOOST:{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+In*(e.length-1))}default:return t[0]}}};function createDefaultEloStrategy(e){return{_id:`NAVIGATION_STRATEGY-ELO-default`,docType:D.NAVIGATION_STRATEGY,name:`ELO (default)`,description:`Default ELO-based navigation strategy for new cards`,implementingClass:d.ELO,course:e,serializedData:``}}function createDefaultSrsStrategy(e){return{_id:`NAVIGATION_STRATEGY-SRS-default`,docType:D.NAVIGATION_STRATEGY,name:`SRS (default)`,description:`Default SRS-based navigation strategy for reviews`,implementingClass:d.SRS,course:e,serializedData:``}}function createDefaultEloDistanceStrategy(e){return{_id:`NAVIGATION_STRATEGY-eloDistance-default`,docType:D.NAVIGATION_STRATEGY,name:`ELO Distance (default)`,description:`Scales every candidate, new or review, by its distance from the learner's ELO`,implementingClass:d.ELO_DISTANCE,course:e,serializedData:JSON.stringify(me)}}function createDefaultPipeline(e,t){let n=t.getCourseID(),r=new Pipeline(new Ln([new fe(e,t,createDefaultEloStrategy(n)),new de(e,t,createDefaultSrsStrategy(n))]),[new pe(e,t,createDefaultEloDistanceStrategy(n))],e,t);return r.strategyHash=te,r}var Rn=[{key:`generate`,title:`Generate`,summary:`Each generator proposes candidates (up to 500 in all), scored on what is specific to its source. A card proposed by several generators keeps their mean score, raised 10% per extra generator.`},{key:`filter`,title:`Filter`,summary:`Each filter multiplies candidate scores, in the order shown. A gate says a card is not ready yet; a signal expresses preference. Gates usually penalize rather than remove, so a gated card stays in the pool at a low score.`},{key:`drop-zero`,title:`Drop zero scores`,summary:`Candidates whose score reached 0 leave the pool.`},{key:`regulate`,title:`Regulate`,summary:`Balances reviews against new cards. Review mass: the due reviews weighed by their filtered scores; above a healthy level, every review is lifted. Intake: hours since a new card was last presented; new cards no gate penalized are lifted, and the clock stops while there are none.`},{key:`hints`,title:`Apply hints`,summary:`The session's hints (from the app: an intro's follow-up, a difficulty boost) exclude, boost, or require cards. Required cards skip the filters entirely.`},{key:`diversity`,title:`Diversity re-rank`,summary:`Demotes candidates that repeat a distinctive tag already ranked above them, so one concept or answer cannot take the whole head of the queue. Sees this run only, not what the session already served.`},{key:`select`,title:`Select`,summary:`Highest scores first, up to the run's limit. The session mixes them into its supply queue.`}];function planned(e,t,n){let r=t===y.FILTER?h(e.implementingClass):void 0;return{role:t,origin:n,name:e.name,implementingClass:e.implementingClass,strategy:e,...r?{kind:r}:{}}}function planPipeline(e,t){if(e.length===0)return{kind:`default`,generators:[planned(createDefaultEloStrategy(t),y.GENERATOR,`default-pipeline`),planned(createDefaultSrsStrategy(t),y.GENERATOR,`default-pipeline`)],filters:[planned(createDefaultEloDistanceStrategy(t),y.FILTER,`default-pipeline`)],skipped:[],warnings:[],notes:[],regulators:ce};let n=[],r=[],i=[],a=[];for(let t of e)u(t.implementingClass)?n.push(planned(t,y.GENERATOR,`strategy-doc`)):b(t.implementingClass)?r.push(planned(t,y.FILTER,`strategy-doc`)):(i.push({strategy:t,reason:`not a registered generator or filter`}),a.push(`Unknown strategy type '${t.implementingClass}', skipping: ${t.name}`));let o=new Set(n.map(e=>e.implementingClass));o.has(createDefaultEloStrategy(t).implementingClass)||n.push(planned(createDefaultEloStrategy(t),y.GENERATOR,`assembler-default`)),o.has(createDefaultSrsStrategy(t).implementingClass)||n.push(planned(createDefaultSrsStrategy(t),y.GENERATOR,`assembler-default`));let s=createDefaultEloDistanceStrategy(t);return r.some(e=>e.implementingClass===s.implementingClass)||r.push(planned(s,y.FILTER,`assembler-default`)),r.sort((e,t)=>e.name.localeCompare(t.name)),{kind:`assembled`,generators:n,filters:r,skipped:i,warnings:a,notes:[],regulators:ce}}function areQuestionRecords(e){return isQuestionRecord(e.records[0])}function isQuestionRecord(e){return e.userAnswer!==void 0}function getCardHistoryID(e,t){return`${O[D.CARDRECORD]}-${e}-${t}`}var zn=r.duration,Bn=1200*60;function newInterval(e,t){return areQuestionRecords(t)?newQuestionInterval(e,t):1e5}function newQuestionInterval(e,t){let n=t.records,r=n[n.length-1],i=lastSuccessfulInterval(n);if(i>t.bestInterval&&(t.bestInterval=i,e.update(t._id,{bestInterval:i}).catch(e=>{p.warn(`[SpacedRepetition] Failed to update bestInterval for ${t._id}: ${e?.message??e}`)})),r.isCorrect){let e=r.performance,n=isTaggedPerformance(e)?e._global:e,a=Math.min(1,Math.max(0,n));p.debug(`Demontrated skill: \t${a}`);let o=i*(.75+a);t.lapses=getLapses(t.records),t.streak=getStreak(t.records);let s=o;return t.lapses&&t.streak&&t.bestInterval&&(t.lapses>=0||t.streak>=0)&&(s=(t.lapses*o+t.streak*t.bestInterval)/(t.lapses+t.streak),p.debug(`Weighted average interval calculation:
14
+ \t(${t.lapses} * ${o} + ${t.streak} * ${t.bestInterval}) / (${t.lapses} + ${t.streak}) = ${s}`)),r.fluent===!1?(p.debug(`Correct but not fluent: capping interval ${s}s at ${Bn}s`),Math.min(s,Bn)):s}else return 0}function lastSuccessfulInterval(e){for(let t=e.length-1;t>=1;t--)if(e[t].priorAttemps===0&&e[t].isCorrect&&e[t].fluent!==!1){let n=secondsBetween(e[t-1].timeStamp,e[t].timeStamp),r=Math.max(n,1200*60);return p.debug(`Last interval w/ this card was: ${n}s, returning ${r}s`),r}return getInitialInterval(e)}function getStreak(e){let t=0,n=e.length-1;for(;n>=0&&e[n].isCorrect;)n--,t++;return t}function getLapses(e){return e.filter(e=>e.isCorrect===!1).length}function getInitialInterval(e){return p.warn(`history of length: ${e.length} ignored!`),3600*24*3}function secondsBetween(e,t){return e=r(e),t=r(t),zn(t.diff(e)).asSeconds()}var Vn=t(_e(),1);function getAppDataDirectory(){return E.LOCAL_STORAGE_PREFIX?Vn.join(Vn.homedir(),`.tuilder`,E.LOCAL_STORAGE_PREFIX):Vn.join(Vn.homedir(),`.tuilder`)}async function ensureAppDataDirectory(){let e=getAppDataDirectory();try{await Vn.promises.mkdir(e,{recursive:!0})}catch(t){if(t.code!==`EEXIST`)throw Error(`Failed to create app data directory ${e}: ${t.message}`)}return e}function getDbPath(e){return Vn.join(getAppDataDirectory(),e)}async function initializeDataDirectory(){await ensureAppDataDirectory(),p.info(`PouchDB data directory initialized: ${getAppDataDirectory()}`)}var UpdateQueue=class extends Loggable{update(e,t){return p.debug(`Update requested on doc: ${e}`),this.pendingUpdates[e]?this.pendingUpdates[e].push(t):this.pendingUpdates[e]=[t],this.applyUpdates(e)}constructor(e,t){super(),i(this,`_className`,`UpdateQueue`),i(this,`pendingUpdates`,{}),i(this,`inprogressUpdates`,{}),i(this,`readDB`,void 0),i(this,`writeDB`,void 0),this.readDB=e,this.writeDB=t||e,p.debug(`UpdateQ initialized...`),this.readDB.info().then(e=>{p.debug(`db info: ${JSON.stringify(e)}`)})}async applyUpdates(e){if(p.debug(`Applying updates on doc: ${e}`),this.inprogressUpdates[e]){for(;this.inprogressUpdates[e];)await new Promise(e=>setTimeout(e,Math.random()*50));return this.applyUpdates(e)}else if(this.pendingUpdates[e]&&this.pendingUpdates[e].length>0){this.inprogressUpdates[e]=!0;for(let t=0;t<5;t++)try{let t={...await this.readDB.get(e)},n=[...this.pendingUpdates[e]];for(let e of n)t=typeof e==`function`?{...t,...e(t)}:{...t,...e};if(await this.writeDB.put(t),this.pendingUpdates[e].splice(0,n.length),this.pendingUpdates[e].length===0)this.inprogressUpdates[e]=!1,delete this.inprogressUpdates[e];else return this.applyUpdates(e);return t}catch(n){if(n.name===`conflict`&&t<4)p.warn(`Conflict on update for doc ${e}, retry #${t+1}`),await new Promise(e=>setTimeout(e,50*Math.random()));else if(n.name===`not_found`&&t===0)throw p.warn(`Update failed for ${e} - does not exist. Throwing to caller.`),delete this.inprogressUpdates[e],n;else throw delete this.inprogressUpdates[e],this.pendingUpdates[e]&&delete this.pendingUpdates[e],p.error(`Error on attemped update (retry ${t}): ${JSON.stringify(n)}`),n}throw Error(`UpdateQueue failed for doc ${e} after 5 retries.`)}else throw Error(`Empty Updates Queue Triggered`)}},Hn={};async function GET_CACHED(e,t){return Hn[e]?Hn[e]:(Hn[e]=t?await t(e):await GET_ITEM(e),GET_CACHED(e))}async function GET_ITEM(e){throw Error(`No implementation found for GET_CACHED(${e})`)}var WeightedFilter=class{constructor(e,t=An,n=!1,r){i(this,`name`,void 0),i(this,`kind`,void 0),i(this,`liveOnly`,void 0),i(this,`inner`,void 0),i(this,`learnable`,void 0),i(this,`staticWeight`,void 0),i(this,`strategyId`,void 0),this.inner=e,this.name=e.name,this.kind=e.kind,this.liveOnly=e.liveOnly,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 i=new Map;for(let t of e)i.set(t.cardId,t.score);return(await this.inner.transform(e,t)).map(e=>{let t=i.get(e.cardId);if(t===void 0||t===0||e.score===0)return e;let a=e.score/t;if(Math.abs(a-1)<1e-4)return e;let o=t*a**+n,s=e.provenance.length-1,c=e.provenance[s];if(c){let t=[...e.provenance];return t[s]={...c,score:o,effectiveWeight:n,deviation:r},{...e,score:o,provenance:t}}return{...e,score:o}})}},PipelineAssembler=class{async assemble(e){let{strategies:t,user:n,course:r}=e,i=[];if(t.length===0)return{pipeline:null,generatorStrategies:[],filterStrategies:[],warnings:i};let a=planPipeline(t,r.getCourseID());i.push(...a.warnings);for(let e of[...a.generators,...a.filters])e.origin===`assembler-default`&&p.debug(`[PipelineAssembler] No ${e.implementingClass} ${e.role} configured, adding default`);let o=a.generators.map(e=>e.strategy),s=a.filters.map(e=>e.strategy);if(o.length===0)return i.push(`No generator strategy found`),{pipeline:null,generatorStrategies:[],filterStrategies:[],warnings:i};let c;o.length===1?(c=await m.create(n,r,o[0]),p.debug(`[PipelineAssembler] Using single generator: ${o[0].name}`)):(p.debug(`[PipelineAssembler] Using CompositeGenerator for ${o.length} generators: ${o.map(e=>e.name).join(`, `)}`),c=await Ln.fromStrategies(n,r,o));let l=[];for(let e of s)try{let t=await m.create(n,r,e);if(`transform`in t&&typeof t.transform==`function`){let n=t;e.learnable&&(n=new WeightedFilter(n,e.learnable,e.staticWeight,e._id)),l.push(n),p.debug(`[PipelineAssembler] Added filter: ${e.name}`)}else i.push(`Filter '${e.name}' does not implement CardFilter.transform(), skipping`)}catch(t){i.push(`Failed to instantiate filter '${e.name}': ${t}`)}let u=new Pipeline(c,l,n,r);return u.strategyHash=w(t),p.debug(`[PipelineAssembler] Assembled pipeline with ${o.length} generator(s) and ${l.length} filter(s)`),{pipeline:u,generatorStrategies:o,filterStrategies:s,warnings:i}}},Un=e(e=>{p.info(e)},`log`);function getLocalUserDB(e){let t=`userdb-${e}`;return typeof window>`u`?new Y(getDbPath(t),{}):new Y(t,{})}function scheduleCardReviewLocal(e,t){let n=r.utc();p.info(`Scheduling for review in: ${t.time.diff(n,`h`)/24} days`),e.put({_id:x(t.time),cardId:t.card_id,reviewTime:t.time.toISOString(),courseId:t.course_id,scheduledAt:n.toISOString(),scheduledFor:t.scheduledFor,schedulingAgentId:t.schedulingAgentId})}async function removeScheduledCardReviewLocal(e,t){let n=await e.get(t);e.remove(n).then(e=>{e.ok&&Un(`Removed Review Doc: ${t}`)}).catch(e=>{Un(`Failed to remove Review Doc: ${t},\n${JSON.stringify(e)}`)})}var UsrCrsData=class{constructor(e,t){i(this,`user`,void 0),i(this,`_courseId`,void 0),this.user=e,this._courseId=t}async getReviewsForcast(e){let t=r.utc().add(e,`days`);return this.getReviewstoDate(t)}async getPendingReviews(){let e=r.utc();return this.getReviewstoDate(e)}async getScheduledReviewCount(){return(await this.getPendingReviews()).length}async getCourseSettings(){let e=(await this.user.getCourseRegistrationsDoc()).courses.find(e=>e.courseID===this._courseId);return e&&e.settings?e.settings:(p.warn(`no settings found during lookup on course ${this._courseId}`),{})}updateCourseSettings(e){`updateCourseSettings`in this.user&&this.user.updateCourseSettings(this._courseId,e)}async getStrategyState(e){return this.user.getStrategyState(this._courseId,e)}async putStrategyState(e,t){return this.user.putStrategyState(this._courseId,e,t)}async deleteStrategyState(e){return this.user.deleteStrategyState(this._courseId,e)}async getReviewstoDate(e){let t=await this.user.getPendingReviews(this._courseId);return p.debug(`Fetching ${this.user.getUsername()}'s scheduled reviews for course ${this._courseId}.`),t.filter(t=>{let n=r.utc(t.reviewTime);return e.isAfter(n)})}};function buildStrategyStateId(e,t){return`STRATEGY_STATE::${e}::${t}`}var Wn=`_local/hydration`,Z,Q=e(e=>{p.info(e)},`log`),Gn=15e3;function withTimeout(e,t,n){let r;return Promise.race([e,new Promise((e,i)=>{r=setTimeout(()=>i(Error(`${n} timed out after ${t}ms`)),t)})]).finally(()=>{r!==void 0&&clearTimeout(r)})}var Kn=(Z=class BaseUser{static Dummy(e){return new BaseUser(`Me`,e)}getUsername(){return this._username}isLoggedIn(){return!this._username.startsWith(S)}remote(){return this.remoteDB}hydrationStatus(){return{...this._hydration}}async awaitHydration(){try{await this._hydrationPromise}catch{}return this.hydrationStatus()}canMaterializeDefaults(){return this._hydration.state!==`failed`&&this._hydration.state!==`hydrating`}async createAccount(e,t){if(!this.syncStrategy.canCreateAccount())throw Error(`Account creation not supported by current sync strategy`);if(!this._username.startsWith(`sk-guest-`))throw Error(`Cannot create a new account while logged in:
15
+ Currently logged-in as ${this._username}.`);let n=await this.syncStrategy.createAccount(e,t);if(n.status===k.ok){Q(`Account created successfully, updating username to ${e}`),this._username=e;try{localStorage.removeItem(`sk-guest-uuid`)}catch(e){p.warn(`localStorage not available (Node.js environment):`,e)}await this.init()}return{status:n.status,error:n.error||``}}async login(e,t){if(!this.syncStrategy.canAuthenticate())throw Error(`Authentication not supported by current sync strategy`);if(!this._username.startsWith(`sk-guest-`)&&this._username!=e){if(this._username!=e)throw Error(`Cannot change accounts while logged in.
16
+ Log out of account ${this.getUsername()} before logging in as ${e}.`);p.warn(`User ${this._username} is already logged in, but executing login again.`)}let n=await this.syncStrategy.authenticate(e,t);if(n.ok){Q(`Logged in as ${e}`),this._username=e;try{localStorage.removeItem(`sk-guest-uuid`)}catch(e){p.warn(`localStorage not available (Node.js environment):`,e)}await this.init()}return n}async adoptSession(e){if(!this.syncStrategy.canAuthenticate()||!this.syncStrategy.adoptSession)throw Error(`Session adoption not supported by current sync strategy`);let t=this._username.startsWith(`sk-guest-`)?this._username:void 0;if(!t)throw Error(`Cannot adopt a session while logged in.
17
+ Log out of account ${this.getUsername()} first.`);let n=await this.syncStrategy.adoptSession(e.migrateGuestData?t:void 0);if(n.ok&&n.username){Q(`Adopted session for ${n.username}`),this._username=n.username;try{localStorage.removeItem(`sk-guest-uuid`)}catch(e){p.warn(`localStorage not available (Node.js environment):`,e)}await this.init()}return n}async resetUserData(){if(this.syncStrategy.canAuthenticate())return{status:k.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(O[D.CARDRECORD])||t.startsWith(O[D.SCHEDULED_CARD])||t.startsWith(O[D.STRATEGY_STATE])||t.startsWith(O[D.USER_OUTCOME])||t.startsWith(O[D.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:k.ok}}catch(e){return p.error(`Failed to reset user data:`,e),{status:k.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();try{localStorage.removeItem(`sk-guest-uuid`)}catch(e){p.warn(`localStorage not available (Node.js environment):`,e)}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(){p.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){if(!this.canMaterializeDefaults())throw Error(`Cannot read course registrations for ${this._username}: the local mirror is unavailable (hydration state '${this._hydration.state}'). Refusing to create an empty registration doc — that would report an existing user as unregistered, and then lose to their real document once sync resumes.`);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=ne(O[D.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 p.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&&(p.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){p.error(`Error processing history item:`,e)}return p.debug(`Found ${t.length} activity records`),t}catch(e){return p.error(`Error in getActivityRecords:`,e),[]}}async getReviewstoDate(e,t){let n=ne(O[D.SCHEDULED_CARD]),i=await this.remoteDB.allDocs({startkey:n.startkey,endkey:n.endkey,include_docs:!0});return Q(`Fetching ${this._username}'s scheduled reviews${t?` for course ${t}`:``}.`),i.rows.filter(n=>{if(n.id.startsWith(O[D.SCHEDULED_CARD])){let i=r.utc(n.id.substr(O[D.SCHEDULED_CARD].length),re);if(e.isAfter(i)&&(t===void 0||n.doc.courseId===t))return!0}}).map(e=>e.doc)}async getReviewsForcast(e,t){let n=r.utc().add(e,`days`);return this.getReviewstoDate(n,t)}async getPendingReviews(e){let t=r.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`;p.debug(`Registering for ${e} with status: ${r}`);let i={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===i.courseID).length===0?(Q(`It's a new course registration!`),n.courses.push(i),n.studyWeight[e]=1):n.courses.forEach(t=>{Q(`Found the previously registered course!`),t.courseID===e&&(t.status=r)}),this.localDB.put(n)}).catch(e=>{throw Q(`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 p.debug(`Raw config from DB:`,e),e}catch(t){let n=t;if(n.name&&n.name===`not_found`){if(!this.canMaterializeDefaults())throw Error(`Cannot read config for ${this._username}: the local mirror is unavailable (hydration state '${this._hydration.state}'). Refusing to write a default config over what may be an existing one.`);return await this.localDB.put(e),this.getConfig()}else throw p.error(`Error setting user default config:`,t),Error(`Error returning the user's configuration: ${JSON.stringify(t)}`)}}async setConfig(e){p.debug(`Setting Config items ${JSON.stringify(e)}`);let t=await this.getConfig(),n=await this.localDB.put({...t,...e});n.ok?p.debug(`Config items set: ${JSON.stringify(e)}`):p.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){i(this,`_username`,void 0),i(this,`syncStrategy`,void 0),i(this,`localDB`,void 0),i(this,`remoteDB`,void 0),i(this,`writeDB`,void 0),i(this,`updateQueue`,void 0),i(this,`_hydration`,{state:`not-required`}),i(this,`_hydrationPromise`,null),i(this,`_hydratedSeq`,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.syncStrategy.stopSync?.(),this.setDBandQ(),this._hydrationPromise=this.hydrateLocalMirror(),await this._hydrationPromise,this.syncStrategy.startSync(this.localDB,this.remoteDB,this._hydratedSeq),this.applyDesignDocs().catch(e=>{Q(`Error in applyDesignDocs background task: ${e}`),e&&typeof e==`object`&&Q(`Full error details in applyDesignDocs: ${JSON.stringify(e)}`)}),this.deduplicateReviews().catch(e=>{Q(`Error in deduplicateReviews background task: ${e}`),e&&typeof e==`object`&&Q(`Full error details in background task: ${JSON.stringify(e)}`)}),BaseUser._initialized=!0}async hydrateLocalMirror(){if(this._hydratedSeq=void 0,this.localDB.name===this.remoteDB.name||!this.syncStrategy.hydrate){this._hydration={state:`not-required`};return}if(await this.hasHydrationMarker()){this._hydration={state:`stale`};return}this._hydration={state:`hydrating`};let e=Date.now();try{let{docsWritten:t,lastSeq:n}=await withTimeout(this.syncStrategy.hydrate(this.localDB,this.remoteDB),Gn,`Hydration of local mirror for ${this._username}`);this._hydratedSeq=n,await this.writeHydrationMarker(),this._hydration={state:`hydrated`,docsWritten:t,durationMs:Date.now()-e},Q(`Hydrated local mirror for ${this._username}: ${t} docs in ${this._hydration.durationMs}ms`)}catch(t){this.syncStrategy.stopSync?.(),this._hydration={state:`failed`,durationMs:Date.now()-e,error:t instanceof Error?t.message:String(t)},p.error(`Failed to hydrate local mirror for ${this._username}:`,t)}}async hasHydrationMarker(){try{return(await this.localDB.get(Wn)).username===this._username}catch{return!1}}async writeHydrationMarker(){try{let e;try{e=(await this.localDB.get(Wn))._rev}catch{}await this.localDB.put({_id:Wn,_rev:e,username:this._username,hydratedAt:new Date().toISOString()})}catch(e){p.warn(`Could not write hydration marker for ${this._username}: ${e}`)}}async applyDesignDocs(){if(Q(`Starting applyDesignDocs for user: ${this._username}`),Q(`Remote DB name: ${this.remoteDB.name||`unknown`}`),this._username===`admin`){Q(`Skipping design docs for admin user`);return}Q(`Applying ${BaseUser.designDocs.length} design docs`);for(let e of BaseUser.designDocs){Q(`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?.name===`not_found`)await this.remoteDB.put(e);else throw t}}catch(t){if(t.name&&t.name===`conflict`)p.warn(`Design doc ${e._id} update conflict - will retry`),await new Promise(e=>setTimeout(e,1e3)),await this.applyDesignDoc(e);else throw p.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?.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=r.utc(e.timeStamp).toString();try{let n=await this.update(t,function(t){return t.records.push(e),t.bestInterval=t.bestInterval||0,areQuestionRecords(t)?(t.lapses=getLapses(t.records),t.streak=getStreak(t.records)):(t.lapses=t.lapses||0,t.streak=t.streak||0),t});return n.records=n.records.map(e=>{let t={...e};return t.timeStamp=r.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:
18
+ name:${r.name}
19
+ error: ${r.error}
20
+ message: ${r.message}`)}}async deduplicateReviews(){try{Q(`Starting deduplication of scheduled reviews...`),Q(`Remote DB name: ${this.remoteDB.name||`unknown`}`),Q(`Write DB name: ${this.writeDB.name||`unknown`}`);let e={},t=[];Q(`Attempting to query remoteDB for reviewCards/reviewCards. Database: ${this.remoteDB.name||`unknown`}`);let n=await this.remoteDB.query(`reviewCards/reviewCards`);if(Q(`Found ${n.rows.length} scheduled reviews to process`),n.rows.forEach(n=>{let r=n.value,i=n.key;e[r]?(Q(`Found duplicate scheduled review for card: ${r}`),Q(`Marking earlier review ${e[r]} for deletion, keeping ${i}`),t.push(e[r]),e[r]=i):e[r]=i}),t.length>0){Q(`Removing ${t.length} duplicate reviews...`);let e=t.map(async e=>{try{let t=await this.remoteDB.get(e);await this.writeDB.remove(t),Q(`Successfully removed duplicate review: ${e}`)}catch(t){Q(`Failed to remove duplicate review ${e}: ${t}`)}});await Promise.all(e),Q(`Deduplication complete. Processed ${t.length} duplicates`)}else Q(`No duplicate reviews found`)}catch(e){Q(`Error during review deduplication: ${e}`),e&&typeof e==`object`&&`status`in e&&e.status===404&&(Q(`Database not found (404) during review deduplication. Database: ${this.remoteDB.name||`unknown`}`),Q(`This might indicate the user database doesn't exist or the reviewCards view isn't available`)),e&&typeof e==`object`&&Q(`Full error details: ${JSON.stringify(e)}`)}}async getSeenCards(e){let t=O[D.CARDRECORD];e&&(t+=`-${e}-`);let n=await ee(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 ee(this.remoteDB,O[D.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:
21
+ 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 p.error(`Database error in getOrCreateClassroomRegistrationsDoc (private method):`,e),Error(`Database error accessing classroom registrations: ${n.message||n.name||`Unknown error`} (status: ${n.status})`)}}return p.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 p.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){if(!this.canMaterializeDefaults())throw Error(`Cannot read strategy state '${t}' for ${this._username}: the local mirror is unavailable (hydration state '${this._hydration.state}').`);return null}throw e}}async putStrategyState(e,t,n){let r=buildStrategyStateId(e,t),i;try{i=(await this.localDB.get(r))._rev}catch(e){if(e.status!==404)throw e}let a={_id:r,_rev:i,docType:D.STRATEGY_STATE,courseId:e,strategyKey:t,data:n,updatedAt:new Date().toISOString()};await this.localDB.put(a)}async putStudySession(e){try{await this.localDB.put(e)}catch(t){if(t.status===409){let t=await this.localDB.get(e._id);await this.localDB.put({...e,_rev:t._rev})}else throw t}}async getStudySessions(e){let t=ne(e?`${O[D.STUDY_SESSION]}::${e}::`:`${O[D.STUDY_SESSION]}::`);return(await this.localDB.allDocs({startkey:t.startkey,endkey:t.endkey,include_docs:!0})).rows.map(e=>e.doc).filter(e=>!!e).sort((e,t)=>t.startTime.localeCompare(e.startTime))}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}}},i(Z,`_instance`,void 0),i(Z,`_initialized`,!1),i(Z,`DOC_IDS`,{CONFIG:`CONFIG`,COURSE_REGISTRATIONS:`CourseRegistrations`,CLASSROOM_REGISTRATIONS:`ClassroomRegistrations`}),i(Z,`designDocs`,[{_id:`_design/reviewCards`,views:{reviewCards:{map:`function (doc) {
22
+ if (doc._id && doc._id.indexOf('card_review') === 0 && doc.courseId && doc.cardId) {
23
+ emit(doc._id, doc.courseId + '-' + doc.cardId);
24
+ }
25
+ }`}}}]),Z);function accomodateGuest(){if(p.log(`[funnel] accomodateGuest() called`),typeof localStorage>`u`)return p.log(`[funnel] localStorage not available (Node.js environment), returning default guest`),{username:S+`nodejs-test`,firstVisit:!0};let e=`sk-guest-uuid`,t,n=localStorage.getItem(e);if(p.log(`[funnel] Checking localStorage for key:`,e),p.log(`[funnel] Existing UUID value:`,n),p.log(`[funnel] existingUUID !== null:`,n!==null),n!==null)t=!1,p.log(`[funnel] Returning guest ${n} "logging in".`);else{t=!0,p.log(`[funnel] No existing UUID, generating new one...`);let n=generateUUID();p.log(`[funnel] Generated UUID:`,n),p.log(`[funnel] UUID length:`,n.length);try{localStorage.setItem(e,n),p.log(`[funnel] Successfully stored UUID in localStorage`);let t=localStorage.getItem(e);p.log(`[funnel] Verification read from localStorage:`,t)}catch(e){p.error(`[funnel] ERROR storing UUID:`,e)}p.log(`[funnel] Accommodating a new guest with account: ${n}`)}let r=localStorage.getItem(e),i=S+r;return p.log(`[funnel] Final UUID from localStorage:`,r),p.log(`[funnel] GuestUsername constant:`,S),p.log(`[funnel] Final username to return:`,i),{username:i,firstVisit:t};function generateUUID(){if(p.log(`[funnel] Inside generateUUID()`),typeof crypto<`u`&&typeof crypto.randomUUID==`function`){let e=crypto.randomUUID();return p.log(`[funnel] Generated UUID using crypto.randomUUID():`,e),e}if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[Array.from(e.slice(0,4)).map(e=>e.toString(16).padStart(2,`0`)).join(``),Array.from(e.slice(4,6)).map(e=>e.toString(16).padStart(2,`0`)).join(``),Array.from(e.slice(6,8)).map(e=>e.toString(16).padStart(2,`0`)).join(``),Array.from(e.slice(8,10)).map(e=>e.toString(16).padStart(2,`0`)).join(``),Array.from(e.slice(10,16)).map(e=>e.toString(16).padStart(2,`0`)).join(``)].join(`-`);return p.log(`[funnel] Generated UUID using crypto.getRandomValues():`,t),t}p.warn(`[funnel] crypto API not available, using timestamp-based UUID (NOT SECURE)`);let e=new Date().getTime();typeof performance<`u`&&typeof performance.now==`function`&&(e+=performance.now());let t=`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,t=>{let n=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(t===`x`?n:n&3|8).toString(16)});return p.log(`[funnel] Generated UUID (fallback):`,t),t}}var qn=`CourseRegistrations`,Jn=`ClassroomRegistrations`;async function getOrCreateClassroomRegistrationsDoc(e){let t;try{t=await getLocalUserDB(e).get(Jn)}catch(n){let r=n;if(r.status===404)await getLocalUserDB(e).put({_id:Jn,registrations:[]}),t=await getOrCreateClassroomRegistrationsDoc(e);else{let e={name:r.name,status:r.status,message:r.message,reason:r.reason,error:r.error};throw p.error(`Database error in getOrCreateClassroomRegistrationsDoc (standalone function):`,e),Error(`Database error accessing classroom registrations: ${r.message||r.name||`Unknown error`} (status: ${r.status})`)}}return t}async function getOrCreateCourseRegistrationsDoc(e){let t;try{t=await getLocalUserDB(e).get(qn)}catch(n){if(n.status===404)await getLocalUserDB(e).put({_id:qn,courses:[],studyWeight:{}}),t=await getOrCreateCourseRegistrationsDoc(e);else throw Error(`Unexpected error ${JSON.stringify(n)} in getOrCreateCourseRegistrationDoc...`)}return t}async function updateUserElo(e,t,n){let r=await getOrCreateCourseRegistrationsDoc(e),i=r.courses.find(e=>e.courseID===t);return i.elo=n,getLocalUserDB(e).put(r)}async function registerUserForClassroom(e,t,n){return Q(`Registering user: ${e} in course: ${t}`),getOrCreateClassroomRegistrationsDoc(e).then(r=>{let i={classID:t,registeredAs:n};return r.registrations.filter(e=>e.classID===i.classID&&e.registeredAs===i.registeredAs).length===0?r.registrations.push(i):Q(`User ${e} is already registered for class ${t}`),getLocalUserDB(e).put(r)})}async function dropUserFromClassroom(e,t){return getOrCreateClassroomRegistrationsDoc(e).then(n=>{let r=-1;for(let e=0;e<n.registrations.length;e++)n.registrations[e].classID===t&&(r=e);return r!==-1&&n.registrations.splice(r,1),getLocalUserDB(e).put(n)})}async function getUserClassrooms(e){return getOrCreateClassroomRegistrationsDoc(e)}var Yn=`classdb-lookup`,Xn=`ClassroomConfig`,ClassroomDBBase=class{constructor(){i(this,`_id`,void 0),i(this,`_db`,void 0),i(this,`_cfg`,void 0),i(this,`_initComplete`,!1),i(this,`_content_prefix`,`content`)}get _content_searchkeys(){return getStartAndEndKeys(this._content_prefix)}async getAssignedContent(){return p.info(`Getting assigned content...`),(await this._db.allDocs({startkey:this._content_prefix,endkey:this._content_prefix+`￰`,include_docs:!0})).rows.map(e=>e.doc)}getContentId(e){return e.type===`tag`?`${this._content_prefix}-${e.courseID}-${e.tagID}`:`${this._content_prefix}-${e.courseID}`}get ready(){return this._initComplete}getConfig(){return this._cfg}},Zn=class StudentClassroomDB extends ClassroomDBBase{constructor(e,t){super(),i(this,`userMessages`,void 0),i(this,`_user`,void 0),this._id=e,this._user=t}async init(){let e=`classdb-student-${this._id}`;this._db=new Y(E.COUCHDB_SERVER_PROTOCOL+`://`+E.COUCHDB_SERVER_URL+e,createPouchDBConfig());try{this._cfg=await this._db.get(Xn),this.userMessages=this._db.changes({since:`now`,live:!0,include_docs:!0}),this._initComplete=!0;return}catch(e){throw Error(`Error in StudentClassroomDB constructor: ${JSON.stringify(e)}`)}}static async factory(e,t){let n=new StudentClassroomDB(e,t);return await n.init(),n}setChangeFcn(e){this.userMessages.on(`change`,e)}async getWeightedCards(e){let t=[],n=(await this._user.getPendingReviews()).filter(e=>e.scheduledFor===`classroom`&&e.schedulingAgentId===this._id);for(let e of n)t.push({cardId:e.cardId,courseId:e.courseId,score:1,reviewID:e._id,provenance:[{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`generated`,score:1,reason:`Classroom scheduled review`}]});let i=await this._user.getActiveCards(),a=new Set(i.map(e=>e.cardID)),o=r.utc(),s=(await this.getAssignedContent()).filter(e=>o.isAfter(r.utc(e.activeOn,ir)));p.info(`[StudentClassroomDB] Due content: ${JSON.stringify(s)}`);for(let n of s)if(n.type===`course`){let{cards:r}=await new CourseDB(n.courseID,async()=>this._user).getWeightedCards(e);for(let e of r)a.has(e.cardId)||t.push({...e,provenance:[...e.provenance,{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`passed`,score:e.score,reason:`Assigned via classroom from course ${n.courseID}`}]})}else if(n.type===`tag`){let e=await getTag(n.courseID,n.tagID);for(let r of e.taggedCards)a.has(r)||t.push({cardId:r,courseId:n.courseID,score:1,provenance:[{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`generated`,score:1,reason:`Classroom assigned tag: ${n.tagID}, new card`}]})}else n.type===`card`&&(a.has(n.cardID)||t.push({cardId:n.cardID,courseId:n.courseID,score:1,provenance:[{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`generated`,score:1,reason:`Classroom assigned card, new card`}]}));return p.info(`[StudentClassroomDB] New cards from classroom ${this._cfg.name}: ${t.length} total (reviews + new)`),{cards:t.sort((e,t)=>t.score-e.score).slice(0,e)}}},Qn=class TeacherClassroomDB extends ClassroomDBBase{constructor(e){super(),i(this,`_stuDb`,void 0),this._id=e}async init(){let e=`classdb-teacher-${this._id}`,t=`classdb-student-${this._id}`;this._db=new Y(E.COUCHDB_SERVER_PROTOCOL+`://`+E.COUCHDB_SERVER_URL+e,createPouchDBConfig()),this._stuDb=new Y(E.COUCHDB_SERVER_PROTOCOL+`://`+E.COUCHDB_SERVER_URL+t,createPouchDBConfig());try{return this._db.get(Xn).then(e=>{this._cfg=e,this._initComplete=!0}).then(()=>{})}catch(e){throw Error(`Error in TeacherClassroomDB constructor: ${JSON.stringify(e)}`)}}static async factory(e){let t=new TeacherClassroomDB(e);return await t.init(),t}async removeContent(e){let t=this.getContentId(e);try{let e=await this._db.get(t);await this._db.remove(e),this._db.replicate.to(this._stuDb,{doc_ids:[t]})}catch(e){p.error(`Failed to remove content:`,t,e)}}async assignContent(e){let t,n=this.getContentId(e);return t=e.type===`tag`?await this._db.put({courseID:e.courseID,tagID:e.tagID,type:`tag`,_id:n,assignedBy:e.assignedBy,assignedOn:r.utc(),activeOn:e.activeOn||r.utc()}):await this._db.put({courseID:e.courseID,type:`course`,_id:n,assignedBy:e.assignedBy,assignedOn:r.utc(),activeOn:e.activeOn||r.utc()}),t.ok?(this._db.replicate.to(this._stuDb,{doc_ids:[n]}),!0):!1}},ClassroomLookupDB=()=>new Y(E.COUCHDB_SERVER_PROTOCOL+`://`+E.COUCHDB_SERVER_URL+Yn,{skip_setup:!0}),AdminDB=class{constructor(){i(this,`usersDB`,void 0),this.usersDB=new Y(E.COUCHDB_SERVER_PROTOCOL+`://`+E.COUCHDB_SERVER_URL+`_users`,createPouchDBConfig())}async getUsers(){return(await this.usersDB.allDocs({include_docs:!0,...getStartAndEndKeys(`org.couchdb.user:`)})).rows.map(e=>e.doc)}async getCourses(){let e=await kn.allCourseWare();return await Promise.all(e.map(e=>getCredentialledCourseConfig(e._id)))}async removeCourse(e){let t=await kn.delete(e),n=await getCredentialledCourseConfig(e);n.deleted=!0;let r=await updateCredentialledCourseConfig(e,n);return{ok:t.ok&&r.ok,id:t.id,rev:t.rev}}async getClassrooms(){let e=(await ClassroomLookupDB().allDocs({include_docs:!0})).rows.map(e=>e.doc.uuid);p.debug(e.join(`, `));let t=[];for(let n=0;n<e.length;n++)try{let r=await Qn.factory(e[n]);t.push(r)}catch(t){let r=t;r.error&&r.error===`not_found`&&p.warn(`db ${e[n]} not found`)}return t.map(e=>({...e.getConfig(),_id:e._id}))}},$n,er={batchSize:1e3,batchesLimit:5},tr=($n=class CourseSyncService{constructor(){i(this,`entries`,new Map),i(this,`replicationOptions`,er)}static getInstance(){return CourseSyncService.instance||(CourseSyncService.instance=new CourseSyncService),CourseSyncService.instance}configure(e){e.replication&&(this.replicationOptions={...er,...e.replication},p.info(`[CourseSyncService] Replication configured: batch_size=${this.replicationOptions.batchSize}, batches_limit=${this.replicationOptions.batchesLimit}`))}static resetInstance(){if(CourseSyncService.instance){for(let[,e]of CourseSyncService.instance.entries)e.localDB&&e.localDB.close().catch(()=>{});CourseSyncService.instance.entries.clear()}CourseSyncService.instance=null}async ensureSynced(e,t){let n=this.entries.get(e);if(n?.status.state===`ready`&&n.localDB){if(!await this.isLocalEpochStale(e,n.localDB))return;p.info(`[CourseSyncService] Remote DB epoch changed for course ${e} — destroying stale local replica`);try{await n.localDB.destroy()}catch{}n.localDB=null,n.readyPromise=null}if(n?.status.state===`disabled`)return;if(n?.readyPromise)return n.readyPromise;let r={localDB:null,status:{state:`not-started`},readyPromise:null};return this.entries.set(e,r),r.readyPromise=this.performSync(e,r,t),r.readyPromise}getLocalDB(e){let t=this.entries.get(e);return t?.status.state===`ready`&&t.localDB?t.localDB:null}isReady(e){return this.entries.get(e)?.status.state===`ready`}getStatus(e){return this.entries.get(e)?.status??{state:`not-started`}}async performSync(e,t,n){try{if(!n&&(t.status={state:`checking-config`},!await this.checkLocalSyncEnabled(e))){t.status={state:`disabled`},t.readyPromise=null,p.debug(`[CourseSyncService] Local sync disabled for course ${e}`);return}t.status={state:`syncing`};let r=this.localDBName(e),i=new Y(r);await this.isLocalEpochStale(e,i)&&(p.info(`[CourseSyncService] Stale local DB detected for course ${e} — destroying before sync`),await i.destroy(),i=new Y(r)),t.localDB=i;let a=this.getRemoteDB(e),o=Date.now();p.info(`[CourseSyncService] Starting one-shot replication for course ${e} (batch_size=${this.replicationOptions.batchSize}, batches_limit=${this.replicationOptions.batchesLimit})`);let s=await this.replicate(a,i),c=Date.now()-o;p.info(`[CourseSyncService] Replication complete for course ${e}: ${s.docs_written} docs in ${c}ms`),t.status={state:`warming-views`};let l=Date.now();await this.warmViewIndices(i);let u=Date.now()-l;p.info(`[CourseSyncService] View indices warmed for course ${e} in ${u}ms`),t.status={state:`ready`,docsReplicated:s.docs_written,syncTimeMs:c,viewWarmTimeMs:u}}catch(n){let r=n instanceof Error?n.message:String(n);if(p.error(`[CourseSyncService] Sync failed for course ${e}: ${r}`),t.status={state:`error`,error:r},t.readyPromise=null,t.localDB){try{await t.localDB.destroy()}catch{}t.localDB=null}}}async checkLocalSyncEnabled(e){try{return(await this.getRemoteDB(e).get(`CourseConfig`)).localSync?.enabled===!0}catch(t){return p.warn(`[CourseSyncService] Could not read CourseConfig for ${e}, assuming local sync disabled: ${t}`),!1}}replicate(e,t){return new Promise((n,r)=>{Y.replicate(e,t,{batch_size:this.replicationOptions.batchSize,batches_limit:this.replicationOptions.batchesLimit}).on(`complete`,e=>{n(e)}).on(`error`,e=>{r(e)})})}async warmViewIndices(e){for(let t of[`elo`,`getTags`])try{await e.query(t,{limit:1}),p.debug(`[CourseSyncService] Warmed view index: ${t}`)}catch(e){p.debug(`[CourseSyncService] Could not warm view ${t}: ${e}`)}}async isLocalEpochStale(e,t){try{let n=await this.getRemoteDB(e).get(`db-epoch`),r=null;try{r=await t.get(`db-epoch`)}catch{return!0}return n.epoch!==r.epoch}catch{return!1}}getRemoteDB(e){return getCourseDB$1(e)}localDBName(e){return`coursedb-local-${e}`}},i($n,`instance`,null),$n),nr=t(n(((e,t)=>{var n=typeof globalThis<`u`&&globalThis||typeof self<`u`&&self||typeof window<`u`&&window,r=(function(){function F(){this.fetch=!1,this.DOMException=n.DOMException}return F.prototype=n,new F})();(function(e){(function(t){var n=e!==void 0&&e||typeof self<`u`&&self||typeof window<`u`&&window||{},r={searchParams:`URLSearchParams`in n,iterable:`Symbol`in n&&`iterator`in Symbol,blob:`FileReader`in n&&`Blob`in n&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:`FormData`in n,arrayBuffer:`ArrayBuffer`in n};function isDataView(e){return e&&DataView.prototype.isPrototypeOf(e)}if(r.arrayBuffer)var i=[`[object Int8Array]`,`[object Uint8Array]`,`[object Uint8ClampedArray]`,`[object Int16Array]`,`[object Uint16Array]`,`[object Int32Array]`,`[object Uint32Array]`,`[object Float32Array]`,`[object Float64Array]`],a=ArrayBuffer.isView||function(e){return e&&i.indexOf(Object.prototype.toString.call(e))>-1};function normalizeName(e){if(typeof e!=`string`&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||e===``)throw TypeError(`Invalid character in header field name: "`+e+`"`);return e.toLowerCase()}function normalizeValue(e){return typeof e!=`string`&&(e=String(e)),e}function iteratorFor(e){var t={next:function(){var t=e.shift();return{done:t===void 0,value:t}}};return r.iterable&&(t[Symbol.iterator]=function(){return t}),t}function Headers(e){this.map={},e instanceof Headers?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){if(e.length!=2)throw TypeError(`Headers constructor: expected name/value pair to be length 2, found`+e.length);this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}Headers.prototype.append=function(e,t){e=normalizeName(e),t=normalizeValue(t);var n=this.map[e];this.map[e]=n?n+`, `+t:t},Headers.prototype.delete=function(e){delete this.map[normalizeName(e)]},Headers.prototype.get=function(e){return e=normalizeName(e),this.has(e)?this.map[e]:null},Headers.prototype.has=function(e){return this.map.hasOwnProperty(normalizeName(e))},Headers.prototype.set=function(e,t){this.map[normalizeName(e)]=normalizeValue(t)},Headers.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},Headers.prototype.keys=function(){var e=[];return this.forEach(function(t,n){e.push(n)}),iteratorFor(e)},Headers.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),iteratorFor(e)},Headers.prototype.entries=function(){var e=[];return this.forEach(function(t,n){e.push([n,t])}),iteratorFor(e)},r.iterable&&(Headers.prototype[Symbol.iterator]=Headers.prototype.entries);function consumed(e){if(!e._noBody){if(e.bodyUsed)return Promise.reject(TypeError(`Already read`));e.bodyUsed=!0}}function fileReaderReady(e){return new Promise(function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}})}function readBlobAsArrayBuffer(e){var t=new FileReader,n=fileReaderReady(t);return t.readAsArrayBuffer(e),n}function readBlobAsText(e){var t=new FileReader,n=fileReaderReady(t),r=/charset=([A-Za-z0-9_-]+)/.exec(e.type),i=r?r[1]:`utf-8`;return t.readAsText(e,i),n}function readArrayBufferAsText(e){for(var t=new Uint8Array(e),n=Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join(``)}function bufferClone(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function Body(){return this.bodyUsed=!1,this._initBody=function(e){this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?typeof e==`string`?this._bodyText=e:r.blob&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:r.formData&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:r.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():r.arrayBuffer&&r.blob&&isDataView(e)?(this._bodyArrayBuffer=bufferClone(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):r.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(e)||a(e))?this._bodyArrayBuffer=bufferClone(e):this._bodyText=e=Object.prototype.toString.call(e):(this._noBody=!0,this._bodyText=``),this.headers.get(`content-type`)||(typeof e==`string`?this.headers.set(`content-type`,`text/plain;charset=UTF-8`):this._bodyBlob&&this._bodyBlob.type?this.headers.set(`content-type`,this._bodyBlob.type):r.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set(`content-type`,`application/x-www-form-urlencoded;charset=UTF-8`))},r.blob&&(this.blob=function(){var e=consumed(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw Error(`could not read FormData body as blob`);return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer)return consumed(this)||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer));if(r.blob)return this.blob().then(readBlobAsArrayBuffer);throw Error(`could not read as ArrayBuffer`)},this.text=function(){var e=consumed(this);if(e)return e;if(this._bodyBlob)return readBlobAsText(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer));if(this._bodyFormData)throw Error(`could not read FormData body as text`);return Promise.resolve(this._bodyText)},r.formData&&(this.formData=function(){return this.text().then(decode)}),this.json=function(){return this.text().then(JSON.parse)},this}var o=[`CONNECT`,`DELETE`,`GET`,`HEAD`,`OPTIONS`,`PATCH`,`POST`,`PUT`,`TRACE`];function normalizeMethod(e){var t=e.toUpperCase();return o.indexOf(t)>-1?t:e}function Request(e,t){if(!(this instanceof Request))throw TypeError(`Please use the "new" operator, this DOM object constructor cannot be called as a function.`);t=t||{};var r=t.body;if(e instanceof Request){if(e.bodyUsed)throw TypeError(`Already read`);this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new Headers(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,!r&&e._bodyInit!=null&&(r=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||`same-origin`,(t.headers||!this.headers)&&(this.headers=new Headers(t.headers)),this.method=normalizeMethod(t.method||this.method||`GET`),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if(`AbortController`in n)return new AbortController().signal}(),this.referrer=null,(this.method===`GET`||this.method===`HEAD`)&&r)throw TypeError(`Body not allowed for GET or HEAD requests`);if(this._initBody(r),(this.method===`GET`||this.method===`HEAD`)&&(t.cache===`no-store`||t.cache===`no-cache`)){var i=/([?&])_=[^&]*/;i.test(this.url)?this.url=this.url.replace(i,`$1_=`+new Date().getTime()):this.url+=(/\?/.test(this.url)?`&`:`?`)+`_=`+new Date().getTime()}}Request.prototype.clone=function(){return new Request(this,{body:this._bodyInit})};function decode(e){var t=new FormData;return e.trim().split(`&`).forEach(function(e){if(e){var n=e.split(`=`),r=n.shift().replace(/\+/g,` `),i=n.join(`=`).replace(/\+/g,` `);t.append(decodeURIComponent(r),decodeURIComponent(i))}}),t}function parseHeaders(e){var t=new Headers;return e.replace(/\r?\n[\t ]+/g,` `).split(`\r`).map(function(e){return e.indexOf(`
26
+ `)===0?e.substr(1,e.length):e}).forEach(function(e){var n=e.split(`:`),r=n.shift().trim();if(r){var i=n.join(`:`).trim();try{t.append(r,i)}catch(e){console.warn(`Response `+e.message)}}}),t}Body.call(Request.prototype);function Response(e,t){if(!(this instanceof Response))throw TypeError(`Please use the "new" operator, this DOM object constructor cannot be called as a function.`);if(t||(t={}),this.type=`default`,this.status=t.status===void 0?200:t.status,this.status<200||this.status>599)throw RangeError(`Failed to construct 'Response': The status provided (0) is outside the range [200, 599].`);this.ok=this.status>=200&&this.status<300,this.statusText=t.statusText===void 0?``:``+t.statusText,this.headers=new Headers(t.headers),this.url=t.url||``,this._initBody(e)}Body.call(Response.prototype),Response.prototype.clone=function(){return new Response(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new Headers(this.headers),url:this.url})},Response.error=function(){var e=new Response(null,{status:200,statusText:``});return e.ok=!1,e.status=0,e.type=`error`,e};var s=[301,302,303,307,308];Response.redirect=function(e,t){if(s.indexOf(t)===-1)throw RangeError(`Invalid status code`);return new Response(null,{status:t,headers:{location:e}})},t.DOMException=n.DOMException;try{new t.DOMException}catch{t.DOMException=function(e,t){this.message=e,this.name=t,this.stack=Error(e).stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function fetch(e,i){return new Promise(function(a,o){var s=new Request(e,i);if(s.signal&&s.signal.aborted)return o(new t.DOMException(`Aborted`,`AbortError`));var c=new XMLHttpRequest;function abortXhr(){c.abort()}c.onload=function(){var e={statusText:c.statusText,headers:parseHeaders(c.getAllResponseHeaders()||``)};s.url.indexOf(`file://`)===0&&(c.status<200||c.status>599)?e.status=200:e.status=c.status,e.url=`responseURL`in c?c.responseURL:e.headers.get(`X-Request-URL`);var t=`response`in c?c.response:c.responseText;setTimeout(function(){a(new Response(t,e))},0)},c.onerror=function(){setTimeout(function(){o(TypeError(`Network request failed`))},0)},c.ontimeout=function(){setTimeout(function(){o(TypeError(`Network request timed out`))},0)},c.onabort=function(){setTimeout(function(){o(new t.DOMException(`Aborted`,`AbortError`))},0)};function fixUrl(e){try{return e===``&&n.location.href?n.location.href:e}catch{return e}}if(c.open(s.method,fixUrl(s.url),!0),s.credentials===`include`?c.withCredentials=!0:s.credentials===`omit`&&(c.withCredentials=!1),`responseType`in c&&(r.blob?c.responseType=`blob`:r.arrayBuffer&&(c.responseType=`arraybuffer`)),i&&typeof i.headers==`object`&&!(i.headers instanceof Headers||n.Headers&&i.headers instanceof n.Headers)){var l=[];Object.getOwnPropertyNames(i.headers).forEach(function(e){l.push(normalizeName(e)),c.setRequestHeader(e,normalizeValue(i.headers[e]))}),s.headers.forEach(function(e,t){l.indexOf(t)===-1&&c.setRequestHeader(t,e)})}else s.headers.forEach(function(e,t){c.setRequestHeader(t,e)});s.signal&&(s.signal.addEventListener(`abort`,abortXhr),c.onreadystatechange=function(){c.readyState===4&&s.signal.removeEventListener(`abort`,abortXhr)}),c.send(s._bodyInit===void 0?null:s._bodyInit)})}return fetch.polyfill=!0,n.fetch||(n.fetch=fetch,n.Headers=Headers,n.Request=Request,n.Response=Response),t.Headers=Headers,t.Request=Request,t.Response=Response,t.fetch=fetch,t})({})})(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=n.fetch?n:r;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e}))(),1);async function getCurrentSession(){try{if(E.COUCHDB_SERVER_URL===`NOT_SET`||E.COUCHDB_SERVER_PROTOCOL===`NOT_SET`)throw Error(`CouchDB server configuration not properly initialized. Protocol: "${E.COUCHDB_SERVER_PROTOCOL}", URL: "${E.COUCHDB_SERVER_URL}"`);let e=E.COUCHDB_SERVER_URL.endsWith(`/`)?E.COUCHDB_SERVER_URL.slice(0,-1):E.COUCHDB_SERVER_URL,t=`${E.COUCHDB_SERVER_PROTOCOL}://${e}/_session`;p.debug(`Attempting session check at: ${t}`);let n=await(0,nr.default)(t,{method:`GET`,credentials:`include`});if(!n.ok)throw Error(`Session check failed: ${n.status}`);return await n.json()}catch(e){let t=E.COUCHDB_SERVER_URL.endsWith(`/`)?E.COUCHDB_SERVER_URL.slice(0,-1):E.COUCHDB_SERVER_URL,n=`${E.COUCHDB_SERVER_PROTOCOL}://${t}/_session`;throw p.error(`Session check error attempting to connect to: ${n} - ${e}`),Error(`Session check failed connecting to ${n}: ${e}`)}}async function getLoggedInUsername(){let e=await getCurrentSession();if(e.userCtx.name&&e.userCtx.name!==``)return e.userCtx.name;throw Error(`No logged in user`)}var log=e=>{p.info(e)},CouchDBSyncStrategy=class{constructor(){i(this,`syncHandle`,void 0),i(this,`hydrationHandle`,void 0)}setupRemoteDB(e){return e===`sk-guest-`||e.startsWith(`sk-guest-`)?getLocalUserDB(e):this.getUserDB(e)}getWriteDB(e){return e===`sk-guest-`||e.startsWith(`sk-guest-`)?getLocalUserDB(e):this.getUserDB(e)}async hydrate(e,t){let n=(await e.info()).doc_count===0,r=Y.replicate(t,e,n?{selector:{_deleted:{$exists:!1}}}:{});this.hydrationHandle=r;try{let e=await r;return{docsWritten:e.docs_written,lastSeq:n?e.last_seq:void 0}}finally{this.hydrationHandle=void 0}}startSync(e,t,n){e.name!==t.name&&(this.syncHandle=Y.sync(e,t,{live:!0,retry:!0,...n===void 0?{}:{pull:{since:n}}}))}stopSync(){if(this.hydrationHandle){try{this.hydrationHandle.cancel()}catch(e){p.warn(`Failed to cancel hydration pull (continuing anyway): ${e}`)}this.hydrationHandle=void 0}if(this.syncHandle){try{this.syncHandle.cancel()}catch(e){p.warn(`Failed to cancel user sync (continuing anyway): ${e}`)}this.syncHandle=void 0}}canCreateAccount(){return!0}canAuthenticate(){return!0}async createAccount(e,t){let n=await this.getCurrentUsername(),r=n.startsWith(S);r&&p.info(`Creating account for funnel user ${n} -> ${e}`);try{let i=await this.getRemoteCouchRootDB().signUp(e,t);if(i.ok){log(`CREATEACCOUNT: Successfully created account for ${e}`);try{log(`CREATEACCOUNT: logged out: ${(await this.getRemoteCouchRootDB().logOut()).ok}`)}catch{}let i=await this.getRemoteCouchRootDB().logIn(e,t);if(log(`CREATEACCOUNT: logged in as new user: ${i.ok}`),i.ok){if(r){p.info(`Migrating data from funnel account ${n} to ${e}`);let t=await this.migrateFunnelData(n,e);t.success||p.warn(`Migration failed: ${t.error}`)}return{status:k.ok,error:void 0}}else return{status:k.error,error:`Failed to log in after account creation`}}else return p.warn(`Signup not OK: ${JSON.stringify(i)}`),{status:k.error,error:`Account creation failed`}}catch(e){return e.reason===`Document update conflict.`?{status:k.error,error:`This username is taken!`}:(p.error(`Error on signup: ${JSON.stringify(e)}`),{status:k.error,error:e.message||`Unknown error during account creation`})}}async authenticate(e,t){try{return(await this.getRemoteCouchRootDB().logIn(e,t)).ok?(log(`Successfully logged in as ${e}`),{ok:!0}):(log(`Login failed for ${e}`),{ok:!1,error:`Invalid username or password`})}catch(t){return p.error(`Authentication error for ${e}:`,t),{ok:!1,error:t.message||`Authentication failed`}}}async adoptSession(e){let t;try{t=await getLoggedInUsername()}catch{return{ok:!1,error:`No session to adopt`}}if(e?.startsWith(`sk-guest-`)){p.info(`Migrating data from funnel account ${e} to ${t}`);let n=await this.migrateFunnelData(e,t);n.success||p.warn(`Migration failed: ${n.error}`)}return{ok:!0,username:t}}async logout(){try{let e=await this.getRemoteCouchRootDB().logOut();return{ok:e.ok,error:e.ok?void 0:`Logout failed`}}catch(e){return p.error(`Logout error:`,e),{ok:!1,error:e.message||`Logout failed`}}}async getCurrentUsername(){p.log(`[funnel] CouchDBSyncStrategy.getCurrentUsername() called`);try{let e=await getLoggedInUsername();return p.log(`[funnel] getLoggedInUsername() returned:`,e),e}catch(e){p.log(`[funnel] getLoggedInUsername() failed, calling accomodateGuest()`),p.log(`[funnel] Error was:`,e);let t=accomodateGuest();return p.log(`[funnel] accomodateGuest() returned:`,t),t.username}}async migrateFunnelData(e,t){try{p.info(`Starting data migration from ${e} to ${t}`);let n=getLocalUserDB(e),r=getLocalUserDB(t),i=await n.allDocs({include_docs:!0});p.info(`Found ${i.rows.length} documents in funnel account`);let a=i.rows.filter(e=>!e.id.startsWith(`_design/`)).map(e=>({...e.doc,_rev:void 0}));a.length>0?(await r.bulkDocs(a),p.info(`Successfully migrated ${a.length} documents from ${e} to ${t}`)):p.info(`No documents to migrate from funnel account`);try{await n.destroy(),p.info(`Destroyed consumed guest DB for ${e}`)}catch(t){p.warn(`Failed to destroy consumed guest DB for ${e} (non-fatal): ${t instanceof Error?t.message:String(t)}`)}return{success:!0}}catch(e){return p.error(`Migration failed:`,e),{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}getRemoteCouchRootDB(){let e=E.COUCHDB_SERVER_PROTOCOL+`://`+E.COUCHDB_SERVER_URL+`skuilder`;try{return new Y(e,{skip_setup:!0})}catch(e){throw p.error(`Failed to initialize remote CouchDB connection:`,e),Error(`Failed to initialize CouchDB: ${JSON.stringify(e)}`)}}getUserDB(e){let t=`userdb-${T(e)}`;return log(`Fetching user database: ${t} (${e})`),new Y(E.COUCHDB_SERVER_PROTOCOL+`://`+E.COUCHDB_SERVER_URL+t,createPouchDBConfig())}};new Y(`userdb-${S}`);var rr={fetch(e,t){return t.credentials=`include`,Y.fetch(e,t)}};function createPouchDBConfig(){return E.COUCHDB_USERNAME&&E.COUCHDB_PASSWORD&&typeof window>`u`?{fetch(e,t={}){let n=btoa(`${E.COUCHDB_USERNAME}:${E.COUCHDB_PASSWORD}`),r=new Headers(t.headers||{});r.set(`Authorization`,`Basic ${n}`);let i={...t,headers:r};return Y.fetch(e,i)}}:rr}function getCourseDB$1(e){return new Y(E.COUCHDB_SERVER_PROTOCOL+`://`+E.COUCHDB_SERVER_URL+`coursedb-`+e,createPouchDBConfig())}e(getCourseDB$1,`getCourseDB`);var ir=`YYYY-MM-DD--kk:mm:ss-SSS`;function filterAllDocsByPrefix(e,t,n){let r={startkey:t,endkey:t+`￰`,include_docs:!0};return n&&Object.assign(r,n),e.allDocs(r)}function getStartAndEndKeys(e){return{startkey:e,endkey:e+`￰`}}var $=[];for(let e=0;e<256;++e)$.push((e+256).toString(16).slice(1));function unsafeStringify(e,t=0){return($[e[t+0]]+$[e[t+1]]+$[e[t+2]]+$[e[t+3]]+`-`+$[e[t+4]]+$[e[t+5]]+`-`+$[e[t+6]]+$[e[t+7]]+`-`+$[e[t+8]]+$[e[t+9]]+`-`+$[e[t+10]]+$[e[t+11]]+$[e[t+12]]+$[e[t+13]]+$[e[t+14]]+$[e[t+15]]).toLowerCase()}var ar,or=new Uint8Array(16);function rng(){if(!ar){if(typeof crypto>`u`||!crypto.getRandomValues)throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);ar=crypto.getRandomValues.bind(crypto)}return ar(or)}var sr={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function v4(e,t,n){if(sr.randomUUID&&!t&&!e)return sr.randomUUID();e=e||{};let r=e.random??e.rng?.()??rng();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n=n||0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return unsafeStringify(r)}async function addNote55(e,t,n,r,i,o,s,c=a()){let l=getCourseDB(e),u=prepareNote55(e,t,n,r,i,o,s),d=`${O[D.DISPLAYABLE_DATA]}-${v4()}`,m=await l.put({...u,_id:d}),h=NameSpacer.getDataShapeString({course:t,dataShape:n.name});if(m.ok)try{await createCards(e,h,m.id,o,c,i)}catch(e){let t=`Unknown error`;t=e instanceof Error?e.message:e&&typeof e==`object`&&`reason`in e?e.reason:e&&typeof e==`object`&&`message`in e?e.message:String(e),p.error(`[addNote55] Failed to create cards for note ${m.id}: ${t}`),m.cardCreationFailed=!0,m.cardCreationError=t}else p.error(`[addNote55] Error adding note. Result: ${JSON.stringify(m)}`);return m}async function createCards(e,t,n,r,i=a(),o){let s=await getCredentialledCourseConfig(e),c=NameSpacer.getDataShapeDescriptor(t),l=[];for(let e of s.dataShapes)e.name===t&&(l=e.questionTypes);if(l.length===0){let e=`No questionViewTypes found for datashapeID: ${t} in course config. Cards cannot be created.`;throw p.error(e),Error(e)}for(let t of l)await createCard(t,e,c,n,r,i,o)}async function createCard(e,t,n,r,i,o=a(),s){let c=NameSpacer.getQuestionDescriptor(e),l=await getCredentialledCourseConfig(t);for(let a of l.questionTypes)if(a.name===e)for(let e of a.viewList)await addCard(t,n.course,[r],NameSpacer.getViewString({course:c.course,questionType:c.questionType,view:e}),o,i,s)}async function addCard(e,t,n,r,i,a,s){let c=getCourseDB(e),l=`${O[D.CARD]}-${v4()}`,u=await c.put({_id:l,course:t,id_displayable_data:n,id_view:r,docType:D.CARD,elo:i||o(990+Math.round(20*Math.random())),author:s});for(let t of a)p.info(`adding tag: ${t} to card ${u.id}`),await addTagToCard(e,u.id,t,s,!1);return u}async function getCredentialledCourseConfig(e){try{let t=await getCourseDB(e).get(`CourseConfig`);return t.courseID=e,p.info(`Returning course config: ${JSON.stringify(t)}`),t}catch(t){throw p.error(`Error fetching config for ${e}:`,t),t}}async function addTagToCard(e,t,n,r,i=!0){let a=getTagID(n),o=getCourseDB(e),s=new CourseDB(e,async()=>Kn.Dummy({setupRemoteDB:()=>null,startSync:()=>{},canCreateAccount:()=>!1,canAuthenticate:()=>!1,getCurrentUsername:async()=>`DummyUser`}));try{p.info(`Applying tag ${n} to card ${e+`-`+t}...`);let r=await o.get(a);if(r.taggedCards.includes(t))throw new AlreadyTaggedErr(`Card ${t} is already tagged with ${n}`);if(r.taggedCards.push(t),i)try{let r=(await s.getCardEloData([t]))[0];r.tags[n]={count:0,score:r.global.score},await updateCardElo(e,t,r)}catch(e){p.error(`Failed to update ELO data for card:`,t,e)}return o.put(r)}catch(a){if(a instanceof AlreadyTaggedErr)throw a;return await createTag(e,n,r),addTagToCard(e,t,n,r,i)}}async function updateCardElo(e,t,n){if(n){let r=getCourseDB(e),i=await r.get(t);return p.debug(`Replacing ${JSON.stringify(i.elo)} with ${JSON.stringify(n)}`),i.elo=n,r.put(i)}}var AlreadyTaggedErr=class extends Error{constructor(e){super(e),this.name=`AlreadyTaggedErr`}};function getTagID(e){let t=D.TAG.valueOf()+`-`;return e.indexOf(t)===0?e:t+e}function getCourseDB(e){let t=`coursedb-${e}`;return new Y(E.COUCHDB_SERVER_PROTOCOL+`://`+E.COUCHDB_SERVER_URL+t,createPouchDBConfig())}var CoursesDB=class{constructor(e){i(this,`_courseIDs`,void 0),e&&e.length>0?this._courseIDs=e:this._courseIDs=void 0}async getCourseList(){let e=await kn.allCourseWare();return p.debug(`AllCourses: ${e.map(e=>e.name+`, `+e._id+`
27
+ `)}`),this._courseIDs&&(e=e.filter(e=>this._courseIDs.includes(e._id))),p.debug(`AllCourses.filtered: ${e.map(e=>e.name+`, `+e._id+`
28
+ `)}`),(await Promise.all(e.map(async e=>{try{let t=await getCredentialledCourseConfig(e._id);return p.debug(`Found cfg: ${JSON.stringify(t)}`),t}catch(t){p.warn(`Error fetching cfg for course ${e.name}, ${e._id}: ${t}`);return}}))).filter(e=>!!e)}async getCourseConfig(e){if(this._courseIDs&&this._courseIDs.length&&!this._courseIDs.includes(e))throw Error(`Course ${e} not in course list`);let t=await getCredentialledCourseConfig(e);if(t===void 0)throw Error(`Error fetching cfg for course ${e}`);return t}async disambiguateCourse(e,t){await kn.updateDisambiguator(e,t)}};function randIntWeightedTowardZero(e){return Math.floor(Math.random()*Math.random()*Math.random()*e)}var CourseDB=class{constructor(e,t,n){i(this,`db`,void 0),i(this,`remoteDB`,void 0),i(this,`id`,void 0),i(this,`_getCurrentUser`,void 0),i(this,`updateQueue`,void 0),i(this,`_pendingHints`,null),i(this,`_eloPoolCache`,null),i(this,`_eloPoolTtlMs`,300*1e3),i(this,`_eloPoolMaxDrift`,200),i(this,`_cachedNavigator`,null),i(this,`_navigatorTtlMs`,300*1e3),this.id=e;let r=getCourseDB$1(this.id);this.remoteDB=r,this.db=n??r,this._getCurrentUser=t,this.updateQueue=new UpdateQueue(this.remoteDB,this.remoteDB)}getCourseID(){return this.id}async getCourseInfo(){return{cardCount:(await this.db.find({selector:{docType:D.CARD},limit:1e3})).docs.length,registeredUsers:0}}async getInexperiencedCards(e=2){return(await this.db.query(`cardsByInexperience`,{limit:e})).rows.map(e=>({courseId:this.id,cardId:e.id,count:e.key,elo:e.value}))}async getCardsByEloLimits(e={low:0,high:-(2**53-1),limit:25,page:0}){return(await this.db.query(`elo`,{startkey:e.low,endkey:e.high,limit:e.limit,skip:e.limit*e.page})).rows.map(e=>`${this.id}-${e.id}-${e.key}`)}async getCardEloData(e){let t=await this.db.allDocs({keys:e,include_docs:!0}),n=[];return t.rows.forEach(e=>{isSuccessRow(e)?e.doc&&e.doc.elo?n.push(o(e.doc.elo)):(p.warn(`no elo data for card: `+e.id),n.push(a())):(p.warn(`no elo data for card: `+JSON.stringify(e)),n.push(a()))}),n}async getELOBounds(){let[e,t]=await Promise.all([(await this.db.query(`elo`,{startkey:0,limit:1,include_docs:!1})).rows[0].key,(await this.db.query(`elo`,{limit:1,descending:!0,startkey:1e5})).rows[0].key]);return{low:e,high:t}}async removeCard(e){let t=await this.remoteDB.get(e);if(!t.docType||t.docType!==D.CARD)throw Error(`failed to remove ${e} from course ${this.id}. id does not point to a card`);try{let t=await this.getAppliedTags(e);(await Promise.allSettled(t.rows.map(async t=>{let n=t.id;await this.removeTagFromCard(e,n)}))).forEach((n,r)=>{if(n.status===`rejected`){let i=t.rows[r].id;p.error(`Failed to remove card ${e} from tag ${i}: ${n.reason}`)}})}catch(t){p.error(`Error removing card ${e} from tags: ${t}`)}return this.remoteDB.remove(t)}async getCardDisplayableDataIDs(e){p.debug(e.join(`, `));let t=await this.db.allDocs({keys:e,include_docs:!0}),n={};return t.rows.forEach(e=>{isSuccessRow(e)&&(n[e.id]=e.doc.id_displayable_data)}),n}async getCardsByELO(e,t){e=parseInt(e);let n=t||25,r=await this.db.query(`elo`,{limit:Math.ceil(n/2),startkey:e,descending:!0}),i=n-r.rows.length,a=await this.db.query(`elo`,{limit:i,startkey:e+1}),o=r.rows;o=o.concat(a.rows);let s=o.sort((t,n)=>{let r=Math.abs(t.key-e)-Math.abs(n.key-e);return r===0?Math.random()-.5:r}).map(e=>({courseID:this.id,cardID:e.id,elo:e.key})),c=`below:\n${r.rows.map(e=>`\t${e.id}-${e.key}\n`)}
29
+
30
+ above:\n${a.rows.map(e=>`\t${e.id}-${e.key}\n`)}`;return p.debug(`Getting ${n} cards centered around elo: ${e}:\n\n`+c),s}async getCourseConfig(){let e=await getCredentialledCourseConfig(this.id);if(e)return e;throw Error(`Course config not found for course ID: ${this.id}`)}async updateCourseConfig(e){p.debug(`Updating: ${JSON.stringify(e)}`);try{return await updateCredentialledCourseConfig(this.id,e)}catch(e){throw p.error(`Error updating course config in course DB: ${e}`),e}}async updateCardElo(e,t){if(!t)throw Error(`Cannot update card elo with null or undefined value for card ID: ${e}`);try{return{ok:!0,id:e,rev:(await this.updateQueue.update(e,e=>(p.debug(`Replacing ${JSON.stringify(e.elo)} with ${JSON.stringify(t)}`),e.elo=t,e)))._rev}}catch(t){throw p.error(`Failed to update card elo for card ID: ${e}`,t),Error(`Failed to update card elo for card ID: ${e}`)}}async getAppliedTags(e){let t=await getAppliedTags(this.id,e);if(t)return t;throw Error(`Failed to find tags for card ${this.id}-${e}`)}async getAppliedTagsBatch(e){if(e.length===0)return new Map;let t=await this.db.query(`getTags`,{keys:e,include_docs:!1}),n=new Map;for(let t of e)n.set(t,[]);for(let e of t.rows){let t=e.key,r=e.value?.name;r&&n.has(t)&&n.get(t).push(r)}return n}async getAllCardIds(){let e=`${O[D.CARD]}-`;return(await this.db.allDocs({startkey:e,endkey:`${e}\ufff0`,include_docs:!1})).rows.map(e=>e.id)}async addTagToCard(e,t,n){return await addTagToCard(this.id,e,t,(await this._getCurrentUser()).getUsername(),n)}async removeTagFromCard(e,t){return await removeTagFromCard(this.id,e,t)}async createTag(e,t){return await createTag(this.id,e,t)}async getTag(e){return await getTag(this.id,e)}async updateTag(e){if(e.course!==this.id)throw Error(`Tag ${JSON.stringify(e)} does not belong to course ${this.id}`);return await updateTag(e)}async getCourseTagStubs(){return getCourseTagStubs(this.id)}async addNote(e,t,n,r,i,o,s=a()){try{let a=await addNote55(this.id,e,t,n,r,i,o,s);return a.ok?a.cardCreationFailed?(p.warn(`[courseDB.addNote] Note added but card creation failed: ${a.cardCreationError}`),{status:k.error,message:`Note was added but no cards were created: ${a.cardCreationError}`,id:a.id}):{status:k.ok,message:``,id:a.id}:{status:k.error,message:`Unexpected error adding note`}}catch(e){let t=e;return p.error(`[addNote] error ${t.name}\n\treason: ${t.reason}\n\tmessage: ${t.message}`),{status:k.error,message:`Error adding note to course. ${e.reason||t.message}`}}}async getCourseDoc(e,t){return await this.db.get(e,t??{})}async getCourseDocs(e,t={}){return await this.db.allDocs({...t,keys:e})}getNavigationStrategy(e){if(p.debug(`[courseDB] Getting navigation strategy: ${e}`),e==``){let e={_id:`NAVIGATION_STRATEGY-ELO`,docType:D.NAVIGATION_STRATEGY,name:`ELO`,description:`ELO-based navigation strategy for ordering content by difficulty`,implementingClass:d.ELO,course:this.id,serializedData:``};return Promise.resolve(e)}else return this.db.get(e)}async getAllNavigationStrategies(){let e=O[D.NAVIGATION_STRATEGY];return(await this.db.allDocs({startkey:e,endkey:`${e}\ufff0`,include_docs:!0})).rows.map(e=>e.doc)}async addNavigationStrategy(e){return p.debug(`[courseDB] Adding navigation strategy: ${e._id}`),this.invalidateNavigatorCache(),this.remoteDB.put(e).then(()=>{})}updateNavigationStrategy(e,t){return p.debug(`[courseDB] Updating navigation strategy: ${e}`),p.debug(JSON.stringify(t)),Promise.resolve()}async createNavigator(e){try{let t=await this.getAllNavigationStrategies();if(t.length===0)return p.debug(`[courseDB] No strategy documents found, using default Pipeline(Composite(ELO, SRS), [eloDistanceFilter])`),createDefaultPipeline(e,this);let{pipeline:n,generatorStrategies:r,filterStrategies:i,warnings:a}=await new PipelineAssembler().assemble({strategies:t,user:e,course:this});for(let e of a)p.warn(`[PipelineAssembler] ${e}`);return n?(p.debug(`[courseDB] Using assembled pipeline with ${r.length} generator(s) and ${i.length} filter(s)`),n):(p.debug(`[courseDB] Pipeline assembly failed, using default pipeline`),createDefaultPipeline(e,this))}catch(e){let t=e instanceof Error?`${e.message}\n${e.stack}`:JSON.stringify(e);throw p.error(`[courseDB] Error creating navigator: ${t}`),e}}setEphemeralHints(e){this._pendingHints=e}notePresented(e){e.status===`new`&&this._getCurrentUser().then(e=>this._getCachedNavigator(e)).then(({navigator:t})=>t.notePresented?.(e)).catch(e=>p.warn(`[courseDB] Could not note a presentation: ${e}`))}async getWeightedCards(e){let t=await this._getCurrentUser();try{let{navigator:n}=await this._getCachedNavigator(t);return this._pendingHints&&(n.setEphemeralHints(this._pendingHints),this._pendingHints=null),await n.getWeightedCards(e)}catch(e){throw p.error(`[courseDB] Error getting weighted cards: ${e}`),e}}async _getCachedNavigator(e){let t=e.getUsername(),n=Date.now();if(this._cachedNavigator&&this._cachedNavigator.userId===t&&n-this._cachedNavigator.builtAt<this._navigatorTtlMs)return{navigator:this._cachedNavigator.navigator,cacheStatus:`hit`};let r=await this.createNavigator(e);return this._cachedNavigator={navigator:r,userId:t,builtAt:n},{navigator:r,cacheStatus:`miss`}}invalidateNavigatorCache(){this._cachedNavigator=null}async getCardsCenteredAtELO(e={limit:99,elo:`user`},t){let n;if(e.elo===`user`){let e=await this._getCurrentUser();n=-1;try{n=s((await e.getCourseRegistrationsDoc()).courses.find(e=>e.courseID===this.id).elo)}catch{n=1e3}}else if(e.elo===`random`){let e=await GET_CACHED(`elo-bounds-${this.id}`,()=>this.getELOBounds());n=Math.round(e.low+Math.random()*(e.high-e.low))}else n=e.elo;let r=Math.max(2e3,e.limit*4),i=Date.now(),a=`hit`;if(!this._eloPoolCache||i-this._eloPoolCache.fetchedAt>this._eloPoolTtlMs||Math.abs(n-this._eloPoolCache.centerElo)>this._eloPoolMaxDrift){let e=await this.getCardsByELO(n,r);e.length>0&&(this._eloPoolCache={rows:e,fetchedAt:i,centerElo:n}),a=`miss`}let rankAgainstCurrentElo=()=>{let e=this._eloPoolCache?.rows??[];return(t?e.filter(e=>t(e)):e).map(e=>({...e})).sort((e,t)=>Math.abs((e.elo??n)-n)-Math.abs((t.elo??n)-n))},o=rankAgainstCurrentElo();if(o.length<e.limit&&(a===`hit`||!this._eloPoolCache)){let e=await this.getCardsByELO(n,r);e.length>0&&(this._eloPoolCache={rows:e,fetchedAt:i,centerElo:n}),o=rankAgainstCurrentElo(),a=`refresh`}let c=[];for(;c.length<e.limit&&o.length>0;){let e=randIntWeightedTowardZero(o.length),t=o.splice(e,1)[0];c.push(t)}return c.map(e=>({courseID:this.id,cardID:e.cardID,contentSourceType:`course`,contentSourceID:this.id,elo:e.elo,status:`new`}))}async searchCards(e){p.log(`[CourseDB ${this.id}] Searching for: "${e}"`);let t;try{t=await this.db.find({selector:{docType:`DISPLAYABLE_DATA`,"data.0.data":{$regex:`.*${e}.*`}}}),p.log(`[CourseDB ${this.id}] Regex search on data[0].data successful`)}catch(n){p.log(`[CourseDB ${this.id}] Regex search failed, falling back to manual search:`,n);let r=await this.db.find({selector:{docType:`DISPLAYABLE_DATA`}});p.log(`[CourseDB ${this.id}] Retrieved ${r.docs.length} documents for manual filtering`),t={docs:r.docs.filter(t=>{let n=JSON.stringify(t).toLowerCase().includes(e.toLowerCase());return n&&p.log(`[CourseDB ${this.id}] Manual match found in document: ${t._id}`),n})}}if(p.log(`[CourseDB ${this.id}] Found ${t.docs.length} displayable data documents`),t.docs.length===0){let e=await this.db.find({selector:{docType:`DISPLAYABLE_DATA`},limit:5});p.log(`[CourseDB ${this.id}] Sample displayable data:`,e.docs.map(e=>({id:e._id,docType:e.docType,dataStructure:e.data?Object.keys(e.data):`no data field`,dataContent:e.data,fullDoc:e})))}let n=[];for(let e of t.docs){let t=await this.db.find({selector:{docType:`CARD`,id_displayable_data:{$in:[e._id]}}});p.log(`[CourseDB ${this.id}] Displayable data ${e._id} linked to ${t.docs.length} cards`),n.push(...t.docs)}return p.log(`[CourseDB ${this.id}] Total cards found: ${n.length}`),n}async find(e){return this.db.find(e)}};async function getCourseTagStubs(e){p.debug(`Getting tag stubs for course: ${e}`);let t=await filterAllDocsByPrefix(getCourseDB$1(e),D.TAG.valueOf()+`-`);return t.rows.forEach(e=>{p.debug(`\tTag stub for doc: ${e.id}`)}),t}async function createTag(e,t,n){p.debug(`Creating tag: ${t}...`);let r=getTagID(t);return await getCourseDB$1(e).put({course:e,docType:D.TAG,name:t,snippet:``,taggedCards:[],wiki:``,author:n,_id:r})}async function updateTag(e){let t=await getTag(e.course,e.name);return await getCourseDB$1(e.course).put({...e,_rev:t._rev})}async function getTag(e,t){let n=getTagID(t);return getCourseDB$1(e).get(n)}async function removeTagFromCard(e,t,n){n=getTagID(n);let r=getCourseDB$1(e),i=await r.get(n);return i.taggedCards=i.taggedCards.filter(e=>t!==e),r.put(i)}async function getAppliedTags(e,t){return await getCourseDB$1(e).query(`getTags`,{startkey:t,endkey:t})}async function updateCredentialledCourseConfig(e,t){p.debug(`Updating course config:
31
+
32
+ ${JSON.stringify(t)}
33
+ `);let n=getCourseDB$1(e),r=await getCredentialledCourseConfig(e);return await n.put({...t,_rev:r._rev})}function isSuccessRow(e){return`doc`in e&&e.doc!==null&&e.doc!==void 0}var TagFilteredContentSource=class{constructor(e,t,n){i(this,`courseId`,void 0),i(this,`filter`,void 0),i(this,`user`,void 0),i(this,`resolvedCardIds`,null),this.courseId=e,this.filter=t,this.user=n,p.info(`[TagFilteredContentSource] Created for course "${e}" with filter:`,JSON.stringify(t))}async resolveFilteredCardIds(){if(this.resolvedCardIds!==null)return this.resolvedCardIds;let e=new Set;if(this.filter.include.length>0)for(let t of this.filter.include)try{(await getTag(this.courseId,t)).taggedCards.forEach(t=>e.add(t))}catch(e){p.warn(`[TagFilteredContentSource] Could not resolve tag "${t}" for inclusion:`,e)}if(e.size===0&&this.filter.include.length>0)return p.warn(`[TagFilteredContentSource] No cards found for include tags: ${this.filter.include.join(`, `)}`),this.resolvedCardIds=new Set,this.resolvedCardIds;let t=new Set;if(this.filter.exclude.length>0)for(let e of this.filter.exclude)try{(await getTag(this.courseId,e)).taggedCards.forEach(e=>t.add(e))}catch(t){p.warn(`[TagFilteredContentSource] Could not resolve tag "${e}" for exclusion:`,t)}let n=new Set;for(let r of e)t.has(r)||n.add(r);return p.info(`[TagFilteredContentSource] Resolved ${n.size} cards (included: ${e.size}, excluded: ${t.size})`),this.resolvedCardIds=n,n}async getWeightedCards(e){if(!hasActiveFilter(this.filter))return p.warn(`[TagFilteredContentSource] getWeightedCards called with no active filter`),{cards:[]};let t=await this.resolveFilteredCardIds(),n=await this.user.getActiveCards(),r=new Set(n.map(e=>e.cardID)),i=[];for(let n of t)if(r.has(n)||i.push({cardId:n,courseId:this.courseId,score:1,provenance:[{strategy:`tagFilter`,strategyName:`Tag Filter`,strategyId:`TAG_FILTER`,action:`generated`,score:1,reason:`Tag-filtered new card (tags: ${this.filter.include.join(`, `)})`}]}),i.length>=e)break;p.info(`[TagFilteredContentSource] Found ${i.length} new cards matching filter`);let a=await this.user.getPendingReviews(this.courseId),o=a.filter(e=>t.has(e.cardId));return p.info(`[TagFilteredContentSource] Found ${o.length} pending reviews matching filter (of ${a.length} total)`),{cards:[...o.map(e=>({cardId:e.cardId,courseId:e.courseId,score:1,reviewID:e._id,provenance:[{strategy:`tagFilter`,strategyName:`Tag Filter`,strategyId:`TAG_FILTER`,action:`generated`,score:1,reason:`Tag-filtered review (tags: ${this.filter.include.join(`, `)})`}]})),...i].slice(0,e)}}clearCache(){this.resolvedCardIds=null}getCourseId(){return this.courseId}getFilter(){return this.filter}};function isReview(e){return e.status===`review`||e.status===`failed-review`||`reviewID`in e}async function getStudySource(e,t){return e.type===`classroom`?await Zn.factory(e.id,t):hasActiveFilter(e.tagFilter)?new TagFilteredContentSource(e.id,e.tagFilter,t):C().getCourseDB(e.id)}export{mergeHints$1 as A,emptyTagFilter as B,newInterval as C,Rn as D,isQuestionRecord as E,recordUserOutcome as F,he as G,isTaggedPerformance as H,computeOutcomeSignal as I,k as K,scoreAccuracyInZone as L,computeEffectiveWeight as M,computeSpread as N,planPipeline as O,createOrchestrationContext as P,Loggable as R,getStreak as S,getCardHistoryID as T,A as U,hasActiveFilter as V,NameSpacer as W,ensureAppDataDirectory as _,CoursesDB as a,initializeDataDirectory as b,AdminDB as c,Kn as d,accomodateGuest as f,PipelineAssembler as g,getLocalUserDB as h,CourseDB as i,computeDeviation as j,createDefaultPipeline as k,Zn as l,buildStrategyStateId as m,isReview as n,CouchDBSyncStrategy as o,Wn as p,TagFilteredContentSource as r,tr as s,getStudySource as t,Qn as u,getAppDataDirectory as v,areQuestionRecords as w,getLapses as x,getDbPath as y,kn as z};
34
+ //# sourceMappingURL=contentSource-DwznMSMs.js.map