@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.
- package/README.md +28 -7
- package/dist/components/createPlayerConnection.svelte.d.ts +90 -0
- package/dist/components/createPlayerConnection.svelte.js +151 -0
- package/dist/components/createPlayerConnection.svelte.js.map +1 -0
- package/dist/components/displaySettings.svelte.d.ts +23 -0
- package/dist/components/displaySettings.svelte.js +40 -0
- package/dist/components/displaySettings.svelte.js.map +1 -0
- package/dist/components/srOnly.d.ts +29 -0
- package/dist/components/srOnly.js +55 -0
- package/dist/components/srOnly.js.map +1 -0
- package/dist/components/submitDialogAction.d.ts +25 -0
- package/dist/components/submitDialogAction.js +89 -0
- package/dist/components/submitDialogAction.js.map +1 -0
- package/dist/core/AssessmentPlayer.d.ts +1102 -53
- package/dist/core/AssessmentPlayer.js +2836 -457
- package/dist/core/AssessmentPlayer.js.map +1 -1
- package/dist/core/AssessmentSessionCoordinator.d.ts +76 -7
- package/dist/core/AssessmentSessionCoordinator.js +185 -10
- package/dist/core/AssessmentSessionCoordinator.js.map +1 -1
- package/dist/core/AutosaveManager.d.ts +104 -0
- package/dist/core/AutosaveManager.js +181 -0
- package/dist/core/AutosaveManager.js.map +1 -0
- package/dist/core/ItemSessionController.d.ts +17 -26
- package/dist/core/ItemSessionController.js +33 -73
- package/dist/core/ItemSessionController.js.map +1 -1
- package/dist/core/NavigationManager.d.ts +18 -50
- package/dist/core/NavigationManager.js +21 -83
- package/dist/core/NavigationManager.js.map +1 -1
- package/dist/core/TimeManager.d.ts +62 -16
- package/dist/core/TimeManager.js +148 -57
- package/dist/core/TimeManager.js.map +1 -1
- package/dist/core/autosave.d.ts +44 -0
- package/dist/core/autosave.js +46 -0
- package/dist/core/autosave.js.map +1 -0
- package/dist/core/deliveryStructure.d.ts +54 -0
- package/dist/core/deliveryStructure.js +72 -0
- package/dist/core/deliveryStructure.js.map +1 -0
- package/dist/core/errors.d.ts +116 -0
- package/dist/core/errors.js +77 -0
- package/dist/core/errors.js.map +1 -0
- package/dist/core/exitBoundaries.d.ts +64 -0
- package/dist/core/exitBoundaries.js +98 -0
- package/dist/core/exitBoundaries.js.map +1 -0
- package/dist/core/feedback.d.ts +46 -0
- package/dist/core/feedback.js +47 -0
- package/dist/core/feedback.js.map +1 -0
- package/dist/core/formatTime.d.ts +8 -0
- package/dist/core/formatTime.js +20 -0
- package/dist/core/formatTime.js.map +1 -0
- package/dist/core/index.d.ts +7 -4
- package/dist/core/index.js +4 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/navigationPolicy.d.ts +46 -0
- package/dist/core/navigationPolicy.js +66 -0
- package/dist/core/navigationPolicy.js.map +1 -0
- package/dist/core/pause.d.ts +58 -0
- package/dist/core/pause.js +101 -0
- package/dist/core/pause.js.map +1 -0
- package/dist/core/playerEvents.d.ts +51 -0
- package/dist/core/playerEvents.js +66 -0
- package/dist/core/playerEvents.js.map +1 -0
- package/dist/core/reviewState.d.ts +81 -0
- package/dist/core/reviewState.js +113 -0
- package/dist/core/reviewState.js.map +1 -0
- package/dist/core/reviewViews.d.ts +43 -0
- package/dist/core/reviewViews.js +88 -0
- package/dist/core/reviewViews.js.map +1 -0
- package/dist/core/scopeLocks.d.ts +36 -0
- package/dist/core/scopeLocks.js +78 -0
- package/dist/core/scopeLocks.js.map +1 -0
- package/dist/core/sessionRecords.d.ts +31 -0
- package/dist/core/sessionRecords.js +74 -0
- package/dist/core/sessionRecords.js.map +1 -0
- package/dist/core/submissionPolicy.d.ts +65 -0
- package/dist/core/submissionPolicy.js +71 -0
- package/dist/core/submissionPolicy.js.map +1 -0
- package/dist/core/templateDefaults.d.ts +26 -0
- package/dist/core/templateDefaults.js +54 -0
- package/dist/core/templateDefaults.js.map +1 -0
- package/dist/core/testStructure.d.ts +118 -3
- package/dist/core/testStructure.js +255 -6
- package/dist/core/testStructure.js.map +1 -1
- package/dist/core/timePolicy.d.ts +40 -0
- package/dist/core/timePolicy.js +106 -0
- package/dist/core/timePolicy.js.map +1 -0
- package/dist/index.d.ts +7 -4
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/integration/ReferenceBackendAdapter.d.ts +64 -101
- package/dist/integration/ReferenceBackendAdapter.js +214 -1033
- package/dist/integration/ReferenceBackendAdapter.js.map +1 -1
- package/dist/integration/api-contract.d.ts +175 -10
- package/dist/integration/api-contract.js.map +1 -1
- package/dist/integration/assessment-item-scorer.d.ts +56 -5
- package/dist/integration/assessment-item-scorer.js +116 -13
- package/dist/integration/assessment-item-scorer.js.map +1 -1
- package/dist/integration/index.d.ts +2 -2
- package/dist/integration/index.js +1 -1
- package/dist/integration/index.js.map +1 -1
- package/dist/integration/qti-test-parser.d.ts +44 -0
- package/dist/integration/qti-test-parser.js +558 -0
- package/dist/integration/qti-test-parser.js.map +1 -0
- package/dist/integration/session-store.d.ts +54 -0
- package/dist/integration/session-store.js +75 -0
- package/dist/integration/session-store.js.map +1 -0
- package/dist/integration/test-navigation.d.ts +23 -0
- package/dist/integration/test-navigation.js +32 -0
- package/dist/integration/test-navigation.js.map +1 -0
- package/dist/integration/toSectionComposition.js +8 -1
- package/dist/integration/toSectionComposition.js.map +1 -1
- package/dist/reporting/index.d.ts +3 -0
- package/dist/reporting/index.js +3 -0
- package/dist/reporting/index.js.map +1 -0
- package/dist/reporting/inferBaseType.d.ts +13 -0
- package/dist/reporting/inferBaseType.js +26 -0
- package/dist/reporting/inferBaseType.js.map +1 -0
- package/dist/reporting/serializeAssessmentResult.d.ts +27 -0
- package/dist/reporting/serializeAssessmentResult.js +377 -0
- package/dist/reporting/serializeAssessmentResult.js.map +1 -0
- package/dist/reporting/toAssessmentResultXml.d.ts +39 -0
- package/dist/reporting/toAssessmentResultXml.js +304 -0
- package/dist/reporting/toAssessmentResultXml.js.map +1 -0
- package/dist/reporting/types.d.ts +85 -0
- package/dist/reporting/types.js +8 -0
- package/dist/reporting/types.js.map +1 -0
- package/dist/types/index.d.ts +96 -9
- package/dist/types/index.js.map +1 -1
- package/package.json +18 -14
- package/dist/core/StatePersistenceManager.d.ts +0 -125
- package/dist/core/StatePersistenceManager.js +0 -268
- package/dist/core/StatePersistenceManager.js.map +0 -1
- package/dist/utils/PerformanceMonitor.d.ts +0 -114
- package/dist/utils/PerformanceMonitor.js +0 -172
- package/dist/utils/PerformanceMonitor.js.map +0 -1
|
@@ -49,6 +49,24 @@ export interface InitSessionResponse {
|
|
|
49
49
|
currentItemIdentifier?: string;
|
|
50
50
|
/** Test-level outcome values of a resumed session, once outcome processing has run */
|
|
51
51
|
outcomes?: TestOutcomeValues;
|
|
52
|
+
/**
|
|
53
|
+
* True when the stored session was already finalized: delivery is over and every
|
|
54
|
+
* further submission would fail. Hosts (and the built-in shell) show a terminal
|
|
55
|
+
* "already submitted" view instead of delivery UI and never offer the resume prompt.
|
|
56
|
+
* `submit()` on such a player returns the stored results instead of failing.
|
|
57
|
+
*/
|
|
58
|
+
finalized?: boolean;
|
|
59
|
+
/**
|
|
60
|
+
* With `finalized`, the stored final result for the terminal view: the totals and,
|
|
61
|
+
* when kept, the per-item scores. A backend may omit it; shells then render the
|
|
62
|
+
* terminal view without scores.
|
|
63
|
+
*/
|
|
64
|
+
finalResults?: {
|
|
65
|
+
totalScore: number;
|
|
66
|
+
maxScore: number;
|
|
67
|
+
itemScores?: Record<string, AssessmentScoringResult>;
|
|
68
|
+
finalizedAt?: number;
|
|
69
|
+
};
|
|
52
70
|
}
|
|
53
71
|
/**
|
|
54
72
|
* A test-level outcome value: a scalar for single cardinality, an array for multiple and ordered,
|
|
@@ -57,6 +75,19 @@ export interface InitSessionResponse {
|
|
|
57
75
|
export type TestOutcomeValue = string | number | boolean | null | Array<string | number | boolean | null> | Record<string, unknown>;
|
|
58
76
|
/** Test-level outcome values keyed by outcome identifier (e.g. "PASS", "GRADE"). */
|
|
59
77
|
export type TestOutcomeValues = Record<string, TestOutcomeValue>;
|
|
78
|
+
/**
|
|
79
|
+
* Structured, typed failure of test-level outcome processing.
|
|
80
|
+
*
|
|
81
|
+
* Delivery continues and candidate responses stay persisted; the error is carried on
|
|
82
|
+
* the session/results so hosts can surface it (onError callback/event) instead of
|
|
83
|
+
* SCORE/testFeedback silently never computing.
|
|
84
|
+
*/
|
|
85
|
+
export interface OutcomeProcessingError {
|
|
86
|
+
/** Stable code — currently always `OUTCOME_PROCESSING_FAILED`. */
|
|
87
|
+
code: 'OUTCOME_PROCESSING_FAILED';
|
|
88
|
+
/** Backend-side detail for logs and host callbacks; never shown verbatim to candidates. */
|
|
89
|
+
message: string;
|
|
90
|
+
}
|
|
60
91
|
/**
|
|
61
92
|
* Assessment structure safe for client consumption
|
|
62
93
|
*
|
|
@@ -78,9 +109,16 @@ export interface TestFeedbackItem {
|
|
|
78
109
|
access: 'atEnd' | 'during';
|
|
79
110
|
/** HTML content to display */
|
|
80
111
|
content: string;
|
|
112
|
+
/**
|
|
113
|
+
* The content's language: the feedback's `xml:lang`, else the test part's or the test's
|
|
114
|
+
* (XML inheritance). Shells render it as the feedback's `lang` and `dir`.
|
|
115
|
+
*/
|
|
116
|
+
language?: string;
|
|
81
117
|
}
|
|
82
118
|
export interface SecureTimeLimits {
|
|
119
|
+
/** Minimum duration in seconds (optional) */
|
|
83
120
|
minTime?: number;
|
|
121
|
+
/** Maximum duration in seconds (optional) */
|
|
84
122
|
maxTime?: number;
|
|
85
123
|
allowLateSubmission?: boolean;
|
|
86
124
|
}
|
|
@@ -127,9 +165,14 @@ export interface SecureTestPart {
|
|
|
127
165
|
* enclosing section to the item ref; the backend enforces maxAttempts.
|
|
128
166
|
*/
|
|
129
167
|
itemSessionControl?: SecureItemSessionControl;
|
|
130
|
-
/**
|
|
168
|
+
/**
|
|
169
|
+
* Serialized direct preCondition expressions, evaluated on entering the part (any navigation
|
|
170
|
+
* mode): by the backend for the moves it decides (`nextItemIdentifier`), and by the player,
|
|
171
|
+
* with the same rules, for a move without a backend decision (a jump into the next part, a
|
|
172
|
+
* move on from a simultaneous part). A part whose precondition fails is skipped.
|
|
173
|
+
*/
|
|
131
174
|
preConditions?: string[];
|
|
132
|
-
/** Branch rules
|
|
175
|
+
/** Branch rules evaluated after the part's last item (any navigation mode). */
|
|
133
176
|
branchRule?: SecureBranchRule[];
|
|
134
177
|
}
|
|
135
178
|
export interface SecureSection {
|
|
@@ -165,7 +208,10 @@ export interface SecureSection {
|
|
|
165
208
|
ordering?: {
|
|
166
209
|
shuffle: boolean;
|
|
167
210
|
};
|
|
168
|
-
/**
|
|
211
|
+
/**
|
|
212
|
+
* Serialized direct preCondition expressions, evaluated on reaching the section in a linear
|
|
213
|
+
* part (by the backend for its decisions, by the player with the same rules otherwise).
|
|
214
|
+
*/
|
|
169
215
|
preConditions?: string[];
|
|
170
216
|
/** Branch rules the backend evaluates after the section's last item, in linear navigation. */
|
|
171
217
|
branchRule?: SecureBranchRule[];
|
|
@@ -220,10 +266,14 @@ export interface SecureItemRef {
|
|
|
220
266
|
deliveryContext?: ResolvedItemDeliveryContext;
|
|
221
267
|
/**
|
|
222
268
|
* QTI branchRule: ordered branch rules on this item. The backend evaluates them after scoring, in
|
|
223
|
-
* linear navigation, and returns the resolved target as nextItemIdentifier.
|
|
269
|
+
* linear navigation, and returns the resolved target as nextItemIdentifier. With no backend
|
|
270
|
+
* decision for the move, the player applies them itself with the same rules.
|
|
224
271
|
*/
|
|
225
272
|
branchRule?: SecureBranchRule[];
|
|
226
|
-
/**
|
|
273
|
+
/**
|
|
274
|
+
* Serialized direct preCondition expressions, evaluated on reaching the item in a linear part
|
|
275
|
+
* (by the backend for its decisions, by the player with the same rules otherwise).
|
|
276
|
+
*/
|
|
227
277
|
preConditions?: string[];
|
|
228
278
|
/** QTI item-ref weights, preserved for backend outcome processing. */
|
|
229
279
|
weights?: Array<{
|
|
@@ -254,9 +304,15 @@ export interface AssessmentRubricBlock {
|
|
|
254
304
|
/** Rubric content (HTML) */
|
|
255
305
|
content: string;
|
|
256
306
|
/** View controls when rubric is shown */
|
|
257
|
-
view
|
|
307
|
+
/** Authored QTI `view` tokens (arbitrary token lists, not just roles). */
|
|
308
|
+
view: string[];
|
|
258
309
|
/** Optional rubric use (QTI rubricBlock@use), e.g. "passage" */
|
|
259
310
|
use?: string;
|
|
311
|
+
/**
|
|
312
|
+
* The content's language: the block's `xml:lang`, else its nearest enclosing element's
|
|
313
|
+
* (XML inheritance). Section layouts render it as the block's `lang`, `dir` and read-aloud voice.
|
|
314
|
+
*/
|
|
315
|
+
language?: string;
|
|
260
316
|
}
|
|
261
317
|
/**
|
|
262
318
|
* Submit responses for scoring
|
|
@@ -273,11 +329,19 @@ export interface SubmitResponsesRequest {
|
|
|
273
329
|
submittedAt: number;
|
|
274
330
|
/** Time spent on item (ms) for analytics */
|
|
275
331
|
timeSpent?: number;
|
|
332
|
+
/**
|
|
333
|
+
* QTI endAttempt countAttempt (default true). False marks a hint / "show me" submission that
|
|
334
|
+
* runs response processing without consuming an attempt: backends must not count it toward
|
|
335
|
+
* maxAttempts and must not record it as the item's result — the candidate continues.
|
|
336
|
+
*/
|
|
337
|
+
countAttempt?: boolean;
|
|
276
338
|
/** Optional client timing evidence; production backends remain authoritative. */
|
|
277
339
|
timing?: SubmitTimingEvidence;
|
|
278
340
|
/**
|
|
279
341
|
* Serialized item session used by backends to restore template/context variables while scoring.
|
|
280
342
|
* Production backends should treat this as a client save format and validate against server-owned state.
|
|
343
|
+
* Sent when the host enables `sendItemSessionToBackend`, and always to a backend that
|
|
344
|
+
* declares `requiresItemSession` (the reference adapter does).
|
|
281
345
|
*/
|
|
282
346
|
itemSession?: SerializedItemSessionState;
|
|
283
347
|
/** Candidate comment, accepted only when the item's allowComment is on. */
|
|
@@ -289,6 +353,32 @@ export interface SubmitTimingEvidence {
|
|
|
289
353
|
limitSeconds?: number;
|
|
290
354
|
expired?: boolean;
|
|
291
355
|
allowLateSubmission?: boolean;
|
|
356
|
+
/**
|
|
357
|
+
* The candidate's assessment clock in ms when the test has a maximum time. It runs
|
|
358
|
+
* only while delivery runs: time behind an opt-in begin gate or a proctor pause is
|
|
359
|
+
* excluded, unlike a wall clock measured from session creation.
|
|
360
|
+
*/
|
|
361
|
+
assessmentElapsedMs?: number;
|
|
362
|
+
/** The test's maximum time in seconds after PNP extended time, when it has one. */
|
|
363
|
+
assessmentLimitSeconds?: number;
|
|
364
|
+
/**
|
|
365
|
+
* Why this submission runs: `candidate` (default) for a normal candidate action,
|
|
366
|
+
* `time-expired` for the terminal response collection a hard time limit triggers
|
|
367
|
+
* (the whole-test auto-submit, and the submit from an expiry dead end), `proctor` for
|
|
368
|
+
* the collection a proctor's forced end of the test (`submit({ force: true })`) runs,
|
|
369
|
+
* `unreachable` for a question the end of the test collects as it stands although its
|
|
370
|
+
* QTI `allowSkipping` / `validateResponses` control would refuse it, because the
|
|
371
|
+
* candidate can no longer reach it (its test part was left — a session restored from
|
|
372
|
+
* before the part-leave gate, a branch rule).
|
|
373
|
+
* Backends must accept a `time-expired` submission whose scope expired: the delivery
|
|
374
|
+
* window closed with the expiry, and collecting the pending responses is the mandated
|
|
375
|
+
* terminal step. A `proctor` collection is an administrative end of the test, made
|
|
376
|
+
* during a pause or ahead of the candidate's own submit; record it as such (it
|
|
377
|
+
* bypasses the candidate-side skipping and validation controls). Record an
|
|
378
|
+
* `unreachable` one as skipped (or incomplete) as it stands, never as a normal
|
|
379
|
+
* candidate submission.
|
|
380
|
+
*/
|
|
381
|
+
submissionReason?: 'candidate' | 'time-expired' | 'proctor' | 'unreachable';
|
|
292
382
|
}
|
|
293
383
|
/**
|
|
294
384
|
* Response value can be string, string[], or complex types
|
|
@@ -300,8 +390,13 @@ export interface SubmitResponsesResponse {
|
|
|
300
390
|
/** Scoring result (if submission mode allows immediate scoring) */
|
|
301
391
|
result?: AssessmentScoringResult;
|
|
302
392
|
/**
|
|
303
|
-
* Backend-authoritative next item (branching/navigation decision)
|
|
304
|
-
*
|
|
393
|
+
* Backend-authoritative next item (branching/navigation decision): the item the test's branch
|
|
394
|
+
* rules and preconditions deliver after this submission, or `EXIT_TEST` / `EXIT_TESTPART` /
|
|
395
|
+
* `EXIT_SECTION`. The player follows it on the candidate's move; a submission that stays on the
|
|
396
|
+
* item (a practice check, a counted endAttemptInteraction) keeps it, and the candidate's next
|
|
397
|
+
* move on from the item that submits nothing follows it. If omitted, the player moves to the
|
|
398
|
+
* next item the delivery rules make eligible, evaluating the test's branch rules and
|
|
399
|
+
* preconditions itself with the reference rules (for a test without any: the adjacent item).
|
|
305
400
|
*/
|
|
306
401
|
nextItemIdentifier?: string;
|
|
307
402
|
/**
|
|
@@ -311,9 +406,24 @@ export interface SubmitResponsesResponse {
|
|
|
311
406
|
updatedState?: AssessmentSessionState;
|
|
312
407
|
/** Test-level outcome values after the outcome processing this submission triggers */
|
|
313
408
|
outcomes?: TestOutcomeValues;
|
|
409
|
+
/** Set when test-level outcome processing failed; responses are still accepted and persisted. */
|
|
410
|
+
outcomeProcessingError?: OutcomeProcessingError;
|
|
314
411
|
/** Error message if success=false */
|
|
315
412
|
error?: string;
|
|
316
413
|
}
|
|
414
|
+
/**
|
|
415
|
+
* Structured, typed failure of one item's response processing.
|
|
416
|
+
*
|
|
417
|
+
* Mirrors `OutcomeProcessingError`: the submission is still accepted and delivery
|
|
418
|
+
* continues, but the item's score is a degenerate 0 (its declared maximum where known)
|
|
419
|
+
* and hosts must be able to tell "answered wrong" from "the engine failed to score".
|
|
420
|
+
*/
|
|
421
|
+
export interface ItemScoringError {
|
|
422
|
+
/** Stable code — currently always `ITEM_SCORING_FAILED`. */
|
|
423
|
+
code: 'ITEM_SCORING_FAILED';
|
|
424
|
+
/** Engine-side detail for logs and host callbacks; never shown verbatim to candidates. */
|
|
425
|
+
message: string;
|
|
426
|
+
}
|
|
317
427
|
/**
|
|
318
428
|
* Scoring result returned from server
|
|
319
429
|
*
|
|
@@ -334,6 +444,11 @@ export interface AssessmentScoringResult {
|
|
|
334
444
|
feedback?: FeedbackItem[];
|
|
335
445
|
/** Correct response (only if role allows) */
|
|
336
446
|
correctResponse?: Record<string, ResponseValue>;
|
|
447
|
+
/**
|
|
448
|
+
* Set when response processing for this item failed: the score is a degenerate 0
|
|
449
|
+
* (the declared maximum where known), NOT a candidate's wrong answer.
|
|
450
|
+
*/
|
|
451
|
+
scoringError?: ItemScoringError;
|
|
337
452
|
}
|
|
338
453
|
export interface FeedbackItem {
|
|
339
454
|
/** Feedback content (HTML) */
|
|
@@ -370,6 +485,28 @@ export interface AssessmentSessionState {
|
|
|
370
485
|
itemSessions?: Record<string, SerializedItemSessionState>;
|
|
371
486
|
/** Candidate comments per item, captured where allowComment is on. */
|
|
372
487
|
itemComments?: Record<string, string>;
|
|
488
|
+
/** Items the candidate flagged for review, keyed by item identifier. */
|
|
489
|
+
itemFlags?: Record<string, boolean>;
|
|
490
|
+
/**
|
|
491
|
+
* The backend's branch decision (`nextItemIdentifier`) kept per item with its
|
|
492
|
+
* last-submission record: item identifier → target (an item, section or test part
|
|
493
|
+
* identifier, or EXIT_TEST). Only the freshest counted submission's decision is kept —
|
|
494
|
+
* any later counted submission replaces it — and delivery follows it on the next
|
|
495
|
+
* forward step from that item that submits nothing, so a restored session lands
|
|
496
|
+
* identically to the live one. (Session format addition; backends that never store it
|
|
497
|
+
* just lose the kept decision across a resume.)
|
|
498
|
+
*/
|
|
499
|
+
branchDecisions?: Record<string, string>;
|
|
500
|
+
/**
|
|
501
|
+
* The test-level outcome values the backend last returned (its outcome processing's
|
|
502
|
+
* result, or undefined before the first submission): branch and preCondition rules read
|
|
503
|
+
* them, so a restored session navigates identically to the live one. (Session format
|
|
504
|
+
* addition; backends that never store it just lose the values across a resume, and the
|
|
505
|
+
* restored rules evaluate on missing outcomes.)
|
|
506
|
+
*/
|
|
507
|
+
testOutcomes?: TestOutcomeValues;
|
|
508
|
+
/** Whether the candidate chose to hide the countdown timer (a persisted shell preference). */
|
|
509
|
+
timerHidden?: boolean;
|
|
373
510
|
/** Time tracking */
|
|
374
511
|
timing: {
|
|
375
512
|
/** Session start time */
|
|
@@ -386,7 +523,18 @@ export interface AssessmentSessionState {
|
|
|
386
523
|
currentItemIdentifier?: string;
|
|
387
524
|
currentSectionIdentifier?: string;
|
|
388
525
|
currentTestPartIdentifier?: string;
|
|
526
|
+
/**
|
|
527
|
+
* A proctor pause was in force when the state was saved: a restored session
|
|
528
|
+
* reopens paused, its clocks frozen, until the host resumes it.
|
|
529
|
+
*/
|
|
389
530
|
isPaused?: boolean;
|
|
531
|
+
/** The candidate-facing reason the proctor gave for the pause. */
|
|
532
|
+
pauseReason?: string;
|
|
533
|
+
/**
|
|
534
|
+
* Client clock (ms) of the last autosave persisted into this snapshot. Shells
|
|
535
|
+
* show it on the resume prompt ("You have answers saved from {time}").
|
|
536
|
+
*/
|
|
537
|
+
savedAt?: number;
|
|
390
538
|
};
|
|
391
539
|
}
|
|
392
540
|
export interface AssessmentItemSessionState {
|
|
@@ -412,10 +560,10 @@ export interface FinalizeAssessmentResponse {
|
|
|
412
560
|
maxScore: number;
|
|
413
561
|
/** Per-item results */
|
|
414
562
|
itemScores: Record<string, AssessmentScoringResult>;
|
|
415
|
-
/** Assessment-level feedback (legacy: single string; prefer outcomes + assessment.testFeedback) */
|
|
416
|
-
feedback?: string;
|
|
417
563
|
/** Test-level outcome values after outcomeProcessing; testFeedback visibility reads them. */
|
|
418
564
|
outcomes?: TestOutcomeValues;
|
|
565
|
+
/** Set when test-level outcome processing failed; item results are still returned. */
|
|
566
|
+
outcomeProcessingError?: OutcomeProcessingError;
|
|
419
567
|
/** Server timestamp */
|
|
420
568
|
finalizedAt: number;
|
|
421
569
|
}
|
|
@@ -481,6 +629,23 @@ export interface BackendAdapter {
|
|
|
481
629
|
* Save session state (auto-save during assessment)
|
|
482
630
|
*/
|
|
483
631
|
saveState(request: SaveAssessmentStateRequest): Promise<SaveAssessmentStateResponse>;
|
|
632
|
+
/**
|
|
633
|
+
* Whether this adapter persists candidate drafts through `saveState`. Autosave is
|
|
634
|
+
* ON by default whenever the backend reports the capability (default `true`, so
|
|
635
|
+
* adapters that implement `saveState` get autosave without extra wiring); set
|
|
636
|
+
* `canSaveState: false` when the backend cannot store drafts or the host saves
|
|
637
|
+
* state itself and wants the shell's autosave and its save indicator off.
|
|
638
|
+
*/
|
|
639
|
+
canSaveState?: boolean;
|
|
640
|
+
/**
|
|
641
|
+
* Whether this backend scores from the candidate's serialized item session
|
|
642
|
+
* (`SubmitResponsesRequest.itemSession`) and therefore must always receive it: a
|
|
643
|
+
* templated item's instance (the key the candidate saw) and an adaptive item's
|
|
644
|
+
* accumulated outcomes live there. When true the player sends it on every submission,
|
|
645
|
+
* whatever `sendItemSessionToBackend` says. `ReferenceBackendAdapter` sets it; a
|
|
646
|
+
* production backend that owns the item session server-side leaves it unset.
|
|
647
|
+
*/
|
|
648
|
+
requiresItemSession?: boolean;
|
|
484
649
|
/**
|
|
485
650
|
* Finalize assessment and get results
|
|
486
651
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-contract.js","sourceRoot":"","sources":["../../src/integration/api-contract.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG","sourcesContent":["/**\n * QTI 2.2 Assessment Player - Backend Integration API Contract\n *\n * This file defines the secure API boundary between the client-side player\n * and backend services. The design prioritizes security by ensuring sensitive\n * data (correct answers, scoring rules) never reaches the client.\n *\n * ## Security Model\n *\n * - **Client-side**: Collects and submits candidate responses only\n * - **Server-side**: Stores QTI XML, performs scoring, validates submissions\n * - **Role-based**: Server controls what data client receives based on QTI role\n *\n * ## Reference Implementation\n *\n * See `ReferenceBackendAdapter.ts` for a simple localStorage-based implementation\n * that demonstrates the API contract without requiring a real backend.\n */\n\nimport type { QTIRole, ResolvedItemDeliveryContext, SerializedItemSessionState } from '@pie-qti/item-player';\n\n// ============================================================================\n// SESSION MANAGEMENT\n// ============================================================================\n\n/**\n * Unique identifier for an assessment session\n * Format: \"{assessmentId}:{candidateId}:{timestamp}\" or similar\n */\nexport type SessionId = string;\n\n/**\n * Initialize a new assessment session\n *\n * Security: Server validates candidate identity and assessment access\n */\nexport interface InitSessionRequest {\n\t/** Assessment identifier (QTI assessmentTest identifier) */\n\tassessmentId: string;\n\t/** Candidate identifier (from authentication system) */\n\tcandidateId: string;\n\t/** Optional: Resume from existing session */\n\tresumeSessionId?: SessionId;\n}\n\nexport interface InitSessionResponse {\n\t/** Unique session identifier for all subsequent requests */\n\tsessionId: SessionId;\n\t/** Assessment structure without sensitive data, as drawn for this session; a resume returns the same draw. */\n\tassessment: SecureAssessment;\n\t/** Restored state if resuming, undefined if new session */\n\trestoredState?: AssessmentSessionState;\n\t/**\n\t * Item delivery starts at in a new session: the first item whose preconditions hold. A resumed\n\t * session carries it in `restoredState`.\n\t */\n\tcurrentItemIdentifier?: string;\n\t/** Test-level outcome values of a resumed session, once outcome processing has run */\n\toutcomes?: TestOutcomeValues;\n}\n\n/**\n * A test-level outcome value: a scalar for single cardinality, an array for multiple and ordered,\n * an object for record, and `null` for NULL.\n */\nexport type TestOutcomeValue =\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| Array<string | number | boolean | null>\n\t| Record<string, unknown>;\n\n/** Test-level outcome values keyed by outcome identifier (e.g. \"PASS\", \"GRADE\"). */\nexport type TestOutcomeValues = Record<string, TestOutcomeValue>;\n\n// ============================================================================\n// ASSESSMENT STRUCTURE (CLIENT-SAFE)\n// ============================================================================\n\n/**\n * Assessment structure safe for client consumption\n *\n * Security: NO correct answers, NO scoring rules, NO sensitive rubrics\n */\nexport interface TestFeedbackItem {\n\tidentifier: string;\n\t/** Outcome variable name to evaluate (e.g. \"PASS\", \"GRADE\") */\n\toutcomeIdentifier: string;\n\t/**\n\t * 'show' = show when the outcome matches identifier (equality for a single value, membership\n\t * for multiple and ordered); 'hide' = show when it does not\n\t */\n\tshowHide: 'show' | 'hide';\n\t/**\n\t * 'atEnd' = once the test (or, for test-part feedback, the part) has ended;\n\t * 'during' = whenever outcome processing has run\n\t */\n\taccess: 'atEnd' | 'during';\n\t/** HTML content to display */\n\tcontent: string;\n}\n\nexport interface SecureTimeLimits {\n\tminTime?: number;\n\tmaxTime?: number;\n\tallowLateSubmission?: boolean;\n}\n\nexport interface SecureAssessment {\n\tidentifier: string;\n\ttitle: string;\n\t/** Navigation mode affects UI */\n\tnavigationMode: 'linear' | 'nonlinear';\n\t/** Submission mode affects when responses are finalized */\n\tsubmissionMode: 'individual' | 'simultaneous';\n\t/** Test parts contain sections */\n\ttestParts: SecureTestPart[];\n\t/** Overall time limit in seconds (optional) */\n\ttimeLimits?: SecureTimeLimits;\n\t/** QTI outcomeDeclarations for test-level variables */\n\toutcomeDeclarations?: Array<{\n\t\tidentifier: string;\n\t\tbaseType: string;\n\t\tcardinality: string;\n\t\tdefaultValue?: unknown;\n\t}>;\n\t/** Raw <outcomeProcessing> XML string, if present */\n\toutcomeProcessingXml?: string;\n\t/** Base URL/path for resolving relative hrefs (e.g. assessmentSectionRef) */\n\tbaseUrl?: string;\n\t/** QTI assessmentTest testFeedback blocks */\n\ttestFeedback?: TestFeedbackItem[];\n}\n\nexport interface SecureTestPart {\n\tidentifier: string;\n\t/** Navigation and submission modes are scoped to each QTI testPart. */\n\tnavigationMode?: 'linear' | 'nonlinear';\n\tsubmissionMode?: 'individual' | 'simultaneous';\n\t/** Sections contain items */\n\tsections: SecureSection[];\n\t/** TestPart-level time limit. */\n\ttimeLimits?: SecureTimeLimits;\n\t/** Candidate instructions (safe for display) */\n\trubricBlocks?: AssessmentRubricBlock[];\n\t/** QTI testPart testFeedback blocks */\n\ttestFeedback?: TestFeedbackItem[];\n\t/**\n\t * Item session control (QTI testPart/itemSessionControl). Each attribute cascades through every\n\t * enclosing section to the item ref; the backend enforces maxAttempts.\n\t */\n\titemSessionControl?: SecureItemSessionControl;\n\t/** Serialized direct preCondition expressions, evaluated by the backend on entering the part. */\n\tpreConditions?: string[];\n\t/** Branch rules the backend evaluates after the part's last item, in linear navigation. */\n\tbranchRule?: SecureBranchRule[];\n}\n\nexport interface SecureSection {\n\tidentifier: string;\n\ttitle?: string;\n\trequired?: boolean;\n\tfixed?: boolean;\n\t/** Visible determines if section appears in navigation */\n\tvisible: boolean;\n\t/** Assessment item references, in the order the backend drew for this session. */\n\tassessmentItemRefs: SecureItemRef[];\n\t/** Nested QTI sections, retained instead of being flattened during XML ingestion. */\n\tsections?: SecureSection[];\n\t/**\n\t * Direct delivery components in document order. When present, this is the\n\t * authoritative order for mixed item/section children.\n\t */\n\tchildren?: SecureSectionComponent[];\n\t/** Section-level time limit */\n\ttimeLimits?: SecureTimeLimits;\n\t/** Candidate instructions (safe for display) */\n\trubricBlocks?: AssessmentRubricBlock[];\n\t/**\n\t * QTI selection: how many children to present from this section. Backends draw selection when\n\t * the session starts and return the drawn assessment without it; the client never draws.\n\t */\n\tselection?: {\n\t\t/** Number of items selected for this session */\n\t\tselect: number;\n\t\twithReplacement?: boolean;\n\t};\n\t/** QTI ordering: whether non-fixed children are shuffled. Backends apply it with selection. */\n\tordering?: {\n\t\tshuffle: boolean;\n\t};\n\t/** Serialized direct preCondition expressions, evaluated by the backend. */\n\tpreConditions?: string[];\n\t/** Branch rules the backend evaluates after the section's last item, in linear navigation. */\n\tbranchRule?: SecureBranchRule[];\n\t/**\n\t * QTI keepTogether, default true. An invisible section with keepTogether false has its children\n\t * mixed into the parent's ordering; the backend applies it while drawing.\n\t */\n\tkeepTogether?: boolean;\n\t/**\n\t * Item session control (QTI assessmentSection/itemSessionControl). Attributes set here override\n\t * the enclosing section's and test part's.\n\t */\n\titemSessionControl?: SecureItemSessionControl;\n}\n\n/** QTI itemSessionControl. Absent attributes inherit from the enclosing section or test part. */\nexport interface SecureItemSessionControl {\n\t/** Default 1; 0 means unlimited. Adaptive items are unlimited whatever the value. */\n\tmaxAttempts?: number;\n\tshowFeedback?: boolean;\n\tallowReview?: boolean;\n\tshowSolution?: boolean;\n\tallowComment?: boolean;\n\tallowSkipping?: boolean;\n\tvalidateResponses?: boolean;\n}\n\nexport interface SecureBranchRule {\n\t/** Identifier of the target item, section or test part, or EXIT_TEST, EXIT_TESTPART or EXIT_SECTION. */\n\ttarget: string;\n\t/** Serialised QTI expression XML (the child of <branchRule>). Absent means unconditional. */\n\tconditionXml?: string;\n}\n\nexport type SecureSectionComponent =\n\t| { type: 'item'; item: SecureItemRef }\n\t| { type: 'section'; section: SecureSection };\n\nexport interface SecureItemRef {\n\t/** Unique item identifier */\n\tidentifier: string;\n\t/** Item XML WITHOUT responseProcessing if role is 'candidate' */\n\titemXml: string;\n\t/** QTI role determines what's visible in itemXml */\n\trole: QTIRole;\n\t/** Required=true means item must be attempted */\n\trequired?: boolean;\n\tfixed?: boolean;\n\t/** Item-ref-level time limit. */\n\ttimeLimits?: SecureTimeLimits;\n\t/** Optional resolved QTI 3 delivery context. Additive; itemXml remains the compatibility path. */\n\tdeliveryContext?: ResolvedItemDeliveryContext;\n\t/**\n\t * QTI branchRule: ordered branch rules on this item. The backend evaluates them after scoring, in\n\t * linear navigation, and returns the resolved target as nextItemIdentifier.\n\t */\n\tbranchRule?: SecureBranchRule[];\n\t/** Serialized direct preCondition expressions, evaluated by the backend. */\n\tpreConditions?: string[];\n\t/** QTI item-ref weights, preserved for backend outcome processing. */\n\tweights?: Array<{ identifier: string; value: number }>;\n\t/** QTI item-ref categories, matched by includeCategory/excludeCategory in outcome processing. */\n\tcategories?: string[];\n\t/** Item session control (assessmentItemRef/itemSessionControl), the innermost cascade level. */\n\titemSessionControl?: SecureItemSessionControl;\n\t/** QTI variableMapping: item variables the test reads under another identifier. */\n\tvariableMappings?: Array<{ sourceIdentifier: string; targetIdentifier: string }>;\n\t/**\n\t * QTI templateDefault: serialized expressions, evaluated against test outcomes, that replace a\n\t * template variable's default before template processing.\n\t */\n\ttemplateDefaults?: Array<{ templateIdentifier: string; expressionXml: string }>;\n}\n\nexport interface AssessmentRubricBlock {\n\t/** Optional rubric identifier (QTI rubricBlock@identifier) */\n\tidentifier?: string;\n\t/** Rubric content (HTML) */\n\tcontent: string;\n\t/** View controls when rubric is shown */\n\tview: QTIRole[];\n\t/** Optional rubric use (QTI rubricBlock@use), e.g. \"passage\" */\n\tuse?: string;\n}\n\n// ============================================================================\n// RESPONSE SUBMISSION\n// ============================================================================\n\n/**\n * Submit responses for scoring\n *\n * Security: Client sends responses only, server performs scoring\n */\nexport interface SubmitResponsesRequest {\n\tsessionId: SessionId;\n\t/** Item identifier */\n\titemIdentifier: string;\n\t/** Response data keyed by responseIdentifier */\n\tresponses: Record<string, ResponseValue>;\n\t/** Client timestamp for analytics */\n\tsubmittedAt: number;\n\t/** Time spent on item (ms) for analytics */\n\ttimeSpent?: number;\n\t/** Optional client timing evidence; production backends remain authoritative. */\n\ttiming?: SubmitTimingEvidence;\n\t/**\n\t * Serialized item session used by backends to restore template/context variables while scoring.\n\t * Production backends should treat this as a client save format and validate against server-owned state.\n\t */\n\titemSession?: SerializedItemSessionState;\n\t/** Candidate comment, accepted only when the item's allowComment is on. */\n\tcomment?: string;\n}\n\nexport interface SubmitTimingEvidence {\n\tscope: 'assessment' | 'testPart' | 'section' | 'item';\n\telapsedMs: number;\n\tlimitSeconds?: number;\n\texpired?: boolean;\n\tallowLateSubmission?: boolean;\n}\n\n/**\n * Response value can be string, string[], or complex types\n */\nexport type ResponseValue = string | string[] | Record<string, any>;\n\nexport interface SubmitResponsesResponse {\n\t/** Was submission accepted? */\n\tsuccess: boolean;\n\t/** Scoring result (if submission mode allows immediate scoring) */\n\tresult?: AssessmentScoringResult;\n\t/**\n\t * Backend-authoritative next item (branching/navigation decision).\n\t * If omitted, client may fall back to linear next/previous UI navigation.\n\t */\n\tnextItemIdentifier?: string;\n\t/**\n\t * Backend-authoritative session state snapshot after applying the submission.\n\t * If provided, client should replace its local state with this.\n\t */\n\tupdatedState?: AssessmentSessionState;\n\t/** Test-level outcome values after the outcome processing this submission triggers */\n\toutcomes?: TestOutcomeValues;\n\t/** Error message if success=false */\n\terror?: string;\n}\n\n// ============================================================================\n// SCORING RESULTS\n// ============================================================================\n\n/**\n * Scoring result returned from server\n *\n * Security: Server computes this, client never sees scoring rules\n */\nexport interface AssessmentScoringResult {\n\t/** Item identifier */\n\titemIdentifier: string;\n\t/** Normalized score 0.0-1.0 */\n\tscore: number;\n\t/** Maximum possible score (usually 1.0) */\n\tmaxScore: number;\n\t/** Was item completed? */\n\tcompleted: boolean;\n\t/** QTI outcome variables */\n\toutcomeValues: Record<string, any>;\n\t/** Feedback to display (role-dependent) */\n\tfeedback?: FeedbackItem[];\n\t/** Correct response (only if role allows) */\n\tcorrectResponse?: Record<string, ResponseValue>;\n}\n\nexport interface FeedbackItem {\n\t/** Feedback content (HTML) */\n\tcontent: string;\n\t/** Feedback type */\n\ttype: 'correct' | 'incorrect' | 'hint' | 'solution';\n}\n\n// ============================================================================\n// STATE PERSISTENCE\n// ============================================================================\n\n/**\n * Save assessment state\n *\n * Security: State includes responses but not scores (until finalized)\n */\nexport interface SaveAssessmentStateRequest {\n\tsessionId: SessionId;\n\tstate: AssessmentSessionState;\n}\n\nexport interface SaveAssessmentStateResponse {\n\tsuccess: boolean;\n\t/** Server timestamp of save */\n\tsavedAt: number;\n}\n\nexport interface AssessmentSessionState {\n\t/** Current item identifier */\n\tcurrentItemIdentifier: string;\n\t/** Visited items (for navigation) */\n\tvisitedItems: string[];\n\t/** Submitted responses per item */\n\titemResponses: Record<string, Record<string, ResponseValue>>;\n\t/** Scoring results per item (populated after submission) */\n\titemScores?: Record<string, AssessmentScoringResult>;\n\t/** ItemSession lifecycle hints per item, used to restore attempt/review UI state */\n\titemSessionStates?: Record<string, AssessmentItemSessionState>;\n\t/** Rich QTI item session snapshots, used to restore variables and score saved sessions. */\n\titemSessions?: Record<string, SerializedItemSessionState>;\n\t/** Candidate comments per item, captured where allowComment is on. */\n\titemComments?: Record<string, string>;\n\t/** Time tracking */\n\ttiming: {\n\t\t/** Session start time */\n\t\tstartedAt: number;\n\t\t/** Time spent per item (ms) */\n\t\titemTimes: Record<string, number>;\n\t\t/** Time spent per assessment section (ms). */\n\t\tsectionTimes?: Record<string, number>;\n\t\t/** Time spent per testPart (ms). */\n\t\ttestPartTimes?: Record<string, number>;\n\t\t/** Total elapsed time (ms) */\n\t\ttotalTime: number;\n\t\t/** Active scope identifiers retained for save/resume timing continuity. */\n\t\tcurrentItemIdentifier?: string;\n\t\tcurrentSectionIdentifier?: string;\n\t\tcurrentTestPartIdentifier?: string;\n\t\tisPaused?: boolean;\n\t};\n}\n\nexport interface AssessmentItemSessionState {\n\titemIdentifier: string;\n\tattemptCount: number;\n\tisAnswered: boolean;\n\tisSubmitted: boolean;\n\tlastSubmissionTime?: number;\n}\n\n// ============================================================================\n// FINALIZE ASSESSMENT\n// ============================================================================\n\n/**\n * Finalize assessment and get full results\n *\n * Security: Server computes final scores, applies late penalties, etc.\n */\nexport interface FinalizeAssessmentRequest {\n\tsessionId: SessionId;\n}\n\nexport interface FinalizeAssessmentResponse {\n\tsuccess: boolean;\n\t/** Overall assessment score */\n\ttotalScore: number;\n\t/** Maximum possible score */\n\tmaxScore: number;\n\t/** Per-item results */\n\titemScores: Record<string, AssessmentScoringResult>;\n\t/** Assessment-level feedback (legacy: single string; prefer outcomes + assessment.testFeedback) */\n\tfeedback?: string;\n\t/** Test-level outcome values after outcomeProcessing; testFeedback visibility reads them. */\n\toutcomes?: TestOutcomeValues;\n\t/** Server timestamp */\n\tfinalizedAt: number;\n}\n\n// ============================================================================\n// ITEM BANK QUERIES\n// ============================================================================\n\n/**\n * Request items from an item bank for random selection\n *\n * Security: Server validates candidate access to bank\n */\nexport interface QueryItemBankRequest {\n\t/** Unique session identifier */\n\tsessionId: SessionId;\n\t/** Item bank identifier (from selection/@fromBank attribute) */\n\tbankId: string;\n\t/** Number of items to select */\n\tcount: number;\n\t/** Whether to allow selecting same item multiple times */\n\twithReplacement?: boolean;\n\t/** Optional filtering criteria (difficulty, topic, etc.) */\n\tfilters?: {\n\t\tdifficulty?: 'easy' | 'medium' | 'hard';\n\t\ttopics?: string[];\n\t\t[key: string]: unknown;\n\t};\n}\n\n/**\n * Items selected from item bank\n *\n * Security: Returns items WITHOUT correct answers or scoring rules\n */\nexport interface QueryItemBankResponse {\n\t/** Selected item references (client-safe) */\n\titems: SecureItemRef[];\n\t/** Server timestamp */\n\tselectedAt: number;\n}\n\n// ============================================================================\n// BACKEND ADAPTER INTERFACE\n// ============================================================================\n\n/**\n * Backend adapter interface - implement this for your backend\n *\n * @example\n * ```typescript\n * class MyBackendAdapter implements BackendAdapter {\n * async initSession(req: InitSessionRequest): Promise<InitSessionResponse> {\n * const response = await fetch('/api/qti/init', {\n * method: 'POST',\n * body: JSON.stringify(req)\n * });\n * return response.json();\n * }\n * // ... implement other methods\n * }\n * ```\n */\nexport interface BackendAdapter {\n\t/**\n\t * Initialize new assessment session\n\t */\n\tinitSession(request: InitSessionRequest): Promise<InitSessionResponse>;\n\n\t/**\n\t * Submit item responses for scoring\n\t */\n\tsubmitResponses(request: SubmitResponsesRequest): Promise<SubmitResponsesResponse>;\n\n\t/**\n\t * Save session state (auto-save during assessment)\n\t */\n\tsaveState(request: SaveAssessmentStateRequest): Promise<SaveAssessmentStateResponse>;\n\n\t/**\n\t * Finalize assessment and get results\n\t */\n\tfinalizeAssessment(request: FinalizeAssessmentRequest): Promise<FinalizeAssessmentResponse>;\n\n\t/**\n\t * Resume session (optional - can reuse initSession)\n\t */\n\tresumeSession?(sessionId: SessionId): Promise<InitSessionResponse>;\n\n\t/**\n\t * Query item bank for random item selection\n\t *\n\t * Security: Server validates access and returns items WITHOUT sensitive data\n\t */\n\tqueryItemBank?(request: QueryItemBankRequest): Promise<QueryItemBankResponse>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"api-contract.js","sourceRoot":"","sources":["../../src/integration/api-contract.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG","sourcesContent":["/**\n * QTI 2.2 Assessment Player - Backend Integration API Contract\n *\n * This file defines the secure API boundary between the client-side player\n * and backend services. The design prioritizes security by ensuring sensitive\n * data (correct answers, scoring rules) never reaches the client.\n *\n * ## Security Model\n *\n * - **Client-side**: Collects and submits candidate responses only\n * - **Server-side**: Stores QTI XML, performs scoring, validates submissions\n * - **Role-based**: Server controls what data client receives based on QTI role\n *\n * ## Reference Implementation\n *\n * See `ReferenceBackendAdapter.ts` for a simple localStorage-based implementation\n * that demonstrates the API contract without requiring a real backend.\n */\n\nimport type { QTIRole, ResolvedItemDeliveryContext, SerializedItemSessionState } from '@pie-qti/item-player';\n\n// ============================================================================\n// SESSION MANAGEMENT\n// ============================================================================\n\n/**\n * Unique identifier for an assessment session\n * Format: \"{assessmentId}:{candidateId}:{timestamp}\" or similar\n */\nexport type SessionId = string;\n\n/**\n * Initialize a new assessment session\n *\n * Security: Server validates candidate identity and assessment access\n */\nexport interface InitSessionRequest {\n\t/** Assessment identifier (QTI assessmentTest identifier) */\n\tassessmentId: string;\n\t/** Candidate identifier (from authentication system) */\n\tcandidateId: string;\n\t/** Optional: Resume from existing session */\n\tresumeSessionId?: SessionId;\n}\n\nexport interface InitSessionResponse {\n\t/** Unique session identifier for all subsequent requests */\n\tsessionId: SessionId;\n\t/** Assessment structure without sensitive data, as drawn for this session; a resume returns the same draw. */\n\tassessment: SecureAssessment;\n\t/** Restored state if resuming, undefined if new session */\n\trestoredState?: AssessmentSessionState;\n\t/**\n\t * Item delivery starts at in a new session: the first item whose preconditions hold. A resumed\n\t * session carries it in `restoredState`.\n\t */\n\tcurrentItemIdentifier?: string;\n\t/** Test-level outcome values of a resumed session, once outcome processing has run */\n\toutcomes?: TestOutcomeValues;\n\t/**\n\t * True when the stored session was already finalized: delivery is over and every\n\t * further submission would fail. Hosts (and the built-in shell) show a terminal\n\t * \"already submitted\" view instead of delivery UI and never offer the resume prompt.\n\t * `submit()` on such a player returns the stored results instead of failing.\n\t */\n\tfinalized?: boolean;\n\t/**\n\t * With `finalized`, the stored final result for the terminal view: the totals and,\n\t * when kept, the per-item scores. A backend may omit it; shells then render the\n\t * terminal view without scores.\n\t */\n\tfinalResults?: {\n\t\ttotalScore: number;\n\t\tmaxScore: number;\n\t\titemScores?: Record<string, AssessmentScoringResult>;\n\t\tfinalizedAt?: number;\n\t};\n}\n\n/**\n * A test-level outcome value: a scalar for single cardinality, an array for multiple and ordered,\n * an object for record, and `null` for NULL.\n */\nexport type TestOutcomeValue =\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| Array<string | number | boolean | null>\n\t| Record<string, unknown>;\n\n/** Test-level outcome values keyed by outcome identifier (e.g. \"PASS\", \"GRADE\"). */\nexport type TestOutcomeValues = Record<string, TestOutcomeValue>;\n\n/**\n * Structured, typed failure of test-level outcome processing.\n *\n * Delivery continues and candidate responses stay persisted; the error is carried on\n * the session/results so hosts can surface it (onError callback/event) instead of\n * SCORE/testFeedback silently never computing.\n */\nexport interface OutcomeProcessingError {\n\t/** Stable code — currently always `OUTCOME_PROCESSING_FAILED`. */\n\tcode: 'OUTCOME_PROCESSING_FAILED';\n\t/** Backend-side detail for logs and host callbacks; never shown verbatim to candidates. */\n\tmessage: string;\n}\n\n// ============================================================================\n// ASSESSMENT STRUCTURE (CLIENT-SAFE)\n// ============================================================================\n\n/**\n * Assessment structure safe for client consumption\n *\n * Security: NO correct answers, NO scoring rules, NO sensitive rubrics\n */\nexport interface TestFeedbackItem {\n\tidentifier: string;\n\t/** Outcome variable name to evaluate (e.g. \"PASS\", \"GRADE\") */\n\toutcomeIdentifier: string;\n\t/**\n\t * 'show' = show when the outcome matches identifier (equality for a single value, membership\n\t * for multiple and ordered); 'hide' = show when it does not\n\t */\n\tshowHide: 'show' | 'hide';\n\t/**\n\t * 'atEnd' = once the test (or, for test-part feedback, the part) has ended;\n\t * 'during' = whenever outcome processing has run\n\t */\n\taccess: 'atEnd' | 'during';\n\t/** HTML content to display */\n\tcontent: string;\n\t/**\n\t * The content's language: the feedback's `xml:lang`, else the test part's or the test's\n\t * (XML inheritance). Shells render it as the feedback's `lang` and `dir`.\n\t */\n\tlanguage?: string;\n}\n\nexport interface SecureTimeLimits {\n\t/** Minimum duration in seconds (optional) */\n\tminTime?: number;\n\t/** Maximum duration in seconds (optional) */\n\tmaxTime?: number;\n\tallowLateSubmission?: boolean;\n}\n\nexport interface SecureAssessment {\n\tidentifier: string;\n\ttitle: string;\n\t/** Navigation mode affects UI */\n\tnavigationMode: 'linear' | 'nonlinear';\n\t/** Submission mode affects when responses are finalized */\n\tsubmissionMode: 'individual' | 'simultaneous';\n\t/** Test parts contain sections */\n\ttestParts: SecureTestPart[];\n\t/** Overall time limit in seconds (optional) */\n\ttimeLimits?: SecureTimeLimits;\n\t/** QTI outcomeDeclarations for test-level variables */\n\toutcomeDeclarations?: Array<{\n\t\tidentifier: string;\n\t\tbaseType: string;\n\t\tcardinality: string;\n\t\tdefaultValue?: unknown;\n\t}>;\n\t/** Raw <outcomeProcessing> XML string, if present */\n\toutcomeProcessingXml?: string;\n\t/** Base URL/path for resolving relative hrefs (e.g. assessmentSectionRef) */\n\tbaseUrl?: string;\n\t/** QTI assessmentTest testFeedback blocks */\n\ttestFeedback?: TestFeedbackItem[];\n}\n\nexport interface SecureTestPart {\n\tidentifier: string;\n\t/** Navigation and submission modes are scoped to each QTI testPart. */\n\tnavigationMode?: 'linear' | 'nonlinear';\n\tsubmissionMode?: 'individual' | 'simultaneous';\n\t/** Sections contain items */\n\tsections: SecureSection[];\n\t/** TestPart-level time limit. */\n\ttimeLimits?: SecureTimeLimits;\n\t/** Candidate instructions (safe for display) */\n\trubricBlocks?: AssessmentRubricBlock[];\n\t/** QTI testPart testFeedback blocks */\n\ttestFeedback?: TestFeedbackItem[];\n\t/**\n\t * Item session control (QTI testPart/itemSessionControl). Each attribute cascades through every\n\t * enclosing section to the item ref; the backend enforces maxAttempts.\n\t */\n\titemSessionControl?: SecureItemSessionControl;\n\t/**\n\t * Serialized direct preCondition expressions, evaluated on entering the part (any navigation\n\t * mode): by the backend for the moves it decides (`nextItemIdentifier`), and by the player,\n\t * with the same rules, for a move without a backend decision (a jump into the next part, a\n\t * move on from a simultaneous part). A part whose precondition fails is skipped.\n\t */\n\tpreConditions?: string[];\n\t/** Branch rules evaluated after the part's last item (any navigation mode). */\n\tbranchRule?: SecureBranchRule[];\n}\n\nexport interface SecureSection {\n\tidentifier: string;\n\ttitle?: string;\n\trequired?: boolean;\n\tfixed?: boolean;\n\t/** Visible determines if section appears in navigation */\n\tvisible: boolean;\n\t/** Assessment item references, in the order the backend drew for this session. */\n\tassessmentItemRefs: SecureItemRef[];\n\t/** Nested QTI sections, retained instead of being flattened during XML ingestion. */\n\tsections?: SecureSection[];\n\t/**\n\t * Direct delivery components in document order. When present, this is the\n\t * authoritative order for mixed item/section children.\n\t */\n\tchildren?: SecureSectionComponent[];\n\t/** Section-level time limit */\n\ttimeLimits?: SecureTimeLimits;\n\t/** Candidate instructions (safe for display) */\n\trubricBlocks?: AssessmentRubricBlock[];\n\t/**\n\t * QTI selection: how many children to present from this section. Backends draw selection when\n\t * the session starts and return the drawn assessment without it; the client never draws.\n\t */\n\tselection?: {\n\t\t/** Number of items selected for this session */\n\t\tselect: number;\n\t\twithReplacement?: boolean;\n\t};\n\t/** QTI ordering: whether non-fixed children are shuffled. Backends apply it with selection. */\n\tordering?: {\n\t\tshuffle: boolean;\n\t};\n\t/**\n\t * Serialized direct preCondition expressions, evaluated on reaching the section in a linear\n\t * part (by the backend for its decisions, by the player with the same rules otherwise).\n\t */\n\tpreConditions?: string[];\n\t/** Branch rules the backend evaluates after the section's last item, in linear navigation. */\n\tbranchRule?: SecureBranchRule[];\n\t/**\n\t * QTI keepTogether, default true. An invisible section with keepTogether false has its children\n\t * mixed into the parent's ordering; the backend applies it while drawing.\n\t */\n\tkeepTogether?: boolean;\n\t/**\n\t * Item session control (QTI assessmentSection/itemSessionControl). Attributes set here override\n\t * the enclosing section's and test part's.\n\t */\n\titemSessionControl?: SecureItemSessionControl;\n}\n\n/** QTI itemSessionControl. Absent attributes inherit from the enclosing section or test part. */\nexport interface SecureItemSessionControl {\n\t/** Default 1; 0 means unlimited. Adaptive items are unlimited whatever the value. */\n\tmaxAttempts?: number;\n\tshowFeedback?: boolean;\n\tallowReview?: boolean;\n\tshowSolution?: boolean;\n\tallowComment?: boolean;\n\tallowSkipping?: boolean;\n\tvalidateResponses?: boolean;\n}\n\nexport interface SecureBranchRule {\n\t/** Identifier of the target item, section or test part, or EXIT_TEST, EXIT_TESTPART or EXIT_SECTION. */\n\ttarget: string;\n\t/** Serialised QTI expression XML (the child of <branchRule>). Absent means unconditional. */\n\tconditionXml?: string;\n}\n\nexport type SecureSectionComponent =\n\t| { type: 'item'; item: SecureItemRef }\n\t| { type: 'section'; section: SecureSection };\n\nexport interface SecureItemRef {\n\t/** Unique item identifier */\n\tidentifier: string;\n\t/** Item XML WITHOUT responseProcessing if role is 'candidate' */\n\titemXml: string;\n\t/** QTI role determines what's visible in itemXml */\n\trole: QTIRole;\n\t/** Required=true means item must be attempted */\n\trequired?: boolean;\n\tfixed?: boolean;\n\t/** Item-ref-level time limit. */\n\ttimeLimits?: SecureTimeLimits;\n\t/** Optional resolved QTI 3 delivery context. Additive; itemXml remains the compatibility path. */\n\tdeliveryContext?: ResolvedItemDeliveryContext;\n\t/**\n\t * QTI branchRule: ordered branch rules on this item. The backend evaluates them after scoring, in\n\t * linear navigation, and returns the resolved target as nextItemIdentifier. With no backend\n\t * decision for the move, the player applies them itself with the same rules.\n\t */\n\tbranchRule?: SecureBranchRule[];\n\t/**\n\t * Serialized direct preCondition expressions, evaluated on reaching the item in a linear part\n\t * (by the backend for its decisions, by the player with the same rules otherwise).\n\t */\n\tpreConditions?: string[];\n\t/** QTI item-ref weights, preserved for backend outcome processing. */\n\tweights?: Array<{ identifier: string; value: number }>;\n\t/** QTI item-ref categories, matched by includeCategory/excludeCategory in outcome processing. */\n\tcategories?: string[];\n\t/** Item session control (assessmentItemRef/itemSessionControl), the innermost cascade level. */\n\titemSessionControl?: SecureItemSessionControl;\n\t/** QTI variableMapping: item variables the test reads under another identifier. */\n\tvariableMappings?: Array<{ sourceIdentifier: string; targetIdentifier: string }>;\n\t/**\n\t * QTI templateDefault: serialized expressions, evaluated against test outcomes, that replace a\n\t * template variable's default before template processing.\n\t */\n\ttemplateDefaults?: Array<{ templateIdentifier: string; expressionXml: string }>;\n}\n\nexport interface AssessmentRubricBlock {\n\t/** Optional rubric identifier (QTI rubricBlock@identifier) */\n\tidentifier?: string;\n\t/** Rubric content (HTML) */\n\tcontent: string;\n\t/** View controls when rubric is shown */\n\t/** Authored QTI `view` tokens (arbitrary token lists, not just roles). */\n\tview: string[];\n\t/** Optional rubric use (QTI rubricBlock@use), e.g. \"passage\" */\n\tuse?: string;\n\t/**\n\t * The content's language: the block's `xml:lang`, else its nearest enclosing element's\n\t * (XML inheritance). Section layouts render it as the block's `lang`, `dir` and read-aloud voice.\n\t */\n\tlanguage?: string;\n}\n\n// ============================================================================\n// RESPONSE SUBMISSION\n// ============================================================================\n\n/**\n * Submit responses for scoring\n *\n * Security: Client sends responses only, server performs scoring\n */\nexport interface SubmitResponsesRequest {\n\tsessionId: SessionId;\n\t/** Item identifier */\n\titemIdentifier: string;\n\t/** Response data keyed by responseIdentifier */\n\tresponses: Record<string, ResponseValue>;\n\t/** Client timestamp for analytics */\n\tsubmittedAt: number;\n\t/** Time spent on item (ms) for analytics */\n\ttimeSpent?: number;\n\t/**\n\t * QTI endAttempt countAttempt (default true). False marks a hint / \"show me\" submission that\n\t * runs response processing without consuming an attempt: backends must not count it toward\n\t * maxAttempts and must not record it as the item's result — the candidate continues.\n\t */\n\tcountAttempt?: boolean;\n\t/** Optional client timing evidence; production backends remain authoritative. */\n\ttiming?: SubmitTimingEvidence;\n\t/**\n\t * Serialized item session used by backends to restore template/context variables while scoring.\n\t * Production backends should treat this as a client save format and validate against server-owned state.\n\t * Sent when the host enables `sendItemSessionToBackend`, and always to a backend that\n\t * declares `requiresItemSession` (the reference adapter does).\n\t */\n\titemSession?: SerializedItemSessionState;\n\t/** Candidate comment, accepted only when the item's allowComment is on. */\n\tcomment?: string;\n}\n\nexport interface SubmitTimingEvidence {\n\tscope: 'assessment' | 'testPart' | 'section' | 'item';\n\telapsedMs: number;\n\tlimitSeconds?: number;\n\texpired?: boolean;\n\tallowLateSubmission?: boolean;\n\t/**\n\t * The candidate's assessment clock in ms when the test has a maximum time. It runs\n\t * only while delivery runs: time behind an opt-in begin gate or a proctor pause is\n\t * excluded, unlike a wall clock measured from session creation.\n\t */\n\tassessmentElapsedMs?: number;\n\t/** The test's maximum time in seconds after PNP extended time, when it has one. */\n\tassessmentLimitSeconds?: number;\n\t/**\n\t * Why this submission runs: `candidate` (default) for a normal candidate action,\n\t * `time-expired` for the terminal response collection a hard time limit triggers\n\t * (the whole-test auto-submit, and the submit from an expiry dead end), `proctor` for\n\t * the collection a proctor's forced end of the test (`submit({ force: true })`) runs,\n\t * `unreachable` for a question the end of the test collects as it stands although its\n\t * QTI `allowSkipping` / `validateResponses` control would refuse it, because the\n\t * candidate can no longer reach it (its test part was left — a session restored from\n\t * before the part-leave gate, a branch rule).\n\t * Backends must accept a `time-expired` submission whose scope expired: the delivery\n\t * window closed with the expiry, and collecting the pending responses is the mandated\n\t * terminal step. A `proctor` collection is an administrative end of the test, made\n\t * during a pause or ahead of the candidate's own submit; record it as such (it\n\t * bypasses the candidate-side skipping and validation controls). Record an\n\t * `unreachable` one as skipped (or incomplete) as it stands, never as a normal\n\t * candidate submission.\n\t */\n\tsubmissionReason?: 'candidate' | 'time-expired' | 'proctor' | 'unreachable';\n}\n\n/**\n * Response value can be string, string[], or complex types\n */\nexport type ResponseValue = string | string[] | Record<string, any>;\n\nexport interface SubmitResponsesResponse {\n\t/** Was submission accepted? */\n\tsuccess: boolean;\n\t/** Scoring result (if submission mode allows immediate scoring) */\n\tresult?: AssessmentScoringResult;\n\t/**\n\t * Backend-authoritative next item (branching/navigation decision): the item the test's branch\n\t * rules and preconditions deliver after this submission, or `EXIT_TEST` / `EXIT_TESTPART` /\n\t * `EXIT_SECTION`. The player follows it on the candidate's move; a submission that stays on the\n\t * item (a practice check, a counted endAttemptInteraction) keeps it, and the candidate's next\n\t * move on from the item that submits nothing follows it. If omitted, the player moves to the\n\t * next item the delivery rules make eligible, evaluating the test's branch rules and\n\t * preconditions itself with the reference rules (for a test without any: the adjacent item).\n\t */\n\tnextItemIdentifier?: string;\n\t/**\n\t * Backend-authoritative session state snapshot after applying the submission.\n\t * If provided, client should replace its local state with this.\n\t */\n\tupdatedState?: AssessmentSessionState;\n\t/** Test-level outcome values after the outcome processing this submission triggers */\n\toutcomes?: TestOutcomeValues;\n\t/** Set when test-level outcome processing failed; responses are still accepted and persisted. */\n\toutcomeProcessingError?: OutcomeProcessingError;\n\t/** Error message if success=false */\n\terror?: string;\n}\n\n// ============================================================================\n// SCORING RESULTS\n// ============================================================================\n\n/**\n * Structured, typed failure of one item's response processing.\n *\n * Mirrors `OutcomeProcessingError`: the submission is still accepted and delivery\n * continues, but the item's score is a degenerate 0 (its declared maximum where known)\n * and hosts must be able to tell \"answered wrong\" from \"the engine failed to score\".\n */\nexport interface ItemScoringError {\n\t/** Stable code — currently always `ITEM_SCORING_FAILED`. */\n\tcode: 'ITEM_SCORING_FAILED';\n\t/** Engine-side detail for logs and host callbacks; never shown verbatim to candidates. */\n\tmessage: string;\n}\n\n/**\n * Scoring result returned from server\n *\n * Security: Server computes this, client never sees scoring rules\n */\nexport interface AssessmentScoringResult {\n\t/** Item identifier */\n\titemIdentifier: string;\n\t/** Normalized score 0.0-1.0 */\n\tscore: number;\n\t/** Maximum possible score (usually 1.0) */\n\tmaxScore: number;\n\t/** Was item completed? */\n\tcompleted: boolean;\n\t/** QTI outcome variables */\n\toutcomeValues: Record<string, any>;\n\t/** Feedback to display (role-dependent) */\n\tfeedback?: FeedbackItem[];\n\t/** Correct response (only if role allows) */\n\tcorrectResponse?: Record<string, ResponseValue>;\n\t/**\n\t * Set when response processing for this item failed: the score is a degenerate 0\n\t * (the declared maximum where known), NOT a candidate's wrong answer.\n\t */\n\tscoringError?: ItemScoringError;\n}\n\nexport interface FeedbackItem {\n\t/** Feedback content (HTML) */\n\tcontent: string;\n\t/** Feedback type */\n\ttype: 'correct' | 'incorrect' | 'hint' | 'solution';\n}\n\n// ============================================================================\n// STATE PERSISTENCE\n// ============================================================================\n\n/**\n * Save assessment state\n *\n * Security: State includes responses but not scores (until finalized)\n */\nexport interface SaveAssessmentStateRequest {\n\tsessionId: SessionId;\n\tstate: AssessmentSessionState;\n}\n\nexport interface SaveAssessmentStateResponse {\n\tsuccess: boolean;\n\t/** Server timestamp of save */\n\tsavedAt: number;\n}\n\nexport interface AssessmentSessionState {\n\t/** Current item identifier */\n\tcurrentItemIdentifier: string;\n\t/** Visited items (for navigation) */\n\tvisitedItems: string[];\n\t/** Submitted responses per item */\n\titemResponses: Record<string, Record<string, ResponseValue>>;\n\t/** Scoring results per item (populated after submission) */\n\titemScores?: Record<string, AssessmentScoringResult>;\n\t/** ItemSession lifecycle hints per item, used to restore attempt/review UI state */\n\titemSessionStates?: Record<string, AssessmentItemSessionState>;\n\t/** Rich QTI item session snapshots, used to restore variables and score saved sessions. */\n\titemSessions?: Record<string, SerializedItemSessionState>;\n\t/** Candidate comments per item, captured where allowComment is on. */\n\titemComments?: Record<string, string>;\n\t/** Items the candidate flagged for review, keyed by item identifier. */\n\titemFlags?: Record<string, boolean>;\n\t/**\n\t * The backend's branch decision (`nextItemIdentifier`) kept per item with its\n\t * last-submission record: item identifier → target (an item, section or test part\n\t * identifier, or EXIT_TEST). Only the freshest counted submission's decision is kept —\n\t * any later counted submission replaces it — and delivery follows it on the next\n\t * forward step from that item that submits nothing, so a restored session lands\n\t * identically to the live one. (Session format addition; backends that never store it\n\t * just lose the kept decision across a resume.)\n\t */\n\tbranchDecisions?: Record<string, string>;\n\t/**\n\t * The test-level outcome values the backend last returned (its outcome processing's\n\t * result, or undefined before the first submission): branch and preCondition rules read\n\t * them, so a restored session navigates identically to the live one. (Session format\n\t * addition; backends that never store it just lose the values across a resume, and the\n\t * restored rules evaluate on missing outcomes.)\n\t */\n\ttestOutcomes?: TestOutcomeValues;\n\t/** Whether the candidate chose to hide the countdown timer (a persisted shell preference). */\n\ttimerHidden?: boolean;\n\t/** Time tracking */\n\ttiming: {\n\t\t/** Session start time */\n\t\tstartedAt: number;\n\t\t/** Time spent per item (ms) */\n\t\titemTimes: Record<string, number>;\n\t\t/** Time spent per assessment section (ms). */\n\t\tsectionTimes?: Record<string, number>;\n\t\t/** Time spent per testPart (ms). */\n\t\ttestPartTimes?: Record<string, number>;\n\t\t/** Total elapsed time (ms) */\n\t\ttotalTime: number;\n\t\t/** Active scope identifiers retained for save/resume timing continuity. */\n\t\tcurrentItemIdentifier?: string;\n\t\tcurrentSectionIdentifier?: string;\n\t\tcurrentTestPartIdentifier?: string;\n\t\t/**\n\t\t * A proctor pause was in force when the state was saved: a restored session\n\t\t * reopens paused, its clocks frozen, until the host resumes it.\n\t\t */\n\t\tisPaused?: boolean;\n\t\t/** The candidate-facing reason the proctor gave for the pause. */\n\t\tpauseReason?: string;\n\t\t/**\n\t\t * Client clock (ms) of the last autosave persisted into this snapshot. Shells\n\t\t * show it on the resume prompt (\"You have answers saved from {time}\").\n\t\t */\n\t\tsavedAt?: number;\n\t};\n}\n\nexport interface AssessmentItemSessionState {\n\titemIdentifier: string;\n\tattemptCount: number;\n\tisAnswered: boolean;\n\tisSubmitted: boolean;\n\tlastSubmissionTime?: number;\n}\n\n// ============================================================================\n// FINALIZE ASSESSMENT\n// ============================================================================\n\n/**\n * Finalize assessment and get full results\n *\n * Security: Server computes final scores, applies late penalties, etc.\n */\nexport interface FinalizeAssessmentRequest {\n\tsessionId: SessionId;\n}\n\nexport interface FinalizeAssessmentResponse {\n\tsuccess: boolean;\n\t/** Overall assessment score */\n\ttotalScore: number;\n\t/** Maximum possible score */\n\tmaxScore: number;\n\t/** Per-item results */\n\titemScores: Record<string, AssessmentScoringResult>;\n\t/** Test-level outcome values after outcomeProcessing; testFeedback visibility reads them. */\n\toutcomes?: TestOutcomeValues;\n\t/** Set when test-level outcome processing failed; item results are still returned. */\n\toutcomeProcessingError?: OutcomeProcessingError;\n\t/** Server timestamp */\n\tfinalizedAt: number;\n}\n\n// ============================================================================\n// ITEM BANK QUERIES\n// ============================================================================\n\n/**\n * Request items from an item bank for random selection\n *\n * Security: Server validates candidate access to bank\n */\nexport interface QueryItemBankRequest {\n\t/** Unique session identifier */\n\tsessionId: SessionId;\n\t/** Item bank identifier (from selection/@fromBank attribute) */\n\tbankId: string;\n\t/** Number of items to select */\n\tcount: number;\n\t/** Whether to allow selecting same item multiple times */\n\twithReplacement?: boolean;\n\t/** Optional filtering criteria (difficulty, topic, etc.) */\n\tfilters?: {\n\t\tdifficulty?: 'easy' | 'medium' | 'hard';\n\t\ttopics?: string[];\n\t\t[key: string]: unknown;\n\t};\n}\n\n/**\n * Items selected from item bank\n *\n * Security: Returns items WITHOUT correct answers or scoring rules\n */\nexport interface QueryItemBankResponse {\n\t/** Selected item references (client-safe) */\n\titems: SecureItemRef[];\n\t/** Server timestamp */\n\tselectedAt: number;\n}\n\n// ============================================================================\n// BACKEND ADAPTER INTERFACE\n// ============================================================================\n\n/**\n * Backend adapter interface - implement this for your backend\n *\n * @example\n * ```typescript\n * class MyBackendAdapter implements BackendAdapter {\n * async initSession(req: InitSessionRequest): Promise<InitSessionResponse> {\n * const response = await fetch('/api/qti/init', {\n * method: 'POST',\n * body: JSON.stringify(req)\n * });\n * return response.json();\n * }\n * // ... implement other methods\n * }\n * ```\n */\nexport interface BackendAdapter {\n\t/**\n\t * Initialize new assessment session\n\t */\n\tinitSession(request: InitSessionRequest): Promise<InitSessionResponse>;\n\n\t/**\n\t * Submit item responses for scoring\n\t */\n\tsubmitResponses(request: SubmitResponsesRequest): Promise<SubmitResponsesResponse>;\n\n\t/**\n\t * Save session state (auto-save during assessment)\n\t */\n\tsaveState(request: SaveAssessmentStateRequest): Promise<SaveAssessmentStateResponse>;\n\n\t/**\n\t * Whether this adapter persists candidate drafts through `saveState`. Autosave is\n\t * ON by default whenever the backend reports the capability (default `true`, so\n\t * adapters that implement `saveState` get autosave without extra wiring); set\n\t * `canSaveState: false` when the backend cannot store drafts or the host saves\n\t * state itself and wants the shell's autosave and its save indicator off.\n\t */\n\tcanSaveState?: boolean;\n\n\t/**\n\t * Whether this backend scores from the candidate's serialized item session\n\t * (`SubmitResponsesRequest.itemSession`) and therefore must always receive it: a\n\t * templated item's instance (the key the candidate saw) and an adaptive item's\n\t * accumulated outcomes live there. When true the player sends it on every submission,\n\t * whatever `sendItemSessionToBackend` says. `ReferenceBackendAdapter` sets it; a\n\t * production backend that owns the item session server-side leaves it unset.\n\t */\n\trequiresItemSession?: boolean;\n\n\t/**\n\t * Finalize assessment and get results\n\t */\n\tfinalizeAssessment(request: FinalizeAssessmentRequest): Promise<FinalizeAssessmentResponse>;\n\n\t/**\n\t * Resume session (optional - can reuse initSession)\n\t */\n\tresumeSession?(sessionId: SessionId): Promise<InitSessionResponse>;\n\n\t/**\n\t * Query item bank for random item selection\n\t *\n\t * Security: Server validates access and returns items WITHOUT sensitive data\n\t */\n\tqueryItemBank?(request: QueryItemBankRequest): Promise<QueryItemBankResponse>;\n}\n"]}
|
|
@@ -1,23 +1,74 @@
|
|
|
1
1
|
import { type SerializedItemSessionState } from '@pie-qti/item-player';
|
|
2
|
-
import { type TestItemState } from '@pie-qti/qti-processing';
|
|
2
|
+
import { type StringComparisonOptions, type TestItemState } from '@pie-qti/qti-processing';
|
|
3
3
|
import type { AssessmentScoringResult, ResponseValue } from './api-contract.js';
|
|
4
4
|
export interface AssessmentItemScoringInput {
|
|
5
5
|
itemXml: string;
|
|
6
6
|
responses: Record<string, ResponseValue>;
|
|
7
|
+
/**
|
|
8
|
+
* The candidate's serialized item session for this submission. Required for a templated
|
|
9
|
+
* item (template processing drew the instance the candidate saw) and for an adaptive item
|
|
10
|
+
* (its outcomes accumulate across attempts): the scorer restores it instead of
|
|
11
|
+
* re-templating, and takes an adaptive item's outcomes as submitted.
|
|
12
|
+
*/
|
|
7
13
|
itemSession?: SerializedItemSessionState;
|
|
14
|
+
/**
|
|
15
|
+
* Force the item-session requirement on (an assessmentItemRef `templateDefault` sets
|
|
16
|
+
* template values the item XML alone does not show).
|
|
17
|
+
*/
|
|
18
|
+
requireItemSession?: boolean;
|
|
19
|
+
/**
|
|
20
|
+
* String comparison folds beyond QTI's equality, as the delivery's input needs them; see the
|
|
21
|
+
* item player's `AssessmentItemDefinitionConfig.stringComparison`. Exact when absent.
|
|
22
|
+
*/
|
|
23
|
+
stringComparison?: StringComparisonOptions;
|
|
8
24
|
}
|
|
25
|
+
/** Why the reference scorer refused to score a submission. */
|
|
26
|
+
export type AssessmentItemScoringErrorCode = 'itemSessionRequired';
|
|
27
|
+
/**
|
|
28
|
+
* A submission the scorer must not score: a templated or adaptive item without the
|
|
29
|
+
* candidate's item session (scoring its responses alone would re-run template processing
|
|
30
|
+
* against a different instance, or lose an adaptive item's accumulated outcomes).
|
|
31
|
+
*/
|
|
32
|
+
export declare class AssessmentItemScoringError extends Error {
|
|
33
|
+
readonly code: AssessmentItemScoringErrorCode;
|
|
34
|
+
readonly itemIdentifier: string;
|
|
35
|
+
constructor(code: AssessmentItemScoringErrorCode, itemIdentifier: string, message: string);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Whether scoring the item needs the candidate's item session: template processing draws
|
|
39
|
+
* a per-session instance (the key the candidate saw), and an adaptive item's outcomes
|
|
40
|
+
* accumulate across its attempts.
|
|
41
|
+
*/
|
|
42
|
+
export declare function itemScoringRequiresSession(itemXml: string): boolean;
|
|
9
43
|
export declare function getAssessmentItemIdentifier(itemXml: string): string;
|
|
10
44
|
/** The item-derived part of a test-level TestItemState; the backend adds the item-ref context. */
|
|
11
45
|
export type ItemTestState = Pick<TestItemState, 'variables' | 'outcomeBounds' | 'responded' | 'correct'>;
|
|
12
46
|
/**
|
|
13
47
|
* Runs QTI ResponseProcessing for one AssessmentItem and normalizes the result
|
|
14
|
-
* to the BackendAdapter scoring shape used by AssessmentPlayer.
|
|
48
|
+
* to the BackendAdapter scoring shape used by AssessmentPlayer. Throws an
|
|
49
|
+
* `AssessmentItemScoringError` (`itemSessionRequired`) for a templated or adaptive item
|
|
50
|
+
* that arrives without the candidate's item session.
|
|
15
51
|
*/
|
|
16
52
|
export declare function scoreAssessmentItem(input: AssessmentItemScoringInput): AssessmentScoringResult;
|
|
17
|
-
/**
|
|
18
|
-
|
|
53
|
+
/**
|
|
54
|
+
* Scores one item and snapshots the variables and flags test-level outcome processing reads.
|
|
55
|
+
*
|
|
56
|
+
* With the candidate's item session the scorer restores it — the template instance the
|
|
57
|
+
* candidate saw, never a fresh draw — and re-runs response processing on it; an adaptive
|
|
58
|
+
* item's outcomes are taken as submitted (they accumulate across attempts, so running
|
|
59
|
+
* response processing again would apply the attempt twice or reset what earlier attempts
|
|
60
|
+
* accumulated). Without a session only a non-templated, non-adaptive item is scored.
|
|
61
|
+
*
|
|
62
|
+
* When response processing fails the item scores 0 (its declared maximum where the item
|
|
63
|
+
* declares one, else 1), and its test state holds no variables: the item still counts as
|
|
64
|
+
* presented, and as responded when the candidate gave any response. The failure is carried
|
|
65
|
+
* on the result as `scoringError` — mirroring the test-level `outcomeProcessingError` — so
|
|
66
|
+
* hosts can tell "answered wrong" from "the engine failed to score"; it never fails the
|
|
67
|
+
* submission.
|
|
68
|
+
*/
|
|
69
|
+
export declare function scoreAssessmentItemForTest({ itemXml, responses, itemSession, requireItemSession, stringComparison, }: AssessmentItemScoringInput): {
|
|
19
70
|
result: AssessmentScoringResult;
|
|
20
|
-
testState
|
|
71
|
+
testState: ItemTestState;
|
|
21
72
|
};
|
|
22
73
|
/** Variables of an item nobody has attempted: declared defaults, with no response processing run. */
|
|
23
74
|
export declare function defaultItemTestState(itemXml: string): ItemTestState | undefined;
|