@pie-qti/item-player 1.0.0-beta.3 → 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 (300) 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 -18
  273. package/dist/components/utils/feedbackUtils.d.ts +0 -77
  274. package/dist/components/utils/feedbackUtils.js +0 -138
  275. package/dist/components/utils/feedbackUtils.js.map +0 -1
  276. package/dist/components/utils/index.d.ts +0 -4
  277. package/dist/components/utils/index.js +0 -5
  278. package/dist/components/utils/index.js.map +0 -1
  279. package/dist/components/utils/stimulusRender.js.map +0 -1
  280. package/dist/components/utils/stylesheetRender.js.map +0 -1
  281. package/dist/core/constants.d.ts +0 -65
  282. package/dist/core/constants.js +0 -74
  283. package/dist/core/constants.js.map +0 -1
  284. package/dist/element-class-X2XXDa29.js +0 -9299
  285. package/dist/element-class-X2XXDa29.js.map +0 -1
  286. package/dist/extensions/MathLiveEditor.d.ts +0 -31
  287. package/dist/extensions/MathLiveEditor.js +0 -248
  288. package/dist/extensions/MathLiveEditor.js.map +0 -1
  289. package/dist/utils/PerformanceMonitor.d.ts +0 -169
  290. package/dist/utils/PerformanceMonitor.js +0 -243
  291. package/dist/utils/PerformanceMonitor.js.map +0 -1
  292. package/dist/utils/responseUtils.d.ts +0 -15
  293. package/dist/utils/responseUtils.js +0 -46
  294. package/dist/utils/responseUtils.js.map +0 -1
  295. package/dist/web-components/QTIInteractionBase.d.ts +0 -119
  296. package/dist/web-components/QTIInteractionBase.js +0 -244
  297. package/dist/web-components/QTIInteractionBase.js.map +0 -1
  298. /package/dist/{components/utils → presentation}/stimulusRender.d.ts +0 -0
  299. /package/dist/{components/utils → presentation}/stylesheetRender.d.ts +0 -0
  300. /package/dist/{components/utils → presentation}/stylesheetRender.js +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mergeDeliveryFields.js","sourceRoot":"","sources":["../../src/extraction/mergeDeliveryFields.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,MAAM,UAAU,mBAAmB,CAClC,UAAwB,EACxB,QAAsB;IAEtB,MAAM,YAAY,GAAG,IAAI,GAAG,EAAa,CAAC;IAC1C,KAAK,MAAM,KAAK,IAAI,CAAC,GAAG,UAAU,EAAE,GAAG,QAAQ,CAAC,EAAE,CAAC;QAClD,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,CAAC;IACrD,CAAC;IACD,OAAO,CAAC,GAAG,YAAY,CAAC,MAAM,EAAE,CAAC,CAAC;AACnC,CAAC","sourcesContent":["/**\n * Merge extension (plugin-owned) sink policy with the authored standard policy\n * for one interaction kind.\n *\n * Both lists may classify the same output path; one path has one sink meaning,\n * so the merge is last-wins by path with the standard policy applied last: a\n * plugin can add new paths but cannot relabel a standard one — not even by\n * changing the field's kind.\n */\nexport function mergeDeliveryFields<T extends { kind: string; path: readonly (string | '*')[] }>(\n\textensions: readonly T[],\n\tstandard: readonly T[],\n): T[] {\n\tconst fieldsByPath = new Map<string, T>();\n\tfor (const field of [...extensions, ...standard]) {\n\t\tfieldsByPath.set(JSON.stringify(field.path), field);\n\t}\n\treturn [...fieldsByPath.values()];\n}\n"]}
@@ -0,0 +1,19 @@
1
+ import type { AttributeNameMapper } from '@pie-qti/qti-common';
2
+ /**
3
+ * Read an element's response binding: the one helper behind interaction
4
+ * discovery (extraction), slot hiding and diagnostics.
5
+ *
6
+ * It accepts the union of spellings an item may bind a response with — the
7
+ * mapper-native name when a mapper is given, plus the QTI 2 `responseIdentifier`
8
+ * and QTI 3 `response-identifier` forms — and reads them case-insensitively on
9
+ * HTML trees (node-html-parser folds attribute names), case-sensitively on XML
10
+ * trees. The value is returned as authored: trimming is a caller's choice
11
+ * (diagnostics trim; extraction and slot hiding keep the authored form).
12
+ *
13
+ * The three call sites stay separate predicates on purpose — slot hiding,
14
+ * extraction and diagnostics differ in defaults and in what a missing binding
15
+ * means — they only share this vocabulary.
16
+ */
17
+ export declare function readResponseIdentifier(element: {
18
+ getAttribute?: (name: string) => string | null | undefined;
19
+ }, attributeNameMapper?: AttributeNameMapper): string | undefined;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Read an element's response binding: the one helper behind interaction
3
+ * discovery (extraction), slot hiding and diagnostics.
4
+ *
5
+ * It accepts the union of spellings an item may bind a response with — the
6
+ * mapper-native name when a mapper is given, plus the QTI 2 `responseIdentifier`
7
+ * and QTI 3 `response-identifier` forms — and reads them case-insensitively on
8
+ * HTML trees (node-html-parser folds attribute names), case-sensitively on XML
9
+ * trees. The value is returned as authored: trimming is a caller's choice
10
+ * (diagnostics trim; extraction and slot hiding keep the authored form).
11
+ *
12
+ * The three call sites stay separate predicates on purpose — slot hiding,
13
+ * extraction and diagnostics differ in defaults and in what a missing binding
14
+ * means — they only share this vocabulary.
15
+ */
16
+ export function readResponseIdentifier(element, attributeNameMapper) {
17
+ const names = ['responseIdentifier'];
18
+ const native = attributeNameMapper?.toNative('responseIdentifier');
19
+ if (native && native !== 'responseIdentifier')
20
+ names.push(native);
21
+ names.push('response-identifier');
22
+ for (const name of names) {
23
+ const value = element.getAttribute?.(name);
24
+ if (value)
25
+ return value;
26
+ }
27
+ return undefined;
28
+ }
29
+ //# sourceMappingURL=responseIdentifier.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"responseIdentifier.js","sourceRoot":"","sources":["../../src/extraction/responseIdentifier.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,sBAAsB,CACrC,OAAuE,EACvE,mBAAyC;IAEzC,MAAM,KAAK,GAAG,CAAC,oBAAoB,CAAC,CAAC;IACrC,MAAM,MAAM,GAAG,mBAAmB,EAAE,QAAQ,CAAC,oBAAoB,CAAC,CAAC;IACnE,IAAI,MAAM,IAAI,MAAM,KAAK,oBAAoB;QAAE,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAClE,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC;IAClC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QAC1B,MAAM,KAAK,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC,IAAI,CAAC,CAAC;QAC3C,IAAI,KAAK;YAAE,OAAO,KAAK,CAAC;IACzB,CAAC;IACD,OAAO,SAAS,CAAC;AAClB,CAAC","sourcesContent":["import type { AttributeNameMapper } from '@pie-qti/qti-common';\n\n/**\n * Read an element's response binding: the one helper behind interaction\n * discovery (extraction), slot hiding and diagnostics.\n *\n * It accepts the union of spellings an item may bind a response with — the\n * mapper-native name when a mapper is given, plus the QTI 2 `responseIdentifier`\n * and QTI 3 `response-identifier` forms — and reads them case-insensitively on\n * HTML trees (node-html-parser folds attribute names), case-sensitively on XML\n * trees. The value is returned as authored: trimming is a caller's choice\n * (diagnostics trim; extraction and slot hiding keep the authored form).\n *\n * The three call sites stay separate predicates on purpose — slot hiding,\n * extraction and diagnostics differ in defaults and in what a missing binding\n * means — they only share this vocabulary.\n */\nexport function readResponseIdentifier(\n\telement: { getAttribute?: (name: string) => string | null | undefined },\n\tattributeNameMapper?: AttributeNameMapper,\n): string | undefined {\n\tconst names = ['responseIdentifier'];\n\tconst native = attributeNameMapper?.toNative('responseIdentifier');\n\tif (native && native !== 'responseIdentifier') names.push(native);\n\tnames.push('response-identifier');\n\tfor (const name of names) {\n\t\tconst value = element.getAttribute?.(name);\n\t\tif (value) return value;\n\t}\n\treturn undefined;\n}\n"]}
@@ -4,7 +4,7 @@
4
4
  * Provides interfaces for extracting data from QTI XML elements with
5
5
  * priority-based dispatch, validation, and type safety.
6
6
  */
7
- import type { AttributeNameMapper, ElementNameMapper } from '@pie-qti/qti-common';
7
+ import type { AttributeNameMapper, ElementNameMapper, QtiVersion } from '@pie-qti/qti-common';
8
8
  import type { PlayerSecurityConfig, QTIRole } from '../types/index.js';
9
9
  import type { QTIElement } from '../interactions/shared/types.js';
10
10
  import type { InteractionDeliverySchema } from './deliveryTypes.js';
@@ -14,6 +14,14 @@ export interface ExtractionConfig {
14
14
  readonly security?: PlayerSecurityConfig;
15
15
  readonly elementNameMapper?: ElementNameMapper;
16
16
  readonly attributeNameMapper?: AttributeNameMapper;
17
+ /**
18
+ * The item's detected QTI version ('unknown' when nothing identified it). Extractors
19
+ * apply per-version spec defaults with it (e.g. graphicGapMatchInteraction
20
+ * `maxAssociations` defaults to 1 in 2.2/3.0 and has no cap in 2.1). Absent in
21
+ * hand-built contexts, where extractors fall back to the 2.2 assumption
22
+ * {@link detectQtiVersion} itself makes.
23
+ */
24
+ readonly qtiVersion?: QtiVersion;
17
25
  }
18
26
  /**
19
27
  * Context provided to extractors during extraction
@@ -27,7 +35,7 @@ export interface ExtractionContext {
27
35
  /** Root DOM element for document-wide queries */
28
36
  dom: QTIElement;
29
37
  /** Variable declarations from responseDeclaration/outcomeDeclaration */
30
- declarations: Map<string, VariableDeclaration>;
38
+ declarations: Map<string, ExtractionVariableDeclaration>;
31
39
  /** Utility functions for DOM manipulation and extraction */
32
40
  utils: ExtractionUtils;
33
41
  /** Immutable extraction-relevant configuration. */
@@ -46,7 +54,7 @@ export interface ExtractionContext {
46
54
  /**
47
55
  * Variable declaration from QTI responseDeclaration/outcomeDeclaration
48
56
  */
49
- export interface VariableDeclaration {
57
+ export interface ExtractionVariableDeclaration {
50
58
  identifier: string;
51
59
  cardinality: 'single' | 'multiple' | 'ordered' | 'record';
52
60
  baseType?: string;
@@ -238,18 +246,3 @@ export type ExtractionDispatchResult<TData extends object> = {
238
246
  success: false;
239
247
  error: ExtractionError;
240
248
  };
241
- /**
242
- * Type guard for successful extraction result
243
- */
244
- export declare function isSuccessResult<TData>(result: ExtractionResult<TData>): result is {
245
- success: true;
246
- data: TData;
247
- warnings?: string[];
248
- };
249
- /**
250
- * Type guard for failed extraction result
251
- */
252
- export declare function isErrorResult<TData>(result: ExtractionResult<TData>): result is {
253
- success: false;
254
- error: ExtractionError;
255
- };
@@ -16,16 +16,4 @@ export class ExtractionError extends Error {
16
16
  this.name = 'ExtractionError';
17
17
  }
18
18
  }
19
- /**
20
- * Type guard for successful extraction result
21
- */
22
- export function isSuccessResult(result) {
23
- return result.success === true;
24
- }
25
- /**
26
- * Type guard for failed extraction result
27
- */
28
- export function isErrorResult(result) {
29
- return result.success === false;
30
- }
31
19
  //# sourceMappingURL=types.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/extraction/types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAoJH;;GAEG;AACH,MAAM,OAAO,eAAgB,SAAQ,KAAK;IACzC,YACC,OAAe,EACC,WAAmB,EACnB,WAAmB,EACnB,KAAa;QAE7B,KAAK,CAAC,OAAO,CAAC,CAAC;QAJC,gBAAW,GAAX,WAAW,CAAQ;QACnB,gBAAW,GAAX,WAAW,CAAQ;QACnB,UAAK,GAAL,KAAK,CAAQ;QAG7B,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;IAC/B,CAAC;CACD;AAoHD;;GAEG;AACH,MAAM,UAAU,eAAe,CAC9B,MAA+B;IAE/B,OAAO,MAAM,CAAC,OAAO,KAAK,IAAI,CAAC;AAChC,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,aAAa,CAC5B,MAA+B;IAE/B,OAAO,MAAM,CAAC,OAAO,KAAK,KAAK,CAAC;AACjC,CAAC","sourcesContent":["/**\n * Core types for the plugin-based element extraction system\n *\n * Provides interfaces for extracting data from QTI XML elements with\n * priority-based dispatch, validation, and type safety.\n */\n\nimport type { AttributeNameMapper, ElementNameMapper } from '@pie-qti/qti-common';\nimport type { PlayerSecurityConfig, QTIRole } from '../types/index.js';\nimport type { QTIElement } from '../interactions/shared/types.js';\nimport type { InteractionDeliverySchema } from './deliveryTypes.js';\n\n/** Configuration visible to extractor implementations. */\nexport interface ExtractionConfig {\n\treadonly role?: QTIRole;\n\treadonly security?: PlayerSecurityConfig;\n\treadonly elementNameMapper?: ElementNameMapper;\n\treadonly attributeNameMapper?: AttributeNameMapper;\n}\n\n/**\n * Context provided to extractors during extraction\n * Contains DOM reference, utilities, and metadata\n */\nexport interface ExtractionContext {\n\t/** The element being extracted */\n\telement: QTIElement;\n\n\t/** Response identifier for this interaction */\n\tresponseId: string;\n\n\t/** Root DOM element for document-wide queries */\n\tdom: QTIElement;\n\n\t/** Variable declarations from responseDeclaration/outcomeDeclaration */\n\tdeclarations: Map<string, VariableDeclaration>;\n\n\t/** Utility functions for DOM manipulation and extraction */\n\tutils: ExtractionUtils;\n\n\t/** Immutable extraction-relevant configuration. */\n\tconfig: ExtractionConfig;\n\n\t/**\n\t * Seeded RNG for interactions honouring the QTI `shuffle` attribute, keyed to the\n\t * item session and this `responseId`. Stateful: successive calls advance the\n\t * sequence, so an extractor with two choice sets (e.g. `matchInteraction`) gets an\n\t * independent permutation for each set.\n\t *\n\t * Optional so that a hand-built context remains valid; extractors that find it\n\t * absent keep the authored order.\n\t */\n\tshuffleRng?: () => number;\n}\n\n/**\n * Variable declaration from QTI responseDeclaration/outcomeDeclaration\n */\nexport interface VariableDeclaration {\n\tidentifier: string;\n\tcardinality: 'single' | 'multiple' | 'ordered' | 'record';\n\tbaseType?: string;\n}\n\n/**\n * Utility functions available to extractors\n * Provides safe, consistent DOM manipulation and content extraction\n */\nexport interface ExtractionUtils {\n\t/** Check an element tag against a canonical QTI 2.x name across QTI versions. */\n\tmatchesTag(element: QTIElement, tagName: string): boolean;\n\n\t/**\n\t * Get direct children with a specific tag name\n\t * @example utils.getChildrenByTag(element, 'simpleChoice')\n\t */\n\tgetChildrenByTag(element: QTIElement, tagName: string): QTIElement[];\n\n\t/**\n\t * Query all descendants matching a selector\n\t * @example utils.querySelectorAll(element, 'choiceInteraction simpleChoice')\n\t */\n\tquerySelectorAll(element: QTIElement, selector: string): QTIElement[];\n\n\t/**\n\t * Query first descendant matching a selector\n\t * @example utils.querySelector(element, 'prompt')\n\t */\n\tquerySelector(element: QTIElement, selector: string): QTIElement | null;\n\n\t/**\n\t * Check if element has a child with specific tag (fast boolean check)\n\t * @example utils.hasChildWithTag(element, 'ratingChoice')\n\t */\n\thasChildWithTag(element: QTIElement, tagName: string): boolean;\n\n\t/**\n\t * Get sanitized HTML content from element\n\t * @example utils.getHtmlContent(element) // '<p>Question <math>...</math></p>'\n\t */\n\tgetHtmlContent(element: QTIElement): string;\n\n\t/**\n\t * Get plain text content (strips HTML tags)\n\t * @example utils.getTextContent(element) // 'Question text'\n\t */\n\tgetTextContent(element: QTIElement): string;\n\n\t/**\n\t * Get attribute value with optional default\n\t * @example utils.getAttribute(element, 'identifier', '')\n\t */\n\tgetAttribute(element: QTIElement, name: string, defaultValue?: string): string;\n\n\t/**\n\t * Get boolean attribute value with optional default\n\t * @example utils.getBooleanAttribute(element, 'shuffle', false) // true\n\t */\n\tgetBooleanAttribute(element: QTIElement, name: string, defaultValue?: boolean): boolean;\n\n\t/**\n\t * Get numeric attribute value with optional default\n\t * @example utils.getNumberAttribute(element, 'maxChoices', 1) // 1\n\t */\n\tgetNumberAttribute(element: QTIElement, name: string, defaultValue?: number): number;\n\n\t/**\n\t * Get CSS classes from element\n\t * @example utils.getClasses(element) // ['rating-interaction', 'custom']\n\t */\n\tgetClasses(element: QTIElement): string[];\n\n\t/**\n\t * Extract prompt element text from an interaction\n\t * @example utils.getPrompt(element) // '<p>Select the correct answer</p>'\n\t */\n\tgetPrompt(element: QTIElement): string | null;\n}\n\n/**\n * Result of validation\n */\nexport interface ValidationResult {\n\t/** Whether validation passed */\n\tvalid: boolean;\n\n\t/** Error messages if validation failed */\n\terrors?: string[];\n\n\t/** Warning messages (non-fatal) */\n\twarnings?: string[];\n}\n\n/**\n * Error thrown during extraction\n */\nexport class ExtractionError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly extractorId: string,\n\t\tpublic readonly elementType: string,\n\t\tpublic readonly cause?: Error\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'ExtractionError';\n\t}\n}\n\n/**\n * Result of extraction operation\n */\nexport type ExtractionResult<TData> =\n\t| { success: true; data: TData; warnings?: string[] }\n\t| { success: false; error: ExtractionError };\n\n/**\n * Element extractor with priority-based dispatch\n *\n * @template TData - The extracted data type (e.g., ChoiceData, TextEntryData)\n * @template TContext - The extraction context type (defaults to ExtractionContext)\n */\nexport interface ElementExtractor<\n\tTPayload extends object = Record<string, unknown>,\n\tTOutputType extends string = string,\n\tTContext extends ExtractionContext = ExtractionContext,\n> {\n\t/**\n\t * Unique identifier for this extractor\n\t * Convention: 'namespace:element-type' (e.g., 'qti:choice', 'renaissance:rating-choice')\n\t */\n\tid: string;\n\n\t/**\n\t * Human-readable name for debugging/error messages\n\t * @example 'QTI Standard Choice Interaction'\n\t */\n\tname: string;\n\n\t/**\n\t * Priority for extractor evaluation (higher = checked first)\n\t * - 1000+: Critical system extractors (error handlers, etc.)\n\t * - 500-999: Vendor-specific extractors (Renaissance, custom content)\n\t * - 100-499: Third-party plugin extractors\n\t * - 1-99: Standard QTI extractors with variations\n\t * - 0: Fallback/default extractors\n\t */\n\tpriority: number;\n\n\t/**\n\t * Element types this extractor handles (for type-based indexing)\n\t * Used for O(M) lookup instead of O(N) scanning\n\t * @example ['choiceInteraction', 'inlineChoiceInteraction']\n\t */\n\telementTypes: string[];\n\n\t/**\n\t * Optional description for debugging/error messages\n\t * @example 'Handles Renaissance rating choice interactions with star/face icons'\n\t */\n\tdescription?: string;\n\n\t/**\n\t * Renderer-facing type attached by the framework after extraction. When\n\t * omitted, the normalized authored element type is used.\n\t */\n\treadonly outputType?: TOutputType;\n\n\t/**\n\t * HTML and resource fields produced by this extractor. The common delivery\n\t * pipeline enforces these rules after extraction, so plugin extractors can\n\t * safely add rich fields without teaching a central type switch their shape.\n\t */\n\tdelivery?: InteractionDeliverySchema;\n\n\t/**\n\t * Predicate to determine if this extractor can handle the element\n\t * Evaluated in priority order (highest first)\n\t *\n\t * IMPORTANT: Must be FAST - use quick checks first\n\t * @example\n\t * canHandle(element, context) {\n\t * // Fast checks first\n\t * if (!context.utils.hasChildWithTag(element, 'ratingChoice')) return false;\n\t * // Expensive checks only if fast checks pass\n\t * return validateRatingStructure(element);\n\t * }\n\t */\n\tcanHandle(element: QTIElement, context: TContext): boolean;\n\n\t/**\n\t * Extract data from the element\n\t * Called only if canHandle() returns true\n\t *\n\t * @throws ExtractionError if extraction fails\n\t * @returns Extracted data structure\n\t */\n\textract(element: QTIElement, context: TContext): TPayload;\n\n\t/**\n\t * Validate extracted data (optional)\n\t * Called after extract() succeeds\n\t *\n\t * @returns Validation result with errors/warnings\n\t */\n\tvalidate?(data: TPayload): ValidationResult;\n}\n\n/**\n * Result of one registry-owned dispatch. On success, `extractor` is the exact\n * snapshotted handler whose predicate matched and whose `extract` method ran.\n * Callers must use this descriptor for renderer and delivery-policy decisions\n * instead of performing a second lookup.\n */\nexport type ExtractionDispatchResult<TData extends object> =\n\t| {\n\t\t\tsuccess: true;\n\t\t\tdata: TData;\n\t\t\textractor: ElementExtractor<any, string>;\n\t\t\twarnings?: string[];\n\t }\n\t| { success: false; error: ExtractionError };\n\n/**\n * Type guard for successful extraction result\n */\nexport function isSuccessResult<TData>(\n\tresult: ExtractionResult<TData>\n): result is { success: true; data: TData; warnings?: string[] } {\n\treturn result.success === true;\n}\n\n/**\n * Type guard for failed extraction result\n */\nexport function isErrorResult<TData>(\n\tresult: ExtractionResult<TData>\n): result is { success: false; error: ExtractionError } {\n\treturn result.success === false;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/extraction/types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AA4JH;;GAEG;AACH,MAAM,OAAO,eAAgB,SAAQ,KAAK;IACzC,YACC,OAAe,EACC,WAAmB,EACnB,WAAmB,EACnB,KAAa;QAE7B,KAAK,CAAC,OAAO,CAAC,CAAC;QAJC,gBAAW,GAAX,WAAW,CAAQ;QACnB,gBAAW,GAAX,WAAW,CAAQ;QACnB,UAAK,GAAL,KAAK,CAAQ;QAG7B,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;IAC/B,CAAC;CACD","sourcesContent":["/**\n * Core types for the plugin-based element extraction system\n *\n * Provides interfaces for extracting data from QTI XML elements with\n * priority-based dispatch, validation, and type safety.\n */\n\nimport type { AttributeNameMapper, ElementNameMapper, QtiVersion } from '@pie-qti/qti-common';\nimport type { PlayerSecurityConfig, QTIRole } from '../types/index.js';\nimport type { QTIElement } from '../interactions/shared/types.js';\nimport type { InteractionDeliverySchema } from './deliveryTypes.js';\n\n/** Configuration visible to extractor implementations. */\nexport interface ExtractionConfig {\n\treadonly role?: QTIRole;\n\treadonly security?: PlayerSecurityConfig;\n\treadonly elementNameMapper?: ElementNameMapper;\n\treadonly attributeNameMapper?: AttributeNameMapper;\n\t/**\n\t * The item's detected QTI version ('unknown' when nothing identified it). Extractors\n\t * apply per-version spec defaults with it (e.g. graphicGapMatchInteraction\n\t * `maxAssociations` defaults to 1 in 2.2/3.0 and has no cap in 2.1). Absent in\n\t * hand-built contexts, where extractors fall back to the 2.2 assumption\n\t * {@link detectQtiVersion} itself makes.\n\t */\n\treadonly qtiVersion?: QtiVersion;\n}\n\n/**\n * Context provided to extractors during extraction\n * Contains DOM reference, utilities, and metadata\n */\nexport interface ExtractionContext {\n\t/** The element being extracted */\n\telement: QTIElement;\n\n\t/** Response identifier for this interaction */\n\tresponseId: string;\n\n\t/** Root DOM element for document-wide queries */\n\tdom: QTIElement;\n\n\t/** Variable declarations from responseDeclaration/outcomeDeclaration */\n\tdeclarations: Map<string, ExtractionVariableDeclaration>;\n\n\t/** Utility functions for DOM manipulation and extraction */\n\tutils: ExtractionUtils;\n\n\t/** Immutable extraction-relevant configuration. */\n\tconfig: ExtractionConfig;\n\n\t/**\n\t * Seeded RNG for interactions honouring the QTI `shuffle` attribute, keyed to the\n\t * item session and this `responseId`. Stateful: successive calls advance the\n\t * sequence, so an extractor with two choice sets (e.g. `matchInteraction`) gets an\n\t * independent permutation for each set.\n\t *\n\t * Optional so that a hand-built context remains valid; extractors that find it\n\t * absent keep the authored order.\n\t */\n\tshuffleRng?: () => number;\n}\n\n/**\n * Variable declaration from QTI responseDeclaration/outcomeDeclaration\n */\nexport interface ExtractionVariableDeclaration {\n\tidentifier: string;\n\tcardinality: 'single' | 'multiple' | 'ordered' | 'record';\n\tbaseType?: string;\n}\n\n/**\n * Utility functions available to extractors\n * Provides safe, consistent DOM manipulation and content extraction\n */\nexport interface ExtractionUtils {\n\t/** Check an element tag against a canonical QTI 2.x name across QTI versions. */\n\tmatchesTag(element: QTIElement, tagName: string): boolean;\n\n\t/**\n\t * Get direct children with a specific tag name\n\t * @example utils.getChildrenByTag(element, 'simpleChoice')\n\t */\n\tgetChildrenByTag(element: QTIElement, tagName: string): QTIElement[];\n\n\t/**\n\t * Query all descendants matching a selector\n\t * @example utils.querySelectorAll(element, 'choiceInteraction simpleChoice')\n\t */\n\tquerySelectorAll(element: QTIElement, selector: string): QTIElement[];\n\n\t/**\n\t * Query first descendant matching a selector\n\t * @example utils.querySelector(element, 'prompt')\n\t */\n\tquerySelector(element: QTIElement, selector: string): QTIElement | null;\n\n\t/**\n\t * Check if element has a child with specific tag (fast boolean check)\n\t * @example utils.hasChildWithTag(element, 'ratingChoice')\n\t */\n\thasChildWithTag(element: QTIElement, tagName: string): boolean;\n\n\t/**\n\t * Get sanitized HTML content from element\n\t * @example utils.getHtmlContent(element) // '<p>Question <math>...</math></p>'\n\t */\n\tgetHtmlContent(element: QTIElement): string;\n\n\t/**\n\t * Get plain text content (strips HTML tags)\n\t * @example utils.getTextContent(element) // 'Question text'\n\t */\n\tgetTextContent(element: QTIElement): string;\n\n\t/**\n\t * Get attribute value with optional default\n\t * @example utils.getAttribute(element, 'identifier', '')\n\t */\n\tgetAttribute(element: QTIElement, name: string, defaultValue?: string): string;\n\n\t/**\n\t * Get boolean attribute value with optional default\n\t * @example utils.getBooleanAttribute(element, 'shuffle', false) // true\n\t */\n\tgetBooleanAttribute(element: QTIElement, name: string, defaultValue?: boolean): boolean;\n\n\t/**\n\t * Get numeric attribute value with optional default\n\t * @example utils.getNumberAttribute(element, 'maxChoices', 1) // 1\n\t */\n\tgetNumberAttribute(element: QTIElement, name: string, defaultValue?: number): number;\n\n\t/**\n\t * Get CSS classes from element\n\t * @example utils.getClasses(element) // ['rating-interaction', 'custom']\n\t */\n\tgetClasses(element: QTIElement): string[];\n\n\t/**\n\t * Extract prompt element text from an interaction\n\t * @example utils.getPrompt(element) // '<p>Select the correct answer</p>'\n\t */\n\tgetPrompt(element: QTIElement): string | null;\n}\n\n/**\n * Result of validation\n */\nexport interface ValidationResult {\n\t/** Whether validation passed */\n\tvalid: boolean;\n\n\t/** Error messages if validation failed */\n\terrors?: string[];\n\n\t/** Warning messages (non-fatal) */\n\twarnings?: string[];\n}\n\n/**\n * Error thrown during extraction\n */\nexport class ExtractionError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly extractorId: string,\n\t\tpublic readonly elementType: string,\n\t\tpublic readonly cause?: Error\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'ExtractionError';\n\t}\n}\n\n/**\n * Result of extraction operation\n */\nexport type ExtractionResult<TData> =\n\t| { success: true; data: TData; warnings?: string[] }\n\t| { success: false; error: ExtractionError };\n\n/**\n * Element extractor with priority-based dispatch\n *\n * @template TData - The extracted data type (e.g., ChoiceData, TextEntryData)\n * @template TContext - The extraction context type (defaults to ExtractionContext)\n */\nexport interface ElementExtractor<\n\tTPayload extends object = Record<string, unknown>,\n\tTOutputType extends string = string,\n\tTContext extends ExtractionContext = ExtractionContext,\n> {\n\t/**\n\t * Unique identifier for this extractor\n\t * Convention: 'namespace:element-type' (e.g., 'qti:choice', 'renaissance:rating-choice')\n\t */\n\tid: string;\n\n\t/**\n\t * Human-readable name for debugging/error messages\n\t * @example 'QTI Standard Choice Interaction'\n\t */\n\tname: string;\n\n\t/**\n\t * Priority for extractor evaluation (higher = checked first)\n\t * - 1000+: Critical system extractors (error handlers, etc.)\n\t * - 500-999: Vendor-specific extractors (Renaissance, custom content)\n\t * - 100-499: Third-party plugin extractors\n\t * - 1-99: Standard QTI extractors with variations\n\t * - 0: Fallback/default extractors\n\t */\n\tpriority: number;\n\n\t/**\n\t * Element types this extractor handles (for type-based indexing)\n\t * Used for O(M) lookup instead of O(N) scanning\n\t * @example ['choiceInteraction', 'inlineChoiceInteraction']\n\t */\n\telementTypes: string[];\n\n\t/**\n\t * Optional description for debugging/error messages\n\t * @example 'Handles Renaissance rating choice interactions with star/face icons'\n\t */\n\tdescription?: string;\n\n\t/**\n\t * Renderer-facing type attached by the framework after extraction. When\n\t * omitted, the normalized authored element type is used.\n\t */\n\treadonly outputType?: TOutputType;\n\n\t/**\n\t * HTML and resource fields produced by this extractor. The common delivery\n\t * pipeline enforces these rules after extraction, so plugin extractors can\n\t * safely add rich fields without teaching a central type switch their shape.\n\t */\n\tdelivery?: InteractionDeliverySchema;\n\n\t/**\n\t * Predicate to determine if this extractor can handle the element\n\t * Evaluated in priority order (highest first)\n\t *\n\t * IMPORTANT: Must be FAST - use quick checks first\n\t * @example\n\t * canHandle(element, context) {\n\t * // Fast checks first\n\t * if (!context.utils.hasChildWithTag(element, 'ratingChoice')) return false;\n\t * // Expensive checks only if fast checks pass\n\t * return validateRatingStructure(element);\n\t * }\n\t */\n\tcanHandle(element: QTIElement, context: TContext): boolean;\n\n\t/**\n\t * Extract data from the element\n\t * Called only if canHandle() returns true\n\t *\n\t * @throws ExtractionError if extraction fails\n\t * @returns Extracted data structure\n\t */\n\textract(element: QTIElement, context: TContext): TPayload;\n\n\t/**\n\t * Validate extracted data (optional)\n\t * Called after extract() succeeds\n\t *\n\t * @returns Validation result with errors/warnings\n\t */\n\tvalidate?(data: TPayload): ValidationResult;\n}\n\n/**\n * Result of one registry-owned dispatch. On success, `extractor` is the exact\n * snapshotted handler whose predicate matched and whose `extract` method ran.\n * Callers must use this descriptor for renderer and delivery-policy decisions\n * instead of performing a second lookup.\n */\nexport type ExtractionDispatchResult<TData extends object> =\n\t| {\n\t\t\tsuccess: true;\n\t\t\tdata: TData;\n\t\t\textractor: ElementExtractor<any, string>;\n\t\t\twarnings?: string[];\n\t }\n\t| { success: false; error: ExtractionError };\n"]}
@@ -6,6 +6,20 @@
6
6
  import type { ElementNameMapper, AttributeNameMapper } from '@pie-qti/qti-common';
7
7
  import type { PlayerSecurityConfig } from '../types/index.js';
8
8
  import type { ExtractionUtils } from './types.js';
9
+ /**
10
+ * Validates one choice-like identifier set for an extractor: every item must carry an identifier
11
+ * and none may repeat, as an interaction whose response holds identifiers would otherwise be
12
+ * ambiguous. Items are identifiers (gapMatchInteraction's gaps are bare strings) or objects with
13
+ * an optional `identifier`; each failure pushes one error into `errors`, with the same wording for
14
+ * every extractor. `labels.plural` names the set in the missing-identifier error ("source
15
+ * choices"), `labels.noun` in the duplicate error ("source").
16
+ */
17
+ export declare function validateUniqueIdentifiers(items: ReadonlyArray<string | {
18
+ identifier?: string;
19
+ } | undefined>, errors: string[], labels: {
20
+ plural: string;
21
+ noun: string;
22
+ }): void;
9
23
  /**
10
24
  * Create extraction utilities instance
11
25
  * Provides standard helpers for extracting data from QTI elements.
@@ -3,8 +3,9 @@
3
3
  *
4
4
  * Provides DOM manipulation and content extraction helpers for extractors
5
5
  */
6
- import { Qti2xElementNameMapper, Qti2xAttributeNameMapper } from '@pie-qti/qti-common';
7
6
  import { sanitizeTextContent } from '../core/sanitizer.js';
7
+ import { defaultExtractionMappers } from '../core/nameMappers.js';
8
+ import { escapeHtmlAttribute } from '../security/escapeHtml.js';
8
9
  import { readAloudAttributes } from './interactionAccessibility.js';
9
10
  /**
10
11
  * Extract text content from QTI elements
@@ -23,6 +24,13 @@ function getChildrenByTagWithMapper(element, tagName, mapper) {
23
24
  /**
24
25
  * Extract a boolean attribute from a QTI element
25
26
  * Supports both QTI 2.x (camelCase) and QTI 3.0 (kebab-case) attributes
27
+ *
28
+ * Every QTI interaction boolean is `xs:boolean`, whose lexical space is
29
+ * `{true, false, 1, 0}` (XML Schema Part 2), so the on-forms are `"true"` and
30
+ * `"1"` — not just the literal `"true"`. This helper is the one xs:boolean
31
+ * reader for every extractor. (The media extractor's `isBooleanAttributeOn`
32
+ * stays separate on purpose: it reads HTML presence semantics for
33
+ * `<track default>`, which has no xs:boolean lexical space.)
26
34
  */
27
35
  function getBooleanAttribute(element, name, defaultValue = false, attributeMapper) {
28
36
  let value = element.getAttribute(name);
@@ -33,7 +41,7 @@ function getBooleanAttribute(element, name, defaultValue = false, attributeMappe
33
41
  }
34
42
  if (value === null || value === undefined)
35
43
  return defaultValue;
36
- return value === 'true';
44
+ return value === 'true' || value === '1';
37
45
  }
38
46
  /**
39
47
  * Extract a number attribute from a QTI element
@@ -93,6 +101,29 @@ function wrapsContentWithIdref(element, idref) {
93
101
  const [only] = content;
94
102
  return content.length === 1 && only.getAttribute?.('data-catalog-idref') === idref;
95
103
  }
104
+ /**
105
+ * Validates one choice-like identifier set for an extractor: every item must carry an identifier
106
+ * and none may repeat, as an interaction whose response holds identifiers would otherwise be
107
+ * ambiguous. Items are identifiers (gapMatchInteraction's gaps are bare strings) or objects with
108
+ * an optional `identifier`; each failure pushes one error into `errors`, with the same wording for
109
+ * every extractor. `labels.plural` names the set in the missing-identifier error ("source
110
+ * choices"), `labels.noun` in the duplicate error ("source").
111
+ */
112
+ export function validateUniqueIdentifiers(items, errors, labels) {
113
+ const identifiers = new Set();
114
+ for (const item of items) {
115
+ const identifier = typeof item === 'string' ? item : item?.identifier;
116
+ if (!identifier) {
117
+ errors.push(`All ${labels.plural} must have an identifier`);
118
+ }
119
+ else if (identifiers.has(identifier)) {
120
+ errors.push(`Duplicate ${labels.noun} identifier: ${identifier}`);
121
+ }
122
+ else {
123
+ identifiers.add(identifier);
124
+ }
125
+ }
126
+ }
96
127
  /**
97
128
  * Create extraction utilities instance
98
129
  * Provides standard helpers for extracting data from QTI elements.
@@ -100,8 +131,7 @@ function wrapsContentWithIdref(element, idref) {
100
131
  */
101
132
  export function createExtractionUtils(security, mapper, attributeMapper) {
102
133
  // Default to QTI 2.x mappers (primary supported QTI format)
103
- const elementMapper = mapper || new Qti2xElementNameMapper();
104
- const attrMapper = attributeMapper || new Qti2xAttributeNameMapper();
134
+ const { elementMapper, attrMapper } = defaultExtractionMappers(mapper, attributeMapper);
105
135
  return {
106
136
  matchesTag(element, tagName) {
107
137
  return matchesTagName(element.rawTagName, tagName, elementMapper);
@@ -157,7 +187,7 @@ export function createExtractionUtils(security, mapper, attributeMapper) {
157
187
  }
158
188
  const wrapped = html && attributes && Object.keys(attributes).length > 0
159
189
  ? `<span ${Object.entries(attributes)
160
- .map(([name, value]) => `${name}="${value.replace(/&/g, '&amp;').replace(/"/g, '&quot;')}"`)
190
+ .map(([name, value]) => `${name}="${escapeHtmlAttribute(value)}"`)
161
191
  .join(' ')}>${html}</span>`
162
192
  : html;
163
193
  return sanitizeTextContent(wrapped, { security });
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/extraction/utils.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AACvF,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAKpE;;GAEG;AACH,SAAS,cAAc,CAAC,OAAsC;IAC7D,OAAO,OAAO,EAAE,WAAW,EAA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,mBAAmB,CAAC,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,UAAU,CAAC,CAAC;QACrE,CAAC;QAED,kBAAkB,CAAC,OAAmB,EAAE,IAAY,EAAE,YAAY,GAAG,CAAC;YACrE,OAAO,kBAAkB,CAAC,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,UAAU,CAAC,CAAC;QACpE,CAAC;QAED,SAAS,CAAC,OAAmB;YAC5B,MAAM,aAAa,GAAG,0BAA0B,CAAC,OAAO,EAAE,QAAQ,EAAE,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC;YACtF,OAAO,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,cAAc,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QAClE,CAAC;QAED,UAAU,CAAC,OAAmB;YAC7B,OAAO,UAAU,CAAC,OAAO,CAAC,CAAC;QAC5B,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Extraction utilities implementation\n *\n * Provides DOM manipulation and content extraction helpers for extractors\n */\n\nimport type { ElementNameMapper, AttributeNameMapper } from '@pie-qti/qti-common';\nimport { Qti2xElementNameMapper, Qti2xAttributeNameMapper } from '@pie-qti/qti-common';\nimport { sanitizeTextContent } from '../core/sanitizer.js';\nimport { readAloudAttributes } from './interactionAccessibility.js';\nimport type { PlayerSecurityConfig } from '../types/index.js';\nimport type { QTIElement } from '../interactions/shared/types.js';\nimport type { ExtractionUtils } from './types.js';\n\n/**\n * Extract text content from QTI elements\n */\nfunction getTextContent(element: QTIElement | null | undefined): string {\n\treturn element?.textContent?.trim() || '';\n}\n\n/**\n * Get children by tag name with QTI version awareness\n */\nfunction getChildrenByTagWithMapper(\n\telement: QTIElement | null | undefined,\n\ttagName: string,\n\tmapper: ElementNameMapper\n): QTIElement[] {\n\tif (!element?.childNodes) return [];\n\treturn element.childNodes.filter((n) =>\n\t\tmatchesTagName((n as QTIElement).rawTagName, tagName, mapper)\n\t) as QTIElement[];\n}\n\n/**\n * Extract a boolean attribute from a QTI element\n * Supports both QTI 2.x (camelCase) and QTI 3.0 (kebab-case) attributes\n */\nfunction getBooleanAttribute(\n\telement: QTIElement,\n\tname: string,\n\tdefaultValue = false,\n\tattributeMapper?: AttributeNameMapper\n): boolean {\n\tlet value = element.getAttribute(name);\n\n\t// If not found and we have a mapper, try the native format (QTI 3.0 kebab-case)\n\tif ((value === null || value === undefined) && attributeMapper) {\n\t\tconst nativeName = attributeMapper.toNative(name);\n\t\tvalue = element.getAttribute(nativeName);\n\t}\n\n\tif (value === null || value === undefined) return defaultValue;\n\treturn value === 'true';\n}\n\n/**\n * Extract a number attribute from a QTI element\n * Supports both QTI 2.x (camelCase) and QTI 3.0 (kebab-case) attributes\n */\nfunction getNumberAttribute(\n\telement: QTIElement,\n\tname: string,\n\tdefaultValue: number,\n\tattributeMapper?: AttributeNameMapper\n): number {\n\tlet value = element.getAttribute(name);\n\n\t// If not found and we have a mapper, try the native format (QTI 3.0 kebab-case)\n\tif ((value === null || value === undefined) && attributeMapper) {\n\t\tconst nativeName = attributeMapper.toNative(name);\n\t\tvalue = element.getAttribute(nativeName);\n\t}\n\n\treturn value ? Number(value) : defaultValue;\n}\n\n/**\n * Extract a string attribute from a QTI element\n * Supports both QTI 2.x (camelCase) and QTI 3.0 (kebab-case) attributes\n */\nfunction getStringAttribute(\n\telement: QTIElement,\n\tname: string,\n\tdefaultValue = '',\n\tattributeMapper?: AttributeNameMapper\n): string {\n\tlet value = element.getAttribute(name);\n\n\t// If not found and we have a mapper, try the native format (QTI 3.0 kebab-case)\n\tif ((value === null || value === undefined) && attributeMapper) {\n\t\tconst nativeName = attributeMapper.toNative(name);\n\t\tvalue = element.getAttribute(nativeName);\n\t}\n\n\treturn value || defaultValue;\n}\n\n/**\n * Extract CSS classes from an element\n */\nfunction getClasses(element: QTIElement): string[] {\n\tconst classAttr = element.getAttribute('class');\n\treturn classAttr ? classAttr.split(/\\s+/).filter(Boolean) : [];\n}\n\n/**\n * Helper to check if an element's tag name matches a given QTI element name.\n * Handles both QTI 2.x and QTI 3.0 element naming conventions.\n *\n * @param rawTagName - The element's raw tag name from the HTML\n * @param expectedTagName - The tag name to check (in QTI 2.x format, e.g., 'simpleChoice')\n * @param mapper - Optional element name mapper for QTI version handling\n * @returns true if the tag name matches\n */\nfunction matchesTagName(\n\trawTagName: string | undefined,\n\texpectedTagName: string,\n\tmapper: ElementNameMapper\n): boolean {\n\tif (!rawTagName) return false;\n\n\t// Convert expected tag name to canonical form (lowercase)\n\tconst canonical = expectedTagName.toLowerCase();\n\n\t// Get the native form for this QTI version\n\tconst native = mapper.toNative(canonical);\n\n\t// Check if raw tag name matches the native form (case-insensitive)\n\treturn rawTagName.toLowerCase() === native.toLowerCase();\n}\n\n/** Whether `element`'s content is one element carrying `idref`. */\nfunction wrapsContentWithIdref(element: QTIElement, idref: string): boolean {\n\tconst content = element.childNodes.filter((child) => child.nodeType === 1 || child.text.trim() !== '');\n\tconst [only] = content;\n\treturn content.length === 1 && (only as QTIElement).getAttribute?.('data-catalog-idref') === idref;\n}\n\n/**\n * Create extraction utilities instance\n * Provides standard helpers for extracting data from QTI elements.\n * Automatically handles both QTI 2.x and QTI 3.0 element and attribute naming conventions.\n */\nexport function createExtractionUtils(\n\tsecurity?: PlayerSecurityConfig,\n\tmapper?: ElementNameMapper,\n\tattributeMapper?: AttributeNameMapper\n): ExtractionUtils {\n\t// Default to QTI 2.x mappers (primary supported QTI format)\n\tconst elementMapper = mapper || new Qti2xElementNameMapper();\n\tconst attrMapper = attributeMapper || new Qti2xAttributeNameMapper();\n\treturn {\n\t\tmatchesTag(element: QTIElement, tagName: string): boolean {\n\t\t\treturn matchesTagName(element.rawTagName, tagName, elementMapper);\n\t\t},\n\n\t\tgetChildrenByTag(element: QTIElement, tagName: string): QTIElement[] {\n\t\t\treturn getChildrenByTagWithMapper(element, tagName, elementMapper);\n\t\t},\n\n\t\tquerySelectorAll(element: QTIElement, selector: string): QTIElement[] {\n\t\t\t// Parse simple selectors like \"choiceInteraction simpleChoice\"\n\t\t\tconst parts = selector.split(/\\s+/);\n\t\t\tlet results: QTIElement[] = [element];\n\n\t\t\tfor (const part of parts) {\n\t\t\t\tconst nextResults: QTIElement[] = [];\n\t\t\t\tfor (const current of results) {\n\t\t\t\t\tif (matchesTagName(current.rawTagName, part, elementMapper)) {\n\t\t\t\t\t\tnextResults.push(current);\n\t\t\t\t\t}\n\t\t\t\t\tif (current.childNodes) {\n\t\t\t\t\t\tfor (const child of current.childNodes) {\n\t\t\t\t\t\t\tif (typeof child !== 'string' && matchesTagName((child as QTIElement).rawTagName, part, elementMapper)) {\n\t\t\t\t\t\t\t\tnextResults.push(child as QTIElement);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tresults = nextResults;\n\t\t\t}\n\n\t\t\treturn results;\n\t\t},\n\n\t\tquerySelector(element: QTIElement, selector: string): QTIElement | null {\n\t\t\tconst results = this.querySelectorAll(element, selector);\n\t\t\treturn results.length > 0 ? results[0] : null;\n\t\t},\n\n\t\thasChildWithTag(element: QTIElement, tagName: string): boolean {\n\t\t\t// Fast boolean check without allocation\n\t\t\tif (!element.childNodes) return false;\n\n\t\t\tfor (const child of element.childNodes) {\n\t\t\t\tif (typeof child !== 'string' && matchesTagName((child as QTIElement).rawTagName, tagName, elementMapper)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\n\t\tgetHtmlContent(element: QTIElement): string {\n\t\t\tconst html = element?.innerHTML?.trim() || '';\n\t\t\t// A prompt's or choice's own language, catalog idref and read-aloud suppression would\n\t\t\t// go with its tag, so they wrap its content. An object's markup stays as authored.\n\t\t\tconst attributes = element?.rawTagName?.toLowerCase() === 'object' ? undefined : readAloudAttributes(element);\n\t\t\t// Markup preparation docks a choice's idref on a wrapper around its content already.\n\t\t\tif (attributes?.['data-catalog-idref'] && wrapsContentWithIdref(element, attributes['data-catalog-idref'])) {\n\t\t\t\tdelete attributes['data-catalog-idref'];\n\t\t\t}\n\t\t\tconst wrapped =\n\t\t\t\thtml && attributes && Object.keys(attributes).length > 0\n\t\t\t\t\t? `<span ${Object.entries(attributes)\n\t\t\t\t\t\t\t.map(([name, value]) => `${name}=\"${value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;')}\"`)\n\t\t\t\t\t\t\t.join(' ')}>${html}</span>`\n\t\t\t\t\t: html;\n\t\t\treturn sanitizeTextContent(wrapped, { security });\n\t\t},\n\n\t\tgetTextContent(element: QTIElement): string {\n\t\t\treturn getTextContent(element);\n\t\t},\n\n\t\tgetAttribute(element: QTIElement, name: string, defaultValue = ''): string {\n\t\t\treturn getStringAttribute(element, name, defaultValue, attrMapper);\n\t\t},\n\n\t\tgetBooleanAttribute(element: QTIElement, name: string, defaultValue = false): boolean {\n\t\t\treturn getBooleanAttribute(element, name, defaultValue, attrMapper);\n\t\t},\n\n\t\tgetNumberAttribute(element: QTIElement, name: string, defaultValue = 0): number {\n\t\t\treturn getNumberAttribute(element, name, defaultValue, attrMapper);\n\t\t},\n\n\t\tgetPrompt(element: QTIElement): string | null {\n\t\t\tconst promptElement = getChildrenByTagWithMapper(element, 'prompt', elementMapper)[0];\n\t\t\treturn promptElement ? this.getHtmlContent(promptElement) : null;\n\t\t},\n\n\t\tgetClasses(element: QTIElement): string[] {\n\t\t\treturn getClasses(element);\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/extraction/utils.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAKpE;;GAEG;AACH,SAAS,cAAc,CAAC,OAAsC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**\n * Extraction utilities implementation\n *\n * Provides DOM manipulation and content extraction helpers for extractors\n */\n\nimport type { ElementNameMapper, AttributeNameMapper } from '@pie-qti/qti-common';\nimport { sanitizeTextContent } from '../core/sanitizer.js';\nimport { defaultExtractionMappers } from '../core/nameMappers.js';\nimport { escapeHtmlAttribute } from '../security/escapeHtml.js';\nimport { readAloudAttributes } from './interactionAccessibility.js';\nimport type { PlayerSecurityConfig } from '../types/index.js';\nimport type { QTIElement } from '../interactions/shared/types.js';\nimport type { ExtractionUtils } from './types.js';\n\n/**\n * Extract text content from QTI elements\n */\nfunction getTextContent(element: QTIElement | null | undefined): string {\n\treturn element?.textContent?.trim() || '';\n}\n\n/**\n * Get children by tag name with QTI version awareness\n */\nfunction getChildrenByTagWithMapper(\n\telement: QTIElement | null | undefined,\n\ttagName: string,\n\tmapper: ElementNameMapper\n): QTIElement[] {\n\tif (!element?.childNodes) return [];\n\treturn element.childNodes.filter((n) =>\n\t\tmatchesTagName((n as QTIElement).rawTagName, tagName, mapper)\n\t) as QTIElement[];\n}\n\n/**\n * Extract a boolean attribute from a QTI element\n * Supports both QTI 2.x (camelCase) and QTI 3.0 (kebab-case) attributes\n *\n * Every QTI interaction boolean is `xs:boolean`, whose lexical space is\n * `{true, false, 1, 0}` (XML Schema Part 2), so the on-forms are `\"true\"` and\n * `\"1\"` — not just the literal `\"true\"`. This helper is the one xs:boolean\n * reader for every extractor. (The media extractor's `isBooleanAttributeOn`\n * stays separate on purpose: it reads HTML presence semantics for\n * `<track default>`, which has no xs:boolean lexical space.)\n */\nfunction getBooleanAttribute(\n\telement: QTIElement,\n\tname: string,\n\tdefaultValue = false,\n\tattributeMapper?: AttributeNameMapper\n): boolean {\n\tlet value = element.getAttribute(name);\n\n\t// If not found and we have a mapper, try the native format (QTI 3.0 kebab-case)\n\tif ((value === null || value === undefined) && attributeMapper) {\n\t\tconst nativeName = attributeMapper.toNative(name);\n\t\tvalue = element.getAttribute(nativeName);\n\t}\n\n\tif (value === null || value === undefined) return defaultValue;\n\treturn value === 'true' || value === '1';\n}\n\n/**\n * Extract a number attribute from a QTI element\n * Supports both QTI 2.x (camelCase) and QTI 3.0 (kebab-case) attributes\n */\nfunction getNumberAttribute(\n\telement: QTIElement,\n\tname: string,\n\tdefaultValue: number,\n\tattributeMapper?: AttributeNameMapper\n): number {\n\tlet value = element.getAttribute(name);\n\n\t// If not found and we have a mapper, try the native format (QTI 3.0 kebab-case)\n\tif ((value === null || value === undefined) && attributeMapper) {\n\t\tconst nativeName = attributeMapper.toNative(name);\n\t\tvalue = element.getAttribute(nativeName);\n\t}\n\n\treturn value ? Number(value) : defaultValue;\n}\n\n/**\n * Extract a string attribute from a QTI element\n * Supports both QTI 2.x (camelCase) and QTI 3.0 (kebab-case) attributes\n */\nfunction getStringAttribute(\n\telement: QTIElement,\n\tname: string,\n\tdefaultValue = '',\n\tattributeMapper?: AttributeNameMapper\n): string {\n\tlet value = element.getAttribute(name);\n\n\t// If not found and we have a mapper, try the native format (QTI 3.0 kebab-case)\n\tif ((value === null || value === undefined) && attributeMapper) {\n\t\tconst nativeName = attributeMapper.toNative(name);\n\t\tvalue = element.getAttribute(nativeName);\n\t}\n\n\treturn value || defaultValue;\n}\n\n/**\n * Extract CSS classes from an element\n */\nfunction getClasses(element: QTIElement): string[] {\n\tconst classAttr = element.getAttribute('class');\n\treturn classAttr ? classAttr.split(/\\s+/).filter(Boolean) : [];\n}\n\n/**\n * Helper to check if an element's tag name matches a given QTI element name.\n * Handles both QTI 2.x and QTI 3.0 element naming conventions.\n *\n * @param rawTagName - The element's raw tag name from the HTML\n * @param expectedTagName - The tag name to check (in QTI 2.x format, e.g., 'simpleChoice')\n * @param mapper - Optional element name mapper for QTI version handling\n * @returns true if the tag name matches\n */\nfunction matchesTagName(\n\trawTagName: string | undefined,\n\texpectedTagName: string,\n\tmapper: ElementNameMapper\n): boolean {\n\tif (!rawTagName) return false;\n\n\t// Convert expected tag name to canonical form (lowercase)\n\tconst canonical = expectedTagName.toLowerCase();\n\n\t// Get the native form for this QTI version\n\tconst native = mapper.toNative(canonical);\n\n\t// Check if raw tag name matches the native form (case-insensitive)\n\treturn rawTagName.toLowerCase() === native.toLowerCase();\n}\n\n/** Whether `element`'s content is one element carrying `idref`. */\nfunction wrapsContentWithIdref(element: QTIElement, idref: string): boolean {\n\tconst content = element.childNodes.filter((child) => child.nodeType === 1 || child.text.trim() !== '');\n\tconst [only] = content;\n\treturn content.length === 1 && (only as QTIElement).getAttribute?.('data-catalog-idref') === idref;\n}\n\n/**\n * Validates one choice-like identifier set for an extractor: every item must carry an identifier\n * and none may repeat, as an interaction whose response holds identifiers would otherwise be\n * ambiguous. Items are identifiers (gapMatchInteraction's gaps are bare strings) or objects with\n * an optional `identifier`; each failure pushes one error into `errors`, with the same wording for\n * every extractor. `labels.plural` names the set in the missing-identifier error (\"source\n * choices\"), `labels.noun` in the duplicate error (\"source\").\n */\nexport function validateUniqueIdentifiers(\n\titems: ReadonlyArray<string | { identifier?: string } | undefined>,\n\terrors: string[],\n\tlabels: { plural: string; noun: string }\n): void {\n\tconst identifiers = new Set<string>();\n\tfor (const item of items) {\n\t\tconst identifier = typeof item === 'string' ? item : item?.identifier;\n\t\tif (!identifier) {\n\t\t\terrors.push(`All ${labels.plural} must have an identifier`);\n\t\t} else if (identifiers.has(identifier)) {\n\t\t\terrors.push(`Duplicate ${labels.noun} identifier: ${identifier}`);\n\t\t} else {\n\t\t\tidentifiers.add(identifier);\n\t\t}\n\t}\n}\n\n/**\n * Create extraction utilities instance\n * Provides standard helpers for extracting data from QTI elements.\n * Automatically handles both QTI 2.x and QTI 3.0 element and attribute naming conventions.\n */\nexport function createExtractionUtils(\n\tsecurity?: PlayerSecurityConfig,\n\tmapper?: ElementNameMapper,\n\tattributeMapper?: AttributeNameMapper\n): ExtractionUtils {\n\t// Default to QTI 2.x mappers (primary supported QTI format)\n\tconst { elementMapper, attrMapper } = defaultExtractionMappers(mapper, attributeMapper);\n\treturn {\n\t\tmatchesTag(element: QTIElement, tagName: string): boolean {\n\t\t\treturn matchesTagName(element.rawTagName, tagName, elementMapper);\n\t\t},\n\n\t\tgetChildrenByTag(element: QTIElement, tagName: string): QTIElement[] {\n\t\t\treturn getChildrenByTagWithMapper(element, tagName, elementMapper);\n\t\t},\n\n\t\tquerySelectorAll(element: QTIElement, selector: string): QTIElement[] {\n\t\t\t// Parse simple selectors like \"choiceInteraction simpleChoice\"\n\t\t\tconst parts = selector.split(/\\s+/);\n\t\t\tlet results: QTIElement[] = [element];\n\n\t\t\tfor (const part of parts) {\n\t\t\t\tconst nextResults: QTIElement[] = [];\n\t\t\t\tfor (const current of results) {\n\t\t\t\t\tif (matchesTagName(current.rawTagName, part, elementMapper)) {\n\t\t\t\t\t\tnextResults.push(current);\n\t\t\t\t\t}\n\t\t\t\t\tif (current.childNodes) {\n\t\t\t\t\t\tfor (const child of current.childNodes) {\n\t\t\t\t\t\t\tif (typeof child !== 'string' && matchesTagName((child as QTIElement).rawTagName, part, elementMapper)) {\n\t\t\t\t\t\t\t\tnextResults.push(child as QTIElement);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tresults = nextResults;\n\t\t\t}\n\n\t\t\treturn results;\n\t\t},\n\n\t\tquerySelector(element: QTIElement, selector: string): QTIElement | null {\n\t\t\tconst results = this.querySelectorAll(element, selector);\n\t\t\treturn results.length > 0 ? results[0] : null;\n\t\t},\n\n\t\thasChildWithTag(element: QTIElement, tagName: string): boolean {\n\t\t\t// Fast boolean check without allocation\n\t\t\tif (!element.childNodes) return false;\n\n\t\t\tfor (const child of element.childNodes) {\n\t\t\t\tif (typeof child !== 'string' && matchesTagName((child as QTIElement).rawTagName, tagName, elementMapper)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\n\t\tgetHtmlContent(element: QTIElement): string {\n\t\t\tconst html = element?.innerHTML?.trim() || '';\n\t\t\t// A prompt's or choice's own language, catalog idref and read-aloud suppression would\n\t\t\t// go with its tag, so they wrap its content. An object's markup stays as authored.\n\t\t\tconst attributes = element?.rawTagName?.toLowerCase() === 'object' ? undefined : readAloudAttributes(element);\n\t\t\t// Markup preparation docks a choice's idref on a wrapper around its content already.\n\t\t\tif (attributes?.['data-catalog-idref'] && wrapsContentWithIdref(element, attributes['data-catalog-idref'])) {\n\t\t\t\tdelete attributes['data-catalog-idref'];\n\t\t\t}\n\t\tconst wrapped =\n\t\t\thtml && attributes && Object.keys(attributes).length > 0\n\t\t\t\t? `<span ${Object.entries(attributes)\n\t\t\t\t\t\t.map(([name, value]) => `${name}=\"${escapeHtmlAttribute(value)}\"`)\n\t\t\t\t\t\t.join(' ')}>${html}</span>`\n\t\t\t\t: html;\n\t\t\treturn sanitizeTextContent(wrapped, { security });\n\t\t},\n\n\t\tgetTextContent(element: QTIElement): string {\n\t\t\treturn getTextContent(element);\n\t\t},\n\n\t\tgetAttribute(element: QTIElement, name: string, defaultValue = ''): string {\n\t\t\treturn getStringAttribute(element, name, defaultValue, attrMapper);\n\t\t},\n\n\t\tgetBooleanAttribute(element: QTIElement, name: string, defaultValue = false): boolean {\n\t\t\treturn getBooleanAttribute(element, name, defaultValue, attrMapper);\n\t\t},\n\n\t\tgetNumberAttribute(element: QTIElement, name: string, defaultValue = 0): number {\n\t\t\treturn getNumberAttribute(element, name, defaultValue, attrMapper);\n\t\t},\n\n\t\tgetPrompt(element: QTIElement): string | null {\n\t\t\tconst promptElement = getChildrenByTagWithMapper(element, 'prompt', elementMapper)[0];\n\t\t\treturn promptElement ? this.getHtmlContent(promptElement) : null;\n\t\t},\n\n\t\tgetClasses(element: QTIElement): string[] {\n\t\t\treturn getClasses(element);\n\t\t},\n\t};\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -2,22 +2,27 @@
2
2
  * @pie-qti/item-player
3
3
  * Modern QTI player (2.2/3.0) - Framework-agnostic with web components
4
4
  */
5
- export { type ComponentConfig, type ComponentPlugin, ComponentRegistry, createComponentRegistry, } from './core/ComponentRegistry.js';
6
- export * from './core/constants.js';
5
+ export { type ComponentConfig, type ComponentPlugin, ComponentRegistry, createComponentRegistry, DEFAULT_COMPONENT_TAGS_BY_TYPE, } from './core/ComponentRegistry.js';
7
6
  export * from './utils/drawingUtils.js';
8
7
  export { createAssessmentItemDefinition, type AssessmentItemDefinition, type AssessmentItemDefinitionConfig, type AssessmentItemDefinitionPlugin, } from './core/AssessmentItemDefinition.js';
9
- export { type ItemPresentationView, type ItemSession, type ItemSessionCommand, type ItemSessionEventCommand, type ItemSessionListener, type ItemSessionPresentationPolicy, type ItemSessionTransition, type ItemSessionView, type OpenItemSessionOptions, } from './core/ItemSession.js';
10
- export type { FinalItemBodyHtml, ItemInteractionMount, ItemPresentation, ItemPresentationFlowNode, } from './presentation/itemPresentationPlan.js';
11
- export { getRoleCapabilities, type RoleCapabilities } from './core/rolePolicy.js';
8
+ export { QtiComplianceError, type QtiItemDiagnostic, type QtiItemDiagnosticCode, type QtiItemDiagnosticSeverity, } from './core/compliance.js';
9
+ export { UnsupportedResponseProcessingTemplateError } from './core/responseProcessingTemplates.js';
10
+ export { UnknownResponseIdentifierError, type ItemPresentationView, type ItemSession, type ItemSessionCommand, type ItemSessionEventCommand, type ItemSessionListener, type ItemSessionPresentationPolicy, type ItemSessionTransition, type ItemSessionView, type OpenItemSessionOptions, } from './core/ItemSession.js';
11
+ export type { FinalItemBodyHtml, InlineInteractionPosition, ItemInteractionMount, ItemPresentation, ItemPresentationFlowNode, } from './presentation/itemPresentationPlan.js';
12
+ export type { ShownFeedback } from './presentation/feedbackAnnouncement.js';
13
+ /** The attribute on the empty slot that marks an interaction's authored position in the body. */
14
+ export { INTERACTION_SLOT_ATTRIBUTE } from './presentation/itemPresentationPlan.js';
15
+ export { isQtiRole, parseQtiRole, getRoleCapabilities, type RoleCapabilities, } from './core/rolePolicy.js';
16
+ export { isMatchGroupCompatible, type MatchGroupChoice } from './core/matchGroups.js';
17
+ export { orderChoiceLimits, type OrderChoiceLimits, type OrderSubsetInteraction, } from './interactions/order/limits.js';
18
+ export { classExcludesMinus, patternExcludesMinus } from './interactions/text-entry/inputMode.js';
12
19
  export type * from './interactions/shared/types.js';
13
20
  export { createExtendedTextNumericRecord, createExtendedTextResponse, createExtendedTextStringResponse, extendedTextResponseToStrings, type ExtendedTextNumericRecord, type ExtendedTextRecordField, } from './interactions/extended-text/response.js';
14
- export type { ElementExtractor, ExtractionContext, ExtractionDispatchResult, ExtractionResult, ExtractionUtils, InteractionDeliveryField, InteractionDeliveryPathSegment, InteractionDeliverySchema, ValidationResult, VariableDeclaration, } from './extraction/index.js';
15
- export { createExtractionContext, createExtractionRegistry, createExtractionUtils, ExtractionError, ExtractionRegistry, htmlField, isErrorResult, isSuccessResult, urlField, } from './extraction/index.js';
21
+ export type { ElementExtractor, ExtractionContext, ExtractionDispatchResult, ExtractionResult, ExtractionUtils, InteractionDeliveryField, InteractionDeliveryPathSegment, InteractionDeliverySchema, ValidationResult, ExtractionVariableDeclaration, } from './extraction/index.js';
22
+ export { createExtractionContext, createExtractionRegistry, createExtractionUtils, ExtractionError, ExtractionRegistry, htmlField, urlField, } from './extraction/index.js';
16
23
  export * from './types/index.js';
17
- export { globalPerformanceMonitor, type PerformanceEntry, PerformanceMonitor, type PerformanceMonitorConfig, type PerformanceReport, } from './utils/PerformanceMonitor.js';
18
- export { isResponseEmpty } from './utils/responseUtils.js';
19
24
  export type { PnpProfile, PnpTextAppearance, PnpToolSupports } from './pnp/types.js';
20
- export { applyPnpToRoot } from './pnp/applyPnp.js';
25
+ export { applyPnpToRoot, applyPnpToSurface, clearPnpSurface, isWithinPnpSurface, PNP_SURFACE_ATTRIBUTE, } from './pnp/applyPnp.js';
21
26
  export type { AfaPnpRecord } from './pnp/parsePnpXml.js';
22
27
  export { AFA_PNP_NAMESPACE, parseAfaPnpXml, parsePnpXml, pnpProfileFromAfa } from './pnp/parsePnpXml.js';
23
28
  export type { CatalogIndex, CatalogCard, CatalogEntry } from './catalog/types.js';
@@ -35,6 +40,7 @@ export type { AmdLoader, AmdLoaderOptions } from './pci/amdLoader.js';
35
40
  export { DEFAULT_RESOLUTION_CONFIG_PATHS, emptyResolutionConfig, parseModuleResolutionConfig, } from './pci/resolutionConfig.js';
36
41
  export type { PciResolutionConfig, PciResolutionShim } from './pci/resolutionConfig.js';
37
42
  export { toQtiVariableJson, fromQtiVariableJson } from './pci/qtiVariableJson.js';
43
+ export type { QtiRecordField } from './pci/qtiVariableJson.js';
38
44
  export { normalizeHeuristicsConfig, applyFeedbackTextHeuristics, shouldUseLenientImagePaths, shouldAutoPopulateFeedbackOutcome, DEFAULT_HEURISTICS_CONFIG, STRICT_QTI_CONFIG, FEEDBACK_TEXT_TRANSFORMS, type QtiHeuristicsConfig, type TextTransform, } from '@pie-qti/ims-cp-core';
39
45
  /**
40
46
  * NOTE (SSR safety):
package/dist/index.js CHANGED
@@ -3,23 +3,34 @@
3
3
  * Modern QTI player (2.2/3.0) - Framework-agnostic with web components
4
4
  */
5
5
  // Export web component registry for pluggable UI components
6
- export { ComponentRegistry, createComponentRegistry, } from './core/ComponentRegistry.js';
7
- export * from './core/constants.js';
6
+ export { ComponentRegistry, createComponentRegistry, DEFAULT_COMPONENT_TAGS_BY_TYPE, } from './core/ComponentRegistry.js';
8
7
  // Export drawing utilities
9
8
  export * from './utils/drawingUtils.js';
10
9
  export { createAssessmentItemDefinition, } from './core/AssessmentItemDefinition.js';
11
- export { getRoleCapabilities } from './core/rolePolicy.js';
10
+ export { QtiComplianceError, } from './core/compliance.js';
11
+ export { UnsupportedResponseProcessingTemplateError } from './core/responseProcessingTemplates.js';
12
+ export { UnknownResponseIdentifierError, } from './core/ItemSession.js';
13
+ /** The attribute on the empty slot that marks an interaction's authored position in the body. */
14
+ export { INTERACTION_SLOT_ATTRIBUTE } from './presentation/itemPresentationPlan.js';
15
+ export { isQtiRole, parseQtiRole, getRoleCapabilities, } from './core/rolePolicy.js';
16
+ // The pure matchGroup pairing rule shared by response validation and the renderers,
17
+ // so the delivered UI can never allow a pair validation rejects nor block one it accepts.
18
+ export { isMatchGroupCompatible } from './core/matchGroups.js';
19
+ // The pure order-subset rule (minChoices/maxChoices) shared by response validation and the
20
+ // order renderers, for the same reason (QTI 2.2 ASI §5.73, §5.42).
21
+ export { orderChoiceLimits, } from './interactions/order/limits.js';
22
+ // The XSD pattern scan shared by the inline text-entry and extended-text mobile
23
+ // keyboards: a numeric pad is only safe when the authored patternMask provably
24
+ // excludes `-` (phone number pads offer no minus key).
25
+ export { classExcludesMinus, patternExcludesMinus } from './interactions/text-entry/inputMode.js';
12
26
  export { createExtendedTextNumericRecord, createExtendedTextResponse, createExtendedTextStringResponse, extendedTextResponseToStrings, } from './interactions/extended-text/response.js';
13
- export { createExtractionContext, createExtractionRegistry, createExtractionUtils, ExtractionError, ExtractionRegistry, htmlField, isErrorResult, isSuccessResult, urlField, } from './extraction/index.js';
27
+ export { createExtractionContext, createExtractionRegistry, createExtractionUtils, ExtractionError, ExtractionRegistry, htmlField, urlField, } from './extraction/index.js';
14
28
  // NOTE:
15
29
  // The player’s primary rendering contract is via web components and the Svelte component entrypoint.
16
30
  // If you need non-web-component rendering, build it externally against the public extraction APIs.
17
31
  // Export all types including adaptive item types
18
32
  export * from './types/index.js';
19
- // Export utilities
20
- export { globalPerformanceMonitor, PerformanceMonitor, } from './utils/PerformanceMonitor.js';
21
- export { isResponseEmpty } from './utils/responseUtils.js';
22
- export { applyPnpToRoot } from './pnp/applyPnp.js';
33
+ export { applyPnpToRoot, applyPnpToSurface, clearPnpSurface, isWithinPnpSurface, PNP_SURFACE_ATTRIBUTE, } from './pnp/applyPnp.js';
23
34
  export { AFA_PNP_NAMESPACE, parseAfaPnpXml, parsePnpXml, pnpProfileFromAfa } from './pnp/parsePnpXml.js';
24
35
  export { extractCatalog, extractCatalogFromItemXml, mergeCatalogs } from './catalog/catalogExtractor.js';
25
36
  export { getCatalogEntry } from './catalog/catalogLookup.js';
package/dist/index.js.map C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,gCAAgC,EAChC,wBAAwB,GACxB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAClG,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAErD,OAAO,EACN,+BAA+B,EAC/B,qBAAqB,EACrB,2BAA2B,GAC3B,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAElF,qEAAqE;AACrE,qDAAqD;AACrD,OAAO,EACN,yBAAyB,EACzB,2BAA2B,EAC3B,0BAA0B,EAC1B,iCAAiC,EACjC,yBAAyB,EACzB,iBAAiB,EACjB,wBAAwB,GAGxB,MAAM,sBAAsB,CAAC;AAE9B;;;;;;;;GAQG","sourcesContent":["/**\n * @pie-qti/item-player\n * Modern QTI player (2.2/3.0) - Framework-agnostic with web components\n */\n\n\n// Export web component registry for pluggable UI components\nexport {\n\ttype ComponentConfig,\n\ttype ComponentPlugin,\n\tComponentRegistry,\n\tcreateComponentRegistry,\n} from './core/ComponentRegistry.js';\nexport * from './core/constants.js';\n// Export drawing utilities\nexport * from './utils/drawingUtils.js';\nexport {\n\tcreateAssessmentItemDefinition,\n\ttype AssessmentItemDefinition,\n\ttype AssessmentItemDefinitionConfig,\n\ttype AssessmentItemDefinitionPlugin,\n} from './core/AssessmentItemDefinition.js';\nexport {\n\ttype ItemPresentationView,\n\ttype ItemSession,\n\ttype ItemSessionCommand,\n\ttype ItemSessionEventCommand,\n\ttype ItemSessionListener,\n\ttype ItemSessionPresentationPolicy,\n\ttype ItemSessionTransition,\n\ttype ItemSessionView,\n\ttype OpenItemSessionOptions,\n} from './core/ItemSession.js';\nexport type {\n\tFinalItemBodyHtml,\n\tItemInteractionMount,\n\tItemPresentation,\n\tItemPresentationFlowNode,\n} from './presentation/itemPresentationPlan.js';\nexport { getRoleCapabilities, type RoleCapabilities } from './core/rolePolicy.js';\n// Render-facing interaction contracts. Standard extractors remain implementation details.\nexport type * from './interactions/shared/types.js';\nexport {\n\tcreateExtendedTextNumericRecord,\n\tcreateExtendedTextResponse,\n\tcreateExtendedTextStringResponse,\n\textendedTextResponseToStrings,\n\ttype ExtendedTextNumericRecord,\n\ttype ExtendedTextRecordField,\n} from './interactions/extended-text/response.js';\nexport type {\n\tElementExtractor,\n\tExtractionContext,\n\tExtractionDispatchResult,\n\tExtractionResult,\n\tExtractionUtils,\n\tInteractionDeliveryField,\n\tInteractionDeliveryPathSegment,\n\tInteractionDeliverySchema,\n\tValidationResult,\n\tVariableDeclaration,\n} from './extraction/index.js';\nexport {\n\tcreateExtractionContext,\n\tcreateExtractionRegistry,\n\tcreateExtractionUtils,\n\tExtractionError,\n\tExtractionRegistry,\n\thtmlField,\n\tisErrorResult,\n\tisSuccessResult,\n\turlField,\n} from './extraction/index.js';\n// NOTE:\n// The player’s primary rendering contract is via web components and the Svelte component entrypoint.\n// If you need non-web-component rendering, build it externally against the public extraction APIs.\n// Export all types including adaptive item types\nexport * from './types/index.js';\n// Export utilities\nexport {\n\tglobalPerformanceMonitor,\n\ttype PerformanceEntry,\n\tPerformanceMonitor,\n\ttype PerformanceMonitorConfig,\n\ttype PerformanceReport,\n} from './utils/PerformanceMonitor.js';\n\nexport { isResponseEmpty } from './utils/responseUtils.js';\n\n// PNP profile (AfA PNP 3.0, QTI 3's per-candidate profile)\nexport type { PnpProfile, PnpTextAppearance, PnpToolSupports } from './pnp/types.js';\nexport { applyPnpToRoot } from './pnp/applyPnp.js';\nexport type { AfaPnpRecord } from './pnp/parsePnpXml.js';\nexport { AFA_PNP_NAMESPACE, parseAfaPnpXml, parsePnpXml, pnpProfileFromAfa } from './pnp/parsePnpXml.js';\n\n// Catalog (QTI 3.0 §6.3)\nexport type { CatalogIndex, CatalogCard, CatalogEntry } from './catalog/types.js';\nexport { extractCatalog, extractCatalogFromItemXml, mergeCatalogs } from './catalog/catalogExtractor.js';\nexport { getCatalogEntry } from './catalog/catalogLookup.js';\nexport type { ResolvedItemDeliveryContext } from '@pie-qti/ims-cp-core';\n\n// PCI — Portable Custom Interaction (QTI 3.0 §6.1)\nexport type {\n\tExtractedPci,\n\tPciConfiguration,\n\tPciCustomInteractionContext,\n\tPciHostController,\n\tPciHostOptions,\n\tPciInteractionStatus,\n\tPciModuleEntry,\n\tPciModulePathKind,\n\tPciModuleResolutionContext,\n\tPciModuleResolver,\n\tPciRegistryObservation,\n\tPciResponseDeclarationInfo,\n\tQtiCustomInteractionRegistration,\n\tQtiPciConfiguration,\n\tQtiPciInstance,\n} from './pci/types.js';\nexport { PciLoadError, PciModuleResolverRequiredError } from './pci/types.js';\nexport { PciHost } from './pci/PciHost.js';\nexport {\n\tcreateAllowlistPciModuleResolver,\n\tPciModuleNotAllowedError,\n} from './pci/allowlistResolver.js';\nexport type { AllowlistPciResolverOptions } from './pci/allowlistResolver.js';\nexport { installPciRegistry, getSharedPciRegistry, PCI_REGISTRY_GLOBAL } from './pci/registry.js';\nexport { createAmdLoader } from './pci/amdLoader.js';\nexport type { AmdLoader, AmdLoaderOptions } from './pci/amdLoader.js';\nexport {\n\tDEFAULT_RESOLUTION_CONFIG_PATHS,\n\temptyResolutionConfig,\n\tparseModuleResolutionConfig,\n} from './pci/resolutionConfig.js';\nexport type { PciResolutionConfig, PciResolutionShim } from './pci/resolutionConfig.js';\nexport { toQtiVariableJson, fromQtiVariableJson } from './pci/qtiVariableJson.js';\n\n// Re-export QTI heuristics from @pie-qti/ims-cp-core for convenience\n// (heuristics are now in the shared ingestion layer)\nexport {\n\tnormalizeHeuristicsConfig,\n\tapplyFeedbackTextHeuristics,\n\tshouldUseLenientImagePaths,\n\tshouldAutoPopulateFeedbackOutcome,\n\tDEFAULT_HEURISTICS_CONFIG,\n\tSTRICT_QTI_CONFIG,\n\tFEEDBACK_TEXT_TRANSFORMS,\n\ttype QtiHeuristicsConfig,\n\ttype TextTransform,\n} from '@pie-qti/ims-cp-core';\n\n/**\n * NOTE (SSR safety):\n * Web component base classes depend on DOM globals like `HTMLElement` and must not be\n * re-exported from the main entrypoint. Item ownership flows through\n * AssessmentItemDefinition and ItemSession in every deployment.\n *\n * Import web-components from the subpath entry instead:\n * - `@pie-qti/item-player/web-components`\n */\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,4DAA4D;AAC5D,OAAO,EAGN,iBAAiB,EACjB,uBAAuB,EACvB,8BAA8B,GAC9B,MAAM,6BAA6B,CAAC;AACrC,2BAA2B;AAC3B,cAAc,yBAAyB,CAAC;AACxC,OAAO,EACN,8BAA8B,GAI9B,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACN,kBAAkB,GAIlB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,0CAA0C,EAAE,MAAM,uCAAuC,CAAC;AACnG,OAAO,EACN,8BAA8B,GAU9B,MAAM,uBAAuB,CAAC;AAS/B,iGAAiG;AACjG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wCAAwC,CAAC;AACpF,OAAO,EACN,SAAS,EACT,YAAY,EACZ,mBAAmB,GAEnB,MAAM,sBAAsB,CAAC;AAC9B,oFAAoF;AACpF,0FAA0F;AAC1F,OAAO,EAAE,sBAAsB,EAAyB,MAAM,uBAAuB,CAAC;AACtF,2FAA2F;AAC3F,mEAAmE;AACnE,OAAO,EACN,iBAAiB,GAGjB,MAAM,gCAAgC,CAAC;AACxC,gFAAgF;AAChF,+EAA+E;AAC/E,uDAAuD;AACvD,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAGlG,OAAO,EACN,+BAA+B,EAC/B,0BAA0B,EAC1B,gCAAgC,EAChC,6BAA6B,GAG7B,MAAM,0CAA0C,CAAC;AAalD,OAAO,EACN,uBAAuB,EACvB,wBAAwB,EACxB,qBAAqB,EACrB,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,QAAQ,GACR,MAAM,uBAAuB,CAAC;AAC/B,QAAQ;AACR,qGAAqG;AACrG,mGAAmG;AACnG,iDAAiD;AACjD,cAAc,kBAAkB,CAAC;AAGjC,OAAO,EACN,cAAc,EACd,iBAAiB,EACjB,eAAe,EACf,kBAAkB,EAClB,qBAAqB,GACrB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAIzG,OAAO,EAAE,cAAc,EAAE,yBAAyB,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACzG,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAqB7D,OAAO,EAAE,YAAY,EAAE,8BAA8B,EAAE,MAAM,gBAAgB,CAAC;AAC9E,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EACN,gCAAgC,EAChC,wBAAwB,GACxB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAClG,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAErD,OAAO,EACN,+BAA+B,EAC/B,qBAAqB,EACrB,2BAA2B,GAC3B,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAGlF,qEAAqE;AACrE,qDAAqD;AACrD,OAAO,EACN,yBAAyB,EACzB,2BAA2B,EAC3B,0BAA0B,EAC1B,iCAAiC,EACjC,yBAAyB,EACzB,iBAAiB,EACjB,wBAAwB,GAGxB,MAAM,sBAAsB,CAAC;AAE9B;;;;;;;;GAQG","sourcesContent":["/**\n * @pie-qti/item-player\n * Modern QTI player (2.2/3.0) - Framework-agnostic with web components\n */\n\n\n// Export web component registry for pluggable UI components\nexport {\n\ttype ComponentConfig,\n\ttype ComponentPlugin,\n\tComponentRegistry,\n\tcreateComponentRegistry,\n\tDEFAULT_COMPONENT_TAGS_BY_TYPE,\n} from './core/ComponentRegistry.js';\n// Export drawing utilities\nexport * from './utils/drawingUtils.js';\nexport {\n\tcreateAssessmentItemDefinition,\n\ttype AssessmentItemDefinition,\n\ttype AssessmentItemDefinitionConfig,\n\ttype AssessmentItemDefinitionPlugin,\n} from './core/AssessmentItemDefinition.js';\nexport {\n\tQtiComplianceError,\n\ttype QtiItemDiagnostic,\n\ttype QtiItemDiagnosticCode,\n\ttype QtiItemDiagnosticSeverity,\n} from './core/compliance.js';\nexport { UnsupportedResponseProcessingTemplateError } from './core/responseProcessingTemplates.js';\nexport {\n\tUnknownResponseIdentifierError,\n\ttype ItemPresentationView,\n\ttype ItemSession,\n\ttype ItemSessionCommand,\n\ttype ItemSessionEventCommand,\n\ttype ItemSessionListener,\n\ttype ItemSessionPresentationPolicy,\n\ttype ItemSessionTransition,\n\ttype ItemSessionView,\n\ttype OpenItemSessionOptions,\n} from './core/ItemSession.js';\nexport type {\n\tFinalItemBodyHtml,\n\tInlineInteractionPosition,\n\tItemInteractionMount,\n\tItemPresentation,\n\tItemPresentationFlowNode,\n} from './presentation/itemPresentationPlan.js';\nexport type { ShownFeedback } from './presentation/feedbackAnnouncement.js';\n/** The attribute on the empty slot that marks an interaction's authored position in the body. */\nexport { INTERACTION_SLOT_ATTRIBUTE } from './presentation/itemPresentationPlan.js';\nexport {\n\tisQtiRole,\n\tparseQtiRole,\n\tgetRoleCapabilities,\n\ttype RoleCapabilities,\n} from './core/rolePolicy.js';\n// The pure matchGroup pairing rule shared by response validation and the renderers,\n// so the delivered UI can never allow a pair validation rejects nor block one it accepts.\nexport { isMatchGroupCompatible, type MatchGroupChoice } from './core/matchGroups.js';\n// The pure order-subset rule (minChoices/maxChoices) shared by response validation and the\n// order renderers, for the same reason (QTI 2.2 ASI §5.73, §5.42).\nexport {\n\torderChoiceLimits,\n\ttype OrderChoiceLimits,\n\ttype OrderSubsetInteraction,\n} from './interactions/order/limits.js';\n// The XSD pattern scan shared by the inline text-entry and extended-text mobile\n// keyboards: a numeric pad is only safe when the authored patternMask provably\n// excludes `-` (phone number pads offer no minus key).\nexport { classExcludesMinus, patternExcludesMinus } from './interactions/text-entry/inputMode.js';\n// Render-facing interaction contracts. Standard extractors remain implementation details.\nexport type * from './interactions/shared/types.js';\nexport {\n\tcreateExtendedTextNumericRecord,\n\tcreateExtendedTextResponse,\n\tcreateExtendedTextStringResponse,\n\textendedTextResponseToStrings,\n\ttype ExtendedTextNumericRecord,\n\ttype ExtendedTextRecordField,\n} from './interactions/extended-text/response.js';\nexport type {\n\tElementExtractor,\n\tExtractionContext,\n\tExtractionDispatchResult,\n\tExtractionResult,\n\tExtractionUtils,\n\tInteractionDeliveryField,\n\tInteractionDeliveryPathSegment,\n\tInteractionDeliverySchema,\n\tValidationResult,\n\tExtractionVariableDeclaration,\n} from './extraction/index.js';\nexport {\n\tcreateExtractionContext,\n\tcreateExtractionRegistry,\n\tcreateExtractionUtils,\n\tExtractionError,\n\tExtractionRegistry,\n\thtmlField,\n\turlField,\n} from './extraction/index.js';\n// NOTE:\n// The player’s primary rendering contract is via web components and the Svelte component entrypoint.\n// If you need non-web-component rendering, build it externally against the public extraction APIs.\n// Export all types including adaptive item types\nexport * from './types/index.js';\n// PNP profile (AfA PNP 3.0, QTI 3's per-candidate profile)\nexport type { PnpProfile, PnpTextAppearance, PnpToolSupports } from './pnp/types.js';\nexport {\n\tapplyPnpToRoot,\n\tapplyPnpToSurface,\n\tclearPnpSurface,\n\tisWithinPnpSurface,\n\tPNP_SURFACE_ATTRIBUTE,\n} from './pnp/applyPnp.js';\nexport type { AfaPnpRecord } from './pnp/parsePnpXml.js';\nexport { AFA_PNP_NAMESPACE, parseAfaPnpXml, parsePnpXml, pnpProfileFromAfa } from './pnp/parsePnpXml.js';\n\n// Catalog (QTI 3.0 §6.3)\nexport type { CatalogIndex, CatalogCard, CatalogEntry } from './catalog/types.js';\nexport { extractCatalog, extractCatalogFromItemXml, mergeCatalogs } from './catalog/catalogExtractor.js';\nexport { getCatalogEntry } from './catalog/catalogLookup.js';\nexport type { ResolvedItemDeliveryContext } from '@pie-qti/ims-cp-core';\n\n// PCI — Portable Custom Interaction (QTI 3.0 §6.1)\nexport type {\n\tExtractedPci,\n\tPciConfiguration,\n\tPciCustomInteractionContext,\n\tPciHostController,\n\tPciHostOptions,\n\tPciInteractionStatus,\n\tPciModuleEntry,\n\tPciModulePathKind,\n\tPciModuleResolutionContext,\n\tPciModuleResolver,\n\tPciRegistryObservation,\n\tPciResponseDeclarationInfo,\n\tQtiCustomInteractionRegistration,\n\tQtiPciConfiguration,\n\tQtiPciInstance,\n} from './pci/types.js';\nexport { PciLoadError, PciModuleResolverRequiredError } from './pci/types.js';\nexport { PciHost } from './pci/PciHost.js';\nexport {\n\tcreateAllowlistPciModuleResolver,\n\tPciModuleNotAllowedError,\n} from './pci/allowlistResolver.js';\nexport type { AllowlistPciResolverOptions } from './pci/allowlistResolver.js';\nexport { installPciRegistry, getSharedPciRegistry, PCI_REGISTRY_GLOBAL } from './pci/registry.js';\nexport { createAmdLoader } from './pci/amdLoader.js';\nexport type { AmdLoader, AmdLoaderOptions } from './pci/amdLoader.js';\nexport {\n\tDEFAULT_RESOLUTION_CONFIG_PATHS,\n\temptyResolutionConfig,\n\tparseModuleResolutionConfig,\n} from './pci/resolutionConfig.js';\nexport type { PciResolutionConfig, PciResolutionShim } from './pci/resolutionConfig.js';\nexport { toQtiVariableJson, fromQtiVariableJson } from './pci/qtiVariableJson.js';\nexport type { QtiRecordField } from './pci/qtiVariableJson.js';\n\n// Re-export QTI heuristics from @pie-qti/ims-cp-core for convenience\n// (heuristics are now in the shared ingestion layer)\nexport {\n\tnormalizeHeuristicsConfig,\n\tapplyFeedbackTextHeuristics,\n\tshouldUseLenientImagePaths,\n\tshouldAutoPopulateFeedbackOutcome,\n\tDEFAULT_HEURISTICS_CONFIG,\n\tSTRICT_QTI_CONFIG,\n\tFEEDBACK_TEXT_TRANSFORMS,\n\ttype QtiHeuristicsConfig,\n\ttype TextTransform,\n} from '@pie-qti/ims-cp-core';\n\n/**\n * NOTE (SSR safety):\n * Web component base classes depend on DOM globals like `HTMLElement` and must not be\n * re-exported from the main entrypoint. Item ownership flows through\n * AssessmentItemDefinition and ItemSession in every deployment.\n *\n * Import web-components from the subpath entry instead:\n * - `@pie-qti/item-player/web-components`\n */\n"]}
@@ -14,6 +14,7 @@ export interface AssociateData {
14
14
  matchMax: number;
15
15
  matchMin?: number;
16
16
  matchGroup?: string[];
17
+ fixed?: boolean;
17
18
  classes?: string[];
18
19
  }>;
19
20
  shuffle: boolean;
@@ -3,6 +3,7 @@
3
3
  *
4
4
  * Extracts data from associateInteraction elements (associating items)
5
5
  */
6
+ import { validateUniqueIdentifiers } from '../../extraction/utils.js';
6
7
  import { maybeShuffle } from '../../core/shuffle.js';
7
8
  /**
8
9
  * Standard QTI associate interaction extractor
@@ -29,18 +30,24 @@ export const standardAssociateExtractor = {
29
30
  const matchMin = utils.getNumberAttribute(choice, 'matchMin', 0);
30
31
  const matchGroupRaw = utils.getAttribute(choice, 'matchGroup', '');
31
32
  const matchGroup = matchGroupRaw.split(/\s+/).filter(Boolean);
33
+ const fixed = utils.getBooleanAttribute(choice, 'fixed');
32
34
  return {
33
35
  identifier: utils.getAttribute(choice, 'identifier', ''),
34
36
  text: utils.getHtmlContent(choice),
35
37
  matchMax,
36
38
  ...(matchMin > 0 ? { matchMin } : {}),
37
39
  ...(matchGroup.length > 0 ? { matchGroup } : {}),
40
+ // Authored fixed pins the choice under shuffle (QTI fixed.SimpleAssociableChoice.Attr).
41
+ ...(fixed ? { fixed } : {}),
38
42
  ...(classes.length > 0 ? { classes } : {}),
39
43
  };
40
44
  });
41
- // Extract attributes with proper defaults
45
+ // Extract attributes with proper defaults. maxAssociations is optional with default 1
46
+ // in every spec that defines it: QTI 2.1 XSD (`use="optional" default="1"`),
47
+ // QTI 2.2 ASI Information Model Table 5.6.2 and QTI 3.0 Table 5.8.2
48
+ // (`Default = "1"`); 0 means no restriction.
42
49
  const shuffle = utils.getBooleanAttribute(element, 'shuffle');
43
- const maxAssociations = utils.getNumberAttribute(element, 'maxAssociations', 0);
50
+ const maxAssociations = utils.getNumberAttribute(element, 'maxAssociations', 1);
44
51
  const minAssociations = utils.getNumberAttribute(element, 'minAssociations', 0);
45
52
  // Extract prompt (optional)
46
53
  const promptElements = utils.getChildrenByTag(element, 'prompt');
@@ -61,17 +68,8 @@ export const standardAssociateExtractor = {
61
68
  }
62
69
  // Validate choice identifiers
63
70
  if (data.choices) {
64
- const identifiers = new Set();
71
+ validateUniqueIdentifiers(data.choices, errors, { plural: 'choices', noun: 'choice' });
65
72
  for (const choice of data.choices) {
66
- if (!choice.identifier) {
67
- errors.push('All choices must have an identifier');
68
- }
69
- else if (identifiers.has(choice.identifier)) {
70
- errors.push(`Duplicate choice identifier: ${choice.identifier}`);
71
- }
72
- else {
73
- identifiers.add(choice.identifier);
74
- }
75
73
  // Validate matchMax
76
74
  if (choice.matchMax < 0) {
77
75
  errors.push(`matchMax must be non-negative for choice ${choice.identifier}`);