@pie-qti/assessment-player 1.0.0-beta.4 → 1.0.0-beta.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 (134) hide show
  1. package/README.md +28 -7
  2. package/dist/components/createPlayerConnection.svelte.d.ts +90 -0
  3. package/dist/components/createPlayerConnection.svelte.js +151 -0
  4. package/dist/components/createPlayerConnection.svelte.js.map +1 -0
  5. package/dist/components/displaySettings.svelte.d.ts +23 -0
  6. package/dist/components/displaySettings.svelte.js +40 -0
  7. package/dist/components/displaySettings.svelte.js.map +1 -0
  8. package/dist/components/srOnly.d.ts +29 -0
  9. package/dist/components/srOnly.js +55 -0
  10. package/dist/components/srOnly.js.map +1 -0
  11. package/dist/components/submitDialogAction.d.ts +25 -0
  12. package/dist/components/submitDialogAction.js +89 -0
  13. package/dist/components/submitDialogAction.js.map +1 -0
  14. package/dist/core/AssessmentPlayer.d.ts +1102 -53
  15. package/dist/core/AssessmentPlayer.js +2835 -460
  16. package/dist/core/AssessmentPlayer.js.map +1 -1
  17. package/dist/core/AssessmentSessionCoordinator.d.ts +76 -7
  18. package/dist/core/AssessmentSessionCoordinator.js +185 -10
  19. package/dist/core/AssessmentSessionCoordinator.js.map +1 -1
  20. package/dist/core/AutosaveManager.d.ts +104 -0
  21. package/dist/core/AutosaveManager.js +181 -0
  22. package/dist/core/AutosaveManager.js.map +1 -0
  23. package/dist/core/ItemSessionController.d.ts +17 -26
  24. package/dist/core/ItemSessionController.js +33 -73
  25. package/dist/core/ItemSessionController.js.map +1 -1
  26. package/dist/core/NavigationManager.d.ts +18 -50
  27. package/dist/core/NavigationManager.js +21 -83
  28. package/dist/core/NavigationManager.js.map +1 -1
  29. package/dist/core/TimeManager.d.ts +62 -16
  30. package/dist/core/TimeManager.js +148 -57
  31. package/dist/core/TimeManager.js.map +1 -1
  32. package/dist/core/autosave.d.ts +44 -0
  33. package/dist/core/autosave.js +46 -0
  34. package/dist/core/autosave.js.map +1 -0
  35. package/dist/core/deliveryStructure.d.ts +54 -0
  36. package/dist/core/deliveryStructure.js +72 -0
  37. package/dist/core/deliveryStructure.js.map +1 -0
  38. package/dist/core/errors.d.ts +116 -0
  39. package/dist/core/errors.js +77 -0
  40. package/dist/core/errors.js.map +1 -0
  41. package/dist/core/exitBoundaries.d.ts +64 -0
  42. package/dist/core/exitBoundaries.js +98 -0
  43. package/dist/core/exitBoundaries.js.map +1 -0
  44. package/dist/core/feedback.d.ts +46 -0
  45. package/dist/core/feedback.js +47 -0
  46. package/dist/core/feedback.js.map +1 -0
  47. package/dist/core/formatTime.d.ts +8 -0
  48. package/dist/core/formatTime.js +20 -0
  49. package/dist/core/formatTime.js.map +1 -0
  50. package/dist/core/index.d.ts +7 -4
  51. package/dist/core/index.js +4 -1
  52. package/dist/core/index.js.map +1 -1
  53. package/dist/core/navigationPolicy.d.ts +42 -0
  54. package/dist/core/navigationPolicy.js +62 -0
  55. package/dist/core/navigationPolicy.js.map +1 -0
  56. package/dist/core/pause.d.ts +58 -0
  57. package/dist/core/pause.js +101 -0
  58. package/dist/core/pause.js.map +1 -0
  59. package/dist/core/playerEvents.d.ts +51 -0
  60. package/dist/core/playerEvents.js +66 -0
  61. package/dist/core/playerEvents.js.map +1 -0
  62. package/dist/core/reviewState.d.ts +81 -0
  63. package/dist/core/reviewState.js +113 -0
  64. package/dist/core/reviewState.js.map +1 -0
  65. package/dist/core/reviewViews.d.ts +43 -0
  66. package/dist/core/reviewViews.js +88 -0
  67. package/dist/core/reviewViews.js.map +1 -0
  68. package/dist/core/scopeLocks.d.ts +36 -0
  69. package/dist/core/scopeLocks.js +78 -0
  70. package/dist/core/scopeLocks.js.map +1 -0
  71. package/dist/core/sessionRecords.d.ts +31 -0
  72. package/dist/core/sessionRecords.js +74 -0
  73. package/dist/core/sessionRecords.js.map +1 -0
  74. package/dist/core/submissionPolicy.d.ts +62 -0
  75. package/dist/core/submissionPolicy.js +67 -0
  76. package/dist/core/submissionPolicy.js.map +1 -0
  77. package/dist/core/templateDefaults.d.ts +26 -0
  78. package/dist/core/templateDefaults.js +53 -0
  79. package/dist/core/templateDefaults.js.map +1 -0
  80. package/dist/core/testStructure.d.ts +118 -3
  81. package/dist/core/testStructure.js +252 -6
  82. package/dist/core/testStructure.js.map +1 -1
  83. package/dist/core/timePolicy.d.ts +40 -0
  84. package/dist/core/timePolicy.js +106 -0
  85. package/dist/core/timePolicy.js.map +1 -0
  86. package/dist/index.d.ts +7 -4
  87. package/dist/index.js +5 -1
  88. package/dist/index.js.map +1 -1
  89. package/dist/integration/ReferenceBackendAdapter.d.ts +64 -101
  90. package/dist/integration/ReferenceBackendAdapter.js +216 -1035
  91. package/dist/integration/ReferenceBackendAdapter.js.map +1 -1
  92. package/dist/integration/api-contract.d.ts +179 -17
  93. package/dist/integration/api-contract.js.map +1 -1
  94. package/dist/integration/assessment-item-scorer.d.ts +56 -5
  95. package/dist/integration/assessment-item-scorer.js +116 -13
  96. package/dist/integration/assessment-item-scorer.js.map +1 -1
  97. package/dist/integration/index.d.ts +2 -2
  98. package/dist/integration/index.js +1 -1
  99. package/dist/integration/index.js.map +1 -1
  100. package/dist/integration/qti-test-parser.d.ts +44 -0
  101. package/dist/integration/qti-test-parser.js +529 -0
  102. package/dist/integration/qti-test-parser.js.map +1 -0
  103. package/dist/integration/session-store.d.ts +54 -0
  104. package/dist/integration/session-store.js +75 -0
  105. package/dist/integration/session-store.js.map +1 -0
  106. package/dist/integration/test-navigation.d.ts +23 -0
  107. package/dist/integration/test-navigation.js +32 -0
  108. package/dist/integration/test-navigation.js.map +1 -0
  109. package/dist/integration/toSectionComposition.js +8 -1
  110. package/dist/integration/toSectionComposition.js.map +1 -1
  111. package/dist/reporting/index.d.ts +3 -0
  112. package/dist/reporting/index.js +3 -0
  113. package/dist/reporting/index.js.map +1 -0
  114. package/dist/reporting/inferBaseType.d.ts +13 -0
  115. package/dist/reporting/inferBaseType.js +26 -0
  116. package/dist/reporting/inferBaseType.js.map +1 -0
  117. package/dist/reporting/serializeAssessmentResult.d.ts +27 -0
  118. package/dist/reporting/serializeAssessmentResult.js +377 -0
  119. package/dist/reporting/serializeAssessmentResult.js.map +1 -0
  120. package/dist/reporting/toAssessmentResultXml.d.ts +39 -0
  121. package/dist/reporting/toAssessmentResultXml.js +304 -0
  122. package/dist/reporting/toAssessmentResultXml.js.map +1 -0
  123. package/dist/reporting/types.d.ts +85 -0
  124. package/dist/reporting/types.js +8 -0
  125. package/dist/reporting/types.js.map +1 -0
  126. package/dist/types/index.d.ts +96 -9
  127. package/dist/types/index.js.map +1 -1
  128. package/package.json +21 -15
  129. package/dist/core/StatePersistenceManager.d.ts +0 -125
  130. package/dist/core/StatePersistenceManager.js +0 -268
  131. package/dist/core/StatePersistenceManager.js.map +0 -1
  132. package/dist/utils/PerformanceMonitor.d.ts +0 -114
  133. package/dist/utils/PerformanceMonitor.js +0 -172
  134. package/dist/utils/PerformanceMonitor.js.map +0 -1
@@ -25,25 +25,45 @@
25
25
  * - Performs scoring server-side
26
26
  * - Validates all requests with authentication
27
27
  * - Filters sensitive data based on role
28
+ *
29
+ * ## Persistence failure semantics
30
+ *
31
+ * A localStorage write that does not land (quota exceeded, private-mode eviction) means
32
+ * the operation did not complete, and every backend method reports it honestly:
33
+ * `saveState` returns `success: false` (the autosave engine shows `failed`, retries with
34
+ * backoff and reports onError), `submitResponses` returns `success: false` (the player
35
+ * restores the pre-submit state and throws its coded `submitFailed` — accepting the
36
+ * submission anyway would silently lose the answer on the next resume), and
37
+ * `finalizeAssessment` returns `success: false` (the `finalized` flag never persisted, so
38
+ * reporting a completion would resurrect the test on resume; the player throws its coded
39
+ * `finalizeFailed` and the test stays open for a retry). The initial session write and
40
+ * the outcome-processing-error bookkeeping are the only best-effort writes: their response
41
+ * shapes carry no failure, and a lost init write merely leaves a fresh session without a
42
+ * resumable draft — which the very next save reports through the paths above.
28
43
  */
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';
33
- /**
34
- * Storage key prefix for localStorage
35
- */
36
- const STORAGE_PREFIX = 'qti_session_';
37
- /**
38
- * Cache key for item bank queries
39
- */
40
- const BANK_CACHE_PREFIX = 'qti_bank_cache_';
41
- class AssessmentSectionReferenceLimitError extends Error {
42
- }
44
+ import { buildOutcomeProcessingAst, DeclarationContext, execProgram, parseXml, qtiValue, } from '@pie-qti/qti-processing';
45
+ import { addItemVariableDeclarations, addScopeDurationDeclarations, applyVariableMappings, deliveredItems, drawAssessment, qtiElementNameMapper, resolveItemSessionControl, testOutcomeDeclarations, } from '../core/testStructure.js';
46
+ import { parseAssessmentTestXml } from './qti-test-parser.js';
47
+ import { firstEligibleItem, getItemRefsInOrder, navigationDeclarations, nextItemIdentifier, } from './test-navigation.js';
48
+ import { generateSessionId, findLatestSession, loadSession, saveSession, } from './session-store.js';
49
+ import { AssessmentItemScoringError, defaultItemTestState, scoreAssessmentItemForTest, } from './assessment-item-scorer.js';
43
50
  export class ReferenceBackendAdapter {
44
51
  constructor(options = {}) {
52
+ /**
53
+ * The adapter persists drafts: sessions live in localStorage and `saveState` writes
54
+ * the candidate's snapshot into them, so shell autosave is ON by default.
55
+ */
56
+ this.canSaveState = true;
57
+ /**
58
+ * The adapter scores from the candidate's serialized item session: a templated item is
59
+ * scored against the instance the candidate saw (never a fresh template draw), and an
60
+ * adaptive item's accumulated outcomes are taken as submitted. The player therefore
61
+ * always sends it (reference mode); a templated or adaptive item without one is refused.
62
+ */
63
+ this.requiresItemSession = true;
45
64
  this.registeredAssessments = new Map();
46
65
  this.rng = options.rng ?? Math.random;
66
+ this.stringComparison = options.stringComparison ? Object.freeze({ ...options.stringComparison }) : undefined;
47
67
  }
48
68
  /**
49
69
  * Register/override a client-provided assessment structure for a given assessmentId.
@@ -58,42 +78,36 @@ export class ReferenceBackendAdapter {
58
78
  getAssessment(assessmentId) {
59
79
  return this.registeredAssessments.get(assessmentId) ?? this.createDemoAssessment(assessmentId);
60
80
  }
61
- hasAnyResponse(responses) {
62
- for (const value of Object.values(responses)) {
63
- if (value == null)
64
- continue;
65
- if (Array.isArray(value)) {
66
- if (value.length > 0)
67
- return true;
68
- continue;
69
- }
70
- if (typeof value === 'string') {
71
- if (value.trim().length > 0)
72
- return true;
73
- continue;
74
- }
75
- return true;
76
- }
77
- return false;
78
- }
79
81
  /**
80
82
  * Initialize a new assessment session
81
83
  */
82
84
  async initSession(request) {
83
85
  // Check if resuming existing session
84
86
  if (request.resumeSessionId) {
85
- const stored = this.loadSession(request.resumeSessionId);
87
+ const stored = loadSession(request.resumeSessionId);
86
88
  if (stored) {
89
+ // A finalized session has no resumable draft: restore terminal (the
90
+ // stored final totals, no restoredState), so hosts show the
91
+ // already-submitted view instead of delivery whose every submit fails.
92
+ if (stored.finalized) {
93
+ return {
94
+ sessionId: stored.sessionId,
95
+ assessment: stored.assessment,
96
+ finalized: true,
97
+ finalResults: this.storedFinalResults(stored),
98
+ outcomes: this.currentOutcomes(stored).outcomes,
99
+ };
100
+ }
87
101
  return {
88
102
  sessionId: stored.sessionId,
89
103
  assessment: stored.assessment,
90
104
  restoredState: stored.state,
91
- outcomes: this.currentOutcomes(stored),
105
+ outcomes: this.currentOutcomes(stored).outcomes,
92
106
  };
93
107
  }
94
108
  }
95
109
  // Create new session
96
- const sessionId = this.generateSessionId(request.assessmentId, request.candidateId);
110
+ const sessionId = generateSessionId(request.assessmentId, request.candidateId);
97
111
  // In a real backend, you would:
98
112
  // 1. Fetch assessment from database
99
113
  // 2. Filter QTI XML based on role
@@ -102,7 +116,7 @@ export class ReferenceBackendAdapter {
102
116
  // For reference implementation, we'll use demo data. Selection and ordering are drawn once
103
117
  // here; the stored draw is what a resume returns.
104
118
  const assessment = drawAssessment(this.getAssessment(request.assessmentId), this.rng);
105
- const firstItemIdentifier = this.firstEligibleItem(assessment, deliveredItems(assessment), 0, undefined, testOutcomeDeclarations(assessment)) ?? '';
119
+ const firstItemIdentifier = firstEligibleItem(deliveredItems(assessment), 0, undefined, testOutcomeDeclarations(assessment), this.rng) ?? '';
106
120
  const state = {
107
121
  currentItemIdentifier: firstItemIdentifier,
108
122
  visitedItems: [],
@@ -124,7 +138,7 @@ export class ReferenceBackendAdapter {
124
138
  createdAt: Date.now(),
125
139
  finalized: false,
126
140
  };
127
- this.saveSession(session);
141
+ saveSession(session);
128
142
  return {
129
143
  sessionId,
130
144
  assessment,
@@ -135,7 +149,7 @@ export class ReferenceBackendAdapter {
135
149
  * Submit responses and get scoring result
136
150
  */
137
151
  async submitResponses(request) {
138
- const session = this.loadSession(request.sessionId);
152
+ const session = loadSession(request.sessionId);
139
153
  if (!session) {
140
154
  return {
141
155
  success: false,
@@ -153,10 +167,24 @@ export class ReferenceBackendAdapter {
153
167
  const effectiveAssessmentLimitSeconds = request.timing?.scope === 'assessment' && request.timing.limitSeconds !== undefined
154
168
  ? request.timing.limitSeconds
155
169
  : assessmentLimit?.maxTime;
170
+ // The candidate's own test clock (gates and pauses excluded) when the client
171
+ // reports it; otherwise the session wall clock, which a production backend owns.
172
+ const assessmentElapsedSeconds = request.timing?.assessmentElapsedMs !== undefined
173
+ ? request.timing.assessmentElapsedMs / 1000
174
+ : (receivedAt - session.createdAt) / 1000;
156
175
  const assessmentAllowsLate = assessmentLimit?.allowLateSubmission ?? request.timing?.allowLateSubmission;
157
- if (effectiveAssessmentLimitSeconds !== undefined &&
176
+ // A `time-expired` submission is the terminal collection a hard limit triggers:
177
+ // the window closed with the expiry, and the pending responses must be accepted.
178
+ // A `proctor` collection is the administrative end of the test, accepted alike, and
179
+ // so is an `unreachable` one (a question the candidate can no longer reach,
180
+ // collected as it stands at the end of the test).
181
+ const timeExpiredCollection = request.timing?.submissionReason === 'time-expired' ||
182
+ request.timing?.submissionReason === 'proctor' ||
183
+ request.timing?.submissionReason === 'unreachable';
184
+ if (!timeExpiredCollection &&
185
+ effectiveAssessmentLimitSeconds !== undefined &&
158
186
  assessmentAllowsLate !== true &&
159
- receivedAt - session.createdAt > effectiveAssessmentLimitSeconds * 1000) {
187
+ assessmentElapsedSeconds > effectiveAssessmentLimitSeconds) {
160
188
  return {
161
189
  success: false,
162
190
  error: 'Assessment time limit expired',
@@ -164,7 +192,7 @@ export class ReferenceBackendAdapter {
164
192
  }
165
193
  const evidenceExpired = request.timing?.limitSeconds !== undefined &&
166
194
  request.timing.elapsedMs >= request.timing.limitSeconds * 1000;
167
- if (evidenceExpired && request.timing?.allowLateSubmission !== true) {
195
+ if (!timeExpiredCollection && evidenceExpired && request.timing?.allowLateSubmission !== true) {
168
196
  return {
169
197
  success: false,
170
198
  error: 'Time limit expired',
@@ -182,7 +210,10 @@ export class ReferenceBackendAdapter {
182
210
  const itemXml = current.item.itemXml;
183
211
  const control = resolveItemSessionControl(current.testPart, current.sections, current.item);
184
212
  const previousItemSession = session.state.itemSessionStates?.[request.itemIdentifier];
185
- if (control.maxAttempts > 0 && (previousItemSession?.attemptCount ?? 0) >= control.maxAttempts) {
213
+ // A QTI endAttempt countAttempt=false submission (a hint request) runs response processing
214
+ // without consuming an attempt, so the attempt limit does not apply to it.
215
+ const countAttempt = request.countAttempt ?? true;
216
+ if (countAttempt && control.maxAttempts > 0 && (previousItemSession?.attemptCount ?? 0) >= control.maxAttempts) {
186
217
  return {
187
218
  success: false,
188
219
  error: 'Maximum attempts reached',
@@ -196,22 +227,35 @@ export class ReferenceBackendAdapter {
196
227
  }
197
228
  // **SECURITY WARNING**: Client-side scoring is INSECURE
198
229
  // In production, this MUST be done server-side
199
- const { result, testState } = scoreAssessmentItemForTest({
200
- itemXml,
201
- responses: request.responses,
202
- itemSession: request.itemSession,
203
- });
204
- // Store responses and result
205
- session.state.itemResponses[request.itemIdentifier] = request.responses;
206
- if (!session.state.itemScores) {
207
- session.state.itemScores = {};
230
+ // A templated (or adaptive) item is scored from the candidate's item session only —
231
+ // an item ref's templateDefault also sets template values the XML alone does not show.
232
+ let scored;
233
+ try {
234
+ scored = scoreAssessmentItemForTest({
235
+ itemXml,
236
+ responses: request.responses,
237
+ itemSession: request.itemSession,
238
+ requireItemSession: (current.item.templateDefaults?.length ?? 0) > 0,
239
+ ...(this.stringComparison ? { stringComparison: this.stringComparison } : {}),
240
+ });
208
241
  }
209
- session.state.itemScores[request.itemIdentifier] = result;
210
- if (testState) {
211
- session.itemTestStates = { ...(session.itemTestStates ?? {}), [request.itemIdentifier]: testState };
242
+ catch (error) {
243
+ if (error instanceof AssessmentItemScoringError) {
244
+ return { success: false, error: `${error.code}: ${error.message}` };
245
+ }
246
+ throw error;
212
247
  }
213
- else if (session.itemTestStates) {
214
- delete session.itemTestStates[request.itemIdentifier];
248
+ const { result, testState } = scored;
249
+ // Store responses and result. An uncounted submission (countAttempt=false) persists the
250
+ // response but records no score, presented state, or attempt: response processing ran,
251
+ // and the candidate continues on the item.
252
+ session.state.itemResponses[request.itemIdentifier] = request.responses;
253
+ if (countAttempt) {
254
+ if (!session.state.itemScores) {
255
+ session.state.itemScores = {};
256
+ }
257
+ session.state.itemScores[request.itemIdentifier] = result;
258
+ session.itemTestStates = { ...session.itemTestStates, [request.itemIdentifier]: testState };
215
259
  }
216
260
  if (request.itemSession) {
217
261
  session.state.itemSessions = {
@@ -226,10 +270,12 @@ export class ReferenceBackendAdapter {
226
270
  ...(session.state.itemSessionStates ?? {}),
227
271
  [request.itemIdentifier]: {
228
272
  itemIdentifier: request.itemIdentifier,
229
- attemptCount: (previousItemSession?.attemptCount ?? 0) + 1,
230
- isAnswered: this.hasAnyResponse(request.responses),
231
- isSubmitted: true,
232
- lastSubmissionTime: request.submittedAt,
273
+ attemptCount: (previousItemSession?.attemptCount ?? 0) + (countAttempt ? 1 : 0),
274
+ // QTI: a response still equal to its declared default is no response (the
275
+ // numberResponded test), so a default-valued untouched item is not answered.
276
+ isAnswered: testState.responded === true,
277
+ isSubmitted: countAttempt ? true : (previousItemSession?.isSubmitted ?? false),
278
+ lastSubmissionTime: countAttempt ? request.submittedAt : previousItemSession?.lastSubmissionTime,
233
279
  },
234
280
  };
235
281
  // Update timing
@@ -237,30 +283,42 @@ export class ReferenceBackendAdapter {
237
283
  session.state.timing.itemTimes[request.itemIdentifier] = request.timeSpent;
238
284
  }
239
285
  // Add to visited items if not already there
240
- if (!session.state.visitedItems.includes(request.itemIdentifier)) {
286
+ if (countAttempt && !session.state.visitedItems.includes(request.itemIdentifier)) {
241
287
  session.state.visitedItems.push(request.itemIdentifier);
242
288
  }
243
- this.saveSession(session);
244
- const outcomes = this.currentOutcomes(session);
245
- const currentVariables = testState?.variables ?? this.scoredItemVariables(result);
246
- const decls = this.navigationDeclarations(session, outcomes, {
289
+ // The responses were scored and applied in memory, but if the write did not land
290
+ // they exist nowhere: accepting the submission anyway would silently lose the
291
+ // candidate's answer on the next resume. The failure is propagated honestly
292
+ // (`success: false`): the player restores the pre-submit session state, throws its
293
+ // coded `submitFailed`, and the candidate can retry — the in-memory session object
294
+ // above is discarded with the failed attempt.
295
+ if (!saveSession(session)) {
296
+ return {
297
+ success: false,
298
+ error: 'Failed to persist the submitted response',
299
+ };
300
+ }
301
+ const { outcomes, error } = this.currentOutcomes(session);
302
+ const currentVariables = testState.variables;
303
+ const decls = navigationDeclarations(session, outcomes, {
247
304
  ...applyVariableMappings(currentVariables, current.item.variableMappings),
248
305
  ...(currentVariables.SCORE ? {} : { SCORE: qtiValue('float', 'single', result.score) }),
249
306
  });
250
- const nextItemIdentifier = this.nextItemIdentifier(session.assessment, delivered, index, decls);
307
+ const nextId = nextItemIdentifier(delivered, index, decls, this.rng);
251
308
  return {
252
309
  success: true,
253
310
  result,
254
- nextItemIdentifier,
311
+ nextItemIdentifier: nextId,
255
312
  updatedState: session.state,
256
313
  outcomes,
314
+ ...(error ? { outcomeProcessingError: error } : {}),
257
315
  };
258
316
  }
259
317
  /**
260
318
  * Save session state (for auto-save)
261
319
  */
262
320
  async saveState(request) {
263
- const session = this.loadSession(request.sessionId);
321
+ const session = loadSession(request.sessionId);
264
322
  if (!session) {
265
323
  return {
266
324
  success: false,
@@ -269,7 +327,15 @@ export class ReferenceBackendAdapter {
269
327
  }
270
328
  // Update state
271
329
  session.state = request.state;
272
- this.saveSession(session);
330
+ // A write that did not land is not a successful save: the autosave engine
331
+ // (`success: false`) shows `failed`, retries with backoff and reports onError —
332
+ // reporting success here would silently drop the draft.
333
+ if (!saveSession(session)) {
334
+ return {
335
+ success: false,
336
+ savedAt: Date.now(),
337
+ };
338
+ }
273
339
  return {
274
340
  success: true,
275
341
  savedAt: Date.now(),
@@ -279,7 +345,7 @@ export class ReferenceBackendAdapter {
279
345
  * Finalize assessment and compute final scores
280
346
  */
281
347
  async finalizeAssessment(request) {
282
- const session = this.loadSession(request.sessionId);
348
+ const session = loadSession(request.sessionId);
283
349
  if (!session) {
284
350
  return {
285
351
  success: false,
@@ -289,15 +355,27 @@ export class ReferenceBackendAdapter {
289
355
  finalizedAt: Date.now(),
290
356
  };
291
357
  }
292
- // Mark as finalized
358
+ // Mark as finalized. If the write fails, the session on disk stays unfinalized —
359
+ // a resume would reopen the test. Reporting `finalized` to the player anyway would
360
+ // end delivery on a state nothing stored, so the failure is propagated: the player
361
+ // throws its coded `finalizeFailed` and the test stays open for a retry.
293
362
  session.finalized = true;
294
- this.saveSession(session);
363
+ if (!saveSession(session)) {
364
+ return {
365
+ success: false,
366
+ totalScore: 0,
367
+ maxScore: 0,
368
+ itemScores: {},
369
+ finalizedAt: Date.now(),
370
+ };
371
+ }
295
372
  // Compute total score
296
373
  const itemScores = session.state.itemScores || {};
297
374
  const fallbackTotal = Object.values(itemScores).reduce((sum, result) => sum + result.score, 0);
298
375
  const maxScore = Object.values(itemScores).reduce((sum, result) => sum + result.maxScore, 0);
299
376
  // Execute test-level outcome processing if available
300
- const outcomes = this.runOutcomeProcessing(session);
377
+ const run = this.runOutcomeProcessing(session);
378
+ const outcomes = run.outcomes;
301
379
  const scoreOutcome = outcomes?.SCORE_TOTAL ?? outcomes?.SCORE;
302
380
  const totalScore = typeof scoreOutcome === 'number' ? scoreOutcome : fallbackTotal;
303
381
  return {
@@ -306,41 +384,62 @@ export class ReferenceBackendAdapter {
306
384
  maxScore,
307
385
  itemScores,
308
386
  outcomes: outcomes ?? undefined,
387
+ ...(run.error ? { outcomeProcessingError: run.error } : {}),
309
388
  finalizedAt: Date.now(),
310
389
  };
311
390
  }
312
- /** Outcome values after the submissions so far; undefined before the first submission. */
391
+ /**
392
+ * Outcome values and any outcome-processing failure after the submissions so far; both
393
+ * undefined before the first submission.
394
+ */
313
395
  currentOutcomes(session) {
314
396
  if (Object.keys(session.state.itemScores ?? {}).length === 0)
315
- return undefined;
316
- return this.runOutcomeProcessing(session) ?? undefined;
397
+ return {};
398
+ const run = this.runOutcomeProcessing(session);
399
+ return { outcomes: run.outcomes ?? undefined, error: run.error };
400
+ }
401
+ /**
402
+ * The stored final totals of a finalized session, for the terminal init response:
403
+ * the same fallback totals `finalizeAssessment` reports (per-item scores included so
404
+ * a shell can render its completion summary).
405
+ */
406
+ storedFinalResults(session) {
407
+ const itemScores = session.state.itemScores ?? {};
408
+ const results = Object.values(itemScores);
409
+ return {
410
+ totalScore: results.reduce((sum, result) => sum + result.score, 0),
411
+ maxScore: results.reduce((sum, result) => sum + result.maxScore, 0),
412
+ itemScores,
413
+ };
317
414
  }
318
415
  /**
319
416
  * Execute test-level outcome processing (T9/T1).
320
- * Returns every declared outcome's value (null for NULL), or null if no outcomeProcessing is
321
- * defined.
417
+ *
418
+ * Returns every declared outcome's value (null for NULL), or null when no
419
+ * outcomeProcessing is defined. A failure is reported as a typed
420
+ * `OutcomeProcessingError` (persisted on the session) — it never fails delivery and
421
+ * candidate responses always stay persisted, but it must surface to the host instead
422
+ * of SCORE/testFeedback silently never computing.
322
423
  */
323
424
  runOutcomeProcessing(session) {
324
425
  const { assessment } = session;
325
426
  if (!assessment.outcomeProcessingXml) {
326
- return null;
427
+ return { outcomes: null };
327
428
  }
328
429
  try {
329
430
  const testItems = this.buildTestItems(session);
330
- const decls = addItemVariableDeclarations(testOutcomeDeclarations(assessment), Object.fromEntries(testItems.map((item) => [item.identifier, item.variables])));
431
+ const decls = addScopeDurationDeclarations(addItemVariableDeclarations(testOutcomeDeclarations(assessment), Object.fromEntries(testItems.map((item) => [item.identifier, item.variables]))), assessment, session.state.timing);
331
432
  const ctx = new DeclarationContext(decls);
332
- const ops = new OperatorRegistry();
333
433
  // Parse and execute outcome processing
334
434
  const opEl = parseXml(assessment.outcomeProcessingXml).documentElement;
335
435
  if (!opEl)
336
- return null;
436
+ return { outcomes: null };
337
437
  const program = buildOutcomeProcessingAst(opEl, {
338
438
  scope: 'test',
339
439
  elementNameMapper: qtiElementNameMapper,
340
440
  });
341
441
  execProgram({
342
442
  ctx,
343
- ops,
344
443
  rng: this.rng,
345
444
  test: { items: testItems },
346
445
  }, program);
@@ -349,11 +448,21 @@ export class ReferenceBackendAdapter {
349
448
  const v = ctx.getValue(d.identifier);
350
449
  result[d.identifier] = v.kind === 'value' ? v.value : null;
351
450
  }
352
- return result;
451
+ if (session.outcomeProcessingError) {
452
+ delete session.outcomeProcessingError;
453
+ saveSession(session);
454
+ }
455
+ return { outcomes: result };
353
456
  }
354
457
  catch (err) {
355
458
  console.warn('[ReferenceBackendAdapter] outcomeProcessing failed:', err);
356
- return null;
459
+ const error = {
460
+ code: 'OUTCOME_PROCESSING_FAILED',
461
+ message: err instanceof Error ? err.message : String(err),
462
+ };
463
+ session.outcomeProcessingError = error;
464
+ saveSession(session);
465
+ return { outcomes: null, error };
357
466
  }
358
467
  }
359
468
  /**
@@ -366,6 +475,14 @@ export class ReferenceBackendAdapter {
366
475
  resumeSessionId: sessionId,
367
476
  });
368
477
  }
478
+ /**
479
+ * The identifier of this adapter's most recent unfinalized session for an
480
+ * assessment and candidate, or null. Hosts pass it as `initSession.resumeSessionId`
481
+ * to resume the stored draft — the reference resume path after a refresh.
482
+ */
483
+ latestSessionId(assessmentId, candidateId) {
484
+ return findLatestSession(assessmentId, candidateId)?.sessionId ?? null;
485
+ }
369
486
  /**
370
487
  * Query item bank for random item selection
371
488
  *
@@ -377,78 +494,20 @@ export class ReferenceBackendAdapter {
377
494
  * @param request - Item bank query request
378
495
  * @returns Selected items from bank
379
496
  */
380
- async queryItemBank(request) {
381
- const { sessionId, bankId, count, withReplacement, filters } = request;
382
- // Validate session exists
383
- const session = this.loadSession(sessionId);
384
- if (!session) {
385
- throw new Error(`Session not found: ${sessionId}`);
386
- }
387
- // Check cache first
388
- const cacheKey = this.getBankCacheKey(sessionId, bankId, count, withReplacement, filters);
389
- const cached = this.loadBankCache(cacheKey);
390
- if (cached) {
391
- return {
392
- items: cached.items,
393
- selectedAt: cached.timestamp,
394
- };
395
- }
396
- // Simulate network call with retry logic
397
- const items = await this.fetchItemsFromBank(bankId, count, withReplacement, filters);
398
- // Cache the result (5 minute TTL)
399
- this.saveBankCache(cacheKey, {
400
- items,
401
- timestamp: Date.now(),
402
- ttl: 5 * 60 * 1000, // 5 minutes
403
- });
404
- return {
405
- items,
406
- selectedAt: Date.now(),
407
- };
408
- }
409
497
  // =========================================================================
410
498
  // PRIVATE HELPERS
411
499
  // =========================================================================
412
- generateSessionId(assessmentId, candidateId) {
413
- return `${assessmentId}:${candidateId}:${Date.now()}`;
414
- }
415
- loadSession(sessionId) {
416
- try {
417
- const key = STORAGE_PREFIX + sessionId;
418
- const data = localStorage.getItem(key);
419
- if (!data)
420
- return null;
421
- return JSON.parse(data);
422
- }
423
- catch {
424
- return null;
425
- }
426
- }
427
- saveSession(session) {
428
- try {
429
- const key = STORAGE_PREFIX + session.sessionId;
430
- localStorage.setItem(key, JSON.stringify(session));
431
- }
432
- catch (error) {
433
- console.error('Failed to save session to localStorage:', error);
434
- }
435
- }
436
- /**
437
- * Create demo assessment for testing
438
- *
439
- * In production, this would fetch from database
440
- */
441
500
  createDemoAssessment(assessmentId) {
442
501
  // This is a minimal demo assessment
443
502
  // In production, load from database and filter based on role
444
503
  return {
445
504
  identifier: assessmentId,
446
505
  title: 'Demo Assessment',
447
- navigationMode: 'nonlinear',
448
- submissionMode: 'simultaneous',
449
506
  testParts: [
450
507
  {
451
508
  identifier: 'part1',
509
+ navigationMode: 'nonlinear',
510
+ submissionMode: 'simultaneous',
452
511
  rubricBlocks: [],
453
512
  itemSessionControl: {
454
513
  maxAttempts: 1,
@@ -556,914 +615,36 @@ export class ReferenceBackendAdapter {
556
615
  // STATIC: QTI TEST XML PARSER
557
616
  // =========================================================================
558
617
  /**
559
- * Parse a QTI assessmentTest XML string into a SecureAssessment structure.
560
- *
561
- * Handles:
562
- * - S1: section-level itemSessionControl
563
- * - S9: assessmentSectionRef href resolution (requires fileResolver)
564
- * - T9/T1: outcomeDeclarations + outcomeProcessing extraction
565
- *
566
- * @param testXml - Raw QTI assessmentTest XML string
567
- * @param options.role - Role to assign to items (default: 'candidate')
568
- * @param options.itemXmlMap - Map of item identifier -> itemXml for pre-loaded items
569
- * @param options.fileResolver - Async function to load external files by relative href
570
- * @param options.baseUrl - Base URL for resolving relative hrefs
571
- */
572
- static async parseAssessmentTestXml(testXml, options = {}) {
573
- const { role = 'candidate', itemXmlMap = {}, fileResolver, baseUrl, sharedCatalogs } = options;
574
- const maxSectionDepth = options.sectionReferenceLimits?.maxDepth ?? 32;
575
- if (!Number.isInteger(maxSectionDepth) || maxSectionDepth < 1) {
576
- throw new Error('sectionReferenceLimits.maxDepth must be a positive integer');
577
- }
578
- const doc = parseXml(testXml);
579
- const root = doc.documentElement;
580
- if (!root)
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.
585
- const getAttr = (el, name) => {
586
- const direct = el.getAttribute(name);
587
- if (direct !== null && direct !== '')
588
- return direct;
589
- const mapped = el.getAttribute(name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`));
590
- return mapped === null || mapped === '' ? undefined : mapped;
591
- };
592
- const childElements = (el) => Array.from(el.childNodes).filter((n) => n.nodeType === 1);
593
- const childrenByTag = (el, tag) => childElements(el).filter((c) => toCanonicalQtiName(c.localName) === tag);
594
- // Parse itemSessionControl element
595
- const parseItemSessionControl = (el) => {
596
- const isc = childrenByTag(el, 'itemSessionControl')[0];
597
- if (!isc)
598
- return undefined;
599
- const boolAttr = (name) => {
600
- const v = getAttr(isc, name);
601
- return v === undefined ? undefined : v !== 'false';
602
- };
603
- const intAttr = (name) => {
604
- const v = getAttr(isc, name);
605
- return v === undefined ? undefined : parseInt(v, 10);
606
- };
607
- return {
608
- maxAttempts: intAttr('maxAttempts'),
609
- showFeedback: boolAttr('showFeedback') ?? boolAttr('show-feedback'),
610
- allowReview: boolAttr('allowReview') ?? boolAttr('allow-review'),
611
- showSolution: boolAttr('showSolution') ?? boolAttr('show-solution'),
612
- allowComment: boolAttr('allowComment') ?? boolAttr('allow-comment'),
613
- allowSkipping: boolAttr('allowSkipping') ?? boolAttr('allow-skipping'),
614
- validateResponses: boolAttr('validateResponses') ?? boolAttr('validate-responses'),
615
- };
616
- };
617
- const parseTimeLimits = (el) => {
618
- const limitsEl = childrenByTag(el, 'timeLimit')[0] ?? childrenByTag(el, 'timeLimits')[0];
619
- if (!limitsEl)
620
- return undefined;
621
- const numberAttr = (name) => {
622
- const value = getAttr(limitsEl, name);
623
- if (value === undefined)
624
- return undefined;
625
- const parsed = Number(value);
626
- return Number.isFinite(parsed) ? parsed : undefined;
627
- };
628
- const boolAttr = (name) => {
629
- const value = getAttr(limitsEl, name);
630
- return value === undefined ? undefined : value === 'true';
631
- };
632
- return {
633
- minTime: numberAttr('minTime'),
634
- maxTime: numberAttr('maxTime'),
635
- allowLateSubmission: boolAttr('allowLateSubmission'),
636
- };
637
- };
638
- const parseConditionExpressions = (el, tag) => {
639
- const expressions = childrenByTag(el, tag)
640
- .map((condition) => childElements(condition)[0])
641
- .filter((expression) => Boolean(expression))
642
- .map((expression) => serializeXml(expression));
643
- return expressions.length > 0 ? expressions : undefined;
644
- };
645
- const parseBranchRules = (el) => {
646
- const rules = childrenByTag(el, 'branchRule').flatMap((rule) => {
647
- const target = getAttr(rule, 'target');
648
- if (!target)
649
- return [];
650
- const expression = childElements(rule)[0];
651
- return [{ target, conditionXml: expression ? serializeXml(expression) : undefined }];
652
- });
653
- return rules.length > 0 ? rules : undefined;
654
- };
655
- const parseSelection = (el) => {
656
- const selection = childrenByTag(el, 'selection')[0];
657
- if (!selection)
658
- return undefined;
659
- const select = Number.parseInt(getAttr(selection, 'select') ?? '', 10);
660
- if (!Number.isInteger(select) || select < 0)
661
- return undefined;
662
- const withReplacementRaw = getAttr(selection, 'withReplacement');
663
- return {
664
- select,
665
- withReplacement: withReplacementRaw === undefined ? undefined : withReplacementRaw === 'true',
666
- };
667
- };
668
- const parseOrdering = (el) => {
669
- const ordering = childrenByTag(el, 'ordering')[0];
670
- if (!ordering)
671
- return undefined;
672
- return { shuffle: getAttr(ordering, 'shuffle') === 'true' };
673
- };
674
- const resolveCheckedHref = (href, sourceHref) => {
675
- if (!href)
676
- return undefined;
677
- if (sourceHref) {
678
- return resolveCheckedPackagePathFromFile(sourceHref, href) ?? undefined;
679
- }
680
- return baseUrl
681
- ? resolveCheckedPackagePathFromFile(baseUrl, href) ?? undefined
682
- : resolveCheckedPackagePath(undefined, href) ?? undefined;
683
- };
684
- const loadText = async (href, sourceHref) => {
685
- if (!href)
686
- return undefined;
687
- const candidates = [href, resolveCheckedHref(href, sourceHref)].filter((value, index, all) => Boolean(value) && all.indexOf(value) === index);
688
- for (const candidate of candidates) {
689
- if (itemXmlMap[candidate] !== undefined) {
690
- return itemXmlMap[candidate];
691
- }
692
- }
693
- if (!fileResolver)
694
- return undefined;
695
- for (const candidate of candidates) {
696
- try {
697
- return await fileResolver(candidate);
698
- }
699
- catch {
700
- // Try the next candidate before giving up.
701
- }
702
- }
703
- return undefined;
704
- };
705
- const buildDeliveryContext = async (itemXml, itemHref) => {
706
- if (!itemHref) {
707
- return undefined;
708
- }
709
- const stimulusXmlByPath = {};
710
- const packageTextByPath = {};
711
- const preloadText = async (baseHref, href) => {
712
- const resolvedPath = resolveCheckedPackagePathFromFile(baseHref, href);
713
- if (!resolvedPath)
714
- return;
715
- const text = await loadText(resolvedPath);
716
- if (text !== undefined) {
717
- packageTextByPath[resolvedPath] = text;
718
- }
719
- };
720
- for (const stylesheet of extractQtiStylesheets(itemXml)) {
721
- await preloadText(itemHref, stylesheet.href);
722
- }
723
- for (const ref of extractAssessmentStimulusRefs(itemXml)) {
724
- const stimulusPath = resolveCheckedPackagePathFromFile(itemHref, ref.href);
725
- if (!stimulusPath)
726
- continue;
727
- const stimulusXml = await loadText(stimulusPath);
728
- if (stimulusXml) {
729
- stimulusXmlByPath[stimulusPath] = stimulusXml;
730
- for (const stylesheet of parseAssessmentStimulusXml(stimulusXml).stylesheets) {
731
- await preloadText(stimulusPath, stylesheet.href);
732
- }
733
- }
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
- }
771
- return createResolvedItemDeliveryContext({
772
- itemXml,
773
- itemHref,
774
- readText: (path) => packageTextByPath[path] ?? stimulusXmlByPath[path] ?? itemXmlMap[path],
775
- ...(Object.keys(processingFragments).length > 0 ? { processingFragments } : {}),
776
- ...(packageCatalogSources.length > 0 ? { packageCatalogSources } : {}),
777
- });
778
- };
779
- let resolveSectionRef;
780
- const parseItemRef = async (ref, sourceHref) => {
781
- const itemId = getAttr(ref, 'identifier') ?? 'item';
782
- const href = getAttr(ref, 'href');
783
- const itemHref = resolveCheckedHref(href, sourceHref);
784
- const resolvedXml = href && !itemHref
785
- ? ''
786
- : itemXmlMap[itemId] ??
787
- (href ? itemXmlMap[href] : undefined) ??
788
- (itemHref ? itemXmlMap[itemHref] : undefined) ??
789
- (await loadText(itemHref)) ??
790
- '';
791
- const requiredRaw = getAttr(ref, 'required');
792
- const fixedRaw = getAttr(ref, 'fixed');
793
- const categories = (getAttr(ref, 'category') ?? '').split(/\s+/).filter(Boolean);
794
- const weights = childrenByTag(ref, 'weight').flatMap((weight) => {
795
- const identifier = getAttr(weight, 'identifier');
796
- const value = Number(getAttr(weight, 'value'));
797
- return identifier && Number.isFinite(value) ? [{ identifier, value }] : [];
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
- });
811
- return {
812
- identifier: itemId,
813
- itemXml: resolvedXml,
814
- role,
815
- required: requiredRaw === undefined ? undefined : requiredRaw !== 'false',
816
- fixed: fixedRaw === undefined ? undefined : fixedRaw !== 'false',
817
- timeLimits: parseTimeLimits(ref),
818
- deliveryContext: await buildDeliveryContext(resolvedXml, itemHref),
819
- branchRule: parseBranchRules(ref),
820
- preConditions: parseConditionExpressions(ref, 'preCondition'),
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,
826
- };
827
- };
828
- // Parse a single assessmentSection element without flattening nested sections.
829
- const parseSection = async (sectionEl, sourceHref, ancestorHrefs = [], depth = 1) => {
830
- const identifier = getAttr(sectionEl, 'identifier') ?? 'section';
831
- if (depth > maxSectionDepth) {
832
- throw new AssessmentSectionReferenceLimitError(`assessmentSection nesting exceeds maxDepth (${maxSectionDepth}) at "${identifier}"`);
833
- }
834
- const title = getAttr(sectionEl, 'title');
835
- const visibleRaw = getAttr(sectionEl, 'visible');
836
- const visible = visibleRaw === undefined ? true : visibleRaw !== 'false';
837
- const requiredRaw = getAttr(sectionEl, 'required');
838
- const fixedRaw = getAttr(sectionEl, 'fixed');
839
- const keepTogetherRaw = getAttr(sectionEl, 'keepTogether');
840
- const itemSessionControl = parseItemSessionControl(sectionEl);
841
- const timeLimits = parseTimeLimits(sectionEl);
842
- // rubricBlocks
843
- const rubricBlockEls = childrenByTag(sectionEl, 'rubricBlock');
844
- const rubricBlocks = rubricBlockEls.length > 0
845
- ? rubricBlockEls.map((b, idx) => ({
846
- identifier: getAttr(b, 'identifier') ?? `${identifier}-rubric-${idx + 1}`,
847
- view: (getAttr(b, 'view') ?? 'candidate').split(/\s+/).filter(Boolean),
848
- use: getAttr(b, 'use'),
849
- content: serializeXml(b),
850
- }))
851
- : undefined;
852
- const assessmentItemRefs = [];
853
- const sections = [];
854
- const children = [];
855
- for (const child of childElements(sectionEl)) {
856
- const name = toCanonicalQtiName(child.localName);
857
- if (name === 'assessmentItemRef') {
858
- const item = await parseItemRef(child, sourceHref);
859
- assessmentItemRefs.push(item);
860
- children.push({ type: 'item', item });
861
- }
862
- else if (name === 'assessmentSection') {
863
- const section = await parseSection(child, sourceHref, ancestorHrefs, depth + 1);
864
- sections.push(section);
865
- children.push({ type: 'section', section });
866
- }
867
- else if (name === 'assessmentSectionRef') {
868
- const section = await resolveSectionRef(child, sourceHref, ancestorHrefs, depth + 1);
869
- if (section) {
870
- sections.push(section);
871
- children.push({ type: 'section', section });
872
- }
873
- }
874
- }
875
- return {
876
- identifier,
877
- title,
878
- visible,
879
- required: requiredRaw === undefined ? undefined : requiredRaw !== 'false',
880
- fixed: fixedRaw === undefined ? undefined : fixedRaw !== 'false',
881
- assessmentItemRefs,
882
- sections: sections.length > 0 ? sections : undefined,
883
- children: children.length > 0 ? children : undefined,
884
- rubricBlocks,
885
- itemSessionControl,
886
- timeLimits,
887
- selection: parseSelection(sectionEl),
888
- ordering: parseOrdering(sectionEl),
889
- preConditions: parseConditionExpressions(sectionEl, 'preCondition'),
890
- branchRule: parseBranchRules(sectionEl),
891
- keepTogether: keepTogetherRaw === undefined ? undefined : keepTogetherRaw !== 'false',
892
- };
893
- };
894
- // Resolve assessmentSectionRef: load and parse referenced section file
895
- resolveSectionRef = async (sectionRefEl, sourceHref, ancestorHrefs = [], depth = 1) => {
896
- const href = getAttr(sectionRefEl, 'href');
897
- if (!href) {
898
- console.warn('[ReferenceBackendAdapter] assessmentSectionRef missing href, skipping');
899
- return null;
900
- }
901
- if (!fileResolver) {
902
- console.warn(`[ReferenceBackendAdapter] assessmentSectionRef href="${href}" found but no fileResolver provided, skipping`);
903
- return null;
904
- }
905
- try {
906
- const resolvedHref = resolveCheckedHref(href, sourceHref);
907
- if (!resolvedHref) {
908
- console.warn(`[ReferenceBackendAdapter] assessmentSectionRef href="${href}" is unsafe, skipping`);
909
- return null;
910
- }
911
- if (ancestorHrefs.includes(resolvedHref)) {
912
- throw new AssessmentSectionReferenceLimitError(`Cyclic assessmentSectionRef detected: ${[...ancestorHrefs, resolvedHref].join(' -> ')}`);
913
- }
914
- if (depth > maxSectionDepth) {
915
- throw new AssessmentSectionReferenceLimitError(`assessmentSectionRef nesting exceeds maxDepth (${maxSectionDepth}) at "${resolvedHref}"`);
916
- }
917
- const sectionXml = await fileResolver(resolvedHref);
918
- const secDoc = parseXml(sectionXml);
919
- const secRoot = secDoc.documentElement;
920
- if (!secRoot || toCanonicalQtiName(secRoot.localName) !== 'assessmentSection') {
921
- console.warn(`[ReferenceBackendAdapter] assessmentSectionRef href="${href}": root element is not <assessmentSection>, skipping`);
922
- return null;
923
- }
924
- return parseSection(secRoot, resolvedHref, [...ancestorHrefs, resolvedHref], depth);
925
- }
926
- catch (err) {
927
- if (err instanceof AssessmentSectionReferenceLimitError)
928
- throw err;
929
- console.warn(`[ReferenceBackendAdapter] Failed to load assessmentSectionRef href="${href}":`, err);
930
- return null;
931
- }
932
- };
933
- // Parse testPart children (sections + sectionRefs)
934
- const parseSectionsForTestPart = async (testPartEl) => {
935
- const sections = [];
936
- for (const child of childElements(testPartEl)) {
937
- if (toCanonicalQtiName(child.localName) === 'assessmentSection') {
938
- sections.push(await parseSection(child));
939
- }
940
- else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {
941
- const resolved = await resolveSectionRef(child);
942
- if (resolved)
943
- sections.push(resolved);
944
- }
945
- }
946
- return sections;
947
- };
948
- // Extract outcomeDeclarations
949
- const outcomeDeclarations = childrenByTag(root, 'outcomeDeclaration').map((d) => {
950
- const identifier = getAttr(d, 'identifier') ?? 'OUTCOME';
951
- const baseType = getAttr(d, 'baseType') ?? 'float';
952
- const cardinality = getAttr(d, 'cardinality') ?? 'single';
953
- // Parse defaultValue if present
954
- const defaultValueEl = childrenByTag(d, 'defaultValue')[0];
955
- let defaultValue = undefined;
956
- if (defaultValueEl) {
957
- const valueEl = childrenByTag(defaultValueEl, 'value')[0];
958
- if (valueEl) {
959
- const text = valueEl.textContent?.trim() ?? '0';
960
- if (baseType === 'float' || baseType === 'integer') {
961
- defaultValue = Number(text);
962
- }
963
- else {
964
- defaultValue = text;
965
- }
966
- }
967
- }
968
- return { identifier, baseType, cardinality, defaultValue };
969
- });
970
- // Extract outcomeProcessing XML
971
- const outcomeProcessingEl = childrenByTag(root, 'outcomeProcessing')[0];
972
- const outcomeProcessingXml = outcomeProcessingEl
973
- ? serializeXml(outcomeProcessingEl)
974
- : undefined;
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);
994
- // Extract assessment-level timeLimits.
995
- const timeLimits = parseTimeLimits(root);
996
- // Parse testParts
997
- const testPartEls = childrenByTag(root, 'testPart');
998
- const firstTestPart = testPartEls[0];
999
- // Retain top-level compatibility fields while preserving the authoritative
1000
- // mode on every testPart below.
1001
- const navigationMode = (getAttr(firstTestPart ?? root, 'navigationMode') ?? 'nonlinear');
1002
- const submissionMode = (getAttr(firstTestPart ?? root, 'submissionMode') ?? 'simultaneous');
1003
- const testParts = [];
1004
- for (const tp of testPartEls) {
1005
- const tpIdentifier = getAttr(tp, 'identifier') ?? 'part-1';
1006
- const tpNavigationMode = (getAttr(tp, 'navigationMode') ?? 'nonlinear');
1007
- const tpSubmissionMode = (getAttr(tp, 'submissionMode') ?? 'simultaneous');
1008
- const tpItemSessionControl = parseItemSessionControl(tp);
1009
- const tpTimeLimits = parseTimeLimits(tp);
1010
- const tpRubricBlockEls = childrenByTag(tp, 'rubricBlock');
1011
- const tpRubricBlocks = tpRubricBlockEls.length > 0
1012
- ? tpRubricBlockEls.map((b, idx) => ({
1013
- identifier: getAttr(b, 'identifier') ?? `${tpIdentifier}-rubric-${idx + 1}`,
1014
- view: (getAttr(b, 'view') ?? 'candidate').split(/\s+/).filter(Boolean),
1015
- use: getAttr(b, 'use'),
1016
- content: serializeXml(b),
1017
- }))
1018
- : undefined;
1019
- const sections = await parseSectionsForTestPart(tp);
1020
- testParts.push({
1021
- identifier: tpIdentifier,
1022
- navigationMode: tpNavigationMode,
1023
- submissionMode: tpSubmissionMode,
1024
- sections,
1025
- rubricBlocks: tpRubricBlocks,
1026
- testFeedback: parseTestFeedback(tp),
1027
- itemSessionControl: tpItemSessionControl,
1028
- timeLimits: tpTimeLimits,
1029
- preConditions: parseConditionExpressions(tp, 'preCondition'),
1030
- branchRule: parseBranchRules(tp),
1031
- });
1032
- }
1033
- // If no testParts, try top-level sections
1034
- if (testParts.length === 0) {
1035
- const topSections = [];
1036
- for (const child of childElements(root)) {
1037
- if (toCanonicalQtiName(child.localName) === 'assessmentSection') {
1038
- topSections.push(await parseSection(child));
1039
- }
1040
- else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {
1041
- const resolved = await resolveSectionRef(child);
1042
- if (resolved)
1043
- topSections.push(resolved);
1044
- }
1045
- }
1046
- if (topSections.length > 0) {
1047
- testParts.push({
1048
- identifier: 'part-1',
1049
- navigationMode,
1050
- submissionMode,
1051
- sections: topSections,
1052
- });
1053
- }
1054
- }
1055
- return {
1056
- identifier: getAttr(root, 'identifier') ?? 'assessment',
1057
- title: getAttr(root, 'title') ?? 'Assessment',
1058
- navigationMode,
1059
- submissionMode,
1060
- testParts,
1061
- timeLimits,
1062
- outcomeDeclarations: outcomeDeclarations.length > 0 ? outcomeDeclarations : undefined,
1063
- outcomeProcessingXml,
1064
- testFeedback,
1065
- baseUrl,
1066
- };
1067
- }
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);
1078
- }
1079
- return addItemVariableDeclarations(testOutcomeDeclarations(session.assessment, outcomes), itemVariables, current);
1080
- }
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;
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;
1128
- };
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;
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;
1178
- }
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.
618
+ * Test-level view of every delivered item. A submitted item is presented and carries the state
619
+ * its latest counted submission recorded (a score without one carries only its SCORE); an item
620
+ * not yet submitted carries its declared defaults and counts as not presented.
1195
621
  */
1196
622
  buildTestItems(session) {
1197
623
  const itemScores = session.state.itemScores ?? {};
1198
- return this.getItemRefsInOrder(session.assessment).map(({ item, sectionIdentifiers }) => {
624
+ return getItemRefsInOrder(session.assessment).map(({ item, sectionIdentifiers }) => {
1199
625
  const scoring = itemScores[item.identifier];
1200
626
  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
- };
627
+ const itemState = presented ? session.itemTestStates?.[item.identifier] : defaultItemTestState(item.itemXml);
628
+ const variables = { ...(itemState?.variables ?? {}) };
1206
629
  if (scoring && !variables.SCORE)
1207
630
  variables.SCORE = qtiValue('float', 'single', scoring.score);
1208
631
  Object.assign(variables, applyVariableMappings(variables, item.variableMappings));
1209
- const legacy = presented && !stored;
1210
632
  return {
1211
633
  identifier: item.identifier,
1212
634
  sectionIdentifiers,
1213
635
  categories: item.categories,
1214
636
  weights: item.weights ? Object.fromEntries(item.weights.map((w) => [w.identifier, w.value])) : undefined,
1215
637
  variables,
1216
- outcomeBounds: (itemState ?? defaultItemTestState(item.itemXml))?.outcomeBounds,
638
+ outcomeBounds: itemState?.outcomeBounds ?? defaultItemTestState(item.itemXml)?.outcomeBounds,
1217
639
  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 }),
640
+ responded: presented && itemState?.responded === true,
641
+ correct: presented && itemState?.correct === true,
642
+ incorrect: presented && itemState?.correct === false,
1224
643
  selected: true,
1225
644
  };
1226
645
  });
1227
646
  }
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
- ]));
1234
- }
1235
- // =========================================================================
1236
- // ITEM BANK HELPERS
1237
- // =========================================================================
1238
- /**
1239
- * Generate cache key for item bank query
1240
- */
1241
- getBankCacheKey(sessionId, bankId, count, withReplacement, filters) {
1242
- const filterKey = filters ? JSON.stringify(filters) : '';
1243
- return `${BANK_CACHE_PREFIX}${sessionId}:${bankId}:${count}:${withReplacement}:${filterKey}`;
1244
- }
1245
- /**
1246
- * Load item bank cache from localStorage
1247
- */
1248
- loadBankCache(cacheKey) {
1249
- try {
1250
- const data = localStorage.getItem(cacheKey);
1251
- if (!data)
1252
- return null;
1253
- const entry = JSON.parse(data);
1254
- // Check if cache is expired
1255
- const now = Date.now();
1256
- if (now - entry.timestamp > entry.ttl) {
1257
- // Clean up expired cache
1258
- localStorage.removeItem(cacheKey);
1259
- return null;
1260
- }
1261
- return entry;
1262
- }
1263
- catch {
1264
- return null;
1265
- }
1266
- }
1267
- /**
1268
- * Save item bank cache to localStorage
1269
- */
1270
- saveBankCache(cacheKey, entry) {
1271
- try {
1272
- localStorage.setItem(cacheKey, JSON.stringify(entry));
1273
- }
1274
- catch (error) {
1275
- console.error('Failed to save bank cache to localStorage:', error);
1276
- }
1277
- }
1278
- /**
1279
- * Fetch items from item bank with retry logic
1280
- *
1281
- * **DEMO IMPLEMENTATION**: Returns hardcoded items
1282
- * In production, this would make HTTP request to item bank service
1283
- */
1284
- async fetchItemsFromBank(bankId, count, withReplacement, filters, retryCount = 0) {
1285
- const maxRetries = 3;
1286
- const baseDelay = 1000; // 1 second
1287
- try {
1288
- // Simulate network call delay
1289
- await this.delay(100);
1290
- // **DEMO**: Return hardcoded items
1291
- // In production, replace with:
1292
- // const response = await fetch(`/api/item-banks/${bankId}`, {
1293
- // method: 'POST',
1294
- // headers: { 'Content-Type': 'application/json' },
1295
- // body: JSON.stringify({ count, withReplacement, filters })
1296
- // });
1297
- // return response.json();
1298
- const demoItems = [
1299
- {
1300
- identifier: `bank-${bankId}-item1`,
1301
- role: 'candidate',
1302
- itemXml: `<assessmentItem identifier="bank-${bankId}-item1" title="Bank Item 1" adaptive="false" timeDependent="false">
1303
- <responseDeclaration identifier="RESPONSE" cardinality="single" baseType="identifier">
1304
- <correctResponse><value>A</value></correctResponse>
1305
- </responseDeclaration>
1306
- <outcomeDeclaration identifier="SCORE" cardinality="single" baseType="float">
1307
- <defaultValue><value>0</value></defaultValue>
1308
- </outcomeDeclaration>
1309
- <itemBody>
1310
- <p>Sample question from bank ${bankId}</p>
1311
- <choiceInteraction responseIdentifier="RESPONSE" shuffle="false" maxChoices="1">
1312
- <simpleChoice identifier="A">Option A</simpleChoice>
1313
- <simpleChoice identifier="B">Option B</simpleChoice>
1314
- </choiceInteraction>
1315
- </itemBody>
1316
- <responseProcessing>
1317
- <responseCondition>
1318
- <responseIf>
1319
- <match>
1320
- <variable identifier="RESPONSE" />
1321
- <correct identifier="RESPONSE" />
1322
- </match>
1323
- <setOutcomeValue identifier="SCORE">
1324
- <baseValue baseType="float">1</baseValue>
1325
- </setOutcomeValue>
1326
- </responseIf>
1327
- <responseElse>
1328
- <setOutcomeValue identifier="SCORE">
1329
- <baseValue baseType="float">0</baseValue>
1330
- </setOutcomeValue>
1331
- </responseElse>
1332
- </responseCondition>
1333
- </responseProcessing>
1334
- </assessmentItem>`,
1335
- },
1336
- {
1337
- identifier: `bank-${bankId}-item2`,
1338
- role: 'candidate',
1339
- itemXml: `<assessmentItem identifier="bank-${bankId}-item2" title="Bank Item 2" adaptive="false" timeDependent="false">
1340
- <responseDeclaration identifier="RESPONSE" cardinality="single" baseType="identifier">
1341
- <correctResponse><value>B</value></correctResponse>
1342
- </responseDeclaration>
1343
- <outcomeDeclaration identifier="SCORE" cardinality="single" baseType="float">
1344
- <defaultValue><value>0</value></defaultValue>
1345
- </outcomeDeclaration>
1346
- <itemBody>
1347
- <p>Another question from bank ${bankId}</p>
1348
- <choiceInteraction responseIdentifier="RESPONSE" shuffle="false" maxChoices="1">
1349
- <simpleChoice identifier="A">Option A</simpleChoice>
1350
- <simpleChoice identifier="B">Option B</simpleChoice>
1351
- </choiceInteraction>
1352
- </itemBody>
1353
- <responseProcessing>
1354
- <responseCondition>
1355
- <responseIf>
1356
- <match>
1357
- <variable identifier="RESPONSE" />
1358
- <correct identifier="RESPONSE" />
1359
- </match>
1360
- <setOutcomeValue identifier="SCORE">
1361
- <baseValue baseType="float">1</baseValue>
1362
- </setOutcomeValue>
1363
- </responseIf>
1364
- <responseElse>
1365
- <setOutcomeValue identifier="SCORE">
1366
- <baseValue baseType="float">0</baseValue>
1367
- </setOutcomeValue>
1368
- </responseElse>
1369
- </responseCondition>
1370
- </responseProcessing>
1371
- </assessmentItem>`,
1372
- },
1373
- {
1374
- identifier: `bank-${bankId}-item3`,
1375
- role: 'candidate',
1376
- itemXml: `<assessmentItem identifier="bank-${bankId}-item3" title="Bank Item 3" adaptive="false" timeDependent="false">
1377
- <responseDeclaration identifier="RESPONSE" cardinality="single" baseType="identifier">
1378
- <correctResponse><value>A</value></correctResponse>
1379
- </responseDeclaration>
1380
- <outcomeDeclaration identifier="SCORE" cardinality="single" baseType="float">
1381
- <defaultValue><value>0</value></defaultValue>
1382
- </outcomeDeclaration>
1383
- <itemBody>
1384
- <p>Third question from bank ${bankId}</p>
1385
- <choiceInteraction responseIdentifier="RESPONSE" shuffle="false" maxChoices="1">
1386
- <simpleChoice identifier="A">Option A</simpleChoice>
1387
- <simpleChoice identifier="B">Option B</simpleChoice>
1388
- </choiceInteraction>
1389
- </itemBody>
1390
- <responseProcessing>
1391
- <responseCondition>
1392
- <responseIf>
1393
- <match>
1394
- <variable identifier="RESPONSE" />
1395
- <correct identifier="RESPONSE" />
1396
- </match>
1397
- <setOutcomeValue identifier="SCORE">
1398
- <baseValue baseType="float">1</baseValue>
1399
- </setOutcomeValue>
1400
- </responseIf>
1401
- <responseElse>
1402
- <setOutcomeValue identifier="SCORE">
1403
- <baseValue baseType="float">0</baseValue>
1404
- </setOutcomeValue>
1405
- </responseElse>
1406
- </responseCondition>
1407
- </responseProcessing>
1408
- </assessmentItem>`,
1409
- },
1410
- ];
1411
- // Apply filtering if specified (demo implementation)
1412
- let filteredItems = [...demoItems];
1413
- if (filters?.difficulty) {
1414
- // In production, server would filter by metadata
1415
- console.log(`Filtering by difficulty: ${filters.difficulty}`);
1416
- }
1417
- // Select requested number of items
1418
- if (withReplacement) {
1419
- // Allow duplicates
1420
- const selected = [];
1421
- for (let i = 0; i < count; i++) {
1422
- const randomIndex = Math.floor(Math.random() * filteredItems.length);
1423
- selected.push(filteredItems[randomIndex]);
1424
- }
1425
- return selected;
1426
- }
1427
- else {
1428
- // No duplicates - shuffle and take first N
1429
- const shuffled = shuffleArray(filteredItems, Math.random);
1430
- return shuffled.slice(0, Math.min(count, shuffled.length));
1431
- }
1432
- }
1433
- catch (error) {
1434
- // Implement exponential backoff retry
1435
- if (retryCount < maxRetries) {
1436
- const delay = baseDelay * Math.pow(2, retryCount);
1437
- console.warn(`Item bank query failed (attempt ${retryCount + 1}/${maxRetries + 1}). ` +
1438
- `Retrying in ${delay}ms...`, error);
1439
- await this.delay(delay);
1440
- return this.fetchItemsFromBank(bankId, count, withReplacement, filters, retryCount + 1);
1441
- }
1442
- // All retries exhausted
1443
- throw new Error(`Failed to load items from bank "${bankId}" after ${maxRetries + 1} attempts: ${error}`);
1444
- }
1445
- }
1446
- /**
1447
- * Delay helper for async operations
1448
- */
1449
- delay(ms) {
1450
- return new Promise((resolve) => setTimeout(resolve, ms));
1451
- }
1452
- }
1453
- /**
1454
- * Fisher-Yates shuffle using a provided RNG (returns a new array).
1455
- *
1456
- * Mirrors the helper of the same name in `core/AssessmentPlayer.ts`. Replaces a
1457
- * `sort(() => Math.random() - 0.5)` comparator, which is not a uniform shuffle: the
1458
- * comparator is inconsistent, so the result depends on the sort algorithm and leaves
1459
- * elements biased toward their original positions.
1460
- */
1461
- function shuffleArray(arr, rng) {
1462
- const out = [...arr];
1463
- for (let i = out.length - 1; i > 0; i--) {
1464
- const j = Math.floor(rng() * (i + 1));
1465
- [out[i], out[j]] = [out[j], out[i]];
1466
- }
1467
- return out;
1468
647
  }
648
+ /** @see ./qti-test-parser.ts — the parser lives in its own module. */
649
+ ReferenceBackendAdapter.parseAssessmentTestXml = parseAssessmentTestXml;
1469
650
  //# sourceMappingURL=ReferenceBackendAdapter.js.map