@pie-qti/assessment-player 1.0.0-beta.3 → 1.0.0-beta.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 (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 +2836 -457
  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 +46 -0
  54. package/dist/core/navigationPolicy.js +66 -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 +65 -0
  75. package/dist/core/submissionPolicy.js +71 -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 +54 -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 +255 -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 +214 -1033
  91. package/dist/integration/ReferenceBackendAdapter.js.map +1 -1
  92. package/dist/integration/api-contract.d.ts +175 -10
  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 +558 -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 +18 -14
  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
@@ -11,13 +11,38 @@ import { createAssessmentItemDefinition, } from '@pie-qti/item-player';
11
11
  import { DefaultI18nProvider } from '@pie-qti/i18n';
12
12
  import { isShownByIdentifier } from '@pie-qti/qti-common';
13
13
  import { AssessmentSessionCoordinator } from './AssessmentSessionCoordinator.js';
14
+ import { AssessmentPlayerError, isAssessmentPlayerError } from './errors.js';
15
+ import { attemptFeedbackVisible, resolveMaxAttempts } from './feedback.js';
14
16
  import { NavigationManager } from './NavigationManager.js';
15
- import { deliveredItems, evaluateTestExpression, isAdaptiveItemXml, plainQtiValue, resolveItemSessionControl, sectionComponents, testOutcomeDeclarations, } from './testStructure.js';
17
+ import { addItemVariableDeclarations, applyVariableMappings, endAttemptInteractionInfo, firstEligibleItem, isAdaptiveItemXml, nextItemIdentifier, recordedItemVariableValues, resolveItemSessionControl, testOutcomeDeclarations, } from './testStructure.js';
16
18
  import { extendTimeLimit, TimeManager } from './TimeManager.js';
19
+ import { asResponseValues, cloneData, cloneResponseRecord, closedItemSession, isWritableItemLifecycle, responseDefaultsOf, responseValuesEqual, valuesFromItemSession, } from './sessionRecords.js';
20
+ import { TypedEventEmitter } from './playerEvents.js';
21
+ import { flattenItems, partOrderOf, presentedSectionOf, presentedSections, } from './deliveryStructure.js';
22
+ import { ScopeLocks, isItemLocked, lockingScopeOf, scopeKey, scopeLimitRanOut, } from './scopeLocks.js';
23
+ import { canNavigateByTestPart, isLegalSectionTarget } from './navigationPolicy.js';
24
+ import { branchExitLeavesPart, branchLandingOf, branchTargetIndex, endedEnclosingSection, resolveExitBoundary, } from './exitBoundaries.js';
25
+ import { effectiveSubmissionMode, submissionBlockerFor, submissionGate as submissionGatePolicy, throwForBlockers, } from './submissionPolicy.js';
26
+ import { ReviewInfoCache, resultsSummaryOf, reviewItemRow } from './reviewViews.js';
27
+ import { assertMinTimeElapsed, effectiveItemTimeLimits, submitTimingEvidence, } from './timePolicy.js';
28
+ import { templateDefaultsFor } from './templateDefaults.js';
29
+ import { PauseController } from './pause.js';
30
+ import { createSessionAutosave } from './autosave.js';
31
+ import { interactionRequirementFromXml, itemAnswerStatus, } from './reviewState.js';
17
32
  export class AssessmentPlayer {
18
33
  static async create(config) {
19
34
  const init = await config.backend.initSession(config.initSession);
20
- return new AssessmentPlayer(config, init);
35
+ const player = new AssessmentPlayer(config, init);
36
+ // Restored terminal and paused states set no listener off during construction:
37
+ // the host hooks hear them once here, so an embedding (the element's
38
+ // `session-finalized` / `player-pause` events) never misses them.
39
+ if (player.finalized && player.finalResults) {
40
+ config.onFinalized?.({ restored: true, results: player.finalResults });
41
+ }
42
+ else if (player.paused) {
43
+ config.onPauseChange?.(true, player.pauseReason);
44
+ }
45
+ return player;
21
46
  }
22
47
  constructor(config, init) {
23
48
  this.config = config;
@@ -25,22 +50,136 @@ export class AssessmentPlayer {
25
50
  this.items = [];
26
51
  this.currentItemIndex = -1;
27
52
  this.itemDefinitions = new Map();
53
+ /** endAttemptInteraction bindings per item: response identifier → countAttempt. */
54
+ this.endAttemptResponses = new Map();
28
55
  this.currentItemSession = null;
29
56
  this.currentItemSessionUnsubscribe = null;
30
57
  /** Test-level outcomes from the last outcome processing; null until it first runs. */
31
58
  this.testOutcomes = null;
32
59
  this.finalized = false;
60
+ /** Set by destroy(); a scheduled end-attempt submission after teardown is dropped. */
61
+ this.destroyed = false;
62
+ /** Results produced by the finalization; returned when submit() is called again after the end. */
63
+ this.finalResults = null;
33
64
  /** Scopes whose time limit expired without late submission, keyed `scope:identifier`. */
34
- this.lockedScopes = new Set();
35
- // Event listeners
36
- this.itemChangeListeners = new Set();
37
- this.sectionChangeListeners = new Set();
38
- this.responseChangeListeners = new Set();
39
- this.completeListeners = new Set();
40
- this.testFeedbackChangeListeners = new Set();
41
- this.timeWarningListeners = new Set();
42
- this.timeExpiredListeners = new Set();
43
- this.timeTickListeners = new Set();
65
+ this.scopeLocks = new ScopeLocks();
66
+ /**
67
+ * Navigation serialization: exactly one navigation or submission transition may run at
68
+ * a time. While set, further navigation and submit calls are rejected as busy.
69
+ */
70
+ this.transitionInFlight = false;
71
+ /**
72
+ * Scope-expiry hops waiting for the transition in flight to settle (the timer fired
73
+ * while it ran). The transition checks this to leave the move to the hop, the way it
74
+ * previously detected the move an unlocked hop had already made mid-flight.
75
+ */
76
+ this.queuedExpiryHops = 0;
77
+ /** Last reported test-level outcome-processing failure, so hosts hear about each new one once. */
78
+ this.reportedOutcomeProcessingError = null;
79
+ /**
80
+ * Test-scope branch rules and preConditions already reported as unevaluable, keyed by
81
+ * condition XML + failure message: the rules re-evaluate on every forward step, and the
82
+ * host must hear about each distinct failed rule once, not on every step.
83
+ */
84
+ this.reportedTestConditionFailures = new Set();
85
+ /** Item scoring failures already reported, keyed by item identifier + failure message. */
86
+ this.reportedItemScoringErrors = new Set();
87
+ /** False while an opt-in begin gate holds delivery: no item is entered and no clock runs. */
88
+ this.started = true;
89
+ /** The whole-test hard limit expired (no late submission); delivery collects and ends. */
90
+ this.assessmentExpired = false;
91
+ /** The live attempt was suspended by a pause; resume() reopens it from its pause snapshot. */
92
+ this.suspendedForPause = false;
93
+ /** Debounced draft persistence through `saveState` (autosave); null when disabled. */
94
+ this.autosave = null;
95
+ /** True while the session carries a backend-restored snapshot (a resume). */
96
+ this.restoredFromSnapshot = false;
97
+ /**
98
+ * Item feedback the most recent item-level submission produced (item modal feedback
99
+ * from the session's response processing, else the backend's `result.feedback`).
100
+ * Shells show it after a check-answer or a submit-on-move; it clears on the next
101
+ * submission or when the shell dismisses it.
102
+ */
103
+ this.lastItemFeedback = null;
104
+ /**
105
+ * The responses each item's last counted submission carried. Moving on from an item
106
+ * that already has a recorded result (a practice check) re-submits only when the
107
+ * candidate changed something: an unchanged response does not spend another attempt.
108
+ */
109
+ this.lastSubmittedResponses = new Map();
110
+ /**
111
+ * Template defaults of nonlinear test parts, evaluated once at part entry for every
112
+ * item ref (QTI): test part identifier → item identifier → defaults.
113
+ */
114
+ this.templateDefaultsByPart = new Map();
115
+ /** The presentation policy the live session was opened with (null: the item-player default). */
116
+ this.liveSessionPresentation = null;
117
+ /** Set during a proctor force-submit: submissions carry `submissionReason: 'proctor'`. */
118
+ this.administrativeReason = null;
119
+ /**
120
+ * Items the running end of the test collects although their QTI skipping/validation
121
+ * control would refuse them, because the candidate can no longer reach them (their
122
+ * test part was left): they go out as they stand, `submissionReason: 'unreachable'`.
123
+ */
124
+ this.unreachableCollection = new Set();
125
+ /** Why the running (or finished) end of the test happens; the first caller decides. */
126
+ this.endReason = null;
127
+ /**
128
+ * Scopes that expired while an end of the test ran: they closed at once, but delivery
129
+ * leaves them only if that end does not finalize (the end of the test never navigates).
130
+ */
131
+ this.expiriesDuringEnd = [];
132
+ /** The delivered items as the delivery rules walk them (index-aligned with `items`). */
133
+ this.deliveredForRules = [];
134
+ /** Flat index per item identifier. */
135
+ this.indexByIdentifier = new Map();
136
+ /**
137
+ * Whether the test carries branch rules or preconditions at all; without them the next item
138
+ * is always the adjacent open one, and no rule is evaluated.
139
+ */
140
+ this.hasDeliveryRules = false;
141
+ /** Set while the end of the test persists its final snapshot: every item session in it is closed. */
142
+ this.snapshotsCloseItemSessions = false;
143
+ /** Rejections for transitions queued behind a transition (`runWhenIdle`), settled on destroy(). */
144
+ this.queuedIdleTransitions = new Set();
145
+ /** A restored whole-test expiry's automatic finalize is scheduled (or ran). */
146
+ this.restoredExpiryFinalizeScheduled = false;
147
+ // Event listeners (typed emitter; the host-config callbacks stay in the notify helpers)
148
+ this.events = new TypedEventEmitter();
149
+ /** Declared response default values per item (QTI: a response equal to its default is no response). */
150
+ this.responseDefaultsCache = new Map();
151
+ /** The item entry a failed hop will retry: the initial item, or an expiry hop target. */
152
+ this.pendingEntryIndex = null;
153
+ /** The last failed item entry, for the shell's typed failure screen. */
154
+ this.entryError = null;
155
+ /**
156
+ * The reporter the delivery-rules walk (`nextItemIdentifier`, `firstEligibleItem`)
157
+ * hands each unevaluable branch rule or preCondition to. A broken rule reads as false
158
+ * (delivery proceeds on the default path — the same rule never blocks or aborts the
159
+ * test), but the host learns of it through `config.onError` as a coded
160
+ * `testConditionFailed` error, once per distinct failed rule rather than on every
161
+ * re-evaluation.
162
+ */
163
+ this.reportTestConditionFailure = (conditionXml, error) => {
164
+ const message = error instanceof Error ? error.message : String(error);
165
+ this.reportOnce(this.reportedTestConditionFailures, `${conditionXml}\n${message}`, () => new AssessmentPlayerError('testConditionFailed', message, {}, { cause: error }));
166
+ };
167
+ this.pauseControl = new PauseController({
168
+ isBusy: () => this.transitionInFlight,
169
+ onTransitionActivity: (listener) => this.onBusyChange(listener),
170
+ freeze: () => {
171
+ this.timeManager?.pause();
172
+ this.suspendLiveSessionForPause();
173
+ },
174
+ unfreeze: () => {
175
+ this.timeManager?.resume();
176
+ this.reopenLiveSessionAfterPause();
177
+ },
178
+ unfreezeAllowed: () => this.started && !this.finalized,
179
+ changed: () => this.notifyPauseChange(),
180
+ afterResume: () => this.finalizeRestoredExpiryWhenRunning(),
181
+ isDestroyed: () => this.destroyed,
182
+ });
44
183
  this.backend = config.backend;
45
184
  this.sessionId = init.sessionId;
46
185
  this.assessment = init.assessment;
@@ -55,191 +194,937 @@ export class AssessmentPlayer {
55
194
  itemSessions: {},
56
195
  timing: { startedAt: Date.now(), itemTimes: {}, totalTime: 0 },
57
196
  };
58
- this.items = this.flattenItems(this.assessment);
59
- const navigationMode = this.assessment.navigationMode || 'nonlinear';
60
- this.navigationManager = new NavigationManager(navigationMode, this.items.length);
197
+ this.items = flattenItems(this.assessment);
198
+ this.deliveredForRules = this.items.map(({ item, testPart, sections }) => ({ item, testPart, sections }));
199
+ for (const q of this.items)
200
+ this.indexByIdentifier.set(q.identifier, q.index);
201
+ this.reviewInfoCache = new ReviewInfoCache(this.items);
202
+ const ruled = (holder) => (holder.preConditions?.length ?? 0) > 0 || (holder.branchRule?.length ?? 0) > 0;
203
+ this.hasDeliveryRules = this.items.some((q) => ruled(q.item) || ruled(q.testPart) || q.sections.some((section) => ruled(section)));
204
+ this.navigationManager = new NavigationManager();
205
+ // Visited marks ride the snapshot: a resumed session keeps them, not only a
206
+ // host-driven restoreState().
207
+ this.navigationManager.restoreState(this.visitedIndexes(initialState.visitedItems));
61
208
  // Item session control is a UI hint; backend remains authoritative.
62
209
  this.sessionCoordinator = new AssessmentSessionCoordinator({
63
210
  state: initialState,
64
211
  itemIdentifiers: this.items.map((q) => q.identifier),
65
212
  itemSessionControlByItem: Object.fromEntries(this.items.map((q) => [q.identifier, resolveItemSessionControl(q.testPart, q.sections, q.item)])),
66
213
  });
214
+ // A resumed session's snapshot carries the test outcomes its submissions produced:
215
+ // the delivery rules read them, so the restored session navigates like the live one.
216
+ if (initialState.testOutcomes) {
217
+ this.testOutcomes = cloneData(initialState.testOutcomes);
218
+ }
219
+ else if (init.outcomes) {
220
+ this.sessionCoordinator.setTestOutcomes(init.outcomes);
221
+ }
67
222
  this.timeManager = new TimeManager({
68
223
  assessmentTimeLimits: this.assessment.timeLimits,
69
- warningThreshold: config.timeWarningThreshold || 60,
224
+ // The default warning (60 s unless the host moves it; 0 turns it off — a 0 threshold
225
+ // never fires), then any additional ones.
226
+ warningThresholds: [config.timeWarningThreshold ?? 60, ...(config.timeWarningThresholds ?? [])],
70
227
  now: config.now,
71
228
  extendedTime: config.pnp?.content?.extendedTime,
72
229
  onWarning: (remainingSeconds) => this.notifyTimeWarning(remainingSeconds),
73
- onExpired: () => this.notifyTimeExpired(),
230
+ onExpired: () => this.handleAssessmentTimeExpired(),
74
231
  onScopeExpired: (scope, identifier) => this.handleScopeExpired(scope, identifier),
75
232
  onTick: (remainingSeconds, elapsedSeconds) => this.notifyTimeTick(remainingSeconds, elapsedSeconds),
76
233
  });
234
+ // Items whose recorded result the snapshot carries were submitted with their
235
+ // snapshot responses: identical responses must not re-submit (and re-spend an
236
+ // attempt) on the next move or at finalize after a resume.
237
+ this.seedSubmittedResponses(initialState);
77
238
  if (init.restoredState?.timing) {
78
239
  this.restoreTimeTracking(init.restoredState.timing);
240
+ // Expiries are not in the snapshot: every scope whose restored clock already ran
241
+ // out locks now, before any item is entered, so none reopens editable.
242
+ this.lockExpiredScopesFromClocks(init.restoredState.timing);
79
243
  }
80
- // Restore to backend-provided current item if present
244
+ // A session saved during a proctor pause reopens paused, its clocks frozen.
245
+ this.pauseControl.setFromRestore(init.restoredState?.timing?.isPaused === true, init.restoredState?.timing?.pauseReason);
246
+ this.restoredFromSnapshot = init.restoredState !== undefined;
247
+ this.restoredSavedAt = init.restoredState?.timing?.savedAt;
248
+ this.createAutosave();
249
+ // A session the backend stored as finalized restores terminal: submit() returns
250
+ // the stored results instead of failing, no item is entered, no clock runs, and
251
+ // nothing autosaves. The shell shows its already-submitted view for it.
252
+ if (init.finalized === true) {
253
+ this.finalized = true;
254
+ this.finalResults = this.finalResultsFromInit(init);
255
+ this.autosave?.stop();
256
+ this.timeManager?.pause();
257
+ this.timeManager?.stopTimer();
258
+ return;
259
+ }
260
+ if (config.beginGate === true) {
261
+ // The begin gate holds delivery: no item is entered and no clock runs until start().
262
+ this.started = false;
263
+ this.timeManager.pause();
264
+ return;
265
+ }
266
+ this.enterInitialItem();
267
+ this.finalizeRestoredExpiryWhenRunning();
268
+ }
269
+ /**
270
+ * Enter the backend-provided current item (or the first) as delivery begins. The
271
+ * restoring navigation has no await before the session is attached, so the live
272
+ * session exists when this returns. A failure is recorded (not swallowed): the shell
273
+ * shows its typed failure screen with Retry instead of an eternal loading state.
274
+ * An item an expired limit closed is never entered editable: delivery lands on the
275
+ * next open item, like the live expiry's hop, or — with none left — shows the closed
276
+ * item read-only and asks for the submission (reported once listeners can hear it).
277
+ */
278
+ enterInitialItem() {
81
279
  const startId = this.state.currentItemIdentifier;
82
280
  const idx = startId ? this.items.findIndex((q) => q.identifier === startId) : -1;
83
- if (idx >= 0) {
84
- this.navigateTo(idx, { restoring: true }).catch(() => { });
281
+ const requested = idx >= 0 ? idx : this.items.length > 0 ? 0 : -1;
282
+ if (requested < 0)
283
+ return;
284
+ const { index: target, deadEnd } = this.restoringEntryTarget(requested);
285
+ this.pendingEntryIndex = target;
286
+ this.performNavigateTo(target, { restoring: true })
287
+ .then(() => {
288
+ if (this.pendingEntryIndex === target)
289
+ this.pendingEntryIndex = null;
290
+ // The shell attaches its listeners right after creation; report the dead end
291
+ // on the next task so it is heard.
292
+ if (deadEnd)
293
+ setTimeout(() => this.notifyExpiryDeadEnd(), 0);
294
+ })
295
+ .catch((error) => {
296
+ this.recordEntryFailure(error);
297
+ });
298
+ }
299
+ /**
300
+ * Where a restoring entry lands: the requested item when it is open; else the open item
301
+ * the live expiry would have moved the candidate to (forward in the part, an open earlier
302
+ * question of a nonlinear part, the next part); else — nothing open remains — the
303
+ * requested item itself, shown read-only, as an expiry dead end.
304
+ */
305
+ restoringEntryTarget(index) {
306
+ const q = this.items[index];
307
+ if (!q || !this.isItemLocked(q))
308
+ return { index, deadEnd: false };
309
+ const open = this.openItemAfterClosure(index);
310
+ return open >= 0 ? { index: open, deadEnd: false } : { index, deadEnd: true };
311
+ }
312
+ /** Flat indexes of the snapshot's visited item identifiers. */
313
+ visitedIndexes(identifiers) {
314
+ return (identifiers ?? [])
315
+ .map((id) => this.items.findIndex((q) => q.identifier === id))
316
+ .filter((index) => index >= 0);
317
+ }
318
+ /**
319
+ * Lock every scope whose restored clock already ran past its hard maximum (no late
320
+ * submission): its live expiry never fired in this runtime, so without this its items
321
+ * would reopen editable until the next tick. A whole-test limit that ran out marks the
322
+ * test expired. The live timer is told, so it does not fire these expiries again.
323
+ */
324
+ lockExpiredScopesFromClocks(timing) {
325
+ if (!timing)
326
+ return;
327
+ const extended = this.config.pnp?.content?.extendedTime;
328
+ const ranOut = (limits, elapsedMs) => scopeLimitRanOut(limits, elapsedMs, extended);
329
+ const expired = [];
330
+ const lock = (scope, identifier) => {
331
+ if (this.scopeLocks.lock(scope, identifier))
332
+ expired.push(scopeKey(scope, identifier));
333
+ };
334
+ for (const q of this.items) {
335
+ if (ranOut(q.testPart.timeLimits, timing.testPartTimes?.[q.testPart.identifier])) {
336
+ lock('testPart', q.testPart.identifier);
337
+ }
338
+ for (const section of q.sections) {
339
+ if (ranOut(section.timeLimits, timing.sectionTimes?.[section.identifier]))
340
+ lock('section', section.identifier);
341
+ }
342
+ if (ranOut(q.item.timeLimits, timing.itemTimes?.[q.identifier]))
343
+ lock('item', q.identifier);
85
344
  }
86
- else if (this.items.length > 0) {
87
- this.navigateTo(0, { restoring: true }).catch(() => { });
345
+ if (ranOut(this.assessment.timeLimits, timing.totalTime)) {
346
+ this.assessmentExpired = true;
347
+ expired.push('assessment');
88
348
  }
349
+ this.timeManager?.markExpired(expired);
350
+ }
351
+ /**
352
+ * A whole-test limit that ran out while the session was away finalizes like a live
353
+ * expiry — once delivery runs (not behind a begin gate, not during a pause), and on
354
+ * the next task so the shell's listeners hear it.
355
+ */
356
+ finalizeRestoredExpiryWhenRunning() {
357
+ if (!this.assessmentExpired || this.restoredExpiryFinalizeScheduled)
358
+ return;
359
+ if (this.finalized || this.destroyed || !this.started || this.paused)
360
+ return;
361
+ this.restoredExpiryFinalizeScheduled = true;
362
+ setTimeout(() => {
363
+ if (this.finalized || this.destroyed || !this.started || this.paused) {
364
+ this.restoredExpiryFinalizeScheduled = false;
365
+ return;
366
+ }
367
+ this.autoFinalizeForTimeExpiry();
368
+ }, 0);
369
+ }
370
+ recordEntryFailure(error) {
371
+ this.entryError = error instanceof Error ? error : new Error(String(error));
372
+ this.config.onError?.(this.entryError);
373
+ }
374
+ /** Whether the last item entry (the first item, or an expiry hop) failed. */
375
+ hasEntryFailure() {
376
+ return this.entryError !== null;
377
+ }
378
+ /** The failed item entry's error, for host logs and localized shell display. */
379
+ getEntryError() {
380
+ return this.entryError;
381
+ }
382
+ /**
383
+ * Retry the failed item entry: re-enter the initial item, or re-run the expiry hop
384
+ * that failed. Serialized with all other transitions; a renewed failure is reported
385
+ * through `onError` and this rejects.
386
+ */
387
+ async retryEntry() {
388
+ const target = this.pendingEntryIndex;
389
+ this.entryError = null;
390
+ if (target === null || target < 0 || this.destroyed)
391
+ return;
392
+ await this.runExclusive(async () => {
393
+ try {
394
+ await this.performNavigateTo(target, { restoring: true });
395
+ if (this.pendingEntryIndex === target)
396
+ this.pendingEntryIndex = null;
397
+ }
398
+ catch (error) {
399
+ // Still broken: the failure is recorded again (the shell's error screen
400
+ // stays) and the rejection surfaces to the caller.
401
+ this.recordEntryFailure(error);
402
+ throw error;
403
+ }
404
+ });
89
405
  }
90
406
  get state() {
91
407
  return this.sessionCoordinator.state;
92
408
  }
93
- set state(state) {
94
- this.sessionCoordinator.restoreState(state);
409
+ /**
410
+ * Whether a navigation or submission transition is currently in flight. Shells must
411
+ * disable navigation controls while this is set.
412
+ */
413
+ isBusy() {
414
+ return this.transitionInFlight;
95
415
  }
96
- getEffectiveItemTimeLimits(flat) {
97
- const scopes = [
98
- { source: 'assessment', limits: this.assessment.timeLimits },
99
- { source: 'testPart', limits: flat.testPart.timeLimits },
100
- { source: 'section', limits: flat.section.timeLimits },
101
- { source: 'item', limits: flat.item.timeLimits },
102
- ];
103
- let source;
104
- let minTime;
105
- let maxTime;
106
- let allowLateSubmission;
107
- for (const scope of scopes) {
108
- if (!scope.limits)
109
- continue;
110
- if (scope.limits.minTime !== undefined) {
111
- minTime = minTime === undefined ? scope.limits.minTime : Math.max(minTime, scope.limits.minTime);
416
+ /**
417
+ * Serialize navigation and submission transitions. Exactly one transition runs at a
418
+ * time; concurrent navigation or submit calls reject with a typed `navigationInFlight`
419
+ * error instead of racing the in-flight backend request. The in-flight flag is set
420
+ * inside the try so nothing before the operation — a throwing listener included —
421
+ * can leave it stuck true (every later transition would then be rejected as busy
422
+ * forever); the `finally` always resets it.
423
+ */
424
+ async runExclusive(operation) {
425
+ if (this.transitionInFlight) {
426
+ throw new AssessmentPlayerError('navigationInFlight', 'A navigation or submission transition is already in progress.');
427
+ }
428
+ try {
429
+ this.transitionInFlight = true;
430
+ this.notifyBusyChange(true);
431
+ return await operation();
432
+ }
433
+ finally {
434
+ this.transitionInFlight = false;
435
+ this.notifyBusyChange(false);
436
+ }
437
+ }
438
+ /**
439
+ * A candidate-initiated transition (navigation, submission): rejected with a coded
440
+ * error during a proctor pause or before the begin gate opens, otherwise serialized
441
+ * like every transition.
442
+ */
443
+ runCandidateTransition(operation) {
444
+ try {
445
+ this.assertCandidateActionAllowed();
446
+ }
447
+ catch (error) {
448
+ return Promise.reject(error);
449
+ }
450
+ return this.runExclusive(operation);
451
+ }
452
+ /** Whether a proctor pause is in force (owned by `PauseController`). */
453
+ get paused() {
454
+ return this.pauseControl.paused;
455
+ }
456
+ /** The candidate-facing reason given for the current pause, if any. */
457
+ get pauseReason() {
458
+ return this.pauseControl.reason;
459
+ }
460
+ assertCandidateActionAllowed() {
461
+ if (this.paused) {
462
+ throw new AssessmentPlayerError('assessmentPaused', 'The assessment is paused.');
463
+ }
464
+ if (!this.started) {
465
+ throw new AssessmentPlayerError('navigationNotAllowed', 'The assessment has not started yet.');
466
+ }
467
+ }
468
+ // ---------------------------------------------------------------------------
469
+ // Autosave: debounced draft persistence through BackendAdapter.saveState
470
+ // ---------------------------------------------------------------------------
471
+ /**
472
+ * Create the autosave engine. ON by default when the backend reports the save
473
+ * capability (`canSaveState !== false`); `config.autosave === false` disables it
474
+ * for hosts that persist state themselves.
475
+ */
476
+ createAutosave() {
477
+ this.autosave = createSessionAutosave({
478
+ autosave: this.config.autosave,
479
+ autosaveIntervalMs: this.config.autosaveIntervalMs,
480
+ canSaveState: this.backend.canSaveState,
481
+ sessionId: this.sessionId,
482
+ getSnapshot: () => this.getState({ includeItemSessions: true }),
483
+ snapshotsCloseItemSessions: () => this.snapshotsCloseItemSessions,
484
+ isBlocked: () => this.transitionInFlight,
485
+ isStopped: () => this.destroyed || this.finalized,
486
+ saveState: (request) => this.backend.saveState(request),
487
+ onStateChange: (state) => this.notifyAutosaveChange(state),
488
+ onError: (error) => this.config.onAutosaveFailed?.(error),
489
+ });
490
+ }
491
+ /** A due save is deferred while a transition runs and retried once it settles. */
492
+ notifyAutosaveActivity() {
493
+ this.autosave?.notify();
494
+ }
495
+ /**
496
+ * Save the current draft immediately (best-effort): the shell calls this from
497
+ * `visibilitychange`/`pagehide`, and hosts may call it before their own teardown.
498
+ * While a transition is in flight the save is re-queued instead of racing it.
499
+ * Resolves once a save attempt settled (or immediately when autosave is off).
500
+ */
501
+ flushAutosave() {
502
+ return this.autosave?.flush() ?? Promise.resolve();
503
+ }
504
+ /** The current save-indicator state (`idle` when autosave is disabled). */
505
+ getAutosaveState() {
506
+ return this.autosave?.getState() ?? { status: 'idle' };
507
+ }
508
+ /** Whether autosave is active for this session (backend capability + config). */
509
+ isAutosaveEnabled() {
510
+ return this.autosave !== null;
511
+ }
512
+ /** Fires on every save-indicator state change. */
513
+ onAutosaveChange(listener) {
514
+ return this.events.on('autosaveChange', listener);
515
+ }
516
+ notifyAutosaveChange(state) {
517
+ this.events.emit('autosaveChange', state);
518
+ this.config.onAutosaveChange?.(state);
519
+ }
520
+ // ---------------------------------------------------------------------------
521
+ // Resume + start over
522
+ // ---------------------------------------------------------------------------
523
+ /**
524
+ * Whether the session was created from a backend snapshot that already carries
525
+ * candidate work (a resume worth offering: saved answers). Shells show their
526
+ * resume prompt from this. Elapsed time alone does not count: a session that was
527
+ * merely started (or started over) has nothing to resume.
528
+ */
529
+ hasRestoredProgress() {
530
+ if (!this.restoredFromSnapshot)
531
+ return false;
532
+ const responses = this.state.itemResponses ?? {};
533
+ return Object.values(responses).some((responsesForItem) => responsesForItem !== undefined && Object.keys(responsesForItem).length > 0);
534
+ }
535
+ /** When the restored snapshot was last saved (client clock), for the resume prompt. */
536
+ getRestoredSavedAt() {
537
+ return this.hasRestoredProgress() ? this.restoredSavedAt : undefined;
538
+ }
539
+ /**
540
+ * Discard the candidate's draft and restart delivery. Start over clears what the
541
+ * candidate authored and the backend has not accepted — responses, flags, comments,
542
+ * visited state, the timer preference and unrecorded check state — and persists the
543
+ * blank draft at once. It keeps the time accounting: every clock, each expired scope
544
+ * and a whole-test expiry persist, so restarting never grants a fresh time allowance
545
+ * after the questions were seen. Items the backend already accepted keep their
546
+ * recorded results (the backend stays authoritative for them). Delivery repositions
547
+ * to the first item that is still open; when none is, the closed item is shown
548
+ * read-only and the expiry's submit path is requested again (`onTimeExpired` with
549
+ * `submissionRequired`). Rejects while paused, behind a begin gate, once finalized,
550
+ * and while another transition runs.
551
+ */
552
+ async startOver() {
553
+ return this.runCandidateTransition(async () => {
554
+ if (this.finalized) {
555
+ throw new AssessmentPlayerError('testFinalized', 'Cannot start over: the assessment has ended.');
112
556
  }
113
- if (scope.limits.maxTime !== undefined) {
114
- const scopedMaxTime = extendTimeLimit(scope.limits.maxTime, this.config.pnp?.content?.extendedTime);
115
- if (scopedMaxTime !== undefined && (maxTime === undefined || scopedMaxTime < maxTime)) {
116
- maxTime = scopedMaxTime;
117
- source = scope.source;
118
- allowLateSubmission = scope.limits.allowLateSubmission;
119
- }
557
+ const snapshot = this.getState({ includeItemSessions: true });
558
+ // Test parts are delivered in order and a left part is never re-entered — not
559
+ // even by a restart. The restart covers the furthest part reached and what
560
+ // follows; questions of parts already left stay closed exactly as they stand
561
+ // (the end of the test collects them so), visited marks included.
562
+ const reachedIndex = Math.max(this.currentItemIndex, ...this.navigationManager.getVisited(), 0);
563
+ const reachedPart = partOrderOf(this.assessment, this.items[reachedIndex]);
564
+ const left = new Set(this.items.filter((q) => partOrderOf(this.assessment, q) < reachedPart).map((q) => q.identifier));
565
+ // Accepted items keep their recorded state; everything else is the draft.
566
+ const accepted = new Set(this.items.filter((q) => this.sessionCoordinator.hasItemResult(q.identifier)).map((q) => q.identifier));
567
+ const keepAccepted = (record) => Object.fromEntries(Object.entries(record ?? {}).filter(([identifier]) => accepted.has(identifier) || left.has(identifier)));
568
+ const keepLeft = (record) => Object.fromEntries(Object.entries(record ?? {}).filter(([identifier]) => left.has(identifier)));
569
+ const fresh = {
570
+ currentItemIdentifier: this.items[0]?.identifier ?? '',
571
+ visitedItems: snapshot.visitedItems.filter((identifier) => left.has(identifier)),
572
+ itemResponses: keepAccepted(snapshot.itemResponses),
573
+ itemScores: keepAccepted(snapshot.itemScores),
574
+ itemSessions: keepAccepted(snapshot.itemSessions),
575
+ itemSessionStates: keepAccepted(snapshot.itemSessionStates),
576
+ itemFlags: keepLeft(snapshot.itemFlags),
577
+ itemComments: keepLeft(snapshot.itemComments),
578
+ // The clocks continue: the live TimeManager is not reset, and the draft's
579
+ // timing reflects it.
580
+ timing: snapshot.timing,
581
+ };
582
+ // Replaces coordinator state (responses, sessions, results, flags) and clears
583
+ // visited/navigation state beyond the left parts. Locked scopes, the whole-test
584
+ // expiry and the timer's fired-limit record stay as they are.
585
+ this.sessionCoordinator.restoreState(fresh);
586
+ this.navigationManager.restoreState(this.visitedIndexes(fresh.visitedItems));
587
+ // (A pause cannot be in force here: startOver is a candidate transition, and a
588
+ // pause requested while it runs applies once it settles.)
589
+ // The resumable draft is gone; the shell's resume prompt must not reappear.
590
+ this.restoredFromSnapshot = false;
591
+ this.restoredSavedAt = undefined;
592
+ // Unrecorded check state goes with the draft; the memory of accepted responses stays.
593
+ for (const identifier of [...this.lastSubmittedResponses.keys()]) {
594
+ if (!accepted.has(identifier))
595
+ this.lastSubmittedResponses.delete(identifier);
120
596
  }
121
- else if (scope.limits.allowLateSubmission !== undefined && maxTime === undefined) {
122
- allowLateSubmission = scope.limits.allowLateSubmission;
123
- source = scope.source;
597
+ this.lastItemFeedback = null;
598
+ this.templateDefaultsByPart.clear();
599
+ // Delivery repositions to the first open item of the furthest part reached (else
600
+ // the first open item after it); with none left, the expiry dead end: the
601
+ // candidate's way out is the submission.
602
+ const inReach = (q) => partOrderOf(this.assessment, q) >= reachedPart;
603
+ const inPart = this.items.findIndex((q) => partOrderOf(this.assessment, q) === reachedPart && this.isOpenTarget(q));
604
+ const firstOpen = inPart >= 0 ? inPart : this.items.findIndex((q) => partOrderOf(this.assessment, q) > reachedPart && !this.isItemLocked(q));
605
+ const target = firstOpen >= 0 ? firstOpen : Math.max(0, this.items.findIndex(inReach));
606
+ if (this.items[target]) {
607
+ this.sessionCoordinator.setCurrentItem(this.items[target].identifier);
608
+ await this.performNavigateTo(target, { restoring: true });
609
+ if (firstOpen < 0)
610
+ this.notifyExpiryDeadEnd();
124
611
  }
125
- }
126
- if (maxTime === undefined && minTime === undefined && allowLateSubmission === undefined) {
127
- return {};
128
- }
129
- return { source, timeLimits: { minTime, maxTime, allowLateSubmission } };
612
+ // Persist the blank draft now so a refresh cannot resurrect the discarded answers.
613
+ await this.autosave?.flushImmediate();
614
+ });
615
+ }
616
+ getEffectiveItemTimeLimits(flat) {
617
+ return effectiveItemTimeLimits(flat, this.assessment.timeLimits, this.config.pnp?.content?.extendedTime);
130
618
  }
131
619
  getCurrentEffectiveTimeLimits() {
132
620
  const q = this.items[this.currentItemIndex];
133
621
  return q ? this.getEffectiveItemTimeLimits(q) : {};
134
622
  }
135
- getSubmitTimingEvidence(q, elapsedMs) {
136
- const effective = this.getEffectiveItemTimeLimits(q);
137
- const limitSeconds = effective.timeLimits?.maxTime;
138
- if (!effective.source || limitSeconds === undefined)
139
- return undefined;
140
- const scopeIdentifier = effective.source === 'item'
141
- ? q.identifier
142
- : effective.source === 'section'
143
- ? q.section.identifier
144
- : effective.source === 'testPart'
145
- ? q.testPart.identifier
146
- : undefined;
147
- const tracked = this.timeManager?.getScopeElapsedMs(effective.source, scopeIdentifier);
148
- const scopedElapsedMs = tracked ?? elapsedMs;
149
- return {
150
- scope: effective.source,
151
- elapsedMs: scopedElapsedMs,
152
- limitSeconds,
153
- expired: scopedElapsedMs >= limitSeconds * 1000,
154
- allowLateSubmission: effective.timeLimits?.allowLateSubmission,
155
- };
623
+ getSubmitTimingEvidence(q, elapsedMs, submissionReason) {
624
+ return submitTimingEvidence({
625
+ q,
626
+ effective: this.getEffectiveItemTimeLimits(q),
627
+ elapsedMs,
628
+ scopeElapsedMs: (scope, identifier) => this.timeManager?.getScopeElapsedMs(scope, identifier),
629
+ assessmentLimitSeconds: this.assessment.timeLimits?.maxTime === undefined
630
+ ? undefined
631
+ : extendTimeLimit(this.assessment.timeLimits.maxTime, this.config.pnp?.content?.extendedTime),
632
+ assessmentElapsedMs: this.timeManager ? this.timeManager.getScopeElapsedMs('assessment') : undefined,
633
+ submissionReason,
634
+ });
156
635
  }
157
- assertMinimumTime(scope, q) {
636
+ assertMinimumTime(scope, q, section = q.section) {
158
637
  const limits = scope === 'assessment'
159
638
  ? this.assessment.timeLimits
160
639
  : scope === 'testPart'
161
640
  ? q.testPart.timeLimits
162
641
  : scope === 'section'
163
- ? q.section.timeLimits
642
+ ? section.timeLimits
164
643
  : q.item.timeLimits;
165
644
  if (limits?.minTime === undefined)
166
645
  return;
167
646
  const identifier = scope === 'testPart'
168
647
  ? q.testPart.identifier
169
648
  : scope === 'section'
170
- ? q.section.identifier
649
+ ? section.identifier
171
650
  : scope === 'item'
172
651
  ? q.identifier
173
652
  : undefined;
174
- const elapsedMs = this.timeManager?.getScopeElapsedMs(scope, identifier) ?? 0;
175
- if (elapsedMs < limits.minTime * 1000) {
176
- const remaining = Math.ceil(limits.minTime - elapsedMs / 1000);
177
- throw new Error(`The ${scope} minimum time has not elapsed (${remaining}s remaining).`);
653
+ assertMinTimeElapsed(scope, limits, this.timeManager?.getScopeElapsedMs(scope, identifier) ?? 0);
654
+ }
655
+ /**
656
+ * Every enclosing section's minimum time gates leaving it: a transition out of an
657
+ * enclosing scope (another section, another test part, or the end of the test) waits
658
+ * for the outer sections' minimums too, not only the innermost section's.
659
+ */
660
+ assertEnclosingSectionMinimumTime(q, target) {
661
+ for (const section of q.sections) {
662
+ if (target?.sections.some((enclosing) => enclosing.identifier === section.identifier))
663
+ continue;
664
+ this.assertMinimumTime('section', q, section);
178
665
  }
179
666
  }
180
667
  assertTransitionMinimum(current, target) {
181
668
  if (current === target)
182
669
  return;
183
670
  this.assertMinimumTime('item', current);
184
- if (current.section.identifier !== target.section.identifier)
185
- this.assertMinimumTime('section', current);
671
+ this.assertEnclosingSectionMinimumTime(current, target);
186
672
  if (current.testPart !== target.testPart)
187
673
  this.assertMinimumTime('testPart', current);
188
674
  }
189
- flattenItems(assessment) {
190
- const sectionIndexes = new Map(this.getAllSections().map((section) => [section.id, section.index]));
191
- return deliveredItems(assessment).map(({ item, testPart, sections }, index) => {
192
- const section = sections[sections.length - 1];
193
- return {
194
- identifier: item.identifier,
195
- item,
196
- section,
197
- sections,
198
- testPart,
199
- index,
200
- sectionIndex: sectionIndexes.get(section.identifier) ?? 0,
201
- };
675
+ /**
676
+ * Whether an item still owes the backend a submission: it has no recorded result yet
677
+ * (the candidate left it open, answered or not), or its live responses differ from the
678
+ * ones its last counted submission carried (a practice answer revised after the
679
+ * check, or a revised answer a nonlinear jump left behind). Unchanged responses are
680
+ * never re-sent, so an accepted item spends no extra attempt here.
681
+ */
682
+ itemNeedsSubmission(q) {
683
+ if (!this.sessionCoordinator.hasItemResult(q.identifier))
684
+ return true;
685
+ return !this.responsesUnchangedSinceSubmission(q.identifier, this.sessionCoordinator.getResponses(q.identifier));
686
+ }
687
+ isIndividual(q) {
688
+ return effectiveSubmissionMode(q.testPart, this.assessment) === 'individual';
689
+ }
690
+ /**
691
+ * Whether submissions carry the serialized item session: always for a backend that
692
+ * scores from it (`requiresItemSession` — the reference adapter: a templated item must be
693
+ * scored against the instance the candidate saw), else as the host configured.
694
+ */
695
+ sendsItemSession() {
696
+ return this.backend.requiresItemSession === true || this.config.sendItemSessionToBackend === true;
697
+ }
698
+ /** The item's current responses: the live session's for the active item, else the stored ones. */
699
+ currentResponsesFor(q) {
700
+ if (this.items[this.currentItemIndex] === q && this.currentItemSession) {
701
+ return cloneResponseRecord(this.currentItemSession.state().responses);
702
+ }
703
+ return this.sessionCoordinator.getResponses(q.identifier);
704
+ }
705
+ /**
706
+ * QTI itemSessionControl `allowSkipping` / `validateResponses` for one item's
707
+ * responses. Both are "only applicable when the item is in a testPart with individual
708
+ * submission mode", so a simultaneous part is never gated. A skipped item (no
709
+ * response at all: every response NULL, empty or still equal to its declared default —
710
+ * the test `numberResponded` applies) may be submitted only when skipping is allowed,
711
+ * and is then not validated; an answered item validates when the item asks for it.
712
+ */
713
+ submissionGate(q, responses) {
714
+ return submissionGatePolicy({
715
+ individual: this.isIndividual(q),
716
+ settings: this.sessionCoordinator.getItemSettings(q.identifier),
717
+ responses,
718
+ defaults: this.responseDefaultsFor(q),
719
+ });
720
+ }
721
+ /**
722
+ * The declared default of each response variable, as the item's own session holds it
723
+ * (template processing may set it): the live session for the active item, the persisted
724
+ * handoff otherwise, else — for an item never opened — a fresh session's declarations.
725
+ */
726
+ responseDefaultsFor(q) {
727
+ const live = this.items[this.currentItemIndex] === q ? this.currentItemSession : null;
728
+ const serialized = live ? live.serialize() : this.state.itemSessions?.[q.identifier];
729
+ if (serialized)
730
+ return responseDefaultsOf(serialized);
731
+ const cached = this.responseDefaultsCache.get(q.identifier);
732
+ if (cached)
733
+ return cached;
734
+ let defaults = {};
735
+ let session = null;
736
+ try {
737
+ session = this.getItemDefinition(q).openSession({});
738
+ defaults = responseDefaultsOf(session.serialize());
739
+ }
740
+ catch {
741
+ // An item that cannot even open has no defaults to honour; the gate stays NULL-based.
742
+ }
743
+ finally {
744
+ session?.dispose();
745
+ }
746
+ this.responseDefaultsCache.set(q.identifier, defaults);
747
+ return defaults;
748
+ }
749
+ /**
750
+ * The item's response validation (a QTI valid response: every value well-formed and,
751
+ * where an interaction requires input — minChoices, minStrings, matchMin… — complete),
752
+ * checked on a detached session so the live attempt is untouched. Null when nothing is
753
+ * left to validate: the attempt already closed (accepted as it is), or the session could
754
+ * not be opened (the submission reports that, the gate invents no failure).
755
+ */
756
+ responseValidationFor(q) {
757
+ const live = this.items[this.currentItemIndex] === q ? this.currentItemSession : null;
758
+ const restore = live ? live.serialize() : this.state.itemSessions?.[q.identifier];
759
+ let session = null;
760
+ try {
761
+ session = this.getItemDefinition(q).openSession({
762
+ restore,
763
+ responses: live ? undefined : this.sessionCoordinator.getResponses(q.identifier),
764
+ activate: true,
765
+ });
766
+ if (!isWritableItemLifecycle(session.state().lifecycleStatus))
767
+ return null;
768
+ const validation = session.dispatch({ action: 'suspendAttempt' }).result?.validation;
769
+ if (!validation)
770
+ return null;
771
+ const unmet = Object.values(validation.entries).find((entry) => !entry.valid || (entry.required && !entry.complete));
772
+ if (validation.valid && !unmet)
773
+ return { ok: true };
774
+ const constraint = unmet?.valid ? interactionRequirementFromXml(q.item.itemXml, unmet.responseId) : undefined;
775
+ return { ok: false, requirement: constraint ?? { kind: 'incomplete' } };
776
+ }
777
+ catch {
778
+ return null;
779
+ }
780
+ finally {
781
+ session?.dispose();
782
+ }
783
+ }
784
+ /** Whether the item's responses satisfy their interactions' constraints (see `responseValidationFor`). */
785
+ responsesSatisfyConstraints(q) {
786
+ return this.responseValidationFor(q)?.ok !== false;
787
+ }
788
+ /**
789
+ * Whether the end of the test would submit this item: mirrors `endTestInternal`'s
790
+ * collection — the open current item without an accepted (unchanged) result, and every
791
+ * visited individual-mode item whose responses the backend has not accepted yet.
792
+ */
793
+ wouldCollectAtFinalize(q) {
794
+ if (!this.isIndividual(q) || this.isItemLocked(q))
795
+ return false;
796
+ if (q.index === this.currentItemIndex) {
797
+ if (!this.sessionCoordinator.hasItemResult(q.identifier))
798
+ return true;
799
+ const status = this.currentItemSession?.state().lifecycleStatus;
800
+ return (status !== undefined &&
801
+ isWritableItemLifecycle(status) &&
802
+ this.sessionCoordinator.canSubmit(q.identifier) &&
803
+ !this.responsesUnchangedSinceSubmission(q.identifier));
804
+ }
805
+ return this.navigationManager.isVisited(q.index) && this.itemNeedsSubmission(q);
806
+ }
807
+ /**
808
+ * The QTI submission control that would refuse this item's submission now, if any:
809
+ * `required` (allowSkipping=false, no response) or `invalid` (validateResponses=true,
810
+ * responses that do not satisfy the interactions), with what the response still owes.
811
+ */
812
+ blockerFor(q) {
813
+ const gate = this.submissionGate(q, this.currentResponsesFor(q));
814
+ let reason = gate.mustAnswer ? 'required' : null;
815
+ let requirement;
816
+ if (!reason && gate.validate) {
817
+ const validation = this.responseValidationFor(q);
818
+ if (validation && !validation.ok) {
819
+ reason = 'invalid';
820
+ requirement = validation.requirement;
821
+ }
822
+ }
823
+ if (!reason)
824
+ return null;
825
+ return submissionBlockerFor(q, reason, requirement, this.isNavigationTargetLegal(q.index));
826
+ }
827
+ /** Every item the end of the test would collect against its submission controls, reachable or not. */
828
+ blockerCandidates(filter = () => true) {
829
+ if (this.finalized)
830
+ return [];
831
+ const blockers = [];
832
+ for (const q of this.items) {
833
+ if (!filter(q) || !this.wouldCollectAtFinalize(q))
834
+ continue;
835
+ const blocker = this.blockerFor(q);
836
+ if (blocker)
837
+ blockers.push(blocker);
838
+ }
839
+ return blockers;
840
+ }
841
+ /**
842
+ * Items a candidate-initiated end of the test would refuse to submit: in individual
843
+ * parts, an item without any response while `allowSkipping=false` (`required`), or an
844
+ * answered item whose responses fail validation while `validateResponses=true`
845
+ * (`invalid`). Only items the end of the test would actually submit are considered
846
+ * (presented ones the backend has not accepted), and only those the candidate can still
847
+ * reach: a question in a test part already left cannot hold Submit — it is collected as
848
+ * it stands (`getUnreachableSubmissionBlockers()`, `submissionReason: 'unreachable'`).
849
+ * An item an expired limit closed is collected as it stands too. Empty once the delivery
850
+ * is closed by time or finalized. Shells list these in the submit confirmation;
851
+ * `submit()` rejects naming them.
852
+ */
853
+ getSubmissionBlockers() {
854
+ if (this.isTimeClosedDelivery())
855
+ return [];
856
+ return this.blockerCandidates().filter((blocker) => blocker.reachable);
857
+ }
858
+ /**
859
+ * Questions the end of the test collects although their QTI skipping/validation control
860
+ * would refuse them, because the candidate can no longer reach them (their test part was
861
+ * left — a session restored from before the leave gate, a branch rule). They never hold
862
+ * Submit: the end of the test sends them as they stand with `submissionReason: 'unreachable'`.
863
+ */
864
+ getUnreachableSubmissionBlockers() {
865
+ return this.blockerCandidates().filter((blocker) => !blocker.reachable);
866
+ }
867
+ /**
868
+ * Questions of the current test part that would be left behind owing an answer: QTI
869
+ * parts cannot be re-entered, so leaving an individual part with them would strand them.
870
+ * The shell's "Leave this part?" confirmation lists them (with jumps) and holds Continue;
871
+ * `next()` / `navigateTo()` refuse to leave the part while any remains
872
+ * (`leavePartResponseRequired` / `leavePartResponseInvalid`). Only questions the
873
+ * candidate can still reach count — one behind them in a linear part (a session restored
874
+ * from before this gate) could never be answered, so it cannot hold the way out; the end
875
+ * of the test collects it as it stands (`unreachable`). Empty for a simultaneous part
876
+ * (QTI: the controls do not apply), once finalized, and in a time-closed delivery.
877
+ */
878
+ getTestPartBlockers() {
879
+ const current = this.items[this.currentItemIndex];
880
+ if (!current || this.isTimeClosedDelivery())
881
+ return [];
882
+ return this.blockerCandidates((q) => q.testPart === current.testPart).filter((blocker) => blocker.reachable);
883
+ }
884
+ /** Reject a candidate-initiated end of the test that would submit held-back items, naming them. */
885
+ assertNoSubmissionBlockers() {
886
+ this.throwForBlockers(this.getSubmissionBlockers(), 'finalize');
887
+ }
888
+ /**
889
+ * Reject leaving the test part `from` belongs to while questions in it (or, for an
890
+ * EXIT_SECTION, in the ended scope) still owe an answer the candidate can still give.
891
+ * `exclude` is the item the move itself submits (next() submits the current item before
892
+ * it moves). An unreachable question never holds the way out (see `getTestPartBlockers`).
893
+ */
894
+ assertCanLeaveScope(from, options = {}) {
895
+ if (!this.isIndividual(from))
896
+ return;
897
+ const inScope = options.scope ?? ((q) => q.testPart === from.testPart);
898
+ this.throwForBlockers(this.blockerCandidates((q) => q !== options.exclude && inScope(q)).filter((blocker) => blocker.reachable), 'leavePart');
899
+ }
900
+ throwForBlockers(blockers, context) {
901
+ throwForBlockers(blockers, context);
902
+ }
903
+ /**
904
+ * QTI feedback visibility is attempt-relative: with more than one attempt allowed,
905
+ * feedback for every non-final attempt must be shown; once the last attempt has
906
+ * ended, `showFeedback` governs. Adaptive items always show their feedback.
907
+ * `attemptsAfter` counts the attempts once the attempt being judged has ended.
908
+ */
909
+ feedbackVisible(q, attemptsAfter) {
910
+ const control = this.sessionCoordinator.getItemSettings(q.identifier);
911
+ const adaptive = isAdaptiveItemXml(q.item.itemXml);
912
+ return attemptFeedbackVisible({
913
+ showFeedback: control.showFeedback === true,
914
+ maxAttempts: resolveMaxAttempts(control, adaptive),
915
+ attempts: attemptsAfter,
916
+ adaptive,
917
+ });
918
+ }
919
+ /**
920
+ * Sections presented to the candidate: visible themselves and under visible ancestors.
921
+ * A QTI `visible="false"` section is not presented as a section — its content appears as
922
+ * part of the parent — so neither it nor its descendants surface a title here. Items
923
+ * inside keep being delivered in order.
924
+ */
925
+ presentedSectionList() {
926
+ return presentedSections(this.assessment);
927
+ }
928
+ /**
929
+ * Whether jumping to a presented section is legal right now: in linear navigation there
930
+ * is no jumping at all; in nonlinear navigation only sections of the current test part
931
+ * are reachable, never locked items or items review has closed. Finalized tests have no
932
+ * legal targets.
933
+ */
934
+ isLegalSectionTarget(section) {
935
+ return isLegalSectionTarget({
936
+ section,
937
+ items: this.items,
938
+ assessment: this.assessment,
939
+ finalized: this.finalized,
940
+ currentIndex: this.currentItemIndex,
941
+ isItemLocked: (q) => this.isItemLocked(q),
942
+ canReviewItem: (q) => this.canReviewItem(q),
202
943
  });
203
944
  }
204
945
  // ---------------------------------------------------------------------------
205
946
  // Public API used by components
206
947
  // ---------------------------------------------------------------------------
948
+ /**
949
+ * The assessmentTest `title` the backend returned, trimmed, or `undefined` when it
950
+ * has none. Shells fall back to a localized generic title, never the identifier.
951
+ */
952
+ getAssessmentTitle() {
953
+ const title = this.assessment.title?.trim();
954
+ return title ? title : undefined;
955
+ }
956
+ /**
957
+ * Candidate-facing sections: visible sections only (QTI `visible="false"` sections are
958
+ * not presented as sections and their titles never surface), each with whether jumping
959
+ * to it is legal right now for the current navigationMode.
960
+ */
207
961
  getAllSections() {
208
- const out = [];
209
- const seen = new Set();
210
- const visit = (section) => {
211
- // A keepTogether="false" section mixed into its parent's shuffle appears as several fragments.
212
- if (!seen.has(section.identifier)) {
213
- seen.add(section.identifier);
214
- out.push({ id: section.identifier, title: section.title, visible: section.visible, index: out.length });
215
- }
216
- for (const component of sectionComponents(section)) {
217
- if (component.type === 'section')
218
- visit(component.section);
962
+ return this.presentedSectionList().map((section, index) => ({
963
+ id: section.identifier,
964
+ title: section.title,
965
+ index,
966
+ navigable: this.isLegalSectionTarget(section),
967
+ }));
968
+ }
969
+ /**
970
+ * Whether jumping straight to a delivered item is legal right now: false once the test
971
+ * has finalized, and — for any item other than the current one — false while the target
972
+ * is time-locked, its review policy forbids returning, or the navigation rules (linear
973
+ * mode, test-part sequencing) do not reach it. The review screen renders illegal targets
974
+ * status-only; `navigateTo()` still enforces this authoritatively.
975
+ */
976
+ isNavigationTargetLegal(index) {
977
+ return this.isNavigationTargetLegalWith(index, this.lazyForward());
978
+ }
979
+ /** `isNavigationTargetLegal` with the forward step computed once for a batch of targets. */
980
+ isNavigationTargetLegalWith(index, forward) {
981
+ if (this.finalized || this.currentItemIndex < 0)
982
+ return false;
983
+ const target = this.items[index];
984
+ if (!target)
985
+ return false;
986
+ if (target !== this.items[this.currentItemIndex]) {
987
+ if (this.isItemLocked(target))
988
+ return false;
989
+ if (!this.canReviewItem(target))
990
+ return false;
991
+ if (!this.canNavigateByTestPart(index, this.currentItemIndex, forward))
992
+ return false;
993
+ }
994
+ return true;
995
+ }
996
+ reviewInfoFor(itemIdentifier) {
997
+ return this.reviewInfoCache.for(itemIdentifier);
998
+ }
999
+ /**
1000
+ * Answered / partially answered / unanswered for one delivered item, from its
1001
+ * candidate responses (one verdict per interaction for composite items). The single
1002
+ * definition of "answered" the review screen, section menu and submit confirmation share.
1003
+ */
1004
+ getItemAnswerStatus(itemIdentifier) {
1005
+ const info = this.reviewInfoFor(itemIdentifier);
1006
+ return itemAnswerStatus(this.sessionCoordinator.getResponses(itemIdentifier), info.responseIds);
1007
+ }
1008
+ /** How many delivered items carry a response (answered or partially answered). */
1009
+ getAnsweredItemCount() {
1010
+ return this.items.filter((item) => this.getItemAnswerStatus(item.identifier) !== 'unanswered').length;
1011
+ }
1012
+ /** Every delivered item as the review screen lists it: status, flag, visited, jump legality. */
1013
+ getReviewItems() {
1014
+ const forward = this.lazyForward();
1015
+ return this.items.map((item) => reviewItemRow(item, {
1016
+ title: this.reviewInfoFor(item.identifier).title,
1017
+ status: this.getItemAnswerStatus(item.identifier),
1018
+ flagged: this.sessionCoordinator.isItemFlagged(item.identifier),
1019
+ visited: this.navigationManager.isVisited(item.index) || item.index === this.currentItemIndex,
1020
+ jumpAllowed: this.isNavigationTargetLegalWith(item.index, forward),
1021
+ isCurrent: item.index === this.currentItemIndex,
1022
+ }));
1023
+ }
1024
+ /**
1025
+ * Candidate-facing results for a shell's opt-in completion summary: per delivered
1026
+ * item the answered status and — when the backend returned one — its score, plus the
1027
+ * finalized totals. Null until the assessment has been finalized; high-stakes hosts
1028
+ * simply never render it (the shell's `showResultsSummary` stays off by default).
1029
+ */
1030
+ getResultsSummary() {
1031
+ if (!this.finalized || !this.finalResults)
1032
+ return null;
1033
+ return resultsSummaryOf({
1034
+ items: this.items,
1035
+ results: this.finalResults,
1036
+ titleOf: (itemIdentifier) => this.reviewInfoFor(itemIdentifier).title,
1037
+ statusOf: (itemIdentifier) => this.getItemAnswerStatus(itemIdentifier),
1038
+ });
1039
+ }
1040
+ /**
1041
+ * What the candidate's next forward step would do. QTI test parts are delivered in
1042
+ * sequence and cannot be re-entered, so a step that leaves the current part is the
1043
+ * irreversible move the shell confirms before making.
1044
+ */
1045
+ getForwardTransitionInfo() {
1046
+ const current = this.items[this.currentItemIndex];
1047
+ if (!current || this.finalized)
1048
+ return { nextIndex: null, leavesTestPart: false };
1049
+ // A decision the backend made for this item and delivery has not followed yet (a
1050
+ // check's, a branch exit held back while questions of the part still owed an answer)
1051
+ // is what Next does now — unless Next re-submits a changed response, which decides anew.
1052
+ const kept = this.nextSubmits(current) ? null : this.keptBranchDecisionFor(current);
1053
+ if (kept) {
1054
+ const landing = branchLandingOf(kept, this.branchTargetIndex(current, kept));
1055
+ if (landing.kind !== 'skipped') {
1056
+ return {
1057
+ nextIndex: landing.kind === 'item' ? landing.index : null,
1058
+ leavesTestPart: this.branchExitLeavesPart(current, kept),
1059
+ };
219
1060
  }
220
- };
221
- for (const tp of this.assessment.testParts || []) {
222
- for (const section of tp.sections || [])
223
- visit(section);
1061
+ // A literal decision that resolves to nothing forward is skipped (the rule does
1062
+ // not fire): Next falls through to the delivery rules, so that is what the step
1063
+ // reports.
224
1064
  }
225
- return out;
1065
+ const nextIndex = this.forwardStepIndex(current);
1066
+ const next = nextIndex >= 0 ? this.items[nextIndex] : undefined;
1067
+ return {
1068
+ nextIndex: next ? nextIndex : null,
1069
+ leavesTestPart: Boolean(next && next.testPart !== current.testPart),
1070
+ };
1071
+ }
1072
+ /**
1073
+ * Set (or clear) the candidate's flag-for-review on an item; defaults to the current
1074
+ * item. Flag state lives in the session state (`itemFlags`), survives navigation and
1075
+ * is part of `getState()` snapshots.
1076
+ */
1077
+ setItemFlag(flagged, itemIdentifier) {
1078
+ const id = itemIdentifier ?? this.items[this.currentItemIndex]?.identifier;
1079
+ if (!id)
1080
+ return;
1081
+ this.sessionCoordinator.setItemFlag(id, flagged);
1082
+ this.events.emit('flagChange', id, flagged);
1083
+ // Flags are part of the persisted draft.
1084
+ this.notifyAutosaveActivity();
1085
+ }
1086
+ /** Toggle the current (or given) item's flag; returns the new state. */
1087
+ toggleItemFlag(itemIdentifier) {
1088
+ const id = itemIdentifier ?? this.items[this.currentItemIndex]?.identifier;
1089
+ if (!id)
1090
+ return false;
1091
+ const flagged = !this.sessionCoordinator.isItemFlagged(id);
1092
+ this.setItemFlag(flagged, id);
1093
+ return flagged;
1094
+ }
1095
+ isItemFlagged(itemIdentifier) {
1096
+ const id = itemIdentifier ?? this.items[this.currentItemIndex]?.identifier;
1097
+ return id ? this.sessionCoordinator.isItemFlagged(id) : false;
1098
+ }
1099
+ /** Identifiers of the items currently flagged for review. */
1100
+ getFlaggedItemIdentifiers() {
1101
+ return this.sessionCoordinator.getFlaggedItemIdentifiers();
1102
+ }
1103
+ /** Fires when an item's flag-for-review state changes. */
1104
+ onFlagChange(listener) {
1105
+ return this.events.on('flagChange', listener);
226
1106
  }
227
1107
  getNavigationState() {
1108
+ const presented = this.presentedSectionList();
1109
+ const sectionIndexes = new Map(presented.map((section, index) => [section.identifier, index]));
228
1110
  const total = this.items.length;
229
- const canPrevious = this.canPrevious();
230
- const canNext = this.canNext();
231
1111
  const q = this.items[this.currentItemIndex];
232
- const totalSections = this.getAllSections().length;
1112
+ const presentedSection = q ? presentedSectionOf(q.sections) : undefined;
233
1113
  return {
234
1114
  currentIndex: this.currentItemIndex,
235
1115
  totalItems: total,
236
- canNext,
237
- canPrevious,
238
- isLoading: false,
239
- currentSection: q
240
- ? { id: q.section.identifier, title: q.section.title, index: q.sectionIndex }
1116
+ canNext: !this.finalized && this.canNext(),
1117
+ canPrevious: !this.finalized && this.canPrevious(),
1118
+ isLoading: this.transitionInFlight,
1119
+ isComplete: this.finalized,
1120
+ currentSection: presentedSection
1121
+ ? {
1122
+ id: presentedSection.identifier,
1123
+ title: presentedSection.title,
1124
+ index: sectionIndexes.get(presentedSection.identifier) ?? -1,
1125
+ }
241
1126
  : undefined,
242
- totalSections,
1127
+ totalSections: presented.length,
243
1128
  };
244
1129
  }
245
1130
  getCurrentItem() {
@@ -248,7 +1133,7 @@ export class AssessmentPlayer {
248
1133
  return null;
249
1134
  return {
250
1135
  identifier: q.item.identifier,
251
- title: q.section.title,
1136
+ title: q.presentedSection?.title,
252
1137
  required: q.item.required,
253
1138
  itemXml: q.item.itemXml,
254
1139
  deliveryContext: q.item.deliveryContext,
@@ -277,13 +1162,42 @@ export class AssessmentPlayer {
277
1162
  href: itemRef.href,
278
1163
  title: itemRef.title,
279
1164
  itemXml: itemRef.itemXml,
280
- deliveryContext: cloneData(itemRef.deliveryContext),
1165
+ // Shared by reference, not cloned: the delivery context is a static
1166
+ // content record the backend returned, composition rebuilds share it so
1167
+ // unchanged items keep identical props, and callers treat it read-only.
1168
+ deliveryContext: itemRef.deliveryContext,
281
1169
  };
282
1170
  });
283
1171
  }
284
1172
  getResponsesForItem(itemIdentifier) {
285
1173
  return cloneData(this.sessionCoordinator.getResponses(itemIdentifier)) ?? {};
286
1174
  }
1175
+ /**
1176
+ * The assessment identifier the backend drew this session for (`SecureAssessment.identifier`).
1177
+ * Section tool bars and host integrations name the assessment with it.
1178
+ */
1179
+ getAssessmentId() {
1180
+ return this.assessment.identifier;
1181
+ }
1182
+ /**
1183
+ * The delivered items of the active item's innermost section, with their current
1184
+ * response records shared by reference (a shallow copy of the outer map only).
1185
+ * For section composition building: the values are read-only views of session
1186
+ * state and must not be mutated by callers — the deep-cloning accessors above
1187
+ * remain the boundary for persistence and events.
1188
+ */
1189
+ getSectionItemResponses() {
1190
+ const current = this.items[this.currentItemIndex];
1191
+ if (!current)
1192
+ return {};
1193
+ const out = {};
1194
+ for (const item of this.items) {
1195
+ if (item.section.identifier !== current.section.identifier)
1196
+ continue;
1197
+ out[item.identifier] = { ...this.sessionCoordinator.getResponses(item.identifier) };
1198
+ }
1199
+ return out;
1200
+ }
287
1201
  getCurrentSharedRubricBlocks() {
288
1202
  const q = this.items[this.currentItemIndex];
289
1203
  if (!q)
@@ -307,15 +1221,9 @@ export class AssessmentPlayer {
307
1221
  */
308
1222
  getVisibleFeedback() {
309
1223
  const outcomes = this.testOutcomes;
310
- const parts = this.assessment.testParts ?? [];
311
- const hasStructured = (this.assessment.testFeedback?.length ?? 0) > 0 || parts.some((part) => (part.testFeedback?.length ?? 0) > 0);
312
- if (!hasStructured) {
313
- return this.finalized && this.legacyFeedback
314
- ? [{ key: 'testFeedback', identifier: 'testFeedback', content: this.legacyFeedback, access: 'atEnd' }]
315
- : [];
316
- }
317
1224
  if (!outcomes)
318
1225
  return [];
1226
+ const parts = this.assessment.testParts ?? [];
319
1227
  const shown = [];
320
1228
  const add = (items, ended, current, part) => {
321
1229
  items?.forEach((fb, index) => {
@@ -329,6 +1237,7 @@ export class AssessmentPlayer {
329
1237
  content: fb.content,
330
1238
  access: fb.access,
331
1239
  ...(part ? { testPartIdentifier: part.identifier } : {}),
1240
+ ...(fb.language ? { language: fb.language } : {}),
332
1241
  });
333
1242
  });
334
1243
  };
@@ -347,12 +1256,15 @@ export class AssessmentPlayer {
347
1256
  if (!outcomes)
348
1257
  return;
349
1258
  this.testOutcomes = cloneData(outcomes);
1259
+ // The snapshot carries them: delivery rules read the same values after a restore.
1260
+ this.sessionCoordinator.setTestOutcomes(outcomes);
350
1261
  this.notifyTestFeedbackChange();
351
1262
  }
352
1263
  updateResponse(responseId, value) {
353
1264
  const active = this.items[this.currentItemIndex];
354
1265
  if (!active)
355
1266
  return;
1267
+ this.assertCandidateActionAllowed();
356
1268
  if (this.currentItemSession) {
357
1269
  this.currentItemSession.dispatch({
358
1270
  action: 'setResponse',
@@ -371,6 +1283,7 @@ export class AssessmentPlayer {
371
1283
  * the same responseIdentifier like "RESPONSE" across items).
372
1284
  */
373
1285
  updateResponseForItem(itemIdentifier, responseId, value) {
1286
+ this.assertCandidateActionAllowed();
374
1287
  const active = this.items[this.currentItemIndex];
375
1288
  if (active?.identifier === itemIdentifier && this.currentItemSession) {
376
1289
  const liveValue = this.currentItemSession.state().responses[responseId];
@@ -387,7 +1300,7 @@ export class AssessmentPlayer {
387
1300
  }
388
1301
  const persisted = this.sessionCoordinator.getPersistedItemSession(itemIdentifier);
389
1302
  if (persisted && !isWritableItemLifecycle(persisted.lifecycleStatus)) {
390
- throw new Error(`Cannot update responses while item session is ${persisted.lifecycleStatus}`);
1303
+ throw new AssessmentPlayerError('itemSessionLocked', `Cannot update responses while item session is ${persisted.lifecycleStatus}`, { status: persisted.lifecycleStatus });
391
1304
  }
392
1305
  this.sessionCoordinator.updateResponseForItem(itemIdentifier, responseId, value);
393
1306
  this.notifyResponseChange();
@@ -415,19 +1328,28 @@ export class AssessmentPlayer {
415
1328
  this.sessionCoordinator.saveItemSession(q.identifier, responses, itemSession, transition?.current.duration ?? currentView.duration);
416
1329
  return itemSession;
417
1330
  }
418
- endItemSessionForSubmit(q, responses, itemSession) {
419
- const validateResponses = this.sessionCoordinator.mustValidateResponses(q.identifier);
1331
+ endItemSessionForSubmit(q, responses, itemSession, options = {}) {
1332
+ // Responses frozen by an expired time limit are final as they stand: validation
1333
+ // cannot ask the candidate to correct them any more.
1334
+ const validateResponses = options.validate !== false && this.sessionCoordinator.mustValidateResponses(q.identifier);
420
1335
  const endAttempt = (session) => {
1336
+ // A session whose attempt already ended contributes its accepted state unchanged;
1337
+ // dispatching another end-attempt on it would throw and fail the final submission.
1338
+ if (!isWritableItemLifecycle(session.state().lifecycleStatus)) {
1339
+ return session.serialize();
1340
+ }
421
1341
  const result = session.dispatch({ action: 'endAttempt', validateResponses }).result;
422
1342
  if (result?.validation && !result.validation.valid) {
423
- throw new Error(result.validation.issues[0]?.message || `Submit failed: invalid response for item ${q.identifier}`);
1343
+ // Coded, naming the item, so a shell shows which question to fix instead of a
1344
+ // generic failure that no retry can clear.
1345
+ throw new AssessmentPlayerError('finalizeResponseInvalid', result.validation.issues[0]?.message || `Submit failed: invalid response for item ${q.identifier}`, { items: String(q.index + 1), itemIdentifiers: q.identifier, count: 1 });
424
1346
  }
425
1347
  return result?.sessionState ?? session.serialize();
426
1348
  };
427
1349
  const active = this.items[this.currentItemIndex];
428
1350
  if (active === q &&
429
1351
  this.currentItemSession &&
430
- this.currentItemSession.state().lifecycleStatus !== 'suspended') {
1352
+ isWritableItemLifecycle(this.currentItemSession.state().lifecycleStatus)) {
431
1353
  return endAttempt(this.currentItemSession);
432
1354
  }
433
1355
  const session = this.getItemDefinition(q).openSession({
@@ -442,6 +1364,38 @@ export class AssessmentPlayer {
442
1364
  session.dispose();
443
1365
  }
444
1366
  }
1367
+ /**
1368
+ * How an item presents feedback and solutions under its resolved item session
1369
+ * control, for its current attempt count (feedback visibility is attempt-relative,
1370
+ * see `feedbackVisible`).
1371
+ */
1372
+ presentationFor(q, attemptsAfter = this.sessionCoordinator.getItemSessionInfo(q.identifier).attemptCount) {
1373
+ const control = this.sessionCoordinator.getItemSettings(q.identifier);
1374
+ return {
1375
+ showFeedback: this.feedbackVisible(q, attemptsAfter),
1376
+ showSolution: control.showSolution === true,
1377
+ };
1378
+ }
1379
+ /**
1380
+ * A counted submission can change what the item shows: feedback a non-final attempt
1381
+ * revealed hides once the last attempt ended (unless showFeedback is on), and the
1382
+ * first non-final attempt reveals it. Reopen the live session under the new policy
1383
+ * when it differs; the item stays where it is.
1384
+ */
1385
+ refreshLivePresentation(q, itemSession) {
1386
+ const live = this.currentItemSession;
1387
+ if (!live || this.items[this.currentItemIndex] !== q)
1388
+ return;
1389
+ const next = this.presentationFor(q);
1390
+ const current = this.liveSessionPresentation ?? { showFeedback: true, showSolution: false };
1391
+ if (current.showFeedback === next.showFeedback && current.showSolution === next.showSolution)
1392
+ return;
1393
+ const restore = isWritableItemLifecycle(live.state().lifecycleStatus) ? live.serialize() : (itemSession ?? live.serialize());
1394
+ const session = this.getItemDefinition(q).openSession({ restore, presentation: next });
1395
+ this.releaseCurrentItemSession();
1396
+ this.attachCurrentItemSession(q, session, next);
1397
+ this.notifyItemChange();
1398
+ }
445
1399
  getItemDefinition(q) {
446
1400
  const cached = this.itemDefinitions.get(q.identifier);
447
1401
  if (cached)
@@ -457,27 +1411,78 @@ export class AssessmentPlayer {
457
1411
  pci: this.config.pci,
458
1412
  plugins: this.config.plugins,
459
1413
  deliveryContext: q.item.deliveryContext,
1414
+ ...(this.config.stringComparison ? { stringComparison: this.config.stringComparison } : {}),
460
1415
  });
461
1416
  this.itemDefinitions.set(q.identifier, definition);
462
1417
  return definition;
463
1418
  }
464
1419
  mirrorSessionResponses(itemIdentifier, responses) {
465
- const current = this.sessionCoordinator.getResponses(itemIdentifier);
466
- if (responseValuesEqual(current, responses))
467
- return false;
468
- const snapshot = cloneResponseRecord(responses);
469
- this.state.itemResponses[itemIdentifier] = snapshot;
470
- this.sessionCoordinator.markAnswered(itemIdentifier, snapshot);
471
- return true;
1420
+ return this.sessionCoordinator.mirrorResponses(itemIdentifier, responses);
472
1421
  }
473
- attachCurrentItemSession(q, session) {
1422
+ attachCurrentItemSession(q, session, presentation) {
474
1423
  this.currentItemSession = session;
1424
+ this.liveSessionPresentation = presentation ?? null;
475
1425
  this.currentItemSessionUnsubscribe = session.subscribe((transition) => {
476
1426
  if (this.currentItemSession !== session)
477
1427
  return;
478
1428
  if (this.mirrorSessionResponses(q.identifier, transition.current.responses)) {
479
1429
  this.notifyResponseChange();
480
1430
  }
1431
+ this.scheduleEndAttemptSubmission(q, session, transition);
1432
+ });
1433
+ }
1434
+ /** The item's endAttemptInteraction bindings, parsed from its item XML once and cached. */
1435
+ endAttemptResponseMap(q) {
1436
+ let map = this.endAttemptResponses.get(q.identifier);
1437
+ if (!map) {
1438
+ map = new Map();
1439
+ for (const info of endAttemptInteractionInfo(q.item.itemXml)) {
1440
+ map.set(info.responseIdentifier, info.countAttempt);
1441
+ }
1442
+ this.endAttemptResponses.set(q.identifier, map);
1443
+ }
1444
+ return map;
1445
+ }
1446
+ /**
1447
+ * QTI endAttempt on the response path: a candidate activating an endAttemptInteraction writes
1448
+ * its boolean response. Assessment delivery decides what that means — the item session is
1449
+ * owned here and must never be closed by a renderer. In a simultaneous test part the response
1450
+ * processing is deferred to the end of the part, so the response is recorded like any other.
1451
+ * In an individual test part the item is submitted through the normal per-item path with the
1452
+ * interaction's countAttempt honored; the candidate stays on the item.
1453
+ */
1454
+ scheduleEndAttemptSubmission(q, session, transition) {
1455
+ const command = transition.command;
1456
+ if (command.action !== 'setResponse')
1457
+ return;
1458
+ const responseId = command.responseIdentifier;
1459
+ // Only the change to true activates the interaction; re-writing the value is inert.
1460
+ if (transition.current.responses[responseId] !== true || transition.previous.responses[responseId] === true) {
1461
+ return;
1462
+ }
1463
+ const countAttempt = this.endAttemptResponseMap(q).get(responseId);
1464
+ if (countAttempt === undefined)
1465
+ return;
1466
+ if (effectiveSubmissionMode(q.testPart, this.assessment) !== 'individual')
1467
+ return;
1468
+ queueMicrotask(() => {
1469
+ void this.runExclusive(async () => {
1470
+ if (this.destroyed ||
1471
+ this.finalized ||
1472
+ this.currentItemSession !== session ||
1473
+ this.items[this.currentItemIndex] !== q) {
1474
+ return;
1475
+ }
1476
+ if (!isWritableItemLifecycle(session.state().lifecycleStatus))
1477
+ return;
1478
+ await this.submitCurrentItemInternal({ countAttempt, followBranching: false });
1479
+ }).catch((error) => {
1480
+ // A concurrent navigation or submission owns the transition; its own path submits
1481
+ // this response. Anything else surfaces to the host without breaking delivery.
1482
+ if (isAssessmentPlayerError(error) && error.code === 'navigationInFlight')
1483
+ return;
1484
+ this.config.onError?.(error instanceof Error ? error : new Error(String(error)));
1485
+ });
481
1486
  });
482
1487
  }
483
1488
  releaseCurrentItemSession() {
@@ -486,16 +1491,60 @@ export class AssessmentPlayer {
486
1491
  this.currentItemSession?.dispose();
487
1492
  this.currentItemSession = null;
488
1493
  }
1494
+ /**
1495
+ * Freeze the live attempt for a proctor pause: suspend it (its responses become
1496
+ * read-only and its QTI `duration` is captured in the persisted snapshot). The
1497
+ * suspended session stays attached so the item keeps rendering, disabled, behind the
1498
+ * pause; `reopenLiveSessionAfterPause()` reopens it from the snapshot so the paused
1499
+ * time never counts as time on task.
1500
+ */
1501
+ suspendLiveSessionForPause() {
1502
+ if (this.suspendedForPause)
1503
+ return;
1504
+ const session = this.currentItemSession;
1505
+ if (!session || !isWritableItemLifecycle(session.state().lifecycleStatus))
1506
+ return;
1507
+ this.saveCurrentItemSession();
1508
+ this.suspendedForPause = true;
1509
+ }
1510
+ /** Reopen the attempt a proctor pause froze, at the exact state the pause captured. */
1511
+ reopenLiveSessionAfterPause() {
1512
+ if (!this.suspendedForPause)
1513
+ return;
1514
+ this.suspendedForPause = false;
1515
+ const q = this.items[this.currentItemIndex];
1516
+ const snapshot = q ? this.state.itemSessions?.[q.identifier] : undefined;
1517
+ if (!q || !snapshot)
1518
+ return;
1519
+ this.releaseCurrentItemSession();
1520
+ const presentation = this.presentationFor(q);
1521
+ this.attachCurrentItemSession(q, this.getItemDefinition(q).openSession({
1522
+ restore: snapshot,
1523
+ activate: true,
1524
+ presentation,
1525
+ }), presentation);
1526
+ }
489
1527
  /**
490
1528
  * Get the current session state snapshot (client-side view).
491
1529
  * Note: backend remains authoritative; this is intended for simple save/resume.
492
1530
  */
493
1531
  getState(options = {}) {
494
1532
  const snapshot = this.sessionCoordinator.snapshot(options);
1533
+ // Every item the candidate has been presented is visited (not only submitted ones),
1534
+ // so the review screen's "not yet visited" marks survive a reload.
1535
+ const visited = new Set(snapshot.visitedItems);
1536
+ for (const index of this.navigationManager.getVisited()) {
1537
+ const identifier = this.items[index]?.identifier;
1538
+ if (identifier)
1539
+ visited.add(identifier);
1540
+ }
1541
+ snapshot.visitedItems = this.items.map((q) => q.identifier).filter((identifier) => visited.has(identifier));
495
1542
  const current = this.items[this.currentItemIndex];
496
- if (options.includeItemSessions && current && this.currentItemSession) {
1543
+ if (options.includeItemSessions && current && this.currentItemSession && !this.paused) {
497
1544
  // Navigation snapshots may predate edits made after revisiting this item.
498
1545
  // Serialize the live authority without suspending the learner's attempt.
1546
+ // (While paused, the snapshot taken at the pause is current: serializing the
1547
+ // suspended session would count the paused time as time on task.)
499
1548
  snapshot.itemSessions = {
500
1549
  ...snapshot.itemSessions,
501
1550
  [current.identifier]: this.currentItemSession.serialize(),
@@ -512,7 +1561,10 @@ export class AssessmentPlayer {
512
1561
  currentItemIdentifier: timing.currentItemId,
513
1562
  currentSectionIdentifier: timing.currentSectionId,
514
1563
  currentTestPartIdentifier: timing.currentTestPartId,
515
- isPaused: timing.isPaused,
1564
+ // The proctor pause, not the begin gate's hold: a restored snapshot reopens
1565
+ // paused only when a proctor paused it.
1566
+ isPaused: this.paused,
1567
+ ...(this.paused && this.pauseReason ? { pauseReason: this.pauseReason } : {}),
516
1568
  };
517
1569
  }
518
1570
  return snapshot;
@@ -520,22 +1572,54 @@ export class AssessmentPlayer {
520
1572
  /**
521
1573
  * Restore a previously saved session state.
522
1574
  */
523
- async restoreState(state) {
524
- this.state = state;
525
- this.restoreTimeTracking(state.timing);
526
- // Restore visited state for UI navigation hints.
527
- const visitedIdx = (state.visitedItems || [])
528
- .map((id) => this.items.findIndex((q) => q.identifier === id))
529
- .filter((i) => i >= 0);
530
- this.navigationManager.restoreState(visitedIdx);
531
- const currentId = state.currentItemIdentifier;
532
- const idx = currentId ? this.items.findIndex((q) => q.identifier === currentId) : -1;
533
- if (idx >= 0) {
534
- await this.navigateTo(idx, { restoring: true });
535
- }
536
- else if (this.items.length > 0) {
537
- await this.navigateTo(0, { restoring: true });
538
- }
1575
+ restoreState(state) {
1576
+ return this.runExclusive(async () => {
1577
+ this.sessionCoordinator.restoreState(state);
1578
+ this.seedSubmittedResponses(state);
1579
+ this.restoreTimeTracking(state.timing);
1580
+ // The snapshot's clocks are the time accounting from here on: expiries are
1581
+ // recomputed from them before any item is entered, so a scope that already ran
1582
+ // out never reopens editable (and one that has not is not held locked).
1583
+ this.scopeLocks.clear();
1584
+ this.assessmentExpired = false;
1585
+ this.restoredExpiryFinalizeScheduled = false;
1586
+ this.timeManager?.resetExpiryRecord();
1587
+ this.lockExpiredScopesFromClocks(state.timing);
1588
+ this.templateDefaultsByPart.clear();
1589
+ // The snapshot replaces delivery — kept branch decisions included, so a restored
1590
+ // session lands identically (a snapshot from before the feature simply carries
1591
+ // none). The test outcomes ride it too: the delivery rules read the values the
1592
+ // session's submissions produced, as the live session did. The snapshot carries
1593
+ // the proctor pause; the begin gate keeps holding the clocks.
1594
+ this.testOutcomes = state.testOutcomes ? cloneData(state.testOutcomes) : null;
1595
+ const pauseChanged = this.pauseControl.setFromRestore(state.timing?.isPaused === true, state.timing?.pauseReason);
1596
+ if (!this.started)
1597
+ this.timeManager?.pause();
1598
+ // Restore visited state for UI navigation hints.
1599
+ this.navigationManager.restoreState(this.visitedIndexes(state.visitedItems));
1600
+ // Behind a begin gate no item is entered yet: start() enters the restored one.
1601
+ let deadEnd = false;
1602
+ if (this.started) {
1603
+ const currentId = state.currentItemIdentifier;
1604
+ const idx = currentId ? this.items.findIndex((q) => q.identifier === currentId) : -1;
1605
+ const requested = idx >= 0 ? idx : this.items.length > 0 ? 0 : -1;
1606
+ if (requested >= 0) {
1607
+ const entry = this.restoringEntryTarget(requested);
1608
+ deadEnd = entry.deadEnd;
1609
+ await this.performNavigateTo(entry.index, { restoring: true });
1610
+ }
1611
+ // The (re-)entry succeeded: a previous entry failure is repaired.
1612
+ this.entryError = null;
1613
+ this.pendingEntryIndex = null;
1614
+ }
1615
+ if (pauseChanged)
1616
+ this.notifyPauseChange();
1617
+ if (deadEnd)
1618
+ this.notifyExpiryDeadEnd();
1619
+ this.finalizeRestoredExpiryWhenRunning();
1620
+ // A host-restored snapshot is the new draft; the save runs once this settles.
1621
+ this.notifyAutosaveActivity();
1622
+ });
539
1623
  }
540
1624
  restoreTimeTracking(timing) {
541
1625
  this.timeManager?.restoreState({
@@ -550,29 +1634,47 @@ export class AssessmentPlayer {
550
1634
  isPaused: timing.isPaused === true,
551
1635
  });
552
1636
  }
553
- async navigateTo(index, options = {}) {
554
- if (index < 0 || index >= this.items.length)
555
- throw new Error(`Invalid item index: ${index}`);
1637
+ /**
1638
+ * Navigate to an item by index. Serialized with all other navigation and submission
1639
+ * transitions: while one is in flight this rejects with a `navigationInFlight` error,
1640
+ * and once the test has finalized it rejects with `testFinalized`.
1641
+ */
1642
+ navigateTo(index, options = {}) {
1643
+ return this.runCandidateTransition(() => this.performNavigateTo(index, options));
1644
+ }
1645
+ async performNavigateTo(index, options = {}) {
1646
+ if (index < 0 || index >= this.items.length) {
1647
+ throw new AssessmentPlayerError('invalidNavigationTarget', `Invalid item index: ${index}`, { index });
1648
+ }
1649
+ if (this.finalized && !options.restoring) {
1650
+ throw new AssessmentPlayerError('testFinalized', 'Cannot navigate: the assessment has ended.');
1651
+ }
556
1652
  // Enforce navigation rules (UI hints, still backend-authoritative for real deployments).
557
1653
  if (!options.restoring && this.currentItemIndex >= 0 && !this.canNavigateByTestPart(index, this.currentItemIndex)) {
558
1654
  const currentMode = this.items[this.currentItemIndex]?.testPart.navigationMode ?? this.assessment.navigationMode;
559
1655
  if (currentMode === 'linear' && index > this.nextUnlockedIndex(this.currentItemIndex)) {
560
- throw new Error('In linear navigation mode, you can only move to the next question.');
1656
+ throw new AssessmentPlayerError('linearNavigationOnly', 'In linear navigation mode, you can only move to the next question.');
561
1657
  }
562
- throw new Error('Navigation is not allowed.');
1658
+ throw new AssessmentPlayerError('navigationNotAllowed', 'Navigation is not allowed.');
563
1659
  }
564
1660
  const target = this.items[index];
565
1661
  if (!options.restoring && target && this.isItemLocked(target)) {
566
- throw new Error('The time limit for this question has expired.');
1662
+ throw new AssessmentPlayerError('itemTimeExpired', 'The time limit for this question has expired.');
567
1663
  }
568
- if (!options.restoring && target && !this.sessionCoordinator.canReview(target.identifier)) {
569
- throw new Error('You cannot go back to previous questions in this assessment.');
1664
+ if (!options.restoring && target && !this.canReviewItem(target)) {
1665
+ throw new AssessmentPlayerError('reviewNotAllowed', 'You cannot go back to previous questions in this assessment.');
570
1666
  }
571
1667
  const currentItem = this.items[this.currentItemIndex];
572
1668
  if (!options.restoring && currentItem && target) {
573
1669
  this.assertTransitionMinimum(currentItem, target);
574
- if (currentItem.testPart !== target.testPart
575
- && (currentItem.testPart.submissionMode ?? this.assessment.submissionMode) === 'simultaneous') {
1670
+ // QTI parts cannot be re-entered: a candidate-initiated step into the next part
1671
+ // refuses while questions of the current part still owe an answer (a left part
1672
+ // can never be revisited, and the end of the test only collects unreachable
1673
+ // questions as they stand). The move's own submission already ran for next();
1674
+ // a direct jump leaves the current item behind, so it is included here.
1675
+ if (target.testPart !== currentItem.testPart)
1676
+ this.assertCanLeaveScope(currentItem);
1677
+ if (target.testPart !== currentItem.testPart && effectiveSubmissionMode(currentItem.testPart, this.assessment) === 'simultaneous') {
576
1678
  // Commit this part before leaving it; a failed request keeps the learner
577
1679
  // in the current part so its remaining answers can be retried.
578
1680
  await this.submitSimultaneousItems(this.items.filter((q) => q.testPart === currentItem.testPart));
@@ -595,117 +1697,639 @@ export class AssessmentPlayer {
595
1697
  this.timeManager?.endItem(currentItem.identifier);
596
1698
  }
597
1699
  this.currentItemIndex = index;
1700
+ this.navigationManager.markVisited(index);
598
1701
  const q = this.items[index];
599
- this.state.currentItemIdentifier = q.identifier;
1702
+ this.sessionCoordinator.setCurrentItem(q.identifier);
600
1703
  this.timeManager?.activateScopes({
601
1704
  testPart: { identifier: q.testPart.identifier, timeLimits: q.testPart.timeLimits },
602
1705
  section: { identifier: q.section.identifier, timeLimits: q.section.timeLimits },
1706
+ // Every enclosing section runs its own clock, outermost first.
1707
+ sections: q.sections.map((section) => ({
1708
+ identifier: section.identifier,
1709
+ timeLimits: section.timeLimits,
1710
+ })),
603
1711
  item: { identifier: q.identifier, timeLimits: q.item.timeLimits },
604
1712
  });
605
1713
  // Restore responses into one live session owned by the assessment. The section
606
1714
  // composition and item renderer receive this exact object.
607
1715
  const responses = this.sessionCoordinator.activateItem(q.identifier);
608
1716
  const restoredItemSession = this.state.itemSessions?.[q.identifier];
609
- const control = this.sessionCoordinator.getItemSettings(q.identifier);
610
1717
  this.releaseCurrentItemSession();
1718
+ const presentation = this.presentationFor(q);
611
1719
  const session = this.getItemDefinition(q).openSession({
612
1720
  restore: restoredItemSession,
613
1721
  responses: restoredItemSession ? undefined : responses,
614
1722
  activate: true,
615
- templateDefaults: restoredItemSession ? undefined : this.evaluateTemplateDefaults(q),
616
- presentation: {
617
- // Feedback during an adaptive item's attempts is part of the item, whatever showFeedback says.
618
- showFeedback: control.showFeedback === true || isAdaptiveItemXml(q.item.itemXml),
619
- showSolution: control.showSolution === true,
620
- },
1723
+ templateDefaults: restoredItemSession ? undefined : this.templateDefaultsFor(q),
1724
+ presentation,
621
1725
  });
622
- this.attachCurrentItemSession(q, session);
1726
+ this.attachCurrentItemSession(q, session, presentation);
1727
+ this.suspendedForPause = false;
1728
+ // An expired limit closed this item (a restoring entry at an expiry dead end, or a
1729
+ // branch into a closed scope): it shows read-only, never editable.
1730
+ if (this.isItemLocked(q))
1731
+ this.saveCurrentItemSession();
1732
+ // Entered during a proctor pause (a restore, or a held start): the attempt stays frozen.
1733
+ if (this.paused)
1734
+ this.suspendLiveSessionForPause();
623
1735
  this.notifyItemChange();
624
1736
  this.notifySectionChange();
625
1737
  if (currentItem?.testPart.identifier !== q.testPart.identifier)
626
1738
  this.notifyTestFeedbackChange();
627
1739
  }
628
- async navigateToSection(sectionId) {
629
- const idx = this.items.findIndex((q) => q.section.identifier === sectionId);
630
- if (idx >= 0)
631
- await this.navigateTo(idx);
1740
+ /**
1741
+ * Navigate to a section by identifier. Legal targets only: a presented (visible)
1742
+ * section reachable under the current navigationMode. Illegal jumps reject with a
1743
+ * typed `AssessmentPlayerError` instead of throwing plain errors.
1744
+ */
1745
+ navigateToSection(sectionId) {
1746
+ return this.runCandidateTransition(async () => {
1747
+ if (this.finalized) {
1748
+ throw new AssessmentPlayerError('testFinalized', `Cannot navigate to section "${sectionId}": the assessment has ended.`);
1749
+ }
1750
+ const idx = this.items.findIndex((q) => q.sections.some((s) => s.identifier === sectionId));
1751
+ if (idx < 0) {
1752
+ throw new AssessmentPlayerError('invalidNavigationTarget', `Unknown section: ${sectionId}`, { sectionId });
1753
+ }
1754
+ const presented = this.presentedSectionList().find((s) => s.identifier === sectionId);
1755
+ if (!presented || !this.isLegalSectionTarget(presented)) {
1756
+ throw new AssessmentPlayerError('navigationNotAllowed', `Navigation to section "${sectionId}" is not allowed.`, { sectionId });
1757
+ }
1758
+ await this.performNavigateTo(idx);
1759
+ });
632
1760
  }
633
- async next() {
634
- const state = this.getNavigationState();
635
- if (!state.canNext)
1761
+ /** Move forward. Serialized with all other transitions; rejects as busy while one is in flight. */
1762
+ next() {
1763
+ return this.runCandidateTransition(() => this.performNext());
1764
+ }
1765
+ async performNext() {
1766
+ const q = this.items[this.currentItemIndex];
1767
+ if (!q || this.finalized)
636
1768
  return;
1769
+ const responses = this.sessionCoordinator.getActiveResponses();
1770
+ // In individual submission mode the move submits the current item unless its attempts
1771
+ // are used up, it is already closed, or its recorded result already carries these exact
1772
+ // responses (a practice item moved on unchanged): the backend then decides where it goes.
1773
+ const submits = this.nextSubmits(q, responses);
1774
+ // A move that submits nothing follows the backend's decision kept for this item (a
1775
+ // check's, an end-attempt's, a branch exit held back, an end of the test that did not
1776
+ // complete); with none on record, the delivery rules decide (`ruleForwardIndex`).
1777
+ const kept = submits ? null : this.keptBranchDecisionFor(q);
1778
+ // Next from a simultaneous part's last item always crosses (or ends the test): the
1779
+ // part commits at the crossing, and only then is a decision on record to follow.
1780
+ const crossesSimultaneousPart = !submits && !kept && this.crossingFlushDue(q);
1781
+ // On a crossing the pre-flush rule result is provisional: the flush can still change
1782
+ // the outcomes the rules read, so the landing is computed again after it.
1783
+ const forward = crossesSimultaneousPart
1784
+ ? this.nextUnlockedIndex(q.index)
1785
+ : submits
1786
+ ? this.nextUnlockedIndex(q.index)
1787
+ : kept
1788
+ ? -1
1789
+ : this.ruleForwardIndex(q);
1790
+ if (!kept && forward < 0 && !crossesSimultaneousPart)
1791
+ return;
1792
+ this.sessionCoordinator.markAnswered(q.identifier, responses);
1793
+ // QTI allowSkipping (individual parts only): an item that is about to be submitted
1794
+ // without any response may only be skipped when skipping is allowed. A simultaneous
1795
+ // part, an item already closed, or one an expired limit closed (collected as it
1796
+ // stands) is never held here.
1797
+ if (submits && !this.isItemLocked(q) && this.submissionGate(q, responses).mustAnswer) {
1798
+ throw new AssessmentPlayerError('responseRequired', 'You must answer this question before continuing.');
1799
+ }
1800
+ // A step out of the part (the next item lies in the next part, or a kept decision
1801
+ // leaves it) is refused before anything is submitted while another question of the
1802
+ // part still owes an answer: the part cannot be re-entered. The current item is this
1803
+ // move's own submission (or already accepted as it stands).
1804
+ const leavesPart = kept
1805
+ ? this.branchExitLeavesPart(q, kept)
1806
+ : crossesSimultaneousPart || this.items[forward].testPart !== q.testPart;
1807
+ if (leavesPart && !this.isItemLocked(q))
1808
+ this.assertCanLeaveScope(q, { exclude: q });
1809
+ if (submits) {
1810
+ const before = this.currentItemIndex;
1811
+ this.clearKeptBranchDecisions();
1812
+ await this.submitCurrentItemInternal();
1813
+ // The submission may branch, navigate, or finalize the test (EXIT_TEST); in those
1814
+ // cases navigation stops here. So does a scope expiry that fired while the
1815
+ // submission was in flight: its hop is queued behind this transition and moves
1816
+ // delivery (its routing decides where an open question is).
1817
+ if (this.currentItemIndex !== before || this.finalized || this.queuedExpiryHops > 0)
1818
+ return;
1819
+ }
1820
+ else if (kept) {
1821
+ // The decision the backend made for this item's accepted submission is followed now.
1822
+ // The move submits nothing, so its minimum times are checked here (an end of the
1823
+ // test checks its own). One that can no longer be followed (it would re-enter a part
1824
+ // already left) leaves the forward step to the delivery rules.
1825
+ const target = this.items[this.branchTargetIndex(q, kept)];
1826
+ if (target && !this.isItemLocked(q))
1827
+ this.assertTransitionMinimum(q, target);
1828
+ const before = this.currentItemIndex;
1829
+ await this.followBranch(q, kept);
1830
+ if (this.currentItemIndex !== before || this.finalized)
1831
+ return;
1832
+ }
1833
+ else if (crossesSimultaneousPart) {
1834
+ await this.crossSimultaneousPart(q);
1835
+ return;
1836
+ }
1837
+ // The candidate may still return and re-attempt this item: reopen it writable while
1838
+ // attempts remain (a no-op for closed single-attempt or writable items), so the
1839
+ // revisit restores an attemptable state instead of the closed one.
1840
+ this.reopenForRemainingAttempts(q);
1841
+ // No backend decision moved delivery (none was returned, or it could not be followed):
1842
+ // the delivery rules decide, as the navigation rules check them.
1843
+ const nextIndex = this.unsubmittedForwardIndex(q);
1844
+ if (nextIndex < 0)
1845
+ return;
1846
+ await this.performNavigateTo(nextIndex);
1847
+ }
1848
+ /**
1849
+ * Leave the simultaneous test part `last` belongs to: its pending responses go out
1850
+ * first (a failed request throws and keeps the candidate here for a retry), and the
1851
+ * branch decision the flush returns for the part's last item — the part's testPart
1852
+ * branchRule ran there, with every item's variables committed — is what delivery
1853
+ * follows, through `followBranch`'s part-leave, EXIT_TEST and finalized guards. With
1854
+ * no decision (or one that led nowhere) the delivery rules decide on the committed
1855
+ * state, honouring the following parts' preconditions.
1856
+ */
1857
+ async crossSimultaneousPart(last) {
1858
+ await this.submitSimultaneousItems(this.items.filter((item) => item.testPart === last.testPart));
1859
+ const target = this.partCrossingDecisionTarget(last);
1860
+ if (target !== null) {
1861
+ const before = this.currentItemIndex;
1862
+ await this.followBranch(last, target);
1863
+ if (this.currentItemIndex !== before || this.finalized)
1864
+ return;
1865
+ }
1866
+ // No decision moved delivery: the delivery rules decide, as the navigation rules
1867
+ // check them — on the state the flush just committed.
1868
+ const nextIndex = this.unsubmittedForwardIndex(last);
1869
+ if (nextIndex < 0)
1870
+ return;
1871
+ await this.performNavigateTo(nextIndex);
1872
+ }
1873
+ /**
1874
+ * The branch decision a simultaneous part's flush left for its last item, when it takes
1875
+ * delivery out of the part that is ending. A target inside that part is rejected: the
1876
+ * part is being left, its responses are out, and its rules cannot deliver into it again.
1877
+ */
1878
+ partCrossingDecisionTarget(last) {
1879
+ const target = this.keptBranchDecisionFor(last);
1880
+ if (!target)
1881
+ return null;
1882
+ const targetIndex = this.indexOfItem(target);
1883
+ if (targetIndex >= 0 && this.items[targetIndex].testPart === last.testPart)
1884
+ return null;
1885
+ return target;
1886
+ }
1887
+ /** Whether the delivered item after `q` lies outside `q`'s test part (or nothing does). */
1888
+ endsTestPart(q) {
1889
+ return this.items[q.index + 1]?.testPart !== q.testPart;
1890
+ }
1891
+ /** The part's effective QTI submission mode. */
1892
+ isSimultaneousSubmission(q) {
1893
+ return effectiveSubmissionMode(q.testPart, this.assessment) === 'simultaneous';
1894
+ }
1895
+ /**
1896
+ * Whether `next()` from the item submits it: an individual part's item whose attempts
1897
+ * remain, that is not closed, and whose responses differ from its last counted submission
1898
+ * (or that has none).
1899
+ */
1900
+ nextSubmits(q, responses = this.sessionCoordinator.getActiveResponses()) {
1901
+ return (this.isIndividual(q) &&
1902
+ this.sessionCoordinator.canSubmit(q.identifier) &&
1903
+ this.itemLifecycleOf(q.identifier) !== 'closed' &&
1904
+ !this.responsesUnchangedSinceSubmission(q.identifier, responses));
1905
+ }
1906
+ /**
1907
+ * The backend's decisions for leaving an item (`nextItemIdentifier`), keyed per item on
1908
+ * the session state (`state.branchDecisions`) with that item's last-submission record,
1909
+ * so a restored session lands identically. A counted submission that stays on the item
1910
+ * (a practice check, a counted endAttemptInteraction) keeps its decision; so does a
1911
+ * branch exit refused while questions of the part still owed an answer, and a
1912
+ * simultaneous part's crossing flush keeps the decision made for its last item. The next
1913
+ * forward step from that item that submits nothing — the candidate moves on with the
1914
+ * response unchanged — follows it; a changed response re-submits and the fresh decision
1915
+ * replaces it. At most the freshest decision is kept: any later counted submission voids
1916
+ * the earlier ones (the outcomes they were decided on have moved), and following a
1917
+ * decision clears it.
1918
+ */
1919
+ /** The backend decision kept for `q` that delivery has not followed yet (its target). */
1920
+ keptDecisionTarget(q) {
1921
+ return this.sessionCoordinator.getBranchDecision(q.identifier) ?? null;
1922
+ }
1923
+ /** Keep `target` as the one decision delivery may still follow — the item's freshest. */
1924
+ keepBranchDecision(q, target) {
1925
+ this.sessionCoordinator.keepBranchDecision(q.identifier, target);
1926
+ }
1927
+ /** Every kept decision is void: a counted submission moved the outcomes they decided on. */
1928
+ clearKeptBranchDecisions() {
1929
+ this.sessionCoordinator.clearBranchDecisions();
1930
+ }
1931
+ /**
1932
+ * The backend decision kept for leaving `q` — its item's entry in the session state
1933
+ * (`branchDecisions`), made by `q`'s last counted submission — if delivery has not
1934
+ * followed it yet. A decision onto an item an expired time limit has closed since is
1935
+ * passed over like the item itself: the delivery rules then find the next open item.
1936
+ */
1937
+ keptBranchDecisionFor(q) {
1938
+ const target = this.keptDecisionTarget(q);
1939
+ if (!target)
1940
+ return null;
1941
+ const targetItem = this.items[this.indexOfItem(target)];
1942
+ return targetItem && this.isItemLocked(targetItem) ? null : target;
1943
+ }
1944
+ /**
1945
+ * Where the candidate's Next goes from `q`: when it submits the item — or crosses out of
1946
+ * a simultaneous part whose responses still have to go out (`crossingFlushDue`) — the
1947
+ * backend decides once the submissions are accepted (the adjacent open item stands for
1948
+ * that decision until then; the pre-flush rules read uncommitted state); otherwise the
1949
+ * destination is known now (`unsubmittedForwardIndex`). -1 when nothing follows — Submit
1950
+ * is the way on.
1951
+ */
1952
+ forwardStepIndex(q) {
1953
+ return this.nextSubmits(q) || this.crossingFlushDue(q)
1954
+ ? this.nextUnlockedIndex(q.index)
1955
+ : this.unsubmittedForwardIndex(q);
1956
+ }
1957
+ /**
1958
+ * Whether `next()` from `q` crosses out of its simultaneous part with some of the part's
1959
+ * responses not yet accepted: the crossing flushes them, and that flush decides the landing.
1960
+ */
1961
+ crossingFlushDue(q) {
1962
+ return (this.endsTestPart(q) &&
1963
+ this.isSimultaneousSubmission(q) &&
1964
+ !this.keptBranchDecisionFor(q) &&
1965
+ this.items.some((item) => item.testPart === q.testPart && this.itemNeedsSubmission(item)));
1966
+ }
1967
+ /**
1968
+ * Where a forward step from `q` that submits nothing lands — a move on after a practice
1969
+ * check, a move out of a simultaneous part, a jump into the next test part: the backend's
1970
+ * decision kept for `q`, else the next item the delivery rules make eligible
1971
+ * (`ruleForwardIndex`). -1 when nothing follows (an EXIT_* decision nothing follows, or
1972
+ * nothing eligible). A decision whose literal target resolves to nothing forward is
1973
+ * skipped — the rule does not fire — so the delivery rules decide, exactly as the
1974
+ * backend's own walk falls through from an unresolvable target.
1975
+ */
1976
+ unsubmittedForwardIndex(q) {
1977
+ const kept = this.keptBranchDecisionFor(q);
1978
+ if (!kept)
1979
+ return this.ruleForwardIndex(q);
1980
+ const landing = branchLandingOf(kept, this.branchTargetIndex(q, kept));
1981
+ switch (landing.kind) {
1982
+ case 'item':
1983
+ return landing.index;
1984
+ case 'exit':
1985
+ // Nothing follows the EXIT_* boundary; Submit is the way on (its own handling
1986
+ // ends the scope or the test — see `followBranch`).
1987
+ return -1;
1988
+ case 'skipped':
1989
+ return this.ruleForwardIndex(q);
1990
+ }
1991
+ }
1992
+ /**
1993
+ * The next item after `q` when no backend decision applies, by the reference backend's own
1994
+ * rules (`nextItemIdentifier`): branch rules first — in a linear part the item's and those
1995
+ * of each section it ends, the test part's at its end — then preconditions: a test part's on
1996
+ * entering it in any navigation mode, a linear part's sections and items on reaching them.
1997
+ * They read the test outcomes the backend last returned and the recorded variables of every
1998
+ * item it accepted (`ITEM.VARIABLE`), as the backend does. Items an expired time limit closed
1999
+ * are passed over. A test without branch rules or preconditions moves to the adjacent open item.
2000
+ */
2001
+ ruleForwardIndex(q) {
2002
+ if (!this.hasDeliveryRules)
2003
+ return this.nextUnlockedIndex(q.index);
2004
+ const decls = this.navigationDeclarationsFor(q);
2005
+ const first = this.indexOfItem(nextItemIdentifier(this.assessment, this.deliveredForRules, q.index, decls, Math.random, this.reportTestConditionFailure));
2006
+ if (first < 0)
2007
+ return -1;
2008
+ if (!this.isItemLocked(this.items[first]))
2009
+ return first;
2010
+ for (const index of this.eligibleIndexesAfter(first, decls)) {
2011
+ if (!this.isItemLocked(this.items[index]))
2012
+ return index;
2013
+ }
2014
+ return -1;
2015
+ }
2016
+ /**
2017
+ * The items the delivery rules reach after `fromIndex`, in order: each one whose
2018
+ * preconditions hold as the sequence enters its test part (any navigation mode) and, in a
2019
+ * linear part, its sections and the item itself. Without rules, every following item.
2020
+ */
2021
+ *eligibleIndexesAfter(fromIndex, decls) {
2022
+ if (!this.hasDeliveryRules) {
2023
+ for (let index = fromIndex + 1; index < this.items.length; index++)
2024
+ yield index;
2025
+ return;
2026
+ }
2027
+ const from = this.items[fromIndex];
2028
+ if (!from)
2029
+ return;
2030
+ const declarations = decls ?? this.navigationDeclarationsFor(from);
2031
+ let previous = this.deliveredForRules[fromIndex];
2032
+ let start = fromIndex + 1;
2033
+ while (start < this.items.length) {
2034
+ const index = this.indexOfItem(firstEligibleItem(this.assessment, this.deliveredForRules, start, previous, declarations, Math.random, this.reportTestConditionFailure));
2035
+ if (index < 0)
2036
+ return;
2037
+ yield index;
2038
+ previous = this.deliveredForRules[index];
2039
+ start = index + 1;
2040
+ }
2041
+ }
2042
+ /**
2043
+ * The declarations branch rules and preconditions read, built as the reference backend
2044
+ * builds them for a decision about leaving `from`: the test outcomes the backend last
2045
+ * returned, every item with a recorded result as `ITEM.VARIABLE` (an item without one reads
2046
+ * as NULL), and `from`'s own variables unprefixed where the test declares no such outcome.
2047
+ */
2048
+ navigationDeclarationsFor(from) {
2049
+ const recorded = {};
2050
+ for (const item of this.items) {
2051
+ const scoring = this.state.itemScores?.[item.identifier];
2052
+ if (!scoring && !this.sessionCoordinator.hasItemResult(item.identifier))
2053
+ continue;
2054
+ const variables = recordedItemVariableValues(this.state.itemSessions?.[item.identifier], scoring?.outcomeValues);
2055
+ if (scoring && !variables.SCORE)
2056
+ variables.SCORE = { kind: 'value', baseType: 'float', cardinality: 'single', value: scoring.score };
2057
+ recorded[item.identifier] = applyVariableMappings(variables, item.item.variableMappings);
2058
+ }
2059
+ return addItemVariableDeclarations(testOutcomeDeclarations(this.assessment, this.testOutcomes ?? this.sessionCoordinator.getTestOutcomes()), recorded, recorded[from.identifier] ?? {});
2060
+ }
2061
+ indexOfItem(identifier) {
2062
+ return identifier === undefined ? -1 : (this.indexByIdentifier.get(identifier) ?? -1);
2063
+ }
2064
+ /** The forward step, computed at most once for a batch of legality checks. */
2065
+ lazyForward() {
2066
+ let forward;
2067
+ return () => {
2068
+ if (forward === undefined) {
2069
+ const current = this.items[this.currentItemIndex];
2070
+ forward = current ? this.unsubmittedForwardIndex(current) : -1;
2071
+ }
2072
+ return forward;
2073
+ };
2074
+ }
2075
+ /**
2076
+ * Whether the item's last counted submission already carried these responses.
2077
+ * False when nothing was recorded: the caller then submits as usual.
2078
+ */
2079
+ responsesUnchangedSinceSubmission(itemIdentifier, responses) {
2080
+ const submitted = this.lastSubmittedResponses.get(itemIdentifier);
2081
+ if (!submitted)
2082
+ return false;
2083
+ const current = responses ?? this.sessionCoordinator.getActiveResponses();
2084
+ return responseValuesEqual(submitted, current);
2085
+ }
2086
+ /**
2087
+ * Seed the submitted-response memory from a restored snapshot: an item whose recorded
2088
+ * result the snapshot carries was accepted with exactly those responses, so moving on
2089
+ * (or finalizing) with them unchanged re-submits nothing and re-spends no attempt.
2090
+ */
2091
+ seedSubmittedResponses(state) {
2092
+ const scores = state.itemScores ?? {};
2093
+ for (const [itemIdentifier, responses] of Object.entries(state.itemResponses ?? {})) {
2094
+ if (!scores[itemIdentifier])
2095
+ continue;
2096
+ if (this.lastSubmittedResponses.has(itemIdentifier))
2097
+ continue;
2098
+ this.lastSubmittedResponses.set(itemIdentifier, cloneResponseRecord(responses));
2099
+ }
2100
+ }
2101
+ /** Move back. Serialized with all other transitions; rejects as busy while one is in flight. */
2102
+ previous() {
2103
+ return this.runCandidateTransition(async () => {
2104
+ const state = this.getNavigationState();
2105
+ if (!state.canPrevious)
2106
+ return;
2107
+ await this.performNavigateTo(this.currentItemIndex - 1);
2108
+ });
2109
+ }
2110
+ /**
2111
+ * Submit current item (server-side scoring). Serialized with all other navigation and
2112
+ * submission transitions; rejects as busy while one is in flight.
2113
+ */
2114
+ submitCurrentItem() {
2115
+ return this.runCandidateTransition(() => this.submitCurrentItemInternal());
2116
+ }
2117
+ /**
2118
+ * Whether the shell should offer the item-level "Check answer" control on the active
2119
+ * item, with the attempt facts it displays. The control exists only in `individual`
2120
+ * submission-mode parts where more than one attempt is allowed (or the item is
2121
+ * adaptive): QTI shows feedback for every non-final attempt then, whatever
2122
+ * `showFeedback` says, so checking in place always reveals something. A single
2123
+ * attempt keeps the submit-on-move delivery (its feedback, under `showFeedback`, rides
2124
+ * the transition); QTI simultaneous parts have no per-item submission.
2125
+ */
2126
+ getCheckAnswerState() {
637
2127
  const q = this.items[this.currentItemIndex];
638
- if (q) {
639
- const responses = this.sessionCoordinator.getActiveResponses();
640
- this.sessionCoordinator.markAnswered(q.identifier, responses);
641
- const navAway = this.sessionCoordinator.canNavigateAway(q.identifier, responses);
642
- if (!navAway.allowed) {
643
- throw new Error(navAway.reason || 'You must answer this question before continuing.');
2128
+ if (!q)
2129
+ return null;
2130
+ const id = q.identifier;
2131
+ const mode = effectiveSubmissionMode(q.testPart, this.assessment);
2132
+ const adaptive = isAdaptiveItemXml(q.item.itemXml);
2133
+ if (mode !== 'individual') {
2134
+ return {
2135
+ available: false,
2136
+ reason: 'simultaneous',
2137
+ adaptive,
2138
+ attemptsUsed: 0,
2139
+ maxAttempts: null,
2140
+ remainingAttempts: null,
2141
+ attemptsExhausted: false,
2142
+ };
2143
+ }
2144
+ const info = this.sessionCoordinator.getItemSessionInfo(id);
2145
+ const maxAttempts = resolveMaxAttempts(this.sessionCoordinator.getItemSettings(id), adaptive);
2146
+ const remainingAttempts = maxAttempts === null ? null : Math.max(0, maxAttempts - info.attemptCount);
2147
+ const attemptsExhausted = maxAttempts !== null && info.attemptCount >= maxAttempts;
2148
+ // maxAttempts 1 delivers feedback on the move (submit-on-move): no check control.
2149
+ const available = maxAttempts === null || maxAttempts > 1;
2150
+ return {
2151
+ available,
2152
+ reason: available ? null : 'feedbackOff',
2153
+ adaptive,
2154
+ attemptsUsed: info.attemptCount,
2155
+ maxAttempts,
2156
+ remainingAttempts,
2157
+ attemptsExhausted,
2158
+ };
2159
+ }
2160
+ /**
2161
+ * Practice flow: submit the active item through the normal per-item path and STAY on
2162
+ * it, so its feedback becomes visible (the shell shows `getLastItemFeedback()`).
2163
+ * The submission counts toward `maxAttempts`; while attempts remain the item reopens
2164
+ * writable afterwards (non-adaptive items reopen from the pre-submit state with the
2165
+ * computed outcomes restored), so the candidate can revise and check again. Adaptive
2166
+ * items keep their engine-driven attempt loop. Once the attempts are used up this
2167
+ * rejects with a coded `maxAttemptsReached`; moving on with `next()` then needs no
2168
+ * further submission. Serialized with all other transitions.
2169
+ */
2170
+ checkCurrentItem() {
2171
+ return this.runCandidateTransition(async () => {
2172
+ const q = this.items[this.currentItemIndex];
2173
+ if (!q)
2174
+ return null;
2175
+ const state = this.getCheckAnswerState();
2176
+ if (!state?.available) {
2177
+ throw new AssessmentPlayerError('navigationNotAllowed', 'Checking answers is not available for this item.');
644
2178
  }
645
- // In individual submission mode, submit the current item before moving forward
646
- // unless its attempts are used up or it is already closed.
647
- const lifecycle = this.currentItemSession?.state().lifecycleStatus;
648
- if ((q.testPart.submissionMode ?? this.assessment.submissionMode) === 'individual' &&
649
- this.sessionCoordinator.canSubmit(q.identifier) &&
650
- lifecycle !== 'closed') {
651
- const before = this.currentItemIndex;
652
- await this.submitCurrentItem();
653
- // submitCurrentItem may branch/navigate; if it did, we're done.
654
- if (this.currentItemIndex !== before)
655
- return;
2179
+ if (state.attemptsExhausted || !this.sessionCoordinator.canSubmit(q.identifier)) {
2180
+ throw new AssessmentPlayerError('maxAttemptsReached', `No attempts remain for item "${q.identifier}".`);
656
2181
  }
657
- }
658
- const nextIndex = this.nextUnlockedIndex(this.currentItemIndex);
659
- if (nextIndex < 0)
2182
+ const live = this.currentItemSession;
2183
+ if (live && !isWritableItemLifecycle(live.state().lifecycleStatus)) {
2184
+ // The attempt already ended (and attempts remain only for adaptive items the
2185
+ // engine kept open); nothing to check until delivery reopens the item.
2186
+ return null;
2187
+ }
2188
+ const result = await this.submitCurrentItemInternal({ countAttempt: true, followBranching: false });
2189
+ this.reopenForRemainingAttempts(q);
2190
+ return result;
2191
+ });
2192
+ }
2193
+ /**
2194
+ * While counted attempts remain on a non-adaptive item whose attempt just ended (a
2195
+ * practice check, a submit-on-move the candidate may come back to), reopen it writable
2196
+ * from that processed attempt: the session keeps the attempt count (the engine restores
2197
+ * `contextVariables.numAttempts`, so the next counted attempt runs response processing as
2198
+ * attempt k+1) and the outcomes response processing computed — the integrated feedback
2199
+ * renders from them while the candidate revises — with its lifecycle set back to
2200
+ * `interacting`. What the item persists from then on is the attempt the backend accepted.
2201
+ */
2202
+ reopenForRemainingAttempts(q) {
2203
+ if (isAdaptiveItemXml(q.item.itemXml))
660
2204
  return;
661
- await this.navigateTo(nextIndex);
2205
+ // Only the item delivery stands on: this swaps the live session, and another
2206
+ // item's is never replaced.
2207
+ if (this.items[this.currentItemIndex] !== q)
2208
+ return;
2209
+ // An item an expired time limit closed stays closed.
2210
+ if (this.isItemLocked(q))
2211
+ return;
2212
+ const live = this.currentItemSession;
2213
+ if (!live || live.state().lifecycleStatus !== 'closed')
2214
+ return;
2215
+ if (!this.sessionCoordinator.canSubmit(q.identifier))
2216
+ return;
2217
+ const presentation = this.presentationFor(q);
2218
+ const session = this.getItemDefinition(q).openSession({
2219
+ restore: { ...live.serialize(), lifecycleStatus: 'interacting' },
2220
+ presentation,
2221
+ });
2222
+ this.releaseCurrentItemSession();
2223
+ this.attachCurrentItemSession(q, session, presentation);
2224
+ this.notifyItemChange();
2225
+ }
2226
+ /**
2227
+ * The item feedback the most recent item-level submission produced (item modal
2228
+ * feedback from response processing, or the backend's `result.feedback`), or null.
2229
+ * Shells show it after `checkCurrentItem()` and after a submit-on-move `next()`.
2230
+ */
2231
+ getLastItemFeedback() {
2232
+ return this.lastItemFeedback ? { ...this.lastItemFeedback, feedback: [...this.lastItemFeedback.feedback] } : null;
662
2233
  }
663
- async previous() {
664
- const state = this.getNavigationState();
665
- if (!state.canPrevious)
2234
+ /** Discard the captured item feedback once the shell has shown it. */
2235
+ clearLastItemFeedback() {
2236
+ this.lastItemFeedback = null;
2237
+ }
2238
+ getLastItemFeedbackFor(itemIdentifier) {
2239
+ return this.lastItemFeedback?.itemIdentifier === itemIdentifier ? this.lastItemFeedback : null;
2240
+ }
2241
+ /**
2242
+ * Capture an item-level submission's feedback for the shell, under the item's
2243
+ * attempt-relative feedback visibility (`attemptsAfter`: the counted attempts once this
2244
+ * submission is recorded). A submission that produces none clears a stale capture for
2245
+ * the flow that follows it.
2246
+ */
2247
+ captureItemFeedback(q, feedback, attemptsAfter) {
2248
+ if (!this.feedbackVisible(q, attemptsAfter) || !feedback || feedback.length === 0) {
2249
+ this.lastItemFeedback = null;
666
2250
  return;
667
- await this.navigateTo(this.currentItemIndex - 1);
2251
+ }
2252
+ this.lastItemFeedback = {
2253
+ itemIdentifier: q.identifier,
2254
+ feedback: cloneData([...feedback]),
2255
+ };
668
2256
  }
669
- /** Submit current item (server-side scoring) */
670
- async submitCurrentItem() {
2257
+ async submitCurrentItemInternal(options = {}) {
2258
+ const countAttempt = options.countAttempt ?? true;
671
2259
  const q = this.items[this.currentItemIndex];
672
2260
  if (!q)
673
- throw new Error('No current item');
674
- this.assertMinimumTime('item', q);
2261
+ throw new AssessmentPlayerError('invalidNavigationTarget', 'No current item');
2262
+ // An expired limit closed this attempt (or a proctor ends the test): neither its
2263
+ // minimum time nor the skipping/validation gates can hold it open, and the backend
2264
+ // receives it as the collection of the responses as they stand.
2265
+ const submissionReason = this.submissionReasonFor(q);
2266
+ const administrative = submissionReason !== undefined;
2267
+ if (!administrative)
2268
+ this.assertMinimumTime('item', q);
2269
+ const responses = this.currentItemSession
2270
+ ? cloneResponseRecord(this.currentItemSession.state().responses)
2271
+ : this.sessionCoordinator.getActiveResponses();
2272
+ // QTI allowSkipping / validateResponses on the per-item path (individual parts only).
2273
+ // A hint (countAttempt=false) is not an attempt and is not held back.
2274
+ const gate = administrative || !countAttempt ? { mustAnswer: false, validate: false } : this.submissionGate(q, responses);
2275
+ if (gate.mustAnswer) {
2276
+ throw new AssessmentPlayerError('responseRequired', 'You must answer this question before continuing.');
2277
+ }
2278
+ if (gate.validate && !this.responsesSatisfyConstraints(q)) {
2279
+ throw new AssessmentPlayerError('attemptValidationFailed', `Submit failed: the responses for item ${q.identifier} do not satisfy its interactions`);
2280
+ }
2281
+ // The counted attempts once this submission is recorded: feedback visibility is
2282
+ // attempt-relative (a non-final attempt shows feedback whatever showFeedback says).
2283
+ const attemptsAfter = this.sessionCoordinator.getItemSessionInfo(q.identifier).attemptCount + (countAttempt ? 1 : 0);
675
2284
  const submittedAt = Date.now();
676
2285
  let itemSession;
677
2286
  const submittedSession = this.currentItemSession;
678
2287
  const preSubmitSession = submittedSession?.serialize();
679
- const responses = this.currentItemSession
680
- ? cloneResponseRecord(this.currentItemSession.state().responses)
681
- : this.sessionCoordinator.getActiveResponses();
682
2288
  let res;
683
2289
  try {
684
2290
  if (submittedSession) {
685
- const transition = submittedSession.dispatch({
686
- action: 'endAttempt',
687
- validateResponses: this.sessionCoordinator.mustValidateResponses(q.identifier),
688
- });
689
- const attempt = transition.result;
690
- if (!attempt)
2291
+ // A session whose attempt already ended contributes its accepted state unchanged;
2292
+ // dispatching another end-attempt on it would throw and fail the submission.
2293
+ const transition = isWritableItemLifecycle(submittedSession.state().lifecycleStatus)
2294
+ ? submittedSession.dispatch({
2295
+ action: 'endAttempt',
2296
+ countAttempt,
2297
+ validateResponses: gate.validate,
2298
+ })
2299
+ : undefined;
2300
+ const attempt = transition?.result;
2301
+ if (transition && !attempt)
691
2302
  throw new Error('Item session did not produce an end-attempt result');
692
- if (attempt.validation && !attempt.validation.valid) {
693
- throw new Error(attempt.validation.issues[0]?.message || 'Submit failed: invalid response');
2303
+ if (attempt?.validation && !attempt.validation.valid) {
2304
+ throw new AssessmentPlayerError('attemptValidationFailed', attempt.validation.issues[0]?.message || 'Submit failed: invalid response');
694
2305
  }
695
- itemSession = attempt.sessionState;
2306
+ itemSession = attempt?.sessionState ?? submittedSession.serialize();
2307
+ this.captureItemFeedback(q, attempt?.scoring?.modalFeedback, attemptsAfter);
696
2308
  }
697
2309
  res = await this.backend.submitResponses({
698
2310
  sessionId: this.sessionId,
699
2311
  itemIdentifier: q.identifier,
700
- responses: responses,
2312
+ responses: asResponseValues(responses),
701
2313
  submittedAt,
2314
+ countAttempt,
702
2315
  timeSpent: itemSession?.duration,
703
- timing: this.getSubmitTimingEvidence(q, itemSession?.duration ?? 0),
704
- itemSession: this.config.sendItemSessionToBackend ? itemSession : undefined,
2316
+ timing: this.getSubmitTimingEvidence(q, itemSession?.duration ?? 0, submissionReason),
2317
+ itemSession: this.sendsItemSession() ? itemSession : undefined,
705
2318
  comment: this.sessionCoordinator.getItemComment(q.identifier),
706
2319
  });
707
2320
  if (!res.success || !res.result) {
708
- throw new Error(res.error || 'Submit failed');
2321
+ // Backend error text stays on the Error (logs/host callbacks); candidates
2322
+ // see the localized `assessment.errors.codes.submitFailed` message instead.
2323
+ throw new AssessmentPlayerError('submitFailed', res.error || 'Submit failed');
2324
+ }
2325
+ // A backend that produced no session-side modal feedback (production item XML
2326
+ // is delivered without responseProcessing) may still return feedback entries
2327
+ // from its own scoring: the same capture, backend-authored.
2328
+ if (res.result.feedback?.length && !this.getLastItemFeedbackFor(q.identifier)) {
2329
+ this.captureItemFeedback(q, res.result.feedback.map((item) => ({
2330
+ identifier: item.type,
2331
+ content: item.content,
2332
+ })), attemptsAfter);
709
2333
  }
710
2334
  }
711
2335
  catch (error) {
@@ -717,82 +2341,205 @@ export class AssessmentPlayer {
717
2341
  this.currentItemSession === submittedSession &&
718
2342
  this.items[this.currentItemIndex] === q) {
719
2343
  this.releaseCurrentItemSession();
720
- this.attachCurrentItemSession(q, this.getItemDefinition(q).openSession({ restore: preSubmitSession }));
2344
+ const presentation = this.presentationFor(q);
2345
+ this.attachCurrentItemSession(q, this.getItemDefinition(q).openSession({ restore: preSubmitSession, presentation }), presentation);
721
2346
  this.notifyItemChange();
722
2347
  }
2348
+ // Nothing committed: no feedback belongs to this attempt.
2349
+ this.lastItemFeedback = null;
723
2350
  throw error;
724
2351
  }
725
2352
  if (itemSession) {
726
2353
  this.sessionCoordinator.setItemSession(q.identifier, itemSession);
727
2354
  }
728
- if (res.updatedState) {
729
- const localResponses = cloneData(this.state.itemResponses || {});
730
- localResponses[q.identifier] = cloneResponseRecord(responses);
731
- this.sessionCoordinator.replaceStatePreservingResponsesAndSessions(res.updatedState, localResponses, cloneData(this.state.itemSessions || {}));
732
- }
733
- else {
734
- // Minimal state update when backend doesn't return full state.
735
- this.state.itemScores = this.state.itemScores || {};
736
- this.state.itemScores[q.identifier] = res.result;
737
- this.sessionCoordinator.markVisited(q.identifier);
738
- this.state.itemResponses[q.identifier] = responses;
739
- if (itemSession) {
740
- this.sessionCoordinator.setItemSession(q.identifier, itemSession);
2355
+ this.setTestOutcomes(res.outcomes);
2356
+ this.reportOutcomeProcessingError(res.outcomeProcessingError);
2357
+ this.reportItemScoringError(res.result);
2358
+ // An uncounted submission (QTI endAttempt countAttempt=false, a hint request) persists the
2359
+ // response and session but records no result and consumes no attempt: the candidate stays
2360
+ // on the item and a later submission carries the final response.
2361
+ if (countAttempt) {
2362
+ // The attempt count before this submission: a backend `updatedState` carries its own
2363
+ // authoritative count (`itemSessionStates`), which must not be counted twice.
2364
+ const attemptsBefore = this.sessionCoordinator.getItemSessionInfo(q.identifier).attemptCount;
2365
+ if (res.updatedState) {
2366
+ this.sessionCoordinator.recordSubmittedItemInUpdatedState(q.identifier, responses, res.updatedState);
2367
+ }
2368
+ else {
2369
+ // Minimal state update when backend doesn't return full state.
2370
+ this.sessionCoordinator.recordIndividualSubmission(q.identifier, responses, itemSession, res.result);
2371
+ }
2372
+ const itemResult = {
2373
+ itemIdentifier: q.identifier,
2374
+ score: res.result.score,
2375
+ maxScore: res.result.maxScore,
2376
+ responses: { ...responses },
2377
+ };
2378
+ this.sessionCoordinator.setItemResult(itemResult);
2379
+ // The counted submission's response set: a later move-time or end-of-test
2380
+ // submission of the same responses is skipped (no wasted attempt).
2381
+ this.lastSubmittedResponses.set(q.identifier, cloneResponseRecord(responses));
2382
+ // Track item session rules (review/attempts) and visited items for navigation hints.
2383
+ // The backend already counted this attempt when its `updatedState` restored a
2384
+ // higher count; only a backend without state updates records locally.
2385
+ this.sessionCoordinator.recordAttemptIfUncounted(q.identifier, attemptsBefore);
2386
+ this.sessionCoordinator.markAnswered(q.identifier, responses);
2387
+ // The submitted item: delivery stands on it for the whole submission (a scope
2388
+ // expiry in flight only queues its hop behind this transition).
2389
+ this.navigationManager.markVisited(q.index);
2390
+ // Apply the backend's branching decision, if any. QTI branchRule semantics:
2391
+ // - EXIT_TEST terminates the test: remaining items are not presented and the test
2392
+ // finalizes exactly like a normal end of test.
2393
+ // - EXIT_TESTPART ends the current test part; EXIT_SECTION ends the current section.
2394
+ // Delivery continues with the next item outside the ended scope; when none follows
2395
+ // (for the part, or the test), the ended scope finalizes like a normal end of test.
2396
+ // A submission that stays on the item (a practice check, a counted end-attempt) keeps
2397
+ // the decision instead: the next forward step from the item that submits nothing
2398
+ // follows it. Either way it voids every earlier decision, which was made on outcomes
2399
+ // this submission has moved.
2400
+ this.clearKeptBranchDecisions();
2401
+ if (options.followBranching === false) {
2402
+ if (res.nextItemIdentifier) {
2403
+ this.keepBranchDecision(q, res.nextItemIdentifier);
2404
+ }
2405
+ }
2406
+ else if (res.nextItemIdentifier) {
2407
+ await this.followBranch(q, res.nextItemIdentifier);
2408
+ }
2409
+ // Still on the item (a check, a hint, the last item): what it shows follows the
2410
+ // attempt count — a final attempt hides feedback a non-final one revealed.
2411
+ if (!this.finalized && this.items[this.currentItemIndex] === q) {
2412
+ this.refreshLivePresentation(q, itemSession);
741
2413
  }
2414
+ return itemResult;
742
2415
  }
743
- this.setTestOutcomes(res.outcomes);
744
- const itemResult = {
2416
+ // The hint consumed no attempt: the item session must be as open as it was before it.
2417
+ // Response processing may have marked the item completed (a hint on a correct answer),
2418
+ // which closes the session and would leave the candidate with no way to answer —
2419
+ // reopen it while attempts remain, as a counted check reopens.
2420
+ // The backend accepted these exact responses (it ran response processing on them), so
2421
+ // they stand as the item's last submitted set: moving on unchanged re-submits nothing
2422
+ // and follows the counted decision on record, never a fresh one on the hint's state.
2423
+ this.lastSubmittedResponses.set(q.identifier, cloneResponseRecord(responses));
2424
+ this.reopenForRemainingAttempts(q);
2425
+ this.sessionCoordinator.markAnswered(q.identifier, responses);
2426
+ return {
745
2427
  itemIdentifier: q.identifier,
746
2428
  score: res.result.score,
747
2429
  maxScore: res.result.maxScore,
748
2430
  responses: { ...responses },
749
2431
  };
750
- this.sessionCoordinator.setItemResult(itemResult);
751
- // Track item session rules (review/attempts) and visited items for navigation hints.
2432
+ }
2433
+ /**
2434
+ * Follow the backend's branching decision for the item just submitted. A decision that
2435
+ * would leave the test part (EXIT_TESTPART, an EXIT_SECTION with nothing after it in
2436
+ * the part, a target in a later part) or end the test (EXIT_TEST) while other questions
2437
+ * of the part still owe an answer is refused like a candidate's own step out of the
2438
+ * part: the candidate stays, the coded error names the questions, and the decision is
2439
+ * kept — the next `next()` from this item follows it once they are answered (a changed
2440
+ * response re-submits and replaces it).
2441
+ *
2442
+ * The end of the test never navigates: a decision its own submission returns is kept
2443
+ * the same way and the collection runs where the candidate stands. A decision whose
2444
+ * submission a scope expiry raced (the item's scope ran out while the submission was in
2445
+ * flight) is not followed — the expiry's queued hop moves delivery, and the decision
2446
+ * would undo that move or land in the closed scope — and a test part delivery already
2447
+ * left is never re-entered.
2448
+ */
2449
+ async followBranch(q, target) {
2450
+ // Literal targets resolve forward-only (QTI 2.2 §5.15: a delivered test never re-enters
2451
+ // presented items) through the same resolver the landing pre-checks use, so the hop
2452
+ // cannot disagree with what `branchTargetIndex` reported; an unresolvable literal is
2453
+ // skipped and delivery falls through to the delivery rules, as on the backend. EXIT_*
2454
+ // land through their own boundary handling below (-1 never navigates).
2455
+ const targetIndex = branchTargetIndex(q, target, this.items, this.currentItemIndex);
2456
+ const standing = this.items[this.currentItemIndex] ?? q;
2457
+ // A test part delivery already left is never re-entered, whatever the decision says.
2458
+ if (targetIndex >= 0 && partOrderOf(this.assessment, this.items[targetIndex]) < partOrderOf(this.assessment, standing)) {
2459
+ this.clearKeptBranchDecisions();
2460
+ return;
2461
+ }
2462
+ // An end of the test is running: it collects where the candidate stands.
2463
+ if (this.endReason !== null) {
2464
+ this.keepBranchDecision(q, target);
2465
+ return;
2466
+ }
2467
+ // A scope expiry fired while the submission was in flight: its hop is queued behind
2468
+ // this transition and moves delivery, so the decision is not followed — the same
2469
+ // outcome as a decision that arrived after delivery moved on.
2470
+ if (this.queuedExpiryHops > 0)
2471
+ return;
752
2472
  try {
753
- this.sessionCoordinator.recordAttempt(q.identifier);
2473
+ if (target === 'EXIT_TEST')
2474
+ this.assertNoSubmissionBlockers();
2475
+ else if (this.branchExitLeavesPart(q, target))
2476
+ this.assertCanLeaveScope(q, { exclude: q });
754
2477
  }
755
- catch {
756
- // ignore
2478
+ catch (error) {
2479
+ this.keepBranchDecision(q, target);
2480
+ throw error;
757
2481
  }
758
- this.sessionCoordinator.markAnswered(q.identifier, responses);
759
- this.navigationManager.markVisited(this.currentItemIndex);
760
- // Apply backend branching decision if provided.
761
- // Special QTI targets EXIT_TEST / EXIT_TESTPART / EXIT_SECTION trigger finalization.
762
- if (res.nextItemIdentifier) {
763
- const special = res.nextItemIdentifier;
764
- if (special === 'EXIT_TEST') {
765
- // Finalize immediately — no further navigation
766
- for (const l of this.completeListeners)
767
- l();
768
- this.config.onComplete?.();
769
- }
770
- else if (special === 'EXIT_TESTPART' || special === 'EXIT_SECTION') {
771
- // Advance past all remaining items in the current testPart or section
772
- const currentItem = this.items[this.currentItemIndex];
773
- const isSection = special === 'EXIT_SECTION';
774
- const nextIdx = this.items.findIndex((item, i) => i > this.currentItemIndex &&
775
- (isSection
776
- ? item.section.identifier !== currentItem?.section.identifier
777
- : item.testPart.identifier !== currentItem?.testPart.identifier));
778
- if (nextIdx >= 0) {
779
- await this.navigateTo(nextIdx, { restoring: true });
780
- }
781
- else {
782
- // No further items — signal completion
783
- for (const l of this.completeListeners)
784
- l();
785
- this.config.onComplete?.();
786
- }
787
- }
788
- else {
789
- const nextIdx = this.items.findIndex((x) => x.identifier === special);
790
- if (nextIdx >= 0) {
791
- await this.navigateTo(nextIdx, { restoring: true });
792
- }
2482
+ this.clearKeptBranchDecisions();
2483
+ if (target === 'EXIT_TEST') {
2484
+ await this.endTestInternal({ reason: 'branch' });
2485
+ return;
2486
+ }
2487
+ if (target === 'EXIT_TESTPART' || target === 'EXIT_SECTION') {
2488
+ await this.applyExitBoundary(target, q);
2489
+ return;
2490
+ }
2491
+ if (targetIndex >= 0) {
2492
+ // A target in the same part leaves this item revisitable: while attempts remain
2493
+ // (QTI allowReview governs only after the last one) its handoff must be
2494
+ // attemptable, exactly as on the candidate's own move — reopen it writable and
2495
+ // hand it off before the hop (a branch hop does not save the outgoing session).
2496
+ if (this.items[targetIndex].testPart === q.testPart) {
2497
+ this.reopenForRemainingAttempts(q);
2498
+ const status = this.currentItemSession?.state().lifecycleStatus;
2499
+ if (status !== undefined && isWritableItemLifecycle(status))
2500
+ this.saveCurrentItemSession();
793
2501
  }
2502
+ await this.performNavigateTo(targetIndex, { restoring: true });
2503
+ }
2504
+ }
2505
+ /** Where a branch decision lands: an item index, or -1 when it ends the test or resolves to nothing forward. */
2506
+ branchTargetIndex(q, target) {
2507
+ return branchTargetIndex(q, target, this.items, this.currentItemIndex);
2508
+ }
2509
+ /** Whether a branch decision takes delivery out of the item's test part (or ends the test). */
2510
+ branchExitLeavesPart(q, target) {
2511
+ return branchExitLeavesPart(q, target, this.items, this.currentItemIndex);
2512
+ }
2513
+ /**
2514
+ * Leave the scope ended by an EXIT_TESTPART / EXIT_SECTION branch rule: continue with
2515
+ * the first delivered item outside it, finalizing the ended test part (or, when nothing
2516
+ * follows anywhere, the whole test) through the same finalization path as submit().
2517
+ *
2518
+ * The literal resolves over the item's full enclosing chain (like the backend's
2519
+ * branch-rule walk), not the innermost section alone: an outer-section EXIT lands
2520
+ * outside the whole outer section.
2521
+ */
2522
+ async applyExitBoundary(special, current) {
2523
+ const nextIdx = resolveExitBoundary(special, current, this.items, this.currentItemIndex);
2524
+ const partEnded = nextIdx < 0 || this.items[nextIdx].testPart !== current.testPart;
2525
+ if (partEnded) {
2526
+ // The part's pending simultaneous-mode responses are due when it ends.
2527
+ await this.submitSimultaneousItems(this.items.filter((item) => item.testPart === current.testPart &&
2528
+ effectiveSubmissionMode(item.testPart, this.assessment) === 'simultaneous'));
2529
+ }
2530
+ if (nextIdx >= 0) {
2531
+ await this.performNavigateTo(nextIdx, { restoring: true });
2532
+ return;
794
2533
  }
795
- return itemResult;
2534
+ // No further test part: end the test exactly like a normal end of test.
2535
+ await this.endTestInternal({ reason: 'branch' });
2536
+ }
2537
+ /**
2538
+ * The enclosing section a literal EXIT_SECTION leaves (see
2539
+ * `exitBoundaries.endedEnclosingSection`).
2540
+ */
2541
+ endedEnclosingSection(current) {
2542
+ return endedEnclosingSection(current, this.items, this.currentItemIndex);
796
2543
  }
797
2544
  canPrevious() {
798
2545
  if (this.currentItemIndex <= 0)
@@ -802,38 +2549,53 @@ export class AssessmentPlayer {
802
2549
  return false;
803
2550
  if (!this.canNavigateByTestPart(this.currentItemIndex - 1, this.currentItemIndex))
804
2551
  return false;
805
- return this.sessionCoordinator.canReview(prev.identifier);
2552
+ return this.canReviewItem(prev);
2553
+ }
2554
+ /**
2555
+ * QTI `allowReview` for returning to an item: it governs only once the item's session is
2556
+ * over — after its last attempt, or (adaptive) once it completed. While attempts remain
2557
+ * the candidate may come back and use them.
2558
+ */
2559
+ canReviewItem(q) {
2560
+ const completed = isAdaptiveItemXml(q.item.itemXml) && this.itemLifecycleOf(q.identifier) === 'closed';
2561
+ return this.sessionCoordinator.canReview(q.identifier, { completed });
2562
+ }
2563
+ /** The lifecycle of an item's session: the live one for the active item, else the persisted handoff. */
2564
+ itemLifecycleOf(itemIdentifier) {
2565
+ const current = this.items[this.currentItemIndex];
2566
+ if (current?.identifier === itemIdentifier) {
2567
+ return (this.currentItemSession?.state().lifecycleStatus ??
2568
+ this.state.itemSessions?.[itemIdentifier]?.lifecycleStatus);
2569
+ }
2570
+ return this.state.itemSessions?.[itemIdentifier]?.lifecycleStatus;
806
2571
  }
807
2572
  canNext() {
808
- if (this.currentItemIndex < 0)
809
- return false;
810
- const nextIdx = this.nextUnlockedIndex(this.currentItemIndex);
811
- if (nextIdx < 0)
812
- return false;
813
- if (!this.canNavigateByTestPart(nextIdx, this.currentItemIndex))
2573
+ const current = this.items[this.currentItemIndex];
2574
+ if (!current)
814
2575
  return false;
815
2576
  // Note: itemSessionControl constraints on leaving current item are enforced in next().
816
- return true;
2577
+ return this.forwardStepIndex(current) >= 0;
817
2578
  }
818
- canNavigateByTestPart(targetIndex, currentIndex) {
819
- if (targetIndex < 0 || targetIndex >= this.items.length)
820
- return false;
2579
+ /**
2580
+ * Whether a candidate-initiated move from `currentIndex` to `targetIndex` follows the
2581
+ * navigation rules (see `navigationPolicy.canNavigateByTestPart`).
2582
+ */
2583
+ canNavigateByTestPart(targetIndex, currentIndex, forward = () => {
821
2584
  const current = this.items[currentIndex];
822
- const target = this.items[targetIndex];
823
- if (!current || !target)
824
- return false;
825
- // Items locked by an expired time limit are passed over.
826
- const nextIndex = this.nextUnlockedIndex(currentIndex);
827
- if (current.testPart !== target.testPart) {
828
- // QTI testParts are delivered in sequence. A candidate may enter the next
829
- // part, but cannot jump across parts or return to a completed part.
830
- return targetIndex === nextIndex;
831
- }
832
- const mode = current.testPart.navigationMode ?? this.assessment.navigationMode ?? 'nonlinear';
833
- return mode === 'nonlinear' || targetIndex === currentIndex || targetIndex === nextIndex;
2585
+ return current ? this.unsubmittedForwardIndex(current) : -1;
2586
+ }) {
2587
+ return canNavigateByTestPart({
2588
+ targetIndex,
2589
+ currentIndex,
2590
+ items: this.items,
2591
+ assessment: this.assessment,
2592
+ forward,
2593
+ });
834
2594
  }
835
2595
  async submitSimultaneousItems(items) {
836
- if (items.every((q) => this.sessionCoordinator.hasItemResult(q.identifier)))
2596
+ // Items the backend already accepted with exactly these responses are done; one
2597
+ // whose recorded result predates the current responses still goes out.
2598
+ if (items.every((q) => !this.itemNeedsSubmission(q)))
837
2599
  return;
838
2600
  const current = this.items[this.currentItemIndex];
839
2601
  const submittedItem = current && items.includes(current) ? current : undefined;
@@ -849,14 +2611,18 @@ export class AssessmentPlayer {
849
2611
  // Some backend adapters return an updatedState snapshot that may only include
850
2612
  // responses for items that have been submitted so far, which would otherwise
851
2613
  // wipe out responses for later items during this loop.
852
- const allItemResponses = cloneData(this.state.itemResponses || {});
853
- allItemSessions = cloneData(this.state.itemSessions || {});
2614
+ const allItemResponses = cloneData(this.state.itemResponses) ?? {};
2615
+ allItemSessions = cloneData(this.state.itemSessions) ?? {};
854
2616
  for (const q of items) {
855
- if (this.sessionCoordinator.hasItemResult(q.identifier))
2617
+ if (!this.itemNeedsSubmission(q))
856
2618
  continue;
857
2619
  const submittedAt = Date.now();
858
- const responsesForItem = (allItemResponses?.[q.identifier] || {});
859
- const itemSession = this.endItemSessionForSubmit(q, responsesForItem, allItemSessions[q.identifier]);
2620
+ const responsesForItem = allItemResponses[q.identifier] || {};
2621
+ // An item an expired limit closed (or a proctor's end of the test) submits its
2622
+ // responses as they stand. Response validation is an individual-part control
2623
+ // (QTI), and a candidate's end of the test checked those items already.
2624
+ const submissionReason = this.submissionReasonFor(q);
2625
+ const itemSession = this.endItemSessionForSubmit(q, responsesForItem, allItemSessions[q.identifier], { validate: submissionReason === undefined && this.isIndividual(q) });
860
2626
  allItemSessions[q.identifier] = itemSession;
861
2627
  const res = await this.backend.submitResponses({
862
2628
  sessionId: this.sessionId,
@@ -864,31 +2630,41 @@ export class AssessmentPlayer {
864
2630
  responses: responsesForItem,
865
2631
  submittedAt,
866
2632
  timeSpent: itemSession.duration,
867
- timing: this.getSubmitTimingEvidence(q, itemSession.duration),
868
- itemSession: this.config.sendItemSessionToBackend ? itemSession : undefined,
2633
+ timing: this.getSubmitTimingEvidence(q, itemSession.duration, submissionReason),
2634
+ itemSession: this.sendsItemSession() ? itemSession : undefined,
869
2635
  comment: this.sessionCoordinator.getItemComment(q.identifier),
870
2636
  });
871
2637
  if (!res.success || !res.result) {
872
- throw new Error(res.error || `Submit failed for item ${q.identifier}`);
2638
+ // Backend error text stays on the Error for logs/host callbacks only.
2639
+ throw new AssessmentPlayerError('submitFailed', res.error || `Submit failed for item ${q.identifier}`);
873
2640
  }
874
2641
  if (res.updatedState) {
875
2642
  this.sessionCoordinator.replaceStatePreservingResponsesAndSessions(res.updatedState, allItemResponses, allItemSessions);
2643
+ this.sessionCoordinator.setItemResult({
2644
+ itemIdentifier: q.identifier,
2645
+ score: res.result.score,
2646
+ maxScore: res.result.maxScore,
2647
+ responses: this.state.itemResponses[q.identifier] || {},
2648
+ });
876
2649
  }
877
2650
  else {
878
- this.state.itemScores = this.state.itemScores || {};
879
- this.state.itemScores[q.identifier] = res.result;
880
- this.sessionCoordinator.markVisited(q.identifier);
881
- this.state.itemResponses[q.identifier] = responsesForItem;
882
- this.sessionCoordinator.setItemSession(q.identifier, itemSession);
883
- this.sessionCoordinator.recordAttempt(q.identifier);
2651
+ this.sessionCoordinator.recordSimultaneousSubmission(q.identifier, responsesForItem, itemSession, res.result);
2652
+ }
2653
+ // The accepted response set: a retry, a later collection pass, or finalize
2654
+ // must not re-submit identical responses for this item.
2655
+ this.lastSubmittedResponses.set(q.identifier, cloneResponseRecord(responsesForItem));
2656
+ // This submission voids every earlier decision (the outcomes they were decided
2657
+ // on have moved). Only a part crossing keeps the fresh one — the decision the
2658
+ // part's last item returns is what the crossing follows — while the end of the
2659
+ // test's own collection (the same submit path, for every item) stores none: it
2660
+ // never navigates.
2661
+ this.clearKeptBranchDecisions();
2662
+ if (this.endReason === null && res.nextItemIdentifier) {
2663
+ this.keepBranchDecision(q, res.nextItemIdentifier);
884
2664
  }
885
- this.sessionCoordinator.setItemResult({
886
- itemIdentifier: q.identifier,
887
- score: res.result.score,
888
- maxScore: res.result.maxScore,
889
- responses: this.state.itemResponses[q.identifier] || {},
890
- });
891
2665
  this.setTestOutcomes(res.outcomes);
2666
+ this.reportOutcomeProcessingError(res.outcomeProcessingError);
2667
+ this.reportItemScoringError(res.result);
892
2668
  }
893
2669
  // The attached item must represent the same accepted lifecycle as persistence.
894
2670
  // Replace the provisional suspended object with one restored from the accepted
@@ -897,7 +2673,8 @@ export class AssessmentPlayer {
897
2673
  const accepted = allItemSessions[submittedItem.identifier];
898
2674
  if (accepted) {
899
2675
  this.releaseCurrentItemSession();
900
- this.attachCurrentItemSession(submittedItem, this.getItemDefinition(submittedItem).openSession({ restore: accepted }));
2676
+ const presentation = this.presentationFor(submittedItem);
2677
+ this.attachCurrentItemSession(submittedItem, this.getItemDefinition(submittedItem).openSession({ restore: accepted, presentation }), presentation);
901
2678
  this.notifyItemChange();
902
2679
  }
903
2680
  }
@@ -916,7 +2693,8 @@ export class AssessmentPlayer {
916
2693
  }
917
2694
  this.releaseCurrentItemSession();
918
2695
  if (restored) {
919
- this.attachCurrentItemSession(submittedItem, this.getItemDefinition(submittedItem).openSession({ restore: restored }));
2696
+ const presentation = this.presentationFor(submittedItem);
2697
+ this.attachCurrentItemSession(submittedItem, this.getItemDefinition(submittedItem).openSession({ restore: restored, presentation }), presentation);
920
2698
  this.notifyItemChange();
921
2699
  this.notifyResponseChange();
922
2700
  }
@@ -924,28 +2702,241 @@ export class AssessmentPlayer {
924
2702
  throw error;
925
2703
  }
926
2704
  }
927
- /** Submit entire assessment (finalize on backend) */
928
- async submit() {
2705
+ /**
2706
+ * Submit the entire assessment and finalize on the backend — the single terminal
2707
+ * transition, also used for QTI `EXIT_TEST` (and for EXIT_TESTPART / EXIT_SECTION when
2708
+ * nothing follows the ended scope). Serialized with all other navigation and submission
2709
+ * transitions. Calling it again after the test has ended returns the same results.
2710
+ *
2711
+ * A candidate's submit is rejected while paused, and — with a coded
2712
+ * `finalizeResponseRequired` / `finalizeResponseInvalid` naming the items
2713
+ * (`getSubmissionBlockers()`) — while items in individual parts would be submitted
2714
+ * against their `allowSkipping=false` / `validateResponses=true` controls.
2715
+ *
2716
+ * `{ force: true }` is the proctor's administrative end of the test: it runs during a
2717
+ * pause, and neither minimum times nor the skipping/validation gates hold it back; the
2718
+ * collected submissions carry `timing.submissionReason: 'proctor'` — except items an
2719
+ * expired time limit closed, which go out as `time-expired` (time wins), and the end is
2720
+ * an `expiry` end when the time had already closed the delivery. It never fails for
2721
+ * concurrency: while a candidate's navigation or submission is in flight, it waits for
2722
+ * that transition to settle and then ends the test (when the transition itself ended
2723
+ * the test, it resolves with those results).
2724
+ */
2725
+ submit(options = {}) {
2726
+ if (options.force === true) {
2727
+ return this.runWhenIdle(async () => {
2728
+ this.administrativeReason = 'proctor';
2729
+ try {
2730
+ return await this.endTestInternal({ administrative: true, reason: 'proctor' });
2731
+ }
2732
+ finally {
2733
+ this.administrativeReason = null;
2734
+ }
2735
+ });
2736
+ }
2737
+ return this.runCandidateTransition(() => this.endTestInternal({ reason: 'candidate' }));
2738
+ }
2739
+ /**
2740
+ * Run an administrative transition exclusively as soon as the lock is free: queued
2741
+ * behind the transition in flight (a pause, a force submit, an expiry hop) instead of
2742
+ * rejecting as busy. The lock is taken synchronously when the in-flight transition
2743
+ * releases it, so no candidate action can slip in between. Rejects only when the
2744
+ * player is destroyed.
2745
+ */
2746
+ runWhenIdle(operation) {
2747
+ if (this.destroyed) {
2748
+ return Promise.reject(new AssessmentPlayerError('navigationNotAllowed', 'The assessment player was destroyed.'));
2749
+ }
2750
+ if (!this.transitionInFlight)
2751
+ return this.runExclusive(operation);
2752
+ return new Promise((resolve, reject) => {
2753
+ const cancel = (error) => {
2754
+ off();
2755
+ reject(error);
2756
+ };
2757
+ const off = this.onBusyChange((busy) => {
2758
+ if (busy || this.transitionInFlight)
2759
+ return;
2760
+ off();
2761
+ this.queuedIdleTransitions.delete(cancel);
2762
+ this.runWhenIdle(operation).then(resolve, reject);
2763
+ });
2764
+ this.queuedIdleTransitions.add(cancel);
2765
+ });
2766
+ }
2767
+ /**
2768
+ * Whether an expired hard limit closed the delivery: the whole test expired, or the
2769
+ * current item sits inside an expired scope and no open question remains reachable from
2770
+ * it (an expiry dead end). An earlier question still open in the part keeps delivery
2771
+ * open — the expiry moves the candidate there instead — so its skipping/validation
2772
+ * controls and minimum times keep applying. Only a closed delivery is collected as
2773
+ * `time-expired` without them.
2774
+ */
2775
+ isTimeClosedDelivery() {
2776
+ if (this.assessmentExpired)
2777
+ return true;
929
2778
  const current = this.items[this.currentItemIndex];
930
- if (current) {
931
- this.assertMinimumTime('item', current);
932
- this.assertMinimumTime('section', current);
933
- this.assertMinimumTime('testPart', current);
2779
+ return current !== undefined && this.isItemLocked(current) && this.openItemAfterClosure(current.index) < 0;
2780
+ }
2781
+ /**
2782
+ * Why an item's submission runs: an item an expired hard limit closed submits the
2783
+ * responses frozen at the expiry (`time-expired`) — its own scope expired, or the
2784
+ * whole test did; a proctor's forced end of the test collects as `proctor`; a question
2785
+ * the candidate can no longer reach although its QTI skipping/validation control would
2786
+ * refuse it is collected as it stands (`unreachable`); everything else is a normal
2787
+ * candidate submission.
2788
+ */
2789
+ submissionReasonFor(q) {
2790
+ if (this.assessmentExpired || this.isItemLocked(q))
2791
+ return 'time-expired';
2792
+ if (this.administrativeReason)
2793
+ return this.administrativeReason;
2794
+ if (this.unreachableCollection.has(q.identifier))
2795
+ return 'unreachable';
2796
+ return undefined;
2797
+ }
2798
+ /**
2799
+ * The one normal-end-of-test path: pending simultaneous-mode responses are submitted,
2800
+ * the current individual-mode item is submitted if needed, then the backend finalizes
2801
+ * (outcome processing runs, results are produced) and navigation closes. Individual-
2802
+ * mode attempts an expired limit closed are collected as well: their responses were
2803
+ * frozen when the time ran out. The same is true for any visited individual-mode item
2804
+ * whose responses never reached the backend because the candidate jumped away without
2805
+ * a forward submission (nonlinear `navigateTo`/`previous` submit nothing): it is
2806
+ * collected through the same detached end-attempt loop instead of being finalized
2807
+ * from NULL.
2808
+ *
2809
+ * A candidate-initiated end of the test first checks the QTI submission controls of
2810
+ * individual parts: it never submits an item without a response while
2811
+ * `allowSkipping=false`, nor an answered item whose responses fail validation while
2812
+ * `validateResponses=true` — it rejects naming them instead, as long as the candidate
2813
+ * can still reach them. A question in a test part already left cannot hold the end of
2814
+ * the test: it is collected as it stands (`submissionReason: 'unreachable'`). An
2815
+ * administrative end (a time expiry, a proctor's forced submit) collects everything as
2816
+ * it stands; an item a skipping control held back is then recorded as skipped.
2817
+ *
2818
+ * `reason` records why the test ends; the outermost caller decides (a candidate's
2819
+ * submit whose final submission branches to EXIT_TEST stays a candidate end) — except
2820
+ * that an end collecting a delivery the time already closed (the whole test expired, or
2821
+ * an expiry dead end left nothing open) is an `expiry` end whoever triggers it: the
2822
+ * auto-finalize, the candidate's Submit after it failed, a proctor's force-submit.
2823
+ *
2824
+ * The end never navigates: it collects where the candidate stands. A branch decision
2825
+ * its own submission returns is kept on record (`followBranch`), and a scope expiry
2826
+ * while it runs only closes the scope — moving delivery off it waits for this end and
2827
+ * happens only if the end does not finalize.
2828
+ */
2829
+ async endTestInternal(options = {}) {
2830
+ if (this.finalized && this.finalResults)
2831
+ return this.finalResults;
2832
+ const outermost = this.endReason === null;
2833
+ if (outermost)
2834
+ this.endReason = this.isTimeClosedDelivery() ? 'expiry' : (options.reason ?? 'candidate');
2835
+ try {
2836
+ return await this.collectAndFinalize(options.administrative === true);
2837
+ }
2838
+ finally {
2839
+ if (outermost) {
2840
+ this.unreachableCollection = new Set();
2841
+ const heldExpiries = this.expiriesDuringEnd.splice(0);
2842
+ if (!this.finalized) {
2843
+ // A refused or failed end leaves the test running: no reason is pending,
2844
+ // and delivery now leaves the scopes that expired while it ran — inline,
2845
+ // under the lock the end still holds.
2846
+ this.endReason = null;
2847
+ for (const expiry of heldExpiries)
2848
+ void this.leaveExpiredScopeLocked(expiry.scope, expiry.identifier);
2849
+ }
2850
+ }
2851
+ }
2852
+ }
2853
+ async collectAndFinalize(administrative) {
2854
+ const closed = administrative || this.isTimeClosedDelivery();
2855
+ const current = this.items[this.currentItemIndex];
2856
+ if (current && !closed) {
2857
+ // A current item an expired limit closed is collected as it stands: its own and
2858
+ // its scopes' minimum times cannot hold the end of the test.
2859
+ if (!this.isItemLocked(current)) {
2860
+ this.assertMinimumTime('item', current);
2861
+ this.assertEnclosingSectionMinimumTime(current);
2862
+ this.assertMinimumTime('testPart', current);
2863
+ }
934
2864
  this.assertMinimumTime('assessment', current);
935
2865
  }
2866
+ if (!closed)
2867
+ this.assertNoSubmissionBlockers();
2868
+ // Questions the candidate can no longer reach go out as they stand, marked so the
2869
+ // backend never mistakes them for a normal candidate submission.
2870
+ if (!administrative) {
2871
+ this.unreachableCollection = new Set(this.getUnreachableSubmissionBlockers().map((blocker) => blocker.identifier));
2872
+ }
2873
+ const isIndividual = (q) => this.isIndividual(q);
936
2874
  // Submission modes belong to test parts. The assessment-level field is only
937
2875
  // a fallback for older hosts that do not supply a mode on each part.
938
- await this.submitSimultaneousItems(this.items.filter((q) => (q.testPart.submissionMode ?? this.assessment.submissionMode) === 'simultaneous'));
2876
+ await this.submitSimultaneousItems(this.items.filter((q) => effectiveSubmissionMode(q.testPart, this.assessment) === 'simultaneous'));
2877
+ if (this.finalized && this.finalResults)
2878
+ return this.finalResults;
2879
+ await this.submitSimultaneousItems(this.items.filter((q) => q !== current &&
2880
+ isIndividual(q) &&
2881
+ this.navigationManager.isVisited(q.index) &&
2882
+ // Only what the backend has not accepted yet: an expired limit froze the
2883
+ // item's responses, but responses it already accepted are never re-sent
2884
+ // (that would spend another attempt and fail the end of the test).
2885
+ this.itemNeedsSubmission(q)));
939
2886
  const q = this.items[this.currentItemIndex];
940
- if (q && (q.testPart.submissionMode ?? this.assessment.submissionMode) === 'individual'
941
- && !this.sessionCoordinator.hasItemResult(q.identifier)) {
942
- await this.submitCurrentItem();
2887
+ if (q && isIndividual(q)) {
2888
+ const liveStatus = this.currentItemSession?.state().lifecycleStatus;
2889
+ const liveWritable = liveStatus !== undefined && isWritableItemLifecycle(liveStatus);
2890
+ const hasResult = this.sessionCoordinator.hasItemResult(q.identifier);
2891
+ // An item without a recorded result is collected as it stands (an expired limit
2892
+ // closed it, or the candidate is leaving it open). An item with a recorded
2893
+ // result — a practice check — re-submits only when the live attempt is still
2894
+ // open, attempts remain, and the candidate changed their response.
2895
+ const needsSubmission = !hasResult
2896
+ ? true
2897
+ : liveWritable
2898
+ ? this.sessionCoordinator.canSubmit(q.identifier) &&
2899
+ !this.responsesUnchangedSinceSubmission(q.identifier)
2900
+ : false;
2901
+ if (needsSubmission) {
2902
+ // Collected where the candidate stands: a branch decision this submission
2903
+ // returns is kept on record, never followed (`followBranch`).
2904
+ await this.submitCurrentItemInternal();
2905
+ if (this.finalized && this.finalResults)
2906
+ return this.finalResults;
2907
+ }
2908
+ }
2909
+ return this.finalizeInternal();
2910
+ }
2911
+ async finalizeInternal() {
2912
+ if (this.finalized && this.finalResults)
2913
+ return this.finalResults;
2914
+ // Persist the final draft before the backend finalizes: outcome processing reads
2915
+ // the stored timing (the built-in durations), so it must see the end-of-test
2916
+ // clocks, not the last debounced autosave. Safe mid-transition (inside the
2917
+ // exclusive lock); a failed save stays non-fatal. It is the record of the ended
2918
+ // test, so every item session in it is over: a practice item reopened for attempts
2919
+ // the candidate did not use stands closed, as the backend last accepted it (the
2920
+ // collection re-sent every changed response).
2921
+ this.snapshotsCloseItemSessions = true;
2922
+ try {
2923
+ await this.autosave?.flushImmediate();
2924
+ }
2925
+ finally {
2926
+ this.snapshotsCloseItemSessions = false;
2927
+ }
2928
+ let finalized;
2929
+ try {
2930
+ finalized = await this.backend.finalizeAssessment({ sessionId: this.sessionId });
2931
+ if (!finalized.success)
2932
+ throw new AssessmentPlayerError('finalizeFailed', 'Finalize failed');
2933
+ }
2934
+ catch (error) {
2935
+ // The test goes on: the stored draft gets its open sessions back, so attempts the
2936
+ // candidate may still use survive a reload.
2937
+ await this.autosave?.flushImmediate();
2938
+ throw error;
943
2939
  }
944
- const finalized = await this.backend.finalizeAssessment({
945
- sessionId: this.sessionId,
946
- });
947
- if (!finalized.success)
948
- throw new Error('Finalize failed');
949
2940
  // Map backend itemScores to ItemResult[]
950
2941
  const itemScores = finalized.itemScores || {};
951
2942
  const itemResults = Object.values(itemScores).map((r) => ({
@@ -957,23 +2948,125 @@ export class AssessmentPlayer {
957
2948
  // Outcome processing has run by the end of the test, so a backend returning no outcomes
958
2949
  // leaves them all NULL.
959
2950
  this.finalized = true;
960
- this.legacyFeedback = finalized.feedback;
2951
+ // A proctor's forced end of the test may land during a pause: the session is over,
2952
+ // so the pause no longer holds anything (no pause event — the end of the test is it).
2953
+ this.pauseControl.clearSilently();
2954
+ this.suspendedForPause = false;
2955
+ // The test ended through its real submission: draft autosave has nothing left to do.
2956
+ this.autosave?.stop();
2957
+ // Delivery is over: no clock keeps running, and no later expiry can fire.
2958
+ this.timeManager?.pause();
2959
+ this.timeManager?.stopTimer();
961
2960
  this.testOutcomes = cloneData(finalized.outcomes ?? this.testOutcomes ?? {});
2961
+ // The persisted snapshot carries them (testFeedback and rules read them on a resume).
2962
+ this.sessionCoordinator.setTestOutcomes(this.testOutcomes);
962
2963
  this.notifyTestFeedbackChange();
963
- this.notifyComplete();
964
- if (this.config.onComplete)
965
- this.config.onComplete();
966
- return {
2964
+ this.reportOutcomeProcessingError(finalized.outcomeProcessingError);
2965
+ const endReason = this.endReason ?? 'candidate';
2966
+ this.endReason = endReason;
2967
+ const results = {
967
2968
  totalScore: finalized.totalScore,
968
2969
  maxScore: finalized.maxScore,
969
2970
  itemResults,
970
2971
  completedAt: new Date(finalized.finalizedAt),
2972
+ endReason,
971
2973
  };
2974
+ if (this.reportedOutcomeProcessingError) {
2975
+ results.outcomeProcessingError = this.reportedOutcomeProcessingError;
2976
+ }
2977
+ this.finalResults = results;
2978
+ // The test is over: no decision remains for delivery to follow.
2979
+ this.clearKeptBranchDecisions();
2980
+ // Every delivered item session is over, the active one included: the player's record
2981
+ // of the ended test reports each as final, never as owing a submission.
2982
+ this.closeItemSessionsForEnd();
2983
+ // Completion listeners run once the results exist, so `getResultsSummary()` (the
2984
+ // shell's completion screen), `getEndReason()` and `submit()` already report them.
2985
+ // Every ending reaches them alike — a candidate submit, a proctor's force-submit, an
2986
+ // EXIT_TEST branch, a whole-test expiry — so a shell hands the results to its host
2987
+ // from here.
2988
+ this.notifyComplete(results);
2989
+ if (this.config.onComplete)
2990
+ this.config.onComplete(results);
2991
+ this.config.onFinalized?.({ restored: false, results, endReason });
2992
+ return results;
2993
+ }
2994
+ /**
2995
+ * Why the test ended in this delivery (`candidate`, `expiry`, `proctor` or `branch`);
2996
+ * null while it runs and for a session restored already finalized.
2997
+ */
2998
+ getEndReason() {
2999
+ return this.finalized ? this.endReason : null;
3000
+ }
3001
+ /**
3002
+ * The test ended: close every delivered item session in the player's record. Nothing
3003
+ * can be submitted any more, so an item a practice check reopened for attempts the
3004
+ * candidate did not use stands as the backend accepted it; the active item's live
3005
+ * session is replaced by a closed one (read-only; no item change — the end never
3006
+ * navigates).
3007
+ */
3008
+ closeItemSessionsForEnd() {
3009
+ this.sessionCoordinator.closeAllItemSessions();
3010
+ const q = this.items[this.currentItemIndex];
3011
+ const live = this.currentItemSession;
3012
+ if (!q || !live || live.state().lifecycleStatus === 'closed')
3013
+ return;
3014
+ const closed = closedItemSession(live.serialize());
3015
+ this.sessionCoordinator.setItemSession(q.identifier, closed);
3016
+ const presentation = this.presentationFor(q);
3017
+ this.releaseCurrentItemSession();
3018
+ this.attachCurrentItemSession(q, this.getItemDefinition(q).openSession({ restore: closed, presentation }), presentation);
3019
+ }
3020
+ /**
3021
+ * Surface a backend test-level outcome-processing failure to the host (onError and,
3022
+ * for finalize, the results). Candidate responses stay accepted and persisted; only
3023
+ * SCORE/testFeedback computation failed.
3024
+ */
3025
+ reportOutcomeProcessingError(error) {
3026
+ if (!error)
3027
+ return;
3028
+ const isNew = !this.reportedOutcomeProcessingError ||
3029
+ this.reportedOutcomeProcessingError.message !== error.message ||
3030
+ this.reportedOutcomeProcessingError.code !== error.code;
3031
+ this.reportedOutcomeProcessingError = error;
3032
+ if (isNew) {
3033
+ this.config.onError?.(new AssessmentPlayerError('outcomeProcessingFailed', error.message, { code: error.code }));
3034
+ }
3035
+ }
3036
+ /**
3037
+ * A backend scoring result whose response processing failed carries a degenerate 0
3038
+ * (its declared maximum where known) plus a `scoringError` — the item-level mirror of
3039
+ * `outcomeProcessingError`. The submission stands and delivery continues, but the host
3040
+ * must be able to tell "answered wrong" from "the engine failed to score"; each
3041
+ * distinct item failure is reported once.
3042
+ */
3043
+ reportItemScoringError(result) {
3044
+ const error = result?.scoringError;
3045
+ if (!error)
3046
+ return;
3047
+ const itemIdentifier = result?.itemIdentifier;
3048
+ this.reportOnce(this.reportedItemScoringErrors, `${itemIdentifier}\n${error.message}`, () => new AssessmentPlayerError('itemScoringFailed', error.message, {
3049
+ itemIdentifier: itemIdentifier ?? '',
3050
+ code: error.code,
3051
+ }));
3052
+ }
3053
+ /**
3054
+ * Report a distinct failure to the host once: `seen` holds the keys already reported,
3055
+ * `key` encodes what makes one failure distinct from another (each reporter composes
3056
+ * its own), and `build` constructs the coded error the host hears through
3057
+ * `config.onError` the first time the key is seen.
3058
+ */
3059
+ reportOnce(seen, key, build) {
3060
+ if (seen.has(key))
3061
+ return;
3062
+ seen.add(key);
3063
+ this.config.onError?.(build());
972
3064
  }
973
3065
  // ---------------------------------------------------------------------------
974
3066
  // Session info + time helpers
975
3067
  // ---------------------------------------------------------------------------
976
- getItemSessionInfo(_itemIdentifier) {
3068
+ /** The current item's session-control state (attempts, feedback, review, skipping, comments); null before delivery. */
3069
+ getItemSessionInfo() {
977
3070
  const q = this.items[this.currentItemIndex];
978
3071
  if (!q)
979
3072
  return null;
@@ -989,6 +3082,8 @@ export class AssessmentPlayer {
989
3082
  if (!id)
990
3083
  throw new Error('No current item');
991
3084
  this.sessionCoordinator.setItemComment(id, comment);
3085
+ // Comments ride the persisted snapshot (`itemComments`), so autosave runs too.
3086
+ this.notifyAutosaveActivity();
992
3087
  }
993
3088
  getItemComment(itemIdentifier) {
994
3089
  const id = itemIdentifier ?? this.items[this.currentItemIndex]?.identifier;
@@ -1005,103 +3100,262 @@ export class AssessmentPlayer {
1005
3100
  return this.timeManager?.isExpired() ?? false;
1006
3101
  }
1007
3102
  // ---------------------------------------------------------------------------
3103
+ // Time administration: begin gate, proctor pause, countdown state
3104
+ // ---------------------------------------------------------------------------
3105
+ /** Whether delivery has begun. False only while an opt-in begin gate holds the start screen. */
3106
+ hasStarted() {
3107
+ return this.started;
3108
+ }
3109
+ /**
3110
+ * Open the begin gate (`beginGate` config): enter the first — or restored — item and
3111
+ * start every clock. The shell calls it from its Begin button. Idempotent, and a no-op
3112
+ * without a begin gate (the player then started at creation). A proctor pause in
3113
+ * force keeps the clocks frozen until `resume()`.
3114
+ */
3115
+ start() {
3116
+ // A test that already ended (a proctor's force-submit behind the gate) never starts.
3117
+ if (this.started || this.destroyed || this.finalized)
3118
+ return;
3119
+ this.started = true;
3120
+ if (!this.paused)
3121
+ this.timeManager?.resume();
3122
+ this.enterInitialItem();
3123
+ this.finalizeRestoredExpiryWhenRunning();
3124
+ }
3125
+ /**
3126
+ * Proctor pause. Freezes every clock — assessment, test part, section and item; the
3127
+ * live attempt is suspended so its QTI `duration` stops too — and rejects candidate
3128
+ * actions with a coded `assessmentPaused` error until `resume()`. `reason` is
3129
+ * host-supplied, candidate-facing text shown with the pause (localize it in the host).
3130
+ * A pause requested during a navigation or submission applies once it settles; while
3131
+ * already paused, a new reason replaces the shown one. No-op after the test ended.
3132
+ */
3133
+ pause(reason) {
3134
+ if (this.finalized || this.destroyed)
3135
+ return;
3136
+ this.pauseControl.pause(reason);
3137
+ }
3138
+ /** End a proctor pause: the clocks continue and the live attempt reopens where it stood. */
3139
+ resume() {
3140
+ this.pauseControl.resume();
3141
+ }
3142
+ isPaused() {
3143
+ return this.paused;
3144
+ }
3145
+ /** The candidate-facing reason given for the current pause, if any. */
3146
+ getPauseReason() {
3147
+ return this.paused ? this.pauseReason : undefined;
3148
+ }
3149
+ /** The countdown a shell shows: the active scope's nearest hard maximum and the clock state. */
3150
+ getTimeState() {
3151
+ const nearest = this.timeManager?.getNearestLimit() ?? null;
3152
+ return {
3153
+ limited: nearest !== null,
3154
+ remainingSeconds: nearest ? Math.max(0, Math.ceil(nearest.remainingSeconds)) : null,
3155
+ elapsedSeconds: this.getElapsedTime(),
3156
+ expired: nearest !== null && nearest.remainingSeconds <= 0,
3157
+ scope: nearest?.scope ?? null,
3158
+ allowLateSubmission: nearest?.allowLateSubmission ?? false,
3159
+ paused: this.paused,
3160
+ started: this.started,
3161
+ };
3162
+ }
3163
+ /**
3164
+ * Whether the session is terminal: the test has ended here, or the backend restored a
3165
+ * session it had already finalized. Shells show their completed view; `submit()`
3166
+ * returns the stored results without another backend round trip.
3167
+ */
3168
+ isFinalized() {
3169
+ return this.finalized;
3170
+ }
3171
+ /** The stored results of a session restored already finalized. */
3172
+ finalResultsFromInit(init) {
3173
+ const summary = init.finalResults;
3174
+ const itemScores = summary?.itemScores ?? {};
3175
+ const itemResults = Object.values(itemScores).map((r) => ({
3176
+ itemIdentifier: r.itemIdentifier,
3177
+ score: r.score,
3178
+ maxScore: r.maxScore,
3179
+ responses: (this.state.itemResponses[r.itemIdentifier] ?? {}),
3180
+ }));
3181
+ return {
3182
+ totalScore: summary?.totalScore ?? 0,
3183
+ maxScore: summary?.maxScore ?? 0,
3184
+ itemResults,
3185
+ completedAt: new Date(summary?.finalizedAt ?? Date.now()),
3186
+ };
3187
+ }
3188
+ /**
3189
+ * What a start screen shows before delivery begins: the test title, the time the
3190
+ * candidate has for the whole test (PNP extended time applied; what remains of it for
3191
+ * a resumed session), whether parts, sections or items carry their own limits, and the
3192
+ * first test part's rubric blocks (role-filter them before display).
3193
+ */
3194
+ getStartInfo() {
3195
+ const extended = this.config.pnp?.content?.extendedTime;
3196
+ const limited = (limits) => limits?.maxTime !== undefined && extendTimeLimit(limits.maxTime, extended) !== undefined;
3197
+ const testRemaining = this.timeManager?.getAssessmentRemainingSeconds() ?? null;
3198
+ const firstPart = this.items[0]?.testPart ?? this.assessment.testParts?.[0];
3199
+ return {
3200
+ title: this.getAssessmentTitle(),
3201
+ testTimeLimitSeconds: testRemaining === null ? undefined : Math.max(0, Math.ceil(testRemaining)),
3202
+ hasScopedTimeLimits: this.items.some((q) => limited(q.testPart.timeLimits) ||
3203
+ q.sections.some((section) => limited(section.timeLimits)) ||
3204
+ limited(q.item.timeLimits)),
3205
+ rubricBlocks: (firstPart?.rubricBlocks ?? []).map((block) => ({ ...block, view: [...block.view] })),
3206
+ totalItems: this.items.length,
3207
+ resuming: (this.state.timing?.totalTime ?? 0) > 0 || this.state.visitedItems.length > 0,
3208
+ savedAt: this.getRestoredSavedAt(),
3209
+ };
3210
+ }
3211
+ /** Whether the candidate hid the countdown. Persisted in the session state, like flags. */
3212
+ isTimerHidden() {
3213
+ return this.state.timerHidden === true;
3214
+ }
3215
+ setTimerHidden(hidden) {
3216
+ this.sessionCoordinator.setTimerHidden(hidden);
3217
+ // The preference rides the persisted snapshot, like flags.
3218
+ this.notifyAutosaveActivity();
3219
+ }
3220
+ // ---------------------------------------------------------------------------
1008
3221
  // Event subscriptions
1009
3222
  // ---------------------------------------------------------------------------
1010
3223
  onItemChange(listener) {
1011
- this.itemChangeListeners.add(listener);
1012
- return () => this.itemChangeListeners.delete(listener);
3224
+ return this.events.on('itemChange', listener);
1013
3225
  }
1014
3226
  onSectionChange(listener) {
1015
- this.sectionChangeListeners.add(listener);
1016
- return () => this.sectionChangeListeners.delete(listener);
3227
+ return this.events.on('sectionChange', listener);
1017
3228
  }
1018
3229
  onResponseChange(listener) {
1019
- this.responseChangeListeners.add(listener);
1020
- return () => this.responseChangeListeners.delete(listener);
3230
+ return this.events.on('responseChange', listener);
1021
3231
  }
3232
+ /**
3233
+ * The test ended in this delivery — by any path: a candidate submit, a proctor's
3234
+ * force-submit, a QTI EXIT_TEST branch, a whole-test expiry — with its results.
3235
+ */
1022
3236
  onComplete(listener) {
1023
- this.completeListeners.add(listener);
1024
- return () => this.completeListeners.delete(listener);
3237
+ return this.events.on('complete', listener);
3238
+ }
3239
+ /** Fires when a navigation/submission transition starts or ends (`getNavigationState().isLoading` mirrors this). */
3240
+ onBusyChange(listener) {
3241
+ return this.events.on('busyChange', listener);
1025
3242
  }
1026
3243
  /** Called when `getVisibleFeedback()` may have changed: new outcomes, a new test part, or the end. */
1027
3244
  onTestFeedbackChange(listener) {
1028
- this.testFeedbackChangeListeners.add(listener);
1029
- return () => this.testFeedbackChangeListeners.delete(listener);
3245
+ return this.events.on('testFeedbackChange', listener);
1030
3246
  }
1031
3247
  onTimeWarning(listener) {
1032
- this.timeWarningListeners.add(listener);
1033
- return () => this.timeWarningListeners.delete(listener);
3248
+ return this.events.on('timeWarning', listener);
1034
3249
  }
3250
+ /**
3251
+ * A hard time limit ran out with no late submission: the whole test (the core then
3252
+ * finalizes automatically; the event follows with `autoFinalized`, or with
3253
+ * `submissionRequired` when finalization failed), or a scope whose expiry leaves nothing
3254
+ * unlocked (`submissionRequired`: the candidate must submit now).
3255
+ */
1035
3256
  onTimeExpired(listener) {
1036
- this.timeExpiredListeners.add(listener);
1037
- return () => this.timeExpiredListeners.delete(listener);
3257
+ return this.events.on('timeExpired', listener);
3258
+ }
3259
+ /** A test part, section or item limit expired: its items closed, delivery moved on if it could. */
3260
+ onScopeTimeExpired(listener) {
3261
+ return this.events.on('scopeTimeExpired', listener);
3262
+ }
3263
+ /** Fires when a proctor pause starts (with its reason) or ends. */
3264
+ onPauseChange(listener) {
3265
+ return this.events.on('pauseChange', listener);
1038
3266
  }
1039
3267
  onTimeTick(listener) {
1040
- this.timeTickListeners.add(listener);
1041
- return () => this.timeTickListeners.delete(listener);
3268
+ return this.events.on('timeTick', listener);
1042
3269
  }
1043
3270
  destroy() {
3271
+ this.destroyed = true;
3272
+ // A transition queued behind the one in flight can no longer run.
3273
+ for (const cancel of [...this.queuedIdleTransitions]) {
3274
+ cancel(new AssessmentPlayerError('navigationNotAllowed', 'The assessment player was destroyed.'));
3275
+ }
3276
+ this.queuedIdleTransitions.clear();
3277
+ this.autosave?.stop();
1044
3278
  this.timeManager?.destroy();
1045
3279
  this.releaseCurrentItemSession();
3280
+ this.lastItemFeedback = null;
3281
+ this.clearKeptBranchDecisions();
1046
3282
  this.itemDefinitions.clear();
1047
- this.itemChangeListeners.clear();
1048
- this.sectionChangeListeners.clear();
1049
- this.responseChangeListeners.clear();
1050
- this.completeListeners.clear();
1051
- this.testFeedbackChangeListeners.clear();
1052
- this.timeWarningListeners.clear();
1053
- this.timeExpiredListeners.clear();
1054
- this.timeTickListeners.clear();
3283
+ this.events.clear();
3284
+ this.reviewInfoCache.clear();
1055
3285
  }
1056
3286
  // ---------------------------------------------------------------------------
1057
3287
  // Internal notify helpers
1058
3288
  // ---------------------------------------------------------------------------
1059
3289
  notifyItemChange() {
1060
- for (const l of this.itemChangeListeners)
1061
- l(this.currentItemIndex, this.items.length);
3290
+ this.events.emit('itemChange', this.currentItemIndex, this.items.length);
1062
3291
  this.config.onItemChange?.(this.currentItemIndex, this.items.length);
3292
+ // A navigation settles into a new draft worth persisting.
3293
+ this.notifyAutosaveActivity();
1063
3294
  }
1064
3295
  notifySectionChange() {
1065
3296
  const q = this.items[this.currentItemIndex];
1066
- const sectionIndex = q?.sectionIndex ?? 0;
1067
- const totalSections = this.getAllSections().length;
1068
- for (const l of this.sectionChangeListeners)
1069
- l(sectionIndex, totalSections);
3297
+ const sectionIndex = q?.sectionIndex ?? -1;
3298
+ const totalSections = this.presentedSectionList().length;
3299
+ this.events.emit('sectionChange', sectionIndex, totalSections);
1070
3300
  this.config.onSectionChange?.(sectionIndex, totalSections);
1071
3301
  }
1072
3302
  notifyResponseChange() {
1073
3303
  const responses = this.sessionCoordinator.getActiveResponses();
1074
- for (const l of this.responseChangeListeners)
1075
- l(responses);
3304
+ this.events.emit('responseChange', responses);
1076
3305
  this.config.onResponseChange?.(responses);
3306
+ // Candidate input happened: restart the autosave debounce.
3307
+ this.notifyAutosaveActivity();
3308
+ }
3309
+ notifyComplete(results) {
3310
+ this.events.emit('complete', results);
1077
3311
  }
1078
- notifyComplete() {
1079
- for (const l of this.completeListeners)
1080
- l();
3312
+ notifyBusyChange(busy) {
3313
+ this.events.emit('busyChange', busy);
1081
3314
  }
1082
3315
  notifyTestFeedbackChange() {
1083
- for (const l of this.testFeedbackChangeListeners)
1084
- l();
3316
+ this.events.emit('testFeedbackChange');
1085
3317
  }
1086
3318
  notifyTimeWarning(remainingSeconds) {
1087
- for (const l of this.timeWarningListeners)
1088
- l(remainingSeconds);
1089
- }
1090
- evaluateTemplateDefaults(q) {
1091
- const defaults = q.item.templateDefaults;
1092
- if (!defaults?.length)
1093
- return undefined;
1094
- const declarations = testOutcomeDeclarations(this.assessment, this.testOutcomes ?? undefined);
1095
- const out = {};
1096
- for (const { templateIdentifier, expressionXml } of defaults) {
1097
- out[templateIdentifier] = plainQtiValue(evaluateTestExpression(expressionXml, declarations, Math.random));
1098
- }
1099
- return out;
3319
+ this.events.emit('timeWarning', remainingSeconds);
3320
+ }
3321
+ notifyPauseChange() {
3322
+ const reason = this.pauseReason;
3323
+ this.events.emit('pauseChange', this.paused, reason);
3324
+ this.config.onPauseChange?.(this.paused, reason);
3325
+ // The pause rides the snapshot (`timing.isPaused`), so persist it too.
3326
+ this.notifyAutosaveActivity();
3327
+ }
3328
+ /**
3329
+ * The template defaults an item's new session starts from (QTI `templateDefault`;
3330
+ * see `templateDefaults.templateDefaultsFor`). The part cache is the player's.
3331
+ */
3332
+ templateDefaultsFor(q) {
3333
+ return templateDefaultsFor({
3334
+ q,
3335
+ items: this.items,
3336
+ assessment: this.assessment,
3337
+ outcomes: this.testOutcomes,
3338
+ persistedSessions: this.state.itemSessions,
3339
+ byPart: this.templateDefaultsByPart,
3340
+ });
1100
3341
  }
1101
3342
  isItemLocked(q) {
1102
- return (this.lockedScopes.has(`item:${q.identifier}`) ||
1103
- this.lockedScopes.has(`testPart:${q.testPart.identifier}`) ||
1104
- q.sections.some((section) => this.lockedScopes.has(`section:${section.identifier}`)));
3343
+ return isItemLocked(q, this.scopeLocks, this.assessmentExpired);
3344
+ }
3345
+ /** The expired scope that closes an item (outermost first); the assessment for a whole-test expiry. */
3346
+ lockingScopeOf(q) {
3347
+ return lockingScopeOf(q, this.scopeLocks, this.assessmentExpired);
3348
+ }
3349
+ /**
3350
+ * Nothing open remains (a restore, or a start over, landed on an expired scope with
3351
+ * no open item after it): the candidate must submit now — the same report the live
3352
+ * expiry dead end makes, so the shell offers Submit wherever the candidate is.
3353
+ */
3354
+ notifyExpiryDeadEnd() {
3355
+ if (this.finalized || this.destroyed)
3356
+ return;
3357
+ const scope = this.lockingScopeOf(this.items[this.currentItemIndex]);
3358
+ this.notifyTimeExpired({ ...scope, autoFinalized: false, submissionRequired: true });
1105
3359
  }
1106
3360
  nextUnlockedIndex(fromIndex) {
1107
3361
  for (let i = fromIndex + 1; i < this.items.length; i++) {
@@ -1110,31 +3364,191 @@ export class AssessmentPlayer {
1110
3364
  }
1111
3365
  return -1;
1112
3366
  }
3367
+ /**
3368
+ * Whether delivery may land on the item after a closure: no expired limit closed it and
3369
+ * the review policy lets the candidate be there (QTI `allowReview` once its attempts are
3370
+ * used up). Later parts are entered fresh, so only the time lock applies to them.
3371
+ */
3372
+ isOpenTarget(q) {
3373
+ return !this.isItemLocked(q) && this.canReviewItem(q);
3374
+ }
3375
+ /**
3376
+ * Where delivery goes when the item at `fromIndex` closes (a scope expiry, or a restore
3377
+ * that lands on a closed item), looking across the whole reachable delivery rather than
3378
+ * only forward: the next open item of its test part; else — in a nonlinear part — the
3379
+ * nearest open item before it; else the first open item of a later part (parts are
3380
+ * delivered in order, so earlier parts are never re-entered, and a part is left only
3381
+ * when nothing in it is open any more). Forward, only items the delivery rules reach
3382
+ * count: a part (or, in a linear part, a section or item) whose precondition fails is
3383
+ * skipped as on any forward step. -1 when nothing open remains: the expiry dead end,
3384
+ * where the candidate's way out is the submission.
3385
+ */
3386
+ openItemAfterClosure(fromIndex) {
3387
+ const from = this.items[fromIndex];
3388
+ if (!from)
3389
+ return -1;
3390
+ const decls = this.hasDeliveryRules ? this.navigationDeclarationsFor(from) : undefined;
3391
+ for (const i of this.eligibleIndexesAfter(fromIndex, decls)) {
3392
+ const q = this.items[i];
3393
+ if (q.testPart !== from.testPart)
3394
+ break;
3395
+ if (this.isOpenTarget(q))
3396
+ return i;
3397
+ }
3398
+ const mode = from.testPart.navigationMode ?? this.assessment.navigationMode ?? 'nonlinear';
3399
+ if (mode === 'nonlinear') {
3400
+ for (let i = fromIndex - 1; i >= 0; i--) {
3401
+ const q = this.items[i];
3402
+ if (q.testPart !== from.testPart)
3403
+ break;
3404
+ if (this.isOpenTarget(q))
3405
+ return i;
3406
+ }
3407
+ }
3408
+ for (const i of this.eligibleIndexesAfter(fromIndex, decls)) {
3409
+ const q = this.items[i];
3410
+ if (q.testPart !== from.testPart && !this.isItemLocked(q))
3411
+ return i;
3412
+ }
3413
+ return -1;
3414
+ }
1113
3415
  /**
1114
3416
  * A test part, section or item without late submission ran out of time: its items close for the
1115
- * candidate, and delivery moves to the next item outside it.
3417
+ * candidate, and delivery moves to the next open item — forward in the part, else an open
3418
+ * question earlier in a nonlinear part, else the next part. Only when nothing open
3419
+ * remains anywhere reachable is it the expiry dead end.
3420
+ *
3421
+ * The end of the test never navigates: while one runs, the expiry only closes the scope
3422
+ * (the collection takes its items as they stand, `time-expired`). Leaving it — the move
3423
+ * and its report — waits for that end, and is moot once the end finalized.
1116
3424
  */
1117
3425
  handleScopeExpired(scope, identifier) {
1118
- this.lockedScopes.add(`${scope}:${identifier}`);
3426
+ this.scopeLocks.lock(scope, identifier);
3427
+ if (this.endReason !== null) {
3428
+ this.expiriesDuringEnd.push({ scope, identifier });
3429
+ return;
3430
+ }
3431
+ this.leaveExpiredScope(scope, identifier);
3432
+ }
3433
+ /**
3434
+ * Close an expired scope for the candidate: move delivery off it, or report the dead
3435
+ * end. Called from the timer's expiry (`handleScopeExpired`), so the hop is a
3436
+ * state-changing transition like any other: it queues behind the navigation or
3437
+ * submission transition in flight and takes the transition lock once that settles,
3438
+ * instead of racing the in-flight backend request.
3439
+ */
3440
+ leaveExpiredScope(scope, identifier) {
3441
+ this.queuedExpiryHops += 1;
3442
+ this.runWhenIdle(async () => {
3443
+ this.queuedExpiryHops -= 1;
3444
+ // An end of the test finalized while the hop waited: the move is moot.
3445
+ if (this.finalized)
3446
+ return;
3447
+ await this.leaveExpiredScopeLocked(scope, identifier);
3448
+ }).catch((error) => {
3449
+ // Silent only when the player was destroyed while the hop waited behind a
3450
+ // transition: nothing left to close. Any other rejection (a host listener
3451
+ // slipping through, a destroyed-queue cancellation race) is a real expiry
3452
+ // failure — report it like the automatic finalization does, instead of
3453
+ // swallowing it with the scope left locked.
3454
+ if (this.destroyed)
3455
+ return;
3456
+ this.config.onError?.(error instanceof Error ? error : new Error(String(error)));
3457
+ });
3458
+ }
3459
+ /** The hop itself, run under the transition lock (or inline while the end holds it). */
3460
+ async leaveExpiredScopeLocked(scope, identifier) {
1119
3461
  const current = this.items[this.currentItemIndex];
1120
- if (!current || !this.isItemLocked(current))
3462
+ if (!current || !this.isItemLocked(current)) {
3463
+ // Delivery is already outside the expired scope; the shell still learns it closed.
3464
+ this.notifyScopeTimeExpired(scope, identifier, true);
1121
3465
  return;
3466
+ }
1122
3467
  this.saveCurrentItemSession();
1123
3468
  this.notifyItemChange();
1124
- const nextIndex = this.nextUnlockedIndex(this.currentItemIndex);
3469
+ const nextIndex = this.openItemAfterClosure(this.currentItemIndex);
1125
3470
  if (nextIndex < 0) {
1126
- this.notifyTimeExpired();
3471
+ // Nothing unlocked remains: the candidate must submit now (a later expiry of
3472
+ // another already-covered scope reports through its own scope event).
3473
+ this.notifyTimeExpired({
3474
+ scope,
3475
+ identifier,
3476
+ autoFinalized: false,
3477
+ submissionRequired: true,
3478
+ });
3479
+ this.notifyScopeTimeExpired(scope, identifier, false);
3480
+ return;
3481
+ }
3482
+ this.notifyScopeTimeExpired(scope, identifier, true, nextIndex);
3483
+ this.pendingEntryIndex = nextIndex;
3484
+ try {
3485
+ await this.performNavigateTo(nextIndex, { restoring: true });
3486
+ }
3487
+ catch (error) {
3488
+ // The expiry's hop failed: the shell's typed failure screen (localized, with
3489
+ // Retry) replaces the "moving on" flow instead of a silently stuck delivery.
3490
+ this.recordEntryFailure(error);
3491
+ }
3492
+ }
3493
+ /**
3494
+ * The whole-test hard limit expired without late submission (TimeManager calls this
3495
+ * only for that case): finalize like a submit so pending responses are collected and
3496
+ * outcomes computed, then report the expiry. If finalization fails, the session stays
3497
+ * open and the shell offers the Submit action.
3498
+ */
3499
+ handleAssessmentTimeExpired() {
3500
+ this.assessmentExpired = true;
3501
+ if (this.finalized) {
3502
+ this.notifyTimeExpired({ scope: 'assessment', autoFinalized: false, submissionRequired: false });
1127
3503
  return;
1128
3504
  }
1129
- this.navigateTo(nextIndex, { restoring: true }).catch(() => { });
3505
+ void this.autoFinalizeForTimeExpiry();
3506
+ }
3507
+ autoFinalizeForTimeExpiry() {
3508
+ if (this.destroyed || this.finalized)
3509
+ return;
3510
+ // Queued behind a candidate transition in flight, however many administrative
3511
+ // transitions (queued expiry hops, a force submit, a host acting on idle) take the
3512
+ // lock before it: `runWhenIdle` takes the lock the moment it settles, so the end is
3513
+ // never starved and no candidate action slips in first.
3514
+ void this.runWhenIdle(async () => {
3515
+ // The transition in flight ended the test itself: nothing left to finalize, and
3516
+ // (as before) no expiry notice on top of its own ending.
3517
+ if (this.finalized)
3518
+ return false;
3519
+ await this.endTestInternal({ reason: 'expiry' });
3520
+ return true;
3521
+ })
3522
+ .then((ended) => {
3523
+ if (!ended || this.destroyed || !this.finalized)
3524
+ return;
3525
+ this.notifyTimeExpired({ scope: 'assessment', autoFinalized: true, submissionRequired: false });
3526
+ })
3527
+ .catch((error) => {
3528
+ if (this.destroyed)
3529
+ return;
3530
+ // Finalization failed: the shell's expiry notice with a Submit action and the
3531
+ // host's error surface keep the candidate unstuck and the host informed.
3532
+ this.config.onError?.(error instanceof Error ? error : new Error(String(error)));
3533
+ this.notifyTimeExpired({ scope: 'assessment', autoFinalized: false, submissionRequired: true });
3534
+ });
1130
3535
  }
1131
- notifyTimeExpired() {
1132
- for (const l of this.timeExpiredListeners)
1133
- l();
3536
+ notifyTimeExpired(event) {
3537
+ this.events.emit('timeExpired', event);
3538
+ this.config.onTimeExpired?.(event);
3539
+ }
3540
+ notifyScopeTimeExpired(scope, identifier, deliveryContinues, nextIndex) {
3541
+ const event = {
3542
+ scope,
3543
+ identifier,
3544
+ deliveryContinues,
3545
+ ...(nextIndex === undefined ? {} : { nextIndex }),
3546
+ };
3547
+ this.events.emit('scopeTimeExpired', event);
3548
+ this.config.onScopeTimeExpired?.(event);
1134
3549
  }
1135
3550
  notifyTimeTick(remainingSeconds, elapsedSeconds) {
1136
- for (const l of this.timeTickListeners)
1137
- l(remainingSeconds, elapsedSeconds);
3551
+ this.events.emit('timeTick', remainingSeconds, elapsedSeconds);
1138
3552
  }
1139
3553
  /**
1140
3554
  * Get the i18n provider instance
@@ -1151,39 +3565,4 @@ export class AssessmentPlayer {
1151
3565
  return new DefaultI18nProvider('en-US');
1152
3566
  }
1153
3567
  }
1154
- function cloneData(value) {
1155
- return value === undefined ? undefined : structuredClone(value);
1156
- }
1157
- function cloneResponseRecord(responses) {
1158
- return structuredClone(responses);
1159
- }
1160
- function valuesFromItemSession(state) {
1161
- return Object.fromEntries(Object.entries(state.responseVariables).map(([identifier, variable]) => [
1162
- identifier,
1163
- cloneData(variable.value),
1164
- ]));
1165
- }
1166
- function responseValuesEqual(left, right) {
1167
- if (Object.is(left, right))
1168
- return true;
1169
- if (Array.isArray(left) || Array.isArray(right)) {
1170
- if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length)
1171
- return false;
1172
- return left.every((value, index) => responseValuesEqual(value, right[index]));
1173
- }
1174
- if (!isRecord(left) || !isRecord(right))
1175
- return false;
1176
- const leftKeys = Object.keys(left);
1177
- const rightKeys = Object.keys(right);
1178
- if (leftKeys.length !== rightKeys.length)
1179
- return false;
1180
- const rightKeySet = new Set(rightKeys);
1181
- return leftKeys.every((key) => rightKeySet.has(key) && responseValuesEqual(left[key], right[key]));
1182
- }
1183
- function isRecord(value) {
1184
- return value !== null && typeof value === 'object';
1185
- }
1186
- function isWritableItemLifecycle(lifecycleStatus) {
1187
- return lifecycleStatus === 'initial' || lifecycleStatus === 'interacting';
1188
- }
1189
3568
  //# sourceMappingURL=AssessmentPlayer.js.map