@pie-qti/assessment-player 0.1.28 → 1.0.0-beta.1

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 (34) hide show
  1. package/README.md +13 -0
  2. package/dist/core/AssessmentPlayer.d.ts +54 -14
  3. package/dist/core/AssessmentPlayer.js +204 -166
  4. package/dist/core/AssessmentPlayer.js.map +1 -1
  5. package/dist/core/AssessmentSessionCoordinator.d.ts +10 -2
  6. package/dist/core/AssessmentSessionCoordinator.js +24 -3
  7. package/dist/core/AssessmentSessionCoordinator.js.map +1 -1
  8. package/dist/core/ItemSessionController.d.ts +14 -3
  9. package/dist/core/ItemSessionController.js +31 -12
  10. package/dist/core/ItemSessionController.js.map +1 -1
  11. package/dist/core/TimeManager.d.ts +20 -7
  12. package/dist/core/TimeManager.js +20 -18
  13. package/dist/core/TimeManager.js.map +1 -1
  14. package/dist/core/testStructure.d.ts +65 -0
  15. package/dist/core/testStructure.js +336 -0
  16. package/dist/core/testStructure.js.map +1 -0
  17. package/dist/index.d.ts +2 -1
  18. package/dist/index.js +2 -0
  19. package/dist/index.js.map +1 -1
  20. package/dist/integration/ReferenceBackendAdapter.d.ts +53 -5
  21. package/dist/integration/ReferenceBackendAdapter.js +317 -230
  22. package/dist/integration/ReferenceBackendAdapter.js.map +1 -1
  23. package/dist/integration/api-contract.d.ts +92 -49
  24. package/dist/integration/api-contract.js.map +1 -1
  25. package/dist/integration/assessment-item-scorer.d.ts +11 -1
  26. package/dist/integration/assessment-item-scorer.js +102 -12
  27. package/dist/integration/assessment-item-scorer.js.map +1 -1
  28. package/dist/integration/index.d.ts +1 -1
  29. package/dist/integration/index.js.map +1 -1
  30. package/dist/integration/toSectionComposition.js +1 -0
  31. package/dist/integration/toSectionComposition.js.map +1 -1
  32. package/dist/types/index.d.ts +10 -0
  33. package/dist/types/index.js.map +1 -1
  34. package/package.json +10 -10
@@ -26,9 +26,10 @@
26
26
  * - Validates all requests with authentication
27
27
  * - Filters sensitive data based on role
28
28
  */
29
- import { buildExpression, buildOutcomeProcessingAst, DeclarationContext, evalExpr, execProgram, OperatorRegistry, parseXml, serializeXml, qtiNull, qtiValue, } from '@pie-qti/qti-processing';
30
- import { createResolvedItemDeliveryContext, extractAssessmentStimulusRefs, extractQtiStylesheets, parseAssessmentStimulusXml, resolveCheckedPackagePath, resolveCheckedPackagePathFromFile, } from '@pie-qti/ims-cp-core';
31
- import { scoreAssessmentItem } from './assessment-item-scorer.js';
29
+ import { buildOutcomeProcessingAst, DeclarationContext, execProgram, OperatorRegistry, parseXml, serializeXml, qtiValue, } from '@pie-qti/qti-processing';
30
+ import { createResolvedItemDeliveryContext, extractAssessmentStimulusRefs, extractProcessingIncludeRefs, extractQtiStylesheets, parseAssessmentStimulusXml, resolveCheckedPackagePath, resolveCheckedPackagePathFromFile, } from '@pie-qti/ims-cp-core';
31
+ import { addItemVariableDeclarations, applyVariableMappings, deliveredItems, drawAssessment, evaluateTestCondition, qtiElementNameMapper, resolveItemSessionControl, testOutcomeDeclarations, toCanonicalQtiName, } from '../core/testStructure.js';
32
+ import { defaultItemTestState, scoreAssessmentItemForTest } from './assessment-item-scorer.js';
32
33
  /**
33
34
  * Storage key prefix for localStorage
34
35
  */
@@ -39,31 +40,10 @@ const STORAGE_PREFIX = 'qti_session_';
39
40
  const BANK_CACHE_PREFIX = 'qti_bank_cache_';
40
41
  class AssessmentSectionReferenceLimitError extends Error {
41
42
  }
42
- function toCanonicalQtiName(name) {
43
- const withoutPrefix = (name ?? '').replace(/^qti-/, '');
44
- return withoutPrefix.replace(/-([a-z])/g, (_, char) => char.toUpperCase());
45
- }
46
- const qtiElementNameMapper = {
47
- version: 'qti2x-or-qti3',
48
- toCanonical: (elementName) => toCanonicalQtiName(elementName).toLowerCase(),
49
- toNative: (canonicalName) => canonicalName,
50
- isValidElementName: () => true,
51
- };
52
- /**
53
- * Reference Backend Adapter using localStorage
54
- *
55
- * @example
56
- * ```typescript
57
- * const adapter = new ReferenceBackendAdapter();
58
- * const response = await adapter.initSession({
59
- * assessmentId: 'test-001',
60
- * candidateId: 'student-123'
61
- * });
62
- * ```
63
- */
64
43
  export class ReferenceBackendAdapter {
65
- constructor() {
44
+ constructor(options = {}) {
66
45
  this.registeredAssessments = new Map();
46
+ this.rng = options.rng ?? Math.random;
67
47
  }
68
48
  /**
69
49
  * Register/override a client-provided assessment structure for a given assessmentId.
@@ -108,6 +88,7 @@ export class ReferenceBackendAdapter {
108
88
  sessionId: stored.sessionId,
109
89
  assessment: stored.assessment,
110
90
  restoredState: stored.state,
91
+ outcomes: this.currentOutcomes(stored),
111
92
  };
112
93
  }
113
94
  }
@@ -118,9 +99,10 @@ export class ReferenceBackendAdapter {
118
99
  // 2. Filter QTI XML based on role
119
100
  // 3. Remove responseProcessing for candidates
120
101
  //
121
- // For reference implementation, we'll use demo data
122
- const assessment = this.getAssessment(request.assessmentId);
123
- const firstItemIdentifier = this.getItemOrder(assessment)[0] ?? '';
102
+ // For reference implementation, we'll use demo data. Selection and ordering are drawn once
103
+ // here; the stored draw is what a resume returns.
104
+ const assessment = drawAssessment(this.getAssessment(request.assessmentId), this.rng);
105
+ const firstItemIdentifier = this.firstEligibleItem(assessment, deliveredItems(assessment), 0, undefined, testOutcomeDeclarations(assessment)) ?? '';
124
106
  const state = {
125
107
  currentItemIdentifier: firstItemIdentifier,
126
108
  visitedItems: [],
@@ -146,6 +128,7 @@ export class ReferenceBackendAdapter {
146
128
  return {
147
129
  sessionId,
148
130
  assessment,
131
+ currentItemIdentifier: firstItemIdentifier || undefined,
149
132
  };
150
133
  }
151
134
  /**
@@ -187,30 +170,58 @@ export class ReferenceBackendAdapter {
187
170
  error: 'Time limit expired',
188
171
  };
189
172
  }
190
- // Find the item XML
191
- const itemXml = this.findItemXml(session.assessment, request.itemIdentifier);
192
- if (!itemXml) {
173
+ const delivered = deliveredItems(session.assessment);
174
+ const index = delivered.findIndex((d) => d.item.identifier === request.itemIdentifier);
175
+ const current = delivered[index];
176
+ if (!current) {
193
177
  return {
194
178
  success: false,
195
179
  error: 'Item not found',
196
180
  };
197
181
  }
182
+ const itemXml = current.item.itemXml;
183
+ const control = resolveItemSessionControl(current.testPart, current.sections, current.item);
184
+ const previousItemSession = session.state.itemSessionStates?.[request.itemIdentifier];
185
+ if (control.maxAttempts > 0 && (previousItemSession?.attemptCount ?? 0) >= control.maxAttempts) {
186
+ return {
187
+ success: false,
188
+ error: 'Maximum attempts reached',
189
+ };
190
+ }
191
+ if (request.comment !== undefined && !control.allowComment) {
192
+ return {
193
+ success: false,
194
+ error: 'Comments are not allowed for this item',
195
+ };
196
+ }
198
197
  // **SECURITY WARNING**: Client-side scoring is INSECURE
199
198
  // In production, this MUST be done server-side
200
- const result = scoreAssessmentItem({ itemXml, responses: request.responses, itemSession: request.itemSession });
199
+ const { result, testState } = scoreAssessmentItemForTest({
200
+ itemXml,
201
+ responses: request.responses,
202
+ itemSession: request.itemSession,
203
+ });
201
204
  // Store responses and result
202
205
  session.state.itemResponses[request.itemIdentifier] = request.responses;
203
206
  if (!session.state.itemScores) {
204
207
  session.state.itemScores = {};
205
208
  }
206
209
  session.state.itemScores[request.itemIdentifier] = result;
210
+ if (testState) {
211
+ session.itemTestStates = { ...(session.itemTestStates ?? {}), [request.itemIdentifier]: testState };
212
+ }
213
+ else if (session.itemTestStates) {
214
+ delete session.itemTestStates[request.itemIdentifier];
215
+ }
207
216
  if (request.itemSession) {
208
217
  session.state.itemSessions = {
209
218
  ...(session.state.itemSessions ?? {}),
210
219
  [request.itemIdentifier]: request.itemSession,
211
220
  };
212
221
  }
213
- const previousItemSession = session.state.itemSessionStates?.[request.itemIdentifier];
222
+ if (request.comment !== undefined) {
223
+ session.state.itemComments = { ...(session.state.itemComments ?? {}), [request.itemIdentifier]: request.comment };
224
+ }
214
225
  session.state.itemSessionStates = {
215
226
  ...(session.state.itemSessionStates ?? {}),
216
227
  [request.itemIdentifier]: {
@@ -230,35 +241,19 @@ export class ReferenceBackendAdapter {
230
241
  session.state.visitedItems.push(request.itemIdentifier);
231
242
  }
232
243
  this.saveSession(session);
233
- const order = this.getItemOrder(session.assessment);
234
- const idx = order.indexOf(request.itemIdentifier);
235
- let nextItemIdentifier = idx >= 0 ? order[idx + 1] : undefined;
236
- // QTI branchRule evaluation (backend-authoritative).
237
- // Evaluate each rule in order; the first matching rule determines the next item.
238
- // Special targets EXIT_TEST / EXIT_TESTPART / EXIT_SECTION are returned as-is for
239
- // the client to interpret.
240
- const itemRef = this.findItemRef(session.assessment, request.itemIdentifier);
241
- if (itemRef?.branchRule && itemRef.branchRule.length > 0) {
242
- const outcomeVars = {
243
- ...result.outcomeValues,
244
- SCORE: result.score,
245
- };
246
- nextItemIdentifier = undefined; // reset — branch rules take full control
247
- for (const rule of itemRef.branchRule) {
248
- const matches = rule.conditionXml
249
- ? this.evaluateConditionXml(rule.conditionXml, outcomeVars)
250
- : true; // unconditional branch
251
- if (matches) {
252
- nextItemIdentifier = rule.target;
253
- break;
254
- }
255
- }
256
- }
244
+ const outcomes = this.currentOutcomes(session);
245
+ const currentVariables = testState?.variables ?? this.scoredItemVariables(result);
246
+ const decls = this.navigationDeclarations(session, outcomes, {
247
+ ...applyVariableMappings(currentVariables, current.item.variableMappings),
248
+ ...(currentVariables.SCORE ? {} : { SCORE: qtiValue('float', 'single', result.score) }),
249
+ });
250
+ const nextItemIdentifier = this.nextItemIdentifier(session.assessment, delivered, index, decls);
257
251
  return {
258
252
  success: true,
259
253
  result,
260
254
  nextItemIdentifier,
261
255
  updatedState: session.state,
256
+ outcomes,
262
257
  };
263
258
  }
264
259
  /**
@@ -302,64 +297,39 @@ export class ReferenceBackendAdapter {
302
297
  const fallbackTotal = Object.values(itemScores).reduce((sum, result) => sum + result.score, 0);
303
298
  const maxScore = Object.values(itemScores).reduce((sum, result) => sum + result.maxScore, 0);
304
299
  // Execute test-level outcome processing if available
305
- const outcomes = this.runOutcomeProcessing(session.assessment, itemScores);
306
- const totalScore = outcomes !== null ? (outcomes['SCORE_TOTAL'] ?? outcomes['SCORE'] ?? fallbackTotal) : fallbackTotal;
300
+ const outcomes = this.runOutcomeProcessing(session);
301
+ const scoreOutcome = outcomes?.SCORE_TOTAL ?? outcomes?.SCORE;
302
+ const totalScore = typeof scoreOutcome === 'number' ? scoreOutcome : fallbackTotal;
307
303
  return {
308
304
  success: true,
309
305
  totalScore,
310
306
  maxScore,
311
307
  itemScores,
308
+ outcomes: outcomes ?? undefined,
312
309
  finalizedAt: Date.now(),
313
310
  };
314
311
  }
312
+ /** Outcome values after the submissions so far; undefined before the first submission. */
313
+ currentOutcomes(session) {
314
+ if (Object.keys(session.state.itemScores ?? {}).length === 0)
315
+ return undefined;
316
+ return this.runOutcomeProcessing(session) ?? undefined;
317
+ }
315
318
  /**
316
319
  * Execute test-level outcome processing (T9/T1).
317
- * Returns a map of outcome variable values, or null if no outcomeProcessing is defined.
320
+ * Returns every declared outcome's value (null for NULL), or null if no outcomeProcessing is
321
+ * defined.
318
322
  */
319
- runOutcomeProcessing(assessment, itemScores) {
323
+ runOutcomeProcessing(session) {
324
+ const { assessment } = session;
320
325
  if (!assessment.outcomeProcessingXml) {
321
326
  return null;
322
327
  }
323
328
  try {
324
- // Build declaration map from outcomeDeclarations
325
- const decls = {};
326
- for (const d of assessment.outcomeDeclarations || []) {
327
- const baseType = d.baseType;
328
- const cardinality = d.cardinality;
329
- let defaultQtiValue;
330
- if (d.defaultValue !== undefined) {
331
- defaultQtiValue = qtiValue(baseType, cardinality, d.defaultValue);
332
- }
333
- else if (baseType === 'float' || baseType === 'integer') {
334
- defaultQtiValue = qtiValue(baseType, 'single', 0);
335
- }
336
- else {
337
- defaultQtiValue = qtiNull();
338
- }
339
- decls[d.identifier] = {
340
- identifier: d.identifier,
341
- baseType,
342
- cardinality,
343
- defaultValue: defaultQtiValue,
344
- value: { ...defaultQtiValue },
345
- };
346
- }
329
+ const testItems = this.buildTestItems(session);
330
+ const decls = addItemVariableDeclarations(testOutcomeDeclarations(assessment), Object.fromEntries(testItems.map((item) => [item.identifier, item.variables])));
347
331
  const ctx = new DeclarationContext(decls);
348
332
  const ops = new OperatorRegistry();
349
- // Build test items array for testVariables expression
350
- const testItems = Object.entries(itemScores).map(([id, scoring]) => ({
351
- identifier: id,
352
- variables: {
353
- SCORE: qtiValue('float', 'single', scoring.score),
354
- // Add any other outcome values from the scoring result
355
- ...Object.fromEntries(Object.entries(scoring.outcomeValues || {}).map(([k, v]) => [
356
- k,
357
- typeof v === 'number'
358
- ? qtiValue('float', 'single', v)
359
- : qtiValue('string', 'single', String(v)),
360
- ])),
361
- },
362
- }));
363
333
  // Parse and execute outcome processing
364
334
  const opEl = parseXml(assessment.outcomeProcessingXml).documentElement;
365
335
  if (!opEl)
@@ -371,16 +341,13 @@ export class ReferenceBackendAdapter {
371
341
  execProgram({
372
342
  ctx,
373
343
  ops,
374
- rng: Math.random,
344
+ rng: this.rng,
375
345
  test: { items: testItems },
376
346
  }, program);
377
- // Extract outcome values
378
347
  const result = {};
379
348
  for (const d of assessment.outcomeDeclarations || []) {
380
349
  const v = ctx.getValue(d.identifier);
381
- if (v.kind === 'value') {
382
- result[d.identifier] = v.value;
383
- }
350
+ result[d.identifier] = v.kind === 'value' ? v.value : null;
384
351
  }
385
352
  return result;
386
353
  }
@@ -466,50 +433,6 @@ export class ReferenceBackendAdapter {
466
433
  console.error('Failed to save session to localStorage:', error);
467
434
  }
468
435
  }
469
- findItemXml(assessment, itemIdentifier) {
470
- const findInSection = (section) => {
471
- for (const item of section.assessmentItemRefs) {
472
- if (item.identifier === itemIdentifier)
473
- return item.itemXml;
474
- }
475
- for (const child of section.sections ?? []) {
476
- const found = findInSection(child);
477
- if (found !== null)
478
- return found;
479
- }
480
- return null;
481
- };
482
- for (const part of assessment.testParts) {
483
- for (const section of part.sections) {
484
- const found = findInSection(section);
485
- if (found !== null)
486
- return found;
487
- }
488
- }
489
- return null;
490
- }
491
- findItemRef(assessment, itemIdentifier) {
492
- const findInSection = (section) => {
493
- for (const item of section.assessmentItemRefs) {
494
- if (item.identifier === itemIdentifier)
495
- return item;
496
- }
497
- for (const child of section.sections ?? []) {
498
- const found = findInSection(child);
499
- if (found)
500
- return found;
501
- }
502
- return null;
503
- };
504
- for (const part of assessment.testParts) {
505
- for (const section of part.sections) {
506
- const found = findInSection(section);
507
- if (found)
508
- return found;
509
- }
510
- }
511
- return null;
512
- }
513
436
  /**
514
437
  * Create demo assessment for testing
515
438
  *
@@ -647,7 +570,7 @@ export class ReferenceBackendAdapter {
647
570
  * @param options.baseUrl - Base URL for resolving relative hrefs
648
571
  */
649
572
  static async parseAssessmentTestXml(testXml, options = {}) {
650
- const { role = 'candidate', itemXmlMap = {}, fileResolver, baseUrl } = options;
573
+ const { role = 'candidate', itemXmlMap = {}, fileResolver, baseUrl, sharedCatalogs } = options;
651
574
  const maxSectionDepth = options.sectionReferenceLimits?.maxDepth ?? 32;
652
575
  if (!Number.isInteger(maxSectionDepth) || maxSectionDepth < 1) {
653
576
  throw new Error('sectionReferenceLimits.maxDepth must be a positive integer');
@@ -656,6 +579,9 @@ export class ReferenceBackendAdapter {
656
579
  const root = doc.documentElement;
657
580
  if (!root)
658
581
  throw new Error('Empty assessmentTest XML');
582
+ // Reads camelCase and QTI 3 kebab-case attribute spellings alike. Empty values
583
+ // are treated as missing here; the player-elements discovery parser keeps '' —
584
+ // the two are intentionally not shared so each call site keeps its semantics.
659
585
  const getAttr = (el, name) => {
660
586
  const direct = el.getAttribute(name);
661
587
  if (direct !== null && direct !== '')
@@ -806,10 +732,48 @@ export class ReferenceBackendAdapter {
806
732
  }
807
733
  }
808
734
  }
735
+ // Preload external processing fragments so the item session's synchronous
736
+ // resolver stays package-contained. Nested includes resolve relative to the
737
+ // fragment that references them; the processing engine still validates
738
+ // namespace, mode, depth, and cycles at build time.
739
+ const processingFragments = {};
740
+ const collectProcessingFragments = async (sourceXml, sourceHref, seen) => {
741
+ for (const includeHref of extractProcessingIncludeRefs(sourceXml)) {
742
+ const fragmentPath = resolveCheckedPackagePathFromFile(sourceHref, includeHref);
743
+ if (!fragmentPath || seen.has(fragmentPath))
744
+ continue;
745
+ seen.add(fragmentPath);
746
+ const fragmentXml = await loadText(fragmentPath);
747
+ if (fragmentXml === undefined)
748
+ continue;
749
+ processingFragments[fragmentPath] = fragmentXml;
750
+ await collectProcessingFragments(fragmentXml, fragmentPath, seen);
751
+ }
752
+ };
753
+ const fragmentSeen = new Set();
754
+ await collectProcessingFragments(itemXml, itemHref, fragmentSeen);
755
+ // Shared catalog files resolve against the package root, not the item.
756
+ const packageCatalogSources = [];
757
+ for (const shared of sharedCatalogs ?? []) {
758
+ if (shared.xml) {
759
+ packageCatalogSources.push({ href: shared.href, xml: shared.xml });
760
+ continue;
761
+ }
762
+ if (!shared.href)
763
+ continue;
764
+ const href = resolveCheckedHref(shared.href);
765
+ if (!href)
766
+ continue;
767
+ const xml = await loadText(href);
768
+ if (xml !== undefined)
769
+ packageCatalogSources.push({ href, xml });
770
+ }
809
771
  return createResolvedItemDeliveryContext({
810
772
  itemXml,
811
773
  itemHref,
812
774
  readText: (path) => packageTextByPath[path] ?? stimulusXmlByPath[path] ?? itemXmlMap[path],
775
+ ...(Object.keys(processingFragments).length > 0 ? { processingFragments } : {}),
776
+ ...(packageCatalogSources.length > 0 ? { packageCatalogSources } : {}),
813
777
  });
814
778
  };
815
779
  let resolveSectionRef;
@@ -826,11 +790,24 @@ export class ReferenceBackendAdapter {
826
790
  '';
827
791
  const requiredRaw = getAttr(ref, 'required');
828
792
  const fixedRaw = getAttr(ref, 'fixed');
793
+ const categories = (getAttr(ref, 'category') ?? '').split(/\s+/).filter(Boolean);
829
794
  const weights = childrenByTag(ref, 'weight').flatMap((weight) => {
830
795
  const identifier = getAttr(weight, 'identifier');
831
796
  const value = Number(getAttr(weight, 'value'));
832
797
  return identifier && Number.isFinite(value) ? [{ identifier, value }] : [];
833
798
  });
799
+ const variableMappings = childrenByTag(ref, 'variableMapping').flatMap((mapping) => {
800
+ const sourceIdentifier = getAttr(mapping, 'sourceIdentifier');
801
+ const targetIdentifier = getAttr(mapping, 'targetIdentifier');
802
+ return sourceIdentifier && targetIdentifier ? [{ sourceIdentifier, targetIdentifier }] : [];
803
+ });
804
+ const templateDefaults = childrenByTag(ref, 'templateDefault').flatMap((templateDefault) => {
805
+ const templateIdentifier = getAttr(templateDefault, 'templateIdentifier');
806
+ const expression = childElements(templateDefault)[0];
807
+ return templateIdentifier && expression
808
+ ? [{ templateIdentifier, expressionXml: serializeXml(expression) }]
809
+ : [];
810
+ });
834
811
  return {
835
812
  identifier: itemId,
836
813
  itemXml: resolvedXml,
@@ -842,6 +819,10 @@ export class ReferenceBackendAdapter {
842
819
  branchRule: parseBranchRules(ref),
843
820
  preConditions: parseConditionExpressions(ref, 'preCondition'),
844
821
  weights: weights.length > 0 ? weights : undefined,
822
+ categories: categories.length > 0 ? categories : undefined,
823
+ itemSessionControl: parseItemSessionControl(ref),
824
+ variableMappings: variableMappings.length > 0 ? variableMappings : undefined,
825
+ templateDefaults: templateDefaults.length > 0 ? templateDefaults : undefined,
845
826
  };
846
827
  };
847
828
  // Parse a single assessmentSection element without flattening nested sections.
@@ -855,6 +836,7 @@ export class ReferenceBackendAdapter {
855
836
  const visible = visibleRaw === undefined ? true : visibleRaw !== 'false';
856
837
  const requiredRaw = getAttr(sectionEl, 'required');
857
838
  const fixedRaw = getAttr(sectionEl, 'fixed');
839
+ const keepTogetherRaw = getAttr(sectionEl, 'keepTogether');
858
840
  const itemSessionControl = parseItemSessionControl(sectionEl);
859
841
  const timeLimits = parseTimeLimits(sectionEl);
860
842
  // rubricBlocks
@@ -905,6 +887,8 @@ export class ReferenceBackendAdapter {
905
887
  selection: parseSelection(sectionEl),
906
888
  ordering: parseOrdering(sectionEl),
907
889
  preConditions: parseConditionExpressions(sectionEl, 'preCondition'),
890
+ branchRule: parseBranchRules(sectionEl),
891
+ keepTogether: keepTogetherRaw === undefined ? undefined : keepTogetherRaw !== 'false',
908
892
  };
909
893
  };
910
894
  // Resolve assessmentSectionRef: load and parse referenced section file
@@ -961,29 +945,6 @@ export class ReferenceBackendAdapter {
961
945
  }
962
946
  return sections;
963
947
  };
964
- // Parse testPart-level itemSessionControl
965
- const parseTestPartItemSessionControl = (testPartEl) => {
966
- const isc = childrenByTag(testPartEl, 'itemSessionControl')[0];
967
- if (!isc)
968
- return undefined;
969
- const boolAttr = (name) => {
970
- const v = getAttr(isc, name);
971
- return v === undefined ? undefined : v !== 'false';
972
- };
973
- const intAttr = (name) => {
974
- const v = getAttr(isc, name);
975
- return v === undefined ? undefined : parseInt(v, 10);
976
- };
977
- return {
978
- maxAttempts: intAttr('maxAttempts'),
979
- showFeedback: boolAttr('showFeedback') ?? boolAttr('show-feedback'),
980
- allowReview: boolAttr('allowReview') ?? boolAttr('allow-review'),
981
- showSolution: boolAttr('showSolution') ?? boolAttr('show-solution'),
982
- allowComment: boolAttr('allowComment') ?? boolAttr('allow-comment'),
983
- allowSkipping: boolAttr('allowSkipping') ?? boolAttr('allow-skipping'),
984
- validateResponses: boolAttr('validateResponses') ?? boolAttr('validate-responses'),
985
- };
986
- };
987
948
  // Extract outcomeDeclarations
988
949
  const outcomeDeclarations = childrenByTag(root, 'outcomeDeclaration').map((d) => {
989
950
  const identifier = getAttr(d, 'identifier') ?? 'OUTCOME';
@@ -1011,19 +972,25 @@ export class ReferenceBackendAdapter {
1011
972
  const outcomeProcessingXml = outcomeProcessingEl
1012
973
  ? serializeXml(outcomeProcessingEl)
1013
974
  : undefined;
1014
- const testFeedback = childrenByTag(root, 'testFeedback').flatMap((feedback, index) => {
1015
- const outcomeIdentifier = getAttr(feedback, 'outcomeIdentifier');
1016
- if (!outcomeIdentifier)
1017
- return [];
1018
- const content = Array.from(feedback.childNodes).map((node) => serializeXml(node)).join('');
1019
- return [{
1020
- identifier: getAttr(feedback, 'identifier') ?? `test-feedback-${index + 1}`,
1021
- outcomeIdentifier,
1022
- showHide: (getAttr(feedback, 'showHide') ?? 'show'),
1023
- access: (getAttr(feedback, 'access') ?? 'atEnd'),
1024
- content,
1025
- }];
1026
- });
975
+ // QTI 3 wraps testFeedback content in qti-content-body.
976
+ const parseTestFeedback = (parent) => {
977
+ const items = childrenByTag(parent, 'testFeedback').flatMap((feedback, index) => {
978
+ const outcomeIdentifier = getAttr(feedback, 'outcomeIdentifier');
979
+ if (!outcomeIdentifier)
980
+ return [];
981
+ const body = childrenByTag(feedback, 'contentBody')[0] ?? feedback;
982
+ const content = Array.from(body.childNodes).map((node) => serializeXml(node)).join('');
983
+ return [{
984
+ identifier: getAttr(feedback, 'identifier') ?? `test-feedback-${index + 1}`,
985
+ outcomeIdentifier,
986
+ showHide: (getAttr(feedback, 'showHide') ?? 'show'),
987
+ access: (getAttr(feedback, 'access') ?? 'atEnd'),
988
+ content,
989
+ }];
990
+ });
991
+ return items.length > 0 ? items : undefined;
992
+ };
993
+ const testFeedback = parseTestFeedback(root);
1027
994
  // Extract assessment-level timeLimits.
1028
995
  const timeLimits = parseTimeLimits(root);
1029
996
  // Parse testParts
@@ -1038,7 +1005,7 @@ export class ReferenceBackendAdapter {
1038
1005
  const tpIdentifier = getAttr(tp, 'identifier') ?? 'part-1';
1039
1006
  const tpNavigationMode = (getAttr(tp, 'navigationMode') ?? 'nonlinear');
1040
1007
  const tpSubmissionMode = (getAttr(tp, 'submissionMode') ?? 'simultaneous');
1041
- const tpItemSessionControl = parseTestPartItemSessionControl(tp);
1008
+ const tpItemSessionControl = parseItemSessionControl(tp);
1042
1009
  const tpTimeLimits = parseTimeLimits(tp);
1043
1010
  const tpRubricBlockEls = childrenByTag(tp, 'rubricBlock');
1044
1011
  const tpRubricBlocks = tpRubricBlockEls.length > 0
@@ -1056,8 +1023,11 @@ export class ReferenceBackendAdapter {
1056
1023
  submissionMode: tpSubmissionMode,
1057
1024
  sections,
1058
1025
  rubricBlocks: tpRubricBlocks,
1026
+ testFeedback: parseTestFeedback(tp),
1059
1027
  itemSessionControl: tpItemSessionControl,
1060
1028
  timeLimits: tpTimeLimits,
1029
+ preConditions: parseConditionExpressions(tp, 'preCondition'),
1030
+ branchRule: parseBranchRules(tp),
1061
1031
  });
1062
1032
  }
1063
1033
  // If no testParts, try top-level sections
@@ -1091,59 +1061,176 @@ export class ReferenceBackendAdapter {
1091
1061
  timeLimits,
1092
1062
  outcomeDeclarations: outcomeDeclarations.length > 0 ? outcomeDeclarations : undefined,
1093
1063
  outcomeProcessingXml,
1094
- testFeedback: testFeedback.length > 0 ? testFeedback : undefined,
1064
+ testFeedback,
1095
1065
  baseUrl,
1096
1066
  };
1097
1067
  }
1098
- evaluateConditionXml(conditionXml, vars) {
1099
- // conditionXml is an operator element like <gt>...</gt> (not wrapped in <expression>).
1100
- const doc = parseXml(conditionXml);
1101
- const root = doc.documentElement;
1102
- if (!root)
1103
- return false;
1104
- const decls = {};
1105
- for (const [k, raw] of Object.entries(vars)) {
1106
- let v = qtiNull();
1107
- if (typeof raw === 'number')
1108
- v = qtiValue('float', 'single', raw);
1109
- else if (typeof raw === 'boolean')
1110
- v = qtiValue('boolean', 'single', raw);
1111
- else if (typeof raw === 'string')
1112
- v = qtiValue('string', 'single', raw);
1113
- decls[k] = {
1114
- identifier: k,
1115
- baseType: v.kind === 'value' ? v.baseType : 'string',
1116
- cardinality: 'single',
1117
- defaultValue: qtiNull(),
1118
- value: v,
1119
- };
1068
+ /**
1069
+ * Context for branch rules and preconditions: test outcomes, every submitted item's variables as
1070
+ * `itemIdentifier.VARIABLE`, and `current` unprefixed where the test declares no such outcome.
1071
+ */
1072
+ navigationDeclarations(session, outcomes, current = {}) {
1073
+ const itemVariables = {};
1074
+ for (const { item } of deliveredItems(session.assessment)) {
1075
+ const variables = session.itemTestStates?.[item.identifier]?.variables;
1076
+ if (variables)
1077
+ itemVariables[item.identifier] = applyVariableMappings(variables, item.variableMappings);
1120
1078
  }
1121
- const ctx = new DeclarationContext(decls);
1122
- const ops = new OperatorRegistry();
1123
- const expr = buildExpression(root, { scope: 'test' });
1124
- const out = evalExpr({ ctx, ops, rng: Math.random }, expr);
1125
- return out.kind === 'value' && out.baseType === 'boolean' ? Boolean(out.value) : false;
1079
+ return addItemVariableDeclarations(testOutcomeDeclarations(session.assessment, outcomes), itemVariables, current);
1126
1080
  }
1127
- getItemOrder(assessment) {
1128
- const out = [];
1129
- const visit = (section) => {
1130
- const components = section.children ?? [
1131
- ...(section.assessmentItemRefs ?? []).map((item) => ({ type: 'item', item })),
1132
- ...(section.sections ?? []).map((child) => ({ type: 'section', section: child })),
1133
- ];
1134
- for (const component of components) {
1135
- if (component.type === 'item')
1136
- out.push(component.item.identifier);
1137
- else
1138
- visit(component.section);
1081
+ /**
1082
+ * Next item after `delivered[index]`. Branch rules come first: the item's, then each enclosing
1083
+ * section's it ends (inner to outer), then the test part's when it ends that too. Item and
1084
+ * section rules apply in linear navigation only. With no matching rule, navigation falls through
1085
+ * to the following item. Preconditions then skip forward from the target. EXIT_TEST means the
1086
+ * remaining items are all skipped; undefined means the current item was the last.
1087
+ */
1088
+ nextItemIdentifier(assessment, delivered, index, decls) {
1089
+ const start = this.branchTarget(assessment, delivered, index, decls) ?? index + 1;
1090
+ const next = this.firstEligibleItem(assessment, delivered, start, delivered[index], decls);
1091
+ return next ?? (index + 1 < delivered.length ? 'EXIT_TEST' : undefined);
1092
+ }
1093
+ branchTarget(assessment, delivered, index, decls) {
1094
+ const current = delivered[index];
1095
+ const following = delivered[index + 1];
1096
+ const linear = this.isLinear(assessment, current.testPart);
1097
+ const holders = [];
1098
+ if (linear) {
1099
+ holders.push({ rules: current.item.branchRule, exitSection: current.sections[current.sections.length - 1] });
1100
+ for (let level = current.sections.length - 1; level >= 0; level--) {
1101
+ const section = current.sections[level];
1102
+ if (following?.sections.includes(section))
1103
+ break;
1104
+ holders.push({ rules: section.branchRule, exitSection: current.sections[level - 1] });
1105
+ }
1106
+ }
1107
+ if (following?.testPart !== current.testPart)
1108
+ holders.push({ rules: current.testPart.branchRule });
1109
+ for (const { rules, exitSection } of holders) {
1110
+ for (const rule of rules ?? []) {
1111
+ if (rule.conditionXml && !evaluateTestCondition(rule.conditionXml, decls, this.rng))
1112
+ continue;
1113
+ const target = this.resolveBranchTarget(rule.target, delivered, index, exitSection);
1114
+ if (target !== undefined)
1115
+ return target;
1139
1116
  }
1117
+ }
1118
+ return undefined;
1119
+ }
1120
+ /** Index a branch target resolves to, forward of `index`; delivered.length ends the test. */
1121
+ resolveBranchTarget(target, delivered, index, exitSection) {
1122
+ const current = delivered[index];
1123
+ const firstAfter = (match) => {
1124
+ for (let j = index + 1; j < delivered.length; j++)
1125
+ if (match(delivered[j]))
1126
+ return j;
1127
+ return undefined;
1140
1128
  };
1141
- for (const part of assessment.testParts || []) {
1142
- for (const section of part.sections || []) {
1143
- visit(section);
1129
+ switch (target) {
1130
+ case 'EXIT_TEST':
1131
+ return delivered.length;
1132
+ case 'EXIT_TESTPART':
1133
+ return firstAfter((d) => d.testPart !== current.testPart) ?? delivered.length;
1134
+ case 'EXIT_SECTION':
1135
+ if (!exitSection)
1136
+ return undefined;
1137
+ return firstAfter((d) => !d.sections.includes(exitSection)) ?? delivered.length;
1138
+ default:
1139
+ return (firstAfter((d) => d.item.identifier === target) ??
1140
+ firstAfter((d) => d.sections.some((section) => section.identifier === target)) ??
1141
+ firstAfter((d) => d.testPart.identifier === target));
1142
+ }
1143
+ }
1144
+ /**
1145
+ * First item from `start` whose preconditions hold. A test part's are checked on entering it in
1146
+ * any navigation mode; a newly entered section's (outermost first) and the item's only in linear
1147
+ * navigation. A failing part or section skips everything inside it.
1148
+ */
1149
+ firstEligibleItem(assessment, delivered, start, from, decls) {
1150
+ const holds = (conditions) => (conditions ?? []).every((condition) => evaluateTestCondition(condition, decls, this.rng));
1151
+ const skipPast = (j, inside) => {
1152
+ let next = j + 1;
1153
+ while (next < delivered.length && inside(delivered[next]))
1154
+ next++;
1155
+ return next;
1156
+ };
1157
+ let j = start;
1158
+ candidates: while (j < delivered.length) {
1159
+ const candidate = delivered[j];
1160
+ const previous = j === start ? from : delivered[j - 1];
1161
+ if (candidate.testPart !== previous?.testPart && !holds(candidate.testPart.preConditions)) {
1162
+ j = skipPast(j, (d) => d.testPart === candidate.testPart);
1163
+ continue;
1144
1164
  }
1165
+ if (this.isLinear(assessment, candidate.testPart)) {
1166
+ for (const section of candidate.sections) {
1167
+ if (previous?.sections.includes(section) || holds(section.preConditions))
1168
+ continue;
1169
+ j = skipPast(j, (d) => d.sections.includes(section));
1170
+ continue candidates;
1171
+ }
1172
+ if (!holds(candidate.item.preConditions)) {
1173
+ j++;
1174
+ continue;
1175
+ }
1176
+ }
1177
+ return candidate.item.identifier;
1145
1178
  }
1146
- return out;
1179
+ return undefined;
1180
+ }
1181
+ isLinear(assessment, testPart) {
1182
+ return (testPart.navigationMode ?? assessment.navigationMode) === 'linear';
1183
+ }
1184
+ /** Delivered item refs in order, each with the identifiers of the sections containing it (outermost first). */
1185
+ getItemRefsInOrder(assessment) {
1186
+ return deliveredItems(assessment).map(({ item, sections }) => ({
1187
+ item,
1188
+ sectionIdentifiers: sections.map((section) => section.identifier),
1189
+ }));
1190
+ }
1191
+ /**
1192
+ * Test-level view of every delivered item. Items not yet submitted carry their declared defaults
1193
+ * and count as not presented; sessions stored before item test states existed fall back to the
1194
+ * submitted scores, leaving correctness to SCORE/MAXSCORE inference.
1195
+ */
1196
+ buildTestItems(session) {
1197
+ const itemScores = session.state.itemScores ?? {};
1198
+ return this.getItemRefsInOrder(session.assessment).map(({ item, sectionIdentifiers }) => {
1199
+ const scoring = itemScores[item.identifier];
1200
+ const presented = scoring !== undefined;
1201
+ const stored = presented ? session.itemTestStates?.[item.identifier] : undefined;
1202
+ const itemState = presented ? stored : defaultItemTestState(item.itemXml);
1203
+ const variables = {
1204
+ ...(itemState?.variables ?? (scoring ? this.scoredItemVariables(scoring) : {})),
1205
+ };
1206
+ if (scoring && !variables.SCORE)
1207
+ variables.SCORE = qtiValue('float', 'single', scoring.score);
1208
+ Object.assign(variables, applyVariableMappings(variables, item.variableMappings));
1209
+ const legacy = presented && !stored;
1210
+ return {
1211
+ identifier: item.identifier,
1212
+ sectionIdentifiers,
1213
+ categories: item.categories,
1214
+ weights: item.weights ? Object.fromEntries(item.weights.map((w) => [w.identifier, w.value])) : undefined,
1215
+ variables,
1216
+ outcomeBounds: (itemState ?? defaultItemTestState(item.itemXml))?.outcomeBounds,
1217
+ presented,
1218
+ responded: legacy
1219
+ ? this.hasAnyResponse(session.state.itemResponses[item.identifier] ?? {})
1220
+ : presented && itemState?.responded === true,
1221
+ ...(legacy
1222
+ ? {}
1223
+ : { correct: presented && itemState?.correct === true, incorrect: presented && itemState?.correct === false }),
1224
+ selected: true,
1225
+ };
1226
+ });
1227
+ }
1228
+ /** Variables recoverable from a scoring result alone: numbers as float, everything else as string. */
1229
+ scoredItemVariables(scoring) {
1230
+ return Object.fromEntries(Object.entries(scoring.outcomeValues || {}).map(([k, v]) => [
1231
+ k,
1232
+ typeof v === 'number' ? qtiValue('float', 'single', v) : qtiValue('string', 'single', String(v)),
1233
+ ]));
1147
1234
  }
1148
1235
  // =========================================================================
1149
1236
  // ITEM BANK HELPERS