@pie-qti/assessment-player 0.1.1 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +19 -16
  2. package/dist/core/AssessmentPlayer.d.ts +30 -8
  3. package/dist/core/AssessmentPlayer.d.ts.map +1 -1
  4. package/dist/core/AssessmentPlayer.js +134 -40
  5. package/dist/core/TimeManager.d.ts +9 -0
  6. package/dist/core/TimeManager.d.ts.map +1 -1
  7. package/dist/core/TimeManager.js +16 -3
  8. package/dist/index.d.ts +1 -1
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/integration/ReferenceBackendAdapter.d.ts +28 -2
  11. package/dist/integration/ReferenceBackendAdapter.d.ts.map +1 -1
  12. package/dist/integration/ReferenceBackendAdapter.js +385 -15
  13. package/dist/integration/api-contract.d.ts +88 -17
  14. package/dist/integration/api-contract.d.ts.map +1 -1
  15. package/dist/integration/index.d.ts +1 -1
  16. package/dist/integration/index.d.ts.map +1 -1
  17. package/dist/types/index.d.ts +1 -1
  18. package/dist/types/index.d.ts.map +1 -1
  19. package/package.json +100 -80
  20. package/src/components/AssessmentShell.svelte +8 -8
  21. package/src/components/ItemRenderer.svelte +8 -8
  22. package/src/components/NavigationBar.svelte +3 -1
  23. package/src/components/RubricDisplay.svelte +2 -2
  24. package/src/components/index.ts +1 -1
  25. package/src/core/AssessmentPlayer.ts +164 -51
  26. package/src/core/TimeManager.ts +20 -3
  27. package/src/index.ts +1 -1
  28. package/src/integration/ReferenceBackendAdapter.ts +454 -23
  29. package/src/integration/api-contract.ts +89 -17
  30. package/src/integration/index.ts +5 -5
  31. package/src/types/index.ts +1 -1
  32. package/.turbo/turbo-build.log +0 -1
  33. package/BACKEND-INTEGRATION.md +0 -620
  34. package/CHANGELOG.md +0 -11
  35. package/EXTENSIBILITY.md +0 -551
  36. package/svelte.config.js +0 -8
  37. package/tests/ReferenceBackendAdapter.spec.ts +0 -309
  38. package/tests/setup.ts +0 -103
  39. package/tests/smoke.test.ts +0 -7
  40. package/tsconfig.json +0 -20
  41. package/tsconfig.svelte.json +0 -10
@@ -29,11 +29,14 @@
29
29
 
30
30
  import {
31
31
  buildExpression,
32
+ buildOutcomeProcessingAst,
32
33
  DeclarationContext,
33
34
  type DeclarationMap,
34
35
  evalExpr,
36
+ execProgram,
35
37
  OperatorRegistry,
36
38
  parseXml,
39
+ serializeXml,
37
40
  type QtiValue,
38
41
  qtiNull,
39
42
  qtiValue,
@@ -41,6 +44,8 @@ import {
41
44
  import { Player } from '@pie-qti/item-player';
42
45
  import { parse } from 'node-html-parser';
43
46
  import type {
47
+ AssessmentSessionState,
48
+ AssessmentScoringResult,
44
49
  BackendAdapter,
45
50
  FinalizeAssessmentRequest,
46
51
  FinalizeAssessmentResponse,
@@ -48,13 +53,13 @@ import type {
48
53
  InitSessionResponse,
49
54
  QueryItemBankRequest,
50
55
  QueryItemBankResponse,
51
- SaveStateRequest,
52
- SaveStateResponse,
53
- ScoringResult,
56
+ SaveAssessmentStateRequest,
57
+ SaveAssessmentStateResponse,
54
58
  SecureAssessment,
55
59
  SecureItemRef,
60
+ SecureSection,
61
+ SecureTestPart,
56
62
  SessionId,
57
- SessionState,
58
63
  SubmitResponsesRequest,
59
64
  SubmitResponsesResponse,
60
65
  } from './api-contract.js';
@@ -69,6 +74,18 @@ const STORAGE_PREFIX = 'qti_session_';
69
74
  */
70
75
  const BANK_CACHE_PREFIX = 'qti_bank_cache_';
71
76
 
77
+ function toCanonicalQtiName(name: string | null | undefined): string {
78
+ const withoutPrefix = (name ?? '').replace(/^qti-/, '');
79
+ return withoutPrefix.replace(/-([a-z])/g, (_, char: string) => char.toUpperCase());
80
+ }
81
+
82
+ const qtiElementNameMapper = {
83
+ version: 'qti2x-or-qti3',
84
+ toCanonical: (elementName: string) => toCanonicalQtiName(elementName).toLowerCase(),
85
+ toNative: (canonicalName: string) => canonicalName,
86
+ isValidElementName: () => true,
87
+ };
88
+
72
89
  /**
73
90
  * Cache entry for item bank queries
74
91
  */
@@ -88,7 +105,7 @@ interface StoredSession {
88
105
  /** Full assessment structure with QTI XML */
89
106
  assessment: SecureAssessment;
90
107
  /** Current state */
91
- state: SessionState;
108
+ state: AssessmentSessionState;
92
109
  /** Created timestamp */
93
110
  createdAt: number;
94
111
  /** Finalized flag */
@@ -152,8 +169,8 @@ export class ReferenceBackendAdapter implements BackendAdapter {
152
169
  // For reference implementation, we'll use demo data
153
170
  const assessment = this.getAssessment(request.assessmentId);
154
171
 
155
- const state: SessionState = {
156
- currentItemIdentifier: assessment.testParts[0].sections[0].items[0].identifier,
172
+ const state: AssessmentSessionState = {
173
+ currentItemIdentifier: assessment.testParts[0].sections[0].assessmentItemRefs[0].identifier,
157
174
  visitedItems: [],
158
175
  itemResponses: {},
159
176
  itemScores: {},
@@ -235,15 +252,27 @@ export class ReferenceBackendAdapter implements BackendAdapter {
235
252
 
236
253
  const order = this.getItemOrder(session.assessment);
237
254
  const idx = order.indexOf(request.itemIdentifier);
238
- let nextItemIdentifier = idx >= 0 ? order[idx + 1] : undefined;
239
-
240
- // Demo branching using qti-processing (backend-authoritative). If SCORE > 0, go to item2.
241
- if (request.itemIdentifier === 'item1') {
242
- const condXml = `<gt><variable identifier="SCORE" /><baseValue baseType="float">0</baseValue></gt>`;
243
- if (this.evaluateConditionXml(condXml, { SCORE: result.score })) {
244
- nextItemIdentifier = 'item2';
245
- } else {
246
- nextItemIdentifier = undefined;
255
+ let nextItemIdentifier: string | undefined = idx >= 0 ? order[idx + 1] : undefined;
256
+
257
+ // QTI branchRule evaluation (backend-authoritative).
258
+ // Evaluate each rule in order; the first matching rule determines the next item.
259
+ // Special targets EXIT_TEST / EXIT_TESTPART / EXIT_SECTION are returned as-is for
260
+ // the client to interpret.
261
+ const itemRef = this.findItemRef(session.assessment, request.itemIdentifier);
262
+ if (itemRef?.branchRule && itemRef.branchRule.length > 0) {
263
+ const outcomeVars: Record<string, unknown> = {
264
+ ...result.outcomeValues,
265
+ SCORE: result.score,
266
+ };
267
+ nextItemIdentifier = undefined; // reset — branch rules take full control
268
+ for (const rule of itemRef.branchRule) {
269
+ const matches = rule.conditionXml
270
+ ? this.evaluateConditionXml(rule.conditionXml, outcomeVars)
271
+ : true; // unconditional branch
272
+ if (matches) {
273
+ nextItemIdentifier = rule.target;
274
+ break;
275
+ }
247
276
  }
248
277
  }
249
278
 
@@ -258,7 +287,7 @@ export class ReferenceBackendAdapter implements BackendAdapter {
258
287
  /**
259
288
  * Save session state (for auto-save)
260
289
  */
261
- async saveState(request: SaveStateRequest): Promise<SaveStateResponse> {
290
+ async saveState(request: SaveAssessmentStateRequest): Promise<SaveAssessmentStateResponse> {
262
291
  const session = this.loadSession(request.sessionId);
263
292
  if (!session) {
264
293
  return {
@@ -300,9 +329,13 @@ export class ReferenceBackendAdapter implements BackendAdapter {
300
329
 
301
330
  // Compute total score
302
331
  const itemScores = session.state.itemScores || {};
303
- const totalScore = Object.values(itemScores).reduce((sum, result) => sum + result.score, 0);
332
+ const fallbackTotal = Object.values(itemScores).reduce((sum, result) => sum + result.score, 0);
304
333
  const maxScore = Object.values(itemScores).reduce((sum, result) => sum + result.maxScore, 0);
305
334
 
335
+ // Execute test-level outcome processing if available
336
+ const outcomes = this.runOutcomeProcessing(session.assessment, itemScores);
337
+ const totalScore = outcomes !== null ? (outcomes['SCORE_TOTAL'] ?? outcomes['SCORE'] ?? fallbackTotal) as number : fallbackTotal;
338
+
306
339
  return {
307
340
  success: true,
308
341
  totalScore,
@@ -312,6 +345,94 @@ export class ReferenceBackendAdapter implements BackendAdapter {
312
345
  };
313
346
  }
314
347
 
348
+ /**
349
+ * Execute test-level outcome processing (T9/T1).
350
+ * Returns a map of outcome variable values, or null if no outcomeProcessing is defined.
351
+ */
352
+ private runOutcomeProcessing(
353
+ assessment: SecureAssessment,
354
+ itemScores: Record<string, AssessmentScoringResult>
355
+ ): Record<string, unknown> | null {
356
+ if (!assessment.outcomeProcessingXml) {
357
+ return null;
358
+ }
359
+
360
+ try {
361
+ // Build declaration map from outcomeDeclarations
362
+ const decls: DeclarationMap = {};
363
+ for (const d of assessment.outcomeDeclarations || []) {
364
+ const baseType = d.baseType as any;
365
+ const cardinality = d.cardinality as any;
366
+ let defaultQtiValue: QtiValue;
367
+ if (d.defaultValue !== undefined) {
368
+ defaultQtiValue = qtiValue(baseType, cardinality, d.defaultValue);
369
+ } else if (baseType === 'float' || baseType === 'integer') {
370
+ defaultQtiValue = qtiValue(baseType, 'single', 0);
371
+ } else {
372
+ defaultQtiValue = qtiNull();
373
+ }
374
+ decls[d.identifier] = {
375
+ identifier: d.identifier,
376
+ baseType,
377
+ cardinality,
378
+ defaultValue: defaultQtiValue,
379
+ value: { ...defaultQtiValue },
380
+ };
381
+ }
382
+
383
+ const ctx = new DeclarationContext(decls);
384
+ const ops = new OperatorRegistry();
385
+
386
+ // Build test items array for testVariables expression
387
+ const testItems = Object.entries(itemScores).map(([id, scoring]) => ({
388
+ identifier: id,
389
+ variables: {
390
+ SCORE: qtiValue('float', 'single', scoring.score),
391
+ // Add any other outcome values from the scoring result
392
+ ...Object.fromEntries(
393
+ Object.entries(scoring.outcomeValues || {}).map(([k, v]) => [
394
+ k,
395
+ typeof v === 'number'
396
+ ? qtiValue('float', 'single', v)
397
+ : qtiValue('string', 'single', String(v)),
398
+ ])
399
+ ),
400
+ },
401
+ }));
402
+
403
+ // Parse and execute outcome processing
404
+ const opEl = parseXml(assessment.outcomeProcessingXml).documentElement;
405
+ if (!opEl) return null;
406
+
407
+ const program = buildOutcomeProcessingAst(opEl, {
408
+ scope: 'test',
409
+ elementNameMapper: qtiElementNameMapper,
410
+ });
411
+ execProgram(
412
+ {
413
+ ctx,
414
+ ops,
415
+ rng: Math.random,
416
+ test: { items: testItems },
417
+ },
418
+ program
419
+ );
420
+
421
+ // Extract outcome values
422
+ const result: Record<string, unknown> = {};
423
+ for (const d of assessment.outcomeDeclarations || []) {
424
+ const v = ctx.getValue(d.identifier);
425
+ if (v.kind === 'value') {
426
+ result[d.identifier] = v.value;
427
+ }
428
+ }
429
+ return result;
430
+ } catch (err) {
431
+ console.warn('[ReferenceBackendAdapter] outcomeProcessing failed:', err);
432
+ return null;
433
+ }
434
+ }
435
+
315
436
  /**
316
437
  * Resume existing session (alias for initSession with resumeSessionId)
317
438
  */
@@ -400,7 +521,7 @@ export class ReferenceBackendAdapter implements BackendAdapter {
400
521
  private findItemXml(assessment: SecureAssessment, itemIdentifier: string): string | null {
401
522
  for (const part of assessment.testParts) {
402
523
  for (const section of part.sections) {
403
- for (const item of section.items) {
524
+ for (const item of section.assessmentItemRefs) {
404
525
  if (item.identifier === itemIdentifier) {
405
526
  return item.itemXml;
406
527
  }
@@ -410,13 +531,26 @@ export class ReferenceBackendAdapter implements BackendAdapter {
410
531
  return null;
411
532
  }
412
533
 
534
+ private findItemRef(assessment: SecureAssessment, itemIdentifier: string): SecureItemRef | null {
535
+ for (const part of assessment.testParts) {
536
+ for (const section of part.sections) {
537
+ for (const item of section.assessmentItemRefs) {
538
+ if (item.identifier === itemIdentifier) {
539
+ return item;
540
+ }
541
+ }
542
+ }
543
+ }
544
+ return null;
545
+ }
546
+
413
547
  /**
414
548
  * Score an item using the Player
415
549
  *
416
550
  * **SECURITY WARNING**: This is done CLIENT-SIDE for demo purposes only.
417
551
  * Production implementations MUST perform scoring SERVER-SIDE.
418
552
  */
419
- private scoreItem(itemXml: string, responses: Record<string, any>): ScoringResult {
553
+ private scoreItem(itemXml: string, responses: Record<string, any>): AssessmentScoringResult {
420
554
  try {
421
555
  // Extract identifier from XML using regex (more reliable than DOM parsing)
422
556
  const identifierMatch = itemXml.match(/assessmentItem[^>]+identifier=["']([^"']+)["']/);
@@ -471,7 +605,7 @@ export class ReferenceBackendAdapter implements BackendAdapter {
471
605
  testParts: [
472
606
  {
473
607
  identifier: 'part1',
474
- rubrics: [],
608
+ rubricBlocks: [],
475
609
  itemSessionControl: {
476
610
  maxAttempts: 1,
477
611
  showFeedback: true,
@@ -486,7 +620,7 @@ export class ReferenceBackendAdapter implements BackendAdapter {
486
620
  identifier: 'section1',
487
621
  title: 'Section 1',
488
622
  visible: true,
489
- items: [
623
+ assessmentItemRefs: [
490
624
  {
491
625
  identifier: 'item1',
492
626
  role: 'candidate',
@@ -575,6 +709,303 @@ export class ReferenceBackendAdapter implements BackendAdapter {
575
709
  };
576
710
  }
577
711
 
712
+ // =========================================================================
713
+ // STATIC: QTI TEST XML PARSER
714
+ // =========================================================================
715
+
716
+ /**
717
+ * Parse a QTI assessmentTest XML string into a SecureAssessment structure.
718
+ *
719
+ * Handles:
720
+ * - S1: section-level itemSessionControl
721
+ * - S9: assessmentSectionRef href resolution (requires fileResolver)
722
+ * - T9/T1: outcomeDeclarations + outcomeProcessing extraction
723
+ *
724
+ * @param testXml - Raw QTI assessmentTest XML string
725
+ * @param options.role - Role to assign to items (default: 'candidate')
726
+ * @param options.itemXmlMap - Map of item identifier -> itemXml for pre-loaded items
727
+ * @param options.fileResolver - Async function to load external files by relative href
728
+ * @param options.baseUrl - Base URL for resolving relative hrefs
729
+ */
730
+ static async parseAssessmentTestXml(
731
+ testXml: string,
732
+ options: {
733
+ role?: SecureItemRef['role'];
734
+ itemXmlMap?: Record<string, string>;
735
+ fileResolver?: (href: string) => Promise<string>;
736
+ baseUrl?: string;
737
+ } = {}
738
+ ): Promise<SecureAssessment> {
739
+ const { role = 'candidate', itemXmlMap = {}, fileResolver, baseUrl } = options;
740
+ const doc = parseXml(testXml);
741
+ const root = doc.documentElement;
742
+ if (!root) throw new Error('Empty assessmentTest XML');
743
+
744
+ const getAttr = (el: Element, name: string): string | undefined => {
745
+ const direct = el.getAttribute(name);
746
+ if (direct !== null && direct !== '') return direct;
747
+ const mapped = el.getAttribute(name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`));
748
+ return mapped === null || mapped === '' ? undefined : mapped;
749
+ };
750
+
751
+ const childElements = (el: Element): Element[] =>
752
+ Array.from(el.childNodes).filter((n): n is Element => n.nodeType === 1);
753
+
754
+ const childrenByTag = (el: Element, tag: string): Element[] =>
755
+ childElements(el).filter((c) => toCanonicalQtiName(c.localName) === tag);
756
+
757
+ // Parse itemSessionControl element
758
+ const parseItemSessionControl = (
759
+ el: Element
760
+ ): SecureSection['itemSessionControl'] | undefined => {
761
+ const isc = childrenByTag(el, 'itemSessionControl')[0];
762
+ if (!isc) return undefined;
763
+ const boolAttr = (name: string): boolean | undefined => {
764
+ const v = getAttr(isc, name);
765
+ return v === undefined ? undefined : v !== 'false';
766
+ };
767
+ const intAttr = (name: string): number | undefined => {
768
+ const v = getAttr(isc, name);
769
+ return v === undefined ? undefined : parseInt(v, 10);
770
+ };
771
+ return {
772
+ maxAttempts: intAttr('maxAttempts'),
773
+ showFeedback: boolAttr('showFeedback') ?? boolAttr('show-feedback'),
774
+ allowReview: boolAttr('allowReview') ?? boolAttr('allow-review'),
775
+ showSolution: boolAttr('showSolution') ?? boolAttr('show-solution'),
776
+ allowComment: boolAttr('allowComment') ?? boolAttr('allow-comment'),
777
+ allowSkipping: boolAttr('allowSkipping') ?? boolAttr('allow-skipping'),
778
+ validateResponses: boolAttr('validateResponses') ?? boolAttr('validate-responses'),
779
+ };
780
+ };
781
+
782
+ // Parse a single assessmentSection element
783
+ const parseSection = (sectionEl: Element): SecureSection => {
784
+ const identifier = getAttr(sectionEl, 'identifier') ?? 'section';
785
+ const title = getAttr(sectionEl, 'title');
786
+ const visibleRaw = getAttr(sectionEl, 'visible');
787
+ const visible = visibleRaw === undefined ? true : visibleRaw !== 'false';
788
+
789
+ const itemSessionControl = parseItemSessionControl(sectionEl);
790
+
791
+ // rubricBlocks
792
+ const rubricBlockEls = childrenByTag(sectionEl, 'rubricBlock');
793
+ const rubricBlocks = rubricBlockEls.length > 0
794
+ ? rubricBlockEls.map((b, idx) => ({
795
+ identifier: getAttr(b, 'identifier') ?? `${identifier}-rubric-${idx + 1}`,
796
+ view: (getAttr(b, 'view') ?? 'candidate').split(/\s+/).filter(Boolean) as any[],
797
+ use: getAttr(b, 'use'),
798
+ content: serializeXml(b),
799
+ }))
800
+ : undefined;
801
+
802
+ // assessmentItemRefs
803
+ const itemRefEls = childrenByTag(sectionEl, 'assessmentItemRef');
804
+ const assessmentItemRefs: SecureItemRef[] = itemRefEls.map((ref) => {
805
+ const itemId = getAttr(ref, 'identifier') ?? 'item';
806
+ const href = getAttr(ref, 'href');
807
+ // Look up pre-loaded XML by identifier or href
808
+ const resolvedXml = itemXmlMap[itemId] ?? (href ? itemXmlMap[href] : undefined) ?? '';
809
+ const requiredRaw = getAttr(ref, 'required');
810
+ const required = requiredRaw === undefined ? undefined : requiredRaw !== 'false';
811
+ return {
812
+ identifier: itemId,
813
+ itemXml: resolvedXml,
814
+ role,
815
+ required,
816
+ };
817
+ });
818
+
819
+ return {
820
+ identifier,
821
+ title,
822
+ visible,
823
+ assessmentItemRefs,
824
+ rubricBlocks,
825
+ itemSessionControl,
826
+ };
827
+ };
828
+
829
+ // Resolve assessmentSectionRef: load and parse referenced section file
830
+ const resolveSectionRef = async (sectionRefEl: Element): Promise<SecureSection | null> => {
831
+ const href = getAttr(sectionRefEl, 'href');
832
+ if (!href) {
833
+ console.warn('[ReferenceBackendAdapter] assessmentSectionRef missing href, skipping');
834
+ return null;
835
+ }
836
+
837
+ if (!fileResolver) {
838
+ console.warn(
839
+ `[ReferenceBackendAdapter] assessmentSectionRef href="${href}" found but no fileResolver provided, skipping`
840
+ );
841
+ return null;
842
+ }
843
+
844
+ try {
845
+ const sectionXml = await fileResolver(href);
846
+ const secDoc = parseXml(sectionXml);
847
+ const secRoot = secDoc.documentElement;
848
+ if (!secRoot || toCanonicalQtiName(secRoot.localName) !== 'assessmentSection') {
849
+ console.warn(
850
+ `[ReferenceBackendAdapter] assessmentSectionRef href="${href}": root element is not <assessmentSection>, skipping`
851
+ );
852
+ return null;
853
+ }
854
+ return parseSection(secRoot);
855
+ } catch (err) {
856
+ console.warn(
857
+ `[ReferenceBackendAdapter] Failed to load assessmentSectionRef href="${href}":`,
858
+ err
859
+ );
860
+ return null;
861
+ }
862
+ };
863
+
864
+ // Parse testPart children (sections + sectionRefs)
865
+ const parseSectionsForTestPart = async (testPartEl: Element): Promise<SecureSection[]> => {
866
+ const sections: SecureSection[] = [];
867
+ for (const child of childElements(testPartEl)) {
868
+ if (toCanonicalQtiName(child.localName) === 'assessmentSection') {
869
+ sections.push(parseSection(child));
870
+ } else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {
871
+ const resolved = await resolveSectionRef(child);
872
+ if (resolved) sections.push(resolved);
873
+ }
874
+ }
875
+ return sections;
876
+ };
877
+
878
+ // Parse testPart-level itemSessionControl
879
+ const parseTestPartItemSessionControl = (
880
+ testPartEl: Element
881
+ ): SecureTestPart['itemSessionControl'] | undefined => {
882
+ const isc = childrenByTag(testPartEl, 'itemSessionControl')[0];
883
+ if (!isc) return undefined;
884
+ const boolAttr = (name: string): boolean | undefined => {
885
+ const v = getAttr(isc, name);
886
+ return v === undefined ? undefined : v !== 'false';
887
+ };
888
+ const intAttr = (name: string): number | undefined => {
889
+ const v = getAttr(isc, name);
890
+ return v === undefined ? undefined : parseInt(v, 10);
891
+ };
892
+ return {
893
+ maxAttempts: intAttr('maxAttempts'),
894
+ showFeedback: boolAttr('showFeedback') ?? boolAttr('show-feedback'),
895
+ allowReview: boolAttr('allowReview') ?? boolAttr('allow-review'),
896
+ showSolution: boolAttr('showSolution') ?? boolAttr('show-solution'),
897
+ allowComment: boolAttr('allowComment') ?? boolAttr('allow-comment'),
898
+ allowSkipping: boolAttr('allowSkipping') ?? boolAttr('allow-skipping'),
899
+ validateResponses: boolAttr('validateResponses') ?? boolAttr('validate-responses'),
900
+ };
901
+ };
902
+
903
+ // Extract outcomeDeclarations
904
+ const outcomeDeclarations = childrenByTag(root, 'outcomeDeclaration').map((d) => {
905
+ const identifier = getAttr(d, 'identifier') ?? 'OUTCOME';
906
+ const baseType = getAttr(d, 'baseType') ?? 'float';
907
+ const cardinality = getAttr(d, 'cardinality') ?? 'single';
908
+ // Parse defaultValue if present
909
+ const defaultValueEl = childrenByTag(d, 'defaultValue')[0];
910
+ let defaultValue: unknown = undefined;
911
+ if (defaultValueEl) {
912
+ const valueEl = childrenByTag(defaultValueEl, 'value')[0];
913
+ if (valueEl) {
914
+ const text = valueEl.textContent?.trim() ?? '0';
915
+ if (baseType === 'float' || baseType === 'integer') {
916
+ defaultValue = Number(text);
917
+ } else {
918
+ defaultValue = text;
919
+ }
920
+ }
921
+ }
922
+ return { identifier, baseType, cardinality, defaultValue };
923
+ });
924
+
925
+ // Extract outcomeProcessing XML
926
+ const outcomeProcessingEl = childrenByTag(root, 'outcomeProcessing')[0];
927
+ const outcomeProcessingXml = outcomeProcessingEl
928
+ ? serializeXml(outcomeProcessingEl)
929
+ : undefined;
930
+
931
+ // Extract timeLimits
932
+ const timeLimitsEl = childrenByTag(root, 'timeLimit')[0] ?? childrenByTag(root, 'timeLimits')[0];
933
+ const timeLimits = timeLimitsEl
934
+ ? {
935
+ maxTime: getAttr(timeLimitsEl, 'maxTime')
936
+ ? Number(getAttr(timeLimitsEl, 'maxTime'))
937
+ : undefined,
938
+ allowLateSubmission: getAttr(timeLimitsEl, 'allowLateSubmission') === 'true',
939
+ }
940
+ : undefined;
941
+
942
+ // Parse testParts
943
+ const testPartEls = childrenByTag(root, 'testPart');
944
+ const firstTestPart = testPartEls[0];
945
+
946
+ // Navigation/submission mode from first testPart (QTI 2.2 spec)
947
+ const navigationMode = (getAttr(firstTestPart ?? root, 'navigationMode') ?? 'nonlinear') as
948
+ | 'linear'
949
+ | 'nonlinear';
950
+ const submissionMode = (getAttr(firstTestPart ?? root, 'submissionMode') ?? 'simultaneous') as
951
+ | 'individual'
952
+ | 'simultaneous';
953
+
954
+ const testParts: SecureTestPart[] = [];
955
+ for (const tp of testPartEls) {
956
+ const tpIdentifier = getAttr(tp, 'identifier') ?? 'part-1';
957
+ const tpItemSessionControl = parseTestPartItemSessionControl(tp);
958
+ const tpRubricBlockEls = childrenByTag(tp, 'rubricBlock');
959
+ const tpRubricBlocks = tpRubricBlockEls.length > 0
960
+ ? tpRubricBlockEls.map((b, idx) => ({
961
+ identifier: getAttr(b, 'identifier') ?? `${tpIdentifier}-rubric-${idx + 1}`,
962
+ view: (getAttr(b, 'view') ?? 'candidate').split(/\s+/).filter(Boolean) as any[],
963
+ use: getAttr(b, 'use'),
964
+ content: serializeXml(b),
965
+ }))
966
+ : undefined;
967
+
968
+ const sections = await parseSectionsForTestPart(tp);
969
+ testParts.push({
970
+ identifier: tpIdentifier,
971
+ sections,
972
+ rubricBlocks: tpRubricBlocks,
973
+ itemSessionControl: tpItemSessionControl,
974
+ });
975
+ }
976
+
977
+ // If no testParts, try top-level sections
978
+ if (testParts.length === 0) {
979
+ const topSections: SecureSection[] = [];
980
+ for (const child of childElements(root)) {
981
+ if (toCanonicalQtiName(child.localName) === 'assessmentSection') {
982
+ topSections.push(parseSection(child));
983
+ } else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {
984
+ const resolved = await resolveSectionRef(child);
985
+ if (resolved) topSections.push(resolved);
986
+ }
987
+ }
988
+ if (topSections.length > 0) {
989
+ testParts.push({
990
+ identifier: 'part-1',
991
+ sections: topSections,
992
+ });
993
+ }
994
+ }
995
+
996
+ return {
997
+ identifier: getAttr(root, 'identifier') ?? 'assessment',
998
+ title: getAttr(root, 'title') ?? 'Assessment',
999
+ navigationMode,
1000
+ submissionMode,
1001
+ testParts,
1002
+ timeLimits,
1003
+ outcomeDeclarations: outcomeDeclarations.length > 0 ? outcomeDeclarations : undefined,
1004
+ outcomeProcessingXml,
1005
+ baseUrl,
1006
+ };
1007
+ }
1008
+
578
1009
  private evaluateConditionXml(conditionXml: string, vars: Record<string, unknown>): boolean {
579
1010
  // conditionXml is an operator element like <gt>...</gt> (not wrapped in <expression>).
580
1011
  const doc = parseXml(conditionXml);
@@ -607,7 +1038,7 @@ export class ReferenceBackendAdapter implements BackendAdapter {
607
1038
  const out: string[] = [];
608
1039
  for (const part of assessment.testParts || []) {
609
1040
  for (const section of part.sections || []) {
610
- for (const item of section.items || []) {
1041
+ for (const item of section.assessmentItemRefs || []) {
611
1042
  out.push(item.identifier);
612
1043
  }
613
1044
  }