@pie-qti/assessment-player 0.1.5 → 0.1.7

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.
@@ -8,7 +8,7 @@
8
8
  * - Apply backend navigation decisions + session state
9
9
  */
10
10
 
11
- import type { QTIRole, PnpProfile } from '@pie-qti/item-player';
11
+ import type { QTIRole, PnpProfile, SerializedItemSessionState } from '@pie-qti/item-player';
12
12
  import { Player } from '@pie-qti/item-player';
13
13
  import type {
14
14
  AssessmentRubricBlock,
@@ -28,8 +28,9 @@ import type {
28
28
  AssessmentResults,
29
29
  ItemResult,
30
30
  NavigationState,
31
+ TimeLimits,
31
32
  } from '../types/index.js';
32
- import { ItemSessionController } from './ItemSessionController.js';
33
+ import { ItemSessionController, type ItemSessionState } from './ItemSessionController.js';
33
34
  import { NavigationManager } from './NavigationManager.js';
34
35
  import { TimeManager } from './TimeManager.js';
35
36
 
@@ -54,6 +55,12 @@ export interface BackendAssessmentPlayerConfig {
54
55
  * If provided, this will be passed to all item players in the assessment.
55
56
  */
56
57
  security?: any; // Will be PlayerSecurityConfig from @pie-qti/item-player
58
+ /**
59
+ * Demo/reference-only escape hatch. When false (default), rich item-session
60
+ * variables stay client-local and are not submitted because template variables
61
+ * can contain answer keys. Production backends should own this state server-side.
62
+ */
63
+ sendItemSessionToBackend?: boolean;
57
64
  // UI options
58
65
  showSections?: boolean;
59
66
  allowSectionNavigation?: boolean;
@@ -88,6 +95,22 @@ type CurrentItemView = {
88
95
  title?: string;
89
96
  required?: boolean;
90
97
  itemXml: string;
98
+ deliveryContext?: SecureItemRef['deliveryContext'];
99
+ };
100
+
101
+ export interface EffectiveItemTimeLimits {
102
+ timeLimits?: TimeLimits;
103
+ source?: 'item' | 'section' | 'testPart' | 'assessment';
104
+ }
105
+
106
+ type ItemSessionCapablePlayer = Player & {
107
+ suspendAttempt(): { sessionState: SerializedItemSessionState; duration: number };
108
+ endAttempt(options?: { countAttempt?: boolean; validateResponses?: boolean }): {
109
+ sessionState: SerializedItemSessionState;
110
+ duration: number;
111
+ validation?: { valid: boolean; issues: Array<{ message: string }> };
112
+ };
113
+ restoreItemSession(state: SerializedItemSessionState): void;
91
114
  };
92
115
 
93
116
  export class AssessmentPlayer {
@@ -134,6 +157,7 @@ export class AssessmentPlayer {
134
157
  visitedItems: [],
135
158
  itemResponses: {},
136
159
  itemScores: {},
160
+ itemSessions: {},
137
161
  timing: { startedAt: Date.now(), itemTimes: {}, totalTime: 0 },
138
162
  } as AssessmentSessionState);
139
163
 
@@ -151,24 +175,24 @@ export class AssessmentPlayer {
151
175
  for (const q of this.items) {
152
176
  this.sessionController.initializeItem(q.identifier);
153
177
  }
154
-
155
- // Initialize time manager if time limits exist
156
- if (this.assessment.timeLimits?.maxTime) {
157
- this.timeManager = new TimeManager({
158
- assessmentTimeLimits: this.assessment.timeLimits,
159
- warningThreshold: config.timeWarningThreshold || 60,
160
- extendedTime: config.pnp?.content?.extendedTime,
161
- onWarning: (remainingSeconds) => this.notifyTimeWarning(remainingSeconds),
162
- onExpired: () => this.notifyTimeExpired(),
163
- onTick: (remainingSeconds, elapsedSeconds) => this.notifyTimeTick(remainingSeconds, elapsedSeconds),
164
- });
165
- }
178
+ this.restoreItemSessionsFromState(this.state);
179
+
180
+ this.timeManager = new TimeManager({
181
+ assessmentTimeLimits: this.assessment.timeLimits,
182
+ warningThreshold: config.timeWarningThreshold || 60,
183
+ extendedTime: config.pnp?.content?.extendedTime,
184
+ onWarning: (remainingSeconds) => this.notifyTimeWarning(remainingSeconds),
185
+ onExpired: () => this.notifyTimeExpired(),
186
+ onTick: (remainingSeconds, elapsedSeconds) => this.notifyTimeTick(remainingSeconds, elapsedSeconds),
187
+ });
166
188
 
167
189
  // Restore to backend-provided current item if present
168
190
  const startId = this.state.currentItemIdentifier;
169
191
  const idx = startId ? this.items.findIndex((q) => q.identifier === startId) : -1;
170
192
  if (idx >= 0) {
171
- this.navigateTo(idx).catch(() => {});
193
+ this.navigateTo(idx, { restoring: true }).catch(() => {});
194
+ } else if (this.items.length > 0) {
195
+ this.navigateTo(0, { restoring: true }).catch(() => {});
172
196
  }
173
197
  }
174
198
 
@@ -195,6 +219,70 @@ export class AssessmentPlayer {
195
219
  };
196
220
  }
197
221
 
222
+ private getEffectiveItemTimeLimits(flat: FlatItem): EffectiveItemTimeLimits {
223
+ const scopes: Array<{ source: EffectiveItemTimeLimits['source']; limits?: TimeLimits }> = [
224
+ { source: 'assessment', limits: this.assessment.timeLimits },
225
+ { source: 'testPart', limits: flat.testPart.timeLimits },
226
+ { source: 'section', limits: flat.section.timeLimits },
227
+ { source: 'item', limits: flat.item.timeLimits },
228
+ ];
229
+ let source: EffectiveItemTimeLimits['source'];
230
+ let minTime: number | undefined;
231
+ let maxTime: number | undefined;
232
+ let allowLateSubmission: boolean | undefined;
233
+ for (const scope of scopes) {
234
+ if (!scope.limits) continue;
235
+ if (scope.limits.minTime !== undefined) {
236
+ minTime = minTime === undefined ? scope.limits.minTime : Math.max(minTime, scope.limits.minTime);
237
+ }
238
+ if (scope.limits.maxTime !== undefined) {
239
+ const extended = this.config.pnp?.content?.extendedTime;
240
+ const scopedMaxTime = extended?.active
241
+ ? extended.multiplier === Infinity
242
+ ? undefined
243
+ : scope.limits.maxTime * extended.multiplier
244
+ : scope.limits.maxTime;
245
+ if (scopedMaxTime !== undefined && (maxTime === undefined || scopedMaxTime < maxTime)) {
246
+ maxTime = scopedMaxTime;
247
+ source = scope.source;
248
+ allowLateSubmission = scope.limits.allowLateSubmission;
249
+ }
250
+ } else if (scope.limits.allowLateSubmission !== undefined && maxTime === undefined) {
251
+ allowLateSubmission = scope.limits.allowLateSubmission;
252
+ source = scope.source;
253
+ }
254
+ }
255
+
256
+ if (maxTime === undefined && minTime === undefined && allowLateSubmission === undefined) {
257
+ return {};
258
+ }
259
+ return { source, timeLimits: { minTime, maxTime, allowLateSubmission } };
260
+ }
261
+
262
+ public getCurrentEffectiveTimeLimits(): EffectiveItemTimeLimits {
263
+ const q = this.items[this.currentItemIndex];
264
+ return q ? this.getEffectiveItemTimeLimits(q) : {};
265
+ }
266
+
267
+ private getSubmitTimingEvidence(q: FlatItem, elapsedMs: number): import('../integration/api-contract.js').SubmitTimingEvidence | undefined {
268
+ const effective = this.getEffectiveItemTimeLimits(q);
269
+ const limitSeconds = effective.timeLimits?.maxTime;
270
+ if (!effective.source || limitSeconds === undefined) return undefined;
271
+ if (effective.source !== 'item' && effective.source !== 'assessment') {
272
+ return undefined;
273
+ }
274
+ const scopedElapsedMs = effective.source === 'assessment'
275
+ ? (this.timeManager?.getElapsedSeconds() ?? 0) * 1000
276
+ : elapsedMs;
277
+ return {
278
+ scope: effective.source,
279
+ elapsedMs: scopedElapsedMs,
280
+ limitSeconds,
281
+ expired: scopedElapsedMs >= limitSeconds * 1000,
282
+ allowLateSubmission: effective.timeLimits?.allowLateSubmission,
283
+ };
284
+ }
285
+
198
286
  private hasAnyResponse(responses: Record<string, unknown>): boolean {
199
287
  for (const v of Object.values(responses)) {
200
288
  if (v == null) continue;
@@ -212,6 +300,42 @@ export class AssessmentPlayer {
212
300
  return false;
213
301
  }
214
302
 
303
+ private restoreItemSessionsFromState(state: AssessmentSessionState): void {
304
+ const restoredStates = new Map<string, ItemSessionState>();
305
+ for (const item of this.items) {
306
+ const persisted = state.itemSessionStates?.[item.identifier];
307
+ if (persisted) {
308
+ restoredStates.set(item.identifier, {
309
+ itemIdentifier: item.identifier,
310
+ attemptCount: Math.max(0, persisted.attemptCount),
311
+ isAnswered: persisted.isAnswered,
312
+ isSubmitted: persisted.isSubmitted,
313
+ lastSubmissionTime: persisted.lastSubmissionTime,
314
+ });
315
+ continue;
316
+ }
317
+
318
+ const responses = state.itemResponses?.[item.identifier] ?? {};
319
+ const isSubmitted = Boolean(state.itemScores?.[item.identifier]);
320
+ restoredStates.set(item.identifier, {
321
+ itemIdentifier: item.identifier,
322
+ attemptCount: isSubmitted ? 1 : 0,
323
+ isAnswered: this.hasAnyResponse(responses),
324
+ isSubmitted,
325
+ });
326
+ }
327
+ this.sessionController.restoreStates(restoredStates);
328
+ }
329
+
330
+ private getItemSessionStateSnapshot(): Record<string, ItemSessionState> {
331
+ return Object.fromEntries(
332
+ [...this.sessionController.getAllStates().entries()].map(([itemIdentifier, state]) => [
333
+ itemIdentifier,
334
+ { ...state },
335
+ ])
336
+ );
337
+ }
338
+
215
339
  private flattenItems(assessment: SecureAssessment): FlatItem[] {
216
340
  const out: FlatItem[] = [];
217
341
  const testParts = assessment.testParts || [];
@@ -292,6 +416,7 @@ export class AssessmentPlayer {
292
416
  title: q.section.title,
293
417
  required: q.item.required,
294
418
  itemXml: q.item.itemXml,
419
+ deliveryContext: q.item.deliveryContext,
295
420
  };
296
421
  }
297
422
 
@@ -325,12 +450,12 @@ export class AssessmentPlayer {
325
450
  const prev = (this.state.itemResponses?.[itemIdentifier] || {}) as Record<string, unknown>;
326
451
  const next = { ...prev, [responseId]: value };
327
452
  this.state.itemResponses[itemIdentifier] = next as any;
453
+ this.sessionController.markAnswered(itemIdentifier, this.hasAnyResponse(next));
328
454
 
329
455
  // If this is the active item, keep the live response state + UI hints in sync.
330
456
  const active = this.items[this.currentItemIndex];
331
457
  if (active?.identifier === itemIdentifier) {
332
458
  this.responses = next;
333
- this.sessionController.markAnswered(itemIdentifier, this.hasAnyResponse(this.responses));
334
459
  this.currentItemPlayer?.setResponses(this.responses as any);
335
460
  this.notifyResponseChange();
336
461
  }
@@ -344,17 +469,54 @@ export class AssessmentPlayer {
344
469
  return { ...this.responses };
345
470
  }
346
471
 
472
+ public saveCurrentItemSession(): SerializedItemSessionState | null {
473
+ const q = this.items[this.currentItemIndex];
474
+ if (!q || !this.currentItemPlayer) return null;
475
+ this.currentItemPlayer.setResponses(this.responses as any);
476
+ const result = (this.currentItemPlayer as ItemSessionCapablePlayer).suspendAttempt();
477
+ this.state.itemSessions = {
478
+ ...(this.state.itemSessions ?? {}),
479
+ [q.identifier]: result.sessionState,
480
+ };
481
+ this.state.itemResponses[q.identifier] = this.responses as any;
482
+ this.state.timing.itemTimes[q.identifier] = result.duration;
483
+ this.sessionController.markAnswered(q.identifier, this.hasAnyResponse(this.responses));
484
+ return result.sessionState;
485
+ }
486
+
487
+ private endItemSessionForSubmit(
488
+ q: FlatItem,
489
+ responses: Record<string, unknown>,
490
+ itemSession?: SerializedItemSessionState
491
+ ): SerializedItemSessionState {
492
+ const player = new Player({
493
+ itemXml: q.item.itemXml,
494
+ role: q.item.role,
495
+ i18nProvider: this.i18nProvider,
496
+ pnp: this.config.pnp,
497
+ security: this.config.security,
498
+ deliveryContext: q.item.deliveryContext,
499
+ }) as ItemSessionCapablePlayer;
500
+ if (itemSession) {
501
+ player.restoreItemSession(itemSession);
502
+ }
503
+ player.setResponses(responses as any);
504
+ return player.endAttempt().sessionState;
505
+ }
506
+
347
507
  /**
348
508
  * Get the current session state snapshot (client-side view).
349
509
  * Note: backend remains authoritative; this is intended for simple save/resume.
350
510
  */
351
- public getState(): AssessmentSessionState {
511
+ public getState(options: { includeItemSessions?: boolean } = {}): AssessmentSessionState {
352
512
  // Shallow clone to avoid accidental external mutation.
353
513
  return {
354
514
  ...this.state,
355
515
  visitedItems: [...this.state.visitedItems],
356
516
  itemResponses: { ...this.state.itemResponses },
357
517
  itemScores: this.state.itemScores ? { ...this.state.itemScores } : undefined,
518
+ itemSessions: options.includeItemSessions && this.state.itemSessions ? { ...this.state.itemSessions } : undefined,
519
+ itemSessionStates: this.getItemSessionStateSnapshot(),
358
520
  timing: {
359
521
  ...this.state.timing,
360
522
  itemTimes: { ...this.state.timing.itemTimes },
@@ -373,6 +535,7 @@ export class AssessmentPlayer {
373
535
  .map((id) => this.items.findIndex((q) => q.identifier === id))
374
536
  .filter((i) => i >= 0);
375
537
  this.navigationManager.restoreState(visitedIdx);
538
+ this.restoreItemSessionsFromState(state);
376
539
 
377
540
  // Rehydrate itemResults from scores if present, so submit() can behave sensibly.
378
541
  this.itemResults.clear();
@@ -390,30 +553,46 @@ export class AssessmentPlayer {
390
553
  const currentId = state.currentItemIdentifier;
391
554
  const idx = currentId ? this.items.findIndex((q) => q.identifier === currentId) : -1;
392
555
  if (idx >= 0) {
393
- await this.navigateTo(idx);
556
+ await this.navigateTo(idx, { restoring: true });
394
557
  } else if (this.items.length > 0) {
395
- await this.navigateTo(0);
558
+ await this.navigateTo(0, { restoring: true });
396
559
  }
397
560
  }
398
561
 
399
- public async navigateTo(index: number): Promise<void> {
562
+ public async navigateTo(index: number, options: { restoring?: boolean } = {}): Promise<void> {
400
563
  if (index < 0 || index >= this.items.length) throw new Error(`Invalid item index: ${index}`);
401
564
 
402
565
  // Enforce navigation rules (UI hints, still backend-authoritative for real deployments).
403
- if (this.currentItemIndex >= 0 && !this.navigationManager.canNavigateTo(index, this.currentItemIndex)) {
566
+ if (!options.restoring && this.currentItemIndex >= 0 && !this.navigationManager.canNavigateTo(index, this.currentItemIndex)) {
404
567
  if (this.navigationManager.getMode() === 'linear' && index > this.currentItemIndex + 1) {
405
568
  throw new Error('In linear navigation mode, you can only move to the next question.');
406
569
  }
407
570
  throw new Error('Navigation is not allowed.');
408
571
  }
409
572
  const target = this.items[index];
410
- if (target && !this.sessionController.canReview(target.identifier)) {
573
+ if (!options.restoring && target && !this.sessionController.canReview(target.identifier)) {
411
574
  throw new Error('You cannot go back to previous questions in this assessment.');
412
575
  }
413
576
 
577
+ const currentItem = this.items[this.currentItemIndex];
578
+ const currentSessionStatus = currentItem ? this.state.itemSessions?.[currentItem.identifier]?.lifecycleStatus : undefined;
579
+ if (
580
+ !options.restoring &&
581
+ this.currentItemIndex >= 0 &&
582
+ this.currentItemIndex !== index &&
583
+ currentSessionStatus !== 'closed'
584
+ ) {
585
+ this.saveCurrentItemSession();
586
+ }
587
+ if (currentItem && this.currentItemIndex !== index) {
588
+ this.timeManager?.endItem(currentItem.identifier);
589
+ }
590
+
414
591
  this.currentItemIndex = index;
415
592
  const q = this.items[index]!;
416
593
  this.state.currentItemIdentifier = q.identifier;
594
+ this.timeManager?.startSection(q.section.identifier);
595
+ this.timeManager?.startItem(q.identifier);
417
596
 
418
597
  // Apply three-level itemSessionControl fallback for this item's section (S1).
419
598
  const effectiveControl = this.getEffectiveItemSessionControl(q);
@@ -425,12 +604,21 @@ export class AssessmentPlayer {
425
604
  this.responses = { ...(this.state.itemResponses[q.identifier] || {}) };
426
605
 
427
606
  // Create item player
607
+ this.currentItemPlayer?.destroy();
428
608
  this.currentItemPlayer = new Player({
429
609
  itemXml: q.item.itemXml,
430
610
  role: q.item.role,
431
611
  i18nProvider: this.i18nProvider,
612
+ pnp: this.config.pnp,
613
+ security: this.config.security,
614
+ deliveryContext: q.item.deliveryContext,
432
615
  });
433
- this.currentItemPlayer.setResponses(this.responses as any);
616
+ const restoredItemSession = this.state.itemSessions?.[q.identifier];
617
+ if (restoredItemSession) {
618
+ (this.currentItemPlayer as ItemSessionCapablePlayer).restoreItemSession(restoredItemSession);
619
+ } else {
620
+ this.currentItemPlayer.setResponses(this.responses as any);
621
+ }
434
622
 
435
623
  this.notifyItemChange();
436
624
  this.notifySectionChange();
@@ -479,11 +667,29 @@ export class AssessmentPlayer {
479
667
  if (!q) throw new Error('No current item');
480
668
 
481
669
  const submittedAt = Date.now();
670
+ let itemSession: SerializedItemSessionState | undefined;
671
+ if (this.currentItemPlayer) {
672
+ this.currentItemPlayer.setResponses(this.responses as any);
673
+ const attempt = (this.currentItemPlayer as ItemSessionCapablePlayer).endAttempt({
674
+ validateResponses: this.sessionController.mustValidateResponses(),
675
+ });
676
+ if (attempt.validation && !attempt.validation.valid) {
677
+ throw new Error(attempt.validation.issues[0]?.message || 'Submit failed: invalid response');
678
+ }
679
+ itemSession = attempt.sessionState;
680
+ this.state.itemSessions = {
681
+ ...(this.state.itemSessions ?? {}),
682
+ [q.identifier]: itemSession,
683
+ };
684
+ }
482
685
  const res = await this.backend.submitResponses({
483
686
  sessionId: this.sessionId,
484
687
  itemIdentifier: q.identifier,
485
688
  responses: this.responses as any,
486
689
  submittedAt,
690
+ timeSpent: itemSession?.duration,
691
+ timing: this.getSubmitTimingEvidence(q, itemSession?.duration ?? 0),
692
+ itemSession: this.config.sendItemSessionToBackend ? itemSession : undefined,
487
693
  });
488
694
 
489
695
  if (!res.success || !res.result) {
@@ -491,13 +697,20 @@ export class AssessmentPlayer {
491
697
  }
492
698
 
493
699
  if (res.updatedState) {
700
+ const localItemSessions = this.state.itemSessions;
494
701
  this.state = res.updatedState;
702
+ if (localItemSessions) {
703
+ this.state.itemSessions = { ...(this.state.itemSessions ?? {}), ...localItemSessions };
704
+ }
495
705
  } else {
496
706
  // Minimal state update when backend doesn't return full state.
497
707
  this.state.itemScores = this.state.itemScores || {};
498
708
  this.state.itemScores[q.identifier] = res.result;
499
709
  if (!this.state.visitedItems.includes(q.identifier)) this.state.visitedItems.push(q.identifier);
500
710
  this.state.itemResponses[q.identifier] = this.responses as any;
711
+ if (itemSession) {
712
+ this.state.itemSessions = { ...(this.state.itemSessions ?? {}), [q.identifier]: itemSession };
713
+ }
501
714
  }
502
715
 
503
716
  const itemResult: ItemResult = {
@@ -575,21 +788,28 @@ export class AssessmentPlayer {
575
788
  // For simultaneous submission, ensure all items are submitted before finalize so
576
789
  // the backend can compute a complete test score.
577
790
  if (this.assessment.submissionMode === 'simultaneous') {
791
+ this.saveCurrentItemSession();
578
792
  // Preserve client-collected responses across backend state updates.
579
793
  // Some backend adapters return an updatedState snapshot that may only include
580
794
  // responses for items that have been submitted so far, which would otherwise
581
795
  // wipe out responses for later items during this loop.
582
796
  const allItemResponses = { ...(this.state.itemResponses || {}) } as any;
797
+ const allItemSessions = { ...(this.state.itemSessions || {}) };
583
798
 
584
799
  for (const q of this.items) {
585
800
  if (this.itemResults.has(q.identifier)) continue;
586
801
  const submittedAt = Date.now();
587
802
  const responsesForItem = (allItemResponses?.[q.identifier] || {}) as any;
803
+ const itemSession = this.endItemSessionForSubmit(q, responsesForItem, allItemSessions[q.identifier]);
804
+ allItemSessions[q.identifier] = itemSession;
588
805
  const res = await this.backend.submitResponses({
589
806
  sessionId: this.sessionId,
590
807
  itemIdentifier: q.identifier,
591
808
  responses: responsesForItem,
592
809
  submittedAt,
810
+ timeSpent: itemSession?.duration,
811
+ timing: this.getSubmitTimingEvidence(q, itemSession?.duration ?? 0),
812
+ itemSession: this.config.sendItemSessionToBackend ? itemSession : undefined,
593
813
  });
594
814
  if (!res.success || !res.result) {
595
815
  throw new Error(res.error || `Submit failed for item ${q.identifier}`);
@@ -598,11 +818,15 @@ export class AssessmentPlayer {
598
818
  this.state = res.updatedState;
599
819
  // Restore full response map captured on the client.
600
820
  this.state.itemResponses = allItemResponses;
821
+ this.state.itemSessions = allItemSessions;
601
822
  } else {
602
823
  this.state.itemScores = this.state.itemScores || {};
603
824
  this.state.itemScores[q.identifier] = res.result;
604
825
  if (!this.state.visitedItems.includes(q.identifier)) this.state.visitedItems.push(q.identifier);
605
826
  this.state.itemResponses[q.identifier] = responsesForItem;
827
+ if (itemSession) {
828
+ this.state.itemSessions = { ...(this.state.itemSessions ?? {}), [q.identifier]: itemSession };
829
+ }
606
830
  }
607
831
  this.itemResults.set(q.identifier, {
608
832
  itemIdentifier: q.identifier,
@@ -751,6 +975,8 @@ export class AssessmentPlayer {
751
975
  }
752
976
 
753
977
  public destroy(): void {
978
+ this.timeManager?.destroy();
979
+ this.currentItemPlayer?.destroy();
754
980
  this.itemChangeListeners.clear();
755
981
  this.sectionChangeListeners.clear();
756
982
  this.responseChangeListeners.clear();