@pie-qti/item-player 0.1.8 → 0.1.10

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 (199) hide show
  1. package/README.md +17 -0
  2. package/dist/catalog/applyGlossaryTriggers.d.ts +13 -2
  3. package/dist/catalog/applyGlossaryTriggers.d.ts.map +1 -1
  4. package/dist/catalog/glossaryAction.d.ts +4 -2
  5. package/dist/catalog/glossaryAction.d.ts.map +1 -1
  6. package/dist/components/utils/index.d.ts +1 -2
  7. package/dist/components/utils/index.d.ts.map +1 -1
  8. package/dist/components/utils/index.js +1 -2
  9. package/dist/core/ComponentRegistry.d.ts +10 -1
  10. package/dist/core/ComponentRegistry.d.ts.map +1 -1
  11. package/dist/core/ComponentRegistry.js +42 -1
  12. package/dist/core/Player.d.ts +10 -2
  13. package/dist/core/Player.d.ts.map +1 -1
  14. package/dist/core/Player.js +54 -46
  15. package/dist/document/AssessmentItemDocument.d.ts +1 -1
  16. package/dist/element.d.ts +15 -0
  17. package/dist/element.js +1921 -1785
  18. package/dist/element.js.map +1 -1
  19. package/dist/extraction/ExtractionRegistry.d.ts +1 -1
  20. package/dist/extraction/createContext.d.ts +1 -1
  21. package/dist/extraction/index.d.ts +2 -2
  22. package/dist/extraction/index.d.ts.map +1 -1
  23. package/dist/extraction/index.js +1 -1
  24. package/dist/extraction/interactionExtractionPipeline.d.ts +1 -1
  25. package/dist/extraction/interactionSecurity.d.ts +1 -1
  26. package/dist/extraction/types.d.ts +1 -1
  27. package/dist/presentation/itemPresentationPlan.d.ts +54 -0
  28. package/dist/presentation/itemPresentationPlan.d.ts.map +1 -0
  29. package/dist/presentation/itemPresentationPlan.js +98 -0
  30. package/dist/types/index.d.ts +17 -2
  31. package/dist/types/index.d.ts.map +1 -1
  32. package/dist/types/index.js +0 -3
  33. package/dist/web-components/QTIInteractionBase.d.ts +1 -1
  34. package/dist/web-components/QTIInteractionElement.d.ts +1 -1
  35. package/package.json +10 -12
  36. package/src/__tests__/catalog.test.ts +0 -267
  37. package/src/__tests__/fixtures/pci/echo-pci.js +0 -49
  38. package/src/__tests__/pci.test.ts +0 -353
  39. package/src/__tests__/qti3-attribute-extraction.test.ts +0 -174
  40. package/src/__tests__/qti3-debug.test.ts +0 -140
  41. package/src/__tests__/qti3-extraction.test.ts +0 -309
  42. package/src/catalog/applyGlossaryTriggers.ts +0 -372
  43. package/src/catalog/catalogExtractor.ts +0 -130
  44. package/src/catalog/catalogLookup.ts +0 -53
  45. package/src/catalog/glossaryAction.ts +0 -38
  46. package/src/catalog/types.ts +0 -37
  47. package/src/components/ItemBody.svelte +0 -363
  48. package/src/components/ItemPlayer.svelte +0 -163
  49. package/src/components/ModalFeedbackDisplay.svelte +0 -97
  50. package/src/components/actions/typesetAction.ts +0 -74
  51. package/src/components/index.ts +0 -22
  52. package/src/components/utils/assignProps.ts +0 -2
  53. package/src/components/utils/feedbackUtils.ts +0 -140
  54. package/src/components/utils/index.ts +0 -13
  55. package/src/components/utils/stimulusRender.ts +0 -93
  56. package/src/components/utils/stylesheetRender.ts +0 -58
  57. package/src/core/ComponentRegistry.ts +0 -248
  58. package/src/core/Player.ts +0 -1618
  59. package/src/core/Plugin.ts +0 -123
  60. package/src/core/PluginManager.ts +0 -182
  61. package/src/core/constants.ts +0 -117
  62. package/src/core/declarations.ts +0 -171
  63. package/src/core/parsingLimits.ts +0 -62
  64. package/src/core/random.ts +0 -24
  65. package/src/core/rolePolicy.ts +0 -34
  66. package/src/core/sanitizer.ts +0 -305
  67. package/src/core/trustedTypes.ts +0 -63
  68. package/src/core/urlPolicy.ts +0 -98
  69. package/src/document/AssessmentItemDocument.ts +0 -247
  70. package/src/element.ts +0 -128
  71. package/src/extensions/MathLiveEditor.ts +0 -313
  72. package/src/extraction/ExtractionRegistry.ts +0 -335
  73. package/src/extraction/createContext.ts +0 -52
  74. package/src/extraction/extractors/associateExtractor.ts +0 -1
  75. package/src/extraction/extractors/choiceExtractor.ts +0 -1
  76. package/src/extraction/extractors/conformance-qti3-advanced.test.ts +0 -239
  77. package/src/extraction/extractors/conformance-qti3-basic.test.ts +0 -82
  78. package/src/extraction/extractors/conformance.test.ts +0 -208
  79. package/src/extraction/extractors/customExtractor.ts +0 -1
  80. package/src/extraction/extractors/drawingExtractor.ts +0 -1
  81. package/src/extraction/extractors/endAttemptExtractor.ts +0 -1
  82. package/src/extraction/extractors/extendedTextExtractor.ts +0 -1
  83. package/src/extraction/extractors/gapMatchExtractor.ts +0 -1
  84. package/src/extraction/extractors/graphicAssociateExtractor.ts +0 -1
  85. package/src/extraction/extractors/graphicGapMatchExtractor.ts +0 -1
  86. package/src/extraction/extractors/graphicOrderExtractor.ts +0 -1
  87. package/src/extraction/extractors/hotspotExtractor.ts +0 -1
  88. package/src/extraction/extractors/hottextExtractor.ts +0 -1
  89. package/src/extraction/extractors/index.ts +0 -9
  90. package/src/extraction/extractors/inlineChoiceExtractor.ts +0 -1
  91. package/src/extraction/extractors/matchExtractor.ts +0 -1
  92. package/src/extraction/extractors/mediaExtractor.ts +0 -1
  93. package/src/extraction/extractors/orderExtractor.ts +0 -1
  94. package/src/extraction/extractors/portableCustomExtractor.ts +0 -1
  95. package/src/extraction/extractors/positionObjectExtractor.ts +0 -1
  96. package/src/extraction/extractors/selectPointExtractor.ts +0 -1
  97. package/src/extraction/extractors/sliderExtractor.ts +0 -1
  98. package/src/extraction/extractors/textEntryExtractor.ts +0 -1
  99. package/src/extraction/extractors/uploadExtractor.ts +0 -1
  100. package/src/extraction/index.ts +0 -108
  101. package/src/extraction/interactionExtractionPipeline.ts +0 -70
  102. package/src/extraction/interactionSecurity.ts +0 -60
  103. package/src/extraction/types.ts +0 -246
  104. package/src/extraction/utils.ts +0 -243
  105. package/src/iframe/IFramePlayerHost.ts +0 -265
  106. package/src/iframe/index.ts +0 -11
  107. package/src/iframe/protocol.ts +0 -137
  108. package/src/index.ts +0 -101
  109. package/src/interactions/associate/extractor.ts +0 -133
  110. package/src/interactions/associate/index.ts +0 -2
  111. package/src/interactions/associate/types.ts +0 -1
  112. package/src/interactions/choice/extractor.ts +0 -121
  113. package/src/interactions/choice/index.ts +0 -2
  114. package/src/interactions/choice/types.ts +0 -1
  115. package/src/interactions/custom/extractor.ts +0 -72
  116. package/src/interactions/custom/index.ts +0 -2
  117. package/src/interactions/custom/types.ts +0 -1
  118. package/src/interactions/drawing/extractor.ts +0 -113
  119. package/src/interactions/drawing/index.ts +0 -2
  120. package/src/interactions/drawing/types.ts +0 -1
  121. package/src/interactions/end-attempt/extractor.ts +0 -74
  122. package/src/interactions/end-attempt/index.ts +0 -2
  123. package/src/interactions/end-attempt/types.ts +0 -1
  124. package/src/interactions/extended-text/extractor.ts +0 -92
  125. package/src/interactions/extended-text/index.ts +0 -2
  126. package/src/interactions/extended-text/types.ts +0 -1
  127. package/src/interactions/gap-match/extractor.ts +0 -193
  128. package/src/interactions/gap-match/index.ts +0 -2
  129. package/src/interactions/gap-match/types.ts +0 -1
  130. package/src/interactions/graphic-associate/extractor.ts +0 -192
  131. package/src/interactions/graphic-associate/index.ts +0 -2
  132. package/src/interactions/graphic-associate/types.ts +0 -1
  133. package/src/interactions/graphic-gap-match/extractor.ts +0 -257
  134. package/src/interactions/graphic-gap-match/index.ts +0 -2
  135. package/src/interactions/graphic-gap-match/types.ts +0 -1
  136. package/src/interactions/graphic-order/extractor.ts +0 -162
  137. package/src/interactions/graphic-order/index.ts +0 -2
  138. package/src/interactions/graphic-order/types.ts +0 -1
  139. package/src/interactions/hotspot/extractor.ts +0 -208
  140. package/src/interactions/hotspot/index.ts +0 -2
  141. package/src/interactions/hotspot/types.ts +0 -1
  142. package/src/interactions/hottext/extractor.ts +0 -163
  143. package/src/interactions/hottext/index.ts +0 -2
  144. package/src/interactions/hottext/types.ts +0 -1
  145. package/src/interactions/index.ts +0 -52
  146. package/src/interactions/inline/index.ts +0 -1
  147. package/src/interactions/inline/render-plan.ts +0 -105
  148. package/src/interactions/inline-choice/InlineChoice.svelte +0 -57
  149. package/src/interactions/inline-choice/extractor.ts +0 -105
  150. package/src/interactions/inline-choice/index.ts +0 -2
  151. package/src/interactions/inline-choice/types.ts +0 -1
  152. package/src/interactions/match/extractor.ts +0 -187
  153. package/src/interactions/match/index.ts +0 -2
  154. package/src/interactions/match/types.ts +0 -1
  155. package/src/interactions/media/extractor.ts +0 -168
  156. package/src/interactions/media/index.ts +0 -2
  157. package/src/interactions/media/types.ts +0 -1
  158. package/src/interactions/modules.ts +0 -111
  159. package/src/interactions/order/extractor.ts +0 -120
  160. package/src/interactions/order/index.ts +0 -2
  161. package/src/interactions/order/types.ts +0 -1
  162. package/src/interactions/portable-custom/extractor.ts +0 -122
  163. package/src/interactions/portable-custom/index.ts +0 -2
  164. package/src/interactions/portable-custom/types.ts +0 -1
  165. package/src/interactions/position-object/extractor.ts +0 -243
  166. package/src/interactions/position-object/index.ts +0 -2
  167. package/src/interactions/position-object/types.ts +0 -1
  168. package/src/interactions/select-point/extractor.ts +0 -143
  169. package/src/interactions/select-point/index.ts +0 -2
  170. package/src/interactions/select-point/types.ts +0 -1
  171. package/src/interactions/shared/index.ts +0 -1
  172. package/src/interactions/shared/types.ts +0 -430
  173. package/src/interactions/slider/extractor.ts +0 -102
  174. package/src/interactions/slider/index.ts +0 -2
  175. package/src/interactions/slider/types.ts +0 -1
  176. package/src/interactions/text-entry/InlineTextEntry.svelte +0 -75
  177. package/src/interactions/text-entry/extractor.ts +0 -79
  178. package/src/interactions/text-entry/index.ts +0 -2
  179. package/src/interactions/text-entry/types.ts +0 -1
  180. package/src/interactions/upload/extractor.ts +0 -81
  181. package/src/interactions/upload/index.ts +0 -2
  182. package/src/interactions/upload/types.ts +0 -1
  183. package/src/pci/PciHost.ts +0 -138
  184. package/src/pci/types.ts +0 -70
  185. package/src/pnp/applyPnp.ts +0 -29
  186. package/src/pnp/parsePnpXml.ts +0 -215
  187. package/src/pnp/types.ts +0 -75
  188. package/src/server.ts +0 -14
  189. package/src/types/index.ts +0 -388
  190. package/src/types/interactions.ts +0 -8
  191. package/src/types/responseValidation.ts +0 -29
  192. package/src/types/xmldom.d.ts +0 -12
  193. package/src/utils/PerformanceMonitor.ts +0 -335
  194. package/src/utils/drawingUtils.ts +0 -73
  195. package/src/utils/responseUtils.ts +0 -51
  196. package/src/utils/touchDragHelper.ts +0 -1
  197. package/src/web-components/QTIInteractionBase.ts +0 -303
  198. package/src/web-components/QTIInteractionElement.ts +0 -125
  199. package/src/web-components/index.ts +0 -22
@@ -1,1618 +0,0 @@
1
- import {
2
- type AreaMapEntry,
3
- type AreaMapping,
4
- type BaseType,
5
- buildOutcomeProcessingAst,
6
- buildResponseProcessingAst,
7
- buildTemplateProcessingAst,
8
- type Cardinality,
9
- childElements,
10
- coerceBaseValue,
11
- DeclarationContext,
12
- type DeclarationMap,
13
- evalExpr,
14
- execProgram,
15
- findDescendants,
16
- findFirstDescendant,
17
- getAttr,
18
- OperatorRegistry,
19
- type ProcessingProgram,
20
- type QtiValue,
21
- qtiNull,
22
- qtiValue,
23
- toBoolean,
24
- toNumber,
25
- toStringValue,
26
- } from '@pie-qti/qti-processing';
27
- import type { ElementNameMapper, AttributeNameMapper } from '@pie-qti/qti-common';
28
- import type { ResolvedItemDeliveryContext } from '@pie-qti/ims-cp-core';
29
- import {
30
- Qti2xElementNameMapper,
31
- Qti2xAttributeNameMapper,
32
- Qti3ElementNameMapper,
33
- Qti3AttributeNameMapper,
34
- detectQtiVersion,
35
- } from '@pie-qti/qti-common';
36
- import type { AssessmentItemDocument } from '../document/AssessmentItemDocument.js';
37
- import { parseAssessmentItemDocument } from '../document/AssessmentItemDocument.js';
38
- import type { ExtractionRegistry } from '../extraction/ExtractionRegistry.js';
39
- import { createExtractionRegistry } from '../extraction/ExtractionRegistry.js';
40
- import { extractInteractionData } from '../extraction/interactionExtractionPipeline.js';
41
- import { getStandardInteractionExtractors } from '../interactions/modules.js';
42
- import type {
43
- AdaptiveAttemptResult,
44
- CompletionStatus,
45
- HtmlContent,
46
- ItemLifecycleStatus,
47
- ItemSessionActionResult,
48
- ItemSessionState,
49
- ModalFeedback,
50
- PlayerConfig,
51
- PlayerSecurityConfig,
52
- QTIRole,
53
- RubricBlock,
54
- ScoringResult,
55
- SerializedItemSessionState,
56
- SerializedItemSessionVariable,
57
- } from '../types/index.js';
58
- import type { InteractionData } from '../types/interactions.js';
59
- import type { ResponseValidationResult } from '../types/responseValidation.js';
60
- import type { ComponentRegistry } from './ComponentRegistry.js';
61
- import { createComponentRegistry } from './ComponentRegistry.js';
62
- import { createSeededRng } from './random.js';
63
- import { sanitizeHtml } from './sanitizer.js';
64
- import { toTrustedHtml } from './trustedTypes.js';
65
- import { sanitizeResourceUrl } from './urlPolicy.js';
66
- import type { PnpProfile } from '../pnp/types.js';
67
- import { applyPnpToRoot } from '../pnp/applyPnp.js';
68
- import type { CatalogIndex } from '../catalog/types.js';
69
- import { extractCatalog, extractCatalogFromItemXml, mergeCatalogs } from '../catalog/catalogExtractor.js';
70
- import { getCatalogEntry } from '../catalog/catalogLookup.js';
71
- import { PciHost } from '../pci/PciHost.js';
72
- import type { ExtractedPci } from '../pci/types.js';
73
-
74
- type DeclKind = 'response' | 'outcome' | 'template';
75
-
76
- export class Player {
77
- private role: QTIRole;
78
- private config: PlayerConfig;
79
- private itemXml: string;
80
- private itemDocument: AssessmentItemDocument;
81
- private assessmentItem: Element;
82
- private decls: DeclarationMap;
83
- private ctx: DeclarationContext;
84
- private rng: () => number;
85
- private ops: OperatorRegistry;
86
- private extractionRegistry: ExtractionRegistry;
87
- private componentRegistry: ComponentRegistry;
88
- private i18nProvider: any; // I18nProvider from @pie-qti/i18n
89
- private mapper: ElementNameMapper;
90
-
91
- private responseProcessingProgram: ProcessingProgram | null = null;
92
- private templateProcessingProgram: ProcessingProgram | null = null;
93
- private outcomeProcessingProgram: ProcessingProgram | null = null;
94
- private _pnp: PnpProfile | undefined;
95
- private _rootEl: HTMLElement | undefined;
96
- private _catalogIndex: CatalogIndex = new Map();
97
- private _stimulusCatalogIndexes: Map<string, CatalogIndex> = new Map();
98
- private _pciHosts: Map<string, PciHost> = new Map();
99
- private _pnpChangeListeners = new Set<(pnp: PnpProfile | undefined) => void>();
100
- private sessionGuid: string;
101
- private lifecycleStatus: ItemLifecycleStatus = 'initial';
102
- private sessionStartedAt: number;
103
- private accumulatedDurationMs = 0;
104
-
105
- constructor(config: PlayerConfig) {
106
- this.config = config;
107
- this.itemXml = config.itemXml ?? '';
108
- this.role = config.role ?? 'candidate';
109
- this.sessionGuid = createSessionGuid();
110
- this.sessionStartedAt = Date.now();
111
- this.rng = config.rng ?? (typeof config.seed === 'number' ? createSeededRng(config.seed) : Math.random);
112
-
113
- // Auto-detect QTI version and create appropriate mappers if not provided
114
- if (!config.elementNameMapper) {
115
- const version = detectQtiVersion(this.itemXml);
116
- if (version === '3.0') {
117
- this.mapper = new Qti3ElementNameMapper();
118
- // Set in config so it's available to extraction utils
119
- (config as any).elementNameMapper = this.mapper;
120
- // Also set attribute mapper if not provided
121
- if (!config.attributeNameMapper) {
122
- (config as any).attributeNameMapper = new Qti3AttributeNameMapper();
123
- }
124
- } else {
125
- this.mapper = new Qti2xElementNameMapper();
126
- (config as any).elementNameMapper = this.mapper;
127
- if (!config.attributeNameMapper) {
128
- (config as any).attributeNameMapper = new Qti2xAttributeNameMapper();
129
- }
130
- }
131
- } else {
132
- this.mapper = config.elementNameMapper as ElementNameMapper;
133
- if (!config.attributeNameMapper) {
134
- (config as any).attributeNameMapper =
135
- this.mapper.version === '3.0'
136
- ? new Qti3AttributeNameMapper()
137
- : new Qti2xAttributeNameMapper();
138
- }
139
- }
140
-
141
- this.itemDocument = parseAssessmentItemDocument({
142
- itemXml: this.itemXml,
143
- elementNameMapper: this.mapper,
144
- attributeNameMapper: config.attributeNameMapper as AttributeNameMapper,
145
- security: this.config.security,
146
- });
147
- this.assessmentItem = this.itemDocument.getAssessmentItem();
148
-
149
- this.decls = this.buildDeclarations();
150
- this.ensureBuiltinDeclarations(this.decls);
151
- this.ctx = new DeclarationContext(this.decls);
152
- this.ops = new OperatorRegistry();
153
-
154
- // Restore session state (outcomes + responses) before running templateProcessing.
155
- if (config.sessionState) {
156
- this.applySessionState(config.sessionState);
157
- }
158
-
159
- // Extraction + rendering registries (for interaction rendering)
160
- // Pass the element name mapper to the extraction registry for QTI version handling
161
- this.extractionRegistry = (config.extractionRegistry as ExtractionRegistry | undefined) ?? createExtractionRegistry(this.mapper);
162
- this.componentRegistry = (config.componentRegistry as ComponentRegistry | undefined) ?? createComponentRegistry();
163
-
164
- // I18n provider (defaults to a simple fallback if not provided)
165
- this.i18nProvider = config.i18nProvider ?? this.createDefaultI18nProvider();
166
-
167
- // Register standard interaction extractors (idempotent per-registry instance)
168
- for (const ex of getStandardInteractionExtractors()) {
169
- try {
170
- this.extractionRegistry.register(ex as any);
171
- } catch {
172
- // ignore duplicates if a caller pre-registered
173
- }
174
- }
175
-
176
- // Plugins can further extend registries
177
- for (const p of (config.plugins ?? []) as any[]) {
178
- try {
179
- p?.registerExtractors?.(this.extractionRegistry);
180
- p?.registerComponents?.(this.componentRegistry);
181
- } catch {
182
- // plugin errors shouldn't prevent core parsing
183
- }
184
- }
185
-
186
- // Build ASTs once.
187
- const templateProcessing = this.itemDocument.getProcessingElement('template');
188
- if (templateProcessing) {
189
- this.templateProcessingProgram = buildTemplateProcessingAst(templateProcessing, {
190
- elementNameMapper: this.mapper,
191
- });
192
- this.execTemplateProcessing();
193
- }
194
-
195
- const responseProcessing = this.itemDocument.getProcessingElement('response');
196
- if (responseProcessing) {
197
- this.responseProcessingProgram = buildResponseProcessingAst(responseProcessing, {
198
- elementNameMapper: this.mapper,
199
- });
200
- }
201
-
202
- const outcomeProcessing = this.itemDocument.getProcessingElement('outcome');
203
- if (outcomeProcessing) {
204
- this.outcomeProcessingProgram = buildOutcomeProcessingAst(outcomeProcessing, {
205
- elementNameMapper: this.mapper,
206
- });
207
- }
208
-
209
- // Apply initial responses after templateProcessing (so template vars are ready).
210
- if (config.responses) {
211
- this.setResponses(config.responses as Record<string, unknown>);
212
- }
213
-
214
- // Detect and log QTI version for compatibility awareness
215
- const detectedVersion = this.detectQTIVersion();
216
- if (detectedVersion === 'unknown') {
217
- console.warn('[QTI Player] Could not detect QTI version. Assuming QTI 2.2 compatibility.');
218
- } else if (detectedVersion === '2.0') {
219
- console.warn(
220
- '[QTI Player] QTI 2.0 detected. Some features may not be fully supported. QTI 2.2 is recommended.'
221
- );
222
- } else if (detectedVersion === '2.1') {
223
- console.info(
224
- '[QTI Player] QTI 2.1 detected. Using QTI 2.2 compatibility mode with CC2 template support.'
225
- );
226
- }
227
-
228
- // Store PNP profile for later use (applyPnpToRoot is called once a root element is available).
229
- this._pnp = config.pnp;
230
-
231
- // Build catalog index from resolved delivery context, legacy shared catalog XML, and item XML.
232
- // Item/global entries are merged first; item-level entries win on global collisions.
233
- // Stimulus entries are kept separately so rendered stimulus terms can avoid ID collisions.
234
- let mergedCatalog: CatalogIndex = new Map();
235
- for (const source of config.deliveryContext?.catalogSources ?? []) {
236
- const sourceCatalog = extractCatalog(source.xml);
237
- if (source.scope === 'stimulus' && source.stimulusIdentifier) {
238
- const existing = this._stimulusCatalogIndexes.get(source.stimulusIdentifier) ?? new Map();
239
- this._stimulusCatalogIndexes.set(source.stimulusIdentifier, mergeCatalogs(existing, sourceCatalog));
240
- } else {
241
- mergedCatalog = mergeCatalogs(mergedCatalog, sourceCatalog);
242
- }
243
- }
244
- if (config.catalogXml) {
245
- mergedCatalog = mergeCatalogs(mergedCatalog, extractCatalogFromItemXml(config.catalogXml));
246
- }
247
- this._catalogIndex = mergeCatalogs(mergedCatalog, extractCatalogFromItemXml(this.itemXml));
248
-
249
- // Check strict compliance if enabled
250
- if (this.config.strictQtiCompliance?.enabled) {
251
- this.validateStrictCompliance();
252
- }
253
- }
254
-
255
- /**
256
- * Apply the PNP profile to a player root element.
257
- * Call this once the root DOM element is available (e.g. after mounting).
258
- * The player stores the element reference so updatePnp() can re-apply without re-parsing the item.
259
- */
260
- public applyPnp(rootEl: HTMLElement): void {
261
- this._rootEl = rootEl;
262
- applyPnpToRoot(rootEl, this._pnp);
263
- }
264
-
265
- /**
266
- * Update the PNP profile mid-session without re-parsing the item XML.
267
- * Deep-merges the partial profile into the current profile and re-applies.
268
- */
269
- public updatePnp(partial: Partial<PnpProfile>): void {
270
- this._pnp = mergePnp(this._pnp, partial);
271
- if (this._rootEl) {
272
- applyPnpToRoot(this._rootEl, this._pnp);
273
- }
274
- for (const listener of this._pnpChangeListeners) {
275
- listener(this._pnp);
276
- }
277
- }
278
-
279
- /** Return the current resolved PNP profile. */
280
- public getPnp(): PnpProfile | undefined {
281
- return this._pnp;
282
- }
283
-
284
- public onPnpChange(listener: (pnp: PnpProfile | undefined) => void): () => void {
285
- this._pnpChangeListeners.add(listener);
286
- return () => this._pnpChangeListeners.delete(listener);
287
- }
288
-
289
- /** Return the package/assessment-resolved delivery context, if one was supplied. */
290
- public getDeliveryContext(): ResolvedItemDeliveryContext | undefined {
291
- return this.config.deliveryContext;
292
- }
293
-
294
- /**
295
- * Look up a catalog entry by card identifier, usage type, and optional language.
296
- * Returns the HTML string for the matched entry, or null if not found.
297
- *
298
- * Language fallback: exact match → prefix match → no-lang entry → null.
299
- */
300
- public getCatalogEntry(
301
- idref: string,
302
- usage: string,
303
- lang?: string,
304
- options?: { stimulusIdentifier?: string }
305
- ): string | null {
306
- const stimulusHtml = options?.stimulusIdentifier
307
- ? getCatalogEntry(this._stimulusCatalogIndexes.get(options.stimulusIdentifier) ?? new Map(), idref, usage, lang)
308
- : null;
309
- const html = stimulusHtml ?? getCatalogEntry(this._catalogIndex, idref, usage, lang);
310
- if (html === null) return null;
311
- if (looksLikeCatalogUrl(html)) {
312
- return sanitizeResourceUrl(html.trim(), this.config.security?.urlPolicy, 'img');
313
- }
314
- return this.sanitizeHtmlContent(html);
315
- }
316
-
317
- /** Sanitize externally resolved item-adjacent HTML before it reaches a rendering sink. */
318
- public sanitizeHtmlContent(html: string): string {
319
- return sanitizeHtml(html, { security: this.config.security });
320
- }
321
-
322
- /**
323
- * Create a PciHost for an extracted PCI and register it for response tracking.
324
- * The caller is responsible for calling host.load() and
325
- * host.initialize(domNode) once the DOM element is available.
326
- */
327
- public createPciHost(data: ExtractedPci): PciHost {
328
- const baseUrl = this.config.pciBaseUrl ?? (typeof document !== 'undefined' ? document.baseURI : '');
329
- const host = new PciHost(data, baseUrl);
330
-
331
- // Wire response changes back into the player's declaration context
332
- host.onResponseChange((responseId: string, value: unknown) => {
333
- const d = this.decls[responseId];
334
- if (d) {
335
- d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, value);
336
- }
337
- });
338
-
339
- this._pciHosts.set(data.responseIdentifier, host);
340
- return host;
341
- }
342
-
343
- /**
344
- * Push a response value into the PCI identified by responseIdentifier.
345
- * Called from setResponses() so session restore reaches PCI modules.
346
- */
347
- public setPciResponse(responseIdentifier: string, value: unknown): void {
348
- this._pciHosts.get(responseIdentifier)?.setResponse(value);
349
- }
350
-
351
- /**
352
- * Disable/enable all PCI hosts based on role.
353
- * 'candidate' = enabled; any other role = disabled.
354
- */
355
- public syncPciDisabledState(): void {
356
- const disabled = this.role !== 'candidate';
357
- for (const host of this._pciHosts.values()) {
358
- if (disabled) host.disable(); else host.enable();
359
- }
360
- }
361
-
362
- /**
363
- * Destroy all PCI hosts. Call on player teardown.
364
- */
365
- public destroyPciHosts(): void {
366
- for (const host of this._pciHosts.values()) {
367
- host.destroy();
368
- }
369
- this._pciHosts.clear();
370
- }
371
-
372
- /** Breaking-change API: returns the typed declaration map */
373
- public getDeclarations(): DeclarationMap {
374
- return this.decls;
375
- }
376
-
377
- public setResponses(responses: Record<string, unknown>): void {
378
- for (const [id, raw] of Object.entries(responses)) {
379
- const d = this.decls[id];
380
- if (!d) continue;
381
- d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw);
382
- // Push restored responses into any mounted PCI modules
383
- this.setPciResponse(id, raw);
384
- }
385
- }
386
-
387
- /**
388
- * Destroy all resources owned by this player instance (PCI modules, etc.).
389
- * Call when unmounting to prevent memory leaks.
390
- */
391
- public destroy(): void {
392
- this.destroyPciHosts();
393
- }
394
-
395
- public processResponses(): ScoringResult {
396
- return this.runResponseProcessing({ finalizeNonAdaptiveAttempt: true });
397
- }
398
-
399
- public saveItemSession(): SerializedItemSessionState {
400
- this.freezeDuration();
401
- return this.serializeItemSession();
402
- }
403
-
404
- public restoreItemSession(state: SerializedItemSessionState): void {
405
- this.sessionGuid = state.sessionGuid;
406
- this.lifecycleStatus = state.lifecycleStatus;
407
- this.accumulatedDurationMs = Math.max(0, Number(state.duration) || 0);
408
- this.sessionStartedAt = Date.now();
409
- this.applySerializedVariables(state.responseVariables);
410
- this.applySerializedVariables(state.outcomeVariables);
411
- this.applySerializedVariables(state.templateVariables);
412
- this.applySerializedVariables(state.contextVariables);
413
- this.updateDuration();
414
- }
415
-
416
- public suspendAttempt(): ItemSessionActionResult {
417
- const validation = this.validateResponses(this.getResponses());
418
- this.lifecycleStatus = 'suspended';
419
- const sessionState = this.saveItemSession();
420
-
421
- return {
422
- action: 'suspendAttempt',
423
- lifecycleStatus: this.lifecycleStatus,
424
- completionStatus: this.getCompletionStatus(),
425
- numAttempts: this.getNumAttempts(),
426
- duration: sessionState.duration,
427
- completed: this.isCompleted(),
428
- sessionState,
429
- validation,
430
- };
431
- }
432
-
433
- public endAttempt(options: { countAttempt?: boolean; validateResponses?: boolean } = {}): ItemSessionActionResult {
434
- const validate = options.validateResponses ?? false;
435
- const validation = validate ? this.validateResponses(this.getResponses()) : undefined;
436
- if (validation && !validation.valid) {
437
- const sessionState = this.saveItemSession();
438
- return {
439
- action: 'endAttempt',
440
- lifecycleStatus: this.lifecycleStatus,
441
- completionStatus: this.getCompletionStatus(),
442
- numAttempts: this.getNumAttempts(),
443
- duration: sessionState.duration,
444
- completed: this.isCompleted(),
445
- sessionState,
446
- validation,
447
- };
448
- }
449
-
450
- const scoring = this.isAdaptive()
451
- ? this.submitAttempt(options.countAttempt ?? true)
452
- : this.runResponseProcessing({
453
- finalizeNonAdaptiveAttempt: true,
454
- countAttempt: options.countAttempt ?? true,
455
- });
456
- this.lifecycleStatus = scoring.completed ? 'closed' : 'interacting';
457
- const sessionState = this.saveItemSession();
458
-
459
- return {
460
- action: 'endAttempt',
461
- lifecycleStatus: this.lifecycleStatus,
462
- completionStatus: this.getCompletionStatus(),
463
- numAttempts: this.getNumAttempts(),
464
- duration: sessionState.duration,
465
- completed: scoring.completed,
466
- sessionState,
467
- validation,
468
- scoring,
469
- };
470
- }
471
-
472
- public scoreAttempt(): ItemSessionActionResult {
473
- const scoring = this.runResponseProcessing({ finalizeNonAdaptiveAttempt: false });
474
- const sessionState = this.saveItemSession();
475
-
476
- return {
477
- action: 'scoreAttempt',
478
- lifecycleStatus: this.lifecycleStatus,
479
- completionStatus: this.getCompletionStatus(),
480
- numAttempts: this.getNumAttempts(),
481
- duration: sessionState.duration,
482
- completed: scoring.completed,
483
- sessionState,
484
- scoring,
485
- };
486
- }
487
-
488
- public newTemplate(options: { resetResponses?: boolean } = {}): ItemSessionActionResult {
489
- this.resetOutcomesToDefault();
490
- if (options.resetResponses ?? true) {
491
- this.resetResponsesToDefault();
492
- }
493
- this.resetTemplatesToDefault();
494
- this.ctx.setValue('completionStatus', qtiValue('identifier', 'single', 'not_attempted'));
495
- this.ctx.setValue('numAttempts', qtiValue('integer', 'single', 0));
496
- this.execTemplateProcessing();
497
- this.lifecycleStatus = 'initial';
498
- this.accumulatedDurationMs = 0;
499
- this.sessionStartedAt = Date.now();
500
- this.updateDuration();
501
- const sessionState = this.serializeItemSession();
502
-
503
- return {
504
- action: 'newTemplate',
505
- lifecycleStatus: this.lifecycleStatus,
506
- completionStatus: this.getCompletionStatus(),
507
- numAttempts: this.getNumAttempts(),
508
- duration: sessionState.duration,
509
- completed: this.isCompleted(),
510
- sessionState,
511
- };
512
- }
513
-
514
- public getSecurityConfig(): PlayerSecurityConfig | undefined {
515
- return this.config.security;
516
- }
517
-
518
- public getTrustedTypesPolicyName(): string | undefined {
519
- return this.config.security?.trustedTypesPolicyName;
520
- }
521
-
522
- /**
523
- * Get the i18n provider instance
524
- * @returns I18nProvider instance
525
- */
526
- public getI18nProvider(): any {
527
- return this.i18nProvider;
528
- }
529
-
530
- /**
531
- * Get attribute value with QTI version support.
532
- * Tries the attribute mapper's native form first, then falls back to direct lookup.
533
- * @param el - Element to get attribute from
534
- * @param canonicalName - Canonical (lowercase) attribute name
535
- * @returns Attribute value or null
536
- */
537
- private getAttrMapped(el: Element, canonicalName: string): string | null {
538
- // Try mapped attribute name first (e.g., 'mapkey' -> 'map-key' for QTI 3.0)
539
- if (this.config.attributeNameMapper) {
540
- const nativeName = this.config.attributeNameMapper.toNative(canonicalName);
541
- const value = el.getAttribute(nativeName);
542
- if (value !== null) return value;
543
- }
544
- // Fallback to canonical name (for QTI 2.x compatibility)
545
- return getAttr(el, canonicalName);
546
- }
547
-
548
- /**
549
- * Create a simple fallback i18n provider when none is provided
550
- * This avoids a hard dependency on @pie-qti/i18n
551
- */
552
- private createDefaultI18nProvider(): any {
553
- return {
554
- getLocale: () => 'en-US',
555
- setLocale: () => {},
556
- t: (key: string) => key, // Fallback to key
557
- plural: (key: string) => key,
558
- formatNumber: (value: number) => value.toString(),
559
- formatDate: (date: Date) => date.toISOString(),
560
- };
561
- }
562
-
563
- /**
564
- * Detects the QTI version from the assessmentItem element.
565
- * Checks both namespace URI and version attribute.
566
- *
567
- * @returns QTI version string ('2.0', '2.1', '2.2') or 'unknown'
568
- */
569
- private detectQTIVersion(): string {
570
- const ns = (this.assessmentItem as any).namespaceURI;
571
- if (ns?.includes('v3p0') || ns?.includes('imsqtiasi_v3p0')) return '3.0';
572
- if (ns?.includes('v2p2') || ns?.includes('imsqti_v2p2')) return '2.2';
573
- if (ns?.includes('v2p1') || ns?.includes('imsqti_v2p1')) return '2.1';
574
- if (ns?.includes('v2p0') || ns?.includes('imsqti_v2p0')) return '2.0';
575
-
576
- // Check element name for QTI 3.0
577
- const localName = (this.assessmentItem as any).localName || (this.assessmentItem as any).tagName;
578
- if (localName === 'qti-assessment-item' || localName === 'qti-assessment-test') {
579
- return '3.0';
580
- }
581
-
582
- const versionAttr = getAttr(this.assessmentItem, 'version');
583
- if (versionAttr?.startsWith('3.')) return '3.0';
584
- if (versionAttr === '2.0') return '2.0';
585
- if (versionAttr === '2.1') return '2.1';
586
- if (versionAttr === '2.2') return '2.2';
587
-
588
- return 'unknown';
589
- }
590
-
591
- /**
592
- * Validates strict QTI 2.2 compliance if enabled in configuration.
593
- * Logs warnings or throws errors based on config settings.
594
- */
595
- private validateStrictCompliance(): void {
596
- const config = this.config.strictQtiCompliance;
597
- if (!config?.enabled) return;
598
-
599
- const version = this.detectQTIVersion();
600
- if (version !== '2.2') {
601
- const message = `[QTI Player] Strict compliance enabled but item version is ${version}, not 2.2`;
602
- if (config.rejectUnknownExtensions) {
603
- throw new Error(message);
604
- } else if (config.logDeviations !== false) {
605
- console.warn(message);
606
- }
607
- }
608
-
609
- // Future: Add validation for non-standard elements/attributes
610
- }
611
-
612
- private resetOutcomesToDefault(): void {
613
- for (const d of Object.values(this.decls)) {
614
- if ((d as any).__kind !== 'outcome') continue;
615
- // Built-in stateful variables must survive across processing runs.
616
- // They are updated by the runtime (adaptive attempt tracking), not by outcome defaults.
617
- if (d.identifier === 'numAttempts' || d.identifier === 'completionStatus' || d.identifier === 'duration') continue;
618
- this.ctx.resetToDefault(d.identifier);
619
- }
620
- }
621
-
622
- private resetResponsesToDefault(): void {
623
- for (const d of Object.values(this.decls)) {
624
- if ((d as any).__kind !== 'response') continue;
625
- this.ctx.resetToDefault(d.identifier);
626
- this.setPciResponse(d.identifier, d.value.kind === 'value' ? d.value.value : null);
627
- }
628
- }
629
-
630
- private resetTemplatesToDefault(): void {
631
- for (const d of Object.values(this.decls)) {
632
- if (!d.isTemplate) continue;
633
- this.ctx.resetToDefault(d.identifier);
634
- }
635
- }
636
-
637
- private runResponseProcessing(options: {
638
- finalizeNonAdaptiveAttempt: boolean;
639
- countAttempt?: boolean;
640
- }): ScoringResult {
641
- this.updateDuration();
642
- // Spec-aligned behavior: each processing run starts from outcome defaults.
643
- // This prevents stale outcomes when response/outcome processing doesn't set every variable.
644
- this.resetOutcomesToDefault();
645
-
646
- // Execute response processing if present
647
- const rpEl = this.itemDocument.getProcessingElement('response');
648
- if (rpEl) {
649
- // If responseProcessing has explicit statements, run the compiled program.
650
- // Otherwise, fall back to template-based processing (responseProcessing@template).
651
- const hasStatements = childElements(rpEl).length > 0;
652
- if (hasStatements) {
653
- this.execResponseProcessingProgram();
654
- } else {
655
- const templateUrl = getAttr(rpEl, 'template');
656
- if (templateUrl) this.execResponseProcessingTemplate(templateUrl);
657
- }
658
- }
659
-
660
- // Execute outcome processing if present (runs after responseProcessing)
661
- this.execOutcomeProcessingProgram();
662
-
663
- // Compatibility: processResponses() has historically finalized non-adaptive items.
664
- // New scoreAttempt() uses this same engine with finalization disabled.
665
- if (!this.isAdaptive() && options.finalizeNonAdaptiveAttempt) {
666
- this.ctx.setValue('completionStatus', qtiValue('identifier', 'single', 'completed'));
667
- if (options.countAttempt ?? true) {
668
- const currentAttempts = this.getNumAttempts();
669
- this.ctx.setValue('numAttempts', qtiValue('integer', 'single', currentAttempts + 1));
670
- }
671
- }
672
-
673
- const outcomes = this.collectOutcomes();
674
-
675
- const score = Number(outcomes.SCORE ?? 0);
676
- const maxScore = Number(outcomes.MAXSCORE ?? 1);
677
- const completionStatus = (outcomes.completionStatus as CompletionStatus | undefined) ?? 'not_attempted';
678
- const completed = completionStatus === 'completed' || (!this.isAdaptive() && options.finalizeNonAdaptiveAttempt);
679
-
680
- return {
681
- score,
682
- maxScore,
683
- completed,
684
- outcomeValues: outcomes,
685
- modalFeedback: this.getModalFeedback(outcomes),
686
- };
687
- }
688
-
689
- public getItemBodyHtml(): HtmlContent {
690
- const inner = this.itemDocument.serializeItemBodyChildren();
691
- if (!inner) return '';
692
-
693
- const printed = this.renderPrintedVariables(inner);
694
- const sanitized = sanitizeHtml(printed, { security: this.config.security });
695
- return toTrustedHtml(sanitized, this.config.security?.trustedTypesPolicyName);
696
- }
697
-
698
- /**
699
- * Extract rubric blocks for the current role.
700
- *
701
- * QTI uses `<rubricBlock view="...">` to provide role-specific guidance.
702
- * We return sanitized HTML for direct rendering.
703
- */
704
- public getRubrics(): RubricBlock[] {
705
- const role = this.role;
706
- const rubricEls = this.itemDocument.findRubricElements();
707
- if (rubricEls.length === 0) return [];
708
-
709
- const blocks: RubricBlock[] = [];
710
- for (const el of rubricEls) {
711
- const viewRaw = (getAttr(el, 'view') || '').trim();
712
- const view = viewRaw ? viewRaw.split(/\s+/).filter(Boolean) : [];
713
-
714
- // If view is specified, show only when it includes the current role.
715
- if (view.length > 0 && role && !view.includes(role)) continue;
716
-
717
- const contentRaw = this.itemDocument.serializeChildren(el) || (el.textContent || '');
718
- const printed = this.renderPrintedVariables(contentRaw);
719
- const sanitized = sanitizeHtml(printed, { security: this.config.security });
720
- const html = toTrustedHtml(sanitized, this.config.security?.trustedTypesPolicyName);
721
-
722
- blocks.push({ view, html });
723
- }
724
-
725
- return blocks;
726
- }
727
-
728
- public getComponentRegistry(): ComponentRegistry {
729
- return this.componentRegistry;
730
- }
731
-
732
- public getExtractionRegistry(): ExtractionRegistry {
733
- return this.extractionRegistry;
734
- }
735
-
736
- /**
737
- * Canonical interaction API (new): extracted, typed interaction data.
738
- */
739
- public getInteractionData(): InteractionData[] {
740
- return extractInteractionData({
741
- document: this.itemDocument,
742
- extractionRegistry: this.extractionRegistry,
743
- declarations: this.decls,
744
- config: this.config,
745
- });
746
- }
747
-
748
- /**
749
- * Convenience API (used by tests/bench): returns a minimal interaction list with QTI-ish field names.
750
- */
751
- public getInteractions(): Array<{ type: string; responseIdentifier: string } & Record<string, any>> {
752
- return this.getInteractionData().map((i: any) => ({
753
- ...i,
754
- responseIdentifier: i.responseId,
755
- }));
756
- }
757
-
758
- public getResponseInteractions(): Array<{ type: string; responseIdentifier: string } & Record<string, any>> {
759
- return this.getInteractions().filter((i) => i.type !== 'endAttemptInteraction');
760
- }
761
-
762
- /**
763
- * Returns response identifiers of endAttempt interactions with countAttempt="false".
764
- * Used to detect hint-only submissions (e.g. Request Hint button).
765
- */
766
- public getHintEndAttemptIdentifiers(): string[] {
767
- return this.getInteractions()
768
- .filter((i: any) => i.type === 'endAttemptInteraction' && i.countAttempt === false)
769
- .map((i: any) => i.responseIdentifier);
770
- }
771
-
772
- public getResponseIdentifiers(): string[] {
773
- return this.getResponseInteractions().map((i) => i.responseIdentifier);
774
- }
775
-
776
- public isAdaptive(): boolean {
777
- return (this.itemDocument.getAssessmentItemAttribute('adaptive') || '').toLowerCase() === 'true';
778
- }
779
-
780
- public getNumAttempts(): number {
781
- return Math.max(0, Math.floor(toNumber(this.ctx.getValue('numAttempts')) || 0));
782
- }
783
-
784
- public getCompletionStatus(): CompletionStatus {
785
- const s = (toStringValue(this.ctx.getValue('completionStatus')) || '').trim() as CompletionStatus;
786
- return (s || 'not_attempted') as CompletionStatus;
787
- }
788
-
789
- public isCompleted(): boolean {
790
- return this.getCompletionStatus() === 'completed';
791
- }
792
-
793
- public submitAttempt(countAttempt: boolean = true): AdaptiveAttemptResult {
794
- if (this.isCompleted()) {
795
- throw new Error('Cannot submit: item is already completed');
796
- }
797
-
798
- // QTI adaptive semantics: numAttempts should reflect the attempt being processed.
799
- if (this.isAdaptive() && countAttempt) {
800
- const next = this.getNumAttempts() + 1;
801
- this.ctx.setValue('numAttempts', qtiValue('integer', 'single', next));
802
- // Promote completionStatus from not_attempted -> unknown on first submission unless RP sets it.
803
- if (this.getCompletionStatus() === 'not_attempted') {
804
- this.ctx.setValue('completionStatus', qtiValue('identifier', 'single', 'unknown'));
805
- }
806
- }
807
-
808
- const base = this.processResponses();
809
- const completionStatus = this.getCompletionStatus();
810
- const completed = completionStatus === 'completed';
811
- const canContinue = this.isAdaptive() ? !completed : false;
812
-
813
- return {
814
- ...base,
815
- completed,
816
- numAttempts: this.getNumAttempts(),
817
- completionStatus,
818
- canContinue,
819
- };
820
- }
821
-
822
- public getResponses(): Record<string, any> {
823
- const out: Record<string, any> = {};
824
- for (const d of Object.values(this.decls)) {
825
- if ((d as any).__kind !== 'response') continue;
826
- out[d.identifier] = d.value.kind === 'value' ? d.value.value : null;
827
- }
828
- return out;
829
- }
830
-
831
- /**
832
- * Get correct response for a specific response identifier
833
- * @param responseId - The response identifier
834
- * @returns The correct response value, or undefined if not available
835
- */
836
- public getCorrectResponse(responseId: string): any | undefined {
837
- const decl = this.decls[responseId];
838
- if (!decl || (decl as any).__kind !== 'response') return undefined;
839
- const respDecl = decl as any; // ResponseDeclaration from qti-processing
840
- if (!respDecl.correctResponse) return undefined;
841
- if (respDecl.correctResponse.kind !== 'value') return undefined;
842
- return respDecl.correctResponse.value;
843
- }
844
-
845
- /**
846
- * Get all correct responses as a map
847
- * @returns Map of responseId to correct response value
848
- */
849
- public getCorrectResponses(): Record<string, any> {
850
- const out: Record<string, any> = {};
851
- for (const d of Object.values(this.decls)) {
852
- if ((d as any).__kind !== 'response') continue;
853
- const respDecl = d as any;
854
- if (!respDecl.correctResponse || respDecl.correctResponse.kind !== 'value') continue;
855
- out[d.identifier] = respDecl.correctResponse.value;
856
- }
857
- return out;
858
- }
859
-
860
- public getTemplateVariables(): Record<string, any> {
861
- const out: Record<string, any> = {};
862
- for (const d of Object.values(this.decls)) {
863
- if (!d.isTemplate) continue;
864
- out[d.identifier] = d.value.kind === 'value' ? d.value.value : null;
865
- }
866
- return out;
867
- }
868
-
869
- public setTemplateVariables(vars: Record<string, any>): void {
870
- for (const [id, raw] of Object.entries(vars)) {
871
- const d = this.decls[id];
872
- if (!d?.isTemplate) continue;
873
- d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw);
874
- }
875
- }
876
-
877
- public getSessionState(): ItemSessionState {
878
- const out: ItemSessionState = {};
879
- for (const d of Object.values(this.decls)) {
880
- out[d.identifier] = d.value.kind === 'value' ? d.value.value : null;
881
- }
882
- return out;
883
- }
884
-
885
- public validateResponses(responses: Record<string, any>): ResponseValidationResult {
886
- const interactions = this.getInteractions();
887
- const entries: ResponseValidationResult['entries'] = {};
888
- const issues: ResponseValidationResult['issues'] = [];
889
-
890
- for (const i of interactions) {
891
- const responseId = i.responseIdentifier;
892
- const decl = this.decls[responseId];
893
- const value = responses[responseId];
894
-
895
- const required =
896
- i.type !== 'endAttemptInteraction' &&
897
- (i.type !== 'mediaInteraction' || (typeof i.minPlays === 'number' && i.minPlays > 0));
898
-
899
- let complete = !required;
900
- if (i.type === 'mediaInteraction' && required) {
901
- const minPlays = Number(i.minPlays || 0);
902
- complete = Number(value || 0) >= minPlays;
903
- } else if (required) {
904
- if (Array.isArray(value)) {
905
- complete = value.length > 0;
906
- // Enforce minChoices / minAssociations where applicable
907
- const minChoices = Number(i.minChoices || i.minAssociations || 0);
908
- if (complete && minChoices > 0) {
909
- complete = value.length >= minChoices;
910
- }
911
- // Enforce matchMin per-choice: each pairing entry "id1 id2" in value must
912
- // appear at least matchMin times for the relevant choice.
913
- // Collect all choice arrays that can carry matchMin across all pairing interaction types.
914
- const choices: Array<{ identifier: string; matchMin?: number }> = [
915
- ...(i.choices ?? []),
916
- ...(i.gapTexts ?? []),
917
- ...(i.gapImages ?? []),
918
- ...(i.sourceSet ?? []),
919
- ...(i.targetSet ?? []),
920
- ...(i.associableHotspots ?? []),
921
- ];
922
- for (const choice of choices) {
923
- const min = Number(choice.matchMin || 0);
924
- if (min > 0) {
925
- const count = (value as string[]).filter((p) => {
926
- const parts = p.split(' ');
927
- return parts[0] === choice.identifier || parts[1] === choice.identifier;
928
- }).length;
929
- if (count < min) {
930
- complete = false;
931
- break;
932
- }
933
- }
934
- }
935
- } else {
936
- complete = value !== null && value !== undefined && value !== '';
937
- }
938
- }
939
-
940
- const errors: string[] = [];
941
- const warnings: string[] = [];
942
-
943
- if (decl) {
944
- if (decl.cardinality === 'multiple' || decl.cardinality === 'ordered') {
945
- if (!(value === null || value === undefined || Array.isArray(value))) {
946
- errors.push(`Expected an array for ${decl.cardinality} response '${responseId}'`);
947
- }
948
- } else {
949
- if (Array.isArray(value)) {
950
- errors.push(`Expected a single value for response '${responseId}'`);
951
- }
952
- }
953
- }
954
-
955
- const valid = errors.length === 0;
956
- entries[responseId] = {
957
- responseId,
958
- interactionType: i.type,
959
- required,
960
- complete,
961
- valid,
962
- errors,
963
- warnings,
964
- };
965
-
966
- for (const e of errors) {
967
- issues.push({
968
- responseId,
969
- code: 'invalid_shape',
970
- message: e,
971
- severity: 'error',
972
- });
973
- }
974
- }
975
-
976
- const allValid = Object.values(entries).every((e) => e.valid);
977
- return { valid: allValid, entries, issues };
978
- }
979
-
980
- public getProgress(responses: Record<string, any>): { total: number; answered: number; unanswered: number } {
981
- const v = this.validateResponses(responses);
982
- const required = Object.values(v.entries).filter((e) => e.required);
983
- const answered = required.filter((e) => e.complete).length;
984
- const total = required.length;
985
- return { total, answered, unanswered: Math.max(0, total - answered) };
986
- }
987
-
988
- public canSubmitResponses(responses: Record<string, any>): boolean {
989
- const v = this.validateResponses(responses);
990
- const required = Object.values(v.entries).filter((e) => e.required);
991
- return v.valid && required.every((e) => e.complete);
992
- }
993
-
994
- /**
995
- * True if the learner has made any meaningful interaction, even if submission is not yet allowed.
996
- * Used by assessment/session controllers to track "answered" state.
997
- */
998
- public isAttempted(responses: Record<string, any>): boolean {
999
- for (const i of this.getResponseInteractions()) {
1000
- const id = i.responseIdentifier;
1001
- const v = responses[id];
1002
- if (i.type === 'mediaInteraction') {
1003
- if (Number(v || 0) > 0) return true;
1004
- continue;
1005
- }
1006
- if (Array.isArray(v)) {
1007
- if (v.length > 0) return true;
1008
- continue;
1009
- }
1010
- if (v !== null && v !== undefined && v !== '') return true;
1011
- }
1012
- return false;
1013
- }
1014
-
1015
- // ----------------------------------------------------------------------------
1016
- // Execution
1017
- // ----------------------------------------------------------------------------
1018
-
1019
- private execTemplateProcessing(): void {
1020
- if (!this.templateProcessingProgram) return;
1021
- execProgram(
1022
- {
1023
- ctx: this.ctx,
1024
- ops: this.ops,
1025
- rng: this.rng,
1026
- customOperators: this.config.customOperators,
1027
- },
1028
- this.templateProcessingProgram
1029
- );
1030
- }
1031
-
1032
- private execResponseProcessingProgram(): void {
1033
- if (!this.responseProcessingProgram) return;
1034
- execProgram(
1035
- {
1036
- ctx: this.ctx,
1037
- ops: this.ops,
1038
- rng: this.rng,
1039
- customOperators: this.config.customOperators,
1040
- },
1041
- this.responseProcessingProgram
1042
- );
1043
- }
1044
-
1045
- private execOutcomeProcessingProgram(): void {
1046
- if (!this.outcomeProcessingProgram) return;
1047
- execProgram(
1048
- {
1049
- ctx: this.ctx,
1050
- ops: this.ops,
1051
- rng: this.rng,
1052
- customOperators: this.config.customOperators,
1053
- },
1054
- this.outcomeProcessingProgram
1055
- );
1056
- }
1057
-
1058
- private execResponseProcessingTemplate(templateUrl: string): void {
1059
- const name = templateUrl.split('/').pop()?.toLowerCase().replace(/\.xml$/, '');
1060
- if (!name) {
1061
- console.warn(`[QTI Player] Could not extract template name from URL: ${templateUrl}`);
1062
- return;
1063
- }
1064
-
1065
- const responseDeclIds = Object.values(this.decls)
1066
- .filter((d) => (d as any).__kind === 'response')
1067
- .map((d) => d.identifier);
1068
-
1069
- switch (name) {
1070
- case 'match_correct':
1071
- case 'cc2_match': { // CC2_match is an alias for match_correct (QTI 2.1 compatibility)
1072
- const allCorrect = responseDeclIds.every((id) => {
1073
- const expr = { kind: 'expr.match', id: 'tmp', a: { kind: 'expr.variable', id: 'tmp', identifier: id }, b: { kind: 'expr.correct', id: 'tmp', identifier: id } } as any;
1074
- // Use evaluator match semantics by evaluating a constructed MatchExpr
1075
- return toBoolean(
1076
- evalExpr(
1077
- { ctx: this.ctx, ops: this.ops, rng: this.rng, customOperators: this.config.customOperators },
1078
- expr
1079
- )
1080
- );
1081
- });
1082
-
1083
- const max = toNumber(this.ctx.getValue('MAXSCORE'));
1084
- this.ctx.setValue('SCORE', qtiValue('float', 'single', allCorrect ? (Number.isFinite(max) ? max : 1) : 0));
1085
- return;
1086
- }
1087
- case 'match_nothing':
1088
- case 'cc2_match_nothing': { // QTI 2.1 compatibility
1089
- const isEmptyResponse = (v: QtiValue | undefined): boolean => {
1090
- if (!v) return true;
1091
- if (v.kind === 'null') return true;
1092
- if (v.kind === 'invalid') return false;
1093
- if (v.value === null || v.value === undefined) return true;
1094
- if (Array.isArray(v.value)) return v.value.length === 0;
1095
- if (typeof v.value === 'string') return v.value.trim().length === 0;
1096
- return false;
1097
- };
1098
-
1099
- const allEmpty = responseDeclIds.every((id) => isEmptyResponse(this.ctx.getValue(id)));
1100
- const max = toNumber(this.ctx.getValue('MAXSCORE'));
1101
- this.ctx.setValue('SCORE', qtiValue('float', 'single', allEmpty ? (Number.isFinite(max) ? max : 1) : 0));
1102
- return;
1103
- }
1104
- case 'map_response':
1105
- case 'cc2_map_response': { // QTI 2.1 compatibility
1106
- let total = 0;
1107
- for (const id of responseDeclIds) {
1108
- const d = this.decls[id];
1109
- if (!d.mapping) continue;
1110
- const v = evalExpr(
1111
- { ctx: this.ctx, ops: this.ops, rng: this.rng },
1112
- { kind: 'expr.mapResponse', id: 'tmp', identifier: id } as any
1113
- );
1114
- total += toNumber(v) || 0;
1115
- }
1116
- this.ctx.setValue('SCORE', qtiValue('float', 'single', total));
1117
- return;
1118
- }
1119
- case 'map_response_point':
1120
- case 'cc2_map_response_point': { // QTI 2.1 compatibility
1121
- let total = 0;
1122
- for (const id of responseDeclIds) {
1123
- const d = this.decls[id];
1124
- if (!d.areaMapping) continue;
1125
- const v = evalExpr(
1126
- { ctx: this.ctx, ops: this.ops, rng: this.rng },
1127
- { kind: 'expr.mapResponsePoint', id: 'tmp', identifier: id } as any
1128
- );
1129
- total += toNumber(v) || 0;
1130
- }
1131
- this.ctx.setValue('SCORE', qtiValue('float', 'single', total));
1132
- return;
1133
- }
1134
- default:
1135
- console.warn(`[QTI Player] Unsupported response processing template: ${name}`);
1136
- return;
1137
- }
1138
- }
1139
-
1140
- // ----------------------------------------------------------------------------
1141
- // Declarations
1142
- // ----------------------------------------------------------------------------
1143
-
1144
- private buildDeclarations(): DeclarationMap {
1145
- const decls: DeclarationMap = {};
1146
-
1147
- const addDecl = (kind: DeclKind, el: Element) => {
1148
- const identifier = this.getAttrMapped(el, 'identifier');
1149
- const cardinality = (this.getAttrMapped(el, 'cardinality') || 'single') as Cardinality;
1150
- const baseType = (this.getAttrMapped(el, 'baseType') || 'string') as BaseType;
1151
- if (!identifier) return;
1152
-
1153
- const defaultValue = this.parseDefaultValue(el, baseType, cardinality);
1154
- decls[identifier] = {
1155
- identifier,
1156
- baseType,
1157
- cardinality,
1158
- defaultValue,
1159
- value: defaultValue,
1160
- isTemplate: kind === 'template',
1161
- // @ts-expect-error internal marker for templates
1162
- __kind: kind,
1163
- };
1164
-
1165
- // Response + outcome declarations may define mappings used by mapResponse/mapOutcome.
1166
- // (Templates do not participate in mapping.)
1167
- if (kind === 'response' || kind === 'outcome') {
1168
- const mappingEl = findFirstDescendant(el, this.mapper.toNative('mapping'));
1169
- if (mappingEl) {
1170
- decls[identifier].mapping = this.parseMapping(mappingEl, baseType);
1171
- }
1172
- }
1173
-
1174
- // Outcome declarations may define a lookup table (matchTable or interpolationTable)
1175
- // used by the lookupOutcomeValue rule.
1176
- if (kind === 'outcome') {
1177
- const matchTableEl = findFirstDescendant(el, this.mapper.toNative('matchtable'));
1178
- const interpolationTableEl = findFirstDescendant(el, this.mapper.toNative('interpolationtable'));
1179
- if (matchTableEl) {
1180
- decls[identifier].lookupTable = this.parseMatchTable(matchTableEl);
1181
- } else if (interpolationTableEl) {
1182
- decls[identifier].lookupTable = this.parseInterpolationTable(interpolationTableEl);
1183
- }
1184
- }
1185
-
1186
- if (kind === 'response') {
1187
- const correctEl = findFirstDescendant(el, this.mapper.toNative('correctresponse'));
1188
- if (correctEl) {
1189
- decls[identifier].correctResponse = this.parseCorrectResponse(correctEl, baseType, cardinality);
1190
- }
1191
- const areaMappingEl = findFirstDescendant(el, this.mapper.toNative('areamapping'));
1192
- if (areaMappingEl) {
1193
- decls[identifier].areaMapping = this.parseAreaMapping(areaMappingEl);
1194
- }
1195
- }
1196
- };
1197
-
1198
- for (const el of this.itemDocument.findDeclarationElements('response')) addDecl('response', el);
1199
- for (const el of this.itemDocument.findDeclarationElements('outcome')) addDecl('outcome', el);
1200
- for (const el of this.itemDocument.findDeclarationElements('template')) addDecl('template', el);
1201
-
1202
- return decls;
1203
- }
1204
-
1205
- private parseMatchTable(el: Element) {
1206
- const defaultValueRaw = (getAttr(el, 'defaultValue') || '').trim();
1207
- const defaultValue = defaultValueRaw ? Number(defaultValueRaw) : undefined;
1208
- return {
1209
- kind: 'table.matchTable' as const,
1210
- defaultValue: Number.isFinite(defaultValue as any) ? defaultValue : undefined,
1211
- entries: findDescendants(el, this.mapper.toNative('matchtableentry')).map((e) => ({
1212
- sourceValue: (getAttr(e, 'sourceValue') || '').trim(),
1213
- targetValue: (getAttr(e, 'targetValue') || '').trim(),
1214
- })),
1215
- };
1216
- }
1217
-
1218
- private parseInterpolationTable(el: Element) {
1219
- const defaultValueRaw = (getAttr(el, 'defaultValue') || '').trim();
1220
- const defaultValue = defaultValueRaw ? Number(defaultValueRaw) : undefined;
1221
- const interpolationMethod = (getAttr(el, 'interpolationMethod') || 'linear').trim();
1222
- return {
1223
- kind: 'table.interpolationTable' as const,
1224
- defaultValue: Number.isFinite(defaultValue as any) ? defaultValue : undefined,
1225
- interpolationMethod,
1226
- entries: findDescendants(el, this.mapper.toNative('interpolationtableentry'))
1227
- .map((e) => ({
1228
- sourceValue: Number((getAttr(e, 'sourceValue') || '').trim()),
1229
- targetValue: Number((getAttr(e, 'targetValue') || '').trim()),
1230
- }))
1231
- .filter((e) => Number.isFinite(e.sourceValue) && Number.isFinite(e.targetValue)),
1232
- };
1233
- }
1234
-
1235
- private ensureBuiltinDeclarations(decls: DeclarationMap): void {
1236
- // completionStatus + numAttempts are defined in QTI (esp. adaptive items) and commonly used
1237
- // without explicit outcomeDeclaration in authoring content.
1238
- if (!decls.completionStatus) {
1239
- decls.completionStatus = {
1240
- identifier: 'completionStatus',
1241
- baseType: 'identifier',
1242
- cardinality: 'single',
1243
- value: qtiValue('identifier', 'single', 'not_attempted'),
1244
- isTemplate: false,
1245
- // @ts-expect-error internal marker
1246
- __kind: 'outcome',
1247
- };
1248
- }
1249
-
1250
- if (!decls.numAttempts) {
1251
- decls.numAttempts = {
1252
- identifier: 'numAttempts',
1253
- baseType: 'integer',
1254
- cardinality: 'single',
1255
- defaultValue: qtiValue('integer', 'single', 0),
1256
- value: qtiValue('integer', 'single', 0),
1257
- isTemplate: false,
1258
- // @ts-expect-error internal marker
1259
- __kind: 'outcome',
1260
- };
1261
- }
1262
-
1263
- if (!decls.duration) {
1264
- decls.duration = {
1265
- identifier: 'duration',
1266
- baseType: 'duration',
1267
- cardinality: 'single',
1268
- defaultValue: qtiValue('duration', 'single', 0),
1269
- value: qtiValue('duration', 'single', 0),
1270
- isTemplate: false,
1271
- // @ts-expect-error internal marker
1272
- __kind: 'outcome',
1273
- };
1274
- }
1275
-
1276
- // Common scoring defaults
1277
- if (!decls.SCORE) {
1278
- decls.SCORE = {
1279
- identifier: 'SCORE',
1280
- baseType: 'float',
1281
- cardinality: 'single',
1282
- value: qtiValue('float', 'single', 0),
1283
- isTemplate: false,
1284
- // @ts-expect-error internal marker
1285
- __kind: 'outcome',
1286
- };
1287
- }
1288
- if (!decls.MAXSCORE) {
1289
- decls.MAXSCORE = {
1290
- identifier: 'MAXSCORE',
1291
- baseType: 'float',
1292
- cardinality: 'single',
1293
- value: qtiValue('float', 'single', 1),
1294
- isTemplate: false,
1295
- // @ts-expect-error internal marker
1296
- __kind: 'outcome',
1297
- };
1298
- }
1299
- }
1300
-
1301
- private applySessionState(state: ItemSessionState): void {
1302
- for (const [id, raw] of Object.entries(state)) {
1303
- const d = this.decls[id];
1304
- if (!d) continue;
1305
- d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw);
1306
- }
1307
- const restoredDuration = Number(state.duration);
1308
- if (Number.isFinite(restoredDuration) && restoredDuration >= 0) {
1309
- this.accumulatedDurationMs = restoredDuration;
1310
- this.sessionStartedAt = Date.now();
1311
- this.updateDuration();
1312
- }
1313
- }
1314
-
1315
- private applySerializedVariables(vars: Record<string, SerializedItemSessionVariable>): void {
1316
- for (const v of Object.values(vars)) {
1317
- const d = this.decls[v.identifier];
1318
- if (!d) continue;
1319
- d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, v.value);
1320
- if ((d as any).__kind === 'response') {
1321
- this.setPciResponse(d.identifier, v.value);
1322
- }
1323
- }
1324
- }
1325
-
1326
- private serializeItemSession(): SerializedItemSessionState {
1327
- const responseVariables: Record<string, SerializedItemSessionVariable> = {};
1328
- const outcomeVariables: Record<string, SerializedItemSessionVariable> = {};
1329
- const templateVariables: Record<string, SerializedItemSessionVariable> = {};
1330
- const contextVariables: Record<string, SerializedItemSessionVariable> = {};
1331
- const contextIds = new Set(['completionStatus', 'numAttempts', 'duration']);
1332
-
1333
- for (const d of Object.values(this.decls)) {
1334
- const variable = this.serializeVariable(d);
1335
- if (d.isTemplate) {
1336
- templateVariables[d.identifier] = { ...variable, kind: 'template' };
1337
- } else if (contextIds.has(d.identifier)) {
1338
- contextVariables[d.identifier] = { ...variable, kind: 'context' };
1339
- } else if ((d as any).__kind === 'response') {
1340
- responseVariables[d.identifier] = { ...variable, kind: 'response' };
1341
- } else if ((d as any).__kind === 'outcome') {
1342
- outcomeVariables[d.identifier] = { ...variable, kind: 'outcome' };
1343
- }
1344
- }
1345
-
1346
- const validation = this.validateResponses(this.getResponses());
1347
- return {
1348
- itemIdentifier: this.itemDocument.getAssessmentItemAttribute('identifier') ?? undefined,
1349
- sessionGuid: this.sessionGuid,
1350
- lifecycleStatus: this.lifecycleStatus,
1351
- completionStatus: this.getCompletionStatus(),
1352
- numAttempts: this.getNumAttempts(),
1353
- duration: this.getDuration(),
1354
- responseVariables,
1355
- outcomeVariables,
1356
- templateVariables,
1357
- contextVariables,
1358
- validationMessages: validation.issues,
1359
- savedAt: new Date().toISOString(),
1360
- };
1361
- }
1362
-
1363
- private serializeVariable(d: DeclarationMap[string]): SerializedItemSessionVariable {
1364
- return {
1365
- identifier: d.identifier,
1366
- kind: ((d as any).__kind ?? (d.isTemplate ? 'template' : 'context')) as SerializedItemSessionVariable['kind'],
1367
- baseType: d.baseType,
1368
- cardinality: d.cardinality,
1369
- value: this.qtiValueToSerializable(d.value),
1370
- defaultValue: this.qtiValueToSerializable(d.defaultValue),
1371
- };
1372
- }
1373
-
1374
- private qtiValueToSerializable(value: QtiValue | undefined): any {
1375
- if (!value || value.kind !== 'value') return null;
1376
- return value.value;
1377
- }
1378
-
1379
- private updateDuration(): void {
1380
- const elapsedMs = Math.max(0, Date.now() - this.sessionStartedAt);
1381
- const durationMs = this.accumulatedDurationMs + elapsedMs;
1382
- this.ctx.setValue('duration', qtiValue('duration', 'single', durationMs));
1383
- }
1384
-
1385
- private freezeDuration(): number {
1386
- this.updateDuration();
1387
- const duration = this.getDuration();
1388
- this.accumulatedDurationMs = duration;
1389
- this.sessionStartedAt = Date.now();
1390
- return duration;
1391
- }
1392
-
1393
- private getDuration(): number {
1394
- const value = this.ctx.getValue('duration');
1395
- return Math.max(0, Math.floor(toNumber(value) || 0));
1396
- }
1397
-
1398
- private parseDefaultValue(declEl: Element, baseType: BaseType, cardinality: Cardinality): QtiValue {
1399
- const defaultEl = findFirstDescendant(declEl, this.mapper.toNative('defaultvalue'));
1400
- if (!defaultEl) return qtiNull(baseType, cardinality);
1401
- const values = findDescendants(defaultEl, this.mapper.toNative('value')).map((v) => (v.textContent || '').trim());
1402
- if (cardinality === 'multiple' || cardinality === 'ordered') {
1403
- return qtiValue(
1404
- baseType,
1405
- cardinality,
1406
- values.map((t) => {
1407
- const v = coerceBaseValue(baseType, t);
1408
- return v.kind === 'value' ? v.value : null;
1409
- })
1410
- );
1411
- }
1412
- return coerceBaseValue(baseType, values[0] ?? '');
1413
- }
1414
-
1415
- private parseCorrectResponse(correctEl: Element, baseType: BaseType, cardinality: Cardinality): QtiValue {
1416
- const values = findDescendants(correctEl, this.mapper.toNative('value')).map((v) => (v.textContent || '').trim());
1417
- if (cardinality === 'multiple' || cardinality === 'ordered') {
1418
- return qtiValue(
1419
- baseType,
1420
- cardinality,
1421
- values.map((t) => {
1422
- const v = coerceBaseValue(baseType, t);
1423
- return v.kind === 'value' ? v.value : null;
1424
- })
1425
- );
1426
- }
1427
- return coerceBaseValue(baseType, values[0] ?? '');
1428
- }
1429
-
1430
- private parseMapping(mappingEl: Element, baseType: BaseType) {
1431
- const defaultValue = Number(this.getAttrMapped(mappingEl, 'defaultValue') || 0);
1432
- const lowerBound = this.getAttrMapped(mappingEl, 'lowerBound') ? Number(this.getAttrMapped(mappingEl, 'lowerBound')) : undefined;
1433
- const upperBound = this.getAttrMapped(mappingEl, 'upperBound') ? Number(this.getAttrMapped(mappingEl, 'upperBound')) : undefined;
1434
- const mappingCaseSensitive = this.getAttrMapped(mappingEl, 'caseSensitive') || 'true';
1435
- const entries: Record<string, any> = {};
1436
-
1437
- const normalizePairKey = (k: string): string => {
1438
- const parts = k.trim().split(/\s+/).filter(Boolean);
1439
- if (parts.length === 2) return [...parts].sort().join(' ');
1440
- return k.trim();
1441
- };
1442
-
1443
- const normalizeDirectedPairKey = (k: string): string => {
1444
- const parts = k.trim().split(/\s+/).filter(Boolean);
1445
- if (parts.length >= 2) return `${parts[0]} ${parts[1]}`;
1446
- return k.trim();
1447
- };
1448
-
1449
- for (const e of findDescendants(mappingEl, this.mapper.toNative('mapentry'))) {
1450
- const mapKey = this.getAttrMapped(e, 'mapKey');
1451
- const mappedValue = this.getAttrMapped(e, 'mappedValue');
1452
- if (!mapKey || mappedValue === null) continue;
1453
- const effectiveCaseSensitive = this.getAttrMapped(e, 'caseSensitive') || mappingCaseSensitive || 'true';
1454
- const storedKey =
1455
- baseType === 'pair'
1456
- ? normalizePairKey(mapKey)
1457
- : baseType === 'directedPair'
1458
- ? normalizeDirectedPairKey(mapKey)
1459
- : mapKey;
1460
- entries[storedKey] = { mapKey: storedKey, mappedValue: Number(mappedValue), caseSensitive: effectiveCaseSensitive };
1461
- if (effectiveCaseSensitive !== 'true') {
1462
- const lowerKey = storedKey.toLowerCase();
1463
- entries[lowerKey] = {
1464
- mapKey: lowerKey,
1465
- mappedValue: Number(mappedValue),
1466
- caseSensitive: effectiveCaseSensitive,
1467
- };
1468
- }
1469
- }
1470
-
1471
- return { defaultValue, lowerBound, upperBound, caseSensitive: mappingCaseSensitive, entries };
1472
- }
1473
-
1474
- private parseAreaMapping(areaMappingEl: Element): AreaMapping {
1475
- const defaultValue = Number(getAttr(areaMappingEl, 'defaultValue') || 0);
1476
- const lowerBound = getAttr(areaMappingEl, 'lowerBound')
1477
- ? Number(getAttr(areaMappingEl, 'lowerBound'))
1478
- : undefined;
1479
- const upperBound = getAttr(areaMappingEl, 'upperBound')
1480
- ? Number(getAttr(areaMappingEl, 'upperBound'))
1481
- : undefined;
1482
-
1483
- const entries: AreaMapEntry[] = [];
1484
- for (const e of findDescendants(areaMappingEl, this.mapper.toNative('areamapentry'))) {
1485
- const shape = (getAttr(e, 'shape') || 'default') as AreaMapEntry['shape'];
1486
- const coords = String(getAttr(e, 'coords') || '');
1487
- const mappedValue = Number(getAttr(e, 'mappedValue') || 0);
1488
- entries.push({ shape, coords, mappedValue });
1489
- }
1490
-
1491
- return { defaultValue, lowerBound, upperBound, entries };
1492
- }
1493
-
1494
- private coerceToDeclarationValue(baseType: BaseType, cardinality: Cardinality, raw: unknown): QtiValue {
1495
- if (raw === null || raw === undefined) return qtiNull(baseType, cardinality);
1496
-
1497
- // Allow callers to pass fully-formed QtiValue (e.g. session restore).
1498
- if (typeof raw === 'object' && raw && 'kind' in raw) {
1499
- return raw as QtiValue;
1500
- }
1501
-
1502
- // For file types, preserve QTIFileResponse objects directly
1503
- if (baseType === 'file') {
1504
- if (cardinality === 'multiple' || cardinality === 'ordered') {
1505
- const arr = Array.isArray(raw) ? raw : [raw];
1506
- // For file types, preserve objects (QTIFileResponse) directly
1507
- return qtiValue(baseType, cardinality, arr.filter((v) => v !== null && v !== undefined));
1508
- }
1509
- // For single file, preserve the object directly
1510
- return qtiValue(baseType, cardinality, raw);
1511
- }
1512
-
1513
- if (cardinality === 'multiple' || cardinality === 'ordered') {
1514
- const arr = Array.isArray(raw) ? raw : [raw];
1515
- const coerced = arr
1516
- .map((v) => String(v ?? '').trim())
1517
- .filter((s) => s.length > 0)
1518
- .map((t) => {
1519
- const v = coerceBaseValue(baseType, t);
1520
- return v.kind === 'value' ? v.value : null;
1521
- })
1522
- .filter((v) => v !== null);
1523
- // Multiple/ordered can legitimately be an empty container (distinct from null).
1524
- return qtiValue(baseType, cardinality, coerced);
1525
- }
1526
-
1527
- const t = String(raw ?? '').trim();
1528
- if (t.length === 0) return qtiNull(baseType, cardinality);
1529
- return coerceBaseValue(baseType, t);
1530
- }
1531
-
1532
- private collectOutcomes(): Record<string, unknown> {
1533
- const out: Record<string, unknown> = {};
1534
- for (const d of Object.values(this.decls)) {
1535
- if ((d as any).__kind !== 'outcome') continue;
1536
- if (d.value.kind === 'value') out[d.identifier] = d.value.value;
1537
- else if (d.value.kind === 'null') out[d.identifier] = null;
1538
- }
1539
- // Ensure MAXSCORE always has a value (fallback to 1.0 if null or missing)
1540
- if (out.MAXSCORE === null || out.MAXSCORE === undefined) {
1541
- out.MAXSCORE = 1.0;
1542
- }
1543
- return out;
1544
- }
1545
-
1546
- // ----------------------------------------------------------------------------
1547
- // printedVariable + feedback
1548
- // ----------------------------------------------------------------------------
1549
-
1550
- private renderPrintedVariables(html: string): string {
1551
- const readIdentifier = (attrs: string): string | null => {
1552
- const m = attrs.match(/identifier\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))/i);
1553
- return (m?.[1] || m?.[2] || m?.[3] || '').trim() || null;
1554
- };
1555
-
1556
- const renderId = (id: string | null): string => {
1557
- if (!id) return '';
1558
- const v = this.ctx.getValue(id);
1559
- if (v.kind !== 'value') return '';
1560
- if (Array.isArray(v.value)) return v.value.map(String).join(', ');
1561
- return String(v.value);
1562
- };
1563
-
1564
- let out = html.replace(/<printedVariable\b([^>]*)>([\s\S]*?)<\/printedVariable>/gi, (_m, attrs) =>
1565
- renderId(readIdentifier(String(attrs)))
1566
- );
1567
- out = out.replace(/<printedVariable\b([^>]*)\/>/gi, (_m, attrs) => renderId(readIdentifier(String(attrs))));
1568
- return out;
1569
- }
1570
-
1571
- private getModalFeedback(outcomes: Record<string, any>): ModalFeedback[] {
1572
- const feedbackEls = this.itemDocument.findModalFeedbackElements();
1573
- const active: ModalFeedback[] = [];
1574
-
1575
- for (const el of feedbackEls) {
1576
- const identifier = this.getAttrMapped(el, 'identifier') || '';
1577
- const outcomeIdentifier = this.getAttrMapped(el, 'outcomeIdentifier') || '';
1578
- const showHide = (this.getAttrMapped(el, 'showHide') || 'show') as 'show' | 'hide';
1579
- const title = this.getAttrMapped(el, 'title') || undefined;
1580
-
1581
- const contentRaw = this.itemDocument.serializeChildren(el) || (el.textContent || '');
1582
- const sanitized = sanitizeHtml(contentRaw, { security: this.config.security });
1583
- const content = toTrustedHtml(sanitized, this.config.security?.trustedTypesPolicyName);
1584
-
1585
- const outcomeValue = outcomes[outcomeIdentifier];
1586
- const shouldShow = showHide === 'show' ? outcomeValue === identifier : outcomeValue !== identifier;
1587
- if (shouldShow && content) {
1588
- active.push({ identifier, outcomeIdentifier, showHide, content, title });
1589
- }
1590
- }
1591
- return active;
1592
- }
1593
- }
1594
-
1595
- // ---------------------------------------------------------------------------
1596
- // Module-level helpers
1597
- // ---------------------------------------------------------------------------
1598
-
1599
- function mergePnp(base: PnpProfile | undefined, partial: Partial<PnpProfile>): PnpProfile {
1600
- return {
1601
- display: { ...(base?.display ?? {}), ...(partial.display ?? {}) },
1602
- content: { ...(base?.content ?? {}), ...(partial.content ?? {}) },
1603
- cognitive: { ...(base?.cognitive ?? {}), ...(partial.cognitive ?? {}) },
1604
- };
1605
- }
1606
-
1607
- function createSessionGuid(): string {
1608
- if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
1609
- return crypto.randomUUID();
1610
- }
1611
- return `item-session-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
1612
- }
1613
-
1614
- function looksLikeCatalogUrl(value: string): boolean {
1615
- const trimmed = value.trim();
1616
- return /^(https?:\/\/|\/\/|\/|\.{0,2}\/|data:|blob:)/i.test(trimmed) ||
1617
- /\.(png|jpe?g|gif|webp|svg|mp3|wav|ogg|mp4|webm|pdf)(\?.*)?$/i.test(trimmed);
1618
- }