@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
package/dist/index.d.ts CHANGED
@@ -2,5 +2,5 @@ export type { BackendAssessmentPlayerConfig } from './core/AssessmentPlayer.js';
2
2
  export type { NavigationMode } from './core/index.js';
3
3
  export { AssessmentPlayer, NavigationManager } from './core/index.js';
4
4
  export * from './integration/index.js';
5
- export type { AssessmentResults, ItemResult, NavigationState, QTIRole, QuestionRef } from './types/index.js';
5
+ export type { AssessmentResults, ItemRef, ItemResult, NavigationState, QTIRole } from './types/index.js';
6
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,YAAY,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAChF,YAAY,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAEtE,cAAc,wBAAwB,CAAC;AAEvC,YAAY,EAAE,iBAAiB,EAAE,UAAU,EAAE,eAAe,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,YAAY,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAChF,YAAY,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAEtE,cAAc,wBAAwB,CAAC;AAEvC,YAAY,EAAE,iBAAiB,EAAE,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC"}
@@ -26,7 +26,7 @@
26
26
  * - Validates all requests with authentication
27
27
  * - Filters sensitive data based on role
28
28
  */
29
- import type { BackendAdapter, FinalizeAssessmentRequest, FinalizeAssessmentResponse, InitSessionRequest, InitSessionResponse, QueryItemBankRequest, QueryItemBankResponse, SaveStateRequest, SaveStateResponse, SecureAssessment, SessionId, SubmitResponsesRequest, SubmitResponsesResponse } from './api-contract.js';
29
+ import type { BackendAdapter, FinalizeAssessmentRequest, FinalizeAssessmentResponse, InitSessionRequest, InitSessionResponse, QueryItemBankRequest, QueryItemBankResponse, SaveAssessmentStateRequest, SaveAssessmentStateResponse, SecureAssessment, SecureItemRef, SessionId, SubmitResponsesRequest, SubmitResponsesResponse } from './api-contract.js';
30
30
  /**
31
31
  * Reference Backend Adapter using localStorage
32
32
  *
@@ -61,11 +61,16 @@ export declare class ReferenceBackendAdapter implements BackendAdapter {
61
61
  /**
62
62
  * Save session state (for auto-save)
63
63
  */
64
- saveState(request: SaveStateRequest): Promise<SaveStateResponse>;
64
+ saveState(request: SaveAssessmentStateRequest): Promise<SaveAssessmentStateResponse>;
65
65
  /**
66
66
  * Finalize assessment and compute final scores
67
67
  */
68
68
  finalizeAssessment(request: FinalizeAssessmentRequest): Promise<FinalizeAssessmentResponse>;
69
+ /**
70
+ * Execute test-level outcome processing (T9/T1).
71
+ * Returns a map of outcome variable values, or null if no outcomeProcessing is defined.
72
+ */
73
+ private runOutcomeProcessing;
69
74
  /**
70
75
  * Resume existing session (alias for initSession with resumeSessionId)
71
76
  */
@@ -86,6 +91,7 @@ export declare class ReferenceBackendAdapter implements BackendAdapter {
86
91
  private loadSession;
87
92
  private saveSession;
88
93
  private findItemXml;
94
+ private findItemRef;
89
95
  /**
90
96
  * Score an item using the Player
91
97
  *
@@ -99,6 +105,26 @@ export declare class ReferenceBackendAdapter implements BackendAdapter {
99
105
  * In production, this would fetch from database
100
106
  */
101
107
  private createDemoAssessment;
108
+ /**
109
+ * Parse a QTI assessmentTest XML string into a SecureAssessment structure.
110
+ *
111
+ * Handles:
112
+ * - S1: section-level itemSessionControl
113
+ * - S9: assessmentSectionRef href resolution (requires fileResolver)
114
+ * - T9/T1: outcomeDeclarations + outcomeProcessing extraction
115
+ *
116
+ * @param testXml - Raw QTI assessmentTest XML string
117
+ * @param options.role - Role to assign to items (default: 'candidate')
118
+ * @param options.itemXmlMap - Map of item identifier -> itemXml for pre-loaded items
119
+ * @param options.fileResolver - Async function to load external files by relative href
120
+ * @param options.baseUrl - Base URL for resolving relative hrefs
121
+ */
122
+ static parseAssessmentTestXml(testXml: string, options?: {
123
+ role?: SecureItemRef['role'];
124
+ itemXmlMap?: Record<string, string>;
125
+ fileResolver?: (href: string) => Promise<string>;
126
+ baseUrl?: string;
127
+ }): Promise<SecureAssessment>;
102
128
  private evaluateConditionXml;
103
129
  private getItemOrder;
104
130
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"ReferenceBackendAdapter.d.ts","sourceRoot":"","sources":["../../src/integration/ReferenceBackendAdapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAeH,OAAO,KAAK,EACX,cAAc,EACd,yBAAyB,EACzB,0BAA0B,EAC1B,kBAAkB,EAClB,mBAAmB,EACnB,oBAAoB,EACpB,qBAAqB,EACrB,gBAAgB,EAChB,iBAAiB,EAEjB,gBAAgB,EAEhB,SAAS,EAET,sBAAsB,EACtB,uBAAuB,EACvB,MAAM,mBAAmB,CAAC;AAsC3B;;;;;;;;;;;GAWG;AACH,qBAAa,uBAAwB,YAAW,cAAc;IAC7D,OAAO,CAAC,qBAAqB,CAA4C;IAEzE;;;;;;OAMG;IACI,kBAAkB,CAAC,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,gBAAgB;IAI5E,OAAO,CAAC,aAAa;IAIrB;;OAEG;IACG,WAAW,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAsD5E;;OAEG;IACG,eAAe,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAAC,uBAAuB,CAAC;IAsExF;;OAEG;IACG,SAAS,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAmBtE;;OAEG;IACG,kBAAkB,CACvB,OAAO,EAAE,yBAAyB,GAChC,OAAO,CAAC,0BAA0B,CAAC;IA8BtC;;OAEG;IACG,aAAa,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAQvE;;;;;;;;;;OAUG;IACG,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,qBAAqB,CAAC;IAuClF,OAAO,CAAC,iBAAiB;IAIzB,OAAO,CAAC,WAAW;IAWnB,OAAO,CAAC,WAAW;IASnB,OAAO,CAAC,WAAW;IAanB;;;;;OAKG;IACH,OAAO,CAAC,SAAS;IAuCjB;;;;OAIG;IACH,OAAO,CAAC,oBAAoB;IAmH5B,OAAO,CAAC,oBAAoB;IA4B5B,OAAO,CAAC,YAAY;IAgBpB;;OAEG;IACH,OAAO,CAAC,eAAe;IAWvB;;OAEG;IACH,OAAO,CAAC,aAAa;IAqBrB;;OAEG;IACH,OAAO,CAAC,aAAa;IAQrB;;;;;OAKG;YACW,kBAAkB;IAkLhC;;OAEG;IACH,OAAO,CAAC,KAAK;CAGb"}
1
+ {"version":3,"file":"ReferenceBackendAdapter.d.ts","sourceRoot":"","sources":["../../src/integration/ReferenceBackendAdapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAkBH,OAAO,KAAK,EAGX,cAAc,EACd,yBAAyB,EACzB,0BAA0B,EAC1B,kBAAkB,EAClB,mBAAmB,EACnB,oBAAoB,EACpB,qBAAqB,EACrB,0BAA0B,EAC1B,2BAA2B,EAC3B,gBAAgB,EAChB,aAAa,EAGb,SAAS,EACT,sBAAsB,EACtB,uBAAuB,EACvB,MAAM,mBAAmB,CAAC;AAkD3B;;;;;;;;;;;GAWG;AACH,qBAAa,uBAAwB,YAAW,cAAc;IAC7D,OAAO,CAAC,qBAAqB,CAA4C;IAEzE;;;;;;OAMG;IACI,kBAAkB,CAAC,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,gBAAgB;IAI5E,OAAO,CAAC,aAAa;IAIrB;;OAEG;IACG,WAAW,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAsD5E;;OAEG;IACG,eAAe,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAAC,uBAAuB,CAAC;IAkFxF;;OAEG;IACG,SAAS,CAAC,OAAO,EAAE,0BAA0B,GAAG,OAAO,CAAC,2BAA2B,CAAC;IAmB1F;;OAEG;IACG,kBAAkB,CACvB,OAAO,EAAE,yBAAyB,GAChC,OAAO,CAAC,0BAA0B,CAAC;IAkCtC;;;OAGG;IACH,OAAO,CAAC,oBAAoB;IAoF5B;;OAEG;IACG,aAAa,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAQvE;;;;;;;;;;OAUG;IACG,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,qBAAqB,CAAC;IAuClF,OAAO,CAAC,iBAAiB;IAIzB,OAAO,CAAC,WAAW;IAWnB,OAAO,CAAC,WAAW;IASnB,OAAO,CAAC,WAAW;IAanB,OAAO,CAAC,WAAW;IAanB;;;;;OAKG;IACH,OAAO,CAAC,SAAS;IAuCjB;;;;OAIG;IACH,OAAO,CAAC,oBAAoB;IAuH5B;;;;;;;;;;;;;OAaG;WACU,sBAAsB,CAClC,OAAO,EAAE,MAAM,EACf,OAAO,GAAE;QACR,IAAI,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;QAC7B,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACpC,YAAY,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;QACjD,OAAO,CAAC,EAAE,MAAM,CAAC;KACZ,GACJ,OAAO,CAAC,gBAAgB,CAAC;IA+Q5B,OAAO,CAAC,oBAAoB;IA4B5B,OAAO,CAAC,YAAY;IAgBpB;;OAEG;IACH,OAAO,CAAC,eAAe;IAWvB;;OAEG;IACH,OAAO,CAAC,aAAa;IAqBrB;;OAEG;IACH,OAAO,CAAC,aAAa;IAQrB;;;;;OAKG;YACW,kBAAkB;IAkLhC;;OAEG;IACH,OAAO,CAAC,KAAK;CAGb"}
@@ -26,7 +26,7 @@
26
26
  * - Validates all requests with authentication
27
27
  * - Filters sensitive data based on role
28
28
  */
29
- import { buildExpression, DeclarationContext, evalExpr, OperatorRegistry, parseXml, qtiNull, qtiValue, } from '@pie-qti/qti-processing';
29
+ import { buildExpression, buildOutcomeProcessingAst, DeclarationContext, evalExpr, execProgram, OperatorRegistry, parseXml, serializeXml, qtiNull, qtiValue, } from '@pie-qti/qti-processing';
30
30
  import { Player } from '@pie-qti/item-player';
31
31
  /**
32
32
  * Storage key prefix for localStorage
@@ -36,6 +36,16 @@ const STORAGE_PREFIX = 'qti_session_';
36
36
  * Cache key for item bank queries
37
37
  */
38
38
  const BANK_CACHE_PREFIX = 'qti_bank_cache_';
39
+ function toCanonicalQtiName(name) {
40
+ const withoutPrefix = (name ?? '').replace(/^qti-/, '');
41
+ return withoutPrefix.replace(/-([a-z])/g, (_, char) => char.toUpperCase());
42
+ }
43
+ const qtiElementNameMapper = {
44
+ version: 'qti2x-or-qti3',
45
+ toCanonical: (elementName) => toCanonicalQtiName(elementName).toLowerCase(),
46
+ toNative: (canonicalName) => canonicalName,
47
+ isValidElementName: () => true,
48
+ };
39
49
  /**
40
50
  * Reference Backend Adapter using localStorage
41
51
  *
@@ -90,7 +100,7 @@ export class ReferenceBackendAdapter {
90
100
  // For reference implementation, we'll use demo data
91
101
  const assessment = this.getAssessment(request.assessmentId);
92
102
  const state = {
93
- currentItemIdentifier: assessment.testParts[0].sections[0].items[0].identifier,
103
+ currentItemIdentifier: assessment.testParts[0].sections[0].assessmentItemRefs[0].identifier,
94
104
  visitedItems: [],
95
105
  itemResponses: {},
96
106
  itemScores: {},
@@ -161,14 +171,25 @@ export class ReferenceBackendAdapter {
161
171
  const order = this.getItemOrder(session.assessment);
162
172
  const idx = order.indexOf(request.itemIdentifier);
163
173
  let nextItemIdentifier = idx >= 0 ? order[idx + 1] : undefined;
164
- // Demo branching using qti-processing (backend-authoritative). If SCORE > 0, go to item2.
165
- if (request.itemIdentifier === 'item1') {
166
- const condXml = `<gt><variable identifier="SCORE" /><baseValue baseType="float">0</baseValue></gt>`;
167
- if (this.evaluateConditionXml(condXml, { SCORE: result.score })) {
168
- nextItemIdentifier = 'item2';
169
- }
170
- else {
171
- nextItemIdentifier = undefined;
174
+ // QTI branchRule evaluation (backend-authoritative).
175
+ // Evaluate each rule in order; the first matching rule determines the next item.
176
+ // Special targets EXIT_TEST / EXIT_TESTPART / EXIT_SECTION are returned as-is for
177
+ // the client to interpret.
178
+ const itemRef = this.findItemRef(session.assessment, request.itemIdentifier);
179
+ if (itemRef?.branchRule && itemRef.branchRule.length > 0) {
180
+ const outcomeVars = {
181
+ ...result.outcomeValues,
182
+ SCORE: result.score,
183
+ };
184
+ nextItemIdentifier = undefined; // reset — branch rules take full control
185
+ for (const rule of itemRef.branchRule) {
186
+ const matches = rule.conditionXml
187
+ ? this.evaluateConditionXml(rule.conditionXml, outcomeVars)
188
+ : true; // unconditional branch
189
+ if (matches) {
190
+ nextItemIdentifier = rule.target;
191
+ break;
192
+ }
172
193
  }
173
194
  }
174
195
  return {
@@ -216,8 +237,11 @@ export class ReferenceBackendAdapter {
216
237
  this.saveSession(session);
217
238
  // Compute total score
218
239
  const itemScores = session.state.itemScores || {};
219
- const totalScore = Object.values(itemScores).reduce((sum, result) => sum + result.score, 0);
240
+ const fallbackTotal = Object.values(itemScores).reduce((sum, result) => sum + result.score, 0);
220
241
  const maxScore = Object.values(itemScores).reduce((sum, result) => sum + result.maxScore, 0);
242
+ // Execute test-level outcome processing if available
243
+ const outcomes = this.runOutcomeProcessing(session.assessment, itemScores);
244
+ const totalScore = outcomes !== null ? (outcomes['SCORE_TOTAL'] ?? outcomes['SCORE'] ?? fallbackTotal) : fallbackTotal;
221
245
  return {
222
246
  success: true,
223
247
  totalScore,
@@ -226,6 +250,83 @@ export class ReferenceBackendAdapter {
226
250
  finalizedAt: Date.now(),
227
251
  };
228
252
  }
253
+ /**
254
+ * Execute test-level outcome processing (T9/T1).
255
+ * Returns a map of outcome variable values, or null if no outcomeProcessing is defined.
256
+ */
257
+ runOutcomeProcessing(assessment, itemScores) {
258
+ if (!assessment.outcomeProcessingXml) {
259
+ return null;
260
+ }
261
+ try {
262
+ // Build declaration map from outcomeDeclarations
263
+ const decls = {};
264
+ for (const d of assessment.outcomeDeclarations || []) {
265
+ const baseType = d.baseType;
266
+ const cardinality = d.cardinality;
267
+ let defaultQtiValue;
268
+ if (d.defaultValue !== undefined) {
269
+ defaultQtiValue = qtiValue(baseType, cardinality, d.defaultValue);
270
+ }
271
+ else if (baseType === 'float' || baseType === 'integer') {
272
+ defaultQtiValue = qtiValue(baseType, 'single', 0);
273
+ }
274
+ else {
275
+ defaultQtiValue = qtiNull();
276
+ }
277
+ decls[d.identifier] = {
278
+ identifier: d.identifier,
279
+ baseType,
280
+ cardinality,
281
+ defaultValue: defaultQtiValue,
282
+ value: { ...defaultQtiValue },
283
+ };
284
+ }
285
+ const ctx = new DeclarationContext(decls);
286
+ const ops = new OperatorRegistry();
287
+ // Build test items array for testVariables expression
288
+ const testItems = Object.entries(itemScores).map(([id, scoring]) => ({
289
+ identifier: id,
290
+ variables: {
291
+ SCORE: qtiValue('float', 'single', scoring.score),
292
+ // Add any other outcome values from the scoring result
293
+ ...Object.fromEntries(Object.entries(scoring.outcomeValues || {}).map(([k, v]) => [
294
+ k,
295
+ typeof v === 'number'
296
+ ? qtiValue('float', 'single', v)
297
+ : qtiValue('string', 'single', String(v)),
298
+ ])),
299
+ },
300
+ }));
301
+ // Parse and execute outcome processing
302
+ const opEl = parseXml(assessment.outcomeProcessingXml).documentElement;
303
+ if (!opEl)
304
+ return null;
305
+ const program = buildOutcomeProcessingAst(opEl, {
306
+ scope: 'test',
307
+ elementNameMapper: qtiElementNameMapper,
308
+ });
309
+ execProgram({
310
+ ctx,
311
+ ops,
312
+ rng: Math.random,
313
+ test: { items: testItems },
314
+ }, program);
315
+ // Extract outcome values
316
+ const result = {};
317
+ for (const d of assessment.outcomeDeclarations || []) {
318
+ const v = ctx.getValue(d.identifier);
319
+ if (v.kind === 'value') {
320
+ result[d.identifier] = v.value;
321
+ }
322
+ }
323
+ return result;
324
+ }
325
+ catch (err) {
326
+ console.warn('[ReferenceBackendAdapter] outcomeProcessing failed:', err);
327
+ return null;
328
+ }
329
+ }
229
330
  /**
230
331
  * Resume existing session (alias for initSession with resumeSessionId)
231
332
  */
@@ -306,7 +407,7 @@ export class ReferenceBackendAdapter {
306
407
  findItemXml(assessment, itemIdentifier) {
307
408
  for (const part of assessment.testParts) {
308
409
  for (const section of part.sections) {
309
- for (const item of section.items) {
410
+ for (const item of section.assessmentItemRefs) {
310
411
  if (item.identifier === itemIdentifier) {
311
412
  return item.itemXml;
312
413
  }
@@ -315,6 +416,18 @@ export class ReferenceBackendAdapter {
315
416
  }
316
417
  return null;
317
418
  }
419
+ findItemRef(assessment, itemIdentifier) {
420
+ for (const part of assessment.testParts) {
421
+ for (const section of part.sections) {
422
+ for (const item of section.assessmentItemRefs) {
423
+ if (item.identifier === itemIdentifier) {
424
+ return item;
425
+ }
426
+ }
427
+ }
428
+ }
429
+ return null;
430
+ }
318
431
  /**
319
432
  * Score an item using the Player
320
433
  *
@@ -372,7 +485,7 @@ export class ReferenceBackendAdapter {
372
485
  testParts: [
373
486
  {
374
487
  identifier: 'part1',
375
- rubrics: [],
488
+ rubricBlocks: [],
376
489
  itemSessionControl: {
377
490
  maxAttempts: 1,
378
491
  showFeedback: true,
@@ -387,7 +500,7 @@ export class ReferenceBackendAdapter {
387
500
  identifier: 'section1',
388
501
  title: 'Section 1',
389
502
  visible: true,
390
- items: [
503
+ assessmentItemRefs: [
391
504
  {
392
505
  identifier: 'item1',
393
506
  role: 'candidate',
@@ -475,6 +588,263 @@ export class ReferenceBackendAdapter {
475
588
  ],
476
589
  };
477
590
  }
591
+ // =========================================================================
592
+ // STATIC: QTI TEST XML PARSER
593
+ // =========================================================================
594
+ /**
595
+ * Parse a QTI assessmentTest XML string into a SecureAssessment structure.
596
+ *
597
+ * Handles:
598
+ * - S1: section-level itemSessionControl
599
+ * - S9: assessmentSectionRef href resolution (requires fileResolver)
600
+ * - T9/T1: outcomeDeclarations + outcomeProcessing extraction
601
+ *
602
+ * @param testXml - Raw QTI assessmentTest XML string
603
+ * @param options.role - Role to assign to items (default: 'candidate')
604
+ * @param options.itemXmlMap - Map of item identifier -> itemXml for pre-loaded items
605
+ * @param options.fileResolver - Async function to load external files by relative href
606
+ * @param options.baseUrl - Base URL for resolving relative hrefs
607
+ */
608
+ static async parseAssessmentTestXml(testXml, options = {}) {
609
+ const { role = 'candidate', itemXmlMap = {}, fileResolver, baseUrl } = options;
610
+ const doc = parseXml(testXml);
611
+ const root = doc.documentElement;
612
+ if (!root)
613
+ throw new Error('Empty assessmentTest XML');
614
+ const getAttr = (el, name) => {
615
+ const direct = el.getAttribute(name);
616
+ if (direct !== null && direct !== '')
617
+ return direct;
618
+ const mapped = el.getAttribute(name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`));
619
+ return mapped === null || mapped === '' ? undefined : mapped;
620
+ };
621
+ const childElements = (el) => Array.from(el.childNodes).filter((n) => n.nodeType === 1);
622
+ const childrenByTag = (el, tag) => childElements(el).filter((c) => toCanonicalQtiName(c.localName) === tag);
623
+ // Parse itemSessionControl element
624
+ const parseItemSessionControl = (el) => {
625
+ const isc = childrenByTag(el, 'itemSessionControl')[0];
626
+ if (!isc)
627
+ return undefined;
628
+ const boolAttr = (name) => {
629
+ const v = getAttr(isc, name);
630
+ return v === undefined ? undefined : v !== 'false';
631
+ };
632
+ const intAttr = (name) => {
633
+ const v = getAttr(isc, name);
634
+ return v === undefined ? undefined : parseInt(v, 10);
635
+ };
636
+ return {
637
+ maxAttempts: intAttr('maxAttempts'),
638
+ showFeedback: boolAttr('showFeedback') ?? boolAttr('show-feedback'),
639
+ allowReview: boolAttr('allowReview') ?? boolAttr('allow-review'),
640
+ showSolution: boolAttr('showSolution') ?? boolAttr('show-solution'),
641
+ allowComment: boolAttr('allowComment') ?? boolAttr('allow-comment'),
642
+ allowSkipping: boolAttr('allowSkipping') ?? boolAttr('allow-skipping'),
643
+ validateResponses: boolAttr('validateResponses') ?? boolAttr('validate-responses'),
644
+ };
645
+ };
646
+ // Parse a single assessmentSection element
647
+ const parseSection = (sectionEl) => {
648
+ const identifier = getAttr(sectionEl, 'identifier') ?? 'section';
649
+ const title = getAttr(sectionEl, 'title');
650
+ const visibleRaw = getAttr(sectionEl, 'visible');
651
+ const visible = visibleRaw === undefined ? true : visibleRaw !== 'false';
652
+ const itemSessionControl = parseItemSessionControl(sectionEl);
653
+ // rubricBlocks
654
+ const rubricBlockEls = childrenByTag(sectionEl, 'rubricBlock');
655
+ const rubricBlocks = rubricBlockEls.length > 0
656
+ ? rubricBlockEls.map((b, idx) => ({
657
+ identifier: getAttr(b, 'identifier') ?? `${identifier}-rubric-${idx + 1}`,
658
+ view: (getAttr(b, 'view') ?? 'candidate').split(/\s+/).filter(Boolean),
659
+ use: getAttr(b, 'use'),
660
+ content: serializeXml(b),
661
+ }))
662
+ : undefined;
663
+ // assessmentItemRefs
664
+ const itemRefEls = childrenByTag(sectionEl, 'assessmentItemRef');
665
+ const assessmentItemRefs = itemRefEls.map((ref) => {
666
+ const itemId = getAttr(ref, 'identifier') ?? 'item';
667
+ const href = getAttr(ref, 'href');
668
+ // Look up pre-loaded XML by identifier or href
669
+ const resolvedXml = itemXmlMap[itemId] ?? (href ? itemXmlMap[href] : undefined) ?? '';
670
+ const requiredRaw = getAttr(ref, 'required');
671
+ const required = requiredRaw === undefined ? undefined : requiredRaw !== 'false';
672
+ return {
673
+ identifier: itemId,
674
+ itemXml: resolvedXml,
675
+ role,
676
+ required,
677
+ };
678
+ });
679
+ return {
680
+ identifier,
681
+ title,
682
+ visible,
683
+ assessmentItemRefs,
684
+ rubricBlocks,
685
+ itemSessionControl,
686
+ };
687
+ };
688
+ // Resolve assessmentSectionRef: load and parse referenced section file
689
+ const resolveSectionRef = async (sectionRefEl) => {
690
+ const href = getAttr(sectionRefEl, 'href');
691
+ if (!href) {
692
+ console.warn('[ReferenceBackendAdapter] assessmentSectionRef missing href, skipping');
693
+ return null;
694
+ }
695
+ if (!fileResolver) {
696
+ console.warn(`[ReferenceBackendAdapter] assessmentSectionRef href="${href}" found but no fileResolver provided, skipping`);
697
+ return null;
698
+ }
699
+ try {
700
+ const sectionXml = await fileResolver(href);
701
+ const secDoc = parseXml(sectionXml);
702
+ const secRoot = secDoc.documentElement;
703
+ if (!secRoot || toCanonicalQtiName(secRoot.localName) !== 'assessmentSection') {
704
+ console.warn(`[ReferenceBackendAdapter] assessmentSectionRef href="${href}": root element is not <assessmentSection>, skipping`);
705
+ return null;
706
+ }
707
+ return parseSection(secRoot);
708
+ }
709
+ catch (err) {
710
+ console.warn(`[ReferenceBackendAdapter] Failed to load assessmentSectionRef href="${href}":`, err);
711
+ return null;
712
+ }
713
+ };
714
+ // Parse testPart children (sections + sectionRefs)
715
+ const parseSectionsForTestPart = async (testPartEl) => {
716
+ const sections = [];
717
+ for (const child of childElements(testPartEl)) {
718
+ if (toCanonicalQtiName(child.localName) === 'assessmentSection') {
719
+ sections.push(parseSection(child));
720
+ }
721
+ else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {
722
+ const resolved = await resolveSectionRef(child);
723
+ if (resolved)
724
+ sections.push(resolved);
725
+ }
726
+ }
727
+ return sections;
728
+ };
729
+ // Parse testPart-level itemSessionControl
730
+ const parseTestPartItemSessionControl = (testPartEl) => {
731
+ const isc = childrenByTag(testPartEl, 'itemSessionControl')[0];
732
+ if (!isc)
733
+ return undefined;
734
+ const boolAttr = (name) => {
735
+ const v = getAttr(isc, name);
736
+ return v === undefined ? undefined : v !== 'false';
737
+ };
738
+ const intAttr = (name) => {
739
+ const v = getAttr(isc, name);
740
+ return v === undefined ? undefined : parseInt(v, 10);
741
+ };
742
+ return {
743
+ maxAttempts: intAttr('maxAttempts'),
744
+ showFeedback: boolAttr('showFeedback') ?? boolAttr('show-feedback'),
745
+ allowReview: boolAttr('allowReview') ?? boolAttr('allow-review'),
746
+ showSolution: boolAttr('showSolution') ?? boolAttr('show-solution'),
747
+ allowComment: boolAttr('allowComment') ?? boolAttr('allow-comment'),
748
+ allowSkipping: boolAttr('allowSkipping') ?? boolAttr('allow-skipping'),
749
+ validateResponses: boolAttr('validateResponses') ?? boolAttr('validate-responses'),
750
+ };
751
+ };
752
+ // Extract outcomeDeclarations
753
+ const outcomeDeclarations = childrenByTag(root, 'outcomeDeclaration').map((d) => {
754
+ const identifier = getAttr(d, 'identifier') ?? 'OUTCOME';
755
+ const baseType = getAttr(d, 'baseType') ?? 'float';
756
+ const cardinality = getAttr(d, 'cardinality') ?? 'single';
757
+ // Parse defaultValue if present
758
+ const defaultValueEl = childrenByTag(d, 'defaultValue')[0];
759
+ let defaultValue = undefined;
760
+ if (defaultValueEl) {
761
+ const valueEl = childrenByTag(defaultValueEl, 'value')[0];
762
+ if (valueEl) {
763
+ const text = valueEl.textContent?.trim() ?? '0';
764
+ if (baseType === 'float' || baseType === 'integer') {
765
+ defaultValue = Number(text);
766
+ }
767
+ else {
768
+ defaultValue = text;
769
+ }
770
+ }
771
+ }
772
+ return { identifier, baseType, cardinality, defaultValue };
773
+ });
774
+ // Extract outcomeProcessing XML
775
+ const outcomeProcessingEl = childrenByTag(root, 'outcomeProcessing')[0];
776
+ const outcomeProcessingXml = outcomeProcessingEl
777
+ ? serializeXml(outcomeProcessingEl)
778
+ : undefined;
779
+ // Extract timeLimits
780
+ const timeLimitsEl = childrenByTag(root, 'timeLimit')[0] ?? childrenByTag(root, 'timeLimits')[0];
781
+ const timeLimits = timeLimitsEl
782
+ ? {
783
+ maxTime: getAttr(timeLimitsEl, 'maxTime')
784
+ ? Number(getAttr(timeLimitsEl, 'maxTime'))
785
+ : undefined,
786
+ allowLateSubmission: getAttr(timeLimitsEl, 'allowLateSubmission') === 'true',
787
+ }
788
+ : undefined;
789
+ // Parse testParts
790
+ const testPartEls = childrenByTag(root, 'testPart');
791
+ const firstTestPart = testPartEls[0];
792
+ // Navigation/submission mode from first testPart (QTI 2.2 spec)
793
+ const navigationMode = (getAttr(firstTestPart ?? root, 'navigationMode') ?? 'nonlinear');
794
+ const submissionMode = (getAttr(firstTestPart ?? root, 'submissionMode') ?? 'simultaneous');
795
+ const testParts = [];
796
+ for (const tp of testPartEls) {
797
+ const tpIdentifier = getAttr(tp, 'identifier') ?? 'part-1';
798
+ const tpItemSessionControl = parseTestPartItemSessionControl(tp);
799
+ const tpRubricBlockEls = childrenByTag(tp, 'rubricBlock');
800
+ const tpRubricBlocks = tpRubricBlockEls.length > 0
801
+ ? tpRubricBlockEls.map((b, idx) => ({
802
+ identifier: getAttr(b, 'identifier') ?? `${tpIdentifier}-rubric-${idx + 1}`,
803
+ view: (getAttr(b, 'view') ?? 'candidate').split(/\s+/).filter(Boolean),
804
+ use: getAttr(b, 'use'),
805
+ content: serializeXml(b),
806
+ }))
807
+ : undefined;
808
+ const sections = await parseSectionsForTestPart(tp);
809
+ testParts.push({
810
+ identifier: tpIdentifier,
811
+ sections,
812
+ rubricBlocks: tpRubricBlocks,
813
+ itemSessionControl: tpItemSessionControl,
814
+ });
815
+ }
816
+ // If no testParts, try top-level sections
817
+ if (testParts.length === 0) {
818
+ const topSections = [];
819
+ for (const child of childElements(root)) {
820
+ if (toCanonicalQtiName(child.localName) === 'assessmentSection') {
821
+ topSections.push(parseSection(child));
822
+ }
823
+ else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {
824
+ const resolved = await resolveSectionRef(child);
825
+ if (resolved)
826
+ topSections.push(resolved);
827
+ }
828
+ }
829
+ if (topSections.length > 0) {
830
+ testParts.push({
831
+ identifier: 'part-1',
832
+ sections: topSections,
833
+ });
834
+ }
835
+ }
836
+ return {
837
+ identifier: getAttr(root, 'identifier') ?? 'assessment',
838
+ title: getAttr(root, 'title') ?? 'Assessment',
839
+ navigationMode,
840
+ submissionMode,
841
+ testParts,
842
+ timeLimits,
843
+ outcomeDeclarations: outcomeDeclarations.length > 0 ? outcomeDeclarations : undefined,
844
+ outcomeProcessingXml,
845
+ baseUrl,
846
+ };
847
+ }
478
848
  evaluateConditionXml(conditionXml, vars) {
479
849
  // conditionXml is an operator element like <gt>...</gt> (not wrapped in <expression>).
480
850
  const doc = parseXml(conditionXml);
@@ -508,7 +878,7 @@ export class ReferenceBackendAdapter {
508
878
  const out = [];
509
879
  for (const part of assessment.testParts || []) {
510
880
  for (const section of part.sections || []) {
511
- for (const item of section.items || []) {
881
+ for (const item of section.assessmentItemRefs || []) {
512
882
  out.push(item.identifier);
513
883
  }
514
884
  }