@pie-qti/assessment-player 0.1.18 → 0.1.20

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.
@@ -7,7 +7,8 @@
7
7
  * - Submit responses to BackendAdapter
8
8
  * - Apply backend navigation decisions + session state
9
9
  */
10
- import type { PciConfiguration, QTIRole, PnpProfile, SerializedItemSessionState } from '@pie-qti/item-player';
10
+ import { type AssessmentItemDefinitionPlugin, type ItemSession, type PciConfiguration, type PnpProfile, type PlayerSecurityConfig, type QTIRole, type SerializedItemSessionState } from '@pie-qti/item-player';
11
+ import type { I18nProvider } from '@pie-qti/i18n';
11
12
  import type { QtiSectionRuntimeHostContract, QtiSectionToolConfig } from '@pie-qti/section-player';
12
13
  import type { AssessmentRubricBlock, AssessmentSessionState, BackendAdapter, InitSessionRequest, SecureItemRef } from '../integration/api-contract.js';
13
14
  import type { AssessmentResults, ItemResult, NavigationState, TimeLimits } from '../types/index.js';
@@ -17,21 +18,18 @@ export interface BackendAssessmentPlayerConfig {
17
18
  role?: QTIRole;
18
19
  /** Optional RNG for deterministic shuffling in selection/ordering. Defaults to Math.random. */
19
20
  rng?: () => number;
20
- /**
21
- * Optional hint for item renderers that support multiple extended text editors.
22
- * (Plumbed through the shell; the item player remains authoritative for behavior.)
23
- */
24
- extendedTextEditor?: string;
21
+ /** Definition-lifetime extractor and renderer extensions applied to every item. */
22
+ plugins?: readonly AssessmentItemDefinitionPlugin[];
25
23
  /**
26
24
  * Optional i18n provider for internationalization.
27
25
  * If provided, this will be shared across all item players in the assessment.
28
26
  */
29
- i18nProvider?: any;
27
+ i18nProvider?: I18nProvider;
30
28
  /**
31
29
  * Security configuration for URL policy and content restrictions.
32
30
  * If provided, this will be passed to all item players in the assessment.
33
31
  */
34
- security?: any;
32
+ security?: PlayerSecurityConfig;
35
33
  /**
36
34
  * Explicit host trust configuration for Portable Custom Interaction modules.
37
35
  * Without this resolver, authored PCI code remains disabled.
@@ -100,7 +98,9 @@ export declare class AssessmentPlayer {
100
98
  private timeManager;
101
99
  private items;
102
100
  private currentItemIndex;
103
- private currentItemPlayer;
101
+ private readonly itemDefinitions;
102
+ private currentItemSession;
103
+ private currentItemSessionUnsubscribe;
104
104
  private visibleFeedback;
105
105
  private itemChangeListeners;
106
106
  private sectionChangeListeners;
@@ -132,6 +132,14 @@ export declare class AssessmentPlayer {
132
132
  }>;
133
133
  getNavigationState(): NavigationState;
134
134
  getCurrentItem(): CurrentItemView | null;
135
+ /**
136
+ * The one authoritative live session for the active item.
137
+ *
138
+ * Section and item renderers receive this exact instance. Serialized item-session
139
+ * state is reserved for persistence and restore, never for synchronizing a second
140
+ * live player.
141
+ */
142
+ getCurrentItemSession(): ItemSession | null;
135
143
  getCurrentSectionItemRefs(): SectionItemRefView[];
136
144
  getResponsesForItem(itemIdentifier: string): Record<string, unknown>;
137
145
  getCurrentSharedRubricBlocks(): AssessmentRubricBlock[];
@@ -156,6 +164,10 @@ export declare class AssessmentPlayer {
156
164
  getResponses(): Record<string, unknown>;
157
165
  saveCurrentItemSession(): SerializedItemSessionState | null;
158
166
  private endItemSessionForSubmit;
167
+ private getItemDefinition;
168
+ private mirrorSessionResponses;
169
+ private attachCurrentItemSession;
170
+ private releaseCurrentItemSession;
159
171
  /**
160
172
  * Get the current session state snapshot (client-side view).
161
173
  * Note: backend remains authoritative; this is intended for simple save/resume.
@@ -212,7 +224,7 @@ export declare class AssessmentPlayer {
212
224
  * Get the i18n provider instance
213
225
  * @returns I18nProvider instance
214
226
  */
215
- getI18nProvider(): any;
227
+ getI18nProvider(): I18nProvider;
216
228
  /**
217
229
  * Create a simple fallback i18n provider when none is provided
218
230
  */
@@ -7,7 +7,7 @@
7
7
  * - Submit responses to BackendAdapter
8
8
  * - Apply backend navigation decisions + session state
9
9
  */
10
- import { Player } from '@pie-qti/item-player';
10
+ import { createAssessmentItemDefinition, } from '@pie-qti/item-player';
11
11
  import { AssessmentSessionCoordinator } from './AssessmentSessionCoordinator.js';
12
12
  import { NavigationManager } from './NavigationManager.js';
13
13
  import { TimeManager } from './TimeManager.js';
@@ -21,7 +21,9 @@ export class AssessmentPlayer {
21
21
  this.timeManager = null;
22
22
  this.items = [];
23
23
  this.currentItemIndex = -1;
24
- this.currentItemPlayer = null;
24
+ this.itemDefinitions = new Map();
25
+ this.currentItemSession = null;
26
+ this.currentItemSessionUnsubscribe = null;
25
27
  this.visibleFeedback = [];
26
28
  // Event listeners
27
29
  this.itemChangeListeners = new Set();
@@ -308,6 +310,16 @@ export class AssessmentPlayer {
308
310
  deliveryContext: q.item.deliveryContext,
309
311
  };
310
312
  }
313
+ /**
314
+ * The one authoritative live session for the active item.
315
+ *
316
+ * Section and item renderers receive this exact instance. Serialized item-session
317
+ * state is reserved for persistence and restore, never for synchronizing a second
318
+ * live player.
319
+ */
320
+ getCurrentItemSession() {
321
+ return this.currentItemSession;
322
+ }
311
323
  getCurrentSectionItemRefs() {
312
324
  const current = this.items[this.currentItemIndex];
313
325
  if (!current)
@@ -347,7 +359,18 @@ export class AssessmentPlayer {
347
359
  return this.visibleFeedback.map((item) => ({ ...item }));
348
360
  }
349
361
  updateResponse(responseId, value) {
350
- this.sessionCoordinator.updateActiveResponse(responseId, value);
362
+ const active = this.items[this.currentItemIndex];
363
+ if (!active)
364
+ return;
365
+ if (this.currentItemSession) {
366
+ this.currentItemSession.dispatch({
367
+ action: 'setResponse',
368
+ responseIdentifier: responseId,
369
+ value,
370
+ });
371
+ return;
372
+ }
373
+ this.sessionCoordinator.updateResponseForItem(active.identifier, responseId, value);
351
374
  this.notifyResponseChange();
352
375
  }
353
376
  /**
@@ -357,46 +380,114 @@ export class AssessmentPlayer {
357
380
  * the same responseIdentifier like "RESPONSE" across items).
358
381
  */
359
382
  updateResponseForItem(itemIdentifier, responseId, value) {
360
- const next = this.sessionCoordinator.updateResponseForItem(itemIdentifier, responseId, value);
361
- // If this is the active item, keep the live response state + UI hints in sync.
362
383
  const active = this.items[this.currentItemIndex];
363
- if (active?.identifier === itemIdentifier) {
364
- this.currentItemPlayer?.setResponses(next);
365
- this.notifyResponseChange();
384
+ if (active?.identifier === itemIdentifier && this.currentItemSession) {
385
+ const liveValue = this.currentItemSession.state().responses[responseId];
386
+ if (!responseValuesEqual(liveValue, value)) {
387
+ // Programmatic/host callers still enter through this API. Browser item
388
+ // adapters have already dispatched, so their equal value is not applied twice.
389
+ this.currentItemSession.dispatch({
390
+ action: 'setResponse',
391
+ responseIdentifier: responseId,
392
+ value,
393
+ });
394
+ }
395
+ return;
396
+ }
397
+ const persisted = this.sessionCoordinator.getPersistedItemSession(itemIdentifier);
398
+ if (persisted && !isWritableItemLifecycle(persisted.lifecycleStatus)) {
399
+ throw new Error(`Cannot update responses while item session is ${persisted.lifecycleStatus}`);
366
400
  }
401
+ this.sessionCoordinator.updateResponseForItem(itemIdentifier, responseId, value);
402
+ this.notifyResponseChange();
367
403
  }
368
404
  /**
369
405
  * Get current unsaved responses for the active item.
370
406
  * (Useful for host integrations / web components.)
371
407
  */
372
408
  getResponses() {
409
+ if (this.currentItemSession) {
410
+ return cloneData(this.currentItemSession.state().responses) ?? {};
411
+ }
373
412
  return this.sessionCoordinator.getActiveResponses();
374
413
  }
375
414
  saveCurrentItemSession() {
376
415
  const q = this.items[this.currentItemIndex];
377
- if (!q || !this.currentItemPlayer)
416
+ if (!q || !this.currentItemSession)
378
417
  return null;
379
- const responses = this.sessionCoordinator.getActiveResponses();
380
- this.currentItemPlayer.setResponses(responses);
381
- const result = this.currentItemPlayer.suspendAttempt();
382
- this.sessionCoordinator.saveItemSession(q.identifier, responses, result.sessionState, result.duration);
383
- return result.sessionState;
418
+ const currentView = this.currentItemSession.state();
419
+ const transition = isWritableItemLifecycle(currentView.lifecycleStatus)
420
+ ? this.currentItemSession.dispatch({ action: 'suspendAttempt' })
421
+ : null;
422
+ const itemSession = transition?.result?.sessionState ?? this.currentItemSession.serialize();
423
+ const responses = cloneData(transition?.current.responses ?? currentView.responses) ?? {};
424
+ this.sessionCoordinator.saveItemSession(q.identifier, responses, itemSession, transition?.current.duration ?? currentView.duration);
425
+ return itemSession;
384
426
  }
385
427
  endItemSessionForSubmit(q, responses, itemSession) {
386
- const player = new Player({
428
+ const active = this.items[this.currentItemIndex];
429
+ if (active === q &&
430
+ this.currentItemSession &&
431
+ this.currentItemSession.state().lifecycleStatus !== 'suspended') {
432
+ const transition = this.currentItemSession.dispatch({ action: 'endAttempt' });
433
+ return transition.result?.sessionState ?? this.currentItemSession.serialize();
434
+ }
435
+ const session = this.getItemDefinition(q).openSession({
436
+ restore: itemSession,
437
+ responses: itemSession ? undefined : responses,
438
+ activate: true,
439
+ });
440
+ try {
441
+ const transition = session.dispatch({ action: 'endAttempt' });
442
+ return transition.result?.sessionState ?? session.serialize();
443
+ }
444
+ finally {
445
+ session.dispose();
446
+ }
447
+ }
448
+ getItemDefinition(q) {
449
+ const cached = this.itemDefinitions.get(q.identifier);
450
+ if (cached)
451
+ return cached;
452
+ const definition = createAssessmentItemDefinition({
387
453
  itemXml: q.item.itemXml,
388
- role: q.item.role,
454
+ // The assessment host chooses the authorized delivery role. Item refs are
455
+ // content records and must not silently widen or narrow session capabilities.
456
+ role: this.config.role ?? 'candidate',
389
457
  i18nProvider: this.i18nProvider,
390
458
  pnp: this.config.pnp,
391
459
  security: this.config.security,
392
460
  pci: this.config.pci,
461
+ plugins: this.config.plugins,
393
462
  deliveryContext: q.item.deliveryContext,
394
463
  });
395
- if (itemSession) {
396
- player.restoreItemSession(itemSession);
397
- }
398
- player.setResponses(responses);
399
- return player.endAttempt().sessionState;
464
+ this.itemDefinitions.set(q.identifier, definition);
465
+ return definition;
466
+ }
467
+ mirrorSessionResponses(itemIdentifier, responses) {
468
+ const current = this.sessionCoordinator.getResponses(itemIdentifier);
469
+ if (responseValuesEqual(current, responses))
470
+ return false;
471
+ const snapshot = cloneResponseRecord(responses);
472
+ this.state.itemResponses[itemIdentifier] = snapshot;
473
+ this.sessionCoordinator.markAnswered(itemIdentifier, snapshot);
474
+ return true;
475
+ }
476
+ attachCurrentItemSession(q, session) {
477
+ this.currentItemSession = session;
478
+ this.currentItemSessionUnsubscribe = session.subscribe((transition) => {
479
+ if (this.currentItemSession !== session)
480
+ return;
481
+ if (this.mirrorSessionResponses(q.identifier, transition.current.responses)) {
482
+ this.notifyResponseChange();
483
+ }
484
+ });
485
+ }
486
+ releaseCurrentItemSession() {
487
+ this.currentItemSessionUnsubscribe?.();
488
+ this.currentItemSessionUnsubscribe = null;
489
+ this.currentItemSession?.dispose();
490
+ this.currentItemSession = null;
400
491
  }
401
492
  /**
402
493
  * Get the current session state snapshot (client-side view).
@@ -472,7 +563,13 @@ export class AssessmentPlayer {
472
563
  if (!options.restoring && currentItem && target) {
473
564
  this.assertTransitionMinimum(currentItem, target);
474
565
  }
475
- const currentSessionStatus = currentItem ? this.state.itemSessions?.[currentItem.identifier]?.lifecycleStatus : undefined;
566
+ if (!options.restoring && this.currentItemIndex === index && this.currentItemSession) {
567
+ return;
568
+ }
569
+ const currentSessionStatus = currentItem
570
+ ? this.currentItemSession?.state().lifecycleStatus ??
571
+ this.state.itemSessions?.[currentItem.identifier]?.lifecycleStatus
572
+ : undefined;
476
573
  if (!options.restoring &&
477
574
  this.currentItemIndex >= 0 &&
478
575
  this.currentItemIndex !== index &&
@@ -495,26 +592,17 @@ export class AssessmentPlayer {
495
592
  if (effectiveControl) {
496
593
  this.sessionCoordinator.updateItemSessionControl(effectiveControl);
497
594
  }
498
- // Restore responses
595
+ // Restore responses into one live session owned by the assessment. The section
596
+ // composition and item renderer receive this exact object.
499
597
  const responses = this.sessionCoordinator.activateItem(q.identifier);
500
- // Create item player
501
- this.currentItemPlayer?.destroy();
502
- this.currentItemPlayer = new Player({
503
- itemXml: q.item.itemXml,
504
- role: q.item.role,
505
- i18nProvider: this.i18nProvider,
506
- pnp: this.config.pnp,
507
- security: this.config.security,
508
- pci: this.config.pci,
509
- deliveryContext: q.item.deliveryContext,
510
- });
511
598
  const restoredItemSession = this.state.itemSessions?.[q.identifier];
512
- if (restoredItemSession) {
513
- this.currentItemPlayer.restoreItemSession(restoredItemSession);
514
- }
515
- else {
516
- this.currentItemPlayer.setResponses(responses);
517
- }
599
+ this.releaseCurrentItemSession();
600
+ const session = this.getItemDefinition(q).openSession({
601
+ restore: restoredItemSession,
602
+ responses: restoredItemSession ? undefined : responses,
603
+ activate: true,
604
+ });
605
+ this.attachCurrentItemSession(q, session);
518
606
  this.notifyItemChange();
519
607
  this.notifySectionChange();
520
608
  }
@@ -560,32 +648,60 @@ export class AssessmentPlayer {
560
648
  this.assertMinimumTime('item', q);
561
649
  const submittedAt = Date.now();
562
650
  let itemSession;
563
- const responses = this.sessionCoordinator.getActiveResponses();
564
- if (this.currentItemPlayer) {
565
- this.currentItemPlayer.setResponses(responses);
566
- const attempt = this.currentItemPlayer.endAttempt({
567
- validateResponses: this.sessionCoordinator.mustValidateResponses(),
651
+ const submittedSession = this.currentItemSession;
652
+ const preSubmitSession = submittedSession?.serialize();
653
+ const responses = this.currentItemSession
654
+ ? cloneResponseRecord(this.currentItemSession.state().responses)
655
+ : this.sessionCoordinator.getActiveResponses();
656
+ let res;
657
+ try {
658
+ if (submittedSession) {
659
+ const transition = submittedSession.dispatch({
660
+ action: 'endAttempt',
661
+ validateResponses: this.sessionCoordinator.mustValidateResponses(),
662
+ });
663
+ const attempt = transition.result;
664
+ if (!attempt)
665
+ throw new Error('Item session did not produce an end-attempt result');
666
+ if (attempt.validation && !attempt.validation.valid) {
667
+ throw new Error(attempt.validation.issues[0]?.message || 'Submit failed: invalid response');
668
+ }
669
+ itemSession = attempt.sessionState;
670
+ }
671
+ res = await this.backend.submitResponses({
672
+ sessionId: this.sessionId,
673
+ itemIdentifier: q.identifier,
674
+ responses: responses,
675
+ submittedAt,
676
+ timeSpent: itemSession?.duration,
677
+ timing: this.getSubmitTimingEvidence(q, itemSession?.duration ?? 0),
678
+ itemSession: this.config.sendItemSessionToBackend ? itemSession : undefined,
568
679
  });
569
- if (attempt.validation && !attempt.validation.valid) {
570
- throw new Error(attempt.validation.issues[0]?.message || 'Submit failed: invalid response');
680
+ if (!res.success || !res.result) {
681
+ throw new Error(res.error || 'Submit failed');
571
682
  }
572
- itemSession = attempt.sessionState;
573
- this.sessionCoordinator.setItemSession(q.identifier, itemSession);
574
683
  }
575
- const res = await this.backend.submitResponses({
576
- sessionId: this.sessionId,
577
- itemIdentifier: q.identifier,
578
- responses: responses,
579
- submittedAt,
580
- timeSpent: itemSession?.duration,
581
- timing: this.getSubmitTimingEvidence(q, itemSession?.duration ?? 0),
582
- itemSession: this.config.sendItemSessionToBackend ? itemSession : undefined,
583
- });
584
- if (!res.success || !res.result) {
585
- throw new Error(res.error || 'Submit failed');
684
+ catch (error) {
685
+ // Ending an attempt is a local provisional commit until the backend accepts
686
+ // it. Restore the exact pre-submit lifecycle so a transient failure can be
687
+ // retried without a closed item or a double-counted attempt.
688
+ if (submittedSession &&
689
+ preSubmitSession &&
690
+ this.currentItemSession === submittedSession &&
691
+ this.items[this.currentItemIndex] === q) {
692
+ this.releaseCurrentItemSession();
693
+ this.attachCurrentItemSession(q, this.getItemDefinition(q).openSession({ restore: preSubmitSession }));
694
+ this.notifyItemChange();
695
+ }
696
+ throw error;
697
+ }
698
+ if (itemSession) {
699
+ this.sessionCoordinator.setItemSession(q.identifier, itemSession);
586
700
  }
587
701
  if (res.updatedState) {
588
- this.sessionCoordinator.replaceStatePreservingItemSessions(res.updatedState);
702
+ const localResponses = cloneData(this.state.itemResponses || {});
703
+ localResponses[q.identifier] = cloneResponseRecord(responses);
704
+ this.sessionCoordinator.replaceStatePreservingResponsesAndSessions(res.updatedState, localResponses, cloneData(this.state.itemSessions || {}));
589
705
  }
590
706
  else {
591
707
  // Minimal state update when backend doesn't return full state.
@@ -698,50 +814,89 @@ export class AssessmentPlayer {
698
814
  // For simultaneous submission, ensure all items are submitted before finalize so
699
815
  // the backend can compute a complete test score.
700
816
  if (this.assessment.submissionMode === 'simultaneous') {
701
- this.saveCurrentItemSession();
702
- // Preserve client-collected responses across backend state updates.
703
- // Some backend adapters return an updatedState snapshot that may only include
704
- // responses for items that have been submitted so far, which would otherwise
705
- // wipe out responses for later items during this loop.
706
- const allItemResponses = { ...(this.state.itemResponses || {}) };
707
- const allItemSessions = { ...(this.state.itemSessions || {}) };
708
- for (const q of this.items) {
709
- if (this.sessionCoordinator.hasItemResult(q.identifier))
710
- continue;
711
- const submittedAt = Date.now();
712
- const responsesForItem = (allItemResponses?.[q.identifier] || {});
713
- const itemSession = this.endItemSessionForSubmit(q, responsesForItem, allItemSessions[q.identifier]);
714
- allItemSessions[q.identifier] = itemSession;
715
- const res = await this.backend.submitResponses({
716
- sessionId: this.sessionId,
717
- itemIdentifier: q.identifier,
718
- responses: responsesForItem,
719
- submittedAt,
720
- timeSpent: itemSession?.duration,
721
- timing: this.getSubmitTimingEvidence(q, itemSession?.duration ?? 0),
722
- itemSession: this.config.sendItemSessionToBackend ? itemSession : undefined,
723
- });
724
- if (!res.success || !res.result) {
725
- throw new Error(res.error || `Submit failed for item ${q.identifier}`);
817
+ const submittedItem = current;
818
+ const preSubmitSession = this.currentItemSession?.serialize();
819
+ let allItemSessions = {};
820
+ try {
821
+ // Suspending the rendered session gives the UI one non-writable state while
822
+ // backend submission is in flight. Detached sessions perform the provisional
823
+ // end-attempt work for every item.
824
+ this.saveCurrentItemSession();
825
+ // Preserve client-collected responses across backend state updates.
826
+ // Some backend adapters return an updatedState snapshot that may only include
827
+ // responses for items that have been submitted so far, which would otherwise
828
+ // wipe out responses for later items during this loop.
829
+ const allItemResponses = cloneData(this.state.itemResponses || {});
830
+ allItemSessions = cloneData(this.state.itemSessions || {});
831
+ for (const q of this.items) {
832
+ if (this.sessionCoordinator.hasItemResult(q.identifier))
833
+ continue;
834
+ const submittedAt = Date.now();
835
+ const responsesForItem = (allItemResponses?.[q.identifier] || {});
836
+ const itemSession = this.endItemSessionForSubmit(q, responsesForItem, allItemSessions[q.identifier]);
837
+ allItemSessions[q.identifier] = itemSession;
838
+ const res = await this.backend.submitResponses({
839
+ sessionId: this.sessionId,
840
+ itemIdentifier: q.identifier,
841
+ responses: responsesForItem,
842
+ submittedAt,
843
+ timeSpent: itemSession.duration,
844
+ timing: this.getSubmitTimingEvidence(q, itemSession.duration),
845
+ itemSession: this.config.sendItemSessionToBackend ? itemSession : undefined,
846
+ });
847
+ if (!res.success || !res.result) {
848
+ throw new Error(res.error || `Submit failed for item ${q.identifier}`);
849
+ }
850
+ if (res.updatedState) {
851
+ this.sessionCoordinator.replaceStatePreservingResponsesAndSessions(res.updatedState, allItemResponses, allItemSessions);
852
+ }
853
+ else {
854
+ this.state.itemScores = this.state.itemScores || {};
855
+ this.state.itemScores[q.identifier] = res.result;
856
+ this.sessionCoordinator.markVisited(q.identifier);
857
+ this.state.itemResponses[q.identifier] = responsesForItem;
858
+ this.sessionCoordinator.setItemSession(q.identifier, itemSession);
859
+ this.sessionCoordinator.recordAttempt(q.identifier);
860
+ }
861
+ this.sessionCoordinator.setItemResult({
862
+ itemIdentifier: q.identifier,
863
+ score: res.result.score,
864
+ maxScore: res.result.maxScore,
865
+ responses: this.state.itemResponses[q.identifier] || {},
866
+ });
726
867
  }
727
- if (res.updatedState) {
728
- this.sessionCoordinator.replaceStatePreservingResponsesAndSessions(res.updatedState, allItemResponses, allItemSessions);
868
+ // The attached item must represent the same accepted lifecycle as persistence.
869
+ // Replace the provisional suspended object with one restored from the accepted
870
+ // closed state; no second live state owner remains.
871
+ if (submittedItem && this.items[this.currentItemIndex] === submittedItem) {
872
+ const accepted = allItemSessions[submittedItem.identifier];
873
+ if (accepted) {
874
+ this.releaseCurrentItemSession();
875
+ this.attachCurrentItemSession(submittedItem, this.getItemDefinition(submittedItem).openSession({ restore: accepted }));
876
+ this.notifyItemChange();
877
+ }
729
878
  }
730
- else {
731
- this.state.itemScores = this.state.itemScores || {};
732
- this.state.itemScores[q.identifier] = res.result;
733
- this.sessionCoordinator.markVisited(q.identifier);
734
- this.state.itemResponses[q.identifier] = responsesForItem;
735
- if (itemSession) {
736
- this.sessionCoordinator.setItemSession(q.identifier, itemSession);
879
+ }
880
+ catch (error) {
881
+ // The backend accepts simultaneous items one request at a time. Keep earlier
882
+ // accepted items committed so retry cannot double-submit them. If the rendered
883
+ // item was not accepted, restore only that item to its exact writable state.
884
+ if (submittedItem && this.items[this.currentItemIndex] === submittedItem) {
885
+ const accepted = this.sessionCoordinator.hasItemResult(submittedItem.identifier)
886
+ ? allItemSessions[submittedItem.identifier]
887
+ : undefined;
888
+ const restored = accepted ?? preSubmitSession;
889
+ if (!accepted && preSubmitSession) {
890
+ this.sessionCoordinator.saveItemSession(submittedItem.identifier, cloneResponseRecord(valuesFromItemSession(preSubmitSession)), preSubmitSession, preSubmitSession.duration);
891
+ }
892
+ this.releaseCurrentItemSession();
893
+ if (restored) {
894
+ this.attachCurrentItemSession(submittedItem, this.getItemDefinition(submittedItem).openSession({ restore: restored }));
895
+ this.notifyItemChange();
896
+ this.notifyResponseChange();
737
897
  }
738
898
  }
739
- this.sessionCoordinator.setItemResult({
740
- itemIdentifier: q.identifier,
741
- score: res.result.score,
742
- maxScore: res.result.maxScore,
743
- responses: this.state.itemResponses[q.identifier] || {},
744
- });
899
+ throw error;
745
900
  }
746
901
  }
747
902
  else {
@@ -848,7 +1003,8 @@ export class AssessmentPlayer {
848
1003
  }
849
1004
  destroy() {
850
1005
  this.timeManager?.destroy();
851
- this.currentItemPlayer?.destroy();
1006
+ this.releaseCurrentItemSession();
1007
+ this.itemDefinitions.clear();
852
1008
  this.itemChangeListeners.clear();
853
1009
  this.sectionChangeListeners.clear();
854
1010
  this.responseChangeListeners.clear();
@@ -856,7 +1012,6 @@ export class AssessmentPlayer {
856
1012
  this.timeWarningListeners.clear();
857
1013
  this.timeExpiredListeners.clear();
858
1014
  this.timeTickListeners.clear();
859
- this.currentItemPlayer = null;
860
1015
  }
861
1016
  // ---------------------------------------------------------------------------
862
1017
  // Internal notify helpers
@@ -948,4 +1103,36 @@ function shuffleSectionComponents(components, rng) {
948
1103
  function cloneData(value) {
949
1104
  return value === undefined ? undefined : structuredClone(value);
950
1105
  }
1106
+ function cloneResponseRecord(responses) {
1107
+ return structuredClone(responses);
1108
+ }
1109
+ function valuesFromItemSession(state) {
1110
+ return Object.fromEntries(Object.entries(state.responseVariables).map(([identifier, variable]) => [
1111
+ identifier,
1112
+ cloneData(variable.value),
1113
+ ]));
1114
+ }
1115
+ function responseValuesEqual(left, right) {
1116
+ if (Object.is(left, right))
1117
+ return true;
1118
+ if (Array.isArray(left) || Array.isArray(right)) {
1119
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length)
1120
+ return false;
1121
+ return left.every((value, index) => responseValuesEqual(value, right[index]));
1122
+ }
1123
+ if (!isRecord(left) || !isRecord(right))
1124
+ return false;
1125
+ const leftKeys = Object.keys(left);
1126
+ const rightKeys = Object.keys(right);
1127
+ if (leftKeys.length !== rightKeys.length)
1128
+ return false;
1129
+ const rightKeySet = new Set(rightKeys);
1130
+ return leftKeys.every((key) => rightKeySet.has(key) && responseValuesEqual(left[key], right[key]));
1131
+ }
1132
+ function isRecord(value) {
1133
+ return value !== null && typeof value === 'object';
1134
+ }
1135
+ function isWritableItemLifecycle(lifecycleStatus) {
1136
+ return lifecycleStatus === 'initial' || lifecycleStatus === 'interacting';
1137
+ }
951
1138
  //# sourceMappingURL=AssessmentPlayer.js.map