@vue-skuilder/db 0.2.35 → 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 (258) hide show
  1. package/CLAUDE.md +15 -4
  2. package/build.entries.mjs +12 -0
  3. package/dist/_virtual/_rolldown/runtime.mjs +8 -0
  4. package/dist/{contentSource-BteiDpxH.d.ts → contentSource-D_E7JaxR.d.ts} +1 -1
  5. package/dist/core/UserDBDebugger.mjs +285 -0
  6. package/dist/core/UserDBDebugger.mjs.map +1 -0
  7. package/dist/core/bulkImport/cardProcessor.mjs +106 -0
  8. package/dist/core/bulkImport/cardProcessor.mjs.map +1 -0
  9. package/dist/core/{index.js → index.cjs} +6438 -7784
  10. package/dist/core/index.cjs.map +1 -0
  11. package/dist/core/index.d.ts +5 -5
  12. package/dist/core/index.mjs +20 -11368
  13. package/dist/core/interfaces/contentSource.mjs +20 -0
  14. package/dist/core/interfaces/contentSource.mjs.map +1 -0
  15. package/dist/core/navigators/Pipeline.mjs +723 -0
  16. package/dist/core/navigators/Pipeline.mjs.map +1 -0
  17. package/dist/core/navigators/PipelineAssembler.mjs +86 -0
  18. package/dist/core/navigators/PipelineAssembler.mjs.map +1 -0
  19. package/dist/core/navigators/PipelineDebugger.mjs +771 -0
  20. package/dist/core/navigators/PipelineDebugger.mjs.map +1 -0
  21. package/dist/core/navigators/SrsDebugger.mjs +34 -0
  22. package/dist/core/navigators/SrsDebugger.mjs.map +1 -0
  23. package/dist/core/navigators/StrategyPressureDebugger.mjs +19 -0
  24. package/dist/core/navigators/StrategyPressureDebugger.mjs.map +1 -0
  25. package/dist/core/navigators/defaults.mjs +96 -0
  26. package/dist/core/navigators/defaults.mjs.map +1 -0
  27. package/dist/core/navigators/diversityRerank.mjs +85 -0
  28. package/dist/core/navigators/diversityRerank.mjs.map +1 -0
  29. package/dist/core/navigators/filters/WeightedFilter.mjs +81 -0
  30. package/dist/core/navigators/filters/WeightedFilter.mjs.map +1 -0
  31. package/dist/core/navigators/filters/eloDistance.mjs +244 -0
  32. package/dist/core/navigators/filters/eloDistance.mjs.map +1 -0
  33. package/dist/core/navigators/filters/hierarchyDefinition.mjs +235 -0
  34. package/dist/core/navigators/filters/hierarchyDefinition.mjs.map +1 -0
  35. package/dist/core/navigators/filters/interferenceMitigator.mjs +201 -0
  36. package/dist/core/navigators/filters/interferenceMitigator.mjs.map +1 -0
  37. package/dist/core/navigators/filters/relativePriority.mjs +135 -0
  38. package/dist/core/navigators/filters/relativePriority.mjs.map +1 -0
  39. package/dist/core/navigators/filters/userTagPreference.mjs +101 -0
  40. package/dist/core/navigators/filters/userTagPreference.mjs.map +1 -0
  41. package/dist/core/navigators/generators/CompositeGenerator.mjs +203 -0
  42. package/dist/core/navigators/generators/CompositeGenerator.mjs.map +1 -0
  43. package/dist/core/navigators/generators/elo.mjs +77 -0
  44. package/dist/core/navigators/generators/elo.mjs.map +1 -0
  45. package/dist/core/navigators/generators/prescribed.mjs +676 -0
  46. package/dist/core/navigators/generators/prescribed.mjs.map +1 -0
  47. package/dist/core/navigators/generators/srs.mjs +158 -0
  48. package/dist/core/navigators/generators/srs.mjs.map +1 -0
  49. package/dist/core/navigators/index.mjs +345 -0
  50. package/dist/core/navigators/index.mjs.map +1 -0
  51. package/dist/core/navigators/pipelinePlan.mjs +109 -0
  52. package/dist/core/navigators/pipelinePlan.mjs.map +1 -0
  53. package/dist/core/navigators/regulators.mjs +128 -0
  54. package/dist/core/navigators/regulators.mjs.map +1 -0
  55. package/dist/core/orchestration/gradient.mjs +101 -0
  56. package/dist/core/orchestration/gradient.mjs.map +1 -0
  57. package/dist/core/orchestration/index.mjs +115 -0
  58. package/dist/core/orchestration/index.mjs.map +1 -0
  59. package/dist/core/orchestration/learning.mjs +140 -0
  60. package/dist/core/orchestration/learning.mjs.map +1 -0
  61. package/dist/core/orchestration/recording.mjs +64 -0
  62. package/dist/core/orchestration/recording.mjs.map +1 -0
  63. package/dist/core/orchestration/signal.mjs +40 -0
  64. package/dist/core/orchestration/signal.mjs.map +1 -0
  65. package/dist/core/types/contentNavigationStrategy.mjs +10 -0
  66. package/dist/core/types/contentNavigationStrategy.mjs.map +1 -0
  67. package/dist/core/types/hydration.mjs +13 -0
  68. package/dist/core/types/hydration.mjs.map +1 -0
  69. package/dist/core/types/strategyState.mjs +16 -0
  70. package/dist/core/types/strategyState.mjs.map +1 -0
  71. package/dist/core/types/studySession.mjs +14 -0
  72. package/dist/core/types/studySession.mjs.map +1 -0
  73. package/dist/core/types/types-legacy.mjs +44 -0
  74. package/dist/core/types/types-legacy.mjs.map +1 -0
  75. package/dist/core/util/index.mjs +31 -0
  76. package/dist/core/util/index.mjs.map +1 -0
  77. package/dist/core/versionStamps.mjs +46 -0
  78. package/dist/core/versionStamps.mjs.map +1 -0
  79. package/dist/courseConfigRegistration.mjs +306 -0
  80. package/dist/courseConfigRegistration.mjs.map +1 -0
  81. package/dist/{dataLayerProvider-C_QWzHf-.d.ts → dataLayerProvider-BDshhSp_.d.ts} +1 -1
  82. package/dist/diagnostics/dataset.mjs +118 -0
  83. package/dist/diagnostics/dataset.mjs.map +1 -0
  84. package/dist/diagnostics/derive.mjs +318 -0
  85. package/dist/diagnostics/derive.mjs.map +1 -0
  86. package/dist/diagnostics/{index.js → index.cjs} +1 -1
  87. package/dist/diagnostics/index.d.ts +3 -3
  88. package/dist/diagnostics/index.mjs +7 -1042
  89. package/dist/diagnostics/loader.mjs +151 -0
  90. package/dist/diagnostics/loader.mjs.map +1 -0
  91. package/dist/diagnostics/pipeline.mjs +161 -0
  92. package/dist/diagnostics/pipeline.mjs.map +1 -0
  93. package/dist/diagnostics/tagElo.mjs +177 -0
  94. package/dist/diagnostics/tagElo.mjs.map +1 -0
  95. package/dist/diagnostics/text.mjs +174 -0
  96. package/dist/diagnostics/text.mjs.map +1 -0
  97. package/dist/factory.mjs +70 -0
  98. package/dist/factory.mjs.map +1 -0
  99. package/dist/impl/common/BaseUserDB.mjs +1103 -0
  100. package/dist/impl/common/BaseUserDB.mjs.map +1 -0
  101. package/dist/impl/common/userDBHelpers.mjs +49 -0
  102. package/dist/impl/common/userDBHelpers.mjs.map +1 -0
  103. package/dist/impl/common/userDBKeys.mjs +45 -0
  104. package/dist/impl/common/userDBKeys.mjs.map +1 -0
  105. package/dist/impl/couch/CouchDBSyncStrategy.mjs +272 -0
  106. package/dist/impl/couch/CouchDBSyncStrategy.mjs.map +1 -0
  107. package/dist/impl/couch/CourseSyncService.mjs +242 -0
  108. package/dist/impl/couch/CourseSyncService.mjs.map +1 -0
  109. package/dist/impl/couch/PouchDataLayerProvider.mjs +74 -0
  110. package/dist/impl/couch/PouchDataLayerProvider.mjs.map +1 -0
  111. package/dist/impl/couch/adminDB.mjs +61 -0
  112. package/dist/impl/couch/adminDB.mjs.map +1 -0
  113. package/dist/impl/couch/auth.mjs +33 -0
  114. package/dist/impl/couch/auth.mjs.map +1 -0
  115. package/dist/impl/couch/classroomDB.mjs +227 -0
  116. package/dist/impl/couch/classroomDB.mjs.map +1 -0
  117. package/dist/impl/couch/clientCache.mjs +15 -0
  118. package/dist/impl/couch/clientCache.mjs.map +1 -0
  119. package/dist/impl/couch/courseAPI.mjs +183 -0
  120. package/dist/impl/couch/courseAPI.mjs.map +1 -0
  121. package/dist/impl/couch/courseDB.mjs +729 -0
  122. package/dist/impl/couch/courseDB.mjs.map +1 -0
  123. package/dist/impl/couch/courseLookupDB.mjs +94 -0
  124. package/dist/impl/couch/courseLookupDB.mjs.map +1 -0
  125. package/dist/impl/couch/{index.js → index.cjs} +6911 -10367
  126. package/dist/impl/couch/index.cjs.map +1 -0
  127. package/dist/impl/couch/index.d.ts +12 -5
  128. package/dist/impl/couch/index.mjs +134 -12146
  129. package/dist/impl/couch/index.mjs.map +1 -1
  130. package/dist/impl/couch/pouchdb-setup.mjs +15 -0
  131. package/dist/impl/couch/pouchdb-setup.mjs.map +1 -0
  132. package/dist/impl/couch/updateQueue.mjs +101 -0
  133. package/dist/impl/couch/updateQueue.mjs.map +1 -0
  134. package/dist/impl/couch/user-course-relDB.mjs +55 -0
  135. package/dist/impl/couch/user-course-relDB.mjs.map +1 -0
  136. package/dist/impl/static/NoOpSyncStrategy.mjs +49 -0
  137. package/dist/impl/static/NoOpSyncStrategy.mjs.map +1 -0
  138. package/dist/impl/static/StaticDataLayerProvider.mjs +94 -0
  139. package/dist/impl/static/StaticDataLayerProvider.mjs.map +1 -0
  140. package/dist/impl/static/StaticDataUnpacker.mjs +311 -0
  141. package/dist/impl/static/StaticDataUnpacker.mjs.map +1 -0
  142. package/dist/impl/static/courseDB.mjs +368 -0
  143. package/dist/impl/static/courseDB.mjs.map +1 -0
  144. package/dist/impl/static/coursesDB.mjs +38 -0
  145. package/dist/impl/static/coursesDB.mjs.map +1 -0
  146. package/dist/impl/static/{index.js → index.cjs} +2461 -5992
  147. package/dist/impl/static/index.cjs.map +1 -0
  148. package/dist/impl/static/index.d.ts +4 -4
  149. package/dist/impl/static/index.mjs +6 -10741
  150. package/dist/{index-C745YB_6.d.ts → index-BLDpFYG3.d.ts} +1 -1
  151. package/dist/{index.js → index.cjs} +14070 -14239
  152. package/dist/index.cjs.map +1 -0
  153. package/dist/index.d.ts +12 -23
  154. package/dist/index.mjs +38 -16937
  155. package/dist/pouch/{index.js → index.cjs} +5 -1
  156. package/dist/pouch/index.cjs.map +1 -0
  157. package/dist/pouch/index.mjs +2 -19
  158. package/dist/study/ItemQueue.mjs +95 -0
  159. package/dist/study/ItemQueue.mjs.map +1 -0
  160. package/dist/study/MixerDebugger.mjs +303 -0
  161. package/dist/study/MixerDebugger.mjs.map +1 -0
  162. package/dist/study/SessionController.mjs +1187 -0
  163. package/dist/study/SessionController.mjs.map +1 -0
  164. package/dist/study/SessionDebugger.mjs +271 -0
  165. package/dist/study/SessionDebugger.mjs.map +1 -0
  166. package/dist/study/SessionOverlay.mjs +407 -0
  167. package/dist/study/SessionOverlay.mjs.map +1 -0
  168. package/dist/study/SourceMixer.mjs +45 -0
  169. package/dist/study/SourceMixer.mjs.map +1 -0
  170. package/dist/study/SpacedRepetition.mjs +108 -0
  171. package/dist/study/SpacedRepetition.mjs.map +1 -0
  172. package/dist/study/TagFilteredContentSource.mjs +136 -0
  173. package/dist/study/TagFilteredContentSource.mjs.map +1 -0
  174. package/dist/study/services/CardHydrationService.mjs +172 -0
  175. package/dist/study/services/CardHydrationService.mjs.map +1 -0
  176. package/dist/study/services/EloService.mjs +217 -0
  177. package/dist/study/services/EloService.mjs.map +1 -0
  178. package/dist/study/services/ResponseProcessor.mjs +190 -0
  179. package/dist/study/services/ResponseProcessor.mjs.map +1 -0
  180. package/dist/study/services/SrsService.mjs +49 -0
  181. package/dist/study/services/SrsService.mjs.map +1 -0
  182. package/dist/study/services/tagRecent.mjs +65 -0
  183. package/dist/study/services/tagRecent.mjs.map +1 -0
  184. package/dist/{types-DF0JuPbs.d.ts → types-DChCz22D.d.ts} +1 -1
  185. package/dist/{types-legacy-DdVjg81H.d.cts → types-legacy-fT5Y1Wuy.d.ts} +1 -1
  186. package/dist/userDBKeys-ne1g4Xuq.d.ts +16 -0
  187. package/dist/util/Loggable.mjs +14 -0
  188. package/dist/util/Loggable.mjs.map +1 -0
  189. package/dist/util/dataDirectory.mjs +47 -0
  190. package/dist/util/dataDirectory.mjs.map +1 -0
  191. package/dist/util/logger.mjs +86 -0
  192. package/dist/util/logger.mjs.map +1 -0
  193. package/dist/util/migrator/FileSystemAdapter.mjs +18 -0
  194. package/dist/util/migrator/FileSystemAdapter.mjs.map +1 -0
  195. package/dist/util/migrator/StaticToCouchDBMigrator.mjs +428 -0
  196. package/dist/util/migrator/StaticToCouchDBMigrator.mjs.map +1 -0
  197. package/dist/util/migrator/types.mjs +11 -0
  198. package/dist/util/migrator/types.mjs.map +1 -0
  199. package/dist/util/migrator/validation.mjs +334 -0
  200. package/dist/util/migrator/validation.mjs.map +1 -0
  201. package/dist/util/packer/CouchDBToStaticPacker.mjs +438 -0
  202. package/dist/util/packer/CouchDBToStaticPacker.mjs.map +1 -0
  203. package/dist/util/packer/{index.js → index.cjs} +73 -9
  204. package/dist/util/packer/index.cjs.map +1 -0
  205. package/dist/util/packer/index.d.ts +3 -3
  206. package/dist/util/packer/index.mjs +2 -537
  207. package/eslint.config.mjs +9 -1
  208. package/package.json +25 -13
  209. package/rolldown.config.mjs +44 -0
  210. package/src/core/UserDBDebugger.ts +47 -46
  211. package/src/core/navigators/Pipeline.ts +10 -10
  212. package/src/core/navigators/PipelineDebugger.ts +55 -55
  213. package/src/core/navigators/filters/eloDistance.ts +1 -1
  214. package/src/core/navigators/generators/elo.ts +5 -1
  215. package/src/core/navigators/index.ts +9 -3
  216. package/src/factory.ts +10 -1
  217. package/src/impl/common/BaseUserDB.ts +1 -3
  218. package/src/impl/common/index.ts +2 -0
  219. package/src/impl/common/userDBHelpers.ts +4 -58
  220. package/src/impl/common/userDBKeys.ts +64 -0
  221. package/src/impl/couch/courseDB.ts +15 -3
  222. package/src/impl/couch/index.ts +2 -18
  223. package/src/impl/couch/pouchdb-setup.ts +8 -0
  224. package/src/index.ts +1 -1
  225. package/src/study/MixerDebugger.ts +46 -46
  226. package/src/study/SessionDebugger.ts +20 -20
  227. package/src/study/SessionOverlay.ts +4 -4
  228. package/src/util/logger.ts +112 -13
  229. package/tests/core/navigators/eloGenerator.test.ts +36 -0
  230. package/tsup.config.ts +24 -21
  231. package/dist/SyncStrategy-BXliog1m.d.cts +0 -116
  232. package/dist/classroomDB-DLTtLZct.d.cts +0 -86
  233. package/dist/contentSource-FQZcZopC.d.cts +0 -2007
  234. package/dist/core/index.d.cts +0 -521
  235. package/dist/core/index.js.map +0 -1
  236. package/dist/core/index.mjs.map +0 -1
  237. package/dist/dataLayerProvider-3y21KtF-.d.cts +0 -61
  238. package/dist/diagnostics/index.d.cts +0 -561
  239. package/dist/diagnostics/index.mjs.map +0 -1
  240. package/dist/impl/couch/index.d.cts +0 -620
  241. package/dist/impl/couch/index.js.map +0 -1
  242. package/dist/impl/static/index.d.cts +0 -232
  243. package/dist/impl/static/index.js.map +0 -1
  244. package/dist/impl/static/index.mjs.map +0 -1
  245. package/dist/index-BIum9Ue2.d.cts +0 -137
  246. package/dist/index.d.cts +0 -1663
  247. package/dist/index.js.map +0 -1
  248. package/dist/index.mjs.map +0 -1
  249. package/dist/pouch/index.d.cts +0 -1
  250. package/dist/pouch/index.js.map +0 -1
  251. package/dist/pouch/index.mjs.map +0 -1
  252. package/dist/types-BcWVH4ww.d.cts +0 -58
  253. package/dist/types-legacy-DdVjg81H.d.ts +0 -168
  254. package/dist/util/packer/index.d.cts +0 -5
  255. package/dist/util/packer/index.js.map +0 -1
  256. package/dist/util/packer/index.mjs.map +0 -1
  257. package/src/study/getCardDataShape.ts +0 -34
  258. /package/dist/diagnostics/{index.js.map → index.cjs.map} +0 -0
@@ -0,0 +1,345 @@
1
+ import "../../_virtual/_rolldown/runtime.mjs";
2
+ import { logger } from "../../util/logger.mjs";
3
+ import "./diversityRerank.mjs";
4
+ import "./PipelineDebugger.mjs";
5
+ import "./SrsDebugger.mjs";
6
+ import "./StrategyPressureDebugger.mjs";
7
+ //#region src/core/navigators/index.ts
8
+ /**
9
+ * Registry mapping implementingClass names to navigator entries.
10
+ * Populated by registerNavigator() and used by ContentNavigator.create().
11
+ */
12
+ const navigatorRegistry = /* @__PURE__ */ new Map();
13
+ /**
14
+ * Register a navigator implementation.
15
+ *
16
+ * Call this to make a navigator available for instantiation by
17
+ * ContentNavigator.create() without relying on dynamic imports.
18
+ *
19
+ * Passing a `role` is optional for built-in navigators (whose roles are in
20
+ * the hardcoded `NavigatorRoles` record), but **required** for consumer-
21
+ * defined navigators that need to participate in pipeline assembly.
22
+ *
23
+ * @param implementingClass - The class name (e.g., 'elo', 'letterGatingFilter')
24
+ * @param constructor - The navigator class constructor
25
+ * @param role - Optional pipeline role (GENERATOR or FILTER)
26
+ */
27
+ function registerNavigator(implementingClass, constructor, role) {
28
+ navigatorRegistry.set(implementingClass, {
29
+ constructor,
30
+ role
31
+ });
32
+ logger.debug(`[NavigatorRegistry] Registered: ${implementingClass}${role ? ` (${role})` : ""}`);
33
+ }
34
+ /**
35
+ * Get a navigator constructor from the registry.
36
+ *
37
+ * @param implementingClass - The class name to look up
38
+ * @returns The constructor, or undefined if not registered
39
+ */
40
+ function getRegisteredNavigator(implementingClass) {
41
+ return navigatorRegistry.get(implementingClass)?.constructor;
42
+ }
43
+ /**
44
+ * Check if a navigator is registered.
45
+ *
46
+ * @param implementingClass - The class name to check
47
+ * @returns true if registered, false otherwise
48
+ */
49
+ function hasRegisteredNavigator(implementingClass) {
50
+ return navigatorRegistry.has(implementingClass);
51
+ }
52
+ /**
53
+ * Get the registered role for a navigator, if one was provided at registration.
54
+ *
55
+ * @param implementingClass - The class name to look up
56
+ * @returns The role, or undefined if not registered or no role was specified
57
+ */
58
+ function getRegisteredNavigatorRole(implementingClass) {
59
+ return navigatorRegistry.get(implementingClass)?.role;
60
+ }
61
+ /**
62
+ * A registered filter's declared kind (see `CardFilter.kind`): the static
63
+ * `kind` on its class. Undefined if unregistered or undeclared; undeclared
64
+ * filters count as gates at run time.
65
+ * @param implementingClass - The class name to look up
66
+ */
67
+ function getRegisteredFilterKind(implementingClass) {
68
+ return (navigatorRegistry.get(implementingClass)?.constructor)?.kind;
69
+ }
70
+ /**
71
+ * Get all registered navigator names.
72
+ * Useful for debugging and testing.
73
+ */
74
+ function getRegisteredNavigatorNames() {
75
+ return Array.from(navigatorRegistry.keys());
76
+ }
77
+ /**
78
+ * Initialize the navigator registry with all built-in navigators.
79
+ *
80
+ * This function dynamically imports all standard navigator implementations
81
+ * and registers them. Call this once at application startup to ensure
82
+ * all navigators are available.
83
+ *
84
+ * In test environments, this may need to be called explicitly before
85
+ * using ContentNavigator.create().
86
+ */
87
+ async function initializeNavigatorRegistry() {
88
+ logger.debug("[NavigatorRegistry] Initializing built-in navigators...");
89
+ const [eloModule, srsModule] = await Promise.all([import("./generators/elo.mjs"), import("./generators/srs.mjs")]);
90
+ const prescribedModule = await import("./generators/prescribed.mjs");
91
+ registerNavigator("elo", eloModule.default);
92
+ registerNavigator("srs", srsModule.default);
93
+ registerNavigator("prescribed", prescribedModule.default);
94
+ const [hierarchyModule, interferenceModule, relativePriorityModule, userTagPreferenceModule, eloDistanceModule] = await Promise.all([
95
+ import("./filters/hierarchyDefinition.mjs"),
96
+ import("./filters/interferenceMitigator.mjs"),
97
+ import("./filters/relativePriority.mjs"),
98
+ import("./filters/userTagPreference.mjs"),
99
+ import("./filters/eloDistance.mjs")
100
+ ]);
101
+ registerNavigator("hierarchyDefinition", hierarchyModule.default);
102
+ registerNavigator("interferenceMitigator", interferenceModule.default);
103
+ registerNavigator("relativePriority", relativePriorityModule.default);
104
+ registerNavigator("userTagPreference", userTagPreferenceModule.default);
105
+ registerNavigator("eloDistance", eloDistanceModule.default);
106
+ logger.debug(`[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(", ")}`);
107
+ }
108
+ /**
109
+ * Extract card origin from provenance trail.
110
+ *
111
+ * The first provenance entry (from the generator) indicates whether
112
+ * this is a new card, review, or failed card. We parse the reason
113
+ * string to extract this information.
114
+ *
115
+ * @param card - Card with provenance trail
116
+ * @returns Card origin ('new', 'review', or 'failed')
117
+ */
118
+ function getCardOrigin(card) {
119
+ if (card.provenance.length === 0) throw new Error("Card has no provenance - cannot determine origin");
120
+ const reason = card.provenance[0].reason.toLowerCase();
121
+ if (reason.includes("failed")) return "failed";
122
+ if (reason.includes("review")) return "review";
123
+ return "new";
124
+ }
125
+ let Navigators = /* @__PURE__ */ function(Navigators) {
126
+ Navigators["ELO"] = "elo";
127
+ Navigators["SRS"] = "srs";
128
+ Navigators["PRESCRIBED"] = "prescribed";
129
+ Navigators["HIERARCHY"] = "hierarchyDefinition";
130
+ Navigators["INTERFERENCE"] = "interferenceMitigator";
131
+ Navigators["RELATIVE_PRIORITY"] = "relativePriority";
132
+ Navigators["USER_TAG_PREFERENCE"] = "userTagPreference";
133
+ Navigators["ELO_DISTANCE"] = "eloDistance";
134
+ return Navigators;
135
+ }({});
136
+ /**
137
+ * Role classification for navigation strategies.
138
+ *
139
+ * - GENERATOR: Produces candidate cards with initial scores
140
+ * - FILTER: Transforms cards with score multipliers
141
+ */
142
+ let NavigatorRole = /* @__PURE__ */ function(NavigatorRole) {
143
+ NavigatorRole["GENERATOR"] = "generator";
144
+ NavigatorRole["FILTER"] = "filter";
145
+ return NavigatorRole;
146
+ }({});
147
+ /**
148
+ * Registry mapping navigator implementations to their roles.
149
+ */
150
+ const NavigatorRoles = {
151
+ [Navigators.ELO]: NavigatorRole.GENERATOR,
152
+ [Navigators.SRS]: NavigatorRole.GENERATOR,
153
+ [Navigators.PRESCRIBED]: NavigatorRole.GENERATOR,
154
+ [Navigators.HIERARCHY]: NavigatorRole.FILTER,
155
+ [Navigators.INTERFERENCE]: NavigatorRole.FILTER,
156
+ [Navigators.RELATIVE_PRIORITY]: NavigatorRole.FILTER,
157
+ [Navigators.USER_TAG_PREFERENCE]: NavigatorRole.FILTER,
158
+ [Navigators.ELO_DISTANCE]: NavigatorRole.FILTER
159
+ };
160
+ /**
161
+ * Check if a navigator implementation is a generator.
162
+ *
163
+ * @param impl - Navigator implementation name (e.g., 'elo', 'hierarchyDefinition')
164
+ * @returns true if the navigator is a generator, false otherwise
165
+ */
166
+ function isGenerator(impl) {
167
+ if (NavigatorRoles[impl] === NavigatorRole.GENERATOR) return true;
168
+ return getRegisteredNavigatorRole(impl) === NavigatorRole.GENERATOR;
169
+ }
170
+ /**
171
+ * Check if a navigator implementation is a filter.
172
+ *
173
+ * Checks the built-in NavigatorRoles enum first, then falls back to the
174
+ * navigator registry for consumer-registered navigators.
175
+ *
176
+ * @param impl - Navigator implementation name (e.g., 'elo', 'letterGatingFilter')
177
+ * @returns true if the navigator is a filter, false otherwise
178
+ */
179
+ function isFilter(impl) {
180
+ if (NavigatorRoles[impl] === NavigatorRole.FILTER) return true;
181
+ return getRegisteredNavigatorRole(impl) === NavigatorRole.FILTER;
182
+ }
183
+ /**
184
+ * Abstract base class for navigation strategies.
185
+ *
186
+ * This class exists primarily for backward compatibility with legacy code.
187
+ * New code should use CardGenerator or CardFilter interfaces directly.
188
+ *
189
+ * The class implements StudyContentSource for compatibility with SessionController.
190
+ * Once SessionController migrates to use getWeightedCards() exclusively,
191
+ * the legacy methods can be removed.
192
+ */
193
+ var ContentNavigator = class {
194
+ /** User interface for this navigation session */
195
+ user;
196
+ /** Course interface for this navigation session */
197
+ course;
198
+ /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
199
+ strategyName;
200
+ /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
201
+ strategyId;
202
+ /** Evolutionary weighting configuration */
203
+ learnable;
204
+ /** Whether to bypass deviation (manual/static weighting) */
205
+ staticWeight;
206
+ /**
207
+ * Constructor for standard navigators.
208
+ * Call this from subclass constructors to initialize common fields.
209
+ *
210
+ * Note: CompositeGenerator and Pipeline call super() without args, then set
211
+ * user/course fields directly if needed.
212
+ */
213
+ constructor(user, course, strategyData) {
214
+ this.user = user;
215
+ this.course = course;
216
+ if (strategyData) {
217
+ this.strategyName = strategyData.name;
218
+ this.strategyId = strategyData._id;
219
+ this.learnable = strategyData.learnable;
220
+ this.staticWeight = strategyData.staticWeight;
221
+ }
222
+ }
223
+ /**
224
+ * Unique key identifying this strategy for state storage.
225
+ *
226
+ * Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
227
+ * Override in subclasses if multiple instances of the same strategy type
228
+ * need separate state storage.
229
+ */
230
+ get strategyKey() {
231
+ return this.constructor.name;
232
+ }
233
+ /**
234
+ * Get this strategy's persisted state for the current course.
235
+ *
236
+ * @returns The strategy's data payload, or null if no state exists
237
+ * @throws Error if user or course is not initialized
238
+ */
239
+ async getStrategyState() {
240
+ if (!this.user || !this.course) throw new Error("Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.");
241
+ return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
242
+ }
243
+ /**
244
+ * Persist this strategy's state for the current course.
245
+ *
246
+ * @param data - The strategy's data payload to store
247
+ * @throws Error if user or course is not initialized
248
+ */
249
+ async putStrategyState(data) {
250
+ if (!this.user || !this.course) throw new Error("Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.");
251
+ return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
252
+ }
253
+ /**
254
+ * Factory method to create navigator instances.
255
+ *
256
+ * First checks the navigator registry for a pre-registered constructor.
257
+ * If not found, falls back to dynamic import (for custom navigators).
258
+ *
259
+ * For reliable operation in test environments, call initializeNavigatorRegistry()
260
+ * before using this method.
261
+ *
262
+ * @param user - User interface
263
+ * @param course - Course interface
264
+ * @param strategyData - Strategy configuration document
265
+ * @returns the runtime object used to steer a study session.
266
+ */
267
+ static async create(user, course, strategyData) {
268
+ const implementingClass = strategyData.implementingClass;
269
+ const RegisteredImpl = getRegisteredNavigator(implementingClass);
270
+ if (RegisteredImpl) {
271
+ logger.debug(`[ContentNavigator.create] Using registered navigator: ${implementingClass}`);
272
+ return new RegisteredImpl(user, course, strategyData);
273
+ }
274
+ logger.debug(`[ContentNavigator.create] Navigator not in registry, attempting dynamic import: ${implementingClass}`);
275
+ let NavigatorImpl;
276
+ const load = (specifier) => import(
277
+ /* @vite-ignore */
278
+ specifier
279
+ );
280
+ for (const ext of [
281
+ ".ts",
282
+ ".js",
283
+ ""
284
+ ]) {
285
+ try {
286
+ NavigatorImpl = (await load(`./generators/${implementingClass}${ext}`)).default;
287
+ if (NavigatorImpl) break;
288
+ } catch (e) {
289
+ logger.debug(`Failed to load generator ${implementingClass}${ext}:`, e);
290
+ }
291
+ try {
292
+ NavigatorImpl = (await load(`./filters/${implementingClass}${ext}`)).default;
293
+ if (NavigatorImpl) break;
294
+ } catch (e) {
295
+ logger.debug(`Failed to load filter ${implementingClass}${ext}:`, e);
296
+ }
297
+ try {
298
+ NavigatorImpl = (await load(`./${implementingClass}${ext}`)).default;
299
+ if (NavigatorImpl) break;
300
+ } catch (e) {
301
+ logger.debug(`Failed to load legacy ${implementingClass}${ext}:`, e);
302
+ }
303
+ if (NavigatorImpl) break;
304
+ }
305
+ if (!NavigatorImpl) throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
306
+ return new NavigatorImpl(user, course, strategyData);
307
+ }
308
+ /**
309
+ * Get cards with suitability scores and provenance trails.
310
+ *
311
+ * **This is the PRIMARY API for navigation strategies.**
312
+ *
313
+ * Returns cards ranked by suitability score (0-1). Higher scores indicate
314
+ * better candidates for presentation. Each card includes a provenance trail
315
+ * documenting how strategies contributed to the final score.
316
+ *
317
+ * ## Implementation Required
318
+ * All navigation strategies MUST override this method. The base class does
319
+ * not provide a default implementation.
320
+ *
321
+ * ## For Generators
322
+ * Override this method to generate candidates and compute scores based on
323
+ * your strategy's logic (e.g., ELO proximity, review urgency). Create the
324
+ * initial provenance entry with action='generated'.
325
+ *
326
+ * ## For Filters
327
+ * Filters should implement the CardFilter interface instead and be composed
328
+ * via Pipeline. Filters do not directly implement getWeightedCards().
329
+ *
330
+ * @param limit - Maximum cards to return
331
+ * @returns Cards sorted by score descending, with provenance trails
332
+ */
333
+ async getWeightedCards(_limit) {
334
+ throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);
335
+ }
336
+ /**
337
+ * Set ephemeral hints for the next pipeline run.
338
+ * No-op for non-Pipeline navigators. Pipeline overrides this.
339
+ */
340
+ setEphemeralHints(_hints) {}
341
+ };
342
+ //#endregion
343
+ export { ContentNavigator, NavigatorRole, NavigatorRoles, Navigators, getCardOrigin, getRegisteredFilterKind, getRegisteredNavigator, getRegisteredNavigatorNames, getRegisteredNavigatorRole, hasRegisteredNavigator, initializeNavigatorRegistry, isFilter, isGenerator, registerNavigator };
344
+
345
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../src/core/navigators/index.ts"],"sourcesContent":["import { StudyContentSource, UserDBInterface, CourseDBInterface } from '..';\nimport type { FilterKind } from './filters/types';\n\n// Re-export filter types\nexport type { CardFilter, FilterContext, CardFilterFactory, FilterKind } from './filters/types';\n\n// Re-export generator types\nexport type { CardGenerator, GeneratorContext, CardGeneratorFactory, GeneratorResult, ReplanHints } from './generators/types';\n\n// Re-export the diversity re-rank stage (pipeline stage 3)\nexport {\n diversityRerank,\n DIVERSITY_STRENGTH,\n DIVERSITY_FLOOR,\n type DiversityRerankOptions,\n} from './diversityRerank';\nimport type { GeneratorResult, ReplanHints } from './generators/types';\n\n// Re-export pipeline debugger API\nexport {\n pipelineDebugAPI,\n mountPipelineDebugger,\n getActivePipeline,\n setDebugSessionId,\n getRunsForSession,\n drainCapturedRuns,\n type PipelineRunReport,\n type RunReportCard,\n type GeneratorSummary,\n type FilterImpact,\n} from './PipelineDebugger';\n\n// Re-export the commit-free forecast capability surface.\nexport type { PipelineForecaster } from './Pipeline';\nexport {\n getSrsBacklogDebug,\n clearSrsBacklogDebug,\n type SrsBacklogDebug,\n} from './SrsDebugger';\n\n// Re-export the generic strategy-pressure debug channel. `captureStrategyPressure`\n// is part of the consumer surface: client-defined strategies (registered via\n// registerNavigator) push their backpressure state through it for the live\n// session overlay.\nexport {\n captureStrategyPressure,\n getStrategyPressureDebug,\n clearStrategyPressureDebug,\n type StrategyPressureDebug,\n type PressureGaugeDebug,\n} from './StrategyPressureDebugger';\n\nimport { LearnableWeight } from '../types/contentNavigationStrategy';\nexport type { ContentNavigationStrategyData, LearnableWeight } from '../types/contentNavigationStrategy';\nimport type { ContentNavigationStrategyData } from '../types/contentNavigationStrategy';\nimport { logger } from '../../util/logger';\n\n// ============================================================================\n// NAVIGATOR REGISTRY\n// ============================================================================\n//\n// Static registry of navigator implementations. This allows ContentNavigator.create()\n// to instantiate navigators without relying on dynamic imports, which don't work\n// reliably in all environments (e.g., test runners, bundled code).\n//\n// Usage:\n// 1. Import your navigator class\n// 2. Call registerNavigator('implementingClass', YourNavigatorClass)\n// 3. ContentNavigator.create() will use the registry before falling back to\n// dynamic import\n//\n// ============================================================================\n\n/**\n * Type for navigator constructor functions.\n */\nexport type NavigatorConstructor = new (\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n) => ContentNavigator;\n\n/**\n * Entry in the navigator registry, storing the constructor and an optional\n * pipeline role. The role is used by PipelineAssembler to classify\n * consumer-registered navigators that aren't in the built-in Navigators enum.\n */\ninterface NavigatorRegistryEntry {\n constructor: NavigatorConstructor;\n role?: NavigatorRole;\n}\n\n/**\n * Registry mapping implementingClass names to navigator entries.\n * Populated by registerNavigator() and used by ContentNavigator.create().\n */\nconst navigatorRegistry = new Map<string, NavigatorRegistryEntry>();\n\n/**\n * Register a navigator implementation.\n *\n * Call this to make a navigator available for instantiation by\n * ContentNavigator.create() without relying on dynamic imports.\n *\n * Passing a `role` is optional for built-in navigators (whose roles are in\n * the hardcoded `NavigatorRoles` record), but **required** for consumer-\n * defined navigators that need to participate in pipeline assembly.\n *\n * @param implementingClass - The class name (e.g., 'elo', 'letterGatingFilter')\n * @param constructor - The navigator class constructor\n * @param role - Optional pipeline role (GENERATOR or FILTER)\n */\nexport function registerNavigator(\n implementingClass: string,\n constructor: NavigatorConstructor,\n role?: NavigatorRole\n): void {\n navigatorRegistry.set(implementingClass, { constructor, role });\n logger.debug(`[NavigatorRegistry] Registered: ${implementingClass}${role ? ` (${role})` : ''}`);\n}\n\n/**\n * Get a navigator constructor from the registry.\n *\n * @param implementingClass - The class name to look up\n * @returns The constructor, or undefined if not registered\n */\nexport function getRegisteredNavigator(implementingClass: string): NavigatorConstructor | undefined {\n return navigatorRegistry.get(implementingClass)?.constructor;\n}\n\n/**\n * Check if a navigator is registered.\n *\n * @param implementingClass - The class name to check\n * @returns true if registered, false otherwise\n */\nexport function hasRegisteredNavigator(implementingClass: string): boolean {\n return navigatorRegistry.has(implementingClass);\n}\n\n/**\n * Get the registered role for a navigator, if one was provided at registration.\n *\n * @param implementingClass - The class name to look up\n * @returns The role, or undefined if not registered or no role was specified\n */\nexport function getRegisteredNavigatorRole(implementingClass: string): NavigatorRole | undefined {\n return navigatorRegistry.get(implementingClass)?.role;\n}\n\n/**\n * A registered filter's declared kind (see `CardFilter.kind`): the static\n * `kind` on its class. Undefined if unregistered or undeclared; undeclared\n * filters count as gates at run time.\n * @param implementingClass - The class name to look up\n */\nexport function getRegisteredFilterKind(implementingClass: string): FilterKind | undefined {\n const ctor = navigatorRegistry.get(implementingClass)?.constructor as\n | { kind?: FilterKind }\n | undefined;\n return ctor?.kind;\n}\n\n/**\n * Get all registered navigator names.\n * Useful for debugging and testing.\n */\nexport function getRegisteredNavigatorNames(): string[] {\n return Array.from(navigatorRegistry.keys());\n}\n\n/**\n * Initialize the navigator registry with all built-in navigators.\n *\n * This function dynamically imports all standard navigator implementations\n * and registers them. Call this once at application startup to ensure\n * all navigators are available.\n *\n * In test environments, this may need to be called explicitly before\n * using ContentNavigator.create().\n */\nexport async function initializeNavigatorRegistry(): Promise<void> {\n logger.debug('[NavigatorRegistry] Initializing built-in navigators...');\n\n // Import and register generators\n const [eloModule, srsModule] = await Promise.all([\n import('./generators/elo'),\n import('./generators/srs'),\n ]);\n const prescribedModule = await import('./generators/prescribed');\n registerNavigator('elo', eloModule.default);\n registerNavigator('srs', srsModule.default);\n registerNavigator('prescribed', prescribedModule.default);\n\n // Import and register filters\n const [\n hierarchyModule,\n interferenceModule,\n relativePriorityModule,\n userTagPreferenceModule,\n eloDistanceModule,\n ] = await Promise.all([\n import('./filters/hierarchyDefinition'),\n import('./filters/interferenceMitigator'),\n import('./filters/relativePriority'),\n import('./filters/userTagPreference'),\n import('./filters/eloDistance'),\n ]);\n registerNavigator('hierarchyDefinition', hierarchyModule.default);\n registerNavigator('interferenceMitigator', interferenceModule.default);\n registerNavigator('relativePriority', relativePriorityModule.default);\n registerNavigator('userTagPreference', userTagPreferenceModule.default);\n registerNavigator('eloDistance', eloDistanceModule.default);\n\n logger.debug(\n `[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(', ')}`\n );\n}\n\n// ============================================================================\n// NAVIGATION STRATEGY API\n// ============================================================================\n//\n// This module defines the ContentNavigator base class and the WeightedCard type,\n// which form the foundation of the pluggable navigation strategy system.\n//\n// KEY CONCEPTS:\n//\n// 1. WeightedCard - A card with a suitability score (0-1) and provenance trail.\n// The provenance tracks how each strategy in the pipeline contributed to\n// the card's final score, ensuring transparency and debuggability.\n//\n// 2. ContentNavigator - Abstract base class for backward compatibility.\n// New code should use CardGenerator or CardFilter interfaces directly.\n//\n// 3. CardGenerator vs CardFilter:\n// - Generators (ELO, SRS) produce candidate cards with scores\n// - Filters (Hierarchy, Interference, Priority, EloDistance) transform scores\n//\n// 4. Pipeline architecture:\n// Pipeline(generator, [filter1, filter2, ...]) executes:\n// cards = generator.getWeightedCards()\n// cards = filter1.transform(cards, context)\n// cards = filter2.transform(cards, context)\n// return sorted(cards)\n//\n// 5. Provenance tracking - Each strategy adds an entry explaining its contribution.\n// This makes the system transparent and debuggable.\n//\n// ============================================================================\n\n/**\n * Tracks a single strategy's contribution to a card's final score.\n *\n * Each strategy in the pipeline adds a StrategyContribution entry to the\n * card's provenance array, creating an audit trail of scoring decisions.\n */\nexport interface StrategyContribution {\n /**\n * Strategy type (implementing class name).\n * Examples: 'elo', 'hierarchyDefinition', 'interferenceMitigator'\n */\n strategy: string;\n\n /**\n * Human-readable name identifying this specific strategy instance.\n * Extracted from ContentNavigationStrategyData.name.\n * Courses may have multiple instances of the same strategy type with\n * different configurations.\n *\n * Examples:\n * - \"ELO (default)\"\n * - \"Interference: b/d/p confusion\"\n * - \"Interference: phonetic confusables\"\n * - \"Priority: Common letters first\"\n */\n strategyName: string;\n\n /**\n * Unique database document ID for this strategy instance.\n * Extracted from ContentNavigationStrategyData._id.\n * Use this to fetch the full strategy configuration document.\n *\n * Examples:\n * - \"NAVIGATION_STRATEGY-ELO-default\"\n * - \"NAVIGATION_STRATEGY-interference-bdp\"\n * - \"NAVIGATION_STRATEGY-priority-common-letters\"\n */\n strategyId: string;\n\n /**\n * What the strategy did:\n * - 'generated': Strategy produced this card (generators only)\n * - 'passed': Strategy evaluated but didn't change score (transparent pass-through)\n * - 'boosted': Strategy increased the score\n * - 'penalized': Strategy decreased the score\n */\n action: 'generated' | 'passed' | 'boosted' | 'penalized';\n\n /** Score after this strategy's processing */\n score: number;\n\n /**\n * The effective weight applied for this strategy instance.\n * If using evolutionary orchestration, this includes deviation.\n * If omitted, implies weight 1.0 (legacy behavior).\n */\n effectiveWeight?: number;\n\n /**\n * The deviation factor applied to this user's cohort for this strategy.\n * Range [-1.0, 1.0].\n */\n deviation?: number;\n\n /**\n * Human-readable explanation of the strategy's decision.\n *\n * Examples:\n * - \"ELO distance 75, new card\"\n * - \"Prerequisites met: letter-sounds\"\n * - \"Interferes with immature tag 'd' (decay 0.8)\"\n * - \"High-priority tag 's' (0.95) → boost 1.15x\"\n *\n * Required for transparency - silent adjusters are anti-patterns.\n */\n reason: string;\n}\n\n/**\n * A card with a suitability score and provenance trail.\n *\n * Scores range from 0-1:\n * - 1.0 = fully suitable\n * - 0.0 = hard filter (e.g., prerequisite not met)\n * - 0.5 = neutral\n * - Intermediate values = soft preference\n *\n * Provenance tracks the scoring pipeline:\n * - First entry: Generator that produced the card\n * - Subsequent entries: Filters that transformed the score\n * - Each entry includes action and human-readable reason\n */\nexport interface WeightedCard {\n cardId: string;\n courseId: string;\n /** Suitability score from 0-1 */\n score: number;\n /**\n * Audit trail of strategy contributions.\n * First entry is from the generator, subsequent entries from filters.\n */\n provenance: StrategyContribution[];\n /**\n * Pre-fetched tags. Populated by Pipeline before filters run.\n * Filters should use this instead of querying getAppliedTags() individually.\n */\n tags?: string[];\n /**\n * Review document ID (_id from ScheduledCard).\n * Present when this card originated from SRS review scheduling.\n * Used by SessionController to track review outcomes and maintain review state.\n */\n reviewID?: string;\n /**\n * The card's global ELO, when the generator already knows it (the ELO\n * generator reads it during retrieval). Lets the ELO distance filter skip a\n * fetch.\n */\n cardElo?: number;\n /**\n * A review's SRS urgency in [0, 1] (overdueness and interval recency), set by\n * the SRS generator. The review-mass regulator weighs the backlog by it.\n */\n reviewUrgency?: number;\n}\n\n/**\n * Extract card origin from provenance trail.\n *\n * The first provenance entry (from the generator) indicates whether\n * this is a new card, review, or failed card. We parse the reason\n * string to extract this information.\n *\n * @param card - Card with provenance trail\n * @returns Card origin ('new', 'review', or 'failed')\n */\nexport function getCardOrigin(card: WeightedCard): 'new' | 'review' | 'failed' {\n if (card.provenance.length === 0) {\n throw new Error('Card has no provenance - cannot determine origin');\n }\n\n const firstEntry = card.provenance[0];\n const reason = firstEntry.reason.toLowerCase();\n\n if (reason.includes('failed')) {\n return 'failed';\n }\n if (reason.includes('review')) {\n return 'review';\n }\n return 'new';\n}\n\nexport enum Navigators {\n ELO = 'elo',\n SRS = 'srs',\n PRESCRIBED = 'prescribed',\n HIERARCHY = 'hierarchyDefinition',\n INTERFERENCE = 'interferenceMitigator',\n RELATIVE_PRIORITY = 'relativePriority',\n USER_TAG_PREFERENCE = 'userTagPreference',\n ELO_DISTANCE = 'eloDistance',\n}\n\n// ============================================================================\n// NAVIGATOR ROLE CLASSIFICATION\n// ============================================================================\n//\n// Navigators are classified as either generators or filters:\n// - Generators: Produce candidate cards (ELO, SRS)\n// - Filters: Transform/score candidates (Hierarchy, Interference, RelativePriority)\n//\n// This classification is used by PipelineAssembler to build pipelines:\n// 1. Instantiate generators (possibly into a CompositeGenerator)\n// 2. Instantiate filters\n// 3. Create Pipeline(generator, filters)\n//\n// ============================================================================\n\n/**\n * Role classification for navigation strategies.\n *\n * - GENERATOR: Produces candidate cards with initial scores\n * - FILTER: Transforms cards with score multipliers\n */\nexport enum NavigatorRole {\n GENERATOR = 'generator',\n FILTER = 'filter',\n}\n\n/**\n * Registry mapping navigator implementations to their roles.\n */\nexport const NavigatorRoles: Record<Navigators, NavigatorRole> = {\n [Navigators.ELO]: NavigatorRole.GENERATOR,\n [Navigators.SRS]: NavigatorRole.GENERATOR,\n [Navigators.PRESCRIBED]: NavigatorRole.GENERATOR,\n [Navigators.HIERARCHY]: NavigatorRole.FILTER,\n [Navigators.INTERFERENCE]: NavigatorRole.FILTER,\n [Navigators.RELATIVE_PRIORITY]: NavigatorRole.FILTER,\n [Navigators.USER_TAG_PREFERENCE]: NavigatorRole.FILTER,\n [Navigators.ELO_DISTANCE]: NavigatorRole.FILTER,\n};\n\n/**\n * Check if a navigator implementation is a generator.\n *\n * @param impl - Navigator implementation name (e.g., 'elo', 'hierarchyDefinition')\n * @returns true if the navigator is a generator, false otherwise\n */\nexport function isGenerator(impl: string): boolean {\n if (NavigatorRoles[impl as Navigators] === NavigatorRole.GENERATOR) return true;\n // Fallback: check the registry for consumer-registered navigators\n return getRegisteredNavigatorRole(impl) === NavigatorRole.GENERATOR;\n}\n\n/**\n * Check if a navigator implementation is a filter.\n *\n * Checks the built-in NavigatorRoles enum first, then falls back to the\n * navigator registry for consumer-registered navigators.\n *\n * @param impl - Navigator implementation name (e.g., 'elo', 'letterGatingFilter')\n * @returns true if the navigator is a filter, false otherwise\n */\nexport function isFilter(impl: string): boolean {\n if (NavigatorRoles[impl as Navigators] === NavigatorRole.FILTER) return true;\n // Fallback: check the registry for consumer-registered navigators\n return getRegisteredNavigatorRole(impl) === NavigatorRole.FILTER;\n}\n\n/**\n * Abstract base class for navigation strategies.\n *\n * This class exists primarily for backward compatibility with legacy code.\n * New code should use CardGenerator or CardFilter interfaces directly.\n *\n * The class implements StudyContentSource for compatibility with SessionController.\n * Once SessionController migrates to use getWeightedCards() exclusively,\n * the legacy methods can be removed.\n */\nexport abstract class ContentNavigator implements StudyContentSource {\n /** User interface for this navigation session */\n protected user: UserDBInterface;\n\n /** Course interface for this navigation session */\n protected course: CourseDBInterface;\n\n /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */\n protected strategyName?: string;\n\n /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */\n protected strategyId?: string;\n\n /** Evolutionary weighting configuration */\n public learnable?: LearnableWeight;\n\n /** Whether to bypass deviation (manual/static weighting) */\n public staticWeight?: boolean;\n\n /**\n * Constructor for standard navigators.\n * Call this from subclass constructors to initialize common fields.\n *\n * Note: CompositeGenerator and Pipeline call super() without args, then set\n * user/course fields directly if needed.\n */\n constructor(\n user?: UserDBInterface,\n course?: CourseDBInterface,\n strategyData?: ContentNavigationStrategyData\n ) {\n this.user = user!;\n this.course = course!;\n if (strategyData) {\n this.strategyName = strategyData.name;\n this.strategyId = strategyData._id;\n this.learnable = strategyData.learnable;\n this.staticWeight = strategyData.staticWeight;\n }\n }\n\n // ============================================================================\n // STRATEGY STATE HELPERS\n // ============================================================================\n //\n // These methods allow strategies to persist their own state (user preferences,\n // learned patterns, temporal tracking) in the user database.\n //\n // ============================================================================\n\n /**\n * Unique key identifying this strategy for state storage.\n *\n * Defaults to the constructor name (e.g., \"UserTagPreferenceFilter\").\n * Override in subclasses if multiple instances of the same strategy type\n * need separate state storage.\n */\n protected get strategyKey(): string {\n return this.constructor.name;\n }\n\n /**\n * Get this strategy's persisted state for the current course.\n *\n * @returns The strategy's data payload, or null if no state exists\n * @throws Error if user or course is not initialized\n */\n protected async getStrategyState<T>(): Promise<T | null> {\n if (!this.user || !this.course) {\n throw new Error(\n `Cannot get strategy state: navigator not properly initialized. ` +\n `Ensure user and course are provided to constructor.`\n );\n }\n return this.user.getStrategyState<T>(this.course.getCourseID(), this.strategyKey);\n }\n\n /**\n * Persist this strategy's state for the current course.\n *\n * @param data - The strategy's data payload to store\n * @throws Error if user or course is not initialized\n */\n protected async putStrategyState<T>(data: T): Promise<void> {\n if (!this.user || !this.course) {\n throw new Error(\n `Cannot put strategy state: navigator not properly initialized. ` +\n `Ensure user and course are provided to constructor.`\n );\n }\n return this.user.putStrategyState<T>(this.course.getCourseID(), this.strategyKey, data);\n }\n\n /**\n * Factory method to create navigator instances.\n *\n * First checks the navigator registry for a pre-registered constructor.\n * If not found, falls back to dynamic import (for custom navigators).\n *\n * For reliable operation in test environments, call initializeNavigatorRegistry()\n * before using this method.\n *\n * @param user - User interface\n * @param course - Course interface\n * @param strategyData - Strategy configuration document\n * @returns the runtime object used to steer a study session.\n */\n static async create(\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n ): Promise<ContentNavigator> {\n const implementingClass = strategyData.implementingClass;\n\n // First, check the registry for a pre-registered constructor\n const RegisteredImpl = getRegisteredNavigator(implementingClass);\n if (RegisteredImpl) {\n logger.debug(`[ContentNavigator.create] Using registered navigator: ${implementingClass}`);\n return new RegisteredImpl(user, course, strategyData);\n }\n\n // Fall back to dynamic import for custom/unknown navigators\n logger.debug(\n `[ContentNavigator.create] Navigator not in registry, attempting dynamic import: ${implementingClass}`\n );\n\n let NavigatorImpl;\n\n // Specifiers built at runtime, never template literals: bundlers expand\n // `import(`./generators/${x}`)` into a glob over the directory, which in a\n // per-module dist matches .map and .d.ts files and breaks the app's build.\n // This fallback only resolves from source (no '.mjs' variation).\n const load = (specifier: string) => import(/* @vite-ignore */ specifier);\n\n // Try different extension variations\n const variations = ['.ts', '.js', ''];\n\n for (const ext of variations) {\n // Try generators directory\n try {\n const module = await load(`./generators/${implementingClass}${ext}`);\n NavigatorImpl = module.default;\n if (NavigatorImpl) break;\n } catch (e) {\n logger.debug(`Failed to load generator ${implementingClass}${ext}:`, e);\n }\n\n // Try filters directory\n try {\n const module = await load(`./filters/${implementingClass}${ext}`);\n NavigatorImpl = module.default;\n if (NavigatorImpl) break;\n } catch (e) {\n logger.debug(`Failed to load filter ${implementingClass}${ext}:`, e);\n }\n\n // Try current directory (legacy)\n try {\n const module = await load(`./${implementingClass}${ext}`);\n NavigatorImpl = module.default;\n if (NavigatorImpl) break;\n } catch (e) {\n logger.debug(`Failed to load legacy ${implementingClass}${ext}:`, e);\n }\n \n if (NavigatorImpl) break;\n }\n\n if (!NavigatorImpl) {\n throw new Error(`Could not load navigator implementation for: ${implementingClass}`);\n }\n\n return new NavigatorImpl(user, course, strategyData);\n }\n\n /**\n * Get cards with suitability scores and provenance trails.\n *\n * **This is the PRIMARY API for navigation strategies.**\n *\n * Returns cards ranked by suitability score (0-1). Higher scores indicate\n * better candidates for presentation. Each card includes a provenance trail\n * documenting how strategies contributed to the final score.\n *\n * ## Implementation Required\n * All navigation strategies MUST override this method. The base class does\n * not provide a default implementation.\n *\n * ## For Generators\n * Override this method to generate candidates and compute scores based on\n * your strategy's logic (e.g., ELO proximity, review urgency). Create the\n * initial provenance entry with action='generated'.\n *\n * ## For Filters\n * Filters should implement the CardFilter interface instead and be composed\n * via Pipeline. Filters do not directly implement getWeightedCards().\n *\n * @param limit - Maximum cards to return\n * @returns Cards sorted by score descending, with provenance trails\n */\n async getWeightedCards(_limit: number): Promise<GeneratorResult> {\n throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);\n }\n\n /**\n * Set ephemeral hints for the next pipeline run.\n * No-op for non-Pipeline navigators. Pipeline overrides this.\n */\n setEphemeralHints(_hints: ReplanHints): void {\n // no-op — only Pipeline implements this\n }\n}\n"],"mappings":"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"}
@@ -0,0 +1,109 @@
1
+ import "../../_virtual/_rolldown/runtime.mjs";
2
+ import { NavigatorRole, getRegisteredFilterKind, isFilter, isGenerator } from "./index.mjs";
3
+ import { DEFAULT_REGULATOR_CONFIG } from "./regulators.mjs";
4
+ import { createDefaultEloDistanceStrategy, createDefaultEloStrategy, createDefaultSrsStrategy } from "./defaults.mjs";
5
+ //#region src/core/navigators/pipelinePlan.ts
6
+ /**
7
+ * The steps every pipeline run takes, in order (`Pipeline.getWeightedCards`).
8
+ * `generate` and `filter` are where a plan's navigators run; the rest are
9
+ * fixed framework behaviour.
10
+ */
11
+ const PIPELINE_STAGES = [
12
+ {
13
+ key: "generate",
14
+ title: "Generate",
15
+ 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."
16
+ },
17
+ {
18
+ key: "filter",
19
+ title: "Filter",
20
+ 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."
21
+ },
22
+ {
23
+ key: "drop-zero",
24
+ title: "Drop zero scores",
25
+ summary: "Candidates whose score reached 0 leave the pool."
26
+ },
27
+ {
28
+ key: "regulate",
29
+ title: "Regulate",
30
+ 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."
31
+ },
32
+ {
33
+ key: "hints",
34
+ title: "Apply hints",
35
+ 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."
36
+ },
37
+ {
38
+ key: "diversity",
39
+ title: "Diversity re-rank",
40
+ 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."
41
+ },
42
+ {
43
+ key: "select",
44
+ title: "Select",
45
+ summary: "Highest scores first, up to the run's limit. The session mixes them into its supply queue."
46
+ }
47
+ ];
48
+ function planned(strategy, role, origin) {
49
+ const kind = role === NavigatorRole.FILTER ? getRegisteredFilterKind(strategy.implementingClass) : void 0;
50
+ return {
51
+ role,
52
+ origin,
53
+ name: strategy.name,
54
+ implementingClass: strategy.implementingClass,
55
+ strategy,
56
+ ...kind ? { kind } : {}
57
+ };
58
+ }
59
+ /**
60
+ * Plan the pipeline a course's strategy documents assemble into.
61
+ *
62
+ * Mirrors the assembly rules: generators keep document order, with ELO and SRS
63
+ * added when absent; an ELO distance filter is added when absent; filters run
64
+ * sorted by name; unknown implementing classes are skipped with a warning. With no documents at all, describes the default
65
+ * pipeline that `createDefaultPipeline` builds instead.
66
+ */
67
+ function planPipeline(strategies, courseId) {
68
+ if (strategies.length === 0) return {
69
+ kind: "default",
70
+ generators: [planned(createDefaultEloStrategy(courseId), NavigatorRole.GENERATOR, "default-pipeline"), planned(createDefaultSrsStrategy(courseId), NavigatorRole.GENERATOR, "default-pipeline")],
71
+ filters: [planned(createDefaultEloDistanceStrategy(courseId), NavigatorRole.FILTER, "default-pipeline")],
72
+ skipped: [],
73
+ warnings: [],
74
+ notes: [],
75
+ regulators: DEFAULT_REGULATOR_CONFIG
76
+ };
77
+ const generators = [];
78
+ const filters = [];
79
+ const skipped = [];
80
+ const warnings = [];
81
+ for (const s of strategies) if (isGenerator(s.implementingClass)) generators.push(planned(s, NavigatorRole.GENERATOR, "strategy-doc"));
82
+ else if (isFilter(s.implementingClass)) filters.push(planned(s, NavigatorRole.FILTER, "strategy-doc"));
83
+ else {
84
+ skipped.push({
85
+ strategy: s,
86
+ reason: "not a registered generator or filter"
87
+ });
88
+ warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
89
+ }
90
+ const declared = new Set(generators.map((g) => g.implementingClass));
91
+ if (!declared.has(createDefaultEloStrategy(courseId).implementingClass)) generators.push(planned(createDefaultEloStrategy(courseId), NavigatorRole.GENERATOR, "assembler-default"));
92
+ if (!declared.has(createDefaultSrsStrategy(courseId).implementingClass)) generators.push(planned(createDefaultSrsStrategy(courseId), NavigatorRole.GENERATOR, "assembler-default"));
93
+ const eloDistance = createDefaultEloDistanceStrategy(courseId);
94
+ if (!filters.some((f) => f.implementingClass === eloDistance.implementingClass)) filters.push(planned(eloDistance, NavigatorRole.FILTER, "assembler-default"));
95
+ filters.sort((a, b) => a.name.localeCompare(b.name));
96
+ return {
97
+ kind: "assembled",
98
+ generators,
99
+ filters,
100
+ skipped,
101
+ warnings,
102
+ notes: [],
103
+ regulators: DEFAULT_REGULATOR_CONFIG
104
+ };
105
+ }
106
+ //#endregion
107
+ export { PIPELINE_STAGES, planPipeline };
108
+
109
+ //# sourceMappingURL=pipelinePlan.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pipelinePlan.mjs","names":[],"sources":["../../../src/core/navigators/pipelinePlan.ts"],"sourcesContent":["import type { ContentNavigationStrategyData } from '../types/contentNavigationStrategy';\nimport { getRegisteredFilterKind, isFilter, isGenerator, NavigatorRole } from './index';\nimport type { FilterKind } from './filters/types';\nimport { DEFAULT_REGULATOR_CONFIG, type RegulatorConfig } from './regulators';\nimport {\n createDefaultEloDistanceStrategy,\n createDefaultEloStrategy,\n createDefaultSrsStrategy,\n} from './defaults';\n\n// ============================================================================\n// PIPELINE PLAN\n// ============================================================================\n//\n// What a course's strategy documents assemble into, as data: which generators\n// and filters run, in what order, and which ones the assembler added itself.\n// Pure: no user, no instantiation. PipelineAssembler builds from this plan and\n// the admin pipeline view renders it, so the view can't drift from what runs.\n//\n// Roles come from the navigator registry, so a plan reflects the app it's\n// computed in. A course's consumer-registered filters plan as `skipped` in an\n// app that never registered them, which is also how they'd assemble there.\n//\n// Not exported from './index' (the navigators barrel): './defaults' imports the\n// generator classes, which extend ContentNavigator from that barrel.\n//\n// ============================================================================\n\nexport type PlannedNavigatorOrigin =\n /** From the course's strategy documents. */\n | 'strategy-doc'\n /** Added by the assembler because the course declared none of its kind. */\n | 'assembler-default'\n /** Part of the fallback pipeline for a course with no strategy documents. */\n | 'default-pipeline';\n\nexport interface PlannedNavigator {\n role: NavigatorRole;\n origin: PlannedNavigatorOrigin;\n /** The name runs report this navigator under (generator summaries, filter impacts). */\n name: string;\n implementingClass: string;\n /** The strategy document: the course's own, or the default the assembler supplies. */\n strategy: ContentNavigationStrategyData;\n /**\n * Filters only: the kind its class declares (`static kind`), read from the\n * navigator registry. Undefined if undeclared, which runs as a gate.\n */\n kind?: FilterKind;\n}\n\nexport interface SkippedStrategy {\n strategy: ContentNavigationStrategyData;\n reason: string;\n}\n\nexport interface PipelinePlan {\n /** Assembled from strategy documents, or the fallback for a course with none. */\n kind: 'assembled' | 'default';\n generators: PlannedNavigator[];\n /** In run order. */\n filters: PlannedNavigator[];\n skipped: SkippedStrategy[];\n warnings: string[];\n /** Consequences of the plan worth knowing that aren't errors. */\n notes: string[];\n /** The regulator stage's settings (see regulators.ts). */\n regulators: RegulatorConfig;\n}\n\nexport type PipelineStageKey =\n | 'generate'\n | 'filter'\n | 'drop-zero'\n | 'regulate'\n | 'hints'\n | 'diversity'\n | 'select';\n\n/** One step of a pipeline run, in order. Shared by views and text exports. */\nexport interface PipelineStageInfo {\n key: PipelineStageKey;\n title: string;\n summary: string;\n}\n\n/**\n * The steps every pipeline run takes, in order (`Pipeline.getWeightedCards`).\n * `generate` and `filter` are where a plan's navigators run; the rest are\n * fixed framework behaviour.\n */\nexport const PIPELINE_STAGES: readonly PipelineStageInfo[] = [\n {\n key: 'generate',\n title: 'Generate',\n summary:\n 'Each generator proposes candidates (up to 500 in all), scored on what is specific to its ' +\n 'source. A card proposed by several generators keeps their mean score, raised 10% per extra ' +\n 'generator.',\n },\n {\n key: 'filter',\n title: 'Filter',\n summary:\n 'Each filter multiplies candidate scores, in the order shown. A gate says a card is not ready ' +\n 'yet; a signal expresses preference. Gates usually penalize rather than remove, so a gated ' +\n 'card stays in the pool at a low score.',\n },\n {\n key: 'drop-zero',\n title: 'Drop zero scores',\n summary: 'Candidates whose score reached 0 leave the pool.',\n },\n {\n key: 'regulate',\n title: 'Regulate',\n summary:\n 'Balances reviews against new cards. Review mass: the due reviews weighed by their filtered ' +\n 'scores; above a healthy level, every review is lifted. Intake: hours since a new card was ' +\n 'last presented; new cards no gate penalized are lifted, and the clock stops while there are ' +\n 'none.',\n },\n {\n key: 'hints',\n title: 'Apply hints',\n summary:\n \"The session's hints (from the app: an intro's follow-up, a difficulty boost) exclude, \" +\n 'boost, or require cards. Required cards skip the filters entirely.',\n },\n {\n key: 'diversity',\n title: 'Diversity re-rank',\n summary:\n 'Demotes candidates that repeat a distinctive tag already ranked above them, so one ' +\n 'concept or answer cannot take the whole head of the queue. Sees this run only, not what ' +\n 'the session already served.',\n },\n {\n key: 'select',\n title: 'Select',\n summary:\n \"Highest scores first, up to the run's limit. The session mixes them into its supply queue.\",\n },\n];\n\nfunction planned(\n strategy: ContentNavigationStrategyData,\n role: NavigatorRole,\n origin: PlannedNavigatorOrigin\n): PlannedNavigator {\n const kind =\n role === NavigatorRole.FILTER ? getRegisteredFilterKind(strategy.implementingClass) : undefined;\n return {\n role,\n origin,\n name: strategy.name,\n implementingClass: strategy.implementingClass,\n strategy,\n ...(kind ? { kind } : {}),\n };\n}\n\n/**\n * Plan the pipeline a course's strategy documents assemble into.\n *\n * Mirrors the assembly rules: generators keep document order, with ELO and SRS\n * added when absent; an ELO distance filter is added when absent; filters run\n * sorted by name; unknown implementing classes are skipped with a warning. With no documents at all, describes the default\n * pipeline that `createDefaultPipeline` builds instead.\n */\nexport function planPipeline(\n strategies: ContentNavigationStrategyData[],\n courseId: string\n): PipelinePlan {\n if (strategies.length === 0) {\n return {\n kind: 'default',\n generators: [\n planned(createDefaultEloStrategy(courseId), NavigatorRole.GENERATOR, 'default-pipeline'),\n planned(createDefaultSrsStrategy(courseId), NavigatorRole.GENERATOR, 'default-pipeline'),\n ],\n filters: [\n planned(\n createDefaultEloDistanceStrategy(courseId),\n NavigatorRole.FILTER,\n 'default-pipeline'\n ),\n ],\n skipped: [],\n warnings: [],\n notes: [],\n regulators: DEFAULT_REGULATOR_CONFIG,\n };\n }\n\n const generators: PlannedNavigator[] = [];\n const filters: PlannedNavigator[] = [];\n const skipped: SkippedStrategy[] = [];\n const warnings: string[] = [];\n\n for (const s of strategies) {\n if (isGenerator(s.implementingClass)) {\n generators.push(planned(s, NavigatorRole.GENERATOR, 'strategy-doc'));\n } else if (isFilter(s.implementingClass)) {\n filters.push(planned(s, NavigatorRole.FILTER, 'strategy-doc'));\n } else {\n skipped.push({ strategy: s, reason: 'not a registered generator or filter' });\n warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);\n }\n }\n\n // ELO and SRS are always present; custom generators supplement, never replace them.\n const declared = new Set(generators.map((g) => g.implementingClass));\n if (!declared.has(createDefaultEloStrategy(courseId).implementingClass)) {\n generators.push(\n planned(createDefaultEloStrategy(courseId), NavigatorRole.GENERATOR, 'assembler-default')\n );\n }\n if (!declared.has(createDefaultSrsStrategy(courseId).implementingClass)) {\n generators.push(\n planned(createDefaultSrsStrategy(courseId), NavigatorRole.GENERATOR, 'assembler-default')\n );\n }\n\n // ELO distance is the one place distance counts, for reviews and new cards alike\n // (the ELO generator only retrieves near the learner's ELO). A course tunes it\n // by declaring its own.\n const eloDistance = createDefaultEloDistanceStrategy(courseId);\n if (!filters.some((f) => f.implementingClass === eloDistance.implementingClass)) {\n filters.push(planned(eloDistance, NavigatorRole.FILTER, 'assembler-default'));\n }\n\n // Sorted by name for deterministic ordering.\n filters.sort((a, b) => a.name.localeCompare(b.name));\n\n return {\n kind: 'assembled',\n generators,\n filters,\n skipped,\n warnings,\n notes: [],\n regulators: DEFAULT_REGULATOR_CONFIG,\n };\n}\n"],"mappings":";;;;;;;;;;AA2FA,MAAa,kBAAgD;CAC3D;EACE,KAAK;EACL,OAAO;EACP,SACE;EAGH;CACD;EACE,KAAK;EACL,OAAO;EACP,SACE;EAGH;CACD;EACE,KAAK;EACL,OAAO;EACP,SAAS;EACV;CACD;EACE,KAAK;EACL,OAAO;EACP,SACE;EAIH;CACD;EACE,KAAK;EACL,OAAO;EACP,SACE;EAEH;CACD;EACE,KAAK;EACL,OAAO;EACP,SACE;EAGH;CACD;EACE,KAAK;EACL,OAAO;EACP,SACE;EACH;CACF;AAED,SAAS,QACP,UACA,MACA,QACkB;CAClB,MAAM,OACJ,SAAS,cAAc,SAAS,wBAAwB,SAAS,kBAAkB,GAAG,KAAA;AACxF,QAAO;EACL;EACA;EACA,MAAM,SAAS;EACf,mBAAmB,SAAS;EAC5B;EACA,GAAI,OAAO,EAAE,MAAM,GAAG,EAAE;EACzB;;;;;;;;;;AAWH,SAAgB,aACd,YACA,UACc;AACd,KAAI,WAAW,WAAW,EACxB,QAAO;EACL,MAAM;EACN,YAAY,CACV,QAAQ,yBAAyB,SAAS,EAAE,cAAc,WAAW,mBAAmB,EACxF,QAAQ,yBAAyB,SAAS,EAAE,cAAc,WAAW,mBAAmB,CACzF;EACD,SAAS,CACP,QACE,iCAAiC,SAAS,EAC1C,cAAc,QACd,mBACD,CACF;EACD,SAAS,EAAE;EACX,UAAU,EAAE;EACZ,OAAO,EAAE;EACT,YAAY;EACb;CAGH,MAAM,aAAiC,EAAE;CACzC,MAAM,UAA8B,EAAE;CACtC,MAAM,UAA6B,EAAE;CACrC,MAAM,WAAqB,EAAE;AAE7B,MAAK,MAAM,KAAK,WACd,KAAI,YAAY,EAAE,kBAAkB,CAClC,YAAW,KAAK,QAAQ,GAAG,cAAc,WAAW,eAAe,CAAC;UAC3D,SAAS,EAAE,kBAAkB,CACtC,SAAQ,KAAK,QAAQ,GAAG,cAAc,QAAQ,eAAe,CAAC;MACzD;AACL,UAAQ,KAAK;GAAE,UAAU;GAAG,QAAQ;GAAwC,CAAC;AAC7E,WAAS,KAAK,0BAA0B,EAAE,kBAAkB,eAAe,EAAE,OAAO;;CAKxF,MAAM,WAAW,IAAI,IAAI,WAAW,KAAK,MAAM,EAAE,kBAAkB,CAAC;AACpE,KAAI,CAAC,SAAS,IAAI,yBAAyB,SAAS,CAAC,kBAAkB,CACrE,YAAW,KACT,QAAQ,yBAAyB,SAAS,EAAE,cAAc,WAAW,oBAAoB,CAC1F;AAEH,KAAI,CAAC,SAAS,IAAI,yBAAyB,SAAS,CAAC,kBAAkB,CACrE,YAAW,KACT,QAAQ,yBAAyB,SAAS,EAAE,cAAc,WAAW,oBAAoB,CAC1F;CAMH,MAAM,cAAc,iCAAiC,SAAS;AAC9D,KAAI,CAAC,QAAQ,MAAM,MAAM,EAAE,sBAAsB,YAAY,kBAAkB,CAC7E,SAAQ,KAAK,QAAQ,aAAa,cAAc,QAAQ,oBAAoB,CAAC;AAI/E,SAAQ,MAAM,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,KAAK,CAAC;AAEpD,QAAO;EACL,MAAM;EACN;EACA;EACA;EACA;EACA,OAAO,EAAE;EACT,YAAY;EACb"}