@pie-qti/assessment-player 0.1.15 → 0.1.16

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,7 @@
7
7
  * - Submit responses to BackendAdapter
8
8
  * - Apply backend navigation decisions + session state
9
9
  */
10
- import type { QTIRole, PnpProfile, SerializedItemSessionState } from '@pie-qti/item-player';
10
+ import type { PciConfiguration, QTIRole, PnpProfile, SerializedItemSessionState } from '@pie-qti/item-player';
11
11
  import type { QtiSectionRuntimeHostContract, QtiSectionToolConfig } from '@pie-qti/section-player';
12
12
  import type { AssessmentRubricBlock, AssessmentSessionState, BackendAdapter, InitSessionRequest, SecureItemRef } from '../integration/api-contract.js';
13
13
  import type { AssessmentResults, ItemResult, NavigationState, TimeLimits } from '../types/index.js';
@@ -32,6 +32,11 @@ export interface BackendAssessmentPlayerConfig {
32
32
  * If provided, this will be passed to all item players in the assessment.
33
33
  */
34
34
  security?: any;
35
+ /**
36
+ * Explicit host trust configuration for Portable Custom Interaction modules.
37
+ * Without this resolver, authored PCI code remains disabled.
38
+ */
39
+ pci?: PciConfiguration;
35
40
  /**
36
41
  * Optional host hooks for delegated section rendering.
37
42
  * Used for section shared-content URL policy and runtime callbacks.
@@ -116,6 +121,8 @@ export declare class AssessmentPlayer {
116
121
  private getEffectiveItemTimeLimits;
117
122
  getCurrentEffectiveTimeLimits(): EffectiveItemTimeLimits;
118
123
  private getSubmitTimingEvidence;
124
+ private assertMinimumTime;
125
+ private assertTransitionMinimum;
119
126
  private flattenItems;
120
127
  getAllSections(): Array<{
121
128
  id: string;
@@ -160,6 +167,7 @@ export declare class AssessmentPlayer {
160
167
  * Restore a previously saved session state.
161
168
  */
162
169
  restoreState(state: AssessmentSessionState): Promise<void>;
170
+ private restoreTimeTracking;
163
171
  navigateTo(index: number, options?: {
164
172
  restoring?: boolean;
165
173
  }): Promise<void>;
@@ -170,6 +178,7 @@ export declare class AssessmentPlayer {
170
178
  submitCurrentItem(): Promise<ItemResult>;
171
179
  private canPrevious;
172
180
  private canNext;
181
+ private canNavigateByTestPart;
173
182
  /** Submit entire assessment (finalize on backend) */
174
183
  submit(): Promise<AssessmentResults>;
175
184
  getItemSessionInfo(_itemIdentifier?: string): {
@@ -63,6 +63,9 @@ export class AssessmentPlayer {
63
63
  onExpired: () => this.notifyTimeExpired(),
64
64
  onTick: (remainingSeconds, elapsedSeconds) => this.notifyTimeTick(remainingSeconds, elapsedSeconds),
65
65
  });
66
+ if (init.restoredState?.timing) {
67
+ this.restoreTimeTracking(init.restoredState.timing);
68
+ }
66
69
  // Restore to backend-provided current item if present
67
70
  const startId = this.state.currentItemIdentifier;
68
71
  const idx = startId ? this.items.findIndex((q) => q.identifier === startId) : -1;
@@ -150,12 +153,15 @@ export class AssessmentPlayer {
150
153
  const limitSeconds = effective.timeLimits?.maxTime;
151
154
  if (!effective.source || limitSeconds === undefined)
152
155
  return undefined;
153
- if (effective.source !== 'item' && effective.source !== 'assessment') {
154
- return undefined;
155
- }
156
- const scopedElapsedMs = effective.source === 'assessment'
157
- ? (this.timeManager?.getElapsedSeconds() ?? 0) * 1000
158
- : elapsedMs;
156
+ const scopeIdentifier = effective.source === 'item'
157
+ ? q.identifier
158
+ : effective.source === 'section'
159
+ ? q.section.identifier
160
+ : effective.source === 'testPart'
161
+ ? q.testPart.identifier
162
+ : undefined;
163
+ const tracked = this.timeManager?.getScopeElapsedMs(effective.source, scopeIdentifier);
164
+ const scopedElapsedMs = tracked ?? elapsedMs;
159
165
  return {
160
166
  scope: effective.source,
161
167
  elapsedMs: scopedElapsedMs,
@@ -164,36 +170,94 @@ export class AssessmentPlayer {
164
170
  allowLateSubmission: effective.timeLimits?.allowLateSubmission,
165
171
  };
166
172
  }
173
+ assertMinimumTime(scope, q) {
174
+ const limits = scope === 'assessment'
175
+ ? this.assessment.timeLimits
176
+ : scope === 'testPart'
177
+ ? q.testPart.timeLimits
178
+ : scope === 'section'
179
+ ? q.section.timeLimits
180
+ : q.item.timeLimits;
181
+ if (limits?.minTime === undefined)
182
+ return;
183
+ const identifier = scope === 'testPart'
184
+ ? q.testPart.identifier
185
+ : scope === 'section'
186
+ ? q.section.identifier
187
+ : scope === 'item'
188
+ ? q.identifier
189
+ : undefined;
190
+ const elapsedMs = this.timeManager?.getScopeElapsedMs(scope, identifier) ?? 0;
191
+ if (elapsedMs < limits.minTime * 1000) {
192
+ const remaining = Math.ceil(limits.minTime - elapsedMs / 1000);
193
+ throw new Error(`The ${scope} minimum time has not elapsed (${remaining}s remaining).`);
194
+ }
195
+ }
196
+ assertTransitionMinimum(current, target) {
197
+ if (current === target)
198
+ return;
199
+ this.assertMinimumTime('item', current);
200
+ if (current.section !== target.section)
201
+ this.assertMinimumTime('section', current);
202
+ if (current.testPart !== target.testPart)
203
+ this.assertMinimumTime('testPart', current);
204
+ }
167
205
  flattenItems(assessment) {
168
206
  const out = [];
169
207
  const testParts = assessment.testParts || [];
170
208
  let idx = 0;
171
209
  let secIdx = 0;
172
210
  const rng = this.config.rng ?? Math.random;
173
- for (const tp of testParts) {
174
- for (const section of tp.sections || []) {
175
- let refs = [...(section.assessmentItemRefs || [])];
176
- // QTI ordering: shuffle items within the section when requested.
177
- // The server may have already shuffled; if not (e.g. reference adapter), do it client-side.
178
- if (section.ordering?.shuffle) {
179
- refs = shuffleArray(refs, rng);
211
+ const visitSection = (section, tp) => {
212
+ const currentSectionIndex = secIdx++;
213
+ let components = section.children
214
+ ? [...section.children]
215
+ : [
216
+ ...(section.assessmentItemRefs ?? []).map((item) => ({ type: 'item', item })),
217
+ ...(section.sections ?? []).map((child) => ({ type: 'section', section: child })),
218
+ ];
219
+ // Selection is applied to direct children only. Required children are always
220
+ // included, and selection preserves source order; ordering is a later step.
221
+ if (section.selection) {
222
+ const count = Math.max(0, section.selection.select);
223
+ const indexed = components.map((component, sourceIndex) => ({ component, sourceIndex }));
224
+ const required = indexed.filter(({ component }) => isRequiredSectionComponent(component));
225
+ if (count < required.length) {
226
+ throw new Error(`Section "${section.identifier}" selects ${count} components but contains ${required.length} required components.`);
180
227
  }
181
- // QTI selection: take only `select` items from the (possibly shuffled) list.
182
- if (section.selection && section.selection.select > 0 && section.selection.select < refs.length) {
183
- refs = refs.slice(0, section.selection.select);
228
+ if (count > indexed.length) {
229
+ const replacement = section.selection.withReplacement === true;
230
+ throw new Error(replacement
231
+ ? `Section "${section.identifier}" requires cloned item instances for withReplacement selection; the backend must materialize those instances before delivery.`
232
+ : `Section "${section.identifier}" selects ${count} components without replacement but only contains ${indexed.length}.`);
184
233
  }
185
- for (const item of refs) {
186
- out.push({
187
- identifier: item.identifier,
188
- item,
189
- section,
190
- testPart: tp,
191
- index: idx++,
192
- sectionIndex: secIdx,
193
- });
234
+ const optional = shuffleArray(indexed.filter(({ component }) => !isRequiredSectionComponent(component)), rng);
235
+ components = [...required, ...optional.slice(0, count - required.length)]
236
+ .sort((a, b) => a.sourceIndex - b.sourceIndex)
237
+ .map(({ component }) => component);
238
+ }
239
+ if (section.ordering?.shuffle) {
240
+ components = shuffleSectionComponents(components, rng);
241
+ }
242
+ for (const component of components) {
243
+ if (component.type === 'section') {
244
+ visitSection(component.section, tp);
245
+ continue;
194
246
  }
195
- secIdx++;
247
+ const item = component.item;
248
+ out.push({
249
+ identifier: item.identifier,
250
+ item,
251
+ section,
252
+ testPart: tp,
253
+ index: idx++,
254
+ sectionIndex: currentSectionIndex,
255
+ });
196
256
  }
257
+ };
258
+ for (const tp of testParts) {
259
+ for (const section of tp.sections || [])
260
+ visitSection(section, tp);
197
261
  }
198
262
  return out;
199
263
  }
@@ -203,10 +267,14 @@ export class AssessmentPlayer {
203
267
  getAllSections() {
204
268
  const out = [];
205
269
  let idx = 0;
270
+ const visit = (section) => {
271
+ out.push({ id: section.identifier, title: section.title, visible: section.visible, index: idx++ });
272
+ for (const child of section.sections ?? [])
273
+ visit(child);
274
+ };
206
275
  for (const tp of this.assessment.testParts || []) {
207
- for (const s of tp.sections || []) {
208
- out.push({ id: s.identifier, title: s.title, visible: s.visible, index: idx++ });
209
- }
276
+ for (const section of tp.sections || [])
277
+ visit(section);
210
278
  }
211
279
  return out;
212
280
  }
@@ -321,6 +389,7 @@ export class AssessmentPlayer {
321
389
  i18nProvider: this.i18nProvider,
322
390
  pnp: this.config.pnp,
323
391
  security: this.config.security,
392
+ pci: this.config.pci,
324
393
  deliveryContext: q.item.deliveryContext,
325
394
  });
326
395
  if (itemSession) {
@@ -334,13 +403,29 @@ export class AssessmentPlayer {
334
403
  * Note: backend remains authoritative; this is intended for simple save/resume.
335
404
  */
336
405
  getState(options = {}) {
337
- return this.sessionCoordinator.snapshot(options);
406
+ const snapshot = this.sessionCoordinator.snapshot(options);
407
+ const timing = this.timeManager?.getState();
408
+ if (timing) {
409
+ snapshot.timing = {
410
+ startedAt: timing.startedAt,
411
+ itemTimes: { ...timing.itemTimes },
412
+ sectionTimes: { ...timing.sectionTimes },
413
+ testPartTimes: { ...timing.testPartTimes },
414
+ totalTime: timing.totalElapsed,
415
+ currentItemIdentifier: timing.currentItemId,
416
+ currentSectionIdentifier: timing.currentSectionId,
417
+ currentTestPartIdentifier: timing.currentTestPartId,
418
+ isPaused: timing.isPaused,
419
+ };
420
+ }
421
+ return snapshot;
338
422
  }
339
423
  /**
340
424
  * Restore a previously saved session state.
341
425
  */
342
426
  async restoreState(state) {
343
427
  this.state = state;
428
+ this.restoreTimeTracking(state.timing);
344
429
  // Restore visited state for UI navigation hints.
345
430
  const visitedIdx = (state.visitedItems || [])
346
431
  .map((id) => this.items.findIndex((q) => q.identifier === id))
@@ -355,12 +440,26 @@ export class AssessmentPlayer {
355
440
  await this.navigateTo(0, { restoring: true });
356
441
  }
357
442
  }
443
+ restoreTimeTracking(timing) {
444
+ this.timeManager?.restoreState({
445
+ totalElapsed: timing.totalTime,
446
+ itemTimes: { ...timing.itemTimes },
447
+ sectionTimes: { ...(timing.sectionTimes ?? {}) },
448
+ testPartTimes: { ...(timing.testPartTimes ?? {}) },
449
+ startedAt: timing.startedAt,
450
+ currentItemId: timing.currentItemIdentifier,
451
+ currentSectionId: timing.currentSectionIdentifier,
452
+ currentTestPartId: timing.currentTestPartIdentifier,
453
+ isPaused: timing.isPaused === true,
454
+ });
455
+ }
358
456
  async navigateTo(index, options = {}) {
359
457
  if (index < 0 || index >= this.items.length)
360
458
  throw new Error(`Invalid item index: ${index}`);
361
459
  // Enforce navigation rules (UI hints, still backend-authoritative for real deployments).
362
- if (!options.restoring && this.currentItemIndex >= 0 && !this.navigationManager.canNavigateTo(index, this.currentItemIndex)) {
363
- if (this.navigationManager.getMode() === 'linear' && index > this.currentItemIndex + 1) {
460
+ if (!options.restoring && this.currentItemIndex >= 0 && !this.canNavigateByTestPart(index, this.currentItemIndex)) {
461
+ const currentMode = this.items[this.currentItemIndex]?.testPart.navigationMode ?? this.assessment.navigationMode;
462
+ if (currentMode === 'linear' && index > this.currentItemIndex + 1) {
364
463
  throw new Error('In linear navigation mode, you can only move to the next question.');
365
464
  }
366
465
  throw new Error('Navigation is not allowed.');
@@ -370,6 +469,9 @@ export class AssessmentPlayer {
370
469
  throw new Error('You cannot go back to previous questions in this assessment.');
371
470
  }
372
471
  const currentItem = this.items[this.currentItemIndex];
472
+ if (!options.restoring && currentItem && target) {
473
+ this.assertTransitionMinimum(currentItem, target);
474
+ }
373
475
  const currentSessionStatus = currentItem ? this.state.itemSessions?.[currentItem.identifier]?.lifecycleStatus : undefined;
374
476
  if (!options.restoring &&
375
477
  this.currentItemIndex >= 0 &&
@@ -383,8 +485,11 @@ export class AssessmentPlayer {
383
485
  this.currentItemIndex = index;
384
486
  const q = this.items[index];
385
487
  this.state.currentItemIdentifier = q.identifier;
386
- this.timeManager?.startSection(q.section.identifier);
387
- this.timeManager?.startItem(q.identifier);
488
+ this.timeManager?.activateScopes({
489
+ testPart: { identifier: q.testPart.identifier, timeLimits: q.testPart.timeLimits },
490
+ section: { identifier: q.section.identifier, timeLimits: q.section.timeLimits },
491
+ item: { identifier: q.identifier, timeLimits: q.item.timeLimits },
492
+ });
388
493
  // Apply three-level itemSessionControl fallback for this item's section (S1).
389
494
  const effectiveControl = this.getEffectiveItemSessionControl(q);
390
495
  if (effectiveControl) {
@@ -400,6 +505,7 @@ export class AssessmentPlayer {
400
505
  i18nProvider: this.i18nProvider,
401
506
  pnp: this.config.pnp,
402
507
  security: this.config.security,
508
+ pci: this.config.pci,
403
509
  deliveryContext: q.item.deliveryContext,
404
510
  });
405
511
  const restoredItemSession = this.state.itemSessions?.[q.identifier];
@@ -430,7 +536,7 @@ export class AssessmentPlayer {
430
536
  throw new Error(navAway.reason || 'You must answer this question before continuing.');
431
537
  }
432
538
  // In individual submission mode, submit current item before moving forward.
433
- if (this.assessment.submissionMode === 'individual') {
539
+ if ((q.testPart.submissionMode ?? this.assessment.submissionMode) === 'individual') {
434
540
  const before = this.currentItemIndex;
435
541
  await this.submitCurrentItem();
436
542
  // submitCurrentItem may branch/navigate; if it did, we're done.
@@ -451,6 +557,7 @@ export class AssessmentPlayer {
451
557
  const q = this.items[this.currentItemIndex];
452
558
  if (!q)
453
559
  throw new Error('No current item');
560
+ this.assertMinimumTime('item', q);
454
561
  const submittedAt = Date.now();
455
562
  let itemSession;
456
563
  const responses = this.sessionCoordinator.getActiveResponses();
@@ -525,7 +632,7 @@ export class AssessmentPlayer {
525
632
  ? item.section.identifier !== currentItem?.section.identifier
526
633
  : item.testPart.identifier !== currentItem?.testPart.identifier));
527
634
  if (nextIdx >= 0) {
528
- await this.navigateTo(nextIdx);
635
+ await this.navigateTo(nextIdx, { restoring: true });
529
636
  }
530
637
  else {
531
638
  // No further items — signal completion
@@ -537,7 +644,7 @@ export class AssessmentPlayer {
537
644
  else {
538
645
  const nextIdx = this.items.findIndex((x) => x.identifier === special);
539
646
  if (nextIdx >= 0) {
540
- await this.navigateTo(nextIdx);
647
+ await this.navigateTo(nextIdx, { restoring: true });
541
648
  }
542
649
  }
543
650
  }
@@ -549,7 +656,7 @@ export class AssessmentPlayer {
549
656
  const prev = this.items[this.currentItemIndex - 1];
550
657
  if (!prev)
551
658
  return false;
552
- if (!this.navigationManager.canNavigateTo(this.currentItemIndex - 1, this.currentItemIndex))
659
+ if (!this.canNavigateByTestPart(this.currentItemIndex - 1, this.currentItemIndex))
553
660
  return false;
554
661
  return this.sessionCoordinator.canReview(prev.identifier);
555
662
  }
@@ -559,13 +666,35 @@ export class AssessmentPlayer {
559
666
  const nextIdx = this.currentItemIndex + 1;
560
667
  if (nextIdx >= this.items.length)
561
668
  return false;
562
- if (!this.navigationManager.canNavigateTo(nextIdx, this.currentItemIndex))
669
+ if (!this.canNavigateByTestPart(nextIdx, this.currentItemIndex))
563
670
  return false;
564
671
  // Note: itemSessionControl constraints on leaving current item are enforced in next().
565
672
  return true;
566
673
  }
674
+ canNavigateByTestPart(targetIndex, currentIndex) {
675
+ if (targetIndex < 0 || targetIndex >= this.items.length)
676
+ return false;
677
+ const current = this.items[currentIndex];
678
+ const target = this.items[targetIndex];
679
+ if (!current || !target)
680
+ return false;
681
+ if (current.testPart !== target.testPart) {
682
+ // QTI testParts are delivered in sequence. A candidate may enter the next
683
+ // part, but cannot jump across parts or return to a completed part.
684
+ return targetIndex === currentIndex + 1;
685
+ }
686
+ const mode = current.testPart.navigationMode ?? this.assessment.navigationMode ?? 'nonlinear';
687
+ return mode === 'nonlinear' || targetIndex === currentIndex || targetIndex === currentIndex + 1;
688
+ }
567
689
  /** Submit entire assessment (finalize on backend) */
568
690
  async submit() {
691
+ const current = this.items[this.currentItemIndex];
692
+ if (current) {
693
+ this.assertMinimumTime('item', current);
694
+ this.assertMinimumTime('section', current);
695
+ this.assertMinimumTime('testPart', current);
696
+ this.assertMinimumTime('assessment', current);
697
+ }
569
698
  // For simultaneous submission, ensure all items are submitted before finalize so
570
699
  // the backend can compute a complete test score.
571
700
  if (this.assessment.submissionMode === 'simultaneous') {
@@ -797,6 +926,25 @@ function shuffleArray(arr, rng) {
797
926
  }
798
927
  return out;
799
928
  }
929
+ function isRequiredSectionComponent(component) {
930
+ return component.type === 'item' ? component.item.required === true : component.section.required === true;
931
+ }
932
+ function isFixedSectionComponent(component) {
933
+ return component.type === 'item' ? component.item.fixed === true : component.section.fixed === true;
934
+ }
935
+ /** Shuffle non-fixed children while retaining fixed children at their post-selection positions. */
936
+ function shuffleSectionComponents(components, rng) {
937
+ const result = [...components];
938
+ const movableIndexes = components
939
+ .map((component, index) => ({ component, index }))
940
+ .filter(({ component }) => !isFixedSectionComponent(component))
941
+ .map(({ index }) => index);
942
+ const shuffled = shuffleArray(movableIndexes.map((index) => components[index]), rng);
943
+ for (let index = 0; index < movableIndexes.length; index++) {
944
+ result[movableIndexes[index]] = shuffled[index];
945
+ }
946
+ return result;
947
+ }
800
948
  function cloneData(value) {
801
949
  return value === undefined ? undefined : structuredClone(value);
802
950
  }