@pie-qti/assessment-player 0.1.4 → 0.1.6

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 (32) hide show
  1. package/README.md +19 -16
  2. package/dist/core/AssessmentPlayer.d.ts +21 -2
  3. package/dist/core/AssessmentPlayer.d.ts.map +1 -1
  4. package/dist/core/AssessmentPlayer.js +144 -15
  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/integration/ReferenceBackendAdapter.d.ts +28 -8
  9. package/dist/integration/ReferenceBackendAdapter.d.ts.map +1 -1
  10. package/dist/integration/ReferenceBackendAdapter.js +409 -51
  11. package/dist/integration/api-contract.d.ts +82 -2
  12. package/dist/integration/api-contract.d.ts.map +1 -1
  13. package/dist/integration/assessment-item-scorer.d.ts +12 -0
  14. package/dist/integration/assessment-item-scorer.d.ts.map +1 -0
  15. package/dist/integration/assessment-item-scorer.js +40 -0
  16. package/dist/integration/index.d.ts +1 -0
  17. package/dist/integration/index.d.ts.map +1 -1
  18. package/dist/integration/index.js +1 -0
  19. package/package.json +6 -6
  20. package/src/components/AccessibilityAnnouncer.svelte +13 -2
  21. package/src/components/AssessmentShell.svelte +13 -8
  22. package/src/components/AssessmentTimer.svelte +23 -0
  23. package/src/components/ItemRenderer.svelte +7 -3
  24. package/src/components/NavigationBar.svelte +2 -0
  25. package/src/components/SectionMenu.svelte +72 -5
  26. package/src/components/index.ts +1 -1
  27. package/src/core/AssessmentPlayer.ts +162 -17
  28. package/src/core/TimeManager.ts +20 -3
  29. package/src/integration/ReferenceBackendAdapter.ts +467 -54
  30. package/src/integration/api-contract.ts +84 -2
  31. package/src/integration/assessment-item-scorer.ts +53 -0
  32. package/src/integration/index.ts +5 -0
@@ -29,16 +29,18 @@
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,
40
43
  } from '@pie-qti/qti-processing';
41
- import { Player } from '@pie-qti/item-player';
42
44
  import { parse } from 'node-html-parser';
43
45
  import type {
44
46
  AssessmentSessionState,
@@ -54,10 +56,13 @@ import type {
54
56
  SaveAssessmentStateResponse,
55
57
  SecureAssessment,
56
58
  SecureItemRef,
59
+ SecureSection,
60
+ SecureTestPart,
57
61
  SessionId,
58
62
  SubmitResponsesRequest,
59
63
  SubmitResponsesResponse,
60
64
  } from './api-contract.js';
65
+ import { scoreAssessmentItem } from './assessment-item-scorer.js';
61
66
 
62
67
  /**
63
68
  * Storage key prefix for localStorage
@@ -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
  */
@@ -125,6 +142,22 @@ export class ReferenceBackendAdapter implements BackendAdapter {
125
142
  return this.registeredAssessments.get(assessmentId) ?? this.createDemoAssessment(assessmentId);
126
143
  }
127
144
 
145
+ private hasAnyResponse(responses: Record<string, unknown>): boolean {
146
+ for (const value of Object.values(responses)) {
147
+ if (value == null) continue;
148
+ if (Array.isArray(value)) {
149
+ if (value.length > 0) return true;
150
+ continue;
151
+ }
152
+ if (typeof value === 'string') {
153
+ if (value.trim().length > 0) return true;
154
+ continue;
155
+ }
156
+ return true;
157
+ }
158
+ return false;
159
+ }
160
+
128
161
  /**
129
162
  * Initialize a new assessment session
130
163
  */
@@ -212,7 +245,7 @@ export class ReferenceBackendAdapter implements BackendAdapter {
212
245
 
213
246
  // **SECURITY WARNING**: Client-side scoring is INSECURE
214
247
  // In production, this MUST be done server-side
215
- const result = this.scoreItem(itemXml, request.responses);
248
+ const result = scoreAssessmentItem({ itemXml, responses: request.responses });
216
249
 
217
250
  // Store responses and result
218
251
  session.state.itemResponses[request.itemIdentifier] = request.responses;
@@ -220,6 +253,17 @@ export class ReferenceBackendAdapter implements BackendAdapter {
220
253
  session.state.itemScores = {};
221
254
  }
222
255
  session.state.itemScores[request.itemIdentifier] = result;
256
+ const previousItemSession = session.state.itemSessionStates?.[request.itemIdentifier];
257
+ session.state.itemSessionStates = {
258
+ ...(session.state.itemSessionStates ?? {}),
259
+ [request.itemIdentifier]: {
260
+ itemIdentifier: request.itemIdentifier,
261
+ attemptCount: (previousItemSession?.attemptCount ?? 0) + 1,
262
+ isAnswered: this.hasAnyResponse(request.responses),
263
+ isSubmitted: true,
264
+ lastSubmissionTime: request.submittedAt,
265
+ },
266
+ };
223
267
 
224
268
  // Update timing
225
269
  if (request.timeSpent) {
@@ -235,15 +279,27 @@ export class ReferenceBackendAdapter implements BackendAdapter {
235
279
 
236
280
  const order = this.getItemOrder(session.assessment);
237
281
  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;
282
+ let nextItemIdentifier: string | undefined = idx >= 0 ? order[idx + 1] : undefined;
283
+
284
+ // QTI branchRule evaluation (backend-authoritative).
285
+ // Evaluate each rule in order; the first matching rule determines the next item.
286
+ // Special targets EXIT_TEST / EXIT_TESTPART / EXIT_SECTION are returned as-is for
287
+ // the client to interpret.
288
+ const itemRef = this.findItemRef(session.assessment, request.itemIdentifier);
289
+ if (itemRef?.branchRule && itemRef.branchRule.length > 0) {
290
+ const outcomeVars: Record<string, unknown> = {
291
+ ...result.outcomeValues,
292
+ SCORE: result.score,
293
+ };
294
+ nextItemIdentifier = undefined; // reset — branch rules take full control
295
+ for (const rule of itemRef.branchRule) {
296
+ const matches = rule.conditionXml
297
+ ? this.evaluateConditionXml(rule.conditionXml, outcomeVars)
298
+ : true; // unconditional branch
299
+ if (matches) {
300
+ nextItemIdentifier = rule.target;
301
+ break;
302
+ }
247
303
  }
248
304
  }
249
305
 
@@ -300,9 +356,13 @@ export class ReferenceBackendAdapter implements BackendAdapter {
300
356
 
301
357
  // Compute total score
302
358
  const itemScores = session.state.itemScores || {};
303
- const totalScore = Object.values(itemScores).reduce((sum, result) => sum + result.score, 0);
359
+ const fallbackTotal = Object.values(itemScores).reduce((sum, result) => sum + result.score, 0);
304
360
  const maxScore = Object.values(itemScores).reduce((sum, result) => sum + result.maxScore, 0);
305
361
 
362
+ // Execute test-level outcome processing if available
363
+ const outcomes = this.runOutcomeProcessing(session.assessment, itemScores);
364
+ const totalScore = outcomes !== null ? (outcomes['SCORE_TOTAL'] ?? outcomes['SCORE'] ?? fallbackTotal) as number : fallbackTotal;
365
+
306
366
  return {
307
367
  success: true,
308
368
  totalScore,
@@ -312,6 +372,94 @@ export class ReferenceBackendAdapter implements BackendAdapter {
312
372
  };
313
373
  }
314
374
 
375
+ /**
376
+ * Execute test-level outcome processing (T9/T1).
377
+ * Returns a map of outcome variable values, or null if no outcomeProcessing is defined.
378
+ */
379
+ private runOutcomeProcessing(
380
+ assessment: SecureAssessment,
381
+ itemScores: Record<string, AssessmentScoringResult>
382
+ ): Record<string, unknown> | null {
383
+ if (!assessment.outcomeProcessingXml) {
384
+ return null;
385
+ }
386
+
387
+ try {
388
+ // Build declaration map from outcomeDeclarations
389
+ const decls: DeclarationMap = {};
390
+ for (const d of assessment.outcomeDeclarations || []) {
391
+ const baseType = d.baseType as any;
392
+ const cardinality = d.cardinality as any;
393
+ let defaultQtiValue: QtiValue;
394
+ if (d.defaultValue !== undefined) {
395
+ defaultQtiValue = qtiValue(baseType, cardinality, d.defaultValue);
396
+ } else if (baseType === 'float' || baseType === 'integer') {
397
+ defaultQtiValue = qtiValue(baseType, 'single', 0);
398
+ } else {
399
+ defaultQtiValue = qtiNull();
400
+ }
401
+ decls[d.identifier] = {
402
+ identifier: d.identifier,
403
+ baseType,
404
+ cardinality,
405
+ defaultValue: defaultQtiValue,
406
+ value: { ...defaultQtiValue },
407
+ };
408
+ }
409
+
410
+ const ctx = new DeclarationContext(decls);
411
+ const ops = new OperatorRegistry();
412
+
413
+ // Build test items array for testVariables expression
414
+ const testItems = Object.entries(itemScores).map(([id, scoring]) => ({
415
+ identifier: id,
416
+ variables: {
417
+ SCORE: qtiValue('float', 'single', scoring.score),
418
+ // Add any other outcome values from the scoring result
419
+ ...Object.fromEntries(
420
+ Object.entries(scoring.outcomeValues || {}).map(([k, v]) => [
421
+ k,
422
+ typeof v === 'number'
423
+ ? qtiValue('float', 'single', v)
424
+ : qtiValue('string', 'single', String(v)),
425
+ ])
426
+ ),
427
+ },
428
+ }));
429
+
430
+ // Parse and execute outcome processing
431
+ const opEl = parseXml(assessment.outcomeProcessingXml).documentElement;
432
+ if (!opEl) return null;
433
+
434
+ const program = buildOutcomeProcessingAst(opEl, {
435
+ scope: 'test',
436
+ elementNameMapper: qtiElementNameMapper,
437
+ });
438
+ execProgram(
439
+ {
440
+ ctx,
441
+ ops,
442
+ rng: Math.random,
443
+ test: { items: testItems },
444
+ },
445
+ program
446
+ );
447
+
448
+ // Extract outcome values
449
+ const result: Record<string, unknown> = {};
450
+ for (const d of assessment.outcomeDeclarations || []) {
451
+ const v = ctx.getValue(d.identifier);
452
+ if (v.kind === 'value') {
453
+ result[d.identifier] = v.value;
454
+ }
455
+ }
456
+ return result;
457
+ } catch (err) {
458
+ console.warn('[ReferenceBackendAdapter] outcomeProcessing failed:', err);
459
+ return null;
460
+ }
461
+ }
462
+
315
463
  /**
316
464
  * Resume existing session (alias for initSession with resumeSessionId)
317
465
  */
@@ -410,49 +558,17 @@ export class ReferenceBackendAdapter implements BackendAdapter {
410
558
  return null;
411
559
  }
412
560
 
413
- /**
414
- * Score an item using the Player
415
- *
416
- * **SECURITY WARNING**: This is done CLIENT-SIDE for demo purposes only.
417
- * Production implementations MUST perform scoring SERVER-SIDE.
418
- */
419
- private scoreItem(itemXml: string, responses: Record<string, any>): AssessmentScoringResult {
420
- try {
421
- // Extract identifier from XML using regex (more reliable than DOM parsing)
422
- const identifierMatch = itemXml.match(/assessmentItem[^>]+identifier=["']([^"']+)["']/);
423
- const itemIdentifier = identifierMatch?.[1] || 'unknown';
424
-
425
- // Use a scorer-grade view of the item for accurate scoring.
426
- // NOTE: This reference adapter is intentionally insecure and runs client-side.
427
- // In production, scoring must happen server-side with secured item content.
428
- const player = new Player({
429
- itemXml,
430
- role: 'scorer',
431
- });
432
-
433
- // Set responses using setResponses (plural)
434
- player.setResponses(responses);
435
-
436
- // Process and score
437
- const result = player.processResponses();
438
-
439
- return {
440
- itemIdentifier,
441
- score: result.score,
442
- maxScore: result.maxScore,
443
- completed: result.completed,
444
- outcomeValues: result.outcomeValues,
445
- };
446
- } catch (error) {
447
- console.error('Scoring error:', error);
448
- return {
449
- itemIdentifier: 'unknown',
450
- score: 0,
451
- maxScore: 1,
452
- completed: false,
453
- outcomeValues: {},
454
- };
561
+ private findItemRef(assessment: SecureAssessment, itemIdentifier: string): SecureItemRef | null {
562
+ for (const part of assessment.testParts) {
563
+ for (const section of part.sections) {
564
+ for (const item of section.assessmentItemRefs) {
565
+ if (item.identifier === itemIdentifier) {
566
+ return item;
567
+ }
568
+ }
569
+ }
455
570
  }
571
+ return null;
456
572
  }
457
573
 
458
574
  /**
@@ -575,6 +691,303 @@ export class ReferenceBackendAdapter implements BackendAdapter {
575
691
  };
576
692
  }
577
693
 
694
+ // =========================================================================
695
+ // STATIC: QTI TEST XML PARSER
696
+ // =========================================================================
697
+
698
+ /**
699
+ * Parse a QTI assessmentTest XML string into a SecureAssessment structure.
700
+ *
701
+ * Handles:
702
+ * - S1: section-level itemSessionControl
703
+ * - S9: assessmentSectionRef href resolution (requires fileResolver)
704
+ * - T9/T1: outcomeDeclarations + outcomeProcessing extraction
705
+ *
706
+ * @param testXml - Raw QTI assessmentTest XML string
707
+ * @param options.role - Role to assign to items (default: 'candidate')
708
+ * @param options.itemXmlMap - Map of item identifier -> itemXml for pre-loaded items
709
+ * @param options.fileResolver - Async function to load external files by relative href
710
+ * @param options.baseUrl - Base URL for resolving relative hrefs
711
+ */
712
+ static async parseAssessmentTestXml(
713
+ testXml: string,
714
+ options: {
715
+ role?: SecureItemRef['role'];
716
+ itemXmlMap?: Record<string, string>;
717
+ fileResolver?: (href: string) => Promise<string>;
718
+ baseUrl?: string;
719
+ } = {}
720
+ ): Promise<SecureAssessment> {
721
+ const { role = 'candidate', itemXmlMap = {}, fileResolver, baseUrl } = options;
722
+ const doc = parseXml(testXml);
723
+ const root = doc.documentElement;
724
+ if (!root) throw new Error('Empty assessmentTest XML');
725
+
726
+ const getAttr = (el: Element, name: string): string | undefined => {
727
+ const direct = el.getAttribute(name);
728
+ if (direct !== null && direct !== '') return direct;
729
+ const mapped = el.getAttribute(name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`));
730
+ return mapped === null || mapped === '' ? undefined : mapped;
731
+ };
732
+
733
+ const childElements = (el: Element): Element[] =>
734
+ Array.from(el.childNodes).filter((n): n is Element => n.nodeType === 1);
735
+
736
+ const childrenByTag = (el: Element, tag: string): Element[] =>
737
+ childElements(el).filter((c) => toCanonicalQtiName(c.localName) === tag);
738
+
739
+ // Parse itemSessionControl element
740
+ const parseItemSessionControl = (
741
+ el: Element
742
+ ): SecureSection['itemSessionControl'] | undefined => {
743
+ const isc = childrenByTag(el, 'itemSessionControl')[0];
744
+ if (!isc) return undefined;
745
+ const boolAttr = (name: string): boolean | undefined => {
746
+ const v = getAttr(isc, name);
747
+ return v === undefined ? undefined : v !== 'false';
748
+ };
749
+ const intAttr = (name: string): number | undefined => {
750
+ const v = getAttr(isc, name);
751
+ return v === undefined ? undefined : parseInt(v, 10);
752
+ };
753
+ return {
754
+ maxAttempts: intAttr('maxAttempts'),
755
+ showFeedback: boolAttr('showFeedback') ?? boolAttr('show-feedback'),
756
+ allowReview: boolAttr('allowReview') ?? boolAttr('allow-review'),
757
+ showSolution: boolAttr('showSolution') ?? boolAttr('show-solution'),
758
+ allowComment: boolAttr('allowComment') ?? boolAttr('allow-comment'),
759
+ allowSkipping: boolAttr('allowSkipping') ?? boolAttr('allow-skipping'),
760
+ validateResponses: boolAttr('validateResponses') ?? boolAttr('validate-responses'),
761
+ };
762
+ };
763
+
764
+ // Parse a single assessmentSection element
765
+ const parseSection = (sectionEl: Element): SecureSection => {
766
+ const identifier = getAttr(sectionEl, 'identifier') ?? 'section';
767
+ const title = getAttr(sectionEl, 'title');
768
+ const visibleRaw = getAttr(sectionEl, 'visible');
769
+ const visible = visibleRaw === undefined ? true : visibleRaw !== 'false';
770
+
771
+ const itemSessionControl = parseItemSessionControl(sectionEl);
772
+
773
+ // rubricBlocks
774
+ const rubricBlockEls = childrenByTag(sectionEl, 'rubricBlock');
775
+ const rubricBlocks = rubricBlockEls.length > 0
776
+ ? rubricBlockEls.map((b, idx) => ({
777
+ identifier: getAttr(b, 'identifier') ?? `${identifier}-rubric-${idx + 1}`,
778
+ view: (getAttr(b, 'view') ?? 'candidate').split(/\s+/).filter(Boolean) as any[],
779
+ use: getAttr(b, 'use'),
780
+ content: serializeXml(b),
781
+ }))
782
+ : undefined;
783
+
784
+ // assessmentItemRefs
785
+ const itemRefEls = childrenByTag(sectionEl, 'assessmentItemRef');
786
+ const assessmentItemRefs: SecureItemRef[] = itemRefEls.map((ref) => {
787
+ const itemId = getAttr(ref, 'identifier') ?? 'item';
788
+ const href = getAttr(ref, 'href');
789
+ // Look up pre-loaded XML by identifier or href
790
+ const resolvedXml = itemXmlMap[itemId] ?? (href ? itemXmlMap[href] : undefined) ?? '';
791
+ const requiredRaw = getAttr(ref, 'required');
792
+ const required = requiredRaw === undefined ? undefined : requiredRaw !== 'false';
793
+ return {
794
+ identifier: itemId,
795
+ itemXml: resolvedXml,
796
+ role,
797
+ required,
798
+ };
799
+ });
800
+
801
+ return {
802
+ identifier,
803
+ title,
804
+ visible,
805
+ assessmentItemRefs,
806
+ rubricBlocks,
807
+ itemSessionControl,
808
+ };
809
+ };
810
+
811
+ // Resolve assessmentSectionRef: load and parse referenced section file
812
+ const resolveSectionRef = async (sectionRefEl: Element): Promise<SecureSection | null> => {
813
+ const href = getAttr(sectionRefEl, 'href');
814
+ if (!href) {
815
+ console.warn('[ReferenceBackendAdapter] assessmentSectionRef missing href, skipping');
816
+ return null;
817
+ }
818
+
819
+ if (!fileResolver) {
820
+ console.warn(
821
+ `[ReferenceBackendAdapter] assessmentSectionRef href="${href}" found but no fileResolver provided, skipping`
822
+ );
823
+ return null;
824
+ }
825
+
826
+ try {
827
+ const sectionXml = await fileResolver(href);
828
+ const secDoc = parseXml(sectionXml);
829
+ const secRoot = secDoc.documentElement;
830
+ if (!secRoot || toCanonicalQtiName(secRoot.localName) !== 'assessmentSection') {
831
+ console.warn(
832
+ `[ReferenceBackendAdapter] assessmentSectionRef href="${href}": root element is not <assessmentSection>, skipping`
833
+ );
834
+ return null;
835
+ }
836
+ return parseSection(secRoot);
837
+ } catch (err) {
838
+ console.warn(
839
+ `[ReferenceBackendAdapter] Failed to load assessmentSectionRef href="${href}":`,
840
+ err
841
+ );
842
+ return null;
843
+ }
844
+ };
845
+
846
+ // Parse testPart children (sections + sectionRefs)
847
+ const parseSectionsForTestPart = async (testPartEl: Element): Promise<SecureSection[]> => {
848
+ const sections: SecureSection[] = [];
849
+ for (const child of childElements(testPartEl)) {
850
+ if (toCanonicalQtiName(child.localName) === 'assessmentSection') {
851
+ sections.push(parseSection(child));
852
+ } else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {
853
+ const resolved = await resolveSectionRef(child);
854
+ if (resolved) sections.push(resolved);
855
+ }
856
+ }
857
+ return sections;
858
+ };
859
+
860
+ // Parse testPart-level itemSessionControl
861
+ const parseTestPartItemSessionControl = (
862
+ testPartEl: Element
863
+ ): SecureTestPart['itemSessionControl'] | undefined => {
864
+ const isc = childrenByTag(testPartEl, 'itemSessionControl')[0];
865
+ if (!isc) return undefined;
866
+ const boolAttr = (name: string): boolean | undefined => {
867
+ const v = getAttr(isc, name);
868
+ return v === undefined ? undefined : v !== 'false';
869
+ };
870
+ const intAttr = (name: string): number | undefined => {
871
+ const v = getAttr(isc, name);
872
+ return v === undefined ? undefined : parseInt(v, 10);
873
+ };
874
+ return {
875
+ maxAttempts: intAttr('maxAttempts'),
876
+ showFeedback: boolAttr('showFeedback') ?? boolAttr('show-feedback'),
877
+ allowReview: boolAttr('allowReview') ?? boolAttr('allow-review'),
878
+ showSolution: boolAttr('showSolution') ?? boolAttr('show-solution'),
879
+ allowComment: boolAttr('allowComment') ?? boolAttr('allow-comment'),
880
+ allowSkipping: boolAttr('allowSkipping') ?? boolAttr('allow-skipping'),
881
+ validateResponses: boolAttr('validateResponses') ?? boolAttr('validate-responses'),
882
+ };
883
+ };
884
+
885
+ // Extract outcomeDeclarations
886
+ const outcomeDeclarations = childrenByTag(root, 'outcomeDeclaration').map((d) => {
887
+ const identifier = getAttr(d, 'identifier') ?? 'OUTCOME';
888
+ const baseType = getAttr(d, 'baseType') ?? 'float';
889
+ const cardinality = getAttr(d, 'cardinality') ?? 'single';
890
+ // Parse defaultValue if present
891
+ const defaultValueEl = childrenByTag(d, 'defaultValue')[0];
892
+ let defaultValue: unknown = undefined;
893
+ if (defaultValueEl) {
894
+ const valueEl = childrenByTag(defaultValueEl, 'value')[0];
895
+ if (valueEl) {
896
+ const text = valueEl.textContent?.trim() ?? '0';
897
+ if (baseType === 'float' || baseType === 'integer') {
898
+ defaultValue = Number(text);
899
+ } else {
900
+ defaultValue = text;
901
+ }
902
+ }
903
+ }
904
+ return { identifier, baseType, cardinality, defaultValue };
905
+ });
906
+
907
+ // Extract outcomeProcessing XML
908
+ const outcomeProcessingEl = childrenByTag(root, 'outcomeProcessing')[0];
909
+ const outcomeProcessingXml = outcomeProcessingEl
910
+ ? serializeXml(outcomeProcessingEl)
911
+ : undefined;
912
+
913
+ // Extract timeLimits
914
+ const timeLimitsEl = childrenByTag(root, 'timeLimit')[0] ?? childrenByTag(root, 'timeLimits')[0];
915
+ const timeLimits = timeLimitsEl
916
+ ? {
917
+ maxTime: getAttr(timeLimitsEl, 'maxTime')
918
+ ? Number(getAttr(timeLimitsEl, 'maxTime'))
919
+ : undefined,
920
+ allowLateSubmission: getAttr(timeLimitsEl, 'allowLateSubmission') === 'true',
921
+ }
922
+ : undefined;
923
+
924
+ // Parse testParts
925
+ const testPartEls = childrenByTag(root, 'testPart');
926
+ const firstTestPart = testPartEls[0];
927
+
928
+ // Navigation/submission mode from first testPart (QTI 2.2 spec)
929
+ const navigationMode = (getAttr(firstTestPart ?? root, 'navigationMode') ?? 'nonlinear') as
930
+ | 'linear'
931
+ | 'nonlinear';
932
+ const submissionMode = (getAttr(firstTestPart ?? root, 'submissionMode') ?? 'simultaneous') as
933
+ | 'individual'
934
+ | 'simultaneous';
935
+
936
+ const testParts: SecureTestPart[] = [];
937
+ for (const tp of testPartEls) {
938
+ const tpIdentifier = getAttr(tp, 'identifier') ?? 'part-1';
939
+ const tpItemSessionControl = parseTestPartItemSessionControl(tp);
940
+ const tpRubricBlockEls = childrenByTag(tp, 'rubricBlock');
941
+ const tpRubricBlocks = tpRubricBlockEls.length > 0
942
+ ? tpRubricBlockEls.map((b, idx) => ({
943
+ identifier: getAttr(b, 'identifier') ?? `${tpIdentifier}-rubric-${idx + 1}`,
944
+ view: (getAttr(b, 'view') ?? 'candidate').split(/\s+/).filter(Boolean) as any[],
945
+ use: getAttr(b, 'use'),
946
+ content: serializeXml(b),
947
+ }))
948
+ : undefined;
949
+
950
+ const sections = await parseSectionsForTestPart(tp);
951
+ testParts.push({
952
+ identifier: tpIdentifier,
953
+ sections,
954
+ rubricBlocks: tpRubricBlocks,
955
+ itemSessionControl: tpItemSessionControl,
956
+ });
957
+ }
958
+
959
+ // If no testParts, try top-level sections
960
+ if (testParts.length === 0) {
961
+ const topSections: SecureSection[] = [];
962
+ for (const child of childElements(root)) {
963
+ if (toCanonicalQtiName(child.localName) === 'assessmentSection') {
964
+ topSections.push(parseSection(child));
965
+ } else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {
966
+ const resolved = await resolveSectionRef(child);
967
+ if (resolved) topSections.push(resolved);
968
+ }
969
+ }
970
+ if (topSections.length > 0) {
971
+ testParts.push({
972
+ identifier: 'part-1',
973
+ sections: topSections,
974
+ });
975
+ }
976
+ }
977
+
978
+ return {
979
+ identifier: getAttr(root, 'identifier') ?? 'assessment',
980
+ title: getAttr(root, 'title') ?? 'Assessment',
981
+ navigationMode,
982
+ submissionMode,
983
+ testParts,
984
+ timeLimits,
985
+ outcomeDeclarations: outcomeDeclarations.length > 0 ? outcomeDeclarations : undefined,
986
+ outcomeProcessingXml,
987
+ baseUrl,
988
+ };
989
+ }
990
+
578
991
  private evaluateConditionXml(conditionXml: string, vars: Record<string, unknown>): boolean {
579
992
  // conditionXml is an operator element like <gt>...</gt> (not wrapped in <expression>).
580
993
  const doc = parseXml(conditionXml);