@pie-qti/assessment-player 1.0.0-beta.5 → 1.0.0-beta.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/AssessmentPlayer.js +12 -16
- package/dist/core/AssessmentPlayer.js.map +1 -1
- package/dist/core/navigationPolicy.d.ts +1 -5
- package/dist/core/navigationPolicy.js +4 -8
- package/dist/core/navigationPolicy.js.map +1 -1
- package/dist/core/submissionPolicy.d.ts +0 -3
- package/dist/core/submissionPolicy.js +0 -4
- package/dist/core/submissionPolicy.js.map +1 -1
- package/dist/core/templateDefaults.js +1 -2
- package/dist/core/templateDefaults.js.map +1 -1
- package/dist/core/testStructure.d.ts +2 -2
- package/dist/core/testStructure.js +7 -10
- package/dist/core/testStructure.js.map +1 -1
- package/dist/integration/ReferenceBackendAdapter.js +4 -4
- package/dist/integration/ReferenceBackendAdapter.js.map +1 -1
- package/dist/integration/api-contract.d.ts +4 -7
- package/dist/integration/api-contract.js.map +1 -1
- package/dist/integration/qti-test-parser.js +0 -29
- package/dist/integration/qti-test-parser.js.map +1 -1
- package/package.json +17 -17
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ReferenceBackendAdapter.js","sourceRoot":"","sources":["../../src/integration/ReferenceBackendAdapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AAEH,OAAO,EACN,yBAAyB,EACzB,kBAAkB,EAElB,WAAW,EACX,QAAQ,EAGR,QAAQ,GAGR,MAAM,yBAAyB,CAAC;AAiCjC,OAAO,EACN,2BAA2B,EAC3B,4BAA4B,EAC5B,qBAAqB,EAErB,cAAc,EACd,cAAc,EACd,oBAAoB,EACpB,yBAAyB,EAEzB,uBAAuB,GAEvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EACN,iBAAiB,EACjB,kBA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AAS,EAAE,IAAI,CAAC,gBAAgB,CAAC,CAAC,CAAC;YAClF,OAAO;gBACN,UAAU,EAAE,IAAI,CAAC,UAAU;gBAC3B,kBAAkB;gBAClB,UAAU,EAAE,IAAI,CAAC,UAAU;gBAC3B,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS;gBACxG,SAAS;gBACT,aAAa,EAAE,SAAS,EAAE,aAAa,IAAI,oBAAoB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,aAAa;gBAC5F,SAAS;gBACT,SAAS,EAAE,SAAS,IAAI,SAAS,EAAE,SAAS,KAAK,IAAI;gBACrD,OAAO,EAAE,SAAS,IAAI,SAAS,EAAE,OAAO,KAAK,IAAI;gBACjD,SAAS,EAAE,SAAS,IAAI,SAAS,EAAE,OAAO,KAAK,KAAK;gBACpD,QAAQ,EAAE,IAAI;aACd,CAAC;QACH,CAAC,CAAC,CAAC;IACJ,CAAC;;AAppBD,sEAAsE;AAC/D,8CAAsB,GAAG,sBAAsB,AAAzB,CAA0B","sourcesContent":["/**\n * Reference Backend Adapter - localStorage Implementation\n *\n * This is a REFERENCE IMPLEMENTATION demonstrating the BackendAdapter contract.\n * It uses localStorage for persistence and performs scoring CLIENT-SIDE.\n *\n * ## Security Warning\n *\n * This implementation is INSECURE for production use because:\n * - Scoring is done client-side (can be manipulated)\n * - QTI XML with correct answers is stored in client\n * - No authentication or authorization checks\n *\n * ## Purpose\n *\n * This adapter serves as:\n * 1. Reference implementation showing the API contract\n * 2. Development/demo tool for offline testing\n * 3. Template for building secure backend adapters\n *\n * ## Production Use\n *\n * Replace this with a real backend adapter that:\n * - Stores QTI XML server-side\n * - Performs scoring server-side\n * - Validates all requests with authentication\n * - Filters sensitive data based on role\n *\n * ## Persistence failure semantics\n *\n * A localStorage write that does not land (quota exceeded, private-mode eviction) means\n * the operation did not complete, and every backend method reports it honestly:\n * `saveState` returns `success: false` (the autosave engine shows `failed`, retries with\n * backoff and reports onError), `submitResponses` returns `success: false` (the player\n * restores the pre-submit state and throws its coded `submitFailed` — accepting the\n * submission anyway would silently lose the answer on the next resume), and\n * `finalizeAssessment` returns `success: false` (the `finalized` flag never persisted, so\n * reporting a completion would resurrect the test on resume; the player throws its coded\n * `finalizeFailed` and the test stays open for a retry). The initial session write and\n * the outcome-processing-error bookkeeping are the only best-effort writes: their response\n * shapes carry no failure, and a lost init write merely leaves a fresh session without a\n * resumable draft — which the very next save reports through the paths above.\n */\n\nimport {\n\tbuildOutcomeProcessingAst,\n\tDeclarationContext,\n\ttype DeclarationMap,\n\texecProgram,\n\tparseXml,\n\tserializeXml,\n\ttype QtiValue,\n\tqtiValue,\n\ttype StringComparisonOptions,\n\ttype TestItemState,\n} from '@pie-qti/qti-processing';\nimport {\n\tcreateResolvedItemDeliveryContext,\n\textractAssessmentStimulusRefs,\n\textractProcessingIncludeRefs,\n\textractQtiStylesheets,\n\tparseAssessmentStimulusXml,\n\tresolveCheckedPackagePath,\n\tresolveCheckedPackagePathFromFile,\n} from '@pie-qti/ims-cp-core';\nimport type {\n\tAssessmentSessionState,\n\tBackendAdapter,\n\tFinalizeAssessmentRequest,\n\tFinalizeAssessmentResponse,\n\tInitSessionRequest,\n\tInitSessionResponse,\n\tOutcomeProcessingError,\n\tSaveAssessmentStateRequest,\n\tSaveAssessmentStateResponse,\n\tSecureAssessment,\n\tSecureBranchRule,\n\tSecureItemRef,\n\tSecureItemSessionControl,\n\tSecureSection,\n\tSecureTestPart,\n\tSessionId,\n\tSubmitResponsesRequest,\n\tSubmitResponsesResponse,\n\tTestFeedbackItem,\n\tTestOutcomeValue,\n\tTestOutcomeValues,\n} from './api-contract.js';\nimport {\n\taddItemVariableDeclarations,\n\taddScopeDurationDeclarations,\n\tapplyVariableMappings,\n\ttype DeliveredItem,\n\tdeliveredItems,\n\tdrawAssessment,\n\tqtiElementNameMapper,\n\tresolveItemSessionControl,\n\tshuffleArray,\n\ttestOutcomeDeclarations,\n\ttoCanonicalQtiName,\n} from '../core/testStructure.js';\nimport { parseAssessmentTestXml } from './qti-test-parser.js';\nimport {\n\tfirstEligibleItem,\n\tgetItemRefsInOrder,\n\tnavigationDeclarations,\n\tnextItemIdentifier,\n} from './test-navigation.js';\nimport {\n\tgenerateSessionId,\n\tfindLatestSession,\n\tloadSession,\n\tsaveSession,\n\ttype StoredSession,\n} from './session-store.js';\nimport {\n\tAssessmentItemScoringError,\n\tdefaultItemTestState,\n\tscoreAssessmentItemForTest,\n} from './assessment-item-scorer.js';\n\n/**\n * Reference Backend Adapter using localStorage\n *\n * @example\n * ```typescript\n * const adapter = new ReferenceBackendAdapter();\n * const response = await adapter.initSession({\n * assessmentId: 'test-001',\n * candidateId: 'student-123'\n * });\n * ```\n */\nexport interface ReferenceBackendAdapterOptions {\n\t/** RNG for the session-start draw of selection and ordering. Defaults to Math.random. */\n\trng?: () => number;\n\t/**\n\t * String comparison folds the scorer applies beyond QTI's equality, as the delivery's input\n\t * needs them (see the item player's `AssessmentItemDefinitionConfig.stringComparison`). Set\n\t * the same value as the player's `stringComparison`. Exact when absent.\n\t */\n\tstringComparison?: StringComparisonOptions;\n}\n\nexport class ReferenceBackendAdapter implements BackendAdapter {\n\t/** @see ./qti-test-parser.ts — the parser lives in its own module. */\n\tstatic parseAssessmentTestXml = parseAssessmentTestXml;\n\t/**\n\t * The adapter persists drafts: sessions live in localStorage and `saveState` writes\n\t * the candidate's snapshot into them, so shell autosave is ON by default.\n\t */\n\treadonly canSaveState = true;\n\t/**\n\t * The adapter scores from the candidate's serialized item session: a templated item is\n\t * scored against the instance the candidate saw (never a fresh template draw), and an\n\t * adaptive item's accumulated outcomes are taken as submitted. The player therefore\n\t * always sends it (reference mode); a templated or adaptive item without one is refused.\n\t */\n\treadonly requiresItemSession = true;\n\tprivate registeredAssessments: Map<string, SecureAssessment> = new Map();\n\tprivate readonly rng: () => number;\n\tprivate readonly stringComparison: StringComparisonOptions | undefined;\n\n\tconstructor(options: ReferenceBackendAdapterOptions = {}) {\n\t\tthis.rng = options.rng ?? Math.random;\n\t\tthis.stringComparison = options.stringComparison ? Object.freeze({ ...options.stringComparison }) : undefined;\n\t}\n\n\t/**\n\t * Register/override a client-provided assessment structure for a given assessmentId.\n\t *\n\t * This is useful for demos or web-components that supply assessment XML directly.\n\t * Security: this remains a reference/demo adapter; production backends should not\n\t * accept client-authored assessments.\n\t */\n\tpublic registerAssessment(assessmentId: string, assessment: SecureAssessment) {\n\t\tthis.registeredAssessments.set(assessmentId, assessment);\n\t}\n\n\tprivate getAssessment(assessmentId: string): SecureAssessment {\n\t\treturn this.registeredAssessments.get(assessmentId) ?? this.createDemoAssessment(assessmentId);\n\t}\n\n\t/**\n\t * Initialize a new assessment session\n\t */\n\tasync initSession(request: InitSessionRequest): Promise<InitSessionResponse> {\n\t\t// Check if resuming existing session\n\t\t\tif (request.resumeSessionId) {\n\t\t\t\tconst stored = loadSession(request.resumeSessionId);\n\t\t\t\tif (stored) {\n\t\t\t\t\t// A finalized session has no resumable draft: restore terminal (the\n\t\t\t\t\t// stored final totals, no restoredState), so hosts show the\n\t\t\t\t\t// already-submitted view instead of delivery whose every submit fails.\n\t\t\t\t\tif (stored.finalized) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tsessionId: stored.sessionId,\n\t\t\t\t\t\t\tassessment: stored.assessment,\n\t\t\t\t\t\t\tfinalized: true,\n\t\t\t\t\t\t\tfinalResults: this.storedFinalResults(stored),\n\t\t\t\t\t\t\toutcomes: this.currentOutcomes(stored).outcomes,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsessionId: stored.sessionId,\n\t\t\t\t\t\tassessment: stored.assessment,\n\t\t\t\t\t\trestoredState: stored.state,\n\t\t\t\t\t\toutcomes: this.currentOutcomes(stored).outcomes,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t// Create new session\n\t\tconst sessionId = generateSessionId(request.assessmentId, request.candidateId);\n\n\t\t// In a real backend, you would:\n\t\t// 1. Fetch assessment from database\n\t\t// 2. Filter QTI XML based on role\n\t\t// 3. Remove responseProcessing for candidates\n\t\t//\n\t\t// For reference implementation, we'll use demo data. Selection and ordering are drawn once\n\t\t// here; the stored draw is what a resume returns.\n\t\tconst assessment = drawAssessment(this.getAssessment(request.assessmentId), this.rng);\n\t\tconst firstItemIdentifier =\n\t\t\tfirstEligibleItem(assessment, deliveredItems(assessment), 0, undefined, testOutcomeDeclarations(assessment), this.rng) ?? '';\n\n\t\tconst state: AssessmentSessionState = {\n\t\t\tcurrentItemIdentifier: firstItemIdentifier,\n\t\t\tvisitedItems: [],\n\t\t\titemResponses: {},\n\t\t\titemScores: {},\n\t\t\titemSessions: {},\n\t\t\ttiming: {\n\t\t\t\tstartedAt: Date.now(),\n\t\t\t\titemTimes: {},\n\t\t\t\ttotalTime: 0,\n\t\t\t},\n\t\t};\n\n\t\tconst session: StoredSession = {\n\t\t\tsessionId,\n\t\t\tassessmentId: request.assessmentId,\n\t\t\tcandidateId: request.candidateId,\n\t\t\tassessment,\n\t\t\tstate,\n\t\t\tcreatedAt: Date.now(),\n\t\t\tfinalized: false,\n\t\t};\n\n\t\tsaveSession(session);\n\n\t\treturn {\n\t\t\tsessionId,\n\t\t\tassessment,\n\t\t\tcurrentItemIdentifier: firstItemIdentifier || undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Submit responses and get scoring result\n\t */\n\tasync submitResponses(request: SubmitResponsesRequest): Promise<SubmitResponsesResponse> {\n\t\tconst session = loadSession(request.sessionId);\n\t\tif (!session) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Session not found',\n\t\t\t};\n\t\t}\n\n\t\tif (session.finalized) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Session already finalized',\n\t\t\t};\n\t\t}\n\n\t\tconst receivedAt = Date.now();\n\t\tconst assessmentLimit = session.assessment.timeLimits;\n\t\tconst effectiveAssessmentLimitSeconds =\n\t\t\trequest.timing?.scope === 'assessment' && request.timing.limitSeconds !== undefined\n\t\t\t\t? request.timing.limitSeconds\n\t\t\t\t: assessmentLimit?.maxTime;\n\t\t// The candidate's own test clock (gates and pauses excluded) when the client\n\t\t// reports it; otherwise the session wall clock, which a production backend owns.\n\t\tconst assessmentElapsedSeconds =\n\t\t\trequest.timing?.assessmentElapsedMs !== undefined\n\t\t\t\t? request.timing.assessmentElapsedMs / 1000\n\t\t\t\t: (receivedAt - session.createdAt) / 1000;\n\t\tconst assessmentAllowsLate = assessmentLimit?.allowLateSubmission ?? request.timing?.allowLateSubmission;\n\t\t// A `time-expired` submission is the terminal collection a hard limit triggers:\n\t\t// the window closed with the expiry, and the pending responses must be accepted.\n\t\t// A `proctor` collection is the administrative end of the test, accepted alike, and\n\t\t// so is an `unreachable` one (a question the candidate can no longer reach,\n\t\t// collected as it stands at the end of the test).\n\t\tconst timeExpiredCollection =\n\t\t\trequest.timing?.submissionReason === 'time-expired' ||\n\t\t\trequest.timing?.submissionReason === 'proctor' ||\n\t\t\trequest.timing?.submissionReason === 'unreachable';\n\t\tif (\n\t\t\t!timeExpiredCollection &&\n\t\t\teffectiveAssessmentLimitSeconds !== undefined &&\n\t\t\tassessmentAllowsLate !== true &&\n\t\t\tassessmentElapsedSeconds > effectiveAssessmentLimitSeconds\n\t\t) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Assessment time limit expired',\n\t\t\t};\n\t\t}\n\n\t\tconst evidenceExpired =\n\t\t\trequest.timing?.limitSeconds !== undefined &&\n\t\t\trequest.timing.elapsedMs >= request.timing.limitSeconds * 1000;\n\t\tif (!timeExpiredCollection && evidenceExpired && request.timing?.allowLateSubmission !== true) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Time limit expired',\n\t\t\t};\n\t\t}\n\n\t\tconst delivered = deliveredItems(session.assessment);\n\t\tconst index = delivered.findIndex((d) => d.item.identifier === request.itemIdentifier);\n\t\tconst current = delivered[index];\n\t\tif (!current) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Item not found',\n\t\t\t};\n\t\t}\n\t\tconst itemXml = current.item.itemXml;\n\t\tconst control = resolveItemSessionControl(current.testPart, current.sections, current.item);\n\t\tconst previousItemSession = session.state.itemSessionStates?.[request.itemIdentifier];\n\t\t// A QTI endAttempt countAttempt=false submission (a hint request) runs response processing\n\t\t// without consuming an attempt, so the attempt limit does not apply to it.\n\t\tconst countAttempt = request.countAttempt ?? true;\n\t\tif (countAttempt && control.maxAttempts > 0 && (previousItemSession?.attemptCount ?? 0) >= control.maxAttempts) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Maximum attempts reached',\n\t\t\t};\n\t\t}\n\t\tif (request.comment !== undefined && !control.allowComment) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Comments are not allowed for this item',\n\t\t\t};\n\t\t}\n\n\t\t// **SECURITY WARNING**: Client-side scoring is INSECURE\n\t\t// In production, this MUST be done server-side\n\t\t// A templated (or adaptive) item is scored from the candidate's item session only —\n\t\t// an item ref's templateDefault also sets template values the XML alone does not show.\n\t\tlet scored: ReturnType<typeof scoreAssessmentItemForTest>;\n\t\ttry {\n\t\t\tscored = scoreAssessmentItemForTest({\n\t\t\t\titemXml,\n\t\t\t\tresponses: request.responses,\n\t\t\t\titemSession: request.itemSession,\n\t\t\t\trequireItemSession: (current.item.templateDefaults?.length ?? 0) > 0,\n\t\t\t\t...(this.stringComparison ? { stringComparison: this.stringComparison } : {}),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof AssessmentItemScoringError) {\n\t\t\t\treturn { success: false, error: `${error.code}: ${error.message}` };\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tconst { result, testState } = scored;\n\n\t\t// Store responses and result. An uncounted submission (countAttempt=false) persists the\n\t\t// response but records no score, presented state, or attempt: response processing ran,\n\t\t// and the candidate continues on the item.\n\t\tsession.state.itemResponses[request.itemIdentifier] = request.responses;\n\t\tif (countAttempt) {\n\t\t\tif (!session.state.itemScores) {\n\t\t\t\tsession.state.itemScores = {};\n\t\t\t}\n\t\t\tsession.state.itemScores[request.itemIdentifier] = result;\n\t\t\tsession.itemTestStates = { ...session.itemTestStates, [request.itemIdentifier]: testState };\n\t\t}\n\t\tif (request.itemSession) {\n\t\t\tsession.state.itemSessions = {\n\t\t\t\t...(session.state.itemSessions ?? {}),\n\t\t\t\t[request.itemIdentifier]: request.itemSession,\n\t\t\t};\n\t\t}\n\t\tif (request.comment !== undefined) {\n\t\t\tsession.state.itemComments = { ...(session.state.itemComments ?? {}), [request.itemIdentifier]: request.comment };\n\t\t}\n\t\tsession.state.itemSessionStates = {\n\t\t\t...(session.state.itemSessionStates ?? {}),\n\t\t\t[request.itemIdentifier]: {\n\t\t\t\titemIdentifier: request.itemIdentifier,\n\t\t\t\tattemptCount: (previousItemSession?.attemptCount ?? 0) + (countAttempt ? 1 : 0),\n\t\t\t\t// QTI: a response still equal to its declared default is no response (the\n\t\t\t\t// numberResponded test), so a default-valued untouched item is not answered.\n\t\t\t\tisAnswered: testState.responded === true,\n\t\t\t\tisSubmitted: countAttempt ? true : (previousItemSession?.isSubmitted ?? false),\n\t\t\t\tlastSubmissionTime: countAttempt ? request.submittedAt : previousItemSession?.lastSubmissionTime,\n\t\t\t},\n\t\t};\n\n\t\t// Update timing\n\t\tif (request.timeSpent) {\n\t\t\tsession.state.timing.itemTimes[request.itemIdentifier] = request.timeSpent;\n\t\t}\n\n\t\t// Add to visited items if not already there\n\t\tif (countAttempt && !session.state.visitedItems.includes(request.itemIdentifier)) {\n\t\t\tsession.state.visitedItems.push(request.itemIdentifier);\n\t\t}\n\n\t\t// The responses were scored and applied in memory, but if the write did not land\n\t\t// they exist nowhere: accepting the submission anyway would silently lose the\n\t\t// candidate's answer on the next resume. The failure is propagated honestly\n\t\t// (`success: false`): the player restores the pre-submit session state, throws its\n\t\t// coded `submitFailed`, and the candidate can retry — the in-memory session object\n\t\t// above is discarded with the failed attempt.\n\t\tif (!saveSession(session)) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Failed to persist the submitted response',\n\t\t\t};\n\t\t}\n\n\t\tconst { outcomes, error } = this.currentOutcomes(session);\n\t\tconst currentVariables = testState.variables;\n\t\tconst decls = navigationDeclarations(session, outcomes, {\n\t\t\t...applyVariableMappings(currentVariables, current.item.variableMappings),\n\t\t\t...(currentVariables.SCORE ? {} : { SCORE: qtiValue('float', 'single', result.score) }),\n\t\t});\n\t\tconst nextId = nextItemIdentifier(session.assessment, delivered, index, decls, this.rng);\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tresult,\n\t\t\tnextItemIdentifier: nextId,\n\t\t\tupdatedState: session.state,\n\t\t\toutcomes,\n\t\t\t...(error ? { outcomeProcessingError: error } : {}),\n\t\t};\n\t}\n\n\t/**\n\t * Save session state (for auto-save)\n\t */\n\tasync saveState(request: SaveAssessmentStateRequest): Promise<SaveAssessmentStateResponse> {\n\t\tconst session = loadSession(request.sessionId);\n\t\tif (!session) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tsavedAt: Date.now(),\n\t\t\t};\n\t\t}\n\n\t\t// Update state\n\t\tsession.state = request.state;\n\t\t// A write that did not land is not a successful save: the autosave engine\n\t\t// (`success: false`) shows `failed`, retries with backoff and reports onError —\n\t\t// reporting success here would silently drop the draft.\n\t\tif (!saveSession(session)) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tsavedAt: Date.now(),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tsavedAt: Date.now(),\n\t\t};\n\t}\n\n\t/**\n\t * Finalize assessment and compute final scores\n\t */\n\tasync finalizeAssessment(\n\t\trequest: FinalizeAssessmentRequest\n\t): Promise<FinalizeAssessmentResponse> {\n\t\tconst session = loadSession(request.sessionId);\n\t\tif (!session) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\ttotalScore: 0,\n\t\t\t\tmaxScore: 0,\n\t\t\t\titemScores: {},\n\t\t\t\tfinalizedAt: Date.now(),\n\t\t\t};\n\t\t}\n\n\t\t// Mark as finalized. If the write fails, the session on disk stays unfinalized —\n\t\t// a resume would reopen the test. Reporting `finalized` to the player anyway would\n\t\t// end delivery on a state nothing stored, so the failure is propagated: the player\n\t\t// throws its coded `finalizeFailed` and the test stays open for a retry.\n\t\tsession.finalized = true;\n\t\tif (!saveSession(session)) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\ttotalScore: 0,\n\t\t\t\tmaxScore: 0,\n\t\t\t\titemScores: {},\n\t\t\t\tfinalizedAt: Date.now(),\n\t\t\t};\n\t\t}\n\n\t\t// Compute total score\n\t\tconst itemScores = session.state.itemScores || {};\n\t\tconst fallbackTotal = Object.values(itemScores).reduce((sum, result) => sum + result.score, 0);\n\t\tconst maxScore = Object.values(itemScores).reduce((sum, result) => sum + result.maxScore, 0);\n\n\t\t// Execute test-level outcome processing if available\n\t\tconst run = this.runOutcomeProcessing(session);\n\t\tconst outcomes = run.outcomes;\n\t\tconst scoreOutcome = outcomes?.SCORE_TOTAL ?? outcomes?.SCORE;\n\t\tconst totalScore = typeof scoreOutcome === 'number' ? scoreOutcome : fallbackTotal;\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\ttotalScore,\n\t\t\tmaxScore,\n\t\t\titemScores,\n\t\t\toutcomes: outcomes ?? undefined,\n\t\t\t...(run.error ? { outcomeProcessingError: run.error } : {}),\n\t\t\tfinalizedAt: Date.now(),\n\t\t};\n\t}\n\n\t/**\n\t * Outcome values and any outcome-processing failure after the submissions so far; both\n\t * undefined before the first submission.\n\t */\n\tprivate currentOutcomes(\n\t\tsession: StoredSession,\n\t): { outcomes?: TestOutcomeValues; error?: OutcomeProcessingError } {\n\t\tif (Object.keys(session.state.itemScores ?? {}).length === 0) return {};\n\t\tconst run = this.runOutcomeProcessing(session);\n\t\treturn { outcomes: run.outcomes ?? undefined, error: run.error };\n\t}\n\n\t/**\n\t * The stored final totals of a finalized session, for the terminal init response:\n\t * the same fallback totals `finalizeAssessment` reports (per-item scores included so\n\t * a shell can render its completion summary).\n\t */\n\tprivate storedFinalResults(session: StoredSession): NonNullable<InitSessionResponse['finalResults']> {\n\t\tconst itemScores = session.state.itemScores ?? {};\n\t\tconst results = Object.values(itemScores);\n\t\treturn {\n\t\t\ttotalScore: results.reduce((sum, result) => sum + result.score, 0),\n\t\t\tmaxScore: results.reduce((sum, result) => sum + result.maxScore, 0),\n\t\t\titemScores,\n\t\t};\n\t}\n\n\t/**\n\t * Execute test-level outcome processing (T9/T1).\n\t *\n\t * Returns every declared outcome's value (null for NULL), or null when no\n\t * outcomeProcessing is defined. A failure is reported as a typed\n\t * `OutcomeProcessingError` (persisted on the session) — it never fails delivery and\n\t * candidate responses always stay persisted, but it must surface to the host instead\n\t * of SCORE/testFeedback silently never computing.\n\t */\n\tprivate runOutcomeProcessing(\n\t\tsession: StoredSession,\n\t): { outcomes: TestOutcomeValues | null; error?: OutcomeProcessingError } {\n\t\tconst { assessment } = session;\n\t\tif (!assessment.outcomeProcessingXml) {\n\t\t\treturn { outcomes: null };\n\t\t}\n\n\ttry {\n\t\tconst testItems = this.buildTestItems(session);\n\t\tconst decls = addScopeDurationDeclarations(\n\t\t\taddItemVariableDeclarations(\n\t\t\t\ttestOutcomeDeclarations(assessment),\n\t\t\t\tObject.fromEntries(testItems.map((item) => [item.identifier, item.variables])),\n\t\t\t),\n\t\t\tassessment,\n\t\t\tsession.state.timing,\n\t\t);\n\t\t\tconst ctx = new DeclarationContext(decls);\n\n\t\t\t// Parse and execute outcome processing\n\t\t\tconst opEl = parseXml(assessment.outcomeProcessingXml).documentElement;\n\t\t\tif (!opEl) return { outcomes: null };\n\n\t\t\tconst program = buildOutcomeProcessingAst(opEl, {\n\t\t\t\tscope: 'test',\n\t\t\t\telementNameMapper: qtiElementNameMapper,\n\t\t\t});\n\t\t\texecProgram(\n\t\t\t\t{\n\t\t\t\t\tctx,\n\t\t\t\t\trng: this.rng,\n\t\t\t\t\ttest: { items: testItems },\n\t\t\t\t},\n\t\t\t\tprogram\n\t\t\t);\n\n\t\t\tconst result: TestOutcomeValues = {};\n\t\t\tfor (const d of assessment.outcomeDeclarations || []) {\n\t\t\t\tconst v = ctx.getValue(d.identifier);\n\t\t\t\tresult[d.identifier] = v.kind === 'value' ? (v.value as TestOutcomeValue) : null;\n\t\t\t}\n\t\t\tif (session.outcomeProcessingError) {\n\t\t\t\tdelete session.outcomeProcessingError;\n\t\t\t\tsaveSession(session);\n\t\t\t}\n\t\t\treturn { outcomes: result };\n\t\t} catch (err) {\n\t\t\tconsole.warn('[ReferenceBackendAdapter] outcomeProcessing failed:', err);\n\t\t\tconst error: OutcomeProcessingError = {\n\t\t\t\tcode: 'OUTCOME_PROCESSING_FAILED',\n\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t};\n\t\t\tsession.outcomeProcessingError = error;\n\t\t\tsaveSession(session);\n\t\t\treturn { outcomes: null, error };\n\t\t}\n\t}\n\n\t/**\n\t * Resume existing session (alias for initSession with resumeSessionId)\n\t */\n\tasync resumeSession(sessionId: SessionId): Promise<InitSessionResponse> {\n\t\treturn this.initSession({\n\t\t\tassessmentId: '',\n\t\t\tcandidateId: '',\n\t\t\tresumeSessionId: sessionId,\n\t\t});\n\t}\n\n\t/**\n\t * The identifier of this adapter's most recent unfinalized session for an\n\t * assessment and candidate, or null. Hosts pass it as `initSession.resumeSessionId`\n\t * to resume the stored draft — the reference resume path after a refresh.\n\t */\n\tlatestSessionId(assessmentId: string, candidateId: string): SessionId | null {\n\t\treturn findLatestSession(assessmentId, candidateId)?.sessionId ?? null;\n\t}\n\n\t/**\n\t * Query item bank for random item selection\n\t *\n\t * This reference implementation:\n\t * - Caches bank queries to avoid repeated calls\n\t * - Implements retry logic with exponential backoff\n\t * - Returns demo items (in production, fetch from real item bank)\n\t *\n\t * @param request - Item bank query request\n\t * @returns Selected items from bank\n\t */\n\t// =========================================================================\n\t// PRIVATE HELPERS\n\t// =========================================================================\n\n\tprivate createDemoAssessment(assessmentId: string): SecureAssessment {\n\t\t// This is a minimal demo assessment\n\t\t// In production, load from database and filter based on role\n\t\treturn {\n\t\t\tidentifier: assessmentId,\n\t\t\ttitle: 'Demo Assessment',\n\t\t\tnavigationMode: 'nonlinear',\n\t\t\tsubmissionMode: 'simultaneous',\n\t\t\ttestParts: [\n\t\t\t\t{\n\t\t\t\t\tidentifier: 'part1',\n\t\t\t\t\trubricBlocks: [],\n\t\t\t\t\titemSessionControl: {\n\t\t\t\t\t\tmaxAttempts: 1,\n\t\t\t\t\t\tshowFeedback: true,\n\t\t\t\t\t\tallowReview: true,\n\t\t\t\t\t\tshowSolution: false,\n\t\t\t\t\t\tallowComment: false,\n\t\t\t\t\t\tallowSkipping: true,\n\t\t\t\t\t\tvalidateResponses: true,\n\t\t\t\t\t},\n\t\t\t\t\tsections: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tidentifier: 'section1',\n\t\t\t\t\t\t\ttitle: 'Section 1',\n\t\t\t\t\t\t\tvisible: true,\n\t\t\t\t\t\t\tassessmentItemRefs: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tidentifier: 'item1',\n\t\t\t\t\t\t\t\t\trole: 'candidate',\n\t\t\t\t\t\t\t\t\t// In production, load from database\n\t\t\t\t\t\t\t\t\t// For candidates, responseProcessing should be removed server-side\n\t\t\t\t\t\t\t\t\titemXml: `<assessmentItem identifier=\"item1\" title=\"Sample Item\" adaptive=\"false\" timeDependent=\"false\">\n <responseDeclaration identifier=\"RESPONSE\" cardinality=\"single\" baseType=\"identifier\">\n <correctResponse>\n <value>A</value>\n </correctResponse>\n </responseDeclaration>\n <outcomeDeclaration identifier=\"SCORE\" cardinality=\"single\" baseType=\"float\">\n <defaultValue>\n <value>0</value>\n </defaultValue>\n </outcomeDeclaration>\n <itemBody>\n <p>What is 2 + 2?</p>\n <choiceInteraction responseIdentifier=\"RESPONSE\" shuffle=\"false\" maxChoices=\"1\">\n <simpleChoice identifier=\"A\">4</simpleChoice>\n <simpleChoice identifier=\"B\">3</simpleChoice>\n <simpleChoice identifier=\"C\">5</simpleChoice>\n </choiceInteraction>\n </itemBody>\n <responseProcessing>\n <responseCondition>\n <responseIf>\n <match>\n <variable identifier=\"RESPONSE\" />\n <correct identifier=\"RESPONSE\" />\n </match>\n <setOutcomeValue identifier=\"SCORE\">\n <baseValue baseType=\"float\">1</baseValue>\n </setOutcomeValue>\n </responseIf>\n <responseElse>\n <setOutcomeValue identifier=\"SCORE\">\n <baseValue baseType=\"float\">0</baseValue>\n </setOutcomeValue>\n </responseElse>\n </responseCondition>\n </responseProcessing>\n</assessmentItem>`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tidentifier: 'item2',\n\t\t\t\t\t\t\t\t\trole: 'candidate',\n\t\t\t\t\t\t\t\t\titemXml: `<assessmentItem identifier=\"item2\" title=\"Follow-up Item\" adaptive=\"false\" timeDependent=\"false\">\n <responseDeclaration identifier=\"RESPONSE\" cardinality=\"single\" baseType=\"identifier\">\n <correctResponse>\n <value>A</value>\n </correctResponse>\n </responseDeclaration>\n <outcomeDeclaration identifier=\"SCORE\" cardinality=\"single\" baseType=\"float\">\n <defaultValue>\n <value>0</value>\n </defaultValue>\n </outcomeDeclaration>\n <itemBody>\n <p>Demo follow-up item</p>\n <choiceInteraction responseIdentifier=\"RESPONSE\" shuffle=\"false\" maxChoices=\"1\">\n <simpleChoice identifier=\"A\">ok</simpleChoice>\n <simpleChoice identifier=\"B\">no</simpleChoice>\n </choiceInteraction>\n </itemBody>\n <responseProcessing>\n <responseCondition>\n <responseIf>\n <match>\n <variable identifier=\"RESPONSE\" />\n <correct identifier=\"RESPONSE\" />\n </match>\n <setOutcomeValue identifier=\"SCORE\">\n <baseValue baseType=\"float\">1</baseValue>\n </setOutcomeValue>\n </responseIf>\n </responseCondition>\n </responseProcessing>\n</assessmentItem>`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\t// =========================================================================\n\t// STATIC: QTI TEST XML PARSER\n\t// =========================================================================\n\n\t/**\n\t * Test-level view of every delivered item. A submitted item is presented and carries the state\n\t * its latest counted submission recorded (a score without one carries only its SCORE); an item\n\t * not yet submitted carries its declared defaults and counts as not presented.\n\t */\n\tprivate buildTestItems(session: StoredSession): TestItemState[] {\n\t\tconst itemScores = session.state.itemScores ?? {};\n\t\treturn getItemRefsInOrder(session.assessment).map(({ item, sectionIdentifiers }) => {\n\t\t\tconst scoring = itemScores[item.identifier];\n\t\t\tconst presented = scoring !== undefined;\n\t\t\tconst itemState = presented ? session.itemTestStates?.[item.identifier] : defaultItemTestState(item.itemXml);\n\t\t\tconst variables: Record<string, QtiValue> = { ...(itemState?.variables ?? {}) };\n\t\t\tif (scoring && !variables.SCORE) variables.SCORE = qtiValue('float', 'single', scoring.score);\n\t\t\tObject.assign(variables, applyVariableMappings(variables, item.variableMappings));\n\t\t\treturn {\n\t\t\t\tidentifier: item.identifier,\n\t\t\t\tsectionIdentifiers,\n\t\t\t\tcategories: item.categories,\n\t\t\t\tweights: item.weights ? Object.fromEntries(item.weights.map((w) => [w.identifier, w.value])) : undefined,\n\t\t\t\tvariables,\n\t\t\t\toutcomeBounds: itemState?.outcomeBounds ?? defaultItemTestState(item.itemXml)?.outcomeBounds,\n\t\t\t\tpresented,\n\t\t\t\tresponded: presented && itemState?.responded === true,\n\t\t\t\tcorrect: presented && itemState?.correct === true,\n\t\t\t\tincorrect: presented && itemState?.correct === false,\n\t\t\t\tselected: true,\n\t\t\t};\n\t\t});\n\t}\n\n\t// =========================================================================\n\t// ITEM BANK HELPERS\n\t// =========================================================================\n\n\t/**\n\t * Generate cache key for item bank query\n\t */\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ReferenceBackendAdapter.js","sourceRoot":"","sources":["../../src/integration/ReferenceBackendAdapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AAEH,OAAO,EACN,yBAAyB,EACzB,kBAAkB,EAElB,WAAW,EACX,QAAQ,EAGR,QAAQ,GAGR,MAAM,yBAAyB,CAAC;AAiCjC,OAAO,EACN,2BAA2B,EAC3B,4BAA4B,EAC5B,qBAAqB,EAErB,cAAc,EACd,cAAc,EACd,oBAAoB,EACpB,yBAAyB,EAEzB,uBAAuB,GAEvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EACN,iBAAiB,EACjB,kBAAkB,EAClB,sBAAsB,EACtB,kBAAkB,GAClB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACN,iBAAiB,EACjB,iBAAiB,EACjB,WAAW,EACX,WAAW,GAEX,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACN,0BAA0B,EAC1B,oBAAoB,EACpB,0BAA0B,GAC1B,MAAM,6BAA6B,CAAC;AAyBrC,MAAM,OAAO,uBAAuB;IAmBnC,YAAY,UAA0C,EAAE;QAhBxD;;;WAGG;QACM,iBAAY,GAAG,IAAI,CAAC;QAC7B;;;;;WAKG;QACM,wBAAmB,GAAG,IAAI,CAAC;QAC5B,0BAAqB,GAAkC,IAAI,GAAG,EAAE,CAAC;QAKxE,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,IAAI,IAAI,CAAC,MAAM,CAAC;QACtC,IAAI,CAAC,g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gBACrD,OAAO,EAAE,SAAS,IAAI,SAAS,EAAE,OAAO,KAAK,IAAI;gBACjD,SAAS,EAAE,SAAS,IAAI,SAAS,EAAE,OAAO,KAAK,KAAK;gBACpD,QAAQ,EAAE,IAAI;aACd,CAAC;QACH,CAAC,CAAC,CAAC;IACJ,CAAC;;AAppBD,sEAAsE;AAC/D,8CAAsB,GAAG,sBAAsB,AAAzB,CAA0B","sourcesContent":["/**\n * Reference Backend Adapter - localStorage Implementation\n *\n * This is a REFERENCE IMPLEMENTATION demonstrating the BackendAdapter contract.\n * It uses localStorage for persistence and performs scoring CLIENT-SIDE.\n *\n * ## Security Warning\n *\n * This implementation is INSECURE for production use because:\n * - Scoring is done client-side (can be manipulated)\n * - QTI XML with correct answers is stored in client\n * - No authentication or authorization checks\n *\n * ## Purpose\n *\n * This adapter serves as:\n * 1. Reference implementation showing the API contract\n * 2. Development/demo tool for offline testing\n * 3. Template for building secure backend adapters\n *\n * ## Production Use\n *\n * Replace this with a real backend adapter that:\n * - Stores QTI XML server-side\n * - Performs scoring server-side\n * - Validates all requests with authentication\n * - Filters sensitive data based on role\n *\n * ## Persistence failure semantics\n *\n * A localStorage write that does not land (quota exceeded, private-mode eviction) means\n * the operation did not complete, and every backend method reports it honestly:\n * `saveState` returns `success: false` (the autosave engine shows `failed`, retries with\n * backoff and reports onError), `submitResponses` returns `success: false` (the player\n * restores the pre-submit state and throws its coded `submitFailed` — accepting the\n * submission anyway would silently lose the answer on the next resume), and\n * `finalizeAssessment` returns `success: false` (the `finalized` flag never persisted, so\n * reporting a completion would resurrect the test on resume; the player throws its coded\n * `finalizeFailed` and the test stays open for a retry). The initial session write and\n * the outcome-processing-error bookkeeping are the only best-effort writes: their response\n * shapes carry no failure, and a lost init write merely leaves a fresh session without a\n * resumable draft — which the very next save reports through the paths above.\n */\n\nimport {\n\tbuildOutcomeProcessingAst,\n\tDeclarationContext,\n\ttype DeclarationMap,\n\texecProgram,\n\tparseXml,\n\tserializeXml,\n\ttype QtiValue,\n\tqtiValue,\n\ttype StringComparisonOptions,\n\ttype TestItemState,\n} from '@pie-qti/qti-processing';\nimport {\n\tcreateResolvedItemDeliveryContext,\n\textractAssessmentStimulusRefs,\n\textractProcessingIncludeRefs,\n\textractQtiStylesheets,\n\tparseAssessmentStimulusXml,\n\tresolveCheckedPackagePath,\n\tresolveCheckedPackagePathFromFile,\n} from '@pie-qti/ims-cp-core';\nimport type {\n\tAssessmentSessionState,\n\tBackendAdapter,\n\tFinalizeAssessmentRequest,\n\tFinalizeAssessmentResponse,\n\tInitSessionRequest,\n\tInitSessionResponse,\n\tOutcomeProcessingError,\n\tSaveAssessmentStateRequest,\n\tSaveAssessmentStateResponse,\n\tSecureAssessment,\n\tSecureBranchRule,\n\tSecureItemRef,\n\tSecureItemSessionControl,\n\tSecureSection,\n\tSecureTestPart,\n\tSessionId,\n\tSubmitResponsesRequest,\n\tSubmitResponsesResponse,\n\tTestFeedbackItem,\n\tTestOutcomeValue,\n\tTestOutcomeValues,\n} from './api-contract.js';\nimport {\n\taddItemVariableDeclarations,\n\taddScopeDurationDeclarations,\n\tapplyVariableMappings,\n\ttype DeliveredItem,\n\tdeliveredItems,\n\tdrawAssessment,\n\tqtiElementNameMapper,\n\tresolveItemSessionControl,\n\tshuffleArray,\n\ttestOutcomeDeclarations,\n\ttoCanonicalQtiName,\n} from '../core/testStructure.js';\nimport { parseAssessmentTestXml } from './qti-test-parser.js';\nimport {\n\tfirstEligibleItem,\n\tgetItemRefsInOrder,\n\tnavigationDeclarations,\n\tnextItemIdentifier,\n} from './test-navigation.js';\nimport {\n\tgenerateSessionId,\n\tfindLatestSession,\n\tloadSession,\n\tsaveSession,\n\ttype StoredSession,\n} from './session-store.js';\nimport {\n\tAssessmentItemScoringError,\n\tdefaultItemTestState,\n\tscoreAssessmentItemForTest,\n} from './assessment-item-scorer.js';\n\n/**\n * Reference Backend Adapter using localStorage\n *\n * @example\n * ```typescript\n * const adapter = new ReferenceBackendAdapter();\n * const response = await adapter.initSession({\n * assessmentId: 'test-001',\n * candidateId: 'student-123'\n * });\n * ```\n */\nexport interface ReferenceBackendAdapterOptions {\n\t/** RNG for the session-start draw of selection and ordering. Defaults to Math.random. */\n\trng?: () => number;\n\t/**\n\t * String comparison folds the scorer applies beyond QTI's equality, as the delivery's input\n\t * needs them (see the item player's `AssessmentItemDefinitionConfig.stringComparison`). Set\n\t * the same value as the player's `stringComparison`. Exact when absent.\n\t */\n\tstringComparison?: StringComparisonOptions;\n}\n\nexport class ReferenceBackendAdapter implements BackendAdapter {\n\t/** @see ./qti-test-parser.ts — the parser lives in its own module. */\n\tstatic parseAssessmentTestXml = parseAssessmentTestXml;\n\t/**\n\t * The adapter persists drafts: sessions live in localStorage and `saveState` writes\n\t * the candidate's snapshot into them, so shell autosave is ON by default.\n\t */\n\treadonly canSaveState = true;\n\t/**\n\t * The adapter scores from the candidate's serialized item session: a templated item is\n\t * scored against the instance the candidate saw (never a fresh template draw), and an\n\t * adaptive item's accumulated outcomes are taken as submitted. The player therefore\n\t * always sends it (reference mode); a templated or adaptive item without one is refused.\n\t */\n\treadonly requiresItemSession = true;\n\tprivate registeredAssessments: Map<string, SecureAssessment> = new Map();\n\tprivate readonly rng: () => number;\n\tprivate readonly stringComparison: StringComparisonOptions | undefined;\n\n\tconstructor(options: ReferenceBackendAdapterOptions = {}) {\n\t\tthis.rng = options.rng ?? Math.random;\n\t\tthis.stringComparison = options.stringComparison ? Object.freeze({ ...options.stringComparison }) : undefined;\n\t}\n\n\t/**\n\t * Register/override a client-provided assessment structure for a given assessmentId.\n\t *\n\t * This is useful for demos or web-components that supply assessment XML directly.\n\t * Security: this remains a reference/demo adapter; production backends should not\n\t * accept client-authored assessments.\n\t */\n\tpublic registerAssessment(assessmentId: string, assessment: SecureAssessment) {\n\t\tthis.registeredAssessments.set(assessmentId, assessment);\n\t}\n\n\tprivate getAssessment(assessmentId: string): SecureAssessment {\n\t\treturn this.registeredAssessments.get(assessmentId) ?? this.createDemoAssessment(assessmentId);\n\t}\n\n\t/**\n\t * Initialize a new assessment session\n\t */\n\tasync initSession(request: InitSessionRequest): Promise<InitSessionResponse> {\n\t\t// Check if resuming existing session\n\t\t\tif (request.resumeSessionId) {\n\t\t\t\tconst stored = loadSession(request.resumeSessionId);\n\t\t\t\tif (stored) {\n\t\t\t\t\t// A finalized session has no resumable draft: restore terminal (the\n\t\t\t\t\t// stored final totals, no restoredState), so hosts show the\n\t\t\t\t\t// already-submitted view instead of delivery whose every submit fails.\n\t\t\t\t\tif (stored.finalized) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tsessionId: stored.sessionId,\n\t\t\t\t\t\t\tassessment: stored.assessment,\n\t\t\t\t\t\t\tfinalized: true,\n\t\t\t\t\t\t\tfinalResults: this.storedFinalResults(stored),\n\t\t\t\t\t\t\toutcomes: this.currentOutcomes(stored).outcomes,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsessionId: stored.sessionId,\n\t\t\t\t\t\tassessment: stored.assessment,\n\t\t\t\t\t\trestoredState: stored.state,\n\t\t\t\t\t\toutcomes: this.currentOutcomes(stored).outcomes,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t// Create new session\n\t\tconst sessionId = generateSessionId(request.assessmentId, request.candidateId);\n\n\t\t// In a real backend, you would:\n\t\t// 1. Fetch assessment from database\n\t\t// 2. Filter QTI XML based on role\n\t\t// 3. Remove responseProcessing for candidates\n\t\t//\n\t\t// For reference implementation, we'll use demo data. Selection and ordering are drawn once\n\t\t// here; the stored draw is what a resume returns.\n\t\tconst assessment = drawAssessment(this.getAssessment(request.assessmentId), this.rng);\n\t\tconst firstItemIdentifier =\n\t\t\tfirstEligibleItem(deliveredItems(assessment), 0, undefined, testOutcomeDeclarations(assessment), this.rng) ?? '';\n\n\t\tconst state: AssessmentSessionState = {\n\t\t\tcurrentItemIdentifier: firstItemIdentifier,\n\t\t\tvisitedItems: [],\n\t\t\titemResponses: {},\n\t\t\titemScores: {},\n\t\t\titemSessions: {},\n\t\t\ttiming: {\n\t\t\t\tstartedAt: Date.now(),\n\t\t\t\titemTimes: {},\n\t\t\t\ttotalTime: 0,\n\t\t\t},\n\t\t};\n\n\t\tconst session: StoredSession = {\n\t\t\tsessionId,\n\t\t\tassessmentId: request.assessmentId,\n\t\t\tcandidateId: request.candidateId,\n\t\t\tassessment,\n\t\t\tstate,\n\t\t\tcreatedAt: Date.now(),\n\t\t\tfinalized: false,\n\t\t};\n\n\t\tsaveSession(session);\n\n\t\treturn {\n\t\t\tsessionId,\n\t\t\tassessment,\n\t\t\tcurrentItemIdentifier: firstItemIdentifier || undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Submit responses and get scoring result\n\t */\n\tasync submitResponses(request: SubmitResponsesRequest): Promise<SubmitResponsesResponse> {\n\t\tconst session = loadSession(request.sessionId);\n\t\tif (!session) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Session not found',\n\t\t\t};\n\t\t}\n\n\t\tif (session.finalized) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Session already finalized',\n\t\t\t};\n\t\t}\n\n\t\tconst receivedAt = Date.now();\n\t\tconst assessmentLimit = session.assessment.timeLimits;\n\t\tconst effectiveAssessmentLimitSeconds =\n\t\t\trequest.timing?.scope === 'assessment' && request.timing.limitSeconds !== undefined\n\t\t\t\t? request.timing.limitSeconds\n\t\t\t\t: assessmentLimit?.maxTime;\n\t\t// The candidate's own test clock (gates and pauses excluded) when the client\n\t\t// reports it; otherwise the session wall clock, which a production backend owns.\n\t\tconst assessmentElapsedSeconds =\n\t\t\trequest.timing?.assessmentElapsedMs !== undefined\n\t\t\t\t? request.timing.assessmentElapsedMs / 1000\n\t\t\t\t: (receivedAt - session.createdAt) / 1000;\n\t\tconst assessmentAllowsLate = assessmentLimit?.allowLateSubmission ?? request.timing?.allowLateSubmission;\n\t\t// A `time-expired` submission is the terminal collection a hard limit triggers:\n\t\t// the window closed with the expiry, and the pending responses must be accepted.\n\t\t// A `proctor` collection is the administrative end of the test, accepted alike, and\n\t\t// so is an `unreachable` one (a question the candidate can no longer reach,\n\t\t// collected as it stands at the end of the test).\n\t\tconst timeExpiredCollection =\n\t\t\trequest.timing?.submissionReason === 'time-expired' ||\n\t\t\trequest.timing?.submissionReason === 'proctor' ||\n\t\t\trequest.timing?.submissionReason === 'unreachable';\n\t\tif (\n\t\t\t!timeExpiredCollection &&\n\t\t\teffectiveAssessmentLimitSeconds !== undefined &&\n\t\t\tassessmentAllowsLate !== true &&\n\t\t\tassessmentElapsedSeconds > effectiveAssessmentLimitSeconds\n\t\t) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Assessment time limit expired',\n\t\t\t};\n\t\t}\n\n\t\tconst evidenceExpired =\n\t\t\trequest.timing?.limitSeconds !== undefined &&\n\t\t\trequest.timing.elapsedMs >= request.timing.limitSeconds * 1000;\n\t\tif (!timeExpiredCollection && evidenceExpired && request.timing?.allowLateSubmission !== true) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Time limit expired',\n\t\t\t};\n\t\t}\n\n\t\tconst delivered = deliveredItems(session.assessment);\n\t\tconst index = delivered.findIndex((d) => d.item.identifier === request.itemIdentifier);\n\t\tconst current = delivered[index];\n\t\tif (!current) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Item not found',\n\t\t\t};\n\t\t}\n\t\tconst itemXml = current.item.itemXml;\n\t\tconst control = resolveItemSessionControl(current.testPart, current.sections, current.item);\n\t\tconst previousItemSession = session.state.itemSessionStates?.[request.itemIdentifier];\n\t\t// A QTI endAttempt countAttempt=false submission (a hint request) runs response processing\n\t\t// without consuming an attempt, so the attempt limit does not apply to it.\n\t\tconst countAttempt = request.countAttempt ?? true;\n\t\tif (countAttempt && control.maxAttempts > 0 && (previousItemSession?.attemptCount ?? 0) >= control.maxAttempts) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Maximum attempts reached',\n\t\t\t};\n\t\t}\n\t\tif (request.comment !== undefined && !control.allowComment) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Comments are not allowed for this item',\n\t\t\t};\n\t\t}\n\n\t\t// **SECURITY WARNING**: Client-side scoring is INSECURE\n\t\t// In production, this MUST be done server-side\n\t\t// A templated (or adaptive) item is scored from the candidate's item session only —\n\t\t// an item ref's templateDefault also sets template values the XML alone does not show.\n\t\tlet scored: ReturnType<typeof scoreAssessmentItemForTest>;\n\t\ttry {\n\t\t\tscored = scoreAssessmentItemForTest({\n\t\t\t\titemXml,\n\t\t\t\tresponses: request.responses,\n\t\t\t\titemSession: request.itemSession,\n\t\t\t\trequireItemSession: (current.item.templateDefaults?.length ?? 0) > 0,\n\t\t\t\t...(this.stringComparison ? { stringComparison: this.stringComparison } : {}),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof AssessmentItemScoringError) {\n\t\t\t\treturn { success: false, error: `${error.code}: ${error.message}` };\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tconst { result, testState } = scored;\n\n\t\t// Store responses and result. An uncounted submission (countAttempt=false) persists the\n\t\t// response but records no score, presented state, or attempt: response processing ran,\n\t\t// and the candidate continues on the item.\n\t\tsession.state.itemResponses[request.itemIdentifier] = request.responses;\n\t\tif (countAttempt) {\n\t\t\tif (!session.state.itemScores) {\n\t\t\t\tsession.state.itemScores = {};\n\t\t\t}\n\t\t\tsession.state.itemScores[request.itemIdentifier] = result;\n\t\t\tsession.itemTestStates = { ...session.itemTestStates, [request.itemIdentifier]: testState };\n\t\t}\n\t\tif (request.itemSession) {\n\t\t\tsession.state.itemSessions = {\n\t\t\t\t...(session.state.itemSessions ?? {}),\n\t\t\t\t[request.itemIdentifier]: request.itemSession,\n\t\t\t};\n\t\t}\n\t\tif (request.comment !== undefined) {\n\t\t\tsession.state.itemComments = { ...(session.state.itemComments ?? {}), [request.itemIdentifier]: request.comment };\n\t\t}\n\t\tsession.state.itemSessionStates = {\n\t\t\t...(session.state.itemSessionStates ?? {}),\n\t\t\t[request.itemIdentifier]: {\n\t\t\t\titemIdentifier: request.itemIdentifier,\n\t\t\t\tattemptCount: (previousItemSession?.attemptCount ?? 0) + (countAttempt ? 1 : 0),\n\t\t\t\t// QTI: a response still equal to its declared default is no response (the\n\t\t\t\t// numberResponded test), so a default-valued untouched item is not answered.\n\t\t\t\tisAnswered: testState.responded === true,\n\t\t\t\tisSubmitted: countAttempt ? true : (previousItemSession?.isSubmitted ?? false),\n\t\t\t\tlastSubmissionTime: countAttempt ? request.submittedAt : previousItemSession?.lastSubmissionTime,\n\t\t\t},\n\t\t};\n\n\t\t// Update timing\n\t\tif (request.timeSpent) {\n\t\t\tsession.state.timing.itemTimes[request.itemIdentifier] = request.timeSpent;\n\t\t}\n\n\t\t// Add to visited items if not already there\n\t\tif (countAttempt && !session.state.visitedItems.includes(request.itemIdentifier)) {\n\t\t\tsession.state.visitedItems.push(request.itemIdentifier);\n\t\t}\n\n\t\t// The responses were scored and applied in memory, but if the write did not land\n\t\t// they exist nowhere: accepting the submission anyway would silently lose the\n\t\t// candidate's answer on the next resume. The failure is propagated honestly\n\t\t// (`success: false`): the player restores the pre-submit session state, throws its\n\t\t// coded `submitFailed`, and the candidate can retry — the in-memory session object\n\t\t// above is discarded with the failed attempt.\n\t\tif (!saveSession(session)) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: 'Failed to persist the submitted response',\n\t\t\t};\n\t\t}\n\n\t\tconst { outcomes, error } = this.currentOutcomes(session);\n\t\tconst currentVariables = testState.variables;\n\t\tconst decls = navigationDeclarations(session, outcomes, {\n\t\t\t...applyVariableMappings(currentVariables, current.item.variableMappings),\n\t\t\t...(currentVariables.SCORE ? {} : { SCORE: qtiValue('float', 'single', result.score) }),\n\t\t});\n\t\tconst nextId = nextItemIdentifier(delivered, index, decls, this.rng);\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tresult,\n\t\t\tnextItemIdentifier: nextId,\n\t\t\tupdatedState: session.state,\n\t\t\toutcomes,\n\t\t\t...(error ? { outcomeProcessingError: error } : {}),\n\t\t};\n\t}\n\n\t/**\n\t * Save session state (for auto-save)\n\t */\n\tasync saveState(request: SaveAssessmentStateRequest): Promise<SaveAssessmentStateResponse> {\n\t\tconst session = loadSession(request.sessionId);\n\t\tif (!session) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tsavedAt: Date.now(),\n\t\t\t};\n\t\t}\n\n\t\t// Update state\n\t\tsession.state = request.state;\n\t\t// A write that did not land is not a successful save: the autosave engine\n\t\t// (`success: false`) shows `failed`, retries with backoff and reports onError —\n\t\t// reporting success here would silently drop the draft.\n\t\tif (!saveSession(session)) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tsavedAt: Date.now(),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tsavedAt: Date.now(),\n\t\t};\n\t}\n\n\t/**\n\t * Finalize assessment and compute final scores\n\t */\n\tasync finalizeAssessment(\n\t\trequest: FinalizeAssessmentRequest\n\t): Promise<FinalizeAssessmentResponse> {\n\t\tconst session = loadSession(request.sessionId);\n\t\tif (!session) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\ttotalScore: 0,\n\t\t\t\tmaxScore: 0,\n\t\t\t\titemScores: {},\n\t\t\t\tfinalizedAt: Date.now(),\n\t\t\t};\n\t\t}\n\n\t\t// Mark as finalized. If the write fails, the session on disk stays unfinalized —\n\t\t// a resume would reopen the test. Reporting `finalized` to the player anyway would\n\t\t// end delivery on a state nothing stored, so the failure is propagated: the player\n\t\t// throws its coded `finalizeFailed` and the test stays open for a retry.\n\t\tsession.finalized = true;\n\t\tif (!saveSession(session)) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\ttotalScore: 0,\n\t\t\t\tmaxScore: 0,\n\t\t\t\titemScores: {},\n\t\t\t\tfinalizedAt: Date.now(),\n\t\t\t};\n\t\t}\n\n\t\t// Compute total score\n\t\tconst itemScores = session.state.itemScores || {};\n\t\tconst fallbackTotal = Object.values(itemScores).reduce((sum, result) => sum + result.score, 0);\n\t\tconst maxScore = Object.values(itemScores).reduce((sum, result) => sum + result.maxScore, 0);\n\n\t\t// Execute test-level outcome processing if available\n\t\tconst run = this.runOutcomeProcessing(session);\n\t\tconst outcomes = run.outcomes;\n\t\tconst scoreOutcome = outcomes?.SCORE_TOTAL ?? outcomes?.SCORE;\n\t\tconst totalScore = typeof scoreOutcome === 'number' ? scoreOutcome : fallbackTotal;\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\ttotalScore,\n\t\t\tmaxScore,\n\t\t\titemScores,\n\t\t\toutcomes: outcomes ?? undefined,\n\t\t\t...(run.error ? { outcomeProcessingError: run.error } : {}),\n\t\t\tfinalizedAt: Date.now(),\n\t\t};\n\t}\n\n\t/**\n\t * Outcome values and any outcome-processing failure after the submissions so far; both\n\t * undefined before the first submission.\n\t */\n\tprivate currentOutcomes(\n\t\tsession: StoredSession,\n\t): { outcomes?: TestOutcomeValues; error?: OutcomeProcessingError } {\n\t\tif (Object.keys(session.state.itemScores ?? {}).length === 0) return {};\n\t\tconst run = this.runOutcomeProcessing(session);\n\t\treturn { outcomes: run.outcomes ?? undefined, error: run.error };\n\t}\n\n\t/**\n\t * The stored final totals of a finalized session, for the terminal init response:\n\t * the same fallback totals `finalizeAssessment` reports (per-item scores included so\n\t * a shell can render its completion summary).\n\t */\n\tprivate storedFinalResults(session: StoredSession): NonNullable<InitSessionResponse['finalResults']> {\n\t\tconst itemScores = session.state.itemScores ?? {};\n\t\tconst results = Object.values(itemScores);\n\t\treturn {\n\t\t\ttotalScore: results.reduce((sum, result) => sum + result.score, 0),\n\t\t\tmaxScore: results.reduce((sum, result) => sum + result.maxScore, 0),\n\t\t\titemScores,\n\t\t};\n\t}\n\n\t/**\n\t * Execute test-level outcome processing (T9/T1).\n\t *\n\t * Returns every declared outcome's value (null for NULL), or null when no\n\t * outcomeProcessing is defined. A failure is reported as a typed\n\t * `OutcomeProcessingError` (persisted on the session) — it never fails delivery and\n\t * candidate responses always stay persisted, but it must surface to the host instead\n\t * of SCORE/testFeedback silently never computing.\n\t */\n\tprivate runOutcomeProcessing(\n\t\tsession: StoredSession,\n\t): { outcomes: TestOutcomeValues | null; error?: OutcomeProcessingError } {\n\t\tconst { assessment } = session;\n\t\tif (!assessment.outcomeProcessingXml) {\n\t\t\treturn { outcomes: null };\n\t\t}\n\n\ttry {\n\t\tconst testItems = this.buildTestItems(session);\n\t\tconst decls = addScopeDurationDeclarations(\n\t\t\taddItemVariableDeclarations(\n\t\t\t\ttestOutcomeDeclarations(assessment),\n\t\t\t\tObject.fromEntries(testItems.map((item) => [item.identifier, item.variables])),\n\t\t\t),\n\t\t\tassessment,\n\t\t\tsession.state.timing,\n\t\t);\n\t\t\tconst ctx = new DeclarationContext(decls);\n\n\t\t\t// Parse and execute outcome processing\n\t\t\tconst opEl = parseXml(assessment.outcomeProcessingXml).documentElement;\n\t\t\tif (!opEl) return { outcomes: null };\n\n\t\t\tconst program = buildOutcomeProcessingAst(opEl, {\n\t\t\t\tscope: 'test',\n\t\t\t\telementNameMapper: qtiElementNameMapper,\n\t\t\t});\n\t\t\texecProgram(\n\t\t\t\t{\n\t\t\t\t\tctx,\n\t\t\t\t\trng: this.rng,\n\t\t\t\t\ttest: { items: testItems },\n\t\t\t\t},\n\t\t\t\tprogram\n\t\t\t);\n\n\t\t\tconst result: TestOutcomeValues = {};\n\t\t\tfor (const d of assessment.outcomeDeclarations || []) {\n\t\t\t\tconst v = ctx.getValue(d.identifier);\n\t\t\t\tresult[d.identifier] = v.kind === 'value' ? (v.value as TestOutcomeValue) : null;\n\t\t\t}\n\t\t\tif (session.outcomeProcessingError) {\n\t\t\t\tdelete session.outcomeProcessingError;\n\t\t\t\tsaveSession(session);\n\t\t\t}\n\t\t\treturn { outcomes: result };\n\t\t} catch (err) {\n\t\t\tconsole.warn('[ReferenceBackendAdapter] outcomeProcessing failed:', err);\n\t\t\tconst error: OutcomeProcessingError = {\n\t\t\t\tcode: 'OUTCOME_PROCESSING_FAILED',\n\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t};\n\t\t\tsession.outcomeProcessingError = error;\n\t\t\tsaveSession(session);\n\t\t\treturn { outcomes: null, error };\n\t\t}\n\t}\n\n\t/**\n\t * Resume existing session (alias for initSession with resumeSessionId)\n\t */\n\tasync resumeSession(sessionId: SessionId): Promise<InitSessionResponse> {\n\t\treturn this.initSession({\n\t\t\tassessmentId: '',\n\t\t\tcandidateId: '',\n\t\t\tresumeSessionId: sessionId,\n\t\t});\n\t}\n\n\t/**\n\t * The identifier of this adapter's most recent unfinalized session for an\n\t * assessment and candidate, or null. Hosts pass it as `initSession.resumeSessionId`\n\t * to resume the stored draft — the reference resume path after a refresh.\n\t */\n\tlatestSessionId(assessmentId: string, candidateId: string): SessionId | null {\n\t\treturn findLatestSession(assessmentId, candidateId)?.sessionId ?? null;\n\t}\n\n\t/**\n\t * Query item bank for random item selection\n\t *\n\t * This reference implementation:\n\t * - Caches bank queries to avoid repeated calls\n\t * - Implements retry logic with exponential backoff\n\t * - Returns demo items (in production, fetch from real item bank)\n\t *\n\t * @param request - Item bank query request\n\t * @returns Selected items from bank\n\t */\n\t// =========================================================================\n\t// PRIVATE HELPERS\n\t// =========================================================================\n\n\tprivate createDemoAssessment(assessmentId: string): SecureAssessment {\n\t\t// This is a minimal demo assessment\n\t\t// In production, load from database and filter based on role\n\t\treturn {\n\t\t\tidentifier: assessmentId,\n\t\t\ttitle: 'Demo Assessment',\n\t\t\ttestParts: [\n\t\t\t\t{\n\t\t\t\t\tidentifier: 'part1',\n\t\t\t\t\tnavigationMode: 'nonlinear',\n\t\t\t\t\tsubmissionMode: 'simultaneous',\n\t\t\t\t\trubricBlocks: [],\n\t\t\t\t\titemSessionControl: {\n\t\t\t\t\t\tmaxAttempts: 1,\n\t\t\t\t\t\tshowFeedback: true,\n\t\t\t\t\t\tallowReview: true,\n\t\t\t\t\t\tshowSolution: false,\n\t\t\t\t\t\tallowComment: false,\n\t\t\t\t\t\tallowSkipping: true,\n\t\t\t\t\t\tvalidateResponses: true,\n\t\t\t\t\t},\n\t\t\t\t\tsections: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tidentifier: 'section1',\n\t\t\t\t\t\t\ttitle: 'Section 1',\n\t\t\t\t\t\t\tvisible: true,\n\t\t\t\t\t\t\tassessmentItemRefs: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tidentifier: 'item1',\n\t\t\t\t\t\t\t\t\trole: 'candidate',\n\t\t\t\t\t\t\t\t\t// In production, load from database\n\t\t\t\t\t\t\t\t\t// For candidates, responseProcessing should be removed server-side\n\t\t\t\t\t\t\t\t\titemXml: `<assessmentItem identifier=\"item1\" title=\"Sample Item\" adaptive=\"false\" timeDependent=\"false\">\n <responseDeclaration identifier=\"RESPONSE\" cardinality=\"single\" baseType=\"identifier\">\n <correctResponse>\n <value>A</value>\n </correctResponse>\n </responseDeclaration>\n <outcomeDeclaration identifier=\"SCORE\" cardinality=\"single\" baseType=\"float\">\n <defaultValue>\n <value>0</value>\n </defaultValue>\n </outcomeDeclaration>\n <itemBody>\n <p>What is 2 + 2?</p>\n <choiceInteraction responseIdentifier=\"RESPONSE\" shuffle=\"false\" maxChoices=\"1\">\n <simpleChoice identifier=\"A\">4</simpleChoice>\n <simpleChoice identifier=\"B\">3</simpleChoice>\n <simpleChoice identifier=\"C\">5</simpleChoice>\n </choiceInteraction>\n </itemBody>\n <responseProcessing>\n <responseCondition>\n <responseIf>\n <match>\n <variable identifier=\"RESPONSE\" />\n <correct identifier=\"RESPONSE\" />\n </match>\n <setOutcomeValue identifier=\"SCORE\">\n <baseValue baseType=\"float\">1</baseValue>\n </setOutcomeValue>\n </responseIf>\n <responseElse>\n <setOutcomeValue identifier=\"SCORE\">\n <baseValue baseType=\"float\">0</baseValue>\n </setOutcomeValue>\n </responseElse>\n </responseCondition>\n </responseProcessing>\n</assessmentItem>`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tidentifier: 'item2',\n\t\t\t\t\t\t\t\t\trole: 'candidate',\n\t\t\t\t\t\t\t\t\titemXml: `<assessmentItem identifier=\"item2\" title=\"Follow-up Item\" adaptive=\"false\" timeDependent=\"false\">\n <responseDeclaration identifier=\"RESPONSE\" cardinality=\"single\" baseType=\"identifier\">\n <correctResponse>\n <value>A</value>\n </correctResponse>\n </responseDeclaration>\n <outcomeDeclaration identifier=\"SCORE\" cardinality=\"single\" baseType=\"float\">\n <defaultValue>\n <value>0</value>\n </defaultValue>\n </outcomeDeclaration>\n <itemBody>\n <p>Demo follow-up item</p>\n <choiceInteraction responseIdentifier=\"RESPONSE\" shuffle=\"false\" maxChoices=\"1\">\n <simpleChoice identifier=\"A\">ok</simpleChoice>\n <simpleChoice identifier=\"B\">no</simpleChoice>\n </choiceInteraction>\n </itemBody>\n <responseProcessing>\n <responseCondition>\n <responseIf>\n <match>\n <variable identifier=\"RESPONSE\" />\n <correct identifier=\"RESPONSE\" />\n </match>\n <setOutcomeValue identifier=\"SCORE\">\n <baseValue baseType=\"float\">1</baseValue>\n </setOutcomeValue>\n </responseIf>\n </responseCondition>\n </responseProcessing>\n</assessmentItem>`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\t// =========================================================================\n\t// STATIC: QTI TEST XML PARSER\n\t// =========================================================================\n\n\t/**\n\t * Test-level view of every delivered item. A submitted item is presented and carries the state\n\t * its latest counted submission recorded (a score without one carries only its SCORE); an item\n\t * not yet submitted carries its declared defaults and counts as not presented.\n\t */\n\tprivate buildTestItems(session: StoredSession): TestItemState[] {\n\t\tconst itemScores = session.state.itemScores ?? {};\n\t\treturn getItemRefsInOrder(session.assessment).map(({ item, sectionIdentifiers }) => {\n\t\t\tconst scoring = itemScores[item.identifier];\n\t\t\tconst presented = scoring !== undefined;\n\t\t\tconst itemState = presented ? session.itemTestStates?.[item.identifier] : defaultItemTestState(item.itemXml);\n\t\t\tconst variables: Record<string, QtiValue> = { ...(itemState?.variables ?? {}) };\n\t\t\tif (scoring && !variables.SCORE) variables.SCORE = qtiValue('float', 'single', scoring.score);\n\t\t\tObject.assign(variables, applyVariableMappings(variables, item.variableMappings));\n\t\t\treturn {\n\t\t\t\tidentifier: item.identifier,\n\t\t\t\tsectionIdentifiers,\n\t\t\t\tcategories: item.categories,\n\t\t\t\tweights: item.weights ? Object.fromEntries(item.weights.map((w) => [w.identifier, w.value])) : undefined,\n\t\t\t\tvariables,\n\t\t\t\toutcomeBounds: itemState?.outcomeBounds ?? defaultItemTestState(item.itemXml)?.outcomeBounds,\n\t\t\t\tpresented,\n\t\t\t\tresponded: presented && itemState?.responded === true,\n\t\t\t\tcorrect: presented && itemState?.correct === true,\n\t\t\t\tincorrect: presented && itemState?.correct === false,\n\t\t\t\tselected: true,\n\t\t\t};\n\t\t});\n\t}\n\n\t// =========================================================================\n\t// ITEM BANK HELPERS\n\t// =========================================================================\n\n\t/**\n\t * Generate cache key for item bank query\n\t */\n}\n"]}
|
|
@@ -125,10 +125,6 @@ export interface SecureTimeLimits {
|
|
|
125
125
|
export interface SecureAssessment {
|
|
126
126
|
identifier: string;
|
|
127
127
|
title: string;
|
|
128
|
-
/** Navigation mode affects UI */
|
|
129
|
-
navigationMode: 'linear' | 'nonlinear';
|
|
130
|
-
/** Submission mode affects when responses are finalized */
|
|
131
|
-
submissionMode: 'individual' | 'simultaneous';
|
|
132
128
|
/** Test parts contain sections */
|
|
133
129
|
testParts: SecureTestPart[];
|
|
134
130
|
/** Overall time limit in seconds (optional) */
|
|
@@ -149,9 +145,10 @@ export interface SecureAssessment {
|
|
|
149
145
|
}
|
|
150
146
|
export interface SecureTestPart {
|
|
151
147
|
identifier: string;
|
|
152
|
-
/**
|
|
153
|
-
navigationMode
|
|
154
|
-
submissionMode
|
|
148
|
+
/** QTI testPart navigationMode. */
|
|
149
|
+
navigationMode: 'linear' | 'nonlinear';
|
|
150
|
+
/** QTI testPart submissionMode: when responses are finalized. */
|
|
151
|
+
submissionMode: 'individual' | 'simultaneous';
|
|
155
152
|
/** Sections contain items */
|
|
156
153
|
sections: SecureSection[];
|
|
157
154
|
/** TestPart-level time limit. */
|
|
@@ -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\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
|
+
{"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/** 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/** QTI testPart navigationMode. */\n\tnavigationMode: 'linear' | 'nonlinear';\n\t/** QTI testPart submissionMode: when responses are finalized. */\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"]}
|
|
@@ -480,11 +480,6 @@ export async function parseAssessmentTestXml(testXml, options = {}) {
|
|
|
480
480
|
const timeLimits = parseTimeLimits(root);
|
|
481
481
|
// Parse testParts
|
|
482
482
|
const testPartEls = childrenByTag(root, 'testPart');
|
|
483
|
-
const firstTestPart = testPartEls[0];
|
|
484
|
-
// Retain top-level compatibility fields while preserving the authoritative
|
|
485
|
-
// mode on every testPart below.
|
|
486
|
-
const navigationMode = (getAttr(firstTestPart ?? root, 'navigationMode') ?? 'nonlinear');
|
|
487
|
-
const submissionMode = (getAttr(firstTestPart ?? root, 'submissionMode') ?? 'simultaneous');
|
|
488
483
|
const testParts = [];
|
|
489
484
|
for (const tp of testPartEls) {
|
|
490
485
|
const tpIdentifier = getAttr(tp, 'identifier') ?? 'part-1';
|
|
@@ -519,34 +514,10 @@ export async function parseAssessmentTestXml(testXml, options = {}) {
|
|
|
519
514
|
branchRule: parseBranchRules(tp),
|
|
520
515
|
});
|
|
521
516
|
}
|
|
522
|
-
// If no testParts, try top-level sections
|
|
523
|
-
if (testParts.length === 0) {
|
|
524
|
-
const topSections = [];
|
|
525
|
-
for (const child of childElements(root)) {
|
|
526
|
-
if (toCanonicalQtiName(child.localName) === 'assessmentSection') {
|
|
527
|
-
topSections.push(await parseSection(child));
|
|
528
|
-
}
|
|
529
|
-
else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {
|
|
530
|
-
const resolved = await resolveSectionRef(child);
|
|
531
|
-
if (resolved)
|
|
532
|
-
topSections.push(resolved);
|
|
533
|
-
}
|
|
534
|
-
}
|
|
535
|
-
if (topSections.length > 0) {
|
|
536
|
-
testParts.push({
|
|
537
|
-
identifier: 'part-1',
|
|
538
|
-
navigationMode,
|
|
539
|
-
submissionMode,
|
|
540
|
-
sections: topSections,
|
|
541
|
-
});
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
517
|
return {
|
|
545
518
|
identifier: getAttr(root, 'identifier') ?? 'assessment',
|
|
546
519
|
// Left empty when absent: shells show a localized generic title, not English text.
|
|
547
520
|
title: getAttr(root, 'title') ?? '',
|
|
548
|
-
navigationMode,
|
|
549
|
-
submissionMode,
|
|
550
521
|
testParts,
|
|
551
522
|
timeLimits,
|
|
552
523
|
outcomeDeclarations: outcomeDeclarations.length > 0 ? outcomeDeclarations : undefined,
|