@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.
- package/CLAUDE.md +15 -4
- package/build.entries.mjs +12 -0
- package/dist/_virtual/_rolldown/runtime.mjs +8 -0
- package/dist/{contentSource-BteiDpxH.d.ts → contentSource-D_E7JaxR.d.ts} +1 -1
- package/dist/core/UserDBDebugger.mjs +285 -0
- package/dist/core/UserDBDebugger.mjs.map +1 -0
- package/dist/core/bulkImport/cardProcessor.mjs +106 -0
- package/dist/core/bulkImport/cardProcessor.mjs.map +1 -0
- package/dist/core/{index.js → index.cjs} +6438 -7784
- package/dist/core/index.cjs.map +1 -0
- package/dist/core/index.d.ts +5 -5
- package/dist/core/index.mjs +20 -11368
- package/dist/core/interfaces/contentSource.mjs +20 -0
- package/dist/core/interfaces/contentSource.mjs.map +1 -0
- package/dist/core/navigators/Pipeline.mjs +723 -0
- package/dist/core/navigators/Pipeline.mjs.map +1 -0
- package/dist/core/navigators/PipelineAssembler.mjs +86 -0
- package/dist/core/navigators/PipelineAssembler.mjs.map +1 -0
- package/dist/core/navigators/PipelineDebugger.mjs +771 -0
- package/dist/core/navigators/PipelineDebugger.mjs.map +1 -0
- package/dist/core/navigators/SrsDebugger.mjs +34 -0
- package/dist/core/navigators/SrsDebugger.mjs.map +1 -0
- package/dist/core/navigators/StrategyPressureDebugger.mjs +19 -0
- package/dist/core/navigators/StrategyPressureDebugger.mjs.map +1 -0
- package/dist/core/navigators/defaults.mjs +96 -0
- package/dist/core/navigators/defaults.mjs.map +1 -0
- package/dist/core/navigators/diversityRerank.mjs +85 -0
- package/dist/core/navigators/diversityRerank.mjs.map +1 -0
- package/dist/core/navigators/filters/WeightedFilter.mjs +81 -0
- package/dist/core/navigators/filters/WeightedFilter.mjs.map +1 -0
- package/dist/core/navigators/filters/eloDistance.mjs +244 -0
- package/dist/core/navigators/filters/eloDistance.mjs.map +1 -0
- package/dist/core/navigators/filters/hierarchyDefinition.mjs +235 -0
- package/dist/core/navigators/filters/hierarchyDefinition.mjs.map +1 -0
- package/dist/core/navigators/filters/interferenceMitigator.mjs +201 -0
- package/dist/core/navigators/filters/interferenceMitigator.mjs.map +1 -0
- package/dist/core/navigators/filters/relativePriority.mjs +135 -0
- package/dist/core/navigators/filters/relativePriority.mjs.map +1 -0
- package/dist/core/navigators/filters/userTagPreference.mjs +101 -0
- package/dist/core/navigators/filters/userTagPreference.mjs.map +1 -0
- package/dist/core/navigators/generators/CompositeGenerator.mjs +203 -0
- package/dist/core/navigators/generators/CompositeGenerator.mjs.map +1 -0
- package/dist/core/navigators/generators/elo.mjs +77 -0
- package/dist/core/navigators/generators/elo.mjs.map +1 -0
- package/dist/core/navigators/generators/prescribed.mjs +676 -0
- package/dist/core/navigators/generators/prescribed.mjs.map +1 -0
- package/dist/core/navigators/generators/srs.mjs +158 -0
- package/dist/core/navigators/generators/srs.mjs.map +1 -0
- package/dist/core/navigators/index.mjs +345 -0
- package/dist/core/navigators/index.mjs.map +1 -0
- package/dist/core/navigators/pipelinePlan.mjs +109 -0
- package/dist/core/navigators/pipelinePlan.mjs.map +1 -0
- package/dist/core/navigators/regulators.mjs +128 -0
- package/dist/core/navigators/regulators.mjs.map +1 -0
- package/dist/core/orchestration/gradient.mjs +101 -0
- package/dist/core/orchestration/gradient.mjs.map +1 -0
- package/dist/core/orchestration/index.mjs +115 -0
- package/dist/core/orchestration/index.mjs.map +1 -0
- package/dist/core/orchestration/learning.mjs +140 -0
- package/dist/core/orchestration/learning.mjs.map +1 -0
- package/dist/core/orchestration/recording.mjs +64 -0
- package/dist/core/orchestration/recording.mjs.map +1 -0
- package/dist/core/orchestration/signal.mjs +40 -0
- package/dist/core/orchestration/signal.mjs.map +1 -0
- package/dist/core/types/contentNavigationStrategy.mjs +10 -0
- package/dist/core/types/contentNavigationStrategy.mjs.map +1 -0
- package/dist/core/types/hydration.mjs +13 -0
- package/dist/core/types/hydration.mjs.map +1 -0
- package/dist/core/types/strategyState.mjs +16 -0
- package/dist/core/types/strategyState.mjs.map +1 -0
- package/dist/core/types/studySession.mjs +14 -0
- package/dist/core/types/studySession.mjs.map +1 -0
- package/dist/core/types/types-legacy.mjs +44 -0
- package/dist/core/types/types-legacy.mjs.map +1 -0
- package/dist/core/util/index.mjs +31 -0
- package/dist/core/util/index.mjs.map +1 -0
- package/dist/core/versionStamps.mjs +46 -0
- package/dist/core/versionStamps.mjs.map +1 -0
- package/dist/courseConfigRegistration.mjs +306 -0
- package/dist/courseConfigRegistration.mjs.map +1 -0
- package/dist/{dataLayerProvider-C_QWzHf-.d.ts → dataLayerProvider-BDshhSp_.d.ts} +1 -1
- package/dist/diagnostics/dataset.mjs +118 -0
- package/dist/diagnostics/dataset.mjs.map +1 -0
- package/dist/diagnostics/derive.mjs +318 -0
- package/dist/diagnostics/derive.mjs.map +1 -0
- package/dist/diagnostics/{index.js → index.cjs} +1 -1
- package/dist/diagnostics/index.d.ts +3 -3
- package/dist/diagnostics/index.mjs +7 -1042
- package/dist/diagnostics/loader.mjs +151 -0
- package/dist/diagnostics/loader.mjs.map +1 -0
- package/dist/diagnostics/pipeline.mjs +161 -0
- package/dist/diagnostics/pipeline.mjs.map +1 -0
- package/dist/diagnostics/tagElo.mjs +177 -0
- package/dist/diagnostics/tagElo.mjs.map +1 -0
- package/dist/diagnostics/text.mjs +174 -0
- package/dist/diagnostics/text.mjs.map +1 -0
- package/dist/factory.mjs +70 -0
- package/dist/factory.mjs.map +1 -0
- package/dist/impl/common/BaseUserDB.mjs +1103 -0
- package/dist/impl/common/BaseUserDB.mjs.map +1 -0
- package/dist/impl/common/userDBHelpers.mjs +49 -0
- package/dist/impl/common/userDBHelpers.mjs.map +1 -0
- package/dist/impl/common/userDBKeys.mjs +45 -0
- package/dist/impl/common/userDBKeys.mjs.map +1 -0
- package/dist/impl/couch/CouchDBSyncStrategy.mjs +272 -0
- package/dist/impl/couch/CouchDBSyncStrategy.mjs.map +1 -0
- package/dist/impl/couch/CourseSyncService.mjs +242 -0
- package/dist/impl/couch/CourseSyncService.mjs.map +1 -0
- package/dist/impl/couch/PouchDataLayerProvider.mjs +74 -0
- package/dist/impl/couch/PouchDataLayerProvider.mjs.map +1 -0
- package/dist/impl/couch/adminDB.mjs +61 -0
- package/dist/impl/couch/adminDB.mjs.map +1 -0
- package/dist/impl/couch/auth.mjs +33 -0
- package/dist/impl/couch/auth.mjs.map +1 -0
- package/dist/impl/couch/classroomDB.mjs +227 -0
- package/dist/impl/couch/classroomDB.mjs.map +1 -0
- package/dist/impl/couch/clientCache.mjs +15 -0
- package/dist/impl/couch/clientCache.mjs.map +1 -0
- package/dist/impl/couch/courseAPI.mjs +183 -0
- package/dist/impl/couch/courseAPI.mjs.map +1 -0
- package/dist/impl/couch/courseDB.mjs +729 -0
- package/dist/impl/couch/courseDB.mjs.map +1 -0
- package/dist/impl/couch/courseLookupDB.mjs +94 -0
- package/dist/impl/couch/courseLookupDB.mjs.map +1 -0
- package/dist/impl/couch/{index.js → index.cjs} +6911 -10367
- package/dist/impl/couch/index.cjs.map +1 -0
- package/dist/impl/couch/index.d.ts +12 -5
- package/dist/impl/couch/index.mjs +134 -12146
- package/dist/impl/couch/index.mjs.map +1 -1
- package/dist/impl/couch/pouchdb-setup.mjs +15 -0
- package/dist/impl/couch/pouchdb-setup.mjs.map +1 -0
- package/dist/impl/couch/updateQueue.mjs +101 -0
- package/dist/impl/couch/updateQueue.mjs.map +1 -0
- package/dist/impl/couch/user-course-relDB.mjs +55 -0
- package/dist/impl/couch/user-course-relDB.mjs.map +1 -0
- package/dist/impl/static/NoOpSyncStrategy.mjs +49 -0
- package/dist/impl/static/NoOpSyncStrategy.mjs.map +1 -0
- package/dist/impl/static/StaticDataLayerProvider.mjs +94 -0
- package/dist/impl/static/StaticDataLayerProvider.mjs.map +1 -0
- package/dist/impl/static/StaticDataUnpacker.mjs +311 -0
- package/dist/impl/static/StaticDataUnpacker.mjs.map +1 -0
- package/dist/impl/static/courseDB.mjs +368 -0
- package/dist/impl/static/courseDB.mjs.map +1 -0
- package/dist/impl/static/coursesDB.mjs +38 -0
- package/dist/impl/static/coursesDB.mjs.map +1 -0
- package/dist/impl/static/{index.js → index.cjs} +2461 -5992
- package/dist/impl/static/index.cjs.map +1 -0
- package/dist/impl/static/index.d.ts +4 -4
- package/dist/impl/static/index.mjs +6 -10741
- package/dist/{index-C745YB_6.d.ts → index-BLDpFYG3.d.ts} +1 -1
- package/dist/{index.js → index.cjs} +14070 -14239
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +12 -23
- package/dist/index.mjs +38 -16937
- package/dist/pouch/{index.js → index.cjs} +5 -1
- package/dist/pouch/index.cjs.map +1 -0
- package/dist/pouch/index.mjs +2 -19
- package/dist/study/ItemQueue.mjs +95 -0
- package/dist/study/ItemQueue.mjs.map +1 -0
- package/dist/study/MixerDebugger.mjs +303 -0
- package/dist/study/MixerDebugger.mjs.map +1 -0
- package/dist/study/SessionController.mjs +1187 -0
- package/dist/study/SessionController.mjs.map +1 -0
- package/dist/study/SessionDebugger.mjs +271 -0
- package/dist/study/SessionDebugger.mjs.map +1 -0
- package/dist/study/SessionOverlay.mjs +407 -0
- package/dist/study/SessionOverlay.mjs.map +1 -0
- package/dist/study/SourceMixer.mjs +45 -0
- package/dist/study/SourceMixer.mjs.map +1 -0
- package/dist/study/SpacedRepetition.mjs +108 -0
- package/dist/study/SpacedRepetition.mjs.map +1 -0
- package/dist/study/TagFilteredContentSource.mjs +136 -0
- package/dist/study/TagFilteredContentSource.mjs.map +1 -0
- package/dist/study/services/CardHydrationService.mjs +172 -0
- package/dist/study/services/CardHydrationService.mjs.map +1 -0
- package/dist/study/services/EloService.mjs +217 -0
- package/dist/study/services/EloService.mjs.map +1 -0
- package/dist/study/services/ResponseProcessor.mjs +190 -0
- package/dist/study/services/ResponseProcessor.mjs.map +1 -0
- package/dist/study/services/SrsService.mjs +49 -0
- package/dist/study/services/SrsService.mjs.map +1 -0
- package/dist/study/services/tagRecent.mjs +65 -0
- package/dist/study/services/tagRecent.mjs.map +1 -0
- package/dist/{types-DF0JuPbs.d.ts → types-DChCz22D.d.ts} +1 -1
- package/dist/{types-legacy-DdVjg81H.d.cts → types-legacy-fT5Y1Wuy.d.ts} +1 -1
- package/dist/userDBKeys-ne1g4Xuq.d.ts +16 -0
- package/dist/util/Loggable.mjs +14 -0
- package/dist/util/Loggable.mjs.map +1 -0
- package/dist/util/dataDirectory.mjs +47 -0
- package/dist/util/dataDirectory.mjs.map +1 -0
- package/dist/util/logger.mjs +86 -0
- package/dist/util/logger.mjs.map +1 -0
- package/dist/util/migrator/FileSystemAdapter.mjs +18 -0
- package/dist/util/migrator/FileSystemAdapter.mjs.map +1 -0
- package/dist/util/migrator/StaticToCouchDBMigrator.mjs +428 -0
- package/dist/util/migrator/StaticToCouchDBMigrator.mjs.map +1 -0
- package/dist/util/migrator/types.mjs +11 -0
- package/dist/util/migrator/types.mjs.map +1 -0
- package/dist/util/migrator/validation.mjs +334 -0
- package/dist/util/migrator/validation.mjs.map +1 -0
- package/dist/util/packer/CouchDBToStaticPacker.mjs +438 -0
- package/dist/util/packer/CouchDBToStaticPacker.mjs.map +1 -0
- package/dist/util/packer/{index.js → index.cjs} +73 -9
- package/dist/util/packer/index.cjs.map +1 -0
- package/dist/util/packer/index.d.ts +3 -3
- package/dist/util/packer/index.mjs +2 -537
- package/eslint.config.mjs +9 -1
- package/package.json +25 -13
- package/rolldown.config.mjs +44 -0
- package/src/core/UserDBDebugger.ts +47 -46
- package/src/core/navigators/Pipeline.ts +10 -10
- package/src/core/navigators/PipelineDebugger.ts +55 -55
- package/src/core/navigators/filters/eloDistance.ts +1 -1
- package/src/core/navigators/generators/elo.ts +5 -1
- package/src/core/navigators/index.ts +9 -3
- package/src/factory.ts +10 -1
- package/src/impl/common/BaseUserDB.ts +1 -3
- package/src/impl/common/index.ts +2 -0
- package/src/impl/common/userDBHelpers.ts +4 -58
- package/src/impl/common/userDBKeys.ts +64 -0
- package/src/impl/couch/courseDB.ts +15 -3
- package/src/impl/couch/index.ts +2 -18
- package/src/impl/couch/pouchdb-setup.ts +8 -0
- package/src/index.ts +1 -1
- package/src/study/MixerDebugger.ts +46 -46
- package/src/study/SessionDebugger.ts +20 -20
- package/src/study/SessionOverlay.ts +4 -4
- package/src/util/logger.ts +112 -13
- package/tests/core/navigators/eloGenerator.test.ts +36 -0
- package/tsup.config.ts +24 -21
- package/dist/SyncStrategy-BXliog1m.d.cts +0 -116
- package/dist/classroomDB-DLTtLZct.d.cts +0 -86
- package/dist/contentSource-FQZcZopC.d.cts +0 -2007
- package/dist/core/index.d.cts +0 -521
- package/dist/core/index.js.map +0 -1
- package/dist/core/index.mjs.map +0 -1
- package/dist/dataLayerProvider-3y21KtF-.d.cts +0 -61
- package/dist/diagnostics/index.d.cts +0 -561
- package/dist/diagnostics/index.mjs.map +0 -1
- package/dist/impl/couch/index.d.cts +0 -620
- package/dist/impl/couch/index.js.map +0 -1
- package/dist/impl/static/index.d.cts +0 -232
- package/dist/impl/static/index.js.map +0 -1
- package/dist/impl/static/index.mjs.map +0 -1
- package/dist/index-BIum9Ue2.d.cts +0 -137
- package/dist/index.d.cts +0 -1663
- package/dist/index.js.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/pouch/index.d.cts +0 -1
- package/dist/pouch/index.js.map +0 -1
- package/dist/pouch/index.mjs.map +0 -1
- package/dist/types-BcWVH4ww.d.cts +0 -58
- package/dist/types-legacy-DdVjg81H.d.ts +0 -168
- package/dist/util/packer/index.d.cts +0 -5
- package/dist/util/packer/index.js.map +0 -1
- package/dist/util/packer/index.mjs.map +0 -1
- package/src/study/getCardDataShape.ts +0 -34
- /package/dist/diagnostics/{index.js.map → index.cjs.map} +0 -0
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import "../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
//#region src/core/orchestration/signal.ts
|
|
3
|
+
/**
|
|
4
|
+
* Computes a scalar signal (0-1) representing the quality of the learning outcome.
|
|
5
|
+
*
|
|
6
|
+
* Current implementation focuses on "accuracy within Zone of Proximal Development".
|
|
7
|
+
* Future versions should include ELO gain rate.
|
|
8
|
+
*
|
|
9
|
+
* @param records - List of question attempts in the period
|
|
10
|
+
* @param config - Configuration for the signal function
|
|
11
|
+
* @returns Score 0.0-1.0, or null if insufficient data
|
|
12
|
+
*/
|
|
13
|
+
function computeOutcomeSignal(records, config = {}) {
|
|
14
|
+
if (!records || records.length === 0) return null;
|
|
15
|
+
const target = config.targetAccuracy ?? .85;
|
|
16
|
+
const tolerance = config.tolerance ?? .05;
|
|
17
|
+
let correct = 0;
|
|
18
|
+
for (const r of records) if (r.isCorrect) correct++;
|
|
19
|
+
return scoreAccuracyInZone(correct / records.length, target, tolerance);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Scores an accuracy value based on how close it is to the target "sweet spot".
|
|
23
|
+
*
|
|
24
|
+
* The function defines a plateau of width (2 * tolerance) around the target
|
|
25
|
+
* where score is 1.0. Outside this plateau, it falls off linearly.
|
|
26
|
+
*
|
|
27
|
+
* @param accuracy - Observed accuracy (0-1)
|
|
28
|
+
* @param target - Target accuracy (e.g. 0.85)
|
|
29
|
+
* @param tolerance - +/- range allowed for max score
|
|
30
|
+
*/
|
|
31
|
+
function scoreAccuracyInZone(accuracy, target, tolerance) {
|
|
32
|
+
const dist = Math.abs(accuracy - target);
|
|
33
|
+
if (dist <= tolerance) return 1;
|
|
34
|
+
const excess = dist - tolerance;
|
|
35
|
+
return Math.max(0, 1 - excess * 2.5);
|
|
36
|
+
}
|
|
37
|
+
//#endregion
|
|
38
|
+
export { computeOutcomeSignal, scoreAccuracyInZone };
|
|
39
|
+
|
|
40
|
+
//# sourceMappingURL=signal.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"signal.mjs","names":[],"sources":["../../../src/core/orchestration/signal.ts"],"sourcesContent":["import { QuestionRecord } from '../types/types-legacy';\n\nexport interface SignalConfig {\n /** Target accuracy for \"in the zone\" learning (default: 0.85) */\n targetAccuracy?: number;\n /** Width of the peak plateau (default: 0.05) */\n tolerance?: number;\n}\n\n/**\n * Computes a scalar signal (0-1) representing the quality of the learning outcome.\n *\n * Current implementation focuses on \"accuracy within Zone of Proximal Development\".\n * Future versions should include ELO gain rate.\n *\n * @param records - List of question attempts in the period\n * @param config - Configuration for the signal function\n * @returns Score 0.0-1.0, or null if insufficient data\n */\nexport function computeOutcomeSignal(\n records: QuestionRecord[],\n config: SignalConfig = {}\n): number | null {\n if (!records || records.length === 0) {\n return null;\n }\n\n const target = config.targetAccuracy ?? 0.85;\n const tolerance = config.tolerance ?? 0.05;\n\n let correct = 0;\n for (const r of records) {\n // Cast to any to avoid type error if Evaluation interface is not correctly propagated\n \n if ((r as any).isCorrect) correct++;\n }\n\n const accuracy = correct / records.length;\n\n return scoreAccuracyInZone(accuracy, target, tolerance);\n}\n\n/**\n * Scores an accuracy value based on how close it is to the target \"sweet spot\".\n *\n * The function defines a plateau of width (2 * tolerance) around the target\n * where score is 1.0. Outside this plateau, it falls off linearly.\n *\n * @param accuracy - Observed accuracy (0-1)\n * @param target - Target accuracy (e.g. 0.85)\n * @param tolerance - +/- range allowed for max score\n */\nexport function scoreAccuracyInZone(accuracy: number, target: number, tolerance: number): number {\n const dist = Math.abs(accuracy - target);\n\n // Inside the sweet spot\n if (dist <= tolerance) {\n return 1.0;\n }\n\n // Outside, fall off.\n // We apply a linear penalty for deviation from the tolerance edge.\n const excess = dist - tolerance;\n const slope = 2.5; // Falloff rate (0.4 deviation = 0 score)\n\n return Math.max(0, 1.0 - excess * slope);\n}"],"mappings":";;;;;;;;;;;;AAmBA,SAAgB,qBACd,SACA,SAAuB,EAAE,EACV;AACf,KAAI,CAAC,WAAW,QAAQ,WAAW,EACjC,QAAO;CAGT,MAAM,SAAS,OAAO,kBAAkB;CACxC,MAAM,YAAY,OAAO,aAAa;CAEtC,IAAI,UAAU;AACd,MAAK,MAAM,KAAK,QAGd,KAAK,EAAU,UAAW;AAK5B,QAAO,oBAFU,UAAU,QAAQ,QAEE,QAAQ,UAAU;;;;;;;;;;;;AAazD,SAAgB,oBAAoB,UAAkB,QAAgB,WAA2B;CAC/F,MAAM,OAAO,KAAK,IAAI,WAAW,OAAO;AAGxC,KAAI,QAAQ,UACV,QAAO;CAKT,MAAM,SAAS,OAAO;AAGtB,QAAO,KAAK,IAAI,GAAG,IAAM,SAFX,IAE0B"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"contentNavigationStrategy.mjs","names":[],"sources":["../../../src/core/types/contentNavigationStrategy.ts"],"sourcesContent":["import { DocType, SkuilderCourseData } from './types-legacy';\nimport type { DocTypePrefixes } from './types-legacy';\n\n/**\n * Configuration for an evolutionarily-weighted strategy.\n *\n * This structure tracks the \"learned\" weight of a strategy, representing the\n * system's confidence in its utility.\n *\n * - weight: The best-known multiplier (peak of the bell curve)\n * - confidence: How certain we are (inverse of variance / spread)\n * - sampleSize: How many data points informed this weight\n */\nexport interface LearnableWeight {\n /** The current best estimate of optimal weight (multiplier) */\n weight: number;\n /** Confidence in this weight (0-1). Higher = narrower exploration spread. */\n confidence: number;\n /** Number of outcome observations that contributed to this weight */\n sampleSize: number;\n}\n\nexport const DEFAULT_LEARNABLE_WEIGHT: LearnableWeight = {\n weight: 1.0,\n confidence: 0.1, // Low confidence initially = wide exploration\n sampleSize: 0,\n};\n\n/**\n *\n */\nexport interface ContentNavigationStrategyData extends SkuilderCourseData {\n _id: `${typeof DocTypePrefixes[DocType.NAVIGATION_STRATEGY]}-${string}`;\n docType: DocType.NAVIGATION_STRATEGY;\n name: string;\n description: string;\n /**\n The name of the class that implements the navigation strategy at runtime.\n */\n implementingClass: string;\n\n /**\n A representation of the strategy's parameterization - to be deserialized\n by the implementing class's constructor at runtime.\n */\n serializedData: string;\n\n /**\n * Evolutionary weighting configuration.\n * If present, the strategy's influence is scaled by this weight.\n * If omitted, weight defaults to 1.0.\n */\n learnable?: LearnableWeight;\n\n /**\n * If true, the weight is applied exactly as configured, without\n * per-user deviation. Used for manual tuning or A/B testing.\n */\n staticWeight?: boolean;\n}\n"],"mappings":";AAsBA,MAAa,2BAA4C;CACvD,QAAQ;CACR,YAAY;CACZ,YAAY;CACb"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
//#region src/core/types/hydration.ts
|
|
2
|
+
/**
|
|
3
|
+
* ID of the per-device marker recording that a full pull once completed.
|
|
4
|
+
*
|
|
5
|
+
* `_local/*` documents are deliberately excluded from replication by CouchDB
|
|
6
|
+
* and PouchDB alike, which is exactly the semantics wanted here: the marker
|
|
7
|
+
* describes THIS device's mirror, and must never travel to another one.
|
|
8
|
+
*/
|
|
9
|
+
const HYDRATION_MARKER_ID = "_local/hydration";
|
|
10
|
+
//#endregion
|
|
11
|
+
export { HYDRATION_MARKER_ID };
|
|
12
|
+
|
|
13
|
+
//# sourceMappingURL=hydration.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hydration.mjs","names":[],"sources":["../../../src/core/types/hydration.ts"],"sourcesContent":["/**\n * User database hydration.\n *\n * A logged-in user's data lives in a remote CouchDB `userdb-<hex>` and is\n * mirrored into a browser-local PouchDB. On a device that has never synced\n * that account, the local mirror starts EMPTY — and every local read\n * (`getStrategyState`, `getConfig`, `getCourseRegistrationsDoc`, ...) answers\n * \"no such document\", which is indistinguishable from \"brand new user\".\n *\n * Consumers acting on that answer render a new-user experience to an existing\n * user, and — worse — compute writes from empty state that then lose to the\n * real remote document at replication time. Hydration closes that window by\n * pulling the account's documents down BEFORE the user object is handed out.\n */\n\n/**\n * Where a user's local database stands relative to its remote counterpart.\n *\n * Only `failed` is a blocking condition. `stale` explicitly is not: it means a\n * full pull completed on this device previously, so local data is real and\n * merely possibly-behind — live sync closes the gap in the background. That is\n * the ordinary offline case and it must keep working.\n */\nexport type UserHydrationState =\n /** Guest, or a data layer with no remote. There is nothing to hydrate from. */\n | 'not-required'\n /** Initial pull in flight. */\n | 'hydrating'\n /** Initial pull completed this session. Local is a faithful mirror. */\n | 'hydrated'\n /**\n * A previous session completed a full pull on this device (recorded by the\n * `_local/hydration` marker). Local data is real; live sync is catching up.\n */\n | 'stale'\n /**\n * No pull has ever completed on this device and one could not be completed\n * now. Local reads CANNOT be trusted to mean \"no data\" — callers must not\n * present a new-user experience or compute writes from what they read.\n */\n | 'failed';\n\n/**\n * Hydration state plus observability detail.\n *\n * Shaped to mirror `CourseSyncStatus` in CourseSyncService, which solves the\n * same problem for course databases.\n */\nexport interface UserHydrationStatus {\n state: UserHydrationState;\n /** Documents pulled by the initial replication (set when state is `hydrated`). */\n docsWritten?: number;\n /** Wall-clock duration of the initial pull attempt, successful or not. */\n durationMs?: number;\n /** Failure detail, set when state is `failed`. */\n error?: string;\n}\n\n/**\n * ID of the per-device marker recording that a full pull once completed.\n *\n * `_local/*` documents are deliberately excluded from replication by CouchDB\n * and PouchDB alike, which is exactly the semantics wanted here: the marker\n * describes THIS device's mirror, and must never travel to another one.\n */\nexport const HYDRATION_MARKER_ID = '_local/hydration';\n\n/**\n * Payload of {@link HYDRATION_MARKER_ID}.\n */\nexport interface HydrationMarker {\n _id: typeof HYDRATION_MARKER_ID;\n _rev?: string;\n /** Account the mirror was hydrated for — guards against a stale marker after an account switch. */\n username: string;\n /** ISO timestamp of the most recent successful full pull. */\n hydratedAt: string;\n}\n"],"mappings":";;;;;;;;AAiEA,MAAa,sBAAsB"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import "../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
//#region src/core/types/strategyState.ts
|
|
3
|
+
/**
|
|
4
|
+
* Build the document ID for a strategy state document.
|
|
5
|
+
*
|
|
6
|
+
* @param courseId - The course ID
|
|
7
|
+
* @param strategyKey - The strategy key (typically class name)
|
|
8
|
+
* @returns The document ID in format `STRATEGY_STATE::{courseId}::{strategyKey}`
|
|
9
|
+
*/
|
|
10
|
+
function buildStrategyStateId(courseId, strategyKey) {
|
|
11
|
+
return `STRATEGY_STATE::${courseId}::${strategyKey}`;
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
export { buildStrategyStateId };
|
|
15
|
+
|
|
16
|
+
//# sourceMappingURL=strategyState.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"strategyState.mjs","names":[],"sources":["../../../src/core/types/strategyState.ts"],"sourcesContent":["import { DocType, DocTypePrefixes } from './types-legacy';\n\n/**\n * Template literal type for strategy state document IDs.\n *\n * Format: `STRATEGY_STATE-{courseId}-{strategyKey}`\n */\nexport type StrategyStateId =\n `${(typeof DocTypePrefixes)[DocType.STRATEGY_STATE]}::${string}::${string}`;\n\n/**\n * Document storing strategy-specific state in the user database.\n *\n * Each strategy can persist its own state (user preferences, learned patterns,\n * temporal tracking, etc.) using this document type. The state is scoped to\n * a (user, course, strategy) tuple.\n *\n * ## Use Cases\n *\n * 1. **Explicit user preferences**: User configures tag filters, difficulty\n * preferences, or learning goals. UI writes to strategy state.\n *\n * 2. **Learned/temporal state**: Strategy tracks patterns over time, e.g.,\n * \"when did I last introduce confusable concepts together?\"\n *\n * 3. **Adaptive personalization**: Strategy infers user preferences from\n * behavior and stores them for future sessions.\n *\n * ## Storage Location\n *\n * These documents live in the **user database**, not the course database.\n * They sync with the user's data across devices.\n *\n * ## Document ID Format\n *\n * `STRATEGY_STATE::{courseId}::{strategyKey}`\n *\n * Example: `STRATEGY_STATE::piano-basics::UserTagPreferenceFilter`\n *\n * @template T - The shape of the strategy-specific data payload\n */\nexport interface StrategyStateDoc<T = unknown> {\n _id: StrategyStateId;\n _rev?: string;\n docType: DocType.STRATEGY_STATE;\n\n /**\n * The course this state applies to.\n */\n courseId: string;\n\n /**\n * Unique key identifying the strategy instance.\n * Typically the strategy class name (e.g., \"UserTagPreferenceFilter\",\n * \"InterferenceMitigatorNavigator\").\n *\n * If a course has multiple instances of the same strategy type with\n * different configurations, use a more specific key.\n */\n strategyKey: string;\n\n /**\n * Strategy-specific data payload.\n * Each strategy defines its own schema for this field.\n */\n data: T;\n\n /**\n * ISO timestamp of last update.\n * Use `moment.utc(updatedAt)` to parse into a Moment object.\n */\n updatedAt: string;\n}\n\n/**\n * Build the document ID for a strategy state document.\n *\n * @param courseId - The course ID\n * @param strategyKey - The strategy key (typically class name)\n * @returns The document ID in format `STRATEGY_STATE::{courseId}::{strategyKey}`\n */\nexport function buildStrategyStateId(courseId: string, strategyKey: string): StrategyStateId {\n return `STRATEGY_STATE::${courseId}::${strategyKey}`;\n}\n"],"mappings":";;;;;;;;;AAiFA,SAAgB,qBAAqB,UAAkB,aAAsC;AAC3F,QAAO,mBAAmB,SAAS,IAAI"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import "../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
import { DocType, DocTypePrefixes } from "./types-legacy.mjs";
|
|
3
|
+
//#region src/core/types/studySession.ts
|
|
4
|
+
/** Stable across the open and close writes, unlike a timestamp-keyed id. */
|
|
5
|
+
function makeStudySessionId(courseId, userId, sessionId) {
|
|
6
|
+
return `${DocTypePrefixes[DocType.STUDY_SESSION]}::${courseId}::${userId}::${sessionId}`;
|
|
7
|
+
}
|
|
8
|
+
function newSessionId() {
|
|
9
|
+
return `session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
10
|
+
}
|
|
11
|
+
//#endregion
|
|
12
|
+
export { makeStudySessionId, newSessionId };
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=studySession.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"studySession.mjs","names":[],"sources":["../../../src/core/types/studySession.ts"],"sourcesContent":["import { DocType, DocTypePrefixes } from './types-legacy';\nimport type { ReplanHints } from '../navigators/generators/types';\nimport type { GeneratorSummary, FilterImpact, RunVersions } from '../navigators/PipelineDebugger';\nimport type { RegulatorReading } from '../navigators/regulators';\nimport type { StrategyContribution } from '../navigators';\n\n/**\n * Durable per-sitting record. Join target for `CardRecord.sessionId`.\n *\n * Written twice: `open` at `prepareSession()`, overwritten at termination.\n */\nexport interface StudySessionDoc {\n /** `SESSION::{courseId}::{userId}::{sessionId}` */\n _id: string;\n _rev?: string;\n docType: DocType.STUDY_SESSION;\n\n sessionId: string;\n courseId: string;\n userId: string;\n\n /** Session construction time, not first-card time. */\n startTime: string;\n endTime?: string;\n\n /**\n * `closed` — ran to natural termination.\n * `abandoned` — host tore the study view down mid-session.\n * `open` — never closed: tab closed, reload, crash. No tally or end state.\n */\n status: 'open' | 'closed' | 'abandoned';\n\n plannedSeconds: number;\n\n config: {\n defaultBatchLimit: number;\n sourceCount: number;\n initHints?: ReplanHints | null;\n };\n\n /**\n * The code this session ran on: the framework's version (`'dev'` when run\n * from source) and the host app's, if it reported one (`appVersion` in the\n * data-layer config). Strategy and content versions are stamped per run.\n * Absent on sessions recorded before this shipped.\n */\n versions?: { framework: string; app?: string };\n\n /** Queue depths after the bootstrap run, before the first draw. */\n initialQueues: { supplyQ: number; failedQ: number };\n\n tally?: {\n /** Distinct cards; a re-presented failed card counts once. */\n cardsPresented: number;\n /** Total responses, including repeat attempts on one card. */\n responses: number;\n correct: number;\n incorrect: number;\n failedQRemaining: number;\n secondsRemaining: number;\n };\n\n /** Bootstrap run plus every replan, in execution order. */\n runs?: StudySessionRunSummary[];\n\n /**\n * Per-response ELO exchanges, in the order they resolved. One entry per\n * ELO-updating response (first attempt of a presentation; retries don't\n * move ELO). Flushed at close from an in-memory log — so `open`/`abandoned`\n * sessions that never reached the close write carry none, and a same-card\n * event still in flight at close may be missing. Absent on sessions\n * recorded before this shipped.\n */\n eloEvents?: SessionEloEvent[];\n\n finalHints?: ReplanHints | null;\n\n stateAtStart?: SessionStateSnapshot;\n stateAtEnd?: SessionStateSnapshot;\n}\n\nexport interface StudySessionRunSummary {\n /** Joins to `PipelineRunReport.runId` while that run is still in memory. */\n runId: string;\n at: string;\n /** `'bootstrap'`, a replan's label, or `'(auto)'`. */\n label: string;\n mode?: string;\n generatedCount: number;\n finalCount: number;\n reviewsSelected: number;\n newSelected: number;\n\n // --- Detail projected from PipelineRunReport at record time ------------\n // These make a run self-explanatory after the in-memory ring buffer that\n // holds the full `PipelineRunReport` has rolled over (MAX_RUNS=10) — which\n // is almost always, by the time anyone reads a persisted session. The\n // multi-KB per-card provenance trail is deliberately NOT persisted; only\n // the compact phase summaries are. All optional: absent on runs recorded\n // before this shipped, and on any run whose report lacked the field.\n\n /** User's global ELO at the moment this run's pipeline executed. */\n userElo?: number;\n /** Per-generator contribution (name, card/new/review counts, top score). */\n generators?: GeneratorSummary[];\n /** Per-filter impact (boosted / penalized / passed / removed). */\n filters?: FilterImpact[];\n /** Ephemeral replan hints in force for this run (what the navigator was told). */\n hints?: ReplanHints;\n /** Compact summary of the scored-but-dropped candidate tail. */\n discardedTail?: {\n count: number;\n scoreRange?: [number, number];\n eloRange?: [number, number];\n note: string;\n };\n /**\n * The selected cards, then the top few unselected ones, each in score\n * order. The lowest selected score against the first runner-up is this\n * run's cutoff.\n */\n cards?: StudySessionRunCard[];\n /**\n * The unselected non-review cards most worth explaining, with their\n * score-changing provenance. See `PipelineRunReport.unselectedNew`.\n */\n unselectedNew?: {\n nextInLine?: StudySessionRunCardTrail;\n topGenerated?: StudySessionRunCardTrail;\n };\n /** The regulator stage's readings: review mass and intake, each with its multiplier (0.2.29+). */\n regulators?: RegulatorReading[];\n /** What the run ran on: the strategy docs' hash and the course's content version. */\n versions?: RunVersions;\n}\n\n/** A card as persisted on a run. `origin` is as counted in `newSelected`/`reviewsSelected`. */\nexport interface StudySessionRunCard {\n cardId: string;\n /**\n * `'review'`: a scheduled review. `'new'`: anything else. `'unknown'` only on\n * older runs, which counted prescribed and hint-required cards as neither.\n */\n origin: 'new' | 'review' | 'unknown';\n /**\n * The strategy that produced the card. Absent if a hint injected it (older\n * runs name the hint here instead).\n */\n generator?: string;\n /** The hint that made the card mandatory, if one did. Its source, over `generator`. */\n required?: string;\n /** Final score; null for a mandatory (required) card, whose score is infinite. */\n score: number | null;\n selected: boolean;\n}\n\n/**\n * A card plus the provenance entries that changed its score, in order.\n * `'passed'` entries are dropped. Strategy ids are dropped (the name is kept).\n */\nexport interface StudySessionRunCardTrail extends StudySessionRunCard {\n trail: Array<{\n strategyName: string;\n action: StrategyContribution['action'];\n score: number;\n reason: string;\n }>;\n}\n\n/**\n * One learner↔card ELO exchange, captured at the moment it resolved so a\n * session can be read as an ELO ledger (why did 88% accuracy net -1?). The\n * exchange is otherwise write-once-and-discard: only the updated aggregates\n * survive on the user/card docs, and ELO is path-dependent, so a response's\n * move can't be reconstructed after the fact. Joins to a `CardRecord` by\n * `cardId` + nearest `at`.\n */\nexport interface SessionEloEvent {\n /** Card this exchange was for. */\n cardId: string;\n /** ISO time the exchange resolved (fires just after the response record). */\n at: string;\n /**\n * Global performance in [0,1] that drove the update. Note this is the ELO\n * `userScore`, not raw correctness: the numeric path maps a correct answer\n * to `0.5 + performance/2` (so a plain correct is 1.0, a graded-correct\n * less) and a miss to 0; the tagged path uses `_global`.\n */\n userScore: number;\n /** Learner global ELO before → after this response. */\n global: { before: number; after: number };\n /** Card global ELO before → after (absent if the card ELO was unreadable). */\n card?: { before: number; after: number };\n /**\n * Per-tag learner ELO before → after, for every tag the exchange touched.\n * `score` is the per-tag performance applied, or null for a count-only\n * exposure tag (`gpc:expose:*`) that increments count without moving ELO.\n */\n tags?: Record<string, { before: number; after: number; score: number | null }>;\n}\n\n/**\n * Host-defined learner state at a session boundary. Keep it thin — this is\n * written on every session, and the deltas between consecutive snapshots are\n * what it's read for.\n */\nexport type SessionStateSnapshot = Record<string, unknown>;\n\n/**\n * Invoked at session open and close. Errors and slow calls are absorbed by\n * the controller.\n */\nexport type SessionStateSnapshotProvider = (\n phase: 'start' | 'end'\n) => SessionStateSnapshot | Promise<SessionStateSnapshot>;\n\n/** Stable across the open and close writes, unlike a timestamp-keyed id. */\nexport function makeStudySessionId(\n courseId: string,\n userId: string,\n sessionId: string\n): string {\n return `${DocTypePrefixes[DocType.STUDY_SESSION]}::${courseId}::${userId}::${sessionId}`;\n}\n\nexport function newSessionId(): string {\n return `session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n}\n"],"mappings":";;;;AAyNA,SAAgB,mBACd,UACA,QACA,WACQ;AACR,QAAO,GAAG,gBAAgB,QAAQ,eAAe,IAAI,SAAS,IAAI,OAAO,IAAI;;AAG/E,SAAgB,eAAuB;AACrC,QAAO,WAAW,KAAK,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,GAAG,EAAE"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import "../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
import { logger } from "../../util/logger.mjs";
|
|
3
|
+
//#region src/core/types/types-legacy.ts
|
|
4
|
+
const GuestUsername = "sk-guest-";
|
|
5
|
+
const log = (message) => {
|
|
6
|
+
logger.log(message);
|
|
7
|
+
};
|
|
8
|
+
let DocType = /* @__PURE__ */ function(DocType) {
|
|
9
|
+
DocType["DISPLAYABLE_DATA"] = "DISPLAYABLE_DATA";
|
|
10
|
+
DocType["CARD"] = "CARD";
|
|
11
|
+
DocType["DATASHAPE"] = "DATASHAPE";
|
|
12
|
+
DocType["QUESTIONTYPE"] = "QUESTION";
|
|
13
|
+
DocType["VIEW"] = "VIEW";
|
|
14
|
+
DocType["PEDAGOGY"] = "PEDAGOGY";
|
|
15
|
+
DocType["CARDRECORD"] = "CARDRECORD";
|
|
16
|
+
DocType["SCHEDULED_CARD"] = "SCHEDULED_CARD";
|
|
17
|
+
DocType["TAG"] = "TAG";
|
|
18
|
+
DocType["NAVIGATION_STRATEGY"] = "NAVIGATION_STRATEGY";
|
|
19
|
+
DocType["STRATEGY_STATE"] = "STRATEGY_STATE";
|
|
20
|
+
DocType["USER_OUTCOME"] = "USER_OUTCOME";
|
|
21
|
+
DocType["STRATEGY_LEARNING_STATE"] = "STRATEGY_LEARNING_STATE";
|
|
22
|
+
DocType["STUDY_SESSION"] = "STUDY_SESSION";
|
|
23
|
+
return DocType;
|
|
24
|
+
}({});
|
|
25
|
+
const DocTypePrefixes = {
|
|
26
|
+
[DocType.CARD]: "c",
|
|
27
|
+
[DocType.DISPLAYABLE_DATA]: "dd",
|
|
28
|
+
[DocType.TAG]: "TAG",
|
|
29
|
+
[DocType.CARDRECORD]: "cardH",
|
|
30
|
+
[DocType.SCHEDULED_CARD]: "card_review_",
|
|
31
|
+
[DocType.DATASHAPE]: "DATASHAPE",
|
|
32
|
+
[DocType.QUESTIONTYPE]: "QUESTION",
|
|
33
|
+
[DocType.VIEW]: "VIEW",
|
|
34
|
+
[DocType.PEDAGOGY]: "PEDAGOGY",
|
|
35
|
+
[DocType.NAVIGATION_STRATEGY]: "NAVIGATION_STRATEGY",
|
|
36
|
+
[DocType.STRATEGY_STATE]: "STRATEGY_STATE",
|
|
37
|
+
[DocType.USER_OUTCOME]: "USER_OUTCOME",
|
|
38
|
+
[DocType.STRATEGY_LEARNING_STATE]: "STRATEGY_LEARNING_STATE",
|
|
39
|
+
[DocType.STUDY_SESSION]: "SESSION"
|
|
40
|
+
};
|
|
41
|
+
//#endregion
|
|
42
|
+
export { DocType, DocTypePrefixes, GuestUsername, log };
|
|
43
|
+
|
|
44
|
+
//# sourceMappingURL=types-legacy.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-legacy.mjs","names":[],"sources":["../../../src/core/types/types-legacy.ts"],"sourcesContent":["import { CourseElo, Answer, Evaluation } from '@vue-skuilder/common';\nimport { Moment } from 'moment';\nimport { logger } from '../../util/logger';\n\nexport const GuestUsername: string = 'sk-guest-';\n\nexport const log = (message: string): void => {\n logger.log(message);\n};\n\nexport enum DocType {\n DISPLAYABLE_DATA = 'DISPLAYABLE_DATA',\n CARD = 'CARD',\n DATASHAPE = 'DATASHAPE',\n QUESTIONTYPE = 'QUESTION',\n VIEW = 'VIEW',\n PEDAGOGY = 'PEDAGOGY',\n CARDRECORD = 'CARDRECORD',\n SCHEDULED_CARD = 'SCHEDULED_CARD',\n TAG = 'TAG',\n NAVIGATION_STRATEGY = 'NAVIGATION_STRATEGY',\n STRATEGY_STATE = 'STRATEGY_STATE',\n USER_OUTCOME = 'USER_OUTCOME',\n STRATEGY_LEARNING_STATE = 'STRATEGY_LEARNING_STATE',\n STUDY_SESSION = 'STUDY_SESSION',\n}\n\nexport interface QualifiedCardID {\n courseID: string;\n cardID: string;\n}\n\n/**\n * Interface for all data on course content and pedagogy stored\n * in the c/pouch database.\n */\nexport interface SkuilderCourseData {\n course: string;\n docType: DocType;\n}\n\nexport interface Tag extends SkuilderCourseData {\n docType: DocType.TAG;\n name: string;\n snippet: string; // 200 char description of the tag\n wiki: string; // 3000 char md-friendly description\n taggedCards: PouchDB.Core.DocumentId[];\n author: string;\n}\nexport interface TagStub {\n name: string;\n snippet: string;\n count: number; // the number of cards that have this tag applied\n}\n\nexport interface CardData extends SkuilderCourseData {\n docType: DocType.CARD;\n id_displayable_data: PouchDB.Core.DocumentId[];\n id_view: PouchDB.Core.DocumentId;\n elo: CourseElo;\n author: string;\n}\n\n/** A list of populated courses in the DB */\nexport interface CourseListData extends PouchDB.Core.Response {\n courses: string[];\n}\n\n/**\n * The data used to hydrate viewable components (questions, info, etc)\n */\nexport interface DisplayableData extends SkuilderCourseData {\n docType: DocType.DISPLAYABLE_DATA;\n author?: string;\n id_datashape: PouchDB.Core.DocumentId;\n data: Field[];\n _attachments?: { [index: string]: PouchDB.Core.FullAttachment };\n}\n\nexport interface Field {\n data: unknown;\n name: string;\n}\n\nexport interface DataShapeData extends SkuilderCourseData {\n docType: DocType.DATASHAPE;\n _id: PouchDB.Core.DocumentId;\n questionTypes: PouchDB.Core.DocumentId[];\n}\n\nexport interface QuestionData extends SkuilderCourseData {\n docType: DocType.QUESTIONTYPE;\n _id: PouchDB.Core.DocumentId;\n viewList: string[];\n dataShapeList: PouchDB.Core.DocumentId[];\n}\n\nexport const DocTypePrefixes = {\n [DocType.CARD]: 'c',\n [DocType.DISPLAYABLE_DATA]: 'dd',\n [DocType.TAG]: 'TAG',\n [DocType.CARDRECORD]: 'cardH',\n [DocType.SCHEDULED_CARD]: 'card_review_',\n // Add other doctypes here as they get prefixed IDs\n [DocType.DATASHAPE]: 'DATASHAPE',\n [DocType.QUESTIONTYPE]: 'QUESTION',\n [DocType.VIEW]: 'VIEW',\n [DocType.PEDAGOGY]: 'PEDAGOGY',\n [DocType.NAVIGATION_STRATEGY]: 'NAVIGATION_STRATEGY',\n [DocType.STRATEGY_STATE]: 'STRATEGY_STATE',\n [DocType.USER_OUTCOME]: 'USER_OUTCOME',\n [DocType.STRATEGY_LEARNING_STATE]: 'STRATEGY_LEARNING_STATE',\n [DocType.STUDY_SESSION]: 'SESSION',\n} as const;\n\nexport interface CardHistory<T extends CardRecord> {\n _id: PouchDB.Core.DocumentId;\n /**\n * The CouchDB id of the card\n */\n cardID: PouchDB.Core.DocumentId;\n\n /**\n * The ID of the course\n */\n courseID: string;\n\n /**\n * The to-date largest interval between successful\n * card reviews. `0` indicates no successful reviews.\n */\n bestInterval: number;\n\n /**\n * The number of times that a card has been\n * failed in review\n */\n lapses: number;\n\n /**\n * The number of consecutive successful impressions\n * on this card\n */\n streak: number;\n\n records: T[];\n}\n\nexport interface CardRecord {\n /**\n * The CouchDB id of the card\n */\n cardID: string;\n /**\n * The ID of the course\n */\n courseID: string;\n /**\n * Number of milliseconds that the user spent before dismissing\n * the card (ie, \"I've read this\" or \"here is my answer\")\n *\n * //TODO: this (sometimes?) wants to be replaced with a rich\n * recording of user activity in working the question\n */\n timeSpent: number;\n /**\n * The date-time that the card was rendered. timeStamp + timeSpent will give the\n * time of user submission.\n */\n timeStamp: Moment;\n /**\n * The study session this response was produced in. Absent on records\n * predating session stamping, and on responses made outside a\n * SessionController.\n */\n sessionId?: string;\n}\n\nexport interface QuestionRecord extends CardRecord, Evaluation {\n userAnswer: Answer;\n /**\n * The number of incorrect user submissions prededing this submisstion.\n *\n * eg, if a user is asked 7*6=__, submitting 46, 48, 42 will result in three\n * records being created having 0, 1, and 2 as their recorded 'priorAttempts' values\n */\n priorAttemps: number;\n}\n"],"mappings":";;;AAIA,MAAa,gBAAwB;AAErC,MAAa,OAAO,YAA0B;AAC5C,QAAO,IAAI,QAAQ;;AAGrB,IAAY,UAAL,yBAAA,SAAA;AACL,SAAA,sBAAA;AACA,SAAA,UAAA;AACA,SAAA,eAAA;AACA,SAAA,kBAAA;AACA,SAAA,UAAA;AACA,SAAA,cAAA;AACA,SAAA,gBAAA;AACA,SAAA,oBAAA;AACA,SAAA,SAAA;AACA,SAAA,yBAAA;AACA,SAAA,oBAAA;AACA,SAAA,kBAAA;AACA,SAAA,6BAAA;AACA,SAAA,mBAAA;;KACD;AAwED,MAAa,kBAAkB;EAC5B,QAAQ,OAAO;EACf,QAAQ,mBAAmB;EAC3B,QAAQ,MAAM;EACd,QAAQ,aAAa;EACrB,QAAQ,iBAAiB;EAEzB,QAAQ,YAAY;EACpB,QAAQ,eAAe;EACvB,QAAQ,OAAO;EACf,QAAQ,WAAW;EACnB,QAAQ,sBAAsB;EAC9B,QAAQ,iBAAiB;EACzB,QAAQ,eAAe;EACvB,QAAQ,0BAA0B;EAClC,QAAQ,gBAAgB;CAC1B"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import "../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
import { DocType, DocTypePrefixes } from "../types/types-legacy.mjs";
|
|
3
|
+
//#region src/core/util/index.ts
|
|
4
|
+
function areQuestionRecords(h) {
|
|
5
|
+
return isQuestionRecord(h.records[0]);
|
|
6
|
+
}
|
|
7
|
+
function isQuestionRecord(c) {
|
|
8
|
+
return c.userAnswer !== void 0;
|
|
9
|
+
}
|
|
10
|
+
function getCardHistoryID(courseID, cardID) {
|
|
11
|
+
return `${DocTypePrefixes[DocType.CARDRECORD]}-${courseID}-${cardID}`;
|
|
12
|
+
}
|
|
13
|
+
function parseCardHistoryID(id) {
|
|
14
|
+
const split = id.split("-");
|
|
15
|
+
let error = "";
|
|
16
|
+
error += split.length === 3 ? "" : `\n\tgiven ID has incorrect number of '-' characters`;
|
|
17
|
+
error += split[0] === DocTypePrefixes[DocType.CARDRECORD] ? "" : `
|
|
18
|
+
given ID does not start with ${DocTypePrefixes[DocType.CARDRECORD]}`;
|
|
19
|
+
if (split.length === 3 && split[0] === DocTypePrefixes[DocType.CARDRECORD]) return {
|
|
20
|
+
courseID: split[1],
|
|
21
|
+
cardID: split[2]
|
|
22
|
+
};
|
|
23
|
+
else throw new Error("parseCardHistory Error:" + error);
|
|
24
|
+
}
|
|
25
|
+
function docIsDeleted(e) {
|
|
26
|
+
return Boolean(e?.error === "not_found" && e?.reason === "deleted");
|
|
27
|
+
}
|
|
28
|
+
//#endregion
|
|
29
|
+
export { areQuestionRecords, docIsDeleted, getCardHistoryID, isQuestionRecord, parseCardHistoryID };
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/core/util/index.ts"],"sourcesContent":["import { DocType, DocTypePrefixes, CardHistory, CardRecord, QuestionRecord } from '../types/types-legacy';\n\nexport function areQuestionRecords(h: CardHistory<CardRecord>): h is CardHistory<QuestionRecord> {\n return isQuestionRecord(h.records[0]);\n}\n\nexport function isQuestionRecord(c: CardRecord): c is QuestionRecord {\n return (c as QuestionRecord).userAnswer !== undefined;\n}\n\nexport function getCardHistoryID(courseID: string, cardID: string): PouchDB.Core.DocumentId {\n return `${DocTypePrefixes[DocType.CARDRECORD]}-${courseID}-${cardID}`;\n}\n\nexport function parseCardHistoryID(id: string): {\n courseID: string;\n cardID: string;\n} {\n const split = id.split('-');\n let error: string = '';\n error += split.length === 3 ? '' : `\\n\\tgiven ID has incorrect number of '-' characters`;\n error +=\n split[0] === DocTypePrefixes[DocType.CARDRECORD] ? '' : `\n\tgiven ID does not start with ${DocTypePrefixes[DocType.CARDRECORD]}`;\n\n if (split.length === 3 && split[0] === DocTypePrefixes[DocType.CARDRECORD]) {\n return {\n courseID: split[1],\n cardID: split[2],\n };\n } else {\n throw new Error('parseCardHistory Error:' + error);\n }\n}\n\ninterface PouchDBError extends Error {\n error?: string;\n reason?: string;\n}\n\nexport function docIsDeleted(e: PouchDBError): boolean {\n return Boolean(e?.error === 'not_found' && e?.reason === 'deleted');\n}\n"],"mappings":";;;AAEA,SAAgB,mBAAmB,GAA8D;AAC/F,QAAO,iBAAiB,EAAE,QAAQ,GAAG;;AAGvC,SAAgB,iBAAiB,GAAoC;AACnE,QAAQ,EAAqB,eAAe,KAAA;;AAG9C,SAAgB,iBAAiB,UAAkB,QAAyC;AAC1F,QAAO,GAAG,gBAAgB,QAAQ,YAAY,GAAG,SAAS,GAAG;;AAG/D,SAAgB,mBAAmB,IAGjC;CACA,MAAM,QAAQ,GAAG,MAAM,IAAI;CAC3B,IAAI,QAAgB;AACpB,UAAS,MAAM,WAAW,IAAI,KAAK;AACnC,UACE,MAAM,OAAO,gBAAgB,QAAQ,cAAc,KAAK;gCAC5B,gBAAgB,QAAQ;AAEtD,KAAI,MAAM,WAAW,KAAK,MAAM,OAAO,gBAAgB,QAAQ,YAC7D,QAAO;EACL,UAAU,MAAM;EAChB,QAAQ,MAAM;EACf;KAED,OAAM,IAAI,MAAM,4BAA4B,MAAM;;AAStD,SAAgB,aAAa,GAA0B;AACrD,QAAO,QAAQ,GAAG,UAAU,eAAe,GAAG,WAAW,UAAU"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import "../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
//#region src/core/versionStamps.ts
|
|
3
|
+
/** This build's @vue-skuilder/db version, set at build time; `'dev'` when run from source. */
|
|
4
|
+
const FRAMEWORK_VERSION = "0.2.36";
|
|
5
|
+
let hostAppVersion;
|
|
6
|
+
/** Record the host app's version (the data layer's `appVersion` option). */
|
|
7
|
+
function setAppVersion(version) {
|
|
8
|
+
hostAppVersion = version;
|
|
9
|
+
}
|
|
10
|
+
/** What a session stamps: the framework's version, and the app's if it reported one. */
|
|
11
|
+
function sessionVersions() {
|
|
12
|
+
return {
|
|
13
|
+
framework: FRAMEWORK_VERSION,
|
|
14
|
+
...hostAppVersion ? { app: hostAppVersion } : {}
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
/** Stamp for a pipeline built without strategy docs (the built-in default). */
|
|
18
|
+
const DEFAULT_STRATEGY_HASH = "default";
|
|
19
|
+
/** JSON with object keys sorted, so equal docs stringify equally. */
|
|
20
|
+
function stableStringify(value) {
|
|
21
|
+
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
|
|
22
|
+
if (value && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
|
|
23
|
+
return JSON.stringify(value);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* A short hash of a course's strategy docs: 8 hex chars, FNV-1a over their
|
|
27
|
+
* content (not `_rev`, which a redeploy of the same content also changes).
|
|
28
|
+
* Equal for equal strategy sets, whatever order they load in.
|
|
29
|
+
*/
|
|
30
|
+
function strategyHash(strategies) {
|
|
31
|
+
if (strategies.length === 0) return DEFAULT_STRATEGY_HASH;
|
|
32
|
+
const text = strategies.map((s) => {
|
|
33
|
+
const { _rev: _ignored, ...rest } = s;
|
|
34
|
+
return stableStringify(rest);
|
|
35
|
+
}).sort().join("\n");
|
|
36
|
+
let h = 2166136261;
|
|
37
|
+
for (let i = 0; i < text.length; i++) {
|
|
38
|
+
h ^= text.charCodeAt(i);
|
|
39
|
+
h = Math.imul(h, 16777619);
|
|
40
|
+
}
|
|
41
|
+
return (h >>> 0).toString(16).padStart(8, "0");
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
export { DEFAULT_STRATEGY_HASH, sessionVersions, setAppVersion, strategyHash };
|
|
45
|
+
|
|
46
|
+
//# sourceMappingURL=versionStamps.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"versionStamps.mjs","names":[],"sources":["../../src/core/versionStamps.ts"],"sourcesContent":["import type { ContentNavigationStrategyData } from './types/contentNavigationStrategy';\n\n// ============================================================================\n// VERSION STAMPS\n// ============================================================================\n//\n// What a study session ran on, written into its records so a change shows up\n// in them: framework and app releases on the session doc, the strategy docs\n// and the content version on each pipeline run (either can change mid-session).\n//\n// ============================================================================\n\ndeclare const __SKUILDER_DB_VERSION__: string | undefined;\n\n/** This build's @vue-skuilder/db version, set at build time; `'dev'` when run from source. */\nexport const FRAMEWORK_VERSION: string =\n typeof __SKUILDER_DB_VERSION__ === 'string' ? __SKUILDER_DB_VERSION__ : 'dev';\n\nlet hostAppVersion: string | undefined;\n\n/** Record the host app's version (the data layer's `appVersion` option). */\nexport function setAppVersion(version: string): void {\n hostAppVersion = version;\n}\n\n/** What a session stamps: the framework's version, and the app's if it reported one. */\nexport function sessionVersions(): { framework: string; app?: string } {\n return { framework: FRAMEWORK_VERSION, ...(hostAppVersion ? { app: hostAppVersion } : {}) };\n}\n\n/** Stamp for a pipeline built without strategy docs (the built-in default). */\nexport const DEFAULT_STRATEGY_HASH = 'default';\n\n/** JSON with object keys sorted, so equal docs stringify equally. */\nfunction stableStringify(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;\n if (value && typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(',')}}`;\n }\n return JSON.stringify(value);\n}\n\n/**\n * A short hash of a course's strategy docs: 8 hex chars, FNV-1a over their\n * content (not `_rev`, which a redeploy of the same content also changes).\n * Equal for equal strategy sets, whatever order they load in.\n */\nexport function strategyHash(strategies: readonly ContentNavigationStrategyData[]): string {\n if (strategies.length === 0) return DEFAULT_STRATEGY_HASH;\n const text = strategies\n .map((s) => {\n const { _rev: _ignored, ...rest } = s as ContentNavigationStrategyData & { _rev?: string };\n return stableStringify(rest);\n })\n .sort()\n .join('\\n');\n let h = 0x811c9dc5;\n for (let i = 0; i < text.length; i++) {\n h ^= text.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0).toString(16).padStart(8, '0');\n}\n"],"mappings":";;;AAeA,MAAa,oBAAA;AAGb,IAAI;;AAGJ,SAAgB,cAAc,SAAuB;AACnD,kBAAiB;;;AAInB,SAAgB,kBAAuD;AACrE,QAAO;EAAE,WAAW;EAAmB,GAAI,iBAAiB,EAAE,KAAK,gBAAgB,GAAG,EAAE;EAAG;;;AAI7F,MAAa,wBAAwB;;AAGrC,SAAS,gBAAgB,OAAwB;AAC/C,KAAI,MAAM,QAAQ,MAAM,CAAE,QAAO,IAAI,MAAM,IAAI,gBAAgB,CAAC,KAAK,IAAI,CAAC;AAC1E,KAAI,SAAS,OAAO,UAAU,SAI5B,QAAO,IAHS,OAAO,QAAQ,MAAiC,CAC7D,QAAQ,GAAG,OAAO,MAAM,KAAA,EAAU,CAClC,MAAM,CAAC,IAAI,CAAC,OAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,EAAG,CAChC,KAAK,CAAC,GAAG,OAAO,GAAG,KAAK,UAAU,EAAE,CAAC,GAAG,gBAAgB,EAAE,GAAG,CAAC,KAAK,IAAI,CAAC;AAE7F,QAAO,KAAK,UAAU,MAAM;;;;;;;AAQ9B,SAAgB,aAAa,YAA8D;AACzF,KAAI,WAAW,WAAW,EAAG,QAAO;CACpC,MAAM,OAAO,WACV,KAAK,MAAM;EACV,MAAM,EAAE,MAAM,UAAU,GAAG,SAAS;AACpC,SAAO,gBAAgB,KAAK;GAC5B,CACD,MAAM,CACN,KAAK,KAAK;CACb,IAAI,IAAI;AACR,MAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,OAAK,KAAK,WAAW,EAAE;AACvB,MAAI,KAAK,KAAK,GAAG,SAAW;;AAE9B,SAAQ,MAAM,GAAG,SAAS,GAAG,CAAC,SAAS,GAAG,IAAI"}
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
import "./_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
import { logger } from "./util/logger.mjs";
|
|
3
|
+
import { NameSpacer, toCourseElo, toZodJSON } from "@vue-skuilder/common";
|
|
4
|
+
//#region src/courseConfigRegistration.ts
|
|
5
|
+
/**
|
|
6
|
+
* Check if a data shape is already registered in the course config with valid schema
|
|
7
|
+
*/
|
|
8
|
+
function isDataShapeRegistered(dataShape, courseConfig) {
|
|
9
|
+
const namespacedName = NameSpacer.getDataShapeString({
|
|
10
|
+
dataShape: dataShape.name,
|
|
11
|
+
course: dataShape.course
|
|
12
|
+
});
|
|
13
|
+
return courseConfig.dataShapes.find((ds) => ds.name === namespacedName) !== void 0;
|
|
14
|
+
}
|
|
15
|
+
function isDataShapeSchemaAvailable(dataShape, courseConfig) {
|
|
16
|
+
const namespacedName = NameSpacer.getDataShapeString({
|
|
17
|
+
dataShape: dataShape.name,
|
|
18
|
+
course: dataShape.course
|
|
19
|
+
});
|
|
20
|
+
const existingDataShape = courseConfig.dataShapes.find((ds) => ds.name === namespacedName);
|
|
21
|
+
return existingDataShape !== void 0 && existingDataShape.serializedZodSchema !== void 0;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Check if a question type is already registered in the course config
|
|
25
|
+
*/
|
|
26
|
+
function isQuestionTypeRegistered(question, courseConfig) {
|
|
27
|
+
const namespacedName = NameSpacer.getQuestionString({
|
|
28
|
+
course: question.course,
|
|
29
|
+
questionType: question.name
|
|
30
|
+
});
|
|
31
|
+
return courseConfig.questionTypes.some((qt) => qt.name === namespacedName);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Process custom questions data into registration-ready format
|
|
35
|
+
*/
|
|
36
|
+
function processCustomQuestionsData(customQuestions) {
|
|
37
|
+
const processedDataShapes = [];
|
|
38
|
+
const processedQuestions = [];
|
|
39
|
+
const courseNames = customQuestions.courses.map((course) => course.name);
|
|
40
|
+
customQuestions.questionClasses.forEach((questionClass) => {
|
|
41
|
+
const courseName = courseNames.length > 0 ? courseNames[0] : customQuestions.meta.packageName;
|
|
42
|
+
if (questionClass.dataShapes && Array.isArray(questionClass.dataShapes)) questionClass.dataShapes.forEach((dataShape) => {
|
|
43
|
+
processedDataShapes.push({
|
|
44
|
+
name: dataShape.name,
|
|
45
|
+
course: courseName,
|
|
46
|
+
dataShape
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
processedQuestions.push({
|
|
50
|
+
name: questionClass.name,
|
|
51
|
+
course: courseName,
|
|
52
|
+
questionClass,
|
|
53
|
+
dataShapes: questionClass.dataShapes || [],
|
|
54
|
+
views: questionClass.views || []
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
return {
|
|
58
|
+
dataShapes: processedDataShapes,
|
|
59
|
+
questions: processedQuestions
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Register a data shape in the course config
|
|
64
|
+
*/
|
|
65
|
+
function registerDataShape(dataShape, courseConfig) {
|
|
66
|
+
const namespacedName = NameSpacer.getDataShapeString({
|
|
67
|
+
dataShape: dataShape.name,
|
|
68
|
+
course: dataShape.course
|
|
69
|
+
});
|
|
70
|
+
let serializedZodSchema;
|
|
71
|
+
try {
|
|
72
|
+
serializedZodSchema = toZodJSON(dataShape.dataShape);
|
|
73
|
+
} catch (error) {
|
|
74
|
+
logger.warn(`Failed to generate schema for ${namespacedName}:`, error);
|
|
75
|
+
serializedZodSchema = void 0;
|
|
76
|
+
}
|
|
77
|
+
const existingIndex = courseConfig.dataShapes.findIndex((ds) => ds.name === namespacedName);
|
|
78
|
+
if (existingIndex !== -1) {
|
|
79
|
+
const existingDataShape = courseConfig.dataShapes[existingIndex];
|
|
80
|
+
if (existingDataShape.serializedZodSchema === serializedZodSchema) {
|
|
81
|
+
logger.info(`DataShape '${dataShape.name}' from '${dataShape.course}' already registered with identical schema`);
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
if (existingDataShape.serializedZodSchema) logger.info(`DataShape '${dataShape.name}' from '${dataShape.course}' schema has changed, updating...`);
|
|
85
|
+
else logger.info(`DataShape '${dataShape.name}' from '${dataShape.course}' already registered, but with no schema. Adding schema to existing entry`);
|
|
86
|
+
courseConfig.dataShapes[existingIndex] = {
|
|
87
|
+
name: namespacedName,
|
|
88
|
+
questionTypes: existingDataShape.questionTypes,
|
|
89
|
+
serializedZodSchema
|
|
90
|
+
};
|
|
91
|
+
logger.info(`Updated DataShape: ${namespacedName}`);
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
courseConfig.dataShapes.push({
|
|
95
|
+
name: namespacedName,
|
|
96
|
+
questionTypes: [],
|
|
97
|
+
serializedZodSchema
|
|
98
|
+
});
|
|
99
|
+
logger.info(`Registered DataShape: ${namespacedName}`);
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Register a question type in the course config
|
|
104
|
+
*/
|
|
105
|
+
function registerQuestionType(question, courseConfig) {
|
|
106
|
+
if (isQuestionTypeRegistered(question, courseConfig)) {
|
|
107
|
+
logger.info(`QuestionType '${question.name}' from '${question.course}' already registered`);
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
const namespacedQuestionName = NameSpacer.getQuestionString({
|
|
111
|
+
course: question.course,
|
|
112
|
+
questionType: question.name
|
|
113
|
+
});
|
|
114
|
+
const viewList = question.views.map((view) => {
|
|
115
|
+
if (view.name) return view.name;
|
|
116
|
+
else return "unnamedComponent";
|
|
117
|
+
});
|
|
118
|
+
const dataShapeList = question.dataShapes.map((dataShape) => NameSpacer.getDataShapeString({
|
|
119
|
+
course: question.course,
|
|
120
|
+
dataShape: dataShape.name
|
|
121
|
+
}));
|
|
122
|
+
courseConfig.questionTypes.push({
|
|
123
|
+
name: namespacedQuestionName,
|
|
124
|
+
viewList,
|
|
125
|
+
dataShapeList
|
|
126
|
+
});
|
|
127
|
+
question.dataShapes.forEach((dataShape) => {
|
|
128
|
+
const namespacedDataShapeName = NameSpacer.getDataShapeString({
|
|
129
|
+
course: question.course,
|
|
130
|
+
dataShape: dataShape.name
|
|
131
|
+
});
|
|
132
|
+
for (const ds of courseConfig.dataShapes) if (ds.name === namespacedDataShapeName) ds.questionTypes.push(namespacedQuestionName);
|
|
133
|
+
});
|
|
134
|
+
logger.info(`Registered QuestionType: ${namespacedQuestionName}`);
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Remove a data shape from the course config
|
|
139
|
+
* @returns true if the data shape was removed, false if it wasn't found
|
|
140
|
+
*/
|
|
141
|
+
function removeDataShape(dataShapeName, courseConfig) {
|
|
142
|
+
const index = courseConfig.dataShapes.findIndex((ds) => ds.name === dataShapeName);
|
|
143
|
+
if (index === -1) {
|
|
144
|
+
logger.info(`DataShape '${dataShapeName}' not found in course config`);
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
courseConfig.dataShapes.splice(index, 1);
|
|
148
|
+
courseConfig.questionTypes.forEach((qt) => {
|
|
149
|
+
const dsIndex = qt.dataShapeList.indexOf(dataShapeName);
|
|
150
|
+
if (dsIndex !== -1) qt.dataShapeList.splice(dsIndex, 1);
|
|
151
|
+
});
|
|
152
|
+
logger.info(`Removed DataShape: ${dataShapeName}`);
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Remove a question type from the course config
|
|
157
|
+
* @returns true if the question type was removed, false if it wasn't found
|
|
158
|
+
*/
|
|
159
|
+
function removeQuestionType(questionTypeName, courseConfig) {
|
|
160
|
+
const index = courseConfig.questionTypes.findIndex((qt) => qt.name === questionTypeName);
|
|
161
|
+
if (index === -1) {
|
|
162
|
+
logger.info(`QuestionType '${questionTypeName}' not found in course config`);
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
courseConfig.questionTypes.splice(index, 1);
|
|
166
|
+
courseConfig.dataShapes.forEach((ds) => {
|
|
167
|
+
const qtIndex = ds.questionTypes.indexOf(questionTypeName);
|
|
168
|
+
if (qtIndex !== -1) ds.questionTypes.splice(qtIndex, 1);
|
|
169
|
+
});
|
|
170
|
+
logger.info(`Removed QuestionType: ${questionTypeName}`);
|
|
171
|
+
return true;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Remove data shapes and question types from course config and persist to database
|
|
175
|
+
*/
|
|
176
|
+
async function removeCustomQuestionTypes(dataShapeNames, questionTypeNames, courseConfig, courseDB) {
|
|
177
|
+
try {
|
|
178
|
+
logger.info("Beginning custom question removal");
|
|
179
|
+
logger.info(`Removing ${dataShapeNames.length} data shapes and ${questionTypeNames.length} question types`);
|
|
180
|
+
let removedCount = 0;
|
|
181
|
+
for (const qtName of questionTypeNames) if (removeQuestionType(qtName, courseConfig)) removedCount++;
|
|
182
|
+
for (const dsName of dataShapeNames) if (removeDataShape(dsName, courseConfig)) removedCount++;
|
|
183
|
+
logger.info("Updating course configuration...");
|
|
184
|
+
const updateResult = await courseDB.updateCourseConfig(courseConfig);
|
|
185
|
+
if (!updateResult.ok) throw new Error(`Failed to update course config: ${JSON.stringify(updateResult)}`);
|
|
186
|
+
logger.info(`Custom question removal complete: ${removedCount} items removed`);
|
|
187
|
+
return {
|
|
188
|
+
success: true,
|
|
189
|
+
removedCount
|
|
190
|
+
};
|
|
191
|
+
} catch (error) {
|
|
192
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
193
|
+
logger.error(`Custom question removal failed: ${errorMessage}`);
|
|
194
|
+
return {
|
|
195
|
+
success: false,
|
|
196
|
+
removedCount: 0,
|
|
197
|
+
errorMessage
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Register seed data for a question type
|
|
203
|
+
*
|
|
204
|
+
* @param question - The processed question data
|
|
205
|
+
* @param courseDB - The course database interface
|
|
206
|
+
* @param username - The username to attribute seed data to
|
|
207
|
+
*/
|
|
208
|
+
async function registerSeedData(question, courseDB, username) {
|
|
209
|
+
if (question.questionClass.seedData && Array.isArray(question.questionClass.seedData)) {
|
|
210
|
+
logger.info(`Registering seed data for question: ${question.name}`);
|
|
211
|
+
try {
|
|
212
|
+
if (question.dataShapes.length > 0) for (const seedDataItem of question.questionClass.seedData) {
|
|
213
|
+
const meta = question.questionClass.seedMeta?.(seedDataItem) ?? {};
|
|
214
|
+
await courseDB.addNote(question.course, question.dataShapes[0], seedDataItem, username, meta.tags ?? [], void 0, meta.elo !== void 0 ? toCourseElo(meta.elo) : void 0);
|
|
215
|
+
}
|
|
216
|
+
logger.info(`Seed data registered for question: ${question.name}`);
|
|
217
|
+
} catch (error) {
|
|
218
|
+
logger.warn(`Failed to register seed data for question '${question.name}': ${error instanceof Error ? error.message : String(error)}`);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Register BlanksCard (markdown fillIn) question type specifically
|
|
224
|
+
*/
|
|
225
|
+
async function registerBlanksCard(BlanksCard, BlanksCardDataShapes, courseConfig, courseDB, username) {
|
|
226
|
+
try {
|
|
227
|
+
logger.info("Registering BlanksCard data shapes and question type...");
|
|
228
|
+
let registeredCount = 0;
|
|
229
|
+
const courseName = "default";
|
|
230
|
+
for (const dataShapeClass of BlanksCardDataShapes) if (registerDataShape({
|
|
231
|
+
name: dataShapeClass.name,
|
|
232
|
+
course: courseName,
|
|
233
|
+
dataShape: dataShapeClass
|
|
234
|
+
}, courseConfig)) registeredCount++;
|
|
235
|
+
const processedQuestion = {
|
|
236
|
+
name: BlanksCard.name,
|
|
237
|
+
course: courseName,
|
|
238
|
+
questionClass: {
|
|
239
|
+
name: BlanksCard.name,
|
|
240
|
+
dataShapes: BlanksCardDataShapes,
|
|
241
|
+
views: BlanksCard.views || []
|
|
242
|
+
},
|
|
243
|
+
dataShapes: BlanksCardDataShapes,
|
|
244
|
+
views: BlanksCard.views || []
|
|
245
|
+
};
|
|
246
|
+
if (registerQuestionType(processedQuestion, courseConfig)) registeredCount++;
|
|
247
|
+
logger.info("Updating course configuration with BlanksCard...");
|
|
248
|
+
const updateResult = await courseDB.updateCourseConfig(courseConfig);
|
|
249
|
+
if (!updateResult.ok) throw new Error(`Failed to update course config: ${JSON.stringify(updateResult)}`);
|
|
250
|
+
if (username) await registerSeedData(processedQuestion, courseDB, username);
|
|
251
|
+
logger.info(`BlanksCard registration complete: ${registeredCount} items registered`);
|
|
252
|
+
return { success: true };
|
|
253
|
+
} catch (error) {
|
|
254
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
255
|
+
logger.error(`BlanksCard registration failed: ${errorMessage}`);
|
|
256
|
+
return {
|
|
257
|
+
success: false,
|
|
258
|
+
errorMessage
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Main function to register all custom question types and data shapes
|
|
264
|
+
*
|
|
265
|
+
* @param customQuestions - The custom questions data from allCustomQuestions()
|
|
266
|
+
* @param courseConfig - The course configuration object
|
|
267
|
+
* @param courseDB - The course database interface
|
|
268
|
+
* @param username - The username to attribute seed data to
|
|
269
|
+
*/
|
|
270
|
+
async function registerCustomQuestionTypes(customQuestions, courseConfig, courseDB, username) {
|
|
271
|
+
try {
|
|
272
|
+
logger.info("Beginning custom question registration");
|
|
273
|
+
logger.info(`Processing ${customQuestions.questionClasses.length} question classes`);
|
|
274
|
+
const { dataShapes, questions } = processCustomQuestionsData(customQuestions);
|
|
275
|
+
logger.info(`Found ${dataShapes.length} data shapes and ${questions.length} questions`);
|
|
276
|
+
let registeredCount = 0;
|
|
277
|
+
logger.info("Registering data shapes...");
|
|
278
|
+
for (const dataShape of dataShapes) if (registerDataShape(dataShape, courseConfig)) registeredCount++;
|
|
279
|
+
logger.info("Registering question types...");
|
|
280
|
+
for (const question of questions) if (registerQuestionType(question, courseConfig)) registeredCount++;
|
|
281
|
+
logger.info("Updating course configuration...");
|
|
282
|
+
const updateResult = await courseDB.updateCourseConfig(courseConfig);
|
|
283
|
+
if (!updateResult.ok) throw new Error(`Failed to update course config: ${JSON.stringify(updateResult)}`);
|
|
284
|
+
if (username) {
|
|
285
|
+
logger.info("Registering seed data...");
|
|
286
|
+
for (const question of questions) await registerSeedData(question, courseDB, username);
|
|
287
|
+
}
|
|
288
|
+
logger.info(`Custom question registration complete: ${registeredCount} items registered`);
|
|
289
|
+
return {
|
|
290
|
+
success: true,
|
|
291
|
+
registeredCount
|
|
292
|
+
};
|
|
293
|
+
} catch (error) {
|
|
294
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
295
|
+
logger.error(`Custom question registration failed: ${errorMessage}`);
|
|
296
|
+
return {
|
|
297
|
+
success: false,
|
|
298
|
+
registeredCount: 0,
|
|
299
|
+
errorMessage
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
//#endregion
|
|
304
|
+
export { isDataShapeRegistered, isDataShapeSchemaAvailable, isQuestionTypeRegistered, processCustomQuestionsData, registerBlanksCard, registerCustomQuestionTypes, registerDataShape, registerQuestionType, registerSeedData, removeCustomQuestionTypes, removeDataShape, removeQuestionType };
|
|
305
|
+
|
|
306
|
+
//# sourceMappingURL=courseConfigRegistration.mjs.map
|