@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
@@ -0,0 +1,335 @@
1
+ /**
2
+ * Response validation: the field checks every interaction's response must satisfy, and
3
+ * the end-attempt gate that additionally rejects incomplete required responses.
4
+ *
5
+ * The generic checks run for every interaction, reading the interaction-shaped fields
6
+ * (minChoices, matchMin, requiredGaps, patternMask, matchGroup) from the delivered
7
+ * interaction data. The per-type entries below (TYPE_VALIDATION_ENTRIES) only restate
8
+ * today's special cases — media minPlays, endAttempt never-required, extendedText
9
+ * maxStrings — keyed on the delivered interaction type (the extractor's output type, so
10
+ * vendor overrides such as acme-likert delivering `choiceInteraction` keep the generic
11
+ * checks); no entry adds a constraint.
12
+ */
13
+ import { isPatternSubjectWithinCap, xsdPatternToRegExp, } from '@pie-qti/qti-processing';
14
+ import { findMatchGroupViolations } from '../matchGroups.js';
15
+ import { orderChoiceLimits } from '../../interactions/order/limits.js';
16
+ const TYPE_VALIDATION_ENTRIES = {
17
+ endAttemptInteraction: {
18
+ // An end-attempt interaction invokes response processing; it carries no candidate
19
+ // answer to require (QTI 3.0 §5.45).
20
+ neverRequired: true,
21
+ },
22
+ mediaInteraction: {
23
+ // A media interaction is answered at minPlays plays, not by any non-null value:
24
+ // its response is the play count (QTI 3.0 §5.69).
25
+ completeWhenRequired: (value, interaction) => Number(value || 0) >= Number(interaction.minPlays || 0),
26
+ attemptedValue: (value) => Number(value || 0) > 0,
27
+ },
28
+ extendedTextInteraction: {
29
+ // maxStrings caps the strings of a multiple-cardinality extended-text response
30
+ // (QTI 2.1 §5.8; QTI 3.0 §5.81).
31
+ shapeErrors: (responseId, value, interaction, isMeaningfulEntry) => Array.isArray(value) &&
32
+ Number(interaction.maxStrings ?? 0) > 0 &&
33
+ value.filter(isMeaningfulEntry).length > Number(interaction.maxStrings)
34
+ ? [`Response '${responseId}' exceeds maxStrings=${interaction.maxStrings}`]
35
+ : [],
36
+ },
37
+ };
38
+ function typeValidationEntryOf(interaction) {
39
+ return TYPE_VALIDATION_ENTRIES[interaction.type];
40
+ }
41
+ export function validateResponses(host, responses) {
42
+ const interactions = host.getInteractions();
43
+ const entries = {};
44
+ const issues = [];
45
+ for (const i of interactions) {
46
+ const responseId = i.responseIdentifier;
47
+ const decl = host.decls[responseId];
48
+ const value = responses[responseId];
49
+ const isMeaningfulEntry = (entry) => isMeaningfulResponseEntry(entry, i);
50
+ const constrainedChoices = [
51
+ ...(i.choices ?? []),
52
+ ...(i.gapTexts ?? []),
53
+ ...(i.gapImages ?? []),
54
+ ...(i.sourceSet ?? []),
55
+ ...(i.targetSet ?? []),
56
+ ...(i.associableHotspots ?? []),
57
+ // graphicGapMatch delivers its hotspots as `hotspots` (graphic-associate
58
+ // delivers the same element as `associableHotspots`); both carry matchMin.
59
+ ...(i.hotspots ?? []),
60
+ ];
61
+ const minimum = Math.max(0, Number(i.minChoices ?? 0), Number(i.minAssociations ?? 0), Number(i.minStrings ?? 0), Number(i.minPlays ?? 0));
62
+ // gap `required` (QTI 2.1 gap; QTI 3.0 §5.55.5): "this gap must be filled by the candidate
63
+ // in order to form a valid response to the interaction".
64
+ const requiredGaps = Array.isArray(i.requiredGaps) ? i.requiredGaps : [];
65
+ const typeEntry = typeValidationEntryOf(i);
66
+ const required = !typeEntry?.neverRequired &&
67
+ (minimum > 0 ||
68
+ requiredGaps.length > 0 ||
69
+ constrainedChoices.some((choice) => Number(choice.matchMin ?? 0) > 0));
70
+ let complete = !required;
71
+ if (required && typeEntry?.completeWhenRequired) {
72
+ complete = typeEntry.completeWhenRequired(value, i);
73
+ }
74
+ else if (required) {
75
+ if (Array.isArray(value)) {
76
+ const nonEmptyValues = value.filter(isMeaningfulEntry);
77
+ complete = nonEmptyValues.length > 0;
78
+ // Enforce minChoices / minAssociations where applicable
79
+ const minChoices = Math.max(Number(i.minChoices ?? 0), Number(i.minAssociations ?? 0), Number(i.minStrings ?? 0));
80
+ if (complete && minChoices > 0) {
81
+ complete = nonEmptyValues.length >= minChoices;
82
+ }
83
+ // Enforce matchMin per-choice: each pairing entry "id1 id2" in value must
84
+ // appear at least matchMin times for the relevant choice.
85
+ // Collect all choice arrays that can carry matchMin across all pairing interaction types.
86
+ for (const choice of constrainedChoices) {
87
+ const min = Number(choice.matchMin || 0);
88
+ if (min > 0) {
89
+ const count = value.filter((p) => {
90
+ const parts = p.split(' ');
91
+ return parts[0] === choice.identifier || parts[1] === choice.identifier;
92
+ }).length;
93
+ if (count < min) {
94
+ complete = false;
95
+ break;
96
+ }
97
+ }
98
+ }
99
+ }
100
+ else if (decl?.cardinality === 'record') {
101
+ const stringValue = value && typeof value === 'object'
102
+ ? value.stringValue
103
+ : undefined;
104
+ complete = isMeaningfulEntry(stringValue);
105
+ }
106
+ else {
107
+ complete = isMeaningfulEntry(value);
108
+ }
109
+ }
110
+ // A gap-match response pairs "gapText gap": each required gap must be the target of a pair.
111
+ if (requiredGaps.length > 0) {
112
+ const filled = new Set((Array.isArray(value) ? value.filter(isMeaningfulEntry) : []).map((pair) => String(pair).split(' ')[1]));
113
+ if (requiredGaps.some((gap) => !filled.has(gap)))
114
+ complete = false;
115
+ }
116
+ // orderInteraction / graphicOrderInteraction: an order that has begun is complete once it
117
+ // holds the minimum its mode sets — every choice when no subset is requested (minChoices
118
+ // unspecified: "all of the choices must be ordered"), at least minChoices when one is.
119
+ // An untouched order stays a skip, as before, which allowSkipping governs.
120
+ const orderLimits = orderInteractionLimits(i);
121
+ const orderedCount = orderLimits && Array.isArray(value) ? value.filter(isMeaningfulEntry).length : 0;
122
+ if (orderLimits && orderedCount > 0) {
123
+ complete = orderedCount >= orderLimits.minOrdered;
124
+ }
125
+ const errors = [];
126
+ const warnings = [];
127
+ if (decl) {
128
+ if (decl.cardinality === 'multiple' || decl.cardinality === 'ordered') {
129
+ if (!(value === null || value === undefined || Array.isArray(value))) {
130
+ errors.push(`Expected an array for ${decl.cardinality} response '${responseId}'`);
131
+ }
132
+ }
133
+ else if (decl.cardinality === 'record') {
134
+ if (!(value === null || value === undefined || (typeof value === 'object' && !Array.isArray(value)))) {
135
+ errors.push(`Expected an object for record response '${responseId}'`);
136
+ }
137
+ }
138
+ else {
139
+ if (Array.isArray(value)) {
140
+ errors.push(`Expected a single value for response '${responseId}'`);
141
+ }
142
+ }
143
+ }
144
+ if (typeEntry?.shapeErrors) {
145
+ errors.push(...typeEntry.shapeErrors(responseId, value, i, isMeaningfulEntry));
146
+ }
147
+ // patternMask (QTI 2.1; QTI 3.0 §5.48.4, §5.162.5): "a regular expression that the
148
+ // candidate's response must match in order to be considered valid", in XSD syntax. A string
149
+ // response holds the text as entered; a numeric one does not, and its input checks the text.
150
+ const patternMask = typeof i.patternMask === 'string' ? xsdPatternToRegExp(i.patternMask) : null;
151
+ if (patternMask && decl?.baseType === 'string') {
152
+ const entered = (Array.isArray(value) ? value : [value]).filter((text) => typeof text === 'string' && text !== '');
153
+ // A response beyond the documented subject cap (see the pattern subject cap in
154
+ // @pie-qti/qti-processing) skips the mask instead of running authored regex over it:
155
+ // it passes unmasked rather than risking a hang on a pathological pattern.
156
+ if (entered.filter(isPatternSubjectWithinCap).some((text) => !patternMask.test(text))) {
157
+ errors.push(`Response '${responseId}' does not match its patternMask`);
158
+ }
159
+ }
160
+ // The order-subset cap: when a subset is requested, a restored or programmatic response
161
+ // may not order more than maxChoices (clamped to the choices); the delivered UI refuses it.
162
+ if (orderLimits?.subset && orderedCount > orderLimits.maxOrdered) {
163
+ errors.push(`Response '${responseId}' exceeds maxChoices=${orderLimits.maxOrdered}`);
164
+ }
165
+ // graphicGapMatch maxima: the delivered interface does not cap them all, so a response
166
+ // built or restored over a limit is checked here.
167
+ if (i.type === 'graphicGapMatchInteraction' && Array.isArray(value)) {
168
+ errors.push(...graphicGapMatchMaximaErrors(responseId, value.filter(isMeaningfulEntry), {
169
+ maxAssociations: i.maxAssociations,
170
+ gapTexts: i.gapTexts,
171
+ gapImages: i.gapImages,
172
+ hotspots: i.hotspots,
173
+ }));
174
+ }
175
+ // gapMatch maxAssociations (0 = no restriction): the delivered interface refuses a
176
+ // placement past it; a restored or programmatic response over it is checked here.
177
+ const gapMatchMax = i.type === 'gapMatchInteraction' ? Number(i.maxAssociations ?? 0) : 0;
178
+ if (gapMatchMax > 0 && Array.isArray(value) && value.filter(isMeaningfulEntry).length > gapMatchMax) {
179
+ errors.push(`Response '${responseId}' exceeds maxAssociations=${gapMatchMax}`);
180
+ }
181
+ const shapeErrorCount = errors.length;
182
+ // matchGroup restricts which choices may pair. The renderers enforce it while the
183
+ // candidate works; a restored or programmatic response is checked here.
184
+ const matchGroups = host.matchGroupConstraints.get(responseId);
185
+ if (matchGroups) {
186
+ for (const pair of findMatchGroupViolations(value, matchGroups)) {
187
+ errors.push(`Response '${responseId}' pairs ${pair.replace(' ', ' with ')}, which matchGroup does not allow`);
188
+ }
189
+ }
190
+ const valid = errors.length === 0;
191
+ entries[responseId] = {
192
+ responseId,
193
+ interactionType: i.type,
194
+ required,
195
+ complete,
196
+ valid,
197
+ errors,
198
+ warnings,
199
+ };
200
+ errors.forEach((e, index) => {
201
+ issues.push({
202
+ responseId,
203
+ code: index < shapeErrorCount ? 'invalid_shape' : 'match_group',
204
+ message: e,
205
+ severity: 'error',
206
+ });
207
+ });
208
+ }
209
+ const allValid = Object.values(entries).every((e) => e.valid);
210
+ return { valid: allValid, entries, issues };
211
+ }
212
+ /**
213
+ * The validation the end attempt with `validateResponses` gates on (QTI ASI §4
214
+ * itemSessionControl validateResponses). An invalid response "does not satisfy the
215
+ * constraints imposed by the interaction": beyond a malformed value or a matchGroup
216
+ * pairing (`validateResponses`), an interaction that requires input — minChoices,
217
+ * minAssociations, minStrings, minPlays, matchMin — rejects an incomplete one. Those
218
+ * entries turn invalid with an `incomplete` issue, so the result reads invalid through
219
+ * the same channel as every other rejection.
220
+ *
221
+ * An item with no response at all is a skip, which allowSkipping governs ("delivery
222
+ * engines must ensure that the candidate can choose to submit no response" when it is
223
+ * true). The item cannot see allowSkipping, so completeness applies only once the
224
+ * candidate has responded and a skip is the caller's decision.
225
+ */
226
+ export function validateAttemptResponses(host, responses) {
227
+ const validation = validateResponses(host, responses);
228
+ if (!isAttempted(host, responses))
229
+ return validation;
230
+ const entries = {};
231
+ const issues = [...validation.issues];
232
+ for (const entry of Object.values(validation.entries)) {
233
+ if (entry.complete) {
234
+ entries[entry.responseId] = entry;
235
+ continue;
236
+ }
237
+ const message = `Response '${entry.responseId}' does not satisfy the constraints of its ${entry.interactionType}`;
238
+ entries[entry.responseId] = { ...entry, valid: false, errors: [...entry.errors, message] };
239
+ issues.push({ responseId: entry.responseId, code: 'incomplete', message, severity: 'error' });
240
+ }
241
+ return { valid: Object.values(entries).every((e) => e.valid), entries, issues };
242
+ }
243
+ export function isAttempted(host, responses) {
244
+ for (const i of host.getResponseInteractions()) {
245
+ const id = i.responseIdentifier;
246
+ const v = responses[id];
247
+ const isMeaningful = (entry) => isMeaningfulResponseEntry(entry, i);
248
+ const attemptedValue = typeValidationEntryOf(i)?.attemptedValue;
249
+ if (attemptedValue) {
250
+ if (attemptedValue(v))
251
+ return true;
252
+ continue;
253
+ }
254
+ if (Array.isArray(v)) {
255
+ if (v.some(isMeaningful))
256
+ return true;
257
+ continue;
258
+ }
259
+ if (v && typeof v === 'object') {
260
+ const record = v;
261
+ if (Object.values(record).some(isMeaningful))
262
+ return true;
263
+ continue;
264
+ }
265
+ if (isMeaningful(v))
266
+ return true;
267
+ }
268
+ return false;
269
+ }
270
+ /**
271
+ * True when a response entry carries meaningful learner input. Extended-text items
272
+ * authored as XHTML are stripped to plain text first, so markup-only answers do not
273
+ * count as "answered". Shared by response validation and attempted-state tracking.
274
+ */
275
+ export function isMeaningfulResponseEntry(entry, interaction) {
276
+ if (entry === null || entry === undefined)
277
+ return false;
278
+ if (typeof entry !== 'string')
279
+ return true;
280
+ const comparable = interaction.type === 'extendedTextInteraction' && interaction.format === 'xhtml'
281
+ ? entry.replace(/<[^>]*>/g, '').replace(/&nbsp;|&#160;/gi, ' ')
282
+ : entry;
283
+ return comparable.trim().length > 0;
284
+ }
285
+ /**
286
+ * The graphicGapMatchInteraction maxima a response breaks (QTI ASI graphicGapMatchInteraction,
287
+ * gapChoice and associableHotspot): at most `maxAssociations` associations, and each gap choice
288
+ * (gapText, gapImg) and each hotspot in at most its `matchMax` associations; 0 means no
289
+ * restriction. Associations are directed pairs "choice hotspot"; other entries count towards
290
+ * `maxAssociations` only.
291
+ */
292
+ function graphicGapMatchMaximaErrors(responseId, entries, interaction) {
293
+ const errors = [];
294
+ const maxAssociations = Number(interaction.maxAssociations ?? 0);
295
+ if (maxAssociations > 0 && entries.length > maxAssociations) {
296
+ errors.push(`Response '${responseId}' exceeds maxAssociations=${maxAssociations}`);
297
+ }
298
+ const pairs = entries
299
+ .filter((entry) => typeof entry === 'string')
300
+ .map((entry) => entry.trim().split(/\s+/))
301
+ .filter((parts) => parts.length === 2);
302
+ const checkMatchMax = (choices, side) => {
303
+ for (const choice of choices) {
304
+ const matchMax = Number(choice.matchMax ?? 0);
305
+ if (!(matchMax > 0))
306
+ continue;
307
+ const count = pairs.filter((parts) => parts[side] === choice.identifier).length;
308
+ if (count > matchMax) {
309
+ errors.push(`Response '${responseId}' uses ${choice.identifier} in ${count} associations, more than matchMax=${matchMax}`);
310
+ }
311
+ }
312
+ };
313
+ checkMatchMax([...(interaction.gapTexts ?? []), ...(interaction.gapImages ?? [])], 0);
314
+ checkMatchMax(interaction.hotspots ?? [], 1);
315
+ return errors;
316
+ }
317
+ /**
318
+ * The order-subset limits of an orderInteraction or graphicOrderInteraction (QTI ASI §5.73,
319
+ * §5.42), read with the same rule the order renderers use; null for any other interaction.
320
+ */
321
+ function orderInteractionLimits(interaction) {
322
+ const choices = interaction.type === 'orderInteraction'
323
+ ? interaction.choices
324
+ : interaction.type === 'graphicOrderInteraction'
325
+ ? interaction.hotspotChoices
326
+ : undefined;
327
+ if (!choices)
328
+ return null;
329
+ return orderChoiceLimits({
330
+ minChoices: interaction.minChoices,
331
+ maxChoices: interaction.maxChoices,
332
+ choiceCount: choices.length,
333
+ });
334
+ }
335
+ //# sourceMappingURL=responseValidation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"responseValidation.js","sourceRoot":"","sources":["../../../src/core/processing/responseValidation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAEN,yBAAyB,EACzB,kBAAkB,GAClB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAA0B,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AAgD/F,MAAM,uBAAuB,GAAkD;IAC9E,qBAAqB,EAAE;QACtB,kFAAkF;QAClF,qCAAqC;QACrC,aAAa,EAAE,IAAI;KACnB;IACD,gBAAgB,EAAE;QACjB,gFAAgF;QAChF,kDAAkD;QAClD,oBAAoB,EAAE,CAAC,KAAK,EAAE,WAAW,EAAE,EAAE,CAC5C,MAAM,CAAC,KAAK,IAAI,CAAC,CAAC,IAAI,MAAM,CAAC,WAAW,CAAC,QAAQ,IAAI,CAAC,CAAC;QACxD,cAAc,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,IAAI,CAAC,CAAC,GAAG,CAAC;KACjD;IACD,uBAAuB,EAAE;QACxB,+EAA+E;QAC/E,iCAAiC;QACjC,WAAW,EAAE,CAAC,UAAU,EAAE,KAAK,EAAE,WAAW,EAAE,iBAAiB,EAAE,EAAE,CAClE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;YACpB,MAAM,CAAC,WAAW,CAAC,UAAU,IAAI,CAAC,CAAC,GAAG,CAAC;YACvC,KAAK,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC,MAAM,GAAG,MAAM,CAAC,WAAW,CAAC,UAAU,CAAC;YACtE,CAAC,CAAC,CAAC,aAAa,UAAU,wBAAwB,WAAW,CAAC,UAAU,EAAE,CAAC;YAC3E,CAAC,CAAC,EAAE;KACN;CACD,CAAC;AAEF,SAAS,qBAAqB,CAAC,W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,CAAC,CAAC,MAAM,CAAC;YAChF,IAAI,KAAK,GAAG,QAAQ,EAAE,CAAC;gBACtB,MAAM,CAAC,IAAI,CAAC,aAAa,UAAU,UAAU,MAAM,CAAC,UAAU,OAAO,KAAK,qCAAqC,QAAQ,EAAE,CAAC,CAAC;YAC5H,CAAC;QACF,CAAC;IACF,CAAC,CAAC;IACF,aAAa,CAAC,CAAC,GAAG,CAAC,WAAW,CAAC,QAAQ,IAAI,EAAE,CAAC,EAAE,GAAG,CAAC,WAAW,CAAC,SAAS,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IACtF,aAAa,CAAC,WAAW,CAAC,QAAQ,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC;IAC7C,OAAO,MAAM,CAAC;AACf,CAAC;AAED;;;GAGG;AACH,SAAS,sBAAsB,CAAC,WAM/B;IACA,MAAM,OAAO,GACZ,WAAW,CAAC,IAAI,KAAK,kBAAkB;QACtC,CAAC,CAAC,WAAW,CAAC,OAAO;QACrB,CAAC,CAAC,WAAW,CAAC,IAAI,KAAK,yBAAyB;YAC/C,CAAC,CAAC,WAAW,CAAC,cAAc;YAC5B,CAAC,CAAC,SAAS,CAAC;IACf,IAAI,CAAC,OAAO;QAAE,OAAO,IAAI,CAAC;IAC1B,OAAO,iBAAiB,CAAC;QACxB,UAAU,EAAE,WAAW,CAAC,UAAU;QAClC,UAAU,EAAE,WAAW,CAAC,UAAU;QAClC,WAAW,EAAE,OAAO,CAAC,MAAM;KAC3B,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Response validation: the field checks every interaction's response must satisfy, and\n * the end-attempt gate that additionally rejects incomplete required responses.\n *\n * The generic checks run for every interaction, reading the interaction-shaped fields\n * (minChoices, matchMin, requiredGaps, patternMask, matchGroup) from the delivered\n * interaction data. The per-type entries below (TYPE_VALIDATION_ENTRIES) only restate\n * today's special cases — media minPlays, endAttempt never-required, extendedText\n * maxStrings — keyed on the delivered interaction type (the extractor's output type, so\n * vendor overrides such as acme-likert delivering `choiceInteraction` keep the generic\n * checks); no entry adds a constraint.\n */\nimport {\n\ttype DeclarationMap,\n\tisPatternSubjectWithinCap,\n\txsdPatternToRegExp,\n} from '@pie-qti/qti-processing';\nimport type { MatchGroupConstraints } from '../matchGroups.js';\nimport { findMatchGroupViolations } from '../matchGroups.js';\nimport { type OrderChoiceLimits, orderChoiceLimits } from '../../interactions/order/limits.js';\nimport type { ResponseValidationResult } from '../../types/responseValidation.js';\n\n/** What response validation reads from the session engine. */\nexport interface ResponseValidationHost {\n\treadonly decls: DeclarationMap;\n\t/** matchGroup constraints of the item's pairing interactions, by response identifier. */\n\treadonly matchGroupConstraints: ReadonlyMap<string, MatchGroupConstraints>;\n\tgetInteractions(): Array<{ type: string; responseIdentifier: string } & Record<string, any>>;\n\tgetResponseInteractions(): Array<{ type: string; responseIdentifier: string } & Record<string, any>>;\n}\n\n/**\n * The interaction-shaped data validation reads generically (whatever fields an interaction's\n * delivered data carries).\n */\ntype InteractionData = { type: string; responseIdentifier: string } & Record<string, any>;\n\n/**\n * Per-type validation entries. Keyed on the delivered interaction `type` — the extractor's\n * output type, so a vendor override that delivers its own type (or a standard type with its\n * own data, such as acme-likert delivering `choiceInteraction`) gets exactly the entry its\n * delivered type names, and the generic field checks either way.\n *\n * Each entry only RESTATES a special case today's validation applies: an end-attempt\n * interaction is never required, a media interaction's required response completes at\n * `minPlays`, and an extended-text response over `maxStrings` is a shape error. An entry adds\n * no constraint of its own; a type with no entry runs the generic checks only.\n */\ninterface TypeValidationEntry {\n\t/** True makes the interaction never required, whatever its data carries. */\n\tneverRequired?: boolean;\n\t/**\n\t * Completeness of a REQUIRED response; absent means the generic container/record/scalar\n\t * rule (a meaningful entry, at least the minimums, at least every matchMin).\n\t */\n\tcompleteWhenRequired?(value: unknown, interaction: InteractionData): boolean;\n\t/** Extra shape errors the delivered data adds, before the matchGroup check. */\n\tshapeErrors?(\n\t\tresponseId: string,\n\t\tvalue: unknown,\n\t\tinteraction: InteractionData,\n\t\tisMeaningfulEntry: (entry: unknown) => boolean,\n\t): string[];\n\t/** Attempted-state reading for this interaction; absent means the generic rule. */\n\tattemptedValue?(value: unknown): boolean;\n}\n\nconst TYPE_VALIDATION_ENTRIES: Readonly<Record<string, TypeValidationEntry>> = {\n\tendAttemptInteraction: {\n\t\t// An end-attempt interaction invokes response processing; it carries no candidate\n\t\t// answer to require (QTI 3.0 §5.45).\n\t\tneverRequired: true,\n\t},\n\tmediaInteraction: {\n\t\t// A media interaction is answered at minPlays plays, not by any non-null value:\n\t\t// its response is the play count (QTI 3.0 §5.69).\n\t\tcompleteWhenRequired: (value, interaction) =>\n\t\t\tNumber(value || 0) >= Number(interaction.minPlays || 0),\n\t\tattemptedValue: (value) => Number(value || 0) > 0,\n\t},\n\textendedTextInteraction: {\n\t\t// maxStrings caps the strings of a multiple-cardinality extended-text response\n\t\t// (QTI 2.1 §5.8; QTI 3.0 §5.81).\n\t\tshapeErrors: (responseId, value, interaction, isMeaningfulEntry) =>\n\t\t\tArray.isArray(value) &&\n\t\t\tNumber(interaction.maxStrings ?? 0) > 0 &&\n\t\t\tvalue.filter(isMeaningfulEntry).length > Number(interaction.maxStrings)\n\t\t\t\t? [`Response '${responseId}' exceeds maxStrings=${interaction.maxStrings}`]\n\t\t\t\t: [],\n\t},\n};\n\nfunction typeValidationEntryOf(interaction: InteractionData): TypeValidationEntry | undefined {\n\treturn TYPE_VALIDATION_ENTRIES[interaction.type];\n}\n\nexport function validateResponses(host: ResponseValidationHost, responses: Record<string, any>): ResponseValidationResult {\n\tconst interactions = host.getInteractions();\n\tconst entries: ResponseValidationResult['entries'] = {};\n\tconst issues: ResponseValidationResult['issues'] = [];\n\n\tfor (const i of interactions) {\n\t\tconst responseId = i.responseIdentifier;\n\t\tconst decl = host.decls[responseId];\n\t\tconst value = responses[responseId];\n\t\tconst isMeaningfulEntry = (entry: unknown): boolean => isMeaningfulResponseEntry(entry, i);\n\n\t\tconst constrainedChoices: Array<{ identifier: string; matchMin?: number }> = [\n\t\t\t...(i.choices ?? []),\n\t\t\t...(i.gapTexts ?? []),\n\t\t\t...(i.gapImages ?? []),\n\t\t\t...(i.sourceSet ?? []),\n\t\t\t...(i.targetSet ?? []),\n\t\t\t...(i.associableHotspots ?? []),\n\t\t\t// graphicGapMatch delivers its hotspots as `hotspots` (graphic-associate\n\t\t\t// delivers the same element as `associableHotspots`); both carry matchMin.\n\t\t\t...(i.hotspots ?? []),\n\t\t];\n\t\tconst minimum = Math.max(\n\t\t\t0,\n\t\t\tNumber(i.minChoices ?? 0),\n\t\t\tNumber(i.minAssociations ?? 0),\n\t\t\tNumber(i.minStrings ?? 0),\n\t\t\tNumber(i.minPlays ?? 0),\n\t\t);\n\t\t// gap `required` (QTI 2.1 gap; QTI 3.0 §5.55.5): \"this gap must be filled by the candidate\n\t\t// in order to form a valid response to the interaction\".\n\t\tconst requiredGaps: string[] = Array.isArray(i.requiredGaps) ? i.requiredGaps : [];\n\t\tconst typeEntry = typeValidationEntryOf(i);\n\t\tconst required =\n\t\t\t!typeEntry?.neverRequired &&\n\t\t\t(minimum > 0 ||\n\t\t\t\trequiredGaps.length > 0 ||\n\t\t\t\tconstrainedChoices.some((choice) => Number(choice.matchMin ?? 0) > 0));\n\n\t\tlet complete = !required;\n\t\tif (required && typeEntry?.completeWhenRequired) {\n\t\t\tcomplete = typeEntry.completeWhenRequired(value, i);\n\t\t} else if (required) {\n\t\t\tif (Array.isArray(value)) {\n\t\t\t\tconst nonEmptyValues = value.filter(isMeaningfulEntry);\n\t\t\t\tcomplete = nonEmptyValues.length > 0;\n\t\t\t\t// Enforce minChoices / minAssociations where applicable\n\t\t\t\t\tconst minChoices = Math.max(\n\t\t\t\t\t\tNumber(i.minChoices ?? 0),\n\t\t\t\t\t\tNumber(i.minAssociations ?? 0),\n\t\t\t\t\t\tNumber(i.minStrings ?? 0),\n\t\t\t\t\t);\n\t\t\t\tif (complete && minChoices > 0) {\n\t\t\t\t\tcomplete = nonEmptyValues.length >= minChoices;\n\t\t\t\t}\n\t\t\t\t// Enforce matchMin per-choice: each pairing entry \"id1 id2\" in value must\n\t\t\t\t// appear at least matchMin times for the relevant choice.\n\t\t\t\t// Collect all choice arrays that can carry matchMin across all pairing interaction types.\n\t\t\t\t\tfor (const choice of constrainedChoices) {\n\t\t\t\t\tconst min = Number(choice.matchMin || 0);\n\t\t\t\t\tif (min > 0) {\n\t\t\t\t\t\tconst count = (value as string[]).filter((p) => {\n\t\t\t\t\t\t\tconst parts = p.split(' ');\n\t\t\t\t\t\t\treturn parts[0] === choice.identifier || parts[1] === choice.identifier;\n\t\t\t\t\t\t}).length;\n\t\t\t\t\t\tif (count < min) {\n\t\t\t\t\t\t\tcomplete = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (decl?.cardinality === 'record') {\n\t\t\t\tconst stringValue = value && typeof value === 'object'\n\t\t\t\t\t? (value as Record<string, unknown>).stringValue\n\t\t\t\t\t: undefined;\n\t\t\t\tcomplete = isMeaningfulEntry(stringValue);\n\t\t\t} else {\n\t\t\t\tcomplete = isMeaningfulEntry(value);\n\t\t\t}\n\t\t}\n\n\t\t// A gap-match response pairs \"gapText gap\": each required gap must be the target of a pair.\n\t\tif (requiredGaps.length > 0) {\n\t\t\tconst filled = new Set(\n\t\t\t\t(Array.isArray(value) ? value.filter(isMeaningfulEntry) : []).map((pair) => String(pair).split(' ')[1]),\n\t\t\t);\n\t\t\tif (requiredGaps.some((gap) => !filled.has(gap))) complete = false;\n\t\t}\n\n\t\t// orderInteraction / graphicOrderInteraction: an order that has begun is complete once it\n\t\t// holds the minimum its mode sets — every choice when no subset is requested (minChoices\n\t\t// unspecified: \"all of the choices must be ordered\"), at least minChoices when one is.\n\t\t// An untouched order stays a skip, as before, which allowSkipping governs.\n\t\tconst orderLimits = orderInteractionLimits(i);\n\t\tconst orderedCount = orderLimits && Array.isArray(value) ? value.filter(isMeaningfulEntry).length : 0;\n\t\tif (orderLimits && orderedCount > 0) {\n\t\t\tcomplete = orderedCount >= orderLimits.minOrdered;\n\t\t}\n\n\t\tconst errors: string[] = [];\n\t\tconst warnings: string[] = [];\n\n\t\tif (decl) {\n\t\t\tif (decl.cardinality === 'multiple' || decl.cardinality === 'ordered') {\n\t\t\t\tif (!(value === null || value === undefined || Array.isArray(value))) {\n\t\t\t\t\terrors.push(`Expected an array for ${decl.cardinality} response '${responseId}'`);\n\t\t\t\t}\n\t\t\t} else if (decl.cardinality === 'record') {\n\t\t\t\tif (!(value === null || value === undefined || (typeof value === 'object' && !Array.isArray(value)))) {\n\t\t\t\t\terrors.push(`Expected an object for record response '${responseId}'`);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (Array.isArray(value)) {\n\t\t\t\t\terrors.push(`Expected a single value for response '${responseId}'`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (typeEntry?.shapeErrors) {\n\t\t\terrors.push(...typeEntry.shapeErrors(responseId, value, i, isMeaningfulEntry));\n\t\t}\n\t\t// patternMask (QTI 2.1; QTI 3.0 §5.48.4, §5.162.5): \"a regular expression that the\n\t\t// candidate's response must match in order to be considered valid\", in XSD syntax. A string\n\t\t// response holds the text as entered; a numeric one does not, and its input checks the text.\n\t\tconst patternMask = typeof i.patternMask === 'string' ? xsdPatternToRegExp(i.patternMask) : null;\n\t\tif (patternMask && decl?.baseType === 'string') {\n\t\t\tconst entered = (Array.isArray(value) ? value : [value]).filter(\n\t\t\t\t(text): text is string => typeof text === 'string' && text !== '',\n\t\t\t);\n\t\t\t// A response beyond the documented subject cap (see the pattern subject cap in\n\t\t\t// @pie-qti/qti-processing) skips the mask instead of running authored regex over it:\n\t\t\t// it passes unmasked rather than risking a hang on a pathological pattern.\n\t\t\tif (entered.filter(isPatternSubjectWithinCap).some((text) => !patternMask.test(text))) {\n\t\t\t\terrors.push(`Response '${responseId}' does not match its patternMask`);\n\t\t\t}\n\t\t}\n\t\t// The order-subset cap: when a subset is requested, a restored or programmatic response\n\t\t// may not order more than maxChoices (clamped to the choices); the delivered UI refuses it.\n\t\tif (orderLimits?.subset && orderedCount > orderLimits.maxOrdered) {\n\t\t\terrors.push(`Response '${responseId}' exceeds maxChoices=${orderLimits.maxOrdered}`);\n\t\t}\n\t\t// graphicGapMatch maxima: the delivered interface does not cap them all, so a response\n\t\t// built or restored over a limit is checked here.\n\t\tif (i.type === 'graphicGapMatchInteraction' && Array.isArray(value)) {\n\t\t\terrors.push(\n\t\t\t\t...graphicGapMatchMaximaErrors(responseId, value.filter(isMeaningfulEntry), {\n\t\t\t\t\tmaxAssociations: i.maxAssociations,\n\t\t\t\t\tgapTexts: i.gapTexts,\n\t\t\t\t\tgapImages: i.gapImages,\n\t\t\t\t\thotspots: i.hotspots,\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\t// gapMatch maxAssociations (0 = no restriction): the delivered interface refuses a\n\t\t// placement past it; a restored or programmatic response over it is checked here.\n\t\tconst gapMatchMax = i.type === 'gapMatchInteraction' ? Number(i.maxAssociations ?? 0) : 0;\n\t\tif (gapMatchMax > 0 && Array.isArray(value) && value.filter(isMeaningfulEntry).length > gapMatchMax) {\n\t\t\terrors.push(`Response '${responseId}' exceeds maxAssociations=${gapMatchMax}`);\n\t\t}\n\t\tconst shapeErrorCount = errors.length;\n\n\t\t// matchGroup restricts which choices may pair. The renderers enforce it while the\n\t\t// candidate works; a restored or programmatic response is checked here.\n\t\tconst matchGroups = host.matchGroupConstraints.get(responseId);\n\t\tif (matchGroups) {\n\t\t\tfor (const pair of findMatchGroupViolations(value, matchGroups)) {\n\t\t\t\terrors.push(`Response '${responseId}' pairs ${pair.replace(' ', ' with ')}, which matchGroup does not allow`);\n\t\t\t}\n\t\t}\n\n\t\tconst valid = errors.length === 0;\n\t\tentries[responseId] = {\n\t\t\tresponseId,\n\t\t\tinteractionType: i.type,\n\t\t\trequired,\n\t\t\tcomplete,\n\t\t\tvalid,\n\t\t\terrors,\n\t\t\twarnings,\n\t\t};\n\n\t\terrors.forEach((e, index) => {\n\t\t\tissues.push({\n\t\t\t\tresponseId,\n\t\t\t\tcode: index < shapeErrorCount ? 'invalid_shape' : 'match_group',\n\t\t\t\tmessage: e,\n\t\t\t\tseverity: 'error',\n\t\t\t});\n\t\t});\n\t}\n\n\tconst allValid = Object.values(entries).every((e) => e.valid);\n\treturn { valid: allValid, entries, issues };\n}\n\n/**\n * The validation the end attempt with `validateResponses` gates on (QTI ASI §4\n * itemSessionControl validateResponses). An invalid response \"does not satisfy the\n * constraints imposed by the interaction\": beyond a malformed value or a matchGroup\n * pairing (`validateResponses`), an interaction that requires input — minChoices,\n * minAssociations, minStrings, minPlays, matchMin — rejects an incomplete one. Those\n * entries turn invalid with an `incomplete` issue, so the result reads invalid through\n * the same channel as every other rejection.\n *\n * An item with no response at all is a skip, which allowSkipping governs (\"delivery\n * engines must ensure that the candidate can choose to submit no response\" when it is\n * true). The item cannot see allowSkipping, so completeness applies only once the\n * candidate has responded and a skip is the caller's decision.\n */\nexport function validateAttemptResponses(host: ResponseValidationHost, responses: Record<string, any>): ResponseValidationResult {\n\tconst validation = validateResponses(host, responses);\n\tif (!isAttempted(host, responses)) return validation;\n\tconst entries: ResponseValidationResult['entries'] = {};\n\tconst issues = [...validation.issues];\n\tfor (const entry of Object.values(validation.entries)) {\n\t\tif (entry.complete) {\n\t\t\tentries[entry.responseId] = entry;\n\t\t\tcontinue;\n\t\t}\n\t\tconst message = `Response '${entry.responseId}' does not satisfy the constraints of its ${entry.interactionType}`;\n\t\tentries[entry.responseId] = { ...entry, valid: false, errors: [...entry.errors, message] };\n\t\tissues.push({ responseId: entry.responseId, code: 'incomplete', message, severity: 'error' });\n\t}\n\treturn { valid: Object.values(entries).every((e) => e.valid), entries, issues };\n}\n\nexport function isAttempted(host: ResponseValidationHost, responses: Record<string, any>): boolean {\n\tfor (const i of host.getResponseInteractions()) {\n\t\tconst id = i.responseIdentifier;\n\t\tconst v = responses[id];\n\t\tconst isMeaningful = (entry: unknown): boolean => isMeaningfulResponseEntry(entry, i);\n\t\tconst attemptedValue = typeValidationEntryOf(i)?.attemptedValue;\n\t\tif (attemptedValue) {\n\t\t\tif (attemptedValue(v)) return true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (Array.isArray(v)) {\n\t\t\tif (v.some(isMeaningful)) return true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (v && typeof v === 'object') {\n\t\t\tconst record = v as Record<string, unknown>;\n\t\t\tif (\n\t\t\t\tObject.values(record).some(isMeaningful)\n\t\t\t) return true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (isMeaningful(v)) return true;\n\t}\n\treturn false;\n}\n\n/**\n * True when a response entry carries meaningful learner input. Extended-text items\n * authored as XHTML are stripped to plain text first, so markup-only answers do not\n * count as \"answered\". Shared by response validation and attempted-state tracking.\n */\nexport function isMeaningfulResponseEntry(\n\tentry: unknown,\n\tinteraction: { type?: string; format?: string },\n): boolean {\n\tif (entry === null || entry === undefined) return false;\n\tif (typeof entry !== 'string') return true;\n\tconst comparable = interaction.type === 'extendedTextInteraction' && interaction.format === 'xhtml'\n\t\t? entry.replace(/<[^>]*>/g, '').replace(/&nbsp;|&#160;/gi, ' ')\n\t\t: entry;\n\treturn comparable.trim().length > 0;\n}\n\n/**\n * The graphicGapMatchInteraction maxima a response breaks (QTI ASI graphicGapMatchInteraction,\n * gapChoice and associableHotspot): at most `maxAssociations` associations, and each gap choice\n * (gapText, gapImg) and each hotspot in at most its `matchMax` associations; 0 means no\n * restriction. Associations are directed pairs \"choice hotspot\"; other entries count towards\n * `maxAssociations` only.\n */\nfunction graphicGapMatchMaximaErrors(\n\tresponseId: string,\n\tentries: readonly unknown[],\n\tinteraction: {\n\t\tmaxAssociations?: number;\n\t\tgapTexts?: ReadonlyArray<{ identifier: string; matchMax?: number }>;\n\t\tgapImages?: ReadonlyArray<{ identifier: string; matchMax?: number }>;\n\t\thotspots?: ReadonlyArray<{ identifier: string; matchMax?: number }>;\n\t},\n): string[] {\n\tconst errors: string[] = [];\n\tconst maxAssociations = Number(interaction.maxAssociations ?? 0);\n\tif (maxAssociations > 0 && entries.length > maxAssociations) {\n\t\terrors.push(`Response '${responseId}' exceeds maxAssociations=${maxAssociations}`);\n\t}\n\tconst pairs = entries\n\t\t.filter((entry): entry is string => typeof entry === 'string')\n\t\t.map((entry) => entry.trim().split(/\\s+/))\n\t\t.filter((parts) => parts.length === 2);\n\tconst checkMatchMax = (choices: ReadonlyArray<{ identifier: string; matchMax?: number }>, side: 0 | 1): void => {\n\t\tfor (const choice of choices) {\n\t\t\tconst matchMax = Number(choice.matchMax ?? 0);\n\t\t\tif (!(matchMax > 0)) continue;\n\t\t\tconst count = pairs.filter((parts) => parts[side] === choice.identifier).length;\n\t\t\tif (count > matchMax) {\n\t\t\t\terrors.push(`Response '${responseId}' uses ${choice.identifier} in ${count} associations, more than matchMax=${matchMax}`);\n\t\t\t}\n\t\t}\n\t};\n\tcheckMatchMax([...(interaction.gapTexts ?? []), ...(interaction.gapImages ?? [])], 0);\n\tcheckMatchMax(interaction.hotspots ?? [], 1);\n\treturn errors;\n}\n\n/**\n * The order-subset limits of an orderInteraction or graphicOrderInteraction (QTI ASI §5.73,\n * §5.42), read with the same rule the order renderers use; null for any other interaction.\n */\nfunction orderInteractionLimits(interaction: {\n\ttype?: string;\n\tminChoices?: number;\n\tmaxChoices?: number;\n\tchoices?: readonly unknown[];\n\thotspotChoices?: readonly unknown[];\n}): OrderChoiceLimits | null {\n\tconst choices =\n\t\tinteraction.type === 'orderInteraction'\n\t\t\t? interaction.choices\n\t\t\t: interaction.type === 'graphicOrderInteraction'\n\t\t\t\t? interaction.hotspotChoices\n\t\t\t\t: undefined;\n\tif (!choices) return null;\n\treturn orderChoiceLimits({\n\t\tminChoices: interaction.minChoices,\n\t\tmaxChoices: interaction.maxChoices,\n\t\tchoiceCount: choices.length,\n\t});\n}\n"]}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The item content pass: the handlers that resolve printed variables, template-shown
3
+ * choices, param variables and MathML template variables against the session's current
4
+ * values while item body, rubric and feedback content serializes.
5
+ */
6
+ import { type DeclarationContext } from '@pie-qti/qti-processing';
7
+ import { type ElementNameMapper } from '@pie-qti/qti-common';
8
+ import { type ContentHandlers } from '../../document/contentPass.js';
9
+ import type { AssessmentItemDocument } from '../../document/AssessmentItemDocument.js';
10
+ /** Choices a template variable can show or hide, by canonical name. */
11
+ export declare const TEMPLATE_CHOICES: readonly ["simplechoice", "simpleassociablechoice", "gaptext", "gapimg", "gap", "hottext", "inlinechoice", "hotspotchoice", "associablehotspot"];
12
+ /** What the content pass reads from the session engine. */
13
+ export interface ContentPassHost {
14
+ readonly itemDocument: AssessmentItemDocument;
15
+ readonly mapper: ElementNameMapper;
16
+ readonly ctx: DeclarationContext;
17
+ /** Template variables declared with `mathVariable`, substituted into MathML. */
18
+ mathVariableIds: ReadonlySet<string> | null;
19
+ /** Template variables declared with `paramVariable`, substituted into `<param>` values. */
20
+ paramVariableIds: ReadonlySet<string> | null;
21
+ }
22
+ /**
23
+ * The item content pass's handlers, reading the session's current variable values. QTI 3 wraps
24
+ * rubric content in `qti-content-body`, which is unwrapped so a rubric renders as in QTI 2.2.
25
+ * Feedback resolves here for rubric and modal feedback content; item body and choice feedback
26
+ * resolve in presentation, which takes the outcome values to present as input.
27
+ */
28
+ export declare function contentHandlers(host: ContentPassHost, { feedback }?: {
29
+ feedback?: boolean;
30
+ }): ContentHandlers;
31
+ export declare function mathVariables(host: ContentPassHost): ReadonlySet<string>;
@@ -0,0 +1,152 @@
1
+ /**
2
+ * The item content pass: the handlers that resolve printed variables, template-shown
3
+ * choices, param variables and MathML template variables against the session's current
4
+ * values while item body, rubric and feedback content serializes.
5
+ */
6
+ import { getAttr, isElement, localName, } from '@pie-qti/qti-processing';
7
+ import { isShownByIdentifier } from '@pie-qti/qti-common';
8
+ import { printVariable, readPrintedVariableOptions } from '../../document/printedVariable.js';
9
+ /** Choices a template variable can show or hide, by canonical name. */
10
+ export const TEMPLATE_CHOICES = [
11
+ 'simplechoice',
12
+ 'simpleassociablechoice',
13
+ 'gaptext',
14
+ 'gapimg',
15
+ 'gap',
16
+ 'hottext',
17
+ 'inlinechoice',
18
+ 'hotspotchoice',
19
+ 'associablehotspot',
20
+ ];
21
+ /**
22
+ * The item content pass's handlers, reading the session's current variable values. QTI 3 wraps
23
+ * rubric content in `qti-content-body`, which is unwrapped so a rubric renders as in QTI 2.2.
24
+ * Feedback resolves here for rubric and modal feedback content; item body and choice feedback
25
+ * resolve in presentation, which takes the outcome values to present as input.
26
+ */
27
+ export function contentHandlers(host, { feedback = true } = {}) {
28
+ const conditional = (variable) => (element) => isShownByVariable(host, element, variable, getAttr(element, 'identifier')) ? Array.from(element.childNodes) : [];
29
+ const handlers = new Map([
30
+ ['printedvariable', (element) => printedVariableNodes(host, element)],
31
+ ['contentbody', (element) => Array.from(element.childNodes)],
32
+ ['templateinline', conditional('templateIdentifier')],
33
+ ['templateblock', conditional('templateIdentifier')],
34
+ ['param', (element) => expandParamVariable(host, element)],
35
+ ]);
36
+ for (const choice of TEMPLATE_CHOICES) {
37
+ handlers.set(choice, (element) => !getAttr(element, 'templateIdentifier') ||
38
+ isShownByVariable(host, element, 'templateIdentifier', getAttr(element, 'identifier'))
39
+ ? undefined
40
+ : []);
41
+ }
42
+ if (mathVariables(host).size > 0) {
43
+ handlers.set('mi', (element) => mathVariableNodes(host, element, 'mn'));
44
+ handlers.set('ci', (element) => mathVariableNodes(host, element, 'cn'));
45
+ }
46
+ if (feedback) {
47
+ handlers.set('feedbackinline', conditional('outcomeIdentifier'));
48
+ handlers.set('feedbackblock', conditional('outcomeIdentifier'));
49
+ }
50
+ return handlers;
51
+ }
52
+ /**
53
+ * Whether `element` shows: the variable named by its `variableAttribute` against `identifier`,
54
+ * by the shared visibility rule. A missing variable or identifier hides it.
55
+ */
56
+ function isShownByVariable(host, element, variableAttribute, identifier) {
57
+ const variable = (getAttr(element, variableAttribute) || '').trim();
58
+ const id = (identifier || '').trim();
59
+ if (!variable || !id)
60
+ return false;
61
+ const current = host.ctx.getValue(variable);
62
+ return isShownByIdentifier(current.kind === 'value' ? current.value : null, id, getAttr(element, 'showHide'));
63
+ }
64
+ export function mathVariables(host) {
65
+ host.mathVariableIds ?? (host.mathVariableIds = new Set(host.itemDocument
66
+ .findDeclarationElements('template')
67
+ .filter((el) => getAttr(el, 'mathVariable')?.trim() === 'true')
68
+ .map((el) => (getAttr(el, 'identifier') || '').trim())));
69
+ return host.mathVariableIds;
70
+ }
71
+ function paramVariables(host) {
72
+ host.paramVariableIds ?? (host.paramVariableIds = new Set(host.itemDocument
73
+ .findDeclarationElements('template')
74
+ .filter((el) => getAttr(el, 'paramVariable')?.trim() === 'true')
75
+ .map((el) => (getAttr(el, 'identifier') || '').trim())));
76
+ return host.paramVariableIds;
77
+ }
78
+ /**
79
+ * templateDeclaration@paramVariable (QTI 2.2 ASI TemplateDeclaration, `paramVariable`
80
+ * characteristic; QTI 3.0 `param-variable`): a `<param>` inside an `<object>` whose `value`
81
+ * names such a template variable is delivered with the variable's current value in place of
82
+ * the variable's name, so a plugin-style object receives its computed parameter instead of a
83
+ * literal.
84
+ *
85
+ * This resolves in the content pass — not in `prepareContentMarkup` (which runs once on the
86
+ * raw XML, before template variables exist) and not on a stored copy — because template
87
+ * variables change during the session (`setTemplateVariables`, `newTemplate`, restore).
88
+ * Resolving with the pass means every (re)render, like printedVariable, delivers the value
89
+ * the session holds at that moment.
90
+ *
91
+ * The spec defines substitution for a param value naming a declared `paramVariable`
92
+ * variable. It is silent on a value naming an undeclared variable or one without the flag:
93
+ * those, and NULL or container (multiple/ordered/record) values — a param carries one
94
+ * opaque string, and joining container values would be invented semantics — deliver the
95
+ * authored value unchanged, which is also the safe reading.
96
+ */
97
+ function expandParamVariable(host, element) {
98
+ const value = getAttr(element, 'value')?.trim();
99
+ if (!value || !paramVariables(host).has(value))
100
+ return undefined;
101
+ const parent = element.parentNode;
102
+ if (!isElement(parent) ||
103
+ host.mapper.toCanonical(localName(parent) ?? '') !== 'object') {
104
+ return undefined;
105
+ }
106
+ const current = host.ctx.getValue(value);
107
+ if (current.kind !== 'value' || current.cardinality !== 'single')
108
+ return undefined;
109
+ // The pass resolves a clone, so this rewrite cannot touch the parsed source.
110
+ element.setAttribute('value', String(current.value));
111
+ return undefined;
112
+ }
113
+ /**
114
+ * A MathML `mi` or `ci` naming a math variable, with the variable's single value in its place:
115
+ * a number as `mn` or `cn` (`numberName`), any other value as the element's text. NULL and
116
+ * container values leave the element as authored.
117
+ */
118
+ function mathVariableNodes(host, element, numberName) {
119
+ const identifier = (element.textContent || '').trim();
120
+ const document = element.ownerDocument;
121
+ if (!document || !mathVariables(host).has(identifier))
122
+ return undefined;
123
+ const value = host.ctx.getValue(identifier);
124
+ if (value.kind !== 'value' || value.cardinality !== 'single')
125
+ return undefined;
126
+ const text = String(value.value);
127
+ if (value.baseType !== 'integer' && value.baseType !== 'float') {
128
+ // The pass resolves a copy, and the element is not walked again, so this cannot cycle.
129
+ element.textContent = text;
130
+ return undefined;
131
+ }
132
+ const name = element.prefix ? `${element.prefix}:${numberName}` : numberName;
133
+ const replacement = document.createElementNS(element.namespaceURI, name);
134
+ replacement.appendChild(document.createTextNode(text));
135
+ return [replacement];
136
+ }
137
+ function printedVariableNodes(host, element) {
138
+ const identifier = (getAttr(element, 'identifier') || '').trim();
139
+ const document = element.ownerDocument;
140
+ if (!identifier || !document)
141
+ return [];
142
+ const variable = (id) => host.ctx.getValue(id);
143
+ const printed = printVariable(variable(identifier), readPrintedVariableOptions(element, variable));
144
+ return printed.map((segment) => {
145
+ if (typeof segment === 'string')
146
+ return document.createTextNode(segment);
147
+ const sup = document.createElementNS(element.namespaceURI, 'sup');
148
+ sup.appendChild(document.createTextNode(segment.superscript));
149
+ return sup;
150
+ });
151
+ }
152
+ //# sourceMappingURL=contentPass.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contentPass.js","sourceRoot":"","sources":["../../../src/core/rendering/contentPass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AAE,0BAA0B,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC;IACnG,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE;QAC9B,IAAI,OAAO,OAAO,KAAK,QAAQ;YAAE,OAAO,QAAQ,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;QACzE,MAAM,GAAG,GAAG,QAAQ,CAAC,eAAe,CAAC,OAAO,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;QAClE,GAAG,CAAC,WAAW,CAAC,QAAQ,CAAC,cAAc,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC;QAC9D,OAAO,GAAG,CAAC;IACZ,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The item content pass: the handlers that resolve printed variables, template-shown\n * choices, param variables and MathML template variables against the session's current\n * values while item body, rubric and feedback content serializes.\n */\nimport {\n\ttype DeclarationContext,\n\tgetAttr,\n\tisElement,\n\tlocalName,\n\ttype QtiValue,\n} from '@pie-qti/qti-processing';\nimport { type ElementNameMapper, isShownByIdentifier } from '@pie-qti/qti-common';\nimport { type ContentHandler, type ContentHandlers } from '../../document/contentPass.js';\nimport { printVariable, readPrintedVariableOptions } from '../../document/printedVariable.js';\nimport type { AssessmentItemDocument } from '../../document/AssessmentItemDocument.js';\n\n/** Choices a template variable can show or hide, by canonical name. */\nexport const TEMPLATE_CHOICES = [\n\t'simplechoice',\n\t'simpleassociablechoice',\n\t'gaptext',\n\t'gapimg',\n\t'gap',\n\t'hottext',\n\t'inlinechoice',\n\t'hotspotchoice',\n\t'associablehotspot',\n] as const;\n\n/** What the content pass reads from the session engine. */\nexport interface ContentPassHost {\n\treadonly itemDocument: AssessmentItemDocument;\n\treadonly mapper: ElementNameMapper;\n\treadonly ctx: DeclarationContext;\n\t/** Template variables declared with `mathVariable`, substituted into MathML. */\n\tmathVariableIds: ReadonlySet<string> | null;\n\t/** Template variables declared with `paramVariable`, substituted into `<param>` values. */\n\tparamVariableIds: ReadonlySet<string> | null;\n}\n\n/**\n * The item content pass's handlers, reading the session's current variable values. QTI 3 wraps\n * rubric content in `qti-content-body`, which is unwrapped so a rubric renders as in QTI 2.2.\n * Feedback resolves here for rubric and modal feedback content; item body and choice feedback\n * resolve in presentation, which takes the outcome values to present as input.\n */\nexport function contentHandlers(host: ContentPassHost, { feedback = true }: { feedback?: boolean } = {}): ContentHandlers {\n\tconst conditional = (variable: string) => (element: Element) =>\n\t\tisShownByVariable(host, element, variable, getAttr(element, 'identifier')) ? Array.from(element.childNodes) : [];\n\tconst handlers = new Map<string, ContentHandler>([\n\t\t['printedvariable', (element) => printedVariableNodes(host, element)],\n\t\t['contentbody', (element) => Array.from(element.childNodes)],\n\t\t['templateinline', conditional('templateIdentifier')],\n\t\t['templateblock', conditional('templateIdentifier')],\n\t\t['param', (element) => expandParamVariable(host, element)],\n\t]);\n\tfor (const choice of TEMPLATE_CHOICES) {\n\t\thandlers.set(choice, (element) =>\n\t\t\t!getAttr(element, 'templateIdentifier') ||\n\t\t\tisShownByVariable(host, element, 'templateIdentifier', getAttr(element, 'identifier'))\n\t\t\t\t? undefined\n\t\t\t\t: [],\n\t\t);\n\t}\n\tif (mathVariables(host).size > 0) {\n\t\thandlers.set('mi', (element) => mathVariableNodes(host, element, 'mn'));\n\t\thandlers.set('ci', (element) => mathVariableNodes(host, element, 'cn'));\n\t}\n\tif (feedback) {\n\t\thandlers.set('feedbackinline', conditional('outcomeIdentifier'));\n\t\thandlers.set('feedbackblock', conditional('outcomeIdentifier'));\n\t}\n\treturn handlers;\n}\n\n/**\n * Whether `element` shows: the variable named by its `variableAttribute` against `identifier`,\n * by the shared visibility rule. A missing variable or identifier hides it.\n */\nfunction isShownByVariable(host: ContentPassHost, element: Element, variableAttribute: string, identifier: string | null): boolean {\n\tconst variable = (getAttr(element, variableAttribute) || '').trim();\n\tconst id = (identifier || '').trim();\n\tif (!variable || !id) return false;\n\tconst current = host.ctx.getValue(variable);\n\treturn isShownByIdentifier(current.kind === 'value' ? current.value : null, id, getAttr(element, 'showHide'));\n}\n\nexport function mathVariables(host: ContentPassHost): ReadonlySet<string> {\n\thost.mathVariableIds ??= new Set(\n\t\thost.itemDocument\n\t\t\t.findDeclarationElements('template')\n\t\t\t.filter((el) => getAttr(el, 'mathVariable')?.trim() === 'true')\n\t\t\t.map((el) => (getAttr(el, 'identifier') || '').trim()),\n\t);\n\treturn host.mathVariableIds;\n}\n\nfunction paramVariables(host: ContentPassHost): ReadonlySet<string> {\n\thost.paramVariableIds ??= new Set(\n\t\thost.itemDocument\n\t\t\t.findDeclarationElements('template')\n\t\t\t.filter((el) => getAttr(el, 'paramVariable')?.trim() === 'true')\n\t\t\t.map((el) => (getAttr(el, 'identifier') || '').trim()),\n\t);\n\treturn host.paramVariableIds;\n}\n\n/**\n * templateDeclaration@paramVariable (QTI 2.2 ASI TemplateDeclaration, `paramVariable`\n * characteristic; QTI 3.0 `param-variable`): a `<param>` inside an `<object>` whose `value`\n * names such a template variable is delivered with the variable's current value in place of\n * the variable's name, so a plugin-style object receives its computed parameter instead of a\n * literal.\n *\n * This resolves in the content pass — not in `prepareContentMarkup` (which runs once on the\n * raw XML, before template variables exist) and not on a stored copy — because template\n * variables change during the session (`setTemplateVariables`, `newTemplate`, restore).\n * Resolving with the pass means every (re)render, like printedVariable, delivers the value\n * the session holds at that moment.\n *\n * The spec defines substitution for a param value naming a declared `paramVariable`\n * variable. It is silent on a value naming an undeclared variable or one without the flag:\n * those, and NULL or container (multiple/ordered/record) values — a param carries one\n * opaque string, and joining container values would be invented semantics — deliver the\n * authored value unchanged, which is also the safe reading.\n */\nfunction expandParamVariable(host: ContentPassHost, element: Element): undefined {\n\tconst value = getAttr(element, 'value')?.trim();\n\tif (!value || !paramVariables(host).has(value)) return undefined;\n\tconst parent = element.parentNode;\n\tif (\n\t\t!isElement(parent) ||\n\t\thost.mapper.toCanonical(localName(parent) ?? '') !== 'object'\n\t) {\n\t\treturn undefined;\n\t}\n\tconst current = host.ctx.getValue(value);\n\tif (current.kind !== 'value' || current.cardinality !== 'single') return undefined;\n\t// The pass resolves a clone, so this rewrite cannot touch the parsed source.\n\telement.setAttribute('value', String(current.value));\n\treturn undefined;\n}\n\n/**\n * A MathML `mi` or `ci` naming a math variable, with the variable's single value in its place:\n * a number as `mn` or `cn` (`numberName`), any other value as the element's text. NULL and\n * container values leave the element as authored.\n */\nfunction mathVariableNodes(host: ContentPassHost, element: Element, numberName: string): Node[] | undefined {\n\tconst identifier = (element.textContent || '').trim();\n\tconst document = element.ownerDocument;\n\tif (!document || !mathVariables(host).has(identifier)) return undefined;\n\tconst value = host.ctx.getValue(identifier);\n\tif (value.kind !== 'value' || value.cardinality !== 'single') return undefined;\n\tconst text = String(value.value);\n\tif (value.baseType !== 'integer' && value.baseType !== 'float') {\n\t\t// The pass resolves a copy, and the element is not walked again, so this cannot cycle.\n\t\telement.textContent = text;\n\t\treturn undefined;\n\t}\n\tconst name = element.prefix ? `${element.prefix}:${numberName}` : numberName;\n\tconst replacement = document.createElementNS(element.namespaceURI, name);\n\treplacement.appendChild(document.createTextNode(text));\n\treturn [replacement];\n}\n\nfunction printedVariableNodes(host: ContentPassHost, element: Element): Node[] {\n\tconst identifier = (getAttr(element, 'identifier') || '').trim();\n\tconst document = element.ownerDocument;\n\tif (!identifier || !document) return [];\n\tconst variable = (id: string): QtiValue => host.ctx.getValue(id);\n\tconst printed = printVariable(variable(identifier), readPrintedVariableOptions(element, variable));\n\treturn printed.map((segment) => {\n\t\tif (typeof segment === 'string') return document.createTextNode(segment);\n\t\tconst sup = document.createElementNS(element.namespaceURI, 'sup');\n\t\tsup.appendChild(document.createTextNode(segment.superscript));\n\t\treturn sup;\n\t});\n}\n"]}