@pie-qti/item-player 1.0.0-beta.4 → 1.0.0-beta.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 (294) hide show
  1. package/README.md +33 -5
  2. package/dist/catalog/applyGlossaryTriggers.js +14 -2
  3. package/dist/catalog/applyGlossaryTriggers.js.map +1 -1
  4. package/dist/catalog/catalogExtractor.js +2 -4
  5. package/dist/catalog/catalogExtractor.js.map +1 -1
  6. package/dist/catalog/sessionCatalog.d.ts +46 -0
  7. package/dist/catalog/sessionCatalog.js +87 -0
  8. package/dist/catalog/sessionCatalog.js.map +1 -0
  9. package/dist/components/utils/endAttempt.d.ts +16 -0
  10. package/dist/components/utils/endAttempt.js +28 -0
  11. package/dist/components/utils/endAttempt.js.map +1 -0
  12. package/dist/components/utils/focus.d.ts +19 -0
  13. package/dist/components/utils/focus.js +67 -0
  14. package/dist/components/utils/focus.js.map +1 -0
  15. package/dist/components/utils/itemBodyRenderer.d.ts +44 -0
  16. package/dist/components/utils/itemBodyRenderer.js +177 -0
  17. package/dist/components/utils/itemBodyRenderer.js.map +1 -0
  18. package/dist/components/utils/sentenceContext.d.ts +6 -0
  19. package/dist/components/utils/sentenceContext.js +16 -0
  20. package/dist/components/utils/sentenceContext.js.map +1 -0
  21. package/dist/core/AssessmentItemDefinition.d.ts +20 -1
  22. package/dist/core/AssessmentItemDefinition.js +12 -31
  23. package/dist/core/AssessmentItemDefinition.js.map +1 -1
  24. package/dist/core/ComponentRegistry.d.ts +92 -0
  25. package/dist/core/ComponentRegistry.js +7 -1
  26. package/dist/core/ComponentRegistry.js.map +1 -1
  27. package/dist/core/ItemSession.d.ts +18 -1
  28. package/dist/core/ItemSession.js +79 -41
  29. package/dist/core/ItemSession.js.map +1 -1
  30. package/dist/core/Player.d.ts +118 -141
  31. package/dist/core/Player.js +387 -1233
  32. package/dist/core/Player.js.map +1 -1
  33. package/dist/core/compliance.d.ts +72 -0
  34. package/dist/core/compliance.js +147 -0
  35. package/dist/core/compliance.js.map +1 -0
  36. package/dist/core/declarations/declarationBuilder.d.ts +29 -0
  37. package/dist/core/declarations/declarationBuilder.js +284 -0
  38. package/dist/core/declarations/declarationBuilder.js.map +1 -0
  39. package/dist/core/declarations/declarationValues.d.ts +11 -0
  40. package/dist/core/declarations/declarationValues.js +168 -0
  41. package/dist/core/declarations/declarationValues.js.map +1 -0
  42. package/dist/core/matchGroups.d.ts +36 -0
  43. package/dist/core/matchGroups.js +100 -0
  44. package/dist/core/matchGroups.js.map +1 -0
  45. package/dist/core/nameMappers.d.ts +35 -0
  46. package/dist/core/nameMappers.js +47 -0
  47. package/dist/core/nameMappers.js.map +1 -0
  48. package/dist/core/parsingLimits.d.ts +4 -0
  49. package/dist/core/parsingLimits.js +5 -2
  50. package/dist/core/parsingLimits.js.map +1 -1
  51. package/dist/core/processing/responseProcessing.d.ts +88 -0
  52. package/dist/core/processing/responseProcessing.js +317 -0
  53. package/dist/core/processing/responseProcessing.js.map +1 -0
  54. package/dist/core/processing/responseValidation.d.ts +55 -0
  55. package/dist/core/processing/responseValidation.js +335 -0
  56. package/dist/core/processing/responseValidation.js.map +1 -0
  57. package/dist/core/rendering/contentPass.d.ts +31 -0
  58. package/dist/core/rendering/contentPass.js +152 -0
  59. package/dist/core/rendering/contentPass.js.map +1 -0
  60. package/dist/core/rendering/htmlRender.d.ts +21 -0
  61. package/dist/core/rendering/htmlRender.js +56 -0
  62. package/dist/core/rendering/htmlRender.js.map +1 -0
  63. package/dist/core/responseProcessingTemplates.d.ts +23 -0
  64. package/dist/core/responseProcessingTemplates.js +45 -0
  65. package/dist/core/responseProcessingTemplates.js.map +1 -0
  66. package/dist/core/rolePolicy.d.ts +5 -0
  67. package/dist/core/rolePolicy.js +21 -0
  68. package/dist/core/rolePolicy.js.map +1 -1
  69. package/dist/core/sanitizer.js +8 -14
  70. package/dist/core/sanitizer.js.map +1 -1
  71. package/dist/core/serialization/sessionState.d.ts +56 -0
  72. package/dist/core/serialization/sessionState.js +139 -0
  73. package/dist/core/serialization/sessionState.js.map +1 -0
  74. package/dist/core/serialization/valueForms.d.ts +32 -0
  75. package/dist/core/serialization/valueForms.js +112 -0
  76. package/dist/core/serialization/valueForms.js.map +1 -0
  77. package/dist/document/AssessmentItemDocument.d.ts +27 -1
  78. package/dist/document/AssessmentItemDocument.js +67 -31
  79. package/dist/document/AssessmentItemDocument.js.map +1 -1
  80. package/dist/element-class-BbF4Dj7F.js +3773 -0
  81. package/dist/element-class-BbF4Dj7F.js.map +1 -0
  82. package/dist/element-class.d.ts +34 -1
  83. package/dist/element-class.js +1 -1
  84. package/dist/element.js +1 -1
  85. package/dist/extraction/ExtractionRegistry.js +6 -12
  86. package/dist/extraction/ExtractionRegistry.js.map +1 -1
  87. package/dist/extraction/createContext.d.ts +2 -2
  88. package/dist/extraction/createContext.js.map +1 -1
  89. package/dist/extraction/index.d.ts +2 -2
  90. package/dist/extraction/index.js +1 -1
  91. package/dist/extraction/index.js.map +1 -1
  92. package/dist/extraction/interactionCoverage.d.ts +31 -0
  93. package/dist/extraction/interactionCoverage.js +40 -0
  94. package/dist/extraction/interactionCoverage.js.map +1 -0
  95. package/dist/extraction/interactionExtractionPipeline.js +5 -10
  96. package/dist/extraction/interactionExtractionPipeline.js.map +1 -1
  97. package/dist/extraction/interactionSecurity.js +1 -28
  98. package/dist/extraction/interactionSecurity.js.map +1 -1
  99. package/dist/extraction/mergeDeliveryFields.d.ts +13 -0
  100. package/dist/extraction/mergeDeliveryFields.js +17 -0
  101. package/dist/extraction/mergeDeliveryFields.js.map +1 -0
  102. package/dist/extraction/responseIdentifier.d.ts +19 -0
  103. package/dist/extraction/responseIdentifier.js +29 -0
  104. package/dist/extraction/responseIdentifier.js.map +1 -0
  105. package/dist/extraction/types.d.ts +11 -18
  106. package/dist/extraction/types.js +0 -12
  107. package/dist/extraction/types.js.map +1 -1
  108. package/dist/extraction/utils.d.ts +14 -0
  109. package/dist/extraction/utils.js +35 -5
  110. package/dist/extraction/utils.js.map +1 -1
  111. package/dist/index.d.ts +16 -10
  112. package/dist/index.js +19 -8
  113. package/dist/index.js.map +1 -1
  114. package/dist/interactions/associate/extractor.d.ts +1 -0
  115. package/dist/interactions/associate/extractor.js +10 -12
  116. package/dist/interactions/associate/extractor.js.map +1 -1
  117. package/dist/interactions/choice/extractor.js +6 -13
  118. package/dist/interactions/choice/extractor.js.map +1 -1
  119. package/dist/interactions/drawing/extractor.d.ts +6 -0
  120. package/dist/interactions/drawing/extractor.js +30 -9
  121. package/dist/interactions/drawing/extractor.js.map +1 -1
  122. package/dist/interactions/end-attempt/extractor.js +2 -1
  123. package/dist/interactions/end-attempt/extractor.js.map +1 -1
  124. package/dist/interactions/extended-text/extractor.d.ts +6 -1
  125. package/dist/interactions/extended-text/extractor.js +10 -5
  126. package/dist/interactions/extended-text/extractor.js.map +1 -1
  127. package/dist/interactions/extended-text/response.js +18 -18
  128. package/dist/interactions/extended-text/response.js.map +1 -1
  129. package/dist/interactions/gap-match/extractor.d.ts +40 -2
  130. package/dist/interactions/gap-match/extractor.js +197 -39
  131. package/dist/interactions/gap-match/extractor.js.map +1 -1
  132. package/dist/interactions/graphic-associate/extractor.d.ts +11 -0
  133. package/dist/interactions/graphic-associate/extractor.js +35 -24
  134. package/dist/interactions/graphic-associate/extractor.js.map +1 -1
  135. package/dist/interactions/graphic-gap-match/extractor.d.ts +21 -0
  136. package/dist/interactions/graphic-gap-match/extractor.js +79 -43
  137. package/dist/interactions/graphic-gap-match/extractor.js.map +1 -1
  138. package/dist/interactions/graphic-order/extractor.d.ts +15 -0
  139. package/dist/interactions/graphic-order/extractor.js +39 -24
  140. package/dist/interactions/graphic-order/extractor.js.map +1 -1
  141. package/dist/interactions/hotspot/extractor.d.ts +6 -0
  142. package/dist/interactions/hotspot/extractor.js +31 -16
  143. package/dist/interactions/hotspot/extractor.js.map +1 -1
  144. package/dist/interactions/hottext/extractor.js +2 -12
  145. package/dist/interactions/hottext/extractor.js.map +1 -1
  146. package/dist/interactions/inline/accessibleName.d.ts +29 -0
  147. package/dist/interactions/inline/accessibleName.js +35 -0
  148. package/dist/interactions/inline/accessibleName.js.map +1 -0
  149. package/dist/interactions/inline/render-plan.d.ts +5 -14
  150. package/dist/interactions/inline/render-plan.js +5 -56
  151. package/dist/interactions/inline/render-plan.js.map +1 -1
  152. package/dist/interactions/inline-choice/extractor.d.ts +4 -0
  153. package/dist/interactions/inline-choice/extractor.js +13 -12
  154. package/dist/interactions/inline-choice/extractor.js.map +1 -1
  155. package/dist/interactions/match/extractor.d.ts +2 -0
  156. package/dist/interactions/match/extractor.js +14 -28
  157. package/dist/interactions/match/extractor.js.map +1 -1
  158. package/dist/interactions/media/extractor.d.ts +5 -11
  159. package/dist/interactions/media/extractor.js +100 -36
  160. package/dist/interactions/media/extractor.js.map +1 -1
  161. package/dist/interactions/modules.js +8 -2
  162. package/dist/interactions/modules.js.map +1 -1
  163. package/dist/interactions/order/extractor.d.ts +2 -0
  164. package/dist/interactions/order/extractor.js +8 -12
  165. package/dist/interactions/order/extractor.js.map +1 -1
  166. package/dist/interactions/order/limits.d.ts +29 -0
  167. package/dist/interactions/order/limits.js +28 -0
  168. package/dist/interactions/order/limits.js.map +1 -0
  169. package/dist/interactions/portable-custom/extractor.js +4 -2
  170. package/dist/interactions/portable-custom/extractor.js.map +1 -1
  171. package/dist/interactions/position-object/extractor.d.ts +18 -1
  172. package/dist/interactions/position-object/extractor.js +81 -22
  173. package/dist/interactions/position-object/extractor.js.map +1 -1
  174. package/dist/interactions/select-point/extractor.d.ts +6 -0
  175. package/dist/interactions/select-point/extractor.js +31 -19
  176. package/dist/interactions/select-point/extractor.js.map +1 -1
  177. package/dist/interactions/shared/imageAlt.d.ts +54 -0
  178. package/dist/interactions/shared/imageAlt.js +84 -0
  179. package/dist/interactions/shared/imageAlt.js.map +1 -0
  180. package/dist/interactions/shared/interactionImage.d.ts +32 -0
  181. package/dist/interactions/shared/interactionImage.js +39 -0
  182. package/dist/interactions/shared/interactionImage.js.map +1 -0
  183. package/dist/interactions/shared/specDefaults.d.ts +20 -0
  184. package/dist/interactions/shared/specDefaults.js +25 -0
  185. package/dist/interactions/shared/specDefaults.js.map +1 -0
  186. package/dist/interactions/shared/types.d.ts +212 -40
  187. package/dist/interactions/shared/types.js.map +1 -1
  188. package/dist/interactions/text-entry/extractor.d.ts +9 -0
  189. package/dist/interactions/text-entry/extractor.js +9 -0
  190. package/dist/interactions/text-entry/extractor.js.map +1 -1
  191. package/dist/interactions/text-entry/inlineInputStyle.d.ts +10 -0
  192. package/dist/interactions/text-entry/inlineInputStyle.js +12 -0
  193. package/dist/interactions/text-entry/inlineInputStyle.js.map +1 -0
  194. package/dist/interactions/text-entry/inputMode.d.ts +35 -0
  195. package/dist/interactions/text-entry/inputMode.js +134 -0
  196. package/dist/interactions/text-entry/inputMode.js.map +1 -0
  197. package/dist/interactions/text-entry/response.d.ts +15 -0
  198. package/dist/interactions/text-entry/response.js +25 -0
  199. package/dist/interactions/text-entry/response.js.map +1 -0
  200. package/dist/interactions/upload/extractor.js +2 -2
  201. package/dist/interactions/upload/extractor.js.map +1 -1
  202. package/dist/pci/PciHost.d.ts +1 -1
  203. package/dist/pci/PciHost.js +11 -11
  204. package/dist/pci/PciHost.js.map +1 -1
  205. package/dist/pci/index.d.ts +1 -0
  206. package/dist/pci/index.js.map +1 -1
  207. package/dist/pci/modulePaths.d.ts +16 -0
  208. package/dist/pci/modulePaths.js +33 -0
  209. package/dist/pci/modulePaths.js.map +1 -0
  210. package/dist/pci/pageRealmSession.js +3 -15
  211. package/dist/pci/pageRealmSession.js.map +1 -1
  212. package/dist/pci/qtiVariableJson.d.ts +46 -3
  213. package/dist/pci/qtiVariableJson.js +247 -53
  214. package/dist/pci/qtiVariableJson.js.map +1 -1
  215. package/dist/pci/sandbox/SandboxedPciSession.d.ts +3 -0
  216. package/dist/pci/sandbox/SandboxedPciSession.js +15 -14
  217. package/dist/pci/sandbox/SandboxedPciSession.js.map +1 -1
  218. package/dist/pci/sandbox/iframeConnector.d.ts +18 -4
  219. package/dist/pci/sandbox/iframeConnector.js +35 -6
  220. package/dist/pci/sandbox/iframeConnector.js.map +1 -1
  221. package/dist/pci/sandbox/protocol.d.ts +14 -0
  222. package/dist/pci/sandbox/protocol.js.map +1 -1
  223. package/dist/pci/sessionHosts.d.ts +47 -0
  224. package/dist/pci/sessionHosts.js +66 -0
  225. package/dist/pci/sessionHosts.js.map +1 -0
  226. package/dist/pci/types.d.ts +7 -1
  227. package/dist/pci/types.js.map +1 -1
  228. package/dist/pnp/applyPnp.d.ts +20 -3
  229. package/dist/pnp/applyPnp.js +84 -9
  230. package/dist/pnp/applyPnp.js.map +1 -1
  231. package/dist/pnp/parsePnpXml.js +2 -0
  232. package/dist/pnp/parsePnpXml.js.map +1 -1
  233. package/dist/pnp/types.d.ts +16 -8
  234. package/dist/pnp/types.js.map +1 -1
  235. package/dist/presentation/feedbackAnnouncement.d.ts +56 -0
  236. package/dist/presentation/feedbackAnnouncement.js +150 -0
  237. package/dist/presentation/feedbackAnnouncement.js.map +1 -0
  238. package/dist/presentation/interactionSlots.d.ts +31 -0
  239. package/dist/presentation/interactionSlots.js +101 -0
  240. package/dist/presentation/interactionSlots.js.map +1 -0
  241. package/dist/presentation/itemPresentationPlan.d.ts +69 -6
  242. package/dist/presentation/itemPresentationPlan.js +93 -81
  243. package/dist/presentation/itemPresentationPlan.js.map +1 -1
  244. package/dist/{components/utils → presentation}/stimulusRender.js +3 -12
  245. package/dist/presentation/stimulusRender.js.map +1 -0
  246. package/dist/presentation/stylesheetRender.js.map +1 -0
  247. package/dist/security/escapeHtml.d.ts +15 -0
  248. package/dist/security/escapeHtml.js +22 -0
  249. package/dist/security/escapeHtml.js.map +1 -0
  250. package/dist/security/index.d.ts +1 -0
  251. package/dist/security/index.js +1 -0
  252. package/dist/security/index.js.map +1 -1
  253. package/dist/server.d.ts +8 -1
  254. package/dist/server.js.map +1 -1
  255. package/dist/session-inputs.d.ts +108 -0
  256. package/dist/session-inputs.js +130 -0
  257. package/dist/session-inputs.js.map +1 -0
  258. package/dist/types/index.d.ts +67 -35
  259. package/dist/types/index.js.map +1 -1
  260. package/dist/utils/cloneFreeze.d.ts +52 -0
  261. package/dist/utils/cloneFreeze.js +113 -0
  262. package/dist/utils/cloneFreeze.js.map +1 -0
  263. package/dist/utils/htmlAttributes.d.ts +13 -0
  264. package/dist/utils/htmlAttributes.js +22 -0
  265. package/dist/utils/htmlAttributes.js.map +1 -0
  266. package/dist/web-components/QTIInteractionElement.d.ts +0 -29
  267. package/dist/web-components/QTIInteractionElement.js +0 -32
  268. package/dist/web-components/QTIInteractionElement.js.map +1 -1
  269. package/dist/web-components/index.d.ts +1 -2
  270. package/dist/web-components/index.js +2 -3
  271. package/dist/web-components/index.js.map +1 -1
  272. package/package.json +15 -14
  273. package/dist/components/utils/stimulusRender.js.map +0 -1
  274. package/dist/components/utils/stylesheetRender.js.map +0 -1
  275. package/dist/core/constants.d.ts +0 -65
  276. package/dist/core/constants.js +0 -74
  277. package/dist/core/constants.js.map +0 -1
  278. package/dist/element-class-DdpiTalY.js +0 -9226
  279. package/dist/element-class-DdpiTalY.js.map +0 -1
  280. package/dist/extensions/MathLiveEditor.d.ts +0 -31
  281. package/dist/extensions/MathLiveEditor.js +0 -248
  282. package/dist/extensions/MathLiveEditor.js.map +0 -1
  283. package/dist/utils/PerformanceMonitor.d.ts +0 -169
  284. package/dist/utils/PerformanceMonitor.js +0 -243
  285. package/dist/utils/PerformanceMonitor.js.map +0 -1
  286. package/dist/utils/responseUtils.d.ts +0 -15
  287. package/dist/utils/responseUtils.js +0 -46
  288. package/dist/utils/responseUtils.js.map +0 -1
  289. package/dist/web-components/QTIInteractionBase.d.ts +0 -119
  290. package/dist/web-components/QTIInteractionBase.js +0 -244
  291. package/dist/web-components/QTIInteractionBase.js.map +0 -1
  292. /package/dist/{components/utils → presentation}/stimulusRender.d.ts +0 -0
  293. /package/dist/{components/utils → presentation}/stylesheetRender.d.ts +0 -0
  294. /package/dist/{components/utils → presentation}/stylesheetRender.js +0 -0
@@ -1,35 +1,31 @@
1
- import { buildOutcomeProcessingAst, buildResponseProcessingAst, buildTemplateProcessingAst, coerceBaseValue, DeclarationContext, evalExpr, execProgram, findDescendants, findFirstDescendant, getAttr, OperatorRegistry, qtiNull, qtiValue, toBoolean, toNumber, toStringValue, } from '@pie-qti/qti-processing';
1
+ import { buildOutcomeProcessingAst, buildResponseProcessingAst, buildTemplateProcessingAst, DeclarationContext, findAssessmentItem, parseXml, qtiValue, toBoolean, toNumber, toStringValue, } from '@pie-qti/qti-processing';
2
2
  import { prepareContentMarkup } from '@pie-qti/qti-common/accessibility';
3
3
  import { DefaultI18nProvider } from '@pie-qti/i18n';
4
- import { Qti2xElementNameMapper, Qti2xAttributeNameMapper, Qti3ElementNameMapper, Qti3AttributeNameMapper, detectQtiVersion, isShownByIdentifier, } from '@pie-qti/qti-common';
4
+ import { detectQtiVersion, detectQtiVersionDetailed, } from '@pie-qti/qti-common';
5
5
  import { parseAssessmentItemDocument } from '../document/AssessmentItemDocument.js';
6
- import { printVariable, readPrintedVariableOptions } from '../document/printedVariable.js';
7
6
  import { createExtractionRegistry, registerFrameworkDeliveryFields, } from '../extraction/ExtractionRegistry.js';
8
7
  import { extractInteractionData } from '../extraction/interactionExtractionPipeline.js';
9
8
  import { getStandardInteractionModules } from '../interactions/modules.js';
10
9
  import { createComponentRegistry } from './ComponentRegistry.js';
10
+ import { collectItemDiagnostics, reportItemDiagnostics } from './compliance.js';
11
+ import { readMatchGroupConstraints } from './matchGroups.js';
11
12
  import { createSeededRng } from './random.js';
12
13
  import { sanitizeHtml } from './sanitizer.js';
13
- import { toTrustedHtml } from './trustedTypes.js';
14
- import { sanitizeResourceUrl } from './urlPolicy.js';
15
14
  import { enforceItemXmlLimits } from './parsingLimits.js';
16
15
  import { applyPnpToRoot } from '../pnp/applyPnp.js';
17
- import { extractCatalog, extractCatalogFromItemXml, mergeCatalogs } from '../catalog/catalogExtractor.js';
18
- import { getCatalogEntryWithAliases } from '../catalog/catalogLookup.js';
19
- import { PciHost } from '../pci/PciHost.js';
20
- import { createExtendedTextNumericRecord, EXTENDED_TEXT_RECORD_FIELD_TYPES, } from '../interactions/extended-text/response.js';
21
- /** Choices a template variable can show or hide, by canonical name. */
22
- const TEMPLATE_CHOICES = [
23
- 'simplechoice',
24
- 'simpleassociablechoice',
25
- 'gaptext',
26
- 'gapimg',
27
- 'gap',
28
- 'hottext',
29
- 'inlinechoice',
30
- 'hotspotchoice',
31
- 'associablehotspot',
32
- ];
16
+ import { buildSessionCatalogIndexes, catalogEntryOf } from '../catalog/sessionCatalog.js';
17
+ import { cloneValue } from '../utils/cloneFreeze.js';
18
+ import { attributeNameMapperForVersion, elementNameMapperForVersion } from './nameMappers.js';
19
+ import { contentHandlers } from './rendering/contentPass.js';
20
+ import { itemBodyHtml, modalFeedbackOf, rubricsOf } from './rendering/htmlRender.js';
21
+ import { applySerializedVariables, freezeDuration, isContextSerialized, serializeItemSession, updateDuration, } from './serialization/sessionState.js';
22
+ import { qtiValueEquals, qtiValueToPci, qtiValueToPublic } from './serialization/valueForms.js';
23
+ import { buildDeclarationMap, ensureBuiltinDeclarations, } from './declarations/declarationBuilder.js';
24
+ import { coerceToDeclarationValue } from './declarations/declarationValues.js';
25
+ import { isAttempted, validateAttemptResponses, validateResponses, } from './processing/responseValidation.js';
26
+ import { assertSupportedResponseProcessing, execTemplateProcessingProgram, resetOutcomesToDefault, resetResponsesToDefault, resetTemplatesToDefault, restoreDeclaredTemplateRuleTargets, runResponseProcessing, } from './processing/responseProcessing.js';
27
+ import { PciHostSession } from '../pci/sessionHosts.js';
28
+ import { createTextEntryStringResponse, textEntryStringIdentifier } from '../interactions/text-entry/response.js';
33
29
  /** @internal Used by AssessmentItemDefinition; deliberately absent from the package root API. */
34
30
  export function preparePlayerDefinitionInternal(config) {
35
31
  const compiler = new Player(config, undefined, { compileOnly: true });
@@ -49,18 +45,50 @@ export function createPlayerFromPreparedInternal(config, prepared, skipTemplateP
49
45
  export class Player {
50
46
  constructor(config, prepared, construction = {}) {
51
47
  this.interactionDataCache = null;
52
- /** Template variables declared with `mathVariable`, substituted into MathML. */
48
+ /** Template variables declared with `mathVariable`, substituted into MathML. @internal */
53
49
  this.mathVariableIds = null;
50
+ /** Template variables declared with `paramVariable`, substituted into `<param>` values. @internal */
51
+ this.paramVariableIds = null;
52
+ /** @internal Set once the implied-zero MAXSCORE warning has fired. */
54
53
  this.warnedImpliedZeroMaxScore = false;
54
+ /** @internal Compiled processing programs, shared by the sessions of one definition. */
55
55
  this.responseProcessingProgram = null;
56
+ /** @internal */
56
57
  this.templateProcessingProgram = null;
58
+ /** @internal */
57
59
  this.outcomeProcessingProgram = null;
58
60
  this._catalogIndex = new Map();
59
61
  this._stimulusCatalogIndexes = new Map();
60
- this._pciHosts = new Map();
62
+ /** @internal The PCI hosts of this session, by response identifier. */
63
+ this.pciSession = new PciHostSession();
61
64
  this._pnpChangeListeners = new Set();
65
+ /** @internal The item-session lifecycle stage; action orchestration mutates it. */
62
66
  this.lifecycleStatus = 'initial';
67
+ /**
68
+ * End-attempt responses the candidate turned true since the attempt last ended: the
69
+ * interactions that invoke the next response processing (see settleEndAttemptResponses).
70
+ * @internal Response resets read and clear it through the host.
71
+ */
72
+ this.endAttemptActivations = new Set();
73
+ this.diagnostics = [];
74
+ /** @internal matchGroup constraints of the item's pairing interactions, by response identifier. */
75
+ this.matchGroupConstraints = new Map();
76
+ /** @internal Time on task accumulated before the current clock window. */
63
77
  this.accumulatedDurationMs = 0;
78
+ /** Time on task at the last duration update, in milliseconds. @internal */
79
+ this.durationMs = 0;
80
+ /**
81
+ * Bumped at every change to the session's response values (candidate input, restore,
82
+ * template rules, PCI writes, attempt settlement) and wherever the interaction data
83
+ * regenerates; keys the response-validation memo.
84
+ */
85
+ this.responseRevision = 0;
86
+ this.interactionDataGeneration = 0;
87
+ /** The base validation of the engine's current responses, memoized per revision. */
88
+ this.engineValidationMemo = null;
89
+ /** The last base validation computed for an explicit responses record. */
90
+ this.validationMemo = null;
91
+ this.responseSnapshotState = null;
64
92
  this.config = config;
65
93
  this.itemXml = config.itemXml ?? '';
66
94
  this.role = config.role ?? 'candidate';
@@ -68,34 +96,25 @@ export class Player {
68
96
  this.sessionStartedAt = Date.now();
69
97
  this.rng = config.rng ?? (typeof config.seed === 'number' ? createSeededRng(config.seed) : Math.random);
70
98
  // Resolve QTI-version mappers without mutating caller-owned configuration.
71
- if (prepared) {
72
- this.mapper = prepared.mapper;
73
- }
74
- else if (!config.elementNameMapper) {
75
- const version = detectQtiVersion(this.itemXml);
76
- if (version === '3.0') {
77
- this.mapper = new Qti3ElementNameMapper();
78
- }
79
- else {
80
- this.mapper = new Qti2xElementNameMapper();
81
- }
82
- }
83
- else {
84
- this.mapper = config.elementNameMapper;
85
- }
99
+ // The detected version also drives per-version spec defaults during extraction
100
+ // (e.g. graphicGapMatchInteraction maxAssociations); detect it once, here.
101
+ this.qtiVersion = config.qtiVersion ?? detectQtiVersion(this.itemXml);
102
+ this.mapper =
103
+ prepared?.mapper ??
104
+ config.elementNameMapper ??
105
+ elementNameMapperForVersion(this.qtiVersion);
86
106
  const attributeMapper = prepared?.attributeMapper ??
87
107
  config.attributeNameMapper ??
88
- (this.mapper.version === '3.0'
89
- ? new Qti3AttributeNameMapper()
90
- : new Qti2xAttributeNameMapper());
108
+ attributeNameMapperForVersion(this.mapper.version);
91
109
  this.config = {
92
110
  ...config,
93
111
  elementNameMapper: this.mapper,
94
112
  attributeNameMapper: attributeMapper,
113
+ qtiVersion: this.qtiVersion,
95
114
  };
96
115
  if (prepared) {
97
116
  this.itemDocument = prepared.itemDocument;
98
- this.decls = cloneDeclarationMap(prepared.declarations);
117
+ this.decls = cloneValue(prepared.declarations);
99
118
  }
100
119
  else {
101
120
  // Read-aloud markup: suppression restated as the attribute the PIE tools read, and SSML
@@ -109,14 +128,17 @@ export class Player {
109
128
  attributeNameMapper: attributeMapper,
110
129
  security: this.config.security,
111
130
  });
112
- this.decls = this.buildDeclarations();
113
- this.ensureBuiltinDeclarations(this.decls);
131
+ this.decls = buildDeclarationMap({
132
+ itemDocument: this.itemDocument,
133
+ mapper: this.mapper,
134
+ attributeMapper: this.config.attributeNameMapper,
135
+ });
136
+ ensureBuiltinDeclarations(this.decls);
114
137
  }
115
138
  this.applyContextVariables(config.contextVariables);
116
139
  this.applyTemplateDefaults(config.templateDefaults);
117
- this.sourceDeclarations = cloneDeclarationMap(this.decls);
140
+ this.sourceDeclarations = cloneValue(this.decls);
118
141
  this.ctx = new DeclarationContext(this.decls);
119
- this.ops = new OperatorRegistry();
120
142
  // Extraction + rendering registries (for interaction rendering)
121
143
  // Pass the element name mapper to the extraction registry for QTI version handling
122
144
  this.extractionRegistry =
@@ -155,6 +177,8 @@ export class Player {
155
177
  }
156
178
  const responseProcessing = prepared ? null : this.itemDocument.getProcessingElement('response');
157
179
  this.responseProcessing = prepared?.responseProcessing ?? this.itemDocument.describeResponseProcessing();
180
+ if (!prepared)
181
+ assertSupportedResponseProcessing(this);
158
182
  this.responseProcessingProgram =
159
183
  prepared?.responseProcessingProgram ??
160
184
  (responseProcessing
@@ -166,15 +190,9 @@ export class Player {
166
190
  (outcomeProcessing
167
191
  ? buildOutcomeProcessingAst(outcomeProcessing, processingBuildOptions)
168
192
  : null);
169
- // Detect and log QTI version for compatibility awareness
170
- const detectedVersion = prepared ? null : this.detectQTIVersion();
171
- if (detectedVersion === 'unknown') {
172
- console.warn('[QTI Player] Could not detect QTI version. Assuming QTI 2.2 compatibility.');
173
- }
174
- else if (detectedVersion === '2.0') {
175
- console.warn('[QTI Player] QTI 2.0 detected. Some features may not be fully supported. QTI 2.2 is recommended.');
176
- }
177
- else if (detectedVersion === '2.1') {
193
+ // QTI 2.1 is delivered through the QTI 2.2 code path; other version findings are diagnostics.
194
+ const versionDetection = prepared ? null : detectQtiVersionDetailed(config.itemXml ?? '');
195
+ if (versionDetection?.version === '2.1' && !this.config.strictQtiCompliance?.enabled) {
178
196
  console.info('[QTI Player] QTI 2.1 detected. Using QTI 2.2 compatibility mode with CC2 template support.');
179
197
  }
180
198
  // Store PNP profile for later use (applyPnpToRoot is called once a root element is available).
@@ -189,30 +207,20 @@ export class Player {
189
207
  this._stimulusCatalogIndexes = prepared.stimulusCatalogIndexes;
190
208
  }
191
209
  else {
192
- let mergedCatalog = new Map();
193
- let deliveryItemCatalog = new Map();
194
- for (const source of this.config.deliveryContext?.catalogSources ?? []) {
195
- const sourceCatalog = extractCatalog(source.xml);
196
- if (source.scope === 'stimulus' && source.stimulusIdentifier) {
197
- const existing = this._stimulusCatalogIndexes.get(source.stimulusIdentifier) ?? new Map();
198
- this._stimulusCatalogIndexes.set(source.stimulusIdentifier, mergeCatalogs(existing, sourceCatalog));
199
- }
200
- else if (source.scope === 'package') {
201
- mergedCatalog = mergeCatalogs(mergedCatalog, sourceCatalog);
202
- }
203
- else {
204
- deliveryItemCatalog = mergeCatalogs(deliveryItemCatalog, sourceCatalog);
205
- }
206
- }
207
- if (this.config.catalogXml) {
208
- mergedCatalog = mergeCatalogs(mergedCatalog, extractCatalogFromItemXml(this.config.catalogXml));
209
- }
210
- mergedCatalog = mergeCatalogs(mergedCatalog, extractCatalogFromItemXml(this.itemXml));
211
- this._catalogIndex = mergeCatalogs(mergedCatalog, deliveryItemCatalog);
210
+ const indexes = buildSessionCatalogIndexes({ config: this.config, itemXml: this.itemXml });
211
+ this._catalogIndex = indexes.catalogIndex;
212
+ this._stimulusCatalogIndexes = indexes.stimulusCatalogIndexes;
212
213
  }
213
- // Check strict compliance if enabled
214
- if (!prepared && this.config.strictQtiCompliance?.enabled) {
215
- this.validateStrictCompliance();
214
+ // Checks that read the item as authored, before the content pass: matchGroup constraints, and
215
+ // compliance findings, reported (or rejected, in strict mode) once, when the item compiles.
216
+ if (prepared) {
217
+ this.matchGroupConstraints = prepared.matchGroupConstraints;
218
+ this.diagnostics = prepared.diagnostics;
219
+ }
220
+ else {
221
+ const sourceItem = findAssessmentItem(parseXml(config.itemXml ?? ''));
222
+ this.matchGroupConstraints = readMatchGroupConstraints(sourceItem, this.mapper);
223
+ this.diagnostics = this.compileDiagnostics(config.itemXml ?? '', sourceItem, versionDetection ?? undefined);
216
224
  }
217
225
  }
218
226
  /** @internal Definition compiler capture; parser artifacts remain module-private. */
@@ -226,15 +234,21 @@ export class Player {
226
234
  mapper: this.mapper,
227
235
  attributeMapper: this.config.attributeNameMapper,
228
236
  itemDocument: this.itemDocument,
229
- declarations: cloneDeclarationMap(this.sourceDeclarations),
237
+ declarations: cloneValue(this.sourceDeclarations),
230
238
  responseProcessing: this.responseProcessing,
231
239
  responseProcessingProgram: this.responseProcessingProgram,
232
240
  templateProcessingProgram: this.templateProcessingProgram,
233
241
  outcomeProcessingProgram: this.outcomeProcessingProgram,
234
242
  catalogIndex: this._catalogIndex,
235
243
  stimulusCatalogIndexes: this._stimulusCatalogIndexes,
244
+ diagnostics: this.diagnostics,
245
+ matchGroupConstraints: this.matchGroupConstraints,
236
246
  });
237
247
  }
248
+ /** The item's QTI compliance findings from compilation; empty when it compiled cleanly. */
249
+ getDiagnostics() {
250
+ return this.diagnostics;
251
+ }
238
252
  /**
239
253
  * Apply the PNP profile to a player root element.
240
254
  * Call this once the root DOM element is available (e.g. after mounting).
@@ -280,98 +294,53 @@ export class Player {
280
294
  * Language fallback: exact match → prefix match → no-lang entry → null.
281
295
  */
282
296
  getCatalogEntry(idref, usage, lang, options) {
283
- const stimulusHtml = options?.stimulusIdentifier
284
- ? getCatalogEntryWithAliases(this._stimulusCatalogIndexes.get(options.stimulusIdentifier) ?? new Map(), idref, usage, lang)
285
- : null;
286
- const html = stimulusHtml ?? getCatalogEntryWithAliases(this._catalogIndex, idref, usage, lang);
287
- if (html === null)
288
- return null;
289
- if (looksLikeCatalogUrl(html)) {
290
- return sanitizeResourceUrl(html.trim(), this.config.security?.urlPolicy, 'img');
291
- }
292
- return toTrustedHtml(this.sanitizeHtmlContent(html), this.config.security?.trustedTypesPolicyName);
297
+ return catalogEntryOf({ catalogIndex: this._catalogIndex, stimulusCatalogIndexes: this._stimulusCatalogIndexes }, idref, usage, lang, options, this.config.security);
293
298
  }
294
- /** Sanitize externally resolved item-adjacent HTML before it reaches a rendering sink. */
295
299
  sanitizeHtmlContent(html) {
296
300
  return sanitizeHtml(html, { security: this.config.security });
297
301
  }
298
- /**
299
- * Create a PciHost for an extracted PCI and register it for response tracking.
300
- * The caller is responsible for calling host.load() and
301
- * host.initialize(domNode) once the DOM element is available.
302
- */
303
302
  createPciHost(data) {
304
- const host = new PciHost(data, {
305
- baseUrl: this.config.pci?.baseUrl,
306
- moduleResolver: this.config.pci?.moduleResolver,
307
- sandbox: this.config.pci?.sandbox,
308
- modulePolicy: this.config.pci?.modulePolicy,
309
- responseDeclaration: (() => {
310
- const d = this.decls[data.responseIdentifier];
311
- return d ? { baseType: d.baseType, cardinality: d.cardinality } : undefined;
312
- })(),
313
- status: () => this.pciInteractionStatus(),
303
+ return this.pciSession.create(data, {
304
+ pci: this.config.pci,
305
+ decls: this.decls,
306
+ lifecycleStatus: () => this.lifecycleStatus,
307
+ interactionStatus: () => this.pciInteractionStatus(),
308
+ contentLanguage: () => this.getContentLanguage(),
309
+ coerceToDeclarationValue: (baseType, cardinality, raw, identifier) => this.coerceToDeclarationValue(baseType, cardinality, raw, identifier),
310
+ onResponseApplied: () => {
311
+ // A mounted PCI module reporting its own change is a candidate response change,
312
+ // so the attempt has begun (beginAttempt's spec citation applies).
313
+ this.beginAttempt();
314
+ this.touchResponses();
315
+ },
314
316
  });
315
- // Wire response changes back into the player's declaration context
316
- host.onResponseChange((responseId, value) => {
317
- if (this.lifecycleStatus !== 'initial' && this.lifecycleStatus !== 'interacting')
318
- return;
319
- const d = this.decls[responseId];
320
- if (d) {
321
- d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, value, d.identifier);
322
- }
323
- });
324
- this._pciHosts.set(data.responseIdentifier, host);
325
- return host;
317
+ }
318
+ pciInteractionStatus() {
319
+ if (this.role !== 'candidate')
320
+ return 'review';
321
+ if (this.lifecycleStatus === 'closed')
322
+ return 'closed';
323
+ return 'interacting';
326
324
  }
327
325
  /**
328
326
  * Offer a response value to the PCI identified by responseIdentifier. A
329
327
  * mounted module that has already reported a response keeps it.
330
328
  */
331
329
  offerPciResponse(responseIdentifier, value) {
332
- this._pciHosts.get(responseIdentifier)?.offerResponse(value);
330
+ this.pciSession.offer(responseIdentifier, value);
333
331
  }
334
332
  /**
335
333
  * Authoritatively replace a PCI's response, discarding in-progress candidate
336
334
  * state. Session restore and reset-to-default use this.
337
335
  */
338
336
  restorePciResponse(responseIdentifier, value) {
339
- this._pciHosts.get(responseIdentifier)?.restore(value);
340
- }
341
- /**
342
- * Disable/enable all PCI hosts based on role.
343
- * 'candidate' = enabled; any other role = disabled.
344
- */
345
- syncPciDisabledState() {
346
- const disabled = this.role !== 'candidate';
347
- for (const host of this._pciHosts.values()) {
348
- if (disabled)
349
- host.disable();
350
- else
351
- host.enable();
352
- }
353
- }
354
- /**
355
- * The QTI 3.0 §6.1 interaction status a PCI instantiates with: 'solution' when
356
- * correct responses are exposed, 'review' for non-candidate roles otherwise,
357
- * 'closed' once the attempt finished, 'interacting' while the candidate works.
358
- * Hosts that know better pass their own `status` to the PciHost options.
359
- */
360
- pciInteractionStatus() {
361
- if (this.role !== 'candidate')
362
- return 'review';
363
- if (this.lifecycleStatus === 'closed')
364
- return 'closed';
365
- return 'interacting';
337
+ this.pciSession.restore(responseIdentifier, value);
366
338
  }
367
339
  /**
368
340
  * Destroy all PCI hosts. Call on player teardown.
369
341
  */
370
342
  destroyPciHosts() {
371
- for (const host of this._pciHosts.values()) {
372
- host.destroy();
373
- }
374
- this._pciHosts.clear();
343
+ this.pciSession.destroyAll();
375
344
  }
376
345
  /** Breaking-change API: returns the typed declaration map */
377
346
  getDeclarations() {
@@ -386,7 +355,16 @@ export class Player {
386
355
  * in-progress module state.
387
356
  */
388
357
  setResponses(responses) {
358
+ const endAttemptIds = this.getEndAttemptResponseIdentifiers().filter((id) => id in responses);
359
+ const wasTrue = new Set(endAttemptIds.filter((id) => this.isResponseTrue(id)));
389
360
  this.applyResponses(responses, (id, value) => this.offerPciResponse(id, value));
361
+ for (const id of endAttemptIds) {
362
+ if (!this.isResponseTrue(id))
363
+ this.endAttemptActivations.delete(id);
364
+ else if (!wasTrue.has(id))
365
+ this.endAttemptActivations.add(id);
366
+ }
367
+ this.beginAttempt();
390
368
  }
391
369
  /**
392
370
  * Apply response values authoritatively, discarding in-progress PCI candidate
@@ -394,6 +372,9 @@ export class Player {
394
372
  */
395
373
  restoreResponses(responses) {
396
374
  this.applyResponses(responses, (id, value) => this.restorePciResponse(id, value));
375
+ // A replaced value is the state as it stands, not the candidate activating an interaction.
376
+ for (const id of Object.keys(responses))
377
+ this.endAttemptActivations.delete(id);
397
378
  }
398
379
  applyResponses(responses, applyToPci) {
399
380
  for (const [id, raw] of Object.entries(responses)) {
@@ -401,8 +382,53 @@ export class Player {
401
382
  if (!d)
402
383
  continue;
403
384
  d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw, d.identifier);
404
- applyToPci(id, this.qtiValueToPublic(d.value));
385
+ // Only a response a textEntryInteraction binds can carry a stringIdentifier companion.
386
+ if (this.itemDocument.getTextEntryBase(id) !== undefined)
387
+ this.applyTextEntryStringResponse(id, raw);
388
+ applyToPci(id, this.qtiValueToPci(d.value));
405
389
  }
390
+ this.touchResponses();
391
+ }
392
+ /**
393
+ * QTI ASI §5.2.1 built-in `completionStatus` transitions, as the specification's table names
394
+ * them: `not_attempted` when the item session is registered, `unknown` once the attempt has
395
+ * begun, and `completed` when response processing completes the attempt (the submission of a
396
+ * non-adaptive item; an adaptive item reaches `completed` only through its own response
397
+ * processing rules). This engine begins the attempt when the candidate changes a response
398
+ * (every candidate write goes through setResponses, a mounted PCI reporting its own change
399
+ * included) and when a suspended handoff is activated for interaction; response processing
400
+ * completes it (responseProcessing.ts).
401
+ *
402
+ * Documented reading of an ambiguous edge: `openSession({ responses })` pre-seeds through
403
+ * setResponses, so it counts as the attempt having begun. `restoreResponses` deliberately
404
+ * does not begin an attempt — it replaces saved state ("the state as it stands"), and the
405
+ * restored completionStatus travels with that state.
406
+ */
407
+ beginAttempt() {
408
+ if (this.getCompletionStatus() === 'not_attempted') {
409
+ this.ctx.setValue('completionStatus', qtiValue('identifier', 'single', 'unknown'));
410
+ }
411
+ }
412
+ /** Response values changed: the response snapshot and its memoized validation drop. */
413
+ touchResponses() {
414
+ this.responseRevision += 1;
415
+ this.responseSnapshotState = null;
416
+ this.engineValidationMemo = null;
417
+ }
418
+ /**
419
+ * textEntryInteraction@stringIdentifier (QTI ASI §5.122.3; `string-identifier` in QTI 3.0):
420
+ * writing the text entry's response also writes the response its stringIdentifier names, with
421
+ * the text as entered before the numeric response reads it — "3.50" where the float response
422
+ * is 3.5 — or NULL for an empty field, so response processing can score that lexical form. A
423
+ * stringIdentifier that repeats the response, or names no declared response, is ignored.
424
+ */
425
+ applyTextEntryStringResponse(responseId, raw) {
426
+ const interaction = this.getInteractionData().find((candidate) => candidate.type === 'textEntryInteraction' && candidate.responseId === responseId);
427
+ const stringIdentifier = interaction ? textEntryStringIdentifier(interaction) : undefined;
428
+ const companion = stringIdentifier ? this.decls[stringIdentifier] : undefined;
429
+ if (!interaction || !companion || companion.__kind !== 'response')
430
+ return;
431
+ companion.value = this.coerceToDeclarationValue(companion.baseType, companion.cardinality, createTextEntryStringResponse(raw, interaction), companion.identifier);
406
432
  }
407
433
  /**
408
434
  * Destroy all resources owned by this player instance (PCI modules, etc.).
@@ -420,7 +446,8 @@ export class Player {
420
446
  }
421
447
  restoreItemSession(state) {
422
448
  this.sessionGuid = state.sessionGuid;
423
- this.interactionDataCache = null;
449
+ this.invalidateInteractionData();
450
+ this.endAttemptActivations.clear();
424
451
  this.lifecycleStatus = state.lifecycleStatus;
425
452
  this.accumulatedDurationMs = Math.max(0, Number(state.duration) || 0);
426
453
  this.sessionStartedAt = Date.now();
@@ -428,6 +455,7 @@ export class Player {
428
455
  this.applySerializedVariables(state.outcomeVariables);
429
456
  this.applySerializedVariables(state.templateVariables);
430
457
  this.applySerializedVariables(state.contextVariables);
458
+ this.touchResponses();
431
459
  this.updateDuration();
432
460
  }
433
461
  /** @internal ItemSession uses this to activate a restored delivery handoff. */
@@ -436,18 +464,14 @@ export class Player {
436
464
  }
437
465
  /** @internal ItemSession uses this to resume a suspended delivery handoff. */
438
466
  activateAttempt() {
439
- if (this.lifecycleStatus === 'suspended')
467
+ if (this.lifecycleStatus === 'suspended') {
440
468
  this.lifecycleStatus = 'interacting';
469
+ // Resuming hands the item back to the candidate: the attempt has begun
470
+ // (beginAttempt's spec citation applies), even before a first response change.
471
+ this.beginAttempt();
472
+ }
441
473
  }
442
- suspendAttempt() {
443
- return this.runItemSessionAction({ action: 'suspendAttempt' });
444
- }
445
- endAttempt(options = {}) {
446
- return this.runItemSessionAction({ action: 'endAttempt', ...options });
447
- }
448
- scoreAttempt() {
449
- return this.runItemSessionAction({ action: 'scoreAttempt' });
450
- }
474
+ /** Test seam (paramVariable delivery); sessions dispatch newTemplate through ItemSession. */
451
475
  newTemplate(options = {}) {
452
476
  return this.runItemSessionAction({ action: 'newTemplate', ...options });
453
477
  }
@@ -466,22 +490,29 @@ export class Player {
466
490
  }
467
491
  }
468
492
  runSuspendAttemptAction() {
469
- const validation = this.validateResponses(this.getResponses());
493
+ const validation = this.currentResponsesValidation();
470
494
  this.lifecycleStatus = 'suspended';
471
495
  const sessionState = this.saveItemSession();
472
496
  return this.createItemSessionActionResult('suspendAttempt', sessionState, { validation });
473
497
  }
474
498
  runEndAttemptAction(options) {
475
499
  const validate = options.validateResponses ?? false;
476
- const validation = validate ? this.validateResponses(this.getResponses()) : undefined;
500
+ const validation = validate ? this.validateAttemptResponses(this.responseSnapshot()) : undefined;
477
501
  if (validation && !validation.valid) {
478
502
  return this.createItemSessionActionResult('endAttempt', this.saveItemSession(), { validation });
479
503
  }
504
+ // QTI countAttempt=false (hint / "show me"): response processing runs so outcomes and
505
+ // feedback compute, but the attempt is not counted and the session stays open for the
506
+ // candidate to continue — only a counted attempt finalizes a non-adaptive item.
507
+ const countAttempt = options.countAttempt ?? true;
508
+ // The adaptive path settles the end-attempt responses in runAdaptiveSubmitAttempt.
509
+ if (!this.isAdaptive())
510
+ this.settleEndAttemptResponses();
480
511
  const scoring = this.isAdaptive()
481
- ? this.runAdaptiveSubmitAttempt(options.countAttempt ?? true)
512
+ ? this.runAdaptiveSubmitAttempt(countAttempt)
482
513
  : this.runResponseProcessing({
483
- finalizeNonAdaptiveAttempt: true,
484
- countAttempt: options.countAttempt ?? true,
514
+ finalizeNonAdaptiveAttempt: countAttempt,
515
+ countAttempt,
485
516
  });
486
517
  this.lifecycleStatus = scoring.completed ? 'closed' : 'interacting';
487
518
  return this.createItemSessionActionResult('endAttempt', this.saveItemSession(), {
@@ -498,6 +529,7 @@ export class Player {
498
529
  });
499
530
  }
500
531
  runNewTemplateAction(options) {
532
+ this.restoreDeclaredTemplateRuleTargets();
501
533
  this.resetOutcomesToDefault();
502
534
  if (options.resetResponses ?? true) {
503
535
  this.resetResponsesToDefault();
@@ -535,9 +567,6 @@ export class Player {
535
567
  getSecurityConfig() {
536
568
  return this.config.security;
537
569
  }
538
- getTrustedTypesPolicyName() {
539
- return this.config.security?.trustedTypesPolicyName;
540
- }
541
570
  /**
542
571
  * Get the i18n provider instance
543
572
  * @returns I18nProvider instance
@@ -545,24 +574,6 @@ export class Player {
545
574
  getI18nProvider() {
546
575
  return this.i18nProvider;
547
576
  }
548
- /**
549
- * Get attribute value with QTI version support.
550
- * Tries the attribute mapper's native form first, then falls back to direct lookup.
551
- * @param el - Element to get attribute from
552
- * @param canonicalName - Canonical (lowercase) attribute name
553
- * @returns Attribute value or null
554
- */
555
- getAttrMapped(el, canonicalName) {
556
- // Try mapped attribute name first (e.g., 'mapkey' -> 'map-key' for QTI 3.0)
557
- if (this.config.attributeNameMapper) {
558
- const nativeName = this.config.attributeNameMapper.toNative(canonicalName);
559
- const value = el.getAttribute(nativeName);
560
- if (value !== null)
561
- return value;
562
- }
563
- // Fallback to canonical name (for QTI 2.x compatibility)
564
- return getAttr(el, canonicalName);
565
- }
566
577
  /**
567
578
  * The provider used when the host passes none: English, from the catalog
568
579
  * `@pie-qti/i18n` bundles eagerly.
@@ -571,142 +582,49 @@ export class Player {
571
582
  return new DefaultI18nProvider('en-US');
572
583
  }
573
584
  /**
574
- * Detects the QTI version from the assessmentItem element.
575
- * Checks both namespace URI and version attribute.
576
- *
577
- * @returns QTI version string ('2.0', '2.1', '2.2') or 'unknown'
578
- */
579
- detectQTIVersion() {
580
- return this.itemDocument.detectVersion();
581
- }
582
- /**
583
- * Validates strict QTI 2.2 compliance if enabled in configuration.
584
- * Logs warnings or throws errors based on config settings.
585
+ * The item's QTI compliance findings (see `collectItemDiagnostics`): errors in strict mode,
586
+ * warnings otherwise. Strict mode with `rejectUnknownExtensions` throws a `QtiComplianceError`
587
+ * on any finding; otherwise they are logged unless `logDeviations` is false.
585
588
  */
586
- validateStrictCompliance() {
587
- const config = this.config.strictQtiCompliance;
588
- if (!config?.enabled)
589
- return;
590
- const version = this.detectQTIVersion();
591
- if (version !== '2.2') {
592
- const message = `[QTI Player] Strict compliance enabled but item version is ${version}, not 2.2`;
593
- if (config.rejectUnknownExtensions) {
594
- throw new Error(message);
595
- }
596
- else if (config.logDeviations !== false) {
597
- console.warn(message);
598
- }
599
- }
600
- // Future: Add validation for non-standard elements/attributes
589
+ compileDiagnostics(sourceXml, sourceItem, versionDetection) {
590
+ const compliance = this.config.strictQtiCompliance;
591
+ const strict = compliance?.enabled === true;
592
+ const diagnostics = Object.freeze(collectItemDiagnostics({
593
+ itemXml: sourceXml,
594
+ item: sourceItem,
595
+ versionDetection,
596
+ elementNameMapper: this.mapper,
597
+ extractionRegistry: this.extractionRegistry,
598
+ responseIdentifiers: new Set(Object.values(this.decls)
599
+ .filter((d) => d.__kind === 'response')
600
+ .map((d) => d.identifier)),
601
+ strict,
602
+ }));
603
+ reportItemDiagnostics(diagnostics, {
604
+ itemIdentifier: this.itemDocument.getAssessmentItemAttribute('identifier') ?? undefined,
605
+ reject: strict && compliance?.rejectUnknownExtensions === true,
606
+ log: compliance?.logDeviations !== false,
607
+ });
608
+ return diagnostics;
601
609
  }
602
610
  resetOutcomesToDefault() {
603
- for (const d of Object.values(this.decls)) {
604
- if (d.__kind !== 'outcome')
605
- continue;
606
- // Built-in stateful variables must survive across processing runs.
607
- // They are updated by the runtime (adaptive attempt tracking), not by outcome defaults.
608
- if (d.identifier === 'numAttempts' || d.identifier === 'completionStatus' || d.identifier === 'duration')
609
- continue;
610
- this.ctx.resetToDefault(d.identifier);
611
- }
611
+ resetOutcomesToDefault(this);
612
612
  }
613
613
  resetResponsesToDefault() {
614
- for (const d of Object.values(this.decls)) {
615
- if (d.__kind !== 'response')
616
- continue;
617
- this.ctx.resetToDefault(d.identifier);
618
- this.restorePciResponse(d.identifier, d.value.kind === 'value' ? d.value.value : null);
619
- }
614
+ resetResponsesToDefault(this);
615
+ this.touchResponses();
620
616
  }
621
617
  resetTemplatesToDefault() {
622
- for (const d of Object.values(this.decls)) {
623
- if (!d.isTemplate)
624
- continue;
625
- this.ctx.resetToDefault(d.identifier);
626
- }
618
+ resetTemplatesToDefault(this);
627
619
  }
628
- /**
629
- * A MAXSCORE declared without a <defaultValue> is 0 per the numeric outcome rule, so an item
630
- * that never assigns it scores against a maximum of zero. That is the spec-correct reading of
631
- * under-specified content, and silently substituting 1 would make this engine disagree with a
632
- * conformant one — so surface the authoring gap instead of masking it.
633
- */
634
- warnOnceOnImpliedZeroMaxScore(outcomes) {
635
- if (this.warnedImpliedZeroMaxScore)
636
- return;
637
- if (!this.decls.MAXSCORE?.impliedNumericDefault)
638
- return;
639
- if (outcomes.MAXSCORE !== 0)
640
- return;
641
- this.warnedImpliedZeroMaxScore = true;
642
- console.warn(`[QTI Player] MAXSCORE is 0 for item "${this.itemDocument.getAssessmentItemAttribute('identifier') ?? 'unknown'}": its outcomeDeclaration ` +
643
- 'has no <defaultValue>, so QTI initializes it to 0 and response processing never assigned it. ' +
644
- 'Declare <defaultValue> on the MAXSCORE outcomeDeclaration to score against a real maximum.');
620
+ restoreDeclaredTemplateRuleTargets() {
621
+ restoreDeclaredTemplateRuleTargets(this);
645
622
  }
646
623
  runResponseProcessing(options) {
647
- this.updateDuration();
648
- // Spec-aligned behavior: each processing run starts from outcome defaults.
649
- // This prevents stale outcomes when response/outcome processing doesn't set every variable.
650
- this.resetOutcomesToDefault();
651
- // Execute response processing if present
652
- if (this.responseProcessing.present) {
653
- // If responseProcessing has explicit statements, run the compiled program.
654
- // Otherwise, fall back to template-based processing (responseProcessing@template).
655
- if (this.responseProcessing.hasStatements) {
656
- this.execResponseProcessingProgram();
657
- }
658
- else if (this.responseProcessing.template) {
659
- this.execResponseProcessingTemplate(this.responseProcessing.template);
660
- }
661
- }
662
- // Execute outcome processing if present (runs after responseProcessing)
663
- this.execOutcomeProcessingProgram();
664
- // Compatibility: processResponses() has historically finalized non-adaptive items.
665
- // New scoreAttempt() uses this same engine with finalization disabled.
666
- if (!this.isAdaptive() && options.finalizeNonAdaptiveAttempt) {
667
- this.ctx.setValue('completionStatus', qtiValue('identifier', 'single', 'completed'));
668
- if (options.countAttempt ?? true) {
669
- const currentAttempts = this.getNumAttempts();
670
- this.ctx.setValue('numAttempts', qtiValue('integer', 'single', currentAttempts + 1));
671
- }
672
- }
673
- const outcomes = this.collectOutcomes();
674
- this.warnOnceOnImpliedZeroMaxScore(outcomes);
675
- const score = Number(outcomes.SCORE ?? 0);
676
- const maxScore = Number(outcomes.MAXSCORE ?? 1);
677
- const completionStatus = outcomes.completionStatus ?? 'not_attempted';
678
- const completed = completionStatus === 'completed' || (!this.isAdaptive() && options.finalizeNonAdaptiveAttempt);
679
- return {
680
- score,
681
- maxScore,
682
- completed,
683
- outcomeValues: outcomes,
684
- correct: this.responsesMatchCorrect(),
685
- modalFeedback: this.getModalFeedback(outcomes),
686
- };
687
- }
688
- /**
689
- * QTI item correctness, as test-level `numberCorrect` reads it: every declared response matches
690
- * its correct response. Undefined when the item has no response or one declares no correct
691
- * response.
692
- */
693
- responsesMatchCorrect() {
694
- const responses = Object.values(this.decls).filter((d) => d.__kind === 'response');
695
- if (responses.length === 0 || responses.some((d) => d.correctResponse?.kind !== 'value'))
696
- return undefined;
697
- const env = this.processingEnv();
698
- return responses.every((d) => toBoolean(evalExpr(env, {
699
- kind: 'expr.match',
700
- id: `correct-${d.identifier}`,
701
- a: { kind: 'expr.variable', id: `correct-${d.identifier}-response`, identifier: d.identifier },
702
- b: { kind: 'expr.correct', id: `correct-${d.identifier}-correct`, identifier: d.identifier },
703
- })));
624
+ return runResponseProcessing(this, options);
704
625
  }
705
626
  getItemBodyHtml() {
706
- const inner = this.itemDocument.serializeItemBodyChildren(this.contentHandlers({ feedback: false }));
707
- if (!inner)
708
- return '';
709
- return this.renderHtmlContent(inner);
627
+ return itemBodyHtml(this, this.contentHandlers({ feedback: false }));
710
628
  }
711
629
  /**
712
630
  * Extract rubric blocks for the current role.
@@ -717,30 +635,11 @@ export class Player {
717
635
  * the rendered item body flow.
718
636
  */
719
637
  getRubrics(options = {}) {
720
- const role = this.role;
721
- const rubrics = this.itemDocument.readRubricBlocks(this.contentHandlers());
722
- if (rubrics.length === 0)
723
- return [];
724
- const blocks = [];
725
- for (const rubric of rubrics) {
726
- const { scope } = rubric;
727
- if (options.scope && options.scope !== 'all' && scope !== options.scope)
728
- continue;
729
- const view = [...rubric.view];
730
- // If view is specified, show only when it includes the current role.
731
- if (view.length > 0 && role && !view.includes(role))
732
- continue;
733
- const html = this.renderHtmlContent(rubric.content);
734
- blocks.push({ view, html, scope, use: rubric.use });
735
- }
736
- return blocks;
638
+ return rubricsOf(this, this.contentHandlers(), options);
737
639
  }
738
640
  getComponentRegistry() {
739
641
  return this.componentRegistry;
740
642
  }
741
- getExtractionRegistry() {
742
- return this.extractionRegistry;
743
- }
744
643
  /**
745
644
  * Canonical interaction API (new): extracted, typed interaction data.
746
645
  */
@@ -783,9 +682,61 @@ export class Player {
783
682
  .filter((i) => i.type === 'endAttemptInteraction' && i.countAttempt === false)
784
683
  .map((i) => i.responseIdentifier);
785
684
  }
685
+ getEndAttemptResponseIdentifiers() {
686
+ return this.getInteractions()
687
+ .filter((i) => i.type === 'endAttemptInteraction')
688
+ .map((i) => i.responseIdentifier);
689
+ }
690
+ isResponseTrue(responseIdentifier) {
691
+ return toBoolean(this.ctx.getValue(responseIdentifier));
692
+ }
693
+ /**
694
+ * QTI endAttemptInteraction (QTI 3.0 §5.45): "If the candidate invokes response processing
695
+ * using an end-attempt interaction then the associated response variable is set to true. If
696
+ * response processing is invoked in any other way […] then the associated response variable
697
+ * is set to false. The default value of the response variable is always ignored." The
698
+ * interactions that invoke this attempt's processing are the ones the candidate turned true
699
+ * since the attempt last ended; a value restored with the session invokes nothing. Rescoring
700
+ * (scoreAttempt) replays the last submission and leaves these responses as they are.
701
+ */
702
+ settleEndAttemptResponses() {
703
+ for (const id of this.getEndAttemptResponseIdentifiers()) {
704
+ const d = this.decls[id];
705
+ if (!d)
706
+ continue;
707
+ d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, this.endAttemptActivations.has(id), d.identifier);
708
+ }
709
+ this.endAttemptActivations.clear();
710
+ this.touchResponses();
711
+ }
786
712
  getResponseIdentifiers() {
787
713
  return this.getResponseInteractions().map((i) => i.responseIdentifier);
788
714
  }
715
+ /**
716
+ * Response identifiers the item's content prints live: the `printedVariable` targets of the
717
+ * body and rubric content that are declared responses. Their values are substituted while
718
+ * `getItemBodyHtml()` serializes (the content pass reads the live context), so they are the
719
+ * part of the response state a presentation's markup actually renders — presentation
720
+ * consumers (ItemBody) can key caching on them. The declared response set is fixed per
721
+ * session, so the filtered set is computed once.
722
+ */
723
+ getResponseIdentifiersPrintedInContent() {
724
+ this.printedResponseIdentifiers ?? (this.printedResponseIdentifiers = new Set([...this.itemDocument.printedVariableIdentifiers()].filter((identifier) => this.decls[identifier]?.__kind === 'response')));
725
+ return this.printedResponseIdentifiers;
726
+ }
727
+ /**
728
+ * Context identifiers the item's content prints live: the `printedVariable` targets of the
729
+ * body and rubric content the session reports as context state — the QTI built-ins
730
+ * (`duration`, `numAttempts`, `completionStatus`) and declared context variables. Their
731
+ * values are substituted while `getItemBodyHtml()` serializes (the content pass reads the
732
+ * live context), so they are the part of the context state a presentation's markup actually
733
+ * renders — presentation consumers (ItemBody) can key caching on them. The context
734
+ * declaration set is fixed per session, so the filtered set is computed once.
735
+ */
736
+ getContextIdentifiersPrintedInContent() {
737
+ this.printedContextIdentifiers ?? (this.printedContextIdentifiers = new Set([...this.itemDocument.printedVariableIdentifiers()].filter((identifier) => isContextSerialized(this.decls[identifier]))));
738
+ return this.printedContextIdentifiers;
739
+ }
789
740
  isAdaptive() {
790
741
  return (this.itemDocument.getAssessmentItemAttribute('adaptive') || '').toLowerCase() === 'true';
791
742
  }
@@ -803,6 +754,7 @@ export class Player {
803
754
  if (this.isCompleted()) {
804
755
  throw new Error('Cannot submit: item is already completed');
805
756
  }
757
+ this.settleEndAttemptResponses();
806
758
  // QTI adaptive semantics: numAttempts should reflect the attempt being processed.
807
759
  if (this.isAdaptive() && countAttempt) {
808
760
  const next = this.getNumAttempts() + 1;
@@ -812,7 +764,10 @@ export class Player {
812
764
  this.ctx.setValue('completionStatus', qtiValue('identifier', 'single', 'unknown'));
813
765
  }
814
766
  }
815
- const base = this.processResponses();
767
+ // A non-adaptive item counts (and finalizes) only a counted attempt, as endAttempt does.
768
+ const base = this.isAdaptive()
769
+ ? this.processResponses()
770
+ : this.runResponseProcessing({ finalizeNonAdaptiveAttempt: countAttempt, countAttempt });
816
771
  const completionStatus = this.getCompletionStatus();
817
772
  const completed = completionStatus === 'completed';
818
773
  const canContinue = this.isAdaptive() ? !completed : false;
@@ -829,30 +784,31 @@ export class Player {
829
784
  for (const d of Object.values(this.decls)) {
830
785
  if (d.__kind !== 'response')
831
786
  continue;
832
- const pciHost = this._pciHosts.get(d.identifier);
787
+ const pciHost = this.pciSession.get(d.identifier);
833
788
  if (pciHost) {
789
+ const before = d.value;
834
790
  const currentResponse = pciHost.getResponse();
835
791
  d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, currentResponse, d.identifier);
792
+ // Adopting a different mounted-module response is a response change.
793
+ if (!qtiValueEquals(before, d.value))
794
+ this.touchResponses();
836
795
  }
837
796
  out[d.identifier] = this.qtiValueToPublic(d.value);
838
797
  }
839
798
  return out;
840
799
  }
841
800
  /**
842
- * Get correct response for a specific response identifier
843
- * @param responseId - The response identifier
844
- * @returns The correct response value, or undefined if not available
801
+ * The engine's current responses, stable within one response revision: the serializer and
802
+ * the end-attempt gate read the same record, so their validations memoize together.
803
+ * @internal Serialization reads it through the host.
845
804
  */
846
- getCorrectResponse(responseId) {
847
- const decl = this.decls[responseId];
848
- if (!decl || decl.__kind !== 'response')
849
- return undefined;
850
- const respDecl = decl; // ResponseDeclaration from qti-processing
851
- if (!respDecl.correctResponse)
852
- return undefined;
853
- if (respDecl.correctResponse.kind !== 'value')
854
- return undefined;
855
- return this.qtiValueToPublic(respDecl.correctResponse);
805
+ responseSnapshot() {
806
+ if (this.responseSnapshotState && this.responseSnapshotState.revision === this.responseRevision) {
807
+ return this.responseSnapshotState.responses;
808
+ }
809
+ const responses = this.getResponses();
810
+ this.responseSnapshotState = { revision: this.responseRevision, responses };
811
+ return responses;
856
812
  }
857
813
  /**
858
814
  * Get all correct responses as a map
@@ -870,17 +826,8 @@ export class Player {
870
826
  }
871
827
  return out;
872
828
  }
873
- getTemplateVariables() {
874
- const out = {};
875
- for (const d of Object.values(this.decls)) {
876
- if (!d.isTemplate)
877
- continue;
878
- out[d.identifier] = this.qtiValueToPublic(d.value);
879
- }
880
- return out;
881
- }
882
829
  setTemplateVariables(vars) {
883
- this.interactionDataCache = null;
830
+ this.invalidateInteractionData();
884
831
  for (const [id, raw] of Object.entries(vars)) {
885
832
  const d = this.decls[id];
886
833
  if (!d?.isTemplate)
@@ -888,129 +835,61 @@ export class Player {
888
835
  d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw, d.identifier);
889
836
  }
890
837
  }
891
- getSessionState() {
892
- const out = {};
893
- for (const d of Object.values(this.decls)) {
894
- out[d.identifier] = this.qtiValueToPublic(d.value);
895
- }
896
- return out;
897
- }
898
838
  validateResponses(responses) {
899
- const interactions = this.getInteractions();
900
- const entries = {};
901
- const issues = [];
902
- for (const i of interactions) {
903
- const responseId = i.responseIdentifier;
904
- const decl = this.decls[responseId];
905
- const value = responses[responseId];
906
- const isMeaningfulEntry = (entry) => {
907
- if (entry === null || entry === undefined)
908
- return false;
909
- if (typeof entry !== 'string')
910
- return true;
911
- const comparable = i.type === 'extendedTextInteraction' && i.format === 'xhtml'
912
- ? entry.replace(/<[^>]*>/g, '').replace(/&nbsp;|&#160;/gi, ' ')
913
- : entry;
914
- return comparable.trim().length > 0;
915
- };
916
- const constrainedChoices = [
917
- ...(i.choices ?? []),
918
- ...(i.gapTexts ?? []),
919
- ...(i.gapImages ?? []),
920
- ...(i.sourceSet ?? []),
921
- ...(i.targetSet ?? []),
922
- ...(i.associableHotspots ?? []),
923
- ];
924
- const minimum = Math.max(0, Number(i.minChoices ?? 0), Number(i.minAssociations ?? 0), Number(i.minStrings ?? 0), Number(i.minPlays ?? 0));
925
- const required = i.type !== 'endAttemptInteraction' &&
926
- (minimum > 0 || constrainedChoices.some((choice) => Number(choice.matchMin ?? 0) > 0));
927
- let complete = !required;
928
- if (i.type === 'mediaInteraction' && required) {
929
- const minPlays = Number(i.minPlays || 0);
930
- complete = Number(value || 0) >= minPlays;
931
- }
932
- else if (required) {
933
- if (Array.isArray(value)) {
934
- const nonEmptyValues = value.filter(isMeaningfulEntry);
935
- complete = nonEmptyValues.length > 0;
936
- // Enforce minChoices / minAssociations where applicable
937
- const minChoices = Math.max(Number(i.minChoices ?? 0), Number(i.minAssociations ?? 0), Number(i.minStrings ?? 0));
938
- if (complete && minChoices > 0) {
939
- complete = nonEmptyValues.length >= minChoices;
940
- }
941
- // Enforce matchMin per-choice: each pairing entry "id1 id2" in value must
942
- // appear at least matchMin times for the relevant choice.
943
- // Collect all choice arrays that can carry matchMin across all pairing interaction types.
944
- for (const choice of constrainedChoices) {
945
- const min = Number(choice.matchMin || 0);
946
- if (min > 0) {
947
- const count = value.filter((p) => {
948
- const parts = p.split(' ');
949
- return parts[0] === choice.identifier || parts[1] === choice.identifier;
950
- }).length;
951
- if (count < min) {
952
- complete = false;
953
- break;
954
- }
955
- }
956
- }
957
- }
958
- else if (decl?.cardinality === 'record') {
959
- const stringValue = value && typeof value === 'object'
960
- ? value.stringValue
961
- : undefined;
962
- complete = isMeaningfulEntry(stringValue);
963
- }
964
- else {
965
- complete = isMeaningfulEntry(value);
966
- }
967
- }
968
- const errors = [];
969
- const warnings = [];
970
- if (decl) {
971
- if (decl.cardinality === 'multiple' || decl.cardinality === 'ordered') {
972
- if (!(value === null || value === undefined || Array.isArray(value))) {
973
- errors.push(`Expected an array for ${decl.cardinality} response '${responseId}'`);
974
- }
975
- }
976
- else if (decl.cardinality === 'record') {
977
- if (!(value === null || value === undefined || (typeof value === 'object' && !Array.isArray(value)))) {
978
- errors.push(`Expected an object for record response '${responseId}'`);
979
- }
980
- }
981
- else {
982
- if (Array.isArray(value)) {
983
- errors.push(`Expected a single value for response '${responseId}'`);
984
- }
985
- }
986
- }
987
- if (i.type === 'extendedTextInteraction' &&
988
- Array.isArray(value) &&
989
- Number(i.maxStrings ?? 0) > 0 &&
990
- value.filter(isMeaningfulEntry).length > Number(i.maxStrings)) {
991
- errors.push(`Response '${responseId}' exceeds maxStrings=${i.maxStrings}`);
992
- }
993
- const valid = errors.length === 0;
994
- entries[responseId] = {
995
- responseId,
996
- interactionType: i.type,
997
- required,
998
- complete,
999
- valid,
1000
- errors,
1001
- warnings,
1002
- };
1003
- for (const e of errors) {
1004
- issues.push({
1005
- responseId,
1006
- code: 'invalid_shape',
1007
- message: e,
1008
- severity: 'error',
1009
- });
1010
- }
1011
- }
1012
- const allValid = Object.values(entries).every((e) => e.valid);
1013
- return { valid: allValid, entries, issues };
839
+ const memo = this.validationMemo;
840
+ if (memo &&
841
+ memo.responses === responses &&
842
+ memo.revision === this.responseRevision &&
843
+ memo.generation === this.interactionDataGeneration) {
844
+ return memo.result;
845
+ }
846
+ const result = validateResponses(this, responses);
847
+ this.validationMemo = {
848
+ responses,
849
+ revision: this.responseRevision,
850
+ generation: this.interactionDataGeneration,
851
+ result,
852
+ };
853
+ return result;
854
+ }
855
+ /**
856
+ * The base validation of the engine's current responses, memoized per response revision
857
+ * and interaction-data generation: serialization and the suspend path read it repeatedly
858
+ * at unchanged state. The end-attempt gate (validateAttemptResponses) stays a separate
859
+ * derivation, so its `incomplete` issues never reach the memoized base result.
860
+ */
861
+ currentResponsesValidation() {
862
+ const memo = this.engineValidationMemo;
863
+ if (memo &&
864
+ memo.revision === this.responseRevision &&
865
+ memo.generation === this.interactionDataGeneration) {
866
+ return memo.result;
867
+ }
868
+ const result = this.validateResponses(this.responseSnapshot());
869
+ this.engineValidationMemo = {
870
+ revision: this.responseRevision,
871
+ generation: this.interactionDataGeneration,
872
+ result,
873
+ };
874
+ return result;
875
+ }
876
+ /**
877
+ * The validation `dispatch({ action: 'endAttempt', validateResponses: true })` gates on
878
+ * (QTI ASI §4
879
+ * itemSessionControl validateResponses). An invalid response "does not satisfy the
880
+ * constraints imposed by the interaction": beyond a malformed value or a matchGroup
881
+ * pairing (`validateResponses`), an interaction that requires input — minChoices,
882
+ * minAssociations, minStrings, minPlays, matchMin — rejects an incomplete one. Those
883
+ * entries turn invalid with an `incomplete` issue, so the result reads invalid through
884
+ * the same channel as every other rejection.
885
+ *
886
+ * An item with no response at all is a skip, which allowSkipping governs ("delivery
887
+ * engines must ensure that the candidate can choose to submit no response" when it is
888
+ * true). The item cannot see allowSkipping, so completeness applies only once the
889
+ * candidate has responded and a skip is the caller's decision.
890
+ */
891
+ validateAttemptResponses(responses) {
892
+ return validateAttemptResponses(this, responses);
1014
893
  }
1015
894
  getProgress(responses) {
1016
895
  const v = this.validateResponses(responses);
@@ -1029,230 +908,30 @@ export class Player {
1029
908
  * Used by assessment/session controllers to track "answered" state.
1030
909
  */
1031
910
  isAttempted(responses) {
1032
- for (const i of this.getResponseInteractions()) {
1033
- const id = i.responseIdentifier;
1034
- const v = responses[id];
1035
- const isMeaningful = (entry) => {
1036
- if (entry === null || entry === undefined)
1037
- return false;
1038
- if (typeof entry !== 'string')
1039
- return true;
1040
- const comparable = i.type === 'extendedTextInteraction' && i.format === 'xhtml'
1041
- ? entry.replace(/<[^>]*>/g, '').replace(/&nbsp;|&#160;/gi, ' ')
1042
- : entry;
1043
- return comparable.trim().length > 0;
1044
- };
1045
- if (i.type === 'mediaInteraction') {
1046
- if (Number(v || 0) > 0)
1047
- return true;
1048
- continue;
1049
- }
1050
- if (Array.isArray(v)) {
1051
- if (v.some(isMeaningful))
1052
- return true;
1053
- continue;
1054
- }
1055
- if (v && typeof v === 'object') {
1056
- const record = v;
1057
- if (Object.values(record).some(isMeaningful))
1058
- return true;
1059
- continue;
1060
- }
1061
- if (isMeaningful(v))
1062
- return true;
1063
- }
1064
- return false;
911
+ return isAttempted(this, responses);
1065
912
  }
1066
913
  // ----------------------------------------------------------------------------
1067
914
  // Execution
1068
915
  // ----------------------------------------------------------------------------
1069
- /** The evaluator's environment, which reads responses in the item's content language. */
1070
- processingEnv() {
1071
- return {
1072
- ctx: this.ctx,
1073
- ops: this.ops,
1074
- rng: this.rng,
1075
- language: this.getContentLanguage(),
1076
- customOperators: this.config.customOperators,
1077
- };
1078
- }
916
+ /**
917
+ * Template processing re-extracts the item's interactions, so the interaction cache
918
+ * drops before the program runs. Template rules can also change response values
919
+ * (setDefaultValue), so the response revision moves with it.
920
+ */
1079
921
  execTemplateProcessing() {
1080
- this.interactionDataCache = null;
1081
- if (!this.templateProcessingProgram)
1082
- return;
1083
- execProgram(this.processingEnv(), this.templateProcessingProgram);
1084
- }
1085
- execResponseProcessingProgram() {
1086
- if (!this.responseProcessingProgram)
1087
- return;
1088
- execProgram(this.processingEnv(), this.responseProcessingProgram);
922
+ this.invalidateInteractionData();
923
+ execTemplateProcessingProgram(this);
924
+ this.responseRevision += 1;
925
+ this.responseSnapshotState = null;
1089
926
  }
1090
- execOutcomeProcessingProgram() {
1091
- if (!this.outcomeProcessingProgram)
1092
- return;
1093
- execProgram(this.processingEnv(), this.outcomeProcessingProgram);
1094
- }
1095
- execResponseProcessingTemplate(templateUrl) {
1096
- const name = templateUrl.split('/').pop()?.toLowerCase().replace(/\.xml$/, '');
1097
- if (!name) {
1098
- console.warn(`[QTI Player] Could not extract template name from URL: ${templateUrl}`);
1099
- return;
1100
- }
1101
- const responseMatchesCorrect = () => {
1102
- const expression = {
1103
- kind: 'expr.match',
1104
- id: 'fixed-template-match',
1105
- a: { kind: 'expr.variable', id: 'fixed-template-response', identifier: 'RESPONSE' },
1106
- b: { kind: 'expr.correct', id: 'fixed-template-correct', identifier: 'RESPONSE' },
1107
- };
1108
- return toBoolean(evalExpr(this.processingEnv(), expression));
1109
- };
1110
- const setScore = (value) => {
1111
- this.ctx.setValue('SCORE', qtiValue('float', 'single', value));
1112
- };
1113
- const setIdentifierOutcome = (identifier, value) => {
1114
- this.ctx.setValue(identifier, qtiValue('identifier', 'single', value));
1115
- };
1116
- const mapResponse = (point) => {
1117
- const response = this.ctx.getValue('RESPONSE');
1118
- if (response.kind === 'null')
1119
- return 0;
1120
- const mapped = evalExpr(this.processingEnv(), {
1121
- kind: point ? 'expr.mapResponsePoint' : 'expr.mapResponse',
1122
- id: point ? 'fixed-template-map-response-point' : 'fixed-template-map-response',
1123
- identifier: 'RESPONSE',
1124
- });
1125
- const value = toNumber(mapped);
1126
- return Number.isFinite(value) ? value : 0;
1127
- };
1128
- switch (name) {
1129
- case 'match_correct':
1130
- case 'cc2_match': {
1131
- setScore(responseMatchesCorrect() ? 1 : 0);
1132
- return;
1133
- }
1134
- case 'cc2_match_basic': {
1135
- if (responseMatchesCorrect()) {
1136
- const maxScore = toNumber(this.ctx.getValue('MAXSCORE'));
1137
- this.ctx.setValue('SCORE', Number.isFinite(maxScore) ? qtiValue('float', 'single', maxScore) : qtiNull('float', 'single'));
1138
- setIdentifierOutcome('FEEDBACKBASIC', 'correct');
1139
- }
1140
- else {
1141
- setIdentifierOutcome('FEEDBACKBASIC', 'incorrect');
1142
- }
1143
- return;
1144
- }
1145
- case 'match_nothing':
1146
- case 'cc2_match_nothing': { // QTI 2.1 compatibility
1147
- const isEmptyResponse = (v) => {
1148
- if (!v)
1149
- return true;
1150
- if (v.kind === 'null')
1151
- return true;
1152
- if (v.kind === 'invalid')
1153
- return false;
1154
- if (v.value === null || v.value === undefined)
1155
- return true;
1156
- if (Array.isArray(v.value))
1157
- return v.value.length === 0;
1158
- if (typeof v.value === 'string')
1159
- return v.value.trim().length === 0;
1160
- return false;
1161
- };
1162
- const allEmpty = isEmptyResponse(this.ctx.getValue('RESPONSE'));
1163
- const max = toNumber(this.ctx.getValue('MAXSCORE'));
1164
- this.ctx.setValue('SCORE', qtiValue('float', 'single', allEmpty ? (Number.isFinite(max) ? max : 1) : 0));
1165
- return;
1166
- }
1167
- case 'map_response': {
1168
- setScore(mapResponse(false));
1169
- return;
1170
- }
1171
- case 'cc2_map_response': {
1172
- const score = mapResponse(false);
1173
- setScore(score);
1174
- const maxScore = toNumber(this.ctx.getValue('MAXSCORE'));
1175
- setIdentifierOutcome('FEEDBACK', Number.isFinite(maxScore) && score === maxScore ? 'correct' : 'incorrect');
1176
- return;
1177
- }
1178
- case 'map_response_point':
1179
- case 'cc2_map_response_point': { // QTI 2.1 compatibility
1180
- setScore(mapResponse(true));
1181
- return;
1182
- }
1183
- default:
1184
- console.warn(`[QTI Player] Unsupported response processing template: ${name}`);
1185
- return;
1186
- }
927
+ invalidateInteractionData() {
928
+ this.interactionDataCache = null;
929
+ this.interactionDataGeneration += 1;
930
+ this.responseSnapshotState = null;
1187
931
  }
1188
932
  // ----------------------------------------------------------------------------
1189
933
  // Declarations
1190
934
  // ----------------------------------------------------------------------------
1191
- buildDeclarations() {
1192
- const decls = {};
1193
- const addDecl = (kind, el) => {
1194
- const identifier = this.getAttrMapped(el, 'identifier');
1195
- const cardinality = (this.getAttrMapped(el, 'cardinality') || 'single');
1196
- const baseType = cardinality === 'record'
1197
- ? undefined
1198
- : (this.getAttrMapped(el, 'baseType') || 'string');
1199
- if (!identifier)
1200
- return;
1201
- const declaredDefault = this.parseDefaultValue(el, baseType, cardinality);
1202
- const impliedNumericDefault = !declaredDefault && this.hasImpliedNumericDefault(kind, baseType, cardinality);
1203
- const defaultValue = declaredDefault ?? this.impliedDefaultValue(kind, baseType, cardinality);
1204
- decls[identifier] = {
1205
- identifier,
1206
- ...(baseType ? { baseType } : {}),
1207
- cardinality,
1208
- defaultValue,
1209
- value: defaultValue,
1210
- isTemplate: kind === 'template',
1211
- impliedNumericDefault,
1212
- // @ts-expect-error internal marker for templates
1213
- __kind: kind,
1214
- };
1215
- // Response + outcome declarations may define mappings used by mapResponse/mapOutcome.
1216
- // (Templates do not participate in mapping.)
1217
- if (kind === 'response' || kind === 'outcome') {
1218
- const mappingEl = findFirstDescendant(el, this.mapper.toNative('mapping'));
1219
- if (mappingEl && baseType) {
1220
- decls[identifier].mapping = this.parseMapping(mappingEl, baseType);
1221
- }
1222
- }
1223
- // Outcome declarations may define a lookup table (matchTable or interpolationTable)
1224
- // used by the lookupOutcomeValue rule.
1225
- if (kind === 'outcome') {
1226
- const matchTableEl = findFirstDescendant(el, this.mapper.toNative('matchtable'));
1227
- const interpolationTableEl = findFirstDescendant(el, this.mapper.toNative('interpolationtable'));
1228
- if (matchTableEl) {
1229
- decls[identifier].lookupTable = this.parseMatchTable(matchTableEl);
1230
- }
1231
- else if (interpolationTableEl) {
1232
- decls[identifier].lookupTable = this.parseInterpolationTable(interpolationTableEl);
1233
- }
1234
- }
1235
- if (kind === 'response') {
1236
- const correctEl = findFirstDescendant(el, this.mapper.toNative('correctresponse'));
1237
- if (correctEl) {
1238
- decls[identifier].correctResponse = this.parseCorrectResponse(correctEl, baseType, cardinality);
1239
- }
1240
- const areaMappingEl = findFirstDescendant(el, this.mapper.toNative('areamapping'));
1241
- if (areaMappingEl) {
1242
- decls[identifier].areaMapping = this.parseAreaMapping(areaMappingEl);
1243
- }
1244
- }
1245
- };
1246
- for (const el of this.itemDocument.findDeclarationElements('response'))
1247
- addDecl('response', el);
1248
- for (const el of this.itemDocument.findDeclarationElements('outcome'))
1249
- addDecl('outcome', el);
1250
- for (const el of this.itemDocument.findDeclarationElements('template'))
1251
- addDecl('template', el);
1252
- for (const el of this.itemDocument.findDeclarationElements('context'))
1253
- addDecl('context', el);
1254
- return decls;
1255
- }
1256
935
  /** Host-supplied context values, e.g. `QTI_CONTEXT`; identifiers that are not context variables are ignored. */
1257
936
  applyContextVariables(values) {
1258
937
  for (const [id, raw] of Object.entries(values ?? {})) {
@@ -1272,555 +951,44 @@ export class Player {
1272
951
  d.value = d.defaultValue;
1273
952
  }
1274
953
  }
1275
- parseMatchTable(el) {
1276
- return {
1277
- kind: 'table.matchTable',
1278
- defaultValue: (getAttr(el, 'defaultValue') || '').trim() || undefined,
1279
- entries: findDescendants(el, this.mapper.toNative('matchtableentry')).map((e) => ({
1280
- sourceValue: (getAttr(e, 'sourceValue') || '').trim(),
1281
- targetValue: (getAttr(e, 'targetValue') || '').trim(),
1282
- })),
1283
- };
1284
- }
1285
- parseInterpolationTable(el) {
1286
- return {
1287
- kind: 'table.interpolationTable',
1288
- defaultValue: (getAttr(el, 'defaultValue') || '').trim() || undefined,
1289
- entries: findDescendants(el, this.mapper.toNative('interpolationtableentry'))
1290
- .map((e) => ({
1291
- sourceValue: Number((getAttr(e, 'sourceValue') || '').trim() || Number.NaN),
1292
- targetValue: (getAttr(e, 'targetValue') || '').trim(),
1293
- includeBoundary: (getAttr(e, 'includeBoundary') || '').trim() !== 'false',
1294
- }))
1295
- .filter((e) => Number.isFinite(e.sourceValue)),
1296
- };
1297
- }
1298
- ensureBuiltinDeclarations(decls) {
1299
- // completionStatus + numAttempts are defined in QTI (esp. adaptive items) and commonly used
1300
- // without explicit outcomeDeclaration in authoring content.
1301
- if (!decls.completionStatus) {
1302
- decls.completionStatus = {
1303
- identifier: 'completionStatus',
1304
- baseType: 'identifier',
1305
- cardinality: 'single',
1306
- value: qtiValue('identifier', 'single', 'not_attempted'),
1307
- isTemplate: false,
1308
- // @ts-expect-error internal marker
1309
- __kind: 'outcome',
1310
- };
1311
- }
1312
- if (!decls.numAttempts) {
1313
- decls.numAttempts = {
1314
- identifier: 'numAttempts',
1315
- baseType: 'integer',
1316
- cardinality: 'single',
1317
- defaultValue: qtiValue('integer', 'single', 0),
1318
- value: qtiValue('integer', 'single', 0),
1319
- isTemplate: false,
1320
- // @ts-expect-error internal marker
1321
- __kind: 'outcome',
1322
- };
1323
- }
1324
- if (!decls.duration) {
1325
- decls.duration = {
1326
- identifier: 'duration',
1327
- baseType: 'duration',
1328
- cardinality: 'single',
1329
- defaultValue: qtiValue('duration', 'single', 0),
1330
- value: qtiValue('duration', 'single', 0),
1331
- isTemplate: false,
1332
- // @ts-expect-error internal marker
1333
- __kind: 'outcome',
1334
- };
1335
- }
1336
- // QTI 3 built-in context variable, set by the delivery system.
1337
- if (!decls.QTI_CONTEXT) {
1338
- decls.QTI_CONTEXT = {
1339
- identifier: 'QTI_CONTEXT',
1340
- cardinality: 'record',
1341
- defaultValue: qtiNull(undefined, 'record'),
1342
- value: qtiNull(undefined, 'record'),
1343
- isTemplate: false,
1344
- // @ts-expect-error internal marker
1345
- __kind: 'context',
1346
- };
1347
- }
1348
- // Common scoring defaults
1349
- if (!decls.SCORE) {
1350
- decls.SCORE = {
1351
- identifier: 'SCORE',
1352
- baseType: 'float',
1353
- cardinality: 'single',
1354
- value: qtiValue('float', 'single', 0),
1355
- isTemplate: false,
1356
- // @ts-expect-error internal marker
1357
- __kind: 'outcome',
1358
- };
1359
- }
1360
- if (!decls.MAXSCORE) {
1361
- decls.MAXSCORE = {
1362
- identifier: 'MAXSCORE',
1363
- baseType: 'float',
1364
- cardinality: 'single',
1365
- value: qtiValue('float', 'single', 1),
1366
- isTemplate: false,
1367
- // @ts-expect-error internal marker
1368
- __kind: 'outcome',
1369
- };
1370
- }
1371
- }
1372
- applySessionState(state) {
1373
- for (const [id, raw] of Object.entries(state)) {
1374
- const d = this.decls[id];
1375
- if (!d)
1376
- continue;
1377
- d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw, d.identifier);
1378
- }
1379
- const restoredDuration = Number(state.duration);
1380
- if (Number.isFinite(restoredDuration) && restoredDuration >= 0) {
1381
- this.accumulatedDurationMs = restoredDuration;
1382
- this.sessionStartedAt = Date.now();
1383
- this.updateDuration();
1384
- }
1385
- }
1386
954
  applySerializedVariables(vars) {
1387
- for (const v of Object.values(vars)) {
1388
- const d = this.decls[v.identifier];
1389
- if (!d)
1390
- continue;
1391
- d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, v.value, d.identifier);
1392
- if (d.__kind === 'response') {
1393
- this.restorePciResponse(d.identifier, this.qtiValueToPublic(d.value));
1394
- }
1395
- }
955
+ applySerializedVariables(this, vars);
1396
956
  }
1397
957
  serializeItemSession() {
1398
- const responseVariables = {};
1399
- const outcomeVariables = {};
1400
- const templateVariables = {};
1401
- const contextVariables = {};
1402
- const contextIds = new Set(['completionStatus', 'numAttempts', 'duration']);
1403
- for (const d of Object.values(this.decls)) {
1404
- const variable = this.serializeVariable(d);
1405
- if (d.isTemplate) {
1406
- templateVariables[d.identifier] = { ...variable, kind: 'template' };
1407
- }
1408
- else if (contextIds.has(d.identifier) || d.__kind === 'context') {
1409
- contextVariables[d.identifier] = { ...variable, kind: 'context' };
1410
- }
1411
- else if (d.__kind === 'response') {
1412
- responseVariables[d.identifier] = { ...variable, kind: 'response' };
1413
- }
1414
- else if (d.__kind === 'outcome') {
1415
- outcomeVariables[d.identifier] = { ...variable, kind: 'outcome' };
1416
- }
1417
- }
1418
- const validation = this.validateResponses(this.getResponses());
1419
- return {
1420
- itemIdentifier: this.itemDocument.getAssessmentItemAttribute('identifier') ?? undefined,
1421
- sessionGuid: this.sessionGuid,
1422
- lifecycleStatus: this.lifecycleStatus,
1423
- completionStatus: this.getCompletionStatus(),
1424
- numAttempts: this.getNumAttempts(),
1425
- duration: this.getDuration(),
1426
- responseVariables,
1427
- outcomeVariables,
1428
- templateVariables,
1429
- contextVariables,
1430
- validationMessages: validation.issues,
1431
- savedAt: new Date().toISOString(),
1432
- };
958
+ return serializeItemSession(this);
1433
959
  }
1434
- serializeVariable(d) {
1435
- return {
1436
- identifier: d.identifier,
1437
- kind: (d.__kind ?? (d.isTemplate ? 'template' : 'context')),
1438
- ...(d.baseType ? { baseType: d.baseType } : {}),
1439
- cardinality: d.cardinality,
1440
- value: this.qtiValueToSerializable(d.value),
1441
- defaultValue: this.qtiValueToSerializable(d.defaultValue),
1442
- };
1443
- }
1444
- qtiValueToSerializable(value) {
1445
- if (!value || value.kind !== 'value')
1446
- return null;
1447
- if (value.cardinality !== 'record')
1448
- return cloneRuntimeValue(value.value);
1449
- const serialized = {};
1450
- for (const [fieldIdentifier, fieldValue] of Object.entries(value.value)) {
1451
- serialized[fieldIdentifier] = {
1452
- ...(fieldValue.baseType ? { baseType: fieldValue.baseType } : {}),
1453
- cardinality: fieldValue.cardinality ?? 'single',
1454
- value: this.qtiValueToSerializable(fieldValue),
1455
- };
1456
- }
1457
- return serialized;
960
+ /** @internal Value forms shared with PCI hosts and the serializer. */
961
+ qtiValueToPci(value) {
962
+ return qtiValueToPci(value);
1458
963
  }
964
+ /** @internal */
1459
965
  qtiValueToPublic(value) {
1460
- if (!value || value.kind !== 'value')
1461
- return null;
1462
- if (value.cardinality !== 'record')
1463
- return cloneRuntimeValue(value.value);
1464
- const record = {};
1465
- for (const [fieldIdentifier, fieldValue] of Object.entries(value.value)) {
1466
- record[fieldIdentifier] = this.qtiValueToPublic(fieldValue);
1467
- }
1468
- return record;
966
+ return qtiValueToPublic(value);
1469
967
  }
968
+ /** @internal Response processing runs start by bringing the duration variable current. */
1470
969
  updateDuration() {
1471
- const elapsedMs = Math.max(0, Date.now() - this.sessionStartedAt);
1472
- const durationMs = this.accumulatedDurationMs + elapsedMs;
1473
- this.ctx.setValue('duration', qtiValue('duration', 'single', durationMs));
970
+ updateDuration(this);
1474
971
  }
1475
972
  freezeDuration() {
1476
- this.updateDuration();
1477
- const duration = this.getDuration();
1478
- this.accumulatedDurationMs = duration;
1479
- this.sessionStartedAt = Date.now();
1480
- return duration;
973
+ return freezeDuration(this);
1481
974
  }
975
+ /** Time on task in whole milliseconds, as the host-facing session fields report it. */
1482
976
  getDuration() {
1483
- const value = this.ctx.getValue('duration');
1484
- return Math.max(0, Math.floor(toNumber(value) || 0));
1485
- }
1486
- /**
1487
- * QTI 2.1 §5.2, carried into 2.2 and 3.0: an outcome variable with no declared default is
1488
- * initialized to NULL unless it is of a numeric type, in which case it is initialized to 0.
1489
- * Response and template variables keep NULL — an unanswered numeric response must stay
1490
- * distinguishable from an answered zero.
1491
- */
1492
- hasImpliedNumericDefault(kind, baseType, cardinality) {
1493
- if (kind !== 'outcome' || cardinality !== 'single')
1494
- return false;
1495
- return baseType === 'integer' || baseType === 'float';
1496
- }
1497
- impliedDefaultValue(kind, baseType, cardinality) {
1498
- if (this.hasImpliedNumericDefault(kind, baseType, cardinality)) {
1499
- return qtiValue(baseType, 'single', 0);
1500
- }
1501
- return qtiNull(baseType, cardinality);
1502
- }
1503
- /** Returns undefined when the declaration carries no <defaultValue> at all. */
1504
- parseDefaultValue(declEl, baseType, cardinality) {
1505
- const defaultEl = findFirstDescendant(declEl, this.mapper.toNative('defaultvalue'));
1506
- if (!defaultEl)
1507
- return undefined;
1508
- return this.parseDeclarationValues(defaultEl, baseType, cardinality);
1509
- }
1510
- parseCorrectResponse(correctEl, baseType, cardinality) {
1511
- return this.parseDeclarationValues(correctEl, baseType, cardinality);
1512
- }
1513
- parseDeclarationValues(container, baseType, cardinality) {
1514
- const valueElements = findDescendants(container, this.mapper.toNative('value'));
1515
- if (cardinality === 'record') {
1516
- const record = {};
1517
- for (const valueElement of valueElements) {
1518
- const fieldIdentifier = this.getAttrMapped(valueElement, 'fieldIdentifier');
1519
- const fieldBaseType = this.getAttrMapped(valueElement, 'baseType');
1520
- if (!fieldIdentifier || !fieldBaseType)
1521
- continue;
1522
- record[fieldIdentifier] = coerceBaseValue(fieldBaseType, valueElement.textContent || '', this.getContentLanguage());
1523
- }
1524
- return Object.keys(record).length > 0
1525
- ? qtiValue(undefined, 'record', record)
1526
- : qtiNull(undefined, 'record');
1527
- }
1528
- if (!baseType)
1529
- return qtiNull(undefined, cardinality);
1530
- const values = valueElements.map((value) => (value.textContent || '').trim());
1531
- if (cardinality === 'multiple' || cardinality === 'ordered') {
1532
- return qtiValue(baseType, cardinality, values.map((t) => {
1533
- const v = coerceBaseValue(baseType, t, this.getContentLanguage());
1534
- return v.kind === 'value' ? v.value : null;
1535
- }));
1536
- }
1537
- return coerceBaseValue(baseType, values[0] ?? '', this.getContentLanguage());
1538
- }
1539
- parseMapping(mappingEl, baseType) {
1540
- const defaultValue = Number(this.getAttrMapped(mappingEl, 'defaultValue') || 0);
1541
- const lowerBound = this.getAttrMapped(mappingEl, 'lowerBound') ? Number(this.getAttrMapped(mappingEl, 'lowerBound')) : undefined;
1542
- const upperBound = this.getAttrMapped(mappingEl, 'upperBound') ? Number(this.getAttrMapped(mappingEl, 'upperBound')) : undefined;
1543
- const mappingCaseSensitive = this.getAttrMapped(mappingEl, 'caseSensitive') || 'true';
1544
- const entries = {};
1545
- const normalizePairKey = (k) => {
1546
- const parts = k.trim().split(/\s+/).filter(Boolean);
1547
- if (parts.length === 2)
1548
- return [...parts].sort().join(' ');
1549
- return k.trim();
1550
- };
1551
- const normalizeDirectedPairKey = (k) => {
1552
- const parts = k.trim().split(/\s+/).filter(Boolean);
1553
- if (parts.length >= 2)
1554
- return `${parts[0]} ${parts[1]}`;
1555
- return k.trim();
1556
- };
1557
- for (const e of findDescendants(mappingEl, this.mapper.toNative('mapentry'))) {
1558
- const mapKey = this.getAttrMapped(e, 'mapKey');
1559
- const mappedValue = this.getAttrMapped(e, 'mappedValue');
1560
- if (!mapKey || mappedValue === null)
1561
- continue;
1562
- const effectiveCaseSensitive = this.getAttrMapped(e, 'caseSensitive') || mappingCaseSensitive || 'true';
1563
- const storedKey = baseType === 'pair'
1564
- ? normalizePairKey(mapKey)
1565
- : baseType === 'directedPair'
1566
- ? normalizeDirectedPairKey(mapKey)
1567
- : mapKey;
1568
- entries[storedKey] = { mapKey: storedKey, mappedValue: Number(mappedValue), caseSensitive: effectiveCaseSensitive };
1569
- if (effectiveCaseSensitive !== 'true') {
1570
- const lowerKey = storedKey.toLowerCase();
1571
- entries[lowerKey] = {
1572
- mapKey: lowerKey,
1573
- mappedValue: Number(mappedValue),
1574
- caseSensitive: effectiveCaseSensitive,
1575
- };
1576
- }
1577
- }
1578
- return { defaultValue, lowerBound, upperBound, caseSensitive: mappingCaseSensitive, entries };
1579
- }
1580
- parseAreaMapping(areaMappingEl) {
1581
- const defaultValue = Number(getAttr(areaMappingEl, 'defaultValue') || 0);
1582
- const lowerBound = getAttr(areaMappingEl, 'lowerBound')
1583
- ? Number(getAttr(areaMappingEl, 'lowerBound'))
1584
- : undefined;
1585
- const upperBound = getAttr(areaMappingEl, 'upperBound')
1586
- ? Number(getAttr(areaMappingEl, 'upperBound'))
1587
- : undefined;
1588
- const entries = [];
1589
- for (const e of findDescendants(areaMappingEl, this.mapper.toNative('areamapentry'))) {
1590
- const shape = (getAttr(e, 'shape') || 'default');
1591
- const coords = String(getAttr(e, 'coords') || '');
1592
- const mappedValue = Number(getAttr(e, 'mappedValue') || 0);
1593
- entries.push({ shape, coords, mappedValue });
1594
- }
1595
- return { defaultValue, lowerBound, upperBound, entries };
977
+ return this.durationMs;
1596
978
  }
979
+ /** Raw values read as a declaration's QTI base type and cardinality; see declarations/declarationValues. */
1597
980
  coerceToDeclarationValue(baseType, cardinality, raw, identifier) {
1598
- if (raw === null || raw === undefined)
1599
- return qtiNull(baseType, cardinality);
1600
- // Allow callers to pass fully-formed QtiValue (e.g. session restore).
1601
- if (typeof raw === 'object' && raw && 'kind' in raw) {
1602
- return cloneRuntimeValue(raw);
1603
- }
1604
- const extendedTextBase = identifier ? this.getExtendedTextBase(identifier) : undefined;
1605
- if (cardinality === 'record') {
1606
- return this.coerceRecordValue(raw, extendedTextBase ?? 10);
1607
- }
1608
- if (!baseType)
1609
- return qtiNull(undefined, cardinality);
1610
- // For file types, preserve QTIFileResponse objects directly
1611
- if (baseType === 'file') {
1612
- if (cardinality === 'multiple' || cardinality === 'ordered') {
1613
- const arr = Array.isArray(raw) ? raw : [raw];
1614
- return qtiValue(baseType, cardinality, cloneRuntimeValue(arr.filter((v) => v !== null && v !== undefined)));
1615
- }
1616
- return qtiValue(baseType, cardinality, cloneRuntimeValue(raw));
1617
- }
1618
- if (cardinality === 'multiple' || cardinality === 'ordered') {
1619
- const arr = Array.isArray(raw) ? raw : [raw];
1620
- const coerced = arr
1621
- .map((v) => String(v ?? '').trim())
1622
- .filter((s) => s.length > 0)
1623
- .map((t) => {
1624
- if (extendedTextBase && (baseType === 'integer' || baseType === 'float')) {
1625
- const numeric = createExtendedTextNumericRecord(t, extendedTextBase, this.getContentLanguage());
1626
- return baseType === 'integer' ? numeric.integerValue : numeric.floatValue;
1627
- }
1628
- const v = coerceBaseValue(baseType, t, this.getContentLanguage());
1629
- return v.kind === 'value' ? v.value : null;
1630
- })
1631
- .filter((v) => v !== null);
1632
- // Multiple/ordered can legitimately be an empty container (distinct from null).
1633
- return qtiValue(baseType, cardinality, coerced);
1634
- }
1635
- const t = String(raw ?? '').trim();
1636
- if (t.length === 0)
1637
- return qtiNull(baseType, cardinality);
1638
- if (extendedTextBase && (baseType === 'integer' || baseType === 'float')) {
1639
- const numeric = createExtendedTextNumericRecord(t, extendedTextBase, this.getContentLanguage());
1640
- const value = baseType === 'integer' ? numeric.integerValue : numeric.floatValue;
1641
- return value === null ? qtiNull(baseType, 'single') : qtiValue(baseType, 'single', value);
1642
- }
1643
- return coerceBaseValue(baseType, t, this.getContentLanguage());
1644
- }
1645
- getExtendedTextBase(responseIdentifier) {
1646
- return this.itemDocument.getExtendedTextBase(responseIdentifier);
1647
- }
1648
- coerceRecordValue(raw, base) {
1649
- let source = raw;
1650
- if (typeof source === 'string') {
1651
- const stringSource = source;
1652
- if (stringSource.trim().length === 0)
1653
- return qtiNull(undefined, 'record');
1654
- if (stringSource.trimStart().startsWith('{')) {
1655
- try {
1656
- source = JSON.parse(stringSource);
1657
- }
1658
- catch {
1659
- return qtiNull(undefined, 'record');
1660
- }
1661
- }
1662
- else {
1663
- source = createExtendedTextNumericRecord(stringSource, base, this.getContentLanguage());
1664
- }
1665
- }
1666
- if (!source || typeof source !== 'object' || Array.isArray(source)) {
1667
- return qtiNull(undefined, 'record');
1668
- }
1669
- const fields = {};
1670
- for (const [fieldIdentifier, rawField] of Object.entries(source)) {
1671
- if (rawField && typeof rawField === 'object' && 'kind' in rawField) {
1672
- fields[fieldIdentifier] = rawField;
1673
- continue;
1674
- }
1675
- let fieldBaseType = EXTENDED_TEXT_RECORD_FIELD_TYPES[fieldIdentifier];
1676
- let fieldValue = rawField;
1677
- if (rawField && typeof rawField === 'object' && !Array.isArray(rawField) && 'value' in rawField) {
1678
- const serializedField = rawField;
1679
- fieldBaseType = serializedField.baseType ?? fieldBaseType;
1680
- fieldValue = serializedField.value;
1681
- }
1682
- if (!fieldBaseType) {
1683
- fieldBaseType = typeof fieldValue === 'boolean'
1684
- ? 'boolean'
1685
- : typeof fieldValue === 'number'
1686
- ? (Number.isInteger(fieldValue) ? 'integer' : 'float')
1687
- : 'string';
1688
- }
1689
- if (fieldValue === null || fieldValue === undefined) {
1690
- fields[fieldIdentifier] = qtiNull(fieldBaseType, 'single');
1691
- }
1692
- else if (fieldBaseType === 'file' && typeof fieldValue === 'object') {
1693
- fields[fieldIdentifier] = qtiValue('file', 'single', fieldValue);
1694
- }
1695
- else {
1696
- fields[fieldIdentifier] = coerceBaseValue(fieldBaseType, String(fieldValue), this.getContentLanguage());
1697
- }
1698
- }
1699
- return Object.keys(fields).length > 0
1700
- ? qtiValue(undefined, 'record', fields)
1701
- : qtiNull(undefined, 'record');
1702
- }
1703
- collectOutcomes() {
1704
- const out = {};
1705
- for (const d of Object.values(this.decls)) {
1706
- if (d.__kind !== 'outcome')
1707
- continue;
1708
- if (d.value.kind === 'value')
1709
- out[d.identifier] = this.qtiValueToPublic(d.value);
1710
- else if (d.value.kind === 'null')
1711
- out[d.identifier] = null;
1712
- }
1713
- // Ensure MAXSCORE always has a value (fallback to 1.0 if null or missing)
1714
- if (out.MAXSCORE === null || out.MAXSCORE === undefined) {
1715
- out.MAXSCORE = 1.0;
1716
- }
1717
- return out;
981
+ return coerceToDeclarationValue({ itemDocument: this.itemDocument }, baseType, cardinality, raw, identifier);
1718
982
  }
1719
983
  // ----------------------------------------------------------------------------
1720
984
  // Item content pass: printedVariable, feedback, templates
1721
985
  // ----------------------------------------------------------------------------
1722
- /**
1723
- * The item content pass's handlers, reading the session's current variable values. QTI 3 wraps
1724
- * rubric content in `qti-content-body`, which is unwrapped so a rubric renders as in QTI 2.2.
1725
- * Feedback resolves here for rubric and modal feedback content; item body and choice feedback
1726
- * resolve in presentation, which takes the outcome values to present as input.
1727
- */
1728
986
  contentHandlers({ feedback = true } = {}) {
1729
- const conditional = (variable) => (element) => this.isShownByVariable(element, variable, getAttr(element, 'identifier')) ? Array.from(element.childNodes) : [];
1730
- const handlers = new Map([
1731
- ['printedvariable', (element) => this.printedVariableNodes(element)],
1732
- ['contentbody', (element) => Array.from(element.childNodes)],
1733
- ['templateinline', conditional('templateIdentifier')],
1734
- ['templateblock', conditional('templateIdentifier')],
1735
- ]);
1736
- for (const choice of TEMPLATE_CHOICES) {
1737
- handlers.set(choice, (element) => !getAttr(element, 'templateIdentifier') ||
1738
- this.isShownByVariable(element, 'templateIdentifier', getAttr(element, 'identifier'))
1739
- ? undefined
1740
- : []);
1741
- }
1742
- if (this.mathVariables().size > 0) {
1743
- handlers.set('mi', (element) => this.mathVariableNodes(element, 'mn'));
1744
- handlers.set('ci', (element) => this.mathVariableNodes(element, 'cn'));
1745
- }
1746
- if (feedback) {
1747
- handlers.set('feedbackinline', conditional('outcomeIdentifier'));
1748
- handlers.set('feedbackblock', conditional('outcomeIdentifier'));
1749
- }
1750
- return handlers;
1751
- }
1752
- /**
1753
- * Whether `element` shows: the variable named by its `variableAttribute` against `identifier`,
1754
- * by the shared visibility rule. A missing variable or identifier hides it.
1755
- */
1756
- isShownByVariable(element, variableAttribute, identifier) {
1757
- const variable = (getAttr(element, variableAttribute) || '').trim();
1758
- const id = (identifier || '').trim();
1759
- if (!variable || !id)
1760
- return false;
1761
- const current = this.ctx.getValue(variable);
1762
- return isShownByIdentifier(current.kind === 'value' ? current.value : null, id, getAttr(element, 'showHide'));
1763
- }
1764
- mathVariables() {
1765
- this.mathVariableIds ?? (this.mathVariableIds = new Set(this.itemDocument
1766
- .findDeclarationElements('template')
1767
- .filter((el) => getAttr(el, 'mathVariable')?.trim() === 'true')
1768
- .map((el) => (getAttr(el, 'identifier') || '').trim())));
1769
- return this.mathVariableIds;
1770
- }
1771
- /**
1772
- * A MathML `mi` or `ci` naming a math variable, with the variable's single value in its place:
1773
- * a number as `mn` or `cn` (`numberName`), any other value as the element's text. NULL and
1774
- * container values leave the element as authored.
1775
- */
1776
- mathVariableNodes(element, numberName) {
1777
- const identifier = (element.textContent || '').trim();
1778
- const document = element.ownerDocument;
1779
- if (!document || !this.mathVariables().has(identifier))
1780
- return undefined;
1781
- const value = this.ctx.getValue(identifier);
1782
- if (value.kind !== 'value' || value.cardinality !== 'single')
1783
- return undefined;
1784
- const text = String(value.value);
1785
- if (value.baseType !== 'integer' && value.baseType !== 'float') {
1786
- // The pass resolves a copy, and the element is not walked again, so this cannot cycle.
1787
- element.textContent = text;
1788
- return undefined;
1789
- }
1790
- const name = element.prefix ? `${element.prefix}:${numberName}` : numberName;
1791
- const replacement = document.createElementNS(element.namespaceURI, name);
1792
- replacement.appendChild(document.createTextNode(text));
1793
- return [replacement];
1794
- }
1795
- printedVariableNodes(element) {
1796
- const identifier = (getAttr(element, 'identifier') || '').trim();
1797
- const document = element.ownerDocument;
1798
- if (!identifier || !document)
1799
- return [];
1800
- const variable = (id) => this.ctx.getValue(id);
1801
- const printed = printVariable(variable(identifier), readPrintedVariableOptions(element, variable));
1802
- return printed.map((segment) => {
1803
- if (typeof segment === 'string')
1804
- return document.createTextNode(segment);
1805
- const sup = document.createElementNS(element.namespaceURI, 'sup');
1806
- sup.appendChild(document.createTextNode(segment.superscript));
1807
- return sup;
1808
- });
1809
- }
1810
- renderHtmlContent(html) {
1811
- const sanitized = sanitizeHtml(html, { security: this.config.security });
1812
- return toTrustedHtml(sanitized, this.config.security?.trustedTypesPolicyName);
987
+ return contentHandlers(this, { feedback });
1813
988
  }
989
+ /** @internal Scoring resolves the attempt's active modal feedback. */
1814
990
  getModalFeedback(outcomes) {
1815
- const active = [];
1816
- for (const feedback of this.itemDocument.readModalFeedback(this.contentHandlers())) {
1817
- const { identifier, outcomeIdentifier, showHide, title } = feedback;
1818
- const content = this.renderHtmlContent(feedback.content);
1819
- if (isShownByIdentifier(outcomes[outcomeIdentifier], identifier, showHide) && content) {
1820
- active.push({ identifier, outcomeIdentifier, showHide, content, title });
1821
- }
1822
- }
1823
- return active;
991
+ return modalFeedbackOf(this, this.contentHandlers(), outcomes);
1824
992
  }
1825
993
  }
1826
994
  // ---------------------------------------------------------------------------
@@ -1857,18 +1025,4 @@ function createSessionGuid() {
1857
1025
  'requires crypto.randomUUID or crypto.getRandomValues (present in all supported ' +
1858
1026
  'browsers and in Node >= 20).');
1859
1027
  }
1860
- function cloneDeclarationMap(declarations) {
1861
- return structuredClone(declarations);
1862
- }
1863
- /** Detach serializable runtime values from caller- and declaration-owned references. */
1864
- function cloneRuntimeValue(value) {
1865
- if (!value || typeof value !== 'object')
1866
- return value;
1867
- return structuredClone(value);
1868
- }
1869
- function looksLikeCatalogUrl(value) {
1870
- const trimmed = value.trim();
1871
- return /^(https?:\/\/|\/\/|\/|\.{0,2}\/|data:|blob:)/i.test(trimmed) ||
1872
- /\.(png|jpe?g|gif|webp|svg|mp3|wav|ogg|mp4|webm|pdf)(\?.*)?$/i.test(trimmed);
1873
- }
1874
1028
  //# sourceMappingURL=Player.js.map