@pie-qti/item-player 0.1.1 → 0.1.5

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 (547) hide show
  1. package/README.md +22 -19
  2. package/dist/catalog/applyGlossaryTriggers.d.ts +15 -0
  3. package/dist/catalog/applyGlossaryTriggers.d.ts.map +1 -0
  4. package/dist/catalog/applyGlossaryTriggers.js +193 -0
  5. package/dist/catalog/catalogExtractor.d.ts +18 -0
  6. package/dist/catalog/catalogExtractor.d.ts.map +1 -0
  7. package/dist/catalog/catalogExtractor.js +114 -0
  8. package/dist/catalog/catalogLookup.d.ts +18 -0
  9. package/dist/catalog/catalogLookup.d.ts.map +1 -0
  10. package/dist/catalog/catalogLookup.js +44 -0
  11. package/dist/catalog/glossaryAction.d.ts +17 -0
  12. package/dist/catalog/glossaryAction.d.ts.map +1 -0
  13. package/dist/catalog/glossaryAction.js +21 -0
  14. package/dist/catalog/types.d.ts +26 -0
  15. package/dist/catalog/types.d.ts.map +1 -0
  16. package/dist/catalog/types.js +6 -0
  17. package/dist/components/actions/typesetAction.d.ts +24 -0
  18. package/dist/components/actions/typesetAction.d.ts.map +1 -0
  19. package/dist/components/actions/typesetAction.js +59 -0
  20. package/dist/components/utils/assignProps.d.ts +2 -0
  21. package/dist/components/utils/assignProps.d.ts.map +1 -0
  22. package/dist/components/utils/assignProps.js +1 -0
  23. package/dist/components/utils/feedbackUtils.d.ts +73 -0
  24. package/dist/components/utils/feedbackUtils.d.ts.map +1 -0
  25. package/dist/components/utils/feedbackUtils.js +93 -0
  26. package/dist/components/utils/index.d.ts +6 -0
  27. package/dist/components/utils/index.d.ts.map +1 -0
  28. package/dist/components/utils/index.js +5 -0
  29. package/dist/core/ComponentRegistry.d.ts +128 -0
  30. package/dist/core/ComponentRegistry.d.ts.map +1 -0
  31. package/dist/core/ComponentRegistry.js +137 -0
  32. package/dist/core/ItemRenderer.d.ts +91 -0
  33. package/dist/core/ItemRenderer.d.ts.map +1 -0
  34. package/dist/core/ItemRenderer.js +261 -0
  35. package/dist/core/Player.d.ts +195 -0
  36. package/dist/core/Player.d.ts.map +1 -0
  37. package/dist/core/Player.js +1235 -0
  38. package/dist/core/Plugin.d.ts +105 -0
  39. package/dist/core/Plugin.d.ts.map +1 -0
  40. package/dist/core/Plugin.js +7 -0
  41. package/dist/core/PluginManager.d.ts +56 -0
  42. package/dist/core/PluginManager.d.ts.map +1 -0
  43. package/dist/core/PluginManager.js +147 -0
  44. package/dist/core/constants.d.ts +68 -0
  45. package/dist/core/constants.d.ts.map +1 -0
  46. package/dist/core/constants.js +106 -0
  47. package/dist/core/declarations.d.ts +45 -0
  48. package/dist/core/declarations.d.ts.map +1 -0
  49. package/dist/core/declarations.js +133 -0
  50. package/dist/core/parsingLimits.d.ts +12 -0
  51. package/dist/core/parsingLimits.d.ts.map +1 -0
  52. package/dist/core/parsingLimits.js +45 -0
  53. package/dist/core/random.d.ts +12 -0
  54. package/dist/core/random.d.ts.map +1 -0
  55. package/dist/core/random.js +21 -0
  56. package/dist/core/rolePolicy.d.ts +16 -0
  57. package/dist/core/rolePolicy.d.ts.map +1 -0
  58. package/dist/core/rolePolicy.js +15 -0
  59. package/dist/core/sanitizer.d.ts +34 -0
  60. package/dist/core/sanitizer.d.ts.map +1 -0
  61. package/dist/core/sanitizer.js +198 -0
  62. package/dist/core/trustedTypes.d.ts +16 -0
  63. package/dist/core/trustedTypes.d.ts.map +1 -0
  64. package/dist/core/trustedTypes.js +55 -0
  65. package/dist/core/urlPolicy.d.ts +8 -0
  66. package/dist/core/urlPolicy.d.ts.map +1 -0
  67. package/dist/core/urlPolicy.js +90 -0
  68. package/dist/element.d.ts +22 -0
  69. package/dist/element.js +5327 -0
  70. package/dist/element.js.map +1 -0
  71. package/dist/extensions/MathLiveEditor.d.ts +32 -0
  72. package/dist/extensions/MathLiveEditor.d.ts.map +1 -0
  73. package/dist/extensions/MathLiveEditor.js +249 -0
  74. package/dist/extraction/ExtractionRegistry.d.ts +112 -0
  75. package/dist/extraction/ExtractionRegistry.d.ts.map +1 -0
  76. package/dist/extraction/ExtractionRegistry.js +260 -0
  77. package/dist/extraction/createContext.d.ts +30 -0
  78. package/dist/extraction/createContext.d.ts.map +1 -0
  79. package/dist/extraction/createContext.js +39 -0
  80. package/dist/extraction/extractors/associateExtractor.d.ts +29 -0
  81. package/dist/extraction/extractors/associateExtractor.d.ts.map +1 -0
  82. package/dist/extraction/extractors/associateExtractor.js +97 -0
  83. package/dist/extraction/extractors/choiceExtractor.d.ts +27 -0
  84. package/dist/extraction/extractors/choiceExtractor.d.ts.map +1 -0
  85. package/dist/extraction/extractors/choiceExtractor.js +93 -0
  86. package/dist/extraction/extractors/customExtractor.d.ts +20 -0
  87. package/dist/extraction/extractors/customExtractor.d.ts.map +1 -0
  88. package/dist/extraction/extractors/customExtractor.js +51 -0
  89. package/dist/extraction/extractors/drawingExtractor.d.ts +30 -0
  90. package/dist/extraction/extractors/drawingExtractor.d.ts.map +1 -0
  91. package/dist/extraction/extractors/drawingExtractor.js +78 -0
  92. package/dist/extraction/extractors/endAttemptExtractor.d.ts +20 -0
  93. package/dist/extraction/extractors/endAttemptExtractor.d.ts.map +1 -0
  94. package/dist/extraction/extractors/endAttemptExtractor.js +53 -0
  95. package/dist/extraction/extractors/extendedTextExtractor.d.ts +21 -0
  96. package/dist/extraction/extractors/extendedTextExtractor.d.ts.map +1 -0
  97. package/dist/extraction/extractors/extendedTextExtractor.js +63 -0
  98. package/dist/extraction/extractors/gapMatchExtractor.d.ts +29 -0
  99. package/dist/extraction/extractors/gapMatchExtractor.d.ts.map +1 -0
  100. package/dist/extraction/extractors/gapMatchExtractor.js +155 -0
  101. package/dist/extraction/extractors/graphicAssociateExtractor.d.ts +41 -0
  102. package/dist/extraction/extractors/graphicAssociateExtractor.d.ts.map +1 -0
  103. package/dist/extraction/extractors/graphicAssociateExtractor.js +143 -0
  104. package/dist/extraction/extractors/graphicGapMatchExtractor.d.ts +53 -0
  105. package/dist/extraction/extractors/graphicGapMatchExtractor.d.ts.map +1 -0
  106. package/dist/extraction/extractors/graphicGapMatchExtractor.js +205 -0
  107. package/dist/extraction/extractors/graphicOrderExtractor.d.ts +37 -0
  108. package/dist/extraction/extractors/graphicOrderExtractor.d.ts.map +1 -0
  109. package/dist/extraction/extractors/graphicOrderExtractor.js +121 -0
  110. package/dist/extraction/extractors/hotspotExtractor.d.ts +38 -0
  111. package/dist/extraction/extractors/hotspotExtractor.d.ts.map +1 -0
  112. package/dist/extraction/extractors/hotspotExtractor.js +159 -0
  113. package/dist/extraction/extractors/hottextExtractor.d.ts +26 -0
  114. package/dist/extraction/extractors/hottextExtractor.d.ts.map +1 -0
  115. package/dist/extraction/extractors/hottextExtractor.js +128 -0
  116. package/dist/extraction/extractors/index.d.ts +63 -0
  117. package/dist/extraction/extractors/index.d.ts.map +1 -0
  118. package/dist/extraction/extractors/index.js +88 -0
  119. package/dist/extraction/extractors/inlineChoiceExtractor.d.ts +25 -0
  120. package/dist/extraction/extractors/inlineChoiceExtractor.d.ts.map +1 -0
  121. package/dist/extraction/extractors/inlineChoiceExtractor.js +80 -0
  122. package/dist/extraction/extractors/matchExtractor.d.ts +37 -0
  123. package/dist/extraction/extractors/matchExtractor.d.ts.map +1 -0
  124. package/dist/extraction/extractors/matchExtractor.js +160 -0
  125. package/dist/extraction/extractors/mediaExtractor.d.ts +33 -0
  126. package/dist/extraction/extractors/mediaExtractor.d.ts.map +1 -0
  127. package/dist/extraction/extractors/mediaExtractor.js +125 -0
  128. package/dist/extraction/extractors/orderExtractor.d.ts +28 -0
  129. package/dist/extraction/extractors/orderExtractor.d.ts.map +1 -0
  130. package/dist/extraction/extractors/orderExtractor.js +90 -0
  131. package/dist/extraction/extractors/portableCustomExtractor.d.ts +14 -0
  132. package/dist/extraction/extractors/portableCustomExtractor.d.ts.map +1 -0
  133. package/dist/extraction/extractors/portableCustomExtractor.js +96 -0
  134. package/dist/extraction/extractors/positionObjectExtractor.d.ts +59 -0
  135. package/dist/extraction/extractors/positionObjectExtractor.d.ts.map +1 -0
  136. package/dist/extraction/extractors/positionObjectExtractor.js +191 -0
  137. package/dist/extraction/extractors/selectPointExtractor.d.ts +31 -0
  138. package/dist/extraction/extractors/selectPointExtractor.d.ts.map +1 -0
  139. package/dist/extraction/extractors/selectPointExtractor.js +109 -0
  140. package/dist/extraction/extractors/sliderExtractor.d.ts +24 -0
  141. package/dist/extraction/extractors/sliderExtractor.d.ts.map +1 -0
  142. package/dist/extraction/extractors/sliderExtractor.js +73 -0
  143. package/dist/extraction/extractors/textEntryExtractor.d.ts +21 -0
  144. package/dist/extraction/extractors/textEntryExtractor.d.ts.map +1 -0
  145. package/dist/extraction/extractors/textEntryExtractor.js +54 -0
  146. package/dist/extraction/extractors/uploadExtractor.d.ts +20 -0
  147. package/dist/extraction/extractors/uploadExtractor.d.ts.map +1 -0
  148. package/dist/extraction/extractors/uploadExtractor.js +59 -0
  149. package/dist/extraction/index.d.ts +49 -0
  150. package/dist/extraction/index.d.ts.map +1 -0
  151. package/dist/extraction/index.js +49 -0
  152. package/dist/extraction/types.d.ts +209 -0
  153. package/dist/extraction/types.d.ts.map +1 -0
  154. package/dist/extraction/types.js +30 -0
  155. package/dist/extraction/utils.d.ts +15 -0
  156. package/dist/extraction/utils.d.ts.map +1 -0
  157. package/dist/extraction/utils.js +178 -0
  158. package/dist/iframe/IFramePlayerHost.d.ts +122 -0
  159. package/dist/iframe/IFramePlayerHost.d.ts.map +1 -0
  160. package/dist/iframe/IFramePlayerHost.js +172 -0
  161. package/dist/iframe/index.d.ts +9 -0
  162. package/dist/iframe/index.d.ts.map +1 -0
  163. package/dist/iframe/index.js +8 -0
  164. package/dist/iframe/protocol.d.ts +75 -0
  165. package/dist/iframe/protocol.d.ts.map +1 -0
  166. package/dist/iframe/protocol.js +53 -0
  167. package/dist/index.d.ts +38 -0
  168. package/dist/index.d.ts.map +1 -0
  169. package/dist/index.js +42 -0
  170. package/dist/pci/PciHost.d.ts +53 -0
  171. package/dist/pci/PciHost.d.ts.map +1 -0
  172. package/dist/pci/PciHost.js +116 -0
  173. package/dist/pci/types.d.ts +57 -0
  174. package/dist/pci/types.d.ts.map +1 -0
  175. package/dist/pci/types.js +19 -0
  176. package/dist/pnp/applyPnp.d.ts +9 -0
  177. package/dist/pnp/applyPnp.d.ts.map +1 -0
  178. package/dist/pnp/applyPnp.js +19 -0
  179. package/dist/pnp/parsePnpXml.d.ts +9 -0
  180. package/dist/pnp/parsePnpXml.d.ts.map +1 -0
  181. package/dist/pnp/parsePnpXml.js +101 -0
  182. package/dist/pnp/types.d.ts +40 -0
  183. package/dist/pnp/types.d.ts.map +1 -0
  184. package/dist/pnp/types.js +1 -0
  185. package/dist/server.d.ts +10 -0
  186. package/dist/server.d.ts.map +1 -0
  187. package/dist/server.js +10 -0
  188. package/dist/types/index.d.ts +304 -0
  189. package/dist/types/index.d.ts.map +1 -0
  190. package/dist/types/index.js +7 -0
  191. package/dist/types/interactions.d.ts +412 -0
  192. package/dist/types/interactions.d.ts.map +1 -0
  193. package/dist/types/interactions.js +7 -0
  194. package/dist/types/responseValidation.d.ts +25 -0
  195. package/dist/types/responseValidation.d.ts.map +1 -0
  196. package/dist/types/responseValidation.js +1 -0
  197. package/dist/utils/PerformanceMonitor.d.ts +170 -0
  198. package/dist/utils/PerformanceMonitor.d.ts.map +1 -0
  199. package/dist/utils/PerformanceMonitor.js +242 -0
  200. package/dist/utils/drawingUtils.d.ts +39 -0
  201. package/dist/utils/drawingUtils.d.ts.map +1 -0
  202. package/dist/utils/drawingUtils.js +57 -0
  203. package/dist/utils/responseUtils.d.ts +16 -0
  204. package/dist/utils/responseUtils.d.ts.map +1 -0
  205. package/dist/utils/responseUtils.js +45 -0
  206. package/dist/utils/touchDragHelper.d.ts +2 -0
  207. package/dist/utils/touchDragHelper.d.ts.map +1 -0
  208. package/dist/utils/touchDragHelper.js +1 -0
  209. package/dist/web-components/QTIInteractionBase.d.ts +120 -0
  210. package/dist/web-components/QTIInteractionBase.d.ts.map +1 -0
  211. package/dist/web-components/QTIInteractionBase.js +243 -0
  212. package/dist/web-components/QTIInteractionElement.d.ts +77 -0
  213. package/dist/web-components/QTIInteractionElement.d.ts.map +1 -0
  214. package/dist/web-components/QTIInteractionElement.js +61 -0
  215. package/dist/web-components/index.d.ts +8 -0
  216. package/dist/web-components/index.d.ts.map +1 -0
  217. package/dist/web-components/index.js +10 -0
  218. package/package.json +104 -76
  219. package/src/__tests__/catalog.test.ts +267 -0
  220. package/src/__tests__/fixtures/pci/echo-pci.js +49 -0
  221. package/src/__tests__/glossaryTriggers.test.ts +411 -0
  222. package/src/__tests__/pci.test.ts +353 -0
  223. package/src/__tests__/pnp.test.ts +250 -0
  224. package/src/__tests__/qti3-attribute-extraction.test.ts +174 -0
  225. package/src/__tests__/qti3-debug.test.ts +140 -0
  226. package/src/__tests__/qti3-extraction.test.ts +309 -0
  227. package/src/catalog/applyGlossaryTriggers.ts +232 -0
  228. package/src/catalog/catalogExtractor.ts +130 -0
  229. package/src/catalog/catalogLookup.ts +53 -0
  230. package/src/catalog/glossaryAction.ts +28 -0
  231. package/src/catalog/types.ts +37 -0
  232. package/src/components/ItemBody.svelte +136 -26
  233. package/src/components/ItemPlayer.svelte +6 -2
  234. package/src/components/index.ts +3 -0
  235. package/src/components/utils/assignProps.ts +1 -23
  236. package/src/core/ComponentRegistry.ts +14 -0
  237. package/src/core/ItemRenderer.ts +4 -0
  238. package/src/core/Player.ts +312 -38
  239. package/src/core/parsingLimits.ts +1 -1
  240. package/src/core/rolePolicy.ts +34 -0
  241. package/src/core/urlPolicy.ts +5 -2
  242. package/src/element.ts +128 -0
  243. package/src/extensions/MathLiveEditor.ts +6 -3
  244. package/src/extraction/ExtractionRegistry.ts +51 -11
  245. package/src/extraction/createContext.ts +6 -1
  246. package/src/extraction/extractors/associateExtractor.ts +4 -0
  247. package/src/extraction/extractors/choiceExtractor.ts +12 -1
  248. package/src/extraction/extractors/conformance-qti3-advanced.test.ts +239 -0
  249. package/src/extraction/extractors/conformance-qti3-basic.test.ts +82 -0
  250. package/src/extraction/extractors/conformance.test.ts +208 -0
  251. package/src/extraction/extractors/extendedTextExtractor.ts +11 -2
  252. package/src/extraction/extractors/gapMatchExtractor.ts +36 -21
  253. package/src/extraction/extractors/graphicAssociateExtractor.ts +4 -0
  254. package/src/extraction/extractors/graphicGapMatchExtractor.ts +82 -10
  255. package/src/extraction/extractors/hotspotExtractor.ts +26 -8
  256. package/src/extraction/extractors/hottextExtractor.ts +15 -5
  257. package/src/extraction/extractors/index.ts +4 -0
  258. package/src/extraction/extractors/inlineChoiceExtractor.ts +22 -5
  259. package/src/extraction/extractors/matchExtractor.ts +33 -6
  260. package/src/extraction/extractors/orderExtractor.ts +6 -0
  261. package/src/extraction/extractors/portableCustomExtractor.ts +122 -0
  262. package/src/extraction/extractors/selectPointExtractor.ts +5 -5
  263. package/src/extraction/extractors/textEntryExtractor.ts +11 -2
  264. package/src/extraction/extractors/uploadExtractor.ts +10 -2
  265. package/src/extraction/utils.ts +99 -16
  266. package/src/index.ts +19 -1
  267. package/src/pci/PciHost.ts +138 -0
  268. package/src/pci/types.ts +70 -0
  269. package/src/pnp/applyPnp.ts +23 -0
  270. package/src/pnp/parsePnpXml.ts +118 -0
  271. package/src/pnp/types.ts +33 -0
  272. package/src/types/index.ts +50 -16
  273. package/src/types/interactions.ts +81 -6
  274. package/src/types/xmldom.d.ts +12 -0
  275. package/src/utils/drawingUtils.ts +73 -0
  276. package/src/utils/touchDragHelper.ts +1 -211
  277. package/.turbo/turbo-build.log +0 -1
  278. package/CHANGELOG.md +0 -9
  279. package/docs/QTI-COMPLIANCE.md +0 -197
  280. package/docs/WCAG-2.2-COMPLIANCE.md +0 -466
  281. package/docs/custom-extractors.md +0 -679
  282. package/docs/iframe-mode.md +0 -78
  283. package/docs/security-audit.md +0 -236
  284. package/docs/server-api.md +0 -691
  285. package/tests/conformance/FIXTURE_POLICY.md +0 -29
  286. package/tests/conformance/README.md +0 -70
  287. package/tests/conformance/fixtures/baseTypes_all/cases.json +0 -61
  288. package/tests/conformance/fixtures/baseTypes_all/item.xml +0 -131
  289. package/tests/conformance/fixtures/baseTypes_all/manifest.json +0 -7
  290. package/tests/conformance/fixtures/choice_match_correct/cases.json +0 -17
  291. package/tests/conformance/fixtures/choice_match_correct/item.xml +0 -55
  292. package/tests/conformance/fixtures/choice_match_correct/manifest.json +0 -14
  293. package/tests/conformance/fixtures/contains_multiple/cases.json +0 -12
  294. package/tests/conformance/fixtures/contains_multiple/item.xml +0 -37
  295. package/tests/conformance/fixtures/contains_multiple/manifest.json +0 -13
  296. package/tests/conformance/fixtures/isNull_isNotNull/cases.json +0 -9
  297. package/tests/conformance/fixtures/isNull_isNotNull/item.xml +0 -41
  298. package/tests/conformance/fixtures/isNull_isNotNull/manifest.json +0 -23
  299. package/tests/conformance/fixtures/mapResponse_bounds_default_duplicates/cases.json +0 -27
  300. package/tests/conformance/fixtures/mapResponse_bounds_default_duplicates/item.xml +0 -30
  301. package/tests/conformance/fixtures/mapResponse_bounds_default_duplicates/manifest.json +0 -15
  302. package/tests/conformance/fixtures/mapResponse_integer_mapKey/cases.json +0 -11
  303. package/tests/conformance/fixtures/mapResponse_integer_mapKey/item.xml +0 -26
  304. package/tests/conformance/fixtures/mapResponse_integer_mapKey/manifest.json +0 -13
  305. package/tests/conformance/fixtures/mapResponse_mapEntry_caseSensitive_override/cases.json +0 -27
  306. package/tests/conformance/fixtures/mapResponse_mapEntry_caseSensitive_override/item.xml +0 -32
  307. package/tests/conformance/fixtures/mapResponse_mapEntry_caseSensitive_override/manifest.json +0 -7
  308. package/tests/conformance/fixtures/mapResponse_mapping_caseSensitive_defaultValue/cases.json +0 -9
  309. package/tests/conformance/fixtures/mapResponse_mapping_caseSensitive_defaultValue/item.xml +0 -25
  310. package/tests/conformance/fixtures/mapResponse_mapping_caseSensitive_defaultValue/manifest.json +0 -12
  311. package/tests/conformance/fixtures/mapResponse_multiple_cardinality/cases.json +0 -12
  312. package/tests/conformance/fixtures/mapResponse_multiple_cardinality/item.xml +0 -35
  313. package/tests/conformance/fixtures/mapResponse_multiple_cardinality/manifest.json +0 -11
  314. package/tests/conformance/fixtures/mapping_bounds_upperLower/cases.json +0 -12
  315. package/tests/conformance/fixtures/mapping_bounds_upperLower/item.xml +0 -37
  316. package/tests/conformance/fixtures/mapping_bounds_upperLower/manifest.json +0 -11
  317. package/tests/conformance/fixtures/mapping_mapResponse/cases.json +0 -22
  318. package/tests/conformance/fixtures/mapping_mapResponse/item.xml +0 -53
  319. package/tests/conformance/fixtures/mapping_mapResponse/manifest.json +0 -16
  320. package/tests/conformance/fixtures/member_multiple/cases.json +0 -12
  321. package/tests/conformance/fixtures/member_multiple/item.xml +0 -37
  322. package/tests/conformance/fixtures/member_multiple/manifest.json +0 -13
  323. package/tests/conformance/fixtures/modalFeedback_basic/cases.json +0 -17
  324. package/tests/conformance/fixtures/modalFeedback_basic/item.xml +0 -52
  325. package/tests/conformance/fixtures/modalFeedback_basic/manifest.json +0 -13
  326. package/tests/conformance/fixtures/multiple_unordered_match/cases.json +0 -17
  327. package/tests/conformance/fixtures/multiple_unordered_match/item.xml +0 -44
  328. package/tests/conformance/fixtures/multiple_unordered_match/manifest.json +0 -11
  329. package/tests/conformance/fixtures/ordered_match/cases.json +0 -17
  330. package/tests/conformance/fixtures/ordered_match/item.xml +0 -48
  331. package/tests/conformance/fixtures/ordered_match/manifest.json +0 -13
  332. package/tests/conformance/fixtures/outcomeProcessing_derive_percent_passfail/cases.json +0 -27
  333. package/tests/conformance/fixtures/outcomeProcessing_derive_percent_passfail/item.xml +0 -103
  334. package/tests/conformance/fixtures/outcomeProcessing_derive_percent_passfail/manifest.json +0 -7
  335. package/tests/conformance/fixtures/outcomeProcessing_exitTest/cases.json +0 -15
  336. package/tests/conformance/fixtures/outcomeProcessing_exitTest/item.xml +0 -33
  337. package/tests/conformance/fixtures/outcomeProcessing_exitTest/manifest.json +0 -10
  338. package/tests/conformance/fixtures/outcomeProcessing_numberExpressions/cases.json +0 -14
  339. package/tests/conformance/fixtures/outcomeProcessing_numberExpressions/item.xml +0 -26
  340. package/tests/conformance/fixtures/outcomeProcessing_numberExpressions/manifest.json +0 -8
  341. package/tests/conformance/fixtures/outcomeProcessing_outcomeCondition_equal/cases.json +0 -17
  342. package/tests/conformance/fixtures/outcomeProcessing_outcomeCondition_equal/item.xml +0 -43
  343. package/tests/conformance/fixtures/outcomeProcessing_outcomeCondition_equal/manifest.json +0 -16
  344. package/tests/conformance/fixtures/outcomeProcessing_outcomeCondition_toBoolean/cases.json +0 -27
  345. package/tests/conformance/fixtures/outcomeProcessing_outcomeCondition_toBoolean/item.xml +0 -37
  346. package/tests/conformance/fixtures/outcomeProcessing_outcomeCondition_toBoolean/manifest.json +0 -16
  347. package/tests/conformance/fixtures/outcomeProcessing_outcomeMaximum/cases.json +0 -14
  348. package/tests/conformance/fixtures/outcomeProcessing_outcomeMaximum/item.xml +0 -35
  349. package/tests/conformance/fixtures/outcomeProcessing_outcomeMaximum/manifest.json +0 -8
  350. package/tests/conformance/fixtures/outcomeProcessing_outcomeMinimum/cases.json +0 -14
  351. package/tests/conformance/fixtures/outcomeProcessing_outcomeMinimum/item.xml +0 -35
  352. package/tests/conformance/fixtures/outcomeProcessing_outcomeMinimum/manifest.json +0 -8
  353. package/tests/conformance/fixtures/outcomeProcessing_outcomeProcessingFragment/cases.json +0 -15
  354. package/tests/conformance/fixtures/outcomeProcessing_outcomeProcessingFragment/item.xml +0 -39
  355. package/tests/conformance/fixtures/outcomeProcessing_outcomeProcessingFragment/manifest.json +0 -11
  356. package/tests/conformance/fixtures/outcomeProcessing_testVariables/cases.json +0 -14
  357. package/tests/conformance/fixtures/outcomeProcessing_testVariables/item.xml +0 -35
  358. package/tests/conformance/fixtures/outcomeProcessing_testVariables/manifest.json +0 -8
  359. package/tests/conformance/fixtures/pair_unordered_match/cases.json +0 -22
  360. package/tests/conformance/fixtures/pair_unordered_match/item.xml +0 -44
  361. package/tests/conformance/fixtures/pair_unordered_match/manifest.json +0 -13
  362. package/tests/conformance/fixtures/positionObject_coordinateSystem_aspectRatio/cases.json +0 -95
  363. package/tests/conformance/fixtures/positionObject_coordinateSystem_aspectRatio/item.xml +0 -53
  364. package/tests/conformance/fixtures/positionObject_mapResponsePoint_scoring/cases.json +0 -115
  365. package/tests/conformance/fixtures/positionObject_mapResponsePoint_scoring/item.xml +0 -45
  366. package/tests/conformance/fixtures/positionObject_mapResponse_wrong/cases.json +0 -29
  367. package/tests/conformance/fixtures/positionObject_mapResponse_wrong/item.xml +0 -40
  368. package/tests/conformance/fixtures/responseCondition_elseIf_chain/cases.json +0 -10
  369. package/tests/conformance/fixtures/responseCondition_elseIf_chain/item.xml +0 -49
  370. package/tests/conformance/fixtures/responseCondition_elseIf_chain/manifest.json +0 -15
  371. package/tests/conformance/fixtures/responseProcessing_anyN/cases.json +0 -27
  372. package/tests/conformance/fixtures/responseProcessing_anyN/item.xml +0 -47
  373. package/tests/conformance/fixtures/responseProcessing_anyN/manifest.json +0 -16
  374. package/tests/conformance/fixtures/responseProcessing_anyN_allN/cases.json +0 -27
  375. package/tests/conformance/fixtures/responseProcessing_anyN_allN/item.xml +0 -69
  376. package/tests/conformance/fixtures/responseProcessing_anyN_allN/manifest.json +0 -23
  377. package/tests/conformance/fixtures/responseProcessing_arithmetic_nulls/cases.json +0 -15
  378. package/tests/conformance/fixtures/responseProcessing_arithmetic_nulls/item.xml +0 -58
  379. package/tests/conformance/fixtures/responseProcessing_arithmetic_nulls/manifest.json +0 -15
  380. package/tests/conformance/fixtures/responseProcessing_boolean_compare_ops/cases.json +0 -37
  381. package/tests/conformance/fixtures/responseProcessing_boolean_compare_ops/item.xml +0 -94
  382. package/tests/conformance/fixtures/responseProcessing_boolean_compare_ops/manifest.json +0 -27
  383. package/tests/conformance/fixtures/responseProcessing_containerSize_index/cases.json +0 -33
  384. package/tests/conformance/fixtures/responseProcessing_containerSize_index/item.xml +0 -79
  385. package/tests/conformance/fixtures/responseProcessing_containerSize_index/manifest.json +0 -16
  386. package/tests/conformance/fixtures/responseProcessing_customOperator/cases.json +0 -15
  387. package/tests/conformance/fixtures/responseProcessing_customOperator/item.xml +0 -30
  388. package/tests/conformance/fixtures/responseProcessing_customOperator/manifest.json +0 -12
  389. package/tests/conformance/fixtures/responseProcessing_default_expression/cases.json +0 -12
  390. package/tests/conformance/fixtures/responseProcessing_default_expression/item.xml +0 -48
  391. package/tests/conformance/fixtures/responseProcessing_default_expression/manifest.json +0 -13
  392. package/tests/conformance/fixtures/responseProcessing_deleteValue_repeat/cases.json +0 -29
  393. package/tests/conformance/fixtures/responseProcessing_deleteValue_repeat/item.xml +0 -68
  394. package/tests/conformance/fixtures/responseProcessing_deleteValue_repeat/manifest.json +0 -17
  395. package/tests/conformance/fixtures/responseProcessing_equalRounded_tolerance/cases.json +0 -39
  396. package/tests/conformance/fixtures/responseProcessing_equalRounded_tolerance/item.xml +0 -39
  397. package/tests/conformance/fixtures/responseProcessing_equalRounded_tolerance/manifest.json +0 -17
  398. package/tests/conformance/fixtures/responseProcessing_exitResponse/cases.json +0 -12
  399. package/tests/conformance/fixtures/responseProcessing_exitResponse/item.xml +0 -25
  400. package/tests/conformance/fixtures/responseProcessing_exitResponse/manifest.json +0 -12
  401. package/tests/conformance/fixtures/responseProcessing_inside_duration_statsOperator/cases.json +0 -26
  402. package/tests/conformance/fixtures/responseProcessing_inside_duration_statsOperator/item.xml +0 -134
  403. package/tests/conformance/fixtures/responseProcessing_inside_duration_statsOperator/manifest.json +0 -16
  404. package/tests/conformance/fixtures/responseProcessing_lookupTable_interpolationTable/cases.json +0 -27
  405. package/tests/conformance/fixtures/responseProcessing_lookupTable_interpolationTable/item.xml +0 -33
  406. package/tests/conformance/fixtures/responseProcessing_lookupTable_interpolationTable/manifest.json +0 -13
  407. package/tests/conformance/fixtures/responseProcessing_lookupTable_matchTable/cases.json +0 -22
  408. package/tests/conformance/fixtures/responseProcessing_lookupTable_matchTable/item.xml +0 -33
  409. package/tests/conformance/fixtures/responseProcessing_lookupTable_matchTable/manifest.json +0 -13
  410. package/tests/conformance/fixtures/responseProcessing_mapOutcome_basic/cases.json +0 -27
  411. package/tests/conformance/fixtures/responseProcessing_mapOutcome_basic/item.xml +0 -40
  412. package/tests/conformance/fixtures/responseProcessing_mapOutcome_basic/manifest.json +0 -18
  413. package/tests/conformance/fixtures/responseProcessing_mapResponsePoint_basic/cases.json +0 -22
  414. package/tests/conformance/fixtures/responseProcessing_mapResponsePoint_basic/item.xml +0 -33
  415. package/tests/conformance/fixtures/responseProcessing_mapResponsePoint_basic/manifest.json +0 -12
  416. package/tests/conformance/fixtures/responseProcessing_mapResponse_directedPair_ordered/cases.json +0 -29
  417. package/tests/conformance/fixtures/responseProcessing_mapResponse_directedPair_ordered/item.xml +0 -26
  418. package/tests/conformance/fixtures/responseProcessing_mapResponse_directedPair_ordered/manifest.json +0 -7
  419. package/tests/conformance/fixtures/responseProcessing_mapResponse_directedPair_whitespace/cases.json +0 -23
  420. package/tests/conformance/fixtures/responseProcessing_mapResponse_directedPair_whitespace/item.xml +0 -28
  421. package/tests/conformance/fixtures/responseProcessing_mapResponse_directedPair_whitespace/manifest.json +0 -11
  422. package/tests/conformance/fixtures/responseProcessing_mapResponse_pair_unordered/cases.json +0 -29
  423. package/tests/conformance/fixtures/responseProcessing_mapResponse_pair_unordered/item.xml +0 -26
  424. package/tests/conformance/fixtures/responseProcessing_mapResponse_pair_unordered/manifest.json +0 -7
  425. package/tests/conformance/fixtures/responseProcessing_mathOperator_integerUtils/cases.json +0 -31
  426. package/tests/conformance/fixtures/responseProcessing_mathOperator_integerUtils/item.xml +0 -102
  427. package/tests/conformance/fixtures/responseProcessing_mathOperator_integerUtils/manifest.json +0 -18
  428. package/tests/conformance/fixtures/responseProcessing_math_max_min_round_truncate/cases.json +0 -22
  429. package/tests/conformance/fixtures/responseProcessing_math_max_min_round_truncate/item.xml +0 -45
  430. package/tests/conformance/fixtures/responseProcessing_math_max_min_round_truncate/manifest.json +0 -21
  431. package/tests/conformance/fixtures/responseProcessing_misc_math_string_stats/cases.json +0 -26
  432. package/tests/conformance/fixtures/responseProcessing_misc_math_string_stats/item.xml +0 -157
  433. package/tests/conformance/fixtures/responseProcessing_misc_math_string_stats/manifest.json +0 -22
  434. package/tests/conformance/fixtures/responseProcessing_notEqual_basic/cases.json +0 -22
  435. package/tests/conformance/fixtures/responseProcessing_notEqual_basic/item.xml +0 -39
  436. package/tests/conformance/fixtures/responseProcessing_notEqual_basic/manifest.json +0 -18
  437. package/tests/conformance/fixtures/responseProcessing_patternMatch_caseSensitive/cases.json +0 -22
  438. package/tests/conformance/fixtures/responseProcessing_patternMatch_caseSensitive/item.xml +0 -51
  439. package/tests/conformance/fixtures/responseProcessing_patternMatch_caseSensitive/manifest.json +0 -19
  440. package/tests/conformance/fixtures/responseProcessing_preCondition/cases.json +0 -31
  441. package/tests/conformance/fixtures/responseProcessing_preCondition/item.xml +0 -44
  442. package/tests/conformance/fixtures/responseProcessing_preCondition/manifest.json +0 -12
  443. package/tests/conformance/fixtures/responseProcessing_random_lookupOutcomeValue/cases.json +0 -27
  444. package/tests/conformance/fixtures/responseProcessing_random_lookupOutcomeValue/item.xml +0 -42
  445. package/tests/conformance/fixtures/responseProcessing_random_lookupOutcomeValue/manifest.json +0 -14
  446. package/tests/conformance/fixtures/responseProcessing_record_fieldValue/cases.json +0 -12
  447. package/tests/conformance/fixtures/responseProcessing_record_fieldValue/item.xml +0 -40
  448. package/tests/conformance/fixtures/responseProcessing_record_fieldValue/manifest.json +0 -17
  449. package/tests/conformance/fixtures/responseProcessing_responseCondition_toBoolean/cases.json +0 -17
  450. package/tests/conformance/fixtures/responseProcessing_responseCondition_toBoolean/item.xml +0 -63
  451. package/tests/conformance/fixtures/responseProcessing_responseCondition_toBoolean/manifest.json +0 -9
  452. package/tests/conformance/fixtures/responseProcessing_responseProcessingFragment/cases.json +0 -12
  453. package/tests/conformance/fixtures/responseProcessing_responseProcessingFragment/item.xml +0 -40
  454. package/tests/conformance/fixtures/responseProcessing_responseProcessingFragment/manifest.json +0 -13
  455. package/tests/conformance/fixtures/responseProcessing_setDefaultValue/cases.json +0 -15
  456. package/tests/conformance/fixtures/responseProcessing_setDefaultValue/item.xml +0 -67
  457. package/tests/conformance/fixtures/responseProcessing_setDefaultValue/manifest.json +0 -9
  458. package/tests/conformance/fixtures/responseProcessing_setResponseValue_setDefaultValue/cases.json +0 -27
  459. package/tests/conformance/fixtures/responseProcessing_setResponseValue_setDefaultValue/item.xml +0 -69
  460. package/tests/conformance/fixtures/responseProcessing_setResponseValue_setDefaultValue/manifest.json +0 -10
  461. package/tests/conformance/fixtures/responseProcessing_subtract_divide/cases.json +0 -15
  462. package/tests/conformance/fixtures/responseProcessing_subtract_divide/item.xml +0 -35
  463. package/tests/conformance/fixtures/responseProcessing_subtract_divide/manifest.json +0 -11
  464. package/tests/conformance/fixtures/responseProcessing_template_map_response/cases.json +0 -17
  465. package/tests/conformance/fixtures/responseProcessing_template_map_response/item.xml +0 -31
  466. package/tests/conformance/fixtures/responseProcessing_template_map_response/manifest.json +0 -8
  467. package/tests/conformance/fixtures/responseProcessing_template_map_response_point/cases.json +0 -22
  468. package/tests/conformance/fixtures/responseProcessing_template_map_response_point/item.xml +0 -27
  469. package/tests/conformance/fixtures/responseProcessing_template_map_response_point/manifest.json +0 -8
  470. package/tests/conformance/fixtures/responseProcessing_template_match_correct/cases.json +0 -17
  471. package/tests/conformance/fixtures/responseProcessing_template_match_correct/item.xml +0 -34
  472. package/tests/conformance/fixtures/responseProcessing_template_match_correct/manifest.json +0 -8
  473. package/tests/conformance/fixtures/responseProcessing_template_match_correct_directedPair/cases.json +0 -22
  474. package/tests/conformance/fixtures/responseProcessing_template_match_correct_directedPair/item.xml +0 -30
  475. package/tests/conformance/fixtures/responseProcessing_template_match_correct_directedPair/manifest.json +0 -7
  476. package/tests/conformance/fixtures/responseProcessing_template_match_correct_two_responses/cases.json +0 -17
  477. package/tests/conformance/fixtures/responseProcessing_template_match_correct_two_responses/item.xml +0 -30
  478. package/tests/conformance/fixtures/responseProcessing_template_match_correct_two_responses/manifest.json +0 -9
  479. package/tests/conformance/fixtures/responseProcessing_template_match_nothing/cases.json +0 -17
  480. package/tests/conformance/fixtures/responseProcessing_template_match_nothing/item.xml +0 -30
  481. package/tests/conformance/fixtures/responseProcessing_template_match_nothing/manifest.json +0 -8
  482. package/tests/conformance/fixtures/responseProcessing_xiInclude/cases.json +0 -14
  483. package/tests/conformance/fixtures/responseProcessing_xiInclude/item.xml +0 -25
  484. package/tests/conformance/fixtures/responseProcessing_xiInclude/manifest.json +0 -9
  485. package/tests/conformance/fixtures/stringMatch_caseSensitive_substring/cases.json +0 -12
  486. package/tests/conformance/fixtures/stringMatch_caseSensitive_substring/item.xml +0 -52
  487. package/tests/conformance/fixtures/stringMatch_caseSensitive_substring/manifest.json +0 -14
  488. package/tests/conformance/fixtures/templateProcessing_exitTemplate/cases.json +0 -12
  489. package/tests/conformance/fixtures/templateProcessing_exitTemplate/item.xml +0 -48
  490. package/tests/conformance/fixtures/templateProcessing_exitTemplate/manifest.json +0 -13
  491. package/tests/conformance/fixtures/templateProcessing_setCorrectResponse/cases.json +0 -27
  492. package/tests/conformance/fixtures/templateProcessing_setCorrectResponse/item.xml +0 -74
  493. package/tests/conformance/fixtures/templateProcessing_setCorrectResponse/manifest.json +0 -22
  494. package/tests/conformance/fixtures/templateProcessing_templateCondition_branching/cases.json +0 -17
  495. package/tests/conformance/fixtures/templateProcessing_templateCondition_branching/item.xml +0 -133
  496. package/tests/conformance/fixtures/templateProcessing_templateCondition_branching/manifest.json +0 -22
  497. package/tests/conformance/fixtures/templateProcessing_templateCondition_toBoolean/cases.json +0 -12
  498. package/tests/conformance/fixtures/templateProcessing_templateCondition_toBoolean/item.xml +0 -107
  499. package/tests/conformance/fixtures/templateProcessing_templateCondition_toBoolean/manifest.json +0 -16
  500. package/tests/conformance/fixtures/templateProcessing_templateConstraint/cases.json +0 -15
  501. package/tests/conformance/fixtures/templateProcessing_templateConstraint/item.xml +0 -52
  502. package/tests/conformance/fixtures/templateProcessing_templateConstraint/manifest.json +0 -14
  503. package/tests/conformance/fixtures/template_randomFloat_roundTo_mathConstant/cases.json +0 -16
  504. package/tests/conformance/fixtures/template_randomFloat_roundTo_mathConstant/item.xml +0 -49
  505. package/tests/conformance/fixtures/template_randomFloat_roundTo_mathConstant/manifest.json +0 -15
  506. package/tests/conformance/fixtures/template_randomInteger_printedVariable/cases.json +0 -16
  507. package/tests/conformance/fixtures/template_randomInteger_printedVariable/item.xml +0 -38
  508. package/tests/conformance/fixtures/template_randomInteger_printedVariable/manifest.json +0 -13
  509. package/tests/conformance/harness.ts +0 -84
  510. package/tests/conformance/run-fixtures.test.ts +0 -127
  511. package/tests/conformance/scripts/normalize-covers.ts +0 -152
  512. package/tests/conformance/types.ts +0 -53
  513. package/tests/core/Player.test.ts +0 -563
  514. package/tests/core/adaptiveItems.test.ts +0 -442
  515. package/tests/core/correctResponse.test.ts +0 -280
  516. package/tests/core/interaction-plumbing.test.ts +0 -141
  517. package/tests/core/modalFeedback.test.ts +0 -308
  518. package/tests/core/outcome-reset.test.ts +0 -43
  519. package/tests/extraction/extractors/associateExtractor.test.ts +0 -182
  520. package/tests/extraction/extractors/choiceExtractor.test.ts +0 -239
  521. package/tests/extraction/extractors/customExtractor.test.ts +0 -83
  522. package/tests/extraction/extractors/drawingExtractor.test.ts +0 -94
  523. package/tests/extraction/extractors/endAttemptExtractor.test.ts +0 -188
  524. package/tests/extraction/extractors/extendedTextExtractor.test.ts +0 -178
  525. package/tests/extraction/extractors/gapMatchExtractor.test.ts +0 -318
  526. package/tests/extraction/extractors/graphicAssociateExtractor.test.ts +0 -260
  527. package/tests/extraction/extractors/graphicGapMatchExtractor.test.ts +0 -320
  528. package/tests/extraction/extractors/graphicOrderExtractor.test.ts +0 -223
  529. package/tests/extraction/extractors/hotspotExtractor.test.ts +0 -298
  530. package/tests/extraction/extractors/hottextExtractor.test.ts +0 -240
  531. package/tests/extraction/extractors/inlineChoiceExtractor.test.ts +0 -292
  532. package/tests/extraction/extractors/matchExtractor.test.ts +0 -241
  533. package/tests/extraction/extractors/mediaExtractor.test.ts +0 -295
  534. package/tests/extraction/extractors/orderExtractor.test.ts +0 -212
  535. package/tests/extraction/extractors/positionObjectExtractor.test.ts +0 -363
  536. package/tests/extraction/extractors/selectPointExtractor.test.ts +0 -214
  537. package/tests/extraction/extractors/sliderExtractor.test.ts +0 -293
  538. package/tests/extraction/extractors/textEntryExtractor.test.ts +0 -133
  539. package/tests/extraction/extractors/uploadExtractor.test.ts +0 -119
  540. package/tests/extraction/test-utils.ts +0 -57
  541. package/tests/iframe/host.test.ts +0 -145
  542. package/tests/iframe/protocol.test.ts +0 -42
  543. package/tests/performance/player-benchmarks.bench.ts +0 -191
  544. package/tests/security/dos-limits.test.ts +0 -56
  545. package/tests/security/xss-prevention.test.ts +0 -522
  546. package/tsconfig.json +0 -20
  547. package/tsconfig.svelte.json +0 -14
@@ -0,0 +1,1235 @@
1
+ import { buildOutcomeProcessingAst, buildResponseProcessingAst, buildTemplateProcessingAst, childElements, coerceBaseValue, DeclarationContext, evalExpr, execProgram, findAssessmentItem, findDescendants, findFirstDescendant, getAttr, OperatorRegistry, parseXml, qtiNull, qtiValue, serializeXml, toBoolean, toNumber, toStringValue, } from '@pie-qti/qti-processing';
2
+ import { Qti2xElementNameMapper, Qti2xAttributeNameMapper, Qti3ElementNameMapper, Qti3AttributeNameMapper, detectQtiVersion, } from '@pie-qti/qti-common';
3
+ import { parse } from 'node-html-parser';
4
+ import { createExtractionRegistry } from '../extraction/ExtractionRegistry.js';
5
+ import { ALL_STANDARD_EXTRACTORS, createExtractionContext } from '../extraction/index.js';
6
+ import { createComponentRegistry } from './ComponentRegistry.js';
7
+ import { enforceItemXmlLimits } from './parsingLimits.js';
8
+ import { createSeededRng } from './random.js';
9
+ import { sanitizeHtml } from './sanitizer.js';
10
+ import { toTrustedHtml } from './trustedTypes.js';
11
+ import { sanitizeResourceUrl } from './urlPolicy.js';
12
+ import { applyPnpToRoot } from '../pnp/applyPnp.js';
13
+ import { extractCatalogFromItemXml, mergeCatalogs } from '../catalog/catalogExtractor.js';
14
+ import { getCatalogEntry } from '../catalog/catalogLookup.js';
15
+ import { PciHost } from '../pci/PciHost.js';
16
+ export class Player {
17
+ constructor(config) {
18
+ this.responseProcessingProgram = null;
19
+ this.templateProcessingProgram = null;
20
+ this.outcomeProcessingProgram = null;
21
+ this._catalogIndex = new Map();
22
+ this._pciHosts = new Map();
23
+ this.config = config;
24
+ this.itemXml = config.itemXml ?? '';
25
+ this.role = config.role ?? 'candidate';
26
+ this.rng = config.rng ?? (typeof config.seed === 'number' ? createSeededRng(config.seed) : Math.random);
27
+ // Auto-detect QTI version and create appropriate mappers if not provided
28
+ if (!config.elementNameMapper) {
29
+ const version = detectQtiVersion(this.itemXml);
30
+ if (version === '3.0') {
31
+ this.mapper = new Qti3ElementNameMapper();
32
+ // Set in config so it's available to extraction utils
33
+ config.elementNameMapper = this.mapper;
34
+ // Also set attribute mapper if not provided
35
+ if (!config.attributeNameMapper) {
36
+ config.attributeNameMapper = new Qti3AttributeNameMapper();
37
+ }
38
+ }
39
+ else {
40
+ this.mapper = new Qti2xElementNameMapper();
41
+ config.elementNameMapper = this.mapper;
42
+ if (!config.attributeNameMapper) {
43
+ config.attributeNameMapper = new Qti2xAttributeNameMapper();
44
+ }
45
+ }
46
+ }
47
+ else {
48
+ this.mapper = config.elementNameMapper;
49
+ }
50
+ // Optional DoS guardrails for untrusted content (compat-by-default; disabled unless enabled).
51
+ enforceItemXmlLimits(this.itemXml, this.config.security);
52
+ this.doc = parseXml(this.itemXml);
53
+ this.assessmentItem = findAssessmentItem(this.doc);
54
+ this.decls = this.buildDeclarations(this.assessmentItem);
55
+ this.ensureBuiltinDeclarations(this.decls);
56
+ this.ctx = new DeclarationContext(this.decls);
57
+ this.ops = new OperatorRegistry();
58
+ // Restore session state (outcomes + responses) before running templateProcessing.
59
+ if (config.sessionState) {
60
+ this.applySessionState(config.sessionState);
61
+ }
62
+ // Extraction + rendering registries (for interaction rendering)
63
+ // Pass the element name mapper to the extraction registry for QTI version handling
64
+ this.extractionRegistry = config.extractionRegistry ?? createExtractionRegistry(this.mapper);
65
+ this.componentRegistry = config.componentRegistry ?? createComponentRegistry();
66
+ // I18n provider (defaults to a simple fallback if not provided)
67
+ this.i18nProvider = config.i18nProvider ?? this.createDefaultI18nProvider();
68
+ // Register standard extractors (idempotent per-registry instance)
69
+ for (const ex of ALL_STANDARD_EXTRACTORS) {
70
+ try {
71
+ this.extractionRegistry.register(ex);
72
+ }
73
+ catch {
74
+ // ignore duplicates if a caller pre-registered
75
+ }
76
+ }
77
+ // Plugins can further extend registries
78
+ for (const p of (config.plugins ?? [])) {
79
+ try {
80
+ p?.registerExtractors?.(this.extractionRegistry);
81
+ p?.registerComponents?.(this.componentRegistry);
82
+ }
83
+ catch {
84
+ // plugin errors shouldn't prevent core parsing
85
+ }
86
+ }
87
+ // Build ASTs once.
88
+ const templateProcessing = findFirstDescendant(this.assessmentItem, this.mapper.toNative('templateprocessing'));
89
+ if (templateProcessing) {
90
+ this.templateProcessingProgram = buildTemplateProcessingAst(templateProcessing, {
91
+ elementNameMapper: this.mapper,
92
+ });
93
+ this.execTemplateProcessing();
94
+ }
95
+ const responseProcessing = findFirstDescendant(this.assessmentItem, this.mapper.toNative('responseprocessing'));
96
+ if (responseProcessing) {
97
+ this.responseProcessingProgram = buildResponseProcessingAst(responseProcessing, {
98
+ elementNameMapper: this.mapper,
99
+ });
100
+ }
101
+ const outcomeProcessing = findFirstDescendant(this.assessmentItem, this.mapper.toNative('outcomeprocessing'));
102
+ if (outcomeProcessing) {
103
+ this.outcomeProcessingProgram = buildOutcomeProcessingAst(outcomeProcessing, {
104
+ elementNameMapper: this.mapper,
105
+ });
106
+ }
107
+ // Apply initial responses after templateProcessing (so template vars are ready).
108
+ if (config.responses) {
109
+ this.setResponses(config.responses);
110
+ }
111
+ // Detect and log QTI version for compatibility awareness
112
+ const detectedVersion = this.detectQTIVersion();
113
+ if (detectedVersion === 'unknown') {
114
+ console.warn('[QTI Player] Could not detect QTI version. Assuming QTI 2.2 compatibility.');
115
+ }
116
+ else if (detectedVersion === '2.0') {
117
+ console.warn('[QTI Player] QTI 2.0 detected. Some features may not be fully supported. QTI 2.2 is recommended.');
118
+ }
119
+ else if (detectedVersion === '2.1') {
120
+ console.info('[QTI Player] QTI 2.1 detected. Using QTI 2.2 compatibility mode with CC2 template support.');
121
+ }
122
+ // Store PNP profile for later use (applyPnpToRoot is called once a root element is available).
123
+ this._pnp = config.pnp;
124
+ // Build catalog index from item XML and optional shared catalog.
125
+ const itemCatalog = extractCatalogFromItemXml(this.itemXml);
126
+ if (config.catalogXml) {
127
+ const sharedCatalog = extractCatalogFromItemXml(config.catalogXml);
128
+ // Item-level wins on collision: merge shared first, then override with item entries.
129
+ this._catalogIndex = mergeCatalogs(sharedCatalog, itemCatalog);
130
+ }
131
+ else {
132
+ this._catalogIndex = itemCatalog;
133
+ }
134
+ // Check strict compliance if enabled
135
+ if (this.config.strictQtiCompliance?.enabled) {
136
+ this.validateStrictCompliance();
137
+ }
138
+ }
139
+ /**
140
+ * Apply the PNP profile to a player root element.
141
+ * Call this once the root DOM element is available (e.g. after mounting).
142
+ * The player stores the element reference so updatePnp() can re-apply without re-parsing the item.
143
+ */
144
+ applyPnp(rootEl) {
145
+ this._rootEl = rootEl;
146
+ applyPnpToRoot(rootEl, this._pnp);
147
+ }
148
+ /**
149
+ * Update the PNP profile mid-session without re-parsing the item XML.
150
+ * Deep-merges the partial profile into the current profile and re-applies.
151
+ */
152
+ updatePnp(partial) {
153
+ this._pnp = mergePnp(this._pnp, partial);
154
+ if (this._rootEl) {
155
+ applyPnpToRoot(this._rootEl, this._pnp);
156
+ }
157
+ }
158
+ /** Return the current resolved PNP profile. */
159
+ getPnp() {
160
+ return this._pnp;
161
+ }
162
+ /**
163
+ * Look up a catalog entry by card identifier, usage type, and optional language.
164
+ * Returns the HTML string for the matched entry, or null if not found.
165
+ *
166
+ * Language fallback: exact match → prefix match → no-lang entry → null.
167
+ */
168
+ getCatalogEntry(idref, usage, lang) {
169
+ return getCatalogEntry(this._catalogIndex, idref, usage, lang);
170
+ }
171
+ /**
172
+ * Create a PciHost for an extracted PCI and register it for response tracking.
173
+ * The caller (typically ItemRenderer) is responsible for calling host.load() and
174
+ * host.initialize(domNode) once the DOM element is available.
175
+ */
176
+ createPciHost(data) {
177
+ const baseUrl = this.config.pciBaseUrl ?? (typeof document !== 'undefined' ? document.baseURI : '');
178
+ const host = new PciHost(data, baseUrl);
179
+ // Wire response changes back into the player's declaration context
180
+ host.onResponseChange((responseId, value) => {
181
+ const d = this.decls[responseId];
182
+ if (d) {
183
+ d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, value);
184
+ }
185
+ });
186
+ this._pciHosts.set(data.responseIdentifier, host);
187
+ return host;
188
+ }
189
+ /**
190
+ * Push a response value into the PCI identified by responseIdentifier.
191
+ * Called from setResponses() so session restore reaches PCI modules.
192
+ */
193
+ setPciResponse(responseIdentifier, value) {
194
+ this._pciHosts.get(responseIdentifier)?.setResponse(value);
195
+ }
196
+ /**
197
+ * Disable/enable all PCI hosts based on role.
198
+ * 'candidate' = enabled; any other role = disabled.
199
+ */
200
+ syncPciDisabledState() {
201
+ const disabled = this.role !== 'candidate';
202
+ for (const host of this._pciHosts.values()) {
203
+ if (disabled)
204
+ host.disable();
205
+ else
206
+ host.enable();
207
+ }
208
+ }
209
+ /**
210
+ * Destroy all PCI hosts. Call on player teardown.
211
+ */
212
+ destroyPciHosts() {
213
+ for (const host of this._pciHosts.values()) {
214
+ host.destroy();
215
+ }
216
+ this._pciHosts.clear();
217
+ }
218
+ /** Breaking-change API: returns the typed declaration map */
219
+ getDeclarations() {
220
+ return this.decls;
221
+ }
222
+ setResponses(responses) {
223
+ for (const [id, raw] of Object.entries(responses)) {
224
+ const d = this.decls[id];
225
+ if (!d)
226
+ continue;
227
+ d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw);
228
+ // Push restored responses into any mounted PCI modules
229
+ this.setPciResponse(id, raw);
230
+ }
231
+ }
232
+ /**
233
+ * Destroy all resources owned by this player instance (PCI modules, etc.).
234
+ * Call when unmounting to prevent memory leaks.
235
+ */
236
+ destroy() {
237
+ this.destroyPciHosts();
238
+ }
239
+ processResponses() {
240
+ // Spec-aligned behavior: each processing run starts from outcome defaults.
241
+ // This prevents stale outcomes when response/outcome processing doesn't set every variable.
242
+ this.resetOutcomesToDefault();
243
+ // Execute response processing if present
244
+ const rpEl = findFirstDescendant(this.assessmentItem, this.mapper.toNative('responseprocessing'));
245
+ if (rpEl) {
246
+ // If responseProcessing has explicit statements, run the compiled program.
247
+ // Otherwise, fall back to template-based processing (responseProcessing@template).
248
+ const hasStatements = childElements(rpEl).length > 0;
249
+ if (hasStatements) {
250
+ this.execResponseProcessingProgram();
251
+ }
252
+ else {
253
+ const templateUrl = getAttr(rpEl, 'template');
254
+ if (templateUrl)
255
+ this.execResponseProcessingTemplate(templateUrl);
256
+ }
257
+ }
258
+ // Execute outcome processing if present (runs after responseProcessing)
259
+ this.execOutcomeProcessingProgram();
260
+ // For non-adaptive items, update completionStatus and numAttempts after processing
261
+ if (!this.isAdaptive()) {
262
+ // Set completionStatus to 'completed' for non-adaptive items (single submission)
263
+ this.ctx.setValue('completionStatus', qtiValue('identifier', 'single', 'completed'));
264
+ // Increment numAttempts for non-adaptive items (tracks total submissions, including retries)
265
+ const currentAttempts = this.getNumAttempts();
266
+ this.ctx.setValue('numAttempts', qtiValue('integer', 'single', currentAttempts + 1));
267
+ }
268
+ const outcomes = this.collectOutcomes();
269
+ const score = Number(outcomes.SCORE ?? 0);
270
+ const maxScore = Number(outcomes.MAXSCORE ?? 1);
271
+ const completionStatus = outcomes.completionStatus ?? 'not_attempted';
272
+ const completed = completionStatus === 'completed' || !this.isAdaptive();
273
+ return {
274
+ score,
275
+ maxScore,
276
+ completed,
277
+ outcomeValues: outcomes,
278
+ modalFeedback: this.getModalFeedback(outcomes),
279
+ };
280
+ }
281
+ getSecurityConfig() {
282
+ return this.config.security;
283
+ }
284
+ getTrustedTypesPolicyName() {
285
+ return this.config.security?.trustedTypesPolicyName;
286
+ }
287
+ /**
288
+ * Get the i18n provider instance
289
+ * @returns I18nProvider instance
290
+ */
291
+ getI18nProvider() {
292
+ return this.i18nProvider;
293
+ }
294
+ /**
295
+ * Get attribute value with QTI version support.
296
+ * Tries the attribute mapper's native form first, then falls back to direct lookup.
297
+ * @param el - Element to get attribute from
298
+ * @param canonicalName - Canonical (lowercase) attribute name
299
+ * @returns Attribute value or null
300
+ */
301
+ getAttrMapped(el, canonicalName) {
302
+ // Try mapped attribute name first (e.g., 'mapkey' -> 'map-key' for QTI 3.0)
303
+ if (this.config.attributeNameMapper) {
304
+ const nativeName = this.config.attributeNameMapper.toNative(canonicalName);
305
+ const value = el.getAttribute(nativeName);
306
+ if (value !== null)
307
+ return value;
308
+ }
309
+ // Fallback to canonical name (for QTI 2.x compatibility)
310
+ return getAttr(el, canonicalName);
311
+ }
312
+ /**
313
+ * Create a simple fallback i18n provider when none is provided
314
+ * This avoids a hard dependency on @pie-qti/i18n
315
+ */
316
+ createDefaultI18nProvider() {
317
+ return {
318
+ getLocale: () => 'en-US',
319
+ setLocale: () => { },
320
+ t: (key) => key, // Fallback to key
321
+ plural: (key) => key,
322
+ formatNumber: (value) => value.toString(),
323
+ formatDate: (date) => date.toISOString(),
324
+ };
325
+ }
326
+ /**
327
+ * Detects the QTI version from the assessmentItem element.
328
+ * Checks both namespace URI and version attribute.
329
+ *
330
+ * @returns QTI version string ('2.0', '2.1', '2.2') or 'unknown'
331
+ */
332
+ detectQTIVersion() {
333
+ const ns = this.assessmentItem.namespaceURI;
334
+ if (ns?.includes('v3p0') || ns?.includes('imsqtiasi_v3p0'))
335
+ return '3.0';
336
+ if (ns?.includes('v2p2') || ns?.includes('imsqti_v2p2'))
337
+ return '2.2';
338
+ if (ns?.includes('v2p1') || ns?.includes('imsqti_v2p1'))
339
+ return '2.1';
340
+ if (ns?.includes('v2p0') || ns?.includes('imsqti_v2p0'))
341
+ return '2.0';
342
+ // Check element name for QTI 3.0
343
+ const localName = this.assessmentItem.localName || this.assessmentItem.tagName;
344
+ if (localName === 'qti-assessment-item' || localName === 'qti-assessment-test') {
345
+ return '3.0';
346
+ }
347
+ const versionAttr = getAttr(this.assessmentItem, 'version');
348
+ if (versionAttr?.startsWith('3.'))
349
+ return '3.0';
350
+ if (versionAttr === '2.0')
351
+ return '2.0';
352
+ if (versionAttr === '2.1')
353
+ return '2.1';
354
+ if (versionAttr === '2.2')
355
+ return '2.2';
356
+ return 'unknown';
357
+ }
358
+ /**
359
+ * Validates strict QTI 2.2 compliance if enabled in configuration.
360
+ * Logs warnings or throws errors based on config settings.
361
+ */
362
+ validateStrictCompliance() {
363
+ const config = this.config.strictQtiCompliance;
364
+ if (!config?.enabled)
365
+ return;
366
+ const version = this.detectQTIVersion();
367
+ if (version !== '2.2') {
368
+ const message = `[QTI Player] Strict compliance enabled but item version is ${version}, not 2.2`;
369
+ if (config.rejectUnknownExtensions) {
370
+ throw new Error(message);
371
+ }
372
+ else if (config.logDeviations !== false) {
373
+ console.warn(message);
374
+ }
375
+ }
376
+ // Future: Add validation for non-standard elements/attributes
377
+ }
378
+ resetOutcomesToDefault() {
379
+ for (const d of Object.values(this.decls)) {
380
+ if (d.__kind !== 'outcome')
381
+ continue;
382
+ // Built-in stateful variables must survive across processing runs.
383
+ // They are updated by the runtime (adaptive attempt tracking), not by outcome defaults.
384
+ if (d.identifier === 'numAttempts' || d.identifier === 'completionStatus')
385
+ continue;
386
+ this.ctx.resetToDefault(d.identifier);
387
+ }
388
+ }
389
+ getItemBodyHtml() {
390
+ const itemBody = findFirstDescendant(this.assessmentItem, this.mapper.toNative('itembody'));
391
+ if (!itemBody)
392
+ return '';
393
+ // Serialize children rather than the container tag itself.
394
+ const inner = childElements(itemBody).map((c) => serializeXml(c)).join('');
395
+ const printed = this.renderPrintedVariables(inner);
396
+ const sanitized = sanitizeHtml(printed, { security: this.config.security });
397
+ return toTrustedHtml(sanitized, this.config.security?.trustedTypesPolicyName);
398
+ }
399
+ /**
400
+ * Extract rubric blocks for the current role.
401
+ *
402
+ * QTI uses `<rubricBlock view="...">` to provide role-specific guidance.
403
+ * We return sanitized HTML for direct rendering.
404
+ */
405
+ getRubrics() {
406
+ const role = this.role;
407
+ const rubricEls = findDescendants(this.assessmentItem, this.mapper.toNative('rubricblock'));
408
+ if (rubricEls.length === 0)
409
+ return [];
410
+ const blocks = [];
411
+ for (const el of rubricEls) {
412
+ const viewRaw = (getAttr(el, 'view') || '').trim();
413
+ const view = viewRaw ? viewRaw.split(/\s+/).filter(Boolean) : [];
414
+ // If view is specified, show only when it includes the current role.
415
+ if (view.length > 0 && role && !view.includes(role))
416
+ continue;
417
+ // Serialize children rather than the container tag itself.
418
+ const contentRaw = childElements(el).map((c) => serializeXml(c)).join('') || (el.textContent || '');
419
+ const printed = this.renderPrintedVariables(contentRaw);
420
+ const sanitized = sanitizeHtml(printed, { security: this.config.security });
421
+ const html = toTrustedHtml(sanitized, this.config.security?.trustedTypesPolicyName);
422
+ blocks.push({ view, html });
423
+ }
424
+ return blocks;
425
+ }
426
+ getComponentRegistry() {
427
+ return this.componentRegistry;
428
+ }
429
+ getExtractionRegistry() {
430
+ return this.extractionRegistry;
431
+ }
432
+ /**
433
+ * Canonical interaction API (new): extracted, typed interaction data.
434
+ */
435
+ getInteractionData() {
436
+ const itemBody = findFirstDescendant(this.assessmentItem, this.mapper.toNative('itembody'));
437
+ if (!itemBody)
438
+ return [];
439
+ // Parse the original item XML with node-html-parser (extractors depend on its HTMLElement API).
440
+ // Important: using the original XML avoids namespace/serialization artifacts from XMLSerializer.
441
+ enforceItemXmlLimits(this.itemXml, this.config.security);
442
+ const docRoot = parse(this.itemXml, { lowerCaseTagName: false, comment: false });
443
+ // node-html-parser's CSS selectors match lowercase tag names.
444
+ // Search for itemBody in the native form for this QTI version (itembody for 2.x, qti-item-body for 3.0)
445
+ const itemBodyTag = this.mapper.toNative('itembody').toLowerCase();
446
+ const parsedItemBody = docRoot.querySelector?.(itemBodyTag) ?? null;
447
+ const root = parsedItemBody ?? docRoot;
448
+ const declMap = new Map();
449
+ for (const d of Object.values(this.decls)) {
450
+ declMap.set(d.identifier, {
451
+ identifier: d.identifier,
452
+ cardinality: d.cardinality,
453
+ baseType: d.baseType,
454
+ });
455
+ }
456
+ // Discover all elements that match any standard extractor elementType.
457
+ // Extractors specify element types in QTI 2.x form (e.g., 'choiceInteraction').
458
+ // We use the mapper to convert to the appropriate form for this QTI version
459
+ // (e.g., 'choiceInteraction' for QTI 2.x, 'qti-choice-interaction' for QTI 3.0).
460
+ const tagSet = new Set();
461
+ for (const ex of ALL_STANDARD_EXTRACTORS) {
462
+ for (const t of ex.elementTypes ?? []) {
463
+ // Convert to canonical form (lowercase), then to native form using mapper
464
+ const canonical = t.toLowerCase();
465
+ const native = this.mapper.toNative(canonical);
466
+ tagSet.add(native.toLowerCase());
467
+ }
468
+ }
469
+ const elements = [];
470
+ for (const tag of tagSet) {
471
+ try {
472
+ elements.push(...root.querySelectorAll(tag));
473
+ }
474
+ catch {
475
+ // ignore selector errors
476
+ }
477
+ }
478
+ const interactions = [];
479
+ for (const el of elements) {
480
+ // Try both QTI 2.x (responseIdentifier) and QTI 3.0 (response-identifier) attribute names
481
+ const responseId = el.getAttribute?.('responseIdentifier') ||
482
+ el.getAttribute?.('response-identifier') ||
483
+ el.getAttribute?.('responseidentifier') ||
484
+ '';
485
+ if (!responseId)
486
+ continue;
487
+ const ctx = createExtractionContext(el, responseId, root, declMap, this.config);
488
+ const res = this.extractionRegistry.extract(el, ctx);
489
+ if (!res.success)
490
+ continue;
491
+ // Normalize raw tag to QTI 2.x camelCase for ComponentRegistry compatibility.
492
+ // QTI 3.0 elements use kebab-case with 'qti-' prefix:
493
+ // 'qti-choice-interaction' → 'choiceInteraction'
494
+ const rawTag = el.rawTagName;
495
+ const normalizedType = rawTag.startsWith('qti-')
496
+ ? rawTag.slice(4).replace(/-([a-z])/g, (_, c) => c.toUpperCase())
497
+ : rawTag;
498
+ interactions.push({
499
+ type: normalizedType,
500
+ responseId,
501
+ ...res.data,
502
+ });
503
+ }
504
+ // Apply URL policy + embed allowances to standard extracted URL fields.
505
+ const policy = this.config.security?.urlPolicy;
506
+ const allowObjectEmbeds = this.config.security?.allowObjectEmbeds === true;
507
+ const ttPolicyName = this.config.security?.trustedTypesPolicyName;
508
+ for (const i of interactions) {
509
+ // Wrap known HTML injection fields in TrustedHTML (when enabled).
510
+ // Important: do NOT wrap fields that are rendered as plain text in our Svelte components
511
+ // (e.g. prompt) to avoid "[object Object]" rendering.
512
+ if (i.type === 'choiceInteraction' && Array.isArray(i.choices)) {
513
+ for (const c of i.choices) {
514
+ if (typeof c?.text === 'string')
515
+ c.text = toTrustedHtml(c.text, ttPolicyName);
516
+ }
517
+ }
518
+ // Shared ImageData shape
519
+ if (i.imageData?.src) {
520
+ i.imageData.src = sanitizeResourceUrl(i.imageData.src, policy, 'img') ?? '';
521
+ }
522
+ if (i.imageData?.content && typeof i.imageData.content === 'string') {
523
+ i.imageData.content = toTrustedHtml(i.imageData.content, ttPolicyName);
524
+ }
525
+ // positionObject stages
526
+ if (Array.isArray(i.positionObjectStages)) {
527
+ for (const st of i.positionObjectStages) {
528
+ if (st?.objectData?.src) {
529
+ st.objectData.src = sanitizeResourceUrl(st.objectData.src, policy, 'img') ?? '';
530
+ }
531
+ if (st?.objectData?.content && typeof st.objectData.content === 'string') {
532
+ st.objectData.content = toTrustedHtml(st.objectData.content, ttPolicyName);
533
+ }
534
+ }
535
+ }
536
+ // mediaInteraction
537
+ if (i.type === 'mediaInteraction' && i.mediaElement?.src) {
538
+ const kind = i.mediaElement.type === 'object' ? 'object' : 'media';
539
+ i.mediaElement.src = sanitizeResourceUrl(i.mediaElement.src, policy, kind) ?? '';
540
+ i.allowObjectEmbeds = allowObjectEmbeds;
541
+ }
542
+ // hottextInteraction content is injected via {@html}
543
+ if (i.type === 'hottextInteraction' && typeof i.contentHtml === 'string') {
544
+ i.contentHtml = toTrustedHtml(i.contentHtml, ttPolicyName);
545
+ }
546
+ }
547
+ return interactions;
548
+ }
549
+ /**
550
+ * Convenience API (used by tests/bench): returns a minimal interaction list with QTI-ish field names.
551
+ */
552
+ getInteractions() {
553
+ return this.getInteractionData().map((i) => ({
554
+ ...i,
555
+ responseIdentifier: i.responseId,
556
+ }));
557
+ }
558
+ getResponseInteractions() {
559
+ return this.getInteractions().filter((i) => i.type !== 'endAttemptInteraction');
560
+ }
561
+ /**
562
+ * Returns response identifiers of endAttempt interactions with countAttempt="false".
563
+ * Used to detect hint-only submissions (e.g. Request Hint button).
564
+ */
565
+ getHintEndAttemptIdentifiers() {
566
+ return this.getInteractions()
567
+ .filter((i) => i.type === 'endAttemptInteraction' && i.countAttempt === false)
568
+ .map((i) => i.responseIdentifier);
569
+ }
570
+ getResponseIdentifiers() {
571
+ return this.getResponseInteractions().map((i) => i.responseIdentifier);
572
+ }
573
+ isAdaptive() {
574
+ return (getAttr(this.assessmentItem, 'adaptive') || '').toLowerCase() === 'true';
575
+ }
576
+ getNumAttempts() {
577
+ return Math.max(0, Math.floor(toNumber(this.ctx.getValue('numAttempts')) || 0));
578
+ }
579
+ getCompletionStatus() {
580
+ const s = (toStringValue(this.ctx.getValue('completionStatus')) || '').trim();
581
+ return (s || 'not_attempted');
582
+ }
583
+ isCompleted() {
584
+ return this.getCompletionStatus() === 'completed';
585
+ }
586
+ submitAttempt(countAttempt = true) {
587
+ if (this.isCompleted()) {
588
+ throw new Error('Cannot submit: item is already completed');
589
+ }
590
+ // QTI adaptive semantics: numAttempts should reflect the attempt being processed.
591
+ if (this.isAdaptive() && countAttempt) {
592
+ const next = this.getNumAttempts() + 1;
593
+ this.ctx.setValue('numAttempts', qtiValue('integer', 'single', next));
594
+ // Promote completionStatus from not_attempted -> unknown on first submission unless RP sets it.
595
+ if (this.getCompletionStatus() === 'not_attempted') {
596
+ this.ctx.setValue('completionStatus', qtiValue('identifier', 'single', 'unknown'));
597
+ }
598
+ }
599
+ const base = this.processResponses();
600
+ const completionStatus = this.getCompletionStatus();
601
+ const completed = completionStatus === 'completed';
602
+ const canContinue = this.isAdaptive() ? !completed : false;
603
+ return {
604
+ ...base,
605
+ completed,
606
+ numAttempts: this.getNumAttempts(),
607
+ completionStatus,
608
+ canContinue,
609
+ };
610
+ }
611
+ getResponses() {
612
+ const out = {};
613
+ for (const d of Object.values(this.decls)) {
614
+ if (d.__kind !== 'response')
615
+ continue;
616
+ out[d.identifier] = d.value.kind === 'value' ? d.value.value : null;
617
+ }
618
+ return out;
619
+ }
620
+ /**
621
+ * Get correct response for a specific response identifier
622
+ * @param responseId - The response identifier
623
+ * @returns The correct response value, or undefined if not available
624
+ */
625
+ getCorrectResponse(responseId) {
626
+ const decl = this.decls[responseId];
627
+ if (!decl || decl.__kind !== 'response')
628
+ return undefined;
629
+ const respDecl = decl; // ResponseDeclaration from qti-processing
630
+ if (!respDecl.correctResponse)
631
+ return undefined;
632
+ if (respDecl.correctResponse.kind !== 'value')
633
+ return undefined;
634
+ return respDecl.correctResponse.value;
635
+ }
636
+ /**
637
+ * Get all correct responses as a map
638
+ * @returns Map of responseId to correct response value
639
+ */
640
+ getCorrectResponses() {
641
+ const out = {};
642
+ for (const d of Object.values(this.decls)) {
643
+ if (d.__kind !== 'response')
644
+ continue;
645
+ const respDecl = d;
646
+ if (!respDecl.correctResponse || respDecl.correctResponse.kind !== 'value')
647
+ continue;
648
+ out[d.identifier] = respDecl.correctResponse.value;
649
+ }
650
+ return out;
651
+ }
652
+ getTemplateVariables() {
653
+ const out = {};
654
+ for (const d of Object.values(this.decls)) {
655
+ if (!d.isTemplate)
656
+ continue;
657
+ out[d.identifier] = d.value.kind === 'value' ? d.value.value : null;
658
+ }
659
+ return out;
660
+ }
661
+ setTemplateVariables(vars) {
662
+ for (const [id, raw] of Object.entries(vars)) {
663
+ const d = this.decls[id];
664
+ if (!d?.isTemplate)
665
+ continue;
666
+ d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw);
667
+ }
668
+ }
669
+ getSessionState() {
670
+ const out = {};
671
+ for (const d of Object.values(this.decls)) {
672
+ out[d.identifier] = d.value.kind === 'value' ? d.value.value : null;
673
+ }
674
+ return out;
675
+ }
676
+ validateResponses(responses) {
677
+ const interactions = this.getInteractions();
678
+ const entries = {};
679
+ const issues = [];
680
+ for (const i of interactions) {
681
+ const responseId = i.responseIdentifier;
682
+ const decl = this.decls[responseId];
683
+ const value = responses[responseId];
684
+ const required = i.type !== 'endAttemptInteraction' &&
685
+ (i.type !== 'mediaInteraction' || (typeof i.minPlays === 'number' && i.minPlays > 0));
686
+ let complete = !required;
687
+ if (i.type === 'mediaInteraction' && required) {
688
+ const minPlays = Number(i.minPlays || 0);
689
+ complete = Number(value || 0) >= minPlays;
690
+ }
691
+ else if (required) {
692
+ if (Array.isArray(value)) {
693
+ complete = value.length > 0;
694
+ // Enforce minChoices / minAssociations where applicable
695
+ const minChoices = Number(i.minChoices || i.minAssociations || 0);
696
+ if (complete && minChoices > 0) {
697
+ complete = value.length >= minChoices;
698
+ }
699
+ // Enforce matchMin per-choice: each pairing entry "id1 id2" in value must
700
+ // appear at least matchMin times for the relevant choice.
701
+ // Collect all choice arrays that can carry matchMin across all pairing interaction types.
702
+ const choices = [
703
+ ...(i.choices ?? []),
704
+ ...(i.gapTexts ?? []),
705
+ ...(i.gapImages ?? []),
706
+ ...(i.sourceSet ?? []),
707
+ ...(i.targetSet ?? []),
708
+ ...(i.associableHotspots ?? []),
709
+ ];
710
+ for (const choice of choices) {
711
+ const min = Number(choice.matchMin || 0);
712
+ if (min > 0) {
713
+ const count = value.filter((p) => {
714
+ const parts = p.split(' ');
715
+ return parts[0] === choice.identifier || parts[1] === choice.identifier;
716
+ }).length;
717
+ if (count < min) {
718
+ complete = false;
719
+ break;
720
+ }
721
+ }
722
+ }
723
+ }
724
+ else {
725
+ complete = value !== null && value !== undefined && value !== '';
726
+ }
727
+ }
728
+ const errors = [];
729
+ const warnings = [];
730
+ if (decl) {
731
+ if (decl.cardinality === 'multiple' || decl.cardinality === 'ordered') {
732
+ if (!(value === null || value === undefined || Array.isArray(value))) {
733
+ errors.push(`Expected an array for ${decl.cardinality} response '${responseId}'`);
734
+ }
735
+ }
736
+ else {
737
+ if (Array.isArray(value)) {
738
+ errors.push(`Expected a single value for response '${responseId}'`);
739
+ }
740
+ }
741
+ }
742
+ const valid = errors.length === 0;
743
+ entries[responseId] = {
744
+ responseId,
745
+ interactionType: i.type,
746
+ required,
747
+ complete,
748
+ valid,
749
+ errors,
750
+ warnings,
751
+ };
752
+ for (const e of errors) {
753
+ issues.push({
754
+ responseId,
755
+ code: 'invalid_shape',
756
+ message: e,
757
+ severity: 'error',
758
+ });
759
+ }
760
+ }
761
+ const allValid = Object.values(entries).every((e) => e.valid);
762
+ return { valid: allValid, entries, issues };
763
+ }
764
+ getProgress(responses) {
765
+ const v = this.validateResponses(responses);
766
+ const required = Object.values(v.entries).filter((e) => e.required);
767
+ const answered = required.filter((e) => e.complete).length;
768
+ const total = required.length;
769
+ return { total, answered, unanswered: Math.max(0, total - answered) };
770
+ }
771
+ canSubmitResponses(responses) {
772
+ const v = this.validateResponses(responses);
773
+ const required = Object.values(v.entries).filter((e) => e.required);
774
+ return v.valid && required.every((e) => e.complete);
775
+ }
776
+ /**
777
+ * True if the learner has made any meaningful interaction, even if submission is not yet allowed.
778
+ * Used by assessment/session controllers to track "answered" state.
779
+ */
780
+ isAttempted(responses) {
781
+ for (const i of this.getResponseInteractions()) {
782
+ const id = i.responseIdentifier;
783
+ const v = responses[id];
784
+ if (i.type === 'mediaInteraction') {
785
+ if (Number(v || 0) > 0)
786
+ return true;
787
+ continue;
788
+ }
789
+ if (Array.isArray(v)) {
790
+ if (v.length > 0)
791
+ return true;
792
+ continue;
793
+ }
794
+ if (v !== null && v !== undefined && v !== '')
795
+ return true;
796
+ }
797
+ return false;
798
+ }
799
+ // ----------------------------------------------------------------------------
800
+ // Execution
801
+ // ----------------------------------------------------------------------------
802
+ execTemplateProcessing() {
803
+ if (!this.templateProcessingProgram)
804
+ return;
805
+ execProgram({
806
+ ctx: this.ctx,
807
+ ops: this.ops,
808
+ rng: this.rng,
809
+ customOperators: this.config.customOperators,
810
+ }, this.templateProcessingProgram);
811
+ }
812
+ execResponseProcessingProgram() {
813
+ if (!this.responseProcessingProgram)
814
+ return;
815
+ execProgram({
816
+ ctx: this.ctx,
817
+ ops: this.ops,
818
+ rng: this.rng,
819
+ customOperators: this.config.customOperators,
820
+ }, this.responseProcessingProgram);
821
+ }
822
+ execOutcomeProcessingProgram() {
823
+ if (!this.outcomeProcessingProgram)
824
+ return;
825
+ execProgram({
826
+ ctx: this.ctx,
827
+ ops: this.ops,
828
+ rng: this.rng,
829
+ customOperators: this.config.customOperators,
830
+ }, this.outcomeProcessingProgram);
831
+ }
832
+ execResponseProcessingTemplate(templateUrl) {
833
+ const name = templateUrl.split('/').pop()?.toLowerCase().replace(/\.xml$/, '');
834
+ if (!name) {
835
+ console.warn(`[QTI Player] Could not extract template name from URL: ${templateUrl}`);
836
+ return;
837
+ }
838
+ const responseDeclIds = Object.values(this.decls)
839
+ .filter((d) => d.__kind === 'response')
840
+ .map((d) => d.identifier);
841
+ switch (name) {
842
+ case 'match_correct':
843
+ case 'cc2_match': { // CC2_match is an alias for match_correct (QTI 2.1 compatibility)
844
+ const allCorrect = responseDeclIds.every((id) => {
845
+ const expr = { kind: 'expr.match', id: 'tmp', a: { kind: 'expr.variable', id: 'tmp', identifier: id }, b: { kind: 'expr.correct', id: 'tmp', identifier: id } };
846
+ // Use evaluator match semantics by evaluating a constructed MatchExpr
847
+ return toBoolean(evalExpr({ ctx: this.ctx, ops: this.ops, rng: this.rng, customOperators: this.config.customOperators }, expr));
848
+ });
849
+ const max = toNumber(this.ctx.getValue('MAXSCORE'));
850
+ this.ctx.setValue('SCORE', qtiValue('float', 'single', allCorrect ? (Number.isFinite(max) ? max : 1) : 0));
851
+ return;
852
+ }
853
+ case 'match_nothing':
854
+ case 'cc2_match_nothing': { // QTI 2.1 compatibility
855
+ const isEmptyResponse = (v) => {
856
+ if (!v)
857
+ return true;
858
+ if (v.kind === 'null')
859
+ return true;
860
+ if (v.kind === 'invalid')
861
+ return false;
862
+ if (v.value === null || v.value === undefined)
863
+ return true;
864
+ if (Array.isArray(v.value))
865
+ return v.value.length === 0;
866
+ if (typeof v.value === 'string')
867
+ return v.value.trim().length === 0;
868
+ return false;
869
+ };
870
+ const allEmpty = responseDeclIds.every((id) => isEmptyResponse(this.ctx.getValue(id)));
871
+ const max = toNumber(this.ctx.getValue('MAXSCORE'));
872
+ this.ctx.setValue('SCORE', qtiValue('float', 'single', allEmpty ? (Number.isFinite(max) ? max : 1) : 0));
873
+ return;
874
+ }
875
+ case 'map_response':
876
+ case 'cc2_map_response': { // QTI 2.1 compatibility
877
+ let total = 0;
878
+ for (const id of responseDeclIds) {
879
+ const d = this.decls[id];
880
+ if (!d.mapping)
881
+ continue;
882
+ const v = evalExpr({ ctx: this.ctx, ops: this.ops, rng: this.rng }, { kind: 'expr.mapResponse', id: 'tmp', identifier: id });
883
+ total += toNumber(v) || 0;
884
+ }
885
+ this.ctx.setValue('SCORE', qtiValue('float', 'single', total));
886
+ return;
887
+ }
888
+ case 'map_response_point':
889
+ case 'cc2_map_response_point': { // QTI 2.1 compatibility
890
+ let total = 0;
891
+ for (const id of responseDeclIds) {
892
+ const d = this.decls[id];
893
+ if (!d.areaMapping)
894
+ continue;
895
+ const v = evalExpr({ ctx: this.ctx, ops: this.ops, rng: this.rng }, { kind: 'expr.mapResponsePoint', id: 'tmp', identifier: id });
896
+ total += toNumber(v) || 0;
897
+ }
898
+ this.ctx.setValue('SCORE', qtiValue('float', 'single', total));
899
+ return;
900
+ }
901
+ default:
902
+ console.warn(`[QTI Player] Unsupported response processing template: ${name}`);
903
+ return;
904
+ }
905
+ }
906
+ // ----------------------------------------------------------------------------
907
+ // Declarations
908
+ // ----------------------------------------------------------------------------
909
+ buildDeclarations(root) {
910
+ const decls = {};
911
+ const addDecl = (kind, el) => {
912
+ const identifier = this.getAttrMapped(el, 'identifier');
913
+ const cardinality = (this.getAttrMapped(el, 'cardinality') || 'single');
914
+ const baseType = (this.getAttrMapped(el, 'baseType') || 'string');
915
+ if (!identifier)
916
+ return;
917
+ const defaultValue = this.parseDefaultValue(el, baseType, cardinality);
918
+ decls[identifier] = {
919
+ identifier,
920
+ baseType,
921
+ cardinality,
922
+ defaultValue,
923
+ value: defaultValue,
924
+ isTemplate: kind === 'template',
925
+ // @ts-expect-error internal marker for templates
926
+ __kind: kind,
927
+ };
928
+ // Response + outcome declarations may define mappings used by mapResponse/mapOutcome.
929
+ // (Templates do not participate in mapping.)
930
+ if (kind === 'response' || kind === 'outcome') {
931
+ const mappingEl = findFirstDescendant(el, this.mapper.toNative('mapping'));
932
+ if (mappingEl) {
933
+ decls[identifier].mapping = this.parseMapping(mappingEl, baseType);
934
+ }
935
+ }
936
+ // Outcome declarations may define a lookup table (matchTable or interpolationTable)
937
+ // used by the lookupOutcomeValue rule.
938
+ if (kind === 'outcome') {
939
+ const matchTableEl = findFirstDescendant(el, this.mapper.toNative('matchtable'));
940
+ const interpolationTableEl = findFirstDescendant(el, this.mapper.toNative('interpolationtable'));
941
+ if (matchTableEl) {
942
+ decls[identifier].lookupTable = this.parseMatchTable(matchTableEl);
943
+ }
944
+ else if (interpolationTableEl) {
945
+ decls[identifier].lookupTable = this.parseInterpolationTable(interpolationTableEl);
946
+ }
947
+ }
948
+ if (kind === 'response') {
949
+ const correctEl = findFirstDescendant(el, this.mapper.toNative('correctresponse'));
950
+ if (correctEl) {
951
+ decls[identifier].correctResponse = this.parseCorrectResponse(correctEl, baseType, cardinality);
952
+ }
953
+ const areaMappingEl = findFirstDescendant(el, this.mapper.toNative('areamapping'));
954
+ if (areaMappingEl) {
955
+ decls[identifier].areaMapping = this.parseAreaMapping(areaMappingEl);
956
+ }
957
+ }
958
+ };
959
+ for (const el of findDescendants(root, this.mapper.toNative('responsedeclaration')))
960
+ addDecl('response', el);
961
+ for (const el of findDescendants(root, this.mapper.toNative('outcomedeclaration')))
962
+ addDecl('outcome', el);
963
+ for (const el of findDescendants(root, this.mapper.toNative('templatedeclaration')))
964
+ addDecl('template', el);
965
+ return decls;
966
+ }
967
+ parseMatchTable(el) {
968
+ const defaultValueRaw = (getAttr(el, 'defaultValue') || '').trim();
969
+ const defaultValue = defaultValueRaw ? Number(defaultValueRaw) : undefined;
970
+ return {
971
+ kind: 'table.matchTable',
972
+ defaultValue: Number.isFinite(defaultValue) ? defaultValue : undefined,
973
+ entries: findDescendants(el, this.mapper.toNative('matchtableentry')).map((e) => ({
974
+ sourceValue: (getAttr(e, 'sourceValue') || '').trim(),
975
+ targetValue: (getAttr(e, 'targetValue') || '').trim(),
976
+ })),
977
+ };
978
+ }
979
+ parseInterpolationTable(el) {
980
+ const defaultValueRaw = (getAttr(el, 'defaultValue') || '').trim();
981
+ const defaultValue = defaultValueRaw ? Number(defaultValueRaw) : undefined;
982
+ const interpolationMethod = (getAttr(el, 'interpolationMethod') || 'linear').trim();
983
+ return {
984
+ kind: 'table.interpolationTable',
985
+ defaultValue: Number.isFinite(defaultValue) ? defaultValue : undefined,
986
+ interpolationMethod,
987
+ entries: findDescendants(el, this.mapper.toNative('interpolationtableentry'))
988
+ .map((e) => ({
989
+ sourceValue: Number((getAttr(e, 'sourceValue') || '').trim()),
990
+ targetValue: Number((getAttr(e, 'targetValue') || '').trim()),
991
+ }))
992
+ .filter((e) => Number.isFinite(e.sourceValue) && Number.isFinite(e.targetValue)),
993
+ };
994
+ }
995
+ ensureBuiltinDeclarations(decls) {
996
+ // completionStatus + numAttempts are defined in QTI (esp. adaptive items) and commonly used
997
+ // without explicit outcomeDeclaration in authoring content.
998
+ if (!decls.completionStatus) {
999
+ decls.completionStatus = {
1000
+ identifier: 'completionStatus',
1001
+ baseType: 'identifier',
1002
+ cardinality: 'single',
1003
+ value: qtiValue('identifier', 'single', 'not_attempted'),
1004
+ isTemplate: false,
1005
+ // @ts-expect-error internal marker
1006
+ __kind: 'outcome',
1007
+ };
1008
+ }
1009
+ if (!decls.numAttempts) {
1010
+ decls.numAttempts = {
1011
+ identifier: 'numAttempts',
1012
+ baseType: 'integer',
1013
+ cardinality: 'single',
1014
+ value: qtiValue('integer', 'single', 0),
1015
+ isTemplate: false,
1016
+ // @ts-expect-error internal marker
1017
+ __kind: 'outcome',
1018
+ };
1019
+ }
1020
+ // Common scoring defaults
1021
+ if (!decls.SCORE) {
1022
+ decls.SCORE = {
1023
+ identifier: 'SCORE',
1024
+ baseType: 'float',
1025
+ cardinality: 'single',
1026
+ value: qtiValue('float', 'single', 0),
1027
+ isTemplate: false,
1028
+ // @ts-expect-error internal marker
1029
+ __kind: 'outcome',
1030
+ };
1031
+ }
1032
+ if (!decls.MAXSCORE) {
1033
+ decls.MAXSCORE = {
1034
+ identifier: 'MAXSCORE',
1035
+ baseType: 'float',
1036
+ cardinality: 'single',
1037
+ value: qtiValue('float', 'single', 1),
1038
+ isTemplate: false,
1039
+ // @ts-expect-error internal marker
1040
+ __kind: 'outcome',
1041
+ };
1042
+ }
1043
+ }
1044
+ applySessionState(state) {
1045
+ for (const [id, raw] of Object.entries(state)) {
1046
+ const d = this.decls[id];
1047
+ if (!d)
1048
+ continue;
1049
+ d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw);
1050
+ }
1051
+ }
1052
+ parseDefaultValue(declEl, baseType, cardinality) {
1053
+ const defaultEl = findFirstDescendant(declEl, this.mapper.toNative('defaultvalue'));
1054
+ if (!defaultEl)
1055
+ return qtiNull(baseType, cardinality);
1056
+ const values = findDescendants(defaultEl, this.mapper.toNative('value')).map((v) => (v.textContent || '').trim());
1057
+ if (cardinality === 'multiple' || cardinality === 'ordered') {
1058
+ return qtiValue(baseType, cardinality, values.map((t) => {
1059
+ const v = coerceBaseValue(baseType, t);
1060
+ return v.kind === 'value' ? v.value : null;
1061
+ }));
1062
+ }
1063
+ return coerceBaseValue(baseType, values[0] ?? '');
1064
+ }
1065
+ parseCorrectResponse(correctEl, baseType, cardinality) {
1066
+ const values = findDescendants(correctEl, this.mapper.toNative('value')).map((v) => (v.textContent || '').trim());
1067
+ if (cardinality === 'multiple' || cardinality === 'ordered') {
1068
+ return qtiValue(baseType, cardinality, values.map((t) => {
1069
+ const v = coerceBaseValue(baseType, t);
1070
+ return v.kind === 'value' ? v.value : null;
1071
+ }));
1072
+ }
1073
+ return coerceBaseValue(baseType, values[0] ?? '');
1074
+ }
1075
+ parseMapping(mappingEl, baseType) {
1076
+ const defaultValue = Number(this.getAttrMapped(mappingEl, 'defaultValue') || 0);
1077
+ const lowerBound = this.getAttrMapped(mappingEl, 'lowerBound') ? Number(this.getAttrMapped(mappingEl, 'lowerBound')) : undefined;
1078
+ const upperBound = this.getAttrMapped(mappingEl, 'upperBound') ? Number(this.getAttrMapped(mappingEl, 'upperBound')) : undefined;
1079
+ const mappingCaseSensitive = this.getAttrMapped(mappingEl, 'caseSensitive') || 'true';
1080
+ const entries = {};
1081
+ const normalizePairKey = (k) => {
1082
+ const parts = k.trim().split(/\s+/).filter(Boolean);
1083
+ if (parts.length === 2)
1084
+ return [...parts].sort().join(' ');
1085
+ return k.trim();
1086
+ };
1087
+ const normalizeDirectedPairKey = (k) => {
1088
+ const parts = k.trim().split(/\s+/).filter(Boolean);
1089
+ if (parts.length >= 2)
1090
+ return `${parts[0]} ${parts[1]}`;
1091
+ return k.trim();
1092
+ };
1093
+ for (const e of findDescendants(mappingEl, this.mapper.toNative('mapentry'))) {
1094
+ const mapKey = this.getAttrMapped(e, 'mapKey');
1095
+ const mappedValue = this.getAttrMapped(e, 'mappedValue');
1096
+ if (!mapKey || mappedValue === null)
1097
+ continue;
1098
+ const effectiveCaseSensitive = this.getAttrMapped(e, 'caseSensitive') || mappingCaseSensitive || 'true';
1099
+ const storedKey = baseType === 'pair'
1100
+ ? normalizePairKey(mapKey)
1101
+ : baseType === 'directedPair'
1102
+ ? normalizeDirectedPairKey(mapKey)
1103
+ : mapKey;
1104
+ entries[storedKey] = { mapKey: storedKey, mappedValue: Number(mappedValue), caseSensitive: effectiveCaseSensitive };
1105
+ if (effectiveCaseSensitive !== 'true') {
1106
+ const lowerKey = storedKey.toLowerCase();
1107
+ entries[lowerKey] = {
1108
+ mapKey: lowerKey,
1109
+ mappedValue: Number(mappedValue),
1110
+ caseSensitive: effectiveCaseSensitive,
1111
+ };
1112
+ }
1113
+ }
1114
+ return { defaultValue, lowerBound, upperBound, caseSensitive: mappingCaseSensitive, entries };
1115
+ }
1116
+ parseAreaMapping(areaMappingEl) {
1117
+ const defaultValue = Number(getAttr(areaMappingEl, 'defaultValue') || 0);
1118
+ const lowerBound = getAttr(areaMappingEl, 'lowerBound')
1119
+ ? Number(getAttr(areaMappingEl, 'lowerBound'))
1120
+ : undefined;
1121
+ const upperBound = getAttr(areaMappingEl, 'upperBound')
1122
+ ? Number(getAttr(areaMappingEl, 'upperBound'))
1123
+ : undefined;
1124
+ const entries = [];
1125
+ for (const e of findDescendants(areaMappingEl, this.mapper.toNative('areamapentry'))) {
1126
+ const shape = (getAttr(e, 'shape') || 'default');
1127
+ const coords = String(getAttr(e, 'coords') || '');
1128
+ const mappedValue = Number(getAttr(e, 'mappedValue') || 0);
1129
+ entries.push({ shape, coords, mappedValue });
1130
+ }
1131
+ return { defaultValue, lowerBound, upperBound, entries };
1132
+ }
1133
+ coerceToDeclarationValue(baseType, cardinality, raw) {
1134
+ if (raw === null || raw === undefined)
1135
+ return qtiNull(baseType, cardinality);
1136
+ // Allow callers to pass fully-formed QtiValue (e.g. session restore).
1137
+ if (typeof raw === 'object' && raw && 'kind' in raw) {
1138
+ return raw;
1139
+ }
1140
+ // For file types, preserve QTIFileResponse objects directly
1141
+ if (baseType === 'file') {
1142
+ if (cardinality === 'multiple' || cardinality === 'ordered') {
1143
+ const arr = Array.isArray(raw) ? raw : [raw];
1144
+ // For file types, preserve objects (QTIFileResponse) directly
1145
+ return qtiValue(baseType, cardinality, arr.filter((v) => v !== null && v !== undefined));
1146
+ }
1147
+ // For single file, preserve the object directly
1148
+ return qtiValue(baseType, cardinality, raw);
1149
+ }
1150
+ if (cardinality === 'multiple' || cardinality === 'ordered') {
1151
+ const arr = Array.isArray(raw) ? raw : [raw];
1152
+ const coerced = arr
1153
+ .map((v) => String(v ?? '').trim())
1154
+ .filter((s) => s.length > 0)
1155
+ .map((t) => {
1156
+ const v = coerceBaseValue(baseType, t);
1157
+ return v.kind === 'value' ? v.value : null;
1158
+ })
1159
+ .filter((v) => v !== null);
1160
+ // Multiple/ordered can legitimately be an empty container (distinct from null).
1161
+ return qtiValue(baseType, cardinality, coerced);
1162
+ }
1163
+ const t = String(raw ?? '').trim();
1164
+ if (t.length === 0)
1165
+ return qtiNull(baseType, cardinality);
1166
+ return coerceBaseValue(baseType, t);
1167
+ }
1168
+ collectOutcomes() {
1169
+ const out = {};
1170
+ for (const d of Object.values(this.decls)) {
1171
+ if (d.__kind !== 'outcome')
1172
+ continue;
1173
+ if (d.value.kind === 'value')
1174
+ out[d.identifier] = d.value.value;
1175
+ else if (d.value.kind === 'null')
1176
+ out[d.identifier] = null;
1177
+ }
1178
+ // Ensure MAXSCORE always has a value (fallback to 1.0 if null or missing)
1179
+ if (out.MAXSCORE === null || out.MAXSCORE === undefined) {
1180
+ out.MAXSCORE = 1.0;
1181
+ }
1182
+ return out;
1183
+ }
1184
+ // ----------------------------------------------------------------------------
1185
+ // printedVariable + feedback
1186
+ // ----------------------------------------------------------------------------
1187
+ renderPrintedVariables(html) {
1188
+ const readIdentifier = (attrs) => {
1189
+ const m = attrs.match(/identifier\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))/i);
1190
+ return (m?.[1] || m?.[2] || m?.[3] || '').trim() || null;
1191
+ };
1192
+ const renderId = (id) => {
1193
+ if (!id)
1194
+ return '';
1195
+ const v = this.ctx.getValue(id);
1196
+ if (v.kind !== 'value')
1197
+ return '';
1198
+ if (Array.isArray(v.value))
1199
+ return v.value.map(String).join(', ');
1200
+ return String(v.value);
1201
+ };
1202
+ let out = html.replace(/<printedVariable\b([^>]*)>([\s\S]*?)<\/printedVariable>/gi, (_m, attrs) => renderId(readIdentifier(String(attrs))));
1203
+ out = out.replace(/<printedVariable\b([^>]*)\/>/gi, (_m, attrs) => renderId(readIdentifier(String(attrs))));
1204
+ return out;
1205
+ }
1206
+ getModalFeedback(outcomes) {
1207
+ const feedbackEls = findDescendants(this.assessmentItem, this.mapper.toNative('modalfeedback'));
1208
+ const active = [];
1209
+ for (const el of feedbackEls) {
1210
+ const identifier = getAttr(el, 'identifier') || '';
1211
+ const outcomeIdentifier = getAttr(el, 'outcomeIdentifier') || '';
1212
+ const showHide = (getAttr(el, 'showHide') || 'show');
1213
+ const title = getAttr(el, 'title') || undefined;
1214
+ const contentRaw = childElements(el).map((c) => serializeXml(c)).join('') || (el.textContent || '');
1215
+ const sanitized = sanitizeHtml(contentRaw, { security: this.config.security });
1216
+ const content = toTrustedHtml(sanitized, this.config.security?.trustedTypesPolicyName);
1217
+ const outcomeValue = outcomes[outcomeIdentifier];
1218
+ const shouldShow = showHide === 'show' ? outcomeValue === identifier : outcomeValue !== identifier;
1219
+ if (shouldShow && content) {
1220
+ active.push({ identifier, outcomeIdentifier, showHide, content, title });
1221
+ }
1222
+ }
1223
+ return active;
1224
+ }
1225
+ }
1226
+ // ---------------------------------------------------------------------------
1227
+ // Module-level helpers
1228
+ // ---------------------------------------------------------------------------
1229
+ function mergePnp(base, partial) {
1230
+ return {
1231
+ display: { ...(base?.display ?? {}), ...(partial.display ?? {}) },
1232
+ content: { ...(base?.content ?? {}), ...(partial.content ?? {}) },
1233
+ cognitive: { ...(base?.cognitive ?? {}), ...(partial.cognitive ?? {}) },
1234
+ };
1235
+ }